diff --git a/.gn b/.gn index 0591fc5..ff4d8e14 100644 --- a/.gn +++ b/.gn
@@ -574,7 +574,6 @@ "//third_party/usrsctp/*", "//third_party/v4l-utils/*", "//third_party/valgrind/*", - "//third_party/visualmetrics/*", "//third_party/vulkan/*", "//third_party/vulkan-validation-layers/*",
diff --git a/DEPS b/DEPS index 9853fb9..b2289be 100644 --- a/DEPS +++ b/DEPS
@@ -133,11 +133,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': 'd40dc3f81b949c40f1119db22ad04501aec61278', + 'skia_revision': '2a2d732c396f6fae7a98898f953a5c8e967da43c', # 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': '4e74864a971dc6992f308d476b1b7b779085ae14', + 'v8_revision': 'db20ee17acd382196d84247293ae978235ea9ad7', # 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. @@ -149,7 +149,7 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling SwiftShader # and whatever else without interference from each other. - 'swiftshader_revision': '3364227fa0d88a3681e03237461cf0d2e4c9b39e', + 'swiftshader_revision': '6a1d92b526d4277be609e235f82ff4132245863f', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling PDFium # and whatever else without interference from each other. @@ -196,7 +196,7 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling catapult # and whatever else without interference from each other. - 'catapult_revision': 'eb73833a2935a42bb618d0557e3d45ae6624c9e9', + 'catapult_revision': 'a7314e4d231068b3ba40ea9b9a24641a7ecbc217', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling libFuzzer # and whatever else without interference from each other. @@ -248,11 +248,11 @@ # 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': 'b12e7338eeeaa06571839d1dfbc21126180090cc', + 'spv_tools_revision': 'b1ff15f2206214cecd6c43f15d59fa4b48e520bf', # 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_headers_revision': 'f25b91a61ea82af85a0d20d4dbf65f5970ea0aef', + 'spv_headers_revision': '3beb2a0373101562e1a1206edc33cf64fae87b54', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling feed # and whatever else without interference from each other. @@ -474,7 +474,7 @@ }, 'src/ios/third_party/motion_animator_objc/src': { - 'url': Var('chromium_git') + '/external/github.com/material-motion/motion-animator-objc.git' + '@' + 'd300ae8ac3131b5ffde017ee2c1747bcc126e647', + 'url': Var('chromium_git') + '/external/github.com/material-motion/motion-animator-objc.git' + '@' + '0581bc3dfacd34e40381e9cf45a15070b3868ba7', 'condition': 'checkout_ios', }, @@ -760,7 +760,7 @@ # Build tools for Chrome OS. Note: This depends on third_party/pyelftools. 'src/third_party/chromite': { - 'url': Var('chromium_git') + '/chromiumos/chromite.git' + '@' + '96053d06c97b5ae20ee13c591ec557a1f745e540', + 'url': Var('chromium_git') + '/chromiumos/chromite.git' + '@' + '6089762331e72dfcb4d38cfa49f9476b264c2903', 'condition': 'checkout_linux', }, @@ -1127,7 +1127,7 @@ }, 'src/third_party/perfetto': - Var('android_git') + '/platform/external/perfetto.git' + '@' + '28f71e89e3ee6c9f472a18f476199ee03c5d6c17', + Var('android_git') + '/platform/external/perfetto.git' + '@' + 'e96498a325006ca04dcaed92864b98fab62e5e78', 'src/third_party/perl': { 'url': Var('chromium_git') + '/chromium/deps/perl.git' + '@' + 'ac0d98b5cee6c024b0cffeb4f8f45b6fc5ccdb78', @@ -1273,9 +1273,6 @@ 'src/third_party/usrsctp/usrsctplib': Var('chromium_git') + '/external/github.com/sctplab/usrsctp' + '@' + '7a8bc9a90ca96634aa56ee712856d97f27d903f8', - 'src/third_party/visualmetrics/src': - Var('chromium_git') + '/external/github.com/WPO-Foundation/visualmetrics.git' + '@' + '1edde9d2fe203229c895b648fdec355917200ad6', - # Display server protocol for Linux. 'src/third_party/wayland/src': { 'url': Var('chromium_git') + '/external/anongit.freedesktop.org/git/wayland/wayland.git' + '@' + '1361da9cd5a719b32d978485a29920429a31ed25', @@ -1301,7 +1298,7 @@ Var('chromium_git') + '/external/khronosgroup/webgl.git' + '@' + 'a0f51b2e123f39c9ff12e621b0b47dd28dd64424', 'src/third_party/webrtc': - Var('webrtc_git') + '/src.git' + '@' + 'a5c0ba186149569832548bc3ea01494562fbcab7', + Var('webrtc_git') + '/src.git' + '@' + '4f779c6aec770277d45c9d0ebce40a8c2a680f18', 'src/third_party/xdg-utils': { 'url': Var('chromium_git') + '/chromium/deps/xdg-utils.git' + '@' + 'd80274d5869b17b8c9067a1022e4416ee7ed5e0d',
diff --git a/WATCHLISTS b/WATCHLISTS index f7e18de9..999bf18 100644 --- a/WATCHLISTS +++ b/WATCHLISTS
@@ -1988,7 +1988,7 @@ 'blink_media_queries': ['kenneth.christiansen@gmail.com', 'yoavweiss@chromium.org'], 'blink_mediastream': ['tommyw+watchlist@chromium.org'], - 'blink_modules': ['haraken@chromium.org'], + 'blink_modules': ['haraken-watch@chromium.org'], 'blink_navigator_content_utils': ['gyuyoung.kim@chromium.org'], 'blink_out_of_process_frames': ['dcheng@chromium.org', 'mlamouri+watch-blink@chromium.org'],
diff --git a/android_webview/browser/aw_contents.cc b/android_webview/browser/aw_contents.cc index 071d5b1..a2bcdeb 100644 --- a/android_webview/browser/aw_contents.cc +++ b/android_webview/browser/aw_contents.cc
@@ -43,6 +43,7 @@ #include "base/android/scoped_java_ref.h" #include "base/atomicops.h" #include "base/bind.h" +#include "base/bind_helpers.h" #include "base/callback.h" #include "base/command_line.h" #include "base/i18n/rtl.h" @@ -1461,7 +1462,7 @@ if (!callback) { // No callback requested. interstitial->GetMainFrame()->ExecuteJavaScriptForTests( - ConvertJavaStringToUTF16(env, script)); + ConvertJavaStringToUTF16(env, script), base::NullCallback()); return; }
diff --git a/android_webview/tools/system_webview_shell/test/data/webexposed/not-webview-exposed.txt b/android_webview/tools/system_webview_shell/test/data/webexposed/not-webview-exposed.txt index 057ae68..4d7e2ce 100644 --- a/android_webview/tools/system_webview_shell/test/data/webexposed/not-webview-exposed.txt +++ b/android_webview/tools/system_webview_shell/test/data/webexposed/not-webview-exposed.txt
@@ -109,26 +109,8 @@ # Background Fetch API is not enabled in Android webview, crbug.com/766077 interface BackgroundFetchManager - method fetch - method get - method getIds interface BackgroundFetchRecord - getter request - getter responseReady interface BackgroundFetchRegistration : EventTarget - getter downloadTotal - getter downloaded - getter failureReason - getter id - getter onprogress - getter recordsAvailable - getter result - getter uploadTotal - getter uploaded - method abort - method match - method matchAll - setter onprogress interface ServiceWorkerRegistration : EventTarget getter backgroundFetch
diff --git a/ash/multi_user/multi_user_window_manager.cc b/ash/multi_user/multi_user_window_manager.cc index 5856493..5459676 100644 --- a/ash/multi_user/multi_user_window_manager.cc +++ b/ash/multi_user/multi_user_window_manager.cc
@@ -184,6 +184,11 @@ if (GetWindowOwner(window) == account_id) return; + + // Transient window ownership is tracked by the parent window's ownership. + if (GetOwningWindowInTransientChain(window)) + return; + DCHECK(GetWindowOwner(window).empty()); std::unique_ptr<WindowEntry> window_entry_ptr = std::make_unique<WindowEntry>(account_id, std::move(window_id)); @@ -361,8 +366,9 @@ // Remove the transient child if the window itself is owned, or one of the // windows in its transient parents chain. if (!GetWindowOwner(window).empty() || - GetOwningWindowInTransientChain(window)) + GetOwningWindowInTransientChain(window)) { RemoveTransientOwnerRecursive(transient_window); + } } void MultiUserWindowManager::OnTabletModeStarted() {
diff --git a/base/message_loop/message_pump_kqueue.cc b/base/message_loop/message_pump_kqueue.cc index bc50186..fd6f72c 100644 --- a/base/message_loop/message_pump_kqueue.cc +++ b/base/message_loop/message_pump_kqueue.cc
@@ -254,7 +254,7 @@ DLOG(ERROR) << "Cannot use the same FdWatchController on two different FDs"; return false; } - controller->Reset(); + StopWatchingFileDescriptor(controller); std::vector<kevent64_s> events; @@ -304,12 +304,12 @@ event.ident = port; event.filter = EVFILT_MACHPORT; event.flags = EV_DELETE; + --event_count_; int rv = ChangeOneEvent(kqueue_, &event); if (rv < 0) { DPLOG(ERROR) << "kevent64"; return false; } - --event_count_; } return true; @@ -341,10 +341,7 @@ int rv = HANDLE_EINTR(kevent64(kqueue_.get(), events.data(), events.size(), nullptr, 0, 0, nullptr)); - if (rv < 0) { - DPLOG(ERROR) << "StopWatchingFileDescriptor kevent64"; - return false; - } + DPLOG_IF(ERROR, rv < 0) << "StopWatchingFileDescriptor kevent64"; // The keys for the IDMap aren't recorded anywhere (they're attached to the // kevent object in the kernel), so locate the entries by controller pointer. @@ -356,7 +353,8 @@ } event_count_ -= events.size(); - return true; + + return rv >= 0; } bool MessagePumpKqueue::DoInternalWork(Delegate::NextWorkInfo* next_work_info) { @@ -412,6 +410,7 @@ // watching. controller->Reset(); fd_controllers_.Remove(event->udata); + --event_count_; } if (event->filter == EVFILT_READ) {
diff --git a/base/metrics/field_trial_unittest.cc b/base/metrics/field_trial_unittest.cc index f8e619be..3003b4e 100644 --- a/base/metrics/field_trial_unittest.cc +++ b/base/metrics/field_trial_unittest.cc
@@ -1482,7 +1482,9 @@ LaunchOptions options; -#if defined(OS_MACOSX) && !defined(OS_IOS) +#if defined(OS_WIN) + options.handles_to_inherit.push_back(shm.region.GetPlatformHandle()); +#elif defined(OS_MACOSX) && !defined(OS_IOS) options.mach_ports_for_rendezvous.insert( std::make_pair('fldt', MachRendezvousPort{shm.region.GetPlatformHandle(), MACH_MSG_TYPE_COPY_SEND}));
diff --git a/base/profiler/native_stack_sampler_mac.cc b/base/profiler/native_stack_sampler_mac.cc index 0cb439126..25abe7ce 100644 --- a/base/profiler/native_stack_sampler_mac.cc +++ b/base/profiler/native_stack_sampler_mac.cc
@@ -4,7 +4,6 @@ #include "base/profiler/native_stack_sampler.h" -#include <dlfcn.h> #include <libkern/OSByteOrder.h> #include <libunwind.h> #include <mach-o/compact_unwind_encoding.h> @@ -15,6 +14,7 @@ #include <mach/thread_act.h> #include <mach/vm_map.h> #include <pthread.h> +#include <sys/ptrace.h> #include <sys/resource.h> #include <sys/syslimits.h> @@ -185,22 +185,12 @@ return true; } -const char* LibSystemKernelName() { - static char path[PATH_MAX]; - static char* name = nullptr; - if (name) - return name; - - Dl_info info; - dladdr(reinterpret_cast<void*>(_exit), &info); - strlcpy(path, info.dli_fname, PATH_MAX); - name = path; - -#if !defined(ADDRESS_SANITIZER) - DCHECK_EQ(std::string(name), - std::string("/usr/lib/system/libsystem_kernel.dylib")); -#endif - return name; +const ModuleCache::Module* GetLibSystemKernelModule(ModuleCache* module_cache) { + const ModuleCache::Module* module = + module_cache->GetModuleForAddress(reinterpret_cast<uintptr_t>(ptrace)); + DCHECK(module); + DCHECK_EQ(FilePath("libsystem_kernel.dylib"), module->GetDebugBasename()); + return module; } void GetSigtrampRange(uintptr_t* start, uintptr_t* end) { @@ -293,6 +283,9 @@ // The stack base address corresponding to |thread_handle_|. const void* const thread_stack_base_address_; + // Cached pointer to the libsystem_kernel module. + const ModuleCache::Module* const libsystem_kernel_module_; + // The address range of |_sigtramp|, the signal trampoline function. uintptr_t sigtramp_start_; uintptr_t sigtramp_end_; @@ -308,7 +301,8 @@ module_cache_(module_cache), test_delegate_(test_delegate), thread_stack_base_address_( - pthread_get_stackaddr_np(pthread_from_mach_thread_np(thread_port))) { + pthread_get_stackaddr_np(pthread_from_mach_thread_np(thread_port))), + libsystem_kernel_module_(GetLibSystemKernelModule(module_cache)) { GetSigtrampRange(&sigtramp_start_, &sigtramp_end_); // This class suspends threads, and those threads might be suspended in dyld. // Therefore, for all the system functions that might be linked in dynamically @@ -486,9 +480,7 @@ // function in libsystem_kernel. uint64_t& rsp = unwind_context.data[7]; uint64_t& rip = unwind_context.data[16]; - Dl_info info; - if (dladdr(reinterpret_cast<void*>(rip), &info) != 0 && - strcmp(info.dli_fname, LibSystemKernelName()) == 0) { + if (module_cache_->GetModuleForAddress(rip) == libsystem_kernel_module_) { rip = *reinterpret_cast<uint64_t*>(rsp); rsp += 8; WalkStackFromContext(&unwind_context, &frame_count, callback,
diff --git a/base/profiler/native_stack_sampler_win.cc b/base/profiler/native_stack_sampler_win.cc index c0e39f9..faca41c 100644 --- a/base/profiler/native_stack_sampler_win.cc +++ b/base/profiler/native_stack_sampler_win.cc
@@ -168,13 +168,33 @@ // fewer. stack.reserve(128); - Win32StackFrameUnwinder frame_unwinder(module_cache); + Win32StackFrameUnwinder frame_unwinder; while (ContextPC(context)) { - uintptr_t instruction_pointer = ContextPC(context); - const ModuleCache::Module* module = nullptr; - if (!frame_unwinder.TryUnwind(context, &module)) + const ModuleCache::Module* const module = + module_cache->GetModuleForAddress(ContextPC(context)); + + if (!module) { + // There's no loaded module containing the instruction pointer. This can + // be due to executing code that is not in a module. In particular, + // runtime-generated code associated with third-party injected DLLs + // typically is not in a module. It can also be due to the the module + // having been unloaded since we recorded the stack. In the latter case + // the function unwind information was part of the unloaded module, so + // it's not possible to unwind further. + // + // If a module was found, it's still theoretically possible for the + // detected module module to be different than the one that was loaded + // when the stack was copied (i.e. if the module was unloaded and a + // different module loaded in overlapping memory). This likely would cause + // a crash, but has not been observed in practice. break; - stack.emplace_back(instruction_pointer, module); + } + + // Record the current frame. + stack.emplace_back(ContextPC(context), module); + + if (!frame_unwinder.TryUnwind(context, module)) + break; } return stack;
diff --git a/base/profiler/win32_stack_frame_unwinder.cc b/base/profiler/win32_stack_frame_unwinder.cc index cfbcbd2..26086c5 100644 --- a/base/profiler/win32_stack_frame_unwinder.cc +++ b/base/profiler/win32_stack_frame_unwinder.cc
@@ -21,7 +21,7 @@ // functions. class Win32UnwindFunctions : public Win32StackFrameUnwinder::UnwindFunctions { public: - explicit Win32UnwindFunctions(ModuleCache* module_cache); + Win32UnwindFunctions(); ~Win32UnwindFunctions() override; PRUNTIME_FUNCTION LookupFunctionEntry(DWORD64 program_counter, @@ -32,17 +32,11 @@ PRUNTIME_FUNCTION runtime_function, CONTEXT* context) override; - const ModuleCache::Module* GetModuleForProgramCounter( - DWORD64 program_counter) override; - private: - ModuleCache* module_cache_; - DISALLOW_COPY_AND_ASSIGN(Win32UnwindFunctions); }; -Win32UnwindFunctions::Win32UnwindFunctions(ModuleCache* module_cache) - : module_cache_(module_cache) {} +Win32UnwindFunctions::Win32UnwindFunctions() {} Win32UnwindFunctions::~Win32UnwindFunctions() {} PRUNTIME_FUNCTION Win32UnwindFunctions::LookupFunctionEntry( @@ -72,52 +66,36 @@ #endif } -const ModuleCache::Module* Win32UnwindFunctions::GetModuleForProgramCounter( - DWORD64 program_counter) { - return module_cache_->GetModuleForAddress(program_counter); -} - } // namespace // Win32StackFrameUnwinder ---------------------------------------------------- -Win32StackFrameUnwinder::UnwindFunctions::~UnwindFunctions() {} -Win32StackFrameUnwinder::UnwindFunctions::UnwindFunctions() {} +Win32StackFrameUnwinder::UnwindFunctions::~UnwindFunctions() = default; +Win32StackFrameUnwinder::UnwindFunctions::UnwindFunctions() = default; -Win32StackFrameUnwinder::Win32StackFrameUnwinder(ModuleCache* module_cache) - : Win32StackFrameUnwinder( - std::make_unique<Win32UnwindFunctions>(module_cache)) {} +Win32StackFrameUnwinder::Win32StackFrameUnwinder() + : Win32StackFrameUnwinder(std::make_unique<Win32UnwindFunctions>()) {} Win32StackFrameUnwinder::~Win32StackFrameUnwinder() {} -bool Win32StackFrameUnwinder::TryUnwind(CONTEXT* context, - const ModuleCache::Module** module) { +bool Win32StackFrameUnwinder::TryUnwind( + CONTEXT* context, + // The module parameter, while not directly used, is still passed because it + // represents an implicit dependency for this function. Having the Module + // ensures that we have incremented the HMODULE reference count, which is + // critical to ensuring that the module is not unloaded during the + // unwinding. Otherwise the module could be unloaded between the + // LookupFunctionEntry and VirtualUnwind calls, resulting in crashes + // accessing unwind information from the unloaded module. + const ModuleCache::Module* module) { #ifdef _WIN64 - *module = nullptr; - - const ModuleCache::Module* frame_module = - unwind_functions_->GetModuleForProgramCounter(ContextPC(context)); - if (!frame_module) { - // There's no loaded module containing the instruction pointer. This can be - // due to executing code that is not in a module. In particular, - // runtime-generated code associated with third-party injected DLLs - // typically is not in a module. It can also be due to the the module having - // been unloaded since we recorded the stack. In the latter case the - // function unwind information was part of the unloaded module, so it's not - // possible to unwind further. - // - // If a module was found, it's still theoretically possible for the detected - // module module to be different than the one that was loaded when the stack - // was copied (i.e. if the module was unloaded and a different module loaded - // in overlapping memory). This likely would cause a crash, but has not been - // observed in practice. - return false; - } - + // Ensure we found a valid module for the program counter. + DCHECK(module); ULONG64 image_base; // Try to look up unwind metadata for the current function. PRUNTIME_FUNCTION runtime_function = unwind_functions_->LookupFunctionEntry(ContextPC(context), &image_base); + DCHECK_EQ(module->GetBaseAddress(), image_base); if (runtime_function) { unwind_functions_->VirtualUnwind(image_base, ContextPC(context), @@ -158,7 +136,6 @@ } } - *module = frame_module; return true; #else NOTREACHED();
diff --git a/base/profiler/win32_stack_frame_unwinder.h b/base/profiler/win32_stack_frame_unwinder.h index 0d1da36..94b186e 100644 --- a/base/profiler/win32_stack_frame_unwinder.h +++ b/base/profiler/win32_stack_frame_unwinder.h
@@ -56,11 +56,6 @@ PRUNTIME_FUNCTION runtime_function, CONTEXT* context) = 0; - // Returns the module containing |program_counter|. Can return null if the - // module has been unloaded. - virtual const ModuleCache::Module* GetModuleForProgramCounter( - DWORD64 program_counter) = 0; - protected: UnwindFunctions(); @@ -68,13 +63,13 @@ DISALLOW_COPY_AND_ASSIGN(UnwindFunctions); }; - explicit Win32StackFrameUnwinder(ModuleCache* module_cache); + explicit Win32StackFrameUnwinder(); ~Win32StackFrameUnwinder(); - // Attempts to unwind the frame represented by the stack and instruction - // pointers in |context|. If successful, updates |context| and provides the - // module associated with the frame in *|module|. - bool TryUnwind(CONTEXT* context, const ModuleCache::Module** module); + // Attempts to unwind the frame represented by |context|, where the + // instruction pointer is known to be in |module|. Updates |context| if + // successful. + bool TryUnwind(CONTEXT* context, const ModuleCache::Module* module); private: // This function is for internal and test purposes only.
diff --git a/base/profiler/win32_stack_frame_unwinder_unittest.cc b/base/profiler/win32_stack_frame_unwinder_unittest.cc index bc6d986..166b4a1 100644 --- a/base/profiler/win32_stack_frame_unwinder_unittest.cc +++ b/base/profiler/win32_stack_frame_unwinder_unittest.cc
@@ -17,16 +17,23 @@ namespace { +// The image base returned by LookupFunctionEntry starts at this value and is +// incremented by the same value with each call. +const uintptr_t kImageBaseIncrement = 1 << 20; + // Stub module for testing. class TestModule : public ModuleCache::Module { public: - uintptr_t GetBaseAddress() const override { return 0; } + TestModule(uintptr_t base_address) : base_address_(base_address) {} + + uintptr_t GetBaseAddress() const override { return base_address_; } std::string GetId() const override { return ""; } FilePath GetDebugBasename() const override { return FilePath(); } size_t GetSize() const override { return 0; } -}; -const TestModule valid_module; + private: + const uintptr_t base_address_; +}; class TestUnwindFunctions : public Win32StackFrameUnwinder::UnwindFunctions { public: @@ -38,22 +45,14 @@ DWORD64 program_counter, PRUNTIME_FUNCTION runtime_function, CONTEXT* context) override; - const ModuleCache::Module* GetModuleForProgramCounter( - DWORD64 program_counter) override; - - // Instructs GetModuleForProgramCounter to return null on the next call. - void SetUnloadedModule(); // These functions set whether the next frame will have a RUNTIME_FUNCTION. void SetHasRuntimeFunction(CONTEXT* context); void SetNoRuntimeFunction(CONTEXT* context); private: - enum { kImageBaseIncrement = 1 << 20 }; - static RUNTIME_FUNCTION* const kInvalidRuntimeFunction; - bool module_is_loaded_; DWORD64 expected_program_counter_; DWORD64 next_image_base_; DWORD64 expected_image_base_; @@ -67,12 +66,10 @@ reinterpret_cast<RUNTIME_FUNCTION*>(static_cast<uintptr_t>(-1)); TestUnwindFunctions::TestUnwindFunctions() - : module_is_loaded_(true), - expected_program_counter_(0), + : expected_program_counter_(0), next_image_base_(kImageBaseIncrement), expected_image_base_(0), - next_runtime_function_(kInvalidRuntimeFunction) { -} + next_runtime_function_(kInvalidRuntimeFunction) {} PRUNTIME_FUNCTION TestUnwindFunctions::LookupFunctionEntry( DWORD64 program_counter, @@ -101,17 +98,6 @@ EXPECT_EQ(&runtime_functions_.back(), runtime_function); } -const ModuleCache::Module* TestUnwindFunctions::GetModuleForProgramCounter( - DWORD64 program_counter) { - bool return_non_null_value = module_is_loaded_; - module_is_loaded_ = true; - return return_non_null_value ? &valid_module : nullptr; -} - -void TestUnwindFunctions::SetUnloadedModule() { - module_is_loaded_ = false; -} - void TestUnwindFunctions::SetHasRuntimeFunction(CONTEXT* context) { RUNTIME_FUNCTION runtime_function = {}; runtime_function.BeginAddress = 16; @@ -158,31 +144,18 @@ TEST_F(Win32StackFrameUnwinderTest, FramesWithUnwindInfo) { std::unique_ptr<Win32StackFrameUnwinder> unwinder = CreateUnwinder(); CONTEXT context = {0}; - const ModuleCache::Module* module = nullptr; + TestModule stub_module1(kImageBaseIncrement); unwind_functions_->SetHasRuntimeFunction(&context); - EXPECT_TRUE(unwinder->TryUnwind(&context, &module)); - EXPECT_NE(nullptr, module); + EXPECT_TRUE(unwinder->TryUnwind(&context, &stub_module1)); + TestModule stub_module2(kImageBaseIncrement * 2); unwind_functions_->SetHasRuntimeFunction(&context); - module = nullptr; - EXPECT_TRUE(unwinder->TryUnwind(&context, &module)); - EXPECT_NE(nullptr, module); + EXPECT_TRUE(unwinder->TryUnwind(&context, &stub_module2)); + TestModule stub_module3(kImageBaseIncrement * 3); unwind_functions_->SetHasRuntimeFunction(&context); - module = nullptr; - EXPECT_TRUE(unwinder->TryUnwind(&context, &module)); - EXPECT_NE(nullptr, module); -} - -// Checks that an instruction pointer in an unloaded module fails to unwind. -TEST_F(Win32StackFrameUnwinderTest, UnloadedModule) { - std::unique_ptr<Win32StackFrameUnwinder> unwinder = CreateUnwinder(); - CONTEXT context = {0}; - const ModuleCache::Module* module = nullptr; - - unwind_functions_->SetUnloadedModule(); - EXPECT_FALSE(unwinder->TryUnwind(&context, &module)); + EXPECT_TRUE(unwinder->TryUnwind(&context, &stub_module3)); } // Checks that the CONTEXT's stack pointer gets popped when the top frame has no @@ -190,26 +163,23 @@ TEST_F(Win32StackFrameUnwinderTest, FrameAtTopWithoutUnwindInfo) { std::unique_ptr<Win32StackFrameUnwinder> unwinder = CreateUnwinder(); CONTEXT context = {0}; - const ModuleCache::Module* module = nullptr; DWORD64 next_ip = 0x0123456789abcdef; DWORD64 original_rsp = reinterpret_cast<DWORD64>(&next_ip); context.Rsp = original_rsp; + TestModule stub_module1(kImageBaseIncrement); unwind_functions_->SetNoRuntimeFunction(&context); - EXPECT_TRUE(unwinder->TryUnwind(&context, &module)); + EXPECT_TRUE(unwinder->TryUnwind(&context, &stub_module1)); EXPECT_EQ(next_ip, context.Rip); EXPECT_EQ(original_rsp + 8, context.Rsp); - EXPECT_NE(nullptr, module); + TestModule stub_module2(kImageBaseIncrement * 2); unwind_functions_->SetHasRuntimeFunction(&context); - module = nullptr; - EXPECT_TRUE(unwinder->TryUnwind(&context, &module)); - EXPECT_NE(nullptr, module); + EXPECT_TRUE(unwinder->TryUnwind(&context, &stub_module2)); + TestModule stub_module3(kImageBaseIncrement * 3); unwind_functions_->SetHasRuntimeFunction(&context); - module = nullptr; - EXPECT_TRUE(unwinder->TryUnwind(&context, &module)); - EXPECT_NE(nullptr, module); + EXPECT_TRUE(unwinder->TryUnwind(&context, &stub_module3)); } // Checks that a frame below the top of the stack with missing unwind info @@ -219,13 +189,14 @@ // First stack, with a bad function below the top of the stack. std::unique_ptr<Win32StackFrameUnwinder> unwinder = CreateUnwinder(); CONTEXT context = {0}; - const ModuleCache::Module* module = nullptr; - unwind_functions_->SetHasRuntimeFunction(&context); - EXPECT_TRUE(unwinder->TryUnwind(&context, &module)); - EXPECT_NE(nullptr, module); + TestModule stub_module1(kImageBaseIncrement); + unwind_functions_->SetHasRuntimeFunction(&context); + EXPECT_TRUE(unwinder->TryUnwind(&context, &stub_module1)); + + TestModule stub_module2(kImageBaseIncrement * 2); unwind_functions_->SetNoRuntimeFunction(&context); - EXPECT_FALSE(unwinder->TryUnwind(&context, &module)); + EXPECT_FALSE(unwinder->TryUnwind(&context, &stub_module2)); } }
diff --git a/base/task/sequence_manager/moveable_auto_lock.h b/base/task/sequence_manager/moveable_auto_lock.h deleted file mode 100644 index a80d5f8..0000000 --- a/base/task/sequence_manager/moveable_auto_lock.h +++ /dev/null
@@ -1,41 +0,0 @@ -// Copyright 2018 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef BASE_TASK_SEQUENCE_MANAGER_MOVEABLE_AUTO_LOCK_H_ -#define BASE_TASK_SEQUENCE_MANAGER_MOVEABLE_AUTO_LOCK_H_ - -#include "base/synchronization/lock.h" - -namespace base { -namespace sequence_manager { - -class MoveableAutoLock { - public: - explicit MoveableAutoLock(Lock& lock) : lock_(lock), moved_(false) { - lock_.Acquire(); - } - - MoveableAutoLock(MoveableAutoLock&& other) noexcept - : lock_(other.lock_), moved_(other.moved_) { - lock_.AssertAcquired(); - other.moved_ = true; - } - - ~MoveableAutoLock() { - if (moved_) - return; - lock_.AssertAcquired(); - lock_.Release(); - } - - private: - Lock& lock_; - bool moved_; - DISALLOW_COPY_AND_ASSIGN(MoveableAutoLock); -}; - -} // namespace sequence_manager -} // namespace base - -#endif // BASE_TASK_SEQUENCE_MANAGER_MOVEABLE_AUTO_LOCK_H_
diff --git a/base/task/sequence_manager/sequence_manager_impl.h b/base/task/sequence_manager/sequence_manager_impl.h index 88e05d19..bee0a18 100644 --- a/base/task/sequence_manager/sequence_manager_impl.h +++ b/base/task/sequence_manager/sequence_manager_impl.h
@@ -28,7 +28,6 @@ #include "base/task/common/task_annotator.h" #include "base/task/sequence_manager/associated_thread_id.h" #include "base/task/sequence_manager/enqueue_order.h" -#include "base/task/sequence_manager/moveable_auto_lock.h" #include "base/task/sequence_manager/sequence_manager.h" #include "base/task/sequence_manager/task_queue_impl.h" #include "base/task/sequence_manager/task_queue_selector.h"
diff --git a/base/task/sequence_manager/task_queue.cc b/base/task/sequence_manager/task_queue.cc index 3886937..8564daf6 100644 --- a/base/task/sequence_manager/task_queue.cc +++ b/base/task/sequence_manager/task_queue.cc
@@ -120,7 +120,8 @@ ? impl_->sequence_manager()->associated_thread() : MakeRefCounted<internal::AssociatedThreadId>()), default_task_runner_(impl_ ? impl_->CreateTaskRunner(kTaskTypeNone) - : CreateNullTaskRunner()) {} + : CreateNullTaskRunner()), + name_(impl_ ? impl_->GetName() : "") {} TaskQueue::~TaskQueue() { // scoped_refptr guarantees us that this object isn't used. @@ -171,7 +172,10 @@ scoped_refptr<SingleThreadTaskRunner> TaskQueue::CreateTaskRunner( int task_type) { - Optional<MoveableAutoLock> lock(AcquireImplReadLockIfNeeded()); + Optional<AutoLock> lock; + // We only need to lock if we're not on the main thread. + if (IsOnMainThread()) + lock.emplace(impl_lock_); if (!impl_) return CreateNullTaskRunner(); return impl_->CreateTaskRunner(task_type); @@ -302,10 +306,7 @@ } const char* TaskQueue::GetName() const { - auto lock = AcquireImplReadLockIfNeeded(); - if (!impl_) - return ""; - return impl_->GetName(); + return name_; } void TaskQueue::SetObserver(Observer* observer) { @@ -327,12 +328,6 @@ return associated_thread_->IsBoundToCurrentThread(); } -Optional<MoveableAutoLock> TaskQueue::AcquireImplReadLockIfNeeded() const { - if (IsOnMainThread()) - return nullopt; - return MoveableAutoLock(impl_lock_); -} - std::unique_ptr<internal::TaskQueueImpl> TaskQueue::TakeTaskQueueImpl() { DCHECK(impl_); return std::move(impl_);
diff --git a/base/task/sequence_manager/task_queue.h b/base/task/sequence_manager/task_queue.h index f046f4d..a0a8552 100644 --- a/base/task/sequence_manager/task_queue.h +++ b/base/task/sequence_manager/task_queue.h
@@ -14,7 +14,6 @@ #include "base/single_thread_task_runner.h" #include "base/synchronization/lock.h" #include "base/task/sequence_manager/lazy_now.h" -#include "base/task/sequence_manager/moveable_auto_lock.h" #include "base/task/sequence_manager/tasks.h" #include "base/threading/platform_thread.h" #include "base/time/time.h" @@ -339,8 +338,6 @@ bool IsOnMainThread() const; - Optional<MoveableAutoLock> AcquireImplReadLockIfNeeded() const; - // TaskQueue has ownership of an underlying implementation but in certain // cases (e.g. detached frames) their lifetime may diverge. // This method should be used to take away the impl for graceful shutdown. @@ -362,6 +359,7 @@ int enabled_voter_count_ = 0; int voter_count_ = 0; + const char* name_; DISALLOW_COPY_AND_ASSIGN(TaskQueue); };
diff --git a/base/threading/thread_restrictions.h b/base/threading/thread_restrictions.h index d1b00361..25f35a53 100644 --- a/base/threading/thread_restrictions.h +++ b/base/threading/thread_restrictions.h
@@ -170,6 +170,9 @@ namespace leveldb { class LevelDBMojoProxy; } +namespace leveldb_env { +class DBTracker; +} namespace media { class AudioInputDevice; class AudioOutputDevice; @@ -384,6 +387,7 @@ friend class functions::ExecScriptScopedAllowBaseSyncPrimitives; friend class internal::TaskTracker; friend class leveldb::LevelDBMojoProxy; + friend class leveldb_env::DBTracker; friend class media::BlockingUrlProtocol; friend class mojo::core::ScopedIPCSupport; friend class net::MultiThreadedCertVerifierScopedAllowBaseSyncPrimitives;
diff --git a/build/android/gyp/create_app_bundle.py b/build/android/gyp/create_app_bundle.py index a1f2eb6e..b7b5106f 100755 --- a/build/android/gyp/create_app_bundle.py +++ b/build/android/gyp/create_app_bundle.py
@@ -179,7 +179,8 @@ # "uncompressNativeLibraries". uncompressed_globs = ['lib/*/crazy.*'] uncompressed_globs.extend('assets/' + x for x in uncompressed_assets) - uncompressed_globs.extend('*.' + ext for ext in _UNCOMPRESSED_FILE_EXTS) + # NOTE: Use '**' instead of '*' to work through directories! + uncompressed_globs.extend('**.' + ext for ext in _UNCOMPRESSED_FILE_EXTS) data = { 'optimizations': {
diff --git a/build/fuchsia/linux.sdk.sha1 b/build/fuchsia/linux.sdk.sha1 index b27180b..5425ea66 100644 --- a/build/fuchsia/linux.sdk.sha1 +++ b/build/fuchsia/linux.sdk.sha1
@@ -1 +1 @@ -899835ec9999d050acd4e023fd0d2d0d2cae3cfe \ No newline at end of file +ddb838f4b90dfdbbfe82583cd86828fa60a7d6e1 \ No newline at end of file
diff --git a/build/fuchsia/mac.sdk.sha1 b/build/fuchsia/mac.sdk.sha1 index 0190d9f..084736163 100644 --- a/build/fuchsia/mac.sdk.sha1 +++ b/build/fuchsia/mac.sdk.sha1
@@ -1 +1 @@ -0900e4c1124c1a676543334b56671bac962641c1 \ No newline at end of file +9d601644050c457a28aa9c6484f6fb7481b0d63e \ No newline at end of file
diff --git a/build/install-build-deps.sh b/build/install-build-deps.sh index 78033f0..b73cd49 100755 --- a/build/install-build-deps.sh +++ b/build/install-build-deps.sh
@@ -140,6 +140,7 @@ libbz2-dev libcairo2-dev libcap-dev + libc6-dev libcups2-dev libcurl4-gnutls-dev libdrm-dev @@ -620,40 +621,34 @@ fi sudo apt-get update -# We initially run "apt-get" with the --reinstall option and parse its output. -# This way, we can find all the packages that need to be newly installed -# without accidentally promoting any packages from "auto" to "manual". -# We then re-run "apt-get" with just the list of missing packages. echo "Finding missing packages..." # Intentionally leaving $packages unquoted so it's more readable. echo "Packages required: " $packages echo -new_list_cmd="sudo apt-get install --reinstall $(echo $packages)" -if new_list="$(yes n | LANGUAGE=en LANG=C $new_list_cmd)"; then - # We probably never hit this following line. - echo "No missing packages, and the packages are up to date." -elif [ $? -eq 1 ]; then - # We expect apt-get to have exit status of 1. - # This indicates that we cancelled the install with "yes n|". - new_list=$(echo "$new_list" | - sed -e '1,/The following NEW packages will be installed:/d;s/^ //;t;d') - new_list=$(echo "$new_list" | sed 's/ *$//') - if [ -z "$new_list" ] ; then +query_cmd="apt-get --just-print install $(echo $packages)" +if cmd_output="$(LANGUAGE=en LANG=C $query_cmd)"; then + new_list=$(echo "$cmd_output" | + sed -e '1,/The following NEW packages will be installed:/d;s/^ //;t;d' | + sed 's/ *$//') + upgrade_list=$(echo "$cmd_output" | + sed -e '1,/The following packages will be upgraded:/d;s/^ //;t;d' | + sed 's/ *$//') + if [ -z "$new_list" ] && [ -z "$upgrade_list" ]; then echo "No missing packages, and the packages are up to date." else - echo "Installing missing packages: $new_list." - sudo apt-get install ${do_quietly-} ${new_list} + echo "Installing and upgrading packages: $new_list $upgrade_list." + sudo apt-get install ${do_quietly-} ${new_list} ${upgrade_list} fi echo else # An apt-get exit status of 100 indicates that a real error has occurred. - # I am intentionally leaving out the '"'s around new_list_cmd, + # I am intentionally leaving out the '"'s around query_cmd, # as this makes it easier to cut and paste the output - echo "The following command failed: " ${new_list_cmd} + echo "The following command failed: " ${query_cmd} echo - echo "It produces the following output:" - yes n | $new_list_cmd || true + echo "It produced the following output:" + echo "$cmd_output" echo echo "You will have to install the above packages yourself." echo
diff --git a/build/sanitizers/asan_suppressions.cc b/build/sanitizers/asan_suppressions.cc index df94bc89..f3b9459d 100644 --- a/build/sanitizers/asan_suppressions.cc +++ b/build/sanitizers/asan_suppressions.cc
@@ -10,14 +10,14 @@ // Please make sure the code below declares a single string variable // kASanDefaultSuppressions which contains ASan suppressions delimited by -// newlines. +// newlines. Entries should look, for example, like: +// +// // http://crbug.com/178677 +// "interceptor_via_lib:libsqlite3.so\n" char kASanDefaultSuppressions[] = -// http://crbug.com/178677 -"interceptor_via_lib:libsqlite3.so\n" -// PLEASE READ ABOVE BEFORE ADDING NEW SUPPRESSIONS. - -// End of suppressions. -; // Please keep this semicolon. + // End of suppressions. + // PLEASE READ ABOVE BEFORE ADDING NEW SUPPRESSIONS. + ""; // Please keep this semicolon. #endif // ADDRESS_SANITIZER
diff --git a/chrome/android/features/autofill_assistant/BUILD.gn b/chrome/android/features/autofill_assistant/BUILD.gn index e401709..d4c02f3 100644 --- a/chrome/android/features/autofill_assistant/BUILD.gn +++ b/chrome/android/features/autofill_assistant/BUILD.gn
@@ -22,6 +22,7 @@ "//ui/android:ui_java", ] java_files = [ + "java/src/org/chromium/chrome/browser/autofill_assistant/AbstractListObserver.java", "java/src/org/chromium/chrome/browser/autofill_assistant/AssistantBottomBarCoordinator.java", "java/src/org/chromium/chrome/browser/autofill_assistant/AssistantCoordinator.java", "java/src/org/chromium/chrome/browser/autofill_assistant/AssistantKeyboardCoordinator.java",
diff --git a/chrome/android/features/autofill_assistant/java/res/drawable/autofill_assistant_bottombar_spacer.xml b/chrome/android/features/autofill_assistant/java/res/drawable/autofill_assistant_bottombar_spacer.xml deleted file mode 100644 index 6636b9ab..0000000 --- a/chrome/android/features/autofill_assistant/java/res/drawable/autofill_assistant_bottombar_spacer.xml +++ /dev/null
@@ -1,9 +0,0 @@ -<?xml version="1.0" encoding="utf-8"?> -<!-- Copyright 2019 The Chromium Authors. All rights reserved. - Use of this source code is governed by a BSD-style license that can be - found in the LICENSE file. --> -<shape xmlns:android="http://schemas.android.com/apk/res/android"> - <size - android:height="@dimen/autofill_assistant_bottombar_vertical_spacing" - android:width="0dp"/> -</shape> \ No newline at end of file
diff --git a/chrome/android/features/autofill_assistant/java/res/layout/autofill_assistant_sheet.xml b/chrome/android/features/autofill_assistant/java/res/layout/autofill_assistant_sheet.xml index 627b370..84014975 100644 --- a/chrome/android/features/autofill_assistant/java/res/layout/autofill_assistant_sheet.xml +++ b/chrome/android/features/autofill_assistant/java/res/layout/autofill_assistant_sheet.xml
@@ -53,13 +53,10 @@ android:id="@+id/autofill_assistant_bottombar_container" android:layout_width="match_parent" android:layout_height="wrap_content" - android:paddingTop="@dimen/autofill_assistant_bottombar_vertical_spacing" android:paddingBottom="@dimen/autofill_assistant_bottombar_vertical_spacing" android:orientation="vertical" android:gravity="center" - android:animateLayoutChanges="true" - android:showDividers="middle" - android:divider="@drawable/autofill_assistant_bottombar_spacer" > + android:animateLayoutChanges="true" > </LinearLayout> </LinearLayout>
diff --git a/chrome/android/features/autofill_assistant/java/src/org/chromium/chrome/browser/autofill_assistant/AbstractListObserver.java b/chrome/android/features/autofill_assistant/java/src/org/chromium/chrome/browser/autofill_assistant/AbstractListObserver.java new file mode 100644 index 0000000..0c82025 --- /dev/null +++ b/chrome/android/features/autofill_assistant/java/src/org/chromium/chrome/browser/autofill_assistant/AbstractListObserver.java
@@ -0,0 +1,35 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package org.chromium.chrome.browser.autofill_assistant; + +import android.support.annotation.Nullable; + +import org.chromium.ui.modelutil.ListObservable; +import org.chromium.ui.modelutil.ListObservable.ListObserver; + +/** + * A {@link ListObserver} that calls {@link #onDataSetChanged} when any item of the list is + * inserted, removed or update. + * @param <T> the type of the observed list. + */ +public abstract class AbstractListObserver<T> implements ListObserver<T> { + @Override + public void onItemRangeInserted(ListObservable source, int index, int count) { + onDataSetChanged(); + } + + @Override + public void onItemRangeRemoved(ListObservable source, int index, int count) { + onDataSetChanged(); + } + + @Override + public void onItemRangeChanged( + ListObservable<T> source, int index, int count, @Nullable T payload) { + onDataSetChanged(); + } + + public abstract void onDataSetChanged(); +}
diff --git a/chrome/android/features/autofill_assistant/java/src/org/chromium/chrome/browser/autofill_assistant/AssistantBottomBarCoordinator.java b/chrome/android/features/autofill_assistant/java/src/org/chromium/chrome/browser/autofill_assistant/AssistantBottomBarCoordinator.java index 241e93e..b459842 100644 --- a/chrome/android/features/autofill_assistant/java/src/org/chromium/chrome/browser/autofill_assistant/AssistantBottomBarCoordinator.java +++ b/chrome/android/features/autofill_assistant/java/src/org/chromium/chrome/browser/autofill_assistant/AssistantBottomBarCoordinator.java
@@ -16,10 +16,12 @@ import org.chromium.base.VisibleForTesting; import org.chromium.chrome.autofill_assistant.R; import org.chromium.chrome.browser.autofill_assistant.carousel.AssistantCarouselCoordinator; +import org.chromium.chrome.browser.autofill_assistant.carousel.AssistantChip; import org.chromium.chrome.browser.autofill_assistant.details.AssistantDetailsCoordinator; import org.chromium.chrome.browser.autofill_assistant.header.AssistantHeaderCoordinator; import org.chromium.chrome.browser.autofill_assistant.infobox.AssistantInfoBoxCoordinator; import org.chromium.chrome.browser.autofill_assistant.payment.AssistantPaymentRequestCoordinator; +import org.chromium.ui.modelutil.ListModel; /** * Coordinator responsible for the Autofill Assistant bottom bar. This coordinator allows to enable @@ -78,6 +80,20 @@ mBottomBarContainerView.addView(mSuggestionsCoordinator.getView()); mBottomBarContainerView.addView(mActionsCoordinator.getView()); + // Set children top margins to have a spacing between them. For the carousels, we set their + // margin only when they are not empty given that they are always shown, even if empty. We + // do not hide them because there is an incompatibility bug between the animateLayoutChanges + // attribute set on mBottomBarContainerView and the animations ran by the carousels + // RecyclerView. + int childSpacing = context.getResources().getDimensionPixelSize( + R.dimen.autofill_assistant_bottombar_vertical_spacing); + setChildMarginTop(mDetailsCoordinator.getView(), childSpacing); + setChildMarginTop(mPaymentRequestCoordinator.getView(), childSpacing); + setCarouselMarginTop(mSuggestionsCoordinator.getView(), + model.getSuggestionsModel().getChipsModel(), childSpacing); + setCarouselMarginTop(mActionsCoordinator.getView(), model.getActionsModel().getChipsModel(), + childSpacing); + // We set the horizontal margins of the details and payment request. We don't set a padding // to the container as we want the carousels children to be scrolled at the limit of the // screen. @@ -125,6 +141,26 @@ } } + private void setChildMarginTop(View child, int marginTop) { + LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) child.getLayoutParams(); + params.topMargin = marginTop; + child.setLayoutParams(params); + } + + /** + * Observe {@code model} such that we set the topMargin of {@code carouselView} to {@code + * marginTop} when {@code model} is not empty and set it to 0 otherwise. + */ + private void setCarouselMarginTop( + View carouselView, ListModel<AssistantChip> chipsModel, int marginTop) { + chipsModel.addObserver(new AbstractListObserver<Void>() { + @Override + public void onDataSetChanged() { + setChildMarginTop(carouselView, chipsModel.size() > 0 ? marginTop : 0); + } + }); + } + @VisibleForTesting public AssistantCarouselCoordinator getSuggestionsCoordinator() { return mSuggestionsCoordinator;
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 fc864cf..b2ba432 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
@@ -257,8 +257,9 @@ private void setActions(List<AssistantChip> chips) { AssistantCarouselModel model = getModel().getActionsModel(); model.set(ALIGNMENT, - chips.size() == 1 ? AssistantCarouselModel.Alignment.CENTER - : AssistantCarouselModel.Alignment.END); + (chips.size() == 1 && chips.get(0).getType() != Type.BUTTON_FILLED_BLUE) + ? AssistantCarouselModel.Alignment.CENTER + : AssistantCarouselModel.Alignment.END); setChips(model, chips); }
diff --git a/chrome/android/features/autofill_assistant/java/src/org/chromium/chrome/browser/autofill_assistant/carousel/AssistantCarouselCoordinator.java b/chrome/android/features/autofill_assistant/java/src/org/chromium/chrome/browser/autofill_assistant/carousel/AssistantCarouselCoordinator.java index 6a792ed..2daff79 100644 --- a/chrome/android/features/autofill_assistant/java/src/org/chromium/chrome/browser/autofill_assistant/carousel/AssistantCarouselCoordinator.java +++ b/chrome/android/features/autofill_assistant/java/src/org/chromium/chrome/browser/autofill_assistant/carousel/AssistantCarouselCoordinator.java
@@ -6,7 +6,6 @@ import android.content.Context; import android.graphics.Rect; -import android.support.annotation.Nullable; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.RecyclerView.ViewHolder; @@ -14,8 +13,7 @@ import android.view.View; import org.chromium.chrome.autofill_assistant.R; -import org.chromium.ui.modelutil.ListObservable; -import org.chromium.ui.modelutil.ListObservable.ListObserver; +import org.chromium.chrome.browser.autofill_assistant.AbstractListObserver; import org.chromium.ui.modelutil.RecyclerViewAdapter; import org.chromium.ui.modelutil.SimpleRecyclerViewMcp; @@ -42,9 +40,6 @@ AssistantChipViewHolder::getViewType, AssistantChipViewHolder::bind), AssistantChipViewHolder::create)); - // Carousel is initially hidden. - setVisible(false); - // Listen for changes on REVERSE_LAYOUT. model.addObserver((source, propertyKey) -> { if (AssistantCarouselModel.ALIGNMENT == propertyKey) { @@ -68,25 +63,10 @@ }); // Listen for changes on chips, and set visibility accordingly. - model.getChipsModel().addObserver(new ListObserver<Void>() { + model.getChipsModel().addObserver(new AbstractListObserver<Void>() { @Override - public void onItemRangeInserted(ListObservable source, int index, int count) { - onChipsChanged(); - } - - @Override - public void onItemRangeRemoved(ListObservable source, int index, int count) { - onChipsChanged(); - } - - @Override - public void onItemRangeChanged( - ListObservable<Void> source, int index, int count, @Nullable Void payload) { - onChipsChanged(); - } - - private void onChipsChanged() { - setVisible(model.getChipsModel().size() > 0); + public void onDataSetChanged() { + mView.invalidateItemDecorations(); } }); } @@ -98,16 +78,6 @@ return mView; } - /** - * Show or hide this carousel within its parent. - */ - private void setVisible(boolean visible) { - int visibility = visible ? View.VISIBLE : View.GONE; - if (mView.getVisibility() != visibility) { - mView.setVisibility(visibility); - } - } - private class SpaceItemDecoration extends RecyclerView.ItemDecoration { private final int mInnerSpacePx; private final int mOuterSpacePx;
diff --git a/chrome/android/features/autofill_assistant/java/src/org/chromium/chrome/browser/autofill_assistant/overlay/TouchEventFilterView.java b/chrome/android/features/autofill_assistant/java/src/org/chromium/chrome/browser/autofill_assistant/overlay/TouchEventFilterView.java index 9f59b47..b38d9b5a 100644 --- a/chrome/android/features/autofill_assistant/java/src/org/chromium/chrome/browser/autofill_assistant/overlay/TouchEventFilterView.java +++ b/chrome/android/features/autofill_assistant/java/src/org/chromium/chrome/browser/autofill_assistant/overlay/TouchEventFilterView.java
@@ -4,6 +4,8 @@ package org.chromium.chrome.browser.autofill_assistant.overlay; +import android.animation.Animator; +import android.animation.AnimatorListenerAdapter; import android.animation.TimeInterpolator; import android.animation.ValueAnimator; import android.content.Context; @@ -16,6 +18,7 @@ import android.support.annotation.IntDef; import android.support.annotation.Nullable; import android.util.AttributeSet; +import android.util.DisplayMetrics; import android.util.TypedValue; import android.view.GestureDetector; import android.view.GestureDetector.SimpleOnGestureListener; @@ -35,7 +38,6 @@ import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.util.ArrayList; -import java.util.Collections; import java.util.Iterator; import java.util.List; @@ -64,7 +66,13 @@ private static final int BACKGROUND_ALPHA = 0x42; /** Width of the line drawn around the boxes. */ - private static final int BOX_STROKE_WIDTH = 3; + private static final int BOX_STROKE_WIDTH_DP = 2; + + /** Padding added to boxes. */ + private static final int BOX_PADDING_DP = 2; + + /** Box corner. */ + private static final int BOX_CORNER_DP = 8; /** * Complain after there's been {@link TAP_TRACKING_COUNT} taps within @@ -94,14 +102,14 @@ private View mCompositorView; private final Paint mBackground; - private final Paint mClear; private final Paint mBoxStroke; + private final Paint mBoxClear; private final Paint mBoxFill; @AssistantOverlayState private int mCurrentState = AssistantOverlayState.HIDDEN; - private List<RectF> mTouchableArea = Collections.emptyList(); + private final List<Box> mTouchableArea = new ArrayList<>(); /** Padding added between the element area and the grayed-out area. */ private final float mPaddingPx; @@ -180,18 +188,6 @@ /** Current bottom margin of this view. */ private int mMarginBottom; - /** - * Currently running animator for boxes fade in and out, either {@link #mFadeOutBoxesAnimator} - * or {@link #mFadeOutBoxesAnimator}. - */ - private ValueAnimator mCurrentBoxesAnimator; - - /** Animator created by {@link #fadeInBoxes}. Fades in box content. */ - private ValueAnimator mFadeInBoxesAnimator; - - /** Animator created by {@link #fadeOutBoxes}. Fades out box content. */ - private ValueAnimator mFadeOutBoxesAnimator; - public TouchEventFilterView(Context context) { this(context, null, 0); } @@ -202,16 +198,20 @@ public TouchEventFilterView(Context context, AttributeSet attributeSet, int defStyle) { super(context, attributeSet, defStyle); - mBackground = new Paint(Paint.ANTI_ALIAS_FLAG); + + DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics(); + + mBackground = new Paint(); mBackground.setColor(Color.BLACK); mBackground.setAlpha(BACKGROUND_ALPHA); mBackground.setStyle(Paint.Style.FILL); - mClear = new Paint(); - mClear.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR)); - mClear.setStyle(Paint.Style.FILL); + mBoxClear = new Paint(); + mBoxClear.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR)); + mBoxClear.setColor(Color.BLACK); + mBoxClear.setStyle(Paint.Style.FILL); - mBoxFill = new Paint(Paint.ANTI_ALIAS_FLAG); + mBoxFill = new Paint(); mBoxFill.setColor(Color.BLACK); mBoxFill.setStyle(Paint.Style.FILL); @@ -219,14 +219,14 @@ mBoxStroke.setColor( ApiCompatibilityUtils.getColor(context.getResources(), R.color.modern_blue_600)); mBoxStroke.setStyle(Paint.Style.STROKE); - mBoxStroke.setStrokeWidth(BOX_STROKE_WIDTH); + mBoxStroke.setStrokeWidth(TypedValue.applyDimension( + TypedValue.COMPLEX_UNIT_DIP, BOX_STROKE_WIDTH_DP, displayMetrics)); mBoxStroke.setStrokeCap(Paint.Cap.ROUND); mPaddingPx = TypedValue.applyDimension( - TypedValue.COMPLEX_UNIT_DIP, 2, context.getResources().getDisplayMetrics()); + TypedValue.COMPLEX_UNIT_DIP, BOX_PADDING_DP, displayMetrics); mCornerPx = TypedValue.applyDimension( - TypedValue.COMPLEX_UNIT_DIP, 8, context.getResources().getDisplayMetrics()); - // TODO(crbug.com/806868): Add support for XML attributes configuration. + TypedValue.COMPLEX_UNIT_DIP, BOX_CORNER_DP, displayMetrics); mTapDetector = new GestureDetector(context, new SimpleOnGestureListener() { @Override @@ -308,10 +308,14 @@ setVisibility(View.VISIBLE); } else if (mCurrentState == AssistantOverlayState.FULL && newState == AssistantOverlayState.PARTIAL) { - if (!mTouchableArea.isEmpty()) fadeOutBoxes(); + for (Box box : mTouchableArea) { + box.fadeOut(); + } } else if (mCurrentState == AssistantOverlayState.PARTIAL && newState == AssistantOverlayState.FULL) { - if (!mTouchableArea.isEmpty()) fadeInBoxes(); + for (Box box : mTouchableArea) { + box.fadeIn(); + } } mCurrentState = newState; @@ -327,18 +331,43 @@ * Set the touchable area. This only applies if current state is AssistantOverlayState.PARTIAL. */ public void setTouchableArea(List<RectF> touchableArea) { - if (mCurrentState == AssistantOverlayState.PARTIAL) { - invalidate(); - boolean wasEmpty = mTouchableArea.isEmpty(); - boolean isEmpty = touchableArea.isEmpty(); - if (wasEmpty && !isEmpty) { - fadeOutBoxes(); - } else if (!wasEmpty && isEmpty) { - fadeInBoxes(); + boolean animate = mCurrentState == AssistantOverlayState.PARTIAL; + + // Add or update boxes for each rectangle in the area. + for (int i = 0; i < touchableArea.size(); i++) { + while (i >= mTouchableArea.size()) { + mTouchableArea.add(new Box()); + } + Box box = mTouchableArea.get(i); + RectF rect = touchableArea.get(i); + boolean isNew = box.mRect.isEmpty() && !rect.isEmpty(); + box.mRect.set(rect); + if (animate && isNew) { + // This box just appeared, fade it out of the background. + box.fadeOut(); + } + // Not fading in here as the element has likely already disappeared; the fade in could + // end up on an unrelated portion of the page. + } + + // Remove rectangles now gone from the area. Fading in works here, because the removal is + // due to a script decision; the elements are still there. + for (Iterator<Box> iter = mTouchableArea.listIterator(touchableArea.size()); + iter.hasNext();) { + Box box = iter.next(); + if (!box.mRect.isEmpty()) { + // Fade in rectangle. + box.fadeIn(); + box.mRect.setEmpty(); + } else if (box.mAnimationType == AnimationType.NONE) { + // We're done fading in. Cleanup. + iter.remove(); } } - mTouchableArea = touchableArea; + clearOffsets(); + + if (mCurrentState == AssistantOverlayState.PARTIAL) invalidate(); } private void clearOffsets() { @@ -541,18 +570,20 @@ } canvas.drawPaint(mBackground); - if (mCurrentState != AssistantOverlayState.PARTIAL) { - return; - } - int yTop = getVisualViewportTop(); int height = yBottom - yTop; - float boxesAlpha = (mCurrentBoxesAnimator != null && mCurrentBoxesAnimator.isRunning()) - ? ((float) mCurrentBoxesAnimator.getAnimatedValue()) - : 0f; - mBoxStroke.setAlpha((int) (0xff * (1.0 - boxesAlpha))); - mBoxFill.setAlpha((int) (BACKGROUND_ALPHA * boxesAlpha)); - for (RectF rect : mTouchableArea) { + for (Box box : mTouchableArea) { + RectF rect = box.getRectToDraw(); + if (rect.isEmpty() + || (mCurrentState != AssistantOverlayState.PARTIAL + && box.mAnimationType != AnimationType.FADE_IN)) { + continue; + } + // At visibility=1, stroke is fully opaque and box fill is fully transparent + mBoxStroke.setAlpha((int) (0xff * box.getVisibility())); + int fillAlpha = (int) (BACKGROUND_ALPHA * (1f - box.getVisibility())); + mBoxFill.setAlpha(fillAlpha); + mDrawRect.left = rect.left * width - mPaddingPx; mDrawRect.top = yTop + rect.top * height - mPaddingPx - mBrowserScrollOffsetY - mOffsetY; @@ -562,16 +593,12 @@ if (mDrawRect.left <= 0 && mDrawRect.right >= width) { // Rounded corners look strange in the case where the rectangle takes exactly the // width of the screen. - canvas.drawRect(mDrawRect, mClear); - if (boxesAlpha > 0f) { - canvas.drawRect(mDrawRect, mBoxFill); - } + canvas.drawRect(mDrawRect, mBoxClear); + if (fillAlpha > 0) canvas.drawRect(mDrawRect, mBoxFill); canvas.drawRect(mDrawRect, mBoxStroke); } else { - canvas.drawRoundRect(mDrawRect, mCornerPx, mCornerPx, mClear); - if (boxesAlpha > 0f) { - canvas.drawRoundRect(mDrawRect, mCornerPx, mCornerPx, mBoxFill); - } + canvas.drawRoundRect(mDrawRect, mCornerPx, mCornerPx, mBoxClear); + if (fillAlpha > 0) canvas.drawRoundRect(mDrawRect, mCornerPx, mCornerPx, mBoxFill); canvas.drawRoundRect(mDrawRect, mCornerPx, mCornerPx, mBoxStroke); } } @@ -660,8 +687,8 @@ } private boolean isInTouchableArea(float x, float y) { - for (RectF rect : mTouchableArea) { - if (rect.contains(x, y, x, y)) { + for (Box box : mTouchableArea) { + if (box.mRect.contains(x, y, x, y)) { return true; } } @@ -730,39 +757,100 @@ setLayoutParams(params); } - private void fadeInBoxes() { - if (mFadeInBoxesAnimator == null) { - mFadeInBoxesAnimator = - createBoxesAnimator(0f, 1f, BakedBezierInterpolator.FADE_IN_CURVE); + @IntDef({AnimationType.NONE, AnimationType.FADE_IN, AnimationType.FADE_OUT}) + @Retention(RetentionPolicy.SOURCE) + private @interface AnimationType { + int NONE = 0; + int FADE_IN = 1; + int FADE_OUT = 2; + } + + private class Box { + /** Current rectangle and touchable area, as reported by the model. */ + final RectF mRect = new RectF(); + + /** A copy of the rectangle that used to be displayed in mRect while fading in. */ + @Nullable + RectF mFadeInRect; + + /** Type of {@link #mAnimator}. */ + @AnimationType + int mAnimationType = AnimationType.NONE; + + /** Current animation. Cleared at end of animation. */ + @Nullable + ValueAnimator mAnimator; + + /** + * Returns 0 if the box should be invisible, 1 if it should be fully visible. + * + * <p>A fully visible box is transparent. An invisible box is identical to the background. + */ + float getVisibility() { + return mAnimator != null ? (float) mAnimator.getAnimatedValue() : 1f; } - runBoxesAnimation(mFadeInBoxesAnimator); - } - private void fadeOutBoxes() { - if (mFadeOutBoxesAnimator == null) { - mFadeOutBoxesAnimator = - createBoxesAnimator(1f, 0f, BakedBezierInterpolator.FADE_OUT_CURVE); + /** Returns the rectangle that should be drawn. */ + RectF getRectToDraw() { + return mFadeInRect != null ? mFadeInRect : mRect; } - runBoxesAnimation(mFadeOutBoxesAnimator); - } - private ValueAnimator createBoxesAnimator( - float start, float end, TimeInterpolator interpolator) { - ValueAnimator animator = ValueAnimator.ofFloat(start, end); - animator.setDuration(FADE_DURATION_MS); - animator.setInterpolator(interpolator); - animator.addUpdateListener((ignoredAnimator) -> invalidate()); - return animator; - } - - private void runBoxesAnimation(ValueAnimator animator) { - if (mCurrentBoxesAnimator != null && mCurrentBoxesAnimator.isRunning()) { - if (mCurrentBoxesAnimator == animator) { + /** Fades out to the current rectangle. Does nothing if empty or already fading out. */ + void fadeOut() { + if (!setupAnimator( + AnimationType.FADE_OUT, 0f, 1f, BakedBezierInterpolator.FADE_OUT_CURVE)) { return; } - mCurrentBoxesAnimator.cancel(); + mAnimator.start(); } - animator.start(); - mCurrentBoxesAnimator = animator; + + /** Fades the current rectangle in. Does nothing if empty or already fading in. */ + void fadeIn() { + if (!setupAnimator( + AnimationType.FADE_IN, 1f, 0f, BakedBezierInterpolator.FADE_IN_CURVE)) { + return; + } + mFadeInRect = new RectF(mRect); + mAnimator.addListener(new AnimatorListenerAdapter() { + @Override + public void onAnimationEnd(Animator ignored) { + mFadeInRect = null; + } + + @Override + public void onAnimationCancel(Animator ignored) { + mFadeInRect = null; + } + }); + mAnimator.start(); + } + + boolean setupAnimator(@AnimationType int animationType, float start, float end, + TimeInterpolator interpolator) { + if (mRect.isEmpty()) { + return false; + } + + if (mAnimator != null && mAnimator.isRunning()) { + if (mAnimationType == animationType) { + return false; + } + start = (Float) mAnimator.getAnimatedValue(); + mAnimator.cancel(); + } + mAnimationType = animationType; + mAnimator = ValueAnimator.ofFloat(start, end); + mAnimator.setDuration(FADE_DURATION_MS); + mAnimator.setInterpolator(interpolator); + mAnimator.addUpdateListener((ignoredAnimator) -> invalidate()); + mAnimator.addListener(new AnimatorListenerAdapter() { + @Override + public void onAnimationEnd(Animator ignored) { + mAnimationType = AnimationType.NONE; + mAnimator = null; + } + }); + return true; + } } }
diff --git a/chrome/android/feed/core/java/src/org/chromium/chrome/browser/feed/FeedDebuggingBridge.java b/chrome/android/feed/core/java/src/org/chromium/chrome/browser/feed/FeedDebuggingBridge.java index 79152083..2d695a58 100644 --- a/chrome/android/feed/core/java/src/org/chromium/chrome/browser/feed/FeedDebuggingBridge.java +++ b/chrome/android/feed/core/java/src/org/chromium/chrome/browser/feed/FeedDebuggingBridge.java
@@ -4,9 +4,15 @@ package org.chromium.chrome.browser.feed; +import com.google.android.libraries.feed.api.scope.FeedProcessScope; +import com.google.android.libraries.feed.common.logging.Dumper; + import org.chromium.base.annotations.CalledByNative; import org.chromium.base.annotations.JNINamespace; +import java.io.IOException; +import java.io.StringWriter; + /** * Java-side bridge that receives and responds to native-initiated requests for debugging data. This * data is then used to populate the Feed Internals page. @@ -17,4 +23,19 @@ static String getFeedFetchUrl() { return FeedConfiguration.getFeedServerEndpoint(); } + + @CalledByNative + static String getFeedProcessScopeDump() { + FeedProcessScope feedProcessScope = FeedProcessScopeFactory.getFeedProcessScope(); + Dumper dumper = Dumper.newDefaultDumper(); + dumper.dump(feedProcessScope); + + try { + StringWriter writer = new StringWriter(); + dumper.write(writer); + return writer.toString(); + } catch (IOException e) { + return "Unable to dump FeedProcessScope"; + } + } }
diff --git a/chrome/android/feed/core/java/src/org/chromium/chrome/browser/feed/FeedNewTabPage.java b/chrome/android/feed/core/java/src/org/chromium/chrome/browser/feed/FeedNewTabPage.java index 34b28f27..80961289 100644 --- a/chrome/android/feed/core/java/src/org/chromium/chrome/browser/feed/FeedNewTabPage.java +++ b/chrome/android/feed/core/java/src/org/chromium/chrome/browser/feed/FeedNewTabPage.java
@@ -435,6 +435,7 @@ mScrollViewForPolicy = new PolicyScrollView(mTab.getActivity()); mScrollViewForPolicy.setBackgroundColor(Color.WHITE); + mScrollViewForPolicy.setVerticalScrollBarEnabled(false); // Make scroll view focusable so that it is the next focusable view when the url bar clears // focus.
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/autofill/AutofillKeyboardAccessoryBridge.java b/chrome/android/java/src/org/chromium/chrome/browser/autofill/AutofillKeyboardAccessoryBridge.java index 1387d40..e5f36f8c 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/autofill/AutofillKeyboardAccessoryBridge.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/autofill/AutofillKeyboardAccessoryBridge.java
@@ -14,8 +14,8 @@ import org.chromium.chrome.browser.ChromeActivity; import org.chromium.chrome.browser.ResourceId; import org.chromium.chrome.browser.autofill.keyboard_accessory.AccessoryAction; -import org.chromium.chrome.browser.autofill.keyboard_accessory.KeyboardAccessoryData; import org.chromium.chrome.browser.autofill.keyboard_accessory.ManualFillingCoordinator; +import org.chromium.chrome.browser.autofill.keyboard_accessory.PropertyProvider; import org.chromium.components.autofill.AutofillDelegate; import org.chromium.components.autofill.AutofillSuggestion; import org.chromium.ui.DropdownItem; @@ -32,8 +32,8 @@ private long mNativeAutofillKeyboardAccessory; private ManualFillingCoordinator mManualFillingCoordinator; private Context mContext; - private KeyboardAccessoryData.Provider<AutofillSuggestion[]> mChipProvider = - new KeyboardAccessoryData.PropertyProvider<>(AccessoryAction.AUTOFILL_SUGGESTION); + private PropertyProvider<AutofillSuggestion[]> mChipProvider = + new PropertyProvider<>(AccessoryAction.AUTOFILL_SUGGESTION); private AutofillKeyboardAccessoryBridge() { }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/autofill/keyboard_accessory/CachedProviderAdapter.java b/chrome/android/java/src/org/chromium/chrome/browser/autofill/keyboard_accessory/CachedProviderAdapter.java new file mode 100644 index 0000000..17be583 --- /dev/null +++ b/chrome/android/java/src/org/chromium/chrome/browser/autofill/keyboard_accessory/CachedProviderAdapter.java
@@ -0,0 +1,59 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package org.chromium.chrome.browser.autofill.keyboard_accessory; + +import android.support.annotation.Nullable; + +import org.chromium.base.Callback; +import org.chromium.chrome.browser.tab.Tab; + +/** + * Provides a cache for a given provider. New sets of data will only be cached and not + * propagated to observers immediately. Instead, a callback is called to when data arrives and + * the decision to make the new data available happens there. + * @param <T> The type of data the provider collects and provides. + */ +class CachedProviderAdapter<T> extends PropertyProvider<T> implements Provider.Observer<T> { + private final @Nullable Callback<CachedProviderAdapter> mNewCachedDataAvailable; + private final Tab mTab; + private T mLastItems; + + /** + * Creates an adapter that listens to the given |provider| and stores items provided by + * it. It will not immediately notify observers but instead call a callback when data arrives. + * @param provider The {@link Provider} to observe and whose data to cache. + * @param defaultItems The items to be notified about if the Provider hasn't provided any. + * @param newCachedDataAvailable Optional callback to be called if new data arrives. + * @param tab A {@link Tab} + */ + CachedProviderAdapter(PropertyProvider<T> provider, T defaultItems, + @Nullable Callback<CachedProviderAdapter> newCachedDataAvailable, Tab tab) { + super(provider.mType); + mNewCachedDataAvailable = newCachedDataAvailable; + mTab = tab; + provider.addObserver(this); + mLastItems = defaultItems; + } + + /** + * Calls {@link #onItemAvailable} with the last used items again. If there haven't been + * any calls, call it with an empty list to avoid putting observers in an undefined + * state. + */ + public void notifyAboutCachedItems() { + notifyObservers(mLastItems); + } + + Tab getTab() { + return mTab; + } + + @Override + public void onItemAvailable(int typeId, T actions) { + mLastItems = actions; + // Update the contents immediately, if the adapter connects to an active element. + if (mNewCachedDataAvailable != null) mNewCachedDataAvailable.onResult(this); + } +} \ No newline at end of file
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/autofill/keyboard_accessory/KeyboardAccessoryCoordinator.java b/chrome/android/java/src/org/chromium/chrome/browser/autofill/keyboard_accessory/KeyboardAccessoryCoordinator.java index e08c3c0..aeca20d 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/autofill/keyboard_accessory/KeyboardAccessoryCoordinator.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/autofill/keyboard_accessory/KeyboardAccessoryCoordinator.java
@@ -179,28 +179,26 @@ } /** - * Allows any {@link KeyboardAccessoryData.Provider} to communicate with the + * Allows any {@link Provider} to communicate with the * {@link KeyboardAccessoryMediator} of this component. * * Note that the provided actions are removed when the accessory is hidden. * * @param provider The object providing action lists to observers in this component. */ - public void registerActionProvider( - KeyboardAccessoryData.Provider<KeyboardAccessoryData.Action[]> provider) { + public void registerActionProvider(Provider<KeyboardAccessoryData.Action[]> provider) { provider.addObserver(mMediator); } /** - * Registers a KeyboardAccessoryData.Observer to the given KeyboardAccessoryData.Provider. The + * Registers a Provider.Observer to the given Provider. The * new observer will render chips into the accessory bar for every new suggestion and call the * given {@link AutofillDelegate} when the user interacts with a chip. - * @param provider A {@link KeyboardAccessoryData.Provider<AutofillSuggestion[]>}. + * @param provider A {@link Provider<AutofillSuggestion[]>}. * @param delegate A {@link AutofillDelegate}. */ public void registerAutofillProvider( - KeyboardAccessoryData.Provider<AutofillSuggestion[]> provider, - AutofillDelegate delegate) { + Provider<AutofillSuggestion[]> provider, AutofillDelegate delegate) { provider.addObserver(mMediator.createAutofillSuggestionsObserver(delegate)); }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/autofill/keyboard_accessory/KeyboardAccessoryData.java b/chrome/android/java/src/org/chromium/chrome/browser/autofill/keyboard_accessory/KeyboardAccessoryData.java index af62bae..3c996d4 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/autofill/keyboard_accessory/KeyboardAccessoryData.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/autofill/keyboard_accessory/KeyboardAccessoryData.java
@@ -21,40 +21,6 @@ */ public class KeyboardAccessoryData { /** - * A provider notifies all registered {@link Observer}s about a changed object. - * @param <T> The object this provider provides. - */ - public interface Provider<T> { - /** - * Every observer added by this needs to be notified whenever the object changes. - * @param observer The observer to be notified. - */ - void addObserver(Observer<T> observer); - - /** - * Passes the given item to all subscribed {@link Observer}s. - * @param item The item to be passed to the {@link Observer}s. - */ - void notifyObservers(T item); - } - - /** - * An observer receives notifications from an {@link Provider} it is subscribed to. - * @param <T> Any object that this instance observes. - */ - public interface Observer<T> { - int DEFAULT_TYPE = Integer.MIN_VALUE; - - /** - * A provider calls this function with an item that should be available in the keyboard - * accessory. - * @param typeId Specifies which type of item this update affects. - * @param item An item to be displayed in the Accessory. - */ - void onItemAvailable(int typeId, T item); - } - - /** * Describes a tab which should be displayed as a small icon at the start of the keyboard * accessory. Typically, a tab is responsible to change the accessory sheet below the accessory. */ @@ -388,35 +354,5 @@ } } - /** - * A simple class that holds a list of {@link Observer}s which can be notified about new data by - * directly passing that data into {@link PropertyProvider#notifyObservers(T)}. - * @param <T> The object this provider provides. - */ - public static class PropertyProvider<T> implements Provider<T> { - private final List<Observer<T>> mObservers = new ArrayList<>(); - protected int mType; - - public PropertyProvider() { - this(Observer.DEFAULT_TYPE); - } - - public PropertyProvider(int type) { - mType = type; - } - - @Override - public void addObserver(Observer<T> observer) { - mObservers.add(observer); - } - - @Override - public void notifyObservers(T item) { - for (Observer<T> observer : mObservers) { - observer.onItemAvailable(mType, item); - } - } - } - private KeyboardAccessoryData() {} }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/autofill/keyboard_accessory/KeyboardAccessoryMediator.java b/chrome/android/java/src/org/chromium/chrome/browser/autofill/keyboard_accessory/KeyboardAccessoryMediator.java index 5f294ea..96b3e43c 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/autofill/keyboard_accessory/KeyboardAccessoryMediator.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/autofill/keyboard_accessory/KeyboardAccessoryMediator.java
@@ -46,8 +46,7 @@ */ class KeyboardAccessoryMediator implements ListObservable.ListObserver<Void>, - PropertyObservable.PropertyObserver<PropertyKey>, - KeyboardAccessoryData.Observer<KeyboardAccessoryData.Action[]>, + PropertyObservable.PropertyObserver<PropertyKey>, Provider.Observer<Action[]>, KeyboardAccessoryTabLayoutCoordinator.AccessoryTabObserver { private final PropertyModel mModel; private final VisibilityDelegate mVisibilityDelegate; @@ -76,9 +75,9 @@ * notifies it about new {@link AutofillSuggestion}s. It ensures the delegate receives * interactions with the view representing a suggestion. * @param delegate A {@link AutofillDelegate}. - * @return A {@link KeyboardAccessoryData.Observer} accepting only {@link AutofillSuggestion}s. + * @return A {@link Provider.Observer} accepting only {@link AutofillSuggestion}s. */ - public KeyboardAccessoryData.Observer<AutofillSuggestion[]> createAutofillSuggestionsObserver( + public Provider.Observer<AutofillSuggestion[]> createAutofillSuggestionsObserver( AutofillDelegate delegate) { return (@AccessoryAction int typeId, AutofillSuggestion[] suggestions) -> { assert typeId
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/autofill/keyboard_accessory/ManualFillingBridge.java b/chrome/android/java/src/org/chromium/chrome/browser/autofill/keyboard_accessory/ManualFillingBridge.java index 613d8a89..437532f 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/autofill/keyboard_accessory/ManualFillingBridge.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/autofill/keyboard_accessory/ManualFillingBridge.java
@@ -20,11 +20,10 @@ import org.chromium.ui.base.WindowAndroid; class ManualFillingBridge { - private final KeyboardAccessoryData.PropertyProvider<AccessorySheetData> mSheetDataProvider = - new KeyboardAccessoryData.PropertyProvider<>(); - private final KeyboardAccessoryData.PropertyProvider<Action[]> mActionProvider = - new KeyboardAccessoryData.PropertyProvider<>( - AccessoryAction.GENERATE_PASSWORD_AUTOMATIC); + private final PropertyProvider<AccessorySheetData> mSheetDataProvider = + new PropertyProvider<>(); + private final PropertyProvider<Action[]> mActionProvider = + new PropertyProvider<>(AccessoryAction.GENERATE_PASSWORD_AUTOMATIC); private final ManualFillingCoordinator mManualFillingCoordinator; private final ChromeActivity mActivity; private long mNativeView;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/autofill/keyboard_accessory/ManualFillingCoordinator.java b/chrome/android/java/src/org/chromium/chrome/browser/autofill/keyboard_accessory/ManualFillingCoordinator.java index 69071cb..a720b44 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/autofill/keyboard_accessory/ManualFillingCoordinator.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/autofill/keyboard_accessory/ManualFillingCoordinator.java
@@ -10,7 +10,6 @@ import org.chromium.base.VisibleForTesting; import org.chromium.chrome.browser.ChromeFeatureList; -import org.chromium.chrome.browser.autofill.keyboard_accessory.KeyboardAccessoryData.Provider; import org.chromium.ui.DeferredViewStubInflationProvider; import org.chromium.ui.DropdownPopupWindow; import org.chromium.ui.ViewProvider; @@ -95,8 +94,7 @@ mMediator.swapSheetWithKeyboard(); } - void registerActionProvider( - KeyboardAccessoryData.PropertyProvider<KeyboardAccessoryData.Action[]> actionProvider) { + void registerActionProvider(PropertyProvider<KeyboardAccessoryData.Action[]> actionProvider) { mMediator.registerActionProvider(actionProvider); }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/autofill/keyboard_accessory/ManualFillingMediator.java b/chrome/android/java/src/org/chromium/chrome/browser/autofill/keyboard_accessory/ManualFillingMediator.java index 83b64f3..3c4d33d 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/autofill/keyboard_accessory/ManualFillingMediator.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/autofill/keyboard_accessory/ManualFillingMediator.java
@@ -17,7 +17,6 @@ import org.chromium.chrome.browser.ChromeWindow; import org.chromium.chrome.browser.InsetObserverView; import org.chromium.chrome.browser.autofill.keyboard_accessory.KeyboardAccessoryData.Action; -import org.chromium.chrome.browser.autofill.keyboard_accessory.KeyboardAccessoryData.Provider; import org.chromium.chrome.browser.compositor.CompositorViewHolder; import org.chromium.chrome.browser.compositor.layouts.Layout; import org.chromium.chrome.browser.compositor.layouts.LayoutManager; @@ -54,54 +53,13 @@ new KeyboardExtensionSizeManager(); /** - * Provides a cache for a given Provider which can repeat the last notification to all - * observers. - */ - private class ActionProviderCacheAdapter - extends KeyboardAccessoryData.PropertyProvider<Action[]> - implements KeyboardAccessoryData.Observer<Action[]> { - private final Tab mTab; - private Action[] mLastItems; - - /** - * Creates an adapter that listens to the given |provider| and stores items provided by it. - * If the observed provider serves a currently visible tab, the data is immediately sent on. - * @param tab The {@link Tab} which the given Provider should affect immediately. - * @param provider The {@link Provider} to observe and whose data to cache. - * @param defaultItems The items to be notified about if the Provider hasn't provided any. - */ - ActionProviderCacheAdapter(Tab tab, - KeyboardAccessoryData.PropertyProvider<Action[]> provider, Action[] defaultItems) { - super(provider.mType); - mTab = tab; - provider.addObserver(this); - mLastItems = defaultItems; - } - - /** - * Calls {@link #onItemAvailable} with the last used items again. If there haven't been - * any calls, call it with an empty list to avoid putting observers in an undefined state. - */ - void notifyAboutCachedItems() { - notifyObservers(mLastItems); - } - - @Override - public void onItemAvailable(int typeId, Action[] actions) { - mLastItems = actions; - // Update the contents immediately, if the adapter connects to an active element. - if (mTab == mActiveBrowserTab) notifyObservers(actions); - } - } - - /** * This class holds all data that is necessary to restore the state of the Keyboard accessory * and its sheet for a given tab. */ @VisibleForTesting static class AccessoryState { @Nullable - ActionProviderCacheAdapter mActionsProvider; + CachedProviderAdapter<Action[]> mActionsProvider; @Nullable PasswordAccessorySheetCoordinator mPasswordAccessorySheet; @Nullable @@ -234,15 +192,20 @@ if (accessorySheet == null) return; } - void registerActionProvider(KeyboardAccessoryData.PropertyProvider<Action[]> actionProvider) { + void registerActionProvider(PropertyProvider<Action[]> actionProvider) { if (!isInitialized()) return; if (mActiveBrowserTab == null) return; - ActionProviderCacheAdapter adapter = - new ActionProviderCacheAdapter(mActiveBrowserTab, actionProvider, new Action[0]); + CachedProviderAdapter<Action[]> adapter = new CachedProviderAdapter<>( + actionProvider, new Action[0], this::onCacheReceivedNewData, mActiveBrowserTab); mModel.get(mActiveBrowserTab).mActionsProvider = adapter; mKeyboardAccessory.registerActionProvider(adapter); } + private void onCacheReceivedNewData(CachedProviderAdapter cachedProviderAdapter) { + if (mActiveBrowserTab != cachedProviderAdapter.getTab()) return; + cachedProviderAdapter.notifyAboutCachedItems(); + } + void destroy() { if (!isInitialized()) return; pause();
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/autofill/keyboard_accessory/PasswordAccessorySheetCoordinator.java b/chrome/android/java/src/org/chromium/chrome/browser/autofill/keyboard_accessory/PasswordAccessorySheetCoordinator.java index d21b66e..2ed566c 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/autofill/keyboard_accessory/PasswordAccessorySheetCoordinator.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/autofill/keyboard_accessory/PasswordAccessorySheetCoordinator.java
@@ -16,7 +16,6 @@ import org.chromium.chrome.browser.ChromeFeatureList; import org.chromium.chrome.browser.autofill.keyboard_accessory.AccessorySheetTabModel.AccessorySheetDataPiece; import org.chromium.chrome.browser.autofill.keyboard_accessory.KeyboardAccessoryData.AccessorySheetData; -import org.chromium.chrome.browser.autofill.keyboard_accessory.KeyboardAccessoryData.Provider; import org.chromium.ui.modelutil.ListModel; import org.chromium.ui.modelutil.RecyclerViewAdapter; import org.chromium.ui.modelutil.SimpleRecyclerViewMcp;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/autofill/keyboard_accessory/PasswordAccessorySheetMediator.java b/chrome/android/java/src/org/chromium/chrome/browser/autofill/keyboard_accessory/PasswordAccessorySheetMediator.java index 81dff31c..a4a904c 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/autofill/keyboard_accessory/PasswordAccessorySheetMediator.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/autofill/keyboard_accessory/PasswordAccessorySheetMediator.java
@@ -21,7 +21,7 @@ * {@link PropertyModel} are observed by a {@link PropertyModelChangeProcessor} and affect the * password accessory sheet tab view. */ -class PasswordAccessorySheetMediator implements KeyboardAccessoryData.Observer<AccessorySheetData> { +class PasswordAccessorySheetMediator implements Provider.Observer<AccessorySheetData> { private final AccessorySheetTabModel mModel; @Override
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/autofill/keyboard_accessory/PropertyProvider.java b/chrome/android/java/src/org/chromium/chrome/browser/autofill/keyboard_accessory/PropertyProvider.java new file mode 100644 index 0000000..1b862f7 --- /dev/null +++ b/chrome/android/java/src/org/chromium/chrome/browser/autofill/keyboard_accessory/PropertyProvider.java
@@ -0,0 +1,38 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package org.chromium.chrome.browser.autofill.keyboard_accessory; + +import java.util.ArrayList; +import java.util.List; + +/** + * A simple class that holds a list of {@link Observer}s which can be notified about new data by + * directly passing that data into {@link PropertyProvider#notifyObservers(T)}. + * @param <T> The object this provider provides. + */ +public class PropertyProvider<T> implements Provider<T> { + private final List<Observer<T>> mObservers = new ArrayList<>(); + protected int mType; + + public PropertyProvider() { + this(Observer.DEFAULT_TYPE); + } + + public PropertyProvider(int type) { + mType = type; + } + + @Override + public void addObserver(Observer<T> observer) { + mObservers.add(observer); + } + + @Override + public void notifyObservers(T item) { + for (Observer<T> observer : mObservers) { + observer.onItemAvailable(mType, item); + } + } +}
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/autofill/keyboard_accessory/Provider.java b/chrome/android/java/src/org/chromium/chrome/browser/autofill/keyboard_accessory/Provider.java new file mode 100644 index 0000000..56bab10 --- /dev/null +++ b/chrome/android/java/src/org/chromium/chrome/browser/autofill/keyboard_accessory/Provider.java
@@ -0,0 +1,39 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package org.chromium.chrome.browser.autofill.keyboard_accessory; + +/** + * A provider notifies all registered {@link Observer}s about a changed object. + * @param <T> The object this provider provides. + */ +interface Provider<T> { + /** + * Every observer added by this needs to be notified whenever the object changes. + * @param observer The observer to be notified. + */ + void addObserver(Observer<T> observer); + + /** + * Passes the given item to all subscribed {@link Observer}s. + * @param item The item to be passed to the {@link Observer}s. + */ + void notifyObservers(T item); + + /** + * An observer receives notifications from an {@link Provider} it is subscribed to. + * @param <T> Any object that this instance observes. + */ + interface Observer<T> { + int DEFAULT_TYPE = Integer.MIN_VALUE; + + /** + * A provider calls this function with an item that should be available in the keyboard + * accessory. + * @param typeId Specifies which type of item this update affects. + * @param item An item to be displayed in the Accessory. + */ + void onItemAvailable(int typeId, T item); + } +}
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/notifications/NotificationBuilderBase.java b/chrome/android/java/src/org/chromium/chrome/browser/notifications/NotificationBuilderBase.java index 0beaf49..b0e3639394 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/notifications/NotificationBuilderBase.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/notifications/NotificationBuilderBase.java
@@ -529,9 +529,11 @@ if (Build.VERSION.SDK_INT == Build.VERSION_CODES.M) { // Updating a notification with a bitmap status bar icon leads to a crash on Samsung // and Coolpad (Yulong) devices on Marshmallow, see https://crbug.com/829367. - // Also, there are crashes on Lenovo M devices: https://crbug.com/894361. + // Also, there are crashes on Lenovo M devices: https://crbug.com/894361. These include + // Lenovo Zuk devices, which have Build.MANUFACTURER="ZUK": https://crbug.com/927271. // And some more crashes from Hisense and LeEco devices: https://crbug.com/903268. - for (String name : new String[] {"samsung", "yulong", "lenovo", "hisense", "leeco"}) { + for (String name : new String[] {"samsung", "yulong", "lenovo", "zuk", "hisense", + "leeco"}) { if (Build.MANUFACTURER.equalsIgnoreCase(name)) { return false; }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/suggestions/SuggestionsRecyclerView.java b/chrome/android/java/src/org/chromium/chrome/browser/suggestions/SuggestionsRecyclerView.java index f56c2d9a..7c370d0 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/suggestions/SuggestionsRecyclerView.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/suggestions/SuggestionsRecyclerView.java
@@ -99,6 +99,7 @@ setFocusable(true); setFocusableInTouchMode(true); setContentDescription(res.getString(R.string.accessibility_new_tab_page)); + setClipToPadding(false); mGestureDetector = new GestureDetector(getContext(), new GestureDetector.SimpleOnGestureListener() {
diff --git a/chrome/android/java_sources.gni b/chrome/android/java_sources.gni index 25b341f..04724dc3 100644 --- a/chrome/android/java_sources.gni +++ b/chrome/android/java_sources.gni
@@ -114,6 +114,7 @@ "java/src/org/chromium/chrome/browser/autofill/keyboard_accessory/AccessorySheetTabViewBinder.java", "java/src/org/chromium/chrome/browser/autofill/keyboard_accessory/AccessorySheetView.java", "java/src/org/chromium/chrome/browser/autofill/keyboard_accessory/AccessorySheetViewBinder.java", + "java/src/org/chromium/chrome/browser/autofill/keyboard_accessory/CachedProviderAdapter.java", "java/src/org/chromium/chrome/browser/autofill/keyboard_accessory/CreditCardAccessorySheetCoordinator.java", "java/src/org/chromium/chrome/browser/autofill/keyboard_accessory/KeyboardAccessoryCoordinator.java", "java/src/org/chromium/chrome/browser/autofill/keyboard_accessory/KeyboardAccessoryData.java", @@ -139,6 +140,8 @@ "java/src/org/chromium/chrome/browser/autofill/keyboard_accessory/PasswordAccessorySheetMediator.java", "java/src/org/chromium/chrome/browser/autofill/keyboard_accessory/PasswordAccessorySheetViewBinder.java", "java/src/org/chromium/chrome/browser/autofill/keyboard_accessory/PasswordAccessorySheetModernViewBinder.java", + "java/src/org/chromium/chrome/browser/autofill/keyboard_accessory/Provider.java", + "java/src/org/chromium/chrome/browser/autofill/keyboard_accessory/PropertyProvider.java", "java/src/org/chromium/chrome/browser/autofill_assistant/AutofillAssistantClient.java", "java/src/org/chromium/chrome/browser/autofill_assistant/AutofillAssistantFacade.java", "java/src/org/chromium/chrome/browser/autofill_assistant/AutofillAssistantMetrics.java",
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/autofill/keyboard_accessory/ManualFillingTestHelper.java b/chrome/android/javatests/src/org/chromium/chrome/browser/autofill/keyboard_accessory/ManualFillingTestHelper.java index 09f19680..a6bdb22e 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/autofill/keyboard_accessory/ManualFillingTestHelper.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/autofill/keyboard_accessory/ManualFillingTestHelper.java
@@ -42,7 +42,6 @@ import org.chromium.chrome.browser.autofill.AutofillTestHelper; import org.chromium.chrome.browser.autofill.PersonalDataManager.AutofillProfile; import org.chromium.chrome.browser.autofill.keyboard_accessory.KeyboardAccessoryData.AccessorySheetData; -import org.chromium.chrome.browser.autofill.keyboard_accessory.KeyboardAccessoryData.Provider; import org.chromium.chrome.test.ChromeTabbedActivityTestRule; import org.chromium.components.autofill.AutofillDelegate; import org.chromium.components.autofill.AutofillSuggestion; @@ -71,8 +70,7 @@ private final ChromeTabbedActivityTestRule mActivityTestRule; private final AtomicReference<WebContents> mWebContentsRef = new AtomicReference<>(); private TestInputMethodManagerWrapper mInputMethodManagerWrapper; - private Provider<AccessorySheetData> mSheetSuggestionsProvider = - new KeyboardAccessoryData.PropertyProvider<>(); + private Provider<AccessorySheetData> mSheetSuggestionsProvider = new PropertyProvider<>(); private EmbeddedTestServer mEmbeddedTestServer; @@ -399,10 +397,8 @@ // -------------------------------------------- public void addGenerationButton() { - KeyboardAccessoryData - .PropertyProvider<KeyboardAccessoryData.Action[]> generationActionProvider = - new KeyboardAccessoryData.PropertyProvider<>( - AccessoryAction.GENERATE_PASSWORD_AUTOMATIC); + PropertyProvider<KeyboardAccessoryData.Action[]> generationActionProvider = + new PropertyProvider<>(AccessoryAction.GENERATE_PASSWORD_AUTOMATIC); mActivityTestRule.getActivity().getManualFillingController().registerActionProvider( generationActionProvider); ThreadUtils.runOnUiThreadBlocking(() -> { @@ -413,8 +409,8 @@ } public void addAutofillChips() { - KeyboardAccessoryData.PropertyProvider<AutofillSuggestion[]> suggestionProvider = - new KeyboardAccessoryData.PropertyProvider<>(AccessoryAction.AUTOFILL_SUGGESTION); + PropertyProvider<AutofillSuggestion[]> suggestionProvider = + new PropertyProvider<>(AccessoryAction.AUTOFILL_SUGGESTION); mActivityTestRule.getActivity() .getManualFillingController() .getKeyboardAccessory()
diff --git a/chrome/android/junit/src/org/chromium/chrome/browser/autofill/keyboard_accessory/KeyboardAccessoryControllerTest.java b/chrome/android/junit/src/org/chromium/chrome/browser/autofill/keyboard_accessory/KeyboardAccessoryControllerTest.java index 43952fd5..9d78a00 100644 --- a/chrome/android/junit/src/org/chromium/chrome/browser/autofill/keyboard_accessory/KeyboardAccessoryControllerTest.java +++ b/chrome/android/junit/src/org/chromium/chrome/browser/autofill/keyboard_accessory/KeyboardAccessoryControllerTest.java
@@ -34,7 +34,6 @@ import org.chromium.base.test.BaseRobolectricTestRunner; import org.chromium.chrome.browser.ChromeFeatureList; import org.chromium.chrome.browser.autofill.keyboard_accessory.KeyboardAccessoryData.Action; -import org.chromium.chrome.browser.autofill.keyboard_accessory.KeyboardAccessoryData.PropertyProvider; import org.chromium.chrome.browser.autofill.keyboard_accessory.KeyboardAccessoryProperties.AutofillBarItem; import org.chromium.chrome.browser.autofill.keyboard_accessory.KeyboardAccessoryProperties.BarItem; import org.chromium.components.autofill.AutofillDelegate; @@ -210,8 +209,8 @@ @Test public void testIsVisibleWithSuggestionsBeforeKeyboardComesUp() { - KeyboardAccessoryData.PropertyProvider<AutofillSuggestion[]> autofillSuggestionProvider = - new KeyboardAccessoryData.PropertyProvider<>(AUTOFILL_SUGGESTION); + PropertyProvider<AutofillSuggestion[]> autofillSuggestionProvider = + new PropertyProvider<>(AUTOFILL_SUGGESTION); AutofillSuggestion suggestion = new AutofillSuggestion("Label", "sublabel", 0, false, 0, false, false, false); mCoordinator.registerAutofillProvider(autofillSuggestionProvider, mMockAutofillDelegate); @@ -236,8 +235,8 @@ @Test public void testIsVisibleWithSuggestionsAfterKeyboardComesUp() { - KeyboardAccessoryData.PropertyProvider<AutofillSuggestion[]> autofillSuggestionProvider = - new KeyboardAccessoryData.PropertyProvider<>(AUTOFILL_SUGGESTION); + PropertyProvider<AutofillSuggestion[]> autofillSuggestionProvider = + new PropertyProvider<>(AUTOFILL_SUGGESTION); AutofillSuggestion suggestion = new AutofillSuggestion("Label", "sublabel", 0, false, 0, false, false, false); mCoordinator.registerAutofillProvider(autofillSuggestionProvider, mMockAutofillDelegate); @@ -272,10 +271,10 @@ @Test public void testSortsActionsBasedOnType() { - KeyboardAccessoryData.PropertyProvider<Action[]> generationProvider = - new KeyboardAccessoryData.PropertyProvider<>(GENERATE_PASSWORD_AUTOMATIC); - KeyboardAccessoryData.PropertyProvider<AutofillSuggestion[]> autofillSuggestionProvider = - new KeyboardAccessoryData.PropertyProvider<>(AUTOFILL_SUGGESTION); + PropertyProvider<Action[]> generationProvider = + new PropertyProvider<>(GENERATE_PASSWORD_AUTOMATIC); + PropertyProvider<AutofillSuggestion[]> autofillSuggestionProvider = + new PropertyProvider<>(AUTOFILL_SUGGESTION); mCoordinator.registerActionProvider(generationProvider); mCoordinator.registerAutofillProvider(autofillSuggestionProvider, mMockAutofillDelegate); @@ -303,10 +302,10 @@ @Test public void testMovesTabSwitcherToEndForRedesign() { setAutofillFeature(true); - KeyboardAccessoryData.PropertyProvider<Action[]> generationProvider = - new KeyboardAccessoryData.PropertyProvider<>(GENERATE_PASSWORD_AUTOMATIC); - KeyboardAccessoryData.PropertyProvider<Action[]> autofillSuggestionProvider = - new KeyboardAccessoryData.PropertyProvider<>(AUTOFILL_SUGGESTION); + PropertyProvider<Action[]> generationProvider = + new PropertyProvider<>(GENERATE_PASSWORD_AUTOMATIC); + PropertyProvider<Action[]> autofillSuggestionProvider = + new PropertyProvider<>(AUTOFILL_SUGGESTION); mCoordinator.registerActionProvider(generationProvider); mCoordinator.registerActionProvider(autofillSuggestionProvider); @@ -327,10 +326,10 @@ @Test public void testDeletingActionsAffectsOnlyOneType() { - KeyboardAccessoryData.PropertyProvider<Action[]> generationProvider = - new KeyboardAccessoryData.PropertyProvider<>(GENERATE_PASSWORD_AUTOMATIC); - KeyboardAccessoryData.PropertyProvider<AutofillSuggestion[]> autofillSuggestionProvider = - new KeyboardAccessoryData.PropertyProvider<>(AUTOFILL_SUGGESTION); + PropertyProvider<Action[]> generationProvider = + new PropertyProvider<>(GENERATE_PASSWORD_AUTOMATIC); + PropertyProvider<AutofillSuggestion[]> autofillSuggestionProvider = + new PropertyProvider<>(AUTOFILL_SUGGESTION); mCoordinator.registerActionProvider(generationProvider); mCoordinator.registerAutofillProvider(autofillSuggestionProvider, mMockAutofillDelegate); @@ -420,8 +419,8 @@ // Adding suggestions adds to the suggestions bucket - and again to tabs and total. mCoordinator.close(); // Hide, so it's brought up again. - KeyboardAccessoryData.PropertyProvider<AutofillSuggestion[]> autofillSuggestionProvider = - new KeyboardAccessoryData.PropertyProvider<>(AUTOFILL_SUGGESTION); + PropertyProvider<AutofillSuggestion[]> autofillSuggestionProvider = + new PropertyProvider<>(AUTOFILL_SUGGESTION); AutofillSuggestion suggestion = new AutofillSuggestion("Label", "sublabel", 0, false, 0, false, false, false); mCoordinator.registerAutofillProvider(autofillSuggestionProvider, mMockAutofillDelegate); @@ -464,8 +463,8 @@ assertThat(getShownMetricsCount(AccessoryBarContents.WITH_ACTIONS), is(1)); assertThat(getShownMetricsCount(AccessoryBarContents.ANY_CONTENTS), is(1)); - KeyboardAccessoryData.PropertyProvider<AutofillSuggestion[]> autofillSuggestionProvider = - new KeyboardAccessoryData.PropertyProvider<>(AUTOFILL_SUGGESTION); + PropertyProvider<AutofillSuggestion[]> autofillSuggestionProvider = + new PropertyProvider<>(AUTOFILL_SUGGESTION); AutofillSuggestion suggestion = new AutofillSuggestion("Label", "sublabel", 0, false, 0, false, false, false); mCoordinator.registerAutofillProvider(autofillSuggestionProvider, mMockAutofillDelegate);
diff --git a/chrome/android/junit/src/org/chromium/chrome/browser/autofill/keyboard_accessory/ManualFillingControllerTest.java b/chrome/android/junit/src/org/chromium/chrome/browser/autofill/keyboard_accessory/ManualFillingControllerTest.java index b00f92a..429a9b4 100644 --- a/chrome/android/junit/src/org/chromium/chrome/browser/autofill/keyboard_accessory/ManualFillingControllerTest.java +++ b/chrome/android/junit/src/org/chromium/chrome/browser/autofill/keyboard_accessory/ManualFillingControllerTest.java
@@ -49,8 +49,6 @@ import org.chromium.chrome.browser.ChromeWindow; import org.chromium.chrome.browser.autofill.keyboard_accessory.KeyboardAccessoryData.AccessorySheetData; import org.chromium.chrome.browser.autofill.keyboard_accessory.KeyboardAccessoryData.Action; -import org.chromium.chrome.browser.autofill.keyboard_accessory.KeyboardAccessoryData.PropertyProvider; -import org.chromium.chrome.browser.autofill.keyboard_accessory.KeyboardAccessoryData.Provider; import org.chromium.chrome.browser.autofill.keyboard_accessory.KeyboardAccessoryData.UserInfo; import org.chromium.chrome.browser.autofill.keyboard_accessory.KeyboardAccessoryProperties.BarItem; import org.chromium.chrome.browser.fullscreen.ChromeFullscreenManager;
diff --git a/chrome/android/junit/src/org/chromium/chrome/browser/autofill/keyboard_accessory/PasswordAccessorySheetControllerTest.java b/chrome/android/junit/src/org/chromium/chrome/browser/autofill/keyboard_accessory/PasswordAccessorySheetControllerTest.java index 851b8b4..897435a 100644 --- a/chrome/android/junit/src/org/chromium/chrome/browser/autofill/keyboard_accessory/PasswordAccessorySheetControllerTest.java +++ b/chrome/android/junit/src/org/chromium/chrome/browser/autofill/keyboard_accessory/PasswordAccessorySheetControllerTest.java
@@ -35,7 +35,6 @@ import org.chromium.chrome.browser.ChromeFeatureList; import org.chromium.chrome.browser.autofill.keyboard_accessory.KeyboardAccessoryData.AccessorySheetData; import org.chromium.chrome.browser.autofill.keyboard_accessory.KeyboardAccessoryData.FooterCommand; -import org.chromium.chrome.browser.autofill.keyboard_accessory.KeyboardAccessoryData.PropertyProvider; import org.chromium.chrome.browser.autofill.keyboard_accessory.KeyboardAccessoryData.UserInfo; import org.chromium.ui.modelutil.ListObservable;
diff --git a/chrome/app/generated_resources.grd b/chrome/app/generated_resources.grd index 217b634..4b48a52 100644 --- a/chrome/app/generated_resources.grd +++ b/chrome/app/generated_resources.grd
@@ -7160,9 +7160,6 @@ <message name="IDS_SYNC_STATUS_NEEDS_PASSWORD_LINK_LABEL" desc="Hyperlink text indicating user must re-enter their sync password."> Enter passphrase </message> - <message name="IDS_SYNC_STATUS_ENABLE_SYNC_ON_ACCOUNT" desc="Message indicating user needs to ask the administrator to enable sync."> - Sync is disabled by your administrator - </message> <message name="IDS_SYNC_SERVER_IS_UNREACHABLE" desc="The message to display in the New Tab Page and Settings Page sync section when the server is unreachable."> Couldn't connect to the sync server. Retrying...
diff --git a/chrome/browser/BUILD.gn b/chrome/browser/BUILD.gn index 8f01685..a900a4bf 100644 --- a/chrome/browser/BUILD.gn +++ b/chrome/browser/BUILD.gn
@@ -2950,6 +2950,7 @@ "media_galleries/win/portable_device_map_service.h", "media_galleries/win/snapshot_file_details.cc", "media_galleries/win/snapshot_file_details.h", + "memory/memory_pressure_monitor_utils.cc", "memory/memory_pressure_monitor_utils.h", "memory/memory_pressure_monitor_utils_impl.h", "memory/oom_memory_details.cc",
diff --git a/chrome/browser/android/autofill_assistant/ui_controller_android.cc b/chrome/browser/android/autofill_assistant/ui_controller_android.cc index e5c4f04a..5ce1999b 100644 --- a/chrome/browser/android/autofill_assistant/ui_controller_android.cc +++ b/chrome/browser/android/autofill_assistant/ui_controller_android.cc
@@ -362,6 +362,12 @@ has_close_or_cancel = true; break; + case DONE_ACTION: + Java_AutofillAssistantUiController_addHighlightedActionButton( + env, java_object_, chips, text, i, action.disabled); + has_close_or_cancel = true; + break; + case SUGGESTION: // Suggestions are handled separately. case UNKNOWN_CHIP_TYPE: // Ignore unknown types break;
diff --git a/chrome/browser/android/feed/feed_debugging_bridge.cc b/chrome/browser/android/feed/feed_debugging_bridge.cc index 41fd1b2ed..bb259795 100644 --- a/chrome/browser/android/feed/feed_debugging_bridge.cc +++ b/chrome/browser/android/feed/feed_debugging_bridge.cc
@@ -17,4 +17,11 @@ return GURL(ConvertJavaStringToUTF8(env, j_string)); } +std::string GetFeedProcessScopeDumpForDebugging() { + JNIEnv* env = base::android::AttachCurrentThread(); + base::android::ScopedJavaLocalRef<jstring> j_string = + Java_FeedDebuggingBridge_getFeedProcessScopeDump(env); + return ConvertJavaStringToUTF8(env, j_string); +} + } // namespace feed
diff --git a/chrome/browser/android/feed/feed_debugging_bridge.h b/chrome/browser/android/feed/feed_debugging_bridge.h index 82c8c55..bace944 100644 --- a/chrome/browser/android/feed/feed_debugging_bridge.h +++ b/chrome/browser/android/feed/feed_debugging_bridge.h
@@ -6,6 +6,7 @@ #define CHROME_BROWSER_ANDROID_FEED_FEED_DEBUGGING_BRIDGE_H_ #include <jni.h> +#include <string> class GURL; @@ -14,6 +15,8 @@ GURL GetFeedFetchUrlForDebugging(); +std::string GetFeedProcessScopeDumpForDebugging(); + } // namespace feed #endif // CHROME_BROWSER_ANDROID_FEED_FEED_DEBUGGING_BRIDGE_H_
diff --git a/chrome/browser/apps/platform_apps/api/media_galleries/media_galleries_watch_apitest.cc b/chrome/browser/apps/platform_apps/api/media_galleries/media_galleries_watch_apitest.cc index 14824a6..ebc1be7719 100644 --- a/chrome/browser/apps/platform_apps/api/media_galleries/media_galleries_watch_apitest.cc +++ b/chrome/browser/apps/platform_apps/api/media_galleries/media_galleries_watch_apitest.cc
@@ -4,6 +4,7 @@ // // MediaGalleries gallery watch API browser tests. +#include "base/bind_helpers.h" #include "base/files/file_path.h" #include "base/files/file_path_watcher.h" #include "base/files/file_util.h" @@ -105,7 +106,7 @@ const std::string& ok_message) { ExtensionTestMessageListener listener(ok_message, false); background_host_->GetMainFrame()->ExecuteJavaScriptForTests( - base::ASCIIToUTF16(js_command)); + base::ASCIIToUTF16(js_command), base::NullCallback()); EXPECT_TRUE(listener.WaitUntilSatisfied()); }
diff --git a/chrome/browser/chrome_content_browser_client.cc b/chrome/browser/chrome_content_browser_client.cc index 39cc09a..4f2ed9edb 100644 --- a/chrome/browser/chrome_content_browser_client.cc +++ b/chrome/browser/chrome_content_browser_client.cc
@@ -3382,6 +3382,13 @@ return l10n_util::GetStringUTF8(IDS_DEFAULT_DOWNLOAD_FILENAME); } +base::FilePath ChromeContentBrowserClient::GetFontLookupTableCacheDir() { + base::FilePath user_data_dir; + base::PathService::Get(chrome::DIR_USER_DATA, &user_data_dir); + DCHECK(!user_data_dir.empty()); + return user_data_dir.Append(FILE_PATH_LITERAL("FontLookupTableCache")); +} + base::FilePath ChromeContentBrowserClient::GetShaderDiskCacheDirectory() { base::FilePath user_data_dir; base::PathService::Get(chrome::DIR_USER_DATA, &user_data_dir);
diff --git a/chrome/browser/chrome_content_browser_client.h b/chrome/browser/chrome_content_browser_client.h index c8966ee..62efefe 100644 --- a/chrome/browser/chrome_content_browser_client.h +++ b/chrome/browser/chrome_content_browser_client.h
@@ -323,6 +323,7 @@ void BrowserURLHandlerCreated(content::BrowserURLHandler* handler) override; base::FilePath GetDefaultDownloadDirectory() override; std::string GetDefaultDownloadName() override; + base::FilePath GetFontLookupTableCacheDir() override; base::FilePath GetShaderDiskCacheDirectory() override; base::FilePath GetGrShaderDiskCacheDirectory() override; void DidCreatePpapiPlugin(content::BrowserPpapiHost* browser_host) override;
diff --git a/chrome/browser/chromeos/BUILD.gn b/chrome/browser/chromeos/BUILD.gn index c436942..11f86c8 100644 --- a/chrome/browser/chromeos/BUILD.gn +++ b/chrome/browser/chromeos/BUILD.gn
@@ -1445,8 +1445,6 @@ "note_taking_controller_client.h", "note_taking_helper.cc", "note_taking_helper.h", - "oauth2_token_service_delegate.cc", - "oauth2_token_service_delegate.h", "ownership/fake_owner_settings_service.cc", "ownership/fake_owner_settings_service.h", "ownership/owner_settings_service_chromeos.cc", @@ -1561,6 +1559,8 @@ "policy/device_status_collector.h", "policy/device_wallpaper_image_handler.cc", "policy/device_wallpaper_image_handler.h", + "policy/device_wilco_dtc_configuration_handler.cc", + "policy/device_wilco_dtc_configuration_handler.h", "policy/display_resolution_handler.cc", "policy/display_resolution_handler.h", "policy/display_rotation_default_handler.cc", @@ -2379,7 +2379,6 @@ "network_change_manager_client_unittest.cc", "night_light/night_light_client_unittest.cc", "note_taking_helper_unittest.cc", - "oauth2_token_service_delegate_unittest.cc", "ownership/owner_settings_service_chromeos_unittest.cc", "plugin_vm/plugin_vm_image_manager_unittest.cc", "policy/active_directory_policy_manager_unittest.cc",
diff --git a/chrome/browser/chromeos/file_manager/file_manager_browsertest.cc b/chrome/browser/chromeos/file_manager/file_manager_browsertest.cc index a10c1d60..1e02c10 100644 --- a/chrome/browser/chromeos/file_manager/file_manager_browsertest.cc +++ b/chrome/browser/chromeos/file_manager/file_manager_browsertest.cc
@@ -582,7 +582,7 @@ TestCase("dirContextMenuCrostini"), TestCase("dirContextMenuPlayFiles"), TestCase("dirContextMenuUsbs"), - TestCase("dirContextMenuFsp"), + // TestCase("dirContextMenuFsp"), TestCase("dirContextMenuDocumentsProvider").EnableDocumentsProvider(), TestCase("dirContextMenuShortcut")));
diff --git a/chrome/browser/chromeos/file_manager/file_manager_browsertest_base.cc b/chrome/browser/chromeos/file_manager/file_manager_browsertest_base.cc index 02c5b92..19cecaeb 100644 --- a/chrome/browser/chromeos/file_manager/file_manager_browsertest_base.cc +++ b/chrome/browser/chromeos/file_manager/file_manager_browsertest_base.cc
@@ -2009,7 +2009,7 @@ CHECK(window->web_contents()->GetMainFrame()); window->web_contents()->GetMainFrame()->ExecuteJavaScriptForTests( - base::UTF8ToUTF16(script)); + base::UTF8ToUTF16(script), base::NullCallback()); break; }
diff --git a/chrome/browser/chromeos/file_manager/video_player_browsertest.cc b/chrome/browser/chromeos/file_manager/video_player_browsertest.cc index e4fcd0f..a671371d 100644 --- a/chrome/browser/chromeos/file_manager/video_player_browsertest.cc +++ b/chrome/browser/chromeos/file_manager/video_player_browsertest.cc
@@ -6,6 +6,7 @@ #include "base/test/scoped_feature_list.h" #include "chromeos/constants/chromeos_switches.h" +#include "content/public/common/content_switches.h" #include "media/base/media_switches.h" namespace file_manager { @@ -19,6 +20,10 @@ void SetUpCommandLine(base::CommandLine* command_line) override { command_line->AppendSwitch( chromeos::switches::kEnableVideoPlayerChromecastSupport); + // TODO(crbug.com/938226): Remove when Auto Picture-in-Picture is not + // experimental anymore. + command_line->AppendSwitch( + switches::kEnableExperimentalWebPlatformFeatures); FileManagerBrowserTestBase::SetUpCommandLine(command_line); }
diff --git a/chrome/browser/chromeos/policy/browser_policy_connector_chromeos.cc b/chrome/browser/chromeos/policy/browser_policy_connector_chromeos.cc index 301d22f..94776513d 100644 --- a/chrome/browser/chromeos/policy/browser_policy_connector_chromeos.cc +++ b/chrome/browser/chromeos/policy/browser_policy_connector_chromeos.cc
@@ -33,6 +33,7 @@ #include "chrome/browser/chromeos/policy/device_network_configuration_updater.h" #include "chrome/browser/chromeos/policy/device_policy_cloud_external_data_manager.h" #include "chrome/browser/chromeos/policy/device_wallpaper_image_handler.h" +#include "chrome/browser/chromeos/policy/device_wilco_dtc_configuration_handler.h" #include "chrome/browser/chromeos/policy/enrollment_config.h" #include "chrome/browser/chromeos/policy/hostname_handler.h" #include "chrome/browser/chromeos/policy/minimum_version_policy_handler.h" @@ -233,6 +234,9 @@ device_wallpaper_image_handler_ = std::make_unique<DeviceWallpaperImageHandler>(local_state, GetPolicyService()); + + device_wilco_dtc_configuration_handler_ = + std::make_unique<DeviceWilcoDtcConfigurationHandler>(GetPolicyService()); } void BrowserPolicyConnectorChromeOS::PreShutdown() { @@ -270,6 +274,9 @@ if (device_wallpaper_image_handler_) device_wallpaper_image_handler_->Shutdown(); + if (device_wilco_dtc_configuration_handler_) + device_wilco_dtc_configuration_handler_->Shutdown(); + ChromeBrowserPolicyConnector::Shutdown(); }
diff --git a/chrome/browser/chromeos/policy/browser_policy_connector_chromeos.h b/chrome/browser/chromeos/policy/browser_policy_connector_chromeos.h index 0a12d909..09d4ea1 100644 --- a/chrome/browser/chromeos/policy/browser_policy_connector_chromeos.h +++ b/chrome/browser/chromeos/policy/browser_policy_connector_chromeos.h
@@ -51,6 +51,7 @@ class DeviceWallpaperImageHandler; class ProxyPolicyProvider; class ServerBackedStateKeysBroker; +class DeviceWilcoDtcConfigurationHandler; // Extends ChromeBrowserPolicyConnector with the setup specific to Chrome OS. class BrowserPolicyConnectorChromeOS @@ -228,6 +229,8 @@ std::unique_ptr<MinimumVersionPolicyHandler> minimum_version_policy_handler_; std::unique_ptr<DeviceNativePrintersHandler> device_native_printers_handler_; std::unique_ptr<DeviceWallpaperImageHandler> device_wallpaper_image_handler_; + std::unique_ptr<DeviceWilcoDtcConfigurationHandler> + device_wilco_dtc_configuration_handler_; // This policy provider is used on Chrome OS to feed user policy into the // global PolicyService instance. This works by installing the cloud policy
diff --git a/chrome/browser/chromeos/policy/device_policy_decoder_chromeos.cc b/chrome/browser/chromeos/policy/device_policy_decoder_chromeos.cc index 67658cf..955ccc03 100644 --- a/chrome/browser/chromeos/policy/device_policy_decoder_chromeos.cc +++ b/chrome/browser/chromeos/policy/device_policy_decoder_chromeos.cc
@@ -799,6 +799,16 @@ external_data_manager, policies); } } + + if (policy.has_device_wilco_dtc_configuration()) { + const em::DeviceWilcoDtcConfigurationProto& container( + policy.device_wilco_dtc_configuration()); + if (container.has_device_wilco_dtc_configuration()) { + SetExternalDataDevicePolicy(key::kDeviceWilcoDtcConfiguration, + container.device_wilco_dtc_configuration(), + external_data_manager, policies); + } + } } void DecodeGenericPolicies(const em::ChromeDeviceSettingsProto& policy,
diff --git a/chrome/browser/chromeos/policy/device_wilco_dtc_configuration_handler.cc b/chrome/browser/chromeos/policy/device_wilco_dtc_configuration_handler.cc new file mode 100644 index 0000000..3b8e77b --- /dev/null +++ b/chrome/browser/chromeos/policy/device_wilco_dtc_configuration_handler.cc
@@ -0,0 +1,37 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/chromeos/policy/device_wilco_dtc_configuration_handler.h" + +#include "components/policy/policy_constants.h" + +namespace policy { + +DeviceWilcoDtcConfigurationHandler::DeviceWilcoDtcConfigurationHandler( + PolicyService* policy_service) + : device_wilco_dtc_configuration_observer_( + std::make_unique<DeviceCloudExternalDataPolicyObserver>( + policy_service, + key::kDeviceWilcoDtcConfiguration, + this)) {} + +DeviceWilcoDtcConfigurationHandler::~DeviceWilcoDtcConfigurationHandler() {} + +void DeviceWilcoDtcConfigurationHandler::OnDeviceExternalDataCleared( + const std::string& policy) { + // TODO(b/123933434): handle a data cleared event. +} + +void DeviceWilcoDtcConfigurationHandler::OnDeviceExternalDataFetched( + const std::string& policy, + std::unique_ptr<std::string> data, + const base::FilePath& file_path) { + // TODO(b/123933434): handle |data|. +} + +void DeviceWilcoDtcConfigurationHandler::Shutdown() { + device_wilco_dtc_configuration_observer_.reset(); +} + +} // namespace policy
diff --git a/chrome/browser/chromeos/policy/device_wilco_dtc_configuration_handler.h b/chrome/browser/chromeos/policy/device_wilco_dtc_configuration_handler.h new file mode 100644 index 0000000..211eabe4 --- /dev/null +++ b/chrome/browser/chromeos/policy/device_wilco_dtc_configuration_handler.h
@@ -0,0 +1,44 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CHROME_BROWSER_CHROMEOS_POLICY_DEVICE_WILCO_DTC_CONFIGURATION_HANDLER_H_ +#define CHROME_BROWSER_CHROMEOS_POLICY_DEVICE_WILCO_DTC_CONFIGURATION_HANDLER_H_ + +#include <memory> +#include <string> + +#include "base/macros.h" +#include "chrome/browser/chromeos/policy/device_cloud_external_data_policy_observer.h" + +namespace policy { + +class PolicyService; + +// This class observes the device setting "DeviceWilcoDtcConfiguration" and +// saves the wilco DTC (diagnostics and telemetry) controller configuration +// received in JSON format. +class DeviceWilcoDtcConfigurationHandler final + : public DeviceCloudExternalDataPolicyObserver::Delegate { + public: + explicit DeviceWilcoDtcConfigurationHandler(PolicyService* policy_service); + ~DeviceWilcoDtcConfigurationHandler() override; + + // DeviceCloudExternalDataPolicyObserver::Delegate: + void OnDeviceExternalDataCleared(const std::string& policy) override; + void OnDeviceExternalDataFetched(const std::string& policy, + std::unique_ptr<std::string> data, + const base::FilePath& file_path) override; + + void Shutdown(); + + private: + std::unique_ptr<DeviceCloudExternalDataPolicyObserver> + device_wilco_dtc_configuration_observer_; + + DISALLOW_COPY_AND_ASSIGN(DeviceWilcoDtcConfigurationHandler); +}; + +} // namespace policy + +#endif // CHROME_BROWSER_CHROMEOS_POLICY_DEVICE_WILCO_DTC_CONFIGURATION_HANDLER_H_
diff --git a/chrome/browser/chromeos/policy/status_uploader.cc b/chrome/browser/chromeos/policy/status_uploader.cc index 24cb4d9..3770773f 100644 --- a/chrome/browser/chromeos/policy/status_uploader.cc +++ b/chrome/browser/chromeos/policy/status_uploader.cc
@@ -32,6 +32,9 @@ const int kMinUploadDelayMs = 60 * 1000; // 60 seconds // Minimum delay after scheduling an upload const int kMinUploadScheduleDelayMs = 60 * 1000; // 60 seconds +// Minimum interval between the last upload and the next immediate upload +constexpr base::TimeDelta kMinImmediateUploadInterval = + base::TimeDelta::FromSeconds(10); } // namespace namespace policy { @@ -81,14 +84,19 @@ return false; } + base::Time now = base::Time::NowFromSystemTime(); + // Calculate when to fire off the next update (if it should have already // happened, this yields a TimeDelta of kMinUploadScheduleDelayMs). - base::TimeDelta delay = std::max( - (last_upload_ + upload_frequency_) - base::Time::NowFromSystemTime(), - base::TimeDelta::FromMilliseconds(kMinUploadScheduleDelayMs)); - // If we want an immediate status upload, set delay to 0. + base::TimeDelta delay = + std::max((last_upload_ + upload_frequency_) - now, + base::TimeDelta::FromMilliseconds(kMinUploadScheduleDelayMs)); + + // The next upload should be scheduled for at least + // kMinImmediateUploadInterval after the last upload if it is immediately. if (immediately) - delay = base::TimeDelta(); + delay = std::max((last_upload_ + kMinImmediateUploadInterval) - now, + base::TimeDelta()); upload_callback_.Reset(base::Bind(&StatusUploader::UploadStatus, base::Unretained(this)));
diff --git a/chrome/browser/chromeos/policy/status_uploader_unittest.cc b/chrome/browser/chromeos/policy/status_uploader_unittest.cc index 0df0282..e821eeea 100644 --- a/chrome/browser/chromeos/policy/status_uploader_unittest.cc +++ b/chrome/browser/chromeos/policy/status_uploader_unittest.cc
@@ -47,6 +47,8 @@ constexpr base::TimeDelta kDefaultStatusUploadDelay = base::TimeDelta::FromHours(1); +constexpr base::TimeDelta kMinImmediateUploadInterval = + base::TimeDelta::FromSeconds(10); class MockDeviceStatusCollector : public policy::DeviceStatusCollector { public: @@ -158,15 +160,17 @@ // upload should be queued. EXPECT_EQ(1U, task_runner_->NumPendingTasks()); - CheckPendingTaskDelay(uploader, expected_delay); + CheckPendingTaskDelay(uploader, expected_delay, + task_runner_->NextPendingTaskDelay()); } void CheckPendingTaskDelay(const StatusUploader& uploader, - base::TimeDelta expected_delay) { + base::TimeDelta expected_delay, + base::TimeDelta task_delay) { // The next task should be scheduled sometime between |last_upload| + // |expected_delay| and |now| + |expected_delay|. base::Time now = base::Time::NowFromSystemTime(); - base::Time next_task = now + task_runner_->NextPendingTaskDelay(); + base::Time next_task = now + task_delay; EXPECT_LE(next_task, now + expected_delay); EXPECT_GE(next_task, uploader.last_upload() + expected_delay); @@ -253,7 +257,8 @@ EXPECT_EQ(1U, task_runner_->NumPendingTasks()); // Check the delay of the queued upload - CheckPendingTaskDelay(uploader, kDefaultStatusUploadDelay); + CheckPendingTaskDelay(uploader, kDefaultStatusUploadDelay, + task_runner_->NextPendingTaskDelay()); } TEST_F(StatusUploaderTest, ResetTimerAfterUploadError) { @@ -294,7 +299,8 @@ // A task to try again should be queued. ASSERT_EQ(1U, task_runner_->NumPendingTasks()); - CheckPendingTaskDelay(uploader, kDefaultStatusUploadDelay); + CheckPendingTaskDelay(uploader, kDefaultStatusUploadDelay, + task_runner_->NextPendingTaskDelay()); } TEST_F(StatusUploaderTest, ChangeFrequency) { @@ -337,4 +343,44 @@ EXPECT_FALSE(uploader.IsSessionDataUploadAllowed()); } +TEST_F(StatusUploaderTest, ScheduleImmediateStatusUpload) { + EXPECT_FALSE(task_runner_->HasPendingTask()); + StatusUploader uploader(&client_, std::move(collector_), task_runner_, + kDefaultStatusUploadDelay); + EXPECT_EQ(1U, task_runner_->NumPendingTasks()); + + // On startup, first update should happen in 1 minute. + EXPECT_EQ(base::TimeDelta::FromMinutes(1), + task_runner_->NextPendingTaskDelay()); + + // Schedule an immediate status upload. + uploader.ScheduleNextStatusUploadImmediately(); + EXPECT_EQ(2U, task_runner_->NumPendingTasks()); + CheckPendingTaskDelay(uploader, base::TimeDelta(), + task_runner_->FinalPendingTaskDelay()); +} + +TEST_F(StatusUploaderTest, ScheduleImmediateStatusUploadConsecutively) { + EXPECT_FALSE(task_runner_->HasPendingTask()); + StatusUploader uploader(&client_, std::move(collector_), task_runner_, + kDefaultStatusUploadDelay); + EXPECT_EQ(1U, task_runner_->NumPendingTasks()); + + // On startup, first update should happen in 1 minute. + EXPECT_EQ(base::TimeDelta::FromMinutes(1), + task_runner_->NextPendingTaskDelay()); + + // Schedule an immediate status upload and run it. + uploader.ScheduleNextStatusUploadImmediately(); + RunPendingUploadTaskAndCheckNext(uploader, kDefaultStatusUploadDelay, + true /* upload_success */); + + // Schedule the next one and check that it was scheduled after + // kMinImmediateUploadInterval of the last upload. + uploader.ScheduleNextStatusUploadImmediately(); + EXPECT_EQ(2U, task_runner_->NumPendingTasks()); + CheckPendingTaskDelay(uploader, kMinImmediateUploadInterval, + task_runner_->FinalPendingTaskDelay()); +} + } // namespace policy
diff --git a/chrome/browser/component_updater/chrome_component_updater_configurator_unittest.cc b/chrome/browser/component_updater/chrome_component_updater_configurator_unittest.cc index 0c84ff2..e60b7abd 100644 --- a/chrome/browser/component_updater/chrome_component_updater_configurator_unittest.cc +++ b/chrome/browser/component_updater/chrome_component_updater_configurator_unittest.cc
@@ -122,8 +122,8 @@ const auto urls = config->UpdateUrl(); ASSERT_EQ(2u, urls.size()); - ASSERT_STREQ(kUpdaterDefaultUrl, urls[0].spec().c_str()); - ASSERT_STREQ(kUpdaterFallbackUrl, urls[1].spec().c_str()); + ASSERT_STREQ(kUpdaterJSONDefaultUrl, urls[0].spec().c_str()); + ASSERT_STREQ(kUpdaterJSONFallbackUrl, urls[1].spec().c_str()); ASSERT_EQ(config->UpdateUrl(), config->PingUrl()); @@ -134,7 +134,7 @@ ComponentUpdaterCommandLineConfigPolicy(cmdline), true); const auto urls = config.UpdateUrl(); ASSERT_EQ(1u, urls.size()); - ASSERT_STREQ(kUpdaterDefaultUrl, urls[0].spec().c_str()); + ASSERT_STREQ(kUpdaterJSONDefaultUrl, urls[0].spec().c_str()); ASSERT_EQ(config.UpdateUrl(), config.PingUrl()); } @@ -143,8 +143,8 @@ ComponentUpdaterCommandLineConfigPolicy(cmdline), false); const auto urls = config.UpdateUrl(); ASSERT_EQ(2u, urls.size()); - ASSERT_STREQ(kUpdaterDefaultUrl, urls[0].spec().c_str()); - ASSERT_STREQ(kUpdaterFallbackUrl, urls[1].spec().c_str()); + ASSERT_STREQ(kUpdaterJSONDefaultUrl, urls[0].spec().c_str()); + ASSERT_STREQ(kUpdaterJSONFallbackUrl, urls[1].spec().c_str()); ASSERT_EQ(config.UpdateUrl(), config.PingUrl()); } }
diff --git a/chrome/browser/devtools/devtools_ui_bindings.cc b/chrome/browser/devtools/devtools_ui_bindings.cc index 5555db7..9b93c31 100644 --- a/chrome/browser/devtools/devtools_ui_bindings.cc +++ b/chrome/browser/devtools/devtools_ui_bindings.cc
@@ -11,6 +11,7 @@ #include "base/base64.h" #include "base/bind.h" +#include "base/bind_helpers.h" #include "base/guid.h" #include "base/json/json_reader.h" #include "base/json/json_writer.h" @@ -603,7 +604,8 @@ base::EscapeJSONString(message, true, ¶m); base::string16 javascript = base::UTF8ToUTF16("DevToolsAPI.dispatchMessage(" + param + ");"); - web_contents_->GetMainFrame()->ExecuteJavaScript(javascript); + web_contents_->GetMainFrame()->ExecuteJavaScript(javascript, + base::NullCallback()); return; } @@ -1344,7 +1346,7 @@ } javascript.append(");"); web_contents_->GetMainFrame()->ExecuteJavaScript( - base::UTF8ToUTF16(javascript)); + base::UTF8ToUTF16(javascript), base::NullCallback()); } void DevToolsUIBindings::ReadyToCommitNavigation(
diff --git a/chrome/browser/devtools/devtools_window_testing.cc b/chrome/browser/devtools/devtools_window_testing.cc index 2bb49cd5..2589d6d 100644 --- a/chrome/browser/devtools/devtools_window_testing.cc +++ b/chrome/browser/devtools/devtools_window_testing.cc
@@ -5,6 +5,7 @@ #include "chrome/browser/devtools/devtools_window_testing.h" #include "base/bind.h" +#include "base/bind_helpers.h" #include "base/lazy_instance.h" #include "base/strings/utf_string_conversions.h" #include "chrome/browser/devtools/chrome_devtools_manager_delegate.h" @@ -112,7 +113,8 @@ } base::string16 harness = base::UTF8ToUTF16( content::DevToolsFrontendHost::GetFrontendResource(kHarnessScript)); - window->main_web_contents_->GetMainFrame()->ExecuteJavaScript(harness); + window->main_web_contents_->GetMainFrame()->ExecuteJavaScript( + harness, base::NullCallback()); } // static
diff --git a/chrome/browser/download/download_browsertest.cc b/chrome/browser/download/download_browsertest.cc index 5875f02..d71bc9d 100644 --- a/chrome/browser/download/download_browsertest.cc +++ b/chrome/browser/download/download_browsertest.cc
@@ -2613,7 +2613,7 @@ content::RenderFrameHost* render_frame_host = web_contents->GetMainFrame(); ASSERT_TRUE(render_frame_host != NULL); render_frame_host->ExecuteJavaScriptForTests( - base::ASCIIToUTF16("SubmitForm()")); + base::ASCIIToUTF16("SubmitForm()"), base::NullCallback()); observer.Wait(); EXPECT_EQ(jpeg_url, web_contents->GetURL()); @@ -3611,8 +3611,8 @@ base::string16 failed_title(base::UTF8ToUTF16("Loaded as main frame")); content::TitleWatcher title_watcher(web_contents, expected_title); title_watcher.AlsoWaitForTitle(failed_title); - render_frame_host->ExecuteJavaScriptForTests( - base::ASCIIToUTF16("runTest();")); + render_frame_host->ExecuteJavaScriptForTests(base::ASCIIToUTF16("runTest();"), + base::NullCallback()); ASSERT_EQ(expected_title, title_watcher.WaitAndGetTitle()); // Also verify that there's no download.
diff --git a/chrome/browser/extensions/alert_apitest.cc b/chrome/browser/extensions/alert_apitest.cc index a2d701d..9bf9b56 100644 --- a/chrome/browser/extensions/alert_apitest.cc +++ b/chrome/browser/extensions/alert_apitest.cc
@@ -5,6 +5,7 @@ #include <stddef.h> #include "base/bind.h" +#include "base/bind_helpers.h" #include "base/strings/string_number_conversions.h" #include "base/strings/utf_string_conversions.h" #include "chrome/browser/extensions/extension_apitest.h" @@ -77,7 +78,8 @@ ->GetBackgroundHostForExtension(extension->id()); ASSERT_TRUE(host); host->host_contents()->GetMainFrame()->ExecuteJavaScriptForTests( - base::ASCIIToUTF16("alert('This should not crash.');")); + base::ASCIIToUTF16("alert('This should not crash.');"), + base::NullCallback()); ASSERT_NO_FATAL_FAILURE(CloseDialog()); }
diff --git a/chrome/browser/extensions/api/enterprise_reporting_private/OWNERS b/chrome/browser/extensions/api/enterprise_reporting_private/OWNERS index 11fc6d2..50855db 100644 --- a/chrome/browser/extensions/api/enterprise_reporting_private/OWNERS +++ b/chrome/browser/extensions/api/enterprise_reporting_private/OWNERS
@@ -1,4 +1,3 @@ -georgesak@chromium.org mad@chromium.org pastarmovj@chromium.org zmin@chromium.org
diff --git a/chrome/browser/extensions/api/web_navigation/web_navigation_apitest.cc b/chrome/browser/extensions/api/web_navigation/web_navigation_apitest.cc index 04714c4..183514c 100644 --- a/chrome/browser/extensions/api/web_navigation/web_navigation_apitest.cc +++ b/chrome/browser/extensions/api/web_navigation/web_navigation_apitest.cc
@@ -6,6 +6,7 @@ #include <set> #include "base/bind.h" +#include "base/bind_helpers.h" #include "base/files/scoped_temp_dir.h" #include "base/macros.h" #include "base/memory/ref_counted.h" @@ -112,7 +113,8 @@ rfh_->ExecuteJavaScriptWithUserGestureForTests( base::UTF8ToUTF16(script_)); } else { - rfh_->ExecuteJavaScriptForTests(base::UTF8ToUTF16(script_)); + rfh_->ExecuteJavaScriptForTests(base::UTF8ToUTF16(script_), + base::NullCallback()); } script_was_executed_ = true; }
diff --git a/chrome/browser/geolocation/geolocation_browsertest.cc b/chrome/browser/geolocation/geolocation_browsertest.cc index 3de86fc..85d89493 100644 --- a/chrome/browser/geolocation/geolocation_browsertest.cc +++ b/chrome/browser/geolocation/geolocation_browsertest.cc
@@ -7,6 +7,7 @@ #include <string> #include "base/bind.h" +#include "base/bind_helpers.h" #include "base/compiler_specific.h" #include "base/macros.h" #include "base/run_loop.h" @@ -106,7 +107,7 @@ "window.domAutomationController.send(addIFrame(%d, \"%s\"));", iframe_id, url.spec().c_str())); web_contents->GetMainFrame()->ExecuteJavaScriptForTests( - base::UTF8ToUTF16(script)); + base::UTF8ToUTF16(script), base::NullCallback()); content::RunMessageLoop(); EXPECT_EQ(base::StringPrintf("\"%d\"", iframe_id), javascript_response_);
diff --git a/chrome/browser/media/webrtc/webrtc_video_high_bitrate_browsertest.cc b/chrome/browser/media/webrtc/webrtc_video_high_bitrate_browsertest.cc index 605b4d7..caea85e 100644 --- a/chrome/browser/media/webrtc/webrtc_video_high_bitrate_browsertest.cc +++ b/chrome/browser/media/webrtc/webrtc_video_high_bitrate_browsertest.cc
@@ -96,11 +96,11 @@ OpenPageAndGetUserMediaInNewTabWithConstraints( embedded_test_server()->GetURL(kMainWebrtcTestHtmlPage), "{audio: true, video: false}"); - SetupPeerconnectionWithLocalStream(left_tab); - SetupPeerconnectionWithLocalStream(right_tab); - const int target_bits_per_second = 80000; + const int target_bits_per_second = 50000; SetDefaultVideoTargetBitrate(left_tab, target_bits_per_second); SetDefaultVideoTargetBitrate(right_tab, target_bits_per_second); + SetupPeerconnectionWithLocalStream(left_tab); + SetupPeerconnectionWithLocalStream(right_tab); NegotiateCall(left_tab, right_tab); // Run the connection a bit to ramp up. @@ -131,10 +131,10 @@ (video_bytes_received_after - video_bytes_received_before) / duration_in_seconds; - perf_test::PrintResult("video", "", "send_rate", video_send_rate, + perf_test::PrintResult("video", "_high_bitrate", "send_rate", video_send_rate, "bytes/second", false); - perf_test::PrintResult("video", "", "receive_rate", video_receive_rate, - "bytes/second", false); + perf_test::PrintResult("video", "_high_bitrate", "receive_rate", + video_receive_rate, "bytes/second", false); HangUp(left_tab); HangUp(right_tab);
diff --git a/chrome/browser/memory/OWNERS b/chrome/browser/memory/OWNERS index a1f6d6a..f740939a32 100644 --- a/chrome/browser/memory/OWNERS +++ b/chrome/browser/memory/OWNERS
@@ -1,3 +1,2 @@ chrisha@chromium.org -georgesak@chromium.org cylee@chromium.org
diff --git a/chrome/browser/memory/memory_pressure_monitor_utils.cc b/chrome/browser/memory/memory_pressure_monitor_utils.cc new file mode 100644 index 0000000..1eedfb5 --- /dev/null +++ b/chrome/browser/memory/memory_pressure_monitor_utils.cc
@@ -0,0 +1,47 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/memory/memory_pressure_monitor_utils.h" + +#include "base/logging.h" + +namespace memory { + +FreeMemoryObservationWindow::FreeMemoryObservationWindow(const Config& config) + : ObservationWindow(config.window_length), config_(config) {} + +FreeMemoryObservationWindow::~FreeMemoryObservationWindow() = default; + +bool FreeMemoryObservationWindow::MemoryIsUnderEarlyLimit() { + return MemoryIsUnderLimitImpl(sample_below_early_limit_count_); +} + +bool FreeMemoryObservationWindow::MemoryIsUnderCriticalLimit() { + return MemoryIsUnderLimitImpl(sample_below_critical_limit_count_); +} + +void FreeMemoryObservationWindow::OnSampleAdded(const int& sample) { + if (sample < config_.low_memory_early_limit_mb) + ++sample_below_early_limit_count_; + if (sample < config_.low_memory_critical_limit_mb) + ++sample_below_critical_limit_count_; +} + +void FreeMemoryObservationWindow::OnSampleRemoved(const int& sample) { + if (sample < config_.low_memory_early_limit_mb) + --sample_below_early_limit_count_; + if (sample < config_.low_memory_critical_limit_mb) + --sample_below_critical_limit_count_; +} + +bool FreeMemoryObservationWindow::MemoryIsUnderLimitImpl( + size_t sample_under_limit_cnt) { + size_t sample_count = SampleCount(); + if (sample_count < config_.min_sample_count) + return false; + return (static_cast<float>(sample_under_limit_cnt) / sample_count) >= + config_.sample_ratio_to_be_positive; +} + +} // namespace memory
diff --git a/chrome/browser/memory/memory_pressure_monitor_utils.h b/chrome/browser/memory/memory_pressure_monitor_utils.h index 4a5d8bb..f9dcbaa2 100644 --- a/chrome/browser/memory/memory_pressure_monitor_utils.h +++ b/chrome/browser/memory/memory_pressure_monitor_utils.h
@@ -8,6 +8,7 @@ #include <deque> #include <utility> +#include "base/gtest_prod_util.h" #include "base/macros.h" #include "base/sequence_checker.h" #include "base/time/time.h" @@ -35,6 +36,9 @@ // first be removed, and then the new one will be added to it. void OnSample(const T sample); + // Returns the number of samples in this window. + size_t SampleCount() { return observations_.size(); } + protected: using Observation = std::pair<const base::TimeTicks, const T>; @@ -68,6 +72,62 @@ }; } // namespace internal + +// Implementation of an observation window that can be used to track the amount +// of free physical memory over time. The user is responsible for providing the +// samples via the |OnSample| method. +class FreeMemoryObservationWindow : public internal::ObservationWindow<int> { + public: + // Configuration of the observation window. The user is responsible for + // providing some appropriate values depending on how it implements the + // memory pressure detector. The values provided below are simple reasonable + // approximations of what value could be used here, they're not based on any + // metric. + struct Config { + const base::TimeDelta window_length = base::TimeDelta::FromMinutes(1); + + // The minimum number of samples to consider that the data in this window is + // meaningful. + const size_t min_sample_count = 4; + + // The ratio of samples that have to be below one of the thresholds to + // consider that the amount of free memory is really below this value. + const float sample_ratio_to_be_positive = 0.75; + + // Default value for the different thresholds, the users of this class will + // want to provide a more appropriate value here (based on the platform + // specs). The early limit is used to indicate that the memory is getting + // low and that more metrics should probably be tracked. The critical limit + // indicates that the system is low on memory and that performance will + // suffer. + const int low_memory_early_limit_mb = 600; + const int low_memory_critical_limit_mb = 400; + }; + + explicit FreeMemoryObservationWindow(const Config& config); + ~FreeMemoryObservationWindow() override; + + // Check if the memory is under one of the limits. + bool MemoryIsUnderEarlyLimit(); + bool MemoryIsUnderCriticalLimit(); + + private: + FRIEND_TEST_ALL_PREFIXES(ObservationWindowTest, FreeMemoryObservationWindow); + + void OnSampleAdded(const int& sample) override; + void OnSampleRemoved(const int& sample) override; + + bool MemoryIsUnderLimitImpl(size_t sample_under_limit_cnt); + + // The current number of samples that are below each threshold. + size_t sample_below_early_limit_count_ = 0; + size_t sample_below_critical_limit_count_ = 0; + + Config config_ = {}; + + DISALLOW_COPY_AND_ASSIGN(FreeMemoryObservationWindow); +}; + } // namespace memory #include "chrome/browser/memory/memory_pressure_monitor_utils_impl.h"
diff --git a/chrome/browser/memory/memory_pressure_monitor_utils_unittest.cc b/chrome/browser/memory/memory_pressure_monitor_utils_unittest.cc index 929e00be..b1f0ef94 100644 --- a/chrome/browser/memory/memory_pressure_monitor_utils_unittest.cc +++ b/chrome/browser/memory/memory_pressure_monitor_utils_unittest.cc
@@ -29,31 +29,43 @@ using internal::ObservationWindow<int>::observations_for_testing; using internal::ObservationWindow<int>::set_clock_for_testing; - bool Empty() { return observations_for_testing().empty(); } - MOCK_METHOD1(OnSampleAdded, void(const int& sample)); MOCK_METHOD1(OnSampleRemoved, void(const int& sample)); + + private: + DISALLOW_COPY_AND_ASSIGN(TestObservationWindow); }; -using ObservationWindowTest = testing::Test; +class ObservationWindowTest : public testing::Test { + public: + ObservationWindowTest() + : scoped_task_environment_( + base::test::ScopedTaskEnvironment::MainThreadType::MOCK_TIME), + tick_clock_(scoped_task_environment_.GetMockTickClock()) {} + ~ObservationWindowTest() override = default; + + protected: + base::test::ScopedTaskEnvironment scoped_task_environment_; + + const base::TickClock* tick_clock_; + + private: + DISALLOW_COPY_AND_ASSIGN(ObservationWindowTest); +}; TEST_F(ObservationWindowTest, OnSample) { - base::test::ScopedTaskEnvironment scoped_task_environment( - base::test::ScopedTaskEnvironment::MainThreadType::MOCK_TIME); - ::testing::StrictMock<TestObservationWindow> window; typedef decltype(window.observations_for_testing()) ObservationContainerType; - const auto* tick_clock = scoped_task_environment.GetMockTickClock(); - window.set_clock_for_testing(tick_clock); + window.set_clock_for_testing(tick_clock_); // The window is expected to be empty by default. - EXPECT_TRUE(window.Empty()); + EXPECT_TRUE(window.observations_for_testing().empty()); // Add a first sample. int t0_sample = 1; - base::TimeTicks t0_timestamp = tick_clock->NowTicks(); + base::TimeTicks t0_timestamp = tick_clock_->NowTicks(); EXPECT_CALL(window, OnSampleAdded(t0_sample)).Times(1); window.OnSample(t0_sample); @@ -68,10 +80,10 @@ // Fast forward by the length of the observation window, no sample should be // removed as all samples have an age that doesn't exceed the window length. - scoped_task_environment.FastForwardBy(kDefaultWindowLength); + scoped_task_environment_.FastForwardBy(kDefaultWindowLength); int t1_sample = 2; - base::TimeTicks t1_timestamp = tick_clock->NowTicks(); + base::TimeTicks t1_timestamp = tick_clock_->NowTicks(); EXPECT_CALL(window, OnSampleAdded(t1_sample)).Times(1); window.OnSample(t1_sample); @@ -86,10 +98,10 @@ // Fast forward by one second, the first sample should be removed the next // time a sample gets added as its age exceed the length of the observation // window. - scoped_task_environment.FastForwardBy(base::TimeDelta::FromSeconds(1)); + scoped_task_environment_.FastForwardBy(base::TimeDelta::FromSeconds(1)); int t2_sample = 3; - base::TimeTicks t2_timestamp = tick_clock->NowTicks(); + base::TimeTicks t2_timestamp = tick_clock_->NowTicks(); EXPECT_CALL(window, OnSampleAdded(t2_sample)).Times(1); EXPECT_CALL(window, OnSampleRemoved(t0_sample)).Times(1); @@ -103,4 +115,75 @@ })); } +TEST_F(ObservationWindowTest, FreeMemoryObservationWindow) { + FreeMemoryObservationWindow::Config window_config = {}; + FreeMemoryObservationWindow window(window_config); + window.set_clock_for_testing(tick_clock_); + + DCHECK_GT(window_config.low_memory_early_limit_mb, + window_config.low_memory_critical_limit_mb); + + // Fill the window with samples with a value higher than the higher limit. + for (size_t i = 0; i < window_config.min_sample_count; ++i) { + EXPECT_FALSE(window.MemoryIsUnderEarlyLimit()); + EXPECT_FALSE(window.MemoryIsUnderCriticalLimit()); + window.OnSample(window_config.low_memory_early_limit_mb + 1); + } + + // The window has enough samples to be evaluated but they're all above the + // thresholds. + EXPECT_FALSE(window.MemoryIsUnderEarlyLimit()); + EXPECT_FALSE(window.MemoryIsUnderCriticalLimit()); + + // Test the detection that the system has reached the early limit. + + // Remove all the observations from the window. + scoped_task_environment_.FastForwardBy(window_config.window_length + + base::TimeDelta::FromSeconds(1)); + + const size_t min_sample_count_to_be_positive = + static_cast<size_t>(window_config.sample_ratio_to_be_positive * + window_config.min_sample_count); + + DCHECK_GE(window_config.min_sample_count, min_sample_count_to_be_positive); + + for (size_t i = 0; + i < window_config.min_sample_count - min_sample_count_to_be_positive; + ++i) { + window.OnSample(window_config.low_memory_early_limit_mb + 1); + EXPECT_FALSE(window.MemoryIsUnderEarlyLimit()); + EXPECT_FALSE(window.MemoryIsUnderCriticalLimit()); + } + + for (size_t i = 0; i < min_sample_count_to_be_positive; ++i) { + EXPECT_FALSE(window.MemoryIsUnderEarlyLimit()); + EXPECT_FALSE(window.MemoryIsUnderCriticalLimit()); + window.OnSample(window_config.low_memory_early_limit_mb - 1); + } + EXPECT_TRUE(window.MemoryIsUnderEarlyLimit()); + EXPECT_FALSE(window.MemoryIsUnderCriticalLimit()); + + // Test the detection that the system has reached the critical limit. + + // Remove all the observations from the window. + scoped_task_environment_.FastForwardBy(window_config.window_length + + base::TimeDelta::FromSeconds(1)); + + for (size_t i = 0; + i < window_config.min_sample_count - min_sample_count_to_be_positive; + ++i) { + window.OnSample(window_config.low_memory_critical_limit_mb + 1); + EXPECT_FALSE(window.MemoryIsUnderEarlyLimit()); + EXPECT_FALSE(window.MemoryIsUnderCriticalLimit()); + } + + for (size_t i = 0; i < min_sample_count_to_be_positive; ++i) { + EXPECT_FALSE(window.MemoryIsUnderEarlyLimit()); + EXPECT_FALSE(window.MemoryIsUnderCriticalLimit()); + window.OnSample(window_config.low_memory_critical_limit_mb - 1); + } + EXPECT_TRUE(window.MemoryIsUnderEarlyLimit()); + EXPECT_TRUE(window.MemoryIsUnderCriticalLimit()); +} + } // namespace memory
diff --git a/chrome/browser/mouse_events_interactive_uitest.cc b/chrome/browser/mouse_events_interactive_uitest.cc index 224e5f9..242c912f 100644 --- a/chrome/browser/mouse_events_interactive_uitest.cc +++ b/chrome/browser/mouse_events_interactive_uitest.cc
@@ -2,6 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +#include "base/bind_helpers.h" #include "base/files/file_path.h" #include "base/macros.h" #include "base/run_loop.h" @@ -154,7 +155,8 @@ menu_observer.WaitForMenuOpenAndClose(); content::WebContents* tab = GetActiveWebContents(); - tab->GetMainFrame()->ExecuteJavaScriptForTests(base::ASCIIToUTF16("done()")); + tab->GetMainFrame()->ExecuteJavaScriptForTests(base::ASCIIToUTF16("done()"), + base::NullCallback()); const base::string16 success_title = base::ASCIIToUTF16("without mouseleave"); const base::string16 failure_title = base::ASCIIToUTF16("with mouseleave"); content::TitleWatcher done_title_watcher(tab, success_title); @@ -182,13 +184,15 @@ JavaScriptDialogTabHelper::FromWebContents(tab); base::RunLoop dialog_wait; js_helper->SetDialogShownCallbackForTesting(dialog_wait.QuitClosure()); - tab->GetMainFrame()->ExecuteJavaScriptForTests(base::UTF8ToUTF16("alert()")); + tab->GetMainFrame()->ExecuteJavaScriptForTests(base::UTF8ToUTF16("alert()"), + base::NullCallback()); dialog_wait.Run(); // Cancel the dialog. js_helper->HandleJavaScriptDialog(tab, false, nullptr); - tab->GetMainFrame()->ExecuteJavaScriptForTests(base::ASCIIToUTF16("done()")); + tab->GetMainFrame()->ExecuteJavaScriptForTests(base::ASCIIToUTF16("done()"), + base::NullCallback()); const base::string16 success_title = base::ASCIIToUTF16("without mouseleave"); const base::string16 failure_title = base::ASCIIToUTF16("with mouseleave"); content::TitleWatcher done_title_watcher(tab, success_title);
diff --git a/chrome/browser/net/errorpage_browsertest.cc b/chrome/browser/net/errorpage_browsertest.cc index fdeb0d7..4bdd5c24 100644 --- a/chrome/browser/net/errorpage_browsertest.cc +++ b/chrome/browser/net/errorpage_browsertest.cc
@@ -7,6 +7,7 @@ #include <utility> #include "base/bind.h" +#include "base/bind_helpers.h" #include "base/command_line.h" #include "base/compiler_specific.h" #include "base/feature_list.h" @@ -579,7 +580,8 @@ // notification that they've run, and scripts that trigger a navigation may // not send that notification. web_contents->GetMainFrame()->ExecuteJavaScriptForTests( - base::ASCIIToUTF16("document.getElementById('search-link').click();")); + base::ASCIIToUTF16("document.getElementById('search-link').click();"), + base::NullCallback()); nav_observer.Wait(); EXPECT_EQ(base::ASCIIToUTF16("Title Of More Awesomeness"), title_watcher.WaitAndGetTitle()); @@ -626,7 +628,8 @@ // notification that they've run, and scripts that trigger a navigation may // not send that notification. web_contents->GetMainFrame()->ExecuteJavaScriptForTests( - base::ASCIIToUTF16("document.getElementById('reload-button').click();")); + base::ASCIIToUTF16("document.getElementById('reload-button').click();"), + base::NullCallback()); nav_observer.Wait(); ExpectDisplayingNavigationCorrections(browser(), net::ERR_NAME_NOT_RESOLVED); @@ -657,7 +660,7 @@ // Do a same-document navigation on the error page, which should not result // in a new navigation. web_contents->GetMainFrame()->ExecuteJavaScriptForTests( - base::ASCIIToUTF16("document.location='#';")); + base::ASCIIToUTF16("document.location='#';"), base::NullCallback()); content::WaitForLoadStop(web_contents); // Page being displayed should not change. ExpectDisplayingNavigationCorrections(browser(), net::ERR_NAME_NOT_RESOLVED); @@ -671,7 +674,8 @@ // notification that they've run, and scripts that trigger a navigation may // not send that notification. web_contents->GetMainFrame()->ExecuteJavaScriptForTests( - base::ASCIIToUTF16("document.getElementById('reload-button').click();")); + base::ASCIIToUTF16("document.getElementById('reload-button').click();"), + base::NullCallback()); nav_observer2.Wait(); ExpectDisplayingNavigationCorrections(browser(), net::ERR_NAME_NOT_RESOLVED); @@ -706,12 +710,13 @@ // The tracking request is triggered by onmousedown, so it catches middle // mouse button clicks, as well as left clicks. web_contents->GetMainFrame()->ExecuteJavaScriptForTests( - base::ASCIIToUTF16(link_selector + ".onmousedown();")); + base::ASCIIToUTF16(link_selector + ".onmousedown();"), + base::NullCallback()); // Can't use content::ExecuteScript because it waits for scripts to send // notification that they've run, and scripts that trigger a navigation may // not send that notification. web_contents->GetMainFrame()->ExecuteJavaScriptForTests( - base::ASCIIToUTF16(link_selector + ".click();")); + base::ASCIIToUTF16(link_selector + ".click();"), base::NullCallback()); EXPECT_EQ(base::ASCIIToUTF16("Title Of Awesomeness"), title_watcher.WaitAndGetTitle()); @@ -796,7 +801,8 @@ content::WindowedNotificationObserver load_observer( content::NOTIFICATION_LOAD_STOP, content::Source<NavigationController>(&wc->GetController())); - wc->GetMainFrame()->ExecuteJavaScriptForTests(base::ASCIIToUTF16(script)); + wc->GetMainFrame()->ExecuteJavaScriptForTests(base::ASCIIToUTF16(script), + base::NullCallback()); load_observer.Wait(); // Ensure we saw the expected failure. @@ -816,7 +822,8 @@ content::WindowedNotificationObserver load_observer( content::NOTIFICATION_LOAD_STOP, content::Source<NavigationController>(&wc->GetController())); - wc->GetMainFrame()->ExecuteJavaScriptForTests(base::ASCIIToUTF16(script)); + wc->GetMainFrame()->ExecuteJavaScriptForTests(base::ASCIIToUTF16(script), + base::NullCallback()); load_observer.Wait(); } @@ -827,7 +834,8 @@ content::WindowedNotificationObserver load_observer( content::NOTIFICATION_LOAD_STOP, content::Source<NavigationController>(&wc->GetController())); - wc->GetMainFrame()->ExecuteJavaScriptForTests(base::ASCIIToUTF16(script)); + wc->GetMainFrame()->ExecuteJavaScriptForTests(base::ASCIIToUTF16(script), + base::NullCallback()); load_observer.Wait(); EXPECT_EQ(fail_url, fail_observer.fail_url()); @@ -1026,7 +1034,8 @@ browser()->tab_strip_model()->GetActiveWebContents(); content::TestNavigationObserver nav_observer(web_contents, 1); web_contents->GetMainFrame()->ExecuteJavaScriptForTests( - base::ASCIIToUTF16("document.getElementById('reload-button').click();")); + base::ASCIIToUTF16("document.getElementById('reload-button').click();"), + base::NullCallback()); nav_observer.Wait(); EXPECT_FALSE(IsDisplayingText( browser(), l10n_util::GetStringUTF8( @@ -1050,7 +1059,7 @@ content::WebContents* web_contents = browser()->tab_strip_model()->GetActiveWebContents(); web_contents->GetMainFrame()->ExecuteJavaScriptForTests( - base::ASCIIToUTF16("document.location='#';")); + base::ASCIIToUTF16("document.location='#';"), base::NullCallback()); content::WaitForLoadStop(web_contents); // Same-document navigation on an error page should not have resulted in a
diff --git a/chrome/browser/page_load_metrics/observers/ad_metrics/ads_page_load_metrics_observer_browsertest.cc b/chrome/browser/page_load_metrics/observers/ad_metrics/ads_page_load_metrics_observer_browsertest.cc index 2cd0535..7ab171b 100644 --- a/chrome/browser/page_load_metrics/observers/ad_metrics/ads_page_load_metrics_observer_browsertest.cc +++ b/chrome/browser/page_load_metrics/observers/ad_metrics/ads_page_load_metrics_observer_browsertest.cc
@@ -5,6 +5,7 @@ #include <string> #include "base/bind.h" +#include "base/bind_helpers.h" #include "base/macros.h" #include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" @@ -597,7 +598,8 @@ browser(), embedded_test_server()->GetURL("foo.com", "/frame_factory.html")); contents->GetMainFrame()->ExecuteJavaScriptForTests( - base::ASCIIToUTF16("createAdFrame('frame_factory.html', '');")); + base::ASCIIToUTF16("createAdFrame('frame_factory.html', '');"), + base::NullCallback()); // Two pages subresources should have been reported as ad. The iframe resource // and its three subresources should also be reported as ads. waiter->AddMinimumAdResourceExpectation(6); @@ -620,7 +622,8 @@ browser(), embedded_test_server()->GetURL("foo.com", "/frame_factory.html")); contents->GetMainFrame()->ExecuteJavaScriptForTests( - base::ASCIIToUTF16("createAdFrame('frame_factory.html', 'test');")); + base::ASCIIToUTF16("createAdFrame('frame_factory.html', 'test');"), + base::NullCallback()); waiter->AddMinimumAdResourceExpectation(6); waiter->Wait(); NavigateIframeToURL( @@ -1031,7 +1034,8 @@ GURL url = embedded_test_server()->GetURL("foo.com", "/frame_factory.html"); ui_test_utils::NavigateToURL(browser(), url); contents->GetMainFrame()->ExecuteJavaScriptForTests( - base::ASCIIToUTF16("createAdFrame('multiple_mimes.html', 'test');")); + base::ASCIIToUTF16("createAdFrame('multiple_mimes.html', 'test');"), + base::NullCallback()); waiter->AddMinimumAdResourceExpectation(8); waiter->Wait(); @@ -1103,7 +1107,8 @@ embedded_test_server()->GetURL(host_name, "/frame_factory.html")); content::TestNavigationObserver navigation_observer(web_contents()); contents->GetMainFrame()->ExecuteJavaScriptForTests( - base::ASCIIToUTF16("createFrame('download.html', 'test');")); + base::ASCIIToUTF16("createFrame('download.html', 'test');"), + base::NullCallback()); navigation_observer.Wait(); content::RenderFrameHost* rfh = content::FrameMatchingPredicate( @@ -1150,7 +1155,7 @@ std::string script = base::StringPrintf("createFrame('%s','test','');", subframe_url.c_str()); web_contents()->GetMainFrame()->ExecuteJavaScriptForTests( - base::ASCIIToUTF16(script)); + base::ASCIIToUTF16(script), base::NullCallback()); new_subframe_waiter.Wait(); GURL dld_url = embedded_test_server()->GetURL(origin1, "/allow.zip"); @@ -1243,7 +1248,7 @@ std::string script = base::StringPrintf( "%s('%s','%s',%s);", method, subframe_url.c_str(), id, sandbox_param); web_contents()->GetMainFrame()->ExecuteJavaScriptForTests( - base::ASCIIToUTF16(script)); + base::ASCIIToUTF16(script), base::NullCallback()); navigation_observer.Wait(); content::RenderFrameHost* child = content::FrameMatchingPredicate( @@ -1459,7 +1464,7 @@ url.c_str(), id, sandbox_param); contents->GetMainFrame()->ExecuteJavaScriptForTests( - base::ASCIIToUTF16(script)); + base::ASCIIToUTF16(script), base::NullCallback()); navigation_observer.Wait(); content::RenderFrameHost* rfh = content::FrameMatchingPredicate(
diff --git a/chrome/browser/plugins/flash_permission_browsertest.cc b/chrome/browser/plugins/flash_permission_browsertest.cc index 36539ff..021baa5 100644 --- a/chrome/browser/plugins/flash_permission_browsertest.cc +++ b/chrome/browser/plugins/flash_permission_browsertest.cc
@@ -2,6 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +#include "base/bind_helpers.h" #include "base/command_line.h" #include "base/path_service.h" #include "base/strings/utf_string_conversions.h" @@ -185,7 +186,8 @@ // Unlike the other tests, this JavaScript is called without a user gesture. GetWebContents()->GetMainFrame()->ExecuteJavaScriptForTests( - base::ASCIIToUTF16("triggerPromptWithMainFrameNavigation();")); + base::ASCIIToUTF16("triggerPromptWithMainFrameNavigation();"), + base::NullCallback()); EXPECT_TRUE(reload_waiter.Wait());
diff --git a/chrome/browser/policy/configuration_policy_handler_list_factory.cc b/chrome/browser/policy/configuration_policy_handler_list_factory.cc index d6c4ed7..ee81202 100644 --- a/chrome/browser/policy/configuration_policy_handler_list_factory.cc +++ b/chrome/browser/policy/configuration_policy_handler_list_factory.cc
@@ -1355,6 +1355,8 @@ std::make_unique<ExternalDataPolicyHandler>(key::kWallpaperImage)); handlers->AddHandler(std::make_unique<ExternalDataPolicyHandler>( key::kNativePrintersBulkConfiguration)); + handlers->AddHandler(std::make_unique<ExternalDataPolicyHandler>( + key::kDeviceWilcoDtcConfiguration)); handlers->AddHandler(base::WrapUnique(new SimpleSchemaValidatingPolicyHandler( key::kSessionLocales, NULL, chrome_schema, SCHEMA_STRICT, SimpleSchemaValidatingPolicyHandler::RECOMMENDED_ALLOWED,
diff --git a/chrome/browser/prefs/browser_prefs.cc b/chrome/browser/prefs/browser_prefs.cc index 3523036a..027f373 100644 --- a/chrome/browser/prefs/browser_prefs.cc +++ b/chrome/browser/prefs/browser_prefs.cc
@@ -973,4 +973,7 @@ // Added 2/2019. syncer::ClearObsoleteClearServerDataPrefs(profile_prefs); syncer::ClearObsoleteAuthErrorPrefs(profile_prefs); + + // Added 3/2019. + syncer::ClearObsoleteFirstSyncTime(profile_prefs); }
diff --git a/chrome/browser/prerender/prerender_browsertest.cc b/chrome/browser/prerender/prerender_browsertest.cc index e9522ad..42850317 100644 --- a/chrome/browser/prerender/prerender_browsertest.cc +++ b/chrome/browser/prerender/prerender_browsertest.cc
@@ -10,6 +10,7 @@ #include <vector> #include "base/bind.h" +#include "base/bind_helpers.h" #include "base/command_line.h" #include "base/files/file_path.h" #include "base/macros.h" @@ -660,14 +661,15 @@ void RemoveLinkElement(int i) const { GetActiveWebContents()->GetMainFrame()->ExecuteJavaScriptForTests( - base::ASCIIToUTF16(base::StringPrintf("RemoveLinkElement(%d)", i))); + base::ASCIIToUTF16(base::StringPrintf("RemoveLinkElement(%d)", i)), + base::NullCallback()); } void ClickToNextPageAfterPrerender() { TestNavigationObserver nav_observer(GetActiveWebContents()); RenderFrameHost* render_frame_host = GetActiveWebContents()->GetMainFrame(); render_frame_host->ExecuteJavaScriptForTests( - base::ASCIIToUTF16("ClickOpenLink()")); + base::ASCIIToUTF16("ClickOpenLink()"), base::NullCallback()); nav_observer.Wait(); } @@ -845,8 +847,8 @@ std::string javascript = base::StringPrintf( "AddPrerender('%s', %d)", url.spec().c_str(), index); RenderFrameHost* render_frame_host = GetActiveWebContents()->GetMainFrame(); - render_frame_host->ExecuteJavaScriptForTests( - base::ASCIIToUTF16(javascript)); + render_frame_host->ExecuteJavaScriptForTests(base::ASCIIToUTF16(javascript), + base::NullCallback()); } base::SimpleTestTickClock* OverridePrerenderManagerTimeTicks() { @@ -1001,7 +1003,7 @@ NavigationOrSwapObserver observer(current_browser()->tab_strip_model(), web_contents); render_frame_host->ExecuteJavaScriptForTests( - base::ASCIIToUTF16(javascript)); + base::ASCIIToUTF16(javascript), base::NullCallback()); observer.Wait(); } } @@ -2951,8 +2953,8 @@ // Check priority after swap. GetActiveWebContents()->GetMainFrame()->ExecuteJavaScriptForTests( - base::ASCIIToUTF16( - "var img=new Image(); img.src='/prerender/image.png'")); + base::ASCIIToUTF16("var img=new Image(); img.src='/prerender/image.png'"), + base::NullCallback()); WaitForRequestCount(after_swap_url, 1); EXPECT_NE(net::IDLE, after_swap_priority); }
diff --git a/chrome/browser/profiles/off_the_record_profile_io_data.cc b/chrome/browser/profiles/off_the_record_profile_io_data.cc index c19b171..d077469 100644 --- a/chrome/browser/profiles/off_the_record_profile_io_data.cc +++ b/chrome/browser/profiles/off_the_record_profile_io_data.cc
@@ -50,13 +50,6 @@ #include "extensions/common/extension.h" #endif -#if BUILDFLAG(ENABLE_REPORTING) -#include "net/network_error_logging/network_error_logging_delegate.h" -#include "net/network_error_logging/network_error_logging_service.h" -#include "net/reporting/reporting_policy.h" -#include "net/reporting/reporting_service.h" -#endif // BUILDFLAG(ENABLE_REPORTING) - using content::BrowserThread; OffTheRecordProfileIOData::Handle::Handle(Profile* profile)
diff --git a/chrome/browser/resources/chromeos/set_time/set_time.js b/chrome/browser/resources/chromeos/set_time/set_time.js index 9201d655..53d24c1 100644 --- a/chrome/browser/resources/chromeos/set_time/set_time.js +++ b/chrome/browser/resources/chromeos/set_time/set_time.js
@@ -65,6 +65,8 @@ $('set-time') .addEventListener('submit', this.onSubmit_.bind(this), false); + + chrome.send('setTimePageReady'); }, /**
diff --git a/chrome/browser/resources/feed_internals/feed_internals.css b/chrome/browser/resources/feed_internals/feed_internals.css index 37bdea5..ed7ffa5 100644 --- a/chrome/browser/resources/feed_internals/feed_internals.css +++ b/chrome/browser/resources/feed_internals/feed_internals.css
@@ -26,7 +26,8 @@ button { display: block; - min-height: 30px; + margin: 10px 0; + padding: 5px; } #current-content table td:first-child {
diff --git a/chrome/browser/resources/feed_internals/feed_internals.html b/chrome/browser/resources/feed_internals/feed_internals.html index ab69914..d93e1fe 100644 --- a/chrome/browser/resources/feed_internals/feed_internals.html +++ b/chrome/browser/resources/feed_internals/feed_internals.html
@@ -119,5 +119,14 @@ </template> </div> + <h2>Feed Process Scope</h2> + <button id="dump-feed-process-scope"> + Dump Feed Process Scope + </button> + <details id="feed-process-scope-details"> + <summary>Show/Hide</summary> + <pre id="feed-process-scope-dump"></pre> + </details> + </body> </html>
diff --git a/chrome/browser/resources/feed_internals/feed_internals.js b/chrome/browser/resources/feed_internals/feed_internals.js index 30d43c9..c1e48eec 100644 --- a/chrome/browser/resources/feed_internals/feed_internals.js +++ b/chrome/browser/resources/feed_internals/feed_internals.js
@@ -127,6 +127,13 @@ setTimeout(updatePageWithLastFetchProperties, 1000); setTimeout(updatePageWithCurrentContent, 1000); }); + + $('dump-feed-process-scope').addEventListener('click', function() { + pageHandler.getFeedProcessScopeDump().then(response => { + $('feed-process-scope-dump').textContent = response.dump; + $('feed-process-scope-details').open = true; + }); + }); } document.addEventListener('DOMContentLoaded', function() {
diff --git a/chrome/browser/resources/management/management_browser_proxy.js b/chrome/browser/resources/management/management_browser_proxy.js index d02cb65..25396e2 100644 --- a/chrome/browser/resources/management/management_browser_proxy.js +++ b/chrome/browser/resources/management/management_browser_proxy.js
@@ -38,7 +38,8 @@ DEVICE_ACTIVITY: 'device activity', STATISTIC: 'device statistics', DEVICE: 'device', - LOGS: 'logs' + LOGS: 'logs', + PRINT: 'print' };
diff --git a/chrome/browser/resources/management/management_ui.js b/chrome/browser/resources/management/management_ui.js index a669283..2cffd606 100644 --- a/chrome/browser/resources/management/management_ui.js +++ b/chrome/browser/resources/management/management_ui.js
@@ -162,6 +162,8 @@ return 'cr:computer'; case management.DeviceReportingType.LOGS: return 'management:report'; + case management.DeviceReportingType.PRINT: + return 'cr:print'; default: return 'cr:computer'; }
diff --git a/chrome/browser/resources/net_internals/browser_bridge.js b/chrome/browser/resources/net_internals/browser_bridge.js index 3938db7..af5a225 100644 --- a/chrome/browser/resources/net_internals/browser_bridge.js +++ b/chrome/browser/resources/net_internals/browser_bridge.js
@@ -97,6 +97,10 @@ this.send('storeDebugLogs'); }, + storeCombinedDebugLogs: function() { + this.send('storeCombinedDebugLogs'); + }, + setNetworkDebugMode: function(subsystem) { this.send('setNetworkDebugMode', [subsystem]); }, @@ -139,6 +143,12 @@ } }, + receivedStoreCombinedDebugLogs: function(status) { + for (let i = 0; i < this.storeDebugLogsObservers_.length; i++) { + this.storeDebugLogsObservers_[i].onStoreCombinedDebugLogs(status); + } + }, + receivedSetNetworkDebugMode: function(status) { for (let i = 0; i < this.setNetworkDebugModeObservers_.length; i++) { this.setNetworkDebugModeObservers_[i].onSetNetworkDebugMode(status); @@ -182,6 +192,7 @@ * back with: * * observer.onStoreDebugLogs(status); + * observer.onStoreCombinedDebugLogs(status); */ addStoreDebugLogsObserver: function(observer) { this.storeDebugLogsObservers_.push(observer);
diff --git a/chrome/browser/resources/net_internals/chromeos_view.html b/chrome/browser/resources/net_internals/chromeos_view.html index 5bce68e..b3b55b90 100644 --- a/chrome/browser/resources/net_internals/chromeos_view.html +++ b/chrome/browser/resources/net_internals/chromeos_view.html
@@ -15,12 +15,22 @@ </div> <div id="chromeos-view-store-debug-logs-div"> <h4>Store Logs</h4> - <input type="button" - id="chromeos-view-store-debug-logs" - value="Store Debug Logs"> - <label for="chromeos-view-store-debug-logs" - id="chromeos-view-store-debug-logs-status"> - </label> + <div> + <input type="button" + id="chromeos-view-store-debug-logs" + value="Store System Logs"> + <label for="chromeos-view-store-debug-logs" + id="chromeos-view-store-debug-logs-status"> + </label> + </div> + <div> + <input type="button" + id="chromeos-view-store-combined-debug-logs" + value="Store System and User Logs"> + <label for="chromeos-view-store-combined-debug-logs" + id="chromeos-view-store-combined-debug-logs-status"> + </label> + </div> </div> <div id="chromeos-view-network-debugging-div"> <h4>Network Debugging</h4>
diff --git a/chrome/browser/resources/net_internals/chromeos_view.js b/chrome/browser/resources/net_internals/chromeos_view.js index 7968a723..5999e6a 100644 --- a/chrome/browser/resources/net_internals/chromeos_view.js +++ b/chrome/browser/resources/net_internals/chromeos_view.js
@@ -119,6 +119,16 @@ $(CrosView.STORE_DEBUG_LOGS_STATUS_ID).innerText = status; } + + /** + * Set storing combined debug logs status. + * + * @private + */ + function setStoreCombinedDebugLogsStatus_(status) { + $(CrosView.STORE_COMBINED_DEBUG_LOGS_STATUS_ID).innerText = status; + } + /** * Set status for current debug mode. * @@ -162,6 +172,11 @@ $(CrosView.STORE_DEBUG_LOGS_STATUS_ID).innerText = ''; g_browser.storeDebugLogs(); }, false); + $(CrosView.STORE_COMBINED_DEBUG_LOGS_ID) + .addEventListener('click', function(event) { + $(CrosView.STORE_COMBINED_DEBUG_LOGS_STATUS_ID).innerText = ''; + g_browser.storeCombinedDebugLogs(); + }, false); $(CrosView.DEBUG_WIFI_ID).addEventListener('click', function(event) { setNetworkDebugMode_('wifi'); @@ -229,6 +244,10 @@ CrosView.PARSE_STATUS_ID = 'chromeos-view-parse-status'; CrosView.STORE_DEBUG_LOGS_ID = 'chromeos-view-store-debug-logs'; CrosView.STORE_DEBUG_LOGS_STATUS_ID = 'chromeos-view-store-debug-logs-status'; + CrosView.STORE_COMBINED_DEBUG_LOGS_ID = + 'chromeos-view-store-combined-debug-logs'; + CrosView.STORE_COMBINED_DEBUG_LOGS_STATUS_ID = + 'chromeos-view-store-combined-debug-logs-status'; CrosView.DEBUG_WIFI_ID = 'chromeos-view-network-debugging-wifi'; CrosView.DEBUG_ETHERNET_ID = 'chromeos-view-network-debugging-ethernet'; CrosView.DEBUG_CELLULAR_ID = 'chromeos-view-network-debugging-cellular'; @@ -244,6 +263,7 @@ onONCFileParse: setParseStatus_, onStoreDebugLogs: setStoreDebugLogsStatus_, + onStoreCombinedDebugLogs: setStoreCombinedDebugLogsStatus_, onSetNetworkDebugMode: setNetworkDebugModeStatus_, };
diff --git a/chrome/browser/resources/omnibox/omnibox_output.js b/chrome/browser/resources/omnibox/omnibox_output.js index bd4c0f4bbb..2d8cee79 100644 --- a/chrome/browser/resources/omnibox/omnibox_output.js +++ b/chrome/browser/resources/omnibox/omnibox_output.js
@@ -14,6 +14,9 @@ */ let ResultsDetails; + /** @typedef {Array<{key: string, value: string}>} */ + let KeyValuePair; + /** @param {!Element} element*/ function clearChildren(element) { while (element.firstChild) { @@ -820,11 +823,11 @@ } } - class OutputKeyValueTuplesProperty extends OutputJsonProperty { + class OutputAdditionalInfoProperty extends OutputJsonProperty { /** @private @override */ render_() { clearChildren(this.pre_); - this.value.forEach(({key, value}) => { + this.tuples_.forEach(({key, value}) => { this.pre_.appendChild( OutputJsonProperty.renderJsonWord(key + ': ', ['key'])); this.pre_.appendChild( @@ -834,9 +837,17 @@ /** @override @return {string} */ get text() { - return this.value.reduce( + return this.tuples_.reduce( (prev, {key, value}) => `${prev}${key}: ${value}\n`, ''); } + + /** @private @return {!KeyValuePair} */ + get tuples_() { + return [ + .../** @type {!KeyValuePair} */ (this.value), + {key: 'document_type', value: this.values_[1]} + ]; + } } class OutputUrlProperty extends FlexWrappingOutputProperty { @@ -1067,7 +1078,7 @@ new Column( ['Additional Info'], '', 'additionalInfo', false, 'Additional Info\nProvider-specific information about the result.', - ['additionalInfo'], OutputKeyValueTuplesProperty) + ['additionalInfo', 'documentType'], OutputAdditionalInfoProperty) ]; /** @type {!Column} */ @@ -1097,7 +1108,7 @@ customElements.define( 'output-json-property', OutputJsonProperty, {extends: 'td'}); customElements.define( - 'output-key-value-tuple-property', OutputKeyValueTuplesProperty, + 'output-additional-info-property', OutputAdditionalInfoProperty, {extends: 'td'}); customElements.define( 'output-url-property', OutputUrlProperty, {extends: 'td'});
diff --git a/chrome/browser/resources/pdf/ink/ink_api.js b/chrome/browser/resources/pdf/ink/ink_api.js index 4fd916d..b5efa32 100644 --- a/chrome/browser/resources/pdf/ink/ink_api.js +++ b/chrome/browser/resources/pdf/ink/ink_api.js
@@ -87,8 +87,32 @@ } dispatchPointerEvent(type, init) { + const engine = document.querySelector('#ink-engine'); + const match = engine.style.transform.match(/(\d+)deg/); + const rotation = match ? Number(match[1]) : 0; + let offsetX = init.clientX; + let offsetY = init.clientY; + // If Ink's canvas has been re-orientated away from 0, we must transform + // the event's offsetX and offsetY to correspond with the rotation and + // offset applied. + if ([90, 180, 270].includes(rotation)) { + const width = window.innerWidth; + const height = window.innerHeight; + const matrix = new DOMMatrix(); + matrix.translateSelf(width / 2, height / 2); + matrix.rotateSelf(0, 0, -rotation); + matrix.translateSelf(-width / 2, -height / 2); + const result = matrix.transformPoint({x: offsetX, y: offsetY}); + offsetX = result.x - engine.offsetLeft; + offsetY = result.y - engine.offsetTop; + } + const event = new PointerEvent(type, init); - document.querySelector('#ink-engine').dispatchEvent(event); + // Ink uses offsetX and offsetY, but we can only override them, not pass + // as part of the init. + Object.defineProperty(event, 'offsetX', {value: offsetX}); + Object.defineProperty(event, 'offsetY', {value: offsetY}); + engine.dispatchEvent(event); } undo() {
diff --git a/chrome/browser/safe_browsing/safe_browsing_blocking_page_test.cc b/chrome/browser/safe_browsing/safe_browsing_blocking_page_test.cc index e34f3b1..5911c8e 100644 --- a/chrome/browser/safe_browsing/safe_browsing_blocking_page_test.cc +++ b/chrome/browser/safe_browsing/safe_browsing_blocking_page_test.cc
@@ -12,6 +12,7 @@ #include <utility> #include "base/bind.h" +#include "base/bind_helpers.h" #include "base/command_line.h" #include "base/feature_list.h" #include "base/macros.h" @@ -702,8 +703,10 @@ // We don't use ExecuteScriptAndGetValue for this one, since clicking // the button/link may navigate away before the injected javascript can // reply, hanging the test. - rfh->ExecuteJavaScriptForTests(base::ASCIIToUTF16( - "document.getElementById('" + node_id + "').click();\n")); + rfh->ExecuteJavaScriptForTests( + base::ASCIIToUTF16("document.getElementById('" + node_id + + "').click();\n"), + base::NullCallback()); return true; }
diff --git a/chrome/browser/safe_browsing/safe_browsing_service_browsertest.cc b/chrome/browser/safe_browsing/safe_browsing_service_browsertest.cc index 649d3681..45174e9 100644 --- a/chrome/browser/safe_browsing/safe_browsing_service_browsertest.cc +++ b/chrome/browser/safe_browsing/safe_browsing_service_browsertest.cc
@@ -785,7 +785,8 @@ // a site that does not respond. Should show interstitial and have first page // in referrer. contents->GetMainFrame()->ExecuteJavaScriptForTests( - base::ASCIIToUTF16("navigateAndLoadMalwareImage()")); + base::ASCIIToUTF16("navigateAndLoadMalwareImage()"), + base::NullCallback()); load_stop_observer.Wait(); EXPECT_TRUE(ShowingInterstitialPage()); @@ -839,7 +840,8 @@ // While the top-level navigation is pending, run javascript // function in the page which loads the malware image. - rfh->ExecuteJavaScriptForTests(base::ASCIIToUTF16("loadMalwareImage()")); + rfh->ExecuteJavaScriptForTests(base::ASCIIToUTF16("loadMalwareImage()"), + base::NullCallback()); // Wait for interstitial to show. load_stop_observer.Wait(); @@ -869,7 +871,8 @@ content::RenderFrameHost* main_rfh = main_contents->GetMainFrame(); content::WebContentsAddedObserver web_contents_added_observer; - main_rfh->ExecuteJavaScriptForTests(base::ASCIIToUTF16("w=window.open();")); + main_rfh->ExecuteJavaScriptForTests(base::ASCIIToUTF16("w=window.open();"), + base::NullCallback()); WebContents* new_tab_contents = web_contents_added_observer.GetWebContents(); content::RenderFrameHost* new_tab_rfh = new_tab_contents->GetMainFrame(); // A fresh WebContents should not have any NavigationEntries yet. (See @@ -883,8 +886,10 @@ new_tab_rfh->ExecuteJavaScriptForTests( base::ASCIIToUTF16("var img=new Image();" "img.src=\"" + - img_url.spec() + "\";" - "document.body.appendChild(img);")); + img_url.spec() + + "\";" + "document.body.appendChild(img);"), + base::NullCallback()); // Wait for interstitial to show. content::WaitForInterstitialAttach(new_tab_contents);
diff --git a/chrome/browser/signin/profile_oauth2_token_service_factory.cc b/chrome/browser/signin/profile_oauth2_token_service_factory.cc index b8b17b2..974a9b0 100644 --- a/chrome/browser/signin/profile_oauth2_token_service_factory.cc +++ b/chrome/browser/signin/profile_oauth2_token_service_factory.cc
@@ -35,9 +35,9 @@ #if defined(OS_CHROMEOS) #include "chrome/browser/browser_process.h" #include "chrome/browser/chromeos/account_manager/account_manager_util.h" -#include "chrome/browser/chromeos/oauth2_token_service_delegate.h" #include "chrome/browser/chromeos/profiles/profile_helper.h" #include "chromeos/account_manager/account_manager_factory.h" +#include "components/signin/core/browser/profile_oauth2_token_service_delegate_chromeos.h" #include "components/user_manager/user_manager.h" #endif // defined(OS_CHROMEOS) @@ -48,7 +48,7 @@ namespace { #if defined(OS_CHROMEOS) -std::unique_ptr<chromeos::ChromeOSOAuth2TokenServiceDelegate> +std::unique_ptr<signin::ProfileOAuth2TokenServiceDelegateChromeOS> CreateCrOsOAuthDelegate(Profile* profile) { chromeos::AccountManagerFactory* factory = g_browser_process->platform_part()->GetAccountManagerFactory(); @@ -57,7 +57,7 @@ factory->GetAccountManager(profile->GetPath().value()); DCHECK(account_manager); - return std::make_unique<chromeos::ChromeOSOAuth2TokenServiceDelegate>( + return std::make_unique<signin::ProfileOAuth2TokenServiceDelegateChromeOS>( AccountTrackerServiceFactory::GetInstance()->GetForProfile(profile), content::GetNetworkConnectionTracker(), account_manager); } @@ -126,8 +126,8 @@ // Fall back to |MutableProfileOAuth2TokenServiceDelegate|: // 1. On all platforms other than Android and Chrome OS. - // 2. On Chrome OS, if |ChromeOSOAuth2TokenServiceDelegate| cannot be used - // for this |profile|. See |chromeos::IsAccountManagerAvailable|. + // 2. On Chrome OS, if |ProfileOAuth2TokenServiceDelegateChromeOS| cannot be + // used for this |profile|. See |chromeos::IsAccountManagerAvailable|. return CreateMutableProfileOAuthDelegate(profile); #endif // defined(OS_ANDROID)
diff --git a/chrome/browser/supervised_user/supervised_user_browsertest.cc b/chrome/browser/supervised_user/supervised_user_browsertest.cc index 447a060..dd3a3ac4 100644 --- a/chrome/browser/supervised_user/supervised_user_browsertest.cc +++ b/chrome/browser/supervised_user/supervised_user_browsertest.cc
@@ -5,6 +5,7 @@ #include <utility> #include "base/bind.h" +#include "base/bind_helpers.h" #include "base/command_line.h" #include "base/feature_list.h" #include "base/run_loop.h" @@ -121,8 +122,10 @@ void SendAccessRequest(WebContents* tab) { if (AreCommittedInterstitialsEnabled()) { - tab->GetMainFrame()->ExecuteJavaScriptForTests(base::ASCIIToUTF16( - "supervisedUserErrorPageController.requestPermission()")); + tab->GetMainFrame()->ExecuteJavaScriptForTests( + base::ASCIIToUTF16( + "supervisedUserErrorPageController.requestPermission()"), + base::NullCallback()); return; } @@ -140,7 +143,8 @@ void GoBack(WebContents* tab) { if (AreCommittedInterstitialsEnabled()) { tab->GetMainFrame()->ExecuteJavaScriptForTests( - base::ASCIIToUTF16("supervisedUserErrorPageController.goBack()")); + base::ASCIIToUTF16("supervisedUserErrorPageController.goBack()"), + base::NullCallback()); return; } InterstitialPage* interstitial_page = tab->GetInterstitialPage();
diff --git a/chrome/browser/supervised_user/supervised_user_interstitial.cc b/chrome/browser/supervised_user/supervised_user_interstitial.cc index 1126b3e5..d4d500d 100644 --- a/chrome/browser/supervised_user/supervised_user_interstitial.cc +++ b/chrome/browser/supervised_user/supervised_user_interstitial.cc
@@ -7,6 +7,7 @@ #include <stddef.h> #include "base/bind.h" +#include "base/bind_helpers.h" #include "base/memory/weak_ptr.h" #include "base/metrics/histogram_macros.h" #include "base/scoped_observer.h" @@ -356,7 +357,7 @@ base::StringPrintf("setRequestStatus(%s);", success ? "true" : "false"); if (interstitial_page_->GetMainFrame()) { interstitial_page_->GetMainFrame()->ExecuteJavaScript( - base::ASCIIToUTF16(jsFunc)); + base::ASCIIToUTF16(jsFunc), base::NullCallback()); } }
diff --git a/chrome/browser/sync/sync_ui_util.cc b/chrome/browser/sync/sync_ui_util.cc index ffd4bd9..466cee7b 100644 --- a/chrome/browser/sync/sync_ui_util.cc +++ b/chrome/browser/sync/sync_ui_util.cc
@@ -23,29 +23,6 @@ namespace { -// Returns the message that should be displayed when the user is authenticated -// and can connect to the sync server. If Sync hasn't finished initializing yet, -// an empty string is returned. -base::string16 GetSyncedStateStatusLabel(const syncer::SyncService* service) { - DCHECK(service); - if (service->HasDisableReason( - syncer::SyncService::DISABLE_REASON_ENTERPRISE_POLICY)) { - return l10n_util::GetStringUTF16(IDS_SIGNED_IN_WITH_SYNC_DISABLED); - } - if (!service->GetUserSettings()->IsSyncRequested()) { - return l10n_util::GetStringUTF16(IDS_SIGNED_IN_WITH_SYNC_SUPPRESSED); - } - if (!service->IsSyncFeatureActive()) { - // Sync is still initializing. - return base::string16(); - } - - return l10n_util::GetStringUTF16( - service->GetUserSettings()->IsSyncEverythingEnabled() - ? IDS_SYNC_ACCOUNT_SYNCING - : IDS_SYNC_ACCOUNT_SYNCING_CUSTOM_DATA_TYPES); -} - // Returns whether there is a non-empty status for the given |action|. bool GetStatusForActionableError(syncer::ClientAction action, base::string16* status_label, @@ -64,12 +41,6 @@ *action_type = UPGRADE_CLIENT; } return true; - case syncer::ENABLE_SYNC_ON_ACCOUNT: - if (status_label) { - *status_label = - l10n_util::GetStringUTF16(IDS_SYNC_STATUS_ENABLE_SYNC_ON_ACCOUNT); - } - return true; default: if (status_label) { *status_label = base::string16(); @@ -155,6 +126,12 @@ } } +syncer::ClientAction GetClientAction(const syncer::SyncService* service) { + syncer::SyncStatus status; + service->QueryDetailedSyncStatus(&status); + return status.sync_protocol_error.action; +} + MessageType GetStatusLabelsImpl( const syncer::SyncService* service, bool is_user_signout_allowed, @@ -172,13 +149,11 @@ // primary (or any) account. DCHECK(!service->IsLocalSyncEnabled()); - syncer::SyncStatus status; - service->QueryDetailedSyncStatus(&status); + syncer::ClientAction client_action = GetClientAction(service); // First check for an unrecoverable error. if (service->HasUnrecoverableError()) { - GetStatusForUnrecoverableError(is_user_signout_allowed, - status.sync_protocol_error.action, + GetStatusForUnrecoverableError(is_user_signout_allowed, client_action, status_label, link_label, action_type); return SYNC_ERROR; } @@ -197,8 +172,8 @@ service->HasDisableReason( syncer::SyncService::DISABLE_REASON_ENTERPRISE_POLICY)) { // Check for an actionable protocol error. - if (GetStatusForActionableError(status.sync_protocol_error.action, - status_label, link_label, action_type)) { + if (GetStatusForActionableError(client_action, status_label, link_label, + action_type)) { return SYNC_ERROR; } @@ -218,21 +193,38 @@ return SYNC_ERROR; } - // At this point, there is no Sync error, but there might still be a message - // we want to show. - // TODO(crbug.com/911153): This also covers the "disabled by policy" and - // "not requested" cases, which doesn't seem right. - if (status_label) { - *status_label = GetSyncedStateStatusLabel(service); + if (service->HasDisableReason( + syncer::SyncService::DISABLE_REASON_ENTERPRISE_POLICY)) { + if (status_label) { + *status_label = + l10n_util::GetStringUTF16(IDS_SIGNED_IN_WITH_SYNC_DISABLED); + } + // TODO(crbug.com/911153): Is SYNCED correct for this case? + return SYNCED; } - // Check to see if sync has been disabled via the dasboard and needs to be + // Check to see if sync has been disabled via the dashboard and needs to be // set up once again. - if (!service->GetUserSettings()->IsSyncRequested() && - status.sync_protocol_error.error_type == syncer::NOT_MY_BIRTHDAY) { + if (!service->GetUserSettings()->IsSyncRequested()) { + if (status_label) { + *status_label = + l10n_util::GetStringUTF16(IDS_SIGNED_IN_WITH_SYNC_SUPPRESSED); + } return PRE_SYNCED; } + // At this point, there is no Sync error. + if (status_label) { + if (service->IsSyncFeatureActive()) { + *status_label = l10n_util::GetStringUTF16( + service->GetUserSettings()->IsSyncEverythingEnabled() + ? IDS_SYNC_ACCOUNT_SYNCING + : IDS_SYNC_ACCOUNT_SYNCING_CUSTOM_DATA_TYPES); + } else { + // Sync s still initializing. + *status_label = base::string16(); + } + } return SYNCED; } @@ -296,9 +288,7 @@ // An unrecoverable error is sometimes accompanied by an actionable error. // If an actionable error is not set to be UPGRADE_CLIENT, then show a // generic unrecoverable error message. - syncer::SyncStatus status; - service->QueryDetailedSyncStatus(&status); - if (status.sync_protocol_error.action != syncer::UPGRADE_CLIENT) { + if (GetClientAction(service) != syncer::UPGRADE_CLIENT) { // Display different messages and buttons for managed accounts. if (!signin_util::IsUserSignoutAllowedForProfile(profile)) { // For a managed user, the user is directed to the signout @@ -328,9 +318,7 @@ // Check for sync errors if the sync service is enabled. if (service) { // Check for an actionable UPGRADE_CLIENT error. - syncer::SyncStatus status; - service->QueryDetailedSyncStatus(&status); - if (status.sync_protocol_error.action == syncer::UPGRADE_CLIENT) { + if (GetClientAction(service) == syncer::UPGRADE_CLIENT) { *content_string_id = IDS_SYNC_ERROR_USER_MENU_UPGRADE_MESSAGE; *button_string_id = IDS_SYNC_ERROR_USER_MENU_UPGRADE_BUTTON; return UPGRADE_CLIENT_ERROR;
diff --git a/chrome/browser/sync/sync_ui_util_unittest.cc b/chrome/browser/sync/sync_ui_util_unittest.cc index c2e9ef2..5a28a75 100644 --- a/chrome/browser/sync/sync_ui_util_unittest.cc +++ b/chrome/browser/sync/sync_ui_util_unittest.cc
@@ -257,29 +257,14 @@ status.sync_protocol_error.action = syncer::UPGRADE_CLIENT; service->SetDetailedSyncStatus(true, status); - base::string16 first_actionable_error_status_label; + base::string16 actionable_error_status_label; base::string16 link_label; sync_ui_util::ActionType action_type = sync_ui_util::NO_ACTION; - sync_ui_util::GetStatusLabels(profile.get(), - &first_actionable_error_status_label, + sync_ui_util::GetStatusLabels(profile.get(), &actionable_error_status_label, &link_label, &action_type); // Expect a 'client upgrade' call to action. EXPECT_EQ(sync_ui_util::UPGRADE_CLIENT, action_type); - - // This time set action to ENABLE_SYNC_ON_ACCOUNT. - status.sync_protocol_error.action = syncer::ENABLE_SYNC_ON_ACCOUNT; - service->SetDetailedSyncStatus(true, status); - - base::string16 second_actionable_error_status_label; - action_type = sync_ui_util::NO_ACTION; - sync_ui_util::GetStatusLabels(profile.get(), - &second_actionable_error_status_label, - &link_label, &action_type); - // Expect a passive message instead of a call to action. - EXPECT_EQ(sync_ui_util::NO_ACTION, action_type); - - EXPECT_NE(first_actionable_error_status_label, - second_actionable_error_status_label); + EXPECT_NE(actionable_error_status_label, base::string16()); } TEST_F(SyncUIUtilTest, SyncSettingsConfirmationNeededTest) {
diff --git a/chrome/browser/sync/test/integration/single_client_polling_sync_test.cc b/chrome/browser/sync/test/integration/single_client_polling_sync_test.cc index 8701d5d1..94800da 100644 --- a/chrome/browser/sync/test/integration/single_client_polling_sync_test.cc +++ b/chrome/browser/sync/test/integration/single_client_polling_sync_test.cc
@@ -35,26 +35,23 @@ DISALLOW_COPY_AND_ASSIGN(SingleClientPollingSyncTest); }; -// This test verifies that the poll intervals in prefs get initialized if no +// This test verifies that the poll interval in prefs gets initialized if no // data is available yet. IN_PROC_BROWSER_TEST_F(SingleClientPollingSyncTest, ShouldInitializePollPrefs) { - // Setup clients and verify no poll intervals are present yet. + // Setup clients and verify no poll interval is present yet. ASSERT_TRUE(SetupClients()) << "SetupClients() failed."; SyncPrefs sync_prefs(GetProfile(0)->GetPrefs()); - EXPECT_TRUE(sync_prefs.GetShortPollInterval().is_zero()); - EXPECT_TRUE(sync_prefs.GetLongPollInterval().is_zero()); + EXPECT_TRUE(sync_prefs.GetPollInterval().is_zero()); ASSERT_TRUE(sync_prefs.GetLastPollTime().is_null()); // Execute a sync cycle and verify the client set up (and persisted) the - // default values. + // default value. ASSERT_TRUE(SetupSync()) << "SetupSync() failed."; - EXPECT_THAT(sync_prefs.GetShortPollInterval().InSeconds(), - Eq(syncer::kDefaultShortPollIntervalSeconds)); - EXPECT_THAT(sync_prefs.GetLongPollInterval().InSeconds(), - Eq(syncer::kDefaultLongPollIntervalSeconds)); + EXPECT_THAT(sync_prefs.GetPollInterval().InSeconds(), + Eq(syncer::kDefaultPollIntervalSeconds)); } -// This test verifies that updates of the poll intervals get persisted +// This test verifies that updates of the poll interval get persisted // That's important make sure clients with short live times will eventually poll // (e.g. Android). IN_PROC_BROWSER_TEST_F(SingleClientPollingSyncTest, ShouldUpdatePollPrefs) { @@ -62,7 +59,6 @@ sync_pb::ClientCommand client_command; client_command.set_set_sync_poll_interval(67); - client_command.set_set_sync_long_poll_interval(199); GetFakeServer()->SetClientCommand(client_command); // Trigger a sync-cycle. @@ -75,28 +71,22 @@ ASSERT_TRUE(checker.Wait()); SyncPrefs sync_prefs(GetProfile(0)->GetPrefs()); - EXPECT_THAT(sync_prefs.GetShortPollInterval().InSeconds(), Eq(67)); - EXPECT_THAT(sync_prefs.GetLongPollInterval().InSeconds(), Eq(199)); + EXPECT_THAT(sync_prefs.GetPollInterval().InSeconds(), Eq(67)); } IN_PROC_BROWSER_TEST_F(SingleClientPollingSyncTest, - ShouldUsePollIntervalsFromPrefs) { - // Setup clients and provide new poll intervals via prefs. + ShouldUsePollIntervalFromPrefs) { + // Setup clients and provide new poll interval via prefs. ASSERT_TRUE(SetupClients()) << "SetupClients() failed."; SyncPrefs sync_prefs(GetProfile(0)->GetPrefs()); - sync_prefs.SetShortPollInterval(base::TimeDelta::FromSeconds(123)); - sync_prefs.SetLongPollInterval(base::TimeDelta::FromSeconds(1234)); + sync_prefs.SetPollInterval(base::TimeDelta::FromSeconds(123)); - // Execute a sync cycle and verify this cycle used those intervals. - // This test assumes the SyncScheduler reads the actual intervals from the + // Execute a sync cycle and verify this cycle used that interval. + // This test assumes the SyncScheduler reads the actual interval from the // context. This is covered in the SyncSchedulerImpl's unittest. ASSERT_TRUE(SetupSync()) << "SetupSync() failed."; - EXPECT_THAT( - GetClient(0)->GetLastCycleSnapshot().short_poll_interval().InSeconds(), - Eq(123)); - EXPECT_THAT( - GetClient(0)->GetLastCycleSnapshot().long_poll_interval().InSeconds(), - Eq(1234)); + EXPECT_THAT(GetClient(0)->GetLastCycleSnapshot().poll_interval().InSeconds(), + Eq(123)); } // This test simulates the poll interval expiring between restarts. @@ -112,11 +102,10 @@ ASSERT_TRUE(SetupClients()) << "SetupClients() failed."; SyncPrefs remote_prefs(GetProfile(0)->GetPrefs()); - // Set small polling intervals to make random delays introduced in + // Set small polling interval to make random delays introduced in // SyncSchedulerImpl::ComputeLastPollOnStart() negligible, but big enough to // avoid periodic polls during a test run. - remote_prefs.SetLongPollInterval(base::TimeDelta::FromSeconds(300)); - remote_prefs.SetShortPollInterval(base::TimeDelta::FromSeconds(300)); + remote_prefs.SetPollInterval(base::TimeDelta::FromSeconds(300)); ASSERT_TRUE(SetupSync()) << "SetupSync() failed."; @@ -135,7 +124,7 @@ // Simulate elapsed time so that the poll interval expired upon restart. remote_prefs.SetLastPollTime(base::Time::Now() - - remote_prefs.GetLongPollInterval()); + remote_prefs.GetPollInterval()); } IN_PROC_BROWSER_TEST_F(SingleClientPollingSyncTest,
diff --git a/chrome/browser/sync/test/integration/sync_test.cc b/chrome/browser/sync/test/integration/sync_test.cc index 14dbad5..843bdb17 100644 --- a/chrome/browser/sync/test/integration/sync_test.cc +++ b/chrome/browser/sync/test/integration/sync_test.cc
@@ -63,6 +63,7 @@ #include "components/sync/base/invalidation_helper.h" #include "components/sync/driver/sync_driver_switches.h" #include "components/sync/driver/sync_user_settings.h" +#include "components/sync/engine/sync_engine_switches.h" #include "components/sync/engine_impl/sync_scheduler_impl.h" #include "components/sync/protocol/sync.pb.h" #include "components/sync/test/fake_server/fake_server_network_resources.h" @@ -304,6 +305,13 @@ if (!cl->HasSwitch(switches::kSyncShortNudgeDelayForTest)) cl->AppendSwitch(switches::kSyncShortNudgeDelayForTest); + // TODO(crbug.com/657130): This a temporary switch because sync integration + // tests depend on the precommit get updates because invalidations aren't + // working for them. Therefore, they pass the command line switch to enable + // this feature. Once sync integrations test support invalidation, this + // should be removed. + if (!cl->HasSwitch(switches::kSyncEnableGetUpdatesBeforeCommit)) + cl->AppendSwitch(switches::kSyncEnableGetUpdatesBeforeCommit); } bool SyncTest::CreateGaiaAccount(const std::string& username,
diff --git a/chrome/browser/sync/test/integration/two_client_polling_sync_test.cc b/chrome/browser/sync/test/integration/two_client_polling_sync_test.cc index a3e1c44..85519c9 100644 --- a/chrome/browser/sync/test/integration/two_client_polling_sync_test.cc +++ b/chrome/browser/sync/test/integration/two_client_polling_sync_test.cc
@@ -65,16 +65,15 @@ // Because the initial run of sync is doing a number of extra sync cycles, // this test is structured in 2 phases. In the first phase, we simply bring // up two clients and have them sync some data. -// In the seconed phase, we take down client 1 and while it's down upload more +// In the second phase, we take down client 1 and while it's down upload more // data from client 0. That second phase will rely on polling on client 1 to // receive the update. IN_PROC_BROWSER_TEST_F(TwoClientPollingSyncTest, ShouldPollOnStartup) { ASSERT_TRUE(SetupClients()) << "SetupClients() failed."; - // Choose larger intervals to verify the poll-on-start logic. + // Choose larger interval to verify the poll-on-start logic. SyncPrefs remote_prefs(GetProfile(1)->GetPrefs()); - remote_prefs.SetShortPollInterval(base::TimeDelta::FromMinutes(2)); - remote_prefs.SetLongPollInterval(base::TimeDelta::FromMinutes(2)); + remote_prefs.SetPollInterval(base::TimeDelta::FromMinutes(2)); ASSERT_TRUE(SetupSync()) << "SetupSync() failed."; @@ -104,7 +103,7 @@ // Phase 2. // Disconnect client 1 from sync and write another change from client 0. - // Disconnnect the remote client from the invalidation service. + // Disconnect the remote client from the invalidation service. DisableNotificationsForClient(1); // Make sure no extra sync cycles get triggered by test infrastructure. StopConfigurationRefresher();
diff --git a/chrome/browser/task_manager/task_manager_browsertest.cc b/chrome/browser/task_manager/task_manager_browsertest.cc index bf230e0..0698cb5 100644 --- a/chrome/browser/task_manager/task_manager_browsertest.cc +++ b/chrome/browser/task_manager/task_manager_browsertest.cc
@@ -6,6 +6,7 @@ #include <vector> #include "base/bind.h" +#include "base/bind_helpers.h" #include "base/files/file_path.h" #include "base/macros.h" #include "base/path_service.h" @@ -692,7 +693,8 @@ ->tab_strip_model() ->GetActiveWebContents() ->GetMainFrame() - ->ExecuteJavaScriptForTests(base::UTF8ToUTF16(test_js)); + ->ExecuteJavaScriptForTests(base::UTF8ToUTF16(test_js), + base::NullCallback()); ASSERT_NO_FATAL_FAILURE(WaitForTaskManagerStatToExceed( MatchTab("network use"), ColumnSpecifier::TOTAL_NETWORK_USE, 16000000)); // There shouldn't be too much usage on the browser process. Note that it @@ -730,7 +732,8 @@ ->tab_strip_model() ->GetActiveWebContents() ->GetMainFrame() - ->ExecuteJavaScriptForTests(base::UTF8ToUTF16(test_js)); + ->ExecuteJavaScriptForTests(base::UTF8ToUTF16(test_js), + base::NullCallback()); // This test uses |setTimeout| to exceed the Nyquist ratio to ensure that at // least 1 refresh has happened of no traffic. @@ -745,7 +748,8 @@ ->tab_strip_model() ->GetActiveWebContents() ->GetMainFrame() - ->ExecuteJavaScriptForTests(base::UTF8ToUTF16(test_js)); + ->ExecuteJavaScriptForTests(base::UTF8ToUTF16(test_js), + base::NullCallback()); ASSERT_NO_FATAL_FAILURE(WaitForTaskManagerStatToExceed( MatchTab("network use"), ColumnSpecifier::TOTAL_NETWORK_USE, 16000000 * 2));
diff --git a/chrome/browser/ui/BUILD.gn b/chrome/browser/ui/BUILD.gn index b52232c..93aaebf3 100644 --- a/chrome/browser/ui/BUILD.gn +++ b/chrome/browser/ui/BUILD.gn
@@ -1220,6 +1220,8 @@ "webui/settings/settings_media_devices_selection_handler.h", "webui/settings/settings_page_ui_handler.cc", "webui/settings/settings_page_ui_handler.h", + "webui/settings/settings_security_key_handler.cc", + "webui/settings/settings_security_key_handler.h", "webui/settings/settings_startup_pages_handler.cc", "webui/settings/settings_startup_pages_handler.h", "webui/settings/site_settings_handler.cc", @@ -1278,6 +1280,7 @@ "//components/web_modal", "//components/zoom", "//device/bluetooth", + "//device/fido", "//services/device/public/cpp:device_features", "//services/device/public/mojom", "//services/identity/public/cpp",
diff --git a/chrome/browser/ui/ash/multi_user/multi_user_window_manager_client_impl_unittest.cc b/chrome/browser/ui/ash/multi_user/multi_user_window_manager_client_impl_unittest.cc index 23a3790..2e49ff4 100644 --- a/chrome/browser/ui/ash/multi_user/multi_user_window_manager_client_impl_unittest.cc +++ b/chrome/browser/ui/ash/multi_user/multi_user_window_manager_client_impl_unittest.cc
@@ -826,6 +826,27 @@ ::wm::RemoveTransientChild(window(7), window(9)); } +// Verifies duplicate observers are not added for transient dialog windows. +// https://crbug.com/937333 +TEST_F(MultiUserWindowManagerClientImplTest, SetWindowOwnerOnTransientDialog) { + SetUpForThisManyWindows(2); + aura::Window* parent = window(0); + aura::Window* transient = window(1); + const AccountId account_id(AccountId::FromUserEmail("A")); + multi_user_window_manager_client()->SetWindowOwner(parent, account_id); + + // Simulate chrome::ShowWebDialog() showing a transient dialog, which calls + // SetWindowOwner() on the transient. + ::wm::AddTransientChild(parent, transient); + multi_user_window_manager_client()->SetWindowOwner(transient, account_id); + + // Both windows are shown and owned by user A. + EXPECT_EQ("S[A], S[A]", GetStatus()); + + // Cleanup. + ::wm::RemoveTransientChild(parent, transient); +} + // Test that the initial visibility state gets remembered. TEST_F(MultiUserWindowManagerClientImplTest, PreserveInitialVisibility) { SetUpForThisManyWindows(4);
diff --git a/chrome/browser/ui/avatar_button_error_controller.cc b/chrome/browser/ui/avatar_button_error_controller.cc index 31c3279..addc90e 100644 --- a/chrome/browser/ui/avatar_button_error_controller.cc +++ b/chrome/browser/ui/avatar_button_error_controller.cc
@@ -9,8 +9,6 @@ #include "chrome/browser/sync/profile_sync_service_factory.h" #include "chrome/browser/sync/sync_ui_util.h" #include "components/sync/driver/sync_service.h" -#include "components/sync/engine/sync_status.h" -#include "components/sync/protocol/sync_protocol_error.h" AvatarButtonErrorController::AvatarButtonErrorController( AvatarButtonErrorControllerDelegate* delegate, @@ -87,10 +85,7 @@ syncer::SyncService* sync_service = ProfileSyncServiceFactory::GetForProfile(profile_); if (sync_service) { - syncer::SyncStatus status; - sync_service->QueryDetailedSyncStatus(&status); return sync_service->HasUnrecoverableError() || - status.sync_protocol_error.action == syncer::UPGRADE_CLIENT || sync_ui_util::ShouldShowPassphraseError(sync_service) || sync_ui_util::ShouldRequestSyncConfirmation(sync_service); }
diff --git a/chrome/browser/ui/blocked_content/popup_blocker_browsertest.cc b/chrome/browser/ui/blocked_content/popup_blocker_browsertest.cc index 5b7337d..dc9b1d22 100644 --- a/chrome/browser/ui/blocked_content/popup_blocker_browsertest.cc +++ b/chrome/browser/ui/blocked_content/popup_blocker_browsertest.cc
@@ -595,13 +595,13 @@ // Navigate it elsewhere. content::TestNavigationObserver nav_observer(popup); popup->GetMainFrame()->ExecuteJavaScriptForTests( - base::UTF8ToUTF16("location.href = '/empty.html'")); + base::UTF8ToUTF16("location.href = '/empty.html'"), base::NullCallback()); nav_observer.Wait(); // Have it close itself. CloseObserver close_observer(popup); popup->GetMainFrame()->ExecuteJavaScriptForTests( - base::UTF8ToUTF16("window.close()")); + base::UTF8ToUTF16("window.close()"), base::NullCallback()); close_observer.Wait(); }
diff --git a/chrome/browser/ui/browser_browsertest.cc b/chrome/browser/ui/browser_browsertest.cc index a255c28..3356cc5 100644 --- a/chrome/browser/ui/browser_browsertest.cc +++ b/chrome/browser/ui/browser_browsertest.cc
@@ -11,6 +11,7 @@ #include <string> #include "base/bind.h" +#include "base/bind_helpers.h" #include "base/command_line.h" #include "base/compiler_specific.h" #include "base/files/file_path.h" @@ -498,7 +499,7 @@ original_delegate, second_tab, "*confirm*suppressed*"); second_tab->SetDelegate(&confirm_observer); second_tab->GetMainFrame()->ExecuteJavaScriptForTests( - ASCIIToUTF16("confirm('Activate!');")); + ASCIIToUTF16("confirm('Activate!');"), base::NullCallback()); confirm_observer.Wait(); EXPECT_EQ(2, browser()->tab_strip_model()->count()); EXPECT_EQ(0, browser()->tab_strip_model()->active_index()); @@ -509,7 +510,7 @@ original_delegate, second_tab, "*prompt*suppressed*"); second_tab->SetDelegate(&prompt_observer); second_tab->GetMainFrame()->ExecuteJavaScriptForTests( - ASCIIToUTF16("prompt('Activate!');")); + ASCIIToUTF16("prompt('Activate!');"), base::NullCallback()); prompt_observer.Wait(); EXPECT_EQ(2, browser()->tab_strip_model()->count()); EXPECT_EQ(0, browser()->tab_strip_model()->active_index()); @@ -523,7 +524,7 @@ base::RunLoop alert_wait; js_helper->SetDialogShownCallbackForTesting(alert_wait.QuitClosure()); second_tab->GetMainFrame()->ExecuteJavaScriptForTests( - ASCIIToUTF16("alert('Activate!');")); + ASCIIToUTF16("alert('Activate!');"), base::NullCallback()); alert_wait.Run(); EXPECT_EQ(2, browser()->tab_strip_model()->count()); EXPECT_EQ(0, browser()->tab_strip_model()->active_index()); @@ -624,7 +625,7 @@ base::RunLoop dialog_wait; js_helper->SetDialogShownCallbackForTesting(dialog_wait.QuitClosure()); contents->GetMainFrame()->ExecuteJavaScriptForTests( - ASCIIToUTF16("alert('one'); alert('two');")); + ASCIIToUTF16("alert('one'); alert('two');"), base::NullCallback()); dialog_wait.Run(); EXPECT_TRUE(js_helper->IsShowingDialogForTesting()); @@ -648,7 +649,8 @@ // Start a navigation to trigger the beforeunload dialog. contents->GetMainFrame()->ExecuteJavaScriptForTests( - ASCIIToUTF16("window.location.href = 'about:blank'")); + ASCIIToUTF16("window.location.href = 'about:blank'"), + base::NullCallback()); JavaScriptAppModalDialog* alert = ui_test_utils::WaitForAppModalDialog(); EXPECT_TRUE(alert->IsValid()); AppModalDialogQueue* dialog_queue = AppModalDialogQueue::GetInstance(); @@ -684,7 +686,8 @@ contents->GetMainFrame()->ExecuteJavaScriptForTests( ASCIIToUTF16("f = document.createElement('iframe');" "f.srcdoc = '<script>alert(1)</script>';" - "document.body.appendChild(f);")); + "document.body.appendChild(f);"), + base::NullCallback()); dialog_wait.Run(); EXPECT_TRUE(js_helper->IsShowingDialogForTesting()); @@ -750,7 +753,7 @@ // Clear the beforeunload handler so the test can easily exit. contents->GetMainFrame()->ExecuteJavaScriptForTests( - ASCIIToUTF16("onbeforeunload=null;")); + ASCIIToUTF16("onbeforeunload=null;"), base::NullCallback()); } // Test for crbug.com/11647. A page closed with window.close() should not have @@ -1730,7 +1733,7 @@ base::RunLoop dialog_wait; js_helper->SetDialogShownCallbackForTesting(dialog_wait.QuitClosure()); contents->GetMainFrame()->ExecuteJavaScriptForTests( - ASCIIToUTF16("alert('Dialog showing!');")); + ASCIIToUTF16("alert('Dialog showing!');"), base::NullCallback()); dialog_wait.Run(); EXPECT_TRUE(js_helper->IsShowingDialogForTesting());
diff --git a/chrome/browser/ui/browser_window.h b/chrome/browser/ui/browser_window.h index 80c1456e..009cf8a1 100644 --- a/chrome/browser/ui/browser_window.h +++ b/chrome/browser/ui/browser_window.h
@@ -175,9 +175,6 @@ // frames may need to refresh their title bar. virtual void UpdateTitleBar() = 0; - // Inform the frame that its color has changed. - virtual void UpdateFrameColor() = 0; - // Invoked when the state of the bookmark bar changes. This is only invoked if // the state changes for the current tab, it is not sent when switching tabs. virtual void BookmarkBarStateChanged(
diff --git a/chrome/browser/ui/content_settings/framebust_block_browsertest.cc b/chrome/browser/ui/content_settings/framebust_block_browsertest.cc index 82a67686..be1f2c2 100644 --- a/chrome/browser/ui/content_settings/framebust_block_browsertest.cc +++ b/chrome/browser/ui/content_settings/framebust_block_browsertest.cc
@@ -5,6 +5,7 @@ #include <cstddef> #include "base/bind.h" +#include "base/bind_helpers.h" #include "base/macros.h" #include "base/optional.h" #include "base/stl_util.h" @@ -248,8 +249,10 @@ base::RunLoop block_waiter; blocked_url_added_closure_ = block_waiter.QuitClosure(); - child->ExecuteJavaScriptForTests(base::ASCIIToUTF16(base::StringPrintf( - "window.top.location = '%s';", redirect_url.spec().c_str()))); + child->ExecuteJavaScriptForTests( + base::ASCIIToUTF16(base::StringPrintf("window.top.location = '%s';", + redirect_url.spec().c_str())), + base::NullCallback()); block_waiter.Run(); EXPECT_TRUE(base::ContainsValue(GetFramebustTabHelper()->blocked_urls(), redirect_url)); @@ -278,8 +281,10 @@ GURL redirect_url = embedded_test_server()->GetURL("b.com", "/title1.html"); content::TestNavigationObserver observer(GetWebContents()); - child->ExecuteJavaScriptForTests(base::ASCIIToUTF16(base::StringPrintf( - "window.top.location = '%s';", redirect_url.spec().c_str()))); + child->ExecuteJavaScriptForTests( + base::ASCIIToUTF16(base::StringPrintf("window.top.location = '%s';", + redirect_url.spec().c_str())), + base::NullCallback()); observer.Wait(); EXPECT_TRUE(GetFramebustTabHelper()->blocked_urls().empty()); } @@ -308,8 +313,10 @@ GURL redirect_url = embedded_test_server()->GetURL("b.com", "/title1.html"); content::TestNavigationObserver observer(GetWebContents()); - child->ExecuteJavaScriptForTests(base::ASCIIToUTF16(base::StringPrintf( - "window.top.location = '%s';", redirect_url.spec().c_str()))); + child->ExecuteJavaScriptForTests( + base::ASCIIToUTF16(base::StringPrintf("window.top.location = '%s';", + redirect_url.spec().c_str())), + base::NullCallback()); observer.Wait(); EXPECT_TRUE(GetFramebustTabHelper()->blocked_urls().empty()); } @@ -332,8 +339,10 @@ base::RunLoop block_waiter; blocked_url_added_closure_ = block_waiter.QuitClosure(); - child->ExecuteJavaScriptForTests(base::ASCIIToUTF16(base::StringPrintf( - "window.top.location = '%s';", redirect_url.spec().c_str()))); + child->ExecuteJavaScriptForTests( + base::ASCIIToUTF16(base::StringPrintf("window.top.location = '%s';", + redirect_url.spec().c_str())), + base::NullCallback()); block_waiter.Run(); EXPECT_TRUE(base::ContainsValue(GetFramebustTabHelper()->blocked_urls(), redirect_url));
diff --git a/chrome/browser/ui/extensions/hosted_app_browser_controller.cc b/chrome/browser/ui/extensions/hosted_app_browser_controller.cc index 6560d51e..085e9067 100644 --- a/chrome/browser/ui/extensions/hosted_app_browser_controller.cc +++ b/chrome/browser/ui/extensions/hosted_app_browser_controller.cc
@@ -146,8 +146,7 @@ } HostedAppBrowserController::HostedAppBrowserController(Browser* browser) - : content::WebContentsObserver(nullptr), - browser_(browser), + : browser_(browser), extension_id_(web_app::GetAppIdFromApplicationName(browser->app_name())), // If a bookmark app has a URL handler, then it is a PWA. // TODO(https://crbug.com/774918): Replace once there is a more explicit @@ -267,27 +266,18 @@ } base::Optional<SkColor> HostedAppBrowserController::GetThemeColor() const { - base::Optional<SkColor> result; - - const Extension* extension = GetExtension(); - if (extension) - result = AppThemeColorInfo::GetThemeColor(extension); - - // HTML meta theme-color tag overrides manifest theme_color, see spec: - // https://www.w3.org/TR/appmanifest/#theme_color-member - content::WebContents* web_contents = - browser_->tab_strip_model()->GetActiveWebContents(); - if (web_contents) { - SkColor color = web_contents->GetThemeColor(); - if (color != SK_ColorTRANSPARENT) - result = color; + ExtensionRegistry* registry = ExtensionRegistry::Get(browser_->profile()); + const Extension* extension = + registry->GetExtensionById(extension_id_, ExtensionRegistry::EVERYTHING); + if (extension) { + const base::Optional<SkColor> color = + AppThemeColorInfo::GetThemeColor(extension); + if (color) { + // The frame/tabstrip code expects an opaque color. + return SkColorSetA(*color, SK_AlphaOPAQUE); + } } - - if (!result) - return base::nullopt; - - // The frame/tabstrip code expects an opaque color. - return SkColorSetA(*result, SK_AlphaOPAQUE); + return base::nullopt; } base::string16 HostedAppBrowserController::GetTitle() const { @@ -370,20 +360,11 @@ } } -void HostedAppBrowserController::DidChangeThemeColor(SkColor theme_color) { - browser_->window()->UpdateFrameColor(); -} - void HostedAppBrowserController::OnTabInserted(content::WebContents* contents) { - DCHECK(!web_contents()) << "Hosted app windows are single tabbed only"; HostedAppBrowserController::SetAppPrefsForWebContents(this, contents); - content::WebContentsObserver::Observe(contents); } void HostedAppBrowserController::OnTabRemoved(content::WebContents* contents) { - DCHECK_EQ(contents, web_contents()); - content::WebContentsObserver::Observe(nullptr); - auto* rvh = contents->GetRenderViewHost(); contents->GetMutableRendererPrefs()->can_accept_load_drops = true;
diff --git a/chrome/browser/ui/extensions/hosted_app_browser_controller.h b/chrome/browser/ui/extensions/hosted_app_browser_controller.h index 988b47b..645c0bb 100644 --- a/chrome/browser/ui/extensions/hosted_app_browser_controller.h +++ b/chrome/browser/ui/extensions/hosted_app_browser_controller.h
@@ -12,7 +12,6 @@ #include "base/strings/string16.h" #include "chrome/browser/extensions/extension_uninstall_dialog.h" #include "chrome/browser/ui/tabs/tab_strip_model_observer.h" -#include "content/public/browser/web_contents_observer.h" #include "third_party/skia/include/core/SkColor.h" class Browser; @@ -34,8 +33,7 @@ // Class to encapsulate logic to control the browser UI for hosted apps. class HostedAppBrowserController : public TabStripModelObserver, - public ExtensionUninstallDialog::Delegate, - public content::WebContentsObserver { + public ExtensionUninstallDialog::Delegate { public: // Returns whether |browser| uses the experimental hosted app experience. // Convenience wrapper for checking IsForExperimentalHostedAppBrowser() on @@ -118,9 +116,6 @@ const TabStripModelChange& change, const TabStripSelectionChange& selection) override; - // content::WebContentsObserver: - void DidChangeThemeColor(SkColor theme_color) override; - private: // Called by OnTabstripModelChanged(). void OnTabInserted(content::WebContents* contents);
diff --git a/chrome/browser/ui/javascript_dialogs/javascript_dialog_browsertest.cc b/chrome/browser/ui/javascript_dialogs/javascript_dialog_browsertest.cc index cb8d940..4c1d2ff 100644 --- a/chrome/browser/ui/javascript_dialogs/javascript_dialog_browsertest.cc +++ b/chrome/browser/ui/javascript_dialogs/javascript_dialog_browsertest.cc
@@ -3,6 +3,7 @@ // found in the LICENSE file. #include "base/bind.h" +#include "base/bind_helpers.h" #include "base/logging.h" #include "base/strings/utf_string_conversions.h" #include "base/test/metrics/histogram_tester.h" @@ -42,7 +43,8 @@ scoped_refptr<content::MessageLoopRunner> runner = new content::MessageLoopRunner; js_helper->SetDialogShownCallbackForTesting(runner->QuitClosure()); - tab->GetMainFrame()->ExecuteJavaScriptForTests(base::UTF8ToUTF16("alert()")); + tab->GetMainFrame()->ExecuteJavaScriptForTests(base::UTF8ToUTF16("alert()"), + base::NullCallback()); runner->Run(); // Try reloading. @@ -64,7 +66,7 @@ browser()->tab_strip_model()->GetActiveWebContents(); content::WebContentsAddedObserver new_wc_observer; tab1->GetMainFrame()->ExecuteJavaScriptForTests( - base::UTF8ToUTF16("window.open('about:blank');")); + base::UTF8ToUTF16("window.open('about:blank');"), base::NullCallback()); content::WebContents* tab2 = new_wc_observer.GetWebContents(); ASSERT_NE(tab1, tab2); ASSERT_EQ(tab1->GetMainFrame()->GetProcess(), @@ -76,7 +78,8 @@ JavaScriptDialogTabHelper* js_helper2 = JavaScriptDialogTabHelper::FromWebContents(tab2); js_helper2->SetDialogShownCallbackForTesting(runner->QuitClosure()); - tab2->GetMainFrame()->ExecuteJavaScriptForTests(base::UTF8ToUTF16("alert()")); + tab2->GetMainFrame()->ExecuteJavaScriptForTests(base::UTF8ToUTF16("alert()"), + base::NullCallback()); runner->Run(); // Tab two is closed while the dialog is up. @@ -106,7 +109,8 @@ scoped_refptr<content::MessageLoopRunner> runner = new content::MessageLoopRunner; js_helper->SetDialogShownCallbackForTesting(runner->QuitClosure()); - tab->GetMainFrame()->ExecuteJavaScriptForTests(base::UTF8ToUTF16(script)); + tab->GetMainFrame()->ExecuteJavaScriptForTests(base::UTF8ToUTF16(script), + base::NullCallback()); runner->Run(); // The tab is closed while the dialog is up.
diff --git a/chrome/browser/ui/views/frame/browser_non_client_frame_view.cc b/chrome/browser/ui/views/frame/browser_non_client_frame_view.cc index 7e08fab..2c50892 100644 --- a/chrome/browser/ui/views/frame/browser_non_client_frame_view.cc +++ b/chrome/browser/ui/views/frame/browser_non_client_frame_view.cc
@@ -137,11 +137,6 @@ return !browser_view_->browser()->hosted_app_controller(); } -SkColor BrowserNonClientFrameView::GetCaptionColor( - ActiveState active_state) const { - return color_utils::GetColorWithMaxContrast(GetFrameColor(active_state)); -} - SkColor BrowserNonClientFrameView::GetFrameColor( ActiveState active_state) const { ThemeProperties::OverwritableByUserThemeProperty color_id; @@ -162,14 +157,6 @@ browser_view_->IsIncognito()); } -void BrowserNonClientFrameView::UpdateFrameColor() { - // Only hosted app windows support dynamic frame colors set by HTML meta tags. - if (!hosted_app_button_container_) - return; - hosted_app_button_container_->UpdateCaptionColors(); - SchedulePaint(); -} - SkColor BrowserNonClientFrameView::GetToolbarTopSeparatorColor() const { const int color_id = ShouldPaintAsActive() @@ -237,6 +224,11 @@ hosted_app_button_container_->UpdateStatusIconsVisibility(); } +SkColor BrowserNonClientFrameView::GetCaptionColor( + ActiveState active_state) const { + return color_utils::GetColorWithMaxContrast(GetFrameColor(active_state)); +} + bool BrowserNonClientFrameView::ShouldPaintAsActive( ActiveState active_state) const { return (active_state == kUseCurrent) ? ShouldPaintAsActive()
diff --git a/chrome/browser/ui/views/frame/browser_non_client_frame_view.h b/chrome/browser/ui/views/frame/browser_non_client_frame_view.h index 7059ce23..26609865 100644 --- a/chrome/browser/ui/views/frame/browser_non_client_frame_view.h +++ b/chrome/browser/ui/views/frame/browser_non_client_frame_view.h
@@ -93,18 +93,10 @@ // Returns whether tab strokes can be drawn. virtual bool CanDrawStrokes() const; - // Returns the color to use for text, caption buttons, and other title bar - // elements. - virtual SkColor GetCaptionColor(ActiveState active_state = kUseCurrent) const; - // Returns the color of the browser frame, which is also the color of the // tabstrip background. SkColor GetFrameColor(ActiveState active_state = kUseCurrent) const; - // Called by BrowserView to signal the frame color has changed and needs - // to be repainted. - void UpdateFrameColor(); - // Returns COLOR_TOOLBAR_TOP_SEPARATOR[,_INACTIVE] depending on the activation // state of the window. SkColor GetToolbarTopSeparatorColor() const; @@ -138,6 +130,10 @@ } protected: + // Returns the color to use for text, caption buttons, and other title bar + // elements. + virtual SkColor GetCaptionColor(ActiveState active_state = kUseCurrent) const; + // Converts an ActiveState to a bool representing whether the frame should be // treated as active. bool ShouldPaintAsActive(ActiveState active_state) const;
diff --git a/chrome/browser/ui/views/frame/browser_non_client_frame_view_browsertest.cc b/chrome/browser/ui/views/frame/browser_non_client_frame_view_browsertest.cc index 0c60b8be..ce441fef 100644 --- a/chrome/browser/ui/views/frame/browser_non_client_frame_view_browsertest.cc +++ b/chrome/browser/ui/views/frame/browser_non_client_frame_view_browsertest.cc
@@ -18,7 +18,6 @@ #include "chrome/common/web_application_info.h" #include "chrome/test/base/in_process_browser_test.h" #include "chrome/test/base/ui_test_utils.h" -#include "content/public/test/browser_test_utils.h" #include "content/public/test/test_navigation_observer.h" #include "ui/base/theme_provider.h" @@ -31,7 +30,6 @@ void SetUpOnMainThread() override { ExtensionBrowserTest::SetUpOnMainThread(); scoped_feature_list_.InitAndEnableFeature(features::kDesktopPWAWindowing); - ASSERT_TRUE(embedded_test_server()->Start()); } // Note: A "bookmark app" is a type of hosted app. All of these tests apply @@ -64,7 +62,7 @@ BrowserNonClientFrameView* app_frame_view_ = nullptr; private: - GURL GetAppURL() { return embedded_test_server()->GetURL("/hello.html"); } + GURL GetAppURL() { return GURL("https://test.org"); } base::test::ScopedFeatureList scoped_feature_list_; @@ -188,24 +186,3 @@ EXPECT_TRUE( app_frame_view_->browser_view()->toolbar()->custom_tab_bar()->IsDrawn()); } - -// Tests that hosted app frames reflect the theme color set by HTML meta tags. -IN_PROC_BROWSER_TEST_F(BrowserNonClientFrameViewBrowserTest, - HTMLMetaThemeColorOverridesManifest) { - // Ensure we're not using the system theme on Linux. - ThemeService* theme_service = - ThemeServiceFactory::GetForProfile(browser()->profile()); - theme_service->UseDefaultTheme(); - - InstallAndLaunchBookmarkApp(); - EXPECT_EQ(app_frame_view_->GetFrameColor(), *app_theme_color_); - - content::WebContents* web_contents = - app_frame_view_->browser_view()->GetActiveWebContents(); - EXPECT_TRUE(content::ExecuteScript(web_contents, R"( - document.documentElement.innerHTML = - '<meta name="theme-color" content="yellow">'; - )")); - EXPECT_EQ(app_frame_view_->GetFrameColor(), SK_ColorYELLOW); - DCHECK_NE(*app_theme_color_, SK_ColorYELLOW); -}
diff --git a/chrome/browser/ui/views/frame/browser_view.cc b/chrome/browser/ui/views/frame/browser_view.cc index c00e524..7976b11 100644 --- a/chrome/browser/ui/views/frame/browser_view.cc +++ b/chrome/browser/ui/views/frame/browser_view.cc
@@ -762,10 +762,6 @@ frame_->UpdateWindowIcon(); } -void BrowserView::UpdateFrameColor() { - frame_->GetFrameView()->UpdateFrameColor(); -} - void BrowserView::BookmarkBarStateChanged( BookmarkBar::AnimateChangeType change_type) { if (bookmark_bar_view_.get()) {
diff --git a/chrome/browser/ui/views/frame/browser_view.h b/chrome/browser/ui/views/frame/browser_view.h index 797ed0d..b36a7ee8 100644 --- a/chrome/browser/ui/views/frame/browser_view.h +++ b/chrome/browser/ui/views/frame/browser_view.h
@@ -305,7 +305,6 @@ void SetTopControlsGestureScrollInProgress(bool in_progress) override; StatusBubble* GetStatusBubble() override; void UpdateTitleBar() override; - void UpdateFrameColor() override; void BookmarkBarStateChanged( BookmarkBar::AnimateChangeType change_type) override; void UpdateDevTools() override;
diff --git a/chrome/browser/ui/views/frame/glass_browser_frame_view.cc b/chrome/browser/ui/views/frame/glass_browser_frame_view.cc index c75aa9e..3a05a4e0 100644 --- a/chrome/browser/ui/views/frame/glass_browser_frame_view.cc +++ b/chrome/browser/ui/views/frame/glass_browser_frame_view.cc
@@ -195,14 +195,6 @@ return BrowserNonClientFrameView::CanDrawStrokes(); } -SkColor GlassBrowserFrameView::GetCaptionColor(ActiveState active_state) const { - const SkAlpha title_alpha = ShouldPaintAsActive(active_state) - ? SK_AlphaOPAQUE - : kInactiveTitlebarFeatureAlpha; - return SkColorSetA(GetReadableFeatureColor(GetFrameColor(active_state)), - title_alpha); -} - void GlassBrowserFrameView::UpdateThrobber(bool running) { if (ShowCustomIcon()) window_icon_->Update(); @@ -237,6 +229,14 @@ return min_size; } +SkColor GlassBrowserFrameView::GetCaptionColor(ActiveState active_state) const { + const SkAlpha title_alpha = ShouldPaintAsActive(active_state) + ? SK_AlphaOPAQUE + : kInactiveTitlebarFeatureAlpha; + return SkColorSetA(GetReadableFeatureColor(GetFrameColor(active_state)), + title_alpha); +} + /////////////////////////////////////////////////////////////////////////////// // GlassBrowserFrameView, views::NonClientFrameView implementation:
diff --git a/chrome/browser/ui/views/frame/glass_browser_frame_view.h b/chrome/browser/ui/views/frame/glass_browser_frame_view.h index 90eb6b2..7c8da89 100644 --- a/chrome/browser/ui/views/frame/glass_browser_frame_view.h +++ b/chrome/browser/ui/views/frame/glass_browser_frame_view.h
@@ -40,9 +40,9 @@ int GetThemeBackgroundXInset() const override; bool HasVisibleBackgroundTabShapes(ActiveState active_state) const override; bool CanDrawStrokes() const override; - SkColor GetCaptionColor(ActiveState active_state) const override; void UpdateThrobber(bool running) override; gfx::Size GetMinimumSize() const override; + SkColor GetCaptionColor(ActiveState active_state) const override; // views::NonClientFrameView: gfx::Rect GetBoundsForClientView() const override;
diff --git a/chrome/browser/ui/views/frame/hosted_app_button_container.cc b/chrome/browser/ui/views/frame/hosted_app_button_container.cc index d808a89a7..a1183f7 100644 --- a/chrome/browser/ui/views/frame/hosted_app_button_container.cc +++ b/chrome/browser/ui/views/frame/hosted_app_button_container.cc
@@ -214,7 +214,7 @@ params.types_enabled.push_back(PageActionIconType::kTranslate); params.types_enabled.push_back(PageActionIconType::kZoom); params.icon_size = GetLayoutConstant(HOSTED_APP_PAGE_ACTION_ICON_SIZE); - params.icon_color = GetCaptionColor(); + params.icon_color = GetIconColor(); params.between_icon_spacing = HorizontalPaddingBetweenItems(); params.browser = browser_view_->browser(); params.command_updater = browser_view_->browser()->command_controller(); @@ -259,16 +259,6 @@ page_action_icon_container_view_->UpdateAll(); } -void HostedAppButtonContainer::UpdateCaptionColors() { - const BrowserNonClientFrameView* frame_view = - browser_view_->frame()->GetFrameView(); - active_color_ = frame_view->GetCaptionColor( - BrowserNonClientFrameView::ActiveState::kActive); - inactive_color_ = frame_view->GetCaptionColor( - BrowserNonClientFrameView::ActiveState::kInactive); - UpdateChildrenColor(); -} - void HostedAppButtonContainer::SetPaintAsActive(bool active) { if (paint_as_active_ == active) return; @@ -321,7 +311,7 @@ } SkColor HostedAppButtonContainer::GetContentSettingInkDropColor() const { - return GetCaptionColor(); + return GetIconColor(); } content::WebContents* HostedAppButtonContainer::GetContentSettingWebContents() { @@ -347,7 +337,7 @@ } SkColor HostedAppButtonContainer::GetPageActionInkDropColor() const { - return GetCaptionColor(); + return GetIconColor(); } content::WebContents* @@ -464,12 +454,12 @@ return content_settings_container_->GetContentSettingViewsForTesting(); } -SkColor HostedAppButtonContainer::GetCaptionColor() const { +SkColor HostedAppButtonContainer::GetIconColor() const { return paint_as_active_ ? active_color_ : inactive_color_; } void HostedAppButtonContainer::UpdateChildrenColor() { - SkColor icon_color = GetCaptionColor(); + SkColor icon_color = GetIconColor(); hosted_app_origin_text_->SetTextColor(icon_color); content_settings_container_->SetIconColor(icon_color); page_action_icon_container_view_->SetIconColor(icon_color);
diff --git a/chrome/browser/ui/views/frame/hosted_app_button_container.h b/chrome/browser/ui/views/frame/hosted_app_button_container.h index f8aa41b..dd732b68 100644 --- a/chrome/browser/ui/views/frame/hosted_app_button_container.h +++ b/chrome/browser/ui/views/frame/hosted_app_button_container.h
@@ -16,7 +16,6 @@ #include "chrome/browser/ui/views/location_bar/content_setting_image_view.h" #include "chrome/browser/ui/views/page_action/page_action_icon_view.h" #include "chrome/browser/ui/views/toolbar/browser_actions_container.h" -#include "ui/gfx/color_palette.h" #include "ui/views/accessible_pane_view.h" #include "ui/views/controls/button/menu_button.h" #include "ui/views/controls/button/menu_button_listener.h" @@ -72,8 +71,6 @@ void UpdateStatusIconsVisibility(); - void UpdateCaptionColors(); - // Sets the container to paints its buttons the active/inactive color. void SetPaintAsActive(bool active); @@ -154,7 +151,7 @@ const std::vector<ContentSettingImageView*>& GetContentSettingViewsForTesting() const; - SkColor GetCaptionColor() const; + SkColor GetIconColor() const; void UpdateChildrenColor(); // Whether we're waiting for the widget to become visible. @@ -171,8 +168,8 @@ // Button and text colors. bool paint_as_active_ = true; - SkColor active_color_; - SkColor inactive_color_; + const SkColor active_color_; + const SkColor inactive_color_; // Owned by the views hierarchy. HostedAppOriginText* hosted_app_origin_text_ = nullptr;
diff --git a/chrome/browser/ui/views/select_file_dialog_extension_browsertest.cc b/chrome/browser/ui/views/select_file_dialog_extension_browsertest.cc index 6051ebb..ff87595cb 100644 --- a/chrome/browser/ui/views/select_file_dialog_extension_browsertest.cc +++ b/chrome/browser/ui/views/select_file_dialog_extension_browsertest.cc
@@ -9,6 +9,7 @@ #include "ash/public/interfaces/constants.mojom.h" #include "ash/public/interfaces/shell_test_api.test-mojom-test-utils.h" #include "ash/public/interfaces/shell_test_api.test-mojom.h" +#include "base/bind_helpers.h" #include "base/files/file_util.h" #include "base/files/scoped_temp_dir.h" #include "base/logging.h" @@ -328,7 +329,8 @@ "document.querySelector(\'" + button_class + "\').click();"); // The file selection handler code closes the dialog but does not return // control to JavaScript, so do not wait for the script return value. - host->GetMainFrame()->ExecuteJavaScriptForTests(script); + host->GetMainFrame()->ExecuteJavaScriptForTests(script, + base::NullCallback()); // Instead, wait for Listener notification that the window has closed. LOG(INFO) << "Waiting for window close notification.";
diff --git a/chrome/browser/ui/webui/chromeos/login/gaia_screen_handler.cc b/chrome/browser/ui/webui/chromeos/login/gaia_screen_handler.cc index 55f15d3..d62a50d 100644 --- a/chrome/browser/ui/webui/chromeos/login/gaia_screen_handler.cc +++ b/chrome/browser/ui/webui/chromeos/login/gaia_screen_handler.cc
@@ -8,6 +8,7 @@ #include "ash/public/cpp/ash_features.h" #include "base/bind.h" +#include "base/bind_helpers.h" #include "base/callback.h" #include "base/containers/flat_set.h" #include "base/feature_list.h" @@ -1044,7 +1045,8 @@ std::string code = "document.getElementById('identifier').value = '" + test_user_ + "';" "document.getElementById('nextButton').click();"; - frame->ExecuteJavaScriptForTests(base::ASCIIToUTF16(code)); + frame->ExecuteJavaScriptForTests(base::ASCIIToUTF16(code), + base::NullCallback()); if (!test_services_.empty()) { // Prefix each doublequote with backslash, so that it will remain correct @@ -1053,13 +1055,15 @@ base::ReplaceChars(test_services_, "\"", "\\\"", &escaped_services); code = "document.getElementById('services').value = \"" + escaped_services + "\";"; - frame->ExecuteJavaScriptForTests(base::ASCIIToUTF16(code)); + frame->ExecuteJavaScriptForTests(base::ASCIIToUTF16(code), + base::NullCallback()); } if (!test_pass_.empty()) { code = "document.getElementById('password').value = '" + test_pass_ + "';"; code += "document.getElementById('nextButton').click();"; - frame->ExecuteJavaScriptForTests(base::ASCIIToUTF16(code)); + frame->ExecuteJavaScriptForTests(base::ASCIIToUTF16(code), + base::NullCallback()); } // Test properties are cleared in HandleCompleteLogin because the form
diff --git a/chrome/browser/ui/webui/chromeos/set_time_ui.cc b/chrome/browser/ui/webui/chromeos/set_time_ui.cc index a40bd56..1128273 100644 --- a/chrome/browser/ui/webui/chromeos/set_time_ui.cc +++ b/chrome/browser/ui/webui/chromeos/set_time_ui.cc
@@ -12,6 +12,7 @@ #include "base/bind_helpers.h" #include "base/build_time.h" #include "base/macros.h" +#include "base/scoped_observer.h" #include "base/values.h" #include "chrome/browser/chromeos/settings/cros_settings.h" #include "chrome/browser/chromeos/system/timezone_util.h" @@ -35,19 +36,16 @@ public chromeos::SystemClockClient::Observer, public system::TimezoneSettings::Observer { public: - SetTimeMessageHandler() { - system::TimezoneSettings::GetInstance()->AddObserver(this); - SystemClockClient::Get()->AddObserver(this); - } - - ~SetTimeMessageHandler() override { - system::TimezoneSettings::GetInstance()->RemoveObserver(this); - SystemClockClient::Get()->RemoveObserver(this); - } + SetTimeMessageHandler() = default; + ~SetTimeMessageHandler() override = default; // WebUIMessageHandler: void RegisterMessages() override { web_ui()->RegisterMessageCallback( + "setTimePageReady", + base::BindRepeating(&SetTimeMessageHandler::OnPageReady, + base::Unretained(this))); + web_ui()->RegisterMessageCallback( "setTimeInSeconds", base::BindRepeating(&SetTimeMessageHandler::OnSetTime, base::Unretained(this))); @@ -57,10 +55,22 @@ base::Unretained(this))); } + void OnJavascriptAllowed() override { + clock_observer_.Add(SystemClockClient::Get()); + timezone_observer_.Add(system::TimezoneSettings::GetInstance()); + } + + void OnJavascriptDisallowed() override { + clock_observer_.RemoveAll(); + timezone_observer_.RemoveAll(); + } + private: + void OnPageReady(const base::ListValue* args) { AllowJavascript(); } + // SystemClockClient::Observer: void SystemClockUpdated() override { - web_ui()->CallJavascriptFunctionUnsafe("settime.TimeSetter.updateTime"); + CallJavascriptFunction("settime.TimeSetter.updateTime"); } // UI actually shows real device timezone, but only allows changing the user @@ -70,8 +80,7 @@ // system::TimezoneSettings::Observer: void TimezoneChanged(const icu::TimeZone& timezone) override { base::Value timezone_id(system::TimezoneSettings::GetTimezoneID(timezone)); - web_ui()->CallJavascriptFunctionUnsafe("settime.TimeSetter.setTimezone", - timezone_id); + CallJavascriptFunction("settime.TimeSetter.setTimezone", timezone_id); } // Handler for Javascript call to set the system clock when the user sets a @@ -102,6 +111,11 @@ system::SetTimezoneFromUI(profile, timezone_id); } + ScopedObserver<SystemClockClient, SystemClockClient::Observer> + clock_observer_{this}; + ScopedObserver<system::TimezoneSettings, system::TimezoneSettings::Observer> + timezone_observer_{this}; + DISALLOW_COPY_AND_ASSIGN(SetTimeMessageHandler); }; @@ -143,7 +157,6 @@ content::WebUIDataSource::Add(Profile::FromWebUI(web_ui), source); } -SetTimeUI::~SetTimeUI() { -} +SetTimeUI::~SetTimeUI() = default; } // namespace chromeos
diff --git a/chrome/browser/ui/webui/chromeos/set_time_ui_browsertest.js b/chrome/browser/ui/webui/chromeos/set_time_ui_browsertest.js index 1249c874..ea19765c 100644 --- a/chrome/browser/ui/webui/chromeos/set_time_ui_browsertest.js +++ b/chrome/browser/ui/webui/chromeos/set_time_ui_browsertest.js
@@ -20,8 +20,23 @@ * @override */ browsePreload: 'chrome://set-time/', + + /** @override */ + preLoad: function() { + testing.Test.prototype.preLoad.call(this); + registerMessageCallback('setTimePageReady', this, function() { + assertFalse(this.setTimePageReadyCalled); + this.setTimePageReadyCalled = true; + }); + }, + + setTimePageReadyCalled: false, }; +TEST_F('SetTimeWebUITest', 'testPageReady', function() { + assertTrue(this.setTimePageReadyCalled); +}); + TEST_F('SetTimeWebUITest', 'testChangeTimezone', function() { assertEquals(this.browsePreload, document.location.href);
diff --git a/chrome/browser/ui/webui/feed_internals/feed_internals.mojom b/chrome/browser/ui/webui/feed_internals/feed_internals.mojom index 3644fadd..351138d 100644 --- a/chrome/browser/ui/webui/feed_internals/feed_internals.mojom +++ b/chrome/browser/ui/webui/feed_internals/feed_internals.mojom
@@ -96,4 +96,7 @@ // Get the last known content with metadata. GetCurrentContent() => (array<Suggestion> suggestions); + + // Internal state dump of the Feed library's process scope. + GetFeedProcessScopeDump() => (string dump); };
diff --git a/chrome/browser/ui/webui/feed_internals/feed_internals_page_handler.cc b/chrome/browser/ui/webui/feed_internals/feed_internals_page_handler.cc index f7f6fea5..52f8b9bf 100644 --- a/chrome/browser/ui/webui/feed_internals/feed_internals_page_handler.cc +++ b/chrome/browser/ui/webui/feed_internals/feed_internals_page_handler.cc
@@ -137,3 +137,7 @@ std::move(callback).Run(std::move(suggestions)); } +void FeedInternalsPageHandler::GetFeedProcessScopeDump( + GetFeedProcessScopeDumpCallback callback) { + std::move(callback).Run(feed::GetFeedProcessScopeDumpForDebugging()); +}
diff --git a/chrome/browser/ui/webui/feed_internals/feed_internals_page_handler.h b/chrome/browser/ui/webui/feed_internals/feed_internals_page_handler.h index 277fb4c..b334469 100644 --- a/chrome/browser/ui/webui/feed_internals/feed_internals_page_handler.h +++ b/chrome/browser/ui/webui/feed_internals/feed_internals_page_handler.h
@@ -40,6 +40,7 @@ void GetLastFetchProperties(GetLastFetchPropertiesCallback) override; void ClearCachedDataAndRefreshFeed() override; void GetCurrentContent(GetCurrentContentCallback) override; + void GetFeedProcessScopeDump(GetFeedProcessScopeDumpCallback) override; private: // Binding from the mojo interface to concrete implementation.
diff --git a/chrome/browser/ui/webui/management_ui.cc b/chrome/browser/ui/webui/management_ui.cc index 336a210..5485434a 100644 --- a/chrome/browser/ui/webui/management_ui.cc +++ b/chrome/browser/ui/webui/management_ui.cc
@@ -78,6 +78,7 @@ {kManagementReportNetworkInterfaces, IDS_MANAGEMENT_REPORT_DEVICE_NETWORK_INTERFACES}, {kManagementReportUsers, IDS_MANAGEMENT_REPORT_DEVICE_USERS}, + {kManagementPrinting, IDS_MANAGEMENT_REPORT_PRINTING}, #endif // defined(OS_CHROMEOS) {"browserReporting", IDS_MANAGEMENT_BROWSER_REPORTING}, {"browserReportingExplanation",
diff --git a/chrome/browser/ui/webui/management_ui_handler.cc b/chrome/browser/ui/webui/management_ui_handler.cc index db95f7a..230209e4 100644 --- a/chrome/browser/ui/webui/management_ui_handler.cc +++ b/chrome/browser/ui/webui/management_ui_handler.cc
@@ -41,6 +41,7 @@ #include "chrome/browser/chromeos/policy/system_log_uploader.h" #include "chrome/browser/chromeos/profiles/profile_helper.h" #include "chrome/grit/chromium_strings.h" +#include "components/prefs/pref_service.h" #include "components/user_manager/user_manager.h" #endif // defined(OS_CHROMEOS) @@ -107,12 +108,15 @@ #endif // BUILDFLAG(ENABLE_EXTENSIONS) +#if defined(OS_CHROMEOS) const char kManagementLogUploadEnabled[] = "managementLogUploadEnabled"; const char kManagementReportActivityTimes[] = "managementReportActivityTimes"; const char kManagementReportHardwareStatus[] = "managementReportHardwareStatus"; const char kManagementReportNetworkInterfaces[] = "managementReportNetworkInterfaces"; const char kManagementReportUsers[] = "managementReportUsers"; +const char kManagementPrinting[] = "managementPrinting"; +#endif // defined(OS_CHROMEOS) namespace { @@ -186,7 +190,8 @@ kDeviceActivity, kDeviceStatistics, kDevice, - kLogs + kLogs, + kPrint }; // Corresponds to DeviceReportingType in management_browser_proxy.js @@ -202,6 +207,8 @@ return "device"; case DeviceReportingType::kLogs: return "logs"; + case DeviceReportingType::kPrint: + return "print"; default: NOTREACHED() << "Unknown device reporting type"; return "device"; @@ -217,7 +224,7 @@ report_sources->GetList().push_back(std::move(data)); } -void AddDeviceReportingInfo(base::Value* report_sources) { +void AddDeviceReportingInfo(base::Value* report_sources, Profile* profile) { policy::BrowserPolicyConnectorChromeOS* connector = g_browser_process->platform_part()->browser_policy_connector_chromeos(); @@ -257,6 +264,12 @@ AddDeviceReportingElement(report_sources, kManagementLogUploadEnabled, DeviceReportingType::kLogs); } + + if (profile->GetPrefs()->GetBoolean( + prefs::kPrintingSendUsernameAndFilenameEnabled)) { + AddDeviceReportingElement(report_sources, kManagementPrinting, + DeviceReportingType::kPrint); + } } #endif // defined(OS_CHROMEOS) @@ -623,7 +636,7 @@ base::Value report_sources(base::Value::Type::LIST); AllowJavascript(); - AddDeviceReportingInfo(&report_sources); + AddDeviceReportingInfo(&report_sources, Profile::FromWebUI(web_ui())); ResolveJavascriptCallback(args->GetList()[0] /* callback_id */, report_sources);
diff --git a/chrome/browser/ui/webui/management_ui_handler.h b/chrome/browser/ui/webui/management_ui_handler.h index 28cf7d1..1f5aa7f 100644 --- a/chrome/browser/ui/webui/management_ui_handler.h +++ b/chrome/browser/ui/webui/management_ui_handler.h
@@ -23,6 +23,7 @@ #include "extensions/browser/extension_registry_observer.h" #endif // BUILDFLAG(ENABLE_EXTENSIONS) +#if defined(OS_CHROMEOS) // Constants defining the IDs for the localized strings sent to the page as // load time data. extern const char kManagementLogUploadEnabled[]; @@ -30,6 +31,8 @@ extern const char kManagementReportHardwareStatus[]; extern const char kManagementReportNetworkInterfaces[]; extern const char kManagementReportUsers[]; +extern const char kManagementPrinting[]; +#endif // defined(OS_CHROMEOS) #if BUILDFLAG(ENABLE_EXTENSIONS) extern const char kCloudReportingExtensionId[];
diff --git a/chrome/browser/ui/webui/net_internals/net_internals_ui.cc b/chrome/browser/ui/webui/net_internals/net_internals_ui.cc index 3621f103..a70b0ac0 100644 --- a/chrome/browser/ui/webui/net_internals/net_internals_ui.cc +++ b/chrome/browser/ui/webui/net_internals/net_internals_ui.cc
@@ -122,10 +122,15 @@ void OnFlushSocketPools(const base::ListValue* list); #if defined(OS_CHROMEOS) void OnDumpPolicyLogsCompleted(const base::FilePath& path, - bool should_compress); + bool should_compress, + bool combined, + const char* received_event); void OnImportONCFile(const base::ListValue* list); - void OnStoreDebugLogs(const base::ListValue* list); - void OnStoreDebugLogsCompleted(const base::FilePath& log_path, + void OnStoreDebugLogs(bool combined, + const char* received_event, + const base::ListValue* list); + void OnStoreDebugLogsCompleted(const char* received_event, + const base::FilePath& log_path, bool succeeded); void OnSetNetworkDebugMode(const base::ListValue* list); void OnSetNetworkDebugModeCompleted(const std::string& subsystem, @@ -194,7 +199,13 @@ web_ui()->RegisterMessageCallback( "storeDebugLogs", base::BindRepeating(&NetInternalsMessageHandler::OnStoreDebugLogs, - base::Unretained(this))); + base::Unretained(this), false /* combined */, + "receivedStoreDebugLogs")); + web_ui()->RegisterMessageCallback( + "storeCombinedDebugLogs", + base::BindRepeating(&NetInternalsMessageHandler::OnStoreDebugLogs, + base::Unretained(this), true /* combined */, + "receivedStoreCombinedDebugLogs")); web_ui()->RegisterMessageCallback( "setNetworkDebugMode", base::BindRepeating(&NetInternalsMessageHandler::OnSetNetworkDebugMode, @@ -412,20 +423,12 @@ base::WriteFile(file_path, json_policies.data(), json_policies.size()); } -void NetInternalsMessageHandler::OnDumpPolicyLogsCompleted( - const base::FilePath& path, - bool should_compress) { - chromeos::DebugLogWriter::StoreLogs( - path, should_compress, - base::Bind(&NetInternalsMessageHandler::OnStoreDebugLogsCompleted, - AsWeakPtr())); -} - -void NetInternalsMessageHandler::OnStoreDebugLogs(const base::ListValue* list) { +void NetInternalsMessageHandler::OnStoreDebugLogs(bool combined, + const char* received_event, + const base::ListValue* list) { DCHECK(list); - SendJavascriptCommand("receivedStoreDebugLogs", - base::Value("Creating log file...")); + SendJavascriptCommand(received_event, base::Value("Creating log file...")); Profile* profile = Profile::FromWebUI(web_ui()); const DownloadPrefs* const prefs = DownloadPrefs::FromBrowserContext(profile); base::FilePath path = prefs->DownloadPath(); @@ -442,17 +445,38 @@ base::TaskShutdownBehavior::BLOCK_SHUTDOWN}, base::BindOnce(DumpPolicyLogs, policies_path, json_policies), base::BindOnce(&NetInternalsMessageHandler::OnDumpPolicyLogsCompleted, - AsWeakPtr(), path, true /* should_compress */)); + AsWeakPtr(), path, true /* should_compress */, combined, + received_event)); +} + +void NetInternalsMessageHandler::OnDumpPolicyLogsCompleted( + const base::FilePath& path, + bool should_compress, + bool combined, + const char* received_event) { + if (combined) { + chromeos::DebugLogWriter::StoreCombinedLogs( + path, + base::BindOnce(&NetInternalsMessageHandler::OnStoreDebugLogsCompleted, + AsWeakPtr(), received_event)); + } else { + chromeos::DebugLogWriter::StoreLogs( + path, should_compress, + base::BindOnce(&NetInternalsMessageHandler::OnStoreDebugLogsCompleted, + AsWeakPtr(), received_event)); + } } void NetInternalsMessageHandler::OnStoreDebugLogsCompleted( - const base::FilePath& log_path, bool succeeded) { + const char* received_event, + const base::FilePath& log_path, + bool succeeded) { std::string status; if (succeeded) status = "Created log file: " + log_path.BaseName().AsUTF8Unsafe(); else status = "Failed to create log file"; - SendJavascriptCommand("receivedStoreDebugLogs", base::Value(status)); + SendJavascriptCommand(received_event, base::Value(status)); } void NetInternalsMessageHandler::OnSetNetworkDebugMode(
diff --git a/chrome/browser/ui/webui/omnibox/omnibox.mojom b/chrome/browser/ui/webui/omnibox/omnibox.mojom index 7e6f9f9..f24279a4 100644 --- a/chrome/browser/ui/webui/omnibox/omnibox.mojom +++ b/chrome/browser/ui/webui/omnibox/omnibox.mojom
@@ -43,6 +43,7 @@ int32 duplicates; bool from_previous; array<AutocompleteAdditionalInfo> additional_info; + string document_type; }; struct AutocompleteResultsForProvider {
diff --git a/chrome/browser/ui/webui/omnibox/omnibox_page_handler.cc b/chrome/browser/ui/webui/omnibox/omnibox_page_handler.cc index f9715b337..132a25c 100644 --- a/chrome/browser/ui/webui/omnibox/omnibox_page_handler.cc +++ b/chrome/browser/ui/webui/omnibox/omnibox_page_handler.cc
@@ -198,6 +198,8 @@ result->additional_info = mojo::ConvertTo<std::vector<mojom::AutocompleteAdditionalInfoPtr>>( input.additional_info); + result->document_type = + AutocompleteMatch::DocumentTypeString(input.document_type); return result; } };
diff --git a/chrome/browser/ui/webui/settings/md_settings_ui.cc b/chrome/browser/ui/webui/settings/md_settings_ui.cc index 8120165..c49956c 100644 --- a/chrome/browser/ui/webui/settings/md_settings_ui.cc +++ b/chrome/browser/ui/webui/settings/md_settings_ui.cc
@@ -43,6 +43,7 @@ #include "chrome/browser/ui/webui/settings/settings_import_data_handler.h" #include "chrome/browser/ui/webui/settings/settings_media_devices_selection_handler.h" #include "chrome/browser/ui/webui/settings/settings_page_ui_handler.h" +#include "chrome/browser/ui/webui/settings/settings_security_key_handler.h" #include "chrome/browser/ui/webui/settings/settings_startup_pages_handler.h" #include "chrome/browser/ui/webui/settings/site_settings_handler.h" #include "chrome/common/pref_names.h" @@ -190,6 +191,7 @@ AddSettingsPageUIHandler(std::make_unique<SearchEnginesHandler>(profile)); AddSettingsPageUIHandler(std::make_unique<SiteSettingsHandler>(profile)); AddSettingsPageUIHandler(std::make_unique<StartupPagesHandler>(web_ui)); + AddSettingsPageUIHandler(std::make_unique<SecurityKeysHandler>()); #if defined(OS_CHROMEOS) AddSettingsPageUIHandler(
diff --git a/chrome/browser/ui/webui/settings/settings_security_key_handler.cc b/chrome/browser/ui/webui/settings/settings_security_key_handler.cc new file mode 100644 index 0000000..834603a --- /dev/null +++ b/chrome/browser/ui/webui/settings/settings_security_key_handler.cc
@@ -0,0 +1,251 @@ +// Copyright 2019 The Chromium 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 <utility> + +#include "base/callback.h" +#include "base/optional.h" +#include "base/values.h" +#include "chrome/browser/ui/webui/settings/settings_page_ui_handler.h" +#include "chrome/browser/ui/webui/settings/settings_security_key_handler.h" +#include "content/public/browser/browser_thread.h" +#include "content/public/browser/web_ui.h" +#include "content/public/common/service_manager_connection.h" +#include "device/fido/pin.h" +#include "device/fido/reset_request_handler.h" +#include "device/fido/set_pin_request_handler.h" + +using content::BrowserThread; + +namespace { + +constexpr char kStartSetPIN[] = "securityKeyStartSetPIN"; +constexpr char kSetPIN[] = "securityKeySetPIN"; +constexpr char kClose[] = "securityKeyClose"; +constexpr char kReset[] = "securityKeyReset"; +constexpr char kCompleteReset[] = "securityKeyCompleteReset"; + +base::flat_set<device::FidoTransportProtocol> supported_transports() { + // If we ever support BLE devices then additional thought will be required + // in the UI; therefore don't enable them here. NFC is not supported on + // desktop thus only USB devices remain to be enabled. + return {device::FidoTransportProtocol::kUsbHumanInterfaceDevice}; +} + +} // namespace + +namespace settings { + +SecurityKeysHandler::SecurityKeysHandler() + : state_(State::kNone), + weak_factory_(new base::WeakPtrFactory<SecurityKeysHandler>(this)) {} + +SecurityKeysHandler::~SecurityKeysHandler() = default; + +void SecurityKeysHandler::RegisterMessages() { + web_ui()->RegisterMessageCallback( + kStartSetPIN, base::BindRepeating(&SecurityKeysHandler::HandleStartSetPIN, + base::Unretained(this))); + web_ui()->RegisterMessageCallback( + kSetPIN, base::BindRepeating(&SecurityKeysHandler::HandleSetPIN, + base::Unretained(this))); + web_ui()->RegisterMessageCallback( + kClose, base::BindRepeating(&SecurityKeysHandler::HandleClose, + base::Unretained(this))); + web_ui()->RegisterMessageCallback( + kReset, base::BindRepeating(&SecurityKeysHandler::HandleReset, + base::Unretained(this))); + web_ui()->RegisterMessageCallback( + kCompleteReset, + base::BindRepeating(&SecurityKeysHandler::HandleCompleteReset, + base::Unretained(this))); +} + +void SecurityKeysHandler::OnJavascriptAllowed() {} +void SecurityKeysHandler::OnJavascriptDisallowed() { + // If Javascript is disallowed, |Close| will invalidate all current WeakPtrs + // and thus drop all pending callbacks. This means that + // |IsJavascriptAllowed| doesn't need to be tested before each callback + // because, if the callback into this object happened, then Javascript is + // allowed. + Close(); +} + +void SecurityKeysHandler::Close() { + // Invalidate all existing WeakPtrs so that no stale callbacks occur. + weak_factory_ = + std::make_unique<base::WeakPtrFactory<SecurityKeysHandler>>(this); + state_ = State::kNone; + set_pin_.reset(); + reset_.reset(); + callback_id_.clear(); +} + +void SecurityKeysHandler::HandleStartSetPIN(const base::ListValue* args) { + DCHECK_CURRENTLY_ON(BrowserThread::UI); + DCHECK_EQ(State::kNone, state_); + DCHECK_EQ(1u, args->GetSize()); + + AllowJavascript(); + DCHECK(callback_id_.empty()); + callback_id_ = args->GetList()[0].GetString(); + state_ = State::kStartSetPIN; + set_pin_ = std::make_unique<device::SetPINRequestHandler>( + content::ServiceManagerConnection::GetForProcess()->GetConnector(), + supported_transports(), + base::BindOnce(&SecurityKeysHandler::OnGatherPIN, + weak_factory_->GetWeakPtr()), + base::BindRepeating(&SecurityKeysHandler::OnSetPINComplete, + weak_factory_->GetWeakPtr())); +} + +void SecurityKeysHandler::OnGatherPIN(base::Optional<int64_t> num_retries) { + DCHECK_EQ(State::kStartSetPIN, state_); + DCHECK_CURRENTLY_ON(BrowserThread::UI); + + base::Value::ListStorage list; + list.emplace_back(0 /* process not complete */); + if (num_retries) { + state_ = State::kGatherChangePIN; + list.emplace_back(static_cast<int>(*num_retries)); + } else { + state_ = State::kGatherNewPIN; + list.emplace_back(base::Value::Type::NONE); + } + + ResolveJavascriptCallback(base::Value(std::move(callback_id_)), + base::Value(std::move(list))); +} + +void SecurityKeysHandler::OnSetPINComplete( + device::CtapDeviceResponseCode code) { + DCHECK(state_ == State::kStartSetPIN || state_ == State::kSettingPIN); + DCHECK_CURRENTLY_ON(BrowserThread::UI); + + if (code == device::CtapDeviceResponseCode::kCtap2ErrPinInvalid) { + // In the event that the old PIN was incorrect, the UI may prompt again. + state_ = State::kGatherChangePIN; + } else { + state_ = State::kNone; + set_pin_.reset(); + } + + base::Value::ListStorage list; + list.emplace_back(1 /* process complete */); + list.emplace_back(static_cast<int>(code)); + ResolveJavascriptCallback(base::Value(std::move(callback_id_)), + base::Value(std::move(list))); +} + +void SecurityKeysHandler::HandleSetPIN(const base::ListValue* args) { + DCHECK(state_ == State::kGatherNewPIN || state_ == State::kGatherChangePIN); + DCHECK_CURRENTLY_ON(BrowserThread::UI); + DCHECK_EQ(3u, args->GetSize()); + + DCHECK(callback_id_.empty()); + callback_id_ = args->GetList()[0].GetString(); + const std::string old_pin = args->GetList()[1].GetString(); + const std::string new_pin = args->GetList()[2].GetString(); + + DCHECK((state_ == State::kGatherNewPIN) == old_pin.empty()); + + CHECK(device::pin::IsValid(new_pin)); + state_ = State::kSettingPIN; + set_pin_->ProvidePIN(old_pin, new_pin); +} + +void SecurityKeysHandler::HandleReset(const base::ListValue* args) { + DCHECK_EQ(State::kNone, state_); + DCHECK_CURRENTLY_ON(BrowserThread::UI); + DCHECK_EQ(1u, args->GetSize()); + + AllowJavascript(); + DCHECK(callback_id_.empty()); + callback_id_ = args->GetList()[0].GetString(); + + state_ = State::kStartReset; + reset_ = std::make_unique<device::ResetRequestHandler>( + content::ServiceManagerConnection::GetForProcess()->GetConnector(), + supported_transports(), + base::BindOnce(&SecurityKeysHandler::OnResetSent, + weak_factory_->GetWeakPtr()), + base::BindOnce(&SecurityKeysHandler::OnResetFinished, + weak_factory_->GetWeakPtr())); +} + +void SecurityKeysHandler::OnResetSent() { + DCHECK_EQ(State::kStartReset, state_); + DCHECK_CURRENTLY_ON(BrowserThread::UI); + + // A reset message has been sent to a security key and it may complete + // before Javascript asks for the result. Therefore |HandleCompleteReset| + // and |OnResetFinished| may be called in either order. + state_ = State::kWaitingForResetNoCallbackYet; + ResolveJavascriptCallback(base::Value(std::move(callback_id_)), + base::Value(0 /* success */)); +} + +void SecurityKeysHandler::HandleCompleteReset(const base::ListValue* args) { + DCHECK_CURRENTLY_ON(BrowserThread::UI); + DCHECK_EQ(1u, args->GetSize()); + + DCHECK(callback_id_.empty()); + callback_id_ = args->GetList()[0].GetString(); + + switch (state_) { + case State::kWaitingForResetNoCallbackYet: + // The reset operation hasn't completed. |callback_id_| will be used in + // |OnResetFinished| when it does. + state_ = State::kWaitingForResetHaveCallback; + break; + + case State::kWaitingForCompleteReset: + // The reset operation has completed and we were waiting for this + // call from Javascript in order to provide the result. + state_ = State::kNone; + ResolveJavascriptCallback(base::Value(std::move(callback_id_)), + base::Value(static_cast<int>(*reset_result_))); + reset_.reset(); + break; + + default: + NOTREACHED(); + } +} + +void SecurityKeysHandler::OnResetFinished( + device::CtapDeviceResponseCode result) { + switch (state_) { + case State::kWaitingForResetNoCallbackYet: + // The reset operation has completed, but Javascript hasn't called + // |CompleteReset| so we cannot make the callback yet. + state_ = State::kWaitingForCompleteReset; + reset_result_ = result; + break; + + case State::kStartReset: + // The reset operation failed immediately, probably because the user + // selected a U2F device. |callback_id_| has been set by |Reset|. + [[fallthrough]]; + + case State::kWaitingForResetHaveCallback: + // The |CompleteReset| call has already provided |callback_id_| so the + // reset can be completed immediately. + state_ = State::kNone; + ResolveJavascriptCallback(base::Value(std::move(callback_id_)), + base::Value(static_cast<int>(result))); + reset_.reset(); + break; + + default: + NOTREACHED(); + } +} + +void SecurityKeysHandler::HandleClose(const base::ListValue* args) { + DCHECK_EQ(0u, args->GetSize()); + Close(); +} + +} // namespace settings
diff --git a/chrome/browser/ui/webui/settings/settings_security_key_handler.h b/chrome/browser/ui/webui/settings/settings_security_key_handler.h new file mode 100644 index 0000000..353d85c --- /dev/null +++ b/chrome/browser/ui/webui/settings/settings_security_key_handler.h
@@ -0,0 +1,78 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CHROME_BROWSER_UI_WEBUI_SETTINGS_SETTINGS_SECURITY_KEY_HANDLER_H_ +#define CHROME_BROWSER_UI_WEBUI_SETTINGS_SETTINGS_SECURITY_KEY_HANDLER_H_ + +#include <memory> +#include <string> + +#include "base/macros.h" +#include "base/memory/weak_ptr.h" +#include "base/optional.h" +#include "device/fido/fido_constants.h" + +namespace base { +class ListValue; +} + +namespace device { +class SetPINRequestHandler; +class ResetRequestHandler; +} // namespace device + +namespace settings { + +// SecurityKeysHandler processes messages from the "Security Keys" section of a +// settings page. An instance of this class is created for each settings tab and +// is destroyed when the tab is closed. See the comments in +// security_keys_browser_proxy.js about the interface. +class SecurityKeysHandler : public SettingsPageUIHandler { + public: + SecurityKeysHandler(); + ~SecurityKeysHandler() override; + + void RegisterMessages() override; + void OnJavascriptAllowed() override; + void OnJavascriptDisallowed() override; + + private: + enum class State { + kNone, + + kStartSetPIN, + kGatherNewPIN, + kGatherChangePIN, + kSettingPIN, + + kStartReset, + kWaitingForResetNoCallbackYet, + kWaitingForResetHaveCallback, + kWaitingForCompleteReset, + }; + + void Close(); + void HandleStartSetPIN(const base::ListValue* args); + void OnGatherPIN(base::Optional<int64_t> num_retries); + void OnSetPINComplete(device::CtapDeviceResponseCode code); + void HandleSetPIN(const base::ListValue* args); + void HandleReset(const base::ListValue* args); + void OnResetSent(); + void HandleCompleteReset(const base::ListValue* args); + void OnResetFinished(device::CtapDeviceResponseCode result); + void HandleClose(const base::ListValue* args); + + State state_; + std::unique_ptr<device::SetPINRequestHandler> set_pin_; + std::unique_ptr<device::ResetRequestHandler> reset_; + base::Optional<device::CtapDeviceResponseCode> reset_result_; + std::string callback_id_; + std::unique_ptr<base::WeakPtrFactory<SecurityKeysHandler>> weak_factory_; + + DISALLOW_COPY_AND_ASSIGN(SecurityKeysHandler); +}; + +} // namespace settings + +#endif // CHROME_BROWSER_UI_WEBUI_SETTINGS_SETTINGS_SECURITY_KEY_HANDLER_H_
diff --git a/chrome/browser/ui/webui/signin/inline_login_handler_chromeos.cc b/chrome/browser/ui/webui/signin/inline_login_handler_chromeos.cc index 8b85f10..5fd630e 100644 --- a/chrome/browser/ui/webui/signin/inline_login_handler_chromeos.cc +++ b/chrome/browser/ui/webui/signin/inline_login_handler_chromeos.cc
@@ -56,10 +56,11 @@ void OnClientOAuthSuccess(const ClientOAuthResult& result) override { // Flow of control after this call: // |AccountManager::UpsertAccount| updates / inserts the account and calls - // its |Observer|s, one of which is |ChromeOSOAuth2TokenServiceDelegate|. - // |ChromeOSOAuth2TokenServiceDelegate::OnTokenUpserted| seeds the Gaia id - // and email id for this account in |AccountTrackerService| and invokes - // |FireRefreshTokenAvailable|. This causes the account to propagate + // its |Observer|s, one of which is + // |ProfileOAuth2TokenServiceDelegateChromeOS|. + // |ProfileOAuth2TokenServiceDelegateChromeOS::OnTokenUpserted| seeds the + // Gaia id and email id for this account in |AccountTrackerService| and + // invokes |FireRefreshTokenAvailable|. This causes the account to propagate // throughout the Identity Service chain, including in // |AccountFetcherService|. |AccountFetcherService::OnRefreshTokenAvailable| // invokes |AccountTrackerService::StartTrackingAccount|, triggers a fetch
diff --git a/chrome/browser/ui/webui/web_ui_test_handler.cc b/chrome/browser/ui/webui/web_ui_test_handler.cc index 617d2645..24e7b89 100644 --- a/chrome/browser/ui/webui/web_ui_test_handler.cc +++ b/chrome/browser/ui/webui/web_ui_test_handler.cc
@@ -43,7 +43,7 @@ void WebUITestHandler::RunJavaScript(const base::string16& js_text) { GetWebUI()->GetWebContents()->GetMainFrame()->ExecuteJavaScriptForTests( - js_text); + js_text, base::NullCallback()); } bool WebUITestHandler::RunJavaScriptTestWithResult(
diff --git a/chrome/browser/ui/webui/webui_browsertest.cc b/chrome/browser/ui/webui/webui_browsertest.cc index 969ce23..a48e98c9 100644 --- a/chrome/browser/ui/webui/webui_browsertest.cc +++ b/chrome/browser/ui/webui/webui_browsertest.cc
@@ -5,6 +5,7 @@ #include <utility> #include "base/bind.h" +#include "base/bind_helpers.h" #include "base/callback.h" #include "base/command_line.h" #include "base/memory/ptr_util.h" @@ -94,7 +95,8 @@ void SendMessageAndWaitForFinish() { main_rfh()->ExecuteJavaScriptForTests( base::ASCIIToUTF16("chrome.send('messageRequiringGesture');" - "chrome.send('notifyFinish');")); + "chrome.send('notifyFinish');"), + base::NullCallback()); base::RunLoop run_loop; test_handler()->set_finish_closure(run_loop.QuitClosure()); run_loop.Run();
diff --git a/chrome/chrome_cleaner/logging/proto/BUILD.gn b/chrome/chrome_cleaner/logging/proto/BUILD.gn index 49b8a254..ac4ca0c3 100644 --- a/chrome/chrome_cleaner/logging/proto/BUILD.gn +++ b/chrome/chrome_cleaner/logging/proto/BUILD.gn
@@ -9,9 +9,7 @@ "shared_data.proto", ] - deps = [ - ":removal_status_proto", - ] + link_deps = [ ":removal_status_proto" ] } proto_library("chrome_cleaner_report_proto") { @@ -19,20 +17,13 @@ "chrome_cleaner_report.proto", ] - deps = [ - ":shared_data_proto", - "//third_party/protobuf:py_proto", - ] + link_deps = [ ":shared_data_proto" ] } proto_library("removal_status_proto") { sources = [ "removal_status.proto", ] - - deps = [ - "//third_party/protobuf:py_proto", - ] } proto_library("reporter_logs_proto") { @@ -40,10 +31,7 @@ "reporter_logs.proto", ] - deps = [ - ":shared_data_proto", - "//third_party/protobuf:py_proto", - ] + link_deps = [ ":shared_data_proto" ] } proto_library("interface_logger_proto") { @@ -52,10 +40,12 @@ ] } -# A target that depends on all the protos imported directly from Python scripts. +# A target that depends on all the protos and protobuf libs imported directly +# from Python scripts. group("ensure_py_protos") { deps = [ ":chrome_cleaner_report_proto", ":reporter_logs_proto", + "//third_party/protobuf:py_proto", ] }
diff --git a/chrome/chrome_cleaner/parsers/json_parser/test_json_parser.cc b/chrome/chrome_cleaner/parsers/json_parser/test_json_parser.cc index d5eeafd..3098237 100644 --- a/chrome/chrome_cleaner/parsers/json_parser/test_json_parser.cc +++ b/chrome/chrome_cleaner/parsers/json_parser/test_json_parser.cc
@@ -12,20 +12,15 @@ void TestJsonParser::Parse(const std::string& json, ParseDoneCallback callback) { - int error_code; - std::string error; - std::unique_ptr<base::Value> value = - base::JSONReader::ReadAndReturnErrorDeprecated( - json, - base::JSON_ALLOW_TRAILING_COMMAS | - base::JSON_REPLACE_INVALID_CHARACTERS, - &error_code, &error); - if (value) { - std::move(callback).Run(base::make_optional(std::move(*value)), - base::nullopt); + base::JSONReader::ValueWithError value_with_error = + base::JSONReader::ReadAndReturnValueWithError( + json, base::JSON_ALLOW_TRAILING_COMMAS | + base::JSON_REPLACE_INVALID_CHARACTERS); + if (value_with_error.value) { + std::move(callback).Run(std::move(value_with_error.value), base::nullopt); } else { - std::move(callback).Run(base::nullopt, - base::make_optional(std::move(error))); + std::move(callback).Run( + base::nullopt, base::make_optional(value_with_error.error_message)); } }
diff --git a/chrome/chrome_cleaner/proto/BUILD.gn b/chrome/chrome_cleaner/proto/BUILD.gn index 7081e54..188ff8b 100644 --- a/chrome/chrome_cleaner/proto/BUILD.gn +++ b/chrome/chrome_cleaner/proto/BUILD.gn
@@ -9,19 +9,13 @@ "uwe_matcher.proto", ] - deps = [ - ":uws_spec_by_version_proto", - ] + link_deps = [ ":uws_spec_by_version_proto" ] } proto_library("file_digest_proto") { sources = [ "file_digest.proto", ] - - deps = [ - "//third_party/protobuf:py_proto", - ] } proto_library("shared_pup_enums_proto") { @@ -34,10 +28,6 @@ sources = [ "spec_footprints.proto", ] - - deps = [ - "//third_party/protobuf:py_proto", - ] } proto_library("uws_spec_by_version_proto") { @@ -45,8 +35,5 @@ "uws_spec_by_version.proto", ] - deps = [ - ":shared_pup_enums_proto", - "//third_party/protobuf:py_proto", - ] + link_deps = [ ":shared_pup_enums_proto" ] }
diff --git a/chrome/test/base/mojo_web_ui_browser_test.cc b/chrome/test/base/mojo_web_ui_browser_test.cc index e811dea..764ff7e 100644 --- a/chrome/test/base/mojo_web_ui_browser_test.cc +++ b/chrome/test/base/mojo_web_ui_browser_test.cc
@@ -5,6 +5,7 @@ #include "chrome/test/base/mojo_web_ui_browser_test.h" #include "base/bind.h" +#include "base/bind_helpers.h" #include "base/macros.h" #include "base/path_service.h" #include "chrome/browser/ui/browser.h" @@ -104,9 +105,11 @@ browser()->tab_strip_model()->GetActiveWebContents(); if (use_mojo_lite_bindings_) { web_contents->GetMainFrame()->ExecuteJavaScriptForTests( - l10n_util::GetStringUTF16(IDR_WEB_UI_TEST_MOJO_LITE_JS)); + l10n_util::GetStringUTF16(IDR_WEB_UI_TEST_MOJO_LITE_JS), + base::NullCallback()); } else { web_contents->GetMainFrame()->ExecuteJavaScriptForTests( - l10n_util::GetStringUTF16(IDR_WEB_UI_TEST_MOJO_JS)); + l10n_util::GetStringUTF16(IDR_WEB_UI_TEST_MOJO_JS), + base::NullCallback()); } }
diff --git a/chrome/test/base/test_browser_window.h b/chrome/test/base/test_browser_window.h index 4e125ab..b892b9d 100644 --- a/chrome/test/base/test_browser_window.h +++ b/chrome/test/base/test_browser_window.h
@@ -60,7 +60,6 @@ void SetTopControlsGestureScrollInProgress(bool in_progress) override; StatusBubble* GetStatusBubble() override; void UpdateTitleBar() override {} - void UpdateFrameColor() override {} void BookmarkBarStateChanged( BookmarkBar::AnimateChangeType change_type) override {} void UpdateDevTools() override {}
diff --git a/chrome/test/data/policy/policy_test_cases.json b/chrome/test/data/policy/policy_test_cases.json index 67a7b1d..a9af93bd 100644 --- a/chrome/test/data/policy/policy_test_cases.json +++ b/chrome/test/data/policy/policy_test_cases.json
@@ -4266,6 +4266,16 @@ "pref_mappings": [{ "pref": "cros.device.wilco_dtc_allowed" }] }, + "DeviceWilcoDtcConfiguration": { + "os": ["chromeos"], + "test_policy": { + "DeviceWilcoDtcCOnfiguration": { + "url": "https://example.com/wilcodtcconfiguration", + "hash": "deadbeefdeadbeefdeadbeef" + } + } + }, + "----- Chrome Frame policies -------------------------------------------": {}, "ChromeFrameRendererSettings": {
diff --git a/chrome/test/data/webrtc/munge_sdp.js b/chrome/test/data/webrtc/munge_sdp.js index b9b1ee4..e66b3b56 100644 --- a/chrome/test/data/webrtc/munge_sdp.js +++ b/chrome/test/data/webrtc/munge_sdp.js
@@ -84,6 +84,30 @@ sdpLines[bLineNo] = "b=AS:" + bitrate; } + // The default codec's ID. + var defaultCodecId = getMLineDefaultCodec(sdpLines[mLineNo]); + if (defaultCodecId === null) { + failure('setSdpTargetBitrate', + '\'m=' + type + '\' line contains no codecs.'); + } + // Find "a=rtpmap:96" line. + var rtpMapLineNo = findRtpmapLine(sdpLines, defaultCodecId); + if (rtpMapLineNo === null) { + failure('setSdpTargetBitrate', + '\'a=rtpmap:XX line could not be found.'); + } else { + rtpMapLineNo += 1 + var newLines = sdpLines.slice(0, rtpMapLineNo) + newLines.push( + 'a=fmtp:' + defaultCodecId + ' x-google-start-bitrate=' + bitrate) + newLines.push( + 'a=fmtp:' + defaultCodecId + ' x-google-min-bitrate=' + bitrate) + newLines.push( + 'a=fmtp:' + defaultCodecId + ' x-google-max-bitrate=' + 2 * bitrate) + newLines = newLines.concat(sdpLines.slice(rtpMapLineNo, sdpLines.length)) + sdpLines = newLines; + } + return mergeSdpLines(sdpLines); }
diff --git a/chrome/test/data/webrtc/peerconnection.js b/chrome/test/data/webrtc/peerconnection.js index b6abdf1..dc1bf5b 100644 --- a/chrome/test/data/webrtc/peerconnection.js +++ b/chrome/test/data/webrtc/peerconnection.js
@@ -246,6 +246,10 @@ if (gOpusDtx) { answer.sdp = setOpusDtxEnabled(answer.sdp); } + if (gDefaultVideoTargetBitrate !== null) { + answer.sdp = setSdpVideoTargetBitrate(answer.sdp, + gDefaultVideoTargetBitrate); + } returnToTest('ok-' + JSON.stringify(answer)); }, function(error) { failure('createAnswer', error); },
diff --git a/chrome/tools/build/win/FILES.cfg b/chrome/tools/build/win/FILES.cfg index e91b265..08201f0 100644 --- a/chrome/tools/build/win/FILES.cfg +++ b/chrome/tools/build/win/FILES.cfg
@@ -662,6 +662,11 @@ 'archive': 'chrome-win32-syms.zip', }, { + 'filename': 'chrome_watcher.dll.pdb', + 'buildtype': ['dev', 'official'], + 'archive': 'chrome-win32-syms.zip', + }, + { 'filename': 'chrome.exe.pdb', 'buildtype': ['dev', 'official'], 'archive': 'chrome-win32-syms.zip',
diff --git a/chromecast/BUILD.gn b/chromecast/BUILD.gn index e998648..4e6a6d6 100644 --- a/chromecast/BUILD.gn +++ b/chromecast/BUILD.gn
@@ -658,5 +658,6 @@ loadable_modules = [ "$root_out_dir/libcrashpad_handler.so" ] command_line_flags_file = "castshell-command-line" + enable_multidex = true } }
diff --git a/chromeos/account_manager/account_manager.h b/chromeos/account_manager/account_manager.h index 26de53a0..32d0c42 100644 --- a/chromeos/account_manager/account_manager.h +++ b/chromeos/account_manager/account_manager.h
@@ -204,8 +204,8 @@ // Returns true if the token stored against |account_key| is a dummy Gaia // token. This is meant to be used only by - // |ChromeOSOAuth2TokenServiceDelegate| to pre-emptively reject access token - // requests for |account_key|. + // |ProfileOAuth2TokenServiceDelegateChromeOS| to pre-emptively reject access + // token requests for |account_key|. bool HasDummyGaiaToken(const AccountKey& account_key) const; private:
diff --git a/components/autofill/core/browser/webdata/autofill_profile_data_type_controller.cc b/components/autofill/core/browser/webdata/autofill_profile_data_type_controller.cc index bd2bff7..ae89e65 100644 --- a/components/autofill/core/browser/webdata/autofill_profile_data_type_controller.cc +++ b/components/autofill/core/browser/webdata/autofill_profile_data_type_controller.cc
@@ -14,7 +14,6 @@ #include "components/autofill/core/common/autofill_features.h" #include "components/autofill/core/common/autofill_prefs.h" #include "components/prefs/pref_service.h" -#include "components/sync/base/experiments.h" #include "components/sync/driver/sync_client.h" #include "components/sync/driver/sync_service.h" #include "components/sync/model/sync_error.h"
diff --git a/components/autofill/core/browser/webdata/autofill_wallet_metadata_sync_bridge_unittest.cc b/components/autofill/core/browser/webdata/autofill_wallet_metadata_sync_bridge_unittest.cc index d5211f2..0635a8d 100644 --- a/components/autofill/core/browser/webdata/autofill_wallet_metadata_sync_bridge_unittest.cc +++ b/components/autofill/core/browser/webdata/autofill_wallet_metadata_sync_bridge_unittest.cc
@@ -309,8 +309,7 @@ ReceiveUpdates(remote_data); } - void ReceiveUpdates( - const std::vector<WalletMetadataSpecifics>& remote_data = {}) { + void ReceiveUpdates(const std::vector<WalletMetadataSpecifics>& remote_data) { // Make sure each update has an updated response version so that it does not // get filtered out as reflection by the processor. ++response_version; @@ -325,18 +324,43 @@ real_processor_->OnUpdateReceived(state, updates); } - EntityData SpecificsToEntity(const WalletMetadataSpecifics& specifics) { + void ReceiveTombstones( + const std::vector<WalletMetadataSpecifics>& remote_tombstones) { + // Make sure each update has an updated response version so that it does not + // get filtered out as reflection by the processor. + ++response_version; + // After this update initial sync is for sure done. + sync_pb::ModelTypeState state; + state.set_initial_sync_done(true); + + syncer::UpdateResponseDataList updates; + for (const WalletMetadataSpecifics& specifics : remote_tombstones) { + updates.push_back( + SpecificsToUpdateResponse(specifics, /*is_deleted=*/true)); + } + real_processor_->OnUpdateReceived(state, updates); + } + + EntityData SpecificsToEntity(const WalletMetadataSpecifics& specifics, + bool is_deleted = false) { EntityData data; *data.specifics.mutable_wallet_metadata() = specifics; data.client_tag_hash = syncer::GenerateSyncableHash( syncer::AUTOFILL_WALLET_METADATA, bridge()->GetClientTag(data)); + if (is_deleted) { + // Specifics had to be set in order to generate the client tag. Since + // deleted entity is defined by specifics being empty, we need to clear + // them now. + data.specifics = sync_pb::EntitySpecifics(); + } return data; } syncer::UpdateResponseData SpecificsToUpdateResponse( - const WalletMetadataSpecifics& specifics) { + const WalletMetadataSpecifics& specifics, + bool is_deleted = false) { syncer::UpdateResponseData data; - data.entity = SpecificsToEntity(specifics).PassToPtr(); + data.entity = SpecificsToEntity(specifics, is_deleted).PassToPtr(); data.response_version = response_version; return data; } @@ -382,6 +406,20 @@ return data; } + std::vector<std::string> GetLocalSyncMetadataStorageKeys() { + std::vector<std::string> storage_keys; + + AutofillTable* table = AutofillTable::FromWebDatabase(&db_); + syncer::MetadataBatch batch; + if (table->GetAllSyncMetadata(syncer::AUTOFILL_WALLET_METADATA, &batch)) { + for (std::pair<std::string, sync_pb::EntityMetadata> entry : + batch.GetAllMetadata()) { + storage_keys.push_back(entry.first); + } + } + return storage_keys; + } + void AdvanceTestClockByTwoYears() { test_clock_.Advance(base::TimeDelta::FromDays(365 * 2)); } @@ -392,6 +430,10 @@ return mock_processor_; } + syncer::ClientTagBasedModelTypeProcessor* real_processor() { + return real_processor_.get(); + } + AutofillTable* table() { return &table_; } MockAutofillWebDataBackend* backend() { return &backend_; } @@ -824,6 +866,192 @@ UnorderedElementsAre(EqualsSpecifics(profile), EqualsSpecifics(card))); } +// Test that both local cards and local profiles that are not in the remote data +// set are uploaded during initial sync. This should rarely happen in practice +// because we wipe local data when disabling sync. Still there are corner cases +// such as when PDM manages to change metadata before the metadata bridge +// performs initial sync. +TEST_F(AutofillWalletMetadataSyncBridgeTest, + InitialSync_UploadUniqueLocalData) { + WalletMetadataSpecifics preexisting_profile = + CreateWalletMetadataSpecificsForAddressWithDetails( + kAddr1SpecificsId, /*use_count=*/10, /*use_date=*/20); + WalletMetadataSpecifics preexisting_card = + CreateWalletMetadataSpecificsForCardWithDetails( + kCard1SpecificsId, /*use_count=*/30, /*use_date=*/40); + + table()->SetServerProfiles( + {CreateServerProfileFromSpecifics(preexisting_profile)}); + table()->SetServerCreditCards( + {CreateServerCreditCardFromSpecifics(preexisting_card)}); + + // Have different entities on the server. + WalletMetadataSpecifics remote_profile = + CreateWalletMetadataSpecificsForAddressWithDetails( + kAddr2SpecificsId, /*use_count=*/10, /*use_date=*/20); + WalletMetadataSpecifics remote_card = + CreateWalletMetadataSpecificsForCardWithDetails( + kCard2SpecificsId, /*use_count=*/30, /*use_date=*/40); + + // The bridge should upload the unique local entities and store the remote + // ones locally. + EXPECT_CALL(mock_processor(), + Put(kAddr1StorageKey, HasSpecifics(preexisting_profile), _)); + EXPECT_CALL(mock_processor(), + Put(kCard1StorageKey, HasSpecifics(preexisting_card), _)); + EXPECT_CALL(mock_processor(), Delete(_, _)).Times(0); + + ResetBridge(/*initial_sync_done=*/false); + StartSyncing({remote_profile, remote_card}); + + EXPECT_THAT(GetAllLocalDataInclRestart(), + UnorderedElementsAre(EqualsSpecifics(preexisting_profile), + EqualsSpecifics(preexisting_card), + EqualsSpecifics(remote_profile), + EqualsSpecifics(remote_card))); +} + +// Test that the initial sync correctly distinguishes data that is unique in the +// local data set from data that is both in the local data and in the remote +// data. We should only upload the local data. This should rarely happen in +// practice because we wipe local data when disabling sync. Still there are +// corner cases such as when PDM manages to change metadata before the metadata +// bridge performs initial sync. +TEST_F(AutofillWalletMetadataSyncBridgeTest, + InitialSync_UploadOnlyUniqueLocalData) { + WalletMetadataSpecifics preexisting_profile = + CreateWalletMetadataSpecificsForAddressWithDetails( + kAddr1SpecificsId, /*use_count=*/10, /*use_date=*/20); + WalletMetadataSpecifics preexisting_card = + CreateWalletMetadataSpecificsForCardWithDetails( + kCard1SpecificsId, /*use_count=*/30, /*use_date=*/40); + + table()->SetServerProfiles( + {CreateServerProfileFromSpecifics(preexisting_profile)}); + table()->SetServerCreditCards( + {CreateServerCreditCardFromSpecifics(preexisting_card)}); + + // The remote profile has the same id as local profile, only is newer. + WalletMetadataSpecifics remote_profile = + CreateWalletMetadataSpecificsForAddressWithDetails( + kAddr1SpecificsId, /*use_count=*/15, /*use_date=*/25); + WalletMetadataSpecifics remote_card = + CreateWalletMetadataSpecificsForCardWithDetails( + kCard2SpecificsId, /*use_count=*/30, /*use_date=*/40); + + // Upload _only_ the unique local data, only the card. + EXPECT_CALL(mock_processor(), + Put(kCard1StorageKey, HasSpecifics(preexisting_card), _)); + EXPECT_CALL(mock_processor(), Delete(_, _)).Times(0); + + ResetBridge(/*initial_sync_done=*/false); + StartSyncing({remote_profile, remote_card}); + + EXPECT_THAT(GetAllLocalDataInclRestart(), + UnorderedElementsAre(EqualsSpecifics(preexisting_card), + EqualsSpecifics(remote_profile), + EqualsSpecifics(remote_card))); +} + +// Test that remote deletions are properly propagated into the local database. +TEST_F(AutofillWalletMetadataSyncBridgeTest, + RemoteDeletion_ShouldDeleteExistingLocalData) { + // Perform initial sync to create sync data & metadata. + ResetBridge(/*initial_sync_done=*/false); + WalletMetadataSpecifics profile = + CreateWalletMetadataSpecificsForAddressWithDetails( + kAddr1SpecificsId, /*use_count=*/10, /*use_date=*/20); + WalletMetadataSpecifics card = + CreateWalletMetadataSpecificsForCardWithDetails( + kCard1SpecificsId, /*use_count=*/30, /*use_date=*/40); + StartSyncing({profile, card}); + + // Verify that both the processor and the local DB contain sync metadata. + ASSERT_TRUE(real_processor()->IsTrackingEntityForTest(kAddr1StorageKey)); + ASSERT_TRUE(real_processor()->IsTrackingEntityForTest(kCard1StorageKey)); + ASSERT_THAT(GetLocalSyncMetadataStorageKeys(), + UnorderedElementsAre(kAddr1StorageKey, kCard1StorageKey)); + + // Now delete the profile. Changes should happen in the local database. + EXPECT_CALL(*backend(), NotifyOfMultipleAutofillChanges()); + ReceiveTombstones({profile, card}); + + // Verify that both data and sync metadata is gone. + EXPECT_FALSE(real_processor()->IsTrackingEntityForTest(kAddr1StorageKey)); + EXPECT_FALSE(real_processor()->IsTrackingEntityForTest(kCard1StorageKey)); + EXPECT_THAT(GetLocalSyncMetadataStorageKeys(), IsEmpty()); + EXPECT_THAT(GetAllLocalDataInclRestart(), IsEmpty()); +} + +// Test that remote deletions are properly handled even when the local data is +// already deleted. We should still delete sync metadata both from the DB and +// from the processor internal memory. +TEST_F(AutofillWalletMetadataSyncBridgeTest, + RemoteDeletion_ShouldNotNotifyChangesWhenLocalDataIsGone) { + // Perform initial sync to create sync data & metadata. + ResetBridge(/*initial_sync_done=*/false); + WalletMetadataSpecifics profile = + CreateWalletMetadataSpecificsForAddressWithDetails( + kAddr1SpecificsId, /*use_count=*/10, /*use_date=*/20); + WalletMetadataSpecifics card = + CreateWalletMetadataSpecificsForCardWithDetails( + kCard1SpecificsId, /*use_count=*/30, /*use_date=*/40); + StartSyncing({profile, card}); + + // Clear the data from the local DB, sync metadata stays untouched both in the + // processor and in the local DB. + table()->SetServerProfiles({}); + table()->SetServerCreditCards({}); + ASSERT_TRUE(real_processor()->IsTrackingEntityForTest(kAddr1StorageKey)); + ASSERT_TRUE(real_processor()->IsTrackingEntityForTest(kCard1StorageKey)); + ASSERT_THAT(GetLocalSyncMetadataStorageKeys(), + UnorderedElementsAre(kAddr1StorageKey, kCard1StorageKey)); + + // Send a deletions from the server. Since the data is already deleted, it + // should not notify about changes. The entities should however get deleted + // from the processor. + EXPECT_CALL(*backend(), NotifyOfMultipleAutofillChanges()).Times(0); + ReceiveTombstones({profile, card}); + + // Verify that sync metadata is gone from both the processor and local DB. + EXPECT_FALSE(real_processor()->IsTrackingEntityForTest(kAddr1StorageKey)); + EXPECT_FALSE(real_processor()->IsTrackingEntityForTest(kCard1StorageKey)); + EXPECT_THAT(GetLocalSyncMetadataStorageKeys(), IsEmpty()); + EXPECT_THAT(GetAllLocalDataInclRestart(), IsEmpty()); +} + +// Test that remote deletions are ignored if there is no sync metadata for the +// entity. +TEST_F(AutofillWalletMetadataSyncBridgeTest, + RemoteDeletion_ShouldNotDeleteLocalDataWithoutSyncMetadata) { + WalletMetadataSpecifics profile = + CreateWalletMetadataSpecificsForAddressWithDetails( + kAddr1SpecificsId, /*use_count=*/10, /*use_date=*/20); + WalletMetadataSpecifics card = + CreateWalletMetadataSpecificsForCardWithDetails( + kCard1SpecificsId, /*use_count=*/30, /*use_date=*/40); + + table()->SetServerProfiles({CreateServerProfileFromSpecifics(profile)}); + table()->SetServerCreditCards({CreateServerCreditCardFromSpecifics(card)}); + + // Do not perform initial sync. This way, no sync metadata gets created, the + // processor does not know about the entities and thus, it should not delete + // them. + ResetBridge(/*initial_sync_done=*/true); + StartSyncing({}); + ASSERT_FALSE(real_processor()->IsTrackingEntityForTest(kAddr1StorageKey)); + ASSERT_FALSE(real_processor()->IsTrackingEntityForTest(kCard1StorageKey)); + ASSERT_THAT(GetLocalSyncMetadataStorageKeys(), IsEmpty()); + + // Send a deletion from the server. The deletion should get ignored. + EXPECT_CALL(*backend(), NotifyOfMultipleAutofillChanges()).Times(0); + ReceiveTombstones({profile, card}); + + EXPECT_THAT( + GetAllLocalDataInclRestart(), + UnorderedElementsAre(EqualsSpecifics(profile), EqualsSpecifics(card))); +} + enum RemoteChangesMode { INITIAL_SYNC_ADD, // Initial sync -> ADD changes. LATER_SYNC_ADD, // Later sync; the client receives the data for the first @@ -843,8 +1071,7 @@ void ResetBridgeWithPotentialInitialSync( const std::vector<WalletMetadataSpecifics>& remote_data) { - AutofillWalletMetadataSyncBridgeTest::ResetBridge( - /*initial_sync_done=*/GetParam() != INITIAL_SYNC_ADD); + ResetBridge(/*initial_sync_done=*/GetParam() != INITIAL_SYNC_ADD); if (GetParam() == LATER_SYNC_UPDATE) { StartSyncing(remote_data); @@ -852,11 +1079,11 @@ } void ReceivePotentiallyInitialUpdates( - const std::vector<WalletMetadataSpecifics>& remote_data = {}) { + const std::vector<WalletMetadataSpecifics>& remote_data) { if (GetParam() != LATER_SYNC_UPDATE) { StartSyncing(remote_data); } else { - AutofillWalletMetadataSyncBridgeTest::ReceiveUpdates(remote_data); + ReceiveUpdates(remote_data); } }
diff --git a/components/autofill_assistant/browser/actions/show_details_action.cc b/components/autofill_assistant/browser/actions/show_details_action.cc index b86a64d..3839729 100644 --- a/components/autofill_assistant/browser/actions/show_details_action.cc +++ b/components/autofill_assistant/browser/actions/show_details_action.cc
@@ -34,9 +34,14 @@ details_valid = Details::UpdateFromProto(proto_.show_details(), details.get()); break; - case ShowDetailsProto::DataToShowCase::kSelectedAddress: + case ShowDetailsProto::DataToShowCase::kContactDetails: details = std::make_unique<Details>(); - details_valid = Details::UpdateFromSelectedAddress( + details_valid = Details::UpdateFromContactDetails( + proto_.show_details(), delegate->GetClientMemory(), details.get()); + break; + case ShowDetailsProto::DataToShowCase::kShippingAddress: + details = std::make_unique<Details>(); + details_valid = Details::UpdateFromShippingAddress( proto_.show_details(), delegate->GetClientMemory(), details.get()); break; case ShowDetailsProto::DataToShowCase::kCreditCard:
diff --git a/components/autofill_assistant/browser/controller.cc b/components/autofill_assistant/browser/controller.cc index 2e8cc30..7566bff 100644 --- a/components/autofill_assistant/browser/controller.cc +++ b/components/autofill_assistant/browser/controller.cc
@@ -723,7 +723,7 @@ void Controller::GetTouchableArea(std::vector<RectF>* area) const { if (touchable_element_area_) - touchable_element_area_->GetArea(area); + touchable_element_area_->GetRectangles(area); } void Controller::OnFatalError(const std::string& error_message,
diff --git a/components/autofill_assistant/browser/details.cc b/components/autofill_assistant/browser/details.cc index bb275720..5fc9edda 100644 --- a/components/autofill_assistant/browser/details.cc +++ b/components/autofill_assistant/browser/details.cc
@@ -10,6 +10,7 @@ #include "base/strings/strcat.h" #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" +#include "components/autofill/core/browser/country_names.h" #include "components/strings/grit/components_strings.h" #include "ui/base/l10n/l10n_util.h" @@ -37,16 +38,16 @@ } // static -bool Details::UpdateFromSelectedAddress(const ShowDetailsProto& proto, - ClientMemory* client_memory, - Details* details) { - std::string selected_address = proto.selected_address(); - if (!client_memory->has_selected_address(selected_address)) { +bool Details::UpdateFromContactDetails(const ShowDetailsProto& proto, + ClientMemory* client_memory, + Details* details) { + std::string contact_details = proto.contact_details(); + if (!client_memory->has_selected_address(contact_details)) { return false; } ShowDetailsProto updated_proto = proto; - auto* profile = client_memory->selected_address(selected_address); + auto* profile = client_memory->selected_address(contact_details); auto* details_proto = updated_proto.mutable_details(); // TODO(crbug.com/806868): Get the actual script locale. std::string app_locale = "en-US"; @@ -61,6 +62,43 @@ return true; } +// static +bool Details::UpdateFromShippingAddress(const ShowDetailsProto& proto, + ClientMemory* client_memory, + Details* details) { + std::string shipping_address = proto.shipping_address(); + if (!client_memory->has_selected_address(shipping_address)) { + return false; + } + + ShowDetailsProto updated_proto = proto; + auto* profile = client_memory->selected_address(shipping_address); + auto* details_proto = updated_proto.mutable_details(); + // TODO(crbug.com/806868): Get the actual script locale. + std::string app_locale = "en-US"; + autofill::CountryNames* country_names = autofill::CountryNames::GetInstance(); + details_proto->set_title( + l10n_util::GetStringUTF8(IDS_PAYMENTS_SHIPPING_ADDRESS_LABEL)); + details_proto->set_description_line_1( + base::UTF16ToUTF8(profile->GetInfo(autofill::NAME_FULL, app_locale))); + details_proto->set_description_line_2(base::StrCat({ + base::UTF16ToUTF8( + profile->GetInfo(autofill::ADDRESS_HOME_STREET_ADDRESS, app_locale)), + " ", + base::UTF16ToUTF8( + profile->GetInfo(autofill::ADDRESS_HOME_ZIP, app_locale)), + " ", + base::UTF16ToUTF8( + profile->GetInfo(autofill::ADDRESS_HOME_CITY, app_locale)), + " ", + country_names->GetCountryCode( + profile->GetInfo(autofill::ADDRESS_HOME_COUNTRY, app_locale)), + })); + details->SetDetailsProto(updated_proto.details()); + details->SetDetailsChangesProto(updated_proto.change_flags()); + return true; +} + bool Details::UpdateFromSelectedCreditCard(const ShowDetailsProto& proto, ClientMemory* client_memory, Details* details) {
diff --git a/components/autofill_assistant/browser/details.h b/components/autofill_assistant/browser/details.h index be019d3..310cc71 100644 --- a/components/autofill_assistant/browser/details.h +++ b/components/autofill_assistant/browser/details.h
@@ -36,9 +36,15 @@ // |details| were successfully updated. static bool UpdateFromProto(const ShowDetailsProto& proto, Details* details); - // Updates the details to show selected address. Returns true if |details| - // were successfully updated. - static bool UpdateFromSelectedAddress(const ShowDetailsProto& proto, + // Updates the details to show selected contact details. It shows only full + // name and email. Returns true if |details| were successfully updated. + static bool UpdateFromContactDetails(const ShowDetailsProto& proto, + ClientMemory* client_memory, + Details* details); + + // Updates the details to show selected shipping details. It shows full name + // and address. Returns true if |details| were successfully updated. + static bool UpdateFromShippingAddress(const ShowDetailsProto& proto, ClientMemory* client_memory, Details* details);
diff --git a/components/autofill_assistant/browser/element_area.cc b/components/autofill_assistant/browser/element_area.cc index dcfc956e..2617d5c 100644 --- a/components/autofill_assistant/browser/element_area.cc +++ b/components/autofill_assistant/browser/element_area.cc
@@ -84,23 +84,10 @@ } } -bool ElementArea::IsEmpty() const { - for (const auto& rectangle : rectangles_) { - for (const auto& position : rectangle.positions) { - if (!position.rect.empty()) { - return false; - } - } - } - return true; -} - -void ElementArea::GetArea(std::vector<RectF>* area) { +void ElementArea::GetRectangles(std::vector<RectF>* area) { for (auto& rectangle : rectangles_) { - RectF rect; - if (rectangle.FillRect(&rect)) { - area->emplace_back(rect); - } + area->emplace_back(); + rectangle.FillRect(&area->back()); } } @@ -121,7 +108,7 @@ return false; } -bool ElementArea::Rectangle::FillRect(RectF* rect) const { +void ElementArea::Rectangle::FillRect(RectF* rect) const { bool has_first_rect = false; for (const auto& position : positions) { if (position.rect.empty()) @@ -137,14 +124,11 @@ rect->left = std::min(rect->left, position.rect.left); rect->right = std::max(rect->right, position.rect.right); } - if (!has_first_rect) - return false; - - if (full_width) { + if (has_first_rect && full_width) { rect->left = 0.0; rect->right = 1.0; } - return true; + return; } void ElementArea::KeepUpdatingElementPositions() { @@ -194,7 +178,7 @@ } std::vector<RectF> area; - GetArea(&area); + GetRectangles(&area); on_update_.Run(area); }
diff --git a/components/autofill_assistant/browser/element_area.h b/components/autofill_assistant/browser/element_area.h index 35b39ca..1074ccd 100644 --- a/components/autofill_assistant/browser/element_area.h +++ b/components/autofill_assistant/browser/element_area.h
@@ -43,27 +43,24 @@ // Does nothing if the area is empty. void UpdatePositions(); - // Returns true if there are no elements to check or if the elements don't - // exist. - bool IsEmpty() const; - - // Returns true if there are elements to check. - bool HasElements() const { return !rectangles_.empty(); } - // Defines a callback that'll be run every time the set of element coordinates // changes. // // The argument reports the areas that corresponds to currently known // elements, which might be empty. void SetOnUpdate( - base::RepeatingCallback<void(const std::vector<RectF>& areas)> cb) { + base::RepeatingCallback<void(const std::vector<RectF>& rectangles)> cb) { on_update_ = cb; } - // Adds the current touchable area to the vector, if any are available. + // Gets the position on the screen of all the rectangles that correspond to + // the configured area. + // + // Each element in the vector corresponds to a rectangle, which might or might + // not be empty. // // Note that the vector is not cleared before rectangles are added. - void GetArea(std::vector<RectF>* area); + void GetRectangles(std::vector<RectF>* area); private: // A rectangle that corresponds to the area of the visual viewport covered by @@ -98,7 +95,7 @@ bool IsPending() const; // Fills the given rectangle from the current state, if possible. - bool FillRect(RectF* rect) const; + void FillRect(RectF* rect) const; }; void KeepUpdatingElementPositions();
diff --git a/components/autofill_assistant/browser/element_area_unittest.cc b/components/autofill_assistant/browser/element_area_unittest.cc index 8ad4115..b4c0188 100644 --- a/components/autofill_assistant/browser/element_area_unittest.cc +++ b/components/autofill_assistant/browser/element_area_unittest.cc
@@ -6,6 +6,7 @@ #include <algorithm> #include <map> +#include <ostream> #include "base/bind.h" #include "base/strings/stringprintf.h" @@ -24,6 +25,19 @@ namespace autofill_assistant { +// User-friendly RectF string representation for matchers. +// +// operator<< must not be in an anonymous namespace to be usable in all +// matchers. +std::string ToString(const RectF& rect) { + return base::StringPrintf("RectF(%2.2f, %2.2f, %2.2f, %2.2f)", rect.left, + rect.top, rect.right, rect.bottom); +} + +std::ostream& operator<<(std::ostream& out, const RectF& rectf) { + return out << ToString(rectf); +} + namespace { MATCHER_P4(MatchingRectF, @@ -31,13 +45,21 @@ top, right, bottom, - base::StringPrintf("MatchingRectF(%2.2f, %2.2f, %2.2f, %2.2f)", - left, - top, - right, - bottom)) { - return abs(left - arg.left) < 0.01 && abs(top - arg.top) < 0.01 && - abs(right - arg.right) < 0.01 && abs(bottom - arg.bottom) < 0.01; + ToString(RectF{left, top, right, bottom})) { + if (abs(left - arg.left) < 0.01 && abs(top - arg.top) < 0.01 && + abs(right - arg.right) < 0.01 && abs(bottom - arg.bottom) < 0.01) { + return true; + } + *result_listener << arg; + return false; +} + +MATCHER(EmptyRectF, "EmptyRectF") { + if (arg.empty()) + return true; + + *result_listener << arg; + return false; } ACTION(DoNothing) {} @@ -74,22 +96,20 @@ }; TEST_F(ElementAreaTest, Empty) { - EXPECT_TRUE(element_area_.IsEmpty()); EXPECT_THAT(reported_area_, IsEmpty()); std::vector<RectF> rectangles; - element_area_.GetArea(&rectangles); + element_area_.GetRectangles(&rectangles); EXPECT_THAT(rectangles, IsEmpty()); } TEST_F(ElementAreaTest, ElementNotFound) { SetElement("#not_found"); - EXPECT_TRUE(element_area_.IsEmpty()); - EXPECT_THAT(reported_area_, IsEmpty()); + EXPECT_THAT(reported_area_, ElementsAre(EmptyRectF())); std::vector<RectF> rectangles; - element_area_.GetArea(&rectangles); - EXPECT_THAT(rectangles, IsEmpty()); + element_area_.GetRectangles(&rectangles); + EXPECT_THAT(rectangles, ElementsAre(EmptyRectF())); } TEST_F(ElementAreaTest, OneRectangle) { @@ -98,9 +118,8 @@ .WillOnce(RunOnceCallback<1>(true, RectF(0.25f, 0.25f, 0.75f, 0.75f))); SetElement("#found"); - EXPECT_FALSE(element_area_.IsEmpty()); std::vector<RectF> rectangles; - element_area_.GetArea(&rectangles); + element_area_.GetRectangles(&rectangles); EXPECT_THAT(rectangles, ElementsAre(MatchingRectF(0.25f, 0.25f, 0.75f, 0.75f))); } @@ -111,7 +130,6 @@ .WillOnce(RunOnceCallback<1>(true, RectF(0.25f, 0.25f, 0.75f, 0.75f))); SetElement("#found"); - EXPECT_FALSE(element_area_.IsEmpty()); EXPECT_THAT(reported_area_, ElementsAre(MatchingRectF(0.25f, 0.25f, 0.75f, 0.75f))); } @@ -129,9 +147,8 @@ area_proto.add_rectangles()->add_elements()->add_selectors("#bottom_right"); element_area_.SetFromProto(area_proto); - EXPECT_FALSE(element_area_.IsEmpty()); std::vector<RectF> rectangles; - element_area_.GetArea(&rectangles); + element_area_.GetRectangles(&rectangles); EXPECT_THAT(rectangles, ElementsAre(MatchingRectF(0.0f, 0.0f, 0.25f, 0.25f), MatchingRectF(0.25f, 0.25f, 1.0f, 1.0f))); } @@ -150,9 +167,8 @@ rectangle_proto->add_elements()->add_selectors("#element2"); element_area_.SetFromProto(area_proto); - EXPECT_FALSE(element_area_.IsEmpty()); std::vector<RectF> rectangles; - element_area_.GetArea(&rectangles); + element_area_.GetRectangles(&rectangles); EXPECT_THAT(rectangles, ElementsAre(MatchingRectF(0.1f, 0.2f, 0.6f, 0.5f))); } @@ -173,12 +189,10 @@ rectangle_proto->add_elements()->add_selectors("#element2"); element_area_.SetFromProto(area_proto); - EXPECT_TRUE(element_area_.HasElements()); - EXPECT_FALSE(element_area_.IsEmpty()); - EXPECT_THAT(reported_area_, IsEmpty()); + EXPECT_THAT(reported_area_, ElementsAre(EmptyRectF())); std::vector<RectF> rectangles; - element_area_.GetArea(&rectangles); + element_area_.GetRectangles(&rectangles); EXPECT_THAT(rectangles, ElementsAre(MatchingRectF(0.1f, 0.3f, 0.2f, 0.4f))); } @@ -205,7 +219,7 @@ element_area_.SetFromProto(area_proto); std::vector<RectF> rectangles; - element_area_.GetArea(&rectangles); + element_area_.GetRectangles(&rectangles); EXPECT_THAT(rectangles, ElementsAre(MatchingRectF(0.0f, 0.0f, 1.0f, 1.0f))); } @@ -224,7 +238,7 @@ element_area_.SetFromProto(area_proto); std::vector<RectF> rectangles; - element_area_.GetArea(&rectangles); + element_area_.GetRectangles(&rectangles); EXPECT_THAT(rectangles, ElementsAre(MatchingRectF(0.1f, 0.1f, 0.2f, 0.2f))); EXPECT_THAT(reported_area_, @@ -247,7 +261,7 @@ element_area_.SetFromProto(area_proto); std::vector<RectF> rectangles; - element_area_.GetArea(&rectangles); + element_area_.GetRectangles(&rectangles); EXPECT_THAT(rectangles, ElementsAre(MatchingRectF(0.0f, 0.3f, 1.0f, 0.8f))); } @@ -267,7 +281,7 @@ // Updated area is available std::vector<RectF> rectangles; - element_area_.GetArea(&rectangles); + element_area_.GetRectangles(&rectangles); EXPECT_THAT(rectangles, ElementsAre(MatchingRectF(0.0f, 0.5f, 1.0f, 0.75f))); // Updated area is reported @@ -292,7 +306,7 @@ // Updated area is available std::vector<RectF> rectangles; - element_area_.GetArea(&rectangles); + element_area_.GetRectangles(&rectangles); EXPECT_THAT(rectangles, ElementsAre(MatchingRectF(0.0f, 0.5f, 1.0f, 0.75f))); // Updated area is reported
diff --git a/components/autofill_assistant/browser/service.proto b/components/autofill_assistant/browser/service.proto index d012e764..7237048 100644 --- a/components/autofill_assistant/browser/service.proto +++ b/components/autofill_assistant/browser/service.proto
@@ -138,6 +138,13 @@ // cancel button. Otherwise, buttons of this type work and look like a // NORMAL_ACTION. CLOSE_ACTION = 5; + + // Chip is a highlighted (blue) action chip. + // + // The presence of this chip inhibit the addition of an implicit close or + // cancel button. Otherwise, buttons of this type work and look like a + // HIGHLIGHTED_ACTION. + DONE_ACTION = 6; } enum ScriptStatusProto { @@ -752,8 +759,11 @@ message ShowDetailsProto { oneof data_to_show { DetailsProto details = 1; - string selected_address = 3; + // Shows full name and email address. + string contact_details = 3; bool credit_card = 4; + // Shows full name and address. + string shipping_address = 5; } // Flags indicating which parts of the details (if any) have changed.
diff --git a/components/autofill_assistant/browser/ui_controller.h b/components/autofill_assistant/browser/ui_controller.h index 13690d33..eadb49c 100644 --- a/components/autofill_assistant/browser/ui_controller.h +++ b/components/autofill_assistant/browser/ui_controller.h
@@ -71,9 +71,10 @@ // Updates the area of the visible viewport that is accessible when the // overlay state is OverlayState::PARTIAL. // - // |areas| is expressed in coordinates relative to the width or height of the - // visible viewport, as a number between 0 and 1. It can be empty. - virtual void OnTouchableAreaChanged(const std::vector<RectF>& areas); + // |rectangles| contains one element per configured rectangles, though these + // can correspond to empty rectangles. Coordinates are relative to the width + // or height of the visible viewport, as a number between 0 and 1. + virtual void OnTouchableAreaChanged(const std::vector<RectF>& rectangles); }; } // namespace autofill_assistant #endif // COMPONENTS_AUTOFILL_ASSISTANT_BROWSER_UI_CONTROLLER_H_
diff --git a/components/autofill_assistant/browser/ui_delegate.h b/components/autofill_assistant/browser/ui_delegate.h index cc3bc0c..e92610e 100644 --- a/components/autofill_assistant/browser/ui_delegate.h +++ b/components/autofill_assistant/browser/ui_delegate.h
@@ -94,11 +94,13 @@ // Adds the rectangles that correspond to the current touchable area to the // given vector. // - // |areas| is expressed in coordinates relative to the width or height of the - // visible viewport, as a number between 0 and 1. It can be empty. + // At the end of this call, |rectangles| contains one element per configured + // rectangles, though these can correspond to empty rectangles. Coordinates + // are relative to the width or height of the visible viewport, as a number + // between 0 and 1. // // Note that the vector is not cleared before rectangles are added. - virtual void GetTouchableArea(std::vector<RectF>* area) const = 0; + virtual void GetTouchableArea(std::vector<RectF>* rectangles) const = 0; // Reports a fatal error to Autofill Assistant, which should then stop. virtual void OnFatalError(const std::string& error_message,
diff --git a/components/browser_sync/profile_sync_service.cc b/components/browser_sync/profile_sync_service.cc index 787e2d2..36ba567 100644 --- a/components/browser_sync/profile_sync_service.cc +++ b/components/browser_sync/profile_sync_service.cc
@@ -112,10 +112,6 @@ factory_switches.backoff_override = EngineComponentsFactory::BACKOFF_SHORT_INITIAL_RETRY_OVERRIDE; } - if (cl->HasSwitch(switches::kSyncEnableGetUpdateAvoidance)) { - factory_switches.pre_commit_updates_policy = - EngineComponentsFactory::FORCE_ENABLE_PRE_COMMIT_UPDATE_AVOIDANCE; - } if (cl->HasSwitch(switches::kSyncShortNudgeDelayForTest)) { factory_switches.force_short_nudge_delay_for_test = true; } @@ -511,21 +507,14 @@ ->GetChannel()); params.saved_nigori_state = crypto_.TakeSavedNigoriState(); sync_prefs_.GetInvalidationVersions(¶ms.invalidation_versions); - params.short_poll_interval = sync_prefs_.GetShortPollInterval(); - if (params.short_poll_interval.is_zero()) { - params.short_poll_interval = - base::TimeDelta::FromSeconds(syncer::kDefaultShortPollIntervalSeconds); - } - params.long_poll_interval = sync_prefs_.GetLongPollInterval(); - if (params.long_poll_interval.is_zero()) { - params.long_poll_interval = - base::TimeDelta::FromSeconds(syncer::kDefaultLongPollIntervalSeconds); + params.poll_interval = sync_prefs_.GetPollInterval(); + if (params.poll_interval.is_zero()) { + params.poll_interval = + base::TimeDelta::FromSeconds(syncer::kDefaultPollIntervalSeconds); } engine_->Initialize(std::move(params)); - UpdateFirstSyncTimePref(); - ReportPreviousSessionMemoryWarningCount(); // TODO(treib): Consider kicking off an access token fetch here. Currently, @@ -945,11 +934,8 @@ UpdateLastSyncedTime(); if (!snapshot.poll_finish_time().is_null()) sync_prefs_.SetLastPollTime(snapshot.poll_finish_time()); - DCHECK(!snapshot.short_poll_interval().is_zero()); - sync_prefs_.SetShortPollInterval(snapshot.short_poll_interval()); - - DCHECK(!snapshot.long_poll_interval().is_zero()); - sync_prefs_.SetLongPollInterval(snapshot.long_poll_interval()); + DCHECK(!snapshot.poll_interval().is_zero()); + sync_prefs_.SetPollInterval(snapshot.poll_interval()); syncer::UserShare* user_share = GetUserShare(); if (user_share) { @@ -961,15 +947,6 @@ NotifySyncCycleCompleted(); } -void ProfileSyncService::OnExperimentsChanged( - const syncer::Experiments& experiments) { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - if (current_experiments_.Matches(experiments)) - return; - - current_experiments_ = experiments; -} - void ProfileSyncService::OnConnectionStatusChange( syncer::ConnectionStatus status) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); @@ -994,9 +971,6 @@ DCHECK_NE(last_actionable_error_.action, syncer::UNKNOWN_ACTION); switch (error.action) { case syncer::UPGRADE_CLIENT: - case syncer::CLEAR_USER_DATA_AND_RESYNC: - case syncer::ENABLE_SYNC_ON_ACCOUNT: - case syncer::STOP_AND_RESTART_SYNC: // TODO(lipalani) : if setup in progress we want to display these // actions in the popup. The current experience might not be optimal for // the user. We just dismiss the dialog. @@ -1871,15 +1845,6 @@ } } -void ProfileSyncService::UpdateFirstSyncTimePref() { - if (!IsLocalSyncEnabled() && !IsSignedIn()) { - sync_prefs_.ClearFirstSyncTime(); - } else if (sync_prefs_.GetFirstSyncTime().is_null()) { - // Set if not set before and it's syncing now. - sync_prefs_.SetFirstSyncTime(base::Time::Now()); - } -} - void ProfileSyncService::FlushDirectory() const { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); // engine_initialized_ implies engine_ isn't null and the manager exists.
diff --git a/components/browser_sync/profile_sync_service.h b/components/browser_sync/profile_sync_service.h index 6c01395b..94118ad 100644 --- a/components/browser_sync/profile_sync_service.h +++ b/components/browser_sync/profile_sync_service.h
@@ -21,7 +21,6 @@ #include "base/threading/thread.h" #include "base/time/time.h" #include "components/invalidation/public/identity_provider.h" -#include "components/sync/base/experiments.h" #include "components/sync/base/model_type.h" #include "components/sync/base/sync_prefs.h" #include "components/sync/base/unrecoverable_error_handler.h" @@ -254,7 +253,6 @@ const syncer::StatusCounters& counters) override; void OnConnectionStatusChange(syncer::ConnectionStatus status) override; void OnMigrationNeededForTypes(syncer::ModelTypeSet types) override; - void OnExperimentsChanged(const syncer::Experiments& experiments) override; void OnActionableError(const syncer::SyncProtocolError& error) override; // DataTypeManagerObserver implementation. @@ -440,9 +438,6 @@ // Whether sync has been authenticated with an account ID. bool IsSignedIn() const; - // Update first sync time stored in preferences - void UpdateFirstSyncTimePref(); - // Tell the sync server that this client has disabled sync. void RemoveClientFromServer() const; @@ -572,9 +567,6 @@ // or must delay loading for some reason). syncer::DataTypeStatusTable::TypeErrorMap data_type_error_map_; - // The set of currently enabled sync experiments. - syncer::Experiments current_experiments_; - // This providers tells the invalidations code which identity to register for. // The account that it registers for should be the same as the currently // syncing account, so we'll need to update this whenever the account changes.
diff --git a/components/browser_sync/profile_sync_service_unittest.cc b/components/browser_sync/profile_sync_service_unittest.cc index 33fab58..2d78f84 100644 --- a/components/browser_sync/profile_sync_service_unittest.cc +++ b/components/browser_sync/profile_sync_service_unittest.cc
@@ -224,7 +224,6 @@ void InitializeForNthSync() { // Set first sync time before initialize to simulate a complete sync setup. syncer::SyncPrefs sync_prefs(prefs()); - sync_prefs.SetFirstSyncTime(base::Time::Now()); sync_prefs.SetLastSyncedTime(base::Time::Now()); sync_prefs.SetFirstSetupComplete(); sync_prefs.SetDataTypesConfiguration(/*keep_everything_synced=*/true,
diff --git a/components/component_updater/component_updater_url_constants.cc b/components/component_updater/component_updater_url_constants.cc index cd1b932..42bf2c4 100644 --- a/components/component_updater/component_updater_url_constants.cc +++ b/components/component_updater/component_updater_url_constants.cc
@@ -14,12 +14,6 @@ // // The value of |kDefaultUrlSource| can be overridden with // --component-updater=url-source=someurl. -const char kUpdaterDefaultUrl[] = - "https://update.googleapis.com/service/update2"; - -const char kUpdaterFallbackUrl[] = - "http://update.googleapis.com/service/update2"; - const char kUpdaterJSONDefaultUrl[] = "https://update.googleapis.com/service/update2/json";
diff --git a/components/component_updater/configurator_impl.cc b/components/component_updater/configurator_impl.cc index 86f70034..81225e22 100644 --- a/components/component_updater/configurator_impl.cc +++ b/components/component_updater/configurator_impl.cc
@@ -34,13 +34,6 @@ const int kDelayOneMinute = 60; const int kDelayOneHour = kDelayOneMinute * 60; -// Enables using JSON as an update client protocol encoding instead of XML. -// -// The JSON implementation is available behind a flag: -// --enable-features=UpdateClientUseJSON -const base::Feature kFeatureUpdateClientUseJSON{ - "UpdateClientUseJSON", base::FEATURE_DISABLED_BY_DEFAULT}; - } // namespace ConfiguratorImpl::ConfiguratorImpl( @@ -83,12 +76,8 @@ if (url_source_override_.is_valid()) return {GURL(url_source_override_)}; - std::vector<GURL> urls = - base::FeatureList::IsEnabled(kFeatureUpdateClientUseJSON) - ? std::vector<GURL>{GURL(kUpdaterJSONDefaultUrl), - GURL(kUpdaterJSONFallbackUrl)} - : std::vector<GURL>{GURL(kUpdaterDefaultUrl), - GURL(kUpdaterFallbackUrl)}; + std::vector<GURL> urls{GURL(kUpdaterJSONDefaultUrl), + GURL(kUpdaterJSONFallbackUrl)}; if (require_encryption_) update_client::RemoveUnsecureUrls(&urls); @@ -148,9 +137,7 @@ std::unique_ptr<update_client::ProtocolHandlerFactory> ConfiguratorImpl::GetProtocolHandlerFactory() const { - if (base::FeatureList::IsEnabled(kFeatureUpdateClientUseJSON)) - return std::make_unique<update_client::ProtocolHandlerFactoryJSON>(); - return std::make_unique<update_client::ProtocolHandlerFactoryXml>(); + return std::make_unique<update_client::ProtocolHandlerFactoryJSON>(); } update_client::RecoveryCRXElevator ConfiguratorImpl::GetRecoveryCRXElevator()
diff --git a/components/gcm_driver/android/java/src/org/chromium/components/gcm_driver/GCMMessage.java b/components/gcm_driver/android/java/src/org/chromium/components/gcm_driver/GCMMessage.java index 5a606b1..0284205 100644 --- a/components/gcm_driver/android/java/src/org/chromium/components/gcm_driver/GCMMessage.java +++ b/components/gcm_driver/android/java/src/org/chromium/components/gcm_driver/GCMMessage.java
@@ -7,6 +7,7 @@ import android.annotation.TargetApi; import android.os.Build; import android.os.Bundle; +import android.support.annotation.IntDef; import android.support.annotation.Nullable; import org.json.JSONArray; @@ -16,6 +17,8 @@ import org.chromium.base.Log; import org.chromium.base.VisibleForTesting; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.List; @@ -38,6 +41,7 @@ private static final String KEY_DATA = "data"; private static final String KEY_RAW_DATA = "rawData"; private static final String KEY_SENDER_ID = "senderId"; + private static final String KEY_ORIGINAL_PRIORITY = "originalPriority"; private final String mSenderId; private final String mAppId; @@ -48,6 +52,24 @@ private final byte[] mRawData; /** + * A list of possible priority values the GCMMessage can have. + */ + @IntDef({Priority.NONE, Priority.NORMAL, Priority.HIGH}) + @Retention(RetentionPolicy.SOURCE) + public @interface Priority { + int NONE = 0; + int NORMAL = 1; + int HIGH = 2; + int NUM_ENTRIES = 3; + } + + /** + * The priority at which this GCMMessage was originally sent. + */ + @Nullable + private final String mOriginalPriority; + + /** * Array that contains pairs of entries in the format of {key, value}. */ private final String[] mDataKeysAndValuesArray; @@ -61,6 +83,7 @@ String bundleRawData = "rawData"; String bundleSenderId = "from"; String bundleSubtype = "subtype"; + String bundleOriginalPriority = "google.original_priority"; if (!extras.containsKey(bundleSubtype)) { throw new IllegalArgumentException("Received push message with no subtype"); @@ -71,12 +94,13 @@ mCollapseKey = extras.getString(bundleCollapseKey); // May be null. mRawData = extras.getByteArray(bundleRawData); // May be null. + mOriginalPriority = extras.getString(bundleOriginalPriority); // May be null. List<String> dataKeysAndValues = new ArrayList<String>(); for (String key : extras.keySet()) { if (key.equals(bundleSubtype) || key.equals(bundleSenderId) || key.equals(bundleCollapseKey) || key.equals(bundleRawData) - || key.startsWith(bundleGcmplex)) { + || key.equals(bundleOriginalPriority) || key.startsWith(bundleGcmplex)) { continue; } @@ -131,13 +155,14 @@ private static <T> boolean validate(T in, Reader<T> reader) { return reader.hasKey(in, KEY_APP_ID) && reader.hasKey(in, KEY_COLLAPSE_KEY) && reader.hasKey(in, KEY_DATA) && reader.hasKey(in, KEY_RAW_DATA) - && reader.hasKey(in, KEY_SENDER_ID); + && reader.hasKey(in, KEY_SENDER_ID) && reader.hasKey(in, KEY_ORIGINAL_PRIORITY); } private <T> GCMMessage(T source, Reader<T> reader) { mSenderId = reader.readString(source, KEY_SENDER_ID); mAppId = reader.readString(source, KEY_APP_ID); mCollapseKey = reader.readString(source, KEY_COLLAPSE_KEY); + mOriginalPriority = reader.readString(source, KEY_ORIGINAL_PRIORITY); // The rawData field needs to distinguish between {not set, set but empty, set with data}. String rawDataString = reader.readString(source, KEY_RAW_DATA); if (rawDataString != null) { @@ -174,6 +199,17 @@ return mRawData; } + public @Priority int getOriginalPriority() { + switch (mOriginalPriority) { + case "normal": + return Priority.NORMAL; + case "high": + return Priority.HIGH; + default: + return Priority.NONE; + } + } + /** * Callers are expected to not modify values in the returned byte array. */ @@ -227,6 +263,7 @@ writer.writeString(out, KEY_SENDER_ID, mSenderId); writer.writeString(out, KEY_APP_ID, mAppId); writer.writeString(out, KEY_COLLAPSE_KEY, mCollapseKey); + writer.writeString(out, KEY_ORIGINAL_PRIORITY, mOriginalPriority); // The rawData field needs to distinguish between {not set, set but empty, set with data}. if (mRawData != null) {
diff --git a/components/gcm_driver/android/junit/src/org/chromium/components/gcm_driver/GCMMessageTest.java b/components/gcm_driver/android/junit/src/org/chromium/components/gcm_driver/GCMMessageTest.java index 8159b3f3..e582983 100644 --- a/components/gcm_driver/android/junit/src/org/chromium/components/gcm_driver/GCMMessageTest.java +++ b/components/gcm_driver/android/junit/src/org/chromium/components/gcm_driver/GCMMessageTest.java
@@ -52,10 +52,12 @@ assertArrayEquals(new String[] {}, message.getDataKeysAndValuesArray()); } - // Add the optional fields: collapse key, raw binary data and a custom property. + // Add the optional fields: collapse key, raw binary data, a custom property and an original + // priority. extras.putString("collapse_key", "MyCollapseKey"); extras.putByteArray("rawData", new byte[] {0x00, 0x15, 0x30, 0x45}); extras.putString("property", "value"); + extras.putString("google.original_priority", "normal"); { GCMMessage message = new GCMMessage("MySenderId", extras); @@ -65,6 +67,7 @@ assertEquals("MyCollapseKey", message.getCollapseKey()); assertArrayEquals( new String[] {"property", "value"}, message.getDataKeysAndValuesArray()); + assertEquals(GCMMessage.Priority.NORMAL, message.getOriginalPriority()); } } @@ -122,6 +125,7 @@ // Add the optional fields: collapse key, raw binary data and a custom property. extras.putString("collapse_key", "MyCollapseKey"); extras.putString("property", "value"); + extras.putString("google.original_priority", "normal"); { GCMMessage message = new GCMMessage("MySenderId", extras); @@ -199,6 +203,7 @@ // Add the optional fields: collapse key, raw binary data and a custom property. extras.putString("collapse_key", "MyCollapseKey"); extras.putString("property", "value"); + extras.putString("google.original_priority", "normal"); { GCMMessage message = new GCMMessage("MySenderId", extras);
diff --git a/components/management_strings.grdp b/components/management_strings.grdp index 4d41e18..970a4ac 100644 --- a/components/management_strings.grdp +++ b/components/management_strings.grdp
@@ -83,6 +83,9 @@ <message name="IDS_MANAGEMENT_REPORT_DEVICE_NETWORK_INTERFACES" desc="Message stating that administrators see device network interfaces."> Network addresses </message> + <message name="IDS_MANAGEMENT_REPORT_PRINTING" desc="Message stating that administrators can see names of printed files."> + Names of files that you print + </message> </if> <message name="IDS_MANAGEMENT_EXTENSION_REPORTING" desc="Title of the force installed extensions section of the page">
diff --git a/components/omnibox/browser/autocomplete_match.cc b/components/omnibox/browser/autocomplete_match.cc index 474d09d..f2b1f56 100644 --- a/components/omnibox/browser/autocomplete_match.cc +++ b/components/omnibox/browser/autocomplete_match.cc
@@ -72,6 +72,22 @@ } // namespace +// static +const char* const AutocompleteMatch::kDocumentTypeStrings[]{ + "none", "drive_docs", "drive_forms", "drive_sheets", "drive_slides", + "drive_image", "drive_pdf", "drive_video", "drive_other"}; + +static_assert( + base::size(AutocompleteMatch::kDocumentTypeStrings) == + static_cast<int>(AutocompleteMatch::DocumentType::DOCUMENT_TYPE_SIZE), + "Sizes of AutocompleteMatch::kDocumentTypeStrings and " + "AutocompleteMatch::DocumentType don't match."); + +// static +const char* AutocompleteMatch::DocumentTypeString(DocumentType type) { + return kDocumentTypeStrings[static_cast<int>(type)]; +} + // AutocompleteMatch ---------------------------------------------------------- // static
diff --git a/components/omnibox/browser/autocomplete_match.h b/components/omnibox/browser/autocomplete_match.h index 6bd42ffb..587bd2d 100644 --- a/components/omnibox/browser/autocomplete_match.h +++ b/components/omnibox/browser/autocomplete_match.h
@@ -118,8 +118,9 @@ static const base::char16 kInvalidChars[]; // Document subtype, for AutocompleteMatchType::DOCUMENT. + // Update kDocumentTypeStrings when updating DocumentType. enum class DocumentType { - NONE, + NONE = 0, DRIVE_DOCS, DRIVE_FORMS, DRIVE_SHEETS, @@ -127,9 +128,15 @@ DRIVE_IMAGE, DRIVE_PDF, DRIVE_VIDEO, - DRIVE_OTHER + DRIVE_OTHER, + DOCUMENT_TYPE_SIZE }; + static const char* const kDocumentTypeStrings[]; + + // Return a string version of the core type values. + static const char* DocumentTypeString(DocumentType type); + AutocompleteMatch(); AutocompleteMatch(AutocompleteProvider* provider, int relevance,
diff --git a/components/password_manager/core/browser/form_parsing/fuzzer/BUILD.gn b/components/password_manager/core/browser/form_parsing/fuzzer/BUILD.gn index 3b5c797..bb501359 100644 --- a/components/password_manager/core/browser/form_parsing/fuzzer/BUILD.gn +++ b/components/password_manager/core/browser/form_parsing/fuzzer/BUILD.gn
@@ -15,6 +15,7 @@ deps = [ "//base", + "//components/autofill/core/browser", "//components/autofill/core/common", "//components/password_manager/core/browser/form_parsing", "//url",
diff --git a/components/password_manager/core/browser/form_parsing/fuzzer/form_data_producer.cc b/components/password_manager/core/browser/form_parsing/fuzzer/form_data_producer.cc index e00006c..5384f5a 100644 --- a/components/password_manager/core/browser/form_parsing/fuzzer/form_data_producer.cc +++ b/components/password_manager/core/browser/form_parsing/fuzzer/form_data_producer.cc
@@ -7,6 +7,7 @@ #include "base/strings/string_number_conversions.h" #include "base/strings/utf_string_conversions.h" #include "build/build_config.h" +#include "components/autofill/core/browser/field_types.h" #include "components/autofill/core/common/form_field_data.h" #include "components/password_manager/core/browser/form_parsing/fuzzer/data_accessor.h" #include "url/gurl.h" @@ -14,11 +15,18 @@ using autofill::FormData; using autofill::FormFieldData; +using autofill::ServerFieldType; namespace password_manager { namespace { +constexpr ServerFieldType kPasswordRelatedServerTypes[] = { + autofill::USERNAME, autofill::USERNAME_AND_EMAIL_ADDRESS, + autofill::PASSWORD, autofill::ACCOUNT_CREATION_PASSWORD, + autofill::NEW_PASSWORD, autofill::CONFIRMATION_PASSWORD, + autofill::NOT_PASSWORD}; + struct FormFieldDataParams { size_t form_control_type_length; size_t autocomplete_attribute_length; @@ -31,9 +39,30 @@ bool same_value_field; }; +// With probability 0.5 returns true and generates |prediction|, with +// probability 0.5 returns false. Uses |accessor| as a source of randomness. +bool MaybeGenerateFieldPrediction(DataAccessor* accessor, + PasswordFieldPrediction* prediction) { + bool generate_prediction = accessor->ConsumeBit(); + if (!generate_prediction) + return false; + prediction->may_use_prefilled_placeholder = accessor->ConsumeBit(); + const size_t prediction_idx = accessor->ConsumeNumber(3); + if (prediction_idx < base::size(kPasswordRelatedServerTypes)) { + prediction->type = kPasswordRelatedServerTypes[prediction_idx]; + } else { + // Set random type, probably even invalid. FormParser should gracefully + // treat any type. + prediction->type = static_cast<ServerFieldType>(accessor->ConsumeNumber(8)); + } + return true; +} + } // namespace -FormData GenerateWithDataAccessor(DataAccessor* accessor) { +autofill::FormData GenerateWithDataAccessor( + password_manager::DataAccessor* accessor, + FormPredictions* predictions) { FormData result; // First determine the main non-string attributes not specific to particular @@ -99,6 +128,15 @@ result.fields[i].name_attribute = result.fields[i].name; result.fields[i].id_attribute = accessor->ConsumeString16(field_params[i].id_length); + // Check both positive and negavites numbers for renderer ids. + result.fields[i].unique_renderer_id = + static_cast<uint32_t>(accessor->ConsumeNumber(6) - 32); + if (predictions) { + PasswordFieldPrediction field_prediction; + if (MaybeGenerateFieldPrediction(accessor, &field_prediction)) + (*predictions)[result.fields[i].unique_renderer_id] = field_prediction; + } + #if defined(OS_IOS) result.fields[i].unique_id = result.fields[i].id_attribute + base::UTF8ToUTF16("-") + @@ -113,6 +151,20 @@ } } + if (predictions) { + // Generate predictions for non-existing fields. + size_t n_predictions = accessor->ConsumeNumber(4); + PasswordFieldPrediction field_prediction; + for (size_t i = 0; i < n_predictions; ++i) { + if (MaybeGenerateFieldPrediction(accessor, &field_prediction)) { + // Check both positive and negavites numbers for renderer ids. + uint32_t unique_renderer_id = + static_cast<uint32_t>(accessor->ConsumeNumber(6) - 32); + (*predictions)[unique_renderer_id] = field_prediction; + } + } + } + return result; }
diff --git a/components/password_manager/core/browser/form_parsing/fuzzer/form_data_producer.h b/components/password_manager/core/browser/form_parsing/fuzzer/form_data_producer.h index 3ea1b79..1078c93 100644 --- a/components/password_manager/core/browser/form_parsing/fuzzer/form_data_producer.h +++ b/components/password_manager/core/browser/form_parsing/fuzzer/form_data_producer.h
@@ -6,14 +6,16 @@ #define COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_FORM_PARSING_FUZZER_FORM_DATA_PRODUCER_H_ #include "components/autofill/core/common/form_data.h" +#include "components/password_manager/core/browser/form_parsing/password_field_prediction.h" namespace password_manager { class DataAccessor; -// Generates a |FormData| object based on values obtained via |accessor|. See -// https://goo.gl/29t6VH for a detailed design. -autofill::FormData GenerateWithDataAccessor(DataAccessor* accessor); +// Generates a |FormData| and |predictions| object based on values obtained via +// |accessor|. See https://goo.gl/29t6VH for a detailed design. +autofill::FormData GenerateWithDataAccessor(DataAccessor* accessor, + FormPredictions* predictions); } // namespace password_manager
diff --git a/components/password_manager/core/browser/form_parsing/fuzzer/form_parser_fuzzer.cc b/components/password_manager/core/browser/form_parsing/fuzzer/form_parser_fuzzer.cc index 2f581e3..51a6108 100644 --- a/components/password_manager/core/browser/form_parsing/fuzzer/form_parser_fuzzer.cc +++ b/components/password_manager/core/browser/form_parsing/fuzzer/form_parser_fuzzer.cc
@@ -29,7 +29,7 @@ DataAccessor accessor(data, size); FormParsingMode mode = accessor.ConsumeBit() ? FormParsingMode::FILLING : FormParsingMode::SAVING; - autofill::FormData form_data = GenerateWithDataAccessor(&accessor); + autofill::FormData form_data = GenerateWithDataAccessor(&accessor, nullptr); std::unique_ptr<autofill::PasswordForm> result = ParseFormData(form_data, mode); if (result) {
diff --git a/components/password_manager/core/browser/form_parsing/fuzzer/form_parser_generic_fuzzer.cc b/components/password_manager/core/browser/form_parsing/fuzzer/form_parser_generic_fuzzer.cc index 81dc4fb..6bafd1c 100644 --- a/components/password_manager/core/browser/form_parsing/fuzzer/form_parser_generic_fuzzer.cc +++ b/components/password_manager/core/browser/form_parsing/fuzzer/form_parser_generic_fuzzer.cc
@@ -30,9 +30,16 @@ FormDataParser::Mode mode = accessor.ConsumeBit() ? FormDataParser::Mode::kFilling : FormDataParser::Mode::kSaving; - autofill::FormData form_data = GenerateWithDataAccessor(&accessor); + + bool use_predictions = accessor.ConsumeBit(); + FormPredictions predictions; + autofill::FormData form_data = GenerateWithDataAccessor( + &accessor, use_predictions ? &predictions : nullptr); FormDataParser parser; + if (use_predictions) + parser.set_predictions(predictions); + std::unique_ptr<autofill::PasswordForm> result = parser.Parse(form_data, mode); if (result) {
diff --git a/components/policy/proto/chrome_device_policy.proto b/components/policy/proto/chrome_device_policy.proto index 18741af..f673ab22 100644 --- a/components/policy/proto/chrome_device_policy.proto +++ b/components/policy/proto/chrome_device_policy.proto
@@ -1153,6 +1153,12 @@ optional bool device_wilco_dtc_allowed = 1; } +// Setting that specifies wilco diagnostics and telemetry controller +// configuration for this device. +message DeviceWilcoDtcConfigurationProto { + optional string device_wilco_dtc_configuration = 1; +} + message ChromeDeviceSettingsProto { reserved 61; optional DevicePolicyRefreshRateProto device_policy_refresh_rate = 1; @@ -1255,4 +1261,5 @@ optional PluginVmLicenseKeyProto plugin_vm_license_key = 78; optional DeviceRebootOnUserSignoutProto device_reboot_on_user_signout = 79; optional DeviceWilcoDtcAllowedProto device_wilco_dtc_allowed = 80; + optional DeviceWilcoDtcConfigurationProto device_wilco_dtc_configuration = 81; }
diff --git a/components/policy/resources/policy_templates.json b/components/policy/resources/policy_templates.json index 67701d9..929c45d2 100644 --- a/components/policy/resources/policy_templates.json +++ b/components/policy/resources/policy_templates.json
@@ -978,6 +978,7 @@ 'desc': '''Controls wilco diagnostics and telemetry controller settings.''', 'policies': [ 'DeviceWilcoDtcAllowed', + 'DeviceWilcoDtcConfiguration', ], }, { @@ -15008,6 +15009,39 @@ See https://www.chromestatus.com/feature/5989473649164288 .''', }, + { + 'name': 'DeviceWilcoDtcConfiguration', + 'type': 'external', + 'schema': { + 'type': 'object', + 'properties': { + 'url': { 'type': 'string' }, + 'hash': { 'type': 'string' } + }, + }, + 'supported_on': ['chrome_os:75-'], + 'device_only': True, + 'features': { + 'dynamic_refresh': True, + 'per_profile': False, + }, + 'example_value': { + "url": "https://example.com/wilcodtcconfig", + "hash": "deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef" + }, + 'max_size': 1000000, + 'id': 535, + 'caption': '''Wilco DTC configuration''', + 'tags': [], + 'desc': '''Provides a wilco DTC (diagnostics and telemetry controller) configuration. + + This policy allows to provide wilco DTC configuration that is allowed to be applied if wilco DTC is available on the given device and allowed by policy. The size of the configuration must not exceed 1MB (1000000 bytes) and must be encoded in JSON. The wilco DTC is responsible for handling it. The cryptographic hash is used to verify the integrity of the download. + + The configuration is downloaded and cached. It will be re-downloaded whenever the URL or the hash changes. + + If you set this policy, users cannot change or override it.''', + }, + ], 'messages': { @@ -15173,5 +15207,5 @@ }, 'placeholders': [], 'deleted_policy_ids': [412], - 'highest_id_currently_used': 534 + 'highest_id_currently_used': 535 }
diff --git a/components/signin/core/browser/BUILD.gn b/components/signin/core/browser/BUILD.gn index e5dedd5..beff475f 100644 --- a/components/signin/core/browser/BUILD.gn +++ b/components/signin/core/browser/BUILD.gn
@@ -82,6 +82,8 @@ "oauth2_token_service_delegate_android.h", "profile_oauth2_token_service.cc", "profile_oauth2_token_service.h", + "profile_oauth2_token_service_delegate_chromeos.cc", + "profile_oauth2_token_service_delegate_chromeos.h", "signin_client.cc", "signin_client.h", "signin_manager.cc", @@ -114,6 +116,10 @@ if (is_android) { deps += [ "android:jni_headers" ] } + + if (is_chromeos) { + deps += [ "//chromeos" ] + } } static_library("browser") { @@ -259,6 +265,7 @@ "identity_utils_unittest.cc", "mice_account_reconcilor_delegate_unittest.cc", "mutable_profile_oauth2_token_service_delegate_unittest.cc", + "profile_oauth2_token_service_delegate_chromeos_unittest.cc", "signin_error_controller_unittest.cc", "signin_header_helper_unittest.cc", "signin_investigator_unittest.cc", @@ -297,6 +304,8 @@ "signin_manager_unittest.cc", "signin_status_metrics_provider_unittest.cc", ] + + deps += [ "//chromeos" ] } if (!enable_dice_support) {
diff --git a/components/signin/core/browser/DEPS b/components/signin/core/browser/DEPS index 51f3013..5ea01a2 100644 --- a/components/signin/core/browser/DEPS +++ b/components/signin/core/browser/DEPS
@@ -1,4 +1,5 @@ include_rules = [ + "+chromeos/account_manager", "+components/account_id", "+components/data_use_measurement/core", "+components/image_fetcher/core",
diff --git a/chrome/browser/chromeos/oauth2_token_service_delegate.cc b/components/signin/core/browser/profile_oauth2_token_service_delegate_chromeos.cc similarity index 81% rename from chrome/browser/chromeos/oauth2_token_service_delegate.cc rename to components/signin/core/browser/profile_oauth2_token_service_delegate_chromeos.cc index e538d61..a4315a7 100644 --- a/chrome/browser/chromeos/oauth2_token_service_delegate.cc +++ b/components/signin/core/browser/profile_oauth2_token_service_delegate_chromeos.cc
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "chrome/browser/chromeos/oauth2_token_service_delegate.h" +#include "components/signin/core/browser/profile_oauth2_token_service_delegate_chromeos.h" #include <string> #include <utility> @@ -17,7 +17,7 @@ #include "net/base/backoff_entry.h" #include "services/network/public/cpp/shared_url_loader_factory.h" -namespace chromeos { +namespace signin { namespace { @@ -44,12 +44,12 @@ // |account_keys| is the set of accounts that need to be translated. // |account_tracker_service| is an unowned pointer. std::vector<std::string> GetOAuthAccountIdsFromAccountKeys( - const std::set<AccountManager::AccountKey>& account_keys, + const std::set<chromeos::AccountManager::AccountKey>& account_keys, const AccountTrackerService* const account_tracker_service) { std::vector<std::string> accounts; for (auto& account_key : account_keys) { if (account_key.account_type != - account_manager::AccountType::ACCOUNT_TYPE_GAIA) { + chromeos::account_manager::AccountType::ACCOUNT_TYPE_GAIA) { continue; } @@ -66,10 +66,11 @@ } // namespace -ChromeOSOAuth2TokenServiceDelegate::ChromeOSOAuth2TokenServiceDelegate( - AccountTrackerService* account_tracker_service, - network::NetworkConnectionTracker* network_connection_tracker, - chromeos::AccountManager* account_manager) +ProfileOAuth2TokenServiceDelegateChromeOS:: + ProfileOAuth2TokenServiceDelegateChromeOS( + AccountTrackerService* account_tracker_service, + network::NetworkConnectionTracker* network_connection_tracker, + chromeos::AccountManager* account_manager) : account_tracker_service_(account_tracker_service), network_connection_tracker_(network_connection_tracker), account_manager_(account_manager), @@ -79,13 +80,14 @@ network_connection_tracker_->AddNetworkConnectionObserver(this); } -ChromeOSOAuth2TokenServiceDelegate::~ChromeOSOAuth2TokenServiceDelegate() { +ProfileOAuth2TokenServiceDelegateChromeOS:: + ~ProfileOAuth2TokenServiceDelegateChromeOS() { account_manager_->RemoveObserver(this); network_connection_tracker_->RemoveNetworkConnectionObserver(this); } OAuth2AccessTokenFetcher* -ChromeOSOAuth2TokenServiceDelegate::CreateAccessTokenFetcher( +ProfileOAuth2TokenServiceDelegateChromeOS::CreateAccessTokenFetcher( const std::string& account_id, scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory, OAuth2AccessTokenConsumer* consumer) { @@ -116,9 +118,9 @@ // |OAuth2TokenService| will manage the lifetime of the released pointer. return account_manager_ ->CreateAccessTokenFetcher( - AccountManager::AccountKey{ + chromeos::AccountManager::AccountKey{ account_tracker_service_->GetAccountInfo(account_id).gaia, - account_manager::AccountType:: + chromeos::account_manager::AccountType:: ACCOUNT_TYPE_GAIA} /* account_key */, url_loader_factory, consumer) .release(); @@ -128,7 +130,7 @@ // |GetAccounts|. See crbug.com/919793 for details. At the time of writing, // both |GetAccounts| and |RefreshTokenIsAvailable| use // |GetOAuthAccountIdsFromAccountKeys|. -bool ChromeOSOAuth2TokenServiceDelegate::RefreshTokenIsAvailable( +bool ProfileOAuth2TokenServiceDelegateChromeOS::RefreshTokenIsAvailable( const std::string& account_id) const { if (load_credentials_state() != LOAD_CREDENTIALS_FINISHED_WITH_SUCCESS) { return false; @@ -141,7 +143,7 @@ account_id); } -void ChromeOSOAuth2TokenServiceDelegate::UpdateAuthError( +void ProfileOAuth2TokenServiceDelegateChromeOS::UpdateAuthError( const std::string& account_id, const GoogleServiceAuthError& error) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); @@ -168,7 +170,7 @@ } } -GoogleServiceAuthError ChromeOSOAuth2TokenServiceDelegate::GetAuthError( +GoogleServiceAuthError ProfileOAuth2TokenServiceDelegateChromeOS::GetAuthError( const std::string& account_id) const { auto it = errors_.find(account_id); if (it != errors_.end()) { @@ -182,7 +184,8 @@ // |RefreshTokenIsAvailable|. See crbug.com/919793 for details. At the time of // writing, both |GetAccounts| and |RefreshTokenIsAvailable| use // |GetOAuthAccountIdsFromAccountKeys|. -std::vector<std::string> ChromeOSOAuth2TokenServiceDelegate::GetAccounts() { +std::vector<std::string> +ProfileOAuth2TokenServiceDelegateChromeOS::GetAccounts() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); // |GetAccounts| intentionally does not care about the state of @@ -193,7 +196,7 @@ account_tracker_service_); } -void ChromeOSOAuth2TokenServiceDelegate::LoadCredentials( +void ProfileOAuth2TokenServiceDelegateChromeOS::LoadCredentials( const std::string& primary_account_id) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); @@ -206,11 +209,11 @@ DCHECK(account_manager_); account_manager_->AddObserver(this); account_manager_->GetAccounts( - base::BindOnce(&ChromeOSOAuth2TokenServiceDelegate::OnGetAccounts, + base::BindOnce(&ProfileOAuth2TokenServiceDelegateChromeOS::OnGetAccounts, weak_factory_.GetWeakPtr())); } -void ChromeOSOAuth2TokenServiceDelegate::UpdateCredentials( +void ProfileOAuth2TokenServiceDelegateChromeOS::UpdateCredentials( const std::string& account_id, const std::string& refresh_token) { // This API could have been called for upserting the Device/Primary @@ -228,8 +231,8 @@ // In both of the aforementioned cases, we can be sure that when this API is // called, |account_id| is guaranteed to be present in // |AccountTrackerService|. This guarantee is important because - // |ChromeOSOAuth2TokenServiceDelegate| relies on |AccountTrackerService| to - // convert |account_id| to an email id. + // |ProfileOAuth2TokenServiceDelegateChromeOS| relies on + // |AccountTrackerService| to convert |account_id| to an email id. // Account update: // If an account is being updated, it must be present in @@ -251,22 +254,22 @@ << "account_id must be present in AccountTrackerService before " "UpdateCredentials is called"; - // Will result in AccountManager calling - // |ChromeOSOAuth2TokenServiceDelegate::OnTokenUpserted|. + // Will result in chromeos::AccountManager calling + // |ProfileOAuth2TokenServiceDelegateChromeOS::OnTokenUpserted|. account_manager_->UpsertAccount( - AccountManager::AccountKey{ - account_info.gaia, - account_manager::AccountType::ACCOUNT_TYPE_GAIA} /* account_key */, + chromeos::AccountManager::AccountKey{ + account_info.gaia, chromeos::account_manager::AccountType:: + ACCOUNT_TYPE_GAIA} /* account_key */, account_info.email /* email */, refresh_token); } scoped_refptr<network::SharedURLLoaderFactory> -ChromeOSOAuth2TokenServiceDelegate::GetURLLoaderFactory() const { +ProfileOAuth2TokenServiceDelegateChromeOS::GetURLLoaderFactory() const { return account_manager_->GetUrlLoaderFactory(); } -void ChromeOSOAuth2TokenServiceDelegate::OnGetAccounts( - const std::vector<AccountManager::Account>& accounts) { +void ProfileOAuth2TokenServiceDelegateChromeOS::OnGetAccounts( + const std::vector<chromeos::AccountManager::Account>& accounts) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); // This callback should only be triggered during |LoadCredentials|, which @@ -288,13 +291,13 @@ FireRefreshTokensLoaded(); } -void ChromeOSOAuth2TokenServiceDelegate::OnTokenUpserted( - const AccountManager::Account& account) { +void ProfileOAuth2TokenServiceDelegateChromeOS::OnTokenUpserted( + const chromeos::AccountManager::Account& account) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); account_keys_.insert(account.key); if (account.key.account_type != - account_manager::AccountType::ACCOUNT_TYPE_GAIA) { + chromeos::account_manager::AccountType::ACCOUNT_TYPE_GAIA) { return; } @@ -346,8 +349,8 @@ FireAuthErrorChanged(account_id, error); } -void ChromeOSOAuth2TokenServiceDelegate::OnAccountRemoved( - const AccountManager::Account& account) { +void ProfileOAuth2TokenServiceDelegateChromeOS::OnAccountRemoved( + const chromeos::AccountManager::Account& account) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); DCHECK_EQ(LOAD_CREDENTIALS_FINISHED_WITH_SUCCESS, load_credentials_state()); @@ -358,7 +361,7 @@ account_keys_.erase(it); if (account.key.account_type != - account_manager::AccountType::ACCOUNT_TYPE_GAIA) { + chromeos::account_manager::AccountType::ACCOUNT_TYPE_GAIA) { return; } std::string account_id = @@ -374,25 +377,25 @@ FireRefreshTokenRevoked(account_id); } -void ChromeOSOAuth2TokenServiceDelegate::RevokeCredentials( +void ProfileOAuth2TokenServiceDelegateChromeOS::RevokeCredentials( const std::string& account_id) { // Signing out of Chrome is not possible on Chrome OS. NOTREACHED(); } -void ChromeOSOAuth2TokenServiceDelegate::RevokeAllCredentials() { +void ProfileOAuth2TokenServiceDelegateChromeOS::RevokeAllCredentials() { // Signing out of Chrome is not possible on Chrome OS. NOTREACHED(); } -const net::BackoffEntry* ChromeOSOAuth2TokenServiceDelegate::BackoffEntry() - const { +const net::BackoffEntry* +ProfileOAuth2TokenServiceDelegateChromeOS::BackoffEntry() const { return &backoff_entry_; } -void ChromeOSOAuth2TokenServiceDelegate::OnConnectionChanged( +void ProfileOAuth2TokenServiceDelegateChromeOS::OnConnectionChanged( network::mojom::ConnectionType type) { backoff_entry_.Reset(); } -} // namespace chromeos +} // namespace signin
diff --git a/chrome/browser/chromeos/oauth2_token_service_delegate.h b/components/signin/core/browser/profile_oauth2_token_service_delegate_chromeos.h similarity index 68% rename from chrome/browser/chromeos/oauth2_token_service_delegate.h rename to components/signin/core/browser/profile_oauth2_token_service_delegate_chromeos.h index aabc6a2..b05c7d85 100644 --- a/chrome/browser/chromeos/oauth2_token_service_delegate.h +++ b/components/signin/core/browser/profile_oauth2_token_service_delegate_chromeos.h
@@ -2,8 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef CHROME_BROWSER_CHROMEOS_OAUTH2_TOKEN_SERVICE_DELEGATE_H_ -#define CHROME_BROWSER_CHROMEOS_OAUTH2_TOKEN_SERVICE_DELEGATE_H_ +#ifndef COMPONENTS_SIGNIN_CORE_BROWSER_PROFILE_OAUTH2_TOKEN_SERVICE_DELEGATE_CHROMEOS_H_ +#define COMPONENTS_SIGNIN_CORE_BROWSER_PROFILE_OAUTH2_TOKEN_SERVICE_DELEGATE_CHROMEOS_H_ #include <map> #include <memory> @@ -20,21 +20,21 @@ class AccountTrackerService; -namespace chromeos { +namespace signin { -class ChromeOSOAuth2TokenServiceDelegate +class ProfileOAuth2TokenServiceDelegateChromeOS : public OAuth2TokenServiceDelegate, - public AccountManager::Observer, + public chromeos::AccountManager::Observer, public network::NetworkConnectionTracker::NetworkConnectionObserver { public: // Accepts non-owning pointers to |AccountTrackerService|, - // |NetworkConnectorTracker|, and |AccountManager|. These objects must all - // outlive |this| delegate. - ChromeOSOAuth2TokenServiceDelegate( + // |NetworkConnectorTracker|, and |chromeos::AccountManager|. These objects + // must all outlive |this| delegate. + ProfileOAuth2TokenServiceDelegateChromeOS( AccountTrackerService* account_tracker_service, network::NetworkConnectionTracker* network_connection_tracker, - AccountManager* account_manager); - ~ChromeOSOAuth2TokenServiceDelegate() override; + chromeos::AccountManager* account_manager); + ~ProfileOAuth2TokenServiceDelegateChromeOS() override; // OAuth2TokenServiceDelegate overrides. OAuth2AccessTokenFetcher* CreateAccessTokenFetcher( @@ -56,9 +56,11 @@ void RevokeAllCredentials() override; const net::BackoffEntry* BackoffEntry() const override; - // |AccountManager::Observer| overrides. - void OnTokenUpserted(const AccountManager::Account& account) override; - void OnAccountRemoved(const AccountManager::Account& account) override; + // |chromeos::AccountManager::Observer| overrides. + void OnTokenUpserted( + const chromeos::AccountManager::Account& account) override; + void OnAccountRemoved( + const chromeos::AccountManager::Account& account) override; // |NetworkConnectionTracker::NetworkConnectionObserver| overrides. void OnConnectionChanged(network::mojom::ConnectionType type) override; @@ -75,8 +77,9 @@ GoogleServiceAuthError last_auth_error; }; - // Callback handler for |AccountManager::GetAccounts|. - void OnGetAccounts(const std::vector<AccountManager::Account>& accounts); + // Callback handler for |chromeos::AccountManager::GetAccounts|. + void OnGetAccounts( + const std::vector<chromeos::AccountManager::Account>& accounts); // A non-owning pointer. AccountTrackerService* const account_tracker_service_; @@ -84,12 +87,12 @@ // A non-owning pointer. network::NetworkConnectionTracker* const network_connection_tracker_; - // A non-owning pointer. |AccountManager| is available + // A non-owning pointer. |chromeos::AccountManager| is available // throughout the lifetime of a user session. - AccountManager* const account_manager_; + chromeos::AccountManager* const account_manager_; // A cache of AccountKeys. - std::set<AccountManager::AccountKey> account_keys_; + std::set<chromeos::AccountManager::AccountKey> account_keys_; // A map from account id to the last seen error for that account. std::map<std::string, AccountErrorStatus> errors_; @@ -99,11 +102,11 @@ GoogleServiceAuthError backoff_error_; SEQUENCE_CHECKER(sequence_checker_); - base::WeakPtrFactory<ChromeOSOAuth2TokenServiceDelegate> weak_factory_; + base::WeakPtrFactory<ProfileOAuth2TokenServiceDelegateChromeOS> weak_factory_; - DISALLOW_COPY_AND_ASSIGN(ChromeOSOAuth2TokenServiceDelegate); + DISALLOW_COPY_AND_ASSIGN(ProfileOAuth2TokenServiceDelegateChromeOS); }; -} // namespace chromeos +} // namespace signin -#endif // CHROME_BROWSER_CHROMEOS_OAUTH2_TOKEN_SERVICE_DELEGATE_H_ +#endif // COMPONENTS_SIGNIN_CORE_BROWSER_PROFILE_OAUTH2_TOKEN_SERVICE_DELEGATE_CHROMEOS_H_
diff --git a/chrome/browser/chromeos/oauth2_token_service_delegate_unittest.cc b/components/signin/core/browser/profile_oauth2_token_service_delegate_chromeos_unittest.cc similarity index 88% rename from chrome/browser/chromeos/oauth2_token_service_delegate_unittest.cc rename to components/signin/core/browser/profile_oauth2_token_service_delegate_chromeos_unittest.cc index 06eea16..cbcaf947 100644 --- a/chrome/browser/chromeos/oauth2_token_service_delegate_unittest.cc +++ b/components/signin/core/browser/profile_oauth2_token_service_delegate_chromeos_unittest.cc
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "chrome/browser/chromeos/oauth2_token_service_delegate.h" +#include "components/signin/core/browser/profile_oauth2_token_service_delegate_chromeos.h" #include <memory> #include <set> @@ -28,12 +28,12 @@ #include "services/network/test/test_network_connection_tracker.h" #include "testing/gtest/include/gtest/gtest.h" -namespace chromeos { +namespace signin { namespace { -using account_manager::AccountType::ACCOUNT_TYPE_GAIA; -using account_manager::AccountType::ACCOUNT_TYPE_ACTIVE_DIRECTORY; +using chromeos::account_manager::AccountType::ACCOUNT_TYPE_ACTIVE_DIRECTORY; +using chromeos::account_manager::AccountType::ACCOUNT_TYPE_GAIA; constexpr char kGaiaId[] = "gaia-id"; constexpr char kGaiaToken[] = "gaia-token"; @@ -158,7 +158,7 @@ gaia_account_key_ = {account_info_.gaia, ACCOUNT_TYPE_GAIA}; ad_account_key_ = {"object-guid", ACCOUNT_TYPE_ACTIVE_DIRECTORY}; - delegate_ = std::make_unique<ChromeOSOAuth2TokenServiceDelegate>( + delegate_ = std::make_unique<ProfileOAuth2TokenServiceDelegateChromeOS>( &account_tracker_service_, network::TestNetworkConnectionTracker::GetInstance(), &account_manager_); @@ -198,12 +198,12 @@ base::ScopedTempDir tmp_dir_; AccountInfo account_info_; - AccountManager::AccountKey gaia_account_key_; - AccountManager::AccountKey ad_account_key_; + chromeos::AccountManager::AccountKey gaia_account_key_; + chromeos::AccountManager::AccountKey ad_account_key_; AccountTrackerService account_tracker_service_; - AccountManager account_manager_; - std::unique_ptr<ChromeOSOAuth2TokenServiceDelegate> delegate_; - AccountManager::DelayNetworkCallRunner immediate_callback_runner_ = + chromeos::AccountManager account_manager_; + std::unique_ptr<ProfileOAuth2TokenServiceDelegateChromeOS> delegate_; + chromeos::AccountManager::DelayNetworkCallRunner immediate_callback_runner_ = base::BindRepeating( [](base::OnceClosure closure) -> void { std::move(closure).Run(); }); sync_preferences::TestingPrefServiceSyncable pref_service_; @@ -241,7 +241,7 @@ base::ContainsValue(delegate_->GetAccounts(), account_info_.account_id)); account_manager_.UpsertAccount(gaia_account_key_, kUserEmail, - AccountManager::kInvalidToken); + chromeos::AccountManager::kInvalidToken); EXPECT_TRUE(delegate_->RefreshTokenIsAvailable(account_info_.account_id)); EXPECT_TRUE( @@ -285,7 +285,7 @@ TEST_F(CrOSOAuthDelegateTest, DummyTokensArePreEmptivelyRejected) { TokenServiceObserver observer(delegate_.get()); delegate_->UpdateCredentials(account_info_.account_id, - AccountManager::kInvalidToken); + chromeos::AccountManager::kInvalidToken); const GoogleServiceAuthError error = delegate_->GetAuthError(account_info_.account_id); @@ -334,8 +334,8 @@ } // If observers register themselves with |OAuth2TokenServiceDelegate| before -// |AccountManager| has been initialized, they should receive all the accounts -// stored in |AccountManager| in a single batch. +// |chromeos::AccountManager| has been initialized, they should receive all the +// accounts stored in |chromeos::AccountManager| in a single batch. TEST_F(CrOSOAuthDelegateTest, BatchChangeObserversAreNotifiedOncePerBatch) { // Setup AccountInfo account1 = CreateAccountInfoTestFixture( @@ -346,37 +346,38 @@ account_tracker_service_.SeedAccountInfo(account1); account_tracker_service_.SeedAccountInfo(account2); account_manager_.UpsertAccount( - AccountManager::AccountKey{account1.gaia, ACCOUNT_TYPE_GAIA}, + chromeos::AccountManager::AccountKey{account1.gaia, ACCOUNT_TYPE_GAIA}, "user1@example.com", "token1"); account_manager_.UpsertAccount( - AccountManager::AccountKey{account2.gaia, ACCOUNT_TYPE_GAIA}, + chromeos::AccountManager::AccountKey{account2.gaia, ACCOUNT_TYPE_GAIA}, "user2@example.com", "token2"); task_environment_.RunUntilIdle(); - AccountManager account_manager; - // AccountManager will not be fully initialized until + chromeos::AccountManager account_manager; + // chromeos::AccountManager will not be fully initialized until // |task_environment_.RunUntilIdle()| is called. account_manager.Initialize(tmp_dir_.GetPath(), client_->GetURLLoaderFactory(), immediate_callback_runner_); - // Register callbacks before AccountManager has been fully initialized. - auto delegate = std::make_unique<ChromeOSOAuth2TokenServiceDelegate>( + // Register callbacks before chromeos::AccountManager has been fully + // initialized. + auto delegate = std::make_unique<ProfileOAuth2TokenServiceDelegateChromeOS>( &account_tracker_service_, network::TestNetworkConnectionTracker::GetInstance(), &account_manager); delegate->LoadCredentials(account1.account_id /* primary_account_id */); TokenServiceObserver observer(delegate.get()); - // Wait until AccountManager is fully initialized. + // Wait until chromeos::AccountManager is fully initialized. task_environment_.RunUntilIdle(); // Tests // The observer should receive 3 batch change callbacks: - // First - A batch of all accounts stored in AccountManager: because of the - // delegate's invocation of |AccountManager::GetAccounts| in its constructor. - // Followed by 2 updates for the individual accounts (|account1| and - // |account2|): because of the delegate's registration as an - // |AccountManager::Observer| before |AccountManager| has been fully - // initialized. + // First - A batch of all accounts stored in chromeos::AccountManager: because + // of the delegate's invocation of |chromeos::AccountManager::GetAccounts| in + // its constructor. Followed by 2 updates for the individual accounts + // (|account1| and |account2|): because of the delegate's registration as an + // |chromeos::AccountManager::Observer| before |chromeos::AccountManager| has + // been fully initialized. EXPECT_EQ(3UL, observer.batch_change_records_.size()); const std::vector<std::string>& first_batch = @@ -389,9 +390,10 @@ TEST_F(CrOSOAuthDelegateTest, GetAccountsShouldNotReturnAdAccounts) { EXPECT_TRUE(delegate_->GetAccounts().empty()); - // Insert an Active Directory account into AccountManager. - account_manager_.UpsertAccount(ad_account_key_, kUserEmail, - AccountManager::kActiveDirectoryDummyToken); + // Insert an Active Directory account into chromeos::AccountManager. + account_manager_.UpsertAccount( + ad_account_key_, kUserEmail, + chromeos::AccountManager::kActiveDirectoryDummyToken); // OAuth delegate should not return Active Directory accounts. EXPECT_TRUE(delegate_->GetAccounts().empty()); @@ -413,7 +415,7 @@ EXPECT_TRUE(delegate_->GetAccounts().empty()); account_manager_.UpsertAccount(gaia_account_key_, kUserEmail, - AccountManager::kInvalidToken); + chromeos::AccountManager::kInvalidToken); std::vector<std::string> accounts = delegate_->GetAccounts(); EXPECT_EQ(1UL, accounts.size()); @@ -433,15 +435,16 @@ // accounts, 1 has a valid refresh token and 1 has a dummy token. account_manager_.UpsertAccount(gaia_account_key_, kUserEmail, kGaiaToken); - AccountManager::AccountKey gaia_account_key2{"random-gaia-id", - ACCOUNT_TYPE_GAIA}; + chromeos::AccountManager::AccountKey gaia_account_key2{"random-gaia-id", + ACCOUNT_TYPE_GAIA}; account_tracker_service_.SeedAccountInfo( CreateAccountInfoTestFixture(gaia_account_key2.id, kUserEmail2)); account_manager_.UpsertAccount(gaia_account_key2, kUserEmail2, - AccountManager::kInvalidToken); + chromeos::AccountManager::kInvalidToken); - account_manager_.UpsertAccount(ad_account_key_, kUserEmail3, - AccountManager::kActiveDirectoryDummyToken); + account_manager_.UpsertAccount( + ad_account_key_, kUserEmail3, + chromeos::AccountManager::kActiveDirectoryDummyToken); // Verify. const std::vector<std::string> accounts = delegate_->GetAccounts(); @@ -572,4 +575,4 @@ EXPECT_EQ(1, access_token_consumer.num_access_token_fetch_failure_); } -} // namespace chromeos +} // namespace signin
diff --git a/components/sync/BUILD.gn b/components/sync/BUILD.gn index 129a828..6ec525b 100644 --- a/components/sync/BUILD.gn +++ b/components/sync/BUILD.gn
@@ -26,7 +26,6 @@ "base/data_type_histogram.h", "base/encryptor.h", "base/enum_set.h", - "base/experiments.h", "base/extensions_activity.cc", "base/extensions_activity.h", "base/get_session_name.cc",
diff --git a/components/sync/base/experiments.h b/components/sync/base/experiments.h deleted file mode 100644 index 921acaa8..0000000 --- a/components/sync/base/experiments.h +++ /dev/null
@@ -1,31 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef COMPONENTS_SYNC_BASE_EXPERIMENTS_H_ -#define COMPONENTS_SYNC_BASE_EXPERIMENTS_H_ - -#include <string> - -#include "components/sync/base/model_type.h" - -namespace syncer { - -const char kFaviconSyncTag[] = "favicon_sync"; -const char kPreCommitUpdateAvoidanceTag[] = "pre_commit_update_avoidance"; - -// A structure to hold the enable status of experimental sync features. -struct Experiments { - Experiments() : favicon_sync_limit(200) {} - - bool Matches(const Experiments& rhs) { - return favicon_sync_limit == rhs.favicon_sync_limit; - } - - // The number of favicons that a client is permitted to sync. - int favicon_sync_limit; -}; - -} // namespace syncer - -#endif // COMPONENTS_SYNC_BASE_EXPERIMENTS_H_
diff --git a/components/sync/base/pref_names.cc b/components/sync/base/pref_names.cc index e660540b..20b750f 100644 --- a/components/sync/base/pref_names.cc +++ b/components/sync/base/pref_names.cc
@@ -15,8 +15,9 @@ const char kSyncLastPollTime[] = "sync.last_poll_time"; // 64-bit integer serialization of base::TimeDelta storing poll intervals -// received by the server (in seconds). -const char kSyncShortPollIntervalSeconds[] = "sync.short_poll_interval"; +// received by the server (in seconds). For historic reasons, this is called +// "short_poll_interval", but it's worth the hassle to rename it. +const char kSyncPollIntervalSeconds[] = "sync.short_poll_interval"; const char kSyncLongPollIntervalSeconds[] = "sync.long_poll_interval"; // Boolean specifying whether the user finished setting up sync at least once. @@ -98,9 +99,6 @@ const char kSyncBirthday[] = "sync.birthday"; const char kSyncBagOfChips[] = "sync.bag_of_chips"; -// Stores the timestamp of first sync. -const char kSyncFirstSyncTime[] = "sync.first_sync_time"; - // Stores whether a platform specific passphrase error prompt has been shown to // the user (e.g. an Android system notification). Used for out of band prompts // that we only want to use once.
diff --git a/components/sync/base/pref_names.h b/components/sync/base/pref_names.h index 896a951..0db1907 100644 --- a/components/sync/base/pref_names.h +++ b/components/sync/base/pref_names.h
@@ -13,7 +13,7 @@ extern const char kSyncLastSyncedTime[]; extern const char kSyncLastPollTime[]; -extern const char kSyncShortPollIntervalSeconds[]; +extern const char kSyncPollIntervalSeconds[]; extern const char kSyncLongPollIntervalSeconds[]; extern const char kSyncFirstSetupComplete[]; extern const char kSyncKeepEverythingSynced[]; @@ -72,8 +72,6 @@ extern const char kSyncSpareBootstrapToken[]; #endif // defined(OS_CHROMEOS) -extern const char kSyncFirstSyncTime[]; - extern const char kSyncPassphrasePrompted[]; extern const char kSyncMemoryPressureWarningCount[];
diff --git a/components/sync/base/sync_prefs.cc b/components/sync/base/sync_prefs.cc index a1aa08c..70df11c 100644 --- a/components/sync/base/sync_prefs.cc +++ b/components/sync/base/sync_prefs.cc
@@ -30,6 +30,9 @@ // Obsolete pref that used to store a bool on whether Sync has an auth error. const char kSyncHasAuthError[] = "sync.has_auth_error"; +// Obsolete pref that used to store the timestamp of first sync. +const char kSyncFirstSyncTime[] = "sync.first_sync_time"; + // Groups of prefs that always have the same value as a "master" pref. // For example, the APPS group has {APP_LIST, APP_SETTINGS} // (as well as APPS, but that is implied), so @@ -153,9 +156,8 @@ registry->RegisterStringPref(prefs::kSyncBagOfChips, std::string()); registry->RegisterInt64Pref(prefs::kSyncLastSyncedTime, 0); registry->RegisterInt64Pref(prefs::kSyncLastPollTime, 0); - // TODO(crbug.com/938865): Remove this pref. - registry->RegisterInt64Pref(prefs::kSyncFirstSyncTime, 0); - registry->RegisterInt64Pref(prefs::kSyncShortPollIntervalSeconds, 0); + registry->RegisterInt64Pref(prefs::kSyncPollIntervalSeconds, 0); + // TODO(crbug.com/930125): Remove this pref. registry->RegisterInt64Pref(prefs::kSyncLongPollIntervalSeconds, 0); registry->RegisterBooleanPref(prefs::kSyncManaged, false); registry->RegisterStringPref(prefs::kSyncEncryptionBootstrapToken, @@ -181,6 +183,7 @@ registry->RegisterStringPref(kSyncNigoriStateForPassphraseTransition, std::string()); registry->RegisterBooleanPref(kSyncHasAuthError, false); + registry->RegisterInt64Pref(kSyncFirstSyncTime, 0); } void SyncPrefs::AddSyncPrefObserver(SyncPrefObserver* sync_pref_observer) { @@ -201,7 +204,7 @@ pref_service_->ClearPref(prefs::kSyncBagOfChips); pref_service_->ClearPref(prefs::kSyncLastSyncedTime); pref_service_->ClearPref(prefs::kSyncLastPollTime); - pref_service_->ClearPref(prefs::kSyncShortPollIntervalSeconds); + pref_service_->ClearPref(prefs::kSyncPollIntervalSeconds); pref_service_->ClearPref(prefs::kSyncLongPollIntervalSeconds); pref_service_->ClearPref(prefs::kSyncEncryptionBootstrapToken); pref_service_->ClearPref(prefs::kSyncKeystoreEncryptionBootstrapToken); @@ -265,27 +268,15 @@ pref_service_->SetInt64(prefs::kSyncLastPollTime, time.ToInternalValue()); } -base::TimeDelta SyncPrefs::GetShortPollInterval() const { +base::TimeDelta SyncPrefs::GetPollInterval() const { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); return base::TimeDelta::FromSeconds( - pref_service_->GetInt64(prefs::kSyncShortPollIntervalSeconds)); + pref_service_->GetInt64(prefs::kSyncPollIntervalSeconds)); } -void SyncPrefs::SetShortPollInterval(base::TimeDelta interval) { +void SyncPrefs::SetPollInterval(base::TimeDelta interval) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - pref_service_->SetInt64(prefs::kSyncShortPollIntervalSeconds, - interval.InSeconds()); -} - -base::TimeDelta SyncPrefs::GetLongPollInterval() const { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - return base::TimeDelta::FromSeconds( - pref_service_->GetInt64(prefs::kSyncLongPollIntervalSeconds)); -} - -void SyncPrefs::SetLongPollInterval(base::TimeDelta interval) { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - pref_service_->SetInt64(prefs::kSyncLongPollIntervalSeconds, + pref_service_->SetInt64(prefs::kSyncPollIntervalSeconds, interval.InSeconds()); } @@ -534,19 +525,6 @@ return decoded; } -base::Time SyncPrefs::GetFirstSyncTime() const { - return base::Time::FromInternalValue( - pref_service_->GetInt64(prefs::kSyncFirstSyncTime)); -} - -void SyncPrefs::SetFirstSyncTime(base::Time time) { - pref_service_->SetInt64(prefs::kSyncFirstSyncTime, time.ToInternalValue()); -} - -void SyncPrefs::ClearFirstSyncTime() { - pref_service_->ClearPref(prefs::kSyncFirstSyncTime); -} - bool SyncPrefs::IsPassphrasePrompted() const { return pref_service_->GetBoolean(prefs::kSyncPassphrasePrompted); } @@ -639,4 +617,8 @@ pref_service->ClearPref(kSyncHasAuthError); } +void ClearObsoleteFirstSyncTime(PrefService* pref_service) { + pref_service->ClearPref(kSyncFirstSyncTime); +} + } // namespace syncer
diff --git a/components/sync/base/sync_prefs.h b/components/sync/base/sync_prefs.h index d0f641ac..650bb2c 100644 --- a/components/sync/base/sync_prefs.h +++ b/components/sync/base/sync_prefs.h
@@ -91,11 +91,8 @@ base::Time GetLastPollTime() const; void SetLastPollTime(base::Time time); - base::TimeDelta GetShortPollInterval() const; - void SetShortPollInterval(base::TimeDelta interval); - - base::TimeDelta GetLongPollInterval() const; - void SetLongPollInterval(base::TimeDelta interval); + base::TimeDelta GetPollInterval() const; + void SetPollInterval(base::TimeDelta interval); bool HasKeepEverythingSynced() const; @@ -155,12 +152,6 @@ void SetBagOfChips(const std::string& bag_of_chips); std::string GetBagOfChips() const; - // Get/set/clear first sync time of current user. Used to roll back browsing - // data later when user signs out. - base::Time GetFirstSyncTime() const; - void SetFirstSyncTime(base::Time time); - void ClearFirstSyncTime(); - // Out of band sync passphrase prompt getter/setter. bool IsPassphrasePrompted() const; void SetPassphrasePrompted(bool value); @@ -237,6 +228,7 @@ void ClearObsoleteUserTypePrefs(PrefService* pref_service); void ClearObsoleteClearServerDataPrefs(PrefService* pref_service); void ClearObsoleteAuthErrorPrefs(PrefService* pref_service); +void ClearObsoleteFirstSyncTime(PrefService* pref_service); } // namespace syncer
diff --git a/components/sync/base/sync_prefs_unittest.cc b/components/sync/base/sync_prefs_unittest.cc index fb2c334..7bcad55 100644 --- a/components/sync/base/sync_prefs_unittest.cc +++ b/components/sync/base/sync_prefs_unittest.cc
@@ -53,22 +53,13 @@ } } -TEST_F(SyncPrefsTest, ShortPollInterval) { - EXPECT_TRUE(sync_prefs_->GetShortPollInterval().is_zero()); +TEST_F(SyncPrefsTest, PollInterval) { + EXPECT_TRUE(sync_prefs_->GetPollInterval().is_zero()); - sync_prefs_->SetShortPollInterval(base::TimeDelta::FromMinutes(30)); + sync_prefs_->SetPollInterval(base::TimeDelta::FromMinutes(30)); - EXPECT_FALSE(sync_prefs_->GetShortPollInterval().is_zero()); - EXPECT_EQ(sync_prefs_->GetShortPollInterval().InMinutes(), 30); -} - -TEST_F(SyncPrefsTest, LongPollInterval) { - EXPECT_TRUE(sync_prefs_->GetLongPollInterval().is_zero()); - - sync_prefs_->SetLongPollInterval(base::TimeDelta::FromMinutes(60)); - - EXPECT_FALSE(sync_prefs_->GetLongPollInterval().is_zero()); - EXPECT_EQ(sync_prefs_->GetLongPollInterval().InMinutes(), 60); + EXPECT_FALSE(sync_prefs_->GetPollInterval().is_zero()); + EXPECT_EQ(sync_prefs_->GetPollInterval().InMinutes(), 30); } class MockSyncPrefObserver : public SyncPrefObserver {
diff --git a/components/sync/driver/glue/sync_backend_host_core.cc b/components/sync/driver/glue/sync_backend_host_core.cc index 9f962da6..e5fce140 100644 --- a/components/sync/driver/glue/sync_backend_host_core.cc +++ b/components/sync/driver/glue/sync_backend_host_core.cc
@@ -348,8 +348,7 @@ params.report_unrecoverable_error_function; args.cancelation_signal = &stop_syncing_signal_; args.saved_nigori_state = std::move(params.saved_nigori_state); - args.short_poll_interval = params.short_poll_interval; - args.long_poll_interval = params.long_poll_interval; + args.poll_interval = params.poll_interval; args.cache_guid = params.cache_guid; args.birthday = params.birthday; args.bag_of_chips = params.bag_of_chips;
diff --git a/components/sync/driver/glue/sync_engine_impl.cc b/components/sync/driver/glue/sync_engine_impl.cc index 0eec6d6..b1b7cdbc 100644 --- a/components/sync/driver/glue/sync_engine_impl.cc +++ b/components/sync/driver/glue/sync_engine_impl.cc
@@ -16,7 +16,6 @@ #include "components/invalidation/impl/invalidation_switches.h" #include "components/invalidation/public/invalidation_service.h" #include "components/invalidation/public/object_id_invalidation_map.h" -#include "components/sync/base/experiments.h" #include "components/sync/base/invalidation_helper.h" #include "components/sync/base/sync_prefs.h" #include "components/sync/driver/glue/sync_backend_host_core.h" @@ -303,13 +302,6 @@ ready_task.Run(succeeded_configuration_types, failed_configuration_types); } -void SyncEngineImpl::AddExperimentalTypes() { - DCHECK(initialized()); - Experiments experiments; - if (core_->sync_manager()->ReceivedExperiment(&experiments)) - host_->OnExperimentsChanged(experiments); -} - void SyncEngineImpl::HandleInitializationSuccessOnFrontendLoop( ModelTypeSet initial_types, const WeakHandle<JsBackend> js_backend, @@ -334,10 +326,6 @@ OnInvalidatorStateChange(invalidator_->GetInvalidatorState()); } - // Now that we've downloaded the control types, we can see if there are any - // experimental types to enable. This should be done before we inform - // the host to ensure they're visible in the customize screen. - AddExperimentalTypes(); host_->OnEngineInitialized(initial_types, js_backend, debug_info_listener, cache_guid, session_name, birthday, bag_of_chips, /*success=*/true); @@ -359,7 +347,6 @@ // Process any changes to the datatypes we're syncing. // TODO(sync): add support for removing types. if (initialized()) { - AddExperimentalTypes(); host_->OnSyncCycleCompleted(snapshot); } }
diff --git a/components/sync/driver/glue/sync_engine_impl.h b/components/sync/driver/glue/sync_engine_impl.h index db4f0ef86..82100c060 100644 --- a/components/sync/driver/glue/sync_engine_impl.h +++ b/components/sync/driver/glue/sync_engine_impl.h
@@ -161,11 +161,6 @@ private: friend class SyncBackendHostCore; - // Checks if we have received a notice to turn on experimental datatypes - // (via the nigori node) and informs the frontend if that is the case. - // Note: it is illegal to call this before the backend is initialized. - void AddExperimentalTypes(); - // Handles backend initialization failure. void HandleInitializationFailureOnFrontendLoop();
diff --git a/components/sync/driver/glue/sync_engine_impl_unittest.cc b/components/sync/driver/glue/sync_engine_impl_unittest.cc index 60cc1a99..feb3f10 100644 --- a/components/sync/driver/glue/sync_engine_impl_unittest.cc +++ b/components/sync/driver/glue/sync_engine_impl_unittest.cc
@@ -28,7 +28,6 @@ #include "components/invalidation/public/invalidation_service.h" #include "components/invalidation/public/invalidator_state.h" #include "components/invalidation/public/object_id_invalidation_map.h" -#include "components/sync/base/experiments.h" #include "components/sync/base/invalidation_helper.h" #include "components/sync/base/sync_prefs.h" #include "components/sync/base/test_unrecoverable_error_handler.h"
diff --git a/components/sync/driver/sync_driver_switches.cc b/components/sync/driver/sync_driver_switches.cc index b9bebb28d..9a28d47e 100644 --- a/components/sync/driver/sync_driver_switches.cc +++ b/components/sync/driver/sync_driver_switches.cc
@@ -14,9 +14,6 @@ // occur. const char kSyncDisableDeferredStartup[] = "sync-disable-deferred-startup"; -// Enables feature to avoid unnecessary GetUpdate requests. -const char kSyncEnableGetUpdateAvoidance[] = "sync-enable-get-update-avoidance"; - // Controls whether the initial state of the "Capture Specifics" flag on // chrome://sync-internals is enabled. const char kSyncIncludeSpecificsInProtocolLog[] = "sync-include-specifics";
diff --git a/components/sync/driver/sync_driver_switches.h b/components/sync/driver/sync_driver_switches.h index 186a6c27..02fb8be 100644 --- a/components/sync/driver/sync_driver_switches.h +++ b/components/sync/driver/sync_driver_switches.h
@@ -14,7 +14,6 @@ // definition of their values in the .cc file. extern const char kSyncDeferredStartupTimeoutSeconds[]; extern const char kSyncDisableDeferredStartup[]; -extern const char kSyncEnableGetUpdateAvoidance[]; extern const char kSyncIncludeSpecificsInProtocolLog[]; extern const char kSyncServiceURL[]; extern const char kSyncShortInitialRetryOverride[];
diff --git a/components/sync/driver/test_sync_service.cc b/components/sync/driver/test_sync_service.cc index 5e82ff4..cf216d3 100644 --- a/components/sync/driver/test_sync_service.cc +++ b/components/sync/driver/test_sync_service.cc
@@ -27,8 +27,7 @@ /*num_to_delete_entries_by_type=*/ std::vector<int>(MODEL_TYPE_COUNT, 0), /*get_updates_origin=*/sync_pb::SyncEnums::UNKNOWN_ORIGIN, - /*short_poll_interval=*/base::TimeDelta::FromMinutes(30), - /*long_poll_interval=*/base::TimeDelta::FromMinutes(180), + /*poll_interval=*/base::TimeDelta::FromMinutes(30), /*has_remaining_local_changes=*/false); }
diff --git a/components/sync/engine/cycle/sync_cycle_snapshot.cc b/components/sync/engine/cycle/sync_cycle_snapshot.cc index 92ddb4f..e307e2f 100644 --- a/components/sync/engine/cycle/sync_cycle_snapshot.cc +++ b/components/sync/engine/cycle/sync_cycle_snapshot.cc
@@ -52,8 +52,7 @@ const std::vector<int>& num_entries_by_type, const std::vector<int>& num_to_delete_entries_by_type, sync_pb::SyncEnums::GetUpdatesOrigin get_updates_origin, - base::TimeDelta short_poll_interval, - base::TimeDelta long_poll_interval, + base::TimeDelta poll_interval, bool has_remaining_local_changes) : model_neutral_state_(model_neutral_state), download_progress_markers_(download_progress_markers), @@ -68,8 +67,7 @@ num_entries_by_type_(num_entries_by_type), num_to_delete_entries_by_type_(num_to_delete_entries_by_type), get_updates_origin_(get_updates_origin), - short_poll_interval_(short_poll_interval), - long_poll_interval_(long_poll_interval), + poll_interval_(poll_interval), has_remaining_local_changes_(has_remaining_local_changes), is_initialized_(true) {} @@ -120,9 +118,7 @@ } value->Set("counter_entries", std::move(counter_entries)); value->SetBoolean("hasRemainingLocalChanges", has_remaining_local_changes_); - value->SetString("short_poll_interval", - FormatTimeDelta(short_poll_interval_)); - value->SetString("long_poll_interval", FormatTimeDelta(long_poll_interval_)); + value->SetString("poll_interval", FormatTimeDelta(poll_interval_)); value->SetString( "poll_finish_time", base::TimeFormatShortDateAndTimeWithTimeZone(poll_finish_time_)); @@ -194,12 +190,8 @@ return get_updates_origin_; } -base::TimeDelta SyncCycleSnapshot::short_poll_interval() const { - return short_poll_interval_; -} - -base::TimeDelta SyncCycleSnapshot::long_poll_interval() const { - return long_poll_interval_; +base::TimeDelta SyncCycleSnapshot::poll_interval() const { + return poll_interval_; } } // namespace syncer
diff --git a/components/sync/engine/cycle/sync_cycle_snapshot.h b/components/sync/engine/cycle/sync_cycle_snapshot.h index efda10f..96275a9 100644 --- a/components/sync/engine/cycle/sync_cycle_snapshot.h +++ b/components/sync/engine/cycle/sync_cycle_snapshot.h
@@ -43,8 +43,7 @@ const std::vector<int>& num_entries_by_type, const std::vector<int>& num_to_delete_entries_by_type, sync_pb::SyncEnums::GetUpdatesOrigin get_updates_origin, - base::TimeDelta short_poll_interval, - base::TimeDelta long_poll_interval, + base::TimeDelta poll_interval, bool has_remaining_local_changes); SyncCycleSnapshot(const SyncCycleSnapshot& other); ~SyncCycleSnapshot(); @@ -66,8 +65,7 @@ const std::vector<int>& num_entries_by_type() const; const std::vector<int>& num_to_delete_entries_by_type() const; sync_pb::SyncEnums::GetUpdatesOrigin get_updates_origin() const; - base::TimeDelta short_poll_interval() const; - base::TimeDelta long_poll_interval() const; + base::TimeDelta poll_interval() const; // Whether usynced items existed at the time the sync cycle completed. bool has_remaining_local_changes() const; @@ -91,8 +89,7 @@ sync_pb::SyncEnums::GetUpdatesOrigin get_updates_origin_; - base::TimeDelta short_poll_interval_; - base::TimeDelta long_poll_interval_; + base::TimeDelta poll_interval_; bool has_remaining_local_changes_;
diff --git a/components/sync/engine/cycle/sync_cycle_snapshot_unittest.cc b/components/sync/engine/cycle/sync_cycle_snapshot_unittest.cc index b59477c..1fbe7d5 100644 --- a/components/sync/engine/cycle/sync_cycle_snapshot_unittest.cc +++ b/components/sync/engine/cycle/sync_cycle_snapshot_unittest.cc
@@ -22,8 +22,8 @@ class SyncCycleSnapshotTest : public testing::Test {}; TEST_F(SyncCycleSnapshotTest, SyncCycleSnapshotToValue) { - // Formatting of "short_poll_interval" and "long_poll_interval" values depends - // on the current locale. Expectations below use English (US) formatting. + // Formatting of "poll_interval" value depends on the current locale. + // Expectations below use English (US) formatting. base::test::ScopedRestoreICUDefaultLocale restore_locale; base::i18n::SetICUDefaultLocale("en_US"); @@ -53,11 +53,10 @@ false, 0, base::Time::Now(), base::Time::Now(), std::vector<int>(MODEL_TYPE_COUNT, 0), std::vector<int>(MODEL_TYPE_COUNT, 0), sync_pb::SyncEnums::UNKNOWN_ORIGIN, - /*short_poll_interval=*/base::TimeDelta::FromMinutes(30), - /*long_poll_interval=*/base::TimeDelta::FromMinutes(180), + /*poll_interval=*/base::TimeDelta::FromMinutes(30), /*has_remaining_local_changes=*/false); std::unique_ptr<base::DictionaryValue> value(snapshot.ToValue()); - EXPECT_EQ(20u, value->size()); + EXPECT_EQ(19u, value->size()); ExpectDictIntegerValue(model_neutral.num_successful_commits, *value, "numSuccessfulCommits"); ExpectDictIntegerValue(model_neutral.num_successful_bookmark_commits, *value, @@ -82,8 +81,7 @@ ExpectDictIntegerValue(kNumServerConflicts, *value, "numServerConflicts"); ExpectDictBooleanValue(false, *value, "notificationsEnabled"); ExpectDictBooleanValue(false, *value, "hasRemainingLocalChanges"); - ExpectDictStringValue("0h 30m", *value, "short_poll_interval"); - ExpectDictStringValue("3h 0m", *value, "long_poll_interval"); + ExpectDictStringValue("0h 30m", *value, "poll_interval"); // poll_finish_time includes the local time zone, so simply verify its // existence. EXPECT_TRUE(
diff --git a/components/sync/engine/engine_components_factory.h b/components/sync/engine/engine_components_factory.h index 08cfb7a..5a08b2b 100644 --- a/components/sync/engine/engine_components_factory.h +++ b/components/sync/engine/engine_components_factory.h
@@ -47,16 +47,6 @@ BACKOFF_SHORT_INITIAL_RETRY_OVERRIDE }; - enum PreCommitUpdatesPolicy { - // By default, the server will enable or disable this experiment through the - // sync protocol's experiments data type. - SERVER_CONTROLLED_PRE_COMMIT_UPDATE_AVOIANCE, - - // This flag overrides the server's decision and enables the pre-commit - // update avoidance experiment. - FORCE_ENABLE_PRE_COMMIT_UPDATE_AVOIDANCE, - }; - // Configuration options for internal components. This struct is expected // to grow and shrink over time with transient features / experiments, // roughly following command line flags in chrome. Implementations of @@ -66,7 +56,6 @@ EncryptionMethod encryption_method; BackoffOverride backoff_override; bool force_short_nudge_delay_for_test; - PreCommitUpdatesPolicy pre_commit_updates_policy; }; // For selecting the types of storage to use to persist sync data when @@ -97,8 +86,7 @@ DebugInfoGetter* debug_info_getter, ModelTypeRegistry* model_type_registry, const std::string& invalidator_client_id, - base::TimeDelta short_poll_interval, - base::TimeDelta long_poll_interval) = 0; + base::TimeDelta poll_interval) = 0; virtual std::unique_ptr<syncable::DirectoryBackingStore> BuildDirectoryBackingStore(StorageOption storage,
diff --git a/components/sync/engine/engine_components_factory_impl.cc b/components/sync/engine/engine_components_factory_impl.cc index 7a70398..2931e58 100644 --- a/components/sync/engine/engine_components_factory_impl.cc +++ b/components/sync/engine/engine_components_factory_impl.cc
@@ -51,15 +51,12 @@ DebugInfoGetter* debug_info_getter, ModelTypeRegistry* model_type_registry, const std::string& invalidation_client_id, - base::TimeDelta short_poll_interval, - base::TimeDelta long_poll_interval) { + base::TimeDelta poll_interval) { return std::make_unique<SyncCycleContext>( connection_manager, directory, extensions_activity, listeners, debug_info_getter, model_type_registry, switches_.encryption_method == ENCRYPTION_KEYSTORE, - switches_.pre_commit_updates_policy == - FORCE_ENABLE_PRE_COMMIT_UPDATE_AVOIDANCE, - invalidation_client_id, short_poll_interval, long_poll_interval); + invalidation_client_id, poll_interval); } std::unique_ptr<syncable::DirectoryBackingStore>
diff --git a/components/sync/engine/engine_components_factory_impl.h b/components/sync/engine/engine_components_factory_impl.h index 9ddc96d..c3ca12c 100644 --- a/components/sync/engine/engine_components_factory_impl.h +++ b/components/sync/engine/engine_components_factory_impl.h
@@ -35,8 +35,7 @@ DebugInfoGetter* debug_info_getter, ModelTypeRegistry* model_type_registry, const std::string& invalidator_client_id, - base::TimeDelta short_poll_interval, - base::TimeDelta long_poll_interval) override; + base::TimeDelta poll_interval) override; std::unique_ptr<syncable::DirectoryBackingStore> BuildDirectoryBackingStore( StorageOption storage,
diff --git a/components/sync/engine/fake_sync_manager.cc b/components/sync/engine/fake_sync_manager.cc index 77fb5f0d..66f32bb 100644 --- a/components/sync/engine/fake_sync_manager.cc +++ b/components/sync/engine/fake_sync_manager.cc
@@ -210,10 +210,6 @@ return test_user_share_.user_share()->directory->cache_guid(); } -bool FakeSyncManager::ReceivedExperiment(Experiments* experiments) { - return false; -} - bool FakeSyncManager::HasUnsyncedItemsForTest() { NOTIMPLEMENTED(); return false;
diff --git a/components/sync/engine/fake_sync_manager.h b/components/sync/engine/fake_sync_manager.h index 4fd558288..c06f795 100644 --- a/components/sync/engine/fake_sync_manager.h +++ b/components/sync/engine/fake_sync_manager.h
@@ -103,7 +103,6 @@ ModelTypeConnector* GetModelTypeConnector() override; std::unique_ptr<ModelTypeConnector> GetModelTypeConnectorProxy() override; const std::string cache_guid() override; - bool ReceivedExperiment(Experiments* experiments) override; bool HasUnsyncedItemsForTest() override; SyncEncryptionHandler* GetEncryptionHandler() override; std::vector<std::unique_ptr<ProtocolEvent>> GetBufferedProtocolEvents()
diff --git a/components/sync/engine/polling_constants.cc b/components/sync/engine/polling_constants.cc index bc44982..61601c4 100644 --- a/components/sync/engine/polling_constants.cc +++ b/components/sync/engine/polling_constants.cc
@@ -7,13 +7,10 @@ namespace syncer { // Server can overwrite these values via client commands. -// Standard short poll. This is used when XMPP is off. // We use high values here to ensure that failure to receive poll updates from // the server doesn't result in rapid-fire polling from the client due to low // local limits. -const int64_t kDefaultShortPollIntervalSeconds = 3600 * 8; -// Long poll is used when XMPP is on. -const int64_t kDefaultLongPollIntervalSeconds = 3600 * 12; +const int64_t kDefaultPollIntervalSeconds = 3600 * 8; // Maximum interval for exponential backoff. const int64_t kMaxBackoffSeconds = 60 * 10; // 10 minutes.
diff --git a/components/sync/engine/polling_constants.h b/components/sync/engine/polling_constants.h index 2f2c4224..90613ce 100644 --- a/components/sync/engine/polling_constants.h +++ b/components/sync/engine/polling_constants.h
@@ -10,8 +10,7 @@ namespace syncer { // Constants used by SyncScheduler when polling servers for updates. -extern const int64_t kDefaultShortPollIntervalSeconds; -extern const int64_t kDefaultLongPollIntervalSeconds; +extern const int64_t kDefaultPollIntervalSeconds; extern const int64_t kMaxBackoffSeconds; extern const int kBackoffRandomizationFactor; extern const int kInitialBackoffRetrySeconds;
diff --git a/components/sync/engine/sync_engine.h b/components/sync/engine/sync_engine.h index 2ed8818b..4348028c 100644 --- a/components/sync/engine/sync_engine.h +++ b/components/sync/engine/sync_engine.h
@@ -84,9 +84,8 @@ std::string birthday; std::string bag_of_chips; - // Define the polling intervals. Must not be zero. - base::TimeDelta short_poll_interval; - base::TimeDelta long_poll_interval; + // Define the polling interval. Must not be zero. + base::TimeDelta poll_interval; private: DISALLOW_COPY_AND_ASSIGN(InitParams);
diff --git a/components/sync/engine/sync_engine_host.h b/components/sync/engine/sync_engine_host.h index 9d1914a6..3fdfc6b 100644 --- a/components/sync/engine/sync_engine_host.h +++ b/components/sync/engine/sync_engine_host.h
@@ -86,9 +86,6 @@ // Called to perform migration of |types|. virtual void OnMigrationNeededForTypes(ModelTypeSet types) = 0; - // Called when new datatypes are available for registration. - virtual void OnExperimentsChanged(const Experiments& experiments) = 0; - // Called when the sync cycle returns there is an user actionable error. virtual void OnActionableError(const SyncProtocolError& error) = 0; };
diff --git a/components/sync/engine/sync_engine_host_stub.cc b/components/sync/engine/sync_engine_host_stub.cc index 31cf58b..e3efc55 100644 --- a/components/sync/engine/sync_engine_host_stub.cc +++ b/components/sync/engine/sync_engine_host_stub.cc
@@ -40,8 +40,6 @@ void SyncEngineHostStub::OnMigrationNeededForTypes(ModelTypeSet types) {} -void SyncEngineHostStub::OnExperimentsChanged(const Experiments& experiments) {} - void SyncEngineHostStub::OnActionableError(const SyncProtocolError& error) {} } // namespace syncer
diff --git a/components/sync/engine/sync_engine_host_stub.h b/components/sync/engine/sync_engine_host_stub.h index b38cdc7..5db071c 100644 --- a/components/sync/engine/sync_engine_host_stub.h +++ b/components/sync/engine/sync_engine_host_stub.h
@@ -38,7 +38,6 @@ const StatusCounters& counters) override; void OnConnectionStatusChange(ConnectionStatus status) override; void OnMigrationNeededForTypes(ModelTypeSet types) override; - void OnExperimentsChanged(const Experiments& experiments) override; void OnActionableError(const SyncProtocolError& error) override; };
diff --git a/components/sync/engine/sync_engine_switches.cc b/components/sync/engine/sync_engine_switches.cc index 08c829c0..d5a3c05 100644 --- a/components/sync/engine/sync_engine_switches.cc +++ b/components/sync/engine/sync_engine_switches.cc
@@ -6,6 +6,14 @@ namespace switches { +// TODO(crbug.com/657130): Sync integration tests depend on the precommit get +// updates because invalidations aren't working for them. Therefore, they pass +// the command line switch to enable this feature. Once sync integrations test +// support invalidation, this should be removed. +// Enables feature to perform GetUpdate requests before every commit. +const char kSyncEnableGetUpdatesBeforeCommit[] = + "sync-enable-get-update-before-commits"; + const base::Feature kSyncResetPollIntervalOnStart{ "SyncResetPollIntervalOnStart", base::FEATURE_DISABLED_BY_DEFAULT};
diff --git a/components/sync/engine/sync_engine_switches.h b/components/sync/engine/sync_engine_switches.h index 45acd7e..6861251 100644 --- a/components/sync/engine/sync_engine_switches.h +++ b/components/sync/engine/sync_engine_switches.h
@@ -9,6 +9,8 @@ namespace switches { +extern const char kSyncEnableGetUpdatesBeforeCommit[]; + extern const base::Feature kSyncResetPollIntervalOnStart; extern const base::Feature kSyncUseScryptForNewCustomPassphrases;
diff --git a/components/sync/engine/sync_manager.h b/components/sync/engine/sync_manager.h index 2a678f0..871b4fd 100644 --- a/components/sync/engine/sync_manager.h +++ b/components/sync/engine/sync_manager.h
@@ -54,7 +54,6 @@ class SyncEncryptionHandler; class TypeDebugInfoObserver; class UnrecoverableErrorHandler; -struct Experiments; struct UserShare; // SyncManager encapsulates syncable::Directory and serves as the parent of all @@ -247,9 +246,8 @@ // Optional nigori state to be restored. std::unique_ptr<SyncEncryptionHandler::NigoriState> saved_nigori_state; - // Define the polling intervals. Must not be zero. - base::TimeDelta short_poll_interval; - base::TimeDelta long_poll_interval; + // Define the polling interval. Must not be zero. + base::TimeDelta poll_interval; // Non-authoritative values from prefs, to be compared with the Directory's // counterparts. @@ -360,11 +358,6 @@ // Requires that the SyncManager be initialized. virtual const std::string cache_guid() = 0; - // Reads the nigori node to determine if any experimental features should - // be enabled. - // Note: opens a transaction. May be called on any thread. - virtual bool ReceivedExperiment(Experiments* experiments) = 0; - // Returns whether there are remaining unsynced items. virtual bool HasUnsyncedItemsForTest() = 0;
diff --git a/components/sync/engine/test_engine_components_factory.cc b/components/sync/engine/test_engine_components_factory.cc index 29e7e05..fb4f593 100644 --- a/components/sync/engine/test_engine_components_factory.cc +++ b/components/sync/engine/test_engine_components_factory.cc
@@ -38,17 +38,14 @@ DebugInfoGetter* debug_info_getter, ModelTypeRegistry* model_type_registry, const std::string& invalidator_client_id, - base::TimeDelta short_poll_interval, - base::TimeDelta long_poll_interval) { + base::TimeDelta poll_interval) { // Tests don't wire up listeners. std::vector<SyncEngineEventListener*> empty_listeners; return std::unique_ptr<SyncCycleContext>(new SyncCycleContext( connection_manager, directory, monitor, empty_listeners, debug_info_getter, model_type_registry, - switches_.encryption_method == ENCRYPTION_KEYSTORE, - switches_.pre_commit_updates_policy == - FORCE_ENABLE_PRE_COMMIT_UPDATE_AVOIDANCE, - invalidator_client_id, short_poll_interval, long_poll_interval)); + switches_.encryption_method == ENCRYPTION_KEYSTORE, invalidator_client_id, + poll_interval)); } std::unique_ptr<syncable::DirectoryBackingStore>
diff --git a/components/sync/engine/test_engine_components_factory.h b/components/sync/engine/test_engine_components_factory.h index 6280fd5..caf57d8 100644 --- a/components/sync/engine/test_engine_components_factory.h +++ b/components/sync/engine/test_engine_components_factory.h
@@ -35,8 +35,7 @@ DebugInfoGetter* debug_info_getter, ModelTypeRegistry* model_type_registry, const std::string& invalidator_client_id, - base::TimeDelta short_poll_interval, - base::TimeDelta long_poll_interval) override; + base::TimeDelta poll_interval) override; std::unique_ptr<syncable::DirectoryBackingStore> BuildDirectoryBackingStore( StorageOption storage,
diff --git a/components/sync/engine_impl/cycle/nudge_tracker.cc b/components/sync/engine_impl/cycle/nudge_tracker.cc index 6f28bf3..ebf6e5b5 100644 --- a/components/sync/engine_impl/cycle/nudge_tracker.cc +++ b/components/sync/engine_impl/cycle/nudge_tracker.cc
@@ -26,7 +26,7 @@ case USER_EVENTS: // Accompany types rely on nudges from other types, and hence have long // nudge delays. - return base::TimeDelta::FromSeconds(kDefaultShortPollIntervalSeconds); + return base::TimeDelta::FromSeconds(kDefaultPollIntervalSeconds); case BOOKMARKS: case PREFERENCES: case SESSIONS: @@ -133,7 +133,7 @@ base::TimeDelta NudgeTracker::RecordLocalChange(ModelTypeSet types) { // Start with the longest delay. base::TimeDelta delay = - base::TimeDelta::FromSeconds(kDefaultShortPollIntervalSeconds); + base::TimeDelta::FromSeconds(kDefaultPollIntervalSeconds); for (ModelType type : types) { TypeTrackerMap::const_iterator tracker_it = type_trackers_.find(type); DCHECK(tracker_it != type_trackers_.end());
diff --git a/components/sync/engine_impl/cycle/sync_cycle.cc b/components/sync/engine_impl/cycle/sync_cycle.cc index 95d30f4c..0fc8384 100644 --- a/components/sync/engine_impl/cycle/sync_cycle.cc +++ b/components/sync/engine_impl/cycle/sync_cycle.cc
@@ -58,7 +58,7 @@ status_controller_->sync_start_time(), status_controller_->poll_finish_time(), num_entries_by_type, num_to_delete_entries_by_type, get_updates_origin, - context_->short_poll_interval(), context_->long_poll_interval(), + context_->poll_interval(), context_->model_type_registry()->HasUnsyncedItems()); return snapshot;
diff --git a/components/sync/engine_impl/cycle/sync_cycle.h b/components/sync/engine_impl/cycle/sync_cycle.h index b41478d..0971b60 100644 --- a/components/sync/engine_impl/cycle/sync_cycle.h +++ b/components/sync/engine_impl/cycle/sync_cycle.h
@@ -58,12 +58,8 @@ // use is for UI reporting. virtual bool IsAnyThrottleOrBackoff() = 0; - // The client has been instructed to change its short poll interval. - virtual void OnReceivedShortPollIntervalUpdate( - const base::TimeDelta& new_interval) = 0; - - // The client has been instructed to change its long poll interval. - virtual void OnReceivedLongPollIntervalUpdate( + // The client has been instructed to change its poll interval. + virtual void OnReceivedPollIntervalUpdate( const base::TimeDelta& new_interval) = 0; // The client has been instructed to change a nudge delay.
diff --git a/components/sync/engine_impl/cycle/sync_cycle_context.cc b/components/sync/engine_impl/cycle/sync_cycle_context.cc index 5dd33e4c..014a89b 100644 --- a/components/sync/engine_impl/cycle/sync_cycle_context.cc +++ b/components/sync/engine_impl/cycle/sync_cycle_context.cc
@@ -16,10 +16,8 @@ DebugInfoGetter* debug_info_getter, ModelTypeRegistry* model_type_registry, bool keystore_encryption_enabled, - bool client_enabled_pre_commit_update_avoidance, const std::string& invalidator_client_id, - base::TimeDelta short_poll_interval, - base::TimeDelta long_poll_interval) + base::TimeDelta poll_interval) : connection_manager_(connection_manager), directory_(directory), extensions_activity_(extensions_activity), @@ -29,15 +27,10 @@ model_type_registry_(model_type_registry), keystore_encryption_enabled_(keystore_encryption_enabled), invalidator_client_id_(invalidator_client_id), - server_enabled_pre_commit_update_avoidance_(false), - client_enabled_pre_commit_update_avoidance_( - client_enabled_pre_commit_update_avoidance), cookie_jar_mismatch_(false), cookie_jar_empty_(false), - short_poll_interval_(short_poll_interval), - long_poll_interval_(long_poll_interval) { - DCHECK(!short_poll_interval.is_zero()); - DCHECK(!long_poll_interval.is_zero()); + poll_interval_(poll_interval) { + DCHECK(!poll_interval.is_zero()); std::vector<SyncEngineEventListener*>::const_iterator it; for (it = listeners.begin(); it != listeners.end(); ++it) listeners_.AddObserver(*it);
diff --git a/components/sync/engine_impl/cycle/sync_cycle_context.h b/components/sync/engine_impl/cycle/sync_cycle_context.h index b3a9099..b4c09517 100644 --- a/components/sync/engine_impl/cycle/sync_cycle_context.h +++ b/components/sync/engine_impl/cycle/sync_cycle_context.h
@@ -48,10 +48,8 @@ DebugInfoGetter* debug_info_getter, ModelTypeRegistry* model_type_registry, bool keystore_encryption_enabled, - bool client_enabled_pre_commit_update_avoidance, const std::string& invalidator_client_id, - base::TimeDelta short_poll_interval, - base::TimeDelta long_poll_interval); + base::TimeDelta poll_interval); ~SyncCycleContext(); @@ -107,15 +105,6 @@ invalidator_client_id_ = id; } - bool ShouldFetchUpdatesBeforeCommit() const { - return !(server_enabled_pre_commit_update_avoidance_ || - client_enabled_pre_commit_update_avoidance_); - } - - void set_server_enabled_pre_commit_update_avoidance(bool value) { - server_enabled_pre_commit_update_avoidance_ = value; - } - ModelTypeRegistry* model_type_registry() { return model_type_registry_; } bool cookie_jar_mismatch() const { return cookie_jar_mismatch_; } @@ -128,16 +117,10 @@ void set_cookie_jar_empty(bool empty_jar) { cookie_jar_empty_ = empty_jar; } - base::TimeDelta short_poll_interval() const { return short_poll_interval_; } - void set_short_poll_interval(base::TimeDelta interval) { + base::TimeDelta poll_interval() const { return poll_interval_; } + void set_poll_interval(base::TimeDelta interval) { DCHECK(!interval.is_zero()); - short_poll_interval_ = interval; - } - - base::TimeDelta long_poll_interval() const { return long_poll_interval_; } - void set_long_poll_interval(base::TimeDelta interval) { - DCHECK(!interval.is_zero()); - long_poll_interval_ = interval; + poll_interval_ = interval; } private: @@ -180,15 +163,6 @@ // prevent us from receiving notifications of changes we make ourselves. std::string invalidator_client_id_; - // Flag to enable or disable the no pre-commit GetUpdates experiment. When - // this flag is set to false, the syncer has the option of not performing at - // GetUpdates request when there is nothing to fetch. - bool server_enabled_pre_commit_update_avoidance_; - - // If true, indicates that we've been passed a command-line flag to force - // enable the pre-commit update avoidance experiment described above. - const bool client_enabled_pre_commit_update_avoidance_; - // Whether the account(s) present in the content area's cookie jar match the // chrome account. If multiple accounts are present in the cookie jar, a // mismatch implies all of them are different from the chrome account. @@ -197,8 +171,7 @@ // If there's a cookie jar mismatch, whether the cookie jar was empty or not. bool cookie_jar_empty_; - base::TimeDelta short_poll_interval_; - base::TimeDelta long_poll_interval_; + base::TimeDelta poll_interval_; DISALLOW_COPY_AND_ASSIGN(SyncCycleContext); };
diff --git a/components/sync/engine_impl/cycle/test_util.cc b/components/sync/engine_impl/cycle/test_util.cc index c524713..4b3b349 100644 --- a/components/sync/engine_impl/cycle/test_util.cc +++ b/components/sync/engine_impl/cycle/test_util.cc
@@ -112,7 +112,7 @@ SyncCycle* cycle, const base::TimeDelta& new_poll) { SimulatePollSuccess(requested_types, cycle); - cycle->delegate()->OnReceivedLongPollIntervalUpdate(new_poll); + cycle->delegate()->OnReceivedPollIntervalUpdate(new_poll); } void SimulateGuRetryDelayCommandImpl(SyncCycle* cycle, base::TimeDelta delay) {
diff --git a/components/sync/engine_impl/js_sync_manager_observer_unittest.cc b/components/sync/engine_impl/js_sync_manager_observer_unittest.cc index 3d4a129..35309f85 100644 --- a/components/sync/engine_impl/js_sync_manager_observer_unittest.cc +++ b/components/sync/engine_impl/js_sync_manager_observer_unittest.cc
@@ -66,8 +66,7 @@ base::Time::Now(), base::Time::Now(), std::vector<int>(MODEL_TYPE_COUNT, 0), std::vector<int>(MODEL_TYPE_COUNT, 0), sync_pb::SyncEnums::UNKNOWN_ORIGIN, - /*short_poll_interval=*/base::TimeDelta::FromMinutes(30), - /*long_poll_interval=*/base::TimeDelta::FromMinutes(180), + /*poll_interval=*/base::TimeDelta::FromMinutes(30), /*has_remaining_local_changes=*/false); base::DictionaryValue expected_details; expected_details.Set("snapshot", snapshot.ToValue()); @@ -82,7 +81,7 @@ TEST_F(JsSyncManagerObserverTest, OnActionableError) { SyncProtocolError sync_error; - sync_error.action = CLEAR_USER_DATA_AND_RESYNC; + sync_error.action = RESET_LOCAL_SYNC_DATA; sync_error.error_type = TRANSIENT_ERROR; base::DictionaryValue expected_details; expected_details.Set("syncError", sync_error.ToValue());
diff --git a/components/sync/engine_impl/sync_encryption_handler_impl.cc b/components/sync/engine_impl/sync_encryption_handler_impl.cc index 61b272e..a0d4bf3 100644 --- a/components/sync/engine_impl/sync_encryption_handler_impl.cc +++ b/components/sync/engine_impl/sync_encryption_handler_impl.cc
@@ -19,7 +19,6 @@ #include "base/sequenced_task_runner.h" #include "base/threading/sequenced_task_runner_handle.h" #include "components/sync/base/encryptor.h" -#include "components/sync/base/experiments.h" #include "components/sync/base/passphrase_enums.h" #include "components/sync/base/sync_base_switches.h" #include "components/sync/base/time.h"
diff --git a/components/sync/engine_impl/sync_manager_impl.cc b/components/sync/engine_impl/sync_manager_impl.cc index f7a287c..ffbdab7e 100644 --- a/components/sync/engine_impl/sync_manager_impl.cc +++ b/components/sync/engine_impl/sync_manager_impl.cc
@@ -16,7 +16,6 @@ #include "base/threading/sequenced_task_runner_handle.h" #include "base/values.h" #include "components/sync/base/cancelation_signal.h" -#include "components/sync/base/experiments.h" #include "components/sync/base/invalidation_interface.h" #include "components/sync/base/model_type.h" #include "components/sync/base/nigori.h" @@ -262,8 +261,7 @@ DCHECK(!initialized_); DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); DCHECK(args->post_factory); - DCHECK(!args->short_poll_interval.is_zero()); - DCHECK(!args->long_poll_interval.is_zero()); + DCHECK(!args->poll_interval.is_zero()); if (!args->enable_local_sync_backend) { DCHECK(!args->credentials.account_id.empty()); } @@ -364,8 +362,7 @@ cycle_context_ = args->engine_components_factory->BuildContext( connection_manager_.get(), directory(), args->extensions_activity, listeners, &debug_info_event_listener_, model_type_registry_.get(), - args->invalidator_client_id, args->short_poll_interval, - args->long_poll_interval); + args->invalidator_client_id, args->poll_interval); scheduler_ = args->engine_components_factory->BuildScheduler( name_, cycle_context_.get(), args->cancelation_signal, args->enable_local_sync_backend); @@ -964,39 +961,6 @@ return directory()->cache_guid(); } -bool SyncManagerImpl::ReceivedExperiment(Experiments* experiments) { - ReadTransaction trans(FROM_HERE, GetUserShare()); - ReadNode nigori_node(&trans); - if (nigori_node.InitTypeRoot(NIGORI) != BaseNode::INIT_OK) { - DVLOG(1) << "Couldn't find Nigori node."; - return false; - } - bool found_experiment = false; - - ReadNode favicon_sync_node(&trans); - if (favicon_sync_node.InitByClientTagLookup(EXPERIMENTS, kFaviconSyncTag) == - BaseNode::INIT_OK) { - experiments->favicon_sync_limit = - favicon_sync_node.GetExperimentsSpecifics() - .favicon_sync() - .favicon_sync_limit(); - found_experiment = true; - } - - ReadNode pre_commit_update_avoidance_node(&trans); - if (pre_commit_update_avoidance_node.InitByClientTagLookup( - EXPERIMENTS, kPreCommitUpdateAvoidanceTag) == BaseNode::INIT_OK) { - cycle_context_->set_server_enabled_pre_commit_update_avoidance( - pre_commit_update_avoidance_node.GetExperimentsSpecifics() - .pre_commit_update_avoidance() - .enabled()); - // We don't bother setting found_experiment. The frontend doesn't need to - // know about this. - } - - return found_experiment; -} - bool SyncManagerImpl::HasUnsyncedItemsForTest() { return model_type_registry_->HasUnsyncedItems(); }
diff --git a/components/sync/engine_impl/sync_manager_impl.h b/components/sync/engine_impl/sync_manager_impl.h index d0f1d63..5462d2c6 100644 --- a/components/sync/engine_impl/sync_manager_impl.h +++ b/components/sync/engine_impl/sync_manager_impl.h
@@ -96,7 +96,6 @@ ModelTypeConnector* GetModelTypeConnector() override; std::unique_ptr<ModelTypeConnector> GetModelTypeConnectorProxy() override; const std::string cache_guid() override; - bool ReceivedExperiment(Experiments* experiments) override; bool HasUnsyncedItemsForTest() override; SyncEncryptionHandler* GetEncryptionHandler() override; std::vector<std::unique_ptr<ProtocolEvent>> GetBufferedProtocolEvents()
diff --git a/components/sync/engine_impl/sync_manager_impl_unittest.cc b/components/sync/engine_impl/sync_manager_impl_unittest.cc index fe2a014..7c03812 100644 --- a/components/sync/engine_impl/sync_manager_impl_unittest.cc +++ b/components/sync/engine_impl/sync_manager_impl_unittest.cc
@@ -971,8 +971,7 @@ args.unrecoverable_error_handler = MakeWeakHandle(mock_unrecoverable_error_handler_.GetWeakPtr()); args.cancelation_signal = &cancelation_signal_; - args.short_poll_interval = base::TimeDelta::FromMinutes(60); - args.long_poll_interval = base::TimeDelta::FromMinutes(120); + args.poll_interval = base::TimeDelta::FromMinutes(60); sync_manager_.Init(&args); sync_manager_.GetEncryptionHandler()->AddObserver(&encryption_observer_);
diff --git a/components/sync/engine_impl/sync_scheduler_impl.cc b/components/sync/engine_impl/sync_scheduler_impl.cc index 6741e77..856cf4be 100644 --- a/components/sync/engine_impl/sync_scheduler_impl.cc +++ b/components/sync/engine_impl/sync_scheduler_impl.cc
@@ -63,10 +63,6 @@ // waiting forever. So assert we would send something. DCHECK_NE(error.action, UNKNOWN_ACTION); return true; - case INVALID_CREDENTIAL: - // The notification for this is handled by PostAndProcessHeaders|. - // Server does no have to send any action for this. - return true; // Make UNKNOWN_ERROR a NOTREACHED. All the other error should be explicitly // handled. case UNKNOWN_ERROR: @@ -117,8 +113,7 @@ bool ignore_auth_credentials) : name_(name), started_(false), - syncer_short_poll_interval_seconds_(context->short_poll_interval()), - syncer_long_poll_interval_seconds_(context->long_poll_interval()), + syncer_poll_interval_seconds_(context->poll_interval()), mode_(CONFIGURATION_MODE), delay_provider_(delay_provider), syncer_(syncer), @@ -546,10 +541,7 @@ } TimeDelta SyncSchedulerImpl::GetPollInterval() { - return (!cycle_context_->notifications_enabled() || - !cycle_context_->ShouldFetchUpdatesBeforeCommit()) - ? syncer_short_poll_interval_seconds_ - : syncer_long_poll_interval_seconds_; + return syncer_poll_interval_seconds_; } void SyncSchedulerImpl::AdjustPolling(PollAdjustType type) { @@ -842,27 +834,15 @@ return wait_interval_ || nudge_tracker_.IsAnyTypeBlocked(); } -void SyncSchedulerImpl::OnReceivedShortPollIntervalUpdate( +void SyncSchedulerImpl::OnReceivedPollIntervalUpdate( const TimeDelta& new_interval) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - if (new_interval == syncer_short_poll_interval_seconds_) + if (new_interval == syncer_poll_interval_seconds_) return; - SDVLOG(1) << "Updating short poll interval to " << new_interval.InMinutes() + SDVLOG(1) << "Updating poll interval to " << new_interval.InMinutes() << " minutes."; - syncer_short_poll_interval_seconds_ = new_interval; - AdjustPolling(UPDATE_INTERVAL); -} - -void SyncSchedulerImpl::OnReceivedLongPollIntervalUpdate( - const TimeDelta& new_interval) { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - - if (new_interval == syncer_long_poll_interval_seconds_) - return; - SDVLOG(1) << "Updating long poll interval to " << new_interval.InMinutes() - << " minutes."; - syncer_long_poll_interval_seconds_ = new_interval; + syncer_poll_interval_seconds_ = new_interval; AdjustPolling(UPDATE_INTERVAL); }
diff --git a/components/sync/engine_impl/sync_scheduler_impl.h b/components/sync/engine_impl/sync_scheduler_impl.h index 27d69fb..4bab3909 100644 --- a/components/sync/engine_impl/sync_scheduler_impl.h +++ b/components/sync/engine_impl/sync_scheduler_impl.h
@@ -69,9 +69,7 @@ const base::TimeDelta& throttle_duration) override; void OnTypesBackedOff(ModelTypeSet types) override; bool IsAnyThrottleOrBackoff() override; - void OnReceivedShortPollIntervalUpdate( - const base::TimeDelta& new_interval) override; - void OnReceivedLongPollIntervalUpdate( + void OnReceivedPollIntervalUpdate( const base::TimeDelta& new_interval) override; void OnReceivedCustomNudgeDelays( const std::map<ModelType, base::TimeDelta>& nudge_delays) override; @@ -225,10 +223,9 @@ // Set in Start(), unset in Stop(). bool started_; - // Modifiable versions of kDefaultLongPollIntervalSeconds which can be + // Modifiable versions of kDefaultPollIntervalSeconds which can be // updated by the server. - base::TimeDelta syncer_short_poll_interval_seconds_; - base::TimeDelta syncer_long_poll_interval_seconds_; + base::TimeDelta syncer_poll_interval_seconds_; // Timer for polling. Restarted on each successful poll, and when entering // normal sync mode or exiting an error state. Not active in configuration
diff --git a/components/sync/engine_impl/sync_scheduler_impl_unittest.cc b/components/sync/engine_impl/sync_scheduler_impl_unittest.cc index a83d7a8..901a904968 100644 --- a/components/sync/engine_impl/sync_scheduler_impl_unittest.cc +++ b/components/sync/engine_impl/sync_scheduler_impl_unittest.cc
@@ -140,11 +140,9 @@ connection_.get(), directory(), extensions_activity_.get(), std::vector<SyncEngineEventListener*>(), nullptr, model_type_registry_.get(), - true, // enable keystore encryption - false, // force enable pre-commit GU avoidance + true, // enable keystore encryption "fake_invalidator_client_id", - /*short_poll_interval=*/base::TimeDelta::FromMinutes(30), - /*long_poll_interval=*/base::TimeDelta::FromMinutes(120)); + /*poll_interval=*/base::TimeDelta::FromMinutes(30)); context_->set_notifications_enabled(true); context_->set_account_name("Test"); RebuildScheduler(); @@ -700,7 +698,7 @@ DoAll(Invoke(test_util::SimulatePollSuccess), RecordSyncShareMultiple(×, kMinNumSamples, true))); - scheduler()->OnReceivedLongPollIntervalUpdate(poll_interval); + scheduler()->OnReceivedPollIntervalUpdate(poll_interval); TimeTicks optimal_start = TimeTicks::Now() + poll_interval; StartSyncScheduler(base::Time()); @@ -716,8 +714,7 @@ TEST_F(SyncSchedulerImplTest, ShouldUseInitialPollIntervalFromContext) { SyncShareTimes times; TimeDelta poll_interval(TimeDelta::FromMilliseconds(30)); - context()->set_short_poll_interval(poll_interval); - context()->set_long_poll_interval(poll_interval); + context()->set_poll_interval(poll_interval); RebuildScheduler(); EXPECT_CALL(*syncer(), PollSyncShare(_, _)) @@ -750,7 +747,7 @@ DoAll(Invoke(test_util::SimulatePollSuccess), RecordSyncShareMultiple(×, kMinNumSamples, true))); - scheduler()->OnReceivedLongPollIntervalUpdate(poll_interval); + scheduler()->OnReceivedPollIntervalUpdate(poll_interval); // Set the start time to now, as the poll was overdue. TimeTicks optimal_start = TimeTicks::Now(); @@ -774,7 +771,7 @@ DoAll(Invoke(test_util::SimulatePollSuccess), RecordSyncShareMultiple(×, kMinNumSamples, true))); - scheduler()->OnReceivedLongPollIntervalUpdate(poll_interval); + scheduler()->OnReceivedPollIntervalUpdate(poll_interval); // Set the start time to |poll_interval| in the future. TimeTicks optimal_start = TimeTicks::Now() + poll_interval; @@ -787,35 +784,12 @@ AnalyzePollRun(times, kMinNumSamples, optimal_start, poll_interval); } -// Test that the short poll interval is used. -TEST_F(SyncSchedulerImplTest, PollNotificationsDisabled) { - SyncShareTimes times; - TimeDelta poll_interval(TimeDelta::FromMilliseconds(30)); - EXPECT_CALL(*syncer(), PollSyncShare(_, _)) - .Times(AtLeast(kMinNumSamples)) - .WillRepeatedly( - DoAll(Invoke(test_util::SimulatePollSuccess), - RecordSyncShareMultiple(×, kMinNumSamples, true))); - - scheduler()->OnReceivedShortPollIntervalUpdate(poll_interval); - scheduler()->SetNotificationsEnabled(false); - - TimeTicks optimal_start = TimeTicks::Now() + poll_interval; - StartSyncScheduler(base::Time()); - - // Run again to wait for polling. - RunLoop(); - - StopSyncScheduler(); - AnalyzePollRun(times, kMinNumSamples, optimal_start, poll_interval); -} - // Test that polling intervals are updated when needed. TEST_F(SyncSchedulerImplTest, PollIntervalUpdate) { SyncShareTimes times; TimeDelta poll1(TimeDelta::FromMilliseconds(120)); TimeDelta poll2(TimeDelta::FromMilliseconds(30)); - scheduler()->OnReceivedLongPollIntervalUpdate(poll1); + scheduler()->OnReceivedPollIntervalUpdate(poll1); EXPECT_CALL(*syncer(), PollSyncShare(_, _)) .Times(AtLeast(kMinNumSamples)) .WillOnce( @@ -840,7 +814,7 @@ const ModelTypeSet types(THEMES); TimeDelta poll(TimeDelta::FromMilliseconds(20)); TimeDelta throttle(TimeDelta::FromMinutes(10)); - scheduler()->OnReceivedLongPollIntervalUpdate(poll); + scheduler()->OnReceivedPollIntervalUpdate(poll); EXPECT_CALL(*syncer(), ConfigureSyncShare(_, _, _)) .WillOnce(DoAll(WithArg<2>(test_util::SimulateThrottled(throttle)), @@ -867,7 +841,7 @@ SyncShareTimes times; TimeDelta poll(TimeDelta::FromMilliseconds(15)); TimeDelta throttle1(TimeDelta::FromMilliseconds(150)); - scheduler()->OnReceivedLongPollIntervalUpdate(poll); + scheduler()->OnReceivedPollIntervalUpdate(poll); ::testing::InSequence seq; EXPECT_CALL(*syncer(), PollSyncShare(_, _)) @@ -893,7 +867,7 @@ SyncShareTimes times; TimeDelta poll(TimeDelta::FromDays(1)); TimeDelta throttle1(TimeDelta::FromMilliseconds(150)); - scheduler()->OnReceivedLongPollIntervalUpdate(poll); + scheduler()->OnReceivedPollIntervalUpdate(poll); ::testing::InSequence seq; EXPECT_CALL(*syncer(), NormalSyncShare(_, _, _)) @@ -921,7 +895,7 @@ SyncShareTimes times; TimeDelta poll(TimeDelta::FromDays(1)); TimeDelta throttle1(TimeDelta::FromMilliseconds(150)); - scheduler()->OnReceivedLongPollIntervalUpdate(poll); + scheduler()->OnReceivedPollIntervalUpdate(poll); ::testing::InSequence seq; EXPECT_CALL(*syncer(), ConfigureSyncShare(_, _, _)) @@ -953,7 +927,7 @@ TEST_F(SyncSchedulerImplTest, TypeThrottlingBlocksNudge) { TimeDelta poll(TimeDelta::FromDays(1)); TimeDelta throttle1(TimeDelta::FromSeconds(60)); - scheduler()->OnReceivedLongPollIntervalUpdate(poll); + scheduler()->OnReceivedPollIntervalUpdate(poll); const ModelTypeSet types(THEMES); @@ -984,7 +958,7 @@ EXPECT_CALL(*delay(), GetDelay(_)).WillRepeatedly(Return(long_delay())); TimeDelta poll(TimeDelta::FromDays(1)); - scheduler()->OnReceivedLongPollIntervalUpdate(poll); + scheduler()->OnReceivedPollIntervalUpdate(poll); const ModelTypeSet types(THEMES); @@ -1014,7 +988,7 @@ EXPECT_CALL(*delay(), GetDelay(_)).WillRepeatedly(Return(default_delay())); TimeDelta poll(TimeDelta::FromDays(1)); - scheduler()->OnReceivedLongPollIntervalUpdate(poll); + scheduler()->OnReceivedPollIntervalUpdate(poll); const ModelTypeSet types(THEMES); @@ -1050,7 +1024,7 @@ EXPECT_CALL(*delay(), GetDelay(_)).WillRepeatedly(Return(long_delay())); TimeDelta poll(TimeDelta::FromDays(1)); - scheduler()->OnReceivedLongPollIntervalUpdate(poll); + scheduler()->OnReceivedPollIntervalUpdate(poll); const ModelTypeSet types(THEMES); @@ -1106,7 +1080,7 @@ TimeDelta poll(TimeDelta::FromDays(1)); TimeDelta throttle(TimeDelta::FromSeconds(60)); - scheduler()->OnReceivedLongPollIntervalUpdate(poll); + scheduler()->OnReceivedPollIntervalUpdate(poll); const ModelTypeSet throttled_types(THEMES); @@ -1157,7 +1131,7 @@ SyncShareTimes times; TimeDelta poll(TimeDelta::FromDays(1)); TimeDelta throttle1(TimeDelta::FromSeconds(60)); - scheduler()->OnReceivedLongPollIntervalUpdate(poll); + scheduler()->OnReceivedPollIntervalUpdate(poll); const ModelTypeSet throttled_types(THEMES); const ModelTypeSet unthrottled_types(PREFERENCES); @@ -1205,7 +1179,7 @@ SyncShareTimes times; TimeDelta poll(TimeDelta::FromDays(1)); - scheduler()->OnReceivedLongPollIntervalUpdate(poll); + scheduler()->OnReceivedPollIntervalUpdate(poll); const ModelTypeSet backed_off_types(THEMES); const ModelTypeSet unbacked_off_types(PREFERENCES); @@ -1251,7 +1225,7 @@ TEST_F(SyncSchedulerImplTest, ConfigurationMode) { TimeDelta poll(TimeDelta::FromMilliseconds(15)); SyncShareTimes times; - scheduler()->OnReceivedLongPollIntervalUpdate(poll); + scheduler()->OnReceivedPollIntervalUpdate(poll); StartSyncConfiguration(); @@ -1276,7 +1250,7 @@ Mock::VerifyAndClearExpectations(syncer()); // Switch to NORMAL_MODE to ensure NUDGES were properly saved and run. - scheduler()->OnReceivedLongPollIntervalUpdate(TimeDelta::FromDays(1)); + scheduler()->OnReceivedPollIntervalUpdate(TimeDelta::FromDays(1)); SyncShareTimes times2; EXPECT_CALL(*syncer(), NormalSyncShare(_, _, _)) .WillOnce(DoAll(Invoke(test_util::SimulateNormalSuccess), @@ -1369,7 +1343,7 @@ SyncShareTimes times; TimeDelta poll(TimeDelta::FromMilliseconds(10)); const ModelTypeSet types(THEMES); - scheduler()->OnReceivedLongPollIntervalUpdate(poll); + scheduler()->OnReceivedPollIntervalUpdate(poll); UseMockDelayProvider(); EXPECT_CALL(*syncer(), NormalSyncShare(_, _, _)) @@ -1494,7 +1468,7 @@ DoAll(Invoke(test_util::SimulatePollSuccess), RecordSyncShareMultiple(×, kMinNumSamples, true))); const TimeDelta poll(TimeDelta::FromMilliseconds(10)); - scheduler()->OnReceivedLongPollIntervalUpdate(poll); + scheduler()->OnReceivedPollIntervalUpdate(poll); // The new optimal time is now, since the desired poll should have happened // in the past. @@ -1516,7 +1490,7 @@ TEST_F(SyncSchedulerImplTest, TransientPollFailure) { SyncShareTimes times; const TimeDelta poll_interval(TimeDelta::FromMilliseconds(10)); - scheduler()->OnReceivedLongPollIntervalUpdate(poll_interval); + scheduler()->OnReceivedPollIntervalUpdate(poll_interval); UseMockDelayProvider(); // Will cause test failure if backoff is initiated. EXPECT_CALL(*delay(), GetDelay(_)) .WillRepeatedly(Return(TimeDelta::FromMilliseconds(0))); @@ -1674,7 +1648,7 @@ TEST_F(SyncSchedulerImplTest, PollFromCanaryAfterAuthError) { SyncShareTimes times; TimeDelta poll(TimeDelta::FromMilliseconds(15)); - scheduler()->OnReceivedLongPollIntervalUpdate(poll); + scheduler()->OnReceivedPollIntervalUpdate(poll); ::testing::InSequence seq; EXPECT_CALL(*syncer(), PollSyncShare(_, _)) @@ -1785,7 +1759,7 @@ TEST_F(SyncSchedulerImplTest, PartialFailureWillExponentialBackoff) { TimeDelta poll(TimeDelta::FromDays(1)); - scheduler()->OnReceivedLongPollIntervalUpdate(poll); + scheduler()->OnReceivedPollIntervalUpdate(poll); const ModelTypeSet types(THEMES); @@ -1830,7 +1804,7 @@ EXPECT_CALL(*delay(), GetDelay(_)).WillRepeatedly(Return(long_delay())); TimeDelta poll(TimeDelta::FromDays(1)); - scheduler()->OnReceivedLongPollIntervalUpdate(poll); + scheduler()->OnReceivedPollIntervalUpdate(poll); const ModelTypeSet types(THEMES); @@ -1880,7 +1854,7 @@ .RetiresOnSaturation(); TimeDelta poll(TimeDelta::FromDays(1)); - scheduler()->OnReceivedLongPollIntervalUpdate(poll); + scheduler()->OnReceivedPollIntervalUpdate(poll); // Set a backoff datatype. const ModelTypeSet themes_types(THEMES); @@ -1947,7 +1921,7 @@ .WillOnce(Return(long_delay())) .RetiresOnSaturation(); TimeDelta poll(TimeDelta::FromDays(1)); - scheduler()->OnReceivedLongPollIntervalUpdate(poll); + scheduler()->OnReceivedPollIntervalUpdate(poll); StartSyncScheduler(base::Time()); scheduler()->ScheduleLocalNudge({THEMES}, FROM_HERE);
diff --git a/components/sync/engine_impl/syncer.cc b/components/sync/engine_impl/syncer.cc index 185e646..91895c6 100644 --- a/components/sync/engine_impl/syncer.cc +++ b/components/sync/engine_impl/syncer.cc
@@ -7,9 +7,11 @@ #include <memory> #include "base/auto_reset.h" +#include "base/command_line.h" #include "base/logging.h" #include "base/trace_event/trace_event.h" #include "components/sync/base/cancelation_signal.h" +#include "components/sync/engine/sync_engine_switches.h" #include "components/sync/engine_impl/apply_control_data_updates.h" #include "components/sync/engine_impl/commit.h" #include "components/sync/engine_impl/commit_processor.h" @@ -45,8 +47,13 @@ SyncCycle* cycle) { base::AutoReset<bool> is_syncing(&is_syncing_, true); HandleCycleBegin(cycle); + // TODO(crbug.com/657130): Sync integration tests depend on the precommit get + // updates because invalidations aren't working for them. Therefore, they pass + // the command line switch to enable this feature. Once sync integrations test + // support invalidation, this should be removed. + base::CommandLine* cl = base::CommandLine::ForCurrentProcess(); if (nudge_tracker->IsGetUpdatesRequired(request_types) || - cycle->context()->ShouldFetchUpdatesBeforeCommit()) { + cl->HasSwitch(switches::kSyncEnableGetUpdatesBeforeCommit)) { VLOG(1) << "Downloading types " << ModelTypeSetToString(request_types); if (!DownloadAndApplyUpdates(&request_types, cycle, NormalGetUpdatesDelegate(*nudge_tracker))) {
diff --git a/components/sync/engine_impl/syncer_proto_util.cc b/components/sync/engine_impl/syncer_proto_util.cc index ceb4ea9d..db55ed5 100644 --- a/components/sync/engine_impl/syncer_proto_util.cc +++ b/components/sync/engine_impl/syncer_proto_util.cc
@@ -489,27 +489,14 @@ command.max_commit_batch_size()); } - if (command.has_set_sync_long_poll_interval()) { - base::TimeDelta interval = - base::TimeDelta::FromSeconds(command.set_sync_long_poll_interval()); - if (interval.is_zero()) { - DLOG(WARNING) - << "Received zero long poll interval from server. Ignoring."; - } else { - cycle->context()->set_long_poll_interval(interval); - cycle->delegate()->OnReceivedLongPollIntervalUpdate(interval); - } - } - if (command.has_set_sync_poll_interval()) { base::TimeDelta interval = base::TimeDelta::FromSeconds(command.set_sync_poll_interval()); if (interval.is_zero()) { - DLOG(WARNING) - << "Received zero short poll interval from server. Ignoring."; + DLOG(WARNING) << "Received zero poll interval from server. Ignoring."; } else { - cycle->context()->set_short_poll_interval(interval); - cycle->delegate()->OnReceivedShortPollIntervalUpdate(interval); + cycle->context()->set_poll_interval(interval); + cycle->delegate()->OnReceivedPollIntervalUpdate(interval); } }
diff --git a/components/sync/engine_impl/syncer_unittest.cc b/components/sync/engine_impl/syncer_unittest.cc index fcdd07a..4635571 100644 --- a/components/sync/engine_impl/syncer_unittest.cc +++ b/components/sync/engine_impl/syncer_unittest.cc
@@ -191,13 +191,9 @@ scheduler_->OnTypesBackedOff(types); } bool IsAnyThrottleOrBackoff() override { return false; } - void OnReceivedLongPollIntervalUpdate( + void OnReceivedPollIntervalUpdate( const base::TimeDelta& new_interval) override { - last_long_poll_interval_received_ = new_interval; - } - void OnReceivedShortPollIntervalUpdate( - const base::TimeDelta& new_interval) override { - last_short_poll_interval_received_ = new_interval; + last_poll_interval_received_ = new_interval; } void OnReceivedCustomNudgeDelays( const std::map<ModelType, base::TimeDelta>& delay_map) override { @@ -283,11 +279,9 @@ context_ = std::make_unique<SyncCycleContext>( mock_server_.get(), directory(), extensions_activity_.get(), listeners, debug_info_getter_.get(), model_type_registry_.get(), - true, // enable keystore encryption - false, // force enable pre-commit GU avoidance experiment + true, // enable keystore encryption "fake_invalidator_client_id", - /*short_poll_interval=*/base::TimeDelta::FromMinutes(30), - /*long_poll_interval=*/base::TimeDelta::FromMinutes(180)); + /*poll_interval=*/base::TimeDelta::FromMinutes(30)); syncer_ = new Syncer(&cancelation_signal_); scheduler_ = std::make_unique<SyncSchedulerImpl>( "TestSyncScheduler", BackoffDelayProvider::FromDefaults(), @@ -519,11 +513,9 @@ // GetUpdates prior to Commit. This method can be used to ensure a Commit is // not preceeded by GetUpdates. void ConfigureNoGetUpdatesRequired() { - context_->set_server_enabled_pre_commit_update_avoidance(true); nudge_tracker_.OnInvalidationsEnabled(); nudge_tracker_.RecordSuccessfulSyncCycle(ProtocolTypes()); - ASSERT_FALSE(context_->ShouldFetchUpdatesBeforeCommit()); ASSERT_FALSE(nudge_tracker_.IsGetUpdatesRequired(ProtocolTypes())); } @@ -553,8 +545,7 @@ std::unique_ptr<ModelTypeRegistry> model_type_registry_; std::unique_ptr<SyncSchedulerImpl> scheduler_; std::unique_ptr<SyncCycleContext> context_; - base::TimeDelta last_short_poll_interval_received_; - base::TimeDelta last_long_poll_interval_received_; + base::TimeDelta last_poll_interval_received_; base::TimeDelta last_sessions_commit_delay_; base::TimeDelta last_bookmarks_commit_delay_; int last_client_invalidation_hint_buffer_size_; @@ -3979,8 +3970,7 @@ mock_server_->SetGUClientCommand(std::move(command)); EXPECT_TRUE(SyncShareNudge()); - EXPECT_EQ(TimeDelta::FromSeconds(8), last_short_poll_interval_received_); - EXPECT_EQ(TimeDelta::FromSeconds(800), last_long_poll_interval_received_); + EXPECT_EQ(TimeDelta::FromSeconds(8), last_poll_interval_received_); EXPECT_EQ(TimeDelta::FromSeconds(3141), last_sessions_commit_delay_); EXPECT_EQ(TimeDelta::FromMilliseconds(950), last_bookmarks_commit_delay_); EXPECT_EQ(11, last_client_invalidation_hint_buffer_size_); @@ -3999,8 +3989,7 @@ mock_server_->SetGUClientCommand(std::move(command)); EXPECT_TRUE(SyncShareNudge()); - EXPECT_EQ(TimeDelta::FromSeconds(180), last_short_poll_interval_received_); - EXPECT_EQ(TimeDelta::FromSeconds(190), last_long_poll_interval_received_); + EXPECT_EQ(TimeDelta::FromSeconds(180), last_poll_interval_received_); EXPECT_EQ(TimeDelta::FromSeconds(2718), last_sessions_commit_delay_); EXPECT_EQ(TimeDelta::FromMilliseconds(1050), last_bookmarks_commit_delay_); EXPECT_EQ(9, last_client_invalidation_hint_buffer_size_); @@ -4023,8 +4012,7 @@ mock_server_->SetCommitClientCommand(std::move(command)); EXPECT_TRUE(SyncShareNudge()); - EXPECT_EQ(TimeDelta::FromSeconds(8), last_short_poll_interval_received_); - EXPECT_EQ(TimeDelta::FromSeconds(800), last_long_poll_interval_received_); + EXPECT_EQ(TimeDelta::FromSeconds(8), last_poll_interval_received_); EXPECT_EQ(TimeDelta::FromSeconds(3141), last_sessions_commit_delay_); EXPECT_EQ(TimeDelta::FromMilliseconds(950), last_bookmarks_commit_delay_); EXPECT_EQ(11, last_client_invalidation_hint_buffer_size_); @@ -4042,8 +4030,7 @@ mock_server_->SetCommitClientCommand(std::move(command)); EXPECT_TRUE(SyncShareNudge()); - EXPECT_EQ(TimeDelta::FromSeconds(180), last_short_poll_interval_received_); - EXPECT_EQ(TimeDelta::FromSeconds(190), last_long_poll_interval_received_); + EXPECT_EQ(TimeDelta::FromSeconds(180), last_poll_interval_received_); EXPECT_EQ(TimeDelta::FromSeconds(2718), last_sessions_commit_delay_); EXPECT_EQ(TimeDelta::FromMilliseconds(1050), last_bookmarks_commit_delay_); EXPECT_EQ(9, last_client_invalidation_hint_buffer_size_);
diff --git a/components/sync/protocol/client_commands.proto b/components/sync/protocol/client_commands.proto index dd428f5..e0c0169 100644 --- a/components/sync/protocol/client_commands.proto +++ b/components/sync/protocol/client_commands.proto
@@ -21,7 +21,8 @@ message ClientCommand { // Time to wait before sending any requests to the server. optional int32 set_sync_poll_interval = 1; // in seconds - optional int32 set_sync_long_poll_interval = 2; // in seconds + // This has been deprecated since M75. + optional int32 set_sync_long_poll_interval = 2 [deprecated = true]; optional int32 max_commit_batch_size = 3;
diff --git a/components/sync/protocol/proto_visitors.h b/components/sync/protocol/proto_visitors.h index 14d3936..b518707b 100644 --- a/components/sync/protocol/proto_visitors.h +++ b/components/sync/protocol/proto_visitors.h
@@ -209,7 +209,6 @@ VISIT_PROTO_FIELDS(const sync_pb::ClientCommand& proto) { VISIT(set_sync_poll_interval); - VISIT(set_sync_long_poll_interval); VISIT(max_commit_batch_size); VISIT(sessions_commit_delay_seconds); VISIT(throttle_delay_seconds);
diff --git a/components/sync/protocol/sync_protocol_error.cc b/components/sync/protocol/sync_protocol_error.cc index 9aceb78..ea9781b 100644 --- a/components/sync/protocol/sync_protocol_error.cc +++ b/components/sync/protocol/sync_protocol_error.cc
@@ -22,7 +22,6 @@ ENUM_CASE(CLEAR_PENDING); ENUM_CASE(TRANSIENT_ERROR); ENUM_CASE(MIGRATION_DONE); - ENUM_CASE(INVALID_CREDENTIAL); ENUM_CASE(DISABLED_BY_ADMIN); ENUM_CASE(PARTIAL_FAILURE); ENUM_CASE(CLIENT_DATA_OBSOLETE); @@ -35,9 +34,6 @@ const char* GetClientActionString(ClientAction action) { switch (action) { ENUM_CASE(UPGRADE_CLIENT); - ENUM_CASE(CLEAR_USER_DATA_AND_RESYNC); - ENUM_CASE(ENABLE_SYNC_ON_ACCOUNT); - ENUM_CASE(STOP_AND_RESTART_SYNC); ENUM_CASE(DISABLE_SYNC_ON_CLIENT); ENUM_CASE(STOP_SYNC_FOR_DISABLED_ACCOUNT); ENUM_CASE(RESET_LOCAL_SYNC_DATA);
diff --git a/components/sync/protocol/sync_protocol_error.h b/components/sync/protocol/sync_protocol_error.h index c76efb1c..6f4acf0 100644 --- a/components/sync/protocol/sync_protocol_error.h +++ b/components/sync/protocol/sync_protocol_error.h
@@ -32,9 +32,6 @@ // them to get the latest progress markers. MIGRATION_DONE, - // Invalid Credential. - INVALID_CREDENTIAL, - // An administrator disabled sync for this domain. DISABLED_BY_ADMIN, @@ -56,15 +53,6 @@ // Upgrade the client to latest version. UPGRADE_CLIENT, - // Clear user data and setup sync again. - CLEAR_USER_DATA_AND_RESYNC, - - // Set the bit on the account to enable sync. - ENABLE_SYNC_ON_ACCOUNT, - - // Stop sync and restart sync. - STOP_AND_RESTART_SYNC, - // Wipe this client of any sync data. DISABLE_SYNC_ON_CLIENT,
diff --git a/components/sync/test/engine/fake_sync_scheduler.cc b/components/sync/test/engine/fake_sync_scheduler.cc index 3a8a00eb..efb3bb26 100644 --- a/components/sync/test/engine/fake_sync_scheduler.cc +++ b/components/sync/test/engine/fake_sync_scheduler.cc
@@ -53,10 +53,7 @@ return false; } -void FakeSyncScheduler::OnReceivedShortPollIntervalUpdate( - const base::TimeDelta& new_interval) {} - -void FakeSyncScheduler::OnReceivedLongPollIntervalUpdate( +void FakeSyncScheduler::OnReceivedPollIntervalUpdate( const base::TimeDelta& new_interval) {} void FakeSyncScheduler::OnReceivedCustomNudgeDelays(
diff --git a/components/sync/test/engine/fake_sync_scheduler.h b/components/sync/test/engine/fake_sync_scheduler.h index e876fc9..e2336dd9 100644 --- a/components/sync/test/engine/fake_sync_scheduler.h +++ b/components/sync/test/engine/fake_sync_scheduler.h
@@ -45,9 +45,7 @@ const base::TimeDelta& throttle_duration) override; void OnTypesBackedOff(ModelTypeSet types) override; bool IsAnyThrottleOrBackoff() override; - void OnReceivedShortPollIntervalUpdate( - const base::TimeDelta& new_interval) override; - void OnReceivedLongPollIntervalUpdate( + void OnReceivedPollIntervalUpdate( const base::TimeDelta& new_interval) override; void OnReceivedCustomNudgeDelays( const std::map<ModelType, base::TimeDelta>& nudge_delays) override;
diff --git a/components/viz/common/features.cc b/components/viz/common/features.cc index 52fe758..344c66d 100644 --- a/components/viz/common/features.cc +++ b/components/viz/common/features.cc
@@ -94,10 +94,24 @@ } bool IsUsingSkiaRenderer() { + // We require OOP-D everywhere but WebView. +#if !defined(OS_ANDROID) + if (!IsVizDisplayCompositorEnabled()) { + DLOG(ERROR) << "UseSkiaRenderer requires VizDisplayCompositor."; + return false; + } +#endif // !defined(OS_ANDROID) return base::FeatureList::IsEnabled(kUseSkiaRenderer); } bool IsUsingSkiaRendererNonDDL() { + // We require OOP-D everywhere but WebView. +#if !defined(OS_ANDROID) + if (!IsVizDisplayCompositorEnabled()) { + DLOG(ERROR) << "UseSkiaRendererNonDDL requires VizDisplayCompositor."; + return false; + } +#endif // !defined(OS_ANDROID) return base::FeatureList::IsEnabled(kUseSkiaRendererNonDDL); }
diff --git a/components/viz/service/display/skia_renderer.cc b/components/viz/service/display/skia_renderer.cc index 490ef4e..aa0f9661 100644 --- a/components/viz/service/display/skia_renderer.cc +++ b/components/viz/service/display/skia_renderer.cc
@@ -156,22 +156,16 @@ const size_t number_of_textures = (is_i420 ? 3 : 2) + (has_alpha ? 1 : 0); std::vector<ResourceMetadata> metadatas; metadatas.reserve(number_of_textures); - // metadata.size is overridden because it is always the same size for - // all planes. Trust the size in |quad| instead. See - // https://crbug.com/939362 auto y_metadata = skia_renderer->lock_set_for_external_use_->LockResource( quad->y_plane_resource_id()); - y_metadata.size = quad->ya_tex_size; metadatas.push_back(std::move(y_metadata)); auto u_metadata = skia_renderer->lock_set_for_external_use_->LockResource( quad->u_plane_resource_id()); - u_metadata.size = quad->uv_tex_size; metadatas.push_back(std::move(u_metadata)); if (is_i420) { auto v_metadata = skia_renderer->lock_set_for_external_use_->LockResource( quad->v_plane_resource_id()); - v_metadata.size = quad->uv_tex_size; metadatas.push_back(std::move(v_metadata)); } @@ -179,7 +173,6 @@ auto a_metadata = skia_renderer->lock_set_for_external_use_->LockResource( quad->a_plane_resource_id()); - a_metadata.size = quad->ya_tex_size; metadatas.push_back(std::move(a_metadata)); }
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 a85a1175..46001b6 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
@@ -175,7 +175,7 @@ void SkiaOutputSurfaceImplTest::SetUpSkiaOutputSurfaceImpl() { // SkiaOutputSurfaceImplOnGpu requires UseSkiaRenderer. - const char enable_features[] = "UseSkiaRenderer"; + const char enable_features[] = "VizDisplayCompositor,UseSkiaRenderer"; const char disable_features[] = ""; scoped_feature_list_ = std::make_unique<base::test::ScopedFeatureList>(); scoped_feature_list_->InitFromCommandLine(enable_features, disable_features);
diff --git a/content/browser/accessibility/accessibility_auralinux_browsertest.cc b/content/browser/accessibility/accessibility_auralinux_browsertest.cc index 2e9faef..6ea470f 100644 --- a/content/browser/accessibility/accessibility_auralinux_browsertest.cc +++ b/content/browser/accessibility/accessibility_auralinux_browsertest.cc
@@ -10,6 +10,7 @@ #include <atk/atk.h> +#include "base/bind_helpers.h" #include "base/macros.h" #include "content/browser/accessibility/browser_accessibility.h" #include "content/browser/renderer_host/render_widget_host_view_aura.h" @@ -76,7 +77,7 @@ void AccessibilityAuraLinuxBrowserTest::ExecuteScript( const std::string& script) { shell()->web_contents()->GetMainFrame()->ExecuteJavaScriptForTests( - base::UTF8ToUTF16(script)); + base::UTF8ToUTF16(script), base::NullCallback()); } void AccessibilityAuraLinuxBrowserTest::LoadInitialAccessibilityTreeFromHtml(
diff --git a/content/browser/accessibility/accessibility_event_recorder_auralinux.cc b/content/browser/accessibility/accessibility_event_recorder_auralinux.cc index 2d5cbad..0f9bb21d 100644 --- a/content/browser/accessibility/accessibility_event_recorder_auralinux.cc +++ b/content/browser/accessibility/accessibility_event_recorder_auralinux.cc
@@ -196,12 +196,17 @@ AtkPropertyValues* property_values = static_cast<AtkPropertyValues*>(g_value_get_pointer(¶ms[1])); - if (g_strcmp0(property_values->property_name, "accessible-value")) + if (g_strcmp0(property_values->property_name, "accessible-value") == 0) { + log += "VALUE-CHANGED:"; + log += + base::NumberToString(g_value_get_double(&property_values->new_value)); + } else if (g_strcmp0(property_values->property_name, "accessible-name") == + 0) { + log += "NAME-CHANGED:"; + log += g_value_get_string(&property_values->new_value); + } else { return; - - log += "VALUE-CHANGED:"; - log += - base::NumberToString(g_value_get_double(&property_values->new_value)); + } } else { log += base::ToUpperASCII(event); if (std::string(event).find("state-change") != std::string::npos) {
diff --git a/content/browser/accessibility/accessibility_win_browsertest.cc b/content/browser/accessibility/accessibility_win_browsertest.cc index 641907b..9814367 100644 --- a/content/browser/accessibility/accessibility_win_browsertest.cc +++ b/content/browser/accessibility/accessibility_win_browsertest.cc
@@ -11,6 +11,7 @@ #include <vector> #include "base/bind.h" +#include "base/bind_helpers.h" #include "base/macros.h" #include "base/process/process_handle.h" #include "base/strings/pattern.h" @@ -172,7 +173,8 @@ } void AccessibilityWinBrowserTest::ExecuteScript(const std::wstring& script) { - shell()->web_contents()->GetMainFrame()->ExecuteJavaScriptForTests(script); + shell()->web_contents()->GetMainFrame()->ExecuteJavaScriptForTests( + script, base::NullCallback()); } // Loads a page with an input text field and places sample text in it. Also,
diff --git a/content/browser/accessibility/browser_accessibility_manager_auralinux.cc b/content/browser/accessibility/browser_accessibility_manager_auralinux.cc index 8b623f1a..d93d95a3 100644 --- a/content/browser/accessibility/browser_accessibility_manager_auralinux.cc +++ b/content/browser/accessibility/browser_accessibility_manager_auralinux.cc
@@ -109,6 +109,11 @@ // Need to implement. } +void BrowserAccessibilityManagerAuraLinux::FireNameChangedEvent( + BrowserAccessibility* node) { + ToBrowserAccessibilityAuraLinux(node)->GetNode()->OnNameChanged(); +} + void BrowserAccessibilityManagerAuraLinux::FireGeneratedEvent( ui::AXEventGenerator::Event event_type, BrowserAccessibility* node) { @@ -140,6 +145,9 @@ case ui::AXEventGenerator::Event::VALUE_CHANGED: FireEvent(node, ax::mojom::Event::kValueChanged); break; + case ui::AXEventGenerator::Event::NAME_CHANGED: + FireNameChangedEvent(node); + break; default: // Need to implement. break;
diff --git a/content/browser/accessibility/browser_accessibility_manager_auralinux.h b/content/browser/accessibility/browser_accessibility_manager_auralinux.h index 47589ce..c0a2915a 100644 --- a/content/browser/accessibility/browser_accessibility_manager_auralinux.h +++ b/content/browser/accessibility/browser_accessibility_manager_auralinux.h
@@ -36,6 +36,7 @@ void FireSelectedEvent(BrowserAccessibility* node); void FireExpandedEvent(BrowserAccessibility* node, bool is_expanded); void FireLoadingEvent(BrowserAccessibility* node, bool is_loading); + void FireNameChangedEvent(BrowserAccessibility* node); protected: // AXTreeObserver methods.
diff --git a/content/browser/accessibility/dump_accessibility_events_browsertest.cc b/content/browser/accessibility/dump_accessibility_events_browsertest.cc index 6e16a02..719330a 100644 --- a/content/browser/accessibility/dump_accessibility_events_browsertest.cc +++ b/content/browser/accessibility/dump_accessibility_events_browsertest.cc
@@ -8,6 +8,7 @@ #include <string> #include <vector> +#include "base/bind_helpers.h" #include "base/path_service.h" #include "base/strings/string16.h" #include "base/strings/string_util.h" @@ -123,7 +124,7 @@ shell()->web_contents(), ui::kAXModeComplete, ax::mojom::Event::kNone)); web_contents->GetMainFrame()->ExecuteJavaScriptForTests( - base::ASCIIToUTF16("go()")); + base::ASCIIToUTF16("go()"), base::NullCallback()); for (;;) { waiter->WaitForNotification(); // Run at least once.
diff --git a/content/browser/browsing_data/browsing_data_remover_impl_unittest.cc b/content/browser/browsing_data/browsing_data_remover_impl_unittest.cc index 15553c4..c229f43 100644 --- a/content/browser/browsing_data/browsing_data_remover_impl_unittest.cc +++ b/content/browser/browsing_data/browsing_data_remover_impl_unittest.cc
@@ -62,7 +62,6 @@ #include "url/origin.h" #if BUILDFLAG(ENABLE_REPORTING) -#include "net/network_error_logging/network_error_logging_delegate.h" #include "net/network_error_logging/network_error_logging_service.h" #include "net/reporting/reporting_cache.h" #include "net/reporting/reporting_report.h" @@ -1517,8 +1516,7 @@ TEST_F(BrowsingDataRemoverImplTest, RemoveNetworkErrorLogging) { std::unique_ptr<net::NetworkErrorLoggingService> logging_service = - net::NetworkErrorLoggingService::Create( - net::NetworkErrorLoggingDelegate::Create()); + net::NetworkErrorLoggingService::Create(); BrowserContext::GetDefaultStoragePartition(GetBrowserContext()) ->GetURLRequestContext() ->GetURLRequestContext() @@ -1539,8 +1537,7 @@ TEST_F(BrowsingDataRemoverImplTest, RemoveNetworkErrorLogging_SpecificOrigins) { std::unique_ptr<net::NetworkErrorLoggingService> logging_service = - net::NetworkErrorLoggingService::Create( - net::NetworkErrorLoggingDelegate::Create()); + net::NetworkErrorLoggingService::Create(); BrowserContext::GetDefaultStoragePartition(GetBrowserContext()) ->GetURLRequestContext() ->GetURLRequestContext()
diff --git a/content/browser/dom_storage/session_storage_area_impl_unittest.cc b/content/browser/dom_storage/session_storage_area_impl_unittest.cc index 2dfce995..3b1552fa 100644 --- a/content/browser/dom_storage/session_storage_area_impl_unittest.cc +++ b/content/browser/dom_storage/session_storage_area_impl_unittest.cc
@@ -71,7 +71,8 @@ auto file_runner = base::CreateSequencedTaskRunnerWithTraits({base::MayBlock()}); CreateStrongBindingOnTaskRunner( - base::CreateSequencedTaskRunnerWithTraits({}), &leveldb_service_, + base::CreateSequencedTaskRunnerWithTraits({base::MayBlock()}), + &leveldb_service_, std::make_unique<leveldb::LevelDBServiceImpl>(std::move(file_runner))); leveldb_service_->OpenInMemory(
diff --git a/content/browser/frame_host/navigation_controller_impl_browsertest.cc b/content/browser/frame_host/navigation_controller_impl_browsertest.cc index af81884..de46b31 100644 --- a/content/browser/frame_host/navigation_controller_impl_browsertest.cc +++ b/content/browser/frame_host/navigation_controller_impl_browsertest.cc
@@ -10,6 +10,7 @@ #include <vector> #include "base/bind.h" +#include "base/bind_helpers.h" #include "base/command_line.h" #include "base/files/scoped_temp_dir.h" #include "base/macros.h" @@ -7234,10 +7235,11 @@ // ExecJs() sets a user gesture flag internally for testing, but we // want to run JavaScript without the flag. Call ExecuteJavaScriptForTests - // directory. + // directly. static_cast<WebContentsImpl*>(web_contents) ->GetMainFrame() - ->ExecuteJavaScriptForTests(base::UTF8ToUTF16(script)); + ->ExecuteJavaScriptForTests(base::UTF8ToUTF16(script), + base::NullCallback()); observer.Wait(); }
diff --git a/content/browser/frame_host/navigation_controller_impl_unittest.cc b/content/browser/frame_host/navigation_controller_impl_unittest.cc index 20145db..4a0724d 100644 --- a/content/browser/frame_host/navigation_controller_impl_unittest.cc +++ b/content/browser/frame_host/navigation_controller_impl_unittest.cc
@@ -554,24 +554,12 @@ const GURL url1("http://foo1"); const GURL url2("http://foo2"); - controller.LoadURL( - url1, Referrer(), ui::PAGE_TRANSITION_TYPED, std::string()); - int entry_id = controller.GetPendingEntry()->GetUniqueID(); - - main_test_rfh()->PrepareForCommit(); - main_test_rfh()->SendNavigate(entry_id, true, url1); + NavigationSimulator::NavigateAndCommitFromBrowser(contents(), url1); EXPECT_EQ(1U, navigation_entry_committed_counter_); navigation_entry_committed_counter_ = 0; // Load another... - controller.LoadURL( - url2, Referrer(), ui::PAGE_TRANSITION_TYPED, std::string()); - entry_id = controller.GetPendingEntry()->GetUniqueID(); - - // Simulate the beforeunload ack for the cross-site transition, and then the - // commit. - main_test_rfh()->PrepareForCommit(); - contents()->GetPendingMainFrame()->SendNavigate(entry_id, true, url2); + NavigationSimulator::NavigateAndCommitFromBrowser(contents(), url2); EXPECT_EQ(1U, navigation_entry_committed_counter_); navigation_entry_committed_counter_ = 0; @@ -845,13 +833,12 @@ const GURL url1("http://foo1"); const GURL url2("http://foo2"); - controller.LoadURL( - url1, Referrer(), ui::PAGE_TRANSITION_TYPED, std::string()); - int entry_id = controller.GetPendingEntry()->GetUniqueID(); + auto navigation = + NavigationSimulator::CreateBrowserInitiated(url1, contents()); + navigation->Start(); EXPECT_EQ(0U, navigation_entry_changed_counter_); EXPECT_EQ(0U, navigation_list_pruned_counter_); - main_test_rfh()->PrepareForCommit(); - main_test_rfh()->SendNavigate(entry_id, true, url1); + navigation->Commit(); EXPECT_EQ(1U, navigation_entry_committed_counter_); navigation_entry_committed_counter_ = 0; @@ -886,11 +873,7 @@ // First make an existing committed entry. const GURL kExistingURL1("http://eh"); - controller.LoadURL( - kExistingURL1, Referrer(), ui::PAGE_TRANSITION_TYPED, std::string()); - int entry_id = controller.GetPendingEntry()->GetUniqueID(); - main_test_rfh()->PrepareForCommit(); - main_test_rfh()->SendNavigate(entry_id, true, kExistingURL1); + NavigationSimulator::NavigateAndCommitFromBrowser(contents(), kExistingURL1); EXPECT_EQ(1U, navigation_entry_committed_counter_); navigation_entry_committed_counter_ = 0; @@ -916,23 +899,20 @@ // First make an existing committed entry. const GURL kExistingURL1("http://eh"); - controller.LoadURL( - kExistingURL1, Referrer(), ui::PAGE_TRANSITION_TYPED, std::string()); - int entry_id = controller.GetPendingEntry()->GetUniqueID(); - main_test_rfh()->PrepareForCommit(); - main_test_rfh()->SendNavigate(entry_id, true, kExistingURL1); + NavigationSimulator::NavigateAndCommitFromBrowser(contents(), kExistingURL1); EXPECT_EQ(1U, navigation_entry_committed_counter_); navigation_entry_committed_counter_ = 0; // Make a pending entry to somewhere new. const GURL kExistingURL2("http://bee"); - controller.LoadURL( - kExistingURL2, Referrer(), ui::PAGE_TRANSITION_TYPED, std::string()); + auto navigation = + NavigationSimulator::CreateBrowserInitiated(kExistingURL2, contents()); + navigation->Start(); EXPECT_EQ(0U, navigation_entry_changed_counter_); EXPECT_EQ(0U, navigation_list_pruned_counter_); // After the beforeunload but before it commits... - main_test_rfh()->PrepareForCommit(); + navigation->ReadyToCommit(); // ... Do a new navigation. const GURL kNewURL("http://see"); @@ -1058,39 +1038,32 @@ // First make some history. const GURL kExistingURL1("http://foo/eh"); - controller.LoadURL( - kExistingURL1, Referrer(), ui::PAGE_TRANSITION_TYPED, std::string()); - int entry_id = controller.GetPendingEntry()->GetUniqueID(); - main_test_rfh()->PrepareForCommit(); - main_test_rfh()->SendNavigate(entry_id, true, kExistingURL1); + NavigationSimulator::NavigateAndCommitFromBrowser(contents(), kExistingURL1); EXPECT_EQ(1U, navigation_entry_committed_counter_); navigation_entry_committed_counter_ = 0; const GURL kExistingURL2("http://foo/bee"); - controller.LoadURL( - kExistingURL2, Referrer(), ui::PAGE_TRANSITION_TYPED, std::string()); - entry_id = controller.GetPendingEntry()->GetUniqueID(); - main_test_rfh()->PrepareForCommit(); - main_test_rfh()->SendNavigate(entry_id, true, kExistingURL2); + NavigationSimulator::NavigateAndCommitFromBrowser(contents(), kExistingURL2); EXPECT_EQ(1U, navigation_entry_committed_counter_); navigation_entry_committed_counter_ = 0; // A back navigation comes in from the renderer... - controller.GoToOffset(-1); - entry_id = controller.GetPendingEntry()->GetUniqueID(); + auto back_navigation = + NavigationSimulator::CreateHistoryNavigation(-1, contents()); + back_navigation->ReadyToCommit(); // ...while the user tries to navigate to a new page... const GURL kNewURL("http://foo/see"); - controller.LoadURL( - kNewURL, Referrer(), ui::PAGE_TRANSITION_TYPED, std::string()); + auto new_navigation = + NavigationSimulator::CreateBrowserInitiated(kNewURL, contents()); + new_navigation->Start(); EXPECT_EQ(0U, navigation_entry_changed_counter_); EXPECT_EQ(0U, navigation_list_pruned_counter_); EXPECT_EQ(-1, controller.GetPendingEntryIndex()); EXPECT_EQ(1, controller.GetLastCommittedEntryIndex()); // ...and the back navigation commits. - main_test_rfh()->PrepareForCommit(); - main_test_rfh()->SendNavigate(entry_id, false, kExistingURL1); + back_navigation->Commit(); // There should no longer be any pending entry, and the back navigation should // be committed. @@ -1203,11 +1176,7 @@ // First make an existing committed entry. const GURL kExistingURL("http://foo/eh"); - controller.LoadURL(kExistingURL, content::Referrer(), - ui::PAGE_TRANSITION_TYPED, std::string()); - int entry_id = controller.GetPendingEntry()->GetUniqueID(); - main_test_rfh()->PrepareForCommit(); - main_test_rfh()->SendNavigate(entry_id, true, kExistingURL); + NavigationSimulator::NavigateAndCommitFromBrowser(contents(), kExistingURL); main_test_rfh()->OnMessageReceived(FrameHostMsg_DidStopLoading(0)); EXPECT_EQ(1U, navigation_entry_committed_counter_); navigation_entry_committed_counter_ = 0; @@ -1326,19 +1295,19 @@ const GURL url1("http://foo1"); - controller.LoadURL( - url1, Referrer(), ui::PAGE_TRANSITION_TYPED, std::string()); - int entry_id = controller.GetPendingEntry()->GetUniqueID(); + auto navigation = NavigationSimulator::CreateBrowserInitiated( + url1, RenderViewHostTestHarness::web_contents()); + navigation->Start(); EXPECT_EQ(0U, navigation_entry_changed_counter_); EXPECT_EQ(0U, navigation_list_pruned_counter_); - main_test_rfh()->PrepareForCommit(); - main_test_rfh()->SendNavigate(entry_id, true, url1); + navigation->Commit(); EXPECT_EQ(1U, navigation_entry_committed_counter_); navigation_entry_committed_counter_ = 0; ASSERT_TRUE(controller.GetVisibleEntry()); - entry_id = controller.GetLastCommittedEntry()->GetUniqueID(); controller.Reload(ReloadType::NORMAL, true); + navigation = NavigationSimulator::CreateFromPending( + RenderViewHostTestHarness::web_contents()); EXPECT_EQ(0U, navigation_entry_changed_counter_); EXPECT_EQ(0U, navigation_list_pruned_counter_); @@ -1354,8 +1323,7 @@ EXPECT_FALSE(controller.CanGoBack()); EXPECT_FALSE(controller.CanGoForward()); - main_test_rfh()->PrepareForCommit(); - main_test_rfh()->SendNavigate(entry_id, false, url1); + navigation->Commit(); EXPECT_EQ(1U, navigation_entry_committed_counter_); navigation_entry_committed_counter_ = 0; @@ -1443,32 +1411,22 @@ EXPECT_EQ(entry1, entry2); } -namespace { -void SetOriginalURL(const GURL& url, - FrameHostMsg_DidCommitProvisionalLoad_Params* params) { - params->original_request_url = url; -} -} - TEST_F(NavigationControllerTest, ReloadOriginalRequestURL) { NavigationControllerImpl& controller = controller_impl(); const GURL original_url("http://foo1"); const GURL final_url("http://foo2"); - auto set_original_url_callback = base::Bind(SetOriginalURL, original_url); // Load up the original URL, but get redirected. - controller.LoadURL( - original_url, Referrer(), ui::PAGE_TRANSITION_TYPED, std::string()); - int entry_id = controller.GetPendingEntry()->GetUniqueID(); + auto navigation = NavigationSimulator::CreateBrowserInitiated( + original_url, RenderViewHostTestHarness::web_contents()); + navigation->Start(); EXPECT_EQ(0U, navigation_entry_changed_counter_); EXPECT_EQ(0U, navigation_list_pruned_counter_); - main_test_rfh()->PrepareForCommitWithServerRedirect(final_url); - main_test_rfh()->SendNavigateWithModificationCallback( - entry_id, true, final_url, std::move(set_original_url_callback)); + navigation->Redirect(final_url); + navigation->Commit(); EXPECT_EQ(1U, navigation_entry_committed_counter_); navigation_entry_committed_counter_ = 0; - entry_id = controller.GetLastCommittedEntry()->GetUniqueID(); // The NavigationEntry should save both the original URL and the final // redirected URL. @@ -1492,8 +1450,10 @@ EXPECT_FALSE(controller.CanGoForward()); // Send that the navigation has proceeded; say it got redirected again. - main_test_rfh()->PrepareForCommitWithServerRedirect(final_url); - main_test_rfh()->SendNavigate(entry_id, false, final_url); + navigation = NavigationSimulator::CreateFromPending( + RenderViewHostTestHarness::web_contents()); + navigation->Redirect(final_url); + navigation->Commit(); EXPECT_EQ(1U, navigation_entry_committed_counter_); navigation_entry_committed_counter_ = 0; @@ -1649,8 +1609,9 @@ EXPECT_EQ(1U, navigation_entry_committed_counter_); navigation_entry_committed_counter_ = 0; - controller.GoBack(); - int entry_id = controller.GetPendingEntry()->GetUniqueID(); + auto back_navigation = + NavigationSimulator::CreateHistoryNavigation(-1, contents()); + back_navigation->Start(); EXPECT_EQ(0U, navigation_entry_changed_counter_); EXPECT_EQ(0U, navigation_list_pruned_counter_); @@ -1671,9 +1632,7 @@ EXPECT_GE(controller.GetEntryAtIndex(1)->GetTimestamp(), controller.GetEntryAtIndex(0)->GetTimestamp()); - TestRenderFrameHost* navigating_rfh = GetNavigatingRenderFrameHost(); - navigating_rfh->PrepareForCommit(); - navigating_rfh->SendNavigate(entry_id, false, url1); + back_navigation->Commit(); EXPECT_EQ(1U, navigation_entry_committed_counter_); navigation_entry_committed_counter_ = 0; @@ -1793,7 +1752,6 @@ navigation_entry_committed_counter_ = 0; NavigationSimulator::NavigateAndCommitFromDocument(url2, main_test_rfh()); - NavigationEntry* entry2 = controller.GetLastCommittedEntry(); EXPECT_EQ(1U, navigation_entry_committed_counter_); navigation_entry_committed_counter_ = 0; @@ -1801,8 +1759,9 @@ EXPECT_EQ(1U, navigation_entry_committed_counter_); navigation_entry_committed_counter_ = 0; - controller.GoForward(); - + auto forward_navigation = + NavigationSimulator::CreateHistoryNavigation(1, contents()); + forward_navigation->Start(); // We should now have a pending navigation to go forward. EXPECT_EQ(controller.GetEntryCount(), 2); EXPECT_EQ(controller.GetLastCommittedEntryIndex(), 0); @@ -1821,11 +1780,7 @@ EXPECT_GE(controller.GetEntryAtIndex(0)->GetTimestamp(), controller.GetEntryAtIndex(1)->GetTimestamp()); - TestRenderFrameHost* navigating_rfh = GetNavigatingRenderFrameHost(); - navigating_rfh->PrepareForCommit(); - navigating_rfh->SendNavigateWithTransition( - entry2->GetUniqueID(), false, url2, - controller.GetPendingEntry()->GetTransitionType()); + forward_navigation->Commit(); EXPECT_EQ(1U, navigation_entry_committed_counter_); navigation_entry_committed_counter_ = 0; @@ -1861,14 +1816,15 @@ NavigationSimulator::NavigateAndCommitFromDocument(url2, main_test_rfh()); EXPECT_EQ(1U, navigation_entry_committed_counter_); - NavigationEntry* entry2 = controller.GetLastCommittedEntry(); navigation_entry_committed_counter_ = 0; NavigationSimulator::GoBack(contents()); EXPECT_EQ(1U, navigation_entry_committed_counter_); navigation_entry_committed_counter_ = 0; - controller.GoForward(); + auto forward_navigation = + NavigationSimulator::CreateHistoryNavigation(1, contents()); + forward_navigation->Start(); EXPECT_EQ(0U, navigation_list_pruned_counter_); // Should now have a pending navigation to go forward. @@ -1880,9 +1836,7 @@ EXPECT_TRUE(controller.CanGoBack()); EXPECT_FALSE(controller.CanGoForward()); - GetNavigatingRenderFrameHost()->PrepareForCommitWithServerRedirect(url3); - GetNavigatingRenderFrameHost()->SendNavigate(entry2->GetUniqueID(), false, - url3); + forward_navigation->Commit(); EXPECT_EQ(1U, navigation_entry_committed_counter_); navigation_entry_committed_counter_ = 0; EXPECT_EQ(0U, navigation_list_pruned_counter_); @@ -2155,20 +2109,11 @@ contents()->GetFrameTree()->root()->child_at(0)->current_frame_host()); const GURL url2("http://foo/2"); { - FrameHostMsg_DidCommitProvisionalLoad_Params params; - params.nav_entry_id = 0; - params.did_create_new_entry = false; - params.url = url2; - params.transition = ui::PAGE_TRANSITION_AUTO_SUBFRAME; - params.should_update_history = false; - params.gesture = NavigationGestureUser; - params.method = "GET"; - params.page_state = PageState::CreateFromURL(url2); - // Navigating should do nothing. - subframe->SendRendererInitiatedNavigationRequest(url2, false); - subframe->PrepareForCommit(); - subframe->SendNavigateWithParams(¶ms, false); + auto subframe_navigation = + NavigationSimulator::CreateRendererInitiated(url2, subframe); + subframe_navigation->SetTransition(ui::PAGE_TRANSITION_AUTO_SUBFRAME); + subframe_navigation->Commit(); // We notify of a PageState update here rather than during UpdateState for // auto subframe navigations. @@ -2203,20 +2148,11 @@ contents()->GetFrameTree()->root()->child_at(1)->current_frame_host()); const GURL url3("http://foo/3"); { - FrameHostMsg_DidCommitProvisionalLoad_Params params; - params.nav_entry_id = 0; - params.did_create_new_entry = false; - params.url = url3; - params.transition = ui::PAGE_TRANSITION_AUTO_SUBFRAME; - params.should_update_history = false; - params.gesture = NavigationGestureUser; - params.method = "GET"; - params.page_state = PageState::CreateFromURL(url3); - // Navigating should do nothing. - subframe2->SendRendererInitiatedNavigationRequest(url3, false); - subframe2->PrepareForCommit(); - subframe2->SendNavigateWithParams(¶ms, false); + auto subframe_navigation = + NavigationSimulator::CreateRendererInitiated(url3, subframe2); + subframe_navigation->SetTransition(ui::PAGE_TRANSITION_AUTO_SUBFRAME); + subframe_navigation->Commit(); // We notify of a PageState update here rather than during UpdateState for // auto subframe navigations. @@ -2256,20 +2192,11 @@ ->current_frame_host()); const GURL url4("http://foo/4"); { - FrameHostMsg_DidCommitProvisionalLoad_Params params; - params.nav_entry_id = 0; - params.did_create_new_entry = false; - params.url = url4; - params.transition = ui::PAGE_TRANSITION_AUTO_SUBFRAME; - params.should_update_history = false; - params.gesture = NavigationGestureUser; - params.method = "GET"; - params.page_state = PageState::CreateFromURL(url4); - // Navigating should do nothing. - subframe3->SendRendererInitiatedNavigationRequest(url4, false); - subframe3->PrepareForCommit(); - subframe3->SendNavigateWithParams(¶ms, false); + auto subframe_navigation = + NavigationSimulator::CreateRendererInitiated(url4, subframe3); + subframe_navigation->SetTransition(ui::PAGE_TRANSITION_AUTO_SUBFRAME); + subframe_navigation->Commit(); // We notify of a PageState update here rather than during UpdateState for // auto subframe navigations. @@ -3523,8 +3450,7 @@ url_with_ref, url::Origin::Create(url_with_ref), true, main_test_rfh())); // Navigate to URL with refs. - NavigationSimulator::NavigateAndCommitFromDocument(url_with_ref, - main_test_rfh()); + NavigationSimulator::NavigateAndCommitFromBrowser(contents(), url_with_ref); // Reloading the page is not a same-document navigation. EXPECT_FALSE(controller.IsURLSameDocumentNavigation( @@ -4625,11 +4551,8 @@ NavigationSimulator::NavigateAndCommitFromDocument(kUrl2, main_test_rfh()); EXPECT_EQ(1U, navigation_entry_committed_counter_); navigation_entry_committed_counter_ = 0; - main_test_rfh()->SendRendererInitiatedNavigationRequest(kUrl1, false); - main_test_rfh()->PrepareForCommit(); - main_test_rfh()->SendNavigateWithTransition( - controller.GetEntryAtIndex(0)->GetUniqueID(), false, kUrl1, - ui::PAGE_TRANSITION_FORWARD_BACK); + + NavigationSimulator::GoBack(contents()); EXPECT_EQ(1U, navigation_entry_committed_counter_); navigation_entry_committed_counter_ = 0; @@ -4902,34 +4825,30 @@ // Test 1. // A normal navigation to initial_url should not be marked as a reload. - controller.LoadURL(initial_url, Referrer(), ui::PAGE_TRANSITION_TYPED, - std::string()); + auto navigation1 = + NavigationSimulator::CreateBrowserInitiated(initial_url, contents()); + navigation1->Start(); EXPECT_EQ(initial_url, controller.GetVisibleEntry()->GetURL()); - main_test_rfh()->SimulateNavigationStart(initial_url); - EXPECT_EQ(initial_url, controller.GetVisibleEntry()->GetURL()); - - main_test_rfh()->SimulateNavigationCommit(initial_url); + navigation1->Commit(); EXPECT_EQ(ReloadType::NONE, last_reload_type_); // Test 2. // A navigation to initial_url with the navigation commit delayed should be // marked as a reload. - controller.LoadURL(initial_url, Referrer(), ui::PAGE_TRANSITION_TYPED, - std::string()); - + auto navigation2 = + NavigationSimulator::CreateBrowserInitiated(initial_url, contents()); + navigation2->Start(); EXPECT_EQ(initial_url, controller.GetVisibleEntry()->GetURL()); - main_test_rfh()->SimulateNavigationStart(initial_url); + navigation2->ReadyToCommit(); EXPECT_EQ(initial_url, controller.GetVisibleEntry()->GetURL()); EXPECT_EQ(ReloadType::NORMAL, last_reload_type_); // Test 3. // A navigation to url_1 while the navigation to intial_url is still pending // should not be marked as a reload. - controller.LoadURL(url_1, Referrer(), ui::PAGE_TRANSITION_TYPED, - std::string()); - - EXPECT_EQ(url_1, controller.GetVisibleEntry()->GetURL()); - main_test_rfh()->SimulateNavigationStart(url_1); + auto navigation3 = + NavigationSimulator::CreateBrowserInitiated(url_1, contents()); + navigation3->Start(); EXPECT_EQ(url_1, controller.GetVisibleEntry()->GetURL()); EXPECT_EQ(ReloadType::NONE, last_reload_type_); @@ -4938,37 +4857,31 @@ // should not be marked as reload. Even though the URL is the same as the // previous navigation, the previous navigation did not commit. We can only // reload navigations that committed. See https://crbug.com/809040. - controller.LoadURL(url_1, Referrer(), ui::PAGE_TRANSITION_TYPED, - std::string()); - - EXPECT_EQ(url_1, controller.GetVisibleEntry()->GetURL()); - main_test_rfh()->SimulateNavigationStart(url_1); + auto navigation4 = + NavigationSimulator::CreateBrowserInitiated(url_1, contents()); + navigation4->Start(); EXPECT_EQ(url_1, controller.GetVisibleEntry()->GetURL()); EXPECT_EQ(ReloadType::NONE, last_reload_type_); - main_test_rfh()->SimulateNavigationCommit(initial_url); + navigation2->Commit(); // Test 5 // A navigation to url_2 followed by a navigation to the previously pending // url_1 should not be marked as a reload. - controller.LoadURL(url_2, Referrer(), ui::PAGE_TRANSITION_TYPED, - std::string()); - EXPECT_EQ(url_2, controller.GetVisibleEntry()->GetURL()); - main_test_rfh()->SimulateNavigationStart(url_2); + auto navigation5 = + NavigationSimulator::CreateBrowserInitiated(url_2, contents()); + navigation5->Start(); EXPECT_EQ(url_2, controller.GetVisibleEntry()->GetURL()); EXPECT_EQ(ReloadType::NONE, last_reload_type_); controller.LoadURL(url_1, Referrer(), ui::PAGE_TRANSITION_TYPED, std::string()); - - EXPECT_EQ(url_1, controller.GetVisibleEntry()->GetURL()); - main_test_rfh()->SimulateNavigationStart(url_1); + auto navigation6 = + NavigationSimulator::CreateBrowserInitiated(url_1, contents()); + navigation6->ReadyToCommit(); EXPECT_EQ(url_1, controller.GetVisibleEntry()->GetURL()); EXPECT_EQ(ReloadType::NONE, last_reload_type_); - - main_test_rfh()->SimulateNavigationCommit(url_2); - main_test_rfh()->SimulateNavigationCommit(url_1); - main_test_rfh()->SimulateNavigationCommit(url_1); + navigation6->Commit(); } // Test to ensure that the pending entry index is updated when a transient entry
diff --git a/content/browser/frame_host/render_frame_host_impl.cc b/content/browser/frame_host/render_frame_host_impl.cc index 584a1aa5..8d479a8 100644 --- a/content/browser/frame_host/render_frame_host_impl.cc +++ b/content/browser/frame_host/render_frame_host_impl.cc
@@ -182,6 +182,7 @@ #include "third_party/blink/public/common/feature_policy/feature_policy.h" #include "third_party/blink/public/common/features.h" #include "third_party/blink/public/common/frame/frame_policy.h" +#include "third_party/blink/public/common/messaging/transferable_message.h" #include "third_party/blink/public/mojom/frame/frame_host_test_interface.mojom.h" #include "third_party/blink/public/mojom/loader/pause_subresource_loading_handle.mojom.h" #include "third_party/blink/public/mojom/loader/url_loader_factory_bundle.mojom.h" @@ -1004,14 +1005,6 @@ return *overlay_routing_token_; } -void RenderFrameHostImpl::DidCommitNavigationForTesting( - NavigationRequest* navigation_request, - std::unique_ptr<FrameHostMsg_DidCommitProvisionalLoad_Params> params, - mojom::DidCommitProvisionalLoadInterfaceParamsPtr interface_params) { - DidCommitNavigation(navigation_request, std::move(params), - std::move(interface_params)); -} - void RenderFrameHostImpl::AudioContextPlaybackStarted(int audio_context_id) { delegate_->AudioContextPlaybackStarted(this, audio_context_id); } @@ -1038,8 +1031,8 @@ child->current_frame_host()->LeaveBackForwardCache(); } -void RenderFrameHostImpl::OnPortalActivated() { - frame_->OnPortalActivated(); +void RenderFrameHostImpl::OnPortalActivated(blink::TransferableMessage data) { + frame_->OnPortalActivated(std::move(data)); } SiteInstanceImpl* RenderFrameHostImpl::GetSiteInstance() { @@ -1194,10 +1187,6 @@ Send(new FrameMsg_AddMessageToConsole(routing_id_, level, message)); } -void RenderFrameHostImpl::ExecuteJavaScript(const base::string16& javascript) { - ExecuteJavaScript(javascript, base::NullCallback()); -} - void RenderFrameHostImpl::ExecuteJavaScript(const base::string16& javascript, JavaScriptResultCallback callback) { DCHECK_CURRENTLY_ON(BrowserThread::UI); @@ -1220,11 +1209,6 @@ } void RenderFrameHostImpl::ExecuteJavaScriptForTests( - const base::string16& javascript) { - ExecuteJavaScriptForTests(javascript, base::NullCallback()); -} - -void RenderFrameHostImpl::ExecuteJavaScriptForTests( const base::string16& javascript, JavaScriptResultCallback callback) { DCHECK_CURRENTLY_ON(BrowserThread::UI); @@ -1365,8 +1349,6 @@ OnDidFailLoadWithError) IPC_MESSAGE_HANDLER(FrameHostMsg_UpdateState, OnUpdateState) IPC_MESSAGE_HANDLER(FrameHostMsg_OpenURL, OnOpenURL) - IPC_MESSAGE_HANDLER(FrameHostMsg_DocumentOnLoadCompleted, - OnDocumentOnLoadCompleted) IPC_MESSAGE_HANDLER(FrameHostMsg_BeforeUnload_ACK, OnBeforeUnloadACK) IPC_MESSAGE_HANDLER(FrameHostMsg_SwapOut_ACK, OnSwapOutACK) IPC_MESSAGE_HANDLER(FrameHostMsg_ContextMenu, OnContextMenu) @@ -2090,7 +2072,7 @@ NOTIMPLEMENTED(); } -void RenderFrameHostImpl::OnDocumentOnLoadCompleted() { +void RenderFrameHostImpl::DocumentOnLoadCompleted() { // This message is only sent for top-level frames. TODO(avi): when frame tree // mirroring works correctly, add a check here to enforce it. delegate_->DocumentOnLoadCompleted(this); @@ -2137,7 +2119,7 @@ mojom::DidCommitProvisionalLoadInterfaceParamsPtr interface_params) { if (MaybeInterceptCommitCallback(nullptr, validated_params.get(), &interface_params)) { - DidCommitNavigation(nullptr /* committing_navigation_request */, + DidCommitNavigation(std::move(navigation_request_), std::move(validated_params), std::move(interface_params)); } @@ -2150,12 +2132,19 @@ mojom::DidCommitProvisionalLoadInterfaceParamsPtr interface_params) { DCHECK(committing_navigation_request); committing_navigation_request->IgnoreCommitInterfaceDisconnection(); - if (MaybeInterceptCommitCallback(committing_navigation_request, - validated_params.get(), &interface_params)) { - DidCommitNavigation(committing_navigation_request, - std::move(validated_params), - std::move(interface_params)); + if (!MaybeInterceptCommitCallback(committing_navigation_request, + validated_params.get(), + &interface_params)) { + return; } + auto request = navigation_requests_.find(committing_navigation_request); + + // The committing request should be in the map of NavigationRequests for + // this RenderFrameHost. + CHECK(request != navigation_requests_.end()); + + DidCommitNavigation(std::move(request->second), std::move(validated_params), + std::move(interface_params)); } void RenderFrameHostImpl::DidCommitSameDocumentNavigation( @@ -2181,13 +2170,14 @@ "RenderFrameHostImpl::DidCommitSameDocumentNavigation", "frame_tree_node", frame_tree_node_->frame_tree_node_id(), "url", validated_params->url.possibly_invalid_spec()); - - // TODO(ahemery): We also create a NavigationRequest for browser initiated - // same document navigations, so implement the passing of this request to - // DidCommitNavigationInternal. - if (!DidCommitNavigationInternal(nullptr /* navigation_request */, - validated_params.get(), - true /* is_same_document_navigation*/)) { + // TODO(clamy): We shouldn't be trusting the renderer to tell us whether this + // was browser-initiated. Use an UnguessableToken to do request matching + // instead of using nav_entry_id. + bool is_browser_initiated = (validated_params->nav_entry_id != 0); + if (!DidCommitNavigationInternal( + is_browser_initiated ? std::move(same_document_navigation_request_) + : nullptr, + validated_params.get(), true /* is_same_document_navigation*/)) { return; } @@ -5756,115 +5746,38 @@ } std::unique_ptr<NavigationRequest> -RenderFrameHostImpl::TakeNavigationRequestForSameDocumentCommit( - const FrameHostMsg_DidCommitProvisionalLoad_Params& params) { - bool is_browser_initiated = (params.nav_entry_id != 0); - - // A NavigationRequest is created for browser-initiated same-document - // navigation. Try to take it if it's still available and matches the - // current navigation. - if (is_browser_initiated && same_document_navigation_request_ && - same_document_navigation_request_->common_params().url == params.url) { - return std::move(same_document_navigation_request_); - } - - // No existing NavigationRequest has been found. Create a new one, but don't - // reset any NavigationRequest tracking an ongoing navigation, since this may - // lead to the cancellation of the navigation. - // First, determine if the navigation corresponds to the pending navigation - // entry. This is the case if the NavigationRequest for a browser-initiated - // same-document navigation was erased due to a race condition. - // TODO(ahemery): Remove when the full mojo interface is in place. - // (https://bugs.chromium.org/p/chromium/issues/detail?id=784904) - bool is_renderer_initiated = true; - NavigationEntryImpl* pending_entry = NavigationEntryImpl::FromNavigationEntry( - frame_tree_node()->navigator()->GetController()->GetPendingEntry()); - if (pending_entry && pending_entry->GetUniqueID() == params.nav_entry_id) { - is_renderer_initiated = pending_entry->is_renderer_initiated(); - } else { - // Don't reuse the pending entry if it doesn't match. - pending_entry = nullptr; - } - +RenderFrameHostImpl::CreateNavigationRequestForCommit( + const FrameHostMsg_DidCommitProvisionalLoad_Params& params, + bool is_same_document, + NavigationEntryImpl* entry_for_request) { + bool is_renderer_initiated = + entry_for_request ? entry_for_request->is_renderer_initiated() : true; return NavigationRequest::CreateForCommit( - frame_tree_node_, this, pending_entry, params, is_renderer_initiated, - true /* was_within_same_document */); + frame_tree_node_, this, entry_for_request, params, is_renderer_initiated, + is_same_document); } -std::unique_ptr<NavigationRequest> -RenderFrameHostImpl::TakeNavigationRequestForCommit( - const FrameHostMsg_DidCommitProvisionalLoad_Params& params) { - // TODO(ahemery): Once we have IsPerNavigationMojoInterfaceEnabled() always - // true, it becomes obsolete to match the NavigationRequest since we are - // sure it is the correct one. However using the same request even though - // url might have changed ("" becomes "about:blank", etc.) requires some - // updating. - - // Determine if the current NavigationRequest can be used. - NavigationHandleImpl* navigation_handle = - navigation_request_ ? navigation_request_->navigation_handle() : nullptr; - - // TODO(lukasza, clamy): https://crbug.com/784904: Match commit IPC to proper - // NavigationHandle without requiring URLs to match. - if (navigation_handle && navigation_handle->GetURL() == params.url) { - return std::move(navigation_request_); - } - - // At this point we know that the right/matching |navigation_request_| has - // already been found based on navigation id look-up performed by - // RFHI::OnCrossDocumentCommitProcessed. OTOH, we cannot use its - // NavigationHandle, because it has a mismatched URL (which would cause - // DCHECKs - for example in NavigationHandleImpl::DidCommitNavigation). - // - // Because of the above, if the URL does not match what the NavigationHandle - // expects, we want to treat the commit as a new navigation. - // This mostly works, but there are some remaining issues here tracked - // by https://crbug.com/872803. - // - // The URL mismatch can happen when loading a Data navigation with - // LoadDataWithBaseURL. - // TODO(csharrison): Data navigations loaded with LoadDataWithBaseURL get - // reset here, because the NavigationHandle tracks the URL but the params.url - // tracks the data. The trick of saving the old entry ids for these - // navigations should go away when this is properly handled. - // See https://crbug.com/588317. - // - // Other cases are where URL mismatch can happen is when committing an error - // page - for example this can happen during CSP/frame-ancestors checks (see - // https://crbug.com/759184). - - NavigationEntryImpl* entry_for_request = nullptr; - bool is_renderer_initiated = true; - - // Make sure that the pending entry was really loaded via LoadDataWithBaseURL - // and that it matches this handle. TODO(csharrison): The pending entry's - // base url should equal |params.base_url|. This is not the case for loads - // with invalid base urls. - if (navigation_handle) { - NavigationEntryImpl* pending_entry = - NavigationEntryImpl::FromNavigationEntry( - frame_tree_node()->navigator()->GetController()->GetPendingEntry()); - bool pending_entry_matches_handle = - pending_entry && pending_entry->GetUniqueID() == - navigation_handle->pending_nav_entry_id(); +bool RenderFrameHostImpl::NavigationRequestWasIntendedForPendingEntry( + NavigationRequest* request, + const FrameHostMsg_DidCommitProvisionalLoad_Params& params, + bool same_document) { + NavigationEntryImpl* pending_entry = NavigationEntryImpl::FromNavigationEntry( + frame_tree_node()->navigator()->GetController()->GetPendingEntry()); + if (!pending_entry) + return false; + if (request->nav_entry_id() != pending_entry->GetUniqueID()) + return false; + if (!same_document) { + // Make sure that the pending entry was really loaded via + // LoadDataWithBaseURL and that it matches this handle. // TODO(csharrison): The pending entry's base url should equal - // |validated_params.base_url|. This is not the case for loads with invalid - // base urls. - if (navigation_handle->GetURL() == params.base_url && - pending_entry_matches_handle && - !pending_entry->GetBaseURLForDataURL().is_empty()) { - entry_for_request = pending_entry; - is_renderer_initiated = pending_entry->is_renderer_initiated(); + // |params.base_url|. This is not the case for loads with invalid base urls. + if (request->common_params().url != params.base_url || + pending_entry->GetBaseURLForDataURL().is_empty()) { + return false; } } - - // There is no pending NavigationEntry in these cases, so pass 0 as the - // pending_nav_entry_id. If the previous handle was a prematurely aborted - // navigation loaded via LoadDataWithBaseURL, propagate the entry id. - return NavigationRequest::CreateForCommit( - frame_tree_node_, this, entry_for_request, params, - is_renderer_initiated /* is_renderer_initiated */, - false /* is_same_document */); + return true; } void RenderFrameHostImpl::BeforeUnloadTimeout() { @@ -6188,21 +6101,60 @@ } bool RenderFrameHostImpl::DidCommitNavigationInternal( - NavigationRequest* navigation_request, + std::unique_ptr<NavigationRequest> navigation_request, FrameHostMsg_DidCommitProvisionalLoad_Params* validated_params, bool is_same_document_navigation) { // Sanity-check the page transition for frame type. DCHECK_EQ(ui::PageTransitionIsMainFrame(validated_params->transition), !GetParent()); - if (navigation_request) { - OnCrossDocumentCommitProcessed(navigation_request, - blink::mojom::CommitResult::Ok); + // Check that the committing URL matches the navigation request. + // TODO(clamy, nasko): Do not use the URL to make the matching check. + std::unique_ptr<NavigationRequest> invalid_request = nullptr; + if (navigation_request && + navigation_request->common_params().url != validated_params->url) { + // At this point we know that the right/matching |navigation_request_| has + // already been found based on pointer look-up performed by + // RFHI::OnCrossDocumentCommitProcessed or the commit originated from a + // NavigationClient owned by the NavigationRequest. OTOH, we cannot use its + // NavigationHandle, because it has a mismatched URL (which would cause + // DCHECKs - for example in NavigationHandleImpl::DidCommitNavigation). + // + // Because of the above, if the URL does not match what the NavigationHandle + // expects, we want to treat the commit as a new navigation. + // + // The URL mismatch can happen when loading a Data navigation with + // LoadDataWithBaseURL. + // TODO(csharrison): Data navigations loaded with LoadDataWithBaseURL get + // reset here, because the NavigationHandle tracks the URL but the + // params.url tracks the data. The trick of saving the old entry ids for + // these navigations should go away when this is properly handled. See + // https://crbug.com/588317. + // + // Other cases are where URL mismatch can happen is when committing an error + // page - for example this can happen during CSP/frame-ancestors checks (see + // https://crbug.com/759184). + + // Note: the NavigationRequest is not reset here, as this could potentially + // lead to the deletion of the pending NavigationEntry. + invalid_request = std::move(navigation_request); + + // TODO(clamy): We should kill the renderer in all cases where we expect to + // have a NavigationRequest matching the commit URL. } if (!ValidateDidCommitParams(validated_params, is_same_document_navigation)) return false; + // The previous call might have changed the committing URL. Check if the + // NavigationRequest still has a matching URL. + // TODO(clamy): We should support the URL filtering without deleting the + // request. + if (navigation_request && + navigation_request->common_params().url != validated_params->url) { + invalid_request = std::move(navigation_request); + } + // Set is loading to true now if it has not been set yet. This happens for // renderer-initiated same-document navigations. It can also happen when a // racy DidStopLoading IPC resets the loading state that was set to true in @@ -6214,45 +6166,62 @@ was_loading); } - if (navigation_request_) - was_discarded_ = navigation_request_->commit_params().was_discarded; + if (navigation_request) + was_discarded_ = navigation_request->commit_params().was_discarded; - std::unique_ptr<NavigationRequest> committed_request; - if (is_same_document_navigation) { - committed_request = - TakeNavigationRequestForSameDocumentCommit(*validated_params); - } else { - committed_request = TakeNavigationRequestForCommit(*validated_params); + // If there is no valid NavigationRequest corresponding to this commit, create + // one in order to properly issue DidFinishNavigation calls to + // WebContentsObservers. + if (!navigation_request) { + // First check if there was a request for this navigation that cannot be + // used due to URL mismatch. If that's the case and it corresponds to a + // navigation to the pending NavigationEntry, the new request should be + // associated with the pending NavigationEntry as well so that the pending + // NavigationEntry is properly committed. + NavigationEntryImpl* entry_for_navigation = nullptr; + if (invalid_request && NavigationRequestWasIntendedForPendingEntry( + invalid_request.get(), *validated_params, + is_same_document_navigation)) { + entry_for_navigation = NavigationEntryImpl::FromNavigationEntry( + frame_tree_node()->navigator()->GetController()->GetPendingEntry()); + } + + navigation_request = CreateNavigationRequestForCommit( + *validated_params, is_same_document_navigation, entry_for_navigation); } - DCHECK(committed_request); - DCHECK(committed_request->navigation_handle()); + DCHECK(navigation_request); + DCHECK(navigation_request->navigation_handle()); // Update the page transition. For subframe navigations, the renderer process // only gives the correct page transition at commit time. // TODO(clamy): We should get the correct page transition when starting the // request. - committed_request->set_transition(validated_params->transition); + navigation_request->set_transition(validated_params->transition); - committed_request->set_has_user_gesture(validated_params->gesture == - NavigationGestureUser); + navigation_request->set_has_user_gesture(validated_params->gesture == + NavigationGestureUser); UpdateSiteURL(validated_params->url, validated_params->url_is_unreachable); // Set the state whether this navigation is to an MHTML document, since there // are certain security checks that we cannot apply to subframes in MHTML // documents. Do not trust renderer data when determining that, rather use - // the |committed_request|, which was generated and stays browser side. + // the |navigation_request|, which was generated and stays browser side. is_mhtml_document_ = - (committed_request->GetMimeType() == "multipart/related" || - committed_request->GetMimeType() == "message/rfc822"); + (navigation_request->GetMimeType() == "multipart/related" || + navigation_request->GetMimeType() == "message/rfc822"); accessibility_reset_count_ = 0; frame_tree_node()->navigator()->DidNavigate(this, *validated_params, - std::move(committed_request), + std::move(navigation_request), is_same_document_navigation); - if (!is_same_document_navigation) - navigation_request_.reset(); + + // TODO(clamy): We should stop having a special case for same-document + // navigation and just put them in the general map of NavigationRequests. + if (is_same_document_navigation && invalid_request) + same_document_navigation_request_ = std::move(invalid_request); + return true; } @@ -6435,7 +6404,7 @@ // Called when the renderer navigates. For every frame loaded, we'll get this // notification containing parameters identifying the navigation. void RenderFrameHostImpl::DidCommitNavigation( - NavigationRequest* committing_navigation_request, + std::unique_ptr<NavigationRequest> committing_navigation_request, std::unique_ptr<FrameHostMsg_DidCommitProvisionalLoad_Params> validated_params, mojom::DidCommitProvisionalLoadInterfaceParamsPtr interface_params) { @@ -6541,7 +6510,7 @@ // therefore the global object is not replaced. } - if (!DidCommitNavigationInternal(committing_navigation_request, + if (!DidCommitNavigationInternal(std::move(committing_navigation_request), validated_params.get(), false /* is_same_document_navigation */)) { return;
diff --git a/content/browser/frame_host/render_frame_host_impl.h b/content/browser/frame_host/render_frame_host_impl.h index df10f21..2ab76da 100644 --- a/content/browser/frame_host/render_frame_host_impl.h +++ b/content/browser/frame_host/render_frame_host_impl.h
@@ -108,6 +108,7 @@ class AssociatedInterfaceProvider; class AssociatedInterfaceRegistry; struct FramePolicy; +struct TransferableMessage; struct WebFullscreenOptions; struct WebScrollIntoViewParams; @@ -132,6 +133,7 @@ class GeolocationServiceImpl; class KeepAliveHandleFactory; class MediaInterfaceProxy; +class NavigationEntryImpl; class NavigationHandleImpl; class NavigationRequest; class PermissionServiceContext; @@ -213,13 +215,11 @@ gfx::NativeView GetNativeView() override; void AddMessageToConsole(ConsoleMessageLevel level, const std::string& message) override; - void ExecuteJavaScript(const base::string16& javascript) override; void ExecuteJavaScript(const base::string16& javascript, JavaScriptResultCallback callback) override; void ExecuteJavaScriptInIsolatedWorld(const base::string16& javascript, JavaScriptResultCallback callback, int world_id) override; - void ExecuteJavaScriptForTests(const base::string16& javascript) override; void ExecuteJavaScriptForTests(const base::string16& javascript, JavaScriptResultCallback callback) override; void ExecuteJavaScriptWithUserGestureForTests( @@ -828,11 +828,6 @@ // waiting to commit in this RenderFrameHost. std::set<int> GetNavigationEntryIdsPendingCommit(); - void DidCommitNavigationForTesting( - NavigationRequest* navigation_request, - std::unique_ptr<FrameHostMsg_DidCommitProvisionalLoad_Params> params, - mojom::DidCommitProvisionalLoadInterfaceParamsPtr interface_params); - service_manager::BinderRegistry& BinderRegistryForTesting() { return *registry_; } @@ -863,7 +858,7 @@ // Called on the main frame of a page embedded in a Portal when it is // activated. - void OnPortalActivated(); + void OnPortalActivated(blink::TransferableMessage data); // mojom::FrameHost: void VisibilityChanged(blink::mojom::FrameVisibility) override; @@ -1024,7 +1019,6 @@ void OnDetach(); void OnFrameFocused(); void OnOpenURL(const FrameHostMsg_OpenURL_Params& params); - void OnDocumentOnLoadCompleted(); void OnDidFailProvisionalLoadWithError( const FrameHostMsg_DidFailProvisionalLoadWithError_Params& params); void OnDidFailLoadWithError(const GURL& url, @@ -1080,9 +1074,8 @@ int child_frame_routing_id, int child_frame_browser_plugin_instance_id, ax::mojom::Event event_to_fire); - void OnAccessibilitySnapshotResponse( - int callback_id, - const AXContentTreeUpdate& snapshot); + void OnAccessibilitySnapshotResponse(int callback_id, + const AXContentTreeUpdate& snapshot); void OnEnterFullscreen(const blink::WebFullscreenOptions& options); void OnExitFullscreen(); void OnSuddenTerminationDisablerChanged( @@ -1172,6 +1165,7 @@ void UpdateEncoding(const std::string& encoding) override; void FrameSizeChanged(const gfx::Size& frame_size) override; void FullscreenStateChanged(bool is_fullscreen) override; + void DocumentOnLoadCompleted() override; #if defined(OS_ANDROID) void UpdateUserGestureCarryoverInfo() override; #endif @@ -1329,12 +1323,24 @@ bool success, const base::string16& user_input); - // Returns ownership of the NavigationRequest associated with a navigation - // that just committed. - std::unique_ptr<NavigationRequest> TakeNavigationRequestForSameDocumentCommit( - const FrameHostMsg_DidCommitProvisionalLoad_Params& params); - std::unique_ptr<NavigationRequest> TakeNavigationRequestForCommit( - const FrameHostMsg_DidCommitProvisionalLoad_Params& params); + // Creates a NavigationRequest to use for commit. This should only be used + // when no appropriate NavigationRequest has been found. + std::unique_ptr<NavigationRequest> CreateNavigationRequestForCommit( + const FrameHostMsg_DidCommitProvisionalLoad_Params& params, + bool is_same_document, + NavigationEntryImpl* entry_for_request); + + // Whether the |request| corresponds to a navigation to the pending + // NavigationEntry. This is used at commit time, when the NavigationRequest + // does not match the data sent by the renderer to re-create a + // NavigationRequest and associate it with the pending NavigationEntry if + // needed. + // TODO(clamy): We should handle the mismatches gracefully without deleting + // the NavigationRequest and having to re-create one. + bool NavigationRequestWasIntendedForPendingEntry( + NavigationRequest* request, + const FrameHostMsg_DidCommitProvisionalLoad_Params& params, + bool same_document); // Helper to process the beforeunload ACK. |proceed| indicates whether the // navigation or tab close should be allowed to proceed. If @@ -1446,7 +1452,7 @@ // The actual implementation of DidCommitProvisionalLoad and // DidCommitPerNavigationMojoInterfaceNavigation. void DidCommitNavigation( - NavigationRequest* committing_navigation_request, + std::unique_ptr<NavigationRequest> committing_navigation_request, std::unique_ptr<FrameHostMsg_DidCommitProvisionalLoad_Params> validated_params, mojom::DidCommitProvisionalLoadInterfaceParamsPtr interface_params); @@ -1457,7 +1463,7 @@ // Returns true if the navigation did commit properly, false if the commit // state should be restored to its pre-commit value. bool DidCommitNavigationInternal( - NavigationRequest* navigation_request, + std::unique_ptr<NavigationRequest> navigation_request, FrameHostMsg_DidCommitProvisionalLoad_Params* validated_params, bool is_same_document_navigation);
diff --git a/content/browser/frame_host/render_frame_host_impl_browsertest.cc b/content/browser/frame_host/render_frame_host_impl_browsertest.cc index 9128cfd..7154f912 100644 --- a/content/browser/frame_host/render_frame_host_impl_browsertest.cc +++ b/content/browser/frame_host/render_frame_host_impl_browsertest.cc
@@ -1952,7 +1952,8 @@ // Launch an alert javascript dialog. This pending dialog should block a // subsequent discarding before unload request. wc->GetMainFrame()->ExecuteJavaScriptForTests( - base::ASCIIToUTF16("setTimeout(function(){alert('hello');}, 10);")); + base::ASCIIToUTF16("setTimeout(function(){alert('hello');}, 10);"), + base::NullCallback()); dialog_manager.Wait(); EXPECT_EQ(0, dialog_manager.num_beforeunload_dialogs_seen()); EXPECT_EQ(0, dialog_manager.num_beforeunload_fired_seen());
diff --git a/content/browser/frame_host/render_frame_host_manager_browsertest.cc b/content/browser/frame_host/render_frame_host_manager_browsertest.cc index 9b7945e..a72a0a4d 100644 --- a/content/browser/frame_host/render_frame_host_manager_browsertest.cc +++ b/content/browser/frame_host/render_frame_host_manager_browsertest.cc
@@ -1347,7 +1347,7 @@ // but the spoofing tests synchronize execution using window title changes. void ExecuteScript(const ToRenderFrameHost& adapter, const char* script) { adapter.render_frame_host()->ExecuteJavaScriptForTests( - base::UTF8ToUTF16(script)); + base::UTF8ToUTF16(script), base::NullCallback()); } };
diff --git a/content/browser/media/media_internals_handler.cc b/content/browser/media/media_internals_handler.cc index 196e7675..900f34a 100644 --- a/content/browser/media/media_internals_handler.cc +++ b/content/browser/media/media_internals_handler.cc
@@ -44,7 +44,7 @@ // if the chrome://media-internals page hasn't finished loading. RenderFrameHost* host = web_ui()->GetWebContents()->GetMainFrame(); if (host && page_load_complete_) - host->ExecuteJavaScript(update); + host->ExecuteJavaScript(update, base::NullCallback()); } } // namespace content
diff --git a/content/browser/media/session/media_session_browsertest.cc b/content/browser/media/session/media_session_browsertest.cc index f91ea1c..add1dd5 100644 --- a/content/browser/media/session/media_session_browsertest.cc +++ b/content/browser/media/session/media_session_browsertest.cc
@@ -4,6 +4,7 @@ #include "content/public/browser/media_session.h" +#include "base/bind_helpers.h" #include "base/command_line.h" #include "base/optional.h" #include "base/run_loop.h" @@ -95,13 +96,15 @@ void StartPlaybackAndWait(Shell* shell, const std::string& id) { shell->web_contents()->GetMainFrame()->ExecuteJavaScriptForTests( - base::ASCIIToUTF16("document.querySelector('#" + id + "').play();")); + base::ASCIIToUTF16("document.querySelector('#" + id + "').play();"), + base::NullCallback()); WaitForStart(shell); } void StopPlaybackAndWait(Shell* shell, const std::string& id) { shell->web_contents()->GetMainFrame()->ExecuteJavaScriptForTests( - base::ASCIIToUTF16("document.querySelector('#" + id + "').pause();")); + base::ASCIIToUTF16("document.querySelector('#" + id + "').pause();"), + base::NullCallback()); WaitForStop(shell); }
diff --git a/content/browser/navigation_browsertest.cc b/content/browser/navigation_browsertest.cc index 28ee776e..29c5ff5 100644 --- a/content/browser/navigation_browsertest.cc +++ b/content/browser/navigation_browsertest.cc
@@ -1041,6 +1041,10 @@ } // Regression test for https://crbug.com/856396. +// Note that original issue for the bug is not applicable anymore, because there +// is no provisional document loader which has not committed yet. We keep the +// modified version of this test to check removing iframe from the load event +// handler. IN_PROC_BROWSER_TEST_F(NavigationBaseBrowserTest, ReplacingDocumentLoaderFiresLoadEvent) { net::test_server::ControllableHttpResponse main_document_response( @@ -1069,8 +1073,8 @@ main_document_response.Done(); // 2) The iframe starts to load, but the server only have time to send the - // response's headers, not the response's body. A provisional DocumentLoader - // will be created in the renderer process, but it will never commit. + // response's headers, not the response's body. This should commit the + // iframe's load. iframe_response.WaitForRequest(); iframe_response.Send( "HTTP/1.1 200 OK\r\n" @@ -1078,11 +1082,14 @@ "\r\n"); // 3) In the meantime the iframe navigates elsewhere. It causes the previous - // provisional DocumentLoader to be replaced by the new one. Removing it may + // DocumentLoader to be replaced by the new one. Removing it may // trigger the 'load' event and delete the iframe. EXPECT_TRUE(ExecuteScript( shell(), "document.querySelector('iframe').src = '/title1.html'")); + // 4) Finish the original request. + iframe_response.Done(); + // Wait for the iframe to be deleted and check the renderer process is still // alive. int iframe_count = 1; @@ -1160,97 +1167,6 @@ EXPECT_TRUE(WaitForLoadStop(shell()->web_contents())); } -// This test reproduces the following race condition: -// 1) A first navigation starts, the headers are received, the navigation -// reaches ready-to-commit. It is sent to the renderer to be committed. -// 2) In the meantime, a second navigation reaches ready-to-commit in the -// browser. -// 3) Before the renderer gets notified of the new navigation, the -// first navigation is committed. -// 4) The browser gets notified of the commit of the first navigation. This -// should not destroy the NavigationRequest corresponding to the second -// navigation. -IN_PROC_BROWSER_TEST_F(NavigationBrowserTest, - RaceNewNavigationCommitWhileOldOneFinishesLoading) { - // Start the test with an initial document. - GURL main_url(embedded_test_server()->GetURL("/simple_page.html")); - EXPECT_TRUE(NavigateToURL(shell(), main_url)); - RenderFrameHostImpl* render_frame_host = static_cast<RenderFrameHostImpl*>( - shell()->web_contents()->GetMainFrame()); - - NavigationRecorder recorder(shell()->web_contents()); - // Note: These two pages contain an image that will never load. The goal is to - // prevent RenderFrameHostImpl::DidStopLoading() to be called since it will - // cancel any pending navigation. - GURL page_1(embedded_test_server()->GetURL("/infinite_load_1.html")); - GURL page_2(embedded_test_server()->GetURL("/infinite_load_2.html")); - // Intercept and cancel any FrameMsgHost_DidCommitProvisionalLoad events. - InterceptAndCancelDidCommitProvisionalLoad interceptor( - shell()->web_contents()); - - // 1) Navigate to page_1. - shell()->LoadURL(page_1); - - // 2) The browser receives the response's headers. The navigation commits in - // the browser. - recorder.WaitForEvents(2); - EXPECT_EQ(2u, recorder.records().size()); - EXPECT_STREQ("start /infinite_load_1.html", recorder.records()[0].c_str()); - EXPECT_STREQ("ready-to-commit /infinite_load_1.html", - recorder.records()[1].c_str()); - - // 3) Wait for the renderer to receive the response's body, but do not notify - // the browser of it right now. It is delayed in 6). - interceptor.Wait(1); - EXPECT_EQ(1u, interceptor.intercepted_messages().size()); - - // 4) In the meantime, the browser starts a navigation to page_2. - shell()->LoadURL(page_2); - - // 5) The response's headers are received, the navigation reaches - // ready-to-commit in the browser. This should not delete the ongoing - // NavigationRequest. - recorder.WaitForEvents(4); - EXPECT_EQ(4u, recorder.records().size()); - EXPECT_STREQ("start /infinite_load_2.html", recorder.records()[2].c_str()); - EXPECT_STREQ("ready-to-commit /infinite_load_2.html", - recorder.records()[3].c_str()); - - // 6) The browser receives the first DidCommitProvisionalLoad message. This - // should not delete the second navigation. This is the end of the first - // navigation. - ASSERT_GE(interceptor.intercepted_navigations().size(), 1u); - render_frame_host->DidCommitNavigationForTesting( - interceptor.intercepted_navigations()[0], - std::make_unique<::FrameHostMsg_DidCommitProvisionalLoad_Params>( - interceptor.intercepted_messages()[0]), - mojom::DidCommitProvisionalLoadInterfaceParams::New( - std::move(interceptor.intercepted_requests()[0]), - std::move(interceptor.intercepted_broker_content_requests()[0]), - std::move(interceptor.intercepted_broker_blink_requests()[0]))); - recorder.WaitForEvents(5); - EXPECT_EQ(5u, recorder.records().size()); - EXPECT_STREQ("did-commit /infinite_load_1.html", - recorder.records()[4].c_str()); - - // 7) Wait for the renderer to receive the second response's body. This is the - // end of the second navigation. - interceptor.Wait(2); - EXPECT_EQ(2u, interceptor.intercepted_messages().size()); - render_frame_host->DidCommitNavigationForTesting( - interceptor.intercepted_navigations()[1], - std::make_unique<::FrameHostMsg_DidCommitProvisionalLoad_Params>( - interceptor.intercepted_messages()[1]), - mojom::DidCommitProvisionalLoadInterfaceParams::New( - std::move(interceptor.intercepted_requests()[1]), - std::move(interceptor.intercepted_broker_content_requests()[1]), - std::move(interceptor.intercepted_broker_blink_requests()[1]))); - recorder.WaitForEvents(6); - EXPECT_EQ(6u, recorder.records().size()); - EXPECT_STREQ("did-commit /infinite_load_2.html", - recorder.records()[5].c_str()); -} - // Renderer initiated back/forward navigation in beforeunload should not prevent // the user to navigate away from a website. IN_PROC_BROWSER_TEST_F(NavigationBrowserTest, HistoryBackInBeforeUnload) {
diff --git a/content/browser/portal/portal.cc b/content/browser/portal/portal.cc index 2fc24bd..242a5f9 100644 --- a/content/browser/portal/portal.cc +++ b/content/browser/portal/portal.cc
@@ -103,7 +103,8 @@ portal_contents_impl_->GetController().LoadURLWithParams(load_url_params); } -void Portal::Activate(base::OnceCallback<void()> callback) { +void Portal::Activate(blink::TransferableMessage data, + base::OnceCallback<void()> callback) { WebContents* outer_contents = WebContents::FromRenderFrameHost(owner_render_frame_host_); WebContentsDelegate* delegate = outer_contents->GetDelegate(); @@ -119,7 +120,7 @@ // TODO(lfg): The old WebContents is currently discarded, but should be // kept and passed to the new page. https://crbug.com/914122 portal_contents_impl_->set_portal(nullptr); - portal_contents_impl_->GetMainFrame()->OnPortalActivated(); + portal_contents_impl_->GetMainFrame()->OnPortalActivated(std::move(data)); std::move(callback).Run(); }
diff --git a/content/browser/portal/portal.h b/content/browser/portal/portal.h index 34e8ae6b..3806b57 100644 --- a/content/browser/portal/portal.h +++ b/content/browser/portal/portal.h
@@ -12,6 +12,7 @@ #include "content/public/browser/web_contents_delegate.h" #include "content/public/browser/web_contents_observer.h" #include "mojo/public/cpp/bindings/strong_binding.h" +#include "third_party/blink/public/common/messaging/transferable_message.h" #include "third_party/blink/public/mojom/portal/portal.mojom.h" namespace content { @@ -51,7 +52,8 @@ // blink::mojom::Portal implementation. void Navigate(const GURL& url) override; - void Activate(base::OnceCallback<void()> callback) override; + void Activate(blink::TransferableMessage data, + base::OnceCallback<void()> callback) override; // WebContentsObserver overrides. void RenderFrameDeleted(RenderFrameHost* render_frame_host) override;
diff --git a/content/browser/portal/portal_browsertest.cc b/content/browser/portal/portal_browsertest.cc index 89562753..6b3b258d 100644 --- a/content/browser/portal/portal_browsertest.cc +++ b/content/browser/portal/portal_browsertest.cc
@@ -44,7 +44,8 @@ blink::mojom::PortalRequest request); static PortalInterceptorForTesting* From(content::Portal* portal); - void Activate(base::OnceCallback<void()> callback) override { + void Activate(blink::TransferableMessage data, + base::OnceCallback<void()> callback) override { portal_activated_ = true; if (run_loop_) { @@ -53,7 +54,7 @@ } // |this| can be destroyed after Activate() is called. - portal_->Activate(std::move(callback)); + portal_->Activate(std::move(data), std::move(callback)); } void WaitForActivate() {
diff --git a/content/browser/renderer_host/compositor_impl_android.cc b/content/browser/renderer_host/compositor_impl_android.cc index 72fae86..7841ee4 100644 --- a/content/browser/renderer_host/compositor_impl_android.cc +++ b/content/browser/renderer_host/compositor_impl_android.cc
@@ -673,7 +673,7 @@ subroot_layer_->RemoveFromParent(); subroot_layer_ = nullptr; } - if (root_window_->GetLayer()) { + if (root_layer.get() && root_window_->GetLayer()) { subroot_layer_ = root_window_->GetLayer(); subroot_layer_->AddChild(root_layer); }
diff --git a/content/browser/renderer_host/dwrite_font_lookup_table_builder_win.cc b/content/browser/renderer_host/dwrite_font_lookup_table_builder_win.cc index ee4ae53..fd49c4a6 100644 --- a/content/browser/renderer_host/dwrite_font_lookup_table_builder_win.cc +++ b/content/browser/renderer_host/dwrite_font_lookup_table_builder_win.cc
@@ -24,6 +24,7 @@ #include "base/trace_event/trace_event.h" #include "content/browser/renderer_host/dwrite_font_file_util_win.h" #include "content/browser/renderer_host/dwrite_font_uma_logging_win.h" +#include "content/public/common/content_client.h" #include "content/public/common/content_features.h" #include "third_party/blink/public/common/font_unique_name_lookup/icu_fold_case_util.h" #include "ui/gfx/win/direct_write.h"
diff --git a/content/browser/renderer_host/render_widget_host_view_android.cc b/content/browser/renderer_host/render_widget_host_view_android.cc index bf2ca4d..d5fc97f3 100644 --- a/content/browser/renderer_host/render_widget_host_view_android.cc +++ b/content/browser/renderer_host/render_widget_host_view_android.cc
@@ -2206,6 +2206,14 @@ ShowInternal(); } +void RenderWidgetHostViewAndroid::OnCursorVisibilityChanged(bool visible) { + TRACE_EVENT0("browser", + "RenderWidgetHostViewAndroid::OnCursorVisibilityChanged"); + DCHECK(observing_root_window_); + if (host()) + host()->SendCursorVisibilityState(visible); +} + void RenderWidgetHostViewAndroid::OnLostResources() { EvictDelegatedFrame(); }
diff --git a/content/browser/renderer_host/render_widget_host_view_android.h b/content/browser/renderer_host/render_widget_host_view_android.h index 5eb77b8..9cfc5139 100644 --- a/content/browser/renderer_host/render_widget_host_view_android.h +++ b/content/browser/renderer_host/render_widget_host_view_android.h
@@ -215,6 +215,7 @@ void OnAnimate(base::TimeTicks begin_frame_time) override; void OnActivityStopped() override; void OnActivityStarted() override; + void OnCursorVisibilityChanged(bool visible) override; // StylusTextSelectorClient implementation. void OnStylusSelectBegin(float x0, float y0, float x1, float y1) override;
diff --git a/content/browser/web_contents/web_contents_android.cc b/content/browser/web_contents/web_contents_android.cc index 4420ce4..ae66982 100644 --- a/content/browser/web_contents/web_contents_android.cc +++ b/content/browser/web_contents/web_contents_android.cc
@@ -15,6 +15,7 @@ #include "base/android/jni_array.h" #include "base/android/jni_string.h" #include "base/bind.h" +#include "base/bind_helpers.h" #include "base/command_line.h" #include "base/json/json_writer.h" #include "base/lazy_instance.h" @@ -517,7 +518,7 @@ if (!callback) { // No callback requested. web_contents_->GetMainFrame()->ExecuteJavaScript( - ConvertJavaStringToUTF16(env, script)); + ConvertJavaStringToUTF16(env, script), base::NullCallback()); return; } @@ -550,7 +551,7 @@ if (!callback) { // No callback requested. web_contents_->GetMainFrame()->ExecuteJavaScriptForTests( - ConvertJavaStringToUTF16(env, script)); + ConvertJavaStringToUTF16(env, script), base::NullCallback()); return; }
diff --git a/content/browser/webauth/webauth_browsertest.cc b/content/browser/webauth/webauth_browsertest.cc index 7616e873..6a055f38 100644 --- a/content/browser/webauth/webauth_browsertest.cc +++ b/content/browser/webauth/webauth_browsertest.cc
@@ -7,6 +7,7 @@ #include <vector> #include "base/bind.h" +#include "base/bind_helpers.h" #include "base/command_line.h" #include "base/json/json_reader.h" #include "base/macros.h" @@ -896,7 +897,7 @@ const std::string& result_prefix) { DOMMessageQueue dom_message_queue(web_contents); web_contents->GetMainFrame()->ExecuteJavaScriptForTests( - base::UTF8ToUTF16(script)); + base::UTF8ToUTF16(script), base::NullCallback()); for (;;) { std::string json;
diff --git a/content/browser/webrtc/webrtc_internals_message_handler.cc b/content/browser/webrtc/webrtc_internals_message_handler.cc index aa69de6..80580be3 100644 --- a/content/browser/webrtc/webrtc_internals_message_handler.cc +++ b/content/browser/webrtc/webrtc_internals_message_handler.cc
@@ -5,6 +5,7 @@ #include "content/browser/webrtc/webrtc_internals_message_handler.h" #include "base/bind.h" +#include "base/bind_helpers.h" #include "content/browser/webrtc/webrtc_internals.h" #include "content/common/media/peer_connection_tracker_messages.h" #include "content/public/browser/browser_thread.h" @@ -153,7 +154,7 @@ args_vector.push_back(args); base::string16 script = WebUI::GetJavascriptCall(command, args_vector); - host->ExecuteJavaScript(script); + host->ExecuteJavaScript(script, base::NullCallback()); } } // namespace content
diff --git a/content/browser/webui/web_ui_impl.cc b/content/browser/webui/web_ui_impl.cc index 1868b57..8ebddd2e 100644 --- a/content/browser/webui/web_ui_impl.cc +++ b/content/browser/webui/web_ui_impl.cc
@@ -9,6 +9,7 @@ #include <string> #include <utility> +#include "base/bind_helpers.h" #include "base/debug/dump_without_crashing.h" #include "base/json/json_writer.h" #include "base/strings/string_util.h" @@ -291,7 +292,8 @@ if (!CanCallJavascript()) return; - web_contents_->GetMainFrame()->ExecuteJavaScript(javascript); + web_contents_->GetMainFrame()->ExecuteJavaScript(javascript, + base::NullCallback()); } void WebUIImpl::DisallowJavascriptOnAllHandlers() {
diff --git a/content/common/frame.mojom b/content/common/frame.mojom index 30f3940..3d32af40 100644 --- a/content/common/frame.mojom +++ b/content/common/frame.mojom
@@ -23,6 +23,7 @@ import "third_party/blink/public/mojom/feature_policy/feature_policy.mojom"; import "third_party/blink/public/mojom/frame/lifecycle.mojom"; import "third_party/blink/public/mojom/frame/navigation_initiator.mojom"; +import "third_party/blink/public/mojom/messaging/transferable_message.mojom"; import "third_party/blink/public/mojom/loader/url_loader_factory_bundle.mojom"; import "third_party/blink/public/mojom/portal/portal.mojom"; import "third_party/blink/public/mojom/referrer.mojom"; @@ -57,7 +58,7 @@ // Called on the main frame of a page embedded in a Portal when it is // activated. - OnPortalActivated(); + OnPortalActivated(blink.mojom.TransferableMessage data); // Set the lifecycle state. SetLifecycleState(blink.mojom.FrameLifecycleState state); @@ -422,4 +423,8 @@ // were initiated by a gesture too, otherwise the navigation may be blocked. [EnableIf=is_android] UpdateUserGestureCarryoverInfo(); + + // Sent after the onload handler has been invoked for the document + // in this frame. Sent for top-level frames. + DocumentOnLoadCompleted(); };
diff --git a/content/common/frame_messages.h b/content/common/frame_messages.h index 0ea49d9..649f113 100644 --- a/content/common/frame_messages.h +++ b/content/common/frame_messages.h
@@ -1174,12 +1174,6 @@ int /* render_frame_id */, std::string /* data_url */) -// Sent when after the onload handler has been invoked for the document -// in this frame. Sent for top-level frames. |report_type| and |ui_timestamp| -// are used to report navigation metrics starting on the ui input event that -// triggered the navigation timestamp. -IPC_MESSAGE_ROUTED0(FrameHostMsg_DocumentOnLoadCompleted) - // Notifies that the initial empty document of a view has been accessed. // After this, it is no longer safe to show a pending navigation's URL without // making a URL spoof possible.
diff --git a/content/public/browser/content_browser_client.cc b/content/public/browser/content_browser_client.cc index 7709ade..abc0a228 100644 --- a/content/public/browser/content_browser_client.cc +++ b/content/public/browser/content_browser_client.cc
@@ -533,6 +533,10 @@ return std::string(); } +base::FilePath ContentBrowserClient::GetFontLookupTableCacheDir() { + return base::FilePath(); +} + base::FilePath ContentBrowserClient::GetShaderDiskCacheDirectory() { return base::FilePath(); }
diff --git a/content/public/browser/content_browser_client.h b/content/public/browser/content_browser_client.h index bdd985c..7d52e8e 100644 --- a/content/public/browser/content_browser_client.h +++ b/content/public/browser/content_browser_client.h
@@ -815,6 +815,11 @@ // else we should do with the file. virtual std::string GetDefaultDownloadName(); + // Returns the path to the font lookup table cache directory in which - on + // Windows 7 & 8 - we cache font name meta information to perform @font-face { + // src: local() } lookups. + virtual base::FilePath GetFontLookupTableCacheDir(); + // Returns the path to the browser shader disk cache root. virtual base::FilePath GetShaderDiskCacheDirectory();
diff --git a/content/public/browser/render_frame_host.h b/content/public/browser/render_frame_host.h index e61f8e9..27d08fa9 100644 --- a/content/public/browser/render_frame_host.h +++ b/content/public/browser/render_frame_host.h
@@ -183,7 +183,6 @@ // This is the default API to run JavaScript in this frame. This API can only // be called on chrome:// or chrome-devtools:// URLs. - virtual void ExecuteJavaScript(const base::string16& javascript) = 0; virtual void ExecuteJavaScript(const base::string16& javascript, JavaScriptResultCallback callback) = 0; @@ -195,7 +194,6 @@ int world_id) = 0; // This runs the JavaScript, but without restrictions. THIS IS ONLY FOR TESTS. - virtual void ExecuteJavaScriptForTests(const base::string16& javascript) = 0; virtual void ExecuteJavaScriptForTests(const base::string16& javascript, JavaScriptResultCallback callback) = 0;
diff --git a/content/public/browser/web_contents.h b/content/public/browser/web_contents.h index 27cbadf..2fe0a25a 100644 --- a/content/public/browser/web_contents.h +++ b/content/public/browser/web_contents.h
@@ -361,9 +361,7 @@ virtual RenderWidgetHostView* GetFullscreenRenderWidgetHostView() = 0; // Returns the theme color for the underlying content as set by the - // theme-color meta tag, returns SK_ColorTRANSPARENT if none. - // TODO(crbug.com/872121): Make this return a base::Optional instead of - // relying on a sentinel value. + // theme-color meta tag. virtual SkColor GetThemeColor() = 0; // Returns the committed WebUI if one exists, otherwise the pending one.
diff --git a/content/public/test/browser_test_utils.cc b/content/public/test/browser_test_utils.cc index dbccfa73..ccd59da 100644 --- a/content/public/test/browser_test_utils.cc +++ b/content/public/test/browser_test_utils.cc
@@ -186,12 +186,14 @@ if (user_gesture) render_frame_host->ExecuteJavaScriptWithUserGestureForTests(script16); else - render_frame_host->ExecuteJavaScriptForTests(script16); + render_frame_host->ExecuteJavaScriptForTests(script16, + base::NullCallback()); } else { // Note that |user_gesture| here is ignored. We allow a value of |true| // because it's the default, but in blink, the execution will occur with // no user gesture. - render_frame_host->ExecuteJavaScriptInIsolatedWorld(script16, {}, world_id); + render_frame_host->ExecuteJavaScriptInIsolatedWorld( + script16, base::NullCallback(), world_id); } std::string json; if (!dom_message_queue.WaitForMessage(&json)) {
diff --git a/content/renderer/loader/web_url_loader_impl.cc b/content/renderer/loader/web_url_loader_impl.cc index c417f29d..8a5a1416 100644 --- a/content/renderer/loader/web_url_loader_impl.cc +++ b/content/renderer/loader/web_url_loader_impl.cc
@@ -886,21 +886,6 @@ WebURLResponse response; PopulateURLResponse(url_, info, &response, report_raw_headers_, request_id_); - if (use_stream_on_response_) { - auto read_handle = std::make_unique<SharedMemoryDataConsumerHandle>( - base::BindOnce(&Context::CancelBodyStreaming, this), - &body_stream_writer_); - - // Here |body_stream_writer_| has an indirect reference to |this| and that - // creates a reference cycle, but it is not a problem because the cycle - // will break if one of the following happens: - // 1) The body data transfer is done (with or without an error). - // 2) |read_handle| (and its reader) is detached. - client_->DidReceiveResponse(response, std::move(read_handle)); - // TODO(yhirano): Support ftp listening and multipart - return; - } - client_->DidReceiveResponse(response); // DidReceiveResponse() may have triggered a cancel, causing the |client_| to @@ -911,40 +896,13 @@ void WebURLLoaderImpl::Context::OnStartLoadingResponseBody( mojo::ScopedDataPipeConsumerHandle body) { - if (!pass_response_pipe_to_client_) { - DCHECK(base::FeatureList::IsEnabled( - blink::features::kResourceLoadViaDataPipe)); - body_handle_ = std::move(body); - body_watcher_.Watch( - body_handle_.get(), - MOJO_HANDLE_SIGNAL_READABLE | MOJO_HANDLE_SIGNAL_PEER_CLOSED, - MOJO_TRIGGER_CONDITION_SIGNALS_SATISFIED, - base::BindRepeating(&WebURLLoaderImpl::Context::OnBodyAvailable, this)); - if (defers_loading_ == NOT_DEFERRING) - OnBodyAvailable(MOJO_RESULT_OK, {}); - return; - } - if (client_) client_->DidStartLoadingResponseBody(std::move(body)); } void WebURLLoaderImpl::Context::OnReceivedData( std::unique_ptr<ReceivedData> data) { - const char* payload = data->payload(); - int data_length = data->length(); - if (!client_) - return; - - TRACE_EVENT_WITH_FLOW0( - "loading", "WebURLLoaderImpl::Context::OnReceivedData", - this, TRACE_EVENT_FLAG_FLOW_IN | TRACE_EVENT_FLAG_FLOW_OUT); - - if (use_stream_on_response_) { - body_stream_writer_->AddData(std::move(data)); - } else { - client_->DidReceiveData(payload, data_length); - } + NOTREACHED(); } void WebURLLoaderImpl::Context::OnTransferSizeUpdated(int transfer_size_diff) {
diff --git a/content/renderer/loader/web_url_loader_impl_unittest.cc b/content/renderer/loader/web_url_loader_impl_unittest.cc index 40dd7a9..d780d77 100644 --- a/content/renderer/loader/web_url_loader_impl_unittest.cc +++ b/content/renderer/loader/web_url_loader_impl_unittest.cc
@@ -15,7 +15,6 @@ #include "base/run_loop.h" #include "base/single_thread_task_runner.h" #include "base/stl_util.h" -#include "base/test/scoped_feature_list.h" #include "base/test/scoped_task_environment.h" #include "base/time/default_tick_clock.h" #include "base/time/time.h" @@ -41,7 +40,6 @@ #include "services/network/public/cpp/weak_wrapper_shared_url_loader_factory.h" #include "services/network/public/mojom/request_context_frame_type.mojom.h" #include "testing/gtest/include/gtest/gtest.h" -#include "third_party/blink/public/common/features.h" #include "third_party/blink/public/platform/scheduler/test/renderer_scheduler_test_support.h" #include "third_party/blink/public/platform/web_data.h" #include "third_party/blink/public/platform/web_string.h" @@ -223,17 +221,15 @@ loader_.reset(); } + void DidStartLoadingResponseBody( + mojo::ScopedDataPipeConsumerHandle response_body) override { + DCHECK(!response_body_); + DCHECK(response_body); + response_body_ = std::move(response_body); + } + void DidReceiveData(const char* data, int dataLength) override { - EXPECT_TRUE(loader_); - // The response should have started, but must not have finished, or failed. - EXPECT_TRUE(did_receive_response_); - EXPECT_FALSE(did_finish_); - EXPECT_FALSE(error_); - - received_data_.append(data, dataLength); - - if (delete_on_receive_data_) - loader_.reset(); + NOTREACHED(); } void DidFinishLoading( @@ -277,7 +273,7 @@ bool did_receive_redirect() const { return did_receive_redirect_; } bool did_receive_response() const { return did_receive_response_; } - const std::string& received_data() const { return received_data_; } + bool did_receive_response_body() const { return !!response_body_; } bool did_finish() const { return did_finish_; } const base::Optional<blink::WebURLError>& error() const { return error_; } const blink::WebURLResponse& response() const { return response_; } @@ -294,7 +290,7 @@ bool did_receive_redirect_; bool did_receive_response_; - std::string received_data_; + mojo::ScopedDataPipeConsumerHandle response_body_; bool did_finish_; base::Optional<blink::WebURLError> error_; blink::WebURLResponse response_; @@ -302,11 +298,9 @@ DISALLOW_COPY_AND_ASSIGN(TestWebURLLoaderClient); }; -class WebURLLoaderImplTest : public testing::TestWithParam<bool> { +class WebURLLoaderImplTest : public testing::Test { public: WebURLLoaderImplTest() { - scoped_feature_list_.InitWithFeatureState( - blink::features::kResourceLoadViaDataPipe, IsResourceLoadViaDataPipe()); client_.reset(new TestWebURLLoaderClient(&dispatcher_)); } @@ -357,8 +351,6 @@ } void DoStartLoadingResponseBody() { - if (!IsResourceLoadViaDataPipe()) - return; mojo::ScopedDataPipeConsumerHandle handle_to_pass; MojoResult rv = mojo::CreateDataPipe(nullptr, &body_handle_, &handle_to_pass); @@ -366,28 +358,11 @@ peer()->OnStartLoadingResponseBody(std::move(handle_to_pass)); } - // Assumes it is called only once for a request. - void DoReceiveData() { - EXPECT_EQ("", client()->received_data()); - uint32_t size = strlen(kTestData); - if (IsResourceLoadViaDataPipe()) { - body_handle_->WriteData(kTestData, &size, MOJO_WRITE_DATA_FLAG_NONE); - EXPECT_EQ(strlen(kTestData), size); - base::RunLoop().RunUntilIdle(); - } else { - peer()->OnReceivedData( - std::make_unique<FixedReceivedData>(kTestData, size)); - } - EXPECT_EQ(kTestData, client()->received_data()); - } - void DoCompleteRequest() { EXPECT_FALSE(client()->did_finish()); - if (body_handle_.is_valid()) { - DCHECK(IsResourceLoadViaDataPipe()); - body_handle_.reset(); - base::RunLoop().RunUntilIdle(); - } + DCHECK(body_handle_); + body_handle_.reset(); + base::RunLoop().RunUntilIdle(); network::URLLoaderCompletionStatus status(net::OK); status.encoded_data_length = base::size(kTestData); status.encoded_body_length = base::size(kTestData); @@ -400,11 +375,9 @@ void DoFailRequest() { EXPECT_FALSE(client()->did_finish()); - if (body_handle_.is_valid()) { - DCHECK(IsResourceLoadViaDataPipe()); - body_handle_.reset(); - base::RunLoop().RunUntilIdle(); - } + DCHECK(body_handle_); + body_handle_.reset(); + base::RunLoop().RunUntilIdle(); network::URLLoaderCompletionStatus status(net::ERR_FAILED); status.encoded_data_length = base::size(kTestData); status.encoded_body_length = base::size(kTestData); @@ -419,91 +392,71 @@ TestResourceDispatcher* dispatcher() { return &dispatcher_; } RequestPeer* peer() { return dispatcher()->peer(); } - static bool IsResourceLoadViaDataPipe() { return GetParam(); } - private: base::test::ScopedTaskEnvironment task_environment_; - base::test::ScopedFeatureList scoped_feature_list_; TestResourceDispatcher dispatcher_; mojo::ScopedDataPipeProducerHandle body_handle_; std::unique_ptr<TestWebURLLoaderClient> client_; }; -INSTANTIATE_TEST_SUITE_P(WebURLLoaderImplTestP, - WebURLLoaderImplTest, - testing::Bool()); - -TEST_P(WebURLLoaderImplTest, Success) { +TEST_F(WebURLLoaderImplTest, Success) { DoStartAsyncRequest(); DoReceiveResponse(); DoStartLoadingResponseBody(); - DoReceiveData(); DoCompleteRequest(); EXPECT_FALSE(dispatcher()->canceled()); - EXPECT_EQ(kTestData, client()->received_data()); + EXPECT_TRUE(client()->did_receive_response_body()); } -TEST_P(WebURLLoaderImplTest, Redirect) { +TEST_F(WebURLLoaderImplTest, Redirect) { DoStartAsyncRequest(); DoReceiveRedirect(); DoReceiveResponse(); DoStartLoadingResponseBody(); - DoReceiveData(); DoCompleteRequest(); EXPECT_FALSE(dispatcher()->canceled()); - EXPECT_EQ(kTestData, client()->received_data()); + EXPECT_TRUE(client()->did_receive_response_body()); } -TEST_P(WebURLLoaderImplTest, Failure) { +TEST_F(WebURLLoaderImplTest, Failure) { DoStartAsyncRequest(); DoReceiveResponse(); DoStartLoadingResponseBody(); - DoReceiveData(); DoFailRequest(); EXPECT_FALSE(dispatcher()->canceled()); } // The client may delete the WebURLLoader during any callback from the loader. // These tests make sure that doesn't result in a crash. -TEST_P(WebURLLoaderImplTest, DeleteOnReceiveRedirect) { +TEST_F(WebURLLoaderImplTest, DeleteOnReceiveRedirect) { client()->set_delete_on_receive_redirect(); DoStartAsyncRequest(); DoReceiveRedirect(); } -TEST_P(WebURLLoaderImplTest, DeleteOnReceiveResponse) { +TEST_F(WebURLLoaderImplTest, DeleteOnReceiveResponse) { client()->set_delete_on_receive_response(); DoStartAsyncRequest(); DoReceiveResponse(); } -TEST_P(WebURLLoaderImplTest, DeleteOnReceiveData) { - client()->set_delete_on_receive_data(); - DoStartAsyncRequest(); - DoReceiveResponse(); - DoStartLoadingResponseBody(); - DoReceiveData(); -} - -TEST_P(WebURLLoaderImplTest, DeleteOnFinish) { +TEST_F(WebURLLoaderImplTest, DeleteOnFinish) { client()->set_delete_on_finish(); DoStartAsyncRequest(); DoReceiveResponse(); DoStartLoadingResponseBody(); - DoReceiveData(); DoCompleteRequest(); } -TEST_P(WebURLLoaderImplTest, DeleteOnFail) { +TEST_F(WebURLLoaderImplTest, DeleteOnFail) { client()->set_delete_on_fail(); DoStartAsyncRequest(); DoReceiveResponse(); DoStartLoadingResponseBody(); - DoReceiveData(); DoFailRequest(); } -TEST_P(WebURLLoaderImplTest, DefersLoadingBeforeStart) { +TEST_F(WebURLLoaderImplTest, DefersLoadingBeforeStart) { client()->loader()->SetDefersLoading(true); EXPECT_FALSE(dispatcher()->defers_loading()); DoStartAsyncRequest(); @@ -512,7 +465,7 @@ // Checks that the navigation response override parameters provided on // navigation commit are properly applied. -TEST_P(WebURLLoaderImplTest, BrowserSideNavigationCommit) { +TEST_F(WebURLLoaderImplTest, BrowserSideNavigationCommit) { // Initialize the request and the stream override. const GURL kNavigationURL = GURL(kTestURL); const std::string kMimeType = "text/html"; @@ -543,13 +496,12 @@ EXPECT_EQ(kMimeType, client()->response().MimeType().Latin1()); DoStartLoadingResponseBody(); - DoReceiveData(); DoCompleteRequest(); EXPECT_FALSE(dispatcher()->canceled()); - EXPECT_EQ(kTestData, client()->received_data()); + EXPECT_TRUE(client()->did_receive_response_body()); } -TEST_P(WebURLLoaderImplTest, ResponseIPAddress) { +TEST_F(WebURLLoaderImplTest, ResponseIPAddress) { GURL url("http://example.test/"); struct TestCase { @@ -577,7 +529,7 @@ }; } -TEST_P(WebURLLoaderImplTest, ResponseCert) { +TEST_F(WebURLLoaderImplTest, ResponseCert) { GURL url("https://test.example/"); net::CertificateList certs; @@ -619,7 +571,7 @@ security_details.certificate[1]); } -TEST_P(WebURLLoaderImplTest, ResponseCertWithNoSANs) { +TEST_F(WebURLLoaderImplTest, ResponseCertWithNoSANs) { GURL url("https://test.example/"); net::CertificateList certs; @@ -653,7 +605,7 @@ // Verifies that the lengths used by the PerformanceResourceTiming API are // correctly assigned for sync XHR. -TEST_P(WebURLLoaderImplTest, SyncLengths) { +TEST_F(WebURLLoaderImplTest, SyncLengths) { static const char kBodyData[] = "Today is Thursday"; const int kEncodedBodyLength = 30; const int kEncodedDataLength = 130;
diff --git a/content/renderer/render_frame_impl.cc b/content/renderer/render_frame_impl.cc index f014139..1624e49 100644 --- a/content/renderer/render_frame_impl.cc +++ b/content/renderer/render_frame_impl.cc
@@ -2573,8 +2573,8 @@ routing_id_, callback_id, response)); } -void RenderFrameImpl::OnPortalActivated() { - frame_->OnPortalActivated(); +void RenderFrameImpl::OnPortalActivated(blink::TransferableMessage data) { + frame_->OnPortalActivated(std::move(data)); } void RenderFrameImpl::SetLifecycleState( @@ -4895,7 +4895,7 @@ void RenderFrameImpl::DidHandleOnloadEvents() { if (!frame_->Parent()) { - Send(new FrameHostMsg_DocumentOnLoadCompleted(routing_id_)); + GetFrameHost()->DocumentOnLoadCompleted(); } for (auto& observer : observers_) observer.DidHandleOnloadEvents();
diff --git a/content/renderer/render_frame_impl.h b/content/renderer/render_frame_impl.h index 3115482..6bbcdb43 100644 --- a/content/renderer/render_frame_impl.h +++ b/content/renderer/render_frame_impl.h
@@ -536,7 +536,7 @@ void BlockRequests() override; void ResumeBlockedRequests() override; void CancelBlockedRequests() override; - void OnPortalActivated() override; + void OnPortalActivated(blink::TransferableMessage data) override; void SetLifecycleState(blink::mojom::FrameLifecycleState state) override; #if defined(OS_ANDROID)
diff --git a/content/shell/browser/shell_devtools_bindings.cc b/content/shell/browser/shell_devtools_bindings.cc index 310d629..3f05ffe7 100644 --- a/content/shell/browser/shell_devtools_bindings.cc +++ b/content/shell/browser/shell_devtools_bindings.cc
@@ -10,6 +10,7 @@ #include "base/base64.h" #include "base/bind.h" +#include "base/bind_helpers.h" #include "base/guid.h" #include "base/json/json_reader.h" #include "base/json/json_writer.h" @@ -219,7 +220,8 @@ agent_host_->DispatchProtocolMessage(this, protocol_message); } else if (method == "loadCompleted") { web_contents()->GetMainFrame()->ExecuteJavaScriptForTests( - base::ASCIIToUTF16("DevToolsAPI.setUseSoftMenu(true);")); + base::ASCIIToUTF16("DevToolsAPI.setUseSoftMenu(true);"), + base::NullCallback()); } else if (method == "loadNetworkResource" && params->GetSize() == 3) { // TODO(pfeldman): handle some of the embedder messages in content. std::string url; @@ -299,7 +301,8 @@ preferences_.RemoveWithoutPathExpansion(name, nullptr); } else if (method == "requestFileSystems") { web_contents()->GetMainFrame()->ExecuteJavaScriptForTests( - base::ASCIIToUTF16("DevToolsAPI.fileSystemsLoaded([]);")); + base::ASCIIToUTF16("DevToolsAPI.fileSystemsLoaded([]);"), + base::NullCallback()); } else if (method == "reattach") { if (!agent_host_) return; @@ -327,7 +330,8 @@ base::EscapeJSONString(message, true, ¶m); std::string code = "DevToolsAPI.dispatchMessage(" + param + ");"; base::string16 javascript = base::UTF8ToUTF16(code); - web_contents()->GetMainFrame()->ExecuteJavaScriptForTests(javascript); + web_contents()->GetMainFrame()->ExecuteJavaScriptForTests( + javascript, base::NullCallback()); return; } @@ -340,7 +344,8 @@ std::string code = "DevToolsAPI.dispatchMessageChunk(" + param + "," + std::to_string(pos ? 0 : total_size) + ");"; base::string16 javascript = base::UTF8ToUTF16(code); - web_contents()->GetMainFrame()->ExecuteJavaScriptForTests(javascript); + web_contents()->GetMainFrame()->ExecuteJavaScriptForTests( + javascript, base::NullCallback()); } } @@ -364,7 +369,7 @@ } javascript.append(");"); web_contents()->GetMainFrame()->ExecuteJavaScriptForTests( - base::UTF8ToUTF16(javascript)); + base::UTF8ToUTF16(javascript), base::NullCallback()); } void ShellDevToolsBindings::SendMessageAck(int request_id,
diff --git a/content/shell/browser/web_test/devtools_protocol_test_bindings.cc b/content/shell/browser/web_test/devtools_protocol_test_bindings.cc index 437842c..0a8236a 100644 --- a/content/shell/browser/web_test/devtools_protocol_test_bindings.cc +++ b/content/shell/browser/web_test/devtools_protocol_test_bindings.cc
@@ -5,6 +5,7 @@ #include "content/shell/browser/web_test/devtools_protocol_test_bindings.h" #include "base/bind.h" +#include "base/bind_helpers.h" #include "base/command_line.h" #include "base/json/json_reader.h" #include "base/json/string_escape.h" @@ -120,7 +121,8 @@ base::EscapeJSONString(message, true, ¶m); std::string code = "DevToolsAPI.dispatchMessage(" + param + ");"; base::string16 javascript = base::UTF8ToUTF16(code); - web_contents()->GetMainFrame()->ExecuteJavaScriptForTests(javascript); + web_contents()->GetMainFrame()->ExecuteJavaScriptForTests( + javascript, base::NullCallback()); return; } @@ -133,7 +135,8 @@ std::string code = "DevToolsAPI.dispatchMessageChunk(" + param + "," + std::to_string(pos ? 0 : total_size) + ");"; base::string16 javascript = base::UTF8ToUTF16(code); - web_contents()->GetMainFrame()->ExecuteJavaScriptForTests(javascript); + web_contents()->GetMainFrame()->ExecuteJavaScriptForTests( + javascript, base::NullCallback()); } }
diff --git a/content/shell/browser/web_test/web_test_devtools_bindings.cc b/content/shell/browser/web_test/web_test_devtools_bindings.cc index 24a1b7f..740b00b4 100644 --- a/content/shell/browser/web_test/web_test_devtools_bindings.cc +++ b/content/shell/browser/web_test/web_test_devtools_bindings.cc
@@ -6,6 +6,7 @@ #include <memory> +#include "base/bind_helpers.h" #include "base/command_line.h" #include "base/path_service.h" #include "base/strings/string_util.h" @@ -119,7 +120,8 @@ ShellDevToolsBindings::Attach(); web_contents()->GetMainFrame()->ExecuteJavaScriptForTests( base::UTF8ToUTF16("TestRunner._startupTestSetupFinished();\n//# " - "sourceURL=layout_test_devtools_bindings.cc")); + "sourceURL=layout_test_devtools_bindings.cc"), + base::NullCallback()); } WebTestDevToolsBindings::WebTestDevToolsBindings(
diff --git a/content/test/accessibility_browser_test_utils.cc b/content/test/accessibility_browser_test_utils.cc index 5e2b3ebc..820911a 100644 --- a/content/test/accessibility_browser_test_utils.cc +++ b/content/test/accessibility_browser_test_utils.cc
@@ -21,51 +21,35 @@ AccessibilityNotificationWaiter::AccessibilityNotificationWaiter( WebContents* web_contents) - : event_to_wait_for_(ax::mojom::Event::kNone), + : WebContentsObserver(web_contents), loop_runner_(new MessageLoopRunner()), - event_target_id_(0), - event_render_frame_host_(nullptr), weak_factory_(this) { - frame_host_ = static_cast<RenderFrameHostImpl*>( - web_contents->GetMainFrame()); - frame_host_->SetAccessibilityCallbackForTesting( - base::Bind(&AccessibilityNotificationWaiter::OnAccessibilityEvent, - weak_factory_.GetWeakPtr())); + RenderFrameHostChanged(nullptr, web_contents->GetMainFrame()); } AccessibilityNotificationWaiter::AccessibilityNotificationWaiter( WebContents* web_contents, ui::AXMode accessibility_mode, ax::mojom::Event event_type) - : event_to_wait_for_(event_type), + : WebContentsObserver(web_contents), + event_to_wait_for_(event_type), loop_runner_(new MessageLoopRunner()), - event_target_id_(0), weak_factory_(this) { - WebContentsImpl* web_contents_impl = static_cast<WebContentsImpl*>( - web_contents); - frame_host_ = static_cast<RenderFrameHostImpl*>( - web_contents_impl->GetMainFrame()); - frame_host_->SetAccessibilityCallbackForTesting( - base::Bind(&AccessibilityNotificationWaiter::OnAccessibilityEvent, - weak_factory_.GetWeakPtr())); - web_contents_impl->AddAccessibilityMode(accessibility_mode); + RenderFrameHostChanged(nullptr, web_contents->GetMainFrame()); + static_cast<WebContentsImpl*>(web_contents) + ->AddAccessibilityMode(accessibility_mode); } AccessibilityNotificationWaiter::AccessibilityNotificationWaiter( RenderFrameHostImpl* frame_host, ax::mojom::Event event_type) - : frame_host_(frame_host), - event_to_wait_for_(event_type), + : event_to_wait_for_(event_type), loop_runner_(new MessageLoopRunner()), - event_target_id_(0), weak_factory_(this) { - frame_host_->SetAccessibilityCallbackForTesting( - base::Bind(&AccessibilityNotificationWaiter::OnAccessibilityEvent, - weak_factory_.GetWeakPtr())); + RenderFrameHostChanged(nullptr, frame_host); } -AccessibilityNotificationWaiter::~AccessibilityNotificationWaiter() { -} +AccessibilityNotificationWaiter::~AccessibilityNotificationWaiter() {} void AccessibilityNotificationWaiter::ListenToAdditionalFrame( RenderFrameHostImpl* frame_host) { @@ -85,9 +69,7 @@ const ui::AXTree& AccessibilityNotificationWaiter::GetAXTree() const { static base::NoDestructor<ui::AXTree> empty_tree; const ui::AXTree* tree = frame_host_->GetAXTreeForTesting(); - if (tree) - return *tree; - return *empty_tree; + return tree ? *tree : *empty_tree; } void AccessibilityNotificationWaiter::OnAccessibilityEvent( @@ -109,4 +91,14 @@ return GetAXTree().data().url == url::kAboutBlankURL; } +// WebContentsObserver override: +void AccessibilityNotificationWaiter::RenderFrameHostChanged( + RenderFrameHost* old_host, + RenderFrameHost* new_host) { + if (frame_host_ != old_host) + return; + frame_host_ = static_cast<RenderFrameHostImpl*>(new_host); + ListenToAdditionalFrame(frame_host_); +} + } // namespace content
diff --git a/content/test/accessibility_browser_test_utils.h b/content/test/accessibility_browser_test_utils.h index 5c0a4df..d283d97 100644 --- a/content/test/accessibility_browser_test_utils.h +++ b/content/test/accessibility_browser_test_utils.h
@@ -7,6 +7,7 @@ #include "base/macros.h" #include "base/memory/weak_ptr.h" +#include "content/public/browser/web_contents_observer.h" #include "ui/accessibility/ax_mode.h" #include "ui/accessibility/ax_node_data.h" #include "ui/accessibility/ax_tree.h" @@ -22,7 +23,7 @@ // clicking on a button). Then call WaitForNotification // afterwards to block until the specified accessibility notification has been // received. -class AccessibilityNotificationWaiter { +class AccessibilityNotificationWaiter : public WebContentsObserver { public: explicit AccessibilityNotificationWaiter(WebContents* web_contents); AccessibilityNotificationWaiter(WebContents* web_contents, @@ -30,7 +31,7 @@ ax::mojom::Event event); AccessibilityNotificationWaiter(RenderFrameHostImpl* frame_host, ax::mojom::Event event); - ~AccessibilityNotificationWaiter(); + ~AccessibilityNotificationWaiter() override; void ListenToAdditionalFrame(RenderFrameHostImpl* frame_host); @@ -53,6 +54,10 @@ return event_render_frame_host_; } + // WebContentsObserver override: + void RenderFrameHostChanged(RenderFrameHost* old_host, + RenderFrameHost* new_host) override; + private: // Callback from RenderViewHostImpl. void OnAccessibilityEvent(content::RenderFrameHostImpl* rfhi, @@ -63,11 +68,11 @@ // GetAXTree() is about the page with the url "about:blank". bool IsAboutBlank(); - RenderFrameHostImpl* frame_host_; - ax::mojom::Event event_to_wait_for_; + RenderFrameHostImpl* frame_host_ = nullptr; + ax::mojom::Event event_to_wait_for_ = ax::mojom::Event::kNone; scoped_refptr<MessageLoopRunner> loop_runner_; - int event_target_id_; - RenderFrameHostImpl* event_render_frame_host_; + int event_target_id_ = 0; + RenderFrameHostImpl* event_render_frame_host_ = nullptr; base::WeakPtrFactory<AccessibilityNotificationWaiter> weak_factory_;
diff --git a/content/test/data/accessibility/event/name-change-expected-auralinux.txt b/content/test/data/accessibility/event/name-change-expected-auralinux.txt new file mode 100644 index 0000000..63ee010 --- /dev/null +++ b/content/test/data/accessibility/event/name-change-expected-auralinux.txt
@@ -0,0 +1 @@ +NAME-CHANGED:After role=ROLE_HEADING name='After' ENABLED,SENSITIVE,SHOWING,VISIBLE
diff --git a/content/test/gpu/gpu_tests/webgl_conformance_expectations.py b/content/test/gpu/gpu_tests/webgl_conformance_expectations.py index fb67954..0f6bbda4 100644 --- a/content/test/gpu/gpu_tests/webgl_conformance_expectations.py +++ b/content/test/gpu/gpu_tests/webgl_conformance_expectations.py
@@ -136,8 +136,6 @@ ['win', 'opengl'], bug=920033) # Passthrough command decoder / OpenGL - self.Fail('conformance/renderbuffers/framebuffer-test.html', - ['passthrough', 'opengl'], bug=665521) self.Fail( 'conformance/textures/canvas/tex-2d-alpha-alpha-unsigned_byte.html', ['passthrough', 'opengl'], bug=2952) # angle bug ID
diff --git a/content/test/navigation_simulator_impl.cc b/content/test/navigation_simulator_impl.cc index 6e713de..0ec76675 100644 --- a/content/test/navigation_simulator_impl.cc +++ b/content/test/navigation_simulator_impl.cc
@@ -312,6 +312,7 @@ ? render_frame_host->frame_tree_node() : web_contents->GetMainFrame()->frame_tree_node()), request_(nullptr), + original_url_(original_url), navigation_url_(original_url), initial_method_("GET"), browser_initiated_(browser_initiated), @@ -361,6 +362,7 @@ CHECK(render_frame_host_); CHECK_EQ(frame_tree_node_, request_->frame_tree_node()); state_ = STARTED; + original_url_ = request->commit_params().original_url; navigation_url_ = handle->GetURL(); // |remote_endpoint_| cannot be inferred from the request. // |initial_method_| cannot be set after the request has started. @@ -1189,7 +1191,7 @@ std::unique_ptr<FrameHostMsg_DidCommitProvisionalLoad_Params> params = std::make_unique<FrameHostMsg_DidCommitProvisionalLoad_Params>(); params->url = navigation_url_; - params->original_request_url = navigation_url_; + params->original_request_url = original_url_; params->referrer = referrer_; params->contents_mime_type = contents_mime_type_; params->transition = transition_;
diff --git a/content/test/navigation_simulator_impl.h b/content/test/navigation_simulator_impl.h index d71d1c8..c8ef0c6 100644 --- a/content/test/navigation_simulator_impl.h +++ b/content/test/navigation_simulator_impl.h
@@ -220,6 +220,7 @@ // Note: additional parameters to modify the navigation should be properly // initialized (if needed) in InitializeFromStartedRequest. + GURL original_url_; GURL navigation_url_; net::IPEndPoint remote_endpoint_; bool is_signed_exchange_inner_response_ = false;
diff --git a/content/test/test_render_frame.cc b/content/test/test_render_frame.cc index 6f60b98..e89106ad 100644 --- a/content/test/test_render_frame.cc +++ b/content/test/test_render_frame.cc
@@ -139,6 +139,8 @@ void CancelInitialHistoryLoad() override {} + void DocumentOnLoadCompleted() override {} + void UpdateEncoding(const std::string& encoding_name) override {} void FrameSizeChanged(const gfx::Size& frame_size) override {}
diff --git a/device/fido/pin.h b/device/fido/pin.h index 0d13397..3a59518 100644 --- a/device/fido/pin.h +++ b/device/fido/pin.h
@@ -15,6 +15,7 @@ #include <string> #include <vector> +#include "base/component_export.h" #include "base/containers/span.h" #include "base/optional.h" #include "components/cbor/values.h" @@ -28,7 +29,7 @@ // IsValid returns true if |pin|, which must be UTF-8, is a syntactically valid // PIN. -bool IsValid(const std::string& pin); +COMPONENT_EXPORT(DEVICE_FIDO) bool IsValid(const std::string& pin); // kMinBytes is the minimum number of *bytes* of PIN data that a CTAP2 device // will accept. Since the PIN is UTF-8 encoded, this could be a single code
diff --git a/extensions/browser/api/system_storage/system_storage_eject_apitest.cc b/extensions/browser/api/system_storage/system_storage_eject_apitest.cc index f96cf3d..5fb7179 100644 --- a/extensions/browser/api/system_storage/system_storage_eject_apitest.cc +++ b/extensions/browser/api/system_storage/system_storage_eject_apitest.cc
@@ -4,6 +4,7 @@ // // SystemStorage eject API browser tests. +#include "base/bind_helpers.h" #include "base/files/file_path.h" #include "base/macros.h" #include "base/strings/stringprintf.h" @@ -60,7 +61,7 @@ const std::string& ok_message) { ExtensionTestMessageListener listener(ok_message, false); host->GetMainFrame()->ExecuteJavaScriptForTests( - base::ASCIIToUTF16(js_command)); + base::ASCIIToUTF16(js_command), base::NullCallback()); EXPECT_TRUE(listener.WaitUntilSatisfied()); }
diff --git a/fuchsia/engine/browser/frame_impl.cc b/fuchsia/engine/browser/frame_impl.cc index 1469419..e1e2e6b 100644 --- a/fuchsia/engine/browser/frame_impl.cc +++ b/fuchsia/engine/browser/frame_impl.cc
@@ -8,6 +8,7 @@ #include <string> +#include "base/bind_helpers.h" #include "base/fuchsia/fuchsia_logging.h" #include "base/logging.h" #include "base/run_loop.h" @@ -326,7 +327,8 @@ return; } - web_contents_->GetMainFrame()->ExecuteJavaScript(script_utf16); + web_contents_->GetMainFrame()->ExecuteJavaScript(script_utf16, + base::NullCallback()); } else { // Store the script as UTF16 shared memory buffer, so that it can be // used directly by renderers without string format conversions.
diff --git a/gpu/command_buffer/service/gles2_cmd_decoder_passthrough.cc b/gpu/command_buffer/service/gles2_cmd_decoder_passthrough.cc index 805d9ae..2165fb9 100644 --- a/gpu/command_buffer/service/gles2_cmd_decoder_passthrough.cc +++ b/gpu/command_buffer/service/gles2_cmd_decoder_passthrough.cc
@@ -779,7 +779,6 @@ "GL_OES_EGL_image", "GL_OES_EGL_image_external", "GL_OES_EGL_image_external_essl3", - "GL_OES_fbo_render_mipmap", "GL_OES_packed_depth_stencil", "GL_OES_rgb8_rgba8", "GL_OES_vertex_array_object",
diff --git a/infra/config/luci-milo.cfg b/infra/config/luci-milo.cfg index 12c6551..7aa1ebe 100644 --- a/infra/config/luci-milo.cfg +++ b/infra/config/luci-milo.cfg
@@ -1931,6 +1931,11 @@ short_name: "rel" } builders { + name: "buildbucket/luci.chrome.ci/ToTMacOfficial" + category: "ToT Mac" + short_name: "ofi" + } + builders { name: "buildbucket/luci.chromium.ci/ToTMac (dbg)" category: "ToT Mac" short_name: "dbg" @@ -2143,6 +2148,11 @@ short_name: "rel" } builders { + name: "buildbucket/luci.chrome.ci/ToTMacOfficial" + category: "ToT Mac" + short_name: "ofi" + } + builders { name: "buildbucket/luci.chromium.ci/ToTMac (dbg)" category: "ToT Mac" short_name: "dbg"
diff --git a/ios/chrome/app/BUILD.gn b/ios/chrome/app/BUILD.gn index fdc3516af..12eae20 100644 --- a/ios/chrome/app/BUILD.gn +++ b/ios/chrome/app/BUILD.gn
@@ -227,6 +227,7 @@ "//ios/chrome/browser/ui/webui:webui_internal", "//ios/chrome/browser/upgrade", "//ios/chrome/browser/url_loading", + "//ios/chrome/browser/url_loading:app", "//ios/chrome/browser/variations:ios_chrome_ui_string_overrider_factory", "//ios/chrome/browser/voice", "//ios/chrome/browser/web",
diff --git a/ios/chrome/app/main_controller.mm b/ios/chrome/app/main_controller.mm index 56f70e2..f6c1c9d0 100644 --- a/ios/chrome/app/main_controller.mm +++ b/ios/chrome/app/main_controller.mm
@@ -135,6 +135,7 @@ #include "ios/chrome/browser/ui/util/ui_util.h" #import "ios/chrome/browser/ui/util/uikit_ui_util.h" #import "ios/chrome/browser/ui/webui/chrome_web_ui_ios_controller_factory.h" +#import "ios/chrome/browser/url_loading/app_url_loading_service.h" #import "ios/chrome/browser/url_loading/url_loading_service.h" #import "ios/chrome/browser/url_loading/url_loading_service_factory.h" #import "ios/chrome/browser/web/tab_id_tab_helper.h" @@ -306,13 +307,14 @@ } // namespace -@interface MainController ()<BrowserStateStorageSwitching, - GoogleServicesNavigationCoordinatorDelegate, - PrefObserverDelegate, - SettingsNavigationControllerDelegate, - TabModelObserver, - TabSwitcherDelegate, - UserFeedbackDataSource> { +@interface MainController () <AppURLLoadingServiceDelegate, + BrowserStateStorageSwitching, + GoogleServicesNavigationCoordinatorDelegate, + PrefObserverDelegate, + SettingsNavigationControllerDelegate, + TabModelObserver, + TabSwitcherDelegate, + UserFeedbackDataSource> { IBOutlet UIWindow* _window; // Weak; owned by the ChromeBrowserProvider. @@ -414,6 +416,10 @@ // Hander for the startup tasks, deferred or not. StartupTasks* _startupTasks; + + // The application level component for url loading. Is passed down to + // browser state level UrlLoadingService instances. + AppUrlLoadingService* _appURLLoadingService; } // The main coordinator, lazily created the first time it is accessed. Manages @@ -730,6 +736,9 @@ [_restoreHelper moveAsideSessionInformation]; } + _appURLLoadingService = new AppUrlLoadingService(); + _appURLLoadingService->SetDelegate(self); + // Initialize and set the main browser state. [self initializeBrowserState:chromeBrowserState]; _mainBrowserState = chromeBrowserState; @@ -738,6 +747,7 @@ [[BrowserViewWrangler alloc] initWithBrowserState:_mainBrowserState tabModelObserver:self applicationCommandEndpoint:self + appURLLoadingService:_appURLLoadingService storageSwitcher:self]; // Force an obvious initialization of the AuthenticationService. This must @@ -1813,6 +1823,14 @@ completion:nil]; } +#pragma mark - AppURLLoadingServiceDelegate + +- (void)openURLInNewTabWithCommand:(OpenNewTabCommand*)command { + // TODO(crbug.com/907527): instead of AppUrlLoadingService calling + // openURLInNewTab, make openURLInNewTab call AppUrlLoadingService. + [self openURLInNewTab:command]; +} + #pragma mark - ApplicationCommands helpers - (void)openUrlFromSettings:(OpenNewTabCommand*)command {
diff --git a/ios/chrome/browser/about_flags.mm b/ios/chrome/browser/about_flags.mm index 4217b33..d9aa65c 100644 --- a/ios/chrome/browser/about_flags.mm +++ b/ios/chrome/browser/about_flags.mm
@@ -313,12 +313,6 @@ {"autofill-dynamic-forms", flag_descriptions::kAutofillDynamicFormsName, flag_descriptions::kAutofillDynamicFormsDescription, flags_ui::kOsIos, FEATURE_VALUE_TYPE(autofill::features::kAutofillDynamicForms)}, - {"autofill-no-local-save-on-upload-success", - flag_descriptions::kAutofillNoLocalSaveOnUploadSuccessName, - flag_descriptions::kAutofillNoLocalSaveOnUploadSuccessDescription, - flags_ui::kOsIos, - FEATURE_VALUE_TYPE( - autofill::features::kAutofillNoLocalSaveOnUploadSuccess)}, {"autofill-prefilled-fields", flag_descriptions::kAutofillPrefilledFieldsName, flag_descriptions::kAutofillPrefilledFieldsDescription, flags_ui::kOsIos, @@ -580,6 +574,12 @@ flag_descriptions::kStorePendingItemInContextName, flag_descriptions::kStorePendingItemInContextDescription, flags_ui::kOsIos, FEATURE_VALUE_TYPE(web::features::kStorePendingItemInContext)}, + {"autofill-no-local-save-on-upload-success", + flag_descriptions::kAutofillNoLocalSaveOnUploadSuccessName, + flag_descriptions::kAutofillNoLocalSaveOnUploadSuccessDescription, + flags_ui::kOsIos, + FEATURE_VALUE_TYPE( + autofill::features::kAutofillNoLocalSaveOnUploadSuccess)}, }; // Add all switches from experimental flags to |command_line|.
diff --git a/ios/chrome/browser/app_startup_parameters.h b/ios/chrome/browser/app_startup_parameters.h index 368e8686..190cf2be 100644 --- a/ios/chrome/browser/app_startup_parameters.h +++ b/ios/chrome/browser/app_startup_parameters.h
@@ -42,10 +42,9 @@ @property(nonatomic, assign) std::map<std::string, std::string> externalURLParams; -//// Boolean to track if a voice search is requested at startup. -//@property(nonatomic, readwrite, assign) BOOL launchVoiceSearch; // Boolean to track if the app should launch in incognito mode. @property(nonatomic, readwrite, assign) BOOL launchInIncognito; +// Action to be taken after opening the initial NTP. @property(nonatomic, readwrite, assign) NTPTabOpeningPostOpeningAction postOpeningAction; // Boolean to track if a Payment Request response is requested at startup.
diff --git a/ios/chrome/browser/ui/autofill/form_input_accessory_coordinator.mm b/ios/chrome/browser/ui/autofill/form_input_accessory_coordinator.mm index 8b1d85df..fdbf5f41 100644 --- a/ios/chrome/browser/ui/autofill/form_input_accessory_coordinator.mm +++ b/ios/chrome/browser/ui/autofill/form_input_accessory_coordinator.mm
@@ -99,6 +99,7 @@ - (void)stop { [self stopChildren]; [self.formInputAccessoryViewController restoreOriginalKeyboardView]; + [self.formInputAccessoryMediator disconnect]; } #pragma mark - Presenting Children
diff --git a/ios/chrome/browser/ui/autofill/form_input_accessory_mediator.h b/ios/chrome/browser/ui/autofill/form_input_accessory_mediator.h index ab03936..0f58f53 100644 --- a/ios/chrome/browser/ui/autofill/form_input_accessory_mediator.h +++ b/ios/chrome/browser/ui/autofill/form_input_accessory_mediator.h
@@ -52,6 +52,9 @@ // consumer. - (void)enableSuggestions; +// Stops observing all objects. +- (void)disconnect; + @end // Methods to allow injection in tests.
diff --git a/ios/chrome/browser/ui/autofill/form_input_accessory_mediator.mm b/ios/chrome/browser/ui/autofill/form_input_accessory_mediator.mm index 35badd5a..2fef18231 100644 --- a/ios/chrome/browser/ui/autofill/form_input_accessory_mediator.mm +++ b/ios/chrome/browser/ui/autofill/form_input_accessory_mediator.mm
@@ -204,6 +204,15 @@ } - (void)dealloc { + [self disconnect]; +} + +- (void)disconnect { + _formActivityObserverBridge.reset(); + if (_personalDataManager && _personalDataManagerObserver.get()) { + _personalDataManager->RemoveObserver(_personalDataManagerObserver.get()); + _personalDataManagerObserver.reset(); + } if (_webState) { _webState->RemoveObserver(_webStateObserverBridge.get()); _webStateObserverBridge.reset(); @@ -214,10 +223,6 @@ _webStateListObserver.reset(); _webStateList = nullptr; } - _formActivityObserverBridge.reset(); - if (_personalDataManager) { - _personalDataManager->RemoveObserver(_personalDataManagerObserver.get()); - } } - (void)detachFromWebState { @@ -519,7 +524,7 @@ return; } FormSuggestionsReadyCompletion formSuggestionsReadyCompletion = - [self accessoryViewReadyBlockWithCompletion:completion]; + [strongSelf accessoryViewReadyBlockWithCompletion:completion]; [provider retrieveSuggestionsForForm:params webState:strongSelf.webState accessoryViewUpdateBlock:formSuggestionsReadyCompletion];
diff --git a/ios/chrome/browser/ui/autofill/manual_fill/fallback_coordinator_egtest.mm b/ios/chrome/browser/ui/autofill/manual_fill/fallback_coordinator_egtest.mm index de9ffa06..c0d77946 100644 --- a/ios/chrome/browser/ui/autofill/manual_fill/fallback_coordinator_egtest.mm +++ b/ios/chrome/browser/ui/autofill/manual_fill/fallback_coordinator_egtest.mm
@@ -597,6 +597,73 @@ assertWithMatcher:grey_sufficientlyVisible()]; } +// Tests the mediator stops observing objects when the incognito BVC is +// destroyed. Waiting for dealloc was causing a race condition with the +// autorelease pool, and some times a DCHECK will be hit. +- (void)testOpeningIncognitoTabsDoNotLeak { + const GURL URL = self.testServer->GetURL(kFormHTMLFile); + NSString* omniboxText = base::SysUTF8ToNSString(URL.spec() + "\n"); + std::string webViewText("Profile form"); + AddAutofillProfile(_personalDataManager); + + [[EarlGrey selectElementWithMatcher:chrome_test_util::WebViewMatcher()] + performAction:chrome_test_util::TapWebElement(kFormElementCity)]; + + // Verify the profiles icon is visible. + [[EarlGrey selectElementWithMatcher:ProfilesIconMatcher()] + assertWithMatcher:grey_sufficientlyVisible()]; + + // Open a tab in incognito. + [ChromeEarlGrey openNewIncognitoTab]; + [ChromeEarlGreyUI focusOmniboxAndType:omniboxText]; + [ChromeEarlGrey waitForWebViewContainingText:webViewText]; + + [[EarlGrey selectElementWithMatcher:chrome_test_util::WebViewMatcher()] + performAction:chrome_test_util::TapWebElement(kFormElementCity)]; + + // Verify the profiles icon is visible. + [[EarlGrey selectElementWithMatcher:ProfilesIconMatcher()] + assertWithMatcher:grey_sufficientlyVisible()]; + + [ChromeEarlGrey closeCurrentTab]; + [ChromeEarlGrey openNewTab]; + [ChromeEarlGrey loadURL:URL]; + [ChromeEarlGrey waitForWebViewContainingText:webViewText]; + + // Bring up the keyboard by tapping the city, which is the element before the + // picker. + [[EarlGrey selectElementWithMatcher:chrome_test_util::WebViewMatcher()] + performAction:chrome_test_util::TapWebElement(kFormElementCity)]; + + // Verify the profiles icon is visible. + [[EarlGrey selectElementWithMatcher:ProfilesIconMatcher()] + assertWithMatcher:grey_sufficientlyVisible()]; + + // Open a tab in incognito. + [ChromeEarlGrey openNewIncognitoTab]; + [ChromeEarlGreyUI focusOmniboxAndType:omniboxText]; + [ChromeEarlGrey waitForWebViewContainingText:webViewText]; + + // Bring up the keyboard by tapping the city, which is the element before the + // picker. + [[EarlGrey selectElementWithMatcher:chrome_test_util::WebViewMatcher()] + performAction:chrome_test_util::TapWebElement(kFormElementCity)]; + + // Open a regular tab. + [ChromeEarlGrey openNewTab]; + [ChromeEarlGrey loadURL:URL]; + [ChromeEarlGrey waitForWebViewContainingText:webViewText]; + + // Bring up the keyboard by tapping the city, which is the element before the + // picker. + [[EarlGrey selectElementWithMatcher:chrome_test_util::WebViewMatcher()] + performAction:chrome_test_util::TapWebElement(kFormElementCity)]; + + // This will fail if there is more than one profiles icon in the hierarchy. + [[EarlGrey selectElementWithMatcher:ProfilesIconMatcher()] + assertWithMatcher:grey_sufficientlyVisible()]; +} + // Tests that the manual fallback view is not duplicated after incognito. - (void)testReturningFromIncognitoDoesNotDuplicatesManualFallbackMenu { // Add the profile to use for verification.
diff --git a/ios/chrome/browser/ui/main/BUILD.gn b/ios/chrome/browser/ui/main/BUILD.gn index c1838cc..a32728e4 100644 --- a/ios/chrome/browser/ui/main/BUILD.gn +++ b/ios/chrome/browser/ui/main/BUILD.gn
@@ -50,6 +50,7 @@ "//ios/chrome/browser/ui/snackbar", "//ios/chrome/browser/ui/translate", "//ios/chrome/browser/url_loading", + "//ios/chrome/browser/url_loading:app", "//ios/chrome/browser/web", "//ios/chrome/browser/web:tab_helper_delegates", "//ios/chrome/browser/web:web_internal",
diff --git a/ios/chrome/browser/ui/main/browser_coordinator.h b/ios/chrome/browser/ui/main/browser_coordinator.h index 88b6480a..29f4873 100644 --- a/ios/chrome/browser/ui/main/browser_coordinator.h +++ b/ios/chrome/browser/ui/main/browser_coordinator.h
@@ -12,6 +12,8 @@ @class BrowserViewController; @class TabModel; +class AppUrlLoadingService; + // Coordinator for BrowserViewController. @interface BrowserCoordinator : ChromeCoordinator @@ -29,6 +31,10 @@ // Command handler for ApplicationCommands. @property(nonatomic, weak) id<ApplicationCommands> applicationCommandHandler; +// The application level component for url loading. Should be used only by +// browser state level UrlLoadingService instances. +@property(nonatomic, assign) AppUrlLoadingService* appURLLoadingService; + // The tab model. @property(nonatomic, weak, readonly) TabModel* tabModel;
diff --git a/ios/chrome/browser/ui/main/browser_coordinator.mm b/ios/chrome/browser/ui/main/browser_coordinator.mm index 02885bd..8ff84ef 100644 --- a/ios/chrome/browser/ui/main/browser_coordinator.mm +++ b/ios/chrome/browser/ui/main/browser_coordinator.mm
@@ -428,10 +428,6 @@ #pragma mark - URLLoadingServiceDelegate -- (void)openURLInNewTabWithCommand:(OpenNewTabCommand*)command { - [self.viewController.dispatcher openURLInNewTab:command]; -} - - (void)animateOpenBackgroundTabFromCommand:(OpenNewTabCommand*)command completion:(void (^)())completion { [self.viewController @@ -497,6 +493,7 @@ UrlLoadingService* urlLoadingService = UrlLoadingServiceFactory::GetForBrowserState(self.browserState); if (urlLoadingService) { + urlLoadingService->SetAppService(self.appURLLoadingService); urlLoadingService->SetDelegate(self); urlLoadingService->SetBrowser(self.browser); } @@ -507,6 +504,7 @@ UrlLoadingService* urlLoadingService = UrlLoadingServiceFactory::GetForBrowserState(self.browserState); if (urlLoadingService) { + urlLoadingService->SetAppService(nullptr); urlLoadingService->SetDelegate(nil); urlLoadingService->SetBrowser(nil); }
diff --git a/ios/chrome/browser/ui/main/browser_view_wrangler.h b/ios/chrome/browser/ui/main/browser_view_wrangler.h index 0d86aac..7de0c6fb 100644 --- a/ios/chrome/browser/ui/main/browser_view_wrangler.h +++ b/ios/chrome/browser/ui/main/browser_view_wrangler.h
@@ -14,6 +14,8 @@ @class DeviceSharingManager; @protocol TabModelObserver; +class AppUrlLoadingService; + namespace ios { class ChromeBrowserState; } @@ -41,6 +43,7 @@ tabModelObserver:(id<TabModelObserver>)tabModelObserver applicationCommandEndpoint: (id<ApplicationCommands>)applicationCommandEndpoint + appURLLoadingService:(AppUrlLoadingService*)appURLLoadingService storageSwitcher: (id<BrowserStateStorageSwitching>)storageSwitcher NS_DESIGNATED_INITIALIZER;
diff --git a/ios/chrome/browser/ui/main/browser_view_wrangler.mm b/ios/chrome/browser/ui/main/browser_view_wrangler.mm index 7880fb8..342591c7 100644 --- a/ios/chrome/browser/ui/main/browser_view_wrangler.mm +++ b/ios/chrome/browser/ui/main/browser_view_wrangler.mm
@@ -20,6 +20,7 @@ #import "ios/chrome/browser/ui/browser_view_controller.h" #import "ios/chrome/browser/ui/browser_view_controller_dependency_factory.h" #import "ios/chrome/browser/ui/main/browser_coordinator.h" +#import "ios/chrome/browser/url_loading/app_url_loading_service.h" #include "ios/public/provider/chrome/browser/chrome_browser_provider.h" #import "ios/web/public/web_state/web_state.h" @@ -87,6 +88,7 @@ __weak id<TabModelObserver> _tabModelObserver; __weak id<ApplicationCommands> _applicationCommandEndpoint; __weak id<BrowserStateStorageSwitching> _storageSwitcher; + AppUrlLoadingService* _appURLLoadingService; BOOL _isShutdown; std::unique_ptr<Browser> _mainBrowser; @@ -137,12 +139,14 @@ tabModelObserver:(id<TabModelObserver>)tabModelObserver applicationCommandEndpoint: (id<ApplicationCommands>)applicationCommandEndpoint + appURLLoadingService:(AppUrlLoadingService*)appURLLoadingService storageSwitcher: (id<BrowserStateStorageSwitching>)storageSwitcher { if ((self = [super init])) { _browserState = browserState; _tabModelObserver = tabModelObserver; _applicationCommandEndpoint = applicationCommandEndpoint; + _appURLLoadingService = appURLLoadingService; _storageSwitcher = storageSwitcher; } return self; @@ -414,6 +418,7 @@ [[BrowserCoordinator alloc] initWithBaseViewController:nil browser:browser]; coordinator.applicationCommandHandler = _applicationCommandEndpoint; + coordinator.appURLLoadingService = _appURLLoadingService; return coordinator; }
diff --git a/ios/chrome/browser/ui/main/browser_view_wrangler_unittest.mm b/ios/chrome/browser/ui/main/browser_view_wrangler_unittest.mm index c4a0e2b4..341aa32c 100644 --- a/ios/chrome/browser/ui/main/browser_view_wrangler_unittest.mm +++ b/ios/chrome/browser/ui/main/browser_view_wrangler_unittest.mm
@@ -37,6 +37,7 @@ initWithBrowserState:chrome_browser_state_.get() tabModelObserver:nil applicationCommandEndpoint:(id<ApplicationCommands>)nil + appURLLoadingService:nil storageSwitcher:nil]; [wrangler createMainBrowser]; // Test that BVC is created on demand.
diff --git a/ios/chrome/browser/url_loading/BUILD.gn b/ios/chrome/browser/url_loading/BUILD.gn index 8c55616..0ede5a8 100644 --- a/ios/chrome/browser/url_loading/BUILD.gn +++ b/ios/chrome/browser/url_loading/BUILD.gn
@@ -23,6 +23,7 @@ "url_loading_util.mm", ] deps = [ + ":app", "//base", "//components/keyed_service/ios", "//components/sessions", @@ -43,6 +44,24 @@ ] } +source_set("app") { + configs += [ "//build/config/compiler:enable_arc" ] + sources = [ + "app_url_loading_service.h", + "app_url_loading_service.mm", + "test_app_url_loading_service.h", + "test_app_url_loading_service.mm", + ] + deps = [ + "//base", + "//ios/chrome/browser", + "//ios/chrome/browser/main", + "//ios/chrome/browser/ui/commands", + "//ui/base", + "//url", + ] +} + source_set("unit_tests") { configs += [ "//build/config/compiler:enable_arc" ] testonly = true @@ -50,6 +69,7 @@ "url_loading_service_unittest.mm", ] deps = [ + ":app", ":url_loading", "//base", "//base/test:test_support",
diff --git a/ios/chrome/browser/url_loading/app_url_loading_service.h b/ios/chrome/browser/url_loading/app_url_loading_service.h new file mode 100644 index 0000000..bb10ada8 --- /dev/null +++ b/ios/chrome/browser/url_loading/app_url_loading_service.h
@@ -0,0 +1,37 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef IOS_CHROME_BROWSER_URL_LOADING_APP_URL_LOADING_SERVICE_H_ +#define IOS_CHROME_BROWSER_URL_LOADING_APP_URL_LOADING_SERVICE_H_ + +#import <Foundation/Foundation.h> +#import <UIKit/UIKit.h> + +@class OpenNewTabCommand; + +// Objective-C delegate for AppUrlLoadingService. +@protocol AppURLLoadingServiceDelegate + +// Implementing delegate must open the url in |command| in a new tab. +// TODO(crbug.com/907527): split into simpler actions, like dismissModals, +// switchModeIfneeded, etc. +- (void)openURLInNewTabWithCommand:(OpenNewTabCommand*)command; + +@end + +// Service used to manage url loading at application level. +class AppUrlLoadingService { + public: + AppUrlLoadingService(); + + void SetDelegate(id<AppURLLoadingServiceDelegate> delegate); + + // Opens a url based on |command| in a new tab. + virtual void LoadUrlInNewTab(OpenNewTabCommand* command); + + private: + __weak id<AppURLLoadingServiceDelegate> delegate_; +}; + +#endif // IOS_CHROME_BROWSER_URL_LOADING_APP_URL_LOADING_SERVICE_H_
diff --git a/ios/chrome/browser/url_loading/app_url_loading_service.mm b/ios/chrome/browser/url_loading/app_url_loading_service.mm new file mode 100644 index 0000000..cecdf31 --- /dev/null +++ b/ios/chrome/browser/url_loading/app_url_loading_service.mm
@@ -0,0 +1,24 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#import "ios/chrome/browser/url_loading/app_url_loading_service.h" + +#import "ios/chrome/browser/main/browser.h" +#import "ios/chrome/browser/ui/commands/open_new_tab_command.h" + +#if !defined(__has_feature) || !__has_feature(objc_arc) +#error "This file requires ARC support." +#endif + +AppUrlLoadingService::AppUrlLoadingService() {} + +void AppUrlLoadingService::SetDelegate( + id<AppURLLoadingServiceDelegate> delegate) { + delegate_ = delegate; +} + +void AppUrlLoadingService::LoadUrlInNewTab(OpenNewTabCommand* command) { + DCHECK(delegate_); + [delegate_ openURLInNewTabWithCommand:command]; +}
diff --git a/ios/chrome/browser/url_loading/test_app_url_loading_service.h b/ios/chrome/browser/url_loading/test_app_url_loading_service.h new file mode 100644 index 0000000..32a66e0 --- /dev/null +++ b/ios/chrome/browser/url_loading/test_app_url_loading_service.h
@@ -0,0 +1,25 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef IOS_CHROME_BROWSER_URL_LOADING_TEST_APP_URL_LOADING_SERVICE_H_ +#define IOS_CHROME_BROWSER_URL_LOADING_TEST_APP_URL_LOADING_SERVICE_H_ + +#include "ios/chrome/browser/url_loading/app_url_loading_service.h" + +@class OpenNewTabCommand; + +// Service used to manage url loading at application level. +class TestAppUrlLoadingService : public AppUrlLoadingService { + public: + TestAppUrlLoadingService(); + + // Opens a url based on |command| in a new tab. + void LoadUrlInNewTab(OpenNewTabCommand* command) override; + + // These are the last parameters passed to |LoadUrlInNewTab|. + OpenNewTabCommand* last_command; + int open_new_tab_call_count = 0; +}; + +#endif // IOS_CHROME_BROWSER_URL_LOADING_APP_URL_LOADING_SERVICE_H_
diff --git a/ios/chrome/browser/url_loading/test_app_url_loading_service.mm b/ios/chrome/browser/url_loading/test_app_url_loading_service.mm new file mode 100644 index 0000000..0b7a73bb --- /dev/null +++ b/ios/chrome/browser/url_loading/test_app_url_loading_service.mm
@@ -0,0 +1,18 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#import "ios/chrome/browser/url_loading/test_app_url_loading_service.h" + +#import "ios/chrome/browser/ui/commands/open_new_tab_command.h" + +#if !defined(__has_feature) || !__has_feature(objc_arc) +#error "This file requires ARC support." +#endif + +TestAppUrlLoadingService::TestAppUrlLoadingService() {} + +void TestAppUrlLoadingService::LoadUrlInNewTab(OpenNewTabCommand* command) { + last_command = command; + open_new_tab_call_count++; +}
diff --git a/ios/chrome/browser/url_loading/url_loading_service.h b/ios/chrome/browser/url_loading/url_loading_service.h index 94dd7df..b0411923 100644 --- a/ios/chrome/browser/url_loading/url_loading_service.h +++ b/ios/chrome/browser/url_loading/url_loading_service.h
@@ -15,6 +15,7 @@ #include "ui/base/page_transition_types.h" #include "url/gurl.h" +class AppUrlLoadingService; class Browser; class UrlLoadingNotifier; @@ -26,9 +27,6 @@ // Objective-C delegate for UrlLoadingService. @protocol URLLoadingServiceDelegate -// Implementing delegate must open the url in |command| in a new tab. -- (void)openURLInNewTabWithCommand:(OpenNewTabCommand*)command; - // Implementing delegate can do an animation using information in |command| when // opening a background tab, then call |completion|. - (void)animateOpenBackgroundTabFromCommand:(OpenNewTabCommand*)command @@ -41,6 +39,7 @@ public: UrlLoadingService(UrlLoadingNotifier* notifier); + void SetAppService(AppUrlLoadingService* app_service); void SetDelegate(id<URLLoadingServiceDelegate> delegate); void SetBrowser(Browser* browser); @@ -58,6 +57,7 @@ private: __weak id<URLLoadingServiceDelegate> delegate_; + AppUrlLoadingService* app_service_; Browser* browser_; UrlLoadingNotifier* notifier_; id<UrlLoader> url_loader_;
diff --git a/ios/chrome/browser/url_loading/url_loading_service.mm b/ios/chrome/browser/url_loading/url_loading_service.mm index 034bc4faf..e6d7f2d3a 100644 --- a/ios/chrome/browser/url_loading/url_loading_service.mm +++ b/ios/chrome/browser/url_loading/url_loading_service.mm
@@ -14,6 +14,7 @@ #import "ios/chrome/browser/tabs/tab_model.h" #import "ios/chrome/browser/ui/commands/open_new_tab_command.h" #import "ios/chrome/browser/ui/ntp/ntp_util.h" +#import "ios/chrome/browser/url_loading/app_url_loading_service.h" #import "ios/chrome/browser/url_loading/url_loading_notifier.h" #import "ios/chrome/browser/url_loading/url_loading_util.h" #import "ios/chrome/browser/web/load_timing_tab_helper.h" @@ -87,6 +88,10 @@ UrlLoadingService::UrlLoadingService(UrlLoadingNotifier* notifier) : notifier_(notifier) {} +void UrlLoadingService::SetAppService(AppUrlLoadingService* app_service) { + app_service_ = app_service; +} + void UrlLoadingService::SetDelegate(id<URLLoadingServiceDelegate> delegate) { delegate_ = delegate; } @@ -176,7 +181,7 @@ void UrlLoadingService::SwitchToTab( const web::NavigationManager::WebLoadParams& web_params) { - DCHECK(delegate_); + DCHECK(app_service_); const GURL& url = web_params.url; @@ -201,7 +206,7 @@ inIncognito:browser_state->IsOffTheRecord() inBackground:NO appendTo:kCurrentTab]; - [delegate_ openURLInNewTabWithCommand:new_tab_command]; + app_service_->LoadUrlInNewTab(new_tab_command); } return; } @@ -221,10 +226,8 @@ notifier_->DidSwitchToTabWithUrl(url, new_web_state_index); } -// TODO(crbug.com/907527): migrate the extra work done in main_controller when -// [delegate_ openURLInNewTabWithCommand:] is called, and remove -// openURLInNewTabWithCommand from delegate. void UrlLoadingService::OpenUrlInNewTab(OpenNewTabCommand* command) { + DCHECK(app_service_); DCHECK(delegate_); DCHECK(browser_); ios::ChromeBrowserState* browser_state = browser_->GetBrowserState(); @@ -235,7 +238,7 @@ // currently selected in the other mode. This is done with the |appendTo| // parameter. command.appendTo = kLastTab; - [delegate_ openURLInNewTabWithCommand:command]; + app_service_->LoadUrlInNewTab(command); return; }
diff --git a/ios/chrome/browser/url_loading/url_loading_service_unittest.mm b/ios/chrome/browser/url_loading/url_loading_service_unittest.mm index 1794b21..ba47a5f7 100644 --- a/ios/chrome/browser/url_loading/url_loading_service_unittest.mm +++ b/ios/chrome/browser/url_loading/url_loading_service_unittest.mm
@@ -15,6 +15,7 @@ #import "ios/chrome/browser/tabs/tab.h" #import "ios/chrome/browser/tabs/tab_helper_util.h" #import "ios/chrome/browser/tabs/tab_model.h" +#import "ios/chrome/browser/url_loading/test_app_url_loading_service.h" #import "ios/chrome/browser/url_loading/url_loading_service_factory.h" #include "ios/chrome/browser/web_state_list/fake_web_state_list_delegate.h" #include "ios/chrome/browser/web_state_list/web_state_list.h" @@ -145,11 +146,14 @@ browser_ = new TestBrowser(chrome_browser_state_.get(), tabModel); + app_service_ = new TestAppUrlLoadingService(); + url_loading_delegate_ = [[URLLoadingServiceTestDelegate alloc] init]; service_ = UrlLoadingServiceFactory::GetForBrowserState( chrome_browser_state_.get()); service_->SetDelegate(url_loading_delegate_); service_->SetBrowser(browser_); + service_->SetAppService(app_service_); } void TearDown() override { @@ -179,6 +183,7 @@ Browser* browser_; URLLoadingServiceTestDelegate* url_loading_delegate_; UrlLoadingService* service_; + TestAppUrlLoadingService* app_service_; }; TEST_F(URLLoadingServiceTest, TestSwitchToTab) { @@ -208,6 +213,7 @@ params.disposition = WindowOpenDisposition::SWITCH_TO_TAB; service_->LoadUrlInCurrentTab(params); EXPECT_EQ(web_state_ptr_2, web_state_list->GetActiveWebState()); + EXPECT_EQ(0, app_service_->open_new_tab_call_count); } // Tests that switch to open tab from the NTP close it if it doesn't have @@ -240,6 +246,7 @@ service_->LoadUrlInCurrentTab(params); EXPECT_EQ(web_state_ptr_2, web_state_list->GetActiveWebState()); EXPECT_EQ(1, web_state_list->count()); + EXPECT_EQ(0, app_service_->open_new_tab_call_count); } // Tests that trying to switch to a closed tab open from the NTP opens it in the @@ -263,6 +270,7 @@ service_->LoadUrlInCurrentTab(params); EXPECT_EQ(1, web_state_list->count()); EXPECT_EQ(web_state_ptr, web_state_list->GetActiveWebState()); + EXPECT_EQ(0, app_service_->open_new_tab_call_count); } // TODO(crbug.com/907527): add tests for UrlLoadingService::OpenUrlInNewTab and
diff --git a/ios/third_party/motion_animator_objc/README.chromium b/ios/third_party/motion_animator_objc/README.chromium index e295295..54f6f08 100644 --- a/ios/third_party/motion_animator_objc/README.chromium +++ b/ios/third_party/motion_animator_objc/README.chromium
@@ -1,7 +1,7 @@ Name: Motion Animator for Objective-C URL: https://github.com/material-motion/motion-animator-objc Version: 0 -Revision: d300ae8ac3131b5ffde017ee2c1747bcc126e647 +Revision: 0581bc3dfacd34e40381e9cf45a15070b3868ba7 License: Apache 2.0 License File: LICENSE Security Critical: yes
diff --git a/ios/web/browsing_data/browsing_data_remover_unittest.mm b/ios/web/browsing_data/browsing_data_remover_unittest.mm index 97ad5100..25ed568b 100644 --- a/ios/web/browsing_data/browsing_data_remover_unittest.mm +++ b/ios/web/browsing_data/browsing_data_remover_unittest.mm
@@ -115,7 +115,13 @@ } // Tests that removing the cookies remove them from the cookie store. -TEST_F(BrowsingDataRemoverTest, RemoveCookie) { +// TODO(crbug.com/940880):Fix this test on iOS 11 device. +#if TARGET_IPHONE_SIMULATOR +#define MAYBE_RemoveCookie RemoveCookie +#else +#define MAYBE_RemoveCookie DISABLED_RemoveCookie +#endif +TEST_F(BrowsingDataRemoverTest, MAYBE_RemoveCookie) { ASSERT_TRUE(AddCookie()); ASSERT_TRUE(HasCookies(true)); @@ -127,7 +133,13 @@ } // Tests that removing the anything but cookies leave the cookies in the store. -TEST_F(BrowsingDataRemoverTest, RemoveNothing) { +// TODO(crbug.com/940880):Fix this test on iOS 11 device. +#if TARGET_IPHONE_SIMULATOR +#define MAYBE_RemoveNothing RemoveNothing +#else +#define MAYBE_RemoveNothing DISABLED_RemoveNothing +#endif +TEST_F(BrowsingDataRemoverTest, MAYBE_RemoveNothing) { ASSERT_TRUE(AddCookie()); ASSERT_TRUE(HasCookies(true)); @@ -140,7 +152,13 @@ } // Tests that removing nothing still call the closure. -TEST_F(BrowsingDataRemoverTest, KeepCookie) { +// TODO(crbug.com/940880):Fix this test on iOS 11 device. +#if TARGET_IPHONE_SIMULATOR +#define MAYBE_KeepCookie KeepCookie +#else +#define MAYBE_KeepCookie DISABLED_KeepCookie +#endif +TEST_F(BrowsingDataRemoverTest, MAYBE_KeepCookie) { ASSERT_TRUE(AddCookie()); // Don't remove anything but check that the closure is still called.
diff --git a/ios/web/web_state/ui/crw_web_controller.mm b/ios/web/web_state/ui/crw_web_controller.mm index c04cc0f..83e4e8b 100644 --- a/ios/web/web_state/ui/crw_web_controller.mm +++ b/ios/web/web_state/ui/crw_web_controller.mm
@@ -515,10 +515,6 @@ - (void)didFinishWithURL:(const GURL&)currentURL loadSuccess:(BOOL)loadSuccess context:(nullable const web::NavigationContextImpl*)context; -// Navigates forwards or backwards by |delta| pages. No-op if delta is out of -// bounds. Reloads if delta is 0. -// TODO(crbug.com/661316): Move this method to NavigationManager. -- (void)rendererInitiatedGoDelta:(int)delta hasUserGesture:(BOOL)hasUserGesture; // Acts on a single message from the JS object, parsed from JSON into a // DictionaryValue. Returns NO if the format for the message was invalid. - (BOOL)respondToMessage:(base::DictionaryValue*)crwMessage @@ -563,36 +559,6 @@ // Maps WKNavigationType to ui::PageTransition. - (ui::PageTransition)pageTransitionFromNavigationType: (WKNavigationType)navigationType; -// Updates the HTML5 history state of the page using the current NavigationItem. -// For same-document navigations and navigations affected by -// window.history.[push/replace]State(), the URL and serialized state object -// will be updated to the current NavigationItem's values. A popState event -// will be triggered for all same-document navigations. Additionally, a -// hashchange event will be triggered for same-document navigations where the -// only difference between the current and previous URL is the fragment. -- (void)updateHTML5HistoryState; -// Generates the JavaScript string used to update the UIWebView's URL so that it -// matches the URL displayed in the omnibox and sets window.history.state to -// stateObject. Needed for history.pushState() and history.replaceState(). -- (NSString*)javaScriptToReplaceWebViewURL:(const GURL&)URL - stateObjectJSON:(NSString*)stateObject; -// Generates the JavaScript string used to manually dispatch a popstate event, -// using |stateObjectJSON| as the event parameter. -- (NSString*)javaScriptToDispatchPopStateWithObject:(NSString*)stateObjectJSON; -// Generates the JavaScript string used to manually dispatch a hashchange event, -// using |oldURL| and |newURL| as the event parameters. -- (NSString*)javaScriptToDispatchHashChangeWithOldURL:(const GURL&)oldURL - newURL:(const GURL&)newURL; -// Injects JavaScript to update the URL and state object of the webview to the -// values found in the current NavigationItem. A hashchange event will be -// dispatched if |dispatchHashChange| is YES, and a popstate event will be -// dispatched if |sameDocument| is YES. Upon the script's completion, resets -// |urlOnStartLoading_| and |_lastRegisteredRequestURL| to the current -// NavigationItem's URL. This is necessary so that sites that depend on URL -// params/fragments continue to work correctly and that checks for the URL don't -// incorrectly trigger |-webPageChangedWithContext| calls. -- (void)injectHTML5HistoryScriptWithHashChange:(BOOL)dispatchHashChange - sameDocumentNavigation:(BOOL)sameDocumentNavigation; // Returns YES if the current live view is a web view with an image MIME type. - (BOOL)contentIsImage; @@ -624,19 +590,6 @@ // Sets scroll offset value for webview scroll view from |scrollState|. - (void)applyWebViewScrollOffsetFromScrollState: (const web::PageScrollState&)scrollState; -// Adds a new NavigationItem with the given URL and state object to the history -// stack. A state object is a serialized generic JavaScript object that contains -// details of the UI's state for a given NavigationItem/URL. -// TODO(stuartmorgan): Move the pushState/replaceState logic into -// NavigationManager. -- (void)pushStateWithPageURL:(const GURL&)pageURL - stateObject:(NSString*)stateObject - transition:(ui::PageTransition)transition - hasUserGesture:(BOOL)hasUserGesture; -// Assigns the given URL and state object to the current NavigationItem. -- (void)replaceStateWithPageURL:(const GURL&)pageUrl - stateObject:(NSString*)stateObject - hasUserGesture:(BOOL)hasUserGesture; // Sets _documentURL to newURL, and updates any relevant state information. - (void)setDocumentURL:(const GURL&)newURL context:(web::NavigationContextImpl*)context; @@ -1740,39 +1693,6 @@ [topView.subviews[0].subviews.lastObject isKindOfClass:[UIButton class]]; } -- (void)pushStateWithPageURL:(const GURL&)pageURL - stateObject:(NSString*)stateObject - transition:(ui::PageTransition)transition - hasUserGesture:(BOOL)hasUserGesture { - std::unique_ptr<web::NavigationContextImpl> context = - web::NavigationContextImpl::CreateNavigationContext( - self.webStateImpl, pageURL, hasUserGesture, transition, - /*is_renderer_initiated=*/true); - context->SetIsSameDocument(true); - self.webStateImpl->OnNavigationStarted(context.get()); - self.navigationManagerImpl->AddPushStateItemIfNecessary(pageURL, stateObject, - transition); - context->SetHasCommitted(true); - self.webStateImpl->OnNavigationFinished(context.get()); - self.userInteractionRegistered = NO; -} - -- (void)replaceStateWithPageURL:(const GURL&)pageURL - stateObject:(NSString*)stateObject - hasUserGesture:(BOOL)hasUserGesture { - std::unique_ptr<web::NavigationContextImpl> context = - web::NavigationContextImpl::CreateNavigationContext( - self.webStateImpl, pageURL, hasUserGesture, - ui::PageTransition::PAGE_TRANSITION_CLIENT_REDIRECT, - /*is_renderer_initiated=*/true); - context->SetIsSameDocument(true); - self.webStateImpl->OnNavigationStarted(context.get()); - self.navigationManagerImpl->UpdateCurrentItemForReplaceState(pageURL, - stateObject); - context->SetHasCommitted(true); - self.webStateImpl->OnNavigationFinished(context.get()); -} - - (void)setDocumentURL:(const GURL&)newURL context:(web::NavigationContextImpl*)context { if (newURL != _documentURL && newURL.is_valid()) { @@ -2019,99 +1939,6 @@ } } -// TODO(crbug.com/788465): Verify that the history state management here are not -// needed for WKBasedNavigationManagerImpl and delete this method. The -// OnNavigationItemCommitted() call is likely the only thing that needs to be -// retained. -- (void)updateHTML5HistoryState { - web::NavigationItemImpl* currentItem = self.currentNavItem; - if (!currentItem) - return; - - // Same-document navigations must trigger a popState event. - CRWSessionController* sessionController = self.sessionController; - BOOL sameDocumentNavigation = [sessionController - isSameDocumentNavigationBetweenItem:sessionController.currentItem - andItem:sessionController.previousItem]; - // WKWebView doesn't send hashchange events for same-document non-BFLI - // navigations, so one must be dispatched manually for hash change same- - // document navigations. - const GURL URL = currentItem->GetURL(); - web::NavigationItem* previousItem = self.sessionController.previousItem; - const GURL oldURL = previousItem ? previousItem->GetURL() : GURL(); - BOOL shouldDispatchHashchange = sameDocumentNavigation && previousItem && - (web::GURLByRemovingRefFromGURL(URL) == - web::GURLByRemovingRefFromGURL(oldURL)); - // The URL and state object must be set for same-document navigations and - // NavigationItems that were created or updated by calls to pushState() or - // replaceState(). - BOOL shouldUpdateState = sameDocumentNavigation || - currentItem->IsCreatedFromPushState() || - currentItem->HasStateBeenReplaced(); - if (!shouldUpdateState) - return; - - // TODO(stuartmorgan): Make CRWSessionController manage this internally (or - // remove it; it's not clear this matches other platforms' behavior). - self.navigationManagerImpl->OnNavigationItemCommitted(); - // Record that a same-document hashchange event will be fired. This flag will - // be reset when resonding to the hashchange message. Note that resetting the - // flag in the completion block below is too early, as that block is called - // before hashchange event listeners have a chance to fire. - _dispatchingSameDocumentHashChangeEvent = shouldDispatchHashchange; - // Inject the JavaScript to update the state on the browser side. - [self injectHTML5HistoryScriptWithHashChange:shouldDispatchHashchange - sameDocumentNavigation:sameDocumentNavigation]; -} - -- (NSString*)javaScriptToReplaceWebViewURL:(const GURL&)URL - stateObjectJSON:(NSString*)stateObject { - std::string outURL; - base::EscapeJSONString(URL.spec(), true, &outURL); - return - [NSString stringWithFormat:@"__gCrWeb.replaceWebViewURL(%@, %@);", - base::SysUTF8ToNSString(outURL), stateObject]; -} - -- (NSString*)javaScriptToDispatchPopStateWithObject:(NSString*)stateObjectJSON { - std::string outState; - base::EscapeJSONString(base::SysNSStringToUTF8(stateObjectJSON), true, - &outState); - return [NSString stringWithFormat:@"__gCrWeb.dispatchPopstateEvent(%@);", - base::SysUTF8ToNSString(outState)]; -} - -- (NSString*)javaScriptToDispatchHashChangeWithOldURL:(const GURL&)oldURL - newURL:(const GURL&)newURL { - return [NSString - stringWithFormat:@"__gCrWeb.dispatchHashchangeEvent(\'%s\', \'%s\');", - oldURL.spec().c_str(), newURL.spec().c_str()]; -} - -- (void)injectHTML5HistoryScriptWithHashChange:(BOOL)dispatchHashChange - sameDocumentNavigation:(BOOL)sameDocumentNavigation { - web::NavigationItemImpl* currentItem = self.currentNavItem; - if (!currentItem) - return; - - const GURL URL = currentItem->GetURL(); - NSString* stateObject = currentItem->GetSerializedStateObject(); - NSMutableString* script = [NSMutableString - stringWithString:[self javaScriptToReplaceWebViewURL:URL - stateObjectJSON:stateObject]]; - if (sameDocumentNavigation) { - [script - appendString:[self javaScriptToDispatchPopStateWithObject:stateObject]]; - } - if (dispatchHashChange) { - web::NavigationItemImpl* previousItem = self.sessionController.previousItem; - const GURL oldURL = previousItem ? previousItem->GetURL() : GURL(); - [script appendString:[self javaScriptToDispatchHashChangeWithOldURL:oldURL - newURL:URL]]; - } - [self executeJavaScript:script completionHandler:nil]; -} - // Load the current URL in a web view, first ensuring the web view is visible. - (void)loadCurrentURLInWebView { web::NavigationItem* item = self.currentNavItem; @@ -2793,24 +2620,6 @@ self.webStateImpl->OnPageLoaded(currentURL, YES); } -- (void)rendererInitiatedGoDelta:(int)delta - hasUserGesture:(BOOL)hasUserGesture { - if (_isBeingDestroyed) - return; - - if (delta == 0) { - [self reloadWithRendererInitiatedNavigation:YES]; - return; - } - - if (self.navigationManagerImpl->CanGoToOffset(delta)) { - int index = self.navigationManagerImpl->GetIndexForOffset(delta); - self.navigationManagerImpl->GoToIndex( - index, web::NavigationInitiationType::RENDERER_INITIATED, - /*has_user_gesture=*/hasUserGesture); - } -} - - (BOOL)shouldClosePageOnNativeApplicationLoad { // The page should be closed if it was initiated by the DOM and there has been // no user interaction with the page since the web view was created, or if @@ -2822,6 +2631,123 @@ return rendererInitiatedWithoutInteraction || noNavigationItems; } +#pragma mark - JavaScript history manipulation + +// Updates the HTML5 history state of the page using the current NavigationItem. +// For same-document navigations and navigations affected by +// window.history.[push/replace]State(), the URL and serialized state object +// will be updated to the current NavigationItem's values. A popState event +// will be triggered for all same-document navigations. Additionally, a +// hashchange event will be triggered for same-document navigations where the +// only difference between the current and previous URL is the fragment. +// TODO(crbug.com/788465): Verify that the history state management here are not +// needed for WKBasedNavigationManagerImpl and delete this method. The +// OnNavigationItemCommitted() call is likely the only thing that needs to be +// retained. +- (void)updateHTML5HistoryState { + web::NavigationItemImpl* currentItem = self.currentNavItem; + if (!currentItem) + return; + + // Same-document navigations must trigger a popState event. + CRWSessionController* sessionController = self.sessionController; + BOOL sameDocumentNavigation = [sessionController + isSameDocumentNavigationBetweenItem:sessionController.currentItem + andItem:sessionController.previousItem]; + // WKWebView doesn't send hashchange events for same-document non-BFLI + // navigations, so one must be dispatched manually for hash change same- + // document navigations. + const GURL URL = currentItem->GetURL(); + web::NavigationItem* previousItem = self.sessionController.previousItem; + const GURL oldURL = previousItem ? previousItem->GetURL() : GURL(); + BOOL shouldDispatchHashchange = sameDocumentNavigation && previousItem && + (web::GURLByRemovingRefFromGURL(URL) == + web::GURLByRemovingRefFromGURL(oldURL)); + // The URL and state object must be set for same-document navigations and + // NavigationItems that were created or updated by calls to pushState() or + // replaceState(). + BOOL shouldUpdateState = sameDocumentNavigation || + currentItem->IsCreatedFromPushState() || + currentItem->HasStateBeenReplaced(); + if (!shouldUpdateState) + return; + + // TODO(stuartmorgan): Make CRWSessionController manage this internally (or + // remove it; it's not clear this matches other platforms' behavior). + self.navigationManagerImpl->OnNavigationItemCommitted(); + // Record that a same-document hashchange event will be fired. This flag will + // be reset when resonding to the hashchange message. Note that resetting the + // flag in the completion block below is too early, as that block is called + // before hashchange event listeners have a chance to fire. + _dispatchingSameDocumentHashChangeEvent = shouldDispatchHashchange; + // Inject the JavaScript to update the state on the browser side. + [self injectHTML5HistoryScriptWithHashChange:shouldDispatchHashchange + sameDocumentNavigation:sameDocumentNavigation]; +} + +// Generates the JavaScript string used to update the UIWebView's URL so that it +// matches the URL displayed in the omnibox and sets window.history.state to +// stateObject. Needed for history.pushState() and history.replaceState(). +- (NSString*)javaScriptToReplaceWebViewURL:(const GURL&)URL + stateObjectJSON:(NSString*)stateObject { + std::string outURL; + base::EscapeJSONString(URL.spec(), true, &outURL); + return + [NSString stringWithFormat:@"__gCrWeb.replaceWebViewURL(%@, %@);", + base::SysUTF8ToNSString(outURL), stateObject]; +} + +// Generates the JavaScript string used to manually dispatch a popstate event, +// using |stateObjectJSON| as the event parameter. +- (NSString*)javaScriptToDispatchPopStateWithObject:(NSString*)stateObjectJSON { + std::string outState; + base::EscapeJSONString(base::SysNSStringToUTF8(stateObjectJSON), true, + &outState); + return [NSString stringWithFormat:@"__gCrWeb.dispatchPopstateEvent(%@);", + base::SysUTF8ToNSString(outState)]; +} + +// Generates the JavaScript string used to manually dispatch a hashchange event, +// using |oldURL| and |newURL| as the event parameters. +- (NSString*)javaScriptToDispatchHashChangeWithOldURL:(const GURL&)oldURL + newURL:(const GURL&)newURL { + return [NSString + stringWithFormat:@"__gCrWeb.dispatchHashchangeEvent(\'%s\', \'%s\');", + oldURL.spec().c_str(), newURL.spec().c_str()]; +} + +// Injects JavaScript to update the URL and state object of the webview to the +// values found in the current NavigationItem. A hashchange event will be +// dispatched if |dispatchHashChange| is YES, and a popstate event will be +// dispatched if |sameDocument| is YES. Upon the script's completion, resets +// |urlOnStartLoading_| and |_lastRegisteredRequestURL| to the current +// NavigationItem's URL. This is necessary so that sites that depend on URL +// params/fragments continue to work correctly and that checks for the URL don't +// incorrectly trigger |-webPageChangedWithContext| calls. +- (void)injectHTML5HistoryScriptWithHashChange:(BOOL)dispatchHashChange + sameDocumentNavigation:(BOOL)sameDocumentNavigation { + web::NavigationItemImpl* currentItem = self.currentNavItem; + if (!currentItem) + return; + + const GURL URL = currentItem->GetURL(); + NSString* stateObject = currentItem->GetSerializedStateObject(); + NSMutableString* script = [NSMutableString + stringWithString:[self javaScriptToReplaceWebViewURL:URL + stateObjectJSON:stateObject]]; + if (sameDocumentNavigation) { + [script + appendString:[self javaScriptToDispatchPopStateWithObject:stateObject]]; + } + if (dispatchHashChange) { + web::NavigationItemImpl* previousItem = self.sessionController.previousItem; + const GURL oldURL = previousItem ? previousItem->GetURL() : GURL(); + [script appendString:[self javaScriptToDispatchHashChangeWithOldURL:oldURL + newURL:URL]]; + } + [self executeJavaScript:script completionHandler:nil]; +} + #pragma mark - Native Content // Returns |YES| if |url| should be loaded in a native view. @@ -3376,17 +3302,6 @@ hasUserGesture:[context[kUserIsInteractingKey] boolValue]]; [self updateSSLStatusForCurrentNavigationItem]; - NSString* replaceWebViewJS = [self javaScriptToReplaceWebViewURL:pushURL - stateObjectJSON:stateObject]; - __weak CRWWebController* weakSelf = self; - [self executeJavaScript:replaceWebViewJS - completionHandler:^(id, NSError*) { - CRWWebController* strongSelf = weakSelf; - if (strongSelf && !strongSelf->_isBeingDestroyed) { - [strongSelf optOutScrollsToTopForSubviews]; - [strongSelf didFinishNavigation:nullptr]; - } - }]; return YES; } @@ -3471,6 +3386,68 @@ return YES; } +#pragma mark - JavaScript message helpers + +// Adds a new NavigationItem with the given URL and state object to the history +// stack. A state object is a serialized generic JavaScript object that contains +// details of the UI's state for a given NavigationItem/URL. +// TODO(stuartmorgan): Move the pushState/replaceState logic into +// NavigationManager. +- (void)pushStateWithPageURL:(const GURL&)pageURL + stateObject:(NSString*)stateObject + transition:(ui::PageTransition)transition + hasUserGesture:(BOOL)hasUserGesture { + std::unique_ptr<web::NavigationContextImpl> context = + web::NavigationContextImpl::CreateNavigationContext( + self.webStateImpl, pageURL, hasUserGesture, transition, + /*is_renderer_initiated=*/true); + context->SetIsSameDocument(true); + self.webStateImpl->OnNavigationStarted(context.get()); + self.navigationManagerImpl->AddPushStateItemIfNecessary(pageURL, stateObject, + transition); + context->SetHasCommitted(true); + self.webStateImpl->OnNavigationFinished(context.get()); + self.userInteractionRegistered = NO; +} + +// Assigns the given URL and state object to the current NavigationItem. +- (void)replaceStateWithPageURL:(const GURL&)pageURL + stateObject:(NSString*)stateObject + hasUserGesture:(BOOL)hasUserGesture { + std::unique_ptr<web::NavigationContextImpl> context = + web::NavigationContextImpl::CreateNavigationContext( + self.webStateImpl, pageURL, hasUserGesture, + ui::PageTransition::PAGE_TRANSITION_CLIENT_REDIRECT, + /*is_renderer_initiated=*/true); + context->SetIsSameDocument(true); + self.webStateImpl->OnNavigationStarted(context.get()); + self.navigationManagerImpl->UpdateCurrentItemForReplaceState(pageURL, + stateObject); + context->SetHasCommitted(true); + self.webStateImpl->OnNavigationFinished(context.get()); +} + +// Navigates forwards or backwards by |delta| pages. No-op if delta is out of +// bounds. Reloads if delta is 0. +// TODO(crbug.com/661316): Move this method to NavigationManager. +- (void)rendererInitiatedGoDelta:(int)delta + hasUserGesture:(BOOL)hasUserGesture { + if (_isBeingDestroyed) + return; + + if (delta == 0) { + [self reloadWithRendererInitiatedNavigation:YES]; + return; + } + + if (self.navigationManagerImpl->CanGoToOffset(delta)) { + int index = self.navigationManagerImpl->GetIndexForOffset(delta); + self.navigationManagerImpl->GoToIndex( + index, web::NavigationInitiationType::RENDERER_INITIATED, + /*has_user_gesture=*/hasUserGesture); + } +} + #pragma mark - WebUI - (void)createWebUIForURL:(const GURL&)URL {
diff --git a/media/base/audio_processing.cc b/media/base/audio_processing.cc index 247e089..ce32fd2 100644 --- a/media/base/audio_processing.cc +++ b/media/base/audio_processing.cc
@@ -26,8 +26,6 @@ switch (type) { case EchoCancellationType::kDisabled: return "disabled"; - case EchoCancellationType::kAec2: - return "aec2"; case EchoCancellationType::kAec3: return "aec3"; case EchoCancellationType::kSystemAec:
diff --git a/media/base/audio_processing.h b/media/base/audio_processing.h index 9a169c90..46428114 100644 --- a/media/base/audio_processing.h +++ b/media/base/audio_processing.h
@@ -20,7 +20,7 @@ kExperimental, kHybridExperimental }; -enum class EchoCancellationType { kDisabled, kAec2, kAec3, kSystemAec }; +enum class EchoCancellationType { kDisabled, kAec3, kSystemAec }; enum class NoiseSuppressionType { kDisabled, kDefault, kExperimental }; struct MEDIA_EXPORT AudioProcessingSettings { @@ -43,8 +43,7 @@ // Indicates whether WebRTC will be required to perform the audio processing. bool requires_apm() const { - return echo_cancellation == EchoCancellationType::kAec2 || - echo_cancellation == EchoCancellationType::kAec3 || + return echo_cancellation == EchoCancellationType::kAec3 || noise_suppression != NoiseSuppressionType::kDisabled || automatic_gain_control != AutomaticGainControlType::kDisabled || high_pass_filter || typing_detection || stereo_mirroring;
diff --git a/media/webrtc/audio_processor.cc b/media/webrtc/audio_processor.cc index 991213df..37826c92 100644 --- a/media/webrtc/audio_processor.cc +++ b/media/webrtc/audio_processor.cc
@@ -46,12 +46,6 @@ } } -bool EchoCancellationIsWebRtcProvided( - const EchoCancellationType& echo_cancellation_type) { - return echo_cancellation_type == EchoCancellationType::kAec2 || - echo_cancellation_type == EchoCancellationType::kAec3; -} - } // namespace AudioProcessor::ProcessingResult::ProcessingResult( @@ -196,7 +190,7 @@ // 2" in those cases. // If we use nothing but, possibly, audio mirroring, don't initialize the APM. - if (!EchoCancellationIsWebRtcProvided(settings_.echo_cancellation) && + if (settings_.echo_cancellation != EchoCancellationType::kAec3 && settings_.noise_suppression == NoiseSuppressionType::kDisabled && settings_.automatic_gain_control == AutomaticGainControlType::kDisabled && !settings_.high_pass_filter && !settings_.typing_detection) { @@ -211,7 +205,7 @@ // Echo cancellation is configured both before and after AudioProcessing // construction, but before Initialize. - if (EchoCancellationIsWebRtcProvided(settings_.echo_cancellation)) { + if (settings_.echo_cancellation == EchoCancellationType::kAec3) { ap_builder.SetEchoControlFactory( std::make_unique<webrtc::EchoCanceller3Factory>()); } @@ -274,7 +268,7 @@ // AEC setup part 2. apm_config.echo_canceller.enabled = - EchoCancellationIsWebRtcProvided(settings_.echo_cancellation); + settings_.echo_cancellation == EchoCancellationType::kAec3; apm_config.echo_canceller.mobile_mode = false; // High-pass filter setup.
diff --git a/media/webrtc/audio_processor_unittest.cc b/media/webrtc/audio_processor_unittest.cc index 7213b08..96d7030 100644 --- a/media/webrtc/audio_processor_unittest.cc +++ b/media/webrtc/audio_processor_unittest.cc
@@ -144,7 +144,7 @@ AudioProcessingSettings GetEnabledAudioProcessingSettings() const { AudioProcessingSettings settings; - settings.echo_cancellation = EchoCancellationType::kAec2; + settings.echo_cancellation = EchoCancellationType::kAec3; settings.noise_suppression = NoiseSuppressionType::kExperimental; settings.automatic_gain_control = AutomaticGainControlType::kExperimental; settings.high_pass_filter = true;
diff --git a/net/BUILD.gn b/net/BUILD.gn index 241d6c4..a37949f 100644 --- a/net/BUILD.gn +++ b/net/BUILD.gn
@@ -1794,8 +1794,6 @@ if (enable_reporting) { sources += [ - "network_error_logging/network_error_logging_delegate.cc", - "network_error_logging/network_error_logging_delegate.h", "network_error_logging/network_error_logging_service.cc", "network_error_logging/network_error_logging_service.h", "reporting/reporting_browsing_data_remover.cc",
diff --git a/net/disk_cache/simple/simple_entry_impl.cc b/net/disk_cache/simple/simple_entry_impl.cc index 2d74e4a..75a12851 100644 --- a/net/disk_cache/simple/simple_entry_impl.cc +++ b/net/disk_cache/simple/simple_entry_impl.cc
@@ -216,7 +216,7 @@ } pending_operations_.push(SimpleEntryOperation::OpenOperation( - this, index_state, std::move(callback), out_entry)); + this, std::move(callback), out_entry)); RunNextOperationIfNeeded(); return net::ERR_IO_PENDING; } @@ -228,10 +228,6 @@ net_log_.AddEvent(net::NetLogEventType::SIMPLE_CACHE_ENTRY_CREATE_CALL); - // Don't really care if we're in index or not for this, so avoid extra lookup. - OpenEntryIndexEnum index_state = - backend_->index()->initialized() ? INDEX_HIT : INDEX_NOEXIST; - net::Error ret_value = net::ERR_FAILED; if (use_optimistic_operations_ && state_ == STATE_UNINITIALIZED && pending_operations_.size() == 0) { @@ -240,7 +236,7 @@ ReturnEntryToCaller(out_entry); pending_operations_.push(SimpleEntryOperation::CreateOperation( - this, index_state, CompletionOnceCallback(), nullptr)); + this, CompletionOnceCallback(), nullptr)); ret_value = net::OK; // If we are optimistically returning before a preceeding doom, we need to @@ -252,7 +248,7 @@ } } else { pending_operations_.push(SimpleEntryOperation::CreateOperation( - this, index_state, std::move(callback), out_entry)); + this, std::move(callback), out_entry)); ret_value = net::ERR_IO_PENDING; } @@ -688,20 +684,15 @@ void SimpleEntryImpl::RunNextOperationIfNeeded() { DCHECK(io_thread_checker_.CalledOnValidThread()); - SIMPLE_CACHE_UMA(CUSTOM_COUNTS, - "EntryOperationsPending", cache_type_, - pending_operations_.size(), 0, 100, 20); if (!pending_operations_.empty() && state_ != STATE_IO_PENDING) { SimpleEntryOperation operation = std::move(pending_operations_.front()); pending_operations_.pop(); switch (operation.type()) { case SimpleEntryOperation::TYPE_OPEN: - OpenEntryInternal(operation.have_index(), operation.ReleaseCallback(), - operation.out_entry()); + OpenEntryInternal(operation.ReleaseCallback(), operation.out_entry()); break; case SimpleEntryOperation::TYPE_CREATE: - CreateEntryInternal(operation.have_index(), operation.ReleaseCallback(), - operation.out_entry()); + CreateEntryInternal(operation.ReleaseCallback(), operation.out_entry()); break; case SimpleEntryOperation::TYPE_OPEN_OR_CREATE: OpenOrCreateEntryInternal(operation.index_state(), @@ -745,8 +736,7 @@ } } -void SimpleEntryImpl::OpenEntryInternal(bool have_index, - net::CompletionOnceCallback callback, +void SimpleEntryImpl::OpenEntryInternal(net::CompletionOnceCallback callback, Entry** out_entry) { ScopedOperationRunner operation_runner(this); @@ -786,10 +776,9 @@ } } - base::OnceClosure task = - base::BindOnce(&SimpleSynchronousEntry::OpenEntry, cache_type_, path_, - key_, entry_hash_, have_index, start_time, file_tracker_, - trailer_prefetch_size, results.get()); + base::OnceClosure task = base::BindOnce( + &SimpleSynchronousEntry::OpenEntry, cache_type_, path_, key_, entry_hash_, + start_time, file_tracker_, trailer_prefetch_size, results.get()); base::OnceClosure reply = base::BindOnce( &SimpleEntryImpl::CreationOperationComplete, this, std::move(callback), @@ -801,8 +790,7 @@ std::move(reply), entry_priority_); } -void SimpleEntryImpl::CreateEntryInternal(bool have_index, - net::CompletionOnceCallback callback, +void SimpleEntryImpl::CreateEntryInternal(net::CompletionOnceCallback callback, Entry** out_entry) { ScopedOperationRunner operation_runner(this); @@ -830,9 +818,9 @@ new SimpleEntryCreationResults(SimpleEntryStat( last_used_, last_modified_, data_size_, sparse_data_size_))); - OnceClosure task = base::BindOnce( - &SimpleSynchronousEntry::CreateEntry, cache_type_, path_, key_, - entry_hash_, have_index, start_time, file_tracker_, results.get()); + OnceClosure task = base::BindOnce(&SimpleSynchronousEntry::CreateEntry, + cache_type_, path_, key_, entry_hash_, + start_time, file_tracker_, results.get()); OnceClosure reply = base::BindOnce( &SimpleEntryImpl::CreationOperationComplete, this, std::move(callback), start_time, base::Time(), base::Passed(&results), out_entry,
diff --git a/net/disk_cache/simple/simple_entry_impl.h b/net/disk_cache/simple/simple_entry_impl.h index 524b823..ecfb1bed 100644 --- a/net/disk_cache/simple/simple_entry_impl.h +++ b/net/disk_cache/simple/simple_entry_impl.h
@@ -226,13 +226,9 @@ // the last reference. void RunNextOperationIfNeeded(); - void OpenEntryInternal(bool have_index, - CompletionOnceCallback callback, - Entry** out_entry); + void OpenEntryInternal(CompletionOnceCallback callback, Entry** out_entry); - void CreateEntryInternal(bool have_index, - CompletionOnceCallback callback, - Entry** out_entry); + void CreateEntryInternal(CompletionOnceCallback callback, Entry** out_entry); void OpenOrCreateEntryInternal(OpenEntryIndexEnum index_state, CompletionOnceCallback callback,
diff --git a/net/disk_cache/simple/simple_entry_operation.cc b/net/disk_cache/simple/simple_entry_operation.cc index 6e64021..6ddb3fb2 100644 --- a/net/disk_cache/simple/simple_entry_operation.cc +++ b/net/disk_cache/simple/simple_entry_operation.cc
@@ -21,23 +21,21 @@ // static SimpleEntryOperation SimpleEntryOperation::OpenOperation( SimpleEntryImpl* entry, - OpenEntryIndexEnum index_state, net::CompletionOnceCallback callback, Entry** out_entry) { return SimpleEntryOperation(entry, nullptr, std::move(callback), out_entry, - nullptr, 0, 0, 0, nullptr, TYPE_OPEN, index_state, - 0, false, false); + nullptr, 0, 0, 0, nullptr, TYPE_OPEN, + INDEX_NOEXIST, 0, false, false); } // static SimpleEntryOperation SimpleEntryOperation::CreateOperation( SimpleEntryImpl* entry, - OpenEntryIndexEnum index_state, net::CompletionOnceCallback callback, Entry** out_entry) { return SimpleEntryOperation(entry, nullptr, std::move(callback), out_entry, nullptr, 0, 0, 0, nullptr, TYPE_CREATE, - index_state, 0, false, false); + INDEX_NOEXIST, 0, false, false); } // static
diff --git a/net/disk_cache/simple/simple_entry_operation.h b/net/disk_cache/simple/simple_entry_operation.h index 869d1d8..ed47a0fc 100644 --- a/net/disk_cache/simple/simple_entry_operation.h +++ b/net/disk_cache/simple/simple_entry_operation.h
@@ -45,11 +45,9 @@ ~SimpleEntryOperation(); static SimpleEntryOperation OpenOperation(SimpleEntryImpl* entry, - OpenEntryIndexEnum index_state, CompletionOnceCallback, Entry** out_entry); static SimpleEntryOperation CreateOperation(SimpleEntryImpl* entry, - OpenEntryIndexEnum index_state, CompletionOnceCallback callback, Entry** out_entry); static SimpleEntryOperation OpenOrCreateOperation( @@ -100,7 +98,6 @@ Entry** out_entry() { return out_entry_; } EntryWithOpened* entry_struct() { return entry_struct_; } - bool have_index() const { return index_state_ != INDEX_NOEXIST; } OpenEntryIndexEnum index_state() const { return index_state_; } int index() const { return index_; } int offset() const { return offset_; } @@ -146,9 +143,7 @@ int64_t* const out_start_; const EntryOperationType type_; - // Used in open and create operations. - // For TYPE_CREATE, only distinguishes whether index exists or NOEXIST. - // Otherwise also indicates whether entry is HIT or MISS in the index. + // Used in the "open or create" operation. const OpenEntryIndexEnum index_state_; // Used in write and read operations. const unsigned int index_;
diff --git a/net/disk_cache/simple/simple_file_tracker_unittest.cc b/net/disk_cache/simple/simple_file_tracker_unittest.cc index e484046..d46362f 100644 --- a/net/disk_cache/simple/simple_file_tracker_unittest.cc +++ b/net/disk_cache/simple/simple_file_tracker_unittest.cc
@@ -51,11 +51,10 @@ std::unique_ptr<SimpleSynchronousEntry, SyncEntryDeleter>; SyncEntryPointer MakeSyncEntry(uint64_t hash) { - return SyncEntryPointer( - new SimpleSynchronousEntry(net::DISK_CACHE, cache_path_, "dummy", hash, - /* had_index=*/true, &file_tracker_, - /*trailer_prefetch_size=*/-1), - SyncEntryDeleter(this)); + return SyncEntryPointer(new SimpleSynchronousEntry( + net::DISK_CACHE, cache_path_, "dummy", hash, + &file_tracker_, /*trailer_prefetch_size=*/-1), + SyncEntryDeleter(this)); } void UpdateEntryFileKey(SimpleSynchronousEntry* sync_entry,
diff --git a/net/disk_cache/simple/simple_synchronous_entry.cc b/net/disk_cache/simple/simple_synchronous_entry.cc index fcaaa9e..3ce539c 100644 --- a/net/disk_cache/simple/simple_synchronous_entry.cc +++ b/net/disk_cache/simple/simple_synchronous_entry.cc
@@ -38,21 +38,10 @@ namespace { -void RecordSyncOpenResult(net::CacheType cache_type, - OpenEntryResult result, - bool had_index) { +void RecordSyncOpenResult(net::CacheType cache_type, OpenEntryResult result) { DCHECK_LT(result, OPEN_ENTRY_MAX); SIMPLE_CACHE_UMA(ENUMERATION, "SyncOpenResult", cache_type, result, OPEN_ENTRY_MAX); - if (had_index) { - SIMPLE_CACHE_UMA(ENUMERATION, - "SyncOpenResult_WithIndex", cache_type, - result, OPEN_ENTRY_MAX); - } else { - SIMPLE_CACHE_UMA(ENUMERATION, - "SyncOpenResult_WithoutIndex", cache_type, - result, OPEN_ENTRY_MAX); - } } void RecordWriteResult(net::CacheType cache_type, SyncWriteResult result) { @@ -349,7 +338,6 @@ const FilePath& path, const std::string& key, const uint64_t entry_hash, - const bool had_index, const base::TimeTicks& time_enqueued, SimpleFileTracker* file_tracker, int32_t trailer_prefetch_size, @@ -358,9 +346,8 @@ SIMPLE_CACHE_UMA(TIMES, "QueueLatency.OpenEntry", cache_type, (start_sync_open_entry - time_enqueued)); - SimpleSynchronousEntry* sync_entry = - new SimpleSynchronousEntry(cache_type, path, key, entry_hash, had_index, - file_tracker, trailer_prefetch_size); + SimpleSynchronousEntry* sync_entry = new SimpleSynchronousEntry( + cache_type, path, key, entry_hash, file_tracker, trailer_prefetch_size); out_results->result = sync_entry->InitializeForOpen( &out_results->entry_stat, out_results->stream_prefetch_data); if (out_results->result != net::OK) { @@ -384,7 +371,6 @@ const FilePath& path, const std::string& key, const uint64_t entry_hash, - const bool had_index, const base::TimeTicks& time_enqueued, SimpleFileTracker* file_tracker, SimpleEntryCreationResults* out_results) { @@ -394,7 +380,7 @@ (start_sync_create_entry - time_enqueued)); SimpleSynchronousEntry* sync_entry = new SimpleSynchronousEntry( - cache_type, path, key, entry_hash, had_index, file_tracker, -1); + cache_type, path, key, entry_hash, file_tracker, -1); out_results->result = sync_entry->InitializeForCreate(&out_results->entry_stat); if (out_results->result != net::OK) { @@ -422,15 +408,13 @@ SimpleFileTracker* file_tracker, int32_t trailer_prefetch_size, SimpleEntryCreationResults* out_results) { - const bool had_index = (index_state != INDEX_NOEXIST); - base::TimeTicks start = base::TimeTicks::Now(); SIMPLE_CACHE_UMA(TIMES, "QueueLatency.OpenOrCreateEntry", cache_type, (start - time_enqueued)); if (index_state == INDEX_MISS) { // Try to just create. auto sync_entry = base::WrapUnique( - new SimpleSynchronousEntry(cache_type, path, key, entry_hash, had_index, + new SimpleSynchronousEntry(cache_type, path, key, entry_hash, file_tracker, trailer_prefetch_size)); out_results->result = @@ -447,8 +431,8 @@ // In this case, ::OpenOrCreateEntry already returned claiming it made // a new entry. Try extra-hard to make that the actual case. sync_entry->Doom(); - CreateEntry(cache_type, path, key, entry_hash, had_index, - time_enqueued, file_tracker, out_results); + CreateEntry(cache_type, path, key, entry_hash, time_enqueued, + file_tracker, out_results); return; } // Otherwise can just try opening. @@ -461,12 +445,12 @@ } // Try open, then if that fails create. - OpenEntry(cache_type, path, key, entry_hash, had_index, time_enqueued, - file_tracker, trailer_prefetch_size, out_results); + OpenEntry(cache_type, path, key, entry_hash, time_enqueued, file_tracker, + trailer_prefetch_size, out_results); if (out_results->sync_entry) return; - CreateEntry(cache_type, path, key, entry_hash, had_index, time_enqueued, - file_tracker, out_results); + CreateEntry(cache_type, path, key, entry_hash, time_enqueued, file_tracker, + out_results); } // static @@ -1108,13 +1092,11 @@ const FilePath& path, const std::string& key, const uint64_t entry_hash, - const bool had_index, SimpleFileTracker* file_tracker, int32_t trailer_prefetch_size) : cache_type_(cache_type), path_(path), entry_file_key_(entry_hash), - had_index_(had_index), key_(key), file_tracker_(file_tracker), trailer_prefetch_size_(trailer_prefetch_size) { @@ -1200,23 +1182,10 @@ file_1_open_start = base::Time::Now(); if (!MaybeOpenFile(i, &error)) { - // TODO(morlovich): Remove one each of these triplets of histograms. We - // can calculate the third as the sum or difference of the other two. - RecordSyncOpenResult(cache_type_, OPEN_ENTRY_PLATFORM_FILE_ERROR, - had_index_); + RecordSyncOpenResult(cache_type_, OPEN_ENTRY_PLATFORM_FILE_ERROR); SIMPLE_CACHE_UMA(ENUMERATION, "SyncOpenPlatformFileError", cache_type_, -error, -base::File::FILE_ERROR_MAX); - if (had_index_) { - SIMPLE_CACHE_UMA(ENUMERATION, - "SyncOpenPlatformFileError_WithIndex", cache_type_, - -error, -base::File::FILE_ERROR_MAX); - } else { - SIMPLE_CACHE_UMA(ENUMERATION, - "SyncOpenPlatformFileError_WithoutIndex", - cache_type_, - -error, -base::File::FILE_ERROR_MAX); - } while (--i >= 0) CloseFile(i); return false; @@ -1263,8 +1232,7 @@ // stream 1 and stream 0 is only determined after reading the EOF record // for stream 0 in ReadAndValidateStream0AndMaybe1. if (!base::IsValueInRangeForNumericType<int>(file_info.size)) { - RecordSyncOpenResult(cache_type_, OPEN_ENTRY_INVALID_FILE_LENGTH, - had_index_); + RecordSyncOpenResult(cache_type_, OPEN_ENTRY_INVALID_FILE_LENGTH); return false; } out_entry_stat->set_data_size(i + 1, static_cast<int>(file_info.size)); @@ -1298,22 +1266,10 @@ for (int i = 0; i < kSimpleEntryNormalFileCount; ++i) { base::File::Error error; if (!MaybeCreateFile(i, FILE_NOT_REQUIRED, &error)) { - // TODO(morlovich): Remove one each of these triplets of histograms. We - // can calculate the third as the sum or difference of the other two. - RecordSyncCreateResult(CREATE_ENTRY_PLATFORM_FILE_ERROR, had_index_); + RecordSyncCreateResult(CREATE_ENTRY_PLATFORM_FILE_ERROR); SIMPLE_CACHE_UMA(ENUMERATION, "SyncCreatePlatformFileError", cache_type_, -error, -base::File::FILE_ERROR_MAX); - if (had_index_) { - SIMPLE_CACHE_UMA(ENUMERATION, - "SyncCreatePlatformFileError_WithIndex", cache_type_, - -error, -base::File::FILE_ERROR_MAX); - } else { - SIMPLE_CACHE_UMA(ENUMERATION, - "SyncCreatePlatformFileError_WithoutIndex", - cache_type_, - -error, -base::File::FILE_ERROR_MAX); - } while (--i >= 0) CloseFile(i); return false; @@ -1364,7 +1320,7 @@ reinterpret_cast<const SimpleFileHeader*>(header_data.data()); if (bytes_read == -1 || static_cast<size_t>(bytes_read) < sizeof(*header)) { - RecordSyncOpenResult(cache_type_, OPEN_ENTRY_CANT_READ_HEADER, had_index_); + RecordSyncOpenResult(cache_type_, OPEN_ENTRY_CANT_READ_HEADER); return false; } // This resize will not invalidate iterators since it does not enlarge the @@ -1373,12 +1329,12 @@ header_data.resize(bytes_read); if (header->initial_magic_number != kSimpleInitialMagicNumber) { - RecordSyncOpenResult(cache_type_, OPEN_ENTRY_BAD_MAGIC_NUMBER, had_index_); + RecordSyncOpenResult(cache_type_, OPEN_ENTRY_BAD_MAGIC_NUMBER); return false; } if (header->version != kSimpleEntryVersionOnDisk) { - RecordSyncOpenResult(cache_type_, OPEN_ENTRY_BAD_VERSION, had_index_); + RecordSyncOpenResult(cache_type_, OPEN_ENTRY_BAD_VERSION); return false; } @@ -1391,7 +1347,7 @@ int bytes_read = file->Read(old_size, header_data.data() + old_size, bytes_to_read); if (bytes_read != bytes_to_read) { - RecordSyncOpenResult(cache_type_, OPEN_ENTRY_CANT_READ_KEY, had_index_); + RecordSyncOpenResult(cache_type_, OPEN_ENTRY_CANT_READ_KEY); return false; } header = reinterpret_cast<const SimpleFileHeader*>(header_data.data()); @@ -1399,7 +1355,7 @@ char* key_data = header_data.data() + sizeof(*header); if (base::Hash(key_data, header->key_length) != header->key_hash) { - RecordSyncOpenResult(cache_type_, OPEN_ENTRY_KEY_HASH_MISMATCH, had_index_); + RecordSyncOpenResult(cache_type_, OPEN_ENTRY_KEY_HASH_MISMATCH); return false; } @@ -1408,7 +1364,7 @@ key_.swap(key_from_header); } else { if (key_ != key_from_header) { - RecordSyncOpenResult(cache_type_, OPEN_ENTRY_KEY_MISMATCH, had_index_); + RecordSyncOpenResult(cache_type_, OPEN_ENTRY_KEY_MISMATCH); return false; } } @@ -1478,8 +1434,7 @@ int32_t sparse_data_size = 0; if (!OpenSparseFileIfExists(&sparse_data_size)) { - RecordSyncOpenResult(cache_type_, OPEN_ENTRY_SPARSE_OPEN_FAILED, - had_index_); + RecordSyncOpenResult(cache_type_, OPEN_ENTRY_SPARSE_OPEN_FAILED); return net::ERR_FAILED; } out_entry_stat->set_sparse_data_size(sparse_data_size); @@ -1500,7 +1455,7 @@ SIMPLE_CACHE_UMA(BOOLEAN, "EntryOpenedAndStream2Removed", cache_type_, removed_stream2); - RecordSyncOpenResult(cache_type_, OPEN_ENTRY_SUCCESS, had_index_); + RecordSyncOpenResult(cache_type_, OPEN_ENTRY_SUCCESS); initialized_ = true; return net::OK; } @@ -1551,11 +1506,11 @@ CreateEntryResult result; if (!InitializeCreatedFile(i, &result)) { - RecordSyncCreateResult(result, had_index_); + RecordSyncCreateResult(result); return net::ERR_FAILED; } } - RecordSyncCreateResult(CREATE_ENTRY_SUCCESS, had_index_); + RecordSyncCreateResult(CREATE_ENTRY_SUCCESS); initialized_ = true; return net::OK; } @@ -1818,20 +1773,10 @@ return result; } -void SimpleSynchronousEntry::RecordSyncCreateResult(CreateEntryResult result, - bool had_index) { +void SimpleSynchronousEntry::RecordSyncCreateResult(CreateEntryResult result) { DCHECK_LT(result, CREATE_ENTRY_MAX); SIMPLE_CACHE_UMA(ENUMERATION, "SyncCreateResult", cache_type_, result, CREATE_ENTRY_MAX); - if (had_index) { - SIMPLE_CACHE_UMA(ENUMERATION, - "SyncCreateResult_WithIndex", cache_type_, - result, CREATE_ENTRY_MAX); - } else { - SIMPLE_CACHE_UMA(ENUMERATION, - "SyncCreateResult_WithoutIndex", cache_type_, - result, CREATE_ENTRY_MAX); - } } FilePath SimpleSynchronousEntry::GetFilenameFromFileIndex(
diff --git a/net/disk_cache/simple/simple_synchronous_entry.h b/net/disk_cache/simple/simple_synchronous_entry.h index 59b3740..958a052e 100644 --- a/net/disk_cache/simple/simple_synchronous_entry.h +++ b/net/disk_cache/simple/simple_synchronous_entry.h
@@ -191,14 +191,12 @@ // Opens a disk cache entry on disk. The |key| parameter is optional, if empty // the operation may be slower. The |entry_hash| parameter is required. - // |had_index| is provided only for histograms. // |time_enqueued| is when this operation was added to the I/O thread pool, // and is provided only for histograms. static void OpenEntry(net::CacheType cache_type, const base::FilePath& path, const std::string& key, uint64_t entry_hash, - bool had_index, const base::TimeTicks& time_enqueued, SimpleFileTracker* file_tracker, int32_t trailer_prefetch_size, @@ -208,7 +206,6 @@ const base::FilePath& path, const std::string& key, uint64_t entry_hash, - bool had_index, const base::TimeTicks& time_enqueued, SimpleFileTracker* file_tracker, SimpleEntryCreationResults* out_results); @@ -341,7 +338,6 @@ const base::FilePath& path, const std::string& key, uint64_t entry_hash, - bool had_index, SimpleFileTracker* simple_file_tracker, int32_t stream_0_size); @@ -473,7 +469,7 @@ static bool TruncateFilesForEntryHash(const base::FilePath& path, uint64_t entry_hash); - void RecordSyncCreateResult(CreateEntryResult result, bool had_index); + void RecordSyncCreateResult(CreateEntryResult result); base::FilePath GetFilenameFromFileIndex(int file_index) const; @@ -482,7 +478,6 @@ const net::CacheType cache_type_; const base::FilePath path_; SimpleFileTracker::EntryFileKey entry_file_key_; - const bool had_index_; std::string key_; bool have_open_files_ = false;
diff --git a/net/dns/host_cache.cc b/net/dns/host_cache.cc index ac5802b..8b9ce44 100644 --- a/net/dns/host_cache.cc +++ b/net/dns/host_cache.cc
@@ -14,7 +14,6 @@ #include "base/time/default_tick_clock.h" #include "base/trace_event/trace_event.h" #include "net/base/ip_endpoint.h" -#include "net/base/net_errors.h" #include "net/base/trace_constants.h" #include "net/dns/host_resolver.h" #include "net/log/net_log.h" @@ -184,8 +183,9 @@ front.expires_ = std::min(front.expires(), back.expires()); front.network_changes_ = std::max(front.network_changes(), back.network_changes()); - front.total_hits_ = front.total_hits() + back.total_hits(); - front.stale_hits_ = front.stale_hits() + back.stale_hits(); + + front.total_hits_ = front.total_hits_ + back.total_hits_; + front.stale_hits_ = front.stale_hits_ + back.stale_hits_; return front; } @@ -244,9 +244,7 @@ source_(entry.source()), ttl_(entry.ttl()), expires_(now + ttl), - network_changes_(network_changes), - total_hits_(0), - stale_hits_(0) {} + network_changes_(network_changes) {} HostCache::Entry::Entry(int error, const base::Optional<AddressList>& addresses, @@ -260,11 +258,8 @@ text_records_(std::move(text_records)), hostnames_(std::move(hostnames)), source_(source), - ttl_(base::TimeDelta::FromSeconds(-1)), expires_(expires), - network_changes_(network_changes), - total_hits_(0), - stale_hits_(0) {} + network_changes_(network_changes) {} bool HostCache::Entry::IsStale(base::TimeTicks now, int network_changes) const { EntryStaleness stale;
diff --git a/net/dns/host_cache.h b/net/dns/host_cache.h index 0fca6de..662761d 100644 --- a/net/dns/host_cache.h +++ b/net/dns/host_cache.h
@@ -18,6 +18,7 @@ #include "base/gtest_prod_util.h" #include "base/logging.h" #include "base/macros.h" +#include "base/numerics/clamped_math.h" #include "base/optional.h" #include "base/threading/thread_checker.h" #include "base/time/time.h" @@ -26,6 +27,7 @@ #include "net/base/address_list.h" #include "net/base/expiring_cache.h" #include "net/base/host_port_pair.h" +#include "net/base/net_errors.h" #include "net/base/net_export.h" #include "net/dns/dns_util.h" #include "net/dns/host_resolver_source.h" @@ -221,22 +223,23 @@ base::DictionaryValue GetAsValue(bool include_staleness) const; // The resolve results for this entry. - int error_; + int error_ = ERR_FAILED; base::Optional<AddressList> addresses_; base::Optional<std::vector<std::string>> text_records_; base::Optional<std::vector<HostPortPair>> hostnames_; // Where results were obtained (e.g. DNS lookup, hosts file, etc). - Source source_; + Source source_ = SOURCE_UNKNOWN; // TTL obtained from the nameserver. Negative if unknown. - base::TimeDelta ttl_; + base::TimeDelta ttl_ = base::TimeDelta::FromSeconds(-1); base::TimeTicks expires_; // Copied from the cache's network_changes_ when the entry is set; can // later be compared to it to see if the entry was received on the current // network. - int network_changes_; - int total_hits_; - int stale_hits_; + int network_changes_ = -1; + // Use clamped math to cap hit counts at INT_MAX. + base::ClampedNumeric<int> total_hits_ = 0; + base::ClampedNumeric<int> stale_hits_ = 0; }; // Interface for interacting with persistent storage, to be provided by the
diff --git a/net/dns/host_cache_unittest.cc b/net/dns/host_cache_unittest.cc index cf5f0253..8dffd246 100644 --- a/net/dns/host_cache_unittest.cc +++ b/net/dns/host_cache_unittest.cc
@@ -14,7 +14,6 @@ #include "base/strings/string_util.h" #include "base/strings/stringprintf.h" #include "base/values.h" -#include "net/base/net_errors.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h"
diff --git a/net/network_error_logging/network_error_logging_delegate.cc b/net/network_error_logging/network_error_logging_delegate.cc deleted file mode 100644 index 649a139..0000000 --- a/net/network_error_logging/network_error_logging_delegate.cc +++ /dev/null
@@ -1,35 +0,0 @@ -// Copyright 2018 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "net/network_error_logging/network_error_logging_delegate.h" - -#include <memory> - -namespace net { - -namespace { - -class NetworkErrorLoggingDelegateImpl : public NetworkErrorLoggingDelegate { - public: - NetworkErrorLoggingDelegateImpl() = default; - - ~NetworkErrorLoggingDelegateImpl() override = default; - - private: - DISALLOW_COPY_AND_ASSIGN(NetworkErrorLoggingDelegateImpl); -}; - -} // namespace - -NetworkErrorLoggingDelegate::~NetworkErrorLoggingDelegate() = default; - -// static -std::unique_ptr<NetworkErrorLoggingDelegate> -NetworkErrorLoggingDelegate::Create() { - return std::make_unique<NetworkErrorLoggingDelegateImpl>(); -} - -NetworkErrorLoggingDelegate::NetworkErrorLoggingDelegate() = default; - -} // namespace net
diff --git a/net/network_error_logging/network_error_logging_delegate.h b/net/network_error_logging/network_error_logging_delegate.h deleted file mode 100644 index 454b985..0000000 --- a/net/network_error_logging/network_error_logging_delegate.h +++ /dev/null
@@ -1,30 +0,0 @@ -// Copyright 2018 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef NET_NETWORK_ERROR_LOGGING_NETWORK_ERROR_LOGGING_DELEGATE_H_ -#define NET_NETWORK_ERROR_LOGGING_NETWORK_ERROR_LOGGING_DELEGATE_H_ - -#include <memory> - -#include "base/macros.h" -#include "net/base/net_export.h" - -namespace net { - -class NET_EXPORT NetworkErrorLoggingDelegate { - public: - virtual ~NetworkErrorLoggingDelegate(); - - static std::unique_ptr<NetworkErrorLoggingDelegate> Create(); - - protected: - NetworkErrorLoggingDelegate(); - - private: - DISALLOW_COPY_AND_ASSIGN(NetworkErrorLoggingDelegate); -}; - -} // namespace net - -#endif // NET_NETWORK_ERROR_LOGGING_NETWORK_ERROR_LOGGING_DELEGATE_H_
diff --git a/net/network_error_logging/network_error_logging_service.cc b/net/network_error_logging/network_error_logging_service.cc index 4607d9f..537445cc 100644 --- a/net/network_error_logging/network_error_logging_service.cc +++ b/net/network_error_logging/network_error_logging_service.cc
@@ -22,7 +22,6 @@ #include "net/base/ip_address.h" #include "net/base/net_errors.h" #include "net/log/net_log.h" -#include "net/network_error_logging/network_error_logging_delegate.h" #include "net/reporting/reporting_service.h" #include "url/gurl.h" #include "url/origin.h" @@ -181,11 +180,7 @@ class NetworkErrorLoggingServiceImpl : public NetworkErrorLoggingService { public: - explicit NetworkErrorLoggingServiceImpl( - std::unique_ptr<NetworkErrorLoggingDelegate> delegate) - : delegate_(std::move(delegate)) { - DCHECK(delegate_); - } + NetworkErrorLoggingServiceImpl() = default; ~NetworkErrorLoggingServiceImpl() override = default; @@ -476,8 +471,6 @@ using WildcardPolicyMap = std::map<std::string, std::set<const OriginPolicy*>>; - std::unique_ptr<NetworkErrorLoggingDelegate> delegate_; - PolicyMap policies_; WildcardPolicyMap wildcard_policies_; @@ -805,9 +798,9 @@ } // static -std::unique_ptr<NetworkErrorLoggingService> NetworkErrorLoggingService::Create( - std::unique_ptr<NetworkErrorLoggingDelegate> delegate) { - return std::make_unique<NetworkErrorLoggingServiceImpl>(std::move(delegate)); +std::unique_ptr<NetworkErrorLoggingService> +NetworkErrorLoggingService::Create() { + return std::make_unique<NetworkErrorLoggingServiceImpl>(); } NetworkErrorLoggingService::~NetworkErrorLoggingService() = default;
diff --git a/net/network_error_logging/network_error_logging_service.h b/net/network_error_logging/network_error_logging_service.h index 7527ff1b..588690ec 100644 --- a/net/network_error_logging/network_error_logging_service.h +++ b/net/network_error_logging/network_error_logging_service.h
@@ -38,8 +38,6 @@ namespace net { -class NetworkErrorLoggingDelegate; - class NET_EXPORT NetworkErrorLoggingService { public: // The details of a network error that are included in an NEL report. @@ -174,8 +172,7 @@ static void RecordRequestDiscardedForNoNetworkErrorLoggingService(); static void RecordRequestDiscardedForInsecureOrigin(); - static std::unique_ptr<NetworkErrorLoggingService> Create( - std::unique_ptr<NetworkErrorLoggingDelegate> delegate); + static std::unique_ptr<NetworkErrorLoggingService> Create(); virtual ~NetworkErrorLoggingService();
diff --git a/net/network_error_logging/network_error_logging_service_unittest.cc b/net/network_error_logging/network_error_logging_service_unittest.cc index 89eae7da..442cb32 100644 --- a/net/network_error_logging/network_error_logging_service_unittest.cc +++ b/net/network_error_logging/network_error_logging_service_unittest.cc
@@ -16,7 +16,6 @@ #include "base/values.h" #include "net/base/ip_address.h" #include "net/base/net_errors.h" -#include "net/network_error_logging/network_error_logging_delegate.h" #include "net/network_error_logging/network_error_logging_service.h" #include "net/reporting/reporting_policy.h" #include "net/reporting/reporting_service.h" @@ -119,8 +118,7 @@ class NetworkErrorLoggingServiceTest : public ::testing::Test { protected: NetworkErrorLoggingServiceTest() { - service_ = NetworkErrorLoggingService::Create( - NetworkErrorLoggingDelegate::Create()); + service_ = NetworkErrorLoggingService::Create(); CreateReportingService(); }
diff --git a/net/url_request/url_request_context_builder.cc b/net/url_request/url_request_context_builder.cc index 388ae80a..5c7d056 100644 --- a/net/url_request/url_request_context_builder.cc +++ b/net/url_request/url_request_context_builder.cc
@@ -57,7 +57,6 @@ #endif #if BUILDFLAG(ENABLE_REPORTING) -#include "net/network_error_logging/network_error_logging_delegate.h" #include "net/network_error_logging/network_error_logging_service.h" #include "net/reporting/reporting_policy.h" #include "net/reporting/reporting_service.h" @@ -544,8 +543,7 @@ if (network_error_logging_enabled_) { storage->set_network_error_logging_service( - NetworkErrorLoggingService::Create( - NetworkErrorLoggingDelegate::Create())); + NetworkErrorLoggingService::Create()); } // If both Reporting and Network Error Logging are actually enabled, then
diff --git a/pdf/pdfium/fuzzers/BUILD.gn b/pdf/pdfium/fuzzers/BUILD.gn index 63fd3bf..b9b45dcf 100644 --- a/pdf/pdfium/fuzzers/BUILD.gn +++ b/pdf/pdfium/fuzzers/BUILD.gn
@@ -42,6 +42,7 @@ ":pdf_codec_jpeg_fuzzer", ":pdf_css_fuzzer", ":pdf_fm2js_fuzzer", + ":pdf_formcalc_context_fuzzer", ":pdf_formcalc_fuzzer", ":pdfium_xfa_fuzzer", ] @@ -250,6 +251,14 @@ dict = "dicts/pdf_formcalc.dict" } + fuzzer_test("pdf_formcalc_context_fuzzer") { + sources = [] + deps = [ + "//third_party/pdfium/testing/fuzzers:pdf_formcalc_fuzzer_src", + ] + dict = "dicts/pdf_xfa_js.dict" + } + fuzzer_test("pdf_formcalc_fuzzer") { sources = [] deps = [
diff --git a/pdf/pdfium/fuzzers/dicts/pdf_xfa_js.dict b/pdf/pdfium/fuzzers/dicts/pdf_xfa_js.dict new file mode 100644 index 0000000..1d33e869 --- /dev/null +++ b/pdf/pdfium/fuzzers/dicts/pdf_xfa_js.dict
@@ -0,0 +1,215 @@ +# Copyright 2019 The Chromium Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +# Extracted from JSE_METHOD and JSE_PROP entries in PDFium's fxjs/xfa directory. + +# JSE_METHOD + +absPage +absPageCount +absPageCountInBatch +absPageInBatch +absPageSpan +addInstance +addItem +addNew +append +applyXSL +assignNode +beep +boundItem +cancel +cancelBatch +clear +clearErrorList +clearItems +clone +close +createNode +deleteItem +documentCountInBatch +documentInBatch +emit +enumerate +evaluate +execCalculate +execEvent +execInitialize +execute +execValidate +exportData +first +formNodes +getAttribute +getDelta +getDeltas +getDisplayItem +getElement +getFocus +getItemState +getSaveItem +gotoRecord +gotoURL +h +hasDataChanged +importData +insert +insertInstance +isBOF +isCompatibleNS +isEOF +isPropertySpecified +isRecordGroup +item +last +loadXML +message +messageBox +metadata +method_name +moveCurrentRecord +moveInstance +namedItem +next +open +openList +page +pageContent +pageCount +pageDown +pageSpan +pageUp +previous +print +recalculate +record +relayout +relayoutPageArea +remerge +remove +removeAttribute +removeInstance +requery +reset +resetData +resolveNode +resolveNodes +response +restore +resync +saveFilteredXML +saveXML +selectedMember +setAttribute +setElement +setFocus +setInstances +setItemState +sheet +sheetCount +sheetCountInBatch +sheetInBatch +sign +trace +traceActivate +traceDeactivate +traceEnabled +update +updateBatch +verifySignature +w +x +y + +# JSE_PROP + +aliasNode +all +appType +calculationsEnabled +cancelAction +change +checksumS +classAll +classIndex +className +commitKey +content +context +count +currentPage +currentRecordNumber +currentValue +db +defaultValue +editValue +errorText +format +formatMessage +formattedValue +fullText +index +instanceManager +isContainer +isDefined +isNull +keyDown +language +length +locale +max +min +model +modifier +name +newContentType +newText +nodes +ns +numPages +oneOfChild +parent +parentSubform +platform +prevContentType +prevText +prop_name +rawValue +ready +recordsAfter +recordsBefore +reenter +savedValue +ScriptAttributeBool +ScriptAttributeInteger +ScriptAttributeString +ScriptSomBorderColor +ScriptSomBorderWidth +ScriptSomDataNode +ScriptSomDefaultValue +ScriptSomDefaultValue_Read +ScriptSomFillColor +ScriptSomFontColor +ScriptSomInstanceIndex +ScriptSomMandatory +ScriptSomMandatoryMessage +ScriptSomValidationMessage +ScriptSubmitFormatMode +selectedIndex +selEnd +selStart +shift +soapFaultCode +soapFaultString +somExpression +stateless +target +thisValue +title +transient +type +validationsEnabled +value +variation +version
diff --git a/services/audio/input_controller.cc b/services/audio/input_controller.cc index 3657131a..ce1f890 100644 --- a/services/audio/input_controller.cc +++ b/services/audio/input_controller.cc
@@ -554,7 +554,6 @@ if (output_stream) stream_->SetOutputDeviceForAec(output_stream->GetDeviceId()); break; - case media::EchoCancellationType::kAec2: case media::EchoCancellationType::kAec3: #if defined(AUDIO_PROCESSING_IN_AUDIO_SERVICE) if (processing_helper_)
diff --git a/services/audio/public/cpp/audio_processing_mojom_traits.h b/services/audio/public/cpp/audio_processing_mojom_traits.h index 58bd591..ff309a2 100644 --- a/services/audio/public/cpp/audio_processing_mojom_traits.h +++ b/services/audio/public/cpp/audio_processing_mojom_traits.h
@@ -59,8 +59,6 @@ switch (type) { case media::EchoCancellationType::kDisabled: return audio::mojom::EchoCancellationType::kDisabled; - case media::EchoCancellationType::kAec2: - return audio::mojom::EchoCancellationType::kAec2; case media::EchoCancellationType::kAec3: return audio::mojom::EchoCancellationType::kAec3; case media::EchoCancellationType::kSystemAec: @@ -76,9 +74,6 @@ case audio::mojom::EchoCancellationType::kDisabled: *out = media::EchoCancellationType::kDisabled; return true; - case audio::mojom::EchoCancellationType::kAec2: - *out = media::EchoCancellationType::kAec2; - return true; case audio::mojom::EchoCancellationType::kAec3: *out = media::EchoCancellationType::kAec3; return true;
diff --git a/services/audio/public/mojom/audio_processing.mojom b/services/audio/public/mojom/audio_processing.mojom index 7f992a33..90ad02d 100644 --- a/services/audio/public/mojom/audio_processing.mojom +++ b/services/audio/public/mojom/audio_processing.mojom
@@ -47,7 +47,6 @@ enum EchoCancellationType { kDisabled, - kAec2, kAec3, kSystemAec };
diff --git a/services/identity/identity_accessor_impl_unittest.cc b/services/identity/identity_accessor_impl_unittest.cc index 30a6a8a3..b657d336 100644 --- a/services/identity/identity_accessor_impl_unittest.cc +++ b/services/identity/identity_accessor_impl_unittest.cc
@@ -6,13 +6,8 @@ #include "base/run_loop.h" #include "base/test/scoped_task_environment.h" #include "build/build_config.h" -#include "components/image_fetcher/core/fake_image_decoder.h" #include "components/signin/core/browser/account_info.h" #include "components/signin/core/browser/account_tracker_service.h" -#include "components/signin/core/browser/fake_profile_oauth2_token_service.h" -#include "components/signin/core/browser/signin_manager.h" -#include "components/signin/core/browser/test_signin_client.h" -#include "components/sync_preferences/testing_pref_service_syncable.h" #include "services/identity/identity_service.h" #include "services/identity/public/cpp/account_state.h" #include "services/identity/public/cpp/identity_test_environment.h" @@ -33,55 +28,12 @@ class IdentityAccessorImplTest : public testing::Test { public: IdentityAccessorImplTest() - : signin_client_(&pref_service_), - token_service_(&pref_service_), -#if defined(OS_CHROMEOS) - signin_manager_(&signin_client_, &token_service_, &account_tracker_), -#else - signin_manager_(&signin_client_, - &token_service_, - &account_tracker_, - nullptr, - signin::AccountConsistencyMethod::kDisabled), -#endif - gaia_cookie_manager_service_( - &token_service_, - &signin_client_, - base::BindRepeating( - [](network::TestURLLoaderFactory* test_url_loader_factory) - -> scoped_refptr<network::SharedURLLoaderFactory> { - return test_url_loader_factory->GetSafeWeakWrapper(); - }, - signin_client_.test_url_loader_factory())), - identity_test_environment_(&pref_service_, - &account_tracker_, - &account_fetcher_, - &token_service_, - &signin_manager_, - &gaia_cookie_manager_service_, - signin_client_.test_url_loader_factory()), + : identity_test_environment_(), service_( identity_test_environment_.identity_manager(), - &account_tracker_, - test_connector_factory_.RegisterInstance(mojom::kServiceName)) { - AccountTrackerService::RegisterPrefs(pref_service_.registry()); - AccountFetcherService::RegisterPrefs(pref_service_.registry()); - ProfileOAuth2TokenService::RegisterProfilePrefs(pref_service_.registry()); - SigninManagerBase::RegisterProfilePrefs(pref_service_.registry()); - SigninManagerBase::RegisterPrefs(pref_service_.registry()); - - account_tracker_.Initialize(&pref_service_, base::FilePath()); - account_fetcher_.Initialize( - &signin_client_, &token_service_, &account_tracker_, - std::make_unique<image_fetcher::FakeImageDecoder>()); - signin_manager_.Initialize(&pref_service_); - } - - ~IdentityAccessorImplTest() override { - signin_manager_.Shutdown(); - account_fetcher_.Shutdown(); - account_tracker_.Shutdown(); - } + identity_test_environment_.identity_manager() + ->GetAccountTrackerService(), + test_connector_factory_.RegisterInstance(mojom::kServiceName)) {} void TearDown() override { // Explicitly destruct IdentityAccessorImpl so that it doesn't outlive its @@ -169,26 +121,11 @@ base::Optional<std::string> access_token_; GoogleServiceAuthError access_token_error_; - AccountTrackerService* account_tracker() { return &account_tracker_; } - FakeProfileOAuth2TokenService* token_service() { return &token_service_; } - IdentityTestEnvironment* identity_test_environment() { return &identity_test_environment_; } private: - sync_preferences::TestingPrefServiceSyncable pref_service_; - AccountTrackerService account_tracker_; - AccountFetcherService account_fetcher_; - TestSigninClient signin_client_; - FakeProfileOAuth2TokenService token_service_; -#if defined(OS_CHROMEOS) - SigninManagerBase signin_manager_; -#else - SigninManager signin_manager_; -#endif - GaiaCookieManagerService gaia_cookie_manager_service_; - identity::IdentityTestEnvironment identity_test_environment_; service_manager::TestConnectorFactory test_connector_factory_; IdentityService service_; @@ -363,7 +300,8 @@ // Set the refresh token, but don't sign in yet. std::string account_id_to_use = - account_tracker()->SeedAccountInfo(kTestGaiaId, kTestEmail); + identity_test_environment()->MakeAccountAvailable(kTestEmail).account_id; + identity_test_environment()->SetRefreshTokenForAccount(account_id_to_use); base::RunLoop run_loop; GetIdentityAccessorImpl()->GetPrimaryAccountWhenAvailable(base::BindRepeating( @@ -513,8 +451,13 @@ // Check that the account info for a given GAIA ID has expected values if that // GAIA ID is known and there is no refresh token available for it. TEST_F(IdentityAccessorImplTest, GetAccountInfoForKnownGaiaIdNoRefreshToken) { + AccountInfo input_info; + input_info.email = kTestEmail; + input_info.gaia = kTestGaiaId; std::string account_id = - account_tracker()->SeedAccountInfo(kTestGaiaId, kTestEmail); + identity_test_environment()->identity_manager()->LegacySeedAccountInfo( + input_info); + base::RunLoop run_loop; GetIdentityAccessorImpl()->GetAccountInfoFromGaiaId( kTestGaiaId, @@ -534,8 +477,7 @@ // GAIA ID is known and has a refresh token available. TEST_F(IdentityAccessorImplTest, GetAccountInfoForKnownGaiaIdRefreshToken) { std::string account_id = - account_tracker()->SeedAccountInfo(kTestGaiaId, kTestEmail); - identity_test_environment()->SetRefreshTokenForAccount(account_id); + identity_test_environment()->MakeAccountAvailable(kTestEmail).account_id; base::RunLoop run_loop; GetIdentityAccessorImpl()->GetAccountInfoFromGaiaId(
diff --git a/services/identity/public/cpp/identity_manager.h b/services/identity/public/cpp/identity_manager.h index d172a0e..d4941f5 100644 --- a/services/identity/public/cpp/identity_manager.h +++ b/services/identity/public/cpp/identity_manager.h
@@ -42,6 +42,9 @@ namespace identity { +// TODO(https://crbug.com/933109): Delete this when conversion is done. +class IdentityAccessorImplTest; + class AccountsMutator; class AccountsCookieMutator; class DiagnosticsProvider; @@ -516,9 +519,11 @@ const std::string& locale, const std::string& picture_url); - // This friend is temporary during the conversion process. - // TODO(crbug.com/889902): Delete this friendship when conversion is done. + // These friends are temporary during the conversion process. + // TODO(https://crbug.com/889902): Delete this when conversion is done. friend SigninManagerAndroid; + // TODO(https://crbug.com/933109): Delete this when conversion is done. + friend IdentityAccessorImplTest; // Private getters used for testing only (i.e. see identity_test_utils.h). SigninManagerBase* GetSigninManager();
diff --git a/services/identity/public/cpp/identity_test_environment.cc b/services/identity/public/cpp/identity_test_environment.cc index 8b91289b..a72f1b5 100644 --- a/services/identity/public/cpp/identity_test_environment.cc +++ b/services/identity/public/cpp/identity_test_environment.cc
@@ -209,24 +209,6 @@ FakeProfileOAuth2TokenService* token_service, SigninManagerBase* signin_manager, GaiaCookieManagerService* gaia_cookie_manager_service, - network::TestURLLoaderFactory* test_url_loader_factory) - : IdentityTestEnvironment(pref_service, - account_tracker_service, - account_fetcher_service, - token_service, - signin_manager, - gaia_cookie_manager_service, - test_url_loader_factory, - /*dependency_owner=*/nullptr, - /*identity_manager=*/nullptr) {} - -IdentityTestEnvironment::IdentityTestEnvironment( - PrefService* pref_service, - AccountTrackerService* account_tracker_service, - AccountFetcherService* account_fetcher_service, - FakeProfileOAuth2TokenService* token_service, - SigninManagerBase* signin_manager, - GaiaCookieManagerService* gaia_cookie_manager_service, IdentityManager* identity_manager, network::TestURLLoaderFactory* test_url_loader_factory) : IdentityTestEnvironment(pref_service,
diff --git a/services/identity/public/cpp/identity_test_environment.h b/services/identity/public/cpp/identity_test_environment.h index 9a392095..32b87028 100644 --- a/services/identity/public/cpp/identity_test_environment.h +++ b/services/identity/public/cpp/identity_test_environment.h
@@ -33,9 +33,6 @@ class IdentityManagerDependenciesOwner; class TestIdentityManagerObserver; -// Necessary to declare this test as a temporary friend. -class IdentityAccessorImplTest; - // Class that creates an IdentityManager for use in testing contexts and // provides facilities for driving that IdentityManager. The IdentityManager // instance is brought up in an environment where the primary account is @@ -275,10 +272,6 @@ friend class ::IdentityTestEnvironmentChromeBrowserStateAdaptor; friend class ::IdentityTestEnvironmentProfileAdaptor; - // TODO(https://crbug.com/933109): Remove friendship after conversion to - // IdentityManager is complete. - friend class identity::IdentityAccessorImplTest; - struct AccessTokenRequestState { AccessTokenRequestState(); ~AccessTokenRequestState(); @@ -293,22 +286,6 @@ base::OnceClosure on_available; }; - // Constructor that takes in instances of the dependencies of - // IdentityManager and constructs an IdentityManager instance from those - // dependencies. For use in contexts where those dependencies are still - // being used directly by the creator of this object (i.e., while a test is - // being incrementally converted). Prefer the above constructor, and switch to - // that constructor once possible (e.g., when an incremental conversion is - // completed). NOTE: The passed-in objects must all outlive this object. - IdentityTestEnvironment( - PrefService* pref_service, - AccountTrackerService* account_tracker_service, - AccountFetcherService* account_fetcher_service, - FakeProfileOAuth2TokenService* token_service, - SigninManagerBase* signin_manager, - GaiaCookieManagerService* gaia_cookie_manager_service, - network::TestURLLoaderFactory* test_url_loader_factory = nullptr); - // Constructor that takes in an IdentityManager instance as well as instances // of the dependencies of that IdentityManager. For use only in contexts where // IdentityManager and its dependencies are all unavoidably created by the
diff --git a/storage/browser/quota/quota_manager.cc b/storage/browser/quota/quota_manager.cc index 80bbbf44..82948ed 100644 --- a/storage/browser/quota/quota_manager.cc +++ b/storage/browser/quota/quota_manager.cc
@@ -195,15 +195,16 @@ } // namespace -class QuotaManager::UsageAndQuotaHelper : public QuotaTask { +// Helper to asynchronously gather usage and quota information. +class QuotaManager::UsageAndQuotaInfoGatherer : public QuotaTask { public: - UsageAndQuotaHelper(QuotaManager* manager, - const url::Origin& origin, - StorageType type, - bool is_unlimited, - bool is_session_only, - bool is_incognito, - UsageAndQuotaWithBreakdownCallback callback) + UsageAndQuotaInfoGatherer(QuotaManager* manager, + const url::Origin& origin, + StorageType type, + bool is_unlimited, + bool is_session_only, + bool is_incognito, + UsageAndQuotaWithBreakdownCallback callback) : QuotaTask(manager), origin_(origin), callback_(std::move(callback)), @@ -219,20 +220,20 @@ // Gather 4 pieces of info before computing an answer: // settings, device_storage_capacity, host_usage, and host_quota. base::Closure barrier = base::BarrierClosure( - 4, base::BindOnce(&UsageAndQuotaHelper::OnBarrierComplete, + 4, base::BindOnce(&UsageAndQuotaInfoGatherer::OnBarrierComplete, weak_factory_.GetWeakPtr())); std::string host = net::GetHostOrSpecFromURL(origin_.GetURL()); manager()->GetQuotaSettings( - base::BindOnce(&UsageAndQuotaHelper::OnGotSettings, + base::BindOnce(&UsageAndQuotaInfoGatherer::OnGotSettings, weak_factory_.GetWeakPtr(), barrier)); manager()->GetStorageCapacity( - base::BindOnce(&UsageAndQuotaHelper::OnGotCapacity, + base::BindOnce(&UsageAndQuotaInfoGatherer::OnGotCapacity, weak_factory_.GetWeakPtr(), barrier)); manager()->GetHostUsageWithBreakdown( host, type_, - base::BindOnce(&UsageAndQuotaHelper::OnGotHostUsage, + base::BindOnce(&UsageAndQuotaInfoGatherer::OnGotHostUsage, weak_factory_.GetWeakPtr(), barrier)); // Determine host_quota differently depending on type. @@ -244,7 +245,7 @@ kSyncableStorageDefaultHostQuota); } else if (type_ == StorageType::kPersistent) { manager()->GetPersistentHostQuota( - host, base::BindOnce(&UsageAndQuotaHelper::SetDesiredHostQuota, + host, base::BindOnce(&UsageAndQuotaInfoGatherer::SetDesiredHostQuota, weak_factory_.GetWeakPtr(), barrier)); } else { DCHECK_EQ(StorageType::kTemporary, type_); @@ -341,8 +342,8 @@ int64_t host_usage_ = 0; blink::mojom::UsageBreakdownPtr host_usage_breakdown_; QuotaSettings settings_; - base::WeakPtrFactory<UsageAndQuotaHelper> weak_factory_; - DISALLOW_COPY_AND_ASSIGN(UsageAndQuotaHelper); + base::WeakPtrFactory<UsageAndQuotaInfoGatherer> weak_factory_; + DISALLOW_COPY_AND_ASSIGN(UsageAndQuotaInfoGatherer); }; // Helper to asynchronously gather information needed at the start of an @@ -930,7 +931,7 @@ bool is_session_only = type == StorageType::kTemporary && special_storage_policy_ && special_storage_policy_->IsStorageSessionOnly(origin.GetURL()); - UsageAndQuotaHelper* helper = new UsageAndQuotaHelper( + UsageAndQuotaInfoGatherer* helper = new UsageAndQuotaInfoGatherer( this, origin, type, IsStorageUnlimited(origin, type), is_session_only, is_incognito_, std::move(callback)); helper->Start();
diff --git a/storage/browser/quota/quota_manager.h b/storage/browser/quota/quota_manager.h index 7ab8428e..649edf36 100644 --- a/storage/browser/quota/quota_manager.h +++ b/storage/browser/quota/quota_manager.h
@@ -277,7 +277,7 @@ friend struct QuotaManagerDeleter; class EvictionRoundInfoHelper; - class UsageAndQuotaHelper; + class UsageAndQuotaInfoGatherer; class GetUsageInfoTask; class OriginDataDeleter; class HostDataDeleter;
diff --git a/testing/buildbot/chromium.android.json b/testing/buildbot/chromium.android.json index 26f98e1..80c70a2 100644 --- a/testing/buildbot/chromium.android.json +++ b/testing/buildbot/chromium.android.json
@@ -6771,7 +6771,7 @@ "name": "shard #${SHARD_INDEX} logcats" } ], - "shards": 11 + "shards": 13 }, "test": "content_browsertests" },
diff --git a/testing/buildbot/chromium.clang.json b/testing/buildbot/chromium.clang.json index 58e048e..8314b88 100644 --- a/testing/buildbot/chromium.clang.json +++ b/testing/buildbot/chromium.clang.json
@@ -13573,6 +13573,622 @@ } ] }, + "ToTMacOfficial": { + "gtest_tests": [ + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "accessibility_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "angle_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "app_shell_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "base_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "blink_common_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "blink_fuzzer_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "blink_heap_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "blink_platform_unittests" + }, + { + "name": "webkit_unit_tests", + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "blink_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "boringssl_crypto_tests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "boringssl_ssl_tests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true, + "shards": 10 + }, + "test": "browser_tests" + }, + { + "args": [ + "--disable-features=WebUIPolymer2", + "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer1_browser_tests.filter" + ], + "name": "webui_polymer1_browser_tests", + "swarming": { + "can_use_on_swarming_builders": true, + "shards": 4 + }, + "test": "browser_tests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "cacheinvalidation_unittests" + }, + { + "args": [ + "--gtest_filter=-*UsingRealWebcam*" + ], + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "capture_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "cast_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "cc_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "chrome_app_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "chromedriver_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "components_browsertests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "components_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true, + "shards": 6 + }, + "test": "content_browsertests" + }, + { + "args": [ + "--enable-perfetto", + "--gtest_filter=TracingControllerTest.*" + ], + "name": "perfetto_content_browsertests", + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "content_browsertests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "content_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "crashpad_tests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "cronet_tests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "cronet_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "crypto_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "device_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "display_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "events_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "extensions_browsertests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "extensions_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "filesystem_service_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "gcm_unit_tests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "gfx_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "gin_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "google_apis_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "gpu_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "headless_browsertests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "headless_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true, + "shards": 3 + }, + "test": "interactive_ui_tests" + }, + { + "args": [ + "--disable-features=WebUIPolymer2", + "--test-launcher-filter-file=../../testing/buildbot/filters/webui_polymer1_interactive_ui_tests.filter" + ], + "name": "webui_polymer1_interactive_ui_tests", + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "interactive_ui_tests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "ipc_tests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "jingle_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "latency_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "leveldb_service_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "libjingle_xmpp_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "media_blink_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "media_service_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "media_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "message_center_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "midi_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "mojo_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "nacl_loader_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "native_theme_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "net_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "pdf_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "ppapi_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "printing_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "remoting_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "sandbox_mac_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "service_manager_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "services_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "shell_dialogs_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "skia_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "snapshot_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "sql_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "storage_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "sync_integration_tests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "ui_base_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "ui_touch_selection_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "unit_tests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "url_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "views_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "viz_unittests" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "wtf_unittests" + } + ], + "isolated_scripts": [ + { + "isolate_name": "blink_python_tests", + "name": "blink_python_tests", + "swarming": { + "can_use_on_swarming_builders": true + } + }, + { + "args": [ + "--test-type=integration" + ], + "isolate_name": "chromedriver_py_tests", + "name": "chromedriver_py_tests", + "swarming": { + "can_use_on_swarming_builders": true + } + }, + { + "isolate_name": "chromedriver_replay_unittests", + "name": "chromedriver_replay_unittests", + "swarming": { + "can_use_on_swarming_builders": true + } + }, + { + "args": [ + "--gtest-benchmark-name=components_perftests" + ], + "isolate_name": "components_perftests", + "merge": { + "args": [ + "--smoke-test-mode" + ], + "script": "//tools/perf/process_perf_results.py" + }, + "name": "components_perftests", + "swarming": { + "can_use_on_swarming_builders": true + } + }, + { + "isolate_name": "content_shell_crash_test", + "name": "content_shell_crash_test", + "swarming": { + "can_use_on_swarming_builders": true + } + }, + { + "isolate_name": "flatbuffers_unittests", + "name": "flatbuffers_unittests", + "swarming": { + "can_use_on_swarming_builders": true + } + }, + { + "isolate_name": "metrics_python_tests", + "name": "metrics_python_tests", + "swarming": { + "can_use_on_swarming_builders": true + } + }, + { + "isolate_name": "telemetry_gpu_unittests", + "name": "telemetry_gpu_unittests", + "swarming": { + "can_use_on_swarming_builders": true, + "idempotent": false + } + }, + { + "isolate_name": "telemetry_perf_unittests", + "name": "telemetry_perf_unittests", + "swarming": { + "can_use_on_swarming_builders": true, + "idempotent": false, + "shards": 12 + } + }, + { + "args": [ + "--jobs=1", + "--extra-browser-args=--disable-gpu" + ], + "isolate_name": "telemetry_unittests", + "name": "telemetry_unittests", + "swarming": { + "can_use_on_swarming_builders": true, + "idempotent": false, + "shards": 4 + } + }, + { + "args": [ + "--gtest-benchmark-name=views_perftests" + ], + "isolate_name": "views_perftests", + "merge": { + "args": [ + "--smoke-test-mode" + ], + "script": "//tools/perf/process_perf_results.py" + }, + "name": "views_perftests", + "swarming": { + "can_use_on_swarming_builders": true + } + }, + { + "args": [ + "--num-retries=3" + ], + "isolate_name": "blink_web_tests_exparchive", + "merge": { + "args": [ + "--verbose" + ], + "script": "//third_party/blink/tools/merge_web_test_results.py" + }, + "name": "webkit_layout_tests", + "results_handler": "layout tests", + "swarming": { + "can_use_on_swarming_builders": true, + "shards": 12 + } + } + ] + }, "ToTWin": { "gtest_tests": [ {
diff --git a/testing/buildbot/chromium.fyi.json b/testing/buildbot/chromium.fyi.json index aab42463..5e425d2 100644 --- a/testing/buildbot/chromium.fyi.json +++ b/testing/buildbot/chromium.fyi.json
@@ -9009,8 +9009,8 @@ }, { "isolate_coverage_data": true, - "isolate_name": "net_host_resolver_impl_fuzzer", - "name": "net_host_resolver_impl_fuzzer", + "isolate_name": "net_host_resolver_manager_fuzzer", + "name": "net_host_resolver_manager_fuzzer", "swarming": { "can_use_on_swarming_builders": false }
diff --git a/testing/buildbot/gn_isolate_map.pyl b/testing/buildbot/gn_isolate_map.pyl index fb57d87..df955e1 100644 --- a/testing/buildbot/gn_isolate_map.pyl +++ b/testing/buildbot/gn_isolate_map.pyl
@@ -1764,8 +1764,8 @@ "label": "//net:net_gzip_source_stream_fuzzer", "type": "fuzzer", }, - "net_host_resolver_impl_fuzzer": { - "label": "//net/dns:net_host_resolver_impl_fuzzer", + "net_host_resolver_manager_fuzzer": { + "label": "//net/dns:net_host_resolver_manager_fuzzer", "type": "fuzzer", }, "net_hpack_decoder_fuzzer": {
diff --git a/testing/buildbot/test_suite_exceptions.pyl b/testing/buildbot/test_suite_exceptions.pyl index 443416d..6d59924 100644 --- a/testing/buildbot/test_suite_exceptions.pyl +++ b/testing/buildbot/test_suite_exceptions.pyl
@@ -355,7 +355,7 @@ # chromium.android 'Lollipop Phone Tester': { 'swarming': { - 'shards': 11, + 'shards': 13, }, }, # chromium.linux
diff --git a/testing/buildbot/test_suites.pyl b/testing/buildbot/test_suites.pyl index d8908b1..d396e53 100644 --- a/testing/buildbot/test_suites.pyl +++ b/testing/buildbot/test_suites.pyl
@@ -1444,7 +1444,7 @@ 'can_use_on_swarming_builders': False, }, }, - 'net_host_resolver_impl_fuzzer': { + 'net_host_resolver_manager_fuzzer': { 'swarming': { 'can_use_on_swarming_builders': False, },
diff --git a/testing/buildbot/waterfalls.pyl b/testing/buildbot/waterfalls.pyl index 24821c6..3a8c55b 100644 --- a/testing/buildbot/waterfalls.pyl +++ b/testing/buildbot/waterfalls.pyl
@@ -862,6 +862,13 @@ '--test-launcher-print-test-stdio=always', ], }, + # Used on an internal builder. + 'ToTMacOfficial': { + 'test_suites': { + 'gtest_tests': 'chromium_mac_gtests', + 'isolated_scripts': 'chromium_rel_isolated_scripts', + }, + }, 'ToTWin': { 'test_suites': { 'gtest_tests': 'chromium_win_gtests',
diff --git a/third_party/.gitignore b/third_party/.gitignore index 181f115..5de7fa31 100644 --- a/third_party/.gitignore +++ b/third_party/.gitignore
@@ -213,7 +213,6 @@ /usrsctp/usrsctplib /v8-i18n /valgrind -/visualmetrics /wayland/src /wayland-protocols/src /wds/src
diff --git a/third_party/blink/common/features.cc b/third_party/blink/common/features.cc index c1e8b6ca..6483ebd 100644 --- a/third_party/blink/common/features.cc +++ b/third_party/blink/common/features.cc
@@ -97,10 +97,6 @@ "PreviewsResourceLoadingHintsSpecificResourceTypes", base::FEATURE_DISABLED_BY_DEFAULT}; -// Purge memory when freezing only if the renderer is backgrounded. -const base::Feature kPurgeMemoryOnlyForBackgroundedProcesses{ - "FreezePurgeMemoryBackgroundedOnly", base::FEATURE_DISABLED_BY_DEFAULT}; - // Enable Implicit Root Scroller. https://crbug.com/903260. const base::Feature kImplicitRootScroller{"ImplicitRootScroller", base::FEATURE_ENABLED_BY_DEFAULT};
diff --git a/third_party/blink/perf_tests/paint/color-changes.html b/third_party/blink/perf_tests/paint/color-changes.html index 3c10a5f4..df28de6 100644 --- a/third_party/blink/perf_tests/paint/color-changes.html +++ b/third_party/blink/perf_tests/paint/color-changes.html
@@ -3,6 +3,11 @@ <script src="../resources/runner.js"></script> <script src="resources/paint.js"></script> <style> + div { + /* To ensure consistent line wrapping behavior about empty spans across + browsers. */ + white-space: pre; + } span { padding: 1px; } @@ -14,13 +19,13 @@ // This test measures the lifecycle update performance of changing background // colors in large trees. -function buildTree(parent, depth, arity, tagNameCallback, createElementCallback) { +function buildTree(parent, depth, arity, createElementCallback) { for (var child = 0; child < arity; child++) { - var element = document.createElement(tagNameCallback(depth)); + var element = createElementCallback(depth); parent.appendChild(element); createElementCallback(element, depth); if (depth > 1) - buildTree(element, depth - 1, arity, tagNameCallback, createElementCallback); + buildTree(element, depth - 1, arity, createElementCallback); } } @@ -29,12 +34,14 @@ buildTree(document.body, 15, 2, function(depth) { // Use divs at upper levels to avoid too much layout time. - return depth > 9 ? 'div' : 'span'; - }, - function(element, depth) { + var element = document.createElement(depth > 9 ? 'div' : 'span'); element.style.backgroundColor = 'green'; if (depth == 5) - element.setAttribute('class', 'changeColor'); + element.classList.add('changeColor'); + // Insert new lines to break long lines. + if (depth == 12) + element.textContent = '\n'; + return element; } ); @@ -43,12 +50,14 @@ buildTree(document.body, 6, 7, function(depth) { // Use divs at upper levels to avoid too much layout time. - return depth > 4 ? 'div' : 'span'; - }, - function(element, depth) { + var element = document.createElement(depth > 4 ? 'div' : 'span'); element.style.backgroundColor = 'orange'; if (depth == 3) - element.setAttribute('class', 'changeColor'); + element.classList.add('changeColor'); + // Insert new lines to break long lines. + if (depth == 6) + element.textContent = '\n'; + return element; } );
diff --git a/third_party/blink/public/common/features.h b/third_party/blink/public/common/features.h index ef4b5d2..7ac37872 100644 --- a/third_party/blink/public/common/features.h +++ b/third_party/blink/public/common/features.h
@@ -36,8 +36,6 @@ BLINK_COMMON_EXPORT extern const base::Feature kPortals; BLINK_COMMON_EXPORT extern const base::Feature kPreviewsResourceLoadingHintsSpecificResourceTypes; -BLINK_COMMON_EXPORT extern const base::Feature - kPurgeMemoryOnlyForBackgroundedProcesses; BLINK_COMMON_EXPORT extern const base::Feature kRTCGetDisplayMedia; BLINK_COMMON_EXPORT extern const base::Feature kRTCUnifiedPlanByDefault; BLINK_COMMON_EXPORT extern const base::Feature kRTCOfferExtmapAllowMixed;
diff --git a/third_party/blink/public/mojom/portal/portal.mojom b/third_party/blink/public/mojom/portal/portal.mojom index 3902465..c68ba69c 100644 --- a/third_party/blink/public/mojom/portal/portal.mojom +++ b/third_party/blink/public/mojom/portal/portal.mojom
@@ -5,6 +5,7 @@ module blink.mojom; import "mojo/public/mojom/base/unguessable_token.mojom"; +import "third_party/blink/public/mojom/messaging/transferable_message.mojom"; import "url/mojom/url.mojom"; // The Portal interface is used by the renderer to interact with the Portal. @@ -13,5 +14,5 @@ Navigate(url.mojom.Url url); // When a portal is activated, it'll replace the current tab with the portal. - Activate() => (); + Activate(TransferableMessage data) => (); };
diff --git a/third_party/blink/public/web/web_local_frame.h b/third_party/blink/public/web/web_local_frame.h index fa0fca6..5b96e0e 100644 --- a/third_party/blink/public/web/web_local_frame.h +++ b/third_party/blink/public/web/web_local_frame.h
@@ -54,6 +54,7 @@ class WebURL; class WebView; enum class WebTreeScopeType; +struct TransferableMessage; struct WebAssociatedURLLoaderOptions; struct WebConsoleMessage; struct WebContentSecurityPolicyViolation; @@ -611,7 +612,7 @@ virtual void UsageCountChromeLoadTimes(const WebString& metric) = 0; // Dispatches an event when a Portal gets activated. - virtual void OnPortalActivated() = 0; + virtual void OnPortalActivated(TransferableMessage data) = 0; // Scheduling ---------------------------------------------------------------
diff --git a/third_party/blink/renderer/build/scripts/templates/instrumenting_probes_impl.cc.tmpl b/third_party/blink/renderer/build/scripts/templates/instrumenting_probes_impl.cc.tmpl index ec295709..d03b833 100644 --- a/third_party/blink/renderer/build/scripts/templates/instrumenting_probes_impl.cc.tmpl +++ b/third_party/blink/renderer/build/scripts/templates/instrumenting_probes_impl.cc.tmpl
@@ -101,7 +101,7 @@ {% for agent in probe.agents %} {% set class_name = agent | agent_name_to_class %} if (probe_sink->Has{{agent}}s()) { - for ({{class_name}}* agent : probe_sink->{{ agent | to_lower_case }}s()) + for ({{class_name}}* agent : probe_sink->{{class_name}}s()) agent->{{agent_probe_name}}({{caller()}}); } {% endfor %}
diff --git a/third_party/blink/renderer/build/scripts/templates/origin_trials.cc.tmpl b/third_party/blink/renderer/build/scripts/templates/origin_trials.cc.tmpl index 7aa623dd..d072ef4 100644 --- a/third_party/blink/renderer/build/scripts/templates/origin_trials.cc.tmpl +++ b/third_party/blink/renderer/build/scripts/templates/origin_trials.cc.tmpl
@@ -22,14 +22,6 @@ bool origin_trials::{{feature.name}}Enabled(const ExecutionContext* executionContext) { if (RuntimeEnabledFeatures::{{feature.name}}EnabledByRuntimeFlag()) return true; -{% if feature.origin_trial_os %} -#if -{%- for os in feature.origin_trial_os %} -{%- if not loop.first %} ||{% endif %} - defined(OS_{{os | upper}}) -{%- endfor %} -{% endif %} - {%- for depends_on in feature.depends_on %} if (!RuntimeEnabledFeatures::{{depends_on}}Enabled()) return false; @@ -47,11 +39,6 @@ return true; {% endfor %} return false; -{% if feature.origin_trial_os %} -#else - return false; -#endif -{% endif %} } {% endif %} @@ -71,4 +58,30 @@ return Vector<AtomicString>(); } + +// TODO(yashard): Make the function take an enum value rather than a string. +bool origin_trials::TrialEnabledForOS(const String& trial_name) { + {% for feature in features %} + {% if feature.origin_trial_feature_name %} + if (trial_name == k{{feature.name}}TrialName) + {% if feature.origin_trial_os %} +#if +{%- for os in feature.origin_trial_os %} +{%- if not loop.first %} ||{% endif %} + defined(OS_{{os | upper}}) +{%- endfor %} + + return true; +#else + return false; +#endif + {% else %} + return true; + {% endif %} + {% endif %} + {% endfor %} + + return false; +} + } // namespace blink
diff --git a/third_party/blink/renderer/build/scripts/templates/origin_trials.h.tmpl b/third_party/blink/renderer/build/scripts/templates/origin_trials.h.tmpl index 7f4ff3b..d53a7151 100644 --- a/third_party/blink/renderer/build/scripts/templates/origin_trials.h.tmpl +++ b/third_party/blink/renderer/build/scripts/templates/origin_trials.h.tmpl
@@ -38,6 +38,8 @@ CORE_EXPORT Vector<AtomicString> GetImpliedTrials(const String& trial_name); +bool TrialEnabledForOS(const String& trial_name); + } // namespace origin_trials } // namespace blink
diff --git a/third_party/blink/renderer/build/scripts/templates/probe_sink.h.tmpl b/third_party/blink/renderer/build/scripts/templates/probe_sink.h.tmpl index fc11dce..f4241e9 100644 --- a/third_party/blink/renderer/build/scripts/templates/probe_sink.h.tmpl +++ b/third_party/blink/renderer/build/scripts/templates/probe_sink.h.tmpl
@@ -43,7 +43,7 @@ {% set class_name = agent | agent_name_to_class %} {% set getter_name = agent | to_lower_case %} bool Has{{agent}}s() const { return !{{getter_name}}s_.IsEmpty(); } - const HeapListHashSet<Member<{{class_name}}>>& {{getter_name}}s() const { return {{getter_name}}s_; } + const HeapListHashSet<Member<{{class_name}}>>& {{class_name}}s() const { return {{getter_name}}s_; } void Add{{agent}}({{class_name}}* agent); void Remove{{agent}}({{class_name}}* agent);
diff --git a/third_party/blink/renderer/core/DEPS b/third_party/blink/renderer/core/DEPS index aadf5873..43985918 100644 --- a/third_party/blink/renderer/core/DEPS +++ b/third_party/blink/renderer/core/DEPS
@@ -2,6 +2,9 @@ "+base/atomic_sequence_num.h", "+base/files/file.h", "+base/mac/foundation_util.h", + "+base/mac/scoped_cftyperef.h", + "+base/mac/scoped_nsobject.h", + "+base/memory/scoped_policy.h", "+base/memory/scoped_refptr.h", "+base/metrics/field_trial_params.h", "+base/strings/stringprintf.h",
diff --git a/third_party/blink/renderer/core/core_idl_files.gni b/third_party/blink/renderer/core/core_idl_files.gni index 2f1dec7..b09fd8d 100644 --- a/third_party/blink/renderer/core/core_idl_files.gni +++ b/third_party/blink/renderer/core/core_idl_files.gni
@@ -669,6 +669,7 @@ "html/canvas/image_encode_options.idl", "html/custom/validity_state_flags.idl", "html/forms/form_data_event_init.idl", + "html/portal/portal_activate_options.idl", "html/track/track_event_init.idl", "imagebitmap/image_bitmap_options.idl", "input/input_device_capabilities_init.idl",
diff --git a/third_party/blink/renderer/core/css/css_color_value.cc b/third_party/blink/renderer/core/css/css_color_value.cc index 85d8332..621b0327 100644 --- a/third_party/blink/renderer/core/css/css_color_value.cc +++ b/third_party/blink/renderer/core/css/css_color_value.cc
@@ -36,13 +36,13 @@ else result.Append("rgb("); - result.AppendNumber(static_cast<unsigned char>(color.Red())); + result.AppendNumber(static_cast<uint16_t>(color.Red())); result.Append(", "); - result.AppendNumber(static_cast<unsigned char>(color.Green())); + result.AppendNumber(static_cast<uint16_t>(color.Green())); result.Append(", "); - result.AppendNumber(static_cast<unsigned char>(color.Blue())); + result.AppendNumber(static_cast<uint16_t>(color.Blue())); if (color_has_alpha) { result.Append(", "); // See <alphavalue> section in
diff --git a/third_party/blink/renderer/core/display_lock/display_lock_utilities.cc b/third_party/blink/renderer/core/display_lock/display_lock_utilities.cc index b64b7e8..c3efad22 100644 --- a/third_party/blink/renderer/core/display_lock/display_lock_utilities.cc +++ b/third_party/blink/renderer/core/display_lock/display_lock_utilities.cc
@@ -60,4 +60,24 @@ return elements_to_activate; } +DisplayLockUtilities::ScopedChainForcedUpdate::ScopedChainForcedUpdate( + const Node* node) { + if (!RuntimeEnabledFeatures::DisplayLockingEnabled() || + node->GetDocument().LockedDisplayLockCount() == 0) { + return; + } + const_cast<Node*>(node)->UpdateDistributionForFlatTreeTraversal(); + // TODO(vmpstr): This is somewhat inefficient, since we would pay the cost + // of traversing the ancestor chain even for nodes that are not in the + // locked subtree. We need to figure out if there is a supplementary + // structure that we can use to quickly identify nodes that are in the + // locked subtree. + for (Node& ancestor : FlatTreeTraversal::InclusiveAncestorsOf(*node)) { + if (!ancestor.IsElementNode()) + continue; + if (auto* context = ToElement(ancestor).GetDisplayLockContext()) + scoped_update_forced_list_.push_back(context->GetScopedForcedUpdate()); + } +} + } // namespace blink
diff --git a/third_party/blink/renderer/core/display_lock/display_lock_utilities.h b/third_party/blink/renderer/core/display_lock/display_lock_utilities.h index 0b202d6..ffef726 100644 --- a/third_party/blink/renderer/core/display_lock/display_lock_utilities.h +++ b/third_party/blink/renderer/core/display_lock/display_lock_utilities.h
@@ -6,6 +6,7 @@ #define THIRD_PARTY_BLINK_RENDERER_CORE_DISPLAY_LOCK_DISPLAY_LOCK_UTILITIES_H_ #include "third_party/blink/renderer/core/core_export.h" +#include "third_party/blink/renderer/core/display_lock/display_lock_context.h" #include "third_party/blink/renderer/core/editing/ephemeral_range.h" #include "third_party/blink/renderer/platform/wtf/allocator.h" @@ -16,6 +17,19 @@ STATIC_ONLY(DisplayLockUtilities); public: + // This class forces updates on display locks from the given node up the + // ancestor chain until the root. + class ScopedChainForcedUpdate { + STACK_ALLOCATED(); + DISALLOW_COPY_AND_ASSIGN(ScopedChainForcedUpdate); + + public: + explicit ScopedChainForcedUpdate(const Node* node); + ~ScopedChainForcedUpdate() = default; + + private: + Vector<DisplayLockContext::ScopedForcedUpdate> scoped_update_forced_list_; + }; // Activates all the nodes within a find-in-page match |range|. // Returns true if at least one node gets activated. // See: http://bit.ly/2RXULVi, "beforeactivate Event" part.
diff --git a/third_party/blink/renderer/core/dom/document.cc b/third_party/blink/renderer/core/dom/document.cc index d52c978a..a0378d2 100644 --- a/third_party/blink/renderer/core/dom/document.cc +++ b/third_party/blink/renderer/core/dom/document.cc
@@ -88,6 +88,7 @@ #include "third_party/blink/renderer/core/css/style_engine.h" #include "third_party/blink/renderer/core/css/style_sheet_contents.h" #include "third_party/blink/renderer/core/css/style_sheet_list.h" +#include "third_party/blink/renderer/core/display_lock/display_lock_utilities.h" #include "third_party/blink/renderer/core/dom/attr.h" #include "third_party/blink/renderer/core/dom/cdata_section.h" #include "third_party/blink/renderer/core/dom/comment.h" @@ -2439,19 +2440,7 @@ if (!NeedsLayoutTreeUpdateForNode(*node)) return; - // Force unlock any element from the given node up the ancestor chain. - Vector<DisplayLockContext::ScopedForcedUpdate> scoped_update_forced_list; - if (RuntimeEnabledFeatures::DisplayLockingEnabled() && - LockedDisplayLockCount() > 0) { - const_cast<Node*>(node)->UpdateDistributionForFlatTreeTraversal(); - for (Node& ancestor : FlatTreeTraversal::InclusiveAncestorsOf(*node)) { - if (!ancestor.IsElementNode()) - continue; - if (auto* context = ToElement(ancestor).GetDisplayLockContext()) - scoped_update_forced_list.push_back(context->GetScopedForcedUpdate()); - } - } - + DisplayLockUtilities::ScopedChainForcedUpdate scoped_update_forced(node); UpdateStyleAndLayoutTree(); } @@ -2460,19 +2449,7 @@ if (!node->InActiveDocument()) return; - // Force unlock any element from the given node up the ancestor chain. - Vector<DisplayLockContext::ScopedForcedUpdate> scoped_update_forced_list; - if (RuntimeEnabledFeatures::DisplayLockingEnabled() && - LockedDisplayLockCount() > 0) { - const_cast<Node*>(node)->UpdateDistributionForFlatTreeTraversal(); - for (Node& ancestor : FlatTreeTraversal::InclusiveAncestorsOf(*node)) { - if (!ancestor.IsElementNode()) - continue; - if (auto* context = ToElement(ancestor).GetDisplayLockContext()) - scoped_update_forced_list.push_back(context->GetScopedForcedUpdate()); - } - } - + DisplayLockUtilities::ScopedChainForcedUpdate scoped_update_forced(node); UpdateStyleAndLayout(); } @@ -2561,26 +2538,7 @@ if (!node->InActiveDocument()) return; - // If we're forcing location information to be updated, we need to ensure that - // all locked elements in the ancestor chain allow us to do the updates. When - // the scoped objects are destroyed, the locks are restored. Note that the - // frame rect of the locked elements themselves will still be the same as at - // the time the lock was acquired. - // TODO(vmpstr): This is somewhat inefficient, since we would pay the cost of - // traversing the ancestor chain even for nodes that are not in the locked - // subtree. We need to figure out if there is a supplementary structure that - // we can use to quickly identify nodes that are in the locked subtree. - Vector<DisplayLockContext::ScopedForcedUpdate> scoped_update_forced_list; - if (RuntimeEnabledFeatures::DisplayLockingEnabled() && - LockedDisplayLockCount() > 0) { - const_cast<Node*>(node)->UpdateDistributionForFlatTreeTraversal(); - for (Node& ancestor : FlatTreeTraversal::InclusiveAncestorsOf(*node)) { - if (!ancestor.IsElementNode()) - continue; - if (auto* context = ToElement(ancestor).GetDisplayLockContext()) - scoped_update_forced_list.push_back(context->GetScopedForcedUpdate()); - } - } + DisplayLockUtilities::ScopedChainForcedUpdate scoped_update_forced(node); // For all nodes we must have up-to-date style and have performed layout to do // any location-based calculation.
diff --git a/third_party/blink/renderer/core/editing/markers/document_marker_controller.cc b/third_party/blink/renderer/core/editing/markers/document_marker_controller.cc index 43239483..17edfdb 100644 --- a/third_party/blink/renderer/core/editing/markers/document_marker_controller.cc +++ b/third_party/blink/renderer/core/editing/markers/document_marker_controller.cc
@@ -972,7 +972,7 @@ list->GetMarkers(); for (const DocumentMarker* marker : markers_in_list) { builder.Append(" "); - builder.AppendNumber(marker->GetType()); + builder.AppendNumber(static_cast<uint32_t>(marker->GetType())); builder.Append(":["); builder.AppendNumber(marker->StartOffset()); builder.Append(":");
diff --git a/third_party/blink/renderer/core/editing/serializers/markup_accumulator.cc b/third_party/blink/renderer/core/editing/serializers/markup_accumulator.cc index a4b166c..09225c2 100644 --- a/third_party/blink/renderer/core/editing/serializers/markup_accumulator.cc +++ b/third_party/blink/renderer/core/editing/serializers/markup_accumulator.cc
@@ -203,8 +203,12 @@ for (const auto& attribute : element.Attributes()) { if (data.ignore_namespace_definition_attribute_ && attribute.NamespaceURI() == xmlns_names::kNamespaceURI && - attribute.Prefix().IsEmpty()) - continue; + attribute.Prefix().IsEmpty()) { + // Drop xmlns= only if it's inconsistent with element's namespace. + // https://github.com/w3c/DOM-Parsing/issues/47 + if (!EqualIgnoringNullity(attribute.Value(), element.namespaceURI())) + continue; + } if (!ShouldIgnoreAttribute(element, attribute)) AppendAttribute(element, attribute); } @@ -315,7 +319,8 @@ // 12.6. Otherwise, if local default namespace is null, or local default // namespace is not null and its value is not equal to ns, then: - if (local_default_namespace.IsNull() || local_default_namespace != ns) { + if (local_default_namespace.IsNull() || + !EqualIgnoringNullity(local_default_namespace, ns)) { // 12.6.1. Set the ignore namespace definition attribute flag to true. data.ignore_namespace_definition_attribute_ = true; // 12.6.3. Let the value of inherited ns be ns. @@ -331,7 +336,7 @@ // 12.7. Otherwise, the node has a local default namespace that matches // ns. Append to qualified name the value of node's localName, let the value // of inherited ns be ns, and append the value of qualified name to markup. - DCHECK_EQ(local_default_namespace, ns); + DCHECK(EqualIgnoringNullity(local_default_namespace, ns)); namespace_context.SetContextNamespace(ns); formatter_.AppendStartTagOpen(markup_, element); return data;
diff --git a/third_party/blink/renderer/core/events/portal_activate_event.cc b/third_party/blink/renderer/core/events/portal_activate_event.cc index 5d7ddae0..ed6d7fa 100644 --- a/third_party/blink/renderer/core/events/portal_activate_event.cc +++ b/third_party/blink/renderer/core/events/portal_activate_event.cc
@@ -4,25 +4,59 @@ #include "third_party/blink/renderer/core/events/portal_activate_event.h" +#include <utility> +#include "third_party/blink/renderer/bindings/core/v8/script_value.h" #include "third_party/blink/renderer/core/event_type_names.h" +#include "third_party/blink/renderer/core/messaging/message_port.h" +#include "third_party/blink/renderer/platform/bindings/script_state.h" #include "third_party/blink/renderer/platform/wtf/time.h" namespace blink { -PortalActivateEvent* PortalActivateEvent::Create() { - return MakeGarbageCollected<PortalActivateEvent>(); +PortalActivateEvent* PortalActivateEvent::Create( + scoped_refptr<SerializedScriptValue> data, + MessagePortArray* ports) { + return MakeGarbageCollected<PortalActivateEvent>( + SerializedScriptValue::Unpack(std::move(data)), ports); } -PortalActivateEvent::PortalActivateEvent() +PortalActivateEvent::PortalActivateEvent(UnpackedSerializedScriptValue* data, + MessagePortArray* ports) : Event(event_type_names::kPortalactivate, Bubbles::kNo, Cancelable::kNo, - CurrentTimeTicks()) {} + CurrentTimeTicks()), + data_(data), + ports_(ports) {} PortalActivateEvent::~PortalActivateEvent() = default; +ScriptValue PortalActivateEvent::data(ScriptState* script_state) { + v8::Isolate* isolate = script_state->GetIsolate(); + v8::HandleScope handle_scope(isolate); + if (!data_) + return ScriptValue(script_state, v8::Null(isolate)); + + auto result = + v8_data_.insert(script_state, TraceWrapperV8Reference<v8::Value>()); + TraceWrapperV8Reference<v8::Value>& relevant_data = + result.stored_value->value; + + if (!result.is_new_entry) + return ScriptValue(script_state, relevant_data.NewLocal(isolate)); + + SerializedScriptValue::DeserializeOptions options; + options.message_ports = ports_.Get(); + v8::Local<v8::Value> value = data_->Deserialize(isolate, options); + relevant_data.Set(isolate, value); + return ScriptValue(script_state, value); +} + void PortalActivateEvent::Trace(blink::Visitor* visitor) { Event::Trace(visitor); + visitor->Trace(data_); + visitor->Trace(v8_data_); + visitor->Trace(ports_); } const AtomicString& PortalActivateEvent::InterfaceName() const {
diff --git a/third_party/blink/renderer/core/events/portal_activate_event.h b/third_party/blink/renderer/core/events/portal_activate_event.h index 8936f89d..a22eca8 100644 --- a/third_party/blink/renderer/core/events/portal_activate_event.h +++ b/third_party/blink/renderer/core/events/portal_activate_event.h
@@ -5,29 +5,43 @@ #ifndef THIRD_PARTY_BLINK_RENDERER_CORE_EVENTS_PORTAL_ACTIVATE_EVENT_H_ #define THIRD_PARTY_BLINK_RENDERER_CORE_EVENTS_PORTAL_ACTIVATE_EVENT_H_ -#include "third_party/blink/renderer/platform/heap/heap.h" - +#include "third_party/blink/renderer/bindings/core/v8/serialization/serialized_script_value.h" +#include "third_party/blink/renderer/bindings/core/v8/serialization/unpacked_serialized_script_value.h" #include "third_party/blink/renderer/core/core_export.h" #include "third_party/blink/renderer/core/dom/events/event.h" #include "third_party/blink/renderer/core/dom/events/event_target.h" +#include "third_party/blink/renderer/platform/bindings/trace_wrapper_v8_reference.h" +#include "third_party/blink/renderer/platform/heap/heap.h" +#include "third_party/blink/renderer/platform/heap/heap_allocator.h" +#include "third_party/blink/renderer/platform/heap/member.h" namespace blink { +class ScriptState; +class ScriptValue; + class CORE_EXPORT PortalActivateEvent : public Event { DEFINE_WRAPPERTYPEINFO(); public: - static PortalActivateEvent* Create(); + static PortalActivateEvent* Create(scoped_refptr<SerializedScriptValue> data, + MessagePortArray* ports); - PortalActivateEvent(); + PortalActivateEvent(UnpackedSerializedScriptValue* data, MessagePortArray*); ~PortalActivateEvent() override; + ScriptValue data(ScriptState*); + void Trace(blink::Visitor*) override; // Event overrides const AtomicString& InterfaceName() const override; private: + Member<UnpackedSerializedScriptValue> data_; + Member<MessagePortArray> ports_; + HeapHashMap<WeakMember<ScriptState>, TraceWrapperV8Reference<v8::Value>> + v8_data_; }; } // namespace blink
diff --git a/third_party/blink/renderer/core/events/portal_activate_event.idl b/third_party/blink/renderer/core/events/portal_activate_event.idl index 74e22f9..0cd6c51a 100644 --- a/third_party/blink/renderer/core/events/portal_activate_event.idl +++ b/third_party/blink/renderer/core/events/portal_activate_event.idl
@@ -6,4 +6,5 @@ [Exposed=Window, RuntimeEnabled=Portals] interface PortalActivateEvent : Event { + [CallWith=ScriptState] readonly attribute any data; };
diff --git a/third_party/blink/renderer/core/frame/web_local_frame_impl.cc b/third_party/blink/renderer/core/frame/web_local_frame_impl.cc index 66ef809..5814a03 100644 --- a/third_party/blink/renderer/core/frame/web_local_frame_impl.cc +++ b/third_party/blink/renderer/core/frame/web_local_frame_impl.cc
@@ -214,6 +214,7 @@ #include "third_party/blink/renderer/core/input/context_menu_allowed_scope.h" #include "third_party/blink/renderer/core/input/event_handler.h" #include "third_party/blink/renderer/core/inspector/console_message.h" +#include "third_party/blink/renderer/core/inspector/main_thread_debugger.h" #include "third_party/blink/renderer/core/layout/hit_test_result.h" #include "third_party/blink/renderer/core/layout/layout_embedded_content.h" #include "third_party/blink/renderer/core/layout/layout_object.h" @@ -2497,10 +2498,27 @@ } } -void WebLocalFrameImpl::OnPortalActivated() { +void WebLocalFrameImpl::OnPortalActivated(TransferableMessage data) { GetFrame()->GetPage()->SetInsidePortal(false); - PortalActivateEvent* event = PortalActivateEvent::Create(); + + LocalDOMWindow* window = GetFrame()->DomWindow(); + + auto blink_data = ToBlinkTransferableMessage(std::move(data)); + DCHECK(!blink_data.locked_agent_cluster_id) + << "portal activation is always cross-agent-cluster and should be " + "diagnosed early"; + MessagePortArray* ports = MessagePort::EntanglePorts( + *window->document(), std::move(blink_data.ports)); + + PortalActivateEvent* event = + PortalActivateEvent::Create(std::move(blink_data.message), ports); + + ThreadDebugger* debugger = MainThreadDebugger::Instance(); + if (debugger) + debugger->ExternalAsyncTaskStarted(blink_data.sender_stack_trace_id); GetFrame()->DomWindow()->DispatchEvent(*event); + if (debugger) + debugger->ExternalAsyncTaskFinished(blink_data.sender_stack_trace_id); } void WebLocalFrameImpl::SetTextCheckClient(
diff --git a/third_party/blink/renderer/core/frame/web_local_frame_impl.h b/third_party/blink/renderer/core/frame/web_local_frame_impl.h index 1d36580..5c20f2ba 100644 --- a/third_party/blink/renderer/core/frame/web_local_frame_impl.h +++ b/third_party/blink/renderer/core/frame/web_local_frame_impl.h
@@ -301,7 +301,7 @@ void AdvanceFocusInForm(WebFocusType) override; void PerformMediaPlayerAction(const WebPoint&, const WebMediaPlayerAction&) override; - void OnPortalActivated() override; + void OnPortalActivated(TransferableMessage data) override; // WebNavigationControl methods: bool DispatchBeforeUnloadEvent(bool) override;
diff --git a/third_party/blink/renderer/core/html/forms/internal_popup_menu.cc b/third_party/blink/renderer/core/html/forms/internal_popup_menu.cc index a89f2e91..6485e66 100644 --- a/third_party/blink/renderer/core/html/forms/internal_popup_menu.cc +++ b/third_party/blink/renderer/core/html/forms/internal_popup_menu.cc
@@ -343,7 +343,7 @@ } // Our UA stylesheet has font-weight:normal for OPTION. if (NormalWeightValue() != font_description.Weight()) { - AddProperty("fontWeight", String::Number(font_description.Weight()), data); + AddProperty("fontWeight", font_description.Weight().ToString(), data); } if (base_font.Family() != font_description.Family()) { PagePopupClient::AddString("fontFamily: [\n", data);
diff --git a/third_party/blink/renderer/core/html/imports/html_import_loader.cc b/third_party/blink/renderer/core/html/imports/html_import_loader.cc index 8fc9dc8..03a6f8d05 100644 --- a/third_party/blink/renderer/core/html/imports/html_import_loader.cc +++ b/third_party/blink/renderer/core/html/imports/html_import_loader.cc
@@ -73,7 +73,7 @@ SetState(StartWritingAndParsing(response)); } -void HTMLImportLoader::DataReceived(Resource*, +void HTMLImportLoader::DataReceived(Resource* resource, const char* data, size_t length) { document_->Parser()->AppendBytes(data, length);
diff --git a/third_party/blink/renderer/core/html/media/media_document.cc b/third_party/blink/renderer/core/html/media/media_document.cc index 0c2805f..48374e46 100644 --- a/third_party/blink/renderer/core/html/media/media_document.cc +++ b/third_party/blink/renderer/core/html/media/media_document.cc
@@ -69,6 +69,10 @@ }; void MediaDocumentParser::CreateDocumentStructure() { + // TODO(dgozman): DocumentLoader might call Finish on a stopped parser. + // See also comments for DocumentParser::{Detach,StopParsing}. + if (IsStopped()) + return; if (did_build_document_structure_) return; did_build_document_structure_ = true;
diff --git a/third_party/blink/renderer/core/html/plugin_document.cc b/third_party/blink/renderer/core/html/plugin_document.cc index 5a71676..53885c19 100644 --- a/third_party/blink/renderer/core/html/plugin_document.cc +++ b/third_party/blink/renderer/core/html/plugin_document.cc
@@ -111,6 +111,10 @@ }; void PluginDocumentParser::CreateDocumentStructure() { + // TODO(dgozman): DocumentLoader might call Finish on a stopped parser. + // See also comments for DocumentParser::{Detach,StopParsing}. + if (IsStopped()) + return; if (embed_element_) return;
diff --git a/third_party/blink/renderer/core/html/portal/html_portal_element.cc b/third_party/blink/renderer/core/html/portal/html_portal_element.cc index e43ef14..a82ef91 100644 --- a/third_party/blink/renderer/core/html/portal/html_portal_element.cc +++ b/third_party/blink/renderer/core/html/portal/html_portal_element.cc
@@ -4,21 +4,27 @@ #include "third_party/blink/renderer/core/html/portal/html_portal_element.h" +#include <utility> #include "services/service_manager/public/cpp/interface_provider.h" #include "third_party/blink/renderer/bindings/core/v8/script_promise.h" #include "third_party/blink/renderer/bindings/core/v8/script_promise_resolver.h" +#include "third_party/blink/renderer/bindings/core/v8/serialization/serialized_script_value.h" #include "third_party/blink/renderer/core/dom/document.h" #include "third_party/blink/renderer/core/dom/dom_exception.h" #include "third_party/blink/renderer/core/dom/node.h" +#include "third_party/blink/renderer/core/execution_context/execution_context.h" #include "third_party/blink/renderer/core/frame/local_frame.h" #include "third_party/blink/renderer/core/frame/local_frame_client.h" #include "third_party/blink/renderer/core/frame/remote_frame.h" #include "third_party/blink/renderer/core/html/html_unknown_element.h" #include "third_party/blink/renderer/core/html/parser/html_parser_idioms.h" #include "third_party/blink/renderer/core/html/portal/document_portals.h" +#include "third_party/blink/renderer/core/html/portal/portal_activate_options.h" #include "third_party/blink/renderer/core/html_names.h" #include "third_party/blink/renderer/core/inspector/console_message.h" +#include "third_party/blink/renderer/core/inspector/thread_debugger.h" #include "third_party/blink/renderer/core/layout/layout_iframe.h" +#include "third_party/blink/renderer/core/messaging/message_port.h" #include "third_party/blink/renderer/platform/bindings/script_state.h" #include "third_party/blink/renderer/platform/heap/handle.h" #include "third_party/blink/renderer/platform/runtime_enabled_features.h" @@ -49,26 +55,95 @@ } } -ScriptPromise HTMLPortalElement::activate(ScriptState* script_state) { +namespace { + +BlinkTransferableMessage ActivateDataAsMessage( + ScriptState* script_state, + PortalActivateOptions* options, + ExceptionState& exception_state) { + v8::Isolate* isolate = script_state->GetIsolate(); + Transferables transferables; + if (options->hasTransfer()) { + if (!SerializedScriptValue::ExtractTransferables( + script_state->GetIsolate(), options->transfer(), transferables, + exception_state)) + return {}; + } + + SerializedScriptValue::SerializeOptions serialize_options; + serialize_options.transferables = &transferables; + v8::Local<v8::Value> data = options->hasData() + ? options->data().V8Value() + : v8::Null(isolate).As<v8::Value>(); + + BlinkTransferableMessage msg; + msg.message = SerializedScriptValue::Serialize( + isolate, data, serialize_options, exception_state); + if (!msg.message) + return {}; + + msg.message->UnregisterMemoryAllocatedWithCurrentScriptContext(); + + auto* execution_context = ExecutionContext::From(script_state); + msg.ports = MessagePort::DisentanglePorts( + execution_context, transferables.message_ports, exception_state); + if (exception_state.HadException()) + return {}; + + // msg.user_activation is left out; we will probably handle user activation + // explicitly for activate data. + // TODO(crbug.com/936184): Answer this for good. + + if (ThreadDebugger* debugger = ThreadDebugger::From(isolate)) + msg.sender_stack_trace_id = debugger->StoreCurrentStackTrace("activate"); + + if (msg.message->IsLockedToAgentCluster()) { + exception_state.ThrowDOMException( + DOMExceptionCode::kDataCloneError, + "Cannot send agent cluster-locked data (e.g. SharedArrayBuffer) " + "through portal activation."); + return {}; + } + + return msg; +} + +} // namespace + +ScriptPromise HTMLPortalElement::activate(ScriptState* script_state, + PortalActivateOptions* options) { ScriptPromiseResolver* resolver = ScriptPromiseResolver::Create(script_state); ScriptPromise promise = resolver->Promise(); - if (portal_ptr_) { - // The HTMLPortalElement is bound as a persistent so that it won't get - // garbage collected while there is a pending callback. This is necessary - // because the HTMLPortalElement owns the mojo interface, so if it were - // garbage collected the callback would never be called and the promise - // would never be resolved. - portal_ptr_->Activate( - WTF::Bind([](HTMLPortalElement* portal, - ScriptPromiseResolver* resolver) { resolver->Resolve(); }, - WrapPersistent(this), WrapPersistent(resolver))); - } else { - resolver->Reject(DOMException::Create( + ExceptionState exception_state(script_state->GetIsolate(), + ExceptionState::kExecutionContext, + "HTMLPortalElement", "activate"); + + if (!portal_ptr_) { + exception_state.ThrowDOMException( DOMExceptionCode::kInvalidStateError, - "The HTMLPortalElement is not associated with a portal context.")); + "The HTMLPortalElement is not associated with a portal context."); + resolver->Reject(exception_state); + return promise; } + BlinkTransferableMessage data = + ActivateDataAsMessage(script_state, options, exception_state); + if (exception_state.HadException()) { + resolver->Reject(exception_state); + return promise; + } + + // The HTMLPortalElement is bound as a persistent so that it won't get + // garbage collected while there is a pending callback. This is necessary + // because the HTMLPortalElement owns the mojo interface, so if it were + // garbage collected the callback would never be called and the promise + // would never be resolved. + portal_ptr_->Activate( + std::move(data), + WTF::Bind([](HTMLPortalElement* portal, + ScriptPromiseResolver* resolver) { resolver->Resolve(); }, + WrapPersistent(this), WrapPersistent(resolver))); return promise; }
diff --git a/third_party/blink/renderer/core/html/portal/html_portal_element.h b/third_party/blink/renderer/core/html/portal/html_portal_element.h index c08b655a..edc3b59 100644 --- a/third_party/blink/renderer/core/html/portal/html_portal_element.h +++ b/third_party/blink/renderer/core/html/portal/html_portal_element.h
@@ -15,6 +15,7 @@ namespace blink { class Document; +class PortalActivateOptions; class RemoteFrame; class ScriptState; @@ -36,7 +37,7 @@ void Trace(Visitor* visitor) override; // idl implementation. - ScriptPromise activate(ScriptState*); + ScriptPromise activate(ScriptState*, PortalActivateOptions*); const base::UnguessableToken& GetToken() const { return portal_token_; }
diff --git a/third_party/blink/renderer/core/html/portal/html_portal_element.idl b/third_party/blink/renderer/core/html/portal/html_portal_element.idl index ba90bbd..e3229e7a 100644 --- a/third_party/blink/renderer/core/html/portal/html_portal_element.idl +++ b/third_party/blink/renderer/core/html/portal/html_portal_element.idl
@@ -7,5 +7,5 @@ [HTMLConstructor, RuntimeEnabled=Portals] interface HTMLPortalElement : HTMLElement { [CEReactions, Reflect, URL, RaisesException=Setter] attribute URLString src; - [CallWith=ScriptState] Promise<void> activate(); + [CallWith=ScriptState] Promise<void> activate(optional PortalActivateOptions options); };
diff --git a/third_party/blink/renderer/core/html/portal/portal_activate_options.idl b/third_party/blink/renderer/core/html/portal/portal_activate_options.idl new file mode 100644 index 0000000..c671168 --- /dev/null +++ b/third_party/blink/renderer/core/html/portal/portal_activate_options.idl
@@ -0,0 +1,11 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +// https://wicg.github.io/portals/#dictdef-portalactivateoptions + +dictionary PortalActivateOptions { + // Exposed on PortalActivateEvent.data. + any data = null; + sequence<object> transfer = []; +};
diff --git a/third_party/blink/renderer/core/imagebitmap/image_bitmap_factories.cc b/third_party/blink/renderer/core/imagebitmap/image_bitmap_factories.cc index b3fa07e15..53bcbfda 100644 --- a/third_party/blink/renderer/core/imagebitmap/image_bitmap_factories.cc +++ b/third_party/blink/renderer/core/imagebitmap/image_bitmap_factories.cc
@@ -337,11 +337,11 @@ if (color_space_conversion_option == "none") ignore_color_space = true; const bool data_complete = true; - std::unique_ptr<ImageDecoder> decoder(ImageDecoder::Create( + std::unique_ptr<ImageDecoder> decoder = ImageDecoder::Create( SegmentReader::CreateFromSkData(SkData::MakeWithoutCopy( array_buffer->Data(), array_buffer->ByteLength())), data_complete, alpha_op, ImageDecoder::kDefaultBitDepth, - ignore_color_space ? ColorBehavior::Ignore() : ColorBehavior::Tag())); + ignore_color_space ? ColorBehavior::Ignore() : ColorBehavior::Tag()); sk_sp<SkImage> frame; if (decoder) { frame = ImageBitmap::GetSkImageFromDecoder(std::move(decoder));
diff --git a/third_party/blink/renderer/core/input/event_handler.cc b/third_party/blink/renderer/core/input/event_handler.cc index 3b49c19..6c8be269 100644 --- a/third_party/blink/renderer/core/input/event_handler.cc +++ b/third_party/blink/renderer/core/input/event_handler.cc
@@ -499,6 +499,7 @@ if (!visible_rect.Contains(cursor_rect)) { Deprecation::CountDeprecation( frame_, WebFeature::kCustomCursorIntersectsViewport); + continue; } }
diff --git a/third_party/blink/renderer/core/input/event_handler_test.cc b/third_party/blink/renderer/core/input/event_handler_test.cc index 1651195..da8e7da8e 100644 --- a/third_party/blink/renderer/core/input/event_handler_test.cc +++ b/third_party/blink/renderer/core/input/event_handler_test.cc
@@ -5,6 +5,7 @@ #include "third_party/blink/renderer/core/input/event_handler.h" #include <memory> + #include "testing/gtest/include/gtest/gtest.h" #include "third_party/blink/renderer/core/dom/document.h" #include "third_party/blink/renderer/core/dom/range.h" @@ -1337,4 +1338,119 @@ EXPECT_EQ("hover over me", element3.InnerHTML().Utf8()); } +TEST_F(EventHandlerSimTest, LargeCustomCursorIntersectsViewport) { + WebView().MainFrameWidget()->Resize(WebSize(800, 600)); + SimRequest request("https://example.com/test.html", "text/html"); + SimSubresourceRequest cursor_request("https://example.com/100x100.png", + "image/png"); + LoadURL("https://example.com/test.html"); + request.Complete( + R"HTML( + <!DOCTYPE html> + <style> + div { + width: 300px; + height: 100px; + cursor: url('100x100.png') 100 100, auto; + } + </style> + <div>foo</div> + )HTML"); + + scoped_refptr<SharedBuffer> img = + test::ReadFromFile(test::CoreTestDataPath("notifications/100x100.png")); + cursor_request.Complete(img->CopyAs<Vector<char>>()); + + Compositor().BeginFrame(); + + // Move the cursor so no part of it intersects the viewport. + { + WebMouseEvent mouse_move_event( + WebMouseEvent::kMouseMove, WebFloatPoint(101, 101), + WebFloatPoint(101, 101), WebPointerProperties::Button::kNoButton, 0, 0, + WebInputEvent::GetStaticTimeStampForTests()); + mouse_move_event.SetFrameScale(1); + GetDocument().GetFrame()->GetEventHandler().HandleMouseMoveEvent( + mouse_move_event, Vector<WebMouseEvent>(), Vector<WebMouseEvent>()); + + const Cursor& cursor = + GetDocument().GetFrame()->GetChromeClient().LastSetCursorForTesting(); + EXPECT_EQ(Cursor::Type::kCustom, cursor.GetType()); + } + + // Now, move the cursor so that it intersects the visual viewport. The cursor + // should be removed. + { + WebMouseEvent mouse_move_event( + WebMouseEvent::kMouseMove, WebFloatPoint(99, 99), WebFloatPoint(99, 99), + WebPointerProperties::Button::kNoButton, 0, 0, + WebInputEvent::GetStaticTimeStampForTests()); + mouse_move_event.SetFrameScale(1); + GetDocument().GetFrame()->GetEventHandler().HandleMouseMoveEvent( + mouse_move_event, Vector<WebMouseEvent>(), Vector<WebMouseEvent>()); + + const Cursor& cursor = + GetDocument().GetFrame()->GetChromeClient().LastSetCursorForTesting(); + EXPECT_EQ(Cursor::Type::kPointer, cursor.GetType()); + } +} + +TEST_F(EventHandlerSimTest, SmallCustomCursorIntersectsViewport) { + WebView().MainFrameWidget()->Resize(WebSize(800, 600)); + SimRequest request("https://example.com/test.html", "text/html"); + SimSubresourceRequest cursor_request("https://example.com/48x48.png", + "image/png"); + LoadURL("https://example.com/test.html"); + request.Complete( + R"HTML( + <!DOCTYPE html> + <style> + div { + width: 300px; + height: 100px; + cursor: -webkit-image-set(url('48x48.png') 2x) 24 24, auto; + } + </style> + <div>foo</div> + )HTML"); + + scoped_refptr<SharedBuffer> img = + test::ReadFromFile(test::CoreTestDataPath("notifications/48x48.png")); + cursor_request.Complete(img->CopyAs<Vector<char>>()); + + Compositor().BeginFrame(); + + // Move the cursor so no part of it intersects the viewport. + { + WebMouseEvent mouse_move_event( + WebMouseEvent::kMouseMove, WebFloatPoint(25, 25), WebFloatPoint(25, 25), + WebPointerProperties::Button::kNoButton, 0, 0, + WebInputEvent::GetStaticTimeStampForTests()); + mouse_move_event.SetFrameScale(1); + GetDocument().GetFrame()->GetEventHandler().HandleMouseMoveEvent( + mouse_move_event, Vector<WebMouseEvent>(), Vector<WebMouseEvent>()); + + const Cursor& cursor = + GetDocument().GetFrame()->GetChromeClient().LastSetCursorForTesting(); + EXPECT_EQ(Cursor::Type::kCustom, cursor.GetType()); + } + + // Now, move the cursor so that it intersects the visual viewport. The cursor + // should not be removed because it is below + // kMaximumCursorSizeWithoutFallback. + { + WebMouseEvent mouse_move_event( + WebMouseEvent::kMouseMove, WebFloatPoint(23, 23), WebFloatPoint(23, 23), + WebPointerProperties::Button::kNoButton, 0, 0, + WebInputEvent::GetStaticTimeStampForTests()); + mouse_move_event.SetFrameScale(1); + GetDocument().GetFrame()->GetEventHandler().HandleMouseMoveEvent( + mouse_move_event, Vector<WebMouseEvent>(), Vector<WebMouseEvent>()); + + const Cursor& cursor = + GetDocument().GetFrame()->GetChromeClient().LastSetCursorForTesting(); + EXPECT_EQ(Cursor::Type::kCustom, cursor.GetType()); + } +} + } // namespace blink
diff --git a/third_party/blink/renderer/core/inspector/inspector_emulation_agent.cc b/third_party/blink/renderer/core/inspector/inspector_emulation_agent.cc index 22622ecf..e4f40c43 100644 --- a/third_party/blink/renderer/core/inspector/inspector_emulation_agent.cc +++ b/third_party/blink/renderer/core/inspector/inspector_emulation_agent.cc
@@ -201,9 +201,9 @@ return response; int max_points = max_touch_points.fromMaybe(1); if (max_points < 1 || max_points > WebTouchEvent::kTouchesLengthCap) { - return Response::InvalidParams( - "Touch points must be between 1 and " + - String::Number(WebTouchEvent::kTouchesLengthCap)); + return Response::InvalidParams("Touch points must be between 1 and " + + String::Number(static_cast<uint16_t>( + WebTouchEvent::kTouchesLengthCap))); } touch_event_emulation_enabled_.Set(enabled); max_touch_points_.Set(max_points);
diff --git a/third_party/blink/renderer/core/loader/document_loader.cc b/third_party/blink/renderer/core/loader/document_loader.cc index fb76cb1..b3d05b1 100644 --- a/third_party/blink/renderer/core/loader/document_loader.cc +++ b/third_party/blink/renderer/core/loader/document_loader.cc
@@ -671,6 +671,11 @@ } } + // We should not call FinishedLoading before committing navigation, + // except for the mhtml case, which is forcefully committed above. + // In any way, by this point we should have already committed. + DCHECK_GE(state_, kCommitted); + TimeTicks response_end_time = finish_time; if (response_end_time.is_null()) response_end_time = time_of_last_data_received_; @@ -678,12 +683,6 @@ response_end_time = CurrentTimeTicks(); GetTiming().SetResponseEnd(response_end_time); - // If this is an empty document, it might not have actually been - // committed yet. Force a commit so that the Document actually gets created. - if (state_ == kProvisional) - CommitNavigation(response_.MimeType()); - DCHECK_GE(state_, kCommitted); - if (!frame_) return; @@ -924,20 +923,16 @@ response_.HttpHeaderField(http_names::kRefresh), Document::kHttpRefreshFromHeader); ReportPreviewsIntervention(); - - // If we did commit MediaDocument, we should stop here. - if (frame_ && frame_->GetDocument()->IsMediaDocument()) { - parser_->Finish(); - StopLoading(); - } } void DocumentLoader::CommitData(const char* bytes, size_t length) { - CommitNavigation(response_.MimeType()); DCHECK_GE(state_, kCommitted); // This can happen if document.close() is called by an event handler while // there's still pending incoming data. + // TODO(dgozman): we should stop body loader when stopping the parser to + // avoid unnecessary work. This may happen, for example, when we abort current + // committed document which is still loading when initiating a new navigation. if (!frame_ || !frame_->GetDocument()->Parsing()) return; @@ -1066,6 +1061,11 @@ response_ = ResourceResponse(url_); response_.SetMimeType("text/html"); response_.SetTextEncodingName("utf-8"); + CommitNavigation(response_.MimeType()); + // Committing can run unload handlers, which can detach this frame or + // stop this loader. + if (!frame_) + return; FinishedLoading(CurrentTimeTicks()); } @@ -1205,12 +1205,30 @@ // If we did not finish synchronously, load empty document instead. FinishedLoading(CurrentTimeTicks()); } + // FinishedLoading call above must commit navigation for mhtml archive. + CHECK_GE(state_, kCommitted); return; } if (defers_loading_) body_loader_->SetDefersLoading(true); + CommitNavigation(response_.MimeType()); + CHECK_GE(state_, kCommitted); + + // TODO(dgozman): why do we stop loading for media documents? + // This seems like a hack. + if (frame_ && frame_->GetDocument()->IsMediaDocument()) { + parser_->Finish(); + StopLoading(); + return; + } + + // Committing can run unload handlers, which can detach this frame or + // stop this loader. + if (!frame_ || !body_loader_) + return; + if (!url_.ProtocolIsInHTTPFamily()) { // We only support code cache for http family, and browser insists on not // event asking for code cache with other schemes.
diff --git a/third_party/blink/renderer/core/loader/document_loader_test.cc b/third_party/blink/renderer/core/loader/document_loader_test.cc index 194388a..7b85aef 100644 --- a/third_party/blink/renderer/core/loader/document_loader_test.cc +++ b/third_party/blink/renderer/core/loader/document_loader_test.cc
@@ -16,6 +16,7 @@ #include "third_party/blink/renderer/core/frame/frame_test_helpers.h" #include "third_party/blink/renderer/core/frame/web_local_frame_impl.h" #include "third_party/blink/renderer/core/page/page.h" +#include "third_party/blink/renderer/core/testing/scoped_fake_plugin_registry.h" #include "third_party/blink/renderer/platform/loader/static_data_navigation_body_loader.h" #include "third_party/blink/renderer/platform/testing/unit_test_helpers.h" #include "third_party/blink/renderer/platform/testing/url_test_helpers.h" @@ -92,13 +93,13 @@ // 2. The middle part of the response, which is dispatched to // BodyDataReceived() reentrantly. // 3. The final chunk, which is dispatched normally at the top-level. - class ChildDelegate : public WebURLLoaderTestDelegate, - public frame_test_helpers::TestWebFrameClient { + class MainFrameClient : public WebURLLoaderTestDelegate, + public frame_test_helpers::TestWebFrameClient { public: // WebURLLoaderTestDelegate overrides: bool FillNavigationParamsResponse(WebNavigationParams* params) override { params->response = WebURLResponse(params->url); - params->response.SetMimeType("text/html"); + params->response.SetMimeType("application/pdf"); params->response.SetHttpStatusCode(200); std::string data("<html><body>foo</body></html>"); @@ -130,19 +131,19 @@ } // WebLocalFrameClient overrides: - void FrameDetached(DetachType detach_type) override { + void RunScriptsAtDocumentElementAvailable() override { if (dispatching_did_receive_data_) { - // This should be called by the first didReceiveData() call, since - // it should commit the provisional load. + // This should be called by the first BodyDataReceived() call, since + // it should create a plugin document structure and trigger this. EXPECT_GT(data_.size(), 10u); - // Dispatch dataReceived() callbacks for part of the remaining + // Dispatch BodyDataReceived() callbacks for part of the remaining // data, saving the rest to be dispatched at the top-level as // normal. while (data_.size() > 10) DispatchOneByte(); served_reentrantly_ = true; } - TestWebFrameClient::FrameDetached(detach_type); + TestWebFrameClient::RunScriptsAtDocumentElementAvailable(); } void DispatchOneByte() { @@ -160,46 +161,27 @@ StaticDataNavigationBodyLoader* body_loader_ = nullptr; }; - class MainFrameClient : public frame_test_helpers::TestWebFrameClient { - public: - explicit MainFrameClient(TestWebFrameClient& child_client) - : child_client_(child_client) {} - WebLocalFrame* CreateChildFrame(WebLocalFrame* parent, - WebTreeScopeType scope, - const WebString& name, - const WebString& fallback_name, - WebSandboxFlags, - const ParsedFeaturePolicy&, - const WebFrameOwnerProperties&, - FrameOwnerElementType) override { - return CreateLocalChild(*parent, scope, &child_client_); - } - - private: - TestWebFrameClient& child_client_; - }; - - ChildDelegate child_delegate; - MainFrameClient main_frame_client(child_delegate); + // We use a plugin document triggered by "application/pdf" mime type, + // because that gives us reliable way to get a WebLocalFrameClient callback + // from inside BodyDataReceived() call. + ScopedFakePluginRegistry fake_plugins; + MainFrameClient main_frame_client; web_view_helper_.Initialize(&main_frame_client); - - // This doesn't go through the mocked URL load path: it's just intended to - // setup a situation where BodyDataReceived() can be invoked reentrantly. - frame_test_helpers::LoadHTMLString(MainFrame(), "<iframe></iframe>", - url_test_helpers::ToKURL("about:blank")); + web_view_helper_.GetWebView()->GetPage()->GetSettings().SetPluginsEnabled( + true); Platform::Current()->GetURLLoaderMockFactory()->SetLoaderDelegate( - &child_delegate); + &main_frame_client); frame_test_helpers::LoadFrameDontWait( MainFrame(), url_test_helpers::ToKURL("https://example.com/foo.html")); - child_delegate.Serve(); + main_frame_client.Serve(); frame_test_helpers::PumpPendingRequestsForFrameToLoad(MainFrame()); Platform::Current()->GetURLLoaderMockFactory()->SetLoaderDelegate(nullptr); - EXPECT_TRUE(child_delegate.ServedReentrantly()); + // Sanity check that we did actually test reeentrancy. + EXPECT_TRUE(main_frame_client.ServedReentrantly()); - // delegate is a WebLocalFrameClient and stack-allocated, so manually reset() - // the WebViewHelper here. + // MainFrameClient is stack-allocated, so manually Reset to avoid UAF. web_view_helper_.Reset(); }
diff --git a/third_party/blink/renderer/core/loader/preload_helper.cc b/third_party/blink/renderer/core/loader/preload_helper.cc index b42ed8d..551311a 100644 --- a/third_party/blink/renderer/core/loader/preload_helper.cc +++ b/third_party/blink/renderer/core/loader/preload_helper.cc
@@ -513,12 +513,18 @@ break; case ResourceType::kAudio: case ResourceType::kVideo: + params.MutableResourceRequest().SetUseStreamOnResponse(true); + params.MutableOptions().data_buffering_policy = kDoNotBufferData; resource = RawResource::FetchMedia(params, resource_fetcher, nullptr); break; case ResourceType::kTextTrack: + params.MutableResourceRequest().SetUseStreamOnResponse(true); + params.MutableOptions().data_buffering_policy = kDoNotBufferData; resource = RawResource::FetchTextTrack(params, resource_fetcher, nullptr); break; case ResourceType::kImportResource: + params.MutableResourceRequest().SetUseStreamOnResponse(true); + params.MutableOptions().data_buffering_policy = kDoNotBufferData; resource = RawResource::FetchImport(params, resource_fetcher, nullptr); break; case ResourceType::kRaw:
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 604990b..c0ebdfe 100644 --- a/third_party/blink/renderer/core/loader/resource/image_resource.cc +++ b/third_party/blink/renderer/core/loader/resource/image_resource.cc
@@ -398,6 +398,7 @@ if (!all_data_received && Loader()) { // Observers are notified via ImageResource::finish(). // TODO(hiroshige): Do not call didFinishLoading() directly. + Loader()->AbortResponseBodyLoading(); Loader()->DidFinishLoading( CurrentTimeTicks(), size, size, size, false, std::vector<network::cors::PreflightTimingInfo>());
diff --git a/third_party/blink/renderer/core/origin_trials/origin_trial_context.cc b/third_party/blink/renderer/core/origin_trials/origin_trial_context.cc index eedc5e1..c3cabb61 100644 --- a/third_party/blink/renderer/core/origin_trials/origin_trial_context.cc +++ b/third_party/blink/renderer/core/origin_trials/origin_trial_context.cc
@@ -268,15 +268,17 @@ token_string.AsStringPiece(), origin->ToUrlOrigin(), &trial_name_str, base::Time::Now()); if (token_result == OriginTrialTokenStatus::kSuccess) { - valid = true; String trial_name = String::FromUTF8(trial_name_str.data(), trial_name_str.size()); - enabled_trials_.insert(trial_name); - // Also enable any trials implied by this trial - Vector<AtomicString> implied_trials = - origin_trials::GetImpliedTrials(trial_name); - for (const AtomicString& implied_trial_name : implied_trials) { - enabled_trials_.insert(implied_trial_name); + if (origin_trials::TrialEnabledForOS(trial_name)) { + valid = true; + enabled_trials_.insert(trial_name); + // Also enable any trials implied by this trial + Vector<AtomicString> implied_trials = + origin_trials::GetImpliedTrials(trial_name); + for (const AtomicString& implied_trial_name : implied_trials) { + enabled_trials_.insert(implied_trial_name); + } } }
diff --git a/third_party/blink/renderer/core/page/scrolling/scrolling_coordinator.cc b/third_party/blink/renderer/core/page/scrolling/scrolling_coordinator.cc index 999832fa..5d23676 100644 --- a/third_party/blink/renderer/core/page/scrolling/scrolling_coordinator.cc +++ b/third_party/blink/renderer/core/page/scrolling/scrolling_coordinator.cc
@@ -61,9 +61,6 @@ #include "third_party/blink/renderer/platform/instrumentation/tracing/trace_event.h" #include "third_party/blink/renderer/platform/runtime_enabled_features.h" #include "third_party/blink/renderer/platform/transforms/transform_state.h" -#if defined(OS_MACOSX) -#include "third_party/blink/renderer/core/scroll/scroll_animator_mac.h" -#endif #include "third_party/blink/public/platform/platform.h" #include "third_party/blink/public/platform/web_layer_tree_view.h" #include "third_party/blink/renderer/core/scroll/scroll_animator_base.h"
diff --git a/third_party/blink/renderer/core/paint/image_painter.cc b/third_party/blink/renderer/core/paint/image_painter.cc index 50f5fab8..c669891 100644 --- a/third_party/blink/renderer/core/paint/image_painter.cc +++ b/third_party/blink/renderer/core/paint/image_painter.cc
@@ -240,8 +240,9 @@ SkBlendMode::kSrcOver, LayoutObject::ShouldRespectImageOrientation(&layout_image_)); if (origin_trials::ElementTimingEnabled(&layout_image_.GetDocument()) && - IsHTMLImageElement(node) && !context.ContextDisabled() && - layout_image_.CachedImage() && layout_image_.CachedImage()->IsLoaded()) { + (IsHTMLImageElement(node) || IsHTMLVideoElement(node)) && + !context.ContextDisabled() && layout_image_.CachedImage() && + layout_image_.CachedImage()->IsLoaded()) { LocalDOMWindow* window = layout_image_.GetDocument().domWindow(); DCHECK(window); ImageElementTiming::From(*window).NotifyImagePainted(
diff --git a/third_party/blink/renderer/core/paint/text_paint_timing_detector_test.cc b/third_party/blink/renderer/core/paint/text_paint_timing_detector_test.cc index 5441033..e42a70f 100644 --- a/third_party/blink/renderer/core/paint/text_paint_timing_detector_test.cc +++ b/third_party/blink/renderer/core/paint/text_paint_timing_detector_test.cc
@@ -125,7 +125,7 @@ .FindLargestPaintCandidate(); } - void SetFontSize(Element* font_element, uint8_t font_size) { + void SetFontSize(Element* font_element, uint16_t font_size) { DCHECK_EQ(font_element->nodeName(), "FONT"); font_element->setAttribute(html_names::kSizeAttr, AtomicString(WTF::String::Number(font_size)));
diff --git a/third_party/blink/renderer/core/scroll/scroll_animator_mac.h b/third_party/blink/renderer/core/scroll/scroll_animator_mac.h index 199a27e8..b9890f8 100644 --- a/third_party/blink/renderer/core/scroll/scroll_animator_mac.h +++ b/third_party/blink/renderer/core/scroll/scroll_animator_mac.h
@@ -27,6 +27,7 @@ #define THIRD_PARTY_BLINK_RENDERER_CORE_SCROLL_SCROLL_ANIMATOR_MAC_H_ #include <memory> +#include "base/mac/scoped_nsobject.h" #include "base/single_thread_task_runner.h" #include "third_party/blink/renderer/core/scroll/scroll_animator_base.h" #include "third_party/blink/renderer/platform/geometry/float_point.h" @@ -35,7 +36,6 @@ #include "third_party/blink/renderer/platform/heap/handle.h" #include "third_party/blink/renderer/platform/scheduler/public/post_cancellable_task.h" #include "third_party/blink/renderer/platform/timer.h" -#include "third_party/blink/renderer/platform/wtf/retain_ptr.h" OBJC_CLASS BlinkScrollAnimationHelperDelegate; OBJC_CLASS BlinkScrollbarPainterControllerDelegate; @@ -118,16 +118,18 @@ } private: - RetainPtr<id> scroll_animation_helper_; - RetainPtr<BlinkScrollAnimationHelperDelegate> + base::scoped_nsobject<id> scroll_animation_helper_; + base::scoped_nsobject<BlinkScrollAnimationHelperDelegate> scroll_animation_helper_delegate_; - RetainPtr<ScrollbarPainterController> scrollbar_painter_controller_; - RetainPtr<BlinkScrollbarPainterControllerDelegate> + base::scoped_nsobject<ScrollbarPainterController> + scrollbar_painter_controller_; + base::scoped_nsobject<BlinkScrollbarPainterControllerDelegate> scrollbar_painter_controller_delegate_; - RetainPtr<BlinkScrollbarPainterDelegate> + base::scoped_nsobject<BlinkScrollbarPainterDelegate> horizontal_scrollbar_painter_delegate_; - RetainPtr<BlinkScrollbarPainterDelegate> vertical_scrollbar_painter_delegate_; + base::scoped_nsobject<BlinkScrollbarPainterDelegate> + vertical_scrollbar_painter_delegate_; void InitialScrollbarPaintTask(); TaskHandle initial_scrollbar_paint_task_handle_;
diff --git a/third_party/blink/renderer/core/scroll/scroll_animator_mac.mm b/third_party/blink/renderer/core/scroll/scroll_animator_mac.mm index 5a349fe2..b07830cf 100644 --- a/third_party/blink/renderer/core/scroll/scroll_animator_mac.mm +++ b/third_party/blink/renderer/core/scroll/scroll_animator_mac.mm
@@ -28,6 +28,8 @@ #import <AppKit/AppKit.h> #include <memory> +#include "base/mac/scoped_cftyperef.h" +#include "base/memory/scoped_policy.h" #include "third_party/blink/public/platform/platform.h" #include "third_party/blink/renderer/core/scroll/ns_scroller_imp_details.h" #include "third_party/blink/renderer/core/scroll/scrollable_area.h" @@ -346,7 +348,7 @@ @interface BlinkScrollbarPartAnimation : NSObject { blink::Scrollbar* _scrollbar; std::unique_ptr<blink::BlinkScrollbarPartAnimationTimer> _timer; - RetainPtr<ScrollbarPainter> _scrollbarPainter; + base::scoped_nsobject<ScrollbarPainter> _scrollbarPainter; FeatureToAnimate _featureToAnimate; CGFloat _startValue; CGFloat _endValue; @@ -382,7 +384,8 @@ - (void)startAnimation { DCHECK(_scrollbar); - _scrollbarPainter = ScrollbarPainterForScrollbar(*_scrollbar); + _scrollbarPainter.reset(ScrollbarPainterForScrollbar(*_scrollbar), + base::scoped_policy::RETAIN); _timer->Start(); } @@ -414,18 +417,18 @@ blink::ScrollbarPart invalidParts = blink::kNoPart; switch (_featureToAnimate) { case ThumbAlpha: - [_scrollbarPainter.Get() setKnobAlpha:currentValue]; + [_scrollbarPainter setKnobAlpha:currentValue]; break; case TrackAlpha: - [_scrollbarPainter.Get() setTrackAlpha:currentValue]; + [_scrollbarPainter setTrackAlpha:currentValue]; invalidParts = static_cast<blink::ScrollbarPart>(~blink::kThumbPart); break; case UIStateTransition: - [_scrollbarPainter.Get() setUiStateTransitionProgress:currentValue]; + [_scrollbarPainter setUiStateTransitionProgress:currentValue]; invalidParts = blink::kAllParts; break; case ExpansionTransition: - [_scrollbarPainter.Get() setExpansionTransitionProgress:currentValue]; + [_scrollbarPainter setExpansionTransitionProgress:currentValue]; invalidParts = blink::kThumbPart; break; } @@ -445,10 +448,12 @@ @interface BlinkScrollbarPainterDelegate : NSObject<NSAnimationDelegate> { blink::Scrollbar* _scrollbar; - RetainPtr<BlinkScrollbarPartAnimation> _knobAlphaAnimation; - RetainPtr<BlinkScrollbarPartAnimation> _trackAlphaAnimation; - RetainPtr<BlinkScrollbarPartAnimation> _uiStateTransitionAnimation; - RetainPtr<BlinkScrollbarPartAnimation> _expansionTransitionAnimation; + base::scoped_nsobject<BlinkScrollbarPartAnimation> _knobAlphaAnimation; + base::scoped_nsobject<BlinkScrollbarPartAnimation> _trackAlphaAnimation; + base::scoped_nsobject<BlinkScrollbarPartAnimation> + _uiStateTransitionAnimation; + base::scoped_nsobject<BlinkScrollbarPartAnimation> + _expansionTransitionAnimation; BOOL _hasExpandedSinceInvisible; } - (id)initWithScrollbar:(blink::Scrollbar*)scrollbar; @@ -474,10 +479,10 @@ - (void)cancelAnimations { BEGIN_BLOCK_OBJC_EXCEPTIONS; - [_knobAlphaAnimation.Get() stopAnimation]; - [_trackAlphaAnimation.Get() stopAnimation]; - [_uiStateTransitionAnimation.Get() stopAnimation]; - [_expansionTransitionAnimation.Get() stopAnimation]; + [_knobAlphaAnimation stopAnimation]; + [_trackAlphaAnimation stopAnimation]; + [_uiStateTransitionAnimation stopAnimation]; + [_expansionTransitionAnimation stopAnimation]; END_BLOCK_OBJC_EXCEPTIONS; } @@ -505,7 +510,8 @@ } - (void)setUpAlphaAnimation: - (RetainPtr<BlinkScrollbarPartAnimation>&)scrollbarPartAnimation + (base::scoped_nsobject<BlinkScrollbarPartAnimation>&) + scrollbarPartAnimation scrollerPainter:(ScrollbarPainter)scrollerPainter part:(blink::ScrollbarPart)part animateAlphaTo:(CGFloat)newAlpha @@ -529,18 +535,18 @@ // If we are currently animating, stop if (scrollbarPartAnimation) { - [scrollbarPartAnimation.Get() stopAnimation]; - scrollbarPartAnimation = nullptr; + [scrollbarPartAnimation stopAnimation]; + scrollbarPartAnimation.reset(); } - scrollbarPartAnimation.AdoptNS([[BlinkScrollbarPartAnimation alloc] + scrollbarPartAnimation.reset([[BlinkScrollbarPartAnimation alloc] initWithScrollbar:_scrollbar featureToAnimate:part == blink::kThumbPart ? ThumbAlpha : TrackAlpha animateFrom:part == blink::kThumbPart ? [scrollerPainter knobAlpha] : [scrollerPainter trackAlpha] animateTo:newAlpha duration:duration]); - [scrollbarPartAnimation.Get() startAnimation]; + [scrollbarPartAnimation startAnimation]; } - (void)scrollerImp:(id)scrollerImp @@ -593,7 +599,7 @@ setUiStateTransitionProgress:1 - [scrollerImp uiStateTransitionProgress]]; if (!_uiStateTransitionAnimation) - _uiStateTransitionAnimation.AdoptNS([[BlinkScrollbarPartAnimation alloc] + _uiStateTransitionAnimation.reset([[BlinkScrollbarPartAnimation alloc] initWithScrollbar:_scrollbar featureToAnimate:UIStateTransition animateFrom:[scrollbarPainter uiStateTransitionProgress] @@ -602,12 +608,12 @@ else { // If we don't need to initialize the animation, just reset the values in // case they have changed. - [_uiStateTransitionAnimation.Get() + [_uiStateTransitionAnimation setStartValue:[scrollbarPainter uiStateTransitionProgress]]; - [_uiStateTransitionAnimation.Get() setEndValue:1.0]; - [_uiStateTransitionAnimation.Get() setDuration:duration]; + [_uiStateTransitionAnimation setEndValue:1.0]; + [_uiStateTransitionAnimation setDuration:duration]; } - [_uiStateTransitionAnimation.Get() startAnimation]; + [_uiStateTransitionAnimation startAnimation]; } - (void)scrollerImp:(id)scrollerImp @@ -629,7 +635,7 @@ [scrollerImp expansionTransitionProgress]]; if (!_expansionTransitionAnimation) { - _expansionTransitionAnimation.AdoptNS([[BlinkScrollbarPartAnimation alloc] + _expansionTransitionAnimation.reset([[BlinkScrollbarPartAnimation alloc] initWithScrollbar:_scrollbar featureToAnimate:ExpansionTransition animateFrom:[scrollbarPainter expansionTransitionProgress] @@ -638,12 +644,12 @@ } else { // If we don't need to initialize the animation, just reset the values in // case they have changed. - [_expansionTransitionAnimation.Get() + [_expansionTransitionAnimation setStartValue:[scrollbarPainter uiStateTransitionProgress]]; - [_expansionTransitionAnimation.Get() setEndValue:1.0]; - [_expansionTransitionAnimation.Get() setDuration:duration]; + [_expansionTransitionAnimation setEndValue:1.0]; + [_expansionTransitionAnimation setDuration:duration]; } - [_expansionTransitionAnimation.Get() startAnimation]; + [_expansionTransitionAnimation startAnimation]; } - (void)scrollerImp:(id)scrollerImp @@ -672,10 +678,10 @@ - (void)invalidate { _scrollbar = 0; BEGIN_BLOCK_OBJC_EXCEPTIONS; - [_knobAlphaAnimation.Get() invalidate]; - [_trackAlphaAnimation.Get() invalidate]; - [_uiStateTransitionAnimation.Get() invalidate]; - [_expansionTransitionAnimation.Get() invalidate]; + [_knobAlphaAnimation invalidate]; + [_trackAlphaAnimation invalidate]; + [_uiStateTransitionAnimation invalidate]; + [_expansionTransitionAnimation invalidate]; END_BLOCK_OBJC_EXCEPTIONS; } @@ -693,21 +699,21 @@ task_runner_(ThreadScheduler::Current()->CompositorTaskRunner()), have_scrolled_since_page_load_(false), needs_scroller_style_update_(false) { - scroll_animation_helper_delegate_.AdoptNS( + scroll_animation_helper_delegate_.reset( [[BlinkScrollAnimationHelperDelegate alloc] initWithScrollAnimator:this]); - scroll_animation_helper_.AdoptNS( - [[NSClassFromString(@"NSScrollAnimationHelper") alloc] - initWithDelegate:scroll_animation_helper_delegate_.Get()]); + scroll_animation_helper_.reset([[NSClassFromString(@"NSScrollAnimationHelper") + alloc] initWithDelegate:scroll_animation_helper_delegate_]); - scrollbar_painter_controller_delegate_.AdoptNS( + scrollbar_painter_controller_delegate_.reset( [[BlinkScrollbarPainterControllerDelegate alloc] initWithScrollableArea:scrollable_area]); - scrollbar_painter_controller_ = - [[[NSClassFromString(@"NSScrollerImpPair") alloc] init] autorelease]; - [scrollbar_painter_controller_.Get() + scrollbar_painter_controller_.reset( + [[[NSClassFromString(@"NSScrollerImpPair") alloc] init] autorelease], + base::scoped_policy::RETAIN); + [scrollbar_painter_controller_ performSelector:@selector(setDelegate:) - withObject:scrollbar_painter_controller_delegate_.Get()]; - [scrollbar_painter_controller_.Get() + withObject:scrollbar_painter_controller_delegate_]; + [scrollbar_painter_controller_ setScrollerStyle:ScrollbarThemeMac::RecommendedScrollerStyle()]; } @@ -716,18 +722,18 @@ void ScrollAnimatorMac::Dispose() { BEGIN_BLOCK_OBJC_EXCEPTIONS; ScrollbarPainter horizontal_scrollbar_painter = - [scrollbar_painter_controller_.Get() horizontalScrollerImp]; + [scrollbar_painter_controller_ horizontalScrollerImp]; [horizontal_scrollbar_painter setDelegate:nil]; ScrollbarPainter vertical_scrollbar_painter = - [scrollbar_painter_controller_.Get() verticalScrollerImp]; + [scrollbar_painter_controller_ verticalScrollerImp]; [vertical_scrollbar_painter setDelegate:nil]; - [scrollbar_painter_controller_delegate_.Get() invalidate]; - [scrollbar_painter_controller_.Get() setDelegate:nil]; - [horizontal_scrollbar_painter_delegate_.Get() invalidate]; - [vertical_scrollbar_painter_delegate_.Get() invalidate]; - [scroll_animation_helper_delegate_.Get() invalidate]; + [scrollbar_painter_controller_delegate_ invalidate]; + [scrollbar_painter_controller_ setDelegate:nil]; + [horizontal_scrollbar_painter_delegate_ invalidate]; + [vertical_scrollbar_painter_delegate_ invalidate]; + [scroll_animation_helper_delegate_ invalidate]; END_BLOCK_OBJC_EXCEPTIONS; initial_scrollbar_paint_task_handle_.Cancel(); @@ -750,8 +756,8 @@ return ScrollResult(); // Prevent clobbering an existing animation on an unscrolled axis. - if ([scroll_animation_helper_.Get() _isAnimating]) { - NSPoint target_origin = [scroll_animation_helper_.Get() targetOrigin]; + if ([scroll_animation_helper_ _isAnimating]) { + NSPoint target_origin = [scroll_animation_helper_ targetOrigin]; if (!delta.Width()) new_offset.SetWidth(target_origin.x); if (!delta.Height()) @@ -759,7 +765,7 @@ } NSPoint new_point = NSMakePoint(new_offset.Width(), new_offset.Height()); - [scroll_animation_helper_.Get() scrollToPoint:new_point]; + [scroll_animation_helper_ scrollToPoint:new_point]; // TODO(bokan): This has different semantics on ScrollResult than // ScrollAnimator, @@ -772,7 +778,7 @@ void ScrollAnimatorMac::ScrollToOffsetWithoutAnimation( const ScrollOffset& offset) { - [scroll_animation_helper_.Get() _stopRun]; + [scroll_animation_helper_ _stopRun]; ImmediateScrollTo(offset); } @@ -812,25 +818,25 @@ void ScrollAnimatorMac::ContentAreaWillPaint() const { if (!GetScrollableArea()->ScrollbarsCanBeActive()) return; - [scrollbar_painter_controller_.Get() contentAreaWillDraw]; + [scrollbar_painter_controller_ contentAreaWillDraw]; } void ScrollAnimatorMac::MouseEnteredContentArea() const { if (!GetScrollableArea()->ScrollbarsCanBeActive()) return; - [scrollbar_painter_controller_.Get() mouseEnteredContentArea]; + [scrollbar_painter_controller_ mouseEnteredContentArea]; } void ScrollAnimatorMac::MouseExitedContentArea() const { if (!GetScrollableArea()->ScrollbarsCanBeActive()) return; - [scrollbar_painter_controller_.Get() mouseExitedContentArea]; + [scrollbar_painter_controller_ mouseExitedContentArea]; } void ScrollAnimatorMac::MouseMovedInContentArea() const { if (!GetScrollableArea()->ScrollbarsCanBeActive()) return; - [scrollbar_painter_controller_.Get() mouseMovedInContentArea]; + [scrollbar_painter_controller_ mouseMovedInContentArea]; } void ScrollAnimatorMac::MouseEnteredScrollbar(Scrollbar& scrollbar) const { @@ -856,23 +862,23 @@ void ScrollAnimatorMac::ContentsResized() const { if (!GetScrollableArea()->ScrollbarsCanBeActive()) return; - [scrollbar_painter_controller_.Get() contentAreaDidResize]; + [scrollbar_painter_controller_ contentAreaDidResize]; } void ScrollAnimatorMac::ContentAreaDidShow() const { if (!GetScrollableArea()->ScrollbarsCanBeActive()) return; - [scrollbar_painter_controller_.Get() windowOrderedIn]; + [scrollbar_painter_controller_ windowOrderedIn]; } void ScrollAnimatorMac::ContentAreaDidHide() const { if (!GetScrollableArea()->ScrollbarsCanBeActive()) return; - [scrollbar_painter_controller_.Get() windowOrderedOut]; + [scrollbar_painter_controller_ windowOrderedOut]; } void ScrollAnimatorMac::FinishCurrentScrollAnimations() { - [scrollbar_painter_controller_.Get() hideOverlayScrollers]; + [scrollbar_painter_controller_ hideOverlayScrollers]; } void ScrollAnimatorMac::DidAddVerticalScrollbar(Scrollbar& scrollbar) { @@ -881,24 +887,24 @@ return; DCHECK(!vertical_scrollbar_painter_delegate_); - vertical_scrollbar_painter_delegate_.AdoptNS( + vertical_scrollbar_painter_delegate_.reset( [[BlinkScrollbarPainterDelegate alloc] initWithScrollbar:&scrollbar]); - [painter setDelegate:vertical_scrollbar_painter_delegate_.Get()]; - [scrollbar_painter_controller_.Get() setVerticalScrollerImp:painter]; + [painter setDelegate:vertical_scrollbar_painter_delegate_]; + [scrollbar_painter_controller_ setVerticalScrollerImp:painter]; } void ScrollAnimatorMac::WillRemoveVerticalScrollbar(Scrollbar& scrollbar) { ScrollbarPainter painter = ScrollbarPainterForScrollbar(scrollbar); - DCHECK_EQ([scrollbar_painter_controller_.Get() verticalScrollerImp], painter); + DCHECK_EQ([scrollbar_painter_controller_ verticalScrollerImp], painter); if (!painter) DCHECK(!vertical_scrollbar_painter_delegate_); [painter setDelegate:nil]; - [vertical_scrollbar_painter_delegate_.Get() invalidate]; - vertical_scrollbar_painter_delegate_ = nullptr; - [scrollbar_painter_controller_.Get() setVerticalScrollerImp:nil]; + [vertical_scrollbar_painter_delegate_ invalidate]; + vertical_scrollbar_painter_delegate_.reset(); + [scrollbar_painter_controller_ setVerticalScrollerImp:nil]; } void ScrollAnimatorMac::DidAddHorizontalScrollbar(Scrollbar& scrollbar) { @@ -907,25 +913,24 @@ return; DCHECK(!horizontal_scrollbar_painter_delegate_); - horizontal_scrollbar_painter_delegate_.AdoptNS( + horizontal_scrollbar_painter_delegate_.reset( [[BlinkScrollbarPainterDelegate alloc] initWithScrollbar:&scrollbar]); - [painter setDelegate:horizontal_scrollbar_painter_delegate_.Get()]; - [scrollbar_painter_controller_.Get() setHorizontalScrollerImp:painter]; + [painter setDelegate:horizontal_scrollbar_painter_delegate_]; + [scrollbar_painter_controller_ setHorizontalScrollerImp:painter]; } void ScrollAnimatorMac::WillRemoveHorizontalScrollbar(Scrollbar& scrollbar) { ScrollbarPainter painter = ScrollbarPainterForScrollbar(scrollbar); - DCHECK_EQ([scrollbar_painter_controller_.Get() horizontalScrollerImp], - painter); + DCHECK_EQ([scrollbar_painter_controller_ horizontalScrollerImp], painter); if (!painter) DCHECK(!horizontal_scrollbar_painter_delegate_); [painter setDelegate:nil]; - [horizontal_scrollbar_painter_delegate_.Get() invalidate]; - horizontal_scrollbar_painter_delegate_ = nullptr; - [scrollbar_painter_controller_.Get() setHorizontalScrollerImp:nil]; + [horizontal_scrollbar_painter_delegate_ invalidate]; + horizontal_scrollbar_painter_delegate_.reset(); + [scrollbar_painter_controller_ setHorizontalScrollerImp:nil]; } void ScrollAnimatorMac::NotifyContentAreaScrolled(const ScrollOffset& delta, @@ -942,18 +947,17 @@ bool ScrollAnimatorMac::SetScrollbarsVisibleForTesting(bool show) { if (show) - [scrollbar_painter_controller_.Get() flashScrollers]; + [scrollbar_painter_controller_ flashScrollers]; else - [scrollbar_painter_controller_.Get() hideOverlayScrollers]; + [scrollbar_painter_controller_ hideOverlayScrollers]; - [vertical_scrollbar_painter_delegate_.Get() updateVisibilityImmediately:show]; - [horizontal_scrollbar_painter_delegate_.Get() - updateVisibilityImmediately:show]; + [vertical_scrollbar_painter_delegate_ updateVisibilityImmediately:show]; + [horizontal_scrollbar_painter_delegate_ updateVisibilityImmediately:show]; return true; } void ScrollAnimatorMac::CancelAnimation() { - [scroll_animation_helper_.Get() _stopRun]; + [scroll_animation_helper_ _stopRun]; have_scrolled_since_page_load_ = false; } @@ -970,25 +974,22 @@ return; } - NSScrollerStyle new_style = - [scrollbar_painter_controller_.Get() scrollerStyle]; + NSScrollerStyle new_style = [scrollbar_painter_controller_ scrollerStyle]; if (Scrollbar* vertical_scrollbar = GetScrollableArea()->VerticalScrollbar()) { vertical_scrollbar->SetNeedsPaintInvalidation(kAllParts); ScrollbarPainter old_vertical_painter = - [scrollbar_painter_controller_.Get() verticalScrollerImp]; + [scrollbar_painter_controller_ verticalScrollerImp]; ScrollbarPainter new_vertical_painter = [NSClassFromString(@"NSScrollerImp") scrollerImpWithStyle:new_style controlSize:(NSControlSize)vertical_scrollbar->GetControlSize() horizontal:NO replacingScrollerImp:old_vertical_painter]; [old_vertical_painter setDelegate:nil]; - [new_vertical_painter - setDelegate:vertical_scrollbar_painter_delegate_.Get()]; - [scrollbar_painter_controller_.Get() - setVerticalScrollerImp:new_vertical_painter]; + [new_vertical_painter setDelegate:vertical_scrollbar_painter_delegate_]; + [scrollbar_painter_controller_ setVerticalScrollerImp:new_vertical_painter]; mac_theme->SetNewPainterForScrollbar(*vertical_scrollbar, new_vertical_painter); @@ -1007,7 +1008,7 @@ horizontal_scrollbar->SetNeedsPaintInvalidation(kAllParts); ScrollbarPainter old_horizontal_painter = - [scrollbar_painter_controller_.Get() horizontalScrollerImp]; + [scrollbar_painter_controller_ horizontalScrollerImp]; ScrollbarPainter new_horizontal_painter = [NSClassFromString(@"NSScrollerImp") scrollerImpWithStyle:new_style @@ -1016,9 +1017,8 @@ horizontal:YES replacingScrollerImp:old_horizontal_painter]; [old_horizontal_painter setDelegate:nil]; - [new_horizontal_painter - setDelegate:horizontal_scrollbar_painter_delegate_.Get()]; - [scrollbar_painter_controller_.Get() + [new_horizontal_painter setDelegate:horizontal_scrollbar_painter_delegate_]; + [scrollbar_painter_controller_ setHorizontalScrollerImp:new_horizontal_painter]; mac_theme->SetNewPainterForScrollbar(*horizontal_scrollbar, new_horizontal_painter); @@ -1065,8 +1065,8 @@ // To force the scrollbars to flash, we have to call hide first. Otherwise, // the ScrollbarPainterController // might think that the scrollbars are already showing and bail early. - [scrollbar_painter_controller_.Get() hideOverlayScrollers]; - [scrollbar_painter_controller_.Get() flashScrollers]; + [scrollbar_painter_controller_ hideOverlayScrollers]; + [scrollbar_painter_controller_ flashScrollers]; } void ScrollAnimatorMac::SendContentAreaScrolledSoon(const ScrollOffset& delta) { @@ -1082,13 +1082,13 @@ void ScrollAnimatorMac::SendContentAreaScrolledTask() { if (SupportsContentAreaScrolledInDirection()) { - [scrollbar_painter_controller_.Get() + [scrollbar_painter_controller_ contentAreaScrolledInDirection: NSMakePoint(content_area_scrolled_timer_scroll_delta_.Width(), content_area_scrolled_timer_scroll_delta_.Height())]; content_area_scrolled_timer_scroll_delta_ = ScrollOffset(); } else - [scrollbar_painter_controller_.Get() contentAreaScrolled]; + [scrollbar_painter_controller_ contentAreaScrolled]; } } // namespace blink
diff --git a/third_party/blink/renderer/core/scroll/scrollbar_theme_mac.mm b/third_party/blink/renderer/core/scroll/scrollbar_theme_mac.mm index 9aac70e..80e0636a 100644 --- a/third_party/blink/renderer/core/scroll/scrollbar_theme_mac.mm +++ b/third_party/blink/renderer/core/scroll/scrollbar_theme_mac.mm
@@ -26,6 +26,8 @@ #include "third_party/blink/renderer/core/scroll/scrollbar_theme_mac.h" #include <Carbon/Carbon.h> +#include "base/mac/scoped_nsobject.h" +#include "base/memory/scoped_policy.h" #include "skia/ext/skia_utils_mac.h" #include "third_party/blink/public/platform/mac/web_scrollbar_theme.h" #include "third_party/blink/public/platform/platform.h" @@ -41,7 +43,6 @@ #include "third_party/blink/renderer/platform/mac/local_current_graphics_context.h" #include "third_party/blink/renderer/platform/runtime_enabled_features.h" #include "third_party/blink/renderer/platform/wtf/hash_set.h" -#include "third_party/blink/renderer/platform/wtf/retain_ptr.h" #include "third_party/blink/renderer/platform/wtf/std_lib_extras.h" // FIXME: There are repainting problems due to Aqua scroll bar buttons' visual @@ -53,30 +54,31 @@ @interface BlinkScrollbarObserver : NSObject { blink::Scrollbar* _scrollbar; - RetainPtr<ScrollbarPainter> _scrollbarPainter; + base::scoped_nsobject<ScrollbarPainter> _scrollbarPainter; BOOL _suppressSetScrollbarsHidden; } - (id)initWithScrollbar:(blink::Scrollbar*)scrollbar - painter:(const RetainPtr<ScrollbarPainter>&)painter; + painter:(const base::scoped_nsobject<ScrollbarPainter>&)painter; @end @implementation BlinkScrollbarObserver - (id)initWithScrollbar:(blink::Scrollbar*)scrollbar - painter:(const RetainPtr<ScrollbarPainter>&)painter { + painter: + (const base::scoped_nsobject<ScrollbarPainter>&)painter { if (!(self = [super init])) return nil; _scrollbar = scrollbar; _scrollbarPainter = painter; - [_scrollbarPainter.Get() addObserver:self - forKeyPath:@"knobAlpha" - options:0 - context:nil]; + [_scrollbarPainter addObserver:self + forKeyPath:@"knobAlpha" + options:0 + context:nil]; return self; } - (id)painter { - return _scrollbarPainter.Get(); + return _scrollbarPainter; } - (void)setSuppressSetScrollbarsHidden:(BOOL)value { @@ -84,7 +86,7 @@ } - (void)dealloc { - [_scrollbarPainter.Get() removeObserver:self forKeyPath:@"knobAlpha"]; + [_scrollbarPainter removeObserver:self forKeyPath:@"knobAlpha"]; [super dealloc]; } @@ -94,7 +96,7 @@ context:(void*)context { if ([keyPath isEqualToString:@"knobAlpha"]) { if (!_suppressSetScrollbarsHidden) { - BOOL visible = [_scrollbarPainter.Get() knobAlpha] > 0; + BOOL visible = [_scrollbarPainter knobAlpha] > 0; _scrollbar->SetScrollbarsHiddenIfOverlay(!visible); } } @@ -117,7 +119,8 @@ return *set; } -typedef HeapHashMap<WeakMember<Scrollbar>, RetainPtr<BlinkScrollbarObserver>> +typedef HeapHashMap<WeakMember<Scrollbar>, + base::scoped_nsobject<BlinkScrollbarObserver>> ScrollbarPainterMap; static ScrollbarPainterMap& GetScrollbarPainterMap() { @@ -207,15 +210,13 @@ GetScrollbarSet().insert(&scrollbar); bool is_horizontal = scrollbar.Orientation() == kHorizontalScrollbar; - RetainPtr<ScrollbarPainter> scrollbar_painter( - kAdoptNS, + base::scoped_nsobject<ScrollbarPainter> scrollbar_painter( [[NSClassFromString(@"NSScrollerImp") scrollerImpWithStyle:RecommendedScrollerStyle() controlSize:(NSControlSize)scrollbar.GetControlSize() horizontal:is_horizontal replacingScrollerImp:nil] retain]); - RetainPtr<BlinkScrollbarObserver> observer( - kAdoptNS, + base::scoped_nsobject<BlinkScrollbarObserver> observer( [[BlinkScrollbarObserver alloc] initWithScrollbar:&scrollbar painter:scrollbar_painter]); @@ -232,9 +233,9 @@ void ScrollbarThemeMac::SetNewPainterForScrollbar( Scrollbar& scrollbar, ScrollbarPainter new_painter) { - RetainPtr<ScrollbarPainter> scrollbar_painter(kAdoptNS, [new_painter retain]); - RetainPtr<BlinkScrollbarObserver> observer( - kAdoptNS, + base::scoped_nsobject<ScrollbarPainter> scrollbar_painter( + [new_painter retain]); + base::scoped_nsobject<BlinkScrollbarObserver> observer( [[BlinkScrollbarObserver alloc] initWithScrollbar:&scrollbar painter:scrollbar_painter]); GetScrollbarPainterMap().Set(&scrollbar, observer); @@ -244,9 +245,8 @@ ScrollbarPainter ScrollbarThemeMac::PainterForScrollbar( const Scrollbar& scrollbar) const { - return [GetScrollbarPainterMap() - .at(const_cast<Scrollbar*>(&scrollbar)) - .Get() painter]; + return + [GetScrollbarPainterMap().at(const_cast<Scrollbar*>(&scrollbar)) painter]; } void ScrollbarThemeMac::PaintTrackBackground(GraphicsContext& context, @@ -294,9 +294,10 @@ { LocalCurrentGraphicsContext local_context(context, local_rect); - RetainPtr<BlinkScrollbarObserver> observer = - GetScrollbarPainterMap().at(const_cast<Scrollbar*>(&scrollbar)); - ScrollbarPainter scrollbar_painter = [observer.Get() painter]; + base::scoped_nsobject<BlinkScrollbarObserver> observer( + GetScrollbarPainterMap().at(const_cast<Scrollbar*>(&scrollbar)), + base::scoped_policy::RETAIN); + ScrollbarPainter scrollbar_painter = [observer painter]; [scrollbar_painter setEnabled:scrollbar.Enabled()]; // drawKnob aligns the thumb to right side of the draw rect. // If the vertical overlay scrollbar is on the left, use trackWidth instead @@ -312,7 +313,7 @@ [scrollbar_painter setDoubleValue:0]; [scrollbar_painter setKnobProportion:1]; - [observer.Get() setSuppressSetScrollbarsHidden:YES]; + [observer setSuppressSetScrollbarsHidden:YES]; CGFloat old_knob_alpha = [scrollbar_painter knobAlpha]; [scrollbar_painter setKnobAlpha:1]; @@ -325,7 +326,7 @@ [scrollbar_painter setBoundsSize:NSSizeFromCGSize(CGSize(scrollbar.FrameRect().Size()))]; [scrollbar_painter setKnobAlpha:old_knob_alpha]; - [observer.Get() setSuppressSetScrollbarsHidden:NO]; + [observer setSuppressSetScrollbarsHidden:NO]; } if (opacity != 1.0f)
diff --git a/third_party/blink/renderer/core/testing/origin_trials_test.h b/third_party/blink/renderer/core/testing/origin_trials_test.h index 923b31a5..8b4aa05 100644 --- a/third_party/blink/renderer/core/testing/origin_trials_test.h +++ b/third_party/blink/renderer/core/testing/origin_trials_test.h
@@ -59,6 +59,8 @@ static bool secureStaticMethod() { return true; } bool impliedAttribute() { return true; } + + bool invalidOSAttribute() { return true; } }; } // namespace blink
diff --git a/third_party/blink/renderer/core/testing/origin_trials_test.idl b/third_party/blink/renderer/core/testing/origin_trials_test.idl index 1e90fee..8f5717be 100644 --- a/third_party/blink/renderer/core/testing/origin_trials_test.idl +++ b/third_party/blink/renderer/core/testing/origin_trials_test.idl
@@ -48,4 +48,7 @@ // These are available if the specified trial is available, and also if the // implied by trial is enabled [OriginTrialEnabled=OriginTrialsSampleAPIImplied] readonly attribute boolean impliedAttribute; + + // These are not available even with the token present. + [OriginTrialEnabled=OriginTrialsSampleAPIInvalidOS] readonly attribute boolean invalidOSAttribute; };
diff --git a/third_party/blink/renderer/modules/accessibility/ax_selection_test.cc b/third_party/blink/renderer/modules/accessibility/ax_selection_test.cc index 1171292..3b0ae5b 100644 --- a/third_party/blink/renderer/modules/accessibility/ax_selection_test.cc +++ b/third_party/blink/renderer/modules/accessibility/ax_selection_test.cc
@@ -1144,6 +1144,87 @@ EXPECT_EQ("backward", ToTextControl(*textarea).selectionDirection()); } +TEST_F(AccessibilitySelectionTest, + SelectEachConsecutiveCharacterInContenteditable) { + // The text should wrap after each word. + SetBodyInnerHTML(R"HTML( + <div id="contenteditable" contenteditable role="textbox" + style="max-width: 5px; overflow-wrap: normal;"> + This is a test. + </div> + )HTML"); + + const Element* contenteditable = + GetDocument().QuerySelector("div[contenteditable]"); + ASSERT_NE(nullptr, contenteditable); + const Node* text = contenteditable->firstChild(); + ASSERT_NE(nullptr, text); + ASSERT_TRUE(text->IsTextNode()); + + const AXObject* ax_contenteditable = + GetAXObjectByElementId("contenteditable"); + ASSERT_NE(nullptr, ax_contenteditable); + ASSERT_EQ(ax::mojom::Role::kTextField, ax_contenteditable->RoleValue()); + ASSERT_EQ(1, ax_contenteditable->ChildCount()); + const AXObject* ax_static_text = ax_contenteditable->FirstChild(); + ASSERT_NE(nullptr, ax_static_text); + ASSERT_EQ(ax::mojom::Role::kStaticText, ax_static_text->RoleValue()); + String computed_name = ax_static_text->ComputedName(); + ASSERT_LE(1u, computed_name.length()); + + for (unsigned int i = 0; i < computed_name.length() - 1; ++i) { + AXSelection::Builder builder; + AXSelection ax_selection = + builder + .SetBase(AXPosition::CreatePositionInTextObject(*ax_static_text, i)) + .SetExtent( + AXPosition::CreatePositionInTextObject(*ax_static_text, i + 1)) + .Build(); + + testing::Message message; + message << "While selecting forward character " << computed_name[i] + << " at position " << i << " in contenteditable."; + SCOPED_TRACE(message); + EXPECT_TRUE(ax_selection.Select()); + + const SelectionInDOMTree dom_selection = + Selection().GetSelectionInDOMTree(); + EXPECT_EQ(text, dom_selection.Base().AnchorNode()); + EXPECT_EQ(text, dom_selection.Extent().AnchorNode()); + // The discrepancy between DOM and AX text offsets is due to the fact that + // there is some white space in the DOM that is compressed in the + // accessibility tree. + EXPECT_EQ(int{i + 9}, dom_selection.Base().OffsetInContainerNode()); + EXPECT_EQ(int{i + 10}, dom_selection.Extent().OffsetInContainerNode()); + } + + for (unsigned int i = computed_name.length(); i > 0; --i) { + AXSelection::Builder builder; + AXSelection ax_selection = + builder + .SetBase(AXPosition::CreatePositionInTextObject(*ax_static_text, i)) + .SetExtent( + AXPosition::CreatePositionInTextObject(*ax_static_text, i - 1)) + .Build(); + + testing::Message message; + message << "While selecting backward character " << computed_name[i] + << " at position " << i << " in contenteditable."; + SCOPED_TRACE(message); + EXPECT_TRUE(ax_selection.Select()); + + const SelectionInDOMTree dom_selection = + Selection().GetSelectionInDOMTree(); + EXPECT_EQ(text, dom_selection.Base().AnchorNode()); + EXPECT_EQ(text, dom_selection.Extent().AnchorNode()); + // The discrepancy between DOM and AX text offsets is due to the fact that + // there is some white space in the DOM that is compressed in the + // accessibility tree. + EXPECT_EQ(int{i + 9}, dom_selection.Base().OffsetInContainerNode()); + EXPECT_EQ(int{i + 8}, dom_selection.Extent().OffsetInContainerNode()); + } +} + // // Declarative tests. //
diff --git a/third_party/blink/renderer/modules/exported/web_embedded_worker_impl.cc b/third_party/blink/renderer/modules/exported/web_embedded_worker_impl.cc index 9050878..a7298998 100644 --- a/third_party/blink/renderer/modules/exported/web_embedded_worker_impl.cc +++ b/third_party/blink/renderer/modules/exported/web_embedded_worker_impl.cc
@@ -556,4 +556,9 @@ document->Fetcher()->GetProperties().GetFetchClientSettingsObject()); } +void WebEmbeddedWorkerImpl::WaitForShutdownForTesting() { + DCHECK(worker_thread_); + worker_thread_->WaitForShutdownForTesting(); +} + } // namespace blink
diff --git a/third_party/blink/renderer/modules/exported/web_embedded_worker_impl.h b/third_party/blink/renderer/modules/exported/web_embedded_worker_impl.h index 84fe471..3adbaf3c 100644 --- a/third_party/blink/renderer/modules/exported/web_embedded_worker_impl.h +++ b/third_party/blink/renderer/modules/exported/web_embedded_worker_impl.h
@@ -83,6 +83,8 @@ std::unique_ptr<WebServiceWorkerContextClient>, std::unique_ptr<ServiceWorkerInstalledScriptsManager>); + void WaitForShutdownForTesting(); + private: // WebDevToolsAgentImpl::Client overrides. void ResumeStartup() override;
diff --git a/third_party/blink/renderer/modules/service_worker/web_embedded_worker_impl_test.cc b/third_party/blink/renderer/modules/service_worker/web_embedded_worker_impl_test.cc index 67e364de..c8cb1197 100644 --- a/third_party/blink/renderer/modules/service_worker/web_embedded_worker_impl_test.cc +++ b/third_party/blink/renderer/modules/service_worker/web_embedded_worker_impl_test.cc
@@ -6,15 +6,19 @@ #include <memory> +#include "base/feature_list.h" #include "base/synchronization/waitable_event.h" +#include "base/test/scoped_feature_list.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" +#include "third_party/blink/public/common/features.h" #include "third_party/blink/public/common/messaging/message_port_channel.h" #include "third_party/blink/public/mojom/service_worker/service_worker_installed_scripts_manager.mojom-blink.h" #include "third_party/blink/public/mojom/service_worker/service_worker_object.mojom-blink.h" #include "third_party/blink/public/platform/modules/service_worker/web_service_worker_network_provider.h" #include "third_party/blink/public/platform/platform.h" #include "third_party/blink/public/platform/web_content_settings_client.h" +#include "third_party/blink/public/platform/web_url_loader_client.h" #include "third_party/blink/public/platform/web_url_loader_mock_factory.h" #include "third_party/blink/public/platform/web_url_response.h" #include "third_party/blink/public/web/modules/service_worker/web_service_worker_context_client.h" @@ -31,8 +35,10 @@ namespace blink { namespace { +const char* kNotFoundScriptURL = "https://www.example.com/sw-404.js"; + // Fake network provider for service worker execution contexts. -class FakeServiceWorkerNetworkProvider +class FakeServiceWorkerNetworkProvider final : public WebServiceWorkerNetworkProvider { public: FakeServiceWorkerNetworkProvider() = default; @@ -62,7 +68,82 @@ void DispatchNetworkQuiet() override {} }; -class MockServiceWorkerContextClient : public WebServiceWorkerContextClient { +// A fake WebURLLoader which is used for off-main-thread script fetch tests. +class FakeWebURLLoader final : public WebURLLoader { + public: + FakeWebURLLoader() {} + ~FakeWebURLLoader() override = default; + + void LoadSynchronously(const WebURLRequest&, + WebURLLoaderClient*, + WebURLResponse&, + base::Optional<WebURLError>&, + WebData&, + int64_t& encoded_data_length, + int64_t& encoded_body_length, + WebBlobInfo& downloaded_blob) override { + NOTREACHED(); + } + + void LoadAsynchronously(const WebURLRequest& request, + WebURLLoaderClient* client) override { + if (request.Url().GetString() == kNotFoundScriptURL) { + WebURLResponse response; + response.SetMimeType("text/javascript"); + response.SetHttpStatusCode(404); + client->DidReceiveResponse(response); + client->DidFinishLoading(TimeTicks(), 0, 0, 0, false, {}); + return; + } + // Don't handle other requests intentionally to emulate ongoing load. + } + + void Cancel() override {} + void SetDefersLoading(bool defers) override {} + void DidChangePriority(WebURLRequest::Priority, int) override {} +}; + +// A fake WebURLLoaderFactory which is used for off-main-thread script fetch +// tests. +class FakeWebURLLoaderFactory final : public WebURLLoaderFactory { + public: + std::unique_ptr<WebURLLoader> CreateURLLoader( + const WebURLRequest&, + std::unique_ptr<scheduler::WebResourceLoadingTaskRunnerHandle>) override { + return std::make_unique<FakeWebURLLoader>(); + } +}; + +// A fake WebWorkerFetchContext which is used for off-main-thread script fetch +// tests. +class FakeWebWorkerFetchContext final : public WebWorkerFetchContext { + public: + void SetTerminateSyncLoadEvent(base::WaitableEvent*) override {} + void InitializeOnWorkerThread(AcceptLanguagesWatcher*) override {} + WebURLLoaderFactory* GetURLLoaderFactory() override { + return &fake_web_url_loader_factory_; + } + std::unique_ptr<WebURLLoaderFactory> WrapURLLoaderFactory( + mojo::ScopedMessagePipeHandle url_loader_factory_handle) override { + return nullptr; + } + void WillSendRequest(WebURLRequest&) override {} + mojom::ControllerServiceWorkerMode IsControlledByServiceWorker() + const override { + return mojom::ControllerServiceWorkerMode::kNoController; + } + WebURL SiteForCookies() const override { return WebURL(); } + base::Optional<WebSecurityOrigin> TopFrameOrigin() const override { + return base::Optional<WebSecurityOrigin>(); + } + WebString GetAcceptLanguages() const override { return WebString(); } + + private: + FakeWebURLLoaderFactory fake_web_url_loader_factory_; +}; + +class MockServiceWorkerContextClient final + : public WebServiceWorkerContextClient { public: MockServiceWorkerContextClient() = default; ~MockServiceWorkerContextClient() override = default; @@ -78,6 +159,14 @@ // message. proxy->ReadyToEvaluateScript(); } + + void FailedToLoadClassicScript() override { + // off-main-script fetch: + // In production code, calling FailedToLoadClassicScript results in + // terminating the worker. + classic_script_load_failure_event_.Signal(); + } + void DidEvaluateScript(bool /* success */) override { script_evaluated_event_.Signal(); } @@ -86,14 +175,26 @@ CreateServiceWorkerNetworkProviderOnMainThread() override { return std::make_unique<FakeServiceWorkerNetworkProvider>(); } + + scoped_refptr<WebWorkerFetchContext> + CreateServiceWorkerFetchContextOnMainThread( + WebServiceWorkerNetworkProvider* network_provider) override { + return base::MakeRefCounted<FakeWebWorkerFetchContext>(); + } + void WorkerContextDestroyed() override { termination_event_.Signal(); } + // These methods must be called on the main thread. void WaitUntilScriptEvaluated() { script_evaluated_event_.Wait(); } void WaitUntilThreadTermination() { termination_event_.Wait(); } + void WaitUntilFailedToLoadClassicScript() { + classic_script_load_failure_event_.Wait(); + } private: base::WaitableEvent script_evaluated_event_; base::WaitableEvent termination_event_; + base::WaitableEvent classic_script_load_failure_event_; }; class MockServiceWorkerInstalledScriptsManager @@ -164,6 +265,10 @@ } // namespace TEST_F(WebEmbeddedWorkerImplTest, TerminateSoonAfterStart) { + base::test::ScopedFeatureList scoped_list; + scoped_list.InitAndDisableFeature( + features::kOffMainThreadServiceWorkerScriptFetch); + EXPECT_CALL(*mock_client_, WorkerReadyForInspectionOnMainThread()).Times(1); worker_->StartWorkerContext(start_data_); testing::Mock::VerifyAndClearExpectations(mock_client_); @@ -173,7 +278,25 @@ testing::Mock::VerifyAndClearExpectations(mock_client_); } +TEST_F(WebEmbeddedWorkerImplTest, TerminateSoonAfterStart_OMT_Fetch) { + base::test::ScopedFeatureList scoped_list; + scoped_list.InitAndEnableFeature( + features::kOffMainThreadServiceWorkerScriptFetch); + + EXPECT_CALL(*mock_client_, WorkerReadyForInspectionOnMainThread()).Times(1); + worker_->StartWorkerContext(start_data_); + testing::Mock::VerifyAndClearExpectations(mock_client_); + + worker_->TerminateWorkerContext(); + // The worker thread was started. Wait for shutdown tasks to finish. + worker_->WaitForShutdownForTesting(); +} + TEST_F(WebEmbeddedWorkerImplTest, TerminateWhileWaitingForDebugger) { + base::test::ScopedFeatureList scoped_list; + scoped_list.InitAndDisableFeature( + features::kOffMainThreadServiceWorkerScriptFetch); + EXPECT_CALL(*mock_client_, WorkerReadyForInspectionOnMainThread()).Times(1); start_data_.wait_for_debugger_mode = WebEmbeddedWorkerStartData::kWaitForDebugger; @@ -185,7 +308,26 @@ testing::Mock::VerifyAndClearExpectations(mock_client_); } +TEST_F(WebEmbeddedWorkerImplTest, TerminateWhileWaitingForDebugger_OMT_Fetch) { + base::test::ScopedFeatureList scoped_list; + scoped_list.InitAndEnableFeature( + features::kOffMainThreadServiceWorkerScriptFetch); + + EXPECT_CALL(*mock_client_, WorkerReadyForInspectionOnMainThread()).Times(1); + start_data_.wait_for_debugger_mode = + WebEmbeddedWorkerStartData::kWaitForDebugger; + worker_->StartWorkerContext(start_data_); + testing::Mock::VerifyAndClearExpectations(mock_client_); + + worker_->TerminateWorkerContext(); + // The worker thread isn't started yet so we don't have to wait for shutdown. +} + TEST_F(WebEmbeddedWorkerImplTest, TerminateWhileLoadingScript) { + base::test::ScopedFeatureList scoped_list; + scoped_list.InitAndDisableFeature( + features::kOffMainThreadServiceWorkerScriptFetch); + // Load the shadow page. EXPECT_CALL(*mock_client_, WorkerReadyForInspectionOnMainThread()).Times(1); EXPECT_CALL(*mock_installed_scripts_manager_, @@ -202,7 +344,36 @@ testing::Mock::VerifyAndClearExpectations(mock_client_); } +TEST_F(WebEmbeddedWorkerImplTest, TerminateWhileLoadingScript_OMT_Fetch) { + base::test::ScopedFeatureList scoped_list; + scoped_list.InitAndEnableFeature( + features::kOffMainThreadServiceWorkerScriptFetch); + + // Load the shadow page. + EXPECT_CALL(*mock_client_, WorkerReadyForInspectionOnMainThread()).Times(1); + EXPECT_CALL(*mock_installed_scripts_manager_, + IsScriptInstalled(KURL(start_data_.script_url))) + .Times(testing::AtLeast(1)) + .WillRepeatedly(testing::Return(false)); + worker_->StartWorkerContext(start_data_); + testing::Mock::VerifyAndClearExpectations(mock_client_); + testing::Mock::VerifyAndClearExpectations(mock_installed_scripts_manager_); + + // Terminate before finishing the script load. + worker_->TerminateWorkerContext(); + // The worker thread was started. Wait for shutdown tasks to finish. + worker_->WaitForShutdownForTesting(); +} + +// Tests terminating worker context between script download and execution. +// No "OMT_Fetch" variant for this test because "pause after download" doesn't +// have effect for off-main-thread script fetch. When off-main-thread fetch +// is on, pausing/resuming is handled in ServiceWorkerGlobalScope. TEST_F(WebEmbeddedWorkerImplTest, TerminateWhilePausedAfterDownload) { + base::test::ScopedFeatureList scoped_list; + scoped_list.InitAndDisableFeature( + features::kOffMainThreadServiceWorkerScriptFetch); + // Load the shadow page. start_data_.pause_after_download_mode = WebEmbeddedWorkerStartData::kPauseAfterDownload; @@ -227,9 +398,12 @@ } TEST_F(WebEmbeddedWorkerImplTest, ScriptNotFound) { + base::test::ScopedFeatureList scoped_list; + scoped_list.InitAndDisableFeature( + features::kOffMainThreadServiceWorkerScriptFetch); + // Load the shadow page. - WebURL script_url = - url_test_helpers::ToKURL("https://www.example.com/sw-404.js"); + WebURL script_url = url_test_helpers::ToKURL(kNotFoundScriptURL); WebURLResponse response; response.SetMimeType("text/javascript"); response.SetHttpStatusCode(404); @@ -253,14 +427,51 @@ testing::Mock::VerifyAndClearExpectations(mock_client_); } +TEST_F(WebEmbeddedWorkerImplTest, ScriptNotFound_OMT_Fetch) { + base::test::ScopedFeatureList scoped_list; + scoped_list.InitAndEnableFeature( + features::kOffMainThreadServiceWorkerScriptFetch); + + // Load the shadow page. + WebURL script_url = url_test_helpers::ToKURL(kNotFoundScriptURL); + WebURLResponse response; + response.SetMimeType("text/javascript"); + response.SetHttpStatusCode(404); + ResourceError error = ResourceError::Failure(script_url); + Platform::Current()->GetURLLoaderMockFactory()->RegisterErrorURL( + script_url, response, error); + start_data_.script_url = script_url; + EXPECT_CALL(*mock_client_, WorkerReadyForInspectionOnMainThread()).Times(1); + EXPECT_CALL(*mock_installed_scripts_manager_, + IsScriptInstalled(KURL(start_data_.script_url))) + .Times(testing::AtLeast(1)) + .WillRepeatedly(testing::Return(false)); + // Start worker and load the script. + worker_->StartWorkerContext(start_data_); + testing::Mock::VerifyAndClearExpectations(mock_client_); + testing::Mock::VerifyAndClearExpectations(mock_installed_scripts_manager_); + + mock_client_->WaitUntilFailedToLoadClassicScript(); + + // The worker thread was started. Ask to shutdown and wait for shutdown + // tasks to finish. + worker_->TerminateWorkerContext(); + worker_->WaitForShutdownForTesting(); +} + // The running worker is detected as a memory leak. crbug.com/586897 and // crbug.com/807754. +// No "OMT_Fetch" variant. See comments on TerminateWhilePausedAfterDownload. #if defined(ADDRESS_SANITIZER) #define MAYBE_DontPauseAfterDownload DISABLED_DontPauseAfterDownload #else #define MAYBE_DontPauseAfterDownload DontPauseAfterDownload #endif TEST_F(WebEmbeddedWorkerImplTest, MAYBE_DontPauseAfterDownload) { + base::test::ScopedFeatureList scoped_list; + scoped_list.InitAndDisableFeature( + features::kOffMainThreadServiceWorkerScriptFetch); + // Load the shadow page. EXPECT_CALL(*mock_client_, WorkerReadyForInspectionOnMainThread()).Times(1); EXPECT_CALL(*mock_installed_scripts_manager_, @@ -291,12 +502,17 @@ // The running worker is detected as a memory leak. crbug.com/586897 and // crbug.com/807754. +// No "OMT_Fetch" variant. See comments on TerminateWhilePausedAfterDownload. #if defined(ADDRESS_SANITIZER) #define MAYBE_PauseAfterDownload DISABLED_PauseAfterDownload #else #define MAYBE_PauseAfterDownload PauseAfterDownload #endif TEST_F(WebEmbeddedWorkerImplTest, MAYBE_PauseAfterDownload) { + base::test::ScopedFeatureList scoped_list; + scoped_list.InitAndDisableFeature( + features::kOffMainThreadServiceWorkerScriptFetch); + // Load the shadow page. EXPECT_CALL(*mock_client_, WorkerReadyForInspectionOnMainThread()).Times(1); EXPECT_CALL(*mock_installed_scripts_manager_,
diff --git a/third_party/blink/renderer/modules/webgl/angle_instanced_arrays.cc b/third_party/blink/renderer/modules/webgl/angle_instanced_arrays.cc index 29f14d52..d71f56d 100644 --- a/third_party/blink/renderer/modules/webgl/angle_instanced_arrays.cc +++ b/third_party/blink/renderer/modules/webgl/angle_instanced_arrays.cc
@@ -72,7 +72,7 @@ void ANGLEInstancedArrays::drawElementsInstancedANGLE(GLenum mode, GLsizei count, GLenum type, - long long offset, + int64_t offset, GLsizei primcount) { WebGLExtensionScopedContext scoped(this); if (scoped.IsLost())
diff --git a/third_party/blink/renderer/modules/webgl/angle_instanced_arrays.h b/third_party/blink/renderer/modules/webgl/angle_instanced_arrays.h index 859a34a..969bf15 100644 --- a/third_party/blink/renderer/modules/webgl/angle_instanced_arrays.h +++ b/third_party/blink/renderer/modules/webgl/angle_instanced_arrays.h
@@ -55,7 +55,7 @@ void drawElementsInstancedANGLE(GLenum mode, GLsizei count, GLenum type, - long long offset, + int64_t offset, GLsizei primcount); void vertexAttribDivisorANGLE(GLuint index, GLuint divisor); };
diff --git a/third_party/blink/renderer/modules/webgl/webgl2_rendering_context_base.cc b/third_party/blink/renderer/modules/webgl/webgl2_rendering_context_base.cc index f95cbea7..25ea271 100644 --- a/third_party/blink/renderer/modules/webgl/webgl2_rendering_context_base.cc +++ b/third_party/blink/renderer/modules/webgl/webgl2_rendering_context_base.cc
@@ -43,26 +43,26 @@ // TODO(kainino): Change outByteLength to GLuint and change the associated // range checking (and all uses) - overflow becomes possible in cases below bool ValidateSubSourceAndGetData(DOMArrayBufferView* view, - long long sub_offset, - long long sub_length, + int64_t sub_offset, + int64_t sub_length, void** out_base_address, - long long* out_byte_length) { + int64_t* out_byte_length) { // This is guaranteed to be non-null by DOM. DCHECK(view); size_t type_size = view->TypeSize(); DCHECK_GE(8u, type_size); - long long byte_length = 0; + int64_t byte_length = 0; if (sub_length) { // type size is at most 8, so no overflow. byte_length = sub_length * type_size; } - long long byte_offset = 0; + int64_t byte_offset = 0; if (sub_offset) { // type size is at most 8, so no overflow. byte_offset = sub_offset * type_size; } - base::CheckedNumeric<long long> total = byte_offset; + base::CheckedNumeric<int64_t> total = byte_offset; total += byte_length; if (!total.IsValid() || total.ValueOrDie() > view->byteLength()) { return false; @@ -238,7 +238,7 @@ if (isContextLost()) return; void* sub_base_address = nullptr; - long long sub_byte_length = 0; + int64_t sub_byte_length = 0; if (!ValidateSubSourceAndGetData(src_data.View(), src_offset, length, &sub_base_address, &sub_byte_length)) { SynthesizeGLError(GL_INVALID_VALUE, "bufferData", @@ -250,7 +250,7 @@ } void WebGL2RenderingContextBase::bufferData(GLenum target, - long long size, + int64_t size, GLenum usage) { WebGLRenderingContextBase::bufferData(target, size, usage); } @@ -270,14 +270,14 @@ void WebGL2RenderingContextBase::bufferSubData( GLenum target, - long long dst_byte_offset, + int64_t dst_byte_offset, MaybeShared<DOMArrayBufferView> src_data, GLuint src_offset, GLuint length) { if (isContextLost()) return; void* sub_base_address = nullptr; - long long sub_byte_length = 0; + int64_t sub_byte_length = 0; if (!ValidateSubSourceAndGetData(src_data.View(), src_offset, length, &sub_base_address, &sub_byte_length)) { SynthesizeGLError(GL_INVALID_VALUE, "bufferSubData", @@ -289,23 +289,23 @@ } void WebGL2RenderingContextBase::bufferSubData(GLenum target, - long long offset, + int64_t offset, DOMArrayBuffer* data) { WebGLRenderingContextBase::bufferSubData(target, offset, data); } void WebGL2RenderingContextBase::bufferSubData( GLenum target, - long long offset, + int64_t offset, const FlexibleArrayBufferView& data) { WebGLRenderingContextBase::bufferSubData(target, offset, data); } void WebGL2RenderingContextBase::copyBufferSubData(GLenum read_target, GLenum write_target, - long long read_offset, - long long write_offset, - long long size) { + int64_t read_offset, + int64_t write_offset, + int64_t size) { if (isContextLost()) return; @@ -353,13 +353,13 @@ void WebGL2RenderingContextBase::getBufferSubData( GLenum target, - long long src_byte_offset, + int64_t src_byte_offset, MaybeShared<DOMArrayBufferView> dst_data, GLuint dst_offset, GLuint length) { WebGLBuffer* source_buffer = nullptr; void* destination_data_ptr = nullptr; - long long destination_byte_length = 0; + int64_t destination_byte_length = 0; const char* message = ValidateGetBufferSubData( __FUNCTION__, target, src_byte_offset, dst_data.View(), dst_offset, length, &source_buffer, &destination_data_ptr, &destination_byte_length); @@ -760,7 +760,7 @@ GLenum format, GLenum type, MaybeShared<DOMArrayBufferView> pixels, - long long offset) { + int64_t offset) { if (isContextLost()) return; if (bound_pixel_pack_buffer_.Get()) { @@ -778,7 +778,7 @@ GLsizei height, GLenum format, GLenum type, - long long offset) { + int64_t offset) { if (isContextLost()) return; @@ -804,7 +804,7 @@ return; } - long long size = buffer->GetSize() - offset; + int64_t size = buffer->GetSize() - offset; // If size is negative, or size is not large enough to store pixels, those // cases are handled by validateReadPixelsFuncParameters to generate // INVALID_OPERATION. @@ -1060,7 +1060,7 @@ GLint border, GLenum format, GLenum type, - long long offset) { + int64_t offset) { if (isContextLost()) return; if (!ValidateTexture2DBinding("texImage2D", target)) @@ -1096,7 +1096,7 @@ GLsizei height, GLenum format, GLenum type, - long long offset) { + int64_t offset) { if (isContextLost()) return; if (!ValidateTexture2DBinding("texSubImage2D", target)) @@ -1745,7 +1745,7 @@ GLint border, GLenum format, GLenum type, - long long offset) { + int64_t offset) { if (isContextLost()) return; if (!ValidateTexture3DBinding("texImage3D", target)) @@ -1942,7 +1942,7 @@ GLsizei depth, GLenum format, GLenum type, - long long offset) { + int64_t offset) { if (isContextLost()) return; if (!ValidateTexture3DBinding("texSubImage3D", target)) @@ -2197,7 +2197,7 @@ GLsizei height, GLint border, GLsizei image_size, - long long offset) { + int64_t offset) { if (isContextLost()) return; if (!bound_pixel_unpack_buffer_) { @@ -2279,7 +2279,7 @@ GLsizei height, GLenum format, GLsizei image_size, - long long offset) { + int64_t offset) { if (isContextLost()) return; if (!bound_pixel_unpack_buffer_) { @@ -2341,7 +2341,7 @@ GLsizei depth, GLint border, GLsizei image_size, - long long offset) { + int64_t offset) { if (isContextLost()) return; if (!bound_pixel_unpack_buffer_) { @@ -2407,7 +2407,7 @@ GLsizei depth, GLenum format, GLsizei image_size, - long long offset) { + int64_t offset) { if (isContextLost()) return; if (!bound_pixel_unpack_buffer_) { @@ -3382,7 +3382,7 @@ GLint size, GLenum type, GLsizei stride, - long long offset) { + int64_t offset) { if (isContextLost()) return; if (index >= max_vertex_attribs_) { @@ -3442,7 +3442,7 @@ void WebGL2RenderingContextBase::drawElementsInstanced(GLenum mode, GLsizei count, GLenum type, - long long offset, + int64_t offset, GLsizei instance_count) { if (!ValidateDrawElements("drawElementsInstanced", type, offset)) return; @@ -3466,7 +3466,7 @@ GLuint end, GLsizei count, GLenum type, - long long offset) { + int64_t offset) { if (!ValidateDrawElements("drawRangeElements", type, offset)) return; @@ -4615,8 +4615,8 @@ void WebGL2RenderingContextBase::bindBufferRange(GLenum target, GLuint index, WebGLBuffer* buffer, - long long offset, - long long size) { + int64_t offset, + int64_t size) { if (isContextLost()) return; if (!ValidateNullableWebGLObject("bindBufferRange", buffer)) @@ -5975,13 +5975,13 @@ const char* WebGL2RenderingContextBase::ValidateGetBufferSubData( const char* function_name, GLenum target, - long long source_byte_offset, + int64_t source_byte_offset, DOMArrayBufferView* destination_array_buffer_view, GLuint destination_offset, GLuint length, WebGLBuffer** out_source_buffer, void** out_destination_data_ptr, - long long* out_destination_byte_length) { + int64_t* out_destination_byte_length) { if (isContextLost()) { return "Context lost"; } @@ -6017,8 +6017,8 @@ const char* function_name, WebGLBuffer* source_buffer, GLintptr source_byte_offset, - long long destination_byte_length) { - base::CheckedNumeric<long long> src_end = source_byte_offset; + int64_t destination_byte_length) { + base::CheckedNumeric<int64_t> src_end = source_byte_offset; src_end += destination_byte_length; if (!src_end.IsValid() || src_end.ValueOrDie() > source_buffer->GetSize()) { SynthesizeGLError(GL_INVALID_VALUE, function_name,
diff --git a/third_party/blink/renderer/modules/webgl/webgl2_rendering_context_base.h b/third_party/blink/renderer/modules/webgl/webgl2_rendering_context_base.h index b5f58d7..e704910a 100644 --- a/third_party/blink/renderer/modules/webgl/webgl2_rendering_context_base.h +++ b/third_party/blink/renderer/modules/webgl/webgl2_rendering_context_base.h
@@ -35,26 +35,26 @@ GLuint, GLuint); void bufferSubData(GLenum, - long long offset, + int64_t offset, MaybeShared<DOMArrayBufferView>, GLuint, GLuint); // Have to re-declare/re-define the following buffer{Sub}Data functions from // base class. This is because the above buffer{Sub}Data() hides the name // from base class. - void bufferData(GLenum target, long long size, GLenum usage); + void bufferData(GLenum target, int64_t size, GLenum usage); void bufferData(GLenum target, DOMArrayBuffer* data, GLenum usage); void bufferData(GLenum target, MaybeShared<DOMArrayBufferView> data, GLenum usage); - void bufferSubData(GLenum target, long long offset, DOMArrayBuffer* data); + void bufferSubData(GLenum target, int64_t offset, DOMArrayBuffer* data); void bufferSubData(GLenum target, - long long offset, + int64_t offset, const FlexibleArrayBufferView& data); - void copyBufferSubData(GLenum, GLenum, long long, long long, long long); + void copyBufferSubData(GLenum, GLenum, int64_t, int64_t, int64_t); void getBufferSubData(GLenum, - long long, + int64_t, MaybeShared<DOMArrayBufferView>, GLuint, GLuint); @@ -98,7 +98,7 @@ GLint, GLenum, GLenum, - long long); + int64_t); void texImage2D(GLenum, GLint, GLint, @@ -170,7 +170,7 @@ GLsizei, GLenum, GLenum, - long long); + int64_t); void texSubImage2D(GLenum, GLint, GLint, @@ -395,7 +395,7 @@ GLint, GLenum, GLenum, - long long); + int64_t); void texSubImage3D(GLenum, GLint, GLint, @@ -418,7 +418,7 @@ GLsizei, GLenum, GLenum, - long long); + int64_t); void texSubImage3D(GLenum, GLint, GLint, @@ -559,7 +559,7 @@ GLsizei height, GLint border, GLsizei image_size, - long long offset); + int64_t offset); void compressedTexSubImage2D(GLenum target, GLint level, GLint xoffset, @@ -568,7 +568,7 @@ GLsizei height, GLenum format, GLsizei image_size, - long long offset); + int64_t offset); void compressedTexImage3D(GLenum target, GLint level, GLenum internalformat, @@ -577,7 +577,7 @@ GLsizei depth, GLint border, GLsizei image_size, - long long offset); + int64_t offset); void compressedTexSubImage3D(GLenum target, GLint level, GLint xoffset, @@ -588,7 +588,7 @@ GLsizei depth, GLenum format, GLsizei image_size, - long long offset); + int64_t offset); // Have to re-declare/re-define the following compressedTex{Sub}Image2D // functions from the base class. This is because the above @@ -839,18 +839,18 @@ GLint size, GLenum type, GLsizei stride, - long long offset); + int64_t offset); /* Writing to the drawing buffer */ void vertexAttribDivisor(GLuint, GLuint); void drawArraysInstanced(GLenum, GLint, GLsizei, GLsizei); - void drawElementsInstanced(GLenum, GLsizei, GLenum, long long, GLsizei); + void drawElementsInstanced(GLenum, GLsizei, GLenum, int64_t, GLsizei); void drawRangeElements(GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, - long long offset); + int64_t offset); /* Multiple Render Targets */ void drawBuffers(const Vector<GLenum>&); @@ -907,7 +907,7 @@ /* Uniform Buffer Objects and Transform Feedback Buffers */ void bindBufferBase(GLenum, GLuint, WebGLBuffer*); - void bindBufferRange(GLenum, GLuint, WebGLBuffer*, long long, long long); + void bindBufferRange(GLenum, GLuint, WebGLBuffer*, int64_t, int64_t); ScriptValue getIndexedParameter(ScriptState*, GLenum, GLuint); Vector<GLuint> getUniformIndices(WebGLProgram*, const Vector<String>&); ScriptValue getActiveUniforms(ScriptState*, @@ -936,14 +936,14 @@ GLenum format, GLenum type, MaybeShared<DOMArrayBufferView> pixels, - long long offset); + int64_t offset); void readPixels(GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, - long long offset); + int64_t offset); /* WebGLRenderingContextBase overrides */ void InitializeNewContext() override; @@ -1088,17 +1088,17 @@ const char* ValidateGetBufferSubData(const char* function_name, GLenum target, - long long source_byte_offset, + int64_t source_byte_offset, DOMArrayBufferView*, GLuint destination_offset, GLuint length, WebGLBuffer**, void** out_destination_data_ptr, - long long* out_destination_byte_length); + int64_t* out_destination_byte_length); const char* ValidateGetBufferSubDataBounds(const char* function_name, WebGLBuffer*, GLintptr source_byte_offset, - long long destination_byte_length); + int64_t destination_byte_length); void RemoveBoundBuffer(WebGLBuffer*) override;
diff --git a/third_party/blink/renderer/modules/webgl/webgl_buffer.h b/third_party/blink/renderer/modules/webgl/webgl_buffer.h index c0c495ac..f5328b34 100644 --- a/third_party/blink/renderer/modules/webgl/webgl_buffer.h +++ b/third_party/blink/renderer/modules/webgl/webgl_buffer.h
@@ -44,8 +44,8 @@ bool HasEverBeenBound() const { return Object() && initial_target_; } - void SetSize(long long size) { size_ = size; } - long long GetSize() const { return size_; } + void SetSize(int64_t size) { size_ = size; } + int64_t GetSize() const { return size_; } protected: void DeleteObjectImpl(gpu::gles2::GLES2Interface*) override; @@ -54,7 +54,7 @@ bool IsBuffer() const override { return true; } GLenum initial_target_; - long long size_; + int64_t size_; }; } // namespace blink
diff --git a/third_party/blink/renderer/modules/webgl/webgl_rendering_context_base.cc b/third_party/blink/renderer/modules/webgl/webgl_rendering_context_base.cc index b306ebb3..f07db7c 100644 --- a/third_party/blink/renderer/modules/webgl/webgl_rendering_context_base.cc +++ b/third_party/blink/renderer/modules/webgl/webgl_rendering_context_base.cc
@@ -1906,7 +1906,7 @@ } void WebGLRenderingContextBase::BufferDataImpl(GLenum target, - long long size, + int64_t size, const void* data, GLenum usage) { WebGLBuffer* buffer = ValidateBufferDataTarget("bufferData", target); @@ -1925,7 +1925,7 @@ } void WebGLRenderingContextBase::bufferData(GLenum target, - long long size, + int64_t size, GLenum usage) { if (isContextLost()) return; @@ -1955,7 +1955,7 @@ } void WebGLRenderingContextBase::BufferSubDataImpl(GLenum target, - long long offset, + int64_t offset, GLsizeiptr size, const void* data) { WebGLBuffer* buffer = ValidateBufferDataTarget("bufferSubData", target); @@ -1965,7 +1965,7 @@ return; if (!data) return; - if (offset + static_cast<long long>(size) > buffer->GetSize()) { + if (offset + static_cast<int64_t>(size) > buffer->GetSize()) { SynthesizeGLError(GL_INVALID_VALUE, "bufferSubData", "buffer overflow"); return; } @@ -1974,7 +1974,7 @@ } void WebGLRenderingContextBase::bufferSubData(GLenum target, - long long offset, + int64_t offset, DOMArrayBuffer* data) { if (isContextLost()) return; @@ -1984,7 +1984,7 @@ void WebGLRenderingContextBase::bufferSubData( GLenum target, - long long offset, + int64_t offset, const FlexibleArrayBufferView& data) { if (isContextLost()) return; @@ -2593,7 +2593,7 @@ void WebGLRenderingContextBase::drawElements(GLenum mode, GLsizei count, GLenum type, - long long offset) { + int64_t offset) { if (!ValidateDrawElements("drawElements", type, offset)) return; @@ -2633,7 +2633,7 @@ void WebGLRenderingContextBase::DrawElementsInstancedANGLE(GLenum mode, GLsizei count, GLenum type, - long long offset, + int64_t offset, GLsizei primcount) { if (!ValidateDrawElements("drawElementsInstancedANGLE", type, offset)) return; @@ -4013,15 +4013,15 @@ } } -long long WebGLRenderingContextBase::getVertexAttribOffset(GLuint index, - GLenum pname) { +int64_t WebGLRenderingContextBase::getVertexAttribOffset(GLuint index, + GLenum pname) { if (isContextLost()) return 0; GLvoid* result = nullptr; // NOTE: If pname is ever a value that returns more than 1 element // this will corrupt memory. ContextGL()->GetVertexAttribPointerv(index, pname, &result); - return static_cast<long long>(reinterpret_cast<intptr_t>(result)); + return static_cast<int64_t>(reinterpret_cast<intptr_t>(result)); } void WebGLRenderingContextBase::hint(GLenum target, GLenum mode) { @@ -4306,7 +4306,7 @@ GLenum format, GLenum type, DOMArrayBufferView* buffer, - long long buffer_size) { + int64_t buffer_size) { if (!ValidateReadPixelsFormatAndType(format, type, buffer)) return false; @@ -4320,7 +4320,7 @@ return false; } if (buffer_size < - static_cast<long long>(total_bytes_required + total_skip_bytes)) { + static_cast<int64_t>(total_bytes_required + total_skip_bytes)) { SynthesizeGLError(GL_INVALID_OPERATION, "readPixels", "buffer is not large enough for dimensions"); return false; @@ -4346,7 +4346,7 @@ GLenum format, GLenum type, DOMArrayBufferView* pixels, - long long offset) { + int64_t offset) { if (isContextLost()) return; // Due to WebGL's same-origin restrictions, it is not possible to @@ -4772,14 +4772,14 @@ bool WebGLRenderingContextBase::ValidateValueFitNonNegInt32( const char* function_name, const char* param_name, - long long value) { + int64_t value) { if (value < 0) { String error_msg = String(param_name) + " < 0"; SynthesizeGLError(GL_INVALID_VALUE, function_name, error_msg.Ascii().data()); return false; } - if (value > static_cast<long long>(std::numeric_limits<int>::max())) { + if (value > static_cast<int64_t>(std::numeric_limits<int>::max())) { String error_msg = String(param_name) + " more than 32-bit"; SynthesizeGLError(GL_INVALID_OPERATION, function_name, error_msg.Ascii().data()); @@ -6433,7 +6433,7 @@ GLenum type, GLboolean normalized, GLsizei stride, - long long offset) { + int64_t offset) { if (isContextLost()) return; if (index >= max_vertex_attribs_) { @@ -7679,7 +7679,7 @@ bool WebGLRenderingContextBase::ValidateDrawElements(const char* function_name, GLenum type, - long long offset) { + int64_t offset) { if (isContextLost()) return false;
diff --git a/third_party/blink/renderer/modules/webgl/webgl_rendering_context_base.h b/third_party/blink/renderer/modules/webgl/webgl_rendering_context_base.h index ac4c82b..f0b7867 100644 --- a/third_party/blink/renderer/modules/webgl/webgl_rendering_context_base.h +++ b/third_party/blink/renderer/modules/webgl/webgl_rendering_context_base.h
@@ -168,14 +168,14 @@ GLenum src_alpha, GLenum dst_alpha); - void bufferData(GLenum target, long long size, GLenum usage); + void bufferData(GLenum target, int64_t size, GLenum usage); void bufferData(GLenum target, DOMArrayBuffer* data, GLenum usage); void bufferData(GLenum target, MaybeShared<DOMArrayBufferView> data, GLenum usage); - void bufferSubData(GLenum target, long long offset, DOMArrayBuffer* data); + void bufferSubData(GLenum target, int64_t offset, DOMArrayBuffer* data); void bufferSubData(GLenum target, - long long offset, + int64_t offset, const FlexibleArrayBufferView& data); GLenum checkFramebufferStatus(GLenum target); @@ -245,7 +245,7 @@ void disable(GLenum cap); void disableVertexAttribArray(GLuint index); void drawArrays(GLenum mode, GLint first, GLsizei count); - void drawElements(GLenum mode, GLsizei count, GLenum type, long long offset); + void drawElements(GLenum mode, GLsizei count, GLenum type, int64_t offset); void DrawArraysInstancedANGLE(GLenum mode, GLint first, @@ -254,7 +254,7 @@ void DrawElementsInstancedANGLE(GLenum mode, GLsizei count, GLenum type, - long long offset, + int64_t offset, GLsizei primcount); void enable(GLenum cap); @@ -307,7 +307,7 @@ const WebGLUniformLocation*); WebGLUniformLocation* getUniformLocation(WebGLProgram*, const String&); ScriptValue getVertexAttrib(ScriptState*, GLuint index, GLenum pname); - long long getVertexAttribOffset(GLuint index, GLenum pname); + int64_t getVertexAttribOffset(GLuint index, GLenum pname); void hint(GLenum target, GLenum mode); GLboolean isBuffer(WebGLBuffer*); @@ -517,7 +517,7 @@ GLenum type, GLboolean normalized, GLsizei stride, - long long offset); + int64_t offset); void VertexAttribDivisorANGLE(GLuint index, GLuint divisor); @@ -1257,7 +1257,7 @@ GLenum format, GLenum type, DOMArrayBufferView*, - long long buffer_size); + int64_t buffer_size); virtual GLint GetMaxTextureLevelForTarget(GLenum target); @@ -1271,7 +1271,7 @@ // a 32-bit integer. Generates GL error and returns false if not. bool ValidateValueFitNonNegInt32(const char* function_name, const char* param_name, - long long value); + int64_t value); enum TexFuncValidationSourceType { kSourceArrayBufferView, @@ -1493,18 +1493,18 @@ // Helper function to validate drawElements(Instanced) calls bool ValidateDrawElements(const char* function_name, GLenum type, - long long offset); + int64_t offset); // State updates and operations necessary before or at draw call time. virtual void OnBeforeDrawCall(); // Helper functions to bufferData() and bufferSubData(). void BufferDataImpl(GLenum target, - long long size, + int64_t size, const void* data, GLenum usage); void BufferSubDataImpl(GLenum target, - long long offset, + int64_t offset, GLsizeiptr, const void* data); @@ -1684,7 +1684,7 @@ GLenum format, GLenum type, DOMArrayBufferView* pixels, - long long offset); + int64_t offset); private: WebGLRenderingContextBase(CanvasRenderingContextHost*,
diff --git a/third_party/blink/renderer/modules/webmidi/midi_output.cc b/third_party/blink/renderer/modules/webmidi/midi_output.cc index bb08257..fb99683 100644 --- a/third_party/blink/renderer/modules/webmidi/midi_output.cc +++ b/third_party/blink/renderer/modules/webmidi/midi_output.cc
@@ -219,7 +219,7 @@ String GetPositionString() { return "at index " + String::Number(offset_) + " (" + - String::Number(data_[offset_]) + ")."; + String::Number(static_cast<uint16_t>(data_[offset_])) + ")."; } const unsigned char* data_;
diff --git a/third_party/blink/renderer/platform/BUILD.gn b/third_party/blink/renderer/platform/BUILD.gn index c09297c..256f726a 100644 --- a/third_party/blink/renderer/platform/BUILD.gn +++ b/third_party/blink/renderer/platform/BUILD.gn
@@ -1817,7 +1817,7 @@ if (is_win) { sources += [ "text/locale_win_test.cc" ] } else if (is_mac) { - sources += [ "text/locale_mac_test.cc" ] + sources += [ "text/locale_mac_test.mm" ] } else if (is_posix || is_fuchsia) { sources += [ "text/locale_icu_test.cc" ] }
diff --git a/third_party/blink/renderer/platform/fonts/shaping/shape_result.cc b/third_party/blink/renderer/platform/fonts/shaping/shape_result.cc index 155408d..742d52a 100644 --- a/third_party/blink/renderer/platform/fonts/shaping/shape_result.cc +++ b/third_party/blink/renderer/platform/fonts/shaping/shape_result.cc
@@ -1590,7 +1590,7 @@ output->Append(", #chars="); output->AppendNumber(run.num_characters_); output->Append(", dir="); - output->AppendNumber(run.direction_); + output->AppendNumber(static_cast<uint32_t>(run.direction_)); output->Append(", glyphs["); output->AppendNumber(run.glyph_data_.size()); output->Append("]{");
diff --git a/third_party/blink/renderer/platform/loader/fetch/raw_resource.cc b/third_party/blink/renderer/platform/loader/fetch/raw_resource.cc index e1fc5f7..33fc681 100644 --- a/third_party/blink/renderer/platform/loader/fetch/raw_resource.cc +++ b/third_party/blink/renderer/platform/loader/fetch/raw_resource.cc
@@ -199,11 +199,11 @@ if (matched_with_non_streaming_destination_) { // In this case, the client needs individual chunks so we need // PreloadBytesConsumerClient for the translation. - auto* bytes_consumer_client = + auto* preload_bytes_consumer_client = MakeGarbageCollected<PreloadBytesConsumerClient>( *bytes_consumer_for_preload, *this, *client); - bytes_consumer_for_preload->SetClient(bytes_consumer_client); - bytes_consumer_client->OnStateChange(); + bytes_consumer_for_preload->SetClient(preload_bytes_consumer_client); + preload_bytes_consumer_client->OnStateChange(); } else { // In this case, we can simply pass the BytesConsumer to the client. client->ResponseBodyReceived(this, *bytes_consumer_for_preload); @@ -287,14 +287,12 @@ // The loading was initiated as a preload (hence UseStreamOnResponse is // set), but this resource has been matched with a request without // UseStreamOnResponse set. - auto* bytes_consumer_for_preload = - MakeGarbageCollected<BufferingBytesConsumer>( - &body_loader.DrainAsBytesConsumer()); - auto* bytes_consumer_client = + auto& bytes_consumer_for_preload = body_loader.DrainAsBytesConsumer(); + auto* preload_bytes_consumer_client = MakeGarbageCollected<PreloadBytesConsumerClient>( - *bytes_consumer_for_preload, *this, *client); - bytes_consumer_for_preload->SetClient(bytes_consumer_client); - bytes_consumer_client->OnStateChange(); + bytes_consumer_for_preload, *this, *client); + bytes_consumer_for_preload.SetClient(preload_bytes_consumer_client); + preload_bytes_consumer_client->OnStateChange(); return; }
diff --git a/third_party/blink/renderer/platform/loader/fetch/resource_fetcher.cc b/third_party/blink/renderer/platform/loader/fetch/resource_fetcher.cc index a73a798..10ddb45 100644 --- a/third_party/blink/renderer/platform/loader/fetch/resource_fetcher.cc +++ b/third_party/blink/renderer/platform/loader/fetch/resource_fetcher.cc
@@ -815,15 +815,12 @@ // Indicate whether the network stack can return a stale resource. If a // stale resource is returned a StaleRevalidation request will be scheduled. // Explicitly disallow stale responses for fetchers that don't have SWR - // enabled (via origin trial), non-GET requests and resource requests that - // are raw. We are explicitly excluding RawResources here to avoid - // unintentional SWR, as bugs around RawResources tend to be complicated and - // critical. + // enabled (via origin trial), and non-GET requests. resource_request.SetAllowStaleResponse( (resource_allows_stale_while_revalidate || stale_while_revalidate_enabled_) && resource_request.HttpMethod() == http_names::kGET && - !IsRawResource(resource_type) && !params.IsStaleRevalidation()); + !params.IsStaleRevalidation()); Context().AddAdditionalRequestHeaders(resource_request);
diff --git a/third_party/blink/renderer/platform/loader/fetch/resource_loader.cc b/third_party/blink/renderer/platform/loader/fetch/resource_loader.cc index b68ab6c..b75a11a 100644 --- a/third_party/blink/renderer/platform/loader/fetch/resource_loader.cc +++ b/third_party/blink/renderer/platform/loader/fetch/resource_loader.cc
@@ -478,8 +478,13 @@ response_body_loader_ = MakeGarbageCollected<ResponseBodyLoader>( bytes_consumer, response_body_loader_client, GetLoadingTaskRunner()); resource_->ResponseBodyReceived(*response_body_loader_); - if (!response_body_loader_->IsDrained()) + if (response_body_loader_->IsDrained()) { + // When streaming, unpause virtual time early to prevent deadlocking + // against stream consumer in case stream has backpressure enabled. + resource_->VirtualTimePauser().UnpauseVirtualTime(); + } else { response_body_loader_->Start(); + } } void ResourceLoader::Run() { @@ -499,11 +504,15 @@ const ResourceResponse& response = resource_->GetResponse(); if (deferred_finish_loading_info_) { + // Create a copy to pass a reference. + const std::vector<network::cors::PreflightTimingInfo> + cors_preflight_timing_info = + deferred_finish_loading_info_->cors_preflight_timing_info; DidFinishLoading(deferred_finish_loading_info_->response_end, response.EncodedDataLength(), response.EncodedBodyLength(), response.DecodedBodyLength(), deferred_finish_loading_info_->should_report_corb_blocking, - deferred_finish_loading_info_->cors_preflight_timing_info); + cors_preflight_timing_info); } } @@ -1125,13 +1134,16 @@ resource_->SetEncodedBodyLength(encoded_body_length); resource_->SetDecodedBodyLength(decoded_body_length); - if (data_pipe_completion_notifier_) - data_pipe_completion_notifier_->SignalComplete(); - - if ((response_body_loader_ && !has_seen_end_of_body_) || + if ((response_body_loader_ && !has_seen_end_of_body_ && + !response_body_loader_->IsAborted()) || (is_downloading_to_blob_ && !blob_finished_ && blob_response_started_)) { + // If the body is still being loaded, we defer the completion until all the + // body is received. deferred_finish_loading_info_ = DeferredFinishLoadingInfo{ response_end, should_report_corb_blocking, cors_preflight_timing_info}; + + if (data_pipe_completion_notifier_) + data_pipe_completion_notifier_->SignalComplete(); return; } @@ -1162,9 +1174,6 @@ int64_t decoded_body_length) { const ResourceRequest& request = resource_->GetResourceRequest(); - if (data_pipe_completion_notifier_) - data_pipe_completion_notifier_->SignalError(BytesConsumer::Error()); - if (request.IsAutomaticUpgrade()) { auto recorder = ukm::MojoUkmRecorder::Create(Platform::Current()->GetConnector()); @@ -1179,6 +1188,12 @@ } void ResourceLoader::HandleError(const ResourceError& error) { + if (response_body_loader_) + response_body_loader_->Abort(); + + if (data_pipe_completion_notifier_) + data_pipe_completion_notifier_->SignalError(BytesConsumer::Error()); + if (is_cache_aware_loading_activated_ && error.IsCacheMiss() && Context().ShouldLoadNewResource(resource_->GetType())) { resource_->WillReloadAfterDiskCacheMiss(); @@ -1195,9 +1210,6 @@ resource_->GetType(), resource_->Options().initiator_info.name)); } - if (response_body_loader_) - response_body_loader_->Abort(); - Release(ResourceLoadScheduler::ReleaseOption::kReleaseAndSchedule, ResourceLoadScheduler::TrafficReportHints::InvalidInstance()); loader_.reset(); @@ -1355,6 +1367,12 @@ resource_->GetResponse().IsNull(); } +void ResourceLoader::AbortResponseBodyLoading() { + if (response_body_loader_) { + response_body_loader_->Abort(); + } +} + scoped_refptr<base::SingleThreadTaskRunner> ResourceLoader::GetLoadingTaskRunner() { return fetcher_->GetTaskRunner();
diff --git a/third_party/blink/renderer/platform/loader/fetch/resource_loader.h b/third_party/blink/renderer/platform/loader/fetch/resource_loader.h index 9a0e6458..a90893bd 100644 --- a/third_party/blink/renderer/platform/loader/fetch/resource_loader.h +++ b/third_party/blink/renderer/platform/loader/fetch/resource_loader.h
@@ -103,6 +103,8 @@ ResourceFetcher* Fetcher() { return fetcher_; } bool ShouldBeKeptAliveWhenDetached() const; + void AbortResponseBodyLoading(); + // WebURLLoaderClient // // A succesful load will consist of:
diff --git a/third_party/blink/renderer/platform/loader/fetch/response_body_loader.cc b/third_party/blink/renderer/platform/loader/fetch/response_body_loader.cc index 0cc9ba6..dd14bf1 100644 --- a/third_party/blink/renderer/platform/loader/fetch/response_body_loader.cc +++ b/third_party/blink/renderer/platform/loader/fetch/response_body_loader.cc
@@ -379,7 +379,6 @@ } void ResponseBodyLoader::Abort() { - DCHECK(!suspended_); if (aborted_) return;
diff --git a/third_party/blink/renderer/platform/runtime_enabled_features.json5 b/third_party/blink/renderer/platform/runtime_enabled_features.json5 index a4ef2fe..c839b778 100644 --- a/third_party/blink/renderer/platform/runtime_enabled_features.json5 +++ b/third_party/blink/renderer/platform/runtime_enabled_features.json5
@@ -981,7 +981,12 @@ { name: "OriginTrialsSampleAPIImplied", origin_trial_feature_name: "FrobulateImplied", - implied_by: ["OriginTrialsSampleAPI"], + implied_by: ["OriginTrialsSampleAPI", "OriginTrialsSampleAPIInvalidOS"], + }, + { + name: "OriginTrialsSampleAPIInvalidOS", + origin_trial_feature_name: "FrobulateInvalidOS", + origin_trial_os: ["invalid"], }, { name: "OutOfBlinkCors",
diff --git a/third_party/blink/renderer/platform/scheduler/main_thread/memory_purge_manager.cc b/third_party/blink/renderer/platform/scheduler/main_thread/memory_purge_manager.cc index c537459..eeda5a8d 100644 --- a/third_party/blink/renderer/platform/scheduler/main_thread/memory_purge_manager.cc +++ b/third_party/blink/renderer/platform/scheduler/main_thread/memory_purge_manager.cc
@@ -60,9 +60,7 @@ } bool MemoryPurgeManager::CanPurge() const { - return !base::FeatureList::IsEnabled( - features::kPurgeMemoryOnlyForBackgroundedProcesses) || - renderer_backgrounded_; + return renderer_backgrounded_; } bool MemoryPurgeManager::AreAllPagesFrozen() const {
diff --git a/third_party/blink/renderer/platform/scheduler/main_thread/memory_purge_manager.h b/third_party/blink/renderer/platform/scheduler/main_thread/memory_purge_manager.h index 7f69ba8e..39c9a99 100644 --- a/third_party/blink/renderer/platform/scheduler/main_thread/memory_purge_manager.h +++ b/third_party/blink/renderer/platform/scheduler/main_thread/memory_purge_manager.h
@@ -21,9 +21,8 @@ void OnPageCreated(bool is_frozen); void OnPageDestroyed(bool was_frozen); - // Called when a page is frozen. Simulates a critical memory pressure signal - // to purge memory. If the kPurgeMemoryOnlyForBackgroundedProcesses feature - // is enabled and the renderer is foregrounded, no signal will be sent. + // Called when a page is frozen. If the renderer is backgrounded, sends a + // critical memory pressure signal to purge memory. void OnPageFrozen(); // Called when a page is unfrozen. Has the effect of unsuppressing memory
diff --git a/third_party/blink/renderer/platform/scheduler/main_thread/memory_purge_manager_unittest.cc b/third_party/blink/renderer/platform/scheduler/main_thread/memory_purge_manager_unittest.cc index 475c46e4..ae13213 100644 --- a/third_party/blink/renderer/platform/scheduler/main_thread/memory_purge_manager_unittest.cc +++ b/third_party/blink/renderer/platform/scheduler/main_thread/memory_purge_manager_unittest.cc
@@ -50,15 +50,9 @@ DISALLOW_COPY_AND_ASSIGN(MemoryPurgeManagerTest); }; -// Verify that OnPageFrozen() triggers a memory pressure notification -// in a backgrounded renderer when the kPurgeMemoryOnlyForBackgroundedProcesses -// feature is disabled. -TEST_F(MemoryPurgeManagerTest, PageFrozenBackgrounded) { - base::test::ScopedFeatureList scoped_feature_list; - scoped_feature_list.InitWithFeatures( - {} /* enabled */, - {features::kPurgeMemoryOnlyForBackgroundedProcesses} /* disabled */); - +// Verify that OnPageFrozen() triggers a memory pressure notification in a +// backgrounded renderer. +TEST_F(MemoryPurgeManagerTest, PageFrozenInBackgroundedRenderer) { memory_purge_manager_.OnPageCreated(false /* is_frozen */); memory_purge_manager_.SetRendererBackgrounded(true); memory_purge_manager_.OnPageFrozen(); @@ -66,49 +60,9 @@ MEMORY_PRESSURE_LEVEL_CRITICAL); } -// Verify that OnPageFrozen() triggers a memory pressure notification -// in a foregrounded renderer when the kPurgeMemoryOnlyForBackgroundedProcesses -// feature is disabled. -TEST_F(MemoryPurgeManagerTest, PageFrozenForegrounded) { - base::test::ScopedFeatureList scoped_feature_list; - scoped_feature_list.InitWithFeatures( - {} /* enabled */, - {features::kPurgeMemoryOnlyForBackgroundedProcesses} /* disabled */); - - memory_purge_manager_.OnPageCreated(false /* is_frozen */); - memory_purge_manager_.SetRendererBackgrounded(false); - memory_purge_manager_.OnPageFrozen(); - ExpectMemoryPressure(base::MemoryPressureListener::MemoryPressureLevel:: - MEMORY_PRESSURE_LEVEL_CRITICAL); -} - -// Verify that OnPageFrozen() triggers a memory pressure notification -// in a backgrounded renderer when the kPurgeMemoryOnlyForBackgroundedProcesses -// feature is enabled. -TEST_F(MemoryPurgeManagerTest, - PageFrozenBackgroundedPreventForegroundedRenderer) { - base::test::ScopedFeatureList scoped_feature_list; - scoped_feature_list.InitWithFeatures( - {features::kPurgeMemoryOnlyForBackgroundedProcesses} /* enabled */, - {} /* disabled */); - - memory_purge_manager_.OnPageCreated(false /* is_frozen */); - memory_purge_manager_.SetRendererBackgrounded(true); - memory_purge_manager_.OnPageFrozen(); - ExpectMemoryPressure(base::MemoryPressureListener::MemoryPressureLevel:: - MEMORY_PRESSURE_LEVEL_CRITICAL); -} - -// Verify that OnPageFrozen() does not trigger a memory pressure -// notification in a foregrounded renderer when the -// kPurgeMemoryOnlyForBackgroundedProcesses feature is enabled. -TEST_F(MemoryPurgeManagerTest, - PageFrozenForegroundedPreventForegroundedRenderer) { - base::test::ScopedFeatureList scoped_feature_list; - scoped_feature_list.InitWithFeatures( - {features::kPurgeMemoryOnlyForBackgroundedProcesses} /* enabled */, - {} /* disabled */); - +// Verify that OnPageFrozen() does not trigger a memory pressure notification in +// a foregrounded renderer. +TEST_F(MemoryPurgeManagerTest, PageFrozenInForegroundedRenderer) { memory_purge_manager_.OnPageCreated(false /* is_frozen */); memory_purge_manager_.SetRendererBackgrounded(false); memory_purge_manager_.OnPageFrozen(); @@ -129,6 +83,8 @@ TEST_F(MemoryPurgeManagerTest, PageFrozenMemorySuppressionOnlyWhenAllPagesFrozen) { + memory_purge_manager_.SetRendererBackgrounded(true); + memory_purge_manager_.OnPageCreated(false /* is_frozen */); memory_purge_manager_.OnPageCreated(false /* is_frozen */); memory_purge_manager_.OnPageCreated(false /* is_frozen */);
diff --git a/third_party/blink/renderer/platform/text/DEPS b/third_party/blink/renderer/platform/text/DEPS index 05eb49a63..d3ea245 100644 --- a/third_party/blink/renderer/platform/text/DEPS +++ b/third_party/blink/renderer/platform/text/DEPS
@@ -6,6 +6,7 @@ "+third_party/blink/renderer/platform/text", # Dependencies. + "+base/mac/scoped_nsobject.h", "+third_party/blink/renderer/platform/date_components.h", "+third_party/blink/renderer/platform/heap", "+third_party/blink/renderer/platform/language.h",
diff --git a/third_party/blink/renderer/platform/text/locale_mac.h b/third_party/blink/renderer/platform/text/locale_mac.h index 38268260..f2ec6fe5 100644 --- a/third_party/blink/renderer/platform/text/locale_mac.h +++ b/third_party/blink/renderer/platform/text/locale_mac.h
@@ -32,9 +32,9 @@ #define THIRD_PARTY_BLINK_RENDERER_PLATFORM_TEXT_LOCALE_MAC_H_ #include <memory> +#include "base/mac/scoped_nsobject.h" #include "third_party/blink/renderer/platform/text/platform_locale.h" #include "third_party/blink/renderer/platform/wtf/forward.h" -#include "third_party/blink/renderer/platform/wtf/retain_ptr.h" #include "third_party/blink/renderer/platform/wtf/text/wtf_string.h" #include "third_party/blink/renderer/platform/wtf/vector.h" @@ -69,17 +69,17 @@ private: explicit LocaleMac(NSLocale*); - RetainPtr<NSDateFormatter> ShortDateFormatter(); + base::scoped_nsobject<NSDateFormatter> ShortDateFormatter(); void InitializeLocaleData() override; - RetainPtr<NSLocale> locale_; - RetainPtr<NSCalendar> gregorian_calendar_; + base::scoped_nsobject<NSLocale> locale_; + base::scoped_nsobject<NSCalendar> gregorian_calendar_; Vector<String> week_day_short_labels_; Vector<String> month_labels_; - RetainPtr<NSDateFormatter> TimeFormatter(); - RetainPtr<NSDateFormatter> ShortTimeFormatter(); - RetainPtr<NSDateFormatter> DateTimeFormatterWithSeconds(); - RetainPtr<NSDateFormatter> DateTimeFormatterWithoutSeconds(); + base::scoped_nsobject<NSDateFormatter> TimeFormatter(); + base::scoped_nsobject<NSDateFormatter> ShortTimeFormatter(); + base::scoped_nsobject<NSDateFormatter> DateTimeFormatterWithSeconds(); + base::scoped_nsobject<NSDateFormatter> DateTimeFormatterWithoutSeconds(); String date_format_; String month_format_;
diff --git a/third_party/blink/renderer/platform/text/locale_mac.mm b/third_party/blink/renderer/platform/text/locale_mac.mm index fdd237e..d62484f 100644 --- a/third_party/blink/renderer/platform/text/locale_mac.mm +++ b/third_party/blink/renderer/platform/text/locale_mac.mm
@@ -30,8 +30,11 @@ #include "third_party/blink/renderer/platform/text/locale_mac.h" +#import <Foundation/NSCalendar.h> #import <Foundation/NSDateFormatter.h> #import <Foundation/NSLocale.h> +#import <Foundation/NSNumberFormatter.h> +#import <Foundation/NSTimeZone.h> #include <memory> #include "base/memory/ptr_util.h" @@ -39,7 +42,6 @@ #include "third_party/blink/renderer/platform/language.h" #include "third_party/blink/renderer/platform/web_test_support.h" #include "third_party/blink/renderer/platform/wtf/date_math.h" -#include "third_party/blink/renderer/platform/wtf/retain_ptr.h" #include "third_party/blink/renderer/platform/wtf/text/string_builder.h" namespace blink { @@ -53,25 +55,25 @@ return normalized_locale.Left(separator_position); } -static RetainPtr<NSLocale> DetermineLocale(const String& locale) { +static NSLocale* DetermineLocale(const String& locale) { if (!WebTestSupport::IsRunningWebTest()) { - RetainPtr<NSLocale> current_locale = [NSLocale currentLocale]; + NSLocale* current_locale = [NSLocale currentLocale]; String current_locale_language = - LanguageFromLocale(String([current_locale.Get() localeIdentifier])); + LanguageFromLocale(String([current_locale localeIdentifier])); String locale_language = LanguageFromLocale(locale); if (DeprecatedEqualIgnoringCase(current_locale_language, locale_language)) return current_locale; } - // It seems initWithLocaleIdentifier accepts dash-separated locale identifier. - return RetainPtr<NSLocale>( - kAdoptNS, [[NSLocale alloc] initWithLocaleIdentifier:locale]); + // It seems localeWithLocaleIdentifier accepts dash-separated locale + // identifier. + return [NSLocale localeWithLocaleIdentifier:locale]; } std::unique_ptr<Locale> Locale::Create(const String& locale) { - return LocaleMac::Create(DetermineLocale(locale).Get()); + return LocaleMac::Create(DetermineLocale(locale)); } -static RetainPtr<NSDateFormatter> CreateDateTimeFormatter( +static base::scoped_nsobject<NSDateFormatter> CreateDateTimeFormatter( NSLocale* locale, NSCalendar* calendar, NSDateFormatterStyle date_style, @@ -82,40 +84,37 @@ [formatter setTimeStyle:time_style]; [formatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]]; [formatter setCalendar:calendar]; - return AdoptNS(formatter); + return base::scoped_nsobject<NSDateFormatter>(formatter); } LocaleMac::LocaleMac(NSLocale* locale) - : locale_(locale), - gregorian_calendar_( - kAdoptNS, - [[NSCalendar alloc] - initWithCalendarIdentifier:NSCalendarIdentifierGregorian]), + : locale_([locale retain]), + gregorian_calendar_([[NSCalendar alloc] + initWithCalendarIdentifier:NSCalendarIdentifierGregorian]), did_initialize_number_data_(false) { NSArray* available_languages = [NSLocale ISOLanguageCodes]; // NSLocale returns a lower case NSLocaleLanguageCode so we don't have care // about case. - NSString* language = [locale_.Get() objectForKey:NSLocaleLanguageCode]; + NSString* language = [locale_ objectForKey:NSLocaleLanguageCode]; if ([available_languages indexOfObject:language] == NSNotFound) - locale_.AdoptNS( + locale_.reset( [[NSLocale alloc] initWithLocaleIdentifier:DefaultLanguage()]); - [gregorian_calendar_.Get() setLocale:locale_.Get()]; + [gregorian_calendar_ setLocale:locale_]; } LocaleMac::~LocaleMac() {} std::unique_ptr<LocaleMac> LocaleMac::Create(const String& locale_identifier) { - RetainPtr<NSLocale> locale = - [[NSLocale alloc] initWithLocaleIdentifier:locale_identifier]; - return base::WrapUnique(new LocaleMac(locale.Get())); + NSLocale* locale = [NSLocale localeWithLocaleIdentifier:locale_identifier]; + return LocaleMac::Create(locale); } std::unique_ptr<LocaleMac> LocaleMac::Create(NSLocale* locale) { return base::WrapUnique(new LocaleMac(locale)); } -RetainPtr<NSDateFormatter> LocaleMac::ShortDateFormatter() { - return CreateDateTimeFormatter(locale_.Get(), gregorian_calendar_.Get(), +base::scoped_nsobject<NSDateFormatter> LocaleMac::ShortDateFormatter() { + return CreateDateTimeFormatter(locale_, gregorian_calendar_, NSDateFormatterShortStyle, NSDateFormatterNoStyle); } @@ -124,7 +123,7 @@ if (!month_labels_.IsEmpty()) return month_labels_; month_labels_.ReserveCapacity(12); - NSArray* array = [ShortDateFormatter().Get() monthSymbols]; + NSArray* array = [ShortDateFormatter() monthSymbols]; if ([array count] == 12) { for (unsigned i = 0; i < 12; ++i) month_labels_.push_back(String([array objectAtIndex:i])); @@ -139,7 +138,7 @@ if (!week_day_short_labels_.IsEmpty()) return week_day_short_labels_; week_day_short_labels_.ReserveCapacity(7); - NSArray* array = [ShortDateFormatter().Get() shortWeekdaySymbols]; + NSArray* array = [ShortDateFormatter() shortWeekdaySymbols]; if ([array count] == 7) { for (unsigned i = 0; i < 7; ++i) week_day_short_labels_.push_back(String([array objectAtIndex:i])); @@ -156,36 +155,38 @@ // The document for NSCalendar - firstWeekday doesn't have an explanation of // firstWeekday value. We can guess it by the document of NSDateComponents - // weekDay, so it can be 1 through 7 and 1 is Sunday. - return [gregorian_calendar_.Get() firstWeekday] - 1; + return [gregorian_calendar_ firstWeekday] - 1; } bool LocaleMac::IsRTL() { return NSLocaleLanguageDirectionRightToLeft == [NSLocale characterDirectionForLanguage: [NSLocale canonicalLanguageIdentifierFromString: - [locale_.Get() localeIdentifier]]]; + [locale_ localeIdentifier]]]; } -RetainPtr<NSDateFormatter> LocaleMac::TimeFormatter() { - return CreateDateTimeFormatter(locale_.Get(), gregorian_calendar_.Get(), +base::scoped_nsobject<NSDateFormatter> LocaleMac::TimeFormatter() { + return CreateDateTimeFormatter(locale_, gregorian_calendar_, NSDateFormatterNoStyle, NSDateFormatterMediumStyle); } -RetainPtr<NSDateFormatter> LocaleMac::ShortTimeFormatter() { - return CreateDateTimeFormatter(locale_.Get(), gregorian_calendar_.Get(), +base::scoped_nsobject<NSDateFormatter> LocaleMac::ShortTimeFormatter() { + return CreateDateTimeFormatter(locale_, gregorian_calendar_, NSDateFormatterNoStyle, NSDateFormatterShortStyle); } -RetainPtr<NSDateFormatter> LocaleMac::DateTimeFormatterWithSeconds() { - return CreateDateTimeFormatter(locale_.Get(), gregorian_calendar_.Get(), +base::scoped_nsobject<NSDateFormatter> +LocaleMac::DateTimeFormatterWithSeconds() { + return CreateDateTimeFormatter(locale_, gregorian_calendar_, NSDateFormatterShortStyle, NSDateFormatterMediumStyle); } -RetainPtr<NSDateFormatter> LocaleMac::DateTimeFormatterWithoutSeconds() { - return CreateDateTimeFormatter(locale_.Get(), gregorian_calendar_.Get(), +base::scoped_nsobject<NSDateFormatter> +LocaleMac::DateTimeFormatterWithoutSeconds() { + return CreateDateTimeFormatter(locale_, gregorian_calendar_, NSDateFormatterShortStyle, NSDateFormatterShortStyle); } @@ -193,7 +194,7 @@ String LocaleMac::DateFormat() { if (!date_format_.IsNull()) return date_format_; - date_format_ = [ShortDateFormatter().Get() dateFormat]; + date_format_ = [ShortDateFormatter() dateFormat]; return date_format_; } @@ -204,7 +205,7 @@ // "MMMM" in some locales. month_format_ = [NSDateFormatter dateFormatFromTemplate:@"yyyyMMMM" options:0 - locale:locale_.Get()]; + locale:locale_]; return month_format_; } @@ -213,29 +214,28 @@ return short_month_format_; short_month_format_ = [NSDateFormatter dateFormatFromTemplate:@"yyyyMMM" options:0 - locale:locale_.Get()]; + locale:locale_]; return short_month_format_; } String LocaleMac::TimeFormat() { if (!time_format_with_seconds_.IsNull()) return time_format_with_seconds_; - time_format_with_seconds_ = [TimeFormatter().Get() dateFormat]; + time_format_with_seconds_ = [TimeFormatter() dateFormat]; return time_format_with_seconds_; } String LocaleMac::ShortTimeFormat() { if (!time_format_without_seconds_.IsNull()) return time_format_without_seconds_; - time_format_without_seconds_ = [ShortTimeFormatter().Get() dateFormat]; + time_format_without_seconds_ = [ShortTimeFormatter() dateFormat]; return time_format_without_seconds_; } String LocaleMac::DateTimeFormatWithSeconds() { if (!date_time_format_with_seconds_.IsNull()) return date_time_format_with_seconds_; - date_time_format_with_seconds_ = - [DateTimeFormatterWithSeconds().Get() dateFormat]; + date_time_format_with_seconds_ = [DateTimeFormatterWithSeconds() dateFormat]; return date_time_format_with_seconds_; } @@ -243,7 +243,7 @@ if (!date_time_format_without_seconds_.IsNull()) return date_time_format_without_seconds_; date_time_format_without_seconds_ = - [DateTimeFormatterWithoutSeconds().Get() dateFormat]; + [DateTimeFormatterWithoutSeconds() dateFormat]; return date_time_format_without_seconds_; } @@ -251,7 +251,7 @@ if (!short_month_labels_.IsEmpty()) return short_month_labels_; short_month_labels_.ReserveCapacity(12); - NSArray* array = [ShortDateFormatter().Get() shortMonthSymbols]; + NSArray* array = [ShortDateFormatter() shortMonthSymbols]; if ([array count] == 12) { for (unsigned i = 0; i < 12; ++i) short_month_labels_.push_back([array objectAtIndex:i]); @@ -265,7 +265,7 @@ const Vector<String>& LocaleMac::StandAloneMonthLabels() { if (!stand_alone_month_labels_.IsEmpty()) return stand_alone_month_labels_; - NSArray* array = [ShortDateFormatter().Get() standaloneMonthSymbols]; + NSArray* array = [ShortDateFormatter() standaloneMonthSymbols]; if ([array count] == 12) { stand_alone_month_labels_.ReserveCapacity(12); for (unsigned i = 0; i < 12; ++i) @@ -279,7 +279,7 @@ const Vector<String>& LocaleMac::ShortStandAloneMonthLabels() { if (!short_stand_alone_month_labels_.IsEmpty()) return short_stand_alone_month_labels_; - NSArray* array = [ShortDateFormatter().Get() shortStandaloneMonthSymbols]; + NSArray* array = [ShortDateFormatter() shortStandaloneMonthSymbols]; if ([array count] == 12) { short_stand_alone_month_labels_.ReserveCapacity(12); for (unsigned i = 0; i < 12; ++i) @@ -294,9 +294,9 @@ if (!time_ampm_labels_.IsEmpty()) return time_ampm_labels_; time_ampm_labels_.ReserveCapacity(2); - RetainPtr<NSDateFormatter> formatter = ShortTimeFormatter(); - time_ampm_labels_.push_back([formatter.Get() AMSymbol]); - time_ampm_labels_.push_back([formatter.Get() PMSymbol]); + base::scoped_nsobject<NSDateFormatter> formatter(ShortTimeFormatter()); + time_ampm_labels_.push_back([formatter AMSymbol]); + time_ampm_labels_.push_back([formatter PMSymbol]); return time_ampm_labels_; } @@ -305,30 +305,30 @@ return; did_initialize_number_data_ = true; - RetainPtr<NSNumberFormatter> formatter(kAdoptNS, - [[NSNumberFormatter alloc] init]); - [formatter.Get() setLocale:locale_.Get()]; - [formatter.Get() setNumberStyle:NSNumberFormatterDecimalStyle]; - [formatter.Get() setUsesGroupingSeparator:NO]; + base::scoped_nsobject<NSNumberFormatter> formatter( + [[NSNumberFormatter alloc] init]); + [formatter setLocale:locale_]; + [formatter setNumberStyle:NSNumberFormatterDecimalStyle]; + [formatter setUsesGroupingSeparator:NO]; - RetainPtr<NSNumber> sample_number( - kAdoptNS, [[NSNumber alloc] initWithDouble:9876543210]); - String nine_to_zero([formatter.Get() stringFromNumber:sample_number.Get()]); + base::scoped_nsobject<NSNumber> sample_number( + [[NSNumber alloc] initWithDouble:9876543210]); + String nine_to_zero([formatter stringFromNumber:sample_number]); if (nine_to_zero.length() != 10) return; Vector<String, kDecimalSymbolsSize> symbols; for (unsigned i = 0; i < 10; ++i) symbols.push_back(nine_to_zero.Substring(9 - i, 1)); DCHECK(symbols.size() == kDecimalSeparatorIndex); - symbols.push_back([formatter.Get() decimalSeparator]); + symbols.push_back([formatter decimalSeparator]); DCHECK(symbols.size() == kGroupSeparatorIndex); - symbols.push_back([formatter.Get() groupingSeparator]); + symbols.push_back([formatter groupingSeparator]); DCHECK(symbols.size() == kDecimalSymbolsSize); - String positive_prefix([formatter.Get() positivePrefix]); - String positive_suffix([formatter.Get() positiveSuffix]); - String negative_prefix([formatter.Get() negativePrefix]); - String negative_suffix([formatter.Get() negativeSuffix]); + String positive_prefix([formatter positivePrefix]); + String positive_suffix([formatter positiveSuffix]); + String negative_prefix([formatter negativePrefix]); + String negative_suffix([formatter negativeSuffix]); SetLocaleData(symbols, positive_prefix, positive_suffix, negative_prefix, negative_suffix); }
diff --git a/third_party/blink/renderer/platform/text/locale_mac_test.cc b/third_party/blink/renderer/platform/text/locale_mac_test.mm similarity index 93% rename from third_party/blink/renderer/platform/text/locale_mac_test.cc rename to third_party/blink/renderer/platform/text/locale_mac_test.mm index 661489c..b9ab231 100644 --- a/third_party/blink/renderer/platform/text/locale_mac_test.cc +++ b/third_party/blink/renderer/platform/text/locale_mac_test.mm
@@ -203,18 +203,16 @@ FormatMonth("en_US", "2005-04", false).Utf8().data()); EXPECT_STREQ("avril 2005", FormatMonth("fr_FR", "2005-04", false).Utf8().data()); - EXPECT_STREQ( - "2005\xE5\xB9\xB4" - "04\xE6\x9C\x88", - FormatMonth("ja_JP", "2005-04", false).Utf8().data()); + EXPECT_STREQ("2005\xE5\xB9\xB4" + "04\xE6\x9C\x88", + FormatMonth("ja_JP", "2005-04", false).Utf8().data()); EXPECT_STREQ("Apr 2005", FormatMonth("en_US", "2005-04", true).Utf8().data()); EXPECT_STREQ("avr. 2005", FormatMonth("fr_FR", "2005-04", true).Utf8().data()); - EXPECT_STREQ( - "2005\xE5\xB9\xB4" - "04\xE6\x9C\x88", - FormatMonth("ja_JP", "2005-04", true).Utf8().data()); + EXPECT_STREQ("2005\xE5\xB9\xB4" + "04\xE6\x9C\x88", + FormatMonth("ja_JP", "2005-04", true).Utf8().data()); } TEST_F(LocaleMacTest, formatDate) { @@ -276,15 +274,13 @@ "\xD9\xA0\xD9\xA7\xD9\xAB\xD9\xA0\xD9\xA0\xD9\xA7\xC2\xA0\xD8\xB5", FormatTime("ar", 07, 07, 07, 007, false).Utf8().data()); } else { - EXPECT_STREQ( - "\xD9\xA7:\xD9\xA0\xD9\xA7:" - "\xD9\xA0\xD9\xA7\xD9\xAB\xD9\xA0\xD9\xA0\xD9\xA7 \xD8\xB5", - FormatTime("ar", 07, 07, 07, 007, false).Utf8().data()); + EXPECT_STREQ("\xD9\xA7:\xD9\xA0\xD9\xA7:" + "\xD9\xA0\xD9\xA7\xD9\xAB\xD9\xA0\xD9\xA0\xD9\xA7 \xD8\xB5", + FormatTime("ar", 07, 07, 07, 007, false).Utf8().data()); } - EXPECT_STREQ( - "\xDB\xB7:\xDB\xB0\xDB\xB7:" - "\xDB\xB0\xDB\xB7\xD9\xAB\xDB\xB0\xDB\xB0\xDB\xB7", - FormatTime("fa", 07, 07, 07, 007, false).Utf8().data()); + EXPECT_STREQ("\xDB\xB7:\xDB\xB0\xDB\xB7:" + "\xDB\xB0\xDB\xB7\xD9\xAB\xDB\xB0\xDB\xB0\xDB\xB7", + FormatTime("fa", 07, 07, 07, 007, false).Utf8().data()); } TEST_F(LocaleMacTest, firstDayOfWeek) { @@ -300,10 +296,9 @@ EXPECT_STREQ("janvier", MonthLabel("fr_FR", kJanuary).Utf8().data()); EXPECT_STREQ("juin", MonthLabel("fr_FR", kJune).Utf8().data()); - EXPECT_STREQ( - "d\xC3\xA9" - "cembre", - MonthLabel("fr_FR", kDecember).Utf8().data()); + EXPECT_STREQ("d\xC3\xA9" + "cembre", + MonthLabel("fr_FR", kDecember).Utf8().data()); EXPECT_STREQ("1\xE6\x9C\x88", MonthLabel("ja_JP", kJanuary).Utf8().data()); EXPECT_STREQ("6\xE6\x9C\x88", MonthLabel("ja_JP", kJune).Utf8().data()); @@ -366,10 +361,9 @@ EXPECT_STREQ("janvier", StandAloneMonthLabel("fr_FR", kJanuary).Utf8().data()); EXPECT_STREQ("juin", StandAloneMonthLabel("fr_FR", kJune).Utf8().data()); - EXPECT_STREQ( - "d\xC3\xA9" - "cembre", - StandAloneMonthLabel("fr_FR", kDecember).Utf8().data()); + EXPECT_STREQ("d\xC3\xA9" + "cembre", + StandAloneMonthLabel("fr_FR", kDecember).Utf8().data()); EXPECT_STREQ("1\xE6\x9C\x88", StandAloneMonthLabel("ja_JP", kJanuary).Utf8().data()); @@ -387,14 +381,12 @@ EXPECT_STREQ("janv.", ShortMonthLabel("fr_FR", 0).Utf8().data()); EXPECT_STREQ("janv.", ShortStandAloneMonthLabel("fr_FR", 0).Utf8().data()); - EXPECT_STREQ( - "d\xC3\xA9" - "c.", - ShortMonthLabel("fr_FR", 11).Utf8().data()); - EXPECT_STREQ( - "d\xC3\xA9" - "c.", - ShortStandAloneMonthLabel("fr_FR", 11).Utf8().data()); + EXPECT_STREQ("d\xC3\xA9" + "c.", + ShortMonthLabel("fr_FR", 11).Utf8().data()); + EXPECT_STREQ("d\xC3\xA9" + "c.", + ShortStandAloneMonthLabel("fr_FR", 11).Utf8().data()); EXPECT_STREQ("1\xE6\x9C\x88", ShortMonthLabel("ja_JP", 0).Utf8().data()); EXPECT_STREQ("1\xE6\x9C\x88",
diff --git a/third_party/blink/renderer/platform/wtf/text/atomic_string.cc b/third_party/blink/renderer/platform/wtf/text/atomic_string.cc index b55d116..b66101ad 100644 --- a/third_party/blink/renderer/platform/wtf/text/atomic_string.cc +++ b/third_party/blink/renderer/platform/wtf/text/atomic_string.cc
@@ -25,7 +25,6 @@ #include "third_party/blink/renderer/platform/wtf/dtoa.h" #include "third_party/blink/renderer/platform/wtf/text/atomic_string_table.h" -#include "third_party/blink/renderer/platform/wtf/text/integer_to_string_conversion.h" #include "third_party/blink/renderer/platform/wtf/text/string_impl.h" namespace WTF { @@ -99,36 +98,6 @@ return AtomicString(impl->UpperASCII()); } -template <typename IntegerType> -static AtomicString IntegerToAtomicString(IntegerType input) { - IntegerToStringConverter<IntegerType> converter(input); - return AtomicString(converter.Characters8(), converter.length()); -} - -AtomicString AtomicString::Number(int number) { - return IntegerToAtomicString(number); -} - -AtomicString AtomicString::Number(unsigned number) { - return IntegerToAtomicString(number); -} - -AtomicString AtomicString::Number(long number) { - return IntegerToAtomicString(number); -} - -AtomicString AtomicString::Number(unsigned long number) { - return IntegerToAtomicString(number); -} - -AtomicString AtomicString::Number(long long number) { - return IntegerToAtomicString(number); -} - -AtomicString AtomicString::Number(unsigned long long number) { - return IntegerToAtomicString(number); -} - AtomicString AtomicString::Number(double number, unsigned precision) { NumberToStringBuffer buffer; return AtomicString(NumberToFixedPrecisionString(number, precision, buffer));
diff --git a/third_party/blink/renderer/platform/wtf/text/atomic_string.h b/third_party/blink/renderer/platform/wtf/text/atomic_string.h index 9255761..b6f1218 100644 --- a/third_party/blink/renderer/platform/wtf/text/atomic_string.h +++ b/third_party/blink/renderer/platform/wtf/text/atomic_string.h
@@ -28,6 +28,7 @@ #include "third_party/blink/renderer/platform/wtf/allocator.h" #include "third_party/blink/renderer/platform/wtf/hash_table_deleted_value_type.h" #include "third_party/blink/renderer/platform/wtf/text/cstring.h" +#include "third_party/blink/renderer/platform/wtf/text/integer_to_string_conversion.h" #include "third_party/blink/renderer/platform/wtf/text/string_view.h" #include "third_party/blink/renderer/platform/wtf/text/wtf_string.h" #include "third_party/blink/renderer/platform/wtf/wtf_export.h" @@ -192,12 +193,11 @@ double ToDouble(bool* ok = nullptr) const { return string_.ToDouble(ok); } float ToFloat(bool* ok = nullptr) const { return string_.ToFloat(ok); } - static AtomicString Number(int); - static AtomicString Number(unsigned); - static AtomicString Number(long); - static AtomicString Number(unsigned long); - static AtomicString Number(long long); - static AtomicString Number(unsigned long long); + template <typename IntegerType> + static AtomicString Number(IntegerType number) { + IntegerToStringConverter<IntegerType> converter(number); + return AtomicString(converter.Characters8(), converter.length()); + } static AtomicString Number(double, unsigned precision = 6);
diff --git a/third_party/blink/renderer/platform/wtf/text/atomic_string_test.cc b/third_party/blink/renderer/platform/wtf/text/atomic_string_test.cc index 9b0a024..84e0fc5 100644 --- a/third_party/blink/renderer/platform/wtf/text/atomic_string_test.cc +++ b/third_party/blink/renderer/platform/wtf/text/atomic_string_test.cc
@@ -35,23 +35,23 @@ namespace WTF { TEST(AtomicStringTest, Number) { - int int_value = 1234; + int16_t int_value = 1234; EXPECT_EQ("1234", AtomicString::Number(int_value)); int_value = -1234; EXPECT_EQ("-1234", AtomicString::Number(int_value)); - unsigned unsigned_value = 1234u; + uint16_t unsigned_value = 1234u; EXPECT_EQ("1234", AtomicString::Number(unsigned_value)); - long long_value = 6553500; + int32_t long_value = 6553500; EXPECT_EQ("6553500", AtomicString::Number(long_value)); long_value = -6553500; EXPECT_EQ("-6553500", AtomicString::Number(long_value)); - unsigned long unsigned_long_value = 4294967295u; + uint32_t unsigned_long_value = 4294967295u; EXPECT_EQ("4294967295", AtomicString::Number(unsigned_long_value)); - long long longlong_value = 9223372036854775807; + int64_t longlong_value = 9223372036854775807; EXPECT_EQ("9223372036854775807", AtomicString::Number(longlong_value)); longlong_value = -9223372036854775807; EXPECT_EQ("-9223372036854775807", AtomicString::Number(longlong_value)); - unsigned long long unsigned_long_long_value = 18446744073709551615u; + uint64_t unsigned_long_long_value = 18446744073709551615u; EXPECT_EQ("18446744073709551615", AtomicString::Number(unsigned_long_long_value)); double double_value = 1234.56;
diff --git a/third_party/blink/renderer/platform/wtf/text/string_builder.cc b/third_party/blink/renderer/platform/wtf/text/string_builder.cc index 2de98044..1fc0c64 100644 --- a/third_party/blink/renderer/platform/wtf/text/string_builder.cc +++ b/third_party/blink/renderer/platform/wtf/text/string_builder.cc
@@ -228,34 +228,12 @@ length_ += length; } -template <typename IntegerType> -static void AppendIntegerInternal(StringBuilder& builder, IntegerType input) { - IntegerToStringConverter<IntegerType> converter(input); - builder.Append(converter.Characters8(), converter.length()); +void StringBuilder::AppendNumber(bool number) { + AppendNumber(static_cast<uint8_t>(number)); } -void StringBuilder::AppendNumber(int number) { - AppendIntegerInternal(*this, number); -} - -void StringBuilder::AppendNumber(unsigned number) { - AppendIntegerInternal(*this, number); -} - -void StringBuilder::AppendNumber(long number) { - AppendIntegerInternal(*this, number); -} - -void StringBuilder::AppendNumber(unsigned long number) { - AppendIntegerInternal(*this, number); -} - -void StringBuilder::AppendNumber(long long number) { - AppendIntegerInternal(*this, number); -} - -void StringBuilder::AppendNumber(unsigned long long number) { - AppendIntegerInternal(*this, number); +void StringBuilder::AppendNumber(float number) { + AppendNumber(static_cast<double>(number)); } void StringBuilder::AppendNumber(double number, unsigned precision) {
diff --git a/third_party/blink/renderer/platform/wtf/text/string_builder.h b/third_party/blink/renderer/platform/wtf/text/string_builder.h index 4898f02..ec90d25 100644 --- a/third_party/blink/renderer/platform/wtf/text/string_builder.h +++ b/third_party/blink/renderer/platform/wtf/text/string_builder.h
@@ -29,6 +29,7 @@ #include "base/macros.h" #include "third_party/blink/renderer/platform/wtf/text/atomic_string.h" +#include "third_party/blink/renderer/platform/wtf/text/integer_to_string_conversion.h" #include "third_party/blink/renderer/platform/wtf/text/string_view.h" #include "third_party/blink/renderer/platform/wtf/text/wtf_string.h" #include "third_party/blink/renderer/platform/wtf/wtf_export.h" @@ -135,12 +136,16 @@ Append(U16_TRAIL(c)); } - void AppendNumber(int); - void AppendNumber(unsigned); - void AppendNumber(long); - void AppendNumber(unsigned long); - void AppendNumber(long long); - void AppendNumber(unsigned long long); + template <typename IntegerType> + void AppendNumber(IntegerType number) { + IntegerToStringConverter<IntegerType> converter(number); + Append(converter.Characters8(), converter.length()); + } + + void AppendNumber(bool); + + void AppendNumber(float); + void AppendNumber(double, unsigned precision = 6); void erase(unsigned);
diff --git a/third_party/blink/renderer/platform/wtf/text/text_stream.cc b/third_party/blink/renderer/platform/wtf/text/text_stream.cc index 80fa175..16dfd83 100644 --- a/third_party/blink/renderer/platform/wtf/text/text_stream.cc +++ b/third_party/blink/renderer/platform/wtf/text/text_stream.cc
@@ -47,32 +47,32 @@ return *this << (b ? "1" : "0"); } -TextStream& TextStream::operator<<(int i) { +TextStream& TextStream::operator<<(int16_t i) { text_.AppendNumber(i); return *this; } -TextStream& TextStream::operator<<(unsigned i) { +TextStream& TextStream::operator<<(uint16_t i) { text_.AppendNumber(i); return *this; } -TextStream& TextStream::operator<<(long i) { +TextStream& TextStream::operator<<(int32_t i) { text_.AppendNumber(i); return *this; } -TextStream& TextStream::operator<<(unsigned long i) { +TextStream& TextStream::operator<<(uint32_t i) { text_.AppendNumber(i); return *this; } -TextStream& TextStream::operator<<(long long i) { +TextStream& TextStream::operator<<(int64_t i) { text_.AppendNumber(i); return *this; } -TextStream& TextStream::operator<<(unsigned long long i) { +TextStream& TextStream::operator<<(uint64_t i) { text_.AppendNumber(i); return *this; }
diff --git a/third_party/blink/renderer/platform/wtf/text/text_stream.h b/third_party/blink/renderer/platform/wtf/text/text_stream.h index 13e39d6..45f367e 100644 --- a/third_party/blink/renderer/platform/wtf/text/text_stream.h +++ b/third_party/blink/renderer/platform/wtf/text/text_stream.h
@@ -44,12 +44,12 @@ }; TextStream& operator<<(bool); - TextStream& operator<<(int); - TextStream& operator<<(unsigned); - TextStream& operator<<(long); - TextStream& operator<<(unsigned long); - TextStream& operator<<(long long); - TextStream& operator<<(unsigned long long); + TextStream& operator<<(int16_t); + TextStream& operator<<(uint16_t); + TextStream& operator<<(int32_t); + TextStream& operator<<(uint32_t); + TextStream& operator<<(int64_t); + TextStream& operator<<(uint64_t); TextStream& operator<<(float); TextStream& operator<<(double); TextStream& operator<<(const char*);
diff --git a/third_party/blink/renderer/platform/wtf/text/wtf_string.cc b/third_party/blink/renderer/platform/wtf/text/wtf_string.cc index a243c0a8..797a38c 100644 --- a/third_party/blink/renderer/platform/wtf/text/wtf_string.cc +++ b/third_party/blink/renderer/platform/wtf/text/wtf_string.cc
@@ -30,7 +30,6 @@ #include "third_party/blink/renderer/platform/wtf/math_extras.h" #include "third_party/blink/renderer/platform/wtf/text/character_names.h" #include "third_party/blink/renderer/platform/wtf/text/cstring.h" -#include "third_party/blink/renderer/platform/wtf/text/integer_to_string_conversion.h" #include "third_party/blink/renderer/platform/wtf/text/unicode.h" #include "third_party/blink/renderer/platform/wtf/text/utf8.h" #include "third_party/blink/renderer/platform/wtf/vector.h" @@ -395,34 +394,8 @@ return str; } -template <typename IntegerType> -static String IntegerToString(IntegerType input) { - IntegerToStringConverter<IntegerType> converter(input); - return StringImpl::Create(converter.Characters8(), converter.length()); -} - -String String::Number(int number) { - return IntegerToString(number); -} - -String String::Number(unsigned number) { - return IntegerToString(number); -} - -String String::Number(long number) { - return IntegerToString(number); -} - -String String::Number(unsigned long number) { - return IntegerToString(number); -} - -String String::Number(long long number) { - return IntegerToString(number); -} - -String String::Number(unsigned long long number) { - return IntegerToString(number); +String String::Number(float number) { + return Number(static_cast<double>(number)); } String String::Number(double number, unsigned precision) {
diff --git a/third_party/blink/renderer/platform/wtf/text/wtf_string.h b/third_party/blink/renderer/platform/wtf/text/wtf_string.h index a22ee403..8fcc9ec7 100644 --- a/third_party/blink/renderer/platform/wtf/text/wtf_string.h +++ b/third_party/blink/renderer/platform/wtf/text/wtf_string.h
@@ -30,6 +30,7 @@ #include "build/build_config.h" #include "third_party/blink/renderer/platform/wtf/allocator.h" #include "third_party/blink/renderer/platform/wtf/compiler.h" +#include "third_party/blink/renderer/platform/wtf/text/integer_to_string_conversion.h" #include "third_party/blink/renderer/platform/wtf/text/string_impl.h" #include "third_party/blink/renderer/platform/wtf/text/string_view.h" #include "third_party/blink/renderer/platform/wtf/wtf_export.h" @@ -162,12 +163,13 @@ return (*impl_)[index]; } - static String Number(int); - static String Number(unsigned); - static String Number(long); - static String Number(unsigned long); - static String Number(long long); - static String Number(unsigned long long); + template <typename IntegerType> + static String Number(IntegerType number) { + IntegerToStringConverter<IntegerType> converter(number); + return StringImpl::Create(converter.Characters8(), converter.length()); + } + + static String Number(float); static String Number(double, unsigned precision = 6);
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 6b5f276..fd87285f0 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
@@ -86,6 +86,12 @@ 'base::RepeatingCallback', 'base::RepeatingClosure', + # //base/mac/scoped_nsobject.h + 'base::scoped_nsobject', + + # //base/memory/scoped_policy.h + 'base::scoped_policy::RETAIN', + # //base/memory/ptr_util.h. 'base::WrapUnique',
diff --git a/third_party/blink/web_tests/NeverFixTests b/third_party/blink/web_tests/NeverFixTests index e60135a..b6acae0 100644 --- a/third_party/blink/web_tests/NeverFixTests +++ b/third_party/blink/web_tests/NeverFixTests
@@ -2144,7 +2144,9 @@ # ==== Tests incompatible with the default WPT Origin Isolation start here ==VV # The section below lists web tests that are incompatible with the WPT Origin # Isolation mode of Site Isolation (see -# WebTestContentBrowserClient::GetOriginsRequiringDedicatedProcess). +# WebTestContentBrowserClient::GetOriginsRequiringDedicatedProcess) which +# isolates WPT origins on top of the default site-per-process mode (see +# ContentBrowserClient::ShouldEnableStrictSiteIsolation). # # Note that test coverage offered by the tests WontFix-ed below is preserved by # the virtual/not-site-per-process test suite (see also @@ -2181,6 +2183,19 @@ Bug(none) virtual/sharedarraybuffer/external/wpt/html/infrastructure/safe-passing-of-structured-data/shared-array-buffers/window-similar-but-cross-origin-success.sub.html [ WontFix ] Bug(none) external/wpt/wasm/serialization/module/window-domain-success.sub.html [ WontFix ] Bug(none) external/wpt/wasm/serialization/module/window-similar-but-cross-origin-success.sub.html [ WontFix ] +# -------------------- origin-vs-url in console messages ----------------- +# Process hosting https://foo.example.com should not get any data from +# https://bar.other-site-example.com. This includes things like cookies +# and localStorage, but also full URLs (which may include some "secrets" +# and [unlike origins] are not exposed to other origins through web APIs). +# To properly enforce security boundary described above, console messages +# cannot include full cross-origin URLs (i.e. the messages need to strip +# cross-origin URLs down to just the origin - for example, +# https://foo.example.com/path?token=secret needs to be replaced with just +# https://foo.example.com). +crbug.com/669083 http/tests/security/frameNavigation/xss-DENIED-top-navigation-without-user-gesture.html [ WontFix ] +crbug.com/669083 virtual/outofblink-cors/http/tests/security/frameNavigation/xss-DENIED-top-navigation-without-user-gesture.html [ WontFix ] +crbug.com/669083 virtual/feature-policy-for-sandbox/http/tests/security/frameNavigation/xss-DENIED-top-navigation-without-user-gesture.html [ WontFix ] # --------------------------- code cache isolation ----------------------- # Code cache isolation tests only make sense if either # 1) site isolation is disabled or
diff --git a/third_party/blink/web_tests/TestExpectations b/third_party/blink/web_tests/TestExpectations index 693abf2c..4dee358 100644 --- a/third_party/blink/web_tests/TestExpectations +++ b/third_party/blink/web_tests/TestExpectations
@@ -161,11 +161,6 @@ # Text auto-sizing: crbug.com/393285 http/tests/text-autosizing/narrow-iframe.html [ Failure Crash ] crbug.com/393285 http/tests/text-autosizing/wide-iframe.html [ Failure Crash ] -# Console message differences (e.g. full URI vs origin-only): -crbug.com/669083 http/tests/security/frameNavigation/xss-DENIED-top-navigation-without-user-gesture.html [ Failure ] -crbug.com/669083 virtual/outofblink-cors/http/tests/security/frameNavigation/xss-DENIED-top-navigation-without-user-gesture.html [ Failure ] -crbug.com/669083 virtual/feature-policy-for-sandbox/http/tests/security/frameNavigation/xss-DENIED-top-navigation-without-user-gesture.html [ Failure ] -crbug.com/886588 external/wpt/dom/events/EventListener-addEventListener.sub.window.html [ Failure ] # Tests temporarily disabled with Site Isolation - uninvestigated bugs: # TODO(lukasza, alexmos): Burn down this list. @@ -629,6 +624,8 @@ # Layout team disagrees with the spec for this particular test. crbug.com/591099 external/wpt/css/css-ui/text-overflow-015.html [ Failure ] +crbug.com/940963 external/wpt/css/css-sizing/range-percent-intrinsic-size-2a.html [ Failure ] + # ====== Layout team owned tests to here ====== # ====== LayoutNG-only failures from here ====== @@ -3066,7 +3063,6 @@ crbug.com/626703 external/wpt/css/css-text/shaping/shaping-014.html [ Failure ] crbug.com/626703 external/wpt/css/css-text/shaping/shaping-015.html [ Failure ] crbug.com/626703 external/wpt/css/css-text/word-break/word-break-break-word-overflow-wrap-interactions.html [ Failure ] -crbug.com/626703 external/wpt/css/css-sizing/range-percent-intrinsic-size-2a.html [ Failure ] crbug.com/626703 external/wpt/infrastructure/reftest/reftest_fuzzy.html [ Failure ] crbug.com/626703 external/wpt/infrastructure/reftest/reftest_fuzzy_1.html [ Failure ] crbug.com/626703 external/wpt/screen-orientation/onchange-event.html [ Timeout ] @@ -4529,12 +4525,6 @@ crbug.com/831509 virtual/navigation-mojo-response/external/wpt/service-workers/service-worker/skip-waiting-installed.https.html [ Failure Pass ] crbug.com/831509 virtual/outofblink-cors/external/wpt/service-workers/service-worker/skip-waiting-installed.https.html [ Failure Pass ] -# Stale While Revalidate -crbug.com/348877 external/wpt/fetch/stale-while-revalidate/fetch-sw.https.tentative.html [ Failure ] -crbug.com/348877 virtual/outofblink-cors/external/wpt/fetch/stale-while-revalidate/fetch-sw.https.tentative.html [ Failure ] -crbug.com/348877 external/wpt/fetch/stale-while-revalidate/fetch.tentative.html [ Failure ] -crbug.com/348877 virtual/outofblink-cors/external/wpt/fetch/stale-while-revalidate/fetch.tentative.html [ Failure ] - # Sheriff failures 2017-02-21 crbug.com/73609 http/tests/media/video-play-stall.html [ Pass Timeout ] @@ -5160,11 +5150,6 @@ crbug.com/833331 [ Win10 ] inspector-protocol/page/pageNavigateToFragment.js [ Pass Failure ] crbug.com/831796 virtual/mouseevent_fractional/fast/events/autoscroll-in-textfield.html [ Failure Pass ] -# Sheriff 2018-04-24 -crbug.com/836242 [ Linux ] fast/loader/reload-zero-byte-plugin.html [ Pass Failure ] -crbug.com/836242 [ Mac ] fast/loader/reload-zero-byte-plugin.html [ Pass Failure ] -crbug.com/836242 [ Win ] fast/loader/reload-zero-byte-plugin.html [ Pass Failure ] - # Sheriff 2018-04-25 crbug.com/836783 fast/peerconnection/RTCRtpSender-setParameters.html [ Pass Timeout ] @@ -6042,7 +6027,6 @@ crbug.com/937170 [ Linux Win7 ] external/wpt/IndexedDB/interleaved-cursors-large.html [ Pass Timeout Crash ] crbug.com/937312 [ Win7 ] external/wpt/background-fetch/fetch.https.window.html [ Pass Timeout ] crbug.com/893659 [ Mac ] virtual/threaded/fast/events/pointerevents/pinch/pointerevent_touch-action-pinch_zoom_touch.html [ Pass Failure Crash ] -crbug.com/937358 [ Win ] virtual/scroll_customization/fast/events/touch/touch-handler-iframe-plugin-assert.html [ Pass Failure ] crbug.com/937378 [ Win7 ] http/tests/devtools/service-workers/service-workers-force-update-on-page-load.js [ Pass Timeout ] crbug.com/864994 [ Linux Win7 ] external/wpt/encoding/legacy-mb-korean/euc-kr/euckr-decode-ksc_5601.html [ Timeout Failure Pass ] crbug.com/937416 [ Linux Mac ] http/tests/devtools/resource-tree/resource-tree-htmlimports.js [ Pass Failure ]
diff --git a/third_party/blink/web_tests/VirtualTestSuites b/third_party/blink/web_tests/VirtualTestSuites index 20f7696..3eb6369 100644 --- a/third_party/blink/web_tests/VirtualTestSuites +++ b/third_party/blink/web_tests/VirtualTestSuites
@@ -771,11 +771,6 @@ }, { "prefix": "not-site-per-process", - "base": "external/wpt/dom/events/EventListener-addEventListener.sub.window.js", - "args": ["--disable-site-isolation-trials"] - }, - { - "prefix": "not-site-per-process", "base": "external/wpt/dom/events/EventListener-incumbent-global-1.sub.html", "args": ["--disable-site-isolation-trials"] }, @@ -851,11 +846,6 @@ }, { "prefix": "not-site-per-process", - "base": "external/wpt/payment-request/allowpaymentrequest/setting-allowpaymentrequest-timing.https.sub.html", - "args": ["--disable-site-isolation-trials"] - }, - { - "prefix": "not-site-per-process", "base": "external/wpt/wasm/serialization/module/window-domain-success.sub.html", "args": ["--disable-site-isolation-trials"] },
diff --git a/third_party/blink/web_tests/animations/animationworklet/worklet-animation-cancel-expected.html b/third_party/blink/web_tests/animations/animationworklet/worklet-animation-cancel-expected.html deleted file mode 100644 index 895dc17..0000000 --- a/third_party/blink/web_tests/animations/animationworklet/worklet-animation-cancel-expected.html +++ /dev/null
@@ -1,11 +0,0 @@ -<!DOCTYPE html> -<style> -#box { - width: 100px; - height: 100px; - background-color: #0000ff; - opacity: 0.8; -} -</style> - -<div id="box"></div>
diff --git a/third_party/blink/web_tests/animations/animationworklet/worklet-animation-cancel.html b/third_party/blink/web_tests/animations/animationworklet/worklet-animation-cancel.html deleted file mode 100644 index 41b7e66f2..0000000 --- a/third_party/blink/web_tests/animations/animationworklet/worklet-animation-cancel.html +++ /dev/null
@@ -1,58 +0,0 @@ -<!DOCTYPE html> -<style> -#box { - width: 100px; - height: 100px; - background-color: #0000ff; -} -</style> - -<div id="box"></div> - -<script id="visual_update" type="text/worklet"> -registerAnimator("test_animator", class { - animate(currentTime, effect) { - effect.localTime = 500; - } -}); -</script> - -<script src="resources/animation-worklet-tests.js"></script> -<script> -if (window.testRunner) { - testRunner.waitUntilDone(); -} - -runInAnimationWorklet(document.getElementById('visual_update').textContent) - .then(_ => { - - const box = document.getElementById('box'); - const effect = new KeyframeEffect(box, - [ - {transform: 'translateY(0)'}, - {transform: 'translateY(200px)'} - ], { - duration: 1000, - iterations: Infinity - } - ); - - const animation = new WorkletAnimation('test_animator', [effect], document.timeline, {}); - - animation.play(); - waitTwoAnimationFrames(_ => { - // Canceling a playing animation should remove the effect from compositor. - animation.cancel(); - // TODO(crbug.com/829926): At the moment cancelling a worklet animation does - // not cause a commit from main to impl which means impl continues to have - // its last animated value even after cancelling. This is certainly a bug! - // But for now force a commit by manually updating the opacity. - box.style.opacity = 0.8; - if (window.testRunner) { - waitTwoAnimationFrames(_ => { - testRunner.notifyDone(); - }); - } - }); -}); -</script>
diff --git a/third_party/blink/web_tests/animations/animationworklet/worklet-animation-creation.html b/third_party/blink/web_tests/animations/animationworklet/worklet-animation-creation.html deleted file mode 100644 index c40513b2..0000000 --- a/third_party/blink/web_tests/animations/animationworklet/worklet-animation-creation.html +++ /dev/null
@@ -1,124 +0,0 @@ -<!DOCTYPE html> -<script src='../../resources/testharness.js'></script> -<script src='../../resources/testharnessreport.js'></script> - -<style> -.scroller { - height: 100px; - width: 100px; - overflow: scroll; -} -.content { - height: 500px; - width: 500px; -} -</style> - -<script> -function CreateKeyframeEffect(element) { - return new KeyframeEffect( - element, - [ - { transform: 'translateY(0%)' }, - { transform: 'translateY(100%)' } - ], - { duration: 3000, fill: 'forwards' } - ); -} -</script> -<script id="simple_animate" type="text/worklet"> -registerAnimator("test-animator", class { - animate(currentTime, effect) {} -}); -</script> - -<div id='element'></div> -<div id='element2'></div> -<div class='scroller'> - <div class='content'></div> -</div> - -<script src="resources/animation-worklet-tests.js"></script> -<script> -promise_test(async t => { - await runInAnimationWorklet(document.getElementById('simple_animate').textContent); - let effect = CreateKeyframeEffect(document.querySelector('#element')); - let workletAnimation = new WorkletAnimation( - 'test-animator', effect); - assert_equals(workletAnimation.playState, 'idle'); - assert_equals(workletAnimation.timeline, document.timeline); -}, 'WorkletAnimation creation without timeline should use default documentation timeline'); - -promise_test(async t => { - await runInAnimationWorklet(document.getElementById('simple_animate').textContent); - let effect = CreateKeyframeEffect(document.querySelector('#element')); - let workletAnimation = new WorkletAnimation( - 'test-animator', effect, document.timeline); - assert_equals(workletAnimation.playState, 'idle'); -}, 'WorkletAnimation creation with timeline should work'); - -promise_test(async t => { - await runInAnimationWorklet(document.getElementById('simple_animate').textContent); - let effect = CreateKeyframeEffect(document.querySelector('#element')); - let options = { my_param: 'foo', my_other_param: true }; - let workletAnimation = new WorkletAnimation( - 'test-animator', effect, document.timeline, options); - assert_equals(workletAnimation.playState, 'idle'); -}, 'WorkletAnimation creation with timeline and options should work'); - -promise_test(async t => { - await runInAnimationWorklet(document.getElementById('simple_animate').textContent); - let effect = CreateKeyframeEffect(document.querySelector('#element')); - let scroller = document.querySelector('.scroller'); - let scrollTimeline = new ScrollTimeline( - { scrollSource: scroller, timeRange: 100, orientation: 'inline' }); - let workletAnimation = new WorkletAnimation( - 'test-animator', effect, scrollTimeline); - assert_equals(workletAnimation.playState, 'idle'); -}, 'ScrollTimeline is a valid timeline for a WorkletAnimation'); - -promise_test(async t => { - await runInAnimationWorklet(document.getElementById('simple_animate').textContent); - let constructorFunc = function() { new WorkletAnimation( - 'test-animator', []); }; - assert_throws('NotSupportedError', constructorFunc); -}, 'If there are no effects specified, object construction should fail'); - -promise_test(async t => { - await runInAnimationWorklet(document.getElementById('simple_animate').textContent); - let effect = CreateKeyframeEffect(document.querySelector('#element')); - - let otherDoc = document.implementation.createHTMLDocument(); - let otherElement = otherDoc.createElement('div'); - otherDoc.body.appendChild(otherElement); - let otherEffect = CreateKeyframeEffect(otherElement); - - let constructorFunc = function() { new WorkletAnimation( - 'test-animator', [ effect, otherEffect ]); }; - assert_throws('NotSupportedError', constructorFunc); -}, 'If the effects are from different documents, object construction should fail'); - -promise_test(async t => { - await runInAnimationWorklet(document.getElementById('simple_animate').textContent); - // TODO(crbug.com/781816): Allow KeyframeEffects with no target in AnimationWorklet. - let effect = CreateKeyframeEffect(null); - let effect2 = CreateKeyframeEffect(document.querySelector('#element')); - - let constructorFunc = function() { new WorkletAnimation( - 'test-animator', [ effect, effect2 ]); }; - assert_throws('NotSupportedError', constructorFunc); - - let constructorFunc2 = function() { new WorkletAnimation( - 'test-animator', [ effect2, effect ]); }; - assert_throws('NotSupportedError', constructorFunc2); -}, 'If an effect has no target, object construction should fail'); - -promise_test(async t => { - await runInAnimationWorklet(document.getElementById('simple_animate').textContent); - let effect = CreateKeyframeEffect(document.querySelector('#element')); - let constructorFunc = function() { - new WorkletAnimation('unregistered-animator', effect); - }; - assert_throws('InvalidStateError', constructorFunc); -}, 'Constructing worklet animation for unregisested animator should throw'); -</script>
diff --git a/third_party/blink/web_tests/animations/animationworklet/worklet-animation-duration-expected.html b/third_party/blink/web_tests/animations/animationworklet/worklet-animation-duration-expected.html deleted file mode 100644 index cecef29..0000000 --- a/third_party/blink/web_tests/animations/animationworklet/worklet-animation-duration-expected.html +++ /dev/null
@@ -1,13 +0,0 @@ -<!DOCTYPE html> -<style> -#box { - width: 100px; - height: 100px; - background-color: #00ff00; - will-change: transform; - transform: translateY(100px); - opacity: 0.8; -} -</style> - -<div id="box"></div>
diff --git a/third_party/blink/web_tests/animations/animationworklet/worklet-animation-duration.html b/third_party/blink/web_tests/animations/animationworklet/worklet-animation-duration.html deleted file mode 100644 index 922d0288..0000000 --- a/third_party/blink/web_tests/animations/animationworklet/worklet-animation-duration.html +++ /dev/null
@@ -1,67 +0,0 @@ -<!DOCTYPE html> -<style> -#box { - width: 100px; - height: 100px; - background-color: #00ff00; -} -</style> - -<div id="box"></div> - -<script id="visual_update" type="text/worklet"> -registerAnimator("test_animator", class { - animate(currentTime, effect) { - effect.localTime = 0.5; - } -}); -</script> - -<script src="resources/animation-worklet-tests.js"></script> - -<script> -if (window.testRunner) { - testRunner.waitUntilDone(); -} - -runInAnimationWorklet( - document.getElementById('visual_update').textContent -).then(() => { - const box = document.getElementById('box'); - const effect = new KeyframeEffect(box, - [ - { transform: 'translateY(0px)' }, - { transform: 'translateY(200px)' } - ], { - duration: 1, - } - ); - - const animation = new WorkletAnimation('test_animator', effect, document.timeline, {}); - animation.play(); - - // The WorkletAnimation should continue to be in effect forever, even if its - // duration is passed. - // - // The animation is specified to last for 1 millisecond, but we wait for 500ms - // to be safe. This is definitely risking flake, but until we start forwarding - // style changes to the main thread there's not much else we can do here. - setTimeout(function() { - // TODO(crbug.com/829926): At the moment a worklet animation ending does not - // cause a commit from main to impl which means impl continues to have its - // last animated value even after cancelling. This is certainly a bug! But - // for now force a commit by manually updating the opacity. - // - // Note that this is only required in the case where this test would *fail*. - // We want to be sure we spot the WorkletAnimation incorrectly ending early, - // so we need to force a redraw. - box.style.opacity = 0.8; - - if (window.testRunner) { - waitTwoAnimationFrames(_ => { - testRunner.notifyDone(); - }); - } - }, 500); -}); -</script>
diff --git a/third_party/blink/web_tests/animations/animationworklet/worklet-animation-start-delay-expected.html b/third_party/blink/web_tests/animations/animationworklet/worklet-animation-start-delay-expected.html deleted file mode 100644 index 640b5be7..0000000 --- a/third_party/blink/web_tests/animations/animationworklet/worklet-animation-start-delay-expected.html +++ /dev/null
@@ -1,11 +0,0 @@ -<!DOCTYPE html> -<style> -.box { - width: 100px; - height: 100px; - background-color: #00ff00; -} -</style> - -<div class="box"></div> -<div style="transform: translateX(100px);" class="box"></div>
diff --git a/third_party/blink/web_tests/animations/animationworklet/worklet-animation-start-delay.html b/third_party/blink/web_tests/animations/animationworklet/worklet-animation-start-delay.html deleted file mode 100644 index e3be2f90..0000000 --- a/third_party/blink/web_tests/animations/animationworklet/worklet-animation-start-delay.html +++ /dev/null
@@ -1,62 +0,0 @@ -<!DOCTYPE html> -<style> -.box { - width: 100px; - height: 100px; - background-color: #00ff00; -} -</style> - -<div id="t0" class="box"></div> -<div id="t1" class="box"></div> - -<script id="visual_update" type="text/worklet"> -registerAnimator("t0_animator", class { - animate(currentTime, effect) { - effect.localTime = 500; - } -}); - -registerAnimator("t1_animator", class { - animate(currentTime, effect) { - effect.localTime = 5500; - } -}); -</script> - -<script src="resources/animation-worklet-tests.js"></script> -<script> -if (window.testRunner) { - testRunner.waitUntilDone(); -} - -runInAnimationWorklet( - document.getElementById('visual_update').textContent -).then(()=>{ - const keyframes = [ - { transform: 'translateX(0)' }, - { transform: 'translateX(200px)' } - ]; - const options = { - duration: 1000, - delay: 5000, - }; - - const $t0 = document.getElementById('t0'); - const $t0_effect = new KeyframeEffect($t0, keyframes, options); - const $t0_animation = new WorkletAnimation('t0_animator', [$t0_effect], document.timeline, {}); - - const $t1 = document.getElementById('t1'); - const $t1_effect = new KeyframeEffect($t1, keyframes, options); - const $t1_animation = new WorkletAnimation('t1_animator', [$t1_effect], document.timeline, {}); - - $t0_animation.play(); - $t1_animation.play(); - - if (window.testRunner) { - waitTwoAnimationFrames(_ => { - testRunner.notifyDone(); - }); - } -}); -</script>
diff --git a/third_party/blink/web_tests/external/WPT_BASE_MANIFEST_5.json b/third_party/blink/web_tests/external/WPT_BASE_MANIFEST_5.json index 6341de8e..3c5ad49 100644 --- a/third_party/blink/web_tests/external/WPT_BASE_MANIFEST_5.json +++ b/third_party/blink/web_tests/external/WPT_BASE_MANIFEST_5.json
@@ -405730,11 +405730,11 @@ "support" ], "domparsing/XMLSerializer-serializeToString-expected.txt": [ - "74a15ed0a603a456e68c8b358a1e34cae590f988", + "0861a3b59d0bfb1cd81859c2b634b6212224b744", "support" ], "domparsing/XMLSerializer-serializeToString.html": [ - "81df61f5bc42880ee013287e90a3808bdccd536b", + "cb8ed9372df5e05588cbd593c40a8c13ee868bec", "testharness" ], "domparsing/createContextualFragment.html": [ @@ -458130,7 +458130,7 @@ "support" ], "screen-orientation/event-before-promise.html": [ - "d876b0c8873ebe0f009ebe4e6ef02a8bac52cf9c", + "51b41e19357141d5bf9699d41f8968378dcc8956", "testharness" ], "screen-orientation/idlharness.window.js": [ @@ -458170,7 +458170,7 @@ "support" ], "screen-orientation/orientation-reading.html": [ - "574258ff52522a14193408bbc8fb0db2f0d154d5", + "2a31203dc2cb5a9056cde148495aabcd5af71e02", "testharness" ], "screen-orientation/page-visibility-manual.html": [ @@ -461498,7 +461498,7 @@ "support" ], "service-workers/service-worker/resources/service-worker-csp-worker.py": [ - "5f06454f144d584dbbec4ec2457f5b5bdd161fe6", + "9d2b1f2d834f523447b2cfd373bb176f2e0e8573", "support" ], "service-workers/service-worker/resources/service-worker-header.py": [ @@ -476038,11 +476038,11 @@ "testharness" ], "webrtc/RTCDataChannel-bufferedAmount-expected.txt": [ - "d1c7fbaf36966a29a16e048bc286a16c1925e03f", + "d98b022634c6d5f0dd088ce42bfcf625a9eeb29f", "support" ], "webrtc/RTCDataChannel-bufferedAmount.html": [ - "2c37cc278f57c218160a11571f980c0f726a34f9", + "f4a7104a4e5f330b7ab2db95b72bc609eeb33e9f", "testharness" ], "webrtc/RTCDataChannel-id.html": [
diff --git a/third_party/blink/web_tests/external/wpt/animation-worklet/worklet-animation-cancel-ref.html b/third_party/blink/web_tests/external/wpt/animation-worklet/worklet-animation-cancel-ref.html new file mode 100644 index 0000000..d4492737 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/animation-worklet/worklet-animation-cancel-ref.html
@@ -0,0 +1,11 @@ +<!DOCTYPE html> +<title>Reference for Canceling a playing WorkletAnimation should remove the effect</title> +<style> +#box { + width: 100px; + height: 100px; + background-color: blue; +} +</style> + +<div id="box"></div>
diff --git a/third_party/blink/web_tests/external/wpt/animation-worklet/worklet-animation-cancel.https.html b/third_party/blink/web_tests/external/wpt/animation-worklet/worklet-animation-cancel.https.html new file mode 100644 index 0000000..3a28c75 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/animation-worklet/worklet-animation-cancel.https.html
@@ -0,0 +1,45 @@ +<html class="reftest-wait"> +<title>Canceling a playing WorkletAnimation should remove the effect</title> +<link rel="help" href="https://drafts.css-houdini.org/css-animationworklet/"> +<meta name="assert" content="Canceling a playing animation should remove the effect"> +<link rel="match" href="worklet-animation-cancel-ref.html"> + +<script src="/web-animations/testcommon.js"></script> +<script src="/common/reftest-wait.js"></script> +<script src="common.js"></script> + +<style> + #box { + width: 100px; + height: 100px; + background-color: blue; + } +</style> + +<div id="box"></div> + +<script> + registerConstantLocalTimeAnimator(500).then(_ => { + const box = document.getElementById('box'); + const effect = new KeyframeEffect(box, + [ + {transform: 'translateY(0)'}, + {transform: 'translateY(200px)'} + ], { + duration: 1000, + iterations: Infinity + } + ); + + const animation = new WorkletAnimation('constant_time', effect); + animation.play(); + + waitForAsyncAnimationFrames(1).then(_ => { + // Canceling a playing animation should remove the effect. + animation.cancel(); + waitForAsyncAnimationFrames(1).then(_ => { + takeScreenshot(); + }); + }); + }); +</script>
diff --git a/third_party/blink/web_tests/external/wpt/animation-worklet/worklet-animation-creation.https.html b/third_party/blink/web_tests/external/wpt/animation-worklet/worklet-animation-creation.https.html new file mode 100644 index 0000000..3e403fe --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/animation-worklet/worklet-animation-creation.https.html
@@ -0,0 +1,126 @@ +<!DOCTYPE html> +<title>Verify that WorkletAnimation is correctly created</title> +<link rel="help" href="https://drafts.css-houdini.org/css-animationworklet/"> + +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<script src="/web-animations/testcommon.js"></script> +<script src="common.js"></script> + +<style> + .scroller { + height: 100px; + width: 100px; + overflow: scroll; + } + .content { + height: 500px; + width: 500px; + } +</style> + +<script> +function CreateKeyframeEffect(element) { + return new KeyframeEffect( + element, + [ + { transform: 'translateY(0%)' }, + { transform: 'translateY(100%)' } + ], + { duration: 3000, fill: 'forwards' } + ); +} +</script> +<script id="simple_animate" type="text/worklet"> + registerAnimator("test-animator", class { + animate(currentTime, effect) {} + }); +</script> + +<div id='element'></div> +<div id='element2'></div> +<div class='scroller'> + <div class='content'></div> +</div> + +<script> + promise_test(async t => { + await runInAnimationWorklet(document.getElementById('simple_animate').textContent); + let effect = CreateKeyframeEffect(document.querySelector('#element')); + let workletAnimation = new WorkletAnimation('test-animator', effect); + assert_equals(workletAnimation.playState, 'idle'); + assert_equals(workletAnimation.timeline, document.timeline); + }, 'WorkletAnimation creation without timeline should use default documentation timeline'); + + promise_test(async t => { + await runInAnimationWorklet(document.getElementById('simple_animate').textContent); + let effect = CreateKeyframeEffect(document.querySelector('#element')); + let workletAnimation = new WorkletAnimation('test-animator', effect); + assert_equals(workletAnimation.playState, 'idle'); + }, 'WorkletAnimation creation with timeline should work'); + + promise_test(async t => { + await runInAnimationWorklet(document.getElementById('simple_animate').textContent); + let effect = CreateKeyframeEffect(document.querySelector('#element')); + let options = { my_param: 'foo', my_other_param: true }; + let workletAnimation = new WorkletAnimation( + 'test-animator', effect, document.timeline, options); + assert_equals(workletAnimation.playState, 'idle'); + }, 'WorkletAnimation creation with timeline and options should work'); + + promise_test(async t => { + await runInAnimationWorklet(document.getElementById('simple_animate').textContent); + let effect = CreateKeyframeEffect(document.querySelector('#element')); + let scroller = document.querySelector('.scroller'); + let scrollTimeline = new ScrollTimeline( + { scrollSource: scroller, timeRange: 100, orientation: 'inline' }); + let workletAnimation = new WorkletAnimation( + 'test-animator', effect, scrollTimeline); + assert_equals(workletAnimation.playState, 'idle'); + }, 'ScrollTimeline is a valid timeline for a WorkletAnimation'); + + promise_test(async t => { + await runInAnimationWorklet(document.getElementById('simple_animate').textContent); + let constructorFunc = function() { new WorkletAnimation( + 'test-animator', []); }; + assert_throws('NotSupportedError', constructorFunc); + }, 'If there are no effects specified, object construction should fail'); + + promise_test(async t => { + await runInAnimationWorklet(document.getElementById('simple_animate').textContent); + let effect = CreateKeyframeEffect(document.querySelector('#element')); + + let otherDoc = document.implementation.createHTMLDocument(); + let otherElement = otherDoc.createElement('div'); + otherDoc.body.appendChild(otherElement); + let otherEffect = CreateKeyframeEffect(otherElement); + + let constructorFunc = function() { new WorkletAnimation( + 'test-animator', [ effect, otherEffect ]); }; + assert_throws('NotSupportedError', constructorFunc); + }, 'If the effects are from different documents, object construction should fail'); + + promise_test(async t => { + await runInAnimationWorklet(document.getElementById('simple_animate').textContent); + // TODO(crbug.com/781816): Allow KeyframeEffects with no target in AnimationWorklet. + let effect = CreateKeyframeEffect(null); + let effect2 = CreateKeyframeEffect(document.querySelector('#element')); + + let constructorFunc = function() { new WorkletAnimation( + 'test-animator', [ effect, effect2 ]); }; + assert_throws('NotSupportedError', constructorFunc); + + let constructorFunc2 = function() { new WorkletAnimation( + 'test-animator', [ effect2, effect ]); }; + assert_throws('NotSupportedError', constructorFunc2); + }, 'If an effect has no target, object construction should fail'); + + promise_test(async t => { + await runInAnimationWorklet(document.getElementById('simple_animate').textContent); + let effect = CreateKeyframeEffect(document.querySelector('#element')); + let constructorFunc = function() { + new WorkletAnimation('unregistered-animator', effect); + }; + assert_throws('InvalidStateError', constructorFunc); + }, 'Constructing worklet animation for unregisested animator should throw'); +</script>
diff --git a/third_party/blink/web_tests/external/wpt/animation-worklet/worklet-animation-duration-ref.html b/third_party/blink/web_tests/external/wpt/animation-worklet/worklet-animation-duration-ref.html new file mode 100644 index 0000000..81b01bd --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/animation-worklet/worklet-animation-duration-ref.html
@@ -0,0 +1,12 @@ +<!DOCTYPE html> +<title>Reference for WorkletAnimation should continue to be in effect forever, even if its duration is passed</title> +<style> +#box { + width: 100px; + height: 100px; + background-color: green; + transform: translateY(100px); +} +</style> + +<div id="box"></div>
diff --git a/third_party/blink/web_tests/external/wpt/animation-worklet/worklet-animation-duration.https.html b/third_party/blink/web_tests/external/wpt/animation-worklet/worklet-animation-duration.https.html new file mode 100644 index 0000000..1526004e --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/animation-worklet/worklet-animation-duration.https.html
@@ -0,0 +1,40 @@ +<html> +<title>WorkletAnimation should continue to be in effect forever, even if its duration is passed</title> +<link rel="help" href="https://drafts.css-houdini.org/css-animationworklet/"> +<link rel="match" href="worklet-animation-duration-ref.html"> + +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<script src="/web-animations/testcommon.js"></script> +<script src="common.js"></script> + +<div id="box"></div> + +<script> + promise_test(async t => { + await registerConstantLocalTimeAnimator(0.5); + + const box = document.getElementById('box'); + const effect = new KeyframeEffect(box, + [ + {transform: 'translateY(0px)' }, + {transform: 'translateY(200px)' } + ], { + duration: 1, + } + ); + + const animation = new WorkletAnimation('constant_time', effect); + animation.play(); + + let expected_transform = "matrix(1, 0, 0, 1, 0, 100)"; + await waitForAnimationFrameWithCondition(_ => { + return getComputedStyle(box).transform == expected_transform; + }); + + // The animation is specified to last for 1 millisecond + await new Promise(resolve => step_timeout(resolve, 500)); + + assert_equals(getComputedStyle(document.getElementById("box")).transform, expected_transform); + }, "WorkletAnimation should continue to be in effect forever, even if its duration is passed"); +</script>
diff --git a/third_party/blink/web_tests/external/wpt/animation-worklet/worklet-animation-start-delay-ref.html b/third_party/blink/web_tests/external/wpt/animation-worklet/worklet-animation-start-delay-ref.html new file mode 100644 index 0000000..efef6f8 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/animation-worklet/worklet-animation-start-delay-ref.html
@@ -0,0 +1,12 @@ +<!DOCTYPE html> +<title>Reference for WorkletAnimation should respect delay given in options</title> +<style> +.box { + width: 100px; + height: 100px; + background-color: green; +} +</style> + +<div class="box"></div> +<div style="transform: translateX(100px);" class="box"></div>
diff --git a/third_party/blink/web_tests/external/wpt/animation-worklet/worklet-animation-start-delay.https.html b/third_party/blink/web_tests/external/wpt/animation-worklet/worklet-animation-start-delay.https.html new file mode 100644 index 0000000..c8683f7d --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/animation-worklet/worklet-animation-start-delay.https.html
@@ -0,0 +1,64 @@ +<html class="reftest-wait"> +<title>WorkletAnimation should respect delay given in options</title> +<link rel="help" href="https://drafts.css-houdini.org/css-animationworklet/"> +<meta name="assert" content="Worklet Animation should respect delay given in options"> +<link rel="match" href="worklet-animation-start-delay-ref.html"> + +<script src="/web-animations/testcommon.js"></script> +<script src="/common/reftest-wait.js"></script> +<script src="common.js"></script> + +<style> + .box { + width: 100px; + height: 100px; + background-color: green; + } +</style> + +<div id="t0" class="box"></div> +<div id="t1" class="box"></div> +<div id="out"></div> +<script id="visual_update" type="text/worklet"> + registerAnimator("t0_animator", class { + animate(currentTime, effect) { + effect.localTime = 500; + } + }); + + registerAnimator("t1_animator", class { + animate(currentTime, effect) { + effect.localTime = 5500; + } + }); +</script> + +<script> + runInAnimationWorklet( + document.getElementById('visual_update').textContent + ).then(()=>{ + const keyframes = [ + {transform: 'translateX(0)' }, + {transform: 'translateX(200px)' } + ]; + const options = { + duration: 1000, + delay: 5000, + }; + + const $t0 = document.getElementById('t0'); + const $t0_effect = new KeyframeEffect($t0, keyframes, options); + const $t0_animation = new WorkletAnimation('t0_animator', $t0_effect); + + const $t1 = document.getElementById('t1'); + const $t1_effect = new KeyframeEffect($t1, keyframes, options); + const $t1_animation = new WorkletAnimation('t1_animator', $t1_effect); + + $t0_animation.play(); + $t1_animation.play(); + + waitForAsyncAnimationFrames(1).then(_ => { + takeScreenshot(); + }); + }); +</script>
diff --git a/third_party/blink/web_tests/external/wpt/domparsing/XMLSerializer-serializeToString-expected.txt b/third_party/blink/web_tests/external/wpt/domparsing/XMLSerializer-serializeToString-expected.txt index 74a15ed0..0861a3b 100644 --- a/third_party/blink/web_tests/external/wpt/domparsing/XMLSerializer-serializeToString-expected.txt +++ b/third_party/blink/web_tests/external/wpt/domparsing/XMLSerializer-serializeToString-expected.txt
@@ -2,6 +2,7 @@ PASS check XMLSerializer.serializeToString method could parsing xmldoc to string PASS Check if the default namespace is correctly reset. PASS Check if there is no redundant empty namespace declaration. +FAIL Check if redundant xmlns="..." is dropped. assert_equals: expected "<root><child/></root>" but got "<root><child xmlns=\"\"/></root>" PASS Check if inconsistent xmlns="..." is dropped. PASS Check if an attribute with namespace and no prefix is serialized with the nearest-declared prefix FAIL Check if an attribute with namespace and no prefix is serialized with the nearest-declared prefix even if the prefix is assigned to another namespace. assert_equals: expected "<el1 xmlns:p=\"u1\" xmlns:q=\"u1\"><el2 xmlns:q=\"u2\" q:name=\"v\"/></el1>" but got "<el1 xmlns:p=\"u1\" xmlns:q=\"u1\"><el2 xmlns:q=\"u2\" p:name=\"v\"/></el1>"
diff --git a/third_party/blink/web_tests/external/wpt/domparsing/XMLSerializer-serializeToString.html b/third_party/blink/web_tests/external/wpt/domparsing/XMLSerializer-serializeToString.html index 81df61f..cb8ed93 100644 --- a/third_party/blink/web_tests/external/wpt/domparsing/XMLSerializer-serializeToString.html +++ b/third_party/blink/web_tests/external/wpt/domparsing/XMLSerializer-serializeToString.html
@@ -46,6 +46,15 @@ }, 'Check if there is no redundant empty namespace declaration.'); test(function() { + assert_equals(serialize(parse('<root><child xmlns=""/></root>')), + '<root><child/></root>'); + assert_equals(serialize(parse('<root xmlns=""><child xmlns=""/></root>')), + '<root><child/></root>'); + assert_equals(serialize(parse('<root xmlns="u1"><child xmlns="u1"/></root>')), + '<root xmlns="u1"><child/></root>'); +}, 'Check if redundant xmlns="..." is dropped.'); + +test(function() { const root = parse('<root xmlns="uri1"/>'); const child = root.ownerDocument.createElement('child'); child.setAttributeNS(XMLNS_URI, 'xmlns', 'FAIL1'); @@ -145,8 +154,6 @@ test(function() { assert_equals(serialize(parse('<root><child/></root>')), '<root><child/></root>'); - assert_equals(serialize(parse('<root><child xmlns=""/></root>')), '<root><child/></root>'); - assert_equals(serialize(parse('<root xmlns="u1"><child xmlns="u1"/></root>')), '<root xmlns="u1"><child/></root>'); assert_equals(serialize(parse('<root xmlns="u1"><p:child xmlns:p="u1"/></root>')), '<root xmlns="u1"><child xmlns:p="u1"/></root>'); }, 'Check if start tag serialization drops element prefix if the namespace is same as inherited default namespace.');
diff --git a/third_party/blink/web_tests/external/wpt/element-timing/observe-video-poster.html b/third_party/blink/web_tests/external/wpt/element-timing/observe-video-poster.html new file mode 100644 index 0000000..4096138 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/element-timing/observe-video-poster.html
@@ -0,0 +1,31 @@ +<!DOCTYPE HTML> +<meta charset=utf-8> +<title>Element Timing: observe video poster image</title> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<script src="resources/element-timing-helpers.js"></script> +<script> +let beforeRender; +async_test(function (t) { + const observer = new PerformanceObserver( + t.step_func_done(function(entryList) { + assert_equals(entryList.getEntries().length, 1); + const entry = entryList.getEntries()[0]; + const index = window.location.href.lastIndexOf('/'); + const pathname = window.location.href.substring(0, index) + + '/resources/circle.svg'; + checkElement(entry, pathname, 'my_poster', beforeRender); + // Assume viewport has size at least 200, so the element is fully visible. + checkRect(entry, [0, 200, 0, 200]); + }) + ); + observer.observe({entryTypes: ['element']}); + beforeRender = performance.now(); +}, "Able to observe a video's poster image."); +</script> +<style> +body { + margin: 0; +} +</style> +<video elementtiming='my_poster' src='/media/test.mp4' poster='resources/circle.svg'/>
diff --git a/third_party/blink/web_tests/external/wpt/html/browsers/browsing-the-web/read-media/pageload-image-in-popup.html b/third_party/blink/web_tests/external/wpt/html/browsers/browsing-the-web/read-media/pageload-image-in-popup.html index 4d81119..e928482 100644 --- a/third_party/blink/web_tests/external/wpt/html/browsers/browsing-the-web/read-media/pageload-image-in-popup.html +++ b/third_party/blink/web_tests/external/wpt/html/browsers/browsing-the-web/read-media/pageload-image-in-popup.html
@@ -13,18 +13,7 @@ var t = async_test("The document for a standalone media file should have one child in the body."); var imgwin = window.open('/images/blue.png'); - // imgwin.onload doesn't work, check popup's URL to see if the loading of - // the image and creation of image document is finished. - function checkURL() { - if (imgwin.location.href.indexOf('blue.png') == -1) { - step_timeout(checkURL, 100); - return; - } - t.step(frameLoaded); - } - checkURL(); - - function frameLoaded() { + imgwin.onload = t.step_func_done(function() { assert_equals(imgwin.opener, window); assert_equals(imgwin.document.contentType, "image/png"); var imgwinChildren = imgwin.document.body.childNodes; @@ -33,8 +22,7 @@ assert_equals(imgwinChildren[0].namespaceURI, "http://www.w3.org/1999/xhtml", "Only child of body must be an HTML element"); imgwin.close(); - t.done(); - } + }); </script> </head> <body>
diff --git a/third_party/blink/web_tests/external/wpt/portals/portal-activate-data.html b/third_party/blink/web_tests/external/wpt/portals/portal-activate-data.html new file mode 100644 index 0000000..e2417cb7 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/portals/portal-activate-data.html
@@ -0,0 +1,65 @@ +<!DOCTYPE html> +<title>Tests passing of data along with portal activation</title> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<script> +function nextMessage(target) { + return new Promise((resolve, reject) => { + target.addEventListener('message', e => resolve(e), {once: true}); + }); +} + +async function openPortalAndActivate(logic, activateOptions) { + const bc = new BroadcastChannel('portal-activate-data'); + const w = window.open(); + try { + const portal = w.document.createElement('portal'); + portal.src = new URL('resources/portal-activate-data-portal.html?logic=' + encodeURIComponent(logic), location.href); + w.document.body.appendChild(portal); + assert_equals((await nextMessage(bc)).data, 'ready'); + await portal.activate(activateOptions); + return (await nextMessage(bc)).data; + } finally { + w.close(); + bc.close(); + } +} + +promise_test(async () => { + const {echo} = await openPortalAndActivate( + 'return {echo: event.data}', + {data: 'banana'}); + assert_equals(echo, 'banana'); +}, "A string can be passed through activate data."); + +promise_test(async () => { + let {port1, port2} = new MessageChannel(); + let replyViaPort = nextMessage(port1); + port1.start(); + let ok = await openPortalAndActivate( + 'let port2 = event.data; port2.postMessage(42); return true;', + {data: port2, transfer: [port2]}); + assert_true(ok); + assert_equals((await replyViaPort).data, 42); +}, "A message port can be passed through activate data."); + +if (window.SharedArrayBuffer) { + promise_test(async t => { + await promise_rejects( + t, 'DataCloneError', + openPortalAndActivate('', {data: new SharedArrayBuffer})); + }, "A SharedArrayBuffer cannot be passed through activate data."); +} + +promise_test(async t => { + await promise_rejects( + t, new Error, + openPortalAndActivate('', {data: {get a() { throw new Error; }}})); +}, "Uncloneable data has its exception propagated."); + +promise_test(async t => { + await promise_rejects( + t, new TypeError, + openPortalAndActivate('', {data: null, transfer: [null]})); +}, "Errors during transfer list processing are propagated."); +</script>
diff --git a/third_party/blink/web_tests/external/wpt/portals/resources/portal-activate-data-portal.html b/third_party/blink/web_tests/external/wpt/portals/resources/portal-activate-data-portal.html new file mode 100644 index 0000000..cba38a00 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/portals/resources/portal-activate-data-portal.html
@@ -0,0 +1,13 @@ +<!DOCTYPE html> +<script> +const bc = new BroadcastChannel('portal-activate-data'); +let logic = new Function('event', (new URL(location)).searchParams.get('logic')); +onload = () => bc.postMessage('ready'); +onportalactivate = event => { + try { + bc.postMessage(logic(event)); + } finally { + bc.close(); + } +}; +</script>
diff --git a/third_party/blink/web_tests/external/wpt/screen-orientation/event-before-promise.html b/third_party/blink/web_tests/external/wpt/screen-orientation/event-before-promise.html index d876b0c8..51b41e1 100644 --- a/third_party/blink/web_tests/external/wpt/screen-orientation/event-before-promise.html +++ b/third_party/blink/web_tests/external/wpt/screen-orientation/event-before-promise.html
@@ -19,5 +19,6 @@ ]); assert_true(result instanceof Event, "Expected an instance of Event"); + return document.exitFullscreen(); }, "The 'change' event must fire before the [[orientationPendingPromise]] is resolved."); </script>
diff --git a/third_party/blink/web_tests/external/wpt/screen-orientation/orientation-reading.html b/third_party/blink/web_tests/external/wpt/screen-orientation/orientation-reading.html index 574258f..2a31203d 100644 --- a/third_party/blink/web_tests/external/wpt/screen-orientation/orientation-reading.html +++ b/third_party/blink/web_tests/external/wpt/screen-orientation/orientation-reading.html
@@ -78,6 +78,9 @@ }, "Test that screen.orientation is always the same object"); promise_test(async t => { + await test_driver.bless("request full screen", () => { + return document.documentElement.requestFullscreen(); + }); const orientation = screen.orientation; const orientationType = screen.orientation.type; const orientationAngle = screen.orientation.angle; @@ -96,5 +99,6 @@ assert_not_equals(screen.orientation.type, orientationType); assert_not_equals(screen.orientation.angle, orientationAngle); screen.orientation.unlock(); + return document.exitFullscreen(); }, "Test that screen.orientation values change if the orientation changes"); </script>
diff --git a/third_party/blink/web_tests/fast/events/dispatchEvent-crash.html b/third_party/blink/web_tests/fast/events/dispatchEvent-crash.html index 33765e8..b695fdf 100644 --- a/third_party/blink/web_tests/fast/events/dispatchEvent-crash.html +++ b/third_party/blink/web_tests/fast/events/dispatchEvent-crash.html
@@ -4,7 +4,8 @@ testRunner.dumpAsText(); // FIXME: this should also test WorkerContext and MessagePort. - var eventTargets = [new XMLHttpRequest, (new XMLHttpRequest).upload, window.applicationCache, new Worker("about:blank"), document.body]; + var workerScriptBlob = new Blob([], {type: 'application/javascript'}); + var eventTargets = [new XMLHttpRequest, (new XMLHttpRequest).upload, window.applicationCache, new Worker(URL.createObjectURL(workerScriptBlob)), document.body]; for (var i = 0; i < eventTargets.length; ++i) { eventTarget = eventTargets[i];
diff --git a/third_party/blink/web_tests/fast/events/touch/resources/touch-handler-iframe-plugin-assert.js b/third_party/blink/web_tests/fast/events/touch/resources/touch-handler-iframe-plugin-assert.js index 363d6b61a..72667f91 100644 --- a/third_party/blink/web_tests/fast/events/touch/resources/touch-handler-iframe-plugin-assert.js +++ b/third_party/blink/web_tests/fast/events/touch/resources/touch-handler-iframe-plugin-assert.js
@@ -2,13 +2,10 @@ window.jsTestIsAsync = true; -function onDone() -{ - finishJSTest(); -} - var frameElem = document.getElementById('frame'); -frameElem.addEventListener('load', function() { - frameElem.src = 'about:blank'; - window.setTimeout(onDone, 0); -}); +function onDone() { + frameElem.removeEventListener('load', onDone); + frameElem.src = 'about:blank'; + window.setTimeout(() => finishJSTest(), 0); +} +frameElem.addEventListener('load', onDone);
diff --git a/third_party/blink/web_tests/fullscreen/rendering/backdrop-object.html b/third_party/blink/web_tests/fullscreen/rendering/backdrop-object.html index 17206cc..156cbec1 100644 --- a/third_party/blink/web_tests/fullscreen/rendering/backdrop-object.html +++ b/third_party/blink/web_tests/fullscreen/rendering/backdrop-object.html
@@ -12,6 +12,8 @@ var t = { step_func: func => func() }; trusted_request(t, document.querySelector("object")); document.addEventListener("fullscreenchange", function() { - testRunner.notifyDone(); + document.querySelector("object").addEventListener("load", () => { + testRunner.notifyDone(); + }); }); </script>
diff --git a/third_party/blink/web_tests/http/tests/origin_trials/resources/invalid-os-worker.js b/third_party/blink/web_tests/http/tests/origin_trials/resources/invalid-os-worker.js new file mode 100644 index 0000000..cafbe8c --- /dev/null +++ b/third_party/blink/web_tests/http/tests/origin_trials/resources/invalid-os-worker.js
@@ -0,0 +1,2 @@ +importScripts('origintrials-worker.js'); +expect_failure_worker_invalid_os();
diff --git a/third_party/blink/web_tests/http/tests/origin_trials/resources/origintrials-worker.js b/third_party/blink/web_tests/http/tests/origin_trials/resources/origintrials-worker.js index c5a420c6..c0cfbe7 100644 --- a/third_party/blink/web_tests/http/tests/origin_trials/resources/origintrials-worker.js +++ b/third_party/blink/web_tests/http/tests/origin_trials/resources/origintrials-worker.js
@@ -59,6 +59,20 @@ done(); } +// Test whether the origin-trial-enabled attributes are *NOT* attached in a +// worker where the trial is not enabled for the OS. +expect_failure_worker_invalid_os = () => { + // Use |worker_type| to make the test descriptions unique when multiple + // workers are created in a single test file. + var worker_type = get_worker_type(); + test(() => { + var testObject = self.internals.originTrialsTest(); + assert_false('invalidOSAttribute' in testObject); + assert_equals(testObject.invalidOSAttribute, undefined); + }, 'Invalid OS attribute should not exist in ' + worker_type + ' worker'); + done(); +} + // Test whether the origin-trial-enabled attributes are attached in a worker // where the trial is enabled. // This is deliberately just a minimal set of tests to ensure that trials are
diff --git a/third_party/blink/web_tests/http/tests/origin_trials/resources/origintrials.js b/third_party/blink/web_tests/http/tests/origin_trials/resources/origintrials.js index c8acab4..89f216a 100644 --- a/third_party/blink/web_tests/http/tests/origin_trials/resources/origintrials.js +++ b/third_party/blink/web_tests/http/tests/origin_trials/resources/origintrials.js
@@ -148,6 +148,19 @@ } }; +// These tests verify that any gated parts of the API are not available +// for a trial with invalid OS +expect_failure_invalid_os = (skip_worker) => { + + test(() => { + expect_member_fails('invalidOSAttribute'); + }, 'Invalid OS attribute should not exist, even with the trial token present.'); + + if (!skip_worker) { + fetch_tests_from_worker(new Worker('resources/invalid-os-worker.js')); + } +} + // These tests verify that the API functions correctly with an enabled trial. expect_success = () => {
diff --git a/third_party/blink/web_tests/http/tests/origin_trials/sample-api-invalid-os.html b/third_party/blink/web_tests/http/tests/origin_trials/sample-api-invalid-os.html new file mode 100644 index 0000000..7ff83d5b --- /dev/null +++ b/third_party/blink/web_tests/http/tests/origin_trials/sample-api-invalid-os.html
@@ -0,0 +1,16 @@ +<!DOCTYPE html> +<meta charset="utf-8"> +<title>Test Sample API when the OS is invalid</title> +<!-- Generate this token with the command: +generate_token.py http://127.0.0.1:8000 FrobulateImplied --expire-timestamp=2000000000 +--> +<meta http-equiv="origin-trial" content="AtU8M1FWS2TbBCuG6ArIzseD6TBqls4fru1tJp4GyEMrvd+BgE14uWvstXek2Aw+iUjrl6QM5l/HZgpqEssvjgcAAABaeyJvcmlnaW4iOiAiaHR0cDovLzEyNy4wLjAuMTo4MDAwIiwgImZlYXR1cmUiOiAiRnJvYnVsYXRlSW52YWxpZE9TIiwgImV4cGlyeSI6IDIwMDAwMDAwMDB9" /> +<script src="../resources/testharness.js"></script> +<script src="../resources/testharnessreport.js"></script> +<script src="resources/origintrials.js"></script> +<script> + +// The trial is not enabled on any real OS. +expect_failure_invalid_os(); + +</script> \ No newline at end of file
diff --git a/third_party/blink/web_tests/http/tests/origin_trials/sample-api-script-added.html b/third_party/blink/web_tests/http/tests/origin_trials/sample-api-script-added.html index 21f2382..bd16c8f0 100644 --- a/third_party/blink/web_tests/http/tests/origin_trials/sample-api-script-added.html +++ b/third_party/blink/web_tests/http/tests/origin_trials/sample-api-script-added.html
@@ -13,6 +13,7 @@ // Generate this token with the command: // generate_token.py http://127.0.0.1:8000 Frobulate --expire-timestamp=2000000000 var token = "AlCoOPbezqtrGMzSzbLQC4c+oPqO6yuioemcBPjgcXajF8jtmZr4B8tJRPAARPbsX6hDeVyXCKHzEJfpBXvZgQEAAABReyJvcmlnaW4iOiAiaHR0cDovLzEyNy4wLjAuMTo4MDAwIiwgImZlYXR1cmUiOiAiRnJvYnVsYXRlIiwgImV4cGlyeSI6IDIwMDAwMDAwMDB9"; +var invalid_os_token = "AtU8M1FWS2TbBCuG6ArIzseD6TBqls4fru1tJp4GyEMrvd+BgE14uWvstXek2Aw+iUjrl6QM5l/HZgpqEssvjgcAAABaeyJvcmlnaW4iOiAiaHR0cDovLzEyNy4wLjAuMTo4MDAwIiwgImZlYXR1cmUiOiAiRnJvYnVsYXRlSW52YWxpZE9TIiwgImV4cGlyeSI6IDIwMDAwMDAwMDB9"; // The trial is not enabled, as no token is provided. // - Skip the worker tests, as they will likely fail due to running after the @@ -24,10 +25,15 @@ // Add the token to enable the trial OriginTrialsHelper.add_token(token); +// Add the token for the trial with invalid os +OriginTrialsHelper.add_token(invalid_os_token); // The trial is now enabled, by the token added via script. expect_success(); expect_success_bindings(); expect_success_implied(); +// The trial should not be enabled for |FrobulateInvalidOS| +expect_failure_invalid_os(); + </script>
diff --git a/third_party/blink/web_tests/svg/css/anchor-change-href.svg b/third_party/blink/web_tests/svg/css/anchor-change-href.svg index b460a4c8..b860dad 100644 --- a/third_party/blink/web_tests/svg/css/anchor-change-href.svg +++ b/third_party/blink/web_tests/svg/css/anchor-change-href.svg
@@ -13,31 +13,33 @@ testRunner.waitUntilDone(); } - window.location.hash = "#x"; + window.addEventListener('load', () => { + window.location.hash = "#x"; - requestAnimationFrame(function(){ + requestAnimationFrame(function(){ - // Change href from non-visited to visited link. - getComputedStyle(document.documentElement); - document.querySelector("a").setAttribute("xlink:href", "#x"); + // Change href from non-visited to visited link. + getComputedStyle(document.documentElement); + document.querySelector("a").setAttribute("xlink:href", "#x"); - if (window.internals) { - var resultText = document.getElementById("result1").firstChild; - var elementCount = internals.updateStyleAndReturnAffectedElementCount(); + if (window.internals) { + var resultText = document.getElementById("result1").firstChild; + var elementCount = internals.updateStyleAndReturnAffectedElementCount(); - // The elementCount should have been 2, but visited links are - // not recognized in content_shell, thus the text color doesn't - // change and an inheritance propagation to text element is not - // necessary. Running this test in Chrome will cause a 2-element - // recalc and green text as expected. - if (elementCount == 1) - resultText.data = "PASS"; - else - resultText.data = "FAIL: " + elementCount; - } + // The elementCount should have been 2, but visited links are + // not recognized in content_shell, thus the text color doesn't + // change and an inheritance propagation to text element is not + // necessary. Running this test in Chrome will cause a 2-element + // recalc and green text as expected. + if (elementCount == 1) + resultText.data = "PASS"; + else + resultText.data = "FAIL: " + elementCount; + } - if (window.testRunner) - testRunner.notifyDone(); + if (window.testRunner) + testRunner.notifyDone(); + }); }); </script> </svg>
diff --git a/third_party/blink/web_tests/svg/custom/use-property-synchronization-crash-expected.txt b/third_party/blink/web_tests/svg/custom/use-property-synchronization-crash-expected.txt index b5030386..31496961 100644 --- a/third_party/blink/web_tests/svg/custom/use-property-synchronization-crash-expected.txt +++ b/third_party/blink/web_tests/svg/custom/use-property-synchronization-crash-expected.txt
@@ -1,2 +1,2 @@ CONSOLE ERROR: line 5: Error: <polyline> attribute points: Unexpected end of attribute. Expected number, "0". -CONSOLE ERROR: Error: <polyline> attribute points: Unexpected end of attribute. Expected number, "0". +CONSOLE ERROR: line 11: Error: <polyline> attribute points: Unexpected end of attribute. Expected number, "0".
diff --git a/third_party/blink/web_tests/virtual/outofblink-cors/http/tests/misc/README.txt b/third_party/blink/web_tests/virtual/outofblink-cors/http/tests/misc/README.txt new file mode 100644 index 0000000..24dad54 --- /dev/null +++ b/third_party/blink/web_tests/virtual/outofblink-cors/http/tests/misc/README.txt
@@ -0,0 +1,7 @@ +This directory is for testing out-of-blink CORS implementation. + +We use "http/tests/misc" directory for testing fetch with CORS. + +Foloowing two tests are especially important. +- http/tests/misc/resource-timing-sizes-cors-preflight-worker.html +- http/tests/misc/resource-timing-sizes-cors-preflight.html
diff --git a/third_party/blink/web_tests/webexposed/global-interface-listing-expected.txt b/third_party/blink/web_tests/webexposed/global-interface-listing-expected.txt index 196779e9..f54c843 100644 --- a/third_party/blink/web_tests/webexposed/global-interface-listing-expected.txt +++ b/third_party/blink/web_tests/webexposed/global-interface-listing-expected.txt
@@ -5489,6 +5489,7 @@ method constructor interface PortalActivateEvent : Event attribute @@toStringTag + getter data method constructor interface PortalHost : EventTarget attribute @@toStringTag
diff --git a/third_party/closure_compiler/externs/picture_in_picture.js b/third_party/closure_compiler/externs/picture_in_picture.js new file mode 100644 index 0000000..a91c23a --- /dev/null +++ b/third_party/closure_compiler/externs/picture_in_picture.js
@@ -0,0 +1,73 @@ +// Copyright 2019 The Chromium 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 Picture-in-picture APIs. + * @see https://wicg.github.io/picture-in-picture/ + * @externs + */ + +/** + * @interface + * @extends {EventTarget} + * @see https://wicg.github.io/picture-in-picture/#interface-picture-in-picture-window + */ +function PictureInPictureWindow() {} + +/** @type {number} */ +PictureInPictureWindow.prototype.width; + +/** @type {number} */ +PictureInPictureWindow.prototype.length; + +/** @type {?function(!Event)} */ +PictureInPictureWindow.prototype.onresize; + +/** + * @see https://wicg.github.io/picture-in-picture/#htmlvideoelement-extensions + * @return {!Promise<!PictureInPictureWindow>} + */ +HTMLVideoElement.prototype.requestPictureInPicture = function() {}; + +/** + * @type {?function(!Event)} + * @see https://wicg.github.io/picture-in-picture/#htmlvideoelement-extensions + */ +HTMLVideoElement.prototype.onenterpictureinpicture; + +/** + * @type {?function(!Event)} + * @see https://wicg.github.io/picture-in-picture/#htmlvideoelement-extensions + */ +HTMLVideoElement.prototype.onleavepictureinpicture; + +/** + * @type {boolean} + * @see https://wicg.github.io/picture-in-picture/#htmlvideoelement-extensions + */ +HTMLVideoElement.prototype.autoPictureInPicture; + +/** + * @type {boolean} + * @see https://wicg.github.io/picture-in-picture/#htmlvideoelement-extensions + */ +HTMLVideoElement.prototype.disablePictureInPicture; + +/** + * @type {boolean} + * @see https://wicg.github.io/picture-in-picture/#document-extensions + */ +Document.prototype.pictureInPictureEnabled; + +/** + * @see https://wicg.github.io/picture-in-picture/#document-extensions + * @return {!Promise<void>} + */ +Document.prototype.exitPictureInPicture = function() {}; + +/** + * @type {?HTMLVideoElement} + * @see https://wicg.github.io/picture-in-picture/#documentorshadowroot-extension + */ +Document.prototype.pictureInPictureElement; \ No newline at end of file
diff --git a/third_party/leveldatabase/env_chromium.cc b/third_party/leveldatabase/env_chromium.cc index a65c341a..b43fbca 100644 --- a/third_party/leveldatabase/env_chromium.cc +++ b/third_party/leveldatabase/env_chromium.cc
@@ -1342,6 +1342,8 @@ ~TrackedDBImpl() override { tracker_->DatabaseDestroyed(this, shared_read_cache_use_); + base::ScopedAllowBaseSyncPrimitives allow_base_sync_primitives; + db_.reset(); } const std::string& name() const override { return name_; }
diff --git a/third_party/libprotobuf-mutator/fuzzable_proto_library.gni b/third_party/libprotobuf-mutator/fuzzable_proto_library.gni index 343d0cf..677e4eab 100644 --- a/third_party/libprotobuf-mutator/fuzzable_proto_library.gni +++ b/third_party/libprotobuf-mutator/fuzzable_proto_library.gni
@@ -19,10 +19,10 @@ proto_library("proto_library_" + target_name) { forward_variables_from(invoker, "*") assert(current_toolchain == host_toolchain) - if (!defined(deps)) { - deps = [] + if (!defined(proto_deps)) { + proto_deps = [] } - deps += + proto_deps += [ "//third_party/libprotobuf-mutator:override_lite_runtime_plugin" ] generator_plugin_label = "//third_party/libprotobuf-mutator:override_lite_runtime_plugin" @@ -31,6 +31,7 @@ # The plugin will generate cc, so don't ask for it to be done by protoc. generate_cc = false generate_python = false + extra_configs = [ "//third_party/protobuf:protobuf_config" ] } # Inspired by proto_library.gni's handling of
diff --git a/third_party/metrics_proto/README.chromium b/third_party/metrics_proto/README.chromium index ee80601..24d876d 100644 --- a/third_party/metrics_proto/README.chromium +++ b/third_party/metrics_proto/README.chromium
@@ -1,8 +1,8 @@ Name: Metrics Protos Short Name: metrics_proto URL: This is the canonical public repository -Version: 236649832 -Date: 2019/03/04 UTC +Version: 237544849 +Date: 2019/03/09 UTC License: BSD Security Critical: Yes
diff --git a/third_party/metrics_proto/system_profile.proto b/third_party/metrics_proto/system_profile.proto index 2936414..c876225 100644 --- a/third_party/metrics_proto/system_profile.proto +++ b/third_party/metrics_proto/system_profile.proto
@@ -15,7 +15,7 @@ // Stores information about the user's brower and system configuration. // The system configuration fields are recorded once per client session. -// Next tag: 29 +// Next tag: 30 message SystemProfileProto { // The time when the client was compiled/linked, in seconds since the epoch. optional int64 build_timestamp = 1; @@ -1013,4 +1013,23 @@ // The Chrome package name on Android, if it's different from // "com.android.chrome". optional string app_package_name = 26; + + // Data related to the "Better Together" multi-device features. This is only + // uploaded on Chrome OS. + // Next Tag: 5 + message LinkedAndroidPhoneData { + // The pii-free model name of the phone used for Better Together with this + // device. Will not be set if Better Together is not set up. + optional fixed32 phone_model_name_hash = 1; + + // True if SmartLock is enabled on this Chromebook. + optional bool is_smartlock_enabled = 2; + + // True if Instant Tethering is enabled on this Chromebook. + optional bool is_instant_tethering_enabled = 3; + + // True if Messages integration is enabled on this Chromebook. + optional bool is_messages_enabled = 4; + } + optional LinkedAndroidPhoneData linked_android_phone_data = 29; }
diff --git a/third_party/metrics_proto/ukm/source.proto b/third_party/metrics_proto/ukm/source.proto index 93105d32..21f6ebc 100644 --- a/third_party/metrics_proto/ukm/source.proto +++ b/third_party/metrics_proto/ukm/source.proto
@@ -21,7 +21,7 @@ CHROME = 5; CHROME_EXTENSION = 6; APP = 7; - }; + } // An identifier for the source. This should be unique within a session. optional int64 id = 1;
diff --git a/third_party/visualmetrics/OWNERS b/third_party/visualmetrics/OWNERS deleted file mode 100644 index 5fe3630..0000000 --- a/third_party/visualmetrics/OWNERS +++ /dev/null
@@ -1,2 +0,0 @@ -pmeenan@chromium.org -nyquist@chromium.org
diff --git a/third_party/visualmetrics/README.chromium b/third_party/visualmetrics/README.chromium deleted file mode 100644 index eccbccf..0000000 --- a/third_party/visualmetrics/README.chromium +++ /dev/null
@@ -1,13 +0,0 @@ -Name: VisualMetrics -URL: https://chromium.googlesource.com/external/github.com/WPO-Foundation/visualmetrics -Version: 0 -Revision: 1edde9d2fe203229c895b648fdec355917200ad6 -License: New BSD -License File: NOT_SHIPPED -Security Critical: No - -Description: -Calculate visual performance metrics from a video (Speed Index, etc). - -Local Modifications: -None.
diff --git a/tools/dump_process_memory/analyze_dumps.py b/tools/dump_process_memory/analyze_dumps.py index 666e9da..f5ee16c 100755 --- a/tools/dump_process_memory/analyze_dumps.py +++ b/tools/dump_process_memory/analyze_dumps.py
@@ -8,19 +8,33 @@ its content. """ +import argparse import array import collections import hashlib import logging import os -import struct -import sys import zlib PAGE_SIZE = 1 << 12 +# These are typically only populated with DCHECK() on. +FREED_PATTERNS = { + 0xcccccccc: 'V8', + 0xcdcdcdcd: 'PartitionAlloc zapped', + 0xabababab: 'PartitionAlloc uninitialized', + 0xdeadbeef: 'V8 zapped', + 0x0baddeaf: 'V8 zapped handles', + 0x0baffedf: 'V8 zapped global handles', + 0x0beefdaf: 'V8 zapped from space', + 0xbeefdeef: 'V8 zapped slots', + 0xbadbaddb: 'V8 debug zapped', + 0xfeed1eaf: 'V8 zapped freelist' +} + + def _ReadPage(f): """Reads a page of data from a file. @@ -45,7 +59,7 @@ (str) Pretty printed version, 2 decimal places. """ if x < 1e3: - return str(x) + return '%dB' % x elif 1e3 <= x < 1e6: return '%.2fkB' % (x / 1e3) elif 1e6 <= x < 1e9: @@ -67,9 +81,11 @@ is_swapped: ([bool]) For each page, whether it has been swapped out. compressed_size: ([int]) If a page is not zero, its compressed size. hashes: ([str]) If a page is not zero, its SHA1 hash. + freed: ({'description (str)': size (int)}) Size of freed data, per type. """ __slots__ = ('filename', 'start', 'end', 'pages', 'is_zero', 'is_present', 'is_swapped', 'compressed_size', 'hashes', 'freed') + def __init__(self, filename, start, end): """Init. @@ -82,12 +98,12 @@ self.start = start self.end = end self.pages = (end - start) / PAGE_SIZE - self.is_zero = [False for i in range(self.pages)] - self.is_present = [False for i in range(self.pages)] - self.is_swapped = [False for i in range(self.pages)] - self.compressed_size = [0 for i in range(self.pages)] - self.hashes = [None for i in range(self.pages)] - self.freed = 0 + self.is_zero = [False for _ in range(self.pages)] + self.is_present = [False for _ in range(self.pages)] + self.is_swapped = [False for _ in range(self.pages)] + self.compressed_size = [0 for _ in range(self.pages)] + self.hashes = [None for _ in range(self.pages)] + self.freed = collections.defaultdict(int) def _GetStatsFromFileDump(filename): @@ -99,17 +115,6 @@ Returns: MappingStats for the mapping. """ - # These are typically only populated with DCHECK() on. - FREED_PATTERNS = (0xcccccccc, # V8 - 0xcdcdcdcd, # PartitionAlloc "zapped" - 0xabababab, # PartitionAlloc "uninitialized" - 0xdeadbeef, # V8 "zapped" - 0x0baddeaf, # V8 zapped handles - 0x0baffedf, # V8 zapped global handles - 0x0beefdaf, # V8 zapped from space - 0xbeefdeef, # V8 zapped slots - 0xbadbaddb, # V8 debug zapped - 0xfeed1eaf) # V8 zapped freelist # Dump integrity checks. metadata_filename = filename + '.metadata' pid_start_end = os.path.basename(filename)[:-len('.dump')] @@ -127,7 +132,9 @@ for i in range(result.pages): page = _ReadPage(f) assert len(page) == 1024 - result.freed += 4 * sum(x in FREED_PATTERNS for x in page) + for x in page: + if x in FREED_PATTERNS: + result.freed[FREED_PATTERNS[x]] += 4 is_zero = max(page) == 0 present, swapped = (bool(int(x)) for x in metadata_f.readline().strip()) # Not present, not swapped private anonymous == lazily initialized zero @@ -177,13 +184,21 @@ print -def PrintStats(dumps): - """Logs statistics about a process mappings dump. +AggregateStats = collections.namedtuple( + 'AggregateStats', ('content_to_count', 'pages', 'zero_pages', + 'compressed_size', 'swapped_pages', + 'not_present_pages', 'present_zero_pages', 'freed')) + + +def _AggregateStats(dump_stats): + """Aggreates statistics across dumps. Args: - dumps: ([str]) List of dumps. + dump_stats: ([MappingStats]) Stats from all mappings. + + Returns: + An instance of AggregateStats. """ - dump_stats = [_GetStatsFromFileDump(filename) for filename in dumps] content_to_count = collections.defaultdict(int) total_pages = sum(stats.pages for stats in dump_stats) total_zero_pages = sum(sum(stats.is_zero) for stats in dump_stats) @@ -195,7 +210,10 @@ total_present_zero_pages = sum( sum(x == (True, True) for x in zip(stats.is_zero, stats.is_present)) for stats in dump_stats) - total_freed_space = sum(stats.freed for stats in dump_stats) + total_freed_space = {x: 0 for x in FREED_PATTERNS.values()} + for dump in dump_stats: + for (freed_data_type, value) in dump.freed.items(): + total_freed_space[freed_data_type] += value content_to_count = collections.defaultdict(int) for stats in dump_stats: @@ -203,50 +221,83 @@ if page_hash: content_to_count[page_hash] += 1 - print 'Total pages = %d (%s)' % (total_pages, - _PrettyPrintSize(total_pages * PAGE_SIZE)) + return AggregateStats( + content_to_count=content_to_count, pages=total_pages, + zero_pages=total_zero_pages, compressed_size=total_compressed_size, + swapped_pages=total_swapped_pages, + not_present_pages=total_not_present_pages, + present_zero_pages=total_present_zero_pages, + freed=total_freed_space) + + +def PrintStats(dumps, verbose): + """Logs statistics about a process mappings dump. + + Args: + dumps: ([str]) List of dumps. + verbose: (bool) Verbose output. + """ + dump_stats = [_GetStatsFromFileDump(filename) for filename in dumps] + total = _AggregateStats(dump_stats) + duplicated_pages = sum(x - 1 for x in total.content_to_count.values()) + count_and_hashes = sorted(((v, k) for k, v in total.content_to_count.items()), + reverse=True) + max_common_pages = count_and_hashes[0][0] - 1 + total_size_non_zero_pages = (total.pages - total.zero_pages) * PAGE_SIZE + + print 'Total pages = %d (%s)' % (total.pages, + _PrettyPrintSize(total.pages * PAGE_SIZE)) print 'Total zero pages = %d (%.02f%%)' % ( - total_zero_pages, (100. * total_zero_pages) / total_pages) + total.zero_pages, (100. * total.zero_pages) / total.pages) print 'Total present zero pages = %d (%s)' % ( - total_present_zero_pages, - _PrettyPrintSize(total_present_zero_pages * PAGE_SIZE)) - total_size_non_zero_pages = (total_pages - total_zero_pages) * PAGE_SIZE + total.present_zero_pages, + _PrettyPrintSize(total.present_zero_pages * PAGE_SIZE)) print 'Total size of non-zero pages = %d (%s)' % ( total_size_non_zero_pages, _PrettyPrintSize(total_size_non_zero_pages)) print 'Total compressed size = %d (%.02f%%)' % ( - total_compressed_size, - (100. * total_compressed_size) / total_size_non_zero_pages) - duplicated_pages = sum(x - 1 for x in content_to_count.values()) + total.compressed_size, + (100. * total.compressed_size) / total_size_non_zero_pages) print 'Duplicated non-zero pages = %d' % duplicated_pages - count_and_hashes = sorted(((v, k) for k, v in content_to_count.items()), - reverse=True) - max_common_pages = count_and_hashes[0][0] - 1 print 'Max non-zero pages with the same content = %d' % max_common_pages print 'Swapped pages = %d (%s)' % ( - total_swapped_pages, _PrettyPrintSize(total_swapped_pages * PAGE_SIZE)) + total.swapped_pages, _PrettyPrintSize(total.swapped_pages * PAGE_SIZE)) print 'Non-present pages = %d (%s)' % ( - total_not_present_pages, - _PrettyPrintSize(total_not_present_pages * PAGE_SIZE)) - print 'Freed = %d (%s)' % ( - total_freed_space, _PrettyPrintSize(total_freed_space)) - print 'Top Duplicated Pages:' - for i in range(10): - count, page_hash = count_and_hashes[i] - print '%d common pages' % count - page = _FindPageFromHash(dump_stats, page_hash) - _PrintPage(page) - print + total.not_present_pages, + _PrettyPrintSize(total.not_present_pages * PAGE_SIZE)) + print 'Freed: ' + for k in total.freed: + print ' %s = %d (%s)' % ( + k, total.freed[k], _PrettyPrintSize(total.freed[k])) + + if verbose: + print 'Top Duplicated Pages:' + for i in range(10): + count, page_hash = count_and_hashes[i] + print '%d common pages' % count + page = _FindPageFromHash(dump_stats, page_hash) + _PrintPage(page) + print + + +def _CreateArgumentParser(): + parser = argparse.ArgumentParser() + parser.add_argument('--directory', type=str, required=True, + help='Dumps directory') + parser.add_argument('--verbose', action='store_true', help='Dumps directory') + return parser def main(): logging.basicConfig(level=logging.INFO) - if len(sys.argv) != 2: - logging.error('Usage: %s <dumps_directory>', sys.argv[0]) - sys.exit(1) - directory = sys.argv[1] - dumps = [os.path.join(directory, f) for f in os.listdir(directory) - if f.endswith('.dump')] - PrintStats(dumps) + parser = _CreateArgumentParser() + args = parser.parse_args() + + dumps = [] + for f in os.listdir(args.directory): + if f.endswith('.dump'): + dumps.append(os.path.join(args.directory, f)) + + PrintStats(dumps, args.verbose) if __name__ == '__main__':
diff --git a/tools/mb/mb_config.pyl b/tools/mb/mb_config.pyl index 5efd410a..e2088b7c 100644 --- a/tools/mb/mb_config.pyl +++ b/tools/mb/mb_config.pyl
@@ -132,7 +132,7 @@ 'ToTAndroidOfficial': 'android_clang_tot_release_minimal_symbols_official_optimize', 'ToTAndroid64': 'android_clang_tot_release_arm64', 'ToTAndroid x64': 'android_clang_tot_x64', - 'ToTLinuxOfficial': 'clang_tot_linux_official', + 'ToTLinuxOfficial': 'clang_tot_official', 'ToTLinux': 'clang_tot_linux_full_symbols_shared_release', 'ToTLinuxCoverage': 'clang_tot_coverage_minimal_symbols_shared_release_with_libfuzzer', 'ToTLinux (dbg)': 'clang_tot_shared_debug', @@ -143,6 +143,7 @@ 'ToTLinuxThinLTO': 'clang_tot_release_minimal_symbols_thin_lto_static', 'ToTLinuxUBSanVptr': 'clang_tot_edge_ubsan_no_recover_hack_static_release', 'ToTMac': 'clang_tot_minimal_symbols_shared_release', + 'ToTMacOfficial': 'clang_tot_official', 'ToTMacCoverage': 'clang_tot_coverage_minimal_symbols_shared_release', 'ToTMac (dbg)': 'clang_tot_shared_debug', 'ToTMacASan': 'asan_disable_nacl_clang_tot_minimal_symbols_static_release', @@ -1210,7 +1211,7 @@ 'clang_tot', 'full_symbols', 'shared', 'release', ], - 'clang_tot_linux_official': [ + 'clang_tot_official': [ 'clang_tot', 'official', ],
diff --git a/tools/metrics/histograms/enums.xml b/tools/metrics/histograms/enums.xml index 866f1024..99cf78e9 100644 --- a/tools/metrics/histograms/enums.xml +++ b/tools/metrics/histograms/enums.xml
@@ -15989,6 +15989,7 @@ <int value="532" label="DeviceWilcoDtcAllowed"/> <int value="533" label="AllowPopupsDuringPageUnload"/> <int value="534" label="RemoteAccessHostAllowFileTransfer"/> + <int value="535" label="DeviceWilcoDtcConfig"/> </enum> <enum name="EnterprisePolicyInvalidations">
diff --git a/tools/metrics/histograms/histograms.xml b/tools/metrics/histograms/histograms.xml index 1c9ea4c0..cdf0946 100644 --- a/tools/metrics/histograms/histograms.xml +++ b/tools/metrics/histograms/histograms.xml
@@ -110465,6 +110465,9 @@ </histogram> <histogram base="true" name="SimpleCache.EntryOperationsPending"> + <obsolete> + Removed 2019-03. + </obsolete> <owner>morlovich@chromium.org</owner> <summary> At the time that operations are run, the number of pending operations on a @@ -126445,8 +126448,9 @@ <owner>adamk@chromium.org</owner> <owner>ahaas@chromium.org</owner> <summary> - The amount of address space reserved by WebAssembly.Memory backing stores in - MiB. + The total amount of address space reserved by the backing stores of all live + WebAssembly.Memory backing stores in MiB. Recorded on each memory + reservation. </summary> </histogram> @@ -126455,7 +126459,8 @@ <owner>adamk@chromium.org</owner> <owner>clemensh@chromium.org</owner> <summary> - Time to compile a WebAssembly function. + Time to compile a WebAssembly function. Recorded on each compilation of a + single function, either synchronous, asynchronous, or lazily. Warning: This metric may include reports from clients with low-resolution clocks (i.e. on Windows, ref. |TimeTicks::IsHighResolution()|). Such reports @@ -126469,7 +126474,10 @@ <owner>titzer@chromium.org</owner> <owner>adamk@chromium.org</owner> <owner>clemensh@chromium.org</owner> - <summary>Peak memory used to compile a WebAssembly function.</summary> + <summary> + Peak memory used to compile a WebAssembly function. Recorded for each + TurboFan compilation of a WebAssembly function. + </summary> </histogram> <histogram name="V8.WasmCompileModuleMicroSeconds" units="microseconds"> @@ -126477,7 +126485,8 @@ <owner>adamk@chromium.org</owner> <owner>clemensh@chromium.org</owner> <summary> - Time to compile a WebAssembly module. + Time to compile a WebAssembly module. Recorded on each synchronous + WebAssembly compilation. Warning: This metric may include reports from clients with low-resolution clocks (i.e. on Windows, ref. |TimeTicks::IsHighResolution()|). Such reports @@ -126492,7 +126501,8 @@ <owner>adamk@chromium.org</owner> <owner>clemensh@chromium.org</owner> <summary> - Time to decode a WebAssembly function. + Time to decode a WebAssembly function. Recorded on each validation of a + WebAssembly function. Warning: This metric may include reports from clients with low-resolution clocks (i.e. on Windows, ref. |TimeTicks::IsHighResolution()|). Such reports @@ -126507,7 +126517,8 @@ <owner>adamk@chromium.org</owner> <owner>clemensh@chromium.org</owner> <summary> - Time to decode a WebAssembly module. + Time to decode a WebAssembly module. Recorded for each WebAssembly module + which is decoded for validation, compilation, or deserialization. Warning: This metric may include reports from clients with low-resolution clocks (i.e. on Windows, ref. |TimeTicks::IsHighResolution()|). Such reports @@ -126521,14 +126532,19 @@ <owner>titzer@chromium.org</owner> <owner>adamk@chromium.org</owner> <owner>clemensh@chromium.org</owner> - <summary>Peak memory used to decode a WebAssembly module.</summary> + <summary> + Peak memory used to decode a WebAssembly module. Recorded for each + WebAssembly module which is decoded for validation, compilation, or + deserialization. + </summary> </histogram> <histogram name="V8.WasmExecutionTimeMicroSeconds" units="microseconds"> + <obsolete> + Deprecated 03/2019. No longer tracked. + </obsolete> <owner>titzer@chromium.org</owner> <owner>adamk@chromium.org</owner> - <owner>herhut@chromium.org</owner> - <owner>kschimpf@chromium.org</owner> <summary> Time spent executing WebAssembly. @@ -126544,14 +126560,20 @@ <owner>titzer@chromium.org</owner> <owner>adamk@chromium.org</owner> <owner>clemensh@chromium.org</owner> - <summary>Size of a WebAssembly function in bytes.</summary> + <summary> + Size of a WebAssembly function in bytes. Recorded on each compilation of a + single function, either synchronous, asynchronous, or lazily. + </summary> </histogram> <histogram name="V8.WasmFunctionsPerModule" units="functions"> <owner>titzer@chromium.org</owner> <owner>adamk@chromium.org</owner> <owner>clemensh@chromium.org</owner> - <summary>Function count per WebAssembly module.</summary> + <summary> + Function count per WebAssembly module. Recorded for each WebAssembly module + which is decoded for validation, compilation, or deserialization. + </summary> </histogram> <histogram name="V8.WasmInstantiateModuleMicroSeconds" units="microseconds"> @@ -126559,7 +126581,8 @@ <owner>adamk@chromium.org</owner> <owner>clemensh@chromium.org</owner> <summary> - Time to instantiate a WebAssembly module. + Time to instantiate a WebAssembly module. Recorded on each instantiation of + a WebAssembly module. Warning: This metric may include reports from clients with low-resolution clocks (i.e. on Windows, ref. |TimeTicks::IsHighResolution()|). Such reports @@ -126604,7 +126627,7 @@ <owner>ahaas@chromium.org</owner> <summary> Number of 64KiB pages a WebAssembly module declares as its maximum - requirement. + requirement. Recorded on each instantiation of a WebAssembly module. </summary> </histogram> @@ -126613,7 +126636,8 @@ <owner>adamk@chromium.org</owner> <owner>ahaas@chromium.org</owner> <summary> - The result of attempts to allocate WebAssembly.Memory buffers. + The result of attempts to allocate WebAssembly.Memory buffers. Recorded on + each attempt to allocate a WebAssembly.Memory buffer. </summary> </histogram> @@ -126623,17 +126647,40 @@ <owner>ahaas@chromium.org</owner> <summary> Number of 64KiB pages a WebAssembly module declares as its minimum - requirement. + requirement. Recorded on each instantiation of a WebAssembly module. </summary> </histogram> -<histogram name="V8.WasmModuleCodeSizeMiB" units="MB"> +<histogram name="V8.WasmModuleCodeSizeBaselineMiB" units="MB" + expires_after="2020-03-31"> <owner>titzer@chromium.org</owner> <owner>adamk@chromium.org</owner> <owner>clemensh@chromium.org</owner> <summary> - The amount of code space in MiB used by individual WebAssembly modules. - Recorded for each module on finalization, i.e. when it is garbage-collected. + The amount of generated code in MiB for one WebAssembly module. Recorded + when baseline compilation finished. + </summary> +</histogram> + +<histogram name="V8.WasmModuleCodeSizeMiB" units="MB" + expires_after="2020-03-31"> + <owner>titzer@chromium.org</owner> + <owner>adamk@chromium.org</owner> + <owner>clemensh@chromium.org</owner> + <summary> + The amount of committed code space in MiB used by individual WebAssembly + modules. Recorded for each live module after each full GC. + </summary> +</histogram> + +<histogram name="V8.WasmModuleCodeSizeTopTierMiB" units="MB" + expires_after="2020-03-31"> + <owner>titzer@chromium.org</owner> + <owner>adamk@chromium.org</owner> + <owner>clemensh@chromium.org</owner> + <summary> + The amount of generated code in MiB for one WebAssembly module. Recorded + when top-tier compilation finished. </summary> </histogram> @@ -126641,7 +126688,11 @@ <owner>titzer@chromium.org</owner> <owner>adamk@chromium.org</owner> <owner>ahaas@chromium.org</owner> - <summary>Size of a WebAssembly module.</summary> + <summary> + Size of the wire bytes of a WebAssembly module. Recorded for each + WebAssembly module which is decoded for validation, compilation, or + deserialization. + </summary> </histogram> <histogram name="Variations.CreateTrials.SeedExpiry" @@ -147030,6 +147081,9 @@ </histogram_suffixes> <histogram_suffixes name="SimpleCacheWithOrWithoutIndex" separator="_"> + <obsolete> + Removed as of 2019-03. + </obsolete> <suffix name="WithIndex" label="The Simple Cache index was loaded."/> <suffix name="WithoutIndex" label="The Simple Cache index was not yet loaded."/>
diff --git a/tools/perf/benchmark.csv b/tools/perf/benchmark.csv index 8baf74f..6afd36b5 100644 --- a/tools/perf/benchmark.csv +++ b/tools/perf/benchmark.csv
@@ -1,7 +1,6 @@ AUTOGENERATED FILE DO NOT EDIT See https://bit.ly/update-benchmarks-info to make changes Benchmark name,Individual owners,Component,Documentation,Tags -UNSCHEDULED_oortonline_tbmv2,ulan@chromium.org,,, angle_perftests,"jmadill@chromium.org, chrome-gpu-perf-owners@chromium.org",Internals>GPU>ANGLE,, base_perftests,"skyostil@chromium.org, gab@chromium.org",Internals>SequenceManager,https://chromium.googlesource.com/chromium/src/+/HEAD/base/README.md#performance-testing, blink_perf.accessibility,dmazzoni@chromium.org,Blink>Accessibility,https://bit.ly/blink-perf-benchmarks, @@ -41,7 +40,7 @@ rasterize_and_record_micro.partial_invalidation,"vmpstr@chromium.org, wkorman@chromium.org",Internals>Compositing>Rasterization,, rasterize_and_record_micro.top_25,"vmpstr@chromium.org, wkorman@chromium.org",Internals>Compositing>Rasterization,, rendering.desktop,"sadrul@chromium.org, vmiura@chromium.org",Internals>GPU>Metrics,https://bit.ly/rendering-benchmarks,"backdrop_filter,gpu_rasterization,image_decoding,key_desktop_move,maps,repaint_desktop,representative_mac_desktop,representative_win_desktop,required_webgl,top_real_world_desktop,tough_animation,tough_canvas,tough_compositor,tough_filters,tough_image_decode,tough_path_rendering,tough_pinch_zoom,tough_scheduling,tough_scrolling,tough_texture_upload,tough_webgl,use_fake_camera_device" -rendering.mobile,"sadrul@chromium.org, vmiura@chromium.org",Internals>GPU>Metrics,https://bit.ly/rendering-benchmarks,"backdrop_filter,fastpath,gpu_rasterization,image_decoding,key_hit_test,key_idle_power,key_noop,key_silk,maps,motionmark,pathological_mobile_sites,polymer,representative_mac_desktop,representative_win_desktop,required_webgl,simple_mobile_sites,top_real_world_desktop,top_real_world_mobile,tough_animation,tough_canvas,tough_compositor,tough_filters,tough_image_decode,tough_path_rendering,tough_scheduling,tough_scrolling,tough_texture_upload,tough_webgl,use_fake_camera_device" +rendering.mobile,"sadrul@chromium.org, vmiura@chromium.org",Internals>GPU>Metrics,https://bit.ly/rendering-benchmarks,"backdrop_filter,fastpath,gpu_rasterization,image_decoding,key_hit_test,key_idle_power,key_noop,key_silk,maps,motionmark,pathological_mobile_sites,polymer,representative_mac_desktop,representative_win_desktop,required_webgl,simple_mobile_sites,top_real_world_desktop,top_real_world_mobile,tough_animation,tough_canvas,tough_compositor,tough_filters,tough_image_decode,tough_path_rendering,tough_pinch_zoom_mobile,tough_scheduling,tough_scrolling,tough_texture_upload,tough_webgl,use_fake_camera_device" resource_sizes,"agrieve@chromium.org, rnephew@chromium.org, perezju@chromium.org",,, sizes (linux),thestig@chromium.org,thomasanderson@chromium.org,Internals>PlatformIntegration, sizes (mac),tapted@chromium.org,,,
diff --git a/tools/perf/benchmarks/oortonline.py b/tools/perf/benchmarks/oortonline.py deleted file mode 100644 index 6992961..0000000 --- a/tools/perf/benchmarks/oortonline.py +++ /dev/null
@@ -1,72 +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. - -import re - -import page_sets - -from core import perf_benchmark -from telemetry import benchmark -from telemetry.timeline import chrome_trace_category_filter -from telemetry.timeline import chrome_trace_config -from telemetry.web_perf import timeline_based_measurement - - -@benchmark.Info(emails=['ulan@chromium.org']) -class OortOnlineTBMv2(perf_benchmark.PerfBenchmark): - """OortOnline benchmark that measures WebGL and V8 performance. - URL: http://oortonline.gl/#run - Info: http://v8project.blogspot.de/2015/10/jank-busters-part-one.html - """ - - # Report only V8-specific and overall renderer memory values. Note that - # detailed values reported by the OS (such as native heap) are excluded. - _V8_AND_OVERALL_MEMORY_RE = re.compile( - r'renderer_processes:' - r'(reported_by_chrome:v8|reported_by_os:system_memory:[^:]+$)') - - page_set = page_sets.OortOnlineTBMPageSet - - def CreateCoreTimelineBasedMeasurementOptions(self): - categories = [ - # Implicitly disable all categories. - '-*', - # V8. - 'blink.console', - 'disabled-by-default-v8.gc', - 'renderer.scheduler', - 'v8', - 'webkit.console', - # Smoothness. - 'benchmark', - 'blink', - 'blink.console', - 'trace_event_overhead', - 'webkit.console', - # Memory. - 'blink.console', - 'disabled-by-default-memory-infra' - ] - category_filter = chrome_trace_category_filter.ChromeTraceCategoryFilter( - ','.join(categories)) - options = timeline_based_measurement.Options(category_filter) - options.SetTimelineBasedMetrics([ - 'gcMetric', 'memoryMetric', 'responsivenessMetric']) - # Setting an empty memory dump config disables periodic dumps. - options.config.chrome_trace_config.SetMemoryDumpConfig( - chrome_trace_config.MemoryDumpConfig()) - return options - - # TODO(934227): Remove this benchmark now that it's descheduled. - @classmethod - def Name(cls): - return 'UNSCHEDULED_oortonline_tbmv2' - - @classmethod - def ShouldAddValue(cls, name, _): - if 'memory:chrome' in name: - return bool(cls._V8_AND_OVERALL_MEMORY_RE.search(name)) - if 'animation ' in name: - return 'throughput' in name or 'frameTimeDiscrepancy' in name - return 'v8' in name
diff --git a/tools/perf/core/shard_maps/android_nexus5x_webview_perf_map.json b/tools/perf/core/shard_maps/android_nexus5x_webview_perf_map.json index a43fd386..f9fa993 100644 --- a/tools/perf/core/shard_maps/android_nexus5x_webview_perf_map.json +++ b/tools/perf/core/shard_maps/android_nexus5x_webview_perf_map.json
@@ -70,7 +70,6 @@ "begin": 18 }, "octane": {}, - "oortonline_tbmv2": {}, "power.typical_10_mobile": {}, "rasterize_and_record_micro.partial_invalidation": {}, "rasterize_and_record_micro.top_25": {},
diff --git a/tools/perf/core/shard_maps/android_nexus6_webview_perf_map.json b/tools/perf/core/shard_maps/android_nexus6_webview_perf_map.json index a15807f..0806679f 100644 --- a/tools/perf/core/shard_maps/android_nexus6_webview_perf_map.json +++ b/tools/perf/core/shard_maps/android_nexus6_webview_perf_map.json
@@ -36,7 +36,6 @@ "media.mobile": {}, "memory.top_10_mobile": {}, "octane": {}, - "oortonline_tbmv2": {}, "power.typical_10_mobile": {}, "rasterize_and_record_micro.partial_invalidation": {}, "rasterize_and_record_micro.top_25": {},
diff --git a/tools/perf/core/shard_maps/mac-10_12_laptop_low_end-perf_map.json b/tools/perf/core/shard_maps/mac-10_12_laptop_low_end-perf_map.json index 2815296..1899c41a 100644 --- a/tools/perf/core/shard_maps/mac-10_12_laptop_low_end-perf_map.json +++ b/tools/perf/core/shard_maps/mac-10_12_laptop_low_end-perf_map.json
@@ -74,7 +74,6 @@ "begin": 6 }, "octane": {}, - "oortonline_tbmv2": {}, "power.desktop": { "end": 10 }
diff --git a/tools/perf/core/shard_maps/mac-10_13_laptop_high_end-perf_map.json b/tools/perf/core/shard_maps/mac-10_13_laptop_high_end-perf_map.json index e4af6dac..1f27561 100644 --- a/tools/perf/core/shard_maps/mac-10_13_laptop_high_end-perf_map.json +++ b/tools/perf/core/shard_maps/mac-10_13_laptop_high_end-perf_map.json
@@ -70,7 +70,6 @@ "6": { "benchmarks": { "octane": {}, - "oortonline_tbmv2": {}, "power.desktop": {}, "rasterize_and_record_micro.partial_invalidation": {}, "rasterize_and_record_micro.top_25": {
diff --git a/tools/perf/core/shard_maps/win-10-perf_map.json b/tools/perf/core/shard_maps/win-10-perf_map.json index 16bf4c0..af9f885 100644 --- a/tools/perf/core/shard_maps/win-10-perf_map.json +++ b/tools/perf/core/shard_maps/win-10-perf_map.json
@@ -78,7 +78,6 @@ "7": { "benchmarks": { "octane": {}, - "oortonline_tbmv2": {}, "power.desktop": {}, "rasterize_and_record_micro.partial_invalidation": {}, "rasterize_and_record_micro.top_25": {},
diff --git a/tools/perf/core/undocumented_benchmarks.py b/tools/perf/core/undocumented_benchmarks.py index 9f1ea240..9767e34 100644 --- a/tools/perf/core/undocumented_benchmarks.py +++ b/tools/perf/core/undocumented_benchmarks.py
@@ -22,7 +22,6 @@ 'memory.top_10_mobile', 'net_perftests', 'octane', - 'UNSCHEDULED_oortonline_tbmv2', 'passthrough_command_buffer_perftests', 'performance_browser_tests', 'rasterize_and_record_micro.partial_invalidation',
diff --git a/tools/perf/expectations.config b/tools/perf/expectations.config index 58ad981..2441816 100644 --- a/tools/perf/expectations.config +++ b/tools/perf/expectations.config
@@ -169,9 +169,6 @@ # Benchmark: oilpan_gc_times.sync_scroll.key_mobile_sites_smooth crbug.com/756119 [ All ] oilpan_gc_times.sync_scroll.key_mobile_sites_smooth/digg [ Skip ] -# Benchmark: oortonline -crbug.com/815181 [ Win ] oortonline_tbmv2/http://oortonline.gl/#run [ Skip ] - # Benchmark: rendering.desktop crbug.com/755556 [ Mac ] rendering.desktop/mix_blend_mode_animation_difference [ Skip ] crbug.com/755556 [ Mac ] rendering.desktop/mix_blend_mode_animation_hue [ Skip ]
diff --git a/tools/perf/page_sets/data/rendering_desktop.json b/tools/perf/page_sets/data/rendering_desktop.json index 5d7eeffb0..0f8182d 100644 --- a/tools/perf/page_sets/data/rendering_desktop.json +++ b/tools/perf/page_sets/data/rendering_desktop.json
@@ -4,13 +4,13 @@ "DEFAULT": "rendering_desktop_000.wprgo" }, "accu_weather_pinch_2018": { - "DEFAULT": "rendering_desktop_007.wprgo" + "DEFAULT": "rendering_desktop_f083c0f144.wprgo" }, "amazon_2018": { "DEFAULT": "rendering_desktop_000.wprgo" }, "amazon_pinch_2018": { - "DEFAULT": "rendering_desktop_007.wprgo" + "DEFAULT": "rendering_desktop_f083c0f144.wprgo" }, "analog_clock_svg": { "DEFAULT": "rendering_desktop_002.wprgo" @@ -37,13 +37,13 @@ "DEFAULT": "rendering_desktop_000.wprgo" }, "blogspot_pinch_2018": { - "DEFAULT": "rendering_desktop_007.wprgo" + "DEFAULT": "rendering_desktop_f083c0f144.wprgo" }, "booking.com_2018": { "DEFAULT": "rendering_desktop_000.wprgo" }, "booking_pinch_2018": { - "DEFAULT": "rendering_desktop_007.wprgo" + "DEFAULT": "rendering_desktop_f083c0f144.wprgo" }, "camera_to_webgl": { "DEFAULT": "rendering_desktop_011.wprgo" @@ -70,7 +70,7 @@ "DEFAULT": "rendering_desktop_000.wprgo" }, "cnn_pinch_2018": { - "DEFAULT": "rendering_desktop_007.wprgo" + "DEFAULT": "rendering_desktop_f083c0f144.wprgo" }, "crafty_mind": { "DEFAULT": "rendering_desktop_004.wprgo" @@ -85,7 +85,7 @@ "DEFAULT": "rendering_desktop_000.wprgo" }, "ebay_pinch_2018": { - "DEFAULT": "rendering_desktop_007.wprgo" + "DEFAULT": "rendering_desktop_f083c0f144.wprgo" }, "effect_games": { "DEFAULT": "rendering_desktop_004.wprgo" @@ -94,13 +94,13 @@ "DEFAULT": "rendering_desktop_000.wprgo" }, "espn_pinch_2018": { - "DEFAULT": "rendering_desktop_007.wprgo" + "DEFAULT": "rendering_desktop_f083c0f144.wprgo" }, "facebook_2018": { "DEFAULT": "rendering_desktop_000.wprgo" }, "facebook_pinch_2018": { - "DEFAULT": "rendering_desktop_007.wprgo" + "DEFAULT": "rendering_desktop_f083c0f144.wprgo" }, "filter_terrain_svg": { "DEFAULT": "rendering_desktop_002.wprgo" @@ -115,19 +115,19 @@ "DEFAULT": "rendering_desktop_001.wprgo" }, "gmail_pinch_2018": { - "DEFAULT": "rendering_desktop_007.wprgo" + "DEFAULT": "rendering_desktop_f083c0f144.wprgo" }, "google_calendar_2018": { "DEFAULT": "rendering_desktop_000.wprgo" }, "google_calendar_pinch_2018": { - "DEFAULT": "rendering_desktop_007.wprgo" + "DEFAULT": "rendering_desktop_f083c0f144.wprgo" }, "google_docs_2018": { "DEFAULT": "rendering_desktop_000.wprgo" }, "google_image_pinch_2018": { - "DEFAULT": "rendering_desktop_007.wprgo" + "DEFAULT": "rendering_desktop_f083c0f144.wprgo" }, "google_image_search_2018": { "DEFAULT": "rendering_desktop_000.wprgo" @@ -136,7 +136,7 @@ "DEFAULT": "rendering_desktop_000.wprgo" }, "google_search_pinch_2018": { - "DEFAULT": "rendering_desktop_007.wprgo" + "DEFAULT": "rendering_desktop_f083c0f144.wprgo" }, "google_web_search_2018": { "DEFAULT": "rendering_desktop_000.wprgo" @@ -175,7 +175,7 @@ "DEFAULT": "rendering_desktop_6eb5e5be2a.wprgo" }, "linkedin_pinch_2018": { - "DEFAULT": "rendering_desktop_007.wprgo" + "DEFAULT": "rendering_desktop_f083c0f144.wprgo" }, "man_in_blue": { "DEFAULT": "rendering_desktop_004.wprgo" @@ -289,13 +289,13 @@ "DEFAULT": "rendering_desktop_000.wprgo" }, "twitch_pinch_2018": { - "DEFAULT": "rendering_desktop_007.wprgo" + "DEFAULT": "rendering_desktop_f083c0f144.wprgo" }, "twitter_2018": { "DEFAULT": "rendering_desktop_000.wprgo" }, "twitter_pinch_2018": { - "DEFAULT": "rendering_desktop_007.wprgo" + "DEFAULT": "rendering_desktop_f083c0f144.wprgo" }, "wikipedia_2018": { "DEFAULT": "rendering_desktop_000.wprgo" @@ -310,19 +310,19 @@ "DEFAULT": "rendering_desktop_000.wprgo" }, "yahoo_news_pinch_2018": { - "DEFAULT": "rendering_desktop_007.wprgo" + "DEFAULT": "rendering_desktop_f083c0f144.wprgo" }, "yahoo_sports_2018": { "DEFAULT": "rendering_desktop_000.wprgo" }, "yahoo_sports_pinch_2018": { - "DEFAULT": "rendering_desktop_007.wprgo" + "DEFAULT": "rendering_desktop_f083c0f144.wprgo" }, "youtube_2018": { "DEFAULT": "rendering_desktop_000.wprgo" }, "youtube_pinch_2018": { - "DEFAULT": "rendering_desktop_007.wprgo" + "DEFAULT": "rendering_desktop_f083c0f144.wprgo" } }, "description": "Describes the Web Page Replay archives for a story set. Don't edit by hand! Use record_wpr for updating.",
diff --git a/tools/perf/page_sets/data/rendering_desktop_79afb10dc5.wprgo.sha1 b/tools/perf/page_sets/data/rendering_desktop_79afb10dc5.wprgo.sha1 new file mode 100644 index 0000000..48bc17f --- /dev/null +++ b/tools/perf/page_sets/data/rendering_desktop_79afb10dc5.wprgo.sha1
@@ -0,0 +1 @@ +79afb10dc5da5ddf4aaac8e291a904cc19b3b637 \ No newline at end of file
diff --git a/tools/perf/page_sets/data/rendering_desktop_f083c0f144.wprgo.sha1 b/tools/perf/page_sets/data/rendering_desktop_f083c0f144.wprgo.sha1 new file mode 100644 index 0000000..1416636 --- /dev/null +++ b/tools/perf/page_sets/data/rendering_desktop_f083c0f144.wprgo.sha1
@@ -0,0 +1 @@ +f083c0f144747054e9b0b81d80deb2616eb7c14c \ No newline at end of file
diff --git a/tools/perf/page_sets/data/rendering_mobile.json b/tools/perf/page_sets/data/rendering_mobile.json index 162b4fae..815ae4b 100644 --- a/tools/perf/page_sets/data/rendering_mobile.json +++ b/tools/perf/page_sets/data/rendering_mobile.json
@@ -6,6 +6,9 @@ "accu_weather_desktop_gpu_raster_2018": { "DEFAULT": "rendering_mobile_000.wprgo" }, + "accu_weather_mobile_pinch_2018": { + "DEFAULT": "rendering_mobile_c47e7f29dd.wprgo" + }, "amazon_2018": { "DEFAULT": "rendering_mobile_000.wprgo" }, @@ -117,6 +120,9 @@ "cnn_mobile_2018": { "DEFAULT": "rendering_mobile_011.wprgo" }, + "cnn_mobile_pinch_2018": { + "DEFAULT": "rendering_mobile_c47e7f29dd.wprgo" + }, "cnn_pathological_2018": { "DEFAULT": "rendering_mobile_025.wprgo" }, @@ -150,6 +156,9 @@ "ebay_mobile_2018": { "DEFAULT": "rendering_mobile_011.wprgo" }, + "ebay_mobile_pinch_2018": { + "DEFAULT": "rendering_mobile_c47e7f29dd.wprgo" + }, "ebay_scroll_2018": { "DEFAULT": "rendering_mobile_016.wprgo" }, @@ -234,6 +243,9 @@ "google_plus_mobile_2018": { "DEFAULT": "rendering_mobile_011.wprgo" }, + "google_search_mobile_pinch_2018": { + "DEFAULT": "rendering_mobile_c47e7f29dd.wprgo" + }, "google_web_search_2018": { "DEFAULT": "rendering_mobile_000.wprgo" }, @@ -300,6 +312,9 @@ "linkedin_mobile_2018": { "DEFAULT": "rendering_mobile_d5f51fba2e.wprgo" }, + "linkedin_mobile_pinch_2018": { + "DEFAULT": "rendering_mobile_c47e7f29dd.wprgo" + }, "linkedin_pathological_2018": { "DEFAULT": "rendering_mobile_d5f51fba2e.wprgo" }, @@ -546,6 +561,9 @@ "twitch_desktop_gpu_raster_2018": { "DEFAULT": "rendering_mobile_000.wprgo" }, + "twitch_mobile_pinch_2018": { + "DEFAULT": "rendering_mobile_c47e7f29dd.wprgo" + }, "twitter_2018": { "DEFAULT": "rendering_mobile_000.wprgo" }, @@ -618,6 +636,9 @@ "yahoo_sports_desktop_gpu_raster_2018": { "DEFAULT": "rendering_mobile_000.wprgo" }, + "yahoo_sports_mobile_pinch_2018": { + "DEFAULT": "rendering_mobile_d00c7313f6.wprgo" + }, "yahoo_sports_pathological_2018": { "DEFAULT": "rendering_mobile_025.wprgo" },
diff --git a/tools/perf/page_sets/data/rendering_mobile_64b26a7503.wprgo.sha1 b/tools/perf/page_sets/data/rendering_mobile_64b26a7503.wprgo.sha1 new file mode 100644 index 0000000..29759f9 --- /dev/null +++ b/tools/perf/page_sets/data/rendering_mobile_64b26a7503.wprgo.sha1
@@ -0,0 +1 @@ +64b26a7503b8c897d37452c690ccd2c8138cac57 \ No newline at end of file
diff --git a/tools/perf/page_sets/data/rendering_mobile_8d57721c03.wprgo.sha1 b/tools/perf/page_sets/data/rendering_mobile_8d57721c03.wprgo.sha1 new file mode 100644 index 0000000..1f98c3ff --- /dev/null +++ b/tools/perf/page_sets/data/rendering_mobile_8d57721c03.wprgo.sha1
@@ -0,0 +1 @@ +8d57721c03df95aad4cb9086106ebd08b8ccb11a \ No newline at end of file
diff --git a/tools/perf/page_sets/data/rendering_mobile_c47e7f29dd.wprgo.sha1 b/tools/perf/page_sets/data/rendering_mobile_c47e7f29dd.wprgo.sha1 new file mode 100644 index 0000000..e9a1c50 --- /dev/null +++ b/tools/perf/page_sets/data/rendering_mobile_c47e7f29dd.wprgo.sha1
@@ -0,0 +1 @@ +c47e7f29dd2e31208a84952cb62ec7bb32375315 \ No newline at end of file
diff --git a/tools/perf/page_sets/data/rendering_mobile_d00c7313f6.wprgo.sha1 b/tools/perf/page_sets/data/rendering_mobile_d00c7313f6.wprgo.sha1 new file mode 100644 index 0000000..94d4ee8 --- /dev/null +++ b/tools/perf/page_sets/data/rendering_mobile_d00c7313f6.wprgo.sha1
@@ -0,0 +1 @@ +d00c7313f66aef0bcd8fcc9b69a0fc4945ebf0d0 \ No newline at end of file
diff --git a/tools/perf/page_sets/oortonline.py b/tools/perf/page_sets/oortonline.py deleted file mode 100644 index 37e75be..0000000 --- a/tools/perf/page_sets/oortonline.py +++ /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. - -from page_sets import webgl_supported_shared_state -from telemetry import page as page_module -from telemetry import story - -STARTUP_SCRIPT = ''' - window.benchmarkStarted =false; - window.benchmarkFinished = false; - window.benchmarkBeforeRun = function() { - window.benchmarkStarted = true; - }; - window.benchmarkAfterRun = function(score) { - window.benchmarkFinished = true; - window.benchmarkScore = score; - window.benchmarkAfterRun = null; - };''' - -class OortOnlinePage(page_module.Page): - def __init__(self, page_set): - super(OortOnlinePage, self).__init__( - url='http://oortonline.gl/#run', page_set=page_set, - shared_page_state_class=( - webgl_supported_shared_state.WebGLSupportedSharedState), - make_javascript_deterministic=False, - name='http://oortonline.gl/#run') - self.script_to_evaluate_on_commit = STARTUP_SCRIPT - - @property - def skipped_gpus(self): - # crbug.com/462729 - return ['arm', 'broadcom', 'hisilicon', 'imagination', 'qualcomm', - 'vivante', 'vmware'] - -class OortOnlinePageSet(story.StorySet): - """Oort Online WebGL benchmark. - URL: http://oortonline.gl/#run - Info: http://v8project.blogspot.de/2015/10/jank-busters-part-one.html - """ - def __init__(self): - super(OortOnlinePageSet, self).__init__( - archive_data_file='data/oortonline.json', - cloud_storage_bucket=story.PARTNER_BUCKET) - self.AddStory(OortOnlinePage(self)) - -class OortOnlineTBMPage(OortOnlinePage): - def __init__(self, page_set): - super(OortOnlineTBMPage, self).__init__(page_set=page_set) - - def RunPageInteractions(self, action_runner): - WAIT_TIME_IN_SECONDS = 2 - RUN_TIME_IN_SECONDS = 20 - action_runner.WaitForJavaScriptCondition('window.benchmarkStarted') - # Perform GC to get rid of start-up garbage. - action_runner.ForceGarbageCollection() - with action_runner.CreateInteraction('Begin'): - action_runner.tab.browser.DumpMemory() - # Skip the first few seconds to get more stable frame times. - action_runner.Wait(WAIT_TIME_IN_SECONDS) - with action_runner.CreateInteraction('Running'): - # We cannot wait until benchmarkFinished because true because the result - # screen does not update, which affects frame-time discrepancy - # computation. Instead we stop based on timer. - action_runner.Wait(RUN_TIME_IN_SECONDS) - with action_runner.CreateInteraction('End'): - action_runner.tab.browser.DumpMemory() - - -class OortOnlineTBMPageSet(story.StorySet): - """Oort Online WebGL benchmark for TBM. - URL: http://oortonline.gl/#run - Info: http://v8project.blogspot.de/2015/10/jank-busters-part-one.html - """ - - def __init__(self): - super(OortOnlineTBMPageSet, self).__init__( - archive_data_file='data/oortonline.json', - cloud_storage_bucket=story.PARTNER_BUCKET) - self.AddStory(OortOnlineTBMPage(self))
diff --git a/tools/perf/page_sets/rendering/rendering_shared_state.py b/tools/perf/page_sets/rendering/rendering_shared_state.py index f3f3a16..342b890 100644 --- a/tools/perf/page_sets/rendering/rendering_shared_state.py +++ b/tools/perf/page_sets/rendering/rendering_shared_state.py
@@ -9,12 +9,6 @@ class RenderingSharedState(shared_page_state.SharedPageState): def CanRunOnBrowser(self, browser_info, page): - if page.TAGS and story_tags.TOUGH_PINCH_ZOOM in page.TAGS: - os_name = self.platform.GetOSName() - if os_name == 'linux' or os_name == 'win': - logging.warning('Pinch zoom pages only for Mac, skipping test') - return False - if page.TAGS and story_tags.REQUIRED_WEBGL in page.TAGS: assert hasattr(page, 'skipped_gpus')
diff --git a/tools/perf/page_sets/rendering/story_tags.py b/tools/perf/page_sets/rendering/story_tags.py index 08f92d8..5bedaa9 100644 --- a/tools/perf/page_sets/rendering/story_tags.py +++ b/tools/perf/page_sets/rendering/story_tags.py
@@ -71,6 +71,8 @@ 'tough_path_rendering', 'Tough path rendering stories') TOUGH_PINCH_ZOOM = Tag( 'tough_pinch_zoom', 'Tough pinch zoom stories (only on Mac for desktop)') +TOUGH_PINCH_ZOOM_MOBILE = Tag( + 'tough_pinch_zoom_mobile', 'Tough pinch zoom mobile stories') TOUGH_SCHEDULING = Tag( 'tough_scheduling', 'Tough scheduling stories') TOUGH_SCROLLING = Tag(
diff --git a/tools/perf/page_sets/rendering/tough_pinch_zoom_cases.py b/tools/perf/page_sets/rendering/tough_pinch_zoom_cases.py index e8dafe55..54b52a3 100644 --- a/tools/perf/page_sets/rendering/tough_pinch_zoom_cases.py +++ b/tools/perf/page_sets/rendering/tough_pinch_zoom_cases.py
@@ -2,6 +2,7 @@ # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from telemetry import story +from telemetry.util import wpr_modes from page_sets.rendering import rendering_shared_state from page_sets.rendering import rendering_story @@ -13,7 +14,6 @@ class ToughPinchZoomPage(rendering_story.RenderingStory): ABSTRACT_STORY = True - # TODO(crbug.com/851499): expand supported_platforms to both desktop & mobile SUPPORTED_PLATFORMS = platforms.DESKTOP_ONLY TAGS = [story_tags.GPU_RASTERIZATION, story_tags.TOUGH_PINCH_ZOOM] @@ -74,7 +74,8 @@ URL = 'https://mail.google.com/mail/' def RunNavigateSteps(self, action_runner): - google_login.NewLoginGoogleAccount(action_runner, 'googletest') + if self.wpr_mode != wpr_modes.WPR_REPLAY: + google_login.NewLoginGoogleAccount(action_runner, 'googletest') super(GmailPinchZoom2018Page, self).RunNavigateSteps(action_runner) action_runner.WaitForJavaScriptCondition( 'window.gmonkey !== undefined &&' @@ -90,7 +91,8 @@ URL = 'https://www.google.com/calendar/' def RunNavigateSteps(self, action_runner): - google_login.NewLoginGoogleAccount(action_runner, 'googletest') + if self.wpr_mode != wpr_modes.WPR_REPLAY: + google_login.NewLoginGoogleAccount(action_runner, 'googletest') super(GoogleCalendarPinchZoom2018Page, self).RunNavigateSteps( action_runner) action_runner.WaitForElement('span[class~="sm8sCf"]') @@ -157,7 +159,8 @@ URL = 'http://www.linkedin.com/in/linustorvalds' def RunNavigateSteps(self, action_runner): - linkedin_login.LoginDesktopAccount(action_runner, 'linkedin') + if self.wpr_mode != wpr_modes.WPR_REPLAY: + linkedin_login.LoginDesktopAccount(action_runner, 'linkedin') super(LinkedinPinchZoom2018Page, self).RunNavigateSteps(action_runner) @@ -259,19 +262,17 @@ # TODO(crbug.com/760553):remove this class after # smoothness.tough_pinch_zoom_cases benchmark is completely # replaced by rendering benchmarks -class ToughPinchZoomCasesPageSet(story.StorySet): +class AndroidToughPinchZoomCasesPageSet(story.StorySet): """ Set of pages that are tricky to pinch-zoom """ - def __init__(self, target_scale_factor): - super(ToughPinchZoomCasesPageSet, self).__init__( + def __init__(self): + super(AndroidToughPinchZoomCasesPageSet, self).__init__( archive_data_file='../data/tough_pinch_zoom_cases.json', cloud_storage_bucket=story.PARTNER_BUCKET) - self.target_scale_factor = target_scale_factor + self.target_scale_factor = 7.0 - self.AddStory(GoogleSearchPinchZoom2018Page( - page_set=self)) self.AddStory(GmailPinchZoom2018Page( page_set=self)) self.AddStory(GoogleCalendarPinchZoom2018Page( @@ -284,47 +285,16 @@ page_set=self)) self.AddStory(FacebookPinchZoom2018Page( page_set=self)) - self.AddStory(LinkedinPinchZoom2018Page( - page_set=self)) self.AddStory(TwitterPinchZoom2018Page( page_set=self)) self.AddStory(ESPNPinchZoom2018Page( page_set=self)) - self.AddStory(TwitchPinchZoom2018Page( - page_set=self)) self.AddStory(YahooNewsPinchZoom2018Page( page_set=self)) - self.AddStory(CnnPinchZoom2018Page( - page_set=self)) self.AddStory(AmazonPinchZoom2018Page( page_set=self)) - self.AddStory(EBayPinchZoom2018Page( - page_set=self)) - self.AddStory(AccuWeatherPinchZoom2018Page( - page_set=self)) self.AddStory(YahooSportsPinchZoom2018Page( page_set=self)) self.AddStory(BookingPinchZoom2018Page( page_set=self)) - -class AndroidToughPinchZoomCasesPageSet(ToughPinchZoomCasesPageSet): - - """ - ToughPinchZoomCasesPageSet using the maximum Android zoom level. This is - chosen as 7x, which may seem to exceed the 5x value specified in - WebPreferences::default_maximum_page_scale_factor. However, as desktop sites - on Android start at less than 1x scale (up to 0.25x), a value of 7x does not - exceed the 5x limit. - """ - - def __init__(self): - super(AndroidToughPinchZoomCasesPageSet, self).__init__(7.0) - - -class DesktopToughPinchZoomCasesPageSet(ToughPinchZoomCasesPageSet): - - """ ToughPinchZoomCasesPageSet using the maximum desktop zoom level """ - - def __init__(self): - super(DesktopToughPinchZoomCasesPageSet, self).__init__(4.0)
diff --git a/tools/perf/page_sets/rendering/tough_pinch_zoom_mobile_cases.py b/tools/perf/page_sets/rendering/tough_pinch_zoom_mobile_cases.py new file mode 100644 index 0000000..c9056f4e --- /dev/null +++ b/tools/perf/page_sets/rendering/tough_pinch_zoom_mobile_cases.py
@@ -0,0 +1,97 @@ +# 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. +from telemetry.page import shared_page_state + +from page_sets.rendering import rendering_story +from page_sets.rendering import story_tags +from page_sets.system_health import platforms +from page_sets.login_helpers import linkedin_login + + +class ToughPinchZoomMobilePage(rendering_story.RenderingStory): + ABSTRACT_STORY = True + SUPPORTED_PLATFORMS = platforms.MOBILE_ONLY + TAGS = [story_tags.TOUGH_PINCH_ZOOM_MOBILE] + + def __init__(self, + page_set, + name_suffix='', + extra_browser_args=None, + shared_page_state_class=shared_page_state.SharedMobilePageState): + super(ToughPinchZoomMobilePage, self).__init__( + page_set=page_set, + name_suffix=name_suffix, + extra_browser_args=extra_browser_args, + shared_page_state_class=shared_page_state_class) + + def RunPinchGesture(self, action_runner, left_anchor_ratio=0.5, + top_anchor_ratio=0.5, scale_factor=None, + speed_in_pixels_per_second=800): + with action_runner.CreateGestureInteraction('PinchAction', + repeatable=True): + action_runner.PinchPage( + left_anchor_ratio=left_anchor_ratio, + top_anchor_ratio=top_anchor_ratio, + scale_factor=scale_factor, + speed_in_pixels_per_second=speed_in_pixels_per_second) + + def RunPageInteractions(self, action_runner): + action_runner.tab.WaitForDocumentReadyStateToBeInteractiveOrBetter() + for _ in xrange(0, 3): + current_scale_factor = 7.0 + self.RunPinchGesture(action_runner, scale_factor=current_scale_factor) + while current_scale_factor > 1.0: + current_scale_factor *= 1/2.0 + self.RunPinchGesture(action_runner, scale_factor=1/2.0) + + +class GoogleSearchPinchZoomMobile2018Page(ToughPinchZoomMobilePage): + """ Why: top google property; a google tab is often open. """ + BASE_NAME = 'google_search_mobile_pinch' + YEAR = '2018' + URL = 'https://www.google.com/#hl=en&q=barack+obama' + + +class LinkedinPinchZoomMobile2018Page(ToughPinchZoomMobilePage): + """ Why: #12 (Alexa global), Public profile.""" + BASE_NAME = 'linkedin_mobile_pinch' + YEAR = '2018' + URL = 'http://www.linkedin.com/in/linustorvalds' + + # Linkedin has expensive shader compilation so it can benefit from shader + # cache from reload. + def RunNavigateSteps(self, action_runner): + linkedin_login.LoginMobileAccount(action_runner, 'linkedin') + super(LinkedinPinchZoomMobile2018Page, + self).RunNavigateSteps(action_runner) + action_runner.WaitForJavaScriptCondition( + 'document.getElementById("profile-wrapper") !== null') + + +class AccuWeatherPinchZoomMobile2018Page(ToughPinchZoomMobilePage): + """ Why: #2 weather according to Alexa.""" + BASE_NAME = 'accu_weather_mobile_pinch' + YEAR = '2018' + URL = 'https://www.accuweather.com/en/us/new-york-ny/10017/weather-forecast/349727' + + +class TwitchPinchZoomMobile2018Page(ToughPinchZoomMobilePage): + """ Why: #1 games according to Alexa.""" + BASE_NAME = 'twitch_mobile_pinch' + YEAR = '2018' + URL = 'https://www.twitch.tv/?no-mobile-redirect=true' + + +class CnnPinchZoomMobile2018Page(ToughPinchZoomMobilePage): + """ Why: #2 news worldwide.""" + BASE_NAME = 'cnn_mobile_pinch' + YEAR = '2018' + URL = 'http://www.cnn.com/travel/article/airbus-a330-900-neo-tours-us-airports/index.html' + + +class EBayPinchZoomMobile2018Page(ToughPinchZoomMobilePage): + """ Why: #1 commerce website by time spent by users in US.""" + BASE_NAME = 'ebay_mobile_pinch' + YEAR = '2018' + URL = 'http://www.ebay.com'
diff --git a/ui/accessibility/platform/ax_platform_node_auralinux.cc b/ui/accessibility/platform/ax_platform_node_auralinux.cc index 0fd8739a..f3a8dc0c 100644 --- a/ui/accessibility/platform/ax_platform_node_auralinux.cc +++ b/ui/accessibility/platform/ax_platform_node_auralinux.cc
@@ -2783,6 +2783,20 @@ nullptr); } +void AXPlatformNodeAuraLinux::OnNameChanged() { + std::string name; + GetStringAttribute(ax::mojom::StringAttribute::kName, &name); + + AtkPropertyValues property_values; + property_values.property_name = "accessible-name"; + property_values.new_value = G_VALUE_INIT; + g_value_init(&property_values.new_value, G_TYPE_STRING); + g_value_set_string(&property_values.new_value, name.c_str()); + g_signal_emit_by_name(G_OBJECT(atk_object_), + "property-change::accessible-name", &property_values, + nullptr); +} + void AXPlatformNodeAuraLinux::NotifyAccessibilityEvent( ax::mojom::Event event_type) { switch (event_type) {
diff --git a/ui/accessibility/platform/ax_platform_node_auralinux.h b/ui/accessibility/platform/ax_platform_node_auralinux.h index 63caa6e..fa6c354 100644 --- a/ui/accessibility/platform/ax_platform_node_auralinux.h +++ b/ui/accessibility/platform/ax_platform_node_auralinux.h
@@ -89,6 +89,7 @@ void OnSelected(); void OnSelectedChildrenChanged(); void OnValueChanged(); + void OnNameChanged(); bool SupportsSelectionWithAtkSelection(); bool SelectionAndFocusAreTheSame();
diff --git a/ui/android/BUILD.gn b/ui/android/BUILD.gn index 726c2a1..be1b751 100644 --- a/ui/android/BUILD.gn +++ b/ui/android/BUILD.gn
@@ -244,6 +244,7 @@ "java/src/org/chromium/ui/base/ActivityWindowAndroid.java", "java/src/org/chromium/ui/base/AndroidPermissionDelegate.java", "java/src/org/chromium/ui/base/Clipboard.java", + "java/src/org/chromium/ui/base/CursorVisibilityObserver.java", "java/src/org/chromium/ui/base/DeviceFormFactor.java", "java/src/org/chromium/ui/base/EventForwarder.java", "java/src/org/chromium/ui/base/TouchlessEventHandler.java",
diff --git a/ui/android/java/src/org/chromium/ui/base/CursorVisibilityObserver.java b/ui/android/java/src/org/chromium/ui/base/CursorVisibilityObserver.java new file mode 100644 index 0000000..f176a22c --- /dev/null +++ b/ui/android/java/src/org/chromium/ui/base/CursorVisibilityObserver.java
@@ -0,0 +1,10 @@ +// Copyright 2019 The Chromium 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.ui.base; + +/** + * Observer Android cursor visibility. + */ +public interface CursorVisibilityObserver { void onCursorVisibilityChanged(boolean visible); } \ No newline at end of file
diff --git a/ui/android/java/src/org/chromium/ui/base/TouchlessEventHandler.java b/ui/android/java/src/org/chromium/ui/base/TouchlessEventHandler.java index 8c2d75f7..0d4412e 100644 --- a/ui/android/java/src/org/chromium/ui/base/TouchlessEventHandler.java +++ b/ui/android/java/src/org/chromium/ui/base/TouchlessEventHandler.java
@@ -29,7 +29,23 @@ return sInstance.onUnconsumedKeyboardEventAckInternal(nativeCode); } + public static void addCursorVisibilityObserver(CursorVisibilityObserver observer) { + if (sInstance != null) { + sInstance.addCursorVisibilityObserverInternal(observer); + } + } + + public static void removeCursorVisibilityObserver(CursorVisibilityObserver observer) { + if (sInstance != null) { + sInstance.removeCursorVisibilityObserverInternal(observer); + } + } + protected boolean onUnconsumedKeyboardEventAckInternal(int nativeCode) { return false; } + + protected void addCursorVisibilityObserverInternal(CursorVisibilityObserver observer) {} + + protected void removeCursorVisibilityObserverInternal(CursorVisibilityObserver observer) {} } \ No newline at end of file
diff --git a/ui/android/java/src/org/chromium/ui/base/WindowAndroid.java b/ui/android/java/src/org/chromium/ui/base/WindowAndroid.java index 826d60b..075869cb 100644 --- a/ui/android/java/src/org/chromium/ui/base/WindowAndroid.java +++ b/ui/android/java/src/org/chromium/ui/base/WindowAndroid.java
@@ -183,6 +183,16 @@ } }; + private final CursorVisibilityObserver mCursorVisibilityObserver = + new CursorVisibilityObserver() { + @Override + public void onCursorVisibilityChanged(boolean visible) { + if (mNativeWindowAndroid != 0) { + nativeOnCursorVisibilityChanged(mNativeWindowAndroid, visible); + } + } + }; + /** * Extract the activity if the given Context either is or wraps one. * Only retrieve the base context if the supplied context is a {@link ContextWrapper} but not @@ -253,6 +263,8 @@ boolean isScreenWideColorGamut = ApiHelperForO.isScreenWideColorGamut(configuration); display.updateIsDisplayServerWideColorGamut(isScreenWideColorGamut); } + + TouchlessEventHandler.addCursorVisibilityObserver(mCursorVisibilityObserver); } @CalledByNative @@ -644,6 +656,8 @@ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { if (mTouchExplorationMonitor != null) mTouchExplorationMonitor.destroy(); } + + TouchlessEventHandler.removeCursorVisibilityObserver(mCursorVisibilityObserver); } /** @@ -857,5 +871,5 @@ private native void nativeOnActivityStarted(long nativeWindowAndroid); private native void nativeSetVSyncPaused(long nativeWindowAndroid, boolean paused); private native void nativeDestroy(long nativeWindowAndroid); - + private native void nativeOnCursorVisibilityChanged(long nativeWindowAndroid, boolean visible); }
diff --git a/ui/android/window_android.cc b/ui/android/window_android.cc index 448daa3..a7e39ed4 100644 --- a/ui/android/window_android.cc +++ b/ui/android/window_android.cc
@@ -344,6 +344,14 @@ begin_frame_source_->OnPauseChanged(paused); } +void WindowAndroid::OnCursorVisibilityChanged( + JNIEnv* env, + const base::android::JavaParamRef<jobject>& obj, + bool visible) { + for (WindowAndroidObserver& observer : observer_list_) + observer.OnCursorVisibilityChanged(visible); +} + bool WindowAndroid::HasPermission(const std::string& permission) { JNIEnv* env = AttachCurrentThread(); return Java_WindowAndroid_hasPermission(
diff --git a/ui/android/window_android.h b/ui/android/window_android.h index 01c1e6a..910b7cc9 100644 --- a/ui/android/window_android.h +++ b/ui/android/window_android.h
@@ -87,6 +87,10 @@ void SetVSyncPaused(JNIEnv* env, const base::android::JavaParamRef<jobject>& obj, bool paused); + void OnCursorVisibilityChanged( + JNIEnv* env, + const base::android::JavaParamRef<jobject>& obj, + bool visible); // Return whether the specified Android permission is granted. bool HasPermission(const std::string& permission);
diff --git a/ui/android/window_android_observer.h b/ui/android/window_android_observer.h index 0a07fd84..549ba29 100644 --- a/ui/android/window_android_observer.h +++ b/ui/android/window_android_observer.h
@@ -22,6 +22,7 @@ // should account for whether or not this is the case. virtual void OnActivityStopped() = 0; virtual void OnActivityStarted() = 0; + virtual void OnCursorVisibilityChanged(bool visible) {} protected: virtual ~WindowAndroidObserver() {}
diff --git a/ui/compositor/callback_layer_animation_observer.h b/ui/compositor/callback_layer_animation_observer.h index 5db3b31..fc631cc2 100644 --- a/ui/compositor/callback_layer_animation_observer.h +++ b/ui/compositor/callback_layer_animation_observer.h
@@ -40,9 +40,9 @@ // ui::LayerAnimator* animator_2 = layer_2->GetAnimator(); // CallbackLayerAnimationObserver* observer = // new CallbackLayerAnimationObserver( -// base::Bind(&Foobar::AnimationStartedCallback), +// base::BindRepeating(&Foobar::AnimationStartedCallback), // base::Unretained(this)); -// base::Bind(&Foobar::AnimationEndedCallback), +// base::BindRepeating(&Foobar::AnimationEndedCallback), // base::Unretained(this)); // animator_1->AddObserver(observer); // animator_2->AddObserver(observer); @@ -61,13 +61,13 @@ public: // The Callback type that will be invoked when all animation sequences have // been started. - typedef base::Callback<void(const CallbackLayerAnimationObserver&)> + typedef base::RepeatingCallback<void(const CallbackLayerAnimationObserver&)> AnimationStartedCallback; // The Callback type that will be invoked when all animation sequences have // finished. |this| will be destroyed after invoking the Callback if it // returns true. - typedef base::Callback<bool(const CallbackLayerAnimationObserver&)> + typedef base::RepeatingCallback<bool(const CallbackLayerAnimationObserver&)> AnimationEndedCallback; // A dummy no-op AnimationStartedCallback.
diff --git a/ui/file_manager/integration_tests/video_player/check_elements.js b/ui/file_manager/integration_tests/video_player/check_elements.js index 95d81dc..5b2d335e 100644 --- a/ui/file_manager/integration_tests/video_player/check_elements.js +++ b/ui/file_manager/integration_tests/video_player/check_elements.js
@@ -16,7 +16,8 @@ return Promise.all([ remoteCallVideoPlayer.waitForElement(appId, 'html[i18n-processed]'), remoteCallVideoPlayer.waitForElement(appId, 'div#video-player'), - remoteCallVideoPlayer.waitForElement(appId, '#video-container > video'), + remoteCallVideoPlayer.waitForElement( + appId, '#video-container > video[autopictureinpicture]'), ]); }); };
diff --git a/ui/file_manager/video_player/js/BUILD.gn b/ui/file_manager/video_player/js/BUILD.gn index 4730eec..f89cfcf 100644 --- a/ui/file_manager/video_player/js/BUILD.gn +++ b/ui/file_manager/video_player/js/BUILD.gn
@@ -25,6 +25,7 @@ "$externs_path/media_player_private.js", "$externs_path/metrics_private.js", "$externs_path/mediasession.js", + "$externs_path/picture_in_picture.js", "../../externs/chrome_cast.js", "../../externs/platform.js", ]
diff --git a/ui/file_manager/video_player/js/video_player.js b/ui/file_manager/video_player/js/video_player.js index c925523..3523e3f 100644 --- a/ui/file_manager/video_player/js/video_player.js +++ b/ui/file_manager/video_player/js/video_player.js
@@ -427,6 +427,7 @@ videoPlayerElement.removeAttribute('casting'); this.videoElement_ = document.createElement('video'); + this.videoElement_.autoPictureInPicture = true; getRequiredElement('video-container').appendChild(this.videoElement_); var videoUrl = video.toURL();
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 361fe1de..6edafd76 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
@@ -38,6 +38,7 @@ // we are confident to remove the feature flag this.videoElement_ = assertInstanceof(document.createElement('video'), HTMLVideoElement); + this.videoElement_.autoPictureInPicture = true; this.videoElement_.controls = true; this.videoElement_.controlsList = 'nodownload'; this.videoElement_.style.pointerEvents = 'auto';
diff --git a/ui/gfx/image/image_skia_operations.cc b/ui/gfx/image/image_skia_operations.cc index 51743e5..9a05026f 100644 --- a/ui/gfx/image/image_skia_operations.cc +++ b/ui/gfx/image/image_skia_operations.cc
@@ -559,9 +559,10 @@ const Rect& subset_bounds) { gfx::Rect clipped_bounds = gfx::IntersectRects(subset_bounds, gfx::Rect(image.size())); - if (image.isNull() || clipped_bounds.IsEmpty()) { + if (image.isNull() || clipped_bounds.IsEmpty()) return ImageSkia(); - } + if (clipped_bounds == gfx::Rect(image.size())) + return image; return ImageSkia( std::make_unique<ExtractSubsetImageSource>(image, clipped_bounds), @@ -575,6 +576,8 @@ const Size& target_dip_size) { if (source.isNull()) return ImageSkia(); + if (source.size() == target_dip_size) + return source; return ImageSkia( std::make_unique<ResizeSource>(source, method, target_dip_size),
diff --git a/ui/ozone/demo/skia/skia_gl_renderer.cc b/ui/ozone/demo/skia/skia_gl_renderer.cc index 59df608..4494fa5 100644 --- a/ui/ozone/demo/skia/skia_gl_renderer.cc +++ b/ui/ozone/demo/skia/skia_gl_renderer.cc
@@ -69,8 +69,6 @@ sk_sp<const GrGLInterface>(GrGLCreateNativeInterface()); DCHECK(native_interface); GrContextOptions options; - if (use_ddl_) - options.fExplicitlyAllocateGPUResources = GrContextOptions::Enable::kYes; gr_context_ = GrContext::MakeGL(std::move(native_interface), options); DCHECK(gr_context_);
diff --git a/ui/views/animation/ink_drop_highlight.cc b/ui/views/animation/ink_drop_highlight.cc index f4be704..866c68b 100644 --- a/ui/views/animation/ink_drop_highlight.cc +++ b/ui/views/animation/ink_drop_highlight.cc
@@ -118,10 +118,10 @@ // AnimationStartedCallback() returns true. ui::CallbackLayerAnimationObserver* animation_observer = new ui::CallbackLayerAnimationObserver( - base::Bind(&InkDropHighlight::AnimationStartedCallback, - base::Unretained(this), animation_type), - base::Bind(&InkDropHighlight::AnimationEndedCallback, - base::Unretained(this), animation_type)); + base::BindRepeating(&InkDropHighlight::AnimationStartedCallback, + base::Unretained(this), animation_type), + base::BindRepeating(&InkDropHighlight::AnimationEndedCallback, + base::Unretained(this), animation_type)); ui::LayerAnimator* animator = layer_->GetAnimator(); ui::ScopedLayerAnimationSettings animation(animator);