diff --git a/DEPS b/DEPS index 830c4c4..533b50e 100644 --- a/DEPS +++ b/DEPS
@@ -195,11 +195,11 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling Skia # and whatever else without interference from each other. - 'skia_revision': '3c02c934afa7f0128b113ce298346fb17d695dac', + 'skia_revision': '03cde5f9997d47458c022c29e72b90d5933100f2', # 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': '1dec2f312a7256de85c67fb4745e58b3222197c4', + 'v8_revision': 'e23bb2ed80db350d79d5c669743cd6690ebe556d', # 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. @@ -207,7 +207,7 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling ANGLE # and whatever else without interference from each other. - 'angle_revision': '3c2454b82c050193b8552000f1a9e208928d07e6', + 'angle_revision': 'bc993b2771f96ff99709ba2af20c7a4e0873fb2c', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling SwiftShader # and whatever else without interference from each other. @@ -215,7 +215,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': '42aaf8bd7f23e39e85c843d36f5a041870726279', + 'pdfium_revision': '184443e8d77994d568436a2213e1d12e433d73b4', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling BoringSSL # and whatever else without interference from each other. @@ -246,7 +246,7 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling freetype # and whatever else without interference from each other. - 'freetype_revision': 'cdc009c24afac88846ed24e21c84e33792384665', + 'freetype_revision': '6730854c397130879c64bd766c673b9bccf9c04a', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling HarfBuzz # and whatever else without interference from each other. @@ -266,7 +266,7 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling devtools-frontend # and whatever else without interference from each other. - 'devtools_frontend_revision': 'ac636dc7dfe037669835bba1bb5ab317345640c4', + 'devtools_frontend_revision': 'fb9ee39c41d43eaabc990658bbc46e1085da8931', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling libprotobuf-mutator # and whatever else without interference from each other. @@ -302,7 +302,7 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling feed # and whatever else without interference from each other. - 'spv_tools_revision': '12df3cafeee0ce84861d93b7ea4c939429453644', + 'spv_tools_revision': '9e26ae04552617102ae22f04946e3b69552f7560', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling feed # and whatever else without interference from each other. @@ -318,7 +318,7 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling feed # and whatever else without interference from each other. - 'dawn_revision': 'c3e3c30b0d7f51064f7247a09b61d208252416b7', + 'dawn_revision': '4f8bdaf473fb7c95ab0c4f6da72f93601a00e019', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling feed # and whatever else without interference from each other. @@ -895,7 +895,7 @@ }, 'src/third_party/depot_tools': - Var('chromium_git') + '/chromium/tools/depot_tools.git' + '@' + 'dff2104727dc207f58d87b938e04402be548329c', + Var('chromium_git') + '/chromium/tools/depot_tools.git' + '@' + 'c6aa15118046ed881094f1d97061bdb92ba7a149', 'src/third_party/devtools-frontend/src': Var('chromium_git') + '/devtools/devtools-frontend' + '@' + Var('devtools_frontend_revision'), @@ -1248,7 +1248,7 @@ }, 'src/third_party/perfetto': - Var('android_git') + '/platform/external/perfetto.git' + '@' + '7023f47299aa157951b4677ee4450cac58685a2d', + Var('android_git') + '/platform/external/perfetto.git' + '@' + '0fdfdcf61cd436faf7cf9b8be2596df9c6ca6010', 'src/third_party/perl': { 'url': Var('chromium_git') + '/chromium/deps/perl.git' + '@' + '6f3e5028eb65d0b4c5fdd792106ac4c84eee1eb3', @@ -1470,7 +1470,7 @@ }, 'src/third_party/webrtc': - Var('webrtc_git') + '/src.git' + '@' + '59230836579a7ce0386faebb07c73ac23f31a2b4', + Var('webrtc_git') + '/src.git' + '@' + '91c0477b4332b9e7880ce48332b1f77d5255a839', 'src/third_party/libgifcodec': Var('skia_git') + '/libgifcodec' + '@'+ Var('libgifcodec_revision'), @@ -1542,7 +1542,7 @@ Var('chromium_git') + '/v8/v8.git' + '@' + Var('v8_revision'), 'src-internal': { - 'url': 'https://chrome-internal.googlesource.com/chrome/src-internal.git@13e23939fb1a500d1748b3a2a89ee3854404329b', + 'url': 'https://chrome-internal.googlesource.com/chrome/src-internal.git@95c5b87ad1a3f0580740f58c6384e34a12077cc6', 'condition': 'checkout_src_internal', },
diff --git a/android_webview/browser/gfx/aw_draw_fn_impl.cc b/android_webview/browser/gfx/aw_draw_fn_impl.cc index 9f22be0..1a82cfc 100644 --- a/android_webview/browser/gfx/aw_draw_fn_impl.cc +++ b/android_webview/browser/gfx/aw_draw_fn_impl.cc
@@ -68,7 +68,7 @@ g_gl_context = this; } - bool MakeCurrent(gl::GLSurface* surface) override { + bool MakeCurrentImpl(gl::GLSurface* surface) override { // A GLNonOwnedCompatibilityContext may have set the GetRealCurrent() // pointer to itself, while re-using our EGL context. In these cases just // call SetCurrent to restore expected GetRealContext(). @@ -83,10 +83,10 @@ return true; } - return gl::GLContextEGL::MakeCurrent(surface); + return gl::GLContextEGL::MakeCurrentImpl(surface); } - bool MakeCurrent() { return MakeCurrent(surface_.get()); } + bool MakeCurrent() { return gl::GLContext::MakeCurrent(surface_.get()); } static scoped_refptr<GLNonOwnedCompatibilityContext> GetOrCreateInstance() { if (g_gl_context)
diff --git a/android_webview/browser/gfx/hardware_renderer_viz.cc b/android_webview/browser/gfx/hardware_renderer_viz.cc index 4d36f960..c0a2614 100644 --- a/android_webview/browser/gfx/hardware_renderer_viz.cc +++ b/android_webview/browser/gfx/hardware_renderer_viz.cc
@@ -67,8 +67,9 @@ // viz::DisplayClient overrides. void DisplayOutputSurfaceLost() override; - void DisplayWillDrawAndSwap(bool will_draw_and_swap, - viz::RenderPassList* render_passes) override; + void DisplayWillDrawAndSwap( + bool will_draw_and_swap, + viz::AggregatedRenderPassList* render_passes) override; void DisplayDidDrawAndSwap() override {} void DisplayDidReceiveCALayerParams( const gfx::CALayerParams& ca_layer_params) override {} @@ -250,7 +251,7 @@ void HardwareRendererViz::OnViz::DisplayWillDrawAndSwap( bool will_draw_and_swap, - viz::RenderPassList* render_passes) { + viz::AggregatedRenderPassList* render_passes) { DCHECK_CALLED_ON_VALID_THREAD(viz_thread_checker_); hit_test_aggregator_->Aggregate(child_surface_id_, render_passes); }
diff --git a/android_webview/browser/gfx/surfaces_instance.h b/android_webview/browser/gfx/surfaces_instance.h index cd49c38..8bd05db4 100644 --- a/android_webview/browser/gfx/surfaces_instance.h +++ b/android_webview/browser/gfx/surfaces_instance.h
@@ -11,6 +11,7 @@ #include "android_webview/browser/gfx/output_surface_provider_webview.h" #include "base/memory/ref_counted.h" #include "components/viz/common/frame_timing_details_map.h" +#include "components/viz/common/quads/aggregated_render_pass.h" #include "components/viz/common/surfaces/frame_sink_id.h" #include "components/viz/common/surfaces/frame_sink_id_allocator.h" #include "components/viz/common/surfaces/local_surface_id_allocation.h" @@ -67,8 +68,9 @@ // viz::DisplayClient overrides. void DisplayOutputSurfaceLost() override; - void DisplayWillDrawAndSwap(bool will_draw_and_swap, - viz::RenderPassList* render_passes) override {} + void DisplayWillDrawAndSwap( + bool will_draw_and_swap, + viz::AggregatedRenderPassList* render_passes) override {} void DisplayDidDrawAndSwap() override {} void DisplayDidReceiveCALayerParams( const gfx::CALayerParams& ca_layer_params) override {}
diff --git a/ash/events/accessibility_event_rewriter.cc b/ash/events/accessibility_event_rewriter.cc index 7d634cf0..7074301 100644 --- a/ash/events/accessibility_event_rewriter.cc +++ b/ash/events/accessibility_event_rewriter.cc
@@ -8,6 +8,7 @@ #include "ash/public/cpp/accessibility_event_rewriter_delegate.h" #include "ash/shell.h" #include "ui/chromeos/events/event_rewriter_chromeos.h" +#include "ui/events/devices/input_device.h" #include "ui/events/event.h" #include "ui/events/event_utils.h" #include "ui/events/types/event_type.h" @@ -19,6 +20,16 @@ AccessibilityEventRewriterDelegate* delegate) : delegate_(delegate), event_rewriter_chromeos_(event_rewriter_chromeos) { Shell::Get()->accessibility_controller()->SetAccessibilityEventRewriter(this); + + // By default, observe all input device types. + keyboard_input_device_types_.insert(ui::INPUT_DEVICE_INTERNAL); + keyboard_input_device_types_.insert(ui::INPUT_DEVICE_USB); + keyboard_input_device_types_.insert(ui::INPUT_DEVICE_BLUETOOTH); + keyboard_input_device_types_.insert(ui::INPUT_DEVICE_UNKNOWN); + + UpdateKeyboardDeviceIds(); + + observer_.Add(ui::DeviceDataManager::GetInstance()); } AccessibilityEventRewriter::~AccessibilityEventRewriter() { @@ -52,23 +63,58 @@ } } -ui::EventDispatchDetails AccessibilityEventRewriter::RewriteEvent( - const ui::Event& event, - const Continuation continuation) { - bool captured = false; - if (!delegate_) - return SendEvent(continuation, &event); +bool AccessibilityEventRewriter::SetKeyCodesForSwitchAccessCommand( + std::set<int> new_key_codes, + SwitchAccessCommand command) { + bool has_changed = false; + std::set<int> to_clear; - if (Shell::Get()->accessibility_controller()->IsSwitchAccessRunning()) { - captured = RewriteEventForSwitchAccess(event, continuation); + // Clear old values that conflict with the new assignment. + // TODO(anastasi): convert to use iterators directly and remove has_changed as + // an extra step. + for (const auto& val : key_code_to_switch_access_command_) { + int old_key_code = val.first; + SwitchAccessCommand old_command = val.second; + + if (new_key_codes.count(old_key_code) > 0) { + if (old_command != command) { + has_changed = true; + // Modifying the map while iterating through it causes reference + // failures. + to_clear.insert(old_key_code); + } else { + new_key_codes.erase(old_key_code); + } + continue; + } + + // This value was previously mapped to the command, but is no longer. + if (old_command == command) { + has_changed = true; + to_clear.insert(old_key_code); + switch_access_key_codes_to_capture_.erase(old_key_code); + } + } + for (int key_code : to_clear) { + key_code_to_switch_access_command_.erase(key_code); } - if (!captured) { - captured = RewriteEventForChromeVox(event, continuation); + if (new_key_codes.size() == 0) + return has_changed; + + // Add any new key codes to the map. + for (int key_code : new_key_codes) { + switch_access_key_codes_to_capture_.insert(key_code); + key_code_to_switch_access_command_[key_code] = command; } - return captured ? DiscardEvent(continuation) - : SendEvent(continuation, &event); + return true; +} + +void AccessibilityEventRewriter::SetKeyboardInputDeviceTypes( + const std::set<ui::InputDeviceType>& keyboard_input_device_types) { + keyboard_input_device_types_ = keyboard_input_device_types; + UpdateKeyboardDeviceIds(); } bool AccessibilityEventRewriter::RewriteEventForChromeVox( @@ -143,52 +189,43 @@ return capture; } -bool AccessibilityEventRewriter::SetKeyCodesForSwitchAccessCommand( - std::set<int> new_key_codes, - SwitchAccessCommand command) { - bool has_changed = false; - std::set<int> to_clear; - - // Clear old values that conflict with the new assignment. - // TODO(anastasi): convert to use iterators directly and remove has_changed as - // an extra step. - for (const auto& val : key_code_to_switch_access_command_) { - int old_key_code = val.first; - SwitchAccessCommand old_command = val.second; - - if (new_key_codes.count(old_key_code) > 0) { - if (old_command != command) { - has_changed = true; - // Modifying the map while iterating through it causes reference - // failures. - to_clear.insert(old_key_code); - } else { - new_key_codes.erase(old_key_code); - } - continue; - } - - // This value was previously mapped to the command, but is no longer. - if (old_command == command) { - has_changed = true; - to_clear.insert(old_key_code); - switch_access_key_codes_to_capture_.erase(old_key_code); - } +void AccessibilityEventRewriter::UpdateKeyboardDeviceIds() { + keyboard_device_ids_.clear(); + for (auto& keyboard : + ui::DeviceDataManager::GetInstance()->GetKeyboardDevices()) { + if (keyboard_input_device_types_.count(keyboard.type)) + keyboard_device_ids_.insert(keyboard.id); } - for (int key_code : to_clear) { - key_code_to_switch_access_command_.erase(key_code); +} + +ui::EventDispatchDetails AccessibilityEventRewriter::RewriteEvent( + const ui::Event& event, + const Continuation continuation) { + if (event.IsKeyEvent() && event.source_device_id() != ui::ED_UNKNOWN_DEVICE && + keyboard_device_ids_.count(event.source_device_id()) == 0) { + return SendEvent(continuation, &event); } - if (new_key_codes.size() == 0) - return has_changed; + bool captured = false; + if (!delegate_) + return SendEvent(continuation, &event); - // Add any new key codes to the map. - for (int key_code : new_key_codes) { - switch_access_key_codes_to_capture_.insert(key_code); - key_code_to_switch_access_command_[key_code] = command; + if (Shell::Get()->accessibility_controller()->IsSwitchAccessRunning()) { + captured = RewriteEventForSwitchAccess(event, continuation); } - return true; + if (!captured) { + captured = RewriteEventForChromeVox(event, continuation); + } + + return captured ? DiscardEvent(continuation) + : SendEvent(continuation, &event); +} + +void AccessibilityEventRewriter::OnInputDeviceConfigurationChanged( + uint8_t input_device_types) { + if (input_device_types & ui::InputDeviceEventObserver::kKeyboard) + UpdateKeyboardDeviceIds(); } } // namespace ash
diff --git a/ash/events/accessibility_event_rewriter.h b/ash/events/accessibility_event_rewriter.h index e086029f..a9b2b24 100644 --- a/ash/events/accessibility_event_rewriter.h +++ b/ash/events/accessibility_event_rewriter.h
@@ -10,10 +10,14 @@ #include <set> #include "ash/ash_export.h" +#include "base/scoped_observer.h" +#include "ui/events/devices/device_data_manager.h" +#include "ui/events/devices/input_device_event_observer.h" #include "ui/events/event_rewriter.h" namespace ui { class EventRewriterChromeOS; +enum InputDeviceType; } namespace ash { @@ -24,7 +28,9 @@ // AccessibilityEventRewriter sends key events to Accessibility extensions (such // as ChromeVox and Switch Access) via the delegate when the corresponding // extension is enabled. Continues dispatch of unhandled key events. -class ASH_EXPORT AccessibilityEventRewriter : public ui::EventRewriter { +class ASH_EXPORT AccessibilityEventRewriter + : public ui::EventRewriter, + public ui::InputDeviceEventObserver { public: AccessibilityEventRewriter(ui::EventRewriterChromeOS* event_rewriter_chromeos, AccessibilityEventRewriterDelegate* delegate); @@ -37,10 +43,15 @@ // NOTE: These events may be delivered out-of-order from non-ChromeVox events. void OnUnhandledSpokenFeedbackEvent(std::unique_ptr<ui::Event> event) const; - // Sets what key_codes are captured for a given Switch Access command. + // Sets what |key_codes| are captured for a given Switch Access command; + // returns true if any mapping changed. bool SetKeyCodesForSwitchAccessCommand(std::set<int> key_codes, SwitchAccessCommand command); + // Set the types of keyboard input types processed by this rewriter. + void SetKeyboardInputDeviceTypes( + const std::set<ui::InputDeviceType>& keyboard_input_device_types); + void set_chromevox_capture_all_keys(bool value) { chromevox_capture_all_keys_ = value; } @@ -58,16 +69,25 @@ } private: + // Internal helpers to rewrite an event for a given accessibility feature. + // Returns true if the event is captured. bool RewriteEventForChromeVox(const ui::Event& event, const Continuation continuation); bool RewriteEventForSwitchAccess(const ui::Event& event, const Continuation continuation); + // Updates the list of allowed keyboard device ids based on the current set of + // keyboard input types. + void UpdateKeyboardDeviceIds(); + // ui::EventRewriter: ui::EventDispatchDetails RewriteEvent( const ui::Event& event, const Continuation continuation) override; + // ui::InputDeviceObserver: + void OnInputDeviceConfigurationChanged(uint8_t input_device_types) override; + // Continuation saved for OnUnhandledSpokenFeedbackEvent(). Continuation chromevox_continuation_; @@ -78,13 +98,29 @@ // Whether to send mouse events to the ChromeVox extension. bool chromevox_send_mouse_events_ = false; - // Whether to capture all keys. + // Whether to capture all keys for ChromeVox. bool chromevox_capture_all_keys_ = false; + // Set of keys to capture for Switch Access. std::set<int> switch_access_key_codes_to_capture_; + + // Maps a captured key from above to a Switch Access command. std::map<int, SwitchAccessCommand> key_code_to_switch_access_command_; + // Used to rewrite events in special cases such as function keys for ChromeVox + // taylored behavior. ui::EventRewriterChromeOS* const event_rewriter_chromeos_; + + // A set of keyboard device ids who's key events we want to process. + std::set<int> keyboard_device_ids_; + + // A set of input device types used to filter the list of keyboard devices + // above. + std::set<ui::InputDeviceType> keyboard_input_device_types_; + + // Used to refresh state when keyboard devices change. + ScopedObserver<ui::DeviceDataManager, ui::InputDeviceEventObserver> observer_{ + this}; }; } // namespace ash
diff --git a/ash/events/accessibility_event_rewriter_unittest.cc b/ash/events/accessibility_event_rewriter_unittest.cc index 97368ba..4c64040b 100644 --- a/ash/events/accessibility_event_rewriter_unittest.cc +++ b/ash/events/accessibility_event_rewriter_unittest.cc
@@ -20,6 +20,7 @@ #include "ui/chromeos/events/event_rewriter_chromeos.h" #include "ui/chromeos/events/modifier_key.h" #include "ui/chromeos/events/pref_names.h" +#include "ui/events/devices/device_data_manager_test_api.h" #include "ui/events/event.h" #include "ui/events/event_constants.h" #include "ui/events/event_handler.h" @@ -646,5 +647,85 @@ EXPECT_EQ(command_map.end(), command_map.find(48)); } +TEST_F(SwitchAccessAccessibilityEventRewriterTest, SetKeyboardInputTypes) { + AccessibilityEventRewriter* rewriter = + controller_->GetAccessibilityEventRewriterForTest(); + EXPECT_NE(nullptr, rewriter); + + // Set Switch Access to capture these keys as the select command. + SetKeyCodesForSwitchAccessCommand( + {ui::VKEY_1, ui::VKEY_2, ui::VKEY_3, ui::VKEY_4}, + SwitchAccessCommand::kSelect); + + std::vector<ui::InputDevice> keyboards; + ui::DeviceDataManagerTestApi device_data_test_api; + keyboards.emplace_back(ui::InputDevice(1, ui::INPUT_DEVICE_INTERNAL, "")); + keyboards.emplace_back(ui::InputDevice(2, ui::INPUT_DEVICE_USB, "")); + keyboards.emplace_back(ui::InputDevice(3, ui::INPUT_DEVICE_BLUETOOTH, "")); + keyboards.emplace_back(ui::InputDevice(4, ui::INPUT_DEVICE_UNKNOWN, "")); + device_data_test_api.SetKeyboardDevices(keyboards); + + // Press the "1" key with no source device id. + generator_->PressKey(ui::VKEY_1, ui::EF_NONE); + generator_->ReleaseKey(ui::VKEY_1, ui::EF_NONE); + + // The event was captured by AccessibilityEventRewriter. + EXPECT_FALSE(event_capturer_.last_key_event()); + EXPECT_EQ(SwitchAccessCommand::kSelect, delegate_->last_command()); + + // Press the "1" key from the internal keyboard which is captured by + // AccessibilityEventRewriter. + generator_->PressKey(ui::VKEY_1, ui::EF_NONE, 1); + generator_->ReleaseKey(ui::VKEY_1, ui::EF_NONE, 1); + EXPECT_FALSE(event_capturer_.last_key_event()); + + // Press the "2" key from the usb keyboard which is captured by + // AccessibilityEventRewriter. + generator_->PressKey(ui::VKEY_2, ui::EF_NONE, 2); + generator_->ReleaseKey(ui::VKEY_2, ui::EF_NONE, 2); + EXPECT_FALSE(event_capturer_.last_key_event()); + + // Press the "3" key from the bluetooth keyboard which is captured by + // AccessibilityEventRewriter. + generator_->PressKey(ui::VKEY_3, ui::EF_NONE, 3); + generator_->ReleaseKey(ui::VKEY_3, ui::EF_NONE, 3); + EXPECT_FALSE(event_capturer_.last_key_event()); + + // Press the "4" key from the unknown keyboard which is captured by + // AccessibilityEventRewriter. + generator_->PressKey(ui::VKEY_4, ui::EF_NONE, 4); + generator_->ReleaseKey(ui::VKEY_4, ui::EF_NONE, 2); + EXPECT_FALSE(event_capturer_.last_key_event()); + + // Now, exclude some device types. + rewriter->SetKeyboardInputDeviceTypes( + {ui::INPUT_DEVICE_USB, ui::INPUT_DEVICE_BLUETOOTH}); + + // Press the "1" key from the internal keyboard which is not captured by + // AccessibilityEventRewriter. + generator_->PressKey(ui::VKEY_1, ui::EF_NONE, 1); + generator_->ReleaseKey(ui::VKEY_1, ui::EF_NONE, 1); + EXPECT_TRUE(event_capturer_.last_key_event()); + event_capturer_.Reset(); + + // Press the "2" key from the usb keyboard which is captured by + // AccessibilityEventRewriter. + generator_->PressKey(ui::VKEY_2, ui::EF_NONE, 2); + generator_->ReleaseKey(ui::VKEY_2, ui::EF_NONE, 2); + EXPECT_FALSE(event_capturer_.last_key_event()); + + // Press the "3" key from the bluetooth keyboard which is captured by + // AccessibilityEventRewriter. + generator_->PressKey(ui::VKEY_3, ui::EF_NONE, 3); + generator_->ReleaseKey(ui::VKEY_3, ui::EF_NONE, 3); + EXPECT_FALSE(event_capturer_.last_key_event()); + + // Press the "4" key from the unknown keyboard which is not captured by + // AccessibilityEventRewriter. + generator_->PressKey(ui::VKEY_4, ui::EF_NONE, 4); + generator_->ReleaseKey(ui::VKEY_4, ui::EF_NONE, 2); + EXPECT_TRUE(event_capturer_.last_key_event()); +} + } // namespace } // namespace ash
diff --git a/base/BUILD.gn b/base/BUILD.gn index 293a4a0e1..101c61a3 100644 --- a/base/BUILD.gn +++ b/base/BUILD.gn
@@ -20,7 +20,6 @@ import("//base/allocator/allocator.gni") import("//base/trace_event/tracing.gni") import("//build/buildflag_header.gni") -import("//build/config/allocator.gni") import("//build/config/arm.gni") import("//build/config/c++/c++.gni") import("//build/config/chromecast_build.gni") @@ -1501,9 +1500,8 @@ ] } - if (current_cpu != "arm") { - # The reached code profiler is only supported on Android with 32-bit arm - # arch. + if (current_cpu != "arm" && current_cpu != "arm64") { + # The reached code profiler is only supported on Android arm arch. sources -= [ "android/reached_code_profiler.cc" ] sources += [ "android/reached_code_profiler_stub.cc" ] }
diff --git a/base/allocator/BUILD.gn b/base/allocator/BUILD.gn index 3e7515e..448e8c2 100644 --- a/base/allocator/BUILD.gn +++ b/base/allocator/BUILD.gn
@@ -4,7 +4,6 @@ import("//base/allocator/allocator.gni") import("//build/buildflag_header.gni") -import("//build/config/allocator.gni") import("//build/config/compiler/compiler.gni") declare_args() {
diff --git a/base/allocator/allocator.gni b/base/allocator/allocator.gni index b50afa3..b9c41be 100644 --- a/base/allocator/allocator.gni +++ b/base/allocator/allocator.gni
@@ -7,7 +7,8 @@ # Temporarily disable tcmalloc on arm64 linux to get rid of compilation errors. if (is_android || is_apple || is_asan || is_lsan || is_tsan || is_msan || - is_win || is_fuchsia || ((is_linux || is_chromeos) && target_cpu == "arm64") || + is_win || is_fuchsia || + ((is_linux || is_chromeos) && target_cpu == "arm64") || (is_cast_audio_only && target_cpu == "arm")) { _default_allocator = "none" } else { @@ -31,6 +32,11 @@ # Causes all the allocations to be routed via allocator_shim.cc. use_allocator_shim = _default_use_allocator_shim + + # Partition alloc is included by default except iOS. + # TODO(lizeb, yukishiino): Remove |use_partition_alloc| once PA-Everywhere + # is enabled. + use_partition_alloc = !is_ios } assert(use_allocator == "none" || use_allocator == "tcmalloc" || @@ -39,15 +45,24 @@ # Don't ship this configuration, not ready yet. assert(!(use_allocator == "partition" && is_official_build)) -assert(!is_win || use_allocator == "none", "Tcmalloc doesn't work on Windows.") -assert(!is_mac || use_allocator == "none", "Tcmalloc doesn't work on macOS.") -assert(!is_ios || use_allocator == "none", "Tcmalloc doesn't work on iOS.") +assert(!is_win || use_allocator != "tcmalloc", + "Tcmalloc doesn't work on Windows.") +assert(!is_mac || use_allocator != "tcmalloc", + "Tcmalloc doesn't work on macOS.") +assert(!is_ios || use_allocator != "tcmalloc", "Tcmalloc doesn't work on iOS.") assert( - !use_allocator_shim || is_linux || is_chromeos || is_android || is_win || is_apple, + !use_allocator_shim || is_linux || is_chromeos || is_android || is_win || + is_apple, "use_allocator_shim works only on Android, iOS, Linux, macOS, and Windows.") if (is_win && use_allocator_shim) { assert(!is_component_build, "The allocator shim doesn't work for the component build on Windows.") } + +if (use_allocator == "partition") { + # If there is a conflict, prioritize |use_allocator| over + # |use_partition_alloc|. + use_partition_alloc = true +}
diff --git a/base/android/reached_code_profiler.cc b/base/android/reached_code_profiler.cc index 14048afe..721fb2c 100644 --- a/base/android/reached_code_profiler.cc +++ b/base/android/reached_code_profiler.cc
@@ -34,6 +34,7 @@ #include "base/synchronization/lock.h" #include "base/threading/thread.h" #include "base/timer/timer.h" +#include "build/build_config.h" #if !BUILDFLAG(SUPPORTS_CODE_ORDERING) #error Code ordering support is required for the reached code profiler. @@ -72,7 +73,11 @@ return; ucontext_t* ucontext = reinterpret_cast<ucontext_t*>(context); - uint32_t address = ucontext->uc_mcontext.arm_pc; +#if defined(ARCH_CPU_ARM64) + uintptr_t address = ucontext->uc_mcontext.pc; +#else + uintptr_t address = ucontext->uc_mcontext.arm_pc; +#endif ReachedAddressesBitset::GetTextBitset()->RecordAddress(address); }
diff --git a/build/args/headless.gn b/build/args/headless.gn index 6936b258..4c2e8d9ff 100644 --- a/build/args/headless.gn +++ b/build/args/headless.gn
@@ -45,3 +45,6 @@ use_glib = false use_gtk = false use_pangocairo = false + +# TODO(1096425): Remove this once use_x11 goes away. +use_x11 = false
diff --git a/build/config/allocator.gni b/build/config/allocator.gni deleted file mode 100644 index 339682b..0000000 --- a/build/config/allocator.gni +++ /dev/null
@@ -1,10 +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. - -declare_args() { - # Partition alloc is included by default except iOS. - # TODO(thakis): Move this elsewhere, probably - # base/allocator/partition_allocator/buildflags.gni - use_partition_alloc = !is_ios -}
diff --git a/build/config/ui.gni b/build/config/ui.gni index 5bdd159d8..063d338 100644 --- a/build/config/ui.gni +++ b/build/config/ui.gni
@@ -18,11 +18,19 @@ # of //build/config/BUILDCONFIG.gn. import("//build/config/chromecast_build.gni") +import("//build/config/chromeos/ui_mode.gni") declare_args() { # Indicates if Ozone is enabled. Ozone is a low-level library layer for Linux - # that does not require X11. Enabling this feature disables use of x11. - use_ozone = is_chromeos || (is_chromecast && !is_android) || is_fuchsia + # that does not require X11. + use_ozone = + is_chromeos || (is_chromecast && !is_android) || is_fuchsia || is_linux + + # Indicates if the UI toolkit depends on X11. + # Enabled by default. Can be disabled if Ozone only build is required and + # vice-versa. + use_x11 = + is_linux && !is_chromecast && !is_chromeos && !chromeos_is_browser_only # Indicates if Aura is enabled. Aura is a low-level windowing library, sort # of a replacement for GDI or GTK. @@ -37,13 +45,6 @@ use_glib = is_desktop_linux && !is_chromecast } -# Additional dependent variables ----------------------------------------------- -# -# These variables depend on other variables and can't be set externally. - -# Indicates if the UI toolkit depends on X11. -use_x11 = is_linux && !use_ozone - # Make sure glib is not used if building for ChromeOS/Chromecast assert(!use_glib || (is_linux && !is_chromeos && !is_chromecast))
diff --git a/build/fuchsia/linux.sdk.sha1 b/build/fuchsia/linux.sdk.sha1 index b87ab98..e689840 100644 --- a/build/fuchsia/linux.sdk.sha1 +++ b/build/fuchsia/linux.sdk.sha1
@@ -1 +1 @@ -0.20200826.0.1 +0.20200826.1.1
diff --git a/build/fuchsia/mac.sdk.sha1 b/build/fuchsia/mac.sdk.sha1 index b87ab98..e689840 100644 --- a/build/fuchsia/mac.sdk.sha1 +++ b/build/fuchsia/mac.sdk.sha1
@@ -1 +1 @@ -0.20200826.0.1 +0.20200826.1.1
diff --git a/cc/animation/keyframe_model.cc b/cc/animation/keyframe_model.cc index b7c3ee7..0f73210 100644 --- a/cc/animation/keyframe_model.cc +++ b/cc/animation/keyframe_model.cc
@@ -286,14 +286,16 @@ if (curve_->Duration() <= base::TimeDelta()) return base::TimeDelta(); - base::TimeDelta repeated_duration = curve_->Duration() * iterations_; - base::TimeDelta active_duration = - repeated_duration / std::abs(playback_rate_); + base::TimeDelta repeated_duration = std::isfinite(iterations_) + ? (curve_->Duration() * iterations_) + : base::TimeDelta::Max(); // Calculate the scaled active time base::TimeDelta scaled_active_time; if (playback_rate_ < 0) { DCHECK(std::isfinite(iterations_)); + base::TimeDelta active_duration = + repeated_duration / std::abs(playback_rate_); scaled_active_time = ((active_time - active_duration) * playback_rate_) + start_offset; } else {
diff --git a/cc/test/layer_tree_test.cc b/cc/test/layer_tree_test.cc index 1c469cb..1139dc3 100644 --- a/cc/test/layer_tree_test.cc +++ b/cc/test/layer_tree_test.cc
@@ -600,8 +600,9 @@ const viz::CompositorFrame& frame) override { hooks_->DisplayReceivedCompositorFrameOnThread(frame); } - void DisplayWillDrawAndSwap(bool will_draw_and_swap, - viz::RenderPassList* render_passes) override { + void DisplayWillDrawAndSwap( + bool will_draw_and_swap, + viz::AggregatedRenderPassList* render_passes) override { hooks_->DisplayWillDrawAndSwapOnThread(will_draw_and_swap, *render_passes); } void DisplayDidDrawAndSwap() override { @@ -665,7 +666,7 @@ init_vulkan = true; } else if (renderer_type_ == TestRendererType::kSkiaDawn) { scoped_feature_list_.InitAndEnableFeature(features::kSkiaDawn); -#if defined(OS_LINUX) +#if defined(OS_LINUX) || defined(OS_CHROMEOS) init_vulkan = true; #elif defined(OS_WIN) // TODO(sgilhuly): Initialize D3D12 for Windows.
diff --git a/cc/test/pixel_test.cc b/cc/test/pixel_test.cc index dc607f6..24676f9ab 100644 --- a/cc/test/pixel_test.cc +++ b/cc/test/pixel_test.cc
@@ -69,7 +69,7 @@ init_vulkan = true; } else if (backend == kSkiaDawn) { scoped_feature_list_.InitAndEnableFeature(features::kSkiaDawn); -#if defined(OS_LINUX) +#if defined(OS_LINUX) || defined(OS_CHROMEOS) init_vulkan = true; #elif defined(OS_WIN) // TODO(sgilhuly): Initialize D3D12 for Windows. @@ -90,7 +90,7 @@ PixelTest::~PixelTest() = default; -bool PixelTest::RunPixelTest(viz::RenderPassList* pass_list, +bool PixelTest::RunPixelTest(viz::AggregatedRenderPassList* pass_list, const base::FilePath& ref_file, const PixelComparator& comparator) { return RunPixelTestWithReadbackTarget(pass_list, pass_list->back().get(), @@ -98,8 +98,8 @@ } bool PixelTest::RunPixelTestWithReadbackTarget( - viz::RenderPassList* pass_list, - viz::RenderPass* target, + viz::AggregatedRenderPassList* pass_list, + viz::AggregatedRenderPass* target, const base::FilePath& ref_file, const PixelComparator& comparator) { return RunPixelTestWithReadbackTargetAndArea( @@ -107,8 +107,8 @@ } bool PixelTest::RunPixelTestWithReadbackTargetAndArea( - viz::RenderPassList* pass_list, - viz::RenderPass* target, + viz::AggregatedRenderPassList* pass_list, + viz::AggregatedRenderPass* target, const base::FilePath& ref_file, const PixelComparator& comparator, const gfx::Rect* copy_rect) { @@ -145,11 +145,11 @@ return PixelsMatchReference(ref_file, comparator); } -bool PixelTest::RunPixelTest(viz::RenderPassList* pass_list, +bool PixelTest::RunPixelTest(viz::AggregatedRenderPassList* pass_list, std::vector<SkColor>* ref_pixels, const PixelComparator& comparator) { base::RunLoop run_loop; - viz::RenderPass* target = pass_list->back().get(); + auto* target = pass_list->back().get(); std::unique_ptr<viz::CopyOutputRequest> request = std::make_unique<viz::CopyOutputRequest>(
diff --git a/cc/test/pixel_test.h b/cc/test/pixel_test.h index fee8f86..affac13 100644 --- a/cc/test/pixel_test.h +++ b/cc/test/pixel_test.h
@@ -58,24 +58,25 @@ explicit PixelTest(GraphicsBackend backend = kDefault); ~PixelTest() override; - bool RunPixelTest(viz::RenderPassList* pass_list, + bool RunPixelTest(viz::AggregatedRenderPassList* pass_list, const base::FilePath& ref_file, const PixelComparator& comparator); - bool RunPixelTest(viz::RenderPassList* pass_list, + bool RunPixelTest(viz::AggregatedRenderPassList* pass_list, std::vector<SkColor>* ref_pixels, const PixelComparator& comparator); - bool RunPixelTestWithReadbackTarget(viz::RenderPassList* pass_list, - viz::RenderPass* target, + bool RunPixelTestWithReadbackTarget(viz::AggregatedRenderPassList* pass_list, + viz::AggregatedRenderPass* target, const base::FilePath& ref_file, const PixelComparator& comparator); - bool RunPixelTestWithReadbackTargetAndArea(viz::RenderPassList* pass_list, - viz::RenderPass* target, - const base::FilePath& ref_file, - const PixelComparator& comparator, - const gfx::Rect* copy_rect); + bool RunPixelTestWithReadbackTargetAndArea( + viz::AggregatedRenderPassList* pass_list, + viz::AggregatedRenderPass* target, + const base::FilePath& ref_file, + const PixelComparator& comparator, + const gfx::Rect* copy_rect); viz::ContextProvider* context_provider() const { return output_surface_->context_provider();
diff --git a/cc/test/render_pass_test_utils.cc b/cc/test/render_pass_test_utils.cc index ca6689b..f4d89a9 100644 --- a/cc/test/render_pass_test_utils.cc +++ b/cc/test/render_pass_test_utils.cc
@@ -14,6 +14,7 @@ #include "base/bind.h" #include "base/bind_helpers.h" #include "components/viz/client/client_resource_provider.h" +#include "components/viz/common/quads/aggregated_render_pass_draw_quad.h" #include "components/viz/common/quads/debug_border_draw_quad.h" #include "components/viz/common/quads/render_pass_draw_quad.h" #include "components/viz/common/quads/shared_quad_state.h" @@ -62,6 +63,20 @@ return saved; } +viz::AggregatedRenderPass* AddRenderPass( + viz::AggregatedRenderPassList* pass_list, + viz::AggregatedRenderPassId render_pass_id, + const gfx::Rect& output_rect, + const gfx::Transform& root_transform, + const FilterOperations& filters) { + auto pass = std::make_unique<viz::AggregatedRenderPass>(); + pass->SetNew(render_pass_id, output_rect, output_rect, root_transform); + pass->filters = filters; + auto* saved = pass.get(); + pass_list->push_back(std::move(pass)); + return saved; +} + viz::RenderPass* AddRenderPassWithDamage(viz::RenderPassList* pass_list, viz::RenderPassId render_pass_id, const gfx::Rect& output_rect, @@ -76,18 +91,22 @@ return saved; } -viz::SolidColorDrawQuad* AddQuad(viz::RenderPass* pass, - const gfx::Rect& rect, - SkColor color) { - viz::SharedQuadState* shared_state = pass->CreateAndAppendSharedQuadState(); - shared_state->SetAll(gfx::Transform(), rect, rect, gfx::RRectF(), rect, false, - false, 1, SkBlendMode::kSrcOver, 0); - auto* quad = pass->CreateAndAppendDrawQuad<viz::SolidColorDrawQuad>(); - quad->SetNew(shared_state, rect, rect, color, false); - return quad; +viz::AggregatedRenderPass* AddRenderPassWithDamage( + viz::AggregatedRenderPassList* pass_list, + viz::AggregatedRenderPassId render_pass_id, + const gfx::Rect& output_rect, + const gfx::Rect& damage_rect, + const gfx::Transform& root_transform, + const FilterOperations& filters) { + auto pass = std::make_unique<viz::AggregatedRenderPass>(); + pass->SetNew(render_pass_id, output_rect, damage_rect, root_transform); + pass->filters = filters; + auto* saved = pass.get(); + pass_list->push_back(std::move(pass)); + return saved; } -viz::SolidColorDrawQuad* AddClippedQuad(viz::RenderPass* pass, +viz::SolidColorDrawQuad* AddClippedQuad(viz::AggregatedRenderPass* pass, const gfx::Rect& rect, SkColor color) { viz::SharedQuadState* shared_state = pass->CreateAndAppendSharedQuadState(); @@ -98,7 +117,7 @@ return quad; } -viz::SolidColorDrawQuad* AddTransformedQuad(viz::RenderPass* pass, +viz::SolidColorDrawQuad* AddTransformedQuad(viz::AggregatedRenderPass* pass, const gfx::Rect& rect, SkColor color, const gfx::Transform& transform) { @@ -112,23 +131,36 @@ return quad; } -viz::RenderPassDrawQuad* AddRenderPassQuad(viz::RenderPass* to_pass, - viz::RenderPass* contributing_pass) { +template <typename QuadType, typename RenderPassType> +QuadType* AddRenderPassQuadInternal(RenderPassType* to_pass, + RenderPassType* contributing_pass) { gfx::Rect output_rect = contributing_pass->output_rect; viz::SharedQuadState* shared_state = to_pass->CreateAndAppendSharedQuadState(); shared_state->SetAll(gfx::Transform(), output_rect, output_rect, gfx::RRectF(), output_rect, false, false, 1, SkBlendMode::kSrcOver, 0); - auto* quad = to_pass->CreateAndAppendDrawQuad<viz::RenderPassDrawQuad>(); + auto* quad = to_pass->template CreateAndAppendDrawQuad<QuadType>(); quad->SetNew(shared_state, output_rect, output_rect, contributing_pass->id, 0, gfx::RectF(), gfx::Size(), gfx::Vector2dF(), gfx::PointF(), gfx::RectF(), false, 1.0f); return quad; } -void AddRenderPassQuad(viz::RenderPass* to_pass, - viz::RenderPass* contributing_pass, +viz::RenderPassDrawQuad* AddRenderPassQuad(viz::RenderPass* to_pass, + viz::RenderPass* contributing_pass) { + return AddRenderPassQuadInternal<viz::RenderPassDrawQuad>(to_pass, + contributing_pass); +} +viz::AggregatedRenderPassDrawQuad* AddRenderPassQuad( + viz::AggregatedRenderPass* to_pass, + viz::AggregatedRenderPass* contributing_pass) { + return AddRenderPassQuadInternal<viz::AggregatedRenderPassDrawQuad>( + to_pass, contributing_pass); +} + +void AddRenderPassQuad(viz::AggregatedRenderPass* to_pass, + viz::AggregatedRenderPass* contributing_pass, viz::ResourceId mask_resource_id, gfx::Transform transform, SkBlendMode blend_mode) { @@ -137,7 +169,8 @@ to_pass->CreateAndAppendSharedQuadState(); shared_state->SetAll(transform, output_rect, output_rect, gfx::RRectF(), output_rect, false, false, 1, blend_mode, 0); - auto* quad = to_pass->CreateAndAppendDrawQuad<viz::RenderPassDrawQuad>(); + auto* quad = + to_pass->CreateAndAppendDrawQuad<viz::AggregatedRenderPassDrawQuad>(); gfx::Size arbitrary_nonzero_size(1, 1); quad->SetNew(shared_state, output_rect, output_rect, contributing_pass->id, mask_resource_id, gfx::RectF(output_rect), @@ -269,11 +302,11 @@ const std::vector<viz::ReturnedResource>& returned) {} void AddOneOfEveryQuadTypeInDisplayResourceProvider( - viz::RenderPass* to_pass, + viz::AggregatedRenderPass* to_pass, viz::DisplayResourceProvider* resource_provider, viz::ClientResourceProvider* child_resource_provider, viz::ContextProvider* child_context_provider, - viz::RenderPassId child_pass_id, + viz::AggregatedRenderPassId child_pass_id, gpu::SyncToken* sync_token_for_mailbox_tebxture) { gfx::Rect rect(0, 0, 100, 100); gfx::Rect visible_rect(0, 0, 100, 100); @@ -365,8 +398,8 @@ to_pass->CreateAndAppendDrawQuad<viz::DebugBorderDrawQuad>(); debug_border_quad->SetNew(shared_state, rect, visible_rect, SK_ColorRED, 1); if (child_pass_id) { - viz::RenderPassDrawQuad* render_pass_quad = - to_pass->CreateAndAppendDrawQuad<viz::RenderPassDrawQuad>(); + auto* render_pass_quad = + to_pass->CreateAndAppendDrawQuad<viz::AggregatedRenderPassDrawQuad>(); render_pass_quad->SetNew(shared_state, rect, visible_rect, child_pass_id, mapped_resource5, gfx::RectF(rect), gfx::Size(73, 26), gfx::Vector2dF(), gfx::PointF(),
diff --git a/cc/test/render_pass_test_utils.h b/cc/test/render_pass_test_utils.h index 2a67689..f43af3ce 100644 --- a/cc/test/render_pass_test_utils.h +++ b/cc/test/render_pass_test_utils.h
@@ -10,6 +10,7 @@ #include <vector> #include "cc/paint/filter_operations.h" +#include "components/viz/common/quads/aggregated_render_pass.h" #include "components/viz/common/quads/render_pass.h" #include "third_party/skia/include/core/SkColor.h" @@ -40,6 +41,13 @@ const gfx::Transform& root_transform, const FilterOperations& filters); +viz::AggregatedRenderPass* AddRenderPass( + viz::AggregatedRenderPassList* pass_list, + viz::AggregatedRenderPassId render_pass_id, + const gfx::Rect& output_rect, + const gfx::Transform& root_transform, + const FilterOperations& filters); + // Adds a new render pass with the provided properties to the given // render pass list. viz::RenderPass* AddRenderPassWithDamage(viz::RenderPassList* pass_list, @@ -48,19 +56,35 @@ const gfx::Rect& damage_rect, const gfx::Transform& root_transform, const FilterOperations& filters); +viz::AggregatedRenderPass* AddRenderPassWithDamage( + viz::AggregatedRenderPassList* pass_list, + viz::AggregatedRenderPassId render_pass_id, + const gfx::Rect& output_rect, + const gfx::Rect& damage_rect, + const gfx::Transform& root_transform, + const FilterOperations& filters); // Adds a solid quad to a given render pass. -viz::SolidColorDrawQuad* AddQuad(viz::RenderPass* pass, - const gfx::Rect& rect, - SkColor color); +template <typename RenderPassType> +inline viz::SolidColorDrawQuad* AddQuad(RenderPassType* pass, + const gfx::Rect& rect, + SkColor color) { + viz::SharedQuadState* shared_state = pass->CreateAndAppendSharedQuadState(); + shared_state->SetAll(gfx::Transform(), rect, rect, gfx::RRectF(), rect, false, + false, 1, SkBlendMode::kSrcOver, 0); + auto* quad = + pass->template CreateAndAppendDrawQuad<viz::SolidColorDrawQuad>(); + quad->SetNew(shared_state, rect, rect, color, false); + return quad; +} // Adds a solid quad to a given render pass and sets is_clipped=true. -viz::SolidColorDrawQuad* AddClippedQuad(viz::RenderPass* pass, +viz::SolidColorDrawQuad* AddClippedQuad(viz::AggregatedRenderPass* pass, const gfx::Rect& rect, SkColor color); // Adds a solid quad with a transform to a given render pass. -viz::SolidColorDrawQuad* AddTransformedQuad(viz::RenderPass* pass, +viz::SolidColorDrawQuad* AddTransformedQuad(viz::AggregatedRenderPass* pass, const gfx::Rect& rect, SkColor color, const gfx::Transform& transform); @@ -68,10 +92,13 @@ // Adds a render pass quad to an existing render pass. viz::RenderPassDrawQuad* AddRenderPassQuad(viz::RenderPass* to_pass, viz::RenderPass* contributing_pass); +viz::AggregatedRenderPassDrawQuad* AddRenderPassQuad( + viz::AggregatedRenderPass* to_pass, + viz::AggregatedRenderPass* contributing_pass); // Adds a render pass quad with the given mask resource, filter, and transform. -void AddRenderPassQuad(viz::RenderPass* to_pass, - viz::RenderPass* contributing_pass, +void AddRenderPassQuad(viz::AggregatedRenderPass* to_pass, + viz::AggregatedRenderPass* contributing_pass, viz::ResourceId mask_resource_id, gfx::Transform transform, SkBlendMode blend_mode); @@ -85,11 +112,11 @@ // The resource used in render pass is created by viz::ClientResourceProvider, // then transferred to viz::DisplayResourceProvider. void AddOneOfEveryQuadTypeInDisplayResourceProvider( - viz::RenderPass* to_pass, + viz::AggregatedRenderPass* to_pass, viz::DisplayResourceProvider* resource_provider, viz::ClientResourceProvider* child_resource_provider, viz::ContextProvider* child_context_provider, - viz::RenderPassId child_pass_id, + viz::AggregatedRenderPassId child_pass_id, gpu::SyncToken* sync_token_for_mailbox_texture); } // namespace cc
diff --git a/cc/test/test_hooks.h b/cc/test/test_hooks.h index ff697200..3ca6587 100644 --- a/cc/test/test_hooks.h +++ b/cc/test/test_hooks.h
@@ -5,9 +5,12 @@ #ifndef CC_TEST_TEST_HOOKS_H_ #define CC_TEST_TEST_HOOKS_H_ +#include <memory> + #include "cc/animation/animation_delegate.h" #include "cc/trees/layer_tree_host.h" #include "cc/trees/layer_tree_host_impl.h" +#include "components/viz/common/quads/aggregated_render_pass.h" namespace gfx { struct PresentationFeedback; @@ -96,7 +99,7 @@ const viz::CompositorFrame& frame) {} virtual void DisplayWillDrawAndSwapOnThread( bool will_draw_and_swap, - const viz::RenderPassList& render_passes) {} + const viz::AggregatedRenderPassList& render_passes) {} virtual void DisplayDidDrawAndSwapOnThread() {} // Main thread hooks.
diff --git a/cc/test/test_layer_tree_frame_sink.cc b/cc/test/test_layer_tree_frame_sink.cc index f8c23e0..36895c2 100644 --- a/cc/test/test_layer_tree_frame_sink.cc +++ b/cc/test/test_layer_tree_frame_sink.cc
@@ -8,6 +8,7 @@ #include <memory> #include <utility> +#include <vector> #include "base/bind.h" #include "base/single_thread_task_runner.h" @@ -248,7 +249,7 @@ void TestLayerTreeFrameSink::DisplayWillDrawAndSwap( bool will_draw_and_swap, - viz::RenderPassList* render_passes) { + viz::AggregatedRenderPassList* render_passes) { test_client_->DisplayWillDrawAndSwap(will_draw_and_swap, render_passes); }
diff --git a/cc/test/test_layer_tree_frame_sink.h b/cc/test/test_layer_tree_frame_sink.h index 864c90d..47cd2fa 100644 --- a/cc/test/test_layer_tree_frame_sink.h +++ b/cc/test/test_layer_tree_frame_sink.h
@@ -5,6 +5,10 @@ #ifndef CC_TEST_TEST_LAYER_TREE_FRAME_SINK_H_ #define CC_TEST_TEST_LAYER_TREE_FRAME_SINK_H_ +#include <memory> +#include <set> +#include <vector> + #include "base/memory/ref_counted.h" #include "base/memory/weak_ptr.h" #include "cc/trees/layer_tree_frame_sink.h" @@ -44,8 +48,9 @@ const viz::LocalSurfaceId& local_surface_id) = 0; virtual void DisplayReceivedCompositorFrame( const viz::CompositorFrame& frame) = 0; - virtual void DisplayWillDrawAndSwap(bool will_draw_and_swap, - viz::RenderPassList* render_passes) = 0; + virtual void DisplayWillDrawAndSwap( + bool will_draw_and_swap, + viz::AggregatedRenderPassList* render_passes) = 0; virtual void DisplayDidDrawAndSwap() = 0; }; @@ -109,8 +114,9 @@ // DisplayClient implementation. void DisplayOutputSurfaceLost() override; - void DisplayWillDrawAndSwap(bool will_draw_and_swap, - viz::RenderPassList* render_passes) override; + void DisplayWillDrawAndSwap( + bool will_draw_and_swap, + viz::AggregatedRenderPassList* render_passes) override; void DisplayDidDrawAndSwap() override; void DisplayDidReceiveCALayerParams( const gfx::CALayerParams& ca_layer_params) override;
diff --git a/cc/trees/layer_tree_host_impl_unittest.cc b/cc/trees/layer_tree_host_impl_unittest.cc index 745bd7a..8a6918b 100644 --- a/cc/trees/layer_tree_host_impl_unittest.cc +++ b/cc/trees/layer_tree_host_impl_unittest.cc
@@ -248,8 +248,8 @@ std::unique_ptr<TestFrameData> frame(new TestFrameData); EXPECT_EQ(DRAW_SUCCESS, host_impl_->PrepareToDraw(frame.get())); last_on_draw_render_passes_.clear(); - viz::RenderPass::CopyAll(frame->render_passes, - &last_on_draw_render_passes_); + viz::RenderPass::CopyAllForTest(frame->render_passes, + &last_on_draw_render_passes_); host_impl_->DrawLayers(frame.get()); host_impl_->DidDrawAllLayers(*frame); last_on_draw_frame_ = std::move(frame); @@ -11559,8 +11559,9 @@ const viz::LocalSurfaceId& local_surface_id) override {} void DisplayReceivedCompositorFrame( const viz::CompositorFrame& frame) override {} - void DisplayWillDrawAndSwap(bool will_draw_and_swap, - viz::RenderPassList* render_passes) override {} + void DisplayWillDrawAndSwap( + bool will_draw_and_swap, + viz::AggregatedRenderPassList* render_passes) override {} void DisplayDidDrawAndSwap() override {} private:
diff --git a/cc/trees/layer_tree_host_pixeltest_tiles.cc b/cc/trees/layer_tree_host_pixeltest_tiles.cc index a2aa1aaf..839ef43 100644 --- a/cc/trees/layer_tree_host_pixeltest_tiles.cc +++ b/cc/trees/layer_tree_host_pixeltest_tiles.cc
@@ -210,7 +210,7 @@ LayerTreeHostTilesTestPartialInvalidationMultiThread, ::testing::ValuesIn(kTestCasesMultiThread)); -#if defined(OS_LINUX) && defined(THREAD_SANITIZER) +#if (defined(OS_LINUX) || defined(OS_CHROMEOS)) && defined(THREAD_SANITIZER) // Flaky on Linux TSAN. https://crbug.com/707711 #define MAYBE_PartialRaster DISABLED_PartialRaster #elif defined(OS_WIN) && defined(ADDRESS_SANITIZER)
diff --git a/cc/trees/layer_tree_host_unittest_copyrequest.cc b/cc/trees/layer_tree_host_unittest_copyrequest.cc index a0191d0e..0d92a9e 100644 --- a/cc/trees/layer_tree_host_unittest_copyrequest.cc +++ b/cc/trees/layer_tree_host_unittest_copyrequest.cc
@@ -541,7 +541,7 @@ void DisplayWillDrawAndSwapOnThread( bool will_draw_and_swap, - const viz::RenderPassList& render_passes) override { + const viz::AggregatedRenderPassList& render_passes) override { EXPECT_TRUE(will_draw_and_swap) << did_swap_; if (did_swap_) { // TODO(crbug.com/564832): Ignore the extra frame that occurs due to copy @@ -582,8 +582,8 @@ void AfterTest() override { EXPECT_TRUE(did_swap_); } - viz::RenderPassId parent_render_pass_id; - viz::RenderPassId copy_layer_render_pass_id; + viz::AggregatedRenderPassId parent_render_pass_id; + viz::AggregatedRenderPassId copy_layer_render_pass_id; TestLayerTreeFrameSink* frame_sink_ = nullptr; bool did_swap_ = false; FakeContentLayerClient client_;
diff --git a/chrome/android/features/autofill_assistant/java/src/org/chromium/chrome/browser/autofill_assistant/AutofillAssistantUiController.java b/chrome/android/features/autofill_assistant/java/src/org/chromium/chrome/browser/autofill_assistant/AutofillAssistantUiController.java index 2457d3c..ca9fffb 100644 --- a/chrome/android/features/autofill_assistant/java/src/org/chromium/chrome/browser/autofill_assistant/AutofillAssistantUiController.java +++ b/chrome/android/features/autofill_assistant/java/src/org/chromium/chrome/browser/autofill_assistant/AutofillAssistantUiController.java
@@ -132,7 +132,7 @@ mActivityTabObserver = new ActivityTabProvider.ActivityTabTabObserver(activity.getActivityTabProvider()) { @Override - protected void onObservingDifferentTab(Tab tab) { + protected void onObservingDifferentTab(Tab tab, boolean hint) { if (mWebContents == null) return; if (!allowTabSwitching) {
diff --git a/chrome/android/features/autofill_assistant/public/java/src/org/chromium/chrome/browser/autofill_assistant/AutofillAssistantMetrics.java b/chrome/android/features/autofill_assistant/public/java/src/org/chromium/chrome/browser/autofill_assistant/AutofillAssistantMetrics.java index 8202528..26bc180 100644 --- a/chrome/android/features/autofill_assistant/public/java/src/org/chromium/chrome/browser/autofill_assistant/AutofillAssistantMetrics.java +++ b/chrome/android/features/autofill_assistant/public/java/src/org/chromium/chrome/browser/autofill_assistant/AutofillAssistantMetrics.java
@@ -4,6 +4,8 @@ package org.chromium.chrome.browser.autofill_assistant; +import androidx.annotation.Nullable; + import org.chromium.base.metrics.RecordHistogram; import org.chromium.chrome.browser.autofill_assistant.metrics.DropOutReason; import org.chromium.chrome.browser.autofill_assistant.metrics.FeatureModuleInstallation; @@ -52,6 +54,9 @@ */ /* package */ static void recordLiteScriptStarted( WebContents webContents, @LiteScriptStarted int started) { + if (!areWebContentsValid(webContents)) { + return; + } new UkmRecorder.Bridge().recordEventWithIntegerMetric(webContents, /* eventName = */ "AutofillAssistant.LiteScriptStarted", /* metricName = */ "LiteScriptStarted", @@ -63,6 +68,9 @@ */ /* package */ static void recordLiteScriptFinished( WebContents webContents, @LiteScriptFinishedState int finishedState) { + if (!areWebContentsValid(webContents)) { + return; + } new UkmRecorder.Bridge().recordEventWithIntegerMetric(webContents, /* eventName = */ "AutofillAssistant.LiteScriptFinished", /* metricName = */ "LiteScriptFinished", @@ -74,9 +82,20 @@ */ /* package */ static void recordLiteScriptOnboarding( WebContents webContents, @LiteScriptOnboarding int onboarding) { + if (!areWebContentsValid(webContents)) { + return; + } new UkmRecorder.Bridge().recordEventWithIntegerMetric(webContents, /* eventName = */ "AutofillAssistant.LiteScriptOnboarding", /* metricName = */ "LiteScriptOnboarding", /* metricValue = */ onboarding); } + + /** + * Returns whether {@code webContents} are non-null and valid. Invalid webContents will cause a + * failed DCHECK when attempting to report UKM metrics. + */ + private static boolean areWebContentsValid(@Nullable WebContents webContents) { + return webContents != null && !webContents.isDestroyed(); + } }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/ActivityTabProvider.java b/chrome/android/java/src/org/chromium/chrome/browser/ActivityTabProvider.java index 56a8f09..1dada493 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/ActivityTabProvider.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/ActivityTabProvider.java
@@ -73,16 +73,32 @@ private Tab mTab; /** - * Create a new {@link TabObserver} that only observes the activity tab. + * Create a new {@link TabObserver} that only observes the activity tab. It doesn't trigger + * for the initial tab being attached to after creation. * @param tabProvider An {@link ActivityTabProvider} to get the activity tab. */ public ActivityTabTabObserver(ActivityTabProvider tabProvider) { + this(tabProvider, false); + } + + /** + * Create a new {@link TabObserver} that only observes the activity tab. This constructor + * allows the option of triggering for the initial tab being attached to after creation. + * @param tabProvider An {@link ActivityTabProvider} to get the activity tab. + * @param shouldTrigger Whether the observer should be triggered for the initial tab after + * creation. + */ + public ActivityTabTabObserver(ActivityTabProvider tabProvider, boolean shouldTrigger) { mTabProvider = tabProvider; mActivityTabObserver = (tab, hint) -> { updateObservedTab(tab); - onObservingDifferentTab(tab); + onObservingDifferentTab(tab, hint); }; - mTabProvider.addObserver(mActivityTabObserver); + if (shouldTrigger) { + mTabProvider.addObserverAndTrigger(mActivityTabObserver); + } else { + mTabProvider.addObserver(mActivityTabObserver); + } updateObservedTab(mTabProvider.get()); } @@ -97,11 +113,14 @@ } /** - * A notification that the observer has switched to observing a different tab. This will not - * be called for the initial tab being attached to after creation. + * A notification that the observer has switched to observing a different tab. This can be + * called a first time with the {@code hint} parameter set to true, indicating that a new + * tab is going to be selected. * @param tab The tab that the observer is now observing. This can be null. + * @param hint Whether the change event is a hint that a tab change is likely. If true, the + * provided tab may still be frozen and is not yet selected. */ - protected void onObservingDifferentTab(Tab tab) {} + protected void onObservingDifferentTab(Tab tab, boolean hint) {} /** * Clean up any state held by this observer.
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/ChromeActionModeHandler.java b/chrome/android/java/src/org/chromium/chrome/browser/ChromeActionModeHandler.java index c43cfb1..8472760 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/ChromeActionModeHandler.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/ChromeActionModeHandler.java
@@ -66,7 +66,7 @@ mActivityTabTabObserver = new ActivityTabProvider.ActivityTabTabObserver(activityTabProvider) { @Override - public void onObservingDifferentTab(Tab tab) { + public void onObservingDifferentTab(Tab tab, boolean hint) { // ActivityTabProvider will null out the tab passed to // onObservingDifferentTab when the tab is non-interactive (e.g. when // entering the TabSwitcher), but in those cases we actually still want to
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/TabThemeColorProvider.java b/chrome/android/java/src/org/chromium/chrome/browser/TabThemeColorProvider.java index b757a50..078f070 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/TabThemeColorProvider.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/TabThemeColorProvider.java
@@ -25,7 +25,7 @@ public void setActivityTabProvider(ActivityTabProvider provider) { mActivityTabTabObserver = new ActivityTabTabObserver(provider) { @Override - public void onObservingDifferentTab(Tab tab) { + public void onObservingDifferentTab(Tab tab, boolean hint) { if (tab == null) return; updatePrimaryColor(TabThemeColorHelper.getColor(tab), false); }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/browserservices/TrustedWebActivitySettingsLauncher.java b/chrome/android/java/src/org/chromium/chrome/browser/browserservices/TrustedWebActivitySettingsLauncher.java index 0bf2459..8e31acf4 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/browserservices/TrustedWebActivitySettingsLauncher.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/browserservices/TrustedWebActivitySettingsLauncher.java
@@ -13,8 +13,8 @@ import org.chromium.chrome.R; import org.chromium.chrome.browser.settings.SettingsLauncher; import org.chromium.chrome.browser.settings.SettingsLauncherImpl; +import org.chromium.components.browser_ui.site_settings.AllSiteSettings; import org.chromium.components.browser_ui.site_settings.SettingsNavigationSource; -import org.chromium.components.browser_ui.site_settings.SingleCategorySettings; import org.chromium.components.browser_ui.site_settings.SingleWebsiteSettings; import org.chromium.components.browser_ui.site_settings.SiteSettingsCategory; @@ -76,17 +76,16 @@ private static void openFilteredAllSiteSettings(Context context, Collection<String> domains) { Bundle extras = new Bundle(); - extras.putString(SingleCategorySettings.EXTRA_CATEGORY, + extras.putString(AllSiteSettings.EXTRA_CATEGORY, SiteSettingsCategory.preferenceKey(SiteSettingsCategory.Type.ALL_SITES)); - extras.putString(SingleCategorySettings.EXTRA_TITLE, + extras.putString(AllSiteSettings.EXTRA_TITLE, context.getString(R.string.twa_clear_data_site_selection_title)); - extras.putStringArrayList( - SingleCategorySettings.EXTRA_SELECTED_DOMAINS, new ArrayList<>(domains)); + extras.putStringArrayList(AllSiteSettings.EXTRA_SELECTED_DOMAINS, new ArrayList<>(domains)); extras.putInt(SettingsNavigationSource.EXTRA_KEY, SettingsNavigationSource.TWA_CLEAR_DATA_DIALOG); SettingsLauncher settingsLauncher = new SettingsLauncherImpl(); - settingsLauncher.launchSettingsActivity(context, SingleCategorySettings.class, extras); + settingsLauncher.launchSettingsActivity(context, AllSiteSettings.class, extras); } /**
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/fullscreen/BrowserControlsManager.java b/chrome/android/java/src/org/chromium/chrome/browser/fullscreen/BrowserControlsManager.java index 2f74126e..906e452 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/fullscreen/BrowserControlsManager.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/fullscreen/BrowserControlsManager.java
@@ -184,7 +184,7 @@ ApplicationStatus.registerStateListenerForActivity(this, mActivity); mActiveTabObserver = new ActivityTabTabObserver(activityTabProvider) { @Override - protected void onObservingDifferentTab(Tab tab) { + protected void onObservingDifferentTab(Tab tab, boolean hint) { setTab(tab); } };
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/fullscreen/FullscreenHtmlApiHandler.java b/chrome/android/java/src/org/chromium/chrome/browser/fullscreen/FullscreenHtmlApiHandler.java index 430b2e4..499b079 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/fullscreen/FullscreenHtmlApiHandler.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/fullscreen/FullscreenHtmlApiHandler.java
@@ -209,7 +209,7 @@ ApplicationStatus.registerWindowFocusChangedListener(this); mActiveTabObserver = new ActivityTabTabObserver(activityTabProvider) { @Override - protected void onObservingDifferentTab(Tab tab) { + protected void onObservingDifferentTab(Tab tab, boolean hint) { mTab = tab; setContentView(tab != null ? tab.getContentView() : null); if (tab != null) updateMultiTouchZoomSupport(!getPersistentFullscreenMode());
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/gesturenav/HistoryNavigationCoordinator.java b/chrome/android/java/src/org/chromium/chrome/browser/gesturenav/HistoryNavigationCoordinator.java index a5cd255..57c3ef12 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/gesturenav/HistoryNavigationCoordinator.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/gesturenav/HistoryNavigationCoordinator.java
@@ -115,7 +115,7 @@ mActivityTabObserver = new ActivityTabProvider.ActivityTabTabObserver(tabProvider) { @Override - protected void onObservingDifferentTab(Tab tab) { + protected void onObservingDifferentTab(Tab tab, boolean hint) { if (mTab != null && mTab.isInitialized()) { SwipeRefreshHandler.from(mTab).setNavigationCoordinator(null); }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/omnibox/suggestions/AutocompleteMediator.java b/chrome/android/java/src/org/chromium/chrome/browser/omnibox/suggestions/AutocompleteMediator.java index 49e2c4f..625b86f 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/omnibox/suggestions/AutocompleteMediator.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/omnibox/suggestions/AutocompleteMediator.java
@@ -373,7 +373,7 @@ } @Override - protected void onObservingDifferentTab(Tab tab) { + protected void onObservingDifferentTab(Tab tab, boolean hint) { if (tab == null) return; maybeTriggerCacheRefresh(tab.getUrlString()); }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/password_manager/PasswordManagerDialogView.java b/chrome/android/java/src/org/chromium/chrome/browser/password_manager/PasswordManagerDialogView.java index 554242c..52131526 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/password_manager/PasswordManagerDialogView.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/password_manager/PasswordManagerDialogView.java
@@ -77,6 +77,17 @@ mInlineHelpButtonView.setVisibility(usesInlineIcon ? VISIBLE : GONE); } + void cropImageToText() { + LinearLayout.LayoutParams marginParams = + new LinearLayout.LayoutParams(mIllustrationView.getLayoutParams()); + marginParams.setMarginStart(getContext().getResources().getDimensionPixelSize( + R.dimen.password_manager_dialog_text_margin)); + marginParams.setMarginEnd(getContext().getResources().getDimensionPixelSize( + R.dimen.password_manager_dialog_text_margin)); + mIllustrationView.setLayoutParams(marginParams); + mIllustrationView.setScaleType(ImageView.ScaleType.CENTER_CROP); + } + void setTitle(String title) { mTitleView.setText(title); }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/password_manager/PasswordManagerDialogViewBinder.java b/chrome/android/java/src/org/chromium/chrome/browser/password_manager/PasswordManagerDialogViewBinder.java index b5a142e..6629cf4 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/password_manager/PasswordManagerDialogViewBinder.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/password_manager/PasswordManagerDialogViewBinder.java
@@ -12,6 +12,7 @@ import android.view.View; +import org.chromium.chrome.browser.flags.ChromeFeatureList; import org.chromium.ui.modelutil.PropertyKey; import org.chromium.ui.modelutil.PropertyModel; @@ -28,6 +29,11 @@ } else if (ILLUSTRATION_VISIBLE == propertyKey) { dialogView.updateIllustrationVisibility(model.get(ILLUSTRATION_VISIBLE)); dialogView.updateHelpIcon(!model.get(ILLUSTRATION_VISIBLE)); + // TODO(crbug.com/1092444): Depending on feature status, remove this or inline the + // cropping into password_manager_dialog_with_help_button.xml. + if (ChromeFeatureList.isEnabled(ChromeFeatureList.PASSWORD_CHECK)) { + dialogView.cropImageToText(); + } } else if (TITLE == propertyKey) { dialogView.setTitle(model.get(TITLE)); } else if (DETAILS == propertyKey) {
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/signin/account_picker/AccountPickerBottomSheetMediator.java b/chrome/android/java/src/org/chromium/chrome/browser/signin/account_picker/AccountPickerBottomSheetMediator.java index 510f4da..26bbd02 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/signin/account_picker/AccountPickerBottomSheetMediator.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/signin/account_picker/AccountPickerBottomSheetMediator.java
@@ -13,7 +13,7 @@ import org.chromium.base.task.AsyncTask; import org.chromium.chrome.R; import org.chromium.chrome.browser.signin.ProfileDataCache; -import org.chromium.chrome.browser.signin.account_picker.AccountPickerBottomSheetProperties.AccountPickerBottomSheetState; +import org.chromium.chrome.browser.signin.account_picker.AccountPickerBottomSheetProperties.ViewState; import org.chromium.components.signin.AccountManagerFacade; import org.chromium.components.signin.AccountManagerFacadeProvider; import org.chromium.components.signin.AccountUtils; @@ -68,8 +68,7 @@ public void onAccountSelected(String accountName, boolean isDefaultAccount) { // Clicking on one account in the account list when the account list is expanded // will collapse it to the selected account - mModel.set(AccountPickerBottomSheetProperties.ACCOUNT_PICKER_BOTTOM_SHEET_STATE, - AccountPickerBottomSheetState.COLLAPSED_ACCOUNT_LIST); + mModel.set(AccountPickerBottomSheetProperties.VIEW_STATE, ViewState.COLLAPSED_ACCOUNT_LIST); setSelectedAccountName(accountName); } @@ -86,8 +85,7 @@ */ @Override public void goIncognitoMode() { - mModel.set(AccountPickerBottomSheetProperties.ACCOUNT_PICKER_BOTTOM_SHEET_STATE, - AccountPickerBottomSheetState.INCOGNITO_INTERSTITIAL); + mModel.set(AccountPickerBottomSheetProperties.VIEW_STATE, ViewState.INCOGNITO_INTERSTITIAL); mAccountPickerDelegate.goIncognitoMode(); } @@ -111,24 +109,22 @@ if (accounts.isEmpty()) { // If all accounts disappeared, no matter if the account list is collapsed or expanded, // we will go to the zero account screen. - mModel.set(AccountPickerBottomSheetProperties.ACCOUNT_PICKER_BOTTOM_SHEET_STATE, - AccountPickerBottomSheetState.NO_ACCOUNTS); + mModel.set(AccountPickerBottomSheetProperties.VIEW_STATE, ViewState.NO_ACCOUNTS); mSelectedAccountName = null; mModel.set(AccountPickerBottomSheetProperties.SELECTED_ACCOUNT_DATA, null); return; } - @AccountPickerBottomSheetState - int state = - mModel.get(AccountPickerBottomSheetProperties.ACCOUNT_PICKER_BOTTOM_SHEET_STATE); - if (state == AccountPickerBottomSheetState.NO_ACCOUNTS) { + @ViewState + int viewState = mModel.get(AccountPickerBottomSheetProperties.VIEW_STATE); + if (viewState == ViewState.NO_ACCOUNTS) { // When a non-empty account list appears while it is currently zero-account screen, // we should change the screen to collapsed account list and set the selected account // to the first account of the account list - mModel.set(AccountPickerBottomSheetProperties.ACCOUNT_PICKER_BOTTOM_SHEET_STATE, - AccountPickerBottomSheetState.COLLAPSED_ACCOUNT_LIST); + mModel.set(AccountPickerBottomSheetProperties.VIEW_STATE, + ViewState.COLLAPSED_ACCOUNT_LIST); setSelectedAccountName(accounts.get(0).name); - } else if (state == AccountPickerBottomSheetState.COLLAPSED_ACCOUNT_LIST + } else if (viewState == ViewState.COLLAPSED_ACCOUNT_LIST && AccountUtils.findAccountByName(accounts, mSelectedAccountName) == null) { // When it is already collapsed account list, we update the selected account only // when the current selected account name is no longer in the new account list @@ -159,8 +155,7 @@ private void onSelectedAccountClicked() { // Clicking on the selected account when the account list is collapsed will expand the // account list and make the account list visible - mModel.set(AccountPickerBottomSheetProperties.ACCOUNT_PICKER_BOTTOM_SHEET_STATE, - AccountPickerBottomSheetState.EXPANDED_ACCOUNT_LIST); + mModel.set(AccountPickerBottomSheetProperties.VIEW_STATE, ViewState.EXPANDED_ACCOUNT_LIST); } /** @@ -171,8 +166,7 @@ if (mSelectedAccountName == null) { addAccount(); } else { - mModel.set(AccountPickerBottomSheetProperties.ACCOUNT_PICKER_BOTTOM_SHEET_STATE, - AccountPickerBottomSheetState.SIGNIN_IN_PROGRESS); + mModel.set(AccountPickerBottomSheetProperties.VIEW_STATE, ViewState.SIGNIN_IN_PROGRESS); new AsyncTask<String>() { @Override protected String doInBackground() { @@ -192,11 +186,10 @@ private void onSignInError(GoogleServiceAuthError error) { if (error.getState() == State.INVALID_GAIA_CREDENTIALS) { - mModel.set(AccountPickerBottomSheetProperties.ACCOUNT_PICKER_BOTTOM_SHEET_STATE, - AccountPickerBottomSheetState.SIGNIN_AUTH_ERROR); + mModel.set(AccountPickerBottomSheetProperties.VIEW_STATE, ViewState.SIGNIN_AUTH_ERROR); } else { - mModel.set(AccountPickerBottomSheetProperties.ACCOUNT_PICKER_BOTTOM_SHEET_STATE, - AccountPickerBottomSheetState.SIGNIN_GENERAL_ERROR); + mModel.set( + AccountPickerBottomSheetProperties.VIEW_STATE, ViewState.SIGNIN_GENERAL_ERROR); } } }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/signin/account_picker/AccountPickerBottomSheetProperties.java b/chrome/android/java/src/org/chromium/chrome/browser/signin/account_picker/AccountPickerBottomSheetProperties.java index 50c2ab39..2cd870b 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/signin/account_picker/AccountPickerBottomSheetProperties.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/signin/account_picker/AccountPickerBottomSheetProperties.java
@@ -21,21 +21,21 @@ */ class AccountPickerBottomSheetProperties { /** - * States of account picker. - * Different account picker state correspond to different account picker bottom sheet + * View states of account picker. + * Different account picker view state correspond to different account picker bottom sheet * configuration. */ @IntDef({ - AccountPickerBottomSheetState.NO_ACCOUNTS, - AccountPickerBottomSheetState.COLLAPSED_ACCOUNT_LIST, - AccountPickerBottomSheetState.EXPANDED_ACCOUNT_LIST, - AccountPickerBottomSheetState.SIGNIN_IN_PROGRESS, - AccountPickerBottomSheetState.INCOGNITO_INTERSTITIAL, - AccountPickerBottomSheetState.SIGNIN_GENERAL_ERROR, - AccountPickerBottomSheetState.SIGNIN_AUTH_ERROR, + ViewState.NO_ACCOUNTS, + ViewState.COLLAPSED_ACCOUNT_LIST, + ViewState.EXPANDED_ACCOUNT_LIST, + ViewState.SIGNIN_IN_PROGRESS, + ViewState.INCOGNITO_INTERSTITIAL, + ViewState.SIGNIN_GENERAL_ERROR, + ViewState.SIGNIN_AUTH_ERROR, }) @Retention(RetentionPolicy.SOURCE) - @interface AccountPickerBottomSheetState { + @interface ViewState { /** * When there is no account on device, the user sees only one blue button * |Add account to device|. @@ -112,18 +112,17 @@ static final ReadableObjectPropertyKey<Runnable> ON_CONTINUE_AS_CLICKED = new ReadableObjectPropertyKey<>("on_continue_as_clicked"); - // PropertyKey indicates the state of the account picker bottom sheet - static final WritableIntPropertyKey ACCOUNT_PICKER_BOTTOM_SHEET_STATE = - new WritableIntPropertyKey("account_picker_bottom_sheet_state"); + // PropertyKey indicates the view state of the account picker bottom sheet + static final WritableIntPropertyKey VIEW_STATE = new WritableIntPropertyKey("view_state"); - static final PropertyKey[] ALL_KEYS = new PropertyKey[] {ON_SELECTED_ACCOUNT_CLICKED, - SELECTED_ACCOUNT_DATA, ON_CONTINUE_AS_CLICKED, ACCOUNT_PICKER_BOTTOM_SHEET_STATE}; + static final PropertyKey[] ALL_KEYS = new PropertyKey[] { + ON_SELECTED_ACCOUNT_CLICKED, SELECTED_ACCOUNT_DATA, ON_CONTINUE_AS_CLICKED, VIEW_STATE}; /** * Creates a default model for the AccountPickerBottomSheet. * * In the default model, as the selected account data is null, the bottom sheet is in the - * state {@link AccountPickerBottomSheetState#NO_ACCOUNTS}. + * state {@link ViewState#NO_ACCOUNTS}. */ static PropertyModel createModel( Runnable onSelectedAccountClicked, Runnable onContinueAsClicked) { @@ -131,7 +130,7 @@ .with(ON_SELECTED_ACCOUNT_CLICKED, onSelectedAccountClicked) .with(SELECTED_ACCOUNT_DATA, null) .with(ON_CONTINUE_AS_CLICKED, onContinueAsClicked) - .with(ACCOUNT_PICKER_BOTTOM_SHEET_STATE, AccountPickerBottomSheetState.NO_ACCOUNTS) + .with(VIEW_STATE, ViewState.NO_ACCOUNTS) .build(); }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/signin/account_picker/AccountPickerBottomSheetViewBinder.java b/chrome/android/java/src/org/chromium/chrome/browser/signin/account_picker/AccountPickerBottomSheetViewBinder.java index 23babd1..b41821f 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/signin/account_picker/AccountPickerBottomSheetViewBinder.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/signin/account_picker/AccountPickerBottomSheetViewBinder.java
@@ -5,7 +5,7 @@ package org.chromium.chrome.browser.signin.account_picker; import org.chromium.chrome.browser.signin.DisplayableProfileData; -import org.chromium.chrome.browser.signin.account_picker.AccountPickerBottomSheetProperties.AccountPickerBottomSheetState; +import org.chromium.chrome.browser.signin.account_picker.AccountPickerBottomSheetProperties.ViewState; import org.chromium.ui.modelutil.PropertyKey; import org.chromium.ui.modelutil.PropertyModel; @@ -19,12 +19,10 @@ view.getSelectedAccountView().setOnClickListener(v -> { model.get(AccountPickerBottomSheetProperties.ON_SELECTED_ACCOUNT_CLICKED).run(); }); - } else if (propertyKey - == AccountPickerBottomSheetProperties.ACCOUNT_PICKER_BOTTOM_SHEET_STATE) { - @AccountPickerBottomSheetState - int state = - model.get(AccountPickerBottomSheetProperties.ACCOUNT_PICKER_BOTTOM_SHEET_STATE); - switchToState(view, state); + } else if (propertyKey == AccountPickerBottomSheetProperties.VIEW_STATE) { + @ViewState + int viewState = model.get(AccountPickerBottomSheetProperties.VIEW_STATE); + switchToState(view, viewState); } else if (propertyKey == AccountPickerBottomSheetProperties.SELECTED_ACCOUNT_DATA) { DisplayableProfileData profileData = model.get(AccountPickerBottomSheetProperties.SELECTED_ACCOUNT_DATA); @@ -39,36 +37,35 @@ } /** - * Sets up the configuration of account picker bottom sheet according to the given state. + * Sets up the configuration of account picker bottom sheet according to the given + * {@link ViewState}. */ - private static void switchToState(AccountPickerBottomSheetView view, - @AccountPickerBottomSheetState int accountPickerBottomSheetState) { - switch (accountPickerBottomSheetState) { - case AccountPickerBottomSheetState.NO_ACCOUNTS: + private static void switchToState(AccountPickerBottomSheetView view, @ViewState int viewState) { + switch (viewState) { + case ViewState.NO_ACCOUNTS: view.collapseToNoAccountView(); break; - case AccountPickerBottomSheetState.COLLAPSED_ACCOUNT_LIST: + case ViewState.COLLAPSED_ACCOUNT_LIST: view.collapseAccountList(); break; - case AccountPickerBottomSheetState.EXPANDED_ACCOUNT_LIST: + case ViewState.EXPANDED_ACCOUNT_LIST: view.expandAccountList(); break; - case AccountPickerBottomSheetState.SIGNIN_IN_PROGRESS: + case ViewState.SIGNIN_IN_PROGRESS: view.setUpSignInInProgressView(); break; - case AccountPickerBottomSheetState.INCOGNITO_INTERSTITIAL: + case ViewState.INCOGNITO_INTERSTITIAL: view.setUpIncognitoInterstitialView(); break; - case AccountPickerBottomSheetState.SIGNIN_GENERAL_ERROR: + case ViewState.SIGNIN_GENERAL_ERROR: view.setUpSignInGeneralErrorView(); break; - case AccountPickerBottomSheetState.SIGNIN_AUTH_ERROR: + case ViewState.SIGNIN_AUTH_ERROR: view.setUpSignInAuthErrorView(); break; default: throw new IllegalArgumentException( - "Cannot bind AccountPickerBottomSheetView for the state:" - + accountPickerBottomSheetState); + "Cannot bind AccountPickerBottomSheetView for the view state:" + viewState); } }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/sync/settings/SyncAndServicesSettings.java b/chrome/android/java/src/org/chromium/chrome/browser/sync/settings/SyncAndServicesSettings.java index 4240e3e3..5e9808c 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/sync/settings/SyncAndServicesSettings.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/sync/settings/SyncAndServicesSettings.java
@@ -274,7 +274,10 @@ @Override public void onDestroy() { super.onDestroy(); - if (wasSigninFlowInterrupted()) { + // The user might also sign out from this page. Check to see if the user is signed in + // before going through this flow. + if (wasSigninFlowInterrupted() + && mSigninPreference.getState() == SignInPreference.State.SIGNED_IN) { // If the setup flow was previously interrupted, and now the user dismissed the page // without turning sync on, then mark first setup as complete (so that we won't show the // error again), but turn sync off.
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/sync/settings/SyncSettingsUtils.java b/chrome/android/java/src/org/chromium/chrome/browser/sync/settings/SyncSettingsUtils.java index 6518db14..33f6e5e 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/sync/settings/SyncSettingsUtils.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/sync/settings/SyncSettingsUtils.java
@@ -212,7 +212,7 @@ Resources res = context.getResources(); if (!AndroidSyncSettings.get().doesMasterSyncSettingAllowChromeSync()) { - return res.getString(R.string.sync_android_master_sync_disabled); + return res.getString(R.string.sync_android_system_sync_disabled); } if (profileSyncService == null) {
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/tab/AccessibilityVisibilityHandler.java b/chrome/android/java/src/org/chromium/chrome/browser/tab/AccessibilityVisibilityHandler.java index 6db4f1b..aa72dd3 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/tab/AccessibilityVisibilityHandler.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/tab/AccessibilityVisibilityHandler.java
@@ -20,7 +20,7 @@ ActivityTabProvider activityTabProvider, TabObscuringHandler tabObscuringHandler) { mActivityTabObserver = new ActivityTabProvider.ActivityTabTabObserver(activityTabProvider) { @Override - public void onObservingDifferentTab(Tab tab) { + public void onObservingDifferentTab(Tab tab, boolean hint) { if (mTab == tab) return; TabImpl tabImpl = (TabImpl) tab;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/toolbar/HomeButton.java b/chrome/android/java/src/org/chromium/chrome/browser/toolbar/HomeButton.java index 36130cb..eec0ac33 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/toolbar/HomeButton.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/toolbar/HomeButton.java
@@ -167,7 +167,7 @@ mActivityTabProvider = activityTabProvider; mActivityTabTabObserver = new ActivityTabTabObserver(activityTabProvider) { @Override - public void onObservingDifferentTab(Tab tab) { + public void onObservingDifferentTab(Tab tab, boolean hint) { if (tab == null) return; updateButtonEnabledState(tab); }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/toolbar/ToolbarManager.java b/chrome/android/java/src/org/chromium/chrome/browser/toolbar/ToolbarManager.java index 10888e5..916975c 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/toolbar/ToolbarManager.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/toolbar/ToolbarManager.java
@@ -353,7 +353,7 @@ mActivityTabTabObserver = new ActivityTabProvider.ActivityTabTabObserver( mActivityTabProvider) { @Override - public void onObservingDifferentTab(Tab tab) { + public void onObservingDifferentTab(Tab tab, boolean hint) { // ActivityTabProvider will null out the tab passed to onObservingDifferentTab when // the tab is non-interactive (e.g. when entering the TabSwitcher), but in those // cases we actually still want to use the most recently selected tab.
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/toolbar/bottom/ShareButton.java b/chrome/android/java/src/org/chromium/chrome/browser/toolbar/bottom/ShareButton.java index f9f58e1..b54faf1 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/toolbar/bottom/ShareButton.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/toolbar/bottom/ShareButton.java
@@ -59,7 +59,7 @@ void setActivityTabProvider(ActivityTabProvider activityTabProvider) { mActivityTabTabObserver = new ActivityTabTabObserver(activityTabProvider) { @Override - public void onObservingDifferentTab(Tab tab) { + public void onObservingDifferentTab(Tab tab, boolean hint) { updateButtonEnabledState(tab); }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/toolbar/load_progress/LoadProgressMediator.java b/chrome/android/java/src/org/chromium/chrome/browser/toolbar/load_progress/LoadProgressMediator.java index fa3c88d..668c6d88 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/toolbar/load_progress/LoadProgressMediator.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/toolbar/load_progress/LoadProgressMediator.java
@@ -85,7 +85,7 @@ } @Override - protected void onObservingDifferentTab(Tab tab) { + protected void onObservingDifferentTab(Tab tab, boolean hint) { onNewTabObserved(tab); } };
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/ui/system/StatusBarColorController.java b/chrome/android/java/src/org/chromium/chrome/browser/ui/system/StatusBarColorController.java index 323a796..cb0f24d3 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/ui/system/StatusBarColorController.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/ui/system/StatusBarColorController.java
@@ -152,7 +152,7 @@ } @Override - protected void onObservingDifferentTab(Tab tab) { + protected void onObservingDifferentTab(Tab tab, boolean hint) { mCurrentTab = tab; mShouldUpdateStatusBarColorForNTP = isStandardNTP();
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/ActivityTabProviderTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/ActivityTabProviderTest.java index 0d16cd1..00bfdc3 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/ActivityTabProviderTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/ActivityTabProviderTest.java
@@ -58,7 +58,7 @@ } @Override - public void onObservingDifferentTab(Tab tab) { + public void onObservingDifferentTab(Tab tab, boolean hint) { mObservedTab = tab; mObserverMoveHelper.notifyCalled(); }
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/signin/AccountPickerBottomSheetTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/signin/AccountPickerBottomSheetTest.java index efb1f3f..4ef7fadc 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/signin/AccountPickerBottomSheetTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/signin/AccountPickerBottomSheetTest.java
@@ -36,7 +36,6 @@ import org.junit.ClassRule; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.RuleChain; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.mockito.Captor; @@ -46,12 +45,13 @@ import org.chromium.base.ThreadUtils; import org.chromium.base.test.util.CommandLineFlags; import org.chromium.chrome.R; +import org.chromium.chrome.browser.app.ChromeActivity; import org.chromium.chrome.browser.flags.ChromeFeatureList; import org.chromium.chrome.browser.flags.ChromeSwitches; import org.chromium.chrome.browser.signin.account_picker.AccountPickerBottomSheetCoordinator; import org.chromium.chrome.browser.signin.account_picker.AccountPickerDelegate; +import org.chromium.chrome.test.ChromeActivityTestRule; import org.chromium.chrome.test.ChromeJUnit4ClassRunner; -import org.chromium.chrome.test.ChromeTabbedActivityTestRule; import org.chromium.chrome.test.util.browser.Features; import org.chromium.chrome.test.util.browser.signin.AccountManagerTestRule; import org.chromium.components.browser_ui.bottomsheet.BottomSheetController; @@ -93,29 +93,25 @@ public static final DisableAnimationsTestRule sNoAnimationsRule = new DisableAnimationsTestRule(); - @Captor - public ArgumentCaptor<Callback<String>> callbackArgumentCaptor; - - private final ChromeTabbedActivityTestRule mActivityTestRule = - new ChromeTabbedActivityTestRule(); + @Rule + public final ChromeActivityTestRule<ChromeActivity> mActivityTestRule = + new ChromeActivityTestRule<>(ChromeActivity.class); private final CustomFakeProfileDataSource mFakeProfileDataSource = new CustomFakeProfileDataSource(); - private final AccountManagerTestRule mAccountManagerTestRule = - new AccountManagerTestRule(mFakeProfileDataSource); - - private AccountPickerBottomSheetCoordinator mCoordinator; - - // Destroys the mock AccountManagerFacade in the end as ChromeActivity may needs - // to unregister observers in the stub. @Rule - public final RuleChain mRuleChain = - RuleChain.outerRule(mAccountManagerTestRule).around(mActivityTestRule); + public final AccountManagerTestRule mAccountManagerTestRule = + new AccountManagerTestRule(mFakeProfileDataSource); @Mock private AccountPickerDelegate mAccountPickerDelegateMock; + @Captor + public ArgumentCaptor<Callback<String>> callbackArgumentCaptor; + + private AccountPickerBottomSheetCoordinator mCoordinator; + @Before public void setUp() { initMocks(this);
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/signin/IdentityManagerIntegrationTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/signin/IdentityManagerIntegrationTest.java index 90226a7..fa7eda9 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/signin/IdentityManagerIntegrationTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/signin/IdentityManagerIntegrationTest.java
@@ -16,8 +16,6 @@ import org.chromium.base.test.BaseJUnit4ClassRunner; import org.chromium.chrome.browser.profiles.Profile; import org.chromium.chrome.test.util.browser.signin.AccountManagerTestRule; -import org.chromium.components.signin.AccountManagerFacadeProvider; -import org.chromium.components.signin.base.CoreAccountId; import org.chromium.components.signin.base.CoreAccountInfo; import org.chromium.components.signin.identitymanager.IdentityManager; import org.chromium.components.signin.identitymanager.IdentityMutator; @@ -48,8 +46,8 @@ @Before public void setUp() { - mTestAccount1 = createCoreAccountInfoFromEmail(TEST_ACCOUNT1); - mTestAccount2 = createCoreAccountInfoFromEmail(TEST_ACCOUNT2); + mTestAccount1 = mAccountManagerTestRule.toCoreAccountInfo(TEST_ACCOUNT1); + mTestAccount2 = mAccountManagerTestRule.toCoreAccountInfo(TEST_ACCOUNT2); NativeLibraryTestUtils.loadNativeLibraryAndInitBrowserProcess(); @@ -62,12 +60,6 @@ }); } - private static CoreAccountInfo createCoreAccountInfoFromEmail(String accountEmail) { - String accountGaiaId = - AccountManagerFacadeProvider.getInstance().getAccountGaiaId(accountEmail); - return new CoreAccountInfo(new CoreAccountId(accountGaiaId), accountEmail, accountGaiaId); - } - @After public void tearDown() { TestThreadUtils.runOnUiThreadBlocking(
diff --git a/chrome/browser/about_flags.cc b/chrome/browser/about_flags.cc index 19f41b8..02119ab 100644 --- a/chrome/browser/about_flags.cc +++ b/chrome/browser/about_flags.cc
@@ -3978,6 +3978,11 @@ {"handwriting-gesture", flag_descriptions::kHandwritingGestureName, flag_descriptions::kHandwritingGestureDescription, kOsCrOS, FEATURE_VALUE_TYPE(features::kHandwritingGesture)}, + + {"handwriting-gesture-editing", + flag_descriptions::kHandwritingGestureEditingName, + flag_descriptions::kHandwritingGestureEditingDescription, kOsCrOS, + FEATURE_VALUE_TYPE(chromeos::features::kHandwritingGestureEditing)}, #endif // OS_CHROMEOS #if BUILDFLAG(ENABLE_EXTENSIONS) @@ -6344,6 +6349,11 @@ FEATURE_VALUE_TYPE(password_manager::features::kPasswordsWeaknessCheck)}, #endif // !defined(OS_ANDROID) + {"well-known-change-password", + flag_descriptions::kWellKnownChangePasswordName, + flag_descriptions::kWellKnownChangePasswordDescription, kOsAll, + FEATURE_VALUE_TYPE(password_manager::features::kWellKnownChangePassword)}, + // NOTE: Adding a new flag requires adding a corresponding entry to enum // "LoginCustomFlags" in tools/metrics/histograms/enums.xml. See "Flag // Histograms" in tools/metrics/histograms/README.md (run the
diff --git a/chrome/browser/android/autofill_assistant/client_android.cc b/chrome/browser/android/autofill_assistant/client_android.cc index 7f4db6b..8c5bfda 100644 --- a/chrome/browser/android/autofill_assistant/client_android.cc +++ b/chrome/browser/android/autofill_assistant/client_android.cc
@@ -587,12 +587,19 @@ } void ClientAndroid::CreateController(std::unique_ptr<Service> service) { + if (controller_) { + DestroyController(); + } controller_ = std::make_unique<Controller>( web_contents_, /* client= */ this, base::DefaultTickClock::GetInstance(), std::move(service)); } void ClientAndroid::DestroyController() { + if (controller_ && ui_controller_android_ && + ui_controller_android_->IsAttachedTo(controller_.get())) { + ui_controller_android_->Detach(); + } controller_.reset(); started_ = false; }
diff --git a/chrome/browser/android/autofill_assistant/ui_controller_android.cc b/chrome/browser/android/autofill_assistant/ui_controller_android.cc index ed485f8..8964ade 100644 --- a/chrome/browser/android/autofill_assistant/ui_controller_android.cc +++ b/chrome/browser/android/autofill_assistant/ui_controller_android.cc
@@ -315,8 +315,7 @@ client_ = client; // Detach from the current ui_delegate, if one was set previously. - if (ui_delegate_) - ui_delegate_->RemoveObserver(this); + Detach(); // Attach to the new ui_delegate. ui_delegate_ = ui_delegate; @@ -385,12 +384,17 @@ SetVisible(true); } +void UiControllerAndroid::Detach() { + if (ui_delegate_) { + ui_delegate_->RemoveObserver(this); + } + ui_delegate_ = nullptr; +} + UiControllerAndroid::~UiControllerAndroid() { Java_AutofillAssistantUiController_clearNativePtr(AttachCurrentThread(), java_object_); - - if (ui_delegate_) - ui_delegate_->RemoveObserver(this); + Detach(); } base::android::ScopedJavaLocalRef<jobject> UiControllerAndroid::GetModel() {
diff --git a/chrome/browser/android/autofill_assistant/ui_controller_android.h b/chrome/browser/android/autofill_assistant/ui_controller_android.h index fbd6ec3f..efc3cc8 100644 --- a/chrome/browser/android/autofill_assistant/ui_controller_android.h +++ b/chrome/browser/android/autofill_assistant/ui_controller_android.h
@@ -66,6 +66,10 @@ Client* client, UiDelegate* ui_delegate); + // Detaches the UI from |ui_delegate_|. It will stop receiving notifications + // from the delegate until it is attached again. + void Detach(); + // Returns true if the UI is attached to a delegate. bool IsAttached() { return ui_delegate_ != nullptr; }
diff --git a/chrome/browser/apps/app_service/app_icon_factory.cc b/chrome/browser/apps/app_service/app_icon_factory.cc index 9fe6c4fd..bfe59640 100644 --- a/chrome/browser/apps/app_service/app_icon_factory.cc +++ b/chrome/browser/apps/app_service/app_icon_factory.cc
@@ -689,6 +689,13 @@ void IconLoadingPipeline::LoadIconFromCompressedData( const std::string& compressed_icon_data) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); + + // For the compressed icon, MaybeApplyEffectsAndComplete() uses + // |icon_scale_for_compressed_response_| to apps::EncodeImageToPngBytes(). So + // set |icon_scale_for_compressed_response_| to match |icon_scale_|, which is + // used to decode the icon. + icon_scale_for_compressed_response_ = icon_scale_; + std::vector<uint8_t> data(compressed_icon_data.begin(), compressed_icon_data.end()); apps::CompressedDataToImageSkiaCallback(
diff --git a/chrome/browser/browsing_data/access_context_audit_service.cc b/chrome/browser/browsing_data/access_context_audit_service.cc index 42f99741..fd2983b 100644 --- a/chrome/browser/browsing_data/access_context_audit_service.cc +++ b/chrome/browser/browsing_data/access_context_audit_service.cc
@@ -55,6 +55,10 @@ void AccessContextAuditService::RecordCookieAccess( const net::CookieList& accessed_cookies, const url::Origin& top_frame_origin) { + // Opaque top frame origins are not supported. + if (top_frame_origin.opaque()) + return; + auto now = clock_->Now(); std::vector<AccessContextAuditDatabase::AccessRecord> access_records; for (const auto& cookie : accessed_cookies) { @@ -76,6 +80,11 @@ const url::Origin& storage_origin, AccessContextAuditDatabase::StorageAPIType type, const url::Origin& top_frame_origin) { + // Opaque top frame origins are not supported. + if (top_frame_origin.opaque()) + return; + DCHECK(!storage_origin.opaque()); + std::vector<AccessContextAuditDatabase::AccessRecord> access_record = { AccessContextAuditDatabase::AccessRecord(top_frame_origin, type, storage_origin, clock_->Now())};
diff --git a/chrome/browser/browsing_data/access_context_audit_service_unittest.cc b/chrome/browser/browsing_data/access_context_audit_service_unittest.cc index 4454af1a..5e10d1c 100644 --- a/chrome/browser/browsing_data/access_context_audit_service_unittest.cc +++ b/chrome/browser/browsing_data/access_context_audit_service_unittest.cc
@@ -633,3 +633,17 @@ records = GetAllAccessRecords(); ASSERT_EQ(0U, records.size()); } + +TEST_F(AccessContextAuditServiceTest, OpaqueOrigins) { + // Check that records which have opaque top frame origins are not recorded. + auto test_cookie = net::CanonicalCookie::Create( + GURL("https://example.com"), "test_1=1; max-age=3600", base::Time::Now(), + base::nullopt /* server_time */); + service()->RecordCookieAccess({*test_cookie}, url::Origin()); + service()->RecordStorageAPIAccess( + url::Origin::Create(GURL("https://example.com")), + AccessContextAuditDatabase::StorageAPIType::kWebDatabase, url::Origin()); + + auto records = GetAllAccessRecords(); + ASSERT_EQ(0U, records.size()); +}
diff --git a/chrome/browser/chromeos/file_manager/web_file_tasks.cc b/chrome/browser/chromeos/file_manager/web_file_tasks.cc index e525d12..2b4e8e8 100644 --- a/chrome/browser/chromeos/file_manager/web_file_tasks.cc +++ b/chrome/browser/chromeos/file_manager/web_file_tasks.cc
@@ -146,9 +146,11 @@ // launched (ie. default handler to open a download from its // notification) from Incognito mode. Use the base profile in these // cases (see crbug.com/1111695). - if (profile->IsOffTheRecord()) { + if (!apps::AppServiceProxyFactory::IsAppServiceAvailableForProfile(profile)) { profile = profile->GetOriginalProfile(); } + DCHECK( + apps::AppServiceProxyFactory::IsAppServiceAvailableForProfile(profile)); apps::AppServiceProxy* proxy = apps::AppServiceProxyFactory::GetForProfile(profile);
diff --git a/chrome/browser/chromeos/guest_os/guest_os_registry_service.cc b/chrome/browser/chromeos/guest_os/guest_os_registry_service.cc index 89b749e0..7f1334c 100644 --- a/chrome/browser/chromeos/guest_os/guest_os_registry_service.cc +++ b/chrome/browser/chromeos/guest_os/guest_os_registry_service.cc
@@ -679,16 +679,6 @@ std::move(callback).Run({}); return; } - // First check to see if this request is in the retry list. If so return - // immediately with an empty icon. - const auto retry_iter = retry_icon_requests_.find(app_id); - if (retry_iter != retry_icon_requests_.end()) { - if (retry_iter->second & (1 << scale_factor)) { - // Icon request already setup to be retried when we are active. - std::move(callback).Run({}); - return; - } - } // Coalesce calls to the container. auto& callbacks = active_icon_requests_[{app_id, scale_factor}];
diff --git a/chrome/browser/chromeos/input_method/ui/undo_window.cc b/chrome/browser/chromeos/input_method/ui/undo_window.cc index 37d977d3..4b7d0dd 100644 --- a/chrome/browser/chromeos/input_method/ui/undo_window.cc +++ b/chrome/browser/chromeos/input_method/ui/undo_window.cc
@@ -32,6 +32,7 @@ set_parent_window(parent); set_margins(gfx::Insets()); + SetArrow(views::BubbleBorder::Arrow::BOTTOM_LEFT); SetLayoutManager(std::make_unique<views::BoxLayout>( views::BoxLayout::Orientation::kHorizontal)); AddUndoButton();
diff --git a/chrome/browser/chromeos/login/screens/family_link_notice_screen.cc b/chrome/browser/chromeos/login/screens/family_link_notice_screen.cc index ea8d0a3..8215cc4 100644 --- a/chrome/browser/chromeos/login/screens/family_link_notice_screen.cc +++ b/chrome/browser/chromeos/login/screens/family_link_notice_screen.cc
@@ -4,15 +4,13 @@ #include "chrome/browser/chromeos/login/screens/family_link_notice_screen.h" -#include "chrome/browser/browser_process.h" -#include "chrome/browser/browser_process_platform_part.h" #include "chrome/browser/chromeos/login/wizard_context.h" -#include "chrome/browser/chromeos/policy/browser_policy_connector_chromeos.h" #include "chrome/browser/policy/profile_policy_connector.h" #include "chrome/browser/profiles/profile_manager.h" #include "chrome/browser/ui/webui/chromeos/login/family_link_notice_screen_handler.h" #include "chromeos/constants/chromeos_features.h" #include "components/user_manager/user_manager.h" +#include "google_apis/gaia/gaia_auth_util.h" namespace { constexpr char kUserActionContinue[] = "continue"; @@ -64,11 +62,10 @@ Profile* profile = ProfileManager::GetActiveUserProfile(); if (profile->GetProfilePolicyConnector()->IsManaged() && !profile->IsChild()) { - policy::BrowserPolicyConnectorChromeOS* connector = - g_browser_process->platform_part()->browser_policy_connector_chromeos(); - view_->SetDomain(connector->GetEnterpriseDisplayDomain()); - view_->SetDisplayEmail( - user_manager::UserManager::Get()->GetActiveUser()->GetDisplayEmail()); + std::string display_email = + user_manager::UserManager::Get()->GetActiveUser()->GetDisplayEmail(); + view_->SetDisplayEmail(display_email); + view_->SetDomain(gaia::ExtractDomainName(display_email)); } else { view_->SetIsNewGaiaAccount(context()->is_child_gaia_account_new); }
diff --git a/chrome/browser/chromeos/login/test/device_state_mixin.cc b/chrome/browser/chromeos/login/test/device_state_mixin.cc index c7256d2..add0dc9 100644 --- a/chrome/browser/chromeos/login/test/device_state_mixin.cc +++ b/chrome/browser/chromeos/login/test/device_state_mixin.cc
@@ -110,11 +110,15 @@ case DeviceStateMixin::State::OOBE_COMPLETED_ACTIVE_DIRECTORY_ENROLLED: case DeviceStateMixin::State::OOBE_COMPLETED_CONSUMER_OWNED: case DeviceStateMixin::State::OOBE_COMPLETED_DEMO_MODE: - case DeviceStateMixin::State::OOBE_COMPLETED_UNOWNED: local_state->SetBoolean(prefs::kOobeComplete, true); local_state->SetInteger(prefs::kDeviceRegistered, 1); local_state->SetBoolean(prefs::kEnrollmentRecoveryRequired, false); break; + case DeviceStateMixin::State::OOBE_COMPLETED_UNOWNED: + local_state->SetBoolean(prefs::kOobeComplete, true); + local_state->SetInteger(prefs::kDeviceRegistered, 0); + local_state->SetBoolean(prefs::kEnrollmentRecoveryRequired, false); + break; case DeviceStateMixin::State::BEFORE_OOBE: local_state->SetInteger(prefs::kDeviceRegistered, 0); break;
diff --git a/chrome/browser/component_updater/cros_component_installer_chromeos.cc b/chrome/browser/component_updater/cros_component_installer_chromeos.cc index 2d8510a..db8d99f4 100644 --- a/chrome/browser/component_updater/cros_component_installer_chromeos.cc +++ b/chrome/browser/component_updater/cros_component_installer_chromeos.cc
@@ -36,7 +36,7 @@ const ComponentConfig kConfigs[] = { {"epson-inkjet-printer-escpr", "5.0", "1913a5e0a6cad30b6f03e176177e0d7ed62c5d6700a9c66da556d7c3f5d6a47e"}, - {"cros-termina", "860.1", + {"cros-termina", "870.1", "e9d960f84f628e1f42d05de4046bb5b3154b6f1f65c08412c6af57a29aecaffb"}, {"rtanalytics-light", "84.0", "69f09d33c439c2ab55bbbe24b47ab55cb3f6c0bd1f1ef46eefea3216ec925038"},
diff --git a/chrome/browser/devtools/devtools_ui_bindings.cc b/chrome/browser/devtools/devtools_ui_bindings.cc index 36fa728c..1835d03 100644 --- a/chrome/browser/devtools/devtools_ui_bindings.cc +++ b/chrome/browser/devtools/devtools_ui_bindings.cc
@@ -113,7 +113,7 @@ static const char kDevtoolsGridSettingChangedHistogram[] = "DevTools.GridSettingChanged"; static const char kDevtoolsCSSGridSettingsHistogram[] = - "DevTools.CSSGridSettings"; + "DevTools.CSSGridSettings2"; static const char kDevtoolsExperimentEnabledHistogram[] = "DevTools.ExperimentEnabled"; static const char kDevtoolsExperimentDisabledHistogram[] =
diff --git a/chrome/browser/extensions/api/virtual_keyboard_private/chrome_virtual_keyboard_delegate.cc b/chrome/browser/extensions/api/virtual_keyboard_private/chrome_virtual_keyboard_delegate.cc index dccb0b2..49700b2b 100644 --- a/chrome/browser/extensions/api/virtual_keyboard_private/chrome_virtual_keyboard_delegate.cc +++ b/chrome/browser/extensions/api/virtual_keyboard_private/chrome_virtual_keyboard_delegate.cc
@@ -392,6 +392,10 @@ features->AppendString(GenerateFeatureFlag( "handwritinggesture", base::FeatureList::IsEnabled(features::kHandwritingGesture))); + features->AppendString( + GenerateFeatureFlag("handwritinggestureediting", + base::FeatureList::IsEnabled( + chromeos::features::kHandwritingGestureEditing))); features->AppendString(GenerateFeatureFlag( "floatingkeyboarddefault", base::FeatureList::IsEnabled(
diff --git a/chrome/browser/extensions/execute_script_apitest.cc b/chrome/browser/extensions/execute_script_apitest.cc index d574758..6526f7b 100644 --- a/chrome/browser/extensions/execute_script_apitest.cc +++ b/chrome/browser/extensions/execute_script_apitest.cc
@@ -31,10 +31,7 @@ class ExecuteScriptApiTest : public ExecuteScriptApiTestBase, public testing::WithParamInterface<ContextType> { protected: - void SetUp() override { - ExecuteScriptApiTestBase::SetUp(); - // Service Workers are currently only available on certain channels, so set - // the channel for those tests. + ExecuteScriptApiTest() { if (GetParam() == ContextType::kServiceWorker) current_channel_ = std::make_unique<ScopedWorkerBasedExtensionsChannel>(); }
diff --git a/chrome/browser/flag-metadata.json b/chrome/browser/flag-metadata.json index 3a1513f2..7f87b19e 100644 --- a/chrome/browser/flag-metadata.json +++ b/chrome/browser/flag-metadata.json
@@ -669,7 +669,7 @@ { "name": "cross-origin-isolated", "owners": [ "ahemery", "arthursonzogni", "clamy", "pmeuleman" ], - "expiry_milestone": 86 + "expiry_milestone": 88 }, { "name": "cross-origin-opener-policy", @@ -679,12 +679,12 @@ { "name": "cross-origin-opener-policy-access-reporting", "owners": [ "ahemery", "arthursonzogni", "clamy", "pmeuleman" ], - "expiry_milestone": 86 + "expiry_milestone": 88 }, { "name": "cross-origin-opener-policy-reporting", "owners": [ "ahemery", "arthursonzogni", "clamy", "pmeuleman" ], - "expiry_milestone": 86 + "expiry_milestone": 88 }, { "name": "crostini-disk-resizing", @@ -2689,6 +2689,11 @@ "expiry_milestone": 90 }, { + "name": "handwriting-gesture-editing", + "owners": [ "essential-inputs-team@google.com" ], + "expiry_milestone": 95 + }, + { "name": "happiness-tracking-surveys-for-desktop", "owners": [ "//chrome/browser/ui/hats/OWNERS" ], "expiry_milestone": 84 @@ -4579,6 +4584,11 @@ "expiry_milestone": -1 }, { + "name": "well-known-change-password", + "owners": ["jdoerrie", "vasilii"], + "expiry_milestone": 87 + }, + { "name": "wifi-sync-android", "owners": [ "jonmann", "cvandermerwe@google.com", "cros-system-services@google.com" ], "expiry_milestone": 92
diff --git a/chrome/browser/flag_descriptions.cc b/chrome/browser/flag_descriptions.cc index efca5ff..8a158ccd 100644 --- a/chrome/browser/flag_descriptions.cc +++ b/chrome/browser/flag_descriptions.cc
@@ -1224,6 +1224,10 @@ "handwriting you write inside the virtual keyboard to Google servers for " "recognition but will not be associated with your Google account."; +const char kHandwritingGestureEditingName[] = "Handwriting Gestures Editing"; +const char kHandwritingGestureEditingDescription[] = + "Enables editing with handwriting gestures within the virtual keyboard."; + const char kHardwareMediaKeyHandling[] = "Hardware Media Key Handling"; const char kHardwareMediaKeyHandlingDescription[] = "Enables using media keys to control the active media session. This " @@ -2528,6 +2532,16 @@ const char kWebXrMultiGpuDescription[] = "Improves WebXR support for computers with more than one GPU."; +const char kWellKnownChangePasswordName[] = + "Support for .well-known/change-password"; + +const char kWellKnownChangePasswordDescription[] = + "If enabled the 'change password' button in password checkup redirects to " + "the .well-known/change-password path. The path is supposed to point to " + "the password change form of the site. When the site doesn't support " + ".well-known/change-password it is checked if a fallback url is available. " + "Otherwise the user is redirected to the orgin."; + const char kZeroCopyName[] = "Zero-copy rasterizer"; const char kZeroCopyDescription[] = "Raster threads write directly to GPU memory associated with tiles.";
diff --git a/chrome/browser/flag_descriptions.h b/chrome/browser/flag_descriptions.h index 94ec43c..aaa27d2 100644 --- a/chrome/browser/flag_descriptions.h +++ b/chrome/browser/flag_descriptions.h
@@ -713,6 +713,9 @@ extern const char kHandwritingGestureName[]; extern const char kHandwritingGestureDescription[]; +extern const char kHandwritingGestureEditingName[]; +extern const char kHandwritingGestureEditingDescription[]; + extern const char kHardwareMediaKeyHandling[]; extern const char kHardwareMediaKeyHandlingDescription[]; @@ -1457,6 +1460,9 @@ extern const char kWebXrMultiGpuName[]; extern const char kWebXrMultiGpuDescription[]; +extern const char kWellKnownChangePasswordName[]; +extern const char kWellKnownChangePasswordDescription[]; + extern const char kZeroCopyName[]; extern const char kZeroCopyDescription[];
diff --git a/chrome/browser/nearby_sharing/client/nearby_share_client_impl.cc b/chrome/browser/nearby_sharing/client/nearby_share_client_impl.cc index 5133ef0..20ffb08 100644 --- a/chrome/browser/nearby_sharing/client/nearby_share_client_impl.cc +++ b/chrome/browser/nearby_sharing/client/nearby_share_client_impl.cc
@@ -36,10 +36,8 @@ const char kNearbyShareV1Path[] = "v1/"; const char kCheckContactsReachabilityPath[] = "contactsReachability:check"; -const char kListContactPeoplePathSeg1[] = "users/me/devices/"; -const char kListContactPeoplePathSeg2[] = "/contactRecords"; -const char kListPublicCertificatesPathSeg1[] = "users/me/devices/"; -const char kListPublicCertificatesPathSeg2[] = "/publicCertificates"; +const char kListContactPeoplePath[] = "contactRecords"; +const char kListPublicCertificatesPath[] = "publicCertificates"; const char kPageSize[] = "page_size"; const char kPageToken[] = "page_token"; @@ -259,10 +257,8 @@ ListContactPeopleCallback&& callback, ErrorCallback&& error_callback) { notifier_->NotifyOfRequest(request); - // TODO(cclem): Use correct identifier in URL - MakeApiCall(CreateV1RequestUrl(kListContactPeoplePathSeg1 + request.parent() + - kListContactPeoplePathSeg2), - RequestType::kGet, /*serialized_request=*/base::nullopt, + MakeApiCall(CreateV1RequestUrl(kListContactPeoplePath), RequestType::kGet, + /*serialized_request=*/base::nullopt, ListContactPeopleRequestToQueryParameters(request), std::move(callback), std::move(error_callback), GetContactsAnnotation()); @@ -273,10 +269,8 @@ ListPublicCertificatesCallback&& callback, ErrorCallback&& error_callback) { notifier_->NotifyOfRequest(request); - // TODO(cclem): Use correct identifier in URL MakeApiCall( - CreateV1RequestUrl(kListPublicCertificatesPathSeg1 + request.parent() + - kListPublicCertificatesPathSeg2), + CreateV1RequestUrl(request.parent() + "/" + kListPublicCertificatesPath), RequestType::kGet, /*serialized_request=*/base::nullopt, ListPublicCertificatesRequestToQueryParameters(request), std::move(callback), std::move(error_callback),
diff --git a/chrome/browser/nearby_sharing/client/nearby_share_client_impl_unittest.cc b/chrome/browser/nearby_sharing/client/nearby_share_client_impl_unittest.cc index 222bbf7..7b63aa0 100644 --- a/chrome/browser/nearby_sharing/client/nearby_share_client_impl_unittest.cc +++ b/chrome/browser/nearby_sharing/client/nearby_share_client_impl_unittest.cc
@@ -30,6 +30,7 @@ #include "url/gurl.h" namespace { + const char kGet[] = "GET"; const char kPost[] = "POST"; const char kPatch[] = "PATCH"; @@ -37,8 +38,7 @@ const char kAccountName1[] = "accountname1"; const char kContactId1[] = "contactid1"; const char kContactId2[] = "contactid2"; -const char kDeviceName1[] = "users/me/devices/devicename1"; -const char kDeviceParent1[] = "kdeviceparent1"; +const char kDeviceIdPath[] = "users/me/devices/deviceid"; const char kEmail[] = "test@gmail.com"; const char kEncryptedMetadataBytes1[] = "encryptedmetadatabytes1"; const char kImageUrl1[] = "https://example.com/image.jpg"; @@ -53,8 +53,7 @@ const char kSecretId1[] = "secretid1"; const char kSecretId2[] = "secretid2"; const char kSecretKey1[] = "secretkey1"; -const char kTestGoogleApisUrl[] = - "https://www.nearbysharing-pa.testgoogleapis.com"; +const char kTestGoogleApisUrl[] = "https://nearbysharing-pa.testgoogleapis.com"; const int32_t kNanos1 = 123123123; const int32_t kNanos2 = 321321321; const int32_t kPageSize1 = 1000; @@ -367,7 +366,7 @@ TEST_F(NearbyShareClientImplTest, UpdateDeviceSuccess) { nearbyshare::proto::UpdateDeviceResponse result_proto; nearbyshare::proto::UpdateDeviceRequest request_proto; - request_proto.mutable_device()->set_name(kDeviceName1); + request_proto.mutable_device()->set_name(kDeviceIdPath); client_->UpdateDevice( request_proto, base::BindOnce( @@ -382,16 +381,16 @@ EXPECT_EQ(kPatch, http_method()); EXPECT_EQ(request_url(), GURL(std::string(kTestGoogleApisUrl) + "/v1/" + - std::string(kDeviceName1))); + std::string(kDeviceIdPath))); nearbyshare::proto::UpdateDeviceRequest expected_request; EXPECT_TRUE(expected_request.ParseFromString(serialized_request())); - EXPECT_EQ(kDeviceName1, expected_request.device().name()); + EXPECT_EQ(kDeviceIdPath, expected_request.device().name()); nearbyshare::proto::UpdateDeviceResponse response_proto; nearbyshare::proto::Device& device = *response_proto.mutable_device(); - device.set_name(kDeviceName1); + device.set_name(kDeviceIdPath); device.add_contacts(); device.mutable_contacts(0)->mutable_identifier()->set_phone_number( kPhoneNumber1); @@ -426,7 +425,7 @@ TEST_F(NearbyShareClientImplTest, UpdateDeviceFailure) { nearbyshare::proto::UpdateDeviceRequest request; - request.mutable_device()->set_name(kDeviceName1); + request.mutable_device()->set_name(kDeviceIdPath); NearbyShareHttpError error; client_->UpdateDevice( @@ -440,7 +439,7 @@ EXPECT_EQ(kPatch, http_method()); EXPECT_EQ(request_url(), GURL(std::string(kTestGoogleApisUrl) + "/v1/" + - std::string(kDeviceName1))); + std::string(kDeviceIdPath))); FailApiCallFlow(NearbyShareHttpError::kInternalServerError); EXPECT_EQ(NearbyShareHttpError::kInternalServerError, error); @@ -519,7 +518,6 @@ TEST_F(NearbyShareClientImplTest, ListContactPeopleSuccess) { nearbyshare::proto::ListContactPeopleResponse result_proto; nearbyshare::proto::ListContactPeopleRequest request_proto; - request_proto.set_parent(kDeviceParent1); request_proto.set_page_size(kPageSize1); request_proto.set_page_token(kPageToken1); @@ -536,9 +534,8 @@ VerifyRequestNotification(request_proto); EXPECT_EQ(kGet, http_method()); - EXPECT_EQ(request_url(), std::string(kTestGoogleApisUrl) + - "/v1/users/me/devices/" + - std::string(kDeviceParent1) + "/contactRecords"); + EXPECT_EQ(request_url(), + std::string(kTestGoogleApisUrl) + "/v1/contactRecords"); EXPECT_EQ( std::vector<std::string>{base::NumberToString(kPageSize1)}, @@ -575,7 +572,7 @@ TEST_F(NearbyShareClientImplTest, ListPublicCertificatesSuccess) { nearbyshare::proto::ListPublicCertificatesResponse result_proto; nearbyshare::proto::ListPublicCertificatesRequest request_proto; - request_proto.set_parent(kDeviceParent1); + request_proto.set_parent(kDeviceIdPath); request_proto.set_page_size(kPageSize1); request_proto.set_page_token(kPageToken1); request_proto.add_secret_ids(); @@ -596,9 +593,9 @@ VerifyRequestNotification(request_proto); EXPECT_EQ(kGet, http_method()); - EXPECT_EQ(request_url(), - std::string(kTestGoogleApisUrl) + "/v1/users/me/devices/" + - std::string(kDeviceParent1) + "/publicCertificates"); + EXPECT_EQ(request_url(), std::string(kTestGoogleApisUrl) + "/v1/" + + std::string(kDeviceIdPath) + + "/publicCertificates"); EXPECT_EQ( std::vector<std::string>{base::NumberToString(kPageSize1)}, @@ -673,7 +670,7 @@ TEST_F(NearbyShareClientImplTest, ParseResponseProtoFailure) { nearbyshare::proto::UpdateDeviceRequest request_proto; - request_proto.mutable_device()->set_name(kDeviceName1); + request_proto.mutable_device()->set_name(kDeviceIdPath); NearbyShareHttpError error; client_->UpdateDevice( @@ -687,7 +684,7 @@ EXPECT_EQ(kPatch, http_method()); EXPECT_EQ(request_url(), std::string(kTestGoogleApisUrl) + "/v1/" + - std::string(kDeviceName1)); + std::string(kDeviceIdPath)); FinishApiCallFlowRaw("Not a valid serialized response message."); EXPECT_EQ(NearbyShareHttpError::kResponseMalformed, error); @@ -695,7 +692,7 @@ TEST_F(NearbyShareClientImplTest, MakeSecondRequestBeforeFirstRequestSucceeds) { nearbyshare::proto::UpdateDeviceRequest request_proto; - request_proto.mutable_device()->set_name(kDeviceName1); + request_proto.mutable_device()->set_name(kDeviceIdPath); // Make first request. nearbyshare::proto::UpdateDeviceResponse result_proto; @@ -711,7 +708,7 @@ EXPECT_EQ(kPatch, http_method()); EXPECT_EQ(request_url(), std::string(kTestGoogleApisUrl) + "/v1/" + - std::string(kDeviceName1)); + std::string(kDeviceIdPath)); // With request pending, make second request. { @@ -726,11 +723,11 @@ // Complete first request. { nearbyshare::proto::UpdateDeviceResponse response_proto; - response_proto.mutable_device()->set_name(kDeviceName1); + response_proto.mutable_device()->set_name(kDeviceIdPath); FinishApiCallFlow(&response_proto); } - EXPECT_EQ(kDeviceName1, result_proto.device().name()); + EXPECT_EQ(kDeviceIdPath, result_proto.device().name()); } TEST_F(NearbyShareClientImplTest, MakeSecondRequestAfterFirstRequestSucceeds) { @@ -738,7 +735,7 @@ { nearbyshare::proto::UpdateDeviceResponse result_proto; nearbyshare::proto::UpdateDeviceRequest request_proto; - request_proto.mutable_device()->set_name(kDeviceName1); + request_proto.mutable_device()->set_name(kDeviceIdPath); client_->UpdateDevice( request_proto, @@ -752,12 +749,12 @@ EXPECT_EQ(kPatch, http_method()); EXPECT_EQ(request_url(), std::string(kTestGoogleApisUrl) + "/v1/" + - std::string(kDeviceName1)); + std::string(kDeviceIdPath)); nearbyshare::proto::UpdateDeviceResponse response_proto; - response_proto.mutable_device()->set_name(kDeviceName1); + response_proto.mutable_device()->set_name(kDeviceIdPath); FinishApiCallFlow(&response_proto); - EXPECT_EQ(kDeviceName1, result_proto.device().name()); + EXPECT_EQ(kDeviceIdPath, result_proto.device().name()); } // Second request fails. @@ -776,7 +773,7 @@ nearbyshare::proto::UpdateDeviceResponse result_proto; nearbyshare::proto::UpdateDeviceRequest request_proto; - request_proto.mutable_device()->set_name(kDeviceName1); + request_proto.mutable_device()->set_name(kDeviceIdPath); client_->UpdateDevice( request_proto, @@ -790,7 +787,7 @@ EXPECT_EQ(kPatch, http_method()); EXPECT_EQ(request_url(), std::string(kTestGoogleApisUrl) + "/v1/" + - std::string(kDeviceName1)); + std::string(kDeviceIdPath)); EXPECT_EQ(kAccessToken, client_->GetAccessTokenUsed()); }
diff --git a/chrome/browser/nearby_sharing/common/nearby_share_prefs.cc b/chrome/browser/nearby_sharing/common/nearby_share_prefs.cc index 50f2e91..98d1f84 100644 --- a/chrome/browser/nearby_sharing/common/nearby_share_prefs.cc +++ b/chrome/browser/nearby_sharing/common/nearby_share_prefs.cc
@@ -28,6 +28,10 @@ const char kNearbySharingIconUrlPrefName[] = "nearby_sharing.icon_url"; const char kNearbySharingOnboardingDismissedTimePrefName[] = "nearby_sharing.onboarding_dismissed_time"; +const char kNearbySharingSchedulerContactDownloadPrefName[] = + "nearby_sharing.scheduler.contact_download"; +const char kNearbySharingSchedulerContactUploadPrefName[] = + "nearby_sharing.scheduler.contact_upload"; const char kNearbySharingSchedulerDownloadDeviceDataPrefName[] = "nearby_sharing.scheduler.download_device_data"; const char kNearbySharingSchedulerUploadDeviceNamePrefName[] = @@ -64,6 +68,10 @@ registry->RegisterStringPref(prefs::kNearbySharingIconUrlPrefName, /*default_value=*/std::string()); registry->RegisterDictionaryPref( + prefs::kNearbySharingSchedulerContactDownloadPrefName); + registry->RegisterDictionaryPref( + prefs::kNearbySharingSchedulerContactUploadPrefName); + registry->RegisterDictionaryPref( prefs::kNearbySharingSchedulerDownloadDeviceDataPrefName); registry->RegisterDictionaryPref( prefs::kNearbySharingSchedulerUploadDeviceNamePrefName);
diff --git a/chrome/browser/nearby_sharing/common/nearby_share_prefs.h b/chrome/browser/nearby_sharing/common/nearby_share_prefs.h index 0f9a465d..04ce8df 100644 --- a/chrome/browser/nearby_sharing/common/nearby_share_prefs.h +++ b/chrome/browser/nearby_sharing/common/nearby_share_prefs.h
@@ -19,6 +19,8 @@ extern const char kNearbySharingFullNamePrefName[]; extern const char kNearbySharingIconUrlPrefName[]; extern const char kNearbySharingOnboardingDismissedTimePrefName[]; +extern const char kNearbySharingSchedulerContactDownloadPrefName[]; +extern const char kNearbySharingSchedulerContactUploadPrefName[]; extern const char kNearbySharingSchedulerDownloadDeviceDataPrefName[]; extern const char kNearbySharingSchedulerUploadDeviceNamePrefName[]; extern const char kNearbySharingPublicCertificateExpirationDictPrefName[];
diff --git a/chrome/browser/nearby_sharing/contacts/BUILD.gn b/chrome/browser/nearby_sharing/contacts/BUILD.gn index 9dc0c66..7045e672 100644 --- a/chrome/browser/nearby_sharing/contacts/BUILD.gn +++ b/chrome/browser/nearby_sharing/contacts/BUILD.gn
@@ -18,8 +18,11 @@ "//base", "//chrome/browser/nearby_sharing/client", "//chrome/browser/nearby_sharing/common", + "//chrome/browser/nearby_sharing/local_device_data", "//chrome/browser/nearby_sharing/logging", "//chrome/browser/nearby_sharing/proto", + "//chrome/browser/nearby_sharing/scheduling", + "//components/prefs", ] } @@ -43,7 +46,10 @@ source_set("unit_tests") { testonly = true - sources = [ "nearby_share_contact_downloader_impl_unittest.cc" ] + sources = [ + "nearby_share_contact_downloader_impl_unittest.cc", + "nearby_share_contact_manager_impl_unittest.cc", + ] deps = [ ":contacts", @@ -53,7 +59,11 @@ "//chrome/browser/nearby_sharing/client", "//chrome/browser/nearby_sharing/client:test_support", "//chrome/browser/nearby_sharing/common", + "//chrome/browser/nearby_sharing/local_device_data:test_support", "//chrome/browser/nearby_sharing/proto", + "//chrome/browser/nearby_sharing/scheduling", + "//chrome/browser/nearby_sharing/scheduling:test_support", + "//components/sync_preferences:test_support", "//testing/gtest", ] }
diff --git a/chrome/browser/nearby_sharing/contacts/fake_nearby_share_contact_manager.cc b/chrome/browser/nearby_sharing/contacts/fake_nearby_share_contact_manager.cc index 94e8eb2..9e6e099 100644 --- a/chrome/browser/nearby_sharing/contacts/fake_nearby_share_contact_manager.cc +++ b/chrome/browser/nearby_sharing/contacts/fake_nearby_share_contact_manager.cc
@@ -9,7 +9,14 @@ FakeNearbyShareContactManager::Factory::~Factory() = default; std::unique_ptr<NearbyShareContactManager> -FakeNearbyShareContactManager::Factory::CreateInstance() { +FakeNearbyShareContactManager::Factory::CreateInstance( + PrefService* pref_service, + NearbyShareClientFactory* http_client_factory, + NearbyShareLocalDeviceDataManager* local_device_data_manager) { + latest_pref_service_ = pref_service; + latest_http_client_factory_ = http_client_factory; + latest_local_device_data_manager_ = local_device_data_manager; + auto instance = std::make_unique<FakeNearbyShareContactManager>(); instances_.push_back(instance.get());
diff --git a/chrome/browser/nearby_sharing/contacts/fake_nearby_share_contact_manager.h b/chrome/browser/nearby_sharing/contacts/fake_nearby_share_contact_manager.h index 02b3a988..9d17088b 100644 --- a/chrome/browser/nearby_sharing/contacts/fake_nearby_share_contact_manager.h +++ b/chrome/browser/nearby_sharing/contacts/fake_nearby_share_contact_manager.h
@@ -15,6 +15,10 @@ #include "chrome/browser/nearby_sharing/contacts/nearby_share_contact_manager_impl.h" #include "chrome/browser/nearby_sharing/proto/rpc_resources.pb.h" +class NearbyShareClientFactory; +class NearbyShareLocalDeviceDataManager; +class PrefService; + // A fake implementation of NearbyShareContactManager, along with a fake // factory, to be used in tests. Stores parameters input into // NearbyShareContactManager method calls. Use the notification methods from the @@ -37,11 +41,29 @@ return instances_; } + PrefService* latest_pref_service() const { return latest_pref_service_; } + + NearbyShareClientFactory* latest_http_client_factory() const { + return latest_http_client_factory_; + } + + NearbyShareLocalDeviceDataManager* latest_local_device_data_manager() + const { + return latest_local_device_data_manager_; + } + private: // NearbyShareContactManagerImpl::Factory: - std::unique_ptr<NearbyShareContactManager> CreateInstance() override; + std::unique_ptr<NearbyShareContactManager> CreateInstance( + PrefService* pref_service, + NearbyShareClientFactory* http_client_factory, + NearbyShareLocalDeviceDataManager* local_device_data_manager) override; std::vector<FakeNearbyShareContactManager*> instances_; + PrefService* latest_pref_service_ = nullptr; + NearbyShareClientFactory* latest_http_client_factory_ = nullptr; + NearbyShareLocalDeviceDataManager* latest_local_device_data_manager_ = + nullptr; }; FakeNearbyShareContactManager();
diff --git a/chrome/browser/nearby_sharing/contacts/nearby_share_contact_downloader_impl.cc b/chrome/browser/nearby_sharing/contacts/nearby_share_contact_downloader_impl.cc index 2888f1d..fe3d61bb 100644 --- a/chrome/browser/nearby_sharing/contacts/nearby_share_contact_downloader_impl.cc +++ b/chrome/browser/nearby_sharing/contacts/nearby_share_contact_downloader_impl.cc
@@ -13,8 +13,6 @@ namespace { -const char kDeviceIdPrefix[] = "users/me/devices/"; - void RecordContactChangeCheckResultMetrics(NearbyShareHttpResult result) { // TODO(https://crbug.com/1105579): Record a histogram value for each result. } @@ -149,7 +147,6 @@ base::Unretained(this))); nearbyshare::proto::ListContactPeopleRequest request; - request.set_parent(kDeviceIdPrefix + device_id()); if (next_page_token) request.set_page_token(*next_page_token);
diff --git a/chrome/browser/nearby_sharing/contacts/nearby_share_contact_downloader_impl_unittest.cc b/chrome/browser/nearby_sharing/contacts/nearby_share_contact_downloader_impl_unittest.cc index f9aacb5..afa69bff 100644 --- a/chrome/browser/nearby_sharing/contacts/nearby_share_contact_downloader_impl_unittest.cc +++ b/chrome/browser/nearby_sharing/contacts/nearby_share_contact_downloader_impl_unittest.cc
@@ -20,7 +20,6 @@ namespace { -const char kDeviceIdPrefix[] = "users/me/devices/"; const char kTestDeviceId[] = "test_device_id"; const char kTestContactRecordId1[] = "contact_id_1"; const char kTestContactRecordId2[] = "contact_id_2"; @@ -150,7 +149,6 @@ const nearbyshare::proto::ListContactPeopleRequest& request = client->list_contact_people_requests()[0].request; - EXPECT_EQ(std::string(kDeviceIdPrefix) + kTestDeviceId, request.parent()); EXPECT_EQ(expected_page_token.value_or(std::string()), request.page_token()); }
diff --git a/chrome/browser/nearby_sharing/contacts/nearby_share_contact_manager_impl.cc b/chrome/browser/nearby_sharing/contacts/nearby_share_contact_manager_impl.cc index 34df7ba..56211c48 100644 --- a/chrome/browser/nearby_sharing/contacts/nearby_share_contact_manager_impl.cc +++ b/chrome/browser/nearby_sharing/contacts/nearby_share_contact_manager_impl.cc
@@ -4,8 +4,59 @@ #include "chrome/browser/nearby_sharing/contacts/nearby_share_contact_manager_impl.h" +#include <algorithm> + #include "base/memory/ptr_util.h" -#include "base/notreached.h" +#include "base/stl_util.h" +#include "base/time/time.h" +#include "chrome/browser/nearby_sharing/common/nearby_share_prefs.h" +#include "chrome/browser/nearby_sharing/contacts/nearby_share_contact_downloader.h" +#include "chrome/browser/nearby_sharing/contacts/nearby_share_contact_downloader_impl.h" +#include "chrome/browser/nearby_sharing/local_device_data/nearby_share_local_device_data_manager.h" +#include "chrome/browser/nearby_sharing/proto/device_rpc.pb.h" +#include "chrome/browser/nearby_sharing/proto/rpc_resources.pb.h" +#include "chrome/browser/nearby_sharing/scheduling/nearby_share_scheduler.h" +#include "chrome/browser/nearby_sharing/scheduling/nearby_share_scheduler_factory.h" +#include "components/prefs/pref_service.h" + +namespace { + +constexpr base::TimeDelta kContactDownloadPeriod = + base::TimeDelta::FromHours(1); +constexpr base::TimeDelta kContactDownloadRpcTimeout = + base::TimeDelta::FromSeconds(60); + +// Removes contact IDs from the allowlist if they are not in |contacts|. +std::set<std::string> RemoveNonexistentContactsFromAllowlist( + const std::set<std::string>& allowed_contact_ids, + const std::vector<nearbyshare::proto::ContactRecord>& contacts) { + std::set<std::string> new_allowed_contact_ids; + for (const nearbyshare::proto::ContactRecord& contact : contacts) { + if (base::Contains(allowed_contact_ids, contact.id())) + new_allowed_contact_ids.insert(contact.id()); + } + return new_allowed_contact_ids; +} + +// Converts a list of ContactRecord protos, along with the allowlist, into a +// list of Contact protos. +std::vector<nearbyshare::proto::Contact> ContactRecordsToContacts( + const std::set<std::string>& allowed_contact_ids, + const std::vector<nearbyshare::proto::ContactRecord>& contact_records) { + std::vector<nearbyshare::proto::Contact> contacts; + for (const auto& contact_record : contact_records) { + bool is_selected = base::Contains(allowed_contact_ids, contact_record.id()); + for (const auto& identifier : contact_record.identifiers()) { + nearbyshare::proto::Contact contact; + contact.mutable_identifier()->CopyFrom(identifier); + contact.set_is_selected(is_selected); + contacts.push_back(contact); + } + } + return contacts; +} + +} // namespace // static NearbyShareContactManagerImpl::Factory* @@ -13,12 +64,16 @@ // static std::unique_ptr<NearbyShareContactManager> -NearbyShareContactManagerImpl::Factory::Create() { +NearbyShareContactManagerImpl::Factory::Create( + PrefService* pref_service, + NearbyShareClientFactory* http_client_factory, + NearbyShareLocalDeviceDataManager* local_device_data_manager) { if (test_factory_) { - return test_factory_->CreateInstance(); + return test_factory_->CreateInstance(pref_service, http_client_factory, + local_device_data_manager); } - - return base::WrapUnique(new NearbyShareContactManagerImpl()); + return base::WrapUnique(new NearbyShareContactManagerImpl( + pref_service, http_client_factory, local_device_data_manager)); } // static @@ -29,24 +84,188 @@ NearbyShareContactManagerImpl::Factory::~Factory() = default; -NearbyShareContactManagerImpl::NearbyShareContactManagerImpl() = default; +NearbyShareContactManagerImpl::NearbyShareContactManagerImpl( + PrefService* pref_service, + NearbyShareClientFactory* http_client_factory, + NearbyShareLocalDeviceDataManager* local_device_data_manager) + : pref_service_(pref_service), + http_client_factory_(http_client_factory), + local_device_data_manager_(local_device_data_manager), + contact_download_scheduler_( + NearbyShareSchedulerFactory::CreatePeriodicScheduler( + kContactDownloadPeriod, + /*retry_failures=*/true, + /*require_connectivity=*/true, + prefs::kNearbySharingSchedulerContactDownloadPrefName, + pref_service_, + base::BindRepeating( + &NearbyShareContactManagerImpl::OnContactsDownloadRequested, + base::Unretained(this)))), + contact_upload_scheduler_( + NearbyShareSchedulerFactory::CreateOnDemandScheduler( + /*retry_failures=*/true, + /*require_connectivity=*/true, + prefs::kNearbySharingSchedulerContactUploadPrefName, + pref_service_, + base::BindRepeating( + &NearbyShareContactManagerImpl::OnContactsUploadRequested, + base::Unretained(this)))) {} NearbyShareContactManagerImpl::~NearbyShareContactManagerImpl() = default; void NearbyShareContactManagerImpl::DownloadContacts( bool only_download_if_changed) { - NOTIMPLEMENTED(); + // A request for a full download always takes priority. + if (!only_download_if_changed) + only_download_if_changed_ = false; + + contact_download_scheduler_->MakeImmediateRequest(); } void NearbyShareContactManagerImpl::SetAllowedContacts( const std::set<std::string>& allowed_contact_ids) { - NOTIMPLEMENTED(); + // If the allowlist changed, re-upload contacts to Nearby server. + if (SetAllowlist(allowed_contact_ids)) + contact_upload_scheduler_->MakeImmediateRequest(); } void NearbyShareContactManagerImpl::OnStart() { - NOTIMPLEMENTED(); + contact_download_scheduler_->Start(); + contact_upload_scheduler_->Start(); } void NearbyShareContactManagerImpl::OnStop() { - NOTIMPLEMENTED(); + contact_download_scheduler_->Stop(); + contact_upload_scheduler_->Stop(); +} + +std::set<std::string> NearbyShareContactManagerImpl::GetAllowedContacts() + const { + std::set<std::string> allowlist; + for (const base::Value& id : + pref_service_->Get(prefs::kNearbySharingAllowedContactsPrefName) + ->GetList()) { + allowlist.insert(id.GetString()); + } + return allowlist; +} + +void NearbyShareContactManagerImpl::OnContactsDownloadRequested() { + DCHECK(!contact_downloader_); + contact_downloader_ = NearbyShareContactDownloaderImpl::Factory::Create( + only_download_if_changed_, local_device_data_manager_->GetId(), + kContactDownloadRpcTimeout, http_client_factory_, + base::BindOnce(&NearbyShareContactManagerImpl::OnContactsDownloadSuccess, + base::Unretained(this)), + base::BindOnce(&NearbyShareContactManagerImpl::OnContactsDownloadFailure, + base::Unretained(this))); + contact_downloader_->Run(); +} + +void NearbyShareContactManagerImpl::OnContactsDownloadSuccess( + bool did_contacts_change_since_last_upload, + base::Optional<std::vector<nearbyshare::proto::ContactRecord>> contacts) { + contact_downloader_.reset(); + + if (contacts) { + // A complete list of contacts was returned. Do not download list again + // until contacts change or until explicitly requested. + only_download_if_changed_ = true; + + // Remove contacts from the allowlist that are no longer in the contact + // list. + bool did_allowlist_change = + SetAllowlist(RemoveNonexistentContactsFromAllowlist( + GetAllowedContacts(), *contacts)); + + // Notify observers that the contact list was downloaded. + NotifyContactsDownloaded(GetAllowedContacts(), *contacts); + + // Request a contacts upload if needed, or process an existing upload + // request now that we have the access to the full contacts list. + switch (upload_state_) { + case UploadState::kIdle: + if (did_contacts_change_since_last_upload || did_allowlist_change) { + contact_upload_scheduler_->MakeImmediateRequest(); + } + break; + case UploadState::kWaitingForDownload: + StartContactsUpload(did_contacts_change_since_last_upload, *contacts); + break; + case UploadState::kInProgress: + // The current upload has a stale allowlist; request another upload. + if (did_allowlist_change) { + contact_upload_scheduler_->MakeImmediateRequest(); + } + // NOTE: We have no way of knowing if the contact list has changed since + // we started our current upload--something that could only happen in a + // very narrow window of time; we only know if the list has changed + // since the last successful upload. We do not handle this edge case, + // instead relying on a subsequent (periodic) download to detect that + // the list needs to be re-uploaded. + break; + } + } + + contact_download_scheduler_->HandleResult(/*success=*/true); +} + +void NearbyShareContactManagerImpl::OnContactsDownloadFailure() { + contact_download_scheduler_->HandleResult(/*success=*/false); +} + +void NearbyShareContactManagerImpl::OnContactsUploadRequested() { + DCHECK_EQ(UploadState::kIdle, upload_state_); + + // Because the user's contact list is not persisted locally, we have to + // retrieve the full contact list ContactRecord protos from the server before + // uploading the list of Contact protos to the server. + upload_state_ = UploadState::kWaitingForDownload; + DownloadContacts(/*only_download_if_changed=*/false); +} + +void NearbyShareContactManagerImpl::StartContactsUpload( + bool did_contacts_change_since_last_upload, + const std::vector<nearbyshare::proto::ContactRecord>& contacts) { + upload_state_ = UploadState::kInProgress; + local_device_data_manager_->UploadContacts( + ContactRecordsToContacts(GetAllowedContacts(), contacts), + base::BindOnce(&NearbyShareContactManagerImpl::OnContactsUploadFinished, + weak_ptr_factory_.GetWeakPtr(), + did_contacts_change_since_last_upload)); +} + +void NearbyShareContactManagerImpl::OnContactsUploadFinished( + bool did_contacts_change_since_last_upload, + bool success) { + if (success) { + NotifyContactsUploaded(did_contacts_change_since_last_upload); + } + upload_state_ = UploadState::kIdle; + contact_upload_scheduler_->HandleResult(success); +} + +bool NearbyShareContactManagerImpl::SetAllowlist( + const std::set<std::string>& new_allowlist) { + std::set<std::string> old_allowlist = GetAllowedContacts(); + bool were_contacts_added = + !std::includes(old_allowlist.begin(), old_allowlist.end(), + new_allowlist.begin(), new_allowlist.end()); + bool were_contacts_removed = + !std::includes(new_allowlist.begin(), new_allowlist.end(), + old_allowlist.begin(), old_allowlist.end()); + + if (!were_contacts_added && !were_contacts_removed) + return false; + + base::Value allowlist_value(base::Value::Type::LIST); + for (const std::string& id : new_allowlist) { + allowlist_value.Append(id); + } + pref_service_->Set(prefs::kNearbySharingAllowedContactsPrefName, + std::move(allowlist_value)); + + NotifyAllowlistChanged(were_contacts_added, were_contacts_removed); + + return true; }
diff --git a/chrome/browser/nearby_sharing/contacts/nearby_share_contact_manager_impl.h b/chrome/browser/nearby_sharing/contacts/nearby_share_contact_manager_impl.h index 0d383d4..c806bcdc 100644 --- a/chrome/browser/nearby_sharing/contacts/nearby_share_contact_manager_impl.h +++ b/chrome/browser/nearby_sharing/contacts/nearby_share_contact_manager_impl.h
@@ -9,19 +9,50 @@ #include <set> #include <string> +#include "base/callback.h" +#include "base/optional.h" #include "chrome/browser/nearby_sharing/contacts/nearby_share_contact_manager.h" +#include "chrome/browser/nearby_sharing/proto/rpc_resources.pb.h" -// TODO(nohle): Add description after class is fully implemented. +class NearbyShareClientFactory; +class NearbyShareContactDownloader; +class NearbyShareLocalDeviceDataManager; +class NearbyShareScheduler; +class PrefService; + +// Implementation of NearbyShareContactManager that persists the set of allowed +// contact IDs--for selected-contacts visiblity mode--in prefs. All other +// contact data is downloaded from People API, via the NearbyShare server, as +// needed. +// +// The Nearby Share server must be explicitly informed of all contacts this +// device is aware of--needed for all-contacts visibility mode--as well as what +// contacts are allowed for selected-contacts visibility mode. The +// NearbyShareContactManagerImpl controls when contacts are uploaded to the +// server: 1) when the server communicates that the contact list has changed +// since the last upload, or 2) when the user locally makes changes to the list +// of selected contacts. These uploaded contact lists are used by the server to +// distribute the device's public certificates accordingly. +// +// In addition to supporting on-demand contact downloads, this implementation +// periodically checks in with the Nearby Share server to see if the user's +// contact list has changed since the last upload. class NearbyShareContactManagerImpl : public NearbyShareContactManager { public: class Factory { public: - static std::unique_ptr<NearbyShareContactManager> Create(); + static std::unique_ptr<NearbyShareContactManager> Create( + PrefService* pref_service, + NearbyShareClientFactory* http_client_factory, + NearbyShareLocalDeviceDataManager* local_device_data_manager); static void SetFactoryForTesting(Factory* test_factory); protected: virtual ~Factory(); - virtual std::unique_ptr<NearbyShareContactManager> CreateInstance() = 0; + virtual std::unique_ptr<NearbyShareContactManager> CreateInstance( + PrefService* pref_service, + NearbyShareClientFactory* http_client_factory, + NearbyShareLocalDeviceDataManager* local_device_data_manager) = 0; private: static Factory* test_factory_; @@ -30,7 +61,12 @@ ~NearbyShareContactManagerImpl() override; private: - NearbyShareContactManagerImpl(); + enum class UploadState { kIdle, kWaitingForDownload, kInProgress }; + + NearbyShareContactManagerImpl( + PrefService* pref_service, + NearbyShareClientFactory* http_client_factory, + NearbyShareLocalDeviceDataManager* local_device_data_manager); // NearbyShareContactsManager: void DownloadContacts(bool only_download_if_changed) override; @@ -38,6 +74,34 @@ const std::set<std::string>& allowed_contact_ids) override; void OnStart() override; void OnStop() override; + + std::set<std::string> GetAllowedContacts() const; + void OnContactsDownloadRequested(); + void OnContactsDownloadSuccess( + bool did_contacts_change_since_last_upload, + base::Optional<std::vector<nearbyshare::proto::ContactRecord>> contacts); + void OnContactsDownloadFailure(); + void OnContactsUploadRequested(); + void StartContactsUpload( + bool did_contacts_change_since_last_upload, + const std::vector<nearbyshare::proto::ContactRecord>& contacts); + void OnContactsUploadFinished(bool did_contacts_change_since_last_upload, + bool success); + bool SetAllowlist(const std::set<std::string>& new_allowlist); + + // By default, only download contacts if they have changed since the last + // upload. Only set to false on explicit request from DownloadContacts(), and + // reset to true after a successful contact download. + bool only_download_if_changed_ = true; + + UploadState upload_state_ = UploadState::kIdle; + PrefService* pref_service_ = nullptr; + NearbyShareClientFactory* http_client_factory_ = nullptr; + NearbyShareLocalDeviceDataManager* local_device_data_manager_ = nullptr; + std::unique_ptr<NearbyShareScheduler> contact_download_scheduler_; + std::unique_ptr<NearbyShareScheduler> contact_upload_scheduler_; + std::unique_ptr<NearbyShareContactDownloader> contact_downloader_; + base::WeakPtrFactory<NearbyShareContactManagerImpl> weak_ptr_factory_{this}; }; #endif // CHROME_BROWSER_NEARBY_SHARING_CONTACTS_NEARBY_SHARE_CONTACT_MANAGER_IMPL_H_
diff --git a/chrome/browser/nearby_sharing/contacts/nearby_share_contact_manager_impl_unittest.cc b/chrome/browser/nearby_sharing/contacts/nearby_share_contact_manager_impl_unittest.cc new file mode 100644 index 0000000..8bbb5af --- /dev/null +++ b/chrome/browser/nearby_sharing/contacts/nearby_share_contact_manager_impl_unittest.cc
@@ -0,0 +1,692 @@ +// Copyright 2020 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include <memory> +#include <set> +#include <string> + +#include "base/no_destructor.h" +#include "base/optional.h" +#include "base/stl_util.h" +#include "base/strings/string_number_conversions.h" +#include "chrome/browser/nearby_sharing/client/fake_nearby_share_client.h" +#include "chrome/browser/nearby_sharing/common/nearby_share_prefs.h" +#include "chrome/browser/nearby_sharing/contacts/fake_nearby_share_contact_downloader.h" +#include "chrome/browser/nearby_sharing/contacts/nearby_share_contact_downloader.h" +#include "chrome/browser/nearby_sharing/contacts/nearby_share_contact_downloader_impl.h" +#include "chrome/browser/nearby_sharing/contacts/nearby_share_contact_manager.h" +#include "chrome/browser/nearby_sharing/contacts/nearby_share_contact_manager_impl.h" +#include "chrome/browser/nearby_sharing/local_device_data/fake_nearby_share_local_device_data_manager.h" +#include "chrome/browser/nearby_sharing/proto/rpc_resources.pb.h" +#include "chrome/browser/nearby_sharing/scheduling/fake_nearby_share_scheduler.h" +#include "chrome/browser/nearby_sharing/scheduling/fake_nearby_share_scheduler_factory.h" +#include "chrome/browser/nearby_sharing/scheduling/nearby_share_scheduler_factory.h" +#include "components/sync_preferences/testing_pref_service_syncable.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace { + +// State for whether an upload is started, requested, or neither after a +// successful download of contacts. +enum class UploadAction { kNone, kRequest, kStart }; + +const char kTestContactIdPrefix[] = "id_"; +const char kTestContactEmailPrefix[] = "email_"; +const char kTestContactPhonePrefix[] = "phone_"; + +// From nearby_share_contact_manager_impl.cc. +constexpr base::TimeDelta kContactDownloadPeriod = + base::TimeDelta::FromHours(1); +constexpr base::TimeDelta kContactDownloadRpcTimeout = + base::TimeDelta::FromSeconds(60); + +std::string GetTestContactId(size_t index) { + return kTestContactIdPrefix + base::NumberToString(index); +} +std::string GetTestContactEmail(size_t index) { + return kTestContactEmailPrefix + base::NumberToString(index); +} +std::string GetTestContactPhone(size_t index) { + return kTestContactPhonePrefix + base::NumberToString(index); +} + +std::set<std::string> TestContactIds(size_t num_contacts) { + std::set<std::string> ids; + for (size_t i = 0; i < num_contacts; ++i) { + ids.insert(GetTestContactId(i)); + } + return ids; +} + +std::vector<nearbyshare::proto::ContactRecord> TestContactRecordList( + size_t num_contacts) { + std::vector<nearbyshare::proto::ContactRecord> contact_list; + for (size_t i = 0; i < num_contacts; ++i) { + nearbyshare::proto::ContactRecord contact; + contact.set_id(GetTestContactId(i)); + contact.add_identifiers()->set_account_name(GetTestContactEmail(i)); + contact.add_identifiers()->set_phone_number(GetTestContactPhone(i)); + contact_list.push_back(contact); + } + return contact_list; +} + +// Converts a list of ContactRecord protos, along with the allowlist, into a +// list of Contact protos. From nearby_share_contact_manager_impl.cc. +std::vector<nearbyshare::proto::Contact> ContactRecordsToContacts( + const std::set<std::string>& allowed_contact_ids, + const std::vector<nearbyshare::proto::ContactRecord>& contact_records) { + std::vector<nearbyshare::proto::Contact> contacts; + for (const auto& contact_record : contact_records) { + bool is_selected = base::Contains(allowed_contact_ids, contact_record.id()); + for (const auto& identifier : contact_record.identifiers()) { + nearbyshare::proto::Contact contact; + contact.mutable_identifier()->CopyFrom(identifier); + contact.set_is_selected(is_selected); + contacts.push_back(contact); + } + } + return contacts; +} + +} // namespace + +class NearbyShareContactManagerImplTest + : public ::testing::Test, + public NearbyShareContactManager::Observer { + protected: + struct AllowlistChangedNotification { + bool were_contacts_added_to_allowlist; + bool were_contacts_removed_from_allowlist; + }; + struct ContactsDownloadedNotification { + std::set<std::string> allowed_contact_ids; + std::vector<nearbyshare::proto::ContactRecord> contacts; + }; + struct ContactsUploadedNotification { + bool did_contacts_change_since_last_upload; + }; + + NearbyShareContactManagerImplTest() = default; + ~NearbyShareContactManagerImplTest() override = default; + + void SetUp() override { + RegisterNearbySharingPrefs(pref_service_.registry()); + NearbyShareSchedulerFactory::SetFactoryForTesting(&scheduler_factory_); + NearbyShareContactDownloaderImpl::Factory::SetFactoryForTesting( + &downloader_factory_); + + manager_ = NearbyShareContactManagerImpl::Factory::Create( + &pref_service_, &http_client_factory_, &local_device_data_manager_); + VerifySchedulerInitialization(); + manager_->AddObserver(this); + manager_->Start(); + } + + void TearDown() override { + manager_->RemoveObserver(this); + manager_.reset(); + NearbyShareSchedulerFactory::SetFactoryForTesting(nullptr); + NearbyShareContactDownloaderImpl::Factory::SetFactoryForTesting(nullptr); + } + + void DownloadContacts(bool only_download_if_changed) { + // Verify that the download scheduler is sent request. + size_t num_requests = download_scheduler()->num_immediate_requests(); + manager_->DownloadContacts(only_download_if_changed); + EXPECT_EQ(num_requests + 1, download_scheduler()->num_immediate_requests()); + } + + void SucceedDownload( + bool did_contacts_change_since_last_upload, + const base::Optional<std::vector<nearbyshare::proto::ContactRecord>>& + contacts, + bool expected_only_download_if_changed, + bool expected_were_contacts_removed_from_allowlist, + const std::set<std::string>& expected_allowed_contact_ids, + UploadAction expected_upload_action) { + TriggerDownloadScheduler(expected_only_download_if_changed); + + size_t num_handled_results = download_scheduler()->handled_results().size(); + size_t num_allowlist_notifications = + allowlist_changed_notifications_.size(); + size_t num_download_notifications = + contacts_downloaded_notifications_.size(); + size_t num_upload_requests = upload_scheduler()->num_immediate_requests(); + size_t num_upload_contacts_calls = + local_device_data_manager_.upload_contacts_calls().size(); + + latest_downloader()->Succeed(did_contacts_change_since_last_upload, + contacts); + + // Verify allowlist notification sent if contacts were removed from the + // allowlist because they no longer exist in the full contacts list. + VerifyAllowlistNotificationSentIfNecessary( + /*initial_num_notifications=*/num_allowlist_notifications, + /*expected_were_contacts_added_to_allowlist=*/false, + expected_were_contacts_removed_from_allowlist); + + VerifyDownloadNotificationSentIfNecessary( + /*initial_num_notifications=*/num_download_notifications, + expected_allowed_contact_ids, contacts); + + // Verify if any uploads were requested or started. + if (contacts) { + switch (expected_upload_action) { + case UploadAction::kNone: + break; + case UploadAction::kRequest: + ++num_upload_requests; + break; + case UploadAction::kStart: + ++num_upload_contacts_calls; + break; + } + } + EXPECT_EQ(num_upload_requests, + upload_scheduler()->num_immediate_requests()); + EXPECT_EQ(num_upload_contacts_calls, + local_device_data_manager_.upload_contacts_calls().size()); + + // Verify that the download success/failure result is sent to the + // scheduler. + EXPECT_EQ(num_handled_results + 1, + download_scheduler()->handled_results().size()); + EXPECT_TRUE(download_scheduler()->handled_results().back()); + } + + void FailDownload(bool expected_only_download_if_changed) { + TriggerDownloadScheduler(expected_only_download_if_changed); + + // Fail download and verify that the result is sent to the scheduler. + size_t num_handled_results = download_scheduler()->handled_results().size(); + latest_downloader()->Fail(); + EXPECT_EQ(num_handled_results + 1, + download_scheduler()->handled_results().size()); + EXPECT_FALSE(download_scheduler()->handled_results().back()); + } + + void TriggerUploadFromScheduler() { + upload_scheduler()->InvokeRequestCallback(); + } + + void FinishUpload( + bool success, + bool expected_did_contacts_change_since_last_upload, + const std::vector<nearbyshare::proto::Contact>& expected_contacts) { + FakeNearbyShareLocalDeviceDataManager::UploadContactsCall& call = + local_device_data_manager_.upload_contacts_calls().back(); + ASSERT_EQ(expected_contacts.size(), call.contacts.size()); + for (size_t i = 0; i < expected_contacts.size(); ++i) { + EXPECT_EQ(expected_contacts[i].SerializeAsString(), + call.contacts[i].SerializeAsString()); + } + + // Invoke upload callback from local device data manager, verify that + // upload notification was sent, and verify that result was sent back to + // the upload scheduler. + size_t num_upload_notifications = contacts_uploaded_notifications_.size(); + size_t num_handled_results = upload_scheduler()->handled_results().size(); + std::move(call.callback).Run(success); + if (success) { + EXPECT_EQ(num_upload_notifications + 1, + contacts_uploaded_notifications_.size()); + EXPECT_EQ(expected_did_contacts_change_since_last_upload, + contacts_uploaded_notifications_.back() + .did_contacts_change_since_last_upload); + } else { + EXPECT_EQ(num_upload_notifications, + contacts_uploaded_notifications_.size()); + } + EXPECT_EQ(num_handled_results + 1, + upload_scheduler()->handled_results().size()); + EXPECT_EQ(success, upload_scheduler()->handled_results().back()); + } + + void SetAllowedContacts(const std::set<std::string>& allowed_contact_ids, + bool expected_were_contacts_added_to_allowlist, + bool expected_were_contacts_removed_from_allowlist) { + size_t num_allowlist_notifications = + allowlist_changed_notifications_.size(); + size_t num_upload_requests = upload_scheduler()->num_immediate_requests(); + + manager_->SetAllowedContacts(allowed_contact_ids); + + // Verify allowlist notification sent and upload requested if contacts were + // added or removed. + if (expected_were_contacts_added_to_allowlist || + expected_were_contacts_removed_from_allowlist) { + EXPECT_EQ(num_allowlist_notifications + 1, + allowlist_changed_notifications_.size()); + EXPECT_EQ(expected_were_contacts_added_to_allowlist, + allowlist_changed_notifications_.back() + .were_contacts_added_to_allowlist); + EXPECT_EQ(expected_were_contacts_removed_from_allowlist, + allowlist_changed_notifications_.back() + .were_contacts_removed_from_allowlist); + EXPECT_EQ(num_upload_requests + 1, + upload_scheduler()->num_immediate_requests()); + } else { + EXPECT_EQ(num_allowlist_notifications, + allowlist_changed_notifications_.size()); + EXPECT_EQ(num_upload_requests, + upload_scheduler()->num_immediate_requests()); + } + } + + private: + // NearbyShareContactManager::Observer: + void OnAllowlistChanged(bool were_contacts_added_to_allowlist, + bool were_contacts_removed_from_allowlist) override { + AllowlistChangedNotification notification; + notification.were_contacts_added_to_allowlist = + were_contacts_added_to_allowlist; + notification.were_contacts_removed_from_allowlist = + were_contacts_removed_from_allowlist; + allowlist_changed_notifications_.push_back(notification); + } + void OnContactsDownloaded( + const std::set<std::string>& allowed_contact_ids, + const std::vector<nearbyshare::proto::ContactRecord>& contacts) override { + ContactsDownloadedNotification notification; + notification.allowed_contact_ids = allowed_contact_ids; + notification.contacts = contacts; + contacts_downloaded_notifications_.push_back(notification); + } + void OnContactsUploaded(bool did_contacts_change_since_last_upload) override { + ContactsUploadedNotification notification; + notification.did_contacts_change_since_last_upload = + did_contacts_change_since_last_upload; + contacts_uploaded_notifications_.push_back(notification); + } + + FakeNearbyShareContactDownloader* latest_downloader() { + return downloader_factory_.instances().back(); + } + + FakeNearbyShareScheduler* download_scheduler() { + return scheduler_factory_.pref_name_to_periodic_instance() + .at(prefs::kNearbySharingSchedulerContactDownloadPrefName) + .fake_scheduler; + } + + FakeNearbyShareScheduler* upload_scheduler() { + return scheduler_factory_.pref_name_to_on_demand_instance() + .at(prefs::kNearbySharingSchedulerContactUploadPrefName) + .fake_scheduler; + } + + void VerifySchedulerInitialization() { + // Verify download scheduler input parameters. + FakeNearbyShareSchedulerFactory::PeriodicInstance + download_scheduler_instance = + scheduler_factory_.pref_name_to_periodic_instance().at( + prefs::kNearbySharingSchedulerContactDownloadPrefName); + EXPECT_TRUE(download_scheduler_instance.fake_scheduler); + EXPECT_EQ(kContactDownloadPeriod, + download_scheduler_instance.request_period); + EXPECT_TRUE(download_scheduler_instance.retry_failures); + EXPECT_TRUE(download_scheduler_instance.require_connectivity); + EXPECT_EQ(&pref_service_, download_scheduler_instance.pref_service); + + // Verify upload scheduler input parameters. + FakeNearbyShareSchedulerFactory::OnDemandInstance + upload_scheduler_instance = + scheduler_factory_.pref_name_to_on_demand_instance().at( + prefs::kNearbySharingSchedulerContactUploadPrefName); + EXPECT_TRUE(upload_scheduler_instance.fake_scheduler); + EXPECT_TRUE(upload_scheduler_instance.retry_failures); + EXPECT_TRUE(upload_scheduler_instance.require_connectivity); + EXPECT_EQ(&pref_service_, upload_scheduler_instance.pref_service); + } + + void TriggerDownloadScheduler(bool expected_only_download_if_changed) { + // Fire download scheduler and verify downloader creation. + size_t num_downloaders = downloader_factory_.instances().size(); + download_scheduler()->InvokeRequestCallback(); + EXPECT_EQ(num_downloaders + 1, downloader_factory_.instances().size()); + EXPECT_EQ(kContactDownloadRpcTimeout, downloader_factory_.latest_timeout()); + EXPECT_EQ(&http_client_factory_, + downloader_factory_.latest_client_factory()); + EXPECT_EQ(local_device_data_manager_.GetId(), + latest_downloader()->device_id()); + EXPECT_EQ(expected_only_download_if_changed, + latest_downloader()->only_download_if_changed()); + } + + void VerifyAllowlistNotificationSentIfNecessary( + size_t initial_num_notifications, + bool expected_were_contacts_added_to_allowlist, + bool expected_were_contacts_removed_from_allowlist) { + if (expected_were_contacts_removed_from_allowlist) { + EXPECT_EQ(initial_num_notifications + 1, + allowlist_changed_notifications_.size()); + EXPECT_FALSE(allowlist_changed_notifications_.back() + .were_contacts_added_to_allowlist); + EXPECT_TRUE(allowlist_changed_notifications_.back() + .were_contacts_removed_from_allowlist); + } else { + EXPECT_EQ(initial_num_notifications, + allowlist_changed_notifications_.size()); + } + } + + void VerifyDownloadNotificationSentIfNecessary( + size_t initial_num_notifications, + const std::set<std::string>& expected_allowed_contact_ids, + const base::Optional<std::vector<nearbyshare::proto::ContactRecord>>& + contacts) { + // Notification should only be sent if contact list is available. + if (contacts) { + EXPECT_EQ(initial_num_notifications + 1, + contacts_downloaded_notifications_.size()); + EXPECT_EQ(expected_allowed_contact_ids, + contacts_downloaded_notifications_.back().allowed_contact_ids); + EXPECT_EQ(contacts->size(), + contacts_downloaded_notifications_.back().contacts.size()); + for (size_t i = 0; i < contacts->size(); ++i) { + EXPECT_EQ(contacts->at(i).SerializeAsString(), + contacts_downloaded_notifications_.back() + .contacts[i] + .SerializeAsString()); + } + } else { + EXPECT_EQ(initial_num_notifications, + contacts_downloaded_notifications_.size()); + } + } + + std::vector<AllowlistChangedNotification> allowlist_changed_notifications_; + std::vector<ContactsDownloadedNotification> + contacts_downloaded_notifications_; + std::vector<ContactsUploadedNotification> contacts_uploaded_notifications_; + sync_preferences::TestingPrefServiceSyncable pref_service_; + FakeNearbyShareClientFactory http_client_factory_; + FakeNearbyShareLocalDeviceDataManager local_device_data_manager_; + FakeNearbyShareSchedulerFactory scheduler_factory_; + FakeNearbyShareContactDownloader::Factory downloader_factory_; + std::unique_ptr<NearbyShareContactManager> manager_; +}; + +TEST_F(NearbyShareContactManagerImplTest, SetAllowlist) { + // Add initial allowed contacts. + SetAllowedContacts(TestContactIds(/*num_contacts=*/3u), + /*expected_were_contacts_added_to_allowlist=*/true, + /*expected_were_contacts_removed_from_allowlist=*/false); + // Remove last allowed contact. + SetAllowedContacts(TestContactIds(/*num_contacts=*/2u), + /*expected_were_contacts_added_to_allowlist=*/false, + /*expected_were_contacts_removed_from_allowlist=*/true); + // Add back last allowed contact. + SetAllowedContacts(TestContactIds(/*num_contacts=*/3u), + /*expected_were_contacts_added_to_allowlist=*/true, + /*expected_were_contacts_removed_from_allowlist=*/false); + // Set list without any changes. + SetAllowedContacts(TestContactIds(/*num_contacts=*/3u), + /*expected_were_contacts_added_to_allowlist=*/false, + /*expected_were_contacts_removed_from_allowlist=*/false); +} + +TEST_F(NearbyShareContactManagerImplTest, + DownloadContacts_Success_ChangedContactListSent_AllowlistUnchanged) { + DownloadContacts(/*only_download_if_changed=*/false); + + // Because contacts changed since last upload, a subsequent upload should be + // requested. + SucceedDownload( + /*did_contacts_change_since_last_upload=*/true, + TestContactRecordList(/*num_contacts=*/3u), + /*expected_only_download_if_changed=*/false, + /*expected_were_contacts_removed_from_allowlist=*/false, + /*expected_allowed_contact_ids=*/std::set<std::string>(), + /*expected_upload_action=*/UploadAction::kRequest); +} + +TEST_F(NearbyShareContactManagerImplTest, + DownloadContacts_Success_UnchangedContactListSent_AllowlistUnchanged) { + DownloadContacts(/*only_download_if_changed=*/false); + + // Because neither the contact list nor the allowlist changed, a subsequent + // upload is not needed. + SucceedDownload( + /*did_contacts_change_since_last_upload=*/false, + TestContactRecordList(/*num_contacts=*/3u), + /*expected_only_download_if_changed=*/false, + /*expected_were_contacts_removed_from_allowlist=*/false, + /*expected_allowed_contact_ids=*/std::set<std::string>(), + /*expected_upload_action=*/UploadAction::kNone); +} + +TEST_F(NearbyShareContactManagerImplTest, + DownloadContacts_Success_UnchangedContactListSent_AllowlistChanged) { + // Add initial allowed contacts. + SetAllowedContacts(TestContactIds(/*num_contacts=*/3u), + /*expected_were_contacts_added_to_allowlist=*/true, + /*expected_were_contacts_removed_from_allowlist=*/false); + + DownloadContacts(/*only_download_if_changed=*/false); + + // Because a contact will be removed from the allowlist because it doesn't + // exist in the returned contact list, a subsequent upload should be + // requested. + SucceedDownload( + /*did_contacts_change_since_last_upload=*/false, + TestContactRecordList(/*num_contacts=*/2u), + /*expected_only_download_if_changed=*/false, + /*expected_were_contacts_removed_from_allowlist=*/true, + /*expected_allowed_contact_ids=*/TestContactIds(/*num_contacts=*/2u), + /*expected_upload_action=*/UploadAction::kRequest); +} + +TEST_F(NearbyShareContactManagerImplTest, + DownloadContacts_Success_ContactListNotSent) { + // Add initial allowed contacts to make sure they're not removed. + SetAllowedContacts(TestContactIds(/*num_contacts=*/3u), + /*expected_were_contacts_added_to_allowlist=*/true, + /*expected_were_contacts_removed_from_allowlist=*/false); + + DownloadContacts(/*only_download_if_changed=*/true); + + // No contacts were downloaded (in practice because contact didn't change and + // we didn't request a full download). + SucceedDownload( + /*did_contacts_change_since_last_upload=*/false, + /*contacts=*/base::nullopt, + /*expected_only_download_if_changed=*/true, + /*expected_were_contacts_removed_from_allowlist=*/false, + /*expected_allowed_contact_ids=*/TestContactIds(/*num_contacts=*/3u), + /*expected_upload_action=*/UploadAction::kNone); +} + +TEST_F(NearbyShareContactManagerImplTest, + DownloadContacts_Success_OverrideOnlyDownloadIfChanged) { + // Do not force a contacts download if the list hasn't changed since the last + // upload. + DownloadContacts(/*only_download_if_changed=*/true); + + // Before the first request can run, request a forced contacts download even + // if contacts haven't changed. + DownloadContacts(/*only_download_if_changed=*/false); + + // Now, request a download only if contacts have changed. + DownloadContacts(/*only_download_if_changed=*/true); + + // Because there was an outstanding request for a forced download when a + // non-forced download was requested, the forced download request will take + // priority. + SucceedDownload( + /*did_contacts_change_since_last_upload=*/false, + TestContactRecordList(/*num_contacts=*/3u), + /*expected_only_download_if_changed=*/false, + /*expected_were_contacts_removed_from_allowlist=*/false, + /*expected_allowed_contact_ids=*/std::set<std::string>(), + /*expected_upload_action=*/UploadAction::kNone); + + // Now, because the request to force a contact download was fulfilled, we can + // request a download only if contacts have changed without being trumped by a + // previous forced-download request. + DownloadContacts(/*only_download_if_changed=*/true); + SucceedDownload( + /*did_contacts_change_since_last_upload=*/false, + /*contacts=*/base::nullopt, + /*expected_only_download_if_changed=*/true, + /*expected_were_contacts_removed_from_allowlist=*/false, + /*expected_allowed_contact_ids=*/TestContactIds(/*num_contacts=*/3u), + /*expected_upload_action=*/UploadAction::kNone); +} + +TEST_F(NearbyShareContactManagerImplTest, DownloadContacts_Failure) { + DownloadContacts(/*only_download_if_changed=*/false); + FailDownload(/*expected_only_download_if_changed=*/false); +} + +TEST_F(NearbyShareContactManagerImplTest, + UploadContacts_Success_FromContactListChanged) { + // During a regular download, notice that the contact list has changed since + // the last upload. + DownloadContacts(/*only_download_if_changed=*/true); + SucceedDownload( + /*did_contacts_change_since_last_upload=*/true, + TestContactRecordList(/*num_contacts=*/2u), + /*expected_only_download_if_changed=*/true, + /*expected_were_contacts_removed_from_allowlist=*/false, + /*expected_allowed_contact_ids=*/std::set<std::string>(), + /*expected_upload_action=*/UploadAction::kRequest); + + // Before contacts can be uploaded, we need to first (force) re-download the + // complete contact list. + TriggerUploadFromScheduler(); + SucceedDownload( + /*did_contacts_change_since_last_upload=*/true, + TestContactRecordList(/*num_contacts=*/2u), + /*expected_only_download_if_changed=*/false, + /*expected_were_contacts_removed_from_allowlist=*/false, + /*expected_allowed_contact_ids=*/std::set<std::string>(), + /*expected_upload_action=*/UploadAction::kStart); + + // Finish the upload successfully. + FinishUpload( + /*success=*/true, + /*expected_did_contacts_change_since_last_upload=*/true, + /*expected_contacts=*/ + ContactRecordsToContacts(TestContactIds(/*num_contacts=*/0u), + TestContactRecordList(/*num_contacts=*/2u))); +} + +TEST_F(NearbyShareContactManagerImplTest, + UploadContacts_Success_FromAllowlistChanged) { + // Add contacts to the allowlist, resulting in an upload request. + std::set<std::string> allowlist = TestContactIds(/*num_contacts=*/1u); + SetAllowedContacts(allowlist, + /*expected_were_contacts_added_to_allowlist=*/true, + /*expected_were_contacts_removed_from_allowlist=*/false); + + // Before contacts can be uploaded, we need to first (force) download the + // complete contact list. + TriggerUploadFromScheduler(); + SucceedDownload( + /*did_contacts_change_since_last_upload=*/false, + TestContactRecordList(/*num_contacts=*/2u), + /*expected_only_download_if_changed=*/false, + /*expected_were_contacts_removed_from_allowlist=*/false, + /*expected_allowed_contact_ids=*/allowlist, + /*expected_upload_action=*/UploadAction::kStart); + + // Finish the upload successfully. + FinishUpload( + /*success=*/true, + /*expected_did_contacts_change_since_last_upload=*/false, + /*expected_contacts=*/ + ContactRecordsToContacts(TestContactIds(/*num_contacts=*/1u), + TestContactRecordList(/*num_contacts=*/2u))); +} + +TEST_F(NearbyShareContactManagerImplTest, + UploadContacts_Success_DownloadRequestedWhileUploadInProgress) { + // Add contacts to the allowlist, resulting in an upload request. + SetAllowedContacts(TestContactIds(/*num_contacts=*/2u), + /*expected_were_contacts_added_to_allowlist=*/true, + /*expected_were_contacts_removed_from_allowlist=*/false); + + // Before contacts can be uploaded, we need to first (force) download the + // complete contact list. Following a successful download, the upload will be + // started. + TriggerUploadFromScheduler(); + SucceedDownload( + /*did_contacts_change_since_last_upload=*/false, + TestContactRecordList(/*num_contacts=*/2u), + /*expected_only_download_if_changed=*/false, + /*expected_were_contacts_removed_from_allowlist=*/false, + /*expected_allowed_contact_ids=*/TestContactIds(/*num_contacts=*/2u), + /*expected_upload_action=*/UploadAction::kStart); + + // Make a download request while the upload is in progress. Because a member + // of the allowlist was removed as a request, another upload should be + // requested. + DownloadContacts(/*only_download_if_changed=*/false); + SucceedDownload( + /*did_contacts_change_since_last_upload=*/false, + TestContactRecordList(/*num_contacts=*/1u), + /*expected_only_download_if_changed=*/false, + /*expected_were_contacts_removed_from_allowlist=*/true, + /*expected_allowed_contact_ids=*/TestContactIds(/*num_contacts=*/1u), + /*expected_upload_action=*/UploadAction::kRequest); + + // Finish the first upload successfully, expecting the old contact list and + // allowlist to have been used. + FinishUpload( + /*success=*/true, + /*expected_did_contacts_change_since_last_upload=*/false, + /*expected_contacts=*/ + ContactRecordsToContacts(TestContactIds(/*num_contacts=*/2u), + TestContactRecordList(/*num_contacts=*/2u))); + + // Run the second upload with the new contact list and allowlist. + TriggerUploadFromScheduler(); + SucceedDownload( + /*did_contacts_change_since_last_upload=*/false, + TestContactRecordList(/*num_contacts=*/1u), + /*expected_only_download_if_changed=*/false, + /*expected_were_contacts_removed_from_allowlist=*/false, + /*expected_allowed_contact_ids=*/TestContactIds(/*num_contacts=*/1u), + /*expected_upload_action=*/UploadAction::kStart); + FinishUpload( + /*success=*/true, + /*expected_did_contacts_change_since_last_upload=*/false, + /*expected_contacts=*/ + ContactRecordsToContacts(TestContactIds(/*num_contacts=*/1u), + TestContactRecordList(/*num_contacts=*/1u))); +} + +TEST_F(NearbyShareContactManagerImplTest, UploadContacts_Failure) { + // During a regular download, notice that the contact list has changed since + // the last upload. + DownloadContacts(/*only_download_if_changed=*/true); + SucceedDownload( + /*did_contacts_change_since_last_upload=*/true, + TestContactRecordList(/*num_contacts=*/2u), + /*expected_only_download_if_changed=*/true, + /*expected_were_contacts_removed_from_allowlist=*/false, + /*expected_allowed_contact_ids=*/std::set<std::string>(), + /*expected_upload_action=*/UploadAction::kRequest); + + // Before contacts can be uploaded, we need to first (force) re-download the + // complete contact list. + TriggerUploadFromScheduler(); + SucceedDownload( + /*did_contacts_change_since_last_upload=*/true, + TestContactRecordList(/*num_contacts=*/2u), + /*expected_only_download_if_changed=*/false, + /*expected_were_contacts_removed_from_allowlist=*/false, + /*expected_allowed_contact_ids=*/std::set<std::string>(), + /*expected_upload_action=*/UploadAction::kStart); + + // Fail the upload. + FinishUpload( + /*success=*/false, + /*expected_did_contacts_change_since_last_upload=*/true, + /*expected_contacts=*/ + ContactRecordsToContacts(TestContactIds(/*num_contacts=*/0u), + TestContactRecordList(/*num_contacts=*/2u))); +}
diff --git a/chrome/browser/nearby_sharing/logging/proto_to_dictionary_conversion.cc b/chrome/browser/nearby_sharing/logging/proto_to_dictionary_conversion.cc index 38a578f..1c5ce9d 100644 --- a/chrome/browser/nearby_sharing/logging/proto_to_dictionary_conversion.cc +++ b/chrome/browser/nearby_sharing/logging/proto_to_dictionary_conversion.cc
@@ -1,4 +1,4 @@ -// Copyright 2020 The Chromium Authors.All rights reserved. +// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. @@ -142,7 +142,6 @@ base::Value ListContactPeopleRequestToReadableDictionary( const nearbyshare::proto::ListContactPeopleRequest& request) { base::Value dict(base::Value::Type::DICTIONARY); - dict.SetStringKey("parent", request.parent()); dict.SetIntKey("page_size", request.page_size()); dict.SetStringKey("page_token", request.page_token()); return dict;
diff --git a/chrome/browser/nearby_sharing/nearby_sharing_service_impl.cc b/chrome/browser/nearby_sharing/nearby_sharing_service_impl.cc index b41f311d..76b1917 100644 --- a/chrome/browser/nearby_sharing/nearby_sharing_service_impl.cc +++ b/chrome/browser/nearby_sharing/nearby_sharing_service_impl.cc
@@ -242,7 +242,10 @@ NearbyShareLocalDeviceDataManagerImpl::Factory::Create( prefs, http_client_factory_.get())), - contact_manager_(NearbyShareContactManagerImpl::Factory::Create()), + contact_manager_(NearbyShareContactManagerImpl::Factory::Create( + prefs, + http_client_factory_.get(), + local_device_data_manager_.get())), certificate_manager_(NearbyShareCertificateManagerImpl::Factory::Create( local_device_data_manager_.get(), prefs,
diff --git a/chrome/browser/nearby_sharing/proto/contact_rpc.proto b/chrome/browser/nearby_sharing/proto/contact_rpc.proto index d3caa23..3963562 100644 --- a/chrome/browser/nearby_sharing/proto/contact_rpc.proto +++ b/chrome/browser/nearby_sharing/proto/contact_rpc.proto
@@ -4,7 +4,7 @@ // Keep in sync with // http://google3/google/internal/location/nearby/sharing/v1/rpcs/contacts.proto -// Messages not used in Chrome have been omitted. Last copied at cl/2228987. +// Messages not used in Chrome have been omitted. Last copied at cl/324307508. syntax = "proto3"; @@ -18,12 +18,9 @@ message CheckContactsReachabilityRequest { message ReachableContact { string contact_id = 1; - repeated string phone_numbers = 2; - repeated string emails = 3; } - repeated ReachableContact contacts = 1; } @@ -38,18 +35,13 @@ // Request to list ContactRecord of a user. message ListContactPeopleRequest { - // Required. The resource name determines which contact records to list. - // The special prefix "users/me" lists the requester's own contacts. This - // is of the format "users/*/devices/*". - string parent = 1; - // Optional limit on the number of ContactRecord in - // [ListContactPeopleResponse.contact_records]. Defaults to 2000 if not set. - int32 page_size = 2; + // [ListContactPeopleResponse.contact_records]. Defaults to 500 if not set. + int32 page_size = 1; // Optional pagination token, returned earlier via // [ListContactPeopleResponse.next_page_token] - string page_token = 3; + string page_token = 2; } // Response from a ListContactPeopleRequest.
diff --git a/chrome/browser/nearby_sharing/proto/device_rpc.proto b/chrome/browser/nearby_sharing/proto/device_rpc.proto index a66c24f..ad28ea7 100644 --- a/chrome/browser/nearby_sharing/proto/device_rpc.proto +++ b/chrome/browser/nearby_sharing/proto/device_rpc.proto
@@ -4,7 +4,7 @@ // Keep in sync with // http://google3/google/internal/location/nearby/sharing/v1/rpcs/devices.proto -// Messages not used in Chrome have been omitted. Last copied at cl/2228987. +// Messages not used in Chrome have been omitted. Last copied at cl/325953873. syntax = "proto3"; @@ -40,3 +40,18 @@ // share target. string image_url = 3; } + +// Request to get a device's state. +message GetDeviceStateRequest { + // Required. The resource name determines which device's contact change + // history to check. The special prefix "users/me" lists the requester's own + // contacts. This is of the format "users/*/devices/*". + string parent = 1; +} + +// Response from a GetDeviceStateRequest. +message GetDeviceStateResponse { + // True if the device's contacts have changed (out of sync) since last + // UpdateDevice call with contacts path. + bool are_contacts_changed = 1; +}
diff --git a/chrome/browser/notifications/profile_notification.cc b/chrome/browser/notifications/profile_notification.cc index c8acd4f..fe13fabe 100644 --- a/chrome/browser/notifications/profile_notification.cc +++ b/chrome/browser/notifications/profile_notification.cc
@@ -51,4 +51,4 @@ #endif } -ProfileNotification::~ProfileNotification() {} +ProfileNotification::~ProfileNotification() = default;
diff --git a/chrome/browser/notifications/profile_notification.h b/chrome/browser/notifications/profile_notification.h index 3e5a30a2..7e556609 100644 --- a/chrome/browser/notifications/profile_notification.h +++ b/chrome/browser/notifications/profile_notification.h
@@ -31,6 +31,8 @@ Profile* profile, const message_center::Notification& notification, NotificationHandler::Type type = NotificationHandler::Type::MAX); + ProfileNotification(const ProfileNotification&) = delete; + ProfileNotification& operator=(const ProfileNotification&) = delete; ~ProfileNotification(); Profile* profile() const { return profile_; } @@ -57,8 +59,6 @@ NotificationHandler::Type type_; std::unique_ptr<ScopedKeepAlive> keep_alive_; - - DISALLOW_COPY_AND_ASSIGN(ProfileNotification); }; #endif // CHROME_BROWSER_NOTIFICATIONS_PROFILE_NOTIFICATION_H_
diff --git a/chrome/browser/password_check/android/internal/java/src/org/chromium/chrome/browser/password_check/PasswordCheckMediator.java b/chrome/browser/password_check/android/internal/java/src/org/chromium/chrome/browser/password_check/PasswordCheckMediator.java index 9d8c0c1..9e8f3af 100644 --- a/chrome/browser/password_check/android/internal/java/src/org/chromium/chrome/browser/password_check/PasswordCheckMediator.java +++ b/chrome/browser/password_check/android/internal/java/src/org/chromium/chrome/browser/password_check/PasswordCheckMediator.java
@@ -108,6 +108,9 @@ @Override public void onPasswordCheckStatusChanged(@PasswordCheckUIStatus int status) { + // There is no UI representation of a canceled check. This status can be sent when + // the bridge and the password check UI are being torn down while a check is running. + if (status == PasswordCheckUIStatus.CANCELED) return; ListModel<ListItem> items = mModel.get(ITEMS); PropertyModel header; if (items.size() == 0) {
diff --git a/chrome/browser/password_check/android/internal/java/src/org/chromium/chrome/browser/password_check/PasswordCheckViewDialogFragment.java b/chrome/browser/password_check/android/internal/java/src/org/chromium/chrome/browser/password_check/PasswordCheckViewDialogFragment.java index 7826411a..98b91ac 100644 --- a/chrome/browser/password_check/android/internal/java/src/org/chromium/chrome/browser/password_check/PasswordCheckViewDialogFragment.java +++ b/chrome/browser/password_check/android/internal/java/src/org/chromium/chrome/browser/password_check/PasswordCheckViewDialogFragment.java
@@ -13,6 +13,8 @@ import androidx.appcompat.app.AlertDialog; import org.chromium.chrome.browser.password_check.internal.R; +import org.chromium.chrome.browser.password_manager.settings.ReauthenticationManager; +import org.chromium.chrome.browser.password_manager.settings.ReauthenticationManager.ReauthScope; /** * Shows the dialog that allows the user to see the compromised credential. @@ -44,4 +46,14 @@ .create(); return viewDialog; } + + @Override + public void onResume() { + super.onResume(); + if (!ReauthenticationManager.authenticationStillValid(ReauthScope.ONE_AT_A_TIME)) { + // If the page was idle (e.g. screenlocked for a few minutes), close the dialog to + // ensure the user goes through reauth again. + dismiss(); + } + } }
diff --git a/chrome/browser/password_check/android/javatests/src/org/chromium/chrome/browser/password_check/PasswordCheckViewTest.java b/chrome/browser/password_check/android/javatests/src/org/chromium/chrome/browser/password_check/PasswordCheckViewTest.java index ded4a6f90..2fee3cd 100644 --- a/chrome/browser/password_check/android/javatests/src/org/chromium/chrome/browser/password_check/PasswordCheckViewTest.java +++ b/chrome/browser/password_check/android/javatests/src/org/chromium/chrome/browser/password_check/PasswordCheckViewTest.java
@@ -42,6 +42,7 @@ import static org.chromium.chrome.browser.password_check.PasswordCheckUIStatus.ERROR_UNKNOWN; import static org.chromium.chrome.browser.password_check.PasswordCheckUIStatus.IDLE; import static org.chromium.chrome.browser.password_check.PasswordCheckUIStatus.RUNNING; +import static org.chromium.chrome.browser.password_manager.settings.ReauthenticationManager.VALID_REAUTHENTICATION_TIME_INTERVAL_MILLIS; import static org.chromium.content_public.browser.test.util.CriteriaHelper.pollUiThread; import static org.chromium.content_public.browser.test.util.TestThreadUtils.runOnUiThreadBlocking; @@ -76,6 +77,8 @@ import org.chromium.chrome.browser.flags.ChromeSwitches; import org.chromium.chrome.browser.password_check.PasswordCheckProperties.HeaderProperties; import org.chromium.chrome.browser.password_check.internal.R; +import org.chromium.chrome.browser.password_manager.settings.ReauthenticationManager; +import org.chromium.chrome.browser.password_manager.settings.ReauthenticationManager.ReauthScope; import org.chromium.chrome.browser.settings.SettingsActivityTestRule; import org.chromium.chrome.test.ChromeJUnit4ClassRunner; import org.chromium.components.browser_ui.widget.listmenu.ListMenuButton; @@ -614,6 +617,9 @@ recordedClosure.incrementAndGet(); } }; + ReauthenticationManager.recordLastReauth( + System.currentTimeMillis(), ReauthScope.ONE_AT_A_TIME); + mModel.set(VIEW_CREDENTIAL, ANA); runOnUiThreadBlocking(() -> mModel.set(VIEW_DIALOG_HANDLER, fakeHandler)); @@ -625,6 +631,35 @@ assertThat(recordedClosure.get(), is(1)); } + @Test + @MediumTest + public void testOnResumeViewDialogReauthenticationNeeded() { + final AtomicInteger recordedDismiss = new AtomicInteger(0); + PasswordCheckDeletionDialogFragment.Handler fakeHandler = + new PasswordCheckDeletionDialogFragment.Handler() { + @Override + public void onDismiss() { + recordedDismiss.incrementAndGet(); + } + @Override + public void onClick(DialogInterface dialogInterface, int i) {} + }; + ReauthenticationManager.recordLastReauth( + System.currentTimeMillis(), ReauthScope.ONE_AT_A_TIME); + + mModel.set(VIEW_CREDENTIAL, ANA); + runOnUiThreadBlocking(() -> mModel.set(VIEW_DIALOG_HANDLER, fakeHandler)); + + ReauthenticationManager.recordLastReauth( + System.currentTimeMillis() - VALID_REAUTHENTICATION_TIME_INTERVAL_MILLIS, + ReauthScope.ONE_AT_A_TIME); + + mTestRule.getFragment().onStop(); + mTestRule.getFragment().onResume(); + + CriteriaHelper.pollInstrumentationThread(() -> recordedDismiss.get() == 1); + } + private MVCListAdapter.ListItem buildHeader(@PasswordCheckUIStatus int status, Integer compromisedCredentialsCount, Long checkTimestamp) { return buildHeader(status, compromisedCredentialsCount, checkTimestamp, null);
diff --git a/chrome/browser/password_check/android/junit/src/org/chromium/chrome/browser/password_check/PasswordCheckControllerTest.java b/chrome/browser/password_check/android/junit/src/org/chromium/chrome/browser/password_check/PasswordCheckControllerTest.java index ed79602..97eef13 100644 --- a/chrome/browser/password_check/android/junit/src/org/chromium/chrome/browser/password_check/PasswordCheckControllerTest.java +++ b/chrome/browser/password_check/android/junit/src/org/chromium/chrome/browser/password_check/PasswordCheckControllerTest.java
@@ -32,6 +32,7 @@ import static org.chromium.chrome.browser.password_check.PasswordCheckProperties.HeaderProperties.RESTART_BUTTON_ACTION; import static org.chromium.chrome.browser.password_check.PasswordCheckProperties.HeaderProperties.UNKNOWN_PROGRESS; import static org.chromium.chrome.browser.password_check.PasswordCheckProperties.ITEMS; +import static org.chromium.chrome.browser.password_check.PasswordCheckUIStatus.CANCELED; import static org.chromium.chrome.browser.password_check.PasswordCheckUIStatus.ERROR_OFFLINE; import static org.chromium.chrome.browser.password_check.PasswordCheckUIStatus.ERROR_UNKNOWN; import static org.chromium.chrome.browser.password_check.PasswordCheckUIStatus.IDLE; @@ -284,6 +285,14 @@ } @Test + public void testCanceledStatusDoesntUpdateModel() { + assertRunningHeader(mModel.get(ITEMS).get(0), UNKNOWN_PROGRESS); + mMediator.onPasswordCheckStatusChanged(CANCELED); + // Check that the header model didn't change. + assertRunningHeader(mModel.get(ITEMS).get(0), UNKNOWN_PROGRESS); + } + + @Test public void testNotIdleStatusNotUpdatedOnCredentialsFetchCompleted() { mMediator.onPasswordCheckStatusChanged(RUNNING); assertNull(mModel.get(ITEMS).get(0).model.get(COMPROMISED_CREDENTIALS_COUNT));
diff --git a/chrome/browser/payments/secure_payment_confirmation_browsertest.cc b/chrome/browser/payments/secure_payment_confirmation_browsertest.cc index 35b6254..b5925171 100644 --- a/chrome/browser/payments/secure_payment_confirmation_browsertest.cc +++ b/chrome/browser/payments/secure_payment_confirmation_browsertest.cc
@@ -3,6 +3,7 @@ // found in the LICENSE file. #include "base/command_line.h" +#include "base/strings/stringprintf.h" #include "build/build_config.h" #include "chrome/test/payments/payment_request_platform_browsertest_base.h" #include "content/public/common/content_switches.h" @@ -13,8 +14,8 @@ namespace payments { namespace { -static constexpr char kInvokePaymentRequest[] = - "getStatusForMethodData([{" +static constexpr char kTestMethodData[] = + "[{ " " supportedMethods: 'secure-payment-confirmation'," " data: {" " action: 'authenticate'," @@ -22,7 +23,11 @@ " networkData: Uint8Array.from('x', c => c.charCodeAt(0))," " timeout: 60000," " fallbackUrl: 'https://fallback.example/url'" - "}}])"; + "}}]"; + +std::string getInvokePaymentRequestSnippet() { + return base::StringPrintf("getStatusForMethodData(%s)", kTestMethodData); +} class SecurePaymentConfirmationTest : public PaymentRequestPlatformBrowserTestBase { @@ -41,7 +46,8 @@ // EvalJs waits for JavaScript promise to resolve. EXPECT_EQ( "The payment method \"secure-payment-confirmation\" is not supported.", - content::EvalJs(GetActiveWebContents(), kInvokePaymentRequest)); + content::EvalJs(GetActiveWebContents(), + getInvokePaymentRequestSnippet())); } #if defined(OS_ANDROID) @@ -59,7 +65,8 @@ // ExecJs starts executing JavaScript and immediately returns, not waiting for // any promise to return. - EXPECT_TRUE(content::ExecJs(GetActiveWebContents(), kInvokePaymentRequest)); + EXPECT_TRUE(content::ExecJs(GetActiveWebContents(), + getInvokePaymentRequestSnippet())); WaitForObservedEvent(); ASSERT_FALSE(test_controller()->app_descriptions().empty()); @@ -67,6 +74,53 @@ EXPECT_EQ("Stub label", test_controller()->app_descriptions().front().label); } +// canMakePayment() and hasEnrolledInstrument() should return false on platforms +// without a compatible authenticator. +IN_PROC_BROWSER_TEST_F(SecurePaymentConfirmationTest, + CanMakePayment_NoAuthenticator) { + test_controller()->SetHasAuthenticator(false); + NavigateTo("a.com", "/can_make_payment_checker.html"); + + { + std::string snippet = + base::StringPrintf("canMakePaymentForMethodData(%s)", kTestMethodData); + EXPECT_EQ("false", content::EvalJs(GetActiveWebContents(), snippet)); + } + { + std::string snippet = base::StringPrintf( + "hasEnrolledInstrumentForMethodData(%s)", kTestMethodData); + EXPECT_EQ("false", content::EvalJs(GetActiveWebContents(), snippet)); + } +} + +// canMakePayment() and hasEnrolledInstrument() should return true on platforms +// with a compatible authenticator regardless of the presence of payment +// credentials. +#if defined(OS_ANDROID) +// TODO(https://crbug.com/1110320): Implement SetHasAuthenticator() for Android, +// so this behavior can be tested on Android as well. +#define MAYBE_CanMakePayment_HasAuthenticator \ + DISABLED_CanMakePayment_HasAuthenticator +#else +#define MAYBE_CanMakePayment_HasAuthenticator CanMakePayment_HasAuthenticator +#endif // OS_ANDROID +IN_PROC_BROWSER_TEST_F(SecurePaymentConfirmationTest, + MAYBE_CanMakePayment_HasAuthenticator) { + test_controller()->SetHasAuthenticator(true); + NavigateTo("a.com", "/can_make_payment_checker.html"); + + { + std::string snippet = + base::StringPrintf("canMakePaymentForMethodData(%s)", kTestMethodData); + EXPECT_EQ("true", content::EvalJs(GetActiveWebContents(), snippet)); + } + { + std::string snippet = base::StringPrintf( + "hasEnrolledInstrumentForMethodData(%s)", kTestMethodData); + EXPECT_EQ("true", content::EvalJs(GetActiveWebContents(), snippet)); + } +} + // Intentionally do not enable the "SecurePaymentConfirmation" Blink runtime // feature. class SecurePaymentConfirmationDisabledTest @@ -80,7 +134,25 @@ // EvalJs waits for JavaScript promise to resolve. EXPECT_EQ( "The payment method \"secure-payment-confirmation\" is not supported.", - content::EvalJs(GetActiveWebContents(), kInvokePaymentRequest)); + content::EvalJs(GetActiveWebContents(), + getInvokePaymentRequestSnippet())); +} + +IN_PROC_BROWSER_TEST_F(SecurePaymentConfirmationDisabledTest, + CannotMakePayment) { + test_controller()->SetHasAuthenticator(true); + NavigateTo("a.com", "/can_make_payment_checker.html"); + + { + std::string snippet = + base::StringPrintf("canMakePaymentForMethodData(%s)", kTestMethodData); + EXPECT_EQ("false", content::EvalJs(GetActiveWebContents(), snippet)); + } + { + std::string snippet = base::StringPrintf( + "hasEnrolledInstrumentForMethodData(%s)", kTestMethodData); + EXPECT_EQ("false", content::EvalJs(GetActiveWebContents(), snippet)); + } } } // namespace
diff --git a/chrome/browser/policy/profile_policy_connector.cc b/chrome/browser/policy/profile_policy_connector.cc index bca0c3ae..91ec335 100644 --- a/chrome/browser/policy/profile_policy_connector.cc +++ b/chrome/browser/policy/profile_policy_connector.cc
@@ -73,6 +73,10 @@ &ProxiedPoliciesPropagatedWatcher::OnProviderUpdatePropagationTimedOut); } + ProxiedPoliciesPropagatedWatcher(const ProxiedPoliciesPropagatedWatcher&) = + delete; + ProxiedPoliciesPropagatedWatcher& operator=( + const ProxiedPoliciesPropagatedWatcher&) = delete; ~ProxiedPoliciesPropagatedWatcher() override { device_wide_policy_service_->RemoveProviderUpdateObserver(this); } @@ -108,8 +112,6 @@ const ConfigurationPolicyProvider* const source_policy_provider_; base::OnceClosure proxied_policies_propagated_callback_; base::OneShotTimer timeout_timer_; - - DISALLOW_COPY_AND_ASSIGN(ProxiedPoliciesPropagatedWatcher); }; } // namespace internal @@ -133,9 +135,9 @@ #endif // defined(OS_CHROMEOS) -ProfilePolicyConnector::ProfilePolicyConnector() {} +ProfilePolicyConnector::ProfilePolicyConnector() = default; -ProfilePolicyConnector::~ProfilePolicyConnector() {} +ProfilePolicyConnector::~ProfilePolicyConnector() = default; void ProfilePolicyConnector::Init( const user_manager::User* user,
diff --git a/chrome/browser/policy/profile_policy_connector.h b/chrome/browser/policy/profile_policy_connector.h index 53a6084..bc72ad1 100644 --- a/chrome/browser/policy/profile_policy_connector.h +++ b/chrome/browser/policy/profile_policy_connector.h
@@ -9,7 +9,6 @@ #include <string> #include <vector> -#include "base/macros.h" #include "base/memory/weak_ptr.h" #include "build/build_config.h" @@ -39,6 +38,8 @@ class ProfilePolicyConnector final { public: ProfilePolicyConnector(); + ProfilePolicyConnector(const ProfilePolicyConnector&) = delete; + ProfilePolicyConnector& operator=(const ProfilePolicyConnector&) = delete; ~ProfilePolicyConnector(); // |user| is only used in Chrome OS builds and should be set to nullptr @@ -164,8 +165,6 @@ std::unique_ptr<PolicyService> policy_service_; std::unique_ptr<bool> is_managed_override_; - - DISALLOW_COPY_AND_ASSIGN(ProfilePolicyConnector); }; } // namespace policy
diff --git a/chrome/browser/prefs/profile_pref_store_manager.cc b/chrome/browser/prefs/profile_pref_store_manager.cc index 7a071d9..c3af5e2b 100644 --- a/chrome/browser/prefs/profile_pref_store_manager.cc +++ b/chrome/browser/prefs/profile_pref_store_manager.cc
@@ -54,7 +54,7 @@ seed_(seed), legacy_device_id_(legacy_device_id) {} -ProfilePrefStoreManager::~ProfilePrefStoreManager() {} +ProfilePrefStoreManager::~ProfilePrefStoreManager() = default; // static void ProfilePrefStoreManager::RegisterProfilePrefs(
diff --git a/chrome/browser/prefs/profile_pref_store_manager.h b/chrome/browser/prefs/profile_pref_store_manager.h index 229a755a..9d47a526 100644 --- a/chrome/browser/prefs/profile_pref_store_manager.h +++ b/chrome/browser/prefs/profile_pref_store_manager.h
@@ -12,7 +12,6 @@ #include <vector> #include "base/files/file_path.h" -#include "base/macros.h" #include "base/memory/ref_counted.h" #include "base/sequenced_task_runner.h" #include "mojo/public/cpp/bindings/pending_remote.h" @@ -47,6 +46,8 @@ const std::string& seed, const std::string& legacy_device_id); + ProfilePrefStoreManager(const ProfilePrefStoreManager&) = delete; + ProfilePrefStoreManager& operator=(const ProfilePrefStoreManager&) = delete; ~ProfilePrefStoreManager(); static const bool kPlatformSupportsPreferenceTracking; @@ -125,8 +126,6 @@ const base::FilePath profile_path_; const std::string seed_; const std::string legacy_device_id_; - - DISALLOW_COPY_AND_ASSIGN(ProfilePrefStoreManager); }; #endif // CHROME_BROWSER_PREFS_PROFILE_PREF_STORE_MANAGER_H_
diff --git a/chrome/browser/privacy_budget/identifiability_study_state.cc b/chrome/browser/privacy_budget/identifiability_study_state.cc index f78acbec..aabfea5 100644 --- a/chrome/browser/privacy_budget/identifiability_study_state.cc +++ b/chrome/browser/privacy_budget/identifiability_study_state.cc
@@ -313,6 +313,10 @@ bool IdentifiabilityStudyState::ShouldRecordSurface( uint64_t source_id, blink::IdentifiableSurface surface) { + if (!blink::IdentifiabilityStudySettings::Get()->IsTypeAllowed( + blink::IdentifiableSurface::Type::kMeasuredSurface)) { + return false; + } return tracked_surfaces_.ShouldRecord(source_id, surface.ToUkmMetricHash()); }
diff --git a/chrome/browser/profiles/profile_activity_metrics_recorder.cc b/chrome/browser/profiles/profile_activity_metrics_recorder.cc index 839fe7cf..fac55348 100644 --- a/chrome/browser/profiles/profile_activity_metrics_recorder.cc +++ b/chrome/browser/profiles/profile_activity_metrics_recorder.cc
@@ -30,7 +30,7 @@ constexpr base::TimeDelta kLongTimeOfInactivity = base::TimeDelta::FromMinutes(30); -int GetMetricsBucketIndex(Profile* profile) { +int GetMetricsBucketIndex(const Profile* profile) { if (profile->IsGuestSession()) return 0; @@ -46,7 +46,7 @@ return entry->GetMetricsBucketIndex(); } -void RecordProfileSessionDuration(Profile* profile, +void RecordProfileSessionDuration(const Profile* profile, base::TimeDelta session_length) { if (!profile || session_length.InMinutes() <= 0) return; @@ -61,7 +61,7 @@ } } -void RecordBrowserActivation(Profile* profile) { +void RecordBrowserActivation(const Profile* profile) { DCHECK(profile); int profile_bucket = GetMetricsBucketIndex(profile); @@ -71,7 +71,7 @@ } } -void RecordUserAction(Profile* profile) { +void RecordUserAction(const Profile* profile) { if (!profile) return; @@ -89,7 +89,7 @@ .RecordProfilesState(); } -void RecordAccountMetrics(Profile* profile) { +void RecordAccountMetrics(const Profile* profile) { DCHECK(profile); ProfileAttributesEntry* entry;
diff --git a/chrome/browser/profiles/profile_activity_metrics_recorder.h b/chrome/browser/profiles/profile_activity_metrics_recorder.h index db7ce21b..96c3ff20 100644 --- a/chrome/browser/profiles/profile_activity_metrics_recorder.h +++ b/chrome/browser/profiles/profile_activity_metrics_recorder.h
@@ -8,7 +8,6 @@ #include <stddef.h> #include <string> -#include "base/macros.h" #include "base/metrics/user_metrics.h" #include "base/scoped_observer.h" #include "base/time/time.h" @@ -24,6 +23,10 @@ public metrics::DesktopSessionDurationTracker::Observer, public ProfileObserver { public: + ProfileActivityMetricsRecorder(const ProfileActivityMetricsRecorder&) = + delete; + ProfileActivityMetricsRecorder& operator=( + const ProfileActivityMetricsRecorder&) = delete; // Initializes a |ProfileActivityMetricsRecorder| object and starts // tracking/recording. static void Initialize(); @@ -54,8 +57,6 @@ base::ActionCallback action_callback_; ScopedObserver<Profile, ProfileObserver> profile_observer_{this}; - - DISALLOW_COPY_AND_ASSIGN(ProfileActivityMetricsRecorder); }; #endif // CHROME_BROWSER_PROFILES_PROFILE_ACTIVITY_METRICS_RECORDER_H_
diff --git a/chrome/browser/profiles/profile_destroyer.cc b/chrome/browser/profiles/profile_destroyer.cc index 6b6120a..33848ef 100644 --- a/chrome/browser/profiles/profile_destroyer.cc +++ b/chrome/browser/profiles/profile_destroyer.cc
@@ -183,7 +183,7 @@ content::RenderProcessHost* host) { TRACE_EVENT2("shutdown", "ProfileDestroyer::RenderProcessHostDestroyed", "profile", profile_, "render_process_host", host); - DCHECK(num_hosts_ > 0); + DCHECK_GT(num_hosts_, 0u); --num_hosts_; if (num_hosts_ == 0) { // Delay the destruction one step further in case other observers need to
diff --git a/chrome/browser/profiles/profile_destroyer.h b/chrome/browser/profiles/profile_destroyer.h index 560742b..30d8ee3 100644 --- a/chrome/browser/profiles/profile_destroyer.h +++ b/chrome/browser/profiles/profile_destroyer.h
@@ -9,7 +9,6 @@ #include <set> -#include "base/macros.h" #include "base/memory/ref_counted.h" #include "base/timer/timer.h" #include "content/public/browser/render_process_host_observer.h" @@ -30,6 +29,8 @@ // Ownership of the profile is passed to profile destroyer and the profile // should not be used after this call. static void DestroyProfileWhenAppropriate(Profile* const profile); + ProfileDestroyer(const ProfileDestroyer&) = delete; + ProfileDestroyer& operator=(const ProfileDestroyer&) = delete; private: friend class ProfileImpl; @@ -78,8 +79,6 @@ Profile* profile_; base::WeakPtrFactory<ProfileDestroyer> weak_ptr_factory_{this}; - - DISALLOW_COPY_AND_ASSIGN(ProfileDestroyer); }; #endif // CHROME_BROWSER_PROFILES_PROFILE_DESTROYER_H_
diff --git a/chrome/browser/profiles/profile_downloader.cc b/chrome/browser/profiles/profile_downloader.cc index 6eecd3e..75b524d 100644 --- a/chrome/browser/profiles/profile_downloader.cc +++ b/chrome/browser/profiles/profile_downloader.cc
@@ -43,10 +43,8 @@ ProfileDownloader::ProfileDownloader(ProfileDownloaderDelegate* delegate) : delegate_(delegate), - picture_status_(PICTURE_FAILED), identity_manager_(delegate_->GetIdentityManager()), - identity_manager_observer_(this), - waiting_for_account_info_(false) { + identity_manager_observer_(this) { DCHECK(delegate_); identity_manager_observer_.Add(identity_manager_); }
diff --git a/chrome/browser/profiles/profile_downloader.h b/chrome/browser/profiles/profile_downloader.h index d04312ef0..97459dc 100644 --- a/chrome/browser/profiles/profile_downloader.h +++ b/chrome/browser/profiles/profile_downloader.h
@@ -9,7 +9,6 @@ #include <string> #include "base/gtest_prod_util.h" -#include "base/macros.h" #include "base/scoped_observer.h" #include "base/sequence_checker.h" #include "base/strings/string16.h" @@ -40,6 +39,8 @@ }; explicit ProfileDownloader(ProfileDownloaderDelegate* delegate); + ProfileDownloader(const ProfileDownloader&) = delete; + ProfileDownloader& operator=(const ProfileDownloader&) = delete; ~ProfileDownloader() override; // Starts downloading profile information if the necessary authorization token @@ -122,13 +123,11 @@ std::unique_ptr<signin::AccessTokenFetcher> oauth2_access_token_fetcher_; AccountInfo account_info_; SkBitmap profile_picture_; - PictureStatus picture_status_; + PictureStatus picture_status_ = PICTURE_FAILED; signin::IdentityManager* identity_manager_; ScopedObserver<signin::IdentityManager, signin::IdentityManager::Observer> identity_manager_observer_; - bool waiting_for_account_info_; - - DISALLOW_COPY_AND_ASSIGN(ProfileDownloader); + bool waiting_for_account_info_ = false; }; #endif // CHROME_BROWSER_PROFILES_PROFILE_DOWNLOADER_H_
diff --git a/chrome/browser/profiles/profile_info_cache_observer.h b/chrome/browser/profiles/profile_info_cache_observer.h index 6bb2896..6b41bba7 100644 --- a/chrome/browser/profiles/profile_info_cache_observer.h +++ b/chrome/browser/profiles/profile_info_cache_observer.h
@@ -5,7 +5,6 @@ #ifndef CHROME_BROWSER_PROFILES_PROFILE_INFO_CACHE_OBSERVER_H_ #define CHROME_BROWSER_PROFILES_PROFILE_INFO_CACHE_OBSERVER_H_ -#include "base/macros.h" #include "base/strings/string16.h" #include "ui/gfx/image/image.h" @@ -17,7 +16,9 @@ // ProfileInfoCache. class ProfileInfoCacheObserver { public: - virtual ~ProfileInfoCacheObserver() {} + ProfileInfoCacheObserver(const ProfileInfoCacheObserver&) = delete; + ProfileInfoCacheObserver& operator=(const ProfileInfoCacheObserver&) = delete; + virtual ~ProfileInfoCacheObserver() = default; virtual void OnProfileAdded(const base::FilePath& profile_path) {} virtual void OnProfileWillBeRemoved(const base::FilePath& profile_path) {} @@ -37,9 +38,7 @@ const base::FilePath& profile_path) {} protected: - ProfileInfoCacheObserver() {} - - DISALLOW_COPY_AND_ASSIGN(ProfileInfoCacheObserver); + ProfileInfoCacheObserver() = default; }; #endif // CHROME_BROWSER_PROFILES_PROFILE_INFO_CACHE_OBSERVER_H_
diff --git a/chrome/browser/profiles/profile_info_cache_unittest.cc b/chrome/browser/profiles/profile_info_cache_unittest.cc index d32156b..93c533c 100644 --- a/chrome/browser/profiles/profile_info_cache_unittest.cc +++ b/chrome/browser/profiles/profile_info_cache_unittest.cc
@@ -8,6 +8,7 @@ #include <stdint.h> #include <algorithm> +#include <set> #include <vector> #include "base/bind.h"
diff --git a/chrome/browser/profiles/profile_info_cache_unittest.h b/chrome/browser/profiles/profile_info_cache_unittest.h index 183b58e..7d07a7bd9 100644 --- a/chrome/browser/profiles/profile_info_cache_unittest.h +++ b/chrome/browser/profiles/profile_info_cache_unittest.h
@@ -7,7 +7,6 @@ #include <set> -#include "base/macros.h" #include "chrome/browser/profiles/profile_info_cache_observer.h" #include "chrome/test/base/testing_profile_manager.h" #include "content/public/test/browser_task_environment.h" @@ -25,6 +24,9 @@ public: explicit ProfileNameVerifierObserver( TestingProfileManager* testing_profile_manager); + ProfileNameVerifierObserver(const ProfileNameVerifierObserver&) = delete; + ProfileNameVerifierObserver& operator=(const ProfileNameVerifierObserver&) = + delete; ~ProfileNameVerifierObserver() override; // ProfileInfoCacheObserver overrides: @@ -40,7 +42,6 @@ ProfileInfoCache* GetCache(); std::map<base::FilePath, base::string16> profile_names_; TestingProfileManager* testing_profile_manager_; - DISALLOW_COPY_AND_ASSIGN(ProfileNameVerifierObserver); }; class ProfileInfoCacheTest : public testing::Test {
diff --git a/chrome/browser/profiles/profile_metrics.cc b/chrome/browser/profiles/profile_metrics.cc index 7638db9..4de5028 100644 --- a/chrome/browser/profiles/profile_metrics.cc +++ b/chrome/browser/profiles/profile_metrics.cc
@@ -202,9 +202,7 @@ } void ProfileMetrics::LogProfileAddNewUser(ProfileAdd metric) { - DCHECK(metric < NUM_PROFILE_ADD_METRICS); - base::UmaHistogramEnumeration("Profile.AddNewUser", metric, - NUM_PROFILE_ADD_METRICS); + base::UmaHistogramEnumeration("Profile.AddNewUser", metric); base::UmaHistogramEnumeration("Profile.NetUserCount", ProfileNetUserCounts::ADD_NEW_USER); }
diff --git a/chrome/browser/profiles/profile_metrics.h b/chrome/browser/profiles/profile_metrics.h index 5719f0c1..618fedc 100644 --- a/chrome/browser/profiles/profile_metrics.h +++ b/chrome/browser/profiles/profile_metrics.h
@@ -32,15 +32,26 @@ class ProfileMetrics { public: - // Enum for counting the ways users were added. + // These values are persisted to logs. Entries should not be renumbered and + // numeric values should never be reused. enum ProfileAdd { - ADD_NEW_USER_ICON = 0, // User adds new user from icon menu - ADD_NEW_USER_MENU, // User adds new user from menu bar - ADD_NEW_USER_DIALOG, // User adds new user from create-profile dialog - ADD_NEW_USER_MANAGER, // User adds new user from User Manager - ADD_NEW_USER_LAST_DELETED, // Auto-created after deleting last user - NUM_PROFILE_ADD_METRICS + // User adds new user from icon menu -- no longer used + // ADD_NEW_USER_ICON = 0, + // User adds new user from menu bar + ADD_NEW_USER_MENU = 1, + // User adds new user from create-profile dialog + ADD_NEW_USER_DIALOG = 2, + // User adds new user from Profile Picker + ADD_NEW_PROFILE_PICKER = 3, + // Auto-created after deleting last user + ADD_NEW_USER_LAST_DELETED = 4, + // Created by the sign-in interception prompt + ADD_NEW_USER_SIGNIN_INTERCEPTION = 5, + // Created during the sync flow (to avoid clash with data in the existing + // profile) + ADD_NEW_USER_SYNC_FLOW = 6, + kMaxValue = ADD_NEW_USER_SYNC_FLOW }; enum ProfileDelete {
diff --git a/chrome/browser/resources/signin/profile_picker/manage_profiles_browser_proxy.js b/chrome/browser/resources/signin/profile_picker/manage_profiles_browser_proxy.js index b3ee8e70..bc026a7f 100644 --- a/chrome/browser/resources/signin/profile_picker/manage_profiles_browser_proxy.js +++ b/chrome/browser/resources/signin/profile_picker/manage_profiles_browser_proxy.js
@@ -22,6 +22,7 @@ * This is the data structure sent back and forth between C++ and JS. * @typedef {{ * colorId: number, + * color: number, * themeFrameColor: string, * themeShapeColor: string, * themeFrameTextColor: string, @@ -81,6 +82,17 @@ /** Loads Google sign in page.*/ loadSignInProfileCreationFlow() {} + + /** + * Creates local profile + * @param {string} profileName + * @param {number} profileColor + * @param {string} avatarUrl + * @param {boolean} isGeneric + * @param {boolean} createShortcut + */ + createProfile( + profileName, profileColor, avatarUrl, isGeneric, createShortcut) {} } /** @implements {ManageProfilesBrowserProxy} */ @@ -129,6 +141,14 @@ loadSignInProfileCreationFlow() { chrome.send('loadSignInProfileCreationFlow'); } + + /** @override */ + createProfile( + profileName, profileColor, avatarUrl, isGeneric, createShortcut) { + chrome.send( + 'createProfile', + [profileName, profileColor, avatarUrl, isGeneric, createShortcut]); + } } addSingletonGetter(ManageProfilesBrowserProxyImpl);
diff --git a/chrome/browser/resources/signin/profile_picker/profile_creation_flow/BUILD.gn b/chrome/browser/resources/signin/profile_picker/profile_creation_flow/BUILD.gn index 5c41f13..4dc5d2b 100644 --- a/chrome/browser/resources/signin/profile_picker/profile_creation_flow/BUILD.gn +++ b/chrome/browser/resources/signin/profile_picker/profile_creation_flow/BUILD.gn
@@ -30,11 +30,14 @@ deps = [ "..:manage_profiles_browser_proxy", "..:navigation_behavior", + "..:policy_helper", "//third_party/polymer/v3_0/components-chromium/polymer:polymer_bundled", + "//ui/webui/resources/cr_elements/cr_button:cr_button.m", "//ui/webui/resources/cr_elements/cr_checkbox:cr_checkbox.m", "//ui/webui/resources/cr_elements/cr_icon_button:cr_icon_button.m", "//ui/webui/resources/cr_elements/cr_input:cr_input.m", "//ui/webui/resources/js:load_time_data.m", + "//ui/webui/resources/js:web_ui_listener_behavior.m", ] }
diff --git a/chrome/browser/resources/signin/profile_picker/profile_creation_flow/local_profile_customization.html b/chrome/browser/resources/signin/profile_picker/profile_creation_flow/local_profile_customization.html index de922b51..6f5fbd30 100644 --- a/chrome/browser/resources/signin/profile_picker/profile_creation_flow/local_profile_customization.html +++ b/chrome/browser/resources/signin/profile_picker/profile_creation_flow/local_profile_customization.html
@@ -10,17 +10,58 @@ text-align: center; } + #wrapperContainer { + align-items: center; + display: flex; + height: calc(max(100vh, var(--view-min-size)) - + (var(--banner-height) + var(--avatar-size)/2 + var(--vertical-gap) + + var(--cr-button-height) + var(--footer-margin))); + justify-content: center; + margin-bottom: var(--vertical-gap); + margin-inline-end: 16px; + margin-inline-start: 16px; + margin-top: calc(var(--avatar-size)/2); + overflow: auto; + } + + #wrapperContainer::-webkit-scrollbar { + width: var(--scrollbar-width); + } + + /* Track */ + #wrapperContainer::-webkit-scrollbar-track { + border-radius: var(--scrollbar-width); + } + + /* Handle */ + #wrapperContainer::-webkit-scrollbar-thumb { + background: var(--scrollbar-background); + border-radius: var(--scrollbar-width); + } + + #wrapper > * { + flex-grow: 0; + flex-shrink: 0; + margin-top: var(--vertical-gap); + } + + #wrapper { + align-items: center; + display: flex; + flex-direction: column; + max-height: 100%; + width: 100%; + } + #nameInput { --cr-input-placeholder-color: rgba(var(--google-grey-900-rgb), .5); --cr-input-border-bottom: 1px solid var(--cr-secondary-text-color); height: 32px; - margin: calc(var(--avatar-size)/2 + var(--vertical-gap)) auto 0 auto; width: 300px; } #colorPicker { height: 220px; - margin: var(--vertical-gap) auto var(--vertical-gap) auto; width: 370px; } @@ -28,7 +69,11 @@ --cr-checkbox-label-color: var(--cr-secondary-text-color); --cr-checkbox-label-padding-start: 8px; height: 20px; - margin: auto; + left: 0; + margin-inline-end: auto; + margin-inline-start: auto; + position: absolute; + right: 0; width: fit-content; } @@ -36,6 +81,13 @@ display: none; } + #save { + display: flex; + margin-inline-end: var(--footer-margin); + margin-inline-start: auto; + width: 111px; + } + @media (prefers-color-scheme: dark) { #nameInput { --cr-input-placeholder-color: rgba(var(--google-grey-200-rgb), .5); @@ -55,17 +107,28 @@ <img class="avatar" src$="[[profileThemeInfo.themeGenericAvatar]]"> </div> -<cr-input id="nameInput" value="{{profileName_}}" pattern=".*\\S.*" - placeholder="$i18n{createProfileNamePlaceholder}" - auto-validate spellcheck="false"> -</cr-input> +<div id="wrapperContainer"> + <div id="wrapper"> + <cr-input id="nameInput" value="{{profileName_}}" pattern=".*\\S.*" + placeholder="$i18n{createProfileNamePlaceholder}" + auto-validate spellcheck="false"> + </cr-input> -<!-- TODO(crbug.com/1115301): Add color picker. --> -<div id="colorPicker" - style$="background-color:[[profileThemeInfo.themeFrameColor]]"> + <!-- TODO(crbug.com/1115301): Add color picker. --> + <div id="colorPicker" + style$="background-color:[[profileThemeInfo.themeFrameColor]]"> + </div> + </div> </div> -<cr-checkbox checked="{{createShortcut_}}" - hidden="[[!isProfileShortcutsEnabled_]]"> - $i18n{createDesktopShortcutLabel} -</cr-checkbox> +<div class="footer"> + <cr-checkbox checked="{{createShortcut_}}" + hidden="[[!isProfileShortcutsEnabled_]]"> + $i18n{createDesktopShortcutLabel} + </cr-checkbox> + + <cr-button id="save" class="action-button" on-click="onSaveClick_" + disabled="[[isSaveDisabled_(createInProgress_, profileName_)]]"> + $i18n{createProfileConfirm} + </cr-button> +</div>
diff --git a/chrome/browser/resources/signin/profile_picker/profile_creation_flow/local_profile_customization.js b/chrome/browser/resources/signin/profile_picker/profile_creation_flow/local_profile_customization.js index d6d1347..ae99a9b 100644 --- a/chrome/browser/resources/signin/profile_picker/profile_creation_flow/local_profile_customization.js +++ b/chrome/browser/resources/signin/profile_picker/profile_creation_flow/local_profile_customization.js
@@ -3,6 +3,7 @@ // found in the LICENSE file. import 'chrome://resources/cr_elements/cr_icon_button/cr_icon_button.m.js'; +import 'chrome://resources/cr_elements/cr_button/cr_button.m.js'; import 'chrome://resources/cr_elements/cr_input/cr_input.m.js'; import 'chrome://resources/cr_elements/cr_checkbox/cr_checkbox.m.js'; import 'chrome://resources/cr_elements/shared_vars_css.m.js'; @@ -10,16 +11,20 @@ import '../icons.js'; import {loadTimeData} from 'chrome://resources/js/load_time_data.m.js'; +import {WebUIListenerBehavior} from 'chrome://resources/js/web_ui_listener_behavior.m.js'; import {html, Polymer} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; -import {AutogeneratedThemeColorInfo} from '../manage_profiles_browser_proxy.js'; +import {AutogeneratedThemeColorInfo, ManageProfilesBrowserProxy, ManageProfilesBrowserProxyImpl} from '../manage_profiles_browser_proxy.js'; import {navigateToPreviousRoute} from '../navigation_behavior.js'; +import {isProfileCreationAllowed} from '../policy_helper.js'; Polymer({ is: 'local-profile-customization', _template: html`{__html_template__}`, + behaviors: [WebUIListenerBehavior], + properties: { /** @type {!AutogeneratedThemeColorInfo} */ profileThemeInfo: { @@ -52,6 +57,71 @@ type: Boolean, value: () => loadTimeData.getBoolean('profileShortcutsEnabled'), }, + + /** + * True if a profile is being created or imported. + * @private {boolean} + */ + createInProgress_: { + type: Boolean, + value: false, + }, + }, + + /** @private {?ManageProfilesBrowserProxy} */ + manageProfilesBrowserProxy_: null, + + /** @override */ + ready() { + this.sanityCheck_(); + this.manageProfilesBrowserProxy_ = + ManageProfilesBrowserProxyImpl.getInstance(); + this.addWebUIListener( + 'create-profile-finished', () => this.handleCreateProfileFinished_()); + }, + + /** + * @return {boolean} + * @private + */ + sanityCheck_() { + if (!isProfileCreationAllowed()) { + this.onClickBack_(); + return false; + } + return true; + }, + + /** + * Determining whether 'Save' button is disabled. + * @return {boolean} + * @private + */ + isSaveDisabled_() { + return this.createInProgress_ || !this.profileName_ || + !this.$.nameInput.validate(); + }, + + /** + * Handler for the 'Save' button click event. + * @param {!Event} event + * @private + */ + onSaveClick_(event) { + if (!this.sanityCheck_()) { + return; + } + + if (this.createInProgress_) { + return; + } + this.createInProgress_ = true; + const createShortcut = + this.isProfileShortcutsEnabled_ && this.createShortcut_; + // TODO(crbug.com/1115056): Support avatar selection. + this.manageProfilesBrowserProxy_.createProfile( + this.profileName_, this.profileThemeInfo.color, '', true, + createShortcut); }, /** @private */ @@ -64,5 +134,12 @@ reset_() { this.profileName_ = ''; this.createShortcut_ = true; + this.$.wrapper.scrollTop = 0; }, + + /** @private */ + handleCreateProfileFinished_() { + this.onClickBack_(); + this.createInProgress_ = false; + } });
diff --git a/chrome/browser/resources/signin/profile_picker/profile_creation_flow/shared_css.html b/chrome/browser/resources/signin/profile_picker/profile_creation_flow/shared_css.html index 916a334..28218f4d 100644 --- a/chrome/browser/resources/signin/profile_picker/profile_creation_flow/shared_css.html +++ b/chrome/browser/resources/signin/profile_picker/profile_creation_flow/shared_css.html
@@ -2,11 +2,12 @@ <style include="cr-icons profile-picker-shared"> :host { --avatar-size: 100px; + --banner-height: 244px; } #headerContainer { background-color: var(--theme-frame-color); - height: 244px; + height: var(--banner-height); position: relative; width: 100%; }
diff --git a/chrome/browser/resources/signin/profile_picker/profile_picker_main_view.html b/chrome/browser/resources/signin/profile_picker/profile_picker_main_view.html index 22722ca5..034bec2 100644 --- a/chrome/browser/resources/signin/profile_picker/profile_picker_main_view.html +++ b/chrome/browser/resources/signin/profile_picker/profile_picker_main_view.html
@@ -42,7 +42,6 @@ --grid-gutter: 24px; --profile-item-height:178px; --profile-item-width: 162px; - --scrollbar-width: 4px; align-items: center; display: grid; grid-column-gap: var(--grid-gutter); @@ -69,7 +68,7 @@ /* Handle */ .profiles-container::-webkit-scrollbar-thumb { - background: var(--google-grey-refresh-100); + background: var(--scrollbar-background); border-radius: var(--scrollbar-width); } @@ -97,21 +96,12 @@ --cr-icon-button-stroke-color: var(--google-grey-refresh-700); } - .footer { - bottom: 0; - display: flex; - font-size: var(--text-font-size); - margin-bottom: 40px; - position: absolute; - width: 100%; - } - .footer > * { background-color: rgba(255, 255, 255, .8); } #browseAsGuestButton { - margin-inline-start: 40px; + margin-inline-start: var(--footer-margin); } #browseAsGuestButton > iron-icon { @@ -122,7 +112,7 @@ --cr-checkbox-label-color: var(--cr-secondary-text-color); --cr-checkbox-label-padding-start: 8px; justify-content: flex-end; - margin-inline-end: 40px; + margin-inline-end: var(--footer-margin); margin-inline-start: auto; padding-inline-end: 5px; padding-inline-start: 5px; @@ -137,10 +127,6 @@ background: url(images/dark_mode_right_banner_image.svg); } - .profiles-container::-webkit-scrollbar-thumb { - background: var(--google-grey-800); - } - #addProfile { border-color: var(--google-grey-refresh-700); }
diff --git a/chrome/browser/resources/signin/profile_picker/profile_picker_shared_css.html b/chrome/browser/resources/signin/profile_picker/profile_picker_shared_css.html index 7ab5166..7881c9e 100644 --- a/chrome/browser/resources/signin/profile_picker/profile_picker_shared_css.html +++ b/chrome/browser/resources/signin/profile_picker/profile_picker_shared_css.html
@@ -2,6 +2,15 @@ <style> :host { --text-font-size: 1.16em; + --scrollbar-width: 4px; + --scrollbar-background: var(--google-grey-refresh-100); + --footer-margin: 40px; + } + + @media (prefers-color-scheme: dark) { + :host { + --scrollbar-background: var(--google-grey-800); + } } html { @@ -32,5 +41,14 @@ white-space: nowrap; width: 130px; } + + .footer { + bottom: 0; + display: flex; + font-size: var(--text-font-size); + margin-bottom: var(--footer-margin); + position: absolute; + width: 100%; + } </style> </template>
diff --git a/chrome/browser/signin/dice_browsertest.cc b/chrome/browser/signin/dice_browsertest.cc index bf2d4b1f..252e7f59 100644 --- a/chrome/browser/signin/dice_browsertest.cc +++ b/chrome/browser/signin/dice_browsertest.cc
@@ -18,6 +18,8 @@ #include "base/run_loop.h" #include "base/strings/string_number_conversions.h" #include "base/strings/stringprintf.h" +#include "base/test/scoped_feature_list.h" +#include "base/test/test_mock_time_task_runner.h" #include "base/threading/thread_task_runner_handle.h" #include "base/time/time.h" #include "build/build_config.h" @@ -35,6 +37,7 @@ #include "chrome/browser/signin/chrome_signin_client.h" #include "chrome/browser/signin/chrome_signin_client_factory.h" #include "chrome/browser/signin/chrome_signin_helper.h" +#include "chrome/browser/signin/dice_response_handler.h" #include "chrome/browser/signin/identity_manager_factory.h" #include "chrome/browser/signin/signin_util.h" #include "chrome/browser/sync/user_event_service_factory.h" @@ -110,6 +113,7 @@ const char kOAuth2TokenRevokeURL[] = "/o/oauth2/revoke"; const char kSecondaryEmail[] = "secondary_email@example.com"; const char kSigninURL[] = "/signin"; +const char kSigninWithOutageInDiceURL[] = "/signin/outage"; const char kSignoutURL[] = "/signout"; // Test response that does not complete synchronously. It must be unblocked by @@ -153,7 +157,8 @@ const base::RepeatingCallback<void(const std::string&)>& callback, const HttpRequest& request) { if (!net::test_server::ShouldHandle(request, kSigninURL) && - !net::test_server::ShouldHandle(request, kChromeSyncEndpointURL)) + !net::test_server::ShouldHandle(request, kChromeSyncEndpointURL) && + !net::test_server::ShouldHandle(request, kSigninWithOutageInDiceURL)) return nullptr; // Extract Dice request header. @@ -168,12 +173,21 @@ // Add the SIGNIN dice header. std::unique_ptr<BasicHttpResponse> http_response(new BasicHttpResponse); if (header_value != kNoDiceRequestHeader) { - http_response->AddCustomHeader( - kDiceResponseHeader, - base::StringPrintf( - "action=SIGNIN,authuser=1,id=%s,email=%s,authorization_code=%s", - signin::GetTestGaiaIdForEmail(main_email).c_str(), - main_email.c_str(), kAuthorizationCode)); + if (net::test_server::ShouldHandle(request, kSigninWithOutageInDiceURL)) { + http_response->AddCustomHeader( + kDiceResponseHeader, + base::StringPrintf("action=SIGNIN,authuser=1,id=%s,email=%s," + "no_authorization_code=true", + signin::GetTestGaiaIdForEmail(main_email).c_str(), + main_email.c_str())); + } else { + http_response->AddCustomHeader( + kDiceResponseHeader, + base::StringPrintf( + "action=SIGNIN,authuser=1,id=%s,email=%s,authorization_code=%s", + signin::GetTestGaiaIdForEmail(main_email).c_str(), + main_email.c_str(), kAuthorizationCode)); + } } // When hitting the Chrome Sync endpoint, redirect to kEnableSyncURL, which @@ -331,6 +345,7 @@ reconcilor_blocked_count_(0), reconcilor_unblocked_count_(0), reconcilor_started_count_(0) { + feature_list_.InitAndEnableFeature(kSupportOAuthOutageInDice); https_server_.RegisterDefaultHandler(base::BindRepeating( &FakeGaia::HandleSigninURL, main_email_, base::BindRepeating(&DiceBrowserTest::OnSigninRequest, @@ -601,6 +616,10 @@ EXPECT_EQ(count, token_revoked_count_); } + DiceResponseHandler* GetDiceResponseHandler() { + return DiceResponseHandler::GetForProfile(browser()->profile()); + } + const std::string main_email_; net::EmbeddedTestServer https_server_; bool enable_sync_requested_; @@ -612,6 +631,7 @@ int reconcilor_unblocked_count_; int reconcilor_started_count_; std::string dice_request_header_; + base::test::ScopedFeatureList feature_list_; // Unblocks the server responses. base::OnceClosure unblock_token_exchange_response_closure_; @@ -659,6 +679,34 @@ EXPECT_EQ(1, reconcilor_started_count_); } +// Checks that the account reconcilor is blocked when where was OAuth +// outage in Dice, and unblocked after the timeout. +IN_PROC_BROWSER_TEST_F(DiceBrowserTest, SupportOAuthOutageInDice) { + DiceResponseHandler* dice_response_handler = GetDiceResponseHandler(); + scoped_refptr<base::TestMockTimeTaskRunner> task_runner = + new base::TestMockTimeTaskRunner(); + dice_response_handler->SetTaskRunner(task_runner); + NavigateToURL(kSigninWithOutageInDiceURL); + // Check that the Dice request header was sent. + std::string client_id = GaiaUrls::GetInstance()->oauth2_chrome_client_id(); + EXPECT_EQ(base::StringPrintf("version=%s,client_id=%s,device_id=%s," + "signin_mode=all_accounts," + "signout_mode=show_confirmation", + signin::kDiceProtocolVersion, client_id.c_str(), + GetDeviceId().c_str()), + dice_request_header_); + // Check that the reconcilor was blocked and not unblocked before timeout. + EXPECT_EQ(1, reconcilor_blocked_count_); + EXPECT_EQ(0, reconcilor_unblocked_count_); + task_runner->FastForwardBy( + base::TimeDelta::FromHours(kLockAccountReconcilorTimeoutHours / 2)); + EXPECT_EQ(0, reconcilor_unblocked_count_); + task_runner->FastForwardBy( + base::TimeDelta::FromHours((kLockAccountReconcilorTimeoutHours + 1) / 2)); + // Check that the reconcilor was unblocked. + EXPECT_EQ(1, reconcilor_unblocked_count_); +} + // Checks that re-auth on Gaia triggers the fetch for a refresh token. IN_PROC_BROWSER_TEST_F(DiceBrowserTest, Reauth) { EXPECT_EQ(0, reconcilor_started_count_);
diff --git a/chrome/browser/signin/dice_response_handler.cc b/chrome/browser/signin/dice_response_handler.cc index f5ac5c21..9e772228 100644 --- a/chrome/browser/signin/dice_response_handler.cc +++ b/chrome/browser/signin/dice_response_handler.cc
@@ -262,6 +262,11 @@ lock_.reset(); } +void DiceResponseHandler::SetTaskRunner( + scoped_refptr<base::SequencedTaskRunner> task_runner) { + task_runner_ = std::move(task_runner); +} + void DiceResponseHandler::ProcessDiceSigninHeader( const std::string& gaia_id, const std::string& email, @@ -271,9 +276,14 @@ if (no_authorization_code) { if (base::FeatureList::IsEnabled(kSupportOAuthOutageInDice)) { lock_ = std::make_unique<AccountReconcilor::Lock>(account_reconcilor_); + if (!timer_) { + timer_ = std::make_unique<base::OneShotTimer>(); + if (task_runner_) + timer_->SetTaskRunner(task_runner_); + } // If there is already another lock, the timer will be reset and // we'll wait another full timeout. - timer_.Start( + timer_->Start( FROM_HERE, base::TimeDelta::FromHours(kLockAccountReconcilorTimeoutHours), base::BindOnce(&DiceResponseHandler::OnTimeoutUnlockReconcilor,
diff --git a/chrome/browser/signin/dice_response_handler.h b/chrome/browser/signin/dice_response_handler.h index 9b9724a..08eebc64 100644 --- a/chrome/browser/signin/dice_response_handler.h +++ b/chrome/browser/signin/dice_response_handler.h
@@ -12,6 +12,9 @@ #include "base/cancelable_callback.h" #include "base/files/file_path.h" #include "base/macros.h" +#include "base/memory/scoped_refptr.h" +#include "base/sequenced_task_runner.h" +#include "base/timer/timer.h" #include "components/keyed_service/core/keyed_service.h" #include "components/signin/core/browser/account_reconcilor.h" #include "components/signin/core/browser/signin_header_helper.h" @@ -79,6 +82,9 @@ // Returns the number of pending DiceTokenFetchers. Exposed for testing. size_t GetPendingDiceTokenFetchersCountForTesting() const; + // Sets |task_runner_| for testing. + void SetTaskRunner(scoped_refptr<base::SequencedTaskRunner> task_runner); + private: // Helper class to fetch a refresh token from an authorization code. class DiceTokenFetcher : public GaiaAuthConsumer { @@ -168,8 +174,8 @@ // Lock the account reconcilor for kLockAccountReconcilorTimeoutHours // when there was OAuth outage in Dice. std::unique_ptr<AccountReconcilor::Lock> lock_; - base::OneShotTimer timer_; - + std::unique_ptr<base::OneShotTimer> timer_; + scoped_refptr<base::SequencedTaskRunner> task_runner_; DISALLOW_COPY_AND_ASSIGN(DiceResponseHandler); };
diff --git a/chrome/browser/signin/dice_web_signin_interceptor.cc b/chrome/browser/signin/dice_web_signin_interceptor.cc index 9972a78e..d57df55 100644 --- a/chrome/browser/signin/dice_web_signin_interceptor.cc +++ b/chrome/browser/signin/dice_web_signin_interceptor.cc
@@ -18,6 +18,7 @@ #include "chrome/browser/profiles/profile_attributes_storage.h" #include "chrome/browser/profiles/profile_avatar_icon_util.h" #include "chrome/browser/profiles/profile_manager.h" +#include "chrome/browser/profiles/profile_metrics.h" #include "chrome/browser/signin/dice_intercepted_session_startup_helper.h" #include "chrome/browser/signin/dice_signed_in_profile_creator.h" #include "chrome/browser/signin/dice_web_signin_interceptor_factory.h" @@ -365,6 +366,8 @@ base::UmaHistogramTimes( "Signin.Intercept.ProfileCreationDuration", base::TimeTicks::Now() - profile_creation_start_time_); + ProfileMetrics::LogProfileAddNewUser( + ProfileMetrics::ADD_NEW_USER_SIGNIN_INTERCEPTION); if (!new_profile) { Reset();
diff --git a/chrome/browser/ui/android/strings/android_chrome_strings.grd b/chrome/browser/ui/android/strings/android_chrome_strings.grd index 2933879..f8e99ad 100644 --- a/chrome/browser/ui/android/strings/android_chrome_strings.grd +++ b/chrome/browser/ui/android/strings/android_chrome_strings.grd
@@ -1396,7 +1396,7 @@ </message> <!-- Sync strings in account management dialog --> - <message name="IDS_SYNC_ANDROID_MASTER_SYNC_DISABLED" desc="Message to show when Android master sync flag is disabled"> + <message name="IDS_SYNC_ANDROID_SYSTEM_SYNC_DISABLED" desc="Message to show when Android system-level sync flag is disabled"> Android system sync disabled </message> <message name="IDS_SYNC_IS_DISABLED" desc="Message to show when Chrome sync is disabled">
diff --git a/chrome/browser/ui/android/strings/android_chrome_strings_grd/IDS_SYNC_ANDROID_SYSTEM_SYNC_DISABLED.png.sha1 b/chrome/browser/ui/android/strings/android_chrome_strings_grd/IDS_SYNC_ANDROID_SYSTEM_SYNC_DISABLED.png.sha1 new file mode 100644 index 0000000..d4e831d --- /dev/null +++ b/chrome/browser/ui/android/strings/android_chrome_strings_grd/IDS_SYNC_ANDROID_SYSTEM_SYNC_DISABLED.png.sha1
@@ -0,0 +1 @@ +ccf962b83dff385259fccbbbfc129d1784343f38 \ No newline at end of file
diff --git a/chrome/browser/ui/app_list/search/mixer.cc b/chrome/browser/ui/app_list/search/mixer.cc index 8ff427b..83f98108 100644 --- a/chrome/browser/ui/app_list/search/mixer.cc +++ b/chrome/browser/ui/app_list/search/mixer.cc
@@ -45,8 +45,7 @@ // Used to group relevant providers together for mixing their results. class Mixer::Group { public: - Group(size_t max_results, double boost) - : max_results_(max_results), boost_(boost) {} + explicit Group(size_t max_results) : max_results_(max_results) {} ~Group() {} void AddProvider(SearchProvider* provider) { @@ -62,9 +61,8 @@ // We cannot rely on providers to give relevance scores in the range // [0.0, 1.0]. Clamp to that range. - const double relevance = - base::ClampToRange(result->relevance(), 0.0, 1.0); - results_.emplace_back(result.get(), relevance + boost_); + results_.emplace_back( + result.get(), base::ClampToRange(result->relevance(), 0.0, 1.0)); } } @@ -80,7 +78,6 @@ private: typedef std::vector<SearchProvider*> Providers; const size_t max_results_; - const double boost_; Providers providers_; // Not owned. SortedResults results_; @@ -102,8 +99,8 @@ } } -size_t Mixer::AddGroup(size_t max_results, double boost) { - groups_.push_back(std::make_unique<Group>(max_results, boost)); +size_t Mixer::AddGroup(size_t max_results) { + groups_.push_back(std::make_unique<Group>(max_results)); return groups_.size() - 1; }
diff --git a/chrome/browser/ui/app_list/search/mixer.h b/chrome/browser/ui/app_list/search/mixer.h index 296cee7f..908abd88 100644 --- a/chrome/browser/ui/app_list/search/mixer.h +++ b/chrome/browser/ui/app_list/search/mixer.h
@@ -43,9 +43,8 @@ // Adds a new mixer group. A "soft" maximum of |max_results| results will be // chosen from this group (if 0, will allow unlimited results from this // group). If there aren't enough results from all groups, more than - // |max_results| may be chosen from this group. Each result in the group will - // have its score increased by |boost|. Returns the group's group_id. - size_t AddGroup(size_t max_results, double boost); + // |max_results| may be chosen from this group. Returns the group's group_id. + size_t AddGroup(size_t max_results); // Associates a provider with a mixer group. void AddProviderToGroup(size_t group_id, SearchProvider* provider);
diff --git a/chrome/browser/ui/app_list/search/search_controller.cc b/chrome/browser/ui/app_list/search/search_controller.cc index afa84e34..773d76f 100644 --- a/chrome/browser/ui/app_list/search/search_controller.cc +++ b/chrome/browser/ui/app_list/search/search_controller.cc
@@ -143,8 +143,8 @@ result->InvokeAction(action_index, event_flags); } -size_t SearchController::AddGroup(size_t max_results, double boost) { - return mixer_->AddGroup(max_results, boost); +size_t SearchController::AddGroup(size_t max_results) { + return mixer_->AddGroup(max_results); } void SearchController::AddProvider(size_t group_id,
diff --git a/chrome/browser/ui/app_list/search/search_controller.h b/chrome/browser/ui/app_list/search/search_controller.h index cc7770e..9f98c03 100644 --- a/chrome/browser/ui/app_list/search/search_controller.h +++ b/chrome/browser/ui/app_list/search/search_controller.h
@@ -59,7 +59,7 @@ int event_flags); // Adds a new mixer group. See Mixer::AddGroup. - size_t AddGroup(size_t max_results, double boost = 0.0f); + size_t AddGroup(size_t max_results); // Takes ownership of |provider| and associates it with given mixer group. void AddProvider(size_t group_id, std::unique_ptr<SearchProvider> provider);
diff --git a/chrome/browser/ui/app_list/search/search_controller_factory.cc b/chrome/browser/ui/app_list/search/search_controller_factory.cc index 91dbab9..4fa52131e 100644 --- a/chrome/browser/ui/app_list/search/search_controller_factory.cc +++ b/chrome/browser/ui/app_list/search/search_controller_factory.cc
@@ -80,8 +80,6 @@ // TODO(wutao): Need UX spec. constexpr size_t kMaxSettingsShortcutResults = 6; -constexpr double kAppBoost = 8.0; - } // namespace std::unique_ptr<SearchController> CreateSearchController( @@ -96,16 +94,8 @@ // Set up rankers for search results. controller->InitializeRankers(); - // Add mixer groups. There are four main groups: answer card, apps - // and omnibox. Each group has a "soft" maximum number of results. However, if - // a query turns up very few results, the mixer may take more than this - // maximum from a particular group. - - // For the fullscreen app list, apps appear above the answer card, which - // appears above other results. Set boosts to |kAppBoost| for apps of all - // kinds, 5.0 for answer card, and otherwise 0.0. - size_t apps_group_id = controller->AddGroup(kMaxAppsGroupResults, kAppBoost); - size_t answer_card_group_id = controller->AddGroup(1, 5.0); + size_t apps_group_id = controller->AddGroup(kMaxAppsGroupResults); + size_t answer_card_group_id = controller->AddGroup(1); size_t omnibox_group_id = controller->AddGroup( ash::AppListConfig::instance().max_search_result_list_items()); @@ -127,8 +117,7 @@ // The Assistant search provider currently only contributes search results // when launcher chip integration is enabled. if (chromeos::assistant::features::IsLauncherChipIntegrationEnabled()) { - size_t assistant_group_id = - controller->AddGroup(kMaxAssistantResults, kAppBoost); + size_t assistant_group_id = controller->AddGroup(kMaxAssistantResults); controller->AddProvider(assistant_group_id, std::make_unique<AssistantSearchProvider>()); } @@ -146,7 +135,7 @@ if (app_list_features::IsAppReinstallZeroStateEnabled() && arc::IsArcAllowedForProfile(profile)) { size_t recommended_app_group_id = - controller->AddGroup(kMaxAppReinstallSearchResults, kAppBoost); + controller->AddGroup(kMaxAppReinstallSearchResults); controller->AddProvider(recommended_app_group_id, std::make_unique<ArcAppReinstallSearchProvider>( profile, kMaxAppReinstallSearchResults)); @@ -155,8 +144,7 @@ if (app_list_features::IsPlayStoreAppSearchEnabled()) { // Set same boost as apps group since Play store results are placed // with apps. - size_t playstore_api_group_id = - controller->AddGroup(kMaxPlayStoreResults, kAppBoost); + size_t playstore_api_group_id = controller->AddGroup(kMaxPlayStoreResults); controller->AddProvider( playstore_api_group_id, std::make_unique<ArcPlayStoreSearchProvider>(kMaxPlayStoreResults, @@ -164,8 +152,7 @@ } if (app_list_features::IsAppDataSearchEnabled()) { - size_t app_data_api_group_id = - controller->AddGroup(kMaxAppDataResults, kAppBoost); + size_t app_data_api_group_id = controller->AddGroup(kMaxAppDataResults); controller->AddProvider(app_data_api_group_id, std::make_unique<ArcAppDataSearchProvider>( kMaxAppDataResults, list_controller)); @@ -182,8 +169,7 @@ } if (arc::IsArcAllowedForProfile(profile)) { - size_t app_shortcut_group_id = - controller->AddGroup(kMaxAppShortcutResults, kAppBoost); + size_t app_shortcut_group_id = controller->AddGroup(kMaxAppShortcutResults); controller->AddProvider( app_shortcut_group_id, std::make_unique<ArcAppShortcutsSearchProvider>(
diff --git a/chrome/browser/ui/app_list/search/tests/mixer_unittest.cc b/chrome/browser/ui/app_list/search/tests/mixer_unittest.cc index a291e5d..6aec6267 100644 --- a/chrome/browser/ui/app_list/search/tests/mixer_unittest.cc +++ b/chrome/browser/ui/app_list/search/tests/mixer_unittest.cc
@@ -152,11 +152,9 @@ void CreateMixer() { mixer_ = std::make_unique<Mixer>(model_updater_.get()); - // TODO(warx): when fullscreen app list is default enabled, modify this test - // to test answer card/apps group having relevance boost. - size_t apps_group_id = mixer_->AddGroup(kMaxAppsGroupResults, 0.0); - size_t omnibox_group_id = mixer_->AddGroup(kMaxOmniboxResults, 0.0); - size_t playstore_group_id = mixer_->AddGroup(kMaxPlaystoreResults, 0.0); + size_t apps_group_id = mixer_->AddGroup(kMaxAppsGroupResults); + size_t omnibox_group_id = mixer_->AddGroup(kMaxOmniboxResults); + size_t playstore_group_id = mixer_->AddGroup(kMaxPlaystoreResults); mixer_->AddProviderToGroup(apps_group_id, providers_[0].get()); mixer_->AddProviderToGroup(omnibox_group_id, providers_[1].get());
diff --git a/chrome/browser/ui/passwords/password_generation_popup_controller_impl.cc b/chrome/browser/ui/passwords/password_generation_popup_controller_impl.cc index 67e67af..ed5fa4b 100644 --- a/chrome/browser/ui/passwords/password_generation_popup_controller_impl.cc +++ b/chrome/browser/ui/passwords/password_generation_popup_controller_impl.cc
@@ -93,7 +93,7 @@ } if (previous.get()) - previous->Hide(PopupHidingReason::kViewDestroyed); + previous->HideImpl(); PasswordGenerationPopupControllerImpl* controller = new PasswordGenerationPopupControllerImpl(bounds, ui_data, driver, @@ -160,7 +160,7 @@ PasswordSelected(true); return true; case ui::VKEY_ESCAPE: - Hide(PopupHidingReason::kUserAborted); + HideImpl(); return true; case ui::VKEY_RETURN: case ui::VKEY_TAB: @@ -199,7 +199,7 @@ // |this| can be destroyed here because GeneratedPasswordAccepted pops up // another UI and generates some event to close the dropdown. if (weak_this) - weak_this->Hide(PopupHidingReason::kAcceptSuggestion); + weak_this->HideImpl(); } void PasswordGenerationPopupControllerImpl::Show(GenerationUIState state) { @@ -218,7 +218,7 @@ // Treat popup as being hidden if creation fails. if (!view_) { - Hide(PopupHidingReason::kViewDestroyed); + HideImpl(); return; } key_press_handler_manager_->RegisterKeyPressHandler(base::BindRepeating( @@ -242,54 +242,44 @@ } void PasswordGenerationPopupControllerImpl::FrameWasScrolled() { - Hide(PopupHidingReason::kContentAreaMoved); + HideImpl(); } void PasswordGenerationPopupControllerImpl::GenerationElementLostFocus() { - Hide(PopupHidingReason::kFocusChanged); + HideImpl(); } void PasswordGenerationPopupControllerImpl::GeneratedPasswordRejected() { - Hide(PopupHidingReason::kUserAborted); + HideImpl(); } void PasswordGenerationPopupControllerImpl::WebContentsDestroyed() { - Hide(PopupHidingReason::kTabGone); + HideImpl(); } void PasswordGenerationPopupControllerImpl::DidFinishNavigation( content::NavigationHandle* navigation_handle) { if (navigation_handle->HasCommitted() && navigation_handle->IsInMainFrame() && !navigation_handle->IsSameDocument()) { - Hide(PopupHidingReason::kNavigation); + HideImpl(); } } #if !defined(OS_ANDROID) void PasswordGenerationPopupControllerImpl::OnZoomChanged( const zoom::ZoomController::ZoomChangedEventData& data) { - Hide(PopupHidingReason::kContentAreaMoved); + HideImpl(); } #endif // !defined(OS_ANDROID) -void PasswordGenerationPopupControllerImpl::Hide(PopupHidingReason reason) { - // Detach if the frame is still alive. - if (driver_) - key_press_handler_manager_->RemoveKeyPressHandler(); - - if (view_) - view_->Hide(); - - if (observer_) - observer_->OnPopupHidden(); - - delete this; +void PasswordGenerationPopupControllerImpl::Hide(PopupHidingReason) { + HideImpl(); } void PasswordGenerationPopupControllerImpl::ViewDestroyed() { view_ = nullptr; - Hide(PopupHidingReason::kViewDestroyed); + HideImpl(); } void PasswordGenerationPopupControllerImpl::SelectionCleared() { @@ -318,6 +308,20 @@ return base::i18n::IsRTL(); } +void PasswordGenerationPopupControllerImpl::HideImpl() { + // Detach if the frame is still alive. + if (driver_) + key_press_handler_manager_->RemoveKeyPressHandler(); + + if (view_) + view_->Hide(); + + if (observer_) + observer_->OnPopupHidden(); + + delete this; +} + PasswordGenerationPopupController::GenerationUIState PasswordGenerationPopupControllerImpl::state() const { return state_;
diff --git a/chrome/browser/ui/passwords/password_generation_popup_controller_impl.h b/chrome/browser/ui/passwords/password_generation_popup_controller_impl.h index 1cc9ed177..301134d 100644 --- a/chrome/browser/ui/passwords/password_generation_popup_controller_impl.h +++ b/chrome/browser/ui/passwords/password_generation_popup_controller_impl.h
@@ -127,7 +127,7 @@ private: class KeyPressRegistrator; // PasswordGenerationPopupController implementation: - void Hide(autofill::PopupHidingReason reason) override; + void Hide(autofill::PopupHidingReason) override; void ViewDestroyed() override; void SelectionCleared() override; void SetSelected() override; @@ -137,6 +137,8 @@ const gfx::RectF& element_bounds() const override; bool IsRTL() const override; + void HideImpl(); + GenerationUIState state() const override; bool password_selected() const override; const base::string16& password() const override;
diff --git a/chrome/browser/ui/views/profiles/profile_picker_view.cc b/chrome/browser/ui/views/profiles/profile_picker_view.cc index ee78fc1..ca3ecbb21 100644 --- a/chrome/browser/ui/views/profiles/profile_picker_view.cc +++ b/chrome/browser/ui/views/profiles/profile_picker_view.cc
@@ -16,6 +16,7 @@ #include "chrome/common/webui_url_constants.h" #include "chrome/grit/chromium_strings.h" #include "chrome/grit/google_chrome_strings.h" +#include "components/keep_alive_registry/keep_alive_types.h" #include "content/public/browser/context_menu_params.h" #include "content/public/browser/render_frame_host.h" #include "content/public/browser/render_widget_host_view.h" @@ -64,7 +65,8 @@ } ProfilePickerView::ProfilePickerView() - : web_view_(nullptr), initialized_(InitState::kNotInitialized) { + : keep_alive_(KeepAliveOrigin::USER_MANAGER_VIEW, + KeepAliveRestartOption::DISABLED) { SetHasWindowSizeControls(true); SetButtons(ui::DIALOG_BUTTON_NONE); SetTitle(IDS_PRODUCT_NAME);
diff --git a/chrome/browser/ui/views/profiles/profile_picker_view.h b/chrome/browser/ui/views/profiles/profile_picker_view.h index 25a9e88..55be4fb 100644 --- a/chrome/browser/ui/views/profiles/profile_picker_view.h +++ b/chrome/browser/ui/views/profiles/profile_picker_view.h
@@ -7,6 +7,7 @@ #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/profile_picker.h" +#include "components/keep_alive_registry/scoped_keep_alive.h" #include "content/public/browser/web_contents_delegate.h" #include "ui/views/controls/webview/webview.h" #include "ui/views/window/dialog_delegate.h" @@ -56,8 +57,9 @@ bool HandleContextMenu(content::RenderFrameHost* render_frame_host, const content::ContextMenuParams& params) override; - views::WebView* web_view_; - InitState initialized_; + ScopedKeepAlive keep_alive_; + views::WebView* web_view_ = nullptr; + InitState initialized_ = InitState::kNotInitialized; base::WeakPtrFactory<ProfilePickerView> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(ProfilePickerView);
diff --git a/chrome/browser/ui/webui/signin/dice_turn_sync_on_helper.cc b/chrome/browser/ui/webui/signin/dice_turn_sync_on_helper.cc index 9361592..63dd9c82 100644 --- a/chrome/browser/ui/webui/signin/dice_turn_sync_on_helper.cc +++ b/chrome/browser/ui/webui/signin/dice_turn_sync_on_helper.cc
@@ -22,6 +22,7 @@ #include "chrome/browser/policy/cloud/user_policy_signin_service.h" #include "chrome/browser/policy/cloud/user_policy_signin_service_factory.h" #include "chrome/browser/policy/profile_policy_connector.h" +#include "chrome/browser/profiles/profile_metrics.h" #include "chrome/browser/signin/account_id_from_account_info.h" #include "chrome/browser/signin/dice_signed_in_profile_creator.h" #include "chrome/browser/signin/identity_manager_factory.h" @@ -385,6 +386,7 @@ void DiceTurnSyncOnHelper::OnNewSignedInProfileCreated(Profile* new_profile) { DCHECK(dice_signed_in_profile_creator_); dice_signed_in_profile_creator_.reset(); + ProfileMetrics::LogProfileAddNewUser(ProfileMetrics::ADD_NEW_USER_SYNC_FLOW); if (!new_profile) { // TODO(atwilson): On error, unregister the client to release the DMToken
diff --git a/chrome/browser/ui/webui/signin/profile_picker_handler.cc b/chrome/browser/ui/webui/signin/profile_picker_handler.cc index 83ae226b..395984d 100644 --- a/chrome/browser/ui/webui/signin/profile_picker_handler.cc +++ b/chrome/browser/ui/webui/signin/profile_picker_handler.cc
@@ -16,6 +16,9 @@ #include "chrome/browser/profiles/profile_statistics_factory.h" #include "chrome/browser/profiles/profile_window.h" #include "chrome/browser/profiles/profiles_state.h" +#include "chrome/browser/signin/signin_util.h" +#include "chrome/browser/themes/theme_service.h" +#include "chrome/browser/themes/theme_service_factory.h" #include "chrome/browser/ui/browser_finder.h" #include "chrome/browser/ui/chrome_pages.h" #include "chrome/browser/ui/profile_picker.h" @@ -84,6 +87,10 @@ base::BindRepeating( &ProfilePickerHandler::HandleLoadSignInProfileCreationFlow, base::Unretained(this))); + web_ui()->RegisterMessageCallback( + "createProfile", + base::BindRepeating(&ProfilePickerHandler::HandleCreateProfile, + base::Unretained(this))); } void ProfilePickerHandler::OnJavascriptAllowed() { @@ -164,6 +171,7 @@ auto theme_colors = GetAutogeneratedThemeColors(color_info.color); base::Value dict(base::Value::Type::DICTIONARY); dict.SetIntKey("colorId", color_info.id); + dict.SetIntKey("color", color_info.color); dict.SetStringKey("themeFrameColor", color_utils::SkColorToRgbaString(theme_colors.frame_color)); dict.SetStringKey("themeShapeColor", color_utils::SkColorToRgbaString( @@ -180,6 +188,104 @@ ResolveJavascriptCallback(callback_id, std::move(dict)); } +void ProfilePickerHandler::HandleCreateProfile(const base::ListValue* args) { + // profileName, profileColor, avatarUrl, isGeneric, createShortcut + base::string16 profile_name; + int profile_color; + std::string avatar_url; + bool is_generic; + bool create_shortcut; + CHECK_EQ(5U, args->GetSize()); + args->GetString(0, &profile_name); + args->GetInteger(1, &profile_color); + args->GetString(2, &avatar_url); + args->GetBoolean(3, &is_generic); + args->GetBoolean(4, &create_shortcut); + DCHECK(base::IsStringASCII(avatar_url)); + base::TrimWhitespace(profile_name, base::TRIM_ALL, &profile_name); + CHECK(!profile_name.empty()); + if (is_generic) { + avatar_url = profiles::GetDefaultAvatarIconUrl( + profiles::GetPlaceholderAvatarIndex()); + } + +#ifndef NDEBUG + size_t icon_index; + DCHECK(profiles::IsDefaultAvatarIconUrl(avatar_url, &icon_index)); +#endif + + ProfileMetrics::LogProfileAddNewUser(ProfileMetrics::ADD_NEW_PROFILE_PICKER); + ProfileManager::CreateMultiProfileAsync( + profile_name, avatar_url, + base::BindRepeating(&ProfilePickerHandler::OnProfileCreated, + weak_factory_.GetWeakPtr(), SkColor(profile_color), + create_shortcut)); +} + +void ProfilePickerHandler::OnProfileCreated(SkColor profile_color, + bool create_shortcut, + Profile* profile, + Profile::CreateStatus status) { + switch (status) { + case Profile::CREATE_STATUS_LOCAL_FAIL: { + NOTREACHED() << "Local fail in creating new profile"; + break; + } + + case Profile::CREATE_STATUS_CREATED: + // Do nothing for an intermediate status. + return; + + case Profile::CREATE_STATUS_INITIALIZED: { + OnProfileCreationSuccess(profile_color, create_shortcut, profile); + break; + } + // User-initiated cancellation is handled in CancelProfileRegistration and + // does not call this callback. + case Profile::CREATE_STATUS_CANCELED: + case Profile::CREATE_STATUS_REMOTE_FAIL: + case Profile::MAX_CREATE_STATUS: { + NOTREACHED(); + break; + } + } + + if (IsJavascriptAllowed()) + FireWebUIListener("create-profile-finished", base::Value()); +} + +void ProfilePickerHandler::OnProfileCreationSuccess(SkColor profile_color, + bool create_shortcut, + Profile* profile) { + DCHECK(profile); + DCHECK(!signin_util::IsForceSigninEnabled()); + + // Apply a new color to the profile. + ThemeServiceFactory::GetForProfile(profile)->BuildAutogeneratedThemeFromColor( + profile_color); + + // Create shortcut if edded. + if (create_shortcut) { + DCHECK(ProfileShortcutManager::IsFeatureEnabled()); + ProfileShortcutManager* shortcut_manager = + g_browser_process->profile_manager()->profile_shortcut_manager(); + DCHECK(shortcut_manager); + if (shortcut_manager) + shortcut_manager->CreateProfileShortcut(profile->GetPath()); + } + + // Launch profile and close the picker. + profiles::OpenBrowserWindowForProfile( + base::Bind(&ProfilePickerHandler::OnSwitchToProfileComplete, + weak_factory_.GetWeakPtr(), false), + false, // Don't create a window if one already exists. + true, // Create a first run window. + false, // There is no need to unblock all extensions because we only open + // browser window if the Profile is not locked. Hence there is no + // extension blocked. + profile, Profile::CREATE_STATUS_INITIALIZED); +} + void ProfilePickerHandler::HandleRemoveProfile(const base::ListValue* args) { CHECK_EQ(1U, args->GetSize()); const base::Value& profile_path_value = args->GetList()[0];
diff --git a/chrome/browser/ui/webui/signin/profile_picker_handler.h b/chrome/browser/ui/webui/signin/profile_picker_handler.h index 68c66fd..cc8611f 100644 --- a/chrome/browser/ui/webui/signin/profile_picker_handler.h +++ b/chrome/browser/ui/webui/signin/profile_picker_handler.h
@@ -30,10 +30,13 @@ const base::ListValue* args); void HandleLaunchGuestProfile(const base::ListValue* args); void HandleAskOnStartupChanged(const base::ListValue* args); - void HandleGetNewProfileSuggestedThemeInfo(const base::ListValue* args); void HandleRemoveProfile(const base::ListValue* args); void HandleGetProfileStatistics(const base::ListValue* args); + + // TODO(crbug.com/1115056): Move to new handler for profile creation. void HandleLoadSignInProfileCreationFlow(const base::ListValue* args); + void HandleGetNewProfileSuggestedThemeInfo(const base::ListValue* args); + void HandleCreateProfile(const base::ListValue* args); void GatherProfileStatistics(Profile* profile); void OnProfileStatisticsReceived(base::FilePath profile_path, @@ -41,6 +44,13 @@ void OnSwitchToProfileComplete(bool open_settings, Profile* profile, Profile::CreateStatus profile_create_status); + void OnProfileCreated(SkColor profile_color, + bool create_shortcut, + Profile* profile, + Profile::CreateStatus status); + void OnProfileCreationSuccess(SkColor profile_color, + bool create_shortcut, + Profile* profile); void PushProfilesList(); base::Value GetProfilesList();
diff --git a/chrome/browser/ui/webui/signin/profile_picker_ui.cc b/chrome/browser/ui/webui/signin/profile_picker_ui.cc index 9e12d7b0..57084b9 100644 --- a/chrome/browser/ui/webui/signin/profile_picker_ui.cc +++ b/chrome/browser/ui/webui/signin/profile_picker_ui.cc
@@ -78,6 +78,8 @@ IDS_PROFILE_PICKER_PROFILE_CREATION_FLOW_LOCAL_PROFILE_CREATION_INPUT_NAME}, {"createDesktopShortcutLabel", IDS_PROFILE_PICKER_PROFILE_CREATION_FLOW_LOCAL_PROFILE_CREATION_SHORTCUT_TEXT}, + {"createProfileConfirm", + IDS_PROFILE_PICKER_PROFILE_CREATION_FLOW_LOCAL_PROFILE_CREATION_DONE}, }; AddLocalizedStringsBulk(html_source, kLocalizedStrings); html_source->AddBoolean("askOnStartup",
diff --git a/chrome/credential_provider/extension/BUILD.gn b/chrome/credential_provider/extension/BUILD.gn index e6b522bf..0c8563b 100644 --- a/chrome/credential_provider/extension/BUILD.gn +++ b/chrome/credential_provider/extension/BUILD.gn
@@ -2,7 +2,6 @@ # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. -import("//build/config/allocator.gni") import("//build/config/clang/clang.gni") import("//build/config/compiler/compiler.gni") import("//build/config/dcheck_always_on.gni")
diff --git a/chrome/credential_provider/gaiacp/BUILD.gn b/chrome/credential_provider/gaiacp/BUILD.gn index f40ba71..96b5e80d5 100644 --- a/chrome/credential_provider/gaiacp/BUILD.gn +++ b/chrome/credential_provider/gaiacp/BUILD.gn
@@ -3,7 +3,6 @@ # found in the LICENSE file. import("//base/win/embedded_i18n/generate_embedded_i18n.gni") -import("//build/config/allocator.gni") import("//build/config/clang/clang.gni") import("//build/config/compiler/compiler.gni") import("//build/config/dcheck_always_on.gni")
diff --git a/chrome/credential_provider/setup/BUILD.gn b/chrome/credential_provider/setup/BUILD.gn index a1aca30..b58775b 100644 --- a/chrome/credential_provider/setup/BUILD.gn +++ b/chrome/credential_provider/setup/BUILD.gn
@@ -2,7 +2,6 @@ # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. -import("//build/config/allocator.gni") import("//build/config/clang/clang.gni") import("//build/config/compiler/compiler.gni") import("//build/config/dcheck_always_on.gni")
diff --git a/chrome/test/BUILD.gn b/chrome/test/BUILD.gn index 070511a..2d706c7 100644 --- a/chrome/test/BUILD.gn +++ b/chrome/test/BUILD.gn
@@ -2,7 +2,6 @@ # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. -import("//build/config/allocator.gni") import("//build/config/buildflags_paint_preview.gni") import("//build/config/chrome_build.gni") import("//build/config/compiler/compiler.gni")
diff --git a/chrome/test/data/policy/policy_test_cases.json b/chrome/test/data/policy/policy_test_cases.json index a773a8c..160800ff 100644 --- a/chrome/test/data/policy/policy_test_cases.json +++ b/chrome/test/data/policy/policy_test_cases.json
@@ -1187,10 +1187,6 @@ ] }, - "EnableOriginBoundCerts": { - "note": "This policy is retired, see http://crbug.com/354749." - }, - "DisableSSLRecordSplitting": { "note": "This policy is retired, see https://bugs.chromium.org/p/chromium/issues/detail?id=485097#c17." }, @@ -1643,10 +1639,6 @@ ] }, - "ExtensionInstallListsMergeEnabled": { - "note": "This policy has no pref as it is only directly read by the policy system." - }, - "BlockUnsupportedFiletypes": { "os": ["win", "linux", "mac", "chromeos"], "policy_pref_mapping_test": [ @@ -3120,10 +3112,6 @@ "note": "This policy is retired, see http://crbug.com/178938." }, - "EnableMemoryInfo": { - "note": "This policy is retired, see http://crbug.com/350339." - }, - "DisablePrintPreview": { "os": ["win", "mac", "linux"], "policy_pref_mapping_test": [
diff --git a/chrome/test/data/webui/signin/test_manage_profiles_browser_proxy.js b/chrome/test/data/webui/signin/test_manage_profiles_browser_proxy.js index 59e9c80..5939713 100644 --- a/chrome/test/data/webui/signin/test_manage_profiles_browser_proxy.js +++ b/chrome/test/data/webui/signin/test_manage_profiles_browser_proxy.js
@@ -19,6 +19,7 @@ 'removeProfile', 'getProfileStatistics', 'loadSignInProfileCreationFlow', + 'createProfile', ]); } @@ -52,6 +53,7 @@ this.methodCalled('getNewProfileSuggestedThemeInfo'); return Promise.resolve({ colorId: 0, + color: 0, themeFrameColor: '', themeShapeColor: '', themeFrameTextColor: '', @@ -73,4 +75,12 @@ loadSignInProfileCreationFlow() { this.methodCalled('loadSignInProfileCreationFlow'); } + + /** @override */ + createProfile( + profileName, profileColor, avatarUrl, isGeneric, createShortcut) { + this.methodCalled( + 'createProfile', + [profileName, profileColor, avatarUrl, isGeneric, createShortcut]); + } }
diff --git a/chrome/updater/app/server/mac/service_delegate.mm b/chrome/updater/app/server/mac/service_delegate.mm index dc33469..49647b3 100644 --- a/chrome/updater/app/server/mac/service_delegate.mm +++ b/chrome/updater/app/server/mac/service_delegate.mm
@@ -226,8 +226,11 @@ VLOG(0) << "performControlTasks complete."; if (reply) reply(); + + _appServer->TaskCompleted(); })); + _appServer->TaskStarted(); _callbackRunner->PostTask( FROM_HERE, base::BindOnce(&updater::ControlService::Run, _service, std::move(cb)));
diff --git a/chrome/utility/importer/firefox_importer_unittest.cc b/chrome/utility/importer/firefox_importer_unittest.cc index cfcd6b77..74cf0e5 100644 --- a/chrome/utility/importer/firefox_importer_unittest.cc +++ b/chrome/utility/importer/firefox_importer_unittest.cc
@@ -58,6 +58,9 @@ // TODO(jschuh): Disabled on Win64 build. http://crbug.com/179688 #if defined(OS_WIN) && defined(ARCH_CPU_X86_64) #define MAYBE_NSS(x) DISABLED_##x +#elif defined(OS_MAC) && defined(ARCH_CPU_ARM_FAMILY) +// No NSS dylibs are available for arm64: https://crbug.com/1121685 +#define MAYBE_NSS(x) DISABLED_##x #else #define MAYBE_NSS(x) x #endif
diff --git a/chromeos/CHROMEOS_LKGM b/chromeos/CHROMEOS_LKGM index 77085de..df345be 100644 --- a/chromeos/CHROMEOS_LKGM +++ b/chromeos/CHROMEOS_LKGM
@@ -1 +1 @@ -13430.0.0 \ No newline at end of file +13431.0.0 \ No newline at end of file
diff --git a/chromeos/constants/chromeos_features.cc b/chromeos/constants/chromeos_features.cc index 214ec5b..f77fe82f 100644 --- a/chromeos/constants/chromeos_features.cc +++ b/chromeos/constants/chromeos_features.cc
@@ -242,6 +242,10 @@ const base::Feature kGesturePropertiesDBusService{ "GesturePropertiesDBusService", base::FEATURE_DISABLED_BY_DEFAULT}; +// Enables editing with handwriting gestures within the virtual keyboard. +const base::Feature kHandwritingGestureEditing{ + "HandwritingGestureEditing", base::FEATURE_DISABLED_BY_DEFAULT}; + // Enable the help app in the first run experience. This opens the help app // after the OOBE, and provides some extra functionality like a getting started // guide inside the app.
diff --git a/chromeos/constants/chromeos_features.h b/chromeos/constants/chromeos_features.h index 517f7b0a..9e6dd85 100644 --- a/chromeos/constants/chromeos_features.h +++ b/chromeos/constants/chromeos_features.h
@@ -103,6 +103,8 @@ extern const base::Feature kEnableImeSandbox; COMPONENT_EXPORT(CHROMEOS_CONSTANTS) extern const base::Feature kFsNosymfollow; COMPONENT_EXPORT(CHROMEOS_CONSTANTS) +extern const base::Feature kHandwritingGestureEditing; +COMPONENT_EXPORT(CHROMEOS_CONSTANTS) extern const base::Feature kGamepadVibration; COMPONENT_EXPORT(CHROMEOS_CONSTANTS) extern const base::Feature kGesturePropertiesDBusService;
diff --git a/chromeos/services/secure_channel/authenticator.h b/chromeos/services/secure_channel/authenticator.h index cc1f400..d8d0749 100644 --- a/chromeos/services/secure_channel/authenticator.h +++ b/chromeos/services/secure_channel/authenticator.h
@@ -39,10 +39,10 @@ // If the authentication protocol succeeds, then |secure_context| will be // contain the SecureContext used to securely exchange messages. Otherwise, it // will be null if the protocol fails. - typedef base::Callback<void(Result result, - std::unique_ptr<SecureContext> secure_context)> + typedef base::OnceCallback< + void(Result result, std::unique_ptr<SecureContext> secure_context)> AuthenticationCallback; - virtual void Authenticate(const AuthenticationCallback& callback) = 0; + virtual void Authenticate(AuthenticationCallback callback) = 0; }; } // namespace secure_channel
diff --git a/chromeos/services/secure_channel/device_to_device_authenticator.cc b/chromeos/services/secure_channel/device_to_device_authenticator.cc index 2e36856a..54414b4 100644 --- a/chromeos/services/secure_channel/device_to_device_authenticator.cc +++ b/chromeos/services/secure_channel/device_to_device_authenticator.cc
@@ -71,15 +71,15 @@ } void DeviceToDeviceAuthenticator::Authenticate( - const AuthenticationCallback& callback) { + AuthenticationCallback callback) { if (state_ != State::NOT_STARTED) { PA_LOG(ERROR) << "Authenticator was already used. Do not reuse this instance!"; - callback.Run(Result::FAILURE, nullptr); + std::move(callback).Run(Result::FAILURE, nullptr); return; } - callback_ = callback; + callback_ = std::move(callback); if (!connection_->IsConnected()) { Fail("Not connected to remote device", Result::DISCONNECTED); return; @@ -90,8 +90,8 @@ // Generate a key-pair for this individual session. state_ = State::GENERATING_SESSION_KEYS; secure_message_delegate_->GenerateKeyPair( - base::Bind(&DeviceToDeviceAuthenticator::OnKeyPairGenerated, - weak_ptr_factory_.GetWeakPtr())); + base::BindOnce(&DeviceToDeviceAuthenticator::OnKeyPairGenerated, + weak_ptr_factory_.GetWeakPtr())); } void DeviceToDeviceAuthenticator::OnKeyPairGenerated( @@ -109,8 +109,8 @@ helper_->CreateHelloMessage( public_key, connection_->remote_device().persistent_symmetric_key(), secure_message_delegate_.get(), - base::Bind(&DeviceToDeviceAuthenticator::OnHelloMessageCreated, - weak_ptr_factory_.GetWeakPtr())); + base::BindOnce(&DeviceToDeviceAuthenticator::OnHelloMessageCreated, + weak_ptr_factory_.GetWeakPtr())); } std::unique_ptr<base::OneShotTimer> DeviceToDeviceAuthenticator::CreateTimer() { @@ -163,8 +163,8 @@ helper_->CreateInitiatorAuthMessage( session_keys_, connection_->remote_device().persistent_symmetric_key(), responder_auth_message_, secure_message_delegate_.get(), - base::Bind(&DeviceToDeviceAuthenticator::OnInitiatorAuthCreated, - weak_ptr_factory_.GetWeakPtr())); + base::BindOnce(&DeviceToDeviceAuthenticator::OnInitiatorAuthCreated, + weak_ptr_factory_.GetWeakPtr())); } void DeviceToDeviceAuthenticator::OnInitiatorAuthCreated( @@ -192,7 +192,7 @@ weak_ptr_factory_.InvalidateWeakPtrs(); connection_->RemoveObserver(this); timer_.reset(); - callback_.Run(result, nullptr); + std::move(callback_).Run(result, nullptr); } void DeviceToDeviceAuthenticator::Succeed() { @@ -203,7 +203,7 @@ state_ = State::AUTHENTICATION_SUCCESS; connection_->RemoveObserver(this); - callback_.Run( + std::move(callback_).Run( Result::SUCCESS, std::make_unique<DeviceToDeviceSecureContext>( std::move(secure_message_delegate_), session_keys_, @@ -240,8 +240,8 @@ connection_->remote_device().persistent_symmetric_key(), local_session_private_key_, hello_message_, secure_message_delegate_.get(), - base::Bind(&DeviceToDeviceAuthenticator::OnResponderAuthValidated, - weak_ptr_factory_.GetWeakPtr())); + base::BindOnce(&DeviceToDeviceAuthenticator::OnResponderAuthValidated, + weak_ptr_factory_.GetWeakPtr())); } else { Fail("Unexpected message received"); }
diff --git a/chromeos/services/secure_channel/device_to_device_authenticator.h b/chromeos/services/secure_channel/device_to_device_authenticator.h index 68cc3be5..620b515 100644 --- a/chromeos/services/secure_channel/device_to_device_authenticator.h +++ b/chromeos/services/secure_channel/device_to_device_authenticator.h
@@ -80,7 +80,7 @@ ~DeviceToDeviceAuthenticator() override; // Authenticator: - void Authenticate(const AuthenticationCallback& callback) override; + void Authenticate(AuthenticationCallback callback) override; protected: // Creates a base::OneShotTimer instance. Exposed for testing.
diff --git a/chromeos/services/secure_channel/device_to_device_authenticator_unittest.cc b/chromeos/services/secure_channel/device_to_device_authenticator_unittest.cc index 6a9d163..f3a757114 100644 --- a/chromeos/services/secure_channel/device_to_device_authenticator_unittest.cc +++ b/chromeos/services/secure_channel/device_to_device_authenticator_unittest.cc
@@ -163,13 +163,13 @@ secure_message_delegate_->DeriveKey( remote_session_private_key_, local_session_public_key_, - base::Bind(&SaveStringResult, &session_symmetric_key_)); + base::BindOnce(&SaveStringResult, &session_symmetric_key_)); } // Begins authentication, and returns the [Hello] message sent from the local // device to the remote device. std::string BeginAuthentication() { - authenticator_.Authenticate(base::Bind( + authenticator_.Authenticate(base::BindOnce( &SecureChannelDeviceToDeviceAuthenticatorTest::OnAuthenticationResult, base::Unretained(this))); @@ -182,8 +182,8 @@ DeviceToDeviceResponderOperations::ValidateHelloMessage( hello_message, remote_device_.persistent_symmetric_key(), secure_message_delegate_, - base::Bind(&SaveValidateHelloMessageResult, &validated, - &local_session_public_key)); + base::BindOnce(&SaveValidateHelloMessageResult, &validated, + &local_session_public_key)); EXPECT_TRUE(validated); EXPECT_EQ(local_session_public_key_, local_session_public_key); @@ -202,7 +202,7 @@ hello_message, remote_session_public_key_, remote_session_private_key_, remote_device_private_key, remote_device_.persistent_symmetric_key(), secure_message_delegate_, - base::Bind(&SaveStringResult, &responder_auth_message)); + base::BindOnce(&SaveStringResult, &responder_auth_message)); EXPECT_FALSE(responder_auth_message.empty()); WireMessage wire_message(responder_auth_message, @@ -264,7 +264,7 @@ initiator_auth, SessionKeys(session_symmetric_key_), remote_device_.persistent_symmetric_key(), responder_auth_message, secure_message_delegate_, - base::Bind(&SaveBooleanResult, &initiator_auth_validated)); + base::BindOnce(&SaveBooleanResult, &initiator_auth_validated)); ASSERT_TRUE(initiator_auth_validated); } @@ -304,7 +304,7 @@ connection_.Disconnect(); EXPECT_CALL(*this, OnAuthenticationResultProxy(Authenticator::Result::DISCONNECTED)); - authenticator_.Authenticate(base::Bind( + authenticator_.Authenticate(base::BindOnce( &SecureChannelDeviceToDeviceAuthenticatorTest::OnAuthenticationResult, base::Unretained(this))); EXPECT_FALSE(secure_context_); @@ -314,7 +314,7 @@ connection_.set_connection_blocked(true); EXPECT_CALL(*this, OnAuthenticationResultProxy(Authenticator::Result::FAILURE)); - authenticator_.Authenticate(base::Bind( + authenticator_.Authenticate(base::BindOnce( &SecureChannelDeviceToDeviceAuthenticatorTest::OnAuthenticationResult, base::Unretained(this))); EXPECT_FALSE(secure_context_);
diff --git a/chromeos/services/secure_channel/device_to_device_initiator_helper.cc b/chromeos/services/secure_channel/device_to_device_initiator_helper.cc index b64ccc5..a6f1fd4 100644 --- a/chromeos/services/secure_channel/device_to_device_initiator_helper.cc +++ b/chromeos/services/secure_channel/device_to_device_initiator_helper.cc
@@ -38,13 +38,13 @@ const std::string& session_public_key, const std::string& persistent_symmetric_key, multidevice::SecureMessageDelegate* secure_message_delegate, - const MessageCallback& callback) { + MessageCallback callback) { // Decode public key into the |initator_hello| proto. securegcm::InitiatorHello initiator_hello; if (!initiator_hello.mutable_public_dh_key()->ParseFromString( session_public_key)) { PA_LOG(ERROR) << "Unable to parse user's public key"; - callback.Run(std::string()); + std::move(callback).Run(std::string()); return; } initiator_hello.set_protocol_version(kD2DProtocolVersion); @@ -60,7 +60,8 @@ create_options.signature_scheme = securemessage::HMAC_SHA256; initiator_hello.SerializeToString(&create_options.public_metadata); secure_message_delegate->CreateSecureMessage( - kPayloadFiller, persistent_symmetric_key, create_options, callback); + kPayloadFiller, persistent_symmetric_key, create_options, + std::move(callback)); } void DeviceToDeviceInitiatorHelper::ValidateResponderAuthMessage( @@ -70,7 +71,7 @@ const std::string& session_private_key, const std::string& hello_message, multidevice::SecureMessageDelegate* secure_message_delegate, - const ValidateResponderAuthCallback& callback) { + ValidateResponderAuthCallback callback) { // The [Responder Auth] message has the structure: // { // header: <responder_public_key>, @@ -91,8 +92,8 @@ ValidateResponderAuthMessageContext context( responder_auth_message, persistent_responder_public_key, persistent_symmetric_key, session_private_key, hello_message, - secure_message_delegate, callback); - BeginResponderAuthValidation(context); + secure_message_delegate); + BeginResponderAuthValidation(context, std::move(callback)); } void DeviceToDeviceInitiatorHelper::CreateInitiatorAuthMessage( @@ -100,7 +101,7 @@ const std::string& persistent_symmetric_key, const std::string& responder_auth_message, multidevice::SecureMessageDelegate* secure_message_delegate, - const MessageCallback& callback) { + MessageCallback callback) { // The [Initiator Auth] message has the structure: // { // header: Sig(payload1, session_symmetric_key) @@ -119,10 +120,10 @@ create_options.associated_data = responder_auth_message; secure_message_delegate->CreateSecureMessage( kPayloadFiller, persistent_symmetric_key, create_options, - base::Bind( + base::BindOnce( &DeviceToDeviceInitiatorHelper::OnInnerMessageCreatedForInitiatorAuth, weak_ptr_factory_.GetWeakPtr(), session_keys, secure_message_delegate, - callback)); + std::move(callback))); } DeviceToDeviceInitiatorHelper::ValidateResponderAuthMessageContext :: @@ -132,15 +133,13 @@ const std::string& persistent_symmetric_key, const std::string& session_private_key, const std::string& hello_message, - multidevice::SecureMessageDelegate* secure_message_delegate, - const ValidateResponderAuthCallback& callback) + multidevice::SecureMessageDelegate* secure_message_delegate) : responder_auth_message(responder_auth_message), persistent_responder_public_key(persistent_responder_public_key), persistent_symmetric_key(persistent_symmetric_key), session_private_key(session_private_key), hello_message(hello_message), - secure_message_delegate(secure_message_delegate), - callback(callback) {} + secure_message_delegate(secure_message_delegate) {} DeviceToDeviceInitiatorHelper::ValidateResponderAuthMessageContext :: ValidateResponderAuthMessageContext( @@ -151,7 +150,6 @@ session_private_key(other.session_private_key), hello_message(other.hello_message), secure_message_delegate(other.secure_message_delegate), - callback(other.callback), responder_session_public_key(other.responder_session_public_key), session_symmetric_key(other.session_symmetric_key) {} @@ -161,11 +159,11 @@ void DeviceToDeviceInitiatorHelper::OnInnerMessageCreatedForInitiatorAuth( const SessionKeys& session_keys, multidevice::SecureMessageDelegate* secure_message_delegate, - const DeviceToDeviceInitiatorHelper::MessageCallback& callback, + DeviceToDeviceInitiatorHelper::MessageCallback callback, const std::string& inner_message) { if (inner_message.empty()) { PA_LOG(VERBOSE) << "Failed to create inner message for [Initiator Auth]."; - callback.Run(std::string()); + std::move(callback).Run(std::string()); return; } @@ -185,11 +183,12 @@ gcm_metadata.SerializeToString(&create_options.public_metadata); secure_message_delegate->CreateSecureMessage( device_to_device_message.SerializeAsString(), - session_keys.initiator_encode_key(), create_options, callback); + session_keys.initiator_encode_key(), create_options, std::move(callback)); } void DeviceToDeviceInitiatorHelper::BeginResponderAuthValidation( - ValidateResponderAuthMessageContext context) { + ValidateResponderAuthMessageContext context, + ValidateResponderAuthCallback callback) { // Parse the encrypted SecureMessage so we can get plaintext data from the // header. Note that the payload will be encrypted. securemessage::SecureMessage encrypted_message; @@ -197,7 +196,7 @@ if (!encrypted_message.ParseFromString(context.responder_auth_message) || !header_and_body.ParseFromString(encrypted_message.header_and_body())) { PA_LOG(WARNING) << "Failed to parse [Responder Hello] message"; - context.callback.Run(false, SessionKeys()); + std::move(callback).Run(false, SessionKeys()); return; } @@ -210,7 +209,7 @@ gcm_metadata.version() != kGcmMetadataVersion) { PA_LOG(WARNING) << "Failed to validate cryptauth::GcmMetadata in " << "[Responder Auth] header."; - context.callback.Run(false, SessionKeys()); + std::move(callback).Run(false, SessionKeys()); return; } @@ -221,19 +220,21 @@ &context.responder_session_public_key)) { PA_LOG(VERBOSE) << "Failed to extract responder session public key in " << "[Responder Auth] header."; - context.callback.Run(false, SessionKeys()); + std::move(callback).Run(false, SessionKeys()); return; } // Perform a Diffie-Helmann key exchange to get the session symmetric key. context.secure_message_delegate->DeriveKey( context.session_private_key, context.responder_session_public_key, - base::Bind(&DeviceToDeviceInitiatorHelper::OnSessionSymmetricKeyDerived, - weak_ptr_factory_.GetWeakPtr(), context)); + base::BindOnce( + &DeviceToDeviceInitiatorHelper::OnSessionSymmetricKeyDerived, + weak_ptr_factory_.GetWeakPtr(), context, std::move(callback))); } void DeviceToDeviceInitiatorHelper::OnSessionSymmetricKeyDerived( ValidateResponderAuthMessageContext context, + ValidateResponderAuthCallback callback, const std::string& session_symmetric_key) { context.session_symmetric_key = session_symmetric_key; @@ -244,19 +245,21 @@ context.secure_message_delegate->UnwrapSecureMessage( context.responder_auth_message, SessionKeys(session_symmetric_key).responder_encode_key(), unwrap_options, - base::Bind(&DeviceToDeviceInitiatorHelper:: - OnOuterMessageUnwrappedForResponderAuth, - weak_ptr_factory_.GetWeakPtr(), context)); + base::BindOnce(&DeviceToDeviceInitiatorHelper:: + OnOuterMessageUnwrappedForResponderAuth, + weak_ptr_factory_.GetWeakPtr(), context, + std::move(callback))); } void DeviceToDeviceInitiatorHelper::OnOuterMessageUnwrappedForResponderAuth( const ValidateResponderAuthMessageContext& context, + ValidateResponderAuthCallback callback, bool verified, const std::string& payload, const securemessage::Header& header) { if (!verified) { PA_LOG(VERBOSE) << "Failed to unwrap outer [Responder Auth] message."; - context.callback.Run(false, SessionKeys()); + std::move(callback).Run(false, SessionKeys()); return; } @@ -265,7 +268,7 @@ if (!device_to_device_message.ParseFromString(payload) || device_to_device_message.sequence_number() != 1) { PA_LOG(VERBOSE) << "Failed to validate DeviceToDeviceMessage payload."; - context.callback.Run(false, SessionKeys()); + std::move(callback).Run(false, SessionKeys()); return; } @@ -278,19 +281,21 @@ context.secure_message_delegate->UnwrapSecureMessage( device_to_device_message.message(), context.persistent_symmetric_key, unwrap_options, - base::Bind(&DeviceToDeviceInitiatorHelper:: - OnMiddleMessageUnwrappedForResponderAuth, - weak_ptr_factory_.GetWeakPtr(), context)); + base::BindOnce(&DeviceToDeviceInitiatorHelper:: + OnMiddleMessageUnwrappedForResponderAuth, + weak_ptr_factory_.GetWeakPtr(), context, + std::move(callback))); } void DeviceToDeviceInitiatorHelper::OnMiddleMessageUnwrappedForResponderAuth( const ValidateResponderAuthMessageContext& context, + ValidateResponderAuthCallback callback, bool verified, const std::string& payload, const securemessage::Header& header) { if (!verified) { PA_LOG(VERBOSE) << "Failed to unwrap middle [Responder Auth] message."; - context.callback.Run(false, SessionKeys()); + std::move(callback).Run(false, SessionKeys()); return; } @@ -302,14 +307,16 @@ unwrap_options.associated_data = context.hello_message; context.secure_message_delegate->UnwrapSecureMessage( payload, context.persistent_responder_public_key, unwrap_options, - base::Bind(&DeviceToDeviceInitiatorHelper:: - OnInnerMessageUnwrappedForResponderAuth, - weak_ptr_factory_.GetWeakPtr(), context)); + base::BindOnce(&DeviceToDeviceInitiatorHelper:: + OnInnerMessageUnwrappedForResponderAuth, + weak_ptr_factory_.GetWeakPtr(), context, + std::move(callback))); } // Called after the inner-most layer of [Responder Auth] is unwrapped. void DeviceToDeviceInitiatorHelper::OnInnerMessageUnwrappedForResponderAuth( const ValidateResponderAuthMessageContext& context, + ValidateResponderAuthCallback callback, bool verified, const std::string& payload, const securemessage::Header& header) { @@ -324,11 +331,11 @@ PA_LOG(WARNING) << "Failed to validate cryptauth::GcmMetadata in inner-most " << "[Responder Auth] message."; - context.callback.Run(false, SessionKeys()); + std::move(callback).Run(false, SessionKeys()); return; } - context.callback.Run(verified, SessionKeys(context.session_symmetric_key)); + std::move(callback).Run(verified, SessionKeys(context.session_symmetric_key)); } } // namespace secure_channel
diff --git a/chromeos/services/secure_channel/device_to_device_initiator_helper.h b/chromeos/services/secure_channel/device_to_device_initiator_helper.h index a016a4a..dedbf010 100644 --- a/chromeos/services/secure_channel/device_to_device_initiator_helper.h +++ b/chromeos/services/secure_channel/device_to_device_initiator_helper.h
@@ -46,13 +46,13 @@ public: // Callback for operations that create a message. Invoked with the serialized // SecureMessage upon success or the empty string upon failure. - typedef base::Callback<void(const std::string&)> MessageCallback; + typedef base::OnceCallback<void(const std::string&)> MessageCallback; // Callback for ValidateResponderAuthMessage. The first argument will be // called with the validation outcome. If validation succeeded, then the // second argument will contain the session symmetric key derived from the // [Responder Auth] message. - typedef base::Callback<void(bool, const SessionKeys&)> + typedef base::OnceCallback<void(bool, const SessionKeys&)> ValidateResponderAuthCallback; DeviceToDeviceInitiatorHelper(); @@ -71,7 +71,7 @@ const std::string& session_public_key, const std::string& persistent_symmetric_key, multidevice::SecureMessageDelegate* secure_message_delegate, - const MessageCallback& callback); + MessageCallback callback); // Validates that the [Responder Auth] message, received from the responder, // is properly signed and encrypted. @@ -97,7 +97,7 @@ const std::string& session_private_key, const std::string& hello_message, multidevice::SecureMessageDelegate* secure_message_delegate, - const ValidateResponderAuthCallback& callback); + ValidateResponderAuthCallback callback); // Creates the [Initiator Auth] message, which allows the responder to // authenticate the initiator: @@ -115,7 +115,7 @@ const std::string& persistent_symmetric_key, const std::string& responder_auth_message, multidevice::SecureMessageDelegate* secure_message_delegate, - const MessageCallback& callback); + MessageCallback callback); private: // Helper struct containing all the context needed to validate the @@ -127,8 +127,7 @@ const std::string& persistent_symmetric_key, const std::string& session_private_key, const std::string& hello_message, - multidevice::SecureMessageDelegate* secure_message_delegate, - const ValidateResponderAuthCallback& callback); + multidevice::SecureMessageDelegate* secure_message_delegate); ValidateResponderAuthMessageContext( const ValidateResponderAuthMessageContext& other); ~ValidateResponderAuthMessageContext(); @@ -139,23 +138,24 @@ std::string session_private_key; std::string hello_message; multidevice::SecureMessageDelegate* secure_message_delegate; - ValidateResponderAuthCallback callback; std::string responder_session_public_key; std::string session_symmetric_key; }; // Begins the [Responder Auth] validation flow by validating the header. - void BeginResponderAuthValidation( - ValidateResponderAuthMessageContext context); + void BeginResponderAuthValidation(ValidateResponderAuthMessageContext context, + ValidateResponderAuthCallback callback); // Called after the session symmetric key is derived, so now we can unwrap the // outer message of [Responder Auth]. void OnSessionSymmetricKeyDerived(ValidateResponderAuthMessageContext context, + ValidateResponderAuthCallback callback, const std::string& session_symmetric_key); // Called after the outer-most layer of [Responder Auth] is unwrapped. void OnOuterMessageUnwrappedForResponderAuth( const ValidateResponderAuthMessageContext& context, + ValidateResponderAuthCallback callback, bool verified, const std::string& payload, const securemessage::Header& header); @@ -163,6 +163,7 @@ // Called after the middle layer of [Responder Auth] is unwrapped. void OnMiddleMessageUnwrappedForResponderAuth( const ValidateResponderAuthMessageContext& context, + ValidateResponderAuthCallback callback, bool verified, const std::string& payload, const securemessage::Header& header); @@ -171,13 +172,14 @@ void OnInnerMessageCreatedForInitiatorAuth( const SessionKeys& session_keys, multidevice::SecureMessageDelegate* secure_message_delegate, - const DeviceToDeviceInitiatorHelper::MessageCallback& callback, + DeviceToDeviceInitiatorHelper::MessageCallback callback, const std::string& inner_message); // Callback for CreateInitiatorAuthMessage(), after the inner message is // created. void OnInnerMessageUnwrappedForResponderAuth( const ValidateResponderAuthMessageContext& context, + ValidateResponderAuthCallback callback, bool verified, const std::string& payload, const securemessage::Header& header);
diff --git a/chromeos/services/secure_channel/device_to_device_operations_unittest.cc b/chromeos/services/secure_channel/device_to_device_operations_unittest.cc index 0f987f7..ba1d965 100644 --- a/chromeos/services/secure_channel/device_to_device_operations_unittest.cc +++ b/chromeos/services/secure_channel/device_to_device_operations_unittest.cc
@@ -92,7 +92,7 @@ // Note: FakeSecureMessageDelegate functions are synchronous. secure_message_delegate_.DeriveKey( local_session_private_key_, remote_session_public_key_, - base::Bind(&SaveMessageResult, &session_symmetric_key_)); + base::BindOnce(&SaveMessageResult, &session_symmetric_key_)); session_keys_ = SessionKeys(session_symmetric_key_); persistent_symmetric_key_ = "persistent symmetric key"; @@ -103,10 +103,10 @@ // Creates the initator's [Hello] message. std::string CreateHelloMessage() { std::string hello_message; - helper_->CreateHelloMessage(local_session_public_key_, - persistent_symmetric_key_, - &secure_message_delegate_, - base::Bind(&SaveMessageResult, &hello_message)); + helper_->CreateHelloMessage( + local_session_public_key_, persistent_symmetric_key_, + &secure_message_delegate_, + base::BindOnce(&SaveMessageResult, &hello_message)); EXPECT_FALSE(hello_message.empty()); return hello_message; } @@ -122,7 +122,7 @@ hello_message, remote_session_public_key_, remote_session_private_key_, persistent_responder_private_key, persistent_symmetric_key_, &secure_message_delegate_, - base::Bind(&SaveMessageResult, &remote_auth_message)); + base::BindOnce(&SaveMessageResult, &remote_auth_message)); EXPECT_FALSE(remote_auth_message.empty()); return remote_auth_message; } @@ -134,7 +134,7 @@ helper_->CreateInitiatorAuthMessage( session_keys_, persistent_symmetric_key_, remote_auth_message, &secure_message_delegate_, - base::Bind(&SaveMessageResult, &local_auth_message)); + base::BindOnce(&SaveMessageResult, &local_auth_message)); EXPECT_FALSE(local_auth_message.empty()); return local_auth_message; } @@ -161,8 +161,8 @@ DeviceToDeviceResponderOperations::ValidateHelloMessage( CreateHelloMessage(), persistent_symmetric_key_, &secure_message_delegate_, - base::Bind(&SaveValidationResultWithKey, &validation_success, - &hello_public_key)); + base::BindOnce(&SaveValidationResultWithKey, &validation_success, + &hello_public_key)); EXPECT_TRUE(validation_success); EXPECT_EQ(local_session_public_key_, hello_public_key); @@ -175,8 +175,8 @@ DeviceToDeviceResponderOperations::ValidateHelloMessage( "some random string", persistent_symmetric_key_, &secure_message_delegate_, - base::Bind(&SaveValidationResultWithKey, &validation_success, - &hello_public_key)); + base::BindOnce(&SaveValidationResultWithKey, &validation_success, + &hello_public_key)); EXPECT_FALSE(validation_success); EXPECT_TRUE(hello_public_key.empty()); @@ -193,8 +193,8 @@ remote_auth_message, kResponderPersistentPublicKey, persistent_symmetric_key_, local_session_private_key_, hello_message, &secure_message_delegate_, - base::Bind(&SaveValidationResultWithSessionKeys, &validation_success, - &session_keys)); + base::BindOnce(&SaveValidationResultWithSessionKeys, &validation_success, + &session_keys)); EXPECT_TRUE(validation_success); EXPECT_EQ(session_keys_.initiator_encode_key(), @@ -214,8 +214,8 @@ remote_auth_message, kResponderPersistentPublicKey, persistent_symmetric_key_, local_session_private_key_, "invalid hello message", &secure_message_delegate_, - base::Bind(&SaveValidationResultWithSessionKeys, &validation_success, - &session_keys)); + base::BindOnce(&SaveValidationResultWithSessionKeys, &validation_success, + &session_keys)); EXPECT_FALSE(validation_success); EXPECT_TRUE(session_keys.initiator_encode_key().empty()); @@ -233,8 +233,8 @@ remote_auth_message, kResponderPersistentPublicKey, "invalid persistent symmetric key", local_session_private_key_, hello_message, &secure_message_delegate_, - base::Bind(&SaveValidationResultWithSessionKeys, &validation_success, - &session_keys)); + base::BindOnce(&SaveValidationResultWithSessionKeys, &validation_success, + &session_keys)); EXPECT_FALSE(validation_success); EXPECT_TRUE(session_keys.initiator_encode_key().empty()); @@ -252,7 +252,7 @@ DeviceToDeviceResponderOperations::ValidateInitiatorAuthMessage( local_auth_message, session_keys_, persistent_symmetric_key_, remote_auth_message, &secure_message_delegate_, - base::Bind(&SaveValidationResult, &validation_success)); + base::BindOnce(&SaveValidationResult, &validation_success)); EXPECT_TRUE(validation_success); } @@ -268,7 +268,7 @@ DeviceToDeviceResponderOperations::ValidateInitiatorAuthMessage( local_auth_message, session_keys_, persistent_symmetric_key_, "invalid remote auth", &secure_message_delegate_, - base::Bind(&SaveValidationResult, &validation_success)); + base::BindOnce(&SaveValidationResult, &validation_success)); EXPECT_FALSE(validation_success); } @@ -284,7 +284,7 @@ DeviceToDeviceResponderOperations::ValidateInitiatorAuthMessage( local_auth_message, session_keys_, "invalid persistent symmetric key", remote_auth_message, &secure_message_delegate_, - base::Bind(&SaveValidationResult, &validation_success)); + base::BindOnce(&SaveValidationResult, &validation_success)); EXPECT_FALSE(validation_success); }
diff --git a/chromeos/services/secure_channel/device_to_device_responder_operations.cc b/chromeos/services/secure_channel/device_to_device_responder_operations.cc index fcead3d..0a33030 100644 --- a/chromeos/services/secure_channel/device_to_device_responder_operations.cc +++ b/chromeos/services/secure_channel/device_to_device_responder_operations.cc
@@ -33,18 +33,19 @@ // Callback for DeviceToDeviceResponderOperations::ValidateHelloMessage(), // after the [Hello] message is unwrapped. void OnHelloMessageUnwrapped( - const DeviceToDeviceResponderOperations::ValidateHelloCallback& callback, + DeviceToDeviceResponderOperations::ValidateHelloCallback callback, bool verified, const std::string& payload, const securemessage::Header& header) { securegcm::InitiatorHello initiator_hello; if (!verified || !initiator_hello.ParseFromString(header.public_metadata()) || initiator_hello.protocol_version() != kD2DProtocolVersion) { - callback.Run(false, std::string()); + std::move(callback).Run(false, std::string()); return; } - callback.Run(true, initiator_hello.public_dh_key().SerializeAsString()); + std::move(callback).Run(true, + initiator_hello.public_dh_key().SerializeAsString()); } // Helper struct containing all the context needed to create the [Responder @@ -56,7 +57,6 @@ std::string persistent_private_key; std::string persistent_symmetric_key; multidevice::SecureMessageDelegate* secure_message_delegate; - DeviceToDeviceResponderOperations::MessageCallback callback; std::string hello_public_key; std::string middle_message; }; @@ -65,26 +65,31 @@ // message, declared in order in which they are called during the creation flow. void OnHelloMessageValidatedForResponderAuth( CreateResponderAuthMessageContext context, + DeviceToDeviceResponderOperations::MessageCallback callback, bool hello_message_validated, const std::string& hello_public_key); void OnInnerMessageCreatedForResponderAuth( CreateResponderAuthMessageContext context, + DeviceToDeviceResponderOperations::MessageCallback callback, const std::string& inner_message); void OnMiddleMessageCreatedForResponderAuth( CreateResponderAuthMessageContext context, + DeviceToDeviceResponderOperations::MessageCallback callback, const std::string& middle_message); void OnSessionSymmetricKeyDerivedForResponderAuth( CreateResponderAuthMessageContext context, + DeviceToDeviceResponderOperations::MessageCallback callback, const std::string& session_symmetric_key); // Called after the initiator's [Hello] message is unwrapped. void OnHelloMessageValidatedForResponderAuth( CreateResponderAuthMessageContext context, + DeviceToDeviceResponderOperations::MessageCallback callback, bool hello_message_validated, const std::string& hello_public_key) { if (!hello_message_validated) { PA_LOG(VERBOSE) << "Invalid [Hello] while creating [Responder Auth]"; - context.callback.Run(std::string()); + std::move(callback).Run(std::string()); return; } @@ -103,16 +108,18 @@ context.secure_message_delegate->CreateSecureMessage( kPayloadFiller, context.persistent_private_key, create_options, - base::Bind(&OnInnerMessageCreatedForResponderAuth, context)); + base::BindOnce(&OnInnerMessageCreatedForResponderAuth, context, + std::move(callback))); } // Called after the inner-most layer of [Responder Auth] is created. void OnInnerMessageCreatedForResponderAuth( CreateResponderAuthMessageContext context, + DeviceToDeviceResponderOperations::MessageCallback callback, const std::string& inner_message) { if (inner_message.empty()) { PA_LOG(VERBOSE) << "Failed to create middle message for [Responder Auth]"; - context.callback.Run(std::string()); + std::move(callback).Run(std::string()); return; } @@ -123,16 +130,18 @@ create_options.associated_data = context.hello_message; context.secure_message_delegate->CreateSecureMessage( inner_message, context.persistent_symmetric_key, create_options, - base::Bind(&OnMiddleMessageCreatedForResponderAuth, context)); + base::BindOnce(&OnMiddleMessageCreatedForResponderAuth, context, + std::move(callback))); } // Called after the middle layer of [Responder Auth] is created. void OnMiddleMessageCreatedForResponderAuth( CreateResponderAuthMessageContext context, + DeviceToDeviceResponderOperations::MessageCallback callback, const std::string& middle_message) { if (middle_message.empty()) { PA_LOG(ERROR) << "Error inner message while creating [Responder Auth]"; - context.callback.Run(std::string()); + std::move(callback).Run(std::string()); return; } @@ -141,17 +150,19 @@ context.middle_message = middle_message; context.secure_message_delegate->DeriveKey( context.session_private_key, context.hello_public_key, - base::Bind(&OnSessionSymmetricKeyDerivedForResponderAuth, context)); + base::BindOnce(&OnSessionSymmetricKeyDerivedForResponderAuth, context, + std::move(callback))); } // Called after the session symmetric key is derived, so we can create the outer // most layer of [Responder Auth]. void OnSessionSymmetricKeyDerivedForResponderAuth( CreateResponderAuthMessageContext context, + DeviceToDeviceResponderOperations::MessageCallback callback, const std::string& session_symmetric_key) { if (session_symmetric_key.empty()) { PA_LOG(ERROR) << "Error inner message while creating [Responder Auth]"; - context.callback.Run(std::string()); + std::move(callback).Run(std::string()); return; } @@ -165,7 +176,7 @@ context.session_public_key)) { PA_LOG(ERROR) << "Error parsing public key while creating [Responder Auth]"; PA_LOG(ERROR) << context.session_public_key; - context.callback.Run(std::string()); + std::move(callback).Run(std::string()); return; } responder_hello.set_protocol_version(kD2DProtocolVersion); @@ -185,7 +196,7 @@ context.secure_message_delegate->CreateSecureMessage( device_to_device_message.SerializeAsString(), SessionKeys(session_symmetric_key).responder_encode_key(), create_options, - context.callback); + std::move(callback)); } // Helper struct containing all the context needed to validate the [Initiator @@ -194,29 +205,30 @@ std::string persistent_symmetric_key; std::string responder_auth_message; multidevice::SecureMessageDelegate* secure_message_delegate; - DeviceToDeviceResponderOperations::ValidationCallback callback; }; // Called after the inner-most layer of [Initiator Auth] is unwrapped. void OnInnerMessageUnwrappedForInitiatorAuth( const ValidateInitiatorAuthMessageContext& context, + DeviceToDeviceResponderOperations::ValidationCallback callback, bool verified, const std::string& payload, const securemessage::Header& header) { if (!verified) PA_LOG(VERBOSE) << "Failed to inner [Initiator Auth] message."; - context.callback.Run(verified); + std::move(callback).Run(verified); } // Called after the outer-most layer of [Initiator Auth] is unwrapped. void OnOuterMessageUnwrappedForInitiatorAuth( const ValidateInitiatorAuthMessageContext& context, + DeviceToDeviceResponderOperations::ValidationCallback callback, bool verified, const std::string& payload, const securemessage::Header& header) { if (!verified) { PA_LOG(VERBOSE) << "Failed to verify outer [Initiator Auth] message"; - context.callback.Run(false); + std::move(callback).Run(false); return; } @@ -225,7 +237,7 @@ if (!device_to_device_message.ParseFromString(payload) || device_to_device_message.sequence_number() != 1) { PA_LOG(VERBOSE) << "Failed to validate DeviceToDeviceMessage payload."; - context.callback.Run(false); + std::move(callback).Run(false); return; } @@ -237,7 +249,8 @@ context.secure_message_delegate->UnwrapSecureMessage( device_to_device_message.message(), context.persistent_symmetric_key, unwrap_options, - base::Bind(&OnInnerMessageUnwrappedForInitiatorAuth, context)); + base::BindOnce(&OnInnerMessageUnwrappedForInitiatorAuth, context, + std::move(callback))); } } // namespace @@ -247,7 +260,7 @@ const std::string& hello_message, const std::string& persistent_symmetric_key, multidevice::SecureMessageDelegate* secure_message_delegate, - const ValidateHelloCallback& callback) { + ValidateHelloCallback callback) { // The [Hello] message has the structure: // { // header: <session_public_key>, @@ -259,7 +272,7 @@ unwrap_options.signature_scheme = securemessage::HMAC_SHA256; secure_message_delegate->UnwrapSecureMessage( hello_message, persistent_symmetric_key, unwrap_options, - base::Bind(&OnHelloMessageUnwrapped, callback)); + base::BindOnce(&OnHelloMessageUnwrapped, std::move(callback))); } // static @@ -270,7 +283,7 @@ const std::string& persistent_private_key, const std::string& persistent_symmetric_key, multidevice::SecureMessageDelegate* secure_message_delegate, - const MessageCallback& callback) { + MessageCallback callback) { // The [Responder Auth] message has the structure: // { // header: <responder_public_key>, @@ -293,14 +306,14 @@ session_private_key, persistent_private_key, persistent_symmetric_key, - secure_message_delegate, - callback}; + secure_message_delegate}; // To create the [Responder Auth] message, we need to first parse the // initiator's [Hello] message and extract the initiator's session public key. DeviceToDeviceResponderOperations::ValidateHelloMessage( hello_message, persistent_symmetric_key, secure_message_delegate, - base::Bind(&OnHelloMessageValidatedForResponderAuth, context)); + base::BindOnce(&OnHelloMessageValidatedForResponderAuth, context, + std::move(callback))); } // static @@ -310,7 +323,7 @@ const std::string& persistent_symmetric_key, const std::string& responder_auth_message, multidevice::SecureMessageDelegate* secure_message_delegate, - const ValidationCallback& callback) { + DeviceToDeviceResponderOperations::ValidationCallback callback) { // The [Initiator Auth] message has the structure: // { // header: Sig(payload1, session_symmetric_key) @@ -323,9 +336,9 @@ // } // }, session_symmetric_key) // } - ValidateInitiatorAuthMessageContext context = { - persistent_symmetric_key, responder_auth_message, secure_message_delegate, - callback}; + ValidateInitiatorAuthMessageContext context = {persistent_symmetric_key, + responder_auth_message, + secure_message_delegate}; multidevice::SecureMessageDelegate::UnwrapOptions unwrap_options; unwrap_options.encryption_scheme = securemessage::AES_256_CBC; @@ -333,7 +346,8 @@ secure_message_delegate->UnwrapSecureMessage( initiator_auth_message, session_keys.initiator_encode_key(), unwrap_options, - base::Bind(&OnOuterMessageUnwrappedForInitiatorAuth, context)); + base::BindOnce(&OnOuterMessageUnwrappedForInitiatorAuth, context, + std::move(callback))); } } // namespace secure_channel
diff --git a/chromeos/services/secure_channel/device_to_device_responder_operations.h b/chromeos/services/secure_channel/device_to_device_responder_operations.h index d1bddb8..87e2a49a 100644 --- a/chromeos/services/secure_channel/device_to_device_responder_operations.h +++ b/chromeos/services/secure_channel/device_to_device_responder_operations.h
@@ -43,15 +43,16 @@ public: // Callback for operations that create a message. Invoked with the serialized // SecureMessage upon success or the empty string upon failure. - typedef base::Callback<void(const std::string&)> MessageCallback; + typedef base::OnceCallback<void(const std::string&)> MessageCallback; // Callback for operations that validates a message. - typedef base::Callback<void(bool)> ValidationCallback; + typedef base::OnceCallback<void(bool)> ValidationCallback; // Callback for ValidateHelloMessage. The first argument will be called with // the validation outcome. If validation succeeded, then the second argument // will contain the initiator's public key. - typedef base::Callback<void(bool, const std::string&)> ValidateHelloCallback; + typedef base::OnceCallback<void(bool, const std::string&)> + ValidateHelloCallback; // Validates that the [Hello] message, received from the initiator, // is properly signed and encrypted. @@ -67,7 +68,7 @@ const std::string& hello_message, const std::string& persistent_symmetric_key, multidevice::SecureMessageDelegate* secure_message_delegate, - const ValidateHelloCallback& callback); + ValidateHelloCallback callback); // Creates the [Responder Auth] message: // |hello_message|: The initial [Hello] message that was sent, which is used @@ -91,7 +92,7 @@ const std::string& persistent_private_key, const std::string& persistent_symmetric_key, multidevice::SecureMessageDelegate* secure_message_delegate, - const MessageCallback& callback); + MessageCallback callback); // Validates that the [Initiator Auth] message, received from the initiator, // is properly signed and encrypted. @@ -110,7 +111,7 @@ const std::string& persistent_symmetric_key, const std::string& responder_auth_message, multidevice::SecureMessageDelegate* secure_message_delegate, - const ValidationCallback& callback); + ValidationCallback callback); private: DISALLOW_IMPLICIT_CONSTRUCTORS(DeviceToDeviceResponderOperations);
diff --git a/chromeos/services/secure_channel/fake_authenticator.cc b/chromeos/services/secure_channel/fake_authenticator.cc index 11dbfba..963d5b2 100644 --- a/chromeos/services/secure_channel/fake_authenticator.cc +++ b/chromeos/services/secure_channel/fake_authenticator.cc
@@ -15,8 +15,8 @@ FakeAuthenticator::~FakeAuthenticator() {} void FakeAuthenticator::Authenticate( - const Authenticator::AuthenticationCallback& callback) { - last_callback_ = callback; + Authenticator::AuthenticationCallback callback) { + last_callback_ = std::move(callback); } } // namespace secure_channel
diff --git a/chromeos/services/secure_channel/fake_authenticator.h b/chromeos/services/secure_channel/fake_authenticator.h index 3b3a53858..9a7c4e0 100644 --- a/chromeos/services/secure_channel/fake_authenticator.h +++ b/chromeos/services/secure_channel/fake_authenticator.h
@@ -20,9 +20,9 @@ ~FakeAuthenticator() override; // Authenticator: - void Authenticate(const AuthenticationCallback& callback) override; + void Authenticate(AuthenticationCallback callback) override; - AuthenticationCallback last_callback() { return last_callback_; } + AuthenticationCallback last_callback() { return std::move(last_callback_); } private: AuthenticationCallback last_callback_;
diff --git a/components/autofill/core/browser/autofill_metrics.cc b/components/autofill/core/browser/autofill_metrics.cc index 2df53d1..f102f93e 100644 --- a/components/autofill/core/browser/autofill_metrics.cc +++ b/components/autofill/core/browser/autofill_metrics.cc
@@ -2433,8 +2433,9 @@ ukm::UkmRecorder* recorder, ukm::SourceId source_id, uint32_t phone_collection_metric_state) { - DCHECK(recorder); - DCHECK_NE(source_id, ukm::kInvalidSourceId); + // UKM recording is not supported for WebViews. + if (!recorder || source_id == ukm::kInvalidSourceId) + return; ukm::builders::WebOTPImpact builder(source_id); builder.SetPhoneCollection(phone_collection_metric_state);
diff --git a/components/autofill/core/browser/form_structure.cc b/components/autofill/core/browser/form_structure.cc index b35ae47..820eb55 100644 --- a/components/autofill/core/browser/form_structure.cc +++ b/components/autofill/core/browser/form_structure.cc
@@ -81,6 +81,21 @@ constexpr int kCommonNamePrefixRemovalFieldThreshold = 3; constexpr int kMinCommonNamePrefixLength = 16; +// Affix removal configuration. Only remove short affixes if they are common +// to all field names and there is at least the minimum number of fields. +// If no affix common to all field names is found, search for a long +// prefix common to a subset of the fields. This case helps include cases of +// prefixes prepended by web frameworks. +// +// Minimum required number of available fields for trying to remove affixes. +constexpr int kCommonNameAffixRemovalFieldNumberThreshold = 3; +// Minimum required length for affixes common to all field names. +constexpr int kMinCommonNameAffixLength = 3; +// Minimum required length for prefixes common to a subset of the field names. +constexpr int kMinCommonNameLongPrefixLength = 16; +// Regex for checking if |parseable_name| is valid after stripping affixes. +constexpr char kParseableNameValidationRe[] = "\\D"; + // Returns true if the scheme given by |url| is one for which autofill is // allowed to activate. By default this only returns true for HTTP and HTTPS. bool HasAllowedScheme(const GURL& url) { @@ -2241,6 +2256,57 @@ } void FormStructure::ProcessExtractedFields() { + if (base::FeatureList::IsEnabled( + autofill::features::kAutofillLabelAffixRemoval)) { + // Updates the field name parsed by heuristics if several criteria are met. + // Several fields must be present in the form. + if (field_count() < kCommonNameAffixRemovalFieldNumberThreshold) + return; + + std::vector<base::StringPiece16> names; + names.reserve(field_count()); + for (const auto& field : *this) + names.push_back(field->name); + + int longest_prefix_length = FindLongestCommonAffixLength(names, false); + int longest_suffix_length = FindLongestCommonAffixLength(names, true); + + // Don't remove the common affix if it's not long enough. + if (longest_prefix_length < kMinCommonNameAffixLength) + longest_prefix_length = 0; + + if (longest_suffix_length < kMinCommonNameAffixLength) + longest_suffix_length = 0; + + bool success = + SetStrippedParseableNames(longest_prefix_length, longest_suffix_length); + + // Don't search for inconsistent prefix if valid affixes are found. + if (success && longest_prefix_length + longest_suffix_length > 0) + return; + + // Functionality for stripping a prefix only common to a subset + // of field names. + // This is needed because an exceptional field may be missing a prefix + // which is otherwise consistently applied--for instance, a framework + // may only apply a prefix to those fields which are bound when POSTing. + names.clear(); + for (const auto& field : *this) + if (field->name.size() > kMinCommonNameLongPrefixLength) + names.push_back(field->name); + + if (names.size() < kCommonNamePrefixRemovalFieldThreshold) + return; + + const int longest_long_prefix_length = + FindLongestCommonAffixLength(names, false); + + if (longest_long_prefix_length >= kMinCommonNameLongPrefixLength) + SetStrippedParseableNames(longest_long_prefix_length, 0); + + return; + } + // Update the field name parsed by heuristics if several criteria are met. // Several fields must be present in the form. if (field_count() < kCommonNamePrefixRemovalFieldThreshold) @@ -2265,6 +2331,70 @@ } } +bool FormStructure::SetStrippedParseableNames(size_t offset_left, + size_t offset_right) { + // Keeps track if all stripped strings are valid according to + // |IsValidParseableName()|. If at least one string is invalid, + // all |parseable_name| are reset to |name|. + bool should_keep = true; + for (auto& field : *this) { + // This check allows to only strip affixes from long enough strings. + if (field->name.size() > offset_right + offset_left) { + field->set_parseable_name(field->name.substr( + offset_left, field->name.size() - offset_right - offset_left)); + } else { + field->set_parseable_name(field->name); + } + + should_keep &= IsValidParseableName(field->parseable_name()); + if (!should_keep) + break; + } + + // Reset if some stripped string was invalid. + if (!should_keep) { + for (auto& field : *this) + field->set_parseable_name(field->name); + } + + return should_keep; +} + +bool FormStructure::IsValidParseableName( + base::string16 candidateParseableName) { + static const base::string16 kParseableNameValidationPattern = + base::UTF8ToUTF16(kParseableNameValidationRe); + if (MatchesPattern(candidateParseableName, kParseableNameValidationPattern)) + return true; + + return false; +} + +// static +size_t FormStructure::FindLongestCommonAffixLength( + const std::vector<base::StringPiece16>& strings, + bool findCommonSuffix) { + if (strings.empty()) + return 0; + + // Go through each character of the first string until there is a mismatch at + // the same position in any other string. Adapted from http://goo.gl/YGukMM. + for (size_t affix_len = 0; affix_len < strings[0].size(); affix_len++) { + size_t base_string_index = + findCommonSuffix ? strings[0].size() - affix_len - 1 : affix_len; + for (size_t i = 1; i < strings.size(); i++) { + size_t compared_string_index = + findCommonSuffix ? strings[i].size() - affix_len - 1 : affix_len; + if (affix_len >= strings[i].size() || + strings[i][compared_string_index] != strings[0][base_string_index]) { + // Mismatch found. + return affix_len; + } + } + } + return strings[0].size(); +} + // static base::string16 FormStructure::FindLongestCommonPrefix( const std::vector<base::string16>& strings) {
diff --git a/components/autofill/core/browser/form_structure.h b/components/autofill/core/browser/form_structure.h index db20768..2028d3be 100644 --- a/components/autofill/core/browser/form_structure.h +++ b/components/autofill/core/browser/form_structure.h
@@ -406,6 +406,8 @@ friend class FormStructureTest; FRIEND_TEST_ALL_PREFIXES(AutofillDownloadTest, QueryAndUploadTest); FRIEND_TEST_ALL_PREFIXES(FormStructureTest, FindLongestCommonPrefix); + FRIEND_TEST_ALL_PREFIXES(FormStructureTest, FindLongestCommonAffixLength); + FRIEND_TEST_ALL_PREFIXES(FormStructureTest, IsValidParseableName); FRIEND_TEST_ALL_PREFIXES(FormStructureTest, RationalizePhoneNumber_RunsOncePerSection); @@ -555,11 +557,32 @@ // Further processes the extracted |fields_|. void ProcessExtractedFields(); + // Tries to set |parseable_name| fields by stripping the given offsets from + // both sides of the |name| fields. + // Sets |parseable_name| to |name| if the sum of offsets is bigger than + // |name|. + // Sets all |parseable_name| to |name| without modification and returns + // false if a name fails the |IsValidParseableName()| check after stripping. + bool SetStrippedParseableNames(size_t offset_left, size_t offset_right); + + // Returns true if |string| is a valid parseable_name. Current criterion + // is the |autofill::kParseableNameValidationRe| regex. + static bool IsValidParseableName(base::string16 string); + + // Returns the length of the longest common prefix found within |strings| + // if |findCommonSuffix| is false. Otherwise returns longest common suffix. + static size_t FindLongestCommonAffixLength( + const std::vector<base::StringPiece16>& strings, + bool findCommonSuffix = false); + // Returns the longest common prefix found within |strings|. Strings below a - // threshold length are excluded when performing this check; this is needed - // because an exceptional field may be missing a prefix which is otherwise - // consistently applied--for instance, a framework may only apply a prefix - // to those fields which are bound when POSTing. + // threshold length defined by |kMinCommonNamePrefixLength| are excluded + // when performing this check; this is needed because an exceptional + // field may be missing a prefix which is otherwise consistently applied. + // For instance, a framework may only apply a prefix to those fields + // which are bound when POSTing. + // + // Soon to be replaced by FindLongestCommonPrefixLength static base::string16 FindLongestCommonPrefix( const std::vector<base::string16>& strings);
diff --git a/components/autofill/core/browser/form_structure_unittest.cc b/components/autofill/core/browser/form_structure_unittest.cc index de7e79d1..889ceb5 100644 --- a/components/autofill/core/browser/form_structure_unittest.cc +++ b/components/autofill/core/browser/form_structure_unittest.cc
@@ -39,6 +39,7 @@ using features::kAutofillEnforceMinRequiredFieldsForHeuristics; using features::kAutofillEnforceMinRequiredFieldsForQuery; using features::kAutofillEnforceMinRequiredFieldsForUpload; +using features::kAutofillLabelAffixRemoval; using mojom::SubmissionIndicatorEvent; using mojom::SubmissionSource; @@ -752,8 +753,280 @@ } // All fields share a common prefix which could confuse the heuristics. Test +// that the common prefixes are stripped out before running heuristics. +// This test ensures that |parseable_name| is used for heuristics. +TEST_F(FormStructureTest, StripCommonNameAffix) { + base::test::ScopedFeatureList feature_list; + feature_list.InitAndEnableFeature(kAutofillLabelAffixRemoval); + + FormData form; + form.url = GURL("http://www.foo.com/"); + + FormFieldData field; + field.form_control_type = "text"; + + field.label = ASCIIToUTF16("First Name"); + field.name = ASCIIToUTF16("ctl01$ctl00$ShippingAddressCreditPhone$firstname"); + form.fields.push_back(field); + + field.label = ASCIIToUTF16("Last Name"); + field.name = ASCIIToUTF16("ctl01$ctl00$ShippingAddressCreditPhone$lastname"); + form.fields.push_back(field); + + field.label = ASCIIToUTF16("Email"); + field.name = ASCIIToUTF16("ctl01$ctl00$ShippingAddressCreditPhone$email"); + form.fields.push_back(field); + + field.label = ASCIIToUTF16("Phone"); + field.name = ASCIIToUTF16("ctl01$ctl00$ShippingAddressCreditPhone$phone"); + form.fields.push_back(field); + + field.label = base::string16(); + field.name = ASCIIToUTF16("ctl01$ctl00$ShippingAddressCreditPhone$submit"); + field.form_control_type = "submit"; + form.fields.push_back(field); + + std::unique_ptr<FormStructure> form_structure(new FormStructure(form)); + form_structure->DetermineHeuristicTypes(); + EXPECT_TRUE(form_structure->IsAutofillable()); + + // Expect the correct number of fields. + ASSERT_EQ(5U, form_structure->field_count()); + ASSERT_EQ(4U, form_structure->autofill_count()); + + // First name. + EXPECT_EQ(ASCIIToUTF16("firstname"), + form_structure->field(0)->parseable_name()); + EXPECT_EQ(NAME_FIRST, form_structure->field(0)->heuristic_type()); + // Last name. + EXPECT_EQ(ASCIIToUTF16("lastname"), + form_structure->field(1)->parseable_name()); + EXPECT_EQ(NAME_LAST, form_structure->field(1)->heuristic_type()); + // Email. + EXPECT_EQ(ASCIIToUTF16("email"), form_structure->field(2)->parseable_name()); + EXPECT_EQ(EMAIL_ADDRESS, form_structure->field(2)->heuristic_type()); + // Phone. + EXPECT_EQ(ASCIIToUTF16("phone"), form_structure->field(3)->parseable_name()); + EXPECT_EQ(PHONE_HOME_WHOLE_NUMBER, + form_structure->field(3)->heuristic_type()); + // Submit. + EXPECT_EQ(ASCIIToUTF16("submit"), form_structure->field(4)->parseable_name()); + EXPECT_EQ(UNKNOWN_TYPE, form_structure->field(4)->heuristic_type()); +} + +// All fields share a common prefix, but it's not stripped due to +// the |IsValidParseableName()| rule. +TEST_F(FormStructureTest, StripCommonNameAffix_SmallPrefix) { + base::test::ScopedFeatureList feature_list; + feature_list.InitAndEnableFeature(kAutofillLabelAffixRemoval); + + FormData form; + form.url = GURL("http://www.foo.com/"); + + FormFieldData field; + field.form_control_type = "text"; + + field.label = ASCIIToUTF16("Address 1"); + field.name = ASCIIToUTF16("address1"); + form.fields.push_back(field); + + field.label = ASCIIToUTF16("Address 2"); + field.name = ASCIIToUTF16("address2"); + form.fields.push_back(field); + + field.label = ASCIIToUTF16("Address 3"); + field.name = ASCIIToUTF16("address3"); + form.fields.push_back(field); + + std::unique_ptr<FormStructure> form_structure(new FormStructure(form)); + + // Expect the correct number of fields. + ASSERT_EQ(3U, form_structure->field_count()); + + // Address 1. + EXPECT_EQ(ASCIIToUTF16("address1"), + form_structure->field(0)->parseable_name()); + // Address 2. + EXPECT_EQ(ASCIIToUTF16("address2"), + form_structure->field(1)->parseable_name()); + // Address 3 + EXPECT_EQ(ASCIIToUTF16("address3"), + form_structure->field(2)->parseable_name()); +} + +// All fields share both a common prefix and suffix which could confuse the +// heuristics. Test that the common affixes are stripped out from +// |parseable_name| during |FormStructure| initialization. +TEST_F(FormStructureTest, StripCommonNameAffix_PrefixAndSuffix) { + base::test::ScopedFeatureList feature_list; + feature_list.InitAndEnableFeature(kAutofillLabelAffixRemoval); + + FormData form; + form.url = GURL("http://www.foo.com/"); + + FormFieldData field; + field.form_control_type = "text"; + + field.label = ASCIIToUTF16("First Name"); + field.name = + ASCIIToUTF16("ctl01$ctl00$ShippingAddressCreditPhone$firstname_data"); + form.fields.push_back(field); + + field.label = ASCIIToUTF16("Last Name"); + field.name = + ASCIIToUTF16("ctl01$ctl00$ShippingAddressCreditPhone$lastname_data"); + form.fields.push_back(field); + + field.label = ASCIIToUTF16("Email"); + field.name = + ASCIIToUTF16("ctl01$ctl00$ShippingAddressCreditPhone$email_data"); + form.fields.push_back(field); + + field.label = ASCIIToUTF16("Phone"); + field.name = + ASCIIToUTF16("ctl01$ctl00$ShippingAddressCreditPhone$phone_data"); + form.fields.push_back(field); + + field.label = base::string16(); + field.name = + ASCIIToUTF16("ctl01$ctl00$ShippingAddressCreditPhone$submit_data"); + field.form_control_type = "submit"; + form.fields.push_back(field); + + std::unique_ptr<FormStructure> form_structure(new FormStructure(form)); + + // Expect the correct number of fields. + ASSERT_EQ(5U, form_structure->field_count()); + + // First name. + EXPECT_EQ(ASCIIToUTF16("firstname"), + form_structure->field(0)->parseable_name()); + // Last name. + EXPECT_EQ(ASCIIToUTF16("lastname"), + form_structure->field(1)->parseable_name()); + // Email. + EXPECT_EQ(ASCIIToUTF16("email"), form_structure->field(2)->parseable_name()); + // Phone. + EXPECT_EQ(ASCIIToUTF16("phone"), form_structure->field(3)->parseable_name()); + // Submit. + EXPECT_EQ(ASCIIToUTF16("submit"), form_structure->field(4)->parseable_name()); +} + +// Only some fields share a long common long prefix, no fields share a suffix. +// Test that only the common prefixes are stripped out in |parseable_name| +// during |FormStructure| initialization. +TEST_F(FormStructureTest, StripCommonNameAffix_SelectiveLongPrefix) { + base::test::ScopedFeatureList feature_list; + feature_list.InitAndEnableFeature(kAutofillLabelAffixRemoval); + + FormData form; + form.url = GURL("http://www.foo.com/"); + + FormFieldData field; + field.form_control_type = "text"; + + field.label = ASCIIToUTF16("First Name"); + field.name = ASCIIToUTF16("ctl01$ctl00$ShippingAddressCreditPhone$firstname"); + form.fields.push_back(field); + + field.label = ASCIIToUTF16("Last Name"); + field.name = ASCIIToUTF16("ctl01$ctl00$ShippingAddressCreditPhone$lastname"); + form.fields.push_back(field); + + field.label = ASCIIToUTF16("Email"); + field.name = ASCIIToUTF16("email"); + form.fields.push_back(field); + + field.label = ASCIIToUTF16("Phone"); + field.name = ASCIIToUTF16("phone"); + form.fields.push_back(field); + + field.label = base::string16(); + field.name = ASCIIToUTF16("ctl01$ctl00$ShippingAddressCreditPhone$submit"); + field.form_control_type = "submit"; + form.fields.push_back(field); + + std::unique_ptr<FormStructure> form_structure(new FormStructure(form)); + + // Expect the correct number of fields. + ASSERT_EQ(5U, form_structure->field_count()); + + // First name. + EXPECT_EQ(ASCIIToUTF16("firstname"), + form_structure->field(0)->parseable_name()); + // Last name. + EXPECT_EQ(ASCIIToUTF16("lastname"), + form_structure->field(1)->parseable_name()); + // Email. + EXPECT_EQ(ASCIIToUTF16("email"), form_structure->field(2)->parseable_name()); + // Phone. + EXPECT_EQ(ASCIIToUTF16("phone"), form_structure->field(3)->parseable_name()); + // Submit. + EXPECT_EQ(ASCIIToUTF16("submit"), form_structure->field(4)->parseable_name()); +} + +// Only some fields share a long common short prefix, no fields share a suffix. +// Test that short uncommon prefixes are not stripped (even if there are +// enough). +TEST_F(FormStructureTest, + StripCommonNameAffix_SelectiveLongPrefixIgnoreLength) { + base::test::ScopedFeatureList feature_list; + feature_list.InitAndEnableFeature(kAutofillLabelAffixRemoval); + + FormData form; + form.url = GURL("http://www.foo.com/"); + + FormFieldData field; + field.form_control_type = "text"; + + field.label = ASCIIToUTF16("First Name"); + field.name = ASCIIToUTF16("firstname"); + form.fields.push_back(field); + + field.label = ASCIIToUTF16("Last Name"); + field.name = ASCIIToUTF16("lastname"); + form.fields.push_back(field); + + field.label = ASCIIToUTF16("Street Name"); + field.name = ASCIIToUTF16("address_streetname"); + form.fields.push_back(field); + + field.label = ASCIIToUTF16("Phone"); + field.name = ASCIIToUTF16("address_housenumber"); + form.fields.push_back(field); + + field.label = base::string16(); + field.name = ASCIIToUTF16("address_apartmentnumber"); + form.fields.push_back(field); + + std::unique_ptr<FormStructure> form_structure(new FormStructure(form)); + + // Expect the correct number of fields. + ASSERT_EQ(5U, form_structure->field_count()); + + // First name. + EXPECT_EQ(ASCIIToUTF16("firstname"), + form_structure->field(0)->parseable_name()); + // Last name. + EXPECT_EQ(ASCIIToUTF16("lastname"), + form_structure->field(1)->parseable_name()); + // Email. + EXPECT_EQ(ASCIIToUTF16("address_streetname"), + form_structure->field(2)->parseable_name()); + // Phone. + EXPECT_EQ(ASCIIToUTF16("address_housenumber"), + form_structure->field(3)->parseable_name()); + // Submit. + EXPECT_EQ(ASCIIToUTF16("address_apartmentnumber"), + form_structure->field(4)->parseable_name()); +} + +// All fields share a common prefix which could confuse the heuristics. Test // that the common prefix is stripped out before running heuristics. TEST_F(FormStructureTest, StripCommonNamePrefix) { + base::test::ScopedFeatureList feature_list; + feature_list.InitAndDisableFeature(kAutofillLabelAffixRemoval); + FormData form; form.url = GURL("http://www.foo.com/"); @@ -805,6 +1078,9 @@ // All fields share a common prefix which is small enough that it is not // stripped from the name before running the heuristics. TEST_F(FormStructureTest, StripCommonNamePrefix_SmallPrefix) { + base::test::ScopedFeatureList feature_list; + feature_list.InitAndDisableFeature(kAutofillLabelAffixRemoval); + FormData form; form.url = GURL("http://www.foo.com/"); @@ -5874,6 +6150,100 @@ EXPECT_EQ(UNKNOWN_TYPE, forms[0]->field(3)->Type().GetStorableType()); } +TEST_F(FormStructureTest, SetStrippedParseableNames) { + base::test::ScopedFeatureList feature_list; + feature_list.InitAndEnableFeature(kAutofillLabelAffixRemoval); +} + +TEST_F(FormStructureTest, IsValidParseableName) { + // Parseable name should not be empty. + EXPECT_FALSE(FormStructure::IsValidParseableName(ASCIIToUTF16(""))); + // Parseable name should not be solely numerical. + EXPECT_FALSE(FormStructure::IsValidParseableName(ASCIIToUTF16("1265125"))); + + // Valid parseable name cases. + EXPECT_TRUE(FormStructure::IsValidParseableName(ASCIIToUTF16("a23"))); + EXPECT_TRUE(FormStructure::IsValidParseableName(ASCIIToUTF16("*)&%@"))); +} + +TEST_F(FormStructureTest, FindLongestCommonAffixLength) { + auto String16ToStringPiece16 = [](std::vector<base::string16>& vin, + std::vector<base::StringPiece16>& vout) { + vout.clear(); + for (auto& str : vin) + vout.push_back(str); + }; + + // Normal prefix case. + std::vector<base::string16> strings; + std::vector<base::StringPiece16> stringPieces; + strings.push_back(ASCIIToUTF16("123456XXX123456789")); + strings.push_back(ASCIIToUTF16("12345678XXX012345678_foo")); + strings.push_back(ASCIIToUTF16("1234567890123456")); + strings.push_back(ASCIIToUTF16("1234567XXX901234567890")); + String16ToStringPiece16(strings, stringPieces); + size_t affixLength = + FormStructure::FindLongestCommonAffixLength(stringPieces, false); + EXPECT_EQ(ASCIIToUTF16("123456").size(), affixLength); + + // Normal suffix case. + strings.clear(); + strings.push_back(ASCIIToUTF16("black and gold dress")); + strings.push_back(ASCIIToUTF16("work_address")); + strings.push_back(ASCIIToUTF16("123456XXX1234_home_address")); + strings.push_back(ASCIIToUTF16("1234567890123456_city_address")); + String16ToStringPiece16(strings, stringPieces); + affixLength = FormStructure::FindLongestCommonAffixLength(stringPieces, true); + EXPECT_EQ(ASCIIToUTF16("dress").size(), affixLength); + + // Handles no common prefix. + strings.clear(); + strings.push_back(ASCIIToUTF16("1234567890123456")); + strings.push_back(ASCIIToUTF16("4567890123456789")); + strings.push_back(ASCIIToUTF16("7890123456789012")); + String16ToStringPiece16(strings, stringPieces); + affixLength = + FormStructure::FindLongestCommonAffixLength(stringPieces, false); + EXPECT_EQ(ASCIIToUTF16("").size(), affixLength); + + // Handles no common suffix. + strings.clear(); + strings.push_back(ASCIIToUTF16("1234567890123456")); + strings.push_back(ASCIIToUTF16("4567890123456789")); + strings.push_back(ASCIIToUTF16("7890123456789012")); + String16ToStringPiece16(strings, stringPieces); + affixLength = FormStructure::FindLongestCommonAffixLength(stringPieces, true); + EXPECT_EQ(ASCIIToUTF16("").size(), affixLength); + + // Only one string, prefix case. + strings.clear(); + strings.push_back(ASCIIToUTF16("1234567890")); + String16ToStringPiece16(strings, stringPieces); + affixLength = + FormStructure::FindLongestCommonAffixLength(stringPieces, false); + EXPECT_EQ(ASCIIToUTF16("1234567890").size(), affixLength); + + // Only one string, suffix case. + strings.clear(); + strings.push_back(ASCIIToUTF16("1234567890")); + String16ToStringPiece16(strings, stringPieces); + affixLength = FormStructure::FindLongestCommonAffixLength(stringPieces, true); + EXPECT_EQ(ASCIIToUTF16("1234567890").size(), affixLength); + + // Empty vector, prefix case. + strings.clear(); + String16ToStringPiece16(strings, stringPieces); + affixLength = + FormStructure::FindLongestCommonAffixLength(stringPieces, false); + EXPECT_EQ(ASCIIToUTF16("").size(), affixLength); + + // Empty vector, suffix case. + strings.clear(); + String16ToStringPiece16(strings, stringPieces); + affixLength = FormStructure::FindLongestCommonAffixLength(stringPieces, true); + EXPECT_EQ(ASCIIToUTF16("").size(), affixLength); +} + TEST_F(FormStructureTest, FindLongestCommonPrefix) { // Normal case: All strings are longer than threshold; some are common. std::vector<base::string16> strings;
diff --git a/components/autofill/core/common/autofill_features.cc b/components/autofill/core/common/autofill_features.cc index 1c5af13..f502606 100644 --- a/components/autofill/core/common/autofill_features.cc +++ b/components/autofill/core/common/autofill_features.cc
@@ -159,6 +159,11 @@ const base::Feature kAutofillKeyboardAccessory{ "AutofillKeyboardAccessory", base::FEATURE_DISABLED_BY_DEFAULT}; +// When enabled, autofill will use new logic to strip both prefixes +// and suffixes when setting FormStructure::parseable_name_ +extern const base::Feature kAutofillLabelAffixRemoval{ + "AutofillLabelAffixRemoval", base::FEATURE_DISABLED_BY_DEFAULT}; + const base::Feature kAutofillPruneSuggestions{ "AutofillPruneSuggestions", base::FEATURE_DISABLED_BY_DEFAULT};
diff --git a/components/autofill/core/common/autofill_features.h b/components/autofill/core/common/autofill_features.h index 98d6ae0f..fef87b6 100644 --- a/components/autofill/core/common/autofill_features.h +++ b/components/autofill/core/common/autofill_features.h
@@ -45,6 +45,7 @@ extern const base::Feature kAutofillKeepInitialFormValuesInCache; extern const base::Feature kAutofillRetrieveFromCacheWithRendererIds; extern const base::Feature kAutofillKeyboardAccessory; +extern const base::Feature kAutofillLabelAffixRemoval; extern const base::Feature kAutofillPruneSuggestions; extern const base::Feature kAutofillMetadataUploads; extern const base::Feature kAutofillOffNoServerData;
diff --git a/components/autofill_assistant/browser/controller.cc b/components/autofill_assistant/browser/controller.cc index ced45b0a..a328d3f 100644 --- a/components/autofill_assistant/browser/controller.cc +++ b/components/autofill_assistant/browser/controller.cc
@@ -1527,9 +1527,14 @@ if (state_ == AutofillAssistantState::STOPPED) return; - RequireUI(); - SetStatusMessage(error_message); - SetProgressBarErrorState(true); + // For lite scripts, don't attach the UI on error, and don't show an error + // while shutting down. + if (!IsRunningLiteScript()) { + RequireUI(); + SetStatusMessage(error_message); + SetProgressBarErrorState(true); + } + EnterStoppedState(); if (tracking_) { @@ -1570,7 +1575,8 @@ void Controller::RecordDropOutOrShutdown(Metrics::DropOutReason reason) { // If there is an UI, we wait for it to be closed before shutting down (the UI // will call |ShutdownIfNecessary|). - if (client_->HasHadUI()) { + // Lite scripts go away immediately, even if UI is currently being shown. + if (client_->HasHadUI() && !IsRunningLiteScript()) { // We report right away to make sure we don't lose this reason if the client // is unexpectedly destroyed while the error message is showing (for example // if the tab is closed). @@ -1933,6 +1939,10 @@ return StateNeedsUiInLiteScript(state); } +bool Controller::IsRunningLiteScript() const { + return trigger_context_ ? trigger_context_->is_lite_script() : false; +} + ElementArea* Controller::touchable_element_area() { if (!touchable_element_area_) { touchable_element_area_ = std::make_unique<ElementArea>(this);
diff --git a/components/autofill_assistant/browser/controller.h b/components/autofill_assistant/browser/controller.h index f6006aa..129d8d4 100644 --- a/components/autofill_assistant/browser/controller.h +++ b/components/autofill_assistant/browser/controller.h
@@ -341,6 +341,7 @@ void PerformDelayedShutdownIfNecessary(); bool StateNeedsUI(AutofillAssistantState state); + bool IsRunningLiteScript() const; ClientSettings settings_; Client* const client_;
diff --git a/components/browser_ui/site_settings/android/BUILD.gn b/components/browser_ui/site_settings/android/BUILD.gn index 5b6f9ff2..62571755 100644 --- a/components/browser_ui/site_settings/android/BUILD.gn +++ b/components/browser_ui/site_settings/android/BUILD.gn
@@ -41,6 +41,7 @@ android_library("java") { sources = [ "java/src/org/chromium/components/browser_ui/site_settings/AddExceptionPreference.java", + "java/src/org/chromium/components/browser_ui/site_settings/AllSiteSettings.java", "java/src/org/chromium/components/browser_ui/site_settings/ChosenObjectInfo.java", "java/src/org/chromium/components/browser_ui/site_settings/ChosenObjectSettings.java", "java/src/org/chromium/components/browser_ui/site_settings/ClearWebsiteStorage.java", @@ -199,6 +200,7 @@ "java/res/layout/website_features.xml", "java/res/menu/website_preferences_menu.xml", "java/res/values/ids.xml", + "java/res/xml/all_site_preferences.xml", "java/res/xml/single_website_preferences.xml", "java/res/xml/site_settings_preferences.xml", "java/res/xml/website_preferences.xml",
diff --git a/components/browser_ui/site_settings/android/java/res/xml/all_site_preferences.xml b/components/browser_ui/site_settings/android/java/res/xml/all_site_preferences.xml new file mode 100644 index 0000000..4a4a1d1 --- /dev/null +++ b/components/browser_ui/site_settings/android/java/res/xml/all_site_preferences.xml
@@ -0,0 +1,9 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- Copyright 2020 The Chromium Authors. All rights reserved. + Use of this source code is governed by a BSD-style license that can be + found in the LICENSE file. --> + +<PreferenceScreen + xmlns:android="http://schemas.android.com/apk/res/android" + xmlns:app="http://schemas.android.com/apk/res-auto"> +</PreferenceScreen>
diff --git a/components/browser_ui/site_settings/android/java/res/xml/site_settings_preferences.xml b/components/browser_ui/site_settings/android/java/res/xml/site_settings_preferences.xml index 13ce2fb..f144feb4 100644 --- a/components/browser_ui/site_settings/android/java/res/xml/site_settings_preferences.xml +++ b/components/browser_ui/site_settings/android/java/res/xml/site_settings_preferences.xml
@@ -8,7 +8,7 @@ xmlns:app="http://schemas.android.com/apk/res-auto"> <!-- All sites --> <org.chromium.components.browser_ui.settings.ChromeBasePreference - android:fragment="org.chromium.components.browser_ui.site_settings.SingleCategorySettings" + android:fragment="org.chromium.components.browser_ui.site_settings.AllSiteSettings" android:key="all_sites" android:title="@string/all_sites" android:icon="@drawable/settings_all_sites" @@ -68,7 +68,7 @@ <!-- Storage --> <!-- TODO(finnur): Move this over to the new Usage screen, once it exists. --> <org.chromium.components.browser_ui.settings.ChromeBasePreference - android:fragment="org.chromium.components.browser_ui.site_settings.SingleCategorySettings" + android:fragment="org.chromium.components.browser_ui.site_settings.AllSiteSettings" android:key="use_storage" android:title="@string/website_settings_storage" android:icon="@drawable/settings_storage"
diff --git a/components/browser_ui/site_settings/android/java/src/org/chromium/components/browser_ui/site_settings/AllSiteSettings.java b/components/browser_ui/site_settings/android/java/src/org/chromium/components/browser_ui/site_settings/AllSiteSettings.java new file mode 100644 index 0000000..f9378f9 --- /dev/null +++ b/components/browser_ui/site_settings/android/java/src/org/chromium/components/browser_ui/site_settings/AllSiteSettings.java
@@ -0,0 +1,353 @@ +// Copyright 2020 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package org.chromium.components.browser_ui.site_settings; + +import static org.chromium.components.browser_ui.settings.SearchUtils.handleSearchNavigation; + +import android.content.Context; +import android.content.DialogInterface; +import android.os.Bundle; +import android.text.format.Formatter; +import android.view.LayoutInflater; +import android.view.Menu; +import android.view.MenuInflater; +import android.view.MenuItem; +import android.view.View; +import android.view.ViewGroup; +import android.widget.Button; +import android.widget.TextView; + +import androidx.annotation.Nullable; +import androidx.appcompat.app.AlertDialog; +import androidx.preference.Preference; +import androidx.preference.PreferenceManager; +import androidx.recyclerview.widget.RecyclerView; +import androidx.vectordrawable.graphics.drawable.VectorDrawableCompat; + +import org.chromium.base.annotations.UsedByReflection; +import org.chromium.base.metrics.RecordUserAction; +import org.chromium.components.browser_ui.settings.SearchUtils; +import org.chromium.components.browser_ui.settings.SettingsUtils; +import org.chromium.components.embedder_support.browser_context.BrowserContextHandle; +import org.chromium.components.embedder_support.util.UrlUtilities; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Set; + +/** + * Shows a list of all sites. When the user selects a site, SingleWebsiteSettings + * is launched to allow the user to see or modify the settings for that particular website. + */ +@UsedByReflection("all_site_preferences.xml") +public class AllSiteSettings extends SiteSettingsPreferenceFragment + implements PreferenceManager.OnPreferenceTreeClickListener, View.OnClickListener { + // The key to use to pass which category this preference should display, + // should only be All Sites or Storage. + public static final String EXTRA_CATEGORY = "category"; + public static final String EXTRA_TITLE = "title"; + + /** + * If present, the list of websites will be filtered by domain using + * {@link UrlUtilities#getDomainAndRegistry}. + */ + public static final String EXTRA_SELECTED_DOMAINS = "selected_domains"; + + // The clear button displayed in the Storage view. + private Button mClearButton; + // The list that contains preferences. + private RecyclerView mListView; + // The view to show when the list is empty. + private TextView mEmptyView; + // The item for searching the list of items. + private MenuItem mSearchItem; + // The Site Settings Category we are showing. + private SiteSettingsCategory mCategory; + // If not blank, represents a substring to use to search for site names. + private String mSearch; + // The websites that are currently displayed to the user. + private List<WebsitePreference> mWebsites; + + @Nullable + private Set<String> mSelectedDomains; + + private class ResultsPopulator implements WebsitePermissionsFetcher.WebsitePermissionsCallback { + @Override + public void onWebsitePermissionsAvailable(Collection<Website> sites) { + // This method may be called after the activity has been destroyed. + // In that case, bail out. + if (getActivity() == null) return; + mWebsites = null; + + resetList(); + + boolean hasEntries = addWebsites(sites); + + if (mEmptyView == null) return; + + mEmptyView.setVisibility(hasEntries ? View.GONE : View.VISIBLE); + } + } + + private void getInfoForOrigins() { + WebsitePermissionsFetcher fetcher = new WebsitePermissionsFetcher( + getSiteSettingsClient().getBrowserContextHandle(), false); + fetcher.fetchPreferencesForCategory(mCategory, new ResultsPopulator()); + } + + @Override + public View onCreateView( + LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { + // Read which category we should be showing. + BrowserContextHandle browserContextHandle = + getSiteSettingsClient().getBrowserContextHandle(); + if (getArguments() != null) { + mCategory = SiteSettingsCategory.createFromPreferenceKey( + browserContextHandle, getArguments().getString(EXTRA_CATEGORY, "")); + } + if (mCategory == null) { + mCategory = SiteSettingsCategory.createFromType( + browserContextHandle, SiteSettingsCategory.Type.ALL_SITES); + } + assert (mCategory.showSites(SiteSettingsCategory.Type.ALL_SITES) + || mCategory.showSites(SiteSettingsCategory.Type.USE_STORAGE)); + + ViewGroup view = (ViewGroup) super.onCreateView(inflater, container, savedInstanceState); + + // Add custom views for Storage Preferences to bottom of the fragment. + if (mCategory.showSites(SiteSettingsCategory.Type.USE_STORAGE)) { + inflater.inflate(R.layout.storage_preferences_view, view, true); + mEmptyView = view.findViewById(R.id.empty_storage); + mClearButton = view.findViewById(R.id.clear_button); + mClearButton.setOnClickListener(this); + } + + mListView = getListView(); + + // Disable animations of preference changes. + mListView.setItemAnimator(null); + + // Remove dividers between preferences. + setDivider(null); + + return view; + } + + /** + * This clears all the storage for websites that are displayed to the user. This happens + * asynchronously, and then we call {@link #getInfoForOrigins()} when we're done. + */ + public void clearStorage() { + if (mWebsites == null) return; + RecordUserAction.record("MobileSettingsStorageClearAll"); + + // The goal is to refresh the info for origins again after we've cleared all of them, so we + // wait until the last website is cleared to refresh the origin list. + final int[] numLeft = new int[1]; + numLeft[0] = mWebsites.size(); + for (int i = 0; i < mWebsites.size(); i++) { + WebsitePreference preference = mWebsites.get(i); + preference.site().clearAllStoredData( + getSiteSettingsClient().getBrowserContextHandle(), () -> { + if (--numLeft[0] <= 0) getInfoForOrigins(); + }); + } + } + + /** OnClickListener for the clear button. We show an alert dialog to confirm the action */ + @Override + public void onClick(View v) { + if (getActivity() == null || v != mClearButton) return; + + long totalUsage = 0; + boolean includesApps = false; + Set<String> originsWithInstalledApp = + getSiteSettingsClient().getWebappSettingsClient().getOriginsWithInstalledApp(); + if (mWebsites != null) { + for (WebsitePreference preference : mWebsites) { + totalUsage += preference.site().getTotalUsage(); + if (!includesApps) { + includesApps = originsWithInstalledApp.contains( + preference.site().getAddress().getOrigin()); + } + } + } + + AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); + View dialogView = + getActivity().getLayoutInflater().inflate(R.layout.clear_data_dialog, null); + TextView message = dialogView.findViewById(android.R.id.message); + TextView signedOutText = dialogView.findViewById(R.id.signed_out_text); + TextView offlineText = dialogView.findViewById(R.id.offline_text); + signedOutText.setText(R.string.webstorage_clear_data_dialog_sign_out_all_message); + offlineText.setText(R.string.webstorage_clear_data_dialog_offline_message); + String dialogFormattedText = + getString(includesApps ? R.string.webstorage_clear_data_dialog_message_with_app + : R.string.webstorage_clear_data_dialog_message, + Formatter.formatShortFileSize(getActivity(), totalUsage)); + message.setText(dialogFormattedText); + builder.setView(dialogView); + builder.setPositiveButton(R.string.storage_clear_dialog_clear_storage_option, + new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int id) { + clearStorage(); + } + }); + builder.setNegativeButton(R.string.cancel, null); + builder.setTitle(R.string.storage_clear_site_storage_title); + builder.create().show(); + } + + @Override + public void onCreatePreferences(Bundle savedInstanceState, String rootKey) { + // Handled in onActivityCreated. Moving the addPreferencesFromResource call up to here + // causes animation jank (crbug.com/985734). + } + + @Override + public void onActivityCreated(Bundle savedInstanceState) { + SettingsUtils.addPreferencesFromResource(this, R.xml.all_site_preferences); + + String title = getArguments().getString(EXTRA_TITLE); + if (title != null) getActivity().setTitle(title); + + mSelectedDomains = getArguments().containsKey(EXTRA_SELECTED_DOMAINS) + ? new HashSet<>(getArguments().getStringArrayList(EXTRA_SELECTED_DOMAINS)) + : null; + + setHasOptionsMenu(true); + + super.onActivityCreated(savedInstanceState); + } + + @Override + public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { + menu.clear(); + inflater.inflate(R.menu.website_preferences_menu, menu); + + mSearchItem = menu.findItem(R.id.search); + SearchUtils.initializeSearchView(mSearchItem, mSearch, getActivity(), (query) -> { + boolean queryHasChanged = + mSearch == null ? query != null && !query.isEmpty() : !mSearch.equals(query); + mSearch = query; + if (queryHasChanged) getInfoForOrigins(); + }); + + if (getSiteSettingsClient().getSiteSettingsHelpClient().isHelpAndFeedbackEnabled()) { + MenuItem help = menu.add( + Menu.NONE, R.id.menu_id_site_settings_help, Menu.NONE, R.string.menu_help); + help.setIcon(VectorDrawableCompat.create( + getResources(), R.drawable.ic_help_and_feedback, getActivity().getTheme())); + } + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + if (item.getItemId() == R.id.menu_id_site_settings_help) { + getSiteSettingsClient() + .getSiteSettingsHelpClient() + .launchSettingsHelpAndFeedbackActivity(getActivity()); + + return true; + } + if (handleSearchNavigation(item, mSearchItem, mSearch, getActivity())) { + boolean queryHasChanged = mSearch != null && !mSearch.isEmpty(); + mSearch = null; + if (queryHasChanged) getInfoForOrigins(); + return true; + } + return false; + } + + @Override + public boolean onPreferenceTreeClick(Preference preference) { + if (preference instanceof WebsitePreference) { + WebsitePreference website = (WebsitePreference) preference; + website.setFragment(SingleWebsiteSettings.class.getName()); + + // EXTRA_SITE re-uses already-fetched permissions, which we can only use if the Website + // was populated with data for all permission types. + website.putSiteIntoExtras(SingleWebsiteSettings.EXTRA_SITE); + + int navigationSource = getArguments().getInt( + SettingsNavigationSource.EXTRA_KEY, SettingsNavigationSource.OTHER); + website.getExtras().putInt(SettingsNavigationSource.EXTRA_KEY, navigationSource); + } + + return super.onPreferenceTreeClick(preference); + } + + @Override + public void onResume() { + super.onResume(); + + if (mSearch == null && mSearchItem != null) { + SearchUtils.clearSearch(mSearchItem, getActivity()); + mSearch = null; + } + + getInfoForOrigins(); + } + + /** + * Reset the preference screen and initialize it again. + */ + private void resetList() { + // This will remove the combo box at the top and all the sites listed below it. + getPreferenceScreen().removeAll(); + // And this will add the filter preference back (combo box). + SettingsUtils.addPreferencesFromResource(this, R.xml.all_site_preferences); + } + + private boolean addWebsites(Collection<Website> sites) { + filterSelectedDomains(sites); + + List<WebsitePreference> websites = new ArrayList<>(); + + // Find origins matching the current search. + for (Website site : sites) { + if (mSearch == null || mSearch.isEmpty() || site.getTitle().contains(mSearch)) { + websites.add(new WebsitePreference( + getStyledContext(), getSiteSettingsClient(), site, mCategory)); + } + } + + if (websites.size() == 0) { + return false; + } + + Collections.sort(websites); + + for (WebsitePreference website : websites) { + getPreferenceScreen().addPreference(website); + } + + mWebsites = websites; + + return websites.size() != 0; + } + + private Context getStyledContext() { + return getPreferenceManager().getContext(); + } + + private void filterSelectedDomains(Collection<Website> websites) { + if (mSelectedDomains == null) { + return; + } + for (Iterator<Website> it = websites.iterator(); it.hasNext();) { + String domain = + UrlUtilities.getDomainAndRegistry(it.next().getAddress().getOrigin(), true); + if (!mSelectedDomains.contains(domain)) { + it.remove(); + } + } + } +}
diff --git a/components/browser_ui/site_settings/android/java/src/org/chromium/components/browser_ui/site_settings/SingleCategorySettings.java b/components/browser_ui/site_settings/android/java/src/org/chromium/components/browser_ui/site_settings/SingleCategorySettings.java index 22e6219..9763d12 100644 --- a/components/browser_ui/site_settings/android/java/src/org/chromium/components/browser_ui/site_settings/SingleCategorySettings.java +++ b/components/browser_ui/site_settings/android/java/src/org/chromium/components/browser_ui/site_settings/SingleCategorySettings.java
@@ -12,12 +12,10 @@ import static org.chromium.components.content_settings.PrefNames.NOTIFICATIONS_VIBRATE_ENABLED; import android.content.Context; -import android.content.DialogInterface; import android.os.Build; import android.os.Bundle; import android.text.Spannable; import android.text.SpannableStringBuilder; -import android.text.format.Formatter; import android.text.style.ForegroundColorSpan; import android.util.Pair; import android.view.LayoutInflater; @@ -26,11 +24,9 @@ import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; -import android.widget.Button; import android.widget.TextView; import androidx.annotation.Nullable; -import androidx.appcompat.app.AlertDialog; import androidx.preference.Preference; import androidx.preference.PreferenceGroup; import androidx.preference.PreferenceManager; @@ -50,7 +46,6 @@ import org.chromium.components.browser_ui.settings.SearchUtils; import org.chromium.components.browser_ui.settings.SettingsUtils; import org.chromium.components.browser_ui.site_settings.FourStateCookieSettingsPreference.CookieSettingsState; -import org.chromium.components.browser_ui.site_settings.Website.StoredDataClearedCallback; import org.chromium.components.content_settings.ContentSettingValues; import org.chromium.components.content_settings.ContentSettingsType; import org.chromium.components.content_settings.CookieControlsMode; @@ -79,7 +74,7 @@ @UsedByReflection("site_settings_preferences.xml") public class SingleCategorySettings extends SiteSettingsPreferenceFragment implements Preference.OnPreferenceChangeListener, Preference.OnPreferenceClickListener, - AddExceptionPreference.SiteAddedCallback, View.OnClickListener, + AddExceptionPreference.SiteAddedCallback, PreferenceManager.OnPreferenceTreeClickListener { // The key to use to pass which category this preference should display, // e.g. Location/Popups/All sites (if blank). @@ -98,8 +93,6 @@ private TextView mEmptyView; // The item for searching the list of items. private MenuItem mSearchItem; - // The clear button displayed in the Storage view. - private Button mClearButton; // The Site Settings Category we are showing. private SiteSettingsCategory mCategory; // If not blank, represents a substring to use to search for site names. @@ -313,10 +306,9 @@ mCategory = SiteSettingsCategory.createFromPreferenceKey( browserContextHandle, getArguments().getString(EXTRA_CATEGORY, "")); } - if (mCategory == null) { - mCategory = SiteSettingsCategory.createFromType( - browserContextHandle, SiteSettingsCategory.Type.ALL_SITES); - } + + assert !(mCategory.showSites(SiteSettingsCategory.Type.ALL_SITES) + || mCategory.showSites(SiteSettingsCategory.Type.USE_STORAGE)); int contentType = mCategory.getContentSettingsType(); mRequiresTriStateSetting = @@ -326,14 +318,6 @@ ViewGroup view = (ViewGroup) super.onCreateView(inflater, container, savedInstanceState); - // Add custom views for Storage Preferences to bottom of the fragment. - if (mCategory.showSites(SiteSettingsCategory.Type.USE_STORAGE)) { - inflater.inflate(R.layout.storage_preferences_view, view, true); - mEmptyView = view.findViewById(R.id.empty_storage); - mClearButton = view.findViewById(R.id.clear_button); - mClearButton.setOnClickListener(this); - } - mListView = getListView(); // Disable animations of preference changes. @@ -352,30 +336,6 @@ return mCategory; } - /** - * This clears all the storage for websites that are displayed to the user. This happens - * asynchronously, and then we call {@link #getInfoForOrigins()} when we're done. - */ - public void clearStorage() { - if (mWebsites == null) return; - RecordUserAction.record("MobileSettingsStorageClearAll"); - - // The goal is to refresh the info for origins again after we've cleared all of them, so we - // wait until the last website is cleared to refresh the origin list. - final int[] numLeft = new int[1]; - numLeft[0] = mWebsites.size(); - for (int i = 0; i < mWebsites.size(); i++) { - WebsitePreference preference = mWebsites.get(i); - preference.site().clearAllStoredData(getSiteSettingsClient().getBrowserContextHandle(), - new StoredDataClearedCallback() { - @Override - public void onStoredDataCleared() { - if (--numLeft[0] <= 0) getInfoForOrigins(); - } - }); - } - } - @Override public void onCreatePreferences(Bundle savedInstanceState, String rootKey) { // Handled in onActivityCreated. Moving the addPreferencesFromResource call up to here @@ -456,13 +416,9 @@ if (preference instanceof WebsitePreference) { WebsitePreference website = (WebsitePreference) preference; website.setFragment(SingleWebsiteSettings.class.getName()); - // EXTRA_SITE re-uses already-fetched permissions, which we can only use if the Website - // was populated with data for all permission types. - if (mCategory.showSites(SiteSettingsCategory.Type.ALL_SITES)) { - website.putSiteIntoExtras(SingleWebsiteSettings.EXTRA_SITE); - } else { - website.putSiteAddressIntoExtras(SingleWebsiteSettings.EXTRA_SITE_ADDRESS); - } + + website.putSiteAddressIntoExtras(SingleWebsiteSettings.EXTRA_SITE_ADDRESS); + int navigationSource = getArguments().getInt( SettingsNavigationSource.EXTRA_KEY, SettingsNavigationSource.OTHER); website.getExtras().putInt(SettingsNavigationSource.EXTRA_KEY, navigationSource); @@ -471,51 +427,6 @@ return super.onPreferenceTreeClick(preference); } - /** OnClickListener for the clear button. We show an alert dialog to confirm the action */ - @Override - public void onClick(View v) { - if (getActivity() == null || v != mClearButton) return; - - long totalUsage = 0; - boolean includesApps = false; - Set<String> originsWithInstalledApp = - getSiteSettingsClient().getWebappSettingsClient().getOriginsWithInstalledApp(); - if (mWebsites != null) { - for (WebsitePreference preference : mWebsites) { - totalUsage += preference.site().getTotalUsage(); - if (!includesApps) { - includesApps = originsWithInstalledApp.contains( - preference.site().getAddress().getOrigin()); - } - } - } - - AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); - View dialogView = - getActivity().getLayoutInflater().inflate(R.layout.clear_data_dialog, null); - TextView message = dialogView.findViewById(android.R.id.message); - TextView signedOutText = dialogView.findViewById(R.id.signed_out_text); - TextView offlineText = dialogView.findViewById(R.id.offline_text); - signedOutText.setText(R.string.webstorage_clear_data_dialog_sign_out_all_message); - offlineText.setText(R.string.webstorage_clear_data_dialog_offline_message); - String dialogFormattedText = - getString(includesApps ? R.string.webstorage_clear_data_dialog_message_with_app - : R.string.webstorage_clear_data_dialog_message, - Formatter.formatShortFileSize(getActivity(), totalUsage)); - message.setText(dialogFormattedText); - builder.setView(dialogView); - builder.setPositiveButton(R.string.storage_clear_dialog_clear_storage_option, - new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int id) { - clearStorage(); - } - }); - builder.setNegativeButton(R.string.cancel, null); - builder.setTitle(R.string.storage_clear_site_storage_title); - builder.create().show(); - } - // OnPreferenceChangeListener: @Override public boolean onPreferenceChange(Preference preference, Object newValue) { @@ -527,9 +438,7 @@ for (@SiteSettingsCategory.Type int type = 0; type < SiteSettingsCategory.Type.NUM_ENTRIES; type++) { - if (type == SiteSettingsCategory.Type.ALL_SITES - || type == SiteSettingsCategory.Type.USE_STORAGE - || !mCategory.showSites(type)) { + if (!mCategory.showSites(type)) { continue; } @@ -947,16 +856,8 @@ PreferenceGroup blockedGroup = (PreferenceGroup) screen.findPreference(BLOCKED_GROUP); PreferenceGroup managedGroup = (PreferenceGroup) screen.findPreference(MANAGED_GROUP); boolean permissionBlockedByOs = mCategory.showPermissionBlockedMessage(getActivity()); - // For these categories, no binary, tri-state or custom toggles should be shown. - boolean hideMainToggles = mCategory.showSites(SiteSettingsCategory.Type.ALL_SITES) - || mCategory.showSites(SiteSettingsCategory.Type.USE_STORAGE); - boolean hideSecondaryToggles = hideMainToggles || permissionBlockedByOs; - if (hideMainToggles) { - screen.removePreference(binaryToggle); - screen.removePreference(triStateToggle); - screen.removePreference(fourStateCookieToggle); - } else if (mRequiresTriStateSetting) { + if (mRequiresTriStateSetting) { screen.removePreference(binaryToggle); screen.removePreference(fourStateCookieToggle); configureTriStateToggle(triStateToggle, contentType); @@ -970,15 +871,13 @@ configureBinaryToggle(binaryToggle, contentType); } - if (permissionBlockedByOs) { - maybeShowOsWarning(screen); - } - if (!mCategory.showSites(SiteSettingsCategory.Type.COOKIES)) { screen.removePreference(screen.findPreference(COOKIE_INFO_TEXT_KEY)); } - if (hideSecondaryToggles) { + if (permissionBlockedByOs) { + maybeShowOsWarning(screen); + screen.removePreference(thirdPartyCookies); screen.removePreference(notificationsVibrate); screen.removePreference(notificationsQuietUi);
diff --git a/components/gwp_asan/buildflags/buildflags.gni b/components/gwp_asan/buildflags/buildflags.gni index f1cc47f8..06769f9 100644 --- a/components/gwp_asan/buildflags/buildflags.gni +++ b/components/gwp_asan/buildflags/buildflags.gni
@@ -3,7 +3,6 @@ # found in the LICENSE file. import("//base/allocator/allocator.gni") -import("//build/config/allocator.gni") import("//build/config/compiler/compiler.gni") # Windows/x86 is disabled due to https://crbug.com/969146
diff --git a/components/gwp_asan/client/BUILD.gn b/components/gwp_asan/client/BUILD.gn index e082144..6c66092f 100644 --- a/components/gwp_asan/client/BUILD.gn +++ b/components/gwp_asan/client/BUILD.gn
@@ -3,7 +3,6 @@ # found in the LICENSE file. import("//base/allocator/allocator.gni") -import("//build/config/allocator.gni") component("client") { output_name = "gwp_asan_client"
diff --git a/components/mirroring/service/receiver_response.cc b/components/mirroring/service/receiver_response.cc index 01de36c..f3f99234 100644 --- a/components/mirroring/service/receiver_response.cc +++ b/components/mirroring/service/receiver_response.cc
@@ -150,10 +150,18 @@ std::unique_ptr<ReceiverCapability> ParseCapability(const Json::Value& value) { auto capability = std::make_unique<ReceiverCapability>(); - if (!value || - !GetStringArray(value["mediaCaps"], &(capability->media_caps))) { + + if (!value) + return {}; + + if (!GetInt(value["remoting"], &(capability->remoting))) { + capability->remoting = ReceiverCapability::kRemotingVersionUnknown; + } + + if (!GetStringArray(value["mediaCaps"], &(capability->media_caps))) { return {}; } + return capability; }
diff --git a/components/mirroring/service/receiver_response.h b/components/mirroring/service/receiver_response.h index a03d6fd..ba68b25 100644 --- a/components/mirroring/service/receiver_response.h +++ b/components/mirroring/service/receiver_response.h
@@ -49,6 +49,11 @@ ReceiverCapability& operator=(ReceiverCapability&& receiver_response); ReceiverCapability& operator=(const ReceiverCapability& receiver_response); + static constexpr int kRemotingVersionUnknown = -1; + + // The remoting version that the receiver uses. + int remoting = kRemotingVersionUnknown; + // Set of capabilities (e.g., ac3, 4k, hevc, vp9, dolby_vision, etc.). std::vector<std::string> media_caps; };
diff --git a/components/mirroring/service/receiver_response_unittest.cc b/components/mirroring/service/receiver_response_unittest.cc index 7898e78..d9983fa 100644 --- a/components/mirroring/service/receiver_response_unittest.cc +++ b/components/mirroring/service/receiver_response_unittest.cc
@@ -143,6 +143,7 @@ "type": "CAPABILITIES_RESPONSE", "result": "ok", "capabilities": { + "remoting": 2, "mediaCaps": ["audio", "video", "vp9"], "keySystems": [ { @@ -171,6 +172,7 @@ ASSERT_TRUE(response->valid()); EXPECT_EQ(std::vector<std::string>({"audio", "video", "vp9"}), response->capabilities().media_caps); + EXPECT_EQ(2, response->capabilities().remoting); } TEST_F(ReceiverResponseTest, ParseRpcMessage) {
diff --git a/components/mirroring/service/session.cc b/components/mirroring/service/session.cc index 8de6bc2..27624971 100644 --- a/components/mirroring/service/session.cc +++ b/components/mirroring/service/session.cc
@@ -90,6 +90,9 @@ constexpr int kVideoSsrcMin = 5e5 + 1; constexpr int kVideoSsrcMax = 10e5; +// The implemented remoting version. +constexpr int kSupportedRemotingVersion = 2; + class TransportClient final : public media::cast::CastTransport::Client { public: explicit TransportClient(Session* session) : session_(session) {} @@ -983,6 +986,22 @@ } return; } + + // Check if the remoting version used in the receiver is supported or not. + int remoting_version = response.capabilities().remoting; + + // For backwards-compatibility, if the remoting version field was not set, + // assume it is 1. + if (remoting_version == ReceiverCapability::kRemotingVersionUnknown) { + remoting_version = 1; + } + + if (remoting_version > kSupportedRemotingVersion) { + VLOG(1) << "Unsupported remoting version (" << remoting_version << " > " + << kSupportedRemotingVersion << ')'; + return; + } + const std::vector<std::string>& caps = response.capabilities().media_caps; std::string build_version;
diff --git a/components/mirroring/service/session_unittest.cc b/components/mirroring/service/session_unittest.cc index ca53d56..d5cdf53 100644 --- a/components/mirroring/service/session_unittest.cc +++ b/components/mirroring/service/session_unittest.cc
@@ -331,6 +331,7 @@ EXPECT_CALL(*this, OnConnectToRemotingSource()).Times(1); EXPECT_CALL(remoting_source_, OnSinkAvailable(_)).Times(1); auto capabilities = std::make_unique<ReceiverCapability>(); + capabilities->remoting = 2; capabilities->media_caps = std::vector<std::string>({"video", "audio", "vp8", "opus"}); auto response = ReceiverResponse::CreateCapabilitiesResponseForTesting(
diff --git a/components/password_manager/core/browser/android_affiliation/affiliated_match_helper_unittest.cc b/components/password_manager/core/browser/android_affiliation/affiliated_match_helper_unittest.cc index 3bd43a2..16544397 100644 --- a/components/password_manager/core/browser/android_affiliation/affiliated_match_helper_unittest.cc +++ b/components/password_manager/core/browser/android_affiliation/affiliated_match_helper_unittest.cc
@@ -29,11 +29,9 @@ using StrategyOnCacheMiss = AndroidAffiliationService::StrategyOnCacheMiss; -class MockAffiliationService - : public testing::StrictMock<AndroidAffiliationService> { +class MockAndroidAffiliationService : public AndroidAffiliationService { public: - MockAffiliationService() - : testing::StrictMock<AndroidAffiliationService>(nullptr) { + MockAndroidAffiliationService() : AndroidAffiliationService(nullptr) { testing::DefaultValue<AffiliatedFacets>::Set(AffiliatedFacets()); } @@ -87,9 +85,6 @@ expected_facet_uri_spec))) .RetiresOnSaturation(); } - - private: - DISALLOW_ASSIGN(MockAffiliationService); }; const char kTestWebFacetURIAlpha1[] = "https://one.alpha.example.com"; @@ -305,7 +300,7 @@ TestPasswordStore* password_store() { return password_store_.get(); } - MockAffiliationService* mock_affiliation_service() { + MockAndroidAffiliationService* mock_affiliation_service() { return mock_affiliation_service_; } @@ -328,7 +323,8 @@ // testing::Test: void SetUp() override { - auto service = std::make_unique<MockAffiliationService>(); + auto service = + std::make_unique<testing::StrictMock<MockAndroidAffiliationService>>(); mock_affiliation_service_ = service.get(); password_store_->Init(nullptr); @@ -357,9 +353,7 @@ std::unique_ptr<AffiliatedMatchHelper> match_helper_; // Owned by |match_helper_|. - MockAffiliationService* mock_affiliation_service_ = nullptr; - - DISALLOW_COPY_AND_ASSIGN(AffiliatedMatchHelperTest); + MockAndroidAffiliationService* mock_affiliation_service_ = nullptr; }; // GetAffiliatedAndroidRealm* tests verify that GetAffiliatedAndroidRealms()
diff --git a/components/password_manager/core/browser/ui/compromised_credentials_manager.cc b/components/password_manager/core/browser/ui/compromised_credentials_manager.cc index e79ed75f..1ff0e0e 100644 --- a/components/password_manager/core/browser/ui/compromised_credentials_manager.cc +++ b/components/password_manager/core/browser/ui/compromised_credentials_manager.cc
@@ -216,15 +216,13 @@ if (saved_password.password_value == credential.password() && CanonicalizeUsername(saved_password.username_value) == canonicalized_username) { - PasswordStore& store = saved_password.IsUsingAccountStore() - ? *account_store_ - : *profile_store_; - store.AddCompromisedCredentials({ - .signon_realm = saved_password.signon_realm, - .username = saved_password.username_value, - .create_time = base::Time::Now(), - .compromise_type = CompromiseType::kLeaked, - }); + GetStoreFor(saved_password) + .AddCompromisedCredentials({ + .signon_realm = saved_password.signon_realm, + .username = saved_password.username_value, + .create_time = base::Time::Now(), + .compromise_type = CompromiseType::kLeaked, + }); } } } @@ -243,7 +241,7 @@ return false; for (size_t i = 1; i < forms.size(); ++i) - profile_store_->RemoveLogin(forms[i]); + GetStoreFor(forms[i]).RemoveLogin(forms[i]); // Note: We Invoke EditPassword on the presenter rather than UpdateLogin() on // the store, so that observers of the presenter get notified of this event. @@ -260,7 +258,7 @@ // credentials were deleted. const auto& saved_passwords = it->second.forms; for (const autofill::PasswordForm& saved_password : saved_passwords) - profile_store_->RemoveLogin(saved_password); + GetStoreFor(saved_password).RemoveLogin(saved_password); return !saved_passwords.empty(); } @@ -313,4 +311,9 @@ } } +PasswordStore& CompromisedCredentialsManager::GetStoreFor( + const autofill::PasswordForm& form) { + return form.IsUsingAccountStore() ? *account_store_ : *profile_store_; +} + } // namespace password_manager
diff --git a/components/password_manager/core/browser/ui/compromised_credentials_manager.h b/components/password_manager/core/browser/ui/compromised_credentials_manager.h index ac58a19..d48134c0 100644 --- a/components/password_manager/core/browser/ui/compromised_credentials_manager.h +++ b/components/password_manager/core/browser/ui/compromised_credentials_manager.h
@@ -162,6 +162,10 @@ void UpdateCachedDataAndNotifyObservers( SavedPasswordsPresenter::SavedPasswordsView saved_passwords); + // Returns the `profile_store_` or `account_store_` if `form` is stored in the + // profile store of the account store accordingly. + PasswordStore& GetStoreFor(const autofill::PasswordForm& form); + // A weak handle to the presenter used to join the list of compromised // credentials with saved passwords. Needs to outlive this instance. SavedPasswordsPresenter* presenter_ = nullptr;
diff --git a/components/password_manager/core/browser/ui/compromised_credentials_manager_unittest.cc b/components/password_manager/core/browser/ui/compromised_credentials_manager_unittest.cc index 25e5bc05..f7dcc5f8 100644 --- a/components/password_manager/core/browser/ui/compromised_credentials_manager_unittest.cc +++ b/components/password_manager/core/browser/ui/compromised_credentials_manager_unittest.cc
@@ -642,4 +642,31 @@ EXPECT_EQ(1U, profile_store().compromised_credentials().size()); EXPECT_EQ(2U, account_store().compromised_credentials().size()); } + +TEST_F(CompromisedCredentialsManagerWithTwoStoresTest, + RemoveCompromisedCredential) { + // Add `kUsername1`,`kPassword1` to both stores. + profile_store().AddLogin( + MakeSavedPassword(kExampleCom, kUsername1, kPassword1)); + account_store().AddLogin( + MakeSavedPassword(kExampleCom, kUsername1, kPassword1)); + + // Mark `kUsername1` and `kPassword1` to be compromised in both stores. + profile_store().AddCompromisedCredentials( + MakeCompromised(kExampleCom, kUsername1)); + account_store().AddCompromisedCredentials( + MakeCompromised(kExampleCom, kUsername1)); + RunUntilIdle(); + + // Now remove the compromised credentials + EXPECT_TRUE(provider().RemoveCompromisedCredential( + CredentialView(kExampleCom, GURL(), base::ASCIIToUTF16(kUsername1), + base::ASCIIToUTF16(kPassword1)))); + RunUntilIdle(); + + // It should have been removed from both stores. + EXPECT_TRUE(profile_store().stored_passwords().at(kExampleCom).empty()); + EXPECT_TRUE(account_store().stored_passwords().at(kExampleCom).empty()); +} + } // namespace password_manager
diff --git a/components/password_manager/ios/password_suggestion_helper.mm b/components/password_manager/ios/password_suggestion_helper.mm index 1d133e0..75a9dcc9 100644 --- a/components/password_manager/ios/password_suggestion_helper.mm +++ b/components/password_manager/ios/password_suggestion_helper.mm
@@ -7,6 +7,7 @@ #include "base/strings/sys_string_conversions.h" #include "components/autofill/core/common/form_data.h" #import "components/autofill/ios/browser/form_suggestion.h" +#include "components/password_manager/core/browser/password_ui_utils.h" #include "components/password_manager/ios/account_select_fill_data.h" #include "ios/web/public/js_messaging/web_frame.h" #include "ios/web/public/js_messaging/web_frame_util.h" @@ -69,9 +70,11 @@ for (const auto& usernameAndRealm : usernameAndRealms) { NSString* username = SysUTF16ToNSString(usernameAndRealm.username); - NSString* realm = usernameAndRealm.realm.empty() - ? nil - : SysUTF8ToNSString(usernameAndRealm.realm); + NSString* realm = nil; + if (!usernameAndRealm.realm.empty()) { + url::Origin origin = url::Origin::Create(GURL(usernameAndRealm.realm)); + realm = SysUTF8ToNSString(password_manager::GetShownOrigin(origin)); + } [results addObject:[FormSuggestion suggestionWithValue:username displayDescription:realm icon:nil
diff --git a/components/payments/content/payment_request.cc b/components/payments/content/payment_request.cc index da0793c..13af88b0 100644 --- a/components/payments/content/payment_request.cc +++ b/components/payments/content/payment_request.cc
@@ -754,6 +754,21 @@ : JourneyLogger::ABORT_REASON_MERCHANT_NAVIGATION); } +void PaymentRequest::RenderFrameDeleted( + content::RenderFrameHost* render_frame_host) { + DCHECK(render_frame_host == + content::RenderFrameHost::FromID(initiator_frame_routing_id_)); + // RenderFrameHost is usually deleted explicitly before PaymentRequest + // destruction if the user closes the tab or browser window without closing + // the payment request dialog. + RecordFirstAbortReason(JourneyLogger::ABORT_REASON_ABORTED_BY_USER); + // But don't bother sending errors to |client_| because the mojo pipe will be + // torn down anyways when RenderFrameHost is destroyed. It's not safe to call + // UserCancelled() here because it is not re-entrant. + // TODO(crbug.com/1121841) Make UserCancelled re-entrant. + OnConnectionTerminated(); +} + void PaymentRequest::OnConnectionTerminated() { // We are here because of a browser-side error, or likely as a result of the // disconnect_handler on |receiver_|, which can mean that the renderer
diff --git a/components/payments/content/payment_request.h b/components/payments/content/payment_request.h index 44a13ee9..da18347 100644 --- a/components/payments/content/payment_request.h +++ b/components/payments/content/payment_request.h
@@ -111,6 +111,12 @@ // another document, but before the PaymentRequest is destroyed. void DidStartMainFrameNavigationToDifferentDocument(bool is_user_initiated); + // Called when the frame attached to this PaymentRequest is about to be + // destroyed. This is used to clean up before the RenderFrameHost is actually + // destroyed because some objects held by the PaymentRequest (e.g. + // InternalAuthenticator) must be out-lived by the RenderFrameHost. + void RenderFrameDeleted(content::RenderFrameHost* render_frame_host); + // As a result of a browser-side error or renderer-initiated mojo channel // closure (e.g. there was an error on the renderer side, or payment was // successful), this method is called. It is responsible for cleaning up, @@ -130,6 +136,10 @@ content::WebContents* web_contents() { return web_contents_; } + const content::GlobalFrameRoutingId& initiator_frame_routing_id() { + return initiator_frame_routing_id_; + } + bool skipped_payment_request_ui() { return skipped_payment_request_ui_; } bool is_show_user_gesture() const { return is_show_user_gesture_; }
diff --git a/components/payments/content/payment_request_web_contents_manager.cc b/components/payments/content/payment_request_web_contents_manager.cc index b971e85..63391f7 100644 --- a/components/payments/content/payment_request_web_contents_manager.cc +++ b/components/payments/content/payment_request_web_contents_manager.cc
@@ -66,6 +66,22 @@ } } +void PaymentRequestWebContentsManager::RenderFrameDeleted( + content::RenderFrameHost* render_frame_host) { + // Two passes to avoid modifying the |payment_requests_| map while iterating + // over it. + std::vector<PaymentRequest*> obsolete; + for (auto& it : payment_requests_) { + if (content::RenderFrameHost::FromID( + it.second->initiator_frame_routing_id()) == render_frame_host) { + obsolete.push_back(it.first); + } + } + for (auto* request : obsolete) { + request->RenderFrameDeleted(render_frame_host); + } +} + void PaymentRequestWebContentsManager::DestroyRequest(PaymentRequest* request) { request->HideIfNecessary(); payment_requests_.erase(request);
diff --git a/components/payments/content/payment_request_web_contents_manager.h b/components/payments/content/payment_request_web_contents_manager.h index 3f9e72b..a00ef17b 100644 --- a/components/payments/content/payment_request_web_contents_manager.h +++ b/components/payments/content/payment_request_web_contents_manager.h
@@ -59,6 +59,7 @@ // WebContentsObserver:: void DidStartNavigation( content::NavigationHandle* navigation_handle) override; + void RenderFrameDeleted(content::RenderFrameHost* render_frame_host) override; private: explicit PaymentRequestWebContentsManager(content::WebContents* web_contents);
diff --git a/components/policy/core/common/policy_service_impl.cc b/components/policy/core/common/policy_service_impl.cc index d607651..a1055d6 100644 --- a/components/policy/core/common/policy_service_impl.cc +++ b/components/policy/core/common/policy_service_impl.cc
@@ -302,15 +302,6 @@ atomic_policy_group_enabled_policy_value->source == POLICY_SOURCE_PRIORITY_CLOUD) && atomic_policy_group_enabled_policy_value->scope == POLICY_SCOPE_USER); - auto* value = - chrome_policies.GetValue(key::kExtensionInstallListsMergeEnabled); - if (value && value->GetBool()) { - policy_lists_to_merge.insert(key::kExtensionInstallForcelist); - policy_lists_to_merge.insert(key::kExtensionInstallBlacklist); - policy_lists_to_merge.insert(key::kExtensionInstallBlocklist); - policy_lists_to_merge.insert(key::kExtensionInstallWhitelist); - policy_lists_to_merge.insert(key::kExtensionInstallAllowlist); - } PolicyListMerger policy_list_merger(std::move(policy_lists_to_merge)); PolicyDictionaryMerger policy_dictionary_merger(
diff --git a/components/policy/resources/policy_templates.json b/components/policy/resources/policy_templates.json index a1492be..6fa3897 100644 --- a/components/policy/resources/policy_templates.json +++ b/components/policy/resources/policy_templates.json
@@ -460,7 +460,6 @@ 'ExtensionAllowedTypes', 'ExtensionAllowInsecureUpdates', 'ExtensionSettings', - 'ExtensionInstallListsMergeEnabled', 'BlockExternalExtensions', ], }, @@ -4730,27 +4729,6 @@ Note: For Windows® instances not joined to a <ph name="MS_AD_NAME">Microsoft® Active Directory®</ph> domain, forced installation is limited to apps and extensions listed in the Chrome Web Store.''', }, { - 'name': 'ExtensionInstallListsMergeEnabled', - 'owners': ['file://components/policy/resources/OWNERS'], - 'type': 'main', - 'schema': { 'type': 'boolean' }, - 'supported_on': ['chrome.*: 75-'], - 'future': True, - 'features': { - 'dynamic_refresh': True, - 'per_profile': True, - }, - 'example_value': True, - 'id': 544, - 'caption': '''Merge extension install list policies from multiple sources''', - 'tags': [], - 'desc': '''Enables merging of the extension install list policies <ph name="EXTENSION_INSTALL_BLOCKLIST_POLICY_NAME">ExtensionInstallBlocklist</ph>, <ph name="EXTENSION_INSTALL_ALLOWLIST_POLICY_NAME">ExtensionInstallAllowlist</ph> and <ph name="EXTENSION_INSTALL_FORCELIST_POLICY_NAME">ExtensionInstallForcelist</ph>. - - If you enable this setting, the values from machine platform policy, machine cloud policy and user platform policy are merged into a single list and used as a whole instead of only using the values from the single source with highest priority. - - If you disable this setting or leave it unset, only list entries from the highest priority source are taken and all other sources are shown as conflicts but ignored.''', - }, - { 'name': 'BlockExternalExtensions', 'owners': ['file://components/policy/resources/OWNERS'], 'type': 'main', @@ -8323,50 +8301,6 @@ 'desc': '''This setting has been retired as of <ph name="PRODUCT_NAME">$1<ex>Google Chrome</ex></ph> version 29. The recommended way to set up organization-hosted extension/app collections is to include the site hosting the CRX packages in ExtensionInstallSources and put direct download links to the packages on a web page. A launcher for that web page can be created using the ExtensionInstallForcelist policy.''', }, { - 'name': 'EnableOriginBoundCerts', - 'owners': ['file://src/net/OWNERS'], - 'type': 'main', - 'schema': { 'type': 'boolean' }, - 'supported_on': ['chrome.*:17-35'], - 'features': { - 'dynamic_refresh': True, - 'per_profile': False, - }, - 'deprecated': True, - 'future': True, - 'example_value': True, - 'id': 114, - 'caption': '''Enable TLS domain-bound certificates extension (deprecated)''', - 'tags': [], - 'desc': '''This policy has been retired as of <ph name="PRODUCT_NAME">$1<ex>Google Chrome</ex></ph> version 36. - - Specifies whether the TLS domain-bound certificates extension should be enabled. - - This setting is used to enable the TLS domain-bound certificates extension for testing. This experimental setting will be removed in the future.''', - }, - { - 'name': 'EnableMemoryInfo', - 'owners': ['file://components/policy/resources/OWNERS'], - 'type': 'main', - 'schema': { 'type': 'boolean' }, - 'supported_on': ['chrome.*:17-34', 'chrome_os:18-34'], - 'features': { - 'dynamic_refresh': True, - 'per_profile': True, - }, - 'deprecated': True, - 'future': True, - 'example_value': False, - 'id': 115, - 'caption': '''Enable reporting memory info (JS heap size) to page (deprecated)''', - 'tags': [], - 'desc': '''This policy has been retired as of <ph name="PRODUCT_NAME">$1<ex>Google Chrome</ex></ph> version 35. - - Memory info is anyway reported to page, regardless of the option value, but the sizes reported are - quantized and the rate of updates is limited for security reasons. To obtain real-time precise data, - please use tools like Telemetry.''', - }, - { 'name': 'DisablePrintPreview', 'owners': ['file://printing/OWNERS'], 'type': 'main', @@ -12891,10 +12825,10 @@ 'features': { 'dynamic_refresh': False, 'per_profile': False, + 'internal_only': True, }, 'example_value': 'restricted', 'id': 196, - 'future': True, 'caption': '''Set the restriction on the fetching of the Variations seed''', 'tags': [], 'desc': '''Add a parameter to the fetching of the Variations seed in <ph name="PRODUCT_NAME">$1<ex>Google Chrome</ex></ph>. @@ -12911,11 +12845,11 @@ 'supported_on': ['chrome_os:28-'], 'features': { 'dynamic_refresh': False, + 'internal_only': True, }, 'device_only': True, 'example_value': 'restricted', 'id': 199, - 'future': True, 'caption': '''Set the restriction on the fetching of the Variations seed''', 'tags': [], 'desc': '''Add a parameter to the fetching of the Variations seed in <ph name="PRODUCT_OS_NAME">$2<ex>Google Chrome OS</ex></ph>. @@ -24172,7 +24106,7 @@ }, ], 'placeholders': [], - 'deleted_policy_ids': [412, 476, 546, 562, 569, 578], + 'deleted_policy_ids': [114, 115, 412, 476, 544, 546, 562, 569, 578], 'highest_id_currently_used': 783, 'highest_atomic_group_id_currently_used': 40 }
diff --git a/components/test/data/payments/can_make_payment_checker.js b/components/test/data/payments/can_make_payment_checker.js index c449b725..ef6ce60 100644 --- a/components/test/data/payments/can_make_payment_checker.js +++ b/components/test/data/payments/can_make_payment_checker.js
@@ -4,6 +4,10 @@ * found in the LICENSE file. */ +const kDetails = { + total: {label: 'TEST', amount: {currency: 'USD', value: '0.01'}}, +}; + /** * Checks whether the given payment method can make payments. * @param {string} method - The payment method identifier to check. @@ -11,12 +15,40 @@ */ async function canMakePayment(method) { // eslint-disable-line no-unused-vars, max-len try { - const request = new PaymentRequest( - [{supportedMethods: method}], - {total: {label: 'TEST', amount: {currency: 'USD', value: '0.01'}}}); + const request = new PaymentRequest([{supportedMethods: method}], kDetails); const result = await request.canMakePayment(); return result ? 'true' : 'false'; } catch (e) { return e.message; } } + +/** + * Creates a PaymentRequest with |methodData| and checks canMakePayment. + * @param {object} methodData - The payment method data to build the request. + * @return {string} - 'true', 'false', or error message on failure. + */ +async function canMakePaymentForMethodData(methodData) { // eslint-disable-line no-unused-vars, max-len + try { + const request = new PaymentRequest(methodData, kDetails); + const result = await request.canMakePayment(); + return result ? 'true' : 'false'; + } catch (e) { + return e.message; + } +} + +/** + * Creates a PaymentRequest with |methodData| and checks hasEnrolledInstrument. + * @param {object} methodData - The payment method data to build the request. + * @return {string} - 'true', 'false', or error message on failure. + */ +async function hasEnrolledInstrumentForMethodData(methodData) { // eslint-disable-line no-unused-vars, max-len + try { + const request = new PaymentRequest(methodData, kDetails); + const result = await request.hasEnrolledInstrument(); + return result ? 'true' : 'false'; + } catch (e) { + return e.message; + } +}
diff --git a/components/url_formatter/spoof_checks/idn_spoof_checker.cc b/components/url_formatter/spoof_checks/idn_spoof_checker.cc index 5086f92..6d66a7c 100644 --- a/components/url_formatter/spoof_checks/idn_spoof_checker.cc +++ b/components/url_formatter/spoof_checks/idn_spoof_checker.cc
@@ -291,7 +291,7 @@ // The ideal fix would be to change the omnibox font used for Thai. In // that case, the Linux-only list should be revisited and potentially // removed. -#if defined(OS_LINUX) +#if defined(OS_LINUX) || defined(OS_CHROMEOS) "[ทนบพรหเแ๐ดลปฟม]", #else "[บพเแ๐]",
diff --git a/components/url_formatter/spoof_checks/idn_spoof_checker_unittest.cc b/components/url_formatter/spoof_checks/idn_spoof_checker_unittest.cc index 4a2b061..b44c024 100644 --- a/components/url_formatter/spoof_checks/idn_spoof_checker_unittest.cc +++ b/components/url_formatter/spoof_checks/idn_spoof_checker_unittest.cc
@@ -1236,7 +1236,7 @@ {"xn--rmdcmef.mm", L"႐႑႕႖႗.mm", kSafe}, {"xn--rmdcmef.xn--7idjb0f4ck", L"႐႑႕႖႗.မြန်မာ", kSafe}, // Thai: -#if defined(OS_LINUX) +#if defined(OS_LINUX) || defined(OS_CHROMEOS) {"xn--o3cedqz2c.com", L"ทนบพรห.com", kUnsafe}, {"xn--o3cedqz2c.th", L"ทนบพรห.th", kSafe}, {"xn--o3cedqz2c.xn--o3cw4h", L"ทนบพรห.ไทย", kSafe},
diff --git a/components/viz/common/BUILD.gn b/components/viz/common/BUILD.gn index 47f43951d..a4ecf26 100644 --- a/components/viz/common/BUILD.gn +++ b/components/viz/common/BUILD.gn
@@ -186,6 +186,10 @@ "hit_test/aggregated_hit_test_region.h", "hit_test/hit_test_region_list.cc", "hit_test/hit_test_region_list.h", + "quads/aggregated_render_pass.cc", + "quads/aggregated_render_pass.h", + "quads/aggregated_render_pass_draw_quad.cc", + "quads/aggregated_render_pass_draw_quad.h", "quads/compositor_frame.cc", "quads/compositor_frame.h", "quads/compositor_frame_metadata.cc", @@ -208,6 +212,10 @@ "quads/render_pass.h", "quads/render_pass_draw_quad.cc", "quads/render_pass_draw_quad.h", + "quads/render_pass_draw_quad_internal.cc", + "quads/render_pass_draw_quad_internal.h", + "quads/render_pass_internal.cc", + "quads/render_pass_internal.h", "quads/render_pass_io.cc", "quads/render_pass_io.h", "quads/selection.h",
diff --git a/components/viz/common/quads/aggregated_render_pass.cc b/components/viz/common/quads/aggregated_render_pass.cc new file mode 100644 index 0000000..c76484b --- /dev/null +++ b/components/viz/common/quads/aggregated_render_pass.cc
@@ -0,0 +1,209 @@ +// Copyright 2020 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "components/viz/common/quads/aggregated_render_pass.h" + +#include "base/memory/ptr_util.h" +#include "base/numerics/safe_conversions.h" +#include "base/values.h" +#include "cc/base/math_util.h" +#include "components/viz/common/quads/aggregated_render_pass_draw_quad.h" +#include "components/viz/common/quads/debug_border_draw_quad.h" +#include "components/viz/common/quads/draw_quad.h" +#include "components/viz/common/quads/largest_draw_quad.h" +#include "components/viz/common/quads/picture_draw_quad.h" +#include "components/viz/common/quads/render_pass_draw_quad.h" +#include "components/viz/common/quads/shared_quad_state.h" +#include "components/viz/common/quads/solid_color_draw_quad.h" +#include "components/viz/common/quads/stream_video_draw_quad.h" +#include "components/viz/common/quads/surface_draw_quad.h" +#include "components/viz/common/quads/texture_draw_quad.h" +#include "components/viz/common/quads/tile_draw_quad.h" +#include "components/viz/common/quads/video_hole_draw_quad.h" +#include "components/viz/common/quads/yuv_video_draw_quad.h" + +namespace viz { + +AggregatedRenderPass::AggregatedRenderPass() = default; +AggregatedRenderPass::~AggregatedRenderPass() = default; + +AggregatedRenderPass::AggregatedRenderPass(size_t shared_quad_state_size, + size_t draw_quad_size) + : RenderPassInternal(shared_quad_state_size, draw_quad_size) {} + +void AggregatedRenderPass::SetNew( + AggregatedRenderPassId id, + const gfx::Rect& output_rect, + const gfx::Rect& damage_rect, + const gfx::Transform& transform_to_root_target) { + DCHECK(id); + DCHECK(damage_rect.IsEmpty() || output_rect.Contains(damage_rect)) + << "damage_rect: " << damage_rect.ToString() + << " output_rect: " << output_rect.ToString(); + + this->id = id; + this->output_rect = output_rect; + this->damage_rect = damage_rect; + this->transform_to_root_target = transform_to_root_target; + + DCHECK(quad_list.empty()); + DCHECK(shared_quad_state_list.empty()); +} + +void AggregatedRenderPass::SetAll( + AggregatedRenderPassId id, + const gfx::Rect& output_rect, + const gfx::Rect& damage_rect, + const gfx::Transform& transform_to_root_target, + const cc::FilterOperations& filters, + const cc::FilterOperations& backdrop_filters, + const base::Optional<gfx::RRectF>& backdrop_filter_bounds, + gfx::ContentColorUsage content_color_usage, + bool has_transparent_background, + bool cache_render_pass, + bool has_damage_from_contributing_content, + bool generate_mipmap) { + DCHECK(id); + + this->id = id; + this->output_rect = output_rect; + this->damage_rect = damage_rect; + this->transform_to_root_target = transform_to_root_target; + this->filters = filters; + this->backdrop_filters = backdrop_filters; + this->backdrop_filter_bounds = backdrop_filter_bounds; + this->content_color_usage = content_color_usage; + this->has_transparent_background = has_transparent_background; + this->cache_render_pass = cache_render_pass; + this->has_damage_from_contributing_content = + has_damage_from_contributing_content; + this->generate_mipmap = generate_mipmap; + + DCHECK(quad_list.empty()); + DCHECK(shared_quad_state_list.empty()); +} + +AggregatedRenderPassDrawQuad* +AggregatedRenderPass::CopyFromAndAppendRenderPassDrawQuad( + const RenderPassDrawQuad* quad, + AggregatedRenderPassId render_pass_id) { + DCHECK(!shared_quad_state_list.empty()); + auto* copy_quad = CreateAndAppendDrawQuad<AggregatedRenderPassDrawQuad>(); + copy_quad->SetAll( + shared_quad_state_list.back(), quad->rect, quad->visible_rect, + quad->needs_blending, render_pass_id, quad->mask_resource_id(), + quad->mask_uv_rect, quad->mask_texture_size, quad->filters_scale, + quad->filters_origin, quad->tex_coord_rect, quad->force_anti_aliasing_off, + quad->backdrop_filter_quality, quad->can_use_backdrop_filter_cache); + return copy_quad; +} + +AggregatedRenderPassDrawQuad* +AggregatedRenderPass::CopyFromAndAppendRenderPassDrawQuad( + const AggregatedRenderPassDrawQuad* quad) { + DCHECK(!shared_quad_state_list.empty()); + auto* copy_quad = + CopyFromAndAppendTypedDrawQuad<AggregatedRenderPassDrawQuad>(quad); + copy_quad->shared_quad_state = shared_quad_state_list.back(); + return copy_quad; +} + +DrawQuad* AggregatedRenderPass::CopyFromAndAppendDrawQuad( + const DrawQuad* quad) { + DCHECK(!shared_quad_state_list.empty()); + switch (quad->material) { + case DrawQuad::Material::kDebugBorder: + CopyFromAndAppendTypedDrawQuad<DebugBorderDrawQuad>(quad); + break; + case DrawQuad::Material::kPictureContent: + CopyFromAndAppendTypedDrawQuad<PictureDrawQuad>(quad); + break; + case DrawQuad::Material::kTextureContent: + CopyFromAndAppendTypedDrawQuad<TextureDrawQuad>(quad); + break; + case DrawQuad::Material::kSolidColor: + CopyFromAndAppendTypedDrawQuad<SolidColorDrawQuad>(quad); + break; + case DrawQuad::Material::kTiledContent: + CopyFromAndAppendTypedDrawQuad<TileDrawQuad>(quad); + break; + case DrawQuad::Material::kStreamVideoContent: + CopyFromAndAppendTypedDrawQuad<StreamVideoDrawQuad>(quad); + break; + case DrawQuad::Material::kSurfaceContent: + CopyFromAndAppendTypedDrawQuad<SurfaceDrawQuad>(quad); + break; + case DrawQuad::Material::kVideoHole: + CopyFromAndAppendTypedDrawQuad<VideoHoleDrawQuad>(quad); + break; + case DrawQuad::Material::kYuvVideoContent: + CopyFromAndAppendTypedDrawQuad<YUVVideoDrawQuad>(quad); + break; + // RenderPass quads need to use specific CopyFrom function. + case DrawQuad::Material::kAggregatedRenderPass: + case DrawQuad::Material::kRenderPass: + case DrawQuad::Material::kInvalid: + // TODO(danakj): Why is this a check instead of dcheck, and validate from + // IPC? + CHECK(false); // Invalid DrawQuad material. + break; + } + quad_list.back()->shared_quad_state = shared_quad_state_list.back(); + return quad_list.back(); +} + +std::unique_ptr<AggregatedRenderPass> AggregatedRenderPass::Copy( + AggregatedRenderPassId new_id) const { + auto copy_pass = std::make_unique<AggregatedRenderPass>( + shared_quad_state_list.size(), quad_list.size()); + copy_pass->SetAll(new_id, output_rect, damage_rect, transform_to_root_target, + filters, backdrop_filters, backdrop_filter_bounds, + content_color_usage, has_transparent_background, + cache_render_pass, has_damage_from_contributing_content, + generate_mipmap); + return copy_pass; +} + +std::unique_ptr<AggregatedRenderPass> AggregatedRenderPass::DeepCopy() const { + // Since we can't copy these, it's wrong to use DeepCopy in a situation where + // you may have copy_requests present. + DCHECK_EQ(copy_requests.size(), 0u); + + auto copy_pass = std::make_unique<AggregatedRenderPass>( + shared_quad_state_list.size(), quad_list.size()); + copy_pass->SetAll(id, output_rect, damage_rect, transform_to_root_target, + filters, backdrop_filters, backdrop_filter_bounds, + content_color_usage, has_transparent_background, + cache_render_pass, has_damage_from_contributing_content, + generate_mipmap); + + if (shared_quad_state_list.empty()) { + DCHECK(quad_list.empty()); + return copy_pass; + } + + SharedQuadStateList::ConstIterator sqs_iter = shared_quad_state_list.begin(); + SharedQuadState* copy_shared_quad_state = + copy_pass->CreateAndAppendSharedQuadState(); + *copy_shared_quad_state = **sqs_iter; + for (auto* quad : quad_list) { + while (quad->shared_quad_state != *sqs_iter) { + ++sqs_iter; + DCHECK(sqs_iter != shared_quad_state_list.end()); + copy_shared_quad_state = copy_pass->CreateAndAppendSharedQuadState(); + *copy_shared_quad_state = **sqs_iter; + } + DCHECK(quad->shared_quad_state == *sqs_iter); + + if (quad->material == DrawQuad::Material::kAggregatedRenderPass) { + const auto* pass_quad = AggregatedRenderPassDrawQuad::MaterialCast(quad); + copy_pass->CopyFromAndAppendRenderPassDrawQuad(pass_quad); + } else { + copy_pass->CopyFromAndAppendDrawQuad(quad); + } + } + return copy_pass; +} + +} // namespace viz
diff --git a/components/viz/common/quads/aggregated_render_pass.h b/components/viz/common/quads/aggregated_render_pass.h new file mode 100644 index 0000000..422b9fb --- /dev/null +++ b/components/viz/common/quads/aggregated_render_pass.h
@@ -0,0 +1,107 @@ +// Copyright 2020 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef COMPONENTS_VIZ_COMMON_QUADS_AGGREGATED_RENDER_PASS_H_ +#define COMPONENTS_VIZ_COMMON_QUADS_AGGREGATED_RENDER_PASS_H_ + +#include <stddef.h> + +#include <memory> +#include <utility> +#include <vector> + +#include "base/callback.h" +#include "base/hash/hash.h" +#include "base/macros.h" +#include "base/util/type_safety/id_type.h" +#include "cc/base/list_container.h" +#include "cc/paint/filter_operations.h" +#include "components/viz/common/quads/draw_quad.h" +#include "components/viz/common/quads/largest_draw_quad.h" +#include "components/viz/common/quads/quad_list.h" +#include "components/viz/common/quads/render_pass_internal.h" +#include "components/viz/common/viz_common_export.h" +#include "ui/gfx/display_color_spaces.h" +#include "ui/gfx/geometry/rect.h" +#include "ui/gfx/rrect_f.h" +#include "ui/gfx/transform.h" + +namespace viz { +class AggregatedRenderPass; +class RenderPassDrawQuad; +class AggregatedRenderPassDrawQuad; + +using AggregatedRenderPassId = util::IdTypeU64<AggregatedRenderPass>; + +// This class represents a render pass that is a result of aggregating render +// passes from all of the relevant surfaces. It is _not_ mojo-serializable since +// it is local to the viz process. It has a unique AggregatedRenderPassId across +// all of the AggregatedRenderPasses. +class VIZ_COMMON_EXPORT AggregatedRenderPass : public RenderPassInternal { + public: + ~AggregatedRenderPass(); + + AggregatedRenderPass(); + AggregatedRenderPass(size_t shared_quad_state_size, size_t draw_quad_size); + + void SetNew(AggregatedRenderPassId id, + const gfx::Rect& output_rect, + const gfx::Rect& damage_rect, + const gfx::Transform& transform_to_root_target); + + void SetAll(AggregatedRenderPassId id, + const gfx::Rect& output_rect, + const gfx::Rect& damage_rect, + const gfx::Transform& transform_to_root_target, + const cc::FilterOperations& filters, + const cc::FilterOperations& backdrop_filters, + const base::Optional<gfx::RRectF>& backdrop_filter_bounds, + gfx::ContentColorUsage content_color_usage, + bool has_transparent_background, + bool cache_render_pass, + bool has_damage_from_contributing_content, + bool generate_mipmap); + + AggregatedRenderPassDrawQuad* CopyFromAndAppendRenderPassDrawQuad( + const RenderPassDrawQuad* quad, + AggregatedRenderPassId render_pass_id); + AggregatedRenderPassDrawQuad* CopyFromAndAppendRenderPassDrawQuad( + const AggregatedRenderPassDrawQuad* quad); + DrawQuad* CopyFromAndAppendDrawQuad(const DrawQuad* quad); + + // A shallow copy of the render pass, which does not include its quads or copy + // requests. + std::unique_ptr<AggregatedRenderPass> Copy( + AggregatedRenderPassId new_id) const; + + // A deep copy of the render pass that includes quads. + std::unique_ptr<AggregatedRenderPass> DeepCopy() const; + + template <typename DrawQuadType> + DrawQuadType* CreateAndAppendDrawQuad() { + static_assert(!std::is_same<DrawQuadType, RenderPassDrawQuad>::value, + "cannot create RenderPassDrawQuad in AggregatedRenderPass"); + return quad_list.AllocateAndConstruct<DrawQuadType>(); + } + + // Uniquely identifies the render pass in the aggregated frame. + AggregatedRenderPassId id; + + private: + template <typename DrawQuadType> + DrawQuadType* CopyFromAndAppendTypedDrawQuad(const DrawQuad* quad) { + static_assert( + !std::is_same<DrawQuadType, RenderPassDrawQuad>::value, + "cannot copy RenderPassDrawQuad type into AggregatedRenderPass"); + return quad_list.AllocateAndCopyFrom(DrawQuadType::MaterialCast(quad)); + } + + DISALLOW_COPY_AND_ASSIGN(AggregatedRenderPass); +}; + +using AggregatedRenderPassList = + std::vector<std::unique_ptr<AggregatedRenderPass>>; + +} // namespace viz +#endif // COMPONENTS_VIZ_COMMON_QUADS_AGGREGATED_RENDER_PASS_H_
diff --git a/components/viz/common/quads/aggregated_render_pass_draw_quad.cc b/components/viz/common/quads/aggregated_render_pass_draw_quad.cc new file mode 100644 index 0000000..e0b1c68 --- /dev/null +++ b/components/viz/common/quads/aggregated_render_pass_draw_quad.cc
@@ -0,0 +1,91 @@ +// Copyright 2011 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "components/viz/common/quads/aggregated_render_pass_draw_quad.h" + +#include "base/trace_event/traced_value.h" +#include "base/values.h" +#include "cc/base/math_util.h" +#include "components/viz/common/traced_value.h" +#include "third_party/skia/include/core/SkImageFilter.h" + +namespace viz { + +AggregatedRenderPassDrawQuad::AggregatedRenderPassDrawQuad() = default; + +AggregatedRenderPassDrawQuad::AggregatedRenderPassDrawQuad( + const AggregatedRenderPassDrawQuad& other) = default; + +AggregatedRenderPassDrawQuad::~AggregatedRenderPassDrawQuad() = default; + +void AggregatedRenderPassDrawQuad::SetNew( + const SharedQuadState* shared_quad_state, + const gfx::Rect& rect, + const gfx::Rect& visible_rect, + AggregatedRenderPassId render_pass_id, + ResourceId mask_resource_id, + const gfx::RectF& mask_uv_rect, + const gfx::Size& mask_texture_size, + const gfx::Vector2dF& filters_scale, + const gfx::PointF& filters_origin, + const gfx::RectF& tex_coord_rect, + bool force_anti_aliasing_off, + float backdrop_filter_quality) { + DCHECK(render_pass_id); + + bool needs_blending = true; + bool can_use_backdrop_filter_cache = false; + SetAll(shared_quad_state, rect, visible_rect, needs_blending, render_pass_id, + mask_resource_id, mask_uv_rect, mask_texture_size, filters_scale, + filters_origin, tex_coord_rect, force_anti_aliasing_off, + backdrop_filter_quality, can_use_backdrop_filter_cache); +} + +void AggregatedRenderPassDrawQuad::SetAll( + const SharedQuadState* shared_quad_state, + const gfx::Rect& rect, + const gfx::Rect& visible_rect, + bool needs_blending, + AggregatedRenderPassId render_pass_id, + ResourceId mask_resource_id, + const gfx::RectF& mask_uv_rect, + const gfx::Size& mask_texture_size, + const gfx::Vector2dF& filters_scale, + const gfx::PointF& filters_origin, + const gfx::RectF& tex_coord_rect, + bool force_anti_aliasing_off, + float backdrop_filter_quality, + bool can_use_backdrop_filter_cache) { + DCHECK(render_pass_id); + + DrawQuad::SetAll(shared_quad_state, DrawQuad::Material::kAggregatedRenderPass, + rect, visible_rect, needs_blending); + this->render_pass_id = render_pass_id; + resources.ids[kMaskResourceIdIndex] = mask_resource_id; + resources.count = mask_resource_id ? 1 : 0; + this->mask_uv_rect = mask_uv_rect; + this->mask_texture_size = mask_texture_size; + this->filters_scale = filters_scale; + this->filters_origin = filters_origin; + this->tex_coord_rect = tex_coord_rect; + this->force_anti_aliasing_off = force_anti_aliasing_off; + this->backdrop_filter_quality = backdrop_filter_quality; + this->can_use_backdrop_filter_cache = can_use_backdrop_filter_cache; +} + +const AggregatedRenderPassDrawQuad* AggregatedRenderPassDrawQuad::MaterialCast( + const DrawQuad* quad) { + DCHECK_EQ(quad->material, DrawQuad::Material::kAggregatedRenderPass); + return static_cast<const AggregatedRenderPassDrawQuad*>(quad); +} + +void AggregatedRenderPassDrawQuad::ExtendValue( + base::trace_event::TracedValue* value) const { + TracedValue::SetIDRef( + reinterpret_cast<void*>(static_cast<uint64_t>(render_pass_id)), value, + "render_pass_id"); + RenderPassDrawQuadInternal::ExtendValue(value); +} + +} // namespace viz
diff --git a/components/viz/common/quads/aggregated_render_pass_draw_quad.h b/components/viz/common/quads/aggregated_render_pass_draw_quad.h new file mode 100644 index 0000000..8c291dc0 --- /dev/null +++ b/components/viz/common/quads/aggregated_render_pass_draw_quad.h
@@ -0,0 +1,68 @@ +// Copyright 2011 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef COMPONENTS_VIZ_COMMON_QUADS_AGGREGATED_RENDER_PASS_DRAW_QUAD_H_ +#define COMPONENTS_VIZ_COMMON_QUADS_AGGREGATED_RENDER_PASS_DRAW_QUAD_H_ + +#include <stddef.h> + +#include <memory> + +#include "cc/paint/filter_operations.h" +#include "components/viz/common/quads/aggregated_render_pass.h" +#include "components/viz/common/quads/draw_quad.h" +#include "components/viz/common/quads/render_pass_draw_quad_internal.h" +#include "components/viz/common/viz_common_export.h" + +#include "ui/gfx/geometry/point_f.h" +#include "ui/gfx/geometry/rect_f.h" + +namespace viz { + +class VIZ_COMMON_EXPORT AggregatedRenderPassDrawQuad + : public RenderPassDrawQuadInternal { + public: + AggregatedRenderPassDrawQuad(); + AggregatedRenderPassDrawQuad(const AggregatedRenderPassDrawQuad& other); + ~AggregatedRenderPassDrawQuad() override; + + void SetNew(const SharedQuadState* shared_quad_state, + const gfx::Rect& rect, + const gfx::Rect& visible_rect, + AggregatedRenderPassId render_pass_id, + ResourceId mask_resource_id, + const gfx::RectF& mask_uv_rect, + const gfx::Size& mask_texture_size, + const gfx::Vector2dF& filters_scale, + const gfx::PointF& filters_origin, + const gfx::RectF& tex_coord_rect, + bool force_anti_aliasing_off, + float backdrop_filter_quality); + + void SetAll(const SharedQuadState* shared_quad_state, + const gfx::Rect& rect, + const gfx::Rect& visible_rect, + bool needs_blending, + AggregatedRenderPassId render_pass_id, + ResourceId mask_resource_id, + const gfx::RectF& mask_uv_rect, + const gfx::Size& mask_texture_size, + const gfx::Vector2dF& filters_scale, + const gfx::PointF& filters_origin, + const gfx::RectF& tex_coord_rect, + bool force_anti_aliasing_off, + float backdrop_filter_quality, + bool can_use_backdrop_filter_cache); + + AggregatedRenderPassId render_pass_id; + + static const AggregatedRenderPassDrawQuad* MaterialCast(const DrawQuad*); + + private: + void ExtendValue(base::trace_event::TracedValue* value) const override; +}; + +} // namespace viz + +#endif // COMPONENTS_VIZ_COMMON_QUADS_AGGREGATED_RENDER_PASS_DRAW_QUAD_H_
diff --git a/components/viz/common/quads/draw_quad.h b/components/viz/common/quads/draw_quad.h index 242a550..653b9e9 100644 --- a/components/viz/common/quads/draw_quad.h +++ b/components/viz/common/quads/draw_quad.h
@@ -37,7 +37,10 @@ kInvalid, kDebugBorder, kPictureContent, + // This is the compositor, pre-aggregation, draw quad. kRenderPass, + // This is the viz, post-aggregation, draw quad. + kAggregatedRenderPass, kSolidColor, kStreamVideoContent, kSurfaceContent,
diff --git a/components/viz/common/quads/draw_quad_unittest.cc b/components/viz/common/quads/draw_quad_unittest.cc index c7fed3c..cdca678 100644 --- a/components/viz/common/quads/draw_quad_unittest.cc +++ b/components/viz/common/quads/draw_quad_unittest.cc
@@ -17,6 +17,8 @@ #include "cc/paint/filter_operations.h" #include "cc/test/fake_raster_source.h" #include "cc/test/geometry_test_utils.h" +#include "components/viz/common/quads/aggregated_render_pass.h" +#include "components/viz/common/quads/aggregated_render_pass_draw_quad.h" #include "components/viz/common/quads/debug_border_draw_quad.h" #include "components/viz/common/quads/largest_draw_quad.h" #include "components/viz/common/quads/picture_draw_quad.h" @@ -685,6 +687,9 @@ for (int i = 0; i <= static_cast<int>(DrawQuad::Material::kMaxValue); ++i) { switch (static_cast<DrawQuad::Material>(i)) { + case DrawQuad::Material::kAggregatedRenderPass: + largest = std::max(largest, sizeof(AggregatedRenderPassDrawQuad)); + break; case DrawQuad::Material::kDebugBorder: largest = std::max(largest, sizeof(DebugBorderDrawQuad)); break; @@ -729,6 +734,9 @@ LOG(ERROR) << "kLargestDrawQuad " << LargestDrawQuadSize(); for (int i = 0; i <= static_cast<int>(DrawQuad::Material::kMaxValue); ++i) { switch (static_cast<DrawQuad::Material>(i)) { + case DrawQuad::Material::kAggregatedRenderPass: + LOG(ERROR) << "AggregatedRenderPass " << sizeof(AggregatedRenderPass); + break; case DrawQuad::Material::kDebugBorder: LOG(ERROR) << "DebugBorderDrawQuad " << sizeof(DebugBorderDrawQuad); break;
diff --git a/components/viz/common/quads/largest_draw_quad.cc b/components/viz/common/quads/largest_draw_quad.cc index 1779a43..b6a1dc2 100644 --- a/components/viz/common/quads/largest_draw_quad.cc +++ b/components/viz/common/quads/largest_draw_quad.cc
@@ -8,6 +8,7 @@ #include <algorithm> +#include "components/viz/common/quads/aggregated_render_pass_draw_quad.h" #include "components/viz/common/quads/debug_border_draw_quad.h" #include "components/viz/common/quads/picture_draw_quad.h" #include "components/viz/common/quads/render_pass_draw_quad.h" @@ -33,15 +34,17 @@ static constexpr size_t value = 0; }; -constexpr size_t kLargestDrawQuadSize = MaxSize<viz::DebugBorderDrawQuad, - viz::PictureDrawQuad, - viz::RenderPassDrawQuad, - viz::SolidColorDrawQuad, - viz::StreamVideoDrawQuad, - viz::SurfaceDrawQuad, - viz::TextureDrawQuad, - viz::TileDrawQuad, - viz::YUVVideoDrawQuad>::value; +constexpr size_t kLargestDrawQuadSize = + MaxSize<viz::AggregatedRenderPassDrawQuad, + viz::DebugBorderDrawQuad, + viz::PictureDrawQuad, + viz::RenderPassDrawQuad, + viz::SolidColorDrawQuad, + viz::StreamVideoDrawQuad, + viz::SurfaceDrawQuad, + viz::TextureDrawQuad, + viz::TileDrawQuad, + viz::YUVVideoDrawQuad>::value; template <typename...> struct MaxAlign {}; @@ -57,7 +60,8 @@ }; constexpr size_t kLargestDrawQuadAlignment = - MaxAlign<viz::DebugBorderDrawQuad, + MaxAlign<viz::AggregatedRenderPassDrawQuad, + viz::DebugBorderDrawQuad, viz::PictureDrawQuad, viz::RenderPassDrawQuad, viz::SolidColorDrawQuad,
diff --git a/components/viz/common/quads/quad_list.cc b/components/viz/common/quads/quad_list.cc index d4c72dc..87ca312 100644 --- a/components/viz/common/quads/quad_list.cc +++ b/components/viz/common/quads/quad_list.cc
@@ -97,6 +97,7 @@ copy); } // RenderPass quads should not be copied. + case DrawQuad::Material::kAggregatedRenderPass: case DrawQuad::Material::kRenderPass: case DrawQuad::Material::kInvalid: NOTREACHED(); // Invalid DrawQuad material.
diff --git a/components/viz/common/quads/render_pass.cc b/components/viz/common/quads/render_pass.cc index 3b7b6b7..1ecc60a 100644 --- a/components/viz/common/quads/render_pass.cc +++ b/components/viz/common/quads/render_pass.cc
@@ -15,7 +15,6 @@ #include "base/trace_event/traced_value.h" #include "base/values.h" #include "cc/base/math_util.h" -#include "components/viz/common/frame_sinks/copy_output_request.h" #include "components/viz/common/quads/debug_border_draw_quad.h" #include "components/viz/common/quads/draw_quad.h" #include "components/viz/common/quads/largest_draw_quad.h" @@ -31,29 +30,8 @@ #include "components/viz/common/quads/yuv_video_draw_quad.h" #include "components/viz/common/traced_value.h" -namespace { -const size_t kDefaultNumSharedQuadStatesToReserve = 32; -const size_t kDefaultNumQuadsToReserve = 128; -} // namespace - namespace viz { -RenderPassInternal::RenderPassInternal() - : RenderPassInternal(kDefaultNumSharedQuadStatesToReserve, - kDefaultNumQuadsToReserve) {} -// Each layer usually produces one shared quad state, so the number of layers -// is a good hint for what to reserve here. -RenderPassInternal::RenderPassInternal(size_t num_layers) - : RenderPassInternal(num_layers, kDefaultNumQuadsToReserve) {} -RenderPassInternal::RenderPassInternal(size_t shared_quad_state_list_size, - size_t quad_list_size) - : quad_list(quad_list_size), - shared_quad_state_list(alignof(SharedQuadState), - sizeof(SharedQuadState), - shared_quad_state_list_size) {} - -RenderPassInternal::~RenderPassInternal() = default; - std::unique_ptr<RenderPass> RenderPass::Create() { return base::WrapUnique(new RenderPass()); } @@ -81,67 +59,6 @@ reinterpret_cast<void*>(static_cast<uint64_t>(id))); } -std::unique_ptr<RenderPass> RenderPass::Copy(RenderPassId new_id) const { - std::unique_ptr<RenderPass> copy_pass( - Create(shared_quad_state_list.size(), quad_list.size())); - copy_pass->SetAll(new_id, output_rect, damage_rect, transform_to_root_target, - filters, backdrop_filters, backdrop_filter_bounds, - content_color_usage, has_transparent_background, - cache_render_pass, has_damage_from_contributing_content, - generate_mipmap); - return copy_pass; -} - -std::unique_ptr<RenderPass> RenderPass::DeepCopy() const { - // Since we can't copy these, it's wrong to use DeepCopy in a situation where - // you may have copy_requests present. - DCHECK_EQ(copy_requests.size(), 0u); - - std::unique_ptr<RenderPass> copy_pass( - Create(shared_quad_state_list.size(), quad_list.size())); - copy_pass->SetAll(id, output_rect, damage_rect, transform_to_root_target, - filters, backdrop_filters, backdrop_filter_bounds, - content_color_usage, has_transparent_background, - cache_render_pass, has_damage_from_contributing_content, - generate_mipmap); - - if (shared_quad_state_list.empty()) { - DCHECK(quad_list.empty()); - return copy_pass; - } - - SharedQuadStateList::ConstIterator sqs_iter = shared_quad_state_list.begin(); - SharedQuadState* copy_shared_quad_state = - copy_pass->CreateAndAppendSharedQuadState(); - *copy_shared_quad_state = **sqs_iter; - for (auto* quad : quad_list) { - while (quad->shared_quad_state != *sqs_iter) { - ++sqs_iter; - DCHECK(sqs_iter != shared_quad_state_list.end()); - copy_shared_quad_state = copy_pass->CreateAndAppendSharedQuadState(); - *copy_shared_quad_state = **sqs_iter; - } - DCHECK(quad->shared_quad_state == *sqs_iter); - - if (quad->material == DrawQuad::Material::kRenderPass) { - const RenderPassDrawQuad* pass_quad = - RenderPassDrawQuad::MaterialCast(quad); - copy_pass->CopyFromAndAppendRenderPassDrawQuad(pass_quad, - pass_quad->render_pass_id); - } else { - copy_pass->CopyFromAndAppendDrawQuad(quad); - } - } - return copy_pass; -} - -// static -void RenderPass::CopyAll(const std::vector<std::unique_ptr<RenderPass>>& in, - std::vector<std::unique_ptr<RenderPass>>* out) { - for (const auto& source : in) - out->push_back(source->DeepCopy()); -} - void RenderPass::SetNew(RenderPassId id, const gfx::Rect& output_rect, const gfx::Rect& damage_rect, @@ -239,15 +156,11 @@ reinterpret_cast<void*>(static_cast<uint64_t>(id))); } -SharedQuadState* RenderPass::CreateAndAppendSharedQuadState() { - return shared_quad_state_list.AllocateAndConstruct<SharedQuadState>(); -} - RenderPassDrawQuad* RenderPass::CopyFromAndAppendRenderPassDrawQuad( const RenderPassDrawQuad* quad, RenderPassId render_pass_id) { DCHECK(!shared_quad_state_list.empty()); - auto* copy_quad = CopyFromAndAppendTypedDrawQuad<RenderPassDrawQuad>(quad); + auto* copy_quad = quad_list.AllocateAndCopyFrom(quad); copy_quad->shared_quad_state = shared_quad_state_list.back(); copy_quad->render_pass_id = render_pass_id; return copy_quad; @@ -257,33 +170,34 @@ DCHECK(!shared_quad_state_list.empty()); switch (quad->material) { case DrawQuad::Material::kDebugBorder: - CopyFromAndAppendTypedDrawQuad<DebugBorderDrawQuad>(quad); + quad_list.AllocateAndCopyFrom(DebugBorderDrawQuad::MaterialCast(quad)); break; case DrawQuad::Material::kPictureContent: - CopyFromAndAppendTypedDrawQuad<PictureDrawQuad>(quad); + quad_list.AllocateAndCopyFrom(PictureDrawQuad::MaterialCast(quad)); break; case DrawQuad::Material::kTextureContent: - CopyFromAndAppendTypedDrawQuad<TextureDrawQuad>(quad); + quad_list.AllocateAndCopyFrom(TextureDrawQuad::MaterialCast(quad)); break; case DrawQuad::Material::kSolidColor: - CopyFromAndAppendTypedDrawQuad<SolidColorDrawQuad>(quad); + quad_list.AllocateAndCopyFrom(SolidColorDrawQuad::MaterialCast(quad)); break; case DrawQuad::Material::kTiledContent: - CopyFromAndAppendTypedDrawQuad<TileDrawQuad>(quad); + quad_list.AllocateAndCopyFrom(TileDrawQuad::MaterialCast(quad)); break; case DrawQuad::Material::kStreamVideoContent: - CopyFromAndAppendTypedDrawQuad<StreamVideoDrawQuad>(quad); + quad_list.AllocateAndCopyFrom(StreamVideoDrawQuad::MaterialCast(quad)); break; case DrawQuad::Material::kSurfaceContent: - CopyFromAndAppendTypedDrawQuad<SurfaceDrawQuad>(quad); + quad_list.AllocateAndCopyFrom(SurfaceDrawQuad::MaterialCast(quad)); break; case DrawQuad::Material::kVideoHole: - CopyFromAndAppendTypedDrawQuad<VideoHoleDrawQuad>(quad); + quad_list.AllocateAndCopyFrom(VideoHoleDrawQuad::MaterialCast(quad)); break; case DrawQuad::Material::kYuvVideoContent: - CopyFromAndAppendTypedDrawQuad<YUVVideoDrawQuad>(quad); + quad_list.AllocateAndCopyFrom(YUVVideoDrawQuad::MaterialCast(quad)); break; // RenderPass quads need to use specific CopyFrom function. + case DrawQuad::Material::kAggregatedRenderPass: case DrawQuad::Material::kRenderPass: case DrawQuad::Material::kInvalid: // TODO(danakj): Why is this a check instead of dcheck, and validate from @@ -295,4 +209,46 @@ return quad_list.back(); } +std::unique_ptr<RenderPass> RenderPass::DeepCopy() const { + // Since we can't copy these, it's wrong to use DeepCopy in a situation where + // you may have copy_requests present. + DCHECK_EQ(copy_requests.size(), 0u); + + auto copy_pass = + RenderPass::Create(shared_quad_state_list.size(), quad_list.size()); + copy_pass->SetAll(id, output_rect, damage_rect, transform_to_root_target, + filters, backdrop_filters, backdrop_filter_bounds, + content_color_usage, has_transparent_background, + cache_render_pass, has_damage_from_contributing_content, + generate_mipmap); + + if (shared_quad_state_list.empty()) { + DCHECK(quad_list.empty()); + return copy_pass; + } + + SharedQuadStateList::ConstIterator sqs_iter = shared_quad_state_list.begin(); + SharedQuadState* copy_shared_quad_state = + copy_pass->CreateAndAppendSharedQuadState(); + *copy_shared_quad_state = **sqs_iter; + for (auto* quad : quad_list) { + while (quad->shared_quad_state != *sqs_iter) { + ++sqs_iter; + DCHECK(sqs_iter != shared_quad_state_list.end()); + copy_shared_quad_state = copy_pass->CreateAndAppendSharedQuadState(); + *copy_shared_quad_state = **sqs_iter; + } + DCHECK(quad->shared_quad_state == *sqs_iter); + + if (quad->material == DrawQuad::Material::kRenderPass) { + const auto* pass_quad = RenderPassDrawQuad::MaterialCast(quad); + copy_pass->CopyFromAndAppendRenderPassDrawQuad(pass_quad, + pass_quad->render_pass_id); + } else { + copy_pass->CopyFromAndAppendDrawQuad(quad); + } + } + return copy_pass; +} + } // namespace viz
diff --git a/components/viz/common/quads/render_pass.h b/components/viz/common/quads/render_pass.h index df217e2..a6854f8b 100644 --- a/components/viz/common/quads/render_pass.h +++ b/components/viz/common/quads/render_pass.h
@@ -20,6 +20,7 @@ #include "components/viz/common/quads/draw_quad.h" #include "components/viz/common/quads/largest_draw_quad.h" #include "components/viz/common/quads/quad_list.h" +#include "components/viz/common/quads/render_pass_internal.h" #include "components/viz/common/viz_common_export.h" #include "ui/gfx/display_color_spaces.h" #include "ui/gfx/geometry/rect.h" @@ -33,72 +34,18 @@ } // namespace base namespace viz { -class CopyOutputRequest; +class AggregatedRenderPass; +class AggregatedRenderPassDrawQuad; class DrawQuad; -class RenderPassDrawQuad; -class SharedQuadState; class RenderPass; +class RenderPassDrawQuad; -using SharedQuadStateList = cc::ListContainer<SharedQuadState>; using RenderPassId = util::IdTypeU64<RenderPass>; -class VIZ_COMMON_EXPORT RenderPassInternal { - public: - // These are in the space of the render pass' physical pixels. - gfx::Rect output_rect; - gfx::Rect damage_rect; - - // Transforms from the origin of the |output_rect| to the origin of the root - // render pass' |output_rect|. - gfx::Transform transform_to_root_target; - - // Post-processing filters, applied to the pixels in the render pass' texture. - cc::FilterOperations filters; - - // Post-processing filters, applied to the pixels showing through the - // backdrop of the render pass, from behind it. - cc::FilterOperations backdrop_filters; - - // Clipping bounds for backdrop filter. - base::Optional<gfx::RRectF> backdrop_filter_bounds; - - // The type of color content present in this RenderPass. - gfx::ContentColorUsage content_color_usage = gfx::ContentColorUsage::kSRGB; - - // If false, the pixels in the render pass' texture are all opaque. - bool has_transparent_background = true; - - // If true we might reuse the texture if there is no damage. - bool cache_render_pass = false; - // Indicates whether there is accumulated damage from contributing render - // surface or layer or surface quad. Not including property changes on itself. - bool has_damage_from_contributing_content = false; - - // Generate mipmap for trilinear filtering, applied to render pass' texture. - bool generate_mipmap = false; - - // Indicates current RenderPass is a color conversion pass. - bool is_color_conversion_pass = false; - - // If non-empty, the renderer should produce a copy of the render pass' - // contents as a bitmap, and give a copy of the bitmap to each callback in - // this list. - std::vector<std::unique_ptr<CopyOutputRequest>> copy_requests; - - QuadList quad_list; - SharedQuadStateList shared_quad_state_list; - - protected: - RenderPassInternal(); - explicit RenderPassInternal(size_t num_layers); - RenderPassInternal(size_t shared_quad_state_list_size, size_t quad_list_size); - - ~RenderPassInternal(); - - private: - DISALLOW_COPY_AND_ASSIGN(RenderPassInternal); -}; - +// This class represents a render pass that is submitted from the UI or renderer +// compositor to viz. It is mojo-serializable and typically has a unique +// RenderPassId within its surface id. +// TODO(vmpstr): Rename this to CompositorRenderPass. class VIZ_COMMON_EXPORT RenderPass : public RenderPassInternal { public: ~RenderPass(); @@ -108,17 +55,6 @@ static std::unique_ptr<RenderPass> Create(size_t shared_quad_state_list_size, size_t quad_list_size); - // A shallow copy of the render pass, which does not include its quads or copy - // requests. - std::unique_ptr<RenderPass> Copy(RenderPassId new_id) const; - - // A deep copy of the render pass that includes quads. - std::unique_ptr<RenderPass> DeepCopy() const; - - // A deep copy of the render passes in the list including the quads. - static void CopyAll(const std::vector<std::unique_ptr<RenderPass>>& in, - std::vector<std::unique_ptr<RenderPass>>* out); - void SetNew(RenderPassId id, const gfx::Rect& output_rect, const gfx::Rect& damage_rect, @@ -139,20 +75,27 @@ void AsValueInto(base::trace_event::TracedValue* dict) const; - SharedQuadState* CreateAndAppendSharedQuadState(); - template <typename DrawQuadType> DrawQuadType* CreateAndAppendDrawQuad() { + static_assert( + !std::is_same<DrawQuadType, AggregatedRenderPassDrawQuad>::value, + "cannot create RenderPassDrawQuad in AggregatedRenderPass"); return quad_list.AllocateAndConstruct<DrawQuadType>(); } + // Uniquely identifies the render pass in the compositor's current frame. + RenderPassId id; + + // For testing functions. + // TODO(vmpstr): See if we can clean these up by moving the tests to use + // AggregatedRenderPasses where appropriate. RenderPassDrawQuad* CopyFromAndAppendRenderPassDrawQuad( const RenderPassDrawQuad* quad, RenderPassId render_pass_id); DrawQuad* CopyFromAndAppendDrawQuad(const DrawQuad* quad); - // Uniquely identifies the render pass in the compositor's current frame. - RenderPassId id; + // A deep copy of the render pass that includes quads. + std::unique_ptr<RenderPass> DeepCopy() const; protected: // This is essentially "using RenderPassInternal::RenderPassInternal", but @@ -163,11 +106,6 @@ RenderPass(size_t shared_quad_state_list_size, size_t quad_list_size); private: - template <typename DrawQuadType> - DrawQuadType* CopyFromAndAppendTypedDrawQuad(const DrawQuad* quad) { - return quad_list.AllocateAndCopyFrom(DrawQuadType::MaterialCast(quad)); - } - DISALLOW_COPY_AND_ASSIGN(RenderPass); };
diff --git a/components/viz/common/quads/render_pass_draw_quad.cc b/components/viz/common/quads/render_pass_draw_quad.cc index a6747d8..64843c8 100644 --- a/components/viz/common/quads/render_pass_draw_quad.cc +++ b/components/viz/common/quads/render_pass_draw_quad.cc
@@ -83,14 +83,7 @@ TracedValue::SetIDRef( reinterpret_cast<void*>(static_cast<uint64_t>(render_pass_id)), value, "render_pass_id"); - value->SetInteger("mask_resource_id", resources.ids[kMaskResourceIdIndex]); - cc::MathUtil::AddToTracedValue("mask_texture_size", mask_texture_size, value); - cc::MathUtil::AddToTracedValue("mask_uv_rect", mask_uv_rect, value); - cc::MathUtil::AddToTracedValue("tex_coord_rect", tex_coord_rect, value); - value->SetBoolean("force_anti_aliasing_off", force_anti_aliasing_off); - value->SetDouble("backdrop_filter_quality", backdrop_filter_quality); - value->SetBoolean("can_use_backdrop_filter_cache", - can_use_backdrop_filter_cache); + RenderPassDrawQuadInternal::ExtendValue(value); } } // namespace viz
diff --git a/components/viz/common/quads/render_pass_draw_quad.h b/components/viz/common/quads/render_pass_draw_quad.h index e7e0e003..fba82f6 100644 --- a/components/viz/common/quads/render_pass_draw_quad.h +++ b/components/viz/common/quads/render_pass_draw_quad.h
@@ -12,6 +12,7 @@ #include "cc/paint/filter_operations.h" #include "components/viz/common/quads/draw_quad.h" #include "components/viz/common/quads/render_pass.h" +#include "components/viz/common/quads/render_pass_draw_quad_internal.h" #include "components/viz/common/viz_common_export.h" #include "ui/gfx/geometry/point_f.h" @@ -19,10 +20,8 @@ namespace viz { -class VIZ_COMMON_EXPORT RenderPassDrawQuad : public DrawQuad { +class VIZ_COMMON_EXPORT RenderPassDrawQuad : public RenderPassDrawQuadInternal { public: - static const size_t kMaskResourceIdIndex = 0; - RenderPassDrawQuad(); RenderPassDrawQuad(const RenderPassDrawQuad& other); ~RenderPassDrawQuad() override; @@ -56,33 +55,6 @@ bool can_use_backdrop_filter_cache); RenderPassId render_pass_id; - gfx::RectF mask_uv_rect; - gfx::Size mask_texture_size; - - // The scale from layer space of the root layer of the render pass to - // the render pass physical pixels. This scale is applied to the filter - // parameters for pixel-moving filters. This scale should include - // content-to-target-space scale, and device pixel ratio. - gfx::Vector2dF filters_scale; - - // The origin for post-processing filters which will be used to offset - // crop rects, lights, etc. - gfx::PointF filters_origin; - - gfx::RectF tex_coord_rect; - - float backdrop_filter_quality; - - bool force_anti_aliasing_off; - - // If the quad has backdrop filters, this flag indicates if the cached - // backdrop filtered result can be used instead of having to recompute the - // filter operation. - mutable bool can_use_backdrop_filter_cache; - - ResourceId mask_resource_id() const { - return resources.ids[kMaskResourceIdIndex]; - } static const RenderPassDrawQuad* MaterialCast(const DrawQuad*);
diff --git a/components/viz/common/quads/render_pass_draw_quad_internal.cc b/components/viz/common/quads/render_pass_draw_quad_internal.cc new file mode 100644 index 0000000..abb1b42 --- /dev/null +++ b/components/viz/common/quads/render_pass_draw_quad_internal.cc
@@ -0,0 +1,34 @@ +// Copyright 2011 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "components/viz/common/quads/render_pass_draw_quad_internal.h" + +#include "base/trace_event/traced_value.h" +#include "base/values.h" +#include "cc/base/math_util.h" +#include "components/viz/common/traced_value.h" +#include "third_party/skia/include/core/SkImageFilter.h" + +namespace viz { + +RenderPassDrawQuadInternal::RenderPassDrawQuadInternal() = default; + +RenderPassDrawQuadInternal::RenderPassDrawQuadInternal( + const RenderPassDrawQuadInternal& other) = default; + +RenderPassDrawQuadInternal::~RenderPassDrawQuadInternal() = default; + +void RenderPassDrawQuadInternal::ExtendValue( + base::trace_event::TracedValue* value) const { + value->SetInteger("mask_resource_id", resources.ids[kMaskResourceIdIndex]); + cc::MathUtil::AddToTracedValue("mask_texture_size", mask_texture_size, value); + cc::MathUtil::AddToTracedValue("mask_uv_rect", mask_uv_rect, value); + cc::MathUtil::AddToTracedValue("tex_coord_rect", tex_coord_rect, value); + value->SetBoolean("force_anti_aliasing_off", force_anti_aliasing_off); + value->SetDouble("backdrop_filter_quality", backdrop_filter_quality); + value->SetBoolean("can_use_backdrop_filter_cache", + can_use_backdrop_filter_cache); +} + +} // namespace viz
diff --git a/components/viz/common/quads/render_pass_draw_quad_internal.h b/components/viz/common/quads/render_pass_draw_quad_internal.h new file mode 100644 index 0000000..b4fa6d6b --- /dev/null +++ b/components/viz/common/quads/render_pass_draw_quad_internal.h
@@ -0,0 +1,63 @@ +// Copyright 2020 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef COMPONENTS_VIZ_COMMON_QUADS_RENDER_PASS_DRAW_QUAD_INTERNAL_H_ +#define COMPONENTS_VIZ_COMMON_QUADS_RENDER_PASS_DRAW_QUAD_INTERNAL_H_ + +#include <stddef.h> + +#include <memory> + +#include "cc/paint/filter_operations.h" +#include "components/viz/common/quads/draw_quad.h" +#include "components/viz/common/viz_common_export.h" + +#include "ui/gfx/geometry/point_f.h" +#include "ui/gfx/geometry/rect_f.h" + +namespace viz { + +class VIZ_COMMON_EXPORT RenderPassDrawQuadInternal : public DrawQuad { + public: + static const size_t kMaskResourceIdIndex = 0; + + gfx::RectF mask_uv_rect; + gfx::Size mask_texture_size; + + // The scale from layer space of the root layer of the render pass to + // the render pass physical pixels. This scale is applied to the filter + // parameters for pixel-moving filters. This scale should include + // content-to-target-space scale, and device pixel ratio. + gfx::Vector2dF filters_scale; + + // The origin for post-processing filters which will be used to offset + // crop rects, lights, etc. + gfx::PointF filters_origin; + + gfx::RectF tex_coord_rect; + + float backdrop_filter_quality; + + bool force_anti_aliasing_off; + + // If the quad has backdrop filters, this flag indicates if the cached + // backdrop filtered result can be used instead of having to recompute the + // filter operation. + mutable bool can_use_backdrop_filter_cache; + + ResourceId mask_resource_id() const { + return resources.ids[kMaskResourceIdIndex]; + } + + protected: + RenderPassDrawQuadInternal(); + RenderPassDrawQuadInternal(const RenderPassDrawQuadInternal& other); + ~RenderPassDrawQuadInternal() override; + + void ExtendValue(base::trace_event::TracedValue* value) const override; +}; + +} // namespace viz + +#endif // COMPONENTS_VIZ_COMMON_QUADS_RENDER_PASS_DRAW_QUAD_INTERNAL_H_
diff --git a/components/viz/common/quads/render_pass_internal.cc b/components/viz/common/quads/render_pass_internal.cc new file mode 100644 index 0000000..07f6612 --- /dev/null +++ b/components/viz/common/quads/render_pass_internal.cc
@@ -0,0 +1,37 @@ +// Copyright 2020 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "components/viz/common/quads/render_pass_internal.h" + +#include <stddef.h> + +#include "components/viz/common/frame_sinks/copy_output_request.h" + +namespace viz { +namespace { +const size_t kDefaultNumSharedQuadStatesToReserve = 32; +const size_t kDefaultNumQuadsToReserve = 128; +} // namespace + +RenderPassInternal::RenderPassInternal() + : RenderPassInternal(kDefaultNumSharedQuadStatesToReserve, + kDefaultNumQuadsToReserve) {} +// Each layer usually produces one shared quad state, so the number of layers +// is a good hint for what to reserve here. +RenderPassInternal::RenderPassInternal(size_t num_layers) + : RenderPassInternal(num_layers, kDefaultNumQuadsToReserve) {} +RenderPassInternal::RenderPassInternal(size_t shared_quad_state_list_size, + size_t quad_list_size) + : quad_list(quad_list_size), + shared_quad_state_list(alignof(SharedQuadState), + sizeof(SharedQuadState), + shared_quad_state_list_size) {} + +RenderPassInternal::~RenderPassInternal() = default; + +SharedQuadState* RenderPassInternal::CreateAndAppendSharedQuadState() { + return shared_quad_state_list.AllocateAndConstruct<SharedQuadState>(); +} + +} // namespace viz
diff --git a/components/viz/common/quads/render_pass_internal.h b/components/viz/common/quads/render_pass_internal.h new file mode 100644 index 0000000..64544c0 --- /dev/null +++ b/components/viz/common/quads/render_pass_internal.h
@@ -0,0 +1,99 @@ +// Copyright 2020 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef COMPONENTS_VIZ_COMMON_QUADS_RENDER_PASS_INTERNAL_H_ +#define COMPONENTS_VIZ_COMMON_QUADS_RENDER_PASS_INTERNAL_H_ + +#include <stddef.h> + +#include <memory> +#include <vector> + +#include "base/optional.h" +#include "cc/paint/filter_operations.h" +#include "components/viz/common/quads/quad_list.h" +#include "components/viz/common/viz_common_export.h" +#include "ui/gfx/display_color_spaces.h" +#include "ui/gfx/geometry/rect.h" +#include "ui/gfx/rrect_f.h" +#include "ui/gfx/transform.h" + +namespace viz { +class SharedQuadState; +class CopyOutputRequest; + +using SharedQuadStateList = cc::ListContainer<SharedQuadState>; + +// This class represents common data that is shared between the compositor and +// aggregated render passes. +class VIZ_COMMON_EXPORT RenderPassInternal { + public: + SharedQuadState* CreateAndAppendSharedQuadState(); + + // These are in the space of the render pass' physical pixels. + gfx::Rect output_rect; + gfx::Rect damage_rect; + + // Transforms from the origin of the |output_rect| to the origin of the root + // render pass' |output_rect|. + gfx::Transform transform_to_root_target; + + // Post-processing filters, applied to the pixels in the render pass' texture. + cc::FilterOperations filters; + + // Post-processing filters, applied to the pixels showing through the + // backdrop of the render pass, from behind it. + cc::FilterOperations backdrop_filters; + + // Clipping bounds for backdrop filter. + base::Optional<gfx::RRectF> backdrop_filter_bounds; + + // The type of color content present in this RenderPass. + gfx::ContentColorUsage content_color_usage = gfx::ContentColorUsage::kSRGB; + + // If false, the pixels in the render pass' texture are all opaque. + bool has_transparent_background = true; + + // If true we might reuse the texture if there is no damage. + bool cache_render_pass = false; + // Indicates whether there is accumulated damage from contributing render + // surface or layer or surface quad. Not including property changes on itself. + bool has_damage_from_contributing_content = false; + + // Generate mipmap for trilinear filtering, applied to render pass' texture. + bool generate_mipmap = false; + + // Indicates current RenderPass is a color conversion pass. + bool is_color_conversion_pass = false; + + // If non-empty, the renderer should produce a copy of the render pass' + // contents as a bitmap, and give a copy of the bitmap to each callback in + // this list. + std::vector<std::unique_ptr<CopyOutputRequest>> copy_requests; + + QuadList quad_list; + SharedQuadStateList shared_quad_state_list; + + template <typename RenderPassType> + static void CopyAllForTest( + const std::vector<std::unique_ptr<RenderPassType>>& in, + std::vector<std::unique_ptr<RenderPassType>>* out) { + for (const auto& source : in) + out->push_back(source->DeepCopy()); + } + + protected: + RenderPassInternal(); + explicit RenderPassInternal(size_t num_layers); + RenderPassInternal(size_t shared_quad_state_list_size, size_t quad_list_size); + + ~RenderPassInternal(); + + private: + DISALLOW_COPY_AND_ASSIGN(RenderPassInternal); +}; + +} // namespace viz + +#endif // COMPONENTS_VIZ_COMMON_QUADS_RENDER_PASS_INTERNAL_H_
diff --git a/components/viz/common/quads/render_pass_unittest.cc b/components/viz/common/quads/render_pass_unittest.cc index 757b5ae..66528eb2 100644 --- a/components/viz/common/quads/render_pass_unittest.cc +++ b/components/viz/common/quads/render_pass_unittest.cc
@@ -10,6 +10,7 @@ #include "cc/test/geometry_test_utils.h" #include "components/viz/common/frame_sinks/copy_output_request.h" +#include "components/viz/common/quads/aggregated_render_pass.h" #include "components/viz/common/quads/render_pass_draw_quad.h" #include "components/viz/common/quads/solid_color_draw_quad.h" #include "testing/gtest/include/gtest/gtest.h" @@ -74,7 +75,7 @@ } TEST(RenderPassTest, CopyShouldBeIdenticalExceptIdAndQuads) { - RenderPassId render_pass_id{3u}; + AggregatedRenderPassId render_pass_id{3u}; gfx::Rect output_rect(45, 22, 120, 13); gfx::Transform transform_to_root = gfx::Transform(1.0, 0.5, 0.5, -0.5, -1.0, 0.0); @@ -91,7 +92,7 @@ bool has_damage_from_contributing_content = false; bool generate_mipmap = false; - std::unique_ptr<RenderPass> pass = RenderPass::Create(); + auto pass = std::make_unique<AggregatedRenderPass>(); pass->SetAll(render_pass_id, output_rect, damage_rect, transform_to_root, filters, backdrop_filters, backdrop_filter_bounds, content_color_usage, has_transparent_background, @@ -109,9 +110,9 @@ color_quad->SetNew(pass->shared_quad_state_list.back(), gfx::Rect(), gfx::Rect(), SkColor(), false); - RenderPassId new_render_pass_id{63u}; + AggregatedRenderPassId new_render_pass_id{63u}; - std::unique_ptr<RenderPass> copy = pass->Copy(new_render_pass_id); + auto copy = pass->Copy(new_render_pass_id); EXPECT_EQ(new_render_pass_id, copy->id); EXPECT_EQ(pass->output_rect, copy->output_rect); EXPECT_EQ(pass->transform_to_root_target, copy->transform_to_root_target); @@ -243,7 +244,7 @@ // Make a copy with CopyAll(). RenderPassList copy_list; - RenderPass::CopyAll(pass_list, ©_list); + RenderPass::CopyAllForTest(pass_list, ©_list); CompareRenderPassLists(pass_list, copy_list); } @@ -312,7 +313,7 @@ // Make a copy with CopyAll(). RenderPassList copy_list; - RenderPass::CopyAll(pass_list, ©_list); + RenderPass::CopyAllForTest(pass_list, ©_list); CompareRenderPassLists(pass_list, copy_list); }
diff --git a/components/viz/common/surfaces/aggregated_frame.h b/components/viz/common/surfaces/aggregated_frame.h index 3010cda..0541b4e 100644 --- a/components/viz/common/surfaces/aggregated_frame.h +++ b/components/viz/common/surfaces/aggregated_frame.h
@@ -10,7 +10,7 @@ #include "base/optional.h" #include "components/viz/common/delegated_ink_metadata.h" -#include "components/viz/common/quads/render_pass.h" +#include "components/viz/common/quads/aggregated_render_pass.h" #include "components/viz/common/viz_common_export.h" #include "ui/gfx/display_color_spaces.h" #include "ui/latency/latency_info.h" @@ -55,7 +55,7 @@ // delegated ink metadata. std::unique_ptr<DelegatedInkMetadata> delegated_ink_metadata; - RenderPassList render_pass_list; + AggregatedRenderPassList render_pass_list; }; } // namespace viz
diff --git a/components/viz/service/display/ca_layer_overlay.cc b/components/viz/service/display/ca_layer_overlay.cc index 393a085..35352e6 100644 --- a/components/viz/service/display/ca_layer_overlay.cc +++ b/components/viz/service/display/ca_layer_overlay.cc
@@ -7,7 +7,7 @@ #include <algorithm> #include "base/metrics/histogram_macros.h" -#include "components/viz/common/quads/render_pass_draw_quad.h" +#include "components/viz/common/quads/aggregated_render_pass_draw_quad.h" #include "components/viz/common/quads/solid_color_draw_quad.h" #include "components/viz/common/quads/stream_video_draw_quad.h" #include "components/viz/common/quads/texture_draw_quad.h" @@ -85,10 +85,10 @@ CALayerResult FromRenderPassQuad( DisplayResourceProvider* resource_provider, - const RenderPassDrawQuad* quad, - const base::flat_map<RenderPassId, cc::FilterOperations*>& + const AggregatedRenderPassDrawQuad* quad, + const base::flat_map<AggregatedRenderPassId, cc::FilterOperations*>& render_pass_filters, - const base::flat_map<RenderPassId, cc::FilterOperations*>& + const base::flat_map<AggregatedRenderPassId, cc::FilterOperations*>& render_pass_backdrop_filters, CALayerOverlay* ca_layer_overlay) { if (render_pass_backdrop_filters.count(quad->render_pass_id)) { @@ -185,9 +185,9 @@ DisplayResourceProvider* resource_provider, const gfx::RectF& display_rect, const DrawQuad* quad, - const base::flat_map<RenderPassId, cc::FilterOperations*>& + const base::flat_map<AggregatedRenderPassId, cc::FilterOperations*>& render_pass_filters, - const base::flat_map<RenderPassId, cc::FilterOperations*>& + const base::flat_map<AggregatedRenderPassId, cc::FilterOperations*>& render_pass_backdrop_filters, CALayerOverlay* ca_layer_overlay, bool* skip, @@ -248,7 +248,8 @@ ca_layer_overlay->bounds_rect = gfx::RectF(quad->rect); - *render_pass_draw_quad = quad->material == DrawQuad::Material::kRenderPass; + *render_pass_draw_quad = + quad->material == DrawQuad::Material::kAggregatedRenderPass; switch (quad->material) { case DrawQuad::Material::kTextureContent: return FromTextureQuad(resource_provider, @@ -268,9 +269,9 @@ return CA_LAYER_FAILED_DEBUG_BORDER; case DrawQuad::Material::kPictureContent: return CA_LAYER_FAILED_PICTURE_CONTENT; - case DrawQuad::Material::kRenderPass: + case DrawQuad::Material::kAggregatedRenderPass: return FromRenderPassQuad( - resource_provider, RenderPassDrawQuad::MaterialCast(quad), + resource_provider, AggregatedRenderPassDrawQuad::MaterialCast(quad), render_pass_filters, render_pass_backdrop_filters, ca_layer_overlay); case DrawQuad::Material::kSurfaceContent: @@ -301,9 +302,9 @@ DisplayResourceProvider* resource_provider, const gfx::RectF& display_rect, const QuadList& quad_list, - const base::flat_map<RenderPassId, cc::FilterOperations*>& + const base::flat_map<AggregatedRenderPassId, cc::FilterOperations*>& render_pass_filters, - const base::flat_map<RenderPassId, cc::FilterOperations*>& + const base::flat_map<AggregatedRenderPassId, cc::FilterOperations*>& render_pass_backdrop_filters, CALayerOverlayList* ca_layer_overlays) const { CALayerResult result = CA_LAYER_SUCCESS;
diff --git a/components/viz/service/display/ca_layer_overlay.h b/components/viz/service/display/ca_layer_overlay.h index 5e9c2f27..af6d2770 100644 --- a/components/viz/service/display/ca_layer_overlay.h +++ b/components/viz/service/display/ca_layer_overlay.h
@@ -5,8 +5,11 @@ #ifndef COMPONENTS_VIZ_SERVICE_DISPLAY_CA_LAYER_OVERLAY_H_ #define COMPONENTS_VIZ_SERVICE_DISPLAY_CA_LAYER_OVERLAY_H_ +#include <vector> + #include "base/containers/flat_map.h" #include "base/memory/ref_counted.h" +#include "components/viz/common/quads/aggregated_render_pass.h" #include "components/viz/common/quads/render_pass.h" #include "components/viz/service/viz_service_export.h" #include "gpu/command_buffer/common/mailbox.h" @@ -17,9 +20,9 @@ #include "ui/gl/ca_renderer_layer_params.h" namespace viz { +class AggregatedRenderPassDrawQuad; class DisplayResourceProvider; class DrawQuad; -class RenderPassDrawQuad; // Holds information that is frequently shared between consecutive // CALayerOverlays. @@ -72,7 +75,7 @@ unsigned filter; // If |rpdq| is present, then the renderer must draw the filter effects and // copy the result into an IOSurface. - const RenderPassDrawQuad* rpdq = nullptr; + const AggregatedRenderPassDrawQuad* rpdq = nullptr; }; typedef std::vector<CALayerOverlay> CALayerOverlayList; @@ -90,9 +93,9 @@ DisplayResourceProvider* resource_provider, const gfx::RectF& display_rect, const QuadList& quad_list, - const base::flat_map<RenderPassId, cc::FilterOperations*>& + const base::flat_map<AggregatedRenderPassId, cc::FilterOperations*>& render_pass_filters, - const base::flat_map<RenderPassId, cc::FilterOperations*>& + const base::flat_map<AggregatedRenderPassId, cc::FilterOperations*>& render_pass_backdrop_filters, CALayerOverlayList* ca_layer_overlays) const;
diff --git a/components/viz/service/display/copy_output_scaling_pixeltest.cc b/components/viz/service/display/copy_output_scaling_pixeltest.cc index fb4679e..d130700 100644 --- a/components/viz/service/display/copy_output_scaling_pixeltest.cc +++ b/components/viz/service/display/copy_output_scaling_pixeltest.cc
@@ -93,13 +93,14 @@ SK_ColorBLUE, SK_ColorYELLOW}; constexpr SkColor root_pass_color = SK_ColorWHITE; - RenderPassList list; + AggregatedRenderPassList list; // Create the render passes drawn on top of the root render pass. - RenderPass* smaller_passes[4]; + AggregatedRenderPass* smaller_passes[4]; gfx::Rect smaller_pass_rects[4]; - RenderPassId pass_id{5}; - for (int i = 0; i < 4; ++i, pass_id = RenderPassId{pass_id.value() - 1}) { + AggregatedRenderPassId pass_id{5}; + for (int i = 0; i < 4; + ++i, pass_id = AggregatedRenderPassId{pass_id.value() - 1}) { smaller_pass_rects[i] = gfx::Rect( i % 2 == 0 ? x_block : (viewport_size.width() - 2 * x_block), i / 2 == 0 ? y_block : (viewport_size.height() - 2 * y_block), @@ -112,7 +113,7 @@ } // Create the root render pass and add all the child passes to it. - RenderPass* root_pass = + auto* root_pass = cc::AddRenderPass(&list, pass_id, gfx::Rect(viewport_size), gfx::Transform(), cc::FilterOperations()); for (int i = 0; i < 4; ++i)
diff --git a/components/viz/service/display/damage_frame_annotator.cc b/components/viz/service/display/damage_frame_annotator.cc index d7205024..15309e2 100644 --- a/components/viz/service/display/damage_frame_annotator.cc +++ b/components/viz/service/display/damage_frame_annotator.cc
@@ -8,8 +8,8 @@ #include <utility> #include "cc/base/math_util.h" +#include "components/viz/common/quads/aggregated_render_pass.h" #include "components/viz/common/quads/debug_border_draw_quad.h" -#include "components/viz/common/quads/render_pass.h" #include "components/viz/common/quads/shared_quad_state.h" #include "components/viz/common/surfaces/aggregated_frame.h" @@ -34,7 +34,8 @@ annotations_.clear(); } -void DamageFrameAnnotator::AnnotateRootRenderPass(RenderPass* render_pass) { +void DamageFrameAnnotator::AnnotateRootRenderPass( + AggregatedRenderPass* render_pass) { const size_t num_quads_to_add = annotations_.size(); // Insert |num_quads_to_add| new DebugBorderDrawQuad at start of list. The
diff --git a/components/viz/service/display/damage_frame_annotator.h b/components/viz/service/display/damage_frame_annotator.h index 54179ac..43e29a6 100644 --- a/components/viz/service/display/damage_frame_annotator.h +++ b/components/viz/service/display/damage_frame_annotator.h
@@ -15,7 +15,7 @@ namespace viz { class AggregatedFrame; -class RenderPass; +class AggregatedRenderPass; // Draws a red outline around the root RenderPasses damage rect. class DamageFrameAnnotator : public SurfaceAggregator::FrameAnnotator { @@ -38,7 +38,7 @@ Highlight highlight; }; - void AnnotateRootRenderPass(RenderPass* render_pass); + void AnnotateRootRenderPass(AggregatedRenderPass* render_pass); std::vector<AnnotationData> annotations_;
diff --git a/components/viz/service/display/dc_layer_overlay.cc b/components/viz/service/display/dc_layer_overlay.cc index 38145d5..a1b2b8d 100644 --- a/components/viz/service/display/dc_layer_overlay.cc +++ b/components/viz/service/display/dc_layer_overlay.cc
@@ -11,8 +11,8 @@ #include "build/build_config.h" #include "cc/base/math_util.h" #include "components/viz/common/display/renderer_settings.h" +#include "components/viz/common/quads/aggregated_render_pass_draw_quad.h" #include "components/viz/common/quads/debug_border_draw_quad.h" -#include "components/viz/common/quads/render_pass_draw_quad.h" #include "components/viz/common/quads/solid_color_draw_quad.h" #include "components/viz/common/quads/texture_draw_quad.h" #include "components/viz/common/quads/yuv_video_draw_quad.h" @@ -372,7 +372,7 @@ const gfx::RectF& display_rect, const gfx::Rect& overlay_rect, SkColor border_color, - RenderPass* render_pass, + AggregatedRenderPass* render_pass, gfx::Rect* damage_rect) { if (overlay_rect.IsEmpty()) return; @@ -397,14 +397,14 @@ void DCLayerOverlayProcessor::Process( DisplayResourceProvider* resource_provider, const gfx::RectF& display_rect, - RenderPassList* render_pass_list, + AggregatedRenderPassList* render_pass_list, gfx::Rect* damage_rect, DCLayerOverlayList* dc_layer_overlays) { gfx::Rect this_frame_overlay_rect; gfx::Rect this_frame_underlay_rect; // Which render passes have backdrop filters. - base::flat_set<RenderPassId> render_pass_has_backdrop_filters; + base::flat_set<AggregatedRenderPassId> render_pass_has_backdrop_filters; for (const auto& render_pass : *render_pass_list) { if (!render_pass->backdrop_filters.IsEmpty()) render_pass_has_backdrop_filters.insert(render_pass->id); @@ -415,7 +415,7 @@ // by backdrop filters. std::vector<gfx::Rect> backdrop_filter_rects; - RenderPass* root_render_pass = render_pass_list->back().get(); + auto* root_render_pass = render_pass_list->back().get(); if (render_pass_list->back()->is_color_conversion_pass) { DCHECK_GT(render_pass_list->size(), 1u); root_render_pass = (*render_pass_list)[render_pass_list->size() - 2].get(); @@ -435,8 +435,8 @@ bool has_required_overlays = false; for (auto it = quad_list->begin(); it != quad_list->end(); ++it, ++index) { - if (it->material == DrawQuad::Material::kRenderPass) { - const RenderPassDrawQuad* rpdq = RenderPassDrawQuad::MaterialCast(*it); + if (it->material == DrawQuad::Material::kAggregatedRenderPass) { + const auto* rpdq = AggregatedRenderPassDrawQuad::MaterialCast(*it); if (render_pass_has_backdrop_filters.count(rpdq->render_pass_id)) { backdrop_filter_rects.push_back( gfx::ToEnclosingRect(ClippedQuadRectangle(rpdq))); @@ -551,7 +551,7 @@ void DCLayerOverlayProcessor::UpdateDCLayerOverlays( const gfx::RectF& display_rect, - RenderPass* render_pass, + AggregatedRenderPass* render_pass, const QuadList::Iterator& it, const gfx::Rect& quad_rectangle_in_target_space, const gfx::Rect& occluding_damage_rect, @@ -625,7 +625,7 @@ QuadList::Iterator DCLayerOverlayProcessor::ProcessForOverlay( const gfx::RectF& display_rect, - RenderPass* render_pass, + AggregatedRenderPass* render_pass, const gfx::Rect& quad_rectangle, const QuadList::Iterator& it, gfx::Rect* damage_rect) { @@ -644,7 +644,7 @@ void DCLayerOverlayProcessor::ProcessForUnderlay( const gfx::RectF& display_rect, - RenderPass* render_pass, + AggregatedRenderPass* render_pass, const gfx::Rect& quad_rectangle, const QuadList::Iterator& it, gfx::Rect* damage_rect,
diff --git a/components/viz/service/display/dc_layer_overlay.h b/components/viz/service/display/dc_layer_overlay.h index 3e25a5ea..b396019 100644 --- a/components/viz/service/display/dc_layer_overlay.h +++ b/components/viz/service/display/dc_layer_overlay.h
@@ -10,7 +10,7 @@ #include "base/containers/flat_map.h" #include "base/memory/ref_counted.h" #include "base/single_thread_task_runner.h" -#include "components/viz/common/quads/render_pass.h" +#include "components/viz/common/quads/aggregated_render_pass.h" #include "components/viz/service/viz_service_export.h" #include "gpu/command_buffer/common/mailbox.h" #include "third_party/skia/include/core/SkColor.h" @@ -84,7 +84,7 @@ // Virtual for testing. virtual void Process(DisplayResourceProvider* resource_provider, const gfx::RectF& display_rect, - RenderPassList* render_passes, + AggregatedRenderPassList* render_passes, gfx::Rect* damage_rect, DCLayerOverlayList* dc_layer_overlays); void ClearOverlayState(); @@ -103,7 +103,7 @@ // UpdateDCLayerOverlays() adds the quad at |it| to the overlay list // |dc_layer_overlays|. void UpdateDCLayerOverlays(const gfx::RectF& display_rect, - RenderPass* render_pass, + AggregatedRenderPass* render_pass, const QuadList::Iterator& it, const gfx::Rect& quad_rectangle_in_target_space, const gfx::Rect& occluding_damage_rect, @@ -117,12 +117,12 @@ // Returns an iterator to the element after |it|. QuadList::Iterator ProcessForOverlay(const gfx::RectF& display_rect, - RenderPass* render_pass, + AggregatedRenderPass* render_pass, const gfx::Rect& quad_rectangle, const QuadList::Iterator& it, gfx::Rect* damage_rect); void ProcessForUnderlay(const gfx::RectF& display_rect, - RenderPass* render_pass, + AggregatedRenderPass* render_pass, const gfx::Rect& quad_rectangle, const QuadList::Iterator& it, gfx::Rect* damage_rect, @@ -132,7 +132,7 @@ void InsertDebugBorderDrawQuad(const gfx::RectF& display_rect, const gfx::Rect& overlay_rect, SkColor border_color, - RenderPass* render_pass, + AggregatedRenderPass* render_pass, gfx::Rect* damage_rect); bool has_overlay_support_;
diff --git a/components/viz/service/display/direct_renderer.cc b/components/viz/service/display/direct_renderer.cc index 1517007..d1d8cd7 100644 --- a/components/viz/service/display/direct_renderer.cc +++ b/components/viz/service/display/direct_renderer.cc
@@ -23,6 +23,7 @@ #include "components/viz/common/display/renderer_settings.h" #include "components/viz/common/frame_sinks/copy_output_request.h" #include "components/viz/common/frame_sinks/copy_output_util.h" +#include "components/viz/common/quads/aggregated_render_pass_draw_quad.h" #include "components/viz/common/quads/draw_quad.h" #include "components/viz/common/quads/render_pass_draw_quad.h" #include "components/viz/service/display/bsp_tree.h" @@ -197,7 +198,8 @@ return window_rect; } -const DrawQuad* DirectRenderer::CanPassBeDrawnDirectly(const RenderPass* pass) { +const DrawQuad* DirectRenderer::CanPassBeDrawnDirectly( + const AggregatedRenderPass* pass) { return nullptr; } @@ -210,12 +212,13 @@ } void DirectRenderer::DecideRenderPassAllocationsForFrame( - const RenderPassList& render_passes_in_draw_order) { + const AggregatedRenderPassList& render_passes_in_draw_order) { DCHECK(render_pass_bypass_quads_.empty()); auto& root_render_pass = render_passes_in_draw_order.back(); - base::flat_map<RenderPassId, RenderPassRequirements> render_passes_in_frame; + base::flat_map<AggregatedRenderPassId, RenderPassRequirements> + render_passes_in_frame; for (const auto& pass : render_passes_in_draw_order) { // If there's a copy request, we need an explicit renderpass backing so // only try to draw directly if there are no copy requests. @@ -238,7 +241,7 @@ } void DirectRenderer::DrawFrame( - RenderPassList* render_passes_in_draw_order, + AggregatedRenderPassList* render_passes_in_draw_order, float device_scale_factor, const gfx::Size& device_viewport_size, const gfx::DisplayColorSpaces& display_color_spaces) { @@ -248,7 +251,7 @@ "Renderer4.renderPassCount", base::saturated_cast<int>(render_passes_in_draw_order->size())); - RenderPass* root_render_pass = render_passes_in_draw_order->back().get(); + auto* root_render_pass = render_passes_in_draw_order->back().get(); DCHECK(root_render_pass); #if DCHECK_IS_ON() @@ -528,19 +531,19 @@ } const cc::FilterOperations* DirectRenderer::FiltersForPass( - RenderPassId render_pass_id) const { + AggregatedRenderPassId render_pass_id) const { auto it = render_pass_filters_.find(render_pass_id); return it == render_pass_filters_.end() ? nullptr : it->second; } const cc::FilterOperations* DirectRenderer::BackdropFiltersForPass( - RenderPassId render_pass_id) const { + AggregatedRenderPassId render_pass_id) const { auto it = render_pass_backdrop_filters_.find(render_pass_id); return it == render_pass_backdrop_filters_.end() ? nullptr : it->second; } const base::Optional<gfx::RRectF> DirectRenderer::BackdropFilterBoundsForPass( - RenderPassId render_pass_id) const { + AggregatedRenderPassId render_pass_id) const { auto it = render_pass_backdrop_filter_bounds_.find(render_pass_id); return it == render_pass_backdrop_filter_bounds_.end() ? base::Optional<gfx::RRectF>() @@ -563,7 +566,7 @@ } void DirectRenderer::DrawRenderPassAndExecuteCopyRequests( - RenderPass* render_pass) { + AggregatedRenderPass* render_pass) { if (render_pass_bypass_quads_.find(render_pass->id) != render_pass_bypass_quads_.end()) { return; @@ -608,7 +611,7 @@ } } -void DirectRenderer::DrawRenderPass(const RenderPass* render_pass) { +void DirectRenderer::DrawRenderPass(const AggregatedRenderPass* render_pass) { TRACE_EVENT0("viz", "DirectRenderer::DrawRenderPass"); if (CanSkipRenderPass(render_pass)) return; @@ -728,7 +731,8 @@ GenerateMipmap(); } -bool DirectRenderer::CanSkipRenderPass(const RenderPass* render_pass) const { +bool DirectRenderer::CanSkipRenderPass( + const AggregatedRenderPass* render_pass) const { if (render_pass == current_frame()->root_render_pass) return false; @@ -757,7 +761,7 @@ return false; } -void DirectRenderer::UseRenderPass(const RenderPass* render_pass) { +void DirectRenderer::UseRenderPass(const AggregatedRenderPass* render_pass) { current_frame()->current_render_pass = render_pass; if (render_pass == current_frame()->root_render_pass) { BindFramebufferToOutputSurface(); @@ -790,8 +794,9 @@ } gfx::Rect DirectRenderer::ComputeScissorRectForRenderPass( - const RenderPass* render_pass) const { - const RenderPass* root_render_pass = current_frame()->root_render_pass; + const AggregatedRenderPass* render_pass) const { + const AggregatedRenderPass* root_render_pass = + current_frame()->root_render_pass; gfx::Rect root_damage_rect = current_frame()->root_damage_rect; if (render_pass == root_render_pass) { @@ -827,9 +832,12 @@ if (!backdrop_filter_output_rects_.empty() && !root_damage_rect.IsEmpty()) { for (auto* quad : render_pass->quad_list) { - if (quad->material == DrawQuad::Material::kRenderPass) { + // Sanity check: we should not have a RenderPassDrawQuad here. + DCHECK_NE(quad->material, DrawQuad::Material::kRenderPass); + if (quad->material == DrawQuad::Material::kAggregatedRenderPass) { auto iter = backdrop_filter_output_rects_.find( - RenderPassDrawQuad::MaterialCast(quad)->render_pass_id); + AggregatedRenderPassDrawQuad::MaterialCast(quad) + ->render_pass_id); if (iter != backdrop_filter_output_rects_.end()) { gfx::Rect this_output_rect = iter->second; if (root_damage_rect.Intersects(this_output_rect)) @@ -871,7 +879,7 @@ } gfx::Size DirectRenderer::CalculateTextureSizeForRenderPass( - const RenderPass* render_pass) { + const AggregatedRenderPass* render_pass) { // Round the size of the render pass backings to a multiple of 64 pixels. This // reduces memory fragmentation. https://crbug.com/146070. This also allows // backings to be more easily reused during a resize operation. @@ -891,7 +899,7 @@ } bool DirectRenderer::HasAllocatedResourcesForTesting( - const RenderPassId& render_pass_id) const { + const AggregatedRenderPassId& render_pass_id) const { return IsRenderPassResourceAllocated(render_pass_id); }
diff --git a/components/viz/service/display/direct_renderer.h b/components/viz/service/display/direct_renderer.h index 7e43e8a..6baac20 100644 --- a/components/viz/service/display/direct_renderer.h +++ b/components/viz/service/display/direct_renderer.h
@@ -16,6 +16,7 @@ #include "base/optional.h" #include "build/build_config.h" #include "components/viz/common/delegated_ink_metadata.h" +#include "components/viz/common/quads/aggregated_render_pass.h" #include "components/viz/common/quads/tile_draw_quad.h" #include "components/viz/service/display/delegated_ink_point_renderer_base.h" #include "components/viz/service/display/display_resource_provider.h" @@ -43,7 +44,6 @@ class OutputSurface; struct DebugRendererSettings; class RendererSettings; -class RenderPass; namespace copy_output { struct RenderPassGeometry; @@ -68,8 +68,8 @@ void SetVisible(bool visible); void DecideRenderPassAllocationsForFrame( - const RenderPassList& render_passes_in_draw_order); - void DrawFrame(RenderPassList* render_passes_in_draw_order, + const AggregatedRenderPassList& render_passes_in_draw_order); + void DrawFrame(AggregatedRenderPassList* render_passes_in_draw_order, float device_scale_factor, const gfx::Size& device_viewport_size, const gfx::DisplayColorSpaces& display_color_spaces); @@ -104,9 +104,9 @@ DrawingFrame(); ~DrawingFrame(); - const RenderPassList* render_passes_in_draw_order = nullptr; - const RenderPass* root_render_pass = nullptr; - const RenderPass* current_render_pass = nullptr; + const AggregatedRenderPassList* render_passes_in_draw_order = nullptr; + const AggregatedRenderPass* root_render_pass = nullptr; + const AggregatedRenderPass* current_render_pass = nullptr; gfx::Rect root_damage_rect; std::vector<gfx::Rect> root_content_bounds; @@ -126,7 +126,7 @@ void SetCurrentFrameForTesting(const DrawingFrame& frame); bool HasAllocatedResourcesForTesting( - const RenderPassId& render_pass_id) const; + const AggregatedRenderPassId& render_pass_id) const; // Allow tests to enlarge the texture size of non-root render passes to // verify cases where the texture doesn't match the render pass size. void SetEnlargePassTextureAmountForTesting(const gfx::Size& amount) { @@ -183,47 +183,50 @@ const gfx::Rect& render_pass_scissor); void SetScissorTestRectInDrawSpace(const gfx::Rect& draw_space_rect); - gfx::Size CalculateTextureSizeForRenderPass(const RenderPass* render_pass); + gfx::Size CalculateTextureSizeForRenderPass( + const AggregatedRenderPass* render_pass); void FlushPolygons( base::circular_deque<std::unique_ptr<DrawPolygon>>* poly_list, const gfx::Rect& render_pass_scissor, bool use_render_pass_scissor); - void DrawRenderPassAndExecuteCopyRequests(RenderPass* render_pass); - void DrawRenderPass(const RenderPass* render_pass); + void DrawRenderPassAndExecuteCopyRequests(AggregatedRenderPass* render_pass); + void DrawRenderPass(const AggregatedRenderPass* render_pass); // Returns true if it detects that we do not need to draw the render pass. // This may be because the RenderPass is already cached, or because it is // entirely clipped out, for instance. - bool CanSkipRenderPass(const RenderPass* render_pass) const; - void UseRenderPass(const RenderPass* render_pass); + bool CanSkipRenderPass(const AggregatedRenderPass* render_pass) const; + void UseRenderPass(const AggregatedRenderPass* render_pass); gfx::Rect ComputeScissorRectForRenderPass( - const RenderPass* render_pass) const; + const AggregatedRenderPass* render_pass) const; void DoDrawPolygon(const DrawPolygon& poly, const gfx::Rect& render_pass_scissor, bool use_render_pass_scissor); - const cc::FilterOperations* FiltersForPass(RenderPassId render_pass_id) const; + const cc::FilterOperations* FiltersForPass( + AggregatedRenderPassId render_pass_id) const; const cc::FilterOperations* BackdropFiltersForPass( - RenderPassId render_pass_id) const; + AggregatedRenderPassId render_pass_id) const; const base::Optional<gfx::RRectF> BackdropFilterBoundsForPass( - RenderPassId render_pass_id) const; + AggregatedRenderPassId render_pass_id) const; // Private interface implemented by subclasses for use by DirectRenderer. virtual bool CanPartialSwap() = 0; virtual void UpdateRenderPassTextures( - const RenderPassList& render_passes_in_draw_order, - const base::flat_map<RenderPassId, RenderPassRequirements>& + const AggregatedRenderPassList& render_passes_in_draw_order, + const base::flat_map<AggregatedRenderPassId, RenderPassRequirements>& render_passes_in_frame) = 0; virtual void AllocateRenderPassResourceIfNeeded( - const RenderPassId& render_pass_id, + const AggregatedRenderPassId& render_pass_id, const RenderPassRequirements& requirements) = 0; virtual bool IsRenderPassResourceAllocated( - const RenderPassId& render_pass_id) const = 0; + const AggregatedRenderPassId& render_pass_id) const = 0; virtual gfx::Size GetRenderPassBackingPixelSize( - const RenderPassId& render_pass_id) = 0; + const AggregatedRenderPassId& render_pass_id) = 0; virtual void BindFramebufferToOutputSurface() = 0; - virtual void BindFramebufferToTexture(const RenderPassId render_pass_id) = 0; + virtual void BindFramebufferToTexture( + const AggregatedRenderPassId render_pass_id) = 0; virtual void SetScissorTestRect(const gfx::Rect& scissor_rect) = 0; virtual void PrepareSurfaceForPass( SurfaceInitializationMode initialization_mode, @@ -239,7 +242,8 @@ // If a pass contains a single tile draw quad and can be drawn without // a render pass (e.g. applying a filter directly to the tile quad) // return that quad, otherwise return null. - virtual const DrawQuad* CanPassBeDrawnDirectly(const RenderPass* pass); + virtual const DrawQuad* CanPassBeDrawnDirectly( + const AggregatedRenderPass* pass); virtual void FinishDrawingQuadList() {} virtual bool FlippedFramebuffer() const = 0; virtual void EnsureScissorTestEnabled() = 0; @@ -281,15 +285,18 @@ // RenderPass. The DrawQuads are owned by their RenderPasses, which outlive // the drawn frame, so it is safe to store these pointers until the end of // DrawFrame(). - base::flat_map<RenderPassId, const DrawQuad*> render_pass_bypass_quads_; + base::flat_map<AggregatedRenderPassId, const DrawQuad*> + render_pass_bypass_quads_; // A map from RenderPass id to the filters used when drawing the RenderPass. - base::flat_map<RenderPassId, cc::FilterOperations*> render_pass_filters_; - base::flat_map<RenderPassId, cc::FilterOperations*> + base::flat_map<AggregatedRenderPassId, cc::FilterOperations*> + render_pass_filters_; + base::flat_map<AggregatedRenderPassId, cc::FilterOperations*> render_pass_backdrop_filters_; - base::flat_map<RenderPassId, base::Optional<gfx::RRectF>> + base::flat_map<AggregatedRenderPassId, base::Optional<gfx::RRectF>> render_pass_backdrop_filter_bounds_; - base::flat_map<RenderPassId, gfx::Rect> backdrop_filter_output_rects_; + base::flat_map<AggregatedRenderPassId, gfx::Rect> + backdrop_filter_output_rects_; bool visible_ = false; bool disable_color_checks_for_testing_ = false;
diff --git a/components/viz/service/display/display.cc b/components/viz/service/display/display.cc index f227e21..17f1887b6 100644 --- a/components/viz/service/display/display.cc +++ b/components/viz/service/display/display.cc
@@ -1036,7 +1036,7 @@ if (frame->render_pass_list.empty()) return; - base::flat_map<RenderPassId, gfx::Rect> backdrop_filter_rects; + base::flat_map<AggregatedRenderPassId, gfx::Rect> backdrop_filter_rects; for (const auto& pass : frame->render_pass_list) { if (!pass->backdrop_filters.IsEmpty() && pass->backdrop_filters.HasFilterThatMovesPixels()) { @@ -1064,15 +1064,17 @@ cc::Region occlusion_in_quad_content_space; gfx::Rect render_pass_quads_in_content_space; for (auto quad = pass->quad_list.begin(); quad != quad_list_end;) { + // Sanity check: we should not have a RenderPassDrawQuad here. + DCHECK_NE(quad->material, DrawQuad::Material::kRenderPass); // Skip quad if it is a RenderPassDrawQuad because RenderPassDrawQuad is a // special type of DrawQuad where the visible_rect of shared quad state is // not entirely covered by draw quads in it. - if (quad->material == ContentDrawQuadBase::Material::kRenderPass) { + if (quad->material == DrawQuad::Material::kAggregatedRenderPass) { // A RenderPass with backdrop filters may apply to a quad underlying // RenderPassQuad. These regions should be tracked so that correctly // handle splitting and occlusion of the underlying quad. - auto it = backdrop_filter_rects.find( - RenderPassDrawQuad::MaterialCast(*quad)->render_pass_id); + auto* rpdq = AggregatedRenderPassDrawQuad::MaterialCast(*quad); + auto it = backdrop_filter_rects.find(rpdq->render_pass_id); if (it != backdrop_filter_rects.end()) { backdrop_filters_in_target_space.Union(it->second); }
diff --git a/components/viz/service/display/display_client.h b/components/viz/service/display/display_client.h index 45bfc4ae..78c0a5ed 100644 --- a/components/viz/service/display/display_client.h +++ b/components/viz/service/display/display_client.h
@@ -5,7 +5,7 @@ #ifndef COMPONENTS_VIZ_SERVICE_DISPLAY_DISPLAY_CLIENT_H_ #define COMPONENTS_VIZ_SERVICE_DISPLAY_DISPLAY_CLIENT_H_ -#include "components/viz/common/quads/render_pass.h" +#include "components/viz/common/quads/aggregated_render_pass.h" #include "services/viz/public/mojom/compositing/compositor_frame_sink.mojom.h" namespace gfx { @@ -21,8 +21,9 @@ virtual void DisplayOutputSurfaceLost() = 0; // It is expected that |render_pass| would only be modified to insert debug // quads. - virtual void DisplayWillDrawAndSwap(bool will_draw_and_swap, - RenderPassList* render_passes) = 0; + virtual void DisplayWillDrawAndSwap( + bool will_draw_and_swap, + AggregatedRenderPassList* render_passes) = 0; virtual void DisplayDidDrawAndSwap() = 0; virtual void DisplayDidReceiveCALayerParams( const gfx::CALayerParams& ca_layer_params) = 0;
diff --git a/components/viz/service/display/display_perftest.cc b/components/viz/service/display/display_perftest.cc index 9e7bcc851..ce2cd52 100644 --- a/components/viz/service/display/display_perftest.cc +++ b/components/viz/service/display/display_perftest.cc
@@ -79,7 +79,7 @@ } // Create an arbitrary SharedQuadState for the given |render_pass|. - SharedQuadState* CreateSharedQuadState(RenderPass* render_pass, + SharedQuadState* CreateSharedQuadState(AggregatedRenderPass* render_pass, gfx::Rect rect) { gfx::Transform quad_transform = gfx::Transform(); bool is_clipped = false; @@ -139,7 +139,7 @@ void IterateOverlapShareQuadStates(const std::string& story, int shared_quad_state_count, int quad_count) { - frame_.render_pass_list.push_back(RenderPass::Create()); + frame_.render_pass_list.push_back(std::make_unique<AggregatedRenderPass>()); CreateOverlapShareQuadStates(shared_quad_state_count, quad_count); std::unique_ptr<Display> display = CreateDisplay(); @@ -180,7 +180,7 @@ void IterateIsolatedSharedQuadStates(const std::string& story, int shared_quad_state_count, int quad_count) { - frame_.render_pass_list.push_back(RenderPass::Create()); + frame_.render_pass_list.push_back(std::make_unique<AggregatedRenderPass>()); CreateIsolatedSharedQuadStates(shared_quad_state_count, quad_count); std::unique_ptr<Display> display = CreateDisplay(); timer_.Reset(); @@ -228,7 +228,7 @@ int shared_quad_state_count, float percentage_overlap, int quad_count) { - frame_.render_pass_list.push_back(RenderPass::Create()); + frame_.render_pass_list.push_back(std::make_unique<AggregatedRenderPass>()); CreatePartiallyOverlapSharedQuadStates(shared_quad_state_count, percentage_overlap, quad_count); std::unique_ptr<Display> display = CreateDisplay(); @@ -275,7 +275,7 @@ void IterateAdjacentSharedQuadStates(const std::string& story, int shared_quad_state_count, int quad_count) { - frame_.render_pass_list.push_back(RenderPass::Create()); + frame_.render_pass_list.push_back(std::make_unique<AggregatedRenderPass>()); CreateAdjacentSharedQuadStates(shared_quad_state_count, quad_count); std::unique_ptr<Display> display = CreateDisplay();
diff --git a/components/viz/service/display/display_unittest.cc b/components/viz/service/display/display_unittest.cc index 7ed89e9..56481d54 100644 --- a/components/viz/service/display/display_unittest.cc +++ b/components/viz/service/display/display_unittest.cc
@@ -20,6 +20,8 @@ #include "components/viz/common/frame_sinks/begin_frame_source.h" #include "components/viz/common/frame_sinks/copy_output_request.h" #include "components/viz/common/frame_sinks/copy_output_result.h" +#include "components/viz/common/quads/aggregated_render_pass.h" +#include "components/viz/common/quads/aggregated_render_pass_draw_quad.h" #include "components/viz/common/quads/compositor_frame.h" #include "components/viz/common/quads/render_pass.h" #include "components/viz/common/quads/render_pass_draw_quad.h" @@ -95,8 +97,9 @@ class StubDisplayClient : public DisplayClient { public: void DisplayOutputSurfaceLost() override {} - void DisplayWillDrawAndSwap(bool will_draw_and_swap, - RenderPassList* render_passes) override {} + void DisplayWillDrawAndSwap( + bool will_draw_and_swap, + AggregatedRenderPassList* render_passes) override {} void DisplayDidDrawAndSwap() override {} void DisplayDidReceiveCALayerParams( const gfx::CALayerParams& ca_layer_params) override {} @@ -936,12 +939,7 @@ SetUpGpuDisplay(settings); StubDisplayClient client; display_->Initialize(&client, manager_.surface_manager()); - CompositorFrame compositor_frame = CompositorFrameBuilder() - .AddDefaultRenderPass() - .AddDefaultRenderPass() - .Build(); - AggregatedFrame frame; - frame.render_pass_list = std::move(compositor_frame.render_pass_list); + AggregatedFrame frame = MakeDefaultAggregatedFrame(/*num_render_passes=*/2); bool is_clipped = false; bool are_contents_opaque = true; @@ -989,12 +987,7 @@ SetUpGpuDisplay(settings); StubDisplayClient client; display_->Initialize(&client, manager_.surface_manager()); - CompositorFrame compositor_frame = CompositorFrameBuilder() - .AddDefaultRenderPass() - .AddDefaultRenderPass() - .Build(); - AggregatedFrame frame; - frame.render_pass_list = std::move(compositor_frame.render_pass_list); + AggregatedFrame frame = MakeDefaultAggregatedFrame(/*num_render_passes=*/2); bool is_clipped = false; bool are_contents_opaque = true; @@ -1017,7 +1010,7 @@ cc::FilterOperations backdrop_filters; backdrop_filters.Append(cc::FilterOperation::CreateBlurFilter(5.0)); bd_render_pass->SetAll( - RenderPassId{2}, bd_filter_rect, gfx::Rect(), gfx::Transform(), + AggregatedRenderPassId{2}, bd_filter_rect, gfx::Rect(), gfx::Transform(), cc::FilterOperations(), backdrop_filters, gfx::RRectF(gfx::RectF(bd_filter_rect), 0), gfx::ContentColorUsage::kSRGB, false, false, false, false); @@ -1030,8 +1023,9 @@ is_clipped, are_contents_opaque, opacity, SkBlendMode::kSrcOver, 0); if (i == 0) { // Backdrop filter quad - auto* new_quad = root_render_pass->quad_list - .AllocateAndConstruct<RenderPassDrawQuad>(); + auto* new_quad = + root_render_pass->quad_list + .AllocateAndConstruct<AggregatedRenderPassDrawQuad>(); new_quad->SetNew(shared_quad_states[i], rects[i], rects[i], bd_render_pass->id, 2, gfx::RectF(), gfx::Size(), gfx::Vector2dF(1, 1), gfx::PointF(), gfx::RectF(), false, @@ -2657,12 +2651,7 @@ StubDisplayClient client; display_->Initialize(&client, manager_.surface_manager()); - CompositorFrame compositor_frame = CompositorFrameBuilder() - .AddDefaultRenderPass() - .AddDefaultRenderPass() - .Build(); - AggregatedFrame frame; - frame.render_pass_list = std::move(compositor_frame.render_pass_list); + AggregatedFrame frame = MakeDefaultAggregatedFrame(/*num_render_passes=*/2); // rect 3 is inside of combined rect of rect 1 and rect 2. // rect 4 is identical to rect 3, but in a separate render pass. @@ -2715,8 +2704,8 @@ gfx::Rect rect1(0, 0, 100, 100); gfx::Rect rect2(100, 0, 60, 60); - std::unique_ptr<RenderPass> render_pass2 = RenderPass::Create(); - render_pass2->SetNew(RenderPassId{1}, gfx::Rect(), gfx::Rect(), + auto render_pass2 = std::make_unique<AggregatedRenderPass>(); + render_pass2->SetNew(AggregatedRenderPassId{1}, gfx::Rect(), gfx::Rect(), gfx::Transform()); frame.render_pass_list.push_back(std::move(render_pass2)); gfx::Rect rect3(10, 10, 120, 30); @@ -2788,15 +2777,15 @@ AggregatedFrame frame = MakeDefaultAggregatedFrame(); gfx::Rect rect1(0, 0, 100, 100); - std::unique_ptr<RenderPass> render_pass2 = RenderPass::Create(); - render_pass2->SetNew(RenderPassId{1}, gfx::Rect(), gfx::Rect(), + auto render_pass2 = std::make_unique<AggregatedRenderPass>(); + render_pass2->SetNew(AggregatedRenderPassId{1}, gfx::Rect(), gfx::Rect(), gfx::Transform()); frame.render_pass_list.push_back(std::move(render_pass2)); bool is_clipped = false; bool opaque_content = true; float opacity = 1.f; - RenderPassId render_pass_id{1}; + AggregatedRenderPassId render_pass_id{1}; ResourceId mask_resource_id = 2; SharedQuadState* shared_quad_state = @@ -2805,12 +2794,13 @@ ->quad_list.AllocateAndConstruct<SolidColorDrawQuad>(); SharedQuadState* shared_quad_state2 = frame.render_pass_list.at(1)->CreateAndAppendSharedQuadState(); - auto* quad1 = frame.render_pass_list.front() - ->quad_list.AllocateAndConstruct<RenderPassDrawQuad>(); + auto* quad1 = + frame.render_pass_list.front() + ->quad_list.AllocateAndConstruct<AggregatedRenderPassDrawQuad>(); { // rect1 is a DrawQuad from SQS1 and which is also the RenderPass rect - // from SQS2. The RenderPassDrawQuad should not be occluded. + // from SQS2. The AggregatedRenderPassDrawQuad should not be occluded. // rect1 // +----+ // | | @@ -3025,17 +3015,19 @@ bool is_clipped = false; bool opaque_content = true; - RenderPassId render_pass_id{1}; + AggregatedRenderPassId render_pass_id{1}; ResourceId mask_resource_id = 2; float opacity = 1.f; SharedQuadState* shared_quad_state = frame.render_pass_list.front()->CreateAndAppendSharedQuadState(); - auto* R1 = frame.render_pass_list.front() - ->quad_list.AllocateAndConstruct<RenderPassDrawQuad>(); + auto* R1 = + frame.render_pass_list.front() + ->quad_list.AllocateAndConstruct<AggregatedRenderPassDrawQuad>(); SharedQuadState* shared_quad_state2 = frame.render_pass_list.front()->CreateAndAppendSharedQuadState(); - auto* R2 = frame.render_pass_list.front() - ->quad_list.AllocateAndConstruct<RenderPassDrawQuad>(); + auto* R2 = + frame.render_pass_list.front() + ->quad_list.AllocateAndConstruct<AggregatedRenderPassDrawQuad>(); SharedQuadState* shared_quad_state3 = frame.render_pass_list.front()->CreateAndAppendSharedQuadState(); auto* D1 = frame.render_pass_list.front() @@ -3075,8 +3067,8 @@ EXPECT_EQ(4u, NumVisibleRects(frame.render_pass_list.front()->quad_list)); display_->RemoveOverdrawQuads(&frame); // As shown in the image above, the opaque region |d1| and |d2| does not - // occlude each other. Since RenderPassDrawQuad |r1| and |r2| cannot be - // removed to reduce overdraw, |quad_list| remains unchanged. + // occlude each other. Since AggregatedRenderPassDrawQuad |r1| and |r2| + // cannot be removed to reduce overdraw, |quad_list| remains unchanged. EXPECT_EQ(4u, NumVisibleRects(frame.render_pass_list.front()->quad_list)); EXPECT_EQ(rect1.ToString(), frame.render_pass_list.front() ->quad_list.ElementAt(0) @@ -3123,8 +3115,8 @@ EXPECT_EQ(4u, NumVisibleRects(frame.render_pass_list.front()->quad_list)); display_->RemoveOverdrawQuads(&frame); // As shown in the image above, the opaque region |d1| and |d2| does not - // occlude each other. Since RenderPassDrawQuad |r1| and |r2| cannot be - // removed to reduce overdraw, |quad_list| remains unchanged. + // occlude each other. Since AggregatedRenderPassDrawQuad |r1| and |r2| + // cannot be removed to reduce overdraw, |quad_list| remains unchanged. EXPECT_EQ(4u, NumVisibleRects(frame.render_pass_list.front()->quad_list)); EXPECT_EQ(rect5.ToString(), frame.render_pass_list.front() ->quad_list.ElementAt(0) @@ -3170,8 +3162,8 @@ EXPECT_EQ(4u, NumVisibleRects(frame.render_pass_list.front()->quad_list)); display_->RemoveOverdrawQuads(&frame); // As shown in the image above, the opaque region |d2| is contained in |d1| - // Since RenderPassDrawQuad |r1| and |r2| cannot be removed to reduce - // overdraw, |quad_list| is reduced by 1. + // Since AggregatedRenderPassDrawQuad |r1| and |r2| cannot be removed to + // reduce overdraw, |quad_list| is reduced by 1. EXPECT_EQ(3u, NumVisibleRects(frame.render_pass_list.front()->quad_list)); EXPECT_EQ(rect5.ToString(), frame.render_pass_list.front() ->quad_list.ElementAt(0)
diff --git a/components/viz/service/display/gl_renderer.cc b/components/viz/service/display/gl_renderer.cc index d7b2f17..8d50154 100644 --- a/components/viz/service/display/gl_renderer.cc +++ b/components/viz/service/display/gl_renderer.cc
@@ -244,7 +244,7 @@ } // Required inputs below. - const RenderPassDrawQuad* quad = nullptr; + const AggregatedRenderPassDrawQuad* quad = nullptr; // Either |contents_texture| or |bypass_quad_texture| is populated. The // |contents_texture| will be valid if non-null, and when null the @@ -587,6 +587,10 @@ case DrawQuad::Material::kInvalid: NOTREACHED(); break; + case DrawQuad::Material::kAggregatedRenderPass: + DrawRenderPassQuad(AggregatedRenderPassDrawQuad::MaterialCast(quad), + clip_region); + break; case DrawQuad::Material::kDebugBorder: DrawDebugBorderQuad(DebugBorderDrawQuad::MaterialCast(quad)); break; @@ -595,7 +599,9 @@ NOTREACHED(); break; case DrawQuad::Material::kRenderPass: - DrawRenderPassQuad(RenderPassDrawQuad::MaterialCast(quad), clip_region); + // At this point, RenderPassDrawQuads should be replaced by + // AggregatedRenderPassDrawQuad. + NOTREACHED(); break; case DrawQuad::Material::kSolidColor: DrawSolidColorQuad(SolidColorDrawQuad::MaterialCast(quad), clip_region); @@ -829,7 +835,7 @@ DCHECK(backdrop_filter_bounds); DCHECK(unclipped_rect); - const RenderPassDrawQuad* quad = params->quad; + const auto* quad = params->quad; gfx::QuadF scaled_region; // |scaled_region| is a quad in [-0.5,0.5] space that represents |clip_region| // as a fraction of the space defined by |quad->rect|. If |clip_region| is @@ -1016,7 +1022,7 @@ params->backdrop_filter_quality <= 1.0f); DCHECK(!params->filters) << "Filters should always be in a separate Effect node"; - const RenderPassDrawQuad* quad = params->quad; + const auto* quad = params->quad; auto use_gr_context = ScopedUseGrContext::Create(this); // Check if cached result can be used @@ -1167,7 +1173,8 @@ return filtered_image_texture; } -const DrawQuad* GLRenderer::CanPassBeDrawnDirectly(const RenderPass* pass) { +const DrawQuad* GLRenderer::CanPassBeDrawnDirectly( + const AggregatedRenderPass* pass) { #if defined(OS_APPLE) // On Macs, this path can sometimes lead to all black output. // TODO(enne): investigate this and remove this hack. @@ -1218,7 +1225,7 @@ #endif } -void GLRenderer::DrawRenderPassQuad(const RenderPassDrawQuad* quad, +void GLRenderer::DrawRenderPassQuad(const AggregatedRenderPassDrawQuad* quad, const gfx::QuadF* clip_region) { auto bypass = render_pass_bypass_quads_.find(quad->render_pass_id); DrawRenderPassDrawQuadParams params; @@ -1285,7 +1292,7 @@ bool GLRenderer::InitializeRPDQParameters( DrawRenderPassDrawQuadParams* params) { DCHECK(params); - const RenderPassDrawQuad* quad = params->quad; + const auto* quad = params->quad; SkMatrix local_matrix; local_matrix.setTranslate(quad->filters_origin.x(), quad->filters_origin.y()); local_matrix.postScale(quad->filters_scale.x(), quad->filters_scale.y()); @@ -1360,7 +1367,7 @@ void GLRenderer::UpdateRPDQShadersForBlending( DrawRenderPassDrawQuadParams* params) { - const RenderPassDrawQuad* quad = params->quad; + const auto* quad = params->quad; params->blend_mode = quad->shared_quad_state->blend_mode; params->use_shaders_for_blending = !CanApplyBlendModeUsingBlendFunc(params->blend_mode) || @@ -1445,7 +1452,7 @@ bool GLRenderer::UpdateRPDQWithSkiaFilters( DrawRenderPassDrawQuadParams* params) { - const RenderPassDrawQuad* quad = params->quad; + const auto* quad = params->quad; // Apply filters to the contents texture. if (params->filters) { DCHECK(!params->filters->IsEmpty()); @@ -1996,7 +2003,7 @@ // static void GLRenderer::SetupRenderPassQuadForClippingAndAntialiasing( const gfx::Transform& device_transform, - const RenderPassDrawQuad* quad, + const AggregatedRenderPassDrawQuad* quad, const gfx::QuadF* aa_quad, const gfx::QuadF* clip_region, gfx::QuadF* local_quad, @@ -3420,7 +3427,8 @@ } } -void GLRenderer::BindFramebufferToTexture(const RenderPassId render_pass_id) { +void GLRenderer::BindFramebufferToTexture( + const AggregatedRenderPassId render_pass_id) { tint_gl_composited_content_ = false; gl_->BindFramebuffer(GL_FRAMEBUFFER, offscreen_framebuffer_id_); @@ -3980,10 +3988,11 @@ } std::unique_ptr<GLRenderer::OverlayTexture> -GLRenderer::FindOrCreateOverlayTexture(const RenderPassId& render_pass_id, - int width, - int height, - const gfx::ColorSpace& color_space) { +GLRenderer::FindOrCreateOverlayTexture( + const AggregatedRenderPassId& render_pass_id, + int width, + int height, + const gfx::ColorSpace& color_space) { // First try to use a texture for the same RenderPassId, to keep things more // stable and less likely to clobber each others textures. auto match_with_id = [&](const std::unique_ptr<OverlayTexture>& overlay) { @@ -4165,11 +4174,11 @@ } void GLRenderer::UpdateRenderPassTextures( - const RenderPassList& render_passes_in_draw_order, - const base::flat_map<RenderPassId, RenderPassRequirements>& + const AggregatedRenderPassList& render_passes_in_draw_order, + const base::flat_map<AggregatedRenderPassId, RenderPassRequirements>& render_passes_in_frame) { // Collect RenderPass textures that should be deleted. - std::vector<RenderPassId> passes_to_delete; + std::vector<AggregatedRenderPassId> passes_to_delete; for (const auto& pair : render_pass_textures_) { auto render_pass_it = render_passes_in_frame.find(pair.first); if (render_pass_it == render_passes_in_frame.end()) { @@ -4209,7 +4218,7 @@ } void GLRenderer::AllocateRenderPassResourceIfNeeded( - const RenderPassId& render_pass_id, + const AggregatedRenderPassId& render_pass_id, const RenderPassRequirements& requirements) { auto contents_texture_it = render_pass_textures_.find(render_pass_id); if (contents_texture_it != render_pass_textures_.end()) { @@ -4226,13 +4235,13 @@ } bool GLRenderer::IsRenderPassResourceAllocated( - const RenderPassId& render_pass_id) const { + const AggregatedRenderPassId& render_pass_id) const { auto texture_it = render_pass_textures_.find(render_pass_id); return texture_it != render_pass_textures_.end(); } gfx::Size GLRenderer::GetRenderPassBackingPixelSize( - const RenderPassId& render_pass_id) { + const AggregatedRenderPassId& render_pass_id) { auto texture_it = render_pass_textures_.find(render_pass_id); DCHECK(texture_it != render_pass_textures_.end()); return texture_it->second.size();
diff --git a/components/viz/service/display/gl_renderer.h b/components/viz/service/display/gl_renderer.h index e5d03f4..81901243 100644 --- a/components/viz/service/display/gl_renderer.h +++ b/components/viz/service/display/gl_renderer.h
@@ -18,6 +18,7 @@ #include "base/macros.h" #include "build/build_config.h" #include "components/viz/common/gpu/context_cache_controller.h" +#include "components/viz/common/quads/aggregated_render_pass_draw_quad.h" #include "components/viz/common/quads/debug_border_draw_quad.h" #include "components/viz/common/quads/render_pass_draw_quad.h" #include "components/viz/common/quads/solid_color_draw_quad.h" @@ -97,18 +98,19 @@ bool CanPartialSwap() override; void UpdateRenderPassTextures( - const RenderPassList& render_passes_in_draw_order, - const base::flat_map<RenderPassId, RenderPassRequirements>& + const AggregatedRenderPassList& render_passes_in_draw_order, + const base::flat_map<AggregatedRenderPassId, RenderPassRequirements>& render_passes_in_frame) override; void AllocateRenderPassResourceIfNeeded( - const RenderPassId& render_pass_id, + const AggregatedRenderPassId& render_pass_id, const RenderPassRequirements& requirements) override; bool IsRenderPassResourceAllocated( - const RenderPassId& render_pass_id) const override; + const AggregatedRenderPassId& render_pass_id) const override; gfx::Size GetRenderPassBackingPixelSize( - const RenderPassId& render_pass_id) override; + const AggregatedRenderPassId& render_pass_id) override; void BindFramebufferToOutputSurface() override; - void BindFramebufferToTexture(const RenderPassId render_pass_id) override; + void BindFramebufferToTexture( + const AggregatedRenderPassId render_pass_id) override; void SetScissorTestRect(const gfx::Rect& scissor_rect) override; void PrepareSurfaceForPass(SurfaceInitializationMode initialization_mode, const gfx::Rect& render_pass_scissor) override; @@ -143,7 +145,7 @@ float edge[24]); static void SetupRenderPassQuadForClippingAndAntialiasing( const gfx::Transform& device_transform, - const RenderPassDrawQuad* quad, + const AggregatedRenderPassDrawQuad* quad, const gfx::QuadF* device_layer_quad, const gfx::QuadF* clip_region, gfx::QuadF* local_quad, @@ -167,7 +169,7 @@ OverlayTexture(); ~OverlayTexture(); - RenderPassId render_pass_id; + AggregatedRenderPassId render_pass_id; ScopedGpuMemoryBufferTexture texture; int frames_waiting_for_reuse = 0; }; @@ -248,9 +250,10 @@ const gfx::Transform& backdrop_filter_bounds_transform); // gl_renderer can bypass TileDrawQuads that fill the RenderPass - const DrawQuad* CanPassBeDrawnDirectly(const RenderPass* pass) override; + const DrawQuad* CanPassBeDrawnDirectly( + const AggregatedRenderPass* pass) override; - void DrawRenderPassQuad(const RenderPassDrawQuad* quadi, + void DrawRenderPassQuad(const AggregatedRenderPassDrawQuad* quadi, const gfx::QuadF* clip_region); void DrawRenderPassQuadInternal(DrawRenderPassDrawQuadParams* params); void DrawSolidColorQuad(const SolidColorDrawQuad* quad, @@ -344,7 +347,7 @@ std::unique_ptr<OverlayTexture>* overlay_texture, gfx::RectF* new_bounds); std::unique_ptr<OverlayTexture> FindOrCreateOverlayTexture( - const RenderPassId& render_pass_id, + const AggregatedRenderPassId& render_pass_id, int width, int height, const gfx::ColorSpace& color_space); @@ -368,10 +371,12 @@ ResourceFormat CurrentRenderPassResourceFormat() const; // A map from RenderPass id to the texture used to draw the RenderPass from. - base::flat_map<RenderPassId, ScopedRenderPassTexture> render_pass_textures_; + base::flat_map<AggregatedRenderPassId, ScopedRenderPassTexture> + render_pass_textures_; // A map from RenderPass id to backdrop filter cache texture. - base::flat_map<RenderPassId, sk_sp<SkImage>> render_pass_backdrop_textures_; + base::flat_map<AggregatedRenderPassId, sk_sp<SkImage>> + render_pass_backdrop_textures_; // OverlayTextures that are free to be used in the next frame. std::vector<std::unique_ptr<OverlayTexture>> available_overlay_textures_;
diff --git a/components/viz/service/display/gl_renderer_unittest.cc b/components/viz/service/display/gl_renderer_unittest.cc index 8ff3685..c2d68df 100644 --- a/components/viz/service/display/gl_renderer_unittest.cc +++ b/components/viz/service/display/gl_renderer_unittest.cc
@@ -92,7 +92,7 @@ // they are all cleaned up and completed before destroying the test. VizTestSuite::RunUntilIdle(); } - RenderPass* root_render_pass() { + AggregatedRenderPass* root_render_pass() { return render_passes_in_draw_order_.back().get(); } void DrawFrame(GLRenderer* renderer, @@ -113,7 +113,7 @@ } DebugRendererSettings debug_settings_; - RenderPassList render_passes_in_draw_order_; + AggregatedRenderPassList render_passes_in_draw_order_; }; #define EXPECT_PROGRAM_VALID(program_binding) \ @@ -251,10 +251,10 @@ void TestShadersWithOutputColorMatrix(const ProgramKey& program_key) { GLRenderer::DrawingFrame frame; - RenderPassList render_passes_in_draw_order; + AggregatedRenderPassList render_passes_in_draw_order; gfx::Size viewport_size(100, 100); - RenderPassId root_pass_id{1}; - RenderPass* root_pass = cc::AddRenderPass( + AggregatedRenderPassId root_pass_id{1}; + auto* root_pass = cc::AddRenderPass( &render_passes_in_draw_order, root_pass_id, gfx::Rect(viewport_size), gfx::Transform(), cc::FilterOperations()); root_pass->damage_rect = gfx::Rect(0, 0, 25, 25); @@ -721,9 +721,9 @@ output_surface_->set_has_external_stencil_test(true); - RenderPass* root_pass = cc::AddRenderPass( - &render_passes_in_draw_order_, RenderPassId{1}, gfx::Rect(viewport_size), - gfx::Transform(), cc::FilterOperations()); + auto* root_pass = cc::AddRenderPass( + &render_passes_in_draw_order_, AggregatedRenderPassId{1}, + gfx::Rect(viewport_size), gfx::Transform(), cc::FilterOperations()); root_pass->has_transparent_background = false; DrawFrame(renderer_.get(), viewport_size); @@ -738,9 +738,9 @@ // the correct precision qualifier. const gfx::Size viewport_size(1, 1); - RenderPass* root_pass = cc::AddRenderPass( - &render_passes_in_draw_order_, RenderPassId{1}, gfx::Rect(viewport_size), - gfx::Transform(), cc::FilterOperations()); + auto* root_pass = cc::AddRenderPass( + &render_passes_in_draw_order_, AggregatedRenderPassId{1}, + gfx::Rect(viewport_size), gfx::Transform(), cc::FilterOperations()); const bool needs_blending = false; const bool premultiplied_alpha = false; @@ -801,9 +801,9 @@ // the correct precision qualifier. const gfx::Size viewport_size(1, 1); - RenderPass* root_pass = cc::AddRenderPass( - &render_passes_in_draw_order_, RenderPassId{1}, gfx::Rect(viewport_size), - gfx::Transform(), cc::FilterOperations()); + auto* root_pass = cc::AddRenderPass( + &render_passes_in_draw_order_, AggregatedRenderPassId{1}, + gfx::Rect(viewport_size), gfx::Transform(), cc::FilterOperations()); const bool needs_blending = false; const bool premultiplied_alpha = false; @@ -861,8 +861,8 @@ protected: void RunTest(bool is_video_frame) { const gfx::Size viewport_size(10, 10); - RenderPass* root_pass = cc::AddRenderPass( - &render_passes_in_draw_order_, RenderPassId{1}, + auto* root_pass = cc::AddRenderPass( + &render_passes_in_draw_order_, AggregatedRenderPassId{1}, gfx::Rect(viewport_size), gfx::Transform(), cc::FilterOperations()); const bool needs_blending = false; @@ -1144,9 +1144,9 @@ renderer.SetVisible(true); gfx::Size viewport_size(1, 1); - RenderPass* root_pass = cc::AddRenderPass( - &render_passes_in_draw_order_, RenderPassId{1}, gfx::Rect(viewport_size), - gfx::Transform(), cc::FilterOperations()); + AggregatedRenderPass* root_pass = cc::AddRenderPass( + &render_passes_in_draw_order_, AggregatedRenderPassId{1}, + gfx::Rect(viewport_size), gfx::Transform(), cc::FilterOperations()); root_pass->has_transparent_background = false; // On DEBUG builds, render passes with opaque background clear to blue to @@ -1190,9 +1190,9 @@ renderer.SetVisible(true); gfx::Size viewport_size(1, 1); - RenderPass* root_pass = cc::AddRenderPass( - &render_passes_in_draw_order_, RenderPassId{1}, gfx::Rect(viewport_size), - gfx::Transform(), cc::FilterOperations()); + AggregatedRenderPass* root_pass = cc::AddRenderPass( + &render_passes_in_draw_order_, AggregatedRenderPassId{1}, + gfx::Rect(viewport_size), gfx::Transform(), cc::FilterOperations()); root_pass->has_transparent_background = true; EXPECT_CALL(*gl, DiscardFramebufferEXT(GL_FRAMEBUFFER, 1, _)).Times(1); @@ -1229,7 +1229,7 @@ renderer.SetVisible(true); gfx::Size viewport_size(1, 1); - cc::AddRenderPass(&render_passes_in_draw_order_, RenderPassId{1}, + cc::AddRenderPass(&render_passes_in_draw_order_, AggregatedRenderPassId{1}, gfx::Rect(viewport_size), gfx::Transform(), cc::FilterOperations()); @@ -1302,13 +1302,14 @@ // During initialization we are allowed to set any texture parameters. EXPECT_CALL(*gl, TexParameteri(_, _, _)).Times(AnyNumber()); - RenderPass* root_pass = cc::AddRenderPass( - &render_passes_in_draw_order_, RenderPassId{1}, gfx::Rect(100, 100), - gfx::Transform(), cc::FilterOperations()); + AggregatedRenderPass* root_pass = cc::AddRenderPass( + &render_passes_in_draw_order_, AggregatedRenderPassId{1}, + gfx::Rect(100, 100), gfx::Transform(), cc::FilterOperations()); gpu::SyncToken mailbox_sync_token; cc::AddOneOfEveryQuadTypeInDisplayResourceProvider( root_pass, resource_provider.get(), child_resource_provider.get(), - child_context_provider.get(), RenderPassId{0}, &mailbox_sync_token); + child_context_provider.get(), AggregatedRenderPassId{0}, + &mailbox_sync_token); EXPECT_EQ(12u, resource_provider->num_resources()); renderer.DecideRenderPassAllocationsForFrame(render_passes_in_draw_order_); @@ -1416,9 +1417,9 @@ renderer.Initialize(); renderer.SetVisible(true); - RenderPass* root_pass = cc::AddRenderPass( - &render_passes_in_draw_order_, RenderPassId{1}, gfx::Rect(viewport_size), - gfx::Transform(), cc::FilterOperations()); + AggregatedRenderPass* root_pass = cc::AddRenderPass( + &render_passes_in_draw_order_, AggregatedRenderPassId{1}, + gfx::Rect(viewport_size), gfx::Transform(), cc::FilterOperations()); root_pass->has_transparent_background = false; gfx::Rect rect(viewport_size); @@ -1492,14 +1493,14 @@ gfx::Size viewport_size(10, 10); - RenderPassId child_pass_id{2}; - RenderPass* child_pass = cc::AddRenderPass( + AggregatedRenderPassId child_pass_id{2}; + AggregatedRenderPass* child_pass = cc::AddRenderPass( &render_passes_in_draw_order_, child_pass_id, gfx::Rect(viewport_size), gfx::Transform(), cc::FilterOperations()); cc::AddQuad(child_pass, gfx::Rect(viewport_size), SK_ColorBLUE); - RenderPassId root_pass_id{1}; - RenderPass* root_pass = cc::AddRenderPass( + AggregatedRenderPassId root_pass_id{1}; + AggregatedRenderPass* root_pass = cc::AddRenderPass( &render_passes_in_draw_order_, root_pass_id, gfx::Rect(viewport_size), gfx::Transform(), cc::FilterOperations()); cc::AddQuad(root_pass, gfx::Rect(viewport_size), SK_ColorGREEN); @@ -1581,21 +1582,21 @@ gfx::Size viewport_size(100, 100); gfx::Rect grand_child_rect(25, 25); - RenderPassId grand_child_pass_id{3}; - RenderPass* grand_child_pass = cc::AddRenderPass( + AggregatedRenderPassId grand_child_pass_id{3}; + AggregatedRenderPass* grand_child_pass = cc::AddRenderPass( &render_passes_in_draw_order_, grand_child_pass_id, grand_child_rect, gfx::Transform(), cc::FilterOperations()); cc::AddClippedQuad(grand_child_pass, grand_child_rect, SK_ColorYELLOW); gfx::Rect child_rect(50, 50); - RenderPassId child_pass_id{2}; - RenderPass* child_pass = + AggregatedRenderPassId child_pass_id{2}; + AggregatedRenderPass* child_pass = cc::AddRenderPass(&render_passes_in_draw_order_, child_pass_id, child_rect, gfx::Transform(), cc::FilterOperations()); cc::AddQuad(child_pass, child_rect, SK_ColorBLUE); - RenderPassId root_pass_id{1}; - RenderPass* root_pass = cc::AddRenderPass( + AggregatedRenderPassId root_pass_id{1}; + AggregatedRenderPass* root_pass = cc::AddRenderPass( &render_passes_in_draw_order_, root_pass_id, gfx::Rect(viewport_size), gfx::Transform(), cc::FilterOperations()); cc::AddQuad(root_pass, gfx::Rect(viewport_size), SK_ColorGREEN); @@ -1657,8 +1658,8 @@ { // Draw one black frame to make sure the output surface is reshaped before // testes. - RenderPassId root_pass_id{1}; - RenderPass* root_pass = cc::AddRenderPass( + AggregatedRenderPassId root_pass_id{1}; + AggregatedRenderPass* root_pass = cc::AddRenderPass( &render_passes_in_draw_order_, root_pass_id, gfx::Rect(viewport_size), gfx::Transform(), cc::FilterOperations()); cc::AddQuad(root_pass, gfx::Rect(viewport_size), SK_ColorBLACK); @@ -1670,8 +1671,8 @@ } { // Partial frame, should not discard. - RenderPassId root_pass_id{1}; - RenderPass* root_pass = cc::AddRenderPass( + AggregatedRenderPassId root_pass_id{1}; + AggregatedRenderPass* root_pass = cc::AddRenderPass( &render_passes_in_draw_order_, root_pass_id, gfx::Rect(viewport_size), gfx::Transform(), cc::FilterOperations()); cc::AddQuad(root_pass, gfx::Rect(viewport_size), SK_ColorGREEN); @@ -1684,8 +1685,8 @@ } { // Full frame, should discard. - RenderPassId root_pass_id{1}; - RenderPass* root_pass = cc::AddRenderPass( + AggregatedRenderPassId root_pass_id{1}; + AggregatedRenderPass* root_pass = cc::AddRenderPass( &render_passes_in_draw_order_, root_pass_id, gfx::Rect(viewport_size), gfx::Transform(), cc::FilterOperations()); cc::AddQuad(root_pass, gfx::Rect(viewport_size), SK_ColorGREEN); @@ -1699,8 +1700,8 @@ { // Full frame, external scissor is set, should not discard. output_surface->set_has_external_stencil_test(true); - RenderPassId root_pass_id{1}; - RenderPass* root_pass = cc::AddRenderPass( + AggregatedRenderPassId root_pass_id{1}; + AggregatedRenderPass* root_pass = cc::AddRenderPass( &render_passes_in_draw_order_, root_pass_id, gfx::Rect(viewport_size), gfx::Transform(), cc::FilterOperations()); cc::AddQuad(root_pass, gfx::Rect(viewport_size), SK_ColorGREEN); @@ -1868,8 +1869,8 @@ gfx::Size viewport_size(100, 100); - RenderPassId root_pass_id{1}; - RenderPass* root_pass = cc::AddRenderPass( + AggregatedRenderPassId root_pass_id{1}; + AggregatedRenderPass* root_pass = cc::AddRenderPass( &render_passes_in_draw_order_, root_pass_id, gfx::Rect(viewport_size), gfx::Transform(), cc::FilterOperations()); cc::AddQuad(root_pass, gfx::Rect(viewport_size), SK_ColorGREEN); @@ -1916,8 +1917,8 @@ void DrawBlackFrame(const gfx::Size& viewport_size) { EXPECT_CALL(*gl_, DrawElements(_, _, _, _)).Times(1); - RenderPassId root_pass_id{1}; - RenderPass* root_pass = cc::AddRenderPass( + AggregatedRenderPassId root_pass_id{1}; + AggregatedRenderPass* root_pass = cc::AddRenderPass( &render_passes_in_draw_order_, root_pass_id, gfx::Rect(viewport_size), gfx::Transform(), cc::FilterOperations()); root_pass->damage_rect = gfx::Rect(viewport_size); @@ -1946,8 +1947,8 @@ DrawBlackFrame(viewport_size); EXPECT_CALL(*gl_, DrawElements(_, _, _, _)).Times(1); - RenderPassId root_pass_id{1}; - RenderPass* root_pass = cc::AddRenderPass( + AggregatedRenderPassId root_pass_id{1}; + AggregatedRenderPass* root_pass = cc::AddRenderPass( &render_passes_in_draw_order_, root_pass_id, gfx::Rect(viewport_size), gfx::Transform(), cc::FilterOperations()); root_pass->damage_rect = gfx::Rect(0, 0, 25, 25); @@ -1965,8 +1966,8 @@ // tests. DrawBlackFrame(viewport_size); - RenderPassId root_pass_id{1}; - RenderPass* root_pass = cc::AddRenderPass( + AggregatedRenderPassId root_pass_id{1}; + AggregatedRenderPass* root_pass = cc::AddRenderPass( &render_passes_in_draw_order_, root_pass_id, gfx::Rect(viewport_size), gfx::Transform(), cc::FilterOperations()); root_pass->damage_rect = gfx::Rect(0, 0, 10, 10); @@ -1990,7 +1991,7 @@ // tests. DrawBlackFrame(viewport_size); - RenderPassId root_pass_id{1}; + AggregatedRenderPassId root_pass_id{1}; auto* root_pass = cc::AddRenderPass(&render_passes_in_draw_order_, root_pass_id, gfx::Rect(viewport_size), @@ -2033,8 +2034,8 @@ gfx::Size viewport_size(100, 100); gfx::Rect quad_rect = gfx::Rect(20, 20, 20, 20); - RenderPassId root_pass_id{1}; - RenderPass* root_pass = cc::AddRenderPass( + AggregatedRenderPassId root_pass_id{1}; + AggregatedRenderPass* root_pass = cc::AddRenderPass( &render_passes_in_draw_order_, root_pass_id, gfx::Rect(viewport_size), gfx::Transform(), cc::FilterOperations()); cc::AddClippedQuad(root_pass, quad_rect, SK_ColorGREEN); @@ -2057,11 +2058,11 @@ gfx::Size viewport_size(60, 75); gfx::Rect child_rect(50, 50); - RenderPassId child_pass_id{2}; - RenderPass* child_pass; + AggregatedRenderPassId child_pass_id{2}; + AggregatedRenderPass* child_pass; - RenderPassId root_pass_id{1}; - RenderPass* root_pass; + AggregatedRenderPassId root_pass_id{1}; + AggregatedRenderPass* root_pass; auto transfer_resource = TransferableResource::MakeGL( gpu::Mailbox::Generate(), GL_LINEAR, GL_TEXTURE_2D, gpu::SyncToken(), @@ -2261,12 +2262,12 @@ // project incorrectly by the given transform, because of w<0 clipping. TEST_F(GLRendererShaderTest, DrawRenderPassQuadSkipsAAForClippingTransform) { gfx::Rect child_rect(50, 50); - RenderPassId child_pass_id{2}; - RenderPass* child_pass; + AggregatedRenderPassId child_pass_id{2}; + AggregatedRenderPass* child_pass; gfx::Size viewport_size(100, 100); - RenderPassId root_pass_id{1}; - RenderPass* root_pass; + AggregatedRenderPassId root_pass_id{1}; + AggregatedRenderPass* root_pass; gfx::Transform transform_preventing_aa; transform_preventing_aa.ApplyPerspectiveDepth(40.0); @@ -2302,8 +2303,8 @@ TEST_F(GLRendererShaderTest, DrawSolidColorShader) { gfx::Size viewport_size(30, 30); // Don't translate out of the viewport. gfx::Size quad_size(3, 3); - RenderPassId root_pass_id{1}; - RenderPass* root_pass; + AggregatedRenderPassId root_pass_id{1}; + AggregatedRenderPass* root_pass; gfx::Transform pixel_aligned_transform_causing_aa; pixel_aligned_transform_causing_aa.Translate(25.5f, 25.5f); @@ -2418,8 +2419,8 @@ bool transparent) { gfx::BufferFormat format = transparent ? gfx::BufferFormat::RGBA_8888 : gfx::BufferFormat::RGBX_8888; - RenderPassId render_pass_id{1}; - RenderPass* render_pass = cc::AddRenderPass( + AggregatedRenderPassId render_pass_id{1}; + AggregatedRenderPass* render_pass = cc::AddRenderPass( &render_passes_in_draw_order_, render_pass_id, gfx::Rect(viewport_size), gfx::Transform(), cc::FilterOperations()); cc::AddQuad(render_pass, gfx::Rect(viewport_size), SK_ColorGREEN); @@ -2471,7 +2472,7 @@ MOCK_METHOD5(Process, void(DisplayResourceProvider* resource_provider, const gfx::RectF& display_rect, - RenderPassList* render_passes, + AggregatedRenderPassList* render_passes, gfx::Rect* damage_rect, DCLayerOverlayList* dc_layer_overlays)); @@ -2500,9 +2501,9 @@ bool(DisplayResourceProvider* resource_provider, const gfx::RectF& display_rect, const QuadList& quad_list, - const base::flat_map<RenderPassId, cc::FilterOperations*>& + const base::flat_map<AggregatedRenderPassId, cc::FilterOperations*>& render_pass_filters, - const base::flat_map<RenderPassId, cc::FilterOperations*>& + const base::flat_map<AggregatedRenderPassId, cc::FilterOperations*>& render_pass_backdrop_filters, CALayerOverlayList* ca_layer_overlays)); }; @@ -2534,7 +2535,7 @@ const OverlayProcessorInterface::FilterOperationsMap& render_pass_backdrop_filters, DisplayResourceProvider* resource_provider, - RenderPassList* render_pass_list, + AggregatedRenderPassList* render_pass_list, const OverlayProcessorInterface::OutputSurfaceOverlayPlane* primary_surface, OverlayCandidateList* candidates, @@ -2643,9 +2644,9 @@ #endif gfx::Size viewport_size(1, 1); - RenderPass* root_pass = cc::AddRenderPass( - &render_passes_in_draw_order_, RenderPassId{1}, gfx::Rect(viewport_size), - gfx::Transform(), cc::FilterOperations()); + AggregatedRenderPass* root_pass = cc::AddRenderPass( + &render_passes_in_draw_order_, AggregatedRenderPassId{1}, + gfx::Rect(viewport_size), gfx::Transform(), cc::FilterOperations()); root_pass->has_transparent_background = false; root_pass->copy_requests.push_back(CopyOutputRequest::CreateStubForTesting()); @@ -2689,9 +2690,9 @@ #endif // Without a copy request Attempt() should be called once. - root_pass = cc::AddRenderPass(&render_passes_in_draw_order_, RenderPassId{1}, - gfx::Rect(viewport_size), gfx::Transform(), - cc::FilterOperations()); + root_pass = cc::AddRenderPass( + &render_passes_in_draw_order_, AggregatedRenderPassId{1}, + gfx::Rect(viewport_size), gfx::Transform(), cc::FilterOperations()); root_pass->has_transparent_background = false; overlay_quad = root_pass->CreateAndAppendDrawQuad<TextureDrawQuad>(); @@ -2831,9 +2832,9 @@ renderer.SetVisible(true); gfx::Size viewport_size(1, 1); - RenderPass* root_pass = cc::AddRenderPass( - &render_passes_in_draw_order_, RenderPassId{1}, gfx::Rect(viewport_size), - gfx::Transform(), cc::FilterOperations()); + AggregatedRenderPass* root_pass = cc::AddRenderPass( + &render_passes_in_draw_order_, AggregatedRenderPassId{1}, + gfx::Rect(viewport_size), gfx::Transform(), cc::FilterOperations()); root_pass->has_transparent_background = false; bool needs_blending = false; @@ -2927,13 +2928,13 @@ // Create a root and a child passes to test that the output color matrix is // registered only for the root pass. gfx::Size viewport_size(100, 100); - RenderPassId child_pass_id{2}; - RenderPass* child_pass = + AggregatedRenderPassId child_pass_id{2}; + AggregatedRenderPass* child_pass = cc::AddRenderPass(&render_passes_in_draw_order_, child_pass_id, gfx::Rect(viewport_size) + gfx::Vector2d(1, 2), gfx::Transform(), cc::FilterOperations()); - RenderPassId root_pass_id{1}; - RenderPass* root_pass = cc::AddRenderPass( + AggregatedRenderPassId root_pass_id{1}; + AggregatedRenderPass* root_pass = cc::AddRenderPass( &render_passes_in_draw_order_, root_pass_id, gfx::Rect(viewport_size), gfx::Transform(), cc::FilterOperations()); root_pass->damage_rect = gfx::Rect(0, 0, 25, 25); @@ -3005,16 +3006,16 @@ renderer.SetVisible(true); gfx::Size viewport_size(100, 100); - RenderPassId child_pass_id{2}; + AggregatedRenderPassId child_pass_id{2}; // Create a child pass with mipmap to verify that npot texture is enabled. - RenderPass* child_pass = + AggregatedRenderPass* child_pass = cc::AddRenderPass(&render_passes_in_draw_order_, child_pass_id, gfx::Rect(viewport_size) + gfx::Vector2d(1, 2), gfx::Transform(), cc::FilterOperations()); child_pass->generate_mipmap = true; - RenderPassId root_pass_id{1}; - RenderPass* root_pass = cc::AddRenderPass( + AggregatedRenderPassId root_pass_id{1}; + AggregatedRenderPass* root_pass = cc::AddRenderPass( &render_passes_in_draw_order_, root_pass_id, gfx::Rect(viewport_size), gfx::Transform(), cc::FilterOperations()); root_pass->damage_rect = gfx::Rect(0, 0, 25, 25); @@ -3088,8 +3089,8 @@ EXPECT_CALL(*gl, Scissor(0, 0, 100, 100)).Times(1); } - RenderPassId root_pass_id{1}; - RenderPass* root_pass = cc::AddRenderPass( + AggregatedRenderPassId root_pass_id{1}; + AggregatedRenderPass* root_pass = cc::AddRenderPass( &render_passes_in_draw_order_, root_pass_id, gfx::Rect(viewport_size), gfx::Transform(), cc::FilterOperations()); root_pass->damage_rect = gfx::Rect(viewport_size); @@ -3100,7 +3101,7 @@ Mock::VerifyAndClearExpectations(gl); for (int i = 0; i < 2; ++i) { - RenderPass* root_pass = cc::AddRenderPassWithDamage( + AggregatedRenderPass* root_pass = cc::AddRenderPassWithDamage( &render_passes_in_draw_order_, root_pass_id, root_pass_output_rect, root_pass_damage_rect, gfx::Transform(), cc::FilterOperations()); cc::AddQuad(root_pass, gfx::Rect(root_pass_output_rect), SK_ColorGREEN); @@ -3232,8 +3233,8 @@ gfx::Size viewport_size(100, 100); for (int i = 0; i < 65; i++) { - RenderPassId root_pass_id{1}; - RenderPass* root_pass = cc::AddRenderPass( + AggregatedRenderPassId root_pass_id{1}; + AggregatedRenderPass* root_pass = cc::AddRenderPass( &render_passes_in_draw_order_, root_pass_id, gfx::Rect(viewport_size), gfx::Transform(), cc::FilterOperations()); if (i == 0) { @@ -3350,7 +3351,7 @@ const OverlayProcessorInterface::FilterOperationsMap& render_pass_backdrop_filters, DisplayResourceProvider* resource_provider, - RenderPassList* render_pass_list, + AggregatedRenderPassList* render_pass_list, const PrimaryPlane* primary_plane, OverlayCandidateList* candidates, std::vector<gfx::Rect>* content_bounds) override { @@ -3421,7 +3422,7 @@ gfx::Size viewport_size(100, 100); { - RenderPassId root_pass_id{1}; + AggregatedRenderPassId root_pass_id{1}; cc::AddRenderPass(&render_passes_in_draw_order_, root_pass_id, gfx::Rect(viewport_size), gfx::Transform(), cc::FilterOperations()); @@ -3522,9 +3523,9 @@ } void DrawBlackFrame(const gfx::Size& viewport_size) { - RenderPassId root_pass_id{1}; + AggregatedRenderPassId root_pass_id{1}; - RenderPass* root_pass = cc::AddRenderPass( + AggregatedRenderPass* root_pass = cc::AddRenderPass( &render_passes_in_draw_order_, root_pass_id, gfx::Rect(viewport_size), gfx::Transform(), cc::FilterOperations()); cc::AddQuad(root_pass, gfx::Rect(viewport_size), SK_ColorBLACK); @@ -3559,14 +3560,14 @@ // This frame has a root pass with a RenderPassDrawQuad pointing to a child // pass that is at 1,2 to make it identifiable. - RenderPassId child_pass_id{2}; - RenderPassId root_pass_id{1}; + AggregatedRenderPassId child_pass_id{2}; + AggregatedRenderPassId root_pass_id{1}; { - RenderPass* child_pass = + AggregatedRenderPass* child_pass = cc::AddRenderPass(&render_passes_in_draw_order_, child_pass_id, gfx::Rect(viewport_size) + gfx::Vector2d(1, 2), gfx::Transform(), cc::FilterOperations()); - RenderPass* root_pass = cc::AddRenderPass( + AggregatedRenderPass* root_pass = cc::AddRenderPass( &render_passes_in_draw_order_, root_pass_id, gfx::Rect(viewport_size), gfx::Transform(), cc::FilterOperations()); cc::AddRenderPassQuad(root_pass, child_pass, 0, gfx::Transform(), @@ -3601,11 +3602,11 @@ // Frame number 2. Same inputs, except... { - RenderPass* child_pass = + AggregatedRenderPass* child_pass = cc::AddRenderPass(&render_passes_in_draw_order_, child_pass_id, gfx::Rect(viewport_size) + gfx::Vector2d(1, 2), gfx::Transform(), cc::FilterOperations()); - RenderPass* root_pass = cc::AddRenderPass( + AggregatedRenderPass* root_pass = cc::AddRenderPass( &render_passes_in_draw_order_, root_pass_id, gfx::Rect(viewport_size), gfx::Transform(), cc::FilterOperations()); cc::AddRenderPassQuad(root_pass, child_pass, 0, gfx::Transform(), @@ -3641,12 +3642,12 @@ DrawBlackFrame(viewport_size); for (size_t subtest = 0; subtest < 3; ++subtest) { - RenderPass* child_pass = cc::AddRenderPass( - &render_passes_in_draw_order_, RenderPassId{1}, gfx::Rect(250, 250), - gfx::Transform(), cc::FilterOperations()); + AggregatedRenderPass* child_pass = cc::AddRenderPass( + &render_passes_in_draw_order_, AggregatedRenderPassId{1}, + gfx::Rect(250, 250), gfx::Transform(), cc::FilterOperations()); - RenderPassId root_pass_id{1}; - RenderPass* root_pass = cc::AddRenderPass( + AggregatedRenderPassId root_pass_id{1}; + AggregatedRenderPass* root_pass = cc::AddRenderPass( &render_passes_in_draw_order_, root_pass_id, gfx::Rect(viewport_size), gfx::Transform(), cc::FilterOperations()); auto* quad = cc::AddRenderPassQuad(root_pass, child_pass); @@ -3704,14 +3705,14 @@ // pass that is at 1,2 to make it identifiable. // The child's size is 250x251, but it will be rounded up to a multiple of 64 // in order to promote easier texture reuse. See https://crbug.com/146070. - RenderPassId child_pass_id{2}; - RenderPassId root_pass_id{1}; + AggregatedRenderPassId child_pass_id{2}; + AggregatedRenderPassId root_pass_id{1}; { - RenderPass* child_pass = + AggregatedRenderPass* child_pass = cc::AddRenderPass(&render_passes_in_draw_order_, child_pass_id, gfx::Rect(250, 251) + gfx::Vector2d(1, 2), gfx::Transform(), cc::FilterOperations()); - RenderPass* root_pass = cc::AddRenderPass( + AggregatedRenderPass* root_pass = cc::AddRenderPass( &render_passes_in_draw_order_, root_pass_id, gfx::Rect(viewport_size), gfx::Transform(), cc::FilterOperations()); cc::AddRenderPassQuad(root_pass, child_pass, 0, gfx::Transform(), @@ -3762,11 +3763,11 @@ // that our texture reuse heuristics will reuse the texture if it is free. // For now, it is not. { - RenderPass* child_pass = + AggregatedRenderPass* child_pass = cc::AddRenderPass(&render_passes_in_draw_order_, child_pass_id, gfx::Rect(190, 191) + gfx::Vector2d(1, 2), gfx::Transform(), cc::FilterOperations()); - RenderPass* root_pass = cc::AddRenderPass( + AggregatedRenderPass* root_pass = cc::AddRenderPass( &render_passes_in_draw_order_, root_pass_id, gfx::Rect(viewport_size), gfx::Transform(), cc::FilterOperations()); cc::AddRenderPassQuad(root_pass, child_pass, 0, gfx::Transform(), @@ -3810,11 +3811,11 @@ // smaller than the next multiple of 64 from the released texture, but larger // than half of its size so that our texture reuse heuristics will kick in. { - RenderPass* child_pass = + AggregatedRenderPass* child_pass = cc::AddRenderPass(&render_passes_in_draw_order_, child_pass_id, gfx::Rect(190, 191) + gfx::Vector2d(1, 2), gfx::Transform(), cc::FilterOperations()); - RenderPass* root_pass = cc::AddRenderPass( + AggregatedRenderPass* root_pass = cc::AddRenderPass( &render_passes_in_draw_order_, root_pass_id, gfx::Rect(viewport_size), gfx::Transform(), cc::FilterOperations()); cc::AddRenderPassQuad(root_pass, child_pass, 0, gfx::Transform(), @@ -3859,14 +3860,14 @@ // pass that is at 1,2 to make it identifiable. // The child's size is 250x251, but it will be rounded up to a multiple of 64 // in order to promote easier texture reuse. See https://crbug.com/146070. - RenderPassId child_pass_id{2}; - RenderPassId root_pass_id{1}; + AggregatedRenderPassId child_pass_id{2}; + AggregatedRenderPassId root_pass_id{1}; { - RenderPass* child_pass = + AggregatedRenderPass* child_pass = cc::AddRenderPass(&render_passes_in_draw_order_, child_pass_id, gfx::Rect(250, 251) + gfx::Vector2d(1, 2), gfx::Transform(), cc::FilterOperations()); - RenderPass* root_pass = cc::AddRenderPass( + AggregatedRenderPass* root_pass = cc::AddRenderPass( &render_passes_in_draw_order_, root_pass_id, gfx::Rect(viewport_size), gfx::Transform(), cc::FilterOperations()); cc::AddRenderPassQuad(root_pass, child_pass, 0, gfx::Transform(), @@ -3915,11 +3916,11 @@ // Frame number 2. We change the size of the child RenderPass to be much // smaller. { - RenderPass* child_pass = + AggregatedRenderPass* child_pass = cc::AddRenderPass(&render_passes_in_draw_order_, child_pass_id, gfx::Rect(20, 21) + gfx::Vector2d(1, 2), gfx::Transform(), cc::FilterOperations()); - RenderPass* root_pass = cc::AddRenderPass( + AggregatedRenderPass* root_pass = cc::AddRenderPass( &render_passes_in_draw_order_, root_pass_id, gfx::Rect(viewport_size), gfx::Transform(), cc::FilterOperations()); cc::AddRenderPassQuad(root_pass, child_pass, 0, gfx::Transform(), @@ -3962,11 +3963,11 @@ // Frame number 3 looks just like frame number 2. The child RenderPass is // too small to reuse the old texture. { - RenderPass* child_pass = + AggregatedRenderPass* child_pass = cc::AddRenderPass(&render_passes_in_draw_order_, child_pass_id, gfx::Rect(20, 21) + gfx::Vector2d(1, 2), gfx::Transform(), cc::FilterOperations()); - RenderPass* root_pass = cc::AddRenderPass( + AggregatedRenderPass* root_pass = cc::AddRenderPass( &render_passes_in_draw_order_, root_pass_id, gfx::Rect(viewport_size), gfx::Transform(), cc::FilterOperations()); cc::AddRenderPassQuad(root_pass, child_pass, 0, gfx::Transform(), @@ -4005,14 +4006,14 @@ // This frame has a root pass with a RenderPassDrawQuad pointing to a child // pass that is at 1,2 to make it identifiable. - RenderPassId child_pass_id{2}; - RenderPassId root_pass_id{1}; + AggregatedRenderPassId child_pass_id{2}; + AggregatedRenderPassId root_pass_id{1}; { - RenderPass* child_pass = + AggregatedRenderPass* child_pass = cc::AddRenderPass(&render_passes_in_draw_order_, child_pass_id, gfx::Rect(100, 100) + gfx::Vector2d(1, 2), gfx::Transform(), cc::FilterOperations()); - RenderPass* root_pass = cc::AddRenderPass( + AggregatedRenderPass* root_pass = cc::AddRenderPass( &render_passes_in_draw_order_, root_pass_id, gfx::Rect(viewport_size), gfx::Transform(), cc::FilterOperations()); cc::AddRenderPassQuad(root_pass, child_pass, 0, gfx::Transform(), @@ -4050,11 +4051,11 @@ // returned yet. We use a different size so we can control which texture gets // reused later. { - RenderPass* child_pass = + AggregatedRenderPass* child_pass = cc::AddRenderPass(&render_passes_in_draw_order_, child_pass_id, gfx::Rect(200, 200) + gfx::Vector2d(1, 2), gfx::Transform(), cc::FilterOperations()); - RenderPass* root_pass = cc::AddRenderPass( + AggregatedRenderPass* root_pass = cc::AddRenderPass( &render_passes_in_draw_order_, root_pass_id, gfx::Rect(viewport_size), gfx::Transform(), cc::FilterOperations()); cc::AddRenderPassQuad(root_pass, child_pass, 0, gfx::Transform(), @@ -4096,11 +4097,11 @@ // Frame number 3 looks just like frame number 2. { - RenderPass* child_pass = + AggregatedRenderPass* child_pass = cc::AddRenderPass(&render_passes_in_draw_order_, child_pass_id, gfx::Rect(200, 200) + gfx::Vector2d(1, 2), gfx::Transform(), cc::FilterOperations()); - RenderPass* root_pass = cc::AddRenderPass( + AggregatedRenderPass* root_pass = cc::AddRenderPass( &render_passes_in_draw_order_, root_pass_id, gfx::Rect(viewport_size), gfx::Transform(), cc::FilterOperations()); cc::AddRenderPassQuad(root_pass, child_pass, 0, gfx::Transform(), @@ -4140,7 +4141,7 @@ // Each frame has a root pass with a RenderPassDrawQuad pointing to a child // pass. We generate a bunch of frames and swap them, each with a different // child RenderPass id, without getting any of the resources back from the OS. - RenderPassId root_pass_id{1}; + AggregatedRenderPassId root_pass_id{1}; // The number is at least 2 larger than the number of textures we expect to // reuse, so that we can leave one in the OS, and have 1 texture returned but @@ -4148,11 +4149,11 @@ const int kNumSendManyTextureIds = 7; uint32_t sent_texture_ids[kNumSendManyTextureIds]; for (int i = 0; i < kNumSendManyTextureIds; ++i) { - RenderPass* child_pass = - cc::AddRenderPass(&render_passes_in_draw_order_, RenderPassId{i + 2}, - gfx::Rect(250, 251) + gfx::Vector2d(1, 2), - gfx::Transform(), cc::FilterOperations()); - RenderPass* root_pass = cc::AddRenderPass( + AggregatedRenderPass* child_pass = cc::AddRenderPass( + &render_passes_in_draw_order_, AggregatedRenderPassId{i + 2}, + gfx::Rect(250, 251) + gfx::Vector2d(1, 2), gfx::Transform(), + cc::FilterOperations()); + AggregatedRenderPass* root_pass = cc::AddRenderPass( &render_passes_in_draw_order_, root_pass_id, gfx::Rect(viewport_size), gfx::Transform(), cc::FilterOperations()); cc::AddRenderPassQuad(root_pass, child_pass, 0, gfx::Transform(), @@ -4209,11 +4210,11 @@ for (int i = 0; i < kNumSendReusedTextures + 1; ++i) { // We use different RenderPass ids to ensure that the cache allows reuse // even if they don't match. - RenderPass* child_pass = - cc::AddRenderPass(&render_passes_in_draw_order_, RenderPassId{i + 100}, - gfx::Rect(250, 251) + gfx::Vector2d(1, 2), - gfx::Transform(), cc::FilterOperations()); - RenderPass* root_pass = cc::AddRenderPass( + AggregatedRenderPass* child_pass = cc::AddRenderPass( + &render_passes_in_draw_order_, AggregatedRenderPassId{i + 100}, + gfx::Rect(250, 251) + gfx::Vector2d(1, 2), gfx::Transform(), + cc::FilterOperations()); + AggregatedRenderPass* root_pass = cc::AddRenderPass( &render_passes_in_draw_order_, root_pass_id, gfx::Rect(viewport_size), gfx::Transform(), cc::FilterOperations()); cc::AddRenderPassQuad(root_pass, child_pass, 0, gfx::Transform(), @@ -4269,18 +4270,18 @@ // Each frame has a root pass with a RenderPassDrawQuad pointing to a child // pass. We generate a bunch of frames and swap them, each with a different // child RenderPass id, without getting any of the resources back from the OS. - RenderPassId child_pass_id{2}; - RenderPassId root_pass_id{1}; + AggregatedRenderPassId child_pass_id{2}; + AggregatedRenderPassId root_pass_id{1}; // We send a whole bunch of textures as overlays to the OS. const int kNumSendManyTextureIds = 7; uint32_t sent_texture_ids[kNumSendManyTextureIds]; for (int i = 0; i < kNumSendManyTextureIds; ++i) { - RenderPass* child_pass = - cc::AddRenderPass(&render_passes_in_draw_order_, RenderPassId{i + 2}, - gfx::Rect(250, 251) + gfx::Vector2d(1, 2), - gfx::Transform(), cc::FilterOperations()); - RenderPass* root_pass = cc::AddRenderPass( + AggregatedRenderPass* child_pass = cc::AddRenderPass( + &render_passes_in_draw_order_, AggregatedRenderPassId{i + 2}, + gfx::Rect(250, 251) + gfx::Vector2d(1, 2), gfx::Transform(), + cc::FilterOperations()); + AggregatedRenderPass* root_pass = cc::AddRenderPass( &render_passes_in_draw_order_, root_pass_id, gfx::Rect(viewport_size), gfx::Transform(), cc::FilterOperations()); cc::AddRenderPassQuad(root_pass, child_pass, 0, gfx::Transform(), @@ -4330,7 +4331,7 @@ // We generate a bunch of frames that don't use the cache, one less than the // number of textures returned. for (int i = 0; i < kNumSendManyTextureIds - 2; ++i) { - RenderPass* root_pass = cc::AddRenderPass( + AggregatedRenderPass* root_pass = cc::AddRenderPass( &render_passes_in_draw_order_, root_pass_id, gfx::Rect(viewport_size), gfx::Transform(), cc::FilterOperations()); cc::AddQuad(root_pass, gfx::Rect(100, 100), SK_ColorRED); @@ -4356,11 +4357,11 @@ // RenderPassDrawQuad and verify that it does not reuse a texture from the // (empty) cache. { - RenderPass* child_pass = + AggregatedRenderPass* child_pass = cc::AddRenderPass(&render_passes_in_draw_order_, child_pass_id, gfx::Rect(250, 251) + gfx::Vector2d(1, 2), gfx::Transform(), cc::FilterOperations()); - RenderPass* root_pass = cc::AddRenderPass( + AggregatedRenderPass* root_pass = cc::AddRenderPass( &render_passes_in_draw_order_, root_pass_id, gfx::Rect(viewport_size), gfx::Transform(), cc::FilterOperations()); cc::AddRenderPassQuad(root_pass, child_pass, 0, gfx::Transform(), @@ -4409,7 +4410,8 @@ FakeRendererGL::BindFramebufferToOutputSurface(); } - void BindFramebufferToTexture(const RenderPassId render_pass_id) override { + void BindFramebufferToTexture( + const AggregatedRenderPassId render_pass_id) override { ++bind_child_framebuffer_calls_; FakeRendererGL::BindFramebufferToTexture(render_pass_id); } @@ -4461,14 +4463,14 @@ gfx::Rect child_rect(10, 10); // First frame, the child and root RenderPass each have damage. - RenderPass* child_pass = - cc::AddRenderPass(&render_passes_in_draw_order_, RenderPassId{2}, - child_rect, gfx::Transform(), cc::FilterOperations()); + AggregatedRenderPass* child_pass = cc::AddRenderPass( + &render_passes_in_draw_order_, AggregatedRenderPassId{2}, child_rect, + gfx::Transform(), cc::FilterOperations()); cc::AddQuad(child_pass, child_rect, SK_ColorGREEN); child_pass->damage_rect = child_rect; - RenderPass* root_pass = cc::AddRenderPass( - &render_passes_in_draw_order_, RenderPassId{1}, + AggregatedRenderPass* root_pass = cc::AddRenderPass( + &render_passes_in_draw_order_, AggregatedRenderPassId{1}, gfx::Rect(viewport_size), gfx::Transform(), cc::FilterOperations()); cc::AddQuad(root_pass, gfx::Rect(viewport_size), SK_ColorRED); cc::AddRenderPassQuad(root_pass, child_pass, 0, gfx::Transform(), @@ -4491,16 +4493,16 @@ renderer.ResetBindCalls(); // Second frame, the child RenderPass has no damage in it. - child_pass = - cc::AddRenderPass(&render_passes_in_draw_order_, RenderPassId{2}, - child_rect, gfx::Transform(), cc::FilterOperations()); + child_pass = cc::AddRenderPass(&render_passes_in_draw_order_, + AggregatedRenderPassId{2}, child_rect, + gfx::Transform(), cc::FilterOperations()); cc::AddQuad(child_pass, child_rect, SK_ColorGREEN); child_pass->damage_rect = gfx::Rect(); // Root RenderPass has some damage that doesn't intersect the child. - root_pass = cc::AddRenderPass(&render_passes_in_draw_order_, - RenderPassId{1}, gfx::Rect(viewport_size), - gfx::Transform(), cc::FilterOperations()); + root_pass = cc::AddRenderPass( + &render_passes_in_draw_order_, AggregatedRenderPassId{1}, + gfx::Rect(viewport_size), gfx::Transform(), cc::FilterOperations()); cc::AddQuad(root_pass, gfx::Rect(viewport_size), SK_ColorRED); cc::AddRenderPassQuad(root_pass, child_pass, 0, gfx::Transform(), SkBlendMode::kSrcOver); @@ -4600,9 +4602,9 @@ TEST_F(GLRendererWithGpuFenceTest, GpuFenceIdIsUsedWithRootRenderPassOverlay) { gfx::Size viewport_size(100, 100); - RenderPass* root_pass = cc::AddRenderPass( - &render_passes_in_draw_order_, RenderPassId{1}, gfx::Rect(viewport_size), - gfx::Transform(), cc::FilterOperations()); + AggregatedRenderPass* root_pass = cc::AddRenderPass( + &render_passes_in_draw_order_, AggregatedRenderPassId{1}, + gfx::Rect(viewport_size), gfx::Transform(), cc::FilterOperations()); root_pass->has_transparent_background = false; EXPECT_CALL(overlay_scheduler_, @@ -4620,9 +4622,9 @@ GTEST_SKIP(); #endif gfx::Size viewport_size(100, 100); - RenderPass* root_pass = cc::AddRenderPass( - &render_passes_in_draw_order_, RenderPassId{1}, gfx::Rect(viewport_size), - gfx::Transform(), cc::FilterOperations()); + AggregatedRenderPass* root_pass = cc::AddRenderPass( + &render_passes_in_draw_order_, AggregatedRenderPassId{1}, + gfx::Rect(viewport_size), gfx::Transform(), cc::FilterOperations()); root_pass->has_transparent_background = false; bool needs_blending = false;
diff --git a/components/viz/service/display/overlay_ca_unittest.cc b/components/viz/service/display/overlay_ca_unittest.cc index f147f79..64b166a 100644 --- a/components/viz/service/display/overlay_ca_unittest.cc +++ b/components/viz/service/display/overlay_ca_unittest.cc
@@ -17,6 +17,8 @@ #include "cc/test/geometry_test_utils.h" #include "cc/test/resource_provider_test_utils.h" #include "components/viz/client/client_resource_provider.h" +#include "components/viz/common/quads/aggregated_render_pass.h" +#include "components/viz/common/quads/aggregated_render_pass_draw_quad.h" #include "components/viz/common/quads/render_pass.h" #include "components/viz/common/quads/render_pass_draw_quad.h" #include "components/viz/common/quads/solid_color_draw_quad.h" @@ -103,10 +105,10 @@ true /* enable_render_pass */) {} }; -std::unique_ptr<RenderPass> CreateRenderPass() { - RenderPassId render_pass_id{1}; +std::unique_ptr<AggregatedRenderPass> CreateRenderPass() { + AggregatedRenderPassId render_pass_id{1}; - std::unique_ptr<RenderPass> pass = RenderPass::Create(); + auto pass = std::make_unique<AggregatedRenderPass>(); pass->SetNew(render_pass_id, kRenderPassOutputRect, kRenderPassOutputRect, gfx::Transform()); @@ -164,7 +166,7 @@ ClientResourceProvider* child_resource_provider, ContextProvider* child_context_provider, const SharedQuadState* shared_quad_state, - RenderPass* render_pass, + AggregatedRenderPass* render_pass, const gfx::Rect& rect, gfx::ProtectedVideoType protected_video_type) { bool needs_blending = false; @@ -194,7 +196,7 @@ ClientResourceProvider* child_resource_provider, ContextProvider* child_context_provider, const SharedQuadState* shared_quad_state, - RenderPass* render_pass, + AggregatedRenderPass* render_pass, const gfx::Rect& rect) { return CreateCandidateQuadAt( parent_resource_provider, child_resource_provider, child_context_provider, @@ -206,7 +208,7 @@ ClientResourceProvider* child_resource_provider, ContextProvider* child_context_provider, const SharedQuadState* shared_quad_state, - RenderPass* render_pass) { + AggregatedRenderPass* render_pass) { return CreateCandidateQuadAt( parent_resource_provider, child_resource_provider, child_context_provider, shared_quad_state, render_pass, render_pass->output_rect); @@ -260,7 +262,7 @@ }; TEST_F(CALayerOverlayTest, AllowNonAxisAlignedTransform) { - std::unique_ptr<RenderPass> pass = CreateRenderPass(); + auto pass = CreateRenderPass(); CreateFullscreenCandidateQuad( resource_provider_.get(), child_resource_provider_.get(), child_provider_.get(), pass->shared_quad_state_list.back(), pass.get()); @@ -271,7 +273,7 @@ CALayerOverlayList ca_layer_list; OverlayProcessorInterface::FilterOperationsMap render_pass_filters; OverlayProcessorInterface::FilterOperationsMap render_pass_backdrop_filters; - RenderPassList pass_list; + AggregatedRenderPassList pass_list; pass_list.push_back(std::move(pass)); overlay_processor_->ProcessForOverlays( resource_provider_.get(), &pass_list, GetIdentityColorMatrix(), @@ -285,7 +287,7 @@ } TEST_F(CALayerOverlayTest, ThreeDTransform) { - std::unique_ptr<RenderPass> pass = CreateRenderPass(); + auto pass = CreateRenderPass(); CreateFullscreenCandidateQuad( resource_provider_.get(), child_resource_provider_.get(), child_provider_.get(), pass->shared_quad_state_list.back(), pass.get()); @@ -295,7 +297,7 @@ CALayerOverlayList ca_layer_list; OverlayProcessorInterface::FilterOperationsMap render_pass_filters; OverlayProcessorInterface::FilterOperationsMap render_pass_backdrop_filters; - RenderPassList pass_list; + AggregatedRenderPassList pass_list; pass_list.push_back(std::move(pass)); overlay_processor_->ProcessForOverlays( resource_provider_.get(), &pass_list, GetIdentityColorMatrix(), @@ -312,7 +314,7 @@ } TEST_F(CALayerOverlayTest, AllowContainingClip) { - std::unique_ptr<RenderPass> pass = CreateRenderPass(); + auto pass = CreateRenderPass(); CreateFullscreenCandidateQuad( resource_provider_.get(), child_resource_provider_.get(), child_provider_.get(), pass->shared_quad_state_list.back(), pass.get()); @@ -323,7 +325,7 @@ CALayerOverlayList ca_layer_list; OverlayProcessorInterface::FilterOperationsMap render_pass_filters; OverlayProcessorInterface::FilterOperationsMap render_pass_backdrop_filters; - RenderPassList pass_list; + AggregatedRenderPassList pass_list; pass_list.push_back(std::move(pass)); overlay_processor_->ProcessForOverlays( resource_provider_.get(), &pass_list, GetIdentityColorMatrix(), @@ -335,7 +337,7 @@ } TEST_F(CALayerOverlayTest, NontrivialClip) { - std::unique_ptr<RenderPass> pass = CreateRenderPass(); + auto pass = CreateRenderPass(); CreateFullscreenCandidateQuad( resource_provider_.get(), child_resource_provider_.get(), child_provider_.get(), pass->shared_quad_state_list.back(), pass.get()); @@ -346,7 +348,7 @@ CALayerOverlayList ca_layer_list; OverlayProcessorInterface::FilterOperationsMap render_pass_filters; OverlayProcessorInterface::FilterOperationsMap render_pass_backdrop_filters; - RenderPassList pass_list; + AggregatedRenderPassList pass_list; pass_list.push_back(std::move(pass)); overlay_processor_->ProcessForOverlays( resource_provider_.get(), &pass_list, GetIdentityColorMatrix(), @@ -361,7 +363,7 @@ } TEST_F(CALayerOverlayTest, SkipTransparent) { - std::unique_ptr<RenderPass> pass = CreateRenderPass(); + auto pass = CreateRenderPass(); CreateFullscreenCandidateQuad( resource_provider_.get(), child_resource_provider_.get(), child_provider_.get(), pass->shared_quad_state_list.back(), pass.get()); @@ -371,7 +373,7 @@ CALayerOverlayList ca_layer_list; OverlayProcessorInterface::FilterOperationsMap render_pass_filters; OverlayProcessorInterface::FilterOperationsMap render_pass_backdrop_filters; - RenderPassList pass_list; + AggregatedRenderPassList pass_list; pass_list.push_back(std::move(pass)); overlay_processor_->ProcessForOverlays( resource_provider_.get(), &pass_list, GetIdentityColorMatrix(), @@ -383,7 +385,7 @@ } TEST_F(CALayerOverlayTest, SkipNonVisible) { - std::unique_ptr<RenderPass> pass = CreateRenderPass(); + auto pass = CreateRenderPass(); CreateFullscreenCandidateQuad( resource_provider_.get(), child_resource_provider_.get(), child_provider_.get(), pass->shared_quad_state_list.back(), pass.get()); @@ -393,7 +395,7 @@ CALayerOverlayList ca_layer_list; OverlayProcessorInterface::FilterOperationsMap render_pass_filters; OverlayProcessorInterface::FilterOperationsMap render_pass_backdrop_filters; - RenderPassList pass_list; + AggregatedRenderPassList pass_list; pass_list.push_back(std::move(pass)); overlay_processor_->ProcessForOverlays( resource_provider_.get(), &pass_list, GetIdentityColorMatrix(), @@ -410,8 +412,8 @@ CALayerOverlayTest::SetUp(); pass_list_.push_back(CreateRenderPass()); pass_ = pass_list_.back().get(); - quad_ = pass_->CreateAndAppendDrawQuad<RenderPassDrawQuad>(); - render_pass_id_ = RenderPassId{3}; + quad_ = pass_->CreateAndAppendDrawQuad<AggregatedRenderPassDrawQuad>(); + render_pass_id_ = AggregatedRenderPassId{3}; } void ProcessForOverlays() { @@ -420,10 +422,10 @@ render_pass_filters_, render_pass_backdrop_filters_, nullptr, &ca_layer_list_, &damage_rect_, &content_bounds_); } - RenderPassList pass_list_; - RenderPass* pass_; - RenderPassDrawQuad* quad_; - RenderPassId render_pass_id_; + AggregatedRenderPassList pass_list_; + AggregatedRenderPass* pass_; + AggregatedRenderPassDrawQuad* quad_; + AggregatedRenderPassId render_pass_id_; cc::FilterOperations filters_; cc::FilterOperations backdrop_filters_; OverlayProcessorInterface::FilterOperationsMap render_pass_filters_; @@ -527,7 +529,7 @@ kOverlayRect, render_pass_id_, 2, gfx::RectF(), gfx::Size(), gfx::Vector2dF(1, 1), gfx::PointF(), gfx::RectF(), false, 1.0f); for (int i = 1; i < count; ++i) { - auto* quad = pass_->CreateAndAppendDrawQuad<RenderPassDrawQuad>(); + auto* quad = pass_->CreateAndAppendDrawQuad<AggregatedRenderPassDrawQuad>(); quad->SetNew(pass_->shared_quad_state_list.back(), kOverlayRect, kOverlayRect, render_pass_id_, 2, gfx::RectF(), gfx::Size(), gfx::Vector2dF(1, 1), gfx::PointF(), gfx::RectF(), false,
diff --git a/components/viz/service/display/overlay_candidate.cc b/components/viz/service/display/overlay_candidate.cc index 03c45ee..9bc7a2c 100644 --- a/components/viz/service/display/overlay_candidate.cc +++ b/components/viz/service/display/overlay_candidate.cc
@@ -9,7 +9,7 @@ #include "build/build_config.h" #include "cc/base/math_util.h" -#include "components/viz/common/quads/render_pass_draw_quad.h" +#include "components/viz/common/quads/aggregated_render_pass_draw_quad.h" #include "components/viz/common/quads/solid_color_draw_quad.h" #include "components/viz/common/quads/stream_video_draw_quad.h" #include "components/viz/common/quads/texture_draw_quad.h" @@ -200,16 +200,16 @@ const OverlayCandidate& candidate, QuadList::ConstIterator quad_list_begin, QuadList::ConstIterator quad_list_end, - const base::flat_map<RenderPassId, cc::FilterOperations*>& + const base::flat_map<AggregatedRenderPassId, cc::FilterOperations*>& render_pass_backdrop_filters) { for (auto overlap_iter = quad_list_begin; overlap_iter != quad_list_end; ++overlap_iter) { - if (overlap_iter->material == DrawQuad::Material::kRenderPass) { + if (overlap_iter->material == DrawQuad::Material::kAggregatedRenderPass) { gfx::RectF overlap_rect = cc::MathUtil::MapClippedRect( overlap_iter->shared_quad_state->quad_to_target_transform, gfx::RectF(overlap_iter->rect)); - const RenderPassDrawQuad* render_pass_draw_quad = - RenderPassDrawQuad::MaterialCast(*overlap_iter); + const auto* render_pass_draw_quad = + AggregatedRenderPassDrawQuad::MaterialCast(*overlap_iter); if (candidate.display_rect.Intersects(overlap_rect) && render_pass_backdrop_filters.count( render_pass_draw_quad->render_pass_id)) {
diff --git a/components/viz/service/display/overlay_candidate.h b/components/viz/service/display/overlay_candidate.h index 4c01bec8..801178b9 100644 --- a/components/viz/service/display/overlay_candidate.h +++ b/components/viz/service/display/overlay_candidate.h
@@ -10,7 +10,7 @@ #include "base/containers/flat_map.h" #include "build/build_config.h" -#include "components/viz/common/quads/render_pass.h" +#include "components/viz/common/quads/aggregated_render_pass.h" #include "components/viz/common/resources/resource_id.h" #include "components/viz/service/viz_service_export.h" #include "gpu/command_buffer/common/mailbox.h" @@ -55,7 +55,7 @@ const OverlayCandidate& candidate, QuadList::ConstIterator quad_list_begin, QuadList::ConstIterator quad_list_end, - const base::flat_map<RenderPassId, cc::FilterOperations*>& + const base::flat_map<AggregatedRenderPassId, cc::FilterOperations*>& render_pass_backdrop_filters); // Returns true if the |quad| cannot be displayed on the main plane. This is
diff --git a/components/viz/service/display/overlay_dc_unittest.cc b/components/viz/service/display/overlay_dc_unittest.cc index 987e8d7..c466c78 100644 --- a/components/viz/service/display/overlay_dc_unittest.cc +++ b/components/viz/service/display/overlay_dc_unittest.cc
@@ -17,8 +17,8 @@ #include "cc/test/resource_provider_test_utils.h" #include "components/viz/client/client_resource_provider.h" #include "components/viz/common/display/renderer_settings.h" -#include "components/viz/common/quads/render_pass.h" -#include "components/viz/common/quads/render_pass_draw_quad.h" +#include "components/viz/common/quads/aggregated_render_pass.h" +#include "components/viz/common/quads/aggregated_render_pass_draw_quad.h" #include "components/viz/common/quads/solid_color_draw_quad.h" #include "components/viz/common/quads/stream_video_draw_quad.h" #include "components/viz/common/quads/texture_draw_quad.h" @@ -108,11 +108,11 @@ DebugRendererSettings debug_settings_; }; -std::unique_ptr<RenderPass> CreateRenderPass() { - RenderPassId render_pass_id{1}; +std::unique_ptr<AggregatedRenderPass> CreateRenderPass() { + AggregatedRenderPassId render_pass_id{1}; gfx::Rect output_rect(0, 0, 256, 256); - std::unique_ptr<RenderPass> pass = RenderPass::Create(); + auto pass = std::make_unique<AggregatedRenderPass>(); pass->SetNew(render_pass_id, output_rect, output_rect, gfx::Transform()); SharedQuadState* shared_state = pass->CreateAndAppendSharedQuadState(); @@ -167,7 +167,7 @@ SolidColorDrawQuad* CreateSolidColorQuadAt( const SharedQuadState* shared_quad_state, SkColor color, - RenderPass* render_pass, + AggregatedRenderPass* render_pass, const gfx::Rect& rect) { SolidColorDrawQuad* quad = render_pass->CreateAndAppendDrawQuad<SolidColorDrawQuad>(); @@ -177,7 +177,7 @@ void CreateOpaqueQuadAt(DisplayResourceProvider* resource_provider, const SharedQuadState* shared_quad_state, - RenderPass* render_pass, + AggregatedRenderPass* render_pass, const gfx::Rect& rect, SkColor color) { DCHECK_EQ(255u, SkColorGetA(color)); @@ -190,7 +190,7 @@ ClientResourceProvider* child_resource_provider, ContextProvider* child_context_provider, const SharedQuadState* shared_quad_state, - RenderPass* render_pass) { + AggregatedRenderPass* render_pass) { bool needs_blending = false; gfx::RectF tex_coord_rect(0, 0, 1, 1); gfx::Rect rect = render_pass->output_rect; @@ -264,7 +264,7 @@ base::test::ScopedFeatureList feature_list; feature_list.InitAndEnableFeature(features::kDirectCompositionUnderlays); { - std::unique_ptr<RenderPass> pass = CreateRenderPass(); + auto pass = CreateRenderPass(); SharedQuadState* first_shared_state = pass->shared_quad_state_list.back(); first_shared_state->occluding_damage_rect = gfx::Rect(1, 1, 10, 10); CreateOpaqueQuadAt(resource_provider_.get(), @@ -293,7 +293,7 @@ OverlayProcessorInterface::FilterOperationsMap render_pass_filters; OverlayProcessorInterface::FilterOperationsMap render_pass_backdrop_filters; damage_rect_ = gfx::Rect(1, 1, 10, 10); - RenderPassList pass_list; + AggregatedRenderPassList pass_list; pass_list.push_back(std::move(pass)); overlay_processor_->ProcessForOverlays( resource_provider_.get(), &pass_list, GetIdentityColorMatrix(), @@ -308,7 +308,7 @@ EXPECT_EQ(gfx::Rect(0, 0, 256, 256), damage_rect_); } { - std::unique_ptr<RenderPass> pass = CreateRenderPass(); + auto pass = CreateRenderPass(); SharedQuadState* first_shared_state = pass->shared_quad_state_list.back(); first_shared_state->occluding_damage_rect = gfx::Rect(1, 1, 10, 10); CreateOpaqueQuadAt(resource_provider_.get(), @@ -336,7 +336,7 @@ OverlayProcessorInterface::FilterOperationsMap render_pass_filters; OverlayProcessorInterface::FilterOperationsMap render_pass_backdrop_filters; damage_rect_ = gfx::Rect(1, 1, 10, 10); - RenderPassList pass_list; + AggregatedRenderPassList pass_list; pass_list.push_back(std::move(pass)); overlay_processor_->ProcessForOverlays( resource_provider_.get(), &pass_list, GetIdentityColorMatrix(), @@ -363,7 +363,7 @@ base::test::ScopedFeatureList feature_list; feature_list.InitAndEnableFeature(features::kDirectCompositionUnderlays); { - std::unique_ptr<RenderPass> pass = CreateRenderPass(); + auto pass = CreateRenderPass(); SharedQuadState* shared_quad_state = pass->shared_quad_state_list.back(); shared_quad_state->occluding_damage_rect = gfx::Rect(210, 210, 20, 20); // Occluding quad fully contained in video rect. @@ -386,7 +386,7 @@ OverlayProcessorInterface::FilterOperationsMap render_pass_backdrop_filters; // Damage rect fully outside video quad damage_rect_ = gfx::Rect(210, 210, 20, 20); - RenderPassList pass_list; + AggregatedRenderPassList pass_list; pass_list.push_back(std::move(pass)); overlay_processor_->ProcessForOverlays( resource_provider_.get(), &pass_list, GetIdentityColorMatrix(), @@ -399,7 +399,7 @@ EXPECT_EQ(gfx::Rect(0, 0, 230, 230), damage_rect_); } { - std::unique_ptr<RenderPass> pass = CreateRenderPass(); + auto pass = CreateRenderPass(); SharedQuadState* shared_quad_state = pass->shared_quad_state_list.back(); shared_quad_state->occluding_damage_rect = gfx::Rect(210, 210, 20, 20); // Occluding quad fully contained in video rect. @@ -422,7 +422,7 @@ OverlayProcessorInterface::FilterOperationsMap render_pass_backdrop_filters; // Damage rect fully outside video quad damage_rect_ = gfx::Rect(210, 210, 20, 20); - RenderPassList pass_list; + AggregatedRenderPassList pass_list; pass_list.push_back(std::move(pass)); overlay_processor_->ProcessForOverlays( resource_provider_.get(), &pass_list, GetIdentityColorMatrix(), @@ -438,7 +438,7 @@ TEST_F(DCLayerOverlayTest, DamageRect) { for (int i = 0; i < 2; i++) { - std::unique_ptr<RenderPass> pass = CreateRenderPass(); + auto pass = CreateRenderPass(); CreateFullscreenCandidateYUVVideoQuad( resource_provider_.get(), child_resource_provider_.get(), child_provider_.get(), pass->shared_quad_state_list.back(), pass.get()); @@ -448,7 +448,7 @@ OverlayProcessorInterface::FilterOperationsMap render_pass_filters; OverlayProcessorInterface::FilterOperationsMap render_pass_backdrop_filters; damage_rect_ = gfx::Rect(1, 1, 10, 10); - RenderPassList pass_list; + AggregatedRenderPassList pass_list; pass_list.push_back(std::move(pass)); overlay_processor_->ProcessForOverlays( resource_provider_.get(), &pass_list, GetIdentityColorMatrix(), @@ -476,7 +476,7 @@ // which will allow the damage rect to reflect just the changes in that // frame. for (size_t i = 0; i < 2; ++i) { - std::unique_ptr<RenderPass> pass = CreateRenderPass(); + auto pass = CreateRenderPass(); CreateOpaqueQuadAt(resource_provider_.get(), pass->shared_quad_state_list.back(), pass.get(), gfx::Rect(0, 2, 100, 100), SK_ColorWHITE); @@ -494,7 +494,7 @@ DCLayerOverlayList dc_layer_list; OverlayProcessorInterface::FilterOperationsMap render_pass_filters; OverlayProcessorInterface::FilterOperationsMap render_pass_backdrop_filters; - RenderPassList pass_list; + AggregatedRenderPassList pass_list; pass_list.push_back(std::move(pass)); damage_rect_ = gfx::Rect(1, 1, 10, 10); overlay_processor_->ProcessForOverlays( @@ -520,7 +520,7 @@ // which will allow the damage rect to reflect just the changes in that // frame. for (size_t i = 0; i < 2; ++i) { - std::unique_ptr<RenderPass> pass = CreateRenderPass(); + auto pass = CreateRenderPass(); CreateFullscreenCandidateYUVVideoQuad( resource_provider_.get(), child_resource_provider_.get(), child_provider_.get(), pass->shared_quad_state_list.back(), pass.get()); @@ -530,7 +530,7 @@ OverlayProcessorInterface::FilterOperationsMap render_pass_filters; OverlayProcessorInterface::FilterOperationsMap render_pass_backdrop_filters; damage_rect_ = gfx::Rect(1, 1, 10, 10); - RenderPassList pass_list; + AggregatedRenderPassList pass_list; pass_list.push_back(std::move(pass)); overlay_processor_->ProcessForOverlays( resource_provider_.get(), &pass_list, GetIdentityColorMatrix(), @@ -548,7 +548,7 @@ feature_list.InitAndEnableFeature(features::kDirectCompositionUnderlays); for (int i = 0; i < 3; i++) { - std::unique_ptr<RenderPass> pass = CreateRenderPass(); + auto pass = CreateRenderPass(); // Add a solid color quad on top SharedQuadState* shared_state_on_top = pass->shared_quad_state_list.back(); CreateSolidColorQuadAt(shared_state_on_top, SK_ColorRED, pass.get(), @@ -563,7 +563,7 @@ DCLayerOverlayList dc_layer_list; OverlayProcessorInterface::FilterOperationsMap render_pass_filters; OverlayProcessorInterface::FilterOperationsMap render_pass_backdrop_filters; - RenderPassList pass_list; + AggregatedRenderPassList pass_list; pass_list.push_back(std::move(pass)); gfx::Rect damage_rect_ = kOverlayRect; @@ -596,7 +596,7 @@ TEST_F(DCLayerOverlayTest, MultipleYUVOverlay) { base::test::ScopedFeatureList feature_list; { - std::unique_ptr<RenderPass> pass = CreateRenderPass(); + auto pass = CreateRenderPass(); pass->shared_quad_state_list.back(); CreateOpaqueQuadAt(resource_provider_.get(), pass->shared_quad_state_list.back(), pass.get(), @@ -620,7 +620,7 @@ OverlayProcessorInterface::FilterOperationsMap render_pass_filters; OverlayProcessorInterface::FilterOperationsMap render_pass_backdrop_filters; damage_rect_ = gfx::Rect(0, 0, 220, 220); - RenderPassList pass_list; + AggregatedRenderPassList pass_list; pass_list.push_back(std::move(pass)); overlay_processor_->ProcessForOverlays( @@ -635,7 +635,7 @@ // Check whether all 3 quads including two YUV quads are still in the render // pass - RenderPass* root_pass = pass_list.back().get(); + auto* root_pass = pass_list.back().get(); int quad_count = root_pass->quad_list.size(); EXPECT_EQ(3, quad_count); } @@ -647,12 +647,12 @@ // Draw 60 frames with overlay video quads. for (int i = 0; i < 60; i++) { - std::unique_ptr<RenderPass> pass = CreateRenderPass(); + auto pass = CreateRenderPass(); CreateFullscreenCandidateYUVVideoQuad( resource_provider_.get(), child_resource_provider_.get(), child_provider_.get(), pass->shared_quad_state_list.back(), pass.get()); - RenderPassList pass_list; + AggregatedRenderPassList pass_list; pass_list.push_back(std::move(pass)); DCLayerOverlayList dc_layer_list; @@ -685,7 +685,7 @@ // Draw 65 frames without overlays. for (int i = 0; i < 65; i++) { - std::unique_ptr<RenderPass> pass = CreateRenderPass(); + auto pass = CreateRenderPass(); damage_rect_ = gfx::Rect(1, 1, 10, 10); auto* quad = pass->CreateAndAppendDrawQuad<SolidColorDrawQuad>(); @@ -696,7 +696,7 @@ OverlayProcessorInterface::FilterOperationsMap render_pass_filters; OverlayProcessorInterface::FilterOperationsMap render_pass_backdrop_filters; - RenderPassList pass_list; + AggregatedRenderPassList pass_list; pass_list.push_back(std::move(pass)); damage_rect_ = gfx::Rect(1, 1, 10, 10);
diff --git a/components/viz/service/display/overlay_processor_interface.h b/components/viz/service/display/overlay_processor_interface.h index 8f99f4a..81383d0 100644 --- a/components/viz/service/display/overlay_processor_interface.h +++ b/components/viz/service/display/overlay_processor_interface.h
@@ -11,7 +11,7 @@ #include "base/containers/flat_map.h" #include "base/macros.h" #include "build/build_config.h" -#include "components/viz/common/quads/render_pass.h" +#include "components/viz/common/quads/aggregated_render_pass.h" #include "components/viz/service/display/output_surface.h" #include "components/viz/service/display/overlay_candidate.h" #include "components/viz/service/viz_service_export.h" @@ -52,7 +52,7 @@ #endif using FilterOperationsMap = - base::flat_map<RenderPassId, cc::FilterOperations*>; + base::flat_map<AggregatedRenderPassId, cc::FilterOperations*>; virtual bool DisableSplittingQuads() const; @@ -121,7 +121,7 @@ // or CALayers. This must be called every frame. virtual void ProcessForOverlays( DisplayResourceProvider* resource_provider, - RenderPassList* render_passes, + AggregatedRenderPassList* render_passes, const SkMatrix44& output_color_matrix, const FilterOperationsMap& render_pass_filters, const FilterOperationsMap& render_pass_backdrop_filters,
diff --git a/components/viz/service/display/overlay_processor_mac.cc b/components/viz/service/display/overlay_processor_mac.cc index 3a63b6e..9c18193 100644 --- a/components/viz/service/display/overlay_processor_mac.cc +++ b/components/viz/service/display/overlay_processor_mac.cc
@@ -57,7 +57,7 @@ void OverlayProcessorMac::ProcessForOverlays( DisplayResourceProvider* resource_provider, - RenderPassList* render_passes, + AggregatedRenderPassList* render_passes, const SkMatrix44& output_color_matrix, const OverlayProcessorInterface::FilterOperationsMap& render_pass_filters, const OverlayProcessorInterface::FilterOperationsMap& @@ -86,7 +86,7 @@ // SkiaRenderer yet. if (!enable_render_pass_) { for (auto* const quad : render_pass->quad_list) { - if (quad->material == DrawQuad::Material::kRenderPass) + if (quad->material == DrawQuad::Material::kAggregatedRenderPass) return; } }
diff --git a/components/viz/service/display/overlay_processor_mac.h b/components/viz/service/display/overlay_processor_mac.h index 17df7cb..1b46febf 100644 --- a/components/viz/service/display/overlay_processor_mac.h +++ b/components/viz/service/display/overlay_processor_mac.h
@@ -11,7 +11,7 @@ #include "base/containers/flat_map.h" #include "base/macros.h" #include "build/build_config.h" -#include "components/viz/common/quads/render_pass.h" +#include "components/viz/common/quads/aggregated_render_pass.h" #include "components/viz/service/display/ca_layer_overlay.h" #include "components/viz/service/display/overlay_candidate.h" #include "components/viz/service/display/overlay_processor_interface.h" @@ -50,7 +50,7 @@ // or CALayers. This must be called every frame. void ProcessForOverlays( DisplayResourceProvider* resource_provider, - RenderPassList* render_passes, + AggregatedRenderPassList* render_passes, const SkMatrix44& output_color_matrix, const FilterOperationsMap& render_pass_filters, const FilterOperationsMap& render_pass_backdrop_filters,
diff --git a/components/viz/service/display/overlay_processor_stub.h b/components/viz/service/display/overlay_processor_stub.h index 1dee051..88032cf 100644 --- a/components/viz/service/display/overlay_processor_stub.h +++ b/components/viz/service/display/overlay_processor_stub.h
@@ -5,6 +5,8 @@ #ifndef COMPONENTS_VIZ_SERVICE_DISPLAY_OVERLAY_PROCESSOR_STUB_H_ #define COMPONENTS_VIZ_SERVICE_DISPLAY_OVERLAY_PROCESSOR_STUB_H_ +#include <vector> + #include "components/viz/service/display/overlay_processor_interface.h" namespace viz { @@ -23,7 +25,7 @@ bool NeedsSurfaceOccludingDamageRect() const final; void ProcessForOverlays( DisplayResourceProvider* resource_provider, - RenderPassList* render_passes, + AggregatedRenderPassList* render_passes, const SkMatrix44& output_color_matrix, const FilterOperationsMap& render_pass_filters, const FilterOperationsMap& render_pass_backdrop_filters,
diff --git a/components/viz/service/display/overlay_processor_using_strategy.cc b/components/viz/service/display/overlay_processor_using_strategy.cc index 86b00f8..0ddc78f 100644 --- a/components/viz/service/display/overlay_processor_using_strategy.cc +++ b/components/viz/service/display/overlay_processor_using_strategy.cc
@@ -55,7 +55,7 @@ void OverlayProcessorUsingStrategy::ProcessForOverlays( DisplayResourceProvider* resource_provider, - RenderPassList* render_passes, + AggregatedRenderPassList* render_passes, const SkMatrix44& output_color_matrix, const OverlayProcessorInterface::FilterOperationsMap& render_pass_filters, const OverlayProcessorInterface::FilterOperationsMap& @@ -67,7 +67,7 @@ TRACE_EVENT0("viz", "OverlayProcessorUsingStrategy::ProcessForOverlays"); DCHECK(candidates->empty()); - RenderPass* render_pass = render_passes->back().get(); + auto* render_pass = render_passes->back().get(); // If we have any copy requests, we can't remove any quads for overlays or // CALayers because the framebuffer would be missing the removed quads' @@ -195,7 +195,7 @@ const OverlayProcessorInterface::FilterOperationsMap& render_pass_backdrop_filters, DisplayResourceProvider* resource_provider, - RenderPassList* render_pass_list, + AggregatedRenderPassList* render_pass_list, OverlayProcessorInterface::OutputSurfaceOverlayPlane* primary_plane, OverlayCandidateList* candidates, std::vector<gfx::Rect>* content_bounds) {
diff --git a/components/viz/service/display/overlay_processor_using_strategy.h b/components/viz/service/display/overlay_processor_using_strategy.h index faa34d1..f04b71d8 100644 --- a/components/viz/service/display/overlay_processor_using_strategy.h +++ b/components/viz/service/display/overlay_processor_using_strategy.h
@@ -11,7 +11,7 @@ #include "base/macros.h" #include "build/build_config.h" #include "components/viz/common/display/overlay_strategy.h" -#include "components/viz/common/quads/render_pass.h" +#include "components/viz/common/quads/aggregated_render_pass.h" #include "components/viz/service/display/output_surface.h" #include "components/viz/service/display/overlay_candidate.h" #include "components/viz/service/display/overlay_processor_interface.h" @@ -44,7 +44,7 @@ const SkMatrix44& output_color_matrix, const FilterOperationsMap& render_pass_backdrop_filters, DisplayResourceProvider* resource_provider, - RenderPassList* render_pass_list, + AggregatedRenderPassList* render_pass_list, const PrimaryPlane* primary_plane, OverlayCandidateList* candidates, std::vector<gfx::Rect>* content_bounds) = 0; @@ -77,7 +77,7 @@ // This must be called every frame. void ProcessForOverlays( DisplayResourceProvider* resource_provider, - RenderPassList* render_passes, + AggregatedRenderPassList* render_passes, const SkMatrix44& output_color_matrix, const FilterOperationsMap& render_pass_filters, const FilterOperationsMap& render_pass_backdrop_filters, @@ -138,7 +138,7 @@ const OverlayProcessorInterface::FilterOperationsMap& render_pass_backdrop_filters, DisplayResourceProvider* resource_provider, - RenderPassList* render_pass_list, + AggregatedRenderPassList* render_pass_list, OverlayProcessorInterface::OutputSurfaceOverlayPlane* primary_plane, OverlayCandidateList* candidates, std::vector<gfx::Rect>* content_bounds);
diff --git a/components/viz/service/display/overlay_processor_win.cc b/components/viz/service/display/overlay_processor_win.cc index 1b9c4e4..a425969 100644 --- a/components/viz/service/display/overlay_processor_win.cc +++ b/components/viz/service/display/overlay_processor_win.cc
@@ -48,7 +48,7 @@ void OverlayProcessorWin::ProcessForOverlays( DisplayResourceProvider* resource_provider, - RenderPassList* render_passes, + AggregatedRenderPassList* render_passes, const SkMatrix44& output_color_matrix, const OverlayProcessorInterface::FilterOperationsMap& render_pass_filters, const OverlayProcessorInterface::FilterOperationsMap& @@ -59,7 +59,7 @@ std::vector<gfx::Rect>* content_bounds) { TRACE_EVENT0("viz", "OverlayProcessorWin::ProcessForOverlays"); - RenderPass* root_render_pass = render_passes->back().get(); + auto* root_render_pass = render_passes->back().get(); // Skip overlay processing if we have copy request. if (!root_render_pass->copy_requests.empty()) { damage_rect->Union(dc_layer_overlay_processor_
diff --git a/components/viz/service/display/overlay_processor_win.h b/components/viz/service/display/overlay_processor_win.h index cead7d7..69570bf 100644 --- a/components/viz/service/display/overlay_processor_win.h +++ b/components/viz/service/display/overlay_processor_win.h
@@ -11,7 +11,7 @@ #include "base/containers/flat_map.h" #include "base/macros.h" #include "build/build_config.h" -#include "components/viz/common/quads/render_pass.h" +#include "components/viz/common/quads/aggregated_render_pass.h" #include "components/viz/service/display/dc_layer_overlay.h" #include "components/viz/service/display/output_surface.h" #include "components/viz/service/display/overlay_candidate.h" @@ -50,7 +50,7 @@ // or CALayers. This must be called every frame. void ProcessForOverlays( DisplayResourceProvider* resource_provider, - RenderPassList* render_passes, + AggregatedRenderPassList* render_passes, const SkMatrix44& output_color_matrix, const FilterOperationsMap& render_pass_filters, const FilterOperationsMap& render_pass_backdrop_filters,
diff --git a/components/viz/service/display/overlay_strategy_fullscreen.cc b/components/viz/service/display/overlay_strategy_fullscreen.cc index dd7f6ae..1d6e95a4 100644 --- a/components/viz/service/display/overlay_strategy_fullscreen.cc +++ b/components/viz/service/display/overlay_strategy_fullscreen.cc
@@ -24,13 +24,13 @@ const OverlayProcessorInterface::FilterOperationsMap& render_pass_backdrop_filters, DisplayResourceProvider* resource_provider, - RenderPassList* render_pass_list, + AggregatedRenderPassList* render_pass_list, const PrimaryPlane* primary_plane, OverlayCandidateList* candidate_list, std::vector<gfx::Rect>* content_bounds) { // Before we attempt an overlay strategy, the candidate list should be empty. DCHECK(candidate_list->empty()); - RenderPass* render_pass = render_pass_list->back().get(); + auto* render_pass = render_pass_list->back().get(); QuadList* quad_list = &render_pass->quad_list; // First quad of quad_list is the top most quad. auto front = quad_list->begin();
diff --git a/components/viz/service/display/overlay_strategy_fullscreen.h b/components/viz/service/display/overlay_strategy_fullscreen.h index 289537d..f9cc821 100644 --- a/components/viz/service/display/overlay_strategy_fullscreen.h +++ b/components/viz/service/display/overlay_strategy_fullscreen.h
@@ -24,7 +24,7 @@ const OverlayProcessorInterface::FilterOperationsMap& render_pass_backdrop_filters, DisplayResourceProvider* resource_provider, - RenderPassList* render_pass, + AggregatedRenderPassList* render_pass, const PrimaryPlane* primary_plane, OverlayCandidateList* candidate_list, std::vector<gfx::Rect>* content_bounds) override;
diff --git a/components/viz/service/display/overlay_strategy_single_on_top.cc b/components/viz/service/display/overlay_strategy_single_on_top.cc index e3da860f1..3904f26 100644 --- a/components/viz/service/display/overlay_strategy_single_on_top.cc +++ b/components/viz/service/display/overlay_strategy_single_on_top.cc
@@ -22,13 +22,13 @@ const OverlayProcessorInterface::FilterOperationsMap& render_pass_backdrop_filters, DisplayResourceProvider* resource_provider, - RenderPassList* render_pass_list, + AggregatedRenderPassList* render_pass_list, const PrimaryPlane* primary_plane, OverlayCandidateList* candidate_list, std::vector<gfx::Rect>* content_bounds) { // Before we attempt an overlay strategy, we shouldn't have a candidate. DCHECK(candidate_list->empty()); - RenderPass* render_pass = render_pass_list->back().get(); + auto* render_pass = render_pass_list->back().get(); QuadList* quad_list = &render_pass->quad_list; // Build a list of candidates with the associated quad. OverlayCandidate best_candidate;
diff --git a/components/viz/service/display/overlay_strategy_single_on_top.h b/components/viz/service/display/overlay_strategy_single_on_top.h index 8794520..1da1029 100644 --- a/components/viz/service/display/overlay_strategy_single_on_top.h +++ b/components/viz/service/display/overlay_strategy_single_on_top.h
@@ -23,7 +23,7 @@ const OverlayProcessorInterface::FilterOperationsMap& render_pass_backdrop_filters, DisplayResourceProvider* resource_provider, - RenderPassList* render_pass, + AggregatedRenderPassList* render_pass, const PrimaryPlane* primary_plane, OverlayCandidateList* candidate_list, std::vector<gfx::Rect>* content_bounds) override;
diff --git a/components/viz/service/display/overlay_strategy_underlay.cc b/components/viz/service/display/overlay_strategy_underlay.cc index 0fc6655c..ef87eb4 100644 --- a/components/viz/service/display/overlay_strategy_underlay.cc +++ b/components/viz/service/display/overlay_strategy_underlay.cc
@@ -24,13 +24,13 @@ const OverlayProcessorInterface::FilterOperationsMap& render_pass_backdrop_filters, DisplayResourceProvider* resource_provider, - RenderPassList* render_pass_list, + AggregatedRenderPassList* render_pass_list, const PrimaryPlane* primary_plane, OverlayCandidateList* candidate_list, std::vector<gfx::Rect>* content_bounds) { // Before we attempt an overlay strategy, the candidate list should be empty. DCHECK(candidate_list->empty()); - RenderPass* render_pass = render_pass_list->back().get(); + auto* render_pass = render_pass_list->back().get(); QuadList& quad_list = render_pass->quad_list; for (auto it = quad_list.begin(); it != quad_list.end(); ++it) {
diff --git a/components/viz/service/display/overlay_strategy_underlay.h b/components/viz/service/display/overlay_strategy_underlay.h index 8ce0668..9170eee 100644 --- a/components/viz/service/display/overlay_strategy_underlay.h +++ b/components/viz/service/display/overlay_strategy_underlay.h
@@ -38,7 +38,7 @@ const OverlayProcessorInterface::FilterOperationsMap& render_pass_backdrop_filters, DisplayResourceProvider* resource_provider, - RenderPassList* render_pass, + AggregatedRenderPassList* render_pass, const PrimaryPlane* primary_plane, OverlayCandidateList* candidate_list, std::vector<gfx::Rect>* content_bounds) override;
diff --git a/components/viz/service/display/overlay_strategy_underlay_cast.cc b/components/viz/service/display/overlay_strategy_underlay_cast.cc index 5436d5d..fa4880d 100644 --- a/components/viz/service/display/overlay_strategy_underlay_cast.cc +++ b/components/viz/service/display/overlay_strategy_underlay_cast.cc
@@ -50,13 +50,13 @@ const OverlayProcessorInterface::FilterOperationsMap& render_pass_backdrop_filters, DisplayResourceProvider* resource_provider, - RenderPassList* render_pass_list, + AggregatedRenderPassList* render_pass_list, const PrimaryPlane* primary_plane, OverlayCandidateList* candidate_list, std::vector<gfx::Rect>* content_bounds) { // Before we attempt an overlay strategy, the candidate list should be empty. DCHECK(candidate_list->empty()); - RenderPass* render_pass = render_pass_list->back().get(); + auto* render_pass = render_pass_list->back().get(); QuadList& quad_list = render_pass->quad_list; bool found_underlay = false; gfx::Rect content_rect;
diff --git a/components/viz/service/display/overlay_strategy_underlay_cast.h b/components/viz/service/display/overlay_strategy_underlay_cast.h index 4c48fab..6f810a3 100644 --- a/components/viz/service/display/overlay_strategy_underlay_cast.h +++ b/components/viz/service/display/overlay_strategy_underlay_cast.h
@@ -32,7 +32,7 @@ const OverlayProcessorInterface::FilterOperationsMap& render_pass_backdrop_filters, DisplayResourceProvider* resource_provider, - RenderPassList* render_pass, + AggregatedRenderPassList* render_pass, const PrimaryPlane* primary_plane, OverlayCandidateList* candidate_list, std::vector<gfx::Rect>* content_bounds) override;
diff --git a/components/viz/service/display/overlay_unittest.cc b/components/viz/service/display/overlay_unittest.cc index 80ba59e..b18a52a 100644 --- a/components/viz/service/display/overlay_unittest.cc +++ b/components/viz/service/display/overlay_unittest.cc
@@ -232,11 +232,11 @@ unsigned bind_framebuffer_count_ = 0; }; -std::unique_ptr<RenderPass> CreateRenderPass() { - RenderPassId render_pass_id{1}; +std::unique_ptr<AggregatedRenderPass> CreateRenderPass() { + AggregatedRenderPassId render_pass_id{1}; gfx::Rect output_rect(0, 0, 256, 256); - std::unique_ptr<RenderPass> pass = RenderPass::Create(); + auto pass = std::make_unique<AggregatedRenderPass>(); pass->SetNew(render_pass_id, output_rect, output_rect, gfx::Transform()); SharedQuadState* shared_state = pass->CreateAndAppendSharedQuadState(); @@ -244,12 +244,12 @@ return pass; } -std::unique_ptr<RenderPass> CreateRenderPassWithTransform( +std::unique_ptr<AggregatedRenderPass> CreateRenderPassWithTransform( const gfx::Transform& transform) { - RenderPassId render_pass_id{1}; + AggregatedRenderPassId render_pass_id{1}; gfx::Rect output_rect(0, 0, 256, 256); - std::unique_ptr<RenderPass> pass = RenderPass::Create(); + auto pass = std::make_unique<AggregatedRenderPass>(); pass->SetNew(render_pass_id, output_rect, output_rect, gfx::Transform()); SharedQuadState* shared_state = pass->CreateAndAppendSharedQuadState(); @@ -305,7 +305,7 @@ SolidColorDrawQuad* CreateSolidColorQuadAt( const SharedQuadState* shared_quad_state, SkColor color, - RenderPass* render_pass, + AggregatedRenderPass* render_pass, const gfx::Rect& rect) { SolidColorDrawQuad* quad = render_pass->CreateAndAppendDrawQuad<SolidColorDrawQuad>(); @@ -318,7 +318,7 @@ ClientResourceProvider* child_resource_provider, ContextProvider* child_context_provider, const SharedQuadState* shared_quad_state, - RenderPass* render_pass, + AggregatedRenderPass* render_pass, const gfx::Rect& rect, gfx::ProtectedVideoType protected_video_type) { bool needs_blending = false; @@ -348,7 +348,7 @@ ClientResourceProvider* child_resource_provider, ContextProvider* child_context_provider, const SharedQuadState* shared_quad_state, - RenderPass* render_pass, + AggregatedRenderPass* render_pass, const gfx::Rect& rect) { return CreateCandidateQuadAt( parent_resource_provider, child_resource_provider, child_context_provider, @@ -359,7 +359,7 @@ // expects. VideoHoleDrawQuad* CreateVideoHoleDrawQuadAt( const SharedQuadState* shared_quad_state, - RenderPass* render_pass, + AggregatedRenderPass* render_pass, const gfx::Rect& rect) { base::UnguessableToken overlay_plane_id = base::UnguessableToken::Create(); auto* overlay_quad = @@ -373,7 +373,7 @@ ClientResourceProvider* child_resource_provider, ContextProvider* child_context_provider, const SharedQuadState* shared_quad_state, - RenderPass* render_pass, + AggregatedRenderPass* render_pass, const gfx::Rect& rect) { bool needs_blending = true; bool premultiplied_alpha = false; @@ -402,7 +402,7 @@ ClientResourceProvider* child_resource_provider, ContextProvider* child_context_provider, const SharedQuadState* shared_quad_state, - RenderPass* render_pass) { + AggregatedRenderPass* render_pass) { return CreateCandidateQuadAt( parent_resource_provider, child_resource_provider, child_context_provider, shared_quad_state, render_pass, render_pass->output_rect); @@ -410,7 +410,7 @@ void CreateOpaqueQuadAt(DisplayResourceProvider* resource_provider, const SharedQuadState* shared_quad_state, - RenderPass* render_pass, + AggregatedRenderPass* render_pass, const gfx::Rect& rect) { auto* color_quad = render_pass->CreateAndAppendDrawQuad<SolidColorDrawQuad>(); color_quad->SetNew(shared_quad_state, rect, rect, SK_ColorBLACK, false); @@ -418,7 +418,7 @@ void CreateOpaqueQuadAt(DisplayResourceProvider* resource_provider, const SharedQuadState* shared_quad_state, - RenderPass* render_pass, + AggregatedRenderPass* render_pass, const gfx::Rect& rect, SkColor color) { DCHECK_EQ(255u, SkColorGetA(color)); @@ -428,17 +428,18 @@ void CreateFullscreenOpaqueQuad(DisplayResourceProvider* resource_provider, const SharedQuadState* shared_quad_state, - RenderPass* render_pass) { + AggregatedRenderPass* render_pass) { CreateOpaqueQuadAt(resource_provider, shared_quad_state, render_pass, render_pass->output_rect); } -static void CompareRenderPassLists(const RenderPassList& expected_list, - const RenderPassList& actual_list) { +static void CompareRenderPassLists( + const AggregatedRenderPassList& expected_list, + const AggregatedRenderPassList& actual_list) { EXPECT_EQ(expected_list.size(), actual_list.size()); for (size_t i = 0; i < actual_list.size(); ++i) { - RenderPass* expected = expected_list[i].get(); - RenderPass* actual = actual_list[i].get(); + AggregatedRenderPass* expected = expected_list[i].get(); + AggregatedRenderPass* actual = actual_list[i].get(); EXPECT_EQ(expected->id, actual->id); EXPECT_EQ(expected->output_rect, actual->output_rect); @@ -547,7 +548,7 @@ #if !defined(OS_APPLE) && !defined(OS_WIN) TEST_F(FullscreenOverlayTest, SuccessfulOverlay) { - std::unique_ptr<RenderPass> pass = CreateRenderPass(); + auto pass = CreateRenderPass(); gfx::Rect output_rect = pass->output_rect; TextureDrawQuad* original_quad = CreateFullscreenCandidateQuad( resource_provider_.get(), child_resource_provider_.get(), @@ -562,8 +563,8 @@ OverlayCandidateList candidate_list; OverlayProcessorInterface::FilterOperationsMap render_pass_filters; OverlayProcessorInterface::FilterOperationsMap render_pass_backdrop_filters; - RenderPassList pass_list; - RenderPass* main_pass = pass.get(); + AggregatedRenderPassList pass_list; + AggregatedRenderPass* main_pass = pass.get(); pass_list.push_back(std::move(pass)); overlay_processor_->ProcessForOverlays( @@ -585,7 +586,7 @@ } TEST_F(FullscreenOverlayTest, FailOnOutputColorMatrix) { - std::unique_ptr<RenderPass> pass = CreateRenderPass(); + auto pass = CreateRenderPass(); CreateFullscreenCandidateQuad( resource_provider_.get(), child_resource_provider_.get(), child_provider_.get(), pass->shared_quad_state_list.back(), pass.get()); @@ -598,8 +599,8 @@ OverlayCandidateList candidate_list; OverlayProcessorInterface::FilterOperationsMap render_pass_filters; OverlayProcessorInterface::FilterOperationsMap render_pass_backdrop_filters; - RenderPassList pass_list; - RenderPass* main_pass = pass.get(); + AggregatedRenderPassList pass_list; + AggregatedRenderPass* main_pass = pass.get(); pass_list.push_back(std::move(pass)); // This is passing a non-identity color matrix which will result in disabling @@ -615,7 +616,7 @@ } TEST_F(FullscreenOverlayTest, AlphaFail) { - std::unique_ptr<RenderPass> pass = CreateRenderPass(); + auto pass = CreateRenderPass(); CreateTransparentCandidateQuadAt( resource_provider_.get(), child_resource_provider_.get(), child_provider_.get(), pass->shared_quad_state_list.back(), pass.get(), @@ -625,8 +626,8 @@ OverlayCandidateList candidate_list; OverlayProcessorInterface::FilterOperationsMap render_pass_filters; OverlayProcessorInterface::FilterOperationsMap render_pass_backdrop_filters; - RenderPassList pass_list; - RenderPass* main_pass = pass.get(); + AggregatedRenderPassList pass_list; + AggregatedRenderPass* main_pass = pass.get(); pass_list.push_back(std::move(pass)); overlay_processor_->ProcessForOverlays( @@ -641,7 +642,7 @@ } TEST_F(FullscreenOverlayTest, SuccessfulResourceSizeInPixels) { - std::unique_ptr<RenderPass> pass = CreateRenderPass(); + auto pass = CreateRenderPass(); TextureDrawQuad* original_quad = CreateFullscreenCandidateQuad( resource_provider_.get(), child_resource_provider_.get(), child_provider_.get(), pass->shared_quad_state_list.back(), pass.get()); @@ -651,8 +652,8 @@ OverlayCandidateList candidate_list; OverlayProcessorInterface::FilterOperationsMap render_pass_filters; OverlayProcessorInterface::FilterOperationsMap render_pass_backdrop_filters; - RenderPassList pass_list; - RenderPass* main_pass = pass.get(); + AggregatedRenderPassList pass_list; + AggregatedRenderPass* main_pass = pass.get(); pass_list.push_back(std::move(pass)); overlay_processor_->ProcessForOverlays( @@ -666,7 +667,7 @@ } TEST_F(FullscreenOverlayTest, OnTopFail) { - std::unique_ptr<RenderPass> pass = CreateRenderPass(); + auto pass = CreateRenderPass(); // Add something in front of it. CreateOpaqueQuadAt(resource_provider_.get(), @@ -681,8 +682,8 @@ OverlayCandidateList candidate_list; OverlayProcessorInterface::FilterOperationsMap render_pass_filters; OverlayProcessorInterface::FilterOperationsMap render_pass_backdrop_filters; - RenderPassList pass_list; - RenderPass* main_pass = pass.get(); + AggregatedRenderPassList pass_list; + AggregatedRenderPass* main_pass = pass.get(); pass_list.push_back(std::move(pass)); overlay_processor_->ProcessForOverlays( @@ -696,7 +697,7 @@ } TEST_F(FullscreenOverlayTest, NotCoveringFullscreenFail) { - std::unique_ptr<RenderPass> pass = CreateRenderPass(); + auto pass = CreateRenderPass(); gfx::Rect inset_rect = pass->output_rect; inset_rect.Inset(0, 1, 0, 1); CreateCandidateQuadAt(resource_provider_.get(), @@ -708,8 +709,8 @@ OverlayCandidateList candidate_list; OverlayProcessorInterface::FilterOperationsMap render_pass_filters; OverlayProcessorInterface::FilterOperationsMap render_pass_backdrop_filters; - RenderPassList pass_list; - RenderPass* main_pass = pass.get(); + AggregatedRenderPassList pass_list; + AggregatedRenderPass* main_pass = pass.get(); pass_list.push_back(std::move(pass)); overlay_processor_->ProcessForOverlays( resource_provider_.get(), &pass_list, GetIdentityColorMatrix(), @@ -722,7 +723,7 @@ } TEST_F(FullscreenOverlayTest, RemoveFullscreenQuadFromQuadList) { - std::unique_ptr<RenderPass> pass = CreateRenderPass(); + auto pass = CreateRenderPass(); // Add something in front of it that is fully transparent. pass->shared_quad_state_list.back()->opacity = 0.0f; @@ -740,8 +741,8 @@ OverlayCandidateList candidate_list; OverlayProcessorInterface::FilterOperationsMap render_pass_filters; OverlayProcessorInterface::FilterOperationsMap render_pass_backdrop_filters; - RenderPassList pass_list; - RenderPass* main_pass = pass.get(); + AggregatedRenderPassList pass_list; + AggregatedRenderPass* main_pass = pass.get(); pass_list.push_back(std::move(pass)); overlay_processor_->ProcessForOverlays( resource_provider_.get(), &pass_list, GetIdentityColorMatrix(), @@ -756,7 +757,7 @@ } TEST_F(SingleOverlayOnTopTest, SuccessfulOverlay) { - std::unique_ptr<RenderPass> pass = CreateRenderPass(); + auto pass = CreateRenderPass(); TextureDrawQuad* original_quad = CreateFullscreenCandidateQuad( resource_provider_.get(), child_resource_provider_.get(), child_provider_.get(), pass->shared_quad_state_list.back(), pass.get()); @@ -772,8 +773,8 @@ OverlayCandidateList candidate_list; OverlayProcessorInterface::FilterOperationsMap render_pass_filters; OverlayProcessorInterface::FilterOperationsMap render_pass_backdrop_filters; - RenderPassList pass_list; - RenderPass* main_pass = pass.get(); + AggregatedRenderPassList pass_list; + AggregatedRenderPass* main_pass = pass.get(); pass_list.push_back(std::move(pass)); overlay_processor_->ProcessForOverlays( resource_provider_.get(), &pass_list, GetIdentityColorMatrix(), @@ -794,7 +795,7 @@ } TEST_F(SingleOverlayOnTopTest, PrioritizeBiggerOne) { - std::unique_ptr<RenderPass> pass = CreateRenderPass(); + auto pass = CreateRenderPass(); // Add a small quad. const auto kSmallCandidateRect = gfx::Rect(0, 0, 16, 16); CreateCandidateQuadAt(resource_provider_.get(), @@ -821,8 +822,8 @@ OverlayCandidateList candidate_list; OverlayProcessorInterface::FilterOperationsMap render_pass_filters; OverlayProcessorInterface::FilterOperationsMap render_pass_backdrop_filters; - RenderPassList pass_list; - RenderPass* main_pass = pass.get(); + AggregatedRenderPassList pass_list; + AggregatedRenderPass* main_pass = pass.get(); pass_list.push_back(std::move(pass)); overlay_processor_->ProcessForOverlays( resource_provider_.get(), &pass_list, GetIdentityColorMatrix(), @@ -839,7 +840,7 @@ } TEST_F(SingleOverlayOnTopTest, DamageRect) { - std::unique_ptr<RenderPass> pass = CreateRenderPass(); + auto pass = CreateRenderPass(); CreateFullscreenCandidateQuad( resource_provider_.get(), child_resource_provider_.get(), child_provider_.get(), pass->shared_quad_state_list.back(), pass.get()); @@ -856,7 +857,7 @@ OverlayProcessorInterface::FilterOperationsMap render_pass_filters; OverlayProcessorInterface::FilterOperationsMap render_pass_backdrop_filters; - RenderPassList pass_list; + AggregatedRenderPassList pass_list; pass_list.push_back(std::move(pass)); overlay_processor_->ProcessForOverlays( resource_provider_.get(), &pass_list, GetIdentityColorMatrix(), @@ -866,17 +867,17 @@ } TEST_F(SingleOverlayOnTopTest, NoCandidates) { - std::unique_ptr<RenderPass> pass = CreateRenderPass(); + auto pass = CreateRenderPass(); CreateFullscreenOpaqueQuad(resource_provider_.get(), pass->shared_quad_state_list.back(), pass.get()); CreateFullscreenOpaqueQuad(resource_provider_.get(), pass->shared_quad_state_list.back(), pass.get()); - RenderPassList pass_list; + AggregatedRenderPassList pass_list; pass_list.push_back(std::move(pass)); - RenderPassList original_pass_list; - RenderPass::CopyAll(pass_list, &original_pass_list); + AggregatedRenderPassList original_pass_list; + AggregatedRenderPass::CopyAllForTest(pass_list, &original_pass_list); OverlayCandidateList candidate_list; OverlayProcessorInterface::FilterOperationsMap render_pass_filters; @@ -891,7 +892,7 @@ } TEST_F(SingleOverlayOnTopTest, OccludedCandidates) { - std::unique_ptr<RenderPass> pass = CreateRenderPass(); + auto pass = CreateRenderPass(); CreateFullscreenOpaqueQuad(resource_provider_.get(), pass->shared_quad_state_list.back(), pass.get()); CreateFullscreenOpaqueQuad(resource_provider_.get(), @@ -901,11 +902,11 @@ resource_provider_.get(), child_resource_provider_.get(), child_provider_.get(), pass->shared_quad_state_list.back(), pass.get()); - RenderPassList pass_list; + AggregatedRenderPassList pass_list; pass_list.push_back(std::move(pass)); - RenderPassList original_pass_list; - RenderPass::CopyAll(pass_list, &original_pass_list); + AggregatedRenderPassList original_pass_list; + AggregatedRenderPass::CopyAllForTest(pass_list, &original_pass_list); OverlayCandidateList candidate_list; OverlayProcessorInterface::FilterOperationsMap render_pass_filters; @@ -921,7 +922,7 @@ // Test with multiple render passes. TEST_F(SingleOverlayOnTopTest, MultipleRenderPasses) { - std::unique_ptr<RenderPass> pass = CreateRenderPass(); + auto pass = CreateRenderPass(); CreateFullscreenCandidateQuad( resource_provider_.get(), child_resource_provider_.get(), child_provider_.get(), pass->shared_quad_state_list.back(), pass.get()); @@ -936,7 +937,7 @@ OverlayCandidateList candidate_list; OverlayProcessorInterface::FilterOperationsMap render_pass_filters; OverlayProcessorInterface::FilterOperationsMap render_pass_backdrop_filters; - RenderPassList pass_list; + AggregatedRenderPassList pass_list; pass_list.push_back(std::move(pass)); overlay_processor_->ProcessForOverlays( resource_provider_.get(), &pass_list, GetIdentityColorMatrix(), @@ -946,7 +947,7 @@ } TEST_F(SingleOverlayOnTopTest, AcceptBlending) { - std::unique_ptr<RenderPass> pass = CreateRenderPass(); + auto pass = CreateRenderPass(); TextureDrawQuad* quad = CreateFullscreenCandidateQuad( resource_provider_.get(), child_resource_provider_.get(), child_provider_.get(), pass->shared_quad_state_list.back(), pass.get()); @@ -956,7 +957,7 @@ OverlayProcessorInterface::FilterOperationsMap render_pass_filters; OverlayProcessorInterface::FilterOperationsMap render_pass_backdrop_filters; damage_rect_ = quad->rect; - RenderPassList pass_list; + AggregatedRenderPassList pass_list; pass_list.push_back(std::move(pass)); overlay_processor_->ProcessForOverlays( resource_provider_.get(), &pass_list, GetIdentityColorMatrix(), @@ -970,7 +971,7 @@ } TEST_F(SingleOverlayOnTopTest, RejectBackgroundColor) { - std::unique_ptr<RenderPass> pass = CreateRenderPass(); + auto pass = CreateRenderPass(); TextureDrawQuad* quad = CreateFullscreenCandidateQuad( resource_provider_.get(), child_resource_provider_.get(), child_provider_.get(), pass->shared_quad_state_list.back(), pass.get()); @@ -979,7 +980,7 @@ OverlayCandidateList candidate_list; OverlayProcessorInterface::FilterOperationsMap render_pass_filters; OverlayProcessorInterface::FilterOperationsMap render_pass_backdrop_filters; - RenderPassList pass_list; + AggregatedRenderPassList pass_list; pass_list.push_back(std::move(pass)); overlay_processor_->ProcessForOverlays( resource_provider_.get(), &pass_list, GetIdentityColorMatrix(), @@ -989,7 +990,7 @@ } TEST_F(SingleOverlayOnTopTest, AcceptBlackBackgroundColor) { - std::unique_ptr<RenderPass> pass = CreateRenderPass(); + auto pass = CreateRenderPass(); TextureDrawQuad* quad = CreateFullscreenCandidateQuad( resource_provider_.get(), child_resource_provider_.get(), child_provider_.get(), pass->shared_quad_state_list.back(), pass.get()); @@ -998,7 +999,7 @@ OverlayCandidateList candidate_list; OverlayProcessorInterface::FilterOperationsMap render_pass_filters; OverlayProcessorInterface::FilterOperationsMap render_pass_backdrop_filters; - RenderPassList pass_list; + AggregatedRenderPassList pass_list; pass_list.push_back(std::move(pass)); overlay_processor_->ProcessForOverlays( resource_provider_.get(), &pass_list, GetIdentityColorMatrix(), @@ -1008,7 +1009,7 @@ } TEST_F(SingleOverlayOnTopTest, RejectBlackBackgroundColorWithBlending) { - std::unique_ptr<RenderPass> pass = CreateRenderPass(); + auto pass = CreateRenderPass(); TextureDrawQuad* quad = CreateFullscreenCandidateQuad( resource_provider_.get(), child_resource_provider_.get(), child_provider_.get(), pass->shared_quad_state_list.back(), pass.get()); @@ -1018,7 +1019,7 @@ OverlayCandidateList candidate_list; OverlayProcessorInterface::FilterOperationsMap render_pass_filters; OverlayProcessorInterface::FilterOperationsMap render_pass_backdrop_filters; - RenderPassList pass_list; + AggregatedRenderPassList pass_list; pass_list.push_back(std::move(pass)); overlay_processor_->ProcessForOverlays( resource_provider_.get(), &pass_list, GetIdentityColorMatrix(), @@ -1028,7 +1029,7 @@ } TEST_F(SingleOverlayOnTopTest, RejectBlendMode) { - std::unique_ptr<RenderPass> pass = CreateRenderPass(); + auto pass = CreateRenderPass(); CreateFullscreenCandidateQuad( resource_provider_.get(), child_resource_provider_.get(), child_provider_.get(), pass->shared_quad_state_list.back(), pass.get()); @@ -1037,7 +1038,7 @@ OverlayCandidateList candidate_list; OverlayProcessorInterface::FilterOperationsMap render_pass_filters; OverlayProcessorInterface::FilterOperationsMap render_pass_backdrop_filters; - RenderPassList pass_list; + AggregatedRenderPassList pass_list; pass_list.push_back(std::move(pass)); overlay_processor_->ProcessForOverlays( resource_provider_.get(), &pass_list, GetIdentityColorMatrix(), @@ -1047,7 +1048,7 @@ } TEST_F(SingleOverlayOnTopTest, RejectOpacity) { - std::unique_ptr<RenderPass> pass = CreateRenderPass(); + auto pass = CreateRenderPass(); CreateFullscreenCandidateQuad( resource_provider_.get(), child_resource_provider_.get(), child_provider_.get(), pass->shared_quad_state_list.back(), pass.get()); @@ -1056,7 +1057,7 @@ OverlayCandidateList candidate_list; OverlayProcessorInterface::FilterOperationsMap render_pass_filters; OverlayProcessorInterface::FilterOperationsMap render_pass_backdrop_filters; - RenderPassList pass_list; + AggregatedRenderPassList pass_list; pass_list.push_back(std::move(pass)); overlay_processor_->ProcessForOverlays( resource_provider_.get(), &pass_list, GetIdentityColorMatrix(), @@ -1066,7 +1067,7 @@ } TEST_F(SingleOverlayOnTopTest, RejectNonAxisAlignedTransform) { - std::unique_ptr<RenderPass> pass = CreateRenderPass(); + auto pass = CreateRenderPass(); CreateFullscreenCandidateQuad( resource_provider_.get(), child_resource_provider_.get(), child_provider_.get(), pass->shared_quad_state_list.back(), pass.get()); @@ -1076,7 +1077,7 @@ OverlayCandidateList candidate_list; OverlayProcessorInterface::FilterOperationsMap render_pass_filters; OverlayProcessorInterface::FilterOperationsMap render_pass_backdrop_filters; - RenderPassList pass_list; + AggregatedRenderPassList pass_list; pass_list.push_back(std::move(pass)); overlay_processor_->ProcessForOverlays( resource_provider_.get(), &pass_list, GetIdentityColorMatrix(), @@ -1086,7 +1087,7 @@ } TEST_F(SingleOverlayOnTopTest, AllowClipped) { - std::unique_ptr<RenderPass> pass = CreateRenderPass(); + auto pass = CreateRenderPass(); CreateFullscreenCandidateQuad( resource_provider_.get(), child_resource_provider_.get(), child_provider_.get(), pass->shared_quad_state_list.back(), pass.get()); @@ -1096,7 +1097,7 @@ OverlayCandidateList candidate_list; OverlayProcessorInterface::FilterOperationsMap render_pass_filters; OverlayProcessorInterface::FilterOperationsMap render_pass_backdrop_filters; - RenderPassList pass_list; + AggregatedRenderPassList pass_list; pass_list.push_back(std::move(pass)); overlay_processor_->ProcessForOverlays( resource_provider_.get(), &pass_list, GetIdentityColorMatrix(), @@ -1109,7 +1110,7 @@ gfx::Rect rect = kOverlayRect; rect.set_width(rect.width() / 2); rect.Offset(0, -rect.height()); - std::unique_ptr<RenderPass> pass = CreateRenderPass(); + auto pass = CreateRenderPass(); CreateCandidateQuadAt(resource_provider_.get(), child_resource_provider_.get(), child_provider_.get(), pass->shared_quad_state_list.back(), pass.get(), rect); @@ -1118,7 +1119,7 @@ OverlayCandidateList candidate_list; OverlayProcessorInterface::FilterOperationsMap render_pass_filters; OverlayProcessorInterface::FilterOperationsMap render_pass_backdrop_filters; - RenderPassList pass_list; + AggregatedRenderPassList pass_list; pass_list.push_back(std::move(pass)); overlay_processor_->ProcessForOverlays( resource_provider_.get(), &pass_list, GetIdentityColorMatrix(), @@ -1133,7 +1134,7 @@ gfx::Rect rect = kOverlayRect; rect.set_height(rect.height() / 2); rect.Offset(-rect.width(), 0); - std::unique_ptr<RenderPass> pass = CreateRenderPass(); + auto pass = CreateRenderPass(); CreateCandidateQuadAt(resource_provider_.get(), child_resource_provider_.get(), child_provider_.get(), pass->shared_quad_state_list.back(), pass.get(), rect); @@ -1143,7 +1144,7 @@ OverlayCandidateList candidate_list; OverlayProcessorInterface::FilterOperationsMap render_pass_filters; OverlayProcessorInterface::FilterOperationsMap render_pass_backdrop_filters; - RenderPassList pass_list; + AggregatedRenderPassList pass_list; pass_list.push_back(std::move(pass)); overlay_processor_->ProcessForOverlays( resource_provider_.get(), &pass_list, GetIdentityColorMatrix(), @@ -1157,7 +1158,7 @@ TEST_F(SingleOverlayOnTopTest, AllowPositiveScaleTransform) { gfx::Rect rect = kOverlayRect; rect.set_width(rect.width() / 2); - std::unique_ptr<RenderPass> pass = CreateRenderPass(); + auto pass = CreateRenderPass(); CreateCandidateQuadAt(resource_provider_.get(), child_resource_provider_.get(), child_provider_.get(), pass->shared_quad_state_list.back(), pass.get(), rect); @@ -1166,7 +1167,7 @@ OverlayCandidateList candidate_list; OverlayProcessorInterface::FilterOperationsMap render_pass_filters; OverlayProcessorInterface::FilterOperationsMap render_pass_backdrop_filters; - RenderPassList pass_list; + AggregatedRenderPassList pass_list; pass_list.push_back(std::move(pass)); overlay_processor_->ProcessForOverlays( resource_provider_.get(), &pass_list, GetIdentityColorMatrix(), @@ -1178,7 +1179,7 @@ TEST_F(SingleOverlayOnTopTest, AcceptMirrorYTransform) { gfx::Rect rect = kOverlayRect; rect.Offset(0, -rect.height()); - std::unique_ptr<RenderPass> pass = CreateRenderPass(); + auto pass = CreateRenderPass(); CreateCandidateQuadAt(resource_provider_.get(), child_resource_provider_.get(), child_provider_.get(), pass->shared_quad_state_list.back(), pass.get(), rect); @@ -1188,7 +1189,7 @@ OverlayCandidateList candidate_list; OverlayProcessorInterface::FilterOperationsMap render_pass_filters; OverlayProcessorInterface::FilterOperationsMap render_pass_backdrop_filters; - RenderPassList pass_list; + AggregatedRenderPassList pass_list; pass_list.push_back(std::move(pass)); overlay_processor_->ProcessForOverlays( resource_provider_.get(), &pass_list, GetIdentityColorMatrix(), @@ -1200,7 +1201,7 @@ TEST_F(UnderlayTest, Allow90DegreeRotation) { gfx::Rect rect = kOverlayRect; rect.Offset(0, -rect.height()); - std::unique_ptr<RenderPass> pass = CreateRenderPass(); + auto pass = CreateRenderPass(); CreateCandidateQuadAt(resource_provider_.get(), child_resource_provider_.get(), child_provider_.get(), pass->shared_quad_state_list.back(), pass.get(), rect); @@ -1210,7 +1211,7 @@ OverlayCandidateList candidate_list; OverlayProcessorInterface::FilterOperationsMap render_pass_filters; OverlayProcessorInterface::FilterOperationsMap render_pass_backdrop_filters; - RenderPassList pass_list; + AggregatedRenderPassList pass_list; pass_list.push_back(std::move(pass)); overlay_processor_->ProcessForOverlays( resource_provider_.get(), &pass_list, GetIdentityColorMatrix(), @@ -1223,7 +1224,7 @@ TEST_F(UnderlayTest, Allow180DegreeRotation) { gfx::Rect rect = kOverlayRect; rect.Offset(-rect.width(), -rect.height()); - std::unique_ptr<RenderPass> pass = CreateRenderPass(); + auto pass = CreateRenderPass(); CreateCandidateQuadAt(resource_provider_.get(), child_resource_provider_.get(), child_provider_.get(), pass->shared_quad_state_list.back(), pass.get(), rect); @@ -1233,7 +1234,7 @@ OverlayCandidateList candidate_list; OverlayProcessorInterface::FilterOperationsMap render_pass_filters; OverlayProcessorInterface::FilterOperationsMap render_pass_backdrop_filters; - RenderPassList pass_list; + AggregatedRenderPassList pass_list; pass_list.push_back(std::move(pass)); overlay_processor_->ProcessForOverlays( resource_provider_.get(), &pass_list, GetIdentityColorMatrix(), @@ -1246,7 +1247,7 @@ TEST_F(UnderlayTest, Allow270DegreeRotation) { gfx::Rect rect = kOverlayRect; rect.Offset(-rect.width(), 0); - std::unique_ptr<RenderPass> pass = CreateRenderPass(); + auto pass = CreateRenderPass(); CreateCandidateQuadAt(resource_provider_.get(), child_resource_provider_.get(), child_provider_.get(), pass->shared_quad_state_list.back(), pass.get(), rect); @@ -1256,7 +1257,7 @@ OverlayCandidateList candidate_list; OverlayProcessorInterface::FilterOperationsMap render_pass_filters; OverlayProcessorInterface::FilterOperationsMap render_pass_backdrop_filters; - RenderPassList pass_list; + AggregatedRenderPassList pass_list; pass_list.push_back(std::move(pass)); overlay_processor_->ProcessForOverlays( resource_provider_.get(), &pass_list, GetIdentityColorMatrix(), @@ -1267,7 +1268,7 @@ } TEST_F(UnderlayTest, AllowsOpaqueCandidates) { - std::unique_ptr<RenderPass> pass = CreateRenderPass(); + auto pass = CreateRenderPass(); CreateFullscreenCandidateQuad( resource_provider_.get(), child_resource_provider_.get(), child_provider_.get(), pass->shared_quad_state_list.back(), pass.get()) @@ -1277,7 +1278,7 @@ OverlayCandidateList candidate_list; OverlayProcessorInterface::FilterOperationsMap render_pass_filters; OverlayProcessorInterface::FilterOperationsMap render_pass_backdrop_filters; - RenderPassList pass_list; + AggregatedRenderPassList pass_list; pass_list.push_back(std::move(pass)); overlay_processor_->ProcessForOverlays( resource_provider_.get(), &pass_list, GetIdentityColorMatrix(), @@ -1287,7 +1288,7 @@ } TEST_F(UnderlayTest, DisallowsTransparentCandidates) { - std::unique_ptr<RenderPass> pass = CreateRenderPass(); + auto pass = CreateRenderPass(); CreateFullscreenCandidateQuad( resource_provider_.get(), child_resource_provider_.get(), child_provider_.get(), pass->shared_quad_state_list.back(), pass.get()) @@ -1296,7 +1297,7 @@ OverlayCandidateList candidate_list; OverlayProcessorInterface::FilterOperationsMap render_pass_filters; OverlayProcessorInterface::FilterOperationsMap render_pass_backdrop_filters; - RenderPassList pass_list; + AggregatedRenderPassList pass_list; pass_list.push_back(std::move(pass)); overlay_processor_->ProcessForOverlays( resource_provider_.get(), &pass_list, GetIdentityColorMatrix(), @@ -1306,11 +1307,11 @@ } TEST_F(UnderlayTest, DisallowFilteredQuadOnTop) { - std::unique_ptr<RenderPass> pass = CreateRenderPass(); + auto pass = CreateRenderPass(); - RenderPassId render_pass_id{3}; - RenderPassDrawQuad* quad = - pass->CreateAndAppendDrawQuad<RenderPassDrawQuad>(); + AggregatedRenderPassId render_pass_id{3}; + AggregatedRenderPassDrawQuad* quad = + pass->CreateAndAppendDrawQuad<AggregatedRenderPassDrawQuad>(); quad->SetNew(pass->shared_quad_state_list.back(), kOverlayRect, kOverlayRect, render_pass_id, 0, gfx::RectF(), gfx::Size(), gfx::Vector2dF(1, 1), gfx::PointF(), gfx::RectF(), false, 1.0f); @@ -1330,7 +1331,7 @@ render_pass_backdrop_filters[render_pass_id] = &filters; - RenderPassList pass_list; + AggregatedRenderPassList pass_list; pass_list.push_back(std::move(pass)); overlay_processor_->ProcessForOverlays( resource_provider_.get(), &pass_list, GetIdentityColorMatrix(), @@ -1340,7 +1341,7 @@ } TEST_F(TransparentUnderlayTest, AllowsOpaqueCandidates) { - std::unique_ptr<RenderPass> pass = CreateRenderPass(); + auto pass = CreateRenderPass(); CreateFullscreenCandidateQuad( resource_provider_.get(), child_resource_provider_.get(), child_provider_.get(), pass->shared_quad_state_list.back(), pass.get()) @@ -1350,7 +1351,7 @@ OverlayCandidateList candidate_list; OverlayProcessorInterface::FilterOperationsMap render_pass_filters; OverlayProcessorInterface::FilterOperationsMap render_pass_backdrop_filters; - RenderPassList pass_list; + AggregatedRenderPassList pass_list; pass_list.push_back(std::move(pass)); overlay_processor_->ProcessForOverlays( resource_provider_.get(), &pass_list, GetIdentityColorMatrix(), @@ -1360,7 +1361,7 @@ } TEST_F(TransparentUnderlayTest, AllowsTransparentCandidates) { - std::unique_ptr<RenderPass> pass = CreateRenderPass(); + auto pass = CreateRenderPass(); CreateFullscreenCandidateQuad( resource_provider_.get(), child_resource_provider_.get(), child_provider_.get(), pass->shared_quad_state_list.back(), pass.get()) @@ -1369,7 +1370,7 @@ OverlayCandidateList candidate_list; OverlayProcessorInterface::FilterOperationsMap render_pass_filters; OverlayProcessorInterface::FilterOperationsMap render_pass_backdrop_filters; - RenderPassList pass_list; + AggregatedRenderPassList pass_list; pass_list.push_back(std::move(pass)); overlay_processor_->ProcessForOverlays( resource_provider_.get(), &pass_list, GetIdentityColorMatrix(), @@ -1381,7 +1382,7 @@ TEST_F(SingleOverlayOnTopTest, AllowNotTopIfNotOccluded) { AddExpectedRectToOverlayProcessor(gfx::RectF(kOverlayBottomRightRect)); - std::unique_ptr<RenderPass> pass = CreateRenderPass(); + auto pass = CreateRenderPass(); CreateOpaqueQuadAt(resource_provider_.get(), pass->shared_quad_state_list.back(), pass.get(), kOverlayTopLeftRect); @@ -1393,7 +1394,7 @@ OverlayCandidateList candidate_list; OverlayProcessorInterface::FilterOperationsMap render_pass_filters; OverlayProcessorInterface::FilterOperationsMap render_pass_backdrop_filters; - RenderPassList pass_list; + AggregatedRenderPassList pass_list; pass_list.push_back(std::move(pass)); overlay_processor_->ProcessForOverlays( resource_provider_.get(), &pass_list, GetIdentityColorMatrix(), @@ -1405,7 +1406,7 @@ TEST_F(SingleOverlayOnTopTest, AllowTransparentOnTop) { AddExpectedRectToOverlayProcessor(gfx::RectF(kOverlayBottomRightRect)); - std::unique_ptr<RenderPass> pass = CreateRenderPass(); + auto pass = CreateRenderPass(); SharedQuadState* shared_state = pass->CreateAndAppendSharedQuadState(); shared_state->opacity = 0.f; CreateSolidColorQuadAt(shared_state, SK_ColorBLACK, pass.get(), @@ -1419,7 +1420,7 @@ OverlayCandidateList candidate_list; OverlayProcessorInterface::FilterOperationsMap render_pass_filters; OverlayProcessorInterface::FilterOperationsMap render_pass_backdrop_filters; - RenderPassList pass_list; + AggregatedRenderPassList pass_list; pass_list.push_back(std::move(pass)); overlay_processor_->ProcessForOverlays( resource_provider_.get(), &pass_list, GetIdentityColorMatrix(), @@ -1431,7 +1432,7 @@ TEST_F(SingleOverlayOnTopTest, AllowTransparentColorOnTop) { AddExpectedRectToOverlayProcessor(gfx::RectF(kOverlayBottomRightRect)); - std::unique_ptr<RenderPass> pass = CreateRenderPass(); + auto pass = CreateRenderPass(); CreateSolidColorQuadAt(pass->shared_quad_state_list.back(), SK_ColorTRANSPARENT, pass.get(), kOverlayBottomRightRect); @@ -1443,7 +1444,7 @@ OverlayCandidateList candidate_list; OverlayProcessorInterface::FilterOperationsMap render_pass_filters; OverlayProcessorInterface::FilterOperationsMap render_pass_backdrop_filters; - RenderPassList pass_list; + AggregatedRenderPassList pass_list; pass_list.push_back(std::move(pass)); overlay_processor_->ProcessForOverlays( resource_provider_.get(), &pass_list, GetIdentityColorMatrix(), @@ -1453,7 +1454,7 @@ } TEST_F(SingleOverlayOnTopTest, RejectOpaqueColorOnTop) { - std::unique_ptr<RenderPass> pass = CreateRenderPass(); + auto pass = CreateRenderPass(); SharedQuadState* shared_state = pass->CreateAndAppendSharedQuadState(); shared_state->opacity = 0.5f; CreateSolidColorQuadAt(shared_state, SK_ColorBLACK, pass.get(), @@ -1467,7 +1468,7 @@ OverlayCandidateList candidate_list; OverlayProcessorInterface::FilterOperationsMap render_pass_filters; OverlayProcessorInterface::FilterOperationsMap render_pass_backdrop_filters; - RenderPassList pass_list; + AggregatedRenderPassList pass_list; pass_list.push_back(std::move(pass)); overlay_processor_->ProcessForOverlays( resource_provider_.get(), &pass_list, GetIdentityColorMatrix(), @@ -1477,7 +1478,7 @@ } TEST_F(SingleOverlayOnTopTest, RejectTransparentColorOnTopWithoutBlending) { - std::unique_ptr<RenderPass> pass = CreateRenderPass(); + auto pass = CreateRenderPass(); SharedQuadState* shared_state = pass->CreateAndAppendSharedQuadState(); CreateSolidColorQuadAt(shared_state, SK_ColorTRANSPARENT, pass.get(), kOverlayBottomRightRect) @@ -1489,7 +1490,7 @@ OverlayCandidateList candidate_list; OverlayProcessorInterface::FilterOperationsMap render_pass_filters; OverlayProcessorInterface::FilterOperationsMap render_pass_backdrop_filters; - RenderPassList pass_list; + AggregatedRenderPassList pass_list; pass_list.push_back(std::move(pass)); overlay_processor_->ProcessForOverlays( resource_provider_.get(), &pass_list, GetIdentityColorMatrix(), @@ -1505,8 +1506,8 @@ ResourceId previous_resource_id; for (size_t i = 0; i < 3 + kFramesSkippedBeforeNotPromoting; ++i) { - std::unique_ptr<RenderPass> pass = CreateRenderPass(); - RenderPass* main_pass = pass.get(); + auto pass = CreateRenderPass(); + AggregatedRenderPass* main_pass = pass.get(); ResourceId resource_id; if (i == 0 || i == 1) { @@ -1542,7 +1543,7 @@ OverlayCandidateList candidate_list; OverlayProcessorInterface::FilterOperationsMap render_pass_filters; OverlayProcessorInterface::FilterOperationsMap render_pass_backdrop_filters; - RenderPassList pass_list; + AggregatedRenderPassList pass_list; pass_list.push_back(std::move(pass)); overlay_processor_->ProcessForOverlays( resource_provider_.get(), &pass_list, GetIdentityColorMatrix(), @@ -1565,7 +1566,7 @@ TEST_F(UnderlayTest, OverlayLayerUnderMainLayer) { AddExpectedRectToOverlayProcessor(gfx::RectF(kOverlayBottomRightRect)); - std::unique_ptr<RenderPass> pass = CreateRenderPass(); + auto pass = CreateRenderPass(); CreateFullscreenOpaqueQuad(resource_provider_.get(), pass->shared_quad_state_list.back(), pass.get()); CreateCandidateQuadAt(resource_provider_.get(), @@ -1576,8 +1577,8 @@ OverlayCandidateList candidate_list; OverlayProcessorInterface::FilterOperationsMap render_pass_filters; OverlayProcessorInterface::FilterOperationsMap render_pass_backdrop_filters; - RenderPassList pass_list; - RenderPass* main_pass = pass.get(); + AggregatedRenderPassList pass_list; + AggregatedRenderPass* main_pass = pass.get(); pass_list.push_back(std::move(pass)); overlay_processor_->ProcessForOverlays( resource_provider_.get(), &pass_list, GetIdentityColorMatrix(), @@ -1596,7 +1597,7 @@ } TEST_F(UnderlayTest, AllowOnTop) { - std::unique_ptr<RenderPass> pass = CreateRenderPass(); + auto pass = CreateRenderPass(); CreateFullscreenCandidateQuad( resource_provider_.get(), child_resource_provider_.get(), child_provider_.get(), pass->shared_quad_state_list.back(), pass.get()); @@ -1607,8 +1608,8 @@ OverlayCandidateList candidate_list; OverlayProcessorInterface::FilterOperationsMap render_pass_filters; OverlayProcessorInterface::FilterOperationsMap render_pass_backdrop_filters; - RenderPassList pass_list; - RenderPass* main_pass = pass.get(); + AggregatedRenderPassList pass_list; + AggregatedRenderPass* main_pass = pass.get(); pass_list.push_back(std::move(pass)); overlay_processor_->ProcessForOverlays( resource_provider_.get(), &pass_list, GetIdentityColorMatrix(), @@ -1627,7 +1628,7 @@ // The first time an underlay is scheduled its damage must not be subtracted. TEST_F(UnderlayTest, InitialUnderlayDamageNotSubtracted) { - std::unique_ptr<RenderPass> pass = CreateRenderPass(); + auto pass = CreateRenderPass(); CreateFullscreenCandidateQuad( resource_provider_.get(), child_resource_provider_.get(), child_provider_.get(), pass->shared_quad_state_list.back(), pass.get()); @@ -1637,7 +1638,7 @@ OverlayCandidateList candidate_list; OverlayProcessorInterface::FilterOperationsMap render_pass_filters; OverlayProcessorInterface::FilterOperationsMap render_pass_backdrop_filters; - RenderPassList pass_list; + AggregatedRenderPassList pass_list; pass_list.push_back(std::move(pass)); overlay_processor_->ProcessForOverlays( resource_provider_.get(), &pass_list, GetIdentityColorMatrix(), @@ -1651,7 +1652,7 @@ // subtracted the second time. TEST_F(UnderlayTest, DamageSubtractedForConsecutiveIdenticalUnderlays) { for (int i = 0; i < 2; ++i) { - std::unique_ptr<RenderPass> pass = CreateRenderPass(); + auto pass = CreateRenderPass(); CreateFullscreenCandidateQuad( resource_provider_.get(), child_resource_provider_.get(), child_provider_.get(), pass->shared_quad_state_list.back(), pass.get()); @@ -1665,7 +1666,7 @@ OverlayCandidateList candidate_list; OverlayProcessorInterface::FilterOperationsMap render_pass_filters; OverlayProcessorInterface::FilterOperationsMap render_pass_backdrop_filters; - RenderPassList pass_list; + AggregatedRenderPassList pass_list; pass_list.push_back(std::move(pass)); overlay_processor_->ProcessForOverlays( resource_provider_.get(), &pass_list, GetIdentityColorMatrix(), @@ -1685,7 +1686,7 @@ for (int i = 0; i < 2; ++i) { AddExpectedRectToOverlayProcessor(gfx::RectF(overlay_rects[i])); - std::unique_ptr<RenderPass> pass = CreateRenderPass(); + auto pass = CreateRenderPass(); CreateCandidateQuadAt(resource_provider_.get(), child_resource_provider_.get(), child_provider_.get(), @@ -1697,7 +1698,7 @@ OverlayCandidateList candidate_list; OverlayProcessorInterface::FilterOperationsMap render_pass_filters; OverlayProcessorInterface::FilterOperationsMap render_pass_backdrop_filters; - RenderPassList pass_list; + AggregatedRenderPassList pass_list; pass_list.push_back(std::move(pass)); overlay_processor_->ProcessForOverlays( resource_provider_.get(), &pass_list, GetIdentityColorMatrix(), @@ -1714,7 +1715,7 @@ bool has_fullscreen_candidate[] = {true, false, true}; for (int i = 0; i < 3; ++i) { - std::unique_ptr<RenderPass> pass = CreateRenderPass(); + auto pass = CreateRenderPass(); if (has_fullscreen_candidate[i]) { CreateFullscreenCandidateQuad( @@ -1732,7 +1733,7 @@ OverlayCandidateList candidate_list; OverlayProcessorInterface::FilterOperationsMap render_pass_filters; OverlayProcessorInterface::FilterOperationsMap render_pass_backdrop_filters; - RenderPassList pass_list; + AggregatedRenderPassList pass_list; pass_list.push_back(std::move(pass)); overlay_processor_->ProcessForOverlays( resource_provider_.get(), &pass_list, GetIdentityColorMatrix(), @@ -1747,7 +1748,7 @@ // it has been unoccluded for more than one frame. TEST_F(UnderlayTest, DamageSubtractedForOneFrameAfterBecomingUnoccluded) { for (int i = 0; i < 3; ++i) { - std::unique_ptr<RenderPass> pass = CreateRenderPass(); + auto pass = CreateRenderPass(); if (i == 0) { // Add an overlapping quad above the candidate for the first frame. CreateFullscreenOpaqueQuad(resource_provider_.get(), @@ -1763,7 +1764,7 @@ OverlayCandidateList candidate_list; OverlayProcessorInterface::FilterOperationsMap render_pass_filters; OverlayProcessorInterface::FilterOperationsMap render_pass_backdrop_filters; - RenderPassList pass_list; + AggregatedRenderPassList pass_list; pass_list.push_back(std::move(pass)); overlay_processor_->ProcessForOverlays( resource_provider_.get(), &pass_list, GetIdentityColorMatrix(), @@ -1782,7 +1783,7 @@ TEST_F(UnderlayTest, DamageNotSubtractedWhenQuadsAboveOverlap) { for (int i = 0; i < 2; ++i) { - std::unique_ptr<RenderPass> pass = CreateRenderPass(); + auto pass = CreateRenderPass(); // Add an overlapping quad above the candidate. CreateFullscreenOpaqueQuad(resource_provider_.get(), pass->shared_quad_state_list.back(), pass.get()); @@ -1795,7 +1796,7 @@ OverlayCandidateList candidate_list; OverlayProcessorInterface::FilterOperationsMap render_pass_filters; OverlayProcessorInterface::FilterOperationsMap render_pass_backdrop_filters; - RenderPassList pass_list; + AggregatedRenderPassList pass_list; pass_list.push_back(std::move(pass)); overlay_processor_->ProcessForOverlays( resource_provider_.get(), &pass_list, GetIdentityColorMatrix(), @@ -1810,7 +1811,7 @@ AddExpectedRectToOverlayProcessor(gfx::RectF(kOverlayBottomRightRect)); for (int i = 0; i < 2; ++i) { - std::unique_ptr<RenderPass> pass = CreateRenderPass(); + auto pass = CreateRenderPass(); // Add a non-overlapping quad above the candidate. CreateOpaqueQuadAt(resource_provider_.get(), pass->shared_quad_state_list.back(), pass.get(), @@ -1825,7 +1826,7 @@ OverlayCandidateList candidate_list; OverlayProcessorInterface::FilterOperationsMap render_pass_filters; OverlayProcessorInterface::FilterOperationsMap render_pass_backdrop_filters; - RenderPassList pass_list; + AggregatedRenderPassList pass_list; pass_list.push_back(std::move(pass)); overlay_processor_->ProcessForOverlays( resource_provider_.get(), &pass_list, GetIdentityColorMatrix(), @@ -1837,7 +1838,7 @@ } TEST_F(UnderlayTest, PrimaryPlaneOverlayIsTransparentWithUnderlay) { - std::unique_ptr<RenderPass> pass = CreateRenderPass(); + auto pass = CreateRenderPass(); gfx::Rect output_rect = pass->output_rect; CreateOpaqueQuadAt(resource_provider_.get(), pass->shared_quad_state_list.back(), pass.get(), @@ -1852,7 +1853,7 @@ OverlayProcessorInterface::FilterOperationsMap render_pass_filters; OverlayProcessorInterface::FilterOperationsMap render_pass_backdrop_filters; - RenderPassList pass_list; + AggregatedRenderPassList pass_list; pass_list.push_back(std::move(pass)); auto output_surface_plane = overlay_processor_->ProcessOutputSurfaceAsOverlay( @@ -1874,7 +1875,7 @@ AddExpectedRectToOverlayProcessor(gfx::RectF(kOverlayTopLeftRect)); for (size_t i = 0; i < 2; ++i) { - std::unique_ptr<RenderPass> pass = CreateRenderPass(); + auto pass = CreateRenderPass(); if (i == 0) { CreateCandidateQuadAt( @@ -1891,7 +1892,7 @@ OverlayCandidateList candidate_list; OverlayProcessorInterface::FilterOperationsMap render_pass_filters; OverlayProcessorInterface::FilterOperationsMap render_pass_backdrop_filters; - RenderPassList pass_list; + AggregatedRenderPassList pass_list; pass_list.push_back(std::move(pass)); overlay_processor_->ProcessForOverlays( resource_provider_.get(), &pass_list, GetIdentityColorMatrix(), @@ -1915,7 +1916,7 @@ size_t expected_candidate_size[] = {1, 0}; for (int i = 0; i < 2; ++i) { - std::unique_ptr<RenderPass> pass = CreateRenderPass(); + auto pass = CreateRenderPass(); if (has_fullscreen_candidate[i]) { CreateFullscreenCandidateQuad( @@ -1934,7 +1935,7 @@ OverlayProcessorInterface::FilterOperationsMap render_pass_filters; OverlayProcessorInterface::FilterOperationsMap render_pass_background_filters; - RenderPassList pass_list; + AggregatedRenderPassList pass_list; pass_list.push_back(std::move(pass)); overlay_processor_->ProcessForOverlays( resource_provider_.get(), &pass_list, GetIdentityColorMatrix(), @@ -1950,7 +1951,7 @@ // damage. TEST_F(UnderlayTest, CandidateNoDamageWhenQuadSharedStateNoOccludingDamage) { for (int i = 0; i < 4; ++i) { - std::unique_ptr<RenderPass> pass = CreateRenderPass(); + auto pass = CreateRenderPass(); gfx::Rect rect(2, 3); SharedQuadState* default_damaged_shared_quad_state = @@ -1977,7 +1978,7 @@ OverlayCandidateList candidate_list; OverlayProcessorInterface::FilterOperationsMap render_pass_filters; OverlayProcessorInterface::FilterOperationsMap render_pass_backdrop_filters; - RenderPassList pass_list; + AggregatedRenderPassList pass_list; pass_list.push_back(std::move(pass)); overlay_processor_->ProcessForOverlays( resource_provider_.get(), &pass_list, GetIdentityColorMatrix(), @@ -1992,7 +1993,7 @@ } TEST_F(UnderlayCastTest, NoOverlayContentBounds) { - std::unique_ptr<RenderPass> pass = CreateRenderPass(); + auto pass = CreateRenderPass(); CreateOpaqueQuadAt(resource_provider_.get(), pass->shared_quad_state_list.back(), pass.get(), @@ -2001,7 +2002,7 @@ OverlayCandidateList candidate_list; OverlayProcessorInterface::FilterOperationsMap render_pass_filters; OverlayProcessorInterface::FilterOperationsMap render_pass_backdrop_filters; - RenderPassList pass_list; + AggregatedRenderPassList pass_list; pass_list.push_back(std::move(pass)); overlay_processor_->ProcessForOverlays( resource_provider_.get(), &pass_list, GetIdentityColorMatrix(), @@ -2011,14 +2012,14 @@ } TEST_F(UnderlayCastTest, FullScreenOverlayContentBounds) { - std::unique_ptr<RenderPass> pass = CreateRenderPass(); + auto pass = CreateRenderPass(); CreateVideoHoleDrawQuadAt(pass->shared_quad_state_list.back(), pass.get(), kOverlayRect); OverlayCandidateList candidate_list; OverlayProcessorInterface::FilterOperationsMap render_pass_filters; OverlayProcessorInterface::FilterOperationsMap render_pass_backdrop_filters; - RenderPassList pass_list; + AggregatedRenderPassList pass_list; pass_list.push_back(std::move(pass)); overlay_processor_->ProcessForOverlays( resource_provider_.get(), &pass_list, GetIdentityColorMatrix(), @@ -2035,7 +2036,7 @@ const gfx::Rect kLeftSide(0, 0, 128, 256); const gfx::Rect kTopRight(128, 0, 128, 128); - std::unique_ptr<RenderPass> pass = CreateRenderPass(); + auto pass = CreateRenderPass(); CreateVideoHoleDrawQuadAt(pass->shared_quad_state_list.back(), pass.get(), kOverlayBottomRightRect); CreateOpaqueQuadAt(resource_provider_.get(), @@ -2048,7 +2049,7 @@ OverlayCandidateList candidate_list; OverlayProcessorInterface::FilterOperationsMap render_pass_filters; OverlayProcessorInterface::FilterOperationsMap render_pass_backdrop_filters; - RenderPassList pass_list; + AggregatedRenderPassList pass_list; pass_list.push_back(std::move(pass)); overlay_processor_->ProcessForOverlays( resource_provider_.get(), &pass_list, GetIdentityColorMatrix(), @@ -2060,7 +2061,7 @@ } TEST_F(UnderlayCastTest, OverlayOccludedContentBounds) { - std::unique_ptr<RenderPass> pass = CreateRenderPass(); + auto pass = CreateRenderPass(); CreateOpaqueQuadAt(resource_provider_.get(), pass->shared_quad_state_list.back(), pass.get(), kOverlayTopLeftRect); @@ -2070,7 +2071,7 @@ OverlayCandidateList candidate_list; OverlayProcessorInterface::FilterOperationsMap render_pass_filters; OverlayProcessorInterface::FilterOperationsMap render_pass_backdrop_filters; - RenderPassList pass_list; + AggregatedRenderPassList pass_list; pass_list.push_back(std::move(pass)); overlay_processor_->ProcessForOverlays( resource_provider_.get(), &pass_list, GetIdentityColorMatrix(), @@ -2082,7 +2083,7 @@ } TEST_F(UnderlayCastTest, OverlayOccludedUnionContentBounds) { - std::unique_ptr<RenderPass> pass = CreateRenderPass(); + auto pass = CreateRenderPass(); CreateOpaqueQuadAt(resource_provider_.get(), pass->shared_quad_state_list.back(), pass.get(), kOverlayTopLeftRect); @@ -2095,7 +2096,7 @@ OverlayCandidateList candidate_list; OverlayProcessorInterface::FilterOperationsMap render_pass_filters; OverlayProcessorInterface::FilterOperationsMap render_pass_backdrop_filters; - RenderPassList pass_list; + AggregatedRenderPassList pass_list; pass_list.push_back(std::move(pass)); overlay_processor_->ProcessForOverlays( resource_provider_.get(), &pass_list, GetIdentityColorMatrix(), @@ -2115,7 +2116,7 @@ gfx::Transform transform; transform.Translate(0.5f, 0.5f); - std::unique_ptr<RenderPass> pass = CreateRenderPassWithTransform(transform); + auto pass = CreateRenderPassWithTransform(transform); CreateVideoHoleDrawQuadAt(pass->shared_quad_state_list.back(), pass.get(), overlay_rect); CreateOpaqueQuadAt(resource_provider_.get(), @@ -2125,7 +2126,7 @@ OverlayCandidateList candidate_list; OverlayProcessorInterface::FilterOperationsMap render_pass_filters; OverlayProcessorInterface::FilterOperationsMap render_pass_backdrop_filters; - RenderPassList pass_list; + AggregatedRenderPassList pass_list; pass_list.push_back(std::move(pass)); overlay_processor_->ProcessForOverlays( resource_provider_.get(), &pass_list, GetIdentityColorMatrix(), @@ -2146,7 +2147,7 @@ gfx::Transform transform; transform.Translate(0.5f, 0.5f); - std::unique_ptr<RenderPass> pass = CreateRenderPassWithTransform(transform); + auto pass = CreateRenderPassWithTransform(transform); CreateVideoHoleDrawQuadAt(pass->shared_quad_state_list.back(), pass.get(), overlay_rect); CreateOpaqueQuadAt(resource_provider_.get(), @@ -2156,7 +2157,7 @@ OverlayCandidateList candidate_list; OverlayProcessorInterface::FilterOperationsMap render_pass_filters; OverlayProcessorInterface::FilterOperationsMap render_pass_backdrop_filters; - RenderPassList pass_list; + AggregatedRenderPassList pass_list; pass_list.push_back(std::move(pass)); overlay_processor_->ProcessForOverlays( resource_provider_.get(), &pass_list, GetIdentityColorMatrix(), @@ -2168,7 +2169,7 @@ } TEST_F(UnderlayCastTest, NoOverlayPromotionWithoutProtectedContent) { - std::unique_ptr<RenderPass> pass = CreateRenderPass(); + auto pass = CreateRenderPass(); CreateCandidateQuadAt(resource_provider_.get(), child_resource_provider_.get(), child_provider_.get(), pass->shared_quad_state_list.back(), pass.get(), @@ -2177,7 +2178,7 @@ OverlayCandidateList candidate_list; OverlayProcessorInterface::FilterOperationsMap render_pass_filters; OverlayProcessorInterface::FilterOperationsMap render_pass_backdrop_filters; - RenderPassList pass_list; + AggregatedRenderPassList pass_list; pass_list.push_back(std::move(pass)); overlay_processor_->ProcessForOverlays( resource_provider_.get(), &pass_list, GetIdentityColorMatrix(), @@ -2191,7 +2192,7 @@ #if defined(ALWAYS_ENABLE_BLENDING_FOR_PRIMARY) TEST_F(UnderlayCastTest, PrimaryPlaneOverlayIsAlwaysTransparent) { - std::unique_ptr<RenderPass> pass = CreateRenderPass(); + auto pass = CreateRenderPass(); gfx::Rect output_rect = pass->output_rect; CreateOpaqueQuadAt(resource_provider_.get(), pass->shared_quad_state_list.back(), pass.get(), @@ -2201,7 +2202,7 @@ OverlayProcessorInterface::FilterOperationsMap render_pass_filters; OverlayProcessorInterface::FilterOperationsMap render_pass_backdrop_filters; - RenderPassList pass_list; + AggregatedRenderPassList pass_list; pass_list.push_back(std::move(pass)); auto output_surface_plane = overlay_processor_->ProcessOutputSurfaceAsOverlay( kDisplaySize, kDefaultBufferFormat, gfx::ColorSpace(), gpu::Mailbox()); @@ -2320,7 +2321,8 @@ renderer_->SetVisible(true); } - void DrawFrame(RenderPassList* pass_list, const gfx::Size& viewport_size) { + void DrawFrame(AggregatedRenderPassList* pass_list, + const gfx::Size& viewport_size) { renderer_->DrawFrame(pass_list, 1.f, viewport_size, gfx::DisplayColorSpaces()); } @@ -2347,13 +2349,13 @@ void DrawEmptyFrame() { // Draw one frame to make sure output surface is reshaped before tests. - std::unique_ptr<RenderPass> pass = CreateRenderPass(); + auto pass = CreateRenderPass(); CreateFullscreenCandidateQuad( resource_provider_.get(), child_resource_provider_.get(), child_provider_.get(), pass->shared_quad_state_list.back(), pass.get()); - RenderPassList pass_list; + AggregatedRenderPassList pass_list; pass_list.push_back(std::move(pass)); EXPECT_CALL(scheduler_, Schedule(_, _, _, _, _, _, _)).Times(2); @@ -2384,7 +2386,7 @@ renderer_->set_expect_overlays(true); AddExpectedRectToOverlayProcessor(gfx::RectF(kOverlayBottomRightRect)); - std::unique_ptr<RenderPass> pass = CreateRenderPass(); + auto pass = CreateRenderPass(); CreateCandidateQuadAt(resource_provider_.get(), child_resource_provider_.get(), child_provider_.get(), @@ -2395,7 +2397,7 @@ CreateFullscreenOpaqueQuad(resource_provider_.get(), pass->shared_quad_state_list.back(), pass.get()); - RenderPassList pass_list; + AggregatedRenderPassList pass_list; pass_list.push_back(std::move(pass)); // Candidate pass was taken out and extra skipped pass added, @@ -2424,7 +2426,7 @@ Init(use_overlay_processor); renderer_->set_expect_overlays(true); - std::unique_ptr<RenderPass> pass = CreateRenderPass(); + auto pass = CreateRenderPass(); CreateFullscreenOpaqueQuad(resource_provider_.get(), pass->shared_quad_state_list.back(), pass.get()); @@ -2435,7 +2437,7 @@ resource_provider_.get(), child_resource_provider_.get(), child_provider_.get(), pass->shared_quad_state_list.back(), pass.get()); - RenderPassList pass_list; + AggregatedRenderPassList pass_list; pass_list.push_back(std::move(pass)); // Candidate quad should fail to be overlaid on top because of occlusion. @@ -2463,7 +2465,7 @@ Init(use_overlay_processor); renderer_->set_expect_overlays(false); - std::unique_ptr<RenderPass> pass = CreateRenderPass(); + auto pass = CreateRenderPass(); CreateFullscreenCandidateQuad( resource_provider_.get(), child_resource_provider_.get(), @@ -2474,7 +2476,7 @@ CreateFullscreenOpaqueQuad(resource_provider_.get(), pass->shared_quad_state_list.back(), pass.get()); - RenderPassList pass_list; + AggregatedRenderPassList pass_list; pass_list.push_back(std::move(pass)); // Should not see the primary surface's overlay. @@ -2499,7 +2501,7 @@ // Draw one frame to make sure output surface is reshaped before tests. DrawEmptyFrame(); - std::unique_ptr<RenderPass> pass = CreateRenderPass(); + auto pass = CreateRenderPass(); CreateFullscreenCandidateQuad( resource_provider_.get(), child_resource_provider_.get(), @@ -2509,7 +2511,7 @@ CreateFullscreenOpaqueQuad(resource_provider_.get(), pass->shared_quad_state_list.back(), pass.get()); - RenderPassList pass_list; + AggregatedRenderPassList pass_list; pass_list.push_back(std::move(pass)); EXPECT_CALL(*renderer_, DoDrawQuad(_, _)).Times(0); @@ -2531,7 +2533,7 @@ // Draw one frame to make sure output surface is reshaped before tests. DrawEmptyFrame(); - std::unique_ptr<RenderPass> pass = CreateRenderPass(); + auto pass = CreateRenderPass(); CreateFullscreenCandidateQuad( resource_provider_.get(), child_resource_provider_.get(), @@ -2542,7 +2544,7 @@ CreateFullscreenOpaqueQuad(resource_provider_.get(), pass->shared_quad_state_list.back(), pass.get()); - RenderPassList pass_list; + AggregatedRenderPassList pass_list; pass_list.push_back(std::move(pass)); output_surface_->set_is_displayed_as_overlay_plane(true); @@ -2577,8 +2579,8 @@ ResourceId mapped_resource2 = resource_map[resource2]; ResourceId mapped_resource3 = resource_map[resource3]; - std::unique_ptr<RenderPass> pass = CreateRenderPass(); - RenderPassList pass_list; + auto pass = CreateRenderPass(); + AggregatedRenderPassList pass_list; pass_list.push_back(std::move(pass)); DirectRenderer::DrawingFrame frame1; @@ -2768,8 +2770,8 @@ ResourceId mapped_resource2 = resource_map[resource2]; ResourceId mapped_resource3 = resource_map[resource3]; - std::unique_ptr<RenderPass> pass = CreateRenderPass(); - RenderPassList pass_list; + auto pass = CreateRenderPass(); + AggregatedRenderPassList pass_list; pass_list.push_back(std::move(pass)); DirectRenderer::DrawingFrame frame1; @@ -2871,7 +2873,7 @@ CALayerOverlayTest::SetUp(); pass_list_.push_back(CreateRenderPass()); pass_ = pass_list_.back().get(); - quad_ = pass_->CreateAndAppendDrawQuad<RenderPassDrawQuad>(); + quad_ = pass_->CreateAndAppendDrawQuad<AggregatedRenderPassDrawQuad>(); render_pass_id_ = 3; } @@ -2881,9 +2883,9 @@ render_pass_filters_, render_pass_backdrop_filters_, nullity, &ca_layer_list_, &damage_rect_, &content_bounds_); } - RenderPassList pass_list_; - RenderPass* pass_; - RenderPassDrawQuad* quad_; + AggregatedRenderPassList pass_list_; + AggregatedRenderPass* pass_; + AggregatedRenderPassDrawQuad* quad_; int render_pass_id_; cc::FilterOperations filters_; cc::FilterOperations backdrop_filters_; @@ -2892,7 +2894,7 @@ CALayerOverlayList ca_layer_list_; }; -TEST_F(CALayerOverlayRPDQTest, RenderPassDrawQuadNoFilters) { +TEST_F(CALayerOverlayRPDQTest, AggregatedRenderPassDrawQuadNoFilters) { quad_->SetNew(pass_->shared_quad_state_list.back(), kOverlayRect, kOverlayRect, render_pass_id_, 0, gfx::RectF(), gfx::Size(), gfx::Vector2dF(1, 1), gfx::PointF(), gfx::RectF(), false, 1.0f); @@ -2901,7 +2903,7 @@ EXPECT_EQ(1U, ca_layer_list_.size()); } -TEST_F(CALayerOverlayRPDQTest, RenderPassDrawQuadAllValidFilters) { +TEST_F(CALayerOverlayRPDQTest, AggregatedRenderPassDrawQuadAllValidFilters) { filters_.Append(cc::FilterOperation::CreateGrayscaleFilter(0.1f)); filters_.Append(cc::FilterOperation::CreateSepiaFilter(0.2f)); filters_.Append(cc::FilterOperation::CreateSaturateFilter(0.3f)); @@ -2922,7 +2924,7 @@ EXPECT_EQ(1U, ca_layer_list_.size()); } -TEST_F(CALayerOverlayRPDQTest, RenderPassDrawQuadOpacityFilterScale) { +TEST_F(CALayerOverlayRPDQTest, AggregatedRenderPassDrawQuadOpacityFilterScale) { filters_.Append(cc::FilterOperation::CreateOpacityFilter(0.8f)); render_pass_filters_[render_pass_id_] = &filters_; quad_->SetNew(pass_->shared_quad_state_list.back(), kOverlayRect, @@ -2932,7 +2934,7 @@ EXPECT_EQ(1U, ca_layer_list_.size()); } -TEST_F(CALayerOverlayRPDQTest, RenderPassDrawQuadBlurFilterScale) { +TEST_F(CALayerOverlayRPDQTest, AggregatedRenderPassDrawQuadBlurFilterScale) { filters_.Append(cc::FilterOperation::CreateBlurFilter(0.8f)); render_pass_filters_[render_pass_id_] = &filters_; quad_->SetNew(pass_->shared_quad_state_list.back(), kOverlayRect, @@ -2942,7 +2944,8 @@ EXPECT_EQ(1U, ca_layer_list_.size()); } -TEST_F(CALayerOverlayRPDQTest, RenderPassDrawQuadDropShadowFilterScale) { +TEST_F(CALayerOverlayRPDQTest, + AggregatedRenderPassDrawQuadDropShadowFilterScale) { filters_.Append(cc::FilterOperation::CreateDropShadowFilter( gfx::Point(10, 20), 1.0f, SK_ColorGREEN)); render_pass_filters_[render_pass_id_] = &filters_; @@ -2953,7 +2956,7 @@ EXPECT_EQ(1U, ca_layer_list_.size()); } -TEST_F(CALayerOverlayRPDQTest, RenderPassDrawQuadBackgroundFilter) { +TEST_F(CALayerOverlayRPDQTest, AggregatedRenderPassDrawQuadBackgroundFilter) { backdrop_filters_.Append(cc::FilterOperation::CreateGrayscaleFilter(0.1f)); render_pass_backdrop_filters_[render_pass_id_] = &backdrop_filters_; quad_->SetNew(pass_->shared_quad_state_list.back(), kOverlayRect, @@ -2963,7 +2966,7 @@ EXPECT_EQ(0U, ca_layer_list_.size()); } -TEST_F(CALayerOverlayRPDQTest, RenderPassDrawQuadMask) { +TEST_F(CALayerOverlayRPDQTest, AggregatedRenderPassDrawQuadMask) { quad_->SetNew(pass_->shared_quad_state_list.back(), kOverlayRect, kOverlayRect, render_pass_id_, 2, gfx::RectF(), gfx::Size(), gfx::Vector2dF(1, 1), gfx::PointF(), gfx::RectF(), false, 1.0f); @@ -2971,7 +2974,7 @@ EXPECT_EQ(1U, ca_layer_list_.size()); } -TEST_F(CALayerOverlayRPDQTest, RenderPassDrawQuadUnsupportedFilter) { +TEST_F(CALayerOverlayRPDQTest, AggregatedRenderPassDrawQuadUnsupportedFilter) { filters_.Append(cc::FilterOperation::CreateZoomFilter(0.9f, 1)); render_pass_filters_[render_pass_id_] = &filters_; quad_->SetNew(pass_->shared_quad_state_list.back(), kOverlayRect, @@ -2986,7 +2989,7 @@ int count = 35; for (int i = 0; i < count; ++i) { - auto* quad = pass_->CreateAndAppendDrawQuad<RenderPassDrawQuad>(); + auto* quad = pass_->CreateAndAppendDrawQuad<AggregatedRenderPassDrawQuad>(); quad->SetNew(pass_->shared_quad_state_list.back(), kOverlayRect, kOverlayRect, render_pass_id_, 2, gfx::RectF(), gfx::Size(), gfx::Vector2dF(1, 1), gfx::PointF(), gfx::RectF(), false, @@ -3000,7 +3003,7 @@ void AddQuad(gfx::Rect quad_rect, const gfx::Transform& quad_to_target_transform, - RenderPass* render_pass) { + AggregatedRenderPass* render_pass) { SharedQuadState* quad_state = render_pass->CreateAndAppendSharedQuadState(); quad_state->SetAll( @@ -3030,7 +3033,8 @@ using OverlayCandidateTest = testing::Test; TEST_F(OverlayCandidateTest, IsOccluded) { - std::unique_ptr<RenderPass> render_pass = RenderPass::Create(); + std::unique_ptr<AggregatedRenderPass> render_pass = + std::make_unique<AggregatedRenderPass>(); gfx::Transform identity; identity.MakeIdentity(); @@ -3061,7 +3065,8 @@ } TEST_F(OverlayCandidateTest, IsOccludedScaled) { - std::unique_ptr<RenderPass> render_pass = RenderPass::Create(); + std::unique_ptr<AggregatedRenderPass> render_pass = + std::make_unique<AggregatedRenderPass>(); gfx::Transform quad_to_target_transform; quad_to_target_transform.Scale(1.6, 1.6);
diff --git a/components/viz/service/display/render_pass_id_remapper.cc b/components/viz/service/display/render_pass_id_remapper.cc index b87b3630..3098370 100644 --- a/components/viz/service/display/render_pass_id_remapper.cc +++ b/components/viz/service/display/render_pass_id_remapper.cc
@@ -7,6 +7,7 @@ #include <utility> #include "base/containers/flat_map.h" +#include "components/viz/common/quads/aggregated_render_pass.h" #include "components/viz/common/quads/render_pass.h" #include "components/viz/common/surfaces/surface_id.h" @@ -16,8 +17,9 @@ RenderPassIdRemapper::~RenderPassIdRemapper() = default; -RenderPassId RenderPassIdRemapper::Remap(RenderPassId surface_local_pass_id, - const SurfaceId& surface_id) { +AggregatedRenderPassId RenderPassIdRemapper::Remap( + RenderPassId surface_local_pass_id, + const SurfaceId& surface_id) { auto key = std::make_pair(surface_id, surface_local_pass_id); auto it = render_pass_allocator_map_.find(key); if (it != render_pass_allocator_map_.end()) { @@ -31,7 +33,7 @@ return render_pass_info.id; } -RenderPassId RenderPassIdRemapper::NextAvailableId() { +AggregatedRenderPassId RenderPassIdRemapper::NextAvailableId() { return render_pass_id_generator_.GenerateNextId(); }
diff --git a/components/viz/service/display/render_pass_id_remapper.h b/components/viz/service/display/render_pass_id_remapper.h index 395898d..0c91b60 100644 --- a/components/viz/service/display/render_pass_id_remapper.h +++ b/components/viz/service/display/render_pass_id_remapper.h
@@ -8,6 +8,7 @@ #include <utility> #include "base/containers/flat_map.h" +#include "components/viz/common/quads/aggregated_render_pass.h" #include "components/viz/common/quads/render_pass.h" #include "components/viz/common/surfaces/surface_id.h" @@ -23,9 +24,9 @@ RenderPassIdRemapper& operator=(const RenderPassIdRemapper&) = delete; - RenderPassId Remap(RenderPassId surface_local_pass_id, - const SurfaceId& surface_id); - RenderPassId NextAvailableId(); + AggregatedRenderPassId Remap(RenderPassId surface_local_pass_id, + const SurfaceId& surface_id); + AggregatedRenderPassId NextAvailableId(); void ClearUnusedMappings(); @@ -38,14 +39,14 @@ RenderPassInfo& operator=(const RenderPassInfo& other); // This is the id the pass is mapped to. - RenderPassId id; + AggregatedRenderPassId id; // This is true if the pass was used in the last aggregated frame. bool in_use = true; }; base::flat_map<std::pair<SurfaceId, RenderPassId>, RenderPassInfo> render_pass_allocator_map_; - RenderPassId::Generator render_pass_id_generator_; + AggregatedRenderPassId::Generator render_pass_id_generator_; }; } // namespace viz
diff --git a/components/viz/service/display/renderer_perftest.cc b/components/viz/service/display/renderer_perftest.cc index 37e6ded9..70835572 100644 --- a/components/viz/service/display/renderer_perftest.cc +++ b/components/viz/service/display/renderer_perftest.cc
@@ -97,8 +97,9 @@ WaitForSwapDisplayClient() = default; void DisplayOutputSurfaceLost() override {} - void DisplayWillDrawAndSwap(bool will_draw_and_swap, - RenderPassList* render_passes) override {} + void DisplayWillDrawAndSwap( + bool will_draw_and_swap, + AggregatedRenderPassList* render_passes) override {} void DisplayDidDrawAndSwap() override {} void DisplayDidReceiveCALayerParams( const gfx::CALayerParams& ca_layer_params) override {} @@ -668,7 +669,7 @@ timer_.Reset(); do { RenderPassList local_list; - RenderPass::CopyAll(render_pass_list, &local_list); + RenderPass::CopyAllForTest(render_pass_list, &local_list); DrawFrame(std::move(local_list)); client_.WaitForSwap(); timer_.NextLap();
diff --git a/components/viz/service/display/renderer_pixeltest.cc b/components/viz/service/display/renderer_pixeltest.cc index 217bec6..3a5de3a 100644 --- a/components/viz/service/display/renderer_pixeltest.cc +++ b/components/viz/service/display/renderer_pixeltest.cc
@@ -114,9 +114,10 @@ std::move(release_callback)); } -std::unique_ptr<RenderPass> CreateTestRootRenderPass(RenderPassId id, - const gfx::Rect& rect) { - std::unique_ptr<RenderPass> pass = RenderPass::Create(); +std::unique_ptr<AggregatedRenderPass> CreateTestRootRenderPass( + AggregatedRenderPassId id, + const gfx::Rect& rect) { + auto pass = std::make_unique<AggregatedRenderPass>(); const gfx::Rect output_rect = rect; const gfx::Rect damage_rect = rect; const gfx::Transform transform_to_root_target; @@ -124,11 +125,11 @@ return pass; } -std::unique_ptr<RenderPass> CreateTestRenderPass( - RenderPassId id, +std::unique_ptr<AggregatedRenderPass> CreateTestRenderPass( + AggregatedRenderPassId id, const gfx::Rect& rect, const gfx::Transform& transform_to_root_target) { - std::unique_ptr<RenderPass> pass = RenderPass::Create(); + auto pass = std::make_unique<AggregatedRenderPass>(); const gfx::Rect output_rect = rect; const gfx::Rect damage_rect = rect; pass->SetNew(id, output_rect, damage_rect, transform_to_root_target); @@ -138,7 +139,7 @@ SharedQuadState* CreateTestSharedQuadState( gfx::Transform quad_to_target_transform, const gfx::Rect& rect, - RenderPass* render_pass, + AggregatedRenderPass* render_pass, const gfx::RRectF& rrect) { const gfx::Rect layer_rect = rect; const gfx::Rect visible_layer_rect = rect; @@ -161,7 +162,7 @@ gfx::Transform quad_to_target_transform, const gfx::Rect& rect, const gfx::Rect& clip_rect, - RenderPass* render_pass) { + AggregatedRenderPass* render_pass) { const gfx::Rect layer_rect = rect; const gfx::Rect visible_layer_rect = clip_rect; const bool is_clipped = true; @@ -179,9 +180,10 @@ void CreateTestRenderPassDrawQuad(const SharedQuadState* shared_state, const gfx::Rect& rect, - RenderPassId pass_id, - RenderPass* render_pass) { - auto* quad = render_pass->CreateAndAppendDrawQuad<RenderPassDrawQuad>(); + AggregatedRenderPassId pass_id, + AggregatedRenderPass* render_pass) { + auto* quad = + render_pass->CreateAndAppendDrawQuad<AggregatedRenderPassDrawQuad>(); quad->SetNew(shared_state, rect, rect, pass_id, 0, // mask_resource_id gfx::RectF(), // mask_uv_rect @@ -214,7 +216,7 @@ ClientResourceProvider* child_resource_provider, SharedBitmapManager* shared_bitmap_manager, scoped_refptr<ContextProvider> child_context_provider, - RenderPass* render_pass) { + AggregatedRenderPass* render_pass) { SkPMColor pixel_color_one = premultiplied_alpha ? SkPreMultiplyColor(texel_color_one) @@ -296,7 +298,7 @@ ClientResourceProvider* child_resource_provider, SharedBitmapManager* shared_bitmap_manager, scoped_refptr<ContextProvider> child_context_provider, - RenderPass* render_pass) { + AggregatedRenderPass* render_pass) { SkPMColor pixel_color = premultiplied_alpha ? SkPreMultiplyColor(texel_color) : SkPackARGB32NoCheck(SkColorGetA(texel_color), @@ -355,7 +357,7 @@ ClientResourceProvider* child_resource_provider, SharedBitmapManager* shared_bitmap_manager, scoped_refptr<ContextProvider> child_context_provider, - RenderPass* render_pass) { + AggregatedRenderPass* render_pass) { float vertex_opacity[4] = {1.0f, 1.0f, 1.0f, 1.0f}; CreateTestTextureDrawQuad(gpu_resource, rect, texel_color, vertex_opacity, background_color, premultiplied_alpha, shared_state, @@ -369,7 +371,7 @@ scoped_refptr<media::VideoFrame> video_frame, uint8_t alpha_value, const gfx::RectF& tex_coord_rect, - RenderPass* render_pass, + AggregatedRenderPass* render_pass, media::VideoResourceUpdater* video_resource_updater, const gfx::Rect& rect, const gfx::Rect& visible_rect, @@ -495,7 +497,7 @@ const SharedQuadState* shared_state, scoped_refptr<media::VideoFrame> video_frame, const gfx::RectF& tex_coord_rect, - RenderPass* render_pass, + AggregatedRenderPass* render_pass, media::VideoResourceUpdater* video_resource_updater, const gfx::Rect& rect, const gfx::Rect& visible_rect, @@ -581,7 +583,7 @@ bool is_transparent, bool highbit, const gfx::RectF& tex_coord_rect, - RenderPass* render_pass, + AggregatedRenderPass* render_pass, media::VideoResourceUpdater* video_resource_updater, const gfx::Rect& rect, const gfx::Rect& visible_rect, @@ -646,7 +648,7 @@ uint8_t y_foreground, uint8_t u_foreground, uint8_t v_foreground, - RenderPass* render_pass, + AggregatedRenderPass* render_pass, media::VideoResourceUpdater* video_resource_updater, DisplayResourceProvider* resource_provider, ClientResourceProvider* child_resource_provider, @@ -705,7 +707,7 @@ uint8_t y, uint8_t u, uint8_t v, - RenderPass* render_pass, + AggregatedRenderPass* render_pass, media::VideoResourceUpdater* video_resource_updater, const gfx::Rect& rect, const gfx::Rect& visible_rect, @@ -742,7 +744,7 @@ uint8_t y, uint8_t u, uint8_t v, - RenderPass* render_pass, + AggregatedRenderPass* render_pass, media::VideoResourceUpdater* video_resource_updater, const gfx::Rect& rect, const gfx::Rect& visible_rect, @@ -799,7 +801,7 @@ const gfx::RectF& tex_coord_rect, uint8_t g_foreground, uint8_t g_background, - RenderPass* render_pass, + AggregatedRenderPass* render_pass, media::VideoResourceUpdater* video_resource_updater, const gfx::Rect& rect, const gfx::Rect& visible_rect, @@ -858,7 +860,7 @@ SkColor back_color, bool needs_blending, bool force_aa_off, - RenderPass* pass) { + AggregatedRenderPass* pass) { gfx::Transform front_quad_to_target_transform; front_quad_to_target_transform.Translate(50, 50); front_quad_to_target_transform.Scale(0.5f + 1.0f / (rect.width() * 2.0f), @@ -920,8 +922,8 @@ TEST_P(RendererPixelTest, SimpleGreenRect) { gfx::Rect rect(this->device_viewport_size_); - RenderPassId id{1}; - std::unique_ptr<RenderPass> pass = CreateTestRootRenderPass(id, rect); + AggregatedRenderPassId id{1}; + auto pass = CreateTestRootRenderPass(id, rect); SharedQuadState* shared_state = CreateTestSharedQuadState( gfx::Transform(), rect, pass.get(), gfx::RRectF()); @@ -929,7 +931,7 @@ auto* color_quad = pass->CreateAndAppendDrawQuad<SolidColorDrawQuad>(); color_quad->SetNew(shared_state, rect, rect, SK_ColorGREEN, false); - RenderPassList pass_list; + AggregatedRenderPassList pass_list; pass_list.push_back(std::move(pass)); EXPECT_TRUE(this->RunPixelTest(&pass_list, @@ -941,8 +943,8 @@ gfx::Rect rect(this->device_viewport_size_); gfx::Rect small_rect(100, 100); - RenderPassId child_id{2}; - std::unique_ptr<RenderPass> child_pass = + AggregatedRenderPassId child_id{2}; + auto child_pass = CreateTestRenderPass(child_id, small_rect, gfx::Transform()); SharedQuadState* child_shared_state = CreateTestSharedQuadState( @@ -951,9 +953,8 @@ auto* color_quad = child_pass->CreateAndAppendDrawQuad<SolidColorDrawQuad>(); color_quad->SetNew(child_shared_state, rect, rect, SK_ColorGREEN, false); - RenderPassId root_id{1}; - std::unique_ptr<RenderPass> root_pass = - CreateTestRenderPass(root_id, rect, gfx::Transform()); + AggregatedRenderPassId root_id{1}; + auto root_pass = CreateTestRenderPass(root_id, rect, gfx::Transform()); SharedQuadState* root_shared_state = CreateTestSharedQuadState( gfx::Transform(), rect, root_pass.get(), gfx::RRectF()); @@ -961,9 +962,9 @@ CreateTestRenderPassDrawQuad(root_shared_state, small_rect, child_id, root_pass.get()); - RenderPass* child_pass_ptr = child_pass.get(); + auto* child_pass_ptr = child_pass.get(); - RenderPassList pass_list; + AggregatedRenderPassList pass_list; pass_list.push_back(std::move(child_pass)); pass_list.push_back(std::move(root_pass)); @@ -976,8 +977,8 @@ TEST_P(RendererPixelTest, PremultipliedTextureWithoutBackground) { gfx::Rect rect(this->device_viewport_size_); - RenderPassId id{1}; - std::unique_ptr<RenderPass> pass = CreateTestRootRenderPass(id, rect); + AggregatedRenderPassId id{1}; + auto pass = CreateTestRootRenderPass(id, rect); SharedQuadState* shared_state = CreateTestSharedQuadState( gfx::Transform(), rect, pass.get(), gfx::RRectF()); @@ -994,7 +995,7 @@ auto* color_quad = pass->CreateAndAppendDrawQuad<SolidColorDrawQuad>(); color_quad->SetNew(shared_state, rect, rect, SK_ColorWHITE, false); - RenderPassList pass_list; + AggregatedRenderPassList pass_list; pass_list.push_back(std::move(pass)); EXPECT_TRUE(this->RunPixelTest( @@ -1005,8 +1006,8 @@ TEST_P(RendererPixelTest, PremultipliedTextureWithBackground) { gfx::Rect rect(this->device_viewport_size_); - RenderPassId id{1}; - std::unique_ptr<RenderPass> pass = CreateTestRootRenderPass(id, rect); + AggregatedRenderPassId id{1}; + auto pass = CreateTestRootRenderPass(id, rect); SharedQuadState* texture_quad_state = CreateTestSharedQuadState( gfx::Transform(), rect, pass.get(), gfx::RRectF()); @@ -1026,7 +1027,7 @@ auto* color_quad = pass->CreateAndAppendDrawQuad<SolidColorDrawQuad>(); color_quad->SetNew(color_quad_state, rect, rect, SK_ColorWHITE, false); - RenderPassList pass_list; + AggregatedRenderPassList pass_list; pass_list.push_back(std::move(pass)); EXPECT_TRUE(this->RunPixelTest( @@ -1037,8 +1038,8 @@ TEST_P(RendererPixelTest, TextureDrawQuadVisibleRectInsetTopLeft) { gfx::Rect rect(this->device_viewport_size_); - RenderPassId id{1}; - std::unique_ptr<RenderPass> pass = CreateTestRootRenderPass(id, rect); + AggregatedRenderPassId id{1}; + auto pass = CreateTestRootRenderPass(id, rect); SharedQuadState* texture_quad_state = CreateTestSharedQuadState( gfx::Transform(), rect, pass.get(), gfx::RRectF()); @@ -1060,7 +1061,7 @@ auto* color_quad = pass->CreateAndAppendDrawQuad<SolidColorDrawQuad>(); color_quad->SetNew(color_quad_state, rect, rect, SK_ColorWHITE, false); - RenderPassList pass_list; + AggregatedRenderPassList pass_list; pass_list.push_back(std::move(pass)); EXPECT_TRUE(this->RunPixelTest( @@ -1074,8 +1075,8 @@ TextureDrawQuadTranslatedAndVisibleRectInsetTopLeftAndCustomUV) { gfx::Rect rect(this->device_viewport_size_); - RenderPassId id{1}; - std::unique_ptr<RenderPass> pass = CreateTestRootRenderPass(id, rect); + AggregatedRenderPassId id{1}; + auto pass = CreateTestRootRenderPass(id, rect); SharedQuadState* texture_quad_state = CreateTestSharedQuadState( gfx::Transform(), rect, pass.get(), gfx::RRectF()); @@ -1103,7 +1104,7 @@ auto* color_quad = pass->CreateAndAppendDrawQuad<SolidColorDrawQuad>(); color_quad->SetNew(color_quad_state, rect, rect, SK_ColorWHITE, false); - RenderPassList pass_list; + AggregatedRenderPassList pass_list; pass_list.push_back(std::move(pass)); EXPECT_TRUE(this->RunPixelTest( @@ -1115,8 +1116,8 @@ TEST_P(RendererPixelTest, TextureDrawQuadVisibleRectInsetBottomRight) { gfx::Rect rect(this->device_viewport_size_); - RenderPassId id{1}; - std::unique_ptr<RenderPass> pass = CreateTestRootRenderPass(id, rect); + AggregatedRenderPassId id{1}; + auto pass = CreateTestRootRenderPass(id, rect); SharedQuadState* texture_quad_state = CreateTestSharedQuadState( gfx::Transform(), rect, pass.get(), gfx::RRectF()); @@ -1138,7 +1139,7 @@ auto* color_quad = pass->CreateAndAppendDrawQuad<SolidColorDrawQuad>(); color_quad->SetNew(color_quad_state, rect, rect, SK_ColorWHITE, false); - RenderPassList pass_list; + AggregatedRenderPassList pass_list; pass_list.push_back(std::move(pass)); EXPECT_TRUE(this->RunPixelTest( @@ -1149,8 +1150,8 @@ TEST_P(GPURendererPixelTest, SolidColorBlend) { gfx::Rect rect(this->device_viewport_size_); - RenderPassId id{1}; - std::unique_ptr<RenderPass> pass = CreateTestRootRenderPass(id, rect); + AggregatedRenderPassId id{1}; + auto pass = CreateTestRootRenderPass(id, rect); pass->has_transparent_background = false; SharedQuadState* shared_state = CreateTestSharedQuadState( @@ -1171,7 +1172,7 @@ background_color, false); // Result should be r=16, g=14, b=16. - RenderPassList pass_list; + AggregatedRenderPassList pass_list; pass_list.push_back(std::move(pass)); EXPECT_TRUE(this->RunPixelTest( @@ -1182,8 +1183,8 @@ TEST_P(GPURendererPixelTest, SolidColorWithTemperature) { gfx::Rect rect(this->device_viewport_size_); - RenderPassId id{1}; - std::unique_ptr<RenderPass> pass = CreateTestRootRenderPass(id, rect); + AggregatedRenderPassId id{1}; + auto pass = CreateTestRootRenderPass(id, rect); SharedQuadState* shared_state = CreateTestSharedQuadState( gfx::Transform(), rect, pass.get(), gfx::RRectF()); @@ -1191,7 +1192,7 @@ auto* color_quad = pass->CreateAndAppendDrawQuad<SolidColorDrawQuad>(); color_quad->SetNew(shared_state, rect, rect, SK_ColorYELLOW, false); - RenderPassList pass_list; + AggregatedRenderPassList pass_list; pass_list.push_back(std::move(pass)); SkMatrix44 color_matrix(SkMatrix44::kIdentity_Constructor); @@ -1207,22 +1208,22 @@ TEST_P(GPURendererPixelTest, SolidColorWithTemperatureNonRootRenderPass) { // Create a root and a child passes with two different solid color quads. - RenderPassList render_passes_in_draw_order; + AggregatedRenderPassList render_passes_in_draw_order; gfx::Rect viewport_rect(this->device_viewport_size_); gfx::Rect root_rect(0, 0, viewport_rect.width(), viewport_rect.height() / 2); gfx::Rect child_rect(0, root_rect.bottom(), viewport_rect.width(), root_rect.height()); // Child pass. - RenderPassId child_pass_id{2}; - RenderPass* child_pass = cc::AddRenderPass( + AggregatedRenderPassId child_pass_id{2}; + AggregatedRenderPass* child_pass = cc::AddRenderPass( &render_passes_in_draw_order, child_pass_id, viewport_rect, gfx::Transform(), cc::FilterOperations()); cc::AddQuad(child_pass, child_rect, SK_ColorGREEN); // Root pass. - RenderPassId root_pass_id{1}; - RenderPass* root_pass = cc::AddRenderPass( + AggregatedRenderPassId root_pass_id{1}; + AggregatedRenderPass* root_pass = cc::AddRenderPass( &render_passes_in_draw_order, root_pass_id, viewport_rect, gfx::Transform(), cc::FilterOperations()); cc::AddQuad(root_pass, root_rect, SK_ColorYELLOW); @@ -1250,8 +1251,8 @@ PremultipliedTextureWithBackgroundAndVertexOpacity) { gfx::Rect rect(this->device_viewport_size_); - RenderPassId id{1}; - std::unique_ptr<RenderPass> pass = CreateTestRootRenderPass(id, rect); + AggregatedRenderPassId id{1}; + auto pass = CreateTestRootRenderPass(id, rect); SharedQuadState* texture_quad_state = CreateTestSharedQuadState( gfx::Transform(), rect, pass.get(), gfx::RRectF()); @@ -1273,7 +1274,7 @@ auto* color_quad = pass->CreateAndAppendDrawQuad<SolidColorDrawQuad>(); color_quad->SetNew(color_quad_state, rect, rect, SK_ColorWHITE, false); - RenderPassList pass_list; + AggregatedRenderPassList pass_list; pass_list.push_back(std::move(pass)); EXPECT_TRUE(this->RunPixelTest( @@ -1296,7 +1297,7 @@ quad_rect_ = gfx::Rect(0, 0, this->device_viewport_size_.width(), this->device_viewport_size_.height() / 2.0); - RenderPassId id{1}; + AggregatedRenderPassId id{1}; render_pass_ = CreateTestRootRenderPass(id, viewport_rect_); // Create the front quad rotated on the Z and Y axis. @@ -1337,12 +1338,12 @@ return render_pass_->CreateAndAppendDrawQuad<T>(); } - std::unique_ptr<RenderPass> render_pass_; + std::unique_ptr<AggregatedRenderPass> render_pass_; gfx::Rect viewport_rect_; SharedQuadState* front_quad_state_; SharedQuadState* back_quad_state_; gfx::Rect quad_rect_; - RenderPassList pass_list_; + AggregatedRenderPassList pass_list_; }; INSTANTIATE_TEST_SUITE_P(, @@ -1539,13 +1540,13 @@ TEST_P(IntersectingQuadPixelTest, RenderPassQuads) { this->SetupQuadStateAndRenderPass(); - RenderPassId child_pass_id1{2}; - RenderPassId child_pass_id2{3}; - std::unique_ptr<RenderPass> child_pass1 = + AggregatedRenderPassId child_pass_id1{2}; + AggregatedRenderPassId child_pass_id2{3}; + auto child_pass1 = CreateTestRenderPass(child_pass_id1, this->quad_rect_, gfx::Transform()); SharedQuadState* child1_quad_state = CreateTestSharedQuadState( gfx::Transform(), this->quad_rect_, child_pass1.get(), gfx::RRectF()); - std::unique_ptr<RenderPass> child_pass2 = + auto child_pass2 = CreateTestRenderPass(child_pass_id2, this->quad_rect_, gfx::Transform()); SharedQuadState* child2_quad_state = CreateTestSharedQuadState( gfx::Transform(), this->quad_rect_, child_pass2.get(), gfx::RRectF()); @@ -1638,8 +1639,8 @@ TEST_P(GPURendererPixelTest, NonPremultipliedTextureWithoutBackground) { gfx::Rect rect(this->device_viewport_size_); - RenderPassId id{1}; - std::unique_ptr<RenderPass> pass = CreateTestRootRenderPass(id, rect); + AggregatedRenderPassId id{1}; + auto pass = CreateTestRootRenderPass(id, rect); SharedQuadState* shared_state = CreateTestSharedQuadState( gfx::Transform(), rect, pass.get(), gfx::RRectF()); @@ -1656,7 +1657,7 @@ auto* color_quad = pass->CreateAndAppendDrawQuad<SolidColorDrawQuad>(); color_quad->SetNew(shared_state, rect, rect, SK_ColorWHITE, false); - RenderPassList pass_list; + AggregatedRenderPassList pass_list; pass_list.push_back(std::move(pass)); EXPECT_TRUE(this->RunPixelTest( @@ -1668,8 +1669,8 @@ TEST_P(GPURendererPixelTest, NonPremultipliedTextureWithBackground) { gfx::Rect rect(this->device_viewport_size_); - RenderPassId id{1}; - std::unique_ptr<RenderPass> pass = CreateTestRootRenderPass(id, rect); + AggregatedRenderPassId id{1}; + auto pass = CreateTestRootRenderPass(id, rect); SharedQuadState* texture_quad_state = CreateTestSharedQuadState( gfx::Transform(), rect, pass.get(), gfx::RRectF()); @@ -1689,7 +1690,7 @@ auto* color_quad = pass->CreateAndAppendDrawQuad<SolidColorDrawQuad>(); color_quad->SetNew(color_quad_state, rect, rect, SK_ColorWHITE, false); - RenderPassList pass_list; + AggregatedRenderPassList pass_list; pass_list.push_back(std::move(pass)); EXPECT_TRUE(this->RunPixelTest( @@ -1709,11 +1710,11 @@ void CreateEdgeBleedPass(media::VideoPixelFormat format, const gfx::ColorSpace& color_space, - RenderPassList* pass_list) { + AggregatedRenderPassList* pass_list) { gfx::Rect rect(200, 200); - RenderPassId id{1}; - std::unique_ptr<RenderPass> pass = CreateTestRootRenderPass(id, rect); + AggregatedRenderPassId id{1}; + auto pass = CreateTestRootRenderPass(id, rect); // Scale the video up so that bilinear filtering kicks in to sample more // than just nearest neighbor would. @@ -1784,8 +1785,8 @@ TEST_P(VideoRendererPixelHiLoTest, SimpleYUVRect) { gfx::Rect rect(this->device_viewport_size_); - RenderPassId id{1}; - std::unique_ptr<RenderPass> pass = CreateTestRootRenderPass(id, rect); + AggregatedRenderPassId id{1}; + auto pass = CreateTestRootRenderPass(id, rect); // Set the output color space to match the input primaries and transfer. this->display_color_spaces_ = kRec601DisplayColorSpaces; @@ -1799,7 +1800,7 @@ this->resource_provider_.get(), this->child_resource_provider_.get(), this->child_context_provider_.get()); - RenderPassList pass_list; + AggregatedRenderPassList pass_list; pass_list.push_back(std::move(pass)); EXPECT_TRUE(this->RunPixelTest( @@ -1812,8 +1813,8 @@ gfx::Rect draw_rect(this->device_viewport_size_.width() * 1.5, this->device_viewport_size_.height() * 1.5); - RenderPassId id{1}; - std::unique_ptr<RenderPass> pass = CreateTestRootRenderPass(id, viewport); + AggregatedRenderPassId id{1}; + auto pass = CreateTestRootRenderPass(id, viewport); // Set the output color space to match the input primaries and transfer. this->display_color_spaces_ = kRec601DisplayColorSpaces; @@ -1826,7 +1827,7 @@ this->video_resource_updater_.get(), draw_rect, viewport, this->resource_provider_.get(), this->child_resource_provider_.get(), this->child_context_provider_.get()); - RenderPassList pass_list; + AggregatedRenderPassList pass_list; pass_list.push_back(std::move(pass)); EXPECT_TRUE(this->RunPixelTest( @@ -1851,8 +1852,8 @@ TEST_P(VideoRendererPixelTest, OffsetYUVRect) { gfx::Rect rect(this->device_viewport_size_); - RenderPassId id{1}; - std::unique_ptr<RenderPass> pass = CreateTestRootRenderPass(id, rect); + AggregatedRenderPassId id{1}; + auto pass = CreateTestRootRenderPass(id, rect); // Set the output color space to match the input primaries and transfer. this->display_color_spaces_ = kRec601DisplayColorSpaces; @@ -1867,7 +1868,7 @@ this->resource_provider_.get(), this->child_resource_provider_.get(), this->child_context_provider_.get()); - RenderPassList pass_list; + AggregatedRenderPassList pass_list; pass_list.push_back(std::move(pass)); EXPECT_TRUE(this->RunPixelTest( @@ -1878,8 +1879,8 @@ TEST_P(VideoRendererPixelTest, SimpleYUVRectBlack) { gfx::Rect rect(this->device_viewport_size_); - RenderPassId id{1}; - std::unique_ptr<RenderPass> pass = CreateTestRootRenderPass(id, rect); + AggregatedRenderPassId id{1}; + auto pass = CreateTestRootRenderPass(id, rect); // Set the output color space to match the input primaries and transfer. this->display_color_spaces_ = kRec601DisplayColorSpaces; @@ -1894,7 +1895,7 @@ this->resource_provider_.get(), this->child_resource_provider_.get(), this->child_context_provider_.get()); - RenderPassList pass_list; + AggregatedRenderPassList pass_list; pass_list.push_back(std::move(pass)); // If we didn't get black out of the YUV values above, then we probably have a @@ -1907,8 +1908,8 @@ TEST_P(VideoRendererPixelTest, SimpleYUVJRect) { gfx::Rect rect(this->device_viewport_size_); - RenderPassId id{1}; - std::unique_ptr<RenderPass> pass = CreateTestRootRenderPass(id, rect); + AggregatedRenderPassId id{1}; + auto pass = CreateTestRootRenderPass(id, rect); SharedQuadState* shared_state = CreateTestSharedQuadState( gfx::Transform(), rect, pass.get(), gfx::RRectF()); @@ -1921,7 +1922,7 @@ this->resource_provider_.get(), this->child_resource_provider_.get(), this->child_context_provider_.get()); - RenderPassList pass_list; + AggregatedRenderPassList pass_list; pass_list.push_back(std::move(pass)); EXPECT_TRUE(this->RunPixelTest(&pass_list, @@ -1932,8 +1933,8 @@ TEST_P(VideoRendererPixelTest, SimpleNV12JRect) { gfx::Rect rect(this->device_viewport_size_); - RenderPassId id{1}; - std::unique_ptr<RenderPass> pass = CreateTestRootRenderPass(id, rect); + AggregatedRenderPassId id{1}; + auto pass = CreateTestRootRenderPass(id, rect); SharedQuadState* shared_state = CreateTestSharedQuadState( gfx::Transform(), rect, pass.get(), gfx::RRectF()); @@ -1946,7 +1947,7 @@ this->resource_provider_.get(), this->child_resource_provider_.get(), this->child_context_provider_); - RenderPassList pass_list; + AggregatedRenderPassList pass_list; pass_list.push_back(std::move(pass)); EXPECT_TRUE(this->RunPixelTest(&pass_list, @@ -1957,7 +1958,7 @@ // Test that a YUV video doesn't bleed outside of its tex coords when the // tex coord rect is only a partial subrectangle of the coded contents. TEST_P(VideoRendererPixelTest, YUVEdgeBleed) { - RenderPassList pass_list; + AggregatedRenderPassList pass_list; this->CreateEdgeBleedPass(media::PIXEL_FORMAT_I420, gfx::ColorSpace::CreateJpeg(), &pass_list); EXPECT_TRUE(this->RunPixelTest(&pass_list, @@ -1966,7 +1967,7 @@ } TEST_P(VideoRendererPixelTest, YUVAEdgeBleed) { - RenderPassList pass_list; + AggregatedRenderPassList pass_list; this->CreateEdgeBleedPass(media::PIXEL_FORMAT_I420A, gfx::ColorSpace::CreateREC601(), &pass_list); // Set the output color space to match the input primaries and transfer. @@ -1979,8 +1980,8 @@ TEST_P(VideoRendererPixelTest, SimpleYUVJRectGrey) { gfx::Rect rect(this->device_viewport_size_); - RenderPassId id{1}; - std::unique_ptr<RenderPass> pass = CreateTestRootRenderPass(id, rect); + AggregatedRenderPassId id{1}; + auto pass = CreateTestRootRenderPass(id, rect); SharedQuadState* shared_state = CreateTestSharedQuadState( gfx::Transform(), rect, pass.get(), gfx::RRectF()); @@ -1993,7 +1994,7 @@ this->resource_provider_.get(), this->child_resource_provider_.get(), this->child_context_provider_.get()); - RenderPassList pass_list; + AggregatedRenderPassList pass_list; pass_list.push_back(std::move(pass)); EXPECT_TRUE(this->RunPixelTest( @@ -2004,8 +2005,8 @@ TEST_P(VideoRendererPixelTest, SimpleYUVARect) { gfx::Rect rect(this->device_viewport_size_); - RenderPassId id{1}; - std::unique_ptr<RenderPass> pass = CreateTestRootRenderPass(id, rect); + AggregatedRenderPassId id{1}; + auto pass = CreateTestRootRenderPass(id, rect); // Set the output color space to match the input primaries and transfer. this->display_color_spaces_ = kRec601DisplayColorSpaces; @@ -2022,7 +2023,7 @@ auto* color_quad = pass->CreateAndAppendDrawQuad<SolidColorDrawQuad>(); color_quad->SetNew(shared_state, rect, rect, SK_ColorWHITE, false); - RenderPassList pass_list; + AggregatedRenderPassList pass_list; pass_list.push_back(std::move(pass)); EXPECT_TRUE(this->RunPixelTest( @@ -2033,8 +2034,8 @@ TEST_P(VideoRendererPixelTest, FullyTransparentYUVARect) { gfx::Rect rect(this->device_viewport_size_); - RenderPassId id{1}; - std::unique_ptr<RenderPass> pass = CreateTestRootRenderPass(id, rect); + AggregatedRenderPassId id{1}; + auto pass = CreateTestRootRenderPass(id, rect); // Set the output color space to match the input primaries and transfer. this->display_color_spaces_ = kRec601DisplayColorSpaces; @@ -2051,7 +2052,7 @@ auto* color_quad = pass->CreateAndAppendDrawQuad<SolidColorDrawQuad>(); color_quad->SetNew(shared_state, rect, rect, SK_ColorBLACK, false); - RenderPassList pass_list; + AggregatedRenderPassList pass_list; pass_list.push_back(std::move(pass)); EXPECT_TRUE(this->RunPixelTest(&pass_list, @@ -2062,8 +2063,8 @@ TEST_P(VideoRendererPixelTest, TwoColorY16Rect) { gfx::Rect rect(this->device_viewport_size_); - RenderPassId id{1}; - std::unique_ptr<RenderPass> pass = CreateTestRootRenderPass(id, rect); + AggregatedRenderPassId id{1}; + auto pass = CreateTestRootRenderPass(id, rect); SharedQuadState* shared_state = CreateTestSharedQuadState( gfx::Transform(), rect, pass.get(), gfx::RRectF()); @@ -2075,7 +2076,7 @@ this->resource_provider_.get(), this->child_resource_provider_.get(), this->child_context_provider_.get()); - RenderPassList pass_list; + AggregatedRenderPassList pass_list; pass_list.push_back(std::move(pass)); EXPECT_TRUE(this->RunPixelTest( @@ -2088,11 +2089,10 @@ TEST_P(RendererPixelTest, DISABLED_FastPassColorFilterAlpha) { gfx::Rect viewport_rect(this->device_viewport_size_); - RenderPassId root_pass_id{1}; - std::unique_ptr<RenderPass> root_pass = - CreateTestRootRenderPass(root_pass_id, viewport_rect); + AggregatedRenderPassId root_pass_id{1}; + auto root_pass = CreateTestRootRenderPass(root_pass_id, viewport_rect); - RenderPassId child_pass_id{2}; + AggregatedRenderPassId child_pass_id{2}; gfx::Rect pass_rect(this->device_viewport_size_); gfx::Transform transform_to_root; float matrix[20]; @@ -2116,7 +2116,7 @@ sk_make_sp<cc::ColorFilterPaintFilter>(SkColorFilters::Matrix(matrix), nullptr))); - std::unique_ptr<RenderPass> child_pass = + auto child_pass = CreateTestRenderPass(child_pass_id, pass_rect, transform_to_root); child_pass->filters = filters; @@ -2146,13 +2146,13 @@ gfx::Transform(), pass_rect, root_pass.get(), gfx::RRectF()); auto* render_pass_quad = - root_pass->CreateAndAppendDrawQuad<RenderPassDrawQuad>(); + root_pass->CreateAndAppendDrawQuad<AggregatedRenderPassDrawQuad>(); render_pass_quad->SetNew(pass_shared_state, pass_rect, pass_rect, child_pass_id, 0, gfx::RectF(), gfx::Size(), gfx::Vector2dF(), gfx::PointF(), gfx::RectF(pass_rect), false, 1.0f); - RenderPassList pass_list; + AggregatedRenderPassList pass_list; pass_list.push_back(std::move(child_pass)); pass_list.push_back(std::move(root_pass)); @@ -2167,17 +2167,16 @@ TEST_P(RendererPixelTest, DISABLED_FastPassSaturateFilter) { gfx::Rect viewport_rect(this->device_viewport_size_); - RenderPassId root_pass_id{1}; - std::unique_ptr<RenderPass> root_pass = - CreateTestRootRenderPass(root_pass_id, viewport_rect); + AggregatedRenderPassId root_pass_id{1}; + auto root_pass = CreateTestRootRenderPass(root_pass_id, viewport_rect); - RenderPassId child_pass_id{2}; + AggregatedRenderPassId child_pass_id{2}; gfx::Rect pass_rect(this->device_viewport_size_); gfx::Transform transform_to_root; cc::FilterOperations filters; filters.Append(cc::FilterOperation::CreateSaturateFilter(0.5f)); - std::unique_ptr<RenderPass> child_pass = + auto child_pass = CreateTestRenderPass(child_pass_id, pass_rect, transform_to_root); child_pass->filters = filters; @@ -2207,13 +2206,13 @@ gfx::Transform(), pass_rect, root_pass.get(), gfx::RRectF()); auto* render_pass_quad = - root_pass->CreateAndAppendDrawQuad<RenderPassDrawQuad>(); + root_pass->CreateAndAppendDrawQuad<AggregatedRenderPassDrawQuad>(); render_pass_quad->SetNew(pass_shared_state, pass_rect, pass_rect, child_pass_id, 0, gfx::RectF(), gfx::Size(), gfx::Vector2dF(), gfx::PointF(), gfx::RectF(pass_rect), false, 1.0f); - RenderPassList pass_list; + AggregatedRenderPassList pass_list; pass_list.push_back(std::move(child_pass)); pass_list.push_back(std::move(root_pass)); @@ -2227,18 +2226,17 @@ TEST_P(RendererPixelTest, FastPassFilterChain) { gfx::Rect viewport_rect(this->device_viewport_size_); - RenderPassId root_pass_id{1}; - std::unique_ptr<RenderPass> root_pass = - CreateTestRootRenderPass(root_pass_id, viewport_rect); + AggregatedRenderPassId root_pass_id{1}; + auto root_pass = CreateTestRootRenderPass(root_pass_id, viewport_rect); - RenderPassId child_pass_id{2}; + AggregatedRenderPassId child_pass_id{2}; gfx::Rect pass_rect(this->device_viewport_size_); gfx::Transform transform_to_root; cc::FilterOperations filters; filters.Append(cc::FilterOperation::CreateGrayscaleFilter(1.f)); filters.Append(cc::FilterOperation::CreateBrightnessFilter(0.5f)); - std::unique_ptr<RenderPass> child_pass = + auto child_pass = CreateTestRenderPass(child_pass_id, pass_rect, transform_to_root); child_pass->filters = filters; @@ -2268,13 +2266,13 @@ gfx::Transform(), pass_rect, root_pass.get(), gfx::RRectF()); auto* render_pass_quad = - root_pass->CreateAndAppendDrawQuad<RenderPassDrawQuad>(); + root_pass->CreateAndAppendDrawQuad<AggregatedRenderPassDrawQuad>(); render_pass_quad->SetNew(pass_shared_state, pass_rect, pass_rect, child_pass_id, 0, gfx::RectF(), gfx::Size(), gfx::Vector2dF(), gfx::PointF(), gfx::RectF(pass_rect), false, 1.0f); - RenderPassList pass_list; + AggregatedRenderPassList pass_list; pass_list.push_back(std::move(child_pass)); pass_list.push_back(std::move(root_pass)); @@ -2290,11 +2288,10 @@ TEST_P(RendererPixelTest, DISABLED_FastPassColorFilterAlphaTranslation) { gfx::Rect viewport_rect(this->device_viewport_size_); - RenderPassId root_pass_id{1}; - std::unique_ptr<RenderPass> root_pass = - CreateTestRootRenderPass(root_pass_id, viewport_rect); + AggregatedRenderPassId root_pass_id{1}; + auto root_pass = CreateTestRootRenderPass(root_pass_id, viewport_rect); - RenderPassId child_pass_id{2}; + AggregatedRenderPassId child_pass_id{2}; gfx::Rect pass_rect(this->device_viewport_size_); gfx::Transform transform_to_root; float matrix[20]; @@ -2321,7 +2318,7 @@ sk_make_sp<cc::ColorFilterPaintFilter>(SkColorFilters::Matrix(matrix), nullptr))); - std::unique_ptr<RenderPass> child_pass = + auto child_pass = CreateTestRenderPass(child_pass_id, pass_rect, transform_to_root); child_pass->filters = filters; @@ -2351,13 +2348,13 @@ gfx::Transform(), pass_rect, root_pass.get(), gfx::RRectF()); auto* render_pass_quad = - root_pass->CreateAndAppendDrawQuad<RenderPassDrawQuad>(); + root_pass->CreateAndAppendDrawQuad<AggregatedRenderPassDrawQuad>(); render_pass_quad->SetNew(pass_shared_state, pass_rect, pass_rect, child_pass_id, 0, gfx::RectF(), gfx::Size(), gfx::Vector2dF(), gfx::PointF(), gfx::RectF(pass_rect), false, 1.0f); - RenderPassList pass_list; + AggregatedRenderPassList pass_list; pass_list.push_back(std::move(child_pass)); pass_list.push_back(std::move(root_pass)); @@ -2373,14 +2370,13 @@ TEST_P(RendererPixelTest, EnlargedRenderPassTexture) { gfx::Rect viewport_rect(this->device_viewport_size_); - RenderPassId root_pass_id{1}; - std::unique_ptr<RenderPass> root_pass = - CreateTestRootRenderPass(root_pass_id, viewport_rect); + AggregatedRenderPassId root_pass_id{1}; + auto root_pass = CreateTestRootRenderPass(root_pass_id, viewport_rect); - RenderPassId child_pass_id{2}; + AggregatedRenderPassId child_pass_id{2}; gfx::Rect pass_rect(this->device_viewport_size_); gfx::Transform transform_to_root; - std::unique_ptr<RenderPass> child_pass = + auto child_pass = CreateTestRenderPass(child_pass_id, pass_rect, transform_to_root); gfx::Transform quad_to_target_transform; @@ -2402,7 +2398,7 @@ CreateTestRenderPassDrawQuad(pass_shared_state, pass_rect, child_pass_id, root_pass.get()); - RenderPassList pass_list; + AggregatedRenderPassList pass_list; pass_list.push_back(std::move(child_pass)); pass_list.push_back(std::move(root_pass)); @@ -2416,14 +2412,13 @@ TEST_P(RendererPixelTest, EnlargedRenderPassTextureWithAntiAliasing) { gfx::Rect viewport_rect(this->device_viewport_size_); - RenderPassId root_pass_id{1}; - std::unique_ptr<RenderPass> root_pass = - CreateTestRootRenderPass(root_pass_id, viewport_rect); + AggregatedRenderPassId root_pass_id{1}; + auto root_pass = CreateTestRootRenderPass(root_pass_id, viewport_rect); - RenderPassId child_pass_id{2}; + AggregatedRenderPassId child_pass_id{2}; gfx::Rect pass_rect(this->device_viewport_size_); gfx::Transform transform_to_root; - std::unique_ptr<RenderPass> child_pass = + auto child_pass = CreateTestRenderPass(child_pass_id, pass_rect, transform_to_root); gfx::Transform quad_to_target_transform; @@ -2455,7 +2450,7 @@ gfx::Rect(this->device_viewport_size_), SK_ColorWHITE, false); - RenderPassList pass_list; + AggregatedRenderPassList pass_list; pass_list.push_back(std::move(child_pass)); pass_list.push_back(std::move(root_pass)); @@ -2472,15 +2467,14 @@ TEST_P(RendererPixelTest, RenderPassAndMaskWithPartialQuad) { gfx::Rect viewport_rect(this->device_viewport_size_); - RenderPassId root_pass_id{1}; - std::unique_ptr<RenderPass> root_pass = - CreateTestRootRenderPass(root_pass_id, viewport_rect); + AggregatedRenderPassId root_pass_id{1}; + auto root_pass = CreateTestRootRenderPass(root_pass_id, viewport_rect); SharedQuadState* root_pass_shared_state = CreateTestSharedQuadState( gfx::Transform(), viewport_rect, root_pass.get(), gfx::RRectF()); - RenderPassId child_pass_id{2}; + AggregatedRenderPassId child_pass_id{2}; gfx::Transform transform_to_root; - std::unique_ptr<RenderPass> child_pass = + auto child_pass = CreateTestRenderPass(child_pass_id, viewport_rect, transform_to_root); SharedQuadState* child_pass_shared_state = CreateTestSharedQuadState( gfx::Transform(), viewport_rect, child_pass.get(), gfx::RRectF()); @@ -2529,7 +2523,7 @@ this->child_context_provider_.get()); ResourceId mapped_mask_resource_id = resource_map[mask_resource_id]; - // This RenderPassDrawQuad does not include the full |viewport_rect| + // This AggregatedRenderPassDrawQuad does not include the full |viewport_rect| // which is the size of the child render pass. gfx::Rect sub_rect = gfx::Rect(50, 50, 200, 100); EXPECT_NE(sub_rect.x(), child_pass->output_rect.x()); @@ -2537,8 +2531,9 @@ EXPECT_NE(sub_rect.right(), child_pass->output_rect.right()); EXPECT_NE(sub_rect.bottom(), child_pass->output_rect.bottom()); - // Set up a mask on the RenderPassDrawQuad. - auto* mask_quad = root_pass->CreateAndAppendDrawQuad<RenderPassDrawQuad>(); + // Set up a mask on the AggregatedRenderPassDrawQuad. + auto* mask_quad = + root_pass->CreateAndAppendDrawQuad<AggregatedRenderPassDrawQuad>(); mask_quad->SetNew( root_pass_shared_state, sub_rect, sub_rect, child_pass_id, mapped_mask_resource_id, @@ -2555,7 +2550,7 @@ white->SetNew(root_pass_shared_state, viewport_rect, viewport_rect, SK_ColorWHITE, false); - RenderPassList pass_list; + AggregatedRenderPassList pass_list; pass_list.push_back(std::move(child_pass)); pass_list.push_back(std::move(root_pass)); @@ -2569,15 +2564,14 @@ TEST_P(RendererPixelTest, RenderPassAndMaskWithPartialQuad2) { gfx::Rect viewport_rect(this->device_viewport_size_); - RenderPassId root_pass_id{1}; - std::unique_ptr<RenderPass> root_pass = - CreateTestRootRenderPass(root_pass_id, viewport_rect); + AggregatedRenderPassId root_pass_id{1}; + auto root_pass = CreateTestRootRenderPass(root_pass_id, viewport_rect); SharedQuadState* root_pass_shared_state = CreateTestSharedQuadState( gfx::Transform(), viewport_rect, root_pass.get(), gfx::RRectF()); - RenderPassId child_pass_id{2}; + AggregatedRenderPassId child_pass_id{2}; gfx::Transform transform_to_root; - std::unique_ptr<RenderPass> child_pass = + auto child_pass = CreateTestRenderPass(child_pass_id, viewport_rect, transform_to_root); SharedQuadState* child_pass_shared_state = CreateTestSharedQuadState( gfx::Transform(), viewport_rect, child_pass.get(), gfx::RRectF()); @@ -2626,7 +2620,7 @@ this->child_context_provider_.get()); ResourceId mapped_mask_resource_id = resource_map[mask_resource_id]; - // This RenderPassDrawQuad does not include the full |viewport_rect| + // This AggregatedRenderPassDrawQuad does not include the full |viewport_rect| // which is the size of the child render pass. gfx::Rect sub_rect = gfx::Rect(50, 20, 200, 60); EXPECT_NE(sub_rect.x(), child_pass->output_rect.x()); @@ -2634,8 +2628,9 @@ EXPECT_NE(sub_rect.right(), child_pass->output_rect.right()); EXPECT_NE(sub_rect.bottom(), child_pass->output_rect.bottom()); - // Set up a mask on the RenderPassDrawQuad. - auto* mask_quad = root_pass->CreateAndAppendDrawQuad<RenderPassDrawQuad>(); + // Set up a mask on the AggregatedRenderPassDrawQuad. + auto* mask_quad = + root_pass->CreateAndAppendDrawQuad<AggregatedRenderPassDrawQuad>(); mask_quad->SetNew( root_pass_shared_state, sub_rect, sub_rect, child_pass_id, mapped_mask_resource_id, @@ -2652,7 +2647,7 @@ white->SetNew(root_pass_shared_state, viewport_rect, viewport_rect, SK_ColorWHITE, false); - RenderPassList pass_list; + AggregatedRenderPassList pass_list; pass_list.push_back(std::move(child_pass)); pass_list.push_back(std::move(root_pass)); @@ -2666,15 +2661,14 @@ constexpr int kInset = 20; constexpr int kCornerRadius = 20; - RenderPassId root_pass_id{1}; - std::unique_ptr<RenderPass> root_pass = - CreateTestRootRenderPass(root_pass_id, viewport_rect); + AggregatedRenderPassId root_pass_id{1}; + auto root_pass = CreateTestRootRenderPass(root_pass_id, viewport_rect); SharedQuadState* root_pass_shared_state = CreateTestSharedQuadState( gfx::Transform(), viewport_rect, root_pass.get(), gfx::RRectF()); - RenderPassId child_pass_id{2}; + AggregatedRenderPassId child_pass_id{2}; gfx::Transform transform_to_root; - std::unique_ptr<RenderPass> child_pass = + auto child_pass = CreateTestRenderPass(child_pass_id, viewport_rect, transform_to_root); SharedQuadState* child_pass_shared_state = CreateTestSharedQuadState( gfx::Transform(), viewport_rect, child_pass.get(), gfx::RRectF()); @@ -2719,8 +2713,9 @@ this->child_context_provider_.get()); ResourceId mapped_mask_resource_id = resource_map[mask_resource_id]; - // Set up a mask on the RenderPassDrawQuad. - auto* mask_quad = root_pass->CreateAndAppendDrawQuad<RenderPassDrawQuad>(); + // Set up a mask on the AggregatedRenderPassDrawQuad. + auto* mask_quad = + root_pass->CreateAndAppendDrawQuad<AggregatedRenderPassDrawQuad>(); mask_quad->SetNew( root_pass_shared_state, viewport_rect, viewport_rect, child_pass_id, mapped_mask_resource_id, @@ -2737,7 +2732,7 @@ white->SetNew(root_pass_shared_state, viewport_rect, viewport_rect, SK_ColorWHITE, false); - RenderPassList pass_list; + AggregatedRenderPassList pass_list; pass_list.push_back(std::move(child_pass)); pass_list.push_back(std::move(root_pass)); @@ -2760,15 +2755,14 @@ SkVector::Make(35.0, 35.0), }; - RenderPassId root_pass_id{1}; - std::unique_ptr<RenderPass> root_pass = - CreateTestRootRenderPass(root_pass_id, viewport_rect); + AggregatedRenderPassId root_pass_id{1}; + auto root_pass = CreateTestRootRenderPass(root_pass_id, viewport_rect); SharedQuadState* root_pass_shared_state = CreateTestSharedQuadState( gfx::Transform(), viewport_rect, root_pass.get(), gfx::RRectF()); - RenderPassId child_pass_id{2}; + AggregatedRenderPassId child_pass_id{2}; gfx::Transform transform_to_root; - std::unique_ptr<RenderPass> child_pass = + auto child_pass = CreateTestRenderPass(child_pass_id, viewport_rect, transform_to_root); SharedQuadState* child_pass_shared_state = CreateTestSharedQuadState( gfx::Transform(), viewport_rect, child_pass.get(), gfx::RRectF()); @@ -2823,8 +2817,9 @@ this->child_context_provider_.get()); ResourceId mapped_mask_resource_id = resource_map[mask_resource_id]; - // Set up a mask on the RenderPassDrawQuad. - auto* mask_quad = root_pass->CreateAndAppendDrawQuad<RenderPassDrawQuad>(); + // Set up a mask on the AggregatedRenderPassDrawQuad. + auto* mask_quad = + root_pass->CreateAndAppendDrawQuad<AggregatedRenderPassDrawQuad>(); mask_quad->SetNew( root_pass_shared_state, viewport_rect, viewport_rect, child_pass_id, mapped_mask_resource_id, @@ -2841,7 +2836,7 @@ white->SetNew(root_pass_shared_state, viewport_rect, viewport_rect, SK_ColorWHITE, false); - RenderPassList pass_list; + AggregatedRenderPassList pass_list; pass_list.push_back(std::move(child_pass)); pass_list.push_back(std::move(root_pass)); @@ -2856,16 +2851,15 @@ void SetUpRenderPassList() { gfx::Rect device_viewport_rect(this->device_viewport_size_); - RenderPassId root_id{1}; - std::unique_ptr<RenderPass> root_pass = - CreateTestRootRenderPass(root_id, device_viewport_rect); + AggregatedRenderPassId root_id{1}; + auto root_pass = CreateTestRootRenderPass(root_id, device_viewport_rect); root_pass->has_transparent_background = false; gfx::Transform identity_quad_to_target_transform; - RenderPassId filter_pass_id{2}; + AggregatedRenderPassId filter_pass_id{2}; gfx::Transform transform_to_root; - std::unique_ptr<RenderPass> filter_pass = CreateTestRenderPass( + auto filter_pass = CreateTestRenderPass( filter_pass_id, filter_pass_layer_rect_, transform_to_root); filter_pass->backdrop_filters = this->backdrop_filters_; filter_pass->backdrop_filter_bounds = this->backdrop_filter_bounds_; @@ -2941,7 +2935,7 @@ filter_pass_to_target_transform_, filter_pass_layer_rect_, filter_pass.get(), gfx::RRectF()); auto* filter_pass_quad = - root_pass->CreateAndAppendDrawQuad<RenderPassDrawQuad>(); + root_pass->CreateAndAppendDrawQuad<AggregatedRenderPassDrawQuad>(); filter_pass_quad->SetNew(shared_state, filter_pass_layer_rect_, filter_pass_layer_rect_, filter_pass_id, mapped_mask_resource_id, mask_uv_rect, @@ -3004,7 +2998,7 @@ pass_list_.push_back(std::move(root_pass)); } - RenderPassList pass_list_; + AggregatedRenderPassList pass_list_; cc::FilterOperations backdrop_filters_; base::Optional<gfx::RRectF> backdrop_filter_bounds_; bool include_backdrop_mask_ = false; @@ -3057,16 +3051,15 @@ pass_list_.clear(); gfx::Rect device_viewport_rect(this->device_viewport_size_); - RenderPassId root_id{1}; - std::unique_ptr<RenderPass> root_pass = - CreateTestRootRenderPass(root_id, device_viewport_rect); + AggregatedRenderPassId root_id{1}; + auto root_pass = CreateTestRootRenderPass(root_id, device_viewport_rect); root_pass->has_transparent_background = false; gfx::Transform identity_quad_to_target_transform; - RenderPassId filter_pass_id{2}; + AggregatedRenderPassId filter_pass_id{2}; gfx::Transform transform_to_root; - std::unique_ptr<RenderPass> filter_pass = CreateTestRenderPass( + auto filter_pass = CreateTestRenderPass( filter_pass_id, filter_pass_layer_rect_, transform_to_root); filter_pass->backdrop_filters = this->backdrop_filters_; filter_pass->backdrop_filter_bounds = this->backdrop_filter_bounds_; @@ -3087,7 +3080,7 @@ filter_pass_to_target_transform_, filter_pass_layer_rect_, filter_pass.get(), gfx::RRectF()); auto* filter_pass_quad = - root_pass->CreateAndAppendDrawQuad<RenderPassDrawQuad>(); + root_pass->CreateAndAppendDrawQuad<AggregatedRenderPassDrawQuad>(); filter_pass_quad->SetAll( shared_state, filter_pass_layer_rect_, filter_pass_layer_rect_, /*needs_blending=*/true, filter_pass_id, 0, gfx::RectF(), gfx::Size(), @@ -3132,7 +3125,7 @@ pass_list_.push_back(std::move(root_pass)); } - RenderPassList pass_list_; + AggregatedRenderPassList pass_list_; cc::FilterOperations backdrop_filters_; base::Optional<gfx::RRectF> backdrop_filter_bounds_; float backdrop_filter_quality_ = 1.0f; @@ -3255,14 +3248,14 @@ // Draw a blue quad that covers the entire device viewport. It should be // clipped to the bottom left and top right corners by the external stencil. gfx::Rect rect(this->device_viewport_size_); - RenderPassId id{1}; - std::unique_ptr<RenderPass> pass = CreateTestRootRenderPass(id, rect); + AggregatedRenderPassId id{1}; + auto pass = CreateTestRootRenderPass(id, rect); SharedQuadState* blue_shared_state = CreateTestSharedQuadState( gfx::Transform(), rect, pass.get(), gfx::RRectF()); auto* blue = pass->CreateAndAppendDrawQuad<SolidColorDrawQuad>(); blue->SetNew(blue_shared_state, rect, rect, SK_ColorBLUE, false); pass->has_transparent_background = false; - RenderPassList pass_list; + AggregatedRenderPassList pass_list; pass_list.push_back(std::move(pass)); EXPECT_TRUE(this->RunPixelTest( @@ -3277,13 +3270,13 @@ // Draw a green quad that covers the entire device viewport. The stencil // buffer should be ignored. gfx::Rect rect(this->device_viewport_size_); - RenderPassId id{1}; - std::unique_ptr<RenderPass> pass = CreateTestRootRenderPass(id, rect); + AggregatedRenderPassId id{1}; + auto pass = CreateTestRootRenderPass(id, rect); SharedQuadState* green_shared_state = CreateTestSharedQuadState( gfx::Transform(), rect, pass.get(), gfx::RRectF()); auto* green = pass->CreateAndAppendDrawQuad<SolidColorDrawQuad>(); green->SetNew(green_shared_state, rect, rect, SK_ColorGREEN, false); - RenderPassList pass_list; + AggregatedRenderPassList pass_list; pass_list.push_back(std::move(pass)); EXPECT_TRUE(this->RunPixelTest(&pass_list, @@ -3299,15 +3292,14 @@ gfx::Rect viewport_rect(this->device_viewport_size_); - RenderPassId root_pass_id{1}; - std::unique_ptr<RenderPass> root_pass = - CreateTestRootRenderPass(root_pass_id, viewport_rect); + AggregatedRenderPassId root_pass_id{1}; + auto root_pass = CreateTestRootRenderPass(root_pass_id, viewport_rect); root_pass->has_transparent_background = false; - RenderPassId child_pass_id{2}; + AggregatedRenderPassId child_pass_id{2}; gfx::Rect pass_rect(this->device_viewport_size_); gfx::Transform transform_to_root; - std::unique_ptr<RenderPass> child_pass = + auto child_pass = CreateTestRenderPass(child_pass_id, pass_rect, transform_to_root); gfx::Transform quad_to_target_transform; @@ -3323,7 +3315,7 @@ gfx::Transform(), pass_rect, root_pass.get(), gfx::RRectF()); CreateTestRenderPassDrawQuad(pass_shared_state, pass_rect, child_pass_id, root_pass.get()); - RenderPassList pass_list; + AggregatedRenderPassList pass_list; pass_list.push_back(std::move(child_pass)); pass_list.push_back(std::move(root_pass)); @@ -3337,8 +3329,8 @@ TEST_P(GPURendererPixelTest, AntiAliasing) { gfx::Rect rect(this->device_viewport_size_); - RenderPassId id{1}; - std::unique_ptr<RenderPass> pass = CreateTestRootRenderPass(id, rect); + AggregatedRenderPassId id{1}; + auto pass = CreateTestRootRenderPass(id, rect); gfx::Transform red_quad_to_target_transform; red_quad_to_target_transform.Rotate(10); @@ -3363,7 +3355,7 @@ auto* blue = pass->CreateAndAppendDrawQuad<SolidColorDrawQuad>(); blue->SetNew(blue_shared_state, rect, rect, SK_ColorBLUE, false); - RenderPassList pass_list; + AggregatedRenderPassList pass_list; pass_list.push_back(std::move(pass)); EXPECT_TRUE( @@ -3377,8 +3369,7 @@ TEST_P(GPURendererPixelTest, AntiAliasingPerspective) { gfx::Rect rect(this->device_viewport_size_); - std::unique_ptr<RenderPass> pass = - CreateTestRootRenderPass(RenderPassId{1}, rect); + auto pass = CreateTestRootRenderPass(AggregatedRenderPassId{1}, rect); gfx::Rect red_rect(0, 0, 180, 500); gfx::Transform red_quad_to_target_transform( @@ -3401,7 +3392,7 @@ auto* blue = pass->CreateAndAppendDrawQuad<SolidColorDrawQuad>(); blue->SetNew(blue_shared_state, rect, rect, SK_ColorBLUE, false); - RenderPassList pass_list; + AggregatedRenderPassList pass_list; pass_list.push_back(std::move(pass)); EXPECT_TRUE(this->RunPixelTest( @@ -3416,10 +3407,9 @@ TEST_P(GPURendererPixelTest, AxisAligned) { gfx::Rect rect(this->device_viewport_size_); - RenderPassId id{1}; + AggregatedRenderPassId id{1}; gfx::Transform transform_to_root; - std::unique_ptr<RenderPass> pass = - CreateTestRenderPass(id, rect, transform_to_root); + auto pass = CreateTestRenderPass(id, rect, transform_to_root); CreateTestAxisAlignedQuads(rect, SK_ColorRED, SK_ColorYELLOW, false, false, pass.get()); @@ -3431,7 +3421,7 @@ auto* blue = pass->CreateAndAppendDrawQuad<SolidColorDrawQuad>(); blue->SetNew(blue_shared_state, rect, rect, SK_ColorBLUE, false); - RenderPassList pass_list; + AggregatedRenderPassList pass_list; pass_list.push_back(std::move(pass)); EXPECT_TRUE(this->RunPixelTest( @@ -3445,10 +3435,9 @@ TEST_P(GPURendererPixelTest, SolidColorDrawQuadForceAntiAliasingOff) { gfx::Rect rect(this->device_viewport_size_); - RenderPassId id{1}; + AggregatedRenderPassId id{1}; gfx::Transform transform_to_root; - std::unique_ptr<RenderPass> pass = - CreateTestRenderPass(id, rect, transform_to_root); + auto pass = CreateTestRenderPass(id, rect, transform_to_root); pass->has_transparent_background = false; gfx::Transform hole_quad_to_target_transform; @@ -3468,7 +3457,7 @@ auto* green = pass->CreateAndAppendDrawQuad<SolidColorDrawQuad>(); green->SetNew(green_shared_state, rect, rect, SK_ColorGREEN, false); - RenderPassList pass_list; + AggregatedRenderPassList pass_list; pass_list.push_back(std::move(pass)); EXPECT_TRUE(this->RunPixelTest( @@ -3483,14 +3472,13 @@ TEST_P(GPURendererPixelTest, RenderPassDrawQuadForceAntiAliasingOff) { gfx::Rect rect(this->device_viewport_size_); - RenderPassId root_pass_id{1}; + AggregatedRenderPassId root_pass_id{1}; gfx::Transform transform_to_root; - std::unique_ptr<RenderPass> root_pass = - CreateTestRenderPass(root_pass_id, rect, transform_to_root); + auto root_pass = CreateTestRenderPass(root_pass_id, rect, transform_to_root); - RenderPassId child_pass_id{2}; + AggregatedRenderPassId child_pass_id{2}; gfx::Transform child_pass_transform; - std::unique_ptr<RenderPass> child_pass = + auto child_pass = CreateTestRenderPass(child_pass_id, rect, child_pass_transform); gfx::Transform quad_to_target_transform; @@ -3511,8 +3499,8 @@ 0.5f + 1.0f / (rect.height() * 2.0f)); SharedQuadState* pass_shared_state = CreateTestSharedQuadState( hole_pass_to_target_transform, rect, root_pass.get(), gfx::RRectF()); - RenderPassDrawQuad* pass_quad = - root_pass->CreateAndAppendDrawQuad<RenderPassDrawQuad>(); + AggregatedRenderPassDrawQuad* pass_quad = + root_pass->CreateAndAppendDrawQuad<AggregatedRenderPassDrawQuad>(); pass_quad->SetAll(pass_shared_state, rect, rect, needs_blending, child_pass_id, 0, gfx::RectF(), gfx::Size(), gfx::Vector2dF(), gfx::PointF(), gfx::RectF(rect), @@ -3527,7 +3515,7 @@ root_pass->CreateAndAppendDrawQuad<SolidColorDrawQuad>(); green->SetNew(green_shared_state, rect, rect, SK_ColorGREEN, false); - RenderPassList pass_list; + AggregatedRenderPassList pass_list; pass_list.push_back(std::move(child_pass)); pass_list.push_back(std::move(root_pass)); @@ -3566,10 +3554,9 @@ this->child_context_provider_.get()); ResourceId mapped_resource = resource_map[resource]; - RenderPassId id{1}; + AggregatedRenderPassId id{1}; gfx::Transform transform_to_root; - std::unique_ptr<RenderPass> pass = - CreateTestRenderPass(id, rect, transform_to_root); + auto pass = CreateTestRenderPass(id, rect, transform_to_root); pass->has_transparent_background = false; bool contents_premultiplied = true; @@ -3596,7 +3583,7 @@ pass->CreateAndAppendDrawQuad<SolidColorDrawQuad>(); green->SetNew(green_shared_state, rect, rect, SK_ColorGREEN, false); - RenderPassList pass_list; + AggregatedRenderPassList pass_list; pass_list.push_back(std::move(pass)); EXPECT_TRUE(this->RunPixelTest( @@ -3611,10 +3598,9 @@ TEST_P(GPURendererPixelTest, BlendingWithoutAntiAliasing) { gfx::Rect rect(this->device_viewport_size_); - RenderPassId id{1}; + AggregatedRenderPassId id{1}; gfx::Transform transform_to_root; - std::unique_ptr<RenderPass> pass = - CreateTestRenderPass(id, rect, transform_to_root); + auto pass = CreateTestRenderPass(id, rect, transform_to_root); pass->has_transparent_background = false; CreateTestAxisAlignedQuads(rect, 0x800000FF, 0x8000FF00, true, true, @@ -3626,7 +3612,7 @@ background_quad->SetNew(background_quad_state, rect, rect, SK_ColorBLACK, false); - RenderPassList pass_list; + AggregatedRenderPassList pass_list; pass_list.push_back(std::move(pass)); EXPECT_TRUE(this->RunPixelTest( @@ -3640,17 +3626,16 @@ TEST_P(GPURendererPixelTest, TrilinearFiltering) { gfx::Rect viewport_rect(this->device_viewport_size_); - RenderPassId root_pass_id{1}; - std::unique_ptr<RenderPass> root_pass = - CreateTestRootRenderPass(root_pass_id, viewport_rect); + AggregatedRenderPassId root_pass_id{1}; + auto root_pass = CreateTestRootRenderPass(root_pass_id, viewport_rect); root_pass->has_transparent_background = false; - RenderPassId child_pass_id{2}; + AggregatedRenderPassId child_pass_id{2}; gfx::Transform transform_to_root; gfx::Rect child_pass_rect( ScaleToCeiledSize(this->device_viewport_size_, 4.0f)); bool generate_mipmap = true; - std::unique_ptr<RenderPass> child_pass = RenderPass::Create(); + auto child_pass = std::make_unique<AggregatedRenderPass>(); child_pass->SetAll( child_pass_id, child_pass_rect, child_pass_rect, transform_to_root, cc::FilterOperations(), cc::FilterOperations(), gfx::RRectF(), @@ -3677,13 +3662,13 @@ SharedQuadState* child_pass_shared_state = CreateTestSharedQuadState( child_to_root_transform, child_pass_rect, root_pass.get(), gfx::RRectF()); auto* child_pass_quad = - root_pass->CreateAndAppendDrawQuad<RenderPassDrawQuad>(); + root_pass->CreateAndAppendDrawQuad<AggregatedRenderPassDrawQuad>(); child_pass_quad->SetNew(child_pass_shared_state, child_pass_rect, child_pass_rect, child_pass_id, 0, gfx::RectF(), gfx::Size(), gfx::Vector2dF(), gfx::PointF(), gfx::RectF(child_pass_rect), false, 1.0f); - RenderPassList pass_list; + AggregatedRenderPassList pass_list; pass_list.push_back(std::move(child_pass)); pass_list.push_back(std::move(root_pass)); @@ -3703,10 +3688,9 @@ ResourceFormat texture_format = RGBA_8888; bool nearest_neighbor = false; - RenderPassId id{1}; + AggregatedRenderPassId id{1}; gfx::Transform transform_to_root; - std::unique_ptr<RenderPass> pass = - CreateTestRenderPass(id, viewport, transform_to_root); + auto pass = CreateTestRenderPass(id, viewport, transform_to_root); // One clipped blue quad in the lower right corner. Outside the clip // is red, which should not appear. @@ -3764,7 +3748,7 @@ nearest_neighbor, texture_format, viewport, 1.f, {}, green_raster_source->GetDisplayItemList()); - RenderPassList pass_list; + AggregatedRenderPassList pass_list; pass_list.push_back(std::move(pass)); EXPECT_TRUE(this->RunPixelTest( @@ -3780,10 +3764,9 @@ ResourceFormat texture_format = RGBA_8888; bool nearest_neighbor = false; - RenderPassId id{1}; + AggregatedRenderPassId id{1}; gfx::Transform transform_to_root; - std::unique_ptr<RenderPass> pass = - CreateTestRenderPass(id, viewport, transform_to_root); + auto pass = CreateTestRenderPass(id, viewport, transform_to_root); // One viewport-filling 0.5-opacity green quad. std::unique_ptr<cc::FakeRecordingSource> green_recording = @@ -3826,7 +3809,7 @@ texture_format, viewport, 1.f, {}, white_raster_source->GetDisplayItemList()); - RenderPassList pass_list; + AggregatedRenderPassList pass_list; pass_list.push_back(std::move(pass)); EXPECT_TRUE(this->RunPixelTest( @@ -3840,10 +3823,9 @@ ResourceFormat texture_format = RGBA_8888; bool nearest_neighbor = false; - RenderPassId id{1}; + AggregatedRenderPassId id{1}; gfx::Transform transform_to_root; - std::unique_ptr<RenderPass> pass = - CreateTestRenderPass(id, viewport, transform_to_root); + auto pass = CreateTestRenderPass(id, viewport, transform_to_root); // One viewport-filling 0.5-opacity transparent quad. std::unique_ptr<cc::FakeRecordingSource> transparent_recording = @@ -3887,7 +3869,7 @@ texture_format, viewport, 1.f, {}, white_raster_source->GetDisplayItemList()); - RenderPassList pass_list; + AggregatedRenderPassList pass_list; pass_list.push_back(std::move(pass)); EXPECT_TRUE(this->RunPixelTest(&pass_list, @@ -3909,10 +3891,9 @@ bool needs_blending = true; bool nearest_neighbor = false; - RenderPassId id{1}; + AggregatedRenderPassId id{1}; gfx::Transform transform_to_root; - std::unique_ptr<RenderPass> pass = - CreateTestRenderPass(id, viewport, transform_to_root); + auto pass = CreateTestRenderPass(id, viewport, transform_to_root); sk_sp<SkSurface> surface = SkSurface::MakeRasterN32Premul(2, 2); ASSERT_NE(surface, nullptr); @@ -3942,7 +3923,7 @@ texture_format, viewport, 1.f, {}, raster_source->GetDisplayItemList()); - RenderPassList pass_list; + AggregatedRenderPassList pass_list; pass_list.push_back(std::move(pass)); this->disable_picture_quad_image_filtering_ = true; @@ -3961,10 +3942,9 @@ bool needs_blending = true; bool nearest_neighbor = true; - RenderPassId id{1}; + AggregatedRenderPassId id{1}; gfx::Transform transform_to_root; - std::unique_ptr<RenderPass> pass = - CreateTestRenderPass(id, viewport, transform_to_root); + auto pass = CreateTestRenderPass(id, viewport, transform_to_root); sk_sp<SkSurface> surface = SkSurface::MakeRasterN32Premul(2, 2); ASSERT_NE(surface, nullptr); @@ -3994,7 +3974,7 @@ texture_format, viewport, 1.f, {}, raster_source->GetDisplayItemList()); - RenderPassList pass_list; + AggregatedRenderPassList pass_list; pass_list.push_back(std::move(pass)); EXPECT_TRUE(this->RunPixelTest( @@ -4041,10 +4021,9 @@ this->child_context_provider_.get()); ResourceId mapped_resource = resource_map[resource]; - RenderPassId id{1}; + AggregatedRenderPassId id{1}; gfx::Transform transform_to_root; - std::unique_ptr<RenderPass> pass = - CreateTestRenderPass(id, viewport, transform_to_root); + auto pass = CreateTestRenderPass(id, viewport, transform_to_root); gfx::Transform quad_to_target_transform; SharedQuadState* shared_state = CreateTestSharedQuadState( @@ -4056,7 +4035,7 @@ contents_premultiplied, nearest_neighbor, force_anti_aliasing_off); - RenderPassList pass_list; + AggregatedRenderPassList pass_list; pass_list.push_back(std::move(pass)); EXPECT_TRUE(this->RunPixelTest( @@ -4092,10 +4071,9 @@ this->child_context_provider_.get()); ResourceId mapped_resource = resource_map[resource]; - RenderPassId id{1}; + AggregatedRenderPassId id{1}; gfx::Transform transform_to_root; - std::unique_ptr<RenderPass> pass = - CreateTestRenderPass(id, viewport, transform_to_root); + auto pass = CreateTestRenderPass(id, viewport, transform_to_root); gfx::Transform quad_to_target_transform; SharedQuadState* shared_state = CreateTestSharedQuadState( @@ -4108,7 +4086,7 @@ SK_ColorBLACK, vertex_opacity, false, nearest_neighbor, /*secure_output_only=*/false, gfx::ProtectedVideoType::kClear); - RenderPassList pass_list; + AggregatedRenderPassList pass_list; pass_list.push_back(std::move(pass)); EXPECT_TRUE(this->RunPixelTest( @@ -4146,10 +4124,9 @@ this->child_context_provider_.get()); ResourceId mapped_resource = resource_map[resource]; - RenderPassId id{1}; + AggregatedRenderPassId id{1}; gfx::Transform transform_to_root; - std::unique_ptr<RenderPass> pass = - CreateTestRenderPass(id, viewport, transform_to_root); + auto pass = CreateTestRenderPass(id, viewport, transform_to_root); gfx::Transform quad_to_target_transform; SharedQuadState* shared_state = CreateTestSharedQuadState( @@ -4162,7 +4139,7 @@ SK_ColorBLACK, vertex_opacity, false, nearest_neighbor, /*secure_output_only=*/false, gfx::ProtectedVideoType::kClear); - RenderPassList pass_list; + AggregatedRenderPassList pass_list; pass_list.push_back(std::move(pass)); // Allow for a small amount of error as the blending alogrithm used by Skia is @@ -4180,10 +4157,9 @@ bool needs_blending = true; bool nearest_neighbor = false; - RenderPassId id{1}; + AggregatedRenderPassId id{1}; gfx::Transform transform_to_root; - std::unique_ptr<RenderPass> pass = - CreateTestRenderPass(id, viewport, transform_to_root); + auto pass = CreateTestRenderPass(id, viewport, transform_to_root); // As scaling up the blue checkerboards will cause sampling on the GPU, // a few extra "cleanup rects" need to be added to clobber the blending @@ -4300,7 +4276,7 @@ half_color_quad->SetNew(half_green_shared_state, half_green_rect, half_green_rect, SK_ColorGREEN, false); - RenderPassList pass_list; + AggregatedRenderPassList pass_list; pass_list.push_back(std::move(pass)); EXPECT_TRUE(this->RunPixelTest( @@ -4325,14 +4301,13 @@ // This draws a blue rect above a yellow rect with an inverted output surface. gfx::Rect viewport_rect(this->device_viewport_size_); - RenderPassId root_pass_id{1}; - std::unique_ptr<RenderPass> root_pass = - CreateTestRootRenderPass(root_pass_id, viewport_rect); + AggregatedRenderPassId root_pass_id{1}; + auto root_pass = CreateTestRootRenderPass(root_pass_id, viewport_rect); - RenderPassId child_pass_id{2}; + AggregatedRenderPassId child_pass_id{2}; gfx::Rect pass_rect(this->device_viewport_size_); gfx::Transform transform_to_root; - std::unique_ptr<RenderPass> child_pass = + auto child_pass = CreateTestRenderPass(child_pass_id, pass_rect, transform_to_root); gfx::Transform quad_to_target_transform; @@ -4354,7 +4329,7 @@ CreateTestRenderPassDrawQuad(pass_shared_state, pass_rect, child_pass_id, root_pass.get()); - RenderPassList pass_list; + AggregatedRenderPassList pass_list; pass_list.push_back(std::move(child_pass)); pass_list.push_back(std::move(root_pass)); @@ -4370,14 +4345,13 @@ // This draws a blue rect above a yellow rect with an inverted output surface. gfx::Rect viewport_rect(this->device_viewport_size_); - RenderPassId root_pass_id{1}; - std::unique_ptr<RenderPass> root_pass = - CreateTestRootRenderPass(root_pass_id, viewport_rect); + AggregatedRenderPassId root_pass_id{1}; + auto root_pass = CreateTestRootRenderPass(root_pass_id, viewport_rect); - RenderPassId child_pass_id{2}; + AggregatedRenderPassId child_pass_id{2}; gfx::Rect pass_rect(this->device_viewport_size_); gfx::Transform transform_to_root; - std::unique_ptr<RenderPass> child_pass = + auto child_pass = CreateTestRenderPass(child_pass_id, pass_rect, transform_to_root); gfx::Transform quad_to_target_transform; @@ -4399,7 +4373,7 @@ CreateTestRenderPassDrawQuad(pass_shared_state, pass_rect, child_pass_id, root_pass.get()); - RenderPassList pass_list; + AggregatedRenderPassList pass_list; pass_list.push_back(std::move(child_pass)); pass_list.push_back(std::move(root_pass)); @@ -4413,14 +4387,13 @@ TEST_P(GPURendererPixelTest, CheckReadbackSubset) { gfx::Rect viewport_rect(this->device_viewport_size_); - RenderPassId root_pass_id{1}; - std::unique_ptr<RenderPass> root_pass = - CreateTestRootRenderPass(root_pass_id, viewport_rect); + AggregatedRenderPassId root_pass_id{1}; + auto root_pass = CreateTestRootRenderPass(root_pass_id, viewport_rect); - RenderPassId child_pass_id{2}; + AggregatedRenderPassId child_pass_id{2}; gfx::Rect pass_rect(this->device_viewport_size_); gfx::Transform transform_to_root; - std::unique_ptr<RenderPass> child_pass = + auto child_pass = CreateTestRenderPass(child_pass_id, pass_rect, transform_to_root); gfx::Transform quad_to_target_transform; @@ -4444,7 +4417,7 @@ CreateTestRenderPassDrawQuad(pass_shared_state, pass_rect, child_pass_id, root_pass.get()); - RenderPassList pass_list; + AggregatedRenderPassList pass_list; pass_list.push_back(std::move(child_pass)); pass_list.push_back(std::move(root_pass)); @@ -4467,8 +4440,8 @@ gfx::Rect rect(this->device_viewport_size_); bool needs_blending = false; - RenderPassId id{1}; - std::unique_ptr<RenderPass> pass = CreateTestRootRenderPass(id, rect); + AggregatedRenderPassId id{1}; + auto pass = CreateTestRootRenderPass(id, rect); SharedQuadState* shared_state = CreateTestSharedQuadState( gfx::Transform(), rect, pass.get(), gfx::RRectF()); @@ -4536,7 +4509,7 @@ } } - RenderPassList pass_list; + AggregatedRenderPassList pass_list; pass_list.push_back(std::move(pass)); EXPECT_TRUE(this->RunPixelTest( @@ -4585,10 +4558,9 @@ this->child_context_provider_.get()); ResourceId mapped_resource = resource_map[resource]; - RenderPassId id{1}; + AggregatedRenderPassId id{1}; gfx::Transform transform_to_root; - std::unique_ptr<RenderPass> pass = - CreateTestRenderPass(id, viewport, transform_to_root); + auto pass = CreateTestRenderPass(id, viewport, transform_to_root); // Green quad that should not show any red pixels from outside the // tex coord rect. @@ -4608,7 +4580,7 @@ color_quad->SetNew(background_shared, viewport, viewport, SK_ColorGREEN, false); - RenderPassList pass_list; + AggregatedRenderPassList pass_list; pass_list.push_back(std::move(pass)); EXPECT_TRUE(this->RunPixelTest(&pass_list, @@ -4621,9 +4593,8 @@ constexpr int kInset = 20; constexpr int kCornerRadius = 20; - RenderPassId root_pass_id{1}; - std::unique_ptr<RenderPass> root_pass = - CreateTestRootRenderPass(root_pass_id, viewport_rect); + AggregatedRenderPassId root_pass_id{1}; + auto root_pass = CreateTestRootRenderPass(root_pass_id, viewport_rect); gfx::Transform quad_to_target_transform; gfx::Rect blue_rect(0, 0, this->device_viewport_size_.width(), @@ -4645,7 +4616,7 @@ auto* white = root_pass->CreateAndAppendDrawQuad<SolidColorDrawQuad>(); white->SetNew(shared_state_normal, red_rect, red_rect, SK_ColorWHITE, false); - RenderPassList pass_list; + AggregatedRenderPassList pass_list; pass_list.push_back(std::move(root_pass)); if (is_gl_renderer()) { @@ -4670,9 +4641,8 @@ constexpr int kInset = 20; constexpr int kCornerRadius = 20; - RenderPassId root_pass_id{1}; - std::unique_ptr<RenderPass> root_pass = - CreateTestRootRenderPass(root_pass_id, viewport_rect); + AggregatedRenderPassId root_pass_id{1}; + auto root_pass = CreateTestRootRenderPass(root_pass_id, viewport_rect); gfx::Transform quad_to_target_transform; gfx::Rect blue_rect(0, 0, this->device_viewport_size_.width(), @@ -4715,7 +4685,7 @@ auto* white = root_pass->CreateAndAppendDrawQuad<SolidColorDrawQuad>(); white->SetNew(shared_state_normal, red_rect, red_rect, SK_ColorWHITE, false); - RenderPassList pass_list; + AggregatedRenderPassList pass_list; pass_list.push_back(std::move(root_pass)); if (is_gl_renderer()) { @@ -4742,18 +4712,17 @@ constexpr int kCornerRadius = 20; constexpr int kBlueCornerRadius = 10; - RenderPassId root_pass_id{1}; - std::unique_ptr<RenderPass> root_pass = - CreateTestRootRenderPass(root_pass_id, viewport_rect); + AggregatedRenderPassId root_pass_id{1}; + auto root_pass = CreateTestRootRenderPass(root_pass_id, viewport_rect); - RenderPassId child_pass_id{2}; + AggregatedRenderPassId child_pass_id{2}; gfx::Rect pass_rect(this->device_viewport_size_); pass_rect.Inset(kInset, kInset); gfx::Rect child_pass_local_rect = gfx::Rect(pass_rect.size()); gfx::Transform transform_to_root; transform_to_root.Translate(pass_rect.OffsetFromOrigin()); - std::unique_ptr<RenderPass> child_pass = CreateTestRenderPass( - child_pass_id, child_pass_local_rect, transform_to_root); + auto child_pass = CreateTestRenderPass(child_pass_id, child_pass_local_rect, + transform_to_root); gfx::Rect blue_rect = child_pass_local_rect; gfx::Vector2dF blue_offset_from_target(-30, 40); @@ -4787,7 +4756,7 @@ CreateTestRenderPassDrawQuad(pass_shared_state, pass_rect, child_pass_id, root_pass.get()); - RenderPassList pass_list; + AggregatedRenderPassList pass_list; pass_list.push_back(std::move(child_pass)); pass_list.push_back(std::move(root_pass)); @@ -4803,9 +4772,8 @@ constexpr gfx::RoundedCornersF kCornerRadii(5, 15, 25, 35); constexpr int kInset = 20; - RenderPassId root_pass_id{1}; - std::unique_ptr<RenderPass> root_pass = - CreateTestRootRenderPass(root_pass_id, viewport_rect); + AggregatedRenderPassId root_pass_id{1}; + auto root_pass = CreateTestRootRenderPass(root_pass_id, viewport_rect); gfx::Rect pass_rect(this->device_viewport_size_); pass_rect.Inset(kInset, kInset); @@ -4833,7 +4801,7 @@ auto* white = root_pass->CreateAndAppendDrawQuad<SolidColorDrawQuad>(); white->SetNew(sqs_white, white_rect, white_rect, SK_ColorWHITE, false); - RenderPassList pass_list; + AggregatedRenderPassList pass_list; pass_list.push_back(std::move(root_pass)); if (is_gl_renderer()) { @@ -4862,9 +4830,8 @@ constexpr gfx::RoundedCornersF kCornerRadiiLL(0, 0, 0, 35); constexpr int kInset = 20; - RenderPassId root_pass_id{1}; - std::unique_ptr<RenderPass> root_pass = - CreateTestRootRenderPass(root_pass_id, viewport_rect); + AggregatedRenderPassId root_pass_id{1}; + auto root_pass = CreateTestRootRenderPass(root_pass_id, viewport_rect); gfx::Rect pass_rect(this->device_viewport_size_); pass_rect.Inset(kInset, kInset); @@ -4921,7 +4888,7 @@ auto* white = root_pass->CreateAndAppendDrawQuad<SolidColorDrawQuad>(); white->SetNew(sqs_white, white_rect, white_rect, SK_ColorWHITE, false); - RenderPassList pass_list; + AggregatedRenderPassList pass_list; pass_list.push_back(std::move(root_pass)); // GL Renderer should have an exact match as that is the reference point. @@ -4952,10 +4919,9 @@ TEST_P(RendererPixelTestWithOverdrawFeedback, TranslucentRectangles) { gfx::Rect rect(this->device_viewport_size_); - RenderPassId id{1}; + AggregatedRenderPassId id{1}; gfx::Transform transform_to_root; - std::unique_ptr<RenderPass> pass = - CreateTestRenderPass(id, rect, transform_to_root); + auto pass = CreateTestRenderPass(id, rect, transform_to_root); CreateTestAxisAlignedQuads(rect, 0x10444444, 0x10CCCCCC, true, false, pass.get()); @@ -4967,7 +4933,7 @@ auto* bg = pass->CreateAndAppendDrawQuad<SolidColorDrawQuad>(); bg->SetNew(bg_shared_state, rect, rect, SK_ColorBLACK, false); - RenderPassList pass_list; + AggregatedRenderPassList pass_list; pass_list.push_back(std::move(pass)); if (is_gl_renderer()) { @@ -5074,8 +5040,8 @@ static_cast<size_t>(255.f * color.z() + 0.5f)); } - RenderPassId id{1}; - std::unique_ptr<RenderPass> pass = CreateTestRootRenderPass(id, rect); + AggregatedRenderPassId id{1}; + auto pass = CreateTestRootRenderPass(id, rect); // Append a quad to execute the transform. { @@ -5112,7 +5078,7 @@ color_quad->SetNew(shared_state, rect, rect, SK_ColorBLACK, false); } - RenderPassList pass_list; + AggregatedRenderPassList pass_list; pass_list.push_back(std::move(pass)); // Allow a difference of 2 bytes in comparison for shader-based transforms,
diff --git a/components/viz/service/display/skia_output_surface.h b/components/viz/service/display/skia_output_surface.h index ebdfcaa..b314449d 100644 --- a/components/viz/service/display/skia_output_surface.h +++ b/components/viz/service/display/skia_output_surface.h
@@ -9,6 +9,7 @@ #include <vector> #include "build/build_config.h" +#include "components/viz/common/quads/aggregated_render_pass.h" #include "components/viz/common/resources/resource_format.h" #include "components/viz/common/resources/resource_id.h" #include "components/viz/service/display/external_use_client.h" @@ -109,7 +110,7 @@ // will use this SkCanvas to paint the render pass. // Note: BeginPaintRenderPass cannot be called without finishing the prior // paint render pass. - virtual SkCanvas* BeginPaintRenderPass(const RenderPassId& id, + virtual SkCanvas* BeginPaintRenderPass(const AggregatedRenderPassId& id, const gfx::Size& size, ResourceFormat format, bool mipmap, @@ -131,7 +132,7 @@ // and mipmap must match arguments used for BeginPaintRenderPass() to paint // this render pass. virtual sk_sp<SkImage> MakePromiseSkImageFromRenderPass( - const RenderPassId& id, + const AggregatedRenderPassId& id, const gfx::Size& size, ResourceFormat format, bool mipmap, @@ -139,11 +140,12 @@ // Remove cached resources generated by BeginPaintRenderPass and // FinishPaintRenderPass. - virtual void RemoveRenderPassResource(std::vector<RenderPassId> ids) = 0; + virtual void RemoveRenderPassResource( + std::vector<AggregatedRenderPassId> ids) = 0; // Copy the output of the current frame if the |id| is zero, otherwise copy // the output of a cached SkSurface for the given |id|. - virtual void CopyOutput(RenderPassId id, + virtual void CopyOutput(AggregatedRenderPassId id, const copy_output::RenderPassGeometry& geometry, const gfx::ColorSpace& color_space, std::unique_ptr<CopyOutputRequest> request) = 0;
diff --git a/components/viz/service/display/skia_readback_pixeltest.cc b/components/viz/service/display/skia_readback_pixeltest.cc index c0cd5b4a..e548e783 100644 --- a/components/viz/service/display/skia_readback_pixeltest.cc +++ b/components/viz/service/display/skia_readback_pixeltest.cc
@@ -42,7 +42,7 @@ return test_dir.Append(base::FilePath(basename)); } -SharedQuadState* CreateSharedQuadState(RenderPass* render_pass, +SharedQuadState* CreateSharedQuadState(AggregatedRenderPass* render_pass, const gfx::Rect& rect) { const gfx::Rect layer_rect = rect; const gfx::Rect visible_layer_rect = rect; @@ -122,7 +122,7 @@ } // Creates a RenderPass that embeds a single quad containing |source_bitmap_|. - std::unique_ptr<RenderPass> GenerateRootRenderPass() { + std::unique_ptr<AggregatedRenderPass> GenerateRootRenderPass() { ResourceFormat format = (source_bitmap_.info().colorType() == kBGRA_8888_SkColorType) ? ResourceFormat::BGRA_8888 @@ -138,8 +138,9 @@ ResourceId mapped_resource_id = resource_map[resource_id]; const gfx::Rect output_rect(kSourceSize); - std::unique_ptr<RenderPass> pass = RenderPass::Create(); - pass->SetNew(RenderPassId{1}, output_rect, output_rect, gfx::Transform()); + auto pass = std::make_unique<AggregatedRenderPass>(); + pass->SetNew(AggregatedRenderPassId{1}, output_rect, output_rect, + gfx::Transform()); SharedQuadState* sqs = CreateSharedQuadState(pass.get(), output_rect); @@ -162,7 +163,7 @@ // Generates a RenderPass which contains one quad that spans the full output. // The quad has our source image, so the framebuffer should contain the source // image after DrawFrame(). - std::unique_ptr<RenderPass> pass = GenerateRootRenderPass(); + auto pass = GenerateRootRenderPass(); std::unique_ptr<CopyOutputResult> result; base::RunLoop loop; @@ -192,7 +193,7 @@ request->set_result_selection(result_selection); pass->copy_requests.push_back(std::move(request)); - RenderPassList pass_list; + AggregatedRenderPassList pass_list; pass_list.push_back(std::move(pass)); renderer_->DecideRenderPassAllocationsForFrame(pass_list);
diff --git a/components/viz/service/display/skia_renderer.cc b/components/viz/service/display/skia_renderer.cc index 1df9ece..274a4fa 100644 --- a/components/viz/service/display/skia_renderer.cc +++ b/components/viz/service/display/skia_renderer.cc
@@ -21,6 +21,7 @@ #include "components/viz/common/display/renderer_settings.h" #include "components/viz/common/frame_sinks/copy_output_request.h" #include "components/viz/common/frame_sinks/copy_output_util.h" +#include "components/viz/common/quads/aggregated_render_pass_draw_quad.h" #include "components/viz/common/quads/debug_border_draw_quad.h" #include "components/viz/common/quads/picture_draw_quad.h" #include "components/viz/common/quads/render_pass_draw_quad.h" @@ -254,7 +255,11 @@ case DrawQuad::Material::kPictureContent: return PictureDrawQuad::MaterialCast(quad)->force_anti_aliasing_off; case DrawQuad::Material::kRenderPass: + NOTREACHED(); return RenderPassDrawQuad::MaterialCast(quad)->force_anti_aliasing_off; + case DrawQuad::Material::kAggregatedRenderPass: + return AggregatedRenderPassDrawQuad::MaterialCast(quad) + ->force_anti_aliasing_off; case DrawQuad::Material::kSolidColor: return SolidColorDrawQuad::MaterialCast(quad)->force_anti_aliasing_off; case DrawQuad::Material::kTiledContent: @@ -881,7 +886,8 @@ } } -void SkiaRenderer::BindFramebufferToTexture(const RenderPassId render_pass_id) { +void SkiaRenderer::BindFramebufferToTexture( + const AggregatedRenderPassId render_pass_id) { auto iter = render_pass_backings_.find(render_pass_id); DCHECK(render_pass_backings_.end() != iter); // This function is called after AllocateRenderPassResourceIfNeeded, so there @@ -974,6 +980,13 @@ } switch (quad->material) { + case DrawQuad::Material::kAggregatedRenderPass: + // RPDQ should only ever be encountered as a top-level quad, not when + // bypassing another renderpass + DCHECK(rpdq_params == nullptr); + DrawRenderPassQuad(AggregatedRenderPassDrawQuad::MaterialCast(quad), + params); + break; case DrawQuad::Material::kDebugBorder: // DebugBorders draw directly into the device space, so are not compatible // with image filters, so should never have been promoted as a bypass quad @@ -988,10 +1001,10 @@ DrawPictureQuad(PictureDrawQuad::MaterialCast(quad), params); break; case DrawQuad::Material::kRenderPass: - // RPDQ should only ever be encountered as a top-level quad, not when - // bypassing another renderpass - DCHECK(rpdq_params == nullptr); - DrawRenderPassQuad(RenderPassDrawQuad::MaterialCast(quad), params); + // RenderPassDrawQuads should be converted to + // AggregatedRenderPassDrawQuads at this point. + DrawUnsupportedQuad(quad, rpdq_params, params); + NOTREACHED(); break; case DrawQuad::Material::kSolidColor: DrawSolidColorQuad(SolidColorDrawQuad::MaterialCast(quad), rpdq_params, @@ -1351,10 +1364,13 @@ if (!contents_device_transform.IsScaleOrTranslation()) return false; - if (quad->material == DrawQuad::Material::kRenderPass) { + // Sanity check: we should not have a RenderPassDrawQuad here. + DCHECK_NE(quad->material, DrawQuad::Material::kRenderPass); + if (quad->material == DrawQuad::Material::kAggregatedRenderPass) { // If the renderpass has filters, the filters may modify the effective // geometry beyond the quad's visible_rect, so it's not safe to pre-clip. - auto pass_id = RenderPassDrawQuad::MaterialCast(quad)->render_pass_id; + auto pass_id = + AggregatedRenderPassDrawQuad::MaterialCast(quad)->render_pass_id; if (FiltersForPass(pass_id) || BackdropFiltersForPass(pass_id)) return false; } @@ -1364,7 +1380,8 @@ contents_device_transform.matrix().get(2, 2) >= 0.0; } -const DrawQuad* SkiaRenderer::CanPassBeDrawnDirectly(const RenderPass* pass) { +const DrawQuad* SkiaRenderer::CanPassBeDrawnDirectly( + const AggregatedRenderPass* pass) { // TODO(michaelludwig) - For now, this only supports opaque, src-over quads // with invertible transforms and simple content (image or color only). // Can only collapse a single tile quad. @@ -1380,6 +1397,7 @@ // and nested render passes cannot bypass a render pass // (their draw functions do not accept DrawRPDQParams either). if (quad->material == DrawQuad::Material::kRenderPass || + quad->material == DrawQuad::Material::kAggregatedRenderPass || quad->material == DrawQuad::Material::kDebugBorder || quad->material == DrawQuad::Material::kPictureContent) return nullptr; @@ -1570,6 +1588,7 @@ return true; if (new_quad->material != DrawQuad::Material::kRenderPass && + new_quad->material != DrawQuad::Material::kAggregatedRenderPass && new_quad->material != DrawQuad::Material::kStreamVideoContent && new_quad->material != DrawQuad::Material::kTextureContent && new_quad->material != DrawQuad::Material::kTiledContent) @@ -2265,8 +2284,10 @@ const char* hdr = R"( uniform half offset; uniform half multiplier; +in shader child; -void main(inout half4 color) { +half4 main() { + half4 color = sample(child); // un-premultiply alpha if (color.a > 0) color.rgb /= color.a; @@ -2277,6 +2298,7 @@ const char* ftr = R"( // premultiply alpha color.rgb *= color.a; + return color; } )"; @@ -2292,7 +2314,8 @@ input.multiplier = resource_multiplier; sk_sp<SkData> data = SkData::MakeWithCopy(&input, sizeof(input)); - return effect->makeColorFilter(std::move(data)); + sk_sp<SkColorFilter> child = nullptr; // = default input color + return effect->makeColorFilter(std::move(data), &child, 1); } sk_sp<SkColorFilter> SkiaRenderer::GetContentColorFilter() { @@ -2332,7 +2355,7 @@ } SkiaRenderer::DrawRPDQParams SkiaRenderer::CalculateRPDQParams( - const RenderPassDrawQuad* quad, + const AggregatedRenderPassDrawQuad* quad, DrawQuadParams* params) { DrawRPDQParams rpdq_params(params->visible_rect); @@ -2476,7 +2499,7 @@ return rpdq_params; } -void SkiaRenderer::DrawRenderPassQuad(const RenderPassDrawQuad* quad, +void SkiaRenderer::DrawRenderPassQuad(const AggregatedRenderPassDrawQuad* quad, DrawQuadParams* params) { DrawRPDQParams rpdq_params = CalculateRPDQParams(quad, params); if (rpdq_params.filter_bounds.IsEmpty()) @@ -2563,7 +2586,7 @@ switch (draw_mode_) { case DrawMode::DDL: { // Root framebuffer uses id 0 in SkiaOutputSurface. - RenderPassId render_pass_id; + AggregatedRenderPassId render_pass_id; const auto* const render_pass = current_frame()->current_render_pass; if (render_pass != current_frame()->root_render_pass) { render_pass_id = render_pass->id; @@ -2633,10 +2656,10 @@ } void SkiaRenderer::UpdateRenderPassTextures( - const RenderPassList& render_passes_in_draw_order, - const base::flat_map<RenderPassId, RenderPassRequirements>& + const AggregatedRenderPassList& render_passes_in_draw_order, + const base::flat_map<AggregatedRenderPassId, RenderPassRequirements>& render_passes_in_frame) { - std::vector<RenderPassId> passes_to_delete; + std::vector<AggregatedRenderPassId> passes_to_delete; for (const auto& pair : render_pass_backings_) { auto render_pass_it = render_passes_in_frame.find(pair.first); if (render_pass_it == render_passes_in_frame.end()) { @@ -2667,7 +2690,7 @@ } void SkiaRenderer::AllocateRenderPassResourceIfNeeded( - const RenderPassId& render_pass_id, + const AggregatedRenderPassId& render_pass_id, const RenderPassRequirements& requirements) { auto it = render_pass_backings_.find(render_pass_id); if (it != render_pass_backings_.end()) { @@ -2766,13 +2789,13 @@ } bool SkiaRenderer::IsRenderPassResourceAllocated( - const RenderPassId& render_pass_id) const { + const AggregatedRenderPassId& render_pass_id) const { auto it = render_pass_backings_.find(render_pass_id); return it != render_pass_backings_.end(); } gfx::Size SkiaRenderer::GetRenderPassBackingPixelSize( - const RenderPassId& render_pass_id) { + const AggregatedRenderPassId& render_pass_id) { auto it = render_pass_backings_.find(render_pass_id); DCHECK(it != render_pass_backings_.end()); return it->second.size;
diff --git a/components/viz/service/display/skia_renderer.h b/components/viz/service/display/skia_renderer.h index 75954c5..c56d674e 100644 --- a/components/viz/service/display/skia_renderer.h +++ b/components/viz/service/display/skia_renderer.h
@@ -29,6 +29,7 @@ } namespace viz { +class AggregatedRenderPassDrawQuad; class DebugBorderDrawQuad; class PictureDrawQuad; class SkiaOutputSurface; @@ -66,18 +67,19 @@ protected: bool CanPartialSwap() override; void UpdateRenderPassTextures( - const RenderPassList& render_passes_in_draw_order, - const base::flat_map<RenderPassId, RenderPassRequirements>& + const AggregatedRenderPassList& render_passes_in_draw_order, + const base::flat_map<AggregatedRenderPassId, RenderPassRequirements>& render_passes_in_frame) override; void AllocateRenderPassResourceIfNeeded( - const RenderPassId& render_pass_id, + const AggregatedRenderPassId& render_pass_id, const RenderPassRequirements& requirements) override; bool IsRenderPassResourceAllocated( - const RenderPassId& render_pass_id) const override; + const AggregatedRenderPassId& render_pass_id) const override; gfx::Size GetRenderPassBackingPixelSize( - const RenderPassId& render_pass_id) override; + const AggregatedRenderPassId& render_pass_id) override; void BindFramebufferToOutputSurface() override; - void BindFramebufferToTexture(const RenderPassId render_pass_id) override; + void BindFramebufferToTexture( + const AggregatedRenderPassId render_pass_id) override; void SetScissorTestRect(const gfx::Rect& scissor_rect) override; void PrepareSurfaceForPass(SurfaceInitializationMode initialization_mode, const gfx::Rect& render_pass_scissor) override; @@ -133,7 +135,7 @@ const gfx::Rect* scissor_rect, const DrawQuad* quad, const gfx::QuadF* draw_region) const; - DrawRPDQParams CalculateRPDQParams(const RenderPassDrawQuad* quad, + DrawRPDQParams CalculateRPDQParams(const AggregatedRenderPassDrawQuad* quad, DrawQuadParams* params); // Modifies |params| and |rpdq_params| to apply correctly when drawing the // RenderPass directly via |bypass_quad|. @@ -190,7 +192,7 @@ // either are not textures (debug, picture), or it's very likely // the texture will have advanced paint effects (rpdq). Additionally, they do // not support being drawn directly for a pass-through RenderPass. - void DrawRenderPassQuad(const RenderPassDrawQuad* quad, + void DrawRenderPassQuad(const AggregatedRenderPassDrawQuad* quad, DrawQuadParams* params); void DrawDebugBorderQuad(const DebugBorderDrawQuad* quad, DrawQuadParams* params); @@ -224,7 +226,8 @@ // skia_renderer can draw most single-quad passes directly, regardless of // blend mode or image filtering. - const DrawQuad* CanPassBeDrawnDirectly(const RenderPass* pass) override; + const DrawQuad* CanPassBeDrawnDirectly( + const AggregatedRenderPass* pass) override; // Get corresponding GrContext. Returns nullptr when there is no GrContext. // TODO(weiliangc): This currently only returns nullptr. If SKPRecord isn't @@ -268,7 +271,8 @@ RenderPassBacking(RenderPassBacking&&); RenderPassBacking& operator=(RenderPassBacking&&); }; - base::flat_map<RenderPassId, RenderPassBacking> render_pass_backings_; + base::flat_map<AggregatedRenderPassId, RenderPassBacking> + render_pass_backings_; const DrawMode draw_mode_;
diff --git a/components/viz/service/display/software_renderer.cc b/components/viz/service/display/software_renderer.cc index 103b701..138ef5a 100644 --- a/components/viz/service/display/software_renderer.cc +++ b/components/viz/service/display/software_renderer.cc
@@ -16,6 +16,7 @@ #include "components/viz/common/display/renderer_settings.h" #include "components/viz/common/frame_sinks/copy_output_request.h" #include "components/viz/common/frame_sinks/copy_output_util.h" +#include "components/viz/common/quads/aggregated_render_pass_draw_quad.h" #include "components/viz/common/quads/debug_border_draw_quad.h" #include "components/viz/common/quads/picture_draw_quad.h" #include "components/viz/common/quads/render_pass_draw_quad.h" @@ -140,7 +141,7 @@ } void SoftwareRenderer::BindFramebufferToTexture( - const RenderPassId render_pass_id) { + const AggregatedRenderPassId render_pass_id) { auto it = render_pass_bitmaps_.find(render_pass_id); DCHECK(it != render_pass_bitmaps_.end()); SkBitmap& bitmap = it->second; @@ -308,6 +309,9 @@ } switch (quad->material) { + case DrawQuad::Material::kAggregatedRenderPass: + DrawRenderPassQuad(AggregatedRenderPassDrawQuad::MaterialCast(quad)); + break; case DrawQuad::Material::kDebugBorder: DrawDebugBorderQuad(DebugBorderDrawQuad::MaterialCast(quad)); break; @@ -315,7 +319,9 @@ DrawPictureQuad(PictureDrawQuad::MaterialCast(quad)); break; case DrawQuad::Material::kRenderPass: - DrawRenderPassQuad(RenderPassDrawQuad::MaterialCast(quad)); + // At this point, all RenderPassDrawQuads should be converted to + // AggregatedRenderPassDrawQuads. + NOTREACHED(); break; case DrawQuad::Material::kSolidColor: DrawSolidColorQuad(SolidColorDrawQuad::MaterialCast(quad)); @@ -491,7 +497,8 @@ ¤t_paint_); } -void SoftwareRenderer::DrawRenderPassQuad(const RenderPassDrawQuad* quad) { +void SoftwareRenderer::DrawRenderPassQuad( + const AggregatedRenderPassDrawQuad* quad) { auto it = render_pass_bitmaps_.find(quad->render_pass_id); if (it == render_pass_bitmaps_.end()) return; @@ -673,7 +680,7 @@ bool SoftwareRenderer::ShouldApplyBackdropFilters( const cc::FilterOperations* backdrop_filters, - const RenderPassDrawQuad* quad) const { + const AggregatedRenderPassDrawQuad* quad) const { if (!backdrop_filters) return false; if (quad->shared_quad_state->opacity == 0.f) @@ -693,7 +700,7 @@ // underlying backdrop. sk_sp<SkImage> SoftwareRenderer::ApplyImageFilter( SkImageFilter* filter, - const RenderPassDrawQuad* quad, + const AggregatedRenderPassDrawQuad* quad, const SkBitmap& to_filter, bool offset_expanded_bounds, SkIRect* result_rect) const { @@ -741,7 +748,7 @@ } gfx::Rect SoftwareRenderer::GetBackdropBoundingBoxForRenderPassQuad( - const RenderPassDrawQuad* quad, + const AggregatedRenderPassDrawQuad* quad, const cc::FilterOperations* backdrop_filters, base::Optional<gfx::RRectF> backdrop_filter_bounds_input, gfx::Transform contents_device_transform, @@ -780,7 +787,7 @@ } sk_sp<SkShader> SoftwareRenderer::GetBackdropFilterShader( - const RenderPassDrawQuad* quad, + const AggregatedRenderPassDrawQuad* quad, SkTileMode content_tile_mode) const { const cc::FilterOperations* backdrop_filters = BackdropFiltersForPass(quad->render_pass_id); @@ -894,10 +901,10 @@ } void SoftwareRenderer::UpdateRenderPassTextures( - const RenderPassList& render_passes_in_draw_order, - const base::flat_map<RenderPassId, RenderPassRequirements>& + const AggregatedRenderPassList& render_passes_in_draw_order, + const base::flat_map<AggregatedRenderPassId, RenderPassRequirements>& render_passes_in_frame) { - std::vector<RenderPassId> passes_to_delete; + std::vector<AggregatedRenderPassId> passes_to_delete; for (const auto& pair : render_pass_bitmaps_) { auto render_pass_it = render_passes_in_frame.find(pair.first); if (render_pass_it == render_passes_in_frame.end()) { @@ -918,12 +925,12 @@ // Delete RenderPass bitmaps from the previous frame that will not be used // again. - for (const RenderPassId& id : passes_to_delete) + for (const AggregatedRenderPassId& id : passes_to_delete) render_pass_bitmaps_.erase(id); } void SoftwareRenderer::AllocateRenderPassResourceIfNeeded( - const RenderPassId& render_pass_id, + const AggregatedRenderPassId& render_pass_id, const RenderPassRequirements& requirements) { auto it = render_pass_bitmaps_.find(render_pass_id); if (it != render_pass_bitmaps_.end()) { @@ -951,13 +958,13 @@ } bool SoftwareRenderer::IsRenderPassResourceAllocated( - const RenderPassId& render_pass_id) const { + const AggregatedRenderPassId& render_pass_id) const { auto it = render_pass_bitmaps_.find(render_pass_id); return it != render_pass_bitmaps_.end(); } gfx::Size SoftwareRenderer::GetRenderPassBackingPixelSize( - const RenderPassId& render_pass_id) { + const AggregatedRenderPassId& render_pass_id) { auto it = render_pass_bitmaps_.find(render_pass_id); DCHECK(it != render_pass_bitmaps_.end()); SkBitmap& bitmap = it->second;
diff --git a/components/viz/service/display/software_renderer.h b/components/viz/service/display/software_renderer.h index 9eae8d5b..1d34c54 100644 --- a/components/viz/service/display/software_renderer.h +++ b/components/viz/service/display/software_renderer.h
@@ -10,6 +10,7 @@ #include "base/macros.h" #include "build/build_config.h" +#include "components/viz/common/quads/aggregated_render_pass.h" #include "components/viz/service/display/direct_renderer.h" #include "components/viz/service/viz_service_export.h" #include "ui/latency/latency_info.h" @@ -19,7 +20,7 @@ class DisplayResourceProvider; class OutputSurface; class PictureDrawQuad; -class RenderPassDrawQuad; +class AggregatedRenderPassDrawQuad; class SoftwareOutputDevice; class SolidColorDrawQuad; class TextureDrawQuad; @@ -44,18 +45,19 @@ protected: bool CanPartialSwap() override; void UpdateRenderPassTextures( - const RenderPassList& render_passes_in_draw_order, - const base::flat_map<RenderPassId, RenderPassRequirements>& + const AggregatedRenderPassList& render_passes_in_draw_order, + const base::flat_map<AggregatedRenderPassId, RenderPassRequirements>& render_passes_in_frame) override; void AllocateRenderPassResourceIfNeeded( - const RenderPassId& render_pass_id, + const AggregatedRenderPassId& render_pass_id, const RenderPassRequirements& requirements) override; bool IsRenderPassResourceAllocated( - const RenderPassId& render_pass_id) const override; + const AggregatedRenderPassId& render_pass_id) const override; gfx::Size GetRenderPassBackingPixelSize( - const RenderPassId& render_pass_id) override; + const AggregatedRenderPassId& render_pass_id) override; void BindFramebufferToOutputSurface() override; - void BindFramebufferToTexture(const RenderPassId render_pass_id) override; + void BindFramebufferToTexture( + const AggregatedRenderPassId render_pass_id) override; void SetScissorTestRect(const gfx::Rect& scissor_rect) override; void PrepareSurfaceForPass(SurfaceInitializationMode initialization_mode, const gfx::Rect& render_pass_scissor) override; @@ -79,20 +81,21 @@ void DrawDebugBorderQuad(const DebugBorderDrawQuad* quad); void DrawPictureQuad(const PictureDrawQuad* quad); - void DrawRenderPassQuad(const RenderPassDrawQuad* quad); + void DrawRenderPassQuad(const AggregatedRenderPassDrawQuad* quad); void DrawSolidColorQuad(const SolidColorDrawQuad* quad); void DrawTextureQuad(const TextureDrawQuad* quad); void DrawTileQuad(const TileDrawQuad* quad); void DrawUnsupportedQuad(const DrawQuad* quad); - bool ShouldApplyBackdropFilters(const cc::FilterOperations* backdrop_filters, - const RenderPassDrawQuad* quad) const; + bool ShouldApplyBackdropFilters( + const cc::FilterOperations* backdrop_filters, + const AggregatedRenderPassDrawQuad* quad) const; sk_sp<SkImage> ApplyImageFilter(SkImageFilter* filter, - const RenderPassDrawQuad* quad, + const AggregatedRenderPassDrawQuad* quad, const SkBitmap& to_filter, bool offset_expanded_bounds, SkIRect* auto_bounds) const; gfx::Rect GetBackdropBoundingBoxForRenderPassQuad( - const RenderPassDrawQuad* quad, + const AggregatedRenderPassDrawQuad* quad, const cc::FilterOperations* backdrop_filters, base::Optional<gfx::RRectF> backdrop_filter_bounds_input, gfx::Transform contents_device_transform, @@ -101,11 +104,12 @@ gfx::Rect* unclipped_rect) const; SkBitmap GetBackdropBitmap(const gfx::Rect& bounding_rect) const; - sk_sp<SkShader> GetBackdropFilterShader(const RenderPassDrawQuad* quad, - SkTileMode content_tile_mode) const; + sk_sp<SkShader> GetBackdropFilterShader( + const AggregatedRenderPassDrawQuad* quad, + SkTileMode content_tile_mode) const; // A map from RenderPass id to the bitmap used to draw the RenderPass from. - base::flat_map<RenderPassId, SkBitmap> render_pass_bitmaps_; + base::flat_map<AggregatedRenderPassId, SkBitmap> render_pass_bitmaps_; bool disable_picture_quad_image_filtering_ = false;
diff --git a/components/viz/service/display/software_renderer_unittest.cc b/components/viz/service/display/software_renderer_unittest.cc index dd460707..3be3186 100644 --- a/components/viz/service/display/software_renderer_unittest.cc +++ b/components/viz/service/display/software_renderer_unittest.cc
@@ -98,7 +98,7 @@ SingleReleaseCallback::Create(base::DoNothing())); } - std::unique_ptr<SkBitmap> DrawAndCopyOutput(RenderPassList* list, + std::unique_ptr<SkBitmap> DrawAndCopyOutput(AggregatedRenderPassList* list, float device_scale_factor, gfx::Size viewport_size) { std::unique_ptr<SkBitmap> bitmap_result; @@ -145,8 +145,8 @@ InitializeRenderer(std::make_unique<SoftwareOutputDevice>()); - RenderPassId root_render_pass_id{1}; - std::unique_ptr<RenderPass> root_render_pass = RenderPass::Create(); + AggregatedRenderPassId root_render_pass_id{1}; + auto root_render_pass = std::make_unique<AggregatedRenderPass>(); root_render_pass->SetNew(root_render_pass_id, outer_rect, outer_rect, gfx::Transform()); SharedQuadState* shared_quad_state = @@ -164,7 +164,7 @@ outer_quad->SetNew(shared_quad_state, outer_rect, outer_rect, SK_ColorYELLOW, false); - RenderPassList list; + AggregatedRenderPassList list; list.push_back(std::move(root_render_pass)); float device_scale_factor = 1.f; @@ -213,8 +213,8 @@ gfx::Rect root_rect = outer_rect; - RenderPassId root_render_pass_id{1}; - std::unique_ptr<RenderPass> root_render_pass = RenderPass::Create(); + AggregatedRenderPassId root_render_pass_id{1}; + auto root_render_pass = std::make_unique<AggregatedRenderPass>(); root_render_pass->SetNew(root_render_pass_id, root_rect, root_rect, gfx::Transform()); SharedQuadState* shared_quad_state = @@ -231,7 +231,7 @@ mapped_resource_yellow, gfx::RectF(gfx::SizeF(outer_size)), outer_size, false, false, false); - RenderPassList list; + AggregatedRenderPassList list; list.push_back(std::move(root_render_pass)); float device_scale_factor = 1.f; @@ -274,8 +274,9 @@ ResourceId mapped_resource_cyan = resource_map[resource_cyan]; gfx::Rect root_rect(tile_size); - RenderPassId root_render_pass_id{1}; - std::unique_ptr<RenderPass> root_render_pass = RenderPass::Create(); + AggregatedRenderPassId root_render_pass_id{1}; + std::unique_ptr<AggregatedRenderPass> root_render_pass = + std::make_unique<AggregatedRenderPass>(); root_render_pass->SetNew(root_render_pass_id, root_rect, root_rect, gfx::Transform()); SharedQuadState* shared_quad_state = @@ -289,7 +290,7 @@ tile_size, false, false, false); quad->visible_rect = visible_rect; - RenderPassList list; + AggregatedRenderPassList list; list.push_back(std::move(root_render_pass)); float device_scale_factor = 1.f; @@ -323,11 +324,11 @@ settings_.should_clear_root_render_pass = false; InitializeRenderer(std::make_unique<SoftwareOutputDevice>()); - RenderPassList list; + AggregatedRenderPassList list; // Draw a fullscreen green quad in a first frame. - RenderPassId root_clear_pass_id{1}; - RenderPass* root_clear_pass = + AggregatedRenderPassId root_clear_pass_id{1}; + AggregatedRenderPass* root_clear_pass = cc::AddRenderPass(&list, root_clear_pass_id, gfx::Rect(viewport_size), gfx::Transform(), cc::FilterOperations()); cc::AddQuad(root_clear_pass, gfx::Rect(viewport_size), SK_ColorGREEN); @@ -349,8 +350,8 @@ // frame. gfx::Rect smaller_rect(20, 20, 60, 60); - RenderPassId root_smaller_pass_id{2}; - RenderPass* root_smaller_pass = + AggregatedRenderPassId root_smaller_pass_id{2}; + AggregatedRenderPass* root_smaller_pass = cc::AddRenderPass(&list, root_smaller_pass_id, gfx::Rect(viewport_size), gfx::Transform(), cc::FilterOperations()); cc::AddQuad(root_smaller_pass, smaller_rect, SK_ColorMAGENTA); @@ -377,19 +378,19 @@ gfx::Size viewport_size(100, 100); InitializeRenderer(std::make_unique<SoftwareOutputDevice>()); - RenderPassList list; + AggregatedRenderPassList list; // Pass drawn as inner quad is magenta. gfx::Rect smaller_rect(20, 20, 60, 60); - RenderPassId smaller_pass_id{2}; - RenderPass* smaller_pass = + AggregatedRenderPassId smaller_pass_id{2}; + auto* smaller_pass = cc::AddRenderPass(&list, smaller_pass_id, smaller_rect, gfx::Transform(), cc::FilterOperations()); cc::AddQuad(smaller_pass, smaller_rect, SK_ColorMAGENTA); // Root pass is green. - RenderPassId root_clear_pass_id{1}; - RenderPass* root_clear_pass = + AggregatedRenderPassId root_clear_pass_id{1}; + AggregatedRenderPass* root_clear_pass = AddRenderPass(&list, root_clear_pass_id, gfx::Rect(viewport_size), gfx::Transform(), cc::FilterOperations()); cc::AddRenderPassQuad(root_clear_pass, smaller_pass); @@ -477,9 +478,9 @@ { // Draw one black frame to make sure output surface is reshaped before // tests. - RenderPassList list; - RenderPassId root_pass_id{1}; - RenderPass* root_pass = + AggregatedRenderPassList list; + AggregatedRenderPassId root_pass_id{1}; + auto* root_pass = AddRenderPass(&list, root_pass_id, gfx::Rect(viewport_size), gfx::Transform(), cc::FilterOperations()); cc::AddQuad(root_pass, gfx::Rect(viewport_size), SK_ColorBLACK); @@ -493,9 +494,9 @@ gfx::DisplayColorSpaces()); } { - RenderPassList list; - RenderPassId root_pass_id{1}; - RenderPass* root_pass = + AggregatedRenderPassList list; + AggregatedRenderPassId root_pass_id{1}; + auto* root_pass = AddRenderPass(&list, root_pass_id, gfx::Rect(viewport_size), gfx::Transform(), cc::FilterOperations()); cc::AddQuad(root_pass, gfx::Rect(viewport_size), SK_ColorGREEN);
diff --git a/components/viz/service/display/surface_aggregator.cc b/components/viz/service/display/surface_aggregator.cc index 7847a0e..7e1890c 100644 --- a/components/viz/service/display/surface_aggregator.cc +++ b/components/viz/service/display/surface_aggregator.cc
@@ -20,6 +20,7 @@ #include "base/trace_event/trace_event.h" #include "cc/base/math_util.h" #include "components/viz/common/display/de_jelly.h" +#include "components/viz/common/quads/aggregated_render_pass_draw_quad.h" #include "components/viz/common/quads/compositor_frame.h" #include "components/viz/common/quads/debug_border_draw_quad.h" #include "components/viz/common/quads/draw_quad.h" @@ -280,8 +281,7 @@ // before this. void SurfaceAggregator::UnionSurfaceDamageRectsOnTop( const gfx::Rect& surface_rect, - const gfx::Transform& quad_to_root_target_transform, - const RenderPass* render_pass) { + const gfx::Transform& quad_to_root_target_transform) { DCHECK(!surface_rect.IsEmpty()); gfx::Rect damage_rect_in_root_target_space = @@ -305,14 +305,42 @@ const Surface* surface, const RenderPassList& render_pass_list, const gfx::Transform& parent_target_transform, - const RenderPass* dest_pass, + const RenderPass* render_pass, + gfx::Rect* occluding_damage_rect) { + auto aggregated_id = + pass_id_remapper_.Remap(render_pass->id, surface->surface_id()); + return ProcessSurfaceOccludingDamageInternal( + surface, render_pass_list, parent_target_transform, + render_pass->transform_to_root_target, aggregated_id, + render_pass->cache_render_pass, occluding_damage_rect); +} + +DrawQuad* SurfaceAggregator::ProcessSurfaceOccludingDamage( + const Surface* surface, + const RenderPassList& render_pass_list, + const gfx::Transform& parent_target_transform, + const AggregatedRenderPass* render_pass, + gfx::Rect* occluding_damage_rect) { + return ProcessSurfaceOccludingDamageInternal( + surface, render_pass_list, parent_target_transform, + render_pass->transform_to_root_target, render_pass->id, + render_pass->cache_render_pass, occluding_damage_rect); +} + +DrawQuad* SurfaceAggregator::ProcessSurfaceOccludingDamageInternal( + const Surface* surface, + const RenderPassList& render_pass_list, + const gfx::Transform& parent_target_transform, + const gfx::Transform& dest_transform_to_root_target, + const AggregatedRenderPassId& dest_pass_id, + bool dest_pass_cached, gfx::Rect* occluding_damage_rect) { if (!needs_surface_occluding_damage_rect_) return nullptr; RenderPass* last_render_pass = render_pass_list.back().get(); - gfx::Transform quad_to_root_target_transform = gfx::Transform( - dest_pass->transform_to_root_target, parent_target_transform); + gfx::Transform quad_to_root_target_transform = + gfx::Transform(dest_transform_to_root_target, parent_target_transform); // The occluding damage optimization currently relies on two things - there // can't be any damage above the quad within the surface, and the quad needs @@ -347,7 +375,7 @@ } gfx::Rect surface_damage_rect; - if (RenderPassNeedsFullDamage(dest_pass)) { + if (RenderPassNeedsFullDamage(dest_pass_id, dest_pass_cached)) { surface_damage_rect = last_render_pass->output_rect; } else { surface_damage_rect = DamageRectForSurface(surface, *last_render_pass, @@ -358,20 +386,17 @@ // This should be done AFTER checking the occluding damage because the surface // on top should not include its own surface. if (!surface_damage_rect.IsEmpty()) { - UnionSurfaceDamageRectsOnTop( - surface_damage_rect, quad_to_root_target_transform, last_render_pass); + UnionSurfaceDamageRectsOnTop(surface_damage_rect, + quad_to_root_target_transform); } return target_quad; } bool SurfaceAggregator::RenderPassNeedsFullDamage( - const RenderPass* pass) const { - if (copy_request_passes_.count(pass->id) || pass->cache_render_pass || - moved_pixel_passes_.count(pass->id)) { - return true; - } else { - return false; - } + const AggregatedRenderPassId& id, + bool cache_render_pass) const { + return cache_render_pass || copy_request_passes_.count(id) || + moved_pixel_passes_.count(id); } // static @@ -395,7 +420,7 @@ float parent_device_scale_factor, const gfx::Transform& target_transform, const ClipData& clip_rect, - RenderPass* dest_pass, + AggregatedRenderPass* dest_pass, bool ignore_undamaged, gfx::Rect* damage_rect_in_quad_space, bool* damage_rect_in_quad_space_valid, @@ -450,7 +475,7 @@ const gfx::Transform& target_transform, const ClipData& clip_rect, bool stretch_content_to_fill_bounds, - RenderPass* dest_pass, + AggregatedRenderPass* dest_pass, bool ignore_undamaged, gfx::Rect* damage_rect_in_quad_space, bool* damage_rect_in_quad_space_valid, @@ -566,11 +591,9 @@ size_t sqs_size = source.shared_quad_state_list.size(); size_t dq_size = source.quad_list.size(); - std::unique_ptr<RenderPass> copy_pass( - RenderPass::Create(sqs_size, dq_size)); + auto copy_pass = std::make_unique<AggregatedRenderPass>(sqs_size, dq_size); - RenderPassId remapped_pass_id = - pass_id_remapper_.Remap(source.id, surface_id); + auto remapped_pass_id = pass_id_remapper_.Remap(source.id, surface_id); gfx::Rect output_rect = source.output_rect; if (max_render_target_size_ > 0) { @@ -609,7 +632,8 @@ // whole output rect so that we always drawn the full content. Otherwise, we // might have incompleted copy request, or cached patially drawn render // pass. - if (!RenderPassNeedsFullDamage(copy_pass.get())) { + if (!RenderPassNeedsFullDamage(copy_pass->id, + copy_pass->cache_render_pass)) { gfx::Transform inverse_transform(gfx::Transform::kSkipInitialization); if (copy_pass->transform_to_root_target.GetInverse(&inverse_transform)) { gfx::Rect damage_rect_in_render_pass_space = @@ -697,18 +721,19 @@ // We can't produce content outside of |quad_rect|, so clip the visible // rect if necessary. quad_visible_rect.Intersect(quad_rect); - RenderPassId remapped_pass_id = - pass_id_remapper_.Remap(last_pass.id, surface_id); + auto remapped_pass_id = pass_id_remapper_.Remap(last_pass.id, surface_id); if (quad_visible_rect.IsEmpty()) { dest_pass_list_->erase( std::remove_if( dest_pass_list_->begin(), dest_pass_list_->end(), - [&remapped_pass_id](const std::unique_ptr<RenderPass>& pass) { + [&remapped_pass_id]( + const std::unique_ptr<AggregatedRenderPass>& pass) { return pass->id == remapped_pass_id; }), dest_pass_list_->end()); } else { - auto* quad = dest_pass->CreateAndAppendDrawQuad<RenderPassDrawQuad>(); + auto* quad = + dest_pass->CreateAndAppendDrawQuad<AggregatedRenderPassDrawQuad>(); quad->SetNew(shared_quad_state, quad_rect, quad_visible_rect, remapped_pass_id, 0, gfx::RectF(), gfx::Size(), gfx::Vector2dF(), gfx::PointF(), tex_coord_rect, @@ -724,7 +749,7 @@ const SurfaceDrawQuad* surface_quad, const gfx::Transform& target_transform, const ClipData& clip_rect, - RenderPass* dest_pass, + AggregatedRenderPass* dest_pass, const RoundedCornerInfo& rounded_corner_info) { // The primary surface is unavailable and there is no fallback // surface specified so create a SolidColorDrawQuad with the default @@ -746,7 +771,7 @@ target_transform, surface_quad->shared_quad_state->quad_to_target_transform); transform.ConcatTransform(dest_pass->transform_to_root_target); - UnionSurfaceDamageRectsOnTop(surface_quad->rect, transform, dest_pass); + UnionSurfaceDamageRectsOnTop(surface_quad->rect, transform); } } @@ -757,7 +782,7 @@ const gfx::Transform& target_transform, const ClipData& clip_rect, SkColor background_color, - RenderPass* dest_pass, + AggregatedRenderPass* dest_pass, const RoundedCornerInfo& rounded_corner_info) { bool has_transparent_background = background_color == SK_ColorTRANSPARENT; @@ -836,7 +861,7 @@ if (!color_conversion_render_pass_id_) color_conversion_render_pass_id_ = pass_id_remapper_.NextAvailableId(); - auto color_conversion_pass = RenderPass::Create(1, 1); + auto color_conversion_pass = std::make_unique<AggregatedRenderPass>(1, 1); color_conversion_pass->SetNew(color_conversion_render_pass_id_, output_rect, root_render_pass->damage_rect, root_render_pass->transform_to_root_target); @@ -858,8 +883,8 @@ /*is_clipped=*/false, /*are_contents_opaque=*/false, /*opacity=*/1.f, /*blend_mode=*/SkBlendMode::kSrc, /*sorting_context_id=*/0); - auto* quad = - color_conversion_pass->CreateAndAppendDrawQuad<RenderPassDrawQuad>(); + auto* quad = color_conversion_pass + ->CreateAndAppendDrawQuad<AggregatedRenderPassDrawQuad>(); quad->SetNew(shared_quad_state, output_rect, output_rect, root_render_pass->id, 0, gfx::RectF(), gfx::Size(), gfx::Vector2dF(), gfx::PointF(), gfx::RectF(output_rect), @@ -879,7 +904,7 @@ if (!display_transform_render_pass_id_) display_transform_render_pass_id_ = pass_id_remapper_.NextAvailableId(); - auto display_transform_pass = RenderPass::Create(1, 1); + auto display_transform_pass = std::make_unique<AggregatedRenderPass>(1, 1); display_transform_pass->SetAll( display_transform_render_pass_id_, cc::MathUtil::MapEnclosedRectWith2dAxisAlignedTransform( @@ -915,8 +940,8 @@ /*is_clipped=*/false, are_contents_opaque, /*opacity=*/1.f, /*blend_mode=*/SkBlendMode::kSrcOver, /*sorting_context_id=*/0); - auto* quad = - display_transform_pass->CreateAndAppendDrawQuad<RenderPassDrawQuad>(); + auto* quad = display_transform_pass + ->CreateAndAppendDrawQuad<AggregatedRenderPassDrawQuad>(); quad->SetNew(shared_quad_state, output_rect, output_rect, root_render_pass->id, 0, gfx::RectF(), gfx::Size(), gfx::Vector2dF(), gfx::PointF(), gfx::RectF(output_rect), @@ -929,7 +954,7 @@ const SharedQuadState* source_sqs, const gfx::Transform& target_transform, const ClipData& clip_rect, - RenderPass* dest_render_pass, + AggregatedRenderPass* dest_render_pass, const RoundedCornerInfo& rounded_corner_info, const gfx::Rect& occluding_damage_rect, bool occluding_damage_rect_valid) { @@ -947,7 +972,7 @@ const gfx::Rect& quad_layer_rect, const gfx::Rect& visible_quad_layer_rect, const ClipData& clip_rect, - RenderPass* dest_render_pass, + AggregatedRenderPass* dest_render_pass, const RoundedCornerInfo& rounded_corner_info, const gfx::Rect& occluding_damage_rect, bool occluding_damage_rect_valid) { @@ -987,7 +1012,7 @@ const std::unordered_map<ResourceId, ResourceId>& child_to_parent_map, const gfx::Transform& target_transform, const ClipData& clip_rect, - RenderPass* dest_pass, + AggregatedRenderPass* dest_pass, const SurfaceId& surface_id, const RoundedCornerInfo& parent_rounded_corner_info, const gfx::Rect& occluding_damage_rect, @@ -1088,7 +1113,7 @@ if (quad->material == DrawQuad::Material::kRenderPass) { const auto* pass_quad = RenderPassDrawQuad::MaterialCast(quad); RenderPassId original_pass_id = pass_quad->render_pass_id; - RenderPassId remapped_pass_id = + AggregatedRenderPassId remapped_pass_id = pass_id_remapper_.Remap(original_pass_id, surface_id); // If the RenderPassDrawQuad is referring to other render pass with the @@ -1171,7 +1196,7 @@ size_t sqs_size = source.shared_quad_state_list.size(); size_t dq_size = source.quad_list.size(); - auto copy_pass = RenderPass::Create(sqs_size, dq_size); + auto copy_pass = std::make_unique<AggregatedRenderPass>(sqs_size, dq_size); MoveMatchingRequests(source.id, ©_requests, ©_pass->copy_requests); @@ -1181,7 +1206,7 @@ is_root_pass && (copy_pass->copy_requests.empty() || surface_transform.IsIdentity()); - RenderPassId remapped_pass_id = + auto remapped_pass_id = pass_id_remapper_.Remap(source.id, surface->surface_id()); gfx::Rect output_rect = source.output_rect; @@ -1220,7 +1245,8 @@ // whole output rect so that we always drawn the full content. Otherwise, we // might have incompleted copy request, or cached patially drawn render // pass. - if (!RenderPassNeedsFullDamage(copy_pass.get())) { + if (!RenderPassNeedsFullDamage(copy_pass->id, + copy_pass->cache_render_pass)) { gfx::Transform inverse_transform(gfx::Transform::kSkipInitialization); if (copy_pass->transform_to_root_target.GetInverse(&inverse_transform)) { gfx::Rect damage_rect_in_render_pass_space = @@ -1268,7 +1294,7 @@ has_pixel_moving_backdrop_filter_ = true; } - RenderPassId remapped_pass_id = + auto remapped_pass_id = pass_id_remapper_.Remap(render_pass.id, surface->surface_id()); // |moved_pixel_passes_| stores all the render passes affected by filters // that move pixels, so |in_moved_pixel_rp| should be set to true either @@ -1417,7 +1443,7 @@ } } - RenderPassId remapped_child_pass_id = + auto remapped_child_pass_id = pass_id_remapper_.Remap(child_pass_id, surface->surface_id()); render_pass_dependencies_[remapped_pass_id].insert( @@ -1454,12 +1480,13 @@ return damage_rect; } -gfx::Rect SurfaceAggregator::PrewalkSurface(Surface* surface, - bool in_moved_pixel_rp, - RenderPassId parent_pass_id, - bool will_draw, - const gfx::Rect& damage_from_parent, - PrewalkResult* result) { +gfx::Rect SurfaceAggregator::PrewalkSurface( + Surface* surface, + bool in_moved_pixel_rp, + AggregatedRenderPassId parent_pass_id, + bool will_draw, + const gfx::Rect& damage_from_parent, + PrewalkResult* result) { if (referenced_surfaces_.count(surface->surface_id())) return gfx::Rect(); @@ -1483,7 +1510,7 @@ provider_->ReceiveFromChild(child_id, frame.resource_list); } - RenderPassId remapped_pass_id = pass_id_remapper_.Remap( + auto remapped_pass_id = pass_id_remapper_.Remap( frame.render_pass_list.back()->id, surface->surface_id()); if (parent_pass_id) render_pass_dependencies_[parent_pass_id].insert(remapped_pass_id); @@ -1580,14 +1607,14 @@ result->undrawn_surfaces.insert(surface_id); Surface* undrawn_surface = manager_->GetSurfaceForId(surface_id); if (undrawn_surface) - PrewalkSurface(undrawn_surface, false, RenderPassId(), + PrewalkSurface(undrawn_surface, false, AggregatedRenderPassId(), /*will_draw=*/false, gfx::Rect(), result); } } for (const auto& render_pass : frame.render_pass_list) { if (!render_pass->copy_requests.empty()) { - RenderPassId remapped_pass_id = + auto remapped_pass_id = pass_id_remapper_.Remap(render_pass->id, surface->surface_id()); copy_request_passes_.insert(remapped_pass_id); } @@ -1644,12 +1671,12 @@ } void SurfaceAggregator::PropagateCopyRequestPasses() { - std::vector<RenderPassId> copy_requests_to_iterate( + std::vector<AggregatedRenderPassId> copy_requests_to_iterate( copy_request_passes_.begin(), copy_request_passes_.end()); while (!copy_requests_to_iterate.empty()) { - RenderPassId first = copy_requests_to_iterate.back(); + auto id = copy_requests_to_iterate.back(); copy_requests_to_iterate.pop_back(); - auto it = render_pass_dependencies_.find(first); + auto it = render_pass_dependencies_.find(id); if (it == render_pass_dependencies_.end()) continue; for (auto pass : it->second) { @@ -1734,7 +1761,8 @@ DCHECK(referenced_surfaces_.empty()); PrewalkResult prewalk_result; gfx::Rect surfaces_damage_rect = PrewalkSurface( - surface, /*in_moved_pixel_rp=*/false, /*parent_pass=*/RenderPassId(), + surface, /*in_moved_pixel_rp=*/false, + /*parent_pass=*/AggregatedRenderPassId(), /*will_draw=*/true, /*damage_from_parent=*/gfx::Rect(), &prewalk_result); root_damage_rect_ = surfaces_damage_rect; // |root_damage_rect_| is used to restrict aggregating quads only if they @@ -1772,7 +1800,8 @@ // surfaces. // The damage on the root render pass should not include the expanded area // since Renderer and OverlayProcessor expect the non expanded damage. - if (!RenderPassNeedsFullDamage(dest_pass_list_->back().get())) + auto* last_pass = dest_pass_list_->back().get(); + if (!RenderPassNeedsFullDamage(last_pass->id, last_pass->cache_render_pass)) dest_pass_list_->back()->damage_rect.Intersect(surfaces_damage_rect); // Now that we've handled our main surface aggregation, apply de-jelly effect @@ -1979,7 +2008,7 @@ // TODO(ericrk): Handle backdrop filters? // TODO(ericrk): This will end up skewing copy requests. Address if // necessary. - std::unique_ptr<RenderPass> old_root = std::move(dest_pass_list_->back()); + auto old_root = std::move(dest_pass_list_->back()); dest_pass_list_->pop_back(); auto new_root = root_render_pass->Copy(root_render_pass->id); new_root->copy_requests = std::move(old_root->copy_requests); @@ -1987,7 +2016,7 @@ // Data tracking the current sub RenderPass (if any) which is being appended // to. We can keep re-using a sub RenderPass if the skew has not changed and // if we are in the typical kSrcOver blend mode. - std::unique_ptr<RenderPass> sub_render_pass; + std::unique_ptr<AggregatedRenderPass> sub_render_pass; SkBlendMode sub_render_pass_blend_mode; float sub_render_pass_opacity; @@ -2015,7 +2044,7 @@ bool create_render_pass = has_skew && state->is_clipped && state->clip_rect != jelly_clip; if (!sub_render_pass && create_render_pass) { - sub_render_pass = RenderPass::Create(1, 1); + sub_render_pass = std::make_unique<AggregatedRenderPass>(1, 1); gfx::Transform skew_transform; skew_transform.Skew(0.0f, max_skew); // Ignore rectangles for now, these are updated in @@ -2055,7 +2084,7 @@ const cc::ListContainer<DrawQuad>::Iterator& end, const gfx::Rect& jelly_clip, float skew, - RenderPass* render_pass) { + AggregatedRenderPass* render_pass) { auto* quad = **quad_iterator; const auto* state = quad->shared_quad_state; @@ -2077,20 +2106,15 @@ // Next, if this is a RenderPass quad, find any filters and expand the // visible rect. if (quad->material == DrawQuad::Material::kRenderPass) { - RenderPassId target_id = - RenderPassDrawQuad::MaterialCast(quad)->render_pass_id; - RenderPass* source_render_pass = nullptr; + auto target_id = AggregatedRenderPassId( + uint64_t{RenderPassDrawQuad::MaterialCast(quad)->render_pass_id}); for (auto& rp : *dest_pass_list_) { if (rp->id == target_id) { - source_render_pass = rp.get(); + render_pass_visible_rect_f = gfx::RectF( + rp->filters.MapRect(state->visible_quad_layer_rect, SkMatrix())); break; } } - if (source_render_pass) { - render_pass_visible_rect_f = - gfx::RectF(source_render_pass->filters.MapRect( - state->visible_quad_layer_rect, SkMatrix())); - } } // Next, find the enclosing Rect for the transformed target space RectF. state->quad_to_target_transform.TransformRect(&render_pass_visible_rect_f); @@ -2125,7 +2149,7 @@ void SurfaceAggregator::CreateDeJellyNormalQuads( cc::ListContainer<DrawQuad>::Iterator* quad_iterator, const cc::ListContainer<DrawQuad>::Iterator& end, - RenderPass* root_pass, + AggregatedRenderPass* root_pass, float skew) { auto* quad = **quad_iterator; const auto* state = quad->shared_quad_state; @@ -2149,15 +2173,16 @@ const gfx::Rect& jelly_clip, float opacity, SkBlendMode blend_mode, - RenderPass* root_pass, - std::unique_ptr<RenderPass> render_pass) { + AggregatedRenderPass* root_pass, + std::unique_ptr<AggregatedRenderPass> render_pass) { // Create a new quad for this renderpass and append it to the pass list. auto* new_state = root_pass->CreateAndAppendSharedQuadState(); gfx::Transform transform; new_state->SetAll(transform, render_pass->output_rect, render_pass->output_rect, gfx::RRectF(), jelly_clip, true, false, opacity, blend_mode, 0); - auto* quad = root_pass->CreateAndAppendDrawQuad<RenderPassDrawQuad>(); + auto* quad = + root_pass->CreateAndAppendDrawQuad<AggregatedRenderPassDrawQuad>(); quad->SetNew(new_state, render_pass->output_rect, render_pass->output_rect, render_pass->id, 0, gfx::RectF(), gfx::Size(), gfx::Vector2dF(), gfx::PointF(), @@ -2173,14 +2198,16 @@ void SurfaceAggregator::AppendDeJellyQuadsForSharedQuadState( cc::ListContainer<DrawQuad>::Iterator* quad_iterator, const cc::ListContainer<DrawQuad>::Iterator& end, - RenderPass* render_pass, + AggregatedRenderPass* render_pass, const SharedQuadState* state) { auto* quad = **quad_iterator; while (quad->shared_quad_state == state) { - if (quad->material == DrawQuad::Material::kRenderPass) { - const auto* pass_quad = RenderPassDrawQuad::MaterialCast(quad); - render_pass->CopyFromAndAppendRenderPassDrawQuad( - pass_quad, pass_quad->render_pass_id); + // Since we're dealing with post-aggregated passes, we should not have any + // RenderPassDrawQuads. + DCHECK_NE(quad->material, DrawQuad::Material::kRenderPass); + if (quad->material == DrawQuad::Material::kAggregatedRenderPass) { + const auto* pass_quad = AggregatedRenderPassDrawQuad::MaterialCast(quad); + render_pass->CopyFromAndAppendRenderPassDrawQuad(pass_quad); } else { render_pass->CopyFromAndAppendDrawQuad(quad); } @@ -2197,7 +2224,7 @@ // damage the entire surface, as we may have removed jelly from an otherwise // unchanged quad. if (last_frame_had_jelly_ && !had_jelly) { - RenderPass* root_pass = dest_pass_list_->back().get(); + auto* root_pass = dest_pass_list_->back().get(); root_pass->damage_rect = root_pass->output_rect; } last_frame_had_jelly_ = had_jelly;
diff --git a/components/viz/service/display/surface_aggregator.h b/components/viz/service/display/surface_aggregator.h index afc3b7b..76a13a61 100644 --- a/components/viz/service/display/surface_aggregator.h +++ b/components/viz/service/display/surface_aggregator.h
@@ -110,7 +110,7 @@ float parent_device_scale_factor, const gfx::Transform& target_transform, const ClipData& clip_rect, - RenderPass* dest_pass, + AggregatedRenderPass* dest_pass, bool ignore_undamaged, gfx::Rect* damage_rect_in_quad_space, bool* damage_rect_in_quad_space_valid, @@ -124,7 +124,7 @@ const gfx::Transform& target_transform, const ClipData& clip_rect, bool stretch_content_to_fill_bounds, - RenderPass* dest_pass, + AggregatedRenderPass* dest_pass, bool ignore_undamaged, gfx::Rect* damage_rect_in_quad_space, bool* damage_rect_in_quad_space_valid, @@ -136,7 +136,7 @@ const SurfaceDrawQuad* surface_quad, const gfx::Transform& target_transform, const ClipData& clip_rect, - RenderPass* dest_pass, + AggregatedRenderPass* dest_pass, const RoundedCornerInfo& rounded_corner_info); void EmitGutterQuadsIfNecessary( @@ -146,14 +146,14 @@ const gfx::Transform& target_transform, const ClipData& clip_rect, SkColor background_color, - RenderPass* dest_pass, + AggregatedRenderPass* dest_pass, const RoundedCornerInfo& rounded_corner_info); SharedQuadState* CopySharedQuadState( const SharedQuadState* source_sqs, const gfx::Transform& target_transform, const ClipData& clip_rect, - RenderPass* dest_render_pass, + AggregatedRenderPass* dest_render_pass, const RoundedCornerInfo& rounded_corner_info, const gfx::Rect& occluding_damage_rect, bool occluding_damage_rect_valid); @@ -165,7 +165,7 @@ const gfx::Rect& quad_layer_rect, const gfx::Rect& visible_quad_layer_rect, const ClipData& clip_rect, - RenderPass* dest_render_pass, + AggregatedRenderPass* dest_render_pass, const RoundedCornerInfo& rounded_corner_info, const gfx::Rect& occluding_damage_rect, bool occluding_damage_rect_valid); @@ -177,7 +177,7 @@ const std::unordered_map<ResourceId, ResourceId>& resource_to_child_map, const gfx::Transform& target_transform, const ClipData& clip_rect, - RenderPass* dest_pass, + AggregatedRenderPass* dest_pass, const SurfaceId& surface_id, const RoundedCornerInfo& rounded_corner_info, const gfx::Rect& occluding_damage_rect, @@ -227,7 +227,7 @@ // and return the combined damage rect. gfx::Rect PrewalkSurface(Surface* surface, bool in_moved_pixel_rp, - RenderPassId parent_pass, + AggregatedRenderPassId parent_pass, bool will_draw, const gfx::Rect& damage_from_parent, PrewalkResult* result); @@ -258,15 +258,32 @@ const DrawQuad* quad, const gfx::Transform& parent_quad_to_root_target_transform); void UnionSurfaceDamageRectsOnTop(const gfx::Rect& surface_rect, - const gfx::Transform& target_transform, - const RenderPass* pass); + const gfx::Transform& target_transform); + + // Determines occluding damage. Note that there is two version of the + // function, differing on what type of RenderPass is given (aggregated or from + // the compositor). If the compositor pass is given, it is assumed that it + // will be transformed into an aggregated pass later, so the values (with the + // exception of the id) will be the same. The id is remapped to an aggregated + // id. DrawQuad* ProcessSurfaceOccludingDamage( const Surface* surface, const RenderPassList& render_pass_list, const gfx::Transform& target_transform, const RenderPass* dest_pass, gfx::Rect* occluding_damage_rect); - bool RenderPassNeedsFullDamage(const RenderPass* pass) const; + DrawQuad* ProcessSurfaceOccludingDamage( + const Surface* surface, + const RenderPassList& render_pass_list, + const gfx::Transform& target_transform, + const AggregatedRenderPass* dest_pass, + gfx::Rect* occluding_damage_rect); + + // Returns true if the render pass with the given id and cache_render_pass + // flag would need full damage. + bool RenderPassNeedsFullDamage(const AggregatedRenderPassId& id, + bool cache_render_pass) const; + bool IsRootSurface(const Surface* surface) const; static void UnrefResources(base::WeakPtr<SurfaceClient> surface_client, @@ -296,30 +313,41 @@ const cc::ListContainer<DrawQuad>::Iterator& end, const gfx::Rect& jelly_clip, float skew, - RenderPass* render_pass); + AggregatedRenderPass* render_pass); // Appends quads directly to |root_pass|, applying |skew|. void CreateDeJellyNormalQuads( cc::ListContainer<DrawQuad>::Iterator* quad_iterator, const cc::ListContainer<DrawQuad>::Iterator& end, - RenderPass* root_pass, + AggregatedRenderPass* root_pass, float skew); // Appends |render_pass| to |root_pass|, applying |skew|, |jelly_clip|, // |opacity|, and |blend_mode|. - void AppendDeJellyRenderPass(float skew, - const gfx::Rect& jelly_clip, - float opacity, - SkBlendMode blend_mode, - RenderPass* root_pass, - std::unique_ptr<RenderPass> render_pass); + void AppendDeJellyRenderPass( + float skew, + const gfx::Rect& jelly_clip, + float opacity, + SkBlendMode blend_mode, + AggregatedRenderPass* root_pass, + std::unique_ptr<AggregatedRenderPass> render_pass); // Appends quads from |quad_iterator| to |render_pass| for |state|. void AppendDeJellyQuadsForSharedQuadState( cc::ListContainer<DrawQuad>::Iterator* quad_iterator, const cc::ListContainer<DrawQuad>::Iterator& end, - RenderPass* render_pass, + AggregatedRenderPass* render_pass, const SharedQuadState* state); // Update |last_frame_had_jelly_|, should be called once per frame. void SetLastFrameHadJelly(bool had_jelly); + // An internal helper for the `ProcessSurfaceOccludingDamage()` functions. + DrawQuad* ProcessSurfaceOccludingDamageInternal( + const Surface* surface, + const RenderPassList& render_pass_list, + const gfx::Transform& parent_target_transform, + const gfx::Transform& dest_transform_to_root_target, + const AggregatedRenderPassId& dest_pass_id, + bool dest_pass_cached, + gfx::Rect* occluding_damage_rect); + SurfaceManager* manager_; DisplayResourceProvider* provider_; @@ -335,9 +363,9 @@ // render passes. int max_render_target_size_ = 0; // The id for the final color conversion render pass. - RenderPassId color_conversion_render_pass_id_; + AggregatedRenderPassId color_conversion_render_pass_id_; // The id for the optional render pass used to apply the display transform. - RenderPassId display_transform_render_pass_id_; + AggregatedRenderPassId display_transform_render_pass_id_; base::flat_map<SurfaceId, int> surface_id_to_resource_child_id_; @@ -363,26 +391,26 @@ base::flat_set<SurfaceId> valid_surfaces_; // This is the pass list for the aggregated frame. - RenderPassList* dest_pass_list_; + AggregatedRenderPassList* dest_pass_list_; // The target display time for the aggregated frame. base::TimeTicks expected_display_time_; // This is the set of aggregated pass ids that are affected by filters that // move pixels. - base::flat_set<RenderPassId> moved_pixel_passes_; + base::flat_set<AggregatedRenderPassId> moved_pixel_passes_; // This is the set of aggregated pass ids that are drawn by copy requests, so // should not have their damage rects clipped to the root damage rect. - base::flat_set<RenderPassId> copy_request_passes_; + base::flat_set<AggregatedRenderPassId> copy_request_passes_; // This is the set of aggregated pass ids that has damage from contributing // content. - base::flat_set<RenderPassId> contributing_content_damaged_passes_; + base::flat_set<AggregatedRenderPassId> contributing_content_damaged_passes_; // This maps each aggregated pass id to the set of (aggregated) pass ids // that its RenderPassDrawQuads depend on - base::flat_map<RenderPassId, base::flat_set<RenderPassId>> + base::flat_map<AggregatedRenderPassId, base::flat_set<AggregatedRenderPassId>> render_pass_dependencies_; // The root damage rect of the currently-aggregating frame.
diff --git a/components/viz/service/display/surface_aggregator_pixeltest.cc b/components/viz/service/display/surface_aggregator_pixeltest.cc index d133cf7..4dd86c8 100644 --- a/components/viz/service/display/surface_aggregator_pixeltest.cc +++ b/components/viz/service/display/surface_aggregator_pixeltest.cc
@@ -119,7 +119,7 @@ bool discard_alpha = false; cc::ExactPixelComparator pixel_comparator(discard_alpha); - RenderPassList* pass_list = &aggregated_frame.render_pass_list; + auto* pass_list = &aggregated_frame.render_pass_list; EXPECT_TRUE(this->RunPixelTest(pass_list, base::FilePath(FILE_PATH_LITERAL("green.png")), pixel_comparator)); @@ -199,7 +199,7 @@ bool discard_alpha = false; cc::ExactPixelComparator pixel_comparator(discard_alpha); - RenderPassList* pass_list = &aggregated_frame.render_pass_list; + auto* pass_list = &aggregated_frame.render_pass_list; EXPECT_TRUE(this->RunPixelTest( pass_list, base::FilePath(FILE_PATH_LITERAL("blue_yellow.png")), pixel_comparator)); @@ -336,7 +336,7 @@ bool discard_alpha = false; cc::ExactPixelComparator pixel_comparator(discard_alpha); - RenderPassList* pass_list = &aggregated_frame.render_pass_list; + auto* pass_list = &aggregated_frame.render_pass_list; EXPECT_TRUE(this->RunPixelTest( pass_list, base::FilePath(FILE_PATH_LITERAL("four_blue_green_checkers.png")),
diff --git a/components/viz/service/display/surface_aggregator_unittest.cc b/components/viz/service/display/surface_aggregator_unittest.cc index 07f7eb9..d26ed7d 100644 --- a/components/viz/service/display/surface_aggregator_unittest.cc +++ b/components/viz/service/display/surface_aggregator_unittest.cc
@@ -21,6 +21,8 @@ #include "base/time/time.h" #include "cc/test/render_pass_test_utils.h" #include "components/viz/common/frame_sinks/begin_frame_args.h" +#include "components/viz/common/quads/aggregated_render_pass.h" +#include "components/viz/common/quads/aggregated_render_pass_draw_quad.h" #include "components/viz/common/quads/compositor_frame.h" #include "components/viz/common/quads/draw_quad.h" #include "components/viz/common/quads/render_pass.h" @@ -316,13 +318,16 @@ EXPECT_EQ(expected_quad.rect, solid_color_quad->rect); break; } + // Expected RenderPass quad will become AggregatedRenderPass after + // aggregation. case DrawQuad::Material::kRenderPass: { - ASSERT_EQ(DrawQuad::Material::kRenderPass, quad->material); + ASSERT_EQ(DrawQuad::Material::kAggregatedRenderPass, quad->material); - const auto* render_pass_quad = RenderPassDrawQuad::MaterialCast(quad); + const auto* render_pass_quad = + AggregatedRenderPassDrawQuad::MaterialCast(quad); EXPECT_EQ(expected_quad.render_pass_id, - render_pass_quad->render_pass_id); + RenderPassId{uint64_t{render_pass_quad->render_pass_id}}); EXPECT_EQ(expected_quad.can_use_backdrop_filter_cache, render_pass_quad->can_use_backdrop_filter_cache); break; @@ -334,7 +339,7 @@ } static void TestPassMatchesExpectations(Pass expected_pass, - const RenderPass* pass) { + const AggregatedRenderPass* pass) { ASSERT_EQ(expected_pass.quads.size(), pass->quad_list.size()); for (auto iter = pass->quad_list.cbegin(); iter != pass->quad_list.cend(); ++iter) { @@ -345,12 +350,12 @@ static void TestPassesMatchExpectations( const std::vector<Pass>& expected_passes, - const RenderPassList* passes) { + const AggregatedRenderPassList* passes) { ASSERT_EQ(expected_passes.size(), passes->size()); for (size_t i = 0; i < expected_passes.size(); ++i) { SCOPED_TRACE(base::StringPrintf("Pass number %" PRIuS, i)); - RenderPass* pass = (*passes)[i].get(); + auto* pass = (*passes)[i].get(); TestPassMatchesExpectations(expected_passes[i], pass); } } @@ -487,7 +492,7 @@ VerifyQuadCoverSQS(&aggregated_frame); // Ensure no duplicate pass ids output. - std::set<RenderPassId> used_passes; + std::set<AggregatedRenderPassId> used_passes; for (const auto& pass : aggregated_frame.render_pass_list) EXPECT_TRUE(used_passes.insert(pass->id).second); @@ -1365,7 +1370,7 @@ EXPECT_EQ(1u, root_render_pass->quad_list.size()); auto* output_quad = root_render_pass->quad_list.back(); - EXPECT_EQ(DrawQuad::Material::kRenderPass, output_quad->material); + EXPECT_EQ(DrawQuad::Material::kAggregatedRenderPass, output_quad->material); // The RenderPassDrawQuad should have the same scale transform that was // applied to the SurfaceDrawQuad. @@ -1594,8 +1599,9 @@ std::vector<Quad> expected_quads = { Quad::SolidColorQuad(SK_ColorWHITE, gfx::Rect(5, 5)), - Quad::RenderPassQuad(aggregated_frame.render_pass_list[0]->id, - gfx::Transform(), false), + Quad::RenderPassQuad( + RenderPassId{uint64_t{aggregated_frame.render_pass_list[0]->id}}, + gfx::Transform(), false), Quad::SolidColorQuad(SK_ColorBLACK, gfx::Rect(5, 5))}; std::vector<Pass> expected_passes = {Pass(embedded_quads, SurfaceSize()), Pass(expected_quads, SurfaceSize())}; @@ -1857,7 +1863,7 @@ const auto& aggregated_pass_list = aggregated_frame.render_pass_list; ASSERT_EQ(5u, aggregated_pass_list.size()); - RenderPassId actual_pass_ids[] = { + AggregatedRenderPassId actual_pass_ids[] = { aggregated_pass_list[0]->id, aggregated_pass_list[1]->id, aggregated_pass_list[2]->id, aggregated_pass_list[3]->id, aggregated_pass_list[4]->id}; @@ -1894,10 +1900,11 @@ // This render pass pass quad will reference the first pass from the // embedded surface, which is the second pass in the aggregated frame. - ASSERT_EQ(DrawQuad::Material::kRenderPass, + ASSERT_EQ(DrawQuad::Material::kAggregatedRenderPass, third_pass_quad_list.ElementAt(1)->material); const auto* third_pass_render_pass_draw_quad = - RenderPassDrawQuad::MaterialCast(third_pass_quad_list.ElementAt(1)); + AggregatedRenderPassDrawQuad::MaterialCast( + third_pass_quad_list.ElementAt(1)); EXPECT_EQ(actual_pass_ids[1], third_pass_render_pass_draw_quad->render_pass_id); } @@ -1916,19 +1923,21 @@ // The next quad will be a render pass quad referencing the second pass from // the embedded surface, which is the third pass in the aggregated frame. - ASSERT_EQ(DrawQuad::Material::kRenderPass, + ASSERT_EQ(DrawQuad::Material::kAggregatedRenderPass, fourth_pass_quad_list.ElementAt(1)->material); const auto* fourth_pass_first_render_pass_draw_quad = - RenderPassDrawQuad::MaterialCast(fourth_pass_quad_list.ElementAt(1)); + AggregatedRenderPassDrawQuad::MaterialCast( + fourth_pass_quad_list.ElementAt(1)); EXPECT_EQ(actual_pass_ids[2], fourth_pass_first_render_pass_draw_quad->render_pass_id); // The last quad will be a render pass quad referencing the first pass from // the root surface, which is the first pass overall. - ASSERT_EQ(DrawQuad::Material::kRenderPass, + ASSERT_EQ(DrawQuad::Material::kAggregatedRenderPass, fourth_pass_quad_list.ElementAt(2)->material); const auto* fourth_pass_second_render_pass_draw_quad = - RenderPassDrawQuad::MaterialCast(fourth_pass_quad_list.ElementAt(2)); + AggregatedRenderPassDrawQuad::MaterialCast( + fourth_pass_quad_list.ElementAt(2)); EXPECT_EQ(actual_pass_ids[0], fourth_pass_second_render_pass_draw_quad->render_pass_id); } @@ -1944,10 +1953,11 @@ // The last quad in the last pass will reference the second pass from the // root surface, which after aggregating is the fourth pass in the overall // list. - ASSERT_EQ(DrawQuad::Material::kRenderPass, + ASSERT_EQ(DrawQuad::Material::kAggregatedRenderPass, fifth_pass_quad_list.ElementAt(1)->material); const auto* fifth_pass_render_pass_draw_quad = - RenderPassDrawQuad::MaterialCast(fifth_pass_quad_list.ElementAt(1)); + AggregatedRenderPassDrawQuad::MaterialCast( + fifth_pass_quad_list.ElementAt(1)); EXPECT_EQ(actual_pass_ids[3], fifth_pass_render_pass_draw_quad->render_pass_id); } @@ -2154,9 +2164,9 @@ const auto& aggregated_pass_list = aggregated_frame.render_pass_list; ASSERT_EQ(3u, aggregated_pass_list.size()); - RenderPassId actual_pass_ids[] = {aggregated_pass_list[0]->id, - aggregated_pass_list[1]->id, - aggregated_pass_list[2]->id}; + AggregatedRenderPassId actual_pass_ids[] = {aggregated_pass_list[0]->id, + aggregated_pass_list[1]->id, + aggregated_pass_list[2]->id}; // Make sure the aggregated frame's pass IDs are all unique. for (size_t i = 0; i < 3; ++i) { for (size_t j = 0; j < i; ++j) { @@ -2168,15 +2178,17 @@ // Make sure the render pass quads reference the remapped pass IDs. DrawQuad* render_pass_quads[] = {aggregated_pass_list[1]->quad_list.front(), aggregated_pass_list[2]->quad_list.front()}; - ASSERT_EQ(render_pass_quads[0]->material, DrawQuad::Material::kRenderPass); - EXPECT_EQ( - actual_pass_ids[0], - RenderPassDrawQuad::MaterialCast(render_pass_quads[0])->render_pass_id); + ASSERT_EQ(render_pass_quads[0]->material, + DrawQuad::Material::kAggregatedRenderPass); + EXPECT_EQ(actual_pass_ids[0], + AggregatedRenderPassDrawQuad::MaterialCast(render_pass_quads[0]) + ->render_pass_id); - ASSERT_EQ(render_pass_quads[1]->material, DrawQuad::Material::kRenderPass); - EXPECT_EQ( - actual_pass_ids[1], - RenderPassDrawQuad::MaterialCast(render_pass_quads[1])->render_pass_id); + ASSERT_EQ(render_pass_quads[1]->material, + DrawQuad::Material::kAggregatedRenderPass); + EXPECT_EQ(actual_pass_ids[1], + AggregatedRenderPassDrawQuad::MaterialCast(render_pass_quads[1]) + ->render_pass_id); } void AddSolidColorQuadWithBlendMode(const gfx::Size& size, @@ -3753,7 +3765,8 @@ EXPECT_EQ(gfx::Rect(SurfaceSize()), aggregated_pass_list.back()->damage_rect); const auto* quad_to_test = aggregated_pass_list.back()->quad_list.front(); - const auto* rp_quad = RenderPassDrawQuad::MaterialCast(quad_to_test); + const auto* rp_quad = + AggregatedRenderPassDrawQuad::MaterialCast(quad_to_test); // The |quad_to_test| (20,30 80x80) intersects with damage below, which is // union of surface quad damage (0,0 70x70) and root surface damage (0,0 // 100x100), so its |can_use_backdrop_filter_cache| is reset to false. @@ -3790,7 +3803,8 @@ EXPECT_EQ(gfx::Rect(), aggregated_pass_list.back()->damage_rect); const auto* quad_to_test = aggregated_pass_list.back()->quad_list.front(); - const auto* rp_quad = RenderPassDrawQuad::MaterialCast(quad_to_test); + const auto* rp_quad = + AggregatedRenderPassDrawQuad::MaterialCast(quad_to_test); // No damage under |quad_to_test| and its |can_use_backdrop_filter_cache| // retains its value. EXPECT_TRUE(rp_quad->can_use_backdrop_filter_cache); @@ -3823,7 +3837,8 @@ ASSERT_EQ(expected_num_passes_after_aggregation, aggregated_pass_list.size()); const auto* quad_to_test = aggregated_pass_list.back()->quad_list.front(); - const auto* rp_quad = RenderPassDrawQuad::MaterialCast(quad_to_test); + const auto* rp_quad = + AggregatedRenderPassDrawQuad::MaterialCast(quad_to_test); // The |quad_to_test| (20,30 80x80) doesn't intersect the damage from the // surface quad below (10,10 10x10) and the |can_use_backdrop_filter_cache| // retains its value of true. @@ -3857,7 +3872,8 @@ ASSERT_EQ(expected_num_passes_after_aggregation, aggregated_pass_list.size()); const auto* quad_to_test = aggregated_pass_list.back()->quad_list.front(); - const auto* rp_quad = RenderPassDrawQuad::MaterialCast(quad_to_test); + const auto* rp_quad = + AggregatedRenderPassDrawQuad::MaterialCast(quad_to_test); // The |quad_to_test| (20,30 80x80) intersects the damage from the // surface quad below (60,60 10x10) and the |can_use_backdrop_filter_cache| // resets to false. @@ -3997,7 +4013,8 @@ aggregated_pass_list.back()->damage_rect); const auto* quad_to_test = aggregated_pass_list[AllowMerge() ? 2 : 1]->quad_list.front(); - const auto* rp_quad = RenderPassDrawQuad::MaterialCast(quad_to_test); + const auto* rp_quad = + AggregatedRenderPassDrawQuad::MaterialCast(quad_to_test); // 1) Without merging, the |quad_to_test| (or more precisely, the // |output_rect| of the render pass referenced by the quad that's used for // damage intersection test) (0,0 60x60) has damage below from surface root @@ -4043,7 +4060,8 @@ EXPECT_EQ(gfx::Rect(), aggregated_pass_list.back()->damage_rect); const auto* quad_to_test = aggregated_pass_list[AllowMerge() ? 2 : 1]->quad_list.front(); - const auto* rp_quad = RenderPassDrawQuad::MaterialCast(quad_to_test); + const auto* rp_quad = + AggregatedRenderPassDrawQuad::MaterialCast(quad_to_test); // With or without merging, the |quad_to_test| (0,0 60x60) has no damage // from under it, so its |can_use_backdrop_filter_cache| remains unchanged. EXPECT_TRUE(rp_quad->can_use_backdrop_filter_cache); @@ -4082,7 +4100,8 @@ EXPECT_EQ(expected_damage_rect, aggregated_pass_list.back()->damage_rect); const auto* quad_to_test = aggregated_pass_list[AllowMerge() ? 2 : 1]->quad_list.front(); - const auto* rp_quad = RenderPassDrawQuad::MaterialCast(quad_to_test); + const auto* rp_quad = + AggregatedRenderPassDrawQuad::MaterialCast(quad_to_test); // 1) Without merging, the |quad_to_test| (0,0 60x60) doesn't have any // damage coming from under it and its |can_use_backdrop_filter_cache| flag // remains unchanged (true). @@ -4126,7 +4145,8 @@ EXPECT_EQ(expected_damage_rect, aggregated_pass_list.back()->damage_rect); const auto* quad_to_test = aggregated_pass_list[AllowMerge() ? 2 : 1]->quad_list.front(); - const auto* rp_quad = RenderPassDrawQuad::MaterialCast(quad_to_test); + const auto* rp_quad = + AggregatedRenderPassDrawQuad::MaterialCast(quad_to_test); // 1) Without merging, the |quad_to_test| (0,0 60x60) doesn't have any // damage from under it and its |can_use_backdrop_filter_cache| remains // unchanged (true). @@ -4261,7 +4281,8 @@ // The damage rect from under |quad_to_test| (0,0 100x100) intersects quad // render pass output rect (0,0 50x50). const auto* quad_to_test = aggregated_pass_list.back()->quad_list.front(); - const auto* rp_quad = RenderPassDrawQuad::MaterialCast(quad_to_test); + const auto* rp_quad = + AggregatedRenderPassDrawQuad::MaterialCast(quad_to_test); EXPECT_FALSE(rp_quad->can_use_backdrop_filter_cache); } @@ -4291,7 +4312,8 @@ // There is no damage from under |quad_to_test| so // |can_use_backdrop_filter_cache| remains true. const auto* quad_to_test = aggregated_pass_list.back()->quad_list.front(); - const auto* rp_quad = RenderPassDrawQuad::MaterialCast(quad_to_test); + const auto* rp_quad = + AggregatedRenderPassDrawQuad::MaterialCast(quad_to_test); EXPECT_TRUE(rp_quad->can_use_backdrop_filter_cache); } @@ -4333,7 +4355,8 @@ // The damage rect from under |quad_to_test| (1,1 10x10) intersects quad // render pass output rect (0,0 50x50). const auto* quad_to_test = aggregated_pass_list.back()->quad_list.front(); - const auto* rp_quad = RenderPassDrawQuad::MaterialCast(quad_to_test); + const auto* rp_quad = + AggregatedRenderPassDrawQuad::MaterialCast(quad_to_test); EXPECT_FALSE(rp_quad->can_use_backdrop_filter_cache); } @@ -4365,7 +4388,8 @@ // |can_use_backdrop_filter_cache| remains true. const auto* quad_to_test = aggregated_pass_list.back()->quad_list.front(); - const auto* rp_quad = RenderPassDrawQuad::MaterialCast(quad_to_test); + const auto* rp_quad = + AggregatedRenderPassDrawQuad::MaterialCast(quad_to_test); EXPECT_TRUE(rp_quad->can_use_backdrop_filter_cache); } } @@ -4474,7 +4498,8 @@ // (2,2 5x5). const auto* quad_to_test = aggregated_frame.render_pass_list.back()->quad_list.front(); - const auto* rp_quad = RenderPassDrawQuad::MaterialCast(quad_to_test); + const auto* rp_quad = + AggregatedRenderPassDrawQuad::MaterialCast(quad_to_test); EXPECT_FALSE(rp_quad->can_use_backdrop_filter_cache); } @@ -4502,7 +4527,8 @@ // |can_use_backdrop_filter_cache| flag of |quad_to_test| remains true. const auto* quad_to_test = aggregated_frame.render_pass_list.back()->quad_list.front(); - const auto* rp_quad = RenderPassDrawQuad::MaterialCast(quad_to_test); + const auto* rp_quad = + AggregatedRenderPassDrawQuad::MaterialCast(quad_to_test); EXPECT_TRUE(rp_quad->can_use_backdrop_filter_cache); } @@ -4547,7 +4573,8 @@ const auto* quad_to_test = aggregated_frame_2.render_pass_list.back()->quad_list.front(); - const auto* rp_quad = RenderPassDrawQuad::MaterialCast(quad_to_test); + const auto* rp_quad = + AggregatedRenderPassDrawQuad::MaterialCast(quad_to_test); EXPECT_TRUE(rp_quad->can_use_backdrop_filter_cache); } @@ -4596,7 +4623,8 @@ const auto* quad_to_test = aggregated_frame_2.render_pass_list.back()->quad_list.front(); - const auto* rp_quad = RenderPassDrawQuad::MaterialCast(quad_to_test); + const auto* rp_quad = + AggregatedRenderPassDrawQuad::MaterialCast(quad_to_test); EXPECT_FALSE(rp_quad->can_use_backdrop_filter_cache); } } @@ -7738,7 +7766,7 @@ // The base pass should contain a single RPDQ with a |rect| matching // |child_rect|. ASSERT_EQ(1u, aggregated_frame.render_pass_list[1]->quad_list.size()); - const RenderPassDrawQuad* rpdq = RenderPassDrawQuad::MaterialCast( + const auto* rpdq = AggregatedRenderPassDrawQuad::MaterialCast( aggregated_frame.render_pass_list[1]->quad_list.front()); EXPECT_EQ(child_rect, rpdq->rect);
diff --git a/components/viz/service/display_embedder/image_context_impl.cc b/components/viz/service/display_embedder/image_context_impl.cc index d3b8401..2aa3836 100644 --- a/components/viz/service/display_embedder/image_context_impl.cc +++ b/components/viz/service/display_embedder/image_context_impl.cc
@@ -29,7 +29,7 @@ ycbcr_info, color_space) {} -ImageContextImpl::ImageContextImpl(RenderPassId render_pass_id, +ImageContextImpl::ImageContextImpl(AggregatedRenderPassId render_pass_id, const gfx::Size& size, ResourceFormat resource_format, bool mipmap,
diff --git a/components/viz/service/display_embedder/image_context_impl.h b/components/viz/service/display_embedder/image_context_impl.h index 51e4a56..724eef3f 100644 --- a/components/viz/service/display_embedder/image_context_impl.h +++ b/components/viz/service/display_embedder/image_context_impl.h
@@ -11,7 +11,7 @@ #include "base/macros.h" #include "base/optional.h" -#include "components/viz/common/quads/render_pass.h" +#include "components/viz/common/quads/aggregated_render_pass.h" #include "components/viz/common/resources/resource_format.h" #include "components/viz/service/display/external_use_client.h" #include "gpu/command_buffer/common/mailbox_holder.h" @@ -52,7 +52,7 @@ // SkiaOutputSurfaceImplOnGpu::OffscreenSurface can be factored out. This // would make ImageContextImpl cleaner and handling of render passes less // confusing. - ImageContextImpl(RenderPassId render_pass_id, + ImageContextImpl(AggregatedRenderPassId render_pass_id, const gfx::Size& size, ResourceFormat resource_format, bool mipmap, @@ -61,7 +61,7 @@ void OnContextLost() final; - RenderPassId render_pass_id() const { return render_pass_id_; } + AggregatedRenderPassId render_pass_id() const { return render_pass_id_; } GrMipMapped mipmap() const { return mipmap_; } void set_promise_image_texture( @@ -100,7 +100,7 @@ bool BindOrCopyTextureIfNecessary(gpu::TextureBase* texture_base, gfx::Size* size); - const RenderPassId render_pass_id_; + const AggregatedRenderPassId render_pass_id_; const GrMipMapped mipmap_ = GrMipMapped::kNo; // Fallback in case we cannot produce a |representation_|.
diff --git a/components/viz/service/display_embedder/skia_output_surface_impl.cc b/components/viz/service/display_embedder/skia_output_surface_impl.cc index 4afabfa..bb4eb79 100644 --- a/components/viz/service/display_embedder/skia_output_surface_impl.cc +++ b/components/viz/service/display_embedder/skia_output_surface_impl.cc
@@ -78,7 +78,7 @@ SkiaOutputSurfaceImpl::ScopedPaint::ScopedPaint( SkSurfaceCharacterization characterization, - RenderPassId render_pass_id) + AggregatedRenderPassId render_pass_id) : render_pass_id_(render_pass_id) { recorder_storage_.emplace(characterization); recorder_ = &recorder_storage_.value(); @@ -117,7 +117,7 @@ root_recorder_.reset(); if (!render_pass_image_cache_.empty()) { - std::vector<RenderPassId> render_pass_ids; + std::vector<AggregatedRenderPassId> render_pass_ids; render_pass_ids.reserve(render_pass_ids.size()); for (auto& entry : render_pass_image_cache_) render_pass_ids.push_back(entry.first); @@ -482,7 +482,7 @@ } SkCanvas* SkiaOutputSurfaceImpl::BeginPaintRenderPass( - const RenderPassId& id, + const AggregatedRenderPassId& id, const gfx::Size& surface_size, ResourceFormat format, bool mipmap, @@ -570,7 +570,7 @@ } sk_sp<SkImage> SkiaOutputSurfaceImpl::MakePromiseSkImageFromRenderPass( - const RenderPassId& id, + const AggregatedRenderPassId& id, const gfx::Size& size, ResourceFormat format, bool mipmap, @@ -605,7 +605,7 @@ } void SkiaOutputSurfaceImpl::RemoveRenderPassResource( - std::vector<RenderPassId> ids) { + std::vector<AggregatedRenderPassId> ids) { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); DCHECK(!ids.empty()); @@ -632,7 +632,7 @@ } void SkiaOutputSurfaceImpl::CopyOutput( - RenderPassId id, + AggregatedRenderPassId id, const copy_output::RenderPassGeometry& geometry, const gfx::ColorSpace& color_space, std::unique_ptr<CopyOutputRequest> request) {
diff --git a/components/viz/service/display_embedder/skia_output_surface_impl.h b/components/viz/service/display_embedder/skia_output_surface_impl.h index 919a954..f2abcd6 100644 --- a/components/viz/service/display_embedder/skia_output_surface_impl.h +++ b/components/viz/service/display_embedder/skia_output_surface_impl.h
@@ -105,7 +105,7 @@ OverlayProcessorInterface::OutputSurfaceOverlayPlane output_surface_plane) override; - SkCanvas* BeginPaintRenderPass(const RenderPassId& id, + SkCanvas* BeginPaintRenderPass(const AggregatedRenderPassId& id, const gfx::Size& surface_size, ResourceFormat format, bool mipmap, @@ -113,17 +113,18 @@ gpu::SyncToken SubmitPaint(base::OnceClosure on_finished) override; void MakePromiseSkImage(ImageContext* image_context) override; sk_sp<SkImage> MakePromiseSkImageFromRenderPass( - const RenderPassId& id, + const AggregatedRenderPassId& id, const gfx::Size& size, ResourceFormat format, bool mipmap, sk_sp<SkColorSpace> color_space) override; - void RemoveRenderPassResource(std::vector<RenderPassId> ids) override; + void RemoveRenderPassResource( + std::vector<AggregatedRenderPassId> ids) override; void ScheduleOverlays(OverlayList overlays, std::vector<gpu::SyncToken> sync_tokens) override; - void CopyOutput(RenderPassId id, + void CopyOutput(AggregatedRenderPassId id, const copy_output::RenderPassGeometry& geometry, const gfx::ColorSpace& color_space, std::unique_ptr<CopyOutputRequest> request) override; @@ -209,11 +210,11 @@ public: explicit ScopedPaint(SkDeferredDisplayListRecorder* root_recorder); ScopedPaint(SkSurfaceCharacterization characterization, - RenderPassId render_pass_id); + AggregatedRenderPassId render_pass_id); ~ScopedPaint(); SkDeferredDisplayListRecorder* recorder() { return recorder_; } - RenderPassId render_pass_id() { return render_pass_id_; } + AggregatedRenderPassId render_pass_id() { return render_pass_id_; } private: // This is recorder being used for current paint @@ -221,7 +222,7 @@ // If we need new recorder for this Paint (i.e it's not root render pass), // it's stored here base::Optional<SkDeferredDisplayListRecorder> recorder_storage_; - const RenderPassId render_pass_id_; + const AggregatedRenderPassId render_pass_id_; }; // This holds current paint info @@ -239,7 +240,7 @@ base::Optional<SkNWayCanvas> nway_canvas_; // The cache for promise image created from render passes. - base::flat_map<RenderPassId, std::unique_ptr<ImageContextImpl>> + base::flat_map<AggregatedRenderPassId, std::unique_ptr<ImageContextImpl>> render_pass_image_cache_; // Sync tokens for resources which are used for the current frame or render
diff --git a/components/viz/service/display_embedder/skia_output_surface_impl_on_gpu.cc b/components/viz/service/display_embedder/skia_output_surface_impl_on_gpu.cc index 42f7b6e..8513061 100644 --- a/components/viz/service/display_embedder/skia_output_surface_impl_on_gpu.cc +++ b/components/viz/service/display_embedder/skia_output_surface_impl_on_gpu.cc
@@ -585,7 +585,7 @@ void SkiaOutputSurfaceImplOnGpu::FinishPaintRenderPass( base::TimeTicks post_task_timestamp, - RenderPassId id, + AggregatedRenderPassId id, sk_sp<SkDeferredDisplayList> ddl, std::vector<ImageContextImpl*> image_contexts, std::vector<gpu::SyncToken> sync_tokens, @@ -652,13 +652,13 @@ } void SkiaOutputSurfaceImplOnGpu::RemoveRenderPassResource( - std::vector<RenderPassId> ids, + std::vector<AggregatedRenderPassId> ids, std::vector<std::unique_ptr<ImageContextImpl>> image_contexts) { TRACE_EVENT0("viz", "SkiaOutputSurfaceImplOnGpu::RemoveRenderPassResource"); DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); DCHECK(!ids.empty()); - for (RenderPassId id : ids) { + for (AggregatedRenderPassId id : ids) { // It's possible that |offscreen_surfaces_| won't contain an entry for the // render pass if draw failed early. auto it = offscreen_surfaces_.find(id); @@ -681,7 +681,7 @@ } bool SkiaOutputSurfaceImplOnGpu::CopyOutput( - RenderPassId id, + AggregatedRenderPassId id, copy_output::RenderPassGeometry geometry, const gfx::ColorSpace& color_space, std::unique_ptr<CopyOutputRequest> request,
diff --git a/components/viz/service/display_embedder/skia_output_surface_impl_on_gpu.h b/components/viz/service/display_embedder/skia_output_surface_impl_on_gpu.h index 69df345..0037545 100644 --- a/components/viz/service/display_embedder/skia_output_surface_impl_on_gpu.h +++ b/components/viz/service/display_embedder/skia_output_surface_impl_on_gpu.h
@@ -140,7 +140,7 @@ void EnsureBackbuffer() { output_device_->EnsureBackbuffer(); } void DiscardBackbuffer() { output_device_->DiscardBackbuffer(); } void FinishPaintRenderPass(base::TimeTicks post_task_timestamp, - RenderPassId id, + AggregatedRenderPassId id, sk_sp<SkDeferredDisplayList> ddl, std::vector<ImageContextImpl*> image_contexts, std::vector<gpu::SyncToken> sync_tokens, @@ -148,9 +148,9 @@ // Deletes resources for RenderPasses in |ids|. Also takes ownership of // |images_contexts| and destroys them on GPU thread. void RemoveRenderPassResource( - std::vector<RenderPassId> ids, + std::vector<AggregatedRenderPassId> ids, std::vector<std::unique_ptr<ImageContextImpl>> image_contexts); - bool CopyOutput(RenderPassId id, + bool CopyOutput(AggregatedRenderPassId id, copy_output::RenderPassGeometry geometry, const gfx::ColorSpace& color_space, std::unique_ptr<CopyOutputRequest> request, @@ -339,7 +339,7 @@ base::Optional<OverlayProcessorInterface::OutputSurfaceOverlayPlane> output_surface_plane_; - base::flat_map<RenderPassId, OffscreenSurface> offscreen_surfaces_; + base::flat_map<AggregatedRenderPassId, OffscreenSurface> offscreen_surfaces_; // Micro-optimization to get to issuing GPU SwapBuffers as soon as possible. std::vector<sk_sp<SkDeferredDisplayList>> destroy_after_swap_;
diff --git a/components/viz/service/display_embedder/skia_output_surface_impl_unittest.cc b/components/viz/service/display_embedder/skia_output_surface_impl_unittest.cc index e5ab3d7..3b09f6f 100644 --- a/components/viz/service/display_embedder/skia_output_surface_impl_unittest.cc +++ b/components/viz/service/display_embedder/skia_output_surface_impl_unittest.cc
@@ -156,7 +156,7 @@ geometry.sampling_bounds = output_rect; geometry.readback_offset = gfx::Vector2d(0, 0); - output_surface_->CopyOutput(RenderPassId{0}, geometry, color_space, + output_surface_->CopyOutput(AggregatedRenderPassId{0}, geometry, color_space, std::move(request)); output_surface_->SwapBuffersSkipped(); BlockMainThread();
diff --git a/components/viz/service/frame_sinks/root_compositor_frame_sink_impl.cc b/components/viz/service/frame_sinks/root_compositor_frame_sink_impl.cc index a9e05db..e08fb708 100644 --- a/components/viz/service/frame_sinks/root_compositor_frame_sink_impl.cc +++ b/components/viz/service/frame_sinks/root_compositor_frame_sink_impl.cc
@@ -427,7 +427,7 @@ void RootCompositorFrameSinkImpl::DisplayWillDrawAndSwap( bool will_draw_and_swap, - RenderPassList* render_passes) { + AggregatedRenderPassList* render_passes) { DCHECK(support_->GetHitTestAggregator()); support_->GetHitTestAggregator()->Aggregate(display_->CurrentSurfaceId(), render_passes);
diff --git a/components/viz/service/frame_sinks/root_compositor_frame_sink_impl.h b/components/viz/service/frame_sinks/root_compositor_frame_sink_impl.h index a2e3994..4bcc0c2 100644 --- a/components/viz/service/frame_sinks/root_compositor_frame_sink_impl.h +++ b/components/viz/service/frame_sinks/root_compositor_frame_sink_impl.h
@@ -118,7 +118,7 @@ // DisplayClient: void DisplayOutputSurfaceLost() override; void DisplayWillDrawAndSwap(bool will_draw_and_swap, - RenderPassList* render_passes) override; + AggregatedRenderPassList* render_passes) override; void DisplayDidDrawAndSwap() override; void DisplayDidReceiveCALayerParams( const gfx::CALayerParams& ca_layer_params) override;
diff --git a/components/viz/service/hit_test/hit_test_aggregator.cc b/components/viz/service/hit_test/hit_test_aggregator.cc index bbf7ebf..0a42bc1 100644 --- a/components/viz/service/hit_test/hit_test_aggregator.cc +++ b/components/viz/service/hit_test/hit_test_aggregator.cc
@@ -33,7 +33,7 @@ HitTestAggregator::~HitTestAggregator() = default; void HitTestAggregator::Aggregate(const SurfaceId& display_surface_id, - RenderPassList* render_passes) { + AggregatedRenderPassList* render_passes) { DCHECK(referenced_child_regions_.empty()); // The index will only have changed when new hit-test data has been submitted. @@ -63,7 +63,8 @@ } } -void HitTestAggregator::InsertHitTestDebugQuads(RenderPassList* render_passes) { +void HitTestAggregator::InsertHitTestDebugQuads( + AggregatedRenderPassList* render_passes) { const base::flat_set<FrameSinkId>* hit_test_async_queried_debug_regions = hit_test_manager_->GetHitTestAsyncQueriedDebugRegions( root_frame_sink_id_);
diff --git a/components/viz/service/hit_test/hit_test_aggregator.h b/components/viz/service/hit_test/hit_test_aggregator.h index 5b1d390..2c760c20 100644 --- a/components/viz/service/hit_test/hit_test_aggregator.h +++ b/components/viz/service/hit_test/hit_test_aggregator.h
@@ -5,8 +5,10 @@ #ifndef COMPONENTS_VIZ_SERVICE_HIT_TEST_HIT_TEST_AGGREGATOR_H_ #define COMPONENTS_VIZ_SERVICE_HIT_TEST_HIT_TEST_AGGREGATOR_H_ +#include <vector> + #include "components/viz/common/hit_test/aggregated_hit_test_region.h" -#include "components/viz/common/quads/render_pass.h" +#include "components/viz/common/quads/aggregated_render_pass.h" #include "components/viz/common/surfaces/surface_id.h" #include "components/viz/service/hit_test/hit_test_manager.h" #include "components/viz/service/surfaces/surface_observer.h" @@ -39,7 +41,7 @@ // are aggregated into |hit_test_data_|. If |render_passes| are given and // the correct flags are set, hit-test debug quads will be inserted. void Aggregate(const SurfaceId& display_surface_id, - RenderPassList* render_passes = nullptr); + AggregatedRenderPassList* render_passes = nullptr); private: friend class TestHitTestAggregator; @@ -71,7 +73,7 @@ uint64_t active_frame_index); // Inserts debug quads based on hit-test data. - void InsertHitTestDebugQuads(RenderPassList* render_passes); + void InsertHitTestDebugQuads(AggregatedRenderPassList* render_passes); const HitTestManager* const hit_test_manager_;
diff --git a/components/viz/test/compositor_frame_helpers.cc b/components/viz/test/compositor_frame_helpers.cc index e4891145..85d0ba9 100644 --- a/components/viz/test/compositor_frame_helpers.cc +++ b/components/viz/test/compositor_frame_helpers.cc
@@ -139,10 +139,15 @@ return CompositorFrameBuilder().AddDefaultRenderPass().Build(); } -AggregatedFrame MakeDefaultAggregatedFrame() { +AggregatedFrame MakeDefaultAggregatedFrame(size_t num_render_passes) { + static AggregatedRenderPassId::Generator id_generator; AggregatedFrame frame; - frame.render_pass_list = - std::move(MakeDefaultCompositorFrame().render_pass_list); + for (size_t i = 0; i < num_render_passes; ++i) { + frame.render_pass_list.push_back(std::make_unique<AggregatedRenderPass>()); + frame.render_pass_list.back()->SetNew(id_generator.GenerateNextId(), + kDefaultOutputRect, + kDefaultDamageRect, gfx::Transform()); + } return frame; }
diff --git a/components/viz/test/compositor_frame_helpers.h b/components/viz/test/compositor_frame_helpers.h index 7a5c171..88073fa7 100644 --- a/components/viz/test/compositor_frame_helpers.h +++ b/components/viz/test/compositor_frame_helpers.h
@@ -76,7 +76,7 @@ CompositorFrame MakeDefaultCompositorFrame(); // Makes an aggregated frame out of the default compositor frame. -AggregatedFrame MakeDefaultAggregatedFrame(); +AggregatedFrame MakeDefaultAggregatedFrame(size_t num_render_passes = 1); // Creates a CompositorFrame that will be valid once its render_pass_list is // initialized.
diff --git a/components/viz/test/fake_skia_output_surface.cc b/components/viz/test/fake_skia_output_surface.cc index b7980a6..c069446f 100644 --- a/components/viz/test/fake_skia_output_surface.cc +++ b/components/viz/test/fake_skia_output_surface.cc
@@ -66,7 +66,7 @@ const gfx::ColorSpace& color_space, gfx::BufferFormat format, bool use_stencil) { - auto& sk_surface = sk_surfaces_[RenderPassId{0}]; + auto& sk_surface = sk_surfaces_[AggregatedRenderPassId{0}]; SkColorType color_type = kRGBA_8888_SkColorType; SkImageInfo image_info = SkImageInfo::Make(size.width(), size.height(), color_type, @@ -134,9 +134,9 @@ SkCanvas* FakeSkiaOutputSurface::BeginPaintCurrentFrame() { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); - auto& sk_surface = sk_surfaces_[RenderPassId{0}]; + auto& sk_surface = sk_surfaces_[AggregatedRenderPassId{0}]; DCHECK(sk_surface); - DCHECK_EQ(current_render_pass_id_, RenderPassId{0u}); + DCHECK_EQ(current_render_pass_id_, AggregatedRenderPassId{0u}); return sk_surface->getCanvas(); } @@ -185,14 +185,14 @@ } SkCanvas* FakeSkiaOutputSurface::BeginPaintRenderPass( - const RenderPassId& id, + const AggregatedRenderPassId& id, const gfx::Size& surface_size, ResourceFormat format, bool mipmap, sk_sp<SkColorSpace> color_space) { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); // Make sure there is no unsubmitted PaintFrame or PaintRenderPass. - DCHECK_EQ(current_render_pass_id_, RenderPassId{0u}); + DCHECK_EQ(current_render_pass_id_, AggregatedRenderPassId{0u}); auto& sk_surface = sk_surfaces_[id]; if (!sk_surface) { @@ -211,7 +211,7 @@ base::OnceClosure on_finished) { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); sk_surfaces_[current_render_pass_id_]->flushAndSubmit(); - current_render_pass_id_ = RenderPassId{0}; + current_render_pass_id_ = AggregatedRenderPassId{0}; if (on_finished) std::move(on_finished).Run(); @@ -222,7 +222,7 @@ } sk_sp<SkImage> FakeSkiaOutputSurface::MakePromiseSkImageFromRenderPass( - const RenderPassId& id, + const AggregatedRenderPassId& id, const gfx::Size& size, ResourceFormat format, bool mipmap, @@ -235,7 +235,7 @@ } void FakeSkiaOutputSurface::RemoveRenderPassResource( - std::vector<RenderPassId> ids) { + std::vector<AggregatedRenderPassId> ids) { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); DCHECK(!ids.empty()); @@ -247,7 +247,7 @@ } void FakeSkiaOutputSurface::CopyOutput( - RenderPassId id, + AggregatedRenderPassId id, const copy_output::RenderPassGeometry& geometry, const gfx::ColorSpace& color_space, std::unique_ptr<CopyOutputRequest> request) {
diff --git a/components/viz/test/fake_skia_output_surface.h b/components/viz/test/fake_skia_output_surface.h index b0cc0686..19e7106e 100644 --- a/components/viz/test/fake_skia_output_surface.h +++ b/components/viz/test/fake_skia_output_surface.h
@@ -15,6 +15,7 @@ #include "base/memory/weak_ptr.h" #include "base/threading/thread_checker.h" #include "build/build_config.h" +#include "components/viz/common/quads/aggregated_render_pass.h" #include "components/viz/service/display/skia_output_surface.h" #include "components/viz/test/test_context_provider.h" #include "gpu/command_buffer/common/sync_token.h" @@ -72,7 +73,7 @@ sk_sp<SkColorSpace> image_color_space, bool has_alpha) override; void SwapBuffersSkipped() override {} - SkCanvas* BeginPaintRenderPass(const RenderPassId& id, + SkCanvas* BeginPaintRenderPass(const AggregatedRenderPassId& id, const gfx::Size& surface_size, ResourceFormat format, bool mipmap, @@ -80,18 +81,19 @@ gpu::SyncToken SubmitPaint(base::OnceClosure on_finished) override; void MakePromiseSkImage(ImageContext* image_context) override; sk_sp<SkImage> MakePromiseSkImageFromRenderPass( - const RenderPassId& id, + const AggregatedRenderPassId& id, const gfx::Size& size, ResourceFormat format, bool mipmap, sk_sp<SkColorSpace> color_space) override; - void RemoveRenderPassResource(std::vector<RenderPassId> ids) override; + void RemoveRenderPassResource( + std::vector<AggregatedRenderPassId> ids) override; void ScheduleOverlays(OverlayList overlays, std::vector<gpu::SyncToken> sync_tokens) override {} #if defined(OS_WIN) void SetEnableDCLayers(bool enable) override {} #endif - void CopyOutput(RenderPassId id, + void CopyOutput(AggregatedRenderPassId id, const copy_output::RenderPassGeometry& geometry, const gfx::ColorSpace& color_space, std::unique_ptr<CopyOutputRequest> request) override; @@ -137,10 +139,10 @@ std::unique_ptr<TextureDeleter> texture_deleter_; // The current render pass id set by BeginPaintRenderPass. - RenderPassId current_render_pass_id_; + AggregatedRenderPassId current_render_pass_id_; // SkSurfaces for render passes, sk_surfaces_[0] is the root surface. - base::flat_map<RenderPassId, sk_sp<SkSurface>> sk_surfaces_; + base::flat_map<AggregatedRenderPassId, sk_sp<SkSurface>> sk_surfaces_; THREAD_CHECKER(thread_checker_);
diff --git a/content/browser/webui/shared_resources_data_source.cc b/content/browser/webui/shared_resources_data_source.cc index b9dc7cc..38585978 100644 --- a/content/browser/webui/shared_resources_data_source.cc +++ b/content/browser/webui/shared_resources_data_source.cc
@@ -121,13 +121,13 @@ {IDR_MOJO_TEXT_DIRECTION_MOJOM_LITE_JS, "mojo/mojo/public/mojom/base/text_direction.mojom-lite.js"}, #if defined(OS_WIN) || defined(OS_MAC) || defined(OS_LINUX) || \ - defined(OS_ANDROID) + defined(OS_CHROMEOS) || defined(OS_ANDROID) {IDR_MOJO_TIME_MOJOM_HTML, "mojo/mojo/public/mojom/base/time.mojom.html"}, {IDR_MOJO_TIME_MOJOM_LITE_JS, "mojo/mojo/public/mojom/base/time.mojom-lite.js"}, #endif // defined(OS_WIN) || defined(OS_MAC) || defined(OS_LINUX) || - // defined(OS_ANDROID) + // defined(OS_CHROMEOS) || defined(OS_ANDROID) }; }
diff --git a/content/child/runtime_features.cc b/content/child/runtime_features.cc index a635276..2363bb6 100644 --- a/content/child/runtime_features.cc +++ b/content/child/runtime_features.cc
@@ -618,15 +618,6 @@ WebRuntimeFeatures::EnableBackForwardCache( content::IsBackForwardCacheEnabled()); - // Gate the ReducedReferrerGranularity runtime feature depending on whether - // content is configured to force a no-referrer-when-downgrade default policy. - // TODO(crbug.com/1016541): After M82, remove when the corresponding - // enterprise policy has been deleted. - WebRuntimeFeatures::EnableReducedReferrerGranularity( - base::FeatureList::IsEnabled( - blink::features::kReducedReferrerGranularity) && - !blink::ReferrerUtils::ShouldForceLegacyDefaultReferrerPolicy()); - if (base::FeatureList::IsEnabled( blink::features::kAppCacheRequireOriginTrial)) { // The kAppCacheRequireOriginTrial is a flag that controls whether or not
diff --git a/content/renderer/android/synchronous_layer_tree_frame_sink_impl.h b/content/renderer/android/synchronous_layer_tree_frame_sink_impl.h index cae9af0e..0bfb6988 100644 --- a/content/renderer/android/synchronous_layer_tree_frame_sink_impl.h +++ b/content/renderer/android/synchronous_layer_tree_frame_sink_impl.h
@@ -164,8 +164,9 @@ class StubDisplayClient : public viz::DisplayClient { void DisplayOutputSurfaceLost() override {} - void DisplayWillDrawAndSwap(bool will_draw_and_swap, - viz::RenderPassList* render_passes) override {} + void DisplayWillDrawAndSwap( + bool will_draw_and_swap, + viz::AggregatedRenderPassList* render_passes) override {} void DisplayDidDrawAndSwap() override {} void DisplayDidReceiveCALayerParams( const gfx::CALayerParams& ca_layer_params) override {}
diff --git a/content/test/data/accessibility/html/modal-dialog-opened-expected-android.txt b/content/test/data/accessibility/html/modal-dialog-opened-expected-android.txt index 417cfb82..bd53d4cd 100644 --- a/content/test/data/accessibility/html/modal-dialog-opened-expected-android.txt +++ b/content/test/data/accessibility/html/modal-dialog-opened-expected-android.txt
@@ -3,4 +3,3 @@ ++++android.widget.TextView name='The dialog subtree should be the only text content in the accessibility tree. ' ++++android.view.View role_description='link' clickable focusable focused link name='Link inside the dialog.' ++++++android.widget.TextView name='Link inside the dialog.' -++android.view.View clickable invisible \ No newline at end of file
diff --git a/content/test/data/accessibility/html/modal-dialog-opened-expected-auralinux.txt b/content/test/data/accessibility/html/modal-dialog-opened-expected-auralinux.txt index c2a8610..a290c1c 100644 --- a/content/test/data/accessibility/html/modal-dialog-opened-expected-auralinux.txt +++ b/content/test/data/accessibility/html/modal-dialog-opened-expected-auralinux.txt
@@ -3,4 +3,3 @@ ++++[static] name='The dialog subtree should be the only text content in the accessibility tree. ' ++++[link] name='Link inside the dialog.' ++++++[static] name='Link inside the dialog.' -++[menu] \ No newline at end of file
diff --git a/content/test/data/accessibility/html/modal-dialog-opened-expected-blink.txt b/content/test/data/accessibility/html/modal-dialog-opened-expected-blink.txt index 7aa8061..a12e986 100644 --- a/content/test/data/accessibility/html/modal-dialog-opened-expected-blink.txt +++ b/content/test/data/accessibility/html/modal-dialog-opened-expected-blink.txt
@@ -9,7 +9,5 @@ ++++++++++++staticText name='Link inside the dialog.' ++++++++++++++inlineTextBox name='Link inside the dialog.' ++++++++popUpButton collapsed ignored invisible value='This should be pruned out of the tree.' -++++++++++menuListPopup invisible -++++++++++++menuListOption ignored name='This should be pruned out of the tree.' selected=true ++++++button ignored invisible name='No file chosen, Choose File' value='No file chosen' -++++++dialog ignored invisible \ No newline at end of file +++++++dialog ignored invisible
diff --git a/content/test/data/accessibility/html/modal-dialog-opened-expected-uia-win.txt b/content/test/data/accessibility/html/modal-dialog-opened-expected-uia-win.txt index 8ef172d7..f4955efd 100644 --- a/content/test/data/accessibility/html/modal-dialog-opened-expected-uia-win.txt +++ b/content/test/data/accessibility/html/modal-dialog-opened-expected-uia-win.txt
@@ -3,4 +3,3 @@ ++++Text Name='The dialog subtree should be the only text content in the accessibility tree. ' ++++Hyperlink Name='Link inside the dialog.' ++++++Text Name='Link inside the dialog.' IsControlElement=false -++List IsControlElement=false Selection.CanSelectMultiple=false Selection.IsSelectionRequired=false \ No newline at end of file
diff --git a/content/test/data/accessibility/html/modal-dialog-opened-expected-win.txt b/content/test/data/accessibility/html/modal-dialog-opened-expected-win.txt index 5d9fd4d..c134aa6 100644 --- a/content/test/data/accessibility/html/modal-dialog-opened-expected-win.txt +++ b/content/test/data/accessibility/html/modal-dialog-opened-expected-win.txt
@@ -3,4 +3,3 @@ ++++ROLE_SYSTEM_STATICTEXT name='The dialog subtree should be the only text content in the accessibility tree. ' ++++ROLE_SYSTEM_LINK name='Link inside the dialog.' FOCUSABLE ++++++ROLE_SYSTEM_STATICTEXT name='Link inside the dialog.' -++ROLE_SYSTEM_LIST INVISIBLE \ No newline at end of file
diff --git a/content/test/data/accessibility/html/modal-dialog-stack-expected-android.txt b/content/test/data/accessibility/html/modal-dialog-stack-expected-android.txt index d273ebb..8b85f273 100644 --- a/content/test/data/accessibility/html/modal-dialog-stack-expected-android.txt +++ b/content/test/data/accessibility/html/modal-dialog-stack-expected-android.txt
@@ -1,5 +1,4 @@ android.webkit.WebView focusable focused scrollable -++android.view.View clickable invisible ++android.app.Dialog role_description='dialog' ++++android.widget.TextView name='This is the now active dialog. Of course it should be in the tree. ' -++++android.widget.Button role_description='button' clickable focusable name='This is in the active dialog and should be in the tree.' \ No newline at end of file +++++android.widget.Button role_description='button' clickable focusable name='This is in the active dialog and should be in the tree.'
diff --git a/content/test/data/accessibility/html/modal-dialog-stack-expected-auralinux.txt b/content/test/data/accessibility/html/modal-dialog-stack-expected-auralinux.txt index b7dc207..64654d8 100644 --- a/content/test/data/accessibility/html/modal-dialog-stack-expected-auralinux.txt +++ b/content/test/data/accessibility/html/modal-dialog-stack-expected-auralinux.txt
@@ -1,5 +1,4 @@ [document web] -++[menu] ++[dialog] modal ++++[static] name='This is the now active dialog. Of course it should be in the tree. ' ++++[push button] name='This is in the active dialog and should be in the tree.'
diff --git a/content/test/data/accessibility/html/modal-dialog-stack-expected-blink.txt b/content/test/data/accessibility/html/modal-dialog-stack-expected-blink.txt index 2082830..3ddd1f2e 100644 --- a/content/test/data/accessibility/html/modal-dialog-stack-expected-blink.txt +++ b/content/test/data/accessibility/html/modal-dialog-stack-expected-blink.txt
@@ -4,8 +4,6 @@ ++++++section ignored invisible ++++++++dialog ignored invisible name=' This was the top dialog and should not be in the tree. ' ++++++++popUpButton collapsed ignored invisible value='This should be pruned out of the tree.' -++++++++++menuListPopup invisible -++++++++++++menuListOption ignored name='This should be pruned out of the tree.' selected=true ++++++button ignored invisible name='This button should not be in the tree.' ++++++dialog ignored invisible name=' This was the middle dialog and should not be in the tree. ' ++++++dialog @@ -14,4 +12,4 @@ ++++++++button name='This is in the active dialog and should be in the tree.' ++++++++++staticText name='This is in the active dialog and should be in the tree.' ++++++++++++inlineTextBox name='This is in the active dialog and should be in the tree.' -++++++dialog ignored invisible \ No newline at end of file +++++++dialog ignored invisible
diff --git a/content/test/data/accessibility/html/modal-dialog-stack-expected-uia-win.txt b/content/test/data/accessibility/html/modal-dialog-stack-expected-uia-win.txt index 64e0b93..8ac0f8d 100644 --- a/content/test/data/accessibility/html/modal-dialog-stack-expected-uia-win.txt +++ b/content/test/data/accessibility/html/modal-dialog-stack-expected-uia-win.txt
@@ -1,5 +1,4 @@ Document -++List IsControlElement=false Selection.CanSelectMultiple=false Selection.IsSelectionRequired=false ++Pane IsControlElement=false Window.IsModal=true ++++Text Name='This is the now active dialog. Of course it should be in the tree. ' -++++Button Name='This is in the active dialog and should be in the tree.' \ No newline at end of file +++++Button Name='This is in the active dialog and should be in the tree.'
diff --git a/content/test/data/accessibility/html/modal-dialog-stack-expected-win.txt b/content/test/data/accessibility/html/modal-dialog-stack-expected-win.txt index fdedce904..6371f34 100644 --- a/content/test/data/accessibility/html/modal-dialog-stack-expected-win.txt +++ b/content/test/data/accessibility/html/modal-dialog-stack-expected-win.txt
@@ -1,5 +1,4 @@ ROLE_SYSTEM_DOCUMENT READONLY FOCUSABLE -++ROLE_SYSTEM_LIST INVISIBLE ++ROLE_SYSTEM_DIALOG IA2_STATE_MODAL ++++ROLE_SYSTEM_STATICTEXT name='This is the now active dialog. Of course it should be in the tree. ' -++++ROLE_SYSTEM_PUSHBUTTON name='This is in the active dialog and should be in the tree.' FOCUSABLE \ No newline at end of file +++++ROLE_SYSTEM_PUSHBUTTON name='This is in the active dialog and should be in the tree.' FOCUSABLE
diff --git a/gin/BUILD.gn b/gin/BUILD.gn index d0489cdf..9ec6eb1b 100644 --- a/gin/BUILD.gn +++ b/gin/BUILD.gn
@@ -2,7 +2,6 @@ # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. -import("//build/config/allocator.gni") import("//testing/test.gni") import("//tools/v8_context_snapshot/v8_context_snapshot.gni") import("//v8/gni/v8.gni")
diff --git a/gin/v8_platform_unittest.cc b/gin/v8_platform_unittest.cc index d2ea2b7..96c57a8 100644 --- a/gin/v8_platform_unittest.cc +++ b/gin/v8_platform_unittest.cc
@@ -74,7 +74,12 @@ explicit Task(std::atomic_size_t* num_tasks_to_run) : num_tasks_to_run(num_tasks_to_run) {} void Run(v8::JobDelegate* delegate) override { --(*num_tasks_to_run); } + + // TODO(1114823): Cleanup the old version once migration is complete. size_t GetMaxConcurrency() const override { return *num_tasks_to_run; } + size_t GetMaxConcurrency(size_t /* worker_count*/) const override { + return GetMaxConcurrency(); + } std::atomic_size_t* num_tasks_to_run; };
diff --git a/gpu/command_buffer/service/gl_context_mock.h b/gpu/command_buffer/service/gl_context_mock.h index 6e2b138..b41cb50 100644 --- a/gpu/command_buffer/service/gl_context_mock.h +++ b/gpu/command_buffer/service/gl_context_mock.h
@@ -14,7 +14,7 @@ public: GLContextMock(); - MOCK_METHOD1(MakeCurrent, bool(gl::GLSurface* surface)); + MOCK_METHOD1(MakeCurrentImpl, bool(gl::GLSurface* surface)); protected: ~GLContextMock() override;
diff --git a/gpu/command_buffer/service/gl_context_virtual.cc b/gpu/command_buffer/service/gl_context_virtual.cc index d9347c0..afceab2 100644 --- a/gpu/command_buffer/service/gl_context_virtual.cc +++ b/gpu/command_buffer/service/gl_context_virtual.cc
@@ -34,7 +34,7 @@ shared_context_ = nullptr; } -bool GLContextVirtual::MakeCurrent(gl::GLSurface* surface) { +bool GLContextVirtual::MakeCurrentImpl(gl::GLSurface* surface) { if (delegate_.get()) return shared_context_->MakeVirtuallyCurrent(this, surface); @@ -86,11 +86,10 @@ return shared_context_->SetSafeToForceGpuSwitch(); } -unsigned int GLContextVirtual::CheckStickyGraphicsResetStatus() { +unsigned int GLContextVirtual::CheckStickyGraphicsResetStatusImpl() { unsigned int reset_status = shared_context_->CheckStickyGraphicsResetStatus(); if (reset_status == GL_NO_ERROR) return GL_NO_ERROR; - shared_context_->MarkVirtualContextLost(); // Don't pretend we know which one of the virtual contexts was responsible. return GL_UNKNOWN_CONTEXT_RESET_ARB; }
diff --git a/gpu/command_buffer/service/gl_context_virtual.h b/gpu/command_buffer/service/gl_context_virtual.h index 3efbba2c..c1341a5fd 100644 --- a/gpu/command_buffer/service/gl_context_virtual.h +++ b/gpu/command_buffer/service/gl_context_virtual.h
@@ -33,7 +33,7 @@ // Implement GLContext. bool Initialize(gl::GLSurface* compatible_surface, const gl::GLContextAttribs& attribs) override; - bool MakeCurrent(gl::GLSurface* surface) override; + bool MakeCurrentImpl(gl::GLSurface* surface) override; void ReleaseCurrent(gl::GLSurface* surface) override; bool IsCurrent(gl::GLSurface* surface) override; void* GetHandle() override; @@ -42,7 +42,7 @@ std::string GetGLRenderer() override; const gfx::ExtensionSet& GetExtensions() override; void SetSafeToForceGpuSwitch() override; - unsigned int CheckStickyGraphicsResetStatus() override; + unsigned int CheckStickyGraphicsResetStatusImpl() override; void SetUnbindFboOnMakeCurrent() override; gl::YUVToRGBConverter* GetYUVToRGBConverter( const gfx::ColorSpace& color_space) override;
diff --git a/gpu/command_buffer/service/gles2_cmd_decoder_unittest.cc b/gpu/command_buffer/service/gles2_cmd_decoder_unittest.cc index f6643bc..4f8d623 100644 --- a/gpu/command_buffer/service/gles2_cmd_decoder_unittest.cc +++ b/gpu/command_buffer/service/gles2_cmd_decoder_unittest.cc
@@ -396,14 +396,15 @@ context_->ReleaseCurrent(surface_.get()); abstract_texture.reset(); // Make the context current again, |context_| overrides it with a mock. - context_->GLContextStub::MakeCurrent(surface_.get()); + context_->GLContextStub::MakeCurrentImpl(surface_.get()); // Having textures to delete should signal idle work. EXPECT_EQ(GetDecoder()->HasMoreIdleWork(), true); EXPECT_CALL(*gl_, DeleteTextures(1, _)).Times(1).RetiresOnSaturation(); // Allow the context to be made current. - EXPECT_CALL(*context_, MakeCurrent(surface_.get())).WillOnce(Return(true)); + EXPECT_CALL(*context_, MakeCurrentImpl(surface_.get())) + .WillOnce(Return(true)); GetDecoder()->MakeCurrent(); }
diff --git a/gpu/command_buffer/service/gles2_cmd_decoder_unittest_base.cc b/gpu/command_buffer/service/gles2_cmd_decoder_unittest_base.cc index 8b471b3b..7047ac4 100644 --- a/gpu/command_buffer/service/gles2_cmd_decoder_unittest_base.cc +++ b/gpu/command_buffer/service/gles2_cmd_decoder_unittest_base.cc
@@ -230,7 +230,7 @@ context_->SetExtensionsString(normalized_init.extensions.c_str()); context_->SetGLVersionString(normalized_init.gl_version.c_str()); - context_->GLContextStub::MakeCurrent(surface_.get()); + context_->GLContextStub::MakeCurrentImpl(surface_.get()); TestHelper::SetupContextGroupInitExpectations( gl_.get(), @@ -525,7 +525,8 @@ return result; } - EXPECT_CALL(*context_, MakeCurrent(surface_.get())).WillOnce(Return(true)); + EXPECT_CALL(*context_, MakeCurrentImpl(surface_.get())) + .WillOnce(Return(true)); if (context_->HasRobustness()) { EXPECT_CALL(*gl_, GetGraphicsResetStatusARB()) .WillOnce(Return(GL_NO_ERROR));
diff --git a/gpu/command_buffer/service/gles2_cmd_decoder_unittest_context_lost.cc b/gpu/command_buffer/service/gles2_cmd_decoder_unittest_context_lost.cc index 236f92d7a..a01a404 100644 --- a/gpu/command_buffer/service/gles2_cmd_decoder_unittest_context_lost.cc +++ b/gpu/command_buffer/service/gles2_cmd_decoder_unittest_context_lost.cc
@@ -132,7 +132,8 @@ TEST_P(GLES2DecoderLostContextTest, LostFromMakeCurrent) { Init(false); // without robustness - EXPECT_CALL(*context_, MakeCurrent(surface_.get())).WillOnce(Return(false)); + EXPECT_CALL(*context_, MakeCurrentImpl(surface_.get())) + .WillOnce(Return(false)); // Expect the group to be lost. EXPECT_CALL(*mock_decoder_, MarkContextLost(error::kUnknown)).Times(1); decoder_->MakeCurrent(); @@ -149,7 +150,8 @@ // If we can't make the context current, we cannot query the robustness // extension. EXPECT_CALL(*gl_, GetGraphicsResetStatusARB()).Times(0); - EXPECT_CALL(*context_, MakeCurrent(surface_.get())).WillOnce(Return(false)); + EXPECT_CALL(*context_, MakeCurrentImpl(surface_.get())) + .WillOnce(Return(false)); // Expect the group to be lost. EXPECT_CALL(*mock_decoder_, MarkContextLost(error::kUnknown)).Times(1); decoder_->MakeCurrent(); @@ -190,7 +192,8 @@ GenHelper<cmds::DeleteTexturesImmediate>(kClientTextureId); // Force context lost for MakeCurrent(). - EXPECT_CALL(*context_, MakeCurrent(surface_.get())).WillOnce(Return(false)); + EXPECT_CALL(*context_, MakeCurrentImpl(surface_.get())) + .WillOnce(Return(false)); // Expect the group to be lost. EXPECT_CALL(*mock_decoder_, MarkContextLost(error::kUnknown)).Times(1); @@ -245,7 +248,8 @@ EXPECT_CALL(*gl_, DeleteSync(kGlSync)).Times(0).RetiresOnSaturation(); // Force context lost for MakeCurrent(). - EXPECT_CALL(*context_, MakeCurrent(surface_.get())).WillOnce(Return(false)); + EXPECT_CALL(*context_, MakeCurrentImpl(surface_.get())) + .WillOnce(Return(false)); // Expect the group to be lost. EXPECT_CALL(*mock_decoder_, MarkContextLost(error::kUnknown)).Times(1); @@ -259,7 +263,8 @@ TEST_P(GLES2DecoderLostContextTest, LostFromResetAfterMakeCurrent) { Init(true); // with robustness InSequence seq; - EXPECT_CALL(*context_, MakeCurrent(surface_.get())).WillOnce(Return(true)); + EXPECT_CALL(*context_, MakeCurrentImpl(surface_.get())) + .WillOnce(Return(true)); EXPECT_CALL(*gl_, GetGraphicsResetStatusARB()) .WillOnce(Return(GL_GUILTY_CONTEXT_RESET_KHR)); // Expect the group to be lost.
diff --git a/gpu/command_buffer/service/raster_decoder_unittest_base.cc b/gpu/command_buffer/service/raster_decoder_unittest_base.cc index 7a8c918..7aa6752 100644 --- a/gpu/command_buffer/service/raster_decoder_unittest_base.cc +++ b/gpu/command_buffer/service/raster_decoder_unittest_base.cc
@@ -161,7 +161,7 @@ context_->SetExtensionsString(all_extensions.c_str()); context_->SetGLVersionString(init.gl_version.c_str()); - context_->GLContextStub::MakeCurrent(surface_.get()); + context_->GLContextStub::MakeCurrentImpl(surface_.get()); GpuFeatureInfo gpu_feature_info; feature_info_ = base::MakeRefCounted<gles2::FeatureInfo>(init.workarounds, @@ -218,7 +218,8 @@ true, gles2::DisallowedFeatures(), attribs), gpu::ContextResult::kSuccess); - EXPECT_CALL(*context_, MakeCurrent(surface_.get())).WillOnce(Return(true)); + EXPECT_CALL(*context_, MakeCurrentImpl(surface_.get())) + .WillOnce(Return(true)); EXPECT_CALL(*gl_, GetError()) .WillOnce(Return(GL_NO_ERROR)) .RetiresOnSaturation(); @@ -265,7 +266,7 @@ for (auto& image : shared_images_) image->OnContextLost(); shared_images_.clear(); - context_->GLContextStub::MakeCurrent(surface_.get()); + context_->GLContextStub::MakeCurrentImpl(surface_.get()); shared_context_state_.reset(); ::gl::MockGLInterface::SetGLInterface(nullptr); gl_.reset();
diff --git a/gpu/command_buffer/service/raster_decoder_unittest_context_lost.cc b/gpu/command_buffer/service/raster_decoder_unittest_context_lost.cc index d82e5e8..91148ea 100644 --- a/gpu/command_buffer/service/raster_decoder_unittest_context_lost.cc +++ b/gpu/command_buffer/service/raster_decoder_unittest_context_lost.cc
@@ -136,7 +136,8 @@ TEST_P(RasterDecoderLostContextTest, LostFromMakeCurrent) { Init(/*has_robustness=*/false); - EXPECT_CALL(*context_, MakeCurrent(surface_.get())).WillOnce(Return(false)); + EXPECT_CALL(*context_, MakeCurrentImpl(surface_.get())) + .WillOnce(Return(false)); EXPECT_FALSE(decoder_->WasContextLost()); decoder_->MakeCurrent(); EXPECT_TRUE(decoder_->WasContextLost()); @@ -149,7 +150,8 @@ TEST_P(RasterDecoderLostContextTest, LostFromDriverOOM) { Init(/*has_robustness=*/false); - EXPECT_CALL(*context_, MakeCurrent(surface_.get())).WillOnce(Return(true)); + EXPECT_CALL(*context_, MakeCurrentImpl(surface_.get())) + .WillOnce(Return(true)); EXPECT_CALL(*gl_, GetError()).WillOnce(Return(GL_OUT_OF_MEMORY)); EXPECT_FALSE(decoder_->WasContextLost()); decoder_->MakeCurrent(); @@ -166,7 +168,8 @@ // If we can't make the context current, we cannot query the robustness // extension. EXPECT_CALL(*gl_, GetGraphicsResetStatusARB()).Times(0); - EXPECT_CALL(*context_, MakeCurrent(surface_.get())).WillOnce(Return(false)); + EXPECT_CALL(*context_, MakeCurrentImpl(surface_.get())) + .WillOnce(Return(false)); decoder_->MakeCurrent(); EXPECT_TRUE(decoder_->WasContextLost()); EXPECT_FALSE(decoder_->WasContextLostByRobustnessExtension()); @@ -216,7 +219,8 @@ EXPECT_CALL(*gl_, DeleteSync(kGlSync)).Times(0).RetiresOnSaturation(); // Force context lost for MakeCurrent(). - EXPECT_CALL(*context_, MakeCurrent(surface_.get())).WillOnce(Return(false)); + EXPECT_CALL(*context_, MakeCurrentImpl(surface_.get())) + .WillOnce(Return(false)); decoder_->MakeCurrent(); EXPECT_TRUE(decoder_->WasContextLost()); @@ -228,7 +232,8 @@ TEST_P(RasterDecoderLostContextTest, LostFromResetAfterMakeCurrent) { Init(/*has_robustness=*/true); InSequence seq; - EXPECT_CALL(*context_, MakeCurrent(surface_.get())).WillOnce(Return(true)); + EXPECT_CALL(*context_, MakeCurrentImpl(surface_.get())) + .WillOnce(Return(true)); EXPECT_CALL(*gl_, GetError()).WillOnce(Return(GL_CONTEXT_LOST_KHR)); EXPECT_CALL(*gl_, GetGraphicsResetStatusARB()) .WillOnce(Return(GL_GUILTY_CONTEXT_RESET_KHR));
diff --git a/ios/chrome/browser/ui/authentication/signed_in_accounts_view_controller.mm b/ios/chrome/browser/ui/authentication/signed_in_accounts_view_controller.mm index c5842c1..d890a940 100644 --- a/ios/chrome/browser/ui/authentication/signed_in_accounts_view_controller.mm +++ b/ios/chrome/browser/ui/authentication/signed_in_accounts_view_controller.mm
@@ -119,6 +119,12 @@ ChromeIdentity* identity = ios::GetChromeBrowserProvider() ->GetChromeIdentityService() ->GetIdentityWithGaiaID(account.gaia); + + // If the account with a refresh token is invalidated during this operation + // then |identity| will be nil. Do not process it in this case. + if (!identity) { + continue; + } CollectionViewItem* item = [self accountItem:identity]; [model addItem:item toSectionWithIdentifier:SectionIdentifierAccounts]; [mutableIdentityMap setObject:item forKey:identity.gaiaID];
diff --git a/ios/chrome/browser/ui/authentication/signin/signin_coordinator_egtest.mm b/ios/chrome/browser/ui/authentication/signin/signin_coordinator_egtest.mm index 857431f..de00f62 100644 --- a/ios/chrome/browser/ui/authentication/signin/signin_coordinator_egtest.mm +++ b/ios/chrome/browser/ui/authentication/signin/signin_coordinator_egtest.mm
@@ -589,4 +589,26 @@ performAction:grey_tap()]; } +// Simulates a potential race condition in which the account is invalidated +// after the user taps the Settings button to navigate to the identity +// choosing UI. Depending on the timing, the account removal may occur after +// the UI has retrieved the list of valid accounts. The test ensures that in +// this case no account is presented to the user. +- (void)testAccountInvalidatedDuringSignin { + FakeChromeIdentity* fakeIdentity = [SigninEarlGrey fakeIdentity1]; + [SigninEarlGrey addFakeIdentity:fakeIdentity]; + + [ChromeEarlGreyUI openSettingsMenu]; + [ChromeEarlGreyUI tapSettingsMenuButton:SecondarySignInButton()]; + + // Invalidate account after menu generation. If the underlying code does not + // handle the race condition of removing an identity while showing menu is in + // progress this test will likely be flaky. + [SigninEarlGrey forgetFakeIdentity:fakeIdentity]; + // Check that the identity has been removed. + [[EarlGrey selectElementWithMatcher:identityChooserButtonMatcherWithEmail( + fakeIdentity.userEmail)] + assertWithMatcher:grey_notVisible()]; +} + @end
diff --git a/ios/chrome/browser/ui/content_suggestions/content_suggestions_header_view_controller.mm b/ios/chrome/browser/ui/content_suggestions/content_suggestions_header_view_controller.mm index 319c2994..059b0fb 100644 --- a/ios/chrome/browser/ui/content_suggestions/content_suggestions_header_view_controller.mm +++ b/ios/chrome/browser/ui/content_suggestions/content_suggestions_header_view_controller.mm
@@ -706,6 +706,7 @@ #pragma mark - UserAccountImageUpdateDelegate - (void)updateAccountImage:(UIImage*)image { + self.identityDiscButton.hidden = !image; [self.identityDiscButton setImage:image forState:UIControlStateNormal]; self.identityDiscButton.imageView.layer.cornerRadius = image.size.width / 2; self.identityDiscButton.imageView.layer.masksToBounds = YES;
diff --git a/ios/chrome/browser/ui/content_suggestions/ntp_home_mediator.mm b/ios/chrome/browser/ui/content_suggestions/ntp_home_mediator.mm index e0beb4fb..29002aae 100644 --- a/ios/chrome/browser/ui/content_suggestions/ntp_home_mediator.mm +++ b/ios/chrome/browser/ui/content_suggestions/ntp_home_mediator.mm
@@ -681,13 +681,14 @@ identityService->GetAvatarForIdentity(identity, nil); } } else { - // User is not signed in, show default avatar. - image = [self defaultAvatar]; + // User is not signed in, don't show any avatar. + image = nil; } // TODO(crbug.com/965962): Use ResizedAvatarCache when it accepts the // specification of different image sizes. CGFloat dimension = ntp_home::kIdentityAvatarDimension; - if (image.size.width != dimension || image.size.height != dimension) { + if (image && + (image.size.width != dimension || image.size.height != dimension)) { image = ResizeImage(image, CGSizeMake(dimension, dimension), ProjectionMode::kAspectFit); }
diff --git a/media/gpu/vaapi/vaapi_video_encode_accelerator.cc b/media/gpu/vaapi/vaapi_video_encode_accelerator.cc index 06ad02b..67e172d 100644 --- a/media/gpu/vaapi/vaapi_video_encode_accelerator.cc +++ b/media/gpu/vaapi/vaapi_video_encode_accelerator.cc
@@ -103,7 +103,7 @@ bool keyframe, base::OnceClosure execute_cb, scoped_refptr<VASurface> input_surface, - scoped_refptr<VASurface> reconstructed_surface, + scoped_refptr<CodecPicture> picture, VABufferID coded_buffer_id); ~VaapiEncodeJob() override = default; @@ -113,17 +113,13 @@ const scoped_refptr<VASurface> input_surface() const { return input_surface_; } - const scoped_refptr<VASurface> reconstructed_surface() const { - return reconstructed_surface_; - } + const scoped_refptr<CodecPicture> picture() const { return picture_; } private: // Input surface for video frame data or scaled data. const scoped_refptr<VASurface> input_surface_; - // Surface for the reconstructed picture, used for reference - // for subsequent frames. - const scoped_refptr<VASurface> reconstructed_surface_; + const scoped_refptr<CodecPicture> picture_; // Buffer that will contain the output bitstream data for this frame. VABufferID coded_buffer_id_; @@ -259,6 +255,11 @@ DCHECK_CALLED_ON_VALID_SEQUENCE(encoder_sequence_checker_); } +CodecPicture* VaapiVideoEncodeAccelerator::GetPictureFromJobForTesting( + VaapiEncodeJob* job) { + return job->picture().get(); +} + bool VaapiVideoEncodeAccelerator::Initialize(const Config& config, Client* client) { DCHECK_CALLED_ON_VALID_SEQUENCE(child_sequence_checker_); @@ -355,10 +356,10 @@ DCHECK_EQ(state_, kUninitialized); VLOGF(2); - VideoCodec codec = VideoCodecProfileToVideoCodec(config.output_profile); + output_codec_ = VideoCodecProfileToVideoCodec(config.output_profile); AcceleratedVideoEncoder::Config ave_config{}; DCHECK_EQ(IsConfiguredForTesting(), !!encoder_); - switch (codec) { + switch (output_codec_) { case kCodecH264: if (!IsConfiguredForTesting()) { encoder_ = std::make_unique<H264Encoder>( @@ -384,7 +385,7 @@ kConstantQuantizationParameter; break; default: - NOTREACHED() << "Unsupported codec type " << GetCodecName(codec); + NOTREACHED() << "Unsupported codec type " << GetCodecName(output_codec_); return; } @@ -769,11 +770,26 @@ kVaSurfaceFormat, base::BindOnce(va_surface_release_cb_)); available_va_surface_ids_.pop_back(); + scoped_refptr<CodecPicture> picture; + switch (output_codec_) { + case kCodecH264: + picture = new VaapiH264Picture(std::move(reconstructed_surface)); + break; + case kCodecVP8: + picture = new VaapiVP8Picture(std::move(reconstructed_surface)); + break; + case kCodecVP9: + picture = new VaapiVP9Picture(std::move(reconstructed_surface)); + break; + default: + return nullptr; + } + auto job = std::make_unique<VaapiEncodeJob>( frame, force_keyframe, base::BindOnce(&VaapiVideoEncodeAccelerator::ExecuteEncode, encoder_weak_this_, input_surface->id()), - input_surface, std::move(reconstructed_surface), coded_buffer_id); + input_surface, std::move(picture), coded_buffer_id); if (!native_input_mode_) { job->AddSetupCallback(base::BindOnce( @@ -1000,14 +1016,14 @@ bool keyframe, base::OnceClosure execute_cb, scoped_refptr<VASurface> input_surface, - scoped_refptr<VASurface> reconstructed_surface, + scoped_refptr<CodecPicture> picture, VABufferID coded_buffer_id) : EncodeJob(input_frame, keyframe, std::move(execute_cb)), input_surface_(input_surface), - reconstructed_surface_(reconstructed_surface), + picture_(std::move(picture)), coded_buffer_id_(coded_buffer_id) { DCHECK(input_surface_); - DCHECK(reconstructed_surface_); + DCHECK(picture_); DCHECK_NE(coded_buffer_id_, VA_INVALID_ID); } @@ -1200,8 +1216,8 @@ scoped_refptr<H264Picture> VaapiVideoEncodeAccelerator::H264Accelerator::GetPicture( AcceleratedVideoEncoder::EncodeJob* job) { - return base::MakeRefCounted<VaapiH264Picture>( - job->AsVaapiEncodeJob()->reconstructed_surface()); + return base::WrapRefCounted( + reinterpret_cast<H264Picture*>(job->AsVaapiEncodeJob()->picture().get())); } bool VaapiVideoEncodeAccelerator::H264Accelerator::SubmitPackedHeaders( @@ -1242,8 +1258,8 @@ scoped_refptr<VP8Picture> VaapiVideoEncodeAccelerator::VP8Accelerator::GetPicture( AcceleratedVideoEncoder::EncodeJob* job) { - return base::MakeRefCounted<VaapiVP8Picture>( - job->AsVaapiEncodeJob()->reconstructed_surface()); + return base::WrapRefCounted( + reinterpret_cast<VP8Picture*>(job->AsVaapiEncodeJob()->picture().get())); } bool VaapiVideoEncodeAccelerator::VP8Accelerator::SubmitFrameParameters( @@ -1417,8 +1433,8 @@ scoped_refptr<VP9Picture> VaapiVideoEncodeAccelerator::VP9Accelerator::GetPicture( AcceleratedVideoEncoder::EncodeJob* job) { - return base::MakeRefCounted<VaapiVP9Picture>( - job->AsVaapiEncodeJob()->reconstructed_surface()); + return base::WrapRefCounted( + reinterpret_cast<VP9Picture*>(job->AsVaapiEncodeJob()->picture().get())); } bool VaapiVideoEncodeAccelerator::VP9Accelerator::SubmitFrameParameters(
diff --git a/media/gpu/vaapi/vaapi_video_encode_accelerator.h b/media/gpu/vaapi/vaapi_video_encode_accelerator.h index ec0f1ca..abeaec1 100644 --- a/media/gpu/vaapi/vaapi_video_encode_accelerator.h +++ b/media/gpu/vaapi/vaapi_video_encode_accelerator.h
@@ -158,6 +158,8 @@ return !supported_profiles_for_testing_.empty(); } + static CodecPicture* GetPictureFromJobForTesting(VaapiEncodeJob* job); + // The unchanged values are filled upon the construction. The varied values // (e.g. ScalingSettings) are filled properly during encoding. VideoEncoderInfo encoder_info_; @@ -173,6 +175,9 @@ // is false. gfx::Size expected_input_coded_size_; + // The codec of the stream to be produced. Set during initialization. + VideoCodec output_codec_; + // The visible rect to be encoded. gfx::Rect visible_rect_;
diff --git a/media/gpu/vaapi/vaapi_video_encode_accelerator_unittest.cc b/media/gpu/vaapi/vaapi_video_encode_accelerator_unittest.cc index 896a725..96f1e33 100644 --- a/media/gpu/vaapi/vaapi_video_encode_accelerator_unittest.cc +++ b/media/gpu/vaapi/vaapi_video_encode_accelerator_unittest.cc
@@ -11,6 +11,7 @@ #include "base/run_loop.h" #include "base/test/gmock_callback_support.h" #include "base/test/task_environment.h" +#include "media/gpu/vp9_picture.h" #include "media/video/video_encode_accelerator.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" @@ -42,9 +43,13 @@ arg.bitrate_control == bitrate_control; } -MATCHER_P2(MatchesBitstreamBufferMetadata, payload_size_bytes, key_frame, "") { +MATCHER_P3(MatchesBitstreamBufferMetadata, + payload_size_bytes, + key_frame, + has_vp9_metadata, + "") { return arg.payload_size_bytes == payload_size_bytes && - arg.key_frame == key_frame; + arg.key_frame == key_frame && arg.vp9.has_value() == has_vp9_metadata; } class MockVideoEncodeAcceleratorClient : public VideoEncodeAccelerator::Client { @@ -93,6 +98,7 @@ MOCK_CONST_METHOD0(GetCodedSize, gfx::Size()); MOCK_CONST_METHOD0(GetBitstreamBufferSize, size_t()); MOCK_CONST_METHOD0(GetMaxNumOfRefFrames, size_t()); + MOCK_METHOD2(GetMetadata, BitstreamBufferMetadata(EncodeJob*, size_t)); MOCK_METHOD1(PrepareEncodeJob, bool(EncodeJob*)); MOCK_METHOD1(BitrateControlUpdate, void(uint64_t)); bool UpdateRates(const VideoBitrateAllocation&, uint32_t) override { @@ -186,7 +192,7 @@ run_loop.Run(); } - void EncodeSequenceForVP9() { + void EncodeSequenceForVP9(bool use_temporal_layer_encoding) { base::RunLoop run_loop; base::Closure quit_closure = run_loop.QuitClosure(); ::testing::InSequence s; @@ -203,7 +209,16 @@ EXPECT_CALL(*mock_encoder_, PrepareEncodeJob(_)) .WillOnce(WithArgs<0>( [encoder = encoder_.get(), kCodedBufferId, + use_temporal_layer_encoding, kInputSurfaceId](AcceleratedVideoEncoder::EncodeJob* job) { + if (use_temporal_layer_encoding) { + // Set Vp9Metadata on temporal layer encoding. + CodecPicture* picture = + VaapiVideoEncodeAccelerator::GetPictureFromJobForTesting( + job->AsVaapiEncodeJob()); + reinterpret_cast<VP9Picture*>(picture)->metadata_for_encoding = + Vp9Metadata(); + } job->AddPostExecuteCallback(base::BindOnce( &VaapiVideoEncodeAccelerator::NotifyEncodedChunkSize, base::Unretained( @@ -235,11 +250,24 @@ })); EXPECT_CALL(*mock_vaapi_wrapper_, DestroyVABuffer(kCodedBufferId)) .WillOnce(Return()); - + EXPECT_CALL(*mock_encoder_, GetMetadata(_, kEncodedChunkSize)) + .WillOnce(WithArgs<0, 1>( + [](AcceleratedVideoEncoder::EncodeJob* job, size_t payload_size) { + // Same implementation in VP9Encoder. + BitstreamBufferMetadata metadata( + payload_size, job->IsKeyframeRequested(), job->timestamp()); + CodecPicture* picture = + VaapiVideoEncodeAccelerator::GetPictureFromJobForTesting( + job->AsVaapiEncodeJob()); + metadata.vp9 = + reinterpret_cast<VP9Picture*>(picture)->metadata_for_encoding; + return metadata; + })); constexpr int32_t kBitstreamId = 12; EXPECT_CALL(client_, BitstreamBufferReady(kBitstreamId, MatchesBitstreamBufferMetadata( - kEncodedChunkSize, false))) + kEncodedChunkSize, false, + use_temporal_layer_encoding))) .WillOnce(RunClosure(quit_closure)); auto region = base::UnsafeSharedMemoryRegion::Create(output_buffer_size_); @@ -314,7 +342,7 @@ SetDefaultMocksBehavior(config); InitializeSequenceForVP9(config); - EncodeSequenceForVP9(); + EncodeSequenceForVP9(spatial_layer.num_of_temporal_layers > 1u); } INSTANTIATE_TEST_SUITE_P(,
diff --git a/net/base/io_buffer.cc b/net/base/io_buffer.cc index 0334008..a226610 100644 --- a/net/base/io_buffer.cc +++ b/net/base/io_buffer.cc
@@ -24,11 +24,6 @@ IOBuffer::IOBuffer() : data_(nullptr) {} -IOBuffer::IOBuffer(int buffer_size) { - AssertValidBufferSize(buffer_size); - data_ = new char[buffer_size]; -} - IOBuffer::IOBuffer(size_t buffer_size) { AssertValidBufferSize(buffer_size); data_ = new char[buffer_size];
diff --git a/net/base/io_buffer.h b/net/base/io_buffer.h index c27a724..77239650 100644 --- a/net/base/io_buffer.h +++ b/net/base/io_buffer.h
@@ -77,8 +77,6 @@ public: IOBuffer(); - // TODO(eroman): Deprecated. Use the size_t flavor instead. crbug.com/488553 - explicit IOBuffer(int buffer_size); explicit IOBuffer(size_t buffer_size); char* data() const { return data_; }
diff --git a/pdf/BUILD.gn b/pdf/BUILD.gn index b25ca19..09fc6f7 100644 --- a/pdf/BUILD.gn +++ b/pdf/BUILD.gn
@@ -194,6 +194,8 @@ "ppapi_migration/image.h", "ppapi_migration/input_event_conversions.cc", "ppapi_migration/input_event_conversions.h", + "ppapi_migration/url_loader.cc", + "ppapi_migration/url_loader.h", "ppapi_migration/value_conversions.cc", "ppapi_migration/value_conversions.h", ] @@ -247,6 +249,7 @@ deps = [ ":internal", + ":ppapi_migration", "//base", "//cc/paint", "//ppapi/cpp:objects", # TODO(crbug.com/1114263): PDFEngine::Client only. @@ -273,6 +276,7 @@ deps = [ ":internal", + ":ppapi_migration", "//base", "//ppapi/cpp:objects", "//testing/gtest",
diff --git a/pdf/out_of_process_instance.cc b/pdf/out_of_process_instance.cc index c0fc186..26eba1f 100644 --- a/pdf/out_of_process_instance.cc +++ b/pdf/out_of_process_instance.cc
@@ -14,9 +14,11 @@ #include <utility> #include "base/auto_reset.h" +#include "base/bind.h" #include "base/callback.h" #include "base/feature_list.h" #include "base/logging.h" +#include "base/memory/scoped_refptr.h" #include "base/memory/weak_ptr.h" #include "base/metrics/histogram_functions.h" #include "base/notreached.h" @@ -38,11 +40,11 @@ #include "pdf/ppapi_migration/geometry_conversions.h" #include "pdf/ppapi_migration/graphics.h" #include "pdf/ppapi_migration/input_event_conversions.h" +#include "pdf/ppapi_migration/url_loader.h" #include "pdf/ppapi_migration/value_conversions.h" #include "ppapi/c/dev/ppb_cursor_control_dev.h" #include "ppapi/c/pp_errors.h" #include "ppapi/c/private/ppb_pdf.h" -#include "ppapi/c/trusted/ppb_url_loader_trusted.h" #include "ppapi/cpp/core.h" #include "ppapi/cpp/dev/memory_dev.h" #include "ppapi/cpp/dev/text_input_dev.h" @@ -1446,13 +1448,9 @@ request.SetMethod("POST"); request.AppendDataToBody(reinterpret_cast<const char*>(data), length); - form_loader_ = CreateURLLoaderInternal(); - pp::CompletionCallback callback = - PPCompletionCallbackFromResultCallback(base::BindOnce( - &OutOfProcessInstance::FormDidOpen, weak_factory_.GetWeakPtr())); - int rv = form_loader_.Open(request, callback); - if (rv != PP_OK_COMPLETIONPENDING) - callback.Run(rv); + form_loader_ = CreateUrlLoaderInternal(); + form_loader_->Open(request, base::BindOnce(&OutOfProcessInstance::FormDidOpen, + weak_factory_.GetWeakPtr())); } void OutOfProcessInstance::FormDidOpen(int32_t result) { @@ -1462,7 +1460,7 @@ } } -pp::URLLoader OutOfProcessInstance::CreateURLLoader() { +scoped_refptr<UrlLoader> OutOfProcessInstance::CreateUrlLoader() { if (full_) { if (!did_call_start_loading_) { did_call_start_loading_ = true; @@ -1476,7 +1474,7 @@ this, PP_CONTENT_RESTRICTION_SAVE | PP_CONTENT_RESTRICTION_PRINT); } - return CreateURLLoaderInternal(); + return CreateUrlLoaderInternal(); } std::vector<PDFEngine::Client::SearchStringResult> @@ -2076,27 +2074,19 @@ request.SetMethod("GET"); request.SetFollowRedirects(false); - pp::URLLoader* loader = - is_print_preview ? &embed_preview_loader_ : &embed_loader_; - *loader = CreateURLLoaderInternal(); - pp::CompletionCallback callback = PPCompletionCallbackFromResultCallback( + scoped_refptr<UrlLoader>& loader = + is_print_preview ? embed_preview_loader_ : embed_loader_; + loader = CreateUrlLoaderInternal(); + loader->Open( + request, base::BindOnce(is_print_preview ? &OutOfProcessInstance::DidOpenPreview : &OutOfProcessInstance::DidOpen, weak_factory_.GetWeakPtr())); - int rv = loader->Open(request, callback); - if (rv != PP_OK_COMPLETIONPENDING) - callback.Run(rv); } -pp::URLLoader OutOfProcessInstance::CreateURLLoaderInternal() { - pp::URLLoader loader(this); - - const PPB_URLLoaderTrusted* trusted_interface = - reinterpret_cast<const PPB_URLLoaderTrusted*>( - pp::Module::Get()->GetBrowserInterface( - PPB_URLLOADERTRUSTED_INTERFACE)); - if (trusted_interface) - trusted_interface->GrantUniversalAccess(loader.pp_resource()); +scoped_refptr<UrlLoader> OutOfProcessInstance::CreateUrlLoaderInternal() { + auto loader = base::MakeRefCounted<UrlLoader>(this); + loader->GrantUniversalAccess(); return loader; }
diff --git a/pdf/out_of_process_instance.h b/pdf/out_of_process_instance.h index 411960cf..47e9afc 100644 --- a/pdf/out_of_process_instance.h +++ b/pdf/out_of_process_instance.h
@@ -16,6 +16,7 @@ #include "base/callback.h" #include "base/containers/queue.h" +#include "base/memory/scoped_refptr.h" #include "base/memory/weak_ptr.h" #include "pdf/paint_manager.h" #include "pdf/pdf_view_plugin_base.h" @@ -25,7 +26,6 @@ #include "ppapi/cpp/image_data.h" #include "ppapi/cpp/instance.h" #include "ppapi/cpp/private/find_private.h" -#include "ppapi/cpp/url_loader.h" #include "third_party/skia/include/core/SkBitmap.h" namespace gfx { @@ -44,6 +44,7 @@ class Graphics; class PaintReadyRect; class PDFiumEngine; +class UrlLoader; class OutOfProcessInstance : public PdfViewPluginBase, public pp::Instance, @@ -144,7 +145,7 @@ void SubmitForm(const std::string& url, const void* data, int length) override; - pp::URLLoader CreateURLLoader() override; + scoped_refptr<UrlLoader> CreateUrlLoader() override; std::vector<SearchStringResult> SearchString(const base::char16* string, const base::char16* term, bool case_sensitive) override; @@ -215,7 +216,7 @@ // Creates a URL loader and allows it to access all urls, i.e. not just the // frame's origin. - pp::URLLoader CreateURLLoaderInternal(); + scoped_refptr<UrlLoader> CreateUrlLoaderInternal(); bool CanSaveEdits() const; void SaveToFile(const std::string& token); @@ -331,8 +332,8 @@ // Used when the plugin is embedded in a page and we have to create the loader // ourself. - pp::URLLoader embed_loader_; - pp::URLLoader embed_preview_loader_; + scoped_refptr<UrlLoader> embed_loader_; + scoped_refptr<UrlLoader> embed_preview_loader_; // The current cursor. PP_CursorType_Dev cursor_ = PP_CURSORTYPE_POINTER; @@ -426,7 +427,7 @@ std::string url_; // Used for submitting forms. - pp::URLLoader form_loader_; + scoped_refptr<UrlLoader> form_loader_; // The callback for receiving the password from the page. base::OnceCallback<void(const std::string&)> password_callback_;
diff --git a/pdf/pdf_engine.h b/pdf/pdf_engine.h index dc78be96..81ddb04 100644 --- a/pdf/pdf_engine.h +++ b/pdf/pdf_engine.h
@@ -12,6 +12,7 @@ #include "base/callback.h" #include "base/containers/span.h" +#include "base/memory/scoped_refptr.h" #include "base/optional.h" #include "base/strings/string16.h" #include "base/time/time.h" @@ -58,6 +59,7 @@ namespace chrome_pdf { class InputEvent; +class UrlLoader; struct DocumentAttachmentInfo; struct DocumentMetadata; @@ -220,7 +222,7 @@ int length) {} // Creates and returns new URL loader for partial document requests. - virtual pp::URLLoader CreateURLLoader() = 0; + virtual scoped_refptr<UrlLoader> CreateUrlLoader() = 0; // Searches the given string for "term" and returns the results. Unicode- // aware. @@ -336,7 +338,7 @@ std::vector<pp::Rect>& ready, std::vector<pp::Rect>& pending) = 0; virtual void PostPaint() = 0; - virtual bool HandleDocumentLoad(const pp::URLLoader& loader) = 0; + virtual bool HandleDocumentLoad(scoped_refptr<UrlLoader> loader) = 0; virtual bool HandleEvent(const InputEvent& event) = 0; virtual uint32_t QuerySupportedPrintOutputFormats() = 0; virtual void PrintBegin() = 0;
diff --git a/pdf/pdf_view_web_plugin.cc b/pdf/pdf_view_web_plugin.cc index 8c7cdda8..0ec84d0 100644 --- a/pdf/pdf_view_web_plugin.cc +++ b/pdf/pdf_view_web_plugin.cc
@@ -10,8 +10,10 @@ #include <vector> #include "base/check_op.h" +#include "base/memory/scoped_refptr.h" #include "cc/paint/paint_canvas.h" #include "pdf/pdf_engine.h" +#include "pdf/ppapi_migration/url_loader.h" #include "ppapi/cpp/url_loader.h" #include "third_party/blink/public/common/input/web_coalesced_input_event.h" #include "third_party/blink/public/common/metrics/document_update_reason.h" @@ -149,8 +151,8 @@ const void* data, int length) {} -pp::URLLoader PdfViewWebPlugin::CreateURLLoader() { - return pp::URLLoader(); +scoped_refptr<UrlLoader> PdfViewWebPlugin::CreateUrlLoader() { + return base::MakeRefCounted<UrlLoader>(); } std::vector<PDFEngine::Client::SearchStringResult>
diff --git a/pdf/pdf_view_web_plugin.h b/pdf/pdf_view_web_plugin.h index da351e4..fd2ff544 100644 --- a/pdf/pdf_view_web_plugin.h +++ b/pdf/pdf_view_web_plugin.h
@@ -79,7 +79,7 @@ void SubmitForm(const std::string& url, const void* data, int length) override; - pp::URLLoader CreateURLLoader() override; + scoped_refptr<UrlLoader> CreateUrlLoader() override; std::vector<SearchStringResult> SearchString(const base::char16* string, const base::char16* term, bool case_sensitive) override;
diff --git a/pdf/pdfium/pdfium_engine.cc b/pdf/pdfium/pdfium_engine.cc index 40b31af..1107c7c 100644 --- a/pdf/pdfium/pdfium_engine.cc +++ b/pdf/pdfium/pdfium_engine.cc
@@ -20,6 +20,7 @@ #include "base/check_op.h" #include "base/debug/alias.h" #include "base/feature_list.h" +#include "base/memory/scoped_refptr.h" #include "base/notreached.h" #include "base/stl_util.h" #include "base/strings/string_util.h" @@ -45,6 +46,7 @@ #include "pdf/ppapi_migration/bitmap.h" #include "pdf/ppapi_migration/geometry_conversions.h" #include "pdf/ppapi_migration/input_event_conversions.h" +#include "pdf/ppapi_migration/url_loader.h" #include "pdf/url_loader_wrapper_impl.h" #include "ppapi/cpp/instance.h" #include "ppapi/cpp/private/pdf.h" @@ -629,14 +631,14 @@ } } -bool PDFiumEngine::HandleDocumentLoad(const pp::URLLoader& loader) { +bool PDFiumEngine::HandleDocumentLoad(scoped_refptr<UrlLoader> loader) { password_tries_remaining_ = kMaxPasswordTries; process_when_pending_request_complete_ = base::FeatureList::IsEnabled(features::kPdfIncrementalLoading); if (!doc_loader_set_for_testing_) { - auto loader_wrapper = - std::make_unique<URLLoaderWrapperImpl>(GetPluginInstance(), loader); + auto loader_wrapper = std::make_unique<URLLoaderWrapperImpl>( + GetPluginInstance(), std::move(loader)); loader_wrapper->SetResponseHeaders(headers_); doc_loader_ = std::make_unique<DocumentLoaderImpl>(this); @@ -656,7 +658,7 @@ std::unique_ptr<URLLoaderWrapper> PDFiumEngine::CreateURLLoader() { return std::make_unique<URLLoaderWrapperImpl>(GetPluginInstance(), - client_->CreateURLLoader()); + client_->CreateUrlLoader()); } void PDFiumEngine::AppendPage(PDFEngine* engine, int index) {
diff --git a/pdf/pdfium/pdfium_engine.h b/pdf/pdfium/pdfium_engine.h index 93ae4cc..9f66b99 100644 --- a/pdf/pdfium/pdfium_engine.h +++ b/pdf/pdfium/pdfium_engine.h
@@ -93,7 +93,7 @@ std::vector<pp::Rect>& ready, std::vector<pp::Rect>& pending) override; void PostPaint() override; - bool HandleDocumentLoad(const pp::URLLoader& loader) override; + bool HandleDocumentLoad(scoped_refptr<UrlLoader> loader) override; bool HandleEvent(const InputEvent& event) override; uint32_t QuerySupportedPrintOutputFormats() override; void PrintBegin() override;
diff --git a/pdf/pdfium/pdfium_test_base.cc b/pdf/pdfium/pdfium_test_base.cc index 5e10938..64bafab 100644 --- a/pdf/pdfium/pdfium_test_base.cc +++ b/pdf/pdfium/pdfium_test_base.cc
@@ -9,8 +9,10 @@ #include <utility> #include "base/check_op.h" +#include "base/memory/scoped_refptr.h" #include "build/build_config.h" #include "pdf/pdfium/pdfium_engine.h" +#include "pdf/ppapi_migration/url_loader.h" #include "pdf/test/test_client.h" #include "pdf/test/test_document_loader.h" @@ -83,7 +85,7 @@ const base::FilePath::CharType* pdf_name) { InitializeEngineResult result; - pp::URLLoader dummy_loader; + auto dummy_loader = base::MakeRefCounted<UrlLoader>(); result.engine = std::make_unique<PDFiumEngine>(client, /*enable_javascript=*/false); client->set_engine(result.engine.get()); @@ -94,7 +96,7 @@ result.engine->SetDocumentLoaderForTesting(std::move(test_loader)); if (!result.engine->New("https://chromium.org/dummy.pdf", "") || - !result.engine->HandleDocumentLoad(dummy_loader)) { + !result.engine->HandleDocumentLoad(std::move(dummy_loader))) { client->set_engine(nullptr); result.engine = nullptr; result.document_loader = nullptr;
diff --git a/pdf/ppapi_migration/url_loader.cc b/pdf/ppapi_migration/url_loader.cc new file mode 100644 index 0000000..9fad8e7 --- /dev/null +++ b/pdf/ppapi_migration/url_loader.cc
@@ -0,0 +1,73 @@ +// Copyright 2020 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "pdf/ppapi_migration/url_loader.h" + +#include <stdint.h> + +#include <utility> + +#include "base/callback.h" +#include "pdf/ppapi_migration/callback.h" +#include "ppapi/c/pp_errors.h" +#include "ppapi/c/trusted/ppb_url_loader_trusted.h" +#include "ppapi/cpp/completion_callback.h" +#include "ppapi/cpp/instance_handle.h" +#include "ppapi/cpp/module.h" +#include "ppapi/cpp/url_loader.h" +#include "ppapi/cpp/url_request_info.h" +#include "ppapi/cpp/url_response_info.h" + +namespace chrome_pdf { + +UrlLoader::UrlLoader() = default; + +UrlLoader::UrlLoader(pp::InstanceHandle plugin_instance) + : pepper_loader_(plugin_instance) {} + +UrlLoader::~UrlLoader() = default; + +void UrlLoader::GrantUniversalAccess() { + const PPB_URLLoaderTrusted* trusted_interface = + static_cast<const PPB_URLLoaderTrusted*>( + pp::Module::Get()->GetBrowserInterface( + PPB_URLLOADERTRUSTED_INTERFACE)); + if (trusted_interface) + trusted_interface->GrantUniversalAccess(pepper_loader_.pp_resource()); +} + +void UrlLoader::Open(const pp::URLRequestInfo& request_info, + ResultCallback callback) { + pp::CompletionCallback pp_callback = + PPCompletionCallbackFromResultCallback(std::move(callback)); + int32_t result = pepper_loader_.Open(request_info, pp_callback); + if (result != PP_OK_COMPLETIONPENDING) + pp_callback.Run(result); +} + +bool UrlLoader::GetDownloadProgress(int64_t* bytes_received, + int64_t* total_bytes_to_be_received) const { + return pepper_loader_.GetDownloadProgress(bytes_received, + total_bytes_to_be_received); +} + +pp::URLResponseInfo UrlLoader::GetResponseInfo() const { + return pepper_loader_.GetResponseInfo(); +} + +void UrlLoader::ReadResponseBody(base::span<char> buffer, + ResultCallback callback) { + pp::CompletionCallback pp_callback = + PPCompletionCallbackFromResultCallback(std::move(callback)); + int32_t result = pepper_loader_.ReadResponseBody(buffer.data(), buffer.size(), + pp_callback); + if (result != PP_OK_COMPLETIONPENDING) + pp_callback.Run(result); +} + +void UrlLoader::Close() { + pepper_loader_.Close(); +} + +} // namespace chrome_pdf
diff --git a/pdf/ppapi_migration/url_loader.h b/pdf/ppapi_migration/url_loader.h new file mode 100644 index 0000000..6081d64d --- /dev/null +++ b/pdf/ppapi_migration/url_loader.h
@@ -0,0 +1,56 @@ +// Copyright 2020 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef PDF_PPAPI_MIGRATION_URL_LOADER_H_ +#define PDF_PPAPI_MIGRATION_URL_LOADER_H_ + +#include <stdint.h> + +#include "base/containers/span.h" +#include "base/memory/ref_counted.h" +#include "pdf/ppapi_migration/callback.h" +#include "ppapi/cpp/url_loader.h" + +namespace pp { +class InstanceHandle; +class URLRequestInfo; +class URLResponseInfo; +} // namespace pp + +namespace chrome_pdf { + +// Thin wrapper around a `pp::URLLoader`. Unlike a `pp::URLLoader`, this class +// does not perform its own reference counting, but relies on `scoped_refptr`. +// +// TODO(crbug.com/1099022): Make this abstract, and add a Blink implementation. +class UrlLoader : public base::RefCounted<UrlLoader> { + public: + UrlLoader(); + explicit UrlLoader(pp::InstanceHandle plugin_instance); + UrlLoader(const UrlLoader&) = delete; + UrlLoader& operator=(const UrlLoader&) = delete; + + // Tries to grant the loader the capability to make unrestricted cross-origin + // requests ("universal access," in `blink::SecurityOrigin` terms). + void GrantUniversalAccess(); + + // Mimic `pp::URLLoader`: + void Open(const pp::URLRequestInfo& request_info, ResultCallback callback); + bool GetDownloadProgress(int64_t* bytes_received, + int64_t* total_bytes_to_be_received) const; + pp::URLResponseInfo GetResponseInfo() const; + void ReadResponseBody(base::span<char> buffer, ResultCallback callback); + void Close(); + + private: + friend class base::RefCounted<UrlLoader>; + + ~UrlLoader(); + + pp::URLLoader pepper_loader_; +}; + +} // namespace chrome_pdf + +#endif // PDF_PPAPI_MIGRATION_URL_LOADER_H_
diff --git a/pdf/preview_mode_client.cc b/pdf/preview_mode_client.cc index 41dd568e..ec7b2aa 100644 --- a/pdf/preview_mode_client.cc +++ b/pdf/preview_mode_client.cc
@@ -10,8 +10,10 @@ #include <utility> #include "base/callback.h" +#include "base/memory/scoped_refptr.h" #include "base/notreached.h" #include "pdf/document_layout.h" +#include "pdf/ppapi_migration/url_loader.h" namespace chrome_pdf { @@ -114,9 +116,9 @@ NOTREACHED(); } -pp::URLLoader PreviewModeClient::CreateURLLoader() { +scoped_refptr<UrlLoader> PreviewModeClient::CreateUrlLoader() { NOTREACHED(); - return pp::URLLoader(); + return base::MakeRefCounted<UrlLoader>(); } std::vector<PDFEngine::Client::SearchStringResult>
diff --git a/pdf/preview_mode_client.h b/pdf/preview_mode_client.h index 5c78f66..c3ed56d 100644 --- a/pdf/preview_mode_client.h +++ b/pdf/preview_mode_client.h
@@ -61,7 +61,7 @@ void SubmitForm(const std::string& url, const void* data, int length) override; - pp::URLLoader CreateURLLoader() override; + scoped_refptr<UrlLoader> CreateUrlLoader() override; std::vector<SearchStringResult> SearchString(const base::char16* string, const base::char16* term, bool case_sensitive) override;
diff --git a/pdf/test/test_client.cc b/pdf/test/test_client.cc index 7fab6611..aec6857 100644 --- a/pdf/test/test_client.cc +++ b/pdf/test/test_client.cc
@@ -4,7 +4,9 @@ #include "pdf/test/test_client.h" +#include "base/memory/scoped_refptr.h" #include "pdf/document_layout.h" +#include "pdf/ppapi_migration/url_loader.h" namespace chrome_pdf { @@ -33,8 +35,8 @@ return std::string(); } -pp::URLLoader TestClient::CreateURLLoader() { - return pp::URLLoader(); +scoped_refptr<UrlLoader> TestClient::CreateUrlLoader() { + return base::MakeRefCounted<UrlLoader>(); } std::vector<PDFEngine::Client::SearchStringResult> TestClient::SearchString(
diff --git a/pdf/test/test_client.h b/pdf/test/test_client.h index 4eaf930..48429bc 100644 --- a/pdf/test/test_client.h +++ b/pdf/test/test_client.h
@@ -30,7 +30,7 @@ std::string Prompt(const std::string& question, const std::string& default_answer) override; std::string GetURL() override; - pp::URLLoader CreateURLLoader() override; + scoped_refptr<UrlLoader> CreateUrlLoader() override; std::vector<SearchStringResult> SearchString(const base::char16* string, const base::char16* term, bool case_sensitive) override;
diff --git a/pdf/url_loader_wrapper_impl.cc b/pdf/url_loader_wrapper_impl.cc index 20ee17a77..1571049 100644 --- a/pdf/url_loader_wrapper_impl.cc +++ b/pdf/url_loader_wrapper_impl.cc
@@ -4,20 +4,26 @@ #include "pdf/url_loader_wrapper_impl.h" -#include <memory> +#include <stddef.h> +#include <stdint.h> +#include <stdlib.h> +#include <string.h> + +#include <string> #include <utility> #include "base/bind.h" #include "base/callback.h" #include "base/check_op.h" +#include "base/containers/span.h" #include "base/strings/string_util.h" #include "base/strings/stringprintf.h" #include "net/http/http_util.h" -#include "ppapi/c/pp_errors.h" -#include "ppapi/cpp/completion_callback.h" -#include "ppapi/cpp/logging.h" +#include "pdf/ppapi_migration/url_loader.h" #include "ppapi/cpp/url_request_info.h" #include "ppapi/cpp/url_response_info.h" +#include "ppapi/cpp/var.h" +#include "ui/gfx/range/range.h" namespace chrome_pdf { @@ -101,8 +107,8 @@ } // namespace URLLoaderWrapperImpl::URLLoaderWrapperImpl(pp::Instance* plugin_instance, - const pp::URLLoader& url_loader) - : plugin_instance_(plugin_instance), url_loader_(url_loader) { + scoped_refptr<UrlLoader> url_loader) + : plugin_instance_(plugin_instance), url_loader_(std::move(url_loader)) { SetHeadersFromLoader(); } @@ -130,7 +136,7 @@ } int URLLoaderWrapperImpl::GetStatusCode() const { - return url_loader_.GetResponseInfo().GetStatusCode(); + return url_loader_->GetResponseInfo().GetStatusCode(); } bool URLLoaderWrapperImpl::IsMultipart() const { @@ -146,12 +152,12 @@ bool URLLoaderWrapperImpl::GetDownloadProgress( int64_t* bytes_received, int64_t* total_bytes_to_be_received) const { - return url_loader_.GetDownloadProgress(bytes_received, - total_bytes_to_be_received); + return url_loader_->GetDownloadProgress(bytes_received, + total_bytes_to_be_received); } void URLLoaderWrapperImpl::Close() { - url_loader_.Close(); + url_loader_->Close(); read_starter_.Stop(); } @@ -160,14 +166,10 @@ uint32_t position, uint32_t size, ResultCallback callback) { - pp::CompletionCallback cc = PPCompletionCallbackFromResultCallback( + url_loader_->Open( + MakeRangeRequest(plugin_instance_, url, referrer_url, position, size), base::BindOnce(&URLLoaderWrapperImpl::DidOpen, weak_factory_.GetWeakPtr(), std::move(callback))); - int rv = url_loader_.Open( - MakeRangeRequest(plugin_instance_, url, referrer_url, position, size), - cc); - if (rv != PP_OK_COMPLETIONPENDING) - cc.Run(rv); } void URLLoaderWrapperImpl::ReadResponseBody(char* buffer, @@ -182,13 +184,10 @@ } void URLLoaderWrapperImpl::ReadResponseBodyImpl(ResultCallback callback) { - pp::CompletionCallback cc = PPCompletionCallbackFromResultCallback( + url_loader_->ReadResponseBody( + base::span<char>(buffer_, buffer_size_), base::BindOnce(&URLLoaderWrapperImpl::DidRead, weak_factory_.GetWeakPtr(), std::move(callback))); - int rv = url_loader_.ReadResponseBody(buffer_, buffer_size_, cc); - if (rv != PP_OK_COMPLETIONPENDING) { - cc.Run(rv); - } } void URLLoaderWrapperImpl::SetResponseHeaders( @@ -300,7 +299,7 @@ } void URLLoaderWrapperImpl::SetHeadersFromLoader() { - pp::URLResponseInfo response = url_loader_.GetResponseInfo(); + pp::URLResponseInfo response = url_loader_->GetResponseInfo(); pp::Var headers_var = response.GetHeaders(); SetResponseHeaders(headers_var.is_string() ? headers_var.AsString() : "");
diff --git a/pdf/url_loader_wrapper_impl.h b/pdf/url_loader_wrapper_impl.h index 1de27e6f..625fb31c 100644 --- a/pdf/url_loader_wrapper_impl.h +++ b/pdf/url_loader_wrapper_impl.h
@@ -10,11 +10,11 @@ #include <memory> #include <string> +#include "base/memory/scoped_refptr.h" #include "base/memory/weak_ptr.h" #include "base/timer/timer.h" #include "pdf/ppapi_migration/callback.h" #include "pdf/url_loader_wrapper.h" -#include "ppapi/cpp/url_loader.h" #include "ui/gfx/range/range.h" namespace pp { @@ -23,10 +23,12 @@ namespace chrome_pdf { +class UrlLoader; + class URLLoaderWrapperImpl : public URLLoaderWrapper { public: URLLoaderWrapperImpl(pp::Instance* plugin_instance, - const pp::URLLoader& url_loader); + scoped_refptr<UrlLoader> url_loader); URLLoaderWrapperImpl(const URLLoaderWrapperImpl&) = delete; URLLoaderWrapperImpl& operator=(const URLLoaderWrapperImpl&) = delete; ~URLLoaderWrapperImpl() override; @@ -63,7 +65,7 @@ void ReadResponseBodyImpl(ResultCallback callback); pp::Instance* const plugin_instance_; - pp::URLLoader url_loader_; + scoped_refptr<UrlLoader> url_loader_; std::string response_headers_; int content_length_ = -1;
diff --git a/services/tracing/public/cpp/stack_sampling/reached_code_data_source_android.cc b/services/tracing/public/cpp/stack_sampling/reached_code_data_source_android.cc index 8d423d9..135ff23 100644 --- a/services/tracing/public/cpp/stack_sampling/reached_code_data_source_android.cc +++ b/services/tracing/public/cpp/stack_sampling/reached_code_data_source_android.cc
@@ -9,11 +9,17 @@ #include "base/android/reached_addresses_bitset.h" #include "base/android/reached_code_profiler.h" +#include "base/debug/elf_reader.h" #include "services/tracing/public/cpp/perfetto/perfetto_producer.h" +#include "services/tracing/public/cpp/stack_sampling/tracing_sampler_profiler.h" #include "third_party/perfetto/include/perfetto/tracing/data_source.h" +#include "third_party/perfetto/protos/perfetto/trace/interned_data/interned_data.pbzero.h" +#include "third_party/perfetto/protos/perfetto/trace/profiling/profile_common.pbzero.h" #include "third_party/perfetto/protos/perfetto/trace/profiling/profile_packet.pbzero.h" #include "third_party/perfetto/protos/perfetto/trace/trace_packet.pbzero.h" +extern char __ehdr_start; + namespace tracing { // static @@ -47,9 +53,30 @@ if (!bitset) { return; } - std::vector<uint32_t> offsets = bitset->GetReachedOffsets(); + perfetto::TraceWriter::TracePacketHandle trace_packet = trace_writer_->NewTracePacket(); + + auto* interned_data = trace_packet->set_interned_data(); + base::debug::ElfBuildIdBuffer buf; + size_t size = base::debug::ReadElfBuildId(&__ehdr_start, true, buf); + if (size > 0) { + std::string module_id(buf, size); + TracingSamplerProfiler::MangleModuleIDIfNeeded(&module_id); + auto* str = interned_data->add_build_ids(); + str->set_iid(0); + str->set_str(module_id); + } + + base::Optional<base::StringPiece> library_name = + base::debug::ReadElfLibraryName(&__ehdr_start); + if (library_name) { + auto* str = interned_data->add_mapping_paths(); + str->set_iid(0); + str->set_str(library_name->as_string()); + } + + std::vector<uint32_t> offsets = bitset->GetReachedOffsets(); // Delta encoded timestamps and interned data require incremental state. auto* streaming_profile_packet = trace_packet->set_streaming_profile_packet(); for (uint32_t offset : offsets) {
diff --git a/services/viz/public/cpp/compositing/quads_mojom_traits.h b/services/viz/public/cpp/compositing/quads_mojom_traits.h index fb60ffff..0b29f620 100644 --- a/services/viz/public/cpp/compositing/quads_mojom_traits.h +++ b/services/viz/public/cpp/compositing/quads_mojom_traits.h
@@ -74,6 +74,8 @@ switch (quad.material) { case viz::DrawQuad::Material::kInvalid: break; + case viz::DrawQuad::Material::kAggregatedRenderPass: + break; case viz::DrawQuad::Material::kDebugBorder: return viz::mojom::DrawQuadStateDataView::Tag::DEBUG_BORDER_QUAD_STATE; case viz::DrawQuad::Material::kPictureContent:
diff --git a/skia/config/SkUserConfig.h b/skia/config/SkUserConfig.h index d9ee3391..a2a56f4 100644 --- a/skia/config/SkUserConfig.h +++ b/skia/config/SkUserConfig.h
@@ -225,9 +225,6 @@ #define SK_SUPPORT_LEGACY_AAA_CHOICE #endif -// Staging for changes to SkRuntimeEffect main() signature -#define SK_USE_LEGACY_RUNTIME_EFFECT_SIGNATURE - // Staging for lowp::bilerp_clamp_8888, and for planned misc. others. #define SK_DISABLE_LOWP_BILERP_CLAMP_CLAMP_STAGE
diff --git a/testing/buildbot/filters/gpu.linux.skiarenderer_dawn_viz_unittests.filter b/testing/buildbot/filters/gpu.linux.skiarenderer_dawn_viz_unittests.filter index 2eb6fe1..8a933506 100644 --- a/testing/buildbot/filters/gpu.linux.skiarenderer_dawn_viz_unittests.filter +++ b/testing/buildbot/filters/gpu.linux.skiarenderer_dawn_viz_unittests.filter
@@ -1,2 +1 @@ -# crbug.com/1061988: Overdraw feedback isn't supported using Skia Dawn Vulkan --SkiaRendererPixelTestWithOverdrawFeedback/2.TranslucentRectangles +# TODO(sgilhuly): Remove this file once SkiaRenderer Dawn is more stable.
diff --git a/third_party/abseil-cpp/absl/base/BUILD.gn b/third_party/abseil-cpp/absl/base/BUILD.gn index 16a6387fe8..346a47d 100644 --- a/third_party/abseil-cpp/absl/base/BUILD.gn +++ b/third_party/abseil-cpp/absl/base/BUILD.gn
@@ -6,7 +6,7 @@ absl_source_set("atomic_hook") { public = [ "internal/atomic_hook.h" ] - deps = [ + public_deps = [ ":config", ":core_headers", ] @@ -15,14 +15,14 @@ absl_source_set("errno_saver") { public = [ "internal/errno_saver.h" ] - deps = [ ":config" ] + public_deps = [ ":config" ] visibility = [ "//third_party/abseil-cpp/absl/*" ] } absl_source_set("log_severity") { sources = [ "log_severity.cc" ] public = [ "log_severity.h" ] - deps = [ + public_deps = [ ":config", ":core_headers", ] @@ -31,7 +31,7 @@ absl_source_set("raw_logging_internal") { sources = [ "internal/raw_logging.cc" ] public = [ "internal/raw_logging.h" ] - deps = [ + public_deps = [ ":atomic_hook", ":config", ":core_headers", @@ -86,7 +86,7 @@ "port.h", "thread_annotations.h", ] - deps = [ ":config" ] + public_deps = [ ":config" ] } absl_source_set("malloc_internal") { @@ -95,7 +95,7 @@ "internal/direct_mmap.h", "internal/low_level_alloc.h", ] - deps = [ + public_deps = [ ":base", ":base_internal", ":config", @@ -113,7 +113,7 @@ "internal/invoke.h", "internal/scheduling_mode.h", ] - deps = [ + public_deps = [ ":config", "//third_party/abseil-cpp/absl/meta:type_traits", ] @@ -144,7 +144,7 @@ # TODO(mbonadei): The bazel file has: # "-DEFAULTLIB:advapi32.lib" # understand if this is needed here as well. - deps = [ + public_deps = [ ":atomic_hook", ":base_internal", ":config", @@ -160,7 +160,7 @@ absl_source_set("throw_delegate") { sources = [ "internal/throw_delegate.cc" ] public = [ "internal/throw_delegate.h" ] - deps = [ + public_deps = [ ":config", ":raw_logging_internal", ] @@ -170,7 +170,7 @@ absl_source_set("exception_testing") { testonly = true public = [ "internal/exception_testing.h" ] - deps = [ ":config" ] + public_deps = [ ":config" ] visibility = [ "//third_party/abseil-cpp/absl/*" ] } @@ -224,7 +224,7 @@ "internal/endian.h", "internal/unaligned_access.h", ] - deps = [ + public_deps = [ ":config", ":core_headers", ] @@ -232,7 +232,7 @@ absl_source_set("bits") { public = [ "internal/bits.h" ] - deps = [ + public_deps = [ ":config", ":core_headers", ] @@ -242,7 +242,7 @@ absl_source_set("exponential_biased") { sources = [ "internal/exponential_biased.cc" ] public = [ "internal/exponential_biased.h" ] - deps = [ + public_deps = [ ":config", ":core_headers", ] @@ -252,7 +252,7 @@ absl_source_set("periodic_sampler") { sources = [ "internal/periodic_sampler.cc" ] public = [ "internal/periodic_sampler.h" ] - deps = [ + public_deps = [ ":core_headers", ":exponential_biased", ] @@ -262,8 +262,10 @@ testonly = true public = [ "internal/scoped_set_env.h" ] sources = [ "internal/scoped_set_env.cc" ] - deps = [ + public_deps = [ ":config", + ] + deps = [ ":raw_logging_internal", ] visibility = [ "//third_party/abseil-cpp/absl/*" ] @@ -272,8 +274,10 @@ absl_source_set("strerror") { sources = [ "internal/strerror.cc" ] public = [ "internal/strerror.h" ] - deps = [ + public_deps = [ ":config", + ] + deps = [ ":core_headers", ":errno_saver", ] @@ -282,7 +286,7 @@ absl_source_set("fast_type_id") { public = [ "internal/fast_type_id.h" ] - deps = [ ":config" ] + public_deps = [ ":config" ] visibility = [ "//third_party/abseil-cpp/absl/*" ] }
diff --git a/third_party/abseil-cpp/absl/types/BUILD.gn b/third_party/abseil-cpp/absl/types/BUILD.gn index f9f1515c..61ce7f4 100644 --- a/third_party/abseil-cpp/absl/types/BUILD.gn +++ b/third_party/abseil-cpp/absl/types/BUILD.gn
@@ -7,7 +7,7 @@ absl_source_set("any") { public = [ "any.h" ] - deps = [ + public_deps = [ ":bad_any_cast", "//third_party/abseil-cpp/absl/base:config", "//third_party/abseil-cpp/absl/base:core_headers", @@ -21,6 +21,8 @@ public = [ "bad_any_cast.h" ] deps = [ ":bad_any_cast_impl", + ] + public_deps = [ "//third_party/abseil-cpp/absl/base:config", ] } @@ -28,8 +30,10 @@ absl_source_set("bad_any_cast_impl") { sources = [ "bad_any_cast.cc" ] public = [ "bad_any_cast.h" ] - deps = [ + public_deps = [ "//third_party/abseil-cpp/absl/base:config", + ] + deps = [ "//third_party/abseil-cpp/absl/base:raw_logging_internal", ] visibility = [ ":*" ] @@ -38,7 +42,7 @@ absl_source_set("span") { public = [ "span.h" ] sources = [ "internal/span.h" ] - deps = [ + public_deps = [ "//third_party/abseil-cpp/absl/algorithm", "//third_party/abseil-cpp/absl/base:core_headers", "//third_party/abseil-cpp/absl/base:throw_delegate", @@ -49,7 +53,7 @@ absl_source_set("optional") { sources = [ "internal/optional.h" ] public = [ "optional.h" ] - deps = [ + public_deps = [ ":bad_optional_access", "//third_party/abseil-cpp/absl/base:base_internal", "//third_party/abseil-cpp/absl/base:config", @@ -63,8 +67,10 @@ absl_source_set("bad_optional_access") { sources = [ "bad_optional_access.cc" ] public = [ "bad_optional_access.h" ] - deps = [ + public_deps = [ "//third_party/abseil-cpp/absl/base:config", + ] + deps = [ "//third_party/abseil-cpp/absl/base:raw_logging_internal", ] } @@ -72,8 +78,10 @@ absl_source_set("bad_variant_access") { sources = [ "bad_variant_access.cc" ] public = [ "bad_variant_access.h" ] - deps = [ + public_deps = [ "//third_party/abseil-cpp/absl/base:config", + ] + deps = [ "//third_party/abseil-cpp/absl/base:raw_logging_internal", ] } @@ -81,7 +89,7 @@ absl_source_set("variant") { sources = [ "internal/variant.h" ] public = [ "variant.h" ] - deps = [ + public_deps = [ ":bad_variant_access", "//third_party/abseil-cpp/absl/base:base_internal", "//third_party/abseil-cpp/absl/base:config", @@ -93,7 +101,7 @@ absl_source_set("compare") { public = [ "compare.h" ] - deps = [ + public_deps = [ "//third_party/abseil-cpp/absl/base:core_headers", "//third_party/abseil-cpp/absl/meta:type_traits", ]
diff --git a/third_party/blink/common/loader/referrer_utils.cc b/third_party/blink/common/loader/referrer_utils.cc index 7b410d9..1193db1 100644 --- a/third_party/blink/common/loader/referrer_utils.cc +++ b/third_party/blink/common/loader/referrer_utils.cc
@@ -63,17 +63,16 @@ // The ReducedReferrerGranularity feature sets the default referrer // policy to strict-origin-when-cross-origin unless forbidden // by the "force legacy policy" global. - // TODO(crbug.com/1016541) Once the pertinent enterprise policy has - // been removed in M88, update this to remove the global. + if (IsReducedReferrerGranularityEnabled()) + return net::ReferrerPolicy::REDUCE_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN; + return net::ReferrerPolicy::CLEAR_ON_TRANSITION_FROM_SECURE_TO_INSECURE; +} - // Short-circuit to avoid acquiring the lock unless necessary. - if (!base::FeatureList::IsEnabled(features::kReducedReferrerGranularity)) - return net::ReferrerPolicy::CLEAR_ON_TRANSITION_FROM_SECURE_TO_INSECURE; - - return ShouldForceLegacyDefaultReferrerPolicy() - ? net::ReferrerPolicy::CLEAR_ON_TRANSITION_FROM_SECURE_TO_INSECURE - : net::ReferrerPolicy:: - REDUCE_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN; +network::mojom::ReferrerPolicy ReferrerUtils::MojoReferrerPolicyResolveDefault( + network::mojom::ReferrerPolicy referrer_policy) { + if (referrer_policy == network::mojom::ReferrerPolicy::kDefault) + return NetToMojoReferrerPolicy(GetDefaultNetReferrerPolicy()); + return referrer_policy; } void ReferrerUtils::SetForceLegacyDefaultReferrerPolicy(bool force) { @@ -84,4 +83,12 @@ return ReadModifyWriteForceLegacyPolicyFlag(base::nullopt); } +// TODO(crbug.com/1016541) Once the pertinent enterprise policy has +// been removed in M88, update this to remove the global. +bool ReferrerUtils::IsReducedReferrerGranularityEnabled() { + return base::FeatureList::IsEnabled( + blink::features::kReducedReferrerGranularity) && + !ShouldForceLegacyDefaultReferrerPolicy(); +} + } // namespace blink
diff --git a/third_party/blink/public/common/loader/referrer_utils.h b/third_party/blink/public/common/loader/referrer_utils.h index 0136839ca..562a6e5 100644 --- a/third_party/blink/public/common/loader/referrer_utils.h +++ b/third_party/blink/public/common/loader/referrer_utils.h
@@ -19,6 +19,13 @@ static BLINK_COMMON_EXPORT net::ReferrerPolicy GetDefaultNetReferrerPolicy(); + // The ReferrerPolicy enum contains a member kDefault, which is not a real + // referrer policy, but instead Blink fallbacks to kNoReferrerWhenDowngrade + // when a certain condition is met. The function below is provided so that a + // referrer policy which may be kDefault can be resolved to a valid value. + static BLINK_COMMON_EXPORT network::mojom::ReferrerPolicy + MojoReferrerPolicyResolveDefault(network::mojom::ReferrerPolicy); + // Configures retaining the pre-M80 default referrer // policy of no-referrer-when-downgrade. // TODO(crbug.com/1016541): After M88, remove when the corresponding @@ -26,6 +33,8 @@ static BLINK_COMMON_EXPORT void SetForceLegacyDefaultReferrerPolicy( bool force); static BLINK_COMMON_EXPORT bool ShouldForceLegacyDefaultReferrerPolicy(); + + static BLINK_COMMON_EXPORT bool IsReducedReferrerGranularityEnabled(); }; } // namespace blink
diff --git a/third_party/blink/public/mojom/sms/sms_receiver.mojom b/third_party/blink/public/mojom/sms/sms_receiver.mojom index 8e0238f..c1722c4f 100644 --- a/third_party/blink/public/mojom/sms/sms_receiver.mojom +++ b/third_party/blink/public/mojom/sms/sms_receiver.mojom
@@ -8,7 +8,7 @@ // Implementation of the proposed "Sms Detection API". // -// Proposal: https://github.com/samuelgoto/sms-receiver +// Proposal: https://github.com/WICG/web-otp enum SmsStatus { kSuccess, kTimeout,
diff --git a/third_party/blink/public/platform/web_runtime_features.h b/third_party/blink/public/platform/web_runtime_features.h index 2811c80..0edffa3 100644 --- a/third_party/blink/public/platform/web_runtime_features.h +++ b/third_party/blink/public/platform/web_runtime_features.h
@@ -154,7 +154,6 @@ BLINK_PLATFORM_EXPORT static void EnablePresentationAPI(bool); BLINK_PLATFORM_EXPORT static void EnablePushMessaging(bool); BLINK_PLATFORM_EXPORT static void EnablePushSubscriptionChangeEvent(bool); - BLINK_PLATFORM_EXPORT static void EnableReducedReferrerGranularity(bool); BLINK_PLATFORM_EXPORT static void EnableRemotePlaybackAPI(bool); BLINK_PLATFORM_EXPORT static void EnableRestrictAutomaticLazyFrameLoadingToDataSaver(bool);
diff --git a/third_party/blink/renderer/bindings/core/v8/generated_code_helper.cc b/third_party/blink/renderer/bindings/core/v8/generated_code_helper.cc index 37f6ed6..6fdce97 100644 --- a/third_party/blink/renderer/bindings/core/v8/generated_code_helper.cc +++ b/third_party/blink/renderer/bindings/core/v8/generated_code_helper.cc
@@ -395,7 +395,7 @@ const QualifiedName& content_attribute, const char* interface_name, const char* attribute_name) { - PerformAttributeSetCEReactionsReflect<IDLStringV2, AtomicString, + PerformAttributeSetCEReactionsReflect<IDLStringV2, const AtomicString&, &Element::setAttribute>( info, content_attribute, interface_name, attribute_name); } @@ -406,7 +406,8 @@ const char* interface_name, const char* attribute_name) { PerformAttributeSetCEReactionsReflect<IDLStringTreatNullAsEmptyStringV2, - AtomicString, &Element::setAttribute>( + const AtomicString&, + &Element::setAttribute>( info, content_attribute, interface_name, attribute_name); } @@ -415,8 +416,8 @@ const QualifiedName& content_attribute, const char* interface_name, const char* attribute_name) { - PerformAttributeSetCEReactionsReflect<IDLNullable<IDLStringV2>, AtomicString, - &Element::setAttribute>( + PerformAttributeSetCEReactionsReflect< + IDLNullable<IDLStringV2>, const AtomicString&, &Element::setAttribute>( info, content_attribute, interface_name, attribute_name); }
diff --git a/third_party/blink/renderer/core/css/css_font_face_src_value.cc b/third_party/blink/renderer/core/css/css_font_face_src_value.cc index d92d5467..943d9d3 100644 --- a/third_party/blink/renderer/core/css/css_font_face_src_value.cc +++ b/third_party/blink/renderer/core/css/css_font_face_src_value.cc
@@ -27,6 +27,7 @@ #include "base/feature_list.h" #include "third_party/blink/public/common/features.h" +#include "third_party/blink/public/common/loader/referrer_utils.h" #include "third_party/blink/public/platform/web_url_request.h" #include "third_party/blink/renderer/core/css/css_markup.h" #include "third_party/blink/renderer/core/css/style_sheet_contents.h" @@ -42,7 +43,6 @@ #include "third_party/blink/renderer/platform/loader/fetch/resource_fetcher.h" #include "third_party/blink/renderer/platform/loader/fetch/resource_loader_options.h" #include "third_party/blink/renderer/platform/runtime_enabled_features.h" -#include "third_party/blink/renderer/platform/weborigin/security_policy.h" #include "third_party/blink/renderer/platform/wtf/text/string_builder.h" namespace blink { @@ -86,7 +86,8 @@ if (!fetched_ || fetched_->GetResource()->Options().world != world_) { ResourceRequest resource_request(absolute_resource_); resource_request.SetReferrerPolicy( - ReferrerPolicyResolveDefault(referrer_.referrer_policy)); + ReferrerUtils::MojoReferrerPolicyResolveDefault( + referrer_.referrer_policy)); resource_request.SetReferrerString(referrer_.referrer); if (is_ad_related_) resource_request.SetIsAdResource();
diff --git a/third_party/blink/renderer/core/css/css_image_set_value.cc b/third_party/blink/renderer/core/css/css_image_set_value.cc index ecb6b77..89ac0c7 100644 --- a/third_party/blink/renderer/core/css/css_image_set_value.cc +++ b/third_party/blink/renderer/core/css/css_image_set_value.cc
@@ -26,6 +26,7 @@ #include "third_party/blink/renderer/core/css/css_image_set_value.h" #include <algorithm> +#include "third_party/blink/public/common/loader/referrer_utils.h" #include "third_party/blink/renderer/core/css/css_image_value.h" #include "third_party/blink/renderer/core/css/css_primitive_value.h" #include "third_party/blink/renderer/core/dom/document.h" @@ -38,7 +39,6 @@ #include "third_party/blink/renderer/platform/loader/fetch/resource_fetcher.h" #include "third_party/blink/renderer/platform/loader/fetch/resource_loader_options.h" #include "third_party/blink/renderer/platform/weborigin/kurl.h" -#include "third_party/blink/renderer/platform/weborigin/security_policy.h" #include "third_party/blink/renderer/platform/wtf/text/string_builder.h" namespace blink { @@ -121,7 +121,8 @@ ImageWithScale image = BestImageForScaleFactor(device_scale_factor); ResourceRequest resource_request(document.CompleteURL(image.image_url)); resource_request.SetReferrerPolicy( - ReferrerPolicyResolveDefault(image.referrer.referrer_policy)); + ReferrerUtils::MojoReferrerPolicyResolveDefault( + image.referrer.referrer_policy)); resource_request.SetReferrerString(image.referrer.referrer); if (is_ad_related_) resource_request.SetIsAdResource();
diff --git a/third_party/blink/renderer/core/css/css_image_value.cc b/third_party/blink/renderer/core/css/css_image_value.cc index 3b1a4341..21fc710 100644 --- a/third_party/blink/renderer/core/css/css_image_value.cc +++ b/third_party/blink/renderer/core/css/css_image_value.cc
@@ -21,6 +21,7 @@ #include "third_party/blink/renderer/core/css/css_image_value.h" #include "third_party/blink/public/common/features.h" +#include "third_party/blink/public/common/loader/referrer_utils.h" #include "third_party/blink/public/web/web_local_frame_client.h" #include "third_party/blink/renderer/core/css/css_markup.h" #include "third_party/blink/renderer/core/dom/document.h" @@ -35,7 +36,6 @@ #include "third_party/blink/renderer/platform/loader/fetch/resource_loader_options.h" #include "third_party/blink/renderer/platform/network/network_state_notifier.h" #include "third_party/blink/renderer/platform/weborigin/kurl.h" -#include "third_party/blink/renderer/platform/weborigin/security_policy.h" namespace blink { @@ -64,7 +64,8 @@ ReResolveURL(document); ResourceRequest resource_request(absolute_url_); resource_request.SetReferrerPolicy( - ReferrerPolicyResolveDefault(referrer_.referrer_policy)); + ReferrerUtils::MojoReferrerPolicyResolveDefault( + referrer_.referrer_policy)); resource_request.SetReferrerString(referrer_.referrer); if (is_ad_related_) resource_request.SetIsAdResource();
diff --git a/third_party/blink/renderer/core/css/css_style_declaration.cc b/third_party/blink/renderer/core/css/css_style_declaration.cc index 583eec4..4d7b07c 100644 --- a/third_party/blink/renderer/core/css/css_style_declaration.cc +++ b/third_party/blink/renderer/core/css/css_style_declaration.cc
@@ -196,6 +196,13 @@ return NamedPropertySetterResult::kIntercepted; } +NamedPropertyDeleterResult CSSStyleDeclaration::AnonymousNamedDeleter( + const AtomicString& name) { + // Pretend to be deleted since web author can define their own property with + // the same name. + return NamedPropertyDeleterResult::kDeleted; +} + void CSSStyleDeclaration::NamedPropertyEnumerator(Vector<String>& names, ExceptionState&) { typedef Vector<String, numCSSProperties - 1> PreAllocatedPropertyVector;
diff --git a/third_party/blink/renderer/core/css/css_style_declaration.h b/third_party/blink/renderer/core/css/css_style_declaration.h index b4a0efc..15e6c8ea 100644 --- a/third_party/blink/renderer/core/css/css_style_declaration.h +++ b/third_party/blink/renderer/core/css/css_style_declaration.h
@@ -102,6 +102,7 @@ NamedPropertySetterResult AnonymousNamedSetter(ScriptState*, const AtomicString& name, const String& value); + NamedPropertyDeleterResult AnonymousNamedDeleter(const AtomicString& name); void NamedPropertyEnumerator(Vector<String>& names, ExceptionState&); bool NamedPropertyQuery(const AtomicString&, ExceptionState&);
diff --git a/third_party/blink/renderer/core/css/css_style_declaration.idl b/third_party/blink/renderer/core/css/css_style_declaration.idl index 934c1c9..ae168e9 100644 --- a/third_party/blink/renderer/core/css/css_style_declaration.idl +++ b/third_party/blink/renderer/core/css/css_style_declaration.idl
@@ -40,4 +40,5 @@ // https://drafts.csswg.org/cssom/#dom-cssstyledeclaration-dashed-attribute [Affects=Nothing] getter DOMString (DOMString name); [CEReactions, CallWith=ScriptState] setter void (DOMString property, [TreatNullAs=EmptyString] DOMString propertyValue); + deleter void (DOMString property); };
diff --git a/third_party/blink/renderer/core/dom/attribute.h b/third_party/blink/renderer/core/dom/attribute.h index 3db098e..1869c50 100644 --- a/third_party/blink/renderer/core/dom/attribute.h +++ b/third_party/blink/renderer/core/dom/attribute.h
@@ -39,8 +39,8 @@ DISALLOW_NEW(); public: - Attribute(const QualifiedName& name, AtomicString value) - : name_(name), value_(std::move(value)) {} + Attribute(const QualifiedName& name, const AtomicString& value) + : name_(name), value_(value) {} // NOTE: The references returned by these functions are only valid for as long // as the Attribute stays in place. For example, calling a function that @@ -56,10 +56,7 @@ bool Matches(const QualifiedName&) const; bool MatchesCaseInsensitive(const QualifiedName&) const; - void SetValue(AtomicString value) { value_ = std::move(value); } - AtomicString ExchangeValue(AtomicString value) { - return std::exchange(value_, std::move(value)); - } + void SetValue(const AtomicString& value) { value_ = value; } // Note: This API is only for HTMLTreeBuilder. It is not safe to change the // name of an attribute once parseAttribute has been called as DOM
diff --git a/third_party/blink/renderer/core/dom/attribute_collection.h b/third_party/blink/renderer/core/dom/attribute_collection.h index 30df3cc..c403f85 100644 --- a/third_party/blink/renderer/core/dom/attribute_collection.h +++ b/third_party/blink/renderer/core/dom/attribute_collection.h
@@ -160,15 +160,13 @@ attributes) {} // These functions do no error/duplicate checking. - const AtomicString& Append(const QualifiedName&, AtomicString value); + void Append(const QualifiedName&, const AtomicString& value); void Remove(unsigned index); }; -inline const AtomicString& MutableAttributeCollection::Append( - const QualifiedName& name, - AtomicString value) { - attributes_.emplace_back(name, std::move(value)); - return attributes_.back().Value(); +inline void MutableAttributeCollection::Append(const QualifiedName& name, + const AtomicString& value) { + attributes_.push_back(Attribute(name, value)); } inline void MutableAttributeCollection::Remove(unsigned index) {
diff --git a/third_party/blink/renderer/core/dom/element-hot.cc b/third_party/blink/renderer/core/dom/element-hot.cc index 87b14332..bee9f40f 100644 --- a/third_party/blink/renderer/core/dom/element-hot.cc +++ b/third_party/blink/renderer/core/dom/element-hot.cc
@@ -120,45 +120,45 @@ g_null_atom)); } -void Element::setAttribute(const QualifiedName& name, AtomicString value) { +void Element::setAttribute(const QualifiedName& name, + const AtomicString& value) { SynchronizeAttribute(name); wtf_size_t index = GetElementData() ? GetElementData()->Attributes().FindIndex(name) : kNotFound; - SetAttributeInternal(index, name, std::move(value), + SetAttributeInternal(index, name, value, kNotInSynchronizationOfLazyAttribute); } void Element::setAttribute(const QualifiedName& name, - AtomicString value, + const AtomicString& value, ExceptionState& exception_state) { SynchronizeAttribute(name); wtf_size_t index = GetElementData() ? GetElementData()->Attributes().FindIndex(name) : kNotFound; - AtomicString trusted_value(TrustedTypesCheckFor( - ExpectedTrustedTypeForAttribute(name), std::move(value), - GetExecutionContext(), exception_state)); + AtomicString trusted_value( + TrustedTypesCheckFor(ExpectedTrustedTypeForAttribute(name), value, + GetExecutionContext(), exception_state)); if (exception_state.HadException()) return; - SetAttributeInternal(index, name, std::move(trusted_value), + SetAttributeInternal(index, name, trusted_value, kNotInSynchronizationOfLazyAttribute); } void Element::SetSynchronizedLazyAttribute(const QualifiedName& name, - AtomicString value) { + const AtomicString& value) { wtf_size_t index = GetElementData() ? GetElementData()->Attributes().FindIndex(name) : kNotFound; - SetAttributeInternal(index, name, std::move(value), - kInSynchronizationOfLazyAttribute); + SetAttributeInternal(index, name, value, kInSynchronizationOfLazyAttribute); } void Element::SetAttributeHinted(const AtomicString& local_name, WTF::AtomicStringTable::WeakResult hint, - AtomicString value, + const AtomicString& value, ExceptionState& exception_state) { if (!Document::IsValidName(local_name)) { exception_state.ThrowDOMException( @@ -178,7 +178,7 @@ if (exception_state.HadException()) return; - SetAttributeInternal(index, q_name, std::move(trusted_value), + SetAttributeInternal(index, q_name, trusted_value, kNotInSynchronizationOfLazyAttribute); } @@ -204,14 +204,14 @@ GetExecutionContext(), exception_state)); if (exception_state.HadException()) return; - SetAttributeInternal(index, q_name, std::move(value), + SetAttributeInternal(index, q_name, value, kNotInSynchronizationOfLazyAttribute); } ALWAYS_INLINE void Element::SetAttributeInternal( wtf_size_t index, const QualifiedName& name, - AtomicString new_value, + const AtomicString& new_value, SynchronizationOfLazyAttribute in_synchronization_of_lazy_attribute) { if (new_value.IsNull()) { if (index != kNotFound) @@ -220,32 +220,25 @@ } if (index == kNotFound) { - AppendAttributeInternal(name, std::move(new_value), + AppendAttributeInternal(name, new_value, in_synchronization_of_lazy_attribute); return; } const Attribute& existing_attribute = GetElementData()->Attributes().at(index); + AtomicString existing_attribute_value = existing_attribute.Value(); + QualifiedName existing_attribute_name = existing_attribute.GetName(); if (!in_synchronization_of_lazy_attribute) { - WillModifyAttribute(existing_attribute.GetName(), - existing_attribute.Value(), new_value); + WillModifyAttribute(existing_attribute_name, existing_attribute_value, + new_value); } - - AtomicString old_value_storage; // Keep the old value alive in an update. - const AtomicString* old_val_ptr = &existing_attribute.Value(); - const AtomicString* new_val_ptr = &new_value; - if (new_value != *old_val_ptr) { - Attribute& attribute = EnsureUniqueElementData().Attributes().at(index); - old_value_storage = attribute.ExchangeValue(std::move(new_value)); - old_val_ptr = &old_value_storage; - new_val_ptr = &attribute.Value(); - } - + if (new_value != existing_attribute_value) + EnsureUniqueElementData().Attributes().at(index).SetValue(new_value); if (!in_synchronization_of_lazy_attribute) { - DidModifyAttribute(existing_attribute.GetName(), *old_val_ptr, - *new_val_ptr); + DidModifyAttribute(existing_attribute_name, existing_attribute_value, + new_value); } } @@ -308,7 +301,7 @@ } } - SetAttributeInternal(index, attr_node->GetQualifiedName(), std::move(value), + SetAttributeInternal(index, attr_node->GetQualifiedName(), value, kNotInSynchronizationOfLazyAttribute); attr_node->AttachToElement(this, local_name);
diff --git a/third_party/blink/renderer/core/dom/element.cc b/third_party/blink/renderer/core/dom/element.cc index 1bc3b60..dcbca6fb 100644 --- a/third_party/blink/renderer/core/dom/element.cc +++ b/third_party/blink/renderer/core/dom/element.cc
@@ -3794,7 +3794,7 @@ if (exception_state.HadException()) return; - setAttribute(parsed_name, std::move(value)); + setAttribute(parsed_name, value); } void Element::RemoveAttributeInternal( @@ -3828,14 +3828,13 @@ void Element::AppendAttributeInternal( const QualifiedName& name, - AtomicString value, + const AtomicString& value, SynchronizationOfLazyAttribute in_synchronization_of_lazy_attribute) { if (!in_synchronization_of_lazy_attribute) WillModifyAttribute(name, g_null_atom, value); - const AtomicString& stored_value = - EnsureUniqueElementData().Attributes().Append(name, std::move(value)); + EnsureUniqueElementData().Attributes().Append(name, value); if (!in_synchronization_of_lazy_attribute) - DidAddAttribute(name, stored_value); + DidAddAttribute(name, value); } void Element::removeAttributeNS(const AtomicString& namespace_uri, @@ -5545,9 +5544,9 @@ DispatchSubtreeModifiedEvent(); } -void Element::DidModifyAttribute(QualifiedName name, - AtomicString old_value, - AtomicString new_value) { +void Element::DidModifyAttribute(const QualifiedName& name, + const AtomicString& old_value, + const AtomicString& new_value) { if (name == html_names::kIdAttr) UpdateId(old_value, new_value); AttributeChanged(AttributeModificationParams(
diff --git a/third_party/blink/renderer/core/dom/element.h b/third_party/blink/renderer/core/dom/element.h index b50c9ada..7d6143be 100644 --- a/third_party/blink/renderer/core/dom/element.h +++ b/third_party/blink/renderer/core/dom/element.h
@@ -162,9 +162,12 @@ // Passing g_null_atom as the second parameter removes the attribute when // calling either of these set methods. - void setAttribute(const QualifiedName&, AtomicString value); - void setAttribute(const QualifiedName&, AtomicString value, ExceptionState&); - void SetSynchronizedLazyAttribute(const QualifiedName&, AtomicString value); + void setAttribute(const QualifiedName&, const AtomicString& value); + void setAttribute(const QualifiedName&, + const AtomicString& value, + ExceptionState&); + void SetSynchronizedLazyAttribute(const QualifiedName&, + const AtomicString& value); void removeAttribute(const QualifiedName&); @@ -230,7 +233,7 @@ void setAttribute(const AtomicString& name, AtomicString value, ExceptionState& exception_state = ASSERT_NO_EXCEPTION) { - SetAttributeHinted(name, WeakLowercaseIfNecessary(name), std::move(value), + SetAttributeHinted(name, WeakLowercaseIfNecessary(name), value, exception_state); } @@ -262,7 +265,7 @@ bool toggleAttribute(const AtomicString&, bool force, ExceptionState&); const AtomicString& GetIdAttribute() const; - void SetIdAttribute(AtomicString); + void SetIdAttribute(const AtomicString&); const AtomicString& GetNameAttribute() const; const AtomicString& GetClassAttribute() const; @@ -1078,12 +1081,9 @@ void WillModifyAttribute(const QualifiedName&, const AtomicString& old_value, const AtomicString& new_value); - // Take arguments by copy as DidModifyAttribute() may modify the - // ElementData().Attributes(). If the arguments are references to entries of - // that array, this would cause a UaF. - void DidModifyAttribute(QualifiedName, - AtomicString old_value, - AtomicString new_value); + void DidModifyAttribute(const QualifiedName&, + const AtomicString& old_value, + const AtomicString& new_value); void DidRemoveAttribute(const QualifiedName&, const AtomicString& old_value); void SynchronizeAllAttributes() const; @@ -1102,10 +1102,10 @@ void SetAttributeInternal(wtf_size_t index, const QualifiedName&, - AtomicString value, + const AtomicString& value, SynchronizationOfLazyAttribute); void AppendAttributeInternal(const QualifiedName&, - AtomicString value, + const AtomicString& value, SynchronizationOfLazyAttribute); void RemoveAttributeInternal(wtf_size_t index, SynchronizationOfLazyAttribute); @@ -1129,7 +1129,7 @@ WTF::AtomicStringTable::WeakResult hint) const; void SetAttributeHinted(const AtomicString& name, WTF::AtomicStringTable::WeakResult hint, - AtomicString value, + const AtomicString& value, ExceptionState& = ASSERT_NO_EXCEPTION); void SetAttributeHinted( const AtomicString& name, @@ -1329,8 +1329,8 @@ return FastGetAttribute(html_names::kClassAttr); } -inline void Element::SetIdAttribute(AtomicString value) { - setAttribute(html_names::kIdAttr, std::move(value)); +inline void Element::SetIdAttribute(const AtomicString& value) { + setAttribute(html_names::kIdAttr, value); } inline const SpaceSplitString& Element::ClassNames() const {
diff --git a/third_party/blink/renderer/core/editing/commands/delete_selection_options.h b/third_party/blink/renderer/core/editing/commands/delete_selection_options.h index 9237735..aa569f16 100644 --- a/third_party/blink/renderer/core/editing/commands/delete_selection_options.h +++ b/third_party/blink/renderer/core/editing/commands/delete_selection_options.h
@@ -43,6 +43,8 @@ public: Builder(); + Builder(const Builder&) = delete; + Builder& operator=(const Builder*) = delete; DeleteSelectionOptions Build() const; @@ -53,8 +55,6 @@ private: DeleteSelectionOptions options_; - - DISALLOW_COPY_AND_ASSIGN(Builder); }; } // namespace blink
diff --git a/third_party/blink/renderer/core/editing/commands/editing_state.h b/third_party/blink/renderer/core/editing/commands/editing_state.h index 2ae504f..b6df49c 100644 --- a/third_party/blink/renderer/core/editing/commands/editing_state.h +++ b/third_party/blink/renderer/core/editing/commands/editing_state.h
@@ -27,14 +27,14 @@ public: EditingState(); + EditingState(const EditingState&) = delete; + EditingState& operator=(const EditingState&) = delete; void Abort(); bool IsAborted() const { return is_aborted_; } private: bool is_aborted_ = false; - - DISALLOW_COPY_AND_ASSIGN(EditingState); }; // TODO(yosin): Once all commands aware |EditingState|, we get rid of @@ -44,14 +44,15 @@ public: IgnorableEditingAbortState(); + IgnorableEditingAbortState(const IgnorableEditingAbortState&) = delete; + IgnorableEditingAbortState& operator=(const IgnorableEditingAbortState&) = + delete; ~IgnorableEditingAbortState(); EditingState* GetEditingState() { return &editing_state_; } private: EditingState editing_state_; - - DISALLOW_COPY_AND_ASSIGN(IgnorableEditingAbortState); }; // Abort the editing command if the specified expression is true. @@ -70,6 +71,8 @@ public: NoEditingAbortChecker(const char* file, int line); + NoEditingAbortChecker(const NoEditingAbortChecker&) = delete; + NoEditingAbortChecker& operator=(const NoEditingAbortChecker&) = delete; ~NoEditingAbortChecker(); EditingState* GetEditingState() { return &editing_state_; } @@ -78,8 +81,6 @@ EditingState editing_state_; const char* const file_; int const line_; - - DISALLOW_COPY_AND_ASSIGN(NoEditingAbortChecker); }; // If a function with EditingState* argument should not be aborted,
diff --git a/third_party/blink/renderer/core/editing/commands/replace_selection_command.cc b/third_party/blink/renderer/core/editing/commands/replace_selection_command.cc index c668cc47..185e152 100644 --- a/third_party/blink/renderer/core/editing/commands/replace_selection_command.cc +++ b/third_party/blink/renderer/core/editing/commands/replace_selection_command.cc
@@ -81,6 +81,8 @@ public: ReplacementFragment(Document*, DocumentFragment*, const VisibleSelection&); + ReplacementFragment(const ReplacementFragment&) = delete; + ReplacementFragment& operator=(const ReplacementFragment&) = delete; Node* FirstChild() const; Node* LastChild() const; @@ -109,8 +111,6 @@ DocumentFragment* fragment_; bool has_interchange_newline_at_start_; bool has_interchange_newline_at_end_; - - DISALLOW_COPY_AND_ASSIGN(ReplacementFragment); }; static bool IsInterchangeHTMLBRElement(const Node* node) {
diff --git a/third_party/blink/renderer/core/editing/commands/selection_for_undo_step.h b/third_party/blink/renderer/core/editing/commands/selection_for_undo_step.h index 45e57db..aa7b148 100644 --- a/third_party/blink/renderer/core/editing/commands/selection_for_undo_step.h +++ b/third_party/blink/renderer/core/editing/commands/selection_for_undo_step.h
@@ -73,6 +73,8 @@ public: Builder(); + Builder(const Builder&) = delete; + Builder& operator=(const Builder&) = delete; const SelectionForUndoStep& Build() const { return selection_; } @@ -88,8 +90,6 @@ private: SelectionForUndoStep selection_; - - DISALLOW_COPY_AND_ASSIGN(Builder); }; VisibleSelection CreateVisibleSelection(const SelectionForUndoStep&);
diff --git a/third_party/blink/renderer/core/exported/web_frame_test.cc b/third_party/blink/renderer/core/exported/web_frame_test.cc index bfc6a50..80c4d147 100644 --- a/third_party/blink/renderer/core/exported/web_frame_test.cc +++ b/third_party/blink/renderer/core/exported/web_frame_test.cc
@@ -56,6 +56,7 @@ #include "third_party/blink/public/common/context_menu_data/edit_flags.h" #include "third_party/blink/public/common/input/web_coalesced_input_event.h" #include "third_party/blink/public/common/input/web_keyboard_event.h" +#include "third_party/blink/public/common/loader/referrer_utils.h" #include "third_party/blink/public/common/messaging/transferable_message.h" #include "third_party/blink/public/common/page/launching_process_state.h" #include "third_party/blink/public/common/widget/device_emulation_params.h" @@ -13615,7 +13616,7 @@ referrer_ = params->referrer ? params->referrer->url : KURL(); referrer_policy_ = params->referrer ? params->referrer->policy - : ReferrerPolicyResolveDefault( + : ReferrerUtils::MojoReferrerPolicyResolveDefault( network::mojom::ReferrerPolicy::kDefault); } @@ -13652,9 +13653,9 @@ frame, GetHTMLStringForReferrerPolicy(std::string(), std::string()), test_url); EXPECT_EQ(frame_host.referrer_, test_url); - EXPECT_EQ( - frame_host.referrer_policy_, - ReferrerPolicyResolveDefault(network::mojom::ReferrerPolicy::kDefault)); + EXPECT_EQ(frame_host.referrer_policy_, + ReferrerUtils::MojoReferrerPolicyResolveDefault( + network::mojom::ReferrerPolicy::kDefault)); // 4.referrerpolicy='origin' frame_test_helpers::LoadHTMLString(
diff --git a/third_party/blink/renderer/core/html/canvas/image_element_base.cc b/third_party/blink/renderer/core/html/canvas/image_element_base.cc index d0bbfde7..33a77ea 100644 --- a/third_party/blink/renderer/core/html/canvas/image_element_base.cc +++ b/third_party/blink/renderer/core/html/canvas/image_element_base.cc
@@ -144,6 +144,7 @@ "specified."); return ScriptPromise(); } + // The following function only works on SVGImages (as checked above). return ImageBitmap::CreateAsync(this, crop_rect, script_state, options); } return ImageBitmapSource::FulfillImageBitmap(
diff --git a/third_party/blink/renderer/core/imagebitmap/image_bitmap.cc b/third_party/blink/renderer/core/imagebitmap/image_bitmap.cc index 7df0af2..2779a73 100644 --- a/third_party/blink/renderer/core/imagebitmap/image_bitmap.cc +++ b/third_party/blink/renderer/core/imagebitmap/image_bitmap.cc
@@ -16,8 +16,10 @@ #include "third_party/blink/renderer/core/dom/dom_exception.h" #include "third_party/blink/renderer/core/html/canvas/html_canvas_element.h" #include "third_party/blink/renderer/core/html/canvas/image_data.h" +#include "third_party/blink/renderer/core/html/canvas/image_element_base.h" #include "third_party/blink/renderer/core/html/media/html_video_element.h" #include "third_party/blink/renderer/core/offscreencanvas/offscreen_canvas.h" +#include "third_party/blink/renderer/core/svg/graphics/svg_image_for_container.h" #include "third_party/blink/renderer/platform/bindings/enumeration_base.h" #include "third_party/blink/renderer/platform/graphics/accelerated_static_bitmap_image.h" #include "third_party/blink/renderer/platform/graphics/canvas_color_params.h" @@ -998,7 +1000,6 @@ auto* resolver = MakeGarbageCollected<ScriptPromiseResolver>(script_state); ScriptPromise promise = resolver->Promise(); - scoped_refptr<Image> input = image->CachedImage()->GetImage(); ParsedOptions parsed_options = ParseOptions(options, crop_rect, image->BitmapSourceSize()); if (DstBufferSizeHasOverflow(parsed_options)) { @@ -1008,13 +1009,14 @@ return promise; } + scoped_refptr<Image> input = image->CachedImage()->GetImage(); + DCHECK(input->IsSVGImage()); IntRect input_rect(IntPoint(), input->Size()); - const IntRect src_rect = Intersection(input_rect, parsed_options.crop_rect); // In the case when |crop_rect| doesn't intersect the source image, we return // a transparent black image, respecting the color_params but ignoring - // poremultiply_alpha. - if (src_rect.IsEmpty()) { + // premultiply_alpha. + if (!parsed_options.crop_rect.Intersects(input_rect)) { ImageBitmap* bitmap = MakeGarbageCollected<ImageBitmap>(MakeBlankImage(parsed_options)); if (bitmap->BitmapImage()) { @@ -1031,9 +1033,21 @@ IntRect draw_src_rect(parsed_options.crop_rect); IntRect draw_dst_rect(0, 0, parsed_options.resize_width, parsed_options.resize_height); - sk_sp<PaintRecord> paint_record = - input->PaintRecordForContainer(NullURL(), input->Size(), draw_src_rect, - draw_dst_rect, parsed_options.flip_y); + PaintRecorder recorder; + cc::PaintCanvas* canvas = recorder.beginRecording(draw_src_rect); + if (parsed_options.flip_y) { + canvas->translate(0, draw_dst_rect.Height()); + canvas->scale(1, -1); + } + SVGImageForContainer::Create(To<SVGImage>(input.get()), + FloatSize(input_rect.Size()), 1, NullURL()) + ->Draw(canvas, cc::PaintFlags(), FloatRect(draw_dst_rect), + FloatRect(draw_src_rect), + // The following will all be ignored. + kRespectImageOrientation, Image::kDoNotClampImageToSourceRect, + Image::kSyncDecode); + sk_sp<PaintRecord> paint_record = recorder.finishRecordingAsPicture(); + std::unique_ptr<ParsedOptions> passed_parsed_options = std::make_unique<ParsedOptions>(parsed_options); worker_pool::PostTask(
diff --git a/third_party/blink/renderer/core/imagebitmap/image_bitmap.h b/third_party/blink/renderer/core/imagebitmap/image_bitmap.h index 17428bd..e77c837 100644 --- a/third_party/blink/renderer/core/imagebitmap/image_bitmap.h +++ b/third_party/blink/renderer/core/imagebitmap/image_bitmap.h
@@ -11,12 +11,12 @@ #include "third_party/blink/renderer/bindings/core/v8/v8_image_bitmap_options.h" #include "third_party/blink/renderer/core/core_export.h" #include "third_party/blink/renderer/core/html/canvas/canvas_image_source.h" -#include "third_party/blink/renderer/core/html/canvas/image_element_base.h" #include "third_party/blink/renderer/core/imagebitmap/image_bitmap_source.h" #include "third_party/blink/renderer/platform/bindings/script_wrappable.h" #include "third_party/blink/renderer/platform/geometry/int_rect.h" #include "third_party/blink/renderer/platform/graphics/image.h" #include "third_party/blink/renderer/platform/graphics/image_orientation.h" +#include "third_party/blink/renderer/platform/graphics/paint/paint_record.h" #include "third_party/blink/renderer/platform/graphics/static_bitmap_image.h" #include "third_party/blink/renderer/platform/heap/handle.h" #include "third_party/blink/renderer/platform/wtf/functional.h" @@ -26,6 +26,7 @@ class HTMLCanvasElement; class HTMLVideoElement; class ImageData; +class ImageElementBase; class ImageDecoder; class OffscreenCanvas; @@ -40,6 +41,7 @@ DEFINE_WRAPPERTYPEINFO(); public: + // Expects the ImageElementBase to return/have an SVGImage. static ScriptPromise CreateAsync( ImageElementBase*, base::Optional<IntRect>,
diff --git a/third_party/blink/renderer/core/input/event_handler.cc b/third_party/blink/renderer/core/input/event_handler.cc index 484d423a..5c17c47 100644 --- a/third_party/blink/renderer/core/input/event_handler.cc +++ b/third_party/blink/renderer/core/input/event_handler.cc
@@ -97,6 +97,7 @@ #include "third_party/blink/renderer/core/style/computed_style.h" #include "third_party/blink/renderer/core/style/cursor_data.h" #include "third_party/blink/renderer/core/svg/graphics/svg_image.h" +#include "third_party/blink/renderer/core/svg/graphics/svg_image_for_container.h" #include "third_party/blink/renderer/platform/bindings/exception_state.h" #include "third_party/blink/renderer/platform/cursors.h" #include "third_party/blink/renderer/platform/geometry/float_point.h" @@ -622,9 +623,11 @@ // If the image is an SVG, then adjust the scale to reflect the device // scale factor so that the SVG can be rasterized in the native // resolution and scaled down to the correct size for the cursor. - if (image && image->IsSVGImage()) { - scale *= + float device_scale_factor = 1; + if (image->IsSVGImage()) { + device_scale_factor = page->GetChromeClient().GetScreenInfo(*frame_).device_scale_factor; + scale *= device_scale_factor; } // Ensure no overflow possible in calculations above. @@ -634,23 +637,21 @@ // Convert from logical pixels to physical pixels. hot_spot.Scale(scale, scale); - ui::Cursor cursor(ui::mojom::blink::CursorType::kCustom); - if (image) { - // Special case for SVG so that it can be rasterized in the appropriate - // resolution for high DPI displays. - if (image->IsSVGImage()) { - SVGImage* svg = static_cast<SVGImage*>(image); - cursor.set_custom_bitmap( - svg->AsSkBitmapForCursor(page->GetChromeClient() - .GetScreenInfo(*frame_) - .device_scale_factor)); - } else { - cursor.set_custom_bitmap( - image->AsSkBitmapForCurrentFrame(kRespectImageOrientation)); - } - } else { - cursor.set_custom_bitmap(SkBitmap()); + // Special case for SVG so that it can be rasterized in the appropriate + // resolution for high DPI displays. + scoped_refptr<Image> svg_image_holder; + if (auto* svg_image = DynamicTo<SVGImage>(image)) { + IntSize scaled_size(svg_image->Size()); + scaled_size.Scale(device_scale_factor); + // TODO(fs): Should pass proper URL. Use StyleImage::GetImage. + svg_image_holder = SVGImageForContainer::Create( + svg_image, FloatSize(scaled_size), device_scale_factor, NullURL()); + image = svg_image_holder.get(); } + + ui::Cursor cursor(ui::mojom::blink::CursorType::kCustom); + cursor.set_custom_bitmap( + image->AsSkBitmapForCurrentFrame(kRespectImageOrientation)); cursor.set_custom_hotspot( DetermineHotSpot(*image, hot_spot_specified, hot_spot)); cursor.set_image_scale_factor(scale);
diff --git a/third_party/blink/renderer/core/inspector/inspector_highlight.cc b/third_party/blink/renderer/core/inspector/inspector_highlight.cc index 94a0d1fb..01fdd3e 100644 --- a/third_party/blink/renderer/core/inspector/inspector_highlight.cc +++ b/third_party/blink/renderer/core/inspector/inspector_highlight.cc
@@ -421,6 +421,35 @@ return PhysicalOffset(offset.top, offset.left); } +size_t GetTrackCount(const LayoutGrid* layout_grid, + GridTrackSizingDirection direction) { + return direction == kForRows ? layout_grid->RowPositions().size() + : layout_grid->ColumnPositions().size(); +} + +LayoutUnit GetPositionForTrackAt(const LayoutGrid* layout_grid, + size_t index, + GridTrackSizingDirection direction) { + if (direction == kForRows) + return layout_grid->RowPositions().at(index); + + LayoutUnit position = layout_grid->ColumnPositions().at(index); + return layout_grid->StyleRef().IsLeftToRightDirection() + ? position + : layout_grid->TranslateRTLCoordinate(position); +} + +LayoutUnit GetPositionForFirstTrack(const LayoutGrid* layout_grid, + GridTrackSizingDirection direction) { + return GetPositionForTrackAt(layout_grid, 0, direction); +} + +LayoutUnit GetPositionForLastTrack(const LayoutGrid* layout_grid, + GridTrackSizingDirection direction) { + size_t index = GetTrackCount(layout_grid, direction) - 1; + return GetPositionForTrackAt(layout_grid, index, direction); +} + PhysicalOffset LocalToAbsolutePoint(Node* node, PhysicalOffset local, float scale) { @@ -451,20 +480,26 @@ const Vector<String>* authored_values) { LayoutObject* layout_object = node->GetLayoutObject(); LayoutGrid* layout_grid = ToLayoutGrid(layout_object); + bool is_rtl = direction == kForColumns && + !layout_grid->StyleRef().IsLeftToRightDirection(); + std::unique_ptr<protocol::ListValue> sizes = protocol::ListValue::create(); - const Vector<LayoutUnit>& positions = direction == kForRows - ? layout_grid->RowPositions() - : layout_grid->ColumnPositions(); - const Vector<LayoutUnit>& alt_positions = direction == kForRows - ? layout_grid->ColumnPositions() - : layout_grid->RowPositions(); - LayoutUnit alt_axis_pos = alt_positions.front(); - for (unsigned i = 1; i < positions.size(); i++) { - LayoutUnit current_position = positions.at(i); - LayoutUnit prev_position = positions.at(i - 1); - LayoutUnit gap_offset = i < positions.size() - 1 ? gap : LayoutUnit(); + size_t track_count = GetTrackCount(layout_grid, direction); + LayoutUnit alt_axis_pos = GetPositionForFirstTrack( + layout_grid, direction == kForRows ? kForColumns : kForRows); + + for (size_t i = 1; i < track_count; i++) { + LayoutUnit current_position = + GetPositionForTrackAt(layout_grid, i, direction); + LayoutUnit prev_position = + GetPositionForTrackAt(layout_grid, i - 1, direction); + LayoutUnit gap_offset = i < track_count - 1 ? gap : LayoutUnit(); LayoutUnit width = current_position - prev_position - gap_offset; + if (is_rtl) + width = prev_position - current_position - gap_offset; LayoutUnit main_axis_pos = prev_position + width / 2; + if (is_rtl) + main_axis_pos = prev_position - width / 2; auto adjusted_size = AdjustForAbsoluteZoom::AdjustFloat( width * scale, layout_grid->StyleRef()); PhysicalOffset track_size_pos(main_axis_pos, alt_axis_pos); @@ -484,20 +519,20 @@ std::unique_ptr<protocol::ListValue> BuildGridPositiveLineNumberPositions( Node* node, - const Vector<LayoutUnit>& track_positions, const LayoutUnit& grid_gap, GridTrackSizingDirection direction, float scale) { LayoutObject* layout_object = node->GetLayoutObject(); LayoutGrid* layout_grid = ToLayoutGrid(layout_object); + bool is_rtl = direction == kForColumns && + !layout_grid->StyleRef().IsLeftToRightDirection(); std::unique_ptr<protocol::ListValue> number_positions = protocol::ListValue::create(); - const Vector<LayoutUnit>& alt_positions = direction == kForRows - ? layout_grid->ColumnPositions() - : layout_grid->RowPositions(); - LayoutUnit alt_axis_pos = alt_positions.front(); + size_t track_count = GetTrackCount(layout_grid, direction); + LayoutUnit alt_axis_pos = GetPositionForFirstTrack( + layout_grid, direction == kForRows ? kForColumns : kForRows); // Find index of the first explicit Grid Line. size_t first_explicit_index = @@ -505,15 +540,17 @@ // Go line by line, calculating the offset to fall in the middle of gaps // if needed. - for (size_t i = first_explicit_index; i < track_positions.size(); ++i) { + for (size_t i = first_explicit_index; i < track_count; ++i) { LayoutUnit gapOffset = grid_gap / 2; + if (is_rtl) + gapOffset *= -1; // No need for a gap offset if there is no gap, or the first line is // explicit, or this is the last line. - if (grid_gap == 0 || i == 0 || i == track_positions.size() - 1) { + if (grid_gap == 0 || i == 0 || i == track_count - 1) { gapOffset = LayoutUnit(); } - PhysicalOffset number_position(track_positions.at(i) - gapOffset, - alt_axis_pos); + LayoutUnit offset = GetPositionForTrackAt(layout_grid, i, direction); + PhysicalOffset number_position(offset - gapOffset, alt_axis_pos); if (direction == kForRows) number_position = Transpose(number_position); number_positions->pushValue( @@ -525,27 +562,27 @@ std::unique_ptr<protocol::ListValue> BuildGridNegativeLineNumberPositions( Node* node, - const Vector<LayoutUnit>& trackPositions, const LayoutUnit& grid_gap, GridTrackSizingDirection direction, float scale) { LayoutObject* layout_object = node->GetLayoutObject(); LayoutGrid* layout_grid = ToLayoutGrid(layout_object); + bool is_rtl = direction == kForColumns && + !layout_grid->StyleRef().IsLeftToRightDirection(); std::unique_ptr<protocol::ListValue> number_positions = protocol::ListValue::create(); - const Vector<LayoutUnit>& alt_positions = direction == kForRows - ? layout_grid->ColumnPositions() - : layout_grid->RowPositions(); - LayoutUnit alt_axis_pos = alt_positions.back(); + size_t track_count = GetTrackCount(layout_grid, direction); + LayoutUnit alt_axis_pos = GetPositionForLastTrack( + layout_grid, direction == kForRows ? kForColumns : kForRows); // This is the number of tracks from the start of the grid, to the end of the // explicit grid (including any leading implicit tracks). size_t explicit_grid_end_track_count = layout_grid->ExplicitGridEndForDirection(direction); - LayoutUnit first_offset = trackPositions.front(); + LayoutUnit first_offset = GetPositionForFirstTrack(layout_grid, direction); // Always start negative numbers at the first line. std::unique_ptr<protocol::DictionaryValue> pos = @@ -560,12 +597,14 @@ // if needed. for (size_t i = 1; i <= explicit_grid_end_track_count; i++) { LayoutUnit gapOffset = grid_gap / 2; - if (grid_gap == 0 || (i == explicit_grid_end_track_count && - i == trackPositions.size() - 1)) { + if (is_rtl) + gapOffset *= -1; + if (grid_gap == 0 || + (i == explicit_grid_end_track_count && i == track_count - 1)) { gapOffset = LayoutUnit(); } - PhysicalOffset number_position(trackPositions.at(i) - gapOffset, - alt_axis_pos); + LayoutUnit offset = GetPositionForTrackAt(layout_grid, i, direction); + PhysicalOffset number_position(offset - gapOffset, alt_axis_pos); if (direction == kForRows) number_position = Transpose(number_position); number_positions->pushValue( @@ -580,6 +619,7 @@ LayoutObject* layout_object = node->GetLayoutObject(); LayoutGrid* layout_grid = ToLayoutGrid(layout_object); LocalFrameView* containing_view = node->GetDocument().View(); + bool is_rtl = !layout_grid->StyleRef().IsLeftToRightDirection(); std::unique_ptr<protocol::DictionaryValue> area_paths = protocol::DictionaryValue::create(); @@ -594,10 +634,14 @@ const GridArea& area = item.value; const String& name = item.key; - LayoutUnit start_column = columns.at(area.columns.StartLine()); - LayoutUnit end_column = columns.at(area.columns.EndLine()); - LayoutUnit start_row = rows.at(area.rows.StartLine()); - LayoutUnit end_row = rows.at(area.rows.EndLine()); + LayoutUnit start_column = GetPositionForTrackAt( + layout_grid, area.columns.StartLine(), kForColumns); + LayoutUnit end_column = + GetPositionForTrackAt(layout_grid, area.columns.EndLine(), kForColumns); + LayoutUnit start_row = + GetPositionForTrackAt(layout_grid, area.rows.StartLine(), kForRows); + LayoutUnit end_row = + GetPositionForTrackAt(layout_grid, area.rows.EndLine(), kForRows); // Only subtract the gap size if the end line isn't the last line in the // container. @@ -606,6 +650,8 @@ LayoutUnit column_gap_offset = area.columns.EndLine() == columns.size() - 1 ? LayoutUnit() : column_gap; + if (is_rtl) + column_gap_offset *= -1; PhysicalOffset position(start_column, start_row); PhysicalSize size(end_column - start_column - column_gap_offset, @@ -628,6 +674,8 @@ float scale) { LayoutObject* layout_object = node->GetLayoutObject(); LayoutGrid* layout_grid = ToLayoutGrid(layout_object); + bool is_rtl = direction == kForColumns && + !layout_grid->StyleRef().IsLeftToRightDirection(); std::unique_ptr<protocol::ListValue> lines = protocol::ListValue::create(); @@ -638,19 +686,19 @@ direction == kForColumns ? layout_grid->StyleRef().NamedGridColumnLines() : layout_grid->StyleRef().NamedGridRowLines(); LayoutUnit gap = layout_grid->GridGap(direction); - const Vector<LayoutUnit>& alt_positions = direction == kForRows - ? layout_grid->ColumnPositions() - : layout_grid->RowPositions(); - LayoutUnit alt_axis_pos = alt_positions.front(); + LayoutUnit alt_axis_pos = GetPositionForFirstTrack( + layout_grid, direction == kForRows ? kForColumns : kForRows); for (const auto& item : named_lines_map) { const String& name = item.key; for (const size_t index : item.value) { - LayoutUnit track = tracks.at(index); + LayoutUnit track = GetPositionForTrackAt(layout_grid, index, direction); LayoutUnit gap_offset = index > 0 && index < tracks.size() - 1 ? gap / 2 : LayoutUnit(); + if (is_rtl) + gap_offset *= -1; LayoutUnit main_axis_pos = track - gap_offset; PhysicalOffset line_name_pos(main_axis_pos, alt_axis_pos); @@ -753,13 +801,6 @@ return result; } -LayoutUnit GetColumnPosition(const LayoutGrid* layout_grid, size_t index) { - LayoutUnit position = layout_grid->ColumnPositions().at(index); - return layout_grid->StyleRef().IsLeftToRightDirection() - ? position - : layout_grid->TranslateRTLCoordinate(position); -} - std::unique_ptr<protocol::DictionaryValue> BuildGridInfo( Node* node, const InspectorGridHighlightConfig& grid_highlight_config, @@ -850,8 +891,9 @@ if (i != columns.size() - 1) size.width -= column_gap; LayoutUnit line_left = - is_ltr ? GetColumnPosition(layout_grid, i - 1) - : GetColumnPosition(layout_grid, i - 1) - size.width; + GetPositionForTrackAt(layout_grid, i - 1, kForColumns); + if (!is_ltr) + line_left -= size.width; PhysicalOffset position(line_left, column_top); PhysicalRect column(position, size); FloatQuad column_quad = layout_grid->LocalRectToAbsoluteQuad(column); @@ -861,9 +903,9 @@ ColumnQuadToPath(column_quad, draw_end_line || column_gap > 0), scale); // Column Gaps if (i != columns.size() - 1) { - LayoutUnit gap_left = is_ltr - ? GetColumnPosition(layout_grid, i) - column_gap - : GetColumnPosition(layout_grid, i); + LayoutUnit gap_left = GetPositionForTrackAt(layout_grid, i, kForColumns); + if (is_ltr) + gap_left -= column_gap; PhysicalOffset gap_position(gap_left, column_top); PhysicalSize gap_size(column_gap, column_height); PhysicalRect gap(gap_position, gap_size); @@ -877,22 +919,22 @@ // Positive Row and column Line positions if (grid_highlight_config.show_positive_line_numbers) { - grid_info->setValue("positiveRowLineNumberPositions", - BuildGridPositiveLineNumberPositions( - node, rows, row_gap, kForRows, scale)); + grid_info->setValue( + "positiveRowLineNumberPositions", + BuildGridPositiveLineNumberPositions(node, row_gap, kForRows, scale)); grid_info->setValue("positiveColumnLineNumberPositions", BuildGridPositiveLineNumberPositions( - node, columns, column_gap, kForColumns, scale)); + node, column_gap, kForColumns, scale)); } // Negative Row and column Line positions if (grid_highlight_config.show_negative_line_numbers) { - grid_info->setValue("negativeRowLineNumberPositions", - BuildGridNegativeLineNumberPositions( - node, rows, row_gap, kForRows, scale)); + grid_info->setValue( + "negativeRowLineNumberPositions", + BuildGridNegativeLineNumberPositions(node, row_gap, kForRows, scale)); grid_info->setValue("negativeColumnLineNumberPositions", BuildGridNegativeLineNumberPositions( - node, columns, column_gap, kForColumns, scale)); + node, column_gap, kForColumns, scale)); } // Area names
diff --git a/third_party/blink/renderer/core/inspector/inspector_network_agent.cc b/third_party/blink/renderer/core/inspector/inspector_network_agent.cc index 739ea97..87fa475 100644 --- a/third_party/blink/renderer/core/inspector/inspector_network_agent.cc +++ b/third_party/blink/renderer/core/inspector/inspector_network_agent.cc
@@ -40,6 +40,7 @@ #include "net/http/http_status_code.h" #include "services/network/public/mojom/referrer_policy.mojom-blink.h" #include "services/network/public/mojom/websocket.mojom-blink.h" +#include "third_party/blink/public/common/loader/referrer_utils.h" #include "third_party/blink/public/mojom/loader/request_context_frame_type.mojom-blink.h" #include "third_party/blink/public/platform/task_type.h" #include "third_party/blink/public/platform/web_effective_connection_type.h" @@ -80,7 +81,6 @@ #include "third_party/blink/renderer/platform/loader/fetch/unique_identifier.h" #include "third_party/blink/renderer/platform/network/http_header_map.h" #include "third_party/blink/renderer/platform/network/network_state_notifier.h" -#include "third_party/blink/renderer/platform/runtime_enabled_features.h" #include "third_party/blink/renderer/platform/scheduler/public/post_cross_thread_task.h" #include "third_party/blink/renderer/platform/scheduler/public/thread_scheduler.h" #include "third_party/blink/renderer/platform/weborigin/kurl.h" @@ -426,7 +426,7 @@ case network::mojom::ReferrerPolicy::kAlways: return protocol::Network::Request::ReferrerPolicyEnum::UnsafeUrl; case network::mojom::ReferrerPolicy::kDefault: - if (RuntimeEnabledFeatures::ReducedReferrerGranularityEnabled()) { + if (ReferrerUtils::IsReducedReferrerGranularityEnabled()) { return protocol::Network::Request::ReferrerPolicyEnum:: StrictOriginWhenCrossOrigin; } else {
diff --git a/third_party/blink/renderer/core/layout/layout_box.cc b/third_party/blink/renderer/core/layout/layout_box.cc index 05d5096..0eee71f 100644 --- a/third_party/blink/renderer/core/layout/layout_box.cc +++ b/third_party/blink/renderer/core/layout/layout_box.cc
@@ -2784,6 +2784,17 @@ if (early_break) return nullptr; + // We'll never re-use the layout result of a fieldset contents wrapper. If the + // current rendered legend ceased to be one, and any next legend child became + // the rendered legend instead, we need to lay out the fieldset contents + // wrapper, to get rid of the fragment for the former regular block child + // legend (now rendered legend). When this happens, the contents wrapper won't + // necessarily be marked for layout, since we don't detect that anything in + // there has changed (and detecting that would be more expensive). So just + // refuse to hit the cache, so that we force re-layout. + if (UNLIKELY(IsAnonymous() && Parent()->IsLayoutNGFieldset())) + return nullptr; + DCHECK_EQ(cached_layout_result->Status(), NGLayoutResult::kSuccess); // Set our initial temporary cache status to "hit".
diff --git a/third_party/blink/renderer/core/layout/ng/inline/ng_inline_node.cc b/third_party/blink/renderer/core/layout/ng/inline/ng_inline_node.cc index 459284b..3497726d 100644 --- a/third_party/blink/renderer/core/layout/ng/inline/ng_inline_node.cc +++ b/third_party/blink/renderer/core/layout/ng/inline/ng_inline_node.cc
@@ -715,26 +715,26 @@ item->shape_result_->CopyAdjustedOffset(item->start_offset_); } + // TODO(yosin): Once we can reproduce invalid |ShapeResult| offsets, we + // should make this function works only for |DCHECK_IS_ON()|. void VerifyItems(const Vector<NGInlineItem>& items) const { -#if DCHECK_IS_ON() unsigned last_offset = items.front().start_offset_; for (const NGInlineItem& item : items) { - DCHECK_LE(item.start_offset_, item.end_offset_); - DCHECK_EQ(last_offset, item.start_offset_); + CHECK_LE(item.start_offset_, item.end_offset_); + CHECK_EQ(last_offset, item.start_offset_); last_offset = item.end_offset_; if (!item.shape_result_ || item.layout_object_ != layout_text_) continue; - DCHECK_LT(item.start_offset_, item.end_offset_); + CHECK_LT(item.start_offset_, item.end_offset_); if (item.shape_result_->StartIndex() == item.start_offset_) { - DCHECK_LE(item.shape_result_->EndIndex(), item.end_offset_); + CHECK_LE(item.shape_result_->EndIndex(), item.end_offset_); } else { - DCHECK_LE(item.start_offset_, item.shape_result_->StartIndex()); - DCHECK_EQ(item.end_offset_, item.shape_result_->EndIndex()); + CHECK_LE(item.start_offset_, item.shape_result_->StartIndex()); + CHECK_EQ(item.end_offset_, item.shape_result_->EndIndex()); } } - DCHECK_EQ(last_offset, - block_flow_->GetNGInlineNodeData()->text_content.length()); -#endif + CHECK_EQ(last_offset, + block_flow_->GetNGInlineNodeData()->text_content.length()); } std::unique_ptr<NGInlineNodeData> data_;
diff --git a/third_party/blink/renderer/core/layout/ng/ng_column_layout_algorithm_test.cc b/third_party/blink/renderer/core/layout/ng/ng_column_layout_algorithm_test.cc index abc909a..53a15e8 100644 --- a/third_party/blink/renderer/core/layout/ng/ng_column_layout_algorithm_test.cc +++ b/third_party/blink/renderer/core/layout/ng/ng_column_layout_algorithm_test.cc
@@ -2081,8 +2081,6 @@ </div> )HTML"); - // TODO(bebeaudr): The OOF positioned element should start in the second - // column rather than the first. String dump = DumpFragmentTree(GetElementById("container")); String expectation = R"DUMP(.:: LayoutNG Physical Fragment Tree ::. offset:unplaced size:1000x70 @@ -2091,12 +2089,13 @@ offset:0,0 size:100x70 offset:0,0 size:0x20 offset:0,20 size:0x20 - offset:0,40 size:33x30 offset:110,0 size:100x70 offset:0,0 size:100x60 offset:0,0 size:0x20 offset:0,20 size:0x20 offset:0,40 size:0x20 + offset:0,40 size:33x30 + offset:220,0 size:100x70 offset:0,0 size:33x3 )DUMP"; EXPECT_EQ(expectation, dump);
diff --git a/third_party/blink/renderer/core/layout/ng/ng_container_fragment_builder.cc b/third_party/blink/renderer/core/layout/ng/ng_container_fragment_builder.cc index 373f768..c04c43d 100644 --- a/third_party/blink/renderer/core/layout/ng/ng_container_fragment_builder.cc +++ b/third_party/blink/renderer/core/layout/ng/ng_container_fragment_builder.cc
@@ -76,15 +76,19 @@ LogicalOffset containing_block_offset = descendant.containing_block_offset.ConvertToLogical( GetWritingMode(), Direction(), child.Size(), PhysicalSize()); - containing_block_offset += child_offset; + if (!child.IsFragmentainerBox()) + containing_block_offset.block_offset += child_offset.block_offset; NGLogicalStaticPosition static_position = descendant.static_position.ConvertToLogical( GetWritingMode(), Direction(), PhysicalSize()); oof_positioned_fragmentainer_descendants_.emplace_back( descendant.node, static_position, descendant.inline_container, - /* needs_block_offset_adjustment */ false, containing_block_offset, - containing_block_fragment); + /* needs_block_offset_adjustment */ false, + IsBlockFragmentationContextRoot() + ? fragmentainer_consumed_block_size_ + : LayoutUnit(), + containing_block_offset, containing_block_fragment); } } } @@ -156,6 +160,15 @@ } } } + + // Always store the consumed block size of the previous fragmentainer so the + // out-of-flow positioned-nodes in the next fragmentainers can use it to + // compute its start position. + if (child.BreakToken() && child.IsFragmentainerBox()) { + DCHECK(IsA<NGBlockBreakToken>(child.BreakToken())); + fragmentainer_consumed_block_size_ = + To<NGBlockBreakToken>(child.BreakToken())->ConsumedBlockSize(); + } } void NGContainerFragmentBuilder::AddChildInternal(
diff --git a/third_party/blink/renderer/core/layout/ng/ng_container_fragment_builder.h b/third_party/blink/renderer/core/layout/ng/ng_container_fragment_builder.h index 13b29aa..80ed156 100644 --- a/third_party/blink/renderer/core/layout/ng/ng_container_fragment_builder.h +++ b/third_party/blink/renderer/core/layout/ng/ng_container_fragment_builder.h
@@ -250,6 +250,10 @@ // See NGLayoutResult::BlockEndAnotationSpace(). LayoutUnit block_end_annotation_space_; + // The block size consumed by all preceding fragmentainers. Used to position + // OOF nodes. + LayoutUnit fragmentainer_consumed_block_size_; + NGAdjoiningObjectTypes adjoining_object_types_ = kAdjoiningNone; bool has_adjoining_object_descendants_ = false;
diff --git a/third_party/blink/renderer/core/layout/ng/ng_out_of_flow_layout_part.cc b/third_party/blink/renderer/core/layout/ng/ng_out_of_flow_layout_part.cc index 85326ca8..b29ab3e 100644 --- a/third_party/blink/renderer/core/layout/ng/ng_out_of_flow_layout_part.cc +++ b/third_party/blink/renderer/core/layout/ng/ng_out_of_flow_layout_part.cc
@@ -318,9 +318,11 @@ LogicalSize content_size = ShrinkLogicalSize(size, border); LogicalOffset container_offset = LogicalOffset(border.inline_start, border.block_start); + container_offset += candidate.containing_block_offset; - ContainingBlockInfo containing_block_info{style.Direction(), content_size, - content_size, container_offset}; + ContainingBlockInfo containing_block_info{ + style.Direction(), content_size, content_size, container_offset, + candidate.fragmentainer_consumed_block_size}; return containing_blocks_map_ .insert(containing_block, containing_block_info) @@ -654,9 +656,12 @@ // Adjust the |static_position| (which is currently relative to the default // container's border-box). ng_absolute_utils expects the static position to - // be relative to the container's padding-box. + // be relative to the container's padding-box. Since + // |container_info.container_offset| is relative to its fragmentainer in this + // case, we also need to adjust the offset to account for this. NGLogicalStaticPosition static_position = descendant.static_position; - static_position.offset -= container_info.container_offset; + static_position.offset -= + container_info.container_offset - descendant.containing_block_offset; NGLogicalStaticPosition descendant_static_position = static_position @@ -674,28 +679,10 @@ builder.SetPercentageResolutionSize(container_content_size); NGConstraintSpace descendant_constraint_space = builder.ToConstraintSpace(); - // TODO(almaher): The index should be based on the fragmentainer that we will - // start layout in (skipping any column spanner fragments) rather than 0 every - // time. - wtf_size_t fragmentainer_index = 0; - const NGBlockBreakToken* break_token = nullptr; - do { - if (break_token) - fragmentainer_index++; - - const NGConstraintSpace& fragmentainer_constraint_space = - GetFragmentainerConstraintSpace(fragmentainer_index); - scoped_refptr<const NGLayoutResult> result = - Layout(node, descendant_constraint_space, descendant_static_position, - container_content_size, container_info, default_writing_mode, - default_direction, nullptr, break_token, - &fragmentainer_constraint_space); - AddOOFResultToFragmentainerResults(result, fragmentainer_index); - - const auto& physical_fragment = - To<NGPhysicalBoxFragment>(result->PhysicalFragment()); - break_token = To<NGBlockBreakToken>(physical_fragment.BreakToken()); - } while (break_token); + Layout(node, descendant_constraint_space, descendant_static_position, + container_content_size, container_info, default_writing_mode, + default_direction, /* only_layout */ nullptr, + /* is_fragmentainer_descendant */ true); } scoped_refptr<const NGLayoutResult> NGOutOfFlowLayoutPart::Layout( @@ -707,8 +694,7 @@ const WritingMode default_writing_mode, const TextDirection default_direction, const LayoutBox* only_layout, - const NGBlockBreakToken* break_token, - const NGConstraintSpace* fragmentainer_constraint_space) { + bool is_fragmentainer_descendant) { const ComputedStyle& candidate_style = node.Style(); const WritingMode candidate_writing_mode = candidate_style.GetWritingMode(); const TextDirection candidate_direction = candidate_style.Direction(); @@ -824,7 +810,8 @@ DCHECK(!has_computed_block_dimensions); layout_result = GenerateFragment( node, container_content_size_in_candidate_writing_mode, block_estimate, - node_dimensions, /* block_offset */ LayoutUnit(), break_token, + node_dimensions, /* block_offset */ LayoutUnit(), + /* break_token */ nullptr, /* fragmentainer_constraint_space */ nullptr); // TODO(layout-dev): Handle abortions caused by block fragmentation. @@ -836,13 +823,14 @@ block_estimate = fragment.BlockSize(); } - // We may have already pre-computed our block-dimensions when determining our - // |min_max_sizes|, only run if needed. + // We may have already pre-computed our block-dimensions when determining + // our |min_max_sizes|, only run if needed. if (!has_computed_block_dimensions) { ComputeOutOfFlowBlockDimensions( candidate_constraint_space, candidate_style, border_padding, candidate_static_position, block_estimate, replaced_size, default_writing_mode, container_direction, &node_dimensions); + has_computed_block_dimensions = true; } // Calculate the offsets. @@ -857,19 +845,27 @@ offset.inline_offset += inset.inline_start; offset.block_offset += inset.block_start; + // Determine in which fragmentainer this OOF element will start its layout and + // adjust the offset to be relative to that fragmentainer. + wtf_size_t start_index = 0; + if (is_fragmentainer_descendant) { + DCHECK_GT(container_builder_->Children().size(), 0u); + ComputeStartFragmentIndexAndRelativeOffset( + container_info, default_writing_mode, &start_index, &offset); + } + if (!only_layout) { // Special case: oof css container is a split inline. // When css container spans multiple anonymous blocks, its dimensions can // only be computed by a block that is an ancestor of all fragments - // generated by css container. That block is parent of anonymous containing - // block. - // That is why instead of OOF being placed by its anonymous container, - // they get placed by anonymous container's parent. + // generated by css container. That block is parent of anonymous + // containing block. That is why instead of OOF being placed by its + // anonymous container, they get placed by anonymous container's parent. // This is different from all other OOF blocks, and requires special // handling in several places in the OOF code. // There is an exception to special case: if anonymous block is Legacy, we - // cannot do the fancy multiple anonymous block traversal, and we handle it - // like regular blocks. + // cannot do the fancy multiple anonymous block traversal, and we handle + // it like regular blocks. // // Detailed example: // @@ -907,40 +903,55 @@ } } - if (break_token) - offset.block_offset = LayoutUnit(); + const NGBlockBreakToken* break_token = nullptr; + do { + if (break_token) { + layout_result = nullptr; + // TODO(almaher): You might want to skip spanning fragments here. + start_index++; + offset.block_offset = LayoutUnit(); + } - // We have calculated the offsets, and if we need to lay out, we can do so at - // the correct block-start offset now. + // Skip this step if we produced a fragment when estimating the + // block-size. + if (!layout_result) { + block_estimate = node_dimensions.size.block_size; + const NGConstraintSpace* fragmentainer_constraint_space = + is_fragmentainer_descendant + ? &GetFragmentainerConstraintSpace(start_index) + : nullptr; + layout_result = GenerateFragment( + node, container_content_size_in_candidate_writing_mode, + block_estimate, node_dimensions, offset.block_offset, break_token, + fragmentainer_constraint_space); + } - // TODO(mstensho): Actually pass the block-start offset to layout. + // TODO(layout-dev): Handle abortions caused by block fragmentation. + DCHECK_EQ(layout_result->Status(), NGLayoutResult::kSuccess); - // Skip this step if we produced a fragment when estimating the block-size. - if (!layout_result) { - block_estimate = node_dimensions.size.block_size; - layout_result = - GenerateFragment(node, container_content_size_in_candidate_writing_mode, - block_estimate, node_dimensions, offset.block_offset, - break_token, fragmentainer_constraint_space); - } + if (node.GetLayoutBox()->IsLayoutNGObject()) { + To<LayoutBlock>(node.GetLayoutBox()) + ->SetIsLegacyInitiatedOutOfFlowLayout(false); + } + // Legacy grid and flexbox handle OOF-positioned margins on their own, and + // break if we set them here. + if (!container_builder_->GetLayoutObject() + ->Style() + ->IsDisplayFlexibleOrGridBox()) { + node.GetLayoutBox()->SetMargin(node_dimensions.margins.ConvertToPhysical( + candidate_writing_mode, candidate_direction)); + } - // TODO(layout-dev): Handle abortions caused by block fragmentation. - DCHECK_EQ(layout_result->Status(), NGLayoutResult::kSuccess); + layout_result->GetMutableForOutOfFlow().SetOutOfFlowPositionedOffset( + offset, allow_first_tier_oof_cache_); + if (is_fragmentainer_descendant) { + AddOOFResultToFragmentainerResults(layout_result, start_index); - // TODO(mstensho): Move the rest of this method back into LayoutCandidate(). - - if (node.GetLayoutBox()->IsLayoutNGObject()) { - To<LayoutBlock>(node.GetLayoutBox()) - ->SetIsLegacyInitiatedOutOfFlowLayout(false); - } - // Legacy grid and flexbox handle OOF-positioned margins on their own, and - // break if we set them here. - if (!container_builder_->GetLayoutObject() - ->Style() - ->IsDisplayFlexibleOrGridBox()) { - node.GetLayoutBox()->SetMargin(node_dimensions.margins.ConvertToPhysical( - candidate_writing_mode, candidate_direction)); - } + const auto& physical_fragment = + To<NGPhysicalBoxFragment>(layout_result->PhysicalFragment()); + break_token = To<NGBlockBreakToken>(physical_fragment.BreakToken()); + } + } while (break_token); // Adjusting the offset for a dialog after layout is fine, since we cannot // have dialogs needing alignment inside block fragmentation. @@ -952,10 +963,10 @@ offset.block_offset = *y; else offset.inline_offset = *y; - } - layout_result->GetMutableForOutOfFlow().SetOutOfFlowPositionedOffset( - offset, allow_first_tier_oof_cache_); + layout_result->GetMutableForOutOfFlow().SetOutOfFlowPositionedOffset( + offset, allow_first_tier_oof_cache_); + } return layout_result; } @@ -1023,7 +1034,7 @@ void NGOutOfFlowLayoutPart::AddOOFResultsToFragmentainer( const Vector<scoped_refptr<const NGLayoutResult>>& results, - const wtf_size_t index) { + wtf_size_t index) { wtf_size_t num_children = container_builder_->Children().size(); bool is_new_fragment = index >= num_children; @@ -1091,7 +1102,7 @@ } const NGConstraintSpace& NGOutOfFlowLayoutPart::GetFragmentainerConstraintSpace( - const wtf_size_t index) { + wtf_size_t index) { // Increase the index by 1 to avoid a key of 0. wtf_size_t stored_index = index + 1; @@ -1129,7 +1140,7 @@ void NGOutOfFlowLayoutPart::AddOOFResultToFragmentainerResults( const scoped_refptr<const NGLayoutResult> result, - const wtf_size_t index) { + wtf_size_t index) { // Increase the index by 1 to avoid a key of 0. wtf_size_t stored_index = index + 1; Vector<scoped_refptr<const NGLayoutResult>> results; @@ -1141,4 +1152,51 @@ fragmentainer_descendant_results_.Set(stored_index, results); } +// Compute in which fragmentainer the OOF element will start its layout and +// position the offset relative to that fragmentainer. +void NGOutOfFlowLayoutPart::ComputeStartFragmentIndexAndRelativeOffset( + const ContainingBlockInfo& container_info, + WritingMode default_writing_mode, + wtf_size_t* start_index, + LogicalOffset* offset) const { + LayoutUnit block_offset_from_root = + offset->block_offset + container_info.fragmentainer_consumed_block_size; + + wtf_size_t child_index = 0; + // The sum of all previous fragmentainers' block size. + LayoutUnit used_block_size; + // The sum of all previous fragmentainers' block size + the current one. + LayoutUnit current_max_block_size; + // The block size for the last fragmentainer we encountered. + LayoutUnit fragmentainer_block_size; + // TODO(bebeaudr): There is a possible performance improvement here as we'll + // repeat this for each abspos in a same fragmentainer. + for (auto& child : container_builder_->Children()) { + if (child.fragment->IsFragmentainerBox()) { + fragmentainer_block_size = child.fragment->Size() + .ConvertToLogical(default_writing_mode) + .block_size; + current_max_block_size += fragmentainer_block_size; + + if (block_offset_from_root < current_max_block_size) { + *start_index = child_index; + offset->block_offset = block_offset_from_root - used_block_size; + return; + } + used_block_size = current_max_block_size; + } + child_index++; + } + // If the right fragmentainer hasn't been found yet, the OOF element will + // start its layout in a proxy fragment. + LayoutUnit remaining_block_offset = block_offset_from_root - used_block_size; + wtf_size_t additional_fragment_count = + int(std::floorf(remaining_block_offset / fragmentainer_block_size)); + *start_index = child_index + additional_fragment_count; + // TODO(almaher): This might need to be updated in the case where we add proxy + // fragments directly after a spanner. + offset->block_offset = remaining_block_offset - + additional_fragment_count * fragmentainer_block_size; +} + } // namespace blink
diff --git a/third_party/blink/renderer/core/layout/ng/ng_out_of_flow_layout_part.h b/third_party/blink/renderer/core/layout/ng/ng_out_of_flow_layout_part.h index 62406f2d..eb0f63be 100644 --- a/third_party/blink/renderer/core/layout/ng/ng_out_of_flow_layout_part.h +++ b/third_party/blink/renderer/core/layout/ng/ng_out_of_flow_layout_part.h
@@ -87,6 +87,9 @@ // Offset of the container's padding-box. LogicalOffset container_offset; + // The block size consumed by all previous fragmentainers. + LayoutUnit fragmentainer_consumed_block_size; + LogicalSize ContentSize(EPosition position) const { return position == EPosition::kAbsolute ? content_size_for_absolute : content_size_for_fixed; @@ -124,19 +127,10 @@ const WritingMode, const TextDirection, const LayoutBox* only_layout, - const NGBlockBreakToken* break_token = nullptr, - const NGConstraintSpace* fragmentainer_constraint_space = nullptr); + bool is_fragmentainer_descendant = false); bool IsContainingBlockForCandidate(const NGLogicalOutOfFlowPositionedNode&); - void AddOOFResultsToFragmentainer( - const Vector<scoped_refptr<const NGLayoutResult>>& results, - const wtf_size_t index); - const NGConstraintSpace& GetFragmentainerConstraintSpace( - const wtf_size_t index); - void AddOOFResultToFragmentainerResults( - const scoped_refptr<const NGLayoutResult> result, - const wtf_size_t index); scoped_refptr<const NGLayoutResult> GenerateFragment( NGBlockNode node, const LogicalSize& container_content_size_in_child_writing_mode, @@ -145,6 +139,18 @@ const LayoutUnit block_offset, const NGBlockBreakToken* break_token, const NGConstraintSpace* fragmentainer_constraint_space); + void AddOOFResultsToFragmentainer( + const Vector<scoped_refptr<const NGLayoutResult>>& results, + wtf_size_t index); + const NGConstraintSpace& GetFragmentainerConstraintSpace(wtf_size_t index); + void AddOOFResultToFragmentainerResults( + const scoped_refptr<const NGLayoutResult> result, + wtf_size_t index); + void ComputeStartFragmentIndexAndRelativeOffset( + const ContainingBlockInfo& container_info, + WritingMode default_writing_mode, + wtf_size_t* start_index, + LogicalOffset* offset) const; const NGConstraintSpace& container_space_; NGBoxFragmentBuilder* container_builder_;
diff --git a/third_party/blink/renderer/core/layout/ng/ng_out_of_flow_layout_part_test.cc b/third_party/blink/renderer/core/layout/ng/ng_out_of_flow_layout_part_test.cc index 0eb17466..b3538fc 100644 --- a/third_party/blink/renderer/core/layout/ng/ng_out_of_flow_layout_part_test.cc +++ b/third_party/blink/renderer/core/layout/ng/ng_out_of_flow_layout_part_test.cc
@@ -139,12 +139,12 @@ offset:0,0 size:1000x40 offset:0,0 size:492x40 offset:0,0 size:100x40 - offset:0,20 size:10x10 - offset:0,10 size:5x5 offset:508,0 size:492x40 offset:0,0 size:100x10 offset:0,10 size:30x8 offset:0,0 size:35x8 + offset:0,30 size:10x10 + offset:0,20 size:5x5 )DUMP"; EXPECT_EQ(expectation, dump); } @@ -176,18 +176,17 @@ )HTML"); String dump = DumpFragmentTree(GetElementById("container")); - // TODO(bebeaudr): The OOF positioned element should start in the second - // column rather than the first. String expectation = R"DUMP(.:: LayoutNG Physical Fragment Tree ::. offset:unplaced size:1000x40 offset:0,0 size:1000x40 offset:0,0 size:492x40 offset:0,0 size:100x40 - offset:0,5 size:19x35 offset:508,0 size:492x40 offset:0,0 size:100x10 offset:0,10 size:30x0 - offset:0,0 size:19x29 + offset:0,15 size:19x25 + offset:1016,0 size:492x40 + offset:0,0 size:19x39 )DUMP"; EXPECT_EQ(expectation, dump); } @@ -305,14 +304,18 @@ )HTML"); String dump = DumpFragmentTree(GetElementById("container")); - // TODO(bebeaudr): The OOF fragment should start at a column fragment with - // index 2, and there should be an empty column fragment at index 1. String expectation = R"DUMP(.:: LayoutNG Physical Fragment Tree ::. offset:unplaced size:1000x40 offset:0,0 size:1000x40 offset:0,0 size:492x40 offset:0,0 size:30x0 - offset:0,80 size:5x120 + offset:508,0 size:492x40 + offset:1016,0 size:492x40 + offset:0,0 size:5x40 + offset:1524,0 size:492x40 + offset:0,0 size:5x40 + offset:2032,0 size:492x40 + offset:0,0 size:5x40 )DUMP"; EXPECT_EQ(expectation, dump); } @@ -326,7 +329,7 @@ column-count:2; column-fill:auto; column-gap:16px; height:40px; } .rel { - position: relative; + position:relative; } .abs { position:absolute; break-inside:avoid; @@ -343,15 +346,15 @@ )HTML"); String dump = DumpFragmentTree(GetElementById("container")); - // TODO(bebeaudr): The abspos should have an offset of (0,10), and - // break into a second column, ignoring "break-inside:avoid". String expectation = R"DUMP(.:: LayoutNG Physical Fragment Tree ::. offset:unplaced size:1000x40 offset:0,0 size:1000x40 offset:0,0 size:492x40 offset:0,0 size:20x10 offset:0,10 size:30x0 - offset:0,0 size:40x40 + offset:0,10 size:40x30 + offset:508,0 size:492x40 + offset:0,0 size:40x10 )DUMP"; EXPECT_EQ(expectation, dump); } @@ -382,15 +385,15 @@ )HTML"); String dump = DumpFragmentTree(GetElementById("container")); - // TODO(bebeaudr): The abspos should have an offset of (0,30) in the first - // column, ignoring "break-before:column", and break into a second column. String expectation = R"DUMP(.:: LayoutNG Physical Fragment Tree ::. offset:unplaced size:1000x40 offset:0,0 size:1000x40 offset:0,0 size:492x40 offset:0,0 size:10x30 offset:0,30 size:30x0 - offset:0,0 size:40x30 + offset:0,30 size:40x10 + offset:508,0 size:492x40 + offset:0,0 size:40x20 )DUMP"; EXPECT_EQ(expectation, dump); } @@ -422,7 +425,6 @@ )HTML"); String dump = DumpFragmentTree(GetElementById("container")); - // TODO(bebeaudr): The abspos should have an offset of (0,20). String expectation = R"DUMP(.:: LayoutNG Physical Fragment Tree ::. offset:unplaced size:1000x40 offset:0,0 size:1000x40 @@ -430,7 +432,7 @@ offset:0,0 size:10x20 offset:0,20 size:30x10 offset:0,30 size:20x10 - offset:0,0 size:40x10 + offset:0,20 size:40x10 )DUMP"; EXPECT_EQ(expectation, dump); } @@ -565,5 +567,189 @@ EXPECT_EQ(expectation, dump); } +// Tests that a positioned element with a negative top property moves the OOF +// node to the previous fragmentainer and spans 3 columns. +// TODO(bebeaudr): Figure out why this is crashing. https://crbug.com/1117625. +TEST_F( + NGOutOfFlowLayoutPartTest, + DISABLED_PositionedFragmentationWithNegativeTopPropertyAndNewEmptyColumn) { + SetBodyInnerHTML( + R"HTML( + <style> + #multicol { + column-count:2; column-fill:auto; column-gap:16px; height:40px; + } + .rel { + position: relative; width:30px; + } + .abs { + position:absolute; top:-40px; width:5px; height:80px; + } + </style> + <div id="container"> + <div id="multicol"> + <div class="rel" style="height: 60px; width: 32px;"></div> + <div class="rel"> + <div class="abs"></div> + </div> + </div> + </div> + )HTML"); + String dump = DumpFragmentTree(GetElementById("container")); + + String expectation = R"DUMP(.:: LayoutNG Physical Fragment Tree ::. + offset:unplaced size:1000x40 + offset:0,0 size:1000x40 + offset:0,0 size:492x40 + offset:0,0 size:32x40 + offset:0,20 size:5x20 + offset:508,0 size:492x40 + offset:0,0 size:32x20 + offset:0,20 size:30x0 + offset:0,0 size:5x40 + offset:1016,0 size:492x40 + offset:0,0 size:5x20 +)DUMP"; + EXPECT_EQ(expectation, dump); +} + +// TODO(bebeaudr): Enable when http://crbug.com/1115584 is fixed. +TEST_F(NGOutOfFlowLayoutPartTest, + DISABLED_PositionedFragmentationWithBottomProperty) { + SetBodyInnerHTML( + R"HTML( + <style> + #multicol { + column-count:2; column-fill:auto; column-gap:16px; height:40px; + } + .rel { + position: relative; + } + .abs { + position:absolute; bottom:10px; width:5px; height:40px; + } + </style> + <div id="container"> + <div id="multicol"> + <div class="rel" style="height: 60px; width: 32px;"> + <div class="abs"></div> + </div> + </div> + </div> + )HTML"); + String dump = DumpFragmentTree(GetElementById("container")); + + String expectation = R"DUMP(.:: LayoutNG Physical Fragment Tree ::. + offset:unplaced size:1000x40 + offset:0,0 size:1000x40 + offset:0,0 size:492x40 + offset:0,0 size:32x40 + offset:0,10 size:5x30 + offset:508,0 size:492x40 + offset:0,0 size:32x20 + offset:0,0 size:5x10 +)DUMP"; + EXPECT_EQ(expectation, dump); +} + +// Tests that a positioned element without a top or bottom property stays in +// flow - even though it's treated as an OOF element. +TEST_F(NGOutOfFlowLayoutPartTest, + PositionedFragmentationInFlowWithAddedColumns) { + SetBodyInnerHTML( + R"HTML( + <style> + #multicol { + column-count:2; column-fill:auto; column-gap:16px; height:40px; + } + .rel { + position:relative; width:30px; + } + .abs { + position:absolute; width:5px; height:80px; + } + </style> + <div id="container"> + <div id="multicol"> + <div class="rel"> + <div style="height: 60px; width: 32px;"></div> + <div class="abs"></div> + </div> + </div> + </div> + )HTML"); + String dump = DumpFragmentTree(GetElementById("container")); + + String expectation = R"DUMP(.:: LayoutNG Physical Fragment Tree ::. + offset:unplaced size:1000x40 + offset:0,0 size:1000x40 + offset:0,0 size:492x40 + offset:0,0 size:30x40 + offset:0,0 size:32x40 + offset:508,0 size:492x40 + offset:0,0 size:30x20 + offset:0,0 size:32x20 + offset:0,20 size:5x20 + offset:1016,0 size:492x40 + offset:0,0 size:5x40 + offset:1524,0 size:492x40 + offset:0,0 size:5x20 +)DUMP"; + EXPECT_EQ(expectation, dump); +} + +// Tests that the fragments of a positioned element are added to the right +// fragmentainer despite the presence of column spanners. +TEST_F(NGOutOfFlowLayoutPartTest, PositionedFragmentationAndColumnSpanners) { + SetBodyInnerHTML( + R"HTML( + <style> + #multicol { + column-count:2; column-fill:auto; column-gap:16px; height:40px; + } + .rel { + position:relative; width:30px; + } + .abs { + position:absolute; width:5px; height:20px; + } + </style> + <div id="container"> + <div id="multicol"> + <div class="rel"> + <div style="column-span:all;"></div> + <div style="height: 60px; width: 32px;"></div> + <div style="column-span:all;"></div> + <div class="abs"></div> + </div> + </div> + </div> + )HTML"); + String dump = DumpFragmentTree(GetElementById("container")); + + // TODO(almaher): The height of fragmentainer `offset:0,30 size:492x10` might + // need to be updated in your CL about column spanners. + String expectation = R"DUMP(.:: LayoutNG Physical Fragment Tree ::. + offset:unplaced size:1000x40 + offset:0,0 size:1000x40 + offset:0,0 size:492x1 + offset:0,0 size:30x0 + offset:0,0 size:1000x0 + offset:0,0 size:492x30 + offset:0,0 size:30x30 + offset:0,0 size:32x30 + offset:508,0 size:492x30 + offset:0,0 size:30x30 + offset:0,0 size:32x30 + offset:0,30 size:1000x0 + offset:0,30 size:492x10 + offset:0,0 size:30x0 + offset:0,0 size:5x10 + offset:508,30 size:492x10 + offset:0,0 size:5x10 +)DUMP"; + EXPECT_EQ(expectation, dump); +} + } // namespace } // namespace blink
diff --git a/third_party/blink/renderer/core/layout/ng/ng_out_of_flow_positioned_node.h b/third_party/blink/renderer/core/layout/ng/ng_out_of_flow_positioned_node.h index 7d4a2509..3c3fa3b 100644 --- a/third_party/blink/renderer/core/layout/ng/ng_out_of_flow_positioned_node.h +++ b/third_party/blink/renderer/core/layout/ng/ng_out_of_flow_positioned_node.h
@@ -27,7 +27,10 @@ // // This needs its static position [1] to be placed correctly in its containing // block. And in the case of fragmentation, this also needs the containing block -// fragment to be placed correctly within the fragmentation context root. +// fragment to be placed correctly within the fragmentation context root. In +// addition, the block size consumed by previous fragmentainers and the +// containing block offset are needed to compute the start offset and the +// initial fragmentainer of an out-of-flow positioned-node. // // This is struct is allowed to be stored/persisted. // @@ -37,6 +40,7 @@ NGPhysicalStaticPosition static_position; // Continuation root of the optional inline container. const LayoutInline* inline_container; + const LayoutUnit fragmentainer_consumed_block_size; PhysicalOffset containing_block_offset; scoped_refptr<const NGPhysicalContainerFragment> containing_block_fragment; @@ -44,12 +48,14 @@ NGBlockNode node, NGPhysicalStaticPosition static_position, const LayoutInline* inline_container = nullptr, + LayoutUnit fragmentainer_consumed_block_size = LayoutUnit(), PhysicalOffset containing_block_offset = PhysicalOffset(), scoped_refptr<const NGPhysicalContainerFragment> containing_block_fragment = nullptr) : node(node), static_position(static_position), inline_container(inline_container), + fragmentainer_consumed_block_size(fragmentainer_consumed_block_size), containing_block_offset(containing_block_offset), containing_block_fragment(std::move(containing_block_fragment)) { DCHECK(!inline_container || @@ -68,6 +74,7 @@ NGLogicalStaticPosition static_position; // Continuation root of the optional inline container. const LayoutInline* inline_container; + const LayoutUnit fragmentainer_consumed_block_size; bool needs_block_offset_adjustment; LogicalOffset containing_block_offset; scoped_refptr<const NGPhysicalContainerFragment> containing_block_fragment; @@ -77,12 +84,14 @@ NGLogicalStaticPosition static_position, const LayoutInline* inline_container = nullptr, bool needs_block_offset_adjustment = false, + LayoutUnit fragmentainer_consumed_block_size = LayoutUnit(), LogicalOffset containing_block_offset = LogicalOffset(), scoped_refptr<const NGPhysicalContainerFragment> containing_block_fragment = nullptr) : node(node), static_position(static_position), inline_container(inline_container), + fragmentainer_consumed_block_size(fragmentainer_consumed_block_size), needs_block_offset_adjustment(needs_block_offset_adjustment), containing_block_offset(containing_block_offset), containing_block_fragment(std::move(containing_block_fragment)) {
diff --git a/third_party/blink/renderer/core/layout/ng/ng_physical_box_fragment.cc b/third_party/blink/renderer/core/layout/ng/ng_physical_box_fragment.cc index a194791..82101c7 100644 --- a/third_party/blink/renderer/core/layout/ng/ng_physical_box_fragment.cc +++ b/third_party/blink/renderer/core/layout/ng/ng_physical_box_fragment.cc
@@ -169,6 +169,7 @@ descendant.static_position.ConvertToPhysical( builder->Style().GetWritingMode(), builder->Direction(), size), descendant.inline_container, + descendant.fragmentainer_consumed_block_size, descendant.containing_block_offset.ConvertToPhysical( builder->Style().GetWritingDirection(), size, descendant.containing_block_fragment
diff --git a/third_party/blink/renderer/core/loader/link_loader_test.cc b/third_party/blink/renderer/core/loader/link_loader_test.cc index ec8a9925..200dc4b 100644 --- a/third_party/blink/renderer/core/loader/link_loader_test.cc +++ b/third_party/blink/renderer/core/loader/link_loader_test.cc
@@ -10,6 +10,7 @@ #include "base/test/scoped_feature_list.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/blink/public/common/features.h" +#include "third_party/blink/public/common/loader/referrer_utils.h" #include "third_party/blink/public/platform/web_prescient_networking.h" #include "third_party/blink/public/platform/web_url_loader_mock_factory.h" #include "third_party/blink/renderer/bindings/core/v8/v8_binding_for_core.h" @@ -591,9 +592,8 @@ EXPECT_EQ(resource->GetResourceRequest().GetRedirectMode(), network::mojom::RedirectMode::kFollow); EXPECT_EQ(resource->GetResourceRequest().GetReferrerPolicy(), - RuntimeEnabledFeatures::ReducedReferrerGranularityEnabled() - ? network::mojom::ReferrerPolicy::kStrictOriginWhenCrossOrigin - : network::mojom::ReferrerPolicy::kNoReferrerWhenDowngrade); + ReferrerUtils::MojoReferrerPolicyResolveDefault( + network::mojom::ReferrerPolicy::kDefault)); } WebURLLoaderMockFactory::GetSingletonInstance()
diff --git a/third_party/blink/renderer/core/loader/resource/image_resource.cc b/third_party/blink/renderer/core/loader/resource/image_resource.cc index e3c68b47..f9d10219 100644 --- a/third_party/blink/renderer/core/loader/resource/image_resource.cc +++ b/third_party/blink/renderer/core/loader/resource/image_resource.cc
@@ -30,6 +30,7 @@ #include "base/metrics/histogram_macros.h" #include "base/numerics/safe_conversions.h" +#include "third_party/blink/public/common/loader/referrer_utils.h" #include "third_party/blink/public/mojom/fetch/fetch_api_request.mojom-blink.h" #include "third_party/blink/public/platform/platform.h" #include "third_party/blink/renderer/core/loader/resource/image_resource_content.h" @@ -50,7 +51,6 @@ #include "third_party/blink/renderer/platform/runtime_enabled_features.h" #include "third_party/blink/renderer/platform/weborigin/kurl.h" #include "third_party/blink/renderer/platform/weborigin/reporting_disposition.h" -#include "third_party/blink/renderer/platform/weborigin/security_policy.h" #include "third_party/blink/renderer/platform/wtf/functional.h" #include "third_party/blink/renderer/platform/wtf/shared_buffer.h" #include "third_party/blink/renderer/platform/wtf/std_lib_extras.h" @@ -195,8 +195,8 @@ // These are needed because some unittests don't go through the usual // request setting path in ResourceFetcher. request.SetRequestorOrigin(SecurityOrigin::CreateUniqueOpaque()); - request.SetReferrerPolicy( - ReferrerPolicyResolveDefault(request.GetReferrerPolicy())); + request.SetReferrerPolicy(ReferrerUtils::MojoReferrerPolicyResolveDefault( + request.GetReferrerPolicy())); request.SetPriority(WebURLRequest::Priority::kLow); return Create(request, nullptr);
diff --git a/third_party/blink/renderer/core/loader/resource/image_resource_content.cc b/third_party/blink/renderer/core/loader/resource/image_resource_content.cc index 56ea892c..53c0ce8 100644 --- a/third_party/blink/renderer/core/loader/resource/image_resource_content.cc +++ b/third_party/blink/renderer/core/loader/resource/image_resource_content.cc
@@ -481,23 +481,27 @@ // Pass image url to reporting API. const String& image_url = Url().GetString(); + const char* message_format = + "Image bpp (byte per pixel) exceeds max value set in %s."; + if (compression_format == ImageDecoder::kLossyFormat) { // Enforce the lossy image policy. return context.IsFeatureEnabled( mojom::blink::DocumentPolicyFeature::kLossyImagesMaxBpp, PolicyValue(compression_ratio_1k), ReportOptions::kReportOnFailure, - g_empty_string, image_url); + String::Format(message_format, "lossy-images-max-bpp"), image_url); } if (compression_format == ImageDecoder::kLosslessFormat) { // Enforce the lossless image policy. bool enabled_by_10k_policy = context.IsFeatureEnabled( mojom::blink::DocumentPolicyFeature::kLosslessImagesMaxBpp, PolicyValue(compression_ratio_10k), ReportOptions::kReportOnFailure, - g_empty_string, image_url); + String::Format(message_format, "lossless-images-max-bpp"), image_url); bool enabled_by_1k_policy = context.IsFeatureEnabled( mojom::blink::DocumentPolicyFeature::kLosslessImagesStrictMaxBpp, PolicyValue(compression_ratio_1k), ReportOptions::kReportOnFailure, - g_empty_string, image_url); + String::Format(message_format, "lossless-images-strict-max-bpp"), + image_url); return enabled_by_10k_policy && enabled_by_1k_policy; }
diff --git a/third_party/blink/renderer/core/loader/resource/image_resource_test.cc b/third_party/blink/renderer/core/loader/resource/image_resource_test.cc index af7e626..abb0f07 100644 --- a/third_party/blink/renderer/core/loader/resource/image_resource_test.cc +++ b/third_party/blink/renderer/core/loader/resource/image_resource_test.cc
@@ -33,6 +33,7 @@ #include <memory> #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" +#include "third_party/blink/public/common/loader/referrer_utils.h" #include "third_party/blink/public/mojom/fetch/fetch_api_request.mojom-blink.h" #include "third_party/blink/public/platform/platform.h" #include "third_party/blink/public/platform/web_url.h" @@ -69,7 +70,6 @@ #include "third_party/blink/renderer/platform/testing/scoped_mocked_url.h" #include "third_party/blink/renderer/platform/testing/testing_platform_support_with_mock_scheduler.h" #include "third_party/blink/renderer/platform/testing/unit_test_helpers.h" -#include "third_party/blink/renderer/platform/weborigin/security_policy.h" #include "third_party/blink/renderer/platform/wtf/shared_buffer.h" #include "third_party/blink/renderer/platform/wtf/text/base64.h" @@ -311,7 +311,8 @@ resource_request.SetInspectorId(CreateUniqueIdentifier()); resource_request.SetRequestorOrigin(SecurityOrigin::CreateUniqueOpaque()); resource_request.SetReferrerPolicy( - ReferrerPolicyResolveDefault(resource_request.GetReferrerPolicy())); + ReferrerUtils::MojoReferrerPolicyResolveDefault( + resource_request.GetReferrerPolicy())); resource_request.SetPriority(WebURLRequest::Priority::kLow); ImageResource* image_resource = ImageResource::Create(resource_request, nullptr /* world */);
diff --git a/third_party/blink/renderer/core/paint/pre_paint_tree_walk.cc b/third_party/blink/renderer/core/paint/pre_paint_tree_walk.cc index 5e84d72..bf86a555 100644 --- a/third_party/blink/renderer/core/paint/pre_paint_tree_walk.cc +++ b/third_party/blink/renderer/core/paint/pre_paint_tree_walk.cc
@@ -110,7 +110,7 @@ // The fragment is block-level. if (IsResumingLayout(incoming_break_token)) { // This isn't the first fragment for the node. We now need to walk past - // all prededing fragments to figure out which FragmentData to return (or + // all preceding fragments to figure out which FragmentData to return (or // create, if it doesn't already exist). const LayoutBox& layout_box = ToLayoutBox(object); for (wtf_size_t idx = 0;; idx++) {
diff --git a/third_party/blink/renderer/core/svg/graphics/svg_image.cc b/third_party/blink/renderer/core/svg/graphics/svg_image.cc index 432a109..11441c8 100644 --- a/third_party/blink/renderer/core/svg/graphics/svg_image.cc +++ b/third_party/blink/renderer/core/svg/graphics/svg_image.cc
@@ -467,26 +467,6 @@ StartAnimation(); } -sk_sp<PaintRecord> SVGImage::PaintRecordForContainer( - const KURL& url, - const IntSize& container_size, - const IntRect& draw_src_rect, - const IntRect& draw_dst_rect, - bool flip_y) { - if (!page_) - return nullptr; - - PaintRecorder recorder; - cc::PaintCanvas* canvas = recorder.beginRecording(draw_src_rect); - if (flip_y) { - canvas->translate(0, draw_dst_rect.Height()); - canvas->scale(1, -1); - } - DrawForContainer(canvas, PaintFlags(), FloatSize(container_size), 1, - FloatRect(draw_dst_rect), FloatRect(draw_src_rect), url); - return recorder.finishRecordingAsPicture(); -} - void SVGImage::PopulatePaintRecordForCurrentFrameForContainer( PaintImageBuilder& builder, const IntSize& zoomed_container_size, @@ -931,32 +911,4 @@ return "svg"; } -SkBitmap SVGImage::AsSkBitmapForCursor(float device_scale_factor) { - // The size should be scaled by the device scale factor for the cursor so that - // the SVG can be drawn at the correct resolution for a crisp image on high - // DPI displays. Scaling the size here causes the SVG to be rasterized at the - // correct resolution and causes the canvas that it is rasterized into being - // the correct size so that the cursor is not clipped. - IntSize scaled_size = Size(); - scaled_size.Scale(device_scale_factor); - - auto builder = - CreatePaintImageBuilder().set_completion_state(completion_state()); - // TODO(fs): Pass |device_scale_factor| as zoom. - PopulatePaintRecordForCurrentFrameForContainer(builder, scaled_size, 1, - NullURL()); - - PaintImage paint_image = builder.TakePaintImage(); - if (!paint_image) - return {}; - - sk_sp<SkImage> sk_image = paint_image.GetSkImage(); - if (!sk_image) - return {}; - - SkBitmap bitmap; - sk_image->asLegacyBitmap(&bitmap); - return bitmap; -} - } // namespace blink
diff --git a/third_party/blink/renderer/core/svg/graphics/svg_image.h b/third_party/blink/renderer/core/svg/graphics/svg_image.h index 60b40ce..7770993 100644 --- a/third_party/blink/renderer/core/svg/graphics/svg_image.h +++ b/third_party/blink/renderer/core/svg/graphics/svg_image.h
@@ -118,16 +118,8 @@ // object size is non-empty.) bool HasIntrinsicDimensions() const; - sk_sp<PaintRecord> PaintRecordForContainer(const KURL&, - const IntSize& container_size, - const IntRect& draw_src_rect, - const IntRect& draw_dst_rect, - bool flip_y) override; - PaintImage PaintImageForCurrentFrame() override; - SkBitmap AsSkBitmapForCursor(float device_scale_factor); - protected: // Whether or not size is available yet. bool IsSizeAvailable() override;
diff --git a/third_party/blink/renderer/modules/accessibility/ax_menu_list_option.cc b/third_party/blink/renderer/modules/accessibility/ax_menu_list_option.cc index 097d5b7..97e9204 100644 --- a/third_party/blink/renderer/modules/accessibility/ax_menu_list_option.cc +++ b/third_party/blink/renderer/modules/accessibility/ax_menu_list_option.cc
@@ -152,8 +152,11 @@ bool AXMenuListOption::ComputeAccessibilityIsIgnored( IgnoredReasons* ignored_reasons) const { - if (IsInertOrAriaHidden()) + if (IsInertOrAriaHidden()) { + if (ignored_reasons) + ComputeIsInertOrAriaHidden(ignored_reasons); return true; + } if (DynamicTo<HTMLOptionElement>(GetNode())->FastHasAttribute( html_names::kHiddenAttr))
diff --git a/third_party/blink/renderer/modules/accessibility/ax_menu_list_popup.cc b/third_party/blink/renderer/modules/accessibility/ax_menu_list_popup.cc index c8e5fe81..b4cbcf0 100644 --- a/third_party/blink/renderer/modules/accessibility/ax_menu_list_popup.cc +++ b/third_party/blink/renderer/modules/accessibility/ax_menu_list_popup.cc
@@ -53,7 +53,11 @@ bool AXMenuListPopup::ComputeAccessibilityIsIgnored( IgnoredReasons* ignored_reasons) const { - return AccessibilityIsIgnoredByDefault(ignored_reasons); + // Base whether the menupopup is ignored on the containing <select>. + if (parent_) + return parent_->ComputeAccessibilityIsIgnored(ignored_reasons); + + return kIgnoreObject; } AXMenuListOption* AXMenuListPopup::MenuListOptionAXObject(
diff --git a/third_party/blink/renderer/modules/accessibility/ax_object.cc b/third_party/blink/renderer/modules/accessibility/ax_object.cc index b890343c..d609e7ca 100644 --- a/third_party/blink/renderer/modules/accessibility/ax_object.cc +++ b/third_party/blink/renderer/modules/accessibility/ax_object.cc
@@ -1238,28 +1238,19 @@ return DefaultObjectInclusion(ignored_reasons) == kIgnoreObject; } -AXObjectInclusion AXObject::AccessibilityPlatformIncludesObject() const { - if (IsA<AXMenuListPopup>(this) || IsA<AXMenuListOption>(this)) - return kIncludeObject; - - return kDefaultBehavior; -} - AXObjectInclusion AXObject::DefaultObjectInclusion( IgnoredReasons* ignored_reasons) const { if (IsInertOrAriaHidden()) { // Keep focusable elements that are aria-hidden in tree, so that they can - // still fire events such as focus and value changes. Handle the case where - // a <select> element is aria-hidden. - if (RoleValue() != ax::mojom::blink::Role::kMenuListPopup && - !CanSetFocusAttribute()) { + // still fire events such as focus and value changes. + if (!CanSetFocusAttribute()) { if (ignored_reasons) ComputeIsInertOrAriaHidden(ignored_reasons); return kIgnoreObject; } } - return AccessibilityPlatformIncludesObject(); + return kDefaultBehavior; } bool AXObject::IsInertOrAriaHidden() const {
diff --git a/third_party/blink/renderer/modules/accessibility/ax_object.h b/third_party/blink/renderer/modules/accessibility/ax_object.h index 7d10bfa..9899426 100644 --- a/third_party/blink/renderer/modules/accessibility/ax_object.h +++ b/third_party/blink/renderer/modules/accessibility/ax_object.h
@@ -526,7 +526,6 @@ return true; } bool AccessibilityIsIgnoredByDefault(IgnoredReasons* = nullptr) const; - AXObjectInclusion AccessibilityPlatformIncludesObject() const; virtual AXObjectInclusion DefaultObjectInclusion( IgnoredReasons* = nullptr) const; bool IsInertOrAriaHidden() const;
diff --git a/third_party/blink/renderer/modules/filesystem/file_system_dispatcher.cc b/third_party/blink/renderer/modules/filesystem/file_system_dispatcher.cc index 63ef464..3fad596f 100644 --- a/third_party/blink/renderer/modules/filesystem/file_system_dispatcher.cc +++ b/third_party/blink/renderer/modules/filesystem/file_system_dispatcher.cc
@@ -422,11 +422,16 @@ std::move(callback).Run(base::File::FILE_ERROR_INVALID_OPERATION); return; } - cancellable_operations_.find(request_id_to_cancel) - ->value->Value() - ->Cancel(WTF::Bind(&FileSystemDispatcher::DidCancel, - WrapWeakPersistent(this), std::move(callback), - request_id_to_cancel)); + auto& remote = + cancellable_operations_.find(request_id_to_cancel)->value->Value(); + if (!remote.is_bound()) { + RemoveOperationRemote(request_id_to_cancel); + std::move(callback).Run(base::File::FILE_ERROR_INVALID_OPERATION); + return; + } + remote->Cancel(WTF::Bind(&FileSystemDispatcher::DidCancel, + WrapWeakPersistent(this), std::move(callback), + request_id_to_cancel)); } void FileSystemDispatcher::CreateSnapshotFile(
diff --git a/third_party/blink/renderer/modules/peerconnection/mock_rtc_peer_connection_handler_client.h b/third_party/blink/renderer/modules/peerconnection/mock_rtc_peer_connection_handler_client.h index 7bced30a..1104343 100644 --- a/third_party/blink/renderer/modules/peerconnection/mock_rtc_peer_connection_handler_client.h +++ b/third_party/blink/renderer/modules/peerconnection/mock_rtc_peer_connection_handler_client.h
@@ -35,6 +35,11 @@ const String& url, int error_code, const String& error_text)); + MOCK_METHOD4(DidChangeSessionDescriptions, + void(RTCSessionDescriptionPlatform*, + RTCSessionDescriptionPlatform*, + RTCSessionDescriptionPlatform*, + RTCSessionDescriptionPlatform*)); MOCK_METHOD1(DidChangeSignalingState, void(webrtc::PeerConnectionInterface::SignalingState state)); MOCK_METHOD1(DidChangeIceGatheringState,
diff --git a/third_party/blink/renderer/modules/peerconnection/mock_rtc_peer_connection_handler_platform.cc b/third_party/blink/renderer/modules/peerconnection/mock_rtc_peer_connection_handler_platform.cc index 5437abb2..da6d4bb 100644 --- a/third_party/blink/renderer/modules/peerconnection/mock_rtc_peer_connection_handler_platform.cc +++ b/third_party/blink/renderer/modules/peerconnection/mock_rtc_peer_connection_handler_platform.cc
@@ -286,36 +286,6 @@ RTCVoidRequest*, RTCSessionDescriptionPlatform*) {} -RTCSessionDescriptionPlatform* -MockRTCPeerConnectionHandlerPlatform::LocalDescription() { - return nullptr; -} - -RTCSessionDescriptionPlatform* -MockRTCPeerConnectionHandlerPlatform::RemoteDescription() { - return nullptr; -} - -RTCSessionDescriptionPlatform* -MockRTCPeerConnectionHandlerPlatform::CurrentLocalDescription() { - return nullptr; -} - -RTCSessionDescriptionPlatform* -MockRTCPeerConnectionHandlerPlatform::CurrentRemoteDescription() { - return nullptr; -} - -RTCSessionDescriptionPlatform* -MockRTCPeerConnectionHandlerPlatform::PendingLocalDescription() { - return nullptr; -} - -RTCSessionDescriptionPlatform* -MockRTCPeerConnectionHandlerPlatform::PendingRemoteDescription() { - return nullptr; -} - const webrtc::PeerConnectionInterface::RTCConfiguration& MockRTCPeerConnectionHandlerPlatform::GetConfiguration() const { static const webrtc::PeerConnectionInterface::RTCConfiguration configuration;
diff --git a/third_party/blink/renderer/modules/peerconnection/mock_rtc_peer_connection_handler_platform.h b/third_party/blink/renderer/modules/peerconnection/mock_rtc_peer_connection_handler_platform.h index 71fadfd1..1a9cb0f 100644 --- a/third_party/blink/renderer/modules/peerconnection/mock_rtc_peer_connection_handler_platform.h +++ b/third_party/blink/renderer/modules/peerconnection/mock_rtc_peer_connection_handler_platform.h
@@ -48,12 +48,6 @@ RTCSessionDescriptionPlatform*) override; void SetRemoteDescription(RTCVoidRequest*, RTCSessionDescriptionPlatform*) override; - RTCSessionDescriptionPlatform* LocalDescription() override; - RTCSessionDescriptionPlatform* RemoteDescription() override; - RTCSessionDescriptionPlatform* CurrentLocalDescription() override; - RTCSessionDescriptionPlatform* CurrentRemoteDescription() override; - RTCSessionDescriptionPlatform* PendingLocalDescription() override; - RTCSessionDescriptionPlatform* PendingRemoteDescription() override; const webrtc::PeerConnectionInterface::RTCConfiguration& GetConfiguration() const override; webrtc::RTCErrorType SetConfiguration(
diff --git a/third_party/blink/renderer/modules/peerconnection/rtc_peer_connection.cc b/third_party/blink/renderer/modules/peerconnection/rtc_peer_connection.cc index cd98310..aa15ab5 100644 --- a/third_party/blink/renderer/modules/peerconnection/rtc_peer_connection.cc +++ b/third_party/blink/renderer/modules/peerconnection/rtc_peer_connection.cc
@@ -746,6 +746,10 @@ MediaConstraints constraints, ExceptionState& exception_state) : ExecutionContextLifecycleObserver(context), + pending_local_description_(nullptr), + current_local_description_(nullptr), + pending_remote_description_(nullptr), + current_remote_description_(nullptr), signaling_state_( webrtc::PeerConnectionInterface::SignalingState::kStable), ice_gathering_state_(webrtc::PeerConnectionInterface::kIceGatheringNew), @@ -1459,28 +1463,17 @@ return ScriptPromise::CastUndefined(script_state); } -RTCSessionDescription* RTCPeerConnection::localDescription() { - auto* platform_session_description = peer_handler_->LocalDescription(); - if (!platform_session_description) - return nullptr; - - return RTCSessionDescription::Create(platform_session_description); +RTCSessionDescription* RTCPeerConnection::localDescription() const { + return pending_local_description_ ? pending_local_description_ + : current_local_description_; } -RTCSessionDescription* RTCPeerConnection::currentLocalDescription() { - auto* platform_session_description = peer_handler_->CurrentLocalDescription(); - if (!platform_session_description) - return nullptr; - - return RTCSessionDescription::Create(platform_session_description); +RTCSessionDescription* RTCPeerConnection::currentLocalDescription() const { + return current_local_description_; } -RTCSessionDescription* RTCPeerConnection::pendingLocalDescription() { - auto* platform_session_description = peer_handler_->PendingLocalDescription(); - if (!platform_session_description) - return nullptr; - - return RTCSessionDescription::Create(platform_session_description); +RTCSessionDescription* RTCPeerConnection::pendingLocalDescription() const { + return pending_local_description_; } ScriptPromise RTCPeerConnection::setRemoteDescription( @@ -1587,30 +1580,17 @@ return ScriptPromise::CastUndefined(script_state); } -RTCSessionDescription* RTCPeerConnection::remoteDescription() { - auto* platform_session_description = peer_handler_->RemoteDescription(); - if (!platform_session_description) - return nullptr; - - return RTCSessionDescription::Create(platform_session_description); +RTCSessionDescription* RTCPeerConnection::remoteDescription() const { + return pending_remote_description_ ? pending_remote_description_ + : current_remote_description_; } -RTCSessionDescription* RTCPeerConnection::currentRemoteDescription() { - auto* platform_session_description = - peer_handler_->CurrentRemoteDescription(); - if (!platform_session_description) - return nullptr; - - return RTCSessionDescription::Create(platform_session_description); +RTCSessionDescription* RTCPeerConnection::currentRemoteDescription() const { + return current_remote_description_; } -RTCSessionDescription* RTCPeerConnection::pendingRemoteDescription() { - auto* platform_session_description = - peer_handler_->PendingRemoteDescription(); - if (!platform_session_description) - return nullptr; - - return RTCSessionDescription::Create(platform_session_description); +RTCSessionDescription* RTCPeerConnection::pendingRemoteDescription() const { + return pending_remote_description_; } RTCConfiguration* RTCPeerConnection::getConfiguration( @@ -2034,7 +2014,7 @@ } base::Optional<bool> RTCPeerConnection::canTrickleIceCandidates() const { - if (closed_ || !peer_handler_->RemoteDescription()) { + if (closed_ || !remoteDescription()) { return base::nullopt; } webrtc::PeerConnectionInterface* native_connection = @@ -2894,6 +2874,31 @@ address, port, host_candidate, url, error_code, error_text)); } +void RTCPeerConnection::DidChangeSessionDescriptions( + RTCSessionDescriptionPlatform* pending_local_description, + RTCSessionDescriptionPlatform* current_local_description, + RTCSessionDescriptionPlatform* pending_remote_description, + RTCSessionDescriptionPlatform* current_remote_description) { + DCHECK(!closed_); + DCHECK(GetExecutionContext()->IsContextThread()); + pending_local_description_ = + pending_local_description + ? RTCSessionDescription::Create(pending_local_description) + : nullptr; + current_local_description_ = + current_local_description + ? RTCSessionDescription::Create(current_local_description) + : nullptr; + pending_remote_description_ = + pending_remote_description + ? RTCSessionDescription::Create(pending_remote_description) + : nullptr; + current_remote_description_ = + current_remote_description + ? RTCSessionDescription::Create(current_remote_description) + : nullptr; +} + void RTCPeerConnection::DidChangeSignalingState( webrtc::PeerConnectionInterface::SignalingState new_state) { DCHECK(!closed_); @@ -3545,6 +3550,10 @@ } void RTCPeerConnection::Trace(Visitor* visitor) const { + visitor->Trace(pending_local_description_); + visitor->Trace(current_local_description_); + visitor->Trace(pending_remote_description_); + visitor->Trace(current_remote_description_); visitor->Trace(tracks_); visitor->Trace(rtp_senders_); visitor->Trace(rtp_receivers_);
diff --git a/third_party/blink/renderer/modules/peerconnection/rtc_peer_connection.h b/third_party/blink/renderer/modules/peerconnection/rtc_peer_connection.h index 72ead12..7a57fc97 100644 --- a/third_party/blink/renderer/modules/peerconnection/rtc_peer_connection.h +++ b/third_party/blink/renderer/modules/peerconnection/rtc_peer_connection.h
@@ -183,9 +183,9 @@ const RTCSessionDescriptionInit*, V8VoidFunction*, V8RTCPeerConnectionErrorCallback* = nullptr); - RTCSessionDescription* localDescription(); - RTCSessionDescription* currentLocalDescription(); - RTCSessionDescription* pendingLocalDescription(); + RTCSessionDescription* localDescription() const; + RTCSessionDescription* currentLocalDescription() const; + RTCSessionDescription* pendingLocalDescription() const; ScriptPromise setRemoteDescription(ScriptState*, const RTCSessionDescriptionInit*, @@ -195,9 +195,9 @@ const RTCSessionDescriptionInit*, V8VoidFunction*, V8RTCPeerConnectionErrorCallback* = nullptr); - RTCSessionDescription* remoteDescription(); - RTCSessionDescription* currentRemoteDescription(); - RTCSessionDescription* pendingRemoteDescription(); + RTCSessionDescription* remoteDescription() const; + RTCSessionDescription* currentRemoteDescription() const; + RTCSessionDescription* pendingRemoteDescription() const; String signalingState() const; @@ -337,6 +337,11 @@ const String& url, int error_code, const String& error_text) override; + void DidChangeSessionDescriptions( + RTCSessionDescriptionPlatform* pending_local_description, + RTCSessionDescriptionPlatform* current_local_description, + RTCSessionDescriptionPlatform* pending_remote_description, + RTCSessionDescriptionPlatform* current_remote_description) override; void DidChangeSignalingState( webrtc::PeerConnectionInterface::SignalingState) override; void DidChangeIceGatheringState( @@ -571,6 +576,10 @@ HeapHashSet<Member<RTCIceTransport>> ActiveIceTransports() const; + Member<RTCSessionDescription> pending_local_description_; + Member<RTCSessionDescription> current_local_description_; + Member<RTCSessionDescription> pending_remote_description_; + Member<RTCSessionDescription> current_remote_description_; webrtc::PeerConnectionInterface::SignalingState signaling_state_; webrtc::PeerConnectionInterface::IceGatheringState ice_gathering_state_; webrtc::PeerConnectionInterface::IceConnectionState ice_connection_state_;
diff --git a/third_party/blink/renderer/modules/peerconnection/rtc_peer_connection_handler.cc b/third_party/blink/renderer/modules/peerconnection/rtc_peer_connection_handler.cc index 404e633..6e19f59 100644 --- a/third_party/blink/renderer/modules/peerconnection/rtc_peer_connection_handler.cc +++ b/third_party/blink/renderer/modules/peerconnection/rtc_peer_connection_handler.cc
@@ -154,29 +154,6 @@ event->Signal(); } -// Initializes |description| if |description_callback| returns non-null, -// otherwise does nothing. -void GetRTCSessionDescriptionPlatformFromSessionDescriptionCallback( - CrossThreadOnceFunction<const webrtc::SessionDescriptionInterface*()> - description_callback, - std::string* out_type, - std::string* out_sdp, - bool* success) { - DCHECK(out_type); - DCHECK(out_sdp); - DCHECK(success); - - const webrtc::SessionDescriptionInterface* description = - std::move(description_callback).Run(); - if (description) { - std::string sdp; - description->ToString(&sdp); - *out_type = description->type(); - *out_sdp = sdp; - *success = true; - } -} - // Converter functions from Blink types to WebRTC types. absl::optional<bool> ConstraintToOptional( @@ -620,9 +597,7 @@ const char kLocalTld[] = ".local"; if (!candidate.Address().ContainsOnlyASCIIOrEmpty()) return false; - // TODO(crbug.com/787254): Replace with String::EndsWithIgnoringCase. - return base::EndsWith(candidate.Address().Ascii(), kLocalTld, - base::CompareCase::INSENSITIVE_ASCII); + return candidate.Address().EndsWithIgnoringASCIICase(kLocalTld); } } // namespace @@ -704,19 +679,14 @@ pending_local_description(states.pending_local_description.release()); std::unique_ptr<webrtc::SessionDescriptionInterface> current_local_description(states.current_local_description.release()); + std::unique_ptr<webrtc::SessionDescriptionInterface> + pending_remote_description( + states.pending_remote_description.release()); + std::unique_ptr<webrtc::SessionDescriptionInterface> + current_remote_description( + states.current_remote_description.release()); - // Process the rest of the state changes differently depending on SDP - // semantics. - if (sdp_semantics_ == webrtc::SdpSemantics::kPlanB) { - ProcessStateChangesPlanB(std::move(states)); - } else { - DCHECK_EQ(sdp_semantics_, webrtc::SdpSemantics::kUnifiedPlan); - ProcessStateChangesUnifiedPlan(std::move(states)); - } - - // |handler_| can become null after this call. - handler_->OnSignalingChange(signaling_state); - + // Track result in chrome://webrtc-internals/. if (tracker_ && handler_) { StringBuilder value; if (action_ == @@ -756,6 +726,24 @@ tracker_->TrackSessionDescriptionCallback( handler_.get(), action_, "OnSuccess", value.ToString()); } + + handler_->OnSessionDescriptionsUpdated( + std::move(pending_local_description), + std::move(current_local_description), + std::move(pending_remote_description), + std::move(current_remote_description)); + + // Process the rest of the state changes differently depending on SDP + // semantics. + if (sdp_semantics_ == webrtc::SdpSemantics::kPlanB) { + ProcessStateChangesPlanB(std::move(states)); + } else { + DCHECK_EQ(sdp_semantics_, webrtc::SdpSemantics::kUnifiedPlan); + ProcessStateChangesUnifiedPlan(std::move(states)); + } + + // |handler_| can become null after this call. + handler_->OnSignalingChange(signaling_state); } if (action_ == PeerConnectionTracker::ACTION_SET_REMOTE_DESCRIPTION) { // Resolve the promise in a post to ensure any events scheduled for @@ -1497,81 +1485,6 @@ CrossThreadUnretained("SetRemoteDescription"))); } -RTCSessionDescriptionPlatform* RTCPeerConnectionHandler::LocalDescription() { - DCHECK(task_runner_->RunsTasksInCurrentSequence()); - TRACE_EVENT0("webrtc", "RTCPeerConnectionHandler::localDescription"); - - CrossThreadOnceFunction<const webrtc::SessionDescriptionInterface*()> - description_cb = CrossThreadBindOnce( - &webrtc::PeerConnectionInterface::local_description, - native_peer_connection_); - return GetRTCSessionDescriptionPlatformOnSignalingThread( - std::move(description_cb), "localDescription"); -} - -RTCSessionDescriptionPlatform* RTCPeerConnectionHandler::RemoteDescription() { - DCHECK(task_runner_->RunsTasksInCurrentSequence()); - TRACE_EVENT0("webrtc", "RTCPeerConnectionHandler::remoteDescription"); - - CrossThreadOnceFunction<const webrtc::SessionDescriptionInterface*()> - description_cb = CrossThreadBindOnce( - &webrtc::PeerConnectionInterface::remote_description, - native_peer_connection_); - return GetRTCSessionDescriptionPlatformOnSignalingThread( - std::move(description_cb), "remoteDescription"); -} - -RTCSessionDescriptionPlatform* -RTCPeerConnectionHandler::CurrentLocalDescription() { - DCHECK(task_runner_->RunsTasksInCurrentSequence()); - TRACE_EVENT0("webrtc", "RTCPeerConnectionHandler::currentLocalDescription"); - - CrossThreadOnceFunction<const webrtc::SessionDescriptionInterface*()> - description_cb = CrossThreadBindOnce( - &webrtc::PeerConnectionInterface::current_local_description, - native_peer_connection_); - return GetRTCSessionDescriptionPlatformOnSignalingThread( - std::move(description_cb), "currentLocalDescription"); -} - -RTCSessionDescriptionPlatform* -RTCPeerConnectionHandler::CurrentRemoteDescription() { - DCHECK(task_runner_->RunsTasksInCurrentSequence()); - TRACE_EVENT0("webrtc", "RTCPeerConnectionHandler::currentRemoteDescription"); - - CrossThreadOnceFunction<const webrtc::SessionDescriptionInterface*()> - description_cb = CrossThreadBindOnce( - &webrtc::PeerConnectionInterface::current_remote_description, - native_peer_connection_); - return GetRTCSessionDescriptionPlatformOnSignalingThread( - std::move(description_cb), "currentRemoteDescription"); -} - -RTCSessionDescriptionPlatform* -RTCPeerConnectionHandler::PendingLocalDescription() { - DCHECK(task_runner_->RunsTasksInCurrentSequence()); - TRACE_EVENT0("webrtc", "RTCPeerConnectionHandler::pendingLocalDescription"); - - CrossThreadOnceFunction<const webrtc::SessionDescriptionInterface*()> - description_cb = CrossThreadBindOnce( - &webrtc::PeerConnectionInterface::pending_local_description, - native_peer_connection_); - return GetRTCSessionDescriptionPlatformOnSignalingThread( - std::move(description_cb), "pendingLocalDescription"); -} - -RTCSessionDescriptionPlatform* -RTCPeerConnectionHandler::PendingRemoteDescription() { - DCHECK(task_runner_->RunsTasksInCurrentSequence()); - TRACE_EVENT0("webrtc", "RTCPeerConnectionHandler::pendingRemoteDescription"); - CrossThreadOnceFunction<const webrtc::SessionDescriptionInterface*()> - description_cb = CrossThreadBindOnce( - &webrtc::PeerConnectionInterface::pending_remote_description, - native_peer_connection_); - return GetRTCSessionDescriptionPlatformOnSignalingThread( - std::move(description_cb), "pendingRemoteDescription"); -} - const webrtc::PeerConnectionInterface::RTCConfiguration& RTCPeerConnectionHandler::GetConfiguration() const { return configuration_; @@ -1622,6 +1535,14 @@ auto callback_on_task_runner = [](base::WeakPtr<RTCPeerConnectionHandler> handler_weak_ptr, base::WeakPtr<PeerConnectionTracker> tracker_weak_ptr, + std::unique_ptr<webrtc::SessionDescriptionInterface> + pending_local_description, + std::unique_ptr<webrtc::SessionDescriptionInterface> + current_local_description, + std::unique_ptr<webrtc::SessionDescriptionInterface> + pending_remote_description, + std::unique_ptr<webrtc::SessionDescriptionInterface> + current_remote_description, RTCIceCandidatePlatform* candidate, webrtc::RTCError result, RTCVoidRequest* request) { // Inform tracker (chrome://webrtc-internals). @@ -1630,6 +1551,14 @@ handler_weak_ptr.get(), candidate, PeerConnectionTracker::SOURCE_REMOTE, result.ok()); } + // Update session descriptions. + if (handler_weak_ptr) { + handler_weak_ptr->OnSessionDescriptionsUpdated( + std::move(pending_local_description), + std::move(current_local_description), + std::move(pending_remote_description), + std::move(current_remote_description)); + } // Resolve promise. if (result.ok()) request->RequestSucceeded(); @@ -1639,12 +1568,26 @@ native_peer_connection_->AddIceCandidate( std::move(native_candidate), - [task_runner = task_runner_, + [pc = native_peer_connection_, task_runner = task_runner_, handler_weak_ptr = weak_factory_.GetWeakPtr(), tracker_weak_ptr = peer_connection_tracker_, candidate, persistent_request = WrapCrossThreadPersistent(request), callback_on_task_runner = std::move(callback_on_task_runner)](webrtc::RTCError result) { + // Grab a snapshot of all the session descriptions. AddIceCandidate may + // have modified the remote description. + std::unique_ptr<webrtc::SessionDescriptionInterface> + pending_local_description = + CopySessionDescription(pc->pending_local_description()); + std::unique_ptr<webrtc::SessionDescriptionInterface> + current_local_description = + CopySessionDescription(pc->current_local_description()); + std::unique_ptr<webrtc::SessionDescriptionInterface> + pending_remote_description = + CopySessionDescription(pc->pending_remote_description()); + std::unique_ptr<webrtc::SessionDescriptionInterface> + current_remote_description = + CopySessionDescription(pc->current_remote_description()); // This callback is invoked on the webrtc signaling thread (this is true // in production, not in rtc_peer_connection_handler_test.cc which uses // a fake |native_peer_connection_|). Jump back to the renderer thread. @@ -1652,8 +1595,12 @@ *task_runner, FROM_HERE, WTF::CrossThreadBindOnce( std::move(callback_on_task_runner), handler_weak_ptr, - tracker_weak_ptr, WrapCrossThreadPersistent(candidate), - std::move(result), std::move(persistent_request))); + tracker_weak_ptr, std::move(pending_local_description), + std::move(current_local_description), + std::move(pending_remote_description), + std::move(current_remote_description), + WrapCrossThreadPersistent(candidate), std::move(result), + std::move(persistent_request))); }); } @@ -2226,6 +2173,32 @@ } } +void RTCPeerConnectionHandler::OnSessionDescriptionsUpdated( + std::unique_ptr<webrtc::SessionDescriptionInterface> + pending_local_description, + std::unique_ptr<webrtc::SessionDescriptionInterface> + current_local_description, + std::unique_ptr<webrtc::SessionDescriptionInterface> + pending_remote_description, + std::unique_ptr<webrtc::SessionDescriptionInterface> + current_remote_description) { + if (!client_ || is_closed_) + return; + client_->DidChangeSessionDescriptions( + pending_local_description + ? CreateWebKitSessionDescription(pending_local_description.get()) + : nullptr, + current_local_description + ? CreateWebKitSessionDescription(current_local_description.get()) + : nullptr, + pending_remote_description + ? CreateWebKitSessionDescription(pending_remote_description.get()) + : nullptr, + current_remote_description + ? CreateWebKitSessionDescription(current_remote_description.get()) + : nullptr); +} + void RTCPeerConnectionHandler::OnSignalingChange( webrtc::PeerConnectionInterface::SignalingState new_state) { DCHECK(task_runner_->RunsTasksInCurrentSequence()); @@ -2709,35 +2682,6 @@ return dependency_factory_->GetWebRtcSignalingTaskRunner(); } -RTCSessionDescriptionPlatform* -RTCPeerConnectionHandler::GetRTCSessionDescriptionPlatformOnSignalingThread( - CrossThreadOnceFunction<const webrtc::SessionDescriptionInterface*()> - description_cb, - const char* log_text) { - // Since the webrtc::PeerConnectionInterface::*_description() functions - // return a pointer to a non-reference-counted object that lives on the - // signaling thread, we cannot fetch a pointer to it and use it directly - // here. - // Instead, we access the object completely on the signaling thread. - // Initializing |description| on the signaling thread is safe because we - // own it and wait for it to be initialized here. - - std::string type, sdp; - bool success = false; - RunSynchronousOnceClosureOnSignalingThread( - CrossThreadBindOnce( - &GetRTCSessionDescriptionPlatformFromSessionDescriptionCallback, - std::move(description_cb), CrossThreadUnretained(&type), - CrossThreadUnretained(&sdp), CrossThreadUnretained(&success)), - log_text); - - if (!success) - return nullptr; - - return MakeGarbageCollected<RTCSessionDescriptionPlatform>( - String::FromUTF8(type), String::FromUTF8(sdp)); -} - void RTCPeerConnectionHandler::ReportICEState( webrtc::PeerConnectionInterface::IceConnectionState new_state) { DCHECK(task_runner_->RunsTasksInCurrentSequence());
diff --git a/third_party/blink/renderer/modules/peerconnection/rtc_peer_connection_handler.h b/third_party/blink/renderer/modules/peerconnection/rtc_peer_connection_handler.h index f2fe772..17ca1e4 100644 --- a/third_party/blink/renderer/modules/peerconnection/rtc_peer_connection_handler.h +++ b/third_party/blink/renderer/modules/peerconnection/rtc_peer_connection_handler.h
@@ -154,13 +154,6 @@ virtual void SetRemoteDescription(blink::RTCVoidRequest* request, RTCSessionDescriptionPlatform* description); - virtual RTCSessionDescriptionPlatform* LocalDescription(); - virtual RTCSessionDescriptionPlatform* RemoteDescription(); - virtual RTCSessionDescriptionPlatform* CurrentLocalDescription(); - virtual RTCSessionDescriptionPlatform* CurrentRemoteDescription(); - virtual RTCSessionDescriptionPlatform* PendingLocalDescription(); - virtual RTCSessionDescriptionPlatform* PendingRemoteDescription(); - virtual const webrtc::PeerConnectionInterface::RTCConfiguration& GetConfiguration() const; virtual webrtc::RTCErrorType SetConfiguration( @@ -259,6 +252,15 @@ class SetLocalDescriptionRequest; friend class SetLocalDescriptionRequest; + void OnSessionDescriptionsUpdated( + std::unique_ptr<webrtc::SessionDescriptionInterface> + pending_local_description, + std::unique_ptr<webrtc::SessionDescriptionInterface> + current_local_description, + std::unique_ptr<webrtc::SessionDescriptionInterface> + pending_remote_description, + std::unique_ptr<webrtc::SessionDescriptionInterface> + current_remote_description); void OnSignalingChange( webrtc::PeerConnectionInterface::SignalingState new_state); void OnIceConnectionChange(
diff --git a/third_party/blink/renderer/modules/peerconnection/rtc_peer_connection_handler_test.cc b/third_party/blink/renderer/modules/peerconnection/rtc_peer_connection_handler_test.cc index 62b37513..bab93c40 100644 --- a/third_party/blink/renderer/modules/peerconnection/rtc_peer_connection_handler_test.cc +++ b/third_party/blink/renderer/modules/peerconnection/rtc_peer_connection_handler_test.cc
@@ -676,8 +676,6 @@ pc_handler_->SetLocalDescription(nullptr /*RTCVoidRequest*/, description); RunMessageLoopsUntilIdle(); - EXPECT_EQ(description->GetType(), pc_handler_->LocalDescription()->GetType()); - EXPECT_EQ(description->Sdp(), pc_handler_->LocalDescription()->Sdp()); std::string sdp_string; ASSERT_TRUE(mock_peer_connection_->local_description()); @@ -711,8 +709,6 @@ mock_dependency_factory_->SetFailToCreateSessionDescription(true); pc_handler_->SetLocalDescription(nullptr /*RTCVoidRequest*/, description); RunMessageLoopsUntilIdle(); - // A description that failed to be applied shouldn't be stored. - EXPECT_TRUE(!pc_handler_->LocalDescription()); } TEST_F(RTCPeerConnectionHandlerTest, setRemoteDescription) { @@ -730,9 +726,6 @@ pc_handler_->SetRemoteDescription(nullptr /*RTCVoidRequest*/, description); RunMessageLoopsUntilIdle(); - EXPECT_EQ(description->GetType(), - pc_handler_->RemoteDescription()->GetType()); - EXPECT_EQ(description->Sdp(), pc_handler_->RemoteDescription()->Sdp()); std::string sdp_string; ASSERT_TRUE(mock_peer_connection_->remote_description()); @@ -766,8 +759,6 @@ mock_dependency_factory_->SetFailToCreateSessionDescription(true); pc_handler_->SetRemoteDescription(nullptr /*RTCVoidRequest*/, description); RunMessageLoopsUntilIdle(); - // A description that failed to be applied shouldn't be stored. - EXPECT_TRUE(!pc_handler_->RemoteDescription()); } TEST_F(RTCPeerConnectionHandlerTest, setConfiguration) {
diff --git a/third_party/blink/renderer/modules/peerconnection/webrtc_set_description_observer.cc b/third_party/blink/renderer/modules/peerconnection/webrtc_set_description_observer.cc index f4f9a15d..77f65fb 100644 --- a/third_party/blink/renderer/modules/peerconnection/webrtc_set_description_observer.cc +++ b/third_party/blink/renderer/modules/peerconnection/webrtc_set_description_observer.cc
@@ -6,10 +6,19 @@ #include "base/bind.h" #include "base/check.h" -#include "third_party/webrtc/pc/sdp_utils.h" namespace blink { +std::unique_ptr<webrtc::SessionDescriptionInterface> CopySessionDescription( + const webrtc::SessionDescriptionInterface* description) { + if (!description) + return nullptr; + std::string sdp; + description->ToString(&sdp); + return std::unique_ptr<webrtc::SessionDescriptionInterface>( + webrtc::CreateSessionDescription(description->type(), sdp, nullptr)); +} + WebRtcSetDescriptionObserver::States::States() : signaling_state( webrtc::PeerConnectionInterface::SignalingState::kClosed) {} @@ -19,7 +28,9 @@ sctp_transport_state(std::move(other.sctp_transport_state)), transceiver_states(std::move(other.transceiver_states)), pending_local_description(std::move(other.pending_local_description)), - current_local_description(std::move(other.current_local_description)) {} + current_local_description(std::move(other.current_local_description)), + pending_remote_description(std::move(other.pending_remote_description)), + current_remote_description(std::move(other.current_remote_description)) {} WebRtcSetDescriptionObserver::States::~States() = default; @@ -30,6 +41,8 @@ transceiver_states = std::move(other.transceiver_states); pending_local_description = std::move(other.pending_local_description); current_local_description = std::move(other.current_local_description); + pending_remote_description = std::move(other.pending_remote_description); + current_remote_description = std::move(other.current_remote_description); return *this; } @@ -81,22 +94,26 @@ transceiver_state_surfacer.Initialize(pc_, track_adapter_map_, std::move(transceivers)); std::unique_ptr<webrtc::SessionDescriptionInterface> - pending_local_description = pc_->pending_local_description() - ? webrtc::CloneSessionDescription( - pc_->pending_local_description()) - : nullptr; + pending_local_description = + CopySessionDescription(pc_->pending_local_description()); std::unique_ptr<webrtc::SessionDescriptionInterface> - current_local_description = pc_->current_local_description() - ? webrtc::CloneSessionDescription( - pc_->current_local_description()) - : nullptr; + current_local_description = + CopySessionDescription(pc_->current_local_description()); + std::unique_ptr<webrtc::SessionDescriptionInterface> + pending_remote_description = + CopySessionDescription(pc_->pending_remote_description()); + std::unique_ptr<webrtc::SessionDescriptionInterface> + current_remote_description = + CopySessionDescription(pc_->current_remote_description()); main_task_runner_->PostTask( FROM_HERE, base::BindOnce(&WebRtcSetDescriptionObserverHandlerImpl:: OnSetDescriptionCompleteOnMainThread, this, std::move(error), pc_->signaling_state(), std::move(transceiver_state_surfacer), std::move(pending_local_description), - std::move(current_local_description))); + std::move(current_local_description), + std::move(pending_remote_description), + std::move(current_remote_description))); } void WebRtcSetDescriptionObserverHandlerImpl:: @@ -107,7 +124,11 @@ std::unique_ptr<webrtc::SessionDescriptionInterface> pending_local_description, std::unique_ptr<webrtc::SessionDescriptionInterface> - current_local_description) { + current_local_description, + std::unique_ptr<webrtc::SessionDescriptionInterface> + pending_remote_description, + std::unique_ptr<webrtc::SessionDescriptionInterface> + current_remote_description) { CHECK(main_task_runner_->BelongsToCurrentThread()); WebRtcSetDescriptionObserver::States states; states.signaling_state = signaling_state; @@ -116,6 +137,8 @@ states.transceiver_states = transceiver_state_surfacer.ObtainStates(); states.pending_local_description = std::move(pending_local_description); states.current_local_description = std::move(current_local_description); + states.pending_remote_description = std::move(pending_remote_description); + states.current_remote_description = std::move(current_remote_description); observer_->OnSetDescriptionComplete(std::move(error), std::move(states)); }
diff --git a/third_party/blink/renderer/modules/peerconnection/webrtc_set_description_observer.h b/third_party/blink/renderer/modules/peerconnection/webrtc_set_description_observer.h index a8914d2..196348e2 100644 --- a/third_party/blink/renderer/modules/peerconnection/webrtc_set_description_observer.h +++ b/third_party/blink/renderer/modules/peerconnection/webrtc_set_description_observer.h
@@ -30,6 +30,14 @@ namespace blink { +// Copies the session description. +// Note: At the time of writing, third_party/webrtc/pc/sdp_utils.h's +// webrtc::CloneSessionDescription() creates a copy that does not include +// candidates added with AddIceCandidate. This is why we need our own copy +// function, which copies everything. +std::unique_ptr<webrtc::SessionDescriptionInterface> CopySessionDescription( + const webrtc::SessionDescriptionInterface* description); + // The blink layer correspondent of the setLocalDescription() observer // (webrtc::SetSessionDescriptionObserver) and setRemoteDescription() observer // (webrtc::SetRemoteDescriptionObserverInterface). The implementation should @@ -51,15 +59,14 @@ webrtc::PeerConnectionInterface::SignalingState signaling_state; blink::WebRTCSctpTransportSnapshot sctp_transport_state; std::vector<blink::RtpTransceiverState> transceiver_states; - // For now, the session descriptions are only surfaced for the sake of - // showing up in chrome://webrtc-internals/ when implicit - // setLocalDescription() resolves. - // TODO(https://crbug.com/788558): Surface all states to blink at the same, - // time, including [current/pending][Local/Remote]Description. std::unique_ptr<webrtc::SessionDescriptionInterface> pending_local_description; std::unique_ptr<webrtc::SessionDescriptionInterface> current_local_description; + std::unique_ptr<webrtc::SessionDescriptionInterface> + pending_remote_description; + std::unique_ptr<webrtc::SessionDescriptionInterface> + current_remote_description; DISALLOW_COPY_AND_ASSIGN(States); }; @@ -117,7 +124,11 @@ std::unique_ptr<webrtc::SessionDescriptionInterface> pending_local_description, std::unique_ptr<webrtc::SessionDescriptionInterface> - current_local_description); + current_local_description, + std::unique_ptr<webrtc::SessionDescriptionInterface> + pending_remote_description, + std::unique_ptr<webrtc::SessionDescriptionInterface> + current_remote_description); scoped_refptr<base::SingleThreadTaskRunner> main_task_runner_; scoped_refptr<base::SingleThreadTaskRunner> signaling_task_runner_;
diff --git a/third_party/blink/renderer/platform/BUILD.gn b/third_party/blink/renderer/platform/BUILD.gn index 84ec6452..08e980ba 100644 --- a/third_party/blink/renderer/platform/BUILD.gn +++ b/third_party/blink/renderer/platform/BUILD.gn
@@ -1381,6 +1381,8 @@ "text/locale_win.cc", "text/locale_win.h", "text/mac/hyphenation_mac.cc", + "text/mathml_operator_dictionary.cc", + "text/mathml_operator_dictionary.h", "text/platform_locale.cc", "text/platform_locale.h", "text/segmented_string.cc", @@ -2000,6 +2002,7 @@ "text/hyphenation_test.cc", "text/icu_error_test.cc", "text/layout_locale_test.cc", + "text/mathml_operator_dictionary_test.cc", "text/platform_locale_test.cc", "text/segmented_string_test.cc", "text/suffix_tree_test.cc",
diff --git a/third_party/blink/renderer/platform/exported/web_runtime_features.cc b/third_party/blink/renderer/platform/exported/web_runtime_features.cc index ac930690..9b17457 100644 --- a/third_party/blink/renderer/platform/exported/web_runtime_features.cc +++ b/third_party/blink/renderer/platform/exported/web_runtime_features.cc
@@ -435,10 +435,6 @@ RuntimeEnabledFeatures::SetV8IdleTasksEnabled(enable); } -void WebRuntimeFeatures::EnableReducedReferrerGranularity(bool enable) { - RuntimeEnabledFeatures::SetReducedReferrerGranularityEnabled(enable); -} - void WebRuntimeFeatures::EnablePushMessaging(bool enable) { RuntimeEnabledFeatures::SetPushMessagingEnabled(enable); }
diff --git a/third_party/blink/renderer/platform/graphics/image.h b/third_party/blink/renderer/platform/graphics/image.h index 0ab24e7..35a6c4ec 100644 --- a/third_party/blink/renderer/platform/graphics/image.h +++ b/third_party/blink/renderer/platform/graphics/image.h
@@ -38,7 +38,6 @@ #include "third_party/blink/renderer/platform/graphics/image_observer.h" #include "third_party/blink/renderer/platform/graphics/image_orientation.h" #include "third_party/blink/renderer/platform/graphics/paint/paint_image.h" -#include "third_party/blink/renderer/platform/graphics/paint/paint_record.h" #include "third_party/blink/renderer/platform/heap/persistent.h" #include "third_party/blink/renderer/platform/platform_export.h" #include "third_party/blink/renderer/platform/wtf/forward.h" @@ -60,7 +59,6 @@ class FloatRect; class GraphicsContext; class Image; -class KURL; class WebGraphicsContext3DProvider; class WebGraphicsContext3DProviderWrapper; @@ -249,15 +247,6 @@ return nullptr; } - virtual sk_sp<PaintRecord> PaintRecordForContainer( - const KURL& url, - const IntSize& container_size, - const IntRect& draw_src_rect, - const IntRect& draw_dst_rect, - bool flip_y) { - return nullptr; - } - PaintImage::Id paint_image_id() const { return stable_image_id_; } // Returns an SkBitmap that is a copy of the image's current frame.
diff --git a/third_party/blink/renderer/platform/graphics/placeholder_image.h b/third_party/blink/renderer/platform/graphics/placeholder_image.h index c6a6f4ff..dd3e3f55 100644 --- a/third_party/blink/renderer/platform/graphics/placeholder_image.h +++ b/third_party/blink/renderer/platform/graphics/placeholder_image.h
@@ -12,6 +12,7 @@ #include "third_party/blink/renderer/platform/geometry/int_size.h" #include "third_party/blink/renderer/platform/graphics/image.h" #include "third_party/blink/renderer/platform/graphics/image_orientation.h" +#include "third_party/blink/renderer/platform/graphics/paint/paint_record.h" #include "third_party/blink/renderer/platform/wtf/text/wtf_string.h" #include "third_party/skia/include/core/SkImage.h" #include "third_party/skia/include/core/SkRefCnt.h"
diff --git a/third_party/blink/renderer/platform/peerconnection/rtc_peer_connection_handler_client.h b/third_party/blink/renderer/platform/peerconnection/rtc_peer_connection_handler_client.h index f7f61d75..1821e68b 100644 --- a/third_party/blink/renderer/platform/peerconnection/rtc_peer_connection_handler_client.h +++ b/third_party/blink/renderer/platform/peerconnection/rtc_peer_connection_handler_client.h
@@ -43,8 +43,9 @@ namespace blink { class RTCIceCandidatePlatform; -class RTCRtpTransceiverPlatform; class RTCRtpReceiverPlatform; +class RTCRtpTransceiverPlatform; +class RTCSessionDescriptionPlatform; struct PLATFORM_EXPORT WebRTCSctpTransportSnapshot { rtc::scoped_refptr<webrtc::SctpTransportInterface> transport; @@ -66,6 +67,11 @@ const String& url, int error_code, const String& error_text) = 0; + virtual void DidChangeSessionDescriptions( + RTCSessionDescriptionPlatform* pending_local_description, + RTCSessionDescriptionPlatform* current_local_description, + RTCSessionDescriptionPlatform* pending_remote_description, + RTCSessionDescriptionPlatform* current_remote_description) = 0; virtual void DidChangeSignalingState( webrtc::PeerConnectionInterface::SignalingState) = 0; virtual void DidChangeIceGatheringState(
diff --git a/third_party/blink/renderer/platform/runtime_enabled_features.json5 b/third_party/blink/renderer/platform/runtime_enabled_features.json5 index dd91417..05ed61ff 100644 --- a/third_party/blink/renderer/platform/runtime_enabled_features.json5 +++ b/third_party/blink/renderer/platform/runtime_enabled_features.json5
@@ -1560,10 +1560,6 @@ name: "RawClipboard", }, { - name: "ReducedReferrerGranularity", - status: "experimental", - }, - { name: "RemotePlayback", status: "stable", },
diff --git a/third_party/blink/renderer/platform/text/mathml_operator_dictionary.cc b/third_party/blink/renderer/platform/text/mathml_operator_dictionary.cc new file mode 100644 index 0000000..16a1e90 --- /dev/null +++ b/third_party/blink/renderer/platform/text/mathml_operator_dictionary.cc
@@ -0,0 +1,199 @@ +// Copyright 2020 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "third_party/blink/renderer/platform/text/mathml_operator_dictionary.h" + +#include "third_party/blink/renderer/platform/wtf/text/character_names.h" + +namespace blink { + +namespace { + +// https://mathml-refresh.github.io/mathml-core/#operator-dictionary-compact-special-tables +const char* operators_2_ascii_chars[] = { + "!!", "!=", "&&", "**", "*=", "++", "+=", "--", "-=", "->", + "..", "//", "/=", ":=", "<=", "<>", "==", ">=", "||"}; + +// https://mathml-refresh.github.io/mathml-core/#operator-dictionary-categories-hexa-table +struct EntryRange { + uint16_t entry; + unsigned range_bounds_delta : 4; +}; +static inline uint16_t ExtractKey(const EntryRange& range) { + return range.entry & 0x3FFF; +} +static inline uint16_t ExtractCategory(const EntryRange& range) { + return range.entry >> 12; +} + +// The following representation is taken from the spec, and reduces storage +// requirements by mapping codepoints and category to better make use of the +// available bytes. For details see +// https://mathml-refresh.github.io/mathml-core/#operator-dictionary. +static const EntryRange compact_dictionary[] = { + {0x8025, 0}, {0x802A, 0}, {0x402B, 0}, {0x402D, 0}, {0x802E, 0}, + {0x402F, 0}, {0x803F, 1}, {0xC05C, 0}, {0x805E, 1}, {0x807C, 0}, + {0x40B1, 0}, {0x80B7, 0}, {0x80D7, 0}, {0x40F7, 0}, {0x4322, 0}, + {0x8323, 0}, {0x832B, 0}, {0x832F, 0}, {0x8332, 0}, {0x8422, 0}, + {0x8443, 0}, {0x4444, 0}, {0xC461, 3}, {0x0590, 9}, {0x059C, 15}, + {0x05AC, 1}, {0x05AF, 6}, {0x05B9, 0}, {0x05BC, 15}, {0x05CC, 0}, + {0x05D0, 13}, {0x05E0, 15}, {0x05F0, 0}, {0x05F3, 0}, {0x05F5, 1}, + {0x05FD, 2}, {0x8606, 0}, {0x860E, 0}, {0x4612, 4}, {0x8617, 0}, + {0x4618, 0}, {0x4624, 0}, {0x4627, 3}, {0x4636, 0}, {0x4638, 0}, + {0x863F, 1}, {0x468C, 3}, {0x4693, 3}, {0x8697, 0}, {0x4698, 0}, + {0x8699, 0}, {0x469D, 2}, {0x86A0, 1}, {0x46BB, 2}, {0x46C4, 0}, + {0x86C5, 0}, {0x46C6, 0}, {0x86C7, 0}, {0x86C9, 3}, {0x46CE, 1}, + {0x46D2, 1}, {0x8705, 1}, {0x89A0, 1}, {0x89AA, 1}, {0x89AD, 4}, + {0x4B95, 2}, {0x8BCB, 0}, {0x8BCD, 0}, {0x0BF0, 1}, {0x4BF4, 0}, + {0x0BF5, 10}, {0x0D0A, 6}, {0x0D12, 1}, {0x0D21, 1}, {0x0D4E, 15}, + {0x0D5E, 3}, {0x0D6E, 1}, {0x8D81, 1}, {0x8D99, 1}, {0x8DB5, 0}, + {0x4DBC, 0}, {0x8DC2, 1}, {0x8DC9, 4}, {0x8DD8, 1}, {0x8DDB, 0}, + {0x8DDF, 1}, {0x8DE2, 0}, {0x8DE7, 6}, {0x4DF6, 0}, {0x8DF8, 3}, + {0x8E1D, 4}, {0x4E22, 12}, {0x8E2F, 8}, {0x4E38, 2}, {0x8E3B, 2}, + {0x8E3F, 0}, {0x4E40, 15}, {0x8E50, 0}, {0x4E51, 15}, {0x4E61, 2}, + {0x4EDA, 1}, {0x8EDC, 1}, {0x4EFB, 0}, {0x4EFD, 0}, {0x8EFE, 0}, + {0x4F32, 0}, {0x0F45, 1}, {0x1021, 0}, {0x5028, 0}, {0x102B, 0}, + {0x102D, 0}, {0x505B, 0}, {0x507B, 1}, {0x10AC, 0}, {0x10B1, 0}, + {0x1332, 0}, {0x5416, 0}, {0x1418, 0}, {0x141C, 0}, {0x1600, 1}, + {0x1603, 1}, {0x1607, 0}, {0xD60F, 2}, {0x1612, 1}, {0x161F, 3}, + {0x962B, 8}, {0x163C, 0}, {0x16BE, 1}, {0xD6C0, 3}, {0x5708, 0}, + {0x570A, 0}, {0x1710, 0}, {0x1719, 0}, {0x5729, 0}, {0x5B72, 0}, + {0x1B95, 1}, {0x1BC0, 0}, {0x5BE6, 0}, {0x5BE8, 0}, {0x5BEA, 0}, + {0x5BEC, 0}, {0x5BEE, 0}, {0x5D80, 0}, {0x5D83, 0}, {0x5D85, 0}, + {0x5D87, 0}, {0x5D89, 0}, {0x5D8B, 0}, {0x5D8D, 0}, {0x5D8F, 0}, + {0x5D91, 0}, {0x5D93, 0}, {0x5D95, 0}, {0x5D97, 0}, {0x1D9B, 15}, + {0x1DAB, 4}, {0x5DFC, 0}, {0xDE00, 10}, {0x9E0B, 15}, {0x9E1B, 1}, + {0x1EEC, 1}, {0xDEFC, 0}, {0xDEFF, 0}, {0x2021, 1}, {0x2026, 1}, + {0x6029, 0}, {0x605D, 0}, {0xA05E, 1}, {0x2060, 0}, {0x607C, 1}, + {0xA07E, 0}, {0x20A8, 0}, {0xA0AF, 0}, {0x20B0, 0}, {0x20B2, 2}, + {0x20B8, 1}, {0xA2C6, 1}, {0xA2C9, 0}, {0x22CA, 1}, {0xA2CD, 0}, + {0x22D8, 2}, {0xA2DC, 0}, {0x22DD, 0}, {0xA2F7, 0}, {0xA302, 0}, + {0x2311, 0}, {0x2320, 0}, {0x2325, 0}, {0x2327, 0}, {0x232A, 0}, + {0x2332, 0}, {0x6416, 0}, {0x2419, 2}, {0x241D, 2}, {0x2432, 5}, + {0xA43E, 0}, {0x2457, 0}, {0x24DB, 1}, {0x6709, 0}, {0x670B, 0}, + {0xA722, 1}, {0x672A, 0}, {0xA7B4, 1}, {0x27CD, 0}, {0xA7DC, 5}, + {0x6B73, 0}, {0x6BE7, 0}, {0x6BE9, 0}, {0x6BEB, 0}, {0x6BED, 0}, + {0x6BEF, 0}, {0x6D80, 0}, {0x6D84, 0}, {0x6D86, 0}, {0x6D88, 0}, + {0x6D8A, 0}, {0x6D8C, 0}, {0x6D8E, 0}, {0x6D90, 0}, {0x6D92, 0}, + {0x6D94, 0}, {0x6D96, 0}, {0x6D98, 0}, {0x6DFD, 0}}; + +} // namespace + +MathMLOperatorDictionaryCategory FindCategory( + const String& content, + MathMLOperatorDictionaryForm form) { + DCHECK(!content.Is8Bit()); + // Handle special cases and calculate a BMP code point used for the key. + uint16_t key{0}; + if (content.length() == 1) { + UChar32 character = content[0]; + if (character < kCombiningMinusSignBelow || + character > kGreekCapitalReversedDottedLunateSigmaSymbol) { + // Accept BMP characters that are not in the ranges where 2-ASCII-chars + // operators are mapped below. + key = character; + } + } else if (content.length() == 2) { + UChar32 character = content.CharacterStartingAt(0); + if (character == kArabicMathematicalOperatorMeemWithHahWithTatweel || + character == kArabicMathematicalOperatorHahWithDal) { + // Special handling of non-BMP Arabic operators. + if (form == MathMLOperatorDictionaryForm::kPostfix) + return MathMLOperatorDictionaryCategory::kI; + return MathMLOperatorDictionaryCategory::kNone; + } else if (content[1] == kCombiningLongSolidusOverlay || + content[1] == kCombiningLongVerticalLineOverlay) { + // If the second character is COMBINING LONG SOLIDUS OVERLAY or + // COMBINING LONG VERTICAL LINE OVERLAY, then use the property of the + // first character. + key = content[0]; + } else { + // Perform a binary search for 2-ASCII-chars operators. + const char** last = + operators_2_ascii_chars + base::size(operators_2_ascii_chars); + const char** entry = std::lower_bound( + operators_2_ascii_chars, last, content, + [](const char* lhs, const String& rhs) -> bool { + return lhs[0] < rhs[0] || (lhs[0] == rhs[0] && lhs[1] < rhs[1]); + }); + if (entry != last && content == *entry) + key = kCombiningMinusSignBelow + (entry - operators_2_ascii_chars); + } + } + + if (!key) + return MathMLOperatorDictionaryCategory::kNone; + + // Handle special categories that are not encoded in the compact dictionary. + // https://mathml-refresh.github.io/mathml-core/#operator-dictionary-categories-values + if (form == MathMLOperatorDictionaryForm::kPrefix && + ((kDoubleStruckItalicCapitalDCharacter <= key && + key <= kDoubleStruckItalicSmallDCharacter) || + key == kPartialDifferential || + (kSquareRootCharacter <= key && key <= kFourthRootCharacter))) { + return MathMLOperatorDictionaryCategory::kK; + } + if (form == MathMLOperatorDictionaryForm::kInfix && + (key == kComma || key == kColon || key == kSemiColon)) { + return MathMLOperatorDictionaryCategory::kM; + } + // Calculate the key for the compact dictionary. + if (kEnQuadCharacter <= key && key <= kHellschreiberPauseSymbol) { + // Map above range (U+2000–U+2BFF) to (U+0400-0x0FFF) to fit into + // 12 bits by decrementing with (U+2000 - U+0400) == 0x1C00. + key -= 0x1C00; + } else if (key > kGreekCapitalReversedDottedLunateSigmaSymbol) { + return MathMLOperatorDictionaryCategory::kNone; + } + // Bitmasks used to set form 2-bits (infix=00, prefix=01, postfix=10). + if (form == MathMLOperatorDictionaryForm::kPrefix) + key |= 0x1000; + else if (form == MathMLOperatorDictionaryForm::kPostfix) + key |= 0x2000; + DCHECK_LE(key, 0x2FFF); + + // Perform a binary search on the compact dictionary. + const EntryRange* entry_range = std::upper_bound( + compact_dictionary, compact_dictionary + base::size(compact_dictionary), + key, [](uint16_t lhs, EntryRange rhs) -> bool { + return lhs < ExtractKey(rhs); + }); + + if (entry_range == compact_dictionary) + return MathMLOperatorDictionaryCategory::kNone; + entry_range--; + + DCHECK_LE(ExtractKey(*entry_range), key); + if (key > (ExtractKey(*entry_range) + entry_range->range_bounds_delta)) + return MathMLOperatorDictionaryCategory::kNone; + + // An entry is found: set the properties according the category. + // https://mathml-refresh.github.io/mathml-core/#operator-dictionary-categories-values + switch (ExtractCategory(*entry_range)) { + case 0x0: + return MathMLOperatorDictionaryCategory::kA; + case 0x4: + return MathMLOperatorDictionaryCategory::kB; + case 0x8: + return MathMLOperatorDictionaryCategory::kC; + case 0x1: + case 0x2: + case 0xC: + return MathMLOperatorDictionaryCategory::kDorEorL; + case 0x5: + case 0x6: + return MathMLOperatorDictionaryCategory::kForG; + case 0x9: + return MathMLOperatorDictionaryCategory::kH; + case 0xA: + return MathMLOperatorDictionaryCategory::kI; + case 0xD: + return MathMLOperatorDictionaryCategory::kJ; + } + + NOTREACHED(); + return MathMLOperatorDictionaryCategory::kNone; +} + +} // namespace blink
diff --git a/third_party/blink/renderer/platform/text/mathml_operator_dictionary.h b/third_party/blink/renderer/platform/text/mathml_operator_dictionary.h new file mode 100644 index 0000000..27fd8cc6 --- /dev/null +++ b/third_party/blink/renderer/platform/text/mathml_operator_dictionary.h
@@ -0,0 +1,39 @@ +// Copyright 2020 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_TEXT_MATHML_OPERATOR_DICTIONARY_H_ +#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_TEXT_MATHML_OPERATOR_DICTIONARY_H_ + +#include "third_party/blink/renderer/platform/platform_export.h" + +#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h" + +namespace blink { + +enum class MathMLOperatorDictionaryCategory : uint8_t { + kNone, + kA, + kB, + kC, + kDorEorL, + kForG, + kH, + kI, + kJ, + kK, + kM, + kUndefined = 15 +}; + +enum MathMLOperatorDictionaryForm { kInfix, kPrefix, kPostfix }; + +// FindCategory takes a UTF-16 string and form (infix, prefix, postfix) as input +// and returns the operator dictionary category for this pair, see: +// https://mathml-refresh.github.io/mathml-core/#operator-dictionary +PLATFORM_EXPORT MathMLOperatorDictionaryCategory +FindCategory(const String& content, MathMLOperatorDictionaryForm); + +} // namespace blink + +#endif // THIRD_PARTY_BLINK_RENDERER_CORE_MATHML_MATHML_OPERATOR_ELEMENT_H_
diff --git a/third_party/blink/renderer/platform/text/mathml_operator_dictionary_test.cc b/third_party/blink/renderer/platform/text/mathml_operator_dictionary_test.cc new file mode 100644 index 0000000..e2d5b43 --- /dev/null +++ b/third_party/blink/renderer/platform/text/mathml_operator_dictionary_test.cc
@@ -0,0 +1,215 @@ +// Copyright 2020 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "third_party/blink/renderer/platform/text/mathml_operator_dictionary.h" + +#include "testing/gtest/include/gtest/gtest.h" +#include "third_party/blink/renderer/platform/wtf/text/character_names.h" +#include "third_party/blink/renderer/platform/wtf/text/string_builder.h" + +namespace blink { + +static const UChar32 category_a[]{ + 0x2190, 0x2191, 0x2192, 0x2193, 0x2194, 0x2195, 0x2196, 0x2197, 0x2198, + 0x2199, 0x219C, 0x219D, 0x219E, 0x219F, 0x21A0, 0x21A1, 0x21A2, 0x21A3, + 0x21A4, 0x21A5, 0x21A6, 0x21A7, 0x21A8, 0x21A9, 0x21AA, 0x21AB, 0x21AC, + 0x21BC, 0x21BD, 0x21BE, 0x21BF, 0x21C0, 0x21C1, 0x21C2, 0x21C3, 0x21C4, + 0x21C5, 0x21C6, 0x21C7, 0x21C8, 0x21C9, 0x21CA, 0x21CB, 0x21CC, 0x21D0, + 0x21D1, 0x21D2, 0x21D3, 0x21D4, 0x21D5, 0x21D6, 0x21D7, 0x21D8, 0x21D9, + 0x21DA, 0x21DB, 0x21DC, 0x21DD, 0x21E0, 0x21E1, 0x21E2, 0x21E3, 0x21E4, + 0x21E5, 0x21E6, 0x21E7, 0x21E8, 0x21E9, 0x21EA, 0x21EB, 0x21EC, 0x21ED, + 0x21EE, 0x21EF, 0x21F0, 0x21F3, 0x21F5, 0x21F6, 0x21FD, 0x21FE, 0x21FF, + 0x27F0, 0x27F1, 0x27F5, 0x27F6, 0x27F7, 0x27F8, 0x27F9, 0x27FA, 0x27FB, + 0x27FC, 0x27FD, 0x27FE, 0x27FF, 0x2952, 0x290A, 0x290B, 0x290C, 0x290D, + 0x290E, 0x290F, 0x2910, 0x2912, 0x2913, 0x2921, 0x2922, 0x294E, 0x294F, + 0x2950, 0x2951, 0x2952, 0x2953, 0x2954, 0x2955, 0x2956, 0x2957, 0x2958, + 0x2959, 0x295A, 0x295B, 0x295C, 0x295D, 0x295E, 0x295F, 0x2960, 0x2961, + 0x296E, 0x296F, 0x2B45, 0x2B46}; + +static const UChar32 category_b[]{ + 0x002B, 0x002D, 0x002F, 0x00B1, 0x00F7, 0x0322, 0x2044, 0x2212, 0x2213, + 0x2214, 0x2215, 0x2216, 0x2218, 0x2224, 0x2227, 0x2228, 0x2229, 0x222A, + 0x2236, 0x2238, 0x228C, 0x228D, 0x228E, 0x228F, 0x2293, 0x2294, 0x2295, + 0x2296, 0x2298, 0x229D, 0x229E, 0x229F, 0x22BB, 0x22BC, 0x22BD, 0x22C4, + 0x22C6, 0x22CE, 0x22CF, 0x22D2, 0x22D3, 0x2795, 0x2796, 0x2797, 0x27F4, + 0x29BC, 0x29F6, 0x2A22, 0x2A23, 0x2A24, 0x2A25, 0x2A26, 0x2A27, 0x2A28, + 0x2A29, 0x2A2A, 0x2A2B, 0x2A2C, 0x2A2D, 0x2A2E, 0x2A38, 0x2A39, 0x2A3A, + 0x2A40, 0x2A41, 0x2A42, 0x2A43, 0x2A44, 0x2A45, 0x2A46, 0x2A47, 0x2A48, + 0x2A49, 0x2A4A, 0x2A4B, 0x2A4C, 0x2A4D, 0x2A4E, 0x2A4F, 0x2A51, 0x2A52, + 0x2A53, 0x2A54, 0x2A55, 0x2A56, 0x2A57, 0x2A58, 0x2A59, 0x2A5A, 0x2A5B, + 0x2A5C, 0x2A5D, 0x2A5E, 0x2A5F, 0x2A60, 0x2A61, 0x2A62, 0x2A63, 0x2ADA, + 0x2ADB, 0x2AFB, 0x2AFD, 0x2B32, +}; + +static const UChar32 category_c[]{ + 0x0025, 0x002A, 0x002E, 0x003F, 0x0040, 0x005E, 0x005F, 0x007C, 0x00B7, + 0x00D7, 0x0323, 0x032B, 0x032F, 0x0332, 0x2022, 0x2043, 0x2206, 0x220E, + 0x2217, 0x223F, 0x2240, 0x2297, 0x2299, 0x22A0, 0x22A1, 0x22C5, 0x22C7, + 0x22C9, 0x22CA, 0x22CB, 0x22CC, 0x2305, 0x2306, 0x25A0, 0x25A1, 0x25AA, + 0x25AB, 0x25AD, 0x25AE, 0x25AF, 0x25B0, 0x25B1, 0x27CB, 0x27CD, 0x2981, + 0x2982, 0x2999, 0x299A, 0x29B5, 0x29C2, 0x29C3, 0x29C9, 0x29CA, 0x29CB, + 0x29CC, 0x29CD, 0x29D8, 0x29D9, 0x29DB, 0x29DF, 0x29E0, 0x29E2, 0x29E7, + 0x29E8, 0x29E9, 0x29EA, 0x29EB, 0x29EC, 0x29ED, 0x29F8, 0x29F9, 0x29FA, + 0x29FB, 0x2A1D, 0x2A1E, 0x2A1F, 0x2A20, 0x2A21, 0x2A2F, 0x2A30, 0x2A31, + 0x2A32, 0x2A33, 0x2A34, 0x2A35, 0x2A36, 0x2A37, 0x2A3B, 0x2A3C, 0x2A3D, + 0x2A3F, 0x2A50, 0x2ADC, 0x2ADD, 0x2AFE, +}; + +static const UChar32 category_d[]{ + 0x0021, 0x002B, 0x002D, 0x00AC, 0x00B1, 0x0332, 0x2018, 0x201C, 0x2200, + 0x2201, 0x2203, 0x2204, 0x2207, 0x2212, 0x2213, 0x221F, 0x2220, 0x2221, + 0x2222, 0x223C, 0x22BE, 0x22BF, 0x2310, 0x2319, 0x2795, 0x2796, 0x27C0, + 0x299B, 0x299C, 0x299D, 0x299E, 0x299F, 0x29A0, 0x29A1, 0x29A2, 0x29A3, + 0x29A4, 0x29A5, 0x29A6, 0x29A7, 0x29A8, 0x29A9, 0x29AA, 0x29AB, 0x29AC, + 0x29AD, 0x29AE, 0x29AF, 0x2AEC, 0x2AED, +}; + +static const UChar32 category_e[]{ + 0x0021, 0x0022, 0x0026, 0x0027, 0x0060, 0x00A8, 0x00B0, 0x00B2, + 0x00B3, 0x00B4, 0x00B8, 0x00B9, 0x02CA, 0x02CB, 0x02D8, 0x02D9, + 0x02DA, 0x02DD, 0x0311, 0x0320, 0x0325, 0x0327, 0x032A, 0x0332, + 0x2019, 0x201A, 0x201B, 0x201D, 0x201E, 0x201F, 0x2032, 0x2033, + 0x2034, 0x2035, 0x2036, 0x2037, 0x2057, 0x20DB, 0x20DC, 0x23CD, +}; + +static const UChar32 category_f[]{ + 0x0028, 0x005B, 0x007B, 0x007C, 0x2016, 0x2308, 0x230A, 0x2329, 0x2772, + 0x27E6, 0x27E8, 0x27EA, 0x27EC, 0x27EE, 0x2980, 0x2983, 0x2985, 0x2987, + 0x2989, 0x298B, 0x298D, 0x298F, 0x2991, 0x2993, 0x2995, 0x2997, 0x29FC, +}; + +static const UChar32 category_g[]{ + 0x0029, 0x005D, 0x007C, 0x007D, 0x2016, 0x2309, 0x230B, 0x232A, 0x2773, + 0x27E7, 0x27E9, 0x27EB, 0x27ED, 0x27EF, 0x2980, 0x2984, 0x2986, 0x2988, + 0x298A, 0x298C, 0x298E, 0x2990, 0x2992, 0x2994, 0x2996, 0x2998, 0x29FD, +}; + +static const UChar32 category_h[]{ + 0x222B, 0x222C, 0x222D, 0x222E, 0x222F, 0x2230, 0x2231, 0x2232, 0x2233, + 0x2A0B, 0x2A0C, 0x2A0D, 0x2A0E, 0x2A0F, 0x2A10, 0x2A11, 0x2A12, 0x2A13, + 0x2A14, 0x2A15, 0x2A16, 0x2A17, 0x2A18, 0x2A19, 0x2A1A, 0x2A1B, 0x2A1C}; + +static const UChar32 category_i[]{ + 0x005E, 0x005F, 0x007E, 0x00AF, 0x02C6, 0x02C7, 0x02C9, 0x02CD, + 0x02DC, 0x02F7, 0x0302, 0x203E, 0x2322, 0x2323, 0x23B4, 0x23B5, + 0x23DC, 0x23DD, 0x23DE, 0x23DF, 0x23E0, 0x23E1, +}; + +static const UChar32 category_j[]{ + 0x220F, 0x2210, 0x2211, 0x22C0, 0x22C1, 0x22C2, 0x22C3, + 0x2A00, 0x2A01, 0x2A02, 0x2A03, 0x2A04, 0x2A05, 0x2A06, + 0x2A07, 0x2A08, 0x2A09, 0x2A0A, 0x2AFC, 0x2AFF, +}; + +static const UChar32 category_k[]{ + 0x2145, 0x2146, 0x2202, 0x221A, 0x221B, 0x221C, +}; + +static const UChar32 category_l[]{ + 0x005C, 0x2061, 0x2062, 0x2063, 0x2064, +}; + +static const UChar32 category_m[]{ + 0x002C, + 0x003A, + 0x003B, +}; + +template <typename T, size_t N> +bool IsInCategory(const T (&table)[N], UChar32 character) { + return std::binary_search(table, table + base::size(table), character); +} + +String FromUChar32(UChar32 c) { + StringBuilder input; + input.Append(c); + return input.ToString(); +} + +TEST(MathOperatorDictionaryTest, Infix) { + for (UChar32 ch = 0; ch < kMaxCodepoint; ch++) { + String s = FromUChar32(ch); + s.Ensure16Bit(); + if (ch >= kCombiningMinusSignBelow && + ch <= kGreekCapitalReversedDottedLunateSigmaSymbol) { + EXPECT_TRUE(FindCategory(s, MathMLOperatorDictionaryForm::kInfix) == + MathMLOperatorDictionaryCategory::kNone); + } else if (IsInCategory(category_a, ch)) { + EXPECT_TRUE(FindCategory(s, MathMLOperatorDictionaryForm::kInfix) == + MathMLOperatorDictionaryCategory::kA); + } else if (IsInCategory(category_b, ch)) { + EXPECT_TRUE(FindCategory(s, MathMLOperatorDictionaryForm::kInfix) == + MathMLOperatorDictionaryCategory::kB); + } else if (IsInCategory(category_c, ch)) { + EXPECT_TRUE(FindCategory(s, MathMLOperatorDictionaryForm::kInfix) == + MathMLOperatorDictionaryCategory::kC); + } else if (IsInCategory(category_l, ch)) { + EXPECT_TRUE(FindCategory(s, MathMLOperatorDictionaryForm::kInfix) == + MathMLOperatorDictionaryCategory::kDorEorL); + } else if (IsInCategory(category_m, ch)) { + EXPECT_TRUE(FindCategory(s, MathMLOperatorDictionaryForm::kInfix) == + MathMLOperatorDictionaryCategory::kM); + } + } +} + +TEST(MathOperatorDictionaryTest, Prefix) { + for (UChar32 ch = 0; ch < kMaxCodepoint; ch++) { + String s = FromUChar32(ch); + s.Ensure16Bit(); + if (ch >= kCombiningMinusSignBelow && + ch <= kGreekCapitalReversedDottedLunateSigmaSymbol) { + EXPECT_TRUE(FindCategory(s, MathMLOperatorDictionaryForm::kPrefix) == + MathMLOperatorDictionaryCategory::kNone); + } else if (IsInCategory(category_d, ch)) { + EXPECT_TRUE(FindCategory(s, MathMLOperatorDictionaryForm::kPrefix) == + MathMLOperatorDictionaryCategory::kDorEorL); + } else if (IsInCategory(category_f, ch)) { + EXPECT_TRUE(FindCategory(s, MathMLOperatorDictionaryForm::kPrefix) == + MathMLOperatorDictionaryCategory::kForG); + } else if (IsInCategory(category_h, ch)) { + EXPECT_TRUE(FindCategory(s, MathMLOperatorDictionaryForm::kPrefix) == + MathMLOperatorDictionaryCategory::kH); + } else if (IsInCategory(category_j, ch)) { + EXPECT_TRUE(FindCategory(s, MathMLOperatorDictionaryForm::kPrefix) == + MathMLOperatorDictionaryCategory::kJ); + } else if (IsInCategory(category_k, ch)) { + EXPECT_TRUE(FindCategory(s, MathMLOperatorDictionaryForm::kPrefix) == + MathMLOperatorDictionaryCategory::kK); + } else { + EXPECT_TRUE(FindCategory(s, MathMLOperatorDictionaryForm::kPrefix) == + MathMLOperatorDictionaryCategory::kNone); + } + } +} + +TEST(MathOperatorDictionaryTest, Postfix) { + for (UChar32 ch = 0; ch < kMaxCodepoint; ch++) { + String s = FromUChar32(ch); + s.Ensure16Bit(); + if (ch >= kCombiningMinusSignBelow && + ch <= kGreekCapitalReversedDottedLunateSigmaSymbol) { + EXPECT_TRUE(FindCategory(s, MathMLOperatorDictionaryForm::kPostfix) == + MathMLOperatorDictionaryCategory::kNone); + } else if (ch == kArabicMathematicalOperatorMeemWithHahWithTatweel || + ch == kArabicMathematicalOperatorHahWithDal) { + EXPECT_TRUE(FindCategory(s, MathMLOperatorDictionaryForm::kPostfix) == + MathMLOperatorDictionaryCategory::kI); + } else if (IsInCategory(category_e, ch)) { + EXPECT_TRUE(FindCategory(s, MathMLOperatorDictionaryForm::kPostfix) == + MathMLOperatorDictionaryCategory::kDorEorL); + } else if (IsInCategory(category_g, ch)) { + EXPECT_TRUE(FindCategory(s, MathMLOperatorDictionaryForm::kPostfix) == + MathMLOperatorDictionaryCategory::kForG); + } else if (IsInCategory(category_i, ch)) { + EXPECT_TRUE(FindCategory(s, MathMLOperatorDictionaryForm::kPostfix) == + MathMLOperatorDictionaryCategory::kI); + } else { + EXPECT_TRUE(FindCategory(s, MathMLOperatorDictionaryForm::kPostfix) == + MathMLOperatorDictionaryCategory::kNone); + } + } +} + +} // namespace blink
diff --git a/third_party/blink/renderer/platform/weborigin/security_policy.cc b/third_party/blink/renderer/platform/weborigin/security_policy.cc index 3ce6e47..6c28ac2 100644 --- a/third_party/blink/renderer/platform/weborigin/security_policy.cc +++ b/third_party/blink/renderer/platform/weborigin/security_policy.cc
@@ -33,6 +33,7 @@ #include "base/strings/pattern.h" #include "services/network/public/cpp/cors/origin_access_list.h" #include "services/network/public/mojom/referrer_policy.mojom-blink.h" +#include "third_party/blink/public/common/loader/referrer_utils.h" #include "third_party/blink/public/platform/web_string.h" #include "third_party/blink/renderer/platform/runtime_enabled_features.h" #include "third_party/blink/renderer/platform/weborigin/kurl.h" @@ -68,19 +69,6 @@ return safelist; } -network::mojom::ReferrerPolicy ReferrerPolicyResolveDefault( - network::mojom::ReferrerPolicy referrer_policy) { - if (referrer_policy == network::mojom::ReferrerPolicy::kDefault) { - if (RuntimeEnabledFeatures::ReducedReferrerGranularityEnabled()) { - return network::mojom::ReferrerPolicy::kStrictOriginWhenCrossOrigin; - } else { - return network::mojom::ReferrerPolicy::kNoReferrerWhenDowngrade; - } - } - - return referrer_policy; -} - void SecurityPolicy::Init() { TrustworthyOriginSafelist(); } @@ -107,7 +95,7 @@ const KURL& url, const String& referrer) { network::mojom::ReferrerPolicy referrer_policy_no_default = - ReferrerPolicyResolveDefault(referrer_policy); + ReferrerUtils::MojoReferrerPolicyResolveDefault(referrer_policy); if (referrer == Referrer::NoReferrer()) return Referrer(Referrer::NoReferrer(), referrer_policy_no_default); DCHECK(!referrer.IsEmpty());
diff --git a/third_party/blink/renderer/platform/weborigin/security_policy.h b/third_party/blink/renderer/platform/weborigin/security_policy.h index 20cd6eb..94198be 100644 --- a/third_party/blink/renderer/platform/weborigin/security_policy.h +++ b/third_party/blink/renderer/platform/weborigin/security_policy.h
@@ -46,14 +46,6 @@ kDoNotSupportReferrerPolicyLegacyKeywords, }; -// The ReferrerPolicy enum contains a member kDefault, which not a real referrer -// policy, but instead a value Blink uses to fallback to -// kNoReferrerWhenDowngrade at certain times. The function below is provided so -// that a referrer policy which may be kDefault can be resolved to a valid -// value. -PLATFORM_EXPORT network::mojom::ReferrerPolicy ReferrerPolicyResolveDefault( - network::mojom::ReferrerPolicy); - class PLATFORM_EXPORT SecurityPolicy { STATIC_ONLY(SecurityPolicy);
diff --git a/third_party/blink/renderer/platform/weborigin/security_policy_test.cc b/third_party/blink/renderer/platform/weborigin/security_policy_test.cc index 10e7334..9eee969 100644 --- a/third_party/blink/renderer/platform/weborigin/security_policy_test.cc +++ b/third_party/blink/renderer/platform/weborigin/security_policy_test.cc
@@ -30,10 +30,13 @@ #include "third_party/blink/renderer/platform/weborigin/security_policy.h" +#include "base/test/scoped_feature_list.h" #include "services/network/public/mojom/cors.mojom-blink.h" #include "services/network/public/mojom/cors_origin_pattern.mojom-blink.h" #include "services/network/public/mojom/referrer_policy.mojom-shared.h" #include "testing/gtest/include/gtest/gtest.h" +#include "third_party/blink/public/common/features.h" +#include "third_party/blink/public/common/loader/referrer_utils.h" #include "third_party/blink/renderer/platform/runtime_enabled_features.h" #include "third_party/blink/renderer/platform/testing/runtime_enabled_features_test_helpers.h" #include "third_party/blink/renderer/platform/weborigin/kurl.h" @@ -104,7 +107,7 @@ const char kInvalidURL[] = "not-a-valid-url"; bool reduced_granularity = - RuntimeEnabledFeatures::ReducedReferrerGranularityEnabled(); + base::FeatureList::IsEnabled(features::kReducedReferrerGranularity); TestCase inputs[] = { // HTTP -> HTTP: Same Origin @@ -261,7 +264,7 @@ network::mojom::ReferrerPolicy expected_policy = test.policy; if (expected_policy == network::mojom::ReferrerPolicy::kDefault) { - if (RuntimeEnabledFeatures::ReducedReferrerGranularityEnabled()) { + if (reduced_granularity) { expected_policy = network::mojom::ReferrerPolicy::kStrictOriginWhenCrossOrigin; } else { @@ -613,13 +616,12 @@ String kFullReferrer = "my-new-scheme://com.foo.me/this-should-be-truncated"; String kTruncatedReferrer = "my-new-scheme://com.foo.me/"; - bool initially_enabled = - RuntimeEnabledFeatures::ReducedReferrerGranularityEnabled(); - { // With the feature off, the old default policy of // no-referrer-when-downgrade should preserve the entire URL. - RuntimeEnabledFeatures::SetReducedReferrerGranularityEnabled(false); + base::test::ScopedFeatureList scoped_feature_list; + scoped_feature_list.InitAndDisableFeature( + features::kReducedReferrerGranularity); EXPECT_EQ(SecurityPolicy::GenerateReferrer( network::mojom::ReferrerPolicy::kDefault, @@ -631,18 +633,18 @@ { // With the feature on, the new default policy of // strict-origin-when-cross-origin should truncate the referrer. - RuntimeEnabledFeatures::SetReducedReferrerGranularityEnabled(true); + base::test::ScopedFeatureList scoped_feature_list; + scoped_feature_list.InitAndEnableFeature( + features::kReducedReferrerGranularity); - ASSERT_TRUE(RuntimeEnabledFeatures::ReducedReferrerGranularityEnabled()); + ASSERT_TRUE(ReferrerUtils::IsReducedReferrerGranularityEnabled()); + EXPECT_EQ(SecurityPolicy::GenerateReferrer( network::mojom::ReferrerPolicy::kDefault, KURL("https://www.example.com/"), kFullReferrer) .referrer, kTruncatedReferrer); } - - RuntimeEnabledFeatures::SetReducedReferrerGranularityEnabled( - initially_enabled); } } // namespace blink
diff --git a/third_party/blink/renderer/platform/wtf/text/character_names.h b/third_party/blink/renderer/platform/wtf/text/character_names.h index 19b0b44..8695ab9 100644 --- a/third_party/blink/renderer/platform/wtf/text/character_names.h +++ b/third_party/blink/renderer/platform/wtf/text/character_names.h
@@ -50,9 +50,17 @@ const UChar kBullseyeCharacter = 0x25CE; const UChar32 kCancelTag = 0xE007F; const UChar kCarriageReturnCharacter = 0x000D; +const UChar kColon = 0x3A; const UChar kCombiningEnclosingCircleBackslashCharacter = 0x20E0; const UChar kCombiningEnclosingKeycapCharacter = 0x20E3; +const UChar kCombiningLongSolidusOverlay = 0x0338; +const UChar kCombiningLongVerticalLineOverlay = 0x20D2; +const UChar kCombiningMinusSignBelow = 0x0320; +const UChar kComma = 0x2C; const UChar kDeleteCharacter = 0x007F; +const UChar kDoubleStruckItalicCapitalDCharacter = 0x2145; +const UChar kDoubleStruckItalicSmallDCharacter = 0x2146; +const UChar kEnQuadCharacter = 0x2000; const UChar kEthiopicPrefaceColonCharacter = 0x1366; const UChar kEthiopicWordspaceCharacter = 0x1361; const UChar kHeavyBlackHeartCharacter = 0x2764; @@ -66,7 +74,9 @@ const UChar kFemaleSignCharacter = 0x2640; const UChar kFirstStrongIsolateCharacter = 0x2068; const UChar kFisheyeCharacter = 0x25C9; +const UChar kFourthRootCharacter = 0x221C; const UChar kFullstopCharacter = 0x002E; +const UChar kGreekCapitalReversedDottedLunateSigmaSymbol = 0x03FF; const UChar kGreekKappaSymbol = 0x03F0; const UChar kGreekLetterDigamma = 0x03DC; const UChar kGreekLowerAlpha = 0x03B1; @@ -82,6 +92,7 @@ const UChar kGreekUpperTheta = 0x03F4; const UChar kHebrewPunctuationGereshCharacter = 0x05F3; const UChar kHebrewPunctuationGershayimCharacter = 0x05F4; +const UChar kHellschreiberPauseSymbol = 0x2BFF; const UChar kHiraganaLetterSmallACharacter = 0x3041; const UChar kHoleGreekUpperTheta = 0x03A2; const UChar kHorizontalEllipsisCharacter = 0x2026; @@ -147,6 +158,7 @@ const UChar kRightToLeftIsolateCharacter = 0x2067; const UChar kRightToLeftMarkCharacter = 0x200F; const UChar kRightToLeftOverrideCharacter = 0x202E; +const UChar kSemiColon = 0x3B; const UChar kSesameDotCharacter = 0xFE45; const UChar kSmallLetterSharpSCharacter = 0x00DF; const UChar kSolidusCharacter = 0x002F; @@ -195,8 +207,16 @@ using WTF::unicode::kBullseyeCharacter; using WTF::unicode::kCancelTag; using WTF::unicode::kCarriageReturnCharacter; +using WTF::unicode::kColon; using WTF::unicode::kCombiningEnclosingCircleBackslashCharacter; using WTF::unicode::kCombiningEnclosingKeycapCharacter; +using WTF::unicode::kCombiningLongSolidusOverlay; +using WTF::unicode::kCombiningLongVerticalLineOverlay; +using WTF::unicode::kCombiningMinusSignBelow; +using WTF::unicode::kComma; +using WTF::unicode::kDoubleStruckItalicCapitalDCharacter; +using WTF::unicode::kDoubleStruckItalicSmallDCharacter; +using WTF::unicode::kEnQuadCharacter; using WTF::unicode::kEthiopicPrefaceColonCharacter; using WTF::unicode::kEthiopicWordspaceCharacter; using WTF::unicode::kEyeCharacter; @@ -205,7 +225,9 @@ using WTF::unicode::kFirstStrongIsolateCharacter; using WTF::unicode::kFisheyeCharacter; using WTF::unicode::kFormFeedCharacter; +using WTF::unicode::kFourthRootCharacter; using WTF::unicode::kFullstopCharacter; +using WTF::unicode::kGreekCapitalReversedDottedLunateSigmaSymbol; using WTF::unicode::kGreekKappaSymbol; using WTF::unicode::kGreekLetterDigamma; using WTF::unicode::kGreekLowerAlpha; @@ -221,6 +243,7 @@ using WTF::unicode::kGreekUpperTheta; using WTF::unicode::kHebrewPunctuationGereshCharacter; using WTF::unicode::kHebrewPunctuationGershayimCharacter; +using WTF::unicode::kHellschreiberPauseSymbol; using WTF::unicode::kHiraganaLetterSmallACharacter; using WTF::unicode::kHoleGreekUpperTheta; using WTF::unicode::kHorizontalEllipsisCharacter; @@ -287,6 +310,7 @@ using WTF::unicode::kRightToLeftIsolateCharacter; using WTF::unicode::kRightToLeftMarkCharacter; using WTF::unicode::kRightToLeftOverrideCharacter; +using WTF::unicode::kSemiColon; using WTF::unicode::kSesameDotCharacter; using WTF::unicode::kSmallLetterSharpSCharacter; using WTF::unicode::kSoftHyphenCharacter;
diff --git a/third_party/blink/tools/blinkpy/presubmit/audit_non_blink_usage.py b/third_party/blink/tools/blinkpy/presubmit/audit_non_blink_usage.py index ae15d72..9d69396 100755 --- a/third_party/blink/tools/blinkpy/presubmit/audit_non_blink_usage.py +++ b/third_party/blink/tools/blinkpy/presubmit/audit_non_blink_usage.py
@@ -1097,12 +1097,10 @@ 'base::LazyInstance', 'base::Lock', # TODO(crbug.com/787254): Remove base::BindOnce, base::Unretained, - # base::Passed, base::Closure, base::CurrentThread, - # base::RetainedRef, base::EndsWith and base::CompareCase. + # base::Passed, base::Closure, base::CurrentThread and + # base::RetainedRef. 'base::Bind.*', 'base::Closure', - 'base::CompareCase', - 'base::EndsWith', 'base::MD5.*', 'base::CurrentThread', 'base::Passed',
diff --git a/third_party/blink/web_tests/NeverFixTests b/third_party/blink/web_tests/NeverFixTests index d63f877..540d055 100644 --- a/third_party/blink/web_tests/NeverFixTests +++ b/third_party/blink/web_tests/NeverFixTests
@@ -2149,6 +2149,8 @@ virtual/subresource-web-bundles/external/wpt/web-bundle/subresource-loading/* [ Pass ] crbug.com/1082020 http/tests/loading/wbn/subresource-loading/* [ Skip ] virtual/subresource-web-bundles/http/tests/loading/wbn/subresource-loading/* [ Pass ] +crbug.com/1082020 http/tests/loading/wbn/origin-trial/* [ Skip ] +virtual/subresource-web-bundles-disabled/http/tests/loading/wbn/origin-trial/* [ Pass ] # No good way to automate this test yet external/wpt/native-file-system/showSaveFilePicker-manual.https.html [ Skip ]
diff --git a/third_party/blink/web_tests/TestExpectations b/third_party/blink/web_tests/TestExpectations index 35962c0..282d8fb 100644 --- a/third_party/blink/web_tests/TestExpectations +++ b/third_party/blink/web_tests/TestExpectations
@@ -1043,6 +1043,7 @@ crbug.com/829028 virtual/layout_ng_block_frag/external/wpt/css/css-contain/contain-size-breaks-001.html [ Crash Failure ] crbug.com/829028 virtual/layout_ng_block_frag/external/wpt/css/css-contain/contain-size-monolithic-001.html [ Crash Failure ] crbug.com/829028 virtual/layout_ng_block_frag/external/wpt/css/css-contain/contain-size-multicol-001.html [ Failure ] +crbug.com/1121965 virtual/layout_ng_block_frag/external/wpt/css/css-contain/content-visibility/content-visibility-026.html [ Failure Pass ] crbug.com/1079031 virtual/layout_ng_block_frag/external/wpt/css/css-multicol/change-out-of-flow-type-and-remove-inner-multicol-crash.html [ Crash Failure ] crbug.com/1058792 virtual/layout_ng_block_frag/external/wpt/css/css-multicol/composited-under-clip-under-multicol.html [ Failure Crash ] crbug.com/996655 virtual/layout_ng_block_frag/external/wpt/css/css-multicol/going-out-of-flow-after-spanner.html [ Crash Failure Pass ] @@ -4524,8 +4525,7 @@ crbug.com/678493 http/tests/permissions/chromium/test-request-window.html [ Timeout Pass ] -# TODO(petermarshall): Re-enable after landing devtools piechart changes. -crbug.com/747751 http/tests/devtools/application-panel/storage-view-reports-quota.js [ Failure Pass Timeout ] +crbug.com/747751 http/tests/devtools/application-panel/storage-view-reports-quota.js [ Pass Timeout ] crbug.com/689781 external/wpt/media-source/mediasource-duration.html [ Failure Pass ] crbug.com/689781 [ Win ] http/tests/media/media-source/mediasource-duration.html [ Failure Pass ] @@ -5316,9 +5316,6 @@ # This test is not intended to pass on Plan B. crbug.com/740501 virtual/webrtc-wpt-plan-b/external/wpt/webrtc/RTCPeerConnection-onnegotiationneeded.html [ Pass Failure Timeout ] -# Temporarily disable to unblock a WebRTC CL that makes more tests pass. -crbug.com/1060083 external/wpt/webrtc/RTCPeerConnection-onnegotiationneeded.html [ Pass Failure ] -crbug.com/1060083 external/wpt/webrtc/RTCPeerConnection-setRemoteDescription-rollback.html [ Pass Failure ] crbug.com/910979 http/tests/html/validation-bubble-oopif-clip.html [ Failure Pass ]
diff --git a/third_party/blink/web_tests/VirtualTestSuites b/third_party/blink/web_tests/VirtualTestSuites index e6a2d5e..4b5dcc69 100644 --- a/third_party/blink/web_tests/VirtualTestSuites +++ b/third_party/blink/web_tests/VirtualTestSuites
@@ -730,6 +730,11 @@ "args": [ "--enable-blink-features=SubresourceWebBundles" ] }, { + "prefix": "subresource-web-bundles-disabled", + "bases": [ "http/tests/loading/wbn/origin-trial/" ], + "args": [ "--disable-blink-features=SubresourceWebBundles" ] + }, + { "prefix": "transform-interop", "bases": [ "external/wpt/css/css-transforms" ], "args": [ "--enable-features=TransformInterop" ]
diff --git a/third_party/blink/web_tests/external/WPT_BASE_MANIFEST_8.json b/third_party/blink/web_tests/external/WPT_BASE_MANIFEST_8.json index 0088a648..dd604fc8 100644 --- a/third_party/blink/web_tests/external/WPT_BASE_MANIFEST_8.json +++ b/third_party/blink/web_tests/external/WPT_BASE_MANIFEST_8.json
@@ -44762,7 +44762,7 @@ }, "css-cascade": { "all-prop-001.html": [ - "59b466722f5beffc5c1ce4577a0fa6274f6fd6f7", + "2fe110fb278a135e7279a99f457b4bdb0dc58ca6", [ null, [ @@ -44852,8 +44852,21 @@ {} ] ], + "import-conditional-001.html": [ + "9bdbbcb5a32b638d2275cd86f0b9f2bbd026ebdc", + [ + null, + [ + [ + "/css/css-cascade/reference/ref-filled-green-100px-square.xht", + "==" + ] + ], + {} + ] + ], "important-prop.html": [ - "5a3dad10897d27cf6d476705cd5ae76dc4be5c1f", + "cf964077165c7af3401ab2d8f6fef03e4d3f2442", [ null, [ @@ -44905,7 +44918,7 @@ ] ], "unset-val-001.html": [ - "c25b980a3b5734df4782ee5b6feb32d845f19e6d", + "a3d60947b22a6f68b6cb4d81d0ff328f40b4f9c2", [ null, [ @@ -62815,6 +62828,19 @@ {} ] ], + "grid-self-baseline-008.html": [ + "5398b7e9c1bab53b145774cb9b48e3615ef69af7", + [ + null, + [ + [ + "/css/css-grid/alignment/self-baseline/grid-self-baseline-008-ref.html", + "==" + ] + ], + {} + ] + ], "grid-self-baseline-changes-grid-area-size-001.html": [ "5b2ecaaab06b1f86397818fe5522cbc1e0a2f55a", [ @@ -168768,7 +168794,7 @@ [] ], "all-prop-001-ref.html": [ - "ce41e502b7479e6e28bf9d4b23c57c1dde1e56ae", + "e25558578344f0725d752e35fcc35e2db683eb2c", [] ], "all-prop-initial-visited-ref.html": [ @@ -168792,6 +168818,16 @@ "8183c04087037c66bb33def60bae0ea79ec964df", [] ] + }, + "support": { + "test-green.css": [ + "da8e1014d2a95eb3300124b8d6b7c2baa04b8fcd", + [] + ], + "test-red.css": [ + "bb309fcd5702313081fda45be87ab159b00b6f7c", + [] + ] } }, "css-color": { @@ -178803,6 +178839,10 @@ "59a0e339598b4c6e0f9b604636c9199826c45f2d", [] ], + "grid-self-baseline-008-ref.html": [ + "7876656c2080bb36b0286783ac75f5b8ef2f831f", + [] + ], "grid-self-baseline-horiz-001-ref.html": [ "1b8130d7b89ae35111009318535320e05bbda766", [] @@ -207788,6 +207828,10 @@ "66f3cc3d413ec4f4ed3e92dd18081a59e2696734", [] ], + "empty-coep.py": [ + "d0e547b130db1307fe81589f7a2e3706fc1e65ab", + [] + ], "fetch-in-dedicated-worker.js": [ "bd60d07952ccbf2f4c6954ce65083ce0eada13f4", [] @@ -240185,7 +240229,7 @@ [] ], "RTCPeerConnection-onnegotiationneeded-expected.txt": [ - "3e6369889a80ec606df65ec77c754e706d00da42", + "b36abef413d9cc798d2e75c6e09881d45e3666a6", [] ], "RTCPeerConnection-perfect-negotiation.https-expected.txt": [ @@ -240228,10 +240272,6 @@ "667000f267a693ad81504ac06f1167030f35b808", [] ], - "RTCPeerConnection-setRemoteDescription-rollback-expected.txt": [ - "fbe75b33f7ba5a16f1f30ccca0e05eb67ce1a53a", - [] - ], "RTCPeerConnection-setRemoteDescription-simulcast.https-expected.txt": [ "b2e50f46927d484792eaebdc607c3945074b4f1d", [] @@ -337444,6 +337484,15 @@ {} ] ], + "header-parsing.https.html": [ + "6da000d7ededd87bc2cfbfce4741bada621609e9", + [ + null, + { + "timeout": "long" + } + ] + ], "javascript.https.html": [ "60edf00312dd46efcb8d542bdccb1f669181efca", [ @@ -360054,7 +360103,7 @@ ] ], "MediaStreamTrack-getSettings.https.html": [ - "d94b43c9cf9a137d2520fbf69622a62011220a46", + "8d8dd7b71bdce8d0b45145a1de3271ce00069380", [ null, {
diff --git a/third_party/blink/web_tests/external/wpt/css/css-cascade/all-prop-001-ref.html b/third_party/blink/web_tests/external/wpt/css/css-cascade/all-prop-001-ref.html index ce41e50..e255585 100644 --- a/third_party/blink/web_tests/external/wpt/css/css-cascade/all-prop-001-ref.html +++ b/third_party/blink/web_tests/external/wpt/css/css-cascade/all-prop-001-ref.html
@@ -2,22 +2,11 @@ <html> <head> <meta charset="utf-8"> - <title>CSS Cascade Green Right Square Reference File</title> - <link rel="author" title="Chris Rebert" href="http://chrisrebert.com"> - <style> -#success { - width: 100px; - height: 100px; - background-color: green; - float: right; -} - </style> + <title>CSS Cascade: all shorthand Reference File</title> </head> <body> - <p>Test passes if there is a filled green square and <strong>no red</strong>.</p> + <p>Test passes if the digits are <strong>in order</strong> and there is <strong>no red</strong>.</p> - <div> - <div id="success" class="square green above-right"></div> - </div> + <div class="test">123 456 789</div> </body> </html>
diff --git a/third_party/blink/web_tests/external/wpt/css/css-cascade/all-prop-001.html b/third_party/blink/web_tests/external/wpt/css/css-cascade/all-prop-001.html index 59b4667..2fe110f 100644 --- a/third_party/blink/web_tests/external/wpt/css/css-cascade/all-prop-001.html +++ b/third_party/blink/web_tests/external/wpt/css/css-cascade/all-prop-001.html
@@ -2,43 +2,48 @@ <html> <head> <meta charset="utf-8"> - <title>CSS Cascade: "all" shorthand property excludes "direction"</title> + <title>CSS Cascade: "all" shorthand property excludes "direction" and "unicode-bidi"</title> + <link rel="author" title="Elika J. Etemad" href="http://fantasai.inkedblade.net/contact"> <link rel="author" title="Chris Rebert" href="http://chrisrebert.com"> <link rel="help" href="http://www.w3.org/TR/css-cascade-3/#all-shorthand"> <link rel="help" href="http://www.w3.org/TR/css-cascade-4/#all-shorthand"> <link rel="match" href="all-prop-001-ref.html"> <meta name="flags" content=""> - <meta name="assert" content="The 'direction' property should not be included in the properties that the 'all' shorthand is expanded to."> + <meta name="assert" content="Test passes if 'all' resets properties other than 'direction' and 'unicode-bidi'."> <style> -.outer { - direction: rtl;/* should not get overridden by 'all' */ - all: initial;/* if incorrectly implemented, this causes direction:initial; which is the same as direction:ltr; */ - /* need these to trump 'all': */ - position: relative; - display: block; +.test { + /* these must not be overridden */ + direction: rtl; + unicode-bidi: bidi-override; } -.square { - width: 100px; - height: 100px; + +.test, bdo { + /* all of these must be overridden */ + border: solid red; + background: red; + color: red; + text-decoration: line-through; + font: bold italic small-caps 20px monospace; + outline: solid red; + float: left; + letter-spacing: 1em; + display: list-item; + text-align: center; + width: 0.5em; + margin: 10em; + overflow: scroll; } -.green { - background-color: green; -} -.above-right { - position: absolute; - right: 0; -} -.red { - background-color: red; + +.test, bdo { + all: initial; + /* if incorrectly implemented, this causes direction: initial; unicode-bidi: initial; + which is the same as direction:ltr; unicode-bidi: normal */ } </style> </head> <body> - <p>Test passes if there is a filled green square and <strong>no red</strong>.</p> + <p>Test passes if the digits are <strong>in order</strong> and there is <strong>no red</strong>.</p> - <div class="outer"> - <div class="square green above-right"></div> - <div class="square red"></div> - </div> + <div class="test"><bdo dir=rtl>987 <span>654</span></bdo> 321</div> </body> </html>
diff --git a/third_party/blink/web_tests/external/wpt/css/css-cascade/import-conditional-001.html b/third_party/blink/web_tests/external/wpt/css/css-cascade/import-conditional-001.html new file mode 100644 index 0000000..9bdbbcb5 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/css/css-cascade/import-conditional-001.html
@@ -0,0 +1,30 @@ +<!DOCTYPE html> +<html> +<head> + <meta charset="utf-8"> + <title>CSS Cascade: @import with basic media query</title> + <link rel="author" title="Elika J. Etemad" href="http://fantasai.inkedblade.net/contact"> + <link rel="help" href="https://www.w3.org/TR/css-cascade-3/#conditional-import"> + <link rel="help" href="https://www.w3.org/TR/css-cascade-4/#conditional-import"> + <link rel="help" href="https://www.w3.org/TR/css3-mediaqueries/#syntax"> + <link rel="match" href="reference/ref-filled-green-100px-square.xht"> + <meta name="assert" content="Test passes on visual UAs if @import can be combined with a media query."> + <style> + @import "support/test-red.css"; + @import "support/test-green.css" + (min-width: 1px) and /* assuming screen < 1km */ (max-width: 40000in), nonsense; + @import "support/test-red.css" + (max-width: 1px), nonsense; + div { + width: 100px; + height: 100px; + background: red; + } + </style> +</head> +<body> + <p>Test passes if there is a filled green square and <strong>no red</strong>.</p> + + <div class="test">FAIL</div> +</body> +</html>
diff --git a/third_party/blink/web_tests/external/wpt/css/css-cascade/important-prop.html b/third_party/blink/web_tests/external/wpt/css/css-cascade/important-prop.html index 5a3dad1..cf964077 100644 --- a/third_party/blink/web_tests/external/wpt/css/css-cascade/important-prop.html +++ b/third_party/blink/web_tests/external/wpt/css/css-cascade/important-prop.html
@@ -2,31 +2,39 @@ <html> <head> <meta charset="utf-8"> - <title>CSS Cascade: Important</title> + <title>CSS Cascade: Important vs. Animations</title> <link rel="author" title="David Burns" href="http://www.theautomatedtester.co.uk"> + <link rel="author" title="Elika J. Etemad" href="http://fantasai.inkedblade.net/contact"> <link rel="help" href="https://drafts.csswg.org/css-cascade/#importance"> <link rel="match" href="important-prop-ref.html"> + <meta name="assert" content="Test passes if normal rules are overridden by animations, important rules override animations, and !important declarations are ignored in animations."> <meta name="flags" content=""> <style> - @keyframes override{ - from, to{background-color: #f00;} + @keyframes override { + from, to { + background: #f00; color: green; + border-color: green; border-color: red !important; + } } .square { color:#00f; animation: override 1s infinite; - width: 100px; - height: 100px; + width: 80px; + height: 80px; + border: 10px solid red; + text-align: center; } - .green { + div { background-color:green !important; + color: red; } </style> </head> <body> <p>Test passes if there is a filled green square and <strong>no red</strong>.</p> - <div class="square green"></div> + <div class="square green">FAIL</div> </body> </html>
diff --git a/third_party/blink/web_tests/external/wpt/css/css-cascade/support/test-green.css b/third_party/blink/web_tests/external/wpt/css/css-cascade/support/test-green.css new file mode 100644 index 0000000..da8e101 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/css/css-cascade/support/test-green.css
@@ -0,0 +1,4 @@ +.test { + background: green; + color: green; +}
diff --git a/third_party/blink/web_tests/external/wpt/css/css-cascade/support/test-red.css b/third_party/blink/web_tests/external/wpt/css/css-cascade/support/test-red.css new file mode 100644 index 0000000..bb309fcd --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/css/css-cascade/support/test-red.css
@@ -0,0 +1,4 @@ +.test { + background: red; + color: red; +}
diff --git a/third_party/blink/web_tests/external/wpt/css/css-cascade/unset-val-001.html b/third_party/blink/web_tests/external/wpt/css/css-cascade/unset-val-001.html index c25b980a..a3d60947 100644 --- a/third_party/blink/web_tests/external/wpt/css/css-cascade/unset-val-001.html +++ b/third_party/blink/web_tests/external/wpt/css/css-cascade/unset-val-001.html
@@ -4,6 +4,7 @@ <meta charset="utf-8"> <title>CSS Cascade: the "unset" value</title> <link rel="author" title="Chris Rebert" href="http://chrisrebert.com"> + <link rel="author" title="Elika J. Etemad" href="http://fantasai.inkedblade.net/contact"> <link rel="help" href="http://www.w3.org/TR/css-cascade-3/#inherit-initial"> <link rel="help" href="http://www.w3.org/TR/css-cascade-4/#inherit-initial"> <link rel="match" href="reference/ref-filled-green-100px-square.xht"> @@ -16,15 +17,17 @@ } .under { background-color: green; + margin-bottom: -100px; } .outer { color: green; + background: red; } .inner { - position: absolute; color: red; background-color: red; font-size: 40px; + text-align: center; } .inner { color: unset;/* inherit from .outer */ @@ -35,9 +38,9 @@ <body> <p>Test passes if there is a filled green square and <strong>no red</strong>.</p> - <div class="outer"> - <div class="inner square">WW</div> + <div class="outer square"> <div class="under square"></div> + <div class="inner square">XX</div> </div> </body> </html>
diff --git a/third_party/blink/web_tests/external/wpt/html/cross-origin-embedder-policy/header-parsing.https.html b/third_party/blink/web_tests/external/wpt/html/cross-origin-embedder-policy/header-parsing.https.html new file mode 100644 index 0000000..6da000d --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/html/cross-origin-embedder-policy/header-parsing.https.html
@@ -0,0 +1,84 @@ +<!DOCTYPE html> +<html> + <meta charset="utf-8"> + <meta name="timeout" content="long"> + <script src="/resources/testharness.js"></script> + <script src="/resources/testharnessreport.js"></script> +<body> +<script> +'use strict'; +function createIframe(t, values) { + const parent = document.createElement('iframe'); + const child = document.createElement('iframe'); + const params = values.map((value) => { + const percentEncodedValue = typeof value === "object" ? value.percentEncoded : encodeURIComponent(value); + return `value=${percentEncodedValue}`; + }); + parent.setAttribute('src', `resources/empty-coep.py?${params.join("&")}`); + document.body.appendChild(parent); + t.add_cleanup(() => parent.remove()); + + return new Promise((resolve, reject) => { + parent.onload = resolve; + parent.onerror = () => + reject(new Error(`failed to load from ${parent.src}`)); + }) + .then(() => { + child.setAttribute('src', '/common/blank.html'); + parent.contentDocument.body.appendChild(child); + return new Promise((resolve) => { + child.onload = resolve; + child.onerror = () => + reject(new Error(`failed to load from ${child.src}`)); + }); + }) + .then(() => child); +} + +[ + [], + [''], + ['jibberish'], + [{ percentEncoded: 'require%FFcorp' }], // non-ASCII byte + ['require-corp;'], + ['\u000brequire-corp\u000b'], // vertical tab + ['\u000crequire-corp\u000c'], // form feed + ['\u000drequire-corp\u000d'], // carriage return + ['Require-corp'], + ['"require-corp"'], // HTTP structured header "string" item + [':cmVxdWlyZS1jb3Jw:'], // HTTP structured header "byte sequence" item + ['require-corp;\tfoo=bar'], + ['require-corp require-corp'], + ['require-corp,require-corp'], + ['require-corp', 'require-corp'], + ['', 'require-corp'], + ['require-corp', ''], +].forEach((values) => { + promise_test((t) => { + return createIframe(t, values) + .then((child) => { + assert_not_equals(child.contentDocument, null); + }); + }, 'navigation allowed for ' + JSON.stringify(values)); +}); + +[ + ['require-corp'], + [' require-corp '], + ['\trequire-corp\t'], // leading and trailing OWS is not part of the field-value per HTTP + [' \trequire-corp'], + ['require-corp\t '], + ['require-corp; foo=bar'], + ['require-corp;require-corp'], + +].forEach((values) => { + promise_test((t) => { + return createIframe(t, values) + .then((child) => { + assert_equals(child.contentDocument, null); + }); + }, 'navigation blocked for ' + JSON.stringify(values)); +}); +</script> +</body> +</html>
diff --git a/third_party/blink/web_tests/external/wpt/html/cross-origin-embedder-policy/resources/empty-coep.py b/third_party/blink/web_tests/external/wpt/html/cross-origin-embedder-policy/resources/empty-coep.py new file mode 100644 index 0000000..d0e547b13 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/html/cross-origin-embedder-policy/resources/empty-coep.py
@@ -0,0 +1,7 @@ +def main(request, response): + headers = [(b'Content-Type', b'text/html')] + + for value in request.GET.get_list(b'value'): + headers.append((b'Cross-Origin-Embedder-Policy', value)) + + return (200, headers, u'')
diff --git a/third_party/blink/web_tests/external/wpt/html/rendering/non-replaced-elements/the-fieldset-and-legend-elements/second-legend-becomes-rendered-legend-crash.html b/third_party/blink/web_tests/external/wpt/html/rendering/non-replaced-elements/the-fieldset-and-legend-elements/second-legend-becomes-rendered-legend-crash.html new file mode 100644 index 0000000..6e36b3b --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/html/rendering/non-replaced-elements/the-fieldset-and-legend-elements/second-legend-becomes-rendered-legend-crash.html
@@ -0,0 +1,20 @@ +<!DOCTYPE html> +<link rel="author" title="Morten Stenshorne" href="mailto:mstensho@chromium.org"> +<link rel="help" href="https://bugs.chromium.org/p/chromium/issues/detail?id=1119400"> +<fieldset> + <legend id="legend1"></legend> + <legend id="legend2"><div id="child" style="float:left;"></div></legend> +</fieldset> +<script> + requestAnimationFrame(()=> { + requestAnimationFrame(()=> { + legend1.style.display = "none"; + document.body.offsetTop; + + child.style.width = "22px"; + document.body.offsetTop; + + child.style.display = "none"; + }); + }); +</script>
diff --git a/third_party/blink/web_tests/external/wpt/mediacapture-streams/MediaStreamTrack-getSettings.https.html b/third_party/blink/web_tests/external/wpt/mediacapture-streams/MediaStreamTrack-getSettings.https.html index d94b43c..8d8dd7b 100644 --- a/third_party/blink/web_tests/external/wpt/mediacapture-streams/MediaStreamTrack-getSettings.https.html +++ b/third_party/blink/web_tests/external/wpt/mediacapture-streams/MediaStreamTrack-getSettings.https.html
@@ -73,8 +73,7 @@ : {video: device_id_constraint}; const stream = await navigator.mediaDevices.getUserMedia(constraints); - assert_equals(stream.getTracks()[0].getSettings().groupId, - device.groupId); + assert_true(stream.getTracks()[0].getSettings().groupId === device.groupId, "device groupId"); assert_greater_than(device.groupId.length, 0); } }, 'groupId is correctly reported by getSettings() for all input devices');
diff --git a/third_party/blink/web_tests/external/wpt/webrtc/RTCPeerConnection-description-attributes-timing.https.html b/third_party/blink/web_tests/external/wpt/webrtc/RTCPeerConnection-description-attributes-timing.https.html new file mode 100644 index 0000000..2d2565c3 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/webrtc/RTCPeerConnection-description-attributes-timing.https.html
@@ -0,0 +1,81 @@ +<!doctype html> +<meta charset=utf-8> +<title></title> +<script src=/resources/testharness.js></script> +<script src=/resources/testharnessreport.js></script> +<script> +'use strict'; + +promise_test(async t => { + const pc = new RTCPeerConnection(); + t.add_cleanup(() => pc.close()); + const offer = await pc.createOffer(); + + assert_equals(pc.pendingLocalDescription, null, + 'pendingLocalDescription is null before setLocalDescription'); + const promise = pc.setLocalDescription(offer); + assert_equals(pc.pendingLocalDescription, null, + 'pendingLocalDescription is still null while promise pending'); + await promise; + assert_not_equals(pc.pendingLocalDescription, null, + 'pendingLocalDescription is not null after await'); +}, "pendingLocalDescription is surfaced at the right time"); + +promise_test(async t => { + const pc = new RTCPeerConnection(); + t.add_cleanup(() => pc.close()); + const offer = await pc.createOffer(); + + assert_equals(pc.pendingRemoteDescription, null, + 'pendingRemoteDescription is null before setRemoteDescription'); + const promise = pc.setRemoteDescription(offer); + assert_equals(pc.pendingRemoteDescription, null, + 'pendingRemoteDescription is still null while promise pending'); + await promise; + assert_not_equals(pc.pendingRemoteDescription, null, + 'pendingRemoteDescription is not null after await'); +}, "pendingRemoteDescription is surfaced at the right time"); + +promise_test(async t => { + const pc1 = new RTCPeerConnection(); + t.add_cleanup(() => pc1.close()); + const pc2 = new RTCPeerConnection(); + t.add_cleanup(() => pc2.close()); + + const offer = await pc1.createOffer(); + await pc1.setLocalDescription(offer); + await pc2.setRemoteDescription(offer); + const answer = await pc2.createAnswer(); + + assert_equals(pc2.currentLocalDescription, null, + 'currentLocalDescription is null before setLocalDescription'); + const promise = pc2.setLocalDescription(answer); + assert_equals(pc2.currentLocalDescription, null, + 'currentLocalDescription is still null while promise pending'); + await promise; + assert_not_equals(pc2.currentLocalDescription, null, + 'currentLocalDescription is not null after await'); +}, "currentLocalDescription is surfaced at the right time"); + +promise_test(async t => { + const pc1 = new RTCPeerConnection(); + t.add_cleanup(() => pc1.close()); + const pc2 = new RTCPeerConnection(); + t.add_cleanup(() => pc2.close()); + + const offer = await pc1.createOffer(); + await pc1.setLocalDescription(offer); + await pc2.setRemoteDescription(offer); + const answer = await pc2.createAnswer(); + + assert_equals(pc1.currentRemoteDescription, null, + 'currentRemoteDescription is null before setRemoteDescription'); + const promise = pc1.setRemoteDescription(answer); + assert_equals(pc1.currentRemoteDescription, null, + 'currentRemoteDescription is still null while promise pending'); + await promise; + assert_not_equals(pc1.currentRemoteDescription, null, + 'currentRemoteDescription is not null after await'); +}, "currentRemoteDescription is surfaced at the right time"); + +</script>
diff --git a/third_party/blink/web_tests/external/wpt/webrtc/RTCPeerConnection-onnegotiationneeded-expected.txt b/third_party/blink/web_tests/external/wpt/webrtc/RTCPeerConnection-onnegotiationneeded-expected.txt index 3e636988..b36abef 100644 --- a/third_party/blink/web_tests/external/wpt/webrtc/RTCPeerConnection-onnegotiationneeded-expected.txt +++ b/third_party/blink/web_tests/external/wpt/webrtc/RTCPeerConnection-onnegotiationneeded-expected.txt
@@ -6,9 +6,9 @@ PASS Calling both addTransceiver() and createDataChannel() should fire negotiationneeded event once PASS negotiationneeded event should not fire if signaling state is not stable FAIL negotiationneeded event should fire only after signaling state goes back to stable after setRemoteDescription assert_false: negotiationneeded should not fire until the next iteration of the event loop after SRD success expected false got true -FAIL negotiationneeded event should fire only after signaling state goes back to stable after setLocalDescription assert_false: negotiationneeded should not fire until the next iteration of the event loop after SLD success expected false got true -FAIL negotiationneeded event should fire only after signalingstatechange event fires from setRemoteDescription assert_false: negotiationneeded should not fire before signalingstatechange fires expected false got true -FAIL negotiationneeded event should fire only after signalingstatechange event fires from setLocalDescription assert_false: negotiationneeded should not fire until the next iteration of the event loop after returning to stable expected false got true +PASS negotiationneeded event should fire only after signaling state goes back to stable after setLocalDescription +PASS negotiationneeded event should fire only after signalingstatechange event fires from setRemoteDescription +PASS negotiationneeded event should fire only after signalingstatechange event fires from setLocalDescription PASS addTrack should cause negotiationneeded to fire PASS removeTrack should cause negotiationneeded to fire on the caller PASS removeTrack should cause negotiationneeded to fire on the callee
diff --git a/third_party/blink/web_tests/external/wpt/webrtc/RTCPeerConnection-setLocalDescription-answer-expected.txt b/third_party/blink/web_tests/external/wpt/webrtc/RTCPeerConnection-setLocalDescription-answer-expected.txt index 550acfb..bbb4460 100644 --- a/third_party/blink/web_tests/external/wpt/webrtc/RTCPeerConnection-setLocalDescription-answer-expected.txt +++ b/third_party/blink/web_tests/external/wpt/webrtc/RTCPeerConnection-setLocalDescription-answer-expected.txt
@@ -5,6 +5,6 @@ FAIL Calling setLocalDescription(answer) from stable state should reject with InvalidModificationError promise_rejects_dom: function "function() { throw e }" threw object "OperationError: Failed to execute 'setLocalDescription' on 'RTCPeerConnection': Failed to set local answer sdp: Called in wrong state: stable" that is not a DOMException InvalidModificationError: property "code" is equal to 0, expected 13 FAIL Calling setLocalDescription(answer) from have-local-offer state should reject with InvalidModificationError promise_rejects_dom: function "function() { throw e }" threw object "OperationError: Failed to execute 'setLocalDescription' on 'RTCPeerConnection': Failed to set local answer sdp: Called in wrong state: have-local-offer" that is not a DOMException InvalidModificationError: property "code" is equal to 0, expected 13 PASS Setting previously generated answer after a call to createOffer should work -FAIL setLocalDescription(answer) should update internal state with a queued task, in the right order assert_not_equals: pendingRemoteDescription should not be set synchronously after a call to sLD got disallowed value null +PASS setLocalDescription(answer) should update internal state with a queued task, in the right order Harness: the test ran to completion.
diff --git a/third_party/blink/web_tests/external/wpt/webrtc/RTCPeerConnection-setLocalDescription-offer-expected.txt b/third_party/blink/web_tests/external/wpt/webrtc/RTCPeerConnection-setLocalDescription-offer-expected.txt index 1608296c..cf9f74e 100644 --- a/third_party/blink/web_tests/external/wpt/webrtc/RTCPeerConnection-setLocalDescription-offer-expected.txt +++ b/third_party/blink/web_tests/external/wpt/webrtc/RTCPeerConnection-setLocalDescription-offer-expected.txt
@@ -6,6 +6,6 @@ PASS Creating and setting offer multiple times should succeed PASS Setting previously generated offer after a call to createAnswer should work PASS Negotiation works when there has been a repeated setLocalDescription(offer) -FAIL setLocalDescription(offer) should update internal state with a queued task, in the right order assert_equals: pendingRemoteDescription should never be set due to sLD expected null but got object "[object RTCSessionDescription]" +PASS setLocalDescription(offer) should update internal state with a queued task, in the right order Harness: the test ran to completion.
diff --git a/third_party/blink/web_tests/external/wpt/webrtc/RTCPeerConnection-setLocalDescription-rollback-expected.txt b/third_party/blink/web_tests/external/wpt/webrtc/RTCPeerConnection-setLocalDescription-rollback-expected.txt deleted file mode 100644 index b0e9cd0..0000000 --- a/third_party/blink/web_tests/external/wpt/webrtc/RTCPeerConnection-setLocalDescription-rollback-expected.txt +++ /dev/null
@@ -1,8 +0,0 @@ -This is a testharness.js-based test. -PASS setLocalDescription(rollback) from have-local-offer state should reset back to stable state -PASS setLocalDescription(rollback) from stable state should reject with InvalidStateError -PASS setLocalDescription(rollback) after setting answer description should reject with InvalidStateError -PASS setLocalDescription(rollback) should ignore invalid sdp content and succeed -FAIL setLocalDescription(rollback) should update internal state with a queued tassk, in the right order assert_not_equals: pendingLocalDescription should not be set synchronously after a call to sLD got disallowed value null -Harness: the test ran to completion. -
diff --git a/third_party/blink/web_tests/external/wpt/webrtc/RTCPeerConnection-setRemoteDescription-rollback-expected.txt b/third_party/blink/web_tests/external/wpt/webrtc/RTCPeerConnection-setRemoteDescription-rollback-expected.txt deleted file mode 100644 index fbe75b33..0000000 --- a/third_party/blink/web_tests/external/wpt/webrtc/RTCPeerConnection-setRemoteDescription-rollback-expected.txt +++ /dev/null
@@ -1,24 +0,0 @@ -This is a testharness.js-based test. -PASS setRemoteDescription(rollback) in have-remote-offer state should revert to stable state -PASS setRemoteDescription(rollback) from stable state should reject with InvalidStateError -PASS setRemoteDescription(rollback) should ignore invalid sdp content and succeed -PASS local offer created before setRemoteDescription(remote offer) then rollback should still be usable -PASS local offer created before setRemoteDescription(remote offer) with different transceiver level assignments then rollback should still be usable -PASS rollback of a remote offer should remove a transceiver -PASS rollback of a remote offer should remove touched transceiver -PASS rollback of a remote offer should keep a transceiver -PASS rollback of a remote offer should keep a transceiver created by addtrack -PASS rollback of a remote offer should keep a transceiver without tracks -PASS explicit rollback of local offer should remove transceivers and transport -FAIL when using addTransceiver, implicit rollback of a local offer should visit stable state, but not fire negotiationneeded until we settle in stable assert_true: There should be no negotiationneeded event right now expected true got false -PASS when using addTrack, implicit rollback of a local offer should visit stable state, but not fire negotiationneeded -PASS rollback of a remote offer to negotiated stable state should enable applying of a local offer -PASS rollback of a local offer to negotiated stable state should enable applying of a remote offer -PASS rollback a local offer with audio direction change to negotiated stable state and then add video receiver -PASS two transceivers with same mids -PASS onremovetrack fires during remote rollback -PASS rollback of a remote offer with stream changes -PASS removeTrack() with a sender being rolled back does not crash or throw -PASS Implicit rollback with only a datachannel works -Harness: the test ran to completion. -
diff --git a/third_party/blink/web_tests/http/tests/devtools/application-panel/storage-view-reports-quota.js b/third_party/blink/web_tests/http/tests/devtools/application-panel/storage-view-reports-quota.js index c6d4eae6..82514575 100644 --- a/third_party/blink/web_tests/http/tests/devtools/application-panel/storage-view-reports-quota.js +++ b/third_party/blink/web_tests/http/tests/devtools/application-panel/storage-view-reports-quota.js
@@ -43,7 +43,7 @@ TestRunner.addResult(quotaStripped); TestRunner.addResult('Usage breakdown:'); - const legendElement = view._pieChart.element.shadowRoot.querySelector('.pie-chart-legend'); + const legendElement = view._pieChart.shadowRoot.querySelector('.pie-chart-legend'); for (var i = 0; i < legendElement.children.length; i++) { var typeUsage = ': ';
diff --git a/third_party/blink/web_tests/http/tests/devtools/elements/highlight/highlight-css-grid-direction-expected.txt b/third_party/blink/web_tests/http/tests/devtools/elements/highlight/highlight-css-grid-direction-expected.txt index 869b787..6cb940e5 100644 --- a/third_party/blink/web_tests/http/tests/devtools/elements/highlight/highlight-css-grid-direction-expected.txt +++ b/third_party/blink/web_tests/http/tests/devtools/elements/highlight/highlight-css-grid-direction-expected.txt
@@ -362,13 +362,13 @@ "writingMode": "horizontal-tb", "columnTrackSizes": [ { - "x": 48, + "x": 98, "y": 44, "computedSize": 20, "authoredSize": "20px" }, { - "x": 83, + "x": 63, "y": 44, "computedSize": 50, "authoredSize": "50px" @@ -376,7 +376,7 @@ ], "rowTrackSizes": [ { - "x": 38, + "x": 108, "y": 94, "computedSize": 100, "authoredSize": "100px" @@ -434,50 +434,50 @@ ], "positiveRowLineNumberPositions": [ { - "x": 38, + "x": 108, "y": 44 }, { - "x": 38, + "x": 108, "y": 144 } ], "positiveColumnLineNumberPositions": [ { - "x": 38, - "y": 44 - }, - { - "x": 58, - "y": 44 - }, - { "x": 108, "y": 44 + }, + { + "x": 88, + "y": 44 + }, + { + "x": 38, + "y": 44 } ], "negativeRowLineNumberPositions": [ { - "x": 108, + "x": 38, "y": 44 }, { - "x": 108, + "x": 38, "y": 144 } ], "negativeColumnLineNumberPositions": [ { - "x": 38, - "y": 144 - }, - { - "x": 58, - "y": 144 - }, - { "x": 108, "y": 144 + }, + { + "x": 88, + "y": 144 + }, + { + "x": 38, + "y": 144 } ], "areaNames": {}, @@ -888,13 +888,13 @@ "writingMode": "horizontal-tb", "columnTrackSizes": [ { - "x": 32, + "x": 98, "y": 44, "computedSize": 20, "authoredSize": "20px" }, { - "x": 83, + "x": 47, "y": 44, "computedSize": 50, "authoredSize": "50px" @@ -902,7 +902,7 @@ ], "rowTrackSizes": [ { - "x": 22, + "x": 108, "y": 94, "computedSize": 100, "authoredSize": "100px" @@ -966,50 +966,50 @@ ], "positiveRowLineNumberPositions": [ { - "x": 22, + "x": 108, "y": 44 }, { - "x": 22, + "x": 108, "y": 144 } ], "positiveColumnLineNumberPositions": [ { - "x": 22, - "y": 44 - }, - { - "x": 50, - "y": 44 - }, - { "x": 108, "y": 44 + }, + { + "x": 80, + "y": 44 + }, + { + "x": 22, + "y": 44 } ], "negativeRowLineNumberPositions": [ { - "x": 108, + "x": 22, "y": 44 }, { - "x": 108, + "x": 22, "y": 144 } ], "negativeColumnLineNumberPositions": [ { - "x": 22, - "y": 144 - }, - { - "x": 50, - "y": 144 - }, - { "x": 108, "y": 144 + }, + { + "x": 80, + "y": 144 + }, + { + "x": 22, + "y": 144 } ], "areaNames": {},
diff --git a/third_party/blink/web_tests/http/tests/images/document-policy-image-policies-with-border-radius-expected.txt b/third_party/blink/web_tests/http/tests/images/document-policy-image-policies-with-border-radius-expected.txt index 193602b..36c52e1 100644 --- a/third_party/blink/web_tests/http/tests/images/document-policy-image-policies-with-border-radius-expected.txt +++ b/third_party/blink/web_tests/http/tests/images/document-policy-image-policies-with-border-radius-expected.txt
@@ -1 +1 @@ -CONSOLE ERROR: Document policy violation: lossy-images-max-bpp is not allowed in this document. +CONSOLE ERROR: Document policy violation: Image bpp (byte per pixel) exceeds max value set in lossy-images-max-bpp.
diff --git a/third_party/blink/web_tests/http/tests/images/document-policy-lossless-images-max-bpp-expected.txt b/third_party/blink/web_tests/http/tests/images/document-policy-lossless-images-max-bpp-expected.txt index b19d46d..1ed32eb 100644 --- a/third_party/blink/web_tests/http/tests/images/document-policy-lossless-images-max-bpp-expected.txt +++ b/third_party/blink/web_tests/http/tests/images/document-policy-lossless-images-max-bpp-expected.txt
@@ -1 +1 @@ -CONSOLE ERROR: Document policy violation: lossless-images-max-bpp is not allowed in this document. +CONSOLE ERROR: Document policy violation: Image bpp (byte per pixel) exceeds max value set in lossless-images-max-bpp.
diff --git a/third_party/blink/web_tests/http/tests/images/document-policy-lossless-images-strict-max-bpp-expected.txt b/third_party/blink/web_tests/http/tests/images/document-policy-lossless-images-strict-max-bpp-expected.txt index 3b6e6c6..1af52c9 100644 --- a/third_party/blink/web_tests/http/tests/images/document-policy-lossless-images-strict-max-bpp-expected.txt +++ b/third_party/blink/web_tests/http/tests/images/document-policy-lossless-images-strict-max-bpp-expected.txt
@@ -1,2 +1,2 @@ -CONSOLE ERROR: Document policy violation: lossless-images-strict-max-bpp is not allowed in this document. -CONSOLE ERROR: Document policy violation: lossless-images-strict-max-bpp is not allowed in this document. +CONSOLE ERROR: Document policy violation: Image bpp (byte per pixel) exceeds max value set in lossless-images-strict-max-bpp. +CONSOLE ERROR: Document policy violation: Image bpp (byte per pixel) exceeds max value set in lossless-images-strict-max-bpp.
diff --git a/third_party/blink/web_tests/http/tests/images/document-policy-lossy-images-max-bpp-expected.txt b/third_party/blink/web_tests/http/tests/images/document-policy-lossy-images-max-bpp-expected.txt index 193602b..36c52e1 100644 --- a/third_party/blink/web_tests/http/tests/images/document-policy-lossy-images-max-bpp-expected.txt +++ b/third_party/blink/web_tests/http/tests/images/document-policy-lossy-images-max-bpp-expected.txt
@@ -1 +1 @@ -CONSOLE ERROR: Document policy violation: lossy-images-max-bpp is not allowed in this document. +CONSOLE ERROR: Document policy violation: Image bpp (byte per pixel) exceeds max value set in lossy-images-max-bpp.
diff --git a/third_party/blink/web_tests/http/tests/images/document-policy-unoptimized-images-cached-image-expected.txt b/third_party/blink/web_tests/http/tests/images/document-policy-unoptimized-images-cached-image-expected.txt index a488b2f..7047316 100644 --- a/third_party/blink/web_tests/http/tests/images/document-policy-unoptimized-images-cached-image-expected.txt +++ b/third_party/blink/web_tests/http/tests/images/document-policy-unoptimized-images-cached-image-expected.txt
@@ -1,3 +1,3 @@ -CONSOLE ERROR: Document policy violation: lossy-images-max-bpp is not allowed in this document. -CONSOLE ERROR: Document policy violation: lossy-images-max-bpp is not allowed in this document. -CONSOLE ERROR: Document policy violation: lossy-images-max-bpp is not allowed in this document. +CONSOLE ERROR: Document policy violation: Image bpp (byte per pixel) exceeds max value set in lossy-images-max-bpp. +CONSOLE ERROR: Document policy violation: Image bpp (byte per pixel) exceeds max value set in lossy-images-max-bpp. +CONSOLE ERROR: Document policy violation: Image bpp (byte per pixel) exceeds max value set in lossy-images-max-bpp.
diff --git a/third_party/blink/web_tests/http/tests/loading/wbn/wbn-subresource-origin-trial.https.html b/third_party/blink/web_tests/http/tests/loading/wbn/origin-trial/wbn-subresource-origin-trial.https.html similarity index 100% rename from third_party/blink/web_tests/http/tests/loading/wbn/wbn-subresource-origin-trial.https.html rename to third_party/blink/web_tests/http/tests/loading/wbn/origin-trial/wbn-subresource-origin-trial.https.html
diff --git a/third_party/blink/web_tests/http/tests/loading/wbn/wbn-subresource-third-party-origin-trial.https.html b/third_party/blink/web_tests/http/tests/loading/wbn/origin-trial/wbn-subresource-third-party-origin-trial.https.html similarity index 100% rename from third_party/blink/web_tests/http/tests/loading/wbn/wbn-subresource-third-party-origin-trial.https.html rename to third_party/blink/web_tests/http/tests/loading/wbn/origin-trial/wbn-subresource-third-party-origin-trial.https.html
diff --git a/third_party/blink/web_tests/virtual/subresource-web-bundles-disabled/README.md b/third_party/blink/web_tests/virtual/subresource-web-bundles-disabled/README.md new file mode 100644 index 0000000..213fe33 --- /dev/null +++ b/third_party/blink/web_tests/virtual/subresource-web-bundles-disabled/README.md
@@ -0,0 +1 @@ +In this virtual test suite subresource web bundles are disabled.
diff --git a/third_party/blink/web_tests/virtual/webrtc-wpt-plan-b/external/wpt/webrtc/RTCPeerConnection-setLocalDescription-answer-expected.txt b/third_party/blink/web_tests/virtual/webrtc-wpt-plan-b/external/wpt/webrtc/RTCPeerConnection-setLocalDescription-answer-expected.txt index 6a545e1..72c9b807 100644 --- a/third_party/blink/web_tests/virtual/webrtc-wpt-plan-b/external/wpt/webrtc/RTCPeerConnection-setLocalDescription-answer-expected.txt +++ b/third_party/blink/web_tests/virtual/webrtc-wpt-plan-b/external/wpt/webrtc/RTCPeerConnection-setLocalDescription-answer-expected.txt
@@ -5,6 +5,6 @@ FAIL Calling setLocalDescription(answer) from stable state should reject with InvalidModificationError promise_rejects_dom: function "function() { throw e }" threw object "OperationError: Failed to execute 'setLocalDescription' on 'RTCPeerConnection': Failed to set local answer sdp: Called in wrong state: stable" that is not a DOMException InvalidModificationError: property "code" is equal to 0, expected 13 FAIL Calling setLocalDescription(answer) from have-local-offer state should reject with InvalidModificationError promise_rejects_dom: function "function() { throw e }" threw object "OperationError: Failed to execute 'setLocalDescription' on 'RTCPeerConnection': Failed to set local answer sdp: Called in wrong state: have-local-offer" that is not a DOMException InvalidModificationError: property "code" is equal to 0, expected 13 FAIL Setting previously generated answer after a call to createOffer should work promise_test: Unhandled rejection with value: object "OperationError: Failed to execute 'setRemoteDescription' on 'RTCPeerConnection': Rollback not supported in Plan B" -FAIL setLocalDescription(answer) should update internal state with a queued task, in the right order assert_not_equals: pendingRemoteDescription should not be set synchronously after a call to sLD got disallowed value null +PASS setLocalDescription(answer) should update internal state with a queued task, in the right order Harness: the test ran to completion.
diff --git a/third_party/blink/web_tests/virtual/webrtc-wpt-plan-b/external/wpt/webrtc/RTCPeerConnection-setLocalDescription-offer-expected.txt b/third_party/blink/web_tests/virtual/webrtc-wpt-plan-b/external/wpt/webrtc/RTCPeerConnection-setLocalDescription-offer-expected.txt index 708aba1..2b750bc 100644 --- a/third_party/blink/web_tests/virtual/webrtc-wpt-plan-b/external/wpt/webrtc/RTCPeerConnection-setLocalDescription-offer-expected.txt +++ b/third_party/blink/web_tests/virtual/webrtc-wpt-plan-b/external/wpt/webrtc/RTCPeerConnection-setLocalDescription-offer-expected.txt
@@ -6,6 +6,6 @@ PASS Creating and setting offer multiple times should succeed FAIL Setting previously generated offer after a call to createAnswer should work promise_test: Unhandled rejection with value: object "OperationError: Failed to execute 'setRemoteDescription' on 'RTCPeerConnection': Rollback not supported in Plan B" FAIL Negotiation works when there has been a repeated setLocalDescription(offer) assert_equals: expected 1 but got 0 -FAIL setLocalDescription(offer) should update internal state with a queued task, in the right order assert_equals: pendingRemoteDescription should never be set due to sLD expected null but got object "[object RTCSessionDescription]" +PASS setLocalDescription(offer) should update internal state with a queued task, in the right order Harness: the test ran to completion.
diff --git a/third_party/freetype/README.chromium b/third_party/freetype/README.chromium index b107c641..bba903e3 100644 --- a/third_party/freetype/README.chromium +++ b/third_party/freetype/README.chromium
@@ -1,7 +1,7 @@ Name: FreeType URL: http://www.freetype.org/ -Version: VER-2-10-2-52-gcdc009c24 -Revision: cdc009c24afac88846ed24e21c84e33792384665 +Version: VER-2-10-2-53-g6730854c3 +Revision: 6730854c397130879c64bd766c673b9bccf9c04a CPEPrefix: cpe:/a:freetype:freetype:2.10.1 License: Custom license "inspired by the BSD, Artistic, and IJG (Independent JPEG Group) licenses"
diff --git a/tools/metrics/histograms/PRESUBMIT.py b/tools/metrics/histograms/PRESUBMIT.py index 8071a98..6fb14d3a 100644 --- a/tools/metrics/histograms/PRESUBMIT.py +++ b/tools/metrics/histograms/PRESUBMIT.py
@@ -92,8 +92,10 @@ # change obsolete_histograms.xml. return False - # If the changed file is histograms.xml, pretty-print and validate prefix it. - elif 'histograms.xml' in filepath: + # If the changed file is histograms.xml or histogram_suffixes_list.xml, + # pretty-print and validate prefix it. + elif ('histograms.xml' in filepath + or 'histogram_suffixes_list.xml' in filepath): GetPrettyPrintErrors(input_api, output_api, cwd, filepath, results) # TODO(crbug/1120229): Re-enable validate prefix check once all histograms # are split.
diff --git a/tools/metrics/histograms/enums.xml b/tools/metrics/histograms/enums.xml index dd8fb8e9..c7bd7df 100644 --- a/tools/metrics/histograms/enums.xml +++ b/tools/metrics/histograms/enums.xml
@@ -16175,6 +16175,18 @@ <int value="20" label="showGridTrackSizes.true"/> </enum> +<enum name="DevtoolsGridSettingChanged2"> + <int value="0" label="showGridLineLabels.none"/> + <int value="1" label="showGridLineLabels.lineNumbers"/> + <int value="2" label="showGridLineLabels.lineNames"/> + <int value="3" label="extendGridLines.false"/> + <int value="4" label="extendGridLines.true"/> + <int value="5" label="showGridAreas.false"/> + <int value="6" label="showGridAreas.true"/> + <int value="7" label="showGridTrackSizes.false"/> + <int value="8" label="showGridTrackSizes.true"/> +</enum> + <enum name="DevToolsIssuesPanelOpenedFrom"> <int value="0" label="Console Info Bar"/> <int value="1" label="Learn More Link COEP"/> @@ -20887,8 +20899,6 @@ <int value="111" label="MediaCacheSize"/> <int value="112" label="EnterpriseWebStoreURL"/> <int value="113" label="EnterpriseWebStoreName"/> - <int value="114" label="EnableOriginBoundCerts"/> - <int value="115" label="EnableMemoryInfo"/> <int value="116" label="ProxySettings"/> <int value="117" label="DisablePrintPreview"/> <int value="118" label="DisableSSLRecordSplitting"/> @@ -21316,7 +21326,6 @@ <int value="541" label="DeviceBootOnAcEnabled"/> <int value="542" label="SignedHTTPExchangeEnabled"/> <int value="543" label="DeviceQuickFixBuildToken"/> - <int value="544" label="ExtensionInstallListsMergeEnabled"/> <int value="545" label="SamlInSessionPasswordChangeEnabled"/> <int value="547" label="DeviceDockMacAddressSource"/> <int value="548" label="DeviceAdvancedBatteryChargeModeEnabled"/> @@ -40630,6 +40639,7 @@ <int value="-1696619241" label="OmniboxWrapPopupPosition:disabled"/> <int value="-1696366449" label="disable-permissions-bubbles"/> <int value="-1695774453" label="skip-extra-ash-window-positioning"/> + <int value="-1694900665" label="HandwritingGestureEditing:enabled"/> <int value="-1693498375" label="CdmFactoryDaemon:enabled"/> <int value="-1692967465" label="ContextMenuPerformanceInfoAndRemoteHintFetching:enabled"/> @@ -40787,6 +40797,7 @@ <int value="-1535758690" label="AutoplayIgnoreWebAudio:disabled"/> <int value="-1535694535" label="PageInfoPerformanceHints:enabled"/> <int value="-1533258008" label="CalculateNativeWinOcclusion:enabled"/> + <int value="-1532720464" label="WellKnownChangePassword:enabled"/> <int value="-1532645183" label="ReleaseNotesNotification:enabled"/> <int value="-1532035450" label="DragTabsInTabletMode:disabled"/> <int value="-1532014193" label="disable-encryption-migration"/> @@ -43526,6 +43537,7 @@ <int value="1320450434" label="ArcUsbStorageUI:disabled"/> <int value="1324623677" label="SessionRestorePrioritizesBackgroundUseCases:enabled"/> + <int value="1325459977" label="HandwritingGestureEditing:disabled"/> <int value="1327883321" label="OmniboxHistoryQuickProviderAllowMidwordContinuations:enabled"/> <int value="1330264457" label="OmniboxUIExperimentVerticalLayout:disabled"/> @@ -43665,6 +43677,7 @@ <int value="1467322206" label="AssistAutoCorrect:enabled"/> <int value="1467583815" label="AVIF:disabled"/> <int value="1469407485" label="disable-accelerated-2d-canvas"/> + <int value="1472938299" label="WellKnownChangePassword:disabled"/> <int value="1473838479" label="EnableVirtualKeyboardMdUi:disabled"/> <int value="1473967338" label="OmniboxShortBookmarkSuggestions:enabled"/> <int value="1474861626" label="disable-multi-mirroring"/> @@ -58135,11 +58148,13 @@ </enum> <enum name="ProfileAddNewUser"> - <int value="0" label="Add new user from icon menu"/> + <int value="0" label="(Deprecated) Add new user from icon menu"/> <int value="1" label="Add new user from title bar menu"/> <int value="2" label="Add new user from settings dialog"/> - <int value="3" label="Add new user from the User Manager"/> + <int value="3" label="Add new user from the Profile picker"/> <int value="4" label="Auto-created after deleting last user"/> + <int value="5" label="Add new user from sign-in interception"/> + <int value="6" label="Add new user from the sync flow (to avoid data clash)"/> </enum> <enum name="ProfileAllAccountsCategories">
diff --git a/tools/metrics/histograms/histograms.xml b/tools/metrics/histograms/histograms.xml index 8f632c7..a874fbd 100644 --- a/tools/metrics/histograms/histograms.xml +++ b/tools/metrics/histograms/histograms.xml
@@ -30132,7 +30132,7 @@ <owner>marcheu@chromium.org</owner> <owner>chromeos-gfx@chromium.org</owner> <summary> - DisplayResolution of the mode for the external display we're about to + DisplayResolution of the mode for the internal display we're about to modeset. 0 means the display was powered off. This is recorded every time the internal display is powered on/off, or when an external monitor is plugged in. @@ -37098,7 +37098,7 @@ </histogram> <histogram name="CustomTabs.ParallelRequestStatusOnStart" - enum="CustomTabsParallelRequestStatusOnStart" expires_after="M84"> + enum="CustomTabsParallelRequestStatusOnStart" expires_after="M87"> <owner>lizeb@chromium.org</owner> <owner>cct-team@google.com</owner> <summary> @@ -39812,6 +39812,20 @@ <histogram name="DevTools.CSSGridSettings" enum="DevtoolsGridSettingChanged" expires_after="M87"> + <obsolete> + Removed 08/2020 because the set of settings has changed. Superseded by + DevTools.CSSGridSettings2. + </obsolete> + <owner>yangguo@chromium.org</owner> + <owner>brgoddar@microsoft.com</owner> + <owner>leo.lee@microsoft.com</owner> + <summary> + DevTools settings for CSS grid recorded on launch of the DevTools. + </summary> +</histogram> + +<histogram name="DevTools.CSSGridSettings2" enum="DevtoolsGridSettingChanged2" + expires_after="M88"> <owner>yangguo@chromium.org</owner> <owner>brgoddar@microsoft.com</owner> <owner>leo.lee@microsoft.com</owner> @@ -68097,8 +68111,9 @@ </histogram> <histogram name="Hardware.Display.Count.OnChange" units="units" - expires_after="2020-06-30"> - <owner>erikchen@chromium.org</owner> + expires_after="2021-06-30"> + <owner>sashamcintosh@chromium.org</owner> + <owner>chromeos-gfx@chromium.org</owner> <summary> The number of displays present right after the user has attached or detached a new display. Excludes mirrored displays, but includes sleeping displays. @@ -68106,8 +68121,9 @@ </histogram> <histogram name="Hardware.Display.Count.OnStartup" units="units" - expires_after="2020-06-30"> - <owner>erikchen@chromium.org</owner> + expires_after="2021-06-30"> + <owner>sashamcintosh@chromium.org</owner> + <owner>chromeos-gfx@chromium.org</owner> <summary> The number of displays present at start up. Excludes mirrored displays, but includes sleeping displays. @@ -81464,8 +81480,9 @@ </histogram> <histogram name="Media.MicrophoneMuted" enum="MicrophoneMuteResult" - expires_after="2020-08-30"> + expires_after="2021-08-30"> <owner>henrika@chromium.org</owner> + <owner>webrtc-audio@google.com</owner> <summary> Heuristically detects if the user has muted the microphone or not. Measured approximately four times per minute.
diff --git a/ui/base/dragdrop/os_exchange_data_provider_win.cc b/ui/base/dragdrop/os_exchange_data_provider_win.cc index f5ec26aa..82f17abd6 100644 --- a/ui/base/dragdrop/os_exchange_data_provider_win.cc +++ b/ui/base/dragdrop/os_exchange_data_provider_win.cc
@@ -43,6 +43,9 @@ namespace ui { +static constexpr STGMEDIUM kNullStorageMedium = {.tymed = TYMED_NULL, + .pUnkForRelease = nullptr}; + static const ClipboardFormatType& GetRendererTaintFormatType() { static base::NoDestructor<ClipboardFormatType> format( ClipboardFormatType::GetType("chromium/x-renderer-taint")); @@ -52,9 +55,9 @@ // Creates a new STGMEDIUM object to hold the specified text. The caller // owns the resulting object. The "Bytes" version does not NULL terminate, the // string version does. -static STGMEDIUM* GetStorageForBytes(const void* data, size_t bytes); +static STGMEDIUM GetStorageForBytes(const void* data, size_t bytes); template <typename T> -static STGMEDIUM* GetStorageForString(const std::basic_string<T>& data); +static STGMEDIUM GetStorageForString(const std::basic_string<T>& data); // Creates the contents of an Internet Shortcut file for the given URL. static void GetInternetShortcutFileContents(const GURL& url, std::string* data); // Creates a valid file name given a suggested title and URL. @@ -62,12 +65,11 @@ const base::string16& title, base::string16* validated); // Creates a new STGMEDIUM object to hold files. -static STGMEDIUM* GetStorageForFileNames( - const std::vector<FileInfo>& filenames); -static STGMEDIUM* GetIDListStorageForFileName(const base::FilePath& path); +static STGMEDIUM GetStorageForFileNames(const std::vector<FileInfo>& filenames); +static STGMEDIUM GetIDListStorageForFileName(const base::FilePath& path); // Creates a File Descriptor for the creation of a file to the given URL and // returns a handle to it. -static STGMEDIUM* GetStorageForFileDescriptor(const base::FilePath& path); +static STGMEDIUM GetStorageForFileDescriptor(const base::FilePath& path); /////////////////////////////////////////////////////////////////////////////// // FormatEtcEnumerator @@ -126,10 +128,10 @@ }; // Safely makes a copy of all of the relevant bits of a FORMATETC object. -static void CloneFormatEtc(FORMATETC* source, FORMATETC* clone) { +static void CloneFormatEtc(const FORMATETC* source, FORMATETC* clone) { *clone = *source; if (source->ptd) { - source->ptd = + clone->ptd = static_cast<DVTARGETDEVICE*>(CoTaskMemAlloc(sizeof(DVTARGETDEVICE))); *(clone->ptd) = *(source->ptd); } @@ -292,8 +294,8 @@ } void OSExchangeDataProviderWin::MarkOriginatedFromRenderer() { - STGMEDIUM* storage = GetStorageForString(std::string()); - data_->contents_.push_back(std::make_unique<DataObjectImpl::StoredDataInfo>( + STGMEDIUM storage = GetStorageForString(std::string()); + data_->contents_.push_back(DataObjectImpl::StoredDataInfo::TakeStorageMedium( GetRendererTaintFormatType().ToFormatEtc(), storage)); } @@ -302,13 +304,13 @@ } void OSExchangeDataProviderWin::SetString(const base::string16& data) { - STGMEDIUM* storage = GetStorageForString(data); - data_->contents_.push_back(std::make_unique<DataObjectImpl::StoredDataInfo>( + STGMEDIUM storage = GetStorageForString(data); + data_->contents_.push_back(DataObjectImpl::StoredDataInfo::TakeStorageMedium( ClipboardFormatType::GetPlainTextType().ToFormatEtc(), storage)); // Also add the UTF8-encoded version. storage = GetStorageForString(base::UTF16ToUTF8(data)); - data_->contents_.push_back(std::make_unique<DataObjectImpl::StoredDataInfo>( + data_->contents_.push_back(DataObjectImpl::StoredDataInfo::TakeStorageMedium( ClipboardFormatType::GetPlainTextAType().ToFormatEtc(), storage)); } @@ -324,8 +326,8 @@ base::string16 x_moz_url_str = base::UTF8ToUTF16(url.spec()); x_moz_url_str += '\n'; x_moz_url_str += title; - STGMEDIUM* storage = GetStorageForString(x_moz_url_str); - data_->contents_.push_back(std::make_unique<DataObjectImpl::StoredDataInfo>( + STGMEDIUM storage = GetStorageForString(x_moz_url_str); + data_->contents_.push_back(DataObjectImpl::StoredDataInfo::TakeStorageMedium( ClipboardFormatType::GetMozUrlType().ToFormatEtc(), storage)); // Add a .URL shortcut file for dragging to Explorer. @@ -337,10 +339,10 @@ // Add a UniformResourceLocator link for apps like IE and Word. storage = GetStorageForString(base::UTF8ToUTF16(url.spec())); - data_->contents_.push_back(std::make_unique<DataObjectImpl::StoredDataInfo>( + data_->contents_.push_back(DataObjectImpl::StoredDataInfo::TakeStorageMedium( ClipboardFormatType::GetUrlType().ToFormatEtc(), storage)); storage = GetStorageForString(url.spec()); - data_->contents_.push_back(std::make_unique<DataObjectImpl::StoredDataInfo>( + data_->contents_.push_back(DataObjectImpl::StoredDataInfo::TakeStorageMedium( ClipboardFormatType::GetUrlAType().ToFormatEtc(), storage)); // TODO(https://crbug.com/6767): add CF_HTML. @@ -353,20 +355,20 @@ void OSExchangeDataProviderWin::SetFilename(const base::FilePath& path) { SetFilenames({FileInfo(path, base::FilePath())}); - STGMEDIUM* storage = GetIDListStorageForFileName(path); - if (!storage) + STGMEDIUM storage = GetIDListStorageForFileName(path); + if (storage.tymed == TYMED_NULL) return; - data_->contents_.push_back(std::make_unique<DataObjectImpl::StoredDataInfo>( + data_->contents_.push_back(DataObjectImpl::StoredDataInfo::TakeStorageMedium( ClipboardFormatType::GetIDListType().ToFormatEtc(), storage)); } void OSExchangeDataProviderWin::SetFilenames( const std::vector<FileInfo>& filenames) { - STGMEDIUM* storage = GetStorageForFileNames(filenames); - if (!storage) + STGMEDIUM storage = GetStorageForFileNames(filenames); + if (storage.tymed == TYMED_NULL) return; - data_->contents_.push_back(std::make_unique<DataObjectImpl::StoredDataInfo>( + data_->contents_.push_back(DataObjectImpl::StoredDataInfo::TakeStorageMedium( ClipboardFormatType::GetCFHDropType().ToFormatEtc(), storage)); } @@ -394,12 +396,9 @@ FILEGROUPDESCRIPTORW* descriptor = locked_mem.get(); descriptor->cItems = num_files; - STGMEDIUM* storage = new STGMEDIUM; - storage->tymed = TYMED_HGLOBAL; - storage->hGlobal = hdata; - storage->pUnkForRelease = NULL; - - data_->contents_.push_back(std::make_unique<DataObjectImpl::StoredDataInfo>( + STGMEDIUM storage = { + .tymed = TYMED_HGLOBAL, .hGlobal = hdata, .pUnkForRelease = nullptr}; + data_->contents_.push_back(DataObjectImpl::StoredDataInfo::TakeStorageMedium( ClipboardFormatType::GetFileDescriptorType().ToFormatEtc(), storage)); for (size_t i = 0; i < num_files; i++) { @@ -422,12 +421,9 @@ base::span<const uint8_t> data_buffer, DWORD tymed, size_t index) { - std::unique_ptr<STGMEDIUM> storage_for_contents; + STGMEDIUM storage_for_contents = kNullStorageMedium; if (tymed == TYMED_ISTORAGE) { - storage_for_contents = std::make_unique<STGMEDIUM>(); - storage_for_contents->pUnkForRelease = nullptr; - Microsoft::WRL::ComPtr<ILockBytes> lock_bytes; HRESULT hr = ::CreateILockBytesOnHGlobal( nullptr, /* fDeleteOnRelease*/ TRUE, &lock_bytes); @@ -435,12 +431,12 @@ if (SUCCEEDED(hr)) { hr = ::StgCreateDocfileOnILockBytes( lock_bytes.Get(), STGM_READWRITE | STGM_SHARE_EXCLUSIVE | STGM_CREATE, - 0, &storage_for_contents->pstg); + 0, &storage_for_contents.pstg); } Microsoft::WRL::ComPtr<IStream> destination_stream; if (SUCCEEDED(hr)) { - hr = storage_for_contents->pstg->CreateStream( + hr = storage_for_contents.pstg->CreateStream( L"Contents", STGM_READWRITE | STGM_SHARE_EXCLUSIVE | STGM_CREATE, 0, 0, &destination_stream); } @@ -459,40 +455,38 @@ nullptr, nullptr); } if (SUCCEEDED(hr)) - hr = storage_for_contents->pstg->Commit(STGC_DEFAULT); + hr = storage_for_contents.pstg->Commit(STGC_DEFAULT); if (SUCCEEDED(hr)) - storage_for_contents->tymed = TYMED_ISTORAGE; + storage_for_contents.tymed = TYMED_ISTORAGE; } else if (tymed == TYMED_ISTREAM) { - storage_for_contents = std::make_unique<STGMEDIUM>(); - storage_for_contents->pUnkForRelease = nullptr; - storage_for_contents->pstm = + storage_for_contents.pstm = ::SHCreateMemStream(data_buffer.data(), data_buffer.size_bytes()); - if (storage_for_contents->pstm) { + if (storage_for_contents.pstm) { // A properly implemented IDataObject::GetData moves the stream pointer // to end. const LARGE_INTEGER kZeroDisplacement = {}; - HRESULT hr = storage_for_contents->pstm->Seek(kZeroDisplacement, - STREAM_SEEK_END, nullptr); + HRESULT hr = storage_for_contents.pstm->Seek(kZeroDisplacement, + STREAM_SEEK_END, nullptr); if (SUCCEEDED(hr)) - storage_for_contents->tymed = TYMED_ISTREAM; + storage_for_contents.tymed = TYMED_ISTREAM; } } else if (tymed == TYMED_HGLOBAL) { - storage_for_contents.reset( - GetStorageForBytes(data_buffer.data(), data_buffer.size_bytes())); + storage_for_contents = + GetStorageForBytes(data_buffer.data(), data_buffer.size_bytes()); } ClipboardFormatType type = ClipboardFormatType::GetFileContentAtIndexType(index); // Pass ownership of |storage_for_contents| here. - data_->contents_.push_back(std::make_unique<DataObjectImpl::StoredDataInfo>( - type.ToFormatEtc(), storage_for_contents.release())); + data_->contents_.push_back(DataObjectImpl::StoredDataInfo::TakeStorageMedium( + type.ToFormatEtc(), storage_for_contents)); } void OSExchangeDataProviderWin::SetPickledData( const ClipboardFormatType& format, const base::Pickle& data) { - STGMEDIUM* storage = GetStorageForBytes(data.data(), data.size()); - data_->contents_.push_back(std::make_unique<DataObjectImpl::StoredDataInfo>( + STGMEDIUM storage = GetStorageForBytes(data.data(), data.size()); + data_->contents_.push_back(DataObjectImpl::StoredDataInfo::TakeStorageMedium( format.ToFormatEtc(), storage)); } @@ -500,14 +494,16 @@ const base::FilePath& filename, const std::string& file_contents) { // Add CFSTR_FILEDESCRIPTORW. - STGMEDIUM* storage = GetStorageForFileDescriptor(filename); - data_->contents_.push_back(std::make_unique<DataObjectImpl::StoredDataInfo>( + STGMEDIUM storage = GetStorageForFileDescriptor(filename); + data_->contents_.push_back(DataObjectImpl::StoredDataInfo::TakeStorageMedium( ClipboardFormatType::GetFileDescriptorType().ToFormatEtc(), storage)); // Add CFSTR_FILECONTENTS. - storage = GetStorageForBytes(file_contents.data(), file_contents.length()); - data_->contents_.push_back(std::make_unique<DataObjectImpl::StoredDataInfo>( - ClipboardFormatType::GetFileContentZeroType().ToFormatEtc(), storage)); + STGMEDIUM storage_contents = + GetStorageForBytes(file_contents.data(), file_contents.length()); + data_->contents_.push_back(DataObjectImpl::StoredDataInfo::TakeStorageMedium( + ClipboardFormatType::GetFileContentZeroType().ToFormatEtc(), + storage_contents)); } void OSExchangeDataProviderWin::SetHtml(const base::string16& html, @@ -517,13 +513,13 @@ std::string url = base_url.is_valid() ? base_url.spec() : std::string(); std::string cf_html = ClipboardUtil::HtmlToCFHtml(utf8_html, url); - STGMEDIUM* storage = GetStorageForBytes(cf_html.c_str(), cf_html.size()); - data_->contents_.push_back(std::make_unique<DataObjectImpl::StoredDataInfo>( + STGMEDIUM storage = GetStorageForBytes(cf_html.c_str(), cf_html.size()); + data_->contents_.push_back(DataObjectImpl::StoredDataInfo::TakeStorageMedium( ClipboardFormatType::GetHtmlType().ToFormatEtc(), storage)); - STGMEDIUM* storage_plain = GetStorageForBytes(utf8_html.c_str(), - utf8_html.size()); - data_->contents_.push_back(std::make_unique<DataObjectImpl::StoredDataInfo>( + STGMEDIUM storage_plain = + GetStorageForBytes(utf8_html.c_str(), utf8_html.size()); + data_->contents_.push_back(DataObjectImpl::StoredDataInfo::TakeStorageMedium( ClipboardFormatType::GetTextHtmlType().ToFormatEtc(), storage_plain)); } @@ -681,12 +677,12 @@ // the delay rendering will be used. // TODO(dcheng): Is it actually possible for filename to be empty here? I // think we always synthesize one in WebContentsDragWin. - STGMEDIUM* storage = NULL; + STGMEDIUM storage = kNullStorageMedium; if (!download->filename.empty()) GetStorageForFileNames({FileInfo(download->filename, base::FilePath())}); // Add CF_HDROP. - auto info = std::make_unique<DataObjectImpl::StoredDataInfo>( + auto info = DataObjectImpl::StoredDataInfo::TakeStorageMedium( ClipboardFormatType::GetCFHDropType().ToFormatEtc(), storage); info->downloader = std::move(download->downloader); data_->contents_.push_back(std::move(info)); @@ -788,63 +784,69 @@ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -static void DuplicateMedium(CLIPFORMAT source_clipformat, - STGMEDIUM* source, - STGMEDIUM* destination) { - switch (source->tymed) { +static STGMEDIUM DuplicateMedium(CLIPFORMAT clipformat, + const STGMEDIUM& storage) { + STGMEDIUM copied = kNullStorageMedium; + switch (storage.tymed) { case TYMED_HGLOBAL: - destination->hGlobal = - static_cast<HGLOBAL>(OleDuplicateData( - source->hGlobal, source_clipformat, 0)); + copied.hGlobal = static_cast<HGLOBAL>( + OleDuplicateData(storage.hGlobal, clipformat, 0)); break; case TYMED_MFPICT: - destination->hMetaFilePict = - static_cast<HMETAFILEPICT>(OleDuplicateData( - source->hMetaFilePict, source_clipformat, 0)); + copied.hMetaFilePict = static_cast<HMETAFILEPICT>( + OleDuplicateData(storage.hMetaFilePict, clipformat, 0)); break; case TYMED_GDI: - destination->hBitmap = - static_cast<HBITMAP>(OleDuplicateData( - source->hBitmap, source_clipformat, 0)); + copied.hBitmap = static_cast<HBITMAP>( + OleDuplicateData(storage.hBitmap, clipformat, 0)); break; case TYMED_ENHMF: - destination->hEnhMetaFile = - static_cast<HENHMETAFILE>(OleDuplicateData( - source->hEnhMetaFile, source_clipformat, 0)); + copied.hEnhMetaFile = static_cast<HENHMETAFILE>( + OleDuplicateData(storage.hEnhMetaFile, clipformat, 0)); break; case TYMED_FILE: - destination->lpszFileName = - static_cast<LPOLESTR>(OleDuplicateData( - source->lpszFileName, source_clipformat, 0)); + copied.lpszFileName = static_cast<LPOLESTR>( + OleDuplicateData(storage.lpszFileName, clipformat, 0)); break; case TYMED_ISTREAM: - destination->pstm = source->pstm; - destination->pstm->AddRef(); + copied.pstm = storage.pstm; + copied.pstm->AddRef(); break; case TYMED_ISTORAGE: - destination->pstg = source->pstg; - destination->pstg->AddRef(); + copied.pstg = storage.pstg; + copied.pstg->AddRef(); break; } - destination->tymed = source->tymed; - destination->pUnkForRelease = source->pUnkForRelease; - if (destination->pUnkForRelease) - destination->pUnkForRelease->AddRef(); + copied.tymed = storage.tymed; + copied.pUnkForRelease = storage.pUnkForRelease; + if (copied.pUnkForRelease) + copied.pUnkForRelease->AddRef(); + + return copied; } -DataObjectImpl::StoredDataInfo::StoredDataInfo(const FORMATETC& format_etc, - STGMEDIUM* medium) - : format_etc(format_etc), medium(medium) {} - DataObjectImpl::StoredDataInfo::~StoredDataInfo() { - ReleaseStgMedium(medium); - delete medium; - + ReleaseStgMedium(&medium); if (downloader.get()) downloader->Stop(); } +// Takes ownership of and nullifies `medium`. +std::unique_ptr<DataObjectImpl::StoredDataInfo> +DataObjectImpl::StoredDataInfo::TakeStorageMedium(const FORMATETC& format_etc, + STGMEDIUM& medium) { + std::unique_ptr<StoredDataInfo> info(new StoredDataInfo(format_etc, medium)); + + // Null `medium` out. + medium = kNullStorageMedium; + return info; +} + +DataObjectImpl::StoredDataInfo::StoredDataInfo(const FORMATETC& format_etc, + const STGMEDIUM& medium) + : format_etc(format_etc), medium(medium) {} + DataObjectImpl::DataObjectImpl() : is_aborting_(false), in_drag_loop_(false), @@ -888,9 +890,9 @@ if (downloader) downloader->Stop(); // Replace stored data. - STGMEDIUM* storage = + STGMEDIUM storage = GetStorageForFileNames({FileInfo(file_path, base::FilePath())}); - content = std::make_unique<StoredDataInfo>( + content = StoredDataInfo::TakeStorageMedium( ClipboardFormatType::GetCFHDropType().ToFormatEtc(), storage); content->downloader = std::move(downloader); break; @@ -909,8 +911,9 @@ content->format_etc.lindex == format_etc->lindex && (content->format_etc.tymed & format_etc->tymed)) { // If medium is NULL, delay-rendering will be used. - if (content->medium) { - DuplicateMedium(content->format_etc.cfFormat, content->medium, medium); + if (content->medium.tymed != TYMED_NULL) { + *medium = + DuplicateMedium(content->format_etc.cfFormat, content->medium); return S_OK; } // Fail all GetData() attempts for DownloadURL data if the drag and drop @@ -970,19 +973,13 @@ FORMATETC* format_etc, STGMEDIUM* medium, BOOL should_release) { RemoveData(*format_etc); - STGMEDIUM* local_medium = new STGMEDIUM; - if (should_release) { - // Ownership of the original data in `medium` is transferred to `this`. - *local_medium = *medium; - } else { - // Ownership of `medium` remains with the caller. To prevent lifetime - // issues, perform a deep copy of `medium`. - DuplicateMedium(format_etc->cfFormat, medium, local_medium); - } - - auto info = std::make_unique<DataObjectImpl::StoredDataInfo>(*format_etc, - local_medium); - info->medium->tymed = format_etc->tymed; + // If `should_release` is true, ownership of the original data in `medium` is + // transferred to `this`. Otherwise it remains with the caller. To prevent + // lifetime issues, perform a deep copy of `medium`. + STGMEDIUM local_medium = + should_release ? *medium : DuplicateMedium(format_etc->cfFormat, *medium); + DCHECK_EQ(local_medium.tymed, format_etc->tymed); + auto info = StoredDataInfo::TakeStorageMedium(*format_etc, local_medium); // Make newly added data appear first. // TODO(dcheng): Make various setters agree whether elements should be @@ -1078,22 +1075,20 @@ /////////////////////////////////////////////////////////////////////////////// // DataObjectImpl, private: -static STGMEDIUM* GetStorageForBytes(const void* data, size_t bytes) { +static STGMEDIUM GetStorageForBytes(const void* data, size_t bytes) { HANDLE handle = GlobalAlloc(GPTR, static_cast<int>(bytes)); if (handle) { base::win::ScopedHGlobal<uint8_t*> scoped(handle); memcpy(scoped.get(), data, bytes); } - STGMEDIUM* storage = new STGMEDIUM; - storage->hGlobal = handle; - storage->tymed = TYMED_HGLOBAL; - storage->pUnkForRelease = NULL; + STGMEDIUM storage = { + .tymed = TYMED_HGLOBAL, .hGlobal = handle, .pUnkForRelease = nullptr}; return storage; } template <typename T> -static STGMEDIUM* GetStorageForString(const std::basic_string<T>& data) { +static STGMEDIUM GetStorageForString(const std::basic_string<T>& data) { return GetStorageForBytes( data.c_str(), (data.size() + 1) * sizeof(typename std::basic_string<T>::value_type)); @@ -1131,7 +1126,7 @@ *validated += kExtension; } -static STGMEDIUM* GetStorageForFileNames( +static STGMEDIUM GetStorageForFileNames( const std::vector<FileInfo>& filenames) { // CF_HDROP clipboard format consists of DROPFILES structure, a series of file // names including the terminating null character and the additional null @@ -1142,7 +1137,7 @@ // https://docs.microsoft.com/en-us/windows/desktop/shell/clipboard#cf_hdrop if (filenames.empty()) - return nullptr; + return kNullStorageMedium; const size_t kDropFilesHeaderSizeInBytes = sizeof(DROPFILES); size_t total_bytes = kDropFilesHeaderSizeInBytes; @@ -1173,10 +1168,8 @@ next_filename_offset += filename.path.value().length() + 1; } - STGMEDIUM* storage = new STGMEDIUM; - storage->tymed = TYMED_HGLOBAL; - storage->hGlobal = hdata; - storage->pUnkForRelease = nullptr; + STGMEDIUM storage = { + .tymed = TYMED_HGLOBAL, .hGlobal = hdata, .pUnkForRelease = nullptr}; return storage; } @@ -1214,10 +1207,10 @@ return SUCCEEDED(hr) ? pidl : NULL; } -static STGMEDIUM* GetIDListStorageForFileName(const base::FilePath& path) { +static STGMEDIUM GetIDListStorageForFileName(const base::FilePath& path) { LPITEMIDLIST pidl = GetPidlFromPath(path); if (!pidl) - return NULL; + return kNullStorageMedium; // When using CFSTR_SHELLIDLIST the hGlobal field of the STGMEDIUM is a // pointer to a CIDA*. A CIDA is a variable length struct that contains a PIDL @@ -1250,15 +1243,12 @@ idl = GetNthPIDL(cida, 1); memcpy(idl, pidl, kSecondPIDLSize); - STGMEDIUM* storage = new STGMEDIUM; - storage->tymed = TYMED_HGLOBAL; - storage->hGlobal = hdata; - storage->pUnkForRelease = NULL; + STGMEDIUM storage = { + .tymed = TYMED_HGLOBAL, .hGlobal = hdata, .pUnkForRelease = nullptr}; return storage; } -static STGMEDIUM* GetStorageForFileDescriptor( - const base::FilePath& path) { +static STGMEDIUM GetStorageForFileDescriptor(const base::FilePath& path) { base::string16 file_name = path.value(); DCHECK(!file_name.empty()); HANDLE hdata = GlobalAlloc(GPTR, sizeof(FILEGROUPDESCRIPTORW)); @@ -1270,10 +1260,8 @@ wcsncpy_s(descriptor->fgd[0].cFileName, MAX_PATH, file_name.c_str(), std::min(file_name.size(), static_cast<size_t>(MAX_PATH - 1u))); - STGMEDIUM* storage = new STGMEDIUM; - storage->tymed = TYMED_HGLOBAL; - storage->hGlobal = hdata; - storage->pUnkForRelease = NULL; + STGMEDIUM storage = { + .tymed = TYMED_HGLOBAL, .hGlobal = hdata, .pUnkForRelease = nullptr}; return storage; }
diff --git a/ui/base/dragdrop/os_exchange_data_provider_win.h b/ui/base/dragdrop/os_exchange_data_provider_win.h index d4f8c93..1fb90911 100644 --- a/ui/base/dragdrop/os_exchange_data_provider_win.h +++ b/ui/base/dragdrop/os_exchange_data_provider_win.h
@@ -87,12 +87,26 @@ // Our internal representation of stored data & type info. struct StoredDataInfo { + public: FORMATETC format_etc; - STGMEDIUM* medium; + STGMEDIUM medium; std::unique_ptr<DownloadFileProvider> downloader; - StoredDataInfo(const FORMATETC& format_etc, STGMEDIUM* medium); ~StoredDataInfo(); + StoredDataInfo(const StoredDataInfo&) = delete; + StoredDataInfo& operator=(const StoredDataInfo&) = delete; + + // Takes ownership of and nullifies `medium` to approximate moving from + // STGMEDIUM. + static std::unique_ptr<StoredDataInfo> TakeStorageMedium( + const FORMATETC& format_etc, + STGMEDIUM& medium); + + private: + // STGMEDIUM is just a POD, it does not guarantee `medium` is no longer be + // used after calling this constructor while the ownership of `medium` is + // passed. + StoredDataInfo(const FORMATETC& format_etc, const STGMEDIUM& medium); }; typedef std::vector<std::unique_ptr<StoredDataInfo>> StoredData;
diff --git a/ui/compositor/test/direct_layer_tree_frame_sink.cc b/ui/compositor/test/direct_layer_tree_frame_sink.cc index 56aeb98..c5ae3fb 100644 --- a/ui/compositor/test/direct_layer_tree_frame_sink.cc +++ b/ui/compositor/test/direct_layer_tree_frame_sink.cc
@@ -145,7 +145,7 @@ void DirectLayerTreeFrameSink::DisplayWillDrawAndSwap( bool will_draw_and_swap, - viz::RenderPassList* render_passes) { + viz::AggregatedRenderPassList* render_passes) { if (support_->GetHitTestAggregator()) { support_->GetHitTestAggregator()->Aggregate(display_->CurrentSurfaceId(), render_passes);
diff --git a/ui/compositor/test/direct_layer_tree_frame_sink.h b/ui/compositor/test/direct_layer_tree_frame_sink.h index 31d6340..3ad16568 100644 --- a/ui/compositor/test/direct_layer_tree_frame_sink.h +++ b/ui/compositor/test/direct_layer_tree_frame_sink.h
@@ -58,8 +58,9 @@ // viz::DisplayClient implementation. void DisplayOutputSurfaceLost() override; - void DisplayWillDrawAndSwap(bool will_draw_and_swap, - viz::RenderPassList* render_passes) override; + void DisplayWillDrawAndSwap( + bool will_draw_and_swap, + viz::AggregatedRenderPassList* render_passes) override; void DisplayDidDrawAndSwap() override {} void DisplayDidReceiveCALayerParams( const gfx::CALayerParams& ca_layer_params) override {}
diff --git a/ui/events/test/event_generator.cc b/ui/events/test/event_generator.cc index 3978347..18809e3f 100644 --- a/ui/events/test/event_generator.cc +++ b/ui/events/test/event_generator.cc
@@ -593,12 +593,16 @@ Dispatch(&scroll); } -void EventGenerator::PressKey(ui::KeyboardCode key_code, int flags) { - DispatchKeyEvent(true, key_code, flags); +void EventGenerator::PressKey(ui::KeyboardCode key_code, + int flags, + int source_device_id) { + DispatchKeyEvent(true, key_code, flags, source_device_id); } -void EventGenerator::ReleaseKey(ui::KeyboardCode key_code, int flags) { - DispatchKeyEvent(false, key_code, flags); +void EventGenerator::ReleaseKey(ui::KeyboardCode key_code, + int flags, + int source_device_id) { + DispatchKeyEvent(false, key_code, flags, source_device_id); } void EventGenerator::Dispatch(ui::Event* event) { @@ -640,7 +644,8 @@ void EventGenerator::DispatchKeyEvent(bool is_press, ui::KeyboardCode key_code, - int flags) { + int flags, + int source_device_id) { #if defined(OS_WIN) UINT key_press = WM_KEYDOWN; uint16_t character = ui::DomCodeToUsLayoutCharacter( @@ -666,6 +671,7 @@ ui::EventType type = is_press ? ui::ET_KEY_PRESSED : ui::ET_KEY_RELEASED; ui::KeyEvent keyev(type, key_code, flags); #endif // OS_WIN + keyev.set_source_device_id(source_device_id); Dispatch(&keyev); }
diff --git a/ui/events/test/event_generator.h b/ui/events/test/event_generator.h index b052879..6d2094e 100644 --- a/ui/events/test/event_generator.h +++ b/ui/events/test/event_generator.h
@@ -443,13 +443,17 @@ // event without native_event() is generated. Note that ui::EF_ flags should // be passed as |flags|, not the native ones like 'ShiftMask' in <X11/X.h>. // TODO(yusukes): Support native_event() on all platforms. - void PressKey(KeyboardCode key_code, int flags); + void PressKey(KeyboardCode key_code, + int flags, + int source_device_id = ED_UNKNOWN_DEVICE); // Generates a key release event. On platforms except Windows and X11, a key // event without native_event() is generated. Note that ui::EF_ flags should // be passed as |flags|, not the native ones like 'ShiftMask' in <X11/X.h>. // TODO(yusukes): Support native_event() on all platforms. - void ReleaseKey(KeyboardCode key_code, int flags); + void ReleaseKey(KeyboardCode key_code, + int flags, + int source_device_id = ED_UNKNOWN_DEVICE); // Dispatch the event to the WindowEventDispatcher. void Dispatch(Event* event); @@ -466,7 +470,10 @@ void Init(gfx::NativeWindow root_window, gfx::NativeWindow target_window); // Dispatch a key event to the WindowEventDispatcher. - void DispatchKeyEvent(bool is_press, KeyboardCode key_code, int flags); + void DispatchKeyEvent(bool is_press, + KeyboardCode key_code, + int flags, + int source_device_id); void UpdateCurrentDispatcher(const gfx::Point& point); void PressButton(int flag);
diff --git a/ui/file_manager/BUILD.gn b/ui/file_manager/BUILD.gn index cdb9cca..211d18c 100644 --- a/ui/file_manager/BUILD.gn +++ b/ui/file_manager/BUILD.gn
@@ -51,7 +51,6 @@ "integration_tests:closure_compile", "integration_tests/file_manager:closure_compile", "video_player/js:closure_compile", - "video_player/js/cast:closure_compile", ] }
diff --git a/ui/file_manager/file_manager/foreground/js/metadata/content_metadata_provider.js b/ui/file_manager/file_manager/foreground/js/metadata/content_metadata_provider.js index dbeeb99..e136a1e 100644 --- a/ui/file_manager/file_manager/foreground/js/metadata/content_metadata_provider.js +++ b/ui/file_manager/file_manager/foreground/js/metadata/content_metadata_provider.js
@@ -67,6 +67,7 @@ const promises = []; for (let i = 0; i < requests.length; i++) { + // TODO(crbug.com/1114622): is the .bind actually needed here? promises.push(new Promise(((request, fulfill) => { this.getImpl_( request.entry, request.names, fulfill); @@ -76,11 +77,11 @@ } /** - * Fetches the metadata. + * Fetches the entry metadata. * @param {!Entry} entry File entry. - * @param {!Array<string>} names Requested metadata type. - * @param {function(!MetadataItem)} callback Callback expects metadata value. - * This callback is called asynchronously. + * @param {!Array<string>} names Requested metadata types. + * @param {function(!MetadataItem)} callback MetadataItem callback. Note + * this callback is called asynchronously. * @private */ getImpl_(entry, names, callback) { @@ -239,7 +240,7 @@ } /** - * Handles the 'initialized' message from the metadata reader Worker. + * Handles the 'initialized' message from the metadata Worker. * @param {RegExp} regexp Regexp of supported urls. * @private */ @@ -257,7 +258,7 @@ } /** - * Handles the 'result' message from the worker. + * Handles the 'result' message from the metadata Worker. * @param {string} url File url. * @param {!MetadataItem} metadataItem The metadata item. * @private @@ -271,7 +272,7 @@ } /** - * Handles the 'log' message from the worker. + * Handles the 'log' message from the metadata Worker. * @param {Array<*>} arglist Log arguments. * @private */ @@ -284,7 +285,7 @@ * Dispatches a message from MediaGalleries API to the appropriate on* method. * @param {!Entry} entry File entry. * @param {!Object} metadata The metadata from MediaGalleries API. - * @return {!Promise<!MetadataItem>} Promise that resolves with + * @return {!Promise<!MetadataItem>} Promise that resolves with the * converted metadata item. * @private */ @@ -367,9 +368,9 @@ } /** - * Handles the 'error' message from the worker. + * Returns an 'error' MetadataItem. * @param {string} url File entry. - * @param {string} step Step failed. + * @param {string} step Step that failed. * @param {string} errorDescription Error description. * @return {!MetadataItem} Error metadata * @private @@ -392,7 +393,7 @@ ContentMetadataProvider.Error = class extends Error { /** * @param {string} url File Entry. - * @param {string} step Step failed. + * @param {string} step Step that failed. * @param {string} errorDescription Error description. */ constructor(url, step, errorDescription) { @@ -429,7 +430,7 @@ ]; /** - * Path of a worker script. + * The metadata Worker script URL. * @public @const {string} */ ContentMetadataProvider.WORKER_SCRIPT =
diff --git a/ui/file_manager/video_player/css/arrow_box.css b/ui/file_manager/video_player/css/arrow_box.css index ff3919c..5b58c7b 100644 --- a/ui/file_manager/video_player/css/arrow_box.css +++ b/ui/file_manager/video_player/css/arrow_box.css
@@ -17,8 +17,8 @@ flex-grow: 1; } -#video-player[tools]:not([first-video]) .arrow.left, -#video-player[tools]:not([last-video]) .arrow.right { +#video-player:not([first-video]) .arrow.left, +#video-player:not([last-video]) .arrow.right { pointer-events: auto; }
diff --git a/ui/file_manager/video_player/css/cast_menu.css b/ui/file_manager/video_player/css/cast_menu.css deleted file mode 100644 index b3978d193..0000000 --- a/ui/file_manager/video_player/css/cast_menu.css +++ /dev/null
@@ -1,80 +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. */ - -.cast-menu { - background-color: white; - border-radius: 2px; - box-shadow: 0 2px 2px 0 rgba(0, 0, 0, 0.14), - 0 1px 5px 0 rgba(0, 0, 0, 0.12), - 0 3px 1px -2px rgba(0, 0, 0, 0.2); - margin-bottom: 3px; - min-width: 120px; - outline: none; - overflow: hidden; - padding: 0 0 7px; - position: absolute; - z-index: 1000; -} - -.cast-menu:before { - -webkit-padding-start: 12px; - border-bottom: solid 1px rgb(217, 217, 217); - color: rgb(77, 77, 77); - content: attr(playon-text); - display: block; - font-size: 13px; - font-weight: 500; - margin-bottom: 7px; - padding-bottom: 9px; - padding-top: 9px; -} - -/* Make the width of the horizontal border one device pixel even on HiDPI. - * crbug.com/417113. */ -@media (-webkit-min-device-pixel-ratio: 2) { - .cast-menu:before { - border-bottom: none; - background-image: linear-gradient(rgba(217, 217, 217, 1), - rgba(217, 217, 217, 1), - rgba(217, 217, 217, 0), - rgba(217, 217, 217, 0)); - background-position: bottom; - background-size: 100% 1px; - background-repeat: no-repeat; - } -} - -.cast-menu.hidden { - display: none; -} - -.cast-menu > :not(hr) { - -webkit-padding-end: 10px; - -webkit-padding-start: 36px; - color: rgb(51, 51, 51); - font-size: 13px; - height: 32px; - line-height: 32px; - text-overflow: ellipsis; -} - -.cast-menu > :not(hr):hover { - background-color: rgb(235, 235, 235); -} - -.cast-menu > [checked]:not(hr) { - background-image: -webkit-image-set( - url(../images/media/media_check.png) 1x, - url(../images/media/2x/media_check.png) 2x); - background-position: left 10px center; - background-repeat: no-repeat; -} - -html[dir='rtl'] .cast-menu > [checked]:not(hr) { - background-position: right 10px center; -} - -.cast-menu > [checked]:before { - display: none; -}
diff --git a/ui/file_manager/video_player/css/media_controls.css b/ui/file_manager/video_player/css/media_controls.css deleted file mode 100644 index 27adf95b..0000000 --- a/ui/file_manager/video_player/css/media_controls.css +++ /dev/null
@@ -1,281 +0,0 @@ -/* Copyright (c) 2012 The Chromium Authors. All rights reserved. - * Use of this source code is governed by a BSD-style license that can be - * found in the LICENSE file. */ - -/* Common styles for media buttons. */ - -.media-button { - background-position: center; - background-repeat: no-repeat; - flex: none; - height: 32px; - position: relative; - width: 32px; -} - -.media-button.disabled { - background-color: transparent; - opacity: 0.26; -} - -.media-button.disabled, -cr-slider.readonly { - pointer-events: none; -} - -/* Media controls in order of appearance. */ - -/* Play/pause button. */ - -.media-button.play { - background-image: -webkit-image-set( - url(../images/media/media_play.png) 1x, - url(../images/media/2x/media_play.png) 2x); -} - -.media-button.play[state='playing'] { - background-image: -webkit-image-set( - url(../images/media/media_pause.png) 1x, - url(../images/media/2x/media_pause.png) 2x); -} - -/* Time controls: a slider and a text time display. */ - -.time-controls { - display: flex; - flex: auto; - height: 100%; -} - -/* Time display. */ - -.time-controls > .time { - cursor: default; - display: flex; - flex: none; - height: 100%; - margin: 0 8px; - position: relative; -} - -.time-controls > .time.disabled { - opacity: 0; -} - -/* Invisible div used to compute the width required for the elapsed time. */ -.time-controls > .time > .spacer { - color: transparent; -} - -.time-controls > .time > .current { - -webkit-box-align: center; - -webkit-box-orient: horizontal; - -webkit-box-pack: end; - color: rgb(51, 51, 51); - display: -webkit-box; - height: 100%; - position: absolute; - right: 0; -} - -/* Progress slider. */ - -.time-controls > .progress { - flex: auto; - height: 100%; - position: relative; -} - -/* Volume controls: sound button and volume slider */ - -.volume-controls { - display: flex; - flex: none; - height: 100%; - margin: 0 8px; -} - -/* Sound button */ - -.media-button.sound { - background-image: -webkit-image-set( - url(../images/media/media_volume.png) 1x, - url(../images/media/2x/media_volume.png) 2x); -} - -.media-button.sound[level='0'] { - background-image: -webkit-image-set( - url(../images/media/media_volume_mute.png) 1x, - url(../images/media/2x/media_volume_mute.png) 2x); -} - -/* Volume slider. */ - -cr-slider.volume { - height: 100%; - position: relative; - width: 110px; -} - -/* Horizontal video control bar, all controls in a row. */ - -.video-controls { - background: rgb(250, 250, 250); - display: flex; - font-size: 13px; - height: 32px; - padding: 8px; - pointer-events: auto; -} - -/* Cast button. */ - -.media-button.cast, -.media-button.cast-button { - background-image: -webkit-image-set( - url(../images/media/media_chromecast.png) 1x, - url(../images/media/2x/media_chromecast.png) 2x); - border-radius: 2px; - display: none; -} - -/* Reset browser's button style. */ -.media-button.cast { - background-color: transparent; - border: none; - cursor: pointer; - outline: none; -} - -#video-player[cast-available][castable] .media-button.cast, -#video-player[mr-cast-available][castable] .media-button.cast-button { - display: block; -} - -#video-player[casting] .media-button.cast, -#video-player[casting] .media-button.cast-button { - background-image: -webkit-image-set( - url(../images/media/media_chromecast_casting.png) 1x, - url(../images/media/2x/media_chromecast_casting.png) 2x); -} - -.media-button.cast:focus:not(.using-mouse) { - box-shadow: 0 0 0 1px rgba(66, 133, 244, 0.5); -} - -/* Fullscreen button. */ -/* There is no final decision whether we need a separate icon when toggled. */ - -.media-button.fullscreen { - background-image: -webkit-image-set( - url(../images/media/media_fullscreen.png) 1x, - url(../images/media/2x/media_fullscreen.png) 2x); -} - -#controls[fullscreen] .media-button.fullscreen { - background-image: -webkit-image-set( - url(../images/media/media_fullscreen_exit.png) 1x, - url(../images/media/2x/media_fullscreen_exit.png) 2x); -} - -.media-button.subtitles { - background-image: -webkit-image-set( - url(../images/media/media_subtitles.png) 1x, - url(../images/media/2x/media_subtitles.png) 2x); -} - -.media-button.subtitles:not([showing]) { - opacity: 0.2; -} - -.media-button.subtitles[unavailable] { - display: none; -} - -.playback-state-icon { - animation: none; - background-position: center center; - background-repeat: no-repeat; - display: none; - height: 32px; - left: 50%; - margin-left: -16px; - margin-top: -16px; - opacity: 0; - pointer-events: none; - position: absolute; - top: 50%; - width: 32px; - z-index: 2; -} - -.text-banner { - background-color: black; - border-radius: 10px; - color: white; - display: none; - font-size: 18px; - left: 50%; - margin-left: -250px; - opacity: 0; - padding: 10px; - pointer-events: none; - position: absolute; - text-align: center; - text-shadow: 0 0 10px black; - top: 20%; - width: 500px; - z-index: 2; -} - -.text-banner[visible] { - animation: text-banner-blowup 3000ms; - display: block; -} - -.playback-state-icon[state] { - display: block; -} - -@keyframes blowup { - from { - opacity: 1; - } - to { - opacity: 0; - transform: scale(3); - } -} - -@keyframes text-banner-blowup { - from { - opacity: 0; - transform: scale(0.5); - } - 20% { - opacity: 0.75; - transform: scale(1); - } - 80% { - opacity: 0.75; - transform: scale(1); - } - to { - opacity: 0; - transform: scale(3); - } -} - -.playback-state-icon[state='play'] { - animation: blowup 500ms; - background-image: -webkit-image-set( - url(../images/media/media_play_onscreen.png) 1x, - url(../images/media/2x/media_play_onscreen.png) 2x); -} - -.playback-state-icon[state='pause'] { - animation: blowup 500ms; - background-image: -webkit-image-set( - url(../images/media/media_pause_onscreen.png) 1x, - url(../images/media/2x/media_pause_onscreen.png) 2x); -}
diff --git a/ui/file_manager/video_player/css/video_player.css b/ui/file_manager/video_player/css/video_player.css index de18f48..185f453 100644 --- a/ui/file_manager/video_player/css/video_player.css +++ b/ui/file_manager/video_player/css/video_player.css
@@ -18,15 +18,6 @@ width: 100%; } -#thumbnail { - background-position: center; - background-repeat: no-repeat; - background-size: contain; - height: 100%; - position: absolute; - width: 100%; -} - #video-container { height: 100%; left: 0; @@ -39,31 +30,6 @@ display: none; } -#spinner-container { - display: none; - height: 100%; - left: 0; - position: absolute; - top: 0; - width: 100%; -} - -#video-player[loading] #spinner-container { - display: block; -} - -#spinner-container > .spinner { - background: url(chrome://resources/images/throbber_medium.svg) center/100% - no-repeat; - height: 32px; - left: 50%; - margin-left: -16px; - margin-top: -16px; - position: absolute; - top: 50%; - width: 32px; -} - video { height: 100%; left: 0; @@ -80,102 +46,6 @@ width: 100%; } -#video-player:not([casting]) > #cast-container { - display: none; -} - -#cast-container { - height: 100%; - left: 0; - position: absolute; - top: 0; - width: 100%; -} - -#cast-container > #cast-info { - background-image: -webkit-image-set( - url(../images/100/cast_big.png) 1x, - url(../images/200/cast_big.png) 2x); - background-position: 0 0; - background-repeat: no-repeat; - bottom: 70px; - height: 38px; - left: 40px; - opacity: 0.8; - padding: 5px 56px; - position: absolute; - z-index: 10; -} - -#cast-container > #cast-info > .first-line { - color: #fff; - font-size: 12px; - font-weight: bold; - line-height: 14px; - text-transform: uppercase; -} - -#cast-container > #cast-info > .second-line { - color: #fff; - font-size: 22px; - font-weight: bold; - line-height: 24px; -} - -#controls-wrapper { - bottom: 0; - display: flex; - left: 0; - position: absolute; - right: 0; -} - -#controls { - flex: auto; -} - -#video-player:not([tools]):not([casting]) .tool { - opacity: 0; -} - -#video-player:not([tools]):not([casting]) { - cursor: none; -} - .tool { transition: opacity 180ms linear; } - -#error-wrapper { - -webkit-box-align: center; - -webkit-box-orient: horizontal; - -webkit-box-pack: center; - display: -webkit-box; - height: 100%; - left: 0; - pointer-events: none; - position: absolute; - top: 0; - width: 100%; -} - -#error { - -webkit-box-align: center; - -webkit-box-orient: horizontal; - -webkit-box-pack: center; - background-color: rgba(24, 24, 24, 1); - background-image: -webkit-image-set( - url(../images/100/error.png) 1x, - url(../images/200/error.png) 2x); - background-position: 25px center; - background-repeat: no-repeat; - color: white; - display: -webkit-box; - height: 54px; - padding-left: 70px; - padding-right: 35px; -} - -#error:not([visible]) { - display: none; -}
diff --git a/ui/file_manager/video_player/images/100/cast_big.png b/ui/file_manager/video_player/images/100/cast_big.png deleted file mode 100644 index 8c16398..0000000 --- a/ui/file_manager/video_player/images/100/cast_big.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/video_player/images/100/error.png b/ui/file_manager/video_player/images/100/error.png deleted file mode 100644 index bfae452..0000000 --- a/ui/file_manager/video_player/images/100/error.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/video_player/images/200/cast_big.png b/ui/file_manager/video_player/images/200/cast_big.png deleted file mode 100644 index 6521d4a..0000000 --- a/ui/file_manager/video_player/images/200/cast_big.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/video_player/images/200/error.png b/ui/file_manager/video_player/images/200/error.png deleted file mode 100644 index 200baf5..0000000 --- a/ui/file_manager/video_player/images/200/error.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/video_player/images/media/2x/media_check.png b/ui/file_manager/video_player/images/media/2x/media_check.png deleted file mode 100644 index 284d93d..0000000 --- a/ui/file_manager/video_player/images/media/2x/media_check.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/video_player/images/media/2x/media_chromecast.png b/ui/file_manager/video_player/images/media/2x/media_chromecast.png deleted file mode 100644 index 6a1ff85..0000000 --- a/ui/file_manager/video_player/images/media/2x/media_chromecast.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/video_player/images/media/2x/media_chromecast_casting.png b/ui/file_manager/video_player/images/media/2x/media_chromecast_casting.png deleted file mode 100644 index d30ee6c4..0000000 --- a/ui/file_manager/video_player/images/media/2x/media_chromecast_casting.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/video_player/images/media/2x/media_fullscreen.png b/ui/file_manager/video_player/images/media/2x/media_fullscreen.png deleted file mode 100644 index e0ac7b5..0000000 --- a/ui/file_manager/video_player/images/media/2x/media_fullscreen.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/video_player/images/media/2x/media_fullscreen_exit.png b/ui/file_manager/video_player/images/media/2x/media_fullscreen_exit.png deleted file mode 100644 index c517513..0000000 --- a/ui/file_manager/video_player/images/media/2x/media_fullscreen_exit.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/video_player/images/media/2x/media_pause.png b/ui/file_manager/video_player/images/media/2x/media_pause.png deleted file mode 100644 index 5e71f9ac..0000000 --- a/ui/file_manager/video_player/images/media/2x/media_pause.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/video_player/images/media/2x/media_pause_onscreen.png b/ui/file_manager/video_player/images/media/2x/media_pause_onscreen.png deleted file mode 100644 index bd33792..0000000 --- a/ui/file_manager/video_player/images/media/2x/media_pause_onscreen.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/video_player/images/media/2x/media_play.png b/ui/file_manager/video_player/images/media/2x/media_play.png deleted file mode 100644 index b848dc9..0000000 --- a/ui/file_manager/video_player/images/media/2x/media_play.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/video_player/images/media/2x/media_play_onscreen.png b/ui/file_manager/video_player/images/media/2x/media_play_onscreen.png deleted file mode 100644 index 7faa7f5..0000000 --- a/ui/file_manager/video_player/images/media/2x/media_play_onscreen.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/video_player/images/media/2x/media_subtitles.png b/ui/file_manager/video_player/images/media/2x/media_subtitles.png deleted file mode 100644 index f5c80de0..0000000 --- a/ui/file_manager/video_player/images/media/2x/media_subtitles.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/video_player/images/media/2x/media_volume.png b/ui/file_manager/video_player/images/media/2x/media_volume.png deleted file mode 100644 index 5b837b5..0000000 --- a/ui/file_manager/video_player/images/media/2x/media_volume.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/video_player/images/media/2x/media_volume_mute.png b/ui/file_manager/video_player/images/media/2x/media_volume_mute.png deleted file mode 100644 index e0a5326a..0000000 --- a/ui/file_manager/video_player/images/media/2x/media_volume_mute.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/video_player/images/media/media_check.png b/ui/file_manager/video_player/images/media/media_check.png deleted file mode 100644 index ab43376..0000000 --- a/ui/file_manager/video_player/images/media/media_check.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/video_player/images/media/media_chromecast.png b/ui/file_manager/video_player/images/media/media_chromecast.png deleted file mode 100644 index 29590689..0000000 --- a/ui/file_manager/video_player/images/media/media_chromecast.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/video_player/images/media/media_chromecast_casting.png b/ui/file_manager/video_player/images/media/media_chromecast_casting.png deleted file mode 100644 index 4b3ebf1b..0000000 --- a/ui/file_manager/video_player/images/media/media_chromecast_casting.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/video_player/images/media/media_fullscreen.png b/ui/file_manager/video_player/images/media/media_fullscreen.png deleted file mode 100644 index 4156ee4..0000000 --- a/ui/file_manager/video_player/images/media/media_fullscreen.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/video_player/images/media/media_fullscreen_exit.png b/ui/file_manager/video_player/images/media/media_fullscreen_exit.png deleted file mode 100644 index 1acd504..0000000 --- a/ui/file_manager/video_player/images/media/media_fullscreen_exit.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/video_player/images/media/media_pause.png b/ui/file_manager/video_player/images/media/media_pause.png deleted file mode 100644 index c070a25..0000000 --- a/ui/file_manager/video_player/images/media/media_pause.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/video_player/images/media/media_pause_onscreen.png b/ui/file_manager/video_player/images/media/media_pause_onscreen.png deleted file mode 100644 index ce1ad173..0000000 --- a/ui/file_manager/video_player/images/media/media_pause_onscreen.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/video_player/images/media/media_play.png b/ui/file_manager/video_player/images/media/media_play.png deleted file mode 100644 index 6f05107..0000000 --- a/ui/file_manager/video_player/images/media/media_play.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/video_player/images/media/media_play_onscreen.png b/ui/file_manager/video_player/images/media/media_play_onscreen.png deleted file mode 100644 index f5a92d2..0000000 --- a/ui/file_manager/video_player/images/media/media_play_onscreen.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/video_player/images/media/media_subtitles.png b/ui/file_manager/video_player/images/media/media_subtitles.png deleted file mode 100644 index 46ddbccd..0000000 --- a/ui/file_manager/video_player/images/media/media_subtitles.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/video_player/images/media/media_volume.png b/ui/file_manager/video_player/images/media/media_volume.png deleted file mode 100644 index ce60e626..0000000 --- a/ui/file_manager/video_player/images/media/media_volume.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/video_player/images/media/media_volume_mute.png b/ui/file_manager/video_player/images/media/media_volume_mute.png deleted file mode 100644 index c9fd787..0000000 --- a/ui/file_manager/video_player/images/media/media_volume_mute.png +++ /dev/null Binary files differ
diff --git a/ui/file_manager/video_player/js/BUILD.gn b/ui/file_manager/video_player/js/BUILD.gn index bf91eecd..2e6c746 100644 --- a/ui/file_manager/video_player/js/BUILD.gn +++ b/ui/file_manager/video_player/js/BUILD.gn
@@ -11,8 +11,6 @@ ":background", ":closure_compile_externs", ":error_util", - ":media_controls", - ":mouse_inactivity_watcher", ":video_player", ":video_player_metrics", ":video_player_native_controls", @@ -25,7 +23,6 @@ "$externs_path/chrome_extensions.js", "$externs_path/media_player_private.js", "$externs_path/metrics_private.js", - "$externs_path/mediasession.js", "$externs_path/picture_in_picture.js", "//ui/file_manager/externs/chrome_cast.js", "//ui/file_manager/externs/platform.js", @@ -43,17 +40,6 @@ js_library("error_util") { } -js_library("media_controls") { - deps = [ - "//ui/file_manager/file_manager/common/js:util", - "//ui/webui/resources/cr_elements/cr_slider:cr_slider", - "//ui/webui/resources/js/cr/ui:menu_button", - ] -} - -js_library("mouse_inactivity_watcher") { -} - js_library("video_player_native_controls") { deps = [ "//ui/file_manager/base/js:app_util", @@ -76,14 +62,9 @@ js_library("video_player") { deps = [ ":error_util", - ":media_controls", - ":mouse_inactivity_watcher", ":video_player_metrics", ":video_player_native_controls", - "cast:cast_video_element", - "cast:media_manager", "//ui/file_manager/base/js:filtered_volume_manager", - "//ui/file_manager/base/js:mediasession_types", "//ui/file_manager/file_manager/common/js:metrics_base", "//ui/file_manager/file_manager/common/js:util", "//ui/file_manager/image_loader:image_loader_client",
diff --git a/ui/file_manager/video_player/js/cast/BUILD.gn b/ui/file_manager/video_player/js/cast/BUILD.gn deleted file mode 100644 index 27243607..0000000 --- a/ui/file_manager/video_player/js/cast/BUILD.gn +++ /dev/null
@@ -1,50 +0,0 @@ -# Copyright 2018 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -import("//third_party/closure_compiler/compile_js.gni") - -js_type_check("closure_compile") { - deps = [ - ":cast_extension_discoverer", - ":cast_video_element", - ":caster", - ":closure_compile_externs", - ":media_manager", - ] -} - -js_library("closure_compile_externs") { - sources = [] - externs_list = [ - "$externs_path/chrome_extensions.js", - "$externs_path/media_player_private.js", - "$externs_path/mediasession.js", - "//ui/file_manager/externs/background/volume_manager_factory.js", - "//ui/file_manager/externs/chrome_cast.js", - "//ui/file_manager/externs/platform.js", - ] -} - -js_library("cast_extension_discoverer") { - deps = [ "//ui/file_manager/video_player/js:error_util" ] -} - -js_library("cast_video_element") { - deps = [ - ":media_manager", - "//ui/file_manager/video_player/js:error_util", - "//ui/file_manager/video_player/js:video_player_metrics", - "//ui/webui/resources/js/cr:event_target", - ] -} - -js_library("caster") { - deps = [ - ":cast_extension_discoverer", - "//ui/file_manager/video_player/js:video_player", - ] -} - -js_library("media_manager") { -}
diff --git a/ui/file_manager/video_player/js/cast/cast_extension_discoverer.js b/ui/file_manager/video_player/js/cast/cast_extension_discoverer.js deleted file mode 100644 index 064732e..0000000 --- a/ui/file_manager/video_player/js/cast/cast_extension_discoverer.js +++ /dev/null
@@ -1,81 +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. - -// TODO(crbug.com/689773): Update to use <script> - -/** - * Discover the ID of installed cast extension. - * @constructor - * @struct - */ -function CastExtensionDiscoverer() {} - -/** - * Tentative IDs to try. - * @type {!Array<string>} - * @const - */ -CastExtensionDiscoverer.CAST_EXTENSION_IDS = [ - 'enhhojjnijigcajfphajepfemndkmdlo', // Media Router Dev - 'pkedcjkdefgpdelpbcmbmeomcjbeemfm' // Media Router Stable -]; - -/** - * @param {function(?string)} callback Callback called with the extension ID. - * The ID may be null if extension is not found. - */ -CastExtensionDiscoverer.findInstalledExtension = function(callback) { - CastExtensionDiscoverer.findInstalledExtensionHelper_(0, callback); -}; - -/** - * @param {number} index Current index which is tried to check. - * @param {function(?string)} callback Callback function which will be called - * the extension is found. - * @private - */ -CastExtensionDiscoverer.findInstalledExtensionHelper_ = function(index, - callback) { - if (index === CastExtensionDiscoverer.CAST_EXTENSION_IDS.length) { - // no extension found. - callback(null); - return; - } - - CastExtensionDiscoverer.isExtensionInstalled_( - CastExtensionDiscoverer.CAST_EXTENSION_IDS[index], - function(installed) { - if (installed) { - callback(CastExtensionDiscoverer.CAST_EXTENSION_IDS[index]); - } else { - CastExtensionDiscoverer.findInstalledExtensionHelper_(index + 1, - callback); - } - }); -}; - -/** - * The result will be notified on |callback|. True if installed, false not. - * @param {string} extensionId Id to be checked. - * @param {function(boolean)} callback Callback to notify the result. - * @private - */ -CastExtensionDiscoverer.isExtensionInstalled_ = - function(extensionId, callback) { - - var xhr = new XMLHttpRequest(); - var url = 'chrome-extension://' + extensionId + '/cast_sender.js'; - xhr.open('GET', url, true); - xhr.onerror = function() { - callback(false); - }; - /** @param {*} event */ - xhr.onreadystatechange = function(event) { - if (xhr.readyState == 4 && xhr.status === 200) { - // Cast extension found. - callback(true); - } - }.wrap(this); - xhr.send(); -};
diff --git a/ui/file_manager/video_player/js/cast/cast_video_element.js b/ui/file_manager/video_player/js/cast/cast_video_element.js deleted file mode 100644 index 56c06f5..0000000 --- a/ui/file_manager/video_player/js/cast/cast_video_element.js +++ /dev/null
@@ -1,549 +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. - -/** - * Interval for updating media info (in ms). - * @type {number} - * @const - */ -var MEDIA_UPDATE_INTERVAL = 250; - -/** - * The namespace for communication between the cast and the player. - * @type {string} - * @const - */ -var CAST_MESSAGE_NAMESPACE = 'urn:x-cast:com.google.chromeos.videoplayer'; - -/** - * This class is the dummy class which has same interface as VideoElement. This - * behaves like VideoElement, and is used for making Chromecast player - * controlled instead of the true Video Element tag. - */ -class CastVideoElement extends cr.EventTarget { - /** - * @param {MediaManager} media Media manager with the media to play. - * @param {chrome.cast.Session} session Session to play a video on. - */ - constructor(media, session) { - super(); - - this.mediaManager_ = media; - this.mediaInfo_ = null; - - this.castMedia_ = null; - this.castSession_ = session; - this.currentTime_ = null; - this.src_ = ''; - this.volume_ = 100; - this.loop_ = false; - this.currentMediaPlayerState_ = null; - this.currentMediaCurrentTime_ = null; - this.currentMediaDuration_ = null; - this.playInProgress_ = false; - this.pauseInProgress_ = false; - this.errorCode_ = 0; - - /** - * @type {number} - * @private - */ - this.updateTimerId_ = 0; - - /** - * @type {?string} - * @private - */ - this.token_ = null; - - this.onMessageBound_ = this.onMessage_.bind(this); - this.onCastMediaUpdatedBound_ = this.onCastMediaUpdated_.bind(this); - this.castSession_.addMessageListener( - CAST_MESSAGE_NAMESPACE, this.onMessageBound_); - } - - /** - * Prepares for unloading this objects. - */ - dispose() { - this.unloadMedia_(); - this.castSession_.removeMessageListener( - CAST_MESSAGE_NAMESPACE, this.onMessageBound_); - } - - /** - * Returns a parent node. This must always be null. - * @type {Element} - */ - get parentNode() { - return null; - } - - /** - * The total time of the video (in sec). - * @type {?number} - */ - get duration() { - return this.currentMediaDuration_; - } - - /** - * The current timestamp of the video (in sec). - * @type {?number} - */ - get currentTime() { - if (this.castMedia_) { - if (this.castMedia_.idleReason === - chrome.cast.media.IdleReason.FINISHED) { - // Returns the duration. - return this.currentMediaDuration_; - } else { - return this.castMedia_.getEstimatedTime(); - } - } else { - return null; - } - } - - set currentTime(currentTime) { - var seekRequest = new chrome.cast.media.SeekRequest(); - seekRequest.currentTime = currentTime; - this.castMedia_.seek(seekRequest, - function() {}, - this.onCastCommandError_.wrap(this)); - } - - /** - * If this video is pauses or not. - * @type {boolean} - */ - get paused() { - if (!this.castMedia_) { - return false; - } - - return !this.playInProgress_ && - (this.pauseInProgress_ || - this.castMedia_.playerState === chrome.cast.media.PlayerState.PAUSED); - } - - /** - * If this video is ended or not. - * @type {boolean} - */ - get ended() { - if (!this.castMedia_) { - return true; - } - - return !this.playInProgress_ && - this.castMedia_.idleReason === chrome.cast.media.IdleReason.FINISHED; - } - - /** - * TimeRange object that represents the seekable ranges of the media - * resource. - * @type {TimeRanges} - */ - get seekable() { - return { - length: 1, - start: function(index) { - return 0; - }, - end: function(index) { - return this.currentMediaDuration_; - }, - }; - } - - /** - * Value of the volume - * @type {number} - */ - get volume() { - return this.castSession_.receiver.volume.muted ? - 0 : - this.castSession_.receiver.volume.level; - } - - set volume(volume) { - var VOLUME_EPS = 0.01; // Threshold for ignoring a small change. - - - if (this.castSession_.receiver.volume.muted) { - if (volume < VOLUME_EPS) { - return; - } - - // Unmute before setting volume. - this.castSession_.setReceiverMuted(false, - function() {}, - this.onCastCommandError_.wrap(this)); - - this.castSession_.setReceiverVolumeLevel(volume, - function() {}, - this.onCastCommandError_.wrap(this)); - } else { - // Ignores < 1% change. - var diff = this.castSession_.receiver.volume.level - volume; - if (Math.abs(diff) < VOLUME_EPS) { - return; - } - - if (volume < VOLUME_EPS) { - this.castSession_.setReceiverMuted(true, - function() {}, - this.onCastCommandError_.wrap(this)); - return; - } - - this.castSession_.setReceiverVolumeLevel(volume, - function() {}, - this.onCastCommandError_.wrap(this)); - } - } - - /** - * Returns the source of the current video. - * @type {?string} - */ - get src() { - return null; - } - - set src(value) { - // Do nothing. - } - - /** - * Returns the flag if the video loops at end or not. - * @type {boolean} - */ - get loop() { - return this.loop_; - } - - set loop(value) { - this.loop_ = !!value; - } - - /** - * Returns the error object if available. - * @type {?Object} - */ - get error() { - if (this.errorCode_ === 0) { - return null; - } - - return {code: this.errorCode_}; - } - - /** - * Plays the video. - * @param {boolean=} opt_seeking True when seeking. False otherwise. - */ - play(opt_seeking) { - if (this.playInProgress_) { - return; - } - - var play = function() { - // If the casted media is already playing and a pause request is not in - // progress, we can skip this play request. - if (this.castMedia_.playerState === - chrome.cast.media.PlayerState.PLAYING && - !this.pauseInProgress_) { - this.playInProgress_ = false; - return; - } - - var playRequest = new chrome.cast.media.PlayRequest(); - playRequest.customData = {seeking: !!opt_seeking}; - - this.castMedia_.play( - playRequest, - function() { - this.playInProgress_ = false; - }.wrap(this), - function(error) { - this.playInProgress_ = false; - this.onCastCommandError_(error); - }.wrap(this)); - }.wrap(this); - - this.playInProgress_ = true; - - if (!this.castMedia_) { - this.load(play); - } else { - play(); - } - } - - /** - * Pauses the video. - * @param {boolean=} opt_seeking True when seeking. False otherwise. - */ - pause(opt_seeking) { - if (!this.castMedia_) { - return; - } - - if (this.pauseInProgress_ || - this.castMedia_.playerState === chrome.cast.media.PlayerState.PAUSED) { - return; - } - - var pauseRequest = new chrome.cast.media.PauseRequest(); - pauseRequest.customData = {seeking: !!opt_seeking}; - - this.pauseInProgress_ = true; - this.castMedia_.pause( - pauseRequest, - function() { - this.pauseInProgress_ = false; - }.wrap(this), - function(error) { - this.pauseInProgress_ = false; - this.onCastCommandError_(error); - }.wrap(this)); - } - - /** - * Loads the video. - */ - load(opt_callback) { - var sendTokenPromise = this.mediaManager_.getToken(false).then( - function(token) { - this.token_ = token; - this.sendMessage_({message: 'push-token', token: token}); - }.bind(this)); - - // Resets the error code. - this.errorCode_ = 0; - - Promise.all([ - sendTokenPromise, - this.mediaManager_.getUrl(), - this.mediaManager_.getMime(), - this.mediaManager_.getThumbnail()]). - then(function(results) { - var url = results[1]; - var mime = results[2]; // maybe empty - var thumbnailUrl = results[3]; // maybe empty - - this.mediaInfo_ = new chrome.cast.media.MediaInfo(url, mime); - this.mediaInfo_.customData = { - tokenRequired: true, - thumbnailUrl: thumbnailUrl, - }; - - var request = new chrome.cast.media.LoadRequest(this.mediaInfo_); - return new Promise( - this.castSession_.loadMedia.bind(this.castSession_, request)). - then(function(media) { - this.onMediaDiscovered_(media); - if (opt_callback) { - opt_callback(); - } - }.bind(this)); - }.bind(this)).catch(function(error) { - this.unloadMedia_(); - this.dispatchEvent(new Event('error')); - console.error('Cast failed.', error.stack || error); - }.bind(this)); - } - - /** - * Unloads the video. - * @private - */ - unloadMedia_() { - if (this.castMedia_) { - this.castMedia_.stop(null, - function() {}, - function(error) { - // Ignores session error, since session may already be closed. - if (error.code !== chrome.cast.ErrorCode.SESSION_ERROR && - error.code !== chrome.cast.ErrorCode.INVALID_PARAMETER) { - this.onCastCommandError_(error); - } - }.wrap(this)); - - this.castMedia_.removeUpdateListener(this.onCastMediaUpdatedBound_); - this.castMedia_ = null; - } - - clearInterval(this.updateTimerId_); - } - - /** - * Sends the message to cast. - * @param {(!Object|string)} message Message to be sent (Must be JSON-able - * object). - * @private - */ - sendMessage_(message) { - this.castSession_.sendMessage(CAST_MESSAGE_NAMESPACE, message, - function() {}, function(error) {}); - } - - /** - * Invoked when receiving a message from the cast. - * @param {string} namespace Namespace of the message. - * @param {string} messageAsJson Content of message as json format. - * @private - */ - onMessage_(namespace, messageAsJson) { - if (namespace !== CAST_MESSAGE_NAMESPACE || !messageAsJson) { - return; - } - - var message = JSON.parse(messageAsJson); - if (message['message'] === 'request-token') { - if (message['previousToken'] === this.token_) { - this.mediaManager_.getToken(true).then(function(token) { - this.token_ = token; - this.sendMessage_({message: 'push-token', token: token}); - // TODO(yoshiki): Revokes the previous token. - }.bind(this)).catch(function(error) { - // Send an empty token as an error. - this.sendMessage_({message: 'push-token', token: ''}); - // TODO(yoshiki): Revokes the previous token. - console.error(error.stack || error); - }); - } else { - console.error( - 'New token is requested, but the previous token mismatches.'); - } - } else if (message['message'] === 'playback-error') { - if (message['detail'] === 'src-not-supported') { - this.errorCode_ = MediaError.MEDIA_ERR_SRC_NOT_SUPPORTED; - } - } - } - - /** - * This method is called periodically to update media information while the - * media is loaded. - * @private - */ - onPeriodicalUpdateTimer_() { - if (!this.castMedia_) { - return; - } - - if (this.castMedia_.playerState === chrome.cast.media.PlayerState.PLAYING) { - this.onCastMediaUpdated_(true); - } - } - - /** - * This method should be called when a media file is loaded. - * @param {chrome.cast.media.Media} media Media object which was discovered. - * @private - */ - onMediaDiscovered_(media) { - if (this.castMedia_ !== null) { - this.unloadMedia_(); - console.info('New media is found and the old media is overridden.'); - } - - this.castMedia_ = media; - this.onCastMediaUpdated_(true); - // Notify that the metadata of the video is ready. - this.dispatchEvent(new Event('loadedmetadata')); - - media.addUpdateListener(this.onCastMediaUpdatedBound_); - this.updateTimerId_ = setInterval(this.onPeriodicalUpdateTimer_.bind(this), - MEDIA_UPDATE_INTERVAL); - } - - /** - * This method should be called when a media command to cast is failed. - * @param {Object} error Object representing the error. - * @private - */ - onCastCommandError_(error) { - this.unloadMedia_(); - this.dispatchEvent(new Event('error')); - console.error('Error on sending command to cast.', error.stack || error); - } - - /** - * This is called when any media data is updated and by the periodical timer - * is fired. - * - * @param {boolean} alive Media availability. False if it's unavailable. - * @private - */ - onCastMediaUpdated_(alive) { - if (!this.castMedia_) { - return; - } - - var media = this.castMedia_; - if (this.loop_ && - media.idleReason === chrome.cast.media.IdleReason.FINISHED && - !alive) { - // Resets the previous media silently. - this.castMedia_ = null; - - // Replay the current media. - this.currentMediaPlayerState_ = chrome.cast.media.PlayerState.BUFFERING; - this.currentMediaCurrentTime_ = 0; - this.dispatchEvent(new Event('play')); - this.dispatchEvent(new Event('timeupdate')); - this.play(); - return; - } - - if (this.currentMediaPlayerState_ !== media.playerState) { - var oldPlayState = false; - var oldState = this.currentMediaPlayerState_; - if (oldState === chrome.cast.media.PlayerState.BUFFERING || - oldState === chrome.cast.media.PlayerState.PLAYING) { - oldPlayState = true; - } - var newPlayState = false; - var newState = media.playerState; - if (newState === chrome.cast.media.PlayerState.BUFFERING || - newState === chrome.cast.media.PlayerState.PLAYING) { - newPlayState = true; - } - if (!oldPlayState && newPlayState) { - this.dispatchEvent(new Event('play')); - } - if (oldPlayState && !newPlayState) { - this.dispatchEvent(new Event('pause')); - } - - this.currentMediaPlayerState_ = newState; - } - if (this.currentMediaCurrentTime_ !== media.getEstimatedTime()) { - this.currentMediaCurrentTime_ = media.getEstimatedTime(); - this.dispatchEvent(new Event('timeupdate')); - } - - if (this.currentMediaDuration_ !== media.media.duration) { - // Since recordMediumCount which is called inside recordCastedVideoLangth - // can take a value ranges from 1 to 10,000, we don't allow to pass 0 - // here. i.e. length 0 is not recorded. - if (this.currentMediaDuration_) { - metrics.recordCastedVideoLength(this.currentMediaDuration_); - } - - this.currentMediaDuration_ = media.media.duration; - this.dispatchEvent(new Event('durationchange')); - } - - // Media is being unloaded. - if (!alive) { - this.unloadMedia_(); - return; - } - } -}
diff --git a/ui/file_manager/video_player/js/cast/caster.js b/ui/file_manager/video_player/js/cast/caster.js deleted file mode 100644 index 7edc29a..0000000 --- a/ui/file_manager/video_player/js/cast/caster.js +++ /dev/null
@@ -1,160 +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. - -// This hack prevents a bug on the cast extension. -// TODO(yoshiki): Remove this once the cast extension supports Chrome apps. -// Although localStorage in Chrome app is not supported, but it's used in the -// cast extension. This line prevents an exception on using localStorage. -Object.defineProperty(window, 'localStorage', { - get: function() { - return {}; - } -}); - -/** - * @type {string} - * @const - */ -var APPLICATION_ID = '4CCB98DA'; - -if (document.readyState === 'loading') { - document.addEventListener('DOMContentLoaded', initialize); -} else { - initialize(); -} - -/** - * Starts initialization of cast-related feature. - */ -function initialize() { - if (window.loadMockCastExtensionForTest) { - // If the test flag is set, the mock extension for test will be laoded by - // the test script. Sets the handler to wait for loading. - onLoadCastSDK(initializeApi); - return; - } - - CastExtensionDiscoverer.findInstalledExtension(function(foundId) { - if (foundId) { - loadCastSDK(foundId, initializeApi); - } else { - console.info('No Google Cast extension is installed.'); - } - }.wrap()); -} - -/** - * Loads the Google Cast Sender SDK from the given cast extension. - * The given callback is executes after the cast SDK is loaded. - * - * @param {string} extensionId ID of the extension to be loaded. - * @param {function()} callback Callback (executed asynchronously). - */ -function loadCastSDK(extensionId, callback) { - var script = document.createElement('script'); - - var onError = function() { - script.removeEventListener('error', onError); - document.body.removeChild(script); - console.error('Google Cast extension load failed.'); - }.wrap(); - - // Load the Cast Sender SDK provided by the given Cast extension. - // Legacy Cast extension relies on the extension ID being set by bootstrap - // code, so set the ID here. - window.chrome['cast'] = window.chrome['cast'] || {}; - window.chrome['cast']['extensionId'] = extensionId; - script.src = 'chrome-extension://' + extensionId + '/cast_sender.js'; - script.addEventListener('error', onError); - script.addEventListener('load', onLoadCastSDK.bind(null, callback)); - document.body.appendChild(script); -} - -/** - * Handles load event of Cast SDK and make sure the Cast API is available. - * @param {function()} callback Callback which is called when the Caset Sender - * API is ready for use. - */ -function onLoadCastSDK(callback) { - var executeCallback = function() { - setTimeout(callback, 0); // Runs asynchronously. - }; - - if(!chrome.cast || !chrome.cast.isAvailable) { - var checkTimer = setTimeout(function() { - console.error('Either "Google Cast API" or "Google Cast" extension ' + - 'seems not to be installed?'); - }.wrap(), 5000); - - window['__onGCastApiAvailable'] = function(loaded, errorInfo) { - clearTimeout(checkTimer); - - if (loaded) { - executeCallback(); - } else { - console.error('Google Cast extension load failed.', errorInfo); - } - }.wrap(); - } else { - // Just executes the callback since the API is already loaded. - executeCallback(); - } -} - -/** - * Initialize Cast API. - */ -function initializeApi() { - var onSession = function() { - // TODO(yoshiki): Implement this. - }; - - var onInitSuccess = function() { - // TODO(yoshiki): Implement this. - }; - - /** - * @param {chrome.cast.Error} error - */ - var onError = function(error) { - console.error('Error on Cast initialization.', error); - }; - - var sessionRequest = new chrome.cast.SessionRequest(APPLICATION_ID); - var apiConfig = new chrome.cast.ApiConfig(sessionRequest, - onSession, - onReceiver); - chrome.cast.initialize(apiConfig, onInitSuccess, onError); -} - -/** - * Called when receiver availability is changed. This method is also called when - * initialization is completed. - * - * @param {chrome.cast.ReceiverAvailability} availability Availability of casts. - * @param {Array<Object>} receivers List of casts. - */ -function onReceiver(availability, receivers) { - if (chrome.cast.usingPresentationApi) { - player.setCastAvailability( - availability === chrome.cast.ReceiverAvailability.AVAILABLE); - return; - } - - if (availability === chrome.cast.ReceiverAvailability.AVAILABLE) { - if (!receivers) { - console.error('Receiver list is empty.'); - receivers = []; - } - - metrics.recordNumberOfCastDevices(receivers.length); - player.setCastList(receivers); - } else if (availability == chrome.cast.ReceiverAvailability.UNAVAILABLE) { - metrics.recordNumberOfCastDevices(0); - player.setCastList([]); - } else { - console.error('Unexpected response in onReceiver.', arguments); - player.setCastList([]); - } -}
diff --git a/ui/file_manager/video_player/js/cast/media_manager.js b/ui/file_manager/video_player/js/cast/media_manager.js deleted file mode 100644 index 2852f42..0000000 --- a/ui/file_manager/video_player/js/cast/media_manager.js +++ /dev/null
@@ -1,157 +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. - -/** - * Media manager class. - * This class supports the information for the media file. - * @param {!FileEntry} entry Entry of media file. This must be a external entry. - * @constructor - */ -function MediaManager(entry) { - this.entry_ = entry; - - this.cachedDriveProp_ = null; - this.cachedUrl_ = null; - this.cachedToken_ = null; - - Object.seal(this); -} - -MediaManager.prototype = {}; - -/** - * Checks if the file is available for cast or not. - * - * @return {Promise} Promise which is resolved with boolean. If true, the file - * is available for cast. False, otherwise. - */ -MediaManager.prototype.isAvailableForCast = function() { - return this.getUrl().then(function(url) { - return true; - }, function() { - return false; - }); -}; - -/** - * Retrieves the token for cast. - * - * @param {boolean} refresh If true, force to refresh a token. If false, use the - * cached token if available. - * @return {Promise} Promise which is resolved with the token. Reject if failed. - */ -MediaManager.prototype.getToken = function(refresh) { - if (chrome.test) { - return Promise.resolve('DUMMY_ACCESS_TOKEN'); - } - - if (this.cachedToken_ && !refresh) { - return Promise.resolve(this.cachedToken_); - } - - return new Promise(function(fulfill, reject) { - // TODO(yoshiki): Creates the method to get a token and use it. - chrome.fileManagerPrivate.getDownloadUrl(this.entry_, fulfill); - }.bind(this)).then(function(url) { - if (chrome.runtime.lastError) { - return Promise.reject( - 'Token fetch failed: ' + chrome.runtime.lastError.message); - } - if (!url) { - return Promise.reject('Token fetch failed.'); - } - var index = url.indexOf('access_token='); - var token = url.substring(index + 13); - if (index > 0 && token) { - this.cachedToken_ = token; - return token; - } else { - return Promise.reject('Token fetch failed.'); - } - }.bind(this)); -}; - -/** - * Retrieves the url for cast. - * - * @return {Promise} Promise which is resolved with the url. Reject if failed. - */ -MediaManager.prototype.getUrl = function() { - if (chrome.test) { - return Promise.resolve('http://example.com/dummy_url.mp4'); - } - - if (this.cachedUrl_) { - return Promise.resolve(this.cachedUrl_); - } - - return new Promise(function(fulfill, reject) { - // TODO(yoshiki): Creates the method to get a url and use it. - chrome.fileManagerPrivate.getDownloadUrl(this.entry_, fulfill); - }.bind(this)).then(function(url) { - if (chrome.runtime.lastError) { - return Promise.reject( - 'URL fetch failed: ' + chrome.runtime.lastError.message); - } - if (!url) { - return Promise.reject('URL fetch failed.'); - } - var accessTokenIndex = url.indexOf('access_token='); - if (accessTokenIndex) { - url = url.substring(0, accessTokenIndex - 1); - } - this.cachedUrl_ = url; - return url; - }.bind(this)); -}; - -/** - * Retrieves the mime of file. - * - * @return {Promise} Promise which is resolved with the mime. Reject if failed. - */ -MediaManager.prototype.getMime = function() { - if (this.cachedDriveProp_) { - return Promise.resolve(this.cachedDriveProp_.contentMimeType || ''); - } - - return new Promise(function(fulfill, reject) { - chrome.fileManagerPrivate.getEntryProperties( - [this.entry_], ['contentMimeType', 'thumbnailUrl'], fulfill); - }.bind(this)).then(function(props) { - if (!props || !props[0]) { - return Promise.reject('Mime fetch failed.'); - } else if (!props[0].contentMimeType) { - // TODO(yoshiki): Adds a logic to guess the mime. - this.cachedDriveProp_ = props[0]; - return ''; - } else { - this.cachedDriveProp_ = props[0]; - return props[0].contentMimeType; - } - }.bind(this)); -}; - -/** - * Retrieves the thumbnail url of file. - * - * @return {Promise} Promise which is resolved with the url. Reject if failed. - */ -MediaManager.prototype.getThumbnail = function() { - if (this.cachedDriveProp_) { - return Promise.resolve(this.cachedDriveProp_.thumbnailUrl || ''); - } - - return new Promise(function(fulfill, reject) { - chrome.fileManagerPrivate.getEntryProperties( - [this.entry_], ['contentMimeType', 'thumbnailUrl'], fulfill); - }.bind(this)).then(function(props) { - if (!props || !props[0]) { - return Promise.reject('Thumbnail fetch failed.'); - } else { - this.cachedDriveProp_ = props[0]; - return props[0].thumbnailUrl || ''; - } - }.bind(this)); -};
diff --git a/ui/file_manager/video_player/js/media_controls.js b/ui/file_manager/video_player/js/media_controls.js deleted file mode 100644 index 9735cb3ce..0000000 --- a/ui/file_manager/video_player/js/media_controls.js +++ /dev/null
@@ -1,1219 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -/** - * @fileoverview MediaControls class implements media playback controls - * that exist outside of the audio/video HTML element. - */ - -/** - * Model of a volume slider and a mute switch and its user interaction. - * @constructor - * @struct - */ -function VolumeModel() { - /** - * @type {boolean} - */ - this.isMuted_ = false; - - /** - * The volume level in [0..1]. - * @type {number} - */ - this.volume_ = 0.5; -} - -/** - * After unmuting, the volume should be non-zero value to avoid that the mute - * button gives no response to user. - */ -VolumeModel.MIN_VOLUME_AFTER_UNMUTE = 0.01; - -/** - * @return {number} the value to be set as the volume level of a media element. - */ -VolumeModel.prototype.getMediaVolume = function() { - return this.isMuted_ ? 0 : this.volume_; -}; - -/** - * Handles operation to the volume level slider. - * @param {number} value new position of the slider in [0..1]. - */ -VolumeModel.prototype.onVolumeChanged = function(value) { - if (value == 0) { - this.isMuted_ = true; - } else { - this.isMuted_ = false; - this.volume_ = value; - } -}; - -/** - * Toggles the mute state. - */ -VolumeModel.prototype.toggleMute = function() { - this.isMuted_ = !this.isMuted_; - if (!this.isMuted_) { - this.volume_ = Math.max(VolumeModel.MIN_VOLUME_AFTER_UNMUTE, this.volume_); - } -}; - -/** - * Sets the status of the model. - * @param {number} volume the volume level in [0..1]. - * @param {boolean} mute whether to mute the sound. - */ -VolumeModel.prototype.set = function(volume, mute) { - this.volume_ = volume; - this.isMuted_ = mute; -}; - -/** - * @param {!HTMLElement} containerElement The container for the controls. - * @param {function(Event)} onMediaError Function to display an error message. - * @constructor - * @struct - */ -function MediaControls(containerElement, onMediaError) { - this.container_ = containerElement; - this.document_ = this.container_.ownerDocument; - this.media_ = null; - - this.onMediaPlayBound_ = this.onMediaPlay_.bind(this, true); - this.onMediaPauseBound_ = this.onMediaPlay_.bind(this, false); - this.onMediaDurationBound_ = this.onMediaDuration_.bind(this); - this.onMediaProgressBound_ = this.onMediaProgress_.bind(this); - this.onMediaError_ = onMediaError || function() {}; - - /** - * @type {VolumeModel} - * @private - */ - this.volumeModel_ = new VolumeModel(); - - /** - * @type {HTMLElement} - * @private - */ - this.playButton_ = null; - - /** - * @type {CrSliderElement} - * @private - */ - this.progressSlider_ = null; - - /** - * @type {CrSliderElement} - * @private - */ - this.volume_ = null; - - /** - * @type {HTMLElement} - * @private - */ - this.textBanner_ = null; - - /** - * @type {HTMLElement} - * @private - */ - this.soundButton_ = null; - - /** - * @type {HTMLElement} - * @private - */ - this.subtitlesButton_ = null; - - /** - * @private {TextTrack} - */ - this.subtitlesTrack_ = null; - - /** - * @type {boolean} - * @private - */ - this.resumeAfterDrag_ = false; - - /** - * @type {HTMLElement} - * @private - */ - this.currentTime_ = null; - - /** - * @type {HTMLElement} - * @private - */ - this.currentTimeSpacer_ = null; - - /** - * @private {boolean} - */ - this.seeking_ = false; - - /** - * @private {boolean} - */ - this.showRemainingTime_ = false; -} - -/** - * Button's state types. Values are used as CSS class names. - * @enum {string} - */ -MediaControls.ButtonStateType = { - DEFAULT: 'default', - PLAYING: 'playing', - ENDED: 'ended' -}; - -/** - * @return {HTMLAudioElement|HTMLVideoElement} The media element. - */ -MediaControls.prototype.getMedia = function() { - return this.media_; -}; - -/** - * Format the time in hh:mm:ss format (omitting redundant leading zeros) - * adding '-' sign if given value is negative. - * @param {number} timeInSec Time in seconds. - * @return {string} Formatted time string. - * @private - */ -MediaControls.formatTime_ = function(timeInSec) { - var result = ''; - if (timeInSec < 0) { - timeInSec *= -1; - result += '-'; - } - var seconds = Math.floor(timeInSec % 60); - var minutes = Math.floor((timeInSec / 60) % 60); - var hours = Math.floor(timeInSec / 60 / 60); - if (hours) result += hours + ':'; - if (hours && (minutes < 10)) result += '0'; - result += minutes + ':'; - if (seconds < 10) result += '0'; - result += seconds; - return result; -}; - -/** - * Create a custom control. - * - * @param {string} className Class name. - * @param {HTMLElement=} opt_parent Parent element or container if undefined. - * @param {string=} opt_tagName Tag name of the control. 'div' if undefined. - * @return {!HTMLElement} The new control element. - */ -MediaControls.prototype.createControl = - function(className, opt_parent, opt_tagName) { - var parent = opt_parent || this.container_; - var control = /** @type {!HTMLElement} */ - (this.document_.createElement(opt_tagName || 'div')); - control.className = className; - parent.appendChild(control); - return control; -}; - -/** - * Create a custom button. - * - * @param {string} className Class name. - * @param {function(Event)=} opt_handler Click handler. - * @param {HTMLElement=} opt_parent Parent element or container if undefined. - * @param {number=} opt_numStates Number of states, default: 1. - * @return {!HTMLElement} The new button element. - */ -MediaControls.prototype.createButton = function( - className, opt_handler, opt_parent, opt_numStates) { - opt_numStates = opt_numStates || 1; - - var button = this.createControl(className, opt_parent, 'files-icon-button'); - button.classList.add('media-button'); - - button.setAttribute('state', MediaControls.ButtonStateType.DEFAULT); - - if (opt_handler) { - button.addEventListener('click', opt_handler); - } - - return button; -}; - -/** - * Enable/disable controls. - * - * @param {boolean} on True if enable, false if disable. - * @private - */ -MediaControls.prototype.enableControls_ = function(on) { - var controls = this.container_.querySelectorAll('.media-control'); - for (var i = 0; i != controls.length; i++) { - var classList = controls[i].classList; - if (on) { - classList.remove('disabled'); - } else { - classList.add('disabled'); - } - } - this.progressSlider_.disabled = !on; - this.volume_.disabled = !on; -}; - -/* - * Playback control. - */ - -/** - * Play the media. - */ -MediaControls.prototype.play = function() { - if (!this.media_) { - return; - } // Media is detached. - - this.media_.play(); -}; - -/** - * Pause the media. - */ -MediaControls.prototype.pause = function() { - if (!this.media_) { - return; // Media is detached. - } - - this.media_.pause(); -}; - -/** - * @return {boolean} True if the media is currently playing. - */ -MediaControls.prototype.isPlaying = function() { - return !!this.media_ && !this.media_.paused && !this.media_.ended; -}; - -/** - * Toggle play/pause. - */ -MediaControls.prototype.togglePlayState = function() { - if (this.isPlaying()) { - this.pause(); - } else { - this.play(); - } -}; - -/** - * Toggles play/pause state on a mouse click on the play/pause button. - * - * @param {Event} event Mouse click event. - */ -MediaControls.prototype.onPlayButtonClicked = function(event) { - this.togglePlayState(); -}; - -/** - * @param {HTMLElement=} opt_parent Parent container. - */ -MediaControls.prototype.initPlayButton = function(opt_parent) { - this.playButton_ = this.createButton('play media-control', - this.onPlayButtonClicked.bind(this), opt_parent, 3 /* States. */); - this.playButton_.setAttribute('aria-label', - str('MEDIA_PLAYER_PLAY_BUTTON_LABEL')); -}; - -/* - * Time controls - */ - -/** - * The default range of 100 is too coarse for the media progress slider. - */ -MediaControls.PROGRESS_RANGE = 5000; - -/** - * 5 seconds should be skipped when left/right key is pressed. - */ -MediaControls.PROGRESS_MAX_SECONDS_TO_SMALL_SKIP = 5; - -/** - * 10 seconds should be skipped when J/L key is pressed. - */ -MediaControls.PROGRESS_MAX_SECONDS_TO_BIG_SKIP = 10; - -/** - * 10% of duration should be skipped when the video is too short to skip 5 - * seconds. - */ -MediaControls.PROGRESS_MAX_RATIO_TO_SMALL_SKIP = 0.1; - -/** - * 20% of duration should be skipped when the video is too short to skip 10 - * seconds. - */ -MediaControls.PROGRESS_MAX_RATIO_TO_BIG_SKIP = 0.2; - -/** - * @param {HTMLElement=} opt_parent Parent container. - */ -MediaControls.prototype.initTimeControls = function(opt_parent) { - var timeControls = this.createControl('time-controls', opt_parent); - - var timeBox = this.createControl('time media-control', timeControls); - - this.currentTimeSpacer_ = this.createControl('spacer', timeBox); - this.currentTime_ = this.createControl('current', timeBox); - this.currentTime_.addEventListener('click', - this.onTimeLabelClick_.bind(this)); - // Set the initial width to the minimum to reduce the flicker. - this.updateTimeLabel_(0, 0); - - this.progressSlider_ = - /** @type {!CrSliderElement} */ (document.createElement('cr-slider')); - this.progressSlider_.classList.add('progress', 'media-control'); - this.progressSlider_.max = MediaControls.PROGRESS_RANGE; - this.progressSlider_.noKeybindings = true; - this.progressSlider_.setAttribute('aria-label', - str('MEDIA_PLAYER_SEEK_SLIDER_LABEL')); - this.progressSlider_.addEventListener('dragging-changed', event => { - this.setSeeking_(event.detail.value); - }); - this.progressSlider_.addEventListener('cr-slider-value-changed', () => { - this.onProgressChange_(); - this.updateTimeFromSlider_(); - }); - timeControls.appendChild(this.progressSlider_); -}; - -/** - * @param {number} current Current time is seconds. - * @param {number} duration Duration in seconds. - * @private - */ -MediaControls.prototype.displayProgress_ = function(current, duration) { - var ratio = current / duration; - this.progressSlider_.value = ratio * this.progressSlider_.max; - this.updateTimeLabel_(current); -}; - -/** @private */ -MediaControls.prototype.updateTimeFromSlider_ = function() { - if (!this.media_) { - return; // Media is detached. - } - - if (this.media_.duration && this.progressSlider_.max > 0) { - this.media_.currentTime = - this.media_.duration * this.progressSlider_.getRatio(); - } -}; - -/** @private */ -MediaControls.prototype.onProgressChange_ = function() { - if (!this.media_) { - return; // Media is detached. - } - - if (!this.media_.seekable || !this.media_.duration) { - console.error('Inconsistent media state'); - return; - } - - // Re-start playing the video when the seek bar is moved from ending point. - if (this.media_.ended) { - this.play(); - } - - if (this.media_.duration && this.progressSlider_.max > 0) { - this.updateTimeLabel_( - this.media_.duration * this.progressSlider_.getRatio()); - } -}; - -/** - * Skips forward/backword. - * @param {number} sec Seconds to skip. Set negative value to skip backword. - * @private - */ -MediaControls.prototype.skip_ = function(sec) { - if (this.media_ && this.media_.duration > 0) { - var stepsToSkip = MediaControls.PROGRESS_RANGE * - (sec / this.media_.duration); - this.progressSlider_.value = Math.max(Math.min( - this.progressSlider_.value + stepsToSkip, - this.progressSlider_.max), 0); - this.onProgressChange_(); - this.updateTimeFromSlider_(); - } -}; - -/** - * Invokes small skip. - * @param {boolean} forward Whether to skip forward or backword. - */ -MediaControls.prototype.smallSkip = function(forward) { - var secondsToSkip = Math.min( - MediaControls.PROGRESS_MAX_SECONDS_TO_SMALL_SKIP, - this.media_.duration * MediaControls.PROGRESS_MAX_RATIO_TO_SMALL_SKIP); - if (!forward) { - secondsToSkip *= -1; - } - this.skip_(secondsToSkip); -}; - -/** - * Invokes big skip. - * @param {boolean} forward Whether to skip forward or backword. - */ -MediaControls.prototype.bigSkip = function(forward) { - var secondsToSkip = Math.min( - MediaControls.PROGRESS_MAX_SECONDS_TO_BIG_SKIP, - this.media_.duration * MediaControls.PROGRESS_MAX_RATIO_TO_BIG_SKIP); - if (!forward) { - secondsToSkip *= -1; - } - this.skip_(secondsToSkip); -}; - -/** - * Handles 'seeking' state, which starts by dragging slider knob and finishes by - * releasing it. While seeking, we pause the video when seeking starts and - * resume the last play state when seeking ends. - * @private - */ -MediaControls.prototype.setSeeking_ = function(seeking) { - if (seeking === this.seeking_) { - return; - } - - this.seeking_ = seeking; - - if (seeking) { - this.resumeAfterDrag_ = this.isPlaying(); - this.media_.pause(true /* seeking */); - } else { - if (this.resumeAfterDrag_) { - if (this.media_.ended) { - this.onMediaPlay_(false); - } else { - this.media_.play(true /* seeking */); - } - } - this.resumeAfterDrag_ = false; - } - this.updatePlayButtonState_(this.isPlaying()); -}; - -/** - * Click handler for the time label. - * @private - */ -MediaControls.prototype.onTimeLabelClick_ = function(event) { - this.showRemainingTime_ = !this.showRemainingTime_; - this.updateTimeLabel_(this.media_.currentTime, this.media_.duration); -}; - -/** - * Update the label for current playing position and video duration. - * The label should be like "0:06 / 0:32" or "-0:26 / 0:32". - * @param {number} current Current playing position. - * @param {number=} opt_duration Video's duration. - * @private - */ -MediaControls.prototype.updateTimeLabel_ = function(current, opt_duration) { - var duration = opt_duration; - if (duration === undefined) { - duration = this.media_ ? this.media_.duration : 0; - } - // media's duration and currentTime can be NaN. Default to 0. - if (isNaN(duration)) { - duration = 0; - } - if (isNaN(current)) { - current = 0; - } - - if (isFinite(duration)) { - this.currentTime_.textContent = - (this.showRemainingTime_ ? MediaControls.formatTime_(current - duration) - : MediaControls.formatTime_(current)) + ' / ' + - MediaControls.formatTime_(duration); - // Keep the maximum space to prevent time label from moving while playing. - this.currentTimeSpacer_.textContent = - (this.showRemainingTime_ ? '-' : '') + - MediaControls.formatTime_(duration) + ' / ' + - MediaControls.formatTime_(duration); - } else { - // Media's duration can be positive infinity value when the media source is - // not known to be bounded yet. In such cases, we should hide duration. - this.currentTime_.textContent = MediaControls.formatTime_(current); - this.currentTimeSpacer_.textContent = MediaControls.formatTime_(current); - } -}; - -/* - * Volume controls - */ - -MediaControls.STORAGE_PREFIX = 'videoplayer-'; - -MediaControls.KEY_NORMALIZED_VOLUME = - MediaControls.STORAGE_PREFIX + 'normalized-volume'; -MediaControls.KEY_MUTED = - MediaControls.STORAGE_PREFIX + 'muted'; - -/** - * @param {HTMLElement=} opt_parent Parent element for the controls. - */ -MediaControls.prototype.initVolumeControls = function(opt_parent) { - var volumeControls = this.createControl('volume-controls', opt_parent); - - this.soundButton_ = this.createButton('sound media-control', - this.onSoundButtonClick_.bind(this), volumeControls); - this.soundButton_.setAttribute('level', 3); // max level. - this.soundButton_.setAttribute('aria-label', - str('MEDIA_PLAYER_MUTE_BUTTON_LABEL')); - - this.volume_ = - /** @type {!CrSliderElement} */ (document.createElement('cr-slider')); - this.volume_.classList.add('volume', 'media-control'); - this.volume_.setAttribute('aria-label', - str('MEDIA_PLAYER_VOLUME_SLIDER_LABEL')); - this.volume_.addEventListener( - 'cr-slider-value-changed', this.onVolumeChange_.bind(this)); - this.loadVolumeControlState(); - volumeControls.appendChild(this.volume_); -}; - -MediaControls.prototype.loadVolumeControlState = function() { - chrome.storage.local.get([MediaControls.KEY_NORMALIZED_VOLUME, - MediaControls.KEY_MUTED], - function(retrieved) { - var normalizedVolume = (MediaControls.KEY_NORMALIZED_VOLUME - in retrieved) - ? retrieved[MediaControls.KEY_NORMALIZED_VOLUME] : 1; - var isMuted = (MediaControls.KEY_MUTED in retrieved) - ? retrieved[MediaControls.KEY_MUTED] : false; - this.volumeModel_.set(normalizedVolume, isMuted); - this.reflectVolumeToUi_(); - }.bind(this)); -}; - -MediaControls.prototype.saveVolumeControlState = function() { - var valuesToStore = {}; - valuesToStore[MediaControls.KEY_NORMALIZED_VOLUME] = - this.volumeModel_.volume_; - valuesToStore[MediaControls.KEY_MUTED] = this.volumeModel_.isMuted_; - chrome.storage.local.set(valuesToStore); -}; - -/** - * Click handler for the sound level button. - * @private - */ -MediaControls.prototype.onSoundButtonClick_ = function() { - this.volumeModel_.toggleMute(); - this.saveVolumeControlState(); - this.reflectVolumeToUi_(); -}; - -/** - * @param {number} value Volume [0..1]. - * @return {number} The rough level [0..3] used to pick an icon. - * @private - */ -MediaControls.getVolumeLevel_ = function(value) { - if (value == 0) return 0; - if (value <= 1 / 3) return 1; - if (value <= 2 / 3) return 2; - return 3; -}; - -/** - * Reflects volume model to the UI elements. - * @private - */ -MediaControls.prototype.reflectVolumeToUi_ = function() { - this.soundButton_.setAttribute('level', - MediaControls.getVolumeLevel_(this.volumeModel_.getMediaVolume())); - this.soundButton_.setAttribute('aria-label', this.volumeModel_.isMuted_ - ? str('MEDIA_PLAYER_UNMUTE_BUTTON_LABEL') - : str('MEDIA_PLAYER_MUTE_BUTTON_LABEL')); - this.volume_.value = this.volumeModel_.getMediaVolume() * this.volume_.max; - if (this.media_) { - this.media_.volume = this.volumeModel_.getMediaVolume(); - } -}; - -/** - * Handles change event of the volume slider. - * @private - */ -MediaControls.prototype.onVolumeChange_ = function() { - if (!this.media_) { - return; // Media is detached. - } - - this.volumeModel_.onVolumeChanged(this.volume_.getRatio()); - this.saveVolumeControlState(); - this.reflectVolumeToUi_(); -}; - -/** - * Initializes subtitles button. - */ -MediaControls.prototype.initSubtitlesButton = function() { - this.subtitlesTrack_ = null; - this.subtitlesButton_ = - this.createButton('subtitles', this.onSubtitlesButtonClicked_.bind(this)); -}; - -/** - * @param {Event} event Mouse click event. - * @private - */ -MediaControls.prototype.onSubtitlesButtonClicked_ = function(event) { - if (!this.subtitlesTrack_) { - return; - } - this.toggleSubtitlesMode_(this.subtitlesTrack_.mode === 'hidden'); -}; - -/** - * @param {boolean} on Whether enabled or not. - * @private - */ -MediaControls.prototype.toggleSubtitlesMode_ = function(on) { - if (!this.subtitlesTrack_) { - return; - } - if (on) { - this.subtitlesTrack_.mode = 'showing'; - this.subtitlesButton_.setAttribute('showing', ''); - this.subtitlesButton_.setAttribute('aria-label', - str('VIDEO_PLAYER_DISABLE_SUBTITLES_BUTTON_LABEL')); - } else { - this.subtitlesTrack_.mode = 'hidden'; - this.subtitlesButton_.removeAttribute('showing'); - this.subtitlesButton_.setAttribute('aria-label', - str('VIDEO_PLAYER_ENABLE_SUBTITLES_BUTTON_LABEL')); - } -}; - -/** - * @param {TextTrack} track Subtitles track - * @private - */ -MediaControls.prototype.attachTextTrack_ = function(track) { - this.subtitlesTrack_ = track; - if (this.subtitlesTrack_) { - this.toggleSubtitlesMode_(true); - this.subtitlesButton_.removeAttribute('unavailable'); - } else { - this.subtitlesButton_.setAttribute('unavailable', ''); - } -}; - -/** - * @private - */ -MediaControls.prototype.detachTextTrack_ = function() { - this.subtitlesTrack_ = null; -}; - -/* - * Media event handlers. - */ - -/** - * Attach a media element. - * - * @param {!HTMLMediaElement} mediaElement The media element to control. - */ -MediaControls.prototype.attachMedia = function(mediaElement) { - this.media_ = mediaElement; - - this.media_.addEventListener('play', this.onMediaPlayBound_); - this.media_.addEventListener('pause', this.onMediaPauseBound_); - this.media_.addEventListener('durationchange', this.onMediaDurationBound_); - this.media_.addEventListener('timeupdate', this.onMediaProgressBound_); - this.media_.addEventListener('error', this.onMediaError_); - - // If the text banner is being displayed, hide it immediately, since it is - // related to the previous media. - this.textBanner_.removeAttribute('visible'); - - // Reflect the media state in the UI. - this.onMediaDuration_(); - this.onMediaPlay_(this.isPlaying()); - this.onMediaProgress_(); - - // Reflect the user specified volume to the media. - this.media_.volume = this.volumeModel_.getMediaVolume(); - - if (this.media_.textTracks && this.media_.textTracks.length > 0) { - this.attachTextTrack_(this.media_.textTracks[0]); - } else { - this.attachTextTrack_(null); - } -}; - -/** - * Detach media event handlers. - */ -MediaControls.prototype.detachMedia = function() { - if (!this.media_) { - return; - } - - this.media_.removeEventListener('play', this.onMediaPlayBound_); - this.media_.removeEventListener('pause', this.onMediaPauseBound_); - this.media_.removeEventListener('durationchange', this.onMediaDurationBound_); - this.media_.removeEventListener('timeupdate', this.onMediaProgressBound_); - this.media_.removeEventListener('error', this.onMediaError_); - - this.media_ = null; - this.detachTextTrack_(); -}; - -/** - * Force-empty the media pipeline. This is a workaround for crbug.com/149957. - * The document is not going to be GC-ed until the last Files app window closes, - * but we want the media pipeline to deinitialize ASAP to minimize leakage. - */ -MediaControls.prototype.cleanup = function() { - if (!this.media_) { - return; - } - - this.media_.src = ''; - this.media_.load(); - this.detachMedia(); -}; - -/** - * 'play' and 'pause' event handler. - * @param {boolean} playing True if playing. - * @private - */ -MediaControls.prototype.onMediaPlay_ = function(playing) { - if (this.progressSlider_.dragging) { - return; - } - - this.updatePlayButtonState_(playing); - this.onPlayStateChanged(); -}; - -/** - * 'durationchange' event handler. - * @private - */ -MediaControls.prototype.onMediaDuration_ = function() { - if (!this.media_ || !this.media_.duration) { - this.enableControls_(false); - return; - } - - this.enableControls_(true); - - if (this.media_.seekable) { - this.progressSlider_.classList.remove('readonly'); - } else { - this.progressSlider_.classList.add('readonly'); - } - - this.updateTimeLabel_(this.media_.currentTime, this.media_.duration); - - if (this.media_.seekable) { - this.restorePlayState(); - } -}; - -/** - * 'timeupdate' event handler. - * @private - */ -MediaControls.prototype.onMediaProgress_ = function() { - if (!this.media_ || !this.media_.duration) { - this.displayProgress_(0, 1); - return; - } - - var current = this.media_.currentTime; - var duration = this.media_.duration; - - if (this.progressSlider_.dragging) { - return; - } - - this.displayProgress_(current, duration); - - if (current == duration) { - this.onMediaComplete(); - } - this.onPlayStateChanged(); -}; - -/** - * Called when the media playback is complete. - */ -MediaControls.prototype.onMediaComplete = function() {}; - -/** - * Called when play/pause state is changed or on playback progress. - * This is the right moment to save the play state. - */ -MediaControls.prototype.onPlayStateChanged = function() {}; - -/** - * Updates the play button state. - * @param {boolean} playing If the video is playing. - * @private - */ -MediaControls.prototype.updatePlayButtonState_ = function(playing) { - if (this.media_.ended && - this.progressSlider_.value === this.progressSlider_.max) { - this.playButton_.setAttribute('state', - MediaControls.ButtonStateType.ENDED); - this.playButton_.setAttribute('aria-label', - str('MEDIA_PLAYER_PLAY_BUTTON_LABEL')); - } else if (playing) { - this.playButton_.setAttribute('state', - MediaControls.ButtonStateType.PLAYING); - this.playButton_.setAttribute('aria-label', - str('MEDIA_PLAYER_PAUSE_BUTTON_LABEL')); - } else { - this.playButton_.setAttribute('state', - MediaControls.ButtonStateType.DEFAULT); - this.playButton_.setAttribute('aria-label', - str('MEDIA_PLAYER_PLAY_BUTTON_LABEL')); - } -}; - -/** - * Restore play state. Base implementation is empty. - */ -MediaControls.prototype.restorePlayState = function() {}; - -/** - * Encode current state into the page URL or the app state. - */ -MediaControls.prototype.encodeState = function() { - if (!this.media_ || !this.media_.duration) { - return; - } - - if (window.appState) { - window.appState.time = this.media_.currentTime; - appUtil.saveAppState(); - } - return; -}; - -/** - * Decode current state from the page URL or the app state. - * @return {boolean} True if decode succeeded. - */ -MediaControls.prototype.decodeState = function() { - if (!this.media_ || !window.appState || !('time' in window.appState)) { - return false; - } - // There is no page reload for apps v2, only app restart. - // Always restart in paused state. - this.media_.currentTime = window.appState.time; - this.pause(); - return true; -}; - -/** - * Remove current state from the page URL or the app state. - */ -MediaControls.prototype.clearState = function() { - if (!window.appState) { - return; - } - - if ('time' in window.appState) { - delete window.appState.time; - } - appUtil.saveAppState(); - return; -}; - -/** - * Create video controls. - * - * @param {!HTMLElement} containerElement The container for the controls. - * @param {function(Event)} onMediaError Function to display an error message. - * @param {function(Event)=} opt_fullScreenToggle Function to toggle fullscreen - * mode. - * @param {HTMLElement=} opt_stateIconParent The parent for the icon that - * gives visual feedback when the playback state changes. - * @constructor - * @struct - * @extends {MediaControls} - */ -function VideoControls( - containerElement, onMediaError, opt_fullScreenToggle, opt_stateIconParent) { - MediaControls.call(this, containerElement, onMediaError); - - this.container_.classList.add('video-controls'); - this.initPlayButton(); - this.initTimeControls(); - this.initVolumeControls(); - this.initSubtitlesButton(); - - // Create the cast menu button. - // We need to use <button> since cr.ui.MenuButton.decorate modifies prototype - // chain, by which <files-icon-button> will not work correctly. - // TODO(fukino): Find a way to use files-icon-button consistently. - this.castButton_ = this.createControl( - 'cast media-button', undefined, 'button'); - this.castButton_.setAttribute('menu', '#cast-menu'); - this.castButton_.setAttribute('aria-label', str('VIDEO_PLAYER_PLAY_ON')); - this.castButton_.setAttribute('state', MediaControls.ButtonStateType.DEFAULT); - this.castButton_.appendChild(document.createElement('files-ripple')); - cr.ui.decorate(this.castButton_, cr.ui.MenuButton); - - // Create the cast button, which is a normal button and is used when we cast - // videos usign Media Router. - this.createButton('cast-button'); - - if (opt_fullScreenToggle) { - this.fullscreenButton_ = - this.createButton('fullscreen', opt_fullScreenToggle); - this.fullscreenButton_.setAttribute('aria-label', - str('VIDEO_PLAYER_FULL_SCREEN_BUTTON_LABEL')); - } - - if (opt_stateIconParent) { - this.stateIcon_ = this.createControl( - 'playback-state-icon', opt_stateIconParent); - this.textBanner_ = this.createControl('text-banner', opt_stateIconParent); - } - - // Disables all controls at first. - this.enableControls_(false); - - var videoControls = this; - chrome.mediaPlayerPrivate.onTogglePlayState.addListener(function() { - videoControls.togglePlayStateWithFeedback(); - }); -} - -/** - * No resume if we are within this margin from the start or the end. - */ -VideoControls.RESUME_MARGIN = 0.03; - -/** - * No resume for videos shorter than this. - */ -VideoControls.RESUME_THRESHOLD = 5 * 60; // 5 min. - -/** - * When resuming rewind back this much. - */ -VideoControls.RESUME_REWIND = 5; // seconds. - -VideoControls.prototype = { __proto__: MediaControls.prototype }; - -/** - * Shows icon feedback for the current state of the video player. - * @private - */ -VideoControls.prototype.showIconFeedback_ = function() { - var stateIcon = this.stateIcon_; - stateIcon.removeAttribute('state'); - - setTimeout(function() { - var newState = this.isPlaying() ? 'play' : 'pause'; - - var onAnimationEnd = function(state, event) { - if (stateIcon.getAttribute('state') === state) { - stateIcon.removeAttribute('state'); - } - - stateIcon.removeEventListener('animationend', onAnimationEnd); - }.bind(null, newState); - stateIcon.addEventListener('animationend', onAnimationEnd); - - // Shows the icon with animation. - stateIcon.setAttribute('state', newState); - }.bind(this), 0); -}; - -/** - * Shows a text banner. - * - * @param {string} identifier String identifier. - * @private - */ -VideoControls.prototype.showTextBanner_ = function(identifier) { - this.textBanner_.removeAttribute('visible'); - this.textBanner_.textContent = str(identifier); - - setTimeout(function() { - var onAnimationEnd = function(event) { - this.textBanner_.removeEventListener( - 'animationend', onAnimationEnd); - this.textBanner_.removeAttribute('visible'); - }.bind(this); - this.textBanner_.addEventListener('animationend', onAnimationEnd); - - this.textBanner_.setAttribute('visible', 'true'); - }.bind(this), 0); -}; - -/** - * @override - */ -VideoControls.prototype.onPlayButtonClicked = function(event) { - if (event.ctrlKey) { - this.toggleLoopedModeWithFeedback(true); - if (!this.isPlaying()) { - this.togglePlayState(); - } - } else { - this.togglePlayState(); - } -}; - -/** - * Media completion handler. - */ -VideoControls.prototype.onMediaComplete = function() { - this.onMediaPlay_(false); // Just update the UI. - this.savePosition(); // This will effectively forget the position. -}; - -/** - * Toggles the looped mode with feedback. - * @param {boolean} on Whether enabled or not. - */ -VideoControls.prototype.toggleLoopedModeWithFeedback = function(on) { - if (!this.getMedia().duration) { - return; - } - this.toggleLoopedMode(on); - if (on) { - // TODO(mtomasz): Simplify, crbug.com/254318. - this.showTextBanner_('VIDEO_PLAYER_LOOPED_MODE'); - } -}; - -/** - * Toggles the looped mode. - * @param {boolean} on Whether enabled or not. - */ -VideoControls.prototype.toggleLoopedMode = function(on) { - this.getMedia().loop = on; -}; - -/** - * Toggles play/pause state and flash an icon over the video. - */ -VideoControls.prototype.togglePlayStateWithFeedback = function() { - if (!this.getMedia().duration) { - return; - } - - this.togglePlayState(); - this.showIconFeedback_(); -}; - -/** - * Toggles play/pause state. - */ -VideoControls.prototype.togglePlayState = function() { - if (this.isPlaying()) { - // User gave the Pause command. Save the state and reset the loop mode. - this.toggleLoopedMode(false); - this.savePosition(); - } - MediaControls.prototype.togglePlayState.apply(this, arguments); -}; - -/** - * Saves the playback position to the persistent storage. - * @param {boolean=} opt_sync True if the position must be saved synchronously - * (required when closing app windows). - */ -VideoControls.prototype.savePosition = function(opt_sync) { - if (!this.media_ || - !this.media_.duration || - this.media_.duration < VideoControls.RESUME_THRESHOLD) { - return; - } - - var ratio = this.media_.currentTime / this.media_.duration; - var position; - if (ratio < VideoControls.RESUME_MARGIN || - ratio > (1 - VideoControls.RESUME_MARGIN)) { - // We are too close to the beginning or the end. - // Remove the resume position so that next time we start from the beginning. - position = null; - } else { - position = Math.floor( - Math.max(0, this.media_.currentTime - VideoControls.RESUME_REWIND)); - } - - if (opt_sync) { - // Packaged apps cannot save synchronously. - // Pass the data to the background page. - if (!window.saveOnExit) { - window.saveOnExit = []; - } - window.saveOnExit.push({ key: this.media_.src, value: position }); - } else { - appUtil.AppCache.update(this.media_.src, position); - } -}; - -/** - * Resumes the playback position saved in the persistent storage. - */ -VideoControls.prototype.restorePlayState = function() { - if (this.media_ && this.media_.duration >= VideoControls.RESUME_THRESHOLD) { - appUtil.AppCache.getValue(this.media_.src, function(position) { - if (position) { - this.media_.currentTime = position; - } - }.bind(this)); - } -}; - -/** - * Updates video control when the window is fullscreened or restored. - */ -VideoControls.prototype.onFullScreenChanged = function() { - var fullscreen = util.isFullScreen(chrome.app.window.current()); - if (fullscreen) { - this.container_.setAttribute('fullscreen', ''); - } else { - this.container_.removeAttribute('fullscreen'); - } - - if (this.fullscreenButton_) { - this.fullscreenButton_.setAttribute( - 'aria-label', - fullscreen ? str('VIDEO_PLAYER_EXIT_FULL_SCREEN_BUTTON_LABEL') : - str('VIDEO_PLAYER_FULL_SCREEN_BUTTON_LABEL')); - // If the fullscreen button has focus on entering fullscreen mode, reset the - // focus to make the spacebar toggle play/pause state. This is the - // consistent behavior with Youtube Web UI. - if (fullscreen) { - this.fullscreenButton_.blur(); - } - } -};
diff --git a/ui/file_manager/video_player/js/mouse_inactivity_watcher.js b/ui/file_manager/video_player/js/mouse_inactivity_watcher.js deleted file mode 100644 index 3f11c29..0000000 --- a/ui/file_manager/video_player/js/mouse_inactivity_watcher.js +++ /dev/null
@@ -1,222 +0,0 @@ -// Copyright (c) 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. - -/** - * A controller class detects mouse inactivity and hides "tool" elements. - * - * @param {Element} container The main DOM container. - * @param {number=} opt_timeout Hide timeout in ms. - * @param {function():boolean=} opt_toolsActive Function that returns |true| - * if the tools are active and should not be hidden. - * @constructor - */ -function MouseInactivityWatcher(container, opt_timeout, opt_toolsActive) { - this.container_ = container; - this.timeout_ = opt_timeout || MouseInactivityWatcher.DEFAULT_TIMEOUT; - this.toolsActive_ = opt_toolsActive || function() { - return false; - }; - - this.onTimeoutBound_ = this.onTimeout_.bind(this); - this.timeoutID_ = null; - this.mouseOverTool_ = false; - - this.clientX_ = 0; - this.clientY_ = 0; - - /** - * Indicates if the inactivity watcher is enabled or disabled. Use getters - * and setters. - * @type {boolean} - * @private - */ - this.disabled_ = false; - - this.container_.addEventListener('mousemove', this.onMouseMove_.bind(this)); - var tools = this.container_.querySelector('.tool'); - for (var i = 0; i < tools.length; i++) { - tools[i].addEventListener('mouseover', this.onToolMouseOver_.bind(this)); - tools[i].addEventListener('mouseout', this.onToolMouseOut_.bind(this)); - } - - // Show tools when the user touches the screen. - this.container_.addEventListener( - 'touchstart', this.activityStarted_.bind(this)); - var initiateFading = this.activityStopped_.bind(this, this.timeout_); - this.container_.addEventListener('touchend', initiateFading); - this.container_.addEventListener('touchcancel', initiateFading); - this.container_.addEventListener('focusin', function() { - this.activityStarted_(); - this.activityStopped_(); - }.bind(this)); - // If pointer goes outside the app window, tools should be hidden immediately. - document.addEventListener('mouseout', function(event) { - if (event.relatedTarget === null) { - this.forceTimeout_(); - } - }.bind(this)); -} - -/** - * Default inactivity timeout. - */ -MouseInactivityWatcher.DEFAULT_TIMEOUT = 3000; - -/** - * Defines getter/setter for disabled property to update inactivity state. - */ -MouseInactivityWatcher.prototype = { - /** - * @return {boolean} - */ - get disabled() { - return this.disabled_; - }, - - /** - * @param {boolean} value - */ - set disabled(value) { - this.disabled_ = value; - if (value) { - this.kick(); - } else { - this.check(); - } - } -}; - -/** - * @param {boolean} on True if show, false if hide. - */ -MouseInactivityWatcher.prototype.showTools = function(on) { - if (on) { - this.container_.setAttribute('tools', 'true'); - } else { - this.container_.removeAttribute('tools'); - } -}; - -/** - * To be called when the user started activity. Shows the tools - * and cancels the countdown. - * @private - */ -MouseInactivityWatcher.prototype.activityStarted_ = function() { - this.showTools(true); - - if (this.timeoutID_) { - clearTimeout(this.timeoutID_); - this.timeoutID_ = null; - } -}; - -/** - * Called when user activity has stopped. Re-starts the countdown. - * @param {number=} opt_timeout Timeout. - * @private - */ -MouseInactivityWatcher.prototype.activityStopped_ = function(opt_timeout) { - if (this.disabled_ || this.mouseOverTool_ || this.toolsActive_()) { - return; - } - - if (this.timeoutID_) { - clearTimeout(this.timeoutID_); - } - - this.timeoutID_ = - setTimeout(this.onTimeoutBound_, opt_timeout || this.timeout_); -}; - -/** - * Called when a user performed a short action (such as a click or a key press) - * that should show the tools if they are not visible. - * @param {number=} opt_timeout Timeout. - */ -MouseInactivityWatcher.prototype.kick = function(opt_timeout) { - this.activityStarted_(); - this.activityStopped_(opt_timeout); -}; - -/** - * Check if the tools are active and update the tools visibility accordingly. - */ -MouseInactivityWatcher.prototype.check = function() { - if (this.toolsActive_()) { - this.activityStarted_(); - } else { - this.activityStopped_(); - } -}; - -/** - * Mouse move handler. - * - * @param {Event} e Event. - * @private - */ -MouseInactivityWatcher.prototype.onMouseMove_ = function(e) { - if (this.clientX_ == e.clientX && this.clientY_ == e.clientY) { - // The mouse has not moved, must be the cursor change triggered by - // some of the attributes on the root container. Ignore the event. - return; - } - this.clientX_ = e.clientX; - this.clientY_ = e.clientY; - - if (this.disabled_) { - return; - } - - this.kick(); -}; - -/** - * Mouse over handler on a tool element. - * - * @param {Event} e Event. - * @private - */ -MouseInactivityWatcher.prototype.onToolMouseOver_ = function(e) { - this.mouseOverTool_ = true; - if (!this.disabled_) { - this.kick(); - } -}; - -/** - * Mouse out handler on a tool element. - * - * @param {Event} e Event. - * @private - */ -MouseInactivityWatcher.prototype.onToolMouseOut_ = function(e) { - this.mouseOverTool_ = false; - if (!this.disabled_) { - this.kick(); - } -}; - -/** - * Timeout handler. - * @private - */ -MouseInactivityWatcher.prototype.onTimeout_ = function() { - this.timeoutID_ = null; - if (!this.disabled_ && !this.toolsActive_()) { - this.showTools(false); - } -}; - -/** - * Force the timer to be timed out immediately. - * @private - */ -MouseInactivityWatcher.prototype.forceTimeout_ = function() { - if (this.timeoutID_) { - clearTimeout(this.timeoutID_); - this.onTimeout_(); - } -};
diff --git a/ui/file_manager/video_player/js/video_player.js b/ui/file_manager/video_player/js/video_player.js index 0277e91..53f21ef 100644 --- a/ui/file_manager/video_player/js/video_player.js +++ b/ui/file_manager/video_player/js/video_player.js
@@ -2,310 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -/** - * @param {!HTMLElement} playerContainer Main container. - * @param {!HTMLElement} videoContainer Container for the video element. - * @param {!HTMLElement} controlsContainer Container for video controls. - * @constructor - * @struct - * @extends {VideoControls} - */ -function FullWindowVideoControls( - playerContainer, videoContainer, controlsContainer) { - VideoControls.call(this, - controlsContainer, - this.onPlaybackError_.wrap(this), - this.toggleFullScreen_.wrap(this), - videoContainer); - - this.playerContainer_ = playerContainer; - this.decodeErrorOccured = false; - - this.casting = false; - this.isRtl_ = - window.getComputedStyle(this.playerContainer_)['direction'] === 'rtl'; - - const currentWindow = chrome.app.window.current(); - currentWindow.onFullscreened.addListener(this.onFullScreenChanged.bind(this)); - currentWindow.onRestored.addListener(this.onFullScreenChanged.bind(this)); - document.addEventListener('keydown', function(e) { - this.inactivityWatcher_.kick(); - switch (util.getKeyModifiers(e) + e.key) { - // Handle debug shortcut keys. - case 'Ctrl-Shift-I': // Ctrl+Shift+I - chrome.fileManagerPrivate.openInspector( - chrome.fileManagerPrivate.InspectionType.NORMAL); - break; - case 'Ctrl-Shift-J': // Ctrl+Shift+J - chrome.fileManagerPrivate.openInspector( - chrome.fileManagerPrivate.InspectionType.CONSOLE); - break; - case 'Ctrl-Shift-C': // Ctrl+Shift+C - chrome.fileManagerPrivate.openInspector( - chrome.fileManagerPrivate.InspectionType.ELEMENT); - break; - case 'Ctrl-Shift-B': // Ctrl+Shift+B - chrome.fileManagerPrivate.openInspector( - chrome.fileManagerPrivate.InspectionType.BACKGROUND); - break; - - case ' ': // Space - case 'k': - case 'MediaPlayPause': - if (!e.target.classList.contains('menu-button')) { - this.togglePlayStateWithFeedback(); - } - break; - case 'Escape': - util.toggleFullScreen( - chrome.app.window.current(), - false); // Leave the full screen mode. - break; - case 'MediaTrackNext': - player.advance_(true); - break; - case 'MediaTrackPrevious': - player.advance_(false); - break; - case 'ArrowRight': - if (!e.target.classList.contains('volume')) { - this.smallSkip(!this.isRtl_ /* forward */); - } - break; - case 'ArrowLeft': - if (!e.target.classList.contains('volume')) { - this.smallSkip(this.isRtl_ /* forward */); - } - break; - case 'l': - this.bigSkip(true /* forward */); - break; - case 'j': - this.bigSkip(false /* forward */); - break; - case 'BrowserBack': - chrome.app.window.current().close(); - break; - case 'MediaStop': - // TODO: Define "Stop" behavior. - break; - } - }.wrap(this)); - document.addEventListener('keypress', function(e) { - this.inactivityWatcher_.kick(); - }.wrap(this)); - controlsContainer.addEventListener('cr-slider-value-changed', () => { - this.inactivityWatcher_.kick(); - }); - - // TODO(mtomasz): Simplify. crbug.com/254318. - let clickInProgress = false; - videoContainer.addEventListener('click', function(e) { - if (clickInProgress) { - return; - } - - clickInProgress = true; - const togglePlayState = function() { - clickInProgress = false; - - if (e.ctrlKey) { - this.toggleLoopedModeWithFeedback(true); - if (!this.isPlaying()) { - this.togglePlayStateWithFeedback(); - } - } else { - this.togglePlayStateWithFeedback(); - } - }.wrap(this); - - if (!this.media_) { - player.reloadCurrentVideo(togglePlayState); - } else { - setTimeout(togglePlayState, 0); - } - }.wrap(this)); - - /** - * @type {MouseInactivityWatcher} - * @private - */ - this.inactivityWatcher_ = new MouseInactivityWatcher(playerContainer); - this.inactivityWatcher_.check(); -} - -FullWindowVideoControls.prototype = { __proto__: VideoControls.prototype }; - -/** - * Gets inactivity watcher. - * @return {MouseInactivityWatcher} An inactivity watcher. - */ -FullWindowVideoControls.prototype.getInactivityWatcher = function() { - return this.inactivityWatcher_; -}; - -/** - * Displays error message. - * - * @param {string} message Message id. - */ -FullWindowVideoControls.prototype.showErrorMessage = function(message) { - const errorBanner = getRequiredElement('error'); - errorBanner.textContent = str(message); - errorBanner.setAttribute('visible', 'true'); - - // The window is hidden if the video has not loaded yet. - chrome.app.window.current().show(); -}; - -/** - * Handles playback (decoder) errors. - * @param {MediaError} error Error object. - * @private - */ -FullWindowVideoControls.prototype.onPlaybackError_ = function(error) { - if (error.target && error.target.error && - error.target.error.code === MediaError.MEDIA_ERR_SRC_NOT_SUPPORTED) { - if (this.casting) { - this.showErrorMessage('VIDEO_PLAYER_VIDEO_FILE_UNSUPPORTED_FOR_CAST'); - } else { - this.showErrorMessage('VIDEO_PLAYER_VIDEO_FILE_UNSUPPORTED'); - } - this.decodeErrorOccured = false; - } else { - this.showErrorMessage('VIDEO_PLAYER_PLAYBACK_ERROR'); - this.decodeErrorOccured = true; - } - - // Disable controls on the ui. - getRequiredElement('video-player').setAttribute('disabled', 'true'); - - // Detach the video element, since it may be unreliable and reset stored - // current playback time. - this.cleanup(); - this.clearState(); - - // Avoid reusing a video element. - player.unloadVideo(); -}; - -/** - * Toggles the full screen mode. - * @private - */ -FullWindowVideoControls.prototype.toggleFullScreen_ = function() { - const appWindow = chrome.app.window.current(); - util.toggleFullScreen(appWindow, !util.isFullScreen(appWindow)); -}; - -/** - * Media completion handler. - */ -FullWindowVideoControls.prototype.onMediaComplete = function() { - VideoControls.prototype.onMediaComplete.apply(this, arguments); - if (!this.getMedia().loop) { - player.advance_(true); - } -}; - -/** - * Video Player - * - * @constructor - * @struct - */ -function VideoPlayer() { - this.controls_ = null; - this.videoElement_ = null; - - /** - * @type {Array<!FileEntry>} - * @private - */ - this.videos_ = null; - - this.currentPos_ = 0; - - this.currentSession_ = null; - this.currentCast_ = null; - - this.loadQueue_ = new AsyncUtil.Queue(); - - this.onCastSessionUpdateBound_ = this.onCastSessionUpdate_.wrap(this); -} - -VideoPlayer.prototype = /** @struct */ { - /** - * @return {FullWindowVideoControls} - */ - get controls() { - return this.controls_; - } -}; - -/** - * Initializes the video player window. This method must be called after DOM - * initialization. - * @param {!Array<!FileEntry>} videos List of videos. - */ -VideoPlayer.prototype.prepare = function(videos) { - this.videos_ = videos; - - const preventDefault = function(event) { - event.preventDefault(); - }.wrap(null); - - document.ondragstart = preventDefault; - - cr.ui.decorate(getRequiredElement('cast-menu'), cr.ui.Menu); - - this.controls_ = new FullWindowVideoControls( - getRequiredElement('video-player'), - getRequiredElement('video-container'), - getRequiredElement('controls')); - - const observer = new MutationObserver(function(mutations) { - const isLoadingOrDisabledChanged = mutations.some(function(mutation) { - return mutation.attributeName === 'loading' || - mutation.attributeName === 'disabled'; - }); - if (isLoadingOrDisabledChanged) { - this.updateInactivityWatcherState_(); - } - }.bind(this)); - observer.observe(getRequiredElement('video-player'), - { attributes: true, childList: false }); - - const reloadVideo = function(e) { - if (this.controls_.decodeErrorOccured && - // Ignore shortcut keys - !e.ctrlKey && !e.altKey && !e.shiftKey && !e.metaKey) { - this.reloadCurrentVideo(function() { - this.videoElement_.play(); - }.wrap(this)); - e.preventDefault(); - } - }.wrap(this); - - const arrowRight = queryRequiredElement('.arrow-box .arrow.right'); - arrowRight.addEventListener('click', this.advance_.wrap(this, 1)); - const arrowLeft = queryRequiredElement('.arrow-box .arrow.left'); - arrowLeft.addEventListener('click', this.advance_.wrap(this, 0)); - - const videoPlayerElement = getRequiredElement('video-player'); - if (videos.length > 1) { - videoPlayerElement.setAttribute('multiple', true); - } else { - videoPlayerElement.removeAttribute('multiple'); - } - - const castButton = queryRequiredElement('.cast-button'); - castButton.addEventListener('click', - this.onCastButtonClicked_.wrap(this)); - - document.addEventListener('keydown', reloadVideo); - document.addEventListener('click', reloadVideo); -}; +const nativePlayer = new NativeControlsVideoPlayer(); /** * Unloads the player. @@ -318,538 +15,6 @@ } /** - * Loads the video file. - * @param {!FileEntry} video Entry of the video to be played. - * @param {function()=} opt_callback Completion callback. - * @private - */ -VideoPlayer.prototype.loadVideo_ = function(video, opt_callback) { - this.unloadVideo(true); - - this.loadQueue_.run(function(callback) { - document.title = video.name; - - const videoPlayerElement = getRequiredElement('video-player'); - if (this.currentPos_ === (this.videos_.length - 1)) { - videoPlayerElement.setAttribute('last-video', true); - } else { - videoPlayerElement.removeAttribute('last-video'); - } - - if (this.currentPos_ === 0) { - videoPlayerElement.setAttribute('first-video', true); - } else { - videoPlayerElement.removeAttribute('first-video'); - } - - // Re-enables ui and hides error message if already displayed. - getRequiredElement('video-player').removeAttribute('disabled'); - getRequiredElement('error').removeAttribute('visible'); - this.controls.detachMedia(); - this.controls.decodeErrorOccured = false; - this.controls.casting = !!this.currentCast_; - - videoPlayerElement.setAttribute('loading', true); - - const media = new MediaManager(video); - - // Show video's thumbnail if available while loading the video. - media.getThumbnail() - .then(function(thumbnailUrl) { - if (!thumbnailUrl) { - return Promise.reject(); - } - - return new Promise(function(resolve, reject) { - ImageLoaderClient.getInstance().load( - thumbnailUrl, function(result) { - if (result.data) { - resolve(result.data); - } else { - reject(); - } - }); - }); - }) - .then(function(dataUrl) { - getRequiredElement('thumbnail').style.backgroundImage = - 'url(' + dataUrl + ')'; - }) - .catch(function() { - // Shows no image on error. - getRequiredElement('thumbnail').style.backgroundImage = ''; - }); - - let videoElementInitializePromise; - if (this.currentCast_) { - metrics.recordPlayType(metrics.PLAY_TYPE.CAST); - - getRequiredElement('cast-name').textContent = - this.currentCast_.friendlyName; - - videoPlayerElement.setAttribute('castable', true); - - videoElementInitializePromise = - media.isAvailableForCast().then(function(result) { - if (!result) { - return Promise.reject('No casts are available.'); - } - - return new Promise(function(fulfill, reject) { - if (this.currentSession_) { - fulfill(this.currentSession_); - } else { - chrome.cast.requestSession( - fulfill, reject, undefined, this.currentCast_.label); - } - }.bind(this)).then(function(session) { - videoPlayerElement.setAttribute('casting', true); - session.addUpdateListener(this.onCastSessionUpdateBound_); - - this.currentSession_ = session; - this.videoElement_ = new CastVideoElement(media, session); - }.bind(this)); - }.bind(this)); - } else { - metrics.recordPlayType(metrics.PLAY_TYPE.LOCAL); - videoPlayerElement.removeAttribute('casting'); - - this.videoElement_ = document.createElement('video'); - this.videoElement_.autoPictureInPicture = true; - getRequiredElement('video-container').appendChild(this.videoElement_); - - const videoUrl = video.toURL(); - const source = document.createElement('source'); - source.src = videoUrl; - this.videoElement_.appendChild(source); - - media.isAvailableForCast() - .then(function(result) { - if (result) { - videoPlayerElement.setAttribute('castable', true); - } else { - videoPlayerElement.removeAttribute('castable'); - } - }) - .catch(function() { - videoPlayerElement.setAttribute('castable', true); - }); - - videoElementInitializePromise = this.searchSubtitle_(videoUrl) - .then(function(subltitleUrl) { - if (subltitleUrl) { - const track = document.createElement('track'); - track.src = subltitleUrl; - track.kind = 'subtitles'; - track.default = true; - this.videoElement_.appendChild(track); - } - }.bind(this)); - } - videoElementInitializePromise - .then(function() { - const handler = function(currentPos) { - if (currentPos === this.currentPos_) { - if (opt_callback) { - opt_callback(); - } - videoPlayerElement.removeAttribute('loading'); - } - - this.videoElement_.removeEventListener('loadedmetadata', handler); - }.wrap(this, this.currentPos_); - - this.videoElement_.addEventListener('loadedmetadata', handler); - - this.videoElement_.addEventListener('play', function() { - chrome.power.requestKeepAwake('display'); - this.updateInactivityWatcherState_(); - this.updateMediaSessionPlaybackState_(); - }.wrap(this)); - this.videoElement_.addEventListener('pause', function() { - chrome.power.releaseKeepAwake(); - this.updateInactivityWatcherState_(); - this.updateMediaSessionPlaybackState_(); - }.wrap(this)); - this.controls.attachMedia(this.videoElement_); - this.videoElement_.load(); - callback(); - }.bind(this)) - // In case of error. - .catch(function(error) { - if (this.currentCast_) { - metrics.recordCastVideoErrorAction(); - } - - videoPlayerElement.removeAttribute('loading'); - console.error('Failed to initialize the video element.', - error.stack || error); - this.controls_.showErrorMessage( - 'VIDEO_PLAYER_VIDEO_FILE_UNSUPPORTED'); - callback(); - }.bind(this)); - }.wrap(this)); -}; - -/** - * Search subtile file corresponding to a video. - * @param {string} url a url of a video. - * @return {string} a url of subtitle file, or an empty string. - */ -VideoPlayer.prototype.searchSubtitle_ = function(url) { - const baseUrl = util.splitExtension(url)[0]; - const resolveLocalFileSystemWithExtension = function(extension) { - return new Promise( - window.webkitResolveLocalFileSystemURL.bind(null, baseUrl + extension)); - }; - return resolveLocalFileSystemWithExtension('.vtt').then(function(subtitle) { - return subtitle.toURL(); - }).catch(function() { - return ''; - }); -}; - -/** - * Plays the first video. - */ -VideoPlayer.prototype.playFirstVideo = function() { - this.currentPos_ = 0; - this.reloadCurrentVideo(this.onFirstVideoReady_.wrap(this)); -}; - -/** - * Unloads the current video. - * @param {boolean=} opt_keepSession If true, keep using the current session. - * Otherwise, discards the session. - */ -VideoPlayer.prototype.unloadVideo = function(opt_keepSession) { - this.loadQueue_.run(function(callback) { - chrome.power.releaseKeepAwake(); - - // Detaches the media from the control. - this.controls.detachMedia(); - - if (this.videoElement_) { - // If the element has dispose method, call it (CastVideoElement has it). - if (this.videoElement_.dispose) { - this.videoElement_.dispose(); - } - // Detach the previous video element, if exists. - if (this.videoElement_.parentNode) { - this.videoElement_.parentNode.removeChild(this.videoElement_); - } - } - this.videoElement_ = null; - - if (!opt_keepSession && this.currentSession_) { - // We should not request stop() if the current session is not connected to - // the receiver. - if (this.currentSession_.status === chrome.cast.SessionStatus.CONNECTED) { - this.currentSession_.stop(callback, callback); - } else { - setTimeout(callback); - } - this.currentSession_.removeUpdateListener(this.onCastSessionUpdateBound_); - this.currentSession_ = null; - } else { - callback(); - } - }.wrap(this)); -}; - -/** - * Called when the first video is ready after starting to load. - * @private - */ -VideoPlayer.prototype.onFirstVideoReady_ = function() { - const videoWidth = this.videoElement_.videoWidth; - const videoHeight = this.videoElement_.videoHeight; - - const aspect = videoWidth / videoHeight; - let newWidth = videoWidth; - let newHeight = videoHeight; - - const shrinkX = newWidth / window.screen.availWidth; - const shrinkY = newHeight / window.screen.availHeight; - if (shrinkX > 1 || shrinkY > 1) { - if (shrinkY > shrinkX) { - newHeight = newHeight / shrinkY; - newWidth = newHeight * aspect; - } else { - newWidth = newWidth / shrinkX; - newHeight = newWidth / aspect; - } - } - - let oldLeft = window.screenX; - let oldTop = window.screenY; - const oldWidth = window.innerWidth; - const oldHeight = window.innerHeight; - - if (!oldWidth && !oldHeight) { - oldLeft = window.screen.availWidth / 2; - oldTop = window.screen.availHeight / 2; - } - - const appWindow = chrome.app.window.current(); - appWindow.innerBounds.width = Math.round(newWidth); - appWindow.innerBounds.height = Math.round(newHeight); - appWindow.outerBounds.left = Math.max( - 0, Math.round(oldLeft - (newWidth - oldWidth) / 2)); - appWindow.outerBounds.top = Math.max( - 0, Math.round(oldTop - (newHeight - oldHeight) / 2)); - appWindow.show(); - - this.videoElement_.play(); -}; - -/** - * Advances to the next (or previous) track. - * - * @param {boolean} direction True to the next, false to the previous. - * @private - */ -VideoPlayer.prototype.advance_ = function(direction) { - const newPos = this.currentPos_ + (direction ? 1 : -1); - if (0 <= newPos && newPos < this.videos_.length) { - this.currentPos_ = newPos; - this.reloadCurrentVideo(function() { - this.videoElement_.play(); - }.wrap(this)); - } -}; - -/** - * Reloads the current video. - * - * @param {function()=} opt_callback Completion callback. - */ -VideoPlayer.prototype.reloadCurrentVideo = function(opt_callback) { - const currentVideo = this.videos_[this.currentPos_]; - this.loadVideo_(currentVideo, opt_callback); -}; - -/** - * Invokes when a menuitem in the cast menu is selected. - * @param {Object} cast Selected element in the list of casts. - * @private - */ -VideoPlayer.prototype.onCastSelected_ = function(cast) { - // If the selected item is same as the current item, do nothing. - if ((this.currentCast_ && this.currentCast_.label) === (cast && cast.label)) { - return; - } - - this.unloadVideo(false); - - // Waits for unloading video. - this.loadQueue_.run(function(callback) { - this.currentCast_ = cast || null; - this.updateCheckOnCastMenu_(); - this.reloadCurrentVideo(); - callback(); - }.wrap(this)); -}; - -/** - * Set the list of casts. - * @param {Array<Object>} casts List of casts. - */ -VideoPlayer.prototype.setCastList = function(casts) { - const videoPlayerElement = getRequiredElement('video-player'); - const menu = getRequiredElement('cast-menu'); - menu.innerHTML = ''; - - // TODO(yoshiki): Handle the case that the current cast disappears. - - if (casts.length === 0) { - videoPlayerElement.removeAttribute('cast-available'); - if (this.currentCast_) { - this.onCurrentCastDisappear_(); - } - return; - } - - if (this.currentCast_) { - const currentCastAvailable = casts.some(function(cast) { - return this.currentCast_.label === cast.label; - }.wrap(this)); - - if (!currentCastAvailable) { - this.onCurrentCastDisappear_(); - } - } - - { - const item = new cr.ui.MenuItem(); - item.label = str('VIDEO_PLAYER_PLAY_THIS_COMPUTER'); - item.setAttribute('aria-label', item.label); - item.castLabel = ''; - item.addEventListener('activate', this.onCastSelected_.wrap(this, null)); - menu.appendChild(item); - } - - for (let i = 0; i < casts.length; i++) { - const item = new cr.ui.MenuItem(); - item.label = casts[i].friendlyName; - item.setAttribute('aria-label', item.label); - item.castLabel = casts[i].label; - item.addEventListener('activate', - this.onCastSelected_.wrap(this, casts[i])); - menu.appendChild(item); - } - this.updateCheckOnCastMenu_(); - videoPlayerElement.setAttribute('cast-available', true); -}; - -/** - * Tells the availability of cast receivers to VideoPlayeru topdate the - * visibility of the cast button.. - * @param {boolean} available Whether at least one cast receiver is available. - */ -VideoPlayer.prototype.setCastAvailability = function(available) { - const videoPlayerElement = getRequiredElement('video-player'); - if (available) { - videoPlayerElement.setAttribute('mr-cast-available', true); - } else { - videoPlayerElement.removeAttribute('mr-cast-available'); - if (this.currentCast_) { - this.onCurrentCastDisappear_(); - } - } -}; - -/** - * Handles click event on cast button to request a session. - * @private - */ -VideoPlayer.prototype.onCastButtonClicked_ = function() { - // This method is called only when Media Router is enabled. - // In this case, requestSession() will open a built-in dialog (not a dropdown - // menu) to choose the receiver, and callback is called with the session - // object after user's operation.. - chrome.cast.requestSession( - function(session) { - this.unloadVideo(true); - this.loadQueue_.run(function(callback) { - this.currentCast_ = { - label: session.receiver.label, - friendlyName: session.receiver.friendlyName - }; - this.currentSession_ = session; - this.reloadCurrentVideo(); - callback(); - }.bind(this)); - }.bind(this), - function(error) { - if (error.code !== chrome.cast.ErrorCode.CANCEL) { - console.error('requestSession from cast button failed', error); - } - }); -}; - -/** - * Updates the check status of the cast menu items. - * @private - */ -VideoPlayer.prototype.updateCheckOnCastMenu_ = function() { - const menuItems = - /** @type {cr.ui.Menu} */ (getRequiredElement('cast-menu')).menuItems; - for (let i = 0; i < menuItems.length; i++) { - const item = menuItems[i]; - if (this.currentCast_ === null) { - // Playing on this computer. - if (item.castLabel === '') { - item.checked = true; - } else { - item.checked = false; - } - } else { - // Playing on cast device. - if (item.castLabel === this.currentCast_.label) { - item.checked = true; - } else { - item.checked = false; - } - } - } -}; - -/** - * Called when the current cast is disappear from the cast list. - * @private - */ -VideoPlayer.prototype.onCurrentCastDisappear_ = function() { - this.currentCast_ = null; - if (this.currentSession_) { - this.currentSession_.removeUpdateListener(this.onCastSessionUpdateBound_); - this.currentSession_ = null; - } - this.controls.showErrorMessage('VIDEO_PLAYER_PLAYBACK_ERROR'); - this.unloadVideo(); -}; - -/** - * This method should be called when the session is updated. - * @param {boolean} alive Whether the session is alive or not. - * @private - */ -VideoPlayer.prototype.onCastSessionUpdate_ = function(alive) { - if (!alive) { - const videoPlayerElement = getRequiredElement('video-player'); - videoPlayerElement.removeAttribute('casting'); - - // Loads the current video in local player. - this.unloadVideo(); - this.loadQueue_.run(function(callback) { - this.currentCast_ = null; - if (!chrome.cast.usingPresentationApi) { - this.updateCheckOnCastMenu_(); - } - this.reloadCurrentVideo(); - callback(); - }.wrap(this)); - } -}; - -/** - * Updates the MouseInactivityWatcher's disable property to prevent control - * panel from being hidden in some situations. - * @private - */ -VideoPlayer.prototype.updateInactivityWatcherState_ = function() { - const videoPlayerElement = getRequiredElement('video-player'); - // If any of following condition is met, we don't hide the tool bar. - // - Loaded video is paused. - // - Loading a video is in progress. - // - Opening video has an error. - this.controls.getInactivityWatcher().disabled = - (this.videoElement_ && this.videoElement_.paused) || - videoPlayerElement.hasAttribute('loading') || - videoPlayerElement.hasAttribute('disabled'); -}; - -/** - * Updates the Media Session API with the current playback state of the video - * element. - * @private - */ -VideoPlayer.prototype.updateMediaSessionPlaybackState_ = function() { - if (!navigator.mediaSession) { - return; - } - - navigator.mediaSession.playbackState = - (this.videoElement_ && !this.videoElement_.paused) ? - MediaSessionPlaybackState.PLAYING : - MediaSessionPlaybackState.PAUSED; -}; - -const player = new VideoPlayer(); - -const nativePlayer = new NativeControlsVideoPlayer(); - -/** * Initializes the load time data. * @param {function()} callback Called when the load time data is ready. */
diff --git a/ui/file_manager/video_player/js/video_player_native_controls.js b/ui/file_manager/video_player/js/video_player_native_controls.js index 2b2fd734..27eafba 100644 --- a/ui/file_manager/video_player/js/video_player_native_controls.js +++ b/ui/file_manager/video_player/js/video_player_native_controls.js
@@ -44,13 +44,6 @@ this.videoElement_.style.pointerEvents = 'auto'; getRequiredElement('video-container').appendChild(this.videoElement_); - // TODO: remove the element in html when remove the feature flag - getRequiredElement('controls-wrapper').style.display = 'none'; - getRequiredElement('spinner-container').style.display = 'none'; - getRequiredElement('error-wrapper').style.display = 'none'; - getRequiredElement('thumbnail').style.display = 'none'; - getRequiredElement('cast-container').style.display = 'none'; - this.videoElement_.addEventListener('pause', this.onPause_.bind(this)); // Restore playback position when duration change.
diff --git a/ui/file_manager/video_player/js/video_player_scripts.js b/ui/file_manager/video_player/js/video_player_scripts.js index 98a11d1..74d86df 100644 --- a/ui/file_manager/video_player/js/video_player_scripts.js +++ b/ui/file_manager/video_player/js/video_player_scripts.js
@@ -27,12 +27,6 @@ // <include src="../../../webui/resources/js/cr/event_target.js"> // <include src="../../../webui/resources/js/cr/ui/array_data_model.js"> -// <include src="../../../webui/resources/js/cr/ui/position_util.js"> -// <include src="../../../webui/resources/js/cr/ui/menu_item.js"> -// <include src="../../../webui/resources/js/cr/ui/menu.js"> -// <include src="../../../webui/resources/js/cr/ui/menu_button.js"> -// <include src="../../../webui/resources/js/cr/ui/context_menu_handler.js"> - (function() { 'use strict'; @@ -46,18 +40,9 @@ /* TODO(tapted): Remove the util.js dependency */ // <include src="../../file_manager/common/js/util.js"> -// <include src="../../base/js/mediasession_types.js"> // <include src="../../base/js/volume_manager_types.js"> // <include src="../../base/js/filtered_volume_manager.js"> -// <include src="cast/cast_extension_discoverer.js"> -// <include src="cast/cast_video_element.js"> -// <include src="cast/media_manager.js"> -// <include src="cast/caster.js"> - -// <include src="media_controls.js"> -// <include src="mouse_inactivity_watcher.js"> - // <include src="video_player_native_controls.js"> // <include src="video_player.js">
diff --git a/ui/file_manager/video_player/video_player.html b/ui/file_manager/video_player/video_player.html index bcab8790..864937d 100644 --- a/ui/file_manager/video_player/video_player.html +++ b/ui/file_manager/video_player/video_player.html
@@ -9,15 +9,10 @@ <title>#xFEFF;</title> <script src="chrome://resources/polymer/v1_0/html-imports/html-imports.min.js"></script> <link rel="stylesheet" href="chrome://resources/css/text_defaults.css"> - <link rel="stylesheet" type="text/css" href="css/media_controls.css"> - <link rel="stylesheet" href="chrome://resources/css/menu.css"> <link rel="stylesheet" type="text/css" href="css/video_player.css"> <link rel="stylesheet" type="text/css" href="css/arrow_box.css"> - <link rel="stylesheet" type="text/css" href="css/cast_menu.css"> - <link rel="import" href="chrome-extension://hhaomjibdihmijegdhdafkllkbggdgoj/foreground/elements/files_icon_button.html"> - <link rel="import" href="chrome://resources/cr_elements/cr_slider/cr_slider.html"> <link rel="import" href="chrome://resources/cr_elements/cr_toast/cr_toast.html"> <script src="js/video_player_scripts.js"></script> @@ -25,18 +20,6 @@ <body> <custom-style> <style> - files-icon-button { - --files-ripple-bg-color: black; - --files-toggle-ripple-bg-color: black; - --files-toggle-ripple-activated-bg-color: black; - } - - cr-slider { - cursor: pointer; - - --cr-slider-knob-color-rgb: 64, 138, 241; - --cr-slider-active-color: rgb(66, 133, 244); - } /* Let cr-toast appear at top left corner */ cr-toast { @@ -51,36 +34,17 @@ </style> </custom-style> - <div id="video-player" tools> + <div id="video-player"> <cr-toast id="toast" duration="3000"> <div id="toast-content"></div> </cr-toast> - <cr-menu id='cast-menu' class='cast-menu tool' - i18n-values="playon-text:VIDEO_PLAYER_PLAY_ON"></cr-menu> - <div id="cast-container"> - <div id="cast-info"> - <div class="first-line" id='cast-name-label' - i18n-content="VIDEO_PLAYER_PLAYING_ON"></div> - <div class="second-line" id="cast-name"></div> - </div> - </div> - <div id="thumbnail"></div> <div id="video-container"> </div> - <div id="spinner-container"> - <div class="spinner"></div> - </div> - <div id="controls-wrapper"> - <div id="controls" class="tool"></div> - </div> <div class="arrow-box"> <div class="arrow left tool"><div></div></div> <div class="arrow-spacer"></div> <div class="arrow right tool"><div></div></div> </div> - <div id="error-wrapper"> - <div id="error"></div> - </div> </div> </body> </html>
diff --git a/ui/gfx/color_transform_unittest.cc b/ui/gfx/color_transform_unittest.cc index 372c3ca..b2801a5 100644 --- a/ui/gfx/color_transform_unittest.cc +++ b/ui/gfx/color_transform_unittest.cc
@@ -519,8 +519,11 @@ for (const auto& dst : common_color_spaces) { auto transform = ColorTransform::NewColorTransform( src, dst, ColorTransform::Intent::INTENT_PERCEPTUAL); - std::string source = "void main(inout half4 color) {" + - transform->GetSkShaderSource() + "}"; + std::string source = + "in shader child;\n" + "half4 main() {\n" + " half4 color = sample(child);\n" + + transform->GetSkShaderSource() + " return color; }"; auto result = SkRuntimeEffect::Make(SkString(source.c_str(), source.length())); EXPECT_NE(std::get<0>(result), nullptr);
diff --git a/ui/gl/gl_context.cc b/ui/gl/gl_context.cc index ad0d0a6..428b5ad08 100644 --- a/ui/gl/gl_context.cc +++ b/ui/gl/gl_context.cc
@@ -122,6 +122,12 @@ } } +bool GLContext::MakeCurrent(GLSurface* surface) { + if (context_lost_) + return false; + return MakeCurrentImpl(surface); +} + GLApi* GLContext::CreateGLApi(DriverGL* driver) { real_gl_api_ = new RealGLApi; real_gl_api_->set_gl_workarounds(gl_workarounds_); @@ -365,6 +371,13 @@ } GLenum GLContext::CheckStickyGraphicsResetStatus() { + GLenum status = CheckStickyGraphicsResetStatusImpl(); + if (status != GL_NO_ERROR) + context_lost_ = true; + return status; +} + +GLenum GLContext::CheckStickyGraphicsResetStatusImpl() { DCHECK(IsCurrent(nullptr)); return GL_NO_ERROR; } @@ -392,7 +405,7 @@ GLContext* virtual_context, GLSurface* surface) { if (!ForceGpuSwitchIfNeeded()) return false; - if (virtual_context_lost_) + if (context_lost_) return false; bool switched_real_contexts = GLContext::GetRealCurrent() != this; @@ -404,7 +417,7 @@ if (switched_real_contexts || !current_surface || !virtual_context->IsCurrent(surface)) { if (!MakeCurrent(surface)) { - virtual_context_lost_ = true; + context_lost_ = true; return false; } } @@ -445,7 +458,7 @@ virtual_context->SetCurrent(surface); if (!surface->OnMakeCurrent(virtual_context)) { LOG(ERROR) << "Could not make GLSurface current."; - virtual_context_lost_ = true; + context_lost_ = true; return false; } return true;
diff --git a/ui/gl/gl_context.h b/ui/gl/gl_context.h index b45c6d40..47c9403a 100644 --- a/ui/gl/gl_context.h +++ b/ui/gl/gl_context.h
@@ -125,7 +125,7 @@ const GLContextAttribs& attribs) = 0; // Makes the GL context and a surface current on the current thread. - virtual bool MakeCurrent(GLSurface* surface) = 0; + bool MakeCurrent(GLSurface* surface); // Releases this GL context and surface as current on the current thread. virtual void ReleaseCurrent(GLSurface* surface) = 0; @@ -190,7 +190,7 @@ // other than GL_NO_ERROR, that value is returned until the context is // destroyed. // The context must be current. - virtual unsigned int CheckStickyGraphicsResetStatus(); + unsigned int CheckStickyGraphicsResetStatus(); // Make this context current when used for context virtualization. bool MakeVirtuallyCurrent(GLContext* virtual_context, GLSurface* surface); @@ -274,6 +274,8 @@ // Returns the last real (non-virtual) GLContext made current. static GLContext* GetRealCurrent(); + virtual bool MakeCurrentImpl(GLSurface* surface) = 0; + virtual unsigned int CheckStickyGraphicsResetStatusImpl(); virtual void ResetExtensions() = 0; GLApi* gl_api() { return gl_api_wrapper_->api(); } @@ -285,8 +287,6 @@ void DestroyBackpressureFences(); #endif - void MarkVirtualContextLost() { virtual_context_lost_ = true; } - private: friend class base::RefCounted<GLContext>; @@ -321,7 +321,7 @@ std::unique_ptr<GLVersionInfo> version_info_; // This bit allows us to avoid virtual context state restoration in the case // where this underlying context becomes lost. https://crbug.com/1061442 - bool virtual_context_lost_ = false; + bool context_lost_ = false; #if defined(OS_APPLE) std::map<uint64_t, std::unique_ptr<GLFence>> backpressure_fences_;
diff --git a/ui/gl/gl_context_cgl.cc b/ui/gl/gl_context_cgl.cc index 28b9264..917e0c1 100644 --- a/ui/gl/gl_context_cgl.cc +++ b/ui/gl/gl_context_cgl.cc
@@ -210,7 +210,7 @@ return yuv_to_rgb_converter.get(); } -bool GLContextCGL::MakeCurrent(GLSurface* surface) { +bool GLContextCGL::MakeCurrentImpl(GLSurface* surface) { DCHECK(context_); if (!ForceGpuSwitchIfNeeded())
diff --git a/ui/gl/gl_context_cgl.h b/ui/gl/gl_context_cgl.h index 2738632..de70cd9 100644 --- a/ui/gl/gl_context_cgl.h +++ b/ui/gl/gl_context_cgl.h
@@ -26,7 +26,7 @@ // Implement GLContext. bool Initialize(GLSurface* compatible_surface, const GLContextAttribs& attribs) override; - bool MakeCurrent(GLSurface* surface) override; + bool MakeCurrentImpl(GLSurface* surface) override; void ReleaseCurrent(GLSurface* surface) override; bool IsCurrent(GLSurface* surface) override; void* GetHandle() override;
diff --git a/ui/gl/gl_context_egl.cc b/ui/gl/gl_context_egl.cc index 630a3c4c..52407ec 100644 --- a/ui/gl/gl_context_egl.cc +++ b/ui/gl/gl_context_egl.cc
@@ -346,7 +346,7 @@ } } -bool GLContextEGL::MakeCurrent(GLSurface* surface) { +bool GLContextEGL::MakeCurrentImpl(GLSurface* surface) { DCHECK(context_); if (lost_) return false; @@ -435,7 +435,7 @@ return context_; } -unsigned int GLContextEGL::CheckStickyGraphicsResetStatus() { +unsigned int GLContextEGL::CheckStickyGraphicsResetStatusImpl() { DCHECK(IsCurrent(nullptr)); DCHECK(g_current_gl_driver); const ExtensionsGL& ext = g_current_gl_driver->ext;
diff --git a/ui/gl/gl_context_egl.h b/ui/gl/gl_context_egl.h index ce18596b..0a95c783 100644 --- a/ui/gl/gl_context_egl.h +++ b/ui/gl/gl_context_egl.h
@@ -29,11 +29,11 @@ // Implement GLContext. bool Initialize(GLSurface* compatible_surface, const GLContextAttribs& attribs) override; - bool MakeCurrent(GLSurface* surface) override; + bool MakeCurrentImpl(GLSurface* surface) override; void ReleaseCurrent(GLSurface* surface) override; bool IsCurrent(GLSurface* surface) override; void* GetHandle() override; - unsigned int CheckStickyGraphicsResetStatus() override; + unsigned int CheckStickyGraphicsResetStatusImpl() override; void SetUnbindFboOnMakeCurrent() override; YUVToRGBConverter* GetYUVToRGBConverter( const gfx::ColorSpace& color_space) override;
diff --git a/ui/gl/gl_context_glx.cc b/ui/gl/gl_context_glx.cc index 59b3c058..8042e110 100644 --- a/ui/gl/gl_context_glx.cc +++ b/ui/gl/gl_context_glx.cc
@@ -212,7 +212,7 @@ } } -bool GLContextGLX::MakeCurrent(GLSurface* surface) { +bool GLContextGLX::MakeCurrentImpl(GLSurface* surface) { DCHECK(context_); if (IsCurrent(surface)) return true; @@ -278,7 +278,7 @@ return context_; } -unsigned int GLContextGLX::CheckStickyGraphicsResetStatus() { +unsigned int GLContextGLX::CheckStickyGraphicsResetStatusImpl() { DCHECK(IsCurrent(nullptr)); DCHECK(g_current_gl_driver); const ExtensionsGL& ext = g_current_gl_driver->ext;
diff --git a/ui/gl/gl_context_glx.h b/ui/gl/gl_context_glx.h index 47beb46..b6e69d2 100644 --- a/ui/gl/gl_context_glx.h +++ b/ui/gl/gl_context_glx.h
@@ -28,11 +28,11 @@ // Implement GLContext. bool Initialize(GLSurface* compatible_surface, const GLContextAttribs& attribs) override; - bool MakeCurrent(GLSurface* surface) override; + bool MakeCurrentImpl(GLSurface* surface) override; void ReleaseCurrent(GLSurface* surface) override; bool IsCurrent(GLSurface* surface) override; void* GetHandle() override; - unsigned int CheckStickyGraphicsResetStatus() override; + unsigned int CheckStickyGraphicsResetStatusImpl() override; protected: ~GLContextGLX() override;
diff --git a/ui/gl/gl_context_stub.cc b/ui/gl/gl_context_stub.cc index 1b2580874..56eca51 100644 --- a/ui/gl/gl_context_stub.cc +++ b/ui/gl/gl_context_stub.cc
@@ -22,7 +22,7 @@ return true; } -bool GLContextStub::MakeCurrent(GLSurface* surface) { +bool GLContextStub::MakeCurrentImpl(GLSurface* surface) { DCHECK(surface); BindGLApi(); SetCurrent(surface); @@ -50,7 +50,7 @@ return std::string("CHROMIUM"); } -unsigned int GLContextStub::CheckStickyGraphicsResetStatus() { +unsigned int GLContextStub::CheckStickyGraphicsResetStatusImpl() { DCHECK(IsCurrent(nullptr)); if ((graphics_reset_status_ == GL_NO_ERROR) && HasRobustness()) { graphics_reset_status_ = glGetGraphicsResetStatusARB();
diff --git a/ui/gl/gl_context_stub.h b/ui/gl/gl_context_stub.h index 46968d2..f3cfa8f7 100644 --- a/ui/gl/gl_context_stub.h +++ b/ui/gl/gl_context_stub.h
@@ -23,13 +23,13 @@ // Implement GLContext. bool Initialize(GLSurface* compatible_surface, const GLContextAttribs& attribs) override; - bool MakeCurrent(GLSurface* surface) override; + bool MakeCurrentImpl(GLSurface* surface) override; void ReleaseCurrent(GLSurface* surface) override; bool IsCurrent(GLSurface* surface) override; void* GetHandle() override; std::string GetGLVersion() override; std::string GetGLRenderer() override; - unsigned int CheckStickyGraphicsResetStatus() override; + unsigned int CheckStickyGraphicsResetStatusImpl() override; void SetUseStubApi(bool stub_api); void SetExtensionsString(const char* extensions);
diff --git a/ui/gl/gl_context_wgl.cc b/ui/gl/gl_context_wgl.cc index bf36be7..9e9633a 100644 --- a/ui/gl/gl_context_wgl.cc +++ b/ui/gl/gl_context_wgl.cc
@@ -91,7 +91,7 @@ } } -bool GLContextWGL::MakeCurrent(GLSurface* surface) { +bool GLContextWGL::MakeCurrentImpl(GLSurface* surface) { DCHECK(context_); if (IsCurrent(surface)) return true;
diff --git a/ui/gl/gl_context_wgl.h b/ui/gl/gl_context_wgl.h index be43a5d3..c792580 100644 --- a/ui/gl/gl_context_wgl.h +++ b/ui/gl/gl_context_wgl.h
@@ -24,7 +24,7 @@ // Implement GLContext. bool Initialize(GLSurface* compatible_surface, const GLContextAttribs& attribs) override; - bool MakeCurrent(GLSurface* surface) override; + bool MakeCurrentImpl(GLSurface* surface) override; void ReleaseCurrent(GLSurface* surface) override; bool IsCurrent(GLSurface* surface) override; void* GetHandle() override;
diff --git a/ui/gl/init/gl_factory_android.cc b/ui/gl/init/gl_factory_android.cc index f7e497b..1e3143b 100644 --- a/ui/gl/init/gl_factory_android.cc +++ b/ui/gl/init/gl_factory_android.cc
@@ -33,7 +33,7 @@ // Implement GLContext. bool Initialize(GLSurface* compatible_surface, const GLContextAttribs& attribs) override; - bool MakeCurrent(GLSurface* surface) override; + bool MakeCurrentImpl(GLSurface* surface) override; void ReleaseCurrent(GLSurface* surface) override {} bool IsCurrent(GLSurface* surface) override { return true; } void* GetHandle() override { return nullptr; } @@ -56,7 +56,7 @@ return true; } -bool GLNonOwnedContext::MakeCurrent(GLSurface* surface) { +bool GLNonOwnedContext::MakeCurrentImpl(GLSurface* surface) { BindGLApi(); SetCurrent(surface); InitializeDynamicBindings();
diff --git a/ui/webui/resources/cr_components/chromeos/cellular_setup/BUILD.gn b/ui/webui/resources/cr_components/chromeos/cellular_setup/BUILD.gn index 8a3ffd1..53290a1 100644 --- a/ui/webui/resources/cr_components/chromeos/cellular_setup/BUILD.gn +++ b/ui/webui/resources/cr_components/chromeos/cellular_setup/BUILD.gn
@@ -129,12 +129,14 @@ ":cellular_types.m", # ":cellular_setup.m", + # ":esim_flow_ui.m", ":final_page.m", ":mojo_interface_provider.m", ":provisioning_page.m", # ":psim_flow_ui.m", ":sim_detect_page.m", + ":subflow_behavior.m", # ":setup_selection_flow.m", ":webview_post_util.m", @@ -203,16 +205,21 @@ js_library("button_bar.m") { sources = [ "$root_gen_dir/ui/webui/resources/cr_components/chromeos/cellular_setup/button_bar.m.js" ] deps = [ + ":cellular_types.m", "//third_party/polymer/v3_0/components-chromium/polymer:polymer_bundled", "//ui/webui/resources/js:i18n_behavior.m", - ":cellular_types.m", ] extra_deps = [ ":button_bar_module" ] } js_library("cellular_types.m") { sources = [ "$root_gen_dir/ui/webui/resources/cr_components/chromeos/cellular_setup/cellular_types.m.js" ] - deps = [] + extra_deps = [ ":modulize" ] +} + +js_library("subflow_behavior.m") { + sources = [ "$root_gen_dir/ui/webui/resources/cr_components/chromeos/cellular_setup/subflow_behavior.m.js" ] + deps = [ ":cellular_types.m" ] extra_deps = [ ":modulize" ] } @@ -269,9 +276,10 @@ js_modulizer("modulize") { input_files = [ + "cellular_types.js", "mojo_interface_provider.js", + "subflow_behavior.js", "webview_post_util.js", - "cellular_types.js" ] namespace_rewrites = cr_components_chromeos_namespace_rewrites }
diff --git a/ui/webui/resources/cr_components/chromeos/cellular_setup/subflow_behavior.html b/ui/webui/resources/cr_components/chromeos/cellular_setup/subflow_behavior.html index 6ca2c63..9ae7b94 100644 --- a/ui/webui/resources/cr_components/chromeos/cellular_setup/subflow_behavior.html +++ b/ui/webui/resources/cr_components/chromeos/cellular_setup/subflow_behavior.html
@@ -1,4 +1,5 @@ <link rel="import" href="../../../html/cr.html"> <link rel="import" href="../../../html/i18n_behavior.html"> +<link rel="import" href="./cellular_types.js"> <script src="subflow_behavior.js"></script> \ No newline at end of file
diff --git a/ui/webui/resources/cr_components/chromeos/cellular_setup/subflow_behavior.js b/ui/webui/resources/cr_components/chromeos/cellular_setup/subflow_behavior.js index bbf48c8..8f73536 100644 --- a/ui/webui/resources/cr_components/chromeos/cellular_setup/subflow_behavior.js +++ b/ui/webui/resources/cr_components/chromeos/cellular_setup/subflow_behavior.js
@@ -2,13 +2,16 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +// #import {assertNotReached} from 'chrome://resources/js/assert.m.js'; +// #import {ButtonBarState} from "./cellular_types.m.js"; + /** * @fileoverview Polymer behavior for dealing with Cellular setup subflows. * It includes some methods and property shared between subflows. */ /** @polymerBehavior */ -const SubflowBehavior = { +/* #export */ const SubflowBehavior = { properties: { /**