diff --git a/DEPS b/DEPS index 45d6ffd..b59c72c 100644 --- a/DEPS +++ b/DEPS
@@ -129,11 +129,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': '4a20dbeaf31a549c0ae857beb3b163962f9aa325', + 'skia_revision': '6caab2161079332c8b6ec3541365096bbea06691', # 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': '36585c1b6b1fd69d093706a6c4ad9775506a7885', + 'v8_revision': '93306f1d7b2c10824e1e8876e5b8a3ab37c42b96', # 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. @@ -141,15 +141,15 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling ANGLE # and whatever else without interference from each other. - 'angle_revision': '38e282570676f3e434482f8a02ea539b286fd1fa', + 'angle_revision': '9b050f846a06463e83160ad192c809692e395dbf', # 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': '1cef4e693fc3acaf87d15c23c3a77fc7d911d27d', + 'swiftshader_revision': '0e712410582f85d3388c939b6c0da6b3e1d761f0', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling PDFium # and whatever else without interference from each other. - 'pdfium_revision': 'bcb9892d16d3b86d3c8fe70cc8ba0430618ff7d4', + 'pdfium_revision': '3d3dcdff38a692c7dfc0a064e37cdf44c0fa34a7', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling openmax_dl # and whatever else without interference from each other. @@ -176,7 +176,7 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling NaCl # and whatever else without interference from each other. - 'nacl_revision': '1ed9878b8eb68c1e0d0268754dafcf83e747fa8f', + 'nacl_revision': '7d24fb15d81f95ed30dde0c04b68584749709657', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling freetype # and whatever else without interference from each other. @@ -248,7 +248,7 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling feed # and whatever else without interference from each other. - 'spv_tools_revision': '2ac348b5c0a58c64305379baca778c2e58873cd6', + 'spv_tools_revision': 'e1a76269b649b7263266c1197622468dae9950b3', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling feed # and whatever else without interference from each other. @@ -264,11 +264,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. - 'dawn_revision': 'fef613365afe5234c1bae9fe33c3d30698d27078', + 'dawn_revision': '54e4d47db4910ebd1ffce0247b60d4e6f984774f', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling feed # and whatever else without interference from each other. - 'quiche_revision': 'f08778a58e717a38fcf59eb1a2ca01b8bf836ad2', + 'quiche_revision': 'd5d13c2a81b5b504c1bf3308b12c5479a1eb8d58', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling ios_webkit # and whatever else without interference from each other. @@ -801,7 +801,7 @@ # Build tools for Chrome OS. Note: This depends on third_party/pyelftools. 'src/third_party/chromite': { - 'url': Var('chromium_git') + '/chromiumos/chromite.git' + '@' + 'f9f298eb11ced7eb906610b37938c2de1d5c7515', + 'url': Var('chromium_git') + '/chromiumos/chromite.git' + '@' + 'fcbfd4ea485ad289b3d1e2abeef7d4719d3d2e3e', 'condition': 'checkout_linux', }, @@ -826,7 +826,7 @@ }, 'src/third_party/depot_tools': - Var('chromium_git') + '/chromium/tools/depot_tools.git' + '@' + 'b542cca266972d6f78afe52d9a9a1a56a3f90d7d', + Var('chromium_git') + '/chromium/tools/depot_tools.git' + '@' + '1c21d7cb523d20b7d3febb5aa9dc5798c1ffdbae', 'src/third_party/devtools-node-modules': Var('chromium_git') + '/external/github.com/ChromeDevTools/devtools-node-modules' + '@' + Var('devtools_node_modules_revision'), @@ -861,7 +861,7 @@ }, 'src/third_party/ffmpeg': - Var('chromium_git') + '/chromium/third_party/ffmpeg.git' + '@' + '7e1e8a4f7df474a4f8109c507a09621acad40314', + Var('chromium_git') + '/chromium/third_party/ffmpeg.git' + '@' + 'f5b197fe669943e9e18d2181dc8aa696075620aa', 'src/third_party/flac': Var('chromium_git') + '/chromium/deps/flac.git' + '@' + 'af862024c8c8fa0ae07ced05e89013d881b00596', @@ -895,7 +895,7 @@ }, 'src/third_party/glslang/src': - Var('chromium_git') + '/external/github.com/KhronosGroup/glslang.git' + '@' + 'b184e41a063792881df531eebbaca591605bacde', + Var('chromium_git') + '/external/github.com/KhronosGroup/glslang.git' + '@' + '5efb004d59601711cdf328c8a8bfbe7f333dc7a0', 'src/third_party/google_toolbox_for_mac/src': { 'url': Var('chromium_git') + '/external/github.com/google/google-toolbox-for-mac.git' + '@' + Var('google_toolbox_for_mac_revision'), @@ -1168,7 +1168,7 @@ }, 'src/third_party/perfetto': - Var('android_git') + '/platform/external/perfetto.git' + '@' + '7b0c9453e8d31c03d16cd1d94bd17a96fb9fe3ef', + Var('android_git') + '/platform/external/perfetto.git' + '@' + '69d721a1be6d2707dd0102a1b6f4ecec7b0c5cb5', 'src/third_party/perl': { 'url': Var('chromium_git') + '/chromium/deps/perl.git' + '@' + 'ac0d98b5cee6c024b0cffeb4f8f45b6fc5ccdb78', @@ -1207,7 +1207,7 @@ Var('chromium_git') + '/external/pyftpdlib.git' + '@' + '2be6d65e31c7ee6320d059f581f05ae8d89d7e45', 'src/third_party/quic_trace/src': - Var('chromium_git') + '/external/github.com/google/quic-trace.git' + '@' + 'fe1b2587410c47adac3b26a224bc9c979024c191', + Var('chromium_git') + '/external/github.com/google/quic-trace.git' + '@' + '9aaca5b4862aaf871e677cbd188fee34f588360d', 'src/third_party/pywebsocket/src': Var('chromium_git') + '/external/github.com/google/pywebsocket.git' + '@' + '2d7b73c3acbd0f41dcab487ae5c97c6feae06ce2', @@ -1380,7 +1380,7 @@ Var('chromium_git') + '/v8/v8.git' + '@' + Var('v8_revision'), 'src-internal': { - 'url': 'https://chrome-internal.googlesource.com/chrome/src-internal.git@6abdbc905c1403fdfb224151fc771eaed28bfe8c', + 'url': 'https://chrome-internal.googlesource.com/chrome/src-internal.git@3fe9205c384b7ebab41c93649f00a9fd04e6a95b', 'condition': 'checkout_src_internal', },
diff --git a/android_webview/BUILD.gn b/android_webview/BUILD.gn index 0fad10a..6b549a9 100644 --- a/android_webview/BUILD.gn +++ b/android_webview/BUILD.gn
@@ -555,8 +555,6 @@ "browser/aw_print_manager.cc", "browser/aw_print_manager.h", "browser/aw_proxy_controller.cc", - "browser/aw_proxying_url_loader_factory.cc", - "browser/aw_proxying_url_loader_factory.h", "browser/aw_quota_manager_bridge.cc", "browser/aw_quota_manager_bridge.h", "browser/aw_quota_permission_context.cc", @@ -573,8 +571,6 @@ "browser/aw_speech_recognition_manager_delegate.h", "browser/aw_ssl_host_state_delegate.cc", "browser/aw_ssl_host_state_delegate.h", - "browser/aw_url_loader_throttle.cc", - "browser/aw_url_loader_throttle.h", "browser/aw_variations_seed_bridge.cc", "browser/aw_variations_seed_bridge.h", "browser/aw_variations_service_client.cc", @@ -621,12 +617,16 @@ "browser/net/init_native_callback.h", "browser/net/input_stream_reader.cc", "browser/net/input_stream_reader.h", - "browser/net_helpers.cc", - "browser/net_helpers.h", - "browser/net_network_service/android_stream_reader_url_loader.cc", - "browser/net_network_service/android_stream_reader_url_loader.h", - "browser/net_network_service/aw_cookie_manager_wrapper.cc", - "browser/net_network_service/aw_cookie_manager_wrapper.h", + "browser/network_service/android_stream_reader_url_loader.cc", + "browser/network_service/android_stream_reader_url_loader.h", + "browser/network_service/aw_cookie_manager_wrapper.cc", + "browser/network_service/aw_cookie_manager_wrapper.h", + "browser/network_service/aw_proxying_url_loader_factory.cc", + "browser/network_service/aw_proxying_url_loader_factory.h", + "browser/network_service/aw_url_loader_throttle.cc", + "browser/network_service/aw_url_loader_throttle.h", + "browser/network_service/net_helpers.cc", + "browser/network_service/net_helpers.h", "browser/permission/aw_permission_request.cc", "browser/permission/aw_permission_request.h", "browser/permission/aw_permission_request_delegate.cc",
diff --git a/android_webview/browser/aw_content_browser_client.cc b/android_webview/browser/aw_content_browser_client.cc index 156e205c..4889f81 100644 --- a/android_webview/browser/aw_content_browser_client.cc +++ b/android_webview/browser/aw_content_browser_client.cc
@@ -22,16 +22,16 @@ #include "android_webview/browser/aw_feature_list.h" #include "android_webview/browser/aw_feature_list_creator.h" #include "android_webview/browser/aw_http_auth_handler.h" -#include "android_webview/browser/aw_proxying_url_loader_factory.h" #include "android_webview/browser/aw_quota_permission_context.h" #include "android_webview/browser/aw_settings.h" #include "android_webview/browser/aw_speech_recognition_manager_delegate.h" -#include "android_webview/browser/aw_url_loader_throttle.h" #include "android_webview/browser/aw_web_contents_view_delegate.h" #include "android_webview/browser/cookie_manager.h" #include "android_webview/browser/net/aw_url_request_context_getter.h" -#include "android_webview/browser/net_helpers.h" -#include "android_webview/browser/net_network_service/aw_cookie_manager_wrapper.h" +#include "android_webview/browser/network_service/aw_cookie_manager_wrapper.h" +#include "android_webview/browser/network_service/aw_proxying_url_loader_factory.h" +#include "android_webview/browser/network_service/aw_url_loader_throttle.h" +#include "android_webview/browser/network_service/net_helpers.h" #include "android_webview/browser/renderer_host/aw_resource_dispatcher_host_delegate.h" #include "android_webview/browser/safe_browsing/aw_url_checker_delegate_impl.h" #include "android_webview/browser/tracing/aw_tracing_delegate.h"
diff --git a/android_webview/browser/aw_settings.cc b/android_webview/browser/aw_settings.cc index 4d9867b2..c4f0f15 100644 --- a/android_webview/browser/aw_settings.cc +++ b/android_webview/browser/aw_settings.cc
@@ -453,10 +453,10 @@ // Using 100M instead of max int to avoid overflows. web_prefs->minimum_accelerated_2d_canvas_size = 100 * 1000 * 1000; } - web_prefs->webgl1_enabled = web_prefs->webgl1_enabled && - enable_supported_hardware_accelerated_features; - web_prefs->webgl2_enabled = web_prefs->webgl2_enabled && - enable_supported_hardware_accelerated_features; + // Always allow webgl. Webview always requires access to the GPU even if + // it only does software draws. WebGL will not show up in software draw so + // there is no more brokenness for user. This makes it easier for apps that + // want to start running webgl content before webview is first attached. // If strict mixed content checking is enabled then running should not be // allowed.
diff --git a/android_webview/browser/cookie_manager.cc b/android_webview/browser/cookie_manager.cc index 526a88f..1f495f45 100644 --- a/android_webview/browser/cookie_manager.cc +++ b/android_webview/browser/cookie_manager.cc
@@ -13,7 +13,7 @@ #include "android_webview/browser/aw_browser_context.h" #include "android_webview/browser/aw_cookie_access_policy.h" #include "android_webview/browser/net/init_native_callback.h" -#include "android_webview/browser/net_network_service/aw_cookie_manager_wrapper.h" +#include "android_webview/browser/network_service/aw_cookie_manager_wrapper.h" #include "base/android/callback_android.h" #include "base/android/jni_string.h" #include "base/android/path_utils.h"
diff --git a/android_webview/browser/gfx/aw_draw_fn_impl.cc b/android_webview/browser/gfx/aw_draw_fn_impl.cc index 7bd0d4d..0f950696 100644 --- a/android_webview/browser/gfx/aw_draw_fn_impl.cc +++ b/android_webview/browser/gfx/aw_draw_fn_impl.cc
@@ -4,7 +4,10 @@ #include "android_webview/browser/gfx/aw_draw_fn_impl.h" +#include <utility> + #include "android_webview/browser/gfx/aw_vulkan_context_provider.h" +#include "android_webview/common/aw_switches.h" #include "android_webview/public/browser/draw_gl.h" #include "base/android/android_hardware_buffer_compat.h" #include "base/android/scoped_hardware_buffer_fence_sync.h" @@ -138,6 +141,69 @@ static_cast<AwDrawFnImpl*>(data)->PostDrawVk(params); } +sk_sp<GrVkSecondaryCBDrawContext> CreateDrawContext( + GrContext* gr_context, + AwDrawFn_DrawVkParams* params, + sk_sp<SkColorSpace> color_space) { + // Create a GrVkSecondaryCBDrawContext to render our AHB w/ Vulkan. + // TODO(ericrk): Handle non-RGBA. + SkImageInfo info = + SkImageInfo::MakeN32Premul(params->width, params->height, color_space); + VkRect2D draw_bounds; + GrVkDrawableInfo drawable_info{ + .fSecondaryCommandBuffer = params->secondary_command_buffer, + .fColorAttachmentIndex = params->color_attachment_index, + .fCompatibleRenderPass = params->compatible_render_pass, + .fFormat = params->format, + .fDrawBounds = &draw_bounds, + }; + SkSurfaceProps props(0, kUnknown_SkPixelGeometry); + return GrVkSecondaryCBDrawContext::Make(gr_context, info, drawable_info, + &props); +} + +template <typename T> +sk_sp<SkColorSpace> CreateColorSpace(T* params) { + skcms_TransferFunction transfer_fn{ + params->transfer_function_g, params->transfer_function_a, + params->transfer_function_b, params->transfer_function_c, + params->transfer_function_d, params->transfer_function_e, + params->transfer_function_f}; + skcms_Matrix3x3 to_xyz; + static_assert(sizeof(to_xyz.vals) == sizeof(params->color_space_toXYZD50), + "Color space matrix sizes do not match"); + memcpy(&to_xyz.vals[0][0], ¶ms->color_space_toXYZD50[0], + sizeof(to_xyz.vals)); + return SkColorSpace::MakeRGB(transfer_fn, to_xyz); +} + +// Create a VkFence and submit it to the queue. +VkFence CreateAndSubmitFence(VkDevice device, VkQueue queue) { + VkFence fence = VK_NULL_HANDLE; + VkFenceCreateInfo create_info{ + .sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO, + .pNext = nullptr, + .flags = 0, + }; + + auto result = + vkCreateFence(device, &create_info, nullptr /* pAllocator */, &fence); + if (result != VK_SUCCESS) { + LOG(ERROR) << "Could not create VkFence."; + return VK_NULL_HANDLE; + } + + result = + vkQueueSubmit(queue, 0 /* submitCount */, nullptr /* pSubmits */, fence); + if (result != VK_SUCCESS) { + LOG(ERROR) << "Could not create VkFence."; + vkDestroyFence(device, fence, nullptr /* pAllocator */); + return VK_NULL_HANDLE; + } + + return fence; +} + } // namespace static void JNI_AwDrawFnImpl_SetDrawFnFunctionTable(JNIEnv* env, @@ -147,7 +213,9 @@ } AwDrawFnImpl::AwDrawFnImpl() - : render_thread_manager_( + : is_interop_mode_(!base::CommandLine::ForCurrentProcess()->HasSwitch( + switches::kWebViewEnableVulkan)), + render_thread_manager_( base::CreateSingleThreadTaskRunnerWithTraits({BrowserThread::UI})) { DCHECK_CURRENTLY_ON(BrowserThread::UI); DCHECK(g_draw_fn_function_table); @@ -209,9 +277,30 @@ false /* save_restore */); } - while (!in_flight_draws_.empty()) { - // Let returned InFlightDraw go out of scope. - TakeInFlightDrawForReUse(); + if (!in_flight_draws_.empty()) { + DCHECK(!is_interop_mode_); + // Make sure the last pending draw is finished, and then we can destroy all + // pending draws safely. + VkFence last_fence = in_flight_draws_.back().fence; + VkDevice device = + vulkan_context_provider_->GetDeviceQueue()->GetVulkanDevice(); + VkResult result = + vkWaitForFences(device, 1, &last_fence, VK_TRUE, + base::TimeDelta::FromSeconds(60).InNanoseconds()); + DCHECK_EQ(result, VK_SUCCESS); + while (!in_flight_draws_.empty()) { + auto& draw = in_flight_draws_.front(); + vkDestroyFence(device, draw.fence, nullptr /* pAllocator */); + draw.draw_context->releaseResources(); + draw.draw_context = nullptr; + in_flight_draws_.pop(); + } + } + + while (!in_flight_interop_draws_.empty()) { + DCHECK(is_interop_mode_); + // Let returned InFlightInteropDraw go out of scope. + TakeInFlightInteropDrawForReUse(); } vulkan_context_provider_.reset(); @@ -219,39 +308,8 @@ } void AwDrawFnImpl::DrawGL(AwDrawFn_DrawGLParams* params) { - struct HardwareRendererDrawParams hr_params {}; - hr_params.clip_left = params->clip_left; - hr_params.clip_top = params->clip_top; - hr_params.clip_right = params->clip_right; - hr_params.clip_bottom = params->clip_bottom; - hr_params.width = params->width; - hr_params.height = params->height; - hr_params.is_layer = params->is_layer; - - static_assert(base::size(decltype(params->transform){}) == - base::size(hr_params.transform), - "transform size mismatch"); - for (size_t i = 0; i < base::size(hr_params.transform); ++i) { - hr_params.transform[i] = params->transform[i]; - } - - if (params->version >= 2) { - skcms_TransferFunction transfer_fn{ - params->transfer_function_g, params->transfer_function_a, - params->transfer_function_b, params->transfer_function_c, - params->transfer_function_d, params->transfer_function_e, - params->transfer_function_f}; - skcms_Matrix3x3 to_xyz; - static_assert(sizeof(to_xyz.vals) == sizeof(params->color_space_toXYZD50), - "Color space matrix sizes do not match"); - memcpy(&to_xyz.vals[0][0], ¶ms->color_space_toXYZD50[0], - sizeof(to_xyz.vals)); - sk_sp<SkColorSpace> color_space = - SkColorSpace::MakeRGB(transfer_fn, to_xyz); - if (color_space) - hr_params.color_space = gfx::ColorSpace(*color_space); - } - render_thread_manager_.DrawOnRT(false /* save_restore */, &hr_params); + auto color_space = params->version >= 2 ? CreateColorSpace(params) : nullptr; + DrawInternal(params, color_space.get()); } void AwDrawFnImpl::InitVk(AwDrawFn_InitVkParams* params) { @@ -267,6 +325,75 @@ } void AwDrawFnImpl::DrawVk(AwDrawFn_DrawVkParams* params) { + if (is_interop_mode_) { + DrawVkInterop(params); + } else { + DrawVkDirect(params); + } +} + +void AwDrawFnImpl::PostDrawVk(AwDrawFn_PostDrawVkParams* params) { + if (is_interop_mode_) { + PostDrawVkInterop(params); + } else { + PostDrawVkDirect(params); + } +} + +void AwDrawFnImpl::DrawVkDirect(AwDrawFn_DrawVkParams* params) { + if (!vulkan_context_provider_) + return; + + DCHECK(!draw_context_); + + auto color_space = CreateColorSpace(params); + if (!color_space) { + // If we weren't passed a valid colorspace, default to sRGB. + LOG(ERROR) << "Received invalid colorspace."; + color_space = SkColorSpace::MakeSRGB(); + } + draw_context_ = CreateDrawContext(vulkan_context_provider_->gr_context(), + params, color_space); + + // Set the draw contexct in |vulkan_context_provider_|, so the SkiaRenderer + // and SkiaOutputSurface* will use it as frame render target. + AwVulkanContextProvider::ScopedDrawContext scoped_draw_context( + vulkan_context_provider_.get(), draw_context_.get()); + DrawInternal(params, color_space.get()); +} + +void AwDrawFnImpl::PostDrawVkDirect(AwDrawFn_PostDrawVkParams* params) { + if (!vulkan_context_provider_) + return; + + DCHECK(draw_context_); + VkDevice device = + vulkan_context_provider_->GetDeviceQueue()->GetVulkanDevice(); + VkQueue queue = vulkan_context_provider_->GetDeviceQueue()->GetVulkanQueue(); + VkFence fence = CreateAndSubmitFence(device, queue); + DCHECK(fence != VK_NULL_HANDLE); + in_flight_draws_.emplace(fence, std::move(draw_context_)); + + // Cleanup completed draws. + while (!in_flight_draws_.empty()) { + auto& draw = in_flight_draws_.front(); + VkResult result = vkGetFenceStatus(device, draw.fence); + if (result == VK_NOT_READY) + break; + if (result == VK_SUCCESS) { + vkDestroyFence(device, draw.fence, nullptr /* pAllocator */); + draw.draw_context->releaseResources(); + draw.draw_context = nullptr; + in_flight_draws_.pop(); + continue; + } + // Handle context lost. + NOTREACHED(); + } + DCHECK_LE(in_flight_draws_.size(), 2u); +} + +void AwDrawFnImpl::DrawVkInterop(AwDrawFn_DrawVkParams* params) { if (!vulkan_context_provider_ || !gl_context_) return; @@ -280,8 +407,8 @@ // If we've exhausted our buffers, re-use an existing one. // TODO(ericrk): Benchmark using more than 1 buffer. - if (in_flight_draws_.size() >= 1 /* single buffering */) { - pending_draw_ = TakeInFlightDrawForReUse(); + if (in_flight_interop_draws_.size() >= 1 /* single buffering */) { + pending_draw_ = TakeInFlightInteropDrawForReUse(); } // If prev buffer is wrong size, just re-allocate. @@ -293,7 +420,7 @@ // If we weren't able to re-use a previous draw, create one. if (!pending_draw_) { pending_draw_ = - std::make_unique<InFlightDraw>(vulkan_context_provider_.get()); + std::make_unique<InFlightInteropDraw>(vulkan_context_provider_.get()); AHardwareBuffer_Desc desc = {}; desc.width = params->width; @@ -344,18 +471,7 @@ // Ask GL to wait on any Vk sync_fd before writing. gpu::InsertEglFenceAndWait(std::move(pending_draw_->sync_fd)); - // Calculate color space. - skcms_TransferFunction transfer_fn{ - params->transfer_function_g, params->transfer_function_a, - params->transfer_function_b, params->transfer_function_c, - params->transfer_function_d, params->transfer_function_e, - params->transfer_function_f}; - skcms_Matrix3x3 to_xyz; - static_assert(sizeof(to_xyz.vals) == sizeof(params->color_space_toXYZD50), - "Color space matrix sizes do not match"); - memcpy(&to_xyz.vals[0][0], ¶ms->color_space_toXYZD50[0], - sizeof(to_xyz.vals)); - sk_sp<SkColorSpace> color_space = SkColorSpace::MakeRGB(transfer_fn, to_xyz); + auto color_space = CreateColorSpace(params); if (!color_space) { // If we weren't passed a valid colorspace, default to sRGB. LOG(ERROR) << "Received invalid colorspace."; @@ -371,42 +487,12 @@ glDisable(GL_SCISSOR_TEST); glClearColor(0.0f, 0.0f, 0.0f, 0.0f); glClear(GL_COLOR_BUFFER_BIT); - - struct HardwareRendererDrawParams hr_params {}; - hr_params.clip_left = params->clip_left; - hr_params.clip_top = params->clip_top; - hr_params.clip_right = params->clip_right; - hr_params.clip_bottom = params->clip_bottom; - hr_params.width = params->width; - hr_params.height = params->height; - hr_params.is_layer = params->is_layer; - hr_params.color_space = gfx::ColorSpace(*color_space); - - static_assert(base::size(decltype(params->transform){}) == - base::size(hr_params.transform), - "transform size mismatch"); - for (size_t i = 0; i < base::size(hr_params.transform); ++i) { - hr_params.transform[i] = params->transform[i]; - } - render_thread_manager_.DrawOnRT(false /* save_restore */, &hr_params); + DrawInternal(params, color_space.get()); gl_done_fd = gpu::CreateEglFenceAndExportFd(); } - // Create a GrVkSecondaryCBDrawContext to render our AHB w/ Vulkan. - // TODO(ericrk): Handle non-RGBA. - SkImageInfo info = - SkImageInfo::MakeN32Premul(params->width, params->height, color_space); - VkRect2D draw_bounds; - GrVkDrawableInfo drawable_info{ - .fSecondaryCommandBuffer = params->secondary_command_buffer, - .fColorAttachmentIndex = params->color_attachment_index, - .fCompatibleRenderPass = params->compatible_render_pass, - .fFormat = params->format, - .fDrawBounds = &draw_bounds, - }; - SkSurfaceProps props(0, kUnknown_SkPixelGeometry); - pending_draw_->draw_context = GrVkSecondaryCBDrawContext::Make( - vulkan_context_provider_->gr_context(), info, drawable_info, &props); + pending_draw_->draw_context = CreateDrawContext( + vulkan_context_provider_->gr_context(), params, color_space); // If we have a |gl_done_fd|, create a Skia GrBackendSemaphore from // |gl_done_fd| and wait. @@ -477,7 +563,7 @@ pending_draw_->draw_context->flush(); } -void AwDrawFnImpl::PostDrawVk(AwDrawFn_PostDrawVkParams* params) { +void AwDrawFnImpl::PostDrawVkInterop(AwDrawFn_PostDrawVkParams* params) { if (!vulkan_context_provider_ || !gl_context_) return; @@ -519,35 +605,48 @@ return; } - // Get a fence to wait on for CPU-side cleanup. - VkFenceCreateInfo create_info{ - .sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO, - .pNext = nullptr, - .flags = 0, - }; DCHECK(VK_NULL_HANDLE == pending_draw_->post_draw_fence); - result = vkCreateFence(vulkan_context_provider_->device(), &create_info, - nullptr, &pending_draw_->post_draw_fence); - if (result != VK_SUCCESS) { - LOG(ERROR) << "Could not create VkFence."; - return; - } - result = vkQueueSubmit(vulkan_context_provider_->queue(), 0, nullptr, - pending_draw_->post_draw_fence); - if (result != VK_SUCCESS) { - LOG(ERROR) << "Could not submit fence to queue."; - return; - } - // Add the |pending_draw_| to |in_flight_draws_|. - in_flight_draws_.push(std::move(pending_draw_)); + VkDevice device = + vulkan_context_provider_->GetDeviceQueue()->GetVulkanDevice(); + VkQueue queue = vulkan_context_provider_->GetDeviceQueue()->GetVulkanQueue(); + VkFence fence = CreateAndSubmitFence(device, queue); + if (fence != VK_NULL_HANDLE) { + pending_draw_->post_draw_fence = fence; + // Add the |pending_draw_| to |in_flight_interop_draws_|. + in_flight_interop_draws_.push(std::move(pending_draw_)); + } else { + pending_draw_ = nullptr; + } } -std::unique_ptr<AwDrawFnImpl::InFlightDraw> -AwDrawFnImpl::TakeInFlightDrawForReUse() { +template <typename T> +void AwDrawFnImpl::DrawInternal(T* params, SkColorSpace* color_space) { + struct HardwareRendererDrawParams hr_params {}; + hr_params.clip_left = params->clip_left; + hr_params.clip_top = params->clip_top; + hr_params.clip_right = params->clip_right; + hr_params.clip_bottom = params->clip_bottom; + hr_params.width = params->width; + hr_params.height = params->height; + hr_params.is_layer = params->is_layer; + if (color_space) + hr_params.color_space = gfx::ColorSpace(*color_space); + + static_assert(base::size(decltype(params->transform){}) == + base::size(hr_params.transform), + "transform size mismatch"); + for (size_t i = 0; i < base::size(hr_params.transform); ++i) { + hr_params.transform[i] = params->transform[i]; + } + render_thread_manager_.DrawOnRT(false /* save_restore */, &hr_params); +} + +std::unique_ptr<AwDrawFnImpl::InFlightInteropDraw> +AwDrawFnImpl::TakeInFlightInteropDrawForReUse() { DCHECK(vulkan_context_provider_); - DCHECK(!in_flight_draws_.empty()); - std::unique_ptr<InFlightDraw>& draw = in_flight_draws_.front(); + DCHECK(!in_flight_interop_draws_.empty()); + std::unique_ptr<InFlightInteropDraw>& draw = in_flight_interop_draws_.front(); // Wait for our draw's |post_draw_fence| to pass. DCHECK(draw->post_draw_fence != VK_NULL_HANDLE); @@ -568,16 +667,24 @@ draw->post_draw_semaphore, nullptr); draw->post_draw_semaphore = VK_NULL_HANDLE; - std::unique_ptr<InFlightDraw> draw_to_return = std::move(draw); - in_flight_draws_.pop(); + std::unique_ptr<InFlightInteropDraw> draw_to_return = std::move(draw); + in_flight_interop_draws_.pop(); return draw_to_return; } AwDrawFnImpl::InFlightDraw::InFlightDraw( + VkFence fence, + sk_sp<GrVkSecondaryCBDrawContext> draw_context) + : fence(fence), draw_context(std::move(draw_context)) {} + +AwDrawFnImpl::InFlightDraw::InFlightDraw(InFlightDraw&& other) = default; +AwDrawFnImpl::InFlightDraw::~InFlightDraw() = default; + +AwDrawFnImpl::InFlightInteropDraw::InFlightInteropDraw( AwVulkanContextProvider* vk_context_provider) : vk_context_provider(vk_context_provider) {} -AwDrawFnImpl::InFlightDraw::~InFlightDraw() { +AwDrawFnImpl::InFlightInteropDraw::~InFlightInteropDraw() { // If |draw_context| is valid, we encountered an error during Vk drawing and // should call vkQueueWaitIdle to ensure safe shutdown. bool encountered_error = !!draw_context;
diff --git a/android_webview/browser/gfx/aw_draw_fn_impl.h b/android_webview/browser/gfx/aw_draw_fn_impl.h index 5359996..80d89d1 100644 --- a/android_webview/browser/gfx/aw_draw_fn_impl.h +++ b/android_webview/browser/gfx/aw_draw_fn_impl.h
@@ -5,6 +5,8 @@ #ifndef ANDROID_WEBVIEW_BROWSER_GFX_AW_DRAW_FN_IMPL_H_ #define ANDROID_WEBVIEW_BROWSER_GFX_AW_DRAW_FN_IMPL_H_ +#include <memory> + #include "android_webview/browser/gfx/compositor_frame_consumer.h" #include "android_webview/browser/gfx/render_thread_manager.h" #include "android_webview/public/browser/draw_fn.h" @@ -46,10 +48,22 @@ void PostDrawVk(AwDrawFn_PostDrawVkParams* params); private: + // With direct mode, we will render frames with Vulkan API directly. + void DrawVkDirect(AwDrawFn_DrawVkParams* params); + void PostDrawVkDirect(AwDrawFn_PostDrawVkParams* params); + + // With interop mode, we will render frames on AHBs with GL api, and then draw + // AHBs with Vulkan API on the final target. + void DrawVkInterop(AwDrawFn_DrawVkParams* params); + void PostDrawVkInterop(AwDrawFn_PostDrawVkParams* params); + + template <typename T> + void DrawInternal(T* params, SkColorSpace* color_space); + // Struct which represents one in-flight draw for the Vk interop path. - struct InFlightDraw { - explicit InFlightDraw(AwVulkanContextProvider* vk_context_provider); - ~InFlightDraw(); + struct InFlightInteropDraw { + explicit InFlightInteropDraw(AwVulkanContextProvider* vk_context_provider); + ~InFlightInteropDraw(); sk_sp<GrVkSecondaryCBDrawContext> draw_context; VkFence post_draw_fence = VK_NULL_HANDLE; VkSemaphore post_draw_semaphore = VK_NULL_HANDLE; @@ -68,20 +82,37 @@ return &render_thread_manager_; } - std::unique_ptr<InFlightDraw> TakeInFlightDrawForReUse(); + std::unique_ptr<InFlightInteropDraw> TakeInFlightInteropDrawForReUse(); + + const bool is_interop_mode_; int functor_handle_; + RenderThreadManager render_thread_manager_; // Vulkan context provider for Vk rendering. scoped_refptr<AwVulkanContextProvider> vulkan_context_provider_; + // The draw context for the current frame. It is for direct mode only. + sk_sp<GrVkSecondaryCBDrawContext> draw_context_; + + struct InFlightDraw { + InFlightDraw(VkFence fence, sk_sp<GrVkSecondaryCBDrawContext> draw_context); + InFlightDraw(InFlightDraw&& other); + ~InFlightDraw(); + + // The fence for cleanup the |draw_context|. + VkFence fence = VK_NULL_HANDLE; + sk_sp<GrVkSecondaryCBDrawContext> draw_context; + }; + base::queue<InFlightDraw> in_flight_draws_; + // GL context used to draw via GL in Vk interop path. scoped_refptr<GLNonOwnedCompatibilityContext> gl_context_; // Queue of draw contexts pending cleanup. - base::queue<std::unique_ptr<InFlightDraw>> in_flight_draws_; - std::unique_ptr<InFlightDraw> pending_draw_; + base::queue<std::unique_ptr<InFlightInteropDraw>> in_flight_interop_draws_; + std::unique_ptr<InFlightInteropDraw> pending_draw_; DISALLOW_COPY_AND_ASSIGN(AwDrawFnImpl); };
diff --git a/android_webview/browser/gfx/aw_vulkan_context_provider.cc b/android_webview/browser/gfx/aw_vulkan_context_provider.cc index da4d3e7f..fb632cc 100644 --- a/android_webview/browser/gfx/aw_vulkan_context_provider.cc +++ b/android_webview/browser/gfx/aw_vulkan_context_provider.cc
@@ -66,6 +66,7 @@ // static scoped_refptr<AwVulkanContextProvider> AwVulkanContextProvider::GetOrCreateInstance(AwDrawFn_InitVkParams* params) { + DCHECK(g_vulkan_context_provider || params); if (g_vulkan_context_provider) { DCHECK_EQ(params->device, g_vulkan_context_provider->device()); DCHECK_EQ(params->queue, g_vulkan_context_provider->queue());
diff --git a/android_webview/browser/gfx/aw_vulkan_context_provider.h b/android_webview/browser/gfx/aw_vulkan_context_provider.h index ba675be..f820c1c 100644 --- a/android_webview/browser/gfx/aw_vulkan_context_provider.h +++ b/android_webview/browser/gfx/aw_vulkan_context_provider.h
@@ -41,7 +41,7 @@ }; static scoped_refptr<AwVulkanContextProvider> GetOrCreateInstance( - AwDrawFn_InitVkParams* params); + AwDrawFn_InitVkParams* params = nullptr); // viz::VulkanContextProvider implementation: gpu::VulkanImplementation* GetVulkanImplementation() override;
diff --git a/android_webview/browser/gfx/hardware_renderer.cc b/android_webview/browser/gfx/hardware_renderer.cc index 453b695..a3b2503 100644 --- a/android_webview/browser/gfx/hardware_renderer.cc +++ b/android_webview/browser/gfx/hardware_renderer.cc
@@ -14,6 +14,8 @@ #include "android_webview/browser/gfx/parent_compositor_draw_constraints.h" #include "android_webview/browser/gfx/render_thread_manager.h" #include "android_webview/browser/gfx/surfaces_instance.h" +#include "android_webview/common/aw_switches.h" +#include "base/command_line.h" #include "base/logging.h" #include "base/macros.h" #include "base/trace_event/trace_event.h" @@ -28,14 +30,15 @@ HardwareRenderer::HardwareRenderer(RenderThreadManager* state) : render_thread_manager_(state), - last_egl_context_(eglGetCurrentContext()), surfaces_(SurfacesInstance::GetOrCreateInstance()), + last_egl_context_(surfaces_->is_using_vulkan() ? nullptr + : eglGetCurrentContext()), frame_sink_id_(surfaces_->AllocateFrameSinkId()), parent_local_surface_id_allocator_( std::make_unique<viz::ParentLocalSurfaceIdAllocator>()), last_committed_layer_tree_frame_sink_id_(0u), last_submitted_layer_tree_frame_sink_id_(0u) { - DCHECK(last_egl_context_); + DCHECK(surfaces_->is_using_vulkan() || last_egl_context_); surfaces_->GetFrameSinkManager()->RegisterFrameSinkId( frame_sink_id_, true /* report_activation */); surfaces_->GetFrameSinkManager()->SetFrameSinkDebugLabel(frame_sink_id_, @@ -96,14 +99,16 @@ child_frame_->layer_tree_frame_sink_id; } - // We need to watch if the current Android context has changed and enforce - // a clean-up in the compositor. - EGLContext current_context = eglGetCurrentContext(); - DCHECK(current_context) << "DrawGL called without EGLContext"; + if (!surfaces_->is_using_vulkan()) { + // We need to watch if the current Android context has changed and enforce a + // clean-up in the compositor. + EGLContext current_context = eglGetCurrentContext(); + DCHECK(current_context) << "DrawGL called without EGLContext"; - // TODO(boliu): Handle context loss. - if (last_egl_context_ != current_context) - DLOG(WARNING) << "EGLContextChanged"; + // TODO(boliu): Handle context loss. + if (last_egl_context_ != current_context) + DLOG(WARNING) << "EGLContextChanged"; + } bool submitted_new_frame = false; // SurfaceFactory::SubmitCompositorFrame might call glFlush. So calling it
diff --git a/android_webview/browser/gfx/hardware_renderer.h b/android_webview/browser/gfx/hardware_renderer.h index 89b8607..5c4c250 100644 --- a/android_webview/browser/gfx/hardware_renderer.h +++ b/android_webview/browser/gfx/hardware_renderer.h
@@ -82,7 +82,9 @@ void CreateNewCompositorFrameSinkSupport(); - RenderThreadManager* render_thread_manager_; + RenderThreadManager* const render_thread_manager_; + + const scoped_refptr<SurfacesInstance> surfaces_; typedef void* EGLContext; EGLContext last_egl_context_; @@ -101,7 +103,6 @@ // been submitted. std::unique_ptr<ChildFrame> child_frame_; - const scoped_refptr<SurfacesInstance> surfaces_; viz::FrameSinkId frame_sink_id_; const std::unique_ptr<viz::ParentLocalSurfaceIdAllocator> parent_local_surface_id_allocator_;
diff --git a/android_webview/browser/gfx/surfaces_instance.cc b/android_webview/browser/gfx/surfaces_instance.cc index ec79f72a..de1fd24c 100644 --- a/android_webview/browser/gfx/surfaces_instance.cc +++ b/android_webview/browser/gfx/surfaces_instance.cc
@@ -10,6 +10,7 @@ #include "android_webview/browser/gfx/aw_gl_surface.h" #include "android_webview/browser/gfx/aw_render_thread_context_provider.h" +#include "android_webview/browser/gfx/aw_vulkan_context_provider.h" #include "android_webview/browser/gfx/deferred_gpu_command_service.h" #include "android_webview/browser/gfx/parent_output_surface.h" #include "android_webview/common/aw_switches.h" @@ -27,7 +28,6 @@ #include "components/viz/service/display_embedder/skia_output_surface_impl_non_ddl.h" #include "components/viz/service/frame_sinks/compositor_frame_sink_support.h" #include "components/viz/service/frame_sinks/frame_sink_manager_impl.h" -#include "gpu/command_buffer/service/shared_context_state.h" #include "ui/gfx/geometry/rect.h" #include "ui/gfx/geometry/size.h" #include "ui/gfx/presentation_feedback.h" @@ -85,6 +85,22 @@ this, frame_sink_manager_.get(), frame_sink_id_, is_root, needs_sync_points); + const bool use_skia_renderer = + settings.use_skia_renderer || settings.use_skia_renderer_non_ddl; + auto* command_line = base::CommandLine::ForCurrentProcess(); + const bool enable_vulkan = + command_line->HasSwitch(switches::kWebViewEnableVulkan); + const bool enable_shared_image = + command_line->HasSwitch(switches::kWebViewEnableSharedImage); + LOG_IF(FATAL, enable_vulkan && !enable_shared_image) + << "--webview-enable-vulkan only works with shared image " + "(--webview-enable-shared-image)."; + LOG_IF(FATAL, enable_vulkan && !use_skia_renderer) + << "--webview-enable-vulkan only works with skia renderer " + "(--enable-features=UseSkiaRenderer or UseSkiaRendererNonDDL)."; + + auto vulkan_context_provider = + enable_vulkan ? AwVulkanContextProvider::GetOrCreateInstance() : nullptr; std::unique_ptr<viz::OutputSurface> output_surface; viz::SkiaOutputSurface* skia_output_surface = nullptr; if (settings.use_skia_renderer || settings.use_skia_renderer_non_ddl) { @@ -98,8 +114,7 @@ shared_context_state_ = base::MakeRefCounted<gpu::SharedContextState>( task_executor->share_group(), std::move(surface), std::move(gl_context), false /* use_virtualized_gl_contexts */, - base::BindOnce(&OnContextLost), - nullptr /* vulkan_context_provider */); + base::BindOnce(&OnContextLost), vulkan_context_provider.get()); shared_context_state_->InitializeGrContext( gpu::GpuDriverBugWorkarounds(task_executor->gpu_feature_info() .enabled_gpu_driver_bug_workarounds), @@ -135,9 +150,6 @@ nullptr /* shared_bitmap_manager */, settings, frame_sink_id_, std::move(output_surface), std::move(scheduler), nullptr /* current_task_runner */, skia_output_surface); - const bool enable_shared_image = - base::CommandLine::ForCurrentProcess()->HasSwitch( - switches::kWebViewEnableSharedImage); display_->Initialize(this, frame_sink_manager_->surface_manager(), enable_shared_image); frame_sink_manager_->RegisterBeginFrameSource(begin_frame_source_.get(),
diff --git a/android_webview/browser/gfx/surfaces_instance.h b/android_webview/browser/gfx/surfaces_instance.h index 43430eeb..737cd6b 100644 --- a/android_webview/browser/gfx/surfaces_instance.h +++ b/android_webview/browser/gfx/surfaces_instance.h
@@ -15,6 +15,7 @@ #include "components/viz/common/surfaces/local_surface_id_allocation.h" #include "components/viz/common/surfaces/surface_id.h" #include "components/viz/service/display/display_client.h" +#include "gpu/command_buffer/service/shared_context_state.h" #include "services/viz/public/interfaces/compositing/compositor_frame_sink.mojom.h" #include "ui/gfx/color_space.h" @@ -24,10 +25,6 @@ class Transform; } -namespace gpu { -class SharedContextState; -} - namespace viz { class BeginFrameSource; class CompositorFrameSinkSupport; @@ -56,6 +53,10 @@ void AddChildId(const viz::SurfaceId& child_id); void RemoveChildId(const viz::SurfaceId& child_id); + bool is_using_vulkan() const { + return shared_context_state_ && + shared_context_state_->use_vulkan_gr_context(); + } private: friend class base::RefCounted<SurfacesInstance>;
diff --git a/android_webview/browser/net/aw_url_request_context_getter.cc b/android_webview/browser/net/aw_url_request_context_getter.cc index 0dfc0d4..0e947ea 100644 --- a/android_webview/browser/net/aw_url_request_context_getter.cc +++ b/android_webview/browser/net/aw_url_request_context_getter.cc
@@ -17,7 +17,7 @@ #include "android_webview/browser/net/aw_request_interceptor.h" #include "android_webview/browser/net/aw_url_request_job_factory.h" #include "android_webview/browser/net/init_native_callback.h" -#include "android_webview/browser/net_helpers.h" +#include "android_webview/browser/network_service/net_helpers.h" #include "android_webview/common/aw_content_client.h" #include "base/base_paths_android.h" #include "base/bind.h"
diff --git a/android_webview/browser/net_network_service/OWNERS b/android_webview/browser/network_service/OWNERS similarity index 100% rename from android_webview/browser/net_network_service/OWNERS rename to android_webview/browser/network_service/OWNERS
diff --git a/android_webview/browser/net_network_service/android_stream_reader_url_loader.cc b/android_webview/browser/network_service/android_stream_reader_url_loader.cc similarity index 99% rename from android_webview/browser/net_network_service/android_stream_reader_url_loader.cc rename to android_webview/browser/network_service/android_stream_reader_url_loader.cc index 503030a..64e46e6 100644 --- a/android_webview/browser/net_network_service/android_stream_reader_url_loader.cc +++ b/android_webview/browser/network_service/android_stream_reader_url_loader.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 "android_webview/browser/net_network_service/android_stream_reader_url_loader.h" +#include "android_webview/browser/network_service/android_stream_reader_url_loader.h" #include "android_webview/browser/input_stream.h" #include "android_webview/browser/net/input_stream_reader.h"
diff --git a/android_webview/browser/net_network_service/android_stream_reader_url_loader.h b/android_webview/browser/network_service/android_stream_reader_url_loader.h similarity index 93% rename from android_webview/browser/net_network_service/android_stream_reader_url_loader.h rename to android_webview/browser/network_service/android_stream_reader_url_loader.h index 6d8b1d6..1fb971bb 100644 --- a/android_webview/browser/net_network_service/android_stream_reader_url_loader.h +++ b/android_webview/browser/network_service/android_stream_reader_url_loader.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 ANDROID_WEBVIEW_BROWSER_NET_NETWORK_SERVICE_ANDROID_STREAM_READER_URL_LOADER_H_ -#define ANDROID_WEBVIEW_BROWSER_NET_NETWORK_SERVICE_ANDROID_STREAM_READER_URL_LOADER_H_ +#ifndef ANDROID_WEBVIEW_BROWSER_NETWORK_SERVICE_ANDROID_STREAM_READER_URL_LOADER_H_ +#define ANDROID_WEBVIEW_BROWSER_NETWORK_SERVICE_ANDROID_STREAM_READER_URL_LOADER_H_ #include "android_webview/browser/net/aw_web_resource_response.h" #include "base/threading/thread_checker.h" @@ -107,4 +107,4 @@ } // namespace android_webview -#endif +#endif // ANDROID_WEBVIEW_BROWSER_NETWORK_SERVICE_ANDROID_STREAM_READER_URL_LOADER_H_
diff --git a/android_webview/browser/net_network_service/android_stream_reader_url_loader_unittest.cc b/android_webview/browser/network_service/android_stream_reader_url_loader_unittest.cc similarity index 99% rename from android_webview/browser/net_network_service/android_stream_reader_url_loader_unittest.cc rename to android_webview/browser/network_service/android_stream_reader_url_loader_unittest.cc index 42a72ff..c030ca4 100644 --- a/android_webview/browser/net_network_service/android_stream_reader_url_loader_unittest.cc +++ b/android_webview/browser/network_service/android_stream_reader_url_loader_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 "android_webview/browser/net_network_service/android_stream_reader_url_loader.h" +#include "android_webview/browser/network_service/android_stream_reader_url_loader.h" #include "android_webview/browser/input_stream.h" #include "base/run_loop.h"
diff --git a/android_webview/browser/net_network_service/aw_cookie_manager_wrapper.cc b/android_webview/browser/network_service/aw_cookie_manager_wrapper.cc similarity index 96% rename from android_webview/browser/net_network_service/aw_cookie_manager_wrapper.cc rename to android_webview/browser/network_service/aw_cookie_manager_wrapper.cc index 096a60f..32601f7 100644 --- a/android_webview/browser/net_network_service/aw_cookie_manager_wrapper.cc +++ b/android_webview/browser/network_service/aw_cookie_manager_wrapper.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 "android_webview/browser/net_network_service/aw_cookie_manager_wrapper.h" +#include "android_webview/browser/network_service/aw_cookie_manager_wrapper.h" #include "base/feature_list.h" #include "services/network/public/cpp/features.h"
diff --git a/android_webview/browser/net_network_service/aw_cookie_manager_wrapper.h b/android_webview/browser/network_service/aw_cookie_manager_wrapper.h similarity index 90% rename from android_webview/browser/net_network_service/aw_cookie_manager_wrapper.h rename to android_webview/browser/network_service/aw_cookie_manager_wrapper.h index 81aca263..8481e8c 100644 --- a/android_webview/browser/net_network_service/aw_cookie_manager_wrapper.h +++ b/android_webview/browser/network_service/aw_cookie_manager_wrapper.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 ANDROID_WEBVIEW_BROWSER_NET_NETWORK_SERVICE_AW_COOKIE_MANAGER_WRAPPER_H_ -#define ANDROID_WEBVIEW_BROWSER_NET_NETWORK_SERVICE_AW_COOKIE_MANAGER_WRAPPER_H_ +#ifndef ANDROID_WEBVIEW_BROWSER_NETWORK_SERVICE_AW_COOKIE_MANAGER_WRAPPER_H_ +#define ANDROID_WEBVIEW_BROWSER_NETWORK_SERVICE_AW_COOKIE_MANAGER_WRAPPER_H_ #include "base/callback.h" #include "net/cookies/cookie_store.h" @@ -65,4 +65,4 @@ } // namespace android_webview -#endif // ANDROID_WEBVIEW_BROWSER_NET_NETWORK_SERVICE_AW_COOKIE_MANAGER_WRAPPER_H_ +#endif // ANDROID_WEBVIEW_BROWSER_NETWORK_SERVICE_AW_COOKIE_MANAGER_WRAPPER_H_
diff --git a/android_webview/browser/aw_proxying_url_loader_factory.cc b/android_webview/browser/network_service/aw_proxying_url_loader_factory.cc similarity index 98% rename from android_webview/browser/aw_proxying_url_loader_factory.cc rename to android_webview/browser/network_service/aw_proxying_url_loader_factory.cc index 393dae2..385e2203 100644 --- a/android_webview/browser/aw_proxying_url_loader_factory.cc +++ b/android_webview/browser/network_service/aw_proxying_url_loader_factory.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 "android_webview/browser/aw_proxying_url_loader_factory.h" +#include "android_webview/browser/network_service/aw_proxying_url_loader_factory.h" #include <utility> @@ -12,8 +12,8 @@ #include "android_webview/browser/aw_cookie_access_policy.h" #include "android_webview/browser/input_stream.h" #include "android_webview/browser/net/aw_web_resource_response.h" -#include "android_webview/browser/net_helpers.h" -#include "android_webview/browser/net_network_service/android_stream_reader_url_loader.h" +#include "android_webview/browser/network_service/android_stream_reader_url_loader.h" +#include "android_webview/browser/network_service/net_helpers.h" #include "android_webview/browser/renderer_host/auto_login_parser.h" #include "android_webview/common/url_constants.h" #include "base/android/build_info.h" @@ -277,7 +277,6 @@ } void InterceptedRequest::Restart() { - std::unique_ptr<AwContentsIoThreadClient> io_thread_client = GetIoThreadClient(); DCHECK(io_thread_client);
diff --git a/android_webview/browser/aw_proxying_url_loader_factory.h b/android_webview/browser/network_service/aw_proxying_url_loader_factory.h similarity index 92% rename from android_webview/browser/aw_proxying_url_loader_factory.h rename to android_webview/browser/network_service/aw_proxying_url_loader_factory.h index 2585ff3..6a457e6 100644 --- a/android_webview/browser/aw_proxying_url_loader_factory.h +++ b/android_webview/browser/network_service/aw_proxying_url_loader_factory.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 ANDROID_WEBVIEW_BROWSER_AW_PROXYING_URL_LOADER_FACTORY_H_ -#define ANDROID_WEBVIEW_BROWSER_AW_PROXYING_URL_LOADER_FACTORY_H_ +#ifndef ANDROID_WEBVIEW_BROWSER_NETWORK_SERVICE_AW_PROXYING_URL_LOADER_FACTORY_H_ +#define ANDROID_WEBVIEW_BROWSER_NETWORK_SERVICE_AW_PROXYING_URL_LOADER_FACTORY_H_ #include "base/callback.h" #include "base/macros.h" @@ -86,4 +86,4 @@ } // namespace android_webview -#endif +#endif // ANDROID_WEBVIEW_BROWSER_NETWORK_SERVICE_AW_PROXYING_URL_LOADER_FACTORY_H_
diff --git a/android_webview/browser/aw_url_loader_throttle.cc b/android_webview/browser/network_service/aw_url_loader_throttle.cc similarity index 95% rename from android_webview/browser/aw_url_loader_throttle.cc rename to android_webview/browser/network_service/aw_url_loader_throttle.cc index 96d619ed..cc96d28 100644 --- a/android_webview/browser/aw_url_loader_throttle.cc +++ b/android_webview/browser/network_service/aw_url_loader_throttle.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 "android_webview/browser/aw_url_loader_throttle.h" +#include "android_webview/browser/network_service/aw_url_loader_throttle.h" #include "android_webview/browser/aw_resource_context.h" #include "content/public/browser/browser_thread.h"
diff --git a/android_webview/browser/aw_url_loader_throttle.h b/android_webview/browser/network_service/aw_url_loader_throttle.h similarity index 84% rename from android_webview/browser/aw_url_loader_throttle.h rename to android_webview/browser/network_service/aw_url_loader_throttle.h index a003b85..38901ed 100644 --- a/android_webview/browser/aw_url_loader_throttle.h +++ b/android_webview/browser/network_service/aw_url_loader_throttle.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 ANDROID_WEBVIEW_BROWSER_AW_URL_LOADER_THROTTLE_H_ -#define ANDROID_WEBVIEW_BROWSER_AW_URL_LOADER_THROTTLE_H_ +#ifndef ANDROID_WEBVIEW_BROWSER_NETWORK_SERVICE_AW_URL_LOADER_THROTTLE_H_ +#define ANDROID_WEBVIEW_BROWSER_NETWORK_SERVICE_AW_URL_LOADER_THROTTLE_H_ #include "base/macros.h" #include "content/public/common/url_loader_throttle.h" @@ -47,4 +47,4 @@ } // namespace android_webview -#endif // ANDROID_WEBVIEW_BROWSER_AW_URL_LOADER_THROTTLE_H_ +#endif // ANDROID_WEBVIEW_BROWSER_NETWORK_SERVICE_AW_URL_LOADER_THROTTLE_H_
diff --git a/android_webview/browser/net_helpers.cc b/android_webview/browser/network_service/net_helpers.cc similarity index 97% rename from android_webview/browser/net_helpers.cc rename to android_webview/browser/network_service/net_helpers.cc index 473806f..b165c89f 100644 --- a/android_webview/browser/net_helpers.cc +++ b/android_webview/browser/network_service/net_helpers.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 "android_webview/browser/net_helpers.h" +#include "android_webview/browser/network_service/net_helpers.h" #include "android_webview/browser/aw_contents_io_thread_client.h" #include "android_webview/common/url_constants.h"
diff --git a/android_webview/browser/net_helpers.h b/android_webview/browser/network_service/net_helpers.h similarity index 78% rename from android_webview/browser/net_helpers.h rename to android_webview/browser/network_service/net_helpers.h index e03bd56..7ab6be3 100644 --- a/android_webview/browser/net_helpers.h +++ b/android_webview/browser/network_service/net_helpers.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 ANDROID_WEBVIEW_BROWSER_NET_HELPERS_H_ -#define ANDROID_WEBVIEW_BROWSER_NET_HELPERS_H_ +#ifndef ANDROID_WEBVIEW_BROWSER_NETWORK_SERVICE_NET_HELPERS_H_ +#define ANDROID_WEBVIEW_BROWSER_NETWORK_SERVICE_NET_HELPERS_H_ #include <memory> @@ -26,4 +26,4 @@ } // namespace android_webview -#endif // ANDROID_WEBVIEW_BROWSER_NET_HELPERS_H_ +#endif // ANDROID_WEBVIEW_BROWSER_NETWORK_SERVICE_NET_HELPERS_H_
diff --git a/android_webview/browser/renderer_host/aw_resource_dispatcher_host_delegate.cc b/android_webview/browser/renderer_host/aw_resource_dispatcher_host_delegate.cc index da8612c4..7eafcf1 100644 --- a/android_webview/browser/renderer_host/aw_resource_dispatcher_host_delegate.cc +++ b/android_webview/browser/renderer_host/aw_resource_dispatcher_host_delegate.cc
@@ -13,7 +13,7 @@ #include "android_webview/browser/aw_contents_io_thread_client.h" #include "android_webview/browser/aw_resource_context.h" #include "android_webview/browser/net/aw_web_resource_request.h" -#include "android_webview/browser/net_helpers.h" +#include "android_webview/browser/network_service/net_helpers.h" #include "android_webview/browser/renderer_host/auto_login_parser.h" #include "android_webview/browser/safe_browsing/aw_safe_browsing_resource_throttle.h" #include "android_webview/common/url_constants.h"
diff --git a/android_webview/common/aw_switches.cc b/android_webview/common/aw_switches.cc index c909a271..2cd0d8e 100644 --- a/android_webview/common/aw_switches.cc +++ b/android_webview/common/aw_switches.cc
@@ -19,4 +19,7 @@ // Used to enable shared image API for webview. const char kWebViewEnableSharedImage[] = "webview-enable-shared-image"; +// Used to enable vulkan draw mode instead of interop draw mode for webview. +const char kWebViewEnableVulkan[] = "webview-enable-vulkan"; + } // namespace switches
diff --git a/android_webview/common/aw_switches.h b/android_webview/common/aw_switches.h index 410c1c8..eae36e3 100644 --- a/android_webview/common/aw_switches.h +++ b/android_webview/common/aw_switches.h
@@ -11,6 +11,7 @@ extern const char kWebViewEnableSafeBrowsingSupport[]; extern const char kWebViewDisableSafeBrowsingSupport[]; extern const char kWebViewEnableSharedImage[]; +extern const char kWebViewEnableVulkan[]; // Please note that if you are adding a flag that is intended for a renderer, // you also need to add it into
diff --git a/android_webview/test/BUILD.gn b/android_webview/test/BUILD.gn index 56c1a68..e7f8bd9f 100644 --- a/android_webview/test/BUILD.gn +++ b/android_webview/test/BUILD.gn
@@ -347,7 +347,7 @@ "../browser/net/aw_cookie_store_wrapper_unittest.cc", "../browser/net/aw_url_request_context_getter_unittest.cc", "../browser/net/input_stream_reader_unittest.cc", - "../browser/net_network_service/android_stream_reader_url_loader_unittest.cc", + "../browser/network_service/android_stream_reader_url_loader_unittest.cc", "../browser/permission/media_access_permission_request_unittest.cc", "../browser/permission/permission_request_handler_unittest.cc", "../browser/renderer_host/auto_login_parser_unittest.cc",
diff --git a/android_webview/ui/grit_resources_whitelist.txt b/android_webview/ui/grit_resources_whitelist.txt index 63836fa4..e39792b3 100644 --- a/android_webview/ui/grit_resources_whitelist.txt +++ b/android_webview/ui/grit_resources_whitelist.txt
@@ -1,6 +1,5 @@ IDR_WEBUI_JS_LOAD_TIME_DATA IDR_WEBUI_JSTEMPLATE_JS -IDR_WEBUI_I18N_TEMPLATE_JS IDR_SECURITY_INTERSTITIAL_HTML IDR_WEBUI_CSS_TEXT_DEFAULTS IDR_SECURITY_INTERSTITIAL_QUIET_HTML
diff --git a/ash/app_list/app_list_metrics.h b/ash/app_list/app_list_metrics.h index b2e65144..f24ad68 100644 --- a/ash/app_list/app_list_metrics.h +++ b/ash/app_list/app_list_metrics.h
@@ -184,7 +184,8 @@ kMouseWheelScroll = 4, kMousePadScroll = 5, kDragAppToBorder = 6, - kMaxAppListPageSwitcherSource = 7, + kMoveAppWithKeyboard = 7, + kMaxAppListPageSwitcherSource = 8, }; // The different ways to move an app in app list's apps grid. These values are @@ -194,9 +195,11 @@ kMoveIntoFolder = 0, kMoveOutOfFolder = 1, kMoveIntoAnotherFolder = 2, - kReorderInFolder = 3, - kReorderInTopLevel = 4, - kMaxAppListAppMovingType = 5, + kReorderByDragInFolder = 3, + kReorderByDragInTopLevel = 4, + kReorderByKeyboardInFolder = 5, + kReorderByKeyboardInTopLevel = 6, + kMaxAppListAppMovingType = 7, }; // Different places a search result can be launched from. These values do not
diff --git a/ash/app_list/app_list_util.cc b/ash/app_list/app_list_util.cc index 89d6e4f..63abb3c 100644 --- a/ash/app_list/app_list_util.cc +++ b/ash/app_list/app_list_util.cc
@@ -38,6 +38,10 @@ if (!IsUnhandledUnmodifiedEvent(event)) return false; + return IsArrowKeyEvent(event); +} + +bool IsArrowKeyEvent(const ui::KeyEvent& event) { return event.key_code() == ui::VKEY_DOWN || event.key_code() == ui::VKEY_RIGHT || event.key_code() == ui::VKEY_LEFT || event.key_code() == ui::VKEY_UP;
diff --git a/ash/app_list/app_list_util.h b/ash/app_list/app_list_util.h index 857f8d19..8ed3e10 100644 --- a/ash/app_list/app_list_util.h +++ b/ash/app_list/app_list_util.h
@@ -26,6 +26,9 @@ // (unmodified by ctrl, shift, or alt) APP_LIST_EXPORT bool IsUnhandledArrowKeyEvent(const ui::KeyEvent& event); +// Returns whether the event is an arrow key event. +APP_LIST_EXPORT bool IsArrowKeyEvent(const ui::KeyEvent& event); + // Returns true if the arrow key event should move focus away from the // |textfield|. This is usually when the insertion point would move away from // text.
diff --git a/ash/app_list/paged_view_structure.cc b/ash/app_list/paged_view_structure.cc index e6570a0..aba1522 100644 --- a/ash/app_list/paged_view_structure.cc +++ b/ash/app_list/paged_view_structure.cc
@@ -237,6 +237,8 @@ target_model_index += page.size(); // Skip the item view to be moved in the page if found. + // Decrement |target_model_index| if |moved_view| is in this page because it + // is represented by a placeholder. auto iter = std::find(page.begin(), page.end(), moved_view); if (iter != page.end()) --target_model_index; @@ -307,6 +309,10 @@ return false; } +void PagedViewStructure::AppendPage() { + pages_.emplace_back(); +} + bool PagedViewStructure::IsFullPage(int page_index) const { if (page_index >= total_pages()) return false;
diff --git a/ash/app_list/paged_view_structure.h b/ash/app_list/paged_view_structure.h index cfd445cb..bb66bbd 100644 --- a/ash/app_list/paged_view_structure.h +++ b/ash/app_list/paged_view_structure.h
@@ -61,7 +61,7 @@ GridIndex GetLastTargetIndex() const; // Returns the last possible visual index to add an item view in the specified - // page. + // page, used only for drag reordering. GridIndex GetLastTargetIndexOfPage(int page_index) const; // Returns the target model index if moving the item view to specified target @@ -78,6 +78,9 @@ // can be moved. bool IsValidReorderTargetIndex(const GridIndex& index) const; + // Adds a page break at the end of |pages_|. + void AppendPage(); + // Returns true if the page has no empty slot. bool IsFullPage(int page_index) const; @@ -100,9 +103,7 @@ // Removes empty page. Returns true if view structure is changed. bool ClearEmptyPages(); - // Represents the item views' locations in each page. This is only used when - // apps grid gap is enabled. (We don't need this in non-gap apps grid since - // all item views are linearly laid out in |view_model_|.) + // Represents the item views' locations in each page. Pages pages_; AppsGridView* const apps_grid_view_; // Not owned.
diff --git a/ash/app_list/pagination_model.h b/ash/app_list/pagination_model.h index 4dc2e82..21187d1 100644 --- a/ash/app_list/pagination_model.h +++ b/ash/app_list/pagination_model.h
@@ -61,8 +61,8 @@ // Whether the page relative |delta| is valid. bool IsValidPageRelative(int delta) const; - // Immediately completes all queued animations, jumping directly to the final - // target page. + // Immediately completes all queued animations, jumping directly to the + // final target page. void FinishAnimation(); void SetTransition(const Transition& transition);
diff --git a/ash/app_list/views/app_list_view.cc b/ash/app_list/views/app_list_view.cc index 6a59675..787ef01 100644 --- a/ash/app_list/views/app_list_view.cc +++ b/ash/app_list/views/app_list_view.cc
@@ -1621,8 +1621,9 @@ if (is_search_box_focused || is_folder_header_view_focused) return; - // Do not redirect the arrow keys as they are are used for focus traversal. - if (IsUnhandledArrowKeyEvent(*event)) + // Do not redirect the arrow keys as they are are used for focus traversal and + // app movement. + if (IsArrowKeyEvent(*event)) return; // Redirect key event to |search_box_|.
diff --git a/ash/app_list/views/apps_grid_view.cc b/ash/app_list/views/apps_grid_view.cc index 5a1f400..9bf7881d 100644 --- a/ash/app_list/views/apps_grid_view.cc +++ b/ash/app_list/views/apps_grid_view.cc
@@ -238,6 +238,12 @@ } // namespace +std::string GridIndex::ToString() const { + std::stringstream ss; + ss << "Page: " << page << ", Slot: " << slot; + return ss.str(); +} + // A layer delegate used for AppsGridView's mask layer, with top and bottom // gradient fading out zones. class AppsGridView::FadeoutLayerDelegate : public ui::LayerDelegate { @@ -536,9 +542,9 @@ // If a drag and drop host is provided, see if the drag operation needs to be // forwarded. - gfx::Point location_in_screen = drag_point_in_grid_view; - views::View::ConvertPointToScreen(this, &location_in_screen); - DispatchDragEventToDragAndDropHost(location_in_screen); + gfx::Point drag_point_in_screen = drag_point_in_grid_view; + views::View::ConvertPointToScreen(this, &drag_point_in_screen); + DispatchDragEventToDragAndDropHost(drag_point_in_screen); if (drag_and_drop_host_) { drag_and_drop_host_->UpdateDragIconProxyByLocation( drag_view_->GetIconBoundsInScreen().origin()); @@ -553,7 +559,7 @@ if (!drag_view_) return; // Drag canceled. - gfx::Vector2d drag_vector(point - drag_start_grid_view_); + const gfx::Vector2d drag_vector(point - drag_start_grid_view_); if (!dragging() && ExceededDragThreshold(drag_vector)) TryStartDragAndDropHostDrag(pointer, point); @@ -661,6 +667,8 @@ // Ensure reorder event has already been announced by the end of drag. MaybeCreateReorderAccessibilityEvent(); MoveItemInModel(drag_view_, drop_target_); + RecordAppMovingTypeMetrics(folder_delegate_ ? kReorderByDragInFolder + : kReorderByDragInTopLevel); } } } @@ -725,6 +733,8 @@ } AppListItemView* AppsGridView::GetItemViewAt(int index) const { + if (index < 0 || index >= view_model_.view_size()) + return nullptr; return view_model_.view_at(index); } @@ -923,6 +933,16 @@ } bool AppsGridView::OnKeyPressed(const ui::KeyEvent& event) { + // The user may press VKEY_CONTROL before an arrow key when intending to do an + // app move with control+arrow. + if (event.key_code() == ui::VKEY_CONTROL) + return true; + + if (IsArrowKeyEvent(event) && event.IsControlDown()) { + HandleKeyboardAppMovement(event.key_code()); + return true; + } + // Let the FocusManager handle Left/Right keys. if (!IsUnhandledUpDownKeyEvent(event)) return false; @@ -931,6 +951,16 @@ ui::VKEY_UP /* arrow_up */); } +bool AppsGridView::OnKeyReleased(const ui::KeyEvent& event) { + if (event.IsControlDown() || !handling_keyboard_move_) + return false; + + handling_keyboard_move_ = false; + RecordAppMovingTypeMetrics(folder_delegate_ ? kReorderByKeyboardInFolder + : kReorderByKeyboardInTopLevel); + return false; +} + void AppsGridView::ViewHierarchyChanged( const ViewHierarchyChangedDetails& details) { if (!details.is_add && details.parent == this) { @@ -1563,6 +1593,24 @@ return folder_delegate_->IsOEMFolder(); } +void AppsGridView::HandleKeyboardAppMovement(ui::KeyboardCode key_code) { + // TODO(newcomer): Support app movement via key in folders. + if (folder_delegate_) + return; + + DCHECK(selected_view_); + const GridIndex target_index = GetTargetGridIndexForKeyboardMove(key_code); + + if (target_index == GetIndexOfView(selected_view_) || + !IsValidReorderTargetIndex(target_index)) { + return; + } + + handling_keyboard_move_ = true; + + MoveAppListItemViewForKeyboardMove(target_index); +} + bool AppsGridView::HandleVerticalFocusMovement(bool arrow_up) { views::View* focused = GetFocusManager()->GetFocusedView(); if (focused->GetClassName() != AppListItemView::kViewClassName) @@ -1822,14 +1870,9 @@ void AppsGridView::StartDragAndDropHostDrag(const gfx::Point& grid_location) { // When a drag and drop host is given, the item can be dragged out of the app // list window. In that case a proxy widget needs to be used. - // Note: This code has very likely to be changed for Windows (non metro mode) - // when a |drag_and_drop_host_| gets implemented. if (!drag_view_ || !drag_and_drop_host_) return; - gfx::Point screen_location = grid_location; - views::View::ConvertPointToScreen(this, &screen_location); - // Determine the mouse offset to the center of the icon so that the drag and // drop host follows this layer. gfx::Vector2d delta = @@ -1948,33 +1991,30 @@ } void AppsGridView::MoveItemInModel(AppListItemView* item_view, - const GridIndex& target) { + const GridIndex& target, + bool clear_overflow) { int current_model_index = view_model_.GetIndexOfView(item_view); - size_t current_item_index; - item_list_->FindItemIndex(item_view->item()->id(), ¤t_item_index); + size_t current_item_list_index; + item_list_->FindItemIndex(item_view->item()->id(), ¤t_item_list_index); DCHECK_GE(current_model_index, 0); int target_model_index = GetTargetModelIndexForMove(item_view, target); - size_t target_item_index = GetTargetItemIndexForMove(item_view, target); - + size_t target_item_list_index = GetTargetItemIndexForMove(item_view, target); // The same item index does not guarantee the same visual index, so move the // item visual index here. if (!folder_delegate_) - view_structure_.Move(item_view, target); + view_structure_.Move(item_view, target, clear_overflow); // Reorder the app list item views in accordance with |view_model_|. ReorderChildView(item_view, target_model_index); - if (target_item_index == current_item_index) + if (target_item_list_index == current_item_list_index) return; item_list_->RemoveObserver(this); - item_list_->MoveItem(current_item_index, target_item_index); + item_list_->MoveItem(current_item_list_index, target_item_list_index); view_model_.Move(current_model_index, target_model_index); item_list_->AddObserver(this); - - RecordAppMovingTypeMetrics(folder_delegate_ ? kReorderInFolder - : kReorderInTopLevel); } void AppsGridView::MoveItemToFolder(AppListItemView* item_view, @@ -2572,6 +2612,128 @@ return GetModelIndexFromIndex(index); } +GridIndex AppsGridView::GetTargetGridIndexForKeyboardMove( + ui::KeyboardCode key_code) const { + DCHECK(key_code == ui::VKEY_LEFT || key_code == ui::VKEY_RIGHT || + key_code == ui::VKEY_UP || key_code == ui::VKEY_DOWN); + DCHECK(selected_view_); + + const GridIndex source_index = GetIndexOfView(selected_view_); + GridIndex target_index; + if (key_code == ui::VKEY_LEFT || key_code == ui::VKEY_RIGHT) { + // Define backward key for traversal based on RTL. + const ui::KeyboardCode backward = + base::i18n::IsRTL() ? ui::VKEY_RIGHT : ui::VKEY_LEFT; + + const int target_model_index = view_model_.GetIndexOfView(selected_view_) + + ((key_code == backward) ? -1 : 1); + + // A forward move on the last item in |view_model_| should result in page + // creation + if (target_model_index == view_model_.view_size()) { + // If |source_index| is the last item in the grid on a page by itself, + // moving right to a new page should be a no-op. + if (view_structure_.items_on_page(source_index.page) == 1) + return source_index; + return GridIndex(pagination_model_.total_pages(), 0); + } + + target_index = GetIndexOfView( + static_cast<const AppListItemView*>(GetItemViewAt(std::min( + std::max(0, target_model_index), view_model_.view_size() - 1)))); + if (key_code == backward && target_index.page < source_index.page && + !view_structure_.IsFullPage(target_index.page)) { + // Apps swap positions if the target page is the same as the + // destination page, or the target page is full. If the page is not + // full the app is dumped on the page. Increase the slot in this case + // to account for the new available spot. + ++target_index.slot; + } + return target_index; + } + + // Handle the vertical move. Attempt to place the app in the same column. + int target_page = source_index.page; + int target_row = + source_index.slot / cols_ + (key_code == ui::VKEY_UP ? -1 : 1); + + if (target_row < 0) { + // The app will move to the last row of the previous page. + --target_page; + if (target_page < 0) + return source_index; + + // When moving up, place the app in the last row. + target_row = (GetItemsNumOfPage(target_page) - 1) / cols_; + } else if (target_row > (GetItemsNumOfPage(target_page) - 1) / cols_) { + // The app will move to the first row of the next page. + ++target_page; + if (target_page >= view_structure_.total_pages()) { + // If |source_index| page only has one item, moving down to a new page + // should be a no-op. + if (view_structure_.items_on_page(source_index.page) == 1) + return source_index; + return GridIndex(target_page, 0); + } + target_row = 0; + } + + // If the app is being moved to a new page there is 1 extra slot available. + const int last_slot_in_target_page = + view_structure_.items_on_page(target_page) - + (source_index.page != target_page ? 0 : 1); + // The ideal slot shares a column with |source_index|. + const int ideal_slot = target_row * cols_ + source_index.slot % cols_; + return GridIndex(target_page, std::min(last_slot_in_target_page, ideal_slot)); +} + +void AppsGridView::MoveAppListItemViewForKeyboardMove( + const GridIndex& target_index) { + DCHECK(selected_view_); + + if (target_index.page == pagination_model_.total_pages()) + view_structure_.AppendPage(); + + AppListItemView* original_selected_view = selected_view_; + const GridIndex original_selected_view_index = + GetIndexOfView(original_selected_view); + // Moving an AppListItemView is either a swap within the origin page, a swap + // to a full page, or a dump to a page with room. + const bool swap_items = + view_structure_.IsFullPage(target_index.page) || + target_index.page == original_selected_view_index.page; + + AppListItemView* target_view = GetViewAtIndex(target_index); + // If the move is a two part operation (swap) do not clear the overflow during + // the initial move. Clearing the overflow when |target_index| is on a full + // page results in the last item being pushed to the next page. + MoveItemInModel(selected_view_, target_index, !swap_items /*clear_overflow*/); + view_structure_.SaveToMetadata(); + + if (swap_items) { + DCHECK(target_view); + MoveItemInModel(target_view, original_selected_view_index); + view_structure_.SaveToMetadata(); + } + + // Update |pagination_model_| because the move could have resulted in a + // page getting collapsed or created. + if (view_structure_.total_pages() != pagination_model_.total_pages()) + pagination_model_.SetTotalPages(view_structure_.total_pages()); + + pagination_model_.SelectPage( + std::min(view_structure_.total_pages() - 1, target_index.page), + false /*animate*/); + SetSelectedView(original_selected_view); + Layout(); + + if (target_index.page != original_selected_view_index.page) { + UMA_HISTOGRAM_ENUMERATION(kAppListPageSwitcherSourceHistogram, + kMoveAppWithKeyboard, + kMaxAppListPageSwitcherSource); + } +} + size_t AppsGridView::GetTargetItemIndexForMove(AppListItemView* moved_view, const GridIndex& index) const { if (!folder_delegate_)
diff --git a/ash/app_list/views/apps_grid_view.h b/ash/app_list/views/apps_grid_view.h index 7e787fa1..bd7cdc9583 100644 --- a/ash/app_list/views/apps_grid_view.h +++ b/ash/app_list/views/apps_grid_view.h
@@ -9,6 +9,7 @@ #include <memory> #include <set> +#include <sstream> #include <string> #include <tuple> @@ -26,6 +27,7 @@ #include "build/build_config.h" #include "ui/base/models/list_model_observer.h" #include "ui/compositor/layer_animation_observer.h" +#include "ui/events/keycodes/keyboard_codes_posix.h" #include "ui/gfx/image/image_skia_operations.h" #include "ui/views/animation/bounds_animator.h" #include "ui/views/controls/button/button.h" @@ -65,6 +67,7 @@ bool operator<(const GridIndex& other) const { return std::tie(page, slot) < std::tie(other.page, other.slot); } + std::string ToString() const; int page; // Which page an item view is on. int slot; // Which slot in the page an item view is in. @@ -177,8 +180,10 @@ gfx::Size CalculatePreferredSize() const override; void Layout() override; bool OnKeyPressed(const ui::KeyEvent& event) override; + bool OnKeyReleased(const ui::KeyEvent& event) override; void ViewHierarchyChanged( const ViewHierarchyChangedDetails& details) override; + bool GetDropFormats(int* formats, std::set<ui::ClipboardFormatType>* format_types) override; bool CanDrop(const OSExchangeData& data) override; @@ -203,7 +208,8 @@ // Returns the ideal bounds of an AppListItemView in AppsGridView coordinates. const gfx::Rect& GetIdealBounds(AppListItemView* view) const; - // Returns the item view of the item at |index|. + // Returns the item view of the item at |index|, or nullptr if there is no + // view at |index|. AppListItemView* GetItemViewAt(int index) const; // Schedules an animation to show or hide the view. @@ -387,7 +393,12 @@ void OnPageFlipTimer(); // Updates |model_| to move item represented by |item_view| to |target| slot. - void MoveItemInModel(AppListItemView* item_view, const GridIndex& target); + // Pushes all items from |item_view|'s GridIndex + 1 to |target| back by 1 + // GridIndex slot. |clear_overflow| is whether, if |target| is on a full page, + // to push the overflow item to the next page. + void MoveItemInModel(AppListItemView* item_view, + const GridIndex& target, + bool clear_overflow = true); // Updates |model_| to move item represented by |item_view| into a folder // containing item located at |target| slot, also update |view_model_| for @@ -519,6 +530,10 @@ // Returns true if the grid view is under an OEM folder. bool IsUnderOEMFolder(); + // Handles moving the |selected_view_|, triggered by Control+Arrow + // up/down/left/right. + void HandleKeyboardAppMovement(ui::KeyboardCode key_code); + // Handle vertical focus movement triggered by arrow up and down. bool HandleVerticalFocusMovement(bool arrow_up); @@ -534,8 +549,7 @@ // Returns the last possible visual index to add an item view. GridIndex GetLastTargetIndex() const; - // Returns the last possible visual index to add an item view in the specified - // page. + // Returns the last possible visual index to add an item view in |page|. GridIndex GetLastTargetIndexOfPage(int page) const; // Returns the target model index if moving the item view to specified target @@ -569,6 +583,12 @@ // updated in item list but its item view has not been updated in view model. int GetTargetModelIndexFromItemIndex(size_t item_index); + // Returns the target GridIndex for a keyboard move. + GridIndex GetTargetGridIndexForKeyboardMove(ui::KeyboardCode key_code) const; + + // Swaps |selected_view_| and the item at |target_index|. + void MoveAppListItemViewForKeyboardMove(const GridIndex& target_index); + // Records the total number of pages, and the number of pages with empty slots // for UMA histograms. void RecordPageMetrics(); @@ -696,6 +716,9 @@ // when dragging a item inside a folder. bool drag_out_of_folder_container_ = false; + // Whether a sequence of keyboard moves are happening. + bool handling_keyboard_move_ = false; + // True if the drag_view_ item is a folder item being dragged for reparenting. bool dragging_for_reparent_item_ = false;
diff --git a/ash/app_list/views/apps_grid_view_unittest.cc b/ash/app_list/views/apps_grid_view_unittest.cc index 36fd66a3..ef03caa8 100644 --- a/ash/app_list/views/apps_grid_view_unittest.cc +++ b/ash/app_list/views/apps_grid_view_unittest.cc
@@ -258,18 +258,23 @@ apps_grid_view_->OnKeyPressed(key_event); } + void SimulateKeyReleased(ui::KeyboardCode key_code, int flags) { + ui::KeyEvent key_event(ui::ET_KEY_RELEASED, key_code, flags); + apps_grid_view_->OnKeyReleased(key_event); + } + // Tests that the order of item views in the AppsGridView is in accordance // with the order in the view model. void TestAppListItemViewIndice() { const views::ViewModelT<AppListItemView>* view_model = apps_grid_view_->view_model(); DCHECK_GT(view_model->view_size(), 0); - const int initial_index = - apps_grid_view_->GetIndexOf(view_model->view_at(0)); - DCHECK_NE(-1, initial_index); - for (int i = 0; i < view_model->view_size(); ++i) { - EXPECT_EQ(view_model->view_at(i), - apps_grid_view_->child_at(i + initial_index)); + auto app_iter = apps_grid_view_->FindChild(view_model->view_at(0)); + DCHECK(app_iter != apps_grid_view_->children().cend()); + for (int i = 1; i < view_model->view_size(); ++i) { + ++app_iter; + ASSERT_NE(apps_grid_view_->children().cend(), app_iter); + EXPECT_EQ(view_model->view_at(i), *app_iter); } } @@ -951,6 +956,386 @@ test_api_->LayoutToIdealBounds(); } +// Test that control+arrow swaps app within the same page. +TEST_F(AppsGridViewTest, ControlArrowSwapsAppsWithinSamePage) { + model_->PopulateApps(GetTilesPerPage(0)); + + AppListItemView* moving_item = GetItemViewAt(0); + apps_grid_view_->GetFocusManager()->SetFocusedView(moving_item); + + // Test that moving left from 0,0 does not move the app. + SimulateKeyPress(ui::VKEY_LEFT, ui::EF_CONTROL_DOWN); + + EXPECT_EQ(moving_item, test_api_->GetViewAtVisualIndex(0, 0)); + EXPECT_TRUE(apps_grid_view_->IsSelectedView(moving_item)); + + // Test that moving up from 0,0 does not move the app. + SimulateKeyPress(ui::VKEY_UP, ui::EF_CONTROL_DOWN); + + EXPECT_EQ(moving_item, GetItemViewAt(0)); + EXPECT_TRUE(apps_grid_view_->IsSelectedView(moving_item)); + + // Test that moving right from 0,0 results in a swap with the item adjacent. + AppListItemView* swapped_item = GetItemViewAt(1); + SimulateKeyPress(ui::VKEY_RIGHT, ui::EF_CONTROL_DOWN); + + EXPECT_EQ(moving_item, GetItemViewAt(1)); + EXPECT_EQ(swapped_item, GetItemViewAt(0)); + EXPECT_TRUE(apps_grid_view_->IsSelectedView(moving_item)); + + // Test that moving down from 0,1 results in a swap with the item at 1,1. + swapped_item = GetItemViewAt(apps_grid_view_->cols() + 1); + SimulateKeyPress(ui::VKEY_DOWN, ui::EF_CONTROL_DOWN); + + EXPECT_EQ(moving_item, GetItemViewAt(apps_grid_view_->cols() + 1)); + EXPECT_EQ(swapped_item, GetItemViewAt(1)); + EXPECT_TRUE(apps_grid_view_->IsSelectedView(moving_item)); + + // Test that moving left from 1,1 results in a swap with the item at 1,0. + swapped_item = GetItemViewAt(apps_grid_view_->cols()); + SimulateKeyPress(ui::VKEY_LEFT, ui::EF_CONTROL_DOWN); + + EXPECT_EQ(moving_item, GetItemViewAt(apps_grid_view_->cols())); + EXPECT_EQ(swapped_item, GetItemViewAt(apps_grid_view_->cols() + 1)); + EXPECT_TRUE(apps_grid_view_->IsSelectedView(moving_item)); + + // Test that moving up from 1,0 results in a swap with the item at 0,0. + swapped_item = GetItemViewAt(0); + SimulateKeyPress(ui::VKEY_UP, ui::EF_CONTROL_DOWN); + + EXPECT_EQ(moving_item, GetItemViewAt(0)); + EXPECT_EQ(swapped_item, GetItemViewAt(apps_grid_view_->cols())); + EXPECT_TRUE(apps_grid_view_->IsSelectedView(moving_item)); +} + +// Tests that histograms are recorded when apps are moved with control+arrow. +TEST_F(AppsGridViewTest, ControlArrowRecordsHistogramBasic) { + base::HistogramTester histogram_tester; + model_->PopulateApps(GetTilesPerPage(0)); + + AppListItemView* moving_item = GetItemViewAt(0); + apps_grid_view_->GetFocusManager()->SetFocusedView(moving_item); + + // Make one move right and expect a histogram is recorded. + SimulateKeyPress(ui::VKEY_RIGHT, ui::EF_CONTROL_DOWN); + SimulateKeyReleased(ui::VKEY_RIGHT, ui::EF_NONE); + + histogram_tester.ExpectBucketCount("Apps.AppListAppMovingType", 6, 1); + + // Make one move down and expect a histogram is recorded. + SimulateKeyPress(ui::VKEY_DOWN, ui::EF_CONTROL_DOWN); + SimulateKeyReleased(ui::VKEY_DOWN, ui::EF_NONE); + + histogram_tester.ExpectBucketCount("Apps.AppListAppMovingType", 6, 2); + + // Make one move up and expect a histogram is recorded. + SimulateKeyPress(ui::VKEY_UP, ui::EF_CONTROL_DOWN); + SimulateKeyReleased(ui::VKEY_UP, ui::EF_NONE); + + histogram_tester.ExpectBucketCount("Apps.AppListAppMovingType", 6, 3); + + // Make one move left and expect a histogram is recorded. + SimulateKeyPress(ui::VKEY_LEFT, ui::EF_CONTROL_DOWN); + SimulateKeyReleased(ui::VKEY_LEFT, ui::EF_NONE); + + histogram_tester.ExpectBucketCount("Apps.AppListAppMovingType", 6, 4); +} + +// Test that histograms do not record when the keyboard move is a no-op. +TEST_F(AppsGridViewTest, ControlArrowDoesNotRecordHistogramWithNoOpMove) { + base::HistogramTester histogram_tester; + model_->PopulateApps(GetTilesPerPage(0)); + + AppListItemView* moving_item = GetItemViewAt(0); + apps_grid_view_->GetFocusManager()->SetFocusedView(moving_item); + + // Make 2 no-op moves and one successful move from 0,0 ane expect a histogram + // is recorded only once. + SimulateKeyPress(ui::VKEY_LEFT, ui::EF_CONTROL_DOWN); + SimulateKeyReleased(ui::VKEY_LEFT, ui::EF_NONE); + + SimulateKeyPress(ui::VKEY_UP, ui::EF_CONTROL_DOWN); + SimulateKeyReleased(ui::VKEY_UP, ui::EF_NONE); + + SimulateKeyPress(ui::VKEY_RIGHT, ui::EF_CONTROL_DOWN); + SimulateKeyReleased(ui::VKEY_RIGHT, ui::EF_NONE); + + histogram_tester.ExpectBucketCount("Apps.AppListAppMovingType", 6, 1); +} + +// Tests that histograms only record once for a long move sequence. +TEST_F(AppsGridViewTest, ControlArrowRecordsHistogramOnceWithOneMoveSequence) { + base::HistogramTester histogram_tester; + model_->PopulateApps(GetTilesPerPage(1) * 2); + + AppListItemView* moving_item = GetItemViewAt(0); + apps_grid_view_->GetFocusManager()->SetFocusedView(moving_item); + + // Make that a series of moves when the control key is left pressed and expect + // one histogram is recorded. + while (GetPaginationModel()->selected_page() != 1) { + SimulateKeyPress(ui::VKEY_DOWN, ui::EF_CONTROL_DOWN); + SimulateKeyReleased(ui::VKEY_DOWN, ui::EF_CONTROL_DOWN); + } + SimulateKeyReleased(ui::VKEY_DOWN, ui::EF_NONE); + + histogram_tester.ExpectBucketCount("Apps.AppListAppMovingType", 6, 1); +} + +// Tests that moving an app down when it is directly below a gap results in a +// swap with the closest item. +TEST_F(AppsGridViewTest, ControlArrowDownToGapOnSamePage) { + // Add two rows of apps, one full and one with just one app. + model_->PopulateApps(apps_grid_view_->cols() + 1); + + // Select the far right item. + AppListItemView* moving_item = GetItemViewAt(apps_grid_view_->cols() - 1); + AppListItemView* swapped_item = GetItemViewAt(apps_grid_view_->cols()); + apps_grid_view_->GetFocusManager()->SetFocusedView(moving_item); + + // Press down to move the app to the next row. It should take the place of the + // app on the next row that is closes to the column of |moving_item|. + SimulateKeyPress(ui::VKEY_DOWN, ui::EF_CONTROL_DOWN); + + EXPECT_EQ(moving_item, GetItemViewAt(apps_grid_view_->cols())); + EXPECT_EQ(swapped_item, GetItemViewAt(apps_grid_view_->cols() - 1)); +} + +// Tests that moving an app up/down/left/right to a full page results in the app +// at the destination slot moving to the source slot (ie. a swap). +TEST_F(AppsGridViewTest, ControlArrowSwapsBetweenFullPages) { + const int kPages = 3; + model_->PopulateApps(kPages * GetTilesPerPage(0)); + // For every item in the first row, ensure an upward move results in the item + // swapping places with the item directly above it. + for (int i = 0; i < apps_grid_view_->cols(); ++i) { + GetPaginationModel()->SelectPage(1, false /*animate*/); + const GridIndex moved_view_index(1, i); + apps_grid_view_->GetFocusManager()->SetFocusedView( + test_api_->GetViewAtIndex(moved_view_index)); + + const GridIndex swapped_view_index( + 0, + apps_grid_view_->cols() * (apps_grid_view_->rows_per_page() - 1) + i); + AppListItemView* moved_view = test_api_->GetViewAtIndex(moved_view_index); + AppListItemView* swapped_view = + test_api_->GetViewAtIndex(swapped_view_index); + + SimulateKeyPress(ui::VKEY_UP, ui::EF_CONTROL_DOWN); + + // |swapped_view| and |moved_view| should swap places when moving up to a + // full page. + EXPECT_EQ(swapped_view, test_api_->GetViewAtIndex(moved_view_index)); + EXPECT_EQ(moved_view, test_api_->GetViewAtIndex(swapped_view_index)); + EXPECT_EQ(0, GetPaginationModel()->selected_page()); + } + + // For every item in the last row of a full page, ensure a downward move + // results in the item swapping places when the target position is occupied. + for (int i = 0; i < apps_grid_view_->cols(); ++i) { + GetPaginationModel()->SelectPage(1, false /*animate*/); + const GridIndex moved_view_index( + 0, + apps_grid_view_->cols() * (apps_grid_view_->rows_per_page() - 1) + i); + apps_grid_view_->GetFocusManager()->SetFocusedView( + test_api_->GetViewAtIndex(moved_view_index)); + + const GridIndex swapped_view_index(1, i); + AppListItemView* moved_view = test_api_->GetViewAtIndex(moved_view_index); + AppListItemView* swapped_view = + test_api_->GetViewAtIndex(swapped_view_index); + + SimulateKeyPress(ui::VKEY_DOWN, ui::EF_CONTROL_DOWN); + + // |swapped_view| and |moved_view| should swap places when moving up to a + // full page. + EXPECT_EQ(swapped_view, test_api_->GetViewAtIndex(moved_view_index)); + EXPECT_EQ(moved_view, test_api_->GetViewAtIndex(swapped_view_index)); + EXPECT_EQ(1, GetPaginationModel()->selected_page()); + } + + // For the final item on the first page, moving right to a full page should + // swap with the first item on the next page. + GetPaginationModel()->SelectPage(0, false /*animate*/); + GridIndex moved_view_index( + 0, apps_grid_view_->cols() * apps_grid_view_->rows_per_page() - 1); + GridIndex swapped_view_index(1, 0); + AppListItemView* moved_view = test_api_->GetViewAtIndex(moved_view_index); + AppListItemView* swapped_view = test_api_->GetViewAtIndex(swapped_view_index); + apps_grid_view_->GetFocusManager()->SetFocusedView( + test_api_->GetViewAtIndex(moved_view_index)); + + SimulateKeyPress(ui::VKEY_RIGHT, ui::EF_CONTROL_DOWN); + + EXPECT_EQ(swapped_view, test_api_->GetViewAtIndex(moved_view_index)); + EXPECT_EQ(moved_view, test_api_->GetViewAtIndex(swapped_view_index)); + EXPECT_EQ(1, GetPaginationModel()->selected_page()); + + // For the first item on the second page, moving left to a full page should + // swap with the first item on the previous page. + swapped_view_index = moved_view_index; + moved_view_index = GridIndex(1, 0); + moved_view = test_api_->GetViewAtIndex(moved_view_index); + swapped_view = test_api_->GetViewAtIndex(swapped_view_index); + + SimulateKeyPress(ui::VKEY_LEFT, ui::EF_CONTROL_DOWN); + + EXPECT_EQ(swapped_view, test_api_->GetViewAtIndex(moved_view_index)); + EXPECT_EQ(moved_view, test_api_->GetViewAtIndex(swapped_view_index)); + EXPECT_EQ(0, GetPaginationModel()->selected_page()); +} + +// Test that a page can be created while moving apps with the control+arrow. +TEST_F(AppsGridViewTest, ControlArrowDownAndRightCreatesNewPage) { + base::HistogramTester histogram_tester; + const int kTilesPerPageStart = GetTilesPerPage(0); + model_->PopulateApps(kTilesPerPageStart); + + // Focus the last item on the page. + AppListItemView* moving_item = GetItemViewAt(kTilesPerPageStart - 1); + apps_grid_view_->GetFocusManager()->SetFocusedView(moving_item); + + // Test that pressing control-right creates a new page. + SimulateKeyPress(ui::VKEY_RIGHT, ui::EF_CONTROL_DOWN); + + histogram_tester.ExpectBucketCount("Apps.AppListPageSwitcherSource", 7, 1); + EXPECT_EQ(moving_item, test_api_->GetViewAtIndex(GridIndex(1, 0))); + EXPECT_EQ(kTilesPerPageStart - 1, test_api_->AppsOnPage(0)); + EXPECT_EQ(1, GetPaginationModel()->selected_page()); + EXPECT_EQ(2, GetPaginationModel()->total_pages()); + + // Reset by moving the app back to the previous page. + SimulateKeyPress(ui::VKEY_UP, ui::EF_CONTROL_DOWN); + + histogram_tester.ExpectBucketCount("Apps.AppListPageSwitcherSource", 7, 2); + + // Test that control-down creates a new page. + SimulateKeyPress(ui::VKEY_DOWN, ui::EF_CONTROL_DOWN); + + // The slot where |moving_item| originated should be empty because items get + // dumped on pages with room, and only swap if the destination page is full. + EXPECT_EQ( + nullptr, + test_api_->GetViewAtIndex(GridIndex( + 0, apps_grid_view_->cols() * apps_grid_view_->rows_per_page() - 1))); + EXPECT_EQ(moving_item, test_api_->GetViewAtIndex(GridIndex(1, 0))); + EXPECT_EQ(kTilesPerPageStart - 1, test_api_->AppsOnPage(0)); + EXPECT_EQ(1, test_api_->AppsOnPage(1)); + EXPECT_EQ(1, GetPaginationModel()->selected_page()); + EXPECT_EQ(2, GetPaginationModel()->total_pages()); + histogram_tester.ExpectBucketCount("Apps.AppListPageSwitcherSource", 7, 3); +} + +// Tests that a page can be deleted if a lonely app is moved down or right to +// another page. +TEST_F(AppsGridViewTest, ControlArrowUpOrLeftRemovesPage) { + base::HistogramTester histogram_tester; + // Move an app so it is by itself on page 1. + model_->PopulateApps(GetTilesPerPage(0)); + AppListItemView* moving_item = GetItemViewAt(GetTilesPerPage(0) - 1); + apps_grid_view_->GetFocusManager()->SetFocusedView(moving_item); + SimulateKeyPress(ui::VKEY_DOWN, ui::EF_CONTROL_DOWN); + histogram_tester.ExpectBucketCount("Apps.AppListPageSwitcherSource", 7, 1); + EXPECT_EQ(1, GetPaginationModel()->selected_page()); + EXPECT_EQ(2, GetPaginationModel()->total_pages()); + + // Move the app up, test that the page is deleted. + SimulateKeyPress(ui::VKEY_UP, ui::EF_CONTROL_DOWN); + + histogram_tester.ExpectBucketCount("Apps.AppListPageSwitcherSource", 7, 2); + EXPECT_EQ(0, GetPaginationModel()->selected_page()); + EXPECT_EQ(1, GetPaginationModel()->total_pages()); + + // Move the app to be by itself again on page 1. + SimulateKeyPress(ui::VKEY_DOWN, ui::EF_CONTROL_DOWN); + histogram_tester.ExpectBucketCount("Apps.AppListPageSwitcherSource", 7, 3); + EXPECT_EQ(1, GetPaginationModel()->selected_page()); + EXPECT_EQ(2, GetPaginationModel()->total_pages()); + + // Move the app left, test that the page is deleted. + SimulateKeyPress(ui::VKEY_LEFT, ui::EF_CONTROL_DOWN); + + histogram_tester.ExpectBucketCount("Apps.AppListPageSwitcherSource", 7, 4); + EXPECT_EQ(0, GetPaginationModel()->selected_page()); + EXPECT_EQ(1, GetPaginationModel()->total_pages()); +} + +// Tests that moving a lonely app on the last page down is a no-op when there +// are no pages below. +TEST_F(AppsGridViewTest, ControlArrowDownOnLastAppOnLastPage) { + base::HistogramTester histogram_tester; + // Move an app so it is by itself on page 1. + model_->PopulateApps(GetTilesPerPage(0)); + AppListItemView* moving_item = GetItemViewAt(GetTilesPerPage(0) - 1); + apps_grid_view_->GetFocusManager()->SetFocusedView(moving_item); + SimulateKeyPress(ui::VKEY_DOWN, ui::EF_CONTROL_DOWN); + SimulateKeyReleased(ui::VKEY_DOWN, ui::EF_NONE); + histogram_tester.ExpectBucketCount("Apps.AppListPageSwitcherSource", 7, 1); + histogram_tester.ExpectBucketCount("Apps.AppListAppMovingType", 6, 1); + EXPECT_EQ(1, GetPaginationModel()->selected_page()); + EXPECT_EQ(2, GetPaginationModel()->total_pages()); + + // Move the app right, test that nothing changes and no histograms are + // recorded. + SimulateKeyPress(ui::VKEY_RIGHT, ui::EF_CONTROL_DOWN); + SimulateKeyReleased(ui::VKEY_RIGHT, ui::EF_NONE); + + histogram_tester.ExpectBucketCount("Apps.AppListPageSwitcherSource", 7, 1); + histogram_tester.ExpectBucketCount("Apps.AppListAppMovingType", 6, 1); + EXPECT_EQ(1, GetPaginationModel()->selected_page()); + EXPECT_EQ(2, GetPaginationModel()->total_pages()); + + // Move the app down, test that nothing changes and no histograms are + // recorded. + SimulateKeyPress(ui::VKEY_DOWN, ui::EF_CONTROL_DOWN); + SimulateKeyReleased(ui::VKEY_DOWN, ui::EF_NONE); + + histogram_tester.ExpectBucketCount("Apps.AppListPageSwitcherSource", 7, 1); + histogram_tester.ExpectBucketCount("Apps.AppListAppMovingType", 6, 1); + EXPECT_EQ(1, GetPaginationModel()->selected_page()); + EXPECT_EQ(2, GetPaginationModel()->total_pages()); +} + +// Test that moving an item down or right when it is by itself on a page with a +// page below results in the page deletion. +TEST_F(AppsGridViewTest, ControlArrowDownOrRightRemovesPage) { + // Move an app so it is by itself on page 1, with another app on page 2. + model_->PopulateApps(GetTilesPerPage(0)); + AppListItemView* moving_item = GetItemViewAt(GetTilesPerPage(0) - 1); + apps_grid_view_->GetFocusManager()->SetFocusedView(moving_item); + SimulateKeyPress(ui::VKEY_DOWN, ui::EF_CONTROL_DOWN); + SimulateKeyPress(ui::VKEY_UP); + SimulateKeyPress(ui::VKEY_DOWN, ui::EF_CONTROL_DOWN); + SimulateKeyPress(ui::VKEY_DOWN, ui::EF_CONTROL_DOWN); + SimulateKeyPress(ui::VKEY_UP); + // The lonely app is selected on page 1, with a page below it containing one + // app. + EXPECT_EQ(1, GetPaginationModel()->selected_page()); + EXPECT_EQ(3, GetPaginationModel()->total_pages()); + + // Test that moving the app on page 1 down, deletes the second page and + // creates a final page with 2 apps. + SimulateKeyPress(ui::VKEY_DOWN, ui::EF_CONTROL_DOWN); + + EXPECT_EQ(1, GetPaginationModel()->selected_page()); + EXPECT_EQ(2, GetPaginationModel()->total_pages()); + EXPECT_EQ(2, test_api_->AppsOnPage(1)); + + // Create a third page, with an app by itself. + SimulateKeyPress(ui::VKEY_DOWN, ui::EF_CONTROL_DOWN); + SimulateKeyPress(ui::VKEY_UP); + EXPECT_EQ(1, GetPaginationModel()->selected_page()); + EXPECT_EQ(3, GetPaginationModel()->total_pages()); + + // Test that moving the app right moves the selected app to the third page, + // and the second page is deleted. + SimulateKeyPress(ui::VKEY_RIGHT, ui::EF_CONTROL_DOWN); + + EXPECT_EQ(1, GetPaginationModel()->selected_page()); + EXPECT_EQ(2, GetPaginationModel()->total_pages()); + EXPECT_EQ(2, test_api_->AppsOnPage(1)); +} + TEST_P(AppsGridViewTest, MouseDragFlipPage) { apps_grid_view_->set_page_flip_delay_in_ms_for_testing(10); GetPaginationModel()->SetTransitionDurations(10, 10);
diff --git a/ash/app_list/views/search_result_answer_card_view.cc b/ash/app_list/views/search_result_answer_card_view.cc index 918b1a7f..0930eac 100644 --- a/ash/app_list/views/search_result_answer_card_view.cc +++ b/ash/app_list/views/search_result_answer_card_view.cc
@@ -261,7 +261,7 @@ OnVisibilityChanged(true /* is_visible */); views::View* content_view = contents_->GetView()->view(); - if (!has_children()) { + if (children().empty()) { AddChildView(content_view); ExcludeCardFromEventHandling(contents_->GetView()->native_view());
diff --git a/ash/app_list/views/search_result_list_view.cc b/ash/app_list/views/search_result_list_view.cc index 8bb7aef..03e458f 100644 --- a/ash/app_list/views/search_result_list_view.cc +++ b/ash/app_list/views/search_result_list_view.cc
@@ -157,7 +157,7 @@ } SearchResultBaseView* SearchResultListView::GetFirstResultView() { - DCHECK(results_container_->has_children()); + DCHECK(!results_container_->children().empty()); return num_results() <= 0 ? nullptr : search_result_views_[0]; }
diff --git a/ash/app_list/views/search_result_view.cc b/ash/app_list/views/search_result_view.cc index 72e9243..0f46a138 100644 --- a/ash/app_list/views/search_result_view.cc +++ b/ash/app_list/views/search_result_view.cc
@@ -271,7 +271,7 @@ } case ui::VKEY_UP: case ui::VKEY_DOWN: { - if (actions_view_->has_children()) { + if (!actions_view_->children().empty()) { return list_view_->HandleVerticalFocusMovement( this, event.key_code() == ui::VKEY_UP); } @@ -300,7 +300,7 @@ text_bounds.set_width( rect.width() - kPreferredIconViewWidth - kTextTrailPadding - actions_view_->bounds().width() - - (actions_view_->has_children() ? kActionButtonRightMargin : 0)); + (actions_view_->children().empty() ? 0 : kActionButtonRightMargin)); } else { text_bounds.set_width(rect.width() - kPreferredIconViewWidth - kTextTrailPadding - progress_bar_->bounds().width() -
diff --git a/ash/app_list/views/test/apps_grid_view_test_api.cc b/ash/app_list/views/test/apps_grid_view_test_api.cc index f614516..97e8d8b 100644 --- a/ash/app_list/views/test/apps_grid_view_test_api.cc +++ b/ash/app_list/views/test/apps_grid_view_test_api.cc
@@ -57,6 +57,14 @@ return view_->TilesPerPage(page); } +int AppsGridViewTestApi::AppsOnPage(int page) const { + return view_->view_structure_.items_on_page(page); +} + +AppListItemView* AppsGridViewTestApi::GetViewAtIndex(GridIndex index) const { + return view_->GetViewAtIndex(index); +} + views::View* AppsGridViewTestApi::GetViewAtVisualIndex(int page, int slot) const { const std::vector<std::vector<AppListItemView*>>& view_structure =
diff --git a/ash/app_list/views/test/apps_grid_view_test_api.h b/ash/app_list/views/test/apps_grid_view_test_api.h index 0013231..ab3edb451 100644 --- a/ash/app_list/views/test/apps_grid_view_test_api.h +++ b/ash/app_list/views/test/apps_grid_view_test_api.h
@@ -5,6 +5,7 @@ #ifndef ASH_APP_LIST_VIEWS_TEST_APPS_GRID_VIEW_TEST_API_H_ #define ASH_APP_LIST_VIEWS_TEST_APPS_GRID_VIEW_TEST_API_H_ +#include "ash/app_list/views/apps_grid_view.h" #include "base/macros.h" namespace gfx { @@ -17,6 +18,7 @@ namespace app_list { +class AppListItemView; class AppsGridView; namespace test { @@ -38,6 +40,10 @@ int TilesPerPage(int page) const; + int AppsOnPage(int page) const; + + AppListItemView* GetViewAtIndex(GridIndex index) const; + views::View* GetViewAtVisualIndex(int page, int slot) const; gfx::Rect GetItemTileRectAtVisualIndex(int page, int slot) const;
diff --git a/ash/ash_service.cc b/ash/ash_service.cc index 89bcc69..32804a1 100644 --- a/ash/ash_service.cc +++ b/ash/ash_service.cc
@@ -163,14 +163,13 @@ // TODO(jamescook): Initialize real audio handler. chromeos::CrasAudioHandler::InitializeForTesting(); - // TODO(estade/stevenjb): Modify PowerManagerClient to use InitializeFake. - chromeos::PowerManagerClient::Initialize(bus); - if (bus) { chromeos::HammerdClient::Initialize(bus); + chromeos::PowerManagerClient::Initialize(bus); chromeos::SystemClockClient::Initialize(bus); } else { chromeos::HammerdClient::InitializeFake(); + chromeos::PowerManagerClient::InitializeFake(); chromeos::SystemClockClient::InitializeFake(); }
diff --git a/ash/assistant/ui/main_stage/ui_element_container_view.cc b/ash/assistant/ui/main_stage/ui_element_container_view.cc index 7aeab3cb..8e5e3e6 100644 --- a/ash/assistant/ui/main_stage/ui_element_container_view.cc +++ b/ash/assistant/ui/main_stage/ui_element_container_view.cc
@@ -165,7 +165,7 @@ // If we don't have any pre-existing content, there is nothing to animate off // stage so we we can proceed to add the new response. - if (!content_view()->has_children()) { + if (content_view()->children().empty()) { OnResponseAdded(std::move(pending_response_)); return; }
diff --git a/ash/components/shortcut_viewer/views/keyboard_shortcut_item_view.cc b/ash/components/shortcut_viewer/views/keyboard_shortcut_item_view.cc index 60acedd..b77fba20 100644 --- a/ash/components/shortcut_viewer/views/keyboard_shortcut_item_view.cc +++ b/ash/components/shortcut_viewer/views/keyboard_shortcut_item_view.cc
@@ -195,7 +195,7 @@ // |description_label_view_|. shortcut_label_view_->SetBounds(0, 0, shortcut_view_preferred_width, shortcut_view_height); - DCHECK(shortcut_label_view_->has_children()); + DCHECK(!shortcut_label_view_->children().empty()); // Labels in |shortcut_label_view_| are right aligned, so we need to find the // minimum left coordinates of all the lables. int min_left = shortcut_view_preferred_width; @@ -225,8 +225,8 @@ // We want the center of the top lines in both views to align with each other. description_label_view_->SetBounds(0, 0, description_view_preferred_width, description_view_height); - DCHECK(shortcut_label_view_->has_children() && - description_label_view_->has_children()); + DCHECK(!shortcut_label_view_->children().empty() && + !description_label_view_->children().empty()); const int description_view_top_line_center_offset_y = description_label_view_->child_at(0)->bounds().CenterPoint().y(); const int shortcut_view_top_line_center_offset_y =
diff --git a/ash/components/shortcut_viewer/views/keyboard_shortcut_view.cc b/ash/components/shortcut_viewer/views/keyboard_shortcut_view.cc index 18db3abd..93d7b56 100644 --- a/ash/components/shortcut_viewer/views/keyboard_shortcut_view.cc +++ b/ash/components/shortcut_viewer/views/keyboard_shortcut_view.cc
@@ -380,7 +380,7 @@ continue; // Add the item to the category contents container. - if (item_list_view->has_children()) + if (!item_list_view->children().empty()) item_list_view->AddHorizontalSeparator(); views::StyledLabel* description_label_view = item_view->description_label_view(); @@ -476,7 +476,7 @@ } std::vector<base::string16> replacement_strings; - if (found_items_list_view->has_children()) { + if (!found_items_list_view->children().empty()) { replacement_strings.emplace_back( base::NumberToString16(number_search_results));
diff --git a/ash/detachable_base/detachable_base_handler_unittest.cc b/ash/detachable_base/detachable_base_handler_unittest.cc index 1edee9a..3a53ee4 100644 --- a/ash/detachable_base/detachable_base_handler_unittest.cc +++ b/ash/detachable_base/detachable_base_handler_unittest.cc
@@ -88,7 +88,7 @@ chromeos::HammerdClient::InitializeFake(); hammerd_client_ = chromeos::FakeHammerdClient::Get(); - chromeos::PowerManagerClient::Initialize(); + chromeos::PowerManagerClient::InitializeFake(); chromeos::FakePowerManagerClient::Get()->SetTabletMode( chromeos::PowerManagerClient::TabletMode::OFF, base::TimeTicks());
diff --git a/ash/display/projecting_observer_unittest.cc b/ash/display/projecting_observer_unittest.cc index 543f4ff..f5cbe79 100644 --- a/ash/display/projecting_observer_unittest.cc +++ b/ash/display/projecting_observer_unittest.cc
@@ -46,7 +46,7 @@ ProjectingObserverTest() = default; void SetUp() override { - chromeos::PowerManagerClient::Initialize(); + chromeos::PowerManagerClient::InitializeFake(); observer_ = std::make_unique<ProjectingObserver>(nullptr); }
diff --git a/ash/login/ui/login_test_utils.cc b/ash/login/ui/login_test_utils.cc index fe4eb85..08dbdd1 100644 --- a/ash/login/ui/login_test_utils.cc +++ b/ash/login/ui/login_test_utils.cc
@@ -123,7 +123,7 @@ views::View* child = current_view->child_at(i); if (views::Button::AsButton(child)) return child; - if (child->has_children()) { + if (!child->children().empty()) { views::View* child_button = FindTopButton(child); if (child_button) return child_button;
diff --git a/ash/media/media_notification_item.cc b/ash/media/media_notification_item.cc index 4bf9fbaf..ecc8736 100644 --- a/ash/media/media_notification_item.cc +++ b/ash/media/media_notification_item.cc
@@ -15,6 +15,7 @@ #include "services/media_session/public/mojom/media_session.mojom.h" #include "ui/gfx/image/image.h" #include "ui/message_center/message_center.h" +#include "ui/message_center/public/cpp/message_center_constants.h" #include "ui/message_center/public/cpp/notification.h" #include "ui/message_center/public/cpp/notification_delegate.h" #include "ui/message_center/public/cpp/notifier_id.h" @@ -53,6 +54,13 @@ kMediaSessionNotificationArtworkMinSize, kMediaSessionNotificationArtworkDesiredSize, std::move(artwork_observer)); + + media_session::mojom::MediaControllerImageObserverPtr icon_observer; + icon_observer_binding_.Bind(mojo::MakeRequest(&icon_observer)); + media_controller_ptr_->ObserveImages( + media_session::mojom::MediaSessionImageType::kSourceIcon, + message_center::kSmallImageSizeMD, message_center::kSmallImageSizeMD, + std::move(icon_observer)); } MaybeHideOrShowNotification(); @@ -92,12 +100,20 @@ void MediaNotificationItem::MediaControllerImageChanged( media_session::mojom::MediaSessionImageType type, const SkBitmap& bitmap) { - DCHECK_EQ(media_session::mojom::MediaSessionImageType::kArtwork, type); + switch (type) { + case media_session::mojom::MediaSessionImageType::kArtwork: + session_artwork_ = gfx::ImageSkia::CreateFrom1xBitmap(bitmap); - session_artwork_ = gfx::ImageSkia::CreateFrom1xBitmap(bitmap); + if (view_) + view_->UpdateWithMediaArtwork(session_artwork_); + break; + case media_session::mojom::MediaSessionImageType::kSourceIcon: + session_icon_ = gfx::ImageSkia::CreateFrom1xBitmap(bitmap); - if (view_) - view_->UpdateWithMediaArtwork(session_artwork_); + if (view_) + view_->UpdateWithMediaIcon(session_icon_); + break; + } } void MediaNotificationItem::SetView(MediaNotificationView* view) {
diff --git a/ash/media/media_notification_item.h b/ash/media/media_notification_item.h index d6080d1..468cccbe 100644 --- a/ash/media/media_notification_item.h +++ b/ash/media/media_notification_item.h
@@ -81,12 +81,17 @@ gfx::ImageSkia session_artwork_; + gfx::ImageSkia session_icon_; + mojo::Binding<media_session::mojom::MediaControllerObserver> observer_binding_{this}; mojo::Binding<media_session::mojom::MediaControllerImageObserver> artwork_observer_binding_{this}; + mojo::Binding<media_session::mojom::MediaControllerImageObserver> + icon_observer_binding_{this}; + base::WeakPtrFactory<MediaNotificationItem> weak_ptr_factory_{this}; DISALLOW_COPY_AND_ASSIGN(MediaNotificationItem);
diff --git a/ash/media/media_notification_view.cc b/ash/media/media_notification_view.cc index a944df9..c966ebe9 100644 --- a/ash/media/media_notification_view.cc +++ b/ash/media/media_notification_view.cc
@@ -71,6 +71,7 @@ header_row_->SetExpandButtonEnabled(true); header_row_->SetAppName( message_center::MessageCenter::Get()->GetSystemNotificationAppName()); + header_row_->ClearAppIcon(); AddChildView(header_row_); // |main_row_| holds the main content of the notification. @@ -277,6 +278,14 @@ GetMediaNotificationBackground()->UpdateArtwork(image); } +void MediaNotificationView::UpdateWithMediaIcon(const gfx::ImageSkia& image) { + if (image.isNull()) { + header_row_->ClearAppIcon(); + } else { + header_row_->SetAppIcon(image); + } +} + void MediaNotificationView::UpdateControlButtonsVisibilityWithNotification( const message_center::Notification& notification) { // Media notifications do not use the settings and snooze buttons.
diff --git a/ash/media/media_notification_view.h b/ash/media/media_notification_view.h index ea3b9a6..f556312 100644 --- a/ash/media/media_notification_view.h +++ b/ash/media/media_notification_view.h
@@ -68,6 +68,7 @@ void UpdateWithMediaActions( const std::set<media_session::mojom::MediaSessionAction>& actions); void UpdateWithMediaArtwork(const gfx::ImageSkia& image); + void UpdateWithMediaIcon(const gfx::ImageSkia& image); private: friend class MediaNotificationViewTest;
diff --git a/ash/media/media_notification_view_unittest.cc b/ash/media/media_notification_view_unittest.cc index dba22a10..39551dc 100644 --- a/ash/media/media_notification_view_unittest.cc +++ b/ash/media/media_notification_view_unittest.cc
@@ -28,6 +28,7 @@ #include "ui/events/base_event_utils.h" #include "ui/events/test/event_generator.h" #include "ui/message_center/message_center.h" +#include "ui/message_center/public/cpp/message_center_constants.h" #include "ui/message_center/views/message_view_factory.h" #include "ui/message_center/views/notification_control_buttons_view.h" #include "ui/message_center/views/notification_header_view.h" @@ -222,6 +223,10 @@ return view_->GetMediaNotificationBackground()->artwork_; } + const gfx::ImageSkia& GetAppIcon() const { + return view_->header_row_->app_icon_for_testing(); + } + private: std::unique_ptr<message_center::MessageView> CreateAndCaptureCustomView( const message_center::Notification& notification) { @@ -694,4 +699,28 @@ EXPECT_EQ(size, view()->size()); } +TEST_F(MediaNotificationViewTest, UpdateIconFromItem) { + gfx::ImageSkia original = GetAppIcon(); + EXPECT_EQ(message_center::kSmallImageSizeMD, original.width()); + EXPECT_EQ(message_center::kSmallImageSizeMD, original.height()); + + // The size for the image we provide should be different so we can compare. + const int alt_size = message_center::kSmallImageSizeMD + 1; + + SkBitmap bitmap; + bitmap.allocN32Pixels(alt_size, alt_size); + + GetItem()->MediaControllerImageChanged( + media_session::mojom::MediaSessionImageType::kSourceIcon, bitmap); + + EXPECT_EQ(alt_size, GetAppIcon().width()); + EXPECT_EQ(alt_size, GetAppIcon().height()); + + GetItem()->MediaControllerImageChanged( + media_session::mojom::MediaSessionImageType::kSourceIcon, SkBitmap()); + + EXPECT_EQ(message_center::kSmallImageSizeMD, GetAppIcon().width()); + EXPECT_EQ(message_center::kSmallImageSizeMD, GetAppIcon().height()); +} + } // namespace ash
diff --git a/ash/shelf/back_button.cc b/ash/shelf/back_button.cc index 4c1ba90..a36bcc6 100644 --- a/ash/shelf/back_button.cc +++ b/ash/shelf/back_button.cc
@@ -38,21 +38,13 @@ void BackButton::OnGestureEvent(ui::GestureEvent* event) { ShelfButton::OnGestureEvent(event); - if (event->type() == ui::ET_GESTURE_TAP || - event->type() == ui::ET_GESTURE_TAP_DOWN) { - GenerateAndSendBackEvent(event->type()); - } -} - -bool BackButton::OnMousePressed(const ui::MouseEvent& event) { - ShelfButton::OnMousePressed(event); - GenerateAndSendBackEvent(event.type()); - return true; + if (event->type() == ui::ET_GESTURE_TAP) + GenerateAndSendBackEvent(); } void BackButton::OnMouseReleased(const ui::MouseEvent& event) { ShelfButton::OnMouseReleased(event); - GenerateAndSendBackEvent(event.type()); + GenerateAndSendBackEvent(); } void BackButton::PaintButtonContents(gfx::Canvas* canvas) { @@ -67,28 +59,15 @@ return kViewClassName; } -void BackButton::GenerateAndSendBackEvent( - const ui::EventType& original_event_type) { - ui::EventType new_event_type; - switch (original_event_type) { - case ui::ET_MOUSE_PRESSED: - case ui::ET_GESTURE_TAP_DOWN: - new_event_type = ui::ET_KEY_PRESSED; - break; - case ui::ET_MOUSE_RELEASED: - case ui::ET_GESTURE_TAP: - new_event_type = ui::ET_KEY_RELEASED; - base::RecordAction(base::UserMetricsAction("Tablet_BackButton")); - break; - default: - return; - } +void BackButton::GenerateAndSendBackEvent() { + base::RecordAction(base::UserMetricsAction("Tablet_BackButton")); // Send the back event to the root window of the back button's widget. const views::Widget* widget = GetWidget(); if (widget && widget->GetNativeWindow()) { aura::Window* root_window = widget->GetNativeWindow()->GetRootWindow(); - ui::KeyEvent key_event(new_event_type, ui::VKEY_BROWSER_BACK, ui::EF_NONE); + ui::KeyEvent key_event(ui::ET_KEY_PRESSED, ui::VKEY_BROWSER_BACK, + ui::EF_NONE); ignore_result( root_window->GetHost()->event_sink()->OnEventFromSource(&key_event)); }
diff --git a/ash/shelf/back_button.h b/ash/shelf/back_button.h index 272426f..7a8119a1 100644 --- a/ash/shelf/back_button.h +++ b/ash/shelf/back_button.h
@@ -26,15 +26,16 @@ protected: // views::Button: void OnGestureEvent(ui::GestureEvent* event) override; - bool OnMousePressed(const ui::MouseEvent& event) override; void OnMouseReleased(const ui::MouseEvent& event) override; void PaintButtonContents(gfx::Canvas* canvas) override; const char* GetClassName() const override; private: - // Generate and send a VKEY_BROWSER_BACK key event when the back button - // is pressed. - void GenerateAndSendBackEvent(const ui::EventType& original_event_type); + // Generate and send a VKEY_BROWSER_BACK key event sequence when the back + // button is pressed. This should on be called on a tap down or mouse release + // event, and will only send a key down event since that is the one which + // triggers the back event. + void GenerateAndSendBackEvent(); DISALLOW_COPY_AND_ASSIGN(BackButton); };
diff --git a/ash/shelf/back_button_unittest.cc b/ash/shelf/back_button_unittest.cc index 0359c32..d50767a0 100644 --- a/ash/shelf/back_button_unittest.cc +++ b/ash/shelf/back_button_unittest.cc
@@ -107,13 +107,17 @@ ui::TestAcceleratorTarget target_back_release; controller->Register({accelerator_back_release}, &target_back_release); - // Verify that by clicking the back button, a back key sequence will be - // generated. + // Verify that by pressing the back button no event is generated on the press, + // but there is one generated on the release. ui::test::EventGenerator* generator = GetEventGenerator(); generator->MoveMouseTo(back_button()->GetBoundsInScreen().CenterPoint()); - generator->ClickLeftButton(); + generator->PressLeftButton(); + EXPECT_EQ(0, target_back_press.accelerator_count()); + EXPECT_EQ(0, target_back_release.accelerator_count()); + + generator->ReleaseLeftButton(); EXPECT_EQ(1, target_back_press.accelerator_count()); - EXPECT_EQ(1, target_back_release.accelerator_count()); + EXPECT_EQ(0, target_back_release.accelerator_count()); } } // namespace ash
diff --git a/ash/system/message_center/arc/arc_notification_delegate.cc b/ash/system/message_center/arc/arc_notification_delegate.cc index b501543..94a33d7 100644 --- a/ash/system/message_center/arc/arc_notification_delegate.cc +++ b/ash/system/message_center/arc/arc_notification_delegate.cc
@@ -23,7 +23,7 @@ std::unique_ptr<message_center::MessageView> ArcNotificationDelegate::CreateCustomMessageView( const message_center::Notification& notification) { - DCHECK(item_); + CHECK(item_); DCHECK_EQ(item_->GetNotificationId(), notification.id()); return std::make_unique<ArcNotificationView>(item_.get(), notification); }
diff --git a/ash/system/power/power_status_unittest.cc b/ash/system/power/power_status_unittest.cc index f6cde88..02a67a9 100644 --- a/ash/system/power/power_status_unittest.cc +++ b/ash/system/power/power_status_unittest.cc
@@ -47,7 +47,7 @@ ~PowerStatusTest() override = default; void SetUp() override { - chromeos::PowerManagerClient::Initialize(); + chromeos::PowerManagerClient::InitializeFake(); PowerStatus::Initialize(); power_status_ = PowerStatus::Get(); test_observer_.reset(new TestObserver);
diff --git a/ash/test/ash_test_helper.cc b/ash/test/ash_test_helper.cc index c9fd4506e..47b8f49 100644 --- a/ash/test/ash_test_helper.cc +++ b/ash/test/ash_test_helper.cc
@@ -170,7 +170,7 @@ bluez_dbus_manager_initialized_ = true; } - chromeos::PowerManagerClient::Initialize(); + chromeos::PowerManagerClient::InitializeFake(); if (!chromeos::PowerPolicyController::IsInitialized()) { chromeos::PowerPolicyController::Initialize(
diff --git a/ash/wm/non_client_frame_controller.h b/ash/wm/non_client_frame_controller.h index 3303c34..df8e140 100644 --- a/ash/wm/non_client_frame_controller.h +++ b/ash/wm/non_client_frame_controller.h
@@ -72,6 +72,10 @@ // value provided by the associated window's aura::WindowDelegate::GetCursor. void StoreCursor(const ui::Cursor& cursor); + ws::TopLevelProxyWindow* top_level_proxy_window() { + return top_level_proxy_window_; + } + // views::WidgetDelegate: base::string16 GetWindowTitle() const override; bool CanResize() const override;
diff --git a/ash/wm/window_mirror_view.cc b/ash/wm/window_mirror_view.cc index f7672ceb7..9f130ed 100644 --- a/ash/wm/window_mirror_view.cc +++ b/ash/wm/window_mirror_view.cc
@@ -7,10 +7,14 @@ #include <algorithm> #include <memory> +#include "ash/wm/non_client_frame_controller.h" #include "ash/wm/widget_finder.h" #include "ash/wm/window_state.h" +#include "services/ws/top_level_proxy_window.h" #include "ui/aura/client/aura_constants.h" +#include "ui/aura/env.h" #include "ui/aura/window.h" +#include "ui/aura/window_occlusion_tracker.h" #include "ui/compositor/layer.h" #include "ui/compositor/layer_tree_owner.h" #include "ui/views/widget/widget.h" @@ -132,6 +136,10 @@ target_ = GetWidget()->GetNativeWindow(); target_->TrackOcclusionState(); + force_occlusion_tracker_visible_.reset(); + force_proxy_window_visible_.reset(); + env_observer_.RemoveAll(); + // Allocate new memory for |target_window_list| here because as soon as a // call is made to SetProperty, the previous memory will be deallocated. auto temp_list = @@ -146,6 +154,19 @@ // NOTE: This will deallocate the current property value so make sure new // memory has been allocated for the property value. source_->SetProperty(aura::client::kMirrorWindowList, temp_list.release()); + + // If |source_| represents a remote client, it needs to be made visible, + // otherwise it won't produce frames. + if (target_ && NonClientFrameController::Get(source_)) { + // Wait for window-occlusion tracker to be running before forcing + // visibility. This is done to minimize the amount of work during the + // initial animation when entering overview. In particular, telling the + // remote client it is visible is likely to result in a fair amount of work. + if (source_->env()->GetWindowOcclusionTracker()->IsPaused()) + env_observer_.Add(target_->env()); + else + ForceVisibilityAndOcclusionForProxyWindow(); + } } void WindowMirrorView::InitLayerOwner() { @@ -191,5 +212,27 @@ return client_view->ConvertRectToWidget(client_view->GetLocalBounds()); } +void WindowMirrorView::ForceVisibilityAndOcclusionForProxyWindow() { + NonClientFrameController* frame_controller = + NonClientFrameController::Get(source_); + // Earlier checks ensure we only get here if there is a + // NonClientFrameController. + DCHECK(frame_controller); + // In order for the remote client to produce frames the client needs to think + // the window is visible. It may not actually be visible now, so force it. + force_proxy_window_visible_ = + frame_controller->top_level_proxy_window()->ForceVisible(); + + // Similarly, force the occlusion tracker to treat the source as visible. + force_occlusion_tracker_visible_ = + std::make_unique<aura::WindowOcclusionTracker::ScopedForceVisible>( + source_); +} + +void WindowMirrorView::OnWindowOcclusionTrackingResumed() { + ForceVisibilityAndOcclusionForProxyWindow(); + env_observer_.RemoveAll(); +} + } // namespace wm } // namespace ash
diff --git a/ash/wm/window_mirror_view.h b/ash/wm/window_mirror_view.h index d6440c0..e43e637 100644 --- a/ash/wm/window_mirror_view.h +++ b/ash/wm/window_mirror_view.h
@@ -9,6 +9,10 @@ #include "ash/ash_export.h" #include "base/macros.h" +#include "base/scoped_observer.h" +#include "ui/aura/env.h" +#include "ui/aura/env_observer.h" +#include "ui/aura/window_occlusion_tracker.h" #include "ui/views/view.h" namespace aura { @@ -19,12 +23,16 @@ class LayerTreeOwner; } -namespace ash { +namespace ws { +class ScopedForceVisible; +} +namespace ash { namespace wm { // A view that mirrors the client area of a single (source) window. -class ASH_EXPORT WindowMirrorView : public views::View { +class ASH_EXPORT WindowMirrorView : public views::View, + public aura::EnvObserver { public: WindowMirrorView(aura::Window* source, bool trilinear_filtering_on_init); ~WindowMirrorView() override; @@ -60,6 +68,11 @@ // coordinate space. gfx::Rect GetClientAreaBounds() const; + void ForceVisibilityAndOcclusionForProxyWindow(); + + // aura::EnvObserver: + void OnWindowOcclusionTrackingResumed() override; + // The original window that is being represented by |this|. aura::Window* source_; @@ -74,6 +87,14 @@ // InitLayerOwner(). bool trilinear_filtering_on_init_; + // These are used when mirroring a window from a remote client (a proxy + // window from the window-service). + std::unique_ptr<aura::WindowOcclusionTracker::ScopedForceVisible> + force_occlusion_tracker_visible_; + std::unique_ptr<ws::ScopedForceVisible> force_proxy_window_visible_; + + ScopedObserver<aura::Env, aura::EnvObserver> env_observer_{this}; + DISALLOW_COPY_AND_ASSIGN(WindowMirrorView); };
diff --git a/ash/wm/window_mirror_view_unittest.cc b/ash/wm/window_mirror_view_unittest.cc index da96a0f..dba54fc 100644 --- a/ash/wm/window_mirror_view_unittest.cc +++ b/ash/wm/window_mirror_view_unittest.cc
@@ -6,10 +6,15 @@ #include "ash/test/ash_test_base.h" #include "mojo/public/cpp/bindings/map.h" +#include "services/ws/client_root.h" +#include "services/ws/client_root_test_helper.h" +#include "services/ws/proxy_window.h" #include "services/ws/window_tree_test_helper.h" #include "ui/aura/client/aura_constants.h" +#include "ui/aura/window_occlusion_tracker.h" #include "ui/gfx/geometry/size.h" #include "ui/views/widget/widget.h" +#include "ui/views/widget/widget_delegate.h" namespace ash { namespace wm { @@ -33,6 +38,58 @@ EXPECT_FALSE(mirror_view->CalculatePreferredSize().IsEmpty()); } +TEST_F(WindowMirrorViewTest, RemoteClientForcedVisible) { + auto properties = CreatePropertiesForProxyWindow(gfx::Rect(0, 0, 400, 300)); + std::unique_ptr<aura::Window> window( + GetWindowTreeTestHelper()->NewTopLevelWindow( + mojo::MapToFlatMap(properties))); + + ws::ClientRootTestHelper client_root_test_helper( + ws::ProxyWindow::GetMayBeNull(window.get()) + ->owning_window_tree() + ->GetClientRootForWindow(window.get())); + EXPECT_FALSE(client_root_test_helper.IsWindowForcedVisible()); + // Assertions only make sense if window occlusion tracker is running, which it + // should be at this point. + EXPECT_FALSE(window->env()->GetWindowOcclusionTracker()->IsPaused()); + auto widget = CreateTestWidget(); + widget->Hide(); + auto mirror_view = std::make_unique<WindowMirrorView>( + window.get(), /*trilinear_filtering_on_init=*/false); + widget->widget_delegate()->GetContentsView()->AddChildView(mirror_view.get()); + // Even though the widget is hidden, the remote client should think it's + // visible. + EXPECT_TRUE(client_root_test_helper.IsWindowForcedVisible()); +} + +TEST_F(WindowMirrorViewTest, RemoteClientForcedVisibleWhenRunning) { + auto properties = CreatePropertiesForProxyWindow(gfx::Rect(0, 0, 400, 300)); + std::unique_ptr<aura::Window> window( + GetWindowTreeTestHelper()->NewTopLevelWindow( + mojo::MapToFlatMap(properties))); + + ws::ClientRootTestHelper client_root_test_helper( + ws::ProxyWindow::GetMayBeNull(window.get()) + ->owning_window_tree() + ->GetClientRootForWindow(window.get())); + + auto pause_occlusion_tracker = + std::make_unique<aura::WindowOcclusionTracker::ScopedPause>( + window->env()); + auto widget = CreateTestWidget(); + widget->Hide(); + auto mirror_view = std::make_unique<WindowMirrorView>( + window.get(), /*trilinear_filtering_on_init=*/false); + widget->widget_delegate()->GetContentsView()->AddChildView(mirror_view.get()); + + // As occlusion tracking is paused, the remote window should remain hidden. + EXPECT_FALSE(client_root_test_helper.IsWindowForcedVisible()); + + // When occlusion tracking is enabled, the remote window shoul be visible. + pause_occlusion_tracker.reset(); + EXPECT_TRUE(client_root_test_helper.IsWindowForcedVisible()); +} + } // namespace } // namespace wm } // namespace ash
diff --git a/base/task/sequence_manager/sequence_manager_impl_unittest.cc b/base/task/sequence_manager/sequence_manager_impl_unittest.cc index e46dea8..fa096b0 100644 --- a/base/task/sequence_manager/sequence_manager_impl_unittest.cc +++ b/base/task/sequence_manager/sequence_manager_impl_unittest.cc
@@ -4628,6 +4628,26 @@ FastForwardUntilNoTasksRemain(); } +TEST_P(SequenceManagerTest, UnregisterTaskQueueTriggersScheduleWork) { + constexpr auto kDelay = TimeDelta::FromMinutes(1); + auto queue_1 = CreateTaskQueue(); + auto queue_2 = CreateTaskQueue(); + + MockTask task; + EXPECT_CALL(task, Run).Times(1); + + queue_1->task_runner()->PostDelayedTask(FROM_HERE, task.Get(), kDelay); + queue_2->task_runner()->PostDelayedTask(FROM_HERE, task.Get(), kDelay * 2); + + AdvanceMockTickClock(kDelay * 2); + + // Wakeup time needs to be adjusted to kDelay * 2 when the queue is + // unregistered from the TimeDomain + queue_1->ShutdownTaskQueue(); + + RunLoop().RunUntilIdle(); +} + } // namespace sequence_manager_impl_unittest } // namespace internal } // namespace sequence_manager
diff --git a/base/task/sequence_manager/task_queue_impl.cc b/base/task/sequence_manager/task_queue_impl.cc index 77bfc92..482e744 100644 --- a/base/task/sequence_manager/task_queue_impl.cc +++ b/base/task/sequence_manager/task_queue_impl.cc
@@ -160,22 +160,20 @@ { base::internal::AutoSchedulerLock lock(any_thread_lock_); - if (main_thread_only().time_domain) - main_thread_only().time_domain->UnregisterQueue(this); - any_thread_.unregistered = true; - - main_thread_only().on_task_completed_handler = OnTaskCompletedHandler(); any_thread_.time_domain = nullptr; - main_thread_only().time_domain = nullptr; - - main_thread_only().on_next_wake_up_changed_callback = - OnNextWakeUpChangedCallback(); immediate_incoming_queue.swap(any_thread_.immediate_incoming_queue); - - empty_queues_to_reload_handle_.ReleaseAtomicFlag(); } + if (main_thread_only().time_domain) + main_thread_only().time_domain->UnregisterQueue(this); + + main_thread_only().on_task_completed_handler = OnTaskCompletedHandler(); + main_thread_only().time_domain = nullptr; + main_thread_only().on_next_wake_up_changed_callback = + OnNextWakeUpChangedCallback(); + empty_queues_to_reload_handle_.ReleaseAtomicFlag(); + // It is possible for a task to hold a scoped_refptr to this, which // will lead to TaskQueueImpl destructor being called when deleting a task. // To avoid use-after-free, we need to clear all fields of a task queue
diff --git a/base/task/task_scheduler/sequence.cc b/base/task/task_scheduler/sequence.cc index d392a789..811bde9 100644 --- a/base/task/task_scheduler/sequence.cc +++ b/base/task/task_scheduler/sequence.cc
@@ -96,6 +96,10 @@ return Transaction(this); } +ExecutionEnvironment Sequence::GetExecutionEnvironment() { + return {token_, &sequence_local_storage_}; +} + // static SequenceAndTransaction SequenceAndTransaction::FromSequence( scoped_refptr<Sequence> sequence) {
diff --git a/base/task/task_scheduler/sequence.h b/base/task/task_scheduler/sequence.h index 19d5d587..f46196c7 100644 --- a/base/task/task_scheduler/sequence.h +++ b/base/task/task_scheduler/sequence.h
@@ -76,6 +76,8 @@ // active Sequence::Transaction. Transaction BeginTransaction(); + ExecutionEnvironment GetExecutionEnvironment() override; + // Returns a token that uniquely identifies this Sequence. const SequenceToken& token() const { return token_; }
diff --git a/base/task/task_scheduler/task_source.h b/base/task/task_scheduler/task_source.h index b31ecabf..74b5bcd 100644 --- a/base/task/task_scheduler/task_source.h +++ b/base/task/task_scheduler/task_source.h
@@ -11,15 +11,22 @@ #include "base/macros.h" #include "base/memory/ref_counted.h" #include "base/optional.h" +#include "base/sequence_token.h" #include "base/task/common/intrusive_heap.h" #include "base/task/task_scheduler/scheduler_lock.h" #include "base/task/task_scheduler/sequence_sort_key.h" #include "base/task/task_scheduler/task.h" #include "base/task/task_traits.h" +#include "base/threading/sequence_local_storage_map.h" namespace base { namespace internal { +struct BASE_EXPORT ExecutionEnvironment { + SequenceToken token; + SequenceLocalStorageMap* sequence_local_storage; +}; + // A TaskSource is a virtual class that provides a series of Tasks that must be // executed. // @@ -107,6 +114,8 @@ // active TaskSource::Transaction. Transaction BeginTransaction(); + virtual ExecutionEnvironment GetExecutionEnvironment() = 0; + // Support for IntrusiveHeap. void SetHeapHandle(const HeapHandle& handle); void ClearHeapHandle();
diff --git a/base/task/task_scheduler/task_source_unittest.cc b/base/task/task_scheduler/task_source_unittest.cc index 17b6ade..65eb3309 100644 --- a/base/task/task_scheduler/task_source_unittest.cc +++ b/base/task/task_scheduler/task_source_unittest.cc
@@ -23,6 +23,8 @@ public: MockTaskSource(TaskTraits traits) : TaskSource(traits) {} + MOCK_METHOD0(GetExecutionEnvironment, ExecutionEnvironment()); + protected: MOCK_METHOD0(TakeTask, base::Optional<Task>()); MOCK_CONST_METHOD0(GetSortKey, SequenceSortKey());
diff --git a/base/task/task_scheduler/task_tracker.cc b/base/task/task_scheduler/task_tracker.cc index 588328c..2d03e95 100644 --- a/base/task/task_scheduler/task_tracker.cc +++ b/base/task/task_scheduler/task_tracker.cc
@@ -577,6 +577,8 @@ RecordLatencyHistogram(LatencyHistogramType::TASK_LATENCY, traits, task.queue_time); + const auto environment = sequence->GetExecutionEnvironment(); + const bool previous_singleton_allowed = ThreadRestrictions::SetSingletonAllowed( traits.shutdown_behavior() != @@ -587,15 +589,22 @@ ThreadRestrictions::SetWaitAllowed(traits.with_base_sync_primitives()); { - const SequenceToken& sequence_token = sequence->token(); - DCHECK(sequence_token.IsValid()); + DCHECK(environment.token.IsValid()); ScopedSetSequenceTokenForCurrentThread - scoped_set_sequence_token_for_current_thread(sequence_token); + scoped_set_sequence_token_for_current_thread(environment.token); ScopedSetTaskPriorityForCurrentThread scoped_set_task_priority_for_current_thread(traits.priority()); + + // Local storage map used if none is provided by |environment|. + Optional<SequenceLocalStorageMap> local_storage_map; + if (!environment.sequence_local_storage) + local_storage_map.emplace(); + ScopedSetSequenceLocalStorageMapForCurrentThread scoped_set_sequence_local_storage_map_for_current_thread( - sequence->sequence_local_storage()); + environment.sequence_local_storage + ? environment.sequence_local_storage + : &local_storage_map.value()); // Set up TaskRunnerHandle as expected for the scope of the task. Optional<SequencedTaskRunnerHandle> sequenced_task_runner_handle; @@ -622,7 +631,7 @@ // http://crbug.com/652692 is resolved. TRACE_EVENT1("task_scheduler", "TaskScheduler_TaskInfo", "task_info", std::make_unique<TaskTracingInfo>(traits, execution_mode, - sequence_token)); + environment.token)); RunTaskWithShutdownBehavior(traits.shutdown_behavior(), &task); }
diff --git a/base/trace_event/builtin_categories.h b/base/trace_event/builtin_categories.h index de84db3..bb5bb19 100644 --- a/base/trace_event/builtin_categories.h +++ b/base/trace_event/builtin_categories.h
@@ -205,6 +205,7 @@ X(TRACE_DISABLED_BY_DEFAULT("v8.runtime")) \ X(TRACE_DISABLED_BY_DEFAULT("v8.runtime_stats")) \ X(TRACE_DISABLED_BY_DEFAULT("v8.runtime_stats_sampling")) \ + X(TRACE_DISABLED_BY_DEFAULT("v8.wasm")) \ X(TRACE_DISABLED_BY_DEFAULT("video_and_image_capture")) \ X(TRACE_DISABLED_BY_DEFAULT("viz.debug.overlay_planes")) \ X(TRACE_DISABLED_BY_DEFAULT("viz.hit_testing_flow")) \
diff --git a/build/android/BUILD.gn b/build/android/BUILD.gn index 5e61187..d77898b 100644 --- a/build/android/BUILD.gn +++ b/build/android/BUILD.gn
@@ -40,30 +40,26 @@ # Write to a file some GN vars that are useful to scripts that use the output # directory. Format is chosen as easliy importable by both python and bash. - CR = "$0x0A" - _data = "" - _data += "android_sdk_build_tools=" + - rebase_path(android_sdk_build_tools, root_build_dir) + CR - _data += "android_sdk_build_tools_version=$android_sdk_build_tools_version$CR" - _data += - "android_sdk_tools_version_suffix=$android_sdk_tools_version_suffix$CR" - _data += - "android_sdk_root=" + rebase_path(android_sdk_root, root_build_dir) + CR - _data += "android_sdk_version=$android_sdk_version$CR" - _data += - "android_ndk_root=" + rebase_path(android_ndk_root, root_build_dir) + CR - _data += "android_tool_prefix=" + - rebase_path(android_tool_prefix, root_build_dir) + CR + _lines = [ + "android_sdk_build_tools=" + + rebase_path(android_sdk_build_tools, root_build_dir), + "android_sdk_build_tools_version=$android_sdk_build_tools_version", + "android_sdk_tools_version_suffix=$android_sdk_tools_version_suffix", + "android_sdk_root=" + rebase_path(android_sdk_root, root_build_dir), + "android_sdk_version=$android_sdk_version", + "android_ndk_root=" + rebase_path(android_ndk_root, root_build_dir), + "android_tool_prefix=" + rebase_path(android_tool_prefix, root_build_dir), + ] if (defined(android_secondary_abi_cpu)) { _secondary_label_info = get_label_info(":foo($android_secondary_abi_toolchain)", "root_out_dir") - _data += "android_secondary_abi_toolchain=" + - rebase_path(_secondary_label_info, root_build_dir) + CR + _lines += [ "android_secondary_abi_toolchain=" + + rebase_path(_secondary_label_info, root_build_dir) ] } if (defined(build_apk_secondary_abi)) { - _data += "build_apk_secondary_abi=$build_apk_secondary_abi" + CR + _lines += [ "build_apk_secondary_abi=$build_apk_secondary_abi" ] } - write_file(android_build_vars, _data) + write_file(android_build_vars, _lines) } python_library("devil_chromium_py") {
diff --git a/build/android/bytecode/java/org/chromium/bytecode/ByteCodeProcessor.java b/build/android/bytecode/java/org/chromium/bytecode/ByteCodeProcessor.java index 11474216..37dc192 100644 --- a/build/android/bytecode/java/org/chromium/bytecode/ByteCodeProcessor.java +++ b/build/android/bytecode/java/org/chromium/bytecode/ByteCodeProcessor.java
@@ -18,6 +18,7 @@ import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; +import java.io.PrintStream; import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; @@ -30,6 +31,7 @@ import java.util.Collection; import java.util.HashSet; import java.util.List; +import java.util.Map; import java.util.Set; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; @@ -177,16 +179,44 @@ throw new RuntimeException(ioException); } - if (sValidator.getNumClassPathErrors() > 0) { - System.err.println("Missing " + sValidator.getNumClassPathErrors() - + " classes missing in direct classpath. To fix, add GN deps for:"); - for (String s : sValidator.getClassPathMissingJars()) { - System.err.println(s); + if (sValidator.hasErrors()) { + System.err.println("Direct classpath is incomplete. To fix, add deps on the " + + "GN target(s) that provide:"); + for (Map.Entry<String, Map<String, Set<String>>> entry : + sValidator.getErrors().entrySet()) { + printValidationError(System.err, entry.getKey(), entry.getValue()); } System.exit(1); } } + private static void printValidationError( + PrintStream out, String jarName, Map<String, Set<String>> missingClasses) { + out.print(" * "); + out.println(jarName); + int i = 0; + final int numErrorsPerJar = 2; + // The list of missing classes is non-exhaustive because each class that fails to validate + // reports only the first missing class. + for (Map.Entry<String, Set<String>> entry : missingClasses.entrySet()) { + String missingClass = entry.getKey(); + Set<String> filesThatNeededIt = entry.getValue(); + out.print(" * "); + if (i == numErrorsPerJar) { + out.print(String.format("And %d more...", missingClasses.size() - numErrorsPerJar)); + break; + } + out.print(missingClass.replace('/', '.')); + out.print(" (needed by "); + out.print(filesThatNeededIt.iterator().next().replace('/', '.')); + if (filesThatNeededIt.size() > 1) { + out.print(String.format(" and %d more", filesThatNeededIt.size() - 1)); + } + out.println(")"); + i++; + } + } + private static byte[] readAllBytes(InputStream inputStream) throws IOException { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); int numRead = 0;
diff --git a/build/android/bytecode/java/org/chromium/bytecode/ClassPathValidator.java b/build/android/bytecode/java/org/chromium/bytecode/ClassPathValidator.java index b73cde80..c35c3f68 100644 --- a/build/android/bytecode/java/org/chromium/bytecode/ClassPathValidator.java +++ b/build/android/bytecode/java/org/chromium/bytecode/ClassPathValidator.java
@@ -8,8 +8,10 @@ import java.util.Collection; import java.util.Collections; -import java.util.HashSet; +import java.util.Map; import java.util.Set; +import java.util.TreeMap; +import java.util.TreeSet; /** * Checks classpaths (given as ClassLoaders) by reading the constant pool of the class file and @@ -18,8 +20,9 @@ * can't find the class with any given classpath. */ public class ClassPathValidator { - private final Set<String> mClassPathMissingJars = new HashSet<>(); - private int mNumClassPathErrors; + // Map of missing .jar -> Missing class -> Classes that failed. + // TreeMap so that error messages have sorted list of jars. + private final Map<String, Map<String, Set<String>>> mErrors = new TreeMap<>(); static class ClassNotLoadedException extends ClassNotFoundException { private final String mClassName; @@ -128,13 +131,24 @@ } // Iterating through all jars that are in the full classpath but not the direct // classpath to find which one provides the class we are looking for. - for (String s : jarsOnlyInFullClassPath) { + for (String jarPath : jarsOnlyInFullClassPath) { try { ClassLoader smallLoader = - ByteCodeProcessor.loadJars(Collections.singletonList(s)); + ByteCodeProcessor.loadJars(Collections.singletonList(jarPath)); validateClass(smallLoader, e.getClassName()); - mClassPathMissingJars.add(s); - mNumClassPathErrors++; + Map<String, Set<String>> failedClassesByMissingClass = mErrors.get(jarPath); + if (failedClassesByMissingClass == null) { + // TreeMap so that error messages have sorted list of classes. + failedClassesByMissingClass = new TreeMap<>(); + mErrors.put(jarPath, failedClassesByMissingClass); + } + Set<String> failedClasses = + failedClassesByMissingClass.get(e.getClassName()); + if (failedClasses == null) { + failedClasses = new TreeSet<>(); + failedClassesByMissingClass.put(e.getClassName(), failedClasses); + } + failedClasses.add(classReader.getClassName()); break; } catch (ClassNotLoadedException f) { } @@ -143,11 +157,11 @@ } } - public int getNumClassPathErrors() { - return mNumClassPathErrors; + public Map<String, Map<String, Set<String>>> getErrors() { + return mErrors; } - public Set<String> getClassPathMissingJars() { - return mClassPathMissingJars; + public boolean hasErrors() { + return !mErrors.isEmpty(); } }
diff --git a/build/android/gyp/proguard.py b/build/android/gyp/proguard.py index 2aec4de..e811e33 100755 --- a/build/android/gyp/proguard.py +++ b/build/android/gyp/proguard.py
@@ -15,6 +15,11 @@ from util import diff_utils from util import proguard_util +_GENERATED_PROGUARD_HEADER = """ +################################################################################ +# Dynamically generated from build/android/gyp/proguard.py +################################################################################ +""" # Example: # android.arch.core.internal.SafeIterableMap$Entry -> b: @@ -76,9 +81,9 @@ options, _ = parser.parse_args(args) assert not options.main_dex_rules_path or options.r8_path, \ - "R8 must be enabled to pass main dex rules." + 'R8 must be enabled to pass main dex rules.' assert not options.min_api or options.r8_path, \ - "R8 must be enabled to pass min api." + 'R8 must be enabled to pass min api.' classpath = [] for arg in options.classpath: @@ -95,7 +100,7 @@ options.input_paths = build_utils.ParseGnList(options.input_paths) if not options.mapping_output: - options.mapping_output = options.output_path + ".mapping" + options.mapping_output = options.output_path + '.mapping' if options.apply_mapping: options.apply_mapping = os.path.abspath(options.apply_mapping) @@ -158,23 +163,28 @@ for config_file in options.proguard_configs: cmd += ['--pg-conf', config_file] - if options.apply_mapping or options.repackage_classes: + temp_config_string = '' + if options.apply_mapping or options.repackage_classes or options.min_api: with open(tmp_config_path, 'w') as f: if options.apply_mapping: - f.write('-applymapping \'%s\'\n' % (options.apply_mapping)) + temp_config_string += '-applymapping \'%s\'\n' % (options.apply_mapping) if options.repackage_classes: - f.write('-repackageclasses \'%s\'\n' % (options.repackage_classes)) + temp_config_string += '-repackageclasses \'%s\'\n' % ( + options.repackage_classes) + if options.min_api: + temp_config_string += ( + '-assumevalues class android.os.Build$VERSION {\n' + + ' public static final int SDK_INT return ' + options.min_api + + '..9999;\n}\n') + f.write(temp_config_string) cmd += ['--pg-conf', tmp_config_path] - if options.min_api: - cmd += ['--min-api', options.min_api] - if options.main_dex_rules_path: for main_dex_rule in options.main_dex_rules_path: cmd += ['--main-dex-rules', main_dex_rule] cmd += options.input_paths - return cmd + return cmd, temp_config_string def main(args): @@ -189,6 +199,7 @@ # TODO(agrieve): Remove proguard usages. if options.r8_path: + temp_config_string = '' with build_utils.TempDir() as tmp_dir: tmp_mapping_path = os.path.join(tmp_dir, 'mapping.txt') tmp_proguard_config_path = os.path.join(tmp_dir, 'proguard_config.txt') @@ -205,13 +216,15 @@ if options.output_path.endswith('.dex'): with build_utils.TempDir() as tmp_dex_dir: - cmd = _CreateR8Command(options, tmp_mapping_path, tmp_dex_dir, - tmp_proguard_config_path, libraries) + cmd, temp_config_string = _CreateR8Command( + options, tmp_mapping_path, tmp_dex_dir, tmp_proguard_config_path, + libraries) build_utils.CheckOutput(cmd, print_stdout=print_stdout) _MoveTempDexFile(tmp_dex_dir, options.output_path) else: - cmd = _CreateR8Command(options, tmp_mapping_path, options.output_path, - tmp_proguard_config_path, libraries) + cmd, temp_config_string = _CreateR8Command( + options, tmp_mapping_path, options.output_path, + tmp_proguard_config_path, libraries) build_utils.CheckOutput(cmd, print_stdout=print_stdout) # Copy output files to correct locations. @@ -219,10 +232,13 @@ # Mapping files generated by R8 include comments that may break # some of our tooling so remove those. with open(tmp_mapping_path) as tmp: - mapping.writelines(l for l in tmp if not l.startswith("#")) + mapping.writelines(l for l in tmp if not l.startswith('#')) with build_utils.AtomicOutput(options.output_config) as f: f.write(merged_configs) + if temp_config_string: + f.write(_GENERATED_PROGUARD_HEADER) + f.write(temp_config_string) if options.expected_configs_file: _VerifyExpectedConfigs(options.expected_configs_file,
diff --git a/build/android/gyp/util/diff_utils.py b/build/android/gyp/util/diff_utils.py index 85acb681..300e35a 100755 --- a/build/android/gyp/util/diff_utils.py +++ b/build/android/gyp/util/diff_utils.py
@@ -23,4 +23,4 @@ tofile=actual_path, n=0) - return '\n'.join(diff) + return ''.join(diff)
diff --git a/build/android/stacktrace/crashpad_stackwalker.py b/build/android/stacktrace/crashpad_stackwalker.py index eedb7e55..02024c9 100755 --- a/build/android/stacktrace/crashpad_stackwalker.py +++ b/build/android/stacktrace/crashpad_stackwalker.py
@@ -18,15 +18,17 @@ import subprocess import tempfile -sys.path.append( - os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir))) +_BUILD_ANDROID_PATH = os.path.abspath( + os.path.join(os.path.dirname(__file__), '..')) +sys.path.append(_BUILD_ANDROID_PATH) import devil_chromium from devil.android import device_utils def _CreateSymbolsDir(build_path, dynamic_library_names): - generator = os.path.join('components', 'crash', 'content', 'tools', - 'generate_breakpad_symbols.py') + generator = os.path.normpath( + os.path.join(_BUILD_ANDROID_PATH, '..', '..', 'components', 'crash', + 'content', 'tools', 'generate_breakpad_symbols.py')) syms_dir = os.path.join(build_path, 'crashpad_syms') shutil.rmtree(syms_dir, ignore_errors=True) os.mkdir(syms_dir) @@ -125,6 +127,12 @@ help='Directory on the device where Chrome stores cached files,' ' crashpad stores dumps in a subdirectory of it') args = parser.parse_args() + + stackwalk_path = os.path.join(args.build_path, 'minidump_stackwalk') + if not os.path.exists(stackwalk_path): + logging.error('Missing minidump_stackwalk executable') + return 1 + devil_chromium.Initialize(adb_path=args.adb_path) device = device_utils.DeviceUtils(args.device) @@ -145,10 +153,7 @@ library_names = _ExtractLibraryNamesFromDump(args.build_path, dump_full_path) symbols_dir = _CreateSymbolsDir(args.build_path, library_names) - stackwalk_cmd = [ - os.path.join(args.build_path, 'minidump_stackwalk'), dump_full_path, - symbols_dir - ] + stackwalk_cmd = [stackwalk_path, dump_full_path, symbols_dir] subprocess.call(stackwalk_cmd) finally: shutil.rmtree(dump_dir, ignore_errors=True)
diff --git a/build/compute_build_timestamp.py b/build/compute_build_timestamp.py index a7191bb..1c4ca9c 100755 --- a/build/compute_build_timestamp.py +++ b/build/compute_build_timestamp.py
@@ -28,6 +28,8 @@ # the symbol server, so rarely changing timestamps can cause conflicts there # as well. We only upload symbols for official builds to the symbol server. +from __future__ import print_function + import argparse import calendar import datetime @@ -112,7 +114,7 @@ now = now - datetime.timedelta(days=1) now = datetime.datetime(now.year, now.month, now.day, 5, 0, 0) build_date = GetBuildDate(args.build_type, now) - print int(calendar.timegm(build_date.utctimetuple())) + print(int(calendar.timegm(build_date.utctimetuple()))) return 0
diff --git a/build/config/android/rules.gni b/build/config/android/rules.gni index 5c97f16..cecb1c4 100644 --- a/build/config/android/rules.gni +++ b/build/config/android/rules.gni
@@ -1702,7 +1702,11 @@ deps = _deps build_config = _build_config proguard_enabled = true - forward_variables_from(invoker, [ "proguard_configs" ]) + forward_variables_from(invoker, + [ + "proguard_configs", + "min_sdk_version", + ]) output = invoker.output } } @@ -4025,6 +4029,10 @@ _enable_multidex = defined(invoker.enable_multidex) && invoker.enable_multidex + if (!_proguard_enabled && defined(invoker.min_sdk_version)) { + not_needed(invoker, [ "min_sdk_version" ]) + } + # Prevent "unused variable". not_needed([ "_enable_multidex" ]) @@ -4075,7 +4083,11 @@ enable_multidex = _enable_multidex proguard_enabled = true proguard_mapping_path = _async_proguard_mapping_path - forward_variables_from(invoker, [ "proguard_jar_path" ]) + forward_variables_from(invoker, + [ + "proguard_jar_path", + "min_sdk_version", + ]) build_config = _module.build_config repackage_classes = "ap${_async_package_number}" @@ -4128,7 +4140,11 @@ enable_multidex = _enable_multidex proguard_enabled = true proguard_mapping_path = _proguard_mapping_path - forward_variables_from(invoker, [ "proguard_jar_path" ]) + forward_variables_from(invoker, + [ + "proguard_jar_path", + "min_sdk_version", + ]) build_config = _build_config deps = _sync_module_targets + [ ":$_build_config_target" ]
diff --git a/build/download_nacl_toolchains.py b/build/download_nacl_toolchains.py index 4b61fc02..286a92a2 100755 --- a/build/download_nacl_toolchains.py +++ b/build/download_nacl_toolchains.py
@@ -5,6 +5,8 @@ """Shim to run nacl toolchain download script only if there is a nacl dir.""" +from __future__ import print_function + import os import shutil import sys @@ -18,9 +20,9 @@ package_version_dir = os.path.join(nacl_build_dir, 'package_version') package_version = os.path.join(package_version_dir, 'package_version.py') if not os.path.exists(package_version): - print "Can't find '%s'" % package_version - print 'Presumably you are intentionally building without NativeClient.' - print 'Skipping NativeClient toolchain download.' + print("Can't find '%s'" % package_version) + print('Presumably you are intentionally building without NativeClient.') + print('Skipping NativeClient toolchain download.') sys.exit(0) sys.path.insert(0, package_version_dir) import package_version @@ -37,7 +39,7 @@ if 'pnacl' in buildbot_name and 'sdk' in buildbot_name: use_pnacl = True if use_pnacl: - print '\n*** DOWNLOADING PNACL TOOLCHAIN ***\n' + print('\n*** DOWNLOADING PNACL TOOLCHAIN ***\n') else: args = ['--exclude', 'pnacl_newlib'] + args @@ -45,7 +47,7 @@ # TODO(olonho): we need to invent more reliable way to get build # configuration info, to know if we're building for ARM. if 'target_arch=arm' not in os.environ.get('GYP_DEFINES', ''): - args = ['--exclude', 'nacl_arm_newlib'] + args + args = ['--exclude', 'nacl_arm_newlib'] + args return package_version.main(args)
diff --git a/build/fuchsia/run_package.py b/build/fuchsia/run_package.py index c828a60..d12698c 100644 --- a/build/fuchsia/run_package.py +++ b/build/fuchsia/run_package.py
@@ -7,16 +7,13 @@ import common import hashlib -import json import logging import multiprocessing import os import re import select -import shutil import subprocess import sys -import tempfile import time import threading import uuid @@ -24,16 +21,10 @@ from symbolizer import SymbolizerFilter FAR = os.path.join(common.SDK_ROOT, 'tools', 'far') -PM = os.path.join(common.SDK_ROOT, 'tools', 'pm') -_REPO_NAME = 'chrome_runner' # Amount of time to wait for the termination of the system log output thread. _JOIN_TIMEOUT_SECS = 5 -# Amount of time to wait for Amber to complete package installation, as a -# mitigation against hangs due to amber/network-related failures. -_INSTALL_TIMEOUT_SECS = 5 * 60 - def _AttachKernelLogReader(target): """Attaches a kernel log reader as a long-running SSH task.""" @@ -116,76 +107,6 @@ package_name) -def _UnregisterAmberRepository(target): - """Unregisters the Amber repository from the target.""" - - logging.debug('Unregistering Amber repository.') - target.RunCommand(['amber_ctl', 'rm_src', '-n', _REPO_NAME]) - - # Re-enable 'devhost' repo if it's present. This is useful for devices that - # were booted with 'fx serve'. - target.RunCommand(['amber_ctl', 'enable_src', '-n', 'devhost'], silent=True) - - -def _RegisterAmberRepository(target, tuf_repo, remote_port): - """Configures a device to use a local TUF repository as an installation source - for packages. - |target|: The remote device to configure. - |tuf_repo|: The host filesystem path to the TUF repository. - |remote_port|: The reverse-forwarded port used to connect to instance of - `pm serve` that is serving the contents of |tuf_repo|.""" - - # Extract the public signing key for inclusion in the config file. - root_keys = [] - root_json = json.load(open(os.path.join(tuf_repo, 'repository', 'root.json'), - 'r')) - for root_key_id in root_json['signed']['roles']['root']['keyids']: - root_keys.append({ - 'Type': root_json['signed']['keys'][root_key_id]['keytype'], - 'Value': root_json['signed']['keys'][root_key_id]['keyval']['public'] - }) - - # "pm serve" can automatically generate a "config.json" file at query time, - # but the file is unusable because it specifies URLs with port - # numbers that are unreachable from across the port forwarding boundary. - # So instead, we generate our own config file with the forwarded port numbers - # instead. - config_file = open(os.path.join(tuf_repo, 'repository', 'repo_config.json'), - 'w') - json.dump({ - 'ID': _REPO_NAME, - 'RepoURL': "http://127.0.0.1:%d" % remote_port, - 'BlobRepoURL': "http://127.0.0.1:%d/blobs" % remote_port, - 'RatePeriod': 10, - 'RootKeys': root_keys, - 'StatusConfig': { - 'Enabled': True - }, - 'Auto': True - }, config_file) - config_file.close() - - # Register the repo. - return_code = target.RunCommand( - [('amber_ctl rm_src -n %s; ' + - 'amber_ctl add_src -f http://127.0.0.1:%d/repo_config.json') - % (_REPO_NAME, remote_port)]) - if return_code != 0: - raise Exception('Error code %d when running amber_ctl.' % return_code) - - -def _DrainStreamToStdout(stream, quit_event): - """Outputs the contents of |stream| until |quit_event| is set.""" - - while not quit_event.is_set(): - rlist, _, _ = select.select([ stream ], [], [], 0.1) - if rlist: - line = rlist[0].readline() - if not line: - return - print line.rstrip() - - class RunPackageArgs: """RunPackage() configuration arguments structure. @@ -211,26 +132,21 @@ return run_package_args -def GetPackageInfo(package_path): - """Returns a tuple with the name and version of a package.""" +def _DrainStreamToStdout(stream, quit_event): + """Outputs the contents of |stream| until |quit_event| is set.""" - # Query the metadata file which resides next to the package file. - package_info = json.load( - open(os.path.join(os.path.dirname(package_path), 'package'))) - return (package_info['name'], package_info['version']) - - -def PublishPackage(tuf_root, package_path): - """Publishes a combined FAR package to a TUF repository root.""" - - subprocess.check_call( - [PM, 'publish', '-a', '-f', package_path, '-r', tuf_root, '-vt', '-v'], - stderr=subprocess.STDOUT) + while not quit_event.is_set(): + rlist, _, _ = select.select([ stream ], [], [], 0.1) + if rlist: + line = rlist[0].readline() + if not line: + return + print line.rstrip() def RunPackage(output_dir, target, package_path, package_name, package_deps, package_args, args): - """Copies the Fuchsia package at |package_path| to the target, + """Installs the Fuchsia package at |package_path| on the target, executes it with |package_args|, and symbolizes its output. output_dir: The path containing the build output files. @@ -242,7 +158,6 @@ Returns the exit code of the remote package process.""" - system_logger = ( _AttachKernelLogReader(target) if args.system_logging else None) try: @@ -256,35 +171,7 @@ log_output_thread.daemon = True log_output_thread.start() - tuf_root = tempfile.mkdtemp() - pm_serve_task = None - - # Publish all packages to the serving TUF repository under |tuf_root|. - subprocess.check_call([PM, 'newrepo', '-repo', tuf_root]) - all_packages = [package_path] + package_deps - for next_package_path in all_packages: - PublishPackage(tuf_root, next_package_path) - - # Serve the |tuf_root| using 'pm serve' and configure the target to pull - # from it. - serve_port = common.GetAvailableTcpPort() - pm_serve_task = subprocess.Popen( - [PM, 'serve', '-d', os.path.join(tuf_root, 'repository'), '-l', - ':%d' % serve_port, '-q']) - remote_port = common.ConnectPortForwardingTask(target, serve_port, 0) - _RegisterAmberRepository(target, tuf_root, remote_port) - - # Install all packages. - for next_package_path in all_packages: - install_package_name, package_version = GetPackageInfo(next_package_path) - logging.info('Installing %s version %s.' % - (install_package_name, package_version)) - return_code = target.RunCommand(['amber_ctl', 'get_up', '-n', - install_package_name, '-v', - package_version], - timeout_secs=_INSTALL_TIMEOUT_SECS) - if return_code != 0: - raise Exception('Error while installing %s.' % install_package_name) + target.InstallPackage(package_path, package_name, package_deps) if system_logger: log_output_quit_event.set() @@ -330,9 +217,4 @@ log_output_thread.join() system_logger.kill() - _UnregisterAmberRepository(target) - if pm_serve_task: - pm_serve_task.kill() - shutil.rmtree(tuf_root) - return process.returncode
diff --git a/build/fuchsia/target.py b/build/fuchsia/target.py index 317186bf..0a2bb23a 100644 --- a/build/fuchsia/target.py +++ b/build/fuchsia/target.py
@@ -4,9 +4,14 @@ import boot_data import common +import json import logging +import os import remote_cmd +import shutil +import subprocess import sys +import tempfile import time @@ -14,6 +19,30 @@ _ATTACH_MAX_RETRIES = 10 _ATTACH_RETRY_INTERVAL = 1 +_PM = os.path.join(common.SDK_ROOT, 'tools', 'pm') +_REPO_NAME = 'chrome_runner' + +# Amount of time to wait for Amber to complete package installation, as a +# mitigation against hangs due to amber/network-related failures. +_INSTALL_TIMEOUT_SECS = 5 * 60 + + +def _GetPackageInfo(package_path): + """Returns a tuple with the name and version of a package.""" + + # Query the metadata file which resides next to the package file. + package_info = json.load( + open(os.path.join(os.path.dirname(package_path), 'package'))) + return (package_info['name'], package_info['version']) + + +def _PublishPackage(tuf_root, package_path): + """Publishes a combined FAR package to a TUF repository root.""" + + subprocess.check_call( + [_PM, 'publish', '-a', '-f', package_path, '-r', tuf_root, '-vt', '-v'], + stderr=subprocess.STDOUT) + class _MapRemoteDataPathForPackage: """Callable object which remaps /data paths to their package-specific @@ -210,3 +239,108 @@ elif self._target_cpu == 'x64': return 'x86_64' raise Exception('Unknown target_cpu %s:' % self._target_cpu) + + + def InstallPackage(self, package_path, package_name, package_deps): + """Installs a package and it's dependencies on the device. If the package is + already installed then it will be updated to the new version. + + package_path: Path to the .far file to be installed. + package_name: Package name. + package_deps: List of .far files with the packages that the main package + depends on. These packages are installed or updated as well. + """ + try: + tuf_root = tempfile.mkdtemp() + pm_serve_task = None + + # Publish all packages to the serving TUF repository under |tuf_root|. + subprocess.check_call([_PM, 'newrepo', '-repo', tuf_root]) + all_packages = [package_path] + package_deps + for next_package_path in all_packages: + _PublishPackage(tuf_root, next_package_path) + + # Serve the |tuf_root| using 'pm serve' and configure the target to pull + # from it. + serve_port = common.GetAvailableTcpPort() + pm_serve_task = subprocess.Popen( + [_PM, 'serve', '-d', os.path.join(tuf_root, 'repository'), '-l', + ':%d' % serve_port, '-q']) + remote_port = common.ConnectPortForwardingTask(self, serve_port, 0) + self._RegisterAmberRepository(tuf_root, remote_port) + + # Install all packages. + for next_package_path in all_packages: + install_package_name, package_version = \ + _GetPackageInfo(next_package_path) + logging.info('Installing %s version %s.' % + (install_package_name, package_version)) + return_code = self.RunCommand(['amber_ctl', 'get_up', '-n', + install_package_name, '-v', + package_version], + timeout_secs=_INSTALL_TIMEOUT_SECS) + if return_code != 0: + raise Exception('Error while installing %s.' % install_package_name) + + finally: + self._UnregisterAmberRepository() + if pm_serve_task: + pm_serve_task.kill() + shutil.rmtree(tuf_root) + + + def _RegisterAmberRepository(self, tuf_repo, remote_port): + """Configures a device to use a local TUF repository as an installation + source for packages. + |tuf_repo|: The host filesystem path to the TUF repository. + |remote_port|: The reverse-forwarded port used to connect to instance of + `pm serve` that is serving the contents of |tuf_repo|.""" + + # Extract the public signing key for inclusion in the config file. + root_keys = [] + root_json_path = os.path.join(tuf_repo, 'repository', 'root.json') + root_json = json.load(open(root_json_path, 'r')) + for root_key_id in root_json['signed']['roles']['root']['keyids']: + root_keys.append({ + 'Type': root_json['signed']['keys'][root_key_id]['keytype'], + 'Value': root_json['signed']['keys'][root_key_id]['keyval']['public'] + }) + + # "pm serve" can automatically generate a "config.json" file at query time, + # but the file is unusable because it specifies URLs with port + # numbers that are unreachable from across the port forwarding boundary. + # So instead, we generate our own config file with the forwarded port + # numbers instead. + config_file = open(os.path.join(tuf_repo, 'repository', 'repo_config.json'), + 'w') + json.dump({ + 'ID': _REPO_NAME, + 'RepoURL': "http://127.0.0.1:%d" % remote_port, + 'BlobRepoURL': "http://127.0.0.1:%d/blobs" % remote_port, + 'RatePeriod': 10, + 'RootKeys': root_keys, + 'StatusConfig': { + 'Enabled': True + }, + 'Auto': True + }, config_file) + config_file.close() + + # Register the repo. + return_code = self.RunCommand( + [('amber_ctl rm_src -n %s; ' + + 'amber_ctl add_src -f http://127.0.0.1:%d/repo_config.json') + % (_REPO_NAME, remote_port)]) + if return_code != 0: + raise Exception('Error code %d when running amber_ctl.' % return_code) + + + def _UnregisterAmberRepository(self): + """Unregisters the Amber repository.""" + + logging.debug('Unregistering Amber repository.') + self.RunCommand(['amber_ctl', 'rm_src', '-n', _REPO_NAME]) + + # Re-enable 'devhost' repo if it's present. This is useful for devices that + # were booted with 'fx serve'. + self.RunCommand(['amber_ctl', 'enable_src', '-n', 'devhost'], silent=True)
diff --git a/build/get_landmines.py b/build/get_landmines.py index 3c484e2..a32ab99 100755 --- a/build/get_landmines.py +++ b/build/get_landmines.py
@@ -8,6 +8,8 @@ (or a list of 'landmines'). """ +from __future__ import print_function + import sys import landmine_utils @@ -37,43 +39,46 @@ # usually less troublesome alternatives. if host_os() == 'win': - print 'Compile on cc_unittests fails due to symbols removed in r185063.' + print('Compile on cc_unittests fails due to symbols removed in r185063.') if host_os() == 'linux': - print 'Builders switching from make to ninja will clobber on this.' + print('Builders switching from make to ninja will clobber on this.') if host_os() == 'mac': - print 'Switching from bundle to unbundled dylib (issue 14743002).' + print('Switching from bundle to unbundled dylib (issue 14743002).') if host_os() in ('win', 'mac'): - print ('Improper dependency for create_nmf.py broke in r240802, ' - 'fixed in r240860.') + print('Improper dependency for create_nmf.py broke in r240802, ' + 'fixed in r240860.') if host_os() == 'win': - print 'Switch to VS2015 Update 3, 14393 SDK' - print 'Need to clobber everything due to an IDL change in r154579 (blink)' - print 'Need to clobber everything due to gen file moves in r175513 (Blink)' - print 'Clobber to get rid of obselete test plugin after r248358' - print 'Clobber to rebuild GN files for V8' - print 'Clobber to get rid of stale generated mojom.h files' - print 'Need to clobber everything due to build_nexe change in nacl r13424' - print '[chromium-dev] PSA: clobber build needed for IDR_INSPECTOR_* compil...' - print 'blink_resources.grd changed: crbug.com/400860' - print 'ninja dependency cycle: crbug.com/408192' - print 'Clobber to fix missing NaCl gyp dependencies (crbug.com/427427).' - print 'Another clobber for missing NaCl gyp deps (crbug.com/427427).' - print 'Clobber to fix GN not picking up increased ID range (crbug.com/444902)' - print 'Remove NaCl toolchains from the output dir (crbug.com/456902)' + print('Switch to VS2015 Update 3, 14393 SDK') + print('Need to clobber everything due to an IDL change in r154579 (blink)') + print('Need to clobber everything due to gen file moves in r175513 (Blink)') + print('Clobber to get rid of obselete test plugin after r248358') + print('Clobber to rebuild GN files for V8') + print('Clobber to get rid of stale generated mojom.h files') + print('Need to clobber everything due to build_nexe change in nacl r13424') + print( + '[chromium-dev] PSA: clobber build needed for IDR_INSPECTOR_* compil...') + print('blink_resources.grd changed: crbug.com/400860') + print('ninja dependency cycle: crbug.com/408192') + print('Clobber to fix missing NaCl gyp dependencies (crbug.com/427427).') + print('Another clobber for missing NaCl gyp deps (crbug.com/427427).') + print( + 'Clobber to fix GN not picking up increased ID range (crbug.com/444902)') + print('Remove NaCl toolchains from the output dir (crbug.com/456902)') if host_os() == 'win': - print 'Clobber to delete stale generated files (crbug.com/510086)' + print('Clobber to delete stale generated files (crbug.com/510086)') if host_os() == 'mac': - print 'Clobber to get rid of evil libsqlite3.dylib (crbug.com/526208)' + print('Clobber to get rid of evil libsqlite3.dylib (crbug.com/526208)') if host_os() == 'mac': - print 'Clobber to remove libsystem.dylib. See crbug.com/620075' + print('Clobber to remove libsystem.dylib. See crbug.com/620075') if host_os() == 'mac': - print 'Clobber to get past mojo gen build error (crbug.com/679607)' + print('Clobber to get past mojo gen build error (crbug.com/679607)') if host_os() == 'win': - print 'Clobber Windows to fix strange PCH-not-rebuilt errors.' - print 'CLobber all to fix GN breakage (crbug.com/736215)' - print 'The Great Blink mv for source files (crbug.com/768828)' + print('Clobber Windows to fix strange PCH-not-rebuilt errors.') + print('CLobber all to fix GN breakage (crbug.com/736215)') + print('The Great Blink mv for source files (crbug.com/768828)') if host_os() == 'linux': - print 'Clobber to workaround buggy .ninja_deps cycle (crbug.com/934404)' + print('Clobber to workaround buggy .ninja_deps cycle (crbug.com/934404)') + def main(): print_landmines()
diff --git a/build/gn_helpers.py b/build/gn_helpers.py index 25f1240..53543e6 100644 --- a/build/gn_helpers.py +++ b/build/gn_helpers.py
@@ -19,6 +19,9 @@ Where the sequence of parameters to join is the relative path from your source file to the build directory.""" +import sys + + class GNException(Exception): pass @@ -29,14 +32,14 @@ allow_dicts indicates if this function will allow converting dictionaries to GN scopes. This is only possible at the top level, you can't nest a GN scope in a list, so this should be set to False for recursive calls.""" - if isinstance(value, basestring): + if isinstance(value, str): if value.find('\n') >= 0: raise GNException("Trying to print a string with a newline in it.") return '"' + \ value.replace('\\', '\\\\').replace('"', '\\"').replace('$', '\\$') + \ '"' - if isinstance(value, unicode): + if sys.version_info.major < 3 and isinstance(value, unicode): return ToGNString(value.encode('utf-8')) if isinstance(value, bool): @@ -52,7 +55,7 @@ raise GNException("Attempting to recursively print a dictionary.") result = "" for key in sorted(value): - if not isinstance(key, basestring): + if not isinstance(key, str) and not isinstance(key, unicode): raise GNException("Dictionary key is not a string.") result += "%s = %s\n" % (key, ToGNString(value[key], False)) return result
diff --git a/build/toolchain/get_concurrent_links.py b/build/toolchain/get_concurrent_links.py index 45a932c1..e5121c77 100644 --- a/build/toolchain/get_concurrent_links.py +++ b/build/toolchain/get_concurrent_links.py
@@ -5,6 +5,8 @@ # This script computs the number of concurrent links we want to run in the build # as a function of machine spec. It's based on GetDefaultConcurrentLinks in GYP. +from __future__ import print_function + import multiprocessing import optparse import os @@ -76,8 +78,8 @@ parser.disable_interspersed_args() options, _ = parser.parse_args() - print _GetDefaultConcurrentLinks(options.mem_per_link_gb, - options.reserve_mem_gb) + print(_GetDefaultConcurrentLinks(options.mem_per_link_gb, + options.reserve_mem_gb)) return 0 if __name__ == '__main__':
diff --git a/build/toolchain/get_cpu_count.py b/build/toolchain/get_cpu_count.py index 1609ce6..765c7c7 100644 --- a/build/toolchain/get_cpu_count.py +++ b/build/toolchain/get_cpu_count.py
@@ -4,6 +4,8 @@ # This script shows cpu count to specify capacity of action pool. +from __future__ import print_function + import multiprocessing import sys @@ -13,7 +15,7 @@ except: cpu_count = 1 - print cpu_count + print(cpu_count) return 0
diff --git a/build/toolchain/win/setup_toolchain.py b/build/toolchain/win/setup_toolchain.py index 2c86752..ef8aeda5 100644 --- a/build/toolchain/win/setup_toolchain.py +++ b/build/toolchain/win/setup_toolchain.py
@@ -10,6 +10,8 @@ # win tool. The script assumes that the root build directory is the current dir # and the files will be written to the current directory. +from __future__ import print_function + import errno import json import os @@ -80,7 +82,7 @@ variables, _ = popen.communicate() if popen.returncode != 0: raise Exception('"%s" failed with error %d' % (args, popen.returncode)) - return variables + return variables.decode(errors='ignore') def _LoadToolchainEnv(cpu, sdk_dir, target_store): @@ -159,7 +161,7 @@ CreateProcess documentation for more details.""" block = '' nul = '\0' - for key, value in envvar_dict.iteritems(): + for key, value in envvar_dict.items(): block += key + '=' + value + nul block += nul return block @@ -241,7 +243,7 @@ # Make include path relative to builddir when cwd and sdk in same drive. try: - include = map(os.path.relpath, include) + include = list(map(os.path.relpath, include)) except ValueError: pass @@ -260,29 +262,29 @@ if (environment_block_name != ''): env_block = _FormatAsEnvironmentBlock(env) - with open(environment_block_name, 'wb') as f: + with open(environment_block_name, 'w') as f: f.write(env_block) assert vc_bin_dir - print 'vc_bin_dir = ' + gn_helpers.ToGNString(vc_bin_dir) + print('vc_bin_dir = ' + gn_helpers.ToGNString(vc_bin_dir)) assert include_I - print 'include_flags_I = ' + gn_helpers.ToGNString(include_I) + print('include_flags_I = ' + gn_helpers.ToGNString(include_I)) assert include_imsvc - print 'include_flags_imsvc = ' + gn_helpers.ToGNString(include_imsvc) + print('include_flags_imsvc = ' + gn_helpers.ToGNString(include_imsvc)) assert vc_lib_path - print 'vc_lib_path = ' + gn_helpers.ToGNString(vc_lib_path) + print('vc_lib_path = ' + gn_helpers.ToGNString(vc_lib_path)) if (target_store != True): # Path is assumed not to exist for desktop applications assert vc_lib_atlmfc_path # Possible atlmfc library path gets introduced in the future for store thus # output result if a result exists. if (vc_lib_atlmfc_path != ''): - print 'vc_lib_atlmfc_path = ' + gn_helpers.ToGNString(vc_lib_atlmfc_path) + print('vc_lib_atlmfc_path = ' + gn_helpers.ToGNString(vc_lib_atlmfc_path)) assert vc_lib_um_path - print 'vc_lib_um_path = ' + gn_helpers.ToGNString(vc_lib_um_path) - print 'paths = ' + gn_helpers.ToGNString(env['PATH']) + print('vc_lib_um_path = ' + gn_helpers.ToGNString(vc_lib_um_path)) + print('paths = ' + gn_helpers.ToGNString(env['PATH'])) assert libpath_flags - print 'libpath_flags = ' + gn_helpers.ToGNString(libpath_flags) + print('libpath_flags = ' + gn_helpers.ToGNString(libpath_flags)) if __name__ == '__main__':
diff --git a/build/util/lastchange.py b/build/util/lastchange.py index 81c7431..327df66 100755 --- a/build/util/lastchange.py +++ b/build/util/lastchange.py
@@ -7,6 +7,8 @@ lastchange.py -- Chromium revision fetching utility. """ +from __future__ import print_function + import re import logging import argparse @@ -76,12 +78,12 @@ if not hsh: return None pos = '' - proc = RunGitCommand(directory, ['cat-file', 'commit', hsh]) + proc = RunGitCommand(directory, ['cat-file', 'commit', hsh.decode()]) if proc: output = proc.communicate()[0] if proc.returncode == 0 and output: for line in reversed(output.splitlines()): - if line.startswith('Cr-Commit-Position:'): + if line.startswith(b'Cr-Commit-Position:'): pos = line.rsplit()[-1].strip() break return VersionInfo(hsh, '%s-%s' % (hsh, pos), int(ct)) @@ -211,7 +213,7 @@ revision_string = version_info.revision_id if args.print_only: - print revision_string + print(revision_string) else: contents = "LASTCHANGE=%s\n" % revision_string if not out_file and not args.header:
diff --git a/build/util/version.gni b/build/util/version.gni index 189d109f1..e9ad80f 100644 --- a/build/util/version.gni +++ b/build/util/version.gni
@@ -33,7 +33,7 @@ "-e", "VERSION_ID='%s%03d00' % (BUILD, int(PATCH))", "-e", - "PATCH_HI=int(PATCH)/256", + "PATCH_HI=int(PATCH)//256", "-e", "PATCH_LO=int(PATCH)%256", ],
diff --git a/build/util/version.py b/build/util/version.py index 767412e9..783268b 100755 --- a/build/util/version.py +++ b/build/util/version.py
@@ -7,6 +7,8 @@ version.py -- Chromium version string substitution utility. """ +from __future__ import print_function + import argparse import os import sys @@ -64,11 +66,11 @@ contains any @KEYWORD@ strings expecting them to be recursively substituted, okay? """ - for key, val in values.iteritems(): + for key, val in values.items(): try: contents = contents.replace('@' + key + '@', val) except TypeError: - print repr(key), repr(val) + print(repr(key), repr(val)) return contents @@ -109,10 +111,14 @@ help='Write substituted strings to FILE.') parser.add_argument('-t', '--template', default=None, help='Use TEMPLATE as the strings to substitute.') - parser.add_argument('-e', '--eval', action='append', default=[], - help='Evaluate VAL after reading variables. Can be used ' - 'to synthesize variables. e.g. -e \'PATCH_HI=int(' - 'PATCH)/256.') + parser.add_argument( + '-e', + '--eval', + action='append', + default=[], + help='Evaluate VAL after reading variables. Can be used ' + 'to synthesize variables. e.g. -e \'PATCH_HI=int(' + 'PATCH)//256.') parser.add_argument('--official', action='store_true', help='Whether the current build should be an official ' 'build, used in addition to the environment ' @@ -141,7 +147,7 @@ parser.error('Unexpected arguments: %r' % options.args) values = fetch_values(options.file, options.official) - for key, val in evals.iteritems(): + for key, val in evals.items(): values[key] = str(eval(val, globals(), values)) if options.template is not None: @@ -161,7 +167,7 @@ if options.output is not None: write_if_changed(options.output, contents) else: - print contents + print(contents) return 0
diff --git a/build/vs_toolchain.py b/build/vs_toolchain.py index 1ab7be5..0ce237fe13 100755 --- a/build/vs_toolchain.py +++ b/build/vs_toolchain.py
@@ -3,6 +3,8 @@ # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. +from __future__ import print_function + import glob import json import os @@ -183,7 +185,7 @@ (not os.path.isfile(target) or abs(os.stat(target).st_mtime - os.stat(source).st_mtime) >= 0.01)): if verbose: - print 'Copying %s to %s...' % (source, target) + print('Copying %s to %s...' % (source, target)) if os.path.exists(target): # Make the file writable so that we can delete it now, and keep it # readable. @@ -398,7 +400,7 @@ will not be downloaded. """ if force != False and force != '--force': - print >>sys.stderr, 'Unknown parameter "%s"' % force + print('Unknown parameter "%s"' % force, file=sys.stderr) return 1 if force == '--force' or os.path.exists(json_data_file): force = True @@ -480,17 +482,15 @@ runtime_dll_dirs = SetEnvironmentAndGetRuntimeDllDirs() win_sdk_dir = SetEnvironmentAndGetSDKDir() - print '''vs_path = %s + print('''vs_path = %s sdk_path = %s vs_version = %s wdk_dir = %s runtime_dirs = %s -''' % ( - ToGNString(NormalizePath(os.environ['GYP_MSVS_OVERRIDE_PATH'])), - ToGNString(win_sdk_dir), - ToGNString(GetVisualStudioVersion()), - ToGNString(NormalizePath(os.environ.get('WDK_DIR', ''))), - ToGNString(os.path.pathsep.join(runtime_dll_dirs or ['None']))) +''' % (ToGNString(NormalizePath(os.environ['GYP_MSVS_OVERRIDE_PATH'])), + ToGNString(win_sdk_dir), ToGNString(GetVisualStudioVersion()), + ToGNString(NormalizePath(os.environ.get('WDK_DIR', ''))), + ToGNString(os.path.pathsep.join(runtime_dll_dirs or ['None'])))) def main(): @@ -500,7 +500,7 @@ 'copy_dlls': CopyDlls, } if len(sys.argv) < 2 or sys.argv[1] not in commands: - print >>sys.stderr, 'Expected one of: %s' % ', '.join(commands) + print('Expected one of: %s' % ', '.join(commands), file=sys.stderr) return 1 return commands[sys.argv[1]](*sys.argv[2:])
diff --git a/build/win/use_ansi_codes.py b/build/win/use_ansi_codes.py index cff5f43..5951c2a 100755 --- a/build/win/use_ansi_codes.py +++ b/build/win/use_ansi_codes.py
@@ -4,7 +4,9 @@ # found in the LICENSE file. """Prints if the the terminal is likely to understand ANSI codes.""" +from __future__ import print_function + import os # Add more terminals here as needed. -print 'ANSICON' in os.environ +print('ANSICON' in os.environ)
diff --git a/build/win_is_xtree_patched.py b/build/win_is_xtree_patched.py index 3f1994f..54aff46 100755 --- a/build/win_is_xtree_patched.py +++ b/build/win_is_xtree_patched.py
@@ -5,6 +5,8 @@ """Determines if the VS xtree header has been patched to disable C4702.""" +from __future__ import print_function + import os @@ -23,4 +25,4 @@ if __name__ == '__main__': - print DoMain([]) + print(DoMain([]))
diff --git a/cc/layers/layer_impl.cc b/cc/layers/layer_impl.cc index 092d9c1..d43e610 100644 --- a/cc/layers/layer_impl.cc +++ b/cc/layers/layer_impl.cc
@@ -146,6 +146,7 @@ effect_node->has_render_surface ? SkBlendMode::kSrcOver : effect_node->blend_mode, GetSortingContextId()); + state->is_fast_rounded_corner = draw_properties_.is_fast_rounded_corner; } void LayerImpl::PopulateScaledSharedQuadState(viz::SharedQuadState* state, @@ -171,6 +172,7 @@ effect_node->has_render_surface ? SkBlendMode::kSrcOver : effect_node->blend_mode, GetSortingContextId()); + state->is_fast_rounded_corner = draw_properties().is_fast_rounded_corner; } bool LayerImpl::WillDraw(DrawMode draw_mode,
diff --git a/cc/layers/surface_layer_impl.cc b/cc/layers/surface_layer_impl.cc index 9f9bd25..5b166bf 100644 --- a/cc/layers/surface_layer_impl.cc +++ b/cc/layers/surface_layer_impl.cc
@@ -131,7 +131,7 @@ return; auto* primary = CreateSurfaceDrawQuad(render_pass, surface_range_); - if (primary && surface_range_.end() != surface_range_.start()) { + if (primary) { // Add the primary surface ID as a dependency. append_quads_data->activation_dependencies.push_back(surface_range_.end()); if (deadline_in_frames_) {
diff --git a/cc/layers/surface_layer_impl_unittest.cc b/cc/layers/surface_layer_impl_unittest.cc index 9442d3f..50ab0f01 100644 --- a/cc/layers/surface_layer_impl_unittest.cc +++ b/cc/layers/surface_layer_impl_unittest.cc
@@ -243,13 +243,8 @@ std::unique_ptr<viz::RenderPass> render_pass = viz::RenderPass::Create(); AppendQuadsData data; surface_layer_impl->AppendQuads(render_pass.get(), &data); - // As the primary and fallback SurfaceInfos match, there is no reason to - // add the primary surface ID to |activation_dependencies| because it is not - // an unresolved dependency. The fallback surface will already be added as a - // reference in referenced_surfaces. Since the primary and fallback surface - // IDs match, there is no reason to propagate the deadline. - EXPECT_THAT(data.activation_dependencies, testing::IsEmpty()); - EXPECT_EQ(base::nullopt, data.deadline_in_frames); + EXPECT_THAT(data.activation_dependencies, UnorderedElementsAre(surface_id1)); + EXPECT_EQ(2u, data.deadline_in_frames); ASSERT_EQ(1u, render_pass->quad_list.size()); const viz::SurfaceDrawQuad* surface_draw_quad1 =
diff --git a/cc/trees/draw_property_utils.cc b/cc/trees/draw_property_utils.cc index c3f4ec3..ec3f35f 100644 --- a/cc/trees/draw_property_utils.cc +++ b/cc/trees/draw_property_utils.cc
@@ -664,9 +664,12 @@ layer->clip_tree_index(), target_node->id); } -static gfx::RRectF GetRoundedCornerRRect(const PropertyTrees* property_trees, - int effect_tree_index, - bool for_render_surface) { +static std::pair<gfx::RRectF, bool> GetRoundedCornerRRect( + const PropertyTrees* property_trees, + int effect_tree_index, + bool for_render_surface) { + static const std::pair<gfx::RRectF, bool> kEmptyRoundedCornerInfo( + gfx::RRectF(), false); const EffectTree* effect_tree = &property_trees->effect_tree; const EffectNode* effect_node = effect_tree->Node(effect_tree_index); const int target_id = effect_node->target_id; @@ -674,7 +677,7 @@ // Return empty rrect if this node has a render surface but the function call // was made for a non render surface. if (effect_node->has_render_surface && !for_render_surface) - return gfx::RRectF(); + return kEmptyRoundedCornerInfo; // Traverse the parent chain up to the render target to find a node which has // a rounded corner bounds set. @@ -697,11 +700,11 @@ // While traversing up the parent chain we did not find any node with a // rounded corner. if (!node || !found_rounded_corner) - return gfx::RRectF(); + return kEmptyRoundedCornerInfo; gfx::Transform to_target; if (!property_trees->GetToTarget(node->transform_id, target_id, &to_target)) - return gfx::RRectF(); + return kEmptyRoundedCornerInfo; DCHECK(to_target.Preserves2dAxisAlignment()); @@ -712,14 +715,7 @@ bounds.Scale(scale.x(), scale.y()); bounds.Offset(translate); - return bounds; -} - -static bool IsFastRoundedCorner(const PropertyTrees* property_trees, - int effect_tree_index) { - const EffectTree* effect_tree = &property_trees->effect_tree; - const EffectNode* effect_node = effect_tree->Node(effect_tree_index); - return effect_node->is_fast_rounded_corner; + return std::make_pair(bounds, node->is_fast_rounded_corner); } static void UpdateRenderTarget(EffectTree* effect_tree) { @@ -955,11 +951,12 @@ layer, property_trees->transform_tree, property_trees->effect_tree); layer->draw_properties().screen_space_transform_is_animating = transform_node->to_screen_is_potentially_animated; - layer->draw_properties().rounded_corner_bounds = + auto rounded_corner_info = GetRoundedCornerRRect(property_trees, layer->effect_tree_index(), /*from_render_surface*/ false); + layer->draw_properties().rounded_corner_bounds = rounded_corner_info.first; layer->draw_properties().is_fast_rounded_corner = - IsFastRoundedCorner(property_trees, layer->effect_tree_index()); + rounded_corner_info.second; } // Compute effects and determine if render surfaces have contributing layers @@ -1033,7 +1030,8 @@ render_surface->SetRoundedCornerRRect( GetRoundedCornerRRect(property_trees, render_surface->EffectTreeIndex(), - /*for_render_surface*/ true)); + /*for_render_surface*/ true) + .first); render_surface->SetScreenSpaceTransform( property_trees->ToScreenSpaceTransformWithoutSurfaceContentsScale( render_surface->TransformTreeIndex(),
diff --git a/chrome/BUILD.gn b/chrome/BUILD.gn index ececd22..7e918a47 100644 --- a/chrome/BUILD.gn +++ b/chrome/BUILD.gn
@@ -1253,7 +1253,6 @@ ":packed_resources", ":swiftshader_library", ":widevine_cdm_library", - "//chrome/app/nibs:chrome_xibs", "//chrome/browser/resources/media/mei_preload:component_bundle", ]
diff --git a/chrome/android/BUILD.gn b/chrome/android/BUILD.gn index 06d07be..5441b73 100644 --- a/chrome/android/BUILD.gn +++ b/chrome/android/BUILD.gn
@@ -2043,6 +2043,7 @@ } enable_language_splits = enable_chrome_language_splits compress_shared_libraries = true + min_sdk_version = 21 if (modularize_vr) { extra_modules = [ { @@ -2069,8 +2070,10 @@ defined(invoker.use_trichrome_library) && invoker.use_trichrome_library if (_is_trichrome) { _bundle_name = "TrichromeChrome${invoker.bundle_suffix}" + _min_sdk_version = 28 } else { _bundle_name = "MonochromePublic${invoker.bundle_suffix}" + _min_sdk_version = 24 } monochrome_public_apk_or_module_tmpl(_base_module_target_name) { @@ -2141,6 +2144,7 @@ proguard_android_sdk_dep = webview_framework_dep } enable_language_splits = enable_chrome_language_splits + min_sdk_version = _min_sdk_version extra_modules = [] if (modularize_ar) {
diff --git a/chrome/android/features/autofill_assistant/java/src/org/chromium/chrome/browser/autofill_assistant/payment/AutofillAssistantPaymentRequest.java b/chrome/android/features/autofill_assistant/java/src/org/chromium/chrome/browser/autofill_assistant/payment/AutofillAssistantPaymentRequest.java index d3a52d7b..6d0e766 100644 --- a/chrome/android/features/autofill_assistant/java/src/org/chromium/chrome/browser/autofill_assistant/payment/AutofillAssistantPaymentRequest.java +++ b/chrome/android/features/autofill_assistant/java/src/org/chromium/chrome/browser/autofill_assistant/payment/AutofillAssistantPaymentRequest.java
@@ -112,8 +112,9 @@ mPaymentOptions = paymentOptions; mDelegate = delegate; - // This feature should only works in non-incognito mode. - mAddressEditor = new AddressEditor(/* emailFieldIncluded= */ true, /* saveToDisk= */ true); + // This feature should only work in non-incognito mode. + mAddressEditor = + new AddressEditor(AddressEditor.Purpose.AUTOFILL_ASSISTANT, /* saveToDisk= */ true); mCardEditor = new CardEditor(mWebContents, mAddressEditor, /* observerForTest= */ null); // Only enable 'basic-card' payment method.
diff --git a/chrome/android/features/tab_ui/java/src/org/chromium/chrome/browser/tasks/tab_management/GridTabSwitcherCoordinator.java b/chrome/android/features/tab_ui/java/src/org/chromium/chrome/browser/tasks/tab_management/GridTabSwitcherCoordinator.java index f0ee57a..11cf153e 100644 --- a/chrome/android/features/tab_ui/java/src/org/chromium/chrome/browser/tasks/tab_management/GridTabSwitcherCoordinator.java +++ b/chrome/android/features/tab_ui/java/src/org/chromium/chrome/browser/tasks/tab_management/GridTabSwitcherCoordinator.java
@@ -28,6 +28,7 @@ */ public class GridTabSwitcherCoordinator implements Destroyable, GridTabSwitcher, GridTabSwitcherMediator.ResetHandler { + private final static String COMPONENT_NAME = "GridTabSwitcher"; private final PropertyModelChangeProcessor mContainerViewChangeProcessor; private final ActivityLifecycleDispatcher mLifecycleDispatcher; private final TabListCoordinator mTabGridCoordinator; @@ -40,7 +41,7 @@ PropertyModel containerViewModel = new PropertyModel(TabListContainerProperties.ALL_KEYS); mTabGridCoordinator = new TabListCoordinator(TabListCoordinator.TabListMode.GRID, context, - tabModelSelector, tabContentManager, compositorViewHolder, true); + tabModelSelector, tabContentManager, compositorViewHolder, true, COMPONENT_NAME); mContainerViewChangeProcessor = PropertyModelChangeProcessor.create(containerViewModel, mTabGridCoordinator.getContainerView(), TabGridContainerViewBinder::bind);
diff --git a/chrome/android/features/tab_ui/java/src/org/chromium/chrome/browser/tasks/tab_management/GridTabSwitcherMediator.java b/chrome/android/features/tab_ui/java/src/org/chromium/chrome/browser/tasks/tab_management/GridTabSwitcherMediator.java index 47538a7..0233f896 100644 --- a/chrome/android/features/tab_ui/java/src/org/chromium/chrome/browser/tasks/tab_management/GridTabSwitcherMediator.java +++ b/chrome/android/features/tab_ui/java/src/org/chromium/chrome/browser/tasks/tab_management/GridTabSwitcherMediator.java
@@ -13,6 +13,7 @@ import static org.chromium.chrome.browser.tasks.tab_management.TabListContainerProperties.VISIBILITY_LISTENER; import org.chromium.base.ObserverList; +import org.chromium.base.metrics.RecordUserAction; import org.chromium.chrome.browser.compositor.layouts.OverviewModeController; import org.chromium.chrome.browser.fullscreen.ChromeFullscreenManager; import org.chromium.chrome.browser.fullscreen.FullscreenManager; @@ -137,6 +138,7 @@ - INITIAL_SCROLL_INDEX_OFFSET, 0); mContainerViewModel.set(INITIAL_SCROLL_INDEX, initialPosition); + RecordUserAction.record("MobileToolbarShowStackView"); } mContainerViewModel.set(IS_VISIBLE, isVisible);
diff --git a/chrome/android/features/tab_ui/java/src/org/chromium/chrome/browser/tasks/tab_management/TabGridSheetCoordinator.java b/chrome/android/features/tab_ui/java/src/org/chromium/chrome/browser/tasks/tab_management/TabGridSheetCoordinator.java index c2d91b5..3ee0443 100644 --- a/chrome/android/features/tab_ui/java/src/org/chromium/chrome/browser/tasks/tab_management/TabGridSheetCoordinator.java +++ b/chrome/android/features/tab_ui/java/src/org/chromium/chrome/browser/tasks/tab_management/TabGridSheetCoordinator.java
@@ -27,6 +27,7 @@ * objects. */ public class TabGridSheetCoordinator implements Destroyable { + public final static String COMPONENT_NAME = "TabGridSheet"; private final Context mContext; private final TabListCoordinator mTabGridCoordinator; private final TabGridSheetMediator mMediator; @@ -42,7 +43,8 @@ mToolbarPropertyModel = new PropertyModel(TabGridSheetProperties.ALL_KEYS); mTabGridCoordinator = new TabListCoordinator(TabListCoordinator.TabListMode.GRID, context, - tabModelSelector, tabContentManager, bottomSheetController.getBottomSheet(), false); + tabModelSelector, tabContentManager, bottomSheetController.getBottomSheet(), false, + COMPONENT_NAME); mMediator = new TabGridSheetMediator(mContext, bottomSheetController, this::resetWithListOfTabs,
diff --git a/chrome/android/features/tab_ui/java/src/org/chromium/chrome/browser/tasks/tab_management/TabGridSheetMediator.java b/chrome/android/features/tab_ui/java/src/org/chromium/chrome/browser/tasks/tab_management/TabGridSheetMediator.java index 7c0a453..7b48fd7 100644 --- a/chrome/android/features/tab_ui/java/src/org/chromium/chrome/browser/tasks/tab_management/TabGridSheetMediator.java +++ b/chrome/android/features/tab_ui/java/src/org/chromium/chrome/browser/tasks/tab_management/TabGridSheetMediator.java
@@ -8,6 +8,7 @@ import android.support.annotation.Nullable; import android.view.View.OnClickListener; +import org.chromium.base.metrics.RecordUserAction; import org.chromium.chrome.R; import org.chromium.chrome.browser.UrlConstants; import org.chromium.chrome.browser.lifecycle.Destroyable; @@ -67,6 +68,9 @@ mSheetObserver = new EmptyBottomSheetObserver() { @Override public void onSheetClosed(@StateChangeReason int reason) { + if (reason == StateChangeReason.SWIPE || reason == StateChangeReason.TAP_SCRIM) { + RecordUserAction.record("TabGroup.MinimizedFromGrid"); + } resetHandler.resetWithListOfTabs(null); } }; @@ -160,6 +164,7 @@ private OnClickListener getCollapseButtonClickListener() { return view -> { + RecordUserAction.record("TabGroup.MinimizedFromGrid"); hideTabGridSheet(); }; } @@ -177,6 +182,7 @@ mTabCreatorManager.getTabCreator(currentTab.isIncognito()) .createNewTab(new LoadUrlParams(UrlConstants.NTP_URL), TabLaunchType.FROM_CHROME_UI, parentTabToAttach); + RecordUserAction.record("MobileNewTabOpened." + TabGridSheetCoordinator.COMPONENT_NAME); }; } }
diff --git a/chrome/android/features/tab_ui/java/src/org/chromium/chrome/browser/tasks/tab_management/TabGroupUiCoordinator.java b/chrome/android/features/tab_ui/java/src/org/chromium/chrome/browser/tasks/tab_management/TabGroupUiCoordinator.java index aec8f45..5490d3e 100644 --- a/chrome/android/features/tab_ui/java/src/org/chromium/chrome/browser/tasks/tab_management/TabGroupUiCoordinator.java +++ b/chrome/android/features/tab_ui/java/src/org/chromium/chrome/browser/tasks/tab_management/TabGroupUiCoordinator.java
@@ -25,6 +25,7 @@ */ public class TabGroupUiCoordinator implements Destroyable, TabGroupUiMediator.ResetHandler, TabGroupUi { + public final static String COMPONENT_NAME = "TabStrip"; private final Context mContext; private final PropertyModel mTabStripToolbarModel; private TabGridSheetCoordinator mTabGridSheetCoordinator; @@ -55,7 +56,7 @@ TabContentManager tabContentManager = activity.getTabContentManager(); mTabStripCoordinator = new TabListCoordinator(TabListCoordinator.TabListMode.STRIP, mContext, tabModelSelector, tabContentManager, - mTabStripToolbarCoordinator.getTabListContainerView(), true); + mTabStripToolbarCoordinator.getTabListContainerView(), true, COMPONENT_NAME); mTabGridSheetCoordinator = new TabGridSheetCoordinator(mContext, activity.getBottomSheetController(), tabModelSelector, tabContentManager, activity);
diff --git a/chrome/android/features/tab_ui/java/src/org/chromium/chrome/browser/tasks/tab_management/TabGroupUiMediator.java b/chrome/android/features/tab_ui/java/src/org/chromium/chrome/browser/tasks/tab_management/TabGroupUiMediator.java index e5e2d36..118cc1e5 100644 --- a/chrome/android/features/tab_ui/java/src/org/chromium/chrome/browser/tasks/tab_management/TabGroupUiMediator.java +++ b/chrome/android/features/tab_ui/java/src/org/chromium/chrome/browser/tasks/tab_management/TabGroupUiMediator.java
@@ -4,6 +4,7 @@ package org.chromium.chrome.browser.tasks.tab_management; +import org.chromium.base.metrics.RecordUserAction; import org.chromium.chrome.browser.UrlConstants; import org.chromium.chrome.browser.compositor.layouts.EmptyOverviewModeObserver; import org.chromium.chrome.browser.compositor.layouts.OverviewModeBehavior; @@ -120,6 +121,7 @@ Tab currentTab = mTabModelSelector.getCurrentTab(); if (currentTab == null) return; mResetHandler.resetSheetWithListOfTabs(getRelatedTabsForId(currentTab.getId())); + RecordUserAction.record("TabGroup.ExpandedFromStrip"); }); mToolbarPropertyModel.set(TabStripToolbarViewProperties.ADD_CLICK_LISTENER, view -> { Tab currentTab = mTabModelSelector.getCurrentTab(); @@ -133,6 +135,7 @@ mTabCreatorManager.getTabCreator(currentTab.isIncognito()) .createNewTab(new LoadUrlParams(UrlConstants.NTP_URL), TabLaunchType.FROM_CHROME_UI, parentTabToAttach); + RecordUserAction.record("MobileNewTabOpened" + TabGroupUiCoordinator.COMPONENT_NAME); }); }
diff --git a/chrome/android/features/tab_ui/java/src/org/chromium/chrome/browser/tasks/tab_management/TabListCoordinator.java b/chrome/android/features/tab_ui/java/src/org/chromium/chrome/browser/tasks/tab_management/TabListCoordinator.java index 0593c718..0073f95 100644 --- a/chrome/android/features/tab_ui/java/src/org/chromium/chrome/browser/tasks/tab_management/TabListCoordinator.java +++ b/chrome/android/features/tab_ui/java/src/org/chromium/chrome/browser/tasks/tab_management/TabListCoordinator.java
@@ -50,9 +50,22 @@ private final TabListRecyclerView mRecyclerView; private final @TabListMode int mMode; + /** + * Construct a coordinator for UI that shows a list of tabs. + * @param mode Modes of showing the list of tabs. Can be used in GRID or STRIP. + * @param context The context to use for accessing {@link android.content.res.Resources}. + * @param tabModelSelector {@link TabModelSelector} that will provide and receive signals about + * the tabs concerned. + * @param tabContentManager {@link TabContentManager} to provide screenshot related details. + * @param parentView {@link ViewGroup} The root view of the UI. + * @param attachToParent Whether the UI should attach to root view. + * @param componentName A unique string uses to identify different components for UMA recording. + * Recommended to use the class name or make sure the string is unique + * through actions.xml file. + */ TabListCoordinator(@TabListMode int mode, Context context, TabModelSelector tabModelSelector, TabContentManager tabContentManager, @NonNull ViewGroup parentView, - boolean attachToParent) { + boolean attachToParent, String componentName) { TabListModel tabListModel = new TabListModel(); mMode = mode; @@ -95,7 +108,7 @@ mRecyclerView.setHasFixedSize(true); mMediator = new TabListMediator(Profile.getLastUsedProfile(), tabListModel, context, - tabModelSelector, tabContentManager, new FaviconHelper()); + tabModelSelector, tabContentManager, new FaviconHelper(), componentName); } /**
diff --git a/chrome/android/features/tab_ui/java/src/org/chromium/chrome/browser/tasks/tab_management/TabListMediator.java b/chrome/android/features/tab_ui/java/src/org/chromium/chrome/browser/tasks/tab_management/TabListMediator.java index 0e9a823..60c3dba5 100644 --- a/chrome/android/features/tab_ui/java/src/org/chromium/chrome/browser/tasks/tab_management/TabListMediator.java +++ b/chrome/android/features/tab_ui/java/src/org/chromium/chrome/browser/tasks/tab_management/TabListMediator.java
@@ -67,22 +67,46 @@ private final TabModelSelector mTabModelSelector; private final TabContentManager mTabContentManager; private final Profile mProfile; + private final String mComponentName; private final TabActionListener mTabSelectedListener = new TabActionListener() { @Override public void run(int tabId) { - int currentIndex = mTabModelSelector.getCurrentModel().index(); + Tab currentTab = mTabModelSelector.getCurrentTab(); + int newIndex = TabModelUtils.getTabIndexById(mTabModelSelector.getCurrentModel(), tabId); mTabModelSelector.getCurrentModel().setIndex(newIndex, TabSelectionType.FROM_USER); - if (newIndex == currentIndex) { - RecordUserAction.record("MobileTabReturnedToCurrentTab"); + Tab newlySelectedTab = mTabModelSelector.getCurrentTab(); + + if (currentTab == newlySelectedTab) { + RecordUserAction.record("MobileTabReturnedToCurrentTab." + mComponentName); } else { - RecordHistogram.recordSparseHistogram( - "Tabs.TabOffsetOfSwitch", currentIndex - newIndex); + recordTabOffsetOfSwitch(currentTab, newlySelectedTab); + RecordUserAction.record("MobileTabSwitched." + mComponentName); } } + private void recordTabOffsetOfSwitch(Tab fromTab, Tab toTab) { + assert fromTab != toTab; + + int fromIndex = mTabModelSelector.getTabModelFilterProvider() + .getCurrentTabModelFilter() + .indexOf(fromTab); + int toIndex = mTabModelSelector.getTabModelFilterProvider() + .getCurrentTabModelFilter() + .indexOf(toTab); + + if (fromIndex == toIndex) { + fromIndex = TabModelUtils.getTabIndexById( + mTabModelSelector.getCurrentModel(), fromTab.getId()); + toIndex = TabModelUtils.getTabIndexById( + mTabModelSelector.getCurrentModel(), toTab.getId()); + } + + RecordHistogram.recordSparseHistogram( + "Tabs.TabOffsetOfSwitch." + mComponentName, fromIndex - toIndex); + } }; private final TabActionListener mTabClosedListener = new TabActionListener() { @@ -91,7 +115,7 @@ mTabModelSelector.getCurrentModel().closeTab( TabModelUtils.getTabById(mTabModelSelector.getCurrentModel(), tabId), false, false, true); - RecordUserAction.record("MobileStackViewCloseTab"); + RecordUserAction.record("MobileTabClosed." + mComponentName); } }; @@ -126,10 +150,11 @@ * @param tabModelSelector {@link TabModelSelector} that will provide and receive signals about * the tabs concerned. * @param tabContentManager {@link TabContentManager} to provide screenshot related details. + * @param componentName This is a unique string to identify different components. */ public TabListMediator(Profile profile, TabListModel model, Context context, TabModelSelector tabModelSelector, TabContentManager tabContentManager, - FaviconHelper faviconHelper) { + FaviconHelper faviconHelper, String componentName) { mFaviconSize = context.getResources().getDimensionPixelSize(R.dimen.tab_grid_favicon_size); mTabModelSelector = tabModelSelector; @@ -137,6 +162,7 @@ mModel = model; mFaviconHelper = faviconHelper; mProfile = profile; + mComponentName = componentName; mTabModelObserver = new EmptyTabModelObserver() { @Override
diff --git a/chrome/android/features/tab_ui/junit/src/org/chromium/chrome/browser/tasks/tab_management/TabListMediatorUnitTest.java b/chrome/android/features/tab_ui/junit/src/org/chromium/chrome/browser/tasks/tab_management/TabListMediatorUnitTest.java index d17256f26..ed640e9 100644 --- a/chrome/android/features/tab_ui/junit/src/org/chromium/chrome/browser/tasks/tab_management/TabListMediatorUnitTest.java +++ b/chrome/android/features/tab_ui/junit/src/org/chromium/chrome/browser/tasks/tab_management/TabListMediatorUnitTest.java
@@ -128,8 +128,8 @@ doReturn(2).when(mTabModel).getCount(); mModel = new TabListModel(); - mMediator = new TabListMediator( - mProfile, mModel, mContext, mTabModelSelector, mTabContentManager, mFaviconHelper); + mMediator = new TabListMediator(mProfile, mModel, mContext, mTabModelSelector, + mTabContentManager, mFaviconHelper, getClass().getSimpleName()); } @After
diff --git a/chrome/android/java/monochrome_public_apk.proguard_flags.expected b/chrome/android/java/monochrome_public_apk.proguard_flags.expected index f6f3783..da7ab5c 100644 --- a/chrome/android/java/monochrome_public_apk.proguard_flags.expected +++ b/chrome/android/java/monochrome_public_apk.proguard_flags.expected
@@ -320,6 +320,27 @@ # picked up from the library APK at runtime. -dontwarn org.chromium.base.library_loader.NativeLibraries +# Let proguard know CastMediaOptions in CastOptions is always null, so it can +# trim unused MediaNotificationService methods. This saves about 170 methods in +# the dex file. https://crbug.com/855081 +-assumevalues class com.google.android.gms.cast.framework.CastOptions { + *** getCastMediaOptions() return null; +} + +# Also, because CastOptions creates a default CastMediaOptions object upon +# construction, we need to trim out the its builder as well, so we are truly +# assuming there's no CastMediaOptions instances anywhere. This is to avoid +# CastMediaOptions to reference resources upon construction. +-assumevalues class com.google.android.gms.cast.framework.media.CastMediaOptions$Builder { + *** build() return null; +} + +-assumenosideeffects class com.google.android.gms.cast.framework.media.CastMediaOptions$Builder { + public <init>(); + public <clinit>(); + *** build() return null; +} + ################################################################################ # ../../components/background_task_scheduler/android/proguard.flags ################################################################################ @@ -682,3 +703,10 @@ @com.google.vr.dynamite.client.UsedByReflection *; } + +################################################################################ +# Dynamically generated from build/android/gyp/proguard.py +################################################################################ +-assumevalues class android.os.Build$VERSION { + public static final int SDK_INT return 24..9999; +}
diff --git a/chrome/android/java/proguard.flags b/chrome/android/java/proguard.flags index 85dc2b5..54326db 100644 --- a/chrome/android/java/proguard.flags +++ b/chrome/android/java/proguard.flags
@@ -36,3 +36,24 @@ # Trichrome builds don't include a native library list in the main APK; it's # picked up from the library APK at runtime. -dontwarn org.chromium.base.library_loader.NativeLibraries + +# Let proguard know CastMediaOptions in CastOptions is always null, so it can +# trim unused MediaNotificationService methods. This saves about 170 methods in +# the dex file. https://crbug.com/855081 +-assumevalues class com.google.android.gms.cast.framework.CastOptions { + *** getCastMediaOptions() return null; +} + +# Also, because CastOptions creates a default CastMediaOptions object upon +# construction, we need to trim out the its builder as well, so we are truly +# assuming there's no CastMediaOptions instances anywhere. This is to avoid +# CastMediaOptions to reference resources upon construction. +-assumevalues class com.google.android.gms.cast.framework.media.CastMediaOptions$Builder { + *** build() return null; +} + +-assumenosideeffects class com.google.android.gms.cast.framework.media.CastMediaOptions$Builder { + public <init>(); + public <clinit>(); + *** build() return null; +}
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/AppHooks.java b/chrome/android/java/src/org/chromium/chrome/browser/AppHooks.java index 06acb00c..0d699fe 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/AppHooks.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/AppHooks.java
@@ -54,6 +54,7 @@ import org.chromium.chrome.browser.tab.AuthenticatorNavigationInterceptor; import org.chromium.chrome.browser.tab.Tab; import org.chromium.chrome.browser.touchless.TouchlessUiController; +import org.chromium.chrome.browser.usage_stats.DigitalWellbeingClient; import org.chromium.chrome.browser.webapps.GooglePlayWebApkInstallDelegate; import org.chromium.chrome.browser.webauth.Fido2ApiHandler; import org.chromium.chrome.browser.widget.FeatureHighlightProvider; @@ -368,6 +369,13 @@ } /** + * @return A new {@link DigitalWellbeingClient} instance. + */ + public DigitalWellbeingClient createDigitalWellbeingClient() { + return new DigitalWellbeingClient(); + } + + /** * @param activity An activity for access to different features. * @return A new {@link TouchlessUiController} instance. */
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/NavigationPopup.java b/chrome/android/java/src/org/chromium/chrome/browser/NavigationPopup.java index 6f5cf55..b09940e 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/NavigationPopup.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/NavigationPopup.java
@@ -100,7 +100,7 @@ mHistory = mNavigationController.getDirectedNavigationHistory( isForward, MAXIMUM_HISTORY_ITEMS); mHistory.addEntry(new NavigationEntry(FULL_HISTORY_ENTRY_INDEX, UrlConstants.HISTORY_URL, - null, null, null, resources.getString(R.string.show_full_history), null, 0)); + null, null, null, resources.getString(R.string.show_full_history), null, 0, 0)); mAdapter = new NavigationAdapter();
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/browserservices/BrowserSessionContentHandler.java b/chrome/android/java/src/org/chromium/chrome/browser/browserservices/BrowserSessionContentHandler.java index 282881e..f3d1e21 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/browserservices/BrowserSessionContentHandler.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/browserservices/BrowserSessionContentHandler.java
@@ -64,11 +64,6 @@ @Nullable String getPendingUrl(); /** - * Triggers sharing of currently shown webpage similarly to the "Share" menu action. - */ - void triggerSharingFlow(); - - /** * @return the task id the content handler is running in. */ int getTaskId();
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/browserservices/BrowserSessionContentUtils.java b/chrome/android/java/src/org/chromium/chrome/browser/browserservices/BrowserSessionContentUtils.java index 4acce6c6..e1e3204 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/browserservices/BrowserSessionContentUtils.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/browserservices/BrowserSessionContentUtils.java
@@ -42,16 +42,9 @@ @Nullable private static BrowserSessionContentHandler sActiveContentHandler; - @Nullable private static Callback<CustomTabsSessionToken> sSessionDisconnectCallback; - /** Extra that is passed to intent to trigger a certain action within a running activity. */ - private static final String EXTRA_INTERNAL_ACTION = - "org.chromium.chrome.extra.EXTRA_INTERNAL_ACTION"; - private static final String INTERNAL_ACTION_SHARE = - "org.chromium.chrome.action.INTERNAL_ACTION_SHARE"; - /** * Sets the currently active {@link BrowserSessionContentHandler} in focus. * @param contentHandler {@link BrowserSessionContentHandler} to set. @@ -105,21 +98,7 @@ if (TextUtils.isEmpty(url)) return false; CustomTabsSessionToken session = CustomTabsSessionToken.getSessionTokenFromIntent(intent); - return handleInternalIntent(intent, session) || handleExternalIntent(intent, url, session); - - } - - private static boolean handleInternalIntent(Intent intent, - @Nullable CustomTabsSessionToken session) { - if (!IntentHandler.wasIntentSenderChrome(intent)) return false; - if (!sessionMatchesActiveContent(session)) return false; - - String internalAction = intent.getStringExtra(EXTRA_INTERNAL_ACTION); - if (INTERNAL_ACTION_SHARE.equals(internalAction)) { - sActiveContentHandler.triggerSharingFlow(); - return true; - } - return false; + return handleExternalIntent(intent, url, session); } private static boolean handleExternalIntent(Intent intent, String url, @@ -226,17 +205,6 @@ return sActiveContentHandler.updateRemoteViews(remoteViews, clickableIDs, pendingIntent); } - /** - * Creates a share intent to be triggered in currently running activity. - * @param originalIntent - intent with which the activity was launched. - */ - public static Intent createShareIntent(Context context, Intent originalIntent) { - Intent intent = new Intent(originalIntent) - .putExtra(EXTRA_INTERNAL_ACTION, INTERNAL_ACTION_SHARE); - IntentHandler.addTrustedIntentExtras(intent); - return intent; - } - private static void ensureSessionCleanUpOnDisconnects() { if (sSessionDisconnectCallback != null) return; sSessionDisconnectCallback = (session) -> {
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/browserservices/trustedwebactivityui/TrustedWebActivityModel.java b/chrome/android/java/src/org/chromium/chrome/browser/browserservices/trustedwebactivityui/TrustedWebActivityModel.java index 742dc3aa..b333a5ea 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/browserservices/trustedwebactivityui/TrustedWebActivityModel.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/browserservices/trustedwebactivityui/TrustedWebActivityModel.java
@@ -30,17 +30,6 @@ public static final int DISCLOSURE_STATE_SHOWN = 1; public static final int DISCLOSURE_STATE_DISMISSED_BY_USER = 2; - /** Tag to use for showing and dismissing a persistent notification. */ - public static final WritableObjectPropertyKey<String> - PERSISTENT_NOTIFICATION_TAG = new WritableObjectPropertyKey<>(); - - /** - * Data for building a persistent notification when it needs to be shown. - * Null when it needs to be hidden. - */ - public static final WritableObjectPropertyKey<PersistentNotificationData> - PERSISTENT_NOTIFICATION = new WritableObjectPropertyKey<>(); - /** Callback for routing disclosure-related view events back to controller side. */ public static final WritableObjectPropertyKey<DisclosureEventsCallback> DISCLOSURE_EVENTS_CALLBACK = new WritableObjectPropertyKey<>(); @@ -64,7 +53,6 @@ @Inject public TrustedWebActivityModel() { - super(TOOLBAR_HIDDEN, DISCLOSURE_STATE, PERSISTENT_NOTIFICATION, - PERSISTENT_NOTIFICATION_TAG, DISCLOSURE_EVENTS_CALLBACK); + super(TOOLBAR_HIDDEN, DISCLOSURE_STATE, DISCLOSURE_EVENTS_CALLBACK); } }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/browserservices/trustedwebactivityui/controller/PersistentNotificationController.java b/chrome/android/java/src/org/chromium/chrome/browser/browserservices/trustedwebactivityui/controller/PersistentNotificationController.java deleted file mode 100644 index 322fa648..0000000 --- a/chrome/android/java/src/org/chromium/chrome/browser/browserservices/trustedwebactivityui/controller/PersistentNotificationController.java +++ /dev/null
@@ -1,97 +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. - -package org.chromium.chrome.browser.browserservices.trustedwebactivityui.controller; - -import static org.chromium.chrome.browser.browserservices.trustedwebactivityui.TrustedWebActivityModel.PERSISTENT_NOTIFICATION; -import static org.chromium.chrome.browser.browserservices.trustedwebactivityui.TrustedWebActivityModel.PERSISTENT_NOTIFICATION_TAG; - -import android.os.Handler; -import android.support.annotation.Nullable; - -import org.chromium.chrome.browser.browserservices.Origin; -import org.chromium.chrome.browser.browserservices.trustedwebactivityui.TrustedWebActivityModel; -import org.chromium.chrome.browser.browserservices.trustedwebactivityui.TrustedWebActivityModel.PersistentNotificationData; -import org.chromium.chrome.browser.browserservices.trustedwebactivityui.controller.TrustedWebActivityVerifier.VerificationState; -import org.chromium.chrome.browser.customtabs.CustomTabIntentDataProvider; -import org.chromium.chrome.browser.dependency_injection.ActivityScope; -import org.chromium.chrome.browser.init.ActivityLifecycleDispatcher; -import org.chromium.chrome.browser.lifecycle.StartStopWithNativeObserver; - -import javax.inject.Inject; - -/** - * Controls when the TWA persistent notification should be shown or hidden. - * The notification is shown while the activity is in started state. It is not removed when the user - * leaves the origin associated with the app by following links. - */ -@ActivityScope -public class PersistentNotificationController implements StartStopWithNativeObserver { - private final CustomTabIntentDataProvider mIntentDataProvider; - private final TrustedWebActivityModel mModel; - private final TrustedWebActivityVerifier mVerifier; - - private boolean mStarted; - - // Origin for which the notification is currently shown. Null when notification not shown. - @Nullable - private Origin mLastVerifiedOrigin; - - @Nullable - private Handler mHandler; - - @Inject - public PersistentNotificationController(ActivityLifecycleDispatcher lifecycleDispatcher, - CustomTabIntentDataProvider intentDataProvider, - TrustedWebActivityModel model, - TrustedWebActivityVerifier verifier) { - mIntentDataProvider = intentDataProvider; - mModel = model; - mVerifier = verifier; - lifecycleDispatcher.register(this); - mVerifier.addVerificationObserver(this::onVerificationStateChanged); - mModel.set(PERSISTENT_NOTIFICATION_TAG, mVerifier.getClientPackageName()); - } - - private void onVerificationStateChanged() { - VerificationState state = mVerifier.getState(); - if (state == null) { - return; - } - if (state.status == TrustedWebActivityVerifier.VerificationStatus.FAILURE) { - return; // Keep showing the notification despite we've left the verified origin - } - if (state.origin.equals(mLastVerifiedOrigin)) { - return; - } - mLastVerifiedOrigin = state.origin; - if (mStarted) { - show(); - } - } - - @Override - public void onStartWithNative() { - mStarted = true; - if (mLastVerifiedOrigin != null) { - show(); - } - } - - @Override - public void onStopWithNative() { - mStarted = false; - hide(); - } - - private void show() { - assert mLastVerifiedOrigin != null; - mModel.set(PERSISTENT_NOTIFICATION, new PersistentNotificationData( - mIntentDataProvider.getIntent(), mLastVerifiedOrigin)); - } - - private void hide() { - mModel.set(PERSISTENT_NOTIFICATION, null); - } -}
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/browserservices/trustedwebactivityui/view/PersistentNotificationView.java b/chrome/android/java/src/org/chromium/chrome/browser/browserservices/trustedwebactivityui/view/PersistentNotificationView.java deleted file mode 100644 index 6c3058a..0000000 --- a/chrome/android/java/src/org/chromium/chrome/browser/browserservices/trustedwebactivityui/view/PersistentNotificationView.java +++ /dev/null
@@ -1,197 +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. - -package org.chromium.chrome.browser.browserservices.trustedwebactivityui.view; - -import static android.app.PendingIntent.FLAG_UPDATE_CURRENT; - -import static org.chromium.chrome.browser.browserservices.trustedwebactivityui.TrustedWebActivityModel.PERSISTENT_NOTIFICATION; -import static org.chromium.chrome.browser.browserservices.trustedwebactivityui.TrustedWebActivityModel.PERSISTENT_NOTIFICATION_TAG; -import static org.chromium.chrome.browser.dependency_injection.ChromeCommonQualifiers.APP_CONTEXT; -import static org.chromium.chrome.browser.notifications.NotificationConstants.NOTIFICATION_ID_TWA_PERSISTENT; - -import android.app.Notification; -import android.app.NotificationManager; -import android.app.PendingIntent; -import android.content.Context; -import android.content.Intent; -import android.content.pm.PackageManager; -import android.os.Build; -import android.os.Handler; -import android.os.HandlerThread; -import android.os.Looper; -import android.support.annotation.Nullable; -import android.support.v4.app.NotificationCompat; - -import org.chromium.chrome.R; -import org.chromium.chrome.browser.browserservices.BrowserSessionContentUtils; -import org.chromium.chrome.browser.browserservices.Origin; -import org.chromium.chrome.browser.browserservices.trustedwebactivityui.TrustedWebActivityModel; -import org.chromium.chrome.browser.browserservices.trustedwebactivityui.TrustedWebActivityModel.PersistentNotificationData; -import org.chromium.chrome.browser.dependency_injection.ActivityScope; -import org.chromium.chrome.browser.init.ActivityLifecycleDispatcher; -import org.chromium.chrome.browser.lifecycle.Destroyable; -import org.chromium.chrome.browser.notifications.NotificationBuilderFactory; -import org.chromium.chrome.browser.notifications.channels.ChannelDefinitions; -import org.chromium.chrome.browser.preferences.PreferencesLauncher; -import org.chromium.chrome.browser.preferences.website.SettingsNavigationSource; -import org.chromium.ui.modelutil.PropertyKey; -import org.chromium.ui.modelutil.PropertyObservable; -import org.chromium.ui.modelutil.PropertyObservable.PropertyObserver; - -import javax.inject.Inject; -import javax.inject.Named; - -/** - * Publishes and dismisses the TWA persistent notification. - */ -@ActivityScope -public class PersistentNotificationView implements Destroyable, PropertyObserver<PropertyKey> { - private final Context mAppContext; - private final TrustedWebActivityModel mModel; - - @Nullable - private Handler mHandler; - - @Inject - public PersistentNotificationView(@Named(APP_CONTEXT) Context context, - ActivityLifecycleDispatcher lifecycleDispatcher, - TrustedWebActivityModel model) { - mAppContext = context; - mModel = model; - lifecycleDispatcher.register(this); - model.addObserver(this); - } - - @Override - public void onPropertyChanged(PropertyObservable<PropertyKey> source, - @Nullable PropertyKey propertyKey) { - if (propertyKey != PERSISTENT_NOTIFICATION) return; - - PersistentNotificationData data = mModel.get(PERSISTENT_NOTIFICATION); - String tag = mModel.get(PERSISTENT_NOTIFICATION_TAG); - Runnable task; - if (data == null) { - task = new DismissTask(mAppContext, tag); - } else { - task = new PublishTask(tag, data.origin, - mAppContext, data.customTabActivityIntent); - } - postToBackgroundThread(task); - } - - @Override - public void destroy() { - killBackgroundThread(); - } - - private void postToBackgroundThread(Runnable task) { - if (mHandler == null) { - HandlerThread backgroundThread = new HandlerThread("TwaPersistentNotification"); - backgroundThread.start(); - mHandler = new Handler(backgroundThread.getLooper()); - } - mHandler.post(task); - } - - private void killBackgroundThread() { - if (mHandler == null) { - return; - } - Looper looper = mHandler.getLooper(); - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) { - looper.quitSafely(); - } else { - looper.quit(); - } - } - - private static class PublishTask implements Runnable { - private final String mPackageName; - private final Origin mOrigin; - private final Context mAppContext; - private final Intent mCustomTabsIntent; - - private PublishTask(String packageName, Origin origin, Context appContext, - Intent customTabsIntent) { - mPackageName = packageName; - mOrigin = origin; - mAppContext = appContext; - mCustomTabsIntent = customTabsIntent; - } - - @Override - public void run() { - Notification notification = createNotification(); - NotificationManager nm = (NotificationManager) mAppContext.getSystemService( - Context.NOTIFICATION_SERVICE); - if (nm != null) { - nm.notify(mPackageName, NOTIFICATION_ID_TWA_PERSISTENT, notification); - } - } - - private Notification createNotification() { - return NotificationBuilderFactory - .createChromeNotificationBuilder(true /* preferCompat */, - ChannelDefinitions.ChannelId.BROWSER) - .setSmallIcon(R.drawable.ic_chrome) - .setContentTitle(makeTitle()) - .setContentText( - mAppContext.getString(R.string.app_running_in_chrome_disclosure)) - .setAutoCancel(false) - .setOngoing(true) - .setPriorityBeforeO(NotificationCompat.PRIORITY_LOW) - .addAction(0 /* icon */, // TODO(pshmakov): set the icons. - mAppContext.getString(R.string.share), - makeShareIntent()) - .addAction(0 /* icon */, - mAppContext.getString(R.string.twa_manage_data), - makeManageDataIntent()) - .build(); - } - - private String makeTitle() { - PackageManager packageManager = mAppContext.getPackageManager(); - try { - return packageManager - .getApplicationLabel(packageManager.getApplicationInfo(mPackageName, 0)) - .toString(); - } catch (PackageManager.NameNotFoundException e) { - assert false : mPackageName + " not found"; - return ""; - } - } - - private PendingIntent makeManageDataIntent() { - Intent settingsIntent = PreferencesLauncher.createIntentForSingleWebsitePreferences( - mAppContext, mOrigin.toString(), SettingsNavigationSource.OTHER); - return PendingIntent.getActivity(mAppContext, 0, settingsIntent, FLAG_UPDATE_CURRENT); - } - - private PendingIntent makeShareIntent() { - Intent shareIntent = - BrowserSessionContentUtils.createShareIntent(mAppContext, mCustomTabsIntent); - return PendingIntent.getActivity(mAppContext, 0, shareIntent, FLAG_UPDATE_CURRENT); - } - } - - private static class DismissTask implements Runnable { - private final Context mAppContext; - private final String mPackageName; - - private DismissTask(Context appContext, String packageName) { - mAppContext = appContext; - mPackageName = packageName; - } - - @Override - public void run() { - NotificationManager nm = (NotificationManager) mAppContext.getSystemService( - Context.NOTIFICATION_SERVICE); - if (nm != null) { - nm.cancel(mPackageName, NOTIFICATION_ID_TWA_PERSISTENT); - } - } - } -}
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/contextual_suggestions/ContextualSuggestionsEnabledStateUtils.java b/chrome/android/java/src/org/chromium/chrome/browser/contextual_suggestions/ContextualSuggestionsEnabledStateUtils.java index f5018e3..09efb288 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/contextual_suggestions/ContextualSuggestionsEnabledStateUtils.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/contextual_suggestions/ContextualSuggestionsEnabledStateUtils.java
@@ -10,7 +10,7 @@ import org.chromium.chrome.browser.preferences.Pref; import org.chromium.chrome.browser.preferences.PrefServiceBridge; import org.chromium.chrome.browser.search_engines.TemplateUrlService; -import org.chromium.chrome.browser.sync.ProfileSyncService; +import org.chromium.chrome.browser.signin.UnifiedConsentServiceBridge; import org.chromium.components.signin.ChromeSigninController; /** Utility functions related to enabled state of Contextual Suggestions. */ @@ -28,8 +28,7 @@ static boolean getSettingsEnabled() { return isDSEConditionMet() && !ContextualSuggestionsBridge.isDisabledByEnterprisePolicy() && ChromeSigninController.get().isSignedIn() - && (ProfileSyncService.get().isUrlKeyedDataCollectionEnabled(false) - || ProfileSyncService.get().isUrlKeyedDataCollectionEnabled(true)); + && UnifiedConsentServiceBridge.isUrlKeyedAnonymizedDataCollectionEnabled(); } /** @return Whether the state is currently enabled. */
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/customtabs/CustomTabActivity.java b/chrome/android/java/src/org/chromium/chrome/browser/customtabs/CustomTabActivity.java index f3287f06..b766af5d 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/customtabs/CustomTabActivity.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/customtabs/CustomTabActivity.java
@@ -8,7 +8,6 @@ import android.app.PendingIntent; import android.content.Context; import android.content.Intent; -import android.content.SharedPreferences; import android.graphics.Bitmap; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; @@ -49,7 +48,6 @@ import org.chromium.chrome.browser.ChromeFeatureList; import org.chromium.chrome.browser.ChromeSwitches; import org.chromium.chrome.browser.IntentHandler; -import org.chromium.chrome.browser.IntentHandler.ExternalAppId; import org.chromium.chrome.browser.KeyboardShortcuts; import org.chromium.chrome.browser.LaunchIntentDispatcher; import org.chromium.chrome.browser.appmenu.AppMenuPropertiesDelegate; @@ -73,8 +71,6 @@ import org.chromium.chrome.browser.net.spdyproxy.DataReductionProxySettings; import org.chromium.chrome.browser.night_mode.NightModeStateProvider; import org.chromium.chrome.browser.page_info.PageInfoController; -import org.chromium.chrome.browser.rappor.RapporServiceBridge; -import org.chromium.chrome.browser.share.ShareMenuActionHandler; import org.chromium.chrome.browser.tab.EmptyTabObserver; import org.chromium.chrome.browser.tab.Tab; import org.chromium.chrome.browser.tabmodel.ChromeTabCreator; @@ -84,7 +80,6 @@ import org.chromium.chrome.browser.toolbar.top.ToolbarControlContainer; import org.chromium.chrome.browser.util.ColorUtils; import org.chromium.chrome.browser.util.IntentUtils; -import org.chromium.chrome.browser.webapps.WebappCustomTabTimeSpentLogger; import org.chromium.components.dom_distiller.core.DomDistillerUrlUtils; import org.chromium.content_public.browser.LoadUrlParams; import org.chromium.content_public.browser.NavigationController; @@ -101,7 +96,6 @@ */ public class CustomTabActivity extends ChromeActivity<CustomTabActivityComponent> { private static final String TAG = "CustomTabActivity"; - private static final String LAST_URL_PREF = "pref_last_custom_tab_url"; // For CustomTabs.WebContentsStateOnLaunch, see histograms.xml. Append only. @IntDef({WebContentsState.NO_WEBCONTENTS, WebContentsState.PRERENDERED_WEBCONTENTS, @@ -141,8 +135,6 @@ // change the package name. private boolean mShouldOverridePackage; - private boolean mIsInitialResume = true; - /** Adds and removes observers from tabs when needed. */ private TabObserverRegistrar mTabObserverRegistrar; @@ -151,8 +143,6 @@ private final CustomTabsConnection mConnection = CustomTabsConnection.getInstance(); - private WebappCustomTabTimeSpentLogger mWebappTimeSpentLogger; - @Nullable private DynamicModuleCoordinator mDynamicModuleCoordinator; @@ -423,18 +413,11 @@ } @Override - public void triggerSharingFlow() { - ShareMenuActionHandler.getInstance().onShareMenuItemSelected(CustomTabActivity.this, - getActivityTab(), false /* shareDirectly */, false /* isIncognito */); - } - - @Override public int getTaskId() { return CustomTabActivity.this.getTaskId(); } }; - recordClientPackageName(); mConnection.showSignInToastIfNecessary(mSession, getIntent()); if (ChromeFeatureList.isEnabled(ChromeFeatureList.AUTOFILL_ASSISTANT) @@ -551,19 +534,6 @@ mBottomBarDelegate.addOverlayPanelManagerObserver(); } - private void recordClientPackageName() { - String clientName = mConnection.getClientPackageNameForSession(mSession); - if (TextUtils.isEmpty(clientName)) clientName = mIntentDataProvider.getClientPackageName(); - final String packageName = clientName; - if (TextUtils.isEmpty(packageName) || packageName.contains(getPackageName())) return; - PostTask.runOrPostTask(UiThreadTaskTraits.DEFAULT, () -> { - RapporServiceBridge.sampleString("CustomTabs.ServiceClient.PackageName", packageName); - if (GSAState.isGsaPackageName(packageName)) return; - RapporServiceBridge.sampleString( - "CustomTabs.ServiceClient.PackageNameThirdParty", packageName); - }); - } - @Override public void onStartWithNative() { super.onStartWithNative(); @@ -572,51 +542,6 @@ } @Override - public void onResumeWithNative() { - super.onResumeWithNative(); - - if (getSavedInstanceState() != null || !mIsInitialResume) { - if (mIntentDataProvider.isOpenedByChrome()) { - RecordUserAction.record("ChromeGeneratedCustomTab.StartedReopened"); - } else { - RecordUserAction.record("CustomTabs.StartedReopened"); - } - } else { - SharedPreferences preferences = ContextUtils.getAppSharedPreferences(); - String lastUrl = preferences.getString(LAST_URL_PREF, null); - String urlToLoad = mIntentDataProvider.getUrlToLoad(); - if (lastUrl != null && lastUrl.equals(urlToLoad)) { - RecordUserAction.record("CustomTabsMenuOpenSameUrl"); - } else { - preferences.edit().putString(LAST_URL_PREF, urlToLoad).apply(); - } - - if (mIntentDataProvider.isOpenedByChrome()) { - RecordUserAction.record("ChromeGeneratedCustomTab.StartedInitially"); - } else { - @ExternalAppId - int externalId = IntentHandler.determineExternalIntentSource(getIntent()); - RecordHistogram.recordEnumeratedHistogram( - "CustomTabs.ClientAppId", externalId, ExternalAppId.NUM_ENTRIES); - - RecordUserAction.record("CustomTabs.StartedInitially"); - } - } - mIsInitialResume = false; - mWebappTimeSpentLogger = WebappCustomTabTimeSpentLogger.createInstanceAndStartTimer( - getIntent().getIntExtra(CustomTabIntentDataProvider.EXTRA_BROWSER_LAUNCH_SOURCE, - CustomTabIntentDataProvider.LaunchSourceType.OTHER)); - } - - @Override - public void onPauseWithNative() { - super.onPauseWithNative(); - if (mWebappTimeSpentLogger != null) { - mWebappTimeSpentLogger.onPause(); - } - } - - @Override public void onStopWithNative() { super.onStopWithNative(); BrowserSessionContentUtils.removeActiveContentHandler(mBrowserSessionContentHandler); @@ -1083,6 +1008,7 @@ mTabObserverRegistrar = component.resolveTabObserverRegistrar(); mTabController = component.resolveTabController(); mTabFactory = component.resolveTabFactory(); + component.resolveUmaTracker(); if (mIntentDataProvider.isTrustedWebActivity()) { component.resolveTrustedWebActivityCoordinator();
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/customtabs/CustomTabActivityLifecycleUmaTracker.java b/chrome/android/java/src/org/chromium/chrome/browser/customtabs/CustomTabActivityLifecycleUmaTracker.java new file mode 100644 index 0000000..159b31b --- /dev/null +++ b/chrome/android/java/src/org/chromium/chrome/browser/customtabs/CustomTabActivityLifecycleUmaTracker.java
@@ -0,0 +1,115 @@ +// 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.customtabs; + +import android.content.SharedPreferences; +import android.text.TextUtils; + +import org.chromium.base.ContextUtils; +import org.chromium.base.metrics.RecordHistogram; +import org.chromium.base.metrics.RecordUserAction; +import org.chromium.base.task.PostTask; +import org.chromium.chrome.browser.ChromeActivity; +import org.chromium.chrome.browser.IntentHandler; +import org.chromium.chrome.browser.dependency_injection.ActivityScope; +import org.chromium.chrome.browser.gsa.GSAState; +import org.chromium.chrome.browser.init.ActivityLifecycleDispatcher; +import org.chromium.chrome.browser.lifecycle.NativeInitObserver; +import org.chromium.chrome.browser.lifecycle.PauseResumeWithNativeObserver; +import org.chromium.chrome.browser.rappor.RapporServiceBridge; +import org.chromium.chrome.browser.webapps.WebappCustomTabTimeSpentLogger; +import org.chromium.content_public.browser.UiThreadTaskTraits; + +import javax.inject.Inject; + +/** + * Handles recording User Metrics for Custom Tab Activity. + */ +@ActivityScope +public class CustomTabActivityLifecycleUmaTracker implements PauseResumeWithNativeObserver, + NativeInitObserver { + private static final String LAST_URL_PREF = "pref_last_custom_tab_url"; + + private final CustomTabIntentDataProvider mIntentDataProvider; + private final ChromeActivity mActivity; + private final CustomTabsConnection mConnection; + + private WebappCustomTabTimeSpentLogger mWebappTimeSpentLogger; + private boolean mIsInitialResume = true; + + @Inject + public CustomTabActivityLifecycleUmaTracker(ActivityLifecycleDispatcher lifecycleDispatcher, + ChromeActivity activity, CustomTabIntentDataProvider intentDataProvider, + CustomTabsConnection customTabsConnection) { + mIntentDataProvider = intentDataProvider; + mActivity = activity; + mConnection = customTabsConnection; + + lifecycleDispatcher.register(this); + } + + @Override + public void onResumeWithNative() { + if (mActivity.getSavedInstanceState() != null || !mIsInitialResume) { + if (mIntentDataProvider.isOpenedByChrome()) { + RecordUserAction.record("ChromeGeneratedCustomTab.StartedReopened"); + } else { + RecordUserAction.record("CustomTabs.StartedReopened"); + } + } else { + SharedPreferences preferences = ContextUtils.getAppSharedPreferences(); + String lastUrl = preferences.getString(LAST_URL_PREF, null); + String urlToLoad = mIntentDataProvider.getUrlToLoad(); + if (lastUrl != null && lastUrl.equals(urlToLoad)) { + RecordUserAction.record("CustomTabsMenuOpenSameUrl"); + } else { + preferences.edit().putString(LAST_URL_PREF, urlToLoad).apply(); + } + + if (mIntentDataProvider.isOpenedByChrome()) { + RecordUserAction.record("ChromeGeneratedCustomTab.StartedInitially"); + } else { + @IntentHandler.ExternalAppId + int externalId = IntentHandler + .determineExternalIntentSource(mIntentDataProvider.getIntent()); + RecordHistogram.recordEnumeratedHistogram("CustomTabs.ClientAppId", + externalId, IntentHandler.ExternalAppId.NUM_ENTRIES); + + RecordUserAction.record("CustomTabs.StartedInitially"); + } + } + mIsInitialResume = false; + + mWebappTimeSpentLogger = WebappCustomTabTimeSpentLogger.createInstanceAndStartTimer( + mIntentDataProvider.getIntent().getIntExtra( + CustomTabIntentDataProvider.EXTRA_BROWSER_LAUNCH_SOURCE, + CustomTabIntentDataProvider.LaunchSourceType.OTHER)); + } + + @Override + public void onPauseWithNative() { + if (mWebappTimeSpentLogger != null) { + mWebappTimeSpentLogger.onPause(); + } + } + + @Override + public void onFinishNativeInitialization() { + String clientName = + mConnection.getClientPackageNameForSession(mIntentDataProvider.getSession()); + if (TextUtils.isEmpty(clientName)) clientName = mIntentDataProvider.getClientPackageName(); + final String packageName = clientName; + if (TextUtils.isEmpty(packageName) || packageName.contains(mActivity.getPackageName())) { + return; + } + + PostTask.postTask(UiThreadTaskTraits.DEFAULT, () -> { + RapporServiceBridge.sampleString("CustomTabs.ServiceClient.PackageName", packageName); + if (GSAState.isGsaPackageName(packageName)) return; + RapporServiceBridge.sampleString( + "CustomTabs.ServiceClient.PackageNameThirdParty", packageName); + }); + } +}
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/customtabs/dependency_injection/CustomTabActivityComponent.java b/chrome/android/java/src/org/chromium/chrome/browser/customtabs/dependency_injection/CustomTabActivityComponent.java index b85d4928..75507b5 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/customtabs/dependency_injection/CustomTabActivityComponent.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/customtabs/dependency_injection/CustomTabActivityComponent.java
@@ -7,6 +7,7 @@ import org.chromium.chrome.browser.browserservices.trustedwebactivityui.TrustedWebActivityCoordinator; import org.chromium.chrome.browser.contextual_suggestions.ContextualSuggestionsModule; import org.chromium.chrome.browser.customtabs.CloseButtonNavigator; +import org.chromium.chrome.browser.customtabs.CustomTabActivityLifecycleUmaTracker; import org.chromium.chrome.browser.customtabs.CustomTabBottomBarDelegate; import org.chromium.chrome.browser.customtabs.CustomTabTabPersistencePolicy; import org.chromium.chrome.browser.customtabs.CustomTabTopBarDelegate; @@ -39,6 +40,7 @@ CustomTabBottomBarDelegate resolveBottomBarDelegate(); CustomTabActivityTabController resolveTabController(); CustomTabActivityTabFactory resolveTabFactory(); + CustomTabActivityLifecycleUmaTracker resolveUmaTracker(); CustomTabTabPersistencePolicy resolveTabPersistencePolicy(); // For testing }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/download/DownloadUtils.java b/chrome/android/java/src/org/chromium/chrome/browser/download/DownloadUtils.java index 53672ab..506ac6b 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/download/DownloadUtils.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/download/DownloadUtils.java
@@ -687,6 +687,17 @@ } } + @CalledByNative + private static void openDownload(String filePath, String mimeType, String downloadGuid, + boolean isOffTheRecord, String originalUrl, String referer, + @DownloadMetrics.DownloadOpenSource int source) { + boolean canOpen = DownloadUtils.openFile( + filePath, mimeType, downloadGuid, isOffTheRecord, originalUrl, referer, source); + if (!canOpen) { + DownloadUtils.showDownloadManager(null, null); + } + } + private static void recordShareHistograms(int count, int filterType) { RecordHistogram.recordEnumeratedHistogram("Android.DownloadManager.Share.FileTypes", filterType, DownloadFilter.Type.NUM_ENTRIES);
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/notifications/NotificationConstants.java b/chrome/android/java/src/org/chromium/chrome/browser/notifications/NotificationConstants.java index 7cec1578..d48149b 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/notifications/NotificationConstants.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/notifications/NotificationConstants.java
@@ -70,8 +70,9 @@ /** * Unique identifier for the persistent notification displayed while a Trusted Web Activity is - * in foreground. + * in foreground. No longer used. */ + @SuppressWarnings("unused") public static final int NOTIFICATION_ID_TWA_PERSISTENT = 6; /**
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/payments/AddressEditor.java b/chrome/android/java/src/org/chromium/chrome/browser/payments/AddressEditor.java index 3f7e326..177b7c3 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/payments/AddressEditor.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/payments/AddressEditor.java
@@ -6,12 +6,14 @@ import android.app.ProgressDialog; import android.os.Handler; +import android.support.annotation.IntDef; import android.support.annotation.Nullable; import android.text.TextUtils; import android.util.Pair; import org.chromium.base.Callback; import org.chromium.chrome.R; +import org.chromium.chrome.browser.ChromeFeatureList; import org.chromium.chrome.browser.autofill.PersonalDataManager; import org.chromium.chrome.browser.autofill.PersonalDataManager.AutofillProfile; import org.chromium.chrome.browser.autofill.PersonalDataManager.GetSubKeysRequestDelegate; @@ -25,6 +27,8 @@ import org.chromium.chrome.browser.widget.prefeditor.EditorModel; import org.chromium.payments.mojom.AddressErrors; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; import java.util.HashMap; import java.util.HashSet; import java.util.List; @@ -38,9 +42,22 @@ */ public class AddressEditor extends EditorBase<AutofillAddress> implements GetSubKeysRequestDelegate { + @IntDef({Purpose.PAYMENT_REQUEST, Purpose.AUTOFILL_SETTINGS, Purpose.AUTOFILL_ASSISTANT}) + @Retention(RetentionPolicy.SOURCE) + public @interface Purpose { + int PAYMENT_REQUEST = 1; + int AUTOFILL_SETTINGS = 2; + int AUTOFILL_ASSISTANT = 3; + } + private final Handler mHandler = new Handler(); private final Map<Integer, EditorFieldModel> mAddressFields = new HashMap<>(); private final Set<CharSequence> mPhoneNumbers = new HashSet<>(); + private final PhoneNumberUtil.CountryAwareFormatTextWatcher mPhoneFormatter; + private final CountryAwarePhoneNumberValidator mPhoneValidator; + @Purpose + private final int mPurpose; + private final boolean mSaveToDisk; @Nullable private AutofillProfileBridge mAutofillProfileBridge; @Nullable @@ -49,8 +66,6 @@ private EditorFieldModel mPhoneField; @Nullable private EditorFieldModel mEmailField; - private PhoneNumberUtil.CountryAwareFormatTextWatcher mPhoneFormatter; - private CountryAwarePhoneNumberValidator mPhoneValidator; @Nullable private List<AddressUiComponent> mAddressUiComponents; private boolean mAdminAreasLoaded; @@ -59,22 +74,20 @@ private AutofillProfile mProfile; private EditorModel mEditor; private ProgressDialog mProgressDialog; - private boolean mEmailFieldIncluded; - private boolean mSaveToDisk; @Nullable private AddressErrors mAddressErrors; /** * Builds an address editor. * - * @param emailFieldIncluded True if the address editor has an email field. The autofill form - * has an email address, and the payment request doesn't. - * @param saveToDisk Whether to save changes to disk after editing. + * @param purpose The purpose of this address editor. One of Purpose.PAYMENT_REQUEST, + * Purpose.AUTOFILL_SETTINGS, or Purpose.AUTOFILL_ASSISTANT. + * @param saveToDisk Whether to save changes to disk after editing. */ - public AddressEditor(boolean emailFieldIncluded, boolean saveToDisk) { + public AddressEditor(@Purpose int purpose, boolean saveToDisk) { mPhoneFormatter = new PhoneNumberUtil.CountryAwareFormatTextWatcher(); mPhoneValidator = new CountryAwarePhoneNumberValidator(); - mEmailFieldIncluded = emailFieldIncluded; + mPurpose = purpose; mSaveToDisk = saveToDisk; } @@ -230,24 +243,26 @@ if (mPhoneField == null) { mPhoneField = EditorFieldModel.createTextInput(EditorFieldModel.INPUT_TYPE_HINT_PHONE, mContext.getString(R.string.autofill_profile_editor_phone_number), - mPhoneNumbers, mPhoneFormatter, mPhoneValidator, null, + mPhoneNumbers, mPhoneFormatter, mPhoneValidator, null /* valueIconGenerator */, mContext.getString(R.string.pref_edit_dialog_field_required_validation_message), - mContext.getString(R.string.payments_phone_invalid_validation_message), null); + mContext.getString(R.string.payments_phone_invalid_validation_message), + null /* value */); } // Phone number field is cached, so its value needs to be updated for every new profile // that's being edited. mPhoneField.setValue(mProfile.getPhoneNumber()); - // Email address is present and required if the mEmailFieldIncluded is true. - if (mEmailFieldIncluded) { + // Email address is present for autofill settings and autofill assistant. + if (mPurpose != Purpose.PAYMENT_REQUEST) { if (mEmailField == null) { mEmailField = EditorFieldModel.createTextInput( EditorFieldModel.INPUT_TYPE_HINT_EMAIL, - mContext.getString(R.string.autofill_profile_editor_email_address), null, - null, null, null, null, + mContext.getString(R.string.autofill_profile_editor_email_address), + null /* suggestions */, null /* formatter */, null /* validator */, + null /* valueIconGenerator */, null /* requiredErrorMessage */, mContext.getString(R.string.payments_email_invalid_validation_message), - null); + null /* value */); } // Retrieve and set the email address field. mEmailField.setValue(mProfile.getEmailAddress()); @@ -296,9 +311,7 @@ // editor model. profile.setCountryCode(mCountryField.getValue().toString()); profile.setPhoneNumber(mPhoneField.getValue().toString()); - if (mEmailFieldIncluded) { - profile.setEmailAddress(mEmailField.getValue().toString()); - } + if (mEmailField != null) profile.setEmailAddress(mEmailField.getValue().toString()); // Autofill profile bridge normalizes the language code for the autofill profile. profile.setLanguageCode(mAutofillProfileBridge.getCurrentBestLanguageCode()); @@ -474,6 +487,13 @@ AddressUiComponent component = mAddressUiComponents.get(i); EditorFieldModel field = mAddressFields.get(component.id); + + if (component.id == AddressField.ORGANIZATION && mPurpose != Purpose.PAYMENT_REQUEST + && !ChromeFeatureList.isEnabled( + ChromeFeatureList.AUTOFILL_ENABLE_COMPANY_NAME)) { + continue; + } + // Labels depend on country, e.g., state is called province in some countries. These are // already localized. field.setLabel(component.label); @@ -495,9 +515,7 @@ // Phone number (and email if applicable) are the last fields of the address. mPhoneField.setCustomErrorMessage(mAddressErrors != null ? mAddressErrors.phone : null); mEditor.addField(mPhoneField); - if (mEmailFieldIncluded) { - mEditor.addField(mEmailField); - } + if (mEmailField != null) mEditor.addField(mEmailField); } /** Country based phone number validator. */
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/payments/PaymentRequestImpl.java b/chrome/android/java/src/org/chromium/chrome/browser/payments/PaymentRequestImpl.java index ee6681393..a8b29ff 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/payments/PaymentRequestImpl.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/payments/PaymentRequestImpl.java
@@ -366,8 +366,8 @@ && activity.getCurrentTabModel().isIncognito(); // Do not persist changes on disk in incognito mode. - mAddressEditor = - new AddressEditor(/*emailFieldIncluded=*/false, /*saveToDisk=*/!mIsIncognito); + mAddressEditor = new AddressEditor( + AddressEditor.Purpose.PAYMENT_REQUEST, /*saveToDisk=*/!mIsIncognito); mCardEditor = new CardEditor(mWebContents, mAddressEditor, sObserverForTest); mJourneyLogger = new JourneyLogger(mIsIncognito, mWebContents);
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/photo_picker/DecoderServiceHost.java b/chrome/android/java/src/org/chromium/chrome/browser/photo_picker/DecoderServiceHost.java index e95ee6f..ab45cd66 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/photo_picker/DecoderServiceHost.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/photo_picker/DecoderServiceHost.java
@@ -5,10 +5,13 @@ package org.chromium.chrome.browser.photo_picker; import android.content.ComponentName; +import android.content.ContentResolver; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; +import android.content.res.AssetFileDescriptor; import android.graphics.Bitmap; +import android.net.Uri; import android.os.Bundle; import android.os.IBinder; import android.os.ParcelFileDescriptor; @@ -24,9 +27,7 @@ import org.chromium.chrome.browser.util.ConversionUtils; import org.chromium.content_public.browser.UiThreadTaskTraits; -import java.io.File; -import java.io.FileDescriptor; -import java.io.FileInputStream; +import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import java.util.LinkedHashMap; @@ -39,6 +40,9 @@ // A tag for logging error messages. private static final String TAG = "ImageDecoderHost"; + // A content resolver for providing file descriptors for the images. + private ContentResolver mContentResolver; + // The number of successful decodes, per batch. private int mSuccessfulDecodes; @@ -96,8 +100,8 @@ * Class for keeping track of the data involved with each request. */ private static class DecoderServiceParams { - // The path to the file containing the bitmap to decode. - public String mFilePath; + // The URI for the file containing the bitmap to decode. + public Uri mUri; // The requested size (width and height) of the bitmap, once decoded. public int mSize; @@ -108,8 +112,8 @@ // The timestamp for when the request was sent for decoding. long mTimestamp; - public DecoderServiceParams(String filePath, int size, ImageDecodedCallback callback) { - mFilePath = filePath; + public DecoderServiceParams(Uri uri, int size, ImageDecodedCallback callback) { + mUri = uri; mSize = size; mCallback = callback; } @@ -139,6 +143,7 @@ mCallbacks.add(sReadyCallbackForTesting); } mContext = context; + mContentResolver = mContext.getContentResolver(); } /** @@ -165,13 +170,13 @@ /** * Accepts a request to decode a single image. Queues up the request and reports back * asynchronously on |callback|. - * @param filePath The path to the file to decode. + * @param uri The URI of the file to decode. * @param size The requested size (width and height) of the resulting bitmap. * @param callback The callback to use to communicate the decoding results. */ - public void decodeImage(String filePath, int size, ImageDecodedCallback callback) { - DecoderServiceParams params = new DecoderServiceParams(filePath, size, callback); - mRequests.put(filePath, params); + public void decodeImage(Uri uri, int size, ImageDecodedCallback callback) { + DecoderServiceParams params = new DecoderServiceParams(uri, size, callback); + mRequests.put(uri.getPath(), params); if (mRequests.size() == 1) dispatchNextDecodeImageRequest(); } @@ -182,7 +187,7 @@ if (mRequests.entrySet().iterator().hasNext()) { DecoderServiceParams params = mRequests.entrySet().iterator().next().getValue(); params.mTimestamp = SystemClock.elapsedRealtime(); - dispatchDecodeImageRequest(params.mFilePath, params.mSize); + dispatchDecodeImageRequest(params.mUri, params.mSize); } else { int totalRequests = mSuccessfulDecodes + mFailedDecodesRuntime + mFailedDecodesMemory; if (totalRequests > 0) { @@ -257,13 +262,11 @@ /** * Communicates with the server to decode a single bitmap. - * @param filePath The path to the image on disk. + * @param uri The URI of the image on disk. * @param size The requested width and height of the resulting bitmap. */ - private void dispatchDecodeImageRequest(String filePath, int size) { + private void dispatchDecodeImageRequest(Uri uri, int size) { // Obtain a file descriptor to send over to the sandboxed process. - File file = new File(filePath); - FileInputStream inputFile = null; ParcelFileDescriptor pfd = null; Bundle bundle = new Bundle(); @@ -271,38 +274,36 @@ // contents, so we need to obtain a file descriptor to pass over. StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads(); try { + AssetFileDescriptor afd = null; try { - inputFile = new FileInputStream(file); - FileDescriptor fd = inputFile.getFD(); - pfd = ParcelFileDescriptor.dup(fd); - bundle.putParcelable(DecoderService.KEY_FILE_DESCRIPTOR, pfd); - } catch (IOException e) { + afd = mContentResolver.openAssetFileDescriptor(uri, "r"); + } catch (FileNotFoundException e) { Log.e(TAG, "Unable to obtain FileDescriptor: " + e); - closeRequest(filePath, null, -1); + closeRequest(uri.getPath(), null, -1); + return; + } + pfd = afd.getParcelFileDescriptor(); + if (pfd == null) { + closeRequest(uri.getPath(), null, -1); + return; } } finally { - try { - if (inputFile != null) inputFile.close(); - } catch (IOException e) { - Log.e(TAG, "Unable to close inputFile: " + e); - } StrictMode.setThreadPolicy(oldPolicy); } - if (pfd == null) return; - // Prepare and send the data over. - bundle.putString(DecoderService.KEY_FILE_PATH, filePath); + bundle.putString(DecoderService.KEY_FILE_PATH, uri.getPath()); + bundle.putParcelable(DecoderService.KEY_FILE_DESCRIPTOR, pfd); bundle.putInt(DecoderService.KEY_SIZE, size); try { mIRemoteService.decodeImage(bundle, this); pfd.close(); } catch (RemoteException e) { Log.e(TAG, "Communications failed (Remote): " + e); - closeRequest(filePath, null, -1); + closeRequest(uri.getPath(), null, -1); } catch (IOException e) { Log.e(TAG, "Communications failed (IO): " + e); - closeRequest(filePath, null, -1); + closeRequest(uri.getPath(), null, -1); } }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/photo_picker/FileEnumWorkerTask.java b/chrome/android/java/src/org/chromium/chrome/browser/photo_picker/FileEnumWorkerTask.java index 5d91aec..789bbdd38 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/photo_picker/FileEnumWorkerTask.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/photo_picker/FileEnumWorkerTask.java
@@ -5,7 +5,11 @@ package org.chromium.chrome.browser.photo_picker; import android.Manifest; +import android.content.ContentResolver; +import android.content.ContentUris; import android.content.Intent; +import android.database.Cursor; +import android.net.Uri; import android.os.Environment; import android.provider.MediaStore; @@ -16,7 +20,6 @@ import java.io.File; import java.util.ArrayList; -import java.util.Collections; import java.util.List; /** @@ -42,6 +45,9 @@ // The filter to apply to the list. private MimeTypeFilter mFilter; + // The ContentResolver to use to retrieve image metadata from disk. + private ContentResolver mContentResolver; + // The camera directory undir DCIM. private static final String SAMPLE_DCIM_SOURCE_SUB_DIRECTORY = "Camera"; @@ -50,12 +56,14 @@ * @param windowAndroid The window wrapper associated with the current activity. * @param callback The callback to use to communicate back the results. * @param filter The file filter to apply to the list. + * @param contentResolver The ContentResolver to use to retrieve image metadata from disk. */ - public FileEnumWorkerTask( - WindowAndroid windowAndroid, FilesEnumeratedCallback callback, MimeTypeFilter filter) { + public FileEnumWorkerTask(WindowAndroid windowAndroid, FilesEnumeratedCallback callback, + MimeTypeFilter filter, ContentResolver contentResolver) { mWindowAndroid = windowAndroid; mCallback = callback; mFilter = filter; + mContentResolver = contentResolver; } /** @@ -67,30 +75,6 @@ } /** - * Recursively enumerate files in a directory (and subdirectories) and add them to a list. - * @param directory The parent directory to recursively traverse. - * @param pickerBitmaps The list to add the results to. - * @return True if traversing can continue, false if traversing was aborted and should stop. - */ - private boolean traverseDir(File directory, List<PickerBitmap> pickerBitmaps) { - File[] files = directory.listFiles(mFilter); - if (files == null) return true; - - for (File file : files) { - if (isCancelled()) return false; - - if (file.isDirectory()) { - if (!traverseDir(file, pickerBitmaps)) return false; - } else { - pickerBitmaps.add(new PickerBitmap( - file.getPath(), file.lastModified(), PickerBitmap.TileTypes.PICTURE)); - } - } - - return true; - } - - /** * Enumerates (in the background) the image files on disk. Called on a non-UI thread * @param params Ignored, do not use. * @return A sorted list of images (by last-modified first). @@ -103,27 +87,48 @@ List<PickerBitmap> pickerBitmaps = new ArrayList<>(); - // TODO(finnur): Figure out which directories to scan and stop hard coding "Camera" above. - File[] sourceDirs = new File[] { - getCameraDirectory(), - Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), - Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), - }; + final String[] selectColumns = {MediaStore.Images.Media._ID, + MediaStore.Images.Media.DATE_TAKEN, MediaStore.Images.Media.DATA}; - for (File directory : sourceDirs) { - if (!traverseDir(directory, pickerBitmaps)) return null; + final String whereClause = "(" + MediaStore.Images.Media.DATA + " LIKE ? OR " + + MediaStore.Images.Media.DATA + " LIKE ? OR " + MediaStore.Images.Media.DATA + + " LIKE ?) AND " + MediaStore.Images.Media.DATA + " NOT LIKE ?"; + + final String[] whereArgs = {// Include: + getCameraDirectory().toString() + "%", + Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "%", + Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + + "%", + // Exclude low-quality sources, such as the screenshots directory: + // TODO(finnur): As of the Q SDK this can be converted to DIRECTORY_SCREENSHOTS. + Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + + "/Screenshots/" + + "%"}; + + final String orderBy = MediaStore.Images.Media.DATE_TAKEN + " DESC"; + + Cursor imageCursor = mContentResolver.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, + selectColumns, whereClause, whereArgs, orderBy); + + while (imageCursor.moveToNext()) { + int dataIndex = imageCursor.getColumnIndex(MediaStore.Images.Media.DATA); + int dateTakenIndex = imageCursor.getColumnIndex(MediaStore.Images.Media.DATE_TAKEN); + int idIndex = imageCursor.getColumnIndex(MediaStore.Images.ImageColumns._ID); + Uri uri = ContentUris.withAppendedId( + MediaStore.Images.Media.EXTERNAL_CONTENT_URI, imageCursor.getInt(idIndex)); + long dateTaken = imageCursor.getLong(dateTakenIndex); + pickerBitmaps.add(new PickerBitmap(uri, dateTaken, PickerBitmap.TileTypes.PICTURE)); } + imageCursor.close(); - Collections.sort(pickerBitmaps); - - pickerBitmaps.add(0, new PickerBitmap("", 0, PickerBitmap.TileTypes.GALLERY)); + pickerBitmaps.add(0, new PickerBitmap(null, 0, PickerBitmap.TileTypes.GALLERY)); boolean hasCameraAppAvailable = mWindowAndroid.canResolveActivity(new Intent(MediaStore.ACTION_IMAGE_CAPTURE)); boolean hasOrCanRequestCameraPermission = mWindowAndroid.hasPermission(Manifest.permission.CAMERA) || mWindowAndroid.canRequestPermission(Manifest.permission.CAMERA); if (hasCameraAppAvailable && hasOrCanRequestCameraPermission) { - pickerBitmaps.add(0, new PickerBitmap("", 0, PickerBitmap.TileTypes.CAMERA)); + pickerBitmaps.add(0, new PickerBitmap(null, 0, PickerBitmap.TileTypes.CAMERA)); } return pickerBitmaps;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/photo_picker/PhotoPickerDialog.java b/chrome/android/java/src/org/chromium/chrome/browser/photo_picker/PhotoPickerDialog.java index ae7a10ae..ac466f21 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/photo_picker/PhotoPickerDialog.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/photo_picker/PhotoPickerDialog.java
@@ -6,6 +6,7 @@ import android.app.Activity; import android.content.Context; +import android.net.Uri; import android.support.v7.app.AlertDialog; import org.chromium.base.ActivityState; @@ -55,7 +56,7 @@ // PhotoPickerListener: @Override - public void onPhotoPickerUserAction(@PhotoPickerAction int action, String[] photos) { + public void onPhotoPickerUserAction(@PhotoPickerAction int action, Uri[] photos) { mExternalIntentSelected = false; if (action == PhotoPickerAction.LAUNCH_GALLERY || action == PhotoPickerAction.LAUNCH_CAMERA) {
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/photo_picker/PickerBitmap.java b/chrome/android/java/src/org/chromium/chrome/browser/photo_picker/PickerBitmap.java index ffc24c8..27f46a29 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/photo_picker/PickerBitmap.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/photo_picker/PickerBitmap.java
@@ -4,6 +4,7 @@ package org.chromium.chrome.browser.photo_picker; +import android.net.Uri; import android.support.annotation.IntDef; import org.chromium.base.ApiCompatibilityUtils; @@ -26,8 +27,8 @@ int GALLERY = 2; } - // The file path to the bitmap to show. - private String mFilePath; + // The URI of the bitmap to show. + private Uri mUri; // When the bitmap was last modified on disk. private long mLastModified; @@ -38,22 +39,22 @@ /** * The PickerBitmap constructor. - * @param filePath The file path to the bitmap to show. + * @param uri The URI for the bitmap to show. * @param lastModified When the bitmap was last modified on disk. * @param type The type of tile involved. */ - public PickerBitmap(String filePath, long lastModified, @TileTypes int type) { - mFilePath = filePath; + public PickerBitmap(Uri uri, long lastModified, @TileTypes int type) { + mUri = uri; mLastModified = lastModified; mType = type; } /** - * Accessor for the filepath. - * @return The file path for this PickerBitmap object. + * Accessor for the URI. + * @return The URI for this PickerBitmap object. */ - public String getFilePath() { - return mFilePath; + public Uri getUri() { + return mUri; } /** @@ -61,9 +62,10 @@ * @return The filename (without the extension and path). */ public String getFilenameWithoutExtension() { - int index = mFilePath.lastIndexOf("/"); - if (index == -1) return mFilePath; - return mFilePath.substring(index + 1, mFilePath.length()); + String filePath = mUri.getPath(); + int index = filePath.lastIndexOf("/"); + if (index == -1) return filePath; + return filePath.substring(index + 1, filePath.length()); } /**
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/photo_picker/PickerBitmapViewHolder.java b/chrome/android/java/src/org/chromium/chrome/browser/photo_picker/PickerBitmapViewHolder.java index 3ae3759..ecdae499 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/photo_picker/PickerBitmapViewHolder.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/photo_picker/PickerBitmapViewHolder.java
@@ -59,7 +59,7 @@ .executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } - if (!TextUtils.equals(mBitmapDetails.getFilePath(), filePath)) { + if (!TextUtils.equals(mBitmapDetails.getUri().getPath(), filePath)) { return; } @@ -87,7 +87,7 @@ return PickerAdapter.DecodeActions.NO_ACTION; } - String filePath = mBitmapDetails.getFilePath(); + String filePath = mBitmapDetails.getUri().getPath(); Bitmap original = mCategoryView.getHighResBitmaps().get(filePath); if (original != null) { mItemView.initialize(mBitmapDetails, original, false); @@ -109,14 +109,17 @@ mItemView.initialize(mBitmapDetails, null, true); } - mCategoryView.getDecoderServiceHost().decodeImage(filePath, size, this); + mCategoryView.getDecoderServiceHost().decodeImage(mBitmapDetails.getUri(), size, this); return PickerAdapter.DecodeActions.DECODE; } /** - * Returns the file path of the current request. + * Returns the file path of the current request, or null if no request is in progress for this + * holder. */ public String getFilePath() { - return mBitmapDetails == null ? null : mBitmapDetails.getFilePath(); + if (mBitmapDetails == null || mBitmapDetails.type() != PickerBitmap.TileTypes.PICTURE) + return null; + return mBitmapDetails.getUri().getPath(); } }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/photo_picker/PickerCategoryView.java b/chrome/android/java/src/org/chromium/chrome/browser/photo_picker/PickerCategoryView.java index 58716e6..d18e6cb 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/photo_picker/PickerCategoryView.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/photo_picker/PickerCategoryView.java
@@ -9,6 +9,7 @@ import android.content.res.Configuration; import android.graphics.Bitmap; import android.graphics.Rect; +import android.net.Uri; import android.os.SystemClock; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.RecyclerView; @@ -366,8 +367,8 @@ } mEnumStartTime = SystemClock.elapsedRealtime(); - mWorkerTask = new FileEnumWorkerTask( - mActivity.getWindowAndroid(), this, new MimeTypeFilter(mMimeTypes, true)); + mWorkerTask = new FileEnumWorkerTask(mActivity.getWindowAndroid(), this, + new MimeTypeFilter(mMimeTypes, true), mActivity.getContentResolver()); mWorkerTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } @@ -377,10 +378,10 @@ private void notifyPhotosSelected() { List<PickerBitmap> selectedFiles = mSelectionDelegate.getSelectedItemsAsList(); Collections.sort(selectedFiles); - String[] photos = new String[selectedFiles.size()]; + Uri[] photos = new Uri[selectedFiles.size()]; int i = 0; for (PickerBitmap bitmap : selectedFiles) { - photos[i++] = bitmap.getFilePath(); + photos[i++] = bitmap.getUri(); } executeAction( @@ -431,7 +432,7 @@ * @param umaId The UMA value to record with the action. */ private void executeAction( - @PhotoPickerListener.PhotoPickerAction int action, String[] photos, int umaId) { + @PhotoPickerListener.PhotoPickerAction int action, Uri[] photos, int umaId) { mListener.onPhotoPickerUserAction(action, photos); mDialog.dismiss(); UiUtils.onPhotoPickerDismissed();
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/preferences/ContextualSuggestionsPreference.java b/chrome/android/java/src/org/chromium/chrome/browser/preferences/ContextualSuggestionsPreference.java index ee5fa36..fede6cd 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/preferences/ContextualSuggestionsPreference.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/preferences/ContextualSuggestionsPreference.java
@@ -21,7 +21,7 @@ import org.chromium.chrome.browser.signin.AccountSigninActivity; import org.chromium.chrome.browser.signin.SigninAccessPoint; import org.chromium.chrome.browser.signin.SigninActivity; -import org.chromium.chrome.browser.sync.ProfileSyncService; +import org.chromium.chrome.browser.signin.UnifiedConsentServiceBridge; import org.chromium.chrome.browser.sync.ui.SyncCustomizationFragment; import org.chromium.chrome.browser.widget.TintedDrawable; import org.chromium.components.signin.ChromeSigninController; @@ -88,8 +88,7 @@ ChromeFeatureList.isEnabled(ChromeFeatureList.UNIFIED_CONSENT); boolean isSignedIn = ChromeSigninController.get().isSignedIn(); if (!isUnifiedConsentEnabled || !isSignedIn - || (!ProfileSyncService.get().isUrlKeyedDataCollectionEnabled(false) - && !ProfileSyncService.get().isUrlKeyedDataCollectionEnabled(true))) { + || !UnifiedConsentServiceBridge.isUrlKeyedAnonymizedDataCollectionEnabled()) { final NoUnderlineClickableSpan span = new NoUnderlineClickableSpan(context.getResources(), (widget) -> { if (isUnifiedConsentEnabled) {
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/preferences/SyncAndServicesPreferences.java b/chrome/android/java/src/org/chromium/chrome/browser/preferences/SyncAndServicesPreferences.java index 94b407f..d00aa615 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/preferences/SyncAndServicesPreferences.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/preferences/SyncAndServicesPreferences.java
@@ -55,7 +55,6 @@ import org.chromium.components.signin.AccountManagerFacade; import org.chromium.components.signin.ChromeSigninController; import org.chromium.components.sync.AndroidSyncSettings; -import org.chromium.components.sync.ProtocolErrorClientAction; import org.chromium.content_public.browser.UiThreadTaskTraits; import org.chromium.ui.widget.ButtonCompat; @@ -404,8 +403,7 @@ return SyncError.AUTH_ERROR; } - if (mProfileSyncService.getProtocolErrorClientAction() - == ProtocolErrorClientAction.UPGRADE_CLIENT) { + if (mProfileSyncService.requiresClientUpgrade()) { return SyncError.CLIENT_OUT_OF_DATE; }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/preferences/SyncPreferenceUtils.java b/chrome/android/java/src/org/chromium/chrome/browser/preferences/SyncPreferenceUtils.java index 711d8a4..9995ddfe 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/preferences/SyncPreferenceUtils.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/preferences/SyncPreferenceUtils.java
@@ -19,7 +19,6 @@ import org.chromium.chrome.browser.sync.ProfileSyncService; import org.chromium.components.signin.ChromeSigninController; import org.chromium.components.sync.AndroidSyncSettings; -import org.chromium.components.sync.ProtocolErrorClientAction; import org.chromium.components.sync.StopSource; import org.chromium.ui.UiUtils; @@ -77,8 +76,7 @@ GoogleServiceAuthError.getMessageID(profileSyncService.getAuthError())); } - if (profileSyncService.getProtocolErrorClientAction() - == ProtocolErrorClientAction.UPGRADE_CLIENT) { + if (profileSyncService.requiresClientUpgrade()) { return res.getString( R.string.sync_error_upgrade_client, BuildInfo.getInstance().hostPackageLabel); }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/preferences/autofill/AutofillProfileEditorPreference.java b/chrome/android/java/src/org/chromium/chrome/browser/preferences/autofill/AutofillProfileEditorPreference.java index 834382bb..51ab608 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/preferences/autofill/AutofillProfileEditorPreference.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/preferences/autofill/AutofillProfileEditorPreference.java
@@ -50,7 +50,7 @@ private void prepareAddressEditor() { AddressEditor addressEditor = - new AddressEditor(/*emailFieldIncluded=*/true, /*saveToDisk=*/true); + new AddressEditor(AddressEditor.Purpose.AUTOFILL_SETTINGS, /*saveToDisk=*/true); addressEditor.setEditorDialog(mEditorDialog); addressEditor.edit(mAutofillAddress, new Callback<AutofillAddress>() {
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/send_tab_to_self/SendTabToSelfAndroidBridge.java b/chrome/android/java/src/org/chromium/chrome/browser/send_tab_to_self/SendTabToSelfAndroidBridge.java index f6a5832..993f310 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/send_tab_to_self/SendTabToSelfAndroidBridge.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/send_tab_to_self/SendTabToSelfAndroidBridge.java
@@ -21,7 +21,7 @@ */ @JNINamespace("send_tab_to_self") public class SendTabToSelfAndroidBridge { - // TODO(tgupta): Add logic back in to track whether model is loaded. + // TODO(https://crbug.com/942549): Add logic back in to track whether model is loaded. private boolean mIsNativeSendTabToSelfModelLoaded; /** @@ -29,8 +29,8 @@ * @returns All GUIDs for all SendTabToSelf entries */ public static List<String> getAllGuids(Profile profile) { - // TODO(tgupta): Add this assertion back in once the code to load is in place. - // assert mIsNativeSendTabToSelfModelLoaded; + // TODO(https://crbug.com/942549): Add this assertion back in once the code to load is in + // place. assert mIsNativeSendTabToSelfModelLoaded; List<String> toPopulate = new ArrayList<String>(); SendTabToSelfAndroidBridgeJni.get().getAllGuids(profile, toPopulate); return toPopulate; @@ -49,8 +49,8 @@ /** Deletes all SendTabToSelf entries. This is called when the user disables sync. */ public static void deleteAllEntries(Profile profile) { - // TODO(tgupta): Add this assertion back in once the code to load is in place. - // assert mIsNativeSendTabToSelfModelLoaded; + // TODO(https://crbug.com/942549): Add this assertion back in once the code to load is in + // place. assert mIsNativeSendTabToSelfModelLoaded; SendTabToSelfAndroidBridgeJni.get().deleteAllEntries(profile); } @@ -60,14 +60,14 @@ * @param profile Profile of the user to add entry for. * @param url URL to be shared * @param title Title of the page - * @return The persisted entry which contains additional information such as the GUID or null in - * the case of an error. + * @param navigationTime Time the user navigated to the page + * @return If the persistent entry in the bridge was created. */ - @Nullable - public static SendTabToSelfEntry addEntry(Profile profile, String url, String title) { - // TODO(tgupta): Add this assertion back in once the code to load is in place. - // assert mIsNativeSendTabToSelfModelLoaded; - return SendTabToSelfAndroidBridgeJni.get().addEntry(profile, url, title); + public static SendTabToSelfEntry addEntry( + Profile profile, String url, String title, long navigationTime) { + // TODO(https://crbug.com/942549): Add this assertion back in once the code to load is in + // place. assert mIsNativeSendTabToSelfModelLoaded; + return SendTabToSelfAndroidBridgeJni.get().addEntry(profile, url, title, navigationTime); } /** @@ -79,8 +79,8 @@ */ @Nullable public static SendTabToSelfEntry getEntryByGUID(Profile profile, String guid) { - // TODO(tgupta): Add this assertion back in once the code to load is in place. - // assert mIsNativeSendTabToSelfModelLoaded; + // TODO(https://crbug.com/942549): Add this assertion back in once the code to load is in + // place. assert mIsNativeSendTabToSelfModelLoaded; return SendTabToSelfAndroidBridgeJni.get().getEntryByGUID(profile, guid); } @@ -106,7 +106,7 @@ @NativeMethods interface Natives { - SendTabToSelfEntry addEntry(Profile profile, String url, String title); + SendTabToSelfEntry addEntry(Profile profile, String url, String title, long navigationTime); void getAllGuids(Profile profile, List<String> guids);
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/send_tab_to_self/SendTabToSelfShareActivity.java b/chrome/android/java/src/org/chromium/chrome/browser/send_tab_to_self/SendTabToSelfShareActivity.java index bd232ca..a7f35654 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/send_tab_to_self/SendTabToSelfShareActivity.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/send_tab_to_self/SendTabToSelfShareActivity.java
@@ -12,6 +12,8 @@ import org.chromium.chrome.browser.tab.Tab; import org.chromium.chrome.browser.util.UrlUtilities; import org.chromium.components.sync.ModelType; +import org.chromium.content_public.browser.NavigationEntry; +import org.chromium.content_public.browser.NavigationHistory; import org.chromium.ui.widget.Toast; /** @@ -21,7 +23,14 @@ @Override protected void handleShareAction(ChromeActivity triggeringActivity) { Tab tab = triggeringActivity.getActivityTabProvider().getActivityTab(); - SendTabToSelfAndroidBridge.addEntry(tab.getProfile(), tab.getUrl(), tab.getTitle()); + + NavigationHistory history = + tab.getWebContents().getNavigationController().getNavigationHistory(); + NavigationEntry entry = history.getEntryAtIndex(history.getCurrentEntryIndex()); + + SendTabToSelfAndroidBridge.addEntry( + tab.getProfile(), entry.getUrl(), entry.getTitle(), entry.getTimestamp()); + Toast.makeText(triggeringActivity, R.string.send_tab_to_self_toast, Toast.LENGTH_SHORT) .show(); }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/sync/ProfileSyncService.java b/chrome/android/java/src/org/chromium/chrome/browser/sync/ProfileSyncService.java index 9e88137..6aff916 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/sync/ProfileSyncService.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/sync/ProfileSyncService.java
@@ -298,13 +298,8 @@ return authErrorCode; } - /** - * Gets client action for sync protocol error. - * - * @return {@link ProtocolErrorClientAction}. - */ - public int getProtocolErrorClientAction() { - return nativeGetProtocolErrorClientAction(mNativeProfileSyncServiceAndroid); + public boolean requiresClientUpgrade() { + return nativeRequiresClientUpgrade(mNativeProfileSyncServiceAndroid); } /** @@ -480,18 +475,6 @@ } /** - * Returns whether either personalized or anonymized URL keyed data collection is enabled. - * - * @param personlized Whether to check for personalized data collection. If false, this will - * check for anonymized data collection. - * @return Whether URL-keyed data collection is enabled for the current profile. - */ - public boolean isUrlKeyedDataCollectionEnabled(boolean personalized) { - return nativeIsUrlKeyedDataCollectionEnabled( - mNativeProfileSyncServiceAndroid, personalized); - } - - /** * Called when the state of the native sync engine has changed, so various * UI elements can update themselves. */ @@ -626,7 +609,7 @@ private native void nativeFlushDirectory(long nativeProfileSyncServiceAndroid); private native void nativeSetSyncSessionsId(long nativeProfileSyncServiceAndroid, String tag); private native int nativeGetAuthError(long nativeProfileSyncServiceAndroid); - private native int nativeGetProtocolErrorClientAction(long nativeProfileSyncServiceAndroid); + private native boolean nativeRequiresClientUpgrade(long nativeProfileSyncServiceAndroid); private native boolean nativeIsEngineInitialized(long nativeProfileSyncServiceAndroid); private native boolean nativeIsEncryptEverythingAllowed(long nativeProfileSyncServiceAndroid); private native boolean nativeIsEncryptEverythingEnabled(long nativeProfileSyncServiceAndroid); @@ -664,8 +647,6 @@ private native boolean nativeIsSyncActive(long nativeProfileSyncServiceAndroid); private native boolean nativeHasKeepEverythingSynced(long nativeProfileSyncServiceAndroid); private native boolean nativeHasUnrecoverableError(long nativeProfileSyncServiceAndroid); - private native boolean nativeIsUrlKeyedDataCollectionEnabled( - long nativeProfileSyncServiceAndroid, boolean personalized); private native boolean nativeIsPassphrasePrompted(long nativeProfileSyncServiceAndroid); private native void nativeSetPassphrasePrompted(long nativeProfileSyncServiceAndroid, boolean prompted);
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/sync/ui/SyncCustomizationFragment.java b/chrome/android/java/src/org/chromium/chrome/browser/sync/ui/SyncCustomizationFragment.java index 8d3ac2a2..bca2cab 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/sync/ui/SyncCustomizationFragment.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/sync/ui/SyncCustomizationFragment.java
@@ -51,7 +51,6 @@ import org.chromium.components.sync.AndroidSyncSettings; import org.chromium.components.sync.ModelType; import org.chromium.components.sync.Passphrase; -import org.chromium.components.sync.ProtocolErrorClientAction; import org.chromium.content_public.browser.UiThreadTaskTraits; import java.lang.annotation.Retention; @@ -600,8 +599,7 @@ return SyncError.AUTH_ERROR; } - if (mProfileSyncService.getProtocolErrorClientAction() - == ProtocolErrorClientAction.UPGRADE_CLIENT) { + if (mProfileSyncService.requiresClientUpgrade()) { return SyncError.CLIENT_OUT_OF_DATE; }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/tab/TabContextMenuItemDelegate.java b/chrome/android/java/src/org/chromium/chrome/browser/tab/TabContextMenuItemDelegate.java index 78548bd..b960310 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/tab/TabContextMenuItemDelegate.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/tab/TabContextMenuItemDelegate.java
@@ -170,6 +170,7 @@ @Override public void onOpenInNewTab(String url, Referrer referrer) { RecordUserAction.record("MobileNewTabOpened"); + RecordUserAction.record("LinkOpenedInNewTab"); LoadUrlParams loadUrlParams = new LoadUrlParams(url); loadUrlParams.setReferrer(referrer); mTab.getTabModelSelector().openNewTab(
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/tab/TabWebContentsDelegateAndroid.java b/chrome/android/java/src/org/chromium/chrome/browser/tab/TabWebContentsDelegateAndroid.java index 349bd51..3a4ab381 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/tab/TabWebContentsDelegateAndroid.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/tab/TabWebContentsDelegateAndroid.java
@@ -24,6 +24,7 @@ import org.chromium.base.Log; import org.chromium.base.ObserverList.RewindableIterator; import org.chromium.base.annotations.CalledByNative; +import org.chromium.base.metrics.RecordUserAction; import org.chromium.blink_public.platform.WebDisplayMode; import org.chromium.chrome.R; import org.chromium.chrome.browser.AppHooks; @@ -329,10 +330,22 @@ boolean createdSuccessfully = tabCreator.createTabWithWebContents(mTab, webContents, mTab.getId(), TabLaunchType.FROM_LONGPRESS_FOREGROUND, url); boolean success = tabCreator.createsTabsAsynchronously() || createdSuccessfully; - if (success && disposition == WindowOpenDisposition.NEW_POPUP) { - PolicyAuditor auditor = AppHooks.get().getPolicyAuditor(); - auditor.notifyAuditEvent(mTab.getApplicationContext(), - AuditEvent.OPEN_POPUP_URL_SUCCESS, url, ""); + + if (success) { + if (disposition == WindowOpenDisposition.NEW_FOREGROUND_TAB) { + if (mTab.getTabModelSelector() + .getTabModelFilterProvider() + .getCurrentTabModelFilter() + .getRelatedTabList(mTab.getId()) + .size() + == 2) { + RecordUserAction.record("TabGroup.Created.DeveloperRequestedNewTab"); + } + } else if (disposition == WindowOpenDisposition.NEW_POPUP) { + PolicyAuditor auditor = AppHooks.get().getPolicyAuditor(); + auditor.notifyAuditEvent( + mTab.getApplicationContext(), AuditEvent.OPEN_POPUP_URL_SUCCESS, url, ""); + } } return success;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/tasks/tab_groups/LayoutTabGroupCreationButton.java b/chrome/android/java/src/org/chromium/chrome/browser/tasks/tab_groups/LayoutTabGroupCreationButton.java index 9967c555..ac35106 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/tasks/tab_groups/LayoutTabGroupCreationButton.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/tasks/tab_groups/LayoutTabGroupCreationButton.java
@@ -12,6 +12,7 @@ import android.text.TextPaint; import org.chromium.base.ApiCompatibilityUtils; +import org.chromium.base.metrics.RecordUserAction; import org.chromium.chrome.R; import org.chromium.chrome.browser.UrlConstants; import org.chromium.chrome.browser.compositor.layouts.components.CompositorButton; @@ -45,6 +46,7 @@ tabModelSelector.openNewTab(new LoadUrlParams(UrlConstants.NTP_URL), TabLaunchType.FROM_CHROME_UI, parentTab, tabModelSelector.isIncognitoSelected()); + RecordUserAction.record("TabGroup.Created.TabSwitcher"); }; mCreateGroupButton = new CompositorButton(context, buttonBitmap.getWidth() * pxToDp,
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/tasks/tabgroup/TabGroupModelFilter.java b/chrome/android/java/src/org/chromium/chrome/browser/tasks/tabgroup/TabGroupModelFilter.java index 651641a5..28fb054 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/tasks/tabgroup/TabGroupModelFilter.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/tasks/tabgroup/TabGroupModelFilter.java
@@ -6,7 +6,9 @@ import android.support.annotation.NonNull; +import org.chromium.base.metrics.RecordUserAction; import org.chromium.chrome.browser.tab.Tab; +import org.chromium.chrome.browser.tabmodel.TabLaunchType; import org.chromium.chrome.browser.tabmodel.TabList; import org.chromium.chrome.browser.tabmodel.TabModel; import org.chromium.chrome.browser.tabmodel.TabModelFilter; @@ -132,6 +134,10 @@ int groupId = tab.getRootId(); if (mGroupIdToGroupMap.containsKey(groupId)) { + if (tab.getLaunchType() == TabLaunchType.FROM_LONGPRESS_BACKGROUND + && mGroupIdToGroupMap.get(groupId).size() == 1) { + RecordUserAction.record("TabGroup.Created.OpenInNewTab"); + } mGroupIdToGroupMap.get(groupId).addTab(tab.getId()); } else { TabGroup tabGroup = new TabGroup(tab.getRootId());
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/usage_stats/DigitalWellbeingClient.java b/chrome/android/java/src/org/chromium/chrome/browser/usage_stats/DigitalWellbeingClient.java new file mode 100644 index 0000000..b76d377e --- /dev/null +++ b/chrome/android/java/src/org/chromium/chrome/browser/usage_stats/DigitalWellbeingClient.java
@@ -0,0 +1,68 @@ +// 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.usage_stats; + +import org.chromium.base.Promise; + +import java.util.Collections; +import java.util.List; + +/** + * Client for interacting with the Digital Wellbeing(DW) app on Android. + * This implementation is inert; the implementation is downstream. + * All methods are async, since completing a request to DW requires binding to a service, which is + * an async process in Android. + */ +public class DigitalWellbeingClient { + /** + * Notify that the user's opt in state for sharing data with Digital Wellbeing has changed to + * be <c>optInState</c> + */ + public Promise<Void> notifyOptInStateChange(boolean optInState) { + return Promise.fulfilled(null); + } + + /** + * Notify DW that the user has deleted history in the range [start, end), so it should delete + * any Chrome-originating records in the same range. + */ + public Promise<Void> notifyHistoryDeletion(long startTimeMs, long endTimeMs) { + return Promise.fulfilled(null); + } + + /** + * Notify DW that the user has deleted all history, so it should delete all Chrome-originating + * records. + */ + public Promise<Void> notifyAllHistoryCleared() { + return Promise.fulfilled(null); + } + + /** + * Inform DW that Chrome will no longer report usage for the domain associated with + * <c>token</c>. + */ + public Promise<Void> cancelToken(String token) { + return Promise.fulfilled(null); + } + + /** + * Inform DW that Chrome will no longer report usage for any domains, thus cancelling all + * tokens associated with those domains. + */ + public Promise<Void> cancelAllTokens() { + return Promise.fulfilled(null); + } + + /** Get a list of all the tokens that DW thinks Chrome is tracking. */ + public Promise<List<String>> getAllTrackedTokens() { + return Promise.fulfilled(Collections.emptyList()); + } + + /** Get a list of all the websites that DW thinks Chrome should suspend. */ + public Promise<List<String>> getAllSuspendedWebsites() { + return Promise.fulfilled(Collections.emptyList()); + } +} \ No newline at end of file
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/usage_stats/UsageStatsService.java b/chrome/android/java/src/org/chromium/chrome/browser/usage_stats/UsageStatsService.java index a6b45dbd7..37af392 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/usage_stats/UsageStatsService.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/usage_stats/UsageStatsService.java
@@ -9,6 +9,7 @@ import org.chromium.base.Promise; import org.chromium.base.ThreadUtils; import org.chromium.base.VisibleForTesting; +import org.chromium.chrome.browser.AppHooks; import org.chromium.chrome.browser.preferences.Pref; import org.chromium.chrome.browser.preferences.PrefServiceBridge; import org.chromium.chrome.browser.profiles.Profile; @@ -28,6 +29,8 @@ private SuspensionTracker mSuspensionTracker; private TokenTracker mTokenTracker; private UsageStatsBridge mBridge; + + private DigitalWellbeingClient mClient; private boolean mOptInState; /** Get the global instance of UsageStatsService */ @@ -46,7 +49,9 @@ mEventTracker = new EventTracker(mBridge); mSuspensionTracker = new SuspensionTracker(mBridge); mTokenTracker = new TokenTracker(mBridge); - // TODO(pnoland): listen for preference changes so we can notify DW. + + mOptInState = getOptInState(); + mClient = AppHooks.get().createDigitalWellbeingClient(); } /** @@ -74,6 +79,11 @@ ThreadUtils.assertOnUiThread(); PrefServiceBridge prefServiceBridge = PrefServiceBridge.getInstance(); prefServiceBridge.setBoolean(Pref.USAGE_STATS_ENABLED, state); + + if (mOptInState == state) return; + + mOptInState = state; + mClient.notifyOptInStateChange(mOptInState); } /** Query for all events that occurred in the half-open range [start, end) */
diff --git a/chrome/android/java/strings/android_chrome_strings.grd b/chrome/android/java/strings/android_chrome_strings.grd index a84d5b9e..f743dbf 100644 --- a/chrome/android/java/strings/android_chrome_strings.grd +++ b/chrome/android/java/strings/android_chrome_strings.grd
@@ -3695,9 +3695,6 @@ <message name="IDS_CLEAR_RELATED_DATA" desc="Notification text asking if the user wants to clear data for the given url as they have just uninstalled/cleared an app linked to that URL."> Would you like to clear data for <ph name="URL">%1$s<ex>youtube.com</ex></ph>? </message> - <message name="IDS_TWA_MANAGE_DATA" desc="Text on button of the notification that would direct the user to site settings for the site being run in a Trusted Web Activity"> - Manage data - </message> <message name="IDS_TWA_CLEAR_DATA_DIALOG_TITLE" desc="Title of the clear data dialog showing after user uninstalls or clears data of an app hosting a Trusted Web Activity"> <ph name="APP_NAME">%1$s<ex>YouTube</ex></ph> also has data in Chrome </message>
diff --git a/chrome/android/java_sources.gni b/chrome/android/java_sources.gni index 00f79258..5266c7f 100644 --- a/chrome/android/java_sources.gni +++ b/chrome/android/java_sources.gni
@@ -209,12 +209,10 @@ "java/src/org/chromium/chrome/browser/browserservices/trustedwebactivityui/TrustedWebActivityCoordinator.java", "java/src/org/chromium/chrome/browser/browserservices/trustedwebactivityui/TrustedWebActivityModel.java", "java/src/org/chromium/chrome/browser/browserservices/trustedwebactivityui/controller/ClientAppDataRecorder.java", - "java/src/org/chromium/chrome/browser/browserservices/trustedwebactivityui/controller/PersistentNotificationController.java", "java/src/org/chromium/chrome/browser/browserservices/trustedwebactivityui/controller/TrustedWebActivityDisclosureController.java", "java/src/org/chromium/chrome/browser/browserservices/trustedwebactivityui/controller/TrustedWebActivityOpenTimeRecorder.java", "java/src/org/chromium/chrome/browser/browserservices/trustedwebactivityui/controller/TrustedWebActivityToolbarController.java", "java/src/org/chromium/chrome/browser/browserservices/trustedwebactivityui/controller/TrustedWebActivityVerifier.java", - "java/src/org/chromium/chrome/browser/browserservices/trustedwebactivityui/view/PersistentNotificationView.java", "java/src/org/chromium/chrome/browser/browserservices/trustedwebactivityui/view/TrustedWebActivityDisclosureView.java", "java/src/org/chromium/chrome/browser/browserservices/trustedwebactivityui/view/TrustedWebActivityToolbarView.java", "java/src/org/chromium/chrome/browser/browsing_data/UrlFilter.java", @@ -441,6 +439,7 @@ "java/src/org/chromium/chrome/browser/customtabs/CloseButtonNavigator.java", "java/src/org/chromium/chrome/browser/customtabs/CustomButtonParams.java", "java/src/org/chromium/chrome/browser/customtabs/CustomTabActivity.java", + "java/src/org/chromium/chrome/browser/customtabs/CustomTabActivityLifecycleUmaTracker.java", "java/src/org/chromium/chrome/browser/customtabs/CustomTabAppMenuPropertiesDelegate.java", "java/src/org/chromium/chrome/browser/customtabs/CustomTabBottomBarDelegate.java", "java/src/org/chromium/chrome/browser/customtabs/CustomTabBrowserControlsVisibilityDelegate.java", @@ -1627,6 +1626,7 @@ "java/src/org/chromium/chrome/browser/upgrade/PackageReplacedBroadcastReceiver.java", "java/src/org/chromium/chrome/browser/upgrade/UpgradeActivity.java", "java/src/org/chromium/chrome/browser/upgrade/UpgradeIntentService.java", + "java/src/org/chromium/chrome/browser/usage_stats/DigitalWellbeingClient.java", "java/src/org/chromium/chrome/browser/usage_stats/EventTracker.java", "java/src/org/chromium/chrome/browser/usage_stats/PageViewObserver.java", "java/src/org/chromium/chrome/browser/usage_stats/SuspendedTab.java",
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/NavigationPopupTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/NavigationPopupTest.java index 1deced96..6e98962 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/NavigationPopupTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/NavigationPopupTest.java
@@ -71,9 +71,9 @@ // Exists solely to expose protected methods to this test. private static class TestNavigationEntry extends NavigationEntry { public TestNavigationEntry(int index, String url, String virtualUrl, String originalUrl, - String title, Bitmap favicon, int transition) { + String title, Bitmap favicon, int transition, long timestamp) { super(index, url, virtualUrl, originalUrl, /*referrerUrl=*/null, title, favicon, - transition); + transition, timestamp); } } @@ -84,9 +84,9 @@ public TestNavigationController() { mHistory = new TestNavigationHistory(); mHistory.addEntry(new TestNavigationEntry( - 1, "about:blank", null, null, "About Blank", null, 0)); + 1, "about:blank", null, null, "About Blank", null, 0, 0)); mHistory.addEntry(new TestNavigationEntry( - 5, UrlUtils.encodeHtmlDataUri("<html>1</html>"), null, null, null, null, 0)); + 5, UrlUtils.encodeHtmlDataUri("<html>1</html>"), null, null, null, null, 0, 0)); } @Override
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/contextual_suggestions/EnabledStateMonitorTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/contextual_suggestions/EnabledStateMonitorTest.java index 203e7770..9278b29a 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/contextual_suggestions/EnabledStateMonitorTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/contextual_suggestions/EnabledStateMonitorTest.java
@@ -21,7 +21,7 @@ import org.chromium.chrome.browser.ChromeFeatureList; import org.chromium.chrome.browser.ChromeSwitches; import org.chromium.chrome.browser.locale.LocaleManager; -import org.chromium.chrome.browser.sync.ProfileSyncService; +import org.chromium.chrome.browser.signin.UnifiedConsentServiceBridge; import org.chromium.chrome.test.ChromeActivityTestRule; import org.chromium.chrome.test.ChromeJUnit4ClassRunner; import org.chromium.chrome.test.util.browser.Features.EnableFeatures; @@ -41,22 +41,10 @@ public ChromeActivityTestRule<ChromeActivity> mActivityTestRule = new ChromeActivityTestRule<>(ChromeActivity.class); - private ProfileSyncServiceStub mProfileSyncServiceStub; private EnabledStateMonitor mEnabledStateMonitor; private String mOriginalSignedInAccountName; - private static class ProfileSyncServiceStub extends ProfileSyncService { - public ProfileSyncServiceStub() { - super(); - } - - @Override - public boolean isUrlKeyedDataCollectionEnabled(boolean personalized) { - return true; - } - } - @Before public void setUp() throws Exception { LocaleManager.setInstanceForTest(new LocaleManager() { @@ -70,8 +58,7 @@ ThreadUtils.runOnUiThreadBlocking(() -> { mOriginalSignedInAccountName = ChromeSigninController.get().getSignedInAccountName(); ChromeSigninController.get().setSignedInAccountName("test@gmail.com"); - mProfileSyncServiceStub = new ProfileSyncServiceStub(); - ProfileSyncService.overrideForTests(mProfileSyncServiceStub); + UnifiedConsentServiceBridge.setUrlKeyedAnonymizedDataCollectionEnabled(true); mEnabledStateMonitor = new EnabledStateMonitorImpl(); }); } @@ -80,8 +67,6 @@ public void tearDown() throws Exception { ThreadUtils.runOnUiThreadBlocking(() -> { ChromeSigninController.get().setSignedInAccountName(mOriginalSignedInAccountName); - // Clear ProfileSyncService in case it was mocked. - ProfileSyncService.resetForTests(); }); }
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/payments/PaymentRequestBillingAddressTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/payments/PaymentRequestBillingAddressTest.java index f092a5d..34f864a 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/payments/PaymentRequestBillingAddressTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/payments/PaymentRequestBillingAddressTest.java
@@ -22,7 +22,6 @@ import org.chromium.base.test.util.CommandLineFlags; import org.chromium.base.test.util.Feature; import org.chromium.chrome.R; -import org.chromium.chrome.browser.ChromeFeatureList; import org.chromium.chrome.browser.ChromeSwitches; import org.chromium.chrome.browser.autofill.AutofillTestHelper; import org.chromium.chrome.browser.autofill.CardType; @@ -324,17 +323,10 @@ mPaymentRequestTestRule.setSpinnerSelectionsInCardEditorAndWait( new int[] {DECEMBER, NEXT_YEAR, ADD_BILLING_ADDRESS}, mPaymentRequestTestRule.getReadyToEdit()); - if (ChromeFeatureList.isEnabled(ChromeFeatureList.AUTOFILL_ENABLE_COMPANY_NAME)) { - mPaymentRequestTestRule.setTextInEditorAndWait( - new String[] {"Seb Doe", "Google", "340 Main St", "Los Angeles", "CA", "90291", - "650-253-0000"}, - mPaymentRequestTestRule.getEditorTextUpdate()); - } else { - mPaymentRequestTestRule.setTextInEditorAndWait( - new String[] { - "Seb Doe", "340 Main St", "Los Angeles", "CA", "90291", "650-253-0000"}, - mPaymentRequestTestRule.getEditorTextUpdate()); - } + mPaymentRequestTestRule.setTextInEditorAndWait( + new String[] {"Seb Doe", "Google", "340 Main St", "Los Angeles", "CA", "90291", + "650-253-0000"}, + mPaymentRequestTestRule.getEditorTextUpdate()); mPaymentRequestTestRule.clickInEditorAndWait( R.id.editor_dialog_done_button, mPaymentRequestTestRule.getReadyToEdit()); @@ -383,17 +375,10 @@ R.id.payments_section, mPaymentRequestTestRule.getReadyForInput()); mPaymentRequestTestRule.clickInShippingAddressAndWait( R.id.payments_add_option_button, mPaymentRequestTestRule.getReadyToEdit()); - if (ChromeFeatureList.isEnabled(ChromeFeatureList.AUTOFILL_ENABLE_COMPANY_NAME)) { - mPaymentRequestTestRule.setTextInEditorAndWait( - new String[] {"Seb Doe", "Google", "340 Main St", "Los Angeles", "CA", "90291", - "650-253-0000"}, - mPaymentRequestTestRule.getEditorTextUpdate()); - } else { - mPaymentRequestTestRule.setTextInEditorAndWait( - new String[] { - "Seb Doe", "340 Main St", "Los Angeles", "CA", "90291", "650-253-0000"}, - mPaymentRequestTestRule.getEditorTextUpdate()); - } + mPaymentRequestTestRule.setTextInEditorAndWait( + new String[] {"Seb Doe", "Google", "340 Main St", "Los Angeles", "CA", "90291", + "650-253-0000"}, + mPaymentRequestTestRule.getEditorTextUpdate()); mPaymentRequestTestRule.clickInEditorAndWait( R.id.editor_dialog_done_button, mPaymentRequestTestRule.getReadyToPay()); @@ -448,17 +433,10 @@ // recipient name brings up the address editor. mPaymentRequestTestRule.setSpinnerSelectionsInCardEditorAndWait( new int[] {DECEMBER, NEXT_YEAR, 5}, mPaymentRequestTestRule.getReadyToEdit()); - if (ChromeFeatureList.isEnabled(ChromeFeatureList.AUTOFILL_ENABLE_COMPANY_NAME)) { - mPaymentRequestTestRule.setTextInEditorAndWait( - new String[] {"Lisa Doh", "Google", "340 Main St", "Los Angeles", "CA", "90291", - "650-253-0000"}, - mPaymentRequestTestRule.getEditorTextUpdate()); - } else { - mPaymentRequestTestRule.setTextInEditorAndWait( - new String[] {"Lisa Doh", "340 Main St", "Los Angeles", "CA", "90291", - "650-253-0000"}, - mPaymentRequestTestRule.getEditorTextUpdate()); - } + mPaymentRequestTestRule.setTextInEditorAndWait( + new String[] {"Lisa Doh", "Google", "340 Main St", "Los Angeles", "CA", "90291", + "650-253-0000"}, + mPaymentRequestTestRule.getEditorTextUpdate()); mPaymentRequestTestRule.clickInEditorAndWait( R.id.editor_dialog_done_button, mPaymentRequestTestRule.getReadyToEdit());
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/payments/PaymentRequestBillingAddressWithoutPhoneTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/payments/PaymentRequestBillingAddressWithoutPhoneTest.java index aff552c..276cb20 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/payments/PaymentRequestBillingAddressWithoutPhoneTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/payments/PaymentRequestBillingAddressWithoutPhoneTest.java
@@ -19,7 +19,6 @@ import org.chromium.base.test.util.CommandLineFlags; import org.chromium.base.test.util.Feature; import org.chromium.chrome.R; -import org.chromium.chrome.browser.ChromeFeatureList; import org.chromium.chrome.browser.ChromeSwitches; import org.chromium.chrome.browser.autofill.AutofillTestHelper; import org.chromium.chrome.browser.autofill.CardType; @@ -156,16 +155,9 @@ mPaymentRequestTestRule.setSpinnerSelectionsInCardEditorAndWait( new int[] {DECEMBER, NEXT_YEAR, ADD_BILLING_ADDRESS}, mPaymentRequestTestRule.getReadyToEdit()); - if (ChromeFeatureList.isEnabled(ChromeFeatureList.AUTOFILL_ENABLE_COMPANY_NAME)) { - mPaymentRequestTestRule.setTextInEditorAndWait( - new String[] { - "Seb Doe", "Google", "340 Main St", "Los Angeles", "CA", "90291", ""}, - mPaymentRequestTestRule.getEditorTextUpdate()); - } else { - mPaymentRequestTestRule.setTextInEditorAndWait( - new String[] {"Seb Doe", "340 Main St", "Los Angeles", "CA", "90291", ""}, - mPaymentRequestTestRule.getEditorTextUpdate()); - } + mPaymentRequestTestRule.setTextInEditorAndWait( + new String[] {"Seb Doe", "Google", "340 Main St", "Los Angeles", "CA", "90291", ""}, + mPaymentRequestTestRule.getEditorTextUpdate()); // Trying to add the address without a phone number should fail. mPaymentRequestTestRule.clickInEditorAndWait( R.id.editor_dialog_done_button, mPaymentRequestTestRule.getEditorValidationError());
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/payments/PaymentRequestEmailAndFreeShippingTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/payments/PaymentRequestEmailAndFreeShippingTest.java index 1b5c6bf5..4bd164e 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/payments/PaymentRequestEmailAndFreeShippingTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/payments/PaymentRequestEmailAndFreeShippingTest.java
@@ -16,7 +16,6 @@ import org.chromium.base.test.util.CommandLineFlags; import org.chromium.base.test.util.Feature; import org.chromium.chrome.R; -import org.chromium.chrome.browser.ChromeFeatureList; import org.chromium.chrome.browser.ChromeSwitches; import org.chromium.chrome.browser.autofill.AutofillTestHelper; import org.chromium.chrome.browser.autofill.CardType; @@ -112,17 +111,10 @@ R.id.payments_section, mPaymentRequestTestRule.getReadyForInput()); mPaymentRequestTestRule.clickInShippingAddressAndWait( R.id.payments_add_option_button, mPaymentRequestTestRule.getReadyToEdit()); - if (ChromeFeatureList.isEnabled(ChromeFeatureList.AUTOFILL_ENABLE_COMPANY_NAME)) { - mPaymentRequestTestRule.setTextInEditorAndWait( - new String[] {"Bob", "Google", "1600 Amphitheatre Pkwy", "Mountain View", "CA", - "94043", "650-253-0000"}, - mPaymentRequestTestRule.getEditorTextUpdate()); - } else { - mPaymentRequestTestRule.setTextInEditorAndWait( - new String[] {"Bob", "1600 Amphitheatre Pkwy", "Mountain View", "CA", "94043", - "650-253-0000"}, - mPaymentRequestTestRule.getEditorTextUpdate()); - } + mPaymentRequestTestRule.setTextInEditorAndWait( + new String[] {"Bob", "Google", "1600 Amphitheatre Pkwy", "Mountain View", "CA", + "94043", "650-253-0000"}, + mPaymentRequestTestRule.getEditorTextUpdate()); mPaymentRequestTestRule.clickInEditorAndWait( R.id.editor_dialog_done_button, mPaymentRequestTestRule.getReadyForInput()); mPaymentRequestTestRule.clickAndWait(
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/payments/PaymentRequestFreeShippingTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/payments/PaymentRequestFreeShippingTest.java index 3fe3bdd6..017e5c029 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/payments/PaymentRequestFreeShippingTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/payments/PaymentRequestFreeShippingTest.java
@@ -18,7 +18,6 @@ import org.chromium.base.test.util.Feature; import org.chromium.base.test.util.FlakyTest; import org.chromium.chrome.R; -import org.chromium.chrome.browser.ChromeFeatureList; import org.chromium.chrome.browser.ChromeSwitches; import org.chromium.chrome.browser.autofill.AutofillTestHelper; import org.chromium.chrome.browser.autofill.CardType; @@ -115,17 +114,10 @@ R.id.payments_section, mPaymentRequestTestRule.getReadyForInput()); mPaymentRequestTestRule.clickInShippingAddressAndWait( R.id.payments_add_option_button, mPaymentRequestTestRule.getReadyToEdit()); - if (ChromeFeatureList.isEnabled(ChromeFeatureList.AUTOFILL_ENABLE_COMPANY_NAME)) { - mPaymentRequestTestRule.setTextInEditorAndWait( - new String[] {"Bob", "Google", "1600 Amphitheatre Pkwy", "Mountain View", "CA", - "94043", "650-253-0000"}, - mPaymentRequestTestRule.getEditorTextUpdate()); - } else { - mPaymentRequestTestRule.setTextInEditorAndWait( - new String[] {"Bob", "1600 Amphitheatre Pkwy", "Mountain View", "CA", "94043", - "650-253-0000"}, - mPaymentRequestTestRule.getEditorTextUpdate()); - } + mPaymentRequestTestRule.setTextInEditorAndWait( + new String[] {"Bob", "Google", "1600 Amphitheatre Pkwy", "Mountain View", "CA", + "94043", "650-253-0000"}, + mPaymentRequestTestRule.getEditorTextUpdate()); mPaymentRequestTestRule.clickInEditorAndWait( R.id.editor_dialog_done_button, mPaymentRequestTestRule.getReadyToPay()); mPaymentRequestTestRule.clickAndWait( @@ -151,16 +143,10 @@ R.id.payments_add_option_button, mPaymentRequestTestRule.getReadyToEdit()); mPaymentRequestTestRule.setSpinnerSelectionInEditorAndWait( 0 /* Afghanistan */, mPaymentRequestTestRule.getReadyToEdit()); - if (ChromeFeatureList.isEnabled(ChromeFeatureList.AUTOFILL_ENABLE_COMPANY_NAME)) { - mPaymentRequestTestRule.setTextInEditorAndWait( - new String[] {"Alice", "Supreme Court", "Airport Road", "Kabul", "1043", - "020-253-0000"}, - mPaymentRequestTestRule.getEditorTextUpdate()); - } else { - mPaymentRequestTestRule.setTextInEditorAndWait( - new String[] {"Alice", "Airport Road", "Kabul", "1043", "020-253-0000"}, - mPaymentRequestTestRule.getEditorTextUpdate()); - } + mPaymentRequestTestRule.setTextInEditorAndWait( + new String[] { + "Alice", "Supreme Court", "Airport Road", "Kabul", "1043", "020-253-0000"}, + mPaymentRequestTestRule.getEditorTextUpdate()); mPaymentRequestTestRule.clickInEditorAndWait( R.id.editor_dialog_done_button, mPaymentRequestTestRule.getReadyToPay()); mPaymentRequestTestRule.clickAndWait( @@ -169,13 +155,8 @@ R.id.card_unmask_input, "123", mPaymentRequestTestRule.getReadyToUnmask()); mPaymentRequestTestRule.clickCardUnmaskButtonAndWait( ModalDialogProperties.ButtonType.POSITIVE, mPaymentRequestTestRule.getDismissed()); - if (ChromeFeatureList.isEnabled(ChromeFeatureList.AUTOFILL_ENABLE_COMPANY_NAME)) { - mPaymentRequestTestRule.expectResultContains(new String[] { - "Alice", "Supreme Court", "Airport Road", "Kabul", "1043", "+93202530000"}); - } else { - mPaymentRequestTestRule.expectResultContains( - new String[] {"Alice", "Airport Road", "Kabul", "1043", "+93202530000"}); - } + mPaymentRequestTestRule.expectResultContains(new String[] { + "Alice", "Supreme Court", "Airport Road", "Kabul", "1043", "+93202530000"}); } /** Quickly pressing on "add address" and then [X] should not crash. */
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/payments/PaymentRequestIncompleteContactDetailsAndFreeShippingTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/payments/PaymentRequestIncompleteContactDetailsAndFreeShippingTest.java index 357796d..8f3d8a0 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/payments/PaymentRequestIncompleteContactDetailsAndFreeShippingTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/payments/PaymentRequestIncompleteContactDetailsAndFreeShippingTest.java
@@ -18,7 +18,6 @@ import org.chromium.base.test.util.CommandLineFlags; import org.chromium.base.test.util.Feature; import org.chromium.chrome.R; -import org.chromium.chrome.browser.ChromeFeatureList; import org.chromium.chrome.browser.ChromeSwitches; import org.chromium.chrome.browser.autofill.AutofillTestHelper; import org.chromium.chrome.browser.autofill.PersonalDataManager.AutofillProfile; @@ -76,17 +75,10 @@ "Phone number required")); mPaymentRequestTestRule.clickInShippingAddressAndWait( R.id.payments_first_radio_button, mPaymentRequestTestRule.getReadyToEdit()); - if (ChromeFeatureList.isEnabled(ChromeFeatureList.AUTOFILL_ENABLE_COMPANY_NAME)) { - mPaymentRequestTestRule.setTextInEditorAndWait( - new String[] {"Jon Doe", "Google", "340 Main St", "Los Angeles", "CA", "90291", - "650-253-0000"}, - mPaymentRequestTestRule.getEditorTextUpdate()); - } else { - mPaymentRequestTestRule.setTextInEditorAndWait( - new String[] { - "Jon Doe", "340 Main St", "Los Angeles", "CA", "90291", "650-253-0000"}, - mPaymentRequestTestRule.getEditorTextUpdate()); - } + mPaymentRequestTestRule.setTextInEditorAndWait( + new String[] {"Jon Doe", "Google", "340 Main St", "Los Angeles", "CA", "90291", + "650-253-0000"}, + mPaymentRequestTestRule.getEditorTextUpdate()); // The contact is now complete, but not selected. mPaymentRequestTestRule.clickInEditorAndWait( R.id.editor_dialog_done_button, mPaymentRequestTestRule.getReadyForInput()); @@ -121,17 +113,10 @@ // Add a new Shipping Address and see that the contact section updates. mPaymentRequestTestRule.clickInShippingAddressAndWait( R.id.payments_add_option_button, mPaymentRequestTestRule.getReadyToEdit()); - if (ChromeFeatureList.isEnabled(ChromeFeatureList.AUTOFILL_ENABLE_COMPANY_NAME)) { - mPaymentRequestTestRule.setTextInEditorAndWait( - new String[] {"Jane Doe", "Edge Corp.", "111 Wall St.", "New York", "NY", - "10110", "650-253-0000"}, - mPaymentRequestTestRule.getEditorTextUpdate()); - } else { - mPaymentRequestTestRule.setTextInEditorAndWait( - new String[] { - "Jane Doe", "111 Wall St.", "New York", "NY", "10110", "650-253-0000"}, - mPaymentRequestTestRule.getEditorTextUpdate()); - } + mPaymentRequestTestRule.setTextInEditorAndWait( + new String[] {"Jane Doe", "Edge Corp.", "111 Wall St.", "New York", "NY", "10110", + "650-253-0000"}, + mPaymentRequestTestRule.getEditorTextUpdate()); mPaymentRequestTestRule.clickInEditorAndWait( R.id.editor_dialog_done_button, mPaymentRequestTestRule.getReadyForInput()); Assert.assertEquals("Jon Doe\njon.doe@google.com\nPhone number required",
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/payments/PaymentRequestJourneyLoggerTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/payments/PaymentRequestJourneyLoggerTest.java index 921545ab..6e19c5dd 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/payments/PaymentRequestJourneyLoggerTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/payments/PaymentRequestJourneyLoggerTest.java
@@ -25,7 +25,6 @@ import org.chromium.base.test.util.Feature; import org.chromium.base.test.util.RetryOnFailure; import org.chromium.chrome.R; -import org.chromium.chrome.browser.ChromeFeatureList; import org.chromium.chrome.browser.ChromeSwitches; import org.chromium.chrome.browser.autofill.AutofillTestHelper; import org.chromium.chrome.browser.autofill.CardType; @@ -213,16 +212,10 @@ R.id.payments_add_option_button, mPaymentRequestTestRule.getReadyToEdit()); mPaymentRequestTestRule.setSpinnerSelectionInEditorAndWait( 0 /* Afghanistan */, mPaymentRequestTestRule.getReadyToEdit()); - if (ChromeFeatureList.isEnabled(ChromeFeatureList.AUTOFILL_ENABLE_COMPANY_NAME)) { - mPaymentRequestTestRule.setTextInEditorAndWait( - new String[] {"Alice", "Supreme Court", "Airport Road", "Kabul", "1043", - "020-253-0000"}, - mPaymentRequestTestRule.getEditorTextUpdate()); - } else { - mPaymentRequestTestRule.setTextInEditorAndWait( - new String[] {"Alice", "Airport Road", "Kabul", "1043", "020-253-0000"}, - mPaymentRequestTestRule.getEditorTextUpdate()); - } + mPaymentRequestTestRule.setTextInEditorAndWait( + new String[] { + "Alice", "Supreme Court", "Airport Road", "Kabul", "1043", "020-253-0000"}, + mPaymentRequestTestRule.getEditorTextUpdate()); mPaymentRequestTestRule.clickInEditorAndWait( R.id.editor_dialog_done_button, mPaymentRequestTestRule.getReadyToPay());
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/payments/PaymentRequestNoShippingTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/payments/PaymentRequestNoShippingTest.java index a7b0c55..950f59e 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/payments/PaymentRequestNoShippingTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/payments/PaymentRequestNoShippingTest.java
@@ -23,7 +23,6 @@ import org.chromium.base.test.util.Feature; import org.chromium.base.test.util.MinAndroidSdkLevel; import org.chromium.chrome.R; -import org.chromium.chrome.browser.ChromeFeatureList; import org.chromium.chrome.browser.ChromeSwitches; import org.chromium.chrome.browser.autofill.AutofillTestHelper; import org.chromium.chrome.browser.autofill.CardType; @@ -253,17 +252,10 @@ mPaymentRequestTestRule.setSpinnerSelectionsInCardEditorAndWait( new int[] {DECEMBER, NEXT_YEAR, addBillingAddress}, mPaymentRequestTestRule.getReadyToEdit()); - if (ChromeFeatureList.isEnabled(ChromeFeatureList.AUTOFILL_ENABLE_COMPANY_NAME)) { - mPaymentRequestTestRule.setTextInEditorAndWait( - new String[] {"Bob", "Google", "1600 Amphitheatre Pkwy", "Mountain View", "CA", - "94043", "650-253-0000"}, - mPaymentRequestTestRule.getEditorTextUpdate()); - } else { - mPaymentRequestTestRule.setTextInEditorAndWait( - new String[] {"Bob", "1600 Amphitheatre Pkwy", "Mountain View", "CA", "94043", - "650-253-0000"}, - mPaymentRequestTestRule.getEditorTextUpdate()); - } + mPaymentRequestTestRule.setTextInEditorAndWait( + new String[] {"Bob", "Google", "1600 Amphitheatre Pkwy", "Mountain View", "CA", + "94043", "650-253-0000"}, + mPaymentRequestTestRule.getEditorTextUpdate()); mPaymentRequestTestRule.clickInEditorAndWait( R.id.editor_dialog_done_button, mPaymentRequestTestRule.getReadyToEdit()); @@ -275,15 +267,9 @@ R.id.card_unmask_input, "123", mPaymentRequestTestRule.getReadyToUnmask()); mPaymentRequestTestRule.clickCardUnmaskButtonAndWait( ModalDialogProperties.ButtonType.POSITIVE, mPaymentRequestTestRule.getDismissed()); - if (ChromeFeatureList.isEnabled(ChromeFeatureList.AUTOFILL_ENABLE_COMPANY_NAME)) { - mPaymentRequestTestRule.expectResultContains(new String[] {"5454545454545454", "12", - "Bob", "Google", "1600 Amphitheatre Pkwy", "Mountain View", "CA", "94043", - "+16502530000"}); - } else { - mPaymentRequestTestRule.expectResultContains( - new String[] {"5454545454545454", "12", "Bob", "1600 Amphitheatre Pkwy", - "Mountain View", "CA", "94043", "+16502530000"}); - } + mPaymentRequestTestRule.expectResultContains( + new String[] {"5454545454545454", "12", "Bob", "Google", "1600 Amphitheatre Pkwy", + "Mountain View", "CA", "94043", "+16502530000"}); } /** Quickly pressing on "add card" and then [X] should not crash. */
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/payments/PaymentRequestShippingAddressAndOptionTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/payments/PaymentRequestShippingAddressAndOptionTest.java index 9e5c3aa..0db5f35 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/payments/PaymentRequestShippingAddressAndOptionTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/payments/PaymentRequestShippingAddressAndOptionTest.java
@@ -156,17 +156,10 @@ R.id.payments_add_option_button, mPaymentRequestTestRule.getReadyToEdit()); Boolean is_company_name_enabled = ChromeFeatureList.isEnabled(ChromeFeatureList.AUTOFILL_ENABLE_COMPANY_NAME); - if (is_company_name_enabled) { - mPaymentRequestTestRule.setTextInEditorAndWait( - new String[] {"Seb Doe", "Google", "340 Main St", "Los Angeles", "CA", "90291", - "650-253-0000"}, - mPaymentRequestTestRule.getEditorTextUpdate()); - } else { - mPaymentRequestTestRule.setTextInEditorAndWait( - new String[] { - "Seb Doe", "340 Main St", "Los Angeles", "CA", "90291", "650-253-0000"}, - mPaymentRequestTestRule.getEditorTextUpdate()); - } + mPaymentRequestTestRule.setTextInEditorAndWait( + new String[] {"Seb Doe", "Google", "340 Main St", "Los Angeles", "CA", "90291", + "650-253-0000"}, + mPaymentRequestTestRule.getEditorTextUpdate()); mPaymentRequestTestRule.clickInEditorAndWait( R.id.editor_dialog_done_button, mPaymentRequestTestRule.getReadyToPay()); @@ -174,10 +167,7 @@ Assert.assertEquals(mPaymentRequestTestRule.getShippingAddressOptionRowAtIndex(0) .getLabelText() .toString(), - is_company_name_enabled ? "Seb Doe\nGoogle, 340 Main St, Los Angeles, CA 90291\n" - + "+1 650-253-0000" - : "Seb Doe\n340 Main St, Los Angeles, CA 90291\n" - + "+1 650-253-0000"); + "Seb Doe\nGoogle, 340 Main St, Los Angeles, CA 90291\n+1 650-253-0000"); } /**
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/photo_picker/PhotoPickerDialogTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/photo_picker/PhotoPickerDialogTest.java index 76f8377..10fe82d 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/photo_picker/PhotoPickerDialogTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/photo_picker/PhotoPickerDialogTest.java
@@ -6,6 +6,7 @@ import static org.chromium.base.test.util.ScalableTimeout.scaleTimeout; +import android.net.Uri; import android.os.Build; import android.support.test.filters.LargeTest; import android.support.v7.widget.RecyclerView; @@ -14,6 +15,7 @@ import org.junit.Assert; import org.junit.Before; +import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; @@ -68,7 +70,7 @@ // The final set of photos picked by the dialog. Can be an empty array, if // nothing was selected. - private String[] mLastSelectedPhotos; + private Uri[] mLastSelectedPhotos; // The list of currently selected photos (built piecemeal). private List<PickerBitmap> mCurrentPhotoSelection; @@ -86,12 +88,12 @@ public void setUp() throws Exception { mActivityTestRule.startMainActivityOnBlankPage(); mTestFiles = new ArrayList<>(); - mTestFiles.add(new PickerBitmap("a", 5L, PickerBitmap.TileTypes.PICTURE)); - mTestFiles.add(new PickerBitmap("b", 4L, PickerBitmap.TileTypes.PICTURE)); - mTestFiles.add(new PickerBitmap("c", 3L, PickerBitmap.TileTypes.PICTURE)); - mTestFiles.add(new PickerBitmap("d", 2L, PickerBitmap.TileTypes.PICTURE)); - mTestFiles.add(new PickerBitmap("e", 1L, PickerBitmap.TileTypes.PICTURE)); - mTestFiles.add(new PickerBitmap("f", 0L, PickerBitmap.TileTypes.PICTURE)); + mTestFiles.add(new PickerBitmap(Uri.parse("a"), 5L, PickerBitmap.TileTypes.PICTURE)); + mTestFiles.add(new PickerBitmap(Uri.parse("b"), 4L, PickerBitmap.TileTypes.PICTURE)); + mTestFiles.add(new PickerBitmap(Uri.parse("c"), 3L, PickerBitmap.TileTypes.PICTURE)); + mTestFiles.add(new PickerBitmap(Uri.parse("d"), 2L, PickerBitmap.TileTypes.PICTURE)); + mTestFiles.add(new PickerBitmap(Uri.parse("e"), 1L, PickerBitmap.TileTypes.PICTURE)); + mTestFiles.add(new PickerBitmap(Uri.parse("f"), 0L, PickerBitmap.TileTypes.PICTURE)); PickerCategoryView.setTestFiles(mTestFiles); DecoderServiceHost.setReadyCallback(this); @@ -100,7 +102,7 @@ // PhotoPickerDialog.PhotoPickerListener: @Override - public void onPhotoPickerUserAction(@PhotoPickerAction int action, String[] photos) { + public void onPhotoPickerUserAction(@PhotoPickerAction int action, Uri[] photos) { mLastActionRecorded = action; mLastSelectedPhotos = photos != null ? photos.clone() : null; if (mLastSelectedPhotos != null) Arrays.sort(mLastSelectedPhotos); @@ -219,6 +221,7 @@ @Test @DisableIf.Build(sdk_is_less_than = Build.VERSION_CODES.LOLLIPOP, message = "crbug.com/761060") + @Ignore("crbug/941488") @LargeTest public void testSingleSelectionPhoto() throws Throwable { createDialog(false, Arrays.asList("image/*")); // Multi-select = false. @@ -233,13 +236,14 @@ Assert.assertEquals(1, mLastSelectedPhotos.length); Assert.assertEquals(PhotoPickerAction.PHOTOS_SELECTED, mLastActionRecorded); - Assert.assertEquals(mTestFiles.get(1).getFilePath(), mLastSelectedPhotos[0]); + Assert.assertEquals(mTestFiles.get(1).getUri().getPath(), mLastSelectedPhotos[0].getPath()); dismissDialog(); } @Test @DisableIf.Build(sdk_is_less_than = Build.VERSION_CODES.LOLLIPOP, message = "crbug.com/761060") + @Ignore("crbug/941488") @LargeTest public void testMultiSelectionPhoto() throws Throwable { createDialog(true, Arrays.asList("image/*")); // Multi-select = true. @@ -255,9 +259,9 @@ Assert.assertEquals(3, mLastSelectedPhotos.length); Assert.assertEquals(PhotoPickerAction.PHOTOS_SELECTED, mLastActionRecorded); - Assert.assertEquals(mTestFiles.get(0).getFilePath(), mLastSelectedPhotos[0]); - Assert.assertEquals(mTestFiles.get(2).getFilePath(), mLastSelectedPhotos[1]); - Assert.assertEquals(mTestFiles.get(4).getFilePath(), mLastSelectedPhotos[2]); + Assert.assertEquals(mTestFiles.get(0).getUri().getPath(), mLastSelectedPhotos[0].getPath()); + Assert.assertEquals(mTestFiles.get(2).getUri().getPath(), mLastSelectedPhotos[1].getPath()); + Assert.assertEquals(mTestFiles.get(4).getUri().getPath(), mLastSelectedPhotos[2].getPath()); dismissDialog(); }
diff --git a/chrome/android/junit/src/org/chromium/chrome/browser/contextual_suggestions/GoogleSearchRestrictionTest.java b/chrome/android/junit/src/org/chromium/chrome/browser/contextual_suggestions/GoogleSearchRestrictionTest.java index 6c820ac..667cbc5 100644 --- a/chrome/android/junit/src/org/chromium/chrome/browser/contextual_suggestions/GoogleSearchRestrictionTest.java +++ b/chrome/android/junit/src/org/chromium/chrome/browser/contextual_suggestions/GoogleSearchRestrictionTest.java
@@ -176,7 +176,7 @@ */ private NavigationController createOneEntryNavController(int pageTransition) { NavigationEntry entry = new NavigationEntry( - 1, FOO_URL, FOO_URL, FOO_URL, "Foo", null, null, pageTransition); + 1, FOO_URL, FOO_URL, FOO_URL, "Foo", null, null, pageTransition, 0); NavigationHistory navHistory = new NavigationHistory(); navHistory.addEntry(entry); @@ -196,14 +196,14 @@ NavigationEntry firstEntry; if (fromSRP) { firstEntry = new NavigationEntry(0, GOOGLE_SEARCH_URL, GOOGLE_SEARCH_URL, - GOOGLE_SEARCH_URL, "foo - Google Search", null, null, PageTransition.TYPED); + GOOGLE_SEARCH_URL, "foo - Google Search", null, null, PageTransition.TYPED, 0); } else { firstEntry = new NavigationEntry( - 0, BAR_URL, BAR_URL, BAR_URL, "bar", null, null, PageTransition.LINK); + 0, BAR_URL, BAR_URL, BAR_URL, "bar", null, null, PageTransition.LINK, 0); } NavigationEntry currentEntry = new NavigationEntry( - 1, FOO_URL, FOO_URL, FOO_URL, "Foo", null, null, pageTransition); + 1, FOO_URL, FOO_URL, FOO_URL, "Foo", null, null, pageTransition, 0); NavigationHistory navHistory = new NavigationHistory(); navHistory.addEntry(firstEntry); @@ -226,24 +226,24 @@ private NavigationController createLongNavHistory( int previousPageTransition, int currentPageTransition, boolean fromSRP) { NavigationEntry firstEntry = new NavigationEntry( - 0, BAZ_URL, BAZ_URL, BAZ_URL, "baz", null, null, PageTransition.LINK); + 0, BAZ_URL, BAZ_URL, BAZ_URL, "baz", null, null, PageTransition.LINK, 0); NavigationEntry secondEntry; if (fromSRP) { secondEntry = new NavigationEntry(1, GOOGLE_SEARCH_URL, GOOGLE_SEARCH_URL, - GOOGLE_SEARCH_URL, "foo - Google Search", null, null, PageTransition.LINK); + GOOGLE_SEARCH_URL, "foo - Google Search", null, null, PageTransition.LINK, 0); } else { secondEntry = new NavigationEntry( - 1, BAR_URL, BAR_URL, BAR_URL, "bar", null, null, PageTransition.LINK); + 1, BAR_URL, BAR_URL, BAR_URL, "bar", null, null, PageTransition.LINK, 0); } NavigationEntry thirdEntry = new NavigationEntry( - 2, FOO_URL, FOO_URL, FOO_URL, "Foo", null, null, previousPageTransition); + 2, FOO_URL, FOO_URL, FOO_URL, "Foo", null, null, previousPageTransition, 0); NavigationEntry fourthEntry = new NavigationEntry(3, QUX_URL, QUX_URL, QUX_URL, "qux", null, - null, currentPageTransition | PageTransition.FORWARD_BACK); + null, currentPageTransition | PageTransition.FORWARD_BACK, 0); NavigationEntry fifthEntry = new NavigationEntry( - 4, QUUX_URL, QUUX_URL, QUUX_URL, "quux", null, null, PageTransition.TYPED); + 4, QUUX_URL, QUUX_URL, QUUX_URL, "quux", null, null, PageTransition.TYPED, 0); NavigationHistory navHistory = new NavigationHistory(); navHistory.addEntry(firstEntry);
diff --git a/chrome/android/junit/src/org/chromium/chrome/browser/customtabs/CloseButtonNavigatorTest.java b/chrome/android/junit/src/org/chromium/chrome/browser/customtabs/CloseButtonNavigatorTest.java index feb6ebc6..8329563 100644 --- a/chrome/android/junit/src/org/chromium/chrome/browser/customtabs/CloseButtonNavigatorTest.java +++ b/chrome/android/junit/src/org/chromium/chrome/browser/customtabs/CloseButtonNavigatorTest.java
@@ -40,7 +40,7 @@ private void addSitesToHistory(String... urls) { for (String url : urls) { - mNavigationHistory.addEntry(new NavigationEntry(0, url, "", "", "", "", null, 0)); + mNavigationHistory.addEntry(new NavigationEntry(0, url, "", "", "", "", null, 0, 0)); } // Point to the most recent entry in history.
diff --git a/chrome/android/junit/src/org/chromium/chrome/browser/send_tab_to_self/SendTabToSelfAndroidBridgeTest.java b/chrome/android/junit/src/org/chromium/chrome/browser/send_tab_to_self/SendTabToSelfAndroidBridgeTest.java index 2a9d36c..4c1ac4bc 100644 --- a/chrome/android/junit/src/org/chromium/chrome/browser/send_tab_to_self/SendTabToSelfAndroidBridgeTest.java +++ b/chrome/android/junit/src/org/chromium/chrome/browser/send_tab_to_self/SendTabToSelfAndroidBridgeTest.java
@@ -57,8 +57,8 @@ @Test @SmallTest public void testAddEntry() { - SendTabToSelfAndroidBridge.addEntry(mProfile, URL, TITLE); - verify(mNativeMock).addEntry(eq(mProfile), eq(URL), eq(TITLE)); + SendTabToSelfAndroidBridge.addEntry(mProfile, URL, TITLE, NAVIGATION_TIME_MS); + verify(mNativeMock).addEntry(eq(mProfile), eq(URL), eq(TITLE), eq(NAVIGATION_TIME_MS)); } @Test
diff --git a/chrome/android/touchless/java/src/org/chromium/chrome/browser/touchless/TouchlessNewTabPage.java b/chrome/android/touchless/java/src/org/chromium/chrome/browser/touchless/TouchlessNewTabPage.java index 922a82a..f0cd880 100644 --- a/chrome/android/touchless/java/src/org/chromium/chrome/browser/touchless/TouchlessNewTabPage.java +++ b/chrome/android/touchless/java/src/org/chromium/chrome/browser/touchless/TouchlessNewTabPage.java
@@ -133,6 +133,7 @@ model, mRecyclerView, ContentSuggestionsViewBinder::bind); newTabPageAdapter.refreshSuggestions(); + eventReporter.onSurfaceOpened(); // Set after the Mediator is constructed so that it has time to refresh the suggestions // before requesting a layout.
diff --git a/chrome/app/nibs/BUILD.gn b/chrome/app/nibs/BUILD.gn deleted file mode 100644 index 87629b2..0000000 --- a/chrome/app/nibs/BUILD.gn +++ /dev/null
@@ -1,35 +0,0 @@ -# Copyright 2016 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -import("//build/config/mac/rules.gni") -import("//ui/base/ui_features.gni") - -assert(is_mac) - -translated_xibs = [ "TaskManager.xib" ] - -mac_xib_bundle_data("chrome_xibs") { - sources = translated_xibs -} - -action("localizer_table") { - script = "generate_localizer.py" - - sources = translated_xibs - table_path = "$target_gen_dir/localizer_table.h" - outputs = [ - table_path, - ] - args = [ - "--output_path", - rebase_path(table_path, root_build_dir), - ] - if (!use_system_xcode) { - args += [ - "--developer_dir", - hermetic_xcode_path, - ] - } - args += rebase_path(translated_xibs, root_build_dir) -}
diff --git a/chrome/app/nibs/OWNERS b/chrome/app/nibs/OWNERS deleted file mode 100644 index f40e0c9..0000000 --- a/chrome/app/nibs/OWNERS +++ /dev/null
@@ -1 +0,0 @@ -file://chrome/browser/ui/cocoa/OWNERS
diff --git a/chrome/app/nibs/PRESUBMIT.py b/chrome/app/nibs/PRESUBMIT.py deleted file mode 100644 index 9c25730..0000000 --- a/chrome/app/nibs/PRESUBMIT.py +++ /dev/null
@@ -1,93 +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. - -"""Presubmit script to verify that XIB changes are done with the right version. - -See http://dev.chromium.org/developers/design-documents/mac-xib-files for more -information. -""" - -import re - -# Minimum is Mac OS X 10.9.5 (13F34). -HUMAN_DARWIN_VERSION = '10.9.5' -ALLOWED_DARWIN_VERSION = 13 # Darwin 13 = 10.9. -MINIMUM_DARWIN_RELEASE = 'F' # Release F = 10.9.5. - -MINIMUM_IB_VERSION = 5053 # Xcode 5.1. -MAXIMUM_IB_VERSION = 5056 # Xcode 5.1.1. -HUMAN_IB_VERSION = '>= 5.1, <= 5.1.1' - -SYSTEM_VERSION_RE = r'<document .* systemVersion="([0-9]{,2})([A-Z])([0-9]+)"' - -IB_VERSION_RE = \ - r'<plugIn identifier="com\.apple\.InterfaceBuilder\.CocoaPlugin" ' + \ - 'version="([0-9]+)"/>' - -def _CheckXIBSystemAndXcodeVersions(input_api, output_api, error_type): - affected_xibs = [x for x in input_api.AffectedFiles() - if x.LocalPath().endswith('.xib')] - - incorrect_system_versions = [] - incorrect_ib_versions = [] - - for xib in affected_xibs: - if len(xib.NewContents()) == 0: - continue - - system_version = None - ib_version = None - - new_contents = xib.NewContents() - if not new_contents: - # Deleting files is always fine. - continue - - for line in new_contents: - m = re.search(SYSTEM_VERSION_RE, line) - if m: - system_version = (m.group(1), m.group(2), m.group(3)) - - m = re.search(IB_VERSION_RE, line) - if m: - ib_version = m.group(1) - - if system_version is not None and ib_version is not None: - break - - if system_version is None: - incorrect_system_versions.append(xib.LocalPath()) - continue - if int(system_version[0]) != ALLOWED_DARWIN_VERSION: - incorrect_system_versions.append(xib.LocalPath()) - continue - if system_version[1] < MINIMUM_DARWIN_RELEASE: - incorrect_system_versions.append(xib.LocalPath()) - continue - - if ib_version is None or int(ib_version) < MINIMUM_IB_VERSION or \ - int(ib_version) > MAXIMUM_IB_VERSION: - incorrect_ib_versions.append(xib.LocalPath()) - continue - - problems = [] - if incorrect_system_versions: - problems.append(error_type( - 'XIB files need to be saved on Mac OS X ' + HUMAN_DARWIN_VERSION, - items=incorrect_system_versions)) - if incorrect_ib_versions: - problems.append(error_type( - 'XIB files need to be saved using Xcode version ' + HUMAN_IB_VERSION, - items=incorrect_ib_versions)) - return problems - -def CheckChangeOnUpload(input_api, output_api): - # Allow uploads to happen even if the presubmit fails, so that contributors - # can ask their reviewer or another person to re-save the XIBs for them. - return _CheckXIBSystemAndXcodeVersions(input_api, output_api, - error_type=output_api.PresubmitPromptWarning) - -def CheckChangeOnCommit(input_api, output_api): - return _CheckXIBSystemAndXcodeVersions(input_api, output_api, - error_type=output_api.PresubmitError)
diff --git a/chrome/app/nibs/TaskManager.xib b/chrome/app/nibs/TaskManager.xib deleted file mode 100644 index 49b4d6e..0000000 --- a/chrome/app/nibs/TaskManager.xib +++ /dev/null
@@ -1,108 +0,0 @@ -<?xml version="1.0" encoding="UTF-8" standalone="no"?> -<document type="com.apple.InterfaceBuilder3.Cocoa.XIB" version="3.0" toolsVersion="5056" systemVersion="13F1603" targetRuntime="MacOSX.Cocoa" propertyAccessControl="none"> - <dependencies> - <deployment version="1090" identifier="macosx"/> - <development version="5100" identifier="xcode"/> - <plugIn identifier="com.apple.InterfaceBuilder.CocoaPlugin" version="5056"/> - </dependencies> - <objects> - <customObject id="-2" userLabel="File's Owner" customClass="TaskManagerWindowController"> - <connections> - <outlet property="endProcessButton_" destination="12" id="31"/> - <outlet property="tableView_" destination="6" id="22"/> - <outlet property="window" destination="1" id="16"/> - </connections> - </customObject> - <customObject id="-1" userLabel="First Responder" customClass="FirstResponder"/> - <customObject id="-3" userLabel="Application"/> - <window title="^IDS_TASK_MANAGER_TITLE" allowsToolTipsWhenApplicationIsInactive="NO" autorecalculatesKeyViewLoop="NO" oneShot="NO" visibleAtLaunch="NO" animationBehavior="default" id="1"> - <windowStyleMask key="styleMask" titled="YES" closable="YES" miniaturizable="YES" resizable="YES"/> - <windowPositionMask key="initialPositionMask" leftStrut="YES" bottomStrut="YES"/> - <rect key="contentRect" x="196" y="240" width="480" height="270"/> - <rect key="screenRect" x="0.0" y="0.0" width="1680" height="1028"/> - <value key="minSize" type="size" width="300" height="200"/> - <view key="contentView" id="2"> - <rect key="frame" x="0.0" y="0.0" width="480" height="270"/> - <autoresizingMask key="autoresizingMask"/> - <subviews> - <scrollView focusRingType="none" horizontalLineScroll="18" horizontalPageScroll="10" verticalLineScroll="18" verticalPageScroll="10" usesPredominantAxisScrolling="NO" id="3"> - <rect key="frame" x="20" y="60" width="440" height="190"/> - <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/> - <clipView key="contentView" id="1k3-HS-xr3"> - <rect key="frame" x="1" y="17" width="438" height="172"/> - <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/> - <subviews> - <tableView focusRingType="none" verticalHuggingPriority="750" allowsExpansionToolTips="YES" alternatingRowBackgroundColors="YES" columnReordering="NO" autosaveColumns="NO" rowHeight="16" headerView="7" id="6"> - <rect key="frame" x="0.0" y="0.0" width="438" height="172"/> - <autoresizingMask key="autoresizingMask"/> - <size key="intercellSpacing" width="3" height="2"/> - <color key="backgroundColor" white="1" alpha="1" colorSpace="calibratedWhite"/> - <color key="gridColor" name="gridColor" catalog="System" colorSpace="catalog"/> - <tableColumns> - <tableColumn width="435" minWidth="40" maxWidth="1000" id="8"> - <tableHeaderCell key="headerCell" lineBreakMode="truncatingTail" borderStyle="border" alignment="left"> - <font key="font" metaFont="smallSystem"/> - <color key="textColor" name="headerTextColor" catalog="System" colorSpace="catalog"/> - <color key="backgroundColor" white="0.33333299" alpha="1" colorSpace="calibratedWhite"/> - </tableHeaderCell> - <textFieldCell key="dataCell" lineBreakMode="truncatingTail" selectable="YES" editable="YES" alignment="left" title="Text Cell" id="11"> - <font key="font" metaFont="system"/> - <color key="textColor" name="controlTextColor" catalog="System" colorSpace="catalog"/> - <color key="backgroundColor" name="controlBackgroundColor" catalog="System" colorSpace="catalog"/> - </textFieldCell> - <tableColumnResizingMask key="resizingMask" resizeWithTable="YES" userResizable="YES"/> - </tableColumn> - </tableColumns> - <connections> - <outlet property="dataSource" destination="-2" id="23"/> - <outlet property="delegate" destination="-2" id="33"/> - </connections> - </tableView> - </subviews> - <color key="backgroundColor" name="controlBackgroundColor" catalog="System" colorSpace="catalog"/> - </clipView> - <scroller key="horizontalScroller" verticalHuggingPriority="750" controlSize="small" horizontal="YES" id="5"> - <rect key="frame" x="1" y="175" width="438" height="14"/> - <autoresizingMask key="autoresizingMask"/> - </scroller> - <scroller key="verticalScroller" verticalHuggingPriority="750" doubleValue="1" controlSize="small" horizontal="NO" id="4"> - <rect key="frame" x="425" y="17" width="14" height="172"/> - <autoresizingMask key="autoresizingMask"/> - </scroller> - <tableHeaderView key="headerView" id="7"> - <rect key="frame" x="0.0" y="0.0" width="438" height="17"/> - <autoresizingMask key="autoresizingMask"/> - </tableHeaderView> - </scrollView> - <customView id="18" customClass="GTMWidthBasedTweaker"> - <rect key="frame" x="356" y="0.0" width="124" height="60"/> - <autoresizingMask key="autoresizingMask" flexibleMinX="YES" flexibleMaxY="YES"/> - <subviews> - <button verticalHuggingPriority="750" id="12"> - <rect key="frame" x="14" y="12" width="96" height="32"/> - <autoresizingMask key="autoresizingMask" flexibleMinX="YES" flexibleMaxY="YES"/> - <buttonCell key="cell" type="push" title="^IDS_TASK_MANAGER_KILL" bezelStyle="rounded" alignment="center" enabled="NO" borderStyle="border" imageScaling="proportionallyDown" inset="2" id="13"> - <behavior key="behavior" pushIn="YES" lightByBackground="YES" lightByGray="YES"/> - <font key="font" metaFont="system"/> - </buttonCell> - <connections> - <action selector="killSelectedProcesses:" target="-2" id="32"/> - </connections> - </button> - </subviews> - </customView> - </subviews> - </view> - <connections> - <outlet property="delegate" destination="-2" id="34"/> - </connections> - </window> - <customObject id="17" customClass="ChromeUILocalizer"/> - <customObject id="19" customClass="GTMUILocalizerAndLayoutTweaker"> - <connections> - <outlet property="localizer_" destination="17" id="20"/> - <outlet property="uiObject_" destination="1" id="21"/> - </connections> - </customObject> - </objects> -</document>
diff --git a/chrome/app/nibs/generate_localizer.py b/chrome/app/nibs/generate_localizer.py deleted file mode 100755 index 6892968..0000000 --- a/chrome/app/nibs/generate_localizer.py +++ /dev/null
@@ -1,151 +0,0 @@ -#!/usr/bin/env python - -# Copyright (c) 2009 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. - -# Usage: generate_localizer [xib_path] [output_dot_h_path] [output_dot_mm_path] -# -# Extracts all the localizable strings that start with "^IDS" from the given -# xib file, and then generates a localizer to process those strings. - - -import argparse -import logging -import os -import plistlib -import subprocess -import sys - -generate_localizer = "me" - -localizer_template_h = \ -'''// ---------- WARNING ---------- -// THIS IS A GENERATED FILE, DO NOT EDIT IT DIRECTLY! -// -// This header includes the table used by ui_localizer.mm. Nothing else should -// be including this file. -// -// Generated by %(generate_localizer)s. -// Generated from: -// %(xib_files)s -// - -#ifndef CHROME_APP_NIBS_LOCALIZER_TABLE_H_ -#define CHROME_APP_NIBS_LOCALIZER_TABLE_H_ - -static const UILocalizerResourceMap kUIResources[] = { -%(resource_map_list)s }; -static const size_t kUIResourcesSize = base::size(kUIResources); - -#endif // CHROME_APP_NIBS_LOCALIZER_TABLE_H_ -''' - -def xib_localizable_strings(xib_path, xcode_path): - """Runs ibtool to extract the localizable strings data from the xib.""" - # Take SDKROOT out of the environment passed to ibtool. ibtool itself has - # no need for it, but when ibtool runs via xcrun and Xcode isn't aware of - # the SDK in use, its presence causes an error. - ibtool_env = os.environ.copy() - if 'SDKROOT' in os.environ: - del ibtool_env['SDKROOT'] - if xcode_path: - ibtool_env['DEVELOPER_DIR'] = xcode_path - - command = ['xcrun', 'ibtool', '--localizable-strings', xib_path] - ibtool_cmd = subprocess.Popen(command, - stdout=subprocess.PIPE, stderr=subprocess.PIPE, - env=ibtool_env) - (cmd_out, cmd_err) = ibtool_cmd.communicate() - if ibtool_cmd.returncode: - sys.stderr.write('%s:0: error: ibtool on "%s" failed (%d):\n%s\n' % - (generate_localizer, xib_path, ibtool_cmd.returncode, - cmd_err)) - return None - return cmd_out - -def extract_resource_constants(plist_localizable_strings_dict, xib_path): - """Extracts all the values that start with ^IDS from the localizable - strings plist entry.""" - constants_list = [] - for item_dict in plist_localizable_strings_dict.itervalues(): - for item_value in item_dict.itervalues(): - if item_value.startswith('^IDS'): - constants_list.append(item_value) - elif item_value.startswith('IDS'): - sys.stderr.write( - '%s:0: warning: %s found a string with questionable prefix, "%s"\n' - % (xib_path, generate_localizer, item_value)); - return constants_list - -def generate_file_contents(constants_list, xib_paths): - """Generates the header listing the constants.""" - # Bounce through a set to uniq the strings, sort the list, then build the - # values we need from it. - constants_list = sorted(set(constants_list)) - constant_list_str = '' - for item in constants_list: - parts = item.split('$', 1) - label_id = parts[0] - if len(parts) == 2: - label_arg_id = parts[1] - else: - label_arg_id = '0' - constant_list_str += ' { "%s", %s, %s },\n' % \ - ( item, label_id[1:], label_arg_id) - # Assemble the contents from the templates. - values_dict = { - 'resource_map_list': constant_list_str, - 'generate_localizer': generate_localizer, - 'xib_files': "\n// ".join(xib_paths), - } - h_file = localizer_template_h % values_dict - return h_file - - -def Main(argv=None): - global generate_localizer - generate_localizer = os.path.basename(argv[0]) - - parser = argparse.ArgumentParser( - description='Generates a header file that localizes libs.') - parser.add_argument('--output_path', required=True, - help='Path to output header file.') - parser.add_argument('--developer_dir', required=False, - help='Path to Xcode.') - parser.add_argument('xibs', nargs='+', - help='A list of xibs to localize') - args = parser.parse_args() - - output_path = args.output_path - xib_paths = args.xibs - - full_constants_list = [] - for xib_path in xib_paths: - # Run ibtool and convert to something Python can deal with - plist_string = xib_localizable_strings(xib_path, args.developer_dir) - if not plist_string: - return 2 - plist = plistlib.readPlistFromString(plist_string) - - # Extract the resource constant strings - localizable_strings = plist['com.apple.ibtool.document.localizable-strings'] - constants_list = extract_resource_constants(localizable_strings, xib_path) - if not constants_list: - sys.stderr.write("%s:0: warning: %s didn't find any resource strings\n" % - (xib_path, generate_localizer)); - full_constants_list.extend(constants_list) - - # Generate our file contents - h_file_content = \ - generate_file_contents(full_constants_list, xib_paths) - - # Write out the file - file_fd = open(output_path, 'w') - file_fd.write(h_file_content) - file_fd.close() - - return 0 - -if __name__ == '__main__': - sys.exit(Main(sys.argv))
diff --git a/chrome/browser/BUILD.gn b/chrome/browser/BUILD.gn index 96bd3dc..395095c 100644 --- a/chrome/browser/BUILD.gn +++ b/chrome/browser/BUILD.gn
@@ -1543,8 +1543,6 @@ "signin/profile_oauth2_token_service_factory.h", "signin/signin_error_controller_factory.cc", "signin/signin_error_controller_factory.h", - "signin/signin_manager_factory.cc", - "signin/signin_manager_factory.h", "signin/signin_profile_attributes_updater.cc", "signin/signin_profile_attributes_updater.h", "signin/signin_profile_attributes_updater_factory.cc", @@ -2935,9 +2933,13 @@ "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.cc", + "memory/memory_pressure_monitor.h", "memory/memory_pressure_monitor_utils.cc", "memory/memory_pressure_monitor_utils.h", "memory/memory_pressure_monitor_utils_impl.h", + "memory/memory_pressure_monitor_win.cc", + "memory/memory_pressure_monitor_win.h", "memory/oom_memory_details.cc", "memory/oom_memory_details.h", "memory/swap_thrashing_monitor.cc", @@ -5186,8 +5188,6 @@ "ssl/ssl_client_auth_requestor_mock.h", "subresource_filter/test_ruleset_publisher.cc", "subresource_filter/test_ruleset_publisher.h", - "sync/profile_sync_test_util.cc", - "sync/profile_sync_test_util.h", ] configs += [ "//build/config:precompiled_headers" ]
diff --git a/chrome/browser/about_flags.cc b/chrome/browser/about_flags.cc index 9d982c93..57c3d9e 100644 --- a/chrome/browser/about_flags.cc +++ b/chrome/browser/about_flags.cc
@@ -45,6 +45,7 @@ #include "components/assist_ranker/predictor_config_definitions.h" #include "components/autofill/core/browser/autofill_experiments.h" #include "components/autofill/core/common/autofill_features.h" +#include "components/autofill/core/common/autofill_payments_features.h" #include "components/autofill/core/common/autofill_switches.h" #include "components/autofill/core/common/autofill_util.h" #include "components/autofill_assistant/browser/features.h" @@ -1265,10 +1266,6 @@ kOsAura, FEATURE_VALUE_TYPE(features::kOverlayScrollbarFlashWhenMouseEnter)}, #endif // USE_AURA - { // See http://crbug.com/120416 for how to remove this flag. - "save-page-as-mhtml", flag_descriptions::kSavePageAsMhtmlName, - flag_descriptions::kSavePageAsMhtmlDescription, kOsMac | kOsWin | kOsLinux, - SINGLE_VALUE_TYPE(switches::kSavePageAsMHTML)}, {"enable-quic", flag_descriptions::kQuicName, flag_descriptions::kQuicDescription, kOsAll, ENABLE_DISABLE_VALUE_TYPE(switches::kEnableQuic, switches::kDisableQuic)}, @@ -4102,6 +4099,14 @@ FEATURE_VALUE_TYPE(app_list_features::kEnableEmbeddedAssistantUI)}, #endif // OS_CHROMEOS + {"autofill-enable-local-card-migration-for-non-sync-user", + flag_descriptions::kAutofillEnableLocalCardMigrationForNonSyncUserName, + flag_descriptions:: + kAutofillEnableLocalCardMigrationForNonSyncUserDescription, + kOsDesktop, + FEATURE_VALUE_TYPE( + autofill::features::kAutofillEnableLocalCardMigrationForNonSyncUser)}, + // NOTE: Adding a new flag requires adding a corresponding entry to enum // "LoginCustomFlags" in tools/metrics/histograms/enums.xml. See "Flag // Histograms" in tools/metrics/histograms/README.md (run the
diff --git a/chrome/browser/accessibility/image_annotation_browsertest.cc b/chrome/browser/accessibility/image_annotation_browsertest.cc index 1ecbb1bf..7efa8be 100644 --- a/chrome/browser/accessibility/image_annotation_browsertest.cc +++ b/chrome/browser/accessibility/image_annotation_browsertest.cc
@@ -75,15 +75,23 @@ image_annotation::mojom::ImageProcessorPtr image_processor, AnnotateImageCallback callback) override { // Use the filename to create an annotation string. + // Adds some trailing whitespace and punctuation to check that clean-up + // happens correctly when combining annotation strings. std::string image_filename = GURL(image_id).ExtractFileName(); image_annotation::mojom::AnnotationPtr ocr_annotation = image_annotation::mojom::Annotation::New( image_annotation::mojom::AnnotationType::kOcr, 1.0, - image_filename + " Annotation"); + image_filename + " Annotation . "); + + image_annotation::mojom::AnnotationPtr label_annotation = + image_annotation::mojom::Annotation::New( + image_annotation::mojom::AnnotationType::kLabel, 1.0, + image_filename + " Label"); // Return that result as an annotation. std::vector<image_annotation::mojom::AnnotationPtr> annotations; annotations.push_back(std::move(ocr_annotation)); + annotations.push_back(std::move(label_annotation)); image_annotation::mojom::AnnotateImageResultPtr result = image_annotation::mojom::AnnotateImageResult::NewAnnotations( @@ -189,7 +197,8 @@ browser()->tab_strip_model()->GetActiveWebContents(); content::WaitForAccessibilityTreeToContainNodeWithName( - web_contents, "Appears to say: red.png Annotation"); + web_contents, + "Appears to say: red.png Annotation. Appears to be: red.png Label"); } // http://crbug.com/940043
diff --git a/chrome/browser/android/download/download_manager_service.cc b/chrome/browser/android/download/download_manager_service.cc index b766290..2b7f626 100644 --- a/chrome/browser/android/download/download_manager_service.cc +++ b/chrome/browser/android/download/download_manager_service.cc
@@ -281,6 +281,9 @@ void DownloadManagerService::OpenDownload(download::DownloadItem* download, int source) { + if (java_ref_.is_null()) + return; + JNIEnv* env = base::android::AttachCurrentThread(); ScopedJavaLocalRef<jobject> j_item = JNI_DownloadManagerService_CreateJavaDownloadItem(env, download);
diff --git a/chrome/browser/android/download/download_utils.cc b/chrome/browser/android/download/download_utils.cc index 05d7ac8..2a6a450 100644 --- a/chrome/browser/android/download/download_utils.cc +++ b/chrome/browser/android/download/download_utils.cc
@@ -15,10 +15,12 @@ #include "components/download/public/common/download_utils.h" #include "components/offline_items_collection/core/offline_content_aggregator.h" #include "content/public/browser/browser_context.h" +#include "content/public/browser/download_item_utils.h" #include "jni/DownloadUtils_jni.h" #include "ui/base/l10n/l10n_util.h" using base::android::ConvertUTF16ToJavaString; +using base::android::ConvertUTF8ToJavaString; using base::android::JavaParamRef; using base::android::ScopedJavaLocalRef; using OfflineContentAggregator = @@ -61,10 +63,8 @@ const base::FilePath& file_path) { JNIEnv* env = base::android::AttachCurrentThread(); auto uri_jstring = Java_DownloadUtils_getUriStringForPath( - env, - base::android::ConvertUTF8ToJavaString(env, file_path.AsUTF8Unsafe())); - return base::FilePath( - base::android::ConvertJavaStringToUTF8(env, uri_jstring)); + env, ConvertUTF8ToJavaString(env, file_path.AsUTF8Unsafe())); + return base::FilePath(ConvertJavaStringToUTF8(env, uri_jstring)); } // static @@ -79,6 +79,26 @@ } // static +void DownloadUtils::OpenDownload(download::DownloadItem* item, + int open_source) { + JNIEnv* env = base::android::AttachCurrentThread(); + content::BrowserContext* browser_context = + content::DownloadItemUtils::GetBrowserContext(item); + bool is_off_the_record = + browser_context ? browser_context->IsOffTheRecord() : false; + std::string original_url = item->GetOriginalUrl().SchemeIs(url::kDataScheme) + ? std::string() + : item->GetOriginalUrl().spec(); + + Java_DownloadUtils_openDownload( + env, ConvertUTF8ToJavaString(env, item->GetTargetFilePath().value()), + ConvertUTF8ToJavaString(env, item->GetMimeType()), + ConvertUTF8ToJavaString(env, item->GetGuid()), is_off_the_record, + ConvertUTF8ToJavaString(env, original_url), + ConvertUTF8ToJavaString(env, item->GetReferrerUrl().spec()), open_source); +} + +// static DownloadOfflineContentProvider* DownloadUtils::GetDownloadOfflineContentProvider( content::BrowserContext* browser_context) {
diff --git a/chrome/browser/android/download/download_utils.h b/chrome/browser/android/download/download_utils.h index 4b5f964..72536c3 100644 --- a/chrome/browser/android/download/download_utils.h +++ b/chrome/browser/android/download/download_utils.h
@@ -11,6 +11,10 @@ class BrowserContext; } +namespace download { +class DownloadItem; +} + class DownloadOfflineContentProvider; // Native side of DownloadUtils.java. @@ -18,6 +22,7 @@ public: static base::FilePath GetUriStringForPath(const base::FilePath& file_path); static int GetAutoResumptionSizeLimit(); + static void OpenDownload(download::DownloadItem* item, int open_source); static DownloadOfflineContentProvider* GetDownloadOfflineContentProvider( content::BrowserContext* browser_context); };
diff --git a/chrome/browser/android/preferences/autofill/OWNERS b/chrome/browser/android/preferences/autofill/OWNERS new file mode 100644 index 0000000..c4d2e224 --- /dev/null +++ b/chrome/browser/android/preferences/autofill/OWNERS
@@ -0,0 +1 @@ +file://components/autofill/OWNERS \ No newline at end of file
diff --git a/chrome/browser/android/preferences/autofill/autofill_profile_bridge.cc b/chrome/browser/android/preferences/autofill/autofill_profile_bridge.cc index 415747e..91fe6316 100644 --- a/chrome/browser/android/preferences/autofill/autofill_profile_bridge.cc +++ b/chrome/browser/android/preferences/autofill/autofill_profile_bridge.cc
@@ -9,7 +9,6 @@ #include "base/strings/utf_string_conversions.h" #include "chrome/browser/browser_process.h" #include "components/autofill/core/browser/autofill_country.h" -#include "components/autofill/core/common/autofill_features.h" #include "jni/AutofillProfileBridge_jni.h" #include "third_party/libaddressinput/src/cpp/include/libaddressinput/address_field.h" #include "third_party/libaddressinput/src/cpp/include/libaddressinput/address_metadata.h" @@ -117,10 +116,6 @@ country_code, localization, language_code, &best_language_tag); for (const auto& ui_component : ui_components) { - if (ui_component.field == AddressField::ORGANIZATION && - !base::FeatureList::IsEnabled(features::kAutofillEnableCompanyName)) { - continue; - } component_labels.push_back(ui_component.name); component_required.push_back( IsFieldRequired(ui_component.field, country_code)); @@ -141,4 +136,4 @@ return ConvertUTF8ToJavaString(env, best_language_tag); } -} // namespace autofill +} // namespace autofill
diff --git a/chrome/browser/android/send_tab_to_self/send_tab_to_self_android_bridge.cc b/chrome/browser/android/send_tab_to_self/send_tab_to_self_android_bridge.cc index f2ddb44..0868551b 100644 --- a/chrome/browser/android/send_tab_to_self/send_tab_to_self_android_bridge.cc +++ b/chrome/browser/android/send_tab_to_self/send_tab_to_self_android_bridge.cc
@@ -84,12 +84,14 @@ JNIEnv* env, const JavaParamRef<jobject>& j_profile, const JavaParamRef<jstring>& j_url, - const JavaParamRef<jstring>& j_title) { + const JavaParamRef<jstring>& j_title, + jlong j_navigation_time) { const std::string url = ConvertJavaStringToUTF8(env, j_url); const std::string title = ConvertJavaStringToUTF8(env, j_title); + base::Time navigation_time = base::Time::FromJavaTime(j_navigation_time); const SendTabToSelfEntry* persisted_entry = - GetModel(j_profile)->AddEntry(GURL(url), title); + GetModel(j_profile)->AddEntry(GURL(url), title, navigation_time); if (persisted_entry == nullptr) { return nullptr;
diff --git a/chrome/browser/android/usage_stats/usage_stats_database.cc b/chrome/browser/android/usage_stats/usage_stats_database.cc index 8f099679..7c267899 100644 --- a/chrome/browser/android/usage_stats/usage_stats_database.cc +++ b/chrome/browser/android/usage_stats/usage_stats_database.cc
@@ -62,7 +62,6 @@ InitializeDBs(); } -// Used for testing. UsageStatsDatabase::UsageStatsDatabase( std::unique_ptr<ProtoDatabase<WebsiteEvent>> website_event_db, std::unique_ptr<ProtoDatabase<Suspension>> suspension_db,
diff --git a/chrome/browser/android/usage_stats/usage_stats_database.h b/chrome/browser/android/usage_stats/usage_stats_database.h index 264914e..80f81864 100644 --- a/chrome/browser/android/usage_stats/usage_stats_database.h +++ b/chrome/browser/android/usage_stats/usage_stats_database.h
@@ -48,12 +48,6 @@ // Initializes the database with user |profile|. explicit UsageStatsDatabase(Profile* profile); - // Initializes the database with a |ProtoDatabase|. Useful for testing. - explicit UsageStatsDatabase( - std::unique_ptr<ProtoDatabase<WebsiteEvent>> website_event_db, - std::unique_ptr<ProtoDatabase<Suspension>> suspension_db, - std::unique_ptr<ProtoDatabase<TokenMapping>> token_mapping_db); - ~UsageStatsDatabase(); void GetAllEvents(EventsCallback callback); @@ -87,6 +81,13 @@ // |mappings|. The map's key is the token, and its value is the FQDN. void SetTokenMappings(TokenMap mappings, StatusCallback callback); + protected: + // For testing only. + UsageStatsDatabase( + std::unique_ptr<ProtoDatabase<WebsiteEvent>> website_event_db, + std::unique_ptr<ProtoDatabase<Suspension>> suspension_db, + std::unique_ptr<ProtoDatabase<TokenMapping>> token_mapping_db); + private: void InitializeDBs();
diff --git a/chrome/browser/android/usage_stats/usage_stats_database_unittest.cc b/chrome/browser/android/usage_stats/usage_stats_database_unittest.cc index 5fd03e0..911de546 100644 --- a/chrome/browser/android/usage_stats/usage_stats_database_unittest.cc +++ b/chrome/browser/android/usage_stats/usage_stats_database_unittest.cc
@@ -45,6 +45,17 @@ } // namespace +class MockUsageStatsDatabase : public UsageStatsDatabase { + public: + MockUsageStatsDatabase( + std::unique_ptr<ProtoDatabase<WebsiteEvent>> website_event_db, + std::unique_ptr<ProtoDatabase<Suspension>> suspension_db, + std::unique_ptr<ProtoDatabase<TokenMapping>> token_mapping_db) + : UsageStatsDatabase(std::move(website_event_db), + std::move(suspension_db), + std::move(token_mapping_db)) {} +}; + class UsageStatsDatabaseTest : public testing::Test { public: UsageStatsDatabaseTest() { @@ -60,7 +71,7 @@ suspension_db_unowned_ = fake_suspension_db.get(); token_mapping_db_unowned_ = fake_token_mapping_db.get(); - usage_stats_database_ = std::make_unique<UsageStatsDatabase>( + usage_stats_database_ = std::make_unique<MockUsageStatsDatabase>( std::move(fake_website_event_db), std::move(fake_suspension_db), std::move(fake_token_mapping_db)); }
diff --git a/chrome/browser/browsing_data/chrome_browsing_data_remover_delegate.cc b/chrome/browser/browsing_data/chrome_browsing_data_remover_delegate.cc index 341ecdd..96933255 100644 --- a/chrome/browser/browsing_data/chrome_browsing_data_remover_delegate.cc +++ b/chrome/browser/browsing_data/chrome_browsing_data_remover_delegate.cc
@@ -65,6 +65,7 @@ #include "components/autofill/core/browser/personal_data_manager.h" #include "components/autofill/core/browser/webdata/autofill_webdata_service.h" #include "components/autofill/core/common/autofill_features.h" +#include "components/autofill/core/common/autofill_payments_features.h" #include "components/bookmarks/browser/bookmark_model.h" #include "components/content_settings/core/browser/content_settings_registry.h" #include "components/content_settings/core/browser/host_content_settings_map.h" @@ -127,8 +128,8 @@ #if defined(OS_CHROMEOS) #include "chrome/browser/chromeos/profiles/profile_helper.h" #include "chromeos/cryptohome/cryptohome_parameters.h" -#include "chromeos/dbus/attestation_constants.h" -#include "chromeos/dbus/cryptohome_client.h" +#include "chromeos/dbus/constants/attestation_constants.h" +#include "chromeos/dbus/cryptohome/cryptohome_client.h" #include "chromeos/dbus/dbus_thread_manager.h" #include "components/user_manager/user.h" #endif // defined(OS_CHROMEOS)
diff --git a/chrome/browser/browsing_data/chrome_browsing_data_remover_delegate_unittest.cc b/chrome/browser/browsing_data/chrome_browsing_data_remover_delegate_unittest.cc index d8458a8d..aebbdd1a 100644 --- a/chrome/browser/browsing_data/chrome_browsing_data_remover_delegate_unittest.cc +++ b/chrome/browser/browsing_data/chrome_browsing_data_remover_delegate_unittest.cc
@@ -114,8 +114,8 @@ #if defined(OS_CHROMEOS) #include "chrome/browser/chromeos/login/users/mock_user_manager.h" +#include "chromeos/dbus/cryptohome/fake_cryptohome_client.h" #include "chromeos/dbus/dbus_thread_manager.h" -#include "chromeos/dbus/fake_cryptohome_client.h" #include "components/account_id/account_id.h" #include "components/user_manager/scoped_user_manager.h" #endif // defined(OS_CHROMEOS)
diff --git a/chrome/browser/chrome_content_browser_client.cc b/chrome/browser/chrome_content_browser_client.cc index cc016c9..0e0148e4 100644 --- a/chrome/browser/chrome_content_browser_client.cc +++ b/chrome/browser/chrome_content_browser_client.cc
@@ -120,7 +120,6 @@ #include "chrome/browser/safe_browsing/ui_manager.h" #include "chrome/browser/safe_browsing/url_checker_delegate_impl.h" #include "chrome/browser/search/search.h" -#include "chrome/browser/serial/chrome_serial_delegate.h" #include "chrome/browser/sessions/session_tab_helper.h" #include "chrome/browser/signin/chrome_signin_proxying_url_loader_factory.h" #include "chrome/browser/signin/chrome_signin_url_loader_throttle.h" @@ -452,6 +451,7 @@ #include "chrome/browser/payments/payment_request_factory.h" #include "chrome/browser/search/instant_service.h" #include "chrome/browser/search/instant_service_factory.h" +#include "chrome/browser/serial/chrome_serial_delegate.h" #include "chrome/browser/ui/passwords/google_password_manager_navigation_throttle.h" #include "chrome/browser/ui/search/new_tab_page_navigation_throttle.h" #include "chrome/common/importer/profile_import.mojom.h" @@ -936,14 +936,6 @@ } #endif // BUILDFLAG(ENABLE_EXTENSIONS) -bool GetDataSaverEnabledPref(const PrefService* prefs) { - // Enable data saver only when data saver pref is enabled and not part of - // "Disabled" group of "SaveDataHeader" experiment. - return prefs->GetBoolean(prefs::kDataSaverEnabled) && - base::FieldTrialList::FindFullName("SaveDataHeader") - .compare("Disabled"); -} - WebContents* GetWebContentsFromProcessAndFrameId(int render_process_id, int render_frame_id) { if (render_process_id) { @@ -3177,7 +3169,7 @@ web_prefs->strict_powerful_feature_restrictions = true; } - web_prefs->data_saver_enabled = GetDataSaverEnabledPref(prefs); + web_prefs->data_saver_enabled = IsDataSaverEnabled(profile); web_prefs->data_saver_holdback_web_api_enabled = base::GetFieldTrialParamByFeatureAsBool(features::kDataSaverHoldback,
diff --git a/chrome/browser/chromeos/app_mode/arc/arc_kiosk_app_manager.cc b/chrome/browser/chromeos/app_mode/arc/arc_kiosk_app_manager.cc index 4670cbcd..b38b43e 100644 --- a/chrome/browser/chromeos/app_mode/arc/arc_kiosk_app_manager.cc +++ b/chrome/browser/chromeos/app_mode/arc/arc_kiosk_app_manager.cc
@@ -19,8 +19,8 @@ #include "chromeos/cryptohome/async_method_caller.h" #include "chromeos/cryptohome/cryptohome_parameters.h" #include "chromeos/cryptohome/cryptohome_util.h" +#include "chromeos/dbus/cryptohome/cryptohome_client.h" #include "chromeos/dbus/cryptohome/rpc.pb.h" -#include "chromeos/dbus/cryptohome_client.h" #include "chromeos/dbus/dbus_thread_manager.h" #include "chromeos/settings/cros_settings_names.h" #include "components/arc/arc_util.h"
diff --git a/chrome/browser/chromeos/app_mode/kiosk_profile_loader.cc b/chrome/browser/chromeos/app_mode/kiosk_profile_loader.cc index a2551f2..f52e7f3 100644 --- a/chrome/browser/chromeos/app_mode/kiosk_profile_loader.cc +++ b/chrome/browser/chromeos/app_mode/kiosk_profile_loader.cc
@@ -21,7 +21,7 @@ #include "chrome/browser/chromeos/settings/cros_settings.h" #include "chrome/browser/lifetime/application_lifetime.h" #include "chromeos/cryptohome/async_method_caller.h" -#include "chromeos/dbus/cryptohome_client.h" +#include "chromeos/dbus/cryptohome/cryptohome_client.h" #include "chromeos/dbus/dbus_thread_manager.h" #include "chromeos/login/auth/auth_status_consumer.h" #include "chromeos/login/auth/user_context.h"
diff --git a/chrome/browser/chromeos/apps/apk_web_app_installer.cc b/chrome/browser/chromeos/apps/apk_web_app_installer.cc index 8dff7d0..964de94 100644 --- a/chrome/browser/chromeos/apps/apk_web_app_installer.cc +++ b/chrome/browser/chromeos/apps/apk_web_app_installer.cc
@@ -9,11 +9,12 @@ #include "base/bind.h" #include "base/strings/utf_string_conversions.h" -#include "chrome/browser/extensions/bookmark_app_helper.h" #include "chrome/browser/installable/installable_metrics.h" #include "chrome/browser/profiles/profile.h" +#include "chrome/browser/web_applications/components/install_manager.h" #include "chrome/browser/web_applications/components/web_app_constants.h" #include "chrome/browser/web_applications/extensions/web_app_extension_ids_map.h" +#include "chrome/browser/web_applications/web_app_provider.h" #include "content/public/browser/browser_thread.h" #include "content/public/common/service_manager_connection.h" #include "services/data_decoder/public/cpp/decode_image.h" @@ -62,7 +63,8 @@ const std::vector<uint8_t>& icon_png_data) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); if (!weak_owner_.get()) { - CompleteInstallation(extensions::ExtensionId()); + CompleteInstallation(web_app::AppId(), + web_app::InstallResultCode::kFailedUnknownReason); return; } @@ -70,21 +72,27 @@ // null if there was an error generating the data. if (web_app_info.is_null() || icon_png_data.empty()) { LOG(ERROR) << "Insufficient data to install a web app"; - CompleteInstallation(extensions::ExtensionId()); + CompleteInstallation(web_app::AppId(), + web_app::InstallResultCode::kFailedUnknownReason); return; } - web_app_info_.title = base::UTF8ToUTF16(web_app_info->title); + DCHECK(!web_app_info_); + web_app_info_ = std::make_unique<WebApplicationInfo>(); - web_app_info_.app_url = GURL(web_app_info->start_url); - DCHECK(web_app_info_.app_url.is_valid()); + web_app_info_->title = base::UTF8ToUTF16(web_app_info->title); - web_app_info_.scope = GURL(web_app_info->scope_url); - DCHECK(web_app_info_.scope.is_valid()); + web_app_info_->app_url = GURL(web_app_info->start_url); + DCHECK(web_app_info_->app_url.is_valid()); - if (web_app_info->theme_color != kInvalidColor) - web_app_info_.theme_color = static_cast<SkColor>(web_app_info->theme_color); - web_app_info_.open_as_window = true; + web_app_info_->scope = GURL(web_app_info->scope_url); + DCHECK(web_app_info_->scope.is_valid()); + + if (web_app_info->theme_color != kInvalidColor) { + web_app_info_->theme_color = + static_cast<SkColor>(web_app_info->theme_color); + } + web_app_info_->open_as_window = true; // Set up the connection to the service manager to decode the raw PNG icon // bytes into SkBitmaps. @@ -102,57 +110,67 @@ base::Unretained(this))); } -void ApkWebAppInstaller::CompleteInstallation( - const extensions::ExtensionId& id) { - std::move(callback_).Run(id); +void ApkWebAppInstaller::CompleteInstallation(const web_app::AppId& id, + web_app::InstallResultCode code) { + std::move(callback_).Run(id, code); delete this; } -void ApkWebAppInstaller::OnBookmarkAppCreated( - const extensions::Extension* extension, - const WebApplicationInfo& web_app_info) { - if (weak_owner_.get() && extension) { - // It is assumed that if |weak_owner_| is gone, |profile_| is gone too. The - // extension will be automatically cleaned up by - // extensions::ExtensionSystem. Otherwise, insert this web app into the - // extensions ID map so it is not removed automatically. - // TODO(crbug.com/910008): have a less bad way of doing this. - web_app::ExtensionIdsMap(profile_->GetPrefs()) - .Insert(web_app_info.app_url, extension->id(), - web_app::InstallSource::kArc); +void ApkWebAppInstaller::OnWebAppCreated(const GURL& app_url, + const web_app::AppId& app_id, + web_app::InstallResultCode code) { + // It is assumed that if |weak_owner_| is gone, |profile_| is gone too. The + // web app will be automatically cleaned up by provider. + if (!weak_owner_.get()) { + CompleteInstallation(web_app::AppId(), + web_app::InstallResultCode::kInstallManagerDestroyed); + return; } - CompleteInstallation(extension ? extension->id() : extensions::ExtensionId()); + + if (code != web_app::InstallResultCode::kSuccess) { + CompleteInstallation(app_id, code); + return; + } + + // Otherwise, insert this web app into the extensions ID map so it is not + // removed automatically. TODO(crbug.com/910008): have a less bad way of doing + // this. + web_app::ExtensionIdsMap(profile_->GetPrefs()) + .Insert(app_url, app_id, web_app::InstallSource::kArc); + CompleteInstallation(app_id, code); } void ApkWebAppInstaller::OnImageDecoded(const SkBitmap& decoded_image) { + DCHECK(web_app_info_); + WebApplicationInfo::IconInfo icon_info; icon_info.data = decoded_image; icon_info.width = decoded_image.width(); icon_info.height = decoded_image.height(); - web_app_info_.icons.push_back(icon_info); + web_app_info_->icons.push_back(icon_info); if (!weak_owner_.get()) { // Assume |profile_| is no longer valid - destroy this object and // terminate. - CompleteInstallation(extensions::ExtensionId()); + CompleteInstallation(web_app::AppId(), + web_app::InstallResultCode::kInstallManagerDestroyed); return; } DoInstall(); } void ApkWebAppInstaller::DoInstall() { - DCHECK(!helper_); + auto* provider = web_app::WebAppProvider::Get(profile_); + DCHECK(provider); - helper_ = std::make_unique<extensions::BookmarkAppHelper>( - profile_, web_app_info_, /*web_contents=*/nullptr, - WebappInstallSource::ARC); + GURL app_url = web_app_info_->app_url; - // We should only install windowed apps via this method. - helper_->set_forced_launch_type(extensions::LAUNCH_TYPE_WINDOW); - helper_->set_is_no_network_install(); - helper_->Create(base::BindRepeating(&ApkWebAppInstaller::OnBookmarkAppCreated, - base::Unretained(this))); + provider->install_manager().InstallWebAppFromInfo( + std::move(web_app_info_), /*no_network_install=*/true, + WebappInstallSource::ARC, + base::BindOnce(&ApkWebAppInstaller::OnWebAppCreated, + base::Unretained(this), std::move(app_url))); } } // namespace chromeos
diff --git a/chrome/browser/chromeos/apps/apk_web_app_installer.h b/chrome/browser/chromeos/apps/apk_web_app_installer.h index 2f09716f..5b7835eefd 100644 --- a/chrome/browser/chromeos/apps/apk_web_app_installer.h +++ b/chrome/browser/chromeos/apps/apk_web_app_installer.h
@@ -8,24 +8,24 @@ #include <memory> #include <vector> -#include "base/callback_forward.h" +#include "base/callback.h" #include "base/macros.h" #include "base/memory/weak_ptr.h" +#include "chrome/browser/web_applications/components/web_app_helpers.h" #include "chrome/common/web_application_info.h" #include "components/arc/common/app.mojom.h" -#include "extensions/common/extension_id.h" +class GURL; class Profile; -namespace extensions { -class BookmarkAppHelper; -class Extension; -} // namespace extensions - namespace service_manager { class Connector; } +namespace web_app { +enum class InstallResultCode; +} + namespace chromeos { // Class which takes an arc::mojom::WebAppInfo struct and decodes the data @@ -33,7 +33,8 @@ class ApkWebAppInstaller { public: using InstallFinishCallback = - base::OnceCallback<void(const extensions::ExtensionId& web_app_id)>; + base::OnceCallback<void(const web_app::AppId&, + web_app::InstallResultCode)>; // Do nothing class purely for the purpose of allowing us to specify // a WeakPtr<Owner> member as a proxy for a profile lifetime observer. @@ -63,11 +64,13 @@ const std::vector<uint8_t>& icon_png_data); // Calls |callback_| with |id|, and deletes this object. Virtual for testing. - virtual void CompleteInstallation(const extensions::ExtensionId& id); + virtual void CompleteInstallation(const web_app::AppId& id, + web_app::InstallResultCode code); - // Callback method for BookmarkAppHelper::Create. - void OnBookmarkAppCreated(const extensions::Extension* extension, - const WebApplicationInfo& web_app_info); + // Callback method for installation completed response. + void OnWebAppCreated(const GURL& app_url, + const web_app::AppId& app_id, + web_app::InstallResultCode code); // Callback method for data_decoder::DecodeImage. void OnImageDecoded(const SkBitmap& decoded_image); @@ -75,10 +78,10 @@ // Run the installation. Virtual for testing. virtual void DoInstall(); - const WebApplicationInfo& web_app_info() const { return web_app_info_; } + bool has_web_app_info() const { return web_app_info_ != nullptr; } + const WebApplicationInfo& web_app_info() const { return *web_app_info_; } private: - std::unique_ptr<extensions::BookmarkAppHelper> helper_; std::unique_ptr<service_manager::Connector> connector_; // If |weak_owner_| is ever invalidated while this class is working, @@ -88,7 +91,7 @@ InstallFinishCallback callback_; base::WeakPtr<Owner> weak_owner_; - WebApplicationInfo web_app_info_; + std::unique_ptr<WebApplicationInfo> web_app_info_; DISALLOW_COPY_AND_ASSIGN(ApkWebAppInstaller); };
diff --git a/chrome/browser/chromeos/apps/apk_web_app_installer_unittest.cc b/chrome/browser/chromeos/apps/apk_web_app_installer_unittest.cc index d6079917..630cc16 100644 --- a/chrome/browser/chromeos/apps/apk_web_app_installer_unittest.cc +++ b/chrome/browser/chromeos/apps/apk_web_app_installer_unittest.cc
@@ -11,6 +11,8 @@ #include "base/run_loop.h" #include "base/strings/utf_string_conversions.h" #include "chrome/browser/chromeos/apps/apk_web_app_installer.h" +#include "chrome/browser/web_applications/components/web_app_constants.h" +#include "chrome/browser/web_applications/components/web_app_helpers.h" #include "chrome/test/base/chrome_render_view_host_test_harness.h" #include "chrome/test/base/testing_profile.h" #include "components/arc/test/fake_app_instance.h" @@ -49,17 +51,19 @@ ~FakeApkWebAppInstaller() override = default; + using ApkWebAppInstaller::has_web_app_info; using ApkWebAppInstaller::Start; using ApkWebAppInstaller::web_app_info; - const extensions::ExtensionId& id() const { return id_; } + const web_app::AppId& id() const { return id_; } bool complete_installation_called() const { return complete_installation_called_; } bool do_install_called() const { return do_install_called_; } private: - void CompleteInstallation(const extensions::ExtensionId& id) override { + void CompleteInstallation(const web_app::AppId& id, + web_app::InstallResultCode code) override { id_ = id; complete_installation_called_ = true; std::move(quit_closure_).Run(); @@ -70,7 +74,7 @@ std::move(quit_closure_).Run(); } - extensions::ExtensionId id_; + web_app::AppId id_; bool complete_installation_called_ = false; bool do_install_called_ = false; base::OnceClosure quit_closure_; @@ -86,15 +90,6 @@ ~ApkWebAppInstallerTest() override = default; protected: - void AssertEmptyWebAppInfo(const FakeApkWebAppInstaller& installer) const { - EXPECT_EQ(base::ASCIIToUTF16(""), installer.web_app_info().title); - EXPECT_EQ(GURL(), installer.web_app_info().app_url); - EXPECT_EQ(GURL(), installer.web_app_info().scope); - EXPECT_FALSE(installer.web_app_info().theme_color.has_value()); - - EXPECT_EQ(0u, installer.web_app_info().icons.size()); - } - service_manager::Connector* connector() const { return test_data_decoder_service_.connector(); } @@ -145,7 +140,7 @@ EXPECT_TRUE(apk_web_app_installer.complete_installation_called()); EXPECT_FALSE(apk_web_app_installer.do_install_called()); - AssertEmptyWebAppInfo(apk_web_app_installer); + EXPECT_FALSE(apk_web_app_installer.has_web_app_info()); } TEST_F(ApkWebAppInstallerTest, @@ -176,7 +171,7 @@ EXPECT_TRUE(apk_web_app_installer.complete_installation_called()); EXPECT_FALSE(apk_web_app_installer.do_install_called()); - AssertEmptyWebAppInfo(apk_web_app_installer); + EXPECT_FALSE(apk_web_app_installer.has_web_app_info()); } TEST_F(ApkWebAppInstallerTest, NullIconCallsCompleteInstallation) { @@ -191,7 +186,7 @@ EXPECT_TRUE(apk_web_app_installer.complete_installation_called()); EXPECT_FALSE(apk_web_app_installer.do_install_called()); - AssertEmptyWebAppInfo(apk_web_app_installer); + EXPECT_FALSE(apk_web_app_installer.has_web_app_info()); } } // namespace chromeos
diff --git a/chrome/browser/chromeos/apps/apk_web_app_service.cc b/chrome/browser/chromeos/apps/apk_web_app_service.cc index b754c43d..da79984 100644 --- a/chrome/browser/chromeos/apps/apk_web_app_service.cc +++ b/chrome/browser/chromeos/apps/apk_web_app_service.cc
@@ -84,8 +84,7 @@ arc_app_list_prefs_->AddObserver(this); } -void ApkWebAppService::UninstallWebApp( - const extensions::ExtensionId& web_app_id) { +void ApkWebAppService::UninstallWebApp(const web_app::AppId& web_app_id) { if (!web_app::ExtensionIdsMap::HasExtensionIdWithInstallSource( profile_->GetPrefs(), web_app_id, web_app::InstallSource::kArc)) { // Do not uninstall a web app that was not installed via ApkWebAppInstaller. @@ -234,9 +233,13 @@ weak_ptr_factory_.GetWeakPtr()); } -void ApkWebAppService::OnDidFinishInstall( - const std::string& package_name, - const extensions::ExtensionId& web_app_id) { +void ApkWebAppService::OnDidFinishInstall(const std::string& package_name, + const web_app::AppId& web_app_id, + web_app::InstallResultCode code) { + // Do nothing: any error cancels installation. + if (code != web_app::InstallResultCode::kSuccess) + return; + // Set a pref to map |web_app_id| to |package_name| for future uninstallation. DictionaryPrefUpdate dict_update(profile_->GetPrefs(), kWebAppToApkDictPref); dict_update->SetPath({web_app_id, kPackageNameKey},
diff --git a/chrome/browser/chromeos/apps/apk_web_app_service.h b/chrome/browser/chromeos/apps/apk_web_app_service.h index 35b91e7..da815131 100644 --- a/chrome/browser/chromeos/apps/apk_web_app_service.h +++ b/chrome/browser/chromeos/apps/apk_web_app_service.h
@@ -14,9 +14,9 @@ #include "base/scoped_observer.h" #include "chrome/browser/chromeos/apps/apk_web_app_installer.h" #include "chrome/browser/ui/app_list/arc/arc_app_list_prefs.h" +#include "chrome/browser/web_applications/components/web_app_helpers.h" #include "components/keyed_service/core/keyed_service.h" #include "extensions/browser/extension_registry_observer.h" -#include "extensions/common/extension_id.h" class ArcAppListPrefs; class Profile; @@ -25,6 +25,10 @@ class PrefRegistrySyncable; } // namespace user_prefs +namespace web_app { +enum class InstallResultCode; +} // namespace web_app + namespace chromeos { class ApkWebAppService : public KeyedService, @@ -46,7 +50,7 @@ // Uninstalls a web app with id |web_app_id| iff it was installed via calling // ApkWebAppInstaller::Install(). - void UninstallWebApp(const extensions::ExtensionId& web_app_id); + void UninstallWebApp(const web_app::AppId& web_app_id); // KeyedService: void Shutdown() override; @@ -67,7 +71,8 @@ arc::mojom::WebAppInfoPtr web_app_info, const std::vector<uint8_t>& icon_png_data); void OnDidFinishInstall(const std::string& package_name, - const extensions::ExtensionId& web_app_id); + const web_app::AppId& web_app_id, + web_app::InstallResultCode code); Profile* profile_; ArcAppListPrefs* arc_app_list_prefs_;
diff --git a/chrome/browser/chromeos/arc/arc_migration_guide_notification_unittest.cc b/chrome/browser/chromeos/arc/arc_migration_guide_notification_unittest.cc index 2bea0fa2..38dbdda 100644 --- a/chrome/browser/chromeos/arc/arc_migration_guide_notification_unittest.cc +++ b/chrome/browser/chromeos/arc/arc_migration_guide_notification_unittest.cc
@@ -24,7 +24,7 @@ TestingProfile profile; // Set a high battery state. - chromeos::PowerManagerClient::Initialize(); + chromeos::PowerManagerClient::InitializeFake(); auto* power_manager = chromeos::FakePowerManagerClient::Get(); power_manager::PowerSupplyProperties props = *power_manager->GetLastStatus(); props.set_battery_percent(99);
diff --git a/chrome/browser/chromeos/arc/arc_session_manager_unittest.cc b/chrome/browser/chromeos/arc/arc_session_manager_unittest.cc index 014eeb1..ff741db 100644 --- a/chrome/browser/chromeos/arc/arc_session_manager_unittest.cc +++ b/chrome/browser/chromeos/arc/arc_session_manager_unittest.cc
@@ -181,7 +181,7 @@ chromeos::DBusThreadManager::GetSetterForTesting()->SetSessionManagerClient( std::make_unique<chromeos::FakeSessionManagerClient>()); - chromeos::PowerManagerClient::Initialize(); + chromeos::PowerManagerClient::InitializeFake(); chromeos::UpstartClient::InitializeFake(); SetArcAvailableCommandLineForTesting(
diff --git a/chrome/browser/chromeos/arc/auth/arc_active_directory_enrollment_token_fetcher_browsertest.cc b/chrome/browser/chromeos/arc/auth/arc_active_directory_enrollment_token_fetcher_browsertest.cc index e0e2279..8fd220e 100644 --- a/chrome/browser/chromeos/arc/auth/arc_active_directory_enrollment_token_fetcher_browsertest.cc +++ b/chrome/browser/chromeos/arc/auth/arc_active_directory_enrollment_token_fetcher_browsertest.cc
@@ -20,8 +20,8 @@ #include "chrome/browser/chromeos/profiles/profile_helper.h" #include "chrome/browser/ui/browser.h" #include "chrome/test/base/in_process_browser_test.h" +#include "chromeos/dbus/cryptohome/fake_cryptohome_client.h" #include "chromeos/dbus/dbus_thread_manager.h" -#include "chromeos/dbus/fake_cryptohome_client.h" #include "components/arc/arc_util.h" #include "components/policy/core/common/cloud/device_management_service.h" #include "components/policy/core/common/policy_switches.h"
diff --git a/chrome/browser/chromeos/arc/tracing/arc_tracing_graphics_model.cc b/chrome/browser/chromeos/arc/tracing/arc_tracing_graphics_model.cc index ce26725..fccf4eb 100644 --- a/chrome/browser/chromeos/arc/tracing/arc_tracing_graphics_model.cc +++ b/chrome/browser/chromeos/arc/tracing/arc_tracing_graphics_model.cc
@@ -4,6 +4,8 @@ #include "chrome/browser/chromeos/arc/tracing/arc_tracing_graphics_model.h" +#include <algorithm> + #include "base/json/json_reader.h" #include "base/json/json_writer.h" #include "base/no_destructor.h" @@ -643,16 +645,38 @@ return score; } -// Helper that performs query in |common_model| and returns sorted list of built -// events. -ArcTracingGraphicsModel::BufferEvents GetEventsFromQuery( - const ArcTracingModel& common_model, - const std::string& query) { - ArcTracingGraphicsModel::BufferEvents collector; - for (const ArcTracingEvent* event : common_model.Select(query)) - GetEventMapper().Produce(*event, &collector); - SortBufferEventsByTimestamp(&collector); - return collector; +// Helper that performs query in |common_model| for top level Chrome GPU events +// and returns bands of sorted list of built events. +std::vector<ArcTracingGraphicsModel::BufferEvents> GetChromeTopLevelEvents( + const ArcTracingModel& common_model) { + // There is a chance that Chrome top level events may overlap. This may happen + // in case on non-trivial GPU load. In this case notification about swap or + // presentation done may come after the next frame draw is started. As a + // result, it leads to confusion in case displayed on the same event band. + // Solution is to allocate extra band and interchange events per buffer. + // Events are grouped per frame's id that starts from 0x100000000 and has + // monotonous increment. So we can simple keep it in the tree map that + // provides us the right ordering. + std::map<std::string, std::vector<const ArcTracingEvent*>> per_frame_events; + + for (const ArcTracingEvent* event : + common_model.Select(kChromeTopEventsQuery)) { + per_frame_events[event->GetId()].emplace_back(event); + } + + size_t band_index = 0; + std::vector<ArcTracingGraphicsModel::BufferEvents> chrome_top_level; + chrome_top_level.resize(2); + for (const auto& it_frame : per_frame_events) { + for (const ArcTracingEvent* event : it_frame.second) + GetEventMapper().Produce(*event, &chrome_top_level[band_index]); + band_index = (band_index + 1) % chrome_top_level.size(); + } + + for (auto& chrome_top_level_band : chrome_top_level) + SortBufferEventsByTimestamp(&chrome_top_level_band); + + return chrome_top_level; } // Helper that extracts top level Android events, such as refresh, vsync. @@ -832,7 +856,7 @@ return false; } - chrome_top_level_ = GetEventsFromQuery(common_model, kChromeTopEventsQuery); + chrome_top_level_ = GetChromeTopLevelEvents(common_model); if (chrome_top_level_.empty()) { LOG(ERROR) << "No Chrome top events"; return false; @@ -862,8 +886,10 @@ min = std::min(min, android_top_level_.front().timestamp); max = std::max(max, android_top_level_.back().timestamp); - min = std::min(min, chrome_top_level_.front().timestamp); - max = std::max(max, chrome_top_level_.back().timestamp); + for (const auto& chrome_top_level_band : chrome_top_level_) { + min = std::min(min, chrome_top_level_band.front().timestamp); + max = std::max(max, chrome_top_level_band.back().timestamp); + } duration_ = max - min + 1; @@ -874,8 +900,10 @@ } } - for (auto& event : chrome_top_level_) - event.timestamp -= min; + for (auto& chrome_top_level_band : chrome_top_level_) { + for (auto& event : chrome_top_level_band) + event.timestamp -= min; + } for (auto& event : android_top_level_) event.timestamp -= min; } @@ -921,7 +949,12 @@ root->SetKey(kKeyAndroid, SerializeEvents(android_top_level_)); // Chrome top events - root->SetKey(kKeyChrome, SerializeEvents(chrome_top_level_)); + base::ListValue chrome_top_level_list; + for (const auto& chrome_top_level_band : chrome_top_level_) { + chrome_top_level_list.GetList().emplace_back( + SerializeEvents(chrome_top_level_band)); + } + root->SetKey(kKeyChrome, std::move(chrome_top_level_list)); // Duration. root->SetKey(kKeyDuration, base::Value(static_cast<double>(duration_))); @@ -980,9 +1013,18 @@ if (!LoadEvents(root->FindKey(kKeyAndroid), &android_top_level_)) return false; - if (!LoadEvents(root->FindKey(kKeyChrome), &chrome_top_level_)) + const base::Value* chrome_top_level_list = + root->FindKeyOfType(kKeyChrome, base::Value::Type::LIST); + if (!chrome_top_level_list || chrome_top_level_list->GetList().empty()) return false; + for (const auto& chrome_top_level_entry : chrome_top_level_list->GetList()) { + ArcTracingGraphicsModel::BufferEvents chrome_top_level_band; + if (!LoadEvents(&chrome_top_level_entry, &chrome_top_level_band)) + return false; + chrome_top_level_.emplace_back(std::move(chrome_top_level_band)); + } + const base::Value* duration = root->FindKey(kKeyDuration); if (!duration || (!duration->is_double() && !duration->is_int())) return false;
diff --git a/chrome/browser/chromeos/arc/tracing/arc_tracing_graphics_model.h b/chrome/browser/chromeos/arc/tracing/arc_tracing_graphics_model.h index 1709164..2c684da 100644 --- a/chrome/browser/chromeos/arc/tracing/arc_tracing_graphics_model.h +++ b/chrome/browser/chromeos/arc/tracing/arc_tracing_graphics_model.h
@@ -117,7 +117,9 @@ const BufferEvents& android_top_level() const { return android_top_level_; } - const BufferEvents& chrome_top_level() const { return chrome_top_level_; } + const std::vector<BufferEvents>& chrome_top_level() const { + return chrome_top_level_; + } private: // Normalizes timestamp for all events by subtracting the timestamp of the @@ -132,7 +134,8 @@ int GetTaskIdFromBufferName(const std::string& chrome_buffer_name) const; ViewMap view_buffers_; - BufferEvents chrome_top_level_; + // To avoid overlapping events are stored interlaced. + std::vector<BufferEvents> chrome_top_level_; BufferEvents android_top_level_; // Total duration of this model. uint32_t duration_ = 0;
diff --git a/chrome/browser/chromeos/arc/tracing/arc_tracing_model_unittest.cc b/chrome/browser/chromeos/arc/tracing/arc_tracing_model_unittest.cc index 9490722..7c29cde 100644 --- a/chrome/browser/chromeos/arc/tracing/arc_tracing_model_unittest.cc +++ b/chrome/browser/chromeos/arc/tracing/arc_tracing_model_unittest.cc
@@ -135,7 +135,7 @@ EXPECT_FALSE(ss.str().empty()); // Continue in this test to avoid heavy calculations for building base model. - // Make sure we can createe graphics model. + // Make sure we can create graphics model. ArcTracingGraphicsModel graphics_model; ASSERT_TRUE(graphics_model.Build(model)); @@ -146,15 +146,17 @@ GraphicsEventType::kSurfaceFlingerInvalidationDone, GraphicsEventType::kSurfaceFlingerCompositionStart, GraphicsEventType::kSurfaceFlingerCompositionDone})); - EXPECT_TRUE( - ValidateGrahpicsEvent(graphics_model.chrome_top_level(), - { - GraphicsEventType::kChromeOSDraw, - GraphicsEventType::kChromeOSSwap, - GraphicsEventType::kChromeOSWaitForAck, - GraphicsEventType::kChromeOSPresentationDone, - GraphicsEventType::kChromeOSSwapDone, - })); + EXPECT_EQ(2U, graphics_model.chrome_top_level().size()); + for (const auto& chrome_top_level_band : graphics_model.chrome_top_level()) { + EXPECT_TRUE(ValidateGrahpicsEvent( + chrome_top_level_band, { + GraphicsEventType::kChromeOSDraw, + GraphicsEventType::kChromeOSSwap, + GraphicsEventType::kChromeOSWaitForAck, + GraphicsEventType::kChromeOSPresentationDone, + GraphicsEventType::kChromeOSSwapDone, + })); + } EXPECT_FALSE(graphics_model.view_buffers().empty()); for (const auto& view : graphics_model.view_buffers()) { // At least one buffer.
diff --git a/chrome/browser/chromeos/attestation/attestation_ca_client.h b/chrome/browser/chromeos/attestation/attestation_ca_client.h index 386502ff..ad4a8c0 100644 --- a/chrome/browser/chromeos/attestation/attestation_ca_client.h +++ b/chrome/browser/chromeos/attestation/attestation_ca_client.h
@@ -11,7 +11,7 @@ #include "base/macros.h" #include "chromeos/attestation/attestation_flow.h" -#include "chromeos/dbus/attestation_constants.h" +#include "chromeos/dbus/constants/attestation_constants.h" namespace network { class SimpleURLLoader;
diff --git a/chrome/browser/chromeos/attestation/attestation_policy_browsertest.cc b/chrome/browser/chromeos/attestation/attestation_policy_browsertest.cc index 5c89b60..fdcfc54 100644 --- a/chrome/browser/chromeos/attestation/attestation_policy_browsertest.cc +++ b/chrome/browser/chromeos/attestation/attestation_policy_browsertest.cc
@@ -14,7 +14,7 @@ #include "chrome/browser/chromeos/settings/device_settings_service.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" -#include "chromeos/dbus/fake_cryptohome_client.h" +#include "chromeos/dbus/cryptohome/fake_cryptohome_client.h" #include "components/policy/proto/chrome_device_policy.pb.h" #include "testing/gtest/include/gtest/gtest.h"
diff --git a/chrome/browser/chromeos/attestation/attestation_policy_observer.cc b/chrome/browser/chromeos/attestation/attestation_policy_observer.cc index 23cdf515..2c308c3 100644 --- a/chrome/browser/chromeos/attestation/attestation_policy_observer.cc +++ b/chrome/browser/chromeos/attestation/attestation_policy_observer.cc
@@ -20,7 +20,7 @@ #include "chromeos/attestation/attestation_flow.h" #include "chromeos/cryptohome/async_method_caller.h" #include "chromeos/cryptohome/cryptohome_parameters.h" -#include "chromeos/dbus/cryptohome_client.h" +#include "chromeos/dbus/cryptohome/cryptohome_client.h" #include "chromeos/dbus/dbus_method_call_status.h" #include "chromeos/dbus/dbus_thread_manager.h" #include "components/account_id/account_id.h"
diff --git a/chrome/browser/chromeos/attestation/attestation_policy_observer.h b/chrome/browser/chromeos/attestation/attestation_policy_observer.h index ee749d8..21c4f34 100644 --- a/chrome/browser/chromeos/attestation/attestation_policy_observer.h +++ b/chrome/browser/chromeos/attestation/attestation_policy_observer.h
@@ -12,7 +12,7 @@ #include "base/macros.h" #include "base/memory/weak_ptr.h" #include "chrome/browser/chromeos/settings/cros_settings.h" -#include "chromeos/dbus/attestation_constants.h" +#include "chromeos/dbus/constants/attestation_constants.h" namespace policy { class CloudPolicyClient;
diff --git a/chrome/browser/chromeos/attestation/attestation_policy_observer_unittest.cc b/chrome/browser/chromeos/attestation/attestation_policy_observer_unittest.cc index 32620754..ec09b8f7 100644 --- a/chrome/browser/chromeos/attestation/attestation_policy_observer_unittest.cc +++ b/chrome/browser/chromeos/attestation/attestation_policy_observer_unittest.cc
@@ -17,7 +17,7 @@ #include "chrome/browser/chromeos/attestation/fake_certificate.h" #include "chrome/browser/chromeos/settings/scoped_cros_settings_test_helper.h" #include "chromeos/attestation/mock_attestation_flow.h" -#include "chromeos/dbus/fake_cryptohome_client.h" +#include "chromeos/dbus/cryptohome/fake_cryptohome_client.h" #include "chromeos/settings/cros_settings_names.h" #include "components/policy/core/common/cloud/mock_cloud_policy_client.h" #include "content/public/test/test_browser_thread_bundle.h"
diff --git a/chrome/browser/chromeos/attestation/enrollment_policy_observer.cc b/chrome/browser/chromeos/attestation/enrollment_policy_observer.cc index 01ffc20f..9d205ddd 100644 --- a/chrome/browser/chromeos/attestation/enrollment_policy_observer.cc +++ b/chrome/browser/chromeos/attestation/enrollment_policy_observer.cc
@@ -19,7 +19,7 @@ #include "chrome/browser/chromeos/attestation/attestation_key_payload.pb.h" #include "chrome/browser/chromeos/settings/cros_settings.h" #include "chromeos/cryptohome/cryptohome_parameters.h" -#include "chromeos/dbus/cryptohome_client.h" +#include "chromeos/dbus/cryptohome/cryptohome_client.h" #include "chromeos/dbus/dbus_method_call_status.h" #include "chromeos/dbus/dbus_thread_manager.h" #include "components/account_id/account_id.h"
diff --git a/chrome/browser/chromeos/attestation/enrollment_policy_observer.h b/chrome/browser/chromeos/attestation/enrollment_policy_observer.h index 74a2263f..6051d17 100644 --- a/chrome/browser/chromeos/attestation/enrollment_policy_observer.h +++ b/chrome/browser/chromeos/attestation/enrollment_policy_observer.h
@@ -12,7 +12,7 @@ #include "base/macros.h" #include "base/memory/weak_ptr.h" #include "chrome/browser/chromeos/settings/device_settings_service.h" -#include "chromeos/dbus/attestation_constants.h" +#include "chromeos/dbus/constants/attestation_constants.h" namespace policy { class CloudPolicyClient;
diff --git a/chrome/browser/chromeos/attestation/enrollment_policy_observer_unittest.cc b/chrome/browser/chromeos/attestation/enrollment_policy_observer_unittest.cc index 85b8173..811ed82 100644 --- a/chrome/browser/chromeos/attestation/enrollment_policy_observer_unittest.cc +++ b/chrome/browser/chromeos/attestation/enrollment_policy_observer_unittest.cc
@@ -18,7 +18,7 @@ #include "base/threading/thread_task_runner_handle.h" #include "chrome/browser/chromeos/attestation/enrollment_policy_observer.h" #include "chrome/browser/chromeos/settings/device_settings_test_helper.h" -#include "chromeos/dbus/fake_cryptohome_client.h" +#include "chromeos/dbus/cryptohome/fake_cryptohome_client.h" #include "chromeos/settings/cros_settings_names.h" #include "components/policy/core/common/cloud/mock_cloud_policy_client.h" #include "testing/gtest/include/gtest/gtest.h"
diff --git a/chrome/browser/chromeos/attestation/platform_verification_flow.cc b/chrome/browser/chromeos/attestation/platform_verification_flow.cc index c53d364..6f1dfc07 100644 --- a/chrome/browser/chromeos/attestation/platform_verification_flow.cc +++ b/chrome/browser/chromeos/attestation/platform_verification_flow.cc
@@ -24,7 +24,7 @@ #include "chromeos/cryptohome/async_method_caller.h" #include "chromeos/cryptohome/cryptohome_parameters.h" #include "chromeos/dbus/attestation/attestation.pb.h" -#include "chromeos/dbus/cryptohome_client.h" +#include "chromeos/dbus/cryptohome/cryptohome_client.h" #include "chromeos/dbus/dbus_thread_manager.h" #include "components/content_settings/core/browser/host_content_settings_map.h" #include "components/content_settings/core/common/content_settings_pattern.h"
diff --git a/chrome/browser/chromeos/attestation/platform_verification_flow.h b/chrome/browser/chromeos/attestation/platform_verification_flow.h index cac0f9fc..313cd26 100644 --- a/chrome/browser/chromeos/attestation/platform_verification_flow.h +++ b/chrome/browser/chromeos/attestation/platform_verification_flow.h
@@ -14,7 +14,7 @@ #include "base/memory/ref_counted.h" #include "base/time/time.h" #include "base/timer/timer.h" -#include "chromeos/dbus/attestation_constants.h" +#include "chromeos/dbus/constants/attestation_constants.h" #include "url/gurl.h" class AccountId;
diff --git a/chrome/browser/chromeos/attestation/platform_verification_flow_unittest.cc b/chrome/browser/chromeos/attestation/platform_verification_flow_unittest.cc index 5f84524..6b47a22 100644 --- a/chrome/browser/chromeos/attestation/platform_verification_flow_unittest.cc +++ b/chrome/browser/chromeos/attestation/platform_verification_flow_unittest.cc
@@ -20,7 +20,7 @@ #include "chromeos/attestation/mock_attestation_flow.h" #include "chromeos/cryptohome/mock_async_method_caller.h" #include "chromeos/dbus/attestation/attestation.pb.h" -#include "chromeos/dbus/fake_cryptohome_client.h" +#include "chromeos/dbus/cryptohome/fake_cryptohome_client.h" #include "chromeos/settings/cros_settings_names.h" #include "content/public/test/test_browser_thread_bundle.h" #include "testing/gtest/include/gtest/gtest.h"
diff --git a/chrome/browser/chromeos/child_accounts/event_based_status_reporting_service_unittest.cc b/chrome/browser/chromeos/child_accounts/event_based_status_reporting_service_unittest.cc index da3c138..a389cc6 100644 --- a/chrome/browser/chromeos/child_accounts/event_based_status_reporting_service_unittest.cc +++ b/chrome/browser/chromeos/child_accounts/event_based_status_reporting_service_unittest.cc
@@ -87,7 +87,7 @@ ~EventBasedStatusReportingServiceTest() override = default; void SetUp() override { - PowerManagerClient::Initialize(); + PowerManagerClient::InitializeFake(); SystemClockClient::InitializeFake(); profile_ = std::make_unique<TestingProfile>(); profile_.get()->SetSupervisedUserId(supervised_users::kChildAccountSUID);
diff --git a/chrome/browser/chromeos/child_accounts/usage_time_state_notifier_unittest.cc b/chrome/browser/chromeos/child_accounts/usage_time_state_notifier_unittest.cc index 1aaf4ac1..a70c4d67 100644 --- a/chrome/browser/chromeos/child_accounts/usage_time_state_notifier_unittest.cc +++ b/chrome/browser/chromeos/child_accounts/usage_time_state_notifier_unittest.cc
@@ -46,7 +46,7 @@ ~UsageTimeStateNotifierTest() override = default; void SetUp() override { - PowerManagerClient::Initialize(); + PowerManagerClient::InitializeFake(); session_manager_.SetSessionState( session_manager::SessionState::LOGIN_PRIMARY); }
diff --git a/chrome/browser/chromeos/chrome_browser_main_chromeos.cc b/chrome/browser/chromeos/chrome_browser_main_chromeos.cc index d12bce7..504ba11 100644 --- a/chrome/browser/chromeos/chrome_browser_main_chromeos.cc +++ b/chrome/browser/chromeos/chrome_browser_main_chromeos.cc
@@ -131,7 +131,7 @@ #include "chromeos/cryptohome/cryptohome_parameters.h" #include "chromeos/cryptohome/homedir_methods.h" #include "chromeos/cryptohome/system_salt_getter.h" -#include "chromeos/dbus/cryptohome_client.h" +#include "chromeos/dbus/cryptohome/cryptohome_client.h" #include "chromeos/dbus/dbus_thread_manager.h" #include "chromeos/dbus/power/power_policy_controller.h" #include "chromeos/dbus/services/cros_dbus_service.h"
diff --git a/chrome/browser/chromeos/dbus/dbus_helper.cc b/chrome/browser/chromeos/dbus/dbus_helper.cc index dc041ea..060b852 100644 --- a/chrome/browser/chromeos/dbus/dbus_helper.cc +++ b/chrome/browser/chromeos/dbus/dbus_helper.cc
@@ -38,17 +38,16 @@ } } - // TODO(estade/stevenjb): Modify PowerManagerClient to use InitializeFake. - PowerManagerClient::Initialize(bus); - if (bus) { BiodClient::Initialize(bus); // For device::Fingerprint. KerberosClient::Initialize(bus); + PowerManagerClient::Initialize(bus); SystemClockClient::Initialize(bus); UpstartClient::Initialize(bus); } else { BiodClient::InitializeFake(); // For device::Fingerprint. KerberosClient::InitializeFake(); + PowerManagerClient::InitializeFake(); SystemClockClient::InitializeFake(); UpstartClient::InitializeFake(); }
diff --git a/chrome/browser/chromeos/extensions/quick_unlock_private/quick_unlock_private_api_unittest.cc b/chrome/browser/chromeos/extensions/quick_unlock_private/quick_unlock_private_api_unittest.cc index 715d1c56..b06fe2d 100644 --- a/chrome/browser/chromeos/extensions/quick_unlock_private/quick_unlock_private_api_unittest.cc +++ b/chrome/browser/chromeos/extensions/quick_unlock_private/quick_unlock_private_api_unittest.cc
@@ -30,8 +30,8 @@ #include "chrome/common/pref_names.h" #include "chromeos/cryptohome/mock_homedir_methods.h" #include "chromeos/cryptohome/system_salt_getter.h" +#include "chromeos/dbus/cryptohome/fake_cryptohome_client.h" #include "chromeos/dbus/dbus_thread_manager.h" -#include "chromeos/dbus/fake_cryptohome_client.h" #include "chromeos/login/auth/fake_extended_authenticator.h" #include "chromeos/services/device_sync/public/cpp/fake_device_sync_client.h" #include "chromeos/services/multidevice_setup/public/cpp/fake_multidevice_setup_client.h"
diff --git a/chrome/browser/chromeos/file_manager/volume_manager_unittest.cc b/chrome/browser/chromeos/file_manager/volume_manager_unittest.cc index dfbaaac2..2fccbe1e2 100644 --- a/chrome/browser/chromeos/file_manager/volume_manager_unittest.cc +++ b/chrome/browser/chromeos/file_manager/volume_manager_unittest.cc
@@ -244,7 +244,7 @@ }; void SetUp() override { - chromeos::PowerManagerClient::Initialize(); + chromeos::PowerManagerClient::InitializeFake(); disk_mount_manager_ = std::make_unique<FakeDiskMountManager>(); main_profile_ = std::make_unique<ProfileEnvironment>( chromeos::PowerManagerClient::Get(), disk_mount_manager_.get()); @@ -726,7 +726,8 @@ volume_manager()->RemoveObserver(&observer); } -TEST_F(VolumeManagerTest, OnFormatEvent_CompletedFailed) { +// TODO(crbug.com/943570): test is flaky, disabled. +TEST_F(VolumeManagerTest, DISABLED_OnFormatEvent_CompletedFailed) { LoggingObserver observer; volume_manager()->AddObserver(&observer);
diff --git a/chrome/browser/chromeos/login/active_directory_login_browsertest.cc b/chrome/browser/chromeos/login/active_directory_login_browsertest.cc index baa4627..70f96ad2 100644 --- a/chrome/browser/chromeos/login/active_directory_login_browsertest.cc +++ b/chrome/browser/chromeos/login/active_directory_login_browsertest.cc
@@ -25,9 +25,9 @@ #include "chrome/test/base/in_process_browser_test.h" #include "chrome/test/base/interactive_test_utils.h" #include "chromeos/constants/chromeos_switches.h" +#include "chromeos/dbus/cryptohome/fake_cryptohome_client.h" #include "chromeos/dbus/dbus_thread_manager.h" #include "chromeos/dbus/fake_auth_policy_client.h" -#include "chromeos/dbus/fake_cryptohome_client.h" #include "chromeos/dbus/util/tpm_util.h" #include "chromeos/login/auth/authpolicy_login_helper.h" #include "components/account_id/account_id.h"
diff --git a/chrome/browser/chromeos/login/auth/cryptohome_authenticator_unittest.cc b/chrome/browser/chromeos/login/auth/cryptohome_authenticator_unittest.cc index 9866bf8..052708d07f 100644 --- a/chrome/browser/chromeos/login/auth/cryptohome_authenticator_unittest.cc +++ b/chrome/browser/chromeos/login/auth/cryptohome_authenticator_unittest.cc
@@ -34,9 +34,9 @@ #include "chromeos/cryptohome/mock_async_method_caller.h" #include "chromeos/cryptohome/system_salt_getter.h" #include "chromeos/dbus/cros_disks_client.h" +#include "chromeos/dbus/cryptohome/fake_cryptohome_client.h" #include "chromeos/dbus/cryptohome/rpc.pb.h" #include "chromeos/dbus/dbus_thread_manager.h" -#include "chromeos/dbus/fake_cryptohome_client.h" #include "chromeos/dbus/util/account_identifier_operators.h" #include "chromeos/login/auth/key.h" #include "chromeos/login/auth/mock_auth_status_consumer.h"
diff --git a/chrome/browser/chromeos/login/auto_launched_kiosk_browsertest.cc b/chrome/browser/chromeos/login/auto_launched_kiosk_browsertest.cc index efba4651..13386e4 100644 --- a/chrome/browser/chromeos/login/auto_launched_kiosk_browsertest.cc +++ b/chrome/browser/chromeos/login/auto_launched_kiosk_browsertest.cc
@@ -32,7 +32,7 @@ #include "chrome/common/chrome_constants.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/pref_names.h" -#include "chromeos/dbus/cryptohome_client.h" +#include "chromeos/dbus/cryptohome/cryptohome_client.h" #include "chromeos/dbus/dbus_thread_manager.h" #include "chromeos/dbus/session_manager/fake_session_manager_client.h" #include "chromeos/dbus/shill_manager_client.h"
diff --git a/chrome/browser/chromeos/login/crash_restore_browsertest.cc b/chrome/browser/chromeos/login/crash_restore_browsertest.cc index f45c581..b0954af 100644 --- a/chrome/browser/chromeos/login/crash_restore_browsertest.cc +++ b/chrome/browser/chromeos/login/crash_restore_browsertest.cc
@@ -26,7 +26,7 @@ #include "chrome/test/base/in_process_browser_test.h" #include "chromeos/constants/chromeos_switches.h" #include "chromeos/cryptohome/cryptohome_parameters.h" -#include "chromeos/dbus/cryptohome_client.h" +#include "chromeos/dbus/cryptohome/cryptohome_client.h" #include "chromeos/dbus/dbus_thread_manager.h" #include "chromeos/dbus/session_manager/fake_session_manager_client.h" #include "chromeos/dbus/session_manager/session_manager_client.h"
diff --git a/chrome/browser/chromeos/login/demo_mode/demo_mode_resources_remover.h b/chrome/browser/chromeos/login/demo_mode/demo_mode_resources_remover.h index b566a42..7d6174ec 100644 --- a/chrome/browser/chromeos/login/demo_mode/demo_mode_resources_remover.h +++ b/chrome/browser/chromeos/login/demo_mode/demo_mode_resources_remover.h
@@ -14,7 +14,7 @@ #include "base/memory/weak_ptr.h" #include "base/optional.h" #include "base/scoped_observer.h" -#include "chromeos/dbus/cryptohome_client.h" +#include "chromeos/dbus/cryptohome/cryptohome_client.h" #include "components/user_manager/user_manager.h" #include "ui/base/user_activity/user_activity_observer.h"
diff --git a/chrome/browser/chromeos/login/demo_mode/demo_mode_resources_remover_unittest.cc b/chrome/browser/chromeos/login/demo_mode/demo_mode_resources_remover_unittest.cc index 916e7e6..9488ecab 100644 --- a/chrome/browser/chromeos/login/demo_mode/demo_mode_resources_remover_unittest.cc +++ b/chrome/browser/chromeos/login/demo_mode/demo_mode_resources_remover_unittest.cc
@@ -18,8 +18,8 @@ #include "chrome/browser/chromeos/login/users/fake_chrome_user_manager.h" #include "chrome/browser/chromeos/profiles/profile_helper.h" #include "chrome/browser/chromeos/settings/stub_install_attributes.h" +#include "chromeos/dbus/cryptohome/fake_cryptohome_client.h" #include "chromeos/dbus/dbus_thread_manager.h" -#include "chromeos/dbus/fake_cryptohome_client.h" #include "components/prefs/testing_pref_service.h" #include "components/sync_preferences/testing_pref_service_syncable.h" #include "components/user_manager/scoped_user_manager.h"
diff --git a/chrome/browser/chromeos/login/easy_unlock/easy_unlock_get_keys_operation.cc b/chrome/browser/chromeos/login/easy_unlock/easy_unlock_get_keys_operation.cc index ae23cac..8144b9d 100644 --- a/chrome/browser/chromeos/login/easy_unlock/easy_unlock_get_keys_operation.cc +++ b/chrome/browser/chromeos/login/easy_unlock/easy_unlock_get_keys_operation.cc
@@ -13,7 +13,7 @@ #include "chrome/browser/chromeos/login/easy_unlock/easy_unlock_key_manager.h" #include "chromeos/components/multidevice/logging/logging.h" #include "chromeos/cryptohome/cryptohome_util.h" -#include "chromeos/dbus/cryptohome_client.h" +#include "chromeos/dbus/cryptohome/cryptohome_client.h" #include "chromeos/dbus/dbus_thread_manager.h" #include "components/account_id/account_id.h" #include "google_apis/gaia/gaia_auth_util.h"
diff --git a/chrome/browser/chromeos/login/easy_unlock/easy_unlock_service_signin_chromeos.cc b/chrome/browser/chromeos/login/easy_unlock/easy_unlock_service_signin_chromeos.cc index 9d6c0e71..403ec45 100644 --- a/chrome/browser/chromeos/login/easy_unlock/easy_unlock_service_signin_chromeos.cc +++ b/chrome/browser/chromeos/login/easy_unlock/easy_unlock_service_signin_chromeos.cc
@@ -542,7 +542,8 @@ } multidevice::RemoteDevice remote_device( - account_id.GetUserEmail(), std::string() /* name */, decoded_public_key, + account_id.GetUserEmail(), std::string() /* name */, + std::string() /* pii_free_name */, decoded_public_key, decoded_psk /* persistent_symmetric_key */, 0L /* last_update_time_millis */, software_features, beacon_seeds);
diff --git a/chrome/browser/chromeos/login/enrollment/auto_enrollment_controller.cc b/chrome/browser/chromeos/login/enrollment/auto_enrollment_controller.cc index e7be7c1..97428e7 100644 --- a/chrome/browser/chromeos/login/enrollment/auto_enrollment_controller.cc +++ b/chrome/browser/chromeos/login/enrollment/auto_enrollment_controller.cc
@@ -18,8 +18,8 @@ #include "chrome/browser/chromeos/policy/server_backed_state_keys_broker.h" #include "chrome/browser/net/system_network_context_manager.h" #include "chromeos/constants/chromeos_switches.h" +#include "chromeos/dbus/cryptohome/cryptohome_client.h" #include "chromeos/dbus/cryptohome/rpc.pb.h" -#include "chromeos/dbus/cryptohome_client.h" #include "chromeos/dbus/dbus_thread_manager.h" #include "chromeos/dbus/system_clock/system_clock_client.h" #include "chromeos/system/factory_ping_embargo_check.h"
diff --git a/chrome/browser/chromeos/login/enrollment/enrollment_screen.cc b/chrome/browser/chromeos/login/enrollment/enrollment_screen.cc index 682e287d..b40a54b1 100644 --- a/chrome/browser/chromeos/login/enrollment/enrollment_screen.cc +++ b/chrome/browser/chromeos/login/enrollment/enrollment_screen.cc
@@ -22,7 +22,7 @@ #include "chrome/browser/chromeos/profiles/profile_helper.h" #include "chrome/browser/lifetime/application_lifetime.h" #include "chrome/browser/lifetime/browser_shutdown.h" -#include "chromeos/dbus/cryptohome_client.h" +#include "chromeos/dbus/cryptohome/cryptohome_client.h" #include "chromeos/dbus/dbus_method_call_status.h" #include "chromeos/dbus/dbus_thread_manager.h" #include "components/policy/core/common/cloud/cloud_policy_constants.h"
diff --git a/chrome/browser/chromeos/login/kiosk_browsertest.cc b/chrome/browser/chromeos/login/kiosk_browsertest.cc index ddd16eea..48da70a 100644 --- a/chrome/browser/chromeos/login/kiosk_browsertest.cc +++ b/chrome/browser/chromeos/login/kiosk_browsertest.cc
@@ -55,7 +55,7 @@ #include "chrome/common/chrome_paths.h" #include "chrome/common/pref_names.h" #include "chromeos/constants/chromeos_switches.h" -#include "chromeos/dbus/cryptohome_client.h" +#include "chromeos/dbus/cryptohome/cryptohome_client.h" #include "chromeos/disks/disk_mount_manager.h" #include "chromeos/settings/cros_settings_provider.h" #include "components/prefs/pref_service.h"
diff --git a/chrome/browser/chromeos/login/quick_unlock/pin_migration_browsertest.cc b/chrome/browser/chromeos/login/quick_unlock/pin_migration_browsertest.cc index fb2c0a7..4e017d3 100644 --- a/chrome/browser/chromeos/login/quick_unlock/pin_migration_browsertest.cc +++ b/chrome/browser/chromeos/login/quick_unlock/pin_migration_browsertest.cc
@@ -10,8 +10,8 @@ #include "chrome/browser/chromeos/login/quick_unlock/quick_unlock_storage.h" #include "chrome/browser/chromeos/login/startup_utils.h" #include "chrome/test/base/in_process_browser_test.h" +#include "chromeos/dbus/cryptohome/fake_cryptohome_client.h" #include "chromeos/dbus/dbus_thread_manager.h" -#include "chromeos/dbus/fake_cryptohome_client.h" #include "components/account_id/account_id.h" #include "testing/gtest/include/gtest/gtest.h"
diff --git a/chrome/browser/chromeos/login/saml/saml_browsertest.cc b/chrome/browser/chromeos/login/saml/saml_browsertest.cc index 4b99313..db733ab 100644 --- a/chrome/browser/chromeos/login/saml/saml_browsertest.cc +++ b/chrome/browser/chromeos/login/saml/saml_browsertest.cc
@@ -57,11 +57,11 @@ #include "chrome/test/base/in_process_browser_test.h" #include "chromeos/constants/chromeos_switches.h" #include "chromeos/cryptohome/system_salt_getter.h" +#include "chromeos/dbus/cryptohome/cryptohome_client.h" +#include "chromeos/dbus/cryptohome/fake_cryptohome_client.h" #include "chromeos/dbus/cryptohome/key.pb.h" #include "chromeos/dbus/cryptohome/rpc.pb.h" -#include "chromeos/dbus/cryptohome_client.h" #include "chromeos/dbus/dbus_thread_manager.h" -#include "chromeos/dbus/fake_cryptohome_client.h" #include "chromeos/dbus/session_manager/fake_session_manager_client.h" #include "chromeos/dbus/session_manager/session_manager_client.h" #include "chromeos/dbus/shill_manager_client.h"
diff --git a/chrome/browser/chromeos/login/screens/eula_screen.cc b/chrome/browser/chromeos/login/screens/eula_screen.cc index 448020f..958ca4a 100644 --- a/chrome/browser/chromeos/login/screens/eula_screen.cc +++ b/chrome/browser/chromeos/login/screens/eula_screen.cc
@@ -11,7 +11,7 @@ #include "chrome/browser/chromeos/customization/customization_document.h" #include "chrome/browser/chromeos/login/screens/eula_view.h" #include "chrome/browser/chromeos/login/wizard_controller.h" -#include "chromeos/dbus/cryptohome_client.h" +#include "chromeos/dbus/cryptohome/cryptohome_client.h" #include "chromeos/dbus/dbus_method_call_status.h" #include "chromeos/dbus/dbus_thread_manager.h"
diff --git a/chrome/browser/chromeos/login/screens/user_selection_screen.cc b/chrome/browser/chromeos/login/screens/user_selection_screen.cc index 23699a14..84e1c5a 100644 --- a/chrome/browser/chromeos/login/screens/user_selection_screen.cc +++ b/chrome/browser/chromeos/login/screens/user_selection_screen.cc
@@ -41,7 +41,7 @@ #include "chromeos/components/proximity_auth/smart_lock_metrics_recorder.h" #include "chromeos/constants/chromeos_switches.h" #include "chromeos/cryptohome/cryptohome_parameters.h" -#include "chromeos/dbus/cryptohome_client.h" +#include "chromeos/dbus/cryptohome/cryptohome_client.h" #include "chromeos/dbus/dbus_thread_manager.h" #include "components/account_id/account_id.h" #include "components/arc/arc_util.h"
diff --git a/chrome/browser/chromeos/login/screens/user_selection_screen_browsertest.cc b/chrome/browser/chromeos/login/screens/user_selection_screen_browsertest.cc index 1e8375d..da6008ad 100644 --- a/chrome/browser/chromeos/login/screens/user_selection_screen_browsertest.cc +++ b/chrome/browser/chromeos/login/screens/user_selection_screen_browsertest.cc
@@ -16,8 +16,8 @@ #include "chrome/browser/ui/webui/chromeos/login/oobe_ui.h" #include "chrome/browser/ui/webui/chromeos/login/signin_screen_handler.h" #include "chromeos/constants/chromeos_switches.h" +#include "chromeos/dbus/cryptohome/fake_cryptohome_client.h" #include "chromeos/dbus/dbus_thread_manager.h" -#include "chromeos/dbus/fake_cryptohome_client.h" namespace chromeos {
diff --git a/chrome/browser/chromeos/login/session/user_session_manager.cc b/chrome/browser/chromeos/login/session/user_session_manager.cc index 96c274a..78e2ac7 100644 --- a/chrome/browser/chromeos/login/session/user_session_manager.cc +++ b/chrome/browser/chromeos/login/session/user_session_manager.cc
@@ -112,7 +112,7 @@ #include "chromeos/constants/chromeos_features.h" #include "chromeos/constants/chromeos_switches.h" #include "chromeos/cryptohome/cryptohome_parameters.h" -#include "chromeos/dbus/cryptohome_client.h" +#include "chromeos/dbus/cryptohome/cryptohome_client.h" #include "chromeos/dbus/dbus_thread_manager.h" #include "chromeos/dbus/session_manager/session_manager_client.h" #include "chromeos/dbus/util/tpm_util.h"
diff --git a/chrome/browser/chromeos/login/users/avatar/user_image_manager_browsertest.cc b/chrome/browser/chromeos/login/users/avatar/user_image_manager_browsertest.cc index 6f297e2..9ede2af 100644 --- a/chrome/browser/chromeos/login/users/avatar/user_image_manager_browsertest.cc +++ b/chrome/browser/chromeos/login/users/avatar/user_image_manager_browsertest.cc
@@ -50,7 +50,7 @@ #include "chromeos/constants/chromeos_switches.h" #include "chromeos/cryptohome/cryptohome_parameters.h" #include "chromeos/dbus/constants/dbus_paths.h" -#include "chromeos/dbus/cryptohome_client.h" +#include "chromeos/dbus/cryptohome/cryptohome_client.h" #include "chromeos/dbus/dbus_thread_manager.h" #include "chromeos/dbus/session_manager/fake_session_manager_client.h" #include "chromeos/dbus/session_manager/session_manager_client.h"
diff --git a/chrome/browser/chromeos/login/users/wallpaper_policy_browsertest.cc b/chrome/browser/chromeos/login/users/wallpaper_policy_browsertest.cc index 7953e6b..f58c1cba 100644 --- a/chrome/browser/chromeos/login/users/wallpaper_policy_browsertest.cc +++ b/chrome/browser/chromeos/login/users/wallpaper_policy_browsertest.cc
@@ -42,7 +42,7 @@ #include "chromeos/cryptohome/cryptohome_parameters.h" #include "chromeos/cryptohome/system_salt_getter.h" #include "chromeos/dbus/constants/dbus_paths.h" -#include "chromeos/dbus/cryptohome_client.h" +#include "chromeos/dbus/cryptohome/cryptohome_client.h" #include "chromeos/dbus/dbus_thread_manager.h" #include "chromeos/dbus/session_manager/fake_session_manager_client.h" #include "chromeos/dbus/session_manager/session_manager_client.h"
diff --git a/chrome/browser/chromeos/login/wizard_controller_browsertest.cc b/chrome/browser/chromeos/login/wizard_controller_browsertest.cc index daa322a..de436f9f 100644 --- a/chrome/browser/chromeos/login/wizard_controller_browsertest.cc +++ b/chrome/browser/chromeos/login/wizard_controller_browsertest.cc
@@ -71,8 +71,8 @@ #include "chromeos/audio/cras_audio_handler.h" #include "chromeos/constants/chromeos_switches.h" #include "chromeos/dbus/constants/dbus_switches.h" +#include "chromeos/dbus/cryptohome/fake_cryptohome_client.h" #include "chromeos/dbus/dbus_thread_manager.h" -#include "chromeos/dbus/fake_cryptohome_client.h" #include "chromeos/dbus/fake_shill_manager_client.h" #include "chromeos/dbus/session_manager/fake_session_manager_client.h" #include "chromeos/dbus/system_clock/system_clock_client.h"
diff --git a/chrome/browser/chromeos/network_change_manager_client_unittest.cc b/chrome/browser/chromeos/network_change_manager_client_unittest.cc index 68c6bca..23e42a6 100644 --- a/chrome/browser/chromeos/network_change_manager_client_unittest.cc +++ b/chrome/browser/chromeos/network_change_manager_client_unittest.cc
@@ -114,7 +114,7 @@ void SetUp() override { network_change_notifier_.reset(net::NetworkChangeNotifier::Create()); DBusThreadManager::Initialize(); - PowerManagerClient::Initialize(); + PowerManagerClient::InitializeFake(); NetworkHandler::Initialize(); proxy_ = std::make_unique<NetworkChangeManagerClient>( static_cast<net::NetworkChangeNotifierPosix*>(
diff --git a/chrome/browser/chromeos/policy/affiliation_test_helper.cc b/chrome/browser/chromeos/policy/affiliation_test_helper.cc index 9a4033af..7274dd4e 100644 --- a/chrome/browser/chromeos/policy/affiliation_test_helper.cc +++ b/chrome/browser/chromeos/policy/affiliation_test_helper.cc
@@ -23,7 +23,7 @@ #include "chromeos/constants/chromeos_switches.h" #include "chromeos/cryptohome/cryptohome_parameters.h" #include "chromeos/dbus/constants/dbus_paths.h" -#include "chromeos/dbus/cryptohome_client.h" +#include "chromeos/dbus/cryptohome/cryptohome_client.h" #include "chromeos/dbus/fake_auth_policy_client.h" #include "chromeos/dbus/session_manager/fake_session_manager_client.h" #include "chromeos/dbus/session_manager/session_manager_client.h"
diff --git a/chrome/browser/chromeos/policy/app_install_event_log_collector_unittest.cc b/chrome/browser/chromeos/policy/app_install_event_log_collector_unittest.cc index ac347bf..b861dd3 100644 --- a/chrome/browser/chromeos/policy/app_install_event_log_collector_unittest.cc +++ b/chrome/browser/chromeos/policy/app_install_event_log_collector_unittest.cc
@@ -111,9 +111,9 @@ void SetUp() override { RegisterLocalState(pref_service_.registry()); TestingBrowserProcess::GetGlobal()->SetLocalState(&pref_service_); - chromeos::PowerManagerClient::Initialize(); chromeos::DBusThreadManager::Initialize(); + chromeos::PowerManagerClient::InitializeFake(); chromeos::NetworkHandler::Initialize(); profile_ = std::make_unique<TestingProfile>(); @@ -136,8 +136,8 @@ profile_.reset(); chromeos::NetworkHandler::Shutdown(); - chromeos::DBusThreadManager::Shutdown(); chromeos::PowerManagerClient::Shutdown(); + chromeos::DBusThreadManager::Shutdown(); TestingBrowserProcess::GetGlobal()->SetLocalState(nullptr); }
diff --git a/chrome/browser/chromeos/policy/app_install_event_logger_unittest.cc b/chrome/browser/chromeos/policy/app_install_event_logger_unittest.cc index cefc78c..ea6c510 100644 --- a/chrome/browser/chromeos/policy/app_install_event_logger_unittest.cc +++ b/chrome/browser/chromeos/policy/app_install_event_logger_unittest.cc
@@ -105,8 +105,9 @@ TestingBrowserProcess::GetGlobal()->SetLocalState(&pref_service_); chromeos::DBusThreadManager::Initialize(); + chromeos::PowerManagerClient::InitializeFake(); + chromeos::NetworkHandler::Initialize(); - chromeos::PowerManagerClient::Initialize(); disk_mount_manager_ = new chromeos::disks::MockDiskMountManager; chromeos::disks::DiskMountManager::InitializeForTesting(
diff --git a/chrome/browser/chromeos/policy/browser_policy_connector_chromeos.cc b/chrome/browser/chromeos/policy/browser_policy_connector_chromeos.cc index 54b4f066..1955ea7e 100644 --- a/chrome/browser/chromeos/policy/browser_policy_connector_chromeos.cc +++ b/chrome/browser/chromeos/policy/browser_policy_connector_chromeos.cc
@@ -51,7 +51,7 @@ #include "chromeos/constants/chromeos_switches.h" #include "chromeos/cryptohome/async_method_caller.h" #include "chromeos/cryptohome/system_salt_getter.h" -#include "chromeos/dbus/cryptohome_client.h" +#include "chromeos/dbus/cryptohome/cryptohome_client.h" #include "chromeos/dbus/dbus_thread_manager.h" #include "chromeos/dbus/upstart/upstart_client.h" #include "chromeos/network/network_cert_loader.h"
diff --git a/chrome/browser/chromeos/policy/cached_policy_key_loader_chromeos.cc b/chrome/browser/chromeos/policy/cached_policy_key_loader_chromeos.cc index 8bd9030..b12ad6f 100644 --- a/chrome/browser/chromeos/policy/cached_policy_key_loader_chromeos.cc +++ b/chrome/browser/chromeos/policy/cached_policy_key_loader_chromeos.cc
@@ -18,7 +18,7 @@ #include "base/strings/stringprintf.h" #include "base/task_runner_util.h" #include "chromeos/cryptohome/cryptohome_parameters.h" -#include "chromeos/dbus/cryptohome_client.h" +#include "chromeos/dbus/cryptohome/cryptohome_client.h" namespace policy {
diff --git a/chrome/browser/chromeos/policy/cached_policy_key_loader_chromeos_unittest.cc b/chrome/browser/chromeos/policy/cached_policy_key_loader_chromeos_unittest.cc index 0624ab32..81ae78f 100644 --- a/chrome/browser/chromeos/policy/cached_policy_key_loader_chromeos_unittest.cc +++ b/chrome/browser/chromeos/policy/cached_policy_key_loader_chromeos_unittest.cc
@@ -15,7 +15,7 @@ #include "base/single_thread_task_runner.h" #include "base/test/scoped_task_environment.h" #include "chromeos/cryptohome/cryptohome_parameters.h" -#include "chromeos/dbus/fake_cryptohome_client.h" +#include "chromeos/dbus/cryptohome/fake_cryptohome_client.h" #include "testing/gtest/include/gtest/gtest.h" namespace policy {
diff --git a/chrome/browser/chromeos/policy/component_active_directory_policy_browsertest.cc b/chrome/browser/chromeos/policy/component_active_directory_policy_browsertest.cc index 4bc91a5..af93269 100644 --- a/chrome/browser/chromeos/policy/component_active_directory_policy_browsertest.cc +++ b/chrome/browser/chromeos/policy/component_active_directory_policy_browsertest.cc
@@ -16,8 +16,8 @@ #include "chrome/common/chrome_paths.h" #include "chromeos/constants/chromeos_switches.h" #include "chromeos/cryptohome/cryptohome_parameters.h" +#include "chromeos/dbus/cryptohome/fake_cryptohome_client.h" #include "chromeos/dbus/dbus_thread_manager.h" -#include "chromeos/dbus/fake_cryptohome_client.h" #include "chromeos/dbus/login_manager/policy_descriptor.pb.h" #include "chromeos/dbus/session_manager/fake_session_manager_client.h" #include "chromeos/dbus/util/tpm_util.h"
diff --git a/chrome/browser/chromeos/policy/device_cloud_policy_manager_chromeos_unittest.cc b/chrome/browser/chromeos/policy/device_cloud_policy_manager_chromeos_unittest.cc index 010d073..4d5cca9 100644 --- a/chrome/browser/chromeos/policy/device_cloud_policy_manager_chromeos_unittest.cc +++ b/chrome/browser/chromeos/policy/device_cloud_policy_manager_chromeos_unittest.cc
@@ -37,9 +37,9 @@ #include "chromeos/constants/chromeos_switches.h" #include "chromeos/cryptohome/async_method_caller.h" #include "chromeos/cryptohome/system_salt_getter.h" +#include "chromeos/dbus/cryptohome/fake_cryptohome_client.h" #include "chromeos/dbus/dbus_client_implementation_type.h" #include "chromeos/dbus/dbus_thread_manager.h" -#include "chromeos/dbus/fake_cryptohome_client.h" #include "chromeos/dbus/session_manager/fake_session_manager_client.h" #include "chromeos/system/fake_statistics_provider.h" #include "chromeos/system/statistics_provider.h"
diff --git a/chrome/browser/chromeos/policy/device_cloud_policy_store_chromeos_unittest.cc b/chrome/browser/chromeos/policy/device_cloud_policy_store_chromeos_unittest.cc index 0374fda..09f909d1 100644 --- a/chrome/browser/chromeos/policy/device_cloud_policy_store_chromeos_unittest.cc +++ b/chrome/browser/chromeos/policy/device_cloud_policy_store_chromeos_unittest.cc
@@ -16,8 +16,8 @@ #include "chrome/browser/chromeos/settings/device_settings_test_helper.h" #include "chrome/test/base/scoped_testing_local_state.h" #include "chrome/test/base/testing_browser_process.h" +#include "chromeos/dbus/cryptohome/fake_cryptohome_client.h" #include "chromeos/dbus/dbus_thread_manager.h" -#include "chromeos/dbus/fake_cryptohome_client.h" #include "chromeos/dbus/util/tpm_util.h" #include "chromeos/network/onc/onc_test_utils.h" #include "chromeos/tpm/install_attributes.h"
diff --git a/chrome/browser/chromeos/policy/device_status_collector.cc b/chrome/browser/chromeos/policy/device_status_collector.cc index 42f9368..40071c1 100644 --- a/chrome/browser/chromeos/policy/device_status_collector.cc +++ b/chrome/browser/chromeos/policy/device_status_collector.cc
@@ -52,8 +52,8 @@ #include "chrome/common/chrome_features.h" #include "chrome/common/pref_names.h" #include "chromeos/audio/cras_audio_handler.h" +#include "chromeos/dbus/cryptohome/cryptohome_client.h" #include "chromeos/dbus/cryptohome/rpc.pb.h" -#include "chromeos/dbus/cryptohome_client.h" #include "chromeos/dbus/dbus_thread_manager.h" #include "chromeos/dbus/power_manager/idle.pb.h" #include "chromeos/dbus/update_engine_client.h"
diff --git a/chrome/browser/chromeos/policy/device_status_collector.h b/chrome/browser/chromeos/policy/device_status_collector.h index 83e71c4..ce15dd7e 100644 --- a/chrome/browser/chromeos/policy/device_status_collector.h +++ b/chrome/browser/chromeos/policy/device_status_collector.h
@@ -26,7 +26,7 @@ #include "base/timer/timer.h" #include "chrome/browser/chromeos/child_accounts/usage_time_state_notifier.h" #include "chrome/browser/chromeos/settings/cros_settings.h" -#include "chromeos/dbus/cryptohome_client.h" +#include "chromeos/dbus/cryptohome/cryptohome_client.h" #include "chromeos/dbus/power/power_manager_client.h" #include "chromeos/dbus/runtime_probe/runtime_probe.pb.h" #include "chromeos/dbus/runtime_probe_client.h"
diff --git a/chrome/browser/chromeos/policy/device_status_collector_browsertest.cc b/chrome/browser/chromeos/policy/device_status_collector_browsertest.cc index b5c615a..aa78bb6 100644 --- a/chrome/browser/chromeos/policy/device_status_collector_browsertest.cc +++ b/chrome/browser/chromeos/policy/device_status_collector_browsertest.cc
@@ -402,14 +402,13 @@ base::WrapUnique<chromeos::UpdateEngineClient>(update_engine_client_)); chromeos::CrasAudioHandler::InitializeForTesting(); + chromeos::PowerManagerClient::InitializeFake(); chromeos::LoginState::Initialize(); - - chromeos::PowerManagerClient::Initialize(); } ~DeviceStatusCollectorTest() override { - chromeos::PowerManagerClient::Shutdown(); chromeos::LoginState::Shutdown(); + chromeos::PowerManagerClient::Shutdown(); chromeos::CrasAudioHandler::Shutdown(); chromeos::KioskAppManager::Shutdown(); TestingBrowserProcess::GetGlobal()->SetLocalState(nullptr);
diff --git a/chrome/browser/chromeos/policy/display_resolution_handler_browsertest.cc b/chrome/browser/chromeos/policy/display_resolution_handler_browsertest.cc index 6f39fa10..5aa95ca9 100644 --- a/chrome/browser/chromeos/policy/display_resolution_handler_browsertest.cc +++ b/chrome/browser/chromeos/policy/display_resolution_handler_browsertest.cc
@@ -20,9 +20,9 @@ #include "chrome/browser/lifetime/application_lifetime.h" #include "chrome/test/base/in_process_browser_test.h" #include "chromeos/constants/chromeos_switches.h" -#include "chromeos/dbus/cryptohome_client.h" +#include "chromeos/dbus/cryptohome/cryptohome_client.h" +#include "chromeos/dbus/cryptohome/fake_cryptohome_client.h" #include "chromeos/dbus/dbus_thread_manager.h" -#include "chromeos/dbus/fake_cryptohome_client.h" #include "chromeos/dbus/session_manager/fake_session_manager_client.h" #include "chromeos/dbus/session_manager/session_manager_client.h" #include "chromeos/settings/cros_settings_names.h"
diff --git a/chrome/browser/chromeos/policy/display_rotation_default_handler_browsertest.cc b/chrome/browser/chromeos/policy/display_rotation_default_handler_browsertest.cc index a1a59d5c..c76076d 100644 --- a/chrome/browser/chromeos/policy/display_rotation_default_handler_browsertest.cc +++ b/chrome/browser/chromeos/policy/display_rotation_default_handler_browsertest.cc
@@ -22,9 +22,9 @@ #include "chrome/browser/lifetime/application_lifetime.h" #include "chrome/test/base/in_process_browser_test.h" #include "chromeos/constants/chromeos_switches.h" -#include "chromeos/dbus/cryptohome_client.h" +#include "chromeos/dbus/cryptohome/cryptohome_client.h" +#include "chromeos/dbus/cryptohome/fake_cryptohome_client.h" #include "chromeos/dbus/dbus_thread_manager.h" -#include "chromeos/dbus/fake_cryptohome_client.h" #include "chromeos/dbus/session_manager/fake_session_manager_client.h" #include "chromeos/dbus/session_manager/session_manager_client.h" #include "chromeos/settings/cros_settings_names.h"
diff --git a/chrome/browser/chromeos/policy/dm_token_storage_unittest.cc b/chrome/browser/chromeos/policy/dm_token_storage_unittest.cc index 75d44a2..105ade2 100644 --- a/chrome/browser/chromeos/policy/dm_token_storage_unittest.cc +++ b/chrome/browser/chromeos/policy/dm_token_storage_unittest.cc
@@ -11,8 +11,8 @@ #include "chrome/test/base/scoped_testing_local_state.h" #include "chrome/test/base/testing_browser_process.h" #include "chromeos/cryptohome/system_salt_getter.h" +#include "chromeos/dbus/cryptohome/fake_cryptohome_client.h" #include "chromeos/dbus/dbus_thread_manager.h" -#include "chromeos/dbus/fake_cryptohome_client.h" #include "content/public/test/test_browser_thread_bundle.h" #include "testing/gtest/include/gtest/gtest.h"
diff --git a/chrome/browser/chromeos/policy/enrollment_handler_chromeos.h b/chrome/browser/chromeos/policy/enrollment_handler_chromeos.h index b8031e0..c432301 100644 --- a/chrome/browser/chromeos/policy/enrollment_handler_chromeos.h +++ b/chrome/browser/chromeos/policy/enrollment_handler_chromeos.h
@@ -17,8 +17,8 @@ #include "chrome/browser/chromeos/policy/device_cloud_policy_initializer.h" #include "chrome/browser/chromeos/policy/device_cloud_policy_validator.h" #include "chrome/browser/chromeos/policy/enrollment_config.h" -#include "chromeos/dbus/attestation_constants.h" #include "chromeos/dbus/auth_policy_client.h" +#include "chromeos/dbus/constants/attestation_constants.h" #include "chromeos/tpm/install_attributes.h" #include "components/policy/core/common/cloud/cloud_policy_client.h" #include "components/policy/core/common/cloud/cloud_policy_constants.h"
diff --git a/chrome/browser/chromeos/policy/power_policy_browsertest.cc b/chrome/browser/chromeos/policy/power_policy_browsertest.cc index 6f8bcc6..e42260d4 100644 --- a/chrome/browser/chromeos/policy/power_policy_browsertest.cc +++ b/chrome/browser/chromeos/policy/power_policy_browsertest.cc
@@ -36,7 +36,7 @@ #include "chromeos/constants/chromeos_switches.h" #include "chromeos/cryptohome/cryptohome_parameters.h" #include "chromeos/dbus/constants/dbus_paths.h" -#include "chromeos/dbus/cryptohome_client.h" +#include "chromeos/dbus/cryptohome/cryptohome_client.h" #include "chromeos/dbus/dbus_thread_manager.h" #include "chromeos/dbus/power/fake_power_manager_client.h" #include "chromeos/dbus/power/power_policy_controller.h"
diff --git a/chrome/browser/chromeos/policy/pre_signin_policy_fetcher.cc b/chrome/browser/chromeos/policy/pre_signin_policy_fetcher.cc index 0b0ecf7..32d26c2 100644 --- a/chrome/browser/chromeos/policy/pre_signin_policy_fetcher.cc +++ b/chrome/browser/chromeos/policy/pre_signin_policy_fetcher.cc
@@ -20,7 +20,7 @@ #include "chromeos/cryptohome/cryptohome_util.h" #include "chromeos/cryptohome/homedir_methods.h" #include "chromeos/dbus/constants/dbus_paths.h" -#include "chromeos/dbus/cryptohome_client.h" +#include "chromeos/dbus/cryptohome/cryptohome_client.h" #include "chromeos/dbus/dbus_thread_manager.h" #include "components/policy/core/common/cloud/cloud_policy_constants.h" #include "components/policy/proto/device_management_backend.pb.h"
diff --git a/chrome/browser/chromeos/policy/pre_signin_policy_fetcher_unittest.cc b/chrome/browser/chromeos/policy/pre_signin_policy_fetcher_unittest.cc index 7653d0d4..1a410db 100644 --- a/chrome/browser/chromeos/policy/pre_signin_policy_fetcher_unittest.cc +++ b/chrome/browser/chromeos/policy/pre_signin_policy_fetcher_unittest.cc
@@ -18,9 +18,9 @@ #include "base/test/scoped_task_environment.h" #include "chromeos/cryptohome/cryptohome_parameters.h" #include "chromeos/dbus/constants/dbus_paths.h" -#include "chromeos/dbus/cryptohome_client.h" +#include "chromeos/dbus/cryptohome/cryptohome_client.h" +#include "chromeos/dbus/cryptohome/fake_cryptohome_client.h" #include "chromeos/dbus/dbus_thread_manager.h" -#include "chromeos/dbus/fake_cryptohome_client.h" #include "chromeos/dbus/session_manager/fake_session_manager_client.h" #include "components/policy/core/common/cloud/cloud_policy_constants.h" #include "components/policy/core/common/cloud/mock_cloud_policy_client.h"
diff --git a/chrome/browser/chromeos/policy/status_uploader_unittest.cc b/chrome/browser/chromeos/policy/status_uploader_unittest.cc index dbc805c..09a1e2e 100644 --- a/chrome/browser/chromeos/policy/status_uploader_unittest.cc +++ b/chrome/browser/chromeos/policy/status_uploader_unittest.cc
@@ -90,7 +90,7 @@ void SetUp() override { chromeos::DBusThreadManager::Initialize(); - chromeos::PowerManagerClient::Initialize(); + chromeos::PowerManagerClient::InitializeFake(); client_.SetDMToken("dm_token"); collector_.reset(new MockDeviceStatusCollector(&prefs_));
diff --git a/chrome/browser/chromeos/policy/user_affiliation_browsertest.cc b/chrome/browser/chromeos/policy/user_affiliation_browsertest.cc index 6988a6e3..9f32714 100644 --- a/chrome/browser/chromeos/policy/user_affiliation_browsertest.cc +++ b/chrome/browser/chromeos/policy/user_affiliation_browsertest.cc
@@ -21,10 +21,10 @@ #include "chrome/test/base/in_process_browser_test.h" #include "chromeos/constants/chromeos_switches.h" #include "chromeos/cryptohome/cryptohome_parameters.h" -#include "chromeos/dbus/cryptohome_client.h" +#include "chromeos/dbus/cryptohome/cryptohome_client.h" +#include "chromeos/dbus/cryptohome/fake_cryptohome_client.h" #include "chromeos/dbus/dbus_thread_manager.h" #include "chromeos/dbus/fake_auth_policy_client.h" -#include "chromeos/dbus/fake_cryptohome_client.h" #include "chromeos/dbus/session_manager/fake_session_manager_client.h" #include "chromeos/dbus/session_manager/session_manager_client.h" #include "chromeos/dbus/upstart/upstart_client.h"
diff --git a/chrome/browser/chromeos/policy/user_cloud_policy_store_chromeos_unittest.cc b/chrome/browser/chromeos/policy/user_cloud_policy_store_chromeos_unittest.cc index 39c6695..032f7cf 100644 --- a/chrome/browser/chromeos/policy/user_cloud_policy_store_chromeos_unittest.cc +++ b/chrome/browser/chromeos/policy/user_cloud_policy_store_chromeos_unittest.cc
@@ -20,7 +20,7 @@ #include "base/test/scoped_task_environment.h" #include "base/threading/thread_task_runner_handle.h" #include "chromeos/cryptohome/cryptohome_parameters.h" -#include "chromeos/dbus/fake_cryptohome_client.h" +#include "chromeos/dbus/cryptohome/fake_cryptohome_client.h" #include "chromeos/dbus/session_manager/fake_session_manager_client.h" #include "chromeos/dbus/util/account_identifier_operators.h" #include "chromeos/network/onc/onc_test_utils.h"
diff --git a/chrome/browser/chromeos/power/auto_screen_brightness/adapter_unittest.cc b/chrome/browser/chromeos/power/auto_screen_brightness/adapter_unittest.cc index bb61efa..8415c73 100644 --- a/chrome/browser/chromeos/power/auto_screen_brightness/adapter_unittest.cc +++ b/chrome/browser/chromeos/power/auto_screen_brightness/adapter_unittest.cc
@@ -126,7 +126,7 @@ ~AdapterTest() override = default; void SetUp() override { - chromeos::PowerManagerClient::Initialize(); + chromeos::PowerManagerClient::InitializeFake(); power_manager::SetBacklightBrightnessRequest request; request.set_percent(1); chromeos::PowerManagerClient::Get()->SetScreenBrightness(request);
diff --git a/chrome/browser/chromeos/power/auto_screen_brightness/brightness_monitor_impl_unittest.cc b/chrome/browser/chromeos/power/auto_screen_brightness/brightness_monitor_impl_unittest.cc index d389acbf..0ca92674 100644 --- a/chrome/browser/chromeos/power/auto_screen_brightness/brightness_monitor_impl_unittest.cc +++ b/chrome/browser/chromeos/power/auto_screen_brightness/brightness_monitor_impl_unittest.cc
@@ -74,7 +74,7 @@ ~BrightnessMonitorImplTest() override {} // testing::Test: - void SetUp() override { PowerManagerClient::Initialize(); } + void SetUp() override { PowerManagerClient::InitializeFake(); } void TearDown() override { test_observer_.reset();
diff --git a/chrome/browser/chromeos/power/auto_screen_brightness/metrics_reporter_unittest.cc b/chrome/browser/chromeos/power/auto_screen_brightness/metrics_reporter_unittest.cc index d666a9a..e08d752 100644 --- a/chrome/browser/chromeos/power/auto_screen_brightness/metrics_reporter_unittest.cc +++ b/chrome/browser/chromeos/power/auto_screen_brightness/metrics_reporter_unittest.cc
@@ -36,7 +36,7 @@ ~MetricsReporterTest() override = default; void SetUp() override { - PowerManagerClient::Initialize(); + PowerManagerClient::InitializeFake(); MetricsReporter::RegisterLocalStatePrefs(pref_service_.registry()); ResetReporter(); }
diff --git a/chrome/browser/chromeos/power/extension_event_observer_unittest.cc b/chrome/browser/chromeos/power/extension_event_observer_unittest.cc index 706eafa..eef92d2 100644 --- a/chrome/browser/chromeos/power/extension_event_observer_unittest.cc +++ b/chrome/browser/chromeos/power/extension_event_observer_unittest.cc
@@ -47,7 +47,7 @@ void SetUp() override { ChromeRenderViewHostTestHarness::SetUp(); - PowerManagerClient::Initialize(); + PowerManagerClient::InitializeFake(); profile_manager_ = std::make_unique<TestingProfileManager>( TestingBrowserProcess::GetGlobal()); extension_event_observer_ = std::make_unique<ExtensionEventObserver>();
diff --git a/chrome/browser/chromeos/power/ml/adaptive_screen_brightness_manager_unittest.cc b/chrome/browser/chromeos/power/ml/adaptive_screen_brightness_manager_unittest.cc index 13bb5950..85d20f2 100644 --- a/chrome/browser/chromeos/power/ml/adaptive_screen_brightness_manager_unittest.cc +++ b/chrome/browser/chromeos/power/ml/adaptive_screen_brightness_manager_unittest.cc
@@ -90,7 +90,7 @@ void SetUp() override { ChromeRenderViewHostTestHarness::SetUp(); - PowerManagerClient::Initialize(); + PowerManagerClient::InitializeFake(); auto logger = std::make_unique<TestingAdaptiveScreenBrightnessUkmLogger>(); ukm_logger_ = logger.get();
diff --git a/chrome/browser/chromeos/power/ml/idle_event_notifier_unittest.cc b/chrome/browser/chromeos/power/ml/idle_event_notifier_unittest.cc index b733b019..9e93e6dd 100644 --- a/chrome/browser/chromeos/power/ml/idle_event_notifier_unittest.cc +++ b/chrome/browser/chromeos/power/ml/idle_event_notifier_unittest.cc
@@ -86,7 +86,7 @@ ~IdleEventNotifierTest() override = default; void SetUp() override { - PowerManagerClient::Initialize(); + PowerManagerClient::InitializeFake(); viz::mojom::VideoDetectorObserverPtr observer; idle_event_notifier_ = std::make_unique<IdleEventNotifier>( PowerManagerClient::Get(), &user_activity_detector_,
diff --git a/chrome/browser/chromeos/power/ml/user_activity_manager_unittest.cc b/chrome/browser/chromeos/power/ml/user_activity_manager_unittest.cc index b24a552..12bf4a0 100644 --- a/chrome/browser/chromeos/power/ml/user_activity_manager_unittest.cc +++ b/chrome/browser/chromeos/power/ml/user_activity_manager_unittest.cc
@@ -181,7 +181,7 @@ void SetUp() override { ChromeRenderViewHostTestHarness::SetUp(); - PowerManagerClient::Initialize(); + PowerManagerClient::InitializeFake(); viz::mojom::VideoDetectorObserverPtr observer; idle_event_notifier_ = std::make_unique<IdleEventNotifier>( PowerManagerClient::Get(), &user_activity_detector_,
diff --git a/chrome/browser/chromeos/power/power_data_collector_unittest.cc b/chrome/browser/chromeos/power/power_data_collector_unittest.cc index affbd62..0c8f9200 100644 --- a/chrome/browser/chromeos/power/power_data_collector_unittest.cc +++ b/chrome/browser/chromeos/power/power_data_collector_unittest.cc
@@ -18,7 +18,7 @@ ~PowerDataCollectorTest() override = default; void SetUp() override { - PowerManagerClient::Initialize(); + PowerManagerClient::InitializeFake(); PowerDataCollector::InitializeForTesting(); power_data_collector_ = PowerDataCollector::Get(); }
diff --git a/chrome/browser/chromeos/power/power_metrics_reporter_unittest.cc b/chrome/browser/chromeos/power/power_metrics_reporter_unittest.cc index 8ae609b4..ebfa6c90 100644 --- a/chrome/browser/chromeos/power/power_metrics_reporter_unittest.cc +++ b/chrome/browser/chromeos/power/power_metrics_reporter_unittest.cc
@@ -23,7 +23,7 @@ ~PowerMetricsReporterTest() override = default; void SetUp() override { - PowerManagerClient::Initialize(); + PowerManagerClient::InitializeFake(); PowerMetricsReporter::RegisterLocalStatePrefs(pref_service_.registry()); ResetReporter(); }
diff --git a/chrome/browser/chromeos/power/renderer_freezer_unittest.cc b/chrome/browser/chromeos/power/renderer_freezer_unittest.cc index 453879d..b594199 100644 --- a/chrome/browser/chromeos/power/renderer_freezer_unittest.cc +++ b/chrome/browser/chromeos/power/renderer_freezer_unittest.cc
@@ -134,7 +134,7 @@ ~RendererFreezerTest() override = default; // testing::Test: - void SetUp() override { PowerManagerClient::Initialize(); } + void SetUp() override { PowerManagerClient::InitializeFake(); } void TearDown() override { DCHECK(renderer_freezer_);
diff --git a/chrome/browser/chromeos/profiles/profile_helper.cc b/chrome/browser/chromeos/profiles/profile_helper.cc index 58b446b..5e6389b4 100644 --- a/chrome/browser/chromeos/profiles/profile_helper.cc +++ b/chrome/browser/chromeos/profiles/profile_helper.cc
@@ -37,7 +37,7 @@ namespace { -// As defined in /chromeos/dbus/cryptohome_client.cc. +// As defined in /chromeos/dbus/cryptohome/cryptohome_client.cc. static const char kUserIdHashSuffix[] = "-hash"; // The name for the lock screen app profile.
diff --git a/chrome/browser/chromeos/settings/device_oauth2_token_service_unittest.cc b/chrome/browser/chromeos/settings/device_oauth2_token_service_unittest.cc index 16ebb3b0..7947a302 100644 --- a/chrome/browser/chromeos/settings/device_oauth2_token_service_unittest.cc +++ b/chrome/browser/chromeos/settings/device_oauth2_token_service_unittest.cc
@@ -24,8 +24,8 @@ #include "chrome/test/base/scoped_testing_local_state.h" #include "chrome/test/base/testing_browser_process.h" #include "chromeos/cryptohome/system_salt_getter.h" +#include "chromeos/dbus/cryptohome/fake_cryptohome_client.h" #include "chromeos/dbus/dbus_thread_manager.h" -#include "chromeos/dbus/fake_cryptohome_client.h" #include "chromeos/dbus/session_manager/fake_session_manager_client.h" #include "components/ownership/mock_owner_key_util.h" #include "components/prefs/testing_pref_service.h"
diff --git a/chrome/browser/chromeos/settings/device_settings_provider.cc b/chrome/browser/chromeos/settings/device_settings_provider.cc index 50842e80..6bcfeb2 100644 --- a/chrome/browser/chromeos/settings/device_settings_provider.cc +++ b/chrome/browser/chromeos/settings/device_settings_provider.cc
@@ -28,7 +28,7 @@ #include "chrome/browser/chromeos/settings/stats_reporting_controller.h" #include "chrome/browser/chromeos/tpm_firmware_update.h" #include "chromeos/constants/chromeos_switches.h" -#include "chromeos/dbus/cryptohome_client.h" +#include "chromeos/dbus/cryptohome/cryptohome_client.h" #include "chromeos/dbus/dbus_thread_manager.h" #include "chromeos/settings/cros_settings_names.h" #include "chromeos/tpm/install_attributes.h"
diff --git a/chrome/browser/chromeos/settings/device_settings_test_helper.cc b/chrome/browser/chromeos/settings/device_settings_test_helper.cc index 883cdb1..ee8f2eb 100644 --- a/chrome/browser/chromeos/settings/device_settings_test_helper.cc +++ b/chrome/browser/chromeos/settings/device_settings_test_helper.cc
@@ -49,8 +49,8 @@ base::WrapUnique(user_manager_)); owner_key_util_ = new ownership::MockOwnerKeyUtil(); device_settings_service_ = std::make_unique<DeviceSettingsService>(); - PowerManagerClient::Initialize(); dbus_setter_ = DBusThreadManager::GetSetterForTesting(); + PowerManagerClient::InitializeFake(); OwnerSettingsServiceChromeOSFactory::SetDeviceSettingsServiceForTesting( device_settings_service_.get()); OwnerSettingsServiceChromeOSFactory::GetInstance()->SetOwnerKeyUtilForTesting( @@ -74,8 +74,8 @@ FlushDeviceSettings(); device_settings_service_->UnsetSessionManager(); device_settings_service_.reset(); - DBusThreadManager::Shutdown(); PowerManagerClient::Shutdown(); + DBusThreadManager::Shutdown(); device_policy_.reset(); base::RunLoop().RunUntilIdle(); profile_.reset();
diff --git a/chrome/browser/chromeos/system/automatic_reboot_manager_unittest.cc b/chrome/browser/chromeos/system/automatic_reboot_manager_unittest.cc index 5b12845..51d7bd7 100644 --- a/chrome/browser/chromeos/system/automatic_reboot_manager_unittest.cc +++ b/chrome/browser/chromeos/system/automatic_reboot_manager_unittest.cc
@@ -327,10 +327,10 @@ TestingBrowserProcess::GetGlobal()->SetLocalState(&local_state_); AutomaticRebootManager::RegisterPrefs(local_state_.registry()); - PowerManagerClient::Initialize(); update_engine_client_ = new FakeUpdateEngineClient; DBusThreadManager::GetSetterForTesting()->SetUpdateEngineClient( std::unique_ptr<UpdateEngineClient>(update_engine_client_)); + PowerManagerClient::InitializeFake(); EXPECT_CALL(*mock_user_manager_, IsUserLoggedIn()) .WillRepeatedly(ReturnPointee(&is_user_logged_in_));
diff --git a/chrome/browser/chromeos/tether/tether_service_unittest.cc b/chrome/browser/chromeos/tether/tether_service_unittest.cc index fcbbfde..c001a85 100644 --- a/chrome/browser/chromeos/tether/tether_service_unittest.cc +++ b/chrome/browser/chromeos/tether/tether_service_unittest.cc
@@ -343,7 +343,7 @@ scoped_user_manager_ = std::make_unique<user_manager::ScopedUserManager>( base::WrapUnique(fake_chrome_user_manager_)); - chromeos::PowerManagerClient::Initialize(); + chromeos::PowerManagerClient::InitializeFake(); fake_device_sync_client_ = std::make_unique<chromeos::device_sync::FakeDeviceSyncClient>();
diff --git a/chrome/browser/chromeos/ui/low_disk_notification.cc b/chrome/browser/chromeos/ui/low_disk_notification.cc index 2e6dd7c..7dc0f15af 100644 --- a/chrome/browser/chromeos/ui/low_disk_notification.cc +++ b/chrome/browser/chromeos/ui/low_disk_notification.cc
@@ -17,7 +17,7 @@ #include "chrome/browser/profiles/profile_manager.h" #include "chrome/browser/ui/chrome_pages.h" #include "chrome/grit/generated_resources.h" -#include "chromeos/dbus/cryptohome_client.h" +#include "chromeos/dbus/cryptohome/cryptohome_client.h" #include "chromeos/dbus/dbus_thread_manager.h" #include "components/user_manager/user_manager.h" #include "content/public/browser/browser_thread.h"
diff --git a/chrome/browser/chromeos/ui/low_disk_notification.h b/chrome/browser/chromeos/ui/low_disk_notification.h index 7f2cdfe8..8bb50d3d 100644 --- a/chrome/browser/chromeos/ui/low_disk_notification.h +++ b/chrome/browser/chromeos/ui/low_disk_notification.h
@@ -13,7 +13,7 @@ #include "base/memory/weak_ptr.h" #include "base/threading/thread_checker.h" #include "base/time/time.h" -#include "chromeos/dbus/cryptohome_client.h" +#include "chromeos/dbus/cryptohome/cryptohome_client.h" namespace message_center { class Notification;
diff --git a/chrome/browser/chromeos/ui/low_disk_notification_unittest.cc b/chrome/browser/chromeos/ui/low_disk_notification_unittest.cc index d3c2c64..d74dee5 100644 --- a/chrome/browser/chromeos/ui/low_disk_notification_unittest.cc +++ b/chrome/browser/chromeos/ui/low_disk_notification_unittest.cc
@@ -16,8 +16,8 @@ #include "chrome/test/base/browser_with_test_window_test.h" #include "chrome/test/base/testing_browser_process.h" #include "chrome/test/base/testing_profile_manager.h" +#include "chromeos/dbus/cryptohome/fake_cryptohome_client.h" #include "chromeos/dbus/dbus_thread_manager.h" -#include "chromeos/dbus/fake_cryptohome_client.h" #include "ui/base/l10n/l10n_util.h" #include "ui/base/resource/resource_bundle.h" #include "ui/message_center/public/cpp/notification.h"
diff --git a/chrome/browser/data_reduction_proxy/data_reduction_proxy_browsertest.cc b/chrome/browser/data_reduction_proxy/data_reduction_proxy_browsertest.cc index b603226..5544651f 100644 --- a/chrome/browser/data_reduction_proxy/data_reduction_proxy_browsertest.cc +++ b/chrome/browser/data_reduction_proxy/data_reduction_proxy_browsertest.cc
@@ -10,11 +10,12 @@ #include "base/test/bind_test_util.h" #include "base/test/metrics/histogram_tester.h" #include "base/test/scoped_feature_list.h" +#include "chrome/browser/data_reduction_proxy/data_reduction_proxy_chrome_settings.h" +#include "chrome/browser/data_reduction_proxy/data_reduction_proxy_chrome_settings_factory.h" #include "chrome/browser/metrics/subprocess_metrics_provider.h" #include "chrome/browser/page_load_metrics/page_load_metrics_test_waiter.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/browser.h" -#include "chrome/common/pref_names.h" #include "chrome/test/base/in_process_browser_test.h" #include "chrome/test/base/ui_test_utils.h" #include "components/data_reduction_proxy/core/browser/data_reduction_proxy_config_service_client_test_utils.h" @@ -152,9 +153,11 @@ protected: void EnableDataSaver(bool enabled) { - PrefService* prefs = browser()->profile()->GetPrefs(); - prefs->SetBoolean(::prefs::kDataSaverEnabled, enabled); - base::RunLoop().RunUntilIdle(); + data_reduction_proxy::DataReductionProxySettings* + data_reduction_proxy_settings = + DataReductionProxyChromeSettingsFactory::GetForBrowserContext( + browser()->profile()); + data_reduction_proxy_settings->SetDataReductionProxyEnabled(enabled); } std::string GetBody() { return GetBody(browser()); }
diff --git a/chrome/browser/data_use_measurement/data_use_measurement_browsertest.cc b/chrome/browser/data_use_measurement/data_use_measurement_browsertest.cc index a7843bcf..4cd9995 100644 --- a/chrome/browser/data_use_measurement/data_use_measurement_browsertest.cc +++ b/chrome/browser/data_use_measurement/data_use_measurement_browsertest.cc
@@ -5,10 +5,11 @@ #include "base/bind.h" #include "base/test/metrics/histogram_tester.h" #include "chrome/browser/browser_process.h" +#include "chrome/browser/data_reduction_proxy/data_reduction_proxy_chrome_settings.h" +#include "chrome/browser/data_reduction_proxy/data_reduction_proxy_chrome_settings_factory.h" #include "chrome/browser/data_use_measurement/chrome_data_use_measurement.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/browser.h" -#include "chrome/common/pref_names.h" #include "chrome/test/base/in_process_browser_test.h" #include "chrome/test/base/ui_test_utils.h" #include "components/data_reduction_proxy/core/browser/data_reduction_proxy_config_service_client_test_utils.h" @@ -78,9 +79,11 @@ protected: void EnableDataSaver(bool enabled) { - PrefService* prefs = browser()->profile()->GetPrefs(); - prefs->SetBoolean(::prefs::kDataSaverEnabled, enabled); - base::RunLoop().RunUntilIdle(); + data_reduction_proxy::DataReductionProxySettings* + data_reduction_proxy_settings = + DataReductionProxyChromeSettingsFactory::GetForBrowserContext( + browser()->profile()); + data_reduction_proxy_settings->SetDataReductionProxyEnabled(enabled); } const base::HistogramTester& histogram_tester() { return histogram_tester_; }
diff --git a/chrome/browser/devtools/devtools_sanity_browsertest.cc b/chrome/browser/devtools/devtools_sanity_browsertest.cc index 8fe0a4d6..2a2cef2 100644 --- a/chrome/browser/devtools/devtools_sanity_browsertest.cc +++ b/chrome/browser/devtools/devtools_sanity_browsertest.cc
@@ -2259,6 +2259,14 @@ } IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, LoadNetworkResourceForFrontend) { + base::FilePath root_dir; + CHECK(base::PathService::Get(base::DIR_SOURCE_ROOT, &root_dir)); + std::string file_url = + "file://" + + root_dir.AppendASCII("content/test/data/devtools/navigation.html") + .NormalizePathSeparatorsTo('/') + .AsUTF8Unsafe(); + embedded_test_server()->ServeFilesFromSourceDirectory("content/test/data"); ASSERT_TRUE(embedded_test_server()->Start()); @@ -2267,7 +2275,8 @@ embedded_test_server()->GetURL("/hello.html")); window_ = DevToolsWindowTesting::OpenDevToolsWindowSync(GetInspectedTab(), false); - RunTestMethod("testLoadResourceForFrontend", url.spec().c_str()); + RunTestMethod("testLoadResourceForFrontend", url.spec().c_str(), + file_url.c_str()); DevToolsWindowTesting::CloseDevToolsWindowSync(window_); }
diff --git a/chrome/browser/devtools/devtools_ui_bindings.cc b/chrome/browser/devtools/devtools_ui_bindings.cc index 9b93c31..bc77ceb 100644 --- a/chrome/browser/devtools/devtools_ui_bindings.cc +++ b/chrome/browser/devtools/devtools_ui_bindings.cc
@@ -48,6 +48,7 @@ #include "content/public/browser/child_process_security_policy.h" #include "content/public/browser/devtools_external_agent_proxy.h" #include "content/public/browser/devtools_external_agent_proxy_delegate.h" +#include "content/public/browser/file_url_loader.h" #include "content/public/browser/navigation_controller.h" #include "content/public/browser/navigation_entry.h" #include "content/public/browser/navigation_handle.h" @@ -56,6 +57,7 @@ #include "content/public/browser/render_frame_host.h" #include "content/public/browser/render_process_host.h" #include "content/public/browser/render_view_host.h" +#include "content/public/browser/shared_cors_origin_access_list.h" #include "content/public/browser/storage_partition.h" #include "content/public/browser/web_contents.h" #include "content/public/browser/web_contents_observer.h" @@ -727,14 +729,27 @@ resource_request->site_for_cookies = gurl; resource_request->headers.AddHeadersFromString(headers); - auto* partition = content::BrowserContext::GetStoragePartitionForSite( - web_contents_->GetBrowserContext(), gurl); - auto factory = partition->GetURLLoaderFactoryForBrowserProcess(); + std::unique_ptr<network::mojom::URLLoaderFactory> file_url_loader_factory; + scoped_refptr<network::SharedURLLoaderFactory> network_url_loader_factory; + network::mojom::URLLoaderFactory* url_loader_factory; + if (gurl.SchemeIsFile()) { + file_url_loader_factory = content::CreateFileURLLoaderFactory( + base::FilePath() /* profile_path */, + nullptr /* shared_cors_origin_access_list */); + url_loader_factory = file_url_loader_factory.get(); + } else { + auto* partition = content::BrowserContext::GetStoragePartitionForSite( + web_contents_->GetBrowserContext(), gurl); + network_url_loader_factory = + partition->GetURLLoaderFactoryForBrowserProcess(); + url_loader_factory = network_url_loader_factory.get(); + } auto simple_url_loader = network::SimpleURLLoader::Create( std::move(resource_request), traffic_annotation); auto resource_loader = std::make_unique<NetworkResourceLoader>( - stream_id, this, std::move(simple_url_loader), factory.get(), callback); + stream_id, this, std::move(simple_url_loader), url_loader_factory, + callback); loaders_.insert(std::move(resource_loader)); }
diff --git a/chrome/browser/download/chrome_download_manager_delegate.cc b/chrome/browser/download/chrome_download_manager_delegate.cc index cfe7f07..3e66919b 100644 --- a/chrome/browser/download/chrome_download_manager_delegate.cc +++ b/chrome/browser/download/chrome_download_manager_delegate.cc
@@ -78,6 +78,7 @@ #include "chrome/browser/android/download/download_controller.h" #include "chrome/browser/android/download/download_location_dialog_bridge_impl.h" #include "chrome/browser/android/download/download_manager_service.h" +#include "chrome/browser/android/download/download_utils.h" #include "chrome/browser/infobars/infobar_service.h" #endif @@ -674,11 +675,7 @@ false /* show_download_in_folder */); #if defined(OS_ANDROID) - // TODO(shaktisahu@): Pull out to static helper method once - // DownloadManagerService goes away. Put the helper method in the download - // component. - DownloadManagerService::GetInstance()->OpenDownload(download, - 0 /* download source */); + DownloadUtils::OpenDownload(download, 0 /* download source */); return; #endif
diff --git a/chrome/browser/download/download_offline_content_provider.cc b/chrome/browser/download/download_offline_content_provider.cc index e87d824e..cc9da61 100644 --- a/chrome/browser/download/download_offline_content_provider.cc +++ b/chrome/browser/download/download_offline_content_provider.cc
@@ -167,7 +167,7 @@ void DownloadOfflineContentProvider::RenameItem(const ContentId& id, const std::string& name, RenameCallback callback) { - DownloadItem* item = manager_->GetDownloadByGuid(id.id); + DownloadItem* item = GetDownload(id.id); if (!item) { base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce(std::move(callback),
diff --git a/chrome/browser/extensions/activity_log/activity_log_browsertest.cc b/chrome/browser/extensions/activity_log/activity_log_browsertest.cc index 50f5ca77..814ced93 100644 --- a/chrome/browser/extensions/activity_log/activity_log_browsertest.cc +++ b/chrome/browser/extensions/activity_log/activity_log_browsertest.cc
@@ -43,7 +43,7 @@ ExtensionApiTest::SetUpOnMainThread(); host_resolver()->AddRule("*", "127.0.0.1"); prerender::PrerenderManager::SetMode( - prerender::PrerenderManager::PRERENDER_MODE_ENABLED); + prerender::PrerenderManager::DEPRECATED_PRERENDER_MODE_ENABLED); } static void Prerender_Arguments(
diff --git a/chrome/browser/extensions/activity_log/activity_log_unittest.cc b/chrome/browser/extensions/activity_log/activity_log_unittest.cc index 0e522fdd..4b5c762c 100644 --- a/chrome/browser/extensions/activity_log/activity_log_unittest.cc +++ b/chrome/browser/extensions/activity_log/activity_log_unittest.cc
@@ -243,7 +243,7 @@ prerender::test_utils::RestorePrerenderMode restore_prerender_mode; prerender::PrerenderManager::SetMode( - prerender::PrerenderManager::PRERENDER_MODE_ENABLED); + prerender::PrerenderManager::DEPRECATED_PRERENDER_MODE_ENABLED); prerender::PrerenderManager* prerender_manager = prerender::PrerenderManagerFactory::GetForBrowserContext(profile());
diff --git a/chrome/browser/extensions/api/enterprise_platform_keys/enterprise_platform_keys_api_unittest.cc b/chrome/browser/extensions/api/enterprise_platform_keys/enterprise_platform_keys_api_unittest.cc index 9c50366..32a255f 100644 --- a/chrome/browser/extensions/api/enterprise_platform_keys/enterprise_platform_keys_api_unittest.cc +++ b/chrome/browser/extensions/api/enterprise_platform_keys/enterprise_platform_keys_api_unittest.cc
@@ -27,9 +27,9 @@ #include "chromeos/cryptohome/async_method_caller.h" #include "chromeos/cryptohome/cryptohome_parameters.h" #include "chromeos/cryptohome/mock_async_method_caller.h" -#include "chromeos/dbus/attestation_constants.h" +#include "chromeos/dbus/constants/attestation_constants.h" +#include "chromeos/dbus/cryptohome/fake_cryptohome_client.h" #include "chromeos/dbus/dbus_method_call_status.h" -#include "chromeos/dbus/fake_cryptohome_client.h" #include "components/account_id/account_id.h" #include "components/policy/core/common/cloud/cloud_policy_constants.h" #include "components/prefs/pref_service.h"
diff --git a/chrome/browser/extensions/api/enterprise_platform_keys_private/enterprise_platform_keys_private_api.cc b/chrome/browser/extensions/api/enterprise_platform_keys_private/enterprise_platform_keys_private_api.cc index fb6f4471..fb9566b 100644 --- a/chrome/browser/extensions/api/enterprise_platform_keys_private/enterprise_platform_keys_private_api.cc +++ b/chrome/browser/extensions/api/enterprise_platform_keys_private/enterprise_platform_keys_private_api.cc
@@ -25,8 +25,8 @@ #include "chromeos/attestation/attestation_flow.h" #include "chromeos/cryptohome/async_method_caller.h" #include "chromeos/cryptohome/cryptohome_parameters.h" -#include "chromeos/dbus/attestation_constants.h" -#include "chromeos/dbus/cryptohome_client.h" +#include "chromeos/dbus/constants/attestation_constants.h" +#include "chromeos/dbus/cryptohome/cryptohome_client.h" #include "chromeos/dbus/dbus_method_call_status.h" #include "chromeos/dbus/dbus_thread_manager.h" #include "chromeos/settings/cros_settings_names.h"
diff --git a/chrome/browser/extensions/api/enterprise_platform_keys_private/enterprise_platform_keys_private_api.h b/chrome/browser/extensions/api/enterprise_platform_keys_private/enterprise_platform_keys_private_api.h index 8161a91f..821da1a 100644 --- a/chrome/browser/extensions/api/enterprise_platform_keys_private/enterprise_platform_keys_private_api.h +++ b/chrome/browser/extensions/api/enterprise_platform_keys_private/enterprise_platform_keys_private_api.h
@@ -16,8 +16,8 @@ #include "base/optional.h" #include "chrome/common/extensions/api/enterprise_platform_keys_private.h" #include "chromeos/attestation/attestation_flow.h" -#include "chromeos/dbus/attestation_constants.h" -#include "chromeos/dbus/cryptohome_client.h" +#include "chromeos/dbus/constants/attestation_constants.h" +#include "chromeos/dbus/cryptohome/cryptohome_client.h" #include "components/account_id/account_id.h" #include "extensions/browser/extension_function.h" #include "extensions/common/extension.h"
diff --git a/chrome/browser/extensions/api/enterprise_platform_keys_private/enterprise_platform_keys_private_api_unittest.cc b/chrome/browser/extensions/api/enterprise_platform_keys_private/enterprise_platform_keys_private_api_unittest.cc index cd85e422..f1fa6dd7 100644 --- a/chrome/browser/extensions/api/enterprise_platform_keys_private/enterprise_platform_keys_private_api_unittest.cc +++ b/chrome/browser/extensions/api/enterprise_platform_keys_private/enterprise_platform_keys_private_api_unittest.cc
@@ -29,8 +29,8 @@ #include "chromeos/cryptohome/async_method_caller.h" #include "chromeos/cryptohome/cryptohome_parameters.h" #include "chromeos/cryptohome/mock_async_method_caller.h" -#include "chromeos/dbus/attestation_constants.h" -#include "chromeos/dbus/fake_cryptohome_client.h" +#include "chromeos/dbus/constants/attestation_constants.h" +#include "chromeos/dbus/cryptohome/fake_cryptohome_client.h" #include "components/account_id/account_id.h" #include "components/policy/core/common/cloud/cloud_policy_constants.h" #include "components/prefs/pref_service.h"
diff --git a/chrome/browser/extensions/api/networking_private/networking_private_chromeos_apitest.cc b/chrome/browser/extensions/api/networking_private/networking_private_chromeos_apitest.cc index 23d4a382..b4076b9e 100644 --- a/chrome/browser/extensions/api/networking_private/networking_private_chromeos_apitest.cc +++ b/chrome/browser/extensions/api/networking_private/networking_private_chromeos_apitest.cc
@@ -23,7 +23,7 @@ #include "chrome/browser/extensions/extension_apitest.h" #include "chromeos/constants/chromeos_switches.h" #include "chromeos/cryptohome/cryptohome_parameters.h" -#include "chromeos/dbus/cryptohome_client.h" +#include "chromeos/dbus/cryptohome/cryptohome_client.h" #include "chromeos/dbus/dbus_thread_manager.h" #include "chromeos/dbus/shill_device_client.h" #include "chromeos/dbus/shill_ipconfig_client.h"
diff --git a/chrome/browser/extensions/api/settings_private/prefs_util.cc b/chrome/browser/extensions/api/settings_private/prefs_util.cc index 37c4bb0..57bac8d 100644 --- a/chrome/browser/extensions/api/settings_private/prefs_util.cc +++ b/chrome/browser/extensions/api/settings_private/prefs_util.cc
@@ -236,7 +236,7 @@ settings_api::PrefType::PREF_TYPE_BOOLEAN; (*s_whitelist)[::prefs::kOfferTranslateEnabled] = settings_api::PrefType::PREF_TYPE_BOOLEAN; - (*s_whitelist)[translate::TranslatePrefs::kPrefTranslateBlockedLanguages] = + (*s_whitelist)[language::prefs::kFluentLanguages] = settings_api::PrefType::PREF_TYPE_LIST; #if defined(OS_CHROMEOS) (*s_whitelist)[::prefs::kLanguageImeMenuActivated] =
diff --git a/chrome/browser/extensions/api/socket/tls_socket_unittest.cc b/chrome/browser/extensions/api/socket/tls_socket_unittest.cc index dadab921..72ae78a8 100644 --- a/chrome/browser/extensions/api/socket/tls_socket_unittest.cc +++ b/chrome/browser/extensions/api/socket/tls_socket_unittest.cc
@@ -133,7 +133,6 @@ net::StaticSocketDataProvider data_provider(kReads, kWrites); mock_client_socket_factory()->AddSocketDataProvider(&data_provider); net::SSLSocketDataProvider ssl_socket(net::ASYNC, net::OK); - ssl_socket.expected_ssl_version_max = net::SSL_PROTOCOL_VERSION_TLS1_2; mock_client_socket_factory()->AddSSLSocketDataProvider(&ssl_socket); std::unique_ptr<TLSSocket> socket = CreateSocket(); @@ -227,6 +226,47 @@ EXPECT_TRUE(ssl_socket.ConnectDataConsumed()); } +// Test the API can parse "tls1.3". +TEST_F(TLSSocketTest, UpgradeToTLSWithCustomOptionsTLS13) { + // Mock data are not consumed. These are here so that net::StreamSocket::Read + // is always pending and blocked on the write. Otherwise, mock socket data + // will complains that there aren't any data to read. + const net::MockRead kReads[] = { + net::MockRead(net::ASYNC, kTestMsg, kTestMsgLength, 1), + net::MockRead(net::ASYNC, net::OK, 2)}; + const net::MockWrite kWrites[] = { + net::MockWrite(net::ASYNC, kTestMsg, kTestMsgLength, 0)}; + net::SequencedSocketData data_provider(kReads, kWrites); + net::SSLSocketDataProvider ssl_socket(net::ASYNC, net::OK); + ssl_socket.expected_ssl_version_min = net::SSL_PROTOCOL_VERSION_TLS1_3; + ssl_socket.expected_ssl_version_max = net::SSL_PROTOCOL_VERSION_TLS1_3; + mock_client_socket_factory()->AddSocketDataProvider(&data_provider); + mock_client_socket_factory()->AddSSLSocketDataProvider(&ssl_socket); + + auto socket = CreateTCPSocket(); + network::mojom::TLSClientSocketPtr tls_socket_ptr; + api::socket::SecureOptions options; + options.tls_version = std::make_unique<api::socket::TLSVersionConstraints>(); + options.tls_version->min = std::make_unique<std::string>("tls1.3"); + options.tls_version->max = std::make_unique<std::string>("tls1.3"); + int net_error = net::ERR_FAILED; + base::RunLoop run_loop; + socket->UpgradeToTLS( + &options, + base::BindLambdaForTesting( + [&](int result, network::mojom::TLSClientSocketPtr tls_socket_ptr, + const net::IPEndPoint& local_addr, + const net::IPEndPoint& peer_addr, + mojo::ScopedDataPipeConsumerHandle receive_handle, + mojo::ScopedDataPipeProducerHandle send_handle) { + net_error = result; + run_loop.Quit(); + })); + run_loop.Run(); + EXPECT_EQ(net::OK, net_error); + EXPECT_TRUE(ssl_socket.ConnectDataConsumed()); +} + INSTANTIATE_TEST_SUITE_P(/* no prefix */, TLSSocketTest, testing::Values(net::SYNCHRONOUS, net::ASYNC)); @@ -240,7 +280,6 @@ net::MockWrite(net::SYNCHRONOUS, kTestMsg, kTestMsgLength, 0)}; net::SequencedSocketData data_provider(kReads, kWrites); net::SSLSocketDataProvider ssl_socket(io_mode, net::OK); - ssl_socket.expected_ssl_version_max = net::SSL_PROTOCOL_VERSION_TLS1_2; mock_client_socket_factory()->AddSocketDataProvider(&data_provider); mock_client_socket_factory()->AddSSLSocketDataProvider(&ssl_socket); std::unique_ptr<TLSSocket> socket = CreateSocket(); @@ -285,7 +324,6 @@ net::MockWrite(net::SYNCHRONOUS, kTestMsg, kTestMsgLength, 0)}; net::SequencedSocketData data_provider(kReads, kWrites); net::SSLSocketDataProvider ssl_socket(io_mode, net::OK); - ssl_socket.expected_ssl_version_max = net::SSL_PROTOCOL_VERSION_TLS1_2; mock_client_socket_factory()->AddSocketDataProvider(&data_provider); mock_client_socket_factory()->AddSSLSocketDataProvider(&ssl_socket); std::unique_ptr<TLSSocket> socket = CreateSocket(); @@ -330,7 +368,6 @@ net::MockWrite(net::SYNCHRONOUS, kTestMsg, kTestMsgLength, 0)}; net::SequencedSocketData data_provider(kReads, kWrites); net::SSLSocketDataProvider ssl_socket(io_mode, net::OK); - ssl_socket.expected_ssl_version_max = net::SSL_PROTOCOL_VERSION_TLS1_2; mock_client_socket_factory()->AddSocketDataProvider(&data_provider); mock_client_socket_factory()->AddSSLSocketDataProvider(&ssl_socket); @@ -387,7 +424,6 @@ 1)}; net::SequencedSocketData data_provider(kReads, kWrites); net::SSLSocketDataProvider ssl_socket(io_mode, net::OK); - ssl_socket.expected_ssl_version_max = net::SSL_PROTOCOL_VERSION_TLS1_2; mock_client_socket_factory()->AddSocketDataProvider(&data_provider); mock_client_socket_factory()->AddSSLSocketDataProvider(&ssl_socket); std::unique_ptr<TLSSocket> socket = CreateSocket(); @@ -422,7 +458,6 @@ net::SequencedSocketData data_provider(kReads, kWrites); net::SSLSocketDataProvider ssl_socket(io_mode, net::OK); - ssl_socket.expected_ssl_version_max = net::SSL_PROTOCOL_VERSION_TLS1_2; mock_client_socket_factory()->AddSocketDataProvider(&data_provider); mock_client_socket_factory()->AddSSLSocketDataProvider(&ssl_socket); @@ -462,7 +497,6 @@ net::SequencedSocketData data_provider(kReads, kWrites); net::SSLSocketDataProvider ssl_socket(io_mode, net::OK); - ssl_socket.expected_ssl_version_max = net::SSL_PROTOCOL_VERSION_TLS1_2; mock_client_socket_factory()->AddSocketDataProvider(&data_provider); mock_client_socket_factory()->AddSSLSocketDataProvider(&ssl_socket); std::unique_ptr<TLSSocket> socket = CreateSocket();
diff --git a/chrome/browser/extensions/api/web_request/web_request_api_unittest.cc b/chrome/browser/extensions/api/web_request/web_request_api_unittest.cc index 6ebdee2..c3e0289 100644 --- a/chrome/browser/extensions/api/web_request/web_request_api_unittest.cc +++ b/chrome/browser/extensions/api/web_request/web_request_api_unittest.cc
@@ -322,35 +322,31 @@ response = new ExtensionWebRequestEventRouter::EventResponse( extension1_id, base::Time::FromDoubleT(1)); response->new_url = not_chosen_redirect_url; - ipc_sender_.PushTask( - base::Bind(&EventHandledOnIOThread, - &profile_, extension1_id, kEventName, kEventName + "/1", - request->identifier(), response)); + ipc_sender_.PushTask(base::BindRepeating( + &EventHandledOnIOThread, &profile_, extension1_id, kEventName, + kEventName + "/1", request->identifier(), response)); // Extension2 response. Arrives second, and chosen because of install_time. response = new ExtensionWebRequestEventRouter::EventResponse( extension2_id, base::Time::FromDoubleT(2)); response->new_url = redirect_url; - ipc_sender_.PushTask( - base::Bind(&EventHandledOnIOThread, - &profile_, extension2_id, kEventName, kEventName + "/2", - request->identifier(), response)); + ipc_sender_.PushTask(base::BindRepeating( + &EventHandledOnIOThread, &profile_, extension2_id, kEventName, + kEventName + "/2", request->identifier(), response)); // Extension2 response to the redirected URL. Arrives first, and chosen. response = new ExtensionWebRequestEventRouter::EventResponse( extension2_id, base::Time::FromDoubleT(2)); - ipc_sender_.PushTask( - base::Bind(&EventHandledOnIOThread, - &profile_, extension2_id, kEventName, kEventName + "/2", - request->identifier(), response)); + ipc_sender_.PushTask(base::BindRepeating( + &EventHandledOnIOThread, &profile_, extension2_id, kEventName, + kEventName + "/2", request->identifier(), response)); // Extension1 response to the redirected URL. Arrives second, and ignored. response = new ExtensionWebRequestEventRouter::EventResponse( extension1_id, base::Time::FromDoubleT(1)); - ipc_sender_.PushTask( - base::Bind(&EventHandledOnIOThread, - &profile_, extension1_id, kEventName, kEventName + "/1", - request->identifier(), response)); + ipc_sender_.PushTask(base::BindRepeating( + &EventHandledOnIOThread, &profile_, extension1_id, kEventName, + kEventName + "/1", request->identifier(), response)); request->Start(); base::RunLoop().Run(); @@ -372,35 +368,31 @@ response = new ExtensionWebRequestEventRouter::EventResponse( extension2_id, base::Time::FromDoubleT(2)); response->new_url = redirect_url; - ipc_sender_.PushTask( - base::Bind(&EventHandledOnIOThread, - &profile_, extension2_id, kEventName, kEventName + "/2", - request2->identifier(), response)); + ipc_sender_.PushTask(base::BindRepeating( + &EventHandledOnIOThread, &profile_, extension2_id, kEventName, + kEventName + "/2", request2->identifier(), response)); // Extension1 response. Arrives second, but ignored due to install_time. response = new ExtensionWebRequestEventRouter::EventResponse( extension1_id, base::Time::FromDoubleT(1)); response->new_url = not_chosen_redirect_url; - ipc_sender_.PushTask( - base::Bind(&EventHandledOnIOThread, - &profile_, extension1_id, kEventName, kEventName + "/1", - request2->identifier(), response)); + ipc_sender_.PushTask(base::BindRepeating( + &EventHandledOnIOThread, &profile_, extension1_id, kEventName, + kEventName + "/1", request2->identifier(), response)); // Extension2 response to the redirected URL. Arrives first, and chosen. response = new ExtensionWebRequestEventRouter::EventResponse( extension2_id, base::Time::FromDoubleT(2)); - ipc_sender_.PushTask( - base::Bind(&EventHandledOnIOThread, - &profile_, extension2_id, kEventName, kEventName + "/2", - request2->identifier(), response)); + ipc_sender_.PushTask(base::BindRepeating( + &EventHandledOnIOThread, &profile_, extension2_id, kEventName, + kEventName + "/2", request2->identifier(), response)); // Extension1 response to the redirected URL. Arrives second, and ignored. response = new ExtensionWebRequestEventRouter::EventResponse( extension1_id, base::Time::FromDoubleT(1)); - ipc_sender_.PushTask( - base::Bind(&EventHandledOnIOThread, - &profile_, extension1_id, kEventName, kEventName + "/1", - request2->identifier(), response)); + ipc_sender_.PushTask(base::BindRepeating( + &EventHandledOnIOThread, &profile_, extension1_id, kEventName, + kEventName + "/1", request2->identifier(), response)); request2->Start(); base::RunLoop().Run(); @@ -453,20 +445,18 @@ response = new ExtensionWebRequestEventRouter::EventResponse( extension1_id, base::Time::FromDoubleT(1)); response->cancel = true; - ipc_sender_.PushTask( - base::Bind(&EventHandledOnIOThread, - &profile_, extension1_id, kEventName, kEventName + "/1", - request->identifier(), response)); + ipc_sender_.PushTask(base::BindRepeating( + &EventHandledOnIOThread, &profile_, extension1_id, kEventName, + kEventName + "/1", request->identifier(), response)); // Extension2 response. Arrives second, but has higher precedence // due to its later install_time. response = new ExtensionWebRequestEventRouter::EventResponse( extension2_id, base::Time::FromDoubleT(2)); response->new_url = redirect_url; - ipc_sender_.PushTask( - base::Bind(&EventHandledOnIOThread, - &profile_, extension2_id, kEventName, kEventName + "/2", - request->identifier(), response)); + ipc_sender_.PushTask(base::BindRepeating( + &EventHandledOnIOThread, &profile_, extension2_id, kEventName, + kEventName + "/2", request->identifier(), response)); request->Start(); @@ -520,18 +510,17 @@ extension_id, base::Time::FromDoubleT(1)); GURL redirect_url("about:redirected"); response->new_url = redirect_url; - ipc_sender_.PushTask( - base::Bind(&EventHandledOnIOThread, - &profile_, extension_id, kEventName, kEventName + "/1", - request->identifier(), response)); + ipc_sender_.PushTask(base::BindRepeating( + &EventHandledOnIOThread, &profile_, extension_id, kEventName, + kEventName + "/1", request->identifier(), response)); base::RunLoop run_loop; // Extension response for OnErrorOccurred: Terminate the message loop. - ipc_sender_.PushTask( - base::Bind(base::IgnoreResult(&base::SingleThreadTaskRunner::PostTask), - base::ThreadTaskRunnerHandle::Get(), FROM_HERE, - run_loop.QuitWhenIdleClosure())); + ipc_sender_.PushTask(base::BindRepeating( + base::IgnoreResult(&base::SingleThreadTaskRunner::PostTask), + base::ThreadTaskRunnerHandle::Get(), FROM_HERE, + run_loop.QuitWhenIdleClosure())); request->Start(); // request->Start() will have submitted OnBeforeRequest by the time we cancel. @@ -1063,10 +1052,10 @@ // Extension response for OnErrorOccurred: Terminate the message loop. { base::RunLoop run_loop; - ipc_sender_.PushTask( - base::Bind(base::IgnoreResult(&base::SingleThreadTaskRunner::PostTask), - base::ThreadTaskRunnerHandle::Get(), FROM_HERE, - run_loop.QuitWhenIdleClosure())); + ipc_sender_.PushTask(base::BindRepeating( + base::IgnoreResult(&base::SingleThreadTaskRunner::PostTask), + base::ThreadTaskRunnerHandle::Get(), FROM_HERE, + run_loop.QuitWhenIdleClosure())); request->Start(); run_loop.Run(); } @@ -1228,11 +1217,11 @@ // the block of modifications for the next extension starts. if (i+1 == test.modification_size || mod.extension_id != test.modification[i+1].extension_id) { - ipc_sender_.PushTask( - base::Bind(&EventHandledOnIOThread, - &profile_, mod.extension_id == 1 ? extension1_id : extension2_id, - kEventName, kEventName + (mod.extension_id == 1 ? "/1" : "/2"), - request->identifier(), response)); + ipc_sender_.PushTask(base::BindRepeating( + &EventHandledOnIOThread, &profile_, + mod.extension_id == 1 ? extension1_id : extension2_id, kEventName, + kEventName + (mod.extension_id == 1 ? "/1" : "/2"), + request->identifier(), response)); response = NULL; } }
diff --git a/chrome/browser/extensions/bookmark_app_navigation_throttle_browsertest.cc b/chrome/browser/extensions/bookmark_app_navigation_throttle_browsertest.cc index abf39795..53832d61 100644 --- a/chrome/browser/extensions/bookmark_app_navigation_throttle_browsertest.cc +++ b/chrome/browser/extensions/bookmark_app_navigation_throttle_browsertest.cc
@@ -845,7 +845,7 @@ IN_PROC_BROWSER_TEST_F(BookmarkAppNavigationThrottleExperimentalBrowserTest, PrerenderLinks) { prerender::PrerenderManager::SetMode( - prerender::PrerenderManager::PRERENDER_MODE_ENABLED); + prerender::PrerenderManager::DEPRECATED_PRERENDER_MODE_ENABLED); InstallTestBookmarkApp(); NavigateToLaunchingPage();
diff --git a/chrome/browser/flag-metadata.json b/chrome/browser/flag-metadata.json index bb3bc53..5473fcc 100644 --- a/chrome/browser/flag-metadata.json +++ b/chrome/browser/flag-metadata.json
@@ -207,6 +207,11 @@ "expiry_milestone": 73 }, { + "name": "autofill-enable-local-card-migration-for-non-sync-user", + "owners": [ "siyua" ], + "expiry_milestone": 76 + }, + { "name": "autofill-enable-toolbar-status-chip", "owners": [ "siyua" ], "expiry_milestone": 77 @@ -969,7 +974,7 @@ }, { "name": "enable-content-suggestions-thumbnail-dominant-color", - // "owners": [ "your-team" ], + "owners": [ "fgorski" ], "expiry_milestone": 76 }, { @@ -1353,8 +1358,10 @@ }, { "name": "enable-network-logging-to-file", - // "owners": [ "your-team" ], - "expiry_milestone": 76 + "owners": [ "eroman", "net-dev" ], + // This flag is used to capture early-browser network logging on platforms + // without easy access to startup time configuration. + "expiry_milestone": -1 }, { "name": "enable-new-contacts-picker", @@ -2761,11 +2768,6 @@ "expiry_milestone": 76 }, { - "name": "save-page-as-mhtml", - // "owners": [ "your-team" ], - "expiry_milestone": 76 - }, - { "name": "scheduler-configuration", "owners": [ "kerrnel", "mnissler" ], "expiry_milestone": 76
diff --git a/chrome/browser/flag-never-expire-list.json b/chrome/browser/flag-never-expire-list.json index 90e9273..277891e 100644 --- a/chrome/browser/flag-never-expire-list.json +++ b/chrome/browser/flag-never-expire-list.json
@@ -29,6 +29,7 @@ "enable-future-v8-vm-features", "enable-gpu-rasterization", "enable-gpu-service-logging", + "enable-network-logging-to-file", "enable-show-autofill-signatures", "enable-site-per-process", "enable-touchscreen-calibration",
diff --git a/chrome/browser/flag_descriptions.cc b/chrome/browser/flag_descriptions.cc index afc8c1a5..464dfc7e 100644 --- a/chrome/browser/flag_descriptions.cc +++ b/chrome/browser/flag_descriptions.cc
@@ -114,6 +114,12 @@ const char kAutofillEnableCompanyNameDescription[] = "When enabled, Company Name fields will be auto filled"; +const char kAutofillEnableLocalCardMigrationForNonSyncUserName[] = + "Enable local card migration flow for non-syncing users"; +const char kAutofillEnableLocalCardMigrationForNonSyncUserDescription[] = + "When enabled, the local card migration flow will be enabled for users who " + "have signed in but not enabled Chrome Sync."; + const char kAutofillEnableToolbarStatusChipName[] = "Move Autofill omnibox icons next to the profile avatar icon"; const char kAutofillEnableToolbarStatusChipDescription[] = @@ -1679,11 +1685,6 @@ "Enables an experiment to switch menu labels that use 'Save as...' to " "'Download'."; -const char kSavePageAsMhtmlName[] = "Save Page as MHTML"; -const char kSavePageAsMhtmlDescription[] = - "Enables saving pages as MHTML: a single text file containing HTML and all " - "sub-resources."; - const char kSendTabToSelfName[] = "Send tab to self"; const char kSendTabToSelfDescription[] = "Allows users to push tabs from Android devices to other synced "
diff --git a/chrome/browser/flag_descriptions.h b/chrome/browser/flag_descriptions.h index 9a7c87ec..5a3d96bb 100644 --- a/chrome/browser/flag_descriptions.h +++ b/chrome/browser/flag_descriptions.h
@@ -99,6 +99,9 @@ extern const char kAutofillEnableCompanyNameName[]; extern const char kAutofillEnableCompanyNameDescription[]; +extern const char kAutofillEnableLocalCardMigrationForNonSyncUserName[]; +extern const char kAutofillEnableLocalCardMigrationForNonSyncUserDescription[]; + extern const char kAutofillEnableToolbarStatusChipName[]; extern const char kAutofillEnableToolbarStatusChipDescription[]; @@ -997,9 +1000,6 @@ extern const char kSaveasMenuLabelExperimentName[]; extern const char kSaveasMenuLabelExperimentDescription[]; -extern const char kSavePageAsMhtmlName[]; -extern const char kSavePageAsMhtmlDescription[]; - extern const char kSendTabToSelfName[]; extern const char kSendTabToSelfDescription[];
diff --git a/chrome/browser/lookalikes/lookalike_url_navigation_throttle_browsertest.cc b/chrome/browser/lookalikes/lookalike_url_navigation_throttle_browsertest.cc index 7b6cf39..d44a5d5 100644 --- a/chrome/browser/lookalikes/lookalike_url_navigation_throttle_browsertest.cc +++ b/chrome/browser/lookalikes/lookalike_url_navigation_throttle_browsertest.cc
@@ -764,10 +764,6 @@ // URL should be showing again when we navigate to a normal URL NavigateToURLSync(browser(), GetURL("example.com")); EXPECT_TRUE(IsUrlShowing(browser())); - - // URL should still get hidden when we navigate to a page with a hidden URL. - NavigateToURLSync(browser(), GURL("chrome://newtab")); - EXPECT_FALSE(IsUrlShowing(browser())); } // Verify that bypassing warnings in the main profile does not affect incognito.
diff --git a/chrome/browser/memory/memory_pressure_monitor.cc b/chrome/browser/memory/memory_pressure_monitor.cc new file mode 100644 index 0000000..d4d8026 --- /dev/null +++ b/chrome/browser/memory/memory_pressure_monitor.cc
@@ -0,0 +1,52 @@ +// 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.h" + +#include "base/logging.h" +#include "base/memory/ptr_util.h" +#include "build/build_config.h" + +#if defined(OS_WIN) +#include "chrome/browser/memory/memory_pressure_monitor_win.h" +#endif + +namespace memory { +namespace { + +// The global instance. +MemoryPressureMonitor* g_memory_pressure_monitor = nullptr; + +} // namespace + +// static +std::unique_ptr<MemoryPressureMonitor> MemoryPressureMonitor::Create() { +#if defined(OS_WIN) + return base::WrapUnique(new MemoryPressureMonitorWin()); +#else + NOTREACHED(); + return base::WrapUnique(new MemoryPressureMonitor()); +#endif +} + +MemoryPressureMonitor::MemoryPressureMonitor() { + DCHECK(!g_memory_pressure_monitor); + g_memory_pressure_monitor = this; +} + +MemoryPressureMonitor::~MemoryPressureMonitor() { + DCHECK_EQ(this, g_memory_pressure_monitor); + g_memory_pressure_monitor = nullptr; +} + +void MemoryPressureMonitor::OnMemoryPressureLevelChange( + const base::MemoryPressureListener::MemoryPressureLevel previous_level, + const base::MemoryPressureListener::MemoryPressureLevel new_level) { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + // TODO(sebmarchand): Implement this function, add the logic that will record + // some metrics and dispatch the memory pressure level changes. + NOTREACHED(); +} + +} // namespace memory
diff --git a/chrome/browser/memory/memory_pressure_monitor.h b/chrome/browser/memory/memory_pressure_monitor.h new file mode 100644 index 0000000..2dbd4522 --- /dev/null +++ b/chrome/browser/memory/memory_pressure_monitor.h
@@ -0,0 +1,60 @@ +// 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_MEMORY_MEMORY_PRESSURE_MONITOR_H_ +#define CHROME_BROWSER_MEMORY_MEMORY_PRESSURE_MONITOR_H_ + +#include <memory> + +#include "base/macros.h" +#include "base/memory/memory_pressure_listener.h" +#include "base/sequence_checker.h" + +namespace memory { + +// The memory pressure monitor is responsible for monitoring some system metrics +// and determining when the system is under memory pressure. +// +// Each platform interested in tracking this should provide a platform specific +// implementation and make MemoryPressureMonitor::Create return it. These +// implementation are responsible for tracking the metrics they need (i.e. if +// some things need to run on a timer these classes should own this timer), they +// also need to call |OnMemoryPressureLevelChange| when the memory pressure +// level changes. +// +// It is recommended to use performance_monitor::SystemMonitor for the platform +// specific implementation. +// +// A single instance of this class can exist at the same time, in practice it is +// expected to be owned by the browser process. +// +// This class isn't thread safe, it should be created and used on the same +// sequence. +// +// NOTE: This class is still a work in progress and doesn't do anything yet. +class MemoryPressureMonitor { + public: + virtual ~MemoryPressureMonitor(); + + // Create the global instance. + static std::unique_ptr<MemoryPressureMonitor> Create(); + + protected: + MemoryPressureMonitor(); + + // This needs to be called by the platform specific implementation when the + // pressure level changes. + void OnMemoryPressureLevelChange( + const base::MemoryPressureListener::MemoryPressureLevel previous_level, + const base::MemoryPressureListener::MemoryPressureLevel new_level); + + private: + SEQUENCE_CHECKER(sequence_checker_); + + DISALLOW_COPY_AND_ASSIGN(MemoryPressureMonitor); +}; + +} // namespace memory + +#endif // CHROME_BROWSER_MEMORY_MEMORY_PRESSURE_MONITOR_H_
diff --git a/chrome/browser/memory/memory_pressure_monitor_win.cc b/chrome/browser/memory/memory_pressure_monitor_win.cc new file mode 100644 index 0000000..984fa69 --- /dev/null +++ b/chrome/browser/memory/memory_pressure_monitor_win.cc
@@ -0,0 +1,15 @@ +// 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_win.h" + +#include "base/logging.h" + +namespace memory { + +MemoryPressureMonitorWin::MemoryPressureMonitorWin() = default; + +MemoryPressureMonitorWin::~MemoryPressureMonitorWin() = default; + +} // namespace memory
diff --git a/chrome/browser/memory/memory_pressure_monitor_win.h b/chrome/browser/memory/memory_pressure_monitor_win.h new file mode 100644 index 0000000..b4c211b --- /dev/null +++ b/chrome/browser/memory/memory_pressure_monitor_win.h
@@ -0,0 +1,30 @@ +// 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_MEMORY_MEMORY_PRESSURE_MONITOR_WIN_H_ +#define CHROME_BROWSER_MEMORY_MEMORY_PRESSURE_MONITOR_WIN_H_ + +#include "base/macros.h" +#include "chrome/browser/memory/memory_pressure_monitor.h" + +namespace memory { + +// Windows implementation of the memory pressure monitor. +class MemoryPressureMonitorWin : public MemoryPressureMonitor { + public: + ~MemoryPressureMonitorWin() override; + + protected: + // This object is expected to be created via MemoryPressureMonitor::Create. + friend class MemoryPressureMonitor; + + MemoryPressureMonitorWin(); + + private: + DISALLOW_COPY_AND_ASSIGN(MemoryPressureMonitorWin); +}; + +} // namespace memory + +#endif // CHROME_BROWSER_MEMORY_MEMORY_PRESSURE_MONITOR_WIN_H_
diff --git a/chrome/browser/metrics/chrome_metrics_service_client_unittest.cc b/chrome/browser/metrics/chrome_metrics_service_client_unittest.cc index d966d66..3c565f7 100644 --- a/chrome/browser/metrics/chrome_metrics_service_client_unittest.cc +++ b/chrome/browser/metrics/chrome_metrics_service_client_unittest.cc
@@ -60,15 +60,15 @@ #if defined(OS_CHROMEOS) // ChromeOs Metrics Provider require g_login_state and power manager client // initialized before they can be instantiated. + chromeos::PowerManagerClient::InitializeFake(); chromeos::LoginState::Initialize(); - chromeos::PowerManagerClient::Initialize(); #endif // defined(OS_CHROMEOS) } void TearDown() override { #if defined(OS_CHROMEOS) - chromeos::PowerManagerClient::Shutdown(); chromeos::LoginState::Shutdown(); + chromeos::PowerManagerClient::Shutdown(); #endif // defined(OS_CHROMEOS) service_manager_context_.reset(); }
diff --git a/chrome/browser/metrics/chromeos_metrics_provider_unittest.cc b/chrome/browser/metrics/chromeos_metrics_provider_unittest.cc index ddee593..bad9e67 100644 --- a/chrome/browser/metrics/chromeos_metrics_provider_unittest.cc +++ b/chrome/browser/metrics/chromeos_metrics_provider_unittest.cc
@@ -78,7 +78,7 @@ new FakeBluetoothAgentManagerClient)); // Set up a PowerManagerClient instance for PerfProvider. - chromeos::PowerManagerClient::Initialize(); + chromeos::PowerManagerClient::InitializeFake(); // Grab pointers to members of the thread manager for easier testing. fake_bluetooth_adapter_client_ = static_cast<FakeBluetoothAdapterClient*>(
diff --git a/chrome/browser/metrics/perf/profile_provider_chromeos_unittest.cc b/chrome/browser/metrics/perf/profile_provider_chromeos_unittest.cc index 683548f1..a23a04a9 100644 --- a/chrome/browser/metrics/perf/profile_provider_chromeos_unittest.cc +++ b/chrome/browser/metrics/perf/profile_provider_chromeos_unittest.cc
@@ -130,8 +130,8 @@ void SetUp() override { // ProfileProvider requires chromeos::LoginState and // chromeos::PowerManagerClient to be initialized. + chromeos::PowerManagerClient::InitializeFake(); chromeos::LoginState::Initialize(); - chromeos::PowerManagerClient::Initialize(); profile_provider_ = std::make_unique<TestProfileProvider>(); profile_provider_->Init(); @@ -139,8 +139,8 @@ void TearDown() override { profile_provider_.reset(); - chromeos::PowerManagerClient::Shutdown(); chromeos::LoginState::Shutdown(); + chromeos::PowerManagerClient::Shutdown(); } protected: @@ -302,13 +302,13 @@ void SetUp() override { // ProfileProvider requires chromeos::LoginState and // chromeos::PowerManagerClient to be initialized. + chromeos::PowerManagerClient::InitializeFake(); chromeos::LoginState::Initialize(); - chromeos::PowerManagerClient::Initialize(); } void TearDown() override { - chromeos::PowerManagerClient::Shutdown(); chromeos::LoginState::Shutdown(); + chromeos::PowerManagerClient::Shutdown(); } private:
diff --git a/chrome/browser/metrics/process_memory_metrics_emitter.cc b/chrome/browser/metrics/process_memory_metrics_emitter.cc index fee8fe8..879775d4 100644 --- a/chrome/browser/metrics/process_memory_metrics_emitter.cc +++ b/chrome/browser/metrics/process_memory_metrics_emitter.cc
@@ -671,9 +671,11 @@ // |native_resident_kb| is only calculated for android devices that support // code ordering. Otherwise it is equal to zero and should not be reported. if (native_resident_kb != 0) { - MEMORY_METRICS_HISTOGRAM_KB( - "Memory.NativeLibrary.MappedAndResidentMemoryFootprint", - native_resident_kb); + // Size of the native library on android is ~40MB. + // More precision is needed in the middle buckets, hence the range. + base::UmaHistogramCustomCounts( + "Memory.NativeLibrary.MappedAndResidentMemoryFootprint2", + native_resident_kb, 1000, 100000, 100); } UMA_HISTOGRAM_MEMORY_LARGE_MB(
diff --git a/chrome/browser/metrics/process_memory_metrics_emitter_unittest.cc b/chrome/browser/metrics/process_memory_metrics_emitter_unittest.cc index 9e18b36..2d422db 100644 --- a/chrome/browser/metrics/process_memory_metrics_emitter_unittest.cc +++ b/chrome/browser/metrics/process_memory_metrics_emitter_unittest.cc
@@ -823,7 +823,7 @@ histograms.ExpectTotalCount("Memory.Total.SharedMemoryFootprint", 0); histograms.ExpectTotalCount("Memory.Total.ResidentSet", 0); histograms.ExpectTotalCount( - "Memory.NativeLibrary.MappedAndResidentMemoryFootprint", 0); + "Memory.NativeLibrary.MappedAndResidentMemoryFootprint2", 0); // Simulate some metrics emission. scoped_refptr<ProcessMemoryMetricsEmitterFake> emitter = @@ -857,7 +857,7 @@ 2 * kTestRendererResidentSet, 1); #endif histograms.ExpectUniqueSample( - "Memory.NativeLibrary.MappedAndResidentMemoryFootprint", + "Memory.NativeLibrary.MappedAndResidentMemoryFootprint2", kNativeLibraryResidentMemoryFootprint, 1); }
diff --git a/chrome/browser/page_load_metrics/observers/ad_metrics/ads_page_load_metrics_observer.cc b/chrome/browser/page_load_metrics/observers/ad_metrics/ads_page_load_metrics_observer.cc index 0afb634a7..cb48732e 100644 --- a/chrome/browser/page_load_metrics/observers/ad_metrics/ads_page_load_metrics_observer.cc +++ b/chrome/browser/page_load_metrics/observers/ad_metrics/ads_page_load_metrics_observer.cc
@@ -20,7 +20,6 @@ #include "content/public/browser/web_contents.h" #include "services/metrics/public/cpp/ukm_builders.h" #include "services/metrics/public/cpp/ukm_recorder.h" -#include "third_party/blink/public/common/download/download_stats.h" #include "third_party/blink/public/common/frame/sandbox_flags.h" #include "ui/gfx/geometry/size.h" #include "url/gurl.h" @@ -236,18 +235,6 @@ kNavigationDownloadInSandboxWithoutUserGesture; RecordSingleFeatureUsage(ad_host, web_feature); } - - blink::DownloadStats::SubframeDownloadFlags flags; - flags.has_sandbox = has_sandbox; - flags.is_cross_origin = - !IsSubframeSameOriginToMainFrame(ad_host, /*use_parent_origin=*/false); - flags.is_ad_frame = is_adframe; - flags.has_gesture = has_gesture; - blink::DownloadStats::RecordSubframeDownloadFlags( - flags, - ukm::GetSourceIdForWebContentsDocument( - navigation_handle->GetWebContents()), - ukm::UkmRecorder::Get()); } RecordAdFrameData(frame_tree_node_id, is_adframe, ad_host, @@ -281,15 +268,6 @@ kNavigationDownloadInSandboxWithoutUserGesture; RecordSingleFeatureUsage(rfh, web_feature); } - - blink::DownloadStats::MainFrameDownloadFlags flags; - flags.has_sandbox = has_sandbox; - flags.has_gesture = has_gesture; - blink::DownloadStats::RecordMainFrameDownloadFlags( - flags, - ukm::GetSourceIdForWebContentsDocument( - navigation_handle->GetWebContents()), - ukm::UkmRecorder::Get()); } }
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 7ab171b..894532e3 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
@@ -40,7 +40,6 @@ #include "services/metrics/public/cpp/ukm_builders.h" #include "services/metrics/public/cpp/ukm_source.h" #include "testing/gtest/include/gtest/gtest.h" -#include "third_party/blink/public/common/download/download_stats.h" #include "url/gurl.h" #include "url/url_constants.h" @@ -497,22 +496,25 @@ explicit AdsPageLoadMetricsTestWaiter(content::WebContents* web_contents) : page_load_metrics::PageLoadMetricsTestWaiter(web_contents) {} void AddMinimumAdResourceExpectation(int num_ad_resources) { - expected_minimum_num_ad_resources_ = num_ad_resources; + expected_minimum_ad_resources_ = num_ad_resources; } protected: bool ExpectationsSatisfied() const override { - int num_ad_resources = 0; - for (auto& kv : page_resources_) { - if (kv.second->reported_as_ad_resource && kv.second->is_complete) - num_ad_resources++; - } - return num_ad_resources >= expected_minimum_num_ad_resources_ && + return complete_ad_resources_ >= expected_minimum_ad_resources_ && PageLoadMetricsTestWaiter::ExpectationsSatisfied(); } + void HandleResourceUpdate( + const page_load_metrics::mojom::ResourceDataUpdatePtr& resource) + override { + if (resource->reported_as_ad_resource && resource->is_complete) + complete_ad_resources_++; + } + private: - int expected_minimum_num_ad_resources_ = 0; + int complete_ad_resources_ = 0; + int expected_minimum_ad_resources_ = 0; }; class AdsPageLoadMetricsObserverResourceBrowserTest @@ -554,6 +556,14 @@ } } + size_t GetNumDownloads() { + std::vector<download::DownloadItem*> download_items; + content::DownloadManager* manager = + content::BrowserContext::GetDownloadManager(browser()->profile()); + manager->GetAllDownloads(&download_items); + return download_items.size(); + } + protected: std::unique_ptr<AdsPageLoadMetricsTestWaiter> CreateAdsPageLoadMetricsTestWaiter() { @@ -1115,9 +1125,7 @@ web_contents(), base::BindRepeating(&content::FrameMatchesName, "test")); OpenLinkInFrame(rfh, "blocked_nav_download_id", false /* gesture*/); - SubprocessMetricsProvider::MergeHistogramDeltasForTesting(); - histogram_tester.ExpectTotalCount("Download.Subframe.SandboxOriginAdGesture", - 0); + EXPECT_EQ(0u, GetNumDownloads()); } class RemoteFrameNavigationBrowserTest @@ -1164,12 +1172,11 @@ "document.getElementById('test').src = \"" + dld_url.spec() + "\";")); subframe_navigation_waiter->Wait(); - SubprocessMetricsProvider::MergeHistogramDeltasForTesting(); - histogram_tester.ExpectTotalCount("Download.Subframe.SandboxOriginAdGesture", - 0 /* expected_count */); + + EXPECT_EQ(0u, GetNumDownloads()); } -class MainFrameDownloadFlagsBrowserTest +class DownloadInMainFrameBrowserTest : public AdsPageLoadMetricsObserverResourceBrowserTest, public ::testing::WithParamInterface<std::tuple< Origin, @@ -1192,8 +1199,8 @@ } }; -// Main frame download events are reported correctly. -IN_PROC_BROWSER_TEST_P(MainFrameDownloadFlagsBrowserTest, Download) { +// Downloads in main frame are handled correctly. +IN_PROC_BROWSER_TEST_P(DownloadInMainFrameBrowserTest, Download) { Origin origin; bool enable_blocking_downloads_in_sandbox_without_user_activation; SandboxOption sandbox_option; @@ -1293,39 +1300,16 @@ expected_download /* wait_count */, content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_FAIL)); OpenLinkInFrame(web_contents(), link_id, has_gesture); - download_observer->WaitForFinished(); if (web_feature_waiter) web_feature_waiter->Wait(); - SubprocessMetricsProvider::MergeHistogramDeltasForTesting(); - if (!expected_download) { - histogram_tester.ExpectTotalCount("Download.MainFrame.SandboxGesture", - 0 /* expected_count */); - return; - } - - blink::DownloadStats::MainFrameDownloadFlags expected_flags; - expected_flags.has_sandbox = expected_sandbox_bit; - expected_flags.has_gesture = has_gesture; - histogram_tester.ExpectUniqueSample("Download.MainFrame.SandboxGesture", - expected_flags.ToUmaValue(), - 1 /* expected_count */); - - auto entries = ukm_recorder.GetEntriesByName( - ukm::builders::MainFrameDownload::kEntryName); - EXPECT_EQ(1u, entries.size()); - ukm_recorder.ExpectEntrySourceHasUrl(entries.back(), main_url); - ukm_recorder.ExpectEntryMetric( - entries.back(), ukm::builders::MainFrameDownload::kHasSandboxName, - expected_sandbox_bit); - ukm_recorder.ExpectEntryMetric( - entries.back(), ukm::builders::MainFrameDownload::kHasGestureName, - has_gesture); + download_observer->WaitForFinished(); + EXPECT_EQ(expected_download, GetNumDownloads()); } INSTANTIATE_TEST_SUITE_P( /* no prefix */, - MainFrameDownloadFlagsBrowserTest, + DownloadInMainFrameBrowserTest, ::testing::Combine( ::testing::Values(Origin::kNavigation, Origin::kAnchorAttribute), ::testing::Bool(), @@ -1335,7 +1319,7 @@ SandboxOption::kAllowDownloadsWithoutUserActivation), ::testing::Bool())); -class SubframeDownloadFlagsBrowserTest +class DownloadInSubframeBrowserTest : public AdsPageLoadMetricsObserverResourceBrowserTest, public ::testing::WithParamInterface<std::tuple< Origin, @@ -1360,8 +1344,8 @@ } }; -// Subframe download events are reported correctly. -IN_PROC_BROWSER_TEST_P(SubframeDownloadFlagsBrowserTest, Download) { +// Downloads in subframe are handled correctly. +IN_PROC_BROWSER_TEST_P(DownloadInSubframeBrowserTest, Download) { Origin origin; bool enable_blocking_downloads_in_sandbox_without_user_activation; SandboxOption sandbox_option; @@ -1471,63 +1455,16 @@ web_contents(), base::BindRepeating(&content::FrameMatchesName, id)); OpenLinkInFrame(rfh, link_id, has_gesture); - download_observer->WaitForFinished(); if (waiter) waiter->Wait(); - SubprocessMetricsProvider::MergeHistogramDeltasForTesting(); - if (!expected_download) { - histogram_tester.ExpectTotalCount( - "Download.Subframe.SandboxOriginAdGesture", 0 /* expected_count */); - return; - } - - blink::DownloadStats::SubframeDownloadFlags expected_flags; - expected_flags.has_sandbox = expected_sandbox_bit; - expected_flags.is_cross_origin = is_cross_origin; - expected_flags.is_ad_frame = is_ad_frame; - expected_flags.has_gesture = has_gesture; - histogram_tester.ExpectUniqueSample( - "Download.Subframe.SandboxOriginAdGesture", expected_flags.ToUmaValue(), - 1 /* expected_count */); - - auto entries = ukm_recorder.GetEntriesByName( - ukm::builders::SubframeDownload::kEntryName); - EXPECT_EQ(1u, entries.size()); - - switch (origin) { - case Origin::kAnchorAttribute: { - const ukm::mojom::UkmEntry* dc_entry = - ukm_recorder.GetDocumentCreatedEntryForSourceId( - entries.back()->source_id); - const ukm::UkmSource* navigation_source = - ukm_recorder.GetSourceForSourceId(*ukm_recorder.GetEntryMetric( - dc_entry, - ukm::builders::DocumentCreated::kNavigationSourceIdName)); - EXPECT_EQ(main_url, navigation_source->url()); - } break; - case Origin::kNavigation: { - ukm_recorder.ExpectEntrySourceHasUrl(entries.back(), main_url); - } break; - } - - ukm_recorder.ExpectEntryMetric( - entries.back(), ukm::builders::SubframeDownload::kHasSandboxName, - expected_flags.has_sandbox); - ukm_recorder.ExpectEntryMetric( - entries.back(), ukm::builders::SubframeDownload::kIsCrossOriginName, - is_cross_origin); - ukm_recorder.ExpectEntryMetric( - entries.back(), ukm::builders::SubframeDownload::kIsAdFrameName, - is_ad_frame); - ukm_recorder.ExpectEntryMetric( - entries.back(), ukm::builders::SubframeDownload::kHasGestureName, - has_gesture); + download_observer->WaitForFinished(); + EXPECT_EQ(expected_download, GetNumDownloads()); } INSTANTIATE_TEST_SUITE_P( /* no prefix */, - SubframeDownloadFlagsBrowserTest, + DownloadInSubframeBrowserTest, ::testing::Combine( ::testing::Values(Origin::kNavigation, Origin::kAnchorAttribute), ::testing::Bool(),
diff --git a/chrome/browser/page_load_metrics/page_load_metrics_test_waiter.cc b/chrome/browser/page_load_metrics/page_load_metrics_test_waiter.cc index 72342a32..171a6584 100644 --- a/chrome/browser/page_load_metrics/page_load_metrics_test_waiter.cc +++ b/chrome/browser/page_load_metrics/page_load_metrics_test_waiter.cc
@@ -128,14 +128,7 @@ const std::vector<page_load_metrics::mojom::ResourceDataUpdatePtr>& resources) { for (auto const& resource : resources) { - auto it = page_resources_.find(resource->request_id); - if (it != page_resources_.end()) { - it->second = resource.Clone(); - } else { - page_resources_.emplace(std::piecewise_construct, - std::forward_as_tuple(resource->request_id), - std::forward_as_tuple(resource->Clone())); - } + HandleResourceUpdate(resource); if (resource->is_complete) { current_complete_resources_++; if (!resource->was_fetched_via_cache)
diff --git a/chrome/browser/page_load_metrics/page_load_metrics_test_waiter.h b/chrome/browser/page_load_metrics/page_load_metrics_test_waiter.h index e10595a..1e73c539 100644 --- a/chrome/browser/page_load_metrics/page_load_metrics_test_waiter.h +++ b/chrome/browser/page_load_metrics/page_load_metrics_test_waiter.h
@@ -73,11 +73,11 @@ protected: virtual bool ExpectationsSatisfied() const; - // Map of all resources loaded by the page, keyed by resource request id. - // Contains ongoing and completed resources. Contains only the most recent - // update (version) of the resource. - std::map<int, page_load_metrics::mojom::ResourceDataUpdatePtr> - page_resources_; + + // Intended to be overridden in tests to allow tests to wait on other resource + // conditions. + virtual void HandleResourceUpdate( + const page_load_metrics::mojom::ResourceDataUpdatePtr& resource) {} private: // PageLoadMetricsObserver used by the PageLoadMetricsTestWaiter to observe @@ -169,9 +169,8 @@ void OnLoadedResource(const page_load_metrics::ExtraRequestCompleteInfo& extra_request_complete_info); - // Updates resource map and associated data counters as updates are received - // from a resource load. Stops waiting if expectations are satisfied after - // update. + // Updates counters as updates are received from a resource load. Stops + // waiting if expectations are satisfied after update. void OnResourceDataUseObserved( FrameTreeNodeId frame_tree_node_id, const std::vector<page_load_metrics::mojom::ResourceDataUpdatePtr>&
diff --git a/chrome/browser/policy/cloud/cloud_policy_browsertest.cc b/chrome/browser/policy/cloud/cloud_policy_browsertest.cc index 1bc0785..d4575b6c 100644 --- a/chrome/browser/policy/cloud/cloud_policy_browsertest.cc +++ b/chrome/browser/policy/cloud/cloud_policy_browsertest.cc
@@ -64,7 +64,7 @@ #include "chrome/browser/chromeos/policy/user_policy_manager_factory_chromeos.h" #include "chromeos/cryptohome/cryptohome_parameters.h" #include "chromeos/dbus/constants/dbus_paths.h" -#include "chromeos/dbus/cryptohome_client.h" +#include "chromeos/dbus/cryptohome/cryptohome_client.h" #include "components/account_id/account_id.h" #include "components/user_manager/user_names.h" #else
diff --git a/chrome/browser/prefs/browser_prefs.cc b/chrome/browser/prefs/browser_prefs.cc index a1cf6d1..dba030d 100644 --- a/chrome/browser/prefs/browser_prefs.cc +++ b/chrome/browser/prefs/browser_prefs.cc
@@ -610,7 +610,7 @@ image_fetcher::ImageCache::RegisterProfilePrefs(registry); ImportantSitesUtil::RegisterProfilePrefs(registry); IncognitoModePrefs::RegisterProfilePrefs(registry); - language::RegisterProfilePrefs(registry); + language::LanguagePrefs::RegisterProfilePrefs(registry); MediaCaptureDevicesDispatcher::RegisterProfilePrefs(registry); MediaDeviceIDSalt::RegisterProfilePrefs(registry); MediaEngagementService::RegisterProfilePrefs(registry);
diff --git a/chrome/browser/prerender/prerender_browsertest.cc b/chrome/browser/prerender/prerender_browsertest.cc index 42850317..063567f9 100644 --- a/chrome/browser/prerender/prerender_browsertest.cc +++ b/chrome/browser/prerender/prerender_browsertest.cc
@@ -570,7 +570,7 @@ void SetUpOnMainThread() override { test_utils::PrerenderInProcessBrowserTest::SetUpOnMainThread(); prerender::PrerenderManager::SetMode( - prerender::PrerenderManager::PRERENDER_MODE_ENABLED); + prerender::PrerenderManager::DEPRECATED_PRERENDER_MODE_ENABLED); const testing::TestInfo* const test_info = testing::UnitTest::GetInstance()->current_test_info(); // This one test fails with the host resolver redirecting all hosts.
diff --git a/chrome/browser/prerender/prerender_manager.cc b/chrome/browser/prerender/prerender_manager.cc index 2e5a232..d6135ce 100644 --- a/chrome/browser/prerender/prerender_manager.cc +++ b/chrome/browser/prerender/prerender_manager.cc
@@ -248,10 +248,12 @@ const GURL& url, SessionStorageNamespace* session_storage_namespace, const gfx::Size& size) { - // TODO(pasko): Remove PRERENDER_MODE_ENABLED allowance. It is only used for - // tests. - if (!IsNoStatePrefetchEnabled() && GetMode() != PRERENDER_MODE_ENABLED) + // TODO(pasko): Remove DEPRECATED_PRERENDER_MODE_ENABLED allowance. It is only + // used for tests. + if (!IsNoStatePrefetchEnabled() && + GetMode() != DEPRECATED_PRERENDER_MODE_ENABLED) { return nullptr; + } return AddPrerender(ORIGIN_OMNIBOX, url, content::Referrer(), gfx::Rect(size), session_storage_namespace); }
diff --git a/chrome/browser/prerender/prerender_manager.h b/chrome/browser/prerender/prerender_manager.h index ad7429ee..e1e48cf 100644 --- a/chrome/browser/prerender/prerender_manager.h +++ b/chrome/browser/prerender/prerender_manager.h
@@ -80,7 +80,7 @@ public: enum PrerenderManagerMode { // Deprecated: Enables all types of prerendering for any origin. - PRERENDER_MODE_ENABLED, + DEPRECATED_PRERENDER_MODE_ENABLED, // For each request to prerender performs a NoStatePrefetch for the same URL // instead.
diff --git a/chrome/browser/profiles/profile_io_data.cc b/chrome/browser/profiles/profile_io_data.cc index 688c03a..fb71f3a 100644 --- a/chrome/browser/profiles/profile_io_data.cc +++ b/chrome/browser/profiles/profile_io_data.cc
@@ -135,7 +135,7 @@ #include "chrome/browser/chromeos/settings/cros_settings.h" #include "chrome/browser/net/nss_context.h" #include "chromeos/constants/chromeos_switches.h" -#include "chromeos/dbus/cryptohome_client.h" +#include "chromeos/dbus/cryptohome/cryptohome_client.h" #include "chromeos/dbus/dbus_thread_manager.h" #include "chromeos/settings/cros_settings_names.h" #include "chromeos/tpm/tpm_token_info_getter.h"
diff --git a/chrome/browser/profiles/profile_manager.cc b/chrome/browser/profiles/profile_manager.cc index 2583c010..07f7eb6 100644 --- a/chrome/browser/profiles/profile_manager.cc +++ b/chrome/browser/profiles/profile_manager.cc
@@ -132,7 +132,7 @@ #include "chrome/browser/browser_process_platform_part_chromeos.h" #include "chrome/browser/chromeos/profiles/profile_helper.h" #include "chromeos/constants/chromeos_switches.h" -#include "chromeos/dbus/cryptohome_client.h" +#include "chromeos/dbus/cryptohome/cryptohome_client.h" #include "chromeos/dbus/dbus_thread_manager.h" #include "components/arc/arc_features.h" #include "components/arc/arc_prefs.h"
diff --git a/chrome/browser/profiles/profile_metrics.cc b/chrome/browser/profiles/profile_metrics.cc index 6b771c5..be4b91c0 100644 --- a/chrome/browser/profiles/profile_metrics.cc +++ b/chrome/browser/profiles/profile_metrics.cc
@@ -432,10 +432,6 @@ UMA_HISTOGRAM_ENUMERATION("Profile.DesktopMenu.GAIAAddSession", metric, NUM_PROFILE_DESKTOP_MENU_METRICS); break; - case signin::GAIA_SERVICE_TYPE_REAUTH: - UMA_HISTOGRAM_ENUMERATION("Profile.DesktopMenu.GAIAReAuth", metric, - NUM_PROFILE_DESKTOP_MENU_METRICS); - break; case signin::GAIA_SERVICE_TYPE_SIGNUP: UMA_HISTOGRAM_ENUMERATION("Profile.DesktopMenu.GAIASignup", metric, NUM_PROFILE_DESKTOP_MENU_METRICS); @@ -488,12 +484,6 @@ metric, NUM_PROFILE_ANDROID_ACCOUNT_MANAGEMENT_MENU_METRICS); break; - case signin::GAIA_SERVICE_TYPE_REAUTH: - UMA_HISTOGRAM_ENUMERATION( - "Profile.AndroidAccountManagementMenu.GAIAReAuth", - metric, - NUM_PROFILE_ANDROID_ACCOUNT_MANAGEMENT_MENU_METRICS); - break; case signin::GAIA_SERVICE_TYPE_SIGNUP: UMA_HISTOGRAM_ENUMERATION( "Profile.AndroidAccountManagementMenu.GAIASignup",
diff --git a/chrome/browser/resource_coordinator/tab_load_tracker_unittest.cc b/chrome/browser/resource_coordinator/tab_load_tracker_unittest.cc index 2b0a2c9..087666f5 100644 --- a/chrome/browser/resource_coordinator/tab_load_tracker_unittest.cc +++ b/chrome/browser/resource_coordinator/tab_load_tracker_unittest.cc
@@ -390,7 +390,7 @@ // Prerender some contents. prerender::test_utils::RestorePrerenderMode restore_prerender_mode; prerender::PrerenderManager::SetMode( - prerender::PrerenderManager::PRERENDER_MODE_ENABLED); + prerender::PrerenderManager::DEPRECATED_PRERENDER_MODE_ENABLED); prerender::PrerenderManager* prerender_manager = prerender::PrerenderManagerFactory::GetForBrowserContext(profile()); GURL url("http://www.example.com");
diff --git a/chrome/browser/resources/chromeos/arc_graphics_tracing/arc_graphics_tracing.css b/chrome/browser/resources/chromeos/arc_graphics_tracing/arc_graphics_tracing.css index 0502cb7..a685200 100644 --- a/chrome/browser/resources/chromeos/arc_graphics_tracing/arc_graphics_tracing.css +++ b/chrome/browser/resources/chromeos/arc_graphics_tracing/arc_graphics_tracing.css
@@ -72,6 +72,7 @@ } .hidden.arc-events-inner-band, +.hidden.arc-events-inner-band-last-buffer, .hidden.arc-events-top-band { display: none; }
diff --git a/chrome/browser/resources/chromeos/arc_graphics_tracing/arc_graphics_tracing_ui.js b/chrome/browser/resources/chromeos/arc_graphics_tracing/arc_graphics_tracing_ui.js index d66ab314..17631c60 100644 --- a/chrome/browser/resources/chromeos/arc_graphics_tracing/arc_graphics_tracing_ui.js +++ b/chrome/browser/resources/chromeos/arc_graphics_tracing/arc_graphics_tracing_ui.js
@@ -475,9 +475,11 @@ $('arc-event-bands').textContent = ''; var chromeTopBandTitle = new EventBandTitle('Chrome'); - var chromeTopBand = new EventBand( - chromeTopBandTitle, 'arc-events-top-band', model.duration, 20); - chromeTopBand.setEvents(model.chrome, 500, 504); + for (i = 0; i < model.chrome.length; i++) { + var chromeTopBand = new EventBand( + chromeTopBandTitle, 'arc-events-top-band', model.duration, 20); + chromeTopBand.setEvents(model.chrome[i], 500, 504); + } var androidTopBandTitle = new EventBandTitle('Android'); var androidTopBand = new EventBand(
diff --git a/chrome/browser/resources/pdf/pdf_viewer.js b/chrome/browser/resources/pdf/pdf_viewer.js index 30a01f5..755a373b4 100644 --- a/chrome/browser/resources/pdf/pdf_viewer.js +++ b/chrome/browser/resources/pdf/pdf_viewer.js
@@ -1590,7 +1590,8 @@ this.viewer_.setIsSelecting(message.data.isSelecting); break; case 'getNamedDestinationReply': - this.paramsParser_.onNamedDestinationReceived(message.data.pageNumber); + this.viewer_.paramsParser_.onNamedDestinationReceived( + message.data.pageNumber); break; case 'formFocusChange': this.viewer_.setIsFormFieldFocused(message.data.focused);
diff --git a/chrome/browser/resources/print_preview/new/model.js b/chrome/browser/resources/print_preview/new/model.js index 1026abd..8c762d30 100644 --- a/chrome/browser/resources/print_preview/new/model.js +++ b/chrome/browser/resources/print_preview/new/model.js
@@ -26,7 +26,8 @@ * isCssBackgroundEnabled: (boolean | undefined), * scaling: (string | undefined), * vendor_options: (Object | undefined), - * isPinEnabled: (boolean | undefined) + * isPinEnabled: (boolean | undefined), + * pinValue: (string | undefined) * }} */ print_preview_new.SerializedSettings; @@ -92,7 +93,7 @@ 'vendorItems', ]; // <if expr="chromeos"> -STICKY_SETTING_NAMES.push('pin'); +STICKY_SETTING_NAMES.push('pin', 'pinValue'); // </if> /** @@ -312,10 +313,18 @@ value: false, unavailableValue: false, valid: true, - available: true, + available: false, setByPolicy: false, key: 'isPinEnabled', }; + value.pinValue = { + value: '', + unavailableValue: '', + valid: true, + available: false, + setByPolicy: false, + key: 'pinValue', + }; // </if> return value; }, @@ -356,7 +365,7 @@ 'settings.scaling.value, settings.duplex.value, ' + 'settings.headerFooter.value, settings.cssBackground.value, ' + 'settings.vendorItems.value, settings.recentDestinations.value.*)', - 'stickySettingsChanged_(settings.pin.value)', + 'stickySettingsChanged_(settings.pin.value, settings.pinValue.value)', ], /** @private {boolean} */ @@ -425,10 +434,10 @@ 'settings.vendorItems.available', !!caps && !!caps.vendor_capability); // <if expr="chromeos"> - this.set( - 'settings.pin.available', - !!caps && !!caps.pin && !!caps.pin.supported && - loadTimeData.getBoolean('isEnterpriseManaged')); + const pinSupported = !!caps && !!caps.pin && !!caps.pin.supported && + loadTimeData.getBoolean('isEnterpriseManaged'); + this.set('settings.pin.available', pinSupported); + this.set('settings.pinValue.available', pinSupported); // </if> if (this.documentSettings) { @@ -787,6 +796,7 @@ const pinPolicy = this.destination.pinPolicy; if (pinPolicy == print_preview.PinModeRestriction.UNSECURE) { this.set('settings.pin.available', false); + this.set('settings.pinValue.available', false); } const pinValue = pinPolicy ? pinPolicy : this.destination.defaultPinPolicy; if (pinValue) { @@ -907,6 +917,12 @@ ticket.OpenPDFInPreview = true; } + // <if expr="chromeos"> + if (this.getSettingValue('pin')) { + ticket.pinValue = this.getSettingValue('pinValue'); + } + // </if> + return JSON.stringify(ticket); },
diff --git a/chrome/browser/resources/print_preview/new/settings_behavior.js b/chrome/browser/resources/print_preview/new/settings_behavior.js index 791cab15..df1b280 100644 --- a/chrome/browser/resources/print_preview/new/settings_behavior.js +++ b/chrome/browser/resources/print_preview/new/settings_behavior.js
@@ -40,6 +40,7 @@ * ranges: !print_preview_new.Setting, * pagesPerSheet: !print_preview_new.Setting, * pin: (print_preview_new.Setting|undefined), + * pinValue: (print_preview_new.Setting|undefined), * }} */ print_preview_new.Settings;
diff --git a/chrome/browser/resources/settings/languages_page/languages_page.html b/chrome/browser/resources/settings/languages_page/languages_page.html index a16b7623..bbc7609 100644 --- a/chrome/browser/resources/settings/languages_page/languages_page.html +++ b/chrome/browser/resources/settings/languages_page/languages_page.html
@@ -91,7 +91,7 @@ #uiLanguageItem cr-policy-indicator { float: right; - margin-left: 20px; + margin-inline-start: 20px; } .name-with-error-list { @@ -365,7 +365,7 @@ detailLanguage_, languages.translateTarget)]]"> $i18n{offerToTranslateInThisLanguage} </cr-checkbox> - <hr> + <hr hidden="[[!shouldShowDialogSeparator_(languages.enabled.*)]]"> <button class="dropdown-item" role="menuitem" on-click="onMoveToTopTap_" hidden="[[isNthLanguage_(
diff --git a/chrome/browser/resources/settings/languages_page/languages_page.js b/chrome/browser/resources/settings/languages_page/languages_page.js index 2fdcb73..5ce1ef7 100644 --- a/chrome/browser/resources/settings/languages_page/languages_page.js +++ b/chrome/browser/resources/settings/languages_page/languages_page.js
@@ -168,6 +168,17 @@ }, /** + * Used to determine whether to show the separator between checkbox settings + * and move buttons in the dialog menu. + * @return {boolean} True if there is currently more than one selected + * language. + * @private + */ + shouldShowDialogSeparator_: function() { + return this.languages != undefined && this.languages.enabled.length > 1; + }, + + /** * Used to determine which "Move" buttons to show for ordering enabled * languages. * @param {number} n
diff --git a/chrome/browser/resources/welcome/onboarding_welcome/email/nux_email.html b/chrome/browser/resources/welcome/onboarding_welcome/email/nux_email.html index 26a93302..1c8b099 100644 --- a/chrome/browser/resources/welcome/onboarding_welcome/email/nux_email.html +++ b/chrome/browser/resources/welcome/onboarding_welcome/email/nux_email.html
@@ -23,7 +23,7 @@ } h1 { - color: var(--google-grey-900); + color: var(--cr-primary-text-color); font-size: 1.5rem; font-weight: 500; margin: 0;
diff --git a/chrome/browser/resources/welcome/onboarding_welcome/google_apps/nux_google_apps.html b/chrome/browser/resources/welcome/onboarding_welcome/google_apps/nux_google_apps.html index 2dac7e1b..51fc1c9 100644 --- a/chrome/browser/resources/welcome/onboarding_welcome/google_apps/nux_google_apps.html +++ b/chrome/browser/resources/welcome/onboarding_welcome/google_apps/nux_google_apps.html
@@ -23,7 +23,7 @@ } h1 { - color: var(--google-grey-900); + color: var(--cr-primary-text-color); font-size: 1.5rem; font-weight: 500; margin: 0;
diff --git a/chrome/browser/resources/welcome/onboarding_welcome/ntp_background/nux_ntp_background.html b/chrome/browser/resources/welcome/onboarding_welcome/ntp_background/nux_ntp_background.html index 1ce760b..132f6c5 100644 --- a/chrome/browser/resources/welcome/onboarding_welcome/ntp_background/nux_ntp_background.html +++ b/chrome/browser/resources/welcome/onboarding_welcome/ntp_background/nux_ntp_background.html
@@ -67,7 +67,7 @@ } h1 { - color: var(--google-grey-900); + color: var(--cr-primary-text-color); font-size: 1.5rem; font-weight: 500; margin: 0;
diff --git a/chrome/browser/resources/welcome/onboarding_welcome/onboarding_welcome_resources.grd b/chrome/browser/resources/welcome/onboarding_welcome/onboarding_welcome_resources.grd index b1837e2..0017267 100644 --- a/chrome/browser/resources/welcome/onboarding_welcome/onboarding_welcome_resources.grd +++ b/chrome/browser/resources/welcome/onboarding_welcome/onboarding_welcome_resources.grd
@@ -219,6 +219,10 @@ file="shared\module_metrics_proxy.js" compress="gzip" type="chrome_html" /> + <structure name="IDR_WELCOME_ONBOARDING_WELCOME_SHARED_NAVI_COLORS_CSS" + file="shared\navi_colors_css.html" + compress="gzip" + type="chrome_html" /> <structure name="IDR_WELCOME_ONBOARDING_WELCOME_SHARED_ONBOARDING_BACKGROUND_HTML" file="shared\onboarding_background.html" compress="gzip"
diff --git a/chrome/browser/resources/welcome/onboarding_welcome/set_as_default/nux_set_as_default.html b/chrome/browser/resources/welcome/onboarding_welcome/set_as_default/nux_set_as_default.html index c88537c4..97e8087 100644 --- a/chrome/browser/resources/welcome/onboarding_welcome/set_as_default/nux_set_as_default.html +++ b/chrome/browser/resources/welcome/onboarding_welcome/set_as_default/nux_set_as_default.html
@@ -39,7 +39,7 @@ } h1 { - color: var(--google-grey-900); + color: var(--cr-primary-text-color); font-size: 1.5rem; font-weight: 500; line-height: 2.5rem; @@ -48,7 +48,7 @@ } h2 { - color: var(--google-grey-900); + color: var(--cr-secondary-text-color); font-size: 1.25rem; font-weight: unset; line-height: 1.875rem;
diff --git a/chrome/browser/resources/welcome/onboarding_welcome/shared/action_link_style_css.html b/chrome/browser/resources/welcome/onboarding_welcome/shared/action_link_style_css.html index b4fb1e7..6e51989 100644 --- a/chrome/browser/resources/welcome/onboarding_welcome/shared/action_link_style_css.html +++ b/chrome/browser/resources/welcome/onboarding_welcome/shared/action_link_style_css.html
@@ -12,7 +12,7 @@ -webkit-appearance: none; background: none; border: none; - color: var(--google-blue-700); + color: var(--cr-link-color); display: inline-block; font-family: inherit; text-decoration: none; @@ -31,4 +31,4 @@ </template> </dom-module> -<script src="action_link_style.js"></script> \ No newline at end of file +<script src="action_link_style.js"></script>
diff --git a/chrome/browser/resources/welcome/onboarding_welcome/shared/chooser_shared_css.html b/chrome/browser/resources/welcome/onboarding_welcome/shared/chooser_shared_css.html index 283c7f05..5a0687fa 100644 --- a/chrome/browser/resources/welcome/onboarding_welcome/shared/chooser_shared_css.html +++ b/chrome/browser/resources/welcome/onboarding_welcome/shared/chooser_shared_css.html
@@ -1,12 +1,13 @@ <link rel="import" href="chrome://resources/html/polymer.html"> <link rel="import" href="chrome://resources/cr_elements/shared_vars_css.html"> +<link rel="import" href="chrome://resources/html/md_select_css.html"> +<link rel="import" href="navi_colors_css.html"> <dom-module id="chooser-shared-css"> <template> - <style> + <style include="navi-colors-css"> :host { - color: var(--google-grey-900); display: block; white-space: nowrap; } @@ -14,10 +15,11 @@ .option { -webkit-appearance: none; align-items: center; - background: white; - border: 1px solid var(--google-grey-refresh-300); + background: var(--cr-card-background-color); + border: 1px solid var(--navi-border-color); border-radius: 8px; box-sizing: border-box; + color: var(--cr-primary-text-color); cursor: pointer; display: inline-flex; flex-direction: column; @@ -33,12 +35,12 @@ } .option:hover { - box-shadow: 0 3px 6px 2px rgba(0, 36, 100, .1); + box-shadow: var(--navi-option-box-shadow); } .option[active] { - border: 1px solid var(--google-blue-600); - color: var(--google-blue-600); + border: 1px solid var(--cr-checked-color); + color: var(--cr-checked-color); font-weight: 500; } @@ -47,7 +49,7 @@ } .option.keyboard-focused:focus { - outline: rgba(26, 115, 232, 0.4) solid 3px; + outline: var(--navi-keyboard-focus-color) solid 3px; } .option .option-name { @@ -68,7 +70,7 @@ } .option .option-icon-shadow { - background-color: var(--google-grey-refresh-100); + background-color: var(--navi-option-icon-shadow-color); border-radius: 50%; display: flex; height: 3rem; @@ -82,8 +84,8 @@ } .option iron-icon { - --iron-icon-fill-color: white; - background: lightgrey; + --iron-icon-fill-color: var(--cr-card-background-color); + background: var(--navi-check-icon-color); border-radius: 50%; display: none; height: 0.75rem; @@ -101,7 +103,7 @@ } .option[active] iron-icon[icon='cr:check'] { - background: var(--google-blue-600); + background: var(--cr-checked-color); } .button-bar {
diff --git a/chrome/browser/resources/welcome/onboarding_welcome/shared/navi_colors_css.html b/chrome/browser/resources/welcome/onboarding_welcome/shared/navi_colors_css.html new file mode 100644 index 0000000..2daae91 --- /dev/null +++ b/chrome/browser/resources/welcome/onboarding_welcome/shared/navi_colors_css.html
@@ -0,0 +1,30 @@ +<link rel="import" href="chrome://resources/html/polymer.html"> + +<link rel="import" href="chrome://resources/cr_elements/shared_vars_css.html"> +<link rel="import" href="chrome://resources/html/md_select_css.html"> + +<dom-module id="navi-colors-css"> + <template> + <style> + :host { + --navi-border-color: var(--google-grey-refresh-300); + --navi-check-icon-color: lightgrey; + --navi-keyboard-focus-color: rgba(var(--google-blue-600-rgb), .4); + --navi-option-box-shadow: + 0 1px 2px 0 rgba(var(--google-grey-800-rgb), .3), + 0 3px 6px 2px rgba(var(--google-grey-800-rgb), .15); + --navi-option-icon-shadow-color: var(--google-grey-refresh-100); + } + + :host-context([dark]) { + --navi-border-color: var(--google-grey-refresh-700); + --navi-check-icon-color: var(--google-grey-refresh-700); + --navi-keyboard-focus-color: + rgba(var(--google-blue-refresh-300-rgb), .5); + --navi-option-box-shadow: 0 1px 2px 0 rgba(0, 0, 0, .3), + 0 3px 6px 2px rgba(0, 0, 0, .15); + --navi-option-icon-shadow-color: var(--google-grey-800); + } + </style> + </template> +</dom-module>
diff --git a/chrome/browser/resources/welcome/onboarding_welcome/shared/splash_pages_shared_css.html b/chrome/browser/resources/welcome/onboarding_welcome/shared/splash_pages_shared_css.html index c23baac..a5d332c8 100644 --- a/chrome/browser/resources/welcome/onboarding_welcome/shared/splash_pages_shared_css.html +++ b/chrome/browser/resources/welcome/onboarding_welcome/shared/splash_pages_shared_css.html
@@ -1,10 +1,11 @@ <link rel="import" href="chrome://resources/html/polymer.html"> <link rel="import" href="chrome://resources/cr_elements/shared_vars_css.html"> +<link rel="import" href="navi_colors_css.html"> <dom-module id="splash-pages-shared-css"> <template> - <style> + <style include="navi-colors-css"> #container { align-items: center; display: flex; @@ -16,6 +17,7 @@ } h1 { + color: var(--cr-primary-text-color); font-size: 4rem; margin-bottom: 40px; margin-top: 16px; @@ -23,7 +25,7 @@ } h2 { - color: var(--google-grey-600); + color: var(--cr-secondary-text-color); font-size: 1.5rem; font-weight: 500; line-height: 2.25rem; @@ -49,4 +51,4 @@ } </style> </template> -</dom-module> \ No newline at end of file +</dom-module>
diff --git a/chrome/browser/resources/welcome/onboarding_welcome/welcome.html b/chrome/browser/resources/welcome/onboarding_welcome/welcome.html index 165ac0a..74245cd 100644 --- a/chrome/browser/resources/welcome/onboarding_welcome/welcome.html +++ b/chrome/browser/resources/welcome/onboarding_welcome/welcome.html
@@ -1,14 +1,21 @@ <!doctype html> -<html dir="$i18n{textdirection}" lang="$i18n{language}"> +<html dir="$i18n{textdirection}" lang="$i18n{language}" $i18n{dark}> <head> <meta charset="utf-8"> <title>$i18n{headerText}</title> <link rel="import" href="welcome_app.html"> + <link rel="stylesheet" href="chrome://resources/css/md_colors.css"> <link rel="stylesheet" href="chrome://resources/css/text_defaults_md.css"> - <link rel="stylesheet" href="chrome://welcome/welcome.css"> </head> <body> + <style> + html { + background: var(--md-background-color); + } + </style> <welcome-app></welcome-app> <script src="/welcome.js"></script> + <link rel="import" href="chrome://resources/html/dark_mode.html"> + <link rel="stylesheet" href="chrome://welcome/welcome.css"> </body> </html>
diff --git a/chrome/browser/send_tab_to_self/send_tab_to_self_util.cc b/chrome/browser/send_tab_to_self/send_tab_to_self_util.cc index 7926de2..e84a32f 100644 --- a/chrome/browser/send_tab_to_self/send_tab_to_self_util.cc +++ b/chrome/browser/send_tab_to_self/send_tab_to_self_util.cc
@@ -21,6 +21,7 @@ #include "components/sync/driver/sync_driver_switches.h" #include "components/sync/driver/sync_service.h" #include "components/sync/driver/sync_user_settings.h" +#include "content/public/browser/navigation_entry.h" #include "content/public/browser/web_contents.h" #include "content/public/common/url_constants.h" #include "url/gurl.h" @@ -71,12 +72,18 @@ } void CreateNewEntry(content::WebContents* tab, Profile* profile) { - GURL url = tab->GetURL(); - std::string title = base::UTF16ToUTF8(tab->GetTitle()); - const send_tab_to_self::SendTabToSelfEntry* entry = + content::NavigationEntry* navigation_entry = + tab->GetController().GetLastCommittedEntry(); + + GURL url = navigation_entry->GetURL(); + std::string title = base::UTF16ToUTF8(navigation_entry->GetTitle()); + base::Time navigation_time = navigation_entry->GetTimestamp(); + + const SendTabToSelfEntry* entry = SendTabToSelfSyncServiceFactory::GetForProfile(profile) ->GetSendTabToSelfModel() - ->AddEntry(url, title); + ->AddEntry(url, title, navigation_time); + if (entry) { DesktopNotificationHandler(profile).DisplaySendingConfirmation(entry); } else {
diff --git a/chrome/browser/send_tab_to_self/send_tab_to_self_util_unittest.cc b/chrome/browser/send_tab_to_self/send_tab_to_self_util_unittest.cc index 5754238..ea74720 100644 --- a/chrome/browser/send_tab_to_self/send_tab_to_self_util_unittest.cc +++ b/chrome/browser/send_tab_to_self/send_tab_to_self_util_unittest.cc
@@ -23,6 +23,7 @@ #include "components/sync/device_info/device_info_sync_service.h" #include "components/sync/driver/sync_driver_switches.h" #include "components/sync/driver/test_sync_service.h" +#include "content/public/browser/navigation_entry.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #include "url/gurl.h" @@ -103,8 +104,10 @@ SendTabToSelfModelMock() = default; ~SendTabToSelfModelMock() override = default; - MOCK_METHOD2(AddEntry, - const SendTabToSelfEntry*(const GURL&, const std::string&)); + MOCK_METHOD3(AddEntry, + const SendTabToSelfEntry*(const GURL&, + const std::string&, + base::Time)); MOCK_METHOD1(DeleteEntry, void(const std::string&)); MOCK_METHOD1(DismissEntry, void(const std::string&)); @@ -153,6 +156,7 @@ incognito_profile_ = profile()->GetOffTheRecordProfile(); url_ = GURL("https://www.google.com"); + title_ = base::UTF8ToUTF16(base::StringPiece("Google")); } // Set up all test conditions to let ShouldOfferFeature() return true @@ -164,7 +168,7 @@ mock_device_sync_service_->SetTrackerActiveDevices(2); AddTab(browser(), url_); - NavigateAndCommitActiveTab(url_); + NavigateAndCommitActiveTabWithTitle(browser(), url_, title_); } // Set up a environment in which the feature flag is disabled @@ -176,7 +180,7 @@ mock_device_sync_service_->SetTrackerActiveDevices(2); AddTab(browser(), url_); - NavigateAndCommitActiveTab(url_); + NavigateAndCommitActiveTabWithTitle(browser(), url_, title_); } protected: @@ -185,6 +189,7 @@ base::test::ScopedFeatureList scoped_feature_list_; Profile* incognito_profile_; GURL url_; + base::string16 title_; }; TEST_F(SendTabToSelfUtilTest, IsFlagEnabled_True) { @@ -275,7 +280,7 @@ ShouldOfferFeature_IsContentRequirementsMet_False) { SetUpAllTrueEnv(); url_ = GURL("192.168.0.0"); - NavigateAndCommitActiveTab(url_); + NavigateAndCommitActiveTabWithTitle(browser(), url_, title_); EXPECT_FALSE(ShouldOfferFeature(browser())); } @@ -286,13 +291,18 @@ profile(), base::BindRepeating(&BuildTestSendTabToSelfSyncService)); content::WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents(); - GURL url = tab->GetURL(); - std::string title = base::UTF16ToUTF8(tab->GetTitle()); + content::NavigationEntry* entry = + tab->GetController().GetLastCommittedEntry(); + + GURL url = entry->GetURL(); + std::string title = base::UTF16ToUTF8(entry->GetTitle()); + base::Time navigation_time = entry->GetTimestamp(); + SendTabToSelfModelMock* model_mock = static_cast<SendTabToSelfModelMock*>( SendTabToSelfSyncServiceFactory::GetForProfile(profile()) ->GetSendTabToSelfModel()); - EXPECT_CALL(*model_mock, AddEntry(url, title)) + EXPECT_CALL(*model_mock, AddEntry(url, title, navigation_time)) .WillOnce(testing::Return(nullptr)); CreateNewEntry(tab, profile());
diff --git a/chrome/browser/signin/identity_manager_factory.cc b/chrome/browser/signin/identity_manager_factory.cc index db84b9b..b959db1 100644 --- a/chrome/browser/signin/identity_manager_factory.cc +++ b/chrome/browser/signin/identity_manager_factory.cc
@@ -4,15 +4,20 @@ #include "chrome/browser/signin/identity_manager_factory.h" +#include <utility> + #include "build/build_config.h" +#include "chrome/browser/browser_process.h" #include "chrome/browser/profiles/profile.h" +#include "chrome/browser/signin/account_consistency_mode_manager.h" #include "chrome/browser/signin/account_fetcher_service_factory.h" #include "chrome/browser/signin/account_tracker_service_factory.h" +#include "chrome/browser/signin/chrome_signin_client_factory.h" #include "chrome/browser/signin/gaia_cookie_manager_service_factory.h" #include "chrome/browser/signin/profile_oauth2_token_service_factory.h" -#include "chrome/browser/signin/signin_manager_factory.h" #include "components/keyed_service/content/browser_context_dependency_manager.h" #include "components/keyed_service/core/keyed_service.h" +#include "components/pref_registry/pref_registry_syncable.h" #include "components/signin/core/browser/signin_manager.h" #include "services/identity/public/cpp/accounts_cookie_mutator.h" #include "services/identity/public/cpp/accounts_cookie_mutator_impl.h" @@ -31,15 +36,22 @@ namespace { +#if !defined(OS_CHROMEOS) +using ConcreteSigninManager = SigninManager; +#else +using ConcreteSigninManager = SigninManagerBase; +#endif + // Helper function returning a newly constructed PrimaryAccountMutator for // |profile|. May return null if mutation of the signed-in state is not // supported on the current platform. std::unique_ptr<identity::PrimaryAccountMutator> BuildPrimaryAccountMutator( - Profile* profile) { + Profile* profile, + ConcreteSigninManager* signin_manager) { #if !defined(OS_CHROMEOS) return std::make_unique<identity::PrimaryAccountMutatorImpl>( AccountTrackerServiceFactory::GetForProfile(profile), - SigninManagerFactory::GetForProfile(profile)); + SigninManager::FromSigninManagerBase(signin_manager)); #else return nullptr; #endif @@ -49,17 +61,38 @@ // |profile|. May return null if mutation of accounts is not supported on the // current platform. std::unique_ptr<identity::AccountsMutator> BuildAccountsMutator( - Profile* profile) { + Profile* profile, + SigninManagerBase* signin_manager) { #if !defined(OS_ANDROID) return std::make_unique<identity::AccountsMutatorImpl>( ProfileOAuth2TokenServiceFactory::GetForProfile(profile), - AccountTrackerServiceFactory::GetForProfile(profile), - SigninManagerFactory::GetForProfile(profile), profile->GetPrefs()); + AccountTrackerServiceFactory::GetForProfile(profile), signin_manager, + profile->GetPrefs()); #else return nullptr; #endif } +std::unique_ptr<ConcreteSigninManager> BuildSigninManager(Profile* profile) { + std::unique_ptr<ConcreteSigninManager> signin_manager; + SigninClient* client = + ChromeSigninClientFactory::GetInstance()->GetForProfile(profile); +#if defined(OS_CHROMEOS) + signin_manager = std::make_unique<ConcreteSigninManager>( + client, ProfileOAuth2TokenServiceFactory::GetForProfile(profile), + AccountTrackerServiceFactory::GetForProfile(profile)); +#else + signin_manager = std::make_unique<ConcreteSigninManager>( + client, ProfileOAuth2TokenServiceFactory::GetForProfile(profile), + AccountTrackerServiceFactory::GetForProfile(profile), + GaiaCookieManagerServiceFactory::GetForProfile(profile), + AccountConsistencyModeManager::GetMethodForProfile(profile)); +#endif + AccountFetcherServiceFactory::GetForProfile(profile); + signin_manager->Initialize(g_browser_process->local_state()); + return signin_manager; +} + } // namespace // Subclass that wraps IdentityManager in a KeyedService (as IdentityManager is @@ -71,15 +104,19 @@ class IdentityManagerWrapper : public KeyedService, public identity::IdentityManager { public: - explicit IdentityManagerWrapper(Profile* profile) + explicit IdentityManagerWrapper( + Profile* profile, + std::unique_ptr<SigninManagerBase> signin_manager, + std::unique_ptr<identity::PrimaryAccountMutator> primary_account_mutator, + std::unique_ptr<identity::AccountsMutator> accounts_mutator) : identity::IdentityManager( - SigninManagerFactory::GetForProfile(profile), + std::move(signin_manager), ProfileOAuth2TokenServiceFactory::GetForProfile(profile), AccountFetcherServiceFactory::GetForProfile(profile), AccountTrackerServiceFactory::GetForProfile(profile), GaiaCookieManagerServiceFactory::GetForProfile(profile), - BuildPrimaryAccountMutator(profile), - BuildAccountsMutator(profile), + std::move(primary_account_mutator), + std::move(accounts_mutator), std::make_unique<identity::AccountsCookieMutatorImpl>( GaiaCookieManagerServiceFactory::GetForProfile(profile)), std::make_unique<identity::DiagnosticsProviderImpl>( @@ -87,15 +124,20 @@ GaiaCookieManagerServiceFactory::GetForProfile(profile))) {} }; +void IdentityManagerFactory::RegisterProfilePrefs( + user_prefs::PrefRegistrySyncable* registry) { + SigninManagerBase::RegisterProfilePrefs(registry); +} + IdentityManagerFactory::IdentityManagerFactory() : BrowserContextKeyedServiceFactory( "IdentityManager", BrowserContextDependencyManager::GetInstance()) { DependsOn(AccountFetcherServiceFactory::GetInstance()); DependsOn(AccountTrackerServiceFactory::GetInstance()); + DependsOn(ChromeSigninClientFactory::GetInstance()); DependsOn(GaiaCookieManagerServiceFactory::GetInstance()); DependsOn(ProfileOAuth2TokenServiceFactory::GetInstance()); - DependsOn(SigninManagerFactory::GetInstance()); } IdentityManagerFactory::~IdentityManagerFactory() {} @@ -124,9 +166,9 @@ void IdentityManagerFactory::EnsureFactoryAndDependeeFactoriesBuilt() { IdentityManagerFactory::GetInstance(); AccountTrackerServiceFactory::GetInstance(); + ChromeSigninClientFactory::GetInstance(); GaiaCookieManagerServiceFactory::GetInstance(); ProfileOAuth2TokenServiceFactory::GetInstance(); - SigninManagerFactory::GetInstance(); } void IdentityManagerFactory::AddObserver(Observer* observer) { @@ -139,8 +181,19 @@ KeyedService* IdentityManagerFactory::BuildServiceInstanceFor( content::BrowserContext* context) const { + Profile* profile = Profile::FromBrowserContext(context); + + // Construct the dependencies that IdentityManager will own. + std::unique_ptr<ConcreteSigninManager> signin_manager = + BuildSigninManager(profile); + std::unique_ptr<identity::PrimaryAccountMutator> primary_account_mutator = + BuildPrimaryAccountMutator(profile, signin_manager.get()); + std::unique_ptr<identity::AccountsMutator> accounts_mutator = + BuildAccountsMutator(profile, signin_manager.get()); + auto identity_manager = std::make_unique<IdentityManagerWrapper>( - Profile::FromBrowserContext(context)); + profile, std::move(signin_manager), std::move(primary_account_mutator), + std::move(accounts_mutator)); for (Observer& observer : observer_list_) observer.IdentityManagerCreated(identity_manager.get()); return identity_manager.release();
diff --git a/chrome/browser/signin/identity_manager_factory.h b/chrome/browser/signin/identity_manager_factory.h index 01aaa3d..0b7814b 100644 --- a/chrome/browser/signin/identity_manager_factory.h +++ b/chrome/browser/signin/identity_manager_factory.h
@@ -63,6 +63,8 @@ KeyedService* BuildServiceInstanceFor( content::BrowserContext* profile) const override; void BrowserContextShutdown(content::BrowserContext* profile) override; + void RegisterProfilePrefs( + user_prefs::PrefRegistrySyncable* registry) override; // List of observers. Checks that list is empty on destruction. base::ObserverList<Observer, /*check_empty=*/true, /*allow_reentrancy=*/false>
diff --git a/chrome/browser/signin/identity_test_environment_profile_adaptor.cc b/chrome/browser/signin/identity_test_environment_profile_adaptor.cc index ae8e757..d21c246 100644 --- a/chrome/browser/signin/identity_test_environment_profile_adaptor.cc +++ b/chrome/browser/signin/identity_test_environment_profile_adaptor.cc
@@ -11,7 +11,6 @@ #include "chrome/browser/signin/gaia_cookie_manager_service_factory.h" #include "chrome/browser/signin/identity_manager_factory.h" #include "chrome/browser/signin/profile_oauth2_token_service_factory.h" -#include "chrome/browser/signin/signin_manager_factory.h" #include "components/signin/core/browser/fake_profile_oauth2_token_service.h" namespace { @@ -92,6 +91,5 @@ AccountFetcherServiceFactory::GetForProfile(profile), static_cast<FakeProfileOAuth2TokenService*>( ProfileOAuth2TokenServiceFactory::GetForProfile(profile)), - SigninManagerFactory::GetForProfile(profile), GaiaCookieManagerServiceFactory::GetForProfile(profile), IdentityManagerFactory::GetForProfile(profile)) {}
diff --git a/chrome/browser/signin/signin_manager_factory.cc b/chrome/browser/signin/signin_manager_factory.cc deleted file mode 100644 index 5284c8f2..0000000 --- a/chrome/browser/signin/signin_manager_factory.cc +++ /dev/null
@@ -1,108 +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. - -#include "chrome/browser/signin/signin_manager_factory.h" - -#include "build/build_config.h" -#include "chrome/browser/browser_process.h" -#include "chrome/browser/profiles/profile.h" -#include "chrome/browser/signin/account_consistency_mode_manager.h" -#include "chrome/browser/signin/account_fetcher_service_factory.h" -#include "chrome/browser/signin/account_tracker_service_factory.h" -#include "chrome/browser/signin/chrome_signin_client_factory.h" -#include "chrome/browser/signin/gaia_cookie_manager_service_factory.h" -#include "chrome/browser/signin/local_auth.h" -#include "chrome/browser/signin/profile_oauth2_token_service_factory.h" -#include "components/keyed_service/content/browser_context_dependency_manager.h" -#include "components/pref_registry/pref_registry_syncable.h" -#include "components/signin/core/browser/signin_manager.h" - -SigninManagerFactory::SigninManagerFactory() - : BrowserContextKeyedServiceFactory( - "SigninManager", - BrowserContextDependencyManager::GetInstance()) { - DependsOn(AccountTrackerServiceFactory::GetInstance()); - DependsOn(ChromeSigninClientFactory::GetInstance()); - DependsOn(GaiaCookieManagerServiceFactory::GetInstance()); - DependsOn(ProfileOAuth2TokenServiceFactory::GetInstance()); -} - -SigninManagerFactory::~SigninManagerFactory() { -} - -#if defined(OS_CHROMEOS) -// static -SigninManagerBase* SigninManagerFactory::GetForProfileIfExists( - Profile* profile) { - return static_cast<SigninManagerBase*>( - GetInstance()->GetServiceForBrowserContext(profile, false)); -} - -const SigninManagerBase* SigninManagerFactory::GetForProfileIfExists( - const Profile* profile) { - return static_cast<const SigninManagerBase*>( - GetInstance()->GetServiceForBrowserContext( - const_cast<Profile*>(profile), false)); -} - -// static -SigninManagerBase* SigninManagerFactory::GetForProfile( - Profile* profile) { - return static_cast<SigninManagerBase*>( - GetInstance()->GetServiceForBrowserContext(profile, true)); -} - -#else -// static -SigninManager* SigninManagerFactory::GetForProfile(Profile* profile) { - return static_cast<SigninManager*>( - GetInstance()->GetServiceForBrowserContext(profile, true)); -} - -// static -SigninManager* SigninManagerFactory::GetForProfileIfExists(Profile* profile) { - return static_cast<SigninManager*>( - GetInstance()->GetServiceForBrowserContext(profile, false)); -} - -// static -const SigninManager* SigninManagerFactory::GetForProfileIfExists( - const Profile* profile) { - return static_cast<const SigninManager*>( - GetInstance()->GetServiceForBrowserContext( - const_cast<Profile*>(profile), false)); -} -#endif - -// static -SigninManagerFactory* SigninManagerFactory::GetInstance() { - return base::Singleton<SigninManagerFactory>::get(); -} - -void SigninManagerFactory::RegisterProfilePrefs( - user_prefs::PrefRegistrySyncable* registry) { - SigninManagerBase::RegisterProfilePrefs(registry); -} - -KeyedService* SigninManagerFactory::BuildServiceInstanceFor( - content::BrowserContext* context) const { - SigninManagerBase* service = NULL; - Profile* profile = static_cast<Profile*>(context); - SigninClient* client = - ChromeSigninClientFactory::GetInstance()->GetForProfile(profile); -#if defined(OS_CHROMEOS) - service = new SigninManagerBase( - client, ProfileOAuth2TokenServiceFactory::GetForProfile(profile), - AccountTrackerServiceFactory::GetForProfile(profile)); -#else - service = new SigninManager( - client, ProfileOAuth2TokenServiceFactory::GetForProfile(profile), - AccountTrackerServiceFactory::GetForProfile(profile), - GaiaCookieManagerServiceFactory::GetForProfile(profile), - AccountConsistencyModeManager::GetMethodForProfile(profile)); -#endif - AccountFetcherServiceFactory::GetForProfile(profile); - service->Initialize(g_browser_process->local_state()); - return service; -}
diff --git a/chrome/browser/signin/signin_manager_factory.h b/chrome/browser/signin/signin_manager_factory.h deleted file mode 100644 index a1446b9..0000000 --- a/chrome/browser/signin/signin_manager_factory.h +++ /dev/null
@@ -1,59 +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 CHROME_BROWSER_SIGNIN_SIGNIN_MANAGER_FACTORY_H_ -#define CHROME_BROWSER_SIGNIN_SIGNIN_MANAGER_FACTORY_H_ - -#include "base/memory/singleton.h" -#include "build/build_config.h" -#include "components/keyed_service/content/browser_context_keyed_service_factory.h" - -class SigninManager; -class SigninManagerBase; -class Profile; - -// Singleton that owns all SigninManagers and associates them with -// Profiles. Listens for the Profile's destruction notification and cleans up -// the associated SigninManager. -class SigninManagerFactory : public BrowserContextKeyedServiceFactory { - public: -#if defined(OS_CHROMEOS) - // Returns the instance of SigninManager associated with this profile - // (creating one if none exists). Returns NULL if this profile cannot have a - // SigninManager (for example, if |profile| is incognito). - static SigninManagerBase* GetForProfile(Profile* profile); - - // Returns the instance of SigninManager associated with this profile. Returns - // null if no SigninManager instance currently exists (will not create a new - // instance). - static SigninManagerBase* GetForProfileIfExists(Profile* profile); - static const SigninManagerBase* GetForProfileIfExists(const Profile* profile); -#else - // On non-ChromeOS platforms, the SigninManager the factory creates will be - // an instance of the extended SigninManager class. - static SigninManager* GetForProfile(Profile* profile); - static SigninManager* GetForProfileIfExists(Profile* profile); - static const SigninManager* GetForProfileIfExists(const Profile* profile); -#endif - - // Returns an instance of the SigninManagerFactory singleton. - static SigninManagerFactory* GetInstance(); - - // Implementation of BrowserContextKeyedServiceFactory (public so tests - // can call it). - void RegisterProfilePrefs( - user_prefs::PrefRegistrySyncable* registry) override; - - private: - friend struct base::DefaultSingletonTraits<SigninManagerFactory>; - - SigninManagerFactory(); - ~SigninManagerFactory() override; - - // BrowserContextKeyedServiceFactory: - KeyedService* BuildServiceInstanceFor( - content::BrowserContext* profile) const override; -}; - -#endif // CHROME_BROWSER_SIGNIN_SIGNIN_MANAGER_FACTORY_H_
diff --git a/chrome/browser/sync/profile_sync_service_android.cc b/chrome/browser/sync/profile_sync_service_android.cc index c4271cf..c4c2aee 100644 --- a/chrome/browser/sync/profile_sync_service_android.cc +++ b/chrome/browser/sync/profile_sync_service_android.cc
@@ -34,7 +34,6 @@ #include "components/sync/driver/sync_service_utils.h" #include "components/sync/engine/net/network_resources.h" #include "components/sync_sessions/session_sync_service.h" -#include "components/unified_consent/url_keyed_data_collection_consent_helper.h" #include "content/public/browser/browser_thread.h" #include "google_apis/gaia/google_service_auth_error.h" #include "jni/ProfileSyncService_jni.h" @@ -46,7 +45,6 @@ using base::android::JavaParamRef; using base::android::ScopedJavaLocalRef; using content::BrowserThread; -using unified_consent::UrlKeyedDataCollectionConsentHelper; namespace { @@ -352,35 +350,11 @@ return sync_service_->HasUnrecoverableError(); } -jboolean ProfileSyncServiceAndroid::IsUrlKeyedDataCollectionEnabled( - JNIEnv* env, - const base::android::JavaParamRef<jobject>& obj, - jboolean personalized) { - DCHECK_CURRENTLY_ON(BrowserThread::UI); - std::unique_ptr<UrlKeyedDataCollectionConsentHelper> - unified_consent_url_helper; - if (personalized) { - unified_consent_url_helper = UrlKeyedDataCollectionConsentHelper:: - NewPersonalizedDataCollectionConsentHelper(sync_service_); - } else { - PrefService* pref_service = profile_->GetPrefs(); - unified_consent_url_helper = UrlKeyedDataCollectionConsentHelper:: - NewAnonymizedDataCollectionConsentHelper(pref_service, sync_service_); - } - - return unified_consent_url_helper->IsEnabled(); -} - -jint ProfileSyncServiceAndroid::GetProtocolErrorClientAction( +jboolean ProfileSyncServiceAndroid::RequiresClientUpgrade( JNIEnv* env, const JavaParamRef<jobject>&) { DCHECK_CURRENTLY_ON(BrowserThread::UI); - // TODO(crbug.com/940437): The Java side is only interested in UPGRADE_CLIENT - // errors specifically, so use RequiresClientUpgrade() here instead of - // QueryDetailedSyncStatus(). - syncer::SyncStatus status; - sync_service_->QueryDetailedSyncStatus(&status); - return status.sync_protocol_error.action; + return sync_service_->RequiresClientUpgrade(); } jboolean ProfileSyncServiceAndroid::IsPassphrasePrompted(
diff --git a/chrome/browser/sync/profile_sync_service_android.h b/chrome/browser/sync/profile_sync_service_android.h index 354856af..50a1fa1 100644 --- a/chrome/browser/sync/profile_sync_service_android.h +++ b/chrome/browser/sync/profile_sync_service_android.h
@@ -119,9 +119,7 @@ JNIEnv* env, const base::android::JavaParamRef<jobject>& obj, jboolean personalized); - - // Gets SyncProtocolError.ClientAction. - jint GetProtocolErrorClientAction( + jboolean RequiresClientUpgrade( JNIEnv* env, const base::android::JavaParamRef<jobject>& obj);
diff --git a/chrome/browser/sync/profile_sync_test_util.cc b/chrome/browser/sync/profile_sync_test_util.cc deleted file mode 100644 index a3f3866..0000000 --- a/chrome/browser/sync/profile_sync_test_util.cc +++ /dev/null
@@ -1,67 +0,0 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/sync/profile_sync_test_util.h" - -#include <utility> - -#include "base/bind.h" -#include "base/bind_helpers.h" -#include "base/location.h" -#include "base/single_thread_task_runner.h" -#include "chrome/browser/invalidation/deprecated_profile_invalidation_provider_factory.h" -#include "chrome/browser/invalidation/profile_invalidation_provider_factory.h" -#include "chrome/browser/profiles/profile.h" -#include "chrome/browser/signin/identity_manager_factory.h" -#include "chrome/browser/signin/identity_test_environment_profile_adaptor.h" -#include "chrome/browser/sync/chrome_sync_client.h" -#include "chrome/common/channel_info.h" -#include "chrome/test/base/testing_profile.h" -#include "components/browser_sync/profile_sync_service.h" -#include "components/browser_sync/profile_sync_test_util.h" -#include "components/invalidation/impl/invalidation_switches.h" -#include "components/invalidation/impl/profile_invalidation_provider.h" -#include "components/sync/driver/startup_controller.h" -#include "components/sync/driver/sync_api_component_factory_mock.h" -#include "content/public/browser/browser_context.h" -#include "content/public/browser/storage_partition.h" -#include "services/network/public/cpp/shared_url_loader_factory.h" - -using browser_sync::ProfileSyncService; -using testing::NiceMock; - -ProfileSyncService::InitParams CreateProfileSyncServiceParamsForTest( - Profile* profile) { - ProfileSyncService::InitParams init_params; - - init_params.identity_manager = IdentityManagerFactory::GetForProfile(profile); - init_params.start_behavior = ProfileSyncService::MANUAL_START; - init_params.sync_client = - std::make_unique<browser_sync::ChromeSyncClient>(profile); - init_params.network_time_update_callback = base::DoNothing(); - bool fcm_invalidations_enabled = - base::FeatureList::IsEnabled(invalidation::switches::kFCMInvalidations); - if (fcm_invalidations_enabled) { - init_params.invalidations_identity_providers.push_back( - invalidation::ProfileInvalidationProviderFactory::GetForProfile(profile) - ->GetIdentityProvider()); - } - init_params.invalidations_identity_providers.push_back( - invalidation::DeprecatedProfileInvalidationProviderFactory::GetForProfile( - profile) - ->GetIdentityProvider()); - init_params.url_loader_factory = - content::BrowserContext::GetDefaultStoragePartition(profile) - ->GetURLLoaderFactoryForBrowserProcess(); - init_params.debug_identifier = profile->GetDebugName(); - - return init_params; -} - -std::unique_ptr<KeyedService> BuildMockProfileSyncService( - content::BrowserContext* context) { - return std::make_unique<NiceMock<browser_sync::ProfileSyncServiceMock>>( - CreateProfileSyncServiceParamsForTest( - Profile::FromBrowserContext(context))); -}
diff --git a/chrome/browser/sync/profile_sync_test_util.h b/chrome/browser/sync/profile_sync_test_util.h deleted file mode 100644 index 9c0abe6..0000000 --- a/chrome/browser/sync/profile_sync_test_util.h +++ /dev/null
@@ -1,48 +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 CHROME_BROWSER_SYNC_PROFILE_SYNC_TEST_UTIL_H_ -#define CHROME_BROWSER_SYNC_PROFILE_SYNC_TEST_UTIL_H_ - -#include <memory> -#include <string> - -#include "base/memory/ref_counted.h" -#include "base/run_loop.h" -#include "components/browser_sync/profile_sync_service_mock.h" -#include "content/public/browser/browser_thread.h" -#include "content/public/browser/notification_service.h" -#include "content/public/browser/notification_source.h" -#include "content/public/browser/notification_types.h" -#include "testing/gmock/include/gmock/gmock.h" - -class KeyedService; -class Profile; - -namespace content { -class BrowserContext; -} - -ACTION_P(Notify, type) { - content::NotificationService::current()->Notify( - type, - content::NotificationService::AllSources(), - content::NotificationService::NoDetails()); -} - -ACTION(QuitUIMessageLoop) { - DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - base::RunLoop::QuitCurrentWhenIdleDeprecated(); -} - -// Helper methods for constructing ProfileSyncService mocks. -browser_sync::ProfileSyncService::InitParams -CreateProfileSyncServiceParamsForTest(Profile* profile); - -// Helper routine to be used in conjunction with -// BrowserContextKeyedServiceFactory::SetTestingFactory(). -std::unique_ptr<KeyedService> BuildMockProfileSyncService( - content::BrowserContext* context); - -#endif // CHROME_BROWSER_SYNC_PROFILE_SYNC_TEST_UTIL_H_
diff --git a/chrome/browser/sync/send_tab_to_self_sync_service_factory.cc b/chrome/browser/sync/send_tab_to_self_sync_service_factory.cc index 12ad59b0..49914b7 100644 --- a/chrome/browser/sync/send_tab_to_self_sync_service_factory.cc +++ b/chrome/browser/sync/send_tab_to_self_sync_service_factory.cc
@@ -6,6 +6,7 @@ #include "base/bind.h" #include "base/memory/singleton.h" +#include "chrome/browser/history/history_service_factory.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/signin/chrome_device_id_helper.h" #include "chrome/browser/sync/device_info_sync_service_factory.h" @@ -36,6 +37,7 @@ BrowserContextDependencyManager::GetInstance()) { DependsOn(DeviceInfoSyncServiceFactory::GetInstance()); DependsOn(ModelTypeStoreServiceFactory::GetInstance()); + DependsOn(HistoryServiceFactory::GetInstance()); } SendTabToSelfSyncServiceFactory::~SendTabToSelfSyncServiceFactory() {} @@ -51,7 +53,11 @@ syncer::OnceModelTypeStoreFactory store_factory = ModelTypeStoreServiceFactory::GetForProfile(profile)->GetStoreFactory(); + history::HistoryService* history_service = + HistoryServiceFactory::GetForProfile(profile, + ServiceAccessType::EXPLICIT_ACCESS); + return new send_tab_to_self::SendTabToSelfSyncService( chrome::GetChannel(), local_device_info_provider, - std::move(store_factory)); + std::move(store_factory), history_service); }
diff --git a/chrome/browser/sync/test/integration/autofill_helper.cc b/chrome/browser/sync/test/integration/autofill_helper.cc index eda3ddb..0a34edb 100644 --- a/chrome/browser/sync/test/integration/autofill_helper.cc +++ b/chrome/browser/sync/test/integration/autofill_helper.cc
@@ -16,7 +16,6 @@ #include "chrome/browser/autofill/personal_data_manager_factory.h" #include "chrome/browser/chrome_notification_types.h" #include "chrome/browser/profiles/profile.h" -#include "chrome/browser/sync/profile_sync_test_util.h" #include "chrome/browser/sync/test/integration/sync_datatype_helper.h" #include "chrome/browser/sync/test/integration/sync_test.h" #include "chrome/browser/web_data_service_factory.h"
diff --git a/chrome/browser/sync/test/integration/single_client_send_tab_to_self_sync_test.cc b/chrome/browser/sync/test/integration/single_client_send_tab_to_self_sync_test.cc index fef3bdd5..3b713bc 100644 --- a/chrome/browser/sync/test/integration/single_client_send_tab_to_self_sync_test.cc +++ b/chrome/browser/sync/test/integration/single_client_send_tab_to_self_sync_test.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/time/time.h" #include "chrome/browser/sync/send_tab_to_self_sync_service_factory.h" #include "chrome/browser/sync/test/integration/send_tab_to_self_helper.h" #include "chrome/browser/sync/test/integration/sync_test.h" @@ -29,17 +30,19 @@ DownloadWhenSyncEnabled) { const std::string kUrl("https://www.example.com"); const std::string kGuid("kGuid"); - sync_pb::EntitySpecifics specifics; sync_pb::SendTabToSelfSpecifics* send_tab_to_self = specifics.mutable_send_tab_to_self(); send_tab_to_self->set_url(kUrl); send_tab_to_self->set_guid(kGuid); + send_tab_to_self->set_shared_time_usec( + base::Time::Now().ToDeltaSinceWindowsEpoch().InMicroseconds()); fake_server_->InjectEntity( syncer::PersistentUniqueClientEntity::CreateFromSpecificsForTesting( - "non_unique_name", kGuid, specifics, /*creation_time=*/0, - /*last_modified_time=*/0)); + "non_unique_name", kGuid, specifics, + /*creation_time=*/base::Time::Now().ToTimeT(), + /*last_modified_time=*/base::Time::Now().ToTimeT())); ASSERT_TRUE(SetupSync());
diff --git a/chrome/browser/sync/test/integration/two_client_send_tab_to_self_sync_test.cc b/chrome/browser/sync/test/integration/two_client_send_tab_to_self_sync_test.cc index 2357d4c..e60a74a 100644 --- a/chrome/browser/sync/test/integration/two_client_send_tab_to_self_sync_test.cc +++ b/chrome/browser/sync/test/integration/two_client_send_tab_to_self_sync_test.cc
@@ -2,9 +2,12 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +#include "base/run_loop.h" +#include "chrome/browser/history/history_service_factory.h" #include "chrome/browser/sync/send_tab_to_self_sync_service_factory.h" #include "chrome/browser/sync/test/integration/send_tab_to_self_helper.h" #include "chrome/browser/sync/test/integration/sync_test.h" +#include "components/history/core/browser/history_service.h" #include "components/send_tab_to_self/send_tab_to_self_model.h" #include "components/send_tab_to_self/send_tab_to_self_sync_service.h" #include "components/sync/driver/sync_driver_switches.h" @@ -28,15 +31,26 @@ IN_PROC_BROWSER_TEST_F(TwoClientSendTabToSelfSyncTest, AddedUrlFoundWhenBothClientsAlreadySyncing) { const GURL kUrl("https://www.example.com"); + const base::Time kHistoryEntryTime = base::Time::Now(); const std::string kTitle("example"); + const base::Time kTime = base::Time::FromDoubleT(1); ASSERT_TRUE(SetupSync()) << "SetupSync() failed."; + history::HistoryService* history_service = + HistoryServiceFactory::GetForProfile(GetProfile(0), + ServiceAccessType::EXPLICIT_ACCESS); + history_service->AddPage(kUrl, kHistoryEntryTime, history::SOURCE_BROWSED); + + base::RunLoop run_loop; + history_service->FlushForTest(run_loop.QuitClosure()); + run_loop.Run(); + send_tab_to_self::SendTabToSelfModel* model0 = SendTabToSelfSyncServiceFactory::GetForProfile(GetProfile(0)) ->GetSendTabToSelfModel(); - model0->AddEntry(kUrl, kTitle); + ASSERT_TRUE(model0->AddEntry(kUrl, kTitle, kTime)); send_tab_to_self::SendTabToSelfSyncService* service1 = SendTabToSelfSyncServiceFactory::GetForProfile(GetProfile(1)); @@ -49,12 +63,15 @@ ModelsMatchAfterAddWhenBothClientsAlreadySyncing) { const GURL kGurl0("https://www.example0.com"); const std::string kTitle0("example0"); + const base::Time kTime0 = base::Time::FromDoubleT(1); const GURL kGurl1("https://www.example1.com"); const std::string kTitle1("example1"); + const base::Time kTime1 = base::Time::FromDoubleT(2); const GURL kGurl2("https://www.example2.com"); const std::string kTitle2("example2"); + const base::Time kTime2 = base::Time::FromDoubleT(3); ASSERT_TRUE(SetupSync()) << "SetupSync() failed."; @@ -62,12 +79,13 @@ SendTabToSelfSyncServiceFactory::GetForProfile(GetProfile(0)) ->GetSendTabToSelfModel(); - model0->AddEntry(kGurl0, kTitle0); - model0->AddEntry(kGurl1, kTitle1); + ASSERT_TRUE(model0->AddEntry(kGurl0, kTitle0, kTime0)); - SendTabToSelfSyncServiceFactory::GetForProfile(GetProfile(1)) - ->GetSendTabToSelfModel() - ->AddEntry(kGurl2, kTitle2); + ASSERT_TRUE(model0->AddEntry(kGurl1, kTitle1, kTime1)); + + ASSERT_TRUE(SendTabToSelfSyncServiceFactory::GetForProfile(GetProfile(1)) + ->GetSendTabToSelfModel() + ->AddEntry(kGurl2, kTitle2, kTime2)); EXPECT_TRUE(send_tab_to_self_helper::SendTabToSelfModelEqualityChecker( SendTabToSelfSyncServiceFactory::GetForProfile(GetProfile(1)),
diff --git a/chrome/browser/sync/test/integration/wallet_helper.cc b/chrome/browser/sync/test/integration/wallet_helper.cc index c7c83aab..af23a1f 100644 --- a/chrome/browser/sync/test/integration/wallet_helper.cc +++ b/chrome/browser/sync/test/integration/wallet_helper.cc
@@ -10,7 +10,6 @@ #include "base/run_loop.h" #include "base/strings/utf_string_conversions.h" #include "chrome/browser/autofill/personal_data_manager_factory.h" -#include "chrome/browser/sync/profile_sync_test_util.h" #include "chrome/browser/sync/test/integration/sync_datatype_helper.h" #include "chrome/browser/sync/test/integration/sync_test.h" #include "chrome/browser/web_data_service_factory.h"
diff --git a/chrome/browser/tracing/chrome_tracing_delegate_browsertest.cc b/chrome/browser/tracing/chrome_tracing_delegate_browsertest.cc index 5a9c826..4c56c23 100644 --- a/chrome/browser/tracing/chrome_tracing_delegate_browsertest.cc +++ b/chrome/browser/tracing/chrome_tracing_delegate_browsertest.cc
@@ -148,6 +148,12 @@ local_state->GetInt64(prefs::kBackgroundTracingLastUpload)); EXPECT_FALSE(last_upload_time.is_null()); + content::BackgroundTracingManager::GetInstance()->AbortScenario(); + base::RunLoop wait_for_abort; + content::BackgroundTracingManager::GetInstance()->WhenIdle( + wait_for_abort.QuitClosure()); + wait_for_abort.Run(); + // We should not be able to start a new reactive scenario immediately after // a previous one gets uploaded. EXPECT_FALSE(StartPreemptiveScenario( @@ -182,6 +188,16 @@ local_state->GetInt64(prefs::kBackgroundTracingLastUpload)); EXPECT_FALSE(last_upload_time.is_null()); + content::BackgroundTracingManager::GetInstance()->AbortScenario(); + base::RunLoop wait_for_abort; + content::BackgroundTracingManager::GetInstance()->WhenIdle( + wait_for_abort.QuitClosure()); + wait_for_abort.Run(); + + EXPECT_FALSE(StartPreemptiveScenario( + base::RepeatingClosure(), + content::BackgroundTracingManager::NO_DATA_FILTERING)); + // We move the last upload time to eight days in the past, // and at that point should be able to start a scenario again. base::Time new_upload_time = last_upload_time - base::TimeDelta::FromDays(8);
diff --git a/chrome/browser/ui/BUILD.gn b/chrome/browser/ui/BUILD.gn index 08979fa9..6d39e47 100644 --- a/chrome/browser/ui/BUILD.gn +++ b/chrome/browser/ui/BUILD.gn
@@ -2113,8 +2113,6 @@ "cocoa/touchbar/credit_card_autofill_touch_bar_controller.mm", "cocoa/touchbar/web_textfield_touch_bar_controller.h", "cocoa/touchbar/web_textfield_touch_bar_controller.mm", - "cocoa/ui_localizer.h", - "cocoa/ui_localizer.mm", "cocoa/window_size_autosaver.h", "cocoa/window_size_autosaver.mm", "views/apps/chrome_app_window_client_views_mac.mm", @@ -2139,7 +2137,6 @@ allow_circular_includes_from += [ "//chrome/browser/apps/app_shim" ] deps += [ - "//chrome/app/nibs:localizer_table", "//chrome/browser/apps/app_shim", "//extensions/components/native_app_window", "//third_party/google_toolbox_for_mac", @@ -2821,6 +2818,8 @@ "views/tabs/tab_hover_card_bubble_view.h", "views/tabs/tab_icon.cc", "views/tabs/tab_icon.h", + "views/tabs/tab_renderer_data.cc", + "views/tabs/tab_renderer_data.h", "views/tabs/tab_strip.cc", "views/tabs/tab_strip.h", "views/tabs/tab_strip_controller.h",
diff --git a/chrome/browser/ui/app_list/app_list_client_impl.cc b/chrome/browser/ui/app_list/app_list_client_impl.cc index 2b0987af6..ac04345d 100644 --- a/chrome/browser/ui/app_list/app_list_client_impl.cc +++ b/chrome/browser/ui/app_list/app_list_client_impl.cc
@@ -74,6 +74,9 @@ } AppListClientImpl::~AppListClientImpl() { + app_list_controller_.reset(); + SetProfile(nullptr); + user_manager::UserManager::Get()->RemoveSessionStateObserver(this); DCHECK_EQ(this, g_app_list_client_instance);
diff --git a/chrome/browser/ui/app_list/chrome_app_list_model_updater.cc b/chrome/browser/ui/app_list/chrome_app_list_model_updater.cc index 4ef90ce..2b831591 100644 --- a/chrome/browser/ui/app_list/chrome_app_list_model_updater.cc +++ b/chrome/browser/ui/app_list/chrome_app_list_model_updater.cc
@@ -20,7 +20,7 @@ ChromeAppListModelUpdater::ChromeAppListModelUpdater(Profile* profile) : profile_(profile), weak_ptr_factory_(this) {} -ChromeAppListModelUpdater::~ChromeAppListModelUpdater() {} +ChromeAppListModelUpdater::~ChromeAppListModelUpdater() = default; void ChromeAppListModelUpdater::SetActive(bool active) { const bool was_active = !!app_list_controller_;
diff --git a/chrome/browser/ui/autofill/autofill_ui_util.cc b/chrome/browser/ui/autofill/autofill_ui_util.cc index 8bcc5c35..fcd3e04 100644 --- a/chrome/browser/ui/autofill/autofill_ui_util.cc +++ b/chrome/browser/ui/autofill/autofill_ui_util.cc
@@ -12,7 +12,7 @@ #include "chrome/browser/ui/browser_window.h" #include "chrome/browser/ui/location_bar/location_bar.h" #include "chrome/browser/ui/page_action/page_action_icon_container.h" -#include "components/autofill/core/common/autofill_features.h" +#include "components/autofill/core/common/autofill_payments_features.h" namespace autofill {
diff --git a/chrome/browser/ui/autofill/local_card_migration_bubble_controller_impl.cc b/chrome/browser/ui/autofill/local_card_migration_bubble_controller_impl.cc index 2e14924..b4d5e8e 100644 --- a/chrome/browser/ui/autofill/local_card_migration_bubble_controller_impl.cc +++ b/chrome/browser/ui/autofill/local_card_migration_bubble_controller_impl.cc
@@ -18,6 +18,7 @@ #include "components/autofill/core/browser/payments/local_card_migration_strike_database.h" #include "components/autofill/core/browser/payments/strike_database.h" #include "components/autofill/core/common/autofill_features.h" +#include "components/autofill/core/common/autofill_payments_features.h" #include "components/strings/grit/components_strings.h" #include "content/public/browser/navigation_handle.h" #include "ui/base/l10n/l10n_util.h"
diff --git a/chrome/browser/ui/autofill/local_card_migration_dialog_controller_impl.cc b/chrome/browser/ui/autofill/local_card_migration_dialog_controller_impl.cc index 38549bd..90c5994 100644 --- a/chrome/browser/ui/autofill/local_card_migration_dialog_controller_impl.cc +++ b/chrome/browser/ui/autofill/local_card_migration_dialog_controller_impl.cc
@@ -31,6 +31,7 @@ #include "components/autofill/core/browser/validation.h" #include "components/autofill/core/common/autofill_clock.h" #include "components/autofill/core/common/autofill_features.h" +#include "components/autofill/core/common/autofill_payments_features.h" #include "components/autofill/core/common/autofill_prefs.h" #include "components/prefs/pref_service.h" #include "components/user_prefs/user_prefs.h"
diff --git a/chrome/browser/ui/autofill/save_card_bubble_controller_impl.cc b/chrome/browser/ui/autofill/save_card_bubble_controller_impl.cc index 629fc92fd..947b9c0 100644 --- a/chrome/browser/ui/autofill/save_card_bubble_controller_impl.cc +++ b/chrome/browser/ui/autofill/save_card_bubble_controller_impl.cc
@@ -31,6 +31,7 @@ #include "components/autofill/core/common/autofill_clock.h" #include "components/autofill/core/common/autofill_constants.h" #include "components/autofill/core/common/autofill_features.h" +#include "components/autofill/core/common/autofill_payments_features.h" #include "components/autofill/core/common/autofill_prefs.h" #include "components/prefs/pref_service.h" #include "components/signin/core/browser/signin_buildflags.h"
diff --git a/chrome/browser/ui/autofill/save_card_bubble_controller_impl_browsertest.cc b/chrome/browser/ui/autofill/save_card_bubble_controller_impl_browsertest.cc index 66f3b2c..8c2ea95 100644 --- a/chrome/browser/ui/autofill/save_card_bubble_controller_impl_browsertest.cc +++ b/chrome/browser/ui/autofill/save_card_bubble_controller_impl_browsertest.cc
@@ -20,6 +20,7 @@ #include "chrome/test/base/ui_test_utils.h" #include "components/autofill/core/browser/autofill_test_utils.h" #include "components/autofill/core/common/autofill_features.h" +#include "components/autofill/core/common/autofill_payments_features.h" #include "testing/gtest/include/gtest/gtest.h" #include "ui/base/ui_base_features.h"
diff --git a/chrome/browser/ui/autofill/save_card_bubble_controller_impl_unittest.cc b/chrome/browser/ui/autofill/save_card_bubble_controller_impl_unittest.cc index 43e8889a..bc7b53b 100644 --- a/chrome/browser/ui/autofill/save_card_bubble_controller_impl_unittest.cc +++ b/chrome/browser/ui/autofill/save_card_bubble_controller_impl_unittest.cc
@@ -26,6 +26,7 @@ #include "components/autofill/core/browser/sync_utils.h" #include "components/autofill/core/browser/test_autofill_clock.h" #include "components/autofill/core/common/autofill_features.h" +#include "components/autofill/core/common/autofill_payments_features.h" #include "components/autofill/core/common/autofill_prefs.h" #include "components/user_prefs/user_prefs.h" #include "content/public/test/mock_navigation_handle.h"
diff --git a/chrome/browser/ui/cocoa/task_manager_mac.h b/chrome/browser/ui/cocoa/task_manager_mac.h index e01eb40..cfb7f9d 100644 --- a/chrome/browser/ui/cocoa/task_manager_mac.h +++ b/chrome/browser/ui/cocoa/task_manager_mac.h
@@ -25,12 +25,13 @@ // This class is responsible for loading the task manager window and for // managing it. @interface TaskManagerWindowController - : NSWindowController<NSTableViewDataSource, - NSTableViewDelegate, - NSMenuDelegate> { + : NSWindowController <NSWindowDelegate, + NSTableViewDataSource, + NSTableViewDelegate, + NSMenuDelegate> { @private - IBOutlet NSTableView* tableView_; - IBOutlet NSButton* endProcessButton_; + NSTableView* tableView_; + NSButton* endProcessButton_; task_manager::TaskManagerMac* taskManagerMac_; // weak task_manager::TaskManagerTableModel* tableModel_; // weak
diff --git a/chrome/browser/ui/cocoa/task_manager_mac.mm b/chrome/browser/ui/cocoa/task_manager_mac.mm index 9bee538..78740ae 100644 --- a/chrome/browser/ui/cocoa/task_manager_mac.mm +++ b/chrome/browser/ui/cocoa/task_manager_mac.mm
@@ -24,11 +24,13 @@ #include "chrome/browser/ui/task_manager/task_manager_columns.h" #include "chrome/common/chrome_features.h" #include "chrome/common/pref_names.h" +#include "chrome/grit/chromium_strings.h" #include "chrome/grit/generated_resources.h" #include "components/prefs/pref_service.h" #include "content/public/browser/notification_service.h" #include "content/public/browser/notification_source.h" #include "third_party/skia/include/core/SkBitmap.h" +#include "ui/base/cocoa/controls/button_utils.h" #include "ui/base/l10n/l10n_util_mac.h" #include "ui/gfx/image/image_skia.h" #include "ui/gfx/image/image_skia_util_mac.h" @@ -46,6 +48,7 @@ } // namespace @interface TaskManagerWindowController (Private) +- (base::scoped_nsobject<NSWindow>)createAndLayOutWindow; - (NSTableColumn*)addColumnWithData: (const task_manager::TableColumnData&)columnData; - (void)setUpTableColumns; @@ -62,13 +65,16 @@ - (id)initWithTaskManagerMac:(task_manager::TaskManagerMac*)taskManagerMac tableModel:(task_manager::TaskManagerTableModel*)tableModel { - NSString* nibpath = [base::mac::FrameworkBundle() - pathForResource:@"TaskManager" - ofType:@"nib"]; - if ((self = [super initWithWindowNibPath:nibpath owner:self])) { + base::scoped_nsobject<NSWindow> window = [self createAndLayOutWindow]; + if ((self = [super initWithWindow:window])) { taskManagerMac_ = taskManagerMac; tableModel_ = tableModel; + [window setDelegate:self]; + + [tableView_ setDelegate:self]; + [tableView_ setDataSource:self]; + if (g_browser_process && g_browser_process->local_state()) { size_saver_.reset([[WindowSizeAutosaver alloc] initWithWindow:[self window] @@ -77,6 +83,11 @@ } [[self window] setExcludedFromWindowsMenu:YES]; + [self setUpTableColumns]; + [self setUpTableHeaderContextMenu]; + [self adjustSelectionAndEndProcessButton]; + [tableView_ sizeToFit]; + [self reloadData]; [self showWindow:self]; } @@ -216,16 +227,6 @@ tableModel_->ActivateTask(viewToModelMap_[row]); } -- (void)awakeFromNib { - [self setUpTableColumns]; - [self setUpTableHeaderContextMenu]; - [self adjustSelectionAndEndProcessButton]; - - [tableView_ setDoubleAction:@selector(tableWasDoubleClicked:)]; - [tableView_ setIntercellSpacing:NSMakeSize(0.0, 0.0)]; - [tableView_ sizeToFit]; -} - - (void)dealloc { // Paranoia. These should have been nilled out in -windowWillClose: but let's // make sure we have no dangling references. @@ -234,6 +235,76 @@ [super dealloc]; } +// Creates a NSWindow for the task manager and lays out the views inside the +// content view. +- (base::scoped_nsobject<NSWindow>)createAndLayOutWindow { + static constexpr CGFloat kWindowWidth = 480; + static constexpr CGFloat kMargin = 20; + + base::scoped_nsobject<NSWindow> window([[NSWindow alloc] + initWithContentRect:NSMakeRect(195, 240, kWindowWidth, 270) + styleMask:NSWindowStyleMaskTitled | NSWindowStyleMaskClosable | + NSWindowStyleMaskMiniaturizable | + NSWindowStyleMaskResizable + backing:NSBackingStoreBuffered + defer:YES]); + [window setMinSize:NSMakeSize(300, 200)]; + [window setTitle:l10n_util::GetNSString(IDS_TASK_MANAGER_TITLE)]; + + NSView* contentView = [window contentView]; + + // Create the button that terminates the selected process in the table. + endProcessButton_ = + [ButtonUtils buttonWithTitle:l10n_util::GetNSString(IDS_TASK_MANAGER_KILL) + action:@selector(killSelectedProcesses:) + target:self]; + [endProcessButton_ setAutoresizingMask:NSViewMinXMargin | NSViewMaxYMargin]; + [endProcessButton_ sizeToFit]; + NSRect buttonFrame = [endProcessButton_ frame]; + buttonFrame.size.width += kMargin; + // Adjust the button's origin so that it is flush with the right-hand side of + // the table. + buttonFrame.origin.x = + NSWidth([contentView frame]) - NSWidth(buttonFrame) - kMargin + 6; + // Use only half the margin, since the full margin is too much whitespace. + buttonFrame.origin.y = kMargin / 2; + [endProcessButton_ setFrame:buttonFrame]; + [contentView addSubview:endProcessButton_]; + + // Create a scroll view to house the table view. + CGFloat scrollViewY = NSMaxY(buttonFrame) + kMargin / 2; + NSRect scrollViewFrame = + NSMakeRect(kMargin, scrollViewY, kWindowWidth - 2 * kMargin, + NSHeight([window frame]) - 2 * kMargin - scrollViewY); + base::scoped_nsobject<NSScrollView> scrollView( + [[NSScrollView alloc] initWithFrame:scrollViewFrame]); + [scrollView setAutoresizesSubviews:YES]; + [scrollView setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable]; + [scrollView setBorderType:NSBezelBorder]; + [scrollView setFocusRingType:NSFocusRingTypeNone]; + [scrollView setHasVerticalScroller:YES]; + [[scrollView verticalScroller] setControlSize:NSControlSizeSmall]; + [contentView addSubview:scrollView]; + + // Create the table view. The data source and delegate are connected in + // the designated initializer. + base::scoped_nsobject<NSTableView> tableView( + [[NSTableView alloc] initWithFrame:NSMakeRect(0, 0, 400, 200)]); + [tableView setAllowsColumnReordering:NO]; + [tableView setAutosaveTableColumns:NO]; + [tableView + setColumnAutoresizingStyle:NSTableViewUniformColumnAutoresizingStyle]; + [tableView setDoubleAction:@selector(tableWasDoubleClicked:)]; + [tableView setFocusRingType:NSFocusRingTypeNone]; + [tableView setIntercellSpacing:NSMakeSize(0, 0)]; + [tableView setUsesAlternatingRowBackgroundColors:YES]; + tableView_ = tableView.get(); + + [scrollView setDocumentView:tableView]; + + return window; +} + // Adds a column which has the given string id as title. |isVisible| specifies // if the column is initially visible. - (NSTableColumn*)addColumnWithData:
diff --git a/chrome/browser/ui/cocoa/ui_localizer.h b/chrome/browser/ui/cocoa/ui_localizer.h deleted file mode 100644 index 65bf67c1..0000000 --- a/chrome/browser/ui/cocoa/ui_localizer.h +++ /dev/null
@@ -1,34 +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 CHROME_BROWSER_UI_COCOA_UI_LOCALIZER_H_ -#define CHROME_BROWSER_UI_COCOA_UI_LOCALIZER_H_ - -#import "third_party/google_toolbox_for_mac/src/AppKit/GTMUILocalizer.h" - -@class NSString; - -// A base class for generated localizers. -// -// To use this, include your xib file in the list generate_localizer scans (see -// chrome_browser.gypi). Then add an instance of ChromeUILocalizer to the xib. -// Connect the owner_ outlet of the instance to the "File's Owner" of the xib. -// It expects the owner_ outlet to be an instance or subclass of -// NSWindowController or NSViewController. It will then localize any items in -// the NSWindowController's window and subviews, or the NSViewController's view -// and subviews, when awakeFromNib is called on the instance. You can -// optionally hook up otherObjectToLocalize_ and yetAnotherObjectToLocalize_ and -// those will also be localized. Strings in the xib that you want localized must -// start with ^IDS. The value must be a valid resource constant. -// Things that will be localized are: -// - Titles and altTitles (for menus, buttons, windows, menuitems, -tabViewItem) -// - -stringValue (for labels) -// - tooltips -// - accessibility help -// - accessibility descriptions -// - menus -@interface ChromeUILocalizer : GTMUILocalizer -@end - -#endif // CHROME_BROWSER_UI_COCOA_UI_LOCALIZER_H_
diff --git a/chrome/browser/ui/cocoa/ui_localizer.mm b/chrome/browser/ui/cocoa/ui_localizer.mm deleted file mode 100644 index 83bd4209..0000000 --- a/chrome/browser/ui/cocoa/ui_localizer.mm +++ /dev/null
@@ -1,101 +0,0 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#import "chrome/browser/ui/cocoa/ui_localizer.h" - -#import <Foundation/Foundation.h> - -#include <stdlib.h> - -#include "base/logging.h" -#include "base/stl_util.h" -#include "base/strings/sys_string_conversions.h" -#include "chrome/grit/chromium_strings.h" -#include "chrome/grit/generated_resources.h" -#include "components/strings/grit/components_strings.h" -#include "ui/base/l10n/l10n_util.h" -#include "ui/base/l10n/l10n_util_mac.h" -#include "ui/strings/grit/ui_strings.h" - -struct UILocalizerResourceMap { - const char* const name; - unsigned int label_id; - unsigned int label_arg_id; -}; - - -namespace { - -// Utility function for bsearch on a ResourceMap table -int ResourceMapCompare(const void* utf8Void, - const void* resourceMapVoid) { - const char* utf8_key = reinterpret_cast<const char*>(utf8Void); - const UILocalizerResourceMap* res_map = - reinterpret_cast<const UILocalizerResourceMap*> (resourceMapVoid); - return strcmp(utf8_key, res_map->name); -} - -} // namespace - -@interface GTMUILocalizer (PrivateAdditions) -- (void)localizedObjects; -@end - -@implementation GTMUILocalizer (PrivateAdditions) -- (void)localizedObjects { - // The ivars are private, so this method lets us trigger the localization - // from -[ChromeUILocalizer awakeFromNib]. - [self localizeObject:owner_ recursively:YES]; - [self localizeObject:otherObjectToLocalize_ recursively:YES]; - [self localizeObject:yetAnotherObjectToLocalize_ recursively:YES]; -} - @end - -@implementation ChromeUILocalizer - -- (void)awakeFromNib { - // The GTM base is bundle based, since don't need the bundle, use this - // override to bypass the bundle lookup and directly do the localization - // calls. - [self localizedObjects]; -} - -- (NSString *)localizedStringForString:(NSString *)string { - - // Include the table here so it is a local static. This header provides - // kUIResources and kUIResourcesSize. -#include "chrome/app/nibs/localizer_table.h" - - // Look up the string for the resource id to fetch. - const char* utf8_key = [string UTF8String]; - if (utf8_key) { - const void* valVoid = bsearch(utf8_key, - kUIResources, - kUIResourcesSize, - sizeof(UILocalizerResourceMap), - ResourceMapCompare); - const UILocalizerResourceMap* val = - reinterpret_cast<const UILocalizerResourceMap*>(valVoid); - if (val) { - // Do we need to build the string, or just fetch it? - if (val->label_arg_id != 0) { - const base::string16 label_arg( - l10n_util::GetStringUTF16(val->label_arg_id)); - return l10n_util::GetNSStringFWithFixup(val->label_id, label_arg); - } - - return l10n_util::GetNSStringWithFixup(val->label_id); - } - - // Sanity check, there shouldn't be any strings with this id that aren't - // in our map. - DLOG_IF(WARNING, [string hasPrefix:@"^ID"]) << "Key '" << utf8_key - << "' wasn't in the resource map?"; - } - - // If we didn't find anything, this string doesn't need localizing. - return nil; -} - -@end
diff --git a/chrome/browser/ui/extensions/extension_message_bubble_factory.cc b/chrome/browser/ui/extensions/extension_message_bubble_factory.cc index d64dea3..f41665a8 100644 --- a/chrome/browser/ui/extensions/extension_message_bubble_factory.cc +++ b/chrome/browser/ui/extensions/extension_message_bubble_factory.cc
@@ -6,7 +6,6 @@ #include "base/base_switches.h" #include "base/command_line.h" -#include "base/metrics/field_trial.h" #include "base/no_destructor.h" #include "base/stl_util.h" #include "build/build_config.h" @@ -32,13 +31,6 @@ ExtensionMessageBubbleFactory::OverrideForTesting g_override_for_testing = ExtensionMessageBubbleFactory::NO_OVERRIDE; -const char kEnableDevModeWarningExperimentName[] = - "ExtensionDeveloperModeWarning"; - -#if !defined(OS_WIN) && !defined(OS_MACOSX) -const char kEnableProxyWarningExperimentName[] = "ExtensionProxyWarning"; -#endif - // A set of all profiles evaluated, so we can tell if it's the initial check. // TODO(devlin): It would be nice to coalesce all the "profiles evaluated" maps // that are in the different bubble controllers. @@ -47,18 +39,6 @@ return *s; } -bool IsExperimentEnabled(const char* experiment_name) { - // Don't allow turning it off via command line. - base::CommandLine* command_line = base::CommandLine::ForCurrentProcess(); - if (command_line->HasSwitch(switches::kForceFieldTrials)) { - std::string forced_trials = - command_line->GetSwitchValueASCII(switches::kForceFieldTrials); - if (forced_trials.find(experiment_name)) - return true; - } - return base::FieldTrialList::FindFullName(experiment_name) == "Enabled"; -} - bool EnableSuspiciousExtensionsBubble() { return g_override_for_testing == ExtensionMessageBubbleFactory::OVERRIDE_ENABLED || @@ -79,8 +59,7 @@ return true; #else return g_override_for_testing == - ExtensionMessageBubbleFactory::OVERRIDE_ENABLED || - IsExperimentEnabled(kEnableProxyWarningExperimentName); + ExtensionMessageBubbleFactory::OVERRIDE_ENABLED; #endif } @@ -102,8 +81,7 @@ #endif return g_override_for_testing == - ExtensionMessageBubbleFactory::OVERRIDE_ENABLED || - IsExperimentEnabled(kEnableDevModeWarningExperimentName); + ExtensionMessageBubbleFactory::OVERRIDE_ENABLED; } } // namespace
diff --git a/chrome/browser/ui/tabs/tab_strip_model.cc b/chrome/browser/ui/tabs/tab_strip_model.cc index e0259dc..c0660ca2 100644 --- a/chrome/browser/ui/tabs/tab_strip_model.cc +++ b/chrome/browser/ui/tabs/tab_strip_model.cc
@@ -958,14 +958,27 @@ void TabStripModel::AddToNewGroup(const std::vector<int>& indices) { group_data_.push_back(std::make_unique<TabGroupData>()); - TabGroupData* group = group_data_.back().get(); + TabGroupData* new_group = group_data_.back().get(); - std::vector<int> new_indices = RemoveFromGroup(indices); - if (IsTabPinned(new_indices[0])) { - new_indices = SetTabsPinned(new_indices, true); + // Find a destination for the first tab that's not inside another group. We + // will stack the rest of the tabs up to its right. + int destination_index = -1; + for (int i = indices[0]; i < count(); i++) { + const int destination_candidate = i + 1; + const bool end_of_strip = !ContainsIndex(destination_candidate); + if (end_of_strip || GetTabGroupForTab(destination_candidate) == nullptr || + GetTabGroupForTab(destination_candidate) != + GetTabGroupForTab(indices[0])) { + destination_index = destination_candidate; + break; + } } - MoveTabsIntoGroup(new_indices, new_indices[0], group); + std::vector<int> new_indices = indices; + if (IsTabPinned(new_indices[0])) + new_indices = SetTabsPinned(new_indices, true); + + MoveTabsIntoGroup(new_indices, destination_index, new_group); } void TabStripModel::AddToExistingGroup(const std::vector<int>& indices, @@ -987,109 +1000,29 @@ new_indices.push_back(indices[i]); } } - new_indices = RemoveFromGroup(new_indices); new_indices = SetTabsPinned(new_indices, pin); MoveTabsIntoGroup(new_indices, destination_index, group); } -void TabStripModel::MoveTabsIntoGroup(const std::vector<int>& indices, - int destination_index, - const TabGroupData* group) { - // Some tabs will need to be moved to the right, some to the left. We need to - // handle those separately. First, move tabs to the right, starting with the - // rightmost tab so we don't cause other tabs we are about to move to shift. - int numTabsMovingRight = 0; - for (size_t i = 0; i < indices.size() && indices[i] < destination_index; - i++) { - numTabsMovingRight++; - } - for (int i = numTabsMovingRight - 1; i >= 0; i--) { - int insertion_index = destination_index - numTabsMovingRight + i; - MoveWebContentsAt(indices[i], insertion_index, false); - contents_data_[insertion_index]->set_group(group); - } - - // Collect indices for tabs moving to the left. - std::vector<int> move_left_indices; - for (size_t i = numTabsMovingRight; i < indices.size(); i++) { - move_left_indices.push_back(indices[i]); - } - // Move tabs to the left, starting with the leftmost tab. - for (size_t i = 0; i < move_left_indices.size(); i++) { - MoveWebContentsAt(move_left_indices[i], destination_index + i, false); - contents_data_[destination_index + i]->set_group(group); - } -} - -std::vector<int> TabStripModel::SetTabsPinned(const std::vector<int>& indices, - bool pinned) { - std::vector<int> new_indices; - if (pinned) { - for (size_t i = 0; i < indices.size(); i++) { - if (IsTabPinned(indices[i])) { - new_indices.push_back(indices[i]); - } else { - SetTabPinned(indices[i], true); - new_indices.push_back(IndexOfFirstNonPinnedTab() - 1); - } - } - } else { - for (size_t i = indices.size() - 1; i < indices.size(); i--) { - if (!IsTabPinned(indices[i])) { - new_indices.push_back(indices[i]); - } else { - SetTabPinned(indices[i], false); - new_indices.push_back(IndexOfFirstNonPinnedTab()); - } - } - std::reverse(new_indices.begin(), new_indices.end()); - } - return new_indices; -} - -std::vector<int> TabStripModel::RemoveFromGroup( - const std::vector<int>& indices) { +void TabStripModel::RemoveFromGroup(const std::vector<int>& indices) { // Remove each tab from the group it's in, if any. Go from right to left - // since tabs may move to the right when ungrouped. - std::deque<int> new_indices; + // since tabs may move to the right. for (int i = indices.size() - 1; i >= 0; i--) { - new_indices.push_front(UngroupTab(indices[i])); - } + const int index = indices[i]; + const TabGroupData* old_group = GetTabGroupForTab(index); + if (old_group == nullptr) + continue; + UngroupTab(index); - return std::vector<int>(new_indices.begin(), new_indices.end()); -} - -int TabStripModel::UngroupTab(int index) { - const TabGroupData* group = GetTabGroupForTab(index); - if (group == nullptr) - return index; - - // Move the tab until it's the rightmost tab in its group - int new_index = index; - while (ContainsIndex(new_index + 1) && - GetTabGroupForTab(new_index + 1) == group) { - new_index++; - } - MoveWebContentsAt(index, new_index, false); - - contents_data_[new_index]->set_group(nullptr); - - // Delete the group if we just ungrouped the last tab in that group. - if (GetTabGroupForTab(index) != group && - (index == 0 || GetTabGroupForTab(index - 1) != group)) { - for (size_t i = 0; i < contents_data_.size(); i++) { - DCHECK_NE(GetTabGroupForTab(i), group); + // Move the tab until it's the rightmost tab in its group + int new_index = index; + while (ContainsIndex(new_index + 1) && + GetTabGroupForTab(new_index + 1) == old_group) { + new_index++; } - for (auto it = group_data_.begin(); it != group_data_.end(); it++) { - if (it->get() == group) { - group_data_.erase(it); - break; - } - } + MoveWebContentsAt(index, new_index, false); } - - return new_index; } // Context menu functions. @@ -1709,6 +1642,82 @@ } } +void TabStripModel::MoveTabsIntoGroup(const std::vector<int>& indices, + int destination_index, + const TabGroupData* group) { + auto move_tab = [&](int current_index, int insertion_index) { + UngroupTab(current_index); + MoveWebContentsAt(current_index, insertion_index, false); + contents_data_[insertion_index]->set_group(group); + }; + + // Some tabs will need to be moved to the right, some to the left. We need to + // handle those separately. First, move tabs to the right, starting with the + // rightmost tab so we don't cause other tabs we are about to move to shift. + int numTabsMovingRight = 0; + for (size_t i = 0; i < indices.size() && indices[i] < destination_index; + i++) { + numTabsMovingRight++; + } + for (int i = numTabsMovingRight - 1; i >= 0; i--) + move_tab(indices[i], destination_index - numTabsMovingRight + i); + + // Collect indices for tabs moving to the left. + std::vector<int> move_left_indices; + for (size_t i = numTabsMovingRight; i < indices.size(); i++) { + move_left_indices.push_back(indices[i]); + } + // Move tabs to the left, starting with the leftmost tab. + for (size_t i = 0; i < move_left_indices.size(); i++) + move_tab(move_left_indices[i], destination_index + i); +} + +void TabStripModel::UngroupTab(int index) { + const TabGroupData* group = GetTabGroupForTab(index); + if (group == nullptr) + return; + + contents_data_[index]->set_group(nullptr); + // Delete the group if we just ungrouped the last tab in that group. + if ((!ContainsIndex(index + 1) || GetTabGroupForTab(index + 1) != group) && + (!ContainsIndex(index - 1) || GetTabGroupForTab(index - 1) != group)) { + for (size_t i = 0; i < contents_data_.size(); i++) + DCHECK_NE(GetTabGroupForTab(i), group); + for (auto it = group_data_.begin(); it != group_data_.end(); it++) { + if (it->get() == group) { + group_data_.erase(it); + break; + } + } + } +} + +std::vector<int> TabStripModel::SetTabsPinned(const std::vector<int>& indices, + bool pinned) { + std::vector<int> new_indices; + if (pinned) { + for (size_t i = 0; i < indices.size(); i++) { + if (IsTabPinned(indices[i])) { + new_indices.push_back(indices[i]); + } else { + SetTabPinned(indices[i], true); + new_indices.push_back(IndexOfFirstNonPinnedTab() - 1); + } + } + } else { + for (size_t i = indices.size() - 1; i < indices.size(); i--) { + if (!IsTabPinned(indices[i])) { + new_indices.push_back(indices[i]); + } else { + SetTabPinned(indices[i], false); + new_indices.push_back(IndexOfFirstNonPinnedTab()); + } + } + std::reverse(new_indices.begin(), new_indices.end()); + } + return new_indices; +} + // Sets the sound content setting for each site at the |indices|. void TabStripModel::SetSitesMuted(const std::vector<int>& indices, bool mute) const {
diff --git a/chrome/browser/ui/tabs/tab_strip_model.h b/chrome/browser/ui/tabs/tab_strip_model.h index e1265c05..140b2ab1 100644 --- a/chrome/browser/ui/tabs/tab_strip_model.h +++ b/chrome/browser/ui/tabs/tab_strip_model.h
@@ -380,11 +380,10 @@ const TabGroupData* group); // Removes the set of tabs pointed to by |indices| from the the groups they - // are in, if any. The tabs are moved out of the group if necessary. Returns - // the new locations of the tabs formerly located at |indices|. |indices| must - // be sorted in ascending order. This feature is in development and gated + // are in, if any. The tabs are moved out of the group if necessary. |indices| + // must be sorted in ascending order. This feature is in development and gated // behind a feature flag. https://crbug.com/915956. - std::vector<int> RemoveFromGroup(const std::vector<int>& indices); + void RemoveFromGroup(const std::vector<int>& indices); // View API ////////////////////////////////////////////////////////////////// @@ -576,10 +575,9 @@ int destination_index, const TabGroupData* group); - // Removes the tab at |index| from the group that contains it, if any. Moves - // the tab to the end of the group if necessary to keep the group it was in - // contiguous. Returns the new index of the ungrouped tab. - int UngroupTab(int index); + // Removes the tab at |index| from the group that contains it, if any. Also + // deletes that group, if it now contains no tabs. + void UngroupTab(int index); // Ensures all tabs indicated by |indices| are pinned, moving them in the // process if necessary. Returns the new locations of all of those tabs.
diff --git a/chrome/browser/ui/tabs/tab_strip_model_unittest.cc b/chrome/browser/ui/tabs/tab_strip_model_unittest.cc index 2e01052..a6453d6 100644 --- a/chrome/browser/ui/tabs/tab_strip_model_unittest.cc +++ b/chrome/browser/ui/tabs/tab_strip_model_unittest.cc
@@ -2633,13 +2633,10 @@ TEST_F(TabStripModelTest, AddTabToNewGroupMiddleOfExistingGroup) { TabStripDummyDelegate delegate; TabStripModel strip(&delegate, profile()); - strip.AppendWebContents(CreateWebContents(), false); - strip.AppendWebContents(CreateWebContents(), false); - strip.AppendWebContents(CreateWebContents(), false); - strip.AppendWebContents(CreateWebContents(), false); - std::vector<WebContents*> orig{ - strip.GetWebContentsAt(0), strip.GetWebContentsAt(1), - strip.GetWebContentsAt(2), strip.GetWebContentsAt(3)}; + strip.AppendWebContents(CreateWebContentsWithID(0), false); + strip.AppendWebContents(CreateWebContentsWithID(1), false); + strip.AppendWebContents(CreateWebContentsWithID(2), false); + strip.AppendWebContents(CreateWebContentsWithID(3), false); strip.AddToNewGroup({0, 1, 2, 3}); const TabGroupData* first_group = strip.GetTabGroupForTab(0); @@ -2649,10 +2646,25 @@ EXPECT_EQ(strip.GetTabGroupForTab(1), first_group); EXPECT_NE(strip.GetTabGroupForTab(2), first_group); EXPECT_EQ(strip.GetTabGroupForTab(2), strip.GetTabGroupForTab(3)); - EXPECT_EQ(strip.GetWebContentsAt(0), orig[0]); - EXPECT_EQ(strip.GetWebContentsAt(1), orig[3]); - EXPECT_EQ(strip.GetWebContentsAt(2), orig[1]); - EXPECT_EQ(strip.GetWebContentsAt(3), orig[2]); + EXPECT_EQ("0 3 1 2", GetTabStripStateString(strip)); + + strip.ActivateTabAt(0, {TabStripModel::GestureType::kOther}); + strip.CloseAllTabs(); +} + +TEST_F(TabStripModelTest, AddTabToNewGroupMiddleOfExistingGroupTwoGroups) { + TabStripDummyDelegate delegate; + TabStripModel strip(&delegate, profile()); + strip.AppendWebContents(CreateWebContentsWithID(0), false); + strip.AppendWebContents(CreateWebContentsWithID(1), false); + strip.AppendWebContents(CreateWebContentsWithID(2), false); + strip.AppendWebContents(CreateWebContentsWithID(3), false); + strip.AddToNewGroup({0, 1, 2}); + strip.AddToNewGroup({3}); + + strip.AddToNewGroup({1}); + EXPECT_NE(strip.GetTabGroupForTab(2), strip.GetTabGroupForTab(0)); + EXPECT_EQ("0 2 1 3", GetTabStripStateString(strip)); strip.ActivateTabAt(0, {TabStripModel::GestureType::kOther}); strip.CloseAllTabs(); @@ -2974,6 +2986,20 @@ strip.CloseAllTabs(); } +TEST_F(TabStripModelTest, RemoveTabFromGroupDoesntReorderIfNoGroup) { + TabStripDummyDelegate delegate; + TabStripModel strip(&delegate, profile()); + strip.AppendWebContents(CreateWebContentsWithID(0), true); + strip.AppendWebContents(CreateWebContentsWithID(1), false); + strip.AppendWebContents(CreateWebContentsWithID(2), false); + strip.AddToNewGroup({0}); + + strip.RemoveFromGroup({0, 1}); + EXPECT_EQ("0 1 2", GetTabStripStateString(strip)); + + strip.CloseAllTabs(); +} + TEST_F(TabStripModelTest, RemoveTabFromGroupMaintainsOrderOfSelectedTabs) { TabStripDummyDelegate delegate; TabStripModel strip(&delegate, profile());
diff --git a/chrome/browser/ui/views/BUILD.gn b/chrome/browser/ui/views/BUILD.gn index 07f24ef8..9e4f35b 100644 --- a/chrome/browser/ui/views/BUILD.gn +++ b/chrome/browser/ui/views/BUILD.gn
@@ -16,8 +16,6 @@ "event_utils.cc", "event_utils.h", "tab_icon_view_model.h", - "tabs/tab_renderer_data.cc", - "tabs/tab_renderer_data.h", "tabs/tab_strip_observer.cc", "tabs/tab_strip_observer.h", "tabs/tab_strip_types.h",
diff --git a/chrome/browser/ui/views/apps/app_info_dialog/app_info_dialog_views.cc b/chrome/browser/ui/views/apps/app_info_dialog/app_info_dialog_views.cc index f2dc480..a991009 100644 --- a/chrome/browser/ui/views/apps/app_info_dialog/app_info_dialog_views.cc +++ b/chrome/browser/ui/views/apps/app_info_dialog/app_info_dialog_views.cc
@@ -117,12 +117,13 @@ 0, 0, kHorizontalSeparatorHeight, 0, kDialogSeparatorColor)); dialog_footer_ = new AppInfoFooterPanel(profile, app); - dialog_footer_->SetBorder(views::CreateSolidSidedBorder( - kHorizontalSeparatorHeight, 0, 0, 0, kDialogSeparatorColor)); - if (!dialog_footer_->has_children()) { + if (dialog_footer_->children().empty()) { // If there are no controls in the footer, don't add it to the dialog. delete dialog_footer_; dialog_footer_ = NULL; + } else { + dialog_footer_->SetBorder(views::CreateSolidSidedBorder( + kHorizontalSeparatorHeight, 0, 0, 0, kDialogSeparatorColor)); } // Make a vertically stacked view of all the panels we want to display in the
diff --git a/chrome/browser/ui/views/apps/app_info_dialog/app_info_permissions_panel.cc b/chrome/browser/ui/views/apps/app_info_dialog/app_info_permissions_panel.cc index db7aca5f..e024590 100644 --- a/chrome/browser/ui/views/apps/app_info_dialog/app_info_permissions_panel.cc +++ b/chrome/browser/ui/views/apps/app_info_dialog/app_info_permissions_panel.cc
@@ -160,7 +160,7 @@ views::Label* permission_label, RevokeButton* revoke_button) { // Add a padding row before every item except the first. - if (has_children()) { + if (!children().empty()) { layout_->AddPaddingRow(views::GridLayout::kFixedSize, ChromeLayoutProvider::Get()->GetDistanceMetric( views::DISTANCE_RELATED_CONTROL_VERTICAL));
diff --git a/chrome/browser/ui/views/autofill/card_unmask_prompt_views.cc b/chrome/browser/ui/views/autofill/card_unmask_prompt_views.cc index 061244b..d41aebf 100644 --- a/chrome/browser/ui/views/autofill/card_unmask_prompt_views.cc +++ b/chrome/browser/ui/views/autofill/card_unmask_prompt_views.cc
@@ -344,7 +344,7 @@ } void CardUnmaskPromptViews::InitIfNecessary() { - if (has_children()) + if (!children().empty()) return; ChromeLayoutProvider* provider = ChromeLayoutProvider::Get(); ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();
diff --git a/chrome/browser/ui/views/autofill/local_card_migration_browsertest.cc b/chrome/browser/ui/views/autofill/local_card_migration_browsertest.cc index fbcff33..bfe8907 100644 --- a/chrome/browser/ui/views/autofill/local_card_migration_browsertest.cc +++ b/chrome/browser/ui/views/autofill/local_card_migration_browsertest.cc
@@ -44,6 +44,7 @@ #include "components/autofill/core/browser/personal_data_manager.h" #include "components/autofill/core/browser/test_event_waiter.h" #include "components/autofill/core/common/autofill_features.h" +#include "components/autofill/core/common/autofill_payments_features.h" #include "components/autofill/core/common/autofill_prefs.h" #include "components/keyed_service/content/browser_context_dependency_manager.h" #include "components/network_session_configurator/common/network_switches.h"
diff --git a/chrome/browser/ui/views/autofill/local_card_migration_dialog_view.cc b/chrome/browser/ui/views/autofill/local_card_migration_dialog_view.cc index 077277e..b8099b99 100644 --- a/chrome/browser/ui/views/autofill/local_card_migration_dialog_view.cc +++ b/chrome/browser/ui/views/autofill/local_card_migration_dialog_view.cc
@@ -468,7 +468,7 @@ void LocalCardMigrationDialogView::ConstructView() { DCHECK(controller_->GetViewState() != LocalCardMigrationDialogState::kOffered || - !has_children()); + children().empty()); RemoveAllChildViews(/*delete_children=*/true);
diff --git a/chrome/browser/ui/views/autofill/local_card_migration_error_dialog_view.cc b/chrome/browser/ui/views/autofill/local_card_migration_error_dialog_view.cc index 350082b..73036c2e 100644 --- a/chrome/browser/ui/views/autofill/local_card_migration_error_dialog_view.cc +++ b/chrome/browser/ui/views/autofill/local_card_migration_error_dialog_view.cc
@@ -93,7 +93,7 @@ } void LocalCardMigrationErrorDialogView::Init() { - if (has_children()) + if (!children().empty()) return; ChromeLayoutProvider* provider = ChromeLayoutProvider::Get();
diff --git a/chrome/browser/ui/views/autofill/save_card_bubble_views_browsertest.cc b/chrome/browser/ui/views/autofill/save_card_bubble_views_browsertest.cc index 676065a..705b80a1 100644 --- a/chrome/browser/ui/views/autofill/save_card_bubble_views_browsertest.cc +++ b/chrome/browser/ui/views/autofill/save_card_bubble_views_browsertest.cc
@@ -41,6 +41,7 @@ #include "components/autofill/core/browser/test_event_waiter.h" #include "components/autofill/core/common/autofill_constants.h" #include "components/autofill/core/common/autofill_features.h" +#include "components/autofill/core/common/autofill_payments_features.h" #include "components/browser_sync/profile_sync_service.h" #include "components/keyed_service/content/browser_context_dependency_manager.h" #include "components/network_session_configurator/common/network_switches.h"
diff --git a/chrome/browser/ui/views/autofill/save_card_offer_bubble_views.cc b/chrome/browser/ui/views/autofill/save_card_offer_bubble_views.cc index f166fd6..b34e42cf 100644 --- a/chrome/browser/ui/views/autofill/save_card_offer_bubble_views.cc +++ b/chrome/browser/ui/views/autofill/save_card_offer_bubble_views.cc
@@ -23,6 +23,7 @@ #include "components/autofill/core/browser/validation.h" #include "components/autofill/core/common/autofill_clock.h" #include "components/autofill/core/common/autofill_features.h" +#include "components/autofill/core/common/autofill_payments_features.h" #include "components/strings/grit/components_strings.h" #include "ui/base/l10n/l10n_util.h" #include "ui/base/resource/resource_bundle.h"
diff --git a/chrome/browser/ui/views/bookmarks/bookmark_bar_view_unittest.cc b/chrome/browser/ui/views/bookmarks/bookmark_bar_view_unittest.cc index b5a6b47..676ebfb 100644 --- a/chrome/browser/ui/views/bookmarks/bookmark_bar_view_unittest.cc +++ b/chrome/browser/ui/views/bookmarks/bookmark_bar_view_unittest.cc
@@ -210,12 +210,12 @@ EXPECT_EQ(6, test_helper_->GetBookmarkButtonCount()); // Ensure buttons were added in the correct place. - int managed_button_index = - bookmark_bar_view_->GetIndexOf(test_helper_->managed_bookmarks_button()); + auto button_iter = + bookmark_bar_view_->FindChild(test_helper_->managed_bookmarks_button()); for (int i = 0; i < test_helper_->GetBookmarkButtonCount(); ++i) { - views::View* button = test_helper_->GetBookmarkButton(i); - EXPECT_EQ(bookmark_bar_view_->GetIndexOf(button), - managed_button_index + 1 + i); + ++button_iter; + ASSERT_NE(bookmark_bar_view_->children().cend(), button_iter); + EXPECT_EQ(test_helper_->GetBookmarkButton(i), *button_iter); } } @@ -234,12 +234,12 @@ bookmark_bar_view_->Layout(); EXPECT_EQ(6, test_helper_->GetBookmarkButtonCount()); // Ensure buttons were added in the correct place. - int managed_button_index = - bookmark_bar_view_->GetIndexOf(test_helper_->managed_bookmarks_button()); + auto button_iter = + bookmark_bar_view_->FindChild(test_helper_->managed_bookmarks_button()); for (int i = 0; i < test_helper_->GetBookmarkButtonCount(); ++i) { - views::View* button = test_helper_->GetBookmarkButton(i); - EXPECT_EQ(bookmark_bar_view_->GetIndexOf(button), - managed_button_index + 1 + i); + ++button_iter; + ASSERT_NE(bookmark_bar_view_->children().cend(), button_iter); + EXPECT_EQ(test_helper_->GetBookmarkButton(i), *button_iter); } }
diff --git a/chrome/browser/ui/views/desktop_capture/desktop_media_list_view.cc b/chrome/browser/ui/views/desktop_capture/desktop_media_list_view.cc index 62770522..ecccafb 100644 --- a/chrome/browser/ui/views/desktop_capture/desktop_media_list_view.cc +++ b/chrome/browser/ui/views/desktop_capture/desktop_media_list_view.cc
@@ -152,7 +152,7 @@ new_index = std::max(new_index, 0); if (index != new_index) new_selected = child_at(new_index); - } else if (has_children()) { + } else if (!children().empty()) { new_selected = child_at(0); }
diff --git a/chrome/browser/ui/views/frame/browser_view.cc b/chrome/browser/ui/views/frame/browser_view.cc index cd6cfb1..f1e5448 100644 --- a/chrome/browser/ui/views/frame/browser_view.cc +++ b/chrome/browser/ui/views/frame/browser_view.cc
@@ -120,7 +120,7 @@ #include "components/app_modal/app_modal_dialog_queue.h" #include "components/app_modal/javascript_app_modal_dialog.h" #include "components/app_modal/native_app_modal_dialog.h" -#include "components/autofill/core/common/autofill_features.h" +#include "components/autofill/core/common/autofill_payments_features.h" #include "components/omnibox/browser/omnibox_popup_model.h" #include "components/omnibox/browser/omnibox_popup_view.h" #include "components/omnibox/browser/omnibox_view.h"
diff --git a/chrome/browser/ui/views/frame/browser_view_unittest.cc b/chrome/browser/ui/views/frame/browser_view_unittest.cc index 063fb572..3639907 100644 --- a/chrome/browser/ui/views/frame/browser_view_unittest.cc +++ b/chrome/browser/ui/views/frame/browser_view_unittest.cc
@@ -98,10 +98,10 @@ // Find bar host is at the front of the view hierarchy, followed by the // infobar container and then top container. - EXPECT_EQ(browser_view()->child_count() - 1, - browser_view()->GetIndexOf(browser_view()->find_bar_host_view())); - EXPECT_EQ(browser_view()->child_count() - 2, - browser_view()->GetIndexOf(browser_view()->infobar_container())); + ASSERT_GE(browser_view()->children().size(), 2U); + auto child = browser_view()->children().crbegin(); + EXPECT_EQ(browser_view()->find_bar_host_view(), *child++); + EXPECT_EQ(browser_view()->infobar_container(), *child); // Verify basic layout. EXPECT_EQ(0, top_container->x()); @@ -143,10 +143,10 @@ // Find bar host is still at the front of the view hierarchy, followed by the // infobar container and then top container. - EXPECT_EQ(browser_view()->child_count() - 1, - browser_view()->GetIndexOf(browser_view()->find_bar_host_view())); - EXPECT_EQ(browser_view()->child_count() - 2, - browser_view()->GetIndexOf(browser_view()->infobar_container())); + ASSERT_GE(browser_view()->children().size(), 2U); + child = browser_view()->children().crbegin(); + EXPECT_EQ(browser_view()->find_bar_host_view(), *child++); + EXPECT_EQ(browser_view()->infobar_container(), *child); // Bookmark bar layout on NTP. EXPECT_EQ(0, bookmark_bar->x());
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 3a05a4e0..af0ce2e5 100644 --- a/chrome/browser/ui/views/frame/glass_browser_frame_view.cc +++ b/chrome/browser/ui/views/frame/glass_browser_frame_view.cc
@@ -217,15 +217,6 @@ gfx::Size min_size(browser_view()->GetMinimumSize()); min_size.Enlarge(0, GetTopInset(false)); - // Ensure that the minimum width is enough to hold a min-width tab strip. - if (browser_view()->IsTabStripVisible()) { - const TabStrip* tabstrip = browser_view()->tabstrip(); - int min_tabstrip_width = tabstrip->GetMinimumSize().width(); - int min_tabstrip_area_width = - width() - GetBoundsForTabStrip(tabstrip).width() + min_tabstrip_width; - min_size.set_width(std::max(min_tabstrip_area_width, min_size.width())); - } - return min_size; }
diff --git a/chrome/browser/ui/views/frame/hosted_app_menu_button.cc b/chrome/browser/ui/views/frame/hosted_app_menu_button.cc index 80da07471..68b66e5 100644 --- a/chrome/browser/ui/views/frame/hosted_app_menu_button.cc +++ b/chrome/browser/ui/views/frame/hosted_app_menu_button.cc
@@ -76,8 +76,9 @@ const ui::Event* event) { Browser* browser = browser_view_->browser(); RunMenu(std::make_unique<HostedAppMenuModel>(browser_view_, browser), browser, - event && event->IsKeyEvent() ? AppMenu::SHOW_MNEMONICS - : AppMenu::NO_FLAGS, + event && event->IsKeyEvent() + ? views::MenuRunner::SHOULD_SHOW_MNEMONICS + : views::MenuRunner::NO_FLAGS, false); // Add UMA for how many times the hosted app menu button are clicked.
diff --git a/chrome/browser/ui/views/infobars/infobar_view.cc b/chrome/browser/ui/views/infobars/infobar_view.cc index ac8a9e37..680278b 100644 --- a/chrome/browser/ui/views/infobars/infobar_view.cc +++ b/chrome/browser/ui/views/infobars/infobar_view.cc
@@ -163,8 +163,7 @@ OffsetY(close_button_))); // For accessibility reasons, the close button should come last. - DCHECK_EQ(close_button_->parent()->child_count() - 1, - close_button_->parent()->GetIndexOf(close_button_)); + DCHECK_EQ(close_button_, close_button_->parent()->children().back()); } void InfoBarView::GetAccessibleNodeData(ui::AXNodeData* node_data) {
diff --git a/chrome/browser/ui/views/location_bar/location_bar_view.cc b/chrome/browser/ui/views/location_bar/location_bar_view.cc index b2c944b..4384187 100644 --- a/chrome/browser/ui/views/location_bar/location_bar_view.cc +++ b/chrome/browser/ui/views/location_bar/location_bar_view.cc
@@ -59,7 +59,7 @@ #include "chrome/common/chrome_features.h" #include "chrome/grit/chromium_strings.h" #include "chrome/grit/generated_resources.h" -#include "components/autofill/core/common/autofill_features.h" +#include "components/autofill/core/common/autofill_payments_features.h" #include "components/bookmarks/common/bookmark_pref_names.h" #include "components/favicon/content/content_favicon_driver.h" #include "components/omnibox/browser/location_bar_model.h"
diff --git a/chrome/browser/ui/views/media_router/app_menu_test_api_views.cc b/chrome/browser/ui/views/media_router/app_menu_test_api_views.cc index 815e081..5bcf712 100644 --- a/chrome/browser/ui/views/media_router/app_menu_test_api_views.cc +++ b/chrome/browser/ui/views/media_router/app_menu_test_api_views.cc
@@ -42,7 +42,7 @@ } void AppMenuTestApiViews::ShowMenu() { - GetAppMenuButton()->ShowMenu(AppMenu::NO_FLAGS); + GetAppMenuButton()->ShowMenu(views::MenuRunner::NO_FLAGS); } void AppMenuTestApiViews::ExecuteCommand(int command) {
diff --git a/chrome/browser/ui/views/page_action/pwa_install_view.cc b/chrome/browser/ui/views/page_action/pwa_install_view.cc index f2c4e4d..eb430378 100644 --- a/chrome/browser/ui/views/page_action/pwa_install_view.cc +++ b/chrome/browser/ui/views/page_action/pwa_install_view.cc
@@ -4,6 +4,7 @@ #include "chrome/browser/ui/views/page_action/pwa_install_view.h" +#include "base/metrics/user_metrics.h" #include "chrome/app/chrome_command_ids.h" #include "chrome/browser/banners/app_banner_manager.h" #include "chrome/browser/web_applications/components/web_app_tab_helper_base.h" @@ -49,7 +50,9 @@ return visible() != was_visible; } -void PwaInstallView::OnExecuting(PageActionIconView::ExecuteSource source) {} +void PwaInstallView::OnExecuting(PageActionIconView::ExecuteSource source) { + base::RecordAction(base::UserMetricsAction("PWAInstallIcon")); +} views::BubbleDialogDelegateView* PwaInstallView::GetBubble() const { // TODO(https://907351): Implement.
diff --git a/chrome/browser/ui/views/page_info/page_info_bubble_view.cc b/chrome/browser/ui/views/page_info/page_info_bubble_view.cc index 28ae071..2832d7b4 100644 --- a/chrome/browser/ui/views/page_info/page_info_bubble_view.cc +++ b/chrome/browser/ui/views/page_info/page_info_bubble_view.cc
@@ -682,7 +682,7 @@ // case that can be recovered from by closing & reopening the bubble. // TODO(patricialor): Investigate removing callsites to this method other than // the constructor. - if (permissions_view_->has_children()) + if (!permissions_view_->children().empty()) return; views::GridLayout* layout = permissions_view_->SetLayoutManager(
diff --git a/chrome/browser/ui/views/payments/editor_view_controller.cc b/chrome/browser/ui/views/payments/editor_view_controller.cc index bea57a6..4557672 100644 --- a/chrome/browser/ui/views/payments/editor_view_controller.cc +++ b/chrome/browser/ui/views/payments/editor_view_controller.cc
@@ -486,7 +486,7 @@ if (error_message.empty()) { label_view_it->second->RemoveAllChildViews(/*delete_children=*/true); } else { - if (!label_view_it->second->has_children()) { + if (label_view_it->second->children().empty()) { // If there was no error label view, add it. label_view_it->second->AddChildView( CreateErrorLabelView(error_message, type).release());
diff --git a/chrome/browser/ui/views/payments/payment_request_item_list_unittest.cc b/chrome/browser/ui/views/payments/payment_request_item_list_unittest.cc index 05d8d1ea..c72ca93 100644 --- a/chrome/browser/ui/views/payments/payment_request_item_list_unittest.cc +++ b/chrome/browser/ui/views/payments/payment_request_item_list_unittest.cc
@@ -61,7 +61,7 @@ PaymentRequestItemList list(nullptr); std::unique_ptr<views::View> list_view = list.CreateListView(); - EXPECT_FALSE(list_view->has_children()); + EXPECT_TRUE(list_view->children().empty()); std::vector<std::unique_ptr<TestListItem>> items; items.push_back(std::make_unique<TestListItem>(&list, false));
diff --git a/chrome/browser/ui/views/status_bubble_views.cc b/chrome/browser/ui/views/status_bubble_views.cc index 9648e13d..45d2c50 100644 --- a/chrome/browser/ui/views/status_bubble_views.cc +++ b/chrome/browser/ui/views/status_bubble_views.cc
@@ -600,9 +600,7 @@ : base_view_(base_view) {} StatusBubbleViews::~StatusBubbleViews() { - CancelExpandTimer(); - if (popup_) - popup_->CloseNow(); + DestroyPopup(); } void StatusBubbleViews::InitPopup() { @@ -637,12 +635,12 @@ } void StatusBubbleViews::DestroyPopup() { - DCHECK(popup_); CancelExpandTimer(); expand_view_.reset(); view_ = nullptr; - popup_->CloseNow(); - popup_.reset(); + // Move |popup_| to the stack to avoid reentrancy issues with CloseNow(). + if (std::unique_ptr<views::Widget> popup = std::move(popup_)) + popup->CloseNow(); } void StatusBubbleViews::Reposition() {
diff --git a/chrome/browser/ui/views/tabs/tab_drag_controller.cc b/chrome/browser/ui/views/tabs/tab_drag_controller.cc index b807bc6a..c58df19 100644 --- a/chrome/browser/ui/views/tabs/tab_drag_controller.cc +++ b/chrome/browser/ui/views/tabs/tab_drag_controller.cc
@@ -508,6 +508,7 @@ GetModel(source_tabstrip_)->count()) { views::Widget* widget = GetAttachedBrowserWidget(); gfx::Rect new_bounds; + gfx::Vector2d drag_offset; if (was_source_maximized_ || was_source_fullscreen_) { did_restore_window_ = true; // When all tabs in a maximized browser are dragged the browser gets @@ -523,14 +524,15 @@ widget->SetVisibilityChangedAnimationsEnabled(false); widget->Restore(); widget->SetBounds(new_bounds); - AdjustBrowserAndTabBoundsForDrag(last_tabstrip_width, - point_in_screen, - &drag_bounds); + drag_offset = GetWindowOffset(point_in_screen); + AdjustBrowserAndTabBoundsForDrag(last_tabstrip_width, point_in_screen, + &drag_offset, &drag_bounds); widget->SetVisibilityChangedAnimationsEnabled(true); } else { new_bounds = CalculateNonMaximizedDraggedBrowserBounds(widget, point_in_screen); widget->SetBounds(new_bounds); + drag_offset = GetWindowOffset(point_in_screen); } #if defined(OS_CHROMEOS) @@ -538,7 +540,7 @@ new_bounds); #endif - RunMoveLoop(GetWindowOffset(point_in_screen)); + RunMoveLoop(drag_offset); return; } } @@ -1285,9 +1287,8 @@ dragged_widget->SetCanAppearInExistingFullscreenSpaces(true); dragged_widget->SetVisibilityChangedAnimationsEnabled(false); Attach(dragged_browser_view->tabstrip(), gfx::Point()); - AdjustBrowserAndTabBoundsForDrag(last_tabstrip_width, - point_in_screen, - &drag_bounds); + AdjustBrowserAndTabBoundsForDrag(last_tabstrip_width, point_in_screen, + &drag_offset, &drag_bounds); browser->window()->Show(); dragged_widget->SetVisibilityChangedAnimationsEnabled(true); // Activate may trigger a focus loss, destroying us. @@ -1867,6 +1868,7 @@ void TabDragController::AdjustBrowserAndTabBoundsForDrag( int last_tabstrip_width, const gfx::Point& point_in_screen, + gfx::Vector2d* drag_offset, std::vector<gfx::Rect>* drag_bounds) { attached_tabstrip_->InvalidateLayout(); attached_tabstrip_->DoLayout(); @@ -1898,6 +1900,7 @@ gfx::Rect bounds = GetAttachedBrowserWidget()->GetWindowBoundsInScreen(); bounds.set_x(point_in_screen.x() - offset.x()); GetAttachedBrowserWidget()->SetBounds(bounds); + *drag_offset = point_in_screen - bounds.origin(); } attached_tabstrip_->SetTabBoundsForDrag(*drag_bounds); } @@ -1910,7 +1913,6 @@ gfx::Rect new_bounds(CalculateDraggedBrowserBounds(source, point_in_screen, drag_bounds)); - *drag_offset = point_in_screen - new_bounds.origin(); Profile* profile = Profile::FromBrowserContext(drag_data_[0].contents->GetBrowserContext());
diff --git a/chrome/browser/ui/views/tabs/tab_drag_controller.h b/chrome/browser/ui/views/tabs/tab_drag_controller.h index b5ba003..dd34258 100644 --- a/chrome/browser/ui/views/tabs/tab_drag_controller.h +++ b/chrome/browser/ui/views/tabs/tab_drag_controller.h
@@ -436,8 +436,12 @@ // When |last_tabstrip_width| is larger than the new tabstrip width the tabs // in the attached tabstrip are scaled and the attached browser is positioned // such that the tab that was dragged remains under the |point_in_screen|. + // |drag_offset| is the offset of |point_in_screen| from the origin of the + // dragging browser window, and will be updated when this method ends up with + // changing the origin of the attached browser window. void AdjustBrowserAndTabBoundsForDrag(int last_tabstrip_width, const gfx::Point& point_in_screen, + gfx::Vector2d* drag_offset, std::vector<gfx::Rect>* drag_bounds); // Creates and returns a new Browser to handle the drag.
diff --git a/chrome/browser/ui/views/tabs/tab_drag_controller_interactive_uitest.cc b/chrome/browser/ui/views/tabs/tab_drag_controller_interactive_uitest.cc index b7b8eab0..ff1194dc 100644 --- a/chrome/browser/ui/views/tabs/tab_drag_controller_interactive_uitest.cc +++ b/chrome/browser/ui/views/tabs/tab_drag_controller_interactive_uitest.cc
@@ -1672,6 +1672,84 @@ namespace { +TabStrip* GetAttachedTabstrip() { + for (Browser* browser : *BrowserList::GetInstance()) { + BrowserView* browser_view = BrowserView::GetBrowserViewForBrowser(browser); + if (TabDragController::IsAttachedTo(browser_view->tabstrip())) + return browser_view->tabstrip(); + } + return nullptr; +} + +void DragWindowAndVerifyOffset(DetachToBrowserTabDragControllerTest* test, + TabStrip* tab_strip, + int tab_index) { + // Move to the tab and drag it enough so that it detaches. + const gfx::Point tab_center = + GetCenterInScreenCoordinates(tab_strip->tab_at(tab_index)); + // The expected offset; the horizontal position should be relative to the + // pressed tab. The vertical position should be relative to the window itself + // since the top margin can be different between the existing browser and + // the dragged one. + const gfx::Vector2d press_offset( + tab_center.x() - tab_strip->tab_at(tab_index)->GetBoundsInScreen().x(), + tab_center.y() - tab_strip->GetWidget()->GetWindowBoundsInScreen().y()); + const gfx::Point initial_move = + tab_center + gfx::Vector2d(0, GetDetachY(tab_strip)); + const gfx::Point second_move = initial_move + gfx::Vector2d(20, 20); + ASSERT_TRUE(test->PressInput(tab_center)); + ASSERT_TRUE(test->DragInputToNotifyWhenDone( + initial_move, base::BindLambdaForTesting([&]() { + // Moves slightly to cause the actual dragging effect on the system and + // makes sure the window is positioned correctly. + ASSERT_TRUE(test->DragInputToNotifyWhenDone( + second_move, base::BindLambdaForTesting([&]() { + TabStrip* attached = GetAttachedTabstrip(); + // Same computation for drag offset. This operation drags a single + // tab, so the target tab index should be always 0. + gfx::Vector2d drag_offset( + second_move.x() - + attached->tab_at(0)->GetBoundsInScreen().x(), + second_move.y() - + attached->GetWidget()->GetWindowBoundsInScreen().y()); + EXPECT_EQ(press_offset, drag_offset); + ASSERT_TRUE(test->ReleaseInput()); + }))); + }))); + test::QuitDraggingObserver().Wait(); +} + +} // namespace + +IN_PROC_BROWSER_TEST_P(DetachToBrowserTabDragControllerTest, + OffsetForDraggingInMaximizedWindow) { + AddTabAndResetBrowser(browser()); + // Moves the browser window slightly to ensure that the browser's restored + // bounds are different from the maximized bound's origin. + browser()->window()->SetBounds(browser()->window()->GetBounds() + + gfx::Vector2d(100, 50)); + browser()->window()->Maximize(); + aura::test::WaitForAllChangesToComplete(); + + DragWindowAndVerifyOffset(this, GetTabStripForBrowser(browser()), 0); + ASSERT_FALSE(TabDragController::IsActive()); +} + +IN_PROC_BROWSER_TEST_P(DetachToBrowserTabDragControllerTest, + OffsetForDraggingInTabletMode) { + AddTabAndResetBrowser(browser()); + // Moves the browser window slightly to ensure that the browser's restored + // bounds are different from the maximized bound's origin. + browser()->window()->SetBounds(browser()->window()->GetBounds() + + gfx::Vector2d(100, 50)); + test::SetAndWaitForTabletMode(true); + + DragWindowAndVerifyOffset(this, GetTabStripForBrowser(browser()), 1); + ASSERT_FALSE(TabDragController::IsActive()); +} + +namespace { + void DragToOverviewWindowStep2(DetachToBrowserTabDragControllerTest* test, TabStrip* not_attached_tab_strip, TabStrip* target_tab_strip) {
diff --git a/chrome/browser/ui/views/tabs/tab_hover_card_bubble_view.cc b/chrome/browser/ui/views/tabs/tab_hover_card_bubble_view.cc index 1c878366..22bbd20 100644 --- a/chrome/browser/ui/views/tabs/tab_hover_card_bubble_view.cc +++ b/chrome/browser/ui/views/tabs/tab_hover_card_bubble_view.cc
@@ -15,6 +15,9 @@ #include "chrome/browser/ui/views/tabs/tab.h" #include "chrome/browser/ui/views/tabs/tab_renderer_data.h" #include "components/url_formatter/url_formatter.h" +#include "ui/gfx/animation/animation_delegate.h" +#include "ui/gfx/animation/linear_animation.h" +#include "ui/gfx/animation/tween.h" #include "ui/gfx/image/image_skia.h" #include "ui/views/bubble/bubble_frame_view.h" #include "ui/views/controls/image_view.h" @@ -76,6 +79,100 @@ } // namespace +// static +bool TabHoverCardBubbleView::disable_animations_for_testing_ = false; + +// TODO(corising): Move this to a place where it could be used for all widgets. +class TabHoverCardBubbleView::WidgetFadeAnimationDelegate + : public gfx::AnimationDelegate { + public: + explicit WidgetFadeAnimationDelegate(views::Widget* hover_card) + : widget_(hover_card), + fade_animation_(std::make_unique<gfx::LinearAnimation>(this)) {} + ~WidgetFadeAnimationDelegate() override {} + + enum class FadeAnimationState { + // No animation is running. + IDLE, + FADE_IN, + FADE_OUT, + }; + + void set_animation_state(FadeAnimationState state) { + animation_state_ = state; + } + + bool IsFadingIn() const { + return animation_state_ == FadeAnimationState::FADE_IN; + } + + bool IsFadingOut() const { + return animation_state_ == FadeAnimationState::FADE_OUT; + } + + void FadeIn() { + if (IsFadingIn()) + return; + constexpr base::TimeDelta kFadeInDuration = + base::TimeDelta::FromMilliseconds(200); + set_animation_state(FadeAnimationState::FADE_IN); + widget_->SetOpacity(0); + fade_animation_ = std::make_unique<gfx::LinearAnimation>(this); + fade_animation_->SetDuration(kFadeInDuration); + fade_animation_->Start(); + } + + void FadeOut() { + if (IsFadingOut()) + return; + constexpr base::TimeDelta kFadeOutDuration = + base::TimeDelta::FromMilliseconds(150); + fade_animation_ = std::make_unique<gfx::LinearAnimation>(this); + set_animation_state(FadeAnimationState::FADE_OUT); + fade_animation_->SetDuration(kFadeOutDuration); + fade_animation_->Start(); + } + + void CancelFadeOut() { + if (!IsFadingOut()) + return; + + fade_animation_->Stop(); + set_animation_state(FadeAnimationState::IDLE); + widget_->SetOpacity(1); + } + + private: + void AnimationProgressed(const gfx::Animation* animation) override { + // Get the value of the animation with a material ease applied. + double value = gfx::Tween::CalculateValue(gfx::Tween::FAST_OUT_SLOW_IN, + animation->GetCurrentValue()); + float opaqueness = 0; + if (IsFadingOut()) { + opaqueness = gfx::Tween::FloatValueBetween(value, 1.0f, 0.0f); + } else if (animation_state_ == FadeAnimationState::FADE_IN) { + opaqueness = gfx::Tween::FloatValueBetween(value, 0.0f, 1.0f); + } + + if (IsFadingOut() && opaqueness == 0) { + widget_->Hide(); + } else { + widget_->SetOpacity(opaqueness); + } + } + + void AnimationEnded(const gfx::Animation* animation) override { + AnimationProgressed(animation); + set_animation_state(FadeAnimationState::IDLE); + } + + views::Widget* const widget_; + std::unique_ptr<gfx::LinearAnimation> fade_animation_; + FadeAnimationState animation_state_ = FadeAnimationState::IDLE; + + DISALLOW_COPY_AND_ASSIGN(WidgetFadeAnimationDelegate); +}; + TabHoverCardBubbleView::TabHoverCardBubbleView(Tab* tab) : BubbleDialogDelegateView(tab, views::BubbleBorder::TOP_LEFT) { // We'll do all of our own layout inside the bubble, so no need to inset this @@ -124,6 +221,8 @@ new gfx::Insets(kLineSpacing, kOuterMargin, kOuterMargin, kOuterMargin)); widget_ = views::BubbleDialogDelegateView::CreateBubble(this); + fade_animation_delegate_ = + std::make_unique<WidgetFadeAnimationDelegate>(widget_); } TabHoverCardBubbleView::~TabHoverCardBubbleView() = default; @@ -133,19 +232,25 @@ views::BubbleDialogDelegateView::SetAnchorView(tab); + fade_animation_delegate_->CancelFadeOut(); + // Start trigger timer if necessary. if (!widget_->IsVisible()) { // Note that this will restart the timer if it is already running. If the // hover cards are not yet visible, moving the cursor within the tabstrip // will not trigger the hover cards. delayed_show_timer_.Start(FROM_HERE, GetDelay(tab->width()), this, - &TabHoverCardBubbleView::ShowImmediately); + &TabHoverCardBubbleView::FadeInToShow); } } -void TabHoverCardBubbleView::Hide() { +void TabHoverCardBubbleView::FadeOutToHide() { delayed_show_timer_.Stop(); - widget_->Hide(); + if (disable_animations_for_testing_) { + widget_->Hide(); + } else { + fade_animation_delegate_->FadeOut(); + } } int TabHoverCardBubbleView::GetDialogButtons() const { @@ -185,8 +290,10 @@ return delay; } -void TabHoverCardBubbleView::ShowImmediately() { +void TabHoverCardBubbleView::FadeInToShow() { widget_->Show(); + if (!disable_animations_for_testing_) + fade_animation_delegate_->FadeIn(); } void TabHoverCardBubbleView::UpdateCardContent(TabRendererData data) {
diff --git a/chrome/browser/ui/views/tabs/tab_hover_card_bubble_view.h b/chrome/browser/ui/views/tabs/tab_hover_card_bubble_view.h index 44d6f388..6c6c6f8 100644 --- a/chrome/browser/ui/views/tabs/tab_hover_card_bubble_view.h +++ b/chrome/browser/ui/views/tabs/tab_hover_card_bubble_view.h
@@ -5,6 +5,8 @@ #ifndef CHROME_BROWSER_UI_VIEWS_TABS_TAB_HOVER_CARD_BUBBLE_VIEW_H_ #define CHROME_BROWSER_UI_VIEWS_TABS_TAB_HOVER_CARD_BUBBLE_VIEW_H_ +#include <memory> + #include "base/time/time.h" #include "base/timer/timer.h" #include "ui/views/bubble/bubble_dialog_delegate_view.h" @@ -28,18 +30,19 @@ // Updates card content and anchoring and shows the tab hover card. void UpdateAndShow(Tab* tab); - void Hide(); + void FadeOutToHide(); // BubbleDialogDelegateView: int GetDialogButtons() const override; private: friend class TabHoverCardBubbleViewBrowserTest; + class WidgetFadeAnimationDelegate; // Get delay in milliseconds based on tab width. base::TimeDelta GetDelay(int tab_width) const; - void ShowImmediately(); + void FadeInToShow(); // Updates and formats title and domain with given data. void UpdateCardContent(TabRendererData data); @@ -48,6 +51,10 @@ base::OneShotTimer delayed_show_timer_; + // Fade animations interfere with browser tests so we disable them in tests. + static bool disable_animations_for_testing_; + std::unique_ptr<WidgetFadeAnimationDelegate> fade_animation_delegate_; + views::Widget* widget_ = nullptr; views::Label* title_label_ = nullptr; views::Label* domain_label_ = nullptr;
diff --git a/chrome/browser/ui/views/tabs/tab_hover_card_bubble_view_browsertest.cc b/chrome/browser/ui/views/tabs/tab_hover_card_bubble_view_browsertest.cc index f076ecf..d1c069e 100644 --- a/chrome/browser/ui/views/tabs/tab_hover_card_bubble_view_browsertest.cc +++ b/chrome/browser/ui/views/tabs/tab_hover_card_bubble_view_browsertest.cc
@@ -75,7 +75,9 @@ class TabHoverCardBubbleViewBrowserTest : public DialogBrowserTest { public: - TabHoverCardBubbleViewBrowserTest() = default; + TabHoverCardBubbleViewBrowserTest() { + TabHoverCardBubbleView::disable_animations_for_testing_ = true; + } ~TabHoverCardBubbleViewBrowserTest() override = default; void SetUp() override {
diff --git a/chrome/browser/ui/views/tabs/tab_renderer_data.h b/chrome/browser/ui/views/tabs/tab_renderer_data.h index 30cca69..2970666 100644 --- a/chrome/browser/ui/views/tabs/tab_renderer_data.h +++ b/chrome/browser/ui/views/tabs/tab_renderer_data.h
@@ -8,12 +8,11 @@ #include "base/strings/string16.h" #include "chrome/browser/ui/tabs/tab_network_state.h" #include "chrome/browser/ui/tabs/tab_utils.h" -#include "chrome/browser/ui/views/chrome_views_export.h" #include "ui/gfx/image/image_skia.h" #include "url/gurl.h" // Wraps the state needed by the renderers. -struct CHROME_VIEWS_EXPORT TabRendererData { +struct TabRendererData { TabRendererData(); TabRendererData(const TabRendererData& other); TabRendererData(TabRendererData&& other);
diff --git a/chrome/browser/ui/views/tabs/tab_strip.cc b/chrome/browser/ui/views/tabs/tab_strip.cc index 978bf8a..833116c 100644 --- a/chrome/browser/ui/views/tabs/tab_strip.cc +++ b/chrome/browser/ui/views/tabs/tab_strip.cc
@@ -1128,7 +1128,7 @@ if (should_show) hover_card_->UpdateAndShow(tab); else - hover_card_->Hide(); + hover_card_->FadeOutToHide(); } bool TabStrip::ShouldPaintTab(const Tab* tab, float scale, SkPath* clip) {
diff --git a/chrome/browser/ui/views/tabs/tab_strip_unittest.cc b/chrome/browser/ui/views/tabs/tab_strip_unittest.cc index a106daa7..e85f7edf 100644 --- a/chrome/browser/ui/views/tabs/tab_strip_unittest.cc +++ b/chrome/browser/ui/views/tabs/tab_strip_unittest.cc
@@ -361,7 +361,7 @@ Tab* left = tab_strip->tab_at(i - 1); Tab* right = tab_strip->tab_at(i); - if (tab_strip->GetIndexOf(right) < tab_strip->GetIndexOf(left)) { + if (tab_strip->FindChild(right) < tab_strip->FindChild(left)) { return false; } }
diff --git a/chrome/browser/ui/views/test/view_event_test_base.cc b/chrome/browser/ui/views/test/view_event_test_base.cc index 45f6ce54..dda24a6 100644 --- a/chrome/browser/ui/views/test/view_event_test_base.cc +++ b/chrome/browser/ui/views/test/view_event_test_base.cc
@@ -42,7 +42,7 @@ // Permit a test to remove the view being tested from the hierarchy, then // still handle a _NET_WM_STATE event on Linux during teardown that triggers // layout. - if (!has_children()) + if (children().empty()) return; View* child_view = child_at(0);
diff --git a/chrome/browser/ui/views/test/view_event_test_platform_part_chromeos.cc b/chrome/browser/ui/views/test/view_event_test_platform_part_chromeos.cc index 346159e8..9ef1055 100644 --- a/chrome/browser/ui/views/test/view_event_test_platform_part_chromeos.cc +++ b/chrome/browser/ui/views/test/view_event_test_platform_part_chromeos.cc
@@ -53,7 +53,7 @@ ui::ContextFactory* context_factory, ui::ContextFactoryPrivate* context_factory_private) { chromeos::DBusThreadManager::Initialize(); - chromeos::PowerManagerClient::Initialize(); + chromeos::PowerManagerClient::InitializeFake(); // ash::Shell::CreateInstance needs chromeos::PowerPolicyController // initialized. In classic ash, it is initialized in chrome process. In mash, // it is initialized by window manager service.
diff --git a/chrome/browser/ui/views/toolbar/app_menu.cc b/chrome/browser/ui/views/toolbar/app_menu.cc index 956a9db..771baf7d 100644 --- a/chrome/browser/ui/views/toolbar/app_menu.cc +++ b/chrome/browser/ui/views/toolbar/app_menu.cc
@@ -773,9 +773,9 @@ // AppMenu ------------------------------------------------------------------ -AppMenu::AppMenu(Browser* browser, int run_flags, bool alert_reopen_tab_items) +AppMenu::AppMenu(Browser* browser, int run_types, bool alert_reopen_tab_items) : browser_(browser), - run_flags_(run_flags), + run_types_(run_types), alert_reopen_tab_items_(alert_reopen_tab_items) { registrar_.Add(this, chrome::NOTIFICATION_GLOBAL_ERRORS_CHANGED, content::Source<Profile>(browser_->profile())); @@ -804,7 +804,7 @@ // BrowserActionsContainer view. types |= views::MenuRunner::FOR_DROP | views::MenuRunner::NESTED_DRAG; } - if (run_flags_ & AppMenu::SHOW_MNEMONICS) + if (run_types_ & views::MenuRunner::SHOULD_SHOW_MNEMONICS) types |= views::MenuRunner::SHOULD_SHOW_MNEMONICS; menu_runner_.reset(new views::MenuRunner(root_, types));
diff --git a/chrome/browser/ui/views/toolbar/app_menu.h b/chrome/browser/ui/views/toolbar/app_menu.h index 7975fee..991e0c9 100644 --- a/chrome/browser/ui/views/toolbar/app_menu.h +++ b/chrome/browser/ui/views/toolbar/app_menu.h
@@ -35,18 +35,7 @@ public content::NotificationObserver, public base::SupportsWeakPtr<AppMenu> { public: - // TODO(cyan): Remove this enum and use MenuRunner::RunTypes instead. - enum RunFlags { - NO_FLAGS = 0, - - // Indicates that the menu was opened for a drag-and-drop operation. - FOR_DROP = 1 << 0, - - // Indicates that the menu should show mnemonics. - SHOW_MNEMONICS = 1 << 1, - }; - - AppMenu(Browser* browser, int run_flags, bool alert_reopen_tab_items); + AppMenu(Browser* browser, int run_types, bool alert_reopen_tab_items); ~AppMenu() override; void Init(ui::MenuModel* model); @@ -60,7 +49,9 @@ // Whether the menu is currently visible to the user. bool IsShowing() const; - bool for_drop() const { return (run_flags_ & FOR_DROP) != 0; } + bool for_drop() const { + return (run_types_ & views::MenuRunner::FOR_DROP) != 0; + } views::MenuItemView* root_menu_item() { return root_; } @@ -193,8 +184,8 @@ content::NotificationRegistrar registrar_; - // The bit mask of RunFlags. - const int run_flags_; + // The bit mask of views::MenuRunner::RunTypes. + const int run_types_; // Whether to show items relating to reopening the last-closed tab as alerted. const bool alert_reopen_tab_items_;
diff --git a/chrome/browser/ui/views/toolbar/browser_app_menu_button.cc b/chrome/browser/ui/views/toolbar/browser_app_menu_button.cc index b63d874..8fde1dd 100644 --- a/chrome/browser/ui/views/toolbar/browser_app_menu_button.cc +++ b/chrome/browser/ui/views/toolbar/browser_app_menu_button.cc
@@ -240,7 +240,7 @@ toolbar_view_->app_menu_icon_controller()), browser, run_types, alert_reopen_tab_items); - if (!(run_types & AppMenu::FOR_DROP)) { + if (!(run_types & views::MenuRunner::FOR_DROP)) { // Record the time-to-action for the menu. We don't record in the case of a // drag-and-drop command because menus opened for drag-and-drop don't block // the message loop. @@ -370,9 +370,9 @@ void BrowserAppMenuButton::OnDragEntered(const ui::DropTargetEvent& event) { DCHECK(!weak_factory_.HasWeakPtrs()); - int run_types = AppMenu::FOR_DROP; + int run_types = views::MenuRunner::FOR_DROP; if (event.IsKeyEvent()) - run_types |= AppMenu::SHOW_MNEMONICS; + run_types |= views::MenuRunner::SHOULD_SHOW_MNEMONICS; if (!g_open_app_immediately_for_testing) { base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
diff --git a/chrome/browser/ui/views/toolbar/toolbar_view.cc b/chrome/browser/ui/views/toolbar/toolbar_view.cc index cc9ed0a2..584aee4 100644 --- a/chrome/browser/ui/views/toolbar/toolbar_view.cc +++ b/chrome/browser/ui/views/toolbar/toolbar_view.cc
@@ -52,7 +52,7 @@ #include "chrome/grit/chromium_strings.h" #include "chrome/grit/generated_resources.h" #include "chrome/grit/theme_resources.h" -#include "components/autofill/core/common/autofill_features.h" +#include "components/autofill/core/common/autofill_payments_features.h" #include "components/omnibox/browser/omnibox_view.h" #include "components/prefs/pref_service.h" #include "components/strings/grit/components_strings.h" @@ -404,7 +404,9 @@ const ui::Event* event) { TRACE_EVENT0("views", "ToolbarView::OnMenuButtonClicked"); DCHECK_EQ(VIEW_ID_APP_MENU, source->id()); - app_menu_button_->ShowMenu(AppMenu::NO_FLAGS); + app_menu_button_->ShowMenu((event && event->IsKeyEvent()) + ? views::MenuRunner::SHOULD_SHOW_MNEMONICS + : views::MenuRunner::NO_FLAGS); } ////////////////////////////////////////////////////////////////////////////////
diff --git a/chrome/browser/ui/views/touch_selection_menu_chromeos.cc b/chrome/browser/ui/views/touch_selection_menu_chromeos.cc index d989110a..1f985ecd 100644 --- a/chrome/browser/ui/views/touch_selection_menu_chromeos.cc +++ b/chrome/browser/ui/views/touch_selection_menu_chromeos.cc
@@ -50,8 +50,7 @@ // default action buttons are already added, we should remove the existent // buttons if any, and then call CreateButtons, this will call the parent // method too. - if (has_children()) - RemoveAllChildViews(/*delete_children=*/true); + RemoveAllChildViews(/*delete_children=*/true); CreateButtons(); }
diff --git a/chrome/browser/ui/views/webauthn/authenticator_request_dialog_view.cc b/chrome/browser/ui/views/webauthn/authenticator_request_dialog_view.cc index ec4d3894..619302f 100644 --- a/chrome/browser/ui/views/webauthn/authenticator_request_dialog_view.cc +++ b/chrome/browser/ui/views/webauthn/authenticator_request_dialog_view.cc
@@ -267,7 +267,7 @@ other_transports_menu_runner_.reset(); delete sheet_; - DCHECK(!has_children()); + DCHECK(children().empty()); sheet_ = new_sheet.get(); AddChildView(new_sheet.release());
diff --git a/chrome/browser/ui/webui/chromeos/cryptohome_web_ui_handler.cc b/chrome/browser/ui/webui/chromeos/cryptohome_web_ui_handler.cc index 8878f366..b57ba5df 100644 --- a/chrome/browser/ui/webui/chromeos/cryptohome_web_ui_handler.cc +++ b/chrome/browser/ui/webui/chromeos/cryptohome_web_ui_handler.cc
@@ -7,7 +7,7 @@ #include "base/bind.h" #include "base/task/post_task.h" #include "base/values.h" -#include "chromeos/dbus/cryptohome_client.h" +#include "chromeos/dbus/cryptohome/cryptohome_client.h" #include "chromeos/dbus/dbus_thread_manager.h" #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h"
diff --git a/chrome/browser/ui/webui/chromeos/login/enable_debugging_screen_handler.cc b/chrome/browser/ui/webui/chromeos/login/enable_debugging_screen_handler.cc index 5f380c7..cbd2af7 100644 --- a/chrome/browser/ui/webui/chromeos/login/enable_debugging_screen_handler.cc +++ b/chrome/browser/ui/webui/chromeos/login/enable_debugging_screen_handler.cc
@@ -18,7 +18,7 @@ #include "chrome/grit/chromium_strings.h" #include "chrome/grit/generated_resources.h" #include "chromeos/constants/chromeos_switches.h" -#include "chromeos/dbus/cryptohome_client.h" +#include "chromeos/dbus/cryptohome/cryptohome_client.h" #include "chromeos/dbus/dbus_thread_manager.h" #include "chromeos/dbus/debug_daemon_client.h" #include "chromeos/dbus/power/power_manager_client.h"
diff --git a/chrome/browser/ui/webui/chromeos/login/encryption_migration_screen_handler.cc b/chrome/browser/ui/webui/chromeos/login/encryption_migration_screen_handler.cc index 3364324..dbd390e 100644 --- a/chrome/browser/ui/webui/chromeos/login/encryption_migration_screen_handler.cc +++ b/chrome/browser/ui/webui/chromeos/login/encryption_migration_screen_handler.cc
@@ -30,7 +30,7 @@ #include "chromeos/cryptohome/async_method_caller.h" #include "chromeos/cryptohome/cryptohome_util.h" #include "chromeos/cryptohome/homedir_methods.h" -#include "chromeos/dbus/cryptohome_client.h" +#include "chromeos/dbus/cryptohome/cryptohome_client.h" #include "chromeos/dbus/dbus_thread_manager.h" #include "chromeos/dbus/power/power_manager_client.h" #include "chromeos/dbus/power/power_policy_controller.h"
diff --git a/chrome/browser/ui/webui/chromeos/login/encryption_migration_screen_handler.h b/chrome/browser/ui/webui/chromeos/login/encryption_migration_screen_handler.h index e9ae36ab..8e2c0c1 100644 --- a/chrome/browser/ui/webui/chromeos/login/encryption_migration_screen_handler.h +++ b/chrome/browser/ui/webui/chromeos/login/encryption_migration_screen_handler.h
@@ -15,8 +15,8 @@ #include "chrome/browser/chromeos/login/screens/encryption_migration_screen_view.h" #include "chrome/browser/ui/webui/chromeos/login/base_screen_handler.h" #include "chromeos/cryptohome/cryptohome_parameters.h" +#include "chromeos/dbus/cryptohome/cryptohome_client.h" #include "chromeos/dbus/cryptohome/rpc.pb.h" -#include "chromeos/dbus/cryptohome_client.h" #include "chromeos/dbus/power/power_manager_client.h" #include "chromeos/login/auth/user_context.h" #include "services/device/public/mojom/wake_lock.mojom.h"
diff --git a/chrome/browser/ui/webui/chromeos/login/encryption_migration_screen_handler_unittest.cc b/chrome/browser/ui/webui/chromeos/login/encryption_migration_screen_handler_unittest.cc index b1e45c1..c8bcf02 100644 --- a/chrome/browser/ui/webui/chromeos/login/encryption_migration_screen_handler_unittest.cc +++ b/chrome/browser/ui/webui/chromeos/login/encryption_migration_screen_handler_unittest.cc
@@ -16,8 +16,8 @@ #include "chrome/browser/ui/webui/chromeos/login/encryption_migration_screen_handler.h" #include "chromeos/cryptohome/homedir_methods.h" #include "chromeos/cryptohome/mock_async_method_caller.h" +#include "chromeos/dbus/cryptohome/fake_cryptohome_client.h" #include "chromeos/dbus/dbus_thread_manager.h" -#include "chromeos/dbus/fake_cryptohome_client.h" #include "chromeos/dbus/power/fake_power_manager_client.h" #include "chromeos/dbus/power/power_policy_controller.h" #include "chromeos/dbus/util/account_identifier_operators.h" @@ -133,10 +133,7 @@ fake_cryptohome_client_ = new FakeCryptohomeClient(); DBusThreadManager::GetSetterForTesting()->SetCryptohomeClient( base::WrapUnique<CryptohomeClient>(fake_cryptohome_client_)); - - PowerManagerClient::Initialize(); - - DBusThreadManager::Initialize(); + PowerManagerClient::InitializeFake(); PowerPolicyController::Initialize(PowerManagerClient::Get());
diff --git a/chrome/browser/ui/webui/settings/chromeos/device_storage_handler.cc b/chrome/browser/ui/webui/settings/chromeos/device_storage_handler.cc index 26b86ea..3eeef21 100644 --- a/chrome/browser/ui/webui/settings/chromeos/device_storage_handler.cc +++ b/chrome/browser/ui/webui/settings/chromeos/device_storage_handler.cc
@@ -32,7 +32,7 @@ #include "chrome/browser/profiles/profile.h" #include "chrome/grit/generated_resources.h" #include "chromeos/cryptohome/cryptohome_util.h" -#include "chromeos/dbus/cryptohome_client.h" +#include "chromeos/dbus/cryptohome/cryptohome_client.h" #include "chromeos/dbus/dbus_thread_manager.h" #include "components/arc/arc_util.h" #include "components/browsing_data/content/conditional_cache_counting_helper.h"
diff --git a/chrome/browser/ui/webui/settings/md_settings_localized_strings_provider.cc b/chrome/browser/ui/webui/settings/md_settings_localized_strings_provider.cc index 4c5eb14..d445cde 100644 --- a/chrome/browser/ui/webui/settings/md_settings_localized_strings_provider.cc +++ b/chrome/browser/ui/webui/settings/md_settings_localized_strings_provider.cc
@@ -36,6 +36,7 @@ #include "components/autofill/core/browser/personal_data_manager.h" #include "components/autofill/core/common/autofill_constants.h" #include "components/autofill/core/common/autofill_features.h" +#include "components/autofill/core/common/autofill_payments_features.h" #include "components/google/core/common/google_util.h" #include "components/omnibox/common/omnibox_features.h" #include "components/password_manager/core/browser/manage_passwords_referrer.h"
diff --git a/chrome/browser/ui/webui/settings/people_handler.cc b/chrome/browser/ui/webui/settings/people_handler.cc index 82385303..e842987 100644 --- a/chrome/browser/ui/webui/settings/people_handler.cc +++ b/chrome/browser/ui/webui/settings/people_handler.cc
@@ -852,8 +852,7 @@ } void PeopleHandler::InitializeSyncBlocker() { - if (!web_ui()) - return; + DCHECK(web_ui()); WebContents* web_contents = web_ui()->GetWebContents(); if (web_contents) { syncer::SyncService* service = GetSyncService(); @@ -877,11 +876,19 @@ void PeopleHandler::OnPrimaryAccountSet( const CoreAccountInfo& primary_account_info) { + // After a primary account was set, the Sync setup will start soon. Grab a + // SetupInProgressHandle right now to avoid a temporary "missing Sync + // confirmation" error in the avatar menu. See crbug.com/928696. + syncer::SyncService* service = GetSyncService(); + if (service && !sync_blocker_) + sync_blocker_ = service->GetSetupInProgressHandle(); + UpdateSyncStatus(); } void PeopleHandler::OnPrimaryAccountCleared( const CoreAccountInfo& previous_primary_account_info) { + sync_blocker_.reset(); UpdateSyncStatus(); } @@ -903,8 +910,8 @@ base::UserMetricsAction("Signin_Signin_CancelAbortAdvancedSyncSettings")); } -std::unique_ptr<base::DictionaryValue> -PeopleHandler::GetSyncStatusDictionary() { +std::unique_ptr<base::DictionaryValue> PeopleHandler::GetSyncStatusDictionary() + const { std::unique_ptr<base::DictionaryValue> sync_status(new base::DictionaryValue); if (profile_->IsGuestSession()) { // Cannot display signin status when running in guest mode on chromeos @@ -1092,7 +1099,21 @@ void PeopleHandler::MarkFirstSetupComplete() { syncer::SyncService* service = GetSyncService(); // The sync service may be nullptr if it has been just disabled by policy. - if (!service || service->GetUserSettings()->IsFirstSetupComplete()) + if (!service) + return; + + // Sync is usually already requested at this point, but it might not be if + // Sync was reset from the dashboard while this page was open. (In most + // situations, resetting Sync also signs the user out of Chrome so this + // doesn't come up, but on ChromeOS or for managed (enterprise) accounts + // signout isn't possible.) + // Note that this has to happen *before* checking if first-time setup is + // already marked complete, because on some platforms (e.g. ChromeOS) that + // gets set automatically. + service->GetUserSettings()->SetSyncRequested(true); + + // If the first-time setup is already complete, there's nothing else to do. + if (service->GetUserSettings()->IsFirstSetupComplete()) return; unified_consent::metrics::RecordSyncSetupDataTypesHistrogam(
diff --git a/chrome/browser/ui/webui/settings/people_handler.h b/chrome/browser/ui/webui/settings/people_handler.h index 0e49428..4a3b17fd 100644 --- a/chrome/browser/ui/webui/settings/people_handler.h +++ b/chrome/browser/ui/webui/settings/people_handler.h
@@ -112,6 +112,10 @@ FRIEND_TEST_ALL_PREFIXES( PeopleHandlerTest, RestartSyncAfterDashboardClearWithStandaloneTransport); + FRIEND_TEST_ALL_PREFIXES(PeopleHandlerTest, + DashboardClearWhileSettingsOpen_ConfirmSoon); + FRIEND_TEST_ALL_PREFIXES(PeopleHandlerTest, + DashboardClearWhileSettingsOpen_ConfirmLater); FRIEND_TEST_ALL_PREFIXES(PeopleHandlerDiceUnifiedConsentTest, StoredAccountsList); @@ -145,7 +149,7 @@ // Returns a newly created dictionary with a number of properties that // correspond to the status of sync. - std::unique_ptr<base::DictionaryValue> GetSyncStatusDictionary(); + std::unique_ptr<base::DictionaryValue> GetSyncStatusDictionary() const; // Helper routine that gets the SyncService associated with the parent // profile.
diff --git a/chrome/browser/ui/webui/settings/people_handler_unittest.cc b/chrome/browser/ui/webui/settings/people_handler_unittest.cc index 9e7e22f..cad8eaaa 100644 --- a/chrome/browser/ui/webui/settings/people_handler_unittest.cc +++ b/chrome/browser/ui/webui/settings/people_handler_unittest.cc
@@ -15,6 +15,7 @@ #include "base/stl_util.h" #include "base/values.h" #include "build/build_config.h" +#include "chrome/browser/defaults.h" #include "chrome/browser/signin/identity_test_environment_profile_adaptor.h" #include "chrome/browser/signin/scoped_account_consistency.h" #include "chrome/browser/signin/signin_error_controller_factory.h" @@ -559,7 +560,7 @@ SetSyncRequested(true)) .WillOnce([&](bool) { // SetSyncRequested(true) clears DISABLE_REASON_USER_CHOICE, and - // immediately starts initialzing the engine. + // immediately starts initializing the engine. ON_CALL(*mock_sync_service_, GetDisableReasons()) .WillByDefault(Return(syncer::SyncService::DISABLE_REASON_NONE)); ON_CALL(*mock_sync_service_->GetMockUserSettings(), IsSyncRequested()) @@ -1134,6 +1135,125 @@ ExpectPageStatusResponse(PeopleHandler::kConfigurePageStatus); } +TEST_F(PeopleHandlerTest, DashboardClearWhileSettingsOpen_ConfirmSoon) { + // Sync starts out fully enabled. + SetDefaultExpectationsForConfigPage(); + + handler_->HandleShowSetupUI(nullptr); + + // Now sync gets reset from the dashboard (the user clicked the "Manage synced + // data" link), which results in the sync-requested and first-setup-complete + // bits being cleared. + ON_CALL(*mock_sync_service_, GetDisableReasons()) + .WillByDefault(Return(syncer::SyncService::DISABLE_REASON_USER_CHOICE)); + ON_CALL(*mock_sync_service_->GetMockUserSettings(), IsSyncRequested()) + .WillByDefault(Return(false)); + ON_CALL(*mock_sync_service_->GetMockUserSettings(), IsFirstSetupComplete()) + .WillByDefault(Return(false)); + // Sync will eventually start again in transport mode. + ON_CALL(*mock_sync_service_, GetTransportState()) + .WillByDefault( + Return(syncer::SyncService::TransportState::START_DEFERRED)); + + NotifySyncStateChanged(); + + // Now the user confirms sync again. This should set both the sync-requested + // and the first-setup-complete bits. + EXPECT_CALL(*mock_sync_service_->GetMockUserSettings(), + SetSyncRequested(true)) + .WillOnce([&](bool) { + // SetSyncRequested(true) clears DISABLE_REASON_USER_CHOICE, and + // immediately starts initializing the engine. + ON_CALL(*mock_sync_service_, GetDisableReasons()) + .WillByDefault(Return(syncer::SyncService::DISABLE_REASON_NONE)); + ON_CALL(*mock_sync_service_->GetMockUserSettings(), IsSyncRequested()) + .WillByDefault(Return(true)); + ON_CALL(*mock_sync_service_, GetTransportState()) + .WillByDefault( + Return(syncer::SyncService::TransportState::INITIALIZING)); + NotifySyncStateChanged(); + }); + EXPECT_CALL(*mock_sync_service_->GetMockUserSettings(), + SetFirstSetupComplete()) + .WillOnce([&]() { + ON_CALL(*mock_sync_service_->GetMockUserSettings(), + IsFirstSetupComplete()) + .WillByDefault(Return(true)); + NotifySyncStateChanged(); + }); + + base::ListValue did_abort; + did_abort.GetList().push_back(base::Value(false)); + handler_->OnDidClosePage(&did_abort); +} + +TEST_F(PeopleHandlerTest, DashboardClearWhileSettingsOpen_ConfirmLater) { + // Sync starts out fully enabled. + SetDefaultExpectationsForConfigPage(); + + handler_->HandleShowSetupUI(nullptr); + + // Now sync gets reset from the dashboard (the user clicked the "Manage synced + // data" link), which results in the sync-requested and first-setup-complete + // bits being cleared. + ON_CALL(*mock_sync_service_, GetDisableReasons()) + .WillByDefault(Return(syncer::SyncService::DISABLE_REASON_USER_CHOICE)); + ON_CALL(*mock_sync_service_->GetMockUserSettings(), IsSyncRequested()) + .WillByDefault(Return(false)); + ON_CALL(*mock_sync_service_->GetMockUserSettings(), IsFirstSetupComplete()) + .WillByDefault(Return(false)); + // Sync will eventually start again in transport mode. + ON_CALL(*mock_sync_service_, GetTransportState()) + .WillByDefault( + Return(syncer::SyncService::TransportState::START_DEFERRED)); + + NotifySyncStateChanged(); + + // The user waits a while before doing anything, so sync starts up in + // transport mode. + ON_CALL(*mock_sync_service_, GetTransportState()) + .WillByDefault(Return(syncer::SyncService::TransportState::ACTIVE)); + // On some platforms (e.g. ChromeOS), the first-setup-complete bit gets set + // automatically during engine startup. + if (browser_defaults::kSyncAutoStarts) { + ON_CALL(*mock_sync_service_->GetMockUserSettings(), IsFirstSetupComplete()) + .WillByDefault(Return(true)); + } + NotifySyncStateChanged(); + + // Now the user confirms sync again. This should set the sync-requested bit + // and (if it wasn't automatically set above already) also the + // first-setup-complete bit. + EXPECT_CALL(*mock_sync_service_->GetMockUserSettings(), + SetSyncRequested(true)) + .WillOnce([&](bool) { + // SetSyncRequested(true) clears DISABLE_REASON_USER_CHOICE, and + // immediately starts initializing the engine. + ON_CALL(*mock_sync_service_, GetDisableReasons()) + .WillByDefault(Return(syncer::SyncService::DISABLE_REASON_NONE)); + ON_CALL(*mock_sync_service_->GetMockUserSettings(), IsSyncRequested()) + .WillByDefault(Return(true)); + ON_CALL(*mock_sync_service_, GetTransportState()) + .WillByDefault( + Return(syncer::SyncService::TransportState::INITIALIZING)); + NotifySyncStateChanged(); + }); + if (!browser_defaults::kSyncAutoStarts) { + EXPECT_CALL(*mock_sync_service_->GetMockUserSettings(), + SetFirstSetupComplete()) + .WillOnce([&]() { + ON_CALL(*mock_sync_service_->GetMockUserSettings(), + IsFirstSetupComplete()) + .WillByDefault(Return(true)); + NotifySyncStateChanged(); + }); + } + + base::ListValue did_abort; + did_abort.GetList().push_back(base::Value(false)); + handler_->OnDidClosePage(&did_abort); +} + #if BUILDFLAG(ENABLE_DICE_SUPPORT) class PeopleHandlerDiceUnifiedConsentTest : public ::testing::TestWithParam<std::tuple<bool, bool>> {};
diff --git a/chrome/browser/ui/webui/signin/inline_login_handler_impl.cc b/chrome/browser/ui/webui/signin/inline_login_handler_impl.cc index b7f731e..d1badaaf 100644 --- a/chrome/browser/ui/webui/signin/inline_login_handler_impl.cc +++ b/chrome/browser/ui/webui/signin/inline_login_handler_impl.cc
@@ -360,12 +360,6 @@ identity::IdentityManager* identity_manager = IdentityManagerFactory::GetForProfile(profile_); - // Seed the account with this combination of gaia id/display email. - AccountInfo account_info; - account_info.gaia = gaia_id_; - account_info.email = email_; - identity_manager->LegacySeedAccountInfo(account_info); - std::string primary_email = identity_manager->GetPrimaryAccountInfo().email; if (gaia::AreEmailsSame(email_, primary_email) && reason == HandlerSigninReason::UNLOCK && !password_.empty() &&
diff --git a/chrome/browser/ui/webui/translate_internals/translate_internals_handler.cc b/chrome/browser/ui/webui/translate_internals/translate_internals_handler.cc index a6b21762..9a9d1b2 100644 --- a/chrome/browser/ui/webui/translate_internals/translate_internals_handler.cc +++ b/chrome/browser/ui/webui/translate_internals/translate_internals_handler.cc
@@ -215,9 +215,9 @@ base::DictionaryValue dict; static const char* const keys[] = { + language::prefs::kFluentLanguages, prefs::kOfferTranslateEnabled, translate::TranslatePrefs::kPrefTranslateRecentTarget, - translate::TranslatePrefs::kPrefTranslateBlockedLanguages, translate::TranslatePrefs::kPrefTranslateSiteBlacklistDeprecated, translate::TranslatePrefs::kPrefTranslateSiteBlacklistWithTime, translate::TranslatePrefs::kPrefTranslateWhitelists,
diff --git a/chrome/browser/ui/webui/welcome/welcome_ui.cc b/chrome/browser/ui/webui/welcome/welcome_ui.cc index 7fb5102e2..b6abe2b 100644 --- a/chrome/browser/ui/webui/welcome/welcome_ui.cc +++ b/chrome/browser/ui/webui/welcome/welcome_ui.cc
@@ -4,7 +4,7 @@ #include "chrome/browser/ui/webui/welcome/welcome_ui.h" -#include <vector> +#include <map> #include "base/bind.h" #include "base/metrics/histogram_macros.h" @@ -39,19 +39,21 @@ #endif namespace { + const bool kIsBranded = #if defined(GOOGLE_CHROME_BUILD) true; #else false; #endif -} // namespace + +const char kPreviewBackgroundPath[] = "preview-background.jpg"; bool HandleRequestCallback( base::WeakPtr<WelcomeUI> weak_ptr, const std::string& path, const content::WebUIDataSource::GotDataCallback& callback) { - if (!base::StartsWith(path, "preview-background.jpg", + if (!base::StartsWith(path, kPreviewBackgroundPath, base::CompareCase::SENSITIVE)) { return false; } @@ -125,6 +127,21 @@ base::size(kLocalizedStrings)); } +const std::map<std::string, bool>& GetGzipMap() { + static std::map<std::string, bool>* gzip_map = nullptr; + if (!gzip_map) { + gzip_map = new std::map<std::string, bool>(); + for (size_t i = 0; i < kOnboardingWelcomeResourcesSize; ++i) { + (*gzip_map)[kOnboardingWelcomeResources[i].name] = + kOnboardingWelcomeResources[i].gzipped; + } + (*gzip_map)[kPreviewBackgroundPath] = false; + } + return *gzip_map; +} + +} // namespace + WelcomeUI::WelcomeUI(content::WebUI* web_ui, const GURL& url) : content::WebUIController(web_ui), weak_ptr_factory_(this) { Profile* profile = Profile::FromWebUI(web_ui); @@ -145,31 +162,12 @@ DarkModeHandler::Initialize(web_ui, html_source); - const bool is_nux_onboarding_enabled = nux::IsNuxOnboardingEnabled(profile); - - if (is_nux_onboarding_enabled) { - std::vector<std::string> gzipped_paths{""}; - for (size_t i = 0; i < kOnboardingWelcomeResourcesSize; ++i) { - if (kOnboardingWelcomeResources[i].gzipped) - gzipped_paths.emplace_back(kOnboardingWelcomeResources[i].name); - } - html_source->UseGzip(base::BindRepeating( - [](const std::vector<std::string>& gzipped_paths, - const std::string& path) { - return base::ContainsValue(gzipped_paths, path); - }, - std::move(gzipped_paths))); - } - - bool is_dice = - AccountConsistencyModeManager::IsDiceEnabledForProfile(profile); - // There are multiple possible configurations that affects the layout, but // first add resources that are shared across all layouts. html_source->AddResourcePath("logo.png", IDR_PRODUCT_LOGO_128); html_source->AddResourcePath("logo2x.png", IDR_PRODUCT_LOGO_256); - if (is_nux_onboarding_enabled) { + if (nux::IsNuxOnboardingEnabled(profile)) { // Add Onboarding welcome strings. AddOnboardingStrings(html_source); @@ -214,7 +212,9 @@ ->GetString()); html_source->SetRequestFilter(base::BindRepeating( &HandleRequestCallback, weak_ptr_factory_.GetWeakPtr())); - } else if (kIsBranded && is_dice) { + html_source->UseGzip(base::BindRepeating(&WelcomeUI::IsGzipped)); + } else if (kIsBranded && + AccountConsistencyModeManager::IsDiceEnabledForProfile(profile)) { // Use special layout if the application is branded and DICE is enabled. html_source->AddLocalizedString("headerText", IDS_WELCOME_HEADER); html_source->AddLocalizedString("acceptText", @@ -275,3 +275,9 @@ // Store that this profile has been shown the Welcome page. profile->GetPrefs()->SetBoolean(prefs::kHasSeenWelcomePage, true); } + +bool WelcomeUI::IsGzipped(const std::string& path) { + const std::map<std::string, bool>& gzip_map = GetGzipMap(); + const auto it = gzip_map.find(path); + return it == gzip_map.end() || it->second; +}
diff --git a/chrome/browser/ui/webui/welcome/welcome_ui.h b/chrome/browser/ui/webui/welcome/welcome_ui.h index e74a6f9..55896de 100644 --- a/chrome/browser/ui/webui/welcome/welcome_ui.h +++ b/chrome/browser/ui/webui/welcome/welcome_ui.h
@@ -28,6 +28,10 @@ size_t background_index, const content::WebUIDataSource::GotDataCallback& callback); + protected: + // Visible for testing. + static bool IsGzipped(const std::string& path); + private: void StorePageSeen(Profile* profile); std::unique_ptr<nux::NtpBackgroundFetcher> background_fetcher_;
diff --git a/chrome/browser/ui/webui/welcome/welcome_ui_unittest.cc b/chrome/browser/ui/webui/welcome/welcome_ui_unittest.cc new file mode 100644 index 0000000..dc45f0d --- /dev/null +++ b/chrome/browser/ui/webui/welcome/welcome_ui_unittest.cc
@@ -0,0 +1,27 @@ +// 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/ui/webui/welcome/welcome_ui.h" + +#include "testing/gtest/include/gtest/gtest.h" + +class TestWelcomeUI : public WelcomeUI { + public: + using WelcomeUI::IsGzipped; +}; + +TEST(WelcomeUITest, IsGzipped) { + // Default resource. + EXPECT_TRUE(TestWelcomeUI::IsGzipped("")); + EXPECT_TRUE(TestWelcomeUI::IsGzipped("welcome.html")); + EXPECT_TRUE(TestWelcomeUI::IsGzipped("new-user")); + EXPECT_TRUE(TestWelcomeUI::IsGzipped("returning-user")); + + // Images are intentionally not gzipped. + EXPECT_FALSE(TestWelcomeUI::IsGzipped("images/set_as_default_1x.png")); + + // This is a dynamic path that fetches from the network and should not be + // considered gzipped. + EXPECT_FALSE(TestWelcomeUI::IsGzipped("preview-background.jpg")); +}
diff --git a/chrome/browser/unified_consent/unified_consent_browsertest.cc b/chrome/browser/unified_consent/unified_consent_browsertest.cc index 8ab8a613..a4db0165 100644 --- a/chrome/browser/unified_consent/unified_consent_browsertest.cc +++ b/chrome/browser/unified_consent/unified_consent_browsertest.cc
@@ -6,7 +6,6 @@ #include "base/test/metrics/histogram_tester.h" #include "chrome/browser/sync/profile_sync_service_factory.h" -#include "chrome/browser/sync/profile_sync_test_util.h" #include "chrome/browser/sync/test/integration/profile_sync_service_harness.h" #include "chrome/browser/sync/test/integration/sync_test.h" #include "chrome/browser/ui/browser.h"
diff --git a/chrome/browser/web_applications/bookmark_apps/BUILD.gn b/chrome/browser/web_applications/bookmark_apps/BUILD.gn index b8cfbab..25842d9 100644 --- a/chrome/browser/web_applications/bookmark_apps/BUILD.gn +++ b/chrome/browser/web_applications/bookmark_apps/BUILD.gn
@@ -48,6 +48,7 @@ testonly = true sources = [ + "bookmark_app_install_manager_unittest.cc", "external_web_apps_unittest.cc", "policy/web_app_policy_manager_unittest.cc", "system_web_app_manager_unittest.cc",
diff --git a/chrome/browser/web_applications/bookmark_apps/bookmark_app_install_manager.cc b/chrome/browser/web_applications/bookmark_apps/bookmark_app_install_manager.cc index d95ecec..5c76fb10 100644 --- a/chrome/browser/web_applications/bookmark_apps/bookmark_app_install_manager.cc +++ b/chrome/browser/web_applications/bookmark_apps/bookmark_app_install_manager.cc
@@ -9,10 +9,12 @@ #include "base/bind.h" #include "base/callback.h" +#include "base/scoped_observer.h" #include "base/threading/thread_task_runner_handle.h" #include "chrome/browser/extensions/bookmark_app_helper.h" #include "chrome/browser/extensions/tab_helper.h" #include "chrome/browser/profiles/profile.h" +#include "chrome/browser/web_applications/components/install_manager_observer.h" #include "chrome/browser/web_applications/components/web_app_constants.h" #include "chrome/browser/web_applications/components/web_app_helpers.h" #include "chrome/common/web_application_info.h" @@ -28,36 +30,64 @@ // installations per one |web_contents|. // This class is a simple holder of BookmarkAppHelper and limits its lifetime to // match WebContents. -class InstallTask : public content::WebContentsObserver { +class InstallTask : public content::WebContentsObserver, + public web_app::InstallManagerObserver { public: - InstallTask(content::WebContents* web_contents, + InstallTask(BookmarkAppInstallManager* install_manager, std::unique_ptr<BookmarkAppHelper> bookmark_app_helper, web_app::InstallManager::OnceInstallCallback callback) - : WebContentsObserver(web_contents), + : WebContentsObserver(), bookmark_app_helper_(std::move(bookmark_app_helper)), - callback_(std::move(callback)) {} + callback_(std::move(callback)) { + manager_observer_.Add(install_manager); + } + + ~InstallTask() override { DCHECK(!callback_); } + + void AttachLifetimeTo(content::WebContents* web_contents) { + Observe(web_contents); + } // WebContentsObserver: void WebContentsDestroyed() override { - if (callback_) { - CallInstallCallback(web_app::AppId(), - web_app::InstallResultCode::kWebContentsDestroyed); - } + DCHECK(callback_); + + CallInstallCallback(web_app::AppId(), + web_app::InstallResultCode::kWebContentsDestroyed); // BookmarkAppHelper should not outsurvive |web_contents|. // This |reset| invalidates all weak references to BookmarkAppHelper and // cancels BookmarkAppHelper-related tasks posted to message loops. + // This |reset| also destroys |this| InstallTask since it is owned by the + // callback bind state. + bookmark_app_helper_.reset(); + } + + // InstallManagerObserver: + void InstallManagerReset() override { + DCHECK(callback_); + + CallInstallCallback(web_app::AppId(), + web_app::InstallResultCode::kInstallManagerDestroyed); + // BookmarkAppHelper should not outsurvive profile and its keyed services. + // This |reset| also destroys |this| InstallTask since it is owned by the + // callback bind state. bookmark_app_helper_.reset(); } void CallInstallCallback(const web_app::AppId& app_id, web_app::InstallResultCode code) { - DCHECK(callback_); - std::move(callback_).Run(app_id, code); + if (callback_) + std::move(callback_).Run(app_id, code); + + Observe(nullptr); + manager_observer_.RemoveAll(); } private: std::unique_ptr<BookmarkAppHelper> bookmark_app_helper_; web_app::InstallManager::OnceInstallCallback callback_; + ScopedObserver<web_app::InstallManager, InstallTask> manager_observer_{this}; + DISALLOW_COPY_AND_ASSIGN(InstallTask); }; @@ -84,7 +114,8 @@ } // namespace -BookmarkAppInstallManager::BookmarkAppInstallManager() = default; +BookmarkAppInstallManager::BookmarkAppInstallManager(Profile* profile) + : profile_(profile) {} BookmarkAppInstallManager::~BookmarkAppInstallManager() = default; @@ -135,9 +166,36 @@ BookmarkAppHelper* helper = bookmark_app_helper.get(); auto install_task = std::make_unique<InstallTask>( - web_contents, std::move(bookmark_app_helper), std::move(callback)); + this, std::move(bookmark_app_helper), std::move(callback)); + install_task->AttachLifetimeTo(web_contents); - // BookmarkAppHelper is owned by the bind state and will be disposed in + // InstallTask is owned by the bind state and will be disposed in + // DestroyInstallTask. + helper->Create(base::BindRepeating(OnBookmarkAppInstalled, + base::Passed(std::move(install_task)))); +} + +void BookmarkAppInstallManager::InstallWebAppFromInfo( + std::unique_ptr<WebApplicationInfo> web_application_info, + bool no_network_install, + WebappInstallSource install_source, + OnceInstallCallback callback) { + auto bookmark_app_helper = std::make_unique<BookmarkAppHelper>( + profile_, *web_application_info, /*web_contents=*/nullptr, + install_source); + + if (no_network_install) { + // We should only install windowed apps via this method. + bookmark_app_helper->set_forced_launch_type(extensions::LAUNCH_TYPE_WINDOW); + bookmark_app_helper->set_is_no_network_install(); + } + + BookmarkAppHelper* helper = bookmark_app_helper.get(); + + auto install_task = std::make_unique<InstallTask>( + this, std::move(bookmark_app_helper), std::move(callback)); + + // InstallTask is owned by the bind state and will be disposed in // DestroyInstallTask. helper->Create(base::BindRepeating(OnBookmarkAppInstalled, base::Passed(std::move(install_task))));
diff --git a/chrome/browser/web_applications/bookmark_apps/bookmark_app_install_manager.h b/chrome/browser/web_applications/bookmark_apps/bookmark_app_install_manager.h index 61651e8..d7da6f4 100644 --- a/chrome/browser/web_applications/bookmark_apps/bookmark_app_install_manager.h +++ b/chrome/browser/web_applications/bookmark_apps/bookmark_app_install_manager.h
@@ -5,16 +5,20 @@ #ifndef CHROME_BROWSER_WEB_APPLICATIONS_BOOKMARK_APPS_BOOKMARK_APP_INSTALL_MANAGER_H_ #define CHROME_BROWSER_WEB_APPLICATIONS_BOOKMARK_APPS_BOOKMARK_APP_INSTALL_MANAGER_H_ +#include <memory> + #include "base/macros.h" #include "chrome/browser/web_applications/components/install_manager.h" +class Profile; + namespace extensions { // TODO(loyso): Erase this subclass together with BookmarkAppHelper. // crbug.com/915043. class BookmarkAppInstallManager final : public web_app::InstallManager { public: - BookmarkAppInstallManager(); + explicit BookmarkAppInstallManager(Profile* profile); ~BookmarkAppInstallManager() override; // InstallManager: @@ -28,8 +32,15 @@ WebappInstallSource install_source, WebAppInstallDialogCallback dialog_callback, OnceInstallCallback callback) override; + void InstallWebAppFromInfo( + std::unique_ptr<WebApplicationInfo> web_application_info, + bool no_network_install, + WebappInstallSource install_source, + OnceInstallCallback callback) override; private: + Profile* profile_; + DISALLOW_COPY_AND_ASSIGN(BookmarkAppInstallManager); };
diff --git a/chrome/browser/web_applications/bookmark_apps/bookmark_app_install_manager_unittest.cc b/chrome/browser/web_applications/bookmark_apps/bookmark_app_install_manager_unittest.cc new file mode 100644 index 0000000..7f27258 --- /dev/null +++ b/chrome/browser/web_applications/bookmark_apps/bookmark_app_install_manager_unittest.cc
@@ -0,0 +1,126 @@ +// 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/web_applications/bookmark_apps/bookmark_app_install_manager.h" + +#include <memory> +#include <utility> + +#include "base/bind_helpers.h" +#include "base/files/file_path.h" +#include "base/run_loop.h" +#include "base/test/bind_test_util.h" +#include "chrome/browser/extensions/test_extension_system.h" +#include "chrome/browser/installable/installable_manager.h" +#include "chrome/browser/installable/installable_metrics.h" +#include "chrome/browser/ssl/security_state_tab_helper.h" +#include "chrome/browser/web_applications/components/web_app_constants.h" +#include "chrome/common/web_application_info.h" +#include "chrome/test/base/chrome_render_view_host_test_harness.h" +#include "chrome/test/base/testing_profile.h" +#include "extensions/browser/extension_file_task_runner.h" +#include "extensions/browser/extension_system.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace extensions { + +class BookmarkAppInstallManagerTest : public ChromeRenderViewHostTestHarness { + public: + void SetUp() override { + ChromeRenderViewHostTestHarness::SetUp(); + + install_manager_ = std::make_unique<BookmarkAppInstallManager>(profile()); + + extensions::TestExtensionSystem* test_extension_system = + static_cast<extensions::TestExtensionSystem*>( + extensions::ExtensionSystem::Get(profile())); + + test_extension_system->CreateExtensionService( + base::CommandLine::ForCurrentProcess(), + profile()->GetPath().Append(FILE_PATH_LITERAL("Extensions")), + /*autoupdate_enabled=*/false); + + InstallableManager::CreateForWebContents(web_contents()); + // Required by InstallableManager. + // Causes eligibility check to return NOT_FROM_SECURE_ORIGIN for GetData. + SecurityStateTabHelper::CreateForWebContents(web_contents()); + } + + void TearDown() override { + // Do not destroy profile and its scoped temp dir: ensure that + // ConvertWebAppOnFileThread finishes. + RunExtensionServiceTaskRunner(); + + ChromeRenderViewHostTestHarness::TearDown(); + } + + // Waits for a round trip between file task runner used by the profile's + // extension service and the main thread - used to ensure that all pending + // file runner task finish, + void RunExtensionServiceTaskRunner() { + base::RunLoop run_loop; + GetExtensionFileTaskRunner()->PostTaskAndReply(FROM_HERE, base::DoNothing(), + run_loop.QuitClosure()); + run_loop.Run(); + } + + protected: + std::unique_ptr<BookmarkAppInstallManager> install_manager_; +}; + +TEST_F(BookmarkAppInstallManagerTest, FromBanner_WebContentsDestroyed) { + NavigateAndCommit(GURL("https://example.com/path")); + + base::RunLoop run_loop; + bool callback_called = false; + + install_manager_->InstallWebAppFromBanner( + web_contents(), WebappInstallSource::MENU_BROWSER_TAB, base::DoNothing(), + base::BindLambdaForTesting([&](const web_app::AppId& installed_app_id, + web_app::InstallResultCode code) { + EXPECT_EQ(web_app::InstallResultCode::kWebContentsDestroyed, code); + EXPECT_EQ(web_app::AppId(), installed_app_id); + callback_called = true; + run_loop.Quit(); + })); + + // Destroy WebContents. + DeleteContents(); + EXPECT_EQ(nullptr, web_contents()); + + run_loop.Run(); + + EXPECT_TRUE(callback_called); +} + +TEST_F(BookmarkAppInstallManagerTest, FromInfo_InstallManagerDestroyed) { + const GURL url("https://example.com/path"); + NavigateAndCommit(url); + + auto web_application_info = std::make_unique<WebApplicationInfo>(); + web_application_info->app_url = url; + + base::RunLoop run_loop; + bool callback_called = false; + + install_manager_->InstallWebAppFromInfo( + std::move(web_application_info), + /*no_network_install=*/true, WebappInstallSource::ARC, + base::BindLambdaForTesting([&](const web_app::AppId& installed_app_id, + web_app::InstallResultCode code) { + EXPECT_EQ(web_app::InstallResultCode::kInstallManagerDestroyed, code); + EXPECT_EQ(web_app::AppId(), installed_app_id); + callback_called = true; + run_loop.Quit(); + })); + + // Destroy InstallManager. + install_manager_->Reset(); + run_loop.Run(); + + install_manager_.reset(); + EXPECT_TRUE(callback_called); +} + +} // namespace extensions
diff --git a/chrome/browser/web_applications/components/BUILD.gn b/chrome/browser/web_applications/components/BUILD.gn index e04a007..91e65fa 100644 --- a/chrome/browser/web_applications/components/BUILD.gn +++ b/chrome/browser/web_applications/components/BUILD.gn
@@ -6,7 +6,9 @@ sources = [ "app_registrar.h", "install_finalizer.h", + "install_manager.cc", "install_manager.h", + "install_manager_observer.h", "pending_app_manager.cc", "pending_app_manager.h", "web_app_audio_focus_id_map.cc",
diff --git a/chrome/browser/web_applications/components/install_manager.cc b/chrome/browser/web_applications/components/install_manager.cc new file mode 100644 index 0000000..266d4e1 --- /dev/null +++ b/chrome/browser/web_applications/components/install_manager.cc
@@ -0,0 +1,28 @@ +// 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/web_applications/components/install_manager.h" + +#include "chrome/browser/web_applications/components/install_manager_observer.h" + +namespace web_app { + +InstallManager::InstallManager() = default; + +InstallManager::~InstallManager() = default; + +void InstallManager::Reset() { + for (InstallManagerObserver& observer : observers_) + observer.InstallManagerReset(); +} + +void InstallManager::AddObserver(InstallManagerObserver* observer) { + observers_.AddObserver(observer); +} + +void InstallManager::RemoveObserver(InstallManagerObserver* observer) { + observers_.RemoveObserver(observer); +} + +} // namespace web_app
diff --git a/chrome/browser/web_applications/components/install_manager.h b/chrome/browser/web_applications/components/install_manager.h index 3123b9e..9fa4328e 100644 --- a/chrome/browser/web_applications/components/install_manager.h +++ b/chrome/browser/web_applications/components/install_manager.h
@@ -8,6 +8,7 @@ #include <memory> #include "base/callback_forward.h" +#include "base/observer_list.h" #include "chrome/browser/web_applications/components/web_app_helpers.h" #include "chrome/browser/web_applications/components/web_app_install_utils.h" @@ -21,6 +22,7 @@ namespace web_app { enum class InstallResultCode; +class InstallManagerObserver; // TODO(loyso): Rework this interface once BookmarkAppHelper erased. Unify the // API and merge similar InstallWebAppZZZZ functions. crbug.com/915043. @@ -63,7 +65,27 @@ WebAppInstallDialogCallback dialog_callback, OnceInstallCallback callback) = 0; - virtual ~InstallManager() = default; + // Starts a web app installation process using prefilled + // |web_application_info|. If |no_network_install| is true, then + // |web_application_info| holds all the data needed for installation and + // InstallManager should not try to fetch a manifest. + virtual void InstallWebAppFromInfo( + std::unique_ptr<WebApplicationInfo> web_application_info, + bool no_network_install, + WebappInstallSource install_source, + OnceInstallCallback callback) = 0; + + InstallManager(); + virtual ~InstallManager(); + + // Called before the web app system gets destroyed. + void Reset(); + + void AddObserver(InstallManagerObserver* observer); + void RemoveObserver(InstallManagerObserver* observer); + + private: + base::ObserverList<InstallManagerObserver, true /*check_empty*/> observers_; }; } // namespace web_app
diff --git a/chrome/browser/web_applications/components/install_manager_observer.h b/chrome/browser/web_applications/components/install_manager_observer.h new file mode 100644 index 0000000..6f7449aa --- /dev/null +++ b/chrome/browser/web_applications/components/install_manager_observer.h
@@ -0,0 +1,20 @@ +// 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_WEB_APPLICATIONS_COMPONENTS_INSTALL_MANAGER_OBSERVER_H_ +#define CHROME_BROWSER_WEB_APPLICATIONS_COMPONENTS_INSTALL_MANAGER_OBSERVER_H_ + +#include "base/observer_list_types.h" + +namespace web_app { + +class InstallManagerObserver : public base::CheckedObserver { + public: + // Called before InstallManager subsystem gets destroyed. + virtual void InstallManagerReset() = 0; +}; + +} // namespace web_app + +#endif // CHROME_BROWSER_WEB_APPLICATIONS_COMPONENTS_INSTALL_MANAGER_OBSERVER_H_
diff --git a/chrome/browser/web_applications/components/web_app_constants.h b/chrome/browser/web_applications/components/web_app_constants.h index f26dcf6c..3e9ba38 100644 --- a/chrome/browser/web_applications/components/web_app_constants.h +++ b/chrome/browser/web_applications/components/web_app_constants.h
@@ -36,7 +36,8 @@ kWebContentsDestroyed = 5, kWriteDataFailed = 6, kUserInstallDeclined = 7, - kMaxValue = kUserInstallDeclined, + kInstallManagerDestroyed = 8, + kMaxValue = kInstallManagerDestroyed, }; // Where an app was installed from. This affects what flags will be used when
diff --git a/chrome/browser/web_applications/web_app_install_manager.cc b/chrome/browser/web_applications/web_app_install_manager.cc index f5df242c..754714d5 100644 --- a/chrome/browser/web_applications/web_app_install_manager.cc +++ b/chrome/browser/web_applications/web_app_install_manager.cc
@@ -74,6 +74,15 @@ NOTIMPLEMENTED(); } +void WebAppInstallManager::InstallWebAppFromInfo( + std::unique_ptr<WebApplicationInfo> web_application_info, + bool no_network_install, + WebappInstallSource install_source, + OnceInstallCallback callback) { + // TODO(loyso): Implement it. + NOTIMPLEMENTED(); +} + void WebAppInstallManager::WebContentsDestroyed() { ReturnError(InstallResultCode::kWebContentsDestroyed); }
diff --git a/chrome/browser/web_applications/web_app_install_manager.h b/chrome/browser/web_applications/web_app_install_manager.h index 0ab47a2..5971c37 100644 --- a/chrome/browser/web_applications/web_app_install_manager.h +++ b/chrome/browser/web_applications/web_app_install_manager.h
@@ -48,6 +48,11 @@ WebappInstallSource install_source, WebAppInstallDialogCallback dialog_callback, OnceInstallCallback callback) override; + void InstallWebAppFromInfo( + std::unique_ptr<WebApplicationInfo> web_application_info, + bool no_network_install, + WebappInstallSource install_source, + OnceInstallCallback callback) override; // WebContentsObserver: void WebContentsDestroyed() override;
diff --git a/chrome/browser/web_applications/web_app_provider.cc b/chrome/browser/web_applications/web_app_provider.cc index 33efb8e..86f74cde 100644 --- a/chrome/browser/web_applications/web_app_provider.cc +++ b/chrome/browser/web_applications/web_app_provider.cc
@@ -101,7 +101,8 @@ auto bookmark_app_registrar = std::make_unique<extensions::BookmarkAppRegistrar>(profile); - install_manager_ = std::make_unique<extensions::BookmarkAppInstallManager>(); + install_manager_ = + std::make_unique<extensions::BookmarkAppInstallManager>(profile); pending_app_manager_ = std::make_unique<extensions::PendingBookmarkAppManager>( @@ -199,10 +200,10 @@ // TODO(loyso): Make it independent to the order of destruction via using two // end-to-end passes: // 1) Do Reset() for each subsystem to nullify pointers (detach subsystems). - // 2) Destroy subsystems. + install_manager_->Reset(); - // PendingAppManager is used by WebAppPolicyManager and therefore should be - // deleted after it. + // 2) Destroy subsystems. + // The order of destruction is the reverse order of creation: web_app_policy_manager_.reset(); system_web_app_manager_.reset(); pending_app_manager_.reset();
diff --git a/chrome/common/pref_names.cc b/chrome/common/pref_names.cc index 7926ebc..aa8b1cf 100644 --- a/chrome/common/pref_names.cc +++ b/chrome/common/pref_names.cc
@@ -380,8 +380,8 @@ const char kWebKitPluginsEnabled[] = "webkit.webprefs.plugins_enabled"; // Boolean that is true when Data Saver is enabled. -// TODO(bengr): Migrate the preference string to "data_saver.enabled" -// (crbug.com/564207). +// Please do not check this directly. Use +// |DataReductionProxyChromeSettings::IsDataReductionProxyEnabled()|. const char kDataSaverEnabled[] = "spdy_proxy.enabled"; // Boolean that is true when the SSL interstitial should allow users to
diff --git a/chrome/services/isolated_xr_device/xr_runtime_provider.cc b/chrome/services/isolated_xr_device/xr_runtime_provider.cc index bf35a70..a54dc90 100644 --- a/chrome/services/isolated_xr_device/xr_runtime_provider.cc +++ b/chrome/services/isolated_xr_device/xr_runtime_provider.cc
@@ -122,4 +122,10 @@ std::unique_ptr<service_manager::ServiceKeepaliveRef> service_ref) : service_ref_(std::move(service_ref)), weak_ptr_factory_(this) {} -IsolatedXRRuntimeProvider::~IsolatedXRRuntimeProvider() {} +IsolatedXRRuntimeProvider::~IsolatedXRRuntimeProvider() { +#if BUILDFLAG(ENABLE_WINDOWS_MR) + // Explicitly null out wmr_device_ to clean up any COM objects that depend + // on being RoInitialized + wmr_device_ = nullptr; +#endif +}
diff --git a/chrome/test/BUILD.gn b/chrome/test/BUILD.gn index 155c562..958ebf4 100644 --- a/chrome/test/BUILD.gn +++ b/chrome/test/BUILD.gn
@@ -3600,6 +3600,7 @@ "../browser/ui/webui/media_router/media_router_web_ui_test.cc", "../browser/ui/webui/media_router/media_router_web_ui_test.h", "../browser/ui/webui/media_router/media_router_webui_message_handler_unittest.cc", + "../browser/ui/webui/welcome/welcome_ui_unittest.cc", "../common/media_router/discovery/media_sink_internal_unittest.cc", "../common/media_router/discovery/media_sink_service_base_unittest.cc", "../common/media_router/mojo/media_router_struct_traits_unittest.cc", @@ -3660,6 +3661,7 @@ "../browser/notifications/notification_ui_manager_unittest.cc", "../browser/signin/chrome_signin_status_metrics_provider_delegate_unittest.cc", "../browser/ui/webui/settings/settings_manage_profile_handler_unittest.cc", + "../browser/ui/webui/welcome/welcome_ui_unittest.cc", # Chrome OS uses window_sizer_ash_unittest.cc "../browser/ui/window_sizer/window_sizer_unittest.cc",
diff --git a/chrome/test/data/arc_graphics_tracing/gm_bad_no_view_buffers.json b/chrome/test/data/arc_graphics_tracing/gm_bad_no_view_buffers.json index e640665c..87e96cb2 100644 --- a/chrome/test/data/arc_graphics_tracing/gm_bad_no_view_buffers.json +++ b/chrome/test/data/arc_graphics_tracing/gm_bad_no_view_buffers.json
@@ -1,6 +1,6 @@ { "android": [ [ 400, 54134.0 ], [ 401, 65796.0 ] ], - "chrome": [ [ 500, 1667.0 ], [ 501, 1808.0 ] ], + "chrome": [ [ [ 500, 1667.0 ], [ 501, 1808.0 ] ] ], "duration": 1053800.0, "views": [ { "activity": "com.android.vending/com.android.vending.AssetBrowserActivity",
diff --git a/chrome/test/data/arc_graphics_tracing/gm_bad_no_view_desc.json b/chrome/test/data/arc_graphics_tracing/gm_bad_no_view_desc.json index 7eaf7fe..a046ed1c 100644 --- a/chrome/test/data/arc_graphics_tracing/gm_bad_no_view_desc.json +++ b/chrome/test/data/arc_graphics_tracing/gm_bad_no_view_desc.json
@@ -1,6 +1,6 @@ { "android": [ [ 400, 54134.0 ], [ 401, 65796.0 ] ], - "chrome": [ [ 500, 1667.0 ], [ 501, 1808.0 ] ], + "chrome": [ [ [ 500, 1667.0 ], [ 501, 1808.0 ] ] ], "duration": 1053800.0, "views": [ { "buffers": [ [ [ 200, 0.0 ], [ 201, 149.0 ] ], [ [ 300, 168.0 ], [ 202, 173.0 ] ] ],
diff --git a/chrome/test/data/arc_graphics_tracing/gm_bad_wrong_timestamp.json b/chrome/test/data/arc_graphics_tracing/gm_bad_wrong_timestamp.json index fe4f0c9b..de1a7e4 100644 --- a/chrome/test/data/arc_graphics_tracing/gm_bad_wrong_timestamp.json +++ b/chrome/test/data/arc_graphics_tracing/gm_bad_wrong_timestamp.json
@@ -1,6 +1,6 @@ { "android": [ [ 400, 65796.0 ], [ 401, 54134.0 ] ], - "chrome": [ [ 500, 1667.0 ], [ 501, 1808.0 ] ], + "chrome": [ [ [ 500, 1667.0 ], [ 501, 1808.0 ] ] ], "duration": 1053800.0, "views": [ { "activity": "com.android.vending/com.android.vending.AssetBrowserActivity",
diff --git a/chrome/test/data/arc_graphics_tracing/gm_good.json b/chrome/test/data/arc_graphics_tracing/gm_good.json index 8ef5538..4b3b070 100644 --- a/chrome/test/data/arc_graphics_tracing/gm_good.json +++ b/chrome/test/data/arc_graphics_tracing/gm_good.json
@@ -1,6 +1,6 @@ { "android": [ [ 400, 54134.0 ], [ 401, 65796.0 ] ], - "chrome": [ [ 500, 1667.0 ], [ 501, 1808.0 ] ], + "chrome": [ [ [ 500, 1667.0 ], [ 501, 1808.0 ] ] ], "duration": 1053800.0, "views": [ { "activity": "com.android.vending/com.android.vending.AssetBrowserActivity",
diff --git a/chrome/test/data/extensions/context_menus/checkboxes/test.js b/chrome/test/data/extensions/context_menus/checkboxes/test.js index 4d626fa..1d8202a 100644 --- a/chrome/test/data/extensions/context_menus/checkboxes/test.js +++ b/chrome/test/data/extensions/context_menus/checkboxes/test.js
@@ -2,15 +2,13 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -window.onload = function() { - createFirstCheckbox() - .then(createSecondCheckbox) - .then(checkSecondCheckbox) - .then(createNormalMenuItem) - .then(function() { - chrome.test.sendMessage('Menu created'); - }); -}; +createFirstCheckbox() + .then(createSecondCheckbox) + .then(checkSecondCheckbox) + .then(createNormalMenuItem) + .then(function() { + chrome.test.sendMessage('Menu created'); + }); function createFirstCheckbox() { return new Promise(function(resolve, reject) {
diff --git a/chrome/test/data/extensions/context_menus/enabled/background.html b/chrome/test/data/extensions/context_menus/enabled/background.html deleted file mode 100644 index 78a21b8..0000000 --- a/chrome/test/data/extensions/context_menus/enabled/background.html +++ /dev/null
@@ -1,6 +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. ---> -<script src="test.js"></script>
diff --git a/chrome/test/data/extensions/context_menus/enabled/manifest.json b/chrome/test/data/extensions/context_menus/enabled/manifest.json index d6b3457d..e81ecfff 100644 --- a/chrome/test/data/extensions/context_menus/enabled/manifest.json +++ b/chrome/test/data/extensions/context_menus/enabled/manifest.json
@@ -3,7 +3,5 @@ "version" : "0.1", "manifest_version": 2, "permissions": [ "contextMenus", "tabs" ], - "background": { - "page": "background.html" - } + "background": { "scripts": ["test.js"] } }
diff --git a/chrome/test/data/extensions/context_menus/frames/background.html b/chrome/test/data/extensions/context_menus/frames/background.html deleted file mode 100644 index 46f4d74c..0000000 --- a/chrome/test/data/extensions/context_menus/frames/background.html +++ /dev/null
@@ -1 +0,0 @@ -<script src="test.js"></script>
diff --git a/chrome/test/data/extensions/context_menus/frames/manifest.json b/chrome/test/data/extensions/context_menus/frames/manifest.json index d6b3457d..e81ecfff 100644 --- a/chrome/test/data/extensions/context_menus/frames/manifest.json +++ b/chrome/test/data/extensions/context_menus/frames/manifest.json
@@ -3,7 +3,5 @@ "version" : "0.1", "manifest_version": 2, "permissions": [ "contextMenus", "tabs" ], - "background": { - "page": "background.html" - } + "background": { "scripts": ["test.js"] } }
diff --git a/chrome/test/data/extensions/context_menus/frames/test.js b/chrome/test/data/extensions/context_menus/frames/test.js index f6d9872b..7f17563 100644 --- a/chrome/test/data/extensions/context_menus/frames/test.js +++ b/chrome/test/data/extensions/context_menus/frames/test.js
@@ -2,23 +2,22 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -window.onload = function() { - function onclick(info, tab) { - chrome.test.sendMessage('pageUrl=' + info.pageUrl + - ', frameUrl=' + info.frameUrl + - ', frameId=' + info.frameId); - } - chrome.contextMenus.create( - {'title':'Page item', contexts: ['page'], id: 'item1', onclick: onclick}, - function() { - if (!chrome.runtime.lastError) { - chrome.contextMenus.create( - {"title":"Frame item", contexts: ["frame"]}, - function() { - if (!chrome.runtime.lastError) { - chrome.test.sendMessage("created items"); - } - }); - } - }); -}; +function onclick(info, tab) { + chrome.test.sendMessage('pageUrl=' + info.pageUrl + + ', frameUrl=' + info.frameUrl + + ', frameId=' + info.frameId); +} + +chrome.contextMenus.create( + {'title':'Page item', contexts: ['page'], id: 'item1', onclick: onclick}, + function() { + if (!chrome.runtime.lastError) { + chrome.contextMenus.create( + {"title":"Frame item", contexts: ["frame"]}, + function() { + if (!chrome.runtime.lastError) { + chrome.test.sendMessage("created items"); + } + }); + } + });
diff --git a/chrome/test/data/extensions/context_menus/incognito/background.html b/chrome/test/data/extensions/context_menus/incognito/background.html deleted file mode 100644 index 46f4d74c..0000000 --- a/chrome/test/data/extensions/context_menus/incognito/background.html +++ /dev/null
@@ -1 +0,0 @@ -<script src="test.js"></script>
diff --git a/chrome/test/data/extensions/context_menus/incognito/manifest.json b/chrome/test/data/extensions/context_menus/incognito/manifest.json index 5d96533..a387c8c 100644 --- a/chrome/test/data/extensions/context_menus/incognito/manifest.json +++ b/chrome/test/data/extensions/context_menus/incognito/manifest.json
@@ -4,7 +4,5 @@ "manifest_version": 2, "permissions": ["contextMenus"], "incognito": "split", - "background": { - "page": "background.html" - } + "background": { "scripts": ["test.js"] } }
diff --git a/chrome/test/data/extensions/context_menus/incognito/test.js b/chrome/test/data/extensions/context_menus/incognito/test.js index 4995774..b7e7898 100644 --- a/chrome/test/data/extensions/context_menus/incognito/test.js +++ b/chrome/test/data/extensions/context_menus/incognito/test.js
@@ -9,11 +9,9 @@ chrome.test.sendMessage("onclick fired " + incognitoStr); } -window.onload = function() { - chrome.contextMenus.create({title: "item " + incognitoStr, - onclick: onclick}, function() { - if (!chrome.runtime.lastError) { - chrome.test.sendMessage("created item " + incognitoStr); - } - }); -}; +chrome.contextMenus.create({title: "item " + incognitoStr, + onclick: onclick}, function() { + if (!chrome.runtime.lastError) { + chrome.test.sendMessage("created item " + incognitoStr); + } +});
diff --git a/chrome/test/data/extensions/context_menus/long_title/background.html b/chrome/test/data/extensions/context_menus/long_title/background.html deleted file mode 100644 index 46f4d74c..0000000 --- a/chrome/test/data/extensions/context_menus/long_title/background.html +++ /dev/null
@@ -1 +0,0 @@ -<script src="test.js"></script>
diff --git a/chrome/test/data/extensions/context_menus/long_title/manifest.json b/chrome/test/data/extensions/context_menus/long_title/manifest.json index d6b3457d..e81ecfff 100644 --- a/chrome/test/data/extensions/context_menus/long_title/manifest.json +++ b/chrome/test/data/extensions/context_menus/long_title/manifest.json
@@ -3,7 +3,5 @@ "version" : "0.1", "manifest_version": 2, "permissions": [ "contextMenus", "tabs" ], - "background": { - "page": "background.html" - } + "background": { "scripts": ["test.js"] } }
diff --git a/chrome/test/data/extensions/context_menus/long_title/test.js b/chrome/test/data/extensions/context_menus/long_title/test.js index e6b0ad5a..67b8534 100644 --- a/chrome/test/data/extensions/context_menus/long_title/test.js +++ b/chrome/test/data/extensions/context_menus/long_title/test.js
@@ -2,16 +2,14 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -window.onload = function() { - // Make a 1000-character long title. - var title = ""; - for (var i = 0; i < 1000; i++) { - title += "x"; +// Make a 1000-character long title. +var title = ""; +for (var i = 0; i < 1000; i++) { + title += "x"; +} +chrome.test.log("creating item"); +chrome.contextMenus.create({"title":title}, function() { + if (!chrome.runtime.lastError) { + chrome.test.sendMessage("created"); } - chrome.test.log("creating item"); - chrome.contextMenus.create({"title":title}, function() { - if (!chrome.runtime.lastError) { - chrome.test.sendMessage("created"); - } - }); -}; +});
diff --git a/chrome/test/data/extensions/context_menus/onclick_null/test.js b/chrome/test/data/extensions/context_menus/onclick_null/test.js index 06d173f..cfdf858 100644 --- a/chrome/test/data/extensions/context_menus/onclick_null/test.js +++ b/chrome/test/data/extensions/context_menus/onclick_null/test.js
@@ -2,15 +2,13 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -window.onload = function() { - chrome.contextMenus.create({ - id: 'id1', - title: 'Menu item 1', - onclick: function() { - chrome.test.sendMessage('onclick1-unexpected'); - } - }, onCreatedFirstMenu); -}; +chrome.contextMenus.create({ + id: 'id1', + title: 'Menu item 1', + onclick: function() { + chrome.test.sendMessage('onclick1-unexpected'); + } +}, onCreatedFirstMenu); function onCreatedFirstMenu() { chrome.contextMenus.update('id1', {
diff --git a/chrome/test/data/extensions/context_menus/patterns/background.html b/chrome/test/data/extensions/context_menus/patterns/background.html deleted file mode 100644 index 46f4d74c..0000000 --- a/chrome/test/data/extensions/context_menus/patterns/background.html +++ /dev/null
@@ -1 +0,0 @@ -<script src="test.js"></script>
diff --git a/chrome/test/data/extensions/context_menus/patterns/manifest.json b/chrome/test/data/extensions/context_menus/patterns/manifest.json index fdcce9b..92b4b2de 100644 --- a/chrome/test/data/extensions/context_menus/patterns/manifest.json +++ b/chrome/test/data/extensions/context_menus/patterns/manifest.json
@@ -3,7 +3,5 @@ "version": "0.1", "manifest_version": 2, "permissions": ["contextMenus", "tabs"], - "background": { - "page": "background.html" - } + "background": { "scripts": ["test.js"] } }
diff --git a/chrome/test/data/extensions/context_menus/patterns/test.html b/chrome/test/data/extensions/context_menus/patterns/test.html deleted file mode 100644 index 5c11777..0000000 --- a/chrome/test/data/extensions/context_menus/patterns/test.html +++ /dev/null
@@ -1,5 +0,0 @@ -<html> -<body> -test -</body> -</html>
diff --git a/chrome/test/data/extensions/context_menus/patterns/test.js b/chrome/test/data/extensions/context_menus/patterns/test.js index 37c8bf6..e3c9903 100644 --- a/chrome/test/data/extensions/context_menus/patterns/test.js +++ b/chrome/test/data/extensions/context_menus/patterns/test.js
@@ -10,22 +10,18 @@ var patterns = ["http://*.google.com/*", "https://*.google.com/*"]; -window.onload = function() { - // Create one item that does have a documentUrlPattern. - var properties1 = { - "title": "test_item1", "documentUrlPatterns": patterns - }; - chrome.contextMenus.create(properties1); - - // Create an item that initially doesn't have a documentUrlPattern, then - // update it, and then proceed with the c++ code in the browser test. - var properties2 = { "title": "test_item2" }; - - var id2; - id2 = chrome.contextMenus.create(properties2, - function() { - var update_properties = { "documentUrlPatterns": patterns }; - chrome.contextMenus.update(id2, update_properties, - make_browsertest_proceed); - }); +// Create one item that does have a documentUrlPattern. +var properties1 = { + "title": "test_item1", "documentUrlPatterns": patterns }; +chrome.contextMenus.create(properties1); + +// Create an item that initially doesn't have a documentUrlPattern, then +// update it, and then proceed with the c++ code in the browser test. +var properties2 = { "title": "test_item2" }; + +var id2 = chrome.contextMenus.create(properties2, function() { + var update_properties = { "documentUrlPatterns": patterns }; + chrome.contextMenus.update(id2, update_properties, + make_browsertest_proceed); +});
diff --git a/chrome/test/data/extensions/context_menus/radio_check/test.js b/chrome/test/data/extensions/context_menus/radio_check/test.js index 3355959..c160050 100644 --- a/chrome/test/data/extensions/context_menus/radio_check/test.js +++ b/chrome/test/data/extensions/context_menus/radio_check/test.js
@@ -2,20 +2,18 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -window.onload = function() { - chrome.contextMenus.create({ - id: 'radio1', - type: 'radio', - title: 'Radio 1', - onclick: function() { - chrome.test.sendMessage('onclick radio1'); - } - }, function() { - chrome.test.sendMessage('created radio1 item', function() { - createSecondRadioButton(); - }); +chrome.contextMenus.create({ + id: 'radio1', + type: 'radio', + title: 'Radio 1', + onclick: function() { + chrome.test.sendMessage('onclick radio1'); + } +}, function() { + chrome.test.sendMessage('created radio1 item', function() { + createSecondRadioButton(); }); -}; +}); function createSecondRadioButton() { chrome.contextMenus.create({
diff --git a/chrome/test/data/extensions/context_menus/simple/background.html b/chrome/test/data/extensions/context_menus/simple/background.html deleted file mode 100644 index 46f4d74c..0000000 --- a/chrome/test/data/extensions/context_menus/simple/background.html +++ /dev/null
@@ -1 +0,0 @@ -<script src="test.js"></script>
diff --git a/chrome/test/data/extensions/context_menus/simple/manifest.json b/chrome/test/data/extensions/context_menus/simple/manifest.json index d6b3457d..e81ecfff 100644 --- a/chrome/test/data/extensions/context_menus/simple/manifest.json +++ b/chrome/test/data/extensions/context_menus/simple/manifest.json
@@ -3,7 +3,5 @@ "version" : "0.1", "manifest_version": 2, "permissions": [ "contextMenus", "tabs" ], - "background": { - "page": "background.html" - } + "background": { "scripts": ["test.js"] } }
diff --git a/chrome/test/data/extensions/context_menus/simple/test.js b/chrome/test/data/extensions/context_menus/simple/test.js index 75011dd..4c96715510 100644 --- a/chrome/test/data/extensions/context_menus/simple/test.js +++ b/chrome/test/data/extensions/context_menus/simple/test.js
@@ -6,11 +6,9 @@ chrome.test.sendMessage("onclick fired"); } -window.onload = function() { - chrome.contextMenus.create({"title":"Extension Item 1", - "onclick": onclick}, function() { - if (!chrome.runtime.lastError) { - chrome.test.sendMessage("created item"); - } - }); -}; +chrome.contextMenus.create({"title":"Extension Item 1", + "onclick": onclick}, function() { + if (!chrome.runtime.lastError) { + chrome.test.sendMessage("created item"); + } +});
diff --git a/chrome/test/data/extensions/context_menus/target_urls/background.html b/chrome/test/data/extensions/context_menus/target_urls/background.html deleted file mode 100644 index 46f4d74c..0000000 --- a/chrome/test/data/extensions/context_menus/target_urls/background.html +++ /dev/null
@@ -1 +0,0 @@ -<script src="test.js"></script>
diff --git a/chrome/test/data/extensions/context_menus/target_urls/manifest.json b/chrome/test/data/extensions/context_menus/target_urls/manifest.json index 00296eb..55b02f2 100644 --- a/chrome/test/data/extensions/context_menus/target_urls/manifest.json +++ b/chrome/test/data/extensions/context_menus/target_urls/manifest.json
@@ -3,7 +3,5 @@ "version" : "0.1", "manifest_version": 2, "permissions": [ "contextMenus", "tabs" ], - "background": { - "page": "background.html" - } + "background": { "scripts": ["test.js"] } }
diff --git a/chrome/test/data/extensions/context_menus/target_urls/test.js b/chrome/test/data/extensions/context_menus/target_urls/test.js index cad65fa..1381989 100644 --- a/chrome/test/data/extensions/context_menus/target_urls/test.js +++ b/chrome/test/data/extensions/context_menus/target_urls/test.js
@@ -2,12 +2,11 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -window.onload = function() { - var patterns = [ "http://*.google.com/*" ]; - chrome.contextMenus.create({"title":"item1", "contexts": ["link"], - "targetUrlPatterns": patterns}, function() { - if (!chrome.runtime.lastError) { - chrome.test.sendMessage("created items"); - } - }); -}; +var patterns = [ "http://*.google.com/*" ]; + +chrome.contextMenus.create({"title":"item1", "contexts": ["link"], + "targetUrlPatterns": patterns}, function() { + if (!chrome.runtime.lastError) { + chrome.test.sendMessage("created items"); + } +});
diff --git a/chrome/test/data/extensions/context_menus/top_level/multi4/background.js b/chrome/test/data/extensions/context_menus/top_level/multi4/background.js index b472551..65bf7a5 100644 --- a/chrome/test/data/extensions/context_menus/top_level/multi4/background.js +++ b/chrome/test/data/extensions/context_menus/top_level/multi4/background.js
@@ -2,14 +2,12 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -window.onload = function() { - chrome.contextMenus.create({ "title": "Context Menu #1" }, function() { - if (!chrome.runtime.lastError) { - chrome.contextMenus.create({ "title": "Context Menu #2" }, function() { - if (!chrome.runtime.lastError) { - chrome.test.sendMessage("created items"); - } - }); - } - }); -}; +chrome.contextMenus.create({ "title": "Context Menu #1" }, function() { + if (!chrome.runtime.lastError) { + chrome.contextMenus.create({ "title": "Context Menu #2" }, function() { + if (!chrome.runtime.lastError) { + chrome.test.sendMessage("created items"); + } + }); + } +});
diff --git a/chrome/test/data/extensions/context_menus/top_level/multi5/background.js b/chrome/test/data/extensions/context_menus/top_level/multi5/background.js index b472551..65bf7a5 100644 --- a/chrome/test/data/extensions/context_menus/top_level/multi5/background.js +++ b/chrome/test/data/extensions/context_menus/top_level/multi5/background.js
@@ -2,14 +2,12 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -window.onload = function() { - chrome.contextMenus.create({ "title": "Context Menu #1" }, function() { - if (!chrome.runtime.lastError) { - chrome.contextMenus.create({ "title": "Context Menu #2" }, function() { - if (!chrome.runtime.lastError) { - chrome.test.sendMessage("created items"); - } - }); - } - }); -}; +chrome.contextMenus.create({ "title": "Context Menu #1" }, function() { + if (!chrome.runtime.lastError) { + chrome.contextMenus.create({ "title": "Context Menu #2" }, function() { + if (!chrome.runtime.lastError) { + chrome.test.sendMessage("created items"); + } + }); + } +});
diff --git a/chrome/test/data/extensions/context_menus/top_level/single1/background.js b/chrome/test/data/extensions/context_menus/top_level/single1/background.js index 5a2f68a..0249e67 100644 --- a/chrome/test/data/extensions/context_menus/top_level/single1/background.js +++ b/chrome/test/data/extensions/context_menus/top_level/single1/background.js
@@ -4,10 +4,8 @@ var contextMenuTitle = "Context Menu #3 - Extension #1"; -window.onload = function() { - chrome.contextMenus.create({ "title": contextMenuTitle }, function() { - if (!chrome.runtime.lastError) { - chrome.test.sendMessage("created item"); - } - }); -}; +chrome.contextMenus.create({ "title": contextMenuTitle }, function() { + if (!chrome.runtime.lastError) { + chrome.test.sendMessage("created item"); + } +});
diff --git a/chrome/test/data/extensions/context_menus/top_level/single2/background.js b/chrome/test/data/extensions/context_menus/top_level/single2/background.js index a712836..6a84326 100644 --- a/chrome/test/data/extensions/context_menus/top_level/single2/background.js +++ b/chrome/test/data/extensions/context_menus/top_level/single2/background.js
@@ -4,10 +4,8 @@ var contextMenuTitle = "Context Menu #1 - Extension #2"; -window.onload = function() { - chrome.contextMenus.create({ "title": contextMenuTitle }, function() { - if (!chrome.runtime.lastError) { - chrome.test.sendMessage("created item"); - } - }); -}; +chrome.contextMenus.create({ "title": contextMenuTitle }, function() { + if (!chrome.runtime.lastError) { + chrome.test.sendMessage("created item"); + } +});
diff --git a/chrome/test/data/extensions/context_menus/top_level/single3/background.js b/chrome/test/data/extensions/context_menus/top_level/single3/background.js index 4e7de66..e2a8929 100644 --- a/chrome/test/data/extensions/context_menus/top_level/single3/background.js +++ b/chrome/test/data/extensions/context_menus/top_level/single3/background.js
@@ -4,10 +4,8 @@ var contextMenuTitle = "Context Menu #2 - Extension #3"; -window.onload = function() { - chrome.contextMenus.create({ "title": contextMenuTitle }, function() { - if (!chrome.runtime.lastError) { - chrome.test.sendMessage("created item"); - } - }); -}; +chrome.contextMenus.create({ "title": contextMenuTitle }, function() { + if (!chrome.runtime.lastError) { + chrome.test.sendMessage("created item"); + } +});
diff --git a/chrome/test/data/webui/print_preview/model_settings_availability_test.js b/chrome/test/data/webui/print_preview/model_settings_availability_test.js index 76fc0f86..af9fe32e 100644 --- a/chrome/test/data/webui/print_preview/model_settings_availability_test.js +++ b/chrome/test/data/webui/print_preview/model_settings_availability_test.js
@@ -511,6 +511,26 @@ model.set('destination.capabilities', capabilities); assertFalse(model.settings.pin.available); }); + + test('pinValue', function() { + assertTrue(model.settings.pinValue.available); + + // Remove pin capability. + let capabilities = + print_preview_test_utils.getCddTemplate(model.destination.id) + .capabilities; + delete capabilities.printer.pin; + model.set('destination.capabilities', capabilities); + assertFalse(model.settings.pinValue.available); + + // Set not supported pin capability. + capabilities = + print_preview_test_utils.getCddTemplate(model.destination.id) + .capabilities; + capabilities.printer.pin.supported = false; + model.set('destination.capabilities', capabilities); + assertFalse(model.settings.pinValue.available); + }); } }); });
diff --git a/chrome/test/data/webui/print_preview/model_test.js b/chrome/test/data/webui/print_preview/model_test.js index 6efc19c7..55b6f2d3 100644 --- a/chrome/test/data/webui/print_preview/model_test.js +++ b/chrome/test/data/webui/print_preview/model_test.js
@@ -46,6 +46,10 @@ isColorEnabled: true, vendorOptions: {}, }; + if (cr.isChromeOS) { + stickySettingsDefault.isPinEnabled = false; + stickySettingsDefault.pinValue = ''; + } // Non-default state const stickySettingsChange = { @@ -68,6 +72,10 @@ printArea: 6, }, }; + if (cr.isChromeOS) { + stickySettingsChange.isPinEnabled = true; + stickySettingsChange.pinValue = '0000'; + } /** * @param {string} setting The name of the setting to check. @@ -101,23 +109,30 @@ }; model.applyStickySettings(); - return testStickySetting('collate', 'isCollateEnabled') - .then(() => testStickySetting('color', 'isColorEnabled')) - .then( - () => - testStickySetting('cssBackground', 'isCssBackgroundEnabled')) - .then(() => testStickySetting('dpi', 'dpi')) - .then(() => testStickySetting('duplex', 'isDuplexEnabled')) - .then(() => testStickySetting('fitToPage', 'isFitToPageEnabled')) - .then( - () => testStickySetting('headerFooter', 'isHeaderFooterEnabled')) - .then(() => testStickySetting('layout', 'isLandscapeEnabled')) - .then(() => testStickySetting('margins', 'marginsType')) - .then(() => testStickySetting('mediaSize', 'mediaSize')) - .then(() => testStickySetting('customScaling', 'customScaling')) - .then(() => testStickySetting('scaling', 'scaling')) - .then(() => testStickySetting('fitToPage', 'isFitToPageEnabled')) - .then(() => testStickySetting('vendorItems', 'vendorOptions')); + let promise = + testStickySetting('collate', 'isCollateEnabled') + .then(() => testStickySetting('color', 'isColorEnabled')) + .then( + () => testStickySetting( + 'cssBackground', 'isCssBackgroundEnabled')) + .then(() => testStickySetting('dpi', 'dpi')) + .then(() => testStickySetting('duplex', 'isDuplexEnabled')) + .then(() => testStickySetting('fitToPage', 'isFitToPageEnabled')) + .then( + () => testStickySetting( + 'headerFooter', 'isHeaderFooterEnabled')) + .then(() => testStickySetting('layout', 'isLandscapeEnabled')) + .then(() => testStickySetting('margins', 'marginsType')) + .then(() => testStickySetting('mediaSize', 'mediaSize')) + .then(() => testStickySetting('customScaling', 'customScaling')) + .then(() => testStickySetting('scaling', 'scaling')) + .then(() => testStickySetting('fitToPage', 'isFitToPageEnabled')) + .then(() => testStickySetting('vendorItems', 'vendorOptions')); + if (cr.isChromeOS) { + promise = promise.then(() => testStickySetting('pin', 'isPinEnabled')) + .then(() => testStickySetting('pinValue', 'pinValue')); + } + return promise; }); /** @@ -186,6 +201,10 @@ }, ranges: [{from: 2, to: 2}], }; + if (cr.isChromeOS) { + settingsChange.pin = true; + settingsChange.pinValue = '0000'; + } // Update settings Object.keys(settingsChange).forEach(setting => { @@ -230,11 +249,16 @@ print_preview_test_utils.getCddTemplateWithAdvancedSettings(2) .capabilities; + if (cr.isChromeOS) { + // Make device managed. It's used for testing pin setting behavior. + loadTimeData.overrideValues({isEnterpriseManaged: true}); + } initializeModel(); model.destination = testDestination; const defaultTicket = model.createPrintTicket(testDestination, false, false); - const expectedDefaultTicket = JSON.stringify({ + + const expectedDefaultTicketObject = { mediaSize: testDestination.capabilities.printer.media_size.option[0], pageCount: 3, landscape: false, @@ -263,13 +287,13 @@ pageWidth: 612, pageHeight: 792, showSystemDialog: false, - }); - expectEquals(expectedDefaultTicket, defaultTicket); + }; + expectEquals(JSON.stringify(expectedDefaultTicketObject), defaultTicket); // Toggle all the values and create a new print ticket. toggleSettings(testDestination); const newTicket = model.createPrintTicket(testDestination, false, false); - const expectedNewTicket = JSON.stringify({ + const expectedNewTicketObject = { mediaSize: testDestination.capabilities.printer.media_size.option[1], pageCount: 1, landscape: true, @@ -304,8 +328,12 @@ marginBottom: 300, marginLeft: 400, }, - }); - expectEquals(expectedNewTicket, newTicket); + }; + if (cr.isChromeOS) { + expectedNewTicketObject.pinValue = '0000'; + } + + expectEquals(JSON.stringify(expectedNewTicketObject), newTicket); }); /**
diff --git a/chromeos/attestation/attestation_flow.cc b/chromeos/attestation/attestation_flow.cc index 9c19421a..ffe6cfe 100644 --- a/chromeos/attestation/attestation_flow.cc +++ b/chromeos/attestation/attestation_flow.cc
@@ -14,7 +14,7 @@ #include "base/timer/timer.h" #include "chromeos/cryptohome/async_method_caller.h" #include "chromeos/cryptohome/cryptohome_parameters.h" -#include "chromeos/dbus/cryptohome_client.h" +#include "chromeos/dbus/cryptohome/cryptohome_client.h" #include "components/account_id/account_id.h" namespace chromeos {
diff --git a/chromeos/attestation/attestation_flow.h b/chromeos/attestation/attestation_flow.h index 5faaf21..9f05711e 100644 --- a/chromeos/attestation/attestation_flow.h +++ b/chromeos/attestation/attestation_flow.h
@@ -14,7 +14,7 @@ #include "base/memory/weak_ptr.h" #include "base/time/time.h" #include "base/timer/timer.h" -#include "chromeos/dbus/attestation_constants.h" +#include "chromeos/dbus/constants/attestation_constants.h" #include "chromeos/dbus/dbus_method_call_status.h" #include "third_party/cros_system_api/dbus/service_constants.h"
diff --git a/chromeos/attestation/attestation_flow_unittest.cc b/chromeos/attestation/attestation_flow_unittest.cc index 18a45d9..861caa5 100644 --- a/chromeos/attestation/attestation_flow_unittest.cc +++ b/chromeos/attestation/attestation_flow_unittest.cc
@@ -15,7 +15,7 @@ #include "chromeos/attestation/mock_attestation_flow.h" #include "chromeos/cryptohome/cryptohome_parameters.h" #include "chromeos/cryptohome/mock_async_method_caller.h" -#include "chromeos/dbus/fake_cryptohome_client.h" +#include "chromeos/dbus/cryptohome/fake_cryptohome_client.h" #include "components/account_id/account_id.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h"
diff --git a/chromeos/components/multidevice/debug_webui/proximity_auth_webui_handler.cc b/chromeos/components/multidevice/debug_webui/proximity_auth_webui_handler.cc index cdf2032..0c92c71 100644 --- a/chromeos/components/multidevice/debug_webui/proximity_auth_webui_handler.cc +++ b/chromeos/components/multidevice/debug_webui/proximity_auth_webui_handler.cc
@@ -79,6 +79,7 @@ const char kExternalDevicePublicKey[] = "publicKey"; const char kExternalDevicePublicKeyTruncated[] = "publicKeyTruncated"; const char kExternalDeviceFriendlyName[] = "friendlyDeviceName"; +const char kExternalDeviceNoPiiName[] = "noPiiName"; const char kExternalDeviceUnlockKey[] = "unlockKey"; const char kExternalDeviceMobileHotspot[] = "hasMobileHotspot"; const char kExternalDeviceConnectionStatus[] = "connectionStatus"; @@ -376,6 +377,8 @@ dictionary->SetString(kExternalDevicePublicKeyTruncated, remote_device.GetTruncatedDeviceIdForLogs()); dictionary->SetString(kExternalDeviceFriendlyName, remote_device.name()); + dictionary->SetString(kExternalDeviceNoPiiName, + remote_device.pii_free_name()); dictionary->SetBoolean(kExternalDeviceUnlockKey, remote_device.GetSoftwareFeatureState( multidevice::SoftwareFeature::kSmartLockHost) ==
diff --git a/chromeos/components/multidevice/debug_webui/resources/proximity_auth.html b/chromeos/components/multidevice/debug_webui/resources/proximity_auth.html index 5765d808..a70c02e 100644 --- a/chromeos/components/multidevice/debug_webui/resources/proximity_auth.html +++ b/chromeos/components/multidevice/debug_webui/resources/proximity_auth.html
@@ -129,6 +129,10 @@ <td class='device-id'></td> </tr> <tr> + <td>PII-Free Name</td> + <td class='no-pii-name'></td> + </tr> + <tr> <td>Supported/Enabled Features</td> <td class='software-features'></td> </tr>
diff --git a/chromeos/components/multidevice/debug_webui/resources/proximity_auth.js b/chromeos/components/multidevice/debug_webui/resources/proximity_auth.js index c935a38..998bf53a 100644 --- a/chromeos/components/multidevice/debug_webui/resources/proximity_auth.js +++ b/chromeos/components/multidevice/debug_webui/resources/proximity_auth.js
@@ -242,6 +242,8 @@ 'state', remoteDevice['connectionStatus']); t.querySelector('.device-name').textContent = remoteDevice['friendlyDeviceName']; + t.querySelector('.no-pii-name').textContent = + remoteDevice['noPiiName']; t.querySelector('.device-id').textContent = remoteDevice['publicKeyTruncated']; t.querySelector('.software-features').textContent =
diff --git a/chromeos/components/multidevice/mojom/multidevice_mojom_traits.cc b/chromeos/components/multidevice/mojom/multidevice_mojom_traits.cc index dcfc8da..c0e31b8f 100644 --- a/chromeos/components/multidevice/mojom/multidevice_mojom_traits.cc +++ b/chromeos/components/multidevice/mojom/multidevice_mojom_traits.cc
@@ -71,6 +71,14 @@ const std::string& StructTraits<chromeos::multidevice::mojom::RemoteDeviceDataView, chromeos::multidevice::RemoteDevice>:: + pii_free_device_name( + const chromeos::multidevice::RemoteDevice& remote_device) { + return remote_device.pii_free_name; +} + +const std::string& +StructTraits<chromeos::multidevice::mojom::RemoteDeviceDataView, + chromeos::multidevice::RemoteDevice>:: persistent_symmetric_key( const chromeos::multidevice::RemoteDevice& remote_device) { return remote_device.persistent_symmetric_key; @@ -106,6 +114,7 @@ base::Time last_update_time; if (!in.ReadUserId(&out->user_id) || !in.ReadDeviceName(&out->name) || + !in.ReadPiiFreeDeviceName(&out->pii_free_name) || !in.ReadDeviceId(&device_id) || !in.ReadPersistentSymmetricKey(&out->persistent_symmetric_key) || !in.ReadLastUpdateTime(&last_update_time) ||
diff --git a/chromeos/components/multidevice/mojom/multidevice_mojom_traits.h b/chromeos/components/multidevice/mojom/multidevice_mojom_traits.h index b89f93a..ed5a5f1 100644 --- a/chromeos/components/multidevice/mojom/multidevice_mojom_traits.h +++ b/chromeos/components/multidevice/mojom/multidevice_mojom_traits.h
@@ -44,6 +44,8 @@ const chromeos::multidevice::RemoteDevice& remote_device); static const std::string& device_name( const chromeos::multidevice::RemoteDevice& remote_device); + static const std::string& pii_free_device_name( + const chromeos::multidevice::RemoteDevice& remote_device); static const std::string& persistent_symmetric_key( const chromeos::multidevice::RemoteDevice& remote_device); static base::Time last_update_time(
diff --git a/chromeos/components/multidevice/mojom/multidevice_mojom_traits_unittest.cc b/chromeos/components/multidevice/mojom/multidevice_mojom_traits_unittest.cc index 12a22f1..68030018 100644 --- a/chromeos/components/multidevice/mojom/multidevice_mojom_traits_unittest.cc +++ b/chromeos/components/multidevice/mojom/multidevice_mojom_traits_unittest.cc
@@ -55,6 +55,7 @@ chromeos::multidevice::RemoteDevice input; input.user_id = "userId"; input.name = "name"; + input.pii_free_name = "piiFreeName"; input.public_key = "publicKey"; input.persistent_symmetric_key = "persistentSymmetricKey"; input.last_update_time_millis = 3L; @@ -67,6 +68,7 @@ EXPECT_EQ("userId", output.user_id); EXPECT_EQ("name", output.name); + EXPECT_EQ("piiFreeName", output.pii_free_name); EXPECT_EQ("publicKey", output.public_key); EXPECT_EQ("persistentSymmetricKey", output.persistent_symmetric_key); EXPECT_EQ(3L, output.last_update_time_millis);
diff --git a/chromeos/components/multidevice/mojom/multidevice_types.mojom b/chromeos/components/multidevice/mojom/multidevice_types.mojom index 9132550f..9f445ba 100644 --- a/chromeos/components/multidevice/mojom/multidevice_types.mojom +++ b/chromeos/components/multidevice/mojom/multidevice_types.mojom
@@ -65,6 +65,9 @@ // model, but this value is editable. string device_name; + // A device model name that's guaranteed not to contain any PII. + string pii_free_device_name; + // Encryption key used for communication with this device. string persistent_symmetric_key;
diff --git a/chromeos/components/multidevice/remote_device.cc b/chromeos/components/multidevice/remote_device.cc index f7d1a24..26da700 100644 --- a/chromeos/components/multidevice/remote_device.cc +++ b/chromeos/components/multidevice/remote_device.cc
@@ -23,6 +23,7 @@ RemoteDevice::RemoteDevice( const std::string& user_id, const std::string& name, + const std::string& pii_free_name, const std::string& public_key, const std::string& persistent_symmetric_key, int64_t last_update_time_millis, @@ -30,6 +31,7 @@ const std::vector<BeaconSeed>& beacon_seeds) : user_id(user_id), name(name), + pii_free_name(pii_free_name), public_key(public_key), persistent_symmetric_key(persistent_symmetric_key), last_update_time_millis(last_update_time_millis), @@ -46,6 +48,7 @@ bool RemoteDevice::operator==(const RemoteDevice& other) const { return user_id == other.user_id && name == other.name && + pii_free_name == other.pii_free_name && public_key == other.public_key && persistent_symmetric_key == other.persistent_symmetric_key && last_update_time_millis == other.last_update_time_millis &&
diff --git a/chromeos/components/multidevice/remote_device.h b/chromeos/components/multidevice/remote_device.h index 5f626be..8017d42 100644 --- a/chromeos/components/multidevice/remote_device.h +++ b/chromeos/components/multidevice/remote_device.h
@@ -23,6 +23,7 @@ std::string user_id; std::string name; + std::string pii_free_name; std::string public_key; std::string persistent_symmetric_key; int64_t last_update_time_millis; @@ -33,6 +34,7 @@ RemoteDevice( const std::string& user_id, const std::string& name, + const std::string& pii_free_name, const std::string& public_key, const std::string& persistent_symmetric_key, int64_t last_update_time_millis,
diff --git a/chromeos/components/multidevice/remote_device_ref.h b/chromeos/components/multidevice/remote_device_ref.h index e604ebf..ae9b4b9 100644 --- a/chromeos/components/multidevice/remote_device_ref.h +++ b/chromeos/components/multidevice/remote_device_ref.h
@@ -58,6 +58,9 @@ const std::string& user_id() const { return remote_device_->user_id; } const std::string& name() const { return remote_device_->name; } + const std::string& pii_free_name() const { + return remote_device_->pii_free_name; + } const std::string& public_key() const { return remote_device_->public_key; } const std::string& persistent_symmetric_key() const { return remote_device_->persistent_symmetric_key;
diff --git a/chromeos/components/multidevice/remote_device_ref_unittest.cc b/chromeos/components/multidevice/remote_device_ref_unittest.cc index 15510be..4621f8b 100644 --- a/chromeos/components/multidevice/remote_device_ref_unittest.cc +++ b/chromeos/components/multidevice/remote_device_ref_unittest.cc
@@ -30,8 +30,8 @@ std::vector<BeaconSeed> beacon_seeds({BeaconSeed(), BeaconSeed()}); remote_device_ = std::make_shared<RemoteDevice>( - "user_id", "name", "public_key", "persistent_symmetric_key", - 42000 /* last_update_time_millis */, + "user_id", "name", "pii_free_name", "public_key", + "persistent_symmetric_key", 42000 /* last_update_time_millis */, software_feature_to_state_map /* software_features */, beacon_seeds /* beacon_seeds */); } @@ -46,6 +46,7 @@ EXPECT_EQ(remote_device_->user_id, remote_device_ref.user_id()); EXPECT_EQ(remote_device_->name, remote_device_ref.name()); + EXPECT_EQ(remote_device_->pii_free_name, remote_device_ref.pii_free_name()); EXPECT_EQ(remote_device_->public_key, remote_device_ref.public_key()); EXPECT_EQ(remote_device_->persistent_symmetric_key, remote_device_ref.persistent_symmetric_key());
diff --git a/chromeos/components/multidevice/remote_device_test_util.cc b/chromeos/components/multidevice/remote_device_test_util.cc index d9ada24..286f289 100644 --- a/chromeos/components/multidevice/remote_device_test_util.cc +++ b/chromeos/components/multidevice/remote_device_test_util.cc
@@ -16,6 +16,7 @@ // Attributes of the default test remote device. const char kTestRemoteDeviceUserId[] = "example@gmail.com"; const char kTestRemoteDeviceName[] = "remote device"; +const char kTestRemoteDevicePiiFreeName[] = "no-pii device"; const char kTestRemoteDevicePublicKey[] = "public key"; const char kTestRemoteDevicePSK[] = "remote device psk"; const int64_t kTestRemoteDeviceLastUpdateTimeMillis = 0L; @@ -38,6 +39,12 @@ return *this; } +RemoteDeviceRefBuilder& RemoteDeviceRefBuilder::SetPiiFreeName( + const std::string& pii_free_name) { + remote_device_->pii_free_name = pii_free_name; + return *this; +} + RemoteDeviceRefBuilder& RemoteDeviceRefBuilder::SetPublicKey( const std::string& public_key) { remote_device_->public_key = public_key; @@ -83,7 +90,8 @@ SoftwareFeatureState::kSupported; return RemoteDevice(kTestRemoteDeviceUserId, kTestRemoteDeviceName, - kTestRemoteDevicePublicKey, kTestRemoteDevicePSK, + kTestRemoteDevicePiiFreeName, kTestRemoteDevicePublicKey, + kTestRemoteDevicePSK, kTestRemoteDeviceLastUpdateTimeMillis, software_features, {} /* beacon_seeds */); }
diff --git a/chromeos/components/multidevice/remote_device_test_util.h b/chromeos/components/multidevice/remote_device_test_util.h index a294ae49..82f2ca6 100644 --- a/chromeos/components/multidevice/remote_device_test_util.h +++ b/chromeos/components/multidevice/remote_device_test_util.h
@@ -25,6 +25,7 @@ ~RemoteDeviceRefBuilder(); RemoteDeviceRefBuilder& SetUserId(const std::string& user_id); RemoteDeviceRefBuilder& SetName(const std::string& name); + RemoteDeviceRefBuilder& SetPiiFreeName(const std::string& pii_free_name); RemoteDeviceRefBuilder& SetPublicKey(const std::string& public_key); RemoteDeviceRefBuilder& SetSupportsMobileHotspot( bool supports_mobile_hotspot);
diff --git a/chromeos/components/proximity_auth/unlock_manager_impl_unittest.cc b/chromeos/components/proximity_auth/unlock_manager_impl_unittest.cc index e8a1ad1..a23221d 100644 --- a/chromeos/components/proximity_auth/unlock_manager_impl_unittest.cc +++ b/chromeos/components/proximity_auth/unlock_manager_impl_unittest.cc
@@ -75,7 +75,7 @@ class MockProximityMonitor : public ProximityMonitor { public: - MockProximityMonitor(base::OnceClosure destroy_callback) + explicit MockProximityMonitor(base::OnceClosure destroy_callback) : destroy_callback_(std::move(destroy_callback)), started_(false) { ON_CALL(*this, IsUnlockAllowed()).WillByDefault(Return(true)); } @@ -171,7 +171,7 @@ life_cycle_.set_messenger(&messenger_); life_cycle_.set_channel(fake_client_channel_.get()); - chromeos::PowerManagerClient::Initialize(); + chromeos::PowerManagerClient::InitializeFake(); } void TearDown() override {
diff --git a/chromeos/cryptohome/async_method_caller.cc b/chromeos/cryptohome/async_method_caller.cc index 220cfcc..7b56126 100644 --- a/chromeos/cryptohome/async_method_caller.cc +++ b/chromeos/cryptohome/async_method_caller.cc
@@ -11,7 +11,7 @@ #include "base/single_thread_task_runner.h" #include "base/threading/thread_task_runner_handle.h" #include "chromeos/cryptohome/cryptohome_parameters.h" -#include "chromeos/dbus/cryptohome_client.h" +#include "chromeos/dbus/cryptohome/cryptohome_client.h" #include "chromeos/dbus/dbus_thread_manager.h" using chromeos::DBusThreadManager;
diff --git a/chromeos/cryptohome/async_method_caller.h b/chromeos/cryptohome/async_method_caller.h index c925fdd..ae8410b 100644 --- a/chromeos/cryptohome/async_method_caller.h +++ b/chromeos/cryptohome/async_method_caller.h
@@ -9,8 +9,8 @@ #include "base/callback_forward.h" #include "base/component_export.h" -#include "chromeos/dbus/attestation_constants.h" -#include "chromeos/dbus/cryptohome_client.h" +#include "chromeos/dbus/constants/attestation_constants.h" +#include "chromeos/dbus/cryptohome/cryptohome_client.h" #include "third_party/cros_system_api/dbus/service_constants.h" namespace cryptohome {
diff --git a/chromeos/cryptohome/homedir_methods.h b/chromeos/cryptohome/homedir_methods.h index 9aff45f..8959087 100644 --- a/chromeos/cryptohome/homedir_methods.h +++ b/chromeos/cryptohome/homedir_methods.h
@@ -13,9 +13,9 @@ #include "base/callback_forward.h" #include "base/component_export.h" #include "chromeos/cryptohome/cryptohome_parameters.h" +#include "chromeos/dbus/cryptohome/cryptohome_client.h" #include "chromeos/dbus/cryptohome/key.pb.h" #include "chromeos/dbus/cryptohome/rpc.pb.h" -#include "chromeos/dbus/cryptohome_client.h" #include "third_party/cros_system_api/dbus/service_constants.h" namespace cryptohome {
diff --git a/chromeos/cryptohome/system_salt_getter.cc b/chromeos/cryptohome/system_salt_getter.cc index 75f8d5b..dc44750 100644 --- a/chromeos/cryptohome/system_salt_getter.cc +++ b/chromeos/cryptohome/system_salt_getter.cc
@@ -14,7 +14,7 @@ #include "base/strings/string_number_conversions.h" #include "base/strings/string_util.h" #include "base/threading/thread_task_runner_handle.h" -#include "chromeos/dbus/cryptohome_client.h" +#include "chromeos/dbus/cryptohome/cryptohome_client.h" #include "chromeos/dbus/dbus_thread_manager.h" namespace chromeos {
diff --git a/chromeos/cryptohome/system_salt_getter_unittest.cc b/chromeos/cryptohome/system_salt_getter_unittest.cc index b7f618f..c47a12f 100644 --- a/chromeos/cryptohome/system_salt_getter_unittest.cc +++ b/chromeos/cryptohome/system_salt_getter_unittest.cc
@@ -7,8 +7,8 @@ #include "base/bind.h" #include "base/run_loop.h" #include "base/test/scoped_task_environment.h" +#include "chromeos/dbus/cryptohome/fake_cryptohome_client.h" #include "chromeos/dbus/dbus_thread_manager.h" -#include "chromeos/dbus/fake_cryptohome_client.h" #include "testing/gtest/include/gtest/gtest.h" namespace chromeos {
diff --git a/chromeos/dbus/BUILD.gn b/chromeos/dbus/BUILD.gn index d42a98930..d2e7da0 100644 --- a/chromeos/dbus/BUILD.gn +++ b/chromeos/dbus/BUILD.gn
@@ -49,8 +49,6 @@ "arc_obb_mounter_client.h", "arc_oemcrypto_client.cc", "arc_oemcrypto_client.h", - "attestation_constants.cc", - "attestation_constants.h", "audio_node.cc", "audio_node.h", "auth_policy_client.cc", @@ -67,12 +65,16 @@ "cicerone_client.h", "concierge_client.cc", "concierge_client.h", + "constants/attestation_constants.cc", + "constants/attestation_constants.h", "cras_audio_client.cc", "cras_audio_client.h", "cros_disks_client.cc", "cros_disks_client.h", - "cryptohome_client.cc", - "cryptohome_client.h", + "cryptohome/cryptohome_client.cc", + "cryptohome/cryptohome_client.h", + "cryptohome/fake_cryptohome_client.cc", + "cryptohome/fake_cryptohome_client.h", "dbus_client.h", "dbus_client_implementation_type.h", "dbus_clients_browser.cc", @@ -109,8 +111,6 @@ "fake_cras_audio_client.h", "fake_cros_disks_client.cc", "fake_cros_disks_client.h", - "fake_cryptohome_client.cc", - "fake_cryptohome_client.h", "fake_debug_daemon_client.cc", "fake_debug_daemon_client.h", "fake_diagnosticsd_client.cc", @@ -283,9 +283,9 @@ "cec_service_client_unittest.cc", "cras_audio_client_unittest.cc", "cros_disks_client_unittest.cc", + "cryptohome/fake_cryptohome_client_unittest.cc", "dbus_thread_manager_unittest.cc", "fake_auth_policy_client_unittest.cc", - "fake_cryptohome_client_unittest.cc", "fake_easy_unlock_client_unittest.cc", "gsm_sms_client_unittest.cc", "modem_messaging_client_unittest.cc",
diff --git a/chromeos/dbus/attestation_constants.cc b/chromeos/dbus/constants/attestation_constants.cc similarity index 89% rename from chromeos/dbus/attestation_constants.cc rename to chromeos/dbus/constants/attestation_constants.cc index c22498986..7186e2b 100644 --- a/chromeos/dbus/attestation_constants.cc +++ b/chromeos/dbus/constants/attestation_constants.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 "chromeos/dbus/attestation_constants.h" +#include "chromeos/dbus/constants/attestation_constants.h" namespace chromeos { namespace attestation {
diff --git a/chromeos/dbus/attestation_constants.h b/chromeos/dbus/constants/attestation_constants.h similarity index 94% rename from chromeos/dbus/attestation_constants.h rename to chromeos/dbus/constants/attestation_constants.h index e0d28705..a5756cb 100644 --- a/chromeos/dbus/attestation_constants.h +++ b/chromeos/dbus/constants/attestation_constants.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 CHROMEOS_DBUS_ATTESTATION_CONSTANTS_H_ -#define CHROMEOS_DBUS_ATTESTATION_CONSTANTS_H_ +#ifndef CHROMEOS_DBUS_CONSTANTS_ATTESTATION_CONSTANTS_H_ +#define CHROMEOS_DBUS_CONSTANTS_ATTESTATION_CONSTANTS_H_ #include "base/component_export.h" @@ -85,4 +85,4 @@ } // namespace attestation } // namespace chromeos -#endif // CHROMEOS_DBUS_ATTESTATION_CONSTANTS_H_ +#endif // CHROMEOS_DBUS_CONSTANTS_ATTESTATION_CONSTANTS_H_
diff --git a/chromeos/dbus/cryptohome_client.cc b/chromeos/dbus/cryptohome/cryptohome_client.cc similarity index 98% rename from chromeos/dbus/cryptohome_client.cc rename to chromeos/dbus/cryptohome/cryptohome_client.cc index 97195be..7a881e8 100644 --- a/chromeos/dbus/cryptohome_client.cc +++ b/chromeos/dbus/cryptohome/cryptohome_client.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 "chromeos/dbus/cryptohome_client.h" +#include "chromeos/dbus/cryptohome/cryptohome_client.h" #include <stddef.h> #include <stdint.h> @@ -426,8 +426,7 @@ dbus::MessageReader reader(response.get()); const uint8_t* bytes = NULL; size_t length = 0; - if (!reader.PopArrayOfBytes(&bytes, &length) || - !reader.PopBool(successful)) + if (!reader.PopArrayOfBytes(&bytes, &length) || !reader.PopBool(successful)) return false; value->assign(bytes, bytes + length); return true; @@ -806,8 +805,7 @@ const cryptohome::CheckKeyRequest& request, DBusMethodCallback<cryptohome::BaseReply> callback) override { const char* method_name = cryptohome::kCryptohomeCheckKeyEx; - dbus::MethodCall method_call(cryptohome::kCryptohomeInterface, - method_name); + dbus::MethodCall method_call(cryptohome::kCryptohomeInterface, method_name); dbus::MessageWriter writer(&method_call); writer.AppendProtoAsArrayOfBytes(id); writer.AppendProtoAsArrayOfBytes(auth); @@ -824,8 +822,7 @@ const cryptohome::MountRequest& request, DBusMethodCallback<cryptohome::BaseReply> callback) override { const char* method_name = cryptohome::kCryptohomeMountEx; - dbus::MethodCall method_call(cryptohome::kCryptohomeInterface, - method_name); + dbus::MethodCall method_call(cryptohome::kCryptohomeInterface, method_name); dbus::MessageWriter writer(&method_call); writer.AppendProtoAsArrayOfBytes(id); writer.AppendProtoAsArrayOfBytes(auth); @@ -842,8 +839,7 @@ const cryptohome::AddKeyRequest& request, DBusMethodCallback<cryptohome::BaseReply> callback) override { const char* method_name = cryptohome::kCryptohomeAddKeyEx; - dbus::MethodCall method_call(cryptohome::kCryptohomeInterface, - method_name); + dbus::MethodCall method_call(cryptohome::kCryptohomeInterface, method_name); dbus::MessageWriter writer(&method_call); writer.AppendProtoAsArrayOfBytes(id); writer.AppendProtoAsArrayOfBytes(auth); @@ -861,8 +857,7 @@ const cryptohome::UpdateKeyRequest& request, DBusMethodCallback<cryptohome::BaseReply> callback) override { const char* method_name = cryptohome::kCryptohomeUpdateKeyEx; - dbus::MethodCall method_call(cryptohome::kCryptohomeInterface, - method_name); + dbus::MethodCall method_call(cryptohome::kCryptohomeInterface, method_name); dbus::MessageWriter writer(&method_call); writer.AppendProtoAsArrayOfBytes(id); writer.AppendProtoAsArrayOfBytes(auth); @@ -975,9 +970,8 @@ } void IsQuotaSupported(DBusMethodCallback<bool> callback) override { - dbus::MethodCall method_call( - cryptohome::kCryptohomeInterface, - cryptohome::kCryptohomeIsQuotaSupported); + dbus::MethodCall method_call(cryptohome::kCryptohomeInterface, + cryptohome::kCryptohomeIsQuotaSupported); proxy_->CallMethod( &method_call, dbus::ObjectProxy::TIMEOUT_USE_DEFAULT, @@ -1114,8 +1108,7 @@ } // Calls a method with a bool value reult and block. - bool CallBoolMethodAndBlock(dbus::MethodCall* method_call, - bool* result) { + bool CallBoolMethodAndBlock(dbus::MethodCall* method_call, bool* result) { base::Time start_time = base::Time::Now(); std::unique_ptr<dbus::Response> response( @@ -1158,7 +1151,7 @@ } void OnInt64DBusMethod(DBusMethodCallback<int64_t> callback, - dbus::Response* response) { + dbus::Response* response) { if (!response) { std::move(callback).Run(base::nullopt); return; @@ -1273,8 +1266,7 @@ int async_id = 0; bool return_status = false; int return_code = 0; - if (!reader.PopInt32(&async_id) || - !reader.PopBool(&return_status) || + if (!reader.PopInt32(&async_id) || !reader.PopBool(&return_status) || !reader.PopInt32(&return_code)) { LOG(ERROR) << "Invalid signal: " << signal->ToString(); return; @@ -1290,8 +1282,7 @@ bool return_status = false; const uint8_t* return_data_buffer = NULL; size_t return_data_length = 0; - if (!reader.PopInt32(&async_id) || - !reader.PopBool(&return_status) || + if (!reader.PopInt32(&async_id) || !reader.PopBool(&return_status) || !reader.PopArrayOfBytes(&return_data_buffer, &return_data_length)) { LOG(ERROR) << "Invalid signal: " << signal->ToString(); return; @@ -1335,8 +1326,8 @@ void OnSignalConnected(const std::string& interface, const std::string& signal, bool succeeded) { - LOG_IF(ERROR, !succeeded) << "Connect to " << interface << " " << - signal << " failed."; + LOG_IF(ERROR, !succeeded) + << "Connect to " << interface << " " << signal << " failed."; } // Makes an asynchronous D-Bus call, using cryptohome interface. |method_name|
diff --git a/chromeos/dbus/cryptohome_client.h b/chromeos/dbus/cryptohome/cryptohome_client.h similarity index 98% rename from chromeos/dbus/cryptohome_client.h rename to chromeos/dbus/cryptohome/cryptohome_client.h index 6870e52..2e69a74 100644 --- a/chromeos/dbus/cryptohome_client.h +++ b/chromeos/dbus/cryptohome/cryptohome_client.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 CHROMEOS_DBUS_CRYPTOHOME_CLIENT_H_ -#define CHROMEOS_DBUS_CRYPTOHOME_CLIENT_H_ +#ifndef CHROMEOS_DBUS_CRYPTOHOME_CRYPTOHOME_CLIENT_H_ +#define CHROMEOS_DBUS_CRYPTOHOME_CRYPTOHOME_CLIENT_H_ #include <stdint.h> @@ -13,7 +13,7 @@ #include "base/callback.h" #include "base/component_export.h" #include "base/macros.h" -#include "chromeos/dbus/attestation_constants.h" +#include "chromeos/dbus/constants/attestation_constants.h" #include "chromeos/dbus/dbus_client.h" #include "chromeos/dbus/dbus_method_call_status.h" #include "third_party/cros_system_api/dbus/service_constants.h" @@ -607,8 +607,7 @@ DBusMethodCallback<cryptohome::BaseReply> callback) = 0; // Calls IsQuotaSupported to know whether quota is supported by cryptohome. - virtual void IsQuotaSupported( - DBusMethodCallback<bool> callback) = 0; + virtual void IsQuotaSupported(DBusMethodCallback<bool> callback) = 0; // Calls GetCurrentSpaceForUid to get the current disk space for an android // uid (a shifted uid). @@ -630,4 +629,4 @@ } // namespace chromeos -#endif // CHROMEOS_DBUS_CRYPTOHOME_CLIENT_H_ +#endif // CHROMEOS_DBUS_CRYPTOHOME_CRYPTOHOME_CLIENT_H_
diff --git a/chromeos/dbus/fake_cryptohome_client.cc b/chromeos/dbus/cryptohome/fake_cryptohome_client.cc similarity index 99% rename from chromeos/dbus/fake_cryptohome_client.cc rename to chromeos/dbus/cryptohome/fake_cryptohome_client.cc index 369c1db..a0b9fa4 100644 --- a/chromeos/dbus/fake_cryptohome_client.cc +++ b/chromeos/dbus/cryptohome/fake_cryptohome_client.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 "chromeos/dbus/fake_cryptohome_client.h" +#include "chromeos/dbus/cryptohome/fake_cryptohome_client.h" #include <stddef.h> #include <stdint.h>
diff --git a/chromeos/dbus/fake_cryptohome_client.h b/chromeos/dbus/cryptohome/fake_cryptohome_client.h similarity index 98% rename from chromeos/dbus/fake_cryptohome_client.h rename to chromeos/dbus/cryptohome/fake_cryptohome_client.h index bc20bf1..e9aeb84 100644 --- a/chromeos/dbus/fake_cryptohome_client.h +++ b/chromeos/dbus/cryptohome/fake_cryptohome_client.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 CHROMEOS_DBUS_FAKE_CRYPTOHOME_CLIENT_H_ -#define CHROMEOS_DBUS_FAKE_CRYPTOHOME_CLIENT_H_ +#ifndef CHROMEOS_DBUS_CRYPTOHOME_FAKE_CRYPTOHOME_CLIENT_H_ +#define CHROMEOS_DBUS_CRYPTOHOME_FAKE_CRYPTOHOME_CLIENT_H_ #include <stdint.h> @@ -17,9 +17,9 @@ #include "base/observer_list.h" #include "base/optional.h" #include "base/timer/timer.h" +#include "chromeos/dbus/cryptohome/cryptohome_client.h" #include "chromeos/dbus/cryptohome/key.pb.h" #include "chromeos/dbus/cryptohome/rpc.pb.h" -#include "chromeos/dbus/cryptohome_client.h" namespace chromeos { @@ -231,9 +231,7 @@ void SetServiceIsAvailable(bool is_available); // Sets the unmount result of Unmount() call. - void set_unmount_result(bool result) { - unmount_result_ = result; - } + void set_unmount_result(bool result) { unmount_result_ = result; } // Sets the system salt which will be returned from GetSystemSalt(). By // default, GetSystemSalt() returns the value generated by @@ -433,4 +431,4 @@ } // namespace chromeos -#endif // CHROMEOS_DBUS_FAKE_CRYPTOHOME_CLIENT_H_ +#endif // CHROMEOS_DBUS_CRYPTOHOME_FAKE_CRYPTOHOME_CLIENT_H_
diff --git a/chromeos/dbus/fake_cryptohome_client_unittest.cc b/chromeos/dbus/cryptohome/fake_cryptohome_client_unittest.cc similarity index 97% rename from chromeos/dbus/fake_cryptohome_client_unittest.cc rename to chromeos/dbus/cryptohome/fake_cryptohome_client_unittest.cc index 11fdd1d..3c413033 100644 --- a/chromeos/dbus/fake_cryptohome_client_unittest.cc +++ b/chromeos/dbus/cryptohome/fake_cryptohome_client_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 "chromeos/dbus/fake_cryptohome_client.h" +#include "chromeos/dbus/cryptohome/fake_cryptohome_client.h" #include <string>
diff --git a/chromeos/dbus/dbus_clients_common.cc b/chromeos/dbus/dbus_clients_common.cc index 905a838..9230692 100644 --- a/chromeos/dbus/dbus_clients_common.cc +++ b/chromeos/dbus/dbus_clients_common.cc
@@ -7,11 +7,11 @@ #include "base/command_line.h" #include "chromeos/dbus/constants/dbus_switches.h" #include "chromeos/dbus/cras_audio_client.h" -#include "chromeos/dbus/cryptohome_client.h" +#include "chromeos/dbus/cryptohome/cryptohome_client.h" +#include "chromeos/dbus/cryptohome/fake_cryptohome_client.h" #include "chromeos/dbus/dbus_client_implementation_type.h" #include "chromeos/dbus/dbus_thread_manager.h" #include "chromeos/dbus/fake_cras_audio_client.h" -#include "chromeos/dbus/fake_cryptohome_client.h" #include "chromeos/dbus/fake_gsm_sms_client.h" #include "chromeos/dbus/fake_modem_messaging_client.h" #include "chromeos/dbus/fake_permission_broker_client.h"
diff --git a/chromeos/dbus/dbus_thread_manager.cc b/chromeos/dbus/dbus_thread_manager.cc index 09823b1..fecfa157 100644 --- a/chromeos/dbus/dbus_thread_manager.cc +++ b/chromeos/dbus/dbus_thread_manager.cc
@@ -21,7 +21,7 @@ #include "chromeos/dbus/constants/dbus_switches.h" #include "chromeos/dbus/cras_audio_client.h" #include "chromeos/dbus/cros_disks_client.h" -#include "chromeos/dbus/cryptohome_client.h" +#include "chromeos/dbus/cryptohome/cryptohome_client.h" #include "chromeos/dbus/dbus_client.h" #include "chromeos/dbus/dbus_clients_browser.h" #include "chromeos/dbus/dbus_clients_common.h"
diff --git a/chromeos/dbus/fake_auth_policy_client.cc b/chromeos/dbus/fake_auth_policy_client.cc index 77c7e21..2b000da 100644 --- a/chromeos/dbus/fake_auth_policy_client.cc +++ b/chromeos/dbus/fake_auth_policy_client.cc
@@ -14,8 +14,8 @@ #include "base/task/post_task.h" #include "base/threading/platform_thread.h" #include "base/threading/thread_task_runner_handle.h" +#include "chromeos/dbus/cryptohome/cryptohome_client.h" #include "chromeos/dbus/cryptohome/rpc.pb.h" -#include "chromeos/dbus/cryptohome_client.h" #include "chromeos/dbus/dbus_thread_manager.h" #include "chromeos/dbus/session_manager/session_manager_client.h" #include "chromeos/dbus/util/tpm_util.h"
diff --git a/chromeos/dbus/fake_auth_policy_client_unittest.cc b/chromeos/dbus/fake_auth_policy_client_unittest.cc index f4631df..550857e0 100644 --- a/chromeos/dbus/fake_auth_policy_client_unittest.cc +++ b/chromeos/dbus/fake_auth_policy_client_unittest.cc
@@ -7,8 +7,8 @@ #include "base/bind.h" #include "base/message_loop/message_loop.h" #include "base/run_loop.h" +#include "chromeos/dbus/cryptohome/fake_cryptohome_client.h" #include "chromeos/dbus/dbus_thread_manager.h" -#include "chromeos/dbus/fake_cryptohome_client.h" #include "chromeos/dbus/session_manager/fake_session_manager_client.h" #include "chromeos/dbus/util/tpm_util.h" #include "components/account_id/account_id.h"
diff --git a/chromeos/dbus/native_timer_unittest.cc b/chromeos/dbus/native_timer_unittest.cc index 3a8b43b..475a3b6 100644 --- a/chromeos/dbus/native_timer_unittest.cc +++ b/chromeos/dbus/native_timer_unittest.cc
@@ -64,7 +64,7 @@ ~NativeTimerTest() override = default; // testing::Test: - void SetUp() override { PowerManagerClient::Initialize(); } + void SetUp() override { PowerManagerClient::InitializeFake(); } void TearDown() override { PowerManagerClient::Shutdown(); }
diff --git a/chromeos/dbus/power/fake_power_manager_client.cc b/chromeos/dbus/power/fake_power_manager_client.cc index e2178f06..fcc44fc8 100644 --- a/chromeos/dbus/power/fake_power_manager_client.cc +++ b/chromeos/dbus/power/fake_power_manager_client.cc
@@ -55,9 +55,15 @@ } // namespace +// static +FakePowerManagerClient* FakePowerManagerClient::Get() { + CHECK(g_instance); + return g_instance; +} + FakePowerManagerClient::FakePowerManagerClient() : props_(power_manager::PowerSupplyProperties()) { - DCHECK(!g_instance); + CHECK(!g_instance); g_instance = this; props_->set_battery_percent(50); @@ -71,7 +77,7 @@ } FakePowerManagerClient::~FakePowerManagerClient() { - DCHECK_EQ(g_instance, this); + CHECK_EQ(g_instance, this); g_instance = nullptr; } @@ -422,11 +428,6 @@ observer.PowerChanged(*props_); } -FakePowerManagerClient* FakePowerManagerClient::Get() { - DCHECK(g_instance); - return g_instance; -} - void FakePowerManagerClient::HandleSuspendReadiness() { CHECK_GT(num_pending_suspend_readiness_callbacks_, 0);
diff --git a/chromeos/dbus/power/fake_power_manager_client.h b/chromeos/dbus/power/fake_power_manager_client.h index e2ed21a..1faac2a 100644 --- a/chromeos/dbus/power/fake_power_manager_client.h +++ b/chromeos/dbus/power/fake_power_manager_client.h
@@ -37,6 +37,9 @@ FakePowerManagerClient(); ~FakePowerManagerClient() override; + // Checks that FakePowerManagerClient was initialized and returns it. + static FakePowerManagerClient* Get(); + const power_manager::PowerManagementPolicy& policy() { return policy_; } int num_request_restart_calls() const { return num_request_restart_calls_; } int num_request_shutdown_calls() const { return num_request_shutdown_calls_; } @@ -184,8 +187,6 @@ keyboard_brightness_percent_ = percent; } - static FakePowerManagerClient* Get(); - private: // Callback that will be run by asynchronous suspend delays to report // readiness.
diff --git a/chromeos/dbus/power/power_manager_client.cc b/chromeos/dbus/power/power_manager_client.cc index 44b94e099..8d66107 100644 --- a/chromeos/dbus/power/power_manager_client.cc +++ b/chromeos/dbus/power/power_manager_client.cc
@@ -1144,21 +1144,30 @@ }; PowerManagerClient::PowerManagerClient() { - DCHECK_EQ(g_instance, nullptr); + CHECK(!g_instance); g_instance = this; } PowerManagerClient::~PowerManagerClient() { - DCHECK_EQ(g_instance, this); + CHECK_EQ(this, g_instance); g_instance = nullptr; } // static void PowerManagerClient::Initialize(dbus::Bus* bus) { - if (bus) - (new PowerManagerClientImpl())->Init(bus); - else - new FakePowerManagerClient(); + CHECK(bus); + (new PowerManagerClientImpl())->Init(bus); +} + +// static +void PowerManagerClient::InitializeFake() { + new FakePowerManagerClient(); +} + +// static +void PowerManagerClient::Shutdown() { + CHECK(g_instance); + delete g_instance; } // static @@ -1166,9 +1175,4 @@ return g_instance; } -// static -void PowerManagerClient::Shutdown() { - delete g_instance; -} - } // namespace chromeos
diff --git a/chromeos/dbus/power/power_manager_client.h b/chromeos/dbus/power/power_manager_client.h index b1f2938a..b6356af 100644 --- a/chromeos/dbus/power/power_manager_client.h +++ b/chromeos/dbus/power/power_manager_client.h
@@ -317,12 +317,18 @@ PowerManagerClient(); virtual ~PowerManagerClient(); - // Creates and inits the instance. If |bus| is null, a FakePowerManagerClient - // will be created. - static void Initialize(dbus::Bus* bus = nullptr); - static PowerManagerClient* Get(); + // Creates and initializes the global instance. |bus| must not be null. + static void Initialize(dbus::Bus* bus); + + // Creates and initializes a fake global instance if not already created. + static void InitializeFake(); + + // Destroys the global instance which must have been initialized. static void Shutdown(); + // Returns the global instance if initialized. May return null. + static PowerManagerClient* Get(); + private: DISALLOW_COPY_AND_ASSIGN(PowerManagerClient); };
diff --git a/chromeos/dbus/power/power_policy_controller_unittest.cc b/chromeos/dbus/power/power_policy_controller_unittest.cc index bdc3e451..da537b5 100644 --- a/chromeos/dbus/power/power_policy_controller_unittest.cc +++ b/chromeos/dbus/power/power_policy_controller_unittest.cc
@@ -20,7 +20,7 @@ ~PowerPolicyControllerTest() override = default; void SetUp() override { - PowerManagerClient::Initialize(); + PowerManagerClient::InitializeFake(); PowerPolicyController::Initialize(FakePowerManagerClient::Get()); ASSERT_TRUE(PowerPolicyController::IsInitialized()); policy_controller_ = PowerPolicyController::Get();
diff --git a/chromeos/dbus/session_manager/fake_session_manager_client.cc b/chromeos/dbus/session_manager/fake_session_manager_client.cc index e628292..ed5361be 100644 --- a/chromeos/dbus/session_manager/fake_session_manager_client.cc +++ b/chromeos/dbus/session_manager/fake_session_manager_client.cc
@@ -20,7 +20,7 @@ #include "base/task/post_task.h" #include "base/threading/thread_task_runner_handle.h" #include "chromeos/dbus/constants/dbus_paths.h" -#include "chromeos/dbus/cryptohome_client.h" +#include "chromeos/dbus/cryptohome/cryptohome_client.h" #include "chromeos/dbus/login_manager/policy_descriptor.pb.h" #include "chromeos/dbus/util/account_identifier_operators.h" #include "components/policy/proto/device_management_backend.pb.h"
diff --git a/chromeos/dbus/session_manager/session_manager_client.cc b/chromeos/dbus/session_manager/session_manager_client.cc index def291b..efbe74b 100644 --- a/chromeos/dbus/session_manager/session_manager_client.cc +++ b/chromeos/dbus/session_manager/session_manager_client.cc
@@ -22,8 +22,8 @@ #include "base/strings/string_util.h" #include "base/threading/thread_task_runner_handle.h" #include "chromeos/dbus/blocking_method_caller.h" +#include "chromeos/dbus/cryptohome/cryptohome_client.h" #include "chromeos/dbus/cryptohome/rpc.pb.h" -#include "chromeos/dbus/cryptohome_client.h" #include "chromeos/dbus/login_manager/arc.pb.h" #include "chromeos/dbus/login_manager/policy_descriptor.pb.h" #include "chromeos/dbus/session_manager/fake_session_manager_client.h"
diff --git a/chromeos/dbus/util/tpm_util.cc b/chromeos/dbus/util/tpm_util.cc index 2340052..c6e356d3 100644 --- a/chromeos/dbus/util/tpm_util.cc +++ b/chromeos/dbus/util/tpm_util.cc
@@ -7,7 +7,7 @@ #include <stdint.h> #include "base/logging.h" -#include "chromeos/dbus/cryptohome_client.h" +#include "chromeos/dbus/cryptohome/cryptohome_client.h" #include "chromeos/dbus/dbus_thread_manager.h" namespace chromeos {
diff --git a/chromeos/dbus/util/version_loader.cc b/chromeos/dbus/util/version_loader.cc index e351ab71..a20ec33 100644 --- a/chromeos/dbus/util/version_loader.cc +++ b/chromeos/dbus/util/version_loader.cc
@@ -20,7 +20,7 @@ #include "base/strings/stringprintf.h" #include "base/system/sys_info.h" #include "base/time/time.h" -#include "chromeos/dbus/cryptohome_client.h" +#include "chromeos/dbus/cryptohome/cryptohome_client.h" #include "chromeos/dbus/dbus_thread_manager.h" namespace chromeos {
diff --git a/chromeos/dbus/util/version_loader.h b/chromeos/dbus/util/version_loader.h index 8c446d4..ad15537 100644 --- a/chromeos/dbus/util/version_loader.h +++ b/chromeos/dbus/util/version_loader.h
@@ -9,7 +9,7 @@ #include "base/callback_forward.h" #include "base/component_export.h" -#include "chromeos/dbus/cryptohome_client.h" +#include "chromeos/dbus/cryptohome/cryptohome_client.h" namespace chromeos { namespace version_loader {
diff --git a/chromeos/disks/disk_mount_manager_unittest.cc b/chromeos/disks/disk_mount_manager_unittest.cc index 73628e4..54d03a8 100644 --- a/chromeos/disks/disk_mount_manager_unittest.cc +++ b/chromeos/disks/disk_mount_manager_unittest.cc
@@ -502,7 +502,7 @@ fake_cros_disks_client_ = new FakeCrosDisksClient; DBusThreadManager::GetSetterForTesting()->SetCrosDisksClient( std::unique_ptr<CrosDisksClient>(fake_cros_disks_client_)); - PowerManagerClient::Initialize(); + PowerManagerClient::InitializeFake(); DiskMountManager::Initialize();
diff --git a/chromeos/login/auth/authpolicy_login_helper_unittest.cc b/chromeos/login/auth/authpolicy_login_helper_unittest.cc index 793c7dc..7e2503fd 100644 --- a/chromeos/login/auth/authpolicy_login_helper_unittest.cc +++ b/chromeos/login/auth/authpolicy_login_helper_unittest.cc
@@ -5,9 +5,9 @@ #include "chromeos/login/auth/authpolicy_login_helper.h" #include "base/bind.h" +#include "chromeos/dbus/cryptohome/fake_cryptohome_client.h" #include "chromeos/dbus/dbus_thread_manager.h" #include "chromeos/dbus/fake_auth_policy_client.h" -#include "chromeos/dbus/fake_cryptohome_client.h" #include "testing/gtest/include/gtest/gtest.h" namespace chromeos {
diff --git a/chromeos/login/auth/cryptohome_authenticator.cc b/chromeos/login/auth/cryptohome_authenticator.cc index b6605c67..a2e2cf5 100644 --- a/chromeos/login/auth/cryptohome_authenticator.cc +++ b/chromeos/login/auth/cryptohome_authenticator.cc
@@ -20,7 +20,7 @@ #include "chromeos/cryptohome/cryptohome_util.h" #include "chromeos/cryptohome/homedir_methods.h" #include "chromeos/cryptohome/system_salt_getter.h" -#include "chromeos/dbus/cryptohome_client.h" +#include "chromeos/dbus/cryptohome/cryptohome_client.h" #include "chromeos/dbus/dbus_thread_manager.h" #include "chromeos/login/auth/auth_status_consumer.h" #include "chromeos/login/auth/key.h"
diff --git a/chromeos/login/auth/extended_authenticator_impl.cc b/chromeos/login/auth/extended_authenticator_impl.cc index 923cac7..b2217cac 100644 --- a/chromeos/login/auth/extended_authenticator_impl.cc +++ b/chromeos/login/auth/extended_authenticator_impl.cc
@@ -14,7 +14,7 @@ #include "chromeos/cryptohome/cryptohome_util.h" #include "chromeos/cryptohome/homedir_methods.h" #include "chromeos/cryptohome/system_salt_getter.h" -#include "chromeos/dbus/cryptohome_client.h" +#include "chromeos/dbus/cryptohome/cryptohome_client.h" #include "chromeos/dbus/dbus_thread_manager.h" #include "chromeos/login/auth/auth_status_consumer.h" #include "chromeos/login/auth/key.h"
diff --git a/chromeos/login/auth/stub_authenticator.cc b/chromeos/login/auth/stub_authenticator.cc index e8b5245..338b3cc 100644 --- a/chromeos/login/auth/stub_authenticator.cc +++ b/chromeos/login/auth/stub_authenticator.cc
@@ -13,7 +13,7 @@ namespace { -// As defined in /chromeos/dbus/cryptohome_client.cc. +// As defined in /chromeos/dbus/cryptohome/cryptohome_client.cc. static const char kUserIdHashSuffix[] = "-hash"; } // anonymous namespace
diff --git a/chromeos/services/assistant/platform/power_manager_provider_impl_unittest.cc b/chromeos/services/assistant/platform/power_manager_provider_impl_unittest.cc index 97762126..195e799 100644 --- a/chromeos/services/assistant/platform/power_manager_provider_impl_unittest.cc +++ b/chromeos/services/assistant/platform/power_manager_provider_impl_unittest.cc
@@ -34,7 +34,7 @@ ~PowerManagerProviderImplTest() override = default; void SetUp() override { - chromeos::PowerManagerClient::Initialize(); + chromeos::PowerManagerClient::InitializeFake(); power_manager_provider_impl_ = std::make_unique<PowerManagerProviderImpl>( connector_factory_.GetDefaultConnector(), scoped_task_environment_.GetMainThreadTaskRunner());
diff --git a/chromeos/services/assistant/service_unittest.cc b/chromeos/services/assistant/service_unittest.cc index 0224667f..7efb422 100644 --- a/chromeos/services/assistant/service_unittest.cc +++ b/chromeos/services/assistant/service_unittest.cc
@@ -161,7 +161,7 @@ // which are irrelevant for these tests. test_connector_factory_.set_ignore_unknown_service_requests(true); - PowerManagerClient::Initialize(); + PowerManagerClient::InitializeFake(); FakePowerManagerClient::Get()->SetTabletMode( PowerManagerClient::TabletMode::OFF, base::TimeTicks());
diff --git a/chromeos/services/device_sync/remote_device_loader.cc b/chromeos/services/device_sync/remote_device_loader.cc index 8397532c..b4c98ad 100644 --- a/chromeos/services/device_sync/remote_device_loader.cc +++ b/chromeos/services/device_sync/remote_device_loader.cc
@@ -143,9 +143,9 @@ } multidevice::RemoteDevice remote_device( - user_id_, device.friendly_device_name(), device.public_key(), psk, - device.last_update_time_millis(), GetSoftwareFeatureToStateMap(device), - multidevice_beacon_seeds); + user_id_, device.friendly_device_name(), device.no_pii_device_name(), + device.public_key(), psk, device.last_update_time_millis(), + GetSoftwareFeatureToStateMap(device), multidevice_beacon_seeds); remote_devices_.push_back(remote_device);
diff --git a/chromeos/services/device_sync/remote_device_loader_unittest.cc b/chromeos/services/device_sync/remote_device_loader_unittest.cc index 23ccb730..1184d28b 100644 --- a/chromeos/services/device_sync/remote_device_loader_unittest.cc +++ b/chromeos/services/device_sync/remote_device_loader_unittest.cc
@@ -24,6 +24,7 @@ // Prefixes for RemoteDevice fields. const char kDeviceNamePrefix[] = "device"; +const char kNoPiiDeviceNamePrefix[] = "no pii here"; const char kPublicKeyPrefix[] = "pk"; // The id of the user who the remote devices belong to. @@ -42,6 +43,8 @@ cryptauth::ExternalDeviceInfo CreateDeviceInfo(const std::string& suffix) { cryptauth::ExternalDeviceInfo device_info; device_info.set_friendly_device_name(std::string(kDeviceNamePrefix) + suffix); + device_info.set_no_pii_device_name(std::string(kNoPiiDeviceNamePrefix) + + suffix); device_info.set_public_key(std::string(kPublicKeyPrefix) + suffix); device_info.add_beacon_seeds(); cryptauth::BeaconSeed* beacon_seed = device_info.mutable_beacon_seeds(0); @@ -112,6 +115,8 @@ EXPECT_EQ(1u, remote_devices_.size()); EXPECT_FALSE(remote_devices_[0].persistent_symmetric_key.empty()); EXPECT_EQ(device_infos[0].friendly_device_name(), remote_devices_[0].name); + EXPECT_EQ(device_infos[0].no_pii_device_name(), + remote_devices_[0].pii_free_name); EXPECT_EQ(device_infos[0].public_key(), remote_devices_[0].public_key); ASSERT_EQ(1u, remote_devices_[0].beacon_seeds.size());
diff --git a/chromeos/system/dark_resume_controller_unittest.cc b/chromeos/system/dark_resume_controller_unittest.cc index 4a2376cb..e6e90435 100644 --- a/chromeos/system/dark_resume_controller_unittest.cc +++ b/chromeos/system/dark_resume_controller_unittest.cc
@@ -43,7 +43,7 @@ device::mojom::WakeLockReason::kOther, kWakeLockDescription, mojo::MakeRequest(&wake_lock_)); - PowerManagerClient::Initialize(); + PowerManagerClient::InitializeFake(); dark_resume_controller_ = std::make_unique<DarkResumeController>( connector_factory_.GetDefaultConnector());
diff --git a/chromeos/tpm/install_attributes.h b/chromeos/tpm/install_attributes.h index e4fa7b0..d27a4e3f 100644 --- a/chromeos/tpm/install_attributes.h +++ b/chromeos/tpm/install_attributes.h
@@ -16,7 +16,7 @@ #include "base/macros.h" #include "base/memory/weak_ptr.h" #include "base/optional.h" -#include "chromeos/dbus/cryptohome_client.h" +#include "chromeos/dbus/cryptohome/cryptohome_client.h" #include "components/policy/core/common/cloud/cloud_policy_constants.h" namespace chromeos {
diff --git a/chromeos/tpm/install_attributes_unittest.cc b/chromeos/tpm/install_attributes_unittest.cc index 5002a28..b1b0afc 100644 --- a/chromeos/tpm/install_attributes_unittest.cc +++ b/chromeos/tpm/install_attributes_unittest.cc
@@ -15,8 +15,8 @@ #include "base/test/metrics/histogram_tester.h" #include "base/test/scoped_task_environment.h" #include "chromeos/dbus/constants/dbus_paths.h" +#include "chromeos/dbus/cryptohome/cryptohome_client.h" #include "chromeos/dbus/cryptohome/rpc.pb.h" -#include "chromeos/dbus/cryptohome_client.h" #include "chromeos/dbus/dbus_thread_manager.h" #include "chromeos/dbus/util/tpm_util.h" #include "components/policy/proto/install_attributes.pb.h"
diff --git a/chromeos/tpm/tpm_password_fetcher.cc b/chromeos/tpm/tpm_password_fetcher.cc index 32d3b93a..af7f6e1 100644 --- a/chromeos/tpm/tpm_password_fetcher.cc +++ b/chromeos/tpm/tpm_password_fetcher.cc
@@ -9,7 +9,7 @@ #include "base/location.h" #include "base/single_thread_task_runner.h" #include "base/threading/thread_task_runner_handle.h" -#include "chromeos/dbus/cryptohome_client.h" +#include "chromeos/dbus/cryptohome/cryptohome_client.h" #include "chromeos/dbus/dbus_thread_manager.h" namespace chromeos {
diff --git a/chromeos/tpm/tpm_token_info_getter.cc b/chromeos/tpm/tpm_token_info_getter.cc index 7bf6b70..cb1befb 100644 --- a/chromeos/tpm/tpm_token_info_getter.cc +++ b/chromeos/tpm/tpm_token_info_getter.cc
@@ -12,7 +12,7 @@ #include "base/location.h" #include "base/task_runner.h" #include "chromeos/cryptohome/cryptohome_parameters.h" -#include "chromeos/dbus/cryptohome_client.h" +#include "chromeos/dbus/cryptohome/cryptohome_client.h" namespace {
diff --git a/chromeos/tpm/tpm_token_info_getter.h b/chromeos/tpm/tpm_token_info_getter.h index a7163de..4d50510 100644 --- a/chromeos/tpm/tpm_token_info_getter.h +++ b/chromeos/tpm/tpm_token_info_getter.h
@@ -15,7 +15,7 @@ #include "base/memory/weak_ptr.h" #include "base/optional.h" #include "base/time/time.h" -#include "chromeos/dbus/cryptohome_client.h" +#include "chromeos/dbus/cryptohome/cryptohome_client.h" #include "components/account_id/account_id.h" namespace base {
diff --git a/chromeos/tpm/tpm_token_info_getter_unittest.cc b/chromeos/tpm/tpm_token_info_getter_unittest.cc index 83d8c4d8..6de30f50 100644 --- a/chromeos/tpm/tpm_token_info_getter_unittest.cc +++ b/chromeos/tpm/tpm_token_info_getter_unittest.cc
@@ -18,8 +18,8 @@ #include "base/task_runner.h" #include "base/threading/thread_task_runner_handle.h" #include "chromeos/cryptohome/cryptohome_parameters.h" -#include "chromeos/dbus/cryptohome_client.h" -#include "chromeos/dbus/fake_cryptohome_client.h" +#include "chromeos/dbus/cryptohome/cryptohome_client.h" +#include "chromeos/dbus/cryptohome/fake_cryptohome_client.h" #include "chromeos/tpm/tpm_token_info_getter.h" #include "testing/gtest/include/gtest/gtest.h"
diff --git a/chromeos/tpm/tpm_token_loader.h b/chromeos/tpm/tpm_token_loader.h index 9bde6965..e61d642 100644 --- a/chromeos/tpm/tpm_token_loader.h +++ b/chromeos/tpm/tpm_token_loader.h
@@ -17,7 +17,7 @@ #include "base/observer_list.h" #include "base/optional.h" #include "base/threading/thread_checker.h" -#include "chromeos/dbus/cryptohome_client.h" +#include "chromeos/dbus/cryptohome/cryptohome_client.h" #include "chromeos/login/login_state/login_state.h" #include "chromeos/tpm/tpm_token_info_getter.h"
diff --git a/components/arc/disk_quota/arc_disk_quota_bridge.cc b/components/arc/disk_quota/arc_disk_quota_bridge.cc index 2489e90..1973fca5 100644 --- a/components/arc/disk_quota/arc_disk_quota_bridge.cc +++ b/components/arc/disk_quota/arc_disk_quota_bridge.cc
@@ -7,7 +7,7 @@ #include "base/bind.h" #include "base/memory/singleton.h" #include "base/optional.h" -#include "chromeos/dbus/cryptohome_client.h" +#include "chromeos/dbus/cryptohome/cryptohome_client.h" #include "chromeos/dbus/dbus_thread_manager.h" #include "components/arc/arc_bridge_service.h" #include "components/arc/arc_browser_context_keyed_service_factory_base.h"
diff --git a/components/arc/metrics/arc_metrics_service_unittest.cc b/components/arc/metrics/arc_metrics_service_unittest.cc index d838a75..5a4fc58d 100644 --- a/components/arc/metrics/arc_metrics_service_unittest.cc +++ b/components/arc/metrics/arc_metrics_service_unittest.cc
@@ -130,7 +130,7 @@ // Set fake clients for testing. dbus_thread_manager_setter->SetSessionManagerClient( std::make_unique<chromeos::FakeSessionManagerClient>()); - chromeos::PowerManagerClient::Initialize(); + chromeos::PowerManagerClient::InitializeFake(); } ~DBusThreadManagerLifetimeHelper() {
diff --git a/components/arc/power/arc_power_bridge_unittest.cc b/components/arc/power/arc_power_bridge_unittest.cc index 8ca5853..e1aa837 100644 --- a/components/arc/power/arc_power_bridge_unittest.cc +++ b/components/arc/power/arc_power_bridge_unittest.cc
@@ -33,7 +33,7 @@ ~ArcPowerBridgeTest() override = default; void SetUp() override { - chromeos::PowerManagerClient::Initialize(); + chromeos::PowerManagerClient::InitializeFake(); power_manager_client()->set_screen_brightness_percent(kInitialBrightness); wake_lock_provider_ = std::make_unique<device::TestWakeLockProvider>(
diff --git a/components/arc/timer/arc_timer_bridge_unittest.cc b/components/arc/timer/arc_timer_bridge_unittest.cc index 7a6f173..2c9e88c 100644 --- a/components/arc/timer/arc_timer_bridge_unittest.cc +++ b/components/arc/timer/arc_timer_bridge_unittest.cc
@@ -90,7 +90,7 @@ public: ArcTimerTest() : thread_bundle_(content::TestBrowserThreadBundle::IO_MAINLOOP) { - chromeos::PowerManagerClient::Initialize(); + chromeos::PowerManagerClient::InitializeFake(); timer_bridge_ = ArcTimerBridge::GetForBrowserContextForTesting(&context_); // This results in ArcTimerBridge::OnInstanceReady being called. ArcServiceManager::Get()->arc_bridge_service()->timer()->SetInstance(
diff --git a/components/autofill/core/browser/autofill_experiments.cc b/components/autofill/core/browser/autofill_experiments.cc index ffc1f9c..9109282 100644 --- a/components/autofill/core/browser/autofill_experiments.cc +++ b/components/autofill/core/browser/autofill_experiments.cc
@@ -14,6 +14,7 @@ #include "build/build_config.h" #include "components/autofill/core/browser/suggestion.h" #include "components/autofill/core/common/autofill_features.h" +#include "components/autofill/core/common/autofill_payments_features.h" #include "components/autofill/core/common/autofill_prefs.h" #include "components/autofill/core/common/autofill_switches.h" #include "components/prefs/pref_service.h"
diff --git a/components/autofill/core/browser/autofill_experiments_unittest.cc b/components/autofill/core/browser/autofill_experiments_unittest.cc index a23650fb..f8623d50 100644 --- a/components/autofill/core/browser/autofill_experiments_unittest.cc +++ b/components/autofill/core/browser/autofill_experiments_unittest.cc
@@ -6,6 +6,7 @@ #include "base/test/scoped_feature_list.h" #include "components/autofill/core/common/autofill_features.h" +#include "components/autofill/core/common/autofill_payments_features.h" #include "components/autofill/core/common/autofill_prefs.h" #include "components/prefs/pref_registry_simple.h" #include "components/prefs/testing_pref_service.h"
diff --git a/components/autofill/core/browser/autofill_external_delegate.cc b/components/autofill/core/browser/autofill_external_delegate.cc index dca2d40..69e08af 100644 --- a/components/autofill/core/browser/autofill_external_delegate.cc +++ b/components/autofill/core/browser/autofill_external_delegate.cc
@@ -22,7 +22,7 @@ #include "components/autofill/core/browser/autofill_manager.h" #include "components/autofill/core/browser/autofill_metrics.h" #include "components/autofill/core/browser/popup_item_ids.h" -#include "components/autofill/core/common/autofill_features.h" +#include "components/autofill/core/common/autofill_payments_features.h" #include "components/autofill/core/common/autofill_util.h" #include "components/signin/core/browser/signin_metrics.h" #include "components/strings/grit/components_strings.h"
diff --git a/components/autofill/core/browser/autofill_external_delegate_unittest.cc b/components/autofill/core/browser/autofill_external_delegate_unittest.cc index 2ca72f3b..f55b9081 100644 --- a/components/autofill/core/browser/autofill_external_delegate_unittest.cc +++ b/components/autofill/core/browser/autofill_external_delegate_unittest.cc
@@ -25,6 +25,7 @@ #include "components/autofill/core/browser/test_autofill_client.h" #include "components/autofill/core/browser/test_autofill_driver.h" #include "components/autofill/core/common/autofill_features.h" +#include "components/autofill/core/common/autofill_payments_features.h" #include "components/autofill/core/common/autofill_switches.h" #include "components/autofill/core/common/form_data.h" #include "components/autofill/core/common/form_field_data.h"
diff --git a/components/autofill/core/browser/autofill_manager.cc b/components/autofill/core/browser/autofill_manager.cc index dcc247b..b2200008 100644 --- a/components/autofill/core/browser/autofill_manager.cc +++ b/components/autofill/core/browser/autofill_manager.cc
@@ -65,6 +65,7 @@ #include "components/autofill/core/common/autofill_constants.h" #include "components/autofill/core/common/autofill_data_validation.h" #include "components/autofill/core/common/autofill_features.h" +#include "components/autofill/core/common/autofill_payments_features.h" #include "components/autofill/core/common/autofill_prefs.h" #include "components/autofill/core/common/autofill_switches.h" #include "components/autofill/core/common/autofill_util.h"
diff --git a/components/autofill/core/browser/autofill_manager_unittest.cc b/components/autofill/core/browser/autofill_manager_unittest.cc index ab993477..c0d504d 100644 --- a/components/autofill/core/browser/autofill_manager_unittest.cc +++ b/components/autofill/core/browser/autofill_manager_unittest.cc
@@ -54,6 +54,7 @@ #include "components/autofill/core/browser/webdata/autofill_webdata_service.h" #include "components/autofill/core/common/autofill_clock.h" #include "components/autofill/core/common/autofill_features.h" +#include "components/autofill/core/common/autofill_payments_features.h" #include "components/autofill/core/common/autofill_prefs.h" #include "components/autofill/core/common/autofill_switches.h" #include "components/autofill/core/common/autofill_util.h"
diff --git a/components/autofill/core/browser/form_data_importer.cc b/components/autofill/core/browser/form_data_importer.cc index 15e57a1..acc03e5 100644 --- a/components/autofill/core/browser/form_data_importer.cc +++ b/components/autofill/core/browser/form_data_importer.cc
@@ -31,6 +31,7 @@ #include "components/autofill/core/browser/phone_number_i18n.h" #include "components/autofill/core/browser/validation.h" #include "components/autofill/core/common/autofill_features.h" +#include "components/autofill/core/common/autofill_payments_features.h" #include "components/autofill/core/common/autofill_util.h" namespace autofill {
diff --git a/components/autofill/core/browser/form_data_importer_unittest.cc b/components/autofill/core/browser/form_data_importer_unittest.cc index 00280a55..86a77ae3 100644 --- a/components/autofill/core/browser/form_data_importer_unittest.cc +++ b/components/autofill/core/browser/form_data_importer_unittest.cc
@@ -38,6 +38,7 @@ #include "components/autofill/core/browser/webdata/autofill_webdata_service.h" #include "components/autofill/core/common/autofill_constants.h" #include "components/autofill/core/common/autofill_features.h" +#include "components/autofill/core/common/autofill_payments_features.h" #include "components/autofill/core/common/autofill_prefs.h" #include "components/autofill/core/common/autofill_switches.h" #include "components/autofill/core/common/autofill_util.h"
diff --git a/components/autofill/core/browser/payments/credit_card_save_manager.cc b/components/autofill/core/browser/payments/credit_card_save_manager.cc index d61ac32e..e896f52 100644 --- a/components/autofill/core/browser/payments/credit_card_save_manager.cc +++ b/components/autofill/core/browser/payments/credit_card_save_manager.cc
@@ -42,6 +42,7 @@ #include "components/autofill/core/common/autofill_clock.h" #include "components/autofill/core/common/autofill_constants.h" #include "components/autofill/core/common/autofill_features.h" +#include "components/autofill/core/common/autofill_payments_features.h" #include "components/autofill/core/common/autofill_util.h" #include "services/identity/public/cpp/identity_manager.h" #include "url/gurl.h"
diff --git a/components/autofill/core/browser/payments/credit_card_save_manager_unittest.cc b/components/autofill/core/browser/payments/credit_card_save_manager_unittest.cc index 28a19571..3e21079d 100644 --- a/components/autofill/core/browser/payments/credit_card_save_manager_unittest.cc +++ b/components/autofill/core/browser/payments/credit_card_save_manager_unittest.cc
@@ -43,6 +43,7 @@ #include "components/autofill/core/browser/webdata/autofill_webdata_service.h" #include "components/autofill/core/common/autofill_clock.h" #include "components/autofill/core/common/autofill_features.h" +#include "components/autofill/core/common/autofill_payments_features.h" #include "components/autofill/core/common/autofill_prefs.h" #include "components/autofill/core/common/form_data.h" #include "components/autofill/core/common/form_field_data.h"
diff --git a/components/autofill/core/browser/payments/local_card_migration_manager.cc b/components/autofill/core/browser/payments/local_card_migration_manager.cc index 682ea01f..b83dd82 100644 --- a/components/autofill/core/browser/payments/local_card_migration_manager.cc +++ b/components/autofill/core/browser/payments/local_card_migration_manager.cc
@@ -22,6 +22,7 @@ #include "components/autofill/core/browser/payments/payments_util.h" #include "components/autofill/core/browser/personal_data_manager.h" #include "components/autofill/core/common/autofill_features.h" +#include "components/autofill/core/common/autofill_payments_features.h" #include "components/autofill/core/common/autofill_prefs.h" #include "services/identity/public/cpp/identity_manager.h"
diff --git a/components/autofill/core/browser/payments/local_card_migration_manager_unittest.cc b/components/autofill/core/browser/payments/local_card_migration_manager_unittest.cc index 2dc5cf0f..1cd6be1 100644 --- a/components/autofill/core/browser/payments/local_card_migration_manager_unittest.cc +++ b/components/autofill/core/browser/payments/local_card_migration_manager_unittest.cc
@@ -42,6 +42,7 @@ #include "components/autofill/core/browser/webdata/autofill_webdata_service.h" #include "components/autofill/core/common/autofill_clock.h" #include "components/autofill/core/common/autofill_features.h" +#include "components/autofill/core/common/autofill_payments_features.h" #include "components/autofill/core/common/autofill_prefs.h" #include "components/autofill/core/common/form_data.h" #include "components/autofill/core/common/form_field_data.h"
diff --git a/components/autofill/core/browser/payments/payments_client.cc b/components/autofill/core/browser/payments/payments_client.cc index 0fd0b85..a4f1fb5 100644 --- a/components/autofill/core/browser/payments/payments_client.cc +++ b/components/autofill/core/browser/payments/payments_client.cc
@@ -27,6 +27,7 @@ #include "components/autofill/core/browser/payments/payments_request.h" #include "components/autofill/core/browser/payments/payments_service_url.h" #include "components/autofill/core/common/autofill_features.h" +#include "components/autofill/core/common/autofill_payments_features.h" #include "components/data_use_measurement/core/data_use_user_data.h" #include "components/variations/net/variations_http_headers.h" #include "net/base/escape.h"
diff --git a/components/autofill/core/browser/payments/payments_client_unittest.cc b/components/autofill/core/browser/payments/payments_client_unittest.cc index 12bdabf..819bada1 100644 --- a/components/autofill/core/browser/payments/payments_client_unittest.cc +++ b/components/autofill/core/browser/payments/payments_client_unittest.cc
@@ -22,6 +22,7 @@ #include "components/autofill/core/browser/payments/payments_client.h" #include "components/autofill/core/browser/test_personal_data_manager.h" #include "components/autofill/core/common/autofill_features.h" +#include "components/autofill/core/common/autofill_payments_features.h" #include "components/autofill/core/common/autofill_switches.h" #include "components/prefs/pref_registry_simple.h" #include "components/prefs/testing_pref_service.h"
diff --git a/components/autofill/core/browser/payments/payments_util.cc b/components/autofill/core/browser/payments/payments_util.cc index 51beb60..5f99b8d 100644 --- a/components/autofill/core/browser/payments/payments_util.cc +++ b/components/autofill/core/browser/payments/payments_util.cc
@@ -11,6 +11,7 @@ #include "components/autofill/core/browser/payments/payments_customer_data.h" #include "components/autofill/core/browser/personal_data_manager.h" #include "components/autofill/core/common/autofill_features.h" +#include "components/autofill/core/common/autofill_payments_features.h" #include "components/autofill/core/common/autofill_prefs.h" #include "components/prefs/pref_service.h"
diff --git a/components/autofill/core/browser/payments/payments_util_unittest.cc b/components/autofill/core/browser/payments/payments_util_unittest.cc index 9ce775c..e461f6f 100644 --- a/components/autofill/core/browser/payments/payments_util_unittest.cc +++ b/components/autofill/core/browser/payments/payments_util_unittest.cc
@@ -10,6 +10,7 @@ #include "components/autofill/core/browser/payments/payments_customer_data.h" #include "components/autofill/core/browser/test_personal_data_manager.h" #include "components/autofill/core/common/autofill_features.h" +#include "components/autofill/core/common/autofill_payments_features.h" #include "components/autofill/core/common/autofill_prefs.h" #include "components/prefs/pref_registry_simple.h" #include "components/prefs/testing_pref_service.h"
diff --git a/components/autofill/core/browser/payments/test_local_card_migration_manager.cc b/components/autofill/core/browser/payments/test_local_card_migration_manager.cc index 34577f8..4fd2f67 100644 --- a/components/autofill/core/browser/payments/test_local_card_migration_manager.cc +++ b/components/autofill/core/browser/payments/test_local_card_migration_manager.cc
@@ -6,7 +6,7 @@ #include "components/autofill/core/browser/autofill_metrics.h" #include "components/autofill/core/browser/payments/test_payments_client.h" -#include "components/autofill/core/common/autofill_features.h" +#include "components/autofill/core/common/autofill_payments_features.h" #include "components/autofill/core/common/autofill_prefs.h" namespace autofill {
diff --git a/components/autofill/core/browser/webdata/autofill_profile_sync_bridge.cc b/components/autofill/core/browser/webdata/autofill_profile_sync_bridge.cc index a5047b4..961972e 100644 --- a/components/autofill/core/browser/webdata/autofill_profile_sync_bridge.cc +++ b/components/autofill/core/browser/webdata/autofill_profile_sync_bridge.cc
@@ -128,6 +128,7 @@ &initial_sync_tracker, AutofillProfileSyncChangeOrigin::kInitial)); + web_data_backend_->CommitChanges(); web_data_backend_->NotifyThatSyncHasStarted(syncer::AUTOFILL_PROFILE); return base::nullopt; } @@ -157,8 +158,12 @@ } } - return FlushSyncTracker(std::move(metadata_change_list), &tracker, - AutofillProfileSyncChangeOrigin::kIncrementalRemote); + RETURN_IF_ERROR( + FlushSyncTracker(std::move(metadata_change_list), &tracker, + AutofillProfileSyncChangeOrigin::kIncrementalRemote)); + + web_data_backend_->CommitChanges(); + return base::nullopt; } void AutofillProfileSyncBridge::GetData(StorageKeyList storage_keys, @@ -267,6 +272,11 @@ break; } + // We do not need to commit any local changes (written by the processor via + // the metadata change list) because the open WebDatabase transaction is + // committed by the AutofillWebDataService when the original local write + // operation (that triggered this notification to the bridge) finishes. + if (Optional<ModelError> error = metadata_change_list->TakeError()) { change_processor()->ReportError(*error); }
diff --git a/components/autofill/core/browser/webdata/autofill_profile_sync_bridge_unittest.cc b/components/autofill/core/browser/webdata/autofill_profile_sync_bridge_unittest.cc index 08e50b60..8a29f61e 100644 --- a/components/autofill/core/browser/webdata/autofill_profile_sync_bridge_unittest.cc +++ b/components/autofill/core/browser/webdata/autofill_profile_sync_bridge_unittest.cc
@@ -342,6 +342,9 @@ EXPECT_CALL( mock_processor(), Put(kGuidA, HasSpecifics(CreateAutofillProfileSpecifics(local)), _)); + // The bridge does not need to commit when reacting to a notification about a + // local change. + EXPECT_CALL(*backend(), CommitChanges()).Times(0); bridge()->AutofillProfileChanged(change); } @@ -358,6 +361,9 @@ EXPECT_CALL( mock_processor(), Put(kGuidA, HasSpecifics(CreateAutofillProfileSpecifics(local)), _)); + // The bridge does not need to commit when reacting to a notification about a + // local change. + EXPECT_CALL(*backend(), CommitChanges()).Times(0); bridge()->AutofillProfileChanged(change); } @@ -374,6 +380,9 @@ EXPECT_CALL( mock_processor(), Put(kGuidA, HasSpecifics(CreateAutofillProfileSpecifics(local)), _)); + // The bridge does not need to commit when reacting to a notification about a + // local change. + EXPECT_CALL(*backend(), CommitChanges()).Times(0); bridge()->AutofillProfileChanged(change); } @@ -389,6 +398,9 @@ EXPECT_CALL( mock_processor(), Put(kGuidA, HasSpecifics(CreateAutofillProfileSpecifics(local)), _)); + // The bridge does not need to commit when reacting to a notification about a + // local change. + EXPECT_CALL(*backend(), CommitChanges()).Times(0); bridge()->AutofillProfileChanged(change); } @@ -417,6 +429,9 @@ EXPECT_CALL( mock_processor(), Put(kGuidA, HasSpecifics(CreateAutofillProfileSpecifics(local)), _)); + // The bridge does not need to commit when reacting to a notification about a + // local change. + EXPECT_CALL(*backend(), CommitChanges()).Times(0); bridge()->AutofillProfileChanged(change); } @@ -440,6 +455,9 @@ AutofillProfileChange change(AutofillProfileChange::REMOVE, kGuidB, nullptr); EXPECT_CALL(mock_processor(), Delete(kGuidB, _)); + // The bridge does not need to commit when reacting to a notification about a + // local change. + EXPECT_CALL(*backend(), CommitChanges()).Times(0); bridge()->AutofillProfileChanged(change); } @@ -503,6 +521,7 @@ mock_processor(), Put(kGuidA, HasSpecifics(CreateAutofillProfileSpecifics(local1)), _)); EXPECT_CALL(mock_processor(), Delete(_, _)).Times(0); + EXPECT_CALL(*backend(), CommitChanges()); StartSyncing({remote1, remote2, remote3}); @@ -521,6 +540,8 @@ // This complete profile is fully uploaded to sync. EXPECT_CALL(mock_processor(), Put(_, HasSpecifics(ConstructCompleteSpecifics()), _)); + EXPECT_CALL(*backend(), CommitChanges()); + StartSyncing({}); // No changes locally. @@ -531,6 +552,7 @@ // the client (and nothing gets uploaded back). TEST_F(AutofillProfileSyncBridgeTest, MergeSyncData_SyncAllFieldsToClient) { EXPECT_CALL(mock_processor(), Put(_, _, _)).Times(0); + EXPECT_CALL(*backend(), CommitChanges()); StartSyncing({ConstructCompleteSpecifics()}); EXPECT_THAT(GetAllLocalData(), @@ -562,6 +584,7 @@ AutofillProfileSpecifics merged2(remote2); merged2.set_origin(kSettingsOrigin); EXPECT_CALL(mock_processor(), Put(kGuidD, HasSpecifics(merged2), _)); + EXPECT_CALL(*backend(), CommitChanges()); StartSyncing({remote1, remote2}); @@ -595,6 +618,7 @@ mock_processor(), Put(kGuidA, HasSpecifics(CreateAutofillProfileSpecifics(local)), _)); EXPECT_CALL(mock_processor(), Delete(_, _)).Times(0); + EXPECT_CALL(*backend(), CommitChanges()); StartSyncing({remote}); @@ -646,6 +670,7 @@ mock_processor(), Put(kGuidB, HasSpecifics(CreateAutofillProfileSpecifics(local2)), _)); EXPECT_CALL(mock_processor(), Delete(_, _)).Times(0); + EXPECT_CALL(*backend(), CommitChanges()); StartSyncing({remote1, remote2}); @@ -680,6 +705,7 @@ merged.set_use_date(30); merged.add_phone_home_whole_number("650234567"); EXPECT_CALL(mock_processor(), Put(kGuidB, HasSpecifics(merged), _)); + EXPECT_CALL(*backend(), CommitChanges()); StartSyncing({remote}); } @@ -703,6 +729,7 @@ AutofillProfileSpecifics merged(remote); merged.add_phone_home_whole_number("650234567"); EXPECT_CALL(mock_processor(), Put(kGuidB, HasSpecifics(merged), _)); + EXPECT_CALL(*backend(), CommitChanges()); StartSyncing({remote}); } @@ -726,6 +753,7 @@ merged.set_use_count(12); merged.add_phone_home_whole_number("650234567"); EXPECT_CALL(mock_processor(), Put(kGuidB, HasSpecifics(merged), _)); + EXPECT_CALL(*backend(), CommitChanges()); StartSyncing({remote}); } @@ -751,6 +779,7 @@ // explicitly covered by previous tests but happens. merged.set_address_home_language_code(""); EXPECT_CALL(mock_processor(), Put(kGuidB, HasSpecifics(merged), _)); + EXPECT_CALL(*backend(), CommitChanges()); StartSyncing({remote}); } @@ -770,6 +799,7 @@ // Expect no sync events to add origin to the remote data. EXPECT_CALL(mock_processor(), Put(_, _, _)).Times(0); + EXPECT_CALL(*backend(), CommitChanges()); StartSyncing({remote}); // Expect the local autofill profile to still have an origin after sync. @@ -795,6 +825,7 @@ ASSERT_FALSE(remote.has_origin()); EXPECT_CALL(mock_processor(), Put(_, _, _)).Times(0); + EXPECT_CALL(*backend(), CommitChanges()); StartSyncing({remote}); EXPECT_THAT(GetAllLocalData(), ElementsAre(local)); } @@ -811,6 +842,7 @@ EXPECT_CALL(mock_processor(), Put(_, _, _)).Times(0); EXPECT_CALL(mock_processor(), Delete(_, _)).Times(0); + EXPECT_CALL(*backend(), CommitChanges()); ApplySyncChanges( {EntityChange::CreateDelete(kGuidA), @@ -829,6 +861,7 @@ CreateAutofillProfileSpecifics(kGuidInvalid, std::string()); EXPECT_CALL(mock_processor(), Put(_, _, _)).Times(0); + EXPECT_CALL(*backend(), CommitChanges()); ApplySyncChanges( {EntityChange::CreateAdd(kGuidA, SpecificsToEntity(remote_valid)), EntityChange::CreateAdd(kGuidInvalid, @@ -888,6 +921,7 @@ remote.set_address_home_street_address( "456 El Camino Real\n" "Suite #1337"); + EXPECT_CALL(*backend(), CommitChanges()); StartSyncing({remote}); @@ -922,6 +956,7 @@ // No update to sync, no change in local data. EXPECT_CALL(mock_processor(), Put(_, _, _)).Times(0); + EXPECT_CALL(*backend(), CommitChanges()); StartSyncing({remote}); EXPECT_THAT(GetAllLocalData(), ElementsAre(local)); } @@ -940,6 +975,7 @@ // No update to sync, no change in local data. EXPECT_CALL(mock_processor(), Put(_, _, _)).Times(0); + EXPECT_CALL(*backend(), CommitChanges()); StartSyncing({remote}); EXPECT_THAT(GetAllLocalData(), ElementsAre(local)); } @@ -958,6 +994,7 @@ // No update to sync, remote language code overwrites the empty local one. EXPECT_CALL(mock_processor(), Put(_, _, _)).Times(0); + EXPECT_CALL(*backend(), CommitChanges()); StartSyncing({remote}); EXPECT_THAT(GetAllLocalData(), ElementsAre(CreateAutofillProfile(remote))); } @@ -976,6 +1013,7 @@ // No update to sync, remote language code overwrites the local one. EXPECT_CALL(mock_processor(), Put(_, _, _)).Times(0); + EXPECT_CALL(*backend(), CommitChanges()); StartSyncing({remote}); EXPECT_THAT(GetAllLocalData(), ElementsAre(CreateAutofillProfile(remote))); } @@ -1001,6 +1039,7 @@ // No update to sync, remote language code overwrites the local one. EXPECT_CALL(mock_processor(), Put(_, _, _)).Times(0); + EXPECT_CALL(*backend(), CommitChanges()); StartSyncing({remote}); EXPECT_THAT(GetAllLocalData(), ElementsAre(merged)); } @@ -1021,6 +1060,7 @@ // No update to sync, no change in local data. EXPECT_CALL(mock_processor(), Put(_, _, _)).Times(0); + EXPECT_CALL(*backend(), CommitChanges()); StartSyncing({remote}); EXPECT_THAT(GetAllLocalData(), ElementsAre(local)); } @@ -1040,6 +1080,7 @@ // No update to sync, the validity bitfield should be stored to local. EXPECT_CALL(mock_processor(), Put(_, _, _)).Times(0); + EXPECT_CALL(*backend(), CommitChanges()); StartSyncing({remote}); EXPECT_THAT(GetAllLocalData(), ElementsAre(CreateAutofillProfile(remote))); } @@ -1059,6 +1100,7 @@ // No update to sync, the remote validity bitfield should overwrite local. EXPECT_CALL(mock_processor(), Put(_, _, _)).Times(0); + EXPECT_CALL(*backend(), CommitChanges()); StartSyncing({remote}); EXPECT_THAT(GetAllLocalData(), ElementsAre(CreateAutofillProfile(remote))); } @@ -1083,6 +1125,7 @@ // No update to sync, the local validity bitfield should stay untouched. EXPECT_CALL(mock_processor(), Put(_, _, _)).Times(0); + EXPECT_CALL(*backend(), CommitChanges()); StartSyncing({remote}); EXPECT_THAT(GetAllLocalData(), ElementsAre(merged)); } @@ -1102,6 +1145,7 @@ // No update to sync, no change in local data. EXPECT_CALL(mock_processor(), Put(_, _, _)).Times(0); + EXPECT_CALL(*backend(), CommitChanges()); StartSyncing({remote}); EXPECT_THAT(GetAllLocalData(), ElementsAre(local)); } @@ -1128,6 +1172,7 @@ // No update to sync, no change in local data. EXPECT_CALL(mock_processor(), Put(_, _, _)).Times(0); + EXPECT_CALL(*backend(), CommitChanges()); StartSyncing({remote}); EXPECT_THAT(GetAllLocalData(), ElementsAre(merged)); } @@ -1151,6 +1196,7 @@ // No update to sync, no change in local data. EXPECT_CALL(mock_processor(), Put(_, _, _)).Times(0); + EXPECT_CALL(*backend(), CommitChanges()); StartSyncing({remote}); EXPECT_THAT(GetAllLocalData(), ElementsAre(WithUsageStats(local))); } @@ -1203,6 +1249,7 @@ // Expect no changes to remote data. EXPECT_CALL(mock_processor(), Put(_, _, _)).Times(0); + EXPECT_CALL(*backend(), CommitChanges()); StartSyncing({remote}); EXPECT_THAT(GetAllLocalData(), ElementsAre(WithUsageStats(merged)));
diff --git a/components/autofill/core/common/BUILD.gn b/components/autofill/core/common/BUILD.gn index 0ff74d6c..fc144ea0 100644 --- a/components/autofill/core/common/BUILD.gn +++ b/components/autofill/core/common/BUILD.gn
@@ -15,6 +15,8 @@ "autofill_features.h", "autofill_l10n_util.cc", "autofill_l10n_util.h", + "autofill_payments_features.cc", + "autofill_payments_features.h", "autofill_prefs.cc", "autofill_prefs.h", "autofill_regex_constants.cc",
diff --git a/components/autofill/core/common/OWNERS b/components/autofill/core/common/OWNERS index 1b519b82..219017c1 100644 --- a/components/autofill/core/common/OWNERS +++ b/components/autofill/core/common/OWNERS
@@ -1,3 +1,5 @@ per-file *password*=dvadym@chromium.org per-file *password*=kolos@chromium.org per-file *password*=vasilii@chromium.org + +per-file autofill_payments_features.*=file://components/autofill/core/browser/payments/OWNERS
diff --git a/components/autofill/core/common/autofill_features.cc b/components/autofill/core/common/autofill_features.cc index 5c8ef56..816c180 100644 --- a/components/autofill/core/common/autofill_features.cc +++ b/components/autofill/core/common/autofill_features.cc
@@ -52,31 +52,15 @@ const base::Feature kAutofillCreateDataForTest{ "AutofillCreateDataForTest", base::FEATURE_DISABLED_BY_DEFAULT}; -const base::Feature kAutofillCreditCardAblationExperiment{ - "AutofillCreditCardAblationExperiment", base::FEATURE_DISABLED_BY_DEFAULT}; - const base::Feature kAutofillCreditCardAssist{ "AutofillCreditCardAssist", base::FEATURE_DISABLED_BY_DEFAULT}; -const base::Feature kAutofillCreditCardLocalCardMigration{ - "AutofillCreditCardLocalCardMigration", base::FEATURE_DISABLED_BY_DEFAULT}; - const base::Feature kAutofillDeleteDisusedAddresses{ "AutofillDeleteDisusedAddresses", base::FEATURE_ENABLED_BY_DEFAULT}; const base::Feature kAutofillDeleteDisusedCreditCards{ "AutofillDeleteDisusedCreditCards", base::FEATURE_ENABLED_BY_DEFAULT}; -const base::Feature kAutofillDoNotUploadSaveUnsupportedCards{ - "AutofillDoNotUploadSaveUnsupportedCards", - base::FEATURE_DISABLED_BY_DEFAULT}; - -// Controls whether the credit card downstream keyboard accessory shows -// the Google Pay logo animation on iOS. -const base::Feature kAutofillDownstreamUseGooglePayBrandingOniOS{ - "AutofillDownstreamUseGooglePayBrandingOniOS", - base::FEATURE_DISABLED_BY_DEFAULT}; - // Controls whether Autofill attemps to fill dynamically changing forms. const base::Feature kAutofillDynamicForms{"AutofillDynamicForms", base::FEATURE_ENABLED_BY_DEFAULT}; @@ -100,22 +84,6 @@ const base::Feature kAutofillEnableIFrameSupportOniOS{ "AutofillEnableIFrameSupportOniOS", base::FEATURE_ENABLED_BY_DEFAULT}; -// When enabled, enable local card migration flow for user who has signed in but -// has not turned on sync. -const base::Feature kAutofillEnableLocalCardMigrationForNonSyncUser{ - "AutofillEnableLocalCardMigrationForNonSyncUser", - base::FEATURE_DISABLED_BY_DEFAULT}; - -// When enabled, Autofill data related icons will be shown in the status -// chip in toolbar along with the avatar toolbar button. -const base::Feature kAutofillEnableToolbarStatusChip{ - "AutofillEnableToolbarStatusChip", base::FEATURE_DISABLED_BY_DEFAULT}; - -// When enabled, no local copy of server card will be saved when upload -// succeeds. -const base::Feature kAutofillNoLocalSaveOnUploadSuccess{ - "AutofillNoLocalSaveOnUploadSuccess", base::FEATURE_DISABLED_BY_DEFAULT}; - // When enabled, autofill server will override field types with rater // consensus data before returning to client. const base::Feature kAutofillOverrideWithRaterConsensus{ @@ -144,30 +112,11 @@ const base::Feature kAutofillGetPaymentsIdentityFromSync{ "AutofillGetPaymentsIdentityFromSync", base::FEATURE_DISABLED_BY_DEFAULT}; -// When enabled, a credit card form that is hidden after receiving input can -// import the card. -const base::Feature kAutofillImportNonFocusableCreditCardForms{ - "AutofillImportNonFocusableCreditCardForms", - base::FEATURE_DISABLED_BY_DEFAULT}; - // When enabled, autofill suggestions are displayed in the keyboard accessory // instead of the regular popup. const base::Feature kAutofillKeyboardAccessory{ "AutofillKeyboardAccessory", base::FEATURE_DISABLED_BY_DEFAULT}; -// When enabled, the local card migration dialog will show the progress -// and result of the migration after starting the migration. When disabled, -// there is no feedback for the migration. -const base::Feature kAutofillLocalCardMigrationShowFeedback{ - "AutofillLocalCardMigrationShowFeedback", - base::FEATURE_DISABLED_BY_DEFAULT}; - -// Controls whether offering to migrate cards will consider data from the -// Autofill strike database (new version). -const base::Feature kAutofillLocalCardMigrationUsesStrikeSystemV2{ - "AutofillLocalCardMigrationUsesStrikeSystemV2", - base::FEATURE_DISABLED_BY_DEFAULT}; - // Controls whether the manual fallback will be present. const base::Feature kAutofillManualFallback{"AutofillManualFallback", base::FEATURE_DISABLED_BY_DEFAULT}; @@ -213,42 +162,6 @@ "AutofillSaveCardDialogUnlabeledExpirationDate", base::FEATURE_ENABLED_BY_DEFAULT}; -// When enabled, local and upload credit card save dialogs will be updated to -// new M72 guidelines, including a [No thanks] cancel button and an extended -// title string. -const base::Feature kAutofillSaveCardImprovedUserConsent{ - "AutofillSaveCardImprovedUserConsent", base::FEATURE_DISABLED_BY_DEFAULT}; - -// When enabled, a sign in promo will show up right after the user -// saves a card locally. This also introduces a "Manage Cards" bubble. -const base::Feature kAutofillSaveCardSignInAfterLocalSave{ - "AutofillSaveCardSignInAfterLocalSave", base::FEATURE_ENABLED_BY_DEFAULT}; - -// Controls whether offering to save cards will consider data from the Autofill -// strike database. -const base::Feature kAutofillSaveCreditCardUsesStrikeSystem{ - "AutofillSaveCreditCardUsesStrikeSystem", - base::FEATURE_DISABLED_BY_DEFAULT}; - -// Controls whether offering to save cards will consider data from the Autofill -// strike database (new version). -const base::Feature kAutofillSaveCreditCardUsesStrikeSystemV2{ - "AutofillSaveCreditCardUsesStrikeSystemV2", - base::FEATURE_DISABLED_BY_DEFAULT}; - -// Controls whether experiment ids should be sent through -// Google Payments RPCs or not. -const base::Feature kAutofillSendExperimentIdsInPaymentsRPCs{ - "AutofillSendExperimentIdsInPaymentsRPCs", - base::FEATURE_ENABLED_BY_DEFAULT}; - -// If enabled, only countries of recently-used addresses are sent in the -// GetUploadDetails call to Payments. If disabled, whole recently-used addresses -// are sent. -const base::Feature kAutofillSendOnlyCountryInGetUploadDetails{ - "AutofillSendOnlyCountryInGetUploadDetails", - base::FEATURE_ENABLED_BY_DEFAULT}; - // Enables or Disables (mostly for hermetic testing) autofill server // communication. The URL of the autofill server can further be controlled via // the autofill-server-url param. The given URL should specify the complete @@ -307,45 +220,10 @@ const base::Feature kAutofillUploadThrottling{"AutofillUploadThrottling", base::FEATURE_ENABLED_BY_DEFAULT}; -const base::Feature kAutofillUpstream{"AutofillUpstream", - base::FEATURE_DISABLED_BY_DEFAULT}; - -const base::Feature kAutofillUpstreamAllowAllEmailDomains{ - "AutofillUpstreamAllowAllEmailDomains", base::FEATURE_DISABLED_BY_DEFAULT}; - -const base::Feature kAutofillUpstreamAlwaysRequestCardholderName{ - "AutofillUpstreamAlwaysRequestCardholderName", - base::FEATURE_DISABLED_BY_DEFAULT}; - -const base::Feature kAutofillUpstreamBlankCardholderNameField{ - "AutofillUpstreamBlankCardholderNameField", - base::FEATURE_DISABLED_BY_DEFAULT}; - -// Controls whether ELO cards should be uploaded to Google Payments. -const base::Feature kAutofillUpstreamDisallowElo{ - "AutofillUpstreamDisallowElo", base::FEATURE_DISABLED_BY_DEFAULT}; - -// Controls whether JCB cards should be uploaded to Google Payments. -const base::Feature kAutofillUpstreamDisallowJcb{ - "AutofillUpstreamDisallowJcb", base::FEATURE_DISABLED_BY_DEFAULT}; - -const base::Feature kAutofillUpstreamEditableCardholderName{ - "AutofillUpstreamEditableCardholderName", - base::FEATURE_DISABLED_BY_DEFAULT}; - -const base::Feature kAutofillUpstreamEditableExpirationDate{ - "AutofillUpstreamEditableExpirationDate", - base::FEATURE_DISABLED_BY_DEFAULT}; - // Controls whether to use the API or use the legacy server. const base::Feature kAutofillUseApi{"AutofillUseApi", base::FEATURE_DISABLED_BY_DEFAULT}; -// Controls whether the PaymentsCustomerData is used to make requests to -// Google Payments. -const base::Feature kAutofillUsePaymentsCustomerData{ - "AutofillUsePaymentsCustomerData", base::FEATURE_ENABLED_BY_DEFAULT}; - // Controls whether password generation is offered automatically on fields // perceived as eligible for generation. #if defined(OS_ANDROID) @@ -356,13 +234,6 @@ "AutomaticPasswordGeneration", base::FEATURE_ENABLED_BY_DEFAULT}; #endif -const char kAutofillCreditCardLocalCardMigrationParameterName[] = "variant"; - -const char kAutofillCreditCardLocalCardMigrationParameterWithoutSettingsPage[] = - "without-settings-page"; - -const char kCreditCardSigninPromoImpressionLimitParamKey[] = "impression_limit"; - #if defined(OS_ANDROID) // Controls whether the Autofill manual fallback for Addresses and Payments is // present on Android. @@ -382,35 +253,6 @@ #endif } -LocalCardMigrationExperimentalFlag GetLocalCardMigrationExperimentalFlag() { - if (!base::FeatureList::IsEnabled(kAutofillCreditCardLocalCardMigration)) - return LocalCardMigrationExperimentalFlag::kMigrationDisabled; - - std::string param = base::GetFieldTrialParamValueByFeature( - kAutofillCreditCardLocalCardMigration, - kAutofillCreditCardLocalCardMigrationParameterName); - - if (param == - kAutofillCreditCardLocalCardMigrationParameterWithoutSettingsPage) { - return LocalCardMigrationExperimentalFlag::kMigrationWithoutSettingsPage; - } - return LocalCardMigrationExperimentalFlag::kMigrationIncludeSettingsPage; -} - -bool IsAutofillUpstreamAlwaysRequestCardholderNameExperimentEnabled() { - return base::FeatureList::IsEnabled( - features::kAutofillUpstreamAlwaysRequestCardholderName); -} - -bool IsAutofillUpstreamBlankCardholderNameFieldExperimentEnabled() { - return base::FeatureList::IsEnabled( - features::kAutofillUpstreamBlankCardholderNameField); -} - -bool IsAutofillUpstreamEditableCardholderNameExperimentEnabled() { - return base::FeatureList::IsEnabled(kAutofillUpstreamEditableCardholderName); -} - bool IsPasswordManualFallbackEnabled() { return base::FeatureList::IsEnabled(kAutofillManualFallback); }
diff --git a/components/autofill/core/common/autofill_features.h b/components/autofill/core/common/autofill_features.h index bccb13e..2a1d3f4 100644 --- a/components/autofill/core/common/autofill_features.h +++ b/components/autofill/core/common/autofill_features.h
@@ -28,32 +28,22 @@ extern const base::Feature kAutofillAlwaysShowServerCardsInSyncTransport; extern const base::Feature kAutofillCacheQueryResponses; extern const base::Feature kAutofillCreateDataForTest; -extern const base::Feature kAutofillCreditCardAblationExperiment; extern const base::Feature kAutofillCreditCardAssist; -extern const base::Feature kAutofillCreditCardLocalCardMigration; extern const base::Feature kAutofillDeleteDisusedAddresses; extern const base::Feature kAutofillDeleteDisusedCreditCards; -extern const base::Feature kAutofillDoNotUploadSaveUnsupportedCards; -extern const base::Feature kAutofillDownstreamUseGooglePayBrandingOniOS; extern const base::Feature kAutofillDynamicForms; extern const base::Feature kAutofillEnableAccountWalletStorage; extern const base::Feature kAutofillEnableAccountWalletStorageUpload; extern const base::Feature kAutofillEnableCompanyName; extern const base::Feature kAutofillEnableIFrameSupportOniOS; -extern const base::Feature kAutofillEnableLocalCardMigrationForNonSyncUser; -extern const base::Feature kAutofillEnableToolbarStatusChip; extern const base::Feature kAutofillEnforceMinRequiredFieldsForHeuristics; extern const base::Feature kAutofillEnforceMinRequiredFieldsForQuery; extern const base::Feature kAutofillEnforceMinRequiredFieldsForUpload; extern const base::Feature kAutofillGetPaymentsIdentityFromSync; -extern const base::Feature kAutofillImportNonFocusableCreditCardForms; extern const base::Feature kAutofillKeyboardAccessory; -extern const base::Feature kAutofillLocalCardMigrationShowFeedback; -extern const base::Feature kAutofillLocalCardMigrationUsesStrikeSystemV2; extern const base::Feature kAutofillManualFallback; extern const base::Feature kAutofillManualFallbackPhaseTwo; extern const base::Feature kAutofillMetadataUploads; -extern const base::Feature kAutofillNoLocalSaveOnUploadSuccess; extern const base::Feature kAutofillOverrideWithRaterConsensus; extern const base::Feature kAutofillPreferServerNamePredictions; extern const base::Feature kAutofillPrefilledFields; @@ -61,13 +51,7 @@ extern const base::Feature kAutofillRestrictUnownedFieldsToFormlessCheckout; extern const base::Feature kAutofillRichMetadataQueries; extern const base::Feature kAutofillSaveCardDialogUnlabeledExpirationDate; -extern const base::Feature kAutofillSaveCardImprovedUserConsent; -extern const base::Feature kAutofillSaveCardSignInAfterLocalSave; -extern const base::Feature kAutofillSaveCreditCardUsesStrikeSystem; -extern const base::Feature kAutofillSaveCreditCardUsesStrikeSystemV2; extern const base::Feature kAutofillSaveOnProbablySubmitted; -extern const base::Feature kAutofillSendExperimentIdsInPaymentsRPCs; -extern const base::Feature kAutofillSendOnlyCountryInGetUploadDetails; extern const base::Feature kAutofillServerCommunication; extern const base::Feature kAutofillSettingsCardTypeSplit; extern const base::Feature kAutofillShowAllSuggestionsOnPrefilledForms; @@ -79,26 +63,9 @@ extern const base::Feature kAutofillSuppressDisusedCreditCards; extern const base::Feature kAutofillTokenPrefixMatching; extern const base::Feature kAutofillUploadThrottling; -extern const base::Feature kAutofillUpstream; -extern const base::Feature kAutofillUpstreamAllowAllEmailDomains; -extern const base::Feature kAutofillUpstreamAlwaysRequestCardholderName; -extern const base::Feature kAutofillUpstreamBlankCardholderNameField; -extern const base::Feature kAutofillUpstreamDisallowElo; -extern const base::Feature kAutofillUpstreamDisallowJcb; -extern const base::Feature kAutofillUpstreamEditableCardholderName; -extern const base::Feature kAutofillUpstreamEditableExpirationDate; -extern const base::Feature kAutofillUpstreamUseGooglePayBrandingOnMobile; extern const base::Feature kAutofillUseApi; extern const base::Feature kAutofillProfileClientValidation; -extern const base::Feature kAutofillUsePaymentsCustomerData; extern const base::Feature kAutomaticPasswordGeneration; -extern const char kAutofillCreditCardLastUsedDateShowExpirationDateKey[]; -extern const char kAutofillLocalCardMigrationCloseButtonDelay[]; -extern const char kAutofillCreditCardLocalCardMigrationParameterName[]; -extern const char kAutofillUpstreamMaxMinutesSinceAutofillProfileUseKey[]; -extern const char kCreditCardSigninPromoImpressionLimitParamKey[]; -extern const char - kAutofillCreditCardLocalCardMigrationParameterWithoutSettingsPage[]; #if defined(OS_ANDROID) extern const base::Feature kAutofillManualFallbackAndroid; @@ -108,42 +75,6 @@ // Returns whether the Autofill credit card assist infobar should be shown. bool IsAutofillCreditCardAssistEnabled(); -// Enum for local card migration experimental flag states. -enum class LocalCardMigrationExperimentalFlag { - // Local card migration disabled. - kMigrationDisabled, - // Only migrate local cards when user submits form. - kMigrationWithoutSettingsPage, - // Migrate both on submitted form and from settings page. - kMigrationIncludeSettingsPage, -}; - -// Returns kMigrationDisabled if no experimental behavior is enabled for -// kAutofillCreditCardLocalCardMigration; Return kMigrationIncludeSettingsPage -// if user enables the local card migration and does not exclude the settings -// page. Return kMigrationWithoutSettingsPage if user chooses to exclude the -// settings page migration. -LocalCardMigrationExperimentalFlag GetLocalCardMigrationExperimentalFlag(); - -// For testing purposes; not to be launched. When enabled, Chrome Upstream -// always requests that the user enters/confirms cardholder name in the -// offer-to-save dialog, regardless of if it was present or if the user is a -// Google Payments customer. Note that this will override the detected -// cardholder name, if one was found. -bool IsAutofillUpstreamAlwaysRequestCardholderNameExperimentEnabled(); - -// For experimental purposes; not to be made available in chrome://flags. When -// enabled and Chrome Upstream requests the cardholder name in the offer-to-save -// dialog, the field will be blank instead of being prefilled with the name from -// the user's Google Account. -bool IsAutofillUpstreamBlankCardholderNameFieldExperimentEnabled(); - -// Returns whether the experiment is enabled where Chrome Upstream can request -// the user to enter/confirm cardholder name in the offer-to-save bubble if it -// was not detected or was conflicting during the checkout flow and the user is -// NOT a Google Payments customer. -bool IsAutofillUpstreamEditableCardholderNameExperimentEnabled(); - #if defined(OS_MACOSX) // Returns true if whether the views autofill popup feature is enabled or the // we're using the views browser.
diff --git a/components/autofill/core/common/autofill_payments_features.cc b/components/autofill/core/common/autofill_payments_features.cc new file mode 100644 index 0000000..e785ffb --- /dev/null +++ b/components/autofill/core/common/autofill_payments_features.cc
@@ -0,0 +1,180 @@ +// 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 "components/autofill/core/common/autofill_payments_features.h" + +#include "base/command_line.h" +#include "base/feature_list.h" +#include "base/metrics/field_trial_params.h" +#include "base/strings/string16.h" +#include "base/strings/string_number_conversions.h" +#include "base/strings/string_util.h" +#include "base/strings/utf_string_conversions.h" +#include "build/build_config.h" +#include "components/autofill/core/common/autofill_prefs.h" +#include "components/autofill/core/common/autofill_switches.h" +#include "components/prefs/pref_service.h" +#include "ui/base/l10n/l10n_util.h" + +namespace autofill { +namespace features { + +const base::Feature kAutofillCreditCardAblationExperiment{ + "AutofillCreditCardAblationExperiment", base::FEATURE_DISABLED_BY_DEFAULT}; + +const base::Feature kAutofillCreditCardLocalCardMigration{ + "AutofillCreditCardLocalCardMigration", base::FEATURE_DISABLED_BY_DEFAULT}; + +const base::Feature kAutofillDoNotUploadSaveUnsupportedCards{ + "AutofillDoNotUploadSaveUnsupportedCards", + base::FEATURE_DISABLED_BY_DEFAULT}; + +// Controls whether the credit card downstream keyboard accessory shows +// the Google Pay logo animation on iOS. +const base::Feature kAutofillDownstreamUseGooglePayBrandingOniOS{ + "AutofillDownstreamUseGooglePayBrandingOniOS", + base::FEATURE_DISABLED_BY_DEFAULT}; + +// When enabled, enable local card migration flow for user who has signed in but +// has not turned on sync. +const base::Feature kAutofillEnableLocalCardMigrationForNonSyncUser{ + "AutofillEnableLocalCardMigrationForNonSyncUser", + base::FEATURE_DISABLED_BY_DEFAULT}; + +// When enabled, Autofill data related icons will be shown in the status +// chip in toolbar along with the avatar toolbar button. +const base::Feature kAutofillEnableToolbarStatusChip{ + "AutofillEnableToolbarStatusChip", base::FEATURE_DISABLED_BY_DEFAULT}; + +// When enabled, a credit card form that is hidden after receiving input can +// import the card. +const base::Feature kAutofillImportNonFocusableCreditCardForms{ + "AutofillImportNonFocusableCreditCardForms", + base::FEATURE_DISABLED_BY_DEFAULT}; + +// When enabled, the local card migration dialog will show the progress +// and result of the migration after starting the migration. When disabled, +// there is no feedback for the migration. +const base::Feature kAutofillLocalCardMigrationShowFeedback{ + "AutofillLocalCardMigrationShowFeedback", + base::FEATURE_DISABLED_BY_DEFAULT}; + +// Controls whether offering to migrate cards will consider data from the +// Autofill strike database (new version). +const base::Feature kAutofillLocalCardMigrationUsesStrikeSystemV2{ + "AutofillLocalCardMigrationUsesStrikeSystemV2", + base::FEATURE_DISABLED_BY_DEFAULT}; + +// When enabled, no local copy of server card will be saved when upload +// succeeds. +const base::Feature kAutofillNoLocalSaveOnUploadSuccess{ + "AutofillNoLocalSaveOnUploadSuccess", base::FEATURE_DISABLED_BY_DEFAULT}; + +// When enabled, local and upload credit card save dialogs will be updated to +// new M72 guidelines, including a [No thanks] cancel button and an extended +// title string. +const base::Feature kAutofillSaveCardImprovedUserConsent{ + "AutofillSaveCardImprovedUserConsent", base::FEATURE_DISABLED_BY_DEFAULT}; + +// When enabled, a sign in promo will show up right after the user +// saves a card locally. This also introduces a "Manage Cards" bubble. +const base::Feature kAutofillSaveCardSignInAfterLocalSave{ + "AutofillSaveCardSignInAfterLocalSave", base::FEATURE_ENABLED_BY_DEFAULT}; + +// Controls whether offering to save cards will consider data from the Autofill +// strike database. +const base::Feature kAutofillSaveCreditCardUsesStrikeSystem{ + "AutofillSaveCreditCardUsesStrikeSystem", + base::FEATURE_DISABLED_BY_DEFAULT}; + +// Controls whether offering to save cards will consider data from the Autofill +// strike database (new version). +const base::Feature kAutofillSaveCreditCardUsesStrikeSystemV2{ + "AutofillSaveCreditCardUsesStrikeSystemV2", + base::FEATURE_DISABLED_BY_DEFAULT}; + +// Controls whether experiment ids should be sent through +// Google Payments RPCs or not. +const base::Feature kAutofillSendExperimentIdsInPaymentsRPCs{ + "AutofillSendExperimentIdsInPaymentsRPCs", + base::FEATURE_ENABLED_BY_DEFAULT}; + +// If enabled, only countries of recently-used addresses are sent in the +// GetUploadDetails call to Payments. If disabled, whole recently-used addresses +// are sent. +const base::Feature kAutofillSendOnlyCountryInGetUploadDetails{ + "AutofillSendOnlyCountryInGetUploadDetails", + base::FEATURE_ENABLED_BY_DEFAULT}; + +const base::Feature kAutofillUpstream{"AutofillUpstream", + base::FEATURE_DISABLED_BY_DEFAULT}; + +const base::Feature kAutofillUpstreamAllowAllEmailDomains{ + "AutofillUpstreamAllowAllEmailDomains", base::FEATURE_DISABLED_BY_DEFAULT}; + +const base::Feature kAutofillUpstreamAlwaysRequestCardholderName{ + "AutofillUpstreamAlwaysRequestCardholderName", + base::FEATURE_DISABLED_BY_DEFAULT}; + +const base::Feature kAutofillUpstreamBlankCardholderNameField{ + "AutofillUpstreamBlankCardholderNameField", + base::FEATURE_DISABLED_BY_DEFAULT}; + +// Controls whether ELO cards should be uploaded to Google Payments. +const base::Feature kAutofillUpstreamDisallowElo{ + "AutofillUpstreamDisallowElo", base::FEATURE_DISABLED_BY_DEFAULT}; + +// Controls whether JCB cards should be uploaded to Google Payments. +const base::Feature kAutofillUpstreamDisallowJcb{ + "AutofillUpstreamDisallowJcb", base::FEATURE_DISABLED_BY_DEFAULT}; + +const base::Feature kAutofillUpstreamEditableCardholderName{ + "AutofillUpstreamEditableCardholderName", + base::FEATURE_DISABLED_BY_DEFAULT}; + +const base::Feature kAutofillUpstreamEditableExpirationDate{ + "AutofillUpstreamEditableExpirationDate", + base::FEATURE_DISABLED_BY_DEFAULT}; + +// Controls whether the PaymentsCustomerData is used to make requests to +// Google Payments. +const base::Feature kAutofillUsePaymentsCustomerData{ + "AutofillUsePaymentsCustomerData", base::FEATURE_ENABLED_BY_DEFAULT}; + +const char kAutofillCreditCardLocalCardMigrationParameterName[] = "variant"; + +const char kAutofillCreditCardLocalCardMigrationParameterWithoutSettingsPage[] = + "without-settings-page"; + +LocalCardMigrationExperimentalFlag GetLocalCardMigrationExperimentalFlag() { + if (!base::FeatureList::IsEnabled(kAutofillCreditCardLocalCardMigration)) + return LocalCardMigrationExperimentalFlag::kMigrationDisabled; + + std::string param = base::GetFieldTrialParamValueByFeature( + kAutofillCreditCardLocalCardMigration, + kAutofillCreditCardLocalCardMigrationParameterName); + + if (param == + kAutofillCreditCardLocalCardMigrationParameterWithoutSettingsPage) { + return LocalCardMigrationExperimentalFlag::kMigrationWithoutSettingsPage; + } + return LocalCardMigrationExperimentalFlag::kMigrationIncludeSettingsPage; +} + +bool IsAutofillUpstreamAlwaysRequestCardholderNameExperimentEnabled() { + return base::FeatureList::IsEnabled( + features::kAutofillUpstreamAlwaysRequestCardholderName); +} + +bool IsAutofillUpstreamBlankCardholderNameFieldExperimentEnabled() { + return base::FeatureList::IsEnabled( + features::kAutofillUpstreamBlankCardholderNameField); +} + +bool IsAutofillUpstreamEditableCardholderNameExperimentEnabled() { + return base::FeatureList::IsEnabled(kAutofillUpstreamEditableCardholderName); +} + +} // namespace features +} // namespace autofill
diff --git a/components/autofill/core/common/autofill_payments_features.h b/components/autofill/core/common/autofill_payments_features.h new file mode 100644 index 0000000..8a0d553e --- /dev/null +++ b/components/autofill/core/common/autofill_payments_features.h
@@ -0,0 +1,90 @@ +// 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 COMPONENTS_AUTOFILL_CORE_COMMON_AUTOFILL_PAYMENTS_FEATURES_H_ +#define COMPONENTS_AUTOFILL_CORE_COMMON_AUTOFILL_PAYMENTS_FEATURES_H_ + +#include <string> + +#include "base/feature_list.h" +#include "base/strings/string16.h" +#include "build/build_config.h" + +namespace base { +struct Feature; +} + +namespace autofill { +namespace features { + +// All features in alphabetical order. +extern const base::Feature kAutofillCreditCardAblationExperiment; +extern const base::Feature kAutofillCreditCardLocalCardMigration; +extern const base::Feature kAutofillDoNotUploadSaveUnsupportedCards; +extern const base::Feature kAutofillDownstreamUseGooglePayBrandingOniOS; +extern const base::Feature kAutofillEnableLocalCardMigrationForNonSyncUser; +extern const base::Feature kAutofillEnableToolbarStatusChip; +extern const base::Feature kAutofillImportNonFocusableCreditCardForms; +extern const base::Feature kAutofillLocalCardMigrationShowFeedback; +extern const base::Feature kAutofillLocalCardMigrationUsesStrikeSystemV2; +extern const base::Feature kAutofillNoLocalSaveOnUploadSuccess; +extern const base::Feature kAutofillSaveCardImprovedUserConsent; +extern const base::Feature kAutofillSaveCardSignInAfterLocalSave; +extern const base::Feature kAutofillSaveCreditCardUsesStrikeSystem; +extern const base::Feature kAutofillSaveCreditCardUsesStrikeSystemV2; +extern const base::Feature kAutofillSendExperimentIdsInPaymentsRPCs; +extern const base::Feature kAutofillSendOnlyCountryInGetUploadDetails; +extern const base::Feature kAutofillUpstream; +extern const base::Feature kAutofillUpstreamAllowAllEmailDomains; +extern const base::Feature kAutofillUpstreamAlwaysRequestCardholderName; +extern const base::Feature kAutofillUpstreamBlankCardholderNameField; +extern const base::Feature kAutofillUpstreamDisallowElo; +extern const base::Feature kAutofillUpstreamDisallowJcb; +extern const base::Feature kAutofillUpstreamEditableCardholderName; +extern const base::Feature kAutofillUpstreamEditableExpirationDate; +extern const base::Feature kAutofillUsePaymentsCustomerData; +extern const char kAutofillCreditCardLocalCardMigrationParameterName[]; +extern const char + kAutofillCreditCardLocalCardMigrationParameterWithoutSettingsPage[]; + +// Enum for local card migration experimental flag states. +enum class LocalCardMigrationExperimentalFlag { + // Local card migration disabled. + kMigrationDisabled, + // Only migrate local cards when user submits form. + kMigrationWithoutSettingsPage, + // Migrate both on submitted form and from settings page. + kMigrationIncludeSettingsPage, +}; + +// Returns kMigrationDisabled if no experimental behavior is enabled for +// kAutofillCreditCardLocalCardMigration; Return kMigrationIncludeSettingsPage +// if user enables the local card migration and does not exclude the settings +// page. Return kMigrationWithoutSettingsPage if user chooses to exclude the +// settings page migration. +LocalCardMigrationExperimentalFlag GetLocalCardMigrationExperimentalFlag(); + +// For testing purposes; not to be launched. When enabled, Chrome Upstream +// always requests that the user enters/confirms cardholder name in the +// offer-to-save dialog, regardless of if it was present or if the user is a +// Google Payments customer. Note that this will override the detected +// cardholder name, if one was found. +bool IsAutofillUpstreamAlwaysRequestCardholderNameExperimentEnabled(); + +// For experimental purposes; not to be made available in chrome://flags. When +// enabled and Chrome Upstream requests the cardholder name in the offer-to-save +// dialog, the field will be blank instead of being prefilled with the name from +// the user's Google Account. +bool IsAutofillUpstreamBlankCardholderNameFieldExperimentEnabled(); + +// Returns whether the experiment is enabled where Chrome Upstream can request +// the user to enter/confirm cardholder name in the offer-to-save bubble if it +// was not detected or was conflicting during the checkout flow and the user is +// NOT a Google Payments customer. +bool IsAutofillUpstreamEditableCardholderNameExperimentEnabled(); + +} // namespace features +} // namespace autofill + +#endif // COMPONENTS_AUTOFILL_CORE_COMMON_AUTOFILL_PAYMENTS_FEATURES_H_
diff --git a/components/autofill_assistant/browser/protocol_utils.cc b/components/autofill_assistant/browser/protocol_utils.cc index b8f2614c..6480392 100644 --- a/components/autofill_assistant/browser/protocol_utils.cc +++ b/components/autofill_assistant/browser/protocol_utils.cc
@@ -170,90 +170,96 @@ } for (const auto& action : response_proto.actions()) { + std::unique_ptr<Action> client_action; switch (action.action_info_case()) { case ActionProto::ActionInfoCase::kClick: { - actions->emplace_back(std::make_unique<ClickAction>(action)); + client_action = std::make_unique<ClickAction>(action); break; } case ActionProto::ActionInfoCase::kTell: { - actions->emplace_back(std::make_unique<TellAction>(action)); + client_action = std::make_unique<TellAction>(action); break; } case ActionProto::ActionInfoCase::kFocusElement: { - actions->emplace_back(std::make_unique<FocusElementAction>(action)); + client_action = std::make_unique<FocusElementAction>(action); break; } case ActionProto::ActionInfoCase::kUseAddress: case ActionProto::ActionInfoCase::kUseCard: { - actions->emplace_back(std::make_unique<AutofillAction>(action)); + client_action = std::make_unique<AutofillAction>(action); break; } case ActionProto::ActionInfoCase::kWaitForDom: { - actions->emplace_back(std::make_unique<WaitForDomAction>(action)); + client_action = std::make_unique<WaitForDomAction>(action); break; } case ActionProto::ActionInfoCase::kSelectOption: { - actions->emplace_back(std::make_unique<SelectOptionAction>(action)); + client_action = std::make_unique<SelectOptionAction>(action); break; } case ActionProto::ActionInfoCase::kNavigate: { - actions->emplace_back(std::make_unique<NavigateAction>(action)); + client_action = std::make_unique<NavigateAction>(action); break; } case ActionProto::ActionInfoCase::kPrompt: { - actions->emplace_back(std::make_unique<PromptAction>(action)); + client_action = std::make_unique<PromptAction>(action); break; } case ActionProto::ActionInfoCase::kStop: { - actions->emplace_back(std::make_unique<StopAction>(action)); + client_action = std::make_unique<StopAction>(action); break; } case ActionProto::ActionInfoCase::kReset: { - actions->emplace_back(std::make_unique<ResetAction>(action)); + client_action = std::make_unique<ResetAction>(action); break; } case ActionProto::ActionInfoCase::kHighlightElement: { - actions->emplace_back(std::make_unique<HighlightElementAction>(action)); + client_action = std::make_unique<HighlightElementAction>(action); break; } case ActionProto::ActionInfoCase::kUploadDom: { - actions->emplace_back(std::make_unique<UploadDomAction>(action)); + client_action = std::make_unique<UploadDomAction>(action); break; } case ActionProto::ActionInfoCase::kShowDetails: { - actions->emplace_back(std::make_unique<ShowDetailsAction>(action)); + client_action = std::make_unique<ShowDetailsAction>(action); break; } case ActionProto::ActionInfoCase::kGetPaymentInformation: { - actions->emplace_back( - std::make_unique<GetPaymentInformationAction>(action)); + client_action = std::make_unique<GetPaymentInformationAction>(action); break; } case ActionProto::ActionInfoCase::kSetFormValue: { - actions->emplace_back( - std::make_unique<SetFormFieldValueAction>(action)); + client_action = std::make_unique<SetFormFieldValueAction>(action); break; } case ActionProto::ActionInfoCase::kShowProgressBar: { - actions->emplace_back(std::make_unique<ShowProgressBarAction>(action)); + client_action = std::make_unique<ShowProgressBarAction>(action); break; } case ActionProto::ActionInfoCase::kSetAttribute: { - actions->emplace_back(std::make_unique<SetAttributeAction>(action)); + client_action = std::make_unique<SetAttributeAction>(action); break; } case ActionProto::ActionInfoCase::kShowInfoBox: { - actions->emplace_back(std::make_unique<ShowInfoBoxAction>(action)); + client_action = std::make_unique<ShowInfoBoxAction>(action); break; } - default: case ActionProto::ActionInfoCase::ACTION_INFO_NOT_SET: { - DVLOG(1) << "Unknown or unsupported action with action_case=" - << action.action_info_case(); - actions->emplace_back(std::make_unique<UnsupportedAction>(action)); + DVLOG(1) << "Encountered action with ACTION_INFO_NOT_SET"; + client_action = std::make_unique<UnsupportedAction>(action); break; } + // Intentionally no default case to ensure a compilation error for new + // cases added to the proto. } + if (client_action == nullptr) { + DVLOG(1) << "Encountered action with Unknown or unsupported action with " + "action_case=" + << action.action_info_case(); + client_action = std::make_unique<UnsupportedAction>(action); + } + actions->emplace_back(std::move(client_action)); } *should_update_scripts = response_proto.has_update_script_list();
diff --git a/components/browser_sync/profile_sync_service.cc b/components/browser_sync/profile_sync_service.cc index 8d02800..bf3500f6 100644 --- a/components/browser_sync/profile_sync_service.cc +++ b/components/browser_sync/profile_sync_service.cc
@@ -29,6 +29,7 @@ #include "components/sync/driver/backend_migrator.h" #include "components/sync/driver/configure_context.h" #include "components/sync/driver/directory_data_type_controller.h" +#include "components/sync/driver/model_type_controller.h" #include "components/sync/driver/sync_api_component_factory.h" #include "components/sync/driver/sync_driver_switches.h" #include "components/sync/driver/sync_type_preference_provider.h" @@ -39,6 +40,7 @@ #include "components/sync/engine/net/network_resources.h" #include "components/sync/engine/polling_constants.h" #include "components/sync/engine/sync_encryption_handler.h" +#include "components/sync/engine/sync_engine_switches.h" #include "components/sync/model/sync_error.h" #include "components/sync/syncable/base_transaction.h" #include "components/sync/syncable/directory.h" @@ -591,6 +593,14 @@ migrator_.reset(); sync_js_controller_.AttachJsBackend(syncer::WeakHandle<syncer::JsBackend>()); + if (base::FeatureList::IsEnabled(switches::kSyncUSSNigori)) { + // We need to remove ModelTypeController for Nigori before the engine + // shutdown because it's no longer valid after shutdown. + // TODO(crbug.com/943019): This logic can be removed if Nigori local + // model will be moved to UI thread. + data_type_controllers_.erase(syncer::NIGORI); + } + engine_->Shutdown(reason); engine_.reset(); @@ -885,6 +895,17 @@ UpdateLastSyncedTime(); } + if (base::FeatureList::IsEnabled(switches::kSyncUSSNigori)) { + // Nigori's ModelTypeController can only be created after sync engine + // initialization. Therefore, it cannot be created with other controllers + // in BuildDataTypeControllerMap(). + // TODO(crbug.com/943019): This logic can be removed if Nigori local + // model will be moved to UI thread. + data_type_controllers_[syncer::NIGORI] = + std::make_unique<syncer::ModelTypeController>( + syncer::NIGORI, engine_->GetNigoriControllerDelegate()); + } + data_type_manager_ = sync_client_->GetSyncApiComponentFactory()->CreateDataTypeManager( initial_types, debug_info_listener, &data_type_controllers_,
diff --git a/components/download/internal/common/BUILD.gn b/components/download/internal/common/BUILD.gn index 6ca95c9..acd3b175 100644 --- a/components/download/internal/common/BUILD.gn +++ b/components/download/internal/common/BUILD.gn
@@ -53,6 +53,7 @@ "resource_downloader.h", "save_package_download_job.cc", "save_package_download_job.h", + "simple_download_manager_coordinator.cc", "stream_handle_input_stream.cc", "url_download_handler_factory.cc", "url_download_request_handle.cc",
diff --git a/components/download/internal/common/simple_download_manager_coordinator.cc b/components/download/internal/common/simple_download_manager_coordinator.cc new file mode 100644 index 0000000..826ac49 --- /dev/null +++ b/components/download/internal/common/simple_download_manager_coordinator.cc
@@ -0,0 +1,46 @@ +// 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 "components/download/public/common/simple_download_manager_coordinator.h" + +#include <utility> + +#include "components/download/public/common/download_item.h" +#include "components/download/public/common/simple_download_manager.h" + +namespace download { + +SimpleDownloadManagerCoordinator::SimpleDownloadManagerCoordinator() = default; + +SimpleDownloadManagerCoordinator::~SimpleDownloadManagerCoordinator() = default; + +void SimpleDownloadManagerCoordinator::SetSimpleDownloadManager( + SimpleDownloadManager* simple_download_manager) { + simple_download_manager_ = simple_download_manager; +} + +void SimpleDownloadManagerCoordinator::DownloadUrl( + std::unique_ptr<download::DownloadUrlParameters> parameters) { + if (simple_download_manager_) + simple_download_manager_->DownloadUrl(std::move(parameters)); +} + +DownloadItem* SimpleDownloadManagerCoordinator::GetDownloadByGuid( + const std::string& guid) { + if (simple_download_manager_) + return simple_download_manager_->GetDownloadByGuid(guid); + return nullptr; +} + +bool SimpleDownloadManagerCoordinator::AreDownloadsInitialized( + bool active_downloads_only) { + return simple_download_manager_->AreDownloadsInitialized( + active_downloads_only); +} + +std::vector<DownloadItem*> SimpleDownloadManagerCoordinator::GetAllDownloads() { + return simple_download_manager_->GetAllDownloads(); +} + +} // namespace download
diff --git a/components/download/public/common/BUILD.gn b/components/download/public/common/BUILD.gn index 26a6dd0..30d3d52 100644 --- a/components/download/public/common/BUILD.gn +++ b/components/download/public/common/BUILD.gn
@@ -59,6 +59,8 @@ "parallel_download_configs.h", "rate_estimator.h", "resume_mode.h", + "simple_download_manager.h", + "simple_download_manager_coordinator.h", "stream_handle_input_stream.h", "url_download_handler_factory.h", "url_download_request_handle.h",
diff --git a/components/download/public/common/simple_download_manager.h b/components/download/public/common/simple_download_manager.h new file mode 100644 index 0000000..85e8acf --- /dev/null +++ b/components/download/public/common/simple_download_manager.h
@@ -0,0 +1,58 @@ +// 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 COMPONENTS_DOWNLOAD_PUBLIC_COMMON_SIMPLE_DOWNLOAD_MANAGER_H_ +#define COMPONENTS_DOWNLOAD_PUBLIC_COMMON_SIMPLE_DOWNLOAD_MANAGER_H_ + +#include <memory> +#include <string> +#include <vector> + +#include "components/download/public/common/download_export.h" +#include "components/download/public/common/download_url_parameters.h" + +namespace download { + +class DownloadItem; + +// Download manager that provides simple functionalities for callers to carry +// out a download task. +class COMPONENTS_DOWNLOAD_EXPORT SimpleDownloadManager { + public: + class Observer { + public: + Observer() = default; + virtual ~Observer() = default; + + virtual void OnDownloadsInitialized(bool active_downloads_only) {} + virtual void OnManagerGoingDown() {} + virtual void OnDownloadCreated(DownloadItem* item) {} + virtual void OnDownloadUpdated(DownloadItem* item) {} + virtual void OnDownloadOpened(DownloadItem* item) {} + virtual void OnDownloadRemoved(DownloadItem* item) {} + + private: + DISALLOW_COPY_AND_ASSIGN(Observer); + }; + + // See DownloadUrlParameters for details about controlling the download. + virtual void DownloadUrl( + std::unique_ptr<download::DownloadUrlParameters> parameters) = 0; + + // Whether downloads are initialized. If |active_downloads_only| is true, this + // call only checks for all the active downloads. Otherwise, it will check all + // downloads. + virtual bool AreDownloadsInitialized(bool active_downloads_only) = 0; + + // Gets all downloads. + virtual std::vector<DownloadItem*> GetAllDownloads() = 0; + + // Get the download item for |guid|. + virtual download::DownloadItem* GetDownloadByGuid( + const std::string& guid) = 0; +}; + +} // namespace download + +#endif // COMPONENTS_DOWNLOAD_PUBLIC_COMMON_SIMPLE_DOWNLOAD_MANAGER_H_
diff --git a/components/download/public/common/simple_download_manager_coordinator.h b/components/download/public/common/simple_download_manager_coordinator.h new file mode 100644 index 0000000..85756fe4 --- /dev/null +++ b/components/download/public/common/simple_download_manager_coordinator.h
@@ -0,0 +1,54 @@ +// 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 COMPONENTS_DOWNLOAD_PUBLIC_COMMON_SIMPLE_DOWNLOAD_MANAGER_COORDINATOR_H_ +#define COMPONENTS_DOWNLOAD_PUBLIC_COMMON_SIMPLE_DOWNLOAD_MANAGER_COORDINATOR_H_ + +#include <memory> +#include <string> +#include <vector> + +#include "components/download/public/common/download_export.h" +#include "components/download/public/common/download_url_parameters.h" + +namespace download { + +class DownloadItem; +class SimpleDownloadManager; + +// This object allows swapping between different SimppleDownloadManager +// instances so that callers don't need to know about the swap. +class COMPONENTS_DOWNLOAD_EXPORT SimpleDownloadManagerCoordinator { + public: + SimpleDownloadManagerCoordinator(); + ~SimpleDownloadManagerCoordinator(); + + void SetSimpleDownloadManager(SimpleDownloadManager* simple_download_manager); + + // See download::DownloadUrlParameters for details about controlling the + // download. + void DownloadUrl(std::unique_ptr<DownloadUrlParameters> parameters); + + // Whether downloads are initialized. If |active_downloads_only| is true, this + // call only checks for all the active downloads. Otherwise, it will check all + // downloads. + bool AreDownloadsInitialized(bool active_downloads_only); + + // Gets all the downloads. Caller needs to call AreDownloadsInitialized() to + // check if all downloads are initialized. If only active downloads are + // initialized, this method will only return all active downloads. + std::vector<DownloadItem*> GetAllDownloads(); + + // Get the download item for |guid|. + download::DownloadItem* GetDownloadByGuid(const std::string& guid); + + private: + SimpleDownloadManager* simple_download_manager_; + + DISALLOW_COPY_AND_ASSIGN(SimpleDownloadManagerCoordinator); +}; + +} // namespace download + +#endif // COMPONENTS_DOWNLOAD_PUBLIC_COMMON_SIMPLE_DOWNLOAD_MANAGER_COORDINATOR_H_
diff --git a/components/keyed_service/core/simple_keyed_service_factory.cc b/components/keyed_service/core/simple_keyed_service_factory.cc index 4582f9c..5220aef 100644 --- a/components/keyed_service/core/simple_keyed_service_factory.cc +++ b/components/keyed_service/core/simple_keyed_service_factory.cc
@@ -49,14 +49,13 @@ KeyedService* SimpleKeyedServiceFactory::GetServiceForKey(SimpleFactoryKey* key, PrefService* prefs, bool create) { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + return KeyedServiceFactory::GetServiceForContext(key, prefs, create); } SimpleFactoryKey* SimpleKeyedServiceFactory::GetKeyToUse( SimpleFactoryKey* key) const { - // TODO(crbug.com/701326): This DCHECK should be moved to GetContextToUse(). - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - // Safe default for Incognito mode: no service. if (key->is_off_the_record()) return nullptr; @@ -65,10 +64,14 @@ } void SimpleKeyedServiceFactory::SimpleContextShutdown(SimpleFactoryKey* key) { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + KeyedServiceFactory::ContextShutdown(key); } void SimpleKeyedServiceFactory::SimpleContextDestroyed(SimpleFactoryKey* key) { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + KeyedServiceFactory::ContextDestroyed(key); }
diff --git a/components/language/DEPS b/components/language/DEPS index fcb6de9..5ab36a5 100644 --- a/components/language/DEPS +++ b/components/language/DEPS
@@ -2,6 +2,7 @@ "+components/pref_registry", "+components/prefs", "+components/strings/grit/components_locale_settings.h", + "+components/sync_preferences", "+third_party/s2cellid", "-components/language/content",
diff --git a/components/language/core/browser/BUILD.gn b/components/language/core/browser/BUILD.gn index bd59d2b..45e6786 100644 --- a/components/language/core/browser/BUILD.gn +++ b/components/language/core/browser/BUILD.gn
@@ -25,6 +25,7 @@ deps = [ "//base", "//components/keyed_service/core", + "//components/language/core/common", "//components/pref_registry", "//components/prefs", "//components/strings", @@ -37,6 +38,7 @@ sources = [ "baseline_language_model_unittest.cc", "heuristic_language_model_unittest.cc", + "language_prefs_unittest.cc", "url_language_histogram_unittest.cc", ] deps = [ @@ -45,6 +47,7 @@ "//components/pref_registry:pref_registry", "//components/prefs", "//components/prefs:test_support", + "//components/sync_preferences:test_support", "//net:test_support", "//testing/gmock", "//testing/gtest",
diff --git a/components/language/core/browser/language_prefs.cc b/components/language/core/browser/language_prefs.cc index bc2dc11..317aa1d 100644 --- a/components/language/core/browser/language_prefs.cc +++ b/components/language/core/browser/language_prefs.cc
@@ -4,8 +4,22 @@ #include "components/language/core/browser/language_prefs.h" +#include <algorithm> +#include <set> +#include <utility> +#include <vector> + +#include "base/stl_util.h" +#include "base/strings/string_piece.h" +#include "base/strings/string_split.h" +#include "base/strings/string_util.h" +#include "base/values.h" #include "components/language/core/browser/pref_names.h" +#include "components/language/core/common/language_util.h" +#include "components/language/core/common/locale_util.h" #include "components/pref_registry/pref_registry_syncable.h" +#include "components/prefs/pref_service.h" +#include "components/prefs/scoped_user_pref_update.h" #include "components/strings/grit/components_locale_settings.h" #include "ui/base/l10n/l10n_util.h" @@ -13,7 +27,8 @@ const char kFallbackInputMethodLocale[] = "en-US"; -void RegisterProfilePrefs(user_prefs::PrefRegistrySyncable* registry) { +void LanguagePrefs::RegisterProfilePrefs( + user_prefs::PrefRegistrySyncable* registry) { registry->RegisterStringPref(language::prefs::kAcceptLanguages, l10n_util::GetStringUTF8(IDS_ACCEPT_LANGUAGES), user_prefs::PrefRegistrySyncable::SYNCABLE_PREF); @@ -24,6 +39,77 @@ registry->RegisterStringPref(language::prefs::kPreferredLanguagesSyncable, "", user_prefs::PrefRegistrySyncable::SYNCABLE_PREF); #endif + registry->RegisterListPref(language::prefs::kFluentLanguages, + LanguagePrefs::GetDefaultFluentLanguages(), + user_prefs::PrefRegistrySyncable::SYNCABLE_PREF); +} + +LanguagePrefs::LanguagePrefs(PrefService* user_prefs) : prefs_(user_prefs) { + ResetEmptyFluentLanguagesToDefault(); +} + +bool LanguagePrefs::IsFluent(const std::string& language) const { + std::string canonical_lang = language; + language::ToTranslateLanguageSynonym(&canonical_lang); + const base::Value* fluents = + prefs_->GetList(language::prefs::kFluentLanguages); + return base::ContainsValue(fluents->GetList(), base::Value(canonical_lang)); +} + +void LanguagePrefs::SetFluent(const std::string& language) { + if (IsFluent(language)) + return; + std::string canonical_lang = language; + language::ToTranslateLanguageSynonym(&canonical_lang); + ListPrefUpdate update(prefs_, language::prefs::kFluentLanguages); + update->GetList().emplace_back(std::move(canonical_lang)); +} + +void LanguagePrefs::ClearFluent(const std::string& language) { + if (NumFluentLanguages() <= 1) // Never remove last fluent language. + return; + std::string canonical_lang = language; + language::ToTranslateLanguageSynonym(&canonical_lang); + ListPrefUpdate update(prefs_, language::prefs::kFluentLanguages); + base::Erase(update->GetList(), base::Value(canonical_lang)); +} + +void LanguagePrefs::ResetFluentLanguagesToDefaults() { + // Reset pref to defaults. + prefs_->ClearPref(language::prefs::kFluentLanguages); +} + +void LanguagePrefs::ResetEmptyFluentLanguagesToDefault() { + if (NumFluentLanguages() == 0) + ResetFluentLanguagesToDefaults(); +} + +base::Value LanguagePrefs::GetDefaultFluentLanguages() { + std::set<const std::string> languages; +#if defined(OS_CHROMEOS) + // Preferred languages. + std::string language = language::kFallbackInputMethodLocale; + language::ToTranslateLanguageSynonym(&language); + languages.insert(std::move(language)); +#else + // Accept languages. + for (std::string language : + base::SplitString(l10n_util::GetStringUTF8(IDS_ACCEPT_LANGUAGES), ",", + base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL)) { + language::ToTranslateLanguageSynonym(&language); + languages.insert(std::move(language)); + } +#endif + base::Value language_values(base::Value::Type::LIST); + for (const std::string& language : languages) + language_values.GetList().emplace_back(language); + return language_values; +} + +size_t LanguagePrefs::NumFluentLanguages() const { + const base::Value* fluents = + prefs_->GetList(language::prefs::kFluentLanguages); + return fluents->GetList().size(); } } // namespace language
diff --git a/components/language/core/browser/language_prefs.h b/components/language/core/browser/language_prefs.h index 296ed932..fb32a8c 100644 --- a/components/language/core/browser/language_prefs.h +++ b/components/language/core/browser/language_prefs.h
@@ -5,6 +5,16 @@ #ifndef COMPONENTS_LANGUAGE_CORE_BROWSER_LANGUAGE_PREFS_H_ #define COMPONENTS_LANGUAGE_CORE_BROWSER_LANGUAGE_PREFS_H_ +#include <string> + +#include "base/macros.h" + +class PrefService; + +namespace base { +class Value; +} // namespace base + namespace user_prefs { class PrefRegistrySyncable; } @@ -13,7 +23,36 @@ extern const char kFallbackInputMethodLocale[]; -void RegisterProfilePrefs(user_prefs::PrefRegistrySyncable* registry); +class LanguagePrefs { + public: + static void RegisterProfilePrefs(user_prefs::PrefRegistrySyncable* registry); + + LanguagePrefs(PrefService* user_prefs); + + // Return true iff the user is fluent in the given |language|. + bool IsFluent(const std::string& language) const; + // Mark that the user is fluent in the given |language|. + void SetFluent(const std::string& language); + // Remove the given |language| from the user's fluent languages. + void ClearFluent(const std::string& language); + // Reset the fluent languages to their defaults. + void ResetFluentLanguagesToDefaults(); + // Get the default fluent languages for the user. + static base::Value GetDefaultFluentLanguages(); + // If the list of fluent languages is empty, reset it to defaults. + void ResetEmptyFluentLanguagesToDefault(); + + private: + base::Value* GetFluentLanguages(); + + const base::Value* GetFluentLanguages() const; + + size_t NumFluentLanguages() const; + + PrefService* prefs_; // Weak. + + DISALLOW_COPY_AND_ASSIGN(LanguagePrefs); +}; } // namespace language
diff --git a/components/language/core/browser/language_prefs_unittest.cc b/components/language/core/browser/language_prefs_unittest.cc new file mode 100644 index 0000000..1b8be62 --- /dev/null +++ b/components/language/core/browser/language_prefs_unittest.cc
@@ -0,0 +1,155 @@ +// Copyright 2014 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "components/language/core/browser/language_prefs.h" + +#include <algorithm> +#include <memory> +#include <string> +#include <utility> +#include <vector> + +#include "base/json/json_reader.h" +#include "base/test/scoped_feature_list.h" +#include "base/test/test_timeouts.h" +#include "base/values.h" +#include "build/build_config.h" +#include "components/language/core/browser/pref_names.h" +#include "components/prefs/scoped_user_pref_update.h" +#include "components/sync_preferences/testing_pref_service_syncable.h" +#include "testing/gmock/include/gmock/gmock.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace language { + +static void ExpectEqualLanguageLists( + const base::Value* language_values, + const std::vector<std::string>& languages) { + const int input_size = languages.size(); + ASSERT_EQ(input_size, static_cast<int>(language_values->GetList().size())); + for (int i = 0; i < input_size; ++i) { + std::string value = language_values->GetList().at(i).GetString(); + EXPECT_EQ(languages[i], value); + } +} + +class LanguagePrefsTest : public testing::Test { + protected: + LanguagePrefsTest() + : prefs_(new sync_preferences::TestingPrefServiceSyncable()) { + LanguagePrefs::RegisterProfilePrefs(prefs_->registry()); + language_prefs_.reset(new language::LanguagePrefs(prefs_.get())); + } + + void ExpectFluentLanguageListContent( + const std::vector<std::string>& list) const { + const base::Value* values = prefs_->Get(language::prefs::kFluentLanguages); + DCHECK(values); + ExpectEqualLanguageLists(values, list); + } + + std::unique_ptr<sync_preferences::TestingPrefServiceSyncable> prefs_; + std::unique_ptr<language::LanguagePrefs> language_prefs_; +}; + +TEST_F(LanguagePrefsTest, SetFluentTest) { + // `en` is a default fluent language, it should be present already. + ExpectFluentLanguageListContent({"en"}); + + // One language. + language_prefs_->SetFluent("fr-CA"); + ExpectFluentLanguageListContent({"en", "fr"}); + + // Add a few more. + language_prefs_->SetFluent("es-AR"); + language_prefs_->SetFluent("de-de"); + ExpectFluentLanguageListContent({"en", "fr", "es", "de"}); + + // Add a duplicate. + language_prefs_->ResetFluentLanguagesToDefaults(); + ExpectFluentLanguageListContent({"en"}); + language_prefs_->SetFluent("es-AR"); + language_prefs_->SetFluent("es-AR"); + ExpectFluentLanguageListContent({"en", "es"}); + + // Two languages with the same base. + language_prefs_->ResetFluentLanguagesToDefaults(); + language_prefs_->SetFluent("fr-CA"); + language_prefs_->SetFluent("fr-FR"); + ExpectFluentLanguageListContent({"en", "fr"}); + + // Chinese is a special case. + language_prefs_->ResetFluentLanguagesToDefaults(); + language_prefs_->SetFluent("zh-MO"); + language_prefs_->SetFluent("zh-CN"); + ExpectFluentLanguageListContent({"en", "zh-TW", "zh-CN"}); + + language_prefs_->ResetFluentLanguagesToDefaults(); + language_prefs_->SetFluent("zh-TW"); + language_prefs_->SetFluent("zh-HK"); + ExpectFluentLanguageListContent({"en", "zh-TW"}); +} + +TEST_F(LanguagePrefsTest, ClearFluentTest) { + // Language in the list. + // Should not clear fluent for last language. + language_prefs_->ClearFluent("en-UK"); + ExpectFluentLanguageListContent({"en"}); + + // Language in the list but with different region. + // Should not clear fluent for last language. + language_prefs_->ClearFluent("en-AU"); + ExpectFluentLanguageListContent({"en"}); + + // Language in the list. + language_prefs_->ResetFluentLanguagesToDefaults(); + language_prefs_->SetFluent("fr"); + language_prefs_->ClearFluent("en-UK"); + ExpectFluentLanguageListContent({"fr"}); + + // Language in the list but with different region. + language_prefs_->ResetFluentLanguagesToDefaults(); + language_prefs_->SetFluent("fr"); + language_prefs_->ClearFluent("en-AU"); + ExpectFluentLanguageListContent({"fr"}); + + // Multiple languages. + language_prefs_->ResetFluentLanguagesToDefaults(); + language_prefs_->SetFluent("fr-CA"); + language_prefs_->SetFluent("fr-FR"); + language_prefs_->SetFluent("es-AR"); + language_prefs_->ClearFluent("fr-FR"); + ExpectFluentLanguageListContent({"en", "es"}); + + // Chinese is a special case. + language_prefs_->ResetFluentLanguagesToDefaults(); + language_prefs_->SetFluent("zh-MO"); + language_prefs_->SetFluent("zh-CN"); + language_prefs_->ClearFluent("zh-TW"); + ExpectFluentLanguageListContent({"en", "zh-CN"}); + + language_prefs_->ResetFluentLanguagesToDefaults(); + language_prefs_->SetFluent("zh-MO"); + language_prefs_->SetFluent("zh-CN"); + language_prefs_->ClearFluent("zh-CN"); + ExpectFluentLanguageListContent({"en", "zh-TW"}); +} + +TEST_F(LanguagePrefsTest, ResetEmptyFluentLanguagesToDefaultTest) { + ExpectFluentLanguageListContent({"en"}); + + language_prefs_->ResetEmptyFluentLanguagesToDefault(); + ExpectFluentLanguageListContent({"en"}); + + language_prefs_->SetFluent("fr"); + language_prefs_->ResetEmptyFluentLanguagesToDefault(); + ExpectFluentLanguageListContent({"en", "fr"}); + + prefs_->Set(language::prefs::kFluentLanguages, base::ListValue()); + ExpectFluentLanguageListContent({}); + language_prefs_->ResetEmptyFluentLanguagesToDefault(); + ExpectFluentLanguageListContent({"en"}); +} + +} // namespace language
diff --git a/components/language/core/browser/pref_names.cc b/components/language/core/browser/pref_names.cc index f2c821ec..fe340274 100644 --- a/components/language/core/browser/pref_names.cc +++ b/components/language/core/browser/pref_names.cc
@@ -25,5 +25,8 @@ // Important: Refer to header file for how to use this. const char kApplicationLocale[] = "intl.app_locale"; +// Originally translate blocked languages from TranslatePrefs. +const char kFluentLanguages[] = "translate_blocked_languages"; + } // namespace prefs } // namespace language
diff --git a/components/language/core/browser/pref_names.h b/components/language/core/browser/pref_names.h index a15a8b9..b878cfee 100644 --- a/components/language/core/browser/pref_names.h +++ b/components/language/core/browser/pref_names.h
@@ -21,6 +21,8 @@ // the user selected, if applicable. extern const char kApplicationLocale[]; +extern const char kFluentLanguages[]; + } // namespace prefs } // namespace language
diff --git a/components/plugins/renderer/webview_plugin.cc b/components/plugins/renderer/webview_plugin.cc index 509d298..58f56a3e 100644 --- a/components/plugins/renderer/webview_plugin.cc +++ b/components/plugins/renderer/webview_plugin.cc
@@ -69,10 +69,7 @@ WebViewPlugin* plugin = new WebViewPlugin(render_view, delegate, preferences); // Loading may synchronously access |delegate| which could be // uninitialized just yet, so load in another task. - scoped_refptr<base::SingleThreadTaskRunner> task_runner = - plugin->web_view_helper_.main_frame()->GetTaskRunner( - blink::TaskType::kInternalDefault); - task_runner->PostTask( + plugin->GetTaskRunner()->PostTask( FROM_HERE, base::BindOnce(&WebViewPlugin::LoadHTML, plugin->weak_factory_.GetWeakPtr(), html_data, url)); @@ -199,7 +196,7 @@ // Plugin updates are forbidden during Blink layout. Therefore, // UpdatePluginForNewGeometry must be posted to a task to run asynchronously. - base::ThreadTaskRunnerHandle::Get()->PostTask( + GetTaskRunner()->PostTask( FROM_HERE, base::BindOnce(&WebViewPlugin::UpdatePluginForNewGeometry, weak_factory_.GetWeakPtr(), window_rect, unobscured_rect)); @@ -411,3 +408,8 @@ web_view()->MainFrameWidget()->UpdateAllLifecyclePhases( blink::WebWidget::LifecycleUpdateReason::kOther); } + +scoped_refptr<base::SingleThreadTaskRunner> WebViewPlugin::GetTaskRunner() { + return web_view_helper_.main_frame()->GetTaskRunner( + blink::TaskType::kInternalDefault); +}
diff --git a/components/plugins/renderer/webview_plugin.h b/components/plugins/renderer/webview_plugin.h index db94a09..20bc3d1 100644 --- a/components/plugins/renderer/webview_plugin.h +++ b/components/plugins/renderer/webview_plugin.h
@@ -130,6 +130,8 @@ void UpdatePluginForNewGeometry(const blink::WebRect& window_rect, const blink::WebRect& unobscured_rect); + scoped_refptr<base::SingleThreadTaskRunner> GetTaskRunner(); + // Manages its own lifetime. Delegate* delegate_;
diff --git a/components/send_tab_to_self/BUILD.gn b/components/send_tab_to_self/BUILD.gn index 900b9b2..c9da2de7 100644 --- a/components/send_tab_to_self/BUILD.gn +++ b/components/send_tab_to_self/BUILD.gn
@@ -16,6 +16,7 @@ ] deps = [ "//base", + "//components/history/core/browser", "//components/keyed_service/core", "//components/send_tab_to_self/proto:send_tab_to_self_proto", "//components/sync", @@ -37,6 +38,7 @@ ":send_tab_to_self", "//base", "//base/test:test_support", + "//components/history/core/browser", "//components/send_tab_to_self/proto:send_tab_to_self_proto", "//components/sync", "//components/sync:test_support_driver",
diff --git a/components/send_tab_to_self/DEPS b/components/send_tab_to_self/DEPS index 4ccca580..8da4a5b5 100644 --- a/components/send_tab_to_self/DEPS +++ b/components/send_tab_to_self/DEPS
@@ -2,4 +2,5 @@ "+components/keyed_service/core", "+components/sync", "+components/version_info", + "+components/history", ]
diff --git a/components/send_tab_to_self/send_tab_to_self_bridge.cc b/components/send_tab_to_self/send_tab_to_self_bridge.cc index 3e2d56f..5c0cbf24 100644 --- a/components/send_tab_to_self/send_tab_to_self_bridge.cc +++ b/components/send_tab_to_self/send_tab_to_self_bridge.cc
@@ -10,6 +10,7 @@ #include "base/memory/ptr_util.h" #include "base/optional.h" #include "base/time/clock.h" +#include "components/history/core/browser/history_service.h" #include "components/send_tab_to_self/proto/send_tab_to_self.pb.h" #include "components/sync/device_info/device_info.h" #include "components/sync/device_info/local_device_info_provider.h" @@ -48,13 +49,18 @@ std::unique_ptr<syncer::ModelTypeChangeProcessor> change_processor, syncer::LocalDeviceInfoProvider* local_device_info_provider, base::Clock* clock, - syncer::OnceModelTypeStoreFactory create_store_callback) + syncer::OnceModelTypeStoreFactory create_store_callback, + history::HistoryService* history_service) : ModelTypeSyncBridge(std::move(change_processor)), clock_(clock), local_device_info_provider_(local_device_info_provider), + history_service_(history_service), weak_ptr_factory_(this) { DCHECK(local_device_info_provider); DCHECK(clock_); + if (history_service) { + history_service->AddObserver(this); + } std::move(create_store_callback) .Run(syncer::SEND_TAB_TO_SELF, @@ -63,6 +69,9 @@ } SendTabToSelfBridge::~SendTabToSelfBridge() { + if (history_service_) { + history_service_->RemoveObserver(this); + } } std::unique_ptr<syncer::MetadataChangeList> @@ -103,13 +112,18 @@ std::unique_ptr<SendTabToSelfEntry> entry = SendTabToSelfEntry::FromProto(specifics, clock_->Now()); - // This entry is new. Add it to the model. - added.push_back(entry.get()); - SendTabToSelfLocal entry_pb = entry->AsLocalProto(); - entries_[entry->GetGUID()] = std::move(entry); + // This entry is new. Add it to the model if it hasn't expired. + if (entry->IsExpired(clock_->Now())) { + // Remove expired data from server. + change_processor()->Delete(guid, batch->GetMetadataChangeList()); + } else { + added.push_back(entry.get()); + SendTabToSelfLocal entry_pb = entry->AsLocalProto(); + entries_[entry->GetGUID()] = std::move(entry); - // Write to the store. - batch->WriteData(guid, entry_pb.SerializeAsString()); + // Write to the store. + batch->WriteData(guid, entry_pb.SerializeAsString()); + } } } @@ -200,8 +214,14 @@ const SendTabToSelfEntry* SendTabToSelfBridge::AddEntry( const GURL& url, - const std::string& title) { + const std::string& title, + base::Time navigation_time) { if (!change_processor()->IsTrackingMetadata()) { + // TODO(crbug.com/940512) handle failure case. + return nullptr; + } + + if (navigation_time.is_null()) { return nullptr; } @@ -220,10 +240,6 @@ trimmed_title = base::CollapseWhitespaceASCII(title, false); } - // TODO(crbug.com/938102) Use history service to find most recent navigation - // time for url. - base::Time navigation_time = clock_->Now(); - auto entry = std::make_unique<SendTabToSelfEntry>( guid, url, trimmed_title, clock_->Now(), navigation_time, local_device_name_); @@ -238,11 +254,11 @@ const SendTabToSelfEntry* result = entries_.emplace(guid, std::move(entry)).first->second.get(); - SendTabToSelfLocal specifics = result->AsLocalProto(); - batch->WriteData(guid, specifics.SerializeAsString()); + batch->WriteData(guid, result->AsLocalProto().SerializeAsString()); Commit(std::move(batch)); + return result; } @@ -278,6 +294,22 @@ Commit(std::move(batch)); } +void SendTabToSelfBridge::OnURLsDeleted( + history::HistoryService* history_service, + const history::DeletionInfo& deletion_info) { + // We only care about actual user (or sync) deletions. + if (deletion_info.is_from_expiration()) + return; + + if (!deletion_info.IsAllHistory()) { + // TODO(crbug.com/938102) remove the specific entries that were deleted. + return; + } + + // All history was cleared: just delete all entries. + DeleteAllEntries(); +} + // static std::unique_ptr<syncer::ModelTypeStore> SendTabToSelfBridge::DestroyAndStealStoreForTest( @@ -368,6 +400,8 @@ } change_processor()->ModelReadyToSync(std::move(metadata_batch)); NotifySendTabToSelfModelLoaded(); + + DoGarbageCollection(); } void SendTabToSelfBridge::OnCommit( @@ -393,4 +427,21 @@ return it->second.get(); } +void SendTabToSelfBridge::DoGarbageCollection() { + std::vector<std::string> removed; + + auto entry = entries_.begin(); + while (entry != entries_.end()) { + DCHECK_EQ(entry->first, entry->second->GetGUID()); + std::string guid = entry->first; + bool expired = entry->second->IsExpired(clock_->Now()); + entry++; + if (expired) { + DeleteEntry(guid); + removed.push_back(guid); + } + } + NotifyRemoteSendTabToSelfEntryDeleted(removed); +} + } // namespace send_tab_to_self
diff --git a/components/send_tab_to_self/send_tab_to_self_bridge.h b/components/send_tab_to_self/send_tab_to_self_bridge.h index d4a2ef86..23fe968 100644 --- a/components/send_tab_to_self/send_tab_to_self_bridge.h +++ b/components/send_tab_to_self/send_tab_to_self_bridge.h
@@ -13,6 +13,8 @@ #include "base/macros.h" #include "base/memory/weak_ptr.h" +#include "base/time/time.h" +#include "components/history/core/browser/history_service_observer.h" #include "components/send_tab_to_self/send_tab_to_self_entry.h" #include "components/send_tab_to_self/send_tab_to_self_model.h" #include "components/sync/base/model_type.h" @@ -20,6 +22,10 @@ #include "components/sync/model/model_type_store.h" #include "components/sync/model/model_type_sync_bridge.h" +namespace history { +class HistoryService; +} // namespace history + namespace syncer { class ModelTypeChangeProcessor; } // namespace syncer @@ -33,7 +39,8 @@ // Interface for a persistence layer for send tab to self. // All interface methods have to be called on main thread. class SendTabToSelfBridge : public syncer::ModelTypeSyncBridge, - public SendTabToSelfModel { + public SendTabToSelfModel, + public history::HistoryServiceObserver { public: // |local_device_info_provider| must not be null and must outlive this object. // |clock| must not be null and must outlive this object. @@ -41,7 +48,8 @@ std::unique_ptr<syncer::ModelTypeChangeProcessor> change_processor, syncer::LocalDeviceInfoProvider* local_device_info_provider, base::Clock* clock, - syncer::OnceModelTypeStoreFactory create_store_callback); + syncer::OnceModelTypeStoreFactory create_store_callback, + history::HistoryService* history_service); ~SendTabToSelfBridge() override; // syncer::ModelTypeSyncBridge overrides. @@ -64,11 +72,15 @@ const SendTabToSelfEntry* GetEntryByGUID( const std::string& guid) const override; const SendTabToSelfEntry* AddEntry(const GURL& url, - const std::string& title) override; - + const std::string& title, + base::Time navigation_time) override; void DeleteEntry(const std::string& guid) override; void DismissEntry(const std::string& guid) override; + // history::HistoryServiceObserver: + void OnURLsDeleted(history::HistoryService* history_service, + const history::DeletionInfo& deletion_info) override; + // For testing only. static std::unique_ptr<syncer::ModelTypeStore> DestroyAndStealStoreForTest( std::unique_ptr<SendTabToSelfBridge> bridge); @@ -111,6 +123,9 @@ // exist. SendTabToSelfEntry* GetMutableEntryByGUID(const std::string& guid) const; + // Delete expired entries. + void DoGarbageCollection(); + // |entries_| is keyed by GUIDs. SendTabToSelfEntries entries_; @@ -120,6 +135,9 @@ // |local_device_info_provider_| isn't owned. syncer::LocalDeviceInfoProvider* const local_device_info_provider_; + // |history_service_| isn't owned. + history::HistoryService* const history_service_; + std::string local_device_name_; // In charge of actually persisting changes to disk, or loading previous data.
diff --git a/components/send_tab_to_self/send_tab_to_self_bridge_unittest.cc b/components/send_tab_to_self/send_tab_to_self_bridge_unittest.cc index 206c9a2..616a430 100644 --- a/components/send_tab_to_self/send_tab_to_self_bridge_unittest.cc +++ b/components/send_tab_to_self/send_tab_to_self_bridge_unittest.cc
@@ -13,6 +13,7 @@ #include "base/strings/stringprintf.h" #include "base/test/scoped_task_environment.h" #include "base/test/simple_test_clock.h" +#include "components/history/core/browser/history_service.h" #include "components/send_tab_to_self/proto/send_tab_to_self.pb.h" #include "components/sync/device_info/local_device_info_provider_mock.h" #include "components/sync/model/entity_change.h" @@ -83,7 +84,8 @@ void InitializeBridge() { bridge_ = std::make_unique<SendTabToSelfBridge>( mock_processor_.CreateForwardingProcessor(), &provider_, &clock_, - syncer::ModelTypeStoreTestUtil::MoveStoreToFactory(std::move(store_))); + syncer::ModelTypeStoreTestUtil::MoveStoreToFactory(std::move(store_)), + nullptr); bridge_->AddObserver(&mock_observer_); base::RunLoop().RunUntilIdle(); } @@ -95,8 +97,9 @@ base::RunLoop().RunUntilIdle(); } - base::Time AdvanceAndGetTime() { - clock_.Advance(base::TimeDelta::FromMilliseconds(10)); + base::Time AdvanceAndGetTime( + base::TimeDelta delta = base::TimeDelta::FromMilliseconds(10)) { + clock_.Advance(delta); return clock_.Now(); } @@ -137,10 +140,11 @@ // For Model Tests. void AddSampleEntries() { - bridge_->AddEntry(GURL("http://a.com"), "a"); - bridge_->AddEntry(GURL("http://b.com"), "b"); - bridge_->AddEntry(GURL("http://c.com"), "c"); - bridge_->AddEntry(GURL("http://d.com"), "d"); + // Adds timer to avoid having two entries with the same shared timestamp. + bridge_->AddEntry(GURL("http://a.com"), "a", AdvanceAndGetTime()); + bridge_->AddEntry(GURL("http://b.com"), "b", AdvanceAndGetTime()); + bridge_->AddEntry(GURL("http://c.com"), "c", AdvanceAndGetTime()); + bridge_->AddEntry(GURL("http://d.com"), "d", AdvanceAndGetTime()); } syncer::MockModelTypeChangeProcessor* processor() { return &mock_processor_; } @@ -353,6 +357,68 @@ EXPECT_TRUE(bridge()->GetEntryByGUID(guids[0])->GetNotificationDismissed()); } +TEST_F(SendTabToSelfBridgeTest, ExpireEntryDuringInit) { + InitializeBridge(); + + const sync_pb::SendTabToSelfSpecifics expired_specifics = + CreateSpecifics(1, AdvanceAndGetTime(), AdvanceAndGetTime()); + + AdvanceAndGetTime(kExpiryTime / 2.0); + + const sync_pb::SendTabToSelfSpecifics not_expired_specifics = + CreateSpecifics(2, AdvanceAndGetTime(), AdvanceAndGetTime()); + + sync_pb::ModelTypeState state = StateWithEncryption("ekn"); + std::unique_ptr<syncer::MetadataChangeList> metadata_changes = + bridge()->CreateMetadataChangeList(); + metadata_changes->UpdateModelTypeState(state); + + auto error = bridge()->ApplySyncChanges( + std::move(metadata_changes), + EntityAddList({expired_specifics, not_expired_specifics})); + ASSERT_FALSE(error); + + AdvanceAndGetTime(kExpiryTime / 2.0); + + EXPECT_CALL(*mock_observer(), EntriesRemovedRemotely(SizeIs(1))); + + ShutdownBridge(); + InitializeBridge(); + + std::vector<std::string> guids = bridge()->GetAllGuids(); + EXPECT_EQ(1ul, guids.size()); + EXPECT_EQ(not_expired_specifics.url(), + bridge()->GetEntryByGUID(guids[0])->GetURL().spec()); +} + +TEST_F(SendTabToSelfBridgeTest, AddExpiredEntry) { + InitializeBridge(); + + sync_pb::ModelTypeState state = StateWithEncryption("ekn"); + std::unique_ptr<syncer::MetadataChangeList> metadata_changes = + bridge()->CreateMetadataChangeList(); + metadata_changes->UpdateModelTypeState(state); + + const sync_pb::SendTabToSelfSpecifics expired_specifics = + CreateSpecifics(1, AdvanceAndGetTime(), AdvanceAndGetTime()); + + AdvanceAndGetTime(kExpiryTime); + + const sync_pb::SendTabToSelfSpecifics not_expired_specifics = + CreateSpecifics(2, AdvanceAndGetTime(), AdvanceAndGetTime()); + + auto error = bridge()->ApplySyncChanges( + std::move(metadata_changes), + EntityAddList({expired_specifics, not_expired_specifics})); + + ASSERT_FALSE(error); + + std::vector<std::string> guids = bridge()->GetAllGuids(); + EXPECT_EQ(1ul, guids.size()); + EXPECT_EQ(not_expired_specifics.url(), + bridge()->GetEntryByGUID(guids[0])->GetURL().spec()); +} + } // namespace } // namespace send_tab_to_self
diff --git a/components/send_tab_to_self/send_tab_to_self_entry.cc b/components/send_tab_to_self/send_tab_to_self_entry.cc index f8e7eac..60ddef68 100644 --- a/components/send_tab_to_self/send_tab_to_self_entry.cc +++ b/components/send_tab_to_self/send_tab_to_self_entry.cc
@@ -131,4 +131,10 @@ return to_return; } +bool SendTabToSelfEntry::IsExpired(base::Time current_time) const { + return (current_time.ToDeltaSinceWindowsEpoch() - + GetSharedTime().ToDeltaSinceWindowsEpoch() >= + kExpiryTime); +} + } // namespace send_tab_to_self
diff --git a/components/send_tab_to_self/send_tab_to_self_entry.h b/components/send_tab_to_self/send_tab_to_self_entry.h index 6b8011d..08bdc3a 100644 --- a/components/send_tab_to_self/send_tab_to_self_entry.h +++ b/components/send_tab_to_self/send_tab_to_self_entry.h
@@ -17,6 +17,8 @@ namespace send_tab_to_self { +constexpr base::TimeDelta kExpiryTime = base::TimeDelta::FromDays(10); + class SendTabToSelfLocal; // A tab that is being shared. The URL is a unique identifier for an entry, as @@ -71,6 +73,9 @@ const SendTabToSelfLocal& pb_entry, base::Time now); + // Returns if the Entry has expired based on the |current_time|. + bool IsExpired(base::Time current_time) const; + private: std::string guid_; GURL url_;
diff --git a/components/send_tab_to_self/send_tab_to_self_entry_unittest.cc b/components/send_tab_to_self/send_tab_to_self_entry_unittest.cc index a1006016..906d4bf 100644 --- a/components/send_tab_to_self/send_tab_to_self_entry_unittest.cc +++ b/components/send_tab_to_self/send_tab_to_self_entry_unittest.cc
@@ -91,6 +91,17 @@ EXPECT_TRUE(IsEqualForTesting(*entry, *pb_entry)); } +// Tests that the send tab to self entry expiry works as expected +TEST(SendTabToSelfEntry, IsExpired) { + SendTabToSelfEntry entry("1", GURL("http://example.com"), "bar", + base::Time::FromTimeT(10), base::Time::FromTimeT(10), + "device"); + + EXPECT_TRUE(entry.IsExpired(base::Time::FromTimeT(11) + + base::TimeDelta::FromDays(10))); + EXPECT_FALSE(entry.IsExpired(base::Time::FromTimeT(11))); +} + } // namespace } // namespace send_tab_to_self
diff --git a/components/send_tab_to_self/send_tab_to_self_model.h b/components/send_tab_to_self/send_tab_to_self_model.h index 6909d298..009d378c 100644 --- a/components/send_tab_to_self/send_tab_to_self_model.h +++ b/components/send_tab_to_self/send_tab_to_self_model.h
@@ -9,8 +9,10 @@ #include <vector> #include "base/observer_list.h" +#include "base/time/time.h" #include "components/send_tab_to_self/send_tab_to_self_entry.h" #include "components/send_tab_to_self/send_tab_to_self_model_observer.h" +#include "url/gurl.h" namespace send_tab_to_self { @@ -35,10 +37,10 @@ // Adds |url| at the top of the entries. The entry title will be a // trimmed copy of |title|. Allows clients to modify the state of the model // as driven by user behaviors. - // If the creation is successful this returns a pointer to the resulting - // Entry. Otherwise this will return nullptr. + // Returns the entry if it was successfully added. virtual const SendTabToSelfEntry* AddEntry(const GURL& url, - const std::string& title) = 0; + const std::string& title, + base::Time navigation_time) = 0; // Remove entry with |guid| from entries. Allows clients to modify the state // of the model as driven by user behaviors.
diff --git a/components/send_tab_to_self/send_tab_to_self_sync_service.cc b/components/send_tab_to_self/send_tab_to_self_sync_service.cc index 64de491..7fa4aca 100644 --- a/components/send_tab_to_self/send_tab_to_self_sync_service.cc +++ b/components/send_tab_to_self/send_tab_to_self_sync_service.cc
@@ -4,8 +4,11 @@ #include "components/send_tab_to_self/send_tab_to_self_sync_service.h" +#include <utility> + #include "base/bind.h" #include "base/time/default_clock.h" +#include "components/history/core/browser/history_service.h" #include "components/send_tab_to_self/send_tab_to_self_bridge.h" #include "components/send_tab_to_self/send_tab_to_self_model.h" #include "components/sync/base/report_unrecoverable_error.h" @@ -20,13 +23,14 @@ SendTabToSelfSyncService::SendTabToSelfSyncService( version_info::Channel channel, syncer::LocalDeviceInfoProvider* local_device_info_provider, - syncer::OnceModelTypeStoreFactory create_store_callback) { + syncer::OnceModelTypeStoreFactory create_store_callback, + history::HistoryService* history_service) { bridge_ = std::make_unique<send_tab_to_self::SendTabToSelfBridge>( std::make_unique<syncer::ClientTagBasedModelTypeProcessor>( syncer::SEND_TAB_TO_SELF, base::BindRepeating(&syncer::ReportUnrecoverableError, channel)), local_device_info_provider, base::DefaultClock::GetInstance(), - std::move(create_store_callback)); + std::move(create_store_callback), history_service); } SendTabToSelfSyncService::~SendTabToSelfSyncService() = default;
diff --git a/components/send_tab_to_self/send_tab_to_self_sync_service.h b/components/send_tab_to_self/send_tab_to_self_sync_service.h index 3d85da0..6d4460db6 100644 --- a/components/send_tab_to_self/send_tab_to_self_sync_service.h +++ b/components/send_tab_to_self/send_tab_to_self_sync_service.h
@@ -13,6 +13,10 @@ #include "components/sync/model/model_type_store_service.h" #include "components/version_info/channel.h" +namespace history { +class HistoryService; +} // namespace history + namespace syncer { class ModelTypeControllerDelegate; class LocalDeviceInfoProvider; @@ -28,7 +32,8 @@ SendTabToSelfSyncService( version_info::Channel channel, syncer::LocalDeviceInfoProvider* local_device_info_provider, - syncer::OnceModelTypeStoreFactory create_store_callback); + syncer::OnceModelTypeStoreFactory create_store_callback, + history::HistoryService* history_service); ~SendTabToSelfSyncService() override; virtual SendTabToSelfModel* GetSendTabToSelfModel();
diff --git a/components/signin/core/browser/chrome_connected_header_helper.cc b/components/signin/core/browser/chrome_connected_header_helper.cc index b29f6139..fa9c1b3 100644 --- a/components/signin/core/browser/chrome_connected_header_helper.cc +++ b/components/signin/core/browser/chrome_connected_header_helper.cc
@@ -39,8 +39,6 @@ return GAIA_SERVICE_TYPE_INCOGNITO; else if (header_value == "ADDSESSION") return GAIA_SERVICE_TYPE_ADDSESSION; - else if (header_value == "REAUTH") - return GAIA_SERVICE_TYPE_REAUTH; else if (header_value == "SIGNUP") return GAIA_SERVICE_TYPE_SIGNUP; else if (header_value == "DEFAULT")
diff --git a/components/signin/core/browser/signin_header_helper.h b/components/signin/core/browser/signin_header_helper.h index fdeb38a4..ab001f6 100644 --- a/components/signin/core/browser/signin_header_helper.h +++ b/components/signin/core/browser/signin_header_helper.h
@@ -47,7 +47,6 @@ GAIA_SERVICE_TYPE_SIGNOUT, // Logout all existing sessions. GAIA_SERVICE_TYPE_INCOGNITO, // Open an incognito tab. GAIA_SERVICE_TYPE_ADDSESSION, // Add a secondary account. - GAIA_SERVICE_TYPE_REAUTH, // Re-authenticate an account. GAIA_SERVICE_TYPE_SIGNUP, // Create a new account. GAIA_SERVICE_TYPE_DEFAULT, // All other cases. };
diff --git a/components/signin/core/browser/signin_header_helper_unittest.cc b/components/signin/core/browser/signin_header_helper_unittest.cc index 1002e880..ac7493a 100644 --- a/components/signin/core/browser/signin_header_helper_unittest.cc +++ b/components/signin/core/browser/signin_header_helper_unittest.cc
@@ -540,10 +540,11 @@ const char kContinueURL[] = "https://www.example.com/continue"; const char kEmail[] = "foo@example.com"; - ManageAccountsParams params = BuildManageAccountsParams(base::StringPrintf( - "action=REAUTH,email=%s,is_saml=true,is_same_tab=true,continue_url=%s", - kEmail, kContinueURL)); - EXPECT_EQ(GAIA_SERVICE_TYPE_REAUTH, params.service_type); + ManageAccountsParams params = BuildManageAccountsParams( + base::StringPrintf("action=ADDSESSION,email=%s,is_saml=true,is_same_tab=" + "true,continue_url=%s", + kEmail, kContinueURL)); + EXPECT_EQ(GAIA_SERVICE_TYPE_ADDSESSION, params.service_type); EXPECT_EQ(kEmail, params.email); EXPECT_EQ(true, params.is_saml); EXPECT_EQ(true, params.is_same_tab);
diff --git a/components/signin/ios/browser/account_consistency_service.mm b/components/signin/ios/browser/account_consistency_service.mm index bc6244f9..66f2a500 100644 --- a/components/signin/ios/browser/account_consistency_service.mm +++ b/components/signin/ios/browser/account_consistency_service.mm
@@ -122,7 +122,6 @@ [delegate_ onAddAccount]; break; case signin::GAIA_SERVICE_TYPE_SIGNOUT: - case signin::GAIA_SERVICE_TYPE_REAUTH: case signin::GAIA_SERVICE_TYPE_DEFAULT: [delegate_ onManageAccounts]; break;
diff --git a/components/sync/BUILD.gn b/components/sync/BUILD.gn index 6d227399..f73f036 100644 --- a/components/sync/BUILD.gn +++ b/components/sync/BUILD.gn
@@ -463,6 +463,7 @@ "model_impl/sync_metadata_store_change_list.h", "model_impl/syncable_service_based_bridge.cc", "model_impl/syncable_service_based_bridge.h", + "nigori/keystore_keys_handler.h", "nigori/nigori_sync_bridge.h", "protocol/proto_enum_conversions.cc", "protocol/proto_enum_conversions.h",
diff --git a/components/sync/android/BUILD.gn b/components/sync/android/BUILD.gn index f5dee92..d38c580 100644 --- a/components/sync/android/BUILD.gn +++ b/components/sync/android/BUILD.gn
@@ -59,7 +59,6 @@ "//components/sync/base/model_type.h", "//components/sync/base/stop_source.h", "//components/sync/driver/sync_service_utils.h", - "//components/sync/protocol/sync_protocol_error.h", ] }
diff --git a/components/sync/driver/glue/sync_backend_host_core.cc b/components/sync/driver/glue/sync_backend_host_core.cc index e5fce140..e22ec85d 100644 --- a/components/sync/driver/glue/sync_backend_host_core.cc +++ b/components/sync/driver/glue/sync_backend_host_core.cc
@@ -617,6 +617,14 @@ sync_manager_->UpdateInvalidationClientId(client_id); } +base::WeakPtr<ModelTypeControllerDelegate> +SyncBackendHostCore::GetNigoriControllerDelegate() { + // TODO(crbug.com/922900): return actual ModelTypeControllerDelegate. + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + NOTIMPLEMENTED(); + return nullptr; +} + bool SyncBackendHostCore::HasUnsyncedItemsForTest() const { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); DCHECK(sync_manager_);
diff --git a/components/sync/driver/glue/sync_backend_host_core.h b/components/sync/driver/glue/sync_backend_host_core.h index d545f99..097fef7f 100644 --- a/components/sync/driver/glue/sync_backend_host_core.h +++ b/components/sync/driver/glue/sync_backend_host_core.h
@@ -172,6 +172,9 @@ // Notify about change in client id. void DoOnInvalidatorClientIdChange(const std::string& client_id); + // Return ModelTypeControllerDelegate for Nigori. + base::WeakPtr<ModelTypeControllerDelegate> GetNigoriControllerDelegate(); + bool HasUnsyncedItemsForTest() const; private:
diff --git a/components/sync/driver/glue/sync_engine_impl.cc b/components/sync/driver/glue/sync_engine_impl.cc index b1b7cdbc..71922ec 100644 --- a/components/sync/driver/glue/sync_engine_impl.cc +++ b/components/sync/driver/glue/sync_engine_impl.cc
@@ -29,6 +29,7 @@ #include "components/sync/engine/sync_engine_host.h" #include "components/sync/engine/sync_manager_factory.h" #include "components/sync/engine/sync_string_conversions.h" +#include "components/sync/model_impl/proxy_model_type_controller_delegate.h" #include "components/sync/syncable/base_transaction.h" namespace syncer { @@ -446,6 +447,15 @@ DCHECK(success); } +std::unique_ptr<ModelTypeControllerDelegate> +SyncEngineImpl::GetNigoriControllerDelegate() { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + return std::make_unique<ProxyModelTypeControllerDelegate>( + sync_task_runner_, + base::BindRepeating(&SyncBackendHostCore::GetNigoriControllerDelegate, + base::RetainedRef(core_))); +} + void SyncEngineImpl::OnInvalidatorClientIdChange(const std::string& client_id) { sync_task_runner_->PostTask( FROM_HERE,
diff --git a/components/sync/driver/glue/sync_engine_impl.h b/components/sync/driver/glue/sync_engine_impl.h index 82100c060..8bbde17e 100644 --- a/components/sync/driver/glue/sync_engine_impl.h +++ b/components/sync/driver/glue/sync_engine_impl.h
@@ -91,6 +91,8 @@ bool empty_jar, const base::Closure& callback) override; void SetInvalidationsForSessionsEnabled(bool enabled) override; + std::unique_ptr<ModelTypeControllerDelegate> GetNigoriControllerDelegate() + override; // InvalidationHandler implementation. void OnInvalidatorStateChange(InvalidatorState state) override;
diff --git a/components/sync/engine/fake_sync_engine.cc b/components/sync/engine/fake_sync_engine.cc index 487b5bc..0ae2598 100644 --- a/components/sync/engine/fake_sync_engine.cc +++ b/components/sync/engine/fake_sync_engine.cc
@@ -6,6 +6,7 @@ #include "components/sync/engine/data_type_activation_response.h" #include "components/sync/engine/sync_engine_host.h" +#include "components/sync/model/model_type_controller_delegate.h" namespace syncer { namespace { @@ -100,6 +101,11 @@ } } +std::unique_ptr<ModelTypeControllerDelegate> +FakeSyncEngine::GetNigoriControllerDelegate() { + return nullptr; +} + void FakeSyncEngine::SetInvalidationsForSessionsEnabled(bool enabled) {} } // namespace syncer
diff --git a/components/sync/engine/fake_sync_engine.h b/components/sync/engine/fake_sync_engine.h index e6e3f54..74ce1f1 100644 --- a/components/sync/engine/fake_sync_engine.h +++ b/components/sync/engine/fake_sync_engine.h
@@ -87,6 +87,9 @@ const base::Closure& callback) override; void SetInvalidationsForSessionsEnabled(bool enabled) override; + std::unique_ptr<ModelTypeControllerDelegate> GetNigoriControllerDelegate() + override; + void set_fail_initial_download(bool should_fail); private:
diff --git a/components/sync/engine/mock_sync_engine.h b/components/sync/engine/mock_sync_engine.h index ee07ea1..db413c0 100644 --- a/components/sync/engine/mock_sync_engine.h +++ b/components/sync/engine/mock_sync_engine.h
@@ -10,6 +10,7 @@ #include "components/sync/engine/data_type_activation_response.h" #include "components/sync/engine/sync_engine.h" +#include "components/sync/model/model_type_controller_delegate.h" #include "testing/gmock/include/gmock/gmock.h" namespace syncer { @@ -59,6 +60,8 @@ MOCK_METHOD1(ClearServerData, void(const base::Closure&)); MOCK_METHOD3(OnCookieJarChanged, void(bool, bool, const base::Closure&)); MOCK_METHOD1(SetInvalidationsForSessionsEnabled, void(bool)); + MOCK_METHOD0(GetNigoriControllerDelegate, + std::unique_ptr<ModelTypeControllerDelegate>()); }; } // namespace syncer
diff --git a/components/sync/engine/sync_engine.h b/components/sync/engine/sync_engine.h index 29d35066..dbd2153e 100644 --- a/components/sync/engine/sync_engine.h +++ b/components/sync/engine/sync_engine.h
@@ -33,6 +33,7 @@ class CancelationSignal; class HttpPostProviderFactory; +class ModelTypeControllerDelegate; class SyncEngineHost; class SyncManagerFactory; class UnrecoverableErrorHandler; @@ -191,6 +192,10 @@ // Enables/Disables invalidations for session sync related datatypes. virtual void SetInvalidationsForSessionsEnabled(bool enabled) = 0; + // Returns ModelTypeControllerDelegate for Nigori. + virtual std::unique_ptr<ModelTypeControllerDelegate> + GetNigoriControllerDelegate() = 0; + private: DISALLOW_COPY_AND_ASSIGN(SyncEngine); };
diff --git a/components/sync/engine/sync_engine_switches.cc b/components/sync/engine/sync_engine_switches.cc index d5a3c05..e05efd0 100644 --- a/components/sync/engine/sync_engine_switches.cc +++ b/components/sync/engine/sync_engine_switches.cc
@@ -25,4 +25,8 @@ const base::Feature kSyncUseScryptForNewCustomPassphrases{ "SyncUseScryptForNewCustomPassphrases", base::FEATURE_ENABLED_BY_DEFAULT}; +// Enable USS implementation of Nigori datatype. +const base::Feature kSyncUSSNigori{"SyncUSSNigori", + base::FEATURE_DISABLED_BY_DEFAULT}; + } // namespace switches
diff --git a/components/sync/engine/sync_engine_switches.h b/components/sync/engine/sync_engine_switches.h index 6861251..5c5eedb 100644 --- a/components/sync/engine/sync_engine_switches.h +++ b/components/sync/engine/sync_engine_switches.h
@@ -14,6 +14,8 @@ extern const base::Feature kSyncResetPollIntervalOnStart; extern const base::Feature kSyncUseScryptForNewCustomPassphrases; +extern const base::Feature kSyncUSSNigori; + } // namespace switches #endif // COMPONENTS_SYNC_ENGINE_SYNC_ENGINE_SWITCHES_H_
diff --git a/components/sync/engine_impl/DEPS b/components/sync/engine_impl/DEPS index 78b788a..d97ea5e 100644 --- a/components/sync/engine_impl/DEPS +++ b/components/sync/engine_impl/DEPS
@@ -3,6 +3,7 @@ "+components/sync/engine", "+components/sync/js", "+components/sync/model", + "+components/sync/nigori", "+components/sync/protocol", "+components/sync/syncable", "+components/sync/test",
diff --git a/components/sync/engine_impl/get_updates_processor.cc b/components/sync/engine_impl/get_updates_processor.cc index e98ba9a..5171a2c 100644 --- a/components/sync/engine_impl/get_updates_processor.cc +++ b/components/sync/engine_impl/get_updates_processor.cc
@@ -15,8 +15,7 @@ #include "components/sync/engine_impl/get_updates_delegate.h" #include "components/sync/engine_impl/syncer_proto_util.h" #include "components/sync/engine_impl/update_handler.h" -#include "components/sync/syncable/directory.h" -#include "components/sync/syncable/nigori_handler.h" +#include "components/sync/nigori/keystore_keys_handler.h" #include "components/sync/syncable/syncable_read_transaction.h" namespace syncer { @@ -28,24 +27,22 @@ using TypeToIndexMap = std::map<ModelType, size_t>; bool ShouldRequestEncryptionKey(SyncCycleContext* context) { - syncable::Directory* dir = context->directory(); - syncable::ReadTransaction trans(FROM_HERE, dir); - syncable::NigoriHandler* nigori_handler = dir->GetNigoriHandler(); - return nigori_handler->NeedKeystoreKey(&trans); + return context->model_type_registry() + ->keystore_keys_handler() + ->NeedKeystoreKey(); } SyncerError HandleGetEncryptionKeyResponse( const sync_pb::ClientToServerResponse& update_response, - syncable::Directory* dir) { + SyncCycleContext* context) { bool success = false; if (update_response.get_updates().encryption_keys_size() == 0) { LOG(ERROR) << "Failed to receive encryption key from server."; return SyncerError(SyncerError::SERVER_RESPONSE_VALIDATION_FAILED); } - syncable::ReadTransaction trans(FROM_HERE, dir); - syncable::NigoriHandler* nigori_handler = dir->GetNigoriHandler(); - success = nigori_handler->SetKeystoreKeys( - update_response.get_updates().encryption_keys(), &trans); + success = + context->model_type_registry()->keystore_keys_handler()->SetKeystoreKeys( + update_response.get_updates().encryption_keys()); DVLOG(1) << "GetUpdates returned " << update_response.get_updates().encryption_keys_size() @@ -259,9 +256,8 @@ if (need_encryption_key || update_response.get_updates().encryption_keys_size() > 0) { - syncable::Directory* dir = cycle->context()->directory(); status->set_last_get_key_result( - HandleGetEncryptionKeyResponse(update_response, dir)); + HandleGetEncryptionKeyResponse(update_response, cycle->context())); } SyncerError process_result =
diff --git a/components/sync/engine_impl/model_type_registry.cc b/components/sync/engine_impl/model_type_registry.cc index 7a92ba06..0420cb50 100644 --- a/components/sync/engine_impl/model_type_registry.cc +++ b/components/sync/engine_impl/model_type_registry.cc
@@ -22,6 +22,7 @@ #include "components/sync/engine_impl/directory_commit_contributor.h" #include "components/sync/engine_impl/directory_update_handler.h" #include "components/sync/engine_impl/model_type_worker.h" +#include "components/sync/nigori/keystore_keys_handler.h" #include "components/sync/syncable/read_transaction.h" #include "components/sync/syncable/syncable_base_transaction.h" @@ -61,11 +62,13 @@ UserShare* user_share, NudgeHandler* nudge_handler, const UssMigrator& uss_migrator, - CancelationSignal* cancelation_signal) + CancelationSignal* cancelation_signal, + KeystoreKeysHandler* keystore_keys_handler) : user_share_(user_share), nudge_handler_(nudge_handler), uss_migrator_(uss_migrator), cancelation_signal_(cancelation_signal), + keystore_keys_handler_(keystore_keys_handler), weak_ptr_factory_(this) { for (size_t i = 0u; i < workers.size(); ++i) { workers_map_.insert( @@ -278,6 +281,10 @@ return &commit_contributor_map_; } +KeystoreKeysHandler* ModelTypeRegistry::keystore_keys_handler() { + return keystore_keys_handler_; +} + void ModelTypeRegistry::RegisterDirectoryTypeDebugInfoObserver( TypeDebugInfoObserver* observer) { if (!type_debug_info_observers_.HasObserver(observer))
diff --git a/components/sync/engine_impl/model_type_registry.h b/components/sync/engine_impl/model_type_registry.h index ae7c9b20..61172a3 100644 --- a/components/sync/engine_impl/model_type_registry.h +++ b/components/sync/engine_impl/model_type_registry.h
@@ -31,6 +31,7 @@ class DataTypeDebugInfoEmitter; class DirectoryCommitContributor; class DirectoryUpdateHandler; +class KeystoreKeysHandler; class ModelTypeWorker; class UpdateHandler; @@ -45,7 +46,8 @@ UserShare* user_share, NudgeHandler* nudge_handler, const UssMigrator& uss_migrator, - CancelationSignal* cancelation_signal); + CancelationSignal* cancelation_signal, + KeystoreKeysHandler* keystore_keys_handler); ~ModelTypeRegistry() override; // Enables an off-thread type for syncing. Connects the given proxy @@ -101,6 +103,7 @@ // Simple getters. UpdateHandlerMap* update_handler_map(); CommitContributorMap* commit_contributor_map(); + KeystoreKeysHandler* keystore_keys_handler(); void RegisterDirectoryTypeDebugInfoObserver(TypeDebugInfoObserver* observer); void UnregisterDirectoryTypeDebugInfoObserver( @@ -149,8 +152,7 @@ // The known ModelSafeWorkers. std::map<ModelSafeGroup, scoped_refptr<ModelSafeWorker>> workers_map_; - // The user share. Not owned. - UserShare* user_share_; + UserShare* const user_share_; // A copy of the directory's most recent cryptographer. std::unique_ptr<Cryptographer> cryptographer_; @@ -162,15 +164,16 @@ // The set of encrypted types. ModelTypeSet encrypted_types_; - // The NudgeHandler. Not owned. - NudgeHandler* nudge_handler_; + NudgeHandler* const nudge_handler_; // Function to call to migrate data from the directory to USS. UssMigrator uss_migrator_; // CancelationSignal is signalled on engine shutdown. It is passed to // ModelTypeWorker to cancel blocking operation. - CancelationSignal* cancelation_signal_; + CancelationSignal* const cancelation_signal_; + + KeystoreKeysHandler* const keystore_keys_handler_; // The set of observers of per-type debug info. //
diff --git a/components/sync/engine_impl/model_type_registry_unittest.cc b/components/sync/engine_impl/model_type_registry_unittest.cc index e3870150..9667ed85 100644 --- a/components/sync/engine_impl/model_type_registry_unittest.cc +++ b/components/sync/engine_impl/model_type_registry_unittest.cc
@@ -40,7 +40,7 @@ workers_, test_user_share_.user_share(), &mock_nudge_handler_, base::Bind(&ModelTypeRegistryTest::MigrateDirectory, base::Unretained(this)), - &cancelation_signal_); + &cancelation_signal_, test_user_share_.keystore_keys_handler()); } void TearDown() override {
diff --git a/components/sync/engine_impl/sync_encryption_handler_impl.cc b/components/sync/engine_impl/sync_encryption_handler_impl.cc index a0d4bf3..df9e2658 100644 --- a/components/sync/engine_impl/sync_encryption_handler_impl.cc +++ b/components/sync/engine_impl/sync_encryption_handler_impl.cc
@@ -35,6 +35,7 @@ #include "components/sync/syncable/read_transaction.h" #include "components/sync/syncable/syncable_base_transaction.h" #include "components/sync/syncable/syncable_model_neutral_write_transaction.h" +#include "components/sync/syncable/syncable_read_transaction.h" #include "components/sync/syncable/syncable_write_transaction.h" #include "components/sync/syncable/user_share.h" #include "components/sync/syncable/write_node.h" @@ -769,16 +770,16 @@ encrypt_everything_, nigori); } -bool SyncEncryptionHandlerImpl::NeedKeystoreKey( - syncable::BaseTransaction* const trans) const { +bool SyncEncryptionHandlerImpl::NeedKeystoreKey() const { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + syncable::ReadTransaction trans(FROM_HERE, user_share_->directory.get()); return keystore_key_.empty(); } bool SyncEncryptionHandlerImpl::SetKeystoreKeys( - const google::protobuf::RepeatedPtrField<google::protobuf::string>& keys, - syncable::BaseTransaction* const trans) { + const google::protobuf::RepeatedPtrField<google::protobuf::string>& keys) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + syncable::ReadTransaction trans(FROM_HERE, user_share_->directory.get()); if (keys.size() == 0) return false; // The last key in the vector is the current keystore key. The others are kept @@ -797,7 +798,7 @@ for (int i = 0; i < keys.size() - 1; ++i) base::Base64Encode(keys.Get(i), &old_keystore_keys_[i]); - Cryptographer* cryptographer = &UnlockVaultMutable(trans)->cryptographer; + Cryptographer* cryptographer = &UnlockVaultMutable(&trans)->cryptographer; // Update the bootstrap token. If this fails, we persist an empty string, // which will force us to download the keystore keys again on the next @@ -814,7 +815,7 @@ // If this is a first time sync, we get the encryption keys before we process // the nigori node. Just return for now, ApplyNigoriUpdate will be invoked // once we have the nigori node. - syncable::Entry entry(trans, syncable::GET_TYPE_ROOT, NIGORI); + syncable::Entry entry(&trans, syncable::GET_TYPE_ROOT, NIGORI); if (!entry.good()) return true; @@ -831,7 +832,7 @@ // Note that triggering migration will have no effect if we're already // properly migrated with the newest keystore keys. if (ShouldTriggerMigration(nigori, *cryptographer, - GetPassphraseType(trans))) { + GetPassphraseType(&trans))) { base::SequencedTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce(&SyncEncryptionHandlerImpl::RewriteNigori, weak_ptr_factory_.GetWeakPtr()));
diff --git a/components/sync/engine_impl/sync_encryption_handler_impl.h b/components/sync/engine_impl/sync_encryption_handler_impl.h index 249a0b5..1f028d4 100644 --- a/components/sync/engine_impl/sync_encryption_handler_impl.h +++ b/components/sync/engine_impl/sync_encryption_handler_impl.h
@@ -19,6 +19,7 @@ #include "base/time/time.h" #include "components/sync/base/cryptographer.h" #include "components/sync/engine/sync_encryption_handler.h" +#include "components/sync/nigori/keystore_keys_handler.h" #include "components/sync/syncable/nigori_handler.h" namespace syncer { @@ -43,11 +44,12 @@ // random salt. Used with scrypt key derivation method. // // Note: See sync_encryption_handler.h for a description of the chrome visible -// methods and what they do, and nigori_handler.h for a description of the -// sync methods. +// methods and what they do, and nigori_handler.h and keystore_keys_handler.h +// for a description of the sync methods. // All methods are non-thread-safe and should only be called from the sync // thread unless explicitly noted otherwise. -class SyncEncryptionHandlerImpl : public SyncEncryptionHandler, +class SyncEncryptionHandlerImpl : public KeystoreKeysHandler, + public SyncEncryptionHandler, public syncable::NigoriHandler { public: SyncEncryptionHandlerImpl( @@ -74,16 +76,17 @@ void UpdateNigoriFromEncryptedTypes( sync_pb::NigoriSpecifics* nigori, syncable::BaseTransaction* const trans) const override; - bool NeedKeystoreKey(syncable::BaseTransaction* const trans) const override; - bool SetKeystoreKeys( - const google::protobuf::RepeatedPtrField<google::protobuf::string>& keys, - syncable::BaseTransaction* const trans) override; // Can be called from any thread. ModelTypeSet GetEncryptedTypes( syncable::BaseTransaction* const trans) const override; PassphraseType GetPassphraseType( syncable::BaseTransaction* const trans) const override; + // KeystoreKeysHandler implementation. + bool NeedKeystoreKey() const override; + bool SetKeystoreKeys( + const google::protobuf::RepeatedPtrField<std::string>& keys) override; + // Unsafe getters. Use only if sync is not up and running and there is no risk // of other threads calling this. Cryptographer* GetCryptographerUnsafe();
diff --git a/components/sync/engine_impl/sync_encryption_handler_impl_unittest.cc b/components/sync/engine_impl/sync_encryption_handler_impl_unittest.cc index 47d565f4..95af66a 100644 --- a/components/sync/engine_impl/sync_encryption_handler_impl_unittest.cc +++ b/components/sync/engine_impl/sync_encryption_handler_impl_unittest.cc
@@ -392,11 +392,7 @@ EXPECT_CALL(*observer(), OnBootstrapTokenUpdated(_, KEYSTORE_BOOTSTRAP_TOKEN)); - { - ReadTransaction trans(FROM_HERE, user_share()); - encryption_handler()->SetKeystoreKeys(proto_keystore_keys, - trans.GetWrappedTrans()); - } + encryption_handler()->SetKeystoreKeys(proto_keystore_keys); PumpLoop(); Mock::VerifyAndClearExpectations(observer()); } @@ -849,14 +845,11 @@ TEST_F(SyncEncryptionHandlerImplTest, SetKeystoreMigratesAndUpdatesBootstrap) { // Passing no keys should do nothing. EXPECT_CALL(*observer(), OnBootstrapTokenUpdated(_, _)).Times(0); - { - WriteTransaction trans(FROM_HERE, user_share()); - EXPECT_FALSE(GetCryptographer()->is_initialized()); - EXPECT_TRUE(encryption_handler()->NeedKeystoreKey(trans.GetWrappedTrans())); - EXPECT_FALSE(encryption_handler()->SetKeystoreKeys( - BuildEncryptionKeyProto(std::string()), trans.GetWrappedTrans())); - EXPECT_TRUE(encryption_handler()->NeedKeystoreKey(trans.GetWrappedTrans())); - } + EXPECT_FALSE(GetCryptographer()->is_initialized()); + EXPECT_TRUE(encryption_handler()->NeedKeystoreKey()); + EXPECT_FALSE(encryption_handler()->SetKeystoreKeys( + BuildEncryptionKeyProto(std::string()))); + EXPECT_TRUE(encryption_handler()->NeedKeystoreKey()); Mock::VerifyAndClearExpectations(observer()); // Build a set of keystore keys. @@ -878,14 +871,9 @@ OnPassphraseTypeChanged(PassphraseType::KEYSTORE_PASSPHRASE, _)); EXPECT_CALL(*observer(), OnBootstrapTokenUpdated(_, KEYSTORE_BOOTSTRAP_TOKEN)) .WillOnce(SaveArg<0>(&keystore_bootstrap)); - { - WriteTransaction trans(FROM_HERE, user_share()); - EXPECT_TRUE( - encryption_handler()->SetKeystoreKeys(keys, trans.GetWrappedTrans())); - EXPECT_FALSE( - encryption_handler()->NeedKeystoreKey(trans.GetWrappedTrans())); - EXPECT_FALSE(GetCryptographer()->is_initialized()); - } + EXPECT_TRUE(encryption_handler()->SetKeystoreKeys(keys)); + EXPECT_FALSE(encryption_handler()->NeedKeystoreKey()); + EXPECT_FALSE(GetCryptographer()->is_initialized()); PumpLoop(); EXPECT_TRUE(GetCryptographer()->is_initialized()); VerifyMigratedNigori(PassphraseType::KEYSTORE_PASSPHRASE, kKeystoreKey, @@ -919,10 +907,7 @@ keystore_bootstrap, fake_random_salt_generator_); - { - WriteTransaction trans(FROM_HERE, user_share()); - EXPECT_FALSE(handler2.NeedKeystoreKey(trans.GetWrappedTrans())); - } + EXPECT_FALSE(handler2.NeedKeystoreKey()); } // Ensure GetKeystoreDecryptor only updates the keystore decryptor token if it @@ -948,14 +933,12 @@ // migrated, we should be in keystore passphrase state. TEST_F(SyncEncryptionHandlerImplTest, MigrateOnDecryptImplicitPass) { const char kOtherKey[] = "other"; - { - EXPECT_CALL(*observer(), - OnBootstrapTokenUpdated(_, KEYSTORE_BOOTSTRAP_TOKEN)); - ReadTransaction trans(FROM_HERE, user_share()); - encryption_handler()->SetKeystoreKeys( - BuildEncryptionKeyProto(kRawKeystoreKey), trans.GetWrappedTrans()); - Mock::VerifyAndClearExpectations(observer()); - } + + EXPECT_CALL(*observer(), + OnBootstrapTokenUpdated(_, KEYSTORE_BOOTSTRAP_TOKEN)); + encryption_handler()->SetKeystoreKeys( + BuildEncryptionKeyProto(kRawKeystoreKey)); + Mock::VerifyAndClearExpectations(observer()); EXPECT_FALSE(encryption_handler()->MigratedToKeystore()); { @@ -1000,14 +983,12 @@ // migrated, we should be in custom passphrase state with encrypt everything. TEST_F(SyncEncryptionHandlerImplTest, MigrateOnDecryptCustomPass) { const char kOtherKey[] = "other"; - { - EXPECT_CALL(*observer(), - OnBootstrapTokenUpdated(_, KEYSTORE_BOOTSTRAP_TOKEN)); - ReadTransaction trans(FROM_HERE, user_share()); - encryption_handler()->SetKeystoreKeys( - BuildEncryptionKeyProto(kRawKeystoreKey), trans.GetWrappedTrans()); - Mock::VerifyAndClearExpectations(observer()); - } + + EXPECT_CALL(*observer(), + OnBootstrapTokenUpdated(_, KEYSTORE_BOOTSTRAP_TOKEN)); + encryption_handler()->SetKeystoreKeys( + BuildEncryptionKeyProto(kRawKeystoreKey)); + Mock::VerifyAndClearExpectations(observer()); EXPECT_FALSE(encryption_handler()->MigratedToKeystore()); { @@ -1072,15 +1053,12 @@ encryption_handler()->Init(); Mock::VerifyAndClearExpectations(observer()); - { - ReadTransaction trans(FROM_HERE, user_share()); - // Once we provide a keystore key, we should perform the migration. - EXPECT_CALL(*observer(), OnCryptographerStateChanged(_)).Times(AnyNumber()); - EXPECT_CALL(*observer(), - OnBootstrapTokenUpdated(_, KEYSTORE_BOOTSTRAP_TOKEN)); - encryption_handler()->SetKeystoreKeys( - BuildEncryptionKeyProto(kRawKeystoreKey), trans.GetWrappedTrans()); - } + // Once we provide a keystore key, we should perform the migration. + EXPECT_CALL(*observer(), OnCryptographerStateChanged(_)).Times(AnyNumber()); + EXPECT_CALL(*observer(), + OnBootstrapTokenUpdated(_, KEYSTORE_BOOTSTRAP_TOKEN)); + encryption_handler()->SetKeystoreKeys( + BuildEncryptionKeyProto(kRawKeystoreKey)); EXPECT_CALL(*observer(), OnPassphraseTypeChanged(PassphraseType::KEYSTORE_PASSPHRASE, _)); // The actual migration gets posted, so run all pending tasks. @@ -1112,15 +1090,12 @@ EXPECT_CALL(*observer(), OnEncryptionComplete()); encryption_handler()->EnableEncryptEverything(); - { - ReadTransaction trans(FROM_HERE, user_share()); - // Once we provide a keystore key, we should perform the migration. - EXPECT_CALL(*observer(), OnCryptographerStateChanged(_)).Times(AnyNumber()); - EXPECT_CALL(*observer(), - OnBootstrapTokenUpdated(_, KEYSTORE_BOOTSTRAP_TOKEN)); - encryption_handler()->SetKeystoreKeys( - BuildEncryptionKeyProto(kRawKeystoreKey), trans.GetWrappedTrans()); - } + // Once we provide a keystore key, we should perform the migration. + EXPECT_CALL(*observer(), OnCryptographerStateChanged(_)).Times(AnyNumber()); + EXPECT_CALL(*observer(), + OnBootstrapTokenUpdated(_, KEYSTORE_BOOTSTRAP_TOKEN)); + encryption_handler()->SetKeystoreKeys( + BuildEncryptionKeyProto(kRawKeystoreKey)); EXPECT_CALL(*observer(), OnPassphraseTypeChanged( PassphraseType::FROZEN_IMPLICIT_PASSPHRASE, _)); @@ -1174,17 +1149,14 @@ Mock::VerifyAndClearExpectations(observer()); SyncEncryptionHandler::NigoriState captured_nigori_state; - { - ReadTransaction trans(FROM_HERE, user_share()); - // Once we provide a keystore key, we should perform the migration. - EXPECT_CALL(*observer(), OnCryptographerStateChanged(_)).Times(AnyNumber()); - EXPECT_CALL(*observer(), - OnBootstrapTokenUpdated(_, KEYSTORE_BOOTSTRAP_TOKEN)); - EXPECT_CALL(*observer(), OnLocalSetPassphraseEncryption(_)) - .WillOnce(testing::SaveArg<0>(&captured_nigori_state)); - encryption_handler()->SetKeystoreKeys( - BuildEncryptionKeyProto(kRawKeystoreKey), trans.GetWrappedTrans()); - } + // Once we provide a keystore key, we should perform the migration. + EXPECT_CALL(*observer(), OnCryptographerStateChanged(_)).Times(AnyNumber()); + EXPECT_CALL(*observer(), + OnBootstrapTokenUpdated(_, KEYSTORE_BOOTSTRAP_TOKEN)); + EXPECT_CALL(*observer(), OnLocalSetPassphraseEncryption(_)) + .WillOnce(testing::SaveArg<0>(&captured_nigori_state)); + encryption_handler()->SetKeystoreKeys( + BuildEncryptionKeyProto(kRawKeystoreKey)); // The actual migration gets posted, so run all pending tasks. PumpLoop(); @@ -1226,15 +1198,12 @@ EXPECT_FALSE(encryption_handler()->custom_passphrase_time().is_null()); Mock::VerifyAndClearExpectations(observer()); - { - ReadTransaction trans(FROM_HERE, user_share()); - // Once we provide a keystore key, we should perform the migration. - EXPECT_CALL(*observer(), OnCryptographerStateChanged(_)).Times(AnyNumber()); - EXPECT_CALL(*observer(), - OnBootstrapTokenUpdated(_, KEYSTORE_BOOTSTRAP_TOKEN)); - encryption_handler()->SetKeystoreKeys( - BuildEncryptionKeyProto(kRawKeystoreKey), trans.GetWrappedTrans()); - } + // Once we provide a keystore key, we should perform the migration. + EXPECT_CALL(*observer(), OnCryptographerStateChanged(_)).Times(AnyNumber()); + EXPECT_CALL(*observer(), + OnBootstrapTokenUpdated(_, KEYSTORE_BOOTSTRAP_TOKEN)); + encryption_handler()->SetKeystoreKeys( + BuildEncryptionKeyProto(kRawKeystoreKey)); EXPECT_CALL(*observer(), OnEncryptedTypesChanged(_, true)); SyncEncryptionHandler::NigoriState captured_nigori_state; EXPECT_CALL(*observer(), OnLocalSetPassphraseEncryption(_)) @@ -1277,28 +1246,26 @@ // Now build a nigori node with the generated keystore decryptor token and // initialize the encryption handler with it. The cryptographer should be // initialized properly to decrypt both kCurKey and kKeystoreKey. + sync_pb::NigoriSpecifics nigori; + nigori.mutable_keystore_decryptor_token()->CopyFrom(keystore_decryptor_token); + other_cryptographer.GetKeys(nigori.mutable_encryption_keybag()); + nigori.set_keybag_is_frozen(true); + nigori.set_keystore_migration_time(1); + nigori.set_passphrase_type(sync_pb::NigoriSpecifics::KEYSTORE_PASSPHRASE); + EXPECT_CALL(*observer(), OnPassphraseAccepted()); + EXPECT_CALL(*observer(), + OnBootstrapTokenUpdated(_, PASSPHRASE_BOOTSTRAP_TOKEN)); + EXPECT_CALL(*observer(), + OnBootstrapTokenUpdated(_, KEYSTORE_BOOTSTRAP_TOKEN)); + EXPECT_CALL(*observer(), + OnPassphraseTypeChanged(PassphraseType::KEYSTORE_PASSPHRASE, _)); + EXPECT_CALL(*observer(), OnCryptographerStateChanged(_)).Times(AnyNumber()); + encryption_handler()->SetKeystoreKeys( + BuildEncryptionKeyProto(kRawKeystoreKey)); { WriteTransaction trans(FROM_HERE, user_share()); WriteNode nigori_node(&trans); ASSERT_EQ(nigori_node.InitTypeRoot(NIGORI), BaseNode::INIT_OK); - sync_pb::NigoriSpecifics nigori; - nigori.mutable_keystore_decryptor_token()->CopyFrom( - keystore_decryptor_token); - other_cryptographer.GetKeys(nigori.mutable_encryption_keybag()); - nigori.set_keybag_is_frozen(true); - nigori.set_keystore_migration_time(1); - nigori.set_passphrase_type(sync_pb::NigoriSpecifics::KEYSTORE_PASSPHRASE); - - EXPECT_CALL(*observer(), OnPassphraseAccepted()); - EXPECT_CALL(*observer(), - OnBootstrapTokenUpdated(_, PASSPHRASE_BOOTSTRAP_TOKEN)); - EXPECT_CALL(*observer(), - OnBootstrapTokenUpdated(_, KEYSTORE_BOOTSTRAP_TOKEN)); - EXPECT_CALL(*observer(), OnPassphraseTypeChanged( - PassphraseType::KEYSTORE_PASSPHRASE, _)); - EXPECT_CALL(*observer(), OnCryptographerStateChanged(_)).Times(AnyNumber()); - encryption_handler()->SetKeystoreKeys( - BuildEncryptionKeyProto(kRawKeystoreKey), trans.GetWrappedTrans()); encryption_handler()->ApplyNigoriUpdate(nigori, trans.GetWrappedTrans()); nigori_node.SetNigoriSpecifics(nigori); } @@ -1341,13 +1308,10 @@ other_cryptographer.AddKey(cur_key); EXPECT_FALSE(encryption_handler()->MigratedToKeystore()); - { - EXPECT_CALL(*observer(), - OnBootstrapTokenUpdated(_, KEYSTORE_BOOTSTRAP_TOKEN)); - ReadTransaction trans(FROM_HERE, user_share()); - encryption_handler()->SetKeystoreKeys( - BuildEncryptionKeyProto(kRawKeystoreKey), trans.GetWrappedTrans()); - } + EXPECT_CALL(*observer(), + OnBootstrapTokenUpdated(_, KEYSTORE_BOOTSTRAP_TOKEN)); + encryption_handler()->SetKeystoreKeys( + BuildEncryptionKeyProto(kRawKeystoreKey)); EXPECT_FALSE(encryption_handler()->MigratedToKeystore()); { @@ -1418,13 +1382,10 @@ other_cryptographer.AddKey(cur_key); EXPECT_FALSE(encryption_handler()->MigratedToKeystore()); - { - EXPECT_CALL(*observer(), - OnBootstrapTokenUpdated(_, KEYSTORE_BOOTSTRAP_TOKEN)); - ReadTransaction trans(FROM_HERE, user_share()); - encryption_handler()->SetKeystoreKeys( - BuildEncryptionKeyProto(kRawKeystoreKey), trans.GetWrappedTrans()); - } + EXPECT_CALL(*observer(), + OnBootstrapTokenUpdated(_, KEYSTORE_BOOTSTRAP_TOKEN)); + encryption_handler()->SetKeystoreKeys( + BuildEncryptionKeyProto(kRawKeystoreKey)); EXPECT_FALSE(encryption_handler()->MigratedToKeystore()); { @@ -1522,13 +1483,11 @@ PassphraseType::CUSTOM_PASSPHRASE, kCurKey, {KeyDerivationParams::CreateForPbkdf2()}); - { - EXPECT_CALL(*observer(), - OnBootstrapTokenUpdated(_, KEYSTORE_BOOTSTRAP_TOKEN)); - ReadTransaction trans(FROM_HERE, user_share()); - encryption_handler()->SetKeystoreKeys( - BuildEncryptionKeyProto(kRawKeystoreKey), trans.GetWrappedTrans()); - } + EXPECT_CALL(*observer(), + OnBootstrapTokenUpdated(_, KEYSTORE_BOOTSTRAP_TOKEN)); + encryption_handler()->SetKeystoreKeys( + BuildEncryptionKeyProto(kRawKeystoreKey)); + Mock::VerifyAndClearExpectations(observer()); // Now build an old unmigrated nigori node with old encrypted types. We should @@ -1613,13 +1572,11 @@ kCurKey, {KeyDerivationParams::CreateForPbkdf2()}); - { - EXPECT_CALL(*observer(), - OnBootstrapTokenUpdated(_, KEYSTORE_BOOTSTRAP_TOKEN)); - ReadTransaction trans(FROM_HERE, user_share()); - encryption_handler()->SetKeystoreKeys( - BuildEncryptionKeyProto(kRawKeystoreKey), trans.GetWrappedTrans()); - } + EXPECT_CALL(*observer(), + OnBootstrapTokenUpdated(_, KEYSTORE_BOOTSTRAP_TOKEN)); + encryption_handler()->SetKeystoreKeys( + BuildEncryptionKeyProto(kRawKeystoreKey)); + Mock::VerifyAndClearExpectations(observer()); // Now build an old keystore nigori node with old encrypted types. We should @@ -1722,13 +1679,11 @@ EXPECT_CALL(*observer(), OnCryptographerStateChanged(_)).Times(AnyNumber()); EXPECT_CALL(*observer(), OnBootstrapTokenUpdated(_, PASSPHRASE_BOOTSTRAP_TOKEN)); - { - EXPECT_CALL(*observer(), - OnBootstrapTokenUpdated(_, KEYSTORE_BOOTSTRAP_TOKEN)); - ReadTransaction trans(FROM_HERE, user_share()); - encryption_handler()->SetKeystoreKeys( - BuildEncryptionKeyProto(kRawKeystoreKey), trans.GetWrappedTrans()); - } + EXPECT_CALL(*observer(), + OnBootstrapTokenUpdated(_, KEYSTORE_BOOTSTRAP_TOKEN)); + encryption_handler()->SetKeystoreKeys( + BuildEncryptionKeyProto(kRawKeystoreKey)); + PumpLoop(); EXPECT_TRUE(encryption_handler()->MigratedToKeystore()); EXPECT_TRUE(GetCryptographer()->is_ready()); @@ -1782,11 +1737,11 @@ nigori.set_keystore_migration_time(migration_time); nigori.set_passphrase_type(sync_pb::NigoriSpecifics::KEYSTORE_PASSPHRASE); nigori_node.SetNigoriSpecifics(nigori); - EXPECT_CALL(*observer(), - OnBootstrapTokenUpdated(_, KEYSTORE_BOOTSTRAP_TOKEN)); - encryption_handler()->SetKeystoreKeys( - BuildEncryptionKeyProto(kRawKeystoreKey), trans.GetWrappedTrans()); } + EXPECT_CALL(*observer(), + OnBootstrapTokenUpdated(_, KEYSTORE_BOOTSTRAP_TOKEN)); + encryption_handler()->SetKeystoreKeys( + BuildEncryptionKeyProto(kRawKeystoreKey)); EXPECT_CALL(*observer(), OnPassphraseAccepted()); EXPECT_CALL(*observer(), @@ -2091,13 +2046,11 @@ EXPECT_TRUE(GetCryptographer()->is_ready()); EXPECT_FALSE(encryption_handler()->IsEncryptEverythingEnabled()); - { - EXPECT_CALL(*observer(), - OnBootstrapTokenUpdated(_, KEYSTORE_BOOTSTRAP_TOKEN)); - ReadTransaction trans(FROM_HERE, user_share()); - encryption_handler()->SetKeystoreKeys( - BuildEncryptionKeyProto(kRawKeystoreKey), trans.GetWrappedTrans()); - } + EXPECT_CALL(*observer(), + OnBootstrapTokenUpdated(_, KEYSTORE_BOOTSTRAP_TOKEN)); + encryption_handler()->SetKeystoreKeys( + BuildEncryptionKeyProto(kRawKeystoreKey)); + EXPECT_CALL(*observer(), OnPassphraseTypeChanged(PassphraseType::KEYSTORE_PASSPHRASE, _)); PumpLoop(); @@ -2217,16 +2170,14 @@ InitAndVerifyUnmigratedNigori(kOldGaiaKey, PassphraseType::IMPLICIT_PASSPHRASE); - { - // Pass multiple keystore keys, signaling a rotation has happened. - google::protobuf::RepeatedPtrField<google::protobuf::string> keys; - keys.Add()->assign(kRawOldKeystoreKey); - keys.Add()->assign(kRawKeystoreKey); - ReadTransaction trans(FROM_HERE, user_share()); - EXPECT_CALL(*observer(), - OnBootstrapTokenUpdated(_, KEYSTORE_BOOTSTRAP_TOKEN)); - encryption_handler()->SetKeystoreKeys(keys, trans.GetWrappedTrans()); - } + // Pass multiple keystore keys, signaling a rotation has happened. + google::protobuf::RepeatedPtrField<google::protobuf::string> keys; + keys.Add()->assign(kRawOldKeystoreKey); + keys.Add()->assign(kRawKeystoreKey); + EXPECT_CALL(*observer(), + OnBootstrapTokenUpdated(_, KEYSTORE_BOOTSTRAP_TOKEN)); + encryption_handler()->SetKeystoreKeys(keys); + PumpLoop(); Mock::VerifyAndClearExpectations(observer()); @@ -2287,16 +2238,14 @@ InitAndVerifyUnmigratedNigori(kOldGaiaKey, PassphraseType::IMPLICIT_PASSPHRASE); - { - // Pass multiple keystore keys, signaling a rotation has happened. - google::protobuf::RepeatedPtrField<google::protobuf::string> keys; - keys.Add()->assign(kRawOldKeystoreKey); - keys.Add()->assign(kRawKeystoreKey); - ReadTransaction trans(FROM_HERE, user_share()); - EXPECT_CALL(*observer(), - OnBootstrapTokenUpdated(_, KEYSTORE_BOOTSTRAP_TOKEN)); - encryption_handler()->SetKeystoreKeys(keys, trans.GetWrappedTrans()); - } + // Pass multiple keystore keys, signaling a rotation has happened. + google::protobuf::RepeatedPtrField<google::protobuf::string> keys; + keys.Add()->assign(kRawOldKeystoreKey); + keys.Add()->assign(kRawKeystoreKey); + EXPECT_CALL(*observer(), + OnBootstrapTokenUpdated(_, KEYSTORE_BOOTSTRAP_TOKEN)); + encryption_handler()->SetKeystoreKeys(keys); + PumpLoop(); Mock::VerifyAndClearExpectations(observer()); @@ -2336,16 +2285,14 @@ EXPECT_CALL(*observer(), OnPassphraseRequired(_, _, _)); InitAndVerifyUnmigratedNigori(kCustomPass, PassphraseType::CUSTOM_PASSPHRASE); - { - // Pass multiple keystore keys, signaling a rotation has happened. - google::protobuf::RepeatedPtrField<google::protobuf::string> keys; - keys.Add()->assign(kRawOldKeystoreKey); - keys.Add()->assign(kRawKeystoreKey); - ReadTransaction trans(FROM_HERE, user_share()); - EXPECT_CALL(*observer(), - OnBootstrapTokenUpdated(_, KEYSTORE_BOOTSTRAP_TOKEN)); - encryption_handler()->SetKeystoreKeys(keys, trans.GetWrappedTrans()); - } + // Pass multiple keystore keys, signaling a rotation has happened. + google::protobuf::RepeatedPtrField<google::protobuf::string> keys; + keys.Add()->assign(kRawOldKeystoreKey); + keys.Add()->assign(kRawKeystoreKey); + EXPECT_CALL(*observer(), + OnBootstrapTokenUpdated(_, KEYSTORE_BOOTSTRAP_TOKEN)); + encryption_handler()->SetKeystoreKeys(keys); + PumpLoop(); Mock::VerifyAndClearExpectations(observer()); @@ -2393,19 +2340,17 @@ {KeyDerivationParams::CreateForPbkdf2()}); SyncEncryptionHandler::NigoriState captured_nigori_state; - { - // Pass multiple keystore keys, signaling a rotation has happened. - google::protobuf::RepeatedPtrField<google::protobuf::string> keys; - keys.Add()->assign(kRawOldKeystoreKey); - keys.Add()->assign(kRawKeystoreKey); - ReadTransaction trans(FROM_HERE, user_share()); - EXPECT_CALL(*observer(), - OnBootstrapTokenUpdated(_, KEYSTORE_BOOTSTRAP_TOKEN)); - EXPECT_CALL(*observer(), OnCryptographerStateChanged(_)).Times(AnyNumber()); - EXPECT_CALL(*observer(), OnLocalSetPassphraseEncryption(_)) - .WillOnce(testing::SaveArg<0>(&captured_nigori_state)); - encryption_handler()->SetKeystoreKeys(keys, trans.GetWrappedTrans()); - } + // Pass multiple keystore keys, signaling a rotation has happened. + google::protobuf::RepeatedPtrField<google::protobuf::string> keys; + keys.Add()->assign(kRawOldKeystoreKey); + keys.Add()->assign(kRawKeystoreKey); + EXPECT_CALL(*observer(), + OnBootstrapTokenUpdated(_, KEYSTORE_BOOTSTRAP_TOKEN)); + EXPECT_CALL(*observer(), OnCryptographerStateChanged(_)).Times(AnyNumber()); + EXPECT_CALL(*observer(), OnLocalSetPassphraseEncryption(_)) + .WillOnce(testing::SaveArg<0>(&captured_nigori_state)); + encryption_handler()->SetKeystoreKeys(keys); + PumpLoop(); Mock::VerifyAndClearExpectations(observer()); @@ -2456,11 +2401,8 @@ EXPECT_CALL(*observer(), OnCryptographerStateChanged(_)).Times(AnyNumber()); EXPECT_CALL(*observer(), OnBootstrapTokenUpdated(_, KEYSTORE_BOOTSTRAP_TOKEN)); - { - ReadTransaction trans(FROM_HERE, user_share()); - encryption_handler()->SetKeystoreKeys( - BuildEncryptionKeyProto(kRawKeystoreKey), trans.GetWrappedTrans()); - } + encryption_handler()->SetKeystoreKeys( + BuildEncryptionKeyProto(kRawKeystoreKey)); } // When we receive a remote Nigori with UNSPECIFIED as the key derivation
diff --git a/components/sync/engine_impl/sync_manager_impl.cc b/components/sync/engine_impl/sync_manager_impl.cc index ffbdab7e..4473f84 100644 --- a/components/sync/engine_impl/sync_manager_impl.cc +++ b/components/sync/engine_impl/sync_manager_impl.cc
@@ -351,7 +351,7 @@ model_type_registry_ = std::make_unique<ModelTypeRegistry>( args->workers, &share_, this, base::Bind(&MigrateDirectoryData), - args->cancelation_signal); + args->cancelation_signal, sync_encryption_handler_.get()); sync_encryption_handler_->AddObserver(model_type_registry_.get()); // Build a SyncCycleContext and store the worker in it.
diff --git a/components/sync/engine_impl/sync_scheduler_impl_unittest.cc b/components/sync/engine_impl/sync_scheduler_impl_unittest.cc index 901a904968..ccb16ce 100644 --- a/components/sync/engine_impl/sync_scheduler_impl_unittest.cc +++ b/components/sync/engine_impl/sync_scheduler_impl_unittest.cc
@@ -129,7 +129,8 @@ model_type_registry_ = std::make_unique<ModelTypeRegistry>( workers_, test_user_share_.user_share(), &mock_nudge_handler_, - UssMigrator(), &cancelation_signal_); + UssMigrator(), &cancelation_signal_, + test_user_share_.keystore_keys_handler()); model_type_registry_->RegisterDirectoryType(HISTORY_DELETE_DIRECTIVES, GROUP_UI); model_type_registry_->RegisterDirectoryType(NIGORI, GROUP_PASSIVE);
diff --git a/components/sync/engine_impl/syncer_unittest.cc b/components/sync/engine_impl/syncer_unittest.cc index 4635571..bc4485e 100644 --- a/components/sync/engine_impl/syncer_unittest.cc +++ b/components/sync/engine_impl/syncer_unittest.cc
@@ -267,7 +267,8 @@ model_type_registry_ = std::make_unique<ModelTypeRegistry>( workers_, test_user_share_.user_share(), &mock_nudge_handler_, - UssMigrator(), &cancelation_signal_); + UssMigrator(), &cancelation_signal_, + test_user_share_.keystore_keys_handler()); model_type_registry_->RegisterDirectoryTypeDebugInfoObserver( &debug_info_cache_); @@ -4846,36 +4847,28 @@ } TEST_F(SyncerTest, GetKeySuccess) { - { - syncable::ReadTransaction rtrans(FROM_HERE, directory()); - EXPECT_TRUE(directory()->GetNigoriHandler()->NeedKeystoreKey(&rtrans)); - } + KeystoreKeysHandler* keystore_keys_handler = + model_type_registry_->keystore_keys_handler(); + EXPECT_TRUE(keystore_keys_handler->NeedKeystoreKey()); SyncShareConfigure(); EXPECT_EQ(SyncerError::SYNCER_OK, cycle_->status_controller().last_get_key_result().value()); - { - syncable::ReadTransaction rtrans(FROM_HERE, directory()); - EXPECT_FALSE(directory()->GetNigoriHandler()->NeedKeystoreKey(&rtrans)); - } + EXPECT_FALSE(keystore_keys_handler->NeedKeystoreKey()); } TEST_F(SyncerTest, GetKeyEmpty) { - { - syncable::ReadTransaction rtrans(FROM_HERE, directory()); - EXPECT_TRUE(directory()->GetNigoriHandler()->NeedKeystoreKey(&rtrans)); - } + KeystoreKeysHandler* keystore_keys_handler = + model_type_registry_->keystore_keys_handler(); + EXPECT_TRUE(keystore_keys_handler->NeedKeystoreKey()); mock_server_->SetKeystoreKey(std::string()); SyncShareConfigure(); EXPECT_NE(SyncerError::SYNCER_OK, cycle_->status_controller().last_get_key_result().value()); - { - syncable::ReadTransaction rtrans(FROM_HERE, directory()); - EXPECT_TRUE(directory()->GetNigoriHandler()->NeedKeystoreKey(&rtrans)); - } + EXPECT_TRUE(keystore_keys_handler->NeedKeystoreKey()); } // Trigger an update that contains a progress marker only and verify that
diff --git a/components/sync/nigori/keystore_keys_handler.h b/components/sync/nigori/keystore_keys_handler.h new file mode 100644 index 0000000..ef5476c7 --- /dev/null +++ b/components/sync/nigori/keystore_keys_handler.h
@@ -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. + +#ifndef COMPONENTS_SYNC_NIGORI_KEYSTORE_KEYS_HANDLER_H_ +#define COMPONENTS_SYNC_NIGORI_KEYSTORE_KEYS_HANDLER_H_ + +#include <google/protobuf/repeated_field.h> +#include <string> + +#include "base/macros.h" + +namespace syncer { + +// Sync internal interface for dealing with Nigori keystore keys. +class KeystoreKeysHandler { + public: + KeystoreKeysHandler() = default; + virtual ~KeystoreKeysHandler() = default; + + // Whether a keystore key needs to be requested from the sync server. + virtual bool NeedKeystoreKey() const = 0; + + // Sets the keystore keys the server returned for this account. + // Returns true on success, false otherwise. + virtual bool SetKeystoreKeys( + const google::protobuf::RepeatedPtrField<std::string>& keys) = 0; + + private: + DISALLOW_COPY_AND_ASSIGN(KeystoreKeysHandler); +}; + +} // namespace syncer + +#endif // COMPONENTS_SYNC_NIGORI_KEYSTORE_KEYS_HANDLER_H_
diff --git a/components/sync/protocol/sync_protocol_error.h b/components/sync/protocol/sync_protocol_error.h index 6f4acf0..08019aa1 100644 --- a/components/sync/protocol/sync_protocol_error.h +++ b/components/sync/protocol/sync_protocol_error.h
@@ -46,9 +46,6 @@ UNKNOWN_ERROR }; -// A Java counterpart will be generated for this enum. -// GENERATED_JAVA_ENUM_PACKAGE: org.chromium.components.sync -// GENERATED_JAVA_CLASS_NAME_OVERRIDE: ProtocolErrorClientAction enum ClientAction { // Upgrade the client to latest version. UPGRADE_CLIENT, @@ -82,5 +79,7 @@ const char* GetSyncErrorTypeString(SyncProtocolErrorType type); const char* GetClientActionString(ClientAction action); + } // namespace syncer + #endif // COMPONENTS_SYNC_PROTOCOL_SYNC_PROTOCOL_ERROR_H_
diff --git a/components/sync/syncable/nigori_handler.h b/components/sync/syncable/nigori_handler.h index 6baa0cca..e50ecf5 100644 --- a/components/sync/syncable/nigori_handler.h +++ b/components/sync/syncable/nigori_handler.h
@@ -9,13 +9,6 @@ #include "components/sync/base/model_type.h" -namespace google { -namespace protobuf { -template <typename T> -class RepeatedPtrField; -} -} - namespace sync_pb { class NigoriSpecifics; } @@ -46,16 +39,6 @@ sync_pb::NigoriSpecifics* nigori, syncable::BaseTransaction* const trans) const = 0; - // Whether a keystore key needs to be requested from the sync server. - virtual bool NeedKeystoreKey( - syncable::BaseTransaction* const trans) const = 0; - - // Set the keystore keys the server returned for this account. - // Returns true on success, false otherwise. - virtual bool SetKeystoreKeys( - const google::protobuf::RepeatedPtrField<std::string>& keys, - syncable::BaseTransaction* const trans) = 0; - // Returns the set of currently encrypted types. virtual ModelTypeSet GetEncryptedTypes( syncable::BaseTransaction* const trans) const = 0;
diff --git a/components/sync/syncable/test_user_share.cc b/components/sync/syncable/test_user_share.cc index 27cfcfc..48ac2a98a 100644 --- a/components/sync/syncable/test_user_share.cc +++ b/components/sync/syncable/test_user_share.cc
@@ -66,6 +66,10 @@ return dir_maker_->encryption_handler(); } +KeystoreKeysHandler* TestUserShare::keystore_keys_handler() { + return dir_maker_->keystore_keys_handler(); +} + syncable::TestTransactionObserver* TestUserShare::transaction_observer() { return dir_maker_->transaction_observer(); }
diff --git a/components/sync/syncable/test_user_share.h b/components/sync/syncable/test_user_share.h index 4c88ce0b..9548205 100644 --- a/components/sync/syncable/test_user_share.h +++ b/components/sync/syncable/test_user_share.h
@@ -15,6 +15,7 @@ namespace syncer { +class KeystoreKeysHandler; class SyncEncryptionHandler; class TestDirectorySetterUpper; @@ -71,6 +72,13 @@ // methods normally handled via the SyncEngine. SyncEncryptionHandler* encryption_handler(); + // KeystoreKeysHandler is required for construction of ModelTypeRegistry in + // several unittests. Currently owned by |dir_maker_|. + // TODO(crbug.com/922900): the ownership of KeystoreKeysHandler should be + // moved outside of TestDirectorySetterUpper, since we need to support USS + // implementation of Nigori. + KeystoreKeysHandler* keystore_keys_handler(); + // Returns the directory's transaction observer. This transaction observer // has methods which can be helpful when writing test assertions. syncable::TestTransactionObserver* transaction_observer();
diff --git a/components/sync/test/engine/test_directory_setter_upper.h b/components/sync/test/engine/test_directory_setter_upper.h index f8915d0..541737d 100644 --- a/components/sync/test/engine/test_directory_setter_upper.h +++ b/components/sync/test/engine/test_directory_setter_upper.h
@@ -68,6 +68,8 @@ SyncEncryptionHandler* encryption_handler() { return &encryption_handler_; } + KeystoreKeysHandler* keystore_keys_handler() { return &encryption_handler_; } + syncable::TestTransactionObserver* transaction_observer() { return test_transaction_observer_.get(); }
diff --git a/components/sync/test/fake_sync_encryption_handler.cc b/components/sync/test/fake_sync_encryption_handler.cc index c488532..2169f96 100644 --- a/components/sync/test/fake_sync_encryption_handler.cc +++ b/components/sync/test/fake_sync_encryption_handler.cc
@@ -63,14 +63,12 @@ encrypt_everything_, nigori); } -bool FakeSyncEncryptionHandler::NeedKeystoreKey( - syncable::BaseTransaction* const trans) const { +bool FakeSyncEncryptionHandler::NeedKeystoreKey() const { return keystore_key_.empty(); } bool FakeSyncEncryptionHandler::SetKeystoreKeys( - const google::protobuf::RepeatedPtrField<google::protobuf::string>& keys, - syncable::BaseTransaction* const trans) { + const google::protobuf::RepeatedPtrField<std::string>& keys) { if (keys.size() == 0) return false; std::string new_key = keys.Get(keys.size() - 1);
diff --git a/components/sync/test/fake_sync_encryption_handler.h b/components/sync/test/fake_sync_encryption_handler.h index 0425ad21..2141139 100644 --- a/components/sync/test/fake_sync_encryption_handler.h +++ b/components/sync/test/fake_sync_encryption_handler.h
@@ -12,6 +12,7 @@ #include "components/sync/base/cryptographer.h" #include "components/sync/base/fake_encryptor.h" #include "components/sync/engine/sync_encryption_handler.h" +#include "components/sync/nigori/keystore_keys_handler.h" #include "components/sync/syncable/nigori_handler.h" namespace syncer { @@ -22,7 +23,8 @@ // (setting pending keys, installing keys). // Note: NOT thread safe. If threads attempt to check encryption state // while another thread is modifying it, races can occur. -class FakeSyncEncryptionHandler : public SyncEncryptionHandler, +class FakeSyncEncryptionHandler : public KeystoreKeysHandler, + public SyncEncryptionHandler, public syncable::NigoriHandler { public: FakeSyncEncryptionHandler(); @@ -45,13 +47,14 @@ void UpdateNigoriFromEncryptedTypes( sync_pb::NigoriSpecifics* nigori, syncable::BaseTransaction* const trans) const override; - bool NeedKeystoreKey(syncable::BaseTransaction* const trans) const override; - bool SetKeystoreKeys( - const google::protobuf::RepeatedPtrField<google::protobuf::string>& keys, - syncable::BaseTransaction* const trans) override; ModelTypeSet GetEncryptedTypes( syncable::BaseTransaction* const trans) const override; + // KeystoreKeysHandler implementation. + bool NeedKeystoreKey() const override; + bool SetKeystoreKeys( + const google::protobuf::RepeatedPtrField<std::string>& keys) override; + Cryptographer* cryptographer() { return &cryptographer_; } private:
diff --git a/components/test/data/js_dialogs/render_tests/VrBrowserJavaScriptModalDialogTest.js_modal_view_vr_confirm_canceled_browser_ui.Pixel_XL-25.png.sha1 b/components/test/data/js_dialogs/render_tests/VrBrowserJavaScriptModalDialogTest.js_modal_view_vr_confirm_canceled_browser_ui.Pixel_XL-25.png.sha1 index aa1c82b..04c9fac 100644 --- a/components/test/data/js_dialogs/render_tests/VrBrowserJavaScriptModalDialogTest.js_modal_view_vr_confirm_canceled_browser_ui.Pixel_XL-25.png.sha1 +++ b/components/test/data/js_dialogs/render_tests/VrBrowserJavaScriptModalDialogTest.js_modal_view_vr_confirm_canceled_browser_ui.Pixel_XL-25.png.sha1
@@ -1 +1 @@ -af38ae743e7e21139613f52a1f2dce4aa1cba749 \ No newline at end of file +9cc3d8580fa561c3675aa4d09f8a26f4765ccdda \ No newline at end of file
diff --git a/components/test/data/js_dialogs/render_tests/VrBrowserJavaScriptModalDialogTest.js_modal_view_vr_confirm_canceled_browser_ui.Pixel_XL-26.png.sha1 b/components/test/data/js_dialogs/render_tests/VrBrowserJavaScriptModalDialogTest.js_modal_view_vr_confirm_canceled_browser_ui.Pixel_XL-26.png.sha1 index 2fa505f..1060e21 100644 --- a/components/test/data/js_dialogs/render_tests/VrBrowserJavaScriptModalDialogTest.js_modal_view_vr_confirm_canceled_browser_ui.Pixel_XL-26.png.sha1 +++ b/components/test/data/js_dialogs/render_tests/VrBrowserJavaScriptModalDialogTest.js_modal_view_vr_confirm_canceled_browser_ui.Pixel_XL-26.png.sha1
@@ -1 +1 @@ -3c68aa21a347e9bb1a8332424322f46d987b71ba \ No newline at end of file +0b911edc9296dc2c3e99c579fc0395d34401df1e \ No newline at end of file
diff --git a/components/test/data/js_dialogs/render_tests/VrBrowserJavaScriptModalDialogTest.js_modal_view_vr_prompt_submitted_browser_ui.Pixel_XL-25.png.sha1 b/components/test/data/js_dialogs/render_tests/VrBrowserJavaScriptModalDialogTest.js_modal_view_vr_prompt_submitted_browser_ui.Pixel_XL-25.png.sha1 index 0dd4161..b058781a 100644 --- a/components/test/data/js_dialogs/render_tests/VrBrowserJavaScriptModalDialogTest.js_modal_view_vr_prompt_submitted_browser_ui.Pixel_XL-25.png.sha1 +++ b/components/test/data/js_dialogs/render_tests/VrBrowserJavaScriptModalDialogTest.js_modal_view_vr_prompt_submitted_browser_ui.Pixel_XL-25.png.sha1
@@ -1 +1 @@ -7b79e54929fcda87cf837a98a4412c36436a5aba \ No newline at end of file +dd8a946ea7f093ce06ecd4083067b0b039b6c30b \ No newline at end of file
diff --git a/components/test/data/js_dialogs/render_tests/VrBrowserJavaScriptModalDialogTest.js_modal_view_vr_prompt_submitted_browser_ui.Pixel_XL-26.png.sha1 b/components/test/data/js_dialogs/render_tests/VrBrowserJavaScriptModalDialogTest.js_modal_view_vr_prompt_submitted_browser_ui.Pixel_XL-26.png.sha1 index 11dbcf7..7445958 100644 --- a/components/test/data/js_dialogs/render_tests/VrBrowserJavaScriptModalDialogTest.js_modal_view_vr_prompt_submitted_browser_ui.Pixel_XL-26.png.sha1 +++ b/components/test/data/js_dialogs/render_tests/VrBrowserJavaScriptModalDialogTest.js_modal_view_vr_prompt_submitted_browser_ui.Pixel_XL-26.png.sha1
@@ -1 +1 @@ -966aa204de3daadc631afc94ae568270272f5c10 \ No newline at end of file +4026cd747141df5b468134b22ce004105f6dfc91 \ No newline at end of file
diff --git a/components/test/data/permission_dialogs/render_tests/VrBrowserDialogTest.camera_permission_prompt_granted_browser_ui.Pixel_XL-25.png.sha1 b/components/test/data/permission_dialogs/render_tests/VrBrowserDialogTest.camera_permission_prompt_granted_browser_ui.Pixel_XL-25.png.sha1 index 3db12b4..8f17a75 100644 --- a/components/test/data/permission_dialogs/render_tests/VrBrowserDialogTest.camera_permission_prompt_granted_browser_ui.Pixel_XL-25.png.sha1 +++ b/components/test/data/permission_dialogs/render_tests/VrBrowserDialogTest.camera_permission_prompt_granted_browser_ui.Pixel_XL-25.png.sha1
@@ -1 +1 @@ -367dfed4304bb011096de92e724240edf42be8a3 \ No newline at end of file +18fa881952df279742ceb8da0118b7ada0c96324 \ No newline at end of file
diff --git a/components/test/data/permission_dialogs/render_tests/VrBrowserDialogTest.camera_permission_prompt_granted_browser_ui.Pixel_XL-26.png.sha1 b/components/test/data/permission_dialogs/render_tests/VrBrowserDialogTest.camera_permission_prompt_granted_browser_ui.Pixel_XL-26.png.sha1 index 76e3cc3..0259458 100644 --- a/components/test/data/permission_dialogs/render_tests/VrBrowserDialogTest.camera_permission_prompt_granted_browser_ui.Pixel_XL-26.png.sha1 +++ b/components/test/data/permission_dialogs/render_tests/VrBrowserDialogTest.camera_permission_prompt_granted_browser_ui.Pixel_XL-26.png.sha1
@@ -1 +1 @@ -c2d1cdc32201243e402e0c86b98e9aa235fd79ea \ No newline at end of file +5cee26131e070f02aaff225b104977a020322653 \ No newline at end of file
diff --git a/components/test/data/permission_dialogs/render_tests/VrBrowserDialogTest.location_permission_prompt_granted_browser_ui.Pixel_XL-25.png.sha1 b/components/test/data/permission_dialogs/render_tests/VrBrowserDialogTest.location_permission_prompt_granted_browser_ui.Pixel_XL-25.png.sha1 index f1632ae..653d5976 100644 --- a/components/test/data/permission_dialogs/render_tests/VrBrowserDialogTest.location_permission_prompt_granted_browser_ui.Pixel_XL-25.png.sha1 +++ b/components/test/data/permission_dialogs/render_tests/VrBrowserDialogTest.location_permission_prompt_granted_browser_ui.Pixel_XL-25.png.sha1
@@ -1 +1 @@ -66c81c1265debb24db6d6b5d2709d520d7438a51 \ No newline at end of file +3a12be310ede417b1299939cf4845fa901f4f502 \ No newline at end of file
diff --git a/components/test/data/permission_dialogs/render_tests/VrBrowserDialogTest.location_permission_prompt_granted_browser_ui.Pixel_XL-26.png.sha1 b/components/test/data/permission_dialogs/render_tests/VrBrowserDialogTest.location_permission_prompt_granted_browser_ui.Pixel_XL-26.png.sha1 index 27a4c27..a280c6a13 100644 --- a/components/test/data/permission_dialogs/render_tests/VrBrowserDialogTest.location_permission_prompt_granted_browser_ui.Pixel_XL-26.png.sha1 +++ b/components/test/data/permission_dialogs/render_tests/VrBrowserDialogTest.location_permission_prompt_granted_browser_ui.Pixel_XL-26.png.sha1
@@ -1 +1 @@ -dd6ce084debbbdf1c8db4c6c8ad63da4444796fc \ No newline at end of file +8c9a6ea3a14048c0fa817ab3855a2b33816c85f3 \ No newline at end of file
diff --git a/components/test/data/permission_dialogs/render_tests/VrBrowserDialogTest.microphone_permission_indicator_hover_browser_ui.Pixel_XL-25.png.sha1 b/components/test/data/permission_dialogs/render_tests/VrBrowserDialogTest.microphone_permission_indicator_hover_browser_ui.Pixel_XL-25.png.sha1 index 76a0f615..5928fe3 100644 --- a/components/test/data/permission_dialogs/render_tests/VrBrowserDialogTest.microphone_permission_indicator_hover_browser_ui.Pixel_XL-25.png.sha1 +++ b/components/test/data/permission_dialogs/render_tests/VrBrowserDialogTest.microphone_permission_indicator_hover_browser_ui.Pixel_XL-25.png.sha1
@@ -1 +1 @@ -dbc9621fc30f416dc344abe04d0f9f9c3dd65ee9 \ No newline at end of file +7406d3c7dcea55deca40b0d83821ad94702c28f3 \ No newline at end of file
diff --git a/components/test/data/permission_dialogs/render_tests/VrBrowserDialogTest.microphone_permission_indicator_hover_browser_ui.Pixel_XL-26.png.sha1 b/components/test/data/permission_dialogs/render_tests/VrBrowserDialogTest.microphone_permission_indicator_hover_browser_ui.Pixel_XL-26.png.sha1 index 34ae9f7..6f166fe1 100644 --- a/components/test/data/permission_dialogs/render_tests/VrBrowserDialogTest.microphone_permission_indicator_hover_browser_ui.Pixel_XL-26.png.sha1 +++ b/components/test/data/permission_dialogs/render_tests/VrBrowserDialogTest.microphone_permission_indicator_hover_browser_ui.Pixel_XL-26.png.sha1
@@ -1 +1 @@ -6c617ea3f2f7ba175533ed0f16780c06b9851cdf \ No newline at end of file +1fade4df8def45e4224ed30029c007e813293dbb \ No newline at end of file
diff --git a/components/test/data/permission_dialogs/render_tests/VrBrowserDialogTest.microphone_permission_indicator_hover_incognito_browser_ui.Pixel_XL-25.png.sha1 b/components/test/data/permission_dialogs/render_tests/VrBrowserDialogTest.microphone_permission_indicator_hover_incognito_browser_ui.Pixel_XL-25.png.sha1 index b19f1e75..adf6d4c 100644 --- a/components/test/data/permission_dialogs/render_tests/VrBrowserDialogTest.microphone_permission_indicator_hover_incognito_browser_ui.Pixel_XL-25.png.sha1 +++ b/components/test/data/permission_dialogs/render_tests/VrBrowserDialogTest.microphone_permission_indicator_hover_incognito_browser_ui.Pixel_XL-25.png.sha1
@@ -1 +1 @@ -2dcb34f6ca7484b97ec7d2eee49f22c796d73bea \ No newline at end of file +6fbc2c60fe40d93d49151b5c359304316390b8a1 \ No newline at end of file
diff --git a/components/test/data/permission_dialogs/render_tests/VrBrowserDialogTest.microphone_permission_indicator_hover_incognito_browser_ui.Pixel_XL-26.png.sha1 b/components/test/data/permission_dialogs/render_tests/VrBrowserDialogTest.microphone_permission_indicator_hover_incognito_browser_ui.Pixel_XL-26.png.sha1 index 5a459d6..a396a7ba 100644 --- a/components/test/data/permission_dialogs/render_tests/VrBrowserDialogTest.microphone_permission_indicator_hover_incognito_browser_ui.Pixel_XL-26.png.sha1 +++ b/components/test/data/permission_dialogs/render_tests/VrBrowserDialogTest.microphone_permission_indicator_hover_incognito_browser_ui.Pixel_XL-26.png.sha1
@@ -1 +1 @@ -f591fc845f1d2938fee3bea1a545847180ce20d4 \ No newline at end of file +3dadae5d956ba98b97df52a4fd1324f955fe430b \ No newline at end of file
diff --git a/components/test/data/permission_dialogs/render_tests/VrBrowserDialogTest.microphone_permission_indicator_hover_reposition_browser_ui.Pixel_XL-25.png.sha1 b/components/test/data/permission_dialogs/render_tests/VrBrowserDialogTest.microphone_permission_indicator_hover_reposition_browser_ui.Pixel_XL-25.png.sha1 index 2d75fedf..36a29d7 100644 --- a/components/test/data/permission_dialogs/render_tests/VrBrowserDialogTest.microphone_permission_indicator_hover_reposition_browser_ui.Pixel_XL-25.png.sha1 +++ b/components/test/data/permission_dialogs/render_tests/VrBrowserDialogTest.microphone_permission_indicator_hover_reposition_browser_ui.Pixel_XL-25.png.sha1
@@ -1 +1 @@ -34a182606c337a192e2759931b5e30c7deff69b9 \ No newline at end of file +5ee3ce1d11c3aeebc3e19ce5c55eb0035964fdda \ No newline at end of file
diff --git a/components/test/data/permission_dialogs/render_tests/VrBrowserDialogTest.microphone_permission_indicator_hover_reposition_browser_ui.Pixel_XL-26.png.sha1 b/components/test/data/permission_dialogs/render_tests/VrBrowserDialogTest.microphone_permission_indicator_hover_reposition_browser_ui.Pixel_XL-26.png.sha1 index cbb79976..b9ed6ab7 100644 --- a/components/test/data/permission_dialogs/render_tests/VrBrowserDialogTest.microphone_permission_indicator_hover_reposition_browser_ui.Pixel_XL-26.png.sha1 +++ b/components/test/data/permission_dialogs/render_tests/VrBrowserDialogTest.microphone_permission_indicator_hover_reposition_browser_ui.Pixel_XL-26.png.sha1
@@ -1 +1 @@ -071a33584ff15e29d0fbf02531393bae05c0bfd8 \ No newline at end of file +03cc1018df9dd3cfb7ffdd311a1c770545404ffb \ No newline at end of file
diff --git a/components/test/data/permission_dialogs/render_tests/VrBrowserDialogTest.microphone_permission_prompt_granted_browser_ui.Pixel_XL-25.png.sha1 b/components/test/data/permission_dialogs/render_tests/VrBrowserDialogTest.microphone_permission_prompt_granted_browser_ui.Pixel_XL-25.png.sha1 index 858e0c36..65e8536 100644 --- a/components/test/data/permission_dialogs/render_tests/VrBrowserDialogTest.microphone_permission_prompt_granted_browser_ui.Pixel_XL-25.png.sha1 +++ b/components/test/data/permission_dialogs/render_tests/VrBrowserDialogTest.microphone_permission_prompt_granted_browser_ui.Pixel_XL-25.png.sha1
@@ -1 +1 @@ -2e93af1c9e7490c48d84ed7d1d140d3fa9cb5aeb \ No newline at end of file +8a5c6c683c8bb8791c1a6be4d4e5069d4dc0702f \ No newline at end of file
diff --git a/components/test/data/permission_dialogs/render_tests/VrBrowserDialogTest.microphone_permission_prompt_granted_browser_ui.Pixel_XL-26.png.sha1 b/components/test/data/permission_dialogs/render_tests/VrBrowserDialogTest.microphone_permission_prompt_granted_browser_ui.Pixel_XL-26.png.sha1 index 83409a3..b7a432a 100644 --- a/components/test/data/permission_dialogs/render_tests/VrBrowserDialogTest.microphone_permission_prompt_granted_browser_ui.Pixel_XL-26.png.sha1 +++ b/components/test/data/permission_dialogs/render_tests/VrBrowserDialogTest.microphone_permission_prompt_granted_browser_ui.Pixel_XL-26.png.sha1
@@ -1 +1 @@ -f919345a1d8da1dc58098a7c84ac8c0a8ed7aff6 \ No newline at end of file +c86c9bbd09b1819cd8386f57b01d211cf8adf261 \ No newline at end of file
diff --git a/components/test/data/permission_dialogs/render_tests/VrBrowserDialogTest.microphone_permission_prompt_incognito_granted_browser_ui.Pixel_XL-25.png.sha1 b/components/test/data/permission_dialogs/render_tests/VrBrowserDialogTest.microphone_permission_prompt_incognito_granted_browser_ui.Pixel_XL-25.png.sha1 index a38215e..c1bcc44 100644 --- a/components/test/data/permission_dialogs/render_tests/VrBrowserDialogTest.microphone_permission_prompt_incognito_granted_browser_ui.Pixel_XL-25.png.sha1 +++ b/components/test/data/permission_dialogs/render_tests/VrBrowserDialogTest.microphone_permission_prompt_incognito_granted_browser_ui.Pixel_XL-25.png.sha1
@@ -1 +1 @@ -e218e0bd67e66a3cdf4563fb6b1659e652d1d860 \ No newline at end of file +112e5f59b4d6c7359272b59ff66d101ad140d9a7 \ No newline at end of file
diff --git a/components/test/data/permission_dialogs/render_tests/VrBrowserDialogTest.microphone_permission_prompt_incognito_granted_browser_ui.Pixel_XL-26.png.sha1 b/components/test/data/permission_dialogs/render_tests/VrBrowserDialogTest.microphone_permission_prompt_incognito_granted_browser_ui.Pixel_XL-26.png.sha1 index 699c331..ba71d5b 100644 --- a/components/test/data/permission_dialogs/render_tests/VrBrowserDialogTest.microphone_permission_prompt_incognito_granted_browser_ui.Pixel_XL-26.png.sha1 +++ b/components/test/data/permission_dialogs/render_tests/VrBrowserDialogTest.microphone_permission_prompt_incognito_granted_browser_ui.Pixel_XL-26.png.sha1
@@ -1 +1 @@ -7dcd06a95bd9c493cb39b66cc64c5b24626118af \ No newline at end of file +5cfcb7987cad985baf31a71138e455e839de3869 \ No newline at end of file
diff --git a/components/test/data/permission_dialogs/render_tests/VrBrowserDialogTest.microphone_permission_prompt_incognito_visible_browser_ui.Pixel_XL-25.png.sha1 b/components/test/data/permission_dialogs/render_tests/VrBrowserDialogTest.microphone_permission_prompt_incognito_visible_browser_ui.Pixel_XL-25.png.sha1 index 65c7d0f..b1127d8 100644 --- a/components/test/data/permission_dialogs/render_tests/VrBrowserDialogTest.microphone_permission_prompt_incognito_visible_browser_ui.Pixel_XL-25.png.sha1 +++ b/components/test/data/permission_dialogs/render_tests/VrBrowserDialogTest.microphone_permission_prompt_incognito_visible_browser_ui.Pixel_XL-25.png.sha1
@@ -1 +1 @@ -a8b31419a73aff40ad4890769d83c26fdd4721df \ No newline at end of file +1d39625008d14a1b6205b8163e9966b359863be6 \ No newline at end of file
diff --git a/components/test/data/permission_dialogs/render_tests/VrBrowserDialogTest.microphone_permission_prompt_incognito_visible_browser_ui.Pixel_XL-26.png.sha1 b/components/test/data/permission_dialogs/render_tests/VrBrowserDialogTest.microphone_permission_prompt_incognito_visible_browser_ui.Pixel_XL-26.png.sha1 index 4cbd71b..4ef0b181 100644 --- a/components/test/data/permission_dialogs/render_tests/VrBrowserDialogTest.microphone_permission_prompt_incognito_visible_browser_ui.Pixel_XL-26.png.sha1 +++ b/components/test/data/permission_dialogs/render_tests/VrBrowserDialogTest.microphone_permission_prompt_incognito_visible_browser_ui.Pixel_XL-26.png.sha1
@@ -1 +1 @@ -b307d31479c34ec2dff788260dc05a67138e3aa7 \ No newline at end of file +d4f9cbe2b0d12c55807fdafef90e7c4823563843 \ No newline at end of file
diff --git a/components/test/data/permission_dialogs/render_tests/VrBrowserDialogTest.microphone_permission_prompt_reposition_granted_browser_ui.Pixel_XL-25.png.sha1 b/components/test/data/permission_dialogs/render_tests/VrBrowserDialogTest.microphone_permission_prompt_reposition_granted_browser_ui.Pixel_XL-25.png.sha1 index a6a76bd..ad1098e 100644 --- a/components/test/data/permission_dialogs/render_tests/VrBrowserDialogTest.microphone_permission_prompt_reposition_granted_browser_ui.Pixel_XL-25.png.sha1 +++ b/components/test/data/permission_dialogs/render_tests/VrBrowserDialogTest.microphone_permission_prompt_reposition_granted_browser_ui.Pixel_XL-25.png.sha1
@@ -1 +1 @@ -7feca6b68dbf4f95f6b4bcb6d8b8534b5ed90cd1 \ No newline at end of file +faa1c98ea9055050fe5d688ab2fed05f550dc3c2 \ No newline at end of file
diff --git a/components/test/data/permission_dialogs/render_tests/VrBrowserDialogTest.microphone_permission_prompt_reposition_granted_browser_ui.Pixel_XL-26.png.sha1 b/components/test/data/permission_dialogs/render_tests/VrBrowserDialogTest.microphone_permission_prompt_reposition_granted_browser_ui.Pixel_XL-26.png.sha1 index 3f335396..67f6057 100644 --- a/components/test/data/permission_dialogs/render_tests/VrBrowserDialogTest.microphone_permission_prompt_reposition_granted_browser_ui.Pixel_XL-26.png.sha1 +++ b/components/test/data/permission_dialogs/render_tests/VrBrowserDialogTest.microphone_permission_prompt_reposition_granted_browser_ui.Pixel_XL-26.png.sha1
@@ -1 +1 @@ -47796386fdb68aa7714d29b905b120e32a380971 \ No newline at end of file +3aa11d74dfe97dbc3eb5959da97e1fb39d09e545 \ No newline at end of file
diff --git a/components/test/data/permission_dialogs/render_tests/VrBrowserDialogTest.microphone_permission_prompt_reposition_visible_browser_ui.Pixel_XL-25.png.sha1 b/components/test/data/permission_dialogs/render_tests/VrBrowserDialogTest.microphone_permission_prompt_reposition_visible_browser_ui.Pixel_XL-25.png.sha1 index f081e8f..146dd944 100644 --- a/components/test/data/permission_dialogs/render_tests/VrBrowserDialogTest.microphone_permission_prompt_reposition_visible_browser_ui.Pixel_XL-25.png.sha1 +++ b/components/test/data/permission_dialogs/render_tests/VrBrowserDialogTest.microphone_permission_prompt_reposition_visible_browser_ui.Pixel_XL-25.png.sha1
@@ -1 +1 @@ -a1bb4630aeb33528b31d9329847718efe4ec90bc \ No newline at end of file +dba7354dd9ee806e6d147a11e6ac47c948c4cf4e \ No newline at end of file
diff --git a/components/test/data/permission_dialogs/render_tests/VrBrowserDialogTest.microphone_permission_prompt_reposition_visible_browser_ui.Pixel_XL-26.png.sha1 b/components/test/data/permission_dialogs/render_tests/VrBrowserDialogTest.microphone_permission_prompt_reposition_visible_browser_ui.Pixel_XL-26.png.sha1 index c59ce33..cde34b2 100644 --- a/components/test/data/permission_dialogs/render_tests/VrBrowserDialogTest.microphone_permission_prompt_reposition_visible_browser_ui.Pixel_XL-26.png.sha1 +++ b/components/test/data/permission_dialogs/render_tests/VrBrowserDialogTest.microphone_permission_prompt_reposition_visible_browser_ui.Pixel_XL-26.png.sha1
@@ -1 +1 @@ -97e6022aff289eae9b3435ff19aa8a311b94df6d \ No newline at end of file +80d577d491ec4ff26236829dc864ec8d5e9dac33 \ No newline at end of file
diff --git a/components/test/data/vr_browser_ui/render_tests/VrBrowserNativeUiTest.back_button_hover_browser_ui.Pixel_XL-25.png.sha1 b/components/test/data/vr_browser_ui/render_tests/VrBrowserNativeUiTest.back_button_hover_browser_ui.Pixel_XL-25.png.sha1 index fa6b5f01..9ecf994a 100644 --- a/components/test/data/vr_browser_ui/render_tests/VrBrowserNativeUiTest.back_button_hover_browser_ui.Pixel_XL-25.png.sha1 +++ b/components/test/data/vr_browser_ui/render_tests/VrBrowserNativeUiTest.back_button_hover_browser_ui.Pixel_XL-25.png.sha1
@@ -1 +1 @@ -86dffd2e44852778071f5b844a452d8db628a317 \ No newline at end of file +a0f783114dd827e4dff21570465dbebf40130cdd \ No newline at end of file
diff --git a/components/test/data/vr_browser_ui/render_tests/VrBrowserNativeUiTest.back_button_hover_browser_ui.Pixel_XL-26.png.sha1 b/components/test/data/vr_browser_ui/render_tests/VrBrowserNativeUiTest.back_button_hover_browser_ui.Pixel_XL-26.png.sha1 index 358d3f3..64a22cca 100644 --- a/components/test/data/vr_browser_ui/render_tests/VrBrowserNativeUiTest.back_button_hover_browser_ui.Pixel_XL-26.png.sha1 +++ b/components/test/data/vr_browser_ui/render_tests/VrBrowserNativeUiTest.back_button_hover_browser_ui.Pixel_XL-26.png.sha1
@@ -1 +1 @@ -59fe98f7c6b55617a474fe08ea5de8e6e7229831 \ No newline at end of file +36003268d52fba3e15a5792c0961a4a9372b299c \ No newline at end of file
diff --git a/components/test/data/vr_browser_ui/render_tests/VrBrowserNativeUiTest.back_button_hover_incognito_browser_ui.Pixel_XL-25.png.sha1 b/components/test/data/vr_browser_ui/render_tests/VrBrowserNativeUiTest.back_button_hover_incognito_browser_ui.Pixel_XL-25.png.sha1 index 4ccba0e..dc6f211 100644 --- a/components/test/data/vr_browser_ui/render_tests/VrBrowserNativeUiTest.back_button_hover_incognito_browser_ui.Pixel_XL-25.png.sha1 +++ b/components/test/data/vr_browser_ui/render_tests/VrBrowserNativeUiTest.back_button_hover_incognito_browser_ui.Pixel_XL-25.png.sha1
@@ -1 +1 @@ -b55a8a4d681a6da30c3713c2b153854513dfb387 \ No newline at end of file +3c6a64da90afab932e83a680c901383e193ea88f \ No newline at end of file
diff --git a/components/test/data/vr_browser_ui/render_tests/VrBrowserNativeUiTest.back_button_hover_incognito_browser_ui.Pixel_XL-26.png.sha1 b/components/test/data/vr_browser_ui/render_tests/VrBrowserNativeUiTest.back_button_hover_incognito_browser_ui.Pixel_XL-26.png.sha1 index 0ac545bb..b8b4516b 100644 --- a/components/test/data/vr_browser_ui/render_tests/VrBrowserNativeUiTest.back_button_hover_incognito_browser_ui.Pixel_XL-26.png.sha1 +++ b/components/test/data/vr_browser_ui/render_tests/VrBrowserNativeUiTest.back_button_hover_incognito_browser_ui.Pixel_XL-26.png.sha1
@@ -1 +1 @@ -0fdb0b329cf6815c7ca17c721469a38af2d6a7ba \ No newline at end of file +77345592e30356dc3733eee9227654ff33c1020a \ No newline at end of file
diff --git a/components/test/data/vr_browser_ui/render_tests/VrBrowserNativeUiTest.data_url_emphasis_browser_ui.Pixel_XL-25.png.sha1 b/components/test/data/vr_browser_ui/render_tests/VrBrowserNativeUiTest.data_url_emphasis_browser_ui.Pixel_XL-25.png.sha1 index 142505da..58cc0f672d 100644 --- a/components/test/data/vr_browser_ui/render_tests/VrBrowserNativeUiTest.data_url_emphasis_browser_ui.Pixel_XL-25.png.sha1 +++ b/components/test/data/vr_browser_ui/render_tests/VrBrowserNativeUiTest.data_url_emphasis_browser_ui.Pixel_XL-25.png.sha1
@@ -1 +1 @@ -bad97edc1db20f128d52be60f0e98ef727a00d55 \ No newline at end of file +ba89ca2c5e6c394b6cb73d9616b5daefb8b2e937 \ No newline at end of file
diff --git a/components/test/data/vr_browser_ui/render_tests/VrBrowserNativeUiTest.data_url_emphasis_browser_ui.Pixel_XL-26.png.sha1 b/components/test/data/vr_browser_ui/render_tests/VrBrowserNativeUiTest.data_url_emphasis_browser_ui.Pixel_XL-26.png.sha1 index 3196165..99c15c0e 100644 --- a/components/test/data/vr_browser_ui/render_tests/VrBrowserNativeUiTest.data_url_emphasis_browser_ui.Pixel_XL-26.png.sha1 +++ b/components/test/data/vr_browser_ui/render_tests/VrBrowserNativeUiTest.data_url_emphasis_browser_ui.Pixel_XL-26.png.sha1
@@ -1 +1 @@ -c46c3e14c1f413809ace5fa5ff475611fe329889 \ No newline at end of file +9eb400738b714176e528adcdd436508f6a4c306f \ No newline at end of file
diff --git a/components/test/data/vr_browser_ui/render_tests/VrBrowserNativeUiTest.file_url_emphasis_browser_ui.Pixel_XL-25.png.sha1 b/components/test/data/vr_browser_ui/render_tests/VrBrowserNativeUiTest.file_url_emphasis_browser_ui.Pixel_XL-25.png.sha1 index 7c7ec2ee..7cd1455 100644 --- a/components/test/data/vr_browser_ui/render_tests/VrBrowserNativeUiTest.file_url_emphasis_browser_ui.Pixel_XL-25.png.sha1 +++ b/components/test/data/vr_browser_ui/render_tests/VrBrowserNativeUiTest.file_url_emphasis_browser_ui.Pixel_XL-25.png.sha1
@@ -1 +1 @@ -382717b911d568c9fd0d4bcb3f69ef324fd70586 \ No newline at end of file +7873eee4e78d673edd4fdbca83f62f80d09193ae \ No newline at end of file
diff --git a/components/test/data/vr_browser_ui/render_tests/VrBrowserNativeUiTest.file_url_emphasis_browser_ui.Pixel_XL-26.png.sha1 b/components/test/data/vr_browser_ui/render_tests/VrBrowserNativeUiTest.file_url_emphasis_browser_ui.Pixel_XL-26.png.sha1 index 7828f59..4ba92f9 100644 --- a/components/test/data/vr_browser_ui/render_tests/VrBrowserNativeUiTest.file_url_emphasis_browser_ui.Pixel_XL-26.png.sha1 +++ b/components/test/data/vr_browser_ui/render_tests/VrBrowserNativeUiTest.file_url_emphasis_browser_ui.Pixel_XL-26.png.sha1
@@ -1 +1 @@ -2af6b96053796d511de0c4fa7d634fe7ccd11bae \ No newline at end of file +7391578759d235fa6ca052e23026f99b573f488c \ No newline at end of file
diff --git a/components/test/data/vr_browser_ui/render_tests/VrBrowserNativeUiTest.overflow_menu_hover_incognito_browser_ui.Pixel_XL-25.png.sha1 b/components/test/data/vr_browser_ui/render_tests/VrBrowserNativeUiTest.overflow_menu_hover_incognito_browser_ui.Pixel_XL-25.png.sha1 index 7a81803..729df10 100644 --- a/components/test/data/vr_browser_ui/render_tests/VrBrowserNativeUiTest.overflow_menu_hover_incognito_browser_ui.Pixel_XL-25.png.sha1 +++ b/components/test/data/vr_browser_ui/render_tests/VrBrowserNativeUiTest.overflow_menu_hover_incognito_browser_ui.Pixel_XL-25.png.sha1
@@ -1 +1 @@ -15ffa800e16c09d8ad80401e0f1c7742e09b311f \ No newline at end of file +b5ed6c7d200eb6b24beead194314eeeb50f6eab3 \ No newline at end of file
diff --git a/components/test/data/vr_browser_ui/render_tests/VrBrowserNativeUiTest.overflow_menu_hover_incognito_browser_ui.Pixel_XL-26.png.sha1 b/components/test/data/vr_browser_ui/render_tests/VrBrowserNativeUiTest.overflow_menu_hover_incognito_browser_ui.Pixel_XL-26.png.sha1 index 186712b..b1114c6 100644 --- a/components/test/data/vr_browser_ui/render_tests/VrBrowserNativeUiTest.overflow_menu_hover_incognito_browser_ui.Pixel_XL-26.png.sha1 +++ b/components/test/data/vr_browser_ui/render_tests/VrBrowserNativeUiTest.overflow_menu_hover_incognito_browser_ui.Pixel_XL-26.png.sha1
@@ -1 +1 @@ -eb64b104f710059e4dedc3c74b6d8a982ce6040c \ No newline at end of file +2ff663c1551a3369444eb04e42f358fd9643c66c \ No newline at end of file
diff --git a/components/test/data/vr_browser_ui/render_tests/VrBrowserNativeUiTest.reposition_bar_keyboard_open.Pixel_XL-25.png.sha1 b/components/test/data/vr_browser_ui/render_tests/VrBrowserNativeUiTest.reposition_bar_keyboard_open.Pixel_XL-25.png.sha1 index 1d7d7d7d..ae4c4924 100644 --- a/components/test/data/vr_browser_ui/render_tests/VrBrowserNativeUiTest.reposition_bar_keyboard_open.Pixel_XL-25.png.sha1 +++ b/components/test/data/vr_browser_ui/render_tests/VrBrowserNativeUiTest.reposition_bar_keyboard_open.Pixel_XL-25.png.sha1
@@ -1 +1 @@ -6f34c598a6fb92ef2ab443ce734a1b3ba0fe1c51 \ No newline at end of file +abad97aeee04a59d23cf4eee16274ae927817fe9 \ No newline at end of file
diff --git a/components/test/data/vr_browser_ui/render_tests/VrBrowserNativeUiTest.reposition_bar_keyboard_open.Pixel_XL-26.png.sha1 b/components/test/data/vr_browser_ui/render_tests/VrBrowserNativeUiTest.reposition_bar_keyboard_open.Pixel_XL-26.png.sha1 index 21c8bfa..80fc958 100644 --- a/components/test/data/vr_browser_ui/render_tests/VrBrowserNativeUiTest.reposition_bar_keyboard_open.Pixel_XL-26.png.sha1 +++ b/components/test/data/vr_browser_ui/render_tests/VrBrowserNativeUiTest.reposition_bar_keyboard_open.Pixel_XL-26.png.sha1
@@ -1 +1 @@ -dd76a89ce00dbc4115c055527f53770a1e376c8f \ No newline at end of file +2bd1f0bd39f1d35d99979db3289dbf2dfb375685 \ No newline at end of file
diff --git a/components/test/data/vr_browser_ui/render_tests/VrBrowserNativeUiTest.repositioned_overflow_menu.Pixel_XL-25.png.sha1 b/components/test/data/vr_browser_ui/render_tests/VrBrowserNativeUiTest.repositioned_overflow_menu.Pixel_XL-25.png.sha1 index 1b5a654..6ed90228 100644 --- a/components/test/data/vr_browser_ui/render_tests/VrBrowserNativeUiTest.repositioned_overflow_menu.Pixel_XL-25.png.sha1 +++ b/components/test/data/vr_browser_ui/render_tests/VrBrowserNativeUiTest.repositioned_overflow_menu.Pixel_XL-25.png.sha1
@@ -1 +1 @@ -18bad9ffcce1a4e3e13c14f320462a94bcac1899 \ No newline at end of file +69c9176c3446e13cbef1da62a0662d149c9b325a \ No newline at end of file
diff --git a/components/test/data/vr_browser_ui/render_tests/VrBrowserNativeUiTest.repositioned_overflow_menu.Pixel_XL-26.png.sha1 b/components/test/data/vr_browser_ui/render_tests/VrBrowserNativeUiTest.repositioned_overflow_menu.Pixel_XL-26.png.sha1 index f6f9ac5c..52c2a865 100644 --- a/components/test/data/vr_browser_ui/render_tests/VrBrowserNativeUiTest.repositioned_overflow_menu.Pixel_XL-26.png.sha1 +++ b/components/test/data/vr_browser_ui/render_tests/VrBrowserNativeUiTest.repositioned_overflow_menu.Pixel_XL-26.png.sha1
@@ -1 +1 @@ -be049c7b078fe370248cdb9bb068d9fc06fd3424 \ No newline at end of file +76a094c08e36daf87c632f1cef8ed6e66e63e07a \ No newline at end of file
diff --git a/components/test/data/vr_browser_ui/render_tests/VrBrowserNativeUiTest.scroll_resizing.Pixel_XL-25.png.sha1 b/components/test/data/vr_browser_ui/render_tests/VrBrowserNativeUiTest.scroll_resizing.Pixel_XL-25.png.sha1 index ea1e849..8a0f79f 100644 --- a/components/test/data/vr_browser_ui/render_tests/VrBrowserNativeUiTest.scroll_resizing.Pixel_XL-25.png.sha1 +++ b/components/test/data/vr_browser_ui/render_tests/VrBrowserNativeUiTest.scroll_resizing.Pixel_XL-25.png.sha1
@@ -1 +1 @@ -aa113baa3920f9aa940ae339d9dbc15f24a56bd6 \ No newline at end of file +e0902dba15773fcb520336020900b947d726830d \ No newline at end of file
diff --git a/components/test/data/vr_browser_ui/render_tests/VrBrowserNativeUiTest.scroll_resizing.Pixel_XL-26.png.sha1 b/components/test/data/vr_browser_ui/render_tests/VrBrowserNativeUiTest.scroll_resizing.Pixel_XL-26.png.sha1 index b95e1b2..55c14d8 100644 --- a/components/test/data/vr_browser_ui/render_tests/VrBrowserNativeUiTest.scroll_resizing.Pixel_XL-26.png.sha1 +++ b/components/test/data/vr_browser_ui/render_tests/VrBrowserNativeUiTest.scroll_resizing.Pixel_XL-26.png.sha1
@@ -1 +1 @@ -f83e0b6762a234126a98b236fefd74b66e116042 \ No newline at end of file +60d7833dd1eec08f5c01c18133c28a3c59e2ca13 \ No newline at end of file
diff --git a/components/test/data/vr_browser_ui/render_tests/VrBrowserNativeUiTest.security_icon_hover_browser_ui.Pixel_XL-25.png.sha1 b/components/test/data/vr_browser_ui/render_tests/VrBrowserNativeUiTest.security_icon_hover_browser_ui.Pixel_XL-25.png.sha1 index 1999dac..7242d8e 100644 --- a/components/test/data/vr_browser_ui/render_tests/VrBrowserNativeUiTest.security_icon_hover_browser_ui.Pixel_XL-25.png.sha1 +++ b/components/test/data/vr_browser_ui/render_tests/VrBrowserNativeUiTest.security_icon_hover_browser_ui.Pixel_XL-25.png.sha1
@@ -1 +1 @@ -59bc39e48484a5eb08b5aacda78c52aace4bd893 \ No newline at end of file +685031e94180ab087c170ae5f2922533377f7265 \ No newline at end of file
diff --git a/components/test/data/vr_browser_ui/render_tests/VrBrowserNativeUiTest.security_icon_hover_browser_ui.Pixel_XL-26.png.sha1 b/components/test/data/vr_browser_ui/render_tests/VrBrowserNativeUiTest.security_icon_hover_browser_ui.Pixel_XL-26.png.sha1 index a3c2b9f..080afb6 100644 --- a/components/test/data/vr_browser_ui/render_tests/VrBrowserNativeUiTest.security_icon_hover_browser_ui.Pixel_XL-26.png.sha1 +++ b/components/test/data/vr_browser_ui/render_tests/VrBrowserNativeUiTest.security_icon_hover_browser_ui.Pixel_XL-26.png.sha1
@@ -1 +1 @@ -534dc63b2768dba6b3383adf2df753865077eab5 \ No newline at end of file +544559cc4e4f36e83956502e542ad76a5457734a \ No newline at end of file
diff --git a/components/test/data/vr_browser_ui/render_tests/VrBrowserNativeUiTest.security_icon_hover_incognito_browser_ui.Pixel_XL-25.png.sha1 b/components/test/data/vr_browser_ui/render_tests/VrBrowserNativeUiTest.security_icon_hover_incognito_browser_ui.Pixel_XL-25.png.sha1 index 793f952..5039e3a 100644 --- a/components/test/data/vr_browser_ui/render_tests/VrBrowserNativeUiTest.security_icon_hover_incognito_browser_ui.Pixel_XL-25.png.sha1 +++ b/components/test/data/vr_browser_ui/render_tests/VrBrowserNativeUiTest.security_icon_hover_incognito_browser_ui.Pixel_XL-25.png.sha1
@@ -1 +1 @@ -d0c7f812d08aae9b2f418e0d746cd8f7fa6f1435 \ No newline at end of file +5e0dd8ee322ba41615930c52becaee4b711e2f68 \ No newline at end of file
diff --git a/components/test/data/vr_browser_ui/render_tests/VrBrowserNativeUiTest.security_icon_hover_incognito_browser_ui.Pixel_XL-26.png.sha1 b/components/test/data/vr_browser_ui/render_tests/VrBrowserNativeUiTest.security_icon_hover_incognito_browser_ui.Pixel_XL-26.png.sha1 index 40a7ada..89561b6b 100644 --- a/components/test/data/vr_browser_ui/render_tests/VrBrowserNativeUiTest.security_icon_hover_incognito_browser_ui.Pixel_XL-26.png.sha1 +++ b/components/test/data/vr_browser_ui/render_tests/VrBrowserNativeUiTest.security_icon_hover_incognito_browser_ui.Pixel_XL-26.png.sha1
@@ -1 +1 @@ -05314129b176b1d7d09c4d046ecb63f7e85328cb \ No newline at end of file +840e6e410270571803149461f48edd17489cb2a6 \ No newline at end of file
diff --git a/components/test/data/vr_browser_ui/render_tests/VrBrowserNativeUiTest.suggestion_clicking_bottom.Pixel_XL-25.png.sha1 b/components/test/data/vr_browser_ui/render_tests/VrBrowserNativeUiTest.suggestion_clicking_bottom.Pixel_XL-25.png.sha1 index 9a8d080..7d037b1 100644 --- a/components/test/data/vr_browser_ui/render_tests/VrBrowserNativeUiTest.suggestion_clicking_bottom.Pixel_XL-25.png.sha1 +++ b/components/test/data/vr_browser_ui/render_tests/VrBrowserNativeUiTest.suggestion_clicking_bottom.Pixel_XL-25.png.sha1
@@ -1 +1 @@ -66f3464c0e885ffa17cc094bd9a55f248e9a6f40 \ No newline at end of file +a8f2df2fd6bdcdcec46507685ffe10949bf9a896 \ No newline at end of file
diff --git a/components/test/data/vr_browser_ui/render_tests/VrBrowserNativeUiTest.suggestion_clicking_bottom.Pixel_XL-26.png.sha1 b/components/test/data/vr_browser_ui/render_tests/VrBrowserNativeUiTest.suggestion_clicking_bottom.Pixel_XL-26.png.sha1 index 9fda43c..4fb87be 100644 --- a/components/test/data/vr_browser_ui/render_tests/VrBrowserNativeUiTest.suggestion_clicking_bottom.Pixel_XL-26.png.sha1 +++ b/components/test/data/vr_browser_ui/render_tests/VrBrowserNativeUiTest.suggestion_clicking_bottom.Pixel_XL-26.png.sha1
@@ -1 +1 @@ -00ad1fb237c5b608c5305034bd8b19a6ab6c3b39 \ No newline at end of file +3c7c6d188174f6b4dd6fb5a0295e9e64c745e119 \ No newline at end of file
diff --git a/components/test/data/vr_browser_ui/render_tests/VrBrowserNativeUiTest.suggestion_clicking_left.Pixel_XL-25.png.sha1 b/components/test/data/vr_browser_ui/render_tests/VrBrowserNativeUiTest.suggestion_clicking_left.Pixel_XL-25.png.sha1 index 4779365..04d9ba5 100644 --- a/components/test/data/vr_browser_ui/render_tests/VrBrowserNativeUiTest.suggestion_clicking_left.Pixel_XL-25.png.sha1 +++ b/components/test/data/vr_browser_ui/render_tests/VrBrowserNativeUiTest.suggestion_clicking_left.Pixel_XL-25.png.sha1
@@ -1 +1 @@ -200aff88733aad23c72b7776c342ddec5a3ba29e \ No newline at end of file +e5a62dc906e8612044ef351e044a778488a11df3 \ No newline at end of file
diff --git a/components/test/data/vr_browser_ui/render_tests/VrBrowserNativeUiTest.suggestion_clicking_left.Pixel_XL-26.png.sha1 b/components/test/data/vr_browser_ui/render_tests/VrBrowserNativeUiTest.suggestion_clicking_left.Pixel_XL-26.png.sha1 index b854b14..ff8aef7 100644 --- a/components/test/data/vr_browser_ui/render_tests/VrBrowserNativeUiTest.suggestion_clicking_left.Pixel_XL-26.png.sha1 +++ b/components/test/data/vr_browser_ui/render_tests/VrBrowserNativeUiTest.suggestion_clicking_left.Pixel_XL-26.png.sha1
@@ -1 +1 @@ -4c4dc76e6922166019129b1abcfb7a0acb9fb164 \ No newline at end of file +dcb2dad069defa7b4a2bde0d9be3d05cb71f71b7 \ No newline at end of file
diff --git a/components/test/data/vr_browser_ui/render_tests/VrBrowserNativeUiTest.suggestion_clicking_right.Pixel_XL-25.png.sha1 b/components/test/data/vr_browser_ui/render_tests/VrBrowserNativeUiTest.suggestion_clicking_right.Pixel_XL-25.png.sha1 index bcd04ce..20faf4a 100644 --- a/components/test/data/vr_browser_ui/render_tests/VrBrowserNativeUiTest.suggestion_clicking_right.Pixel_XL-25.png.sha1 +++ b/components/test/data/vr_browser_ui/render_tests/VrBrowserNativeUiTest.suggestion_clicking_right.Pixel_XL-25.png.sha1
@@ -1 +1 @@ -461168a6069c053be9aea5546145f93696612cba \ No newline at end of file +7606df871cd2ec83d07c1c351729975e8fe39bbc \ No newline at end of file
diff --git a/components/test/data/vr_browser_ui/render_tests/VrBrowserNativeUiTest.suggestion_clicking_right.Pixel_XL-26.png.sha1 b/components/test/data/vr_browser_ui/render_tests/VrBrowserNativeUiTest.suggestion_clicking_right.Pixel_XL-26.png.sha1 index 713f746b..4a41b5e2 100644 --- a/components/test/data/vr_browser_ui/render_tests/VrBrowserNativeUiTest.suggestion_clicking_right.Pixel_XL-26.png.sha1 +++ b/components/test/data/vr_browser_ui/render_tests/VrBrowserNativeUiTest.suggestion_clicking_right.Pixel_XL-26.png.sha1
@@ -1 +1 @@ -cf653d95288c47e9a922e3547b8af20c0f14ee25 \ No newline at end of file +222103fb4cc27e847a9842e4f732a68c81a0e2ef \ No newline at end of file
diff --git a/components/test/data/vr_browser_ui/render_tests/VrBrowserNativeUiTest.suggestion_clicking_top.Pixel_XL-25.png.sha1 b/components/test/data/vr_browser_ui/render_tests/VrBrowserNativeUiTest.suggestion_clicking_top.Pixel_XL-25.png.sha1 index 523e243..c90e177c12 100644 --- a/components/test/data/vr_browser_ui/render_tests/VrBrowserNativeUiTest.suggestion_clicking_top.Pixel_XL-25.png.sha1 +++ b/components/test/data/vr_browser_ui/render_tests/VrBrowserNativeUiTest.suggestion_clicking_top.Pixel_XL-25.png.sha1
@@ -1 +1 @@ -a3a55fb5bac792c5be3e87fa37d2f8e1028202f7 \ No newline at end of file +3644057beb3128ce64691be576a2659fafff7e49 \ No newline at end of file
diff --git a/components/test/data/vr_browser_ui/render_tests/VrBrowserNativeUiTest.suggestion_clicking_top.Pixel_XL-26.png.sha1 b/components/test/data/vr_browser_ui/render_tests/VrBrowserNativeUiTest.suggestion_clicking_top.Pixel_XL-26.png.sha1 index 8640882..42a8919f 100644 --- a/components/test/data/vr_browser_ui/render_tests/VrBrowserNativeUiTest.suggestion_clicking_top.Pixel_XL-26.png.sha1 +++ b/components/test/data/vr_browser_ui/render_tests/VrBrowserNativeUiTest.suggestion_clicking_top.Pixel_XL-26.png.sha1
@@ -1 +1 @@ -aeb9f806ce58b9721787474532008d8877aff506 \ No newline at end of file +105cbd41503275d7f9bb15bccec32806d5ea19bb \ No newline at end of file
diff --git a/components/test/data/vr_browser_ui/render_tests/VrBrowserNativeUiTest.suggestion_hovering_middle.Pixel_XL-25.png.sha1 b/components/test/data/vr_browser_ui/render_tests/VrBrowserNativeUiTest.suggestion_hovering_middle.Pixel_XL-25.png.sha1 index c5507c3..3c3f18f6 100644 --- a/components/test/data/vr_browser_ui/render_tests/VrBrowserNativeUiTest.suggestion_hovering_middle.Pixel_XL-25.png.sha1 +++ b/components/test/data/vr_browser_ui/render_tests/VrBrowserNativeUiTest.suggestion_hovering_middle.Pixel_XL-25.png.sha1
@@ -1 +1 @@ -22a1452e97861e5436c9316ebd4215dfea7d937b \ No newline at end of file +200a1dc7467ef3cc554b01fa4d4553f517bb994c \ No newline at end of file
diff --git a/components/test/data/vr_browser_ui/render_tests/VrBrowserNativeUiTest.suggestion_hovering_middle.Pixel_XL-26.png.sha1 b/components/test/data/vr_browser_ui/render_tests/VrBrowserNativeUiTest.suggestion_hovering_middle.Pixel_XL-26.png.sha1 index 070c8174..b9af91a 100644 --- a/components/test/data/vr_browser_ui/render_tests/VrBrowserNativeUiTest.suggestion_hovering_middle.Pixel_XL-26.png.sha1 +++ b/components/test/data/vr_browser_ui/render_tests/VrBrowserNativeUiTest.suggestion_hovering_middle.Pixel_XL-26.png.sha1
@@ -1 +1 @@ -4ed1ba491463f6d5850966bb67208481fc83bd24 \ No newline at end of file +d0a914ee179e6ee428c0011dcdec6a5aebeeb25a \ No newline at end of file
diff --git a/components/test/data/vr_browser_ui/render_tests/VrBrowserNativeUiTest.suggestion_hovering_top.Pixel_XL-25.png.sha1 b/components/test/data/vr_browser_ui/render_tests/VrBrowserNativeUiTest.suggestion_hovering_top.Pixel_XL-25.png.sha1 index eb78fef..836d3a1 100644 --- a/components/test/data/vr_browser_ui/render_tests/VrBrowserNativeUiTest.suggestion_hovering_top.Pixel_XL-25.png.sha1 +++ b/components/test/data/vr_browser_ui/render_tests/VrBrowserNativeUiTest.suggestion_hovering_top.Pixel_XL-25.png.sha1
@@ -1 +1 @@ -9945ec8cf622180e3aa7a6be754f4013e421747e \ No newline at end of file +ceb77320776fc9253108cf5ca1be64fccdf611d8 \ No newline at end of file
diff --git a/components/test/data/vr_browser_ui/render_tests/VrBrowserNativeUiTest.suggestion_hovering_top.Pixel_XL-26.png.sha1 b/components/test/data/vr_browser_ui/render_tests/VrBrowserNativeUiTest.suggestion_hovering_top.Pixel_XL-26.png.sha1 index 1a9f8cd..dbfc097 100644 --- a/components/test/data/vr_browser_ui/render_tests/VrBrowserNativeUiTest.suggestion_hovering_top.Pixel_XL-26.png.sha1 +++ b/components/test/data/vr_browser_ui/render_tests/VrBrowserNativeUiTest.suggestion_hovering_top.Pixel_XL-26.png.sha1
@@ -1 +1 @@ -6009239091198462e429f1c6842ee2c57290989a \ No newline at end of file +e20d2d0ee7705f772cd7fd6cd9d76287c6059610 \ No newline at end of file
diff --git a/components/test/data/vr_browser_ui/render_tests/VrBrowserNativeUiTest.url_bar_hover_browser_ui.Pixel_XL-25.png.sha1 b/components/test/data/vr_browser_ui/render_tests/VrBrowserNativeUiTest.url_bar_hover_browser_ui.Pixel_XL-25.png.sha1 index 6503ef1..5cad5ae 100644 --- a/components/test/data/vr_browser_ui/render_tests/VrBrowserNativeUiTest.url_bar_hover_browser_ui.Pixel_XL-25.png.sha1 +++ b/components/test/data/vr_browser_ui/render_tests/VrBrowserNativeUiTest.url_bar_hover_browser_ui.Pixel_XL-25.png.sha1
@@ -1 +1 @@ -f4b2d50f663c61ce29998714d6dcb7c9ca41fefb \ No newline at end of file +38cfb432ebe7098d9c418700d1ec058848798365 \ No newline at end of file
diff --git a/components/test/data/vr_browser_ui/render_tests/VrBrowserNativeUiTest.url_bar_hover_browser_ui.Pixel_XL-26.png.sha1 b/components/test/data/vr_browser_ui/render_tests/VrBrowserNativeUiTest.url_bar_hover_browser_ui.Pixel_XL-26.png.sha1 index 9948c4f..2c687d5 100644 --- a/components/test/data/vr_browser_ui/render_tests/VrBrowserNativeUiTest.url_bar_hover_browser_ui.Pixel_XL-26.png.sha1 +++ b/components/test/data/vr_browser_ui/render_tests/VrBrowserNativeUiTest.url_bar_hover_browser_ui.Pixel_XL-26.png.sha1
@@ -1 +1 @@ -54480ef7bc154ee6b85c2c09f2567a9402a639c4 \ No newline at end of file +cd6677657811dfbe5ed13b238455c8fee660b028 \ No newline at end of file
diff --git a/components/test/data/vr_browser_ui/render_tests/VrBrowserNativeUiTest.url_bar_hover_incognito_browser_ui.Pixel_XL-25.png.sha1 b/components/test/data/vr_browser_ui/render_tests/VrBrowserNativeUiTest.url_bar_hover_incognito_browser_ui.Pixel_XL-25.png.sha1 index 93864da6..6b6edabf 100644 --- a/components/test/data/vr_browser_ui/render_tests/VrBrowserNativeUiTest.url_bar_hover_incognito_browser_ui.Pixel_XL-25.png.sha1 +++ b/components/test/data/vr_browser_ui/render_tests/VrBrowserNativeUiTest.url_bar_hover_incognito_browser_ui.Pixel_XL-25.png.sha1
@@ -1 +1 @@ -7f28d8cc402a785c1b8783b827bbc6022abf46f7 \ No newline at end of file +9c7f0bee443c79f81bbb2e41c41809daa1cabafa \ No newline at end of file
diff --git a/components/test/data/vr_browser_ui/render_tests/VrBrowserNativeUiTest.url_bar_hover_incognito_browser_ui.Pixel_XL-26.png.sha1 b/components/test/data/vr_browser_ui/render_tests/VrBrowserNativeUiTest.url_bar_hover_incognito_browser_ui.Pixel_XL-26.png.sha1 index 7833e5d..2eaade1 100644 --- a/components/test/data/vr_browser_ui/render_tests/VrBrowserNativeUiTest.url_bar_hover_incognito_browser_ui.Pixel_XL-26.png.sha1 +++ b/components/test/data/vr_browser_ui/render_tests/VrBrowserNativeUiTest.url_bar_hover_incognito_browser_ui.Pixel_XL-26.png.sha1
@@ -1 +1 @@ -6c8517eafe74a3b7219bfdbaebcc8a427a8277b1 \ No newline at end of file +f8952c9a33641cb20ff1597eb5f716950fea7a1c \ No newline at end of file
diff --git a/components/translate/content/browser/BUILD.gn b/components/translate/content/browser/BUILD.gn index 008b702c..df077d0 100644 --- a/components/translate/content/browser/BUILD.gn +++ b/components/translate/content/browser/BUILD.gn
@@ -19,6 +19,7 @@ deps = [ "//components/language/core/browser", "//components/search_engines:search_engines", + "//components/ukm/content", "//content/public/browser", "//content/public/common", "//net",
diff --git a/components/translate/content/browser/DEPS b/components/translate/content/browser/DEPS index 4619358..697e520 100644 --- a/components/translate/content/browser/DEPS +++ b/components/translate/content/browser/DEPS
@@ -1,4 +1,6 @@ include_rules = [ "+content/public/browser", "+components/search_engines", + "+components/ukm", + "+services/metrics/public/cpp", ]
diff --git a/components/translate/content/browser/content_translate_driver.cc b/components/translate/content/browser/content_translate_driver.cc index cee7663b..d0afc9d 100644 --- a/components/translate/content/browser/content_translate_driver.cc +++ b/components/translate/content/browser/content_translate_driver.cc
@@ -17,6 +17,7 @@ #include "components/translate/core/browser/translate_download_manager.h" #include "components/translate/core/browser/translate_manager.h" #include "components/translate/core/common/translate_util.h" +#include "components/ukm/content/source_url_recorder.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/navigation_controller.h" #include "content/public/browser/navigation_details.h" @@ -28,6 +29,7 @@ #include "content/public/browser/web_contents.h" #include "content/public/common/referrer.h" #include "net/http/http_status_code.h" +#include "services/metrics/public/cpp/ukm_source_id.h" #include "services/network/public/mojom/network_context.mojom.h" #include "url/gurl.h" @@ -168,6 +170,11 @@ return navigation_controller_->GetWebContents()->GetVisibleURL(); } +ukm::SourceId ContentTranslateDriver::GetUkmSourceId() { + return ukm::GetSourceIdForWebContentsDocument( + navigation_controller_->GetWebContents()); +} + bool ContentTranslateDriver::HasCurrentPage() { return (navigation_controller_->GetLastCommittedEntry() != nullptr); }
diff --git a/components/translate/content/browser/content_translate_driver.h b/components/translate/content/browser/content_translate_driver.h index f937d826..55e5170 100644 --- a/components/translate/content/browser/content_translate_driver.h +++ b/components/translate/content/browser/content_translate_driver.h
@@ -16,6 +16,7 @@ #include "components/translate/core/common/translate_errors.h" #include "content/public/browser/web_contents_observer.h" #include "mojo/public/cpp/bindings/binding_set.h" +#include "services/metrics/public/cpp/ukm_source_id.h" #include "services/network/public/mojom/url_loader_factory.mojom.h" namespace content { @@ -98,6 +99,7 @@ const std::string& GetContentsMimeType() override; const GURL& GetLastCommittedURL() override; const GURL& GetVisibleURL() override; + ukm::SourceId GetUkmSourceId() override; bool HasCurrentPage() override; void OpenUrlInNewTab(const GURL& url) override;
diff --git a/components/translate/content/renderer/translate_helper.cc b/components/translate/content/renderer/translate_helper.cc index 8b8a8a6..f5db426 100644 --- a/components/translate/content/renderer/translate_helper.cc +++ b/components/translate/content/renderer/translate_helper.cc
@@ -17,7 +17,6 @@ #include "base/strings/string16.h" #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" -#include "base/threading/thread_task_runner_handle.h" #include "components/translate/core/common/translate_constants.h" #include "components/translate/core/common/translate_metrics.h" #include "components/translate/core/common/translate_util.h" @@ -427,7 +426,7 @@ NotifyBrowserTranslationFailed(TranslateErrors::TRANSLATION_TIMEOUT); return; } - base::ThreadTaskRunnerHandle::Get()->PostDelayedTask( + translate_task_runner_->PostDelayedTask( FROM_HERE, base::BindOnce(&TranslateHelper::TranslatePageImpl, weak_method_factory_.GetWeakPtr(), count),
diff --git a/components/translate/core/browser/BUILD.gn b/components/translate/core/browser/BUILD.gn index 5ee75683..03b0c68 100644 --- a/components/translate/core/browser/BUILD.gn +++ b/components/translate/core/browser/BUILD.gn
@@ -112,6 +112,7 @@ "//components/ukm:test_support", "//components/variations", "//net:test_support", + "//services/metrics/public/cpp:metrics_cpp", "//services/metrics/public/cpp:ukm_builders", "//services/network:test_support", "//services/network/public/cpp:cpp", @@ -137,6 +138,7 @@ "//components/sync_preferences:test_support", "//components/translate/core/browser", "//components/translate/core/common", + "//services/metrics/public/cpp:metrics_cpp", "//testing/gmock", "//testing/gtest", "//third_party/metrics_proto:metrics_proto",
diff --git a/components/translate/core/browser/mock_translate_driver.cc b/components/translate/core/browser/mock_translate_driver.cc index 9b712c4..10e4046 100644 --- a/components/translate/core/browser/mock_translate_driver.cc +++ b/components/translate/core/browser/mock_translate_driver.cc
@@ -4,6 +4,8 @@ #include "components/translate/core/browser/mock_translate_driver.h" +#include <string> + namespace translate { namespace testing { @@ -58,6 +60,10 @@ return GURL::EmptyGURL(); } +ukm::SourceId MockTranslateDriver::GetUkmSourceId() { + return ukm::kInvalidSourceId; +} + bool MockTranslateDriver::HasCurrentPage() { return true; }
diff --git a/components/translate/core/browser/mock_translate_driver.h b/components/translate/core/browser/mock_translate_driver.h index 843906e..63ba9d0e 100644 --- a/components/translate/core/browser/mock_translate_driver.h +++ b/components/translate/core/browser/mock_translate_driver.h
@@ -6,6 +6,7 @@ #define COMPONENTS_TRANSLATE_CORE_BROWSER_MOCK_TRANSLATE_DRIVER_H_ #include <memory> +#include <string> #include "base/macros.h" #include "components/translate/core/browser/language_state.h" @@ -38,6 +39,7 @@ const std::string& GetContentsMimeType() override; const GURL& GetLastCommittedURL() override; const GURL& GetVisibleURL() override; + ukm::SourceId GetUkmSourceId() override; bool HasCurrentPage() override; void OpenUrlInNewTab(const GURL& url) override {}
diff --git a/components/translate/core/browser/mock_translate_infobar_delegate.cc b/components/translate/core/browser/mock_translate_infobar_delegate.cc index 9b67068..16fa1d4 100644 --- a/components/translate/core/browser/mock_translate_infobar_delegate.cc +++ b/components/translate/core/browser/mock_translate_infobar_delegate.cc
@@ -36,6 +36,7 @@ const std::string& target_language) { pref_service_ = std::make_unique<sync_preferences::TestingPrefServiceSyncable>(); + language::LanguagePrefs::RegisterProfilePrefs(pref_service_->registry()); translate::TranslatePrefs::RegisterProfilePrefs(pref_service_->registry()); pref_service_->registry()->RegisterBooleanPref(prefs::kOfferTranslateEnabled, true);
diff --git a/components/translate/core/browser/mock_translate_infobar_delegate.h b/components/translate/core/browser/mock_translate_infobar_delegate.h index 3f736f90..3e8154f 100644 --- a/components/translate/core/browser/mock_translate_infobar_delegate.h +++ b/components/translate/core/browser/mock_translate_infobar_delegate.h
@@ -10,6 +10,7 @@ #include <vector> #include "components/language/core/browser/language_model.h" +#include "components/language/core/browser/language_prefs.h" #include "components/sync_preferences/testing_pref_service_syncable.h" #include "components/translate/core/browser/mock_translate_client.h" #include "components/translate/core/browser/mock_translate_driver.h"
diff --git a/components/translate/core/browser/mock_translate_ranker.h b/components/translate/core/browser/mock_translate_ranker.h index 1bef23d..f7ecb6c 100644 --- a/components/translate/core/browser/mock_translate_ranker.h +++ b/components/translate/core/browser/mock_translate_ranker.h
@@ -10,9 +10,9 @@ #include <vector> #include "components/translate/core/browser/translate_ranker.h" +#include "services/metrics/public/cpp/ukm_source_id.h" #include "testing/gmock/include/gmock/gmock.h" -class GURL; namespace metrics { class TranslateEventProto; @@ -49,11 +49,11 @@ std::vector<metrics::TranslateEventProto>* events) override; MOCK_METHOD3(RecordTranslateEvent, void(int event_type, - const GURL& url, + ukm::SourceId ukm_source_id, metrics::TranslateEventProto* translate_event)); MOCK_METHOD3(ShouldOverrideDecision, bool(int event_type, - const GURL& url, + ukm::SourceId ukm_source_id, metrics::TranslateEventProto* translate_event)); private:
diff --git a/components/translate/core/browser/translate_driver.h b/components/translate/core/browser/translate_driver.h index e58589f..060e13e 100644 --- a/components/translate/core/browser/translate_driver.h +++ b/components/translate/core/browser/translate_driver.h
@@ -6,6 +6,7 @@ #define COMPONENTS_TRANSLATE_CORE_BROWSER_TRANSLATE_DRIVER_H_ #include <string> +#include "services/metrics/public/cpp/ukm_source_id.h" class GURL; @@ -47,6 +48,9 @@ // Returns the visible URL, or an empty GURL if there is no visible URL. virtual const GURL& GetVisibleURL() = 0; + // Returns the Ukm SourceId for the associated WebContents. + virtual ukm::SourceId GetUkmSourceId() = 0; + // Returns whether the driver has access to the current page. virtual bool HasCurrentPage() = 0;
diff --git a/components/translate/core/browser/translate_manager.cc b/components/translate/core/browser/translate_manager.cc index 2e9836d..2b5693b8 100644 --- a/components/translate/core/browser/translate_manager.cc +++ b/components/translate/core/browser/translate_manager.cc
@@ -566,13 +566,13 @@ void TranslateManager::RecordTranslateEvent(int event_type) { translate_ranker_->RecordTranslateEvent( - event_type, translate_driver_->GetVisibleURL(), translate_event_.get()); + event_type, translate_driver_->GetUkmSourceId(), translate_event_.get()); translate_client_->RecordTranslateEvent(*translate_event_); } bool TranslateManager::ShouldOverrideDecision(int event_type) { return translate_ranker_->ShouldOverrideDecision( - event_type, translate_driver_->GetVisibleURL(), translate_event_.get()); + event_type, translate_driver_->GetUkmSourceId(), translate_event_.get()); } bool TranslateManager::ShouldSuppressBubbleUI(
diff --git a/components/translate/core/browser/translate_manager_unittest.cc b/components/translate/core/browser/translate_manager_unittest.cc index f24d0171..47d39e5 100644 --- a/components/translate/core/browser/translate_manager_unittest.cc +++ b/components/translate/core/browser/translate_manager_unittest.cc
@@ -14,6 +14,7 @@ #include "build/build_config.h" #include "components/infobars/core/infobar.h" #include "components/language/core/browser/language_model.h" +#include "components/language/core/browser/language_prefs.h" #include "components/language/core/common/language_experiments.h" #include "components/pref_registry/pref_registry_syncable.h" #include "components/sync_preferences/testing_pref_service_syncable.h" @@ -114,11 +115,10 @@ // TranslatePrefs gets created. struct ProfilePrefRegistration { ProfilePrefRegistration(sync_preferences::TestingPrefServiceSyncable* prefs) { - prefs->registry()->RegisterStringPref(accept_languages_prefs, - std::string()); + language::LanguagePrefs::RegisterProfilePrefs(prefs->registry()); + prefs->SetString(accept_languages_prefs, std::string()); #if defined(OS_CHROMEOS) - prefs->registry()->RegisterStringPref(preferred_languages_prefs, - std::string()); + prefs->SetString(preferred_languages_prefs, std::string()); #endif TranslatePrefs::RegisterProfilePrefs(prefs->registry()); // TODO(groby): Figure out RegisterProfilePrefs() should register this.
diff --git a/components/translate/core/browser/translate_prefs.cc b/components/translate/core/browser/translate_prefs.cc index 6d52f86..8863d28 100644 --- a/components/translate/core/browser/translate_prefs.cc +++ b/components/translate/core/browser/translate_prefs.cc
@@ -50,8 +50,6 @@ "translate_ignored_count_for_language"; const char TranslatePrefs::kPrefTranslateAcceptedCount[] = "translate_accepted_count"; -const char TranslatePrefs::kPrefTranslateBlockedLanguages[] = - "translate_blocked_languages"; const char TranslatePrefs::kPrefTranslateLastDeniedTimeForLanguage[] = "translate_last_denied_time_for_language"; const char TranslatePrefs::kPrefTranslateTooOftenDeniedForLanguage[] = @@ -155,7 +153,9 @@ TranslatePrefs::TranslatePrefs(PrefService* user_prefs, const char* accept_languages_pref, const char* preferred_languages_pref) - : accept_languages_pref_(accept_languages_pref), prefs_(user_prefs) { + : accept_languages_pref_(accept_languages_pref), + prefs_(user_prefs), + language_prefs_(std::make_unique<language::LanguagePrefs>(user_prefs)) { #if defined(OS_CHROMEOS) preferred_languages_pref_ = preferred_languages_pref; #else @@ -165,6 +165,8 @@ ResetEmptyBlockedLanguagesToDefaults(); } +TranslatePrefs::~TranslatePrefs() = default; + bool TranslatePrefs::IsOfferTranslateEnabled() const { return prefs_->GetBoolean(prefs::kOfferTranslateEnabled); } @@ -187,7 +189,7 @@ } void TranslatePrefs::ResetToDefaults() { - ClearBlockedLanguages(); + ResetBlockedLanguagesToDefault(); ClearBlacklistedSites(); ClearWhitelistedLanguagePairs(); prefs_->ClearPref(kPrefTranslateDeniedCount); @@ -205,8 +207,8 @@ } bool TranslatePrefs::IsBlockedLanguage( - const std::string& original_language) const { - return IsValueBlacklisted(kPrefTranslateBlockedLanguages, original_language); + const std::string& input_language) const { + return language_prefs_->IsFluent(input_language); } // Note: the language codes used in the language settings list have the Chrome @@ -451,22 +453,12 @@ void TranslatePrefs::BlockLanguage(const std::string& input_language) { DCHECK(!input_language.empty()); - - std::string translate_language = input_language; - language::ToTranslateLanguageSynonym(&translate_language); - - BlacklistValue(kPrefTranslateBlockedLanguages, translate_language); + language_prefs_->SetFluent(input_language); } void TranslatePrefs::UnblockLanguage(const std::string& input_language) { DCHECK(!input_language.empty()); - - std::string translate_language = input_language; - language::ToTranslateLanguageSynonym(&translate_language); - if (GetListSize(kPrefTranslateBlockedLanguages) > 1) { - RemoveValueFromBlacklist(kPrefTranslateBlockedLanguages, - translate_language); - } + language_prefs_->ClearFluent(input_language); } bool TranslatePrefs::IsSiteBlacklisted(const std::string& site) const { @@ -549,12 +541,8 @@ dict->Remove(original_language, nullptr); } -bool TranslatePrefs::HasBlockedLanguages() const { - return GetListSize(kPrefTranslateBlockedLanguages) != 0; -} - -void TranslatePrefs::ClearBlockedLanguages() { - prefs_->ClearPref(kPrefTranslateBlockedLanguages); +void TranslatePrefs::ResetBlockedLanguagesToDefault() { + language_prefs_->ResetFluentLanguagesToDefaults(); } bool TranslatePrefs::HasBlacklistedSites() const { @@ -841,9 +829,6 @@ registry->RegisterDictionaryPref( kPrefTranslateAcceptedCount, user_prefs::PrefRegistrySyncable::SYNCABLE_PREF); - registry->RegisterListPref(kPrefTranslateBlockedLanguages, - GetDefaultBlockedLanguages(), - user_prefs::PrefRegistrySyncable::SYNCABLE_PREF); registry->RegisterDictionaryPref(kPrefTranslateLastDeniedTimeForLanguage); registry->RegisterDictionaryPref( kPrefTranslateTooOftenDeniedForLanguage, @@ -893,8 +878,7 @@ } void TranslatePrefs::ResetEmptyBlockedLanguagesToDefaults() { - if (!HasBlockedLanguages()) - ClearBlockedLanguages(); + language_prefs_->ResetEmptyFluentLanguagesToDefault(); } bool TranslatePrefs::IsValueInList(const base::ListValue* list, @@ -974,25 +958,4 @@ } } -base::Value TranslatePrefs::GetDefaultBlockedLanguages() { -#if defined(OS_CHROMEOS) - // Preferred languages. - std::vector<std::string> languages = {language::kFallbackInputMethodLocale}; -#else - // Accept languages. - std::vector<std::string> languages = - base::SplitString(l10n_util::GetStringUTF8(IDS_ACCEPT_LANGUAGES), ",", - base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL); -#endif - base::ListValue language_values; - for (std::string& language : languages) { - language::ToTranslateLanguageSynonym(&language); - if (std::find(language_values.GetList().begin(), - language_values.GetList().end(), - base::Value(language)) == language_values.GetList().end()) - language_values.GetList().emplace_back(language); - } - return std::move(language_values); -} - } // namespace translate
diff --git a/components/translate/core/browser/translate_prefs.h b/components/translate/core/browser/translate_prefs.h index 6051301..c4d3efd3 100644 --- a/components/translate/core/browser/translate_prefs.h +++ b/components/translate/core/browser/translate_prefs.h
@@ -30,6 +30,10 @@ class PrefRegistrySyncable; } +namespace language { +class LanguagePrefs; +} + namespace translate { // Enables or disables the regional locales as valid selection for the display @@ -135,7 +139,6 @@ static const char kPrefTranslateDeniedCount[]; static const char kPrefTranslateIgnoredCount[]; static const char kPrefTranslateAcceptedCount[]; - static const char kPrefTranslateBlockedLanguages[]; static const char kPrefTranslateLastDeniedTimeForLanguage[]; static const char kPrefTranslateTooOftenDeniedForLanguage[]; static const char kPrefTranslateRecentTarget[]; @@ -165,6 +168,8 @@ const char* accept_languages_pref, const char* preferred_languages_pref); + ~TranslatePrefs(); + // Checks if the "offer translate" (i.e. automatic translate bubble) feature // is enabled. bool IsOfferTranslateEnabled() const; @@ -349,16 +354,7 @@ // Updates the language list of the language settings. void UpdateLanguageList(const std::vector<std::string>& languages); - // Will return true if at least one language has been blocked. - bool HasBlockedLanguages() const; - - // Merges two language sets to migrate to the language setting UI. - static void CreateBlockedLanguages( - std::vector<std::string>* blocked_languages, - const std::vector<std::string>& blacklisted_languages, - const std::vector<std::string>& accept_languages); - - void ClearBlockedLanguages(); + void ResetBlockedLanguagesToDefault(); void ClearBlacklistedSites(); void ClearWhitelistedLanguagePairs(); @@ -403,6 +399,8 @@ std::string country_; // The country the app runs in. + std::unique_ptr<language::LanguagePrefs> language_prefs_; + DISALLOW_COPY_AND_ASSIGN(TranslatePrefs); };
diff --git a/components/translate/core/browser/translate_prefs_unittest.cc b/components/translate/core/browser/translate_prefs_unittest.cc index b4b5d80..a65c965f 100644 --- a/components/translate/core/browser/translate_prefs_unittest.cc +++ b/components/translate/core/browser/translate_prefs_unittest.cc
@@ -61,6 +61,7 @@ protected: TranslatePrefsTest() : prefs_(new sync_preferences::TestingPrefServiceSyncable()) { + language::LanguagePrefs::RegisterProfilePrefs(prefs_->registry()); TranslatePrefs::RegisterProfilePrefs(prefs_->registry()); translate_prefs_.reset(new translate::TranslatePrefs( prefs_.get(), kAcceptLanguagesPref, kPreferredLanguagesPref)); @@ -69,10 +70,9 @@ } void SetUp() override { - prefs_->registry()->RegisterStringPref(kAcceptLanguagesPref, std::string()); + prefs_->SetString(kAcceptLanguagesPref, std::string()); #if defined(OS_CHROMEOS) - prefs_->registry()->RegisterStringPref(kPreferredLanguagesPref, - std::string()); + prefs_->SetString(kPreferredLanguagesPref, std::string()); #endif } @@ -403,24 +403,24 @@ ExpectBlockedLanguageListContent({"en", "fr", "es", "de"}); // Add a duplicate. - translate_prefs_->ClearBlockedLanguages(); + translate_prefs_->ResetBlockedLanguagesToDefault(); translate_prefs_->BlockLanguage("es-AR"); translate_prefs_->BlockLanguage("es-AR"); ExpectBlockedLanguageListContent({"en", "es"}); // Two languages with the same base. - translate_prefs_->ClearBlockedLanguages(); + translate_prefs_->ResetBlockedLanguagesToDefault(); translate_prefs_->BlockLanguage("fr-CA"); translate_prefs_->BlockLanguage("fr-FR"); ExpectBlockedLanguageListContent({"en", "fr"}); // Chinese is a special case. - translate_prefs_->ClearBlockedLanguages(); + translate_prefs_->ResetBlockedLanguagesToDefault(); translate_prefs_->BlockLanguage("zh-MO"); translate_prefs_->BlockLanguage("zh-CN"); ExpectBlockedLanguageListContent({"en", "zh-TW", "zh-CN"}); - translate_prefs_->ClearBlockedLanguages(); + translate_prefs_->ResetBlockedLanguagesToDefault(); translate_prefs_->BlockLanguage("zh-TW"); translate_prefs_->BlockLanguage("zh-HK"); ExpectBlockedLanguageListContent({"en", "zh-TW"}); @@ -438,19 +438,19 @@ ExpectBlockedLanguageListContent({"en"}); // Language in the list. - translate_prefs_->ClearBlockedLanguages(); + translate_prefs_->ResetBlockedLanguagesToDefault(); translate_prefs_->BlockLanguage("fr"); translate_prefs_->UnblockLanguage("en-UK"); ExpectBlockedLanguageListContent({"fr"}); // Language in the list but with different region. - translate_prefs_->ClearBlockedLanguages(); + translate_prefs_->ResetBlockedLanguagesToDefault(); translate_prefs_->BlockLanguage("fr"); translate_prefs_->UnblockLanguage("en-AU"); ExpectBlockedLanguageListContent({"fr"}); // Multiple languages. - translate_prefs_->ClearBlockedLanguages(); + translate_prefs_->ResetBlockedLanguagesToDefault(); translate_prefs_->BlockLanguage("fr-CA"); translate_prefs_->BlockLanguage("fr-FR"); translate_prefs_->BlockLanguage("es-AR"); @@ -458,13 +458,13 @@ ExpectBlockedLanguageListContent({"en", "es"}); // Chinese is a special case. - translate_prefs_->ClearBlockedLanguages(); + translate_prefs_->ResetBlockedLanguagesToDefault(); translate_prefs_->BlockLanguage("zh-MO"); translate_prefs_->BlockLanguage("zh-CN"); translate_prefs_->UnblockLanguage("zh-TW"); ExpectBlockedLanguageListContent({"en", "zh-CN"}); - translate_prefs_->ClearBlockedLanguages(); + translate_prefs_->ResetBlockedLanguagesToDefault(); translate_prefs_->BlockLanguage("zh-MO"); translate_prefs_->BlockLanguage("zh-CN"); translate_prefs_->UnblockLanguage("zh-CN"); @@ -477,7 +477,7 @@ // Force blocked false, language not already in list. languages = {"en"}; translate_prefs_->UpdateLanguageList(languages); - translate_prefs_->ClearBlockedLanguages(); + translate_prefs_->ResetBlockedLanguagesToDefault(); translate_prefs_->AddToLanguageList("it-IT", /*force_blocked=*/false); ExpectLanguagePrefs("en,it-IT"); ExpectBlockedLanguageListContent({"en", "it"}); @@ -485,7 +485,7 @@ // Force blocked false, language from same family already in list. languages = {"en", "es-AR"}; translate_prefs_->UpdateLanguageList(languages); - translate_prefs_->ClearBlockedLanguages(); + translate_prefs_->ResetBlockedLanguagesToDefault(); translate_prefs_->AddToLanguageList("es-ES", /*force_blocked=*/false); ExpectLanguagePrefs("en,es-AR,es-ES"); ExpectBlockedLanguageListContent({"en"}); @@ -497,7 +497,7 @@ // Unblock last language of a family. languages = {"en-US", "es-AR"}; translate_prefs_->UpdateLanguageList(languages); - translate_prefs_->ClearBlockedLanguages(); + translate_prefs_->ResetBlockedLanguagesToDefault(); translate_prefs_->BlockLanguage("en-US"); translate_prefs_->BlockLanguage("es-AR"); translate_prefs_->RemoveFromLanguageList("es-AR"); @@ -507,7 +507,7 @@ // Do not unblock if not the last language of a family. languages = {"en-US", "es-AR", "es-ES"}; translate_prefs_->UpdateLanguageList(languages); - translate_prefs_->ClearBlockedLanguages(); + translate_prefs_->ResetBlockedLanguagesToDefault(); translate_prefs_->BlockLanguage("en-US"); translate_prefs_->BlockLanguage("es-AR"); translate_prefs_->RemoveFromLanguageList("es-AR"); @@ -529,23 +529,6 @@ ExpectLanguagePrefs(""); } -TEST_F(TranslatePrefsTest, ResetEmptyBlockedLanguagesToDefaults) { - ExpectBlockedLanguageListContent({"en"}); - - translate_prefs_->ResetEmptyBlockedLanguagesToDefaults(); - ExpectBlockedLanguageListContent({"en"}); - - translate_prefs_->BlockLanguage("fr"); - translate_prefs_->ResetEmptyBlockedLanguagesToDefaults(); - ExpectBlockedLanguageListContent({"en", "fr"}); - - prefs_->Set(TranslatePrefs::kPrefTranslateBlockedLanguages, - base::ListValue()); - ExpectBlockedLanguageListContent({}); - translate_prefs_->ResetEmptyBlockedLanguagesToDefaults(); - ExpectBlockedLanguageListContent({"en"}); -} - TEST_F(TranslatePrefsTest, RemoveFromLanguageListClearsRecentLanguage) { std::vector<std::string> languages;
diff --git a/components/translate/core/browser/translate_ranker.h b/components/translate/core/browser/translate_ranker.h index 5b4e710..4b62b1c0 100644 --- a/components/translate/core/browser/translate_ranker.h +++ b/components/translate/core/browser/translate_ranker.h
@@ -11,8 +11,7 @@ #include "base/macros.h" #include "components/keyed_service/core/keyed_service.h" - -class GURL; +#include "services/metrics/public/cpp/ukm_source_id.h" namespace metrics { class TranslateEventProto; @@ -46,7 +45,7 @@ // metrics::TranslateEventProto::EventType. virtual void RecordTranslateEvent( int event_type, - const GURL& url, + ukm::SourceId ukm_source_id, metrics::TranslateEventProto* translate_event) = 0; // If override for the given |event_type| is enabled, will return true and add @@ -57,7 +56,7 @@ // metrics::TranslateEventProto::EventType. virtual bool ShouldOverrideDecision( int event_type, - const GURL& url, + ukm::SourceId ukm_source_id, metrics::TranslateEventProto* translate_event) = 0; // Override the default enabled/disabled state of translate event logging.
diff --git a/components/translate/core/browser/translate_ranker_impl.cc b/components/translate/core/browser/translate_ranker_impl.cc index f76863a..dfcd77b 100644 --- a/components/translate/core/browser/translate_ranker_impl.cc +++ b/components/translate/core/browser/translate_ranker_impl.cc
@@ -6,6 +6,8 @@ #include <cmath> #include <memory> +#include <utility> +#include <vector> #include "base/bind.h" #include "base/bind_helpers.h" @@ -27,6 +29,7 @@ #include "components/variations/variations_associated_data.h" #include "services/metrics/public/cpp/ukm_builders.h" #include "services/metrics/public/cpp/ukm_recorder.h" +#include "services/metrics/public/cpp/ukm_source_id.h" #include "third_party/metrics_proto/translate_event.pb.h" #include "url/gurl.h" @@ -319,16 +322,13 @@ void TranslateRankerImpl::SendEventToUKM( const metrics::TranslateEventProto& event, - const GURL& url) { + ukm::SourceId ukm_source_id) { if (!ukm_recorder_) { DVLOG(3) << "No UKM service."; return; } - DVLOG(3) << "Sending event for url: " << url.spec(); - ukm::SourceId source_id = ukm_recorder_->GetNewSourceID(); - ukm_recorder_->UpdateSourceURL(source_id, url); - // TODO(hamelphi): Remove hashing functions once UKM accepts strings metrics. - ukm::builders::Translate(source_id) + + ukm::builders::Translate(ukm_source_id) .SetSourceLanguage(base::HashMetricName(event.source_language())) .SetTargetLanguage(base::HashMetricName(event.target_language())) .SetCountry(base::HashMetricName(event.country())) @@ -343,12 +343,12 @@ void TranslateRankerImpl::AddTranslateEvent( const metrics::TranslateEventProto& event, - const GURL& url) { + ukm::SourceId ukm_source_id) { DCHECK(sequence_checker_.CalledOnValidSequence()); if (is_logging_enabled_) { DVLOG(3) << "Adding translate ranker event."; - if (url.is_valid()) { - SendEventToUKM(event, url); + if (ukm_source_id != ukm::kInvalidSourceId) { + SendEventToUKM(event, ukm_source_id); } event_cache_.push_back(event); } @@ -365,19 +365,19 @@ void TranslateRankerImpl::RecordTranslateEvent( int event_type, - const GURL& url, + ukm::SourceId ukm_source_id, metrics::TranslateEventProto* translate_event) { DCHECK(metrics::TranslateEventProto::EventType_IsValid(event_type)); translate_event->set_event_type( static_cast<metrics::TranslateEventProto::EventType>(event_type)); translate_event->set_event_timestamp_sec( (base::TimeTicks::Now() - base::TimeTicks()).InSeconds()); - AddTranslateEvent(*translate_event, url); + AddTranslateEvent(*translate_event, ukm_source_id); } bool TranslateRankerImpl::ShouldOverrideDecision( int event_type, - const GURL& url, + ukm::SourceId ukm_source_id, metrics::TranslateEventProto* translate_event) { DCHECK(metrics::TranslateEventProto::EventType_IsValid(event_type)); if ((event_type == metrics::TranslateEventProto::MATCHES_PREVIOUS_LANGUAGE && @@ -390,7 +390,7 @@ DVLOG(3) << "Overriding decision of type: " << event_type; return true; } else { - RecordTranslateEvent(event_type, url, translate_event); + RecordTranslateEvent(event_type, ukm_source_id, translate_event); return false; } }
diff --git a/components/translate/core/browser/translate_ranker_impl.h b/components/translate/core/browser/translate_ranker_impl.h index 22adcff..5d9a6d5 100644 --- a/components/translate/core/browser/translate_ranker_impl.h +++ b/components/translate/core/browser/translate_ranker_impl.h
@@ -7,6 +7,7 @@ #include <memory> #include <string> +#include <vector> #include "base/feature_list.h" #include "base/memory/ref_counted.h" @@ -16,6 +17,7 @@ #include "components/assist_ranker/ranker_model_loader.h" #include "components/keyed_service/core/keyed_service.h" #include "components/translate/core/browser/translate_ranker.h" +#include "services/metrics/public/cpp/ukm_source_id.h" #include "url/gurl.h" class GURL; @@ -54,7 +56,7 @@ const std::string& cntry, const std::string& locale); - TranslateRankerFeatures(const metrics::TranslateEventProto& tep); + explicit TranslateRankerFeatures(const metrics::TranslateEventProto& tep); ~TranslateRankerFeatures(); @@ -90,7 +92,7 @@ static base::FilePath GetModelPath(const base::FilePath& data_dir); // Get the URL from which the download the translate ranker model, by default - // from Finch. + // from Field Trial parameters. static GURL GetModelURL(); // TranslateRanker... @@ -102,11 +104,11 @@ std::vector<metrics::TranslateEventProto>* events) override; void RecordTranslateEvent( int event_type, - const GURL& url, + ukm::SourceId ukm_source_id, metrics::TranslateEventProto* translate_event) override; bool ShouldOverrideDecision( int event_type, - const GURL& url, + ukm::SourceId ukm_source_id, metrics::TranslateEventProto* translate_event) override; void OnModelAvailable(std::unique_ptr<assist_ranker::RankerModel> model); @@ -121,11 +123,11 @@ private: void SendEventToUKM(const metrics::TranslateEventProto& translate_event, - const GURL& url); + ukm::SourceId ukm_source_id); // Caches the translate event. void AddTranslateEvent(const metrics::TranslateEventProto& translate_event, - const GURL& url); + ukm::SourceId ukm_source_id); // Used to log URL-keyed metrics. This pointer will outlive |this|. ukm::UkmRecorder* ukm_recorder_;
diff --git a/components/translate/core/browser/translate_ranker_impl_unittest.cc b/components/translate/core/browser/translate_ranker_impl_unittest.cc index 2f9b5be..1ab9980 100644 --- a/components/translate/core/browser/translate_ranker_impl_unittest.cc +++ b/components/translate/core/browser/translate_ranker_impl_unittest.cc
@@ -6,6 +6,8 @@ #include <initializer_list> #include <memory> +#include <utility> +#include <vector> #include "base/feature_list.h" #include "base/run_loop.h" @@ -36,6 +38,8 @@ using translate::TranslateRankerImpl; constexpr uint32_t kModelVersion = 1234; +ukm::SourceId kUkmSourceId0 = 123; +ukm::SourceId kUkmSourceId1 = 567; class TranslateRankerImplTest : public ::testing::Test { protected: @@ -340,16 +344,13 @@ ranker->EnableLogging(true); std::vector<metrics::TranslateEventProto> flushed_events; - GURL url0("https://www.google.com"); - GURL url1("https://www.gmail.com"); - // Check that flushing an empty cache will return an empty vector. ranker->FlushTranslateEvents(&flushed_events); EXPECT_EQ(0U, flushed_events.size()); - ranker->RecordTranslateEvent(0, url0, &translate_event1_); - ranker->RecordTranslateEvent(1, GURL(), &translate_event2_); - ranker->RecordTranslateEvent(2, url1, &translate_event3_); + ranker->RecordTranslateEvent(0, kUkmSourceId0, &translate_event1_); + ranker->RecordTranslateEvent(1, ukm::kInvalidSourceId, &translate_event2_); + ranker->RecordTranslateEvent(2, kUkmSourceId1, &translate_event3_); // Capture the data and verify that it is as expected. ranker->FlushTranslateEvents(&flushed_events); @@ -371,18 +372,16 @@ const auto& entries = GetTestUkmRecorder()->GetEntriesByName( ukm::builders::Translate::kEntryName); EXPECT_EQ(2u, entries.size()); - bool has_url0 = false; - bool has_url1 = false; + bool has_kUkmSourceId0 = false; + bool has_kUkmSourceId1 = false; for (const auto* entry : entries) { - const ukm::UkmSource* source = - GetTestUkmRecorder()->GetSourceForSourceId(entry->source_id); - if (source && source->url() == url0) - has_url0 = true; - else if (source && source->url() == url1) - has_url1 = true; + if (entry->source_id == kUkmSourceId0) + has_kUkmSourceId0 = true; + if (entry->source_id == kUkmSourceId1) + has_kUkmSourceId1 = true; } - EXPECT_TRUE(has_url0); - EXPECT_TRUE(has_url1); + EXPECT_TRUE(has_kUkmSourceId0); + EXPECT_TRUE(has_kUkmSourceId1); } TEST_F(TranslateRankerImplTest, EnableLogging) { @@ -391,16 +390,16 @@ std::vector<metrics::TranslateEventProto> flushed_events; // Logging is disabled by default. No events will be cached. - ranker->RecordTranslateEvent(0, GURL(), &translate_event1_); - ranker->RecordTranslateEvent(1, GURL(), &translate_event2_); + ranker->RecordTranslateEvent(0, kUkmSourceId0, &translate_event1_); + ranker->RecordTranslateEvent(1, kUkmSourceId0, &translate_event2_); ranker->FlushTranslateEvents(&flushed_events); EXPECT_EQ(0U, flushed_events.size()); // Once we enable logging, events will be cached. ranker->EnableLogging(true); - ranker->RecordTranslateEvent(0, GURL(), &translate_event1_); - ranker->RecordTranslateEvent(1, GURL(), &translate_event2_); + ranker->RecordTranslateEvent(0, kUkmSourceId0, &translate_event1_); + ranker->RecordTranslateEvent(1, kUkmSourceId0, &translate_event2_); ranker->FlushTranslateEvents(&flushed_events); EXPECT_EQ(2U, flushed_events.size()); @@ -408,8 +407,8 @@ // Turning logging back off, caching is disabled once again. ranker->EnableLogging(false); - ranker->RecordTranslateEvent(0, GURL(), &translate_event1_); - ranker->RecordTranslateEvent(1, GURL(), &translate_event2_); + ranker->RecordTranslateEvent(0, kUkmSourceId0, &translate_event1_); + ranker->RecordTranslateEvent(1, kUkmSourceId0, &translate_event2_); // Logging is disabled, so no events should be cached. ranker->FlushTranslateEvents(&flushed_events); @@ -421,15 +420,15 @@ GetRankerForTest(0.0f); std::vector<metrics::TranslateEventProto> flushed_events; // Logging is disabled by default. No events will be cached. - ranker->RecordTranslateEvent(0, GURL(), &translate_event1_); + ranker->RecordTranslateEvent(0, kUkmSourceId0, &translate_event1_); // Making sure that cache is still empty once logging is turned on. ranker->EnableLogging(true); ranker->FlushTranslateEvents(&flushed_events); EXPECT_EQ(0U, flushed_events.size()); // These events will be cached. - ranker->RecordTranslateEvent(0, GURL(), &translate_event1_); - ranker->RecordTranslateEvent(1, GURL(), &translate_event2_); + ranker->RecordTranslateEvent(0, kUkmSourceId0, &translate_event1_); + ranker->RecordTranslateEvent(1, kUkmSourceId0, &translate_event2_); // Cache will not be cleared if the logging state does not change. ranker->EnableLogging(true); ranker->FlushTranslateEvents(&flushed_events); @@ -441,8 +440,8 @@ // Filling cache again. ranker->EnableLogging(true); - ranker->RecordTranslateEvent(0, GURL(), &translate_event1_); - ranker->RecordTranslateEvent(1, GURL(), &translate_event2_); + ranker->RecordTranslateEvent(0, kUkmSourceId0, &translate_event1_); + ranker->RecordTranslateEvent(1, kUkmSourceId0, &translate_event2_); // Switching logging off will clear the cache. ranker->EnableLogging(false); ranker->FlushTranslateEvents(&flushed_events); @@ -450,8 +449,8 @@ // Filling cache again. ranker->EnableLogging(true); - ranker->RecordTranslateEvent(0, GURL(), &translate_event1_); - ranker->RecordTranslateEvent(1, GURL(), &translate_event2_); + ranker->RecordTranslateEvent(0, kUkmSourceId0, &translate_event1_); + ranker->RecordTranslateEvent(1, kUkmSourceId0, &translate_event2_); // Switching logging off and on again will clear the cache. ranker->EnableLogging(false); ranker->EnableLogging(true); @@ -468,8 +467,8 @@ const int kEventType = 12; metrics::TranslateEventProto translate_event = CreateDefaultTranslateEvent(); - EXPECT_FALSE( - ranker->ShouldOverrideDecision(kEventType, GURL(), &translate_event)); + EXPECT_FALSE(ranker->ShouldOverrideDecision(kEventType, kUkmSourceId0, + &translate_event)); std::vector<metrics::TranslateEventProto> flushed_events; ranker->FlushTranslateEvents(&flushed_events); @@ -494,10 +493,10 @@ EXPECT_TRUE( GetRankerForTest(0.99f)->ShouldOfferTranslation(&translate_event)); EXPECT_TRUE(ranker->ShouldOverrideDecision( - metrics::TranslateEventProto::LANGUAGE_DISABLED_BY_AUTO_BLACKLIST, GURL(), - &translate_event)); + metrics::TranslateEventProto::LANGUAGE_DISABLED_BY_AUTO_BLACKLIST, + kUkmSourceId0, &translate_event)); EXPECT_FALSE(ranker->ShouldOverrideDecision( - metrics::TranslateEventProto::MATCHES_PREVIOUS_LANGUAGE, GURL(), + metrics::TranslateEventProto::MATCHES_PREVIOUS_LANGUAGE, kUkmSourceId0, &translate_event)); std::vector<metrics::TranslateEventProto> flushed_events; @@ -529,11 +528,11 @@ EXPECT_TRUE( GetRankerForTest(0.99f)->ShouldOfferTranslation(&translate_event)); EXPECT_TRUE(ranker->ShouldOverrideDecision( - metrics::TranslateEventProto::MATCHES_PREVIOUS_LANGUAGE, GURL(), + metrics::TranslateEventProto::MATCHES_PREVIOUS_LANGUAGE, kUkmSourceId0, &translate_event)); EXPECT_FALSE(ranker->ShouldOverrideDecision( - metrics::TranslateEventProto::LANGUAGE_DISABLED_BY_AUTO_BLACKLIST, GURL(), - &translate_event)); + metrics::TranslateEventProto::LANGUAGE_DISABLED_BY_AUTO_BLACKLIST, + kUkmSourceId0, &translate_event)); std::vector<metrics::TranslateEventProto> flushed_events; ranker->FlushTranslateEvents(&flushed_events); @@ -561,11 +560,11 @@ EXPECT_TRUE( GetRankerForTest(0.99f)->ShouldOfferTranslation(&translate_event)); EXPECT_TRUE(ranker->ShouldOverrideDecision( - metrics::TranslateEventProto::MATCHES_PREVIOUS_LANGUAGE, GURL(), + metrics::TranslateEventProto::MATCHES_PREVIOUS_LANGUAGE, kUkmSourceId0, &translate_event)); EXPECT_TRUE(ranker->ShouldOverrideDecision( - metrics::TranslateEventProto::LANGUAGE_DISABLED_BY_AUTO_BLACKLIST, GURL(), - &translate_event)); + metrics::TranslateEventProto::LANGUAGE_DISABLED_BY_AUTO_BLACKLIST, + kUkmSourceId0, &translate_event)); std::vector<metrics::TranslateEventProto> flushed_events; ranker->FlushTranslateEvents(&flushed_events); @@ -601,11 +600,11 @@ GetRankerForTest(0.99f)->ShouldOfferTranslation(&translate_event)); EXPECT_TRUE(ranker->ShouldOverrideDecision( - metrics::TranslateEventProto::LANGUAGE_DISABLED_BY_AUTO_BLACKLIST, GURL(), - &translate_event)); + metrics::TranslateEventProto::LANGUAGE_DISABLED_BY_AUTO_BLACKLIST, + kUkmSourceId0, &translate_event)); ranker->RecordTranslateEvent( - metrics::TranslateEventProto::USER_NEVER_TRANSLATE_LANGUAGE, GURL(), - &translate_event); + metrics::TranslateEventProto::USER_NEVER_TRANSLATE_LANGUAGE, + kUkmSourceId0, &translate_event); std::vector<metrics::TranslateEventProto> flushed_events; ranker->FlushTranslateEvents(&flushed_events);
diff --git a/components/translate/core/browser/translate_ui_delegate_unittest.cc b/components/translate/core/browser/translate_ui_delegate_unittest.cc index 5d2724e..1e48ee8 100644 --- a/components/translate/core/browser/translate_ui_delegate_unittest.cc +++ b/components/translate/core/browser/translate_ui_delegate_unittest.cc
@@ -12,6 +12,8 @@ #include "build/build_config.h" #include "components/infobars/core/infobar.h" #include "components/language/core/browser/language_model.h" +#include "components/language/core/browser/language_prefs.h" +#include "components/language/core/browser/pref_names.h" #include "components/pref_registry/pref_registry_syncable.h" #include "components/sync_preferences/testing_pref_service_syncable.h" #include "components/translate/core/browser/mock_translate_client.h" @@ -20,6 +22,7 @@ #include "components/translate/core/browser/translate_client.h" #include "components/translate/core/browser/translate_infobar_delegate.h" #include "components/translate/core/browser/translate_manager.h" +#include "components/translate/core/browser/translate_pref_names.h" #include "components/translate/core/browser/translate_prefs.h" #include "components/variations/variations_associated_data.h" #include "testing/gmock/include/gmock/gmock.h" @@ -48,11 +51,16 @@ void SetUp() override { pref_service_.reset(new sync_preferences::TestingPrefServiceSyncable()); - pref_service_->registry()->RegisterStringPref( - "settings.language.preferred_languages", std::string()); - pref_service_->registry()->RegisterStringPref("intl.accept_languages", - std::string()); - pref_service_->registry()->RegisterBooleanPref("translate.enabled", true); + + language::LanguagePrefs::RegisterProfilePrefs(pref_service_->registry()); + pref_service_->SetString(language::prefs::kAcceptLanguages, std::string()); +#if defined(OS_CHROMEOS) + pref_service_->SetString(language::prefs::kPreferredLanguages, + std::string()); +#endif + + pref_service_->registry()->RegisterBooleanPref( + prefs::kOfferTranslateEnabled, true); TranslatePrefs::RegisterProfilePrefs(pref_service_->registry()); client_.reset(new MockTranslateClient(&driver_, pref_service_.get()));
diff --git a/components/translate/ios/browser/BUILD.gn b/components/translate/ios/browser/BUILD.gn index 003164d..15f6c2d7 100644 --- a/components/translate/ios/browser/BUILD.gn +++ b/components/translate/ios/browser/BUILD.gn
@@ -29,6 +29,7 @@ "//components/translate/core/browser", "//components/translate/core/common", "//components/translate/core/language_detection", + "//ios/chrome/browser/metrics:ukm_url_recorder", "//ios/web", "//ui/base", "//url",
diff --git a/components/translate/ios/browser/DEPS b/components/translate/ios/browser/DEPS index a3d71d672..b944556 100644 --- a/components/translate/ios/browser/DEPS +++ b/components/translate/ios/browser/DEPS
@@ -1,3 +1,4 @@ include_rules = [ "+components/language/core/browser", + "+ios/chrome/browser/metrics" ]
diff --git a/components/translate/ios/browser/ios_translate_driver.h b/components/translate/ios/browser/ios_translate_driver.h index 8c6f255..29bce8e8 100644 --- a/components/translate/ios/browser/ios_translate_driver.h +++ b/components/translate/ios/browser/ios_translate_driver.h
@@ -68,6 +68,7 @@ const std::string& GetContentsMimeType() override; const GURL& GetLastCommittedURL() override; const GURL& GetVisibleURL() override; + ukm::SourceId GetUkmSourceId() override; bool HasCurrentPage() override; void OpenUrlInNewTab(const GURL& url) override;
diff --git a/components/translate/ios/browser/ios_translate_driver.mm b/components/translate/ios/browser/ios_translate_driver.mm index 954096fa..92f9e3a 100644 --- a/components/translate/ios/browser/ios_translate_driver.mm +++ b/components/translate/ios/browser/ios_translate_driver.mm
@@ -18,6 +18,7 @@ #import "components/translate/ios/browser/js_translate_manager.h" #import "components/translate/ios/browser/language_detection_controller.h" #import "components/translate/ios/browser/translate_controller.h" +#include "ios/chrome/browser/metrics/ukm_url_recorder.h" #include "ios/web/public/browser_state.h" #include "ios/web/public/navigation_item.h" #include "ios/web/public/navigation_manager.h" @@ -179,6 +180,10 @@ return web_state_->GetVisibleURL(); } +ukm::SourceId IOSTranslateDriver::GetUkmSourceId() { + return ukm::GetSourceIdForWebStateDocument(web_state_); +} + bool IOSTranslateDriver::HasCurrentPage() { return (navigation_manager_->GetVisibleItem() != nullptr); }
diff --git a/components/ukm/ukm_service.cc b/components/ukm/ukm_service.cc index 1ed68c5..7725e3f 100644 --- a/components/ukm/ukm_service.cc +++ b/components/ukm/ukm_service.cc
@@ -35,7 +35,7 @@ uint64_t client_id = 0; while (!client_id) client_id = base::RandUint64(); - pref_service->SetInt64(prefs::kUkmClientId, client_id); + pref_service->SetUint64(prefs::kUkmClientId, client_id); // Also reset the session id counter. pref_service->SetInteger(prefs::kUkmSessionId, 0); @@ -43,10 +43,26 @@ } uint64_t LoadOrGenerateAndStoreClientId(PrefService* pref_service) { - uint64_t client_id = pref_service->GetInt64(prefs::kUkmClientId); - if (!client_id) - client_id = GenerateAndStoreClientId(pref_service); - return client_id; + uint64_t client_id = pref_service->GetUint64(prefs::kUkmClientId); + // The pref is stored as a string and GetUint64() uses base::StringToUint64() + // to convert it. base::StringToUint64() will treat a negative value as + // underflow, which results in 0 (the minimum Uint64 value). + if (client_id) { + UMA_HISTOGRAM_BOOLEAN("UKM.MigratedClientIdInt64ToUInt64", false); + return client_id; + } + + // Since client_id was 0, the pref value may have been negative. Attempt to + // get it as an Int64 to migrate it to Uint64. + client_id = pref_service->GetInt64(prefs::kUkmClientId); + if (client_id) { + pref_service->SetUint64(prefs::kUkmClientId, client_id); + UMA_HISTOGRAM_BOOLEAN("UKM.MigratedClientIdInt64ToUInt64", true); + return client_id; + } + + // The client_id is still 0, so it wasn't set. + return GenerateAndStoreClientId(pref_service); } int32_t LoadAndIncrementSessionId(PrefService* pref_service) { @@ -198,7 +214,7 @@ // static void UkmService::RegisterPrefs(PrefRegistrySimple* registry) { - registry->RegisterInt64Pref(prefs::kUkmClientId, 0); + registry->RegisterUint64Pref(prefs::kUkmClientId, 0); registry->RegisterIntegerPref(prefs::kUkmSessionId, 0); UkmReportingService::RegisterPrefs(registry); }
diff --git a/components/ukm/ukm_service_unittest.cc b/components/ukm/ukm_service_unittest.cc index 5fef928..ead2550 100644 --- a/components/ukm/ukm_service_unittest.cc +++ b/components/ukm/ukm_service_unittest.cc
@@ -186,6 +186,16 @@ } // namespace +TEST_F(UkmServiceTest, ClientIdMigration) { + prefs_.SetInt64(prefs::kUkmClientId, -1); + UkmService service(&prefs_, &client_, + true /* restrict_to_whitelisted_entries */); + service.Initialize(); + uint64_t migrated_id = prefs_.GetUint64(prefs::kUkmClientId); + // -1 migrates to the max UInt 64 value. + EXPECT_EQ(migrated_id, 18446744073709551615ULL); +} + TEST_F(UkmServiceTest, EnableDisableSchedule) { UkmService service(&prefs_, &client_, true /* restrict_to_whitelisted_entries */);
diff --git a/components/viz/common/quads/shared_quad_state.h b/components/viz/common/quads/shared_quad_state.h index d8dcf3c..c9043f50 100644 --- a/components/viz/common/quads/shared_quad_state.h +++ b/components/viz/common/quads/shared_quad_state.h
@@ -72,6 +72,10 @@ // on top are not damaged. SetAll() doesn't update this flag. It has to be set // sepaerately. bool has_surface_damage = false; + // An internal flag used only by the SurfaceAggregator to decide whether to + // merge quads for a surface into their target render pass. It is a + // performance optimization by avoiding render passes as much as possible. + bool is_fast_rounded_corner = false; }; } // namespace viz
diff --git a/components/viz/service/compositor_frame_fuzzer/compositor_frame_fuzzer.cc b/components/viz/service/compositor_frame_fuzzer/compositor_frame_fuzzer.cc index 0412aed9..c20c503 100644 --- a/components/viz/service/compositor_frame_fuzzer/compositor_frame_fuzzer.cc +++ b/components/viz/service/compositor_frame_fuzzer/compositor_frame_fuzzer.cc
@@ -48,7 +48,10 @@ DEFINE_BINARY_PROTO_FUZZER( const content::fuzzing::proto::RenderPass& render_pass_spec) { static base::NoDestructor<Env> env; - viz::CompositorFrame frame = + + viz::FuzzedData fuzzed_data = viz::GenerateFuzzedCompositorFrame(render_pass_spec); - env->browser_process->EmbedFuzzedCompositorFrame(std::move(frame)); + + env->browser_process->EmbedFuzzedCompositorFrame( + std::move(fuzzed_data.frame), std::move(fuzzed_data.allocated_bitmaps)); }
diff --git a/components/viz/service/compositor_frame_fuzzer/compositor_frame_fuzzer.proto b/components/viz/service/compositor_frame_fuzzer/compositor_frame_fuzzer.proto index 3134523..e7fdf826 100644 --- a/components/viz/service/compositor_frame_fuzzer/compositor_frame_fuzzer.proto +++ b/components/viz/service/compositor_frame_fuzzer/compositor_frame_fuzzer.proto
@@ -16,7 +16,13 @@ required SharedQuadState sqs = 1; required Rect rect = 2; required Rect visible_rect = 3; - required SolidColorDrawQuad quad = 4; + + // |oneof| means "at most one of", so be aware that this message could + // have none of the following (consider it invalid and skip if so): + oneof quad { + SolidColorDrawQuad solid_color_quad = 4; + TileDrawQuad tile_quad = 5; + } } message SharedQuadState { @@ -43,6 +49,23 @@ required bool force_anti_aliasing_off = 2; } +message TileDrawQuad { + required bool needs_blending = 1; + + // Allocate an SkBitmap from these values and pass the ResourceId + // to the TileDrawQuad. + required fixed32 texture_color = 2; + required Size texture_size = 3; + + // TODO (celineo): enable fuzzing gfx::RectF + required Rect tex_coord_rect = 4; + + required bool swizzle_contents = 5; + required bool is_premultiplied = 6; + required bool nearest_neighbor = 7; + required bool force_anti_aliasing_off = 8; +} + // Spec to initialize a gfx::Rect. // Defaults to the size of the renderer frame as defined in // fuzzer_browser_process.cc, in the hopes that this generally yields more @@ -54,6 +77,12 @@ required sint32 height = 4 [default = 400]; } +// maps to a gfx::Size, same defaults as gfx::Rect +message Size { + required sint32 width = 1 [default = 620]; + required sint32 height = 2 [default = 400]; +} + message Transform { required double rotate = 1 [default = 0];
diff --git a/components/viz/service/compositor_frame_fuzzer/compositor_frame_fuzzer_util.cc b/components/viz/service/compositor_frame_fuzzer/compositor_frame_fuzzer_util.cc index aa695fb..563ade8b 100644 --- a/components/viz/service/compositor_frame_fuzzer/compositor_frame_fuzzer_util.cc +++ b/components/viz/service/compositor_frame_fuzzer/compositor_frame_fuzzer_util.cc
@@ -9,12 +9,20 @@ #include <utility> #include "components/viz/common/quads/solid_color_draw_quad.h" +#include "components/viz/common/quads/tile_draw_quad.h" +#include "components/viz/common/resources/resource_sizes.h" #include "components/viz/service/compositor_frame_fuzzer/fuzzer_browser_process.h" +#include "third_party/skia/include/core/SkBitmap.h" namespace viz { namespace { +// Hard limit on number of bytes of memory to allocate (e.g. for referenced +// bitmaps) in association with a single CompositorFrame. Currently 1 GiB; +// reduce this if bots are running out of memory. +constexpr uint64_t kMaxMappedMemory = 1 << 30; + // Handles inf / NaN by setting to 0. double MakeNormal(double x) { return isnormal(x) ? x : 0; @@ -29,6 +37,10 @@ return static_cast<float>(x) / std::numeric_limits<uint32_t>::max(); } +gfx::Size GetSizeFromProtobuf(const content::fuzzing::proto::Size& proto_size) { + return gfx::Size(proto_size.width(), proto_size.height()); +} + gfx::Rect GetRectFromProtobuf(const content::fuzzing::proto::Rect& proto_rect) { return gfx::Rect(proto_rect.x(), proto_rect.y(), proto_rect.width(), proto_rect.height()); @@ -82,19 +94,47 @@ } } +// Allocate and map memory for a bitmap filled with |color|. +FuzzedBitmap AllocateFuzzedBitmap(const gfx::Size& size, SkColor color) { + SharedBitmapId shared_bitmap_id = SharedBitmap::GenerateId(); + std::unique_ptr<base::SharedMemory> shared_memory = + bitmap_allocation::AllocateMappedBitmap(size, RGBA_8888); + + SkBitmap tile; + SkImageInfo info = SkImageInfo::MakeN32Premul(size.width(), size.height()); + tile.installPixels(info, shared_memory->memory(), info.minRowBytes()); + tile.eraseColor(color); + + return FuzzedBitmap(shared_bitmap_id, size, std::move(shared_memory)); +} + } // namespace -CompositorFrame GenerateFuzzedCompositorFrame( - const content::fuzzing::proto::RenderPass& render_pass_spec) { - CompositorFrame frame; +FuzzedBitmap::FuzzedBitmap(SharedBitmapId id, + gfx::Size size, + std::unique_ptr<base::SharedMemory> shared_memory) + : id(id), size(size), shared_memory(std::move(shared_memory)) {} +FuzzedBitmap::~FuzzedBitmap() = default; +FuzzedBitmap::FuzzedBitmap(FuzzedBitmap&& other) = default; - frame.metadata.begin_frame_ack.source_id = BeginFrameArgs::kManualSourceId; - frame.metadata.begin_frame_ack.sequence_number = +FuzzedData::FuzzedData() = default; +FuzzedData::~FuzzedData() = default; +FuzzedData::FuzzedData(FuzzedData&& other) = default; + +FuzzedData GenerateFuzzedCompositorFrame( + const content::fuzzing::proto::RenderPass& render_pass_spec) { + FuzzedData fuzzed_data; + uint32_t allocated_bytes = 0; + + fuzzed_data.frame.metadata.begin_frame_ack.source_id = + BeginFrameArgs::kManualSourceId; + fuzzed_data.frame.metadata.begin_frame_ack.sequence_number = BeginFrameArgs::kStartingFrameNumber; - frame.metadata.begin_frame_ack.has_damage = true; - frame.metadata.frame_token = 1; - frame.metadata.device_scale_factor = 1; - frame.metadata.local_surface_id_allocation_time = base::TimeTicks::Now(); + fuzzed_data.frame.metadata.begin_frame_ack.has_damage = true; + fuzzed_data.frame.metadata.frame_token = 1; + fuzzed_data.frame.metadata.device_scale_factor = 1; + fuzzed_data.frame.metadata.local_surface_id_allocation_time = + base::TimeTicks::Now(); std::unique_ptr<RenderPass> pass = RenderPass::Create(); gfx::Rect rp_output_rect = @@ -111,12 +151,17 @@ pass->SetNew(1, rp_output_rect, rp_damage_rect, gfx::Transform()); for (const auto& quad_spec : render_pass_spec.quad_list()) { + if (quad_spec.quad_case() == + content::fuzzing::proto::DrawQuad::QUAD_NOT_SET) { + continue; + } + gfx::Rect quad_rect = GetRectFromProtobuf(quad_spec.rect()); gfx::Rect quad_visible_rect = GetRectFromProtobuf(quad_spec.visible_rect()); // Handle constraints on DrawQuad: - // Ensure that |quad_rect| has non-zero area and that |quad_visible_rect| is - // contained in |quad_rect|. + // Ensure that |quad_rect| has non-zero area and that |quad_visible_rect| + // is contained in |quad_rect|. ExpandToMinSize(&quad_rect, 1); quad_visible_rect.AdjustToFit(quad_rect); @@ -129,14 +174,62 @@ quad_spec.sqs().is_clipped(), quad_spec.sqs().are_contents_opaque(), Normalize(quad_spec.sqs().opacity()), SkBlendMode::kSrcOver, quad_spec.sqs().sorting_context_id()); - auto* color_quad = pass->CreateAndAppendDrawQuad<SolidColorDrawQuad>(); - color_quad->SetNew(shared_quad_state, quad_rect, quad_visible_rect, - quad_spec.quad().color(), - quad_spec.quad().force_anti_aliasing_off()); + + switch (quad_spec.quad_case()) { + case content::fuzzing::proto::DrawQuad::kSolidColorQuad: { + auto* color_quad = pass->CreateAndAppendDrawQuad<SolidColorDrawQuad>(); + color_quad->SetNew( + shared_quad_state, quad_rect, quad_visible_rect, + quad_spec.solid_color_quad().color(), + quad_spec.solid_color_quad().force_anti_aliasing_off()); + break; + } + case content::fuzzing::proto::DrawQuad::kTileQuad: { + gfx::Size tile_size = + GetSizeFromProtobuf(quad_spec.tile_quad().texture_size()); + + // Skip TileDrawQuads with bitmaps that cannot be allocated (size is 0 + // or would overflow our limit on allocated memory for this + // CompositorFrame.) + uint64_t tile_bytes; + if (!ResourceSizes::MaybeSizeInBytes<uint64_t>(tile_size, RGBA_8888, + &tile_bytes) || + tile_bytes > kMaxMappedMemory - allocated_bytes) { + continue; + } + + FuzzedBitmap fuzzed_bitmap = AllocateFuzzedBitmap( + tile_size, quad_spec.tile_quad().texture_color()); + allocated_bytes += tile_bytes; + + TransferableResource transferable_resource = + TransferableResource::MakeSoftware(fuzzed_bitmap.id, + fuzzed_bitmap.size, RGBA_8888); + + auto* tile_quad = pass->CreateAndAppendDrawQuad<TileDrawQuad>(); + tile_quad->SetNew( + shared_quad_state, quad_rect, quad_visible_rect, + quad_spec.tile_quad().needs_blending(), transferable_resource.id, + gfx::RectF( + GetRectFromProtobuf(quad_spec.tile_quad().tex_coord_rect())), + tile_size, quad_spec.tile_quad().swizzle_contents(), + quad_spec.tile_quad().is_premultiplied(), + quad_spec.tile_quad().nearest_neighbor(), + quad_spec.tile_quad().force_anti_aliasing_off()); + + fuzzed_data.frame.resource_list.push_back(transferable_resource); + fuzzed_data.allocated_bitmaps.push_back(std::move(fuzzed_bitmap)); + + break; + } + case content::fuzzing::proto::DrawQuad::QUAD_NOT_SET: { + NOTREACHED(); + } + } } - frame.render_pass_list.push_back(std::move(pass)); - return frame; + fuzzed_data.frame.render_pass_list.push_back(std::move(pass)); + return fuzzed_data; } } // namespace viz
diff --git a/components/viz/service/compositor_frame_fuzzer/compositor_frame_fuzzer_util.h b/components/viz/service/compositor_frame_fuzzer/compositor_frame_fuzzer_util.h index 633bc08d..51f7bd5 100644 --- a/components/viz/service/compositor_frame_fuzzer/compositor_frame_fuzzer_util.h +++ b/components/viz/service/compositor_frame_fuzzer/compositor_frame_fuzzer_util.h
@@ -5,11 +5,44 @@ #ifndef COMPONENTS_VIZ_SERVICE_COMPOSITOR_FRAME_FUZZER_COMPOSITOR_FRAME_FUZZER_UTIL_H_ #define COMPONENTS_VIZ_SERVICE_COMPOSITOR_FRAME_FUZZER_COMPOSITOR_FRAME_FUZZER_UTIL_H_ +#include <memory> +#include <vector> + #include "components/viz/common/quads/compositor_frame.h" +#include "components/viz/common/resources/bitmap_allocation.h" #include "components/viz/service/compositor_frame_fuzzer/compositor_frame_fuzzer.pb.h" namespace viz { +struct FuzzedBitmap { + FuzzedBitmap(SharedBitmapId id, + gfx::Size size, + std::unique_ptr<base::SharedMemory> shared_memory); + ~FuzzedBitmap(); + + FuzzedBitmap(FuzzedBitmap&& other) noexcept; + FuzzedBitmap& operator=(FuzzedBitmap&& other) = default; + + SharedBitmapId id; + gfx::Size size; + std::unique_ptr<base::SharedMemory> shared_memory; + + DISALLOW_COPY(FuzzedBitmap); +}; + +struct FuzzedData { + FuzzedData(); + ~FuzzedData(); + + FuzzedData(FuzzedData&& other) noexcept; + FuzzedData& operator=(FuzzedData&& other) = default; + + CompositorFrame frame; + std::vector<FuzzedBitmap> allocated_bitmaps; + + DISALLOW_COPY(FuzzedData); +}; + // Converts a fuzzed specification in the form of a RenderPass protobuf message // (as defined in compositor_frame_fuzzer.proto) into a CompositorFrame with a // RenderPass member. @@ -17,7 +50,7 @@ // Performs minimal validation and corrections to ensure that submitting the // frame to a CompositorFrameSink will not result in a mojo deserialization // validation error. -CompositorFrame GenerateFuzzedCompositorFrame( +FuzzedData GenerateFuzzedCompositorFrame( const content::fuzzing::proto::RenderPass& render_pass_spec); } // namespace viz
diff --git a/components/viz/service/compositor_frame_fuzzer/fuzzer_browser_process.cc b/components/viz/service/compositor_frame_fuzzer/fuzzer_browser_process.cc index d6f9f15c..f558826 100644 --- a/components/viz/service/compositor_frame_fuzzer/fuzzer_browser_process.cc +++ b/components/viz/service/compositor_frame_fuzzer/fuzzer_browser_process.cc
@@ -50,13 +50,22 @@ } void FuzzerBrowserProcess::EmbedFuzzedCompositorFrame( - CompositorFrame fuzzed_frame) { + CompositorFrame fuzzed_frame, + std::vector<FuzzedBitmap> allocated_bitmaps) { mojom::CompositorFrameSinkPtr sink_ptr; FakeCompositorFrameSinkClient sink_client; frame_sink_manager_.CreateCompositorFrameSink(kEmbeddedFrameSinkId, mojo::MakeRequest(&sink_ptr), sink_client.BindInterfacePtr()); + for (auto& fuzzed_bitmap : allocated_bitmaps) { + mojo::ScopedSharedBufferHandle handle = + bitmap_allocation::DuplicateAndCloseMappedBitmap( + fuzzed_bitmap.shared_memory.get(), fuzzed_bitmap.size, + ResourceFormat::RGBA_8888); + sink_ptr->DidAllocateSharedBitmap(std::move(handle), fuzzed_bitmap.id); + } + lsi_allocator_.GenerateId(); SurfaceId embedded_surface_id( kEmbeddedFrameSinkId, @@ -70,6 +79,10 @@ root_local_surface_id_, std::move(browser_frame), base::nullopt, 0); display_private_->ForceImmediateDrawAndSwapIfPossible(); + for (auto& fuzzed_bitmap : allocated_bitmaps) { + sink_ptr->DidDeleteSharedBitmap(fuzzed_bitmap.id); + } + base::RunLoop().RunUntilIdle(); // needed to actually run queued messages frame_sink_manager_.DestroyCompositorFrameSink(kEmbeddedFrameSinkId,
diff --git a/components/viz/service/compositor_frame_fuzzer/fuzzer_browser_process.h b/components/viz/service/compositor_frame_fuzzer/fuzzer_browser_process.h index d080d6a..f06a979 100644 --- a/components/viz/service/compositor_frame_fuzzer/fuzzer_browser_process.h +++ b/components/viz/service/compositor_frame_fuzzer/fuzzer_browser_process.h
@@ -5,8 +5,11 @@ #ifndef COMPONENTS_VIZ_SERVICE_COMPOSITOR_FRAME_FUZZER_FUZZER_BROWSER_PROCESS_H_ #define COMPONENTS_VIZ_SERVICE_COMPOSITOR_FRAME_FUZZER_FUZZER_BROWSER_PROCESS_H_ +#include <vector> + #include "components/viz/common/surfaces/frame_sink_id.h" #include "components/viz/common/surfaces/parent_local_surface_id_allocator.h" +#include "components/viz/service/compositor_frame_fuzzer/compositor_frame_fuzzer_util.h" #include "components/viz/service/compositor_frame_fuzzer/fuzzer_software_display_provider.h" #include "components/viz/service/display_embedder/server_shared_bitmap_manager.h" #include "components/viz/service/frame_sinks/frame_sink_manager_impl.h" @@ -31,7 +34,11 @@ // Submits a CompositorFrame to the RootCompositorFrameSinkImpl // with a SolidColorDrawQuad "toolbar" and a SurfaceDrawQuad "renderer frame" // embedding the fuzzed CompositorFrame. - void EmbedFuzzedCompositorFrame(CompositorFrame fuzzed_frame); + // + // |allocated_bitmaps| should contain references to already-allocated memory + // that is referenced by the frame's DrawQuads and |resource_list|. + void EmbedFuzzedCompositorFrame(CompositorFrame fuzzed_frame, + std::vector<FuzzedBitmap> allocated_bitmaps); private: mojom::RootCompositorFrameSinkParamsPtr BuildRootCompositorFrameSinkParams();
diff --git a/components/viz/service/compositor_frame_fuzzer/text_format_seed_corpus/1_quad_renderpass.asciipb b/components/viz/service/compositor_frame_fuzzer/text_format_seed_corpus/1_quad_renderpass.asciipb index 92469d4..4bf77d0 100644 --- a/components/viz/service/compositor_frame_fuzzer/text_format_seed_corpus/1_quad_renderpass.asciipb +++ b/components/viz/service/compositor_frame_fuzzer/text_format_seed_corpus/1_quad_renderpass.asciipb
@@ -24,7 +24,7 @@ width: 620 height: 400 } - quad: { + solid_color_quad: { color: 0xffffffff force_anti_aliasing_off: false }
diff --git a/components/viz/service/compositor_frame_fuzzer/text_format_seed_corpus/2_quad_renderpass.asciipb b/components/viz/service/compositor_frame_fuzzer/text_format_seed_corpus/2_quad_renderpass.asciipb index 6156825..8f0e52b 100644 --- a/components/viz/service/compositor_frame_fuzzer/text_format_seed_corpus/2_quad_renderpass.asciipb +++ b/components/viz/service/compositor_frame_fuzzer/text_format_seed_corpus/2_quad_renderpass.asciipb
@@ -24,7 +24,7 @@ width: 620 height: 400 } - quad: { + solid_color_quad: { color: 0xffffffff force_anti_aliasing_off: false } @@ -73,8 +73,22 @@ width: 620 height: 400 } - quad: { - color: 0xff000000 + tile_quad: { + needs_blending: true + texture_color: 0xff000000 + texture_size: { + width: 620 + height: 400 + } + tex_coord_rect: { + x: 0 + y: 0 + width: 620 + height: 400 + } + swizzle_contents: true + is_premultiplied: true + nearest_neighbor: true force_anti_aliasing_off: true } sqs: {
diff --git a/components/viz/service/compositor_frame_fuzzer/text_format_seed_corpus/solid_color_tiled_background_with_2_quads_on_top.asciipb b/components/viz/service/compositor_frame_fuzzer/text_format_seed_corpus/solid_color_tiled_background_with_2_quads_on_top.asciipb index f6d487a..33f304b 100644 --- a/components/viz/service/compositor_frame_fuzzer/text_format_seed_corpus/solid_color_tiled_background_with_2_quads_on_top.asciipb +++ b/components/viz/service/compositor_frame_fuzzer/text_format_seed_corpus/solid_color_tiled_background_with_2_quads_on_top.asciipb
@@ -24,8 +24,22 @@ width: 100 height: 100 } - quad: { - color: 0xffff0000 + tile_quad: { + needs_blending: false + texture_color: 0xffff0000 + texture_size: { + width: 100 + height: 100 + } + tex_coord_rect: { + x: 0 + y: 0 + width: 100 + height: 100 + } + swizzle_contents: false + is_premultiplied: false + nearest_neighbor: false force_anti_aliasing_off: false } sqs: { @@ -73,7 +87,7 @@ width: 100 height: 100 } - quad: { + solid_color_quad: { color: 0xffffffff force_anti_aliasing_off: false } @@ -122,8 +136,22 @@ width: 256 height: 256 } - quad: { - color: 0xff000000 + tile_quad: { + needs_blending: false + texture_color: 0xff000000 + texture_size: { + width: 256 + height: 256 + } + tex_coord_rect: { + x: 0 + y: 0 + width: 256 + height: 256 + } + swizzle_contents: false + is_premultiplied: false + nearest_neighbor: false force_anti_aliasing_off: false } sqs: { @@ -171,7 +199,7 @@ width: 256 height: 256 } - quad: { + solid_color_quad: { color: 0xff00ff00 force_anti_aliasing_off: false } @@ -220,7 +248,7 @@ width: 108 height: 256 } - quad: { + solid_color_quad: { color: 0xff0000ff force_anti_aliasing_off: false } @@ -269,7 +297,7 @@ width: 256 height: 144 } - quad: { + solid_color_quad: { color: 0xff0000ff force_anti_aliasing_off: false } @@ -318,7 +346,7 @@ width: 256 height: 144 } - quad: { + solid_color_quad: { color: 0xff00ff00 force_anti_aliasing_off: false } @@ -367,7 +395,7 @@ width: 108 height: 144 } - quad: { + solid_color_quad: { color: 0xff000000 force_anti_aliasing_off: false }
diff --git a/components/viz/service/display/skia_renderer.cc b/components/viz/service/display/skia_renderer.cc index aa0f9661..7dc18c3 100644 --- a/components/viz/service/display/skia_renderer.cc +++ b/components/viz/service/display/skia_renderer.cc
@@ -17,6 +17,7 @@ #include "components/viz/common/quads/picture_draw_quad.h" #include "components/viz/common/quads/render_pass_draw_quad.h" #include "components/viz/common/quads/solid_color_draw_quad.h" +#include "components/viz/common/quads/stream_video_draw_quad.h" #include "components/viz/common/quads/texture_draw_quad.h" #include "components/viz/common/quads/tile_draw_quad.h" #include "components/viz/common/quads/yuv_video_draw_quad.h" @@ -508,8 +509,10 @@ case DrawQuad::YUV_VIDEO_CONTENT: DrawYUVVideoQuad(YUVVideoDrawQuad::MaterialCast(quad), &paint); break; - case DrawQuad::INVALID: case DrawQuad::STREAM_VIDEO_CONTENT: + DrawStreamVideoQuad(StreamVideoDrawQuad::MaterialCast(quad), &paint); + break; + case DrawQuad::INVALID: DrawUnsupportedQuad(quad, &paint); NOTREACHED(); break; @@ -703,6 +706,26 @@ current_canvas_->drawImageRect(image, sk_uv_rect, quad_rect, paint); } +void SkiaRenderer::DrawStreamVideoQuad(const StreamVideoDrawQuad* quad, + SkPaint* paint) { + DCHECK(paint); + ScopedSkImageBuilder builder(this, quad->resource_id(), + kUnpremul_SkAlphaType); + const SkImage* image = builder.sk_image(); + if (!image) + return; + gfx::RectF uv_rect = gfx::ScaleRect( + gfx::BoundingRect(quad->uv_top_left, quad->uv_bottom_right), + image->width(), image->height()); + gfx::RectF visible_uv_rect = cc::MathUtil::ScaleRectProportional( + uv_rect, gfx::RectF(quad->rect), gfx::RectF(quad->visible_rect)); + SkRect sk_uv_rect = gfx::RectFToSkRect(visible_uv_rect); + SkRect quad_rect = gfx::RectToSkRect(quad->visible_rect); + // TODO: figure out how to set correct filter quality. + paint->setFilterQuality(kLow_SkFilterQuality); + current_canvas_->drawImageRect(image, sk_uv_rect, quad_rect, paint); +} + void SkiaRenderer::AddTileQuadToBatch(const TileDrawQuad* quad, const gfx::QuadF* draw_region) { gfx::Transform contents_device_transform =
diff --git a/components/viz/service/display/skia_renderer.h b/components/viz/service/display/skia_renderer.h index 2456721..b124b20e 100644 --- a/components/viz/service/display/skia_renderer.h +++ b/components/viz/service/display/skia_renderer.h
@@ -106,6 +106,7 @@ void DrawSolidColorQuad(const SolidColorDrawQuad* quad, SkPaint* paint); void DrawTextureQuad(const TextureDrawQuad* quad, SkPaint* paint); + void DrawStreamVideoQuad(const StreamVideoDrawQuad* quad, SkPaint* paint); bool MustDrawBatchedTileQuads(const DrawQuad* new_quad, const gfx::Transform& content_device_transform, bool apply_transform_and_scissor,
diff --git a/components/viz/service/display/surface_aggregator.cc b/components/viz/service/display/surface_aggregator.cc index 9aa6b7d..cb2797d4 100644 --- a/components/viz/service/display/surface_aggregator.cc +++ b/components/viz/service/display/surface_aggregator.cc
@@ -200,7 +200,8 @@ RenderPass* dest_pass, bool ignore_undamaged, gfx::Rect* damage_rect_in_quad_space, - bool* damage_rect_in_quad_space_valid) { + bool* damage_rect_in_quad_space_valid, + const RoundedCornerInfo& rounded_corner_info) { SurfaceId primary_surface_id = surface_quad->surface_range.end(); // If there's no fallback surface ID available, then simply emit a @@ -210,7 +211,7 @@ manager_->GetLatestInFlightSurface(surface_quad->surface_range); if (!latest_surface || !latest_surface->HasActiveFrame()) { EmitDefaultBackgroundColorQuad(surface_quad, target_transform, clip_rect, - dest_pass); + dest_pass, rounded_corner_info); return; } @@ -226,10 +227,11 @@ gfx::ScaleToEnclosingRect(fallback_rect, scale_ratio, scale_ratio); fallback_rect = gfx::IntersectRects(fallback_rect, surface_quad->rect); - EmitGutterQuadsIfNecessary( - surface_quad->rect, fallback_rect, surface_quad->shared_quad_state, - target_transform, clip_rect, - fallback_frame.metadata.root_background_color, dest_pass); + EmitGutterQuadsIfNecessary(surface_quad->rect, fallback_rect, + surface_quad->shared_quad_state, + target_transform, clip_rect, + fallback_frame.metadata.root_background_color, + dest_pass, rounded_corner_info); } EmitSurfaceContent(latest_surface, parent_device_scale_factor, @@ -237,7 +239,7 @@ surface_quad->visible_rect, target_transform, clip_rect, surface_quad->stretch_content_to_fill_bounds, dest_pass, ignore_undamaged, damage_rect_in_quad_space, - damage_rect_in_quad_space_valid); + damage_rect_in_quad_space_valid, rounded_corner_info); } void SurfaceAggregator::EmitSurfaceContent( @@ -252,7 +254,8 @@ RenderPass* dest_pass, bool ignore_undamaged, gfx::Rect* damage_rect_in_quad_space, - bool* damage_rect_in_quad_space_valid) { + bool* damage_rect_in_quad_space_valid, + const RoundedCornerInfo& rounded_corner_info) { // If this surface's id is already in our referenced set then it creates // a cycle in the graph and should be dropped. SurfaceId surface_id = surface->surface_id(); @@ -323,7 +326,8 @@ combined_transform.ConcatTransform(target_transform); bool merge_pass = base::IsApproximatelyEqual(source_sqs->opacity, 1.f, kOpacityEpsilon) && - copy_requests.empty() && combined_transform.Preserves2dAxisAlignment(); + copy_requests.empty() && combined_transform.Preserves2dAxisAlignment() && + CanMergeRoundedCorner(rounded_corner_info, *render_pass_list.back()); const RenderPassList& referenced_passes = render_pass_list; // TODO(fsamuel): Move this to a separate helper function. @@ -361,7 +365,8 @@ CopyQuadsToPass(source.quad_list, source.shared_quad_state_list, surface->GetActiveFrame().device_scale_factor(), child_to_parent_map, gfx::Transform(), ClipData(), - copy_pass.get(), surface_id, has_surface_damage); + copy_pass.get(), surface_id, has_surface_damage, + RoundedCornerInfo()); // If the render pass has copy requests, or should be cached, or has // moving-pixel filters, or in a moving-pixel surface, we should damage the @@ -415,7 +420,8 @@ CopyQuadsToPass(quads, last_pass.shared_quad_state_list, surface->GetActiveFrame().device_scale_factor(), child_to_parent_map, surface_transform, quads_clip, - dest_pass, surface_id, has_surface_damage); + dest_pass, surface_id, has_surface_damage, + rounded_corner_info); } else { auto* shared_quad_state = CopyAndScaleSharedQuadState( source_sqs, scaled_quad_to_target_transform, target_transform, @@ -425,7 +431,7 @@ gfx::ScaleToEnclosingRect(source_sqs->visible_quad_layer_rect, layer_to_content_scale_x, layer_to_content_scale_y), - clip_rect, dest_pass, has_surface_damage); + clip_rect, dest_pass, has_surface_damage, rounded_corner_info); gfx::Rect scaled_rect(gfx::ScaleToEnclosingRect( source_rect, layer_to_content_scale_x, layer_to_content_scale_y)); @@ -451,14 +457,15 @@ const SurfaceDrawQuad* surface_quad, const gfx::Transform& target_transform, const ClipData& clip_rect, - RenderPass* dest_pass) { + RenderPass* dest_pass, + const RoundedCornerInfo& rounded_corner_info) { // The primary surface is unavailable and there is no fallback // surface specified so create a SolidColorDrawQuad with the default // background color. SkColor background_color = surface_quad->default_background_color; - auto* shared_quad_state = - CopySharedQuadState(surface_quad->shared_quad_state, target_transform, - clip_rect, dest_pass, /*has_surface_damage*/ true); + auto* shared_quad_state = CopySharedQuadState( + surface_quad->shared_quad_state, target_transform, clip_rect, dest_pass, + /*has_surface_damage*/ true, rounded_corner_info); auto* solid_color_quad = dest_pass->CreateAndAppendDrawQuad<SolidColorDrawQuad>(); solid_color_quad->SetNew(shared_quad_state, surface_quad->rect, @@ -472,7 +479,8 @@ const gfx::Transform& target_transform, const ClipData& clip_rect, SkColor background_color, - RenderPass* dest_pass) { + RenderPass* dest_pass, + const RoundedCornerInfo& rounded_corner_info) { bool has_transparent_background = background_color == SK_ColorTRANSPARENT; // If the fallback Surface's active CompositorFrame has a non-transparent @@ -490,7 +498,7 @@ primary_shared_quad_state, primary_shared_quad_state->quad_to_target_transform, target_transform, right_gutter_rect, right_gutter_rect, clip_rect, dest_pass, - /*has_surface_damage*/ true); + /*has_surface_damage*/ true, rounded_corner_info); auto* right_gutter = dest_pass->CreateAndAppendDrawQuad<SolidColorDrawQuad>(); @@ -507,7 +515,7 @@ primary_shared_quad_state, primary_shared_quad_state->quad_to_target_transform, target_transform, bottom_gutter_rect, bottom_gutter_rect, clip_rect, dest_pass, - /*has_surface_damage*/ true); + /*has_surface_damage*/ true, rounded_corner_info); auto* bottom_gutter = dest_pass->CreateAndAppendDrawQuad<SolidColorDrawQuad>(); @@ -562,11 +570,12 @@ const gfx::Transform& target_transform, const ClipData& clip_rect, RenderPass* dest_render_pass, - bool has_surface_damage) { + bool has_surface_damage, + const RoundedCornerInfo& rounded_corner_info) { return CopyAndScaleSharedQuadState( source_sqs, source_sqs->quad_to_target_transform, target_transform, source_sqs->quad_layer_rect, source_sqs->visible_quad_layer_rect, - clip_rect, dest_render_pass, has_surface_damage); + clip_rect, dest_render_pass, has_surface_damage, rounded_corner_info); } SharedQuadState* SurfaceAggregator::CopyAndScaleSharedQuadState( @@ -577,11 +586,13 @@ const gfx::Rect& visible_quad_layer_rect, const ClipData& clip_rect, RenderPass* dest_render_pass, - bool has_surface_damage) { + bool has_surface_damage, + const RoundedCornerInfo& rounded_corner_info) { auto* shared_quad_state = dest_render_pass->CreateAndAppendSharedQuadState(); ClipData new_clip_rect = CalculateClipRect( clip_rect, ClipData(source_sqs->is_clipped, source_sqs->clip_rect), target_transform); + DCHECK(rounded_corner_info.bounds); // target_transform contains any transformation that may exist // between the context that these quads are being copied from (i.e. the @@ -594,11 +605,12 @@ shared_quad_state->SetAll( new_transform, quad_layer_rect, visible_quad_layer_rect, - source_sqs->rounded_corner_bounds, new_clip_rect.rect, - new_clip_rect.is_clipped, source_sqs->are_contents_opaque, - source_sqs->opacity, source_sqs->blend_mode, - source_sqs->sorting_context_id); + *rounded_corner_info.bounds, new_clip_rect.rect, new_clip_rect.is_clipped, + source_sqs->are_contents_opaque, source_sqs->opacity, + source_sqs->blend_mode, source_sqs->sorting_context_id); shared_quad_state->has_surface_damage = has_surface_damage; + shared_quad_state->is_fast_rounded_corner = + rounded_corner_info.is_fast_rounded_corner; return shared_quad_state; } @@ -612,7 +624,8 @@ const ClipData& clip_rect, RenderPass* dest_pass, const SurfaceId& surface_id, - bool has_surface_damage) { + bool has_surface_damage, + const RoundedCornerInfo& parent_rounded_corner_info) { const SharedQuadState* last_copied_source_shared_quad_state = nullptr; // If the current frame has copy requests or cached render passes, then // aggregate the entire thing, as otherwise parts of the copy requests may be @@ -639,7 +652,13 @@ } #endif + RoundedCornerInfo new_rounded_corner_info = parent_rounded_corner_info; for (auto* quad : source_quad_list) { + // Both cannot be set at once. If this happens then a surface is being + // merged when it should not. + DCHECK(quad->shared_quad_state->rounded_corner_bounds.IsEmpty() || + parent_rounded_corner_info.IsEmpty()); + if (quad->material == DrawQuad::SURFACE_CONTENT) { const auto* surface_quad = SurfaceDrawQuad::MaterialCast(quad); // HandleSurfaceQuad may add other shared quad state, so reset the @@ -649,15 +668,26 @@ if (!surface_quad->surface_range.end().is_valid()) continue; - HandleSurfaceQuad(surface_quad, parent_device_scale_factor, - target_transform, clip_rect, dest_pass, - ignore_undamaged, &damage_rect_in_quad_space, - &damage_rect_in_quad_space_valid); + if (parent_rounded_corner_info.IsEmpty()) { + new_rounded_corner_info = + RoundedCornerInfo(&quad->shared_quad_state->rounded_corner_bounds, + quad->shared_quad_state->is_fast_rounded_corner); + } + + HandleSurfaceQuad( + surface_quad, parent_device_scale_factor, target_transform, clip_rect, + dest_pass, ignore_undamaged, &damage_rect_in_quad_space, + &damage_rect_in_quad_space_valid, new_rounded_corner_info); } else { if (quad->shared_quad_state != last_copied_source_shared_quad_state) { - const SharedQuadState* dest_shared_quad_state = - CopySharedQuadState(quad->shared_quad_state, target_transform, - clip_rect, dest_pass, has_surface_damage); + if (parent_rounded_corner_info.IsEmpty()) { + new_rounded_corner_info = RoundedCornerInfo( + &quad->shared_quad_state->rounded_corner_bounds, + quad->shared_quad_state->is_fast_rounded_corner); + } + const SharedQuadState* dest_shared_quad_state = CopySharedQuadState( + quad->shared_quad_state, target_transform, clip_rect, dest_pass, + has_surface_damage, new_rounded_corner_info); last_copied_source_shared_quad_state = quad->shared_quad_state; if (ignore_undamaged) { damage_rect_in_quad_space_valid = CalculateQuadSpaceDamageRect( @@ -763,7 +793,8 @@ CopyQuadsToPass(source.quad_list, source.shared_quad_state_list, frame.device_scale_factor(), child_to_parent_map, gfx::Transform(), ClipData(), copy_pass.get(), - surface->surface_id(), has_surface_damage); + surface->surface_id(), has_surface_damage, + RoundedCornerInfo()); // If the render pass has copy requests, or should be cached, or has // moving-pixel filters, or in a moving-pixel surface, we should damage the @@ -1131,6 +1162,28 @@ } } +bool SurfaceAggregator::CanMergeRoundedCorner( + const RoundedCornerInfo& rounded_corner_info, + const RenderPass& root_render_pass) { + // If the quad has no rounded corner, then we do not have to block merging. + if (rounded_corner_info.IsEmpty()) + return true; + + // If the quad has rounded corner and it is not a fast rounded corner, we + // cannot merge. + if (!rounded_corner_info.is_fast_rounded_corner) + return false; + + // If any of the quads in the root render pass has a rounded corner of its + // own, then we cannot merge. + const SharedQuadStateList& sqs_list = root_render_pass.shared_quad_state_list; + for (const auto* sqs : sqs_list) { + if (!sqs->rounded_corner_bounds.IsEmpty()) + return false; + } + return true; +} + CompositorFrame SurfaceAggregator::Aggregate( const SurfaceId& surface_id, base::TimeTicks expected_display_time,
diff --git a/components/viz/service/display/surface_aggregator.h b/components/viz/service/display/surface_aggregator.h index d692e75..6ff8f31f 100644 --- a/components/viz/service/display/surface_aggregator.h +++ b/components/viz/service/display/surface_aggregator.h
@@ -87,6 +87,16 @@ bool in_use = true; }; + struct RoundedCornerInfo { + RoundedCornerInfo() : bounds(nullptr), is_fast_rounded_corner(false) {} + RoundedCornerInfo(const gfx::RRectF* bounds, bool is_fast_rounded_corner) + : bounds(bounds), is_fast_rounded_corner(is_fast_rounded_corner) {} + + bool IsEmpty() const { return !bounds || bounds->IsEmpty(); } + const gfx::RRectF* bounds; + bool is_fast_rounded_corner; + }; + ClipData CalculateClipRect(const ClipData& surface_clip, const ClipData& quad_clip, const gfx::Transform& target_transform); @@ -101,7 +111,8 @@ RenderPass* dest_pass, bool ignore_undamaged, gfx::Rect* damage_rect_in_quad_space, - bool* damage_rect_in_quad_space_valid); + bool* damage_rect_in_quad_space_valid, + const RoundedCornerInfo& rounded_corner_info); void EmitSurfaceContent(Surface* surface, float parent_device_scale_factor, @@ -114,12 +125,15 @@ RenderPass* dest_pass, bool ignore_undamaged, gfx::Rect* damage_rect_in_quad_space, - bool* damage_rect_in_quad_space_valid); + bool* damage_rect_in_quad_space_valid, + const RoundedCornerInfo& rounded_corner_info); - void EmitDefaultBackgroundColorQuad(const SurfaceDrawQuad* surface_quad, - const gfx::Transform& target_transform, - const ClipData& clip_rect, - RenderPass* dest_pass); + void EmitDefaultBackgroundColorQuad( + const SurfaceDrawQuad* surface_quad, + const gfx::Transform& target_transform, + const ClipData& clip_rect, + RenderPass* dest_pass, + const RoundedCornerInfo& rounded_corner_info); void EmitGutterQuadsIfNecessary( const gfx::Rect& primary_rect, @@ -128,13 +142,16 @@ const gfx::Transform& target_transform, const ClipData& clip_rect, SkColor background_color, - RenderPass* dest_pass); + RenderPass* dest_pass, + const RoundedCornerInfo& rounded_corner_info); - SharedQuadState* CopySharedQuadState(const SharedQuadState* source_sqs, - const gfx::Transform& target_transform, - const ClipData& clip_rect, - RenderPass* dest_render_pass, - bool has_surface_damage); + SharedQuadState* CopySharedQuadState( + const SharedQuadState* source_sqs, + const gfx::Transform& target_transform, + const ClipData& clip_rect, + RenderPass* dest_render_pass, + bool has_surface_damage, + const RoundedCornerInfo& rounded_corner_info); SharedQuadState* CopyAndScaleSharedQuadState( const SharedQuadState* source_sqs, @@ -144,7 +161,8 @@ const gfx::Rect& visible_quad_layer_rect, const ClipData& clip_rect, RenderPass* dest_render_pass, - bool has_surface_damage); + bool has_surface_damage, + const RoundedCornerInfo& rounded_corner_info); void CopyQuadsToPass( const QuadList& source_quad_list, @@ -155,7 +173,8 @@ const ClipData& clip_rect, RenderPass* dest_pass, const SurfaceId& surface_id, - bool has_surface_damage); + bool has_surface_damage, + const RoundedCornerInfo& rounded_corner_info); gfx::Rect PrewalkTree(Surface* surface, bool in_moved_pixel_surface, int parent_pass, @@ -173,6 +192,11 @@ void PropagateCopyRequestPasses(); + // Returns true if the quad list from the render pass provided can be merged + // with its target render pass based on rounded corners. + bool CanMergeRoundedCorner(const RoundedCornerInfo& rounded_corner_info, + const RenderPass& root_render_pass); + int ChildIdForSurface(Surface* surface); bool IsSurfaceFrameIndexSameAsPrevious(const Surface* surface) const; gfx::Rect DamageRectForSurface(const Surface* surface,
diff --git a/components/viz/service/display/surface_aggregator_unittest.cc b/components/viz/service/display/surface_aggregator_unittest.cc index 83bd96e2..a9c8b51 100644 --- a/components/viz/service/display/surface_aggregator_unittest.cc +++ b/components/viz/service/display/surface_aggregator_unittest.cc
@@ -2142,11 +2142,12 @@ void AddSolidColorQuadWithBlendMode(const gfx::Size& size, RenderPass* pass, - const SkBlendMode blend_mode) { + const SkBlendMode blend_mode, + const gfx::RRectF& corner_bounds) { const gfx::Transform layer_to_target_transform; const gfx::Rect layer_rect(size); const gfx::Rect visible_layer_rect(size); - const gfx::RRectF rounded_corner_bounds = gfx::RRectF(); + const gfx::RRectF rounded_corner_bounds = corner_bounds; const gfx::Rect clip_rect(size); bool is_clipped = false; @@ -2230,7 +2231,7 @@ grandchild_pass->SetNew(pass_id, output_rect, damage_rect, transform_to_root_target); AddSolidColorQuadWithBlendMode(SurfaceSize(), grandchild_pass.get(), - blend_modes[2]); + blend_modes[2], gfx::RRectF()); QueuePassAsFrame(std::move(grandchild_pass), grandchild_local_surface_id, device_scale_factor, grandchild_support.get()); @@ -2245,7 +2246,7 @@ child_one_pass->SetNew(pass_id, output_rect, damage_rect, transform_to_root_target); AddSolidColorQuadWithBlendMode(SurfaceSize(), child_one_pass.get(), - blend_modes[1]); + blend_modes[1], gfx::RRectF()); auto* grandchild_surface_quad = child_one_pass->CreateAndAppendDrawQuad<SurfaceDrawQuad>(); grandchild_surface_quad->SetNew( @@ -2254,7 +2255,7 @@ SurfaceRange(base::nullopt, grandchild_surface_id), SK_ColorWHITE, /*stretch_content_to_fill_bounds=*/false, /*ignores_input_event=*/false); AddSolidColorQuadWithBlendMode(SurfaceSize(), child_one_pass.get(), - blend_modes[3]); + blend_modes[3], gfx::RRectF()); QueuePassAsFrame(std::move(child_one_pass), child_one_local_surface_id, device_scale_factor, child_one_support.get()); @@ -2269,7 +2270,7 @@ child_two_pass->SetNew(pass_id, output_rect, damage_rect, transform_to_root_target); AddSolidColorQuadWithBlendMode(SurfaceSize(), child_two_pass.get(), - blend_modes[5]); + blend_modes[5], gfx::RRectF()); QueuePassAsFrame(std::move(child_two_pass), child_two_local_surface_id, device_scale_factor, child_two_support.get()); @@ -2277,8 +2278,8 @@ root_pass->SetNew(pass_id, output_rect, damage_rect, transform_to_root_target); - AddSolidColorQuadWithBlendMode(SurfaceSize(), root_pass.get(), - blend_modes[0]); + AddSolidColorQuadWithBlendMode(SurfaceSize(), root_pass.get(), blend_modes[0], + gfx::RRectF()); auto* child_one_surface_quad = root_pass->CreateAndAppendDrawQuad<SurfaceDrawQuad>(); child_one_surface_quad->SetNew( @@ -2286,8 +2287,8 @@ gfx::Rect(SurfaceSize()), SurfaceRange(base::nullopt, child_one_surface_id), SK_ColorWHITE, /*stretch_content_to_fill_bounds=*/false, /*ignores_input_event=*/false); - AddSolidColorQuadWithBlendMode(SurfaceSize(), root_pass.get(), - blend_modes[4]); + AddSolidColorQuadWithBlendMode(SurfaceSize(), root_pass.get(), blend_modes[4], + gfx::RRectF()); auto* child_two_surface_quad = root_pass->CreateAndAppendDrawQuad<SurfaceDrawQuad>(); child_two_surface_quad->SetNew( @@ -2295,8 +2296,8 @@ gfx::Rect(SurfaceSize()), SurfaceRange(base::nullopt, child_two_surface_id), SK_ColorWHITE, /*stretch_content_to_fill_bounds=*/false, /*ignores_input_event=*/false); - AddSolidColorQuadWithBlendMode(SurfaceSize(), root_pass.get(), - blend_modes[6]); + AddSolidColorQuadWithBlendMode(SurfaceSize(), root_pass.get(), blend_modes[6], + gfx::RRectF()); QueuePassAsFrame(std::move(root_pass), root_local_surface_id_, device_scale_factor, root_sink_.get()); @@ -2321,6 +2322,211 @@ } } +// This tests that we update shared quad state pointers for rounded corner +// bounds correctly within aggregated passes. In case of fast rounded corners, +// the surface aggregator tries to optimize by merging the the surface quads +// instead of keeping the surface render pass. +// +// This test has 4 surfaces in the following structure: +// root_surface -> [child_root_surface] has fast rounded corner [1], +// child_root_surface -> [child_one_surface], +// [child_two_surface], +// quad (a), +// child_one_surface -> quad (b), +// [child three surface], +// child_two_surface -> quad (c), +// -> quad (d) has rounded corner [2] +// child_three_surface -> quad (e), +// +// Resulting in the following aggregated pass: +// Root Pass: +// quad (b) - rounded corner [1] +// quad (e) - rounded corner [1] +// render pass quad - rounded corner [1] +// quad (a) - rounded corner [1] +// Render pass for child two surface: +// quad (c) - no rounded corner on sqs +// quad(d) - rounded corner [2] +TEST_F(SurfaceAggregatorValidSurfaceTest, + AggregateSharedQuadStateRoundedCornerBounds) { + const gfx::RRectF kFastRoundedCornerBounds = gfx::RRectF(0, 0, 640, 480, 5); + const gfx::RRectF kRoundedCornerBounds = gfx::RRectF(0, 0, 100, 100, 2); + + ParentLocalSurfaceIdAllocator child_root_allocator; + ParentLocalSurfaceIdAllocator child_one_allocator; + ParentLocalSurfaceIdAllocator child_two_allocator; + ParentLocalSurfaceIdAllocator child_three_allocator; + auto child_root_support = std::make_unique<CompositorFrameSinkSupport>( + nullptr, &manager_, kArbitraryFrameSinkId1, kChildIsRoot, + kNeedsSyncPoints); + auto child_one_support = std::make_unique<CompositorFrameSinkSupport>( + nullptr, &manager_, kArbitraryFrameSinkId2, kChildIsRoot, + kNeedsSyncPoints); + auto child_two_support = std::make_unique<CompositorFrameSinkSupport>( + nullptr, &manager_, kArbitraryMiddleFrameSinkId, kChildIsRoot, + kNeedsSyncPoints); + auto child_three_support = std::make_unique<CompositorFrameSinkSupport>( + nullptr, &manager_, kArbitraryFrameSinkId3, kChildIsRoot, + kNeedsSyncPoints); + int pass_id = 1; + + gfx::Rect output_rect(SurfaceSize()); + gfx::Rect damage_rect(SurfaceSize()); + constexpr float device_scale_factor = 1.0f; + gfx::Transform transform_to_root_target; + + // Setup childe three surface. + child_three_allocator.GenerateId(); + LocalSurfaceId child_three_local_surface_id = + child_three_allocator.GetCurrentLocalSurfaceIdAllocation() + .local_surface_id(); + SurfaceId child_three_surface_id(child_three_support->frame_sink_id(), + child_three_local_surface_id); + + auto child_three_pass = RenderPass::Create(); + child_three_pass->SetNew(pass_id, output_rect, damage_rect, + transform_to_root_target); + AddSolidColorQuadWithBlendMode(SurfaceSize(), child_three_pass.get(), + SkBlendMode::kSrcOver, gfx::RRectF()); + QueuePassAsFrame(std::move(child_three_pass), child_three_local_surface_id, + device_scale_factor, child_three_support.get()); + + // Setup Child one surface + child_one_allocator.GenerateId(); + LocalSurfaceId child_one_local_surface_id = + child_one_allocator.GetCurrentLocalSurfaceIdAllocation() + .local_surface_id(); + SurfaceId child_one_surface_id(child_one_support->frame_sink_id(), + child_one_local_surface_id); + + auto child_one_pass = RenderPass::Create(); + child_one_pass->SetNew(pass_id, output_rect, damage_rect, + transform_to_root_target); + AddSolidColorQuadWithBlendMode(SurfaceSize(), child_one_pass.get(), + SkBlendMode::kSrcOver, gfx::RRectF()); + + // Add child three surface quad + auto* child_three_surface_sqs = + child_one_pass->CreateAndAppendSharedQuadState(); + child_three_surface_sqs->opacity = 1.f; + auto* child_three_surface_quad = + child_one_pass->CreateAndAppendDrawQuad<SurfaceDrawQuad>(); + child_three_surface_quad->SetNew( + child_three_surface_sqs, gfx::Rect(SurfaceSize()), + gfx::Rect(SurfaceSize()), + SurfaceRange(base::nullopt, child_three_surface_id), SK_ColorWHITE, + /*stretch_content_to_fill_bounds=*/false, /*ignores_input_event=*/false); + + QueuePassAsFrame(std::move(child_one_pass), child_one_local_surface_id, + device_scale_factor, child_one_support.get()); + + // Setup child two surface + child_two_allocator.GenerateId(); + LocalSurfaceId child_two_local_surface_id = + child_two_allocator.GetCurrentLocalSurfaceIdAllocation() + .local_surface_id(); + SurfaceId child_two_surface_id(child_two_support->frame_sink_id(), + child_two_local_surface_id); + + auto child_two_pass = RenderPass::Create(); + child_two_pass->SetNew(pass_id, output_rect, damage_rect, + transform_to_root_target); + AddSolidColorQuadWithBlendMode(SurfaceSize(), child_two_pass.get(), + SkBlendMode::kSrcOver, gfx::RRectF()); + AddSolidColorQuadWithBlendMode(SurfaceSize(), child_two_pass.get(), + SkBlendMode::kSrcOver, kRoundedCornerBounds); + QueuePassAsFrame(std::move(child_two_pass), child_two_local_surface_id, + device_scale_factor, child_two_support.get()); + + // Setup child root surface + child_root_allocator.GenerateId(); + LocalSurfaceId child_root_local_surface_id = + child_root_allocator.GetCurrentLocalSurfaceIdAllocation() + .local_surface_id(); + SurfaceId child_root_surface_id(child_root_support->frame_sink_id(), + child_root_local_surface_id); + + auto child_root_pass = RenderPass::Create(); + child_root_pass->SetNew(pass_id, output_rect, damage_rect, + transform_to_root_target); + + // Add child one surface quad + auto* child_one_surface_sqs = + child_root_pass->CreateAndAppendSharedQuadState(); + child_one_surface_sqs->opacity = 1.f; + auto* child_one_surface_quad = + child_root_pass->CreateAndAppendDrawQuad<SurfaceDrawQuad>(); + child_one_surface_quad->SetNew( + child_one_surface_sqs, gfx::Rect(SurfaceSize()), gfx::Rect(SurfaceSize()), + SurfaceRange(base::nullopt, child_one_surface_id), SK_ColorWHITE, + /*stretch_content_to_fill_bounds=*/false, /*ignores_input_event=*/false); + + // Add child two surface quad + auto* child_two_surface_sqs = + child_root_pass->CreateAndAppendSharedQuadState(); + child_two_surface_sqs->opacity = 1.f; + auto* child_two_surface_quad = + child_root_pass->CreateAndAppendDrawQuad<SurfaceDrawQuad>(); + child_two_surface_quad->SetNew( + child_two_surface_sqs, gfx::Rect(SurfaceSize()), gfx::Rect(SurfaceSize()), + SurfaceRange(base::nullopt, child_two_surface_id), SK_ColorWHITE, + /*stretch_content_to_fill_bounds=*/false, /*ignores_input_event=*/false); + + // Add solid color quad + AddSolidColorQuadWithBlendMode(SurfaceSize(), child_root_pass.get(), + SkBlendMode::kSrcOver, gfx::RRectF()); + QueuePassAsFrame(std::move(child_root_pass), child_root_local_surface_id, + device_scale_factor, child_root_support.get()); + + auto root_pass = RenderPass::Create(); + root_pass->SetNew(pass_id, output_rect, damage_rect, + transform_to_root_target); + + auto* child_root_surface_sqs = root_pass->CreateAndAppendSharedQuadState(); + auto* child_root_surface_quad = + root_pass->CreateAndAppendDrawQuad<SurfaceDrawQuad>(); + child_root_surface_sqs->opacity = 1.f; + child_root_surface_sqs->rounded_corner_bounds = kFastRoundedCornerBounds; + child_root_surface_sqs->is_fast_rounded_corner = true; + child_root_surface_quad->SetNew( + child_root_surface_sqs, gfx::Rect(SurfaceSize()), + gfx::Rect(SurfaceSize()), + SurfaceRange(base::nullopt, child_root_surface_id), SK_ColorWHITE, + /*stretch_content_to_fill_bounds=*/false, /*ignores_input_event=*/false); + + QueuePassAsFrame(std::move(root_pass), root_local_surface_id_, + device_scale_factor, root_sink_.get()); + + SurfaceId root_surface_id(root_sink_->frame_sink_id(), + root_local_surface_id_); + CompositorFrame aggregated_frame = + aggregator_.Aggregate(root_surface_id, GetNextDisplayTimeAndIncrement()); + + const auto& aggregated_pass_list = aggregated_frame.render_pass_list; + + // There should be 2 render pass since one of the surface quad qould reject + // merging due to it having a quad with a rounded corner of its own. + EXPECT_EQ(2u, aggregated_pass_list.size()); + + // The surface quad which has a render pass of its own, will have 2 quads. + // One of them will have the rounded corner set on it. + const auto& aggregated_quad_list_of_surface = + aggregated_pass_list[0]->quad_list; + EXPECT_EQ(2u, aggregated_quad_list_of_surface.size()); + EXPECT_EQ(kRoundedCornerBounds, + aggregated_quad_list_of_surface.back() + ->shared_quad_state->rounded_corner_bounds); + + // The root render pass will have all the remaining quads with the rounded + // corner set on them. + const auto& aggregated_quad_list_of_root = aggregated_pass_list[1]->quad_list; + EXPECT_EQ(4u, aggregated_quad_list_of_root.size()); + for (const auto* q : aggregated_quad_list_of_root) { + EXPECT_EQ(q->shared_quad_state->rounded_corner_bounds, + kFastRoundedCornerBounds); + } +} + // This tests that when aggregating a frame with multiple render passes that we // map the transforms for the root pass but do not modify the transform on child // passes.
diff --git a/components/viz/service/display_embedder/skia_output_surface_impl_non_ddl.cc b/components/viz/service/display_embedder/skia_output_surface_impl_non_ddl.cc index cdcc403..444b0d7e 100644 --- a/components/viz/service/display_embedder/skia_output_surface_impl_non_ddl.cc +++ b/components/viz/service/display_embedder/skia_output_surface_impl_non_ddl.cc
@@ -14,6 +14,7 @@ #include "components/viz/common/frame_sinks/begin_frame_source.h" #include "components/viz/common/frame_sinks/copy_output_request.h" #include "components/viz/common/gpu/context_lost_observer.h" +#include "components/viz/common/gpu/vulkan_context_provider.h" #include "components/viz/common/resources/resource_format_utils.h" #include "components/viz/service/display/output_surface_client.h" #include "components/viz/service/display/output_surface_frame.h" @@ -26,6 +27,7 @@ #include "gpu/command_buffer/service/skia_utils.h" #include "gpu/command_buffer/service/sync_point_manager.h" #include "gpu/command_buffer/service/texture_base.h" +#include "gpu/vulkan/buildflags.h" #include "third_party/skia/include/core/SkPromiseImageTexture.h" #include "third_party/skia/include/core/SkYUVAIndex.h" #include "ui/gfx/skia_util.h" @@ -35,6 +37,10 @@ #include "ui/gl/gl_surface.h" #include "ui/gl/gl_version_info.h" +#if BUILDFLAG(ENABLE_VULKAN) +#include "third_party/skia/src/gpu/vk/GrVkSecondaryCBDrawContext.h" +#endif + namespace viz { namespace { @@ -128,30 +134,36 @@ reshape_has_alpha_ = has_alpha; reshape_use_stencil_ = use_stencil; - // Conversion to GLSurface's color space follows the same logic as in - // gl::GetGLColorSpace(). - gl::GLSurface::ColorSpace surface_color_space = - color_space.IsHDR() ? gl::GLSurface::ColorSpace::SCRGB_LINEAR - : gl::GLSurface::ColorSpace::UNSPECIFIED; - gl_surface_->Resize(size, device_scale_factor, surface_color_space, - has_alpha); + const bool is_using_vulkan = shared_context_state_->use_vulkan_gr_context(); + if (is_using_vulkan) { + auto* context_provider = shared_context_state_->vk_context_provider(); + DCHECK(context_provider->GetGrSecondaryCBDrawContext()); + } else { + // Conversion to GLSurface's color space follows the same logic as in + // gl::GetGLColorSpace(). + gl::GLSurface::ColorSpace surface_color_space = + color_space.IsHDR() ? gl::GLSurface::ColorSpace::SCRGB_LINEAR + : gl::GLSurface::ColorSpace::UNSPECIFIED; + gl_surface_->Resize(size, device_scale_factor, surface_color_space, + has_alpha); - backing_framebuffer_object_ = gl_surface_->GetBackingFramebufferObject(); + backing_framebuffer_object_ = gl_surface_->GetBackingFramebufferObject(); - SkSurfaceProps surface_props = - SkSurfaceProps(0, SkSurfaceProps::kLegacyFontHost_InitType); + SkSurfaceProps surface_props = + SkSurfaceProps(0, SkSurfaceProps::kLegacyFontHost_InitType); - GrGLFramebufferInfo framebuffer_info; - framebuffer_info.fFBOID = backing_framebuffer_object_; - framebuffer_info.fFormat = GL_RGBA8; + GrGLFramebufferInfo framebuffer_info; + framebuffer_info.fFBOID = backing_framebuffer_object_; + framebuffer_info.fFormat = GL_RGBA8; - GrBackendRenderTarget render_target(size.width(), size.height(), 0, 8, - framebuffer_info); + GrBackendRenderTarget render_target(size.width(), size.height(), 0, 8, + framebuffer_info); - sk_surface_ = SkSurface::MakeFromBackendRenderTarget( - gr_context(), render_target, kBottomLeft_GrSurfaceOrigin, - kRGBA_8888_SkColorType, color_space.ToSkColorSpace(), &surface_props); - DCHECK(sk_surface_); + sk_surface_ = SkSurface::MakeFromBackendRenderTarget( + gr_context(), render_target, kBottomLeft_GrSurfaceOrigin, + kRGBA_8888_SkColorType, color_space.ToSkColorSpace(), &surface_props); + DCHECK(sk_surface_); + } } void SkiaOutputSurfaceImplNonDDL::SwapBuffers(OutputSurfaceFrame frame) { @@ -203,20 +215,35 @@ SkCanvas* SkiaOutputSurfaceImplNonDDL::BeginPaintCurrentFrame() { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); - DCHECK(sk_surface_); DCHECK_EQ(current_render_pass_id_, 0u); DCHECK_EQ(order_num_, 0u); order_num_ = sync_point_order_data_->GenerateUnprocessedOrderNumber(); sync_point_order_data_->BeginProcessingOrderNumber(order_num_); - // If FBO is changed, we need call Reshape() to recreate |sk_surface_|. - if (backing_framebuffer_object_ != - gl_surface_->GetBackingFramebufferObject()) { - Reshape(reshape_surface_size_, reshape_device_scale_factor_, - reshape_color_space_, reshape_has_alpha_, reshape_use_stencil_); - } + const bool is_using_vulkan = shared_context_state_->use_vulkan_gr_context(); - return sk_surface_->getCanvas(); + if (is_using_vulkan) { +#if BUILDFLAG(ENABLE_VULKAN) + DCHECK(!draw_context_); + draw_context_ = shared_context_state_->vk_context_provider() + ->GetGrSecondaryCBDrawContext(); + DCHECK(draw_context_); + return draw_context_->getCanvas(); +#else + NOTREACHED(); + return nullptr; +#endif + } else { + DCHECK(sk_surface_); + // If FBO is changed, we need call Reshape() to recreate |sk_surface_|. + if (backing_framebuffer_object_ != + gl_surface_->GetBackingFramebufferObject()) { + Reshape(reshape_surface_size_, reshape_device_scale_factor_, + reshape_color_space_, reshape_has_alpha_, reshape_use_stencil_); + } + + return sk_surface_->getCanvas(); + } } sk_sp<SkImage> SkiaOutputSurfaceImplNonDDL::MakePromiseSkImage( @@ -366,7 +393,18 @@ DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); if (current_render_pass_id_ == 0) { - sk_surface_->flush(); + const bool is_using_vulkan = shared_context_state_->use_vulkan_gr_context(); + if (is_using_vulkan) { +#if BUILDFLAG(ENABLE_VULKAN) + DCHECK(draw_context_); + draw_context_->flush(); + draw_context_ = nullptr; +#else + NOTREACHED(); +#endif + } else { + sk_surface_->flush(); + } } else { offscreen_sk_surfaces_[current_render_pass_id_]->flush(); } @@ -375,8 +413,11 @@ sync_point_client_state_->command_buffer_id(), ++sync_fence_release_); sync_token.SetVerifyFlush(); sync_point_client_state_->ReleaseFenceSync(sync_fence_release_); - DCHECK(mailbox_manager_->UsesSync()); - mailbox_manager_->PushTextureUpdates(sync_token); + const bool is_using_vulkan = shared_context_state_->use_vulkan_gr_context(); + if (!is_using_vulkan) { + DCHECK(mailbox_manager_->UsesSync()); + mailbox_manager_->PushTextureUpdates(sync_token); + } DCHECK_NE(order_num_, 0u); sync_point_order_data_->FinishProcessingOrderNumber(order_num_); order_num_ = 0u; @@ -486,8 +527,11 @@ GrBackendTexture* backend_texture) { DCHECK(!metadata.mailbox_holder.mailbox.IsZero()); if (WaitSyncToken(metadata.mailbox_holder.sync_token)) { - DCHECK(mailbox_manager_->UsesSync()); - mailbox_manager_->PullTextureUpdates(metadata.mailbox_holder.sync_token); + const bool is_using_vulkan = shared_context_state_->use_vulkan_gr_context(); + if (!is_using_vulkan) { + DCHECK(mailbox_manager_->UsesSync()); + mailbox_manager_->PullTextureUpdates(metadata.mailbox_holder.sync_token); + } } auto* texture_base =
diff --git a/components/viz/service/display_embedder/skia_output_surface_impl_non_ddl.h b/components/viz/service/display_embedder/skia_output_surface_impl_non_ddl.h index 3bb3e957..80cf1df 100644 --- a/components/viz/service/display_embedder/skia_output_surface_impl_non_ddl.h +++ b/components/viz/service/display_embedder/skia_output_surface_impl_non_ddl.h
@@ -17,6 +17,11 @@ #include "components/viz/service/viz_service_export.h" #include "gpu/command_buffer/common/sync_token.h" #include "gpu/command_buffer/service/shared_context_state.h" +#include "gpu/vulkan/buildflags.h" + +#if BUILDFLAG(ENABLE_VULKAN) +class GrVkSecondaryCBDrawContext; +#endif namespace gfx { struct PresentationFeedback; @@ -148,6 +153,11 @@ // The SkSurface for the framebuffer. sk_sp<SkSurface> sk_surface_; +#if BUILDFLAG(ENABLE_VULKAN) + // The |draw_context_| for the current frame. + GrVkSecondaryCBDrawContext* draw_context_ = nullptr; +#endif + // Offscreen SkSurfaces for render passes. base::flat_map<RenderPassId, sk_sp<SkSurface>> offscreen_sk_surfaces_;
diff --git a/components/viz/service/frame_sinks/frame_sink_manager_impl.cc b/components/viz/service/frame_sinks/frame_sink_manager_impl.cc index 96e240aa..a4637ab 100644 --- a/components/viz/service/frame_sinks/frame_sink_manager_impl.cc +++ b/components/viz/service/frame_sinks/frame_sink_manager_impl.cc
@@ -229,7 +229,7 @@ mapping.children.erase(child_frame_sink_id); // Delete the FrameSinkSourceMapping for |parent_frame_sink_id| if empty. - if (!mapping.has_children() && !mapping.source) { + if (mapping.children.empty() && !mapping.source) { frame_sink_source_map_.erase(iter); return; } @@ -470,7 +470,7 @@ } // Delete the FrameSinkSourceMapping for |frame_sink_id| if empty. - if (!mapping.has_children()) { + if (mapping.children.empty()) { frame_sink_source_map_.erase(iter); return; }
diff --git a/components/viz/service/frame_sinks/frame_sink_manager_impl.h b/components/viz/service/frame_sinks/frame_sink_manager_impl.h index 9d2647b..6925b56a3 100644 --- a/components/viz/service/frame_sinks/frame_sink_manager_impl.h +++ b/components/viz/service/frame_sinks/frame_sink_manager_impl.h
@@ -228,7 +228,6 @@ ~FrameSinkSourceMapping(); FrameSinkSourceMapping& operator=(FrameSinkSourceMapping&& other); - bool has_children() const { return !children.empty(); } // The currently assigned begin frame source for this client. BeginFrameSource* source = nullptr; // This represents a dag of parent -> children mapping.
diff --git a/content/browser/BUILD.gn b/content/browser/BUILD.gn index 4994ea7..bda4857 100644 --- a/content/browser/BUILD.gn +++ b/content/browser/BUILD.gn
@@ -1792,6 +1792,8 @@ "tracing/background_memory_tracing_observer.h", "tracing/background_startup_tracing_observer.cc", "tracing/background_startup_tracing_observer.h", + "tracing/background_tracing_active_scenario.cc", + "tracing/background_tracing_active_scenario.h", "tracing/background_tracing_config_impl.cc", "tracing/background_tracing_config_impl.h", "tracing/background_tracing_manager_impl.cc",
diff --git a/content/browser/accessibility/browser_accessibility_com_win.cc b/content/browser/accessibility/browser_accessibility_com_win.cc index ed7bad1..e7ffee00 100644 --- a/content/browser/accessibility/browser_accessibility_com_win.cc +++ b/content/browser/accessibility/browser_accessibility_com_win.cc
@@ -6,6 +6,8 @@ #include <algorithm> #include <iterator> +#include <map> +#include <string> #include <utility> #include "base/strings/string_number_conversions.h" @@ -1066,7 +1068,7 @@ } IFACEMETHODIMP -BrowserAccessibilityComWin::get_nameSpaceURIForID(short name_space_id, +BrowserAccessibilityComWin::get_nameSpaceURIForID(SHORT name_space_id, BSTR* name_space_uri) { WIN_ACCESSIBILITY_API_HISTOGRAM(UMA_API_GET_NAMESPACE_URI_FOR_ID); return E_NOTIMPL; @@ -1085,11 +1087,11 @@ IFACEMETHODIMP BrowserAccessibilityComWin::get_nodeInfo( BSTR* node_name, - short* name_space_id, + SHORT* name_space_id, BSTR* node_value, unsigned int* num_children, unsigned int* unique_id, - unsigned short* node_type) { + USHORT* node_type) { WIN_ACCESSIBILITY_API_HISTOGRAM(UMA_API_GET_NODE_INFO); AddAccessibilityModeFlags(kScreenReaderAndHTMLAccessibilityModes); if (!owner()) @@ -1122,12 +1124,11 @@ return S_OK; } -IFACEMETHODIMP BrowserAccessibilityComWin::get_attributes( - unsigned short max_attribs, - BSTR* attrib_names, - short* name_space_id, - BSTR* attrib_values, - unsigned short* num_attribs) { +IFACEMETHODIMP BrowserAccessibilityComWin::get_attributes(USHORT max_attribs, + BSTR* attrib_names, + SHORT* name_space_id, + BSTR* attrib_values, + USHORT* num_attribs) { WIN_ACCESSIBILITY_API_HISTOGRAM(UMA_API_ISIMPLEDOMNODE_GET_ATTRIBUTES); AddAccessibilityModeFlags(kScreenReaderAndHTMLAccessibilityModes); if (!owner()) @@ -1140,7 +1141,7 @@ if (*num_attribs > owner()->GetHtmlAttributes().size()) *num_attribs = owner()->GetHtmlAttributes().size(); - for (unsigned short i = 0; i < *num_attribs; ++i) { + for (USHORT i = 0; i < *num_attribs; ++i) { attrib_names[i] = SysAllocString( base::UTF8ToUTF16(owner()->GetHtmlAttributes()[i].first).c_str()); name_space_id[i] = 0; @@ -1151,9 +1152,9 @@ } IFACEMETHODIMP BrowserAccessibilityComWin::get_attributesForNames( - unsigned short num_attribs, + USHORT num_attribs, BSTR* attrib_names, - short* name_space_id, + SHORT* name_space_id, BSTR* attrib_values) { WIN_ACCESSIBILITY_API_HISTOGRAM(UMA_API_GET_ATTRIBUTES_FOR_NAMES); AddAccessibilityModeFlags(kScreenReaderAndHTMLAccessibilityModes); @@ -1163,7 +1164,7 @@ if (!attrib_names || !name_space_id || !attrib_values) return E_INVALIDARG; - for (unsigned short i = 0; i < num_attribs; ++i) { + for (USHORT i = 0; i < num_attribs; ++i) { name_space_id[i] = 0; bool found = false; std::string name = base::UTF16ToUTF8((LPCWSTR)attrib_names[i]); @@ -1183,11 +1184,11 @@ } IFACEMETHODIMP BrowserAccessibilityComWin::get_computedStyle( - unsigned short max_style_properties, + USHORT max_style_properties, boolean use_alternate_view, BSTR* style_properties, BSTR* style_values, - unsigned short* num_style_properties) { + USHORT* num_style_properties) { WIN_ACCESSIBILITY_API_HISTOGRAM(UMA_API_GET_COMPUTED_STYLE); AddAccessibilityModeFlags(kScreenReaderAndHTMLAccessibilityModes); if (!owner()) @@ -1214,7 +1215,7 @@ } IFACEMETHODIMP BrowserAccessibilityComWin::get_computedStyleForProperties( - unsigned short num_style_properties, + USHORT num_style_properties, boolean use_alternate_view, BSTR* style_properties, BSTR* style_values) { @@ -1228,7 +1229,7 @@ // We only cache a single style property for now: DISPLAY - for (unsigned short i = 0; i < num_style_properties; ++i) { + for (USHORT i = 0; i < num_style_properties; ++i) { base::string16 name = base::ToLowerASCII( reinterpret_cast<const base::char16*>(style_properties[i])); if (name == L"display") { @@ -1707,7 +1708,7 @@ } void BrowserAccessibilityComWin::UpdateStep2ComputeHypertext() { - hypertext_ = ComputeHypertext(); + UpdateComputedHypertext(); } void BrowserAccessibilityComWin::UpdateStep3FireEvents( @@ -2068,9 +2069,9 @@ } // Pass in prefix with ":" included at the end, e.g. "invalid:". -bool HasAttribute(std::vector<base::string16>& existing_attributes, +bool HasAttribute(const std::vector<base::string16>& existing_attributes, base::string16 prefix) { - for (base::string16& attr : existing_attributes) { + for (const base::string16& attr : existing_attributes) { if (base::StartsWith(attr, prefix, base::CompareCase::SENSITIVE)) return true; }
diff --git a/content/browser/accessibility/browser_accessibility_com_win.h b/content/browser/accessibility/browser_accessibility_com_win.h index 352bd2b5d..b724f25c 100644 --- a/content/browser/accessibility/browser_accessibility_com_win.h +++ b/content/browser/accessibility/browser_accessibility_com_win.h
@@ -276,7 +276,7 @@ CONTENT_EXPORT IFACEMETHODIMP get_docType(BSTR* doc_type) override; CONTENT_EXPORT IFACEMETHODIMP - get_nameSpaceURIForID(short name_space_id, BSTR* name_space_uri) override; + get_nameSpaceURIForID(SHORT name_space_id, BSTR* name_space_uri) override; CONTENT_EXPORT IFACEMETHODIMP put_alternateViewMediaTypes(BSTR* comma_separated_media_types) override; @@ -284,36 +284,34 @@ // ISimpleDOMNode methods. // - CONTENT_EXPORT IFACEMETHODIMP - get_nodeInfo(BSTR* node_name, - short* name_space_id, - BSTR* node_value, - unsigned int* num_children, - unsigned int* unique_id, - unsigned short* node_type) override; + CONTENT_EXPORT IFACEMETHODIMP get_nodeInfo(BSTR* node_name, + SHORT* name_space_id, + BSTR* node_value, + unsigned int* num_children, + unsigned int* unique_id, + USHORT* node_type) override; + + CONTENT_EXPORT IFACEMETHODIMP get_attributes(USHORT max_attribs, + BSTR* attrib_names, + SHORT* name_space_id, + BSTR* attrib_values, + USHORT* num_attribs) override; CONTENT_EXPORT IFACEMETHODIMP - get_attributes(unsigned short max_attribs, - BSTR* attrib_names, - short* name_space_id, - BSTR* attrib_values, - unsigned short* num_attribs) override; - - CONTENT_EXPORT IFACEMETHODIMP - get_attributesForNames(unsigned short num_attribs, + get_attributesForNames(USHORT num_attribs, BSTR* attrib_names, - short* name_space_id, + SHORT* name_space_id, BSTR* attrib_values) override; CONTENT_EXPORT IFACEMETHODIMP - get_computedStyle(unsigned short max_style_properties, + get_computedStyle(USHORT max_style_properties, boolean use_alternate_view, BSTR* style_properties, BSTR* style_values, - unsigned short* num_style_properties) override; + USHORT* num_style_properties) override; CONTENT_EXPORT IFACEMETHODIMP - get_computedStyleForProperties(unsigned short num_style_properties, + get_computedStyleForProperties(USHORT num_style_properties, boolean use_alternate_view, BSTR* style_properties, BSTR* style_values) override;
diff --git a/content/browser/background_sync/background_sync_manager.cc b/content/browser/background_sync/background_sync_manager.cc index 4a2803b..ff36afe2 100644 --- a/content/browser/background_sync/background_sync_manager.cc +++ b/content/browser/background_sync/background_sync_manager.cc
@@ -741,8 +741,6 @@ } if (status != blink::ServiceWorkerStatusCode::kOk) { - LOG(ERROR) << "BackgroundSync failed to store registration due to backend " - "failure."; BackgroundSyncMetrics::CountRegisterFailure( BACKGROUND_SYNC_STATUS_STORAGE_ERROR); DisableAndClearManager(base::BindOnce( @@ -1332,8 +1330,6 @@ } if (status_code != blink::ServiceWorkerStatusCode::kOk) { - LOG(ERROR) << "BackgroundSync failed to store registration due to backend " - "failure."; DisableAndClearManager(std::move(callback)); return; }
diff --git a/content/browser/cache_storage/cache_storage_cache_unittest.cc b/content/browser/cache_storage/cache_storage_cache_unittest.cc index c78fc1e..263d6d0f 100644 --- a/content/browser/cache_storage/cache_storage_cache_unittest.cc +++ b/content/browser/cache_storage/cache_storage_cache_unittest.cc
@@ -98,12 +98,11 @@ class DelayableBackend : public disk_cache::Backend { public: explicit DelayableBackend(std::unique_ptr<disk_cache::Backend> backend) - : backend_(std::move(backend)), delay_open_entry_(false) {} + : Backend(backend->GetCacheType()), + backend_(std::move(backend)), + delay_open_entry_(false) {} // disk_cache::Backend overrides - net::CacheType GetCacheType() const override { - return backend_->GetCacheType(); - } int32_t GetEntryCount() const override { return backend_->GetEntryCount(); } net::Error OpenEntry(const std::string& key, net::RequestPriority request_priority,
diff --git a/content/browser/devtools/devtools_session_encoding.cc b/content/browser/devtools/devtools_session_encoding.cc index a297b78e0..8995f73 100644 --- a/content/browser/devtools/devtools_session_encoding.cc +++ b/content/browser/devtools/devtools_session_encoding.cc
@@ -13,7 +13,6 @@ #include "third_party/inspector_protocol/encoding/encoding.h" using inspector_protocol_encoding::span; -using inspector_protocol_encoding::Status; using inspector_protocol_encoding::StreamingParserHandler; using inspector_protocol_encoding::cbor::NewCBOREncoder; using inspector_protocol_encoding::cbor::ParseCBOR; @@ -52,7 +51,7 @@ std::string ConvertCBORToJSON(const std::string& cbor) { ContentShellPlatform platform; std::string json_message; - Status status; + inspector_protocol_encoding::Status status; std::unique_ptr<StreamingParserHandler> json_writer = NewJSONEncoder(&platform, &json_message, &status); ParseCBOR( @@ -70,7 +69,7 @@ std::string ConvertJSONToCBOR(const std::string& json) { ContentShellPlatform platform; std::vector<uint8_t> cbor; - Status status; + inspector_protocol_encoding::Status status; std::unique_ptr<StreamingParserHandler> encoder = NewCBOREncoder(&cbor, &status); ParseJSON(
diff --git a/content/browser/frame_host/navigation_controller_android.cc b/content/browser/frame_host/navigation_controller_android.cc index 03e869395..1baf7aa 100644 --- a/content/browser/frame_host/navigation_controller_android.cc +++ b/content/browser/frame_host/navigation_controller_android.cc
@@ -53,10 +53,11 @@ const content::FaviconStatus& status = entry->GetFavicon(); if (status.valid && status.image.ToSkBitmap()->computeByteSize() > 0) j_bitmap = gfx::ConvertToJavaBitmap(status.image.ToSkBitmap()); + jlong j_timestamp = entry->GetTimestamp().ToJavaTime(); return content::Java_NavigationControllerImpl_createNavigationEntry( env, index, j_url, j_virtual_url, j_original_url, j_referrer_url, j_title, - j_bitmap, entry->GetTransitionType()); + j_bitmap, entry->GetTransitionType(), j_timestamp); } static void JNI_NavigationControllerImpl_AddNavigationEntryToHistory(
diff --git a/content/browser/frame_host/navigation_controller_impl_unittest.cc b/content/browser/frame_host/navigation_controller_impl_unittest.cc index 81219960..ea4a842 100644 --- a/content/browser/frame_host/navigation_controller_impl_unittest.cc +++ b/content/browser/frame_host/navigation_controller_impl_unittest.cc
@@ -4318,7 +4318,7 @@ process()->sink().ClearMessages(); // Simulate the page calling history.back(). It should create a pending entry. - contents()->OnGoToEntryAtOffset(test_rvh(), -1, false); + contents()->OnGoToEntryAtOffset(main_test_rfh(), -1, false); EXPECT_EQ(0, controller.GetPendingEntryIndex()); // Also make sure we told the page to navigate. @@ -4328,7 +4328,7 @@ process()->sink().ClearMessages(); // Now test history.forward() - contents()->OnGoToEntryAtOffset(test_rvh(), 2, false); + contents()->OnGoToEntryAtOffset(main_test_rfh(), 2, false); EXPECT_EQ(2, controller.GetPendingEntryIndex()); nav_url = GetLastNavigationURL(); @@ -4339,7 +4339,8 @@ controller.DiscardNonCommittedEntries(); // Make sure an extravagant history.go() doesn't break. - contents()->OnGoToEntryAtOffset(test_rvh(), 120, false); // Out of bounds. + contents()->OnGoToEntryAtOffset(main_test_rfh(), 120, + false); // Out of bounds. EXPECT_EQ(-1, controller.GetPendingEntryIndex()); EXPECT_FALSE(HasNavigationRequest()); }
diff --git a/content/browser/frame_host/navigation_request.cc b/content/browser/frame_host/navigation_request.cc index 4d43fd1..c5c8289 100644 --- a/content/browser/frame_host/navigation_request.cc +++ b/content/browser/frame_host/navigation_request.cc
@@ -382,7 +382,7 @@ // - Restore-navigations are always browser-initiated. // - History-navigations use the browser-initiated path, event the ones that // are initiated by a javascript script, please see the IPC message - // ViewHostMsg_GoToEntryAtOffset. + // FrameHostMsg_GoToEntryAtOffset. DCHECK(FrameMsg_Navigate_Type::IsReload(common_params.navigation_type) || common_params.navigation_type == FrameMsg_Navigate_Type::DIFFERENT_DOCUMENT); @@ -1368,7 +1368,10 @@ // Sanity check that we haven't changed the RenderFrameHost picked for the // error page in OnRequestFailedInternal when running the WillFailRequest // checks. - CHECK(!render_frame_host_ || render_frame_host_ == render_frame_host); + // TODO(https://crbug.com/636952): Replace this by a CHECK when the bug is + // fixed. + if (render_frame_host_ && render_frame_host_ != render_frame_host) + base::debug::DumpWithoutCrashing(); render_frame_host_ = render_frame_host; DCHECK(render_frame_host_);
diff --git a/content/browser/frame_host/render_frame_host_impl.h b/content/browser/frame_host/render_frame_host_impl.h index 455fc85..c8e8068 100644 --- a/content/browser/frame_host/render_frame_host_impl.h +++ b/content/browser/frame_host/render_frame_host_impl.h
@@ -70,7 +70,6 @@ #include "third_party/blink/public/mojom/frame/find_in_page.mojom.h" #include "third_party/blink/public/mojom/frame/navigation_initiator.mojom.h" #include "third_party/blink/public/mojom/presentation/presentation.mojom.h" -#include "third_party/blink/public/mojom/serial/serial.mojom.h" #include "third_party/blink/public/mojom/service_worker/service_worker_provider.mojom.h" #include "third_party/blink/public/mojom/worker/dedicated_worker_host_factory.mojom.h" #include "third_party/blink/public/platform/modules/bluetooth/web_bluetooth.mojom.h" @@ -91,6 +90,8 @@ #if defined(OS_ANDROID) #include "services/device/public/mojom/nfc.mojom.h" +#else +#include "third_party/blink/public/mojom/serial/serial.mojom.h" #endif class GURL;
diff --git a/content/browser/indexed_db/indexed_db_dispatcher_host.cc b/content/browser/indexed_db/indexed_db_dispatcher_host.cc index eb9878f..2667a9e 100644 --- a/content/browser/indexed_db/indexed_db_dispatcher_host.cc +++ b/content/browser/indexed_db/indexed_db_dispatcher_host.cc
@@ -59,45 +59,6 @@ } // namespace -// TODO(cmp): Flatten calls / remove this class once IDB task runner CL settles. -class IndexedDBDispatcherHost::IDBSequenceHelper { - public: - IDBSequenceHelper(int ipc_process_id, - scoped_refptr<IndexedDBContextImpl> indexed_db_context) - : ipc_process_id_(ipc_process_id), - indexed_db_context_(std::move(indexed_db_context)) {} - ~IDBSequenceHelper() {} - - void GetDatabaseInfoOnIDBThread(scoped_refptr<IndexedDBCallbacks> callbacks, - const url::Origin& origin); - - void GetDatabaseNamesOnIDBThread(scoped_refptr<IndexedDBCallbacks> callbacks, - const url::Origin& origin); - void OpenOnIDBThread( - scoped_refptr<IndexedDBCallbacks> callbacks, - scoped_refptr<IndexedDBDatabaseCallbacks> database_callbacks, - const url::Origin& origin, - const base::string16& name, - int64_t version, - int64_t transaction_id); - void DeleteDatabaseOnIDBThread(scoped_refptr<IndexedDBCallbacks> callbacks, - const url::Origin& origin, - const base::string16& name, - bool force_close); - void AbortTransactionsAndCompactDatabaseOnIDBThread( - base::OnceCallback<void(leveldb::Status)> callback, - const url::Origin& origin); - void AbortTransactionsForDatabaseOnIDBThread( - base::OnceCallback<void(leveldb::Status)> callback, - const url::Origin& origin); - - private: - const int ipc_process_id_; - scoped_refptr<IndexedDBContextImpl> indexed_db_context_; - - DISALLOW_COPY_AND_ASSIGN(IDBSequenceHelper); -}; - IndexedDBDispatcherHost::IndexedDBDispatcherHost( int ipc_process_id, scoped_refptr<IndexedDBContextImpl> indexed_db_context, @@ -105,8 +66,6 @@ : indexed_db_context_(std::move(indexed_db_context)), blob_storage_context_(std::move(blob_storage_context)), ipc_process_id_(ipc_process_id), - idb_helper_(std::make_unique<IDBSequenceHelper>(ipc_process_id_, - indexed_db_context_)), weak_factory_(this) { DCHECK_CURRENTLY_ON(BrowserThread::UI); DETACH_FROM_SEQUENCE(sequence_checker_); @@ -171,7 +130,9 @@ scoped_refptr<IndexedDBCallbacks> callbacks( new IndexedDBCallbacks(this->AsWeakPtr(), context.origin, std::move(callbacks_info), IDBTaskRunner())); - idb_helper_->GetDatabaseInfoOnIDBThread(std::move(callbacks), context.origin); + base::FilePath indexed_db_path = indexed_db_context_->data_path(); + indexed_db_context_->GetIDBFactory()->GetDatabaseInfo( + std::move(callbacks), context.origin, indexed_db_path); } void IndexedDBDispatcherHost::GetDatabaseNames( @@ -182,8 +143,9 @@ scoped_refptr<IndexedDBCallbacks> callbacks( new IndexedDBCallbacks(this->AsWeakPtr(), context.origin, std::move(callbacks_info), IDBTaskRunner())); - idb_helper_->GetDatabaseNamesOnIDBThread(std::move(callbacks), - context.origin); + base::FilePath indexed_db_path = indexed_db_context_->data_path(); + indexed_db_context_->GetIDBFactory()->GetDatabaseNames( + std::move(callbacks), context.origin, indexed_db_path); } void IndexedDBDispatcherHost::Open( @@ -202,9 +164,16 @@ new IndexedDBDatabaseCallbacks(indexed_db_context_, std::move(database_callbacks_info), IDBTaskRunner())); - idb_helper_->OpenOnIDBThread(std::move(callbacks), - std::move(database_callbacks), context.origin, - name, version, transaction_id); + base::FilePath indexed_db_path = indexed_db_context_->data_path(); + + // TODO(dgrogan): Don't let a non-existing database be opened (and therefore + // created) if this origin is already over quota. + std::unique_ptr<IndexedDBPendingConnection> connection = + std::make_unique<IndexedDBPendingConnection>( + std::move(callbacks), std::move(database_callbacks), ipc_process_id_, + transaction_id, version); + indexed_db_context_->GetIDBFactory()->Open(name, std::move(connection), + context.origin, indexed_db_path); } void IndexedDBDispatcherHost::DeleteDatabase( @@ -217,8 +186,9 @@ scoped_refptr<IndexedDBCallbacks> callbacks( new IndexedDBCallbacks(this->AsWeakPtr(), context.origin, std::move(callbacks_info), IDBTaskRunner())); - idb_helper_->DeleteDatabaseOnIDBThread(std::move(callbacks), context.origin, - name, force_close); + base::FilePath indexed_db_path = indexed_db_context_->data_path(); + indexed_db_context_->GetIDBFactory()->DeleteDatabase( + name, std::move(callbacks), context.origin, indexed_db_path, force_close); } void IndexedDBDispatcherHost::AbortTransactionsAndCompactDatabase( @@ -228,7 +198,7 @@ const auto& context = bindings_.dispatch_context(); base::OnceCallback<void(leveldb::Status)> callback_on_io = base::BindOnce( &CallCompactionStatusCallbackOnIDBThread, std::move(mojo_callback)); - idb_helper_->AbortTransactionsAndCompactDatabaseOnIDBThread( + indexed_db_context_->GetIDBFactory()->AbortTransactionsAndCompactDatabase( std::move(callback_on_io), context.origin); } @@ -239,7 +209,7 @@ const auto& context = bindings_.dispatch_context(); base::OnceCallback<void(leveldb::Status)> callback_on_io = base::BindOnce( &CallAbortStatusCallbackOnIDBThread, std::move(mojo_callback)); - idb_helper_->AbortTransactionsForDatabaseOnIDBThread( + indexed_db_context_->GetIDBFactory()->AbortTransactionsForDatabase( std::move(callback_on_io), context.origin); } @@ -254,77 +224,4 @@ return indexed_db_context_->TaskRunner(); } -void IndexedDBDispatcherHost::IDBSequenceHelper::GetDatabaseInfoOnIDBThread( - scoped_refptr<IndexedDBCallbacks> callbacks, - const url::Origin& origin) { - DCHECK(indexed_db_context_->TaskRunner()->RunsTasksInCurrentSequence()); - - base::FilePath indexed_db_path = indexed_db_context_->data_path(); - indexed_db_context_->GetIDBFactory()->GetDatabaseInfo(callbacks, origin, - indexed_db_path); -} - -void IndexedDBDispatcherHost::IDBSequenceHelper::GetDatabaseNamesOnIDBThread( - scoped_refptr<IndexedDBCallbacks> callbacks, - const url::Origin& origin) { - DCHECK(indexed_db_context_->TaskRunner()->RunsTasksInCurrentSequence()); - - base::FilePath indexed_db_path = indexed_db_context_->data_path(); - indexed_db_context_->GetIDBFactory()->GetDatabaseNames(callbacks, origin, - indexed_db_path); -} - -void IndexedDBDispatcherHost::IDBSequenceHelper::OpenOnIDBThread( - scoped_refptr<IndexedDBCallbacks> callbacks, - scoped_refptr<IndexedDBDatabaseCallbacks> database_callbacks, - const url::Origin& origin, - const base::string16& name, - int64_t version, - int64_t transaction_id) { - DCHECK(indexed_db_context_->TaskRunner()->RunsTasksInCurrentSequence()); - - base::FilePath indexed_db_path = indexed_db_context_->data_path(); - - // TODO(dgrogan): Don't let a non-existing database be opened (and therefore - // created) if this origin is already over quota. - std::unique_ptr<IndexedDBPendingConnection> connection = - std::make_unique<IndexedDBPendingConnection>( - callbacks, database_callbacks, ipc_process_id_, transaction_id, - version); - indexed_db_context_->GetIDBFactory()->Open(name, std::move(connection), - origin, indexed_db_path); -} - -void IndexedDBDispatcherHost::IDBSequenceHelper::DeleteDatabaseOnIDBThread( - scoped_refptr<IndexedDBCallbacks> callbacks, - const url::Origin& origin, - const base::string16& name, - bool force_close) { - DCHECK(indexed_db_context_->TaskRunner()->RunsTasksInCurrentSequence()); - - base::FilePath indexed_db_path = indexed_db_context_->data_path(); - indexed_db_context_->GetIDBFactory()->DeleteDatabase( - name, callbacks, origin, indexed_db_path, force_close); -} - -void IndexedDBDispatcherHost::IDBSequenceHelper:: - AbortTransactionsAndCompactDatabaseOnIDBThread( - base::OnceCallback<void(leveldb::Status)> callback, - const url::Origin& origin) { - DCHECK(indexed_db_context_->TaskRunner()->RunsTasksInCurrentSequence()); - - indexed_db_context_->GetIDBFactory()->AbortTransactionsAndCompactDatabase( - std::move(callback), origin); -} - -void IndexedDBDispatcherHost::IDBSequenceHelper:: - AbortTransactionsForDatabaseOnIDBThread( - base::OnceCallback<void(leveldb::Status)> callback, - const url::Origin& origin) { - DCHECK(indexed_db_context_->TaskRunner()->RunsTasksInCurrentSequence()); - - indexed_db_context_->GetIDBFactory()->AbortTransactionsForDatabase( - std::move(callback), origin); -} - } // namespace content
diff --git a/content/browser/indexed_db/indexed_db_dispatcher_host.h b/content/browser/indexed_db/indexed_db_dispatcher_host.h index 62eb24f..6f166ba3 100644 --- a/content/browser/indexed_db/indexed_db_dispatcher_host.h +++ b/content/browser/indexed_db/indexed_db_dispatcher_host.h
@@ -126,8 +126,6 @@ mojo::StrongAssociatedBindingSet<blink::mojom::IDBCursor> cursor_bindings_; - std::unique_ptr<IDBSequenceHelper> idb_helper_; - SEQUENCE_CHECKER(sequence_checker_); base::WeakPtrFactory<IndexedDBDispatcherHost> weak_factory_;
diff --git a/content/browser/indexed_db/indexed_db_leveldb_operations.cc b/content/browser/indexed_db/indexed_db_leveldb_operations.cc index 0d6b7905..fbcde08 100644 --- a/content/browser/indexed_db/indexed_db_leveldb_operations.cc +++ b/content/browser/indexed_db/indexed_db_leveldb_operations.cc
@@ -156,9 +156,9 @@ LOG(ERROR) << "IndexedDB backing store cleanup succeeded, reopening"; state.reset(); bool is_disk_full; - std::tie(state, status, is_disk_full) = - ldb_factory->OpenLevelDB(database_path, GetDefaultIndexedDBComparator(), - GetDefaultLevelDBComparator()); + std::tie(state, status, is_disk_full) = ldb_factory->OpenLevelDBState( + database_path, GetDefaultIndexedDBComparator(), + GetDefaultLevelDBComparator()); if (!status.ok()) { LOG(ERROR) << "IndexedDB backing store reopen after recovery failed"; ReportOpenStatus( @@ -717,9 +717,9 @@ std::unique_ptr<LevelDBDatabase> database; leveldb::Status status; scoped_refptr<LevelDBState> state; - std::tie(state, status, is_disk_full) = - ldb_factory->OpenLevelDB(database_path, GetDefaultIndexedDBComparator(), - GetDefaultLevelDBComparator()); + std::tie(state, status, is_disk_full) = ldb_factory->OpenLevelDBState( + database_path, GetDefaultIndexedDBComparator(), + GetDefaultLevelDBComparator()); bool is_schema_known = false; // On I/O error the database isn't deleted, in case the issue is temporary. if (status.IsIOError()) {
diff --git a/content/browser/indexed_db/indexed_db_tombstone_sweeper_unittest.cc b/content/browser/indexed_db/indexed_db_tombstone_sweeper_unittest.cc index 4ebb872..c31c8f2 100644 --- a/content/browser/indexed_db/indexed_db_tombstone_sweeper_unittest.cc +++ b/content/browser/indexed_db/indexed_db_tombstone_sweeper_unittest.cc
@@ -140,7 +140,7 @@ scoped_refptr<LevelDBState> level_db_state; leveldb::Status s; std::tie(level_db_state, s, std::ignore) = - indexed_db::GetDefaultLevelDBFactory()->OpenLevelDB( + indexed_db::GetDefaultLevelDBFactory()->OpenLevelDBState( base::FilePath(), indexed_db::GetDefaultIndexedDBComparator(), indexed_db::GetDefaultLevelDBComparator()); ASSERT_TRUE(s.ok());
diff --git a/content/browser/indexed_db/leveldb/fake_leveldb_factory.cc b/content/browser/indexed_db/leveldb/fake_leveldb_factory.cc index baf374a..bd42a311 100644 --- a/content/browser/indexed_db/leveldb/fake_leveldb_factory.cc +++ b/content/browser/indexed_db/leveldb/fake_leveldb_factory.cc
@@ -4,7 +4,16 @@ #include "content/browser/indexed_db/leveldb/fake_leveldb_factory.h" +#include <mutex> +#include <string> +#include <thread> +#include <utility> + +#include "base/bind.h" #include "base/memory/ptr_util.h" +#include "base/optional.h" +#include "base/synchronization/lock.h" +#include "base/thread_annotations.h" #include "content/browser/indexed_db/indexed_db_leveldb_operations.h" #include "third_party/leveldatabase/src/include/leveldb/db.h" #include "third_party/leveldatabase/src/include/leveldb/slice.h" @@ -13,6 +22,23 @@ namespace content { namespace indexed_db { namespace { +class BrokenIterator : public leveldb::Iterator { + public: + BrokenIterator(leveldb::Status returned_status) + : returned_status_(returned_status) {} + bool Valid() const override { return false; } + void SeekToFirst() override {} + void SeekToLast() override {} + void Seek(const leveldb::Slice& target) override {} + void Next() override {} + void Prev() override {} + leveldb::Slice key() const override { return leveldb::Slice(); } + leveldb::Slice value() const override { return leveldb::Slice(); } + leveldb::Status status() const override { return returned_status_; } + + private: + leveldb::Status returned_status_; +}; // BrokenDB is a fake leveldb::DB that will return a given error status on every // method call, or no-op if there is nothing to return. @@ -20,7 +46,7 @@ public: BrokenDB(leveldb::Status returned_status) : returned_status_(std::move(returned_status)) {} - ~BrokenDB() override {} + ~BrokenDB() override = default; // Implementations of the DB interface leveldb::Status Put(const leveldb::WriteOptions&, @@ -42,7 +68,7 @@ return returned_status_; } leveldb::Iterator* NewIterator(const leveldb::ReadOptions&) override { - return nullptr; + return new BrokenIterator(returned_status_); } const leveldb::Snapshot* GetSnapshot() override { return nullptr; } void ReleaseSnapshot(const leveldb::Snapshot* snapshot) override {} @@ -60,6 +86,117 @@ leveldb::Status returned_status_; }; +// BreakOnCallbackDB is a leveldb::DB wrapper that will return a given error +// status or fail every method call after the |Break| method is called. This is +// thread-safe, just like leveldb::DB. +class BreakOnCallbackDB : public leveldb::DB { + public: + BreakOnCallbackDB(std::unique_ptr<leveldb::DB> db) : db_(std::move(db)) {} + ~BreakOnCallbackDB() override = default; + + void Break(leveldb::Status broken_status) { + base::AutoLock lock(lock_); + broken_status_ = std::move(broken_status); + } + + // Implementations of the DB interface + leveldb::Status Put(const leveldb::WriteOptions& options, + const leveldb::Slice& key, + const leveldb::Slice& value) override { + { + base::AutoLock lock(lock_); + if (broken_status_) + return broken_status_.value(); + } + return db_->Put(options, key, value); + } + leveldb::Status Delete(const leveldb::WriteOptions& options, + const leveldb::Slice& key) override { + { + base::AutoLock lock(lock_); + if (broken_status_) + return broken_status_.value(); + } + return db_->Delete(options, key); + } + leveldb::Status Write(const leveldb::WriteOptions& options, + leveldb::WriteBatch* updates) override { + { + base::AutoLock lock(lock_); + if (broken_status_) + return broken_status_.value(); + } + return db_->Write(options, updates); + } + leveldb::Status Get(const leveldb::ReadOptions& options, + const leveldb::Slice& key, + std::string* value) override { + { + base::AutoLock lock(lock_); + if (broken_status_) + return broken_status_.value(); + } + return db_->Get(options, key, value); + } + leveldb::Iterator* NewIterator(const leveldb::ReadOptions& options) override { + { + base::AutoLock lock(lock_); + if (broken_status_) + return new BrokenIterator(broken_status_.value()); + } + return db_->NewIterator(options); + } + const leveldb::Snapshot* GetSnapshot() override { + { + base::AutoLock lock(lock_); + if (broken_status_) + return nullptr; + } + return db_->GetSnapshot(); + } + void ReleaseSnapshot(const leveldb::Snapshot* snapshot) override { + { + base::AutoLock lock(lock_); + if (broken_status_) + return; + } + return db_->ReleaseSnapshot(snapshot); + } + bool GetProperty(const leveldb::Slice& property, + std::string* value) override { + { + base::AutoLock lock(lock_); + if (broken_status_) + return false; + } + return db_->GetProperty(property, value); + } + void GetApproximateSizes(const leveldb::Range* range, + int n, + uint64_t* sizes) override { + { + base::AutoLock lock(lock_); + if (broken_status_) + return; + } + db_->GetApproximateSizes(range, n, sizes); + } + void CompactRange(const leveldb::Slice* begin, + const leveldb::Slice* end) override { + { + base::AutoLock lock(lock_); + if (broken_status_) + return; + } + db_->CompactRange(begin, end); + } + + private: + base::Lock lock_; + const std::unique_ptr<leveldb::DB> db_; + base::Optional<leveldb::Status> broken_status_ GUARDED_BY(lock_); +}; + } // namespace FakeLevelDBFactory::FakeLevelDBFactory() = default; @@ -75,22 +212,53 @@ std::make_unique<BrokenDB>(error_to_return), reported_file_path); } -void FakeLevelDBFactory::EnqueueNextOpenLevelDBResult( +// static +std::pair<std::unique_ptr<leveldb::DB>, + base::OnceCallback<void(leveldb::Status)>> +FakeLevelDBFactory::CreateBreakableDB(std::unique_ptr<leveldb::DB> db) { + std::unique_ptr<BreakOnCallbackDB> breakable_db = + std::make_unique<BreakOnCallbackDB>(std::move(db)); + base::OnceCallback<void(leveldb::Status)> callback = base::BindOnce( + &BreakOnCallbackDB::Break, base::Unretained(breakable_db.get())); + return std::make_pair(std::move(breakable_db), std::move(callback)); +} + +void FakeLevelDBFactory::EnqueueNextOpenDBResult( + std::unique_ptr<leveldb::DB> db, + leveldb::Status status) { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + next_dbs_.push(std::make_tuple(std::move(db), status)); +} + +std::tuple<std::unique_ptr<leveldb::DB>, leveldb::Status> +FakeLevelDBFactory::OpenDB(const leveldb_env::Options& options, + const std::string& name) { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + if (next_dbs_.empty()) + return DefaultLevelDBFactory::OpenDB(options, name); + auto tuple = std::move(next_dbs_.front()); + next_dbs_.pop(); + return tuple; +} + +void FakeLevelDBFactory::EnqueueNextOpenLevelDBStateResult( scoped_refptr<LevelDBState> state, leveldb::Status status, bool is_disk_full) { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); next_leveldb_states_.push( std::make_tuple(std::move(state), status, is_disk_full)); } std::tuple<scoped_refptr<LevelDBState>, leveldb::Status, bool /*disk_full*/> -FakeLevelDBFactory::OpenLevelDB( +FakeLevelDBFactory::OpenLevelDBState( const base::FilePath& file_name, const LevelDBComparator* idb_comparator, - const leveldb::Comparator* ldb_comparator) const { + const leveldb::Comparator* ldb_comparator) { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); if (next_leveldb_states_.empty()) { - return DefaultLevelDBFactory::OpenLevelDB(file_name, idb_comparator, - ldb_comparator); + return DefaultLevelDBFactory::OpenLevelDBState(file_name, idb_comparator, + ldb_comparator); } auto tuple = std::move(next_leveldb_states_.front()); next_leveldb_states_.pop();
diff --git a/content/browser/indexed_db/leveldb/fake_leveldb_factory.h b/content/browser/indexed_db/leveldb/fake_leveldb_factory.h index 9f21b63..6c88e737 100644 --- a/content/browser/indexed_db/leveldb/fake_leveldb_factory.h +++ b/content/browser/indexed_db/leveldb/fake_leveldb_factory.h
@@ -5,9 +5,11 @@ #ifndef CONTENT_BROWSER_INDEXED_DB_LEVELDB_FAKE_LEVELDB_FACTORY_H_ #define CONTENT_BROWSER_INDEXED_DB_LEVELDB_FAKE_LEVELDB_FACTORY_H_ +#include <memory> #include <queue> #include <utility> +#include "base/sequence_checker.h" #include "content/browser/indexed_db/leveldb/leveldb_env.h" namespace content { @@ -25,19 +27,36 @@ leveldb::Status error_to_return, const base::FilePath& reported_file_path); - void EnqueueNextOpenLevelDBResult(scoped_refptr<LevelDBState> state, - leveldb::Status status, - bool is_disk_full); + // The returned callback will trigger the database to be broken, and forever + // return the given status. + static std::pair<std::unique_ptr<leveldb::DB>, + base::OnceCallback<void(leveldb::Status)>> + CreateBreakableDB(std::unique_ptr<leveldb::DB> db); + + void EnqueueNextOpenDBResult(std::unique_ptr<leveldb::DB>, + leveldb::Status status); + + std::tuple<std::unique_ptr<leveldb::DB>, leveldb::Status> OpenDB( + const leveldb_env::Options& options, + const std::string& name) override; + + void EnqueueNextOpenLevelDBStateResult(scoped_refptr<LevelDBState> state, + leveldb::Status status, + bool is_disk_full); std::tuple<scoped_refptr<LevelDBState>, leveldb::Status, bool /*disk_full*/> - OpenLevelDB(const base::FilePath& file_name, - const LevelDBComparator* idb_comparator, - const leveldb::Comparator* ldb_comparator) const override; + OpenLevelDBState(const base::FilePath& file_name, + const LevelDBComparator* idb_comparator, + const leveldb::Comparator* ldb_comparator) override; private: - mutable std::queue<std::tuple<scoped_refptr<LevelDBState>, - leveldb::Status, - bool /*disk_full*/>> + SEQUENCE_CHECKER(sequence_checker_); + + std::queue<std::tuple<std::unique_ptr<leveldb::DB>, leveldb::Status>> + next_dbs_; + std::queue<std::tuple<scoped_refptr<LevelDBState>, + leveldb::Status, + bool /*disk_full*/>> next_leveldb_states_; };
diff --git a/content/browser/indexed_db/leveldb/leveldb_env.cc b/content/browser/indexed_db/leveldb/leveldb_env.cc index f61b8bb..926fd3f0 100644 --- a/content/browser/indexed_db/leveldb/leveldb_env.cc +++ b/content/browser/indexed_db/leveldb/leveldb_env.cc
@@ -15,11 +15,15 @@ #include "third_party/leveldatabase/src/include/leveldb/filter_policy.h" namespace content { -namespace { -// Static member initialization. -base::LazyInstance<content::LevelDBEnv>::Leaky g_leveldb_env = - LAZY_INSTANCE_INITIALIZER; +LevelDBEnv::LevelDBEnv() : ChromiumEnv("LevelDBEnv.IDB") {} + +LevelDBEnv* LevelDBEnv::Get() { + static base::NoDestructor<LevelDBEnv> g_leveldb_env; + return g_leveldb_env.get(); +} + +namespace indexed_db { leveldb_env::Options GetLevelDBOptions(leveldb::Env* env, const leveldb::Comparator* comparator, @@ -42,21 +46,19 @@ return options; } -} // namespace - -LevelDBEnv::LevelDBEnv() : ChromiumEnv("LevelDBEnv.IDB") {} - -LevelDBEnv* LevelDBEnv::Get() { - return g_leveldb_env.Pointer(); +std::tuple<std::unique_ptr<leveldb::DB>, leveldb::Status> +DefaultLevelDBFactory::OpenDB(const leveldb_env::Options& options, + const std::string& name) { + std::unique_ptr<leveldb::DB> db; + leveldb::Status s = leveldb_env::OpenDB(options, name, &db); + return {std::move(db), s}; } -namespace indexed_db { - std::tuple<scoped_refptr<LevelDBState>, leveldb::Status, bool /* disk_full*/> -DefaultLevelDBFactory::OpenLevelDB( +DefaultLevelDBFactory::OpenLevelDBState( const base::FilePath& file_name, const LevelDBComparator* idb_comparator, - const leveldb::Comparator* ldb_comparator) const { + const leveldb::Comparator* ldb_comparator) { // Please see docs/open_and_verify_leveldb_database.code2flow, and the // generated pdf (from https://code2flow.com). // The intended strategy here is to have this function match that flowchart, @@ -77,7 +79,7 @@ GetLevelDBOptions(in_memory_env.get(), ldb_comparator, /* default of 4MB */ 4 * kBytesInOneMegabyte, /*paranoid_checks=*/false); - status = leveldb_env::OpenDB(in_memory_options, std::string(), &db); + std::tie(db, status) = OpenDB(in_memory_options, std::string()); if (!status.ok()) { LOG(ERROR) << "Failed to open in-memory LevelDB database: " << status.ToString(); @@ -98,7 +100,7 @@ /*paranoid_checks=*/true); // ChromiumEnv assumes UTF8, converts back to FilePath before using. - status = leveldb_env::OpenDB(options, file_name.AsUTF8Unsafe(), &db); + std::tie(db, status) = OpenDB(options, file_name.AsUTF8Unsafe()); if (!status.ok()) { ReportLevelDBError("WebCore.IndexedDB.LevelDBOpenErrors", status); @@ -128,7 +130,7 @@ } leveldb::Status DefaultLevelDBFactory::DestroyLevelDB( - scoped_refptr<LevelDBState> level_db_state) const { + scoped_refptr<LevelDBState> level_db_state) { DCHECK(level_db_state); DCHECK(!level_db_state->in_memory_env() && !level_db_state->database_path().empty()) @@ -145,7 +147,7 @@ } leveldb::Status DefaultLevelDBFactory::DestroyLevelDB( - const base::FilePath& path) const { + const base::FilePath& path) { leveldb_env::Options options; options.env = LevelDBEnv::Get(); return leveldb::DestroyDB(path.AsUTF8Unsafe(), options);
diff --git a/content/browser/indexed_db/leveldb/leveldb_env.h b/content/browser/indexed_db/leveldb/leveldb_env.h index d142c10..a1ec007 100644 --- a/content/browser/indexed_db/leveldb/leveldb_env.h +++ b/content/browser/indexed_db/leveldb/leveldb_env.h
@@ -5,11 +5,13 @@ #ifndef CONTENT_BROWSER_INDEXED_DB_LEVELDB_LEVELDB_ENV_H_ #define CONTENT_BROWSER_INDEXED_DB_LEVELDB_LEVELDB_ENV_H_ +#include <memory> #include <tuple> #include "base/files/file_path.h" #include "base/lazy_instance.h" #include "base/memory/scoped_refptr.h" +#include "base/no_destructor.h" #include "base/optional.h" #include "content/browser/indexed_db/leveldb/leveldb_comparator.h" #include "content/browser/indexed_db/scopes/leveldb_state.h" @@ -18,57 +20,78 @@ #include "third_party/leveldatabase/src/include/leveldb/comparator.h" #include "third_party/leveldatabase/src/include/leveldb/status.h" +namespace base { +template <typename T> +class NoDestructor; +} + namespace content { // The leveldb::Env used by the Indexed DB backend. class LevelDBEnv : public leveldb_env::ChromiumEnv { - LevelDBEnv(); - public: - friend struct base::LazyInstanceTraitsBase<LevelDBEnv>; CONTENT_EXPORT static LevelDBEnv* Get(); + + private: + friend class base::NoDestructor<LevelDBEnv>; + LevelDBEnv(); }; namespace indexed_db { +// Visible for testing. +leveldb_env::Options GetLevelDBOptions(leveldb::Env* env, + const leveldb::Comparator* comparator, + size_t write_buffer_size, + bool paranoid_checks); + // Factory class used to open leveldb databases, and stores all necessary // objects in a LevelDBState. This interface exists so that it can be mocked out // for tests. class CONTENT_EXPORT LevelDBFactory { public: - virtual ~LevelDBFactory() {} + virtual ~LevelDBFactory() = default; + + virtual std::tuple<std::unique_ptr<leveldb::DB>, leveldb::Status> OpenDB( + const leveldb_env::Options& options, + const std::string& name) = 0; // Opens a leveldb database with the given comparators and populates it in // |output_state|. If the |file_name| is empty, then the database will be // in-memory. The comparator names must match. virtual std:: tuple<scoped_refptr<LevelDBState>, leveldb::Status, bool /* disk_full*/> - OpenLevelDB(const base::FilePath& file_name, - const LevelDBComparator* idb_comparator, - const leveldb::Comparator* ldb_comparator) const = 0; + OpenLevelDBState(const base::FilePath& file_name, + const LevelDBComparator* idb_comparator, + const leveldb::Comparator* ldb_comparator) = 0; // A somewhat safe way to destroy a leveldb database. This asserts that there // are no other references to the given LevelDBState, and deletes the database // on disk. |level_db_state| must only have one ref. virtual leveldb::Status DestroyLevelDB( - scoped_refptr<LevelDBState> output_state) const = 0; + scoped_refptr<LevelDBState> output_state) = 0; // Assumes that there is no leveldb database currently running for this path. - virtual leveldb::Status DestroyLevelDB(const base::FilePath& path) const = 0; + virtual leveldb::Status DestroyLevelDB(const base::FilePath& path) = 0; }; class CONTENT_EXPORT DefaultLevelDBFactory : public LevelDBFactory { public: DefaultLevelDBFactory() = default; ~DefaultLevelDBFactory() override {} + + std::tuple<std::unique_ptr<leveldb::DB>, leveldb::Status> OpenDB( + const leveldb_env::Options& options, + const std::string& name) override; + std::tuple<scoped_refptr<LevelDBState>, leveldb::Status, bool /* disk_full*/> - OpenLevelDB(const base::FilePath& file_name, - const LevelDBComparator* idb_comparator, - const leveldb::Comparator* ldb_comparator) const override; + OpenLevelDBState(const base::FilePath& file_name, + const LevelDBComparator* idb_comparator, + const leveldb::Comparator* ldb_comparator) override; leveldb::Status DestroyLevelDB( - scoped_refptr<LevelDBState> output_state) const override; - leveldb::Status DestroyLevelDB(const base::FilePath& path) const override; + scoped_refptr<LevelDBState> output_state) override; + leveldb::Status DestroyLevelDB(const base::FilePath& path) override; }; // Returns a singleton default factory.
diff --git a/content/browser/indexed_db/leveldb/leveldb_env_unittest.cc b/content/browser/indexed_db/leveldb/leveldb_env_unittest.cc index dbec948..ec29f3a 100644 --- a/content/browser/indexed_db/leveldb/leveldb_env_unittest.cc +++ b/content/browser/indexed_db/leveldb/leveldb_env_unittest.cc
@@ -20,7 +20,7 @@ TEST(LevelDBEnvTest, TestInMemory) { DefaultLevelDBFactory default_factory; scoped_refptr<LevelDBState> state; - std::tie(state, std::ignore, std::ignore) = default_factory.OpenLevelDB( + std::tie(state, std::ignore, std::ignore) = default_factory.OpenLevelDBState( base::FilePath(), GetDefaultIndexedDBComparator(), GetDefaultLevelDBComparator()); EXPECT_TRUE(state);
diff --git a/content/browser/indexed_db/leveldb/leveldb_transaction_unittest.cc b/content/browser/indexed_db/leveldb/leveldb_transaction_unittest.cc index 21902f4a..ad8af3a 100644 --- a/content/browser/indexed_db/leveldb/leveldb_transaction_unittest.cc +++ b/content/browser/indexed_db/leveldb/leveldb_transaction_unittest.cc
@@ -37,7 +37,7 @@ scoped_refptr<LevelDBState> ldb_state; leveldb::Status status; std::tie(ldb_state, status, std::ignore) = - indexed_db::GetDefaultLevelDBFactory()->OpenLevelDB( + indexed_db::GetDefaultLevelDBFactory()->OpenLevelDBState( temp_directory_.GetPath(), LevelDBComparator::BytewiseComparator(), leveldb::BytewiseComparator()); EXPECT_TRUE(status.ok());
diff --git a/content/browser/indexed_db/leveldb/leveldb_unittest.cc b/content/browser/indexed_db/leveldb/leveldb_unittest.cc index f569f1a..d371e9c 100644 --- a/content/browser/indexed_db/leveldb/leveldb_unittest.cc +++ b/content/browser/indexed_db/leveldb/leveldb_unittest.cc
@@ -64,7 +64,7 @@ std::tuple<scoped_refptr<LevelDBState>, leveldb::Status, bool /* disk_full*/> OpenLevelDB(base::FilePath file_name) { - return indexed_db::GetDefaultLevelDBFactory()->OpenLevelDB( + return indexed_db::GetDefaultLevelDBFactory()->OpenLevelDBState( file_name, SimpleComparator::Get(), SimpleLDBComparator::Get()); }
diff --git a/content/browser/indexed_db/scopes/leveldb_state.cc b/content/browser/indexed_db/scopes/leveldb_state.cc index 868ff96..f98286a 100644 --- a/content/browser/indexed_db/scopes/leveldb_state.cc +++ b/content/browser/indexed_db/scopes/leveldb_state.cc
@@ -2,7 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include <content/browser/indexed_db/scopes/leveldb_state.h> +#include "content/browser/indexed_db/scopes/leveldb_state.h" + #include "base/memory/ptr_util.h" #include "base/metrics/histogram_macros.h" #include "content/browser/indexed_db/leveldb/leveldb_env.h" @@ -44,9 +45,27 @@ idb_comparator_(idb_comparator), db_(std::move(database)), database_path_(std::move(database_path)), - name_for_tracing_(std::move(name_for_tracing)) {} + name_for_tracing_(std::move(name_for_tracing)), + destruction_requested_(false) {} + +bool LevelDBState::RequestDestruction( + base::OnceClosure on_state_destruction, + scoped_refptr<base::SequencedTaskRunner> task_runner) { + if (destruction_requested_.exchange(true, std::memory_order_relaxed)) + return false; + + DCHECK(!on_destruction_); + DCHECK(!on_destruction_task_runner_); + on_destruction_ = std::move(on_state_destruction); + on_destruction_task_runner_ = std::move(task_runner); + return true; +} LevelDBState::~LevelDBState() { + if (on_destruction_) { + on_destruction_task_runner_->PostTask(FROM_HERE, + std::move(on_destruction_)); + } if (!db_) return; base::TimeTicks begin_time = base::TimeTicks::Now();
diff --git a/content/browser/indexed_db/scopes/leveldb_state.h b/content/browser/indexed_db/scopes/leveldb_state.h index e3dcf5c3..7695bb5 100644 --- a/content/browser/indexed_db/scopes/leveldb_state.h +++ b/content/browser/indexed_db/scopes/leveldb_state.h
@@ -5,11 +5,15 @@ #ifndef CONTENT_BROWSER_INDEXED_DB_SCOPES_LEVELDB_STATE_H_ #define CONTENT_BROWSER_INDEXED_DB_SCOPES_LEVELDB_STATE_H_ -#include "base/memory/ref_counted.h" - +#include <atomic> #include <memory> +#include <utility> +#include "base/callback.h" #include "base/files/file_path.h" +#include "base/memory/ref_counted.h" +#include "base/memory/scoped_refptr.h" +#include "base/sequenced_task_runner.h" #include "content/browser/indexed_db/leveldb/leveldb_comparator.h" #include "content/common/content_export.h" #include "third_party/leveldatabase/src/include/leveldb/comparator.h" @@ -17,6 +21,9 @@ #include "third_party/leveldatabase/src/include/leveldb/filter_policy.h" namespace content { +namespace indexed_db { +class FakeLevelDBFactory; +} // Encapsulates a leveldb database and comparator, allowing them to be used // safely across thread boundaries. @@ -36,6 +43,17 @@ std::unique_ptr<leveldb::DB> in_memory_database, std::string name_for_tracing); + // Returns if this call was successfully the first call to request destruction + // of this state. Can be called on any thread. The given |task_runner| will be + // used to call the |on_destruction| closure, which is called on the + // destruction of this state. + bool RequestDestruction(base::OnceClosure on_destruction, + scoped_refptr<base::SequencedTaskRunner> task_runner); + + bool destruction_requested() const { + return destruction_requested_.load(std::memory_order_relaxed); + } + const leveldb::Comparator* comparator() const { return comparator_; } const LevelDBComparator* idb_comparator() const { return idb_comparator_; } leveldb::DB* db() const { return db_.get(); } @@ -47,6 +65,7 @@ const base::FilePath& database_path() const { return database_path_; } private: + friend class indexed_db::FakeLevelDBFactory; friend class base::RefCountedThreadSafe<LevelDBState>; LevelDBState(std::unique_ptr<leveldb::Env> optional_in_memory_env, @@ -63,6 +82,15 @@ const std::unique_ptr<leveldb::DB> db_; const base::FilePath database_path_; const std::string name_for_tracing_; + + // This member transitions from false to true at most once in the instance's + // lifetime. + std::atomic_bool destruction_requested_; + // These members are written only once (when |destruction_requested_| + // transitions from false to true) and read only once in the destructor, so + // they are thread-compatible. + base::OnceClosure on_destruction_; + scoped_refptr<base::SequencedTaskRunner> on_destruction_task_runner_; }; } // namespace content
diff --git a/content/browser/loader/navigation_url_loader_impl.cc b/content/browser/loader/navigation_url_loader_impl.cc index 068a7c8..f9d3104 100644 --- a/content/browser/loader/navigation_url_loader_impl.cc +++ b/content/browser/loader/navigation_url_loader_impl.cc
@@ -1348,7 +1348,7 @@ : network::mojom::RequestContextFrameType::kNested; storage::BlobStorageContext* blob_storage_context = GetBlobStorageContext( GetChromeBlobStorageContextForResourceContext(resource_context_)); - return ServiceWorkerRequestHandler::InitializeForNavigationNetworkService( + return ServiceWorkerRequestHandler::InitializeForNavigation( resource_request_->url, resource_context_, service_worker_navigation_handle_core, blob_storage_context, request_info.begin_params->skip_service_worker, resource_type,
diff --git a/content/browser/navigation_browsertest.cc b/content/browser/navigation_browsertest.cc index 7471887..1e9ef564 100644 --- a/content/browser/navigation_browsertest.cc +++ b/content/browser/navigation_browsertest.cc
@@ -1291,7 +1291,7 @@ "};")); TestNavigationManager navigation(shell()->web_contents(), url_2); auto ipc_observer = base::MakeRefCounted<BrowserMessageObserver>( - ViewMsgStart, ViewHostMsg_GoToEntryAtOffset::ID); + FrameMsgStart, FrameHostMsg_GoToEntryAtOffset::ID); static_cast<RenderFrameHostImpl*>(shell()->web_contents()->GetMainFrame()) ->GetProcess() ->AddFilter(ipc_observer.get());
diff --git a/content/browser/renderer_host/render_widget_host_impl.cc b/content/browser/renderer_host/render_widget_host_impl.cc index 4e3f74dd..a69f75996 100644 --- a/content/browser/renderer_host/render_widget_host_impl.cc +++ b/content/browser/renderer_host/render_widget_host_impl.cc
@@ -680,7 +680,7 @@ } bool RenderWidgetHostImpl::ShouldShowStaleContentOnEviction() { - return delegate_->ShouldShowStaleContentOnEviction(); + return delegate_ && delegate_->ShouldShowStaleContentOnEviction(); } void RenderWidgetHostImpl::ShutdownAndDestroyWidget(bool also_delete) {
diff --git a/content/browser/service_worker/service_worker_cache_writer.cc b/content/browser/service_worker/service_worker_cache_writer.cc index 6df907e..586196a 100644 --- a/content/browser/service_worker/service_worker_cache_writer.cc +++ b/content/browser/service_worker/service_worker_cache_writer.cc
@@ -22,8 +22,10 @@ : public base::RefCounted<AsyncOnlyCompletionCallbackAdaptor> { public: explicit AsyncOnlyCompletionCallbackAdaptor( - const net::CompletionCallback& callback) - : async_(false), result_(net::ERR_IO_PENDING), callback_(callback) {} + net::CompletionOnceCallback callback) + : async_(false), + result_(net::ERR_IO_PENDING), + callback_(std::move(callback)) {} void set_async(bool async) { async_ = async; } bool async() { return async_; } @@ -32,7 +34,7 @@ void WrappedCallback(int result) { result_ = result; if (async_) - callback_.Run(result); + std::move(callback_).Run(result); } private: @@ -41,7 +43,7 @@ bool async_; int result_; - net::CompletionCallback callback_; + net::CompletionOnceCallback callback_; }; } // namespace @@ -547,7 +549,7 @@ int ServiceWorkerCacheWriter::ReadInfoHelper( const std::unique_ptr<ServiceWorkerResponseReader>& reader, HttpResponseInfoIOBuffer* buf) { - net::CompletionCallback run_callback = base::Bind( + net::CompletionOnceCallback run_callback = base::BindOnce( &ServiceWorkerCacheWriter::AsyncDoLoop, weak_factory_.GetWeakPtr()); scoped_refptr<AsyncOnlyCompletionCallbackAdaptor> adaptor( new AsyncOnlyCompletionCallbackAdaptor(std::move(run_callback))); @@ -562,7 +564,7 @@ const std::unique_ptr<ServiceWorkerResponseReader>& reader, net::IOBuffer* buf, int buf_len) { - net::CompletionCallback run_callback = base::Bind( + net::CompletionOnceCallback run_callback = base::BindOnce( &ServiceWorkerCacheWriter::AsyncDoLoop, weak_factory_.GetWeakPtr()); scoped_refptr<AsyncOnlyCompletionCallbackAdaptor> adaptor( new AsyncOnlyCompletionCallbackAdaptor(std::move(run_callback))); @@ -578,7 +580,7 @@ const std::unique_ptr<ServiceWorkerResponseWriter>& writer, HttpResponseInfoIOBuffer* buf) { did_replace_ = true; - net::CompletionCallback run_callback = base::Bind( + net::CompletionOnceCallback run_callback = base::BindOnce( &ServiceWorkerCacheWriter::AsyncDoLoop, weak_factory_.GetWeakPtr()); scoped_refptr<AsyncOnlyCompletionCallbackAdaptor> adaptor( new AsyncOnlyCompletionCallbackAdaptor(std::move(run_callback))); @@ -593,7 +595,7 @@ const std::unique_ptr<ServiceWorkerResponseWriter>& writer, net::IOBuffer* buf, int buf_len) { - net::CompletionCallback run_callback = base::Bind( + net::CompletionOnceCallback run_callback = base::BindOnce( &ServiceWorkerCacheWriter::AsyncDoLoop, weak_factory_.GetWeakPtr()); scoped_refptr<AsyncOnlyCompletionCallbackAdaptor> adaptor( new AsyncOnlyCompletionCallbackAdaptor(std::move(run_callback)));
diff --git a/content/browser/service_worker/service_worker_controllee_request_handler.cc b/content/browser/service_worker/service_worker_controllee_request_handler.cc index 54f561d1..06aff19 100644 --- a/content/browser/service_worker/service_worker_controllee_request_handler.cc +++ b/content/browser/service_worker/service_worker_controllee_request_handler.cc
@@ -126,8 +126,6 @@ std::move(blob_storage_context), resource_type), resource_type_(resource_type), - is_main_resource_load_( - ServiceWorkerUtils::IsMainResourceType(resource_type)), request_mode_(request_mode), credentials_mode_(credentials_mode), redirect_mode_(redirect_mode), @@ -138,7 +136,9 @@ body_(std::move(body)), force_update_started_(false), use_network_(false), - weak_factory_(this) {} + weak_factory_(this) { + DCHECK(ServiceWorkerUtils::IsMainResourceType(resource_type)); +} ServiceWorkerControlleeRequestHandler:: ~ServiceWorkerControlleeRequestHandler() { @@ -149,30 +149,21 @@ if (!provider_host_ || !provider_host_->controller()) return; - if (blink::ServiceWorkerUtils::IsServicificationEnabled()) { - // For subresources: S13nServiceWorker doesn't come here. - DCHECK(is_main_resource_load_); + // For navigations, the update logic is taken care of + // during navigation and waits for the HintToUpdateServiceWorker message. + if (IsResourceTypeFrame(resource_type_)) + return; - // For navigations, the update logic is taken care of - // during navigation and waits for the HintToUpdateServiceWorker message. - if (IsResourceTypeFrame(resource_type_)) - return; - - // Continue to the common non-S13nServiceWorker code for triggering update - // for shared workers. The renderer doesn't yet send a - // HintToUpdateServiceWorker message. - // TODO(falken): Make the renderer send the message for shared worker, - // to simplify the code. - } + // For shared workers. The renderer doesn't yet send a + // HintToUpdateServiceWorker message. + // TODO(falken): Make the renderer send the message for shared worker, + // to simplify the code. // If DevTools forced an update, there is no need to update again. if (force_update_started_) return; - if (is_main_resource_load_) - provider_host_->controller()->ScheduleUpdate(); - else - provider_host_->controller()->DeferScheduledUpdate(); + provider_host_->controller()->ScheduleUpdate(); } void ServiceWorkerControlleeRequestHandler::MaybeCreateLoader( @@ -180,8 +171,6 @@ ResourceContext* resource_context, LoaderCallback callback, FallbackCallback fallback_callback) { - DCHECK(blink::ServiceWorkerUtils::IsServicificationEnabled()); - DCHECK(is_main_resource_load_); ClearJob(); if (!context_ || !provider_host_) { @@ -566,26 +555,6 @@ std::move(disallow_controller))); } -void ServiceWorkerControlleeRequestHandler::PrepareForSubResource() { - DCHECK(IsJobAlive()); - DCHECK(context_); - - // When this request handler was created, the provider host had a controller - // and hence an active version, but by the time MaybeCreateJob() is called - // the active version may have been lost. This happens when - // ServiceWorkerRegistration::DeleteVersion() was called to delete the worker - // because a permanent failure occurred when trying to start it. - // - // As this is an exceptional case, just error out. - ServiceWorkerVersion* controller = provider_host_->controller(); - if (!controller) { - url_job_->FailDueToLostController(); - return; - } - - MaybeForwardToServiceWorker(url_job_.get(), controller); -} - void ServiceWorkerControlleeRequestHandler::OnPrepareToRestart() { use_network_ = true; ClearJob();
diff --git a/content/browser/service_worker/service_worker_controllee_request_handler.h b/content/browser/service_worker/service_worker_controllee_request_handler.h index 1eb88992..326b12ac 100644 --- a/content/browser/service_worker/service_worker_controllee_request_handler.h +++ b/content/browser/service_worker/service_worker_controllee_request_handler.h
@@ -34,11 +34,8 @@ class ServiceWorkerRegistration; class ServiceWorkerVersion; -// A request handler derivative used to handle requests for, -// and requests from, controlled documents and shared workers. -// -// Note that in IsServicificationEnabled cases this is used only for -// main resource fetch during navigation or shared worker creation. +// Handles main resource requests for service worker clients (documents and +// shared workers). class CONTENT_EXPORT ServiceWorkerControlleeRequestHandler : public ServiceWorkerRequestHandler, public ServiceWorkerURLJobWrapper::Delegate { @@ -107,9 +104,6 @@ std::unique_ptr<ScopedDisallowSetControllerRegistration> disallow_controller); - // For sub resource case. - void PrepareForSubResource(); - // ServiceWorkerURLJobWrapper::Delegate implementation: void OnPrepareToRestart() override; ServiceWorkerVersion* GetServiceWorkerVersion( @@ -129,7 +123,6 @@ void MaybeScheduleUpdate(); const ResourceType resource_type_; - const bool is_main_resource_load_; std::unique_ptr<ServiceWorkerURLJobWrapper> url_job_; network::mojom::FetchRequestMode request_mode_; network::mojom::FetchCredentialsMode credentials_mode_;
diff --git a/content/browser/service_worker/service_worker_provider_host.cc b/content/browser/service_worker/service_worker_provider_host.cc index 5e4172a..35bce25 100644 --- a/content/browser/service_worker/service_worker_provider_host.cc +++ b/content/browser/service_worker/service_worker_provider_host.cc
@@ -622,25 +622,21 @@ // We only get here for main resource requests for service worker clients // (navigations, dedicated workers, and shared workers). DCHECK(!IsProviderForServiceWorker()); - - // TODO(falken): Add DCHECK(IsMainResourceType()) and remove the calls to it - // below. + DCHECK(ServiceWorkerUtils::IsMainResourceType(resource_type)); if (skip_service_worker) { - if (!ServiceWorkerUtils::IsMainResourceType(resource_type)) - return std::unique_ptr<ServiceWorkerRequestHandler>(); + // Use a request handler that just observes redirects so the resulting + // provider host can have the correct URL. + // TODO(falken): Just pass |skip_service_worker| to + // ServiceWorkerControlleeRequestHandler. return std::make_unique<ServiceWorkerURLTrackingRequestHandler>( context_, AsWeakPtr(), blob_storage_context, resource_type); } - if (ServiceWorkerUtils::IsMainResourceType(resource_type) || controller()) { - return std::make_unique<ServiceWorkerControlleeRequestHandler>( - context_, AsWeakPtr(), blob_storage_context, request_mode, - credentials_mode, redirect_mode, integrity, keepalive, resource_type, - request_context_type, frame_type, body); - } - - return std::unique_ptr<ServiceWorkerRequestHandler>(); + return std::make_unique<ServiceWorkerControlleeRequestHandler>( + context_, AsWeakPtr(), blob_storage_context, request_mode, + credentials_mode, redirect_mode, integrity, keepalive, resource_type, + request_context_type, frame_type, body); } base::WeakPtr<ServiceWorkerObjectHost>
diff --git a/content/browser/service_worker/service_worker_request_handler.cc b/content/browser/service_worker/service_worker_request_handler.cc index f742c0ac..ae6a418 100644 --- a/content/browser/service_worker/service_worker_request_handler.cc +++ b/content/browser/service_worker/service_worker_request_handler.cc
@@ -44,11 +44,8 @@ } // namespace // static -int ServiceWorkerRequestHandler::user_data_key_; - -// static std::unique_ptr<NavigationLoaderInterceptor> -ServiceWorkerRequestHandler::InitializeForNavigationNetworkService( +ServiceWorkerRequestHandler::InitializeForNavigation( const GURL& url, ResourceContext* resource_context, ServiceWorkerNavigationHandleCore* navigation_handle_core,
diff --git a/content/browser/service_worker/service_worker_request_handler.h b/content/browser/service_worker/service_worker_request_handler.h index 3cf10ff..c0663d3 100644 --- a/content/browser/service_worker/service_worker_request_handler.h +++ b/content/browser/service_worker/service_worker_request_handler.h
@@ -44,10 +44,7 @@ public: // Returns a loader interceptor for a navigation. May return nullptr // if the navigation cannot use service workers. - // TODO(falken): Rename to InitializeForNavigation since this also is called - // when NetworkService is disabled. - static std::unique_ptr<NavigationLoaderInterceptor> - InitializeForNavigationNetworkService( + static std::unique_ptr<NavigationLoaderInterceptor> InitializeForNavigation( const GURL& url, ResourceContext* resource_context, ServiceWorkerNavigationHandleCore* navigation_handle_core, @@ -86,8 +83,6 @@ ResourceType resource_type_; private: - static int user_data_key_; // Only address is used. - DISALLOW_COPY_AND_ASSIGN(ServiceWorkerRequestHandler); };
diff --git a/content/browser/service_worker/service_worker_request_handler_unittest.cc b/content/browser/service_worker/service_worker_request_handler_unittest.cc index 30b62bd0..c85ec1f 100644 --- a/content/browser/service_worker/service_worker_request_handler_unittest.cc +++ b/content/browser/service_worker/service_worker_request_handler_unittest.cc
@@ -77,7 +77,7 @@ CreateNavigationHandleCore(helper_->context_wrapper()); base::WeakPtr<ServiceWorkerProviderHost> service_worker_provider_host; std::unique_ptr<NavigationLoaderInterceptor> interceptor = - ServiceWorkerRequestHandler::InitializeForNavigationNetworkService( + ServiceWorkerRequestHandler::InitializeForNavigation( GURL(url), nullptr /* resource_context */, navigation_handle_core.get(), &blob_storage_context_, false /* skip_service_worker */, RESOURCE_TYPE_MAIN_FRAME,
diff --git a/content/browser/service_worker/service_worker_storage.cc b/content/browser/service_worker/service_worker_storage.cc index 53449a24..6c0de46d 100644 --- a/content/browser/service_worker/service_worker_storage.cc +++ b/content/browser/service_worker/service_worker_storage.cc
@@ -23,7 +23,7 @@ #include "content/common/service_worker/service_worker_types.h" #include "content/common/service_worker/service_worker_utils.h" #include "content/public/browser/browser_thread.h" -#include "net/base/completion_callback.h" +#include "net/base/completion_once_callback.h" #include "net/base/io_buffer.h" #include "net/base/net_errors.h" #include "storage/browser/quota/quota_manager_proxy.h" @@ -1721,7 +1721,8 @@ base::FilePath path = GetDiskCachePath(); if (path.empty()) { int rv = disk_cache_->InitWithMemBackend( - kMaxServiceWorkerStorageMemDiskCacheSize, net::CompletionCallback()); + kMaxServiceWorkerStorageMemDiskCacheSize, + net::CompletionOnceCallback()); DCHECK_EQ(net::OK, rv); return disk_cache_.get(); }
diff --git a/content/browser/service_worker/service_worker_version.cc b/content/browser/service_worker/service_worker_version.cc index 57989c8c..cf716c5 100644 --- a/content/browser/service_worker/service_worker_version.cc +++ b/content/browser/service_worker/service_worker_version.cc
@@ -529,11 +529,6 @@ weak_factory_.GetWeakPtr())); } -void ServiceWorkerVersion::DeferScheduledUpdate() { - if (update_timer_.IsRunning()) - update_timer_.Reset(); -} - int ServiceWorkerVersion::StartRequest( ServiceWorkerMetrics::EventType event_type, StatusCallback error_callback) {
diff --git a/content/browser/service_worker/service_worker_version.h b/content/browser/service_worker/service_worker_version.h index 3892721..03108d60 100644 --- a/content/browser/service_worker/service_worker_version.h +++ b/content/browser/service_worker/service_worker_version.h
@@ -271,10 +271,6 @@ // Schedules an update to be run 'soon'. void ScheduleUpdate(); - // If an update is scheduled but not yet started, this resets the timer - // delaying the start time by a 'small' amount. - void DeferScheduledUpdate(); - // Starts an update now. void StartUpdate();
diff --git a/content/browser/tracing/background_tracing_active_scenario.cc b/content/browser/tracing/background_tracing_active_scenario.cc new file mode 100644 index 0000000..259b0a0 --- /dev/null +++ b/content/browser/tracing/background_tracing_active_scenario.cc
@@ -0,0 +1,408 @@ +// 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 "content/browser/tracing/background_tracing_active_scenario.h" + +#include <set> +#include <utility> + +#include "base/memory/ref_counted_memory.h" +#include "base/metrics/histogram_macros.h" +#include "base/rand_util.h" +#include "base/timer/timer.h" +#include "build/build_config.h" +#include "content/browser/tracing/background_tracing_config_impl.h" +#include "content/browser/tracing/background_tracing_manager_impl.h" +#include "content/browser/tracing/background_tracing_rule.h" +#include "content/browser/tracing/tracing_controller_impl.h" +#include "services/tracing/public/cpp/perfetto/trace_event_data_source.h" +#include "services/tracing/public/cpp/tracing_features.h" + +using base::trace_event::TraceConfig; +using Metrics = content::BackgroundTracingManagerImpl::Metrics; + +namespace content { + +class BackgroundTracingActiveScenario::TracingTimer { + public: + TracingTimer(BackgroundTracingActiveScenario* scenario, + BackgroundTracingManager::StartedFinalizingCallback callback) + : scenario_(scenario), callback_(callback) {} + ~TracingTimer() = default; + + void StartTimer(int seconds) { + tracing_timer_.Start(FROM_HERE, base::TimeDelta::FromSeconds(seconds), this, + &TracingTimer::TracingTimerFired); + } + void CancelTimer() { tracing_timer_.Stop(); } + + void FireTimerForTesting() { + CancelTimer(); + TracingTimerFired(); + } + + private: + void TracingTimerFired() { scenario_->BeginFinalizing(callback_); } + + BackgroundTracingActiveScenario* scenario_; + base::OneShotTimer tracing_timer_; + BackgroundTracingManager::StartedFinalizingCallback callback_; +}; + +BackgroundTracingActiveScenario::BackgroundTracingActiveScenario( + std::unique_ptr<const BackgroundTracingConfigImpl> config, + bool requires_anonymized_data, + BackgroundTracingManager::ReceiveCallback receive_callback, + base::OnceClosure on_aborted_callback) + : config_(std::move(config)), + requires_anonymized_data_(requires_anonymized_data), + scenario_state_(State::kIdle), + receive_callback_(std::move(receive_callback)), + triggered_named_event_handle_(-1), + on_aborted_callback_(std::move(on_aborted_callback)), + weak_ptr_factory_(this) { + DCHECK(config_ && !config_->rules().empty()); + for (const auto& rule : config_->rules()) { + rule->Install(); + } +} + +BackgroundTracingActiveScenario::~BackgroundTracingActiveScenario() = default; + +const BackgroundTracingConfigImpl* BackgroundTracingActiveScenario::GetConfig() + const { + return config_.get(); +} + +void BackgroundTracingActiveScenario::SetState(State new_state) { + auto old_state = scenario_state_; + scenario_state_ = new_state; + + if ((old_state == State::kTracing) && + base::trace_event::TraceLog::GetInstance()->IsEnabled()) { + // Leaving the kTracing state means we're supposed to have fully + // shut down tracing at this point. Since StartTracing directly enables + // tracing in TraceLog, in addition to going through Mojo, there's an + // edge-case where tracing is rapidly stopped after starting, too quickly + // for the TraceEventAgent of the browser process to register itself, + // which means that we're left in a state where the Mojo interface doesn't + // think we're tracing but TraceLog is still enabled. If that's the case, + // we abort tracing here. + auto record_mode = + (config_->tracing_mode() == BackgroundTracingConfigImpl::PREEMPTIVE) + ? base::trace_event::RECORD_CONTINUOUSLY + : base::trace_event::RECORD_UNTIL_FULL; + TraceConfig config = + BackgroundTracingConfigImpl::GetConfigForCategoryPreset( + config_->category_preset(), record_mode); + + uint8_t modes = base::trace_event::TraceLog::RECORDING_MODE; + if (!config.event_filters().empty()) + modes |= base::trace_event::TraceLog::FILTERING_MODE; + base::trace_event::TraceLog::GetInstance()->SetDisabled(modes); + } + + if (scenario_state_ == State::kAborted) { + std::move(on_aborted_callback_).Run(); + } +} + +void BackgroundTracingActiveScenario::FireTimerForTesting() { + DCHECK(tracing_timer_); + tracing_timer_->FireTimerForTesting(); +} + +void BackgroundTracingActiveScenario::SetRuleTriggeredCallbackForTesting( + const base::RepeatingClosure& callback) { + rule_triggered_callback_for_testing_ = callback; +} + +void BackgroundTracingActiveScenario::StartTracingIfConfigNeedsIt() { + DCHECK(config_); + if (config_->tracing_mode() == BackgroundTracingConfigImpl::PREEMPTIVE) { + StartTracing(config_->category_preset(), + base::trace_event::RECORD_CONTINUOUSLY); + return; + } + + // There is nothing to do in case of reactive tracing. +} + +void BackgroundTracingActiveScenario::StartTracing( + BackgroundTracingConfigImpl::CategoryPreset preset, + base::trace_event::TraceRecordMode record_mode) { + TraceConfig config = BackgroundTracingConfigImpl::GetConfigForCategoryPreset( + preset, record_mode); + if (requires_anonymized_data_) + config.EnableArgumentFilter(); +#if defined(OS_ANDROID) + // Set low trace buffer size on Android in order to upload small trace files. + if (config_->tracing_mode() == BackgroundTracingConfigImpl::PREEMPTIVE) { + config.SetTraceBufferSizeInEvents(20000); + config.SetTraceBufferSizeInKb(500); + } +#endif + + if (!TracingControllerImpl::GetInstance()->IsTracing() && + tracing::TracingUsesPerfettoBackend()) { + tracing::TraceEventDataSource::GetInstance()->SetupStartupTracing(); + } + + if (!TracingControllerImpl::GetInstance()->StartTracing( + config, + base::BindOnce( + &BackgroundTracingManagerImpl::OnStartTracingDone, + base::Unretained(BackgroundTracingManagerImpl::GetInstance()), + preset))) { + AbortScenario(); + return; + } + + SetState(State::kTracing); + + // Activate the categories immediately. StartTracing eventually does this + // itself, but asynchronously via PostTask, and in the meantime events will be + // dropped. This ensures that we start recording events for those categories + // immediately. + uint8_t modes = base::trace_event::TraceLog::RECORDING_MODE; + if (!config.event_filters().empty()) + modes |= base::trace_event::TraceLog::FILTERING_MODE; + base::trace_event::TraceLog::GetInstance()->SetEnabled(config, modes); + + BackgroundTracingManagerImpl::RecordMetric(Metrics::RECORDING_ENABLED); +} + +void BackgroundTracingActiveScenario::BeginFinalizing( + BackgroundTracingManager::StartedFinalizingCallback callback) { + triggered_named_event_handle_ = -1; + tracing_timer_.reset(); + + scoped_refptr<TracingControllerImpl::TraceDataEndpoint> trace_data_endpoint; + bool is_allowed_finalization = + BackgroundTracingManagerImpl::GetInstance()->IsAllowedFinalization(); + base::RepeatingClosure started_finalizing_closure; + if (!callback.is_null()) { + started_finalizing_closure = + base::BindRepeating(callback, is_allowed_finalization); + } + + if (is_allowed_finalization) { + trace_data_endpoint = TracingControllerImpl::CreateCompressedStringEndpoint( + TracingControllerImpl::CreateCallbackEndpoint(base::BindRepeating( + &BackgroundTracingActiveScenario::OnTracingStopped, + weak_ptr_factory_.GetWeakPtr(), + std::move(started_finalizing_closure))), + true /* compress_with_background_priority */); + BackgroundTracingManagerImpl::RecordMetric(Metrics::FINALIZATION_ALLOWED); + } else { + trace_data_endpoint = + TracingControllerImpl::CreateCallbackEndpoint(base::BindRepeating( + [](base::RepeatingClosure closure, + base::WeakPtr<BackgroundTracingActiveScenario> active_scenario, + std::unique_ptr<const base::DictionaryValue> metadata, + base::RefCountedString* file_contents) { + if (active_scenario) { + active_scenario->SetState(State::kAborted); + } + + if (closure) { + std::move(closure).Run(); + } + }, + std::move(started_finalizing_closure), + weak_ptr_factory_.GetWeakPtr())); + BackgroundTracingManagerImpl::RecordMetric( + Metrics::FINALIZATION_DISALLOWED); + } + + TracingControllerImpl::GetInstance()->StopTracing(trace_data_endpoint); +} + +void BackgroundTracingActiveScenario::OnTracingStopped( + base::RepeatingClosure started_finalizing_closure, + std::unique_ptr<const base::DictionaryValue> metadata, + base::RefCountedString* file_contents) { + SetState(State::kFinalizing); + BackgroundTracingManagerImpl::RecordMetric(Metrics::FINALIZATION_STARTED); + UMA_HISTOGRAM_MEMORY_KB("Tracing.Background.FinalizingTraceSizeInKB", + file_contents->size() / 1024); + + if (!receive_callback_.is_null()) { + receive_callback_.Run( + file_contents, std::move(metadata), + base::BindOnce(&BackgroundTracingActiveScenario::OnFinalizeComplete, + weak_ptr_factory_.GetWeakPtr())); + } + + if (!started_finalizing_closure.is_null()) { + std::move(started_finalizing_closure).Run(); + } +} + +void BackgroundTracingActiveScenario::OnFinalizeComplete(bool success) { + if (success) { + BackgroundTracingManagerImpl::RecordMetric(Metrics::UPLOAD_SUCCEEDED); + } else { + BackgroundTracingManagerImpl::RecordMetric(Metrics::UPLOAD_FAILED); + } + + SetState(State::kIdle); + + // Now that a trace has completed, we may need to enable recording again. + StartTracingIfConfigNeedsIt(); +} + +void BackgroundTracingActiveScenario::AbortScenario() { + if ((state() != State::kTracing)) { + // Setting the kAborted state will cause |this| to be destroyed. + SetState(State::kAborted); + return; + } + + auto trace_data_endpoint = + TracingControllerImpl::CreateCallbackEndpoint(base::BindRepeating( + [](base::WeakPtr<BackgroundTracingActiveScenario> active_scenario, + std::unique_ptr<const base::DictionaryValue>, + base::RefCountedString*) { + if (active_scenario) { + active_scenario->SetState(State::kAborted); + } + }, + weak_ptr_factory_.GetWeakPtr())); + + TracingControllerImpl::GetInstance()->StopTracing(trace_data_endpoint); +} + +void BackgroundTracingActiveScenario::TriggerNamedEvent( + BackgroundTracingManager::TriggerHandle handle, + BackgroundTracingManager::StartedFinalizingCallback callback) { + std::string trigger_name = + BackgroundTracingManagerImpl::GetInstance()->GetTriggerNameFromHandle( + handle); + auto* triggered_rule = GetRuleAbleToTriggerTracing(trigger_name); + if (!triggered_rule) { + if (!callback.is_null()) { + std::move(callback).Run(false); + } + return; + } + + // A different reactive config than the running one tried to trigger. + if ((config_->tracing_mode() == BackgroundTracingConfigImpl::REACTIVE && + (state() == State::kTracing) && + triggered_named_event_handle_ != handle)) { + if (!callback.is_null()) { + std::move(callback).Run(false); + } + return; + } + + triggered_named_event_handle_ = handle; + OnRuleTriggered(triggered_rule, std::move(callback)); +} + +void BackgroundTracingActiveScenario::OnHistogramTrigger( + const std::string& histogram_name) { + for (const auto& rule : config_->rules()) { + if (rule->ShouldTriggerNamedEvent(histogram_name)) { + OnRuleTriggered(rule.get(), + BackgroundTracingManager::StartedFinalizingCallback()); + } + } +} + +void BackgroundTracingActiveScenario::OnRuleTriggered( + const BackgroundTracingRule* triggered_rule, + BackgroundTracingManager::StartedFinalizingCallback callback) { + double trigger_chance = triggered_rule->trigger_chance(); + if (trigger_chance < 1.0 && base::RandDouble() > trigger_chance) { + if (!callback.is_null()) { + std::move(callback).Run(false); + } + return; + } + + last_triggered_rule_.reset(new base::DictionaryValue); + triggered_rule->IntoDict(last_triggered_rule_.get()); + + int trace_delay = triggered_rule->GetTraceDelay(); + + if (config_->tracing_mode() == BackgroundTracingConfigImpl::REACTIVE) { + // In reactive mode, a trigger starts tracing, or finalizes tracing + // immediately if it's already running. + BackgroundTracingManagerImpl::RecordMetric(Metrics::REACTIVE_TRIGGERED); + + if (state() != State::kTracing) { + // It was not already tracing, start a new trace. + StartTracing(triggered_rule->category_preset(), + base::trace_event::RECORD_UNTIL_FULL); + } else { + // Some reactive configs that trigger again while tracing should just + // end right away (to not capture multiple navigations, for example). + // For others we just want to ignore the repeated trigger. + if (triggered_rule->stop_tracing_on_repeated_reactive()) { + trace_delay = -1; + } else { + if (!callback.is_null()) { + std::move(callback).Run(false); + } + return; + } + } + } else { + // In preemptive mode, a trigger starts finalizing a trace if one is + // running and we haven't got a finalization timer running, + // otherwise we do nothing. + if ((state() != State::kTracing) || tracing_timer_) { + if (!callback.is_null()) { + std::move(callback).Run(false); + } + return; + } + + BackgroundTracingManagerImpl::RecordMetric(Metrics::PREEMPTIVE_TRIGGERED); + } + + if (trace_delay < 0) { + BeginFinalizing(std::move(callback)); + } else { + tracing_timer_ = std::make_unique<TracingTimer>(this, std::move(callback)); + tracing_timer_->StartTimer(trace_delay); + } + + if (!rule_triggered_callback_for_testing_.is_null()) { + rule_triggered_callback_for_testing_.Run(); + } +} + +BackgroundTracingRule* +BackgroundTracingActiveScenario::GetRuleAbleToTriggerTracing( + const std::string& trigger_name) { + // If the last trace is still uploading, we don't allow a new one to trigger. + if (state() == State::kFinalizing) { + return nullptr; + } + + for (const auto& rule : config_->rules()) { + if (rule->ShouldTriggerNamedEvent(trigger_name)) { + return rule.get(); + } + } + + return nullptr; +} + +void BackgroundTracingActiveScenario::GenerateMetadataDict( + base::DictionaryValue* metadata_dict) { + auto config_dict = std::make_unique<base::DictionaryValue>(); + config_->IntoDict(config_dict.get()); + metadata_dict->Set("config", std::move(config_dict)); + metadata_dict->SetString("scenario_name", config_->scenario_name()); + + if (last_triggered_rule_) { + metadata_dict->Set("last_triggered_rule", std::move(last_triggered_rule_)); + } +} + +} // namespace content
diff --git a/content/browser/tracing/background_tracing_active_scenario.h b/content/browser/tracing/background_tracing_active_scenario.h new file mode 100644 index 0000000..8c1aaaa --- /dev/null +++ b/content/browser/tracing/background_tracing_active_scenario.h
@@ -0,0 +1,92 @@ +// 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 CONTENT_BROWSER_TRACING_BACKGROUND_TRACING_ACTIVE_SCENARIO_H_ +#define CONTENT_BROWSER_TRACING_BACKGROUND_TRACING_ACTIVE_SCENARIO_H_ + +#include <memory> +#include <string> + +#include "base/macros.h" +#include "base/memory/weak_ptr.h" +#include "content/browser/tracing/background_tracing_config_impl.h" +#include "content/public/browser/background_tracing_manager.h" + +namespace base { +class RefCountedString; +} // namespace base + +namespace content { + +class BackgroundTracingConfigImpl; + +class BackgroundTracingActiveScenario { + public: + enum class State { kIdle, kTracing, kFinalizing, kUploading, kAborted }; + + BackgroundTracingActiveScenario( + std::unique_ptr<const BackgroundTracingConfigImpl> config, + bool requires_anonymized_data, + BackgroundTracingManager::ReceiveCallback receive_callback, + base::OnceClosure on_aborted_callback); + ~BackgroundTracingActiveScenario(); + + void StartTracingIfConfigNeedsIt(); + void AbortScenario(); + + const BackgroundTracingConfigImpl* GetConfig() const; + void GenerateMetadataDict(base::DictionaryValue* metadata_dict); + State state() const { return scenario_state_; } + bool requires_anonymized_data() const { return requires_anonymized_data_; } + + void TriggerNamedEvent( + BackgroundTracingManager::TriggerHandle handle, + BackgroundTracingManager::StartedFinalizingCallback callback); + void OnHistogramTrigger(const std::string& histogram_name); + void OnRuleTriggered( + const BackgroundTracingRule* triggered_rule, + BackgroundTracingManager::StartedFinalizingCallback callback); + + // For testing + CONTENT_EXPORT void FireTimerForTesting(); + CONTENT_EXPORT void SetRuleTriggeredCallbackForTesting( + const base::RepeatingClosure& callback); + + private: + void StartTracing(BackgroundTracingConfigImpl::CategoryPreset, + base::trace_event::TraceRecordMode); + + void BeginFinalizing( + BackgroundTracingManager::StartedFinalizingCallback callback); + void OnTracingStopped(base::RepeatingClosure started_finalizing_closure, + std::unique_ptr<const base::DictionaryValue> metadata, + base::RefCountedString*); + + void OnFinalizeComplete(bool success); + + BackgroundTracingRule* GetRuleAbleToTriggerTracing( + const std::string& trigger_name); + + void SetState(State new_state); + + std::unique_ptr<const BackgroundTracingConfigImpl> config_; + bool requires_anonymized_data_; + State scenario_state_; + std::unique_ptr<base::DictionaryValue> last_triggered_rule_; + base::RepeatingClosure rule_triggered_callback_for_testing_; + BackgroundTracingManager::ReceiveCallback receive_callback_; + BackgroundTracingManager::TriggerHandle triggered_named_event_handle_; + base::OnceClosure on_aborted_callback_; + + class TracingTimer; + std::unique_ptr<TracingTimer> tracing_timer_; + + // NOTE: Weak pointers must be invalidated before all other member variables. + base::WeakPtrFactory<BackgroundTracingActiveScenario> weak_ptr_factory_; + DISALLOW_COPY_AND_ASSIGN(BackgroundTracingActiveScenario); +}; + +} // namespace content + +#endif // CONTENT_BROWSER_TRACING_BACKGROUND_TRACING_ACTIVE_SCENARIO_H_
diff --git a/content/browser/tracing/background_tracing_config_impl.cc b/content/browser/tracing/background_tracing_config_impl.cc index e33c569..eb65789 100644 --- a/content/browser/tracing/background_tracing_config_impl.cc +++ b/content/browser/tracing/background_tracing_config_impl.cc
@@ -4,12 +4,16 @@ #include "content/browser/tracing/background_tracing_config_impl.h" +#include <set> #include <utility> #include "base/macros.h" #include "base/values.h" +#include "components/tracing/common/trace_startup_config.h" #include "content/browser/tracing/background_tracing_rule.h" +using base::trace_event::TraceConfig; + namespace content { namespace { @@ -21,8 +25,6 @@ const char kConfigModeReactive[] = "REACTIVE_TRACING_MODE"; const char kConfigScenarioName[] = "scenario_name"; -const char kConfigEnableBlinkFeatures[] = "enable_blink_features"; -const char kConfigDisableBlinkFeatures[] = "disable_blink_features"; const char kConfigCategoryKey[] = "category"; const char kConfigCategoryBenchmark[] = "BENCHMARK"; @@ -50,6 +52,7 @@ BackgroundTracingConfigImpl::~BackgroundTracingConfigImpl() {} +// static std::string BackgroundTracingConfigImpl::CategoryPresetToString( BackgroundTracingConfigImpl::CategoryPreset category_preset) { switch (category_preset) { @@ -88,6 +91,7 @@ return ""; } +// static bool BackgroundTracingConfigImpl::StringToCategoryPreset( const std::string& category_preset_string, BackgroundTracingConfigImpl::CategoryPreset* category_preset) { @@ -189,10 +193,6 @@ if (!scenario_name_.empty()) dict->SetString(kConfigScenarioName, scenario_name_); - if (!enable_blink_features_.empty()) - dict->SetString(kConfigEnableBlinkFeatures, enable_blink_features_); - if (!disable_blink_features_.empty()) - dict->SetString(kConfigDisableBlinkFeatures, disable_blink_features_); } void BackgroundTracingConfigImpl::AddPreemptiveRule( @@ -214,6 +214,7 @@ } } +// static std::unique_ptr<BackgroundTracingConfigImpl> BackgroundTracingConfigImpl::FromDict(const base::DictionaryValue* dict) { DCHECK(dict); @@ -234,15 +235,12 @@ if (config) { dict->GetString(kConfigScenarioName, &config->scenario_name_); - dict->GetString(kConfigEnableBlinkFeatures, - &config->enable_blink_features_); - dict->GetString(kConfigDisableBlinkFeatures, - &config->disable_blink_features_); } return config; } +// static std::unique_ptr<BackgroundTracingConfigImpl> BackgroundTracingConfigImpl::PreemptiveFromDict( const base::DictionaryValue* dict) { @@ -277,6 +275,7 @@ return config; } +// static std::unique_ptr<BackgroundTracingConfigImpl> BackgroundTracingConfigImpl::ReactiveFromDict( const base::DictionaryValue* dict) { @@ -311,4 +310,90 @@ return config; } +// static +TraceConfig BackgroundTracingConfigImpl::GetConfigForCategoryPreset( + BackgroundTracingConfigImpl::CategoryPreset preset, + base::trace_event::TraceRecordMode record_mode) { + switch (preset) { + case BackgroundTracingConfigImpl::CategoryPreset::BENCHMARK: + return TraceConfig("benchmark,toplevel", record_mode); + case BackgroundTracingConfigImpl::CategoryPreset::BENCHMARK_DEEP: + return TraceConfig( + "*,disabled-by-default-benchmark.detailed," + "disabled-by-default-v8.cpu_profile," + "disabled-by-default-v8.runtime_stats", + record_mode); + case BackgroundTracingConfigImpl::CategoryPreset::BENCHMARK_GPU: + return TraceConfig( + "benchmark,toplevel,gpu,base,mojom,ipc," + "disabled-by-default-system_stats,disabled-by-default-cpu_profiler", + record_mode); + case BackgroundTracingConfigImpl::CategoryPreset::BENCHMARK_IPC: + return TraceConfig("benchmark,toplevel,ipc", record_mode); + case BackgroundTracingConfigImpl::CategoryPreset::BENCHMARK_STARTUP: { + auto config = + tracing::TraceStartupConfig::GetDefaultBrowserStartupConfig(); + config.SetTraceRecordMode(record_mode); + return config; + } + case BackgroundTracingConfigImpl::CategoryPreset::BENCHMARK_BLINK_GC: + return TraceConfig("blink_gc,disabled-by-default-blink_gc", record_mode); + case BackgroundTracingConfigImpl::CategoryPreset:: + BENCHMARK_EXECUTION_METRIC: + return TraceConfig("blink.console,v8", record_mode); + case BackgroundTracingConfigImpl::CategoryPreset::BENCHMARK_NAVIGATION: { + auto config = TraceConfig( + "benchmark,toplevel,ipc,base,browser,navigation,omnibox,ui,shutdown," + "safe_browsing,Java,EarlyJava,loading,startup,mojom,renderer_host," + "disabled-by-default-system_stats,disabled-by-default-cpu_profiler," + "dwrite,fonts", + record_mode); + // Filter only browser process events. + base::trace_event::TraceConfig::ProcessFilterConfig process_config( + {base::GetCurrentProcId()}); + config.SetProcessFilterConfig(process_config); + return config; + } + case BackgroundTracingConfigImpl::CategoryPreset::BENCHMARK_RENDERERS: + return TraceConfig( + "benchmark,toplevel,ipc,base,ui,v8,renderer,blink,blink_gc,mojom," + "latency,latencyInfo,renderer_host,cc,memory,dwrite,fonts," + "disabled-by-default-v8.gc," + "disabled-by-default-blink_gc," + "disabled-by-default-renderer.scheduler," + "disabled-by-default-system_stats,disabled-by-default-cpu_profiler", + record_mode); + case BackgroundTracingConfigImpl::CategoryPreset::BENCHMARK_SERVICEWORKER: + return TraceConfig( + "benchmark,toplevel,ipc,base,ServiceWorker,CacheStorage,Blob," + "loader,loading,navigation,blink.user_timing," + "disabled-by-default-network", + record_mode); + case BackgroundTracingConfigImpl::CategoryPreset::BENCHMARK_POWER: + return TraceConfig( + "benchmark,toplevel,ipc,base,audio,compositor,gpu,media,memory,midi," + "native,omnibox,renderer,skia,task_scheduler,ui,v8,views,webaudio", + record_mode); + case BackgroundTracingConfigImpl::CategoryPreset::BLINK_STYLE: + return TraceConfig("blink_style", record_mode); + + case BackgroundTracingConfigImpl::CategoryPreset::BENCHMARK_MEMORY_HEAVY: + return TraceConfig("-*,disabled-by-default-memory-infra", record_mode); + case BackgroundTracingConfigImpl::CategoryPreset::BENCHMARK_MEMORY_LIGHT: { + // On memory light mode, the periodic memory dumps are disabled. + base::trace_event::TraceConfig::MemoryDumpConfig memory_config; + memory_config.allowed_dump_modes = + std::set<base::trace_event::MemoryDumpLevelOfDetail>( + {base::trace_event::MemoryDumpLevelOfDetail::BACKGROUND}); + TraceConfig config("-*,disabled-by-default-memory-infra", record_mode); + config.ResetMemoryDumpConfig(memory_config); + return config; + } + case BackgroundTracingConfigImpl::CategoryPreset::CATEGORY_PRESET_UNSET: + NOTREACHED(); + } + NOTREACHED(); + return TraceConfig(); +} + } // namespace content
diff --git a/content/browser/tracing/background_tracing_config_impl.h b/content/browser/tracing/background_tracing_config_impl.h index f13f5d2..9abb311a 100644 --- a/content/browser/tracing/background_tracing_config_impl.h +++ b/content/browser/tracing/background_tracing_config_impl.h
@@ -6,10 +6,12 @@ #define CONTENT_BROWSER_TRACING_BACKGROUND_TRACING_CONFIG_IMPL_H_ #include <memory> +#include <string> #include <vector> #include "base/gtest_prod_util.h" #include "base/macros.h" +#include "base/trace_event/trace_config.h" #include "content/common/content_export.h" #include "content/public/browser/background_tracing_config.h" @@ -53,12 +55,6 @@ return rules_; } const std::string& scenario_name() const { return scenario_name_; } - const std::string& enable_blink_features() const { - return enable_blink_features_; - } - const std::string& disable_blink_features() const { - return disable_blink_features_; - } void AddPreemptiveRule(const base::DictionaryValue* dict); void AddReactiveRule( @@ -79,6 +75,10 @@ const std::string& category_preset_string, BackgroundTracingConfigImpl::CategoryPreset* category_preset); + static base::trace_event::TraceConfig GetConfigForCategoryPreset( + BackgroundTracingConfigImpl::CategoryPreset, + base::trace_event::TraceRecordMode); + private: FRIEND_TEST_ALL_PREFIXES(BackgroundTracingConfigTest, ValidPreemptiveConfigToString); @@ -86,8 +86,6 @@ CategoryPreset category_preset_; std::vector<std::unique_ptr<BackgroundTracingRule>> rules_; std::string scenario_name_; - std::string enable_blink_features_; - std::string disable_blink_features_; DISALLOW_COPY_AND_ASSIGN(BackgroundTracingConfigImpl); };
diff --git a/content/browser/tracing/background_tracing_config_unittest.cc b/content/browser/tracing/background_tracing_config_unittest.cc index 744ea23b..a535f36 100644 --- a/content/browser/tracing/background_tracing_config_unittest.cc +++ b/content/browser/tracing/background_tracing_config_unittest.cc
@@ -256,17 +256,6 @@ EXPECT_EQ(RuleToString(config->rules()[1]), "{\"rule\":\"MONITOR_AND_DUMP_WHEN_TRIGGER_NAMED\"," "\"trigger_name\":\"foo2\"}"); - - config = ReadFromJSONString( - "{\"category\":\"BENCHMARK_DEEP\",\"configs\":[{\"rule\":" - "\"MONITOR_AND_DUMP_WHEN_TRIGGER_NAMED\",\"trigger_name\":" - "\"foo1\"}],\"disable_blink_features\":\"SlowerWeb1,SlowerWeb2\"," - "\"enable_blink_features\":\"FasterWeb1,FasterWeb2\"," - "\"mode\":\"PREEMPTIVE_TRACING_MODE\"," - "\"scenario_name\":\"my_awesome_experiment\"}"); - EXPECT_EQ(config->enable_blink_features(), "FasterWeb1,FasterWeb2"); - EXPECT_EQ(config->disable_blink_features(), "SlowerWeb1,SlowerWeb2"); - EXPECT_EQ(config->scenario_name(), "my_awesome_experiment"); } TEST_F(BackgroundTracingConfigTest, ValidPreemptiveCategoryToString) { @@ -513,29 +502,6 @@ "SPECIFIC_HISTOGRAM_AND_VALUE\",\"trigger_delay\":10}],\"mode\":" "\"PREEMPTIVE_TRACING_MODE\"}"); } - - { - config.reset( - new BackgroundTracingConfigImpl(BackgroundTracingConfig::PREEMPTIVE)); - config->set_category_preset(BackgroundTracingConfigImpl::BENCHMARK_DEEP); - - std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue()); - dict->SetString("rule", "MONITOR_AND_DUMP_WHEN_TRIGGER_NAMED"); - dict->SetString("trigger_name", "foo1"); - config->AddPreemptiveRule(dict.get()); - - config->scenario_name_ = "my_awesome_experiment"; - config->enable_blink_features_ = "FasterWeb1,FasterWeb2"; - config->disable_blink_features_ = "SlowerWeb1,SlowerWeb2"; - - EXPECT_EQ(ConfigToString(config.get()), - "{\"category\":\"BENCHMARK_DEEP\",\"configs\":[{\"rule\":" - "\"MONITOR_AND_DUMP_WHEN_TRIGGER_NAMED\",\"trigger_name\":" - "\"foo1\"}],\"disable_blink_features\":\"SlowerWeb1,SlowerWeb2\"," - "\"enable_blink_features\":\"FasterWeb1,FasterWeb2\"," - "\"mode\":\"PREEMPTIVE_TRACING_MODE\"," - "\"scenario_name\":\"my_awesome_experiment\"}"); - } } TEST_F(BackgroundTracingConfigTest, InvalidPreemptiveConfigToString) {
diff --git a/content/browser/tracing/background_tracing_manager_browsertest.cc b/content/browser/tracing/background_tracing_manager_browsertest.cc index 067cae31..20cf874 100644 --- a/content/browser/tracing/background_tracing_manager_browsertest.cc +++ b/content/browser/tracing/background_tracing_manager_browsertest.cc
@@ -18,6 +18,7 @@ #include "base/task/post_task.h" #include "base/trace_event/trace_event.h" #include "content/browser/tracing/background_startup_tracing_observer.h" +#include "content/browser/tracing/background_tracing_active_scenario.h" #include "content/browser/tracing/background_tracing_manager_impl.h" #include "content/browser/tracing/background_tracing_rule.h" #include "content/public/browser/browser_task_traits.h" @@ -121,17 +122,17 @@ void OnScenarioActivated(const BackgroundTracingConfigImpl* config) override { is_scenario_active_ = true; - wait_for_scenario_activated_.QuitWhenIdle(); + wait_for_scenario_activated_.Quit(); } void OnScenarioAborted() override { is_scenario_active_ = false; - wait_for_scenario_aborted_.QuitWhenIdle(); + wait_for_scenario_aborted_.Quit(); } void OnTracingEnabled( BackgroundTracingConfigImpl::CategoryPreset preset) override { - wait_for_tracing_enabled_.QuitWhenIdle(); + wait_for_tracing_enabled_.Quit(); } void WaitForScenarioActivated() { wait_for_scenario_activated_.Run(); } @@ -183,8 +184,8 @@ z_stream stream = {nullptr}; stream.avail_in = compressed_length; stream.avail_out = kOutputBufferLength; - stream.next_in = (Bytef*)&file_contents->data()[0]; - stream.next_out = (Bytef*)output_str.data(); + stream.next_in = reinterpret_cast<Bytef*>(&file_contents->data()[0]); + stream.next_out = reinterpret_cast<Bytef*>(output_str.data()); // 16 + MAX_WBITS means only decoding gzip encoded streams, and using // the biggest window size, according to zlib.h @@ -275,7 +276,7 @@ BackgroundTracingManagerBrowserTest() {} void PreRunTestOnMainThread() override { - content::BackgroundTracingManager::GetInstance() + BackgroundTracingManagerImpl::GetInstance() ->InvalidateTriggerHandlesForTesting(); ContentBrowserTest::PreRunTestOnMainThread(); @@ -332,10 +333,6 @@ return config; } -void DisableScenarioWhenIdle() { - BackgroundTracingManager::GetInstance()->AbortScenario(); -} - // This tests that the endpoint receives the final trace data. IN_PROC_BROWSER_TEST_F(BackgroundTracingManagerBrowserTest, ReceiveTraceFinalContentsOnTrigger) { @@ -348,9 +345,6 @@ BackgroundTracingManager::GetInstance()->RegisterTriggerType( "preemptive_test"); - BackgroundTracingManager::GetInstance()->WhenIdle( - base::BindRepeating(&DisableScenarioWhenIdle)); - EXPECT_TRUE(BackgroundTracingManager::GetInstance()->SetActiveScenario( std::move(config), trace_receiver_helper.get_receive_callback(), BackgroundTracingManager::NO_DATA_FILTERING)); @@ -362,6 +356,7 @@ handle, trigger_helper.receive_closure(true)); trace_receiver_helper.WaitForTraceReceived(); + BackgroundTracingManager::GetInstance()->AbortScenario(); background_tracing_helper.WaitForScenarioAborted(); EXPECT_TRUE(trace_receiver_helper.trace_received()); @@ -379,9 +374,6 @@ content::BackgroundTracingManager::GetInstance()->RegisterTriggerType( "preemptive_test"); - BackgroundTracingManager::GetInstance()->WhenIdle( - base::BindRepeating(&DisableScenarioWhenIdle)); - EXPECT_TRUE(BackgroundTracingManager::GetInstance()->SetActiveScenario( std::move(config), trace_receiver_helper.get_receive_callback(), BackgroundTracingManager::NO_DATA_FILTERING)); @@ -395,6 +387,7 @@ handle, trigger_helper.receive_closure(false)); trace_receiver_helper.WaitForTraceReceived(); + BackgroundTracingManager::GetInstance()->AbortScenario(); background_tracing_helper.WaitForScenarioAborted(); EXPECT_TRUE(trace_receiver_helper.trace_received()); @@ -412,9 +405,6 @@ content::BackgroundTracingManager::GetInstance()->RegisterTriggerType( "preemptive_test"); - BackgroundTracingManager::GetInstance()->WhenIdle( - base::BindRepeating(&DisableScenarioWhenIdle)); - EXPECT_TRUE(BackgroundTracingManager::GetInstance()->SetActiveScenario( std::move(config), trace_receiver_helper.get_receive_callback(), BackgroundTracingManager::ANONYMIZE_DATA)); @@ -431,6 +421,7 @@ trigger_helper.WaitForTriggerReceived(); trace_receiver_helper.WaitForTraceReceived(); + BackgroundTracingManager::GetInstance()->AbortScenario(); background_tracing_helper.WaitForScenarioAborted(); EXPECT_TRUE(trace_receiver_helper.trace_received()); @@ -456,9 +447,6 @@ content::BackgroundTracingManager::GetInstance()->RegisterTriggerType( "preemptive_test"); - BackgroundTracingManager::GetInstance()->WhenIdle( - base::BindRepeating(&DisableScenarioWhenIdle)); - EXPECT_TRUE(BackgroundTracingManager::GetInstance()->SetActiveScenario( std::move(config), trace_receiver_helper.get_receive_callback(), BackgroundTracingManager::ANONYMIZE_DATA)); @@ -473,6 +461,7 @@ trigger_helper.WaitForTriggerReceived(); trace_receiver_helper.WaitForTraceReceived(); + BackgroundTracingManager::GetInstance()->AbortScenario(); background_tracing_helper.WaitForScenarioAborted(); EXPECT_TRUE(trace_receiver_helper.trace_received()); @@ -492,9 +481,6 @@ content::BackgroundTracingManager::GetInstance()->RegisterTriggerType( "preemptive_test"); - BackgroundTracingManager::GetInstance()->WhenIdle( - base::BindRepeating(&DisableScenarioWhenIdle)); - EXPECT_TRUE(BackgroundTracingManager::GetInstance()->SetActiveScenario( std::move(config), trace_receiver_helper.get_receive_callback(), BackgroundTracingManager::ANONYMIZE_DATA)); @@ -506,6 +492,7 @@ handle, trigger_helper.receive_closure(true)); trace_receiver_helper.WaitForTraceReceived(); + BackgroundTracingManager::GetInstance()->AbortScenario(); background_tracing_helper.WaitForScenarioAborted(); EXPECT_TRUE(trace_receiver_helper.trace_received()); @@ -531,9 +518,6 @@ content::BackgroundTracingManager::GetInstance()->RegisterTriggerType( "preemptive_test"); - BackgroundTracingManager::GetInstance()->WhenIdle( - base::BindRepeating(&DisableScenarioWhenIdle)); - EXPECT_TRUE(BackgroundTracingManager::GetInstance()->SetActiveScenario( std::move(config), trace_receiver_helper.get_receive_callback(), BackgroundTracingManager::ANONYMIZE_DATA)); @@ -547,6 +531,7 @@ handle, trigger_helper.receive_closure(true)); trace_receiver_helper.WaitForTraceReceived(); + BackgroundTracingManager::GetInstance()->AbortScenario(); background_tracing_helper.WaitForScenarioAborted(); EXPECT_TRUE(trace_receiver_helper.trace_received()); @@ -592,9 +577,6 @@ BackgroundTracingManager::TriggerHandle handle2 = BackgroundTracingManager::GetInstance()->RegisterTriggerType("test2"); - BackgroundTracingManager::GetInstance()->WhenIdle( - base::BindRepeating(&DisableScenarioWhenIdle)); - EXPECT_TRUE(BackgroundTracingManager::GetInstance()->SetActiveScenario( std::move(config), trace_receiver_helper.get_receive_callback(), BackgroundTracingManager::NO_DATA_FILTERING)); @@ -608,106 +590,10 @@ handle2, trigger_helper.receive_closure(false)); trace_receiver_helper.WaitForTraceReceived(); - background_tracing_helper.WaitForScenarioAborted(); - - EXPECT_TRUE(trace_receiver_helper.trace_received()); -} - -// This tests that toggling Blink scenarios in the config alters the -// command-line. -IN_PROC_BROWSER_TEST_F(BackgroundTracingManagerBrowserTest, - ToggleBlinkScenarios) { - TestBackgroundTracingHelper background_tracing_helper; - TestTraceReceiverHelper trace_receiver_helper; - - base::CommandLine* command_line = base::CommandLine::ForCurrentProcess(); - ASSERT_TRUE(command_line); - - // Early bailout in the case command line arguments have been explicitly set - // for the runner. - if (!command_line->GetSwitchValueASCII(switches::kEnableBlinkFeatures) - .empty() || - !command_line->GetSwitchValueASCII(switches::kDisableBlinkFeatures) - .empty()) { - return; - } - - base::DictionaryValue dict; - dict.SetString("mode", "PREEMPTIVE_TRACING_MODE"); - dict.SetString("category", "BENCHMARK"); - - std::unique_ptr<base::ListValue> rules_list(new base::ListValue()); - { - std::unique_ptr<base::DictionaryValue> rules_dict( - new base::DictionaryValue()); - rules_dict->SetString("rule", "MONITOR_AND_DUMP_WHEN_TRIGGER_NAMED"); - rules_dict->SetString("trigger_name", "test2"); - rules_list->Append(std::move(rules_dict)); - } - - dict.Set("configs", std::move(rules_list)); - dict.SetString("enable_blink_features", "FasterWeb1,FasterWeb2"); - dict.SetString("disable_blink_features", "SlowerWeb1,SlowerWeb2"); - std::unique_ptr<BackgroundTracingConfig> config( - BackgroundTracingConfigImpl::FromDict(&dict)); - EXPECT_TRUE(config); - - bool scenario_activated = - BackgroundTracingManager::GetInstance()->SetActiveScenario( - std::move(config), trace_receiver_helper.get_receive_callback(), - BackgroundTracingManager::NO_DATA_FILTERING); - - EXPECT_TRUE(scenario_activated); - EXPECT_EQ(command_line->GetSwitchValueASCII(switches::kEnableBlinkFeatures), - "FasterWeb1,FasterWeb2"); - EXPECT_EQ(command_line->GetSwitchValueASCII(switches::kDisableBlinkFeatures), - "SlowerWeb1,SlowerWeb2"); - - background_tracing_helper.WaitForTracingEnabled(); - - // Abort the scenario. BackgroundTracingManager::GetInstance()->AbortScenario(); background_tracing_helper.WaitForScenarioAborted(); - EXPECT_FALSE(trace_receiver_helper.trace_received()); -} - -// This tests that toggling Blink scenarios in a scenario won't activate -// if there's already Blink features toggled by something else (about://flags) -IN_PROC_BROWSER_TEST_F(BackgroundTracingManagerBrowserTest, - ToggleBlinkScenariosNotOverridingSwitches) { - TestTraceReceiverHelper trace_receiver_helper; - - base::DictionaryValue dict; - dict.SetString("mode", "PREEMPTIVE_TRACING_MODE"); - dict.SetString("category", "BENCHMARK"); - - std::unique_ptr<base::ListValue> rules_list(new base::ListValue()); - { - std::unique_ptr<base::DictionaryValue> rules_dict( - new base::DictionaryValue()); - rules_dict->SetString("rule", "MONITOR_AND_DUMP_WHEN_TRIGGER_NAMED"); - rules_dict->SetString("trigger_name", "test2"); - rules_list->Append(std::move(rules_dict)); - } - - dict.Set("configs", std::move(rules_list)); - dict.SetString("enable_blink_features", "FasterWeb1,FasterWeb2"); - dict.SetString("disable_blink_features", "SlowerWeb1,SlowerWeb2"); - std::unique_ptr<BackgroundTracingConfig> config( - BackgroundTracingConfigImpl::FromDict(&dict)); - EXPECT_TRUE(config); - - base::CommandLine::ForCurrentProcess()->AppendSwitchASCII( - switches::kEnableBlinkFeatures, "FooFeature"); - - bool scenario_activated = - BackgroundTracingManager::GetInstance()->SetActiveScenario( - std::move(config), trace_receiver_helper.get_receive_callback(), - BackgroundTracingManager::NO_DATA_FILTERING); - - EXPECT_FALSE(scenario_activated); - EXPECT_FALSE(trace_receiver_helper.trace_received()); + EXPECT_TRUE(trace_receiver_helper.trace_received()); } // This tests that delayed histogram triggers work as expected @@ -739,20 +625,18 @@ BackgroundTracingConfigImpl::FromDict(&dict)); EXPECT_TRUE(config); - BackgroundTracingManager::GetInstance()->WhenIdle( - base::BindRepeating(&DisableScenarioWhenIdle)); - base::RunLoop rule_triggered_runloop; - BackgroundTracingManagerImpl::GetInstance() - ->SetRuleTriggeredCallbackForTesting( - rule_triggered_runloop.QuitClosure()); - EXPECT_TRUE(BackgroundTracingManager::GetInstance()->SetActiveScenario( std::move(config), trace_receiver_helper.get_receive_callback(), BackgroundTracingManager::NO_DATA_FILTERING)); background_tracing_helper.WaitForTracingEnabled(); + BackgroundTracingManagerImpl::GetInstance() + ->GetActiveScenarioForTesting() + ->SetRuleTriggeredCallbackForTesting( + rule_triggered_runloop.QuitClosure()); + // Our reference value is "1", so a value of "2" should trigger a trace. LOCAL_HISTOGRAM_COUNTS("fake", 2); @@ -764,24 +648,21 @@ BackgroundTracingManagerImpl::GetInstance()->IsTracingForTesting()); // Fake the timer firing. - BackgroundTracingManagerImpl::GetInstance()->FireTimerForTesting(); - - background_tracing_helper.WaitForScenarioAborted(); - - EXPECT_FALSE( - BackgroundTracingManagerImpl::GetInstance()->IsTracingForTesting()); + BackgroundTracingManagerImpl::GetInstance() + ->GetActiveScenarioForTesting() + ->FireTimerForTesting(); trace_receiver_helper.WaitForTraceReceived(); + + BackgroundTracingManager::GetInstance()->AbortScenario(); + background_tracing_helper.WaitForScenarioAborted(); + EXPECT_TRUE(trace_receiver_helper.trace_received()); } // This tests that you can't trigger without a scenario set. IN_PROC_BROWSER_TEST_F(BackgroundTracingManagerBrowserTest, CannotTriggerWithoutScenarioSet) { - TestBackgroundTracingHelper background_tracing_helper; - - std::unique_ptr<BackgroundTracingConfig> config = CreatePreemptiveConfig(); - content::BackgroundTracingManager::TriggerHandle handle = content::BackgroundTracingManager::GetInstance()->RegisterTriggerType( "preemptive_test"); @@ -790,10 +671,6 @@ BackgroundTracingManager::GetInstance()->TriggerNamedEvent( handle, trigger_helper.receive_closure(false)); trigger_helper.WaitForTriggerReceived(); - - // Abort the scenario. - BackgroundTracingManager::GetInstance()->AbortScenario(); - background_tracing_helper.WaitForScenarioAborted(); } // This tests that no trace is triggered with a handle that isn't specified @@ -809,9 +686,6 @@ content::BackgroundTracingManager::GetInstance()->RegisterTriggerType( "does_not_exist"); - BackgroundTracingManager::GetInstance()->WhenIdle( - base::BindRepeating(&DisableScenarioWhenIdle)); - EXPECT_TRUE(BackgroundTracingManager::GetInstance()->SetActiveScenario( std::move(config), trace_receiver_helper.get_receive_callback(), BackgroundTracingManager::NO_DATA_FILTERING)); @@ -838,15 +712,12 @@ std::unique_ptr<BackgroundTracingConfig> config = CreatePreemptiveConfig(); content::BackgroundTracingManager::TriggerHandle handle = - content::BackgroundTracingManager::GetInstance()->RegisterTriggerType( + BackgroundTracingManager::GetInstance()->RegisterTriggerType( "preemptive_test"); - content::BackgroundTracingManager::GetInstance() + BackgroundTracingManagerImpl::GetInstance() ->InvalidateTriggerHandlesForTesting(); - BackgroundTracingManager::GetInstance()->WhenIdle( - base::BindRepeating(&DisableScenarioWhenIdle)); - EXPECT_TRUE(BackgroundTracingManager::GetInstance()->SetActiveScenario( std::move(config), trace_receiver_helper.get_receive_callback(), BackgroundTracingManager::NO_DATA_FILTERING)); @@ -893,9 +764,6 @@ content::BackgroundTracingManager::GetInstance()->RegisterTriggerType( "preemptive_test"); - BackgroundTracingManager::GetInstance()->WhenIdle( - base::BindRepeating(&DisableScenarioWhenIdle)); - EXPECT_TRUE(BackgroundTracingManager::GetInstance()->SetActiveScenario( std::move(config), trace_receiver_helper.get_receive_callback(), BackgroundTracingManager::NO_DATA_FILTERING)); @@ -943,9 +811,6 @@ content::BackgroundTracingManager::GetInstance()->RegisterTriggerType( "preemptive_test"); - BackgroundTracingManager::GetInstance()->WhenIdle( - base::BindRepeating(&DisableScenarioWhenIdle)); - EXPECT_TRUE(BackgroundTracingManager::GetInstance()->SetActiveScenario( std::move(config), trace_receiver_helper.get_receive_callback(), BackgroundTracingManager::NO_DATA_FILTERING)); @@ -989,9 +854,6 @@ BackgroundTracingConfigImpl::FromDict(&dict)); EXPECT_TRUE(config); - BackgroundTracingManager::GetInstance()->WhenIdle( - base::BindRepeating(&DisableScenarioWhenIdle)); - EXPECT_TRUE(BackgroundTracingManager::GetInstance()->SetActiveScenario( std::move(config), trace_receiver_helper.get_receive_callback(), BackgroundTracingManager::NO_DATA_FILTERING)); @@ -1002,6 +864,7 @@ LOCAL_HISTOGRAM_COUNTS("fake", 2); trace_receiver_helper.WaitForTraceReceived(); + BackgroundTracingManager::GetInstance()->AbortScenario(); background_tracing_helper.WaitForScenarioAborted(); EXPECT_TRUE(trace_receiver_helper.trace_received()); @@ -1034,9 +897,6 @@ BackgroundTracingConfigImpl::FromDict(&dict)); EXPECT_TRUE(config); - BackgroundTracingManager::GetInstance()->WhenIdle( - base::BindRepeating(&DisableScenarioWhenIdle)); - EXPECT_TRUE(BackgroundTracingManager::GetInstance()->SetActiveScenario( std::move(config), trace_receiver_helper.get_receive_callback(), BackgroundTracingManager::NO_DATA_FILTERING)); @@ -1082,9 +942,6 @@ BackgroundTracingConfigImpl::FromDict(&dict)); EXPECT_TRUE(config); - BackgroundTracingManager::GetInstance()->WhenIdle( - base::BindRepeating(&DisableScenarioWhenIdle)); - EXPECT_TRUE(BackgroundTracingManager::GetInstance()->SetActiveScenario( std::move(config), trace_receiver_helper.get_receive_callback(), BackgroundTracingManager::NO_DATA_FILTERING)); @@ -1130,9 +987,6 @@ BackgroundTracingConfigImpl::FromDict(&dict)); EXPECT_TRUE(config); - BackgroundTracingManager::GetInstance()->WhenIdle( - base::BindRepeating(&DisableScenarioWhenIdle)); - EXPECT_TRUE(BackgroundTracingManager::GetInstance()->SetActiveScenario( std::move(config), trace_receiver_helper.get_receive_callback(), BackgroundTracingManager::NO_DATA_FILTERING)); @@ -1185,9 +1039,6 @@ BackgroundTracingManager::GetInstance()->RegisterTriggerType( "reactive_test"); - BackgroundTracingManager::GetInstance()->WhenIdle( - base::BindRepeating(&DisableScenarioWhenIdle)); - EXPECT_TRUE(BackgroundTracingManager::GetInstance()->SetActiveScenario( std::move(config), trace_receiver_helper.get_receive_callback(), BackgroundTracingManager::NO_DATA_FILTERING)); @@ -1196,9 +1047,12 @@ BackgroundTracingManager::GetInstance()->TriggerNamedEvent( handle, trigger_helper.receive_closure(true)); - BackgroundTracingManager::GetInstance()->FireTimerForTesting(); + BackgroundTracingManagerImpl::GetInstance() + ->GetActiveScenarioForTesting() + ->FireTimerForTesting(); trace_receiver_helper.WaitForTraceReceived(); + BackgroundTracingManager::GetInstance()->AbortScenario(); background_tracing_helper.WaitForScenarioAborted(); EXPECT_TRUE(trace_receiver_helper.trace_received()); @@ -1220,9 +1074,6 @@ std::move(config), trace_receiver_helper.get_receive_callback(), BackgroundTracingManager::NO_DATA_FILTERING)); - BackgroundTracingManager::GetInstance()->WhenIdle( - base::BindRepeating(&DisableScenarioWhenIdle)); - TestTriggerHelper trigger_helper; BackgroundTracingManager::GetInstance()->TriggerNamedEvent( handle, trigger_helper.receive_closure(true)); @@ -1231,6 +1082,7 @@ handle, trigger_helper.receive_closure(true)); trace_receiver_helper.WaitForTraceReceived(); + BackgroundTracingManager::GetInstance()->AbortScenario(); background_tracing_helper.WaitForScenarioAborted(); EXPECT_TRUE(trace_receiver_helper.trace_received()); @@ -1321,9 +1173,6 @@ BackgroundTracingManager::GetInstance()->RegisterTriggerType( "reactive_test2"); - BackgroundTracingManager::GetInstance()->WhenIdle( - base::BindRepeating(&DisableScenarioWhenIdle)); - EXPECT_TRUE(BackgroundTracingManager::GetInstance()->SetActiveScenario( std::move(config), trace_receiver_helper.get_receive_callback(), BackgroundTracingManager::NO_DATA_FILTERING)); @@ -1343,6 +1192,7 @@ handle1, trigger_helper.receive_closure(true)); trace_receiver_helper.WaitForTraceReceived(); + BackgroundTracingManager::GetInstance()->AbortScenario(); background_tracing_helper.WaitForScenarioAborted(); EXPECT_TRUE(trace_receiver_helper.trace_received()); @@ -1360,9 +1210,6 @@ BackgroundTracingManager::GetInstance()->RegisterTriggerType( "reactive_test"); - BackgroundTracingManager::GetInstance()->WhenIdle( - base::BindRepeating(&DisableScenarioWhenIdle)); - EXPECT_TRUE(BackgroundTracingManager::GetInstance()->SetActiveScenario( std::move(config), trace_receiver_helper.get_receive_callback(), BackgroundTracingManager::NO_DATA_FILTERING)); @@ -1380,6 +1227,7 @@ handle, trigger_helper.receive_closure(false)); trace_receiver_helper.WaitForTraceReceived(); + BackgroundTracingManager::GetInstance()->AbortScenario(); background_tracing_helper.WaitForScenarioAborted(); EXPECT_TRUE(trace_receiver_helper.trace_received()); @@ -1415,9 +1263,6 @@ BackgroundTracingManager::GetInstance()->RegisterTriggerType( "reactive_test"); - BackgroundTracingManager::GetInstance()->WhenIdle( - base::BindRepeating(&DisableScenarioWhenIdle)); - EXPECT_TRUE(BackgroundTracingManager::GetInstance()->SetActiveScenario( std::move(config), trace_receiver_helper.get_receive_callback(), BackgroundTracingManager::NO_DATA_FILTERING)); @@ -1437,12 +1282,12 @@ EXPECT_TRUE( BackgroundTracingManagerImpl::GetInstance()->IsTracingForTesting()); - BackgroundTracingManager::GetInstance()->FireTimerForTesting(); - - EXPECT_FALSE( - BackgroundTracingManagerImpl::GetInstance()->IsTracingForTesting()); + BackgroundTracingManagerImpl::GetInstance() + ->GetActiveScenarioForTesting() + ->FireTimerForTesting(); trace_receiver_helper.WaitForTraceReceived(); + BackgroundTracingManager::GetInstance()->AbortScenario(); background_tracing_helper.WaitForScenarioAborted(); EXPECT_TRUE(trace_receiver_helper.trace_received()); @@ -1477,9 +1322,6 @@ std::unique_ptr<BackgroundTracingConfig> config( BackgroundTracingConfigImpl::ReactiveFromDict(&dict)); - BackgroundTracingManager::GetInstance()->WhenIdle( - base::BindRepeating(&DisableScenarioWhenIdle)); - EXPECT_TRUE(BackgroundTracingManager::GetInstance()->SetActiveScenario( std::move(config), trace_receiver_helper.get_receive_callback(), BackgroundTracingManager::NO_DATA_FILTERING)); @@ -1528,9 +1370,6 @@ std::unique_ptr<BackgroundTracingConfig> config( BackgroundTracingConfigImpl::ReactiveFromDict(&dict)); - BackgroundTracingManager::GetInstance()->WhenIdle( - base::BindRepeating(&DisableScenarioWhenIdle)); - EXPECT_TRUE(BackgroundTracingManager::GetInstance()->SetActiveScenario( std::move(config), trace_receiver_helper.get_receive_callback(), BackgroundTracingManager::NO_DATA_FILTERING)); @@ -1539,7 +1378,8 @@ background_tracing_helper.WaitForTracingEnabled(); EXPECT_TRUE(BackgroundTracingManagerImpl::GetInstance() - ->requires_anonymized_data_for_testing()); + ->GetActiveScenarioForTesting() + ->requires_anonymized_data()); EXPECT_TRUE(base::trace_event::TraceLog::GetInstance() ->GetCurrentTraceConfig() .IsArgumentFilterEnabled()); @@ -1549,12 +1389,12 @@ EXPECT_TRUE( BackgroundTracingManagerImpl::GetInstance()->IsTracingForTesting()); - BackgroundTracingManager::GetInstance()->FireTimerForTesting(); - - EXPECT_FALSE( - BackgroundTracingManagerImpl::GetInstance()->IsTracingForTesting()); + BackgroundTracingManagerImpl::GetInstance() + ->GetActiveScenarioForTesting() + ->FireTimerForTesting(); trace_receiver_helper.WaitForTraceReceived(); + BackgroundTracingManager::GetInstance()->AbortScenario(); background_tracing_helper.WaitForScenarioAborted(); EXPECT_TRUE(trace_receiver_helper.trace_received());
diff --git a/content/browser/tracing/background_tracing_manager_impl.cc b/content/browser/tracing/background_tracing_manager_impl.cc index 2870733a..d6cec3f 100644 --- a/content/browser/tracing/background_tracing_manager_impl.cc +++ b/content/browser/tracing/background_tracing_manager_impl.cc
@@ -12,7 +12,7 @@ #include "base/location.h" #include "base/macros.h" #include "base/metrics/histogram_macros.h" -#include "base/rand_util.h" +#include "base/no_destructor.h" #include "base/single_thread_task_runner.h" #include "base/task/post_task.h" #include "base/threading/thread_task_runner_handle.h" @@ -21,6 +21,7 @@ #include "components/tracing/common/trace_startup_config.h" #include "content/browser/tracing/background_memory_tracing_observer.h" #include "content/browser/tracing/background_startup_tracing_observer.h" +#include "content/browser/tracing/background_tracing_active_scenario.h" #include "content/browser/tracing/background_tracing_rule.h" #include "content/browser/tracing/trace_message_filter.h" #include "content/browser/tracing/tracing_controller_impl.h" @@ -38,84 +39,31 @@ namespace content { -namespace { - -base::LazyInstance<BackgroundTracingManagerImpl>::Leaky - g_background_tracing_manager = LAZY_INSTANCE_INITIALIZER; - -// These values are used for a histogram. Do not reorder. -enum BackgroundTracingMetrics { - SCENARIO_ACTIVATION_REQUESTED = 0, - SCENARIO_ACTIVATED_SUCCESSFULLY = 1, - RECORDING_ENABLED = 2, - PREEMPTIVE_TRIGGERED = 3, - REACTIVE_TRIGGERED = 4, - FINALIZATION_ALLOWED = 5, - FINALIZATION_DISALLOWED = 6, - FINALIZATION_STARTED = 7, - OBSOLETE_FINALIZATION_COMPLETE = 8, - SCENARIO_ACTION_FAILED_LOWRES_CLOCK = 9, - UPLOAD_FAILED = 10, - UPLOAD_SUCCEEDED = 11, - STARTUP_SCENARIO_TRIGGERED = 12, - NUMBER_OF_BACKGROUND_TRACING_METRICS, -}; - -void RecordBackgroundTracingMetric(BackgroundTracingMetrics metric) { +// static +void BackgroundTracingManagerImpl::RecordMetric(Metrics metric) { UMA_HISTOGRAM_ENUMERATION("Tracing.Background.ScenarioState", metric, - NUMBER_OF_BACKGROUND_TRACING_METRICS); + Metrics::NUMBER_OF_BACKGROUND_TRACING_METRICS); } -} // namespace - -BackgroundTracingManagerImpl::TracingTimer::TracingTimer( - StartedFinalizingCallback callback) : callback_(callback) { -} - -BackgroundTracingManagerImpl::TracingTimer::~TracingTimer() { -} - -void BackgroundTracingManagerImpl::TracingTimer::StartTimer(int seconds) { - tracing_timer_.Start( - FROM_HERE, base::TimeDelta::FromSeconds(seconds), this, - &BackgroundTracingManagerImpl::TracingTimer::TracingTimerFired); -} - -void BackgroundTracingManagerImpl::TracingTimer::CancelTimer() { - tracing_timer_.Stop(); -} - -void BackgroundTracingManagerImpl::TracingTimer::TracingTimerFired() { - BackgroundTracingManagerImpl::GetInstance()->BeginFinalizing(callback_); -} - -void BackgroundTracingManagerImpl::TracingTimer::FireTimerForTesting() { - CancelTimer(); - TracingTimerFired(); -} - +// static BackgroundTracingManager* BackgroundTracingManager::GetInstance() { return BackgroundTracingManagerImpl::GetInstance(); } +// static BackgroundTracingManagerImpl* BackgroundTracingManagerImpl::GetInstance() { - return g_background_tracing_manager.Pointer(); + static base::NoDestructor<BackgroundTracingManagerImpl> manager; + return manager.get(); } BackgroundTracingManagerImpl::BackgroundTracingManagerImpl() : delegate_(GetContentClient()->browser()->GetTracingDelegate()), - is_gathering_(false), - is_tracing_(false), - requires_anonymized_data_(true), - trigger_handle_ids_(0), - triggered_named_event_handle_(-1) { + trigger_handle_ids_(0) { AddEnabledStateObserver(BackgroundMemoryTracingObserver::GetInstance()); AddEnabledStateObserver(BackgroundStartupTracingObserver::GetInstance()); } -BackgroundTracingManagerImpl::~BackgroundTracingManagerImpl() { - NOTREACHED(); -} +BackgroundTracingManagerImpl::~BackgroundTracingManagerImpl() = default; void BackgroundTracingManagerImpl::AddMetadataGeneratorFunction() { tracing::TraceEventAgent::GetInstance()->AddMetadataGeneratorFunction( @@ -123,32 +71,30 @@ base::Unretained(this))); } -void BackgroundTracingManagerImpl::WhenIdle( - base::Callback<void()> idle_callback) { - CHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI)); - idle_callback_ = std::move(idle_callback); -} - bool BackgroundTracingManagerImpl::SetActiveScenario( std::unique_ptr<BackgroundTracingConfig> config, BackgroundTracingManager::ReceiveCallback receive_callback, DataFiltering data_filtering) { - CHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI)); - if (config) - RecordBackgroundTracingMetric(SCENARIO_ACTIVATION_REQUESTED); + DCHECK_CURRENTLY_ON(BrowserThread::UI); + if (config) { + RecordMetric(Metrics::SCENARIO_ACTIVATION_REQUESTED); + } - if (is_tracing_) + if (active_scenario_ && (active_scenario_->state() != + BackgroundTracingActiveScenario::State::kIdle)) { return false; + } // If we don't have a high resolution timer available, traces will be // too inaccurate to be useful. if (!base::TimeTicks::IsHighResolution()) { - if (config) - RecordBackgroundTracingMetric(SCENARIO_ACTION_FAILED_LOWRES_CLOCK); + if (config) { + RecordMetric(Metrics::SCENARIO_ACTION_FAILED_LOWRES_CLOCK); + } return false; } - std::unique_ptr<content::BackgroundTracingConfigImpl> config_impl( + std::unique_ptr<BackgroundTracingConfigImpl> config_impl( static_cast<BackgroundTracingConfigImpl*>(config.release())); config_impl = BackgroundStartupTracingObserver::GetInstance() ->IncludeStartupConfigIfNeeded(std::move(config_impl)); @@ -157,16 +103,18 @@ // Anonymize data for startup tracing by default. We currently do not // support storing the config in preferences for next session. data_filtering = DataFiltering::ANONYMIZE_DATA; - RecordBackgroundTracingMetric(STARTUP_SCENARIO_TRIGGERED); + RecordMetric(Metrics::STARTUP_SCENARIO_TRIGGERED); } else { // If startup config was not set and tracing was enabled, then do not set // any scenario. - if (base::trace_event::TraceLog::GetInstance()->IsEnabled()) + if (base::trace_event::TraceLog::GetInstance()->IsEnabled()) { return false; + } } - if (!config_impl) + if (!config_impl) { return false; + } bool requires_anonymized_data = (data_filtering == ANONYMIZE_DATA); @@ -187,103 +135,72 @@ base::Unretained(this))); } - base::CommandLine* command_line = base::CommandLine::ForCurrentProcess(); - - if (config_impl) { - // No point in tracing if there's nowhere to send it. - if (receive_callback.is_null()) - return false; - - // If the scenario requires us to toggle Blink features, we want - // to neither override anything else nor to do we want to activate - // the scenario without doing the toggle, so if something else has - // configured these switches we just abort. - if (!config_impl->enable_blink_features().empty() && - command_line->HasSwitch(switches::kEnableBlinkFeatures)) { - return false; - } - - if (!config_impl->disable_blink_features().empty() && - command_line->HasSwitch(switches::kDisableBlinkFeatures)) { - return false; - } + // No point in tracing if there's nowhere to send it. + if (config_impl && receive_callback.is_null()) { + return false; } - config_ = std::move(config_impl); - receive_callback_ = std::move(receive_callback); - requires_anonymized_data_ = requires_anonymized_data; - - DCHECK(!config_->rules().empty()); - for (const auto& rule : config_->rules()) - rule->Install(); - - if (!config_->enable_blink_features().empty()) { - command_line->AppendSwitchASCII(switches::kEnableBlinkFeatures, - config_->enable_blink_features()); - } - - if (!config_->disable_blink_features().empty()) { - command_line->AppendSwitchASCII(switches::kDisableBlinkFeatures, - config_->disable_blink_features()); - } + active_scenario_ = std::make_unique<BackgroundTracingActiveScenario>( + std::move(config_impl), requires_anonymized_data, + std::move(receive_callback), + base::BindOnce(&BackgroundTracingManagerImpl::OnScenarioAborted, + base::Unretained(this))); // Notify observers before starting tracing. - for (auto* observer : background_tracing_observers_) - observer->OnScenarioActivated(config_.get()); + for (auto* observer : background_tracing_observers_) { + observer->OnScenarioActivated(active_scenario_->GetConfig()); + } - StartTracingIfConfigNeedsIt(); - RecordBackgroundTracingMetric(SCENARIO_ACTIVATED_SUCCESSFULLY); + active_scenario_->StartTracingIfConfigNeedsIt(); + RecordMetric(Metrics::SCENARIO_ACTIVATED_SUCCESSFULLY); + return true; } bool BackgroundTracingManagerImpl::HasActiveScenario() { - return !!config_; -} - -void BackgroundTracingManagerImpl::OnStartTracingDone( - BackgroundTracingConfigImpl::CategoryPreset preset) { - DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - for (auto* observer : background_tracing_observers_) - observer->OnTracingEnabled(preset); + return !!active_scenario_; } void BackgroundTracingManagerImpl::AddEnabledStateObserver( EnabledStateObserver* observer) { - DCHECK_CURRENTLY_ON(content::BrowserThread::UI); + DCHECK_CURRENTLY_ON(BrowserThread::UI); background_tracing_observers_.insert(observer); } void BackgroundTracingManagerImpl::RemoveEnabledStateObserver( EnabledStateObserver* observer) { - DCHECK_CURRENTLY_ON(content::BrowserThread::UI); + DCHECK_CURRENTLY_ON(BrowserThread::UI); background_tracing_observers_.erase(observer); } void BackgroundTracingManagerImpl::AddTraceMessageFilter( TraceMessageFilter* trace_message_filter) { - DCHECK_CURRENTLY_ON(content::BrowserThread::UI); + DCHECK_CURRENTLY_ON(BrowserThread::UI); trace_message_filters_.insert(trace_message_filter); - for (auto* observer : trace_message_filter_observers_) + for (auto* observer : trace_message_filter_observers_) { observer->OnTraceMessageFilterAdded(trace_message_filter); + } } void BackgroundTracingManagerImpl::RemoveTraceMessageFilter( TraceMessageFilter* trace_message_filter) { - DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - for (auto* observer : trace_message_filter_observers_) + DCHECK_CURRENTLY_ON(BrowserThread::UI); + for (auto* observer : trace_message_filter_observers_) { observer->OnTraceMessageFilterRemoved(trace_message_filter); + } trace_message_filters_.erase(trace_message_filter); } void BackgroundTracingManagerImpl::AddTraceMessageFilterObserver( TraceMessageFilterObserver* observer) { - DCHECK_CURRENTLY_ON(content::BrowserThread::UI); + DCHECK_CURRENTLY_ON(BrowserThread::UI); trace_message_filter_observers_.insert(observer); - for (auto& filter : trace_message_filters_) + for (auto& filter : trace_message_filters_) { observer->OnTraceMessageFilterAdded(filter.get()); + } } void BackgroundTracingManagerImpl::RemoveTraceMessageFilterObserver( @@ -291,183 +208,87 @@ DCHECK_CURRENTLY_ON(BrowserThread::UI); trace_message_filter_observers_.erase(observer); - for (auto& filter : trace_message_filters_) + for (auto& filter : trace_message_filters_) { observer->OnTraceMessageFilterRemoved(filter.get()); + } +} + +BackgroundTracingActiveScenario* +BackgroundTracingManagerImpl::GetActiveScenarioForTesting() { + DCHECK(active_scenario_); + return active_scenario_.get(); } bool BackgroundTracingManagerImpl::IsTracingForTesting() { - return is_tracing_; + return active_scenario_ && (active_scenario_->state() == + BackgroundTracingActiveScenario::State::kTracing); } void BackgroundTracingManagerImpl::ValidateStartupScenario() { - if (!config_ || !delegate_) + if (!active_scenario_ || !delegate_) { return; + } if (!delegate_->IsAllowedToBeginBackgroundScenario( - *config_.get(), requires_anonymized_data_)) { + *active_scenario_->GetConfig(), + active_scenario_->requires_anonymized_data())) { AbortScenario(); } } -void BackgroundTracingManagerImpl::StartTracingIfConfigNeedsIt() { - if (!config_) - return; - - if (config_->tracing_mode() == BackgroundTracingConfigImpl::PREEMPTIVE) { - StartTracing(config_->category_preset(), - base::trace_event::RECORD_CONTINUOUSLY); - } - // There is nothing to do in case of reactive tracing. -} - -BackgroundTracingRule* -BackgroundTracingManagerImpl::GetRuleAbleToTriggerTracing( - TriggerHandle handle) const { - if (!config_) - return nullptr; - - // If the last trace is still uploading, we don't allow a new one to trigger. - if (is_gathering_) - return nullptr; - - if (!IsTriggerHandleValid(handle)) { - return nullptr; - } - - std::string trigger_name = GetTriggerNameFromHandle(handle); - for (const auto& rule : config_->rules()) { - if (rule->ShouldTriggerNamedEvent(trigger_name)) - return rule.get(); - } - - return nullptr; -} void BackgroundTracingManagerImpl::OnHistogramTrigger( const std::string& histogram_name) { - if (!content::BrowserThread::CurrentlyOn(content::BrowserThread::UI)) { + if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) { base::PostTaskWithTraits( - FROM_HERE, {content::BrowserThread::UI}, + FROM_HERE, {BrowserThread::UI}, base::BindOnce(&BackgroundTracingManagerImpl::OnHistogramTrigger, base::Unretained(this), histogram_name)); return; } - if (!config_) - return; - - for (const auto& rule : config_->rules()) { - if (rule->ShouldTriggerNamedEvent(histogram_name)) - OnRuleTriggered(rule.get(), StartedFinalizingCallback()); + if (active_scenario_) { + active_scenario_->OnHistogramTrigger(histogram_name); } } void BackgroundTracingManagerImpl::TriggerNamedEvent( BackgroundTracingManagerImpl::TriggerHandle handle, StartedFinalizingCallback callback) { - if (!content::BrowserThread::CurrentlyOn(content::BrowserThread::UI)) { + if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) { base::PostTaskWithTraits( - FROM_HERE, {content::BrowserThread::UI}, + FROM_HERE, {BrowserThread::UI}, base::BindOnce(&BackgroundTracingManagerImpl::TriggerNamedEvent, base::Unretained(this), handle, std::move(callback))); return; } - bool is_valid_trigger = true; - - const BackgroundTracingRule* triggered_rule = - GetRuleAbleToTriggerTracing(handle); - if (!triggered_rule) - is_valid_trigger = false; - - // A different reactive config than the running one tried to trigger. - if (!config_ || - (config_->tracing_mode() == BackgroundTracingConfigImpl::REACTIVE && - is_tracing_ && triggered_named_event_handle_ != handle)) { - is_valid_trigger = false; - } - - if (!is_valid_trigger) { - if (!callback.is_null()) + if (!active_scenario_ || !IsTriggerHandleValid(handle)) { + if (!callback.is_null()) { std::move(callback).Run(false); + } return; } - triggered_named_event_handle_ = handle; - OnRuleTriggered(triggered_rule, std::move(callback)); + active_scenario_->TriggerNamedEvent(handle, std::move(callback)); } void BackgroundTracingManagerImpl::OnRuleTriggered( const BackgroundTracingRule* triggered_rule, StartedFinalizingCallback callback) { - // Config can be null here if scenario was aborted when validation and rule - // was triggered just before validation. If validation kicked in after this - // point, we still check before uploading. - if (!config_) - return; - - double trigger_chance = triggered_rule->trigger_chance(); - if (trigger_chance < 1.0 && base::RandDouble() > trigger_chance) { - if (!callback.is_null()) - std::move(callback).Run(false); - return; + // The active scenario can be null here if scenario was aborted during + // validation and the rule was triggered just before validation. If validation + // kicked in after this point, we still check before uploading. + if (active_scenario_) { + active_scenario_->OnRuleTriggered(triggered_rule, callback); } - - last_triggered_rule_.reset(new base::DictionaryValue); - triggered_rule->IntoDict(last_triggered_rule_.get()); - int trace_delay = triggered_rule->GetTraceDelay(); - - if (config_->tracing_mode() == BackgroundTracingConfigImpl::REACTIVE) { - // In reactive mode, a trigger starts tracing, or finalizes tracing - // immediately if it's already running. - RecordBackgroundTracingMetric(REACTIVE_TRIGGERED); - - if (!is_tracing_) { - // It was not already tracing, start a new trace. - StartTracing(triggered_rule->category_preset(), - base::trace_event::RECORD_UNTIL_FULL); - } else { - // Some reactive configs that trigger again while tracing should just - // end right away (to not capture multiple navigations, for example). - // For others we just want to ignore the repeated trigger. - if (triggered_rule->stop_tracing_on_repeated_reactive()) { - trace_delay = -1; - } else { - if (!callback.is_null()) - std::move(callback).Run(false); - return; - } - } - } else { - // In preemptive mode, a trigger starts finalizing a trace if one is - // running and we're not got a finalization timer running, - // otherwise we do nothing. - if (!is_tracing_ || is_gathering_ || tracing_timer_) { - if (!callback.is_null()) - std::move(callback).Run(false); - return; - } - - RecordBackgroundTracingMetric(PREEMPTIVE_TRIGGERED); - } - - if (trace_delay < 0) { - BeginFinalizing(std::move(callback)); - } else { - tracing_timer_.reset(new TracingTimer(std::move(callback))); - tracing_timer_->StartTimer(trace_delay); - } - - if (!rule_triggered_callback_for_testing_.is_null()) - rule_triggered_callback_for_testing_.Run(); } BackgroundTracingManagerImpl::TriggerHandle BackgroundTracingManagerImpl::RegisterTriggerType(const char* trigger_name) { - CHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI)); + DCHECK_CURRENTLY_ON(BrowserThread::UI); trigger_handle_ids_ += 1; - trigger_handles_.insert( std::pair<TriggerHandle, std::string>(trigger_handle_ids_, trigger_name)); @@ -489,114 +310,29 @@ trigger_handles_.clear(); } -void BackgroundTracingManagerImpl::SetRuleTriggeredCallbackForTesting( - const base::Closure& callback) { - rule_triggered_callback_for_testing_ = callback; +void BackgroundTracingManagerImpl::OnStartTracingDone( + BackgroundTracingConfigImpl::CategoryPreset preset) { + DCHECK_CURRENTLY_ON(BrowserThread::UI); + for (auto* observer : background_tracing_observers_) { + observer->OnTracingEnabled(preset); + } } -void BackgroundTracingManagerImpl::FireTimerForTesting() { - DCHECK(tracing_timer_); - tracing_timer_->FireTimerForTesting(); -} +void BackgroundTracingManagerImpl::WhenIdle( + base::RepeatingClosure idle_callback) { + DCHECK_CURRENTLY_ON(BrowserThread::UI); + idle_callback_ = std::move(idle_callback); -void BackgroundTracingManagerImpl::StartTracing( - BackgroundTracingConfigImpl::CategoryPreset preset, - base::trace_event::TraceRecordMode record_mode) { - TraceConfig config = GetConfigForCategoryPreset(preset, record_mode); - if (requires_anonymized_data_) - config.EnableArgumentFilter(); -#if defined(OS_ANDROID) - // Set low trace buffer size on Android in order to upload small trace files. - if (config_->tracing_mode() == BackgroundTracingConfigImpl::PREEMPTIVE) { - config.SetTraceBufferSizeInEvents(20000); - config.SetTraceBufferSizeInKb(500); - } -#endif - - if (!TracingControllerImpl::GetInstance()->IsTracing() && - tracing::TracingUsesPerfettoBackend()) { - tracing::TraceEventDataSource::GetInstance()->SetupStartupTracing(); - } - - is_tracing_ = TracingControllerImpl::GetInstance()->StartTracing( - config, base::BindOnce(&BackgroundTracingManagerImpl::OnStartTracingDone, - base::Unretained(this), preset)); - - // Activate the categories immediately. StartTracing eventually does this - // itself, but asynchronously via PostTask, and in the meantime events will be - // dropped. This ensures that we start recording events for those categories - // immediately. - if (is_tracing_) { - uint8_t modes = base::trace_event::TraceLog::RECORDING_MODE; - if (!config.event_filters().empty()) - modes |= base::trace_event::TraceLog::FILTERING_MODE; - base::trace_event::TraceLog::GetInstance()->SetEnabled(config, modes); - } - - RecordBackgroundTracingMetric(RECORDING_ENABLED); -} - -void BackgroundTracingManagerImpl::OnFinalizeStarted( - base::Closure started_finalizing_closure, - std::unique_ptr<const base::DictionaryValue> metadata, - base::RefCountedString* file_contents) { - CHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI)); - - RecordBackgroundTracingMetric(FINALIZATION_STARTED); - UMA_HISTOGRAM_MEMORY_KB("Tracing.Background.FinalizingTraceSizeInKB", - file_contents->size() / 1024); - - if (!receive_callback_.is_null()) { - receive_callback_.Run( - file_contents, std::move(metadata), - base::BindOnce(&BackgroundTracingManagerImpl::OnFinalizeComplete, - base::Unretained(this))); - } - - if (!started_finalizing_closure.is_null()) - std::move(started_finalizing_closure).Run(); -} - -void BackgroundTracingManagerImpl::OnFinalizeComplete(bool success) { - if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) { - base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::UI}, - base::BindOnce(&BackgroundTracingManagerImpl::OnFinalizeComplete, - base::Unretained(this), success)); - return; - } - - CHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI)); - - is_gathering_ = false; - - if (!idle_callback_.is_null()) + if (!active_scenario_) { idle_callback_.Run(); - - bool is_allowed_begin = - !delegate_ || (config_ && - delegate_->IsAllowedToBeginBackgroundScenario( - *config_.get(), requires_anonymized_data_)); - - // Now that a trace has completed, we may need to enable recording again. - // TODO(oysteine): Retry later if IsAllowedToBeginBackgroundScenario fails. - if (is_allowed_begin) { - StartTracingIfConfigNeedsIt(); - } else { - AbortScenario(); - } - - if (success) { - RecordBackgroundTracingMetric(UPLOAD_SUCCEEDED); - } else { - RecordBackgroundTracingMetric(UPLOAD_FAILED); } } bool BackgroundTracingManagerImpl::IsAllowedFinalization() const { - return !delegate_ || - (config_ && delegate_->IsAllowedToEndBackgroundScenario( - *config_.get(), requires_anonymized_data_)); + return !delegate_ || (active_scenario_ && + delegate_->IsAllowedToEndBackgroundScenario( + *active_scenario_->GetConfig(), + active_scenario_->requires_anonymized_data())); } std::unique_ptr<base::DictionaryValue> @@ -604,187 +340,31 @@ DCHECK_CURRENTLY_ON(BrowserThread::UI); auto metadata_dict = std::make_unique<base::DictionaryValue>(); - if (config_) { - auto config_dict = std::make_unique<base::DictionaryValue>(); - config_->IntoDict(config_dict.get()); - metadata_dict->Set("config", std::move(config_dict)); - metadata_dict->SetString("scenario_name", config_->scenario_name()); + if (active_scenario_) { + active_scenario_->GenerateMetadataDict(metadata_dict.get()); } - if (last_triggered_rule_) - metadata_dict->Set("last_triggered_rule", std::move(last_triggered_rule_)); + return metadata_dict; } -void BackgroundTracingManagerImpl::BeginFinalizing( - StartedFinalizingCallback callback) { - is_gathering_ = true; - is_tracing_ = false; - triggered_named_event_handle_ = -1; - tracing_timer_.reset(); - - scoped_refptr<TracingControllerImpl::TraceDataEndpoint> trace_data_endpoint; - bool is_allowed_finalization = IsAllowedFinalization(); - base::Closure started_finalizing_closure; - if (!callback.is_null()) { - started_finalizing_closure = - base::BindRepeating(callback, is_allowed_finalization); - } - if (is_allowed_finalization) { - trace_data_endpoint = TracingControllerImpl::CreateCompressedStringEndpoint( - TracingControllerImpl::CreateCallbackEndpoint(base::Bind( - &BackgroundTracingManagerImpl::OnFinalizeStarted, - base::Unretained(this), std::move(started_finalizing_closure))), - true /* compress_with_background_priority */); - RecordBackgroundTracingMetric(FINALIZATION_ALLOWED); - } else { - if (!std::move(callback).is_null()) { - trace_data_endpoint = - TracingControllerImpl::CreateCallbackEndpoint(base::BindRepeating( - [](base::Closure closure, - std::unique_ptr<const base::DictionaryValue> metadata, - base::RefCountedString* file_contents) { - std::move(closure).Run(); - }, - std::move(started_finalizing_closure))); - } - RecordBackgroundTracingMetric(FINALIZATION_DISALLOWED); - } - - content::TracingControllerImpl::GetInstance()->StopTracing( - trace_data_endpoint); -} - void BackgroundTracingManagerImpl::AbortScenario() { - if (is_tracing_) { - scoped_refptr<TracingControllerImpl::TraceDataEndpoint> trace_data_endpoint; - trace_data_endpoint = - TracingControllerImpl::CreateCallbackEndpoint(base::BindRepeating( - &BackgroundTracingManagerImpl::OnAbortScenarioReceived, - base::Unretained(this))); - - content::TracingControllerImpl::GetInstance()->StopTracing( - trace_data_endpoint); - } else { - OnAbortScenarioReceived(nullptr, nullptr); + if (active_scenario_) { + active_scenario_->AbortScenario(); } } -void BackgroundTracingManagerImpl::OnAbortScenarioReceived( - std::unique_ptr<const base::DictionaryValue> metadata, - base::RefCountedString* trace_str) { - if (base::trace_event::TraceLog::GetInstance()->IsEnabled()) { - // Since the BackgroundTracingManager directly enables tracing - // in TraceLog, in addition to going through Mojo, there's an edge-case - // where tracing is rapidly stopped after starting, too quickly for the - // TraceEventAgent of the browser process to register itself, which means - // that we're left in a state where the Mojo interface doesn't think we're - // tracing but TraceLog is still enabled. If that's the case, we abort - // tracing here. - auto record_mode = - (config_->tracing_mode() == BackgroundTracingConfigImpl::PREEMPTIVE) - ? base::trace_event::RECORD_CONTINUOUSLY - : base::trace_event::RECORD_UNTIL_FULL; - TraceConfig config = - GetConfigForCategoryPreset(config_->category_preset(), record_mode); +void BackgroundTracingManagerImpl::OnScenarioAborted() { + DCHECK(active_scenario_); - uint8_t modes = base::trace_event::TraceLog::RECORDING_MODE; - if (!config.event_filters().empty()) - modes |= base::trace_event::TraceLog::FILTERING_MODE; - base::trace_event::TraceLog::GetInstance()->SetDisabled(modes); - } + active_scenario_.reset(); - is_tracing_ = false; - triggered_named_event_handle_ = -1; - config_.reset(); - tracing_timer_.reset(); - - for (auto* observer : background_tracing_observers_) + for (auto* observer : background_tracing_observers_) { observer->OnScenarioAborted(); -} - -TraceConfig BackgroundTracingManagerImpl::GetConfigForCategoryPreset( - BackgroundTracingConfigImpl::CategoryPreset preset, - base::trace_event::TraceRecordMode record_mode) const { - switch (preset) { - case BackgroundTracingConfigImpl::CategoryPreset::BENCHMARK: - return TraceConfig("benchmark,toplevel", record_mode); - case BackgroundTracingConfigImpl::CategoryPreset::BENCHMARK_DEEP: - return TraceConfig( - "*,disabled-by-default-benchmark.detailed," - "disabled-by-default-v8.cpu_profile," - "disabled-by-default-v8.runtime_stats", - record_mode); - case BackgroundTracingConfigImpl::CategoryPreset::BENCHMARK_GPU: - return TraceConfig( - "benchmark,toplevel,gpu,base,mojom,ipc," - "disabled-by-default-system_stats,disabled-by-default-cpu_profiler", - record_mode); - case BackgroundTracingConfigImpl::CategoryPreset::BENCHMARK_IPC: - return TraceConfig("benchmark,toplevel,ipc", record_mode); - case BackgroundTracingConfigImpl::CategoryPreset::BENCHMARK_STARTUP: { - auto config = - tracing::TraceStartupConfig::GetDefaultBrowserStartupConfig(); - config.SetTraceRecordMode(record_mode); - return config; - } - case BackgroundTracingConfigImpl::CategoryPreset::BENCHMARK_BLINK_GC: - return TraceConfig("blink_gc,disabled-by-default-blink_gc", record_mode); - case BackgroundTracingConfigImpl::CategoryPreset:: - BENCHMARK_EXECUTION_METRIC: - return TraceConfig("blink.console,v8", record_mode); - case BackgroundTracingConfigImpl::CategoryPreset::BENCHMARK_NAVIGATION: { - auto config = TraceConfig( - "benchmark,toplevel,ipc,base,browser,navigation,omnibox,ui,shutdown," - "safe_browsing,Java,EarlyJava,loading,startup,mojom,renderer_host," - "disabled-by-default-system_stats,disabled-by-default-cpu_profiler," - "dwrite,fonts", - record_mode); - // Filter only browser process events. - base::trace_event::TraceConfig::ProcessFilterConfig process_config( - {base::GetCurrentProcId()}); - config.SetProcessFilterConfig(process_config); - return config; - } - case BackgroundTracingConfigImpl::CategoryPreset::BENCHMARK_RENDERERS: - return TraceConfig( - "benchmark,toplevel,ipc,base,ui,v8,renderer,blink,blink_gc,mojom," - "latency,latencyInfo,renderer_host,cc,memory,dwrite,fonts," - "disabled-by-default-v8.gc," - "disabled-by-default-blink_gc," - "disabled-by-default-renderer.scheduler," - "disabled-by-default-system_stats,disabled-by-default-cpu_profiler", - record_mode); - case BackgroundTracingConfigImpl::CategoryPreset::BENCHMARK_SERVICEWORKER: - return TraceConfig( - "benchmark,toplevel,ipc,base,ServiceWorker,CacheStorage,Blob," - "loader,loading,navigation,blink.user_timing," - "disabled-by-default-network", - record_mode); - case BackgroundTracingConfigImpl::CategoryPreset::BENCHMARK_POWER: - return TraceConfig( - "benchmark,toplevel,ipc,base,audio,compositor,gpu,media,memory,midi," - "native,omnibox,renderer,skia,task_scheduler,ui,v8,views,webaudio", - record_mode); - case BackgroundTracingConfigImpl::CategoryPreset::BLINK_STYLE: - return TraceConfig("blink_style", record_mode); - - case BackgroundTracingConfigImpl::CategoryPreset::BENCHMARK_MEMORY_HEAVY: - return TraceConfig("-*,disabled-by-default-memory-infra", record_mode); - case BackgroundTracingConfigImpl::CategoryPreset::BENCHMARK_MEMORY_LIGHT: { - // On memory light mode, the periodic memory dumps are disabled. - base::trace_event::TraceConfig::MemoryDumpConfig memory_config; - memory_config.allowed_dump_modes = - std::set<base::trace_event::MemoryDumpLevelOfDetail>( - {base::trace_event::MemoryDumpLevelOfDetail::BACKGROUND}); - TraceConfig config("-*,disabled-by-default-memory-infra", record_mode); - config.ResetMemoryDumpConfig(memory_config); - return config; - } - case BackgroundTracingConfigImpl::CategoryPreset::CATEGORY_PRESET_UNSET: - NOTREACHED(); } - NOTREACHED(); - return TraceConfig(); + + if (!idle_callback_.is_null()) { + idle_callback_.Run(); + } } } // namespace content
diff --git a/content/browser/tracing/background_tracing_manager_impl.h b/content/browser/tracing/background_tracing_manager_impl.h index 22b3faf5..e26cddc2 100644 --- a/content/browser/tracing/background_tracing_manager_impl.h +++ b/content/browser/tracing/background_tracing_manager_impl.h
@@ -10,20 +10,19 @@ #include <set> #include <string> -#include "base/lazy_instance.h" #include "base/macros.h" -#include "base/timer/timer.h" -#include "base/trace_event/trace_config.h" #include "content/browser/tracing/background_tracing_config_impl.h" #include "content/public/browser/background_tracing_manager.h" namespace base { -class RefCountedString; +template <typename T> +class NoDestructor; } // namespace base namespace content { class BackgroundTracingRule; +class BackgroundTracingActiveScenario; class TraceMessageFilter; class TracingDelegate; @@ -55,24 +54,42 @@ virtual void OnTraceMessageFilterRemoved(TraceMessageFilter* filter) = 0; }; + // These values are used for a histogram. Do not reorder. + enum class Metrics { + SCENARIO_ACTIVATION_REQUESTED = 0, + SCENARIO_ACTIVATED_SUCCESSFULLY = 1, + RECORDING_ENABLED = 2, + PREEMPTIVE_TRIGGERED = 3, + REACTIVE_TRIGGERED = 4, + FINALIZATION_ALLOWED = 5, + FINALIZATION_DISALLOWED = 6, + FINALIZATION_STARTED = 7, + OBSOLETE_FINALIZATION_COMPLETE = 8, + SCENARIO_ACTION_FAILED_LOWRES_CLOCK = 9, + UPLOAD_FAILED = 10, + UPLOAD_SUCCEEDED = 11, + STARTUP_SCENARIO_TRIGGERED = 12, + NUMBER_OF_BACKGROUND_TRACING_METRICS, + }; + static void RecordMetric(Metrics metric); + CONTENT_EXPORT static BackgroundTracingManagerImpl* GetInstance(); bool SetActiveScenario(std::unique_ptr<BackgroundTracingConfig>, ReceiveCallback, DataFiltering data_filtering) override; - void WhenIdle(IdleCallback idle_callback) override; + CONTENT_EXPORT void AbortScenario() override; + bool HasActiveScenario() override; + // Named triggers void TriggerNamedEvent(TriggerHandle, StartedFinalizingCallback) override; TriggerHandle RegisterTriggerType(const char* trigger_name) override; + std::string GetTriggerNameFromHandle(TriggerHandle handle) const; void OnHistogramTrigger(const std::string& histogram_name); void OnRuleTriggered(const BackgroundTracingRule* triggered_rule, StartedFinalizingCallback callback); - CONTENT_EXPORT void AbortScenario() override; - bool HasActiveScenario() override; - - void OnStartTracingDone(BackgroundTracingConfigImpl::CategoryPreset preset); // Add/remove EnabledStateObserver. CONTENT_EXPORT void AddEnabledStateObserver(EnabledStateObserver* observer); @@ -87,77 +104,35 @@ void AddMetadataGeneratorFunction(); + bool IsAllowedFinalization() const; + + // Called by BackgroundTracingActiveScenario + void OnStartTracingDone(BackgroundTracingConfigImpl::CategoryPreset preset); + // For tests - void InvalidateTriggerHandlesForTesting() override; - CONTENT_EXPORT void SetRuleTriggeredCallbackForTesting( - const base::Closure& callback); - void FireTimerForTesting() override; + CONTENT_EXPORT BackgroundTracingActiveScenario* GetActiveScenarioForTesting(); + CONTENT_EXPORT void InvalidateTriggerHandlesForTesting(); CONTENT_EXPORT bool IsTracingForTesting(); - CONTENT_EXPORT bool requires_anonymized_data_for_testing() const { - return requires_anonymized_data_; - } + void WhenIdle(IdleCallback idle_callback) override; private: + friend class base::NoDestructor<BackgroundTracingManagerImpl>; + BackgroundTracingManagerImpl(); ~BackgroundTracingManagerImpl() override; - void StartTracing(BackgroundTracingConfigImpl::CategoryPreset, - base::trace_event::TraceRecordMode); - void StartTracingIfConfigNeedsIt(); - void OnFinalizeStarted(base::Closure started_finalizing_closure, - std::unique_ptr<const base::DictionaryValue> metadata, - base::RefCountedString*); - void OnFinalizeComplete(bool success); - void BeginFinalizing(StartedFinalizingCallback); void ValidateStartupScenario(); - - std::unique_ptr<base::DictionaryValue> GenerateMetadataDict(); - - bool IsAllowedFinalization() const; - std::string GetTriggerNameFromHandle(TriggerHandle handle) const; - bool IsTriggerHandleValid(TriggerHandle handle) const; - - BackgroundTracingRule* GetRuleAbleToTriggerTracing( - TriggerHandle handle) const; bool IsSupportedConfig(BackgroundTracingConfigImpl* config); + std::unique_ptr<base::DictionaryValue> GenerateMetadataDict(); + bool IsTriggerHandleValid(TriggerHandle handle) const; + void OnScenarioAborted(); - base::trace_event::TraceConfig GetConfigForCategoryPreset( - BackgroundTracingConfigImpl::CategoryPreset, - base::trace_event::TraceRecordMode) const; - - void OnAbortScenarioReceived( - std::unique_ptr<const base::DictionaryValue> metadata, - base::RefCountedString* trace_str); - - class TracingTimer { - public: - explicit TracingTimer(StartedFinalizingCallback); - ~TracingTimer(); - - void StartTimer(int seconds); - void CancelTimer(); - void FireTimerForTesting(); - - private: - void TracingTimerFired(); - - base::OneShotTimer tracing_timer_; - StartedFinalizingCallback callback_; - }; + std::unique_ptr<BackgroundTracingActiveScenario> active_scenario_; std::unique_ptr<TracingDelegate> delegate_; - std::unique_ptr<const content::BackgroundTracingConfigImpl> config_; std::map<TriggerHandle, std::string> trigger_handles_; - std::unique_ptr<TracingTimer> tracing_timer_; - ReceiveCallback receive_callback_; - std::unique_ptr<base::DictionaryValue> last_triggered_rule_; - bool is_gathering_; - bool is_tracing_; - bool requires_anonymized_data_; int trigger_handle_ids_; - TriggerHandle triggered_named_event_handle_; - // There is no need to use base::ObserverList to store observers because we // only access |background_tracing_observers_| and // |trace_message_filter_observers_| from the UI thread. @@ -166,10 +141,7 @@ std::set<TraceMessageFilterObserver*> trace_message_filter_observers_; IdleCallback idle_callback_; - base::Closure tracing_enabled_callback_for_testing_; - base::Closure rule_triggered_callback_for_testing_; - - friend struct base::LazyInstanceTraitsBase<BackgroundTracingManagerImpl>; + base::RepeatingClosure tracing_enabled_callback_for_testing_; DISALLOW_COPY_AND_ASSIGN(BackgroundTracingManagerImpl); };
diff --git a/content/browser/tracing/tracing_controller_impl.cc b/content/browser/tracing/tracing_controller_impl.cc index 4308cf6a..9c739f7 100644 --- a/content/browser/tracing/tracing_controller_impl.cc +++ b/content/browser/tracing/tracing_controller_impl.cc
@@ -190,10 +190,6 @@ tracing::mojom::kServiceName, &coordinator_); coordinator_.set_connection_error_handler(base::BindOnce( [](TracingControllerImpl* controller) { - // If the tracing service dies while we're tracing, the browser is - // in an unrecoverable state (it'll keep tracing until shared memory - // buffers are full and then stall). - CHECK(!controller->IsTracing()); controller->coordinator_.reset(); }, base::Unretained(this))); @@ -394,7 +390,7 @@ bool TracingControllerImpl::StopTracing( const scoped_refptr<TraceDataEndpoint>& trace_data_endpoint, const std::string& agent_label) { - if (!IsTracing() || drainer_) + if (!IsTracing() || drainer_ || !coordinator_) return false; DCHECK_CURRENTLY_ON(BrowserThread::UI);
diff --git a/content/browser/web_contents/web_contents_impl.cc b/content/browser/web_contents/web_contents_impl.cc index 0c5634c..487d587 100644 --- a/content/browser/web_contents/web_contents_impl.cc +++ b/content/browser/web_contents/web_contents_impl.cc
@@ -857,7 +857,6 @@ bool handled = true; IPC_BEGIN_MESSAGE_MAP_WITH_PARAM(WebContentsImpl, message, render_view_host) - IPC_MESSAGE_HANDLER(ViewHostMsg_GoToEntryAtOffset, OnGoToEntryAtOffset) IPC_MESSAGE_HANDLER(ViewHostMsg_UpdateZoomLimits, OnUpdateZoomLimits) IPC_MESSAGE_HANDLER(ViewHostMsg_PageScaleFactorChanged, OnPageScaleFactorChanged) @@ -908,6 +907,7 @@ OnDidDisplayContentWithCertificateErrors) IPC_MESSAGE_HANDLER(FrameHostMsg_DidRunContentWithCertificateErrors, OnDidRunContentWithCertificateErrors) + IPC_MESSAGE_HANDLER(FrameHostMsg_GoToEntryAtOffset, OnGoToEntryAtOffset) IPC_MESSAGE_HANDLER(FrameHostMsg_RegisterProtocolHandler, OnRegisterProtocolHandler) IPC_MESSAGE_HANDLER(FrameHostMsg_UnregisterProtocolHandler, @@ -4731,7 +4731,7 @@ observer.DidFinishLoad(source, validated_url); } -void WebContentsImpl::OnGoToEntryAtOffset(RenderViewHostImpl* source, +void WebContentsImpl::OnGoToEntryAtOffset(RenderFrameHostImpl* source, int offset, bool has_user_gesture) { // Non-user initiated navigations coming from the renderer should be ignored
diff --git a/content/browser/web_contents/web_contents_impl.h b/content/browser/web_contents/web_contents_impl.h index c81ed2e2..70f816e 100644 --- a/content/browser/web_contents/web_contents_impl.h +++ b/content/browser/web_contents/web_contents_impl.h
@@ -1226,7 +1226,7 @@ void OnDidRunContentWithCertificateErrors(RenderFrameHostImpl* source); void OnDocumentLoadedInFrame(RenderFrameHostImpl* source); void OnDidFinishLoad(RenderFrameHostImpl* source, const GURL& url); - void OnGoToEntryAtOffset(RenderViewHostImpl* source, + void OnGoToEntryAtOffset(RenderFrameHostImpl* source, int offset, bool has_user_gesture); void OnUpdateZoomLimits(RenderViewHostImpl* source,
diff --git a/content/child/runtime_features.cc b/content/child/runtime_features.cc index dcfa614..b610ef5 100644 --- a/content/child/runtime_features.cc +++ b/content/child/runtime_features.cc
@@ -373,6 +373,9 @@ WebRuntimeFeatures::EnableModernMediaControls( base::FeatureList::IsEnabled(media::kUseModernMediaControls)); + WebRuntimeFeatures::EnableScheduledScriptStreaming( + base::FeatureList::IsEnabled(features::kScheduledScriptStreaming)); + WebRuntimeFeatures::EnableScriptStreamingOnPreload( base::FeatureList::IsEnabled(features::kScriptStreamingOnPreload));
diff --git a/content/common/frame_messages.h b/content/common/frame_messages.h index 986478e..364be52 100644 --- a/content/common/frame_messages.h +++ b/content/common/frame_messages.h
@@ -1637,6 +1637,13 @@ // should render fallback content. IPC_MESSAGE_ROUTED0(FrameHostMsg_RenderFallbackContentInParentProcess) +// Used to go to the session history entry at the given offset (ie, -1 will +// return the "back" item). This message affects a view and not just a frame, +// but is sent on the frame channel for attribution purposes. +IPC_MESSAGE_ROUTED2(FrameHostMsg_GoToEntryAtOffset, + int /* offset (from current) of history item to get */, + bool /* has_user_gesture */) + #if BUILDFLAG(USE_EXTERNAL_POPUP_MENU) // Message to show/hide a popup menu using native controls.
diff --git a/content/common/swapped_out_messages.cc b/content/common/swapped_out_messages.cc index 260f33d..a17bd78 100644 --- a/content/common/swapped_out_messages.cc +++ b/content/common/swapped_out_messages.cc
@@ -28,8 +28,6 @@ case ViewHostMsg_RouteCloseEvent::ID: // Send page scale factor reset notification upon cross-process navigations. case ViewHostMsg_PageScaleFactorChanged::ID: - // Allow history.back() in OOPIFs - https://crbug.com/845923. - case ViewHostMsg_GoToEntryAtOffset::ID: return true; default: break;
diff --git a/content/common/view_messages.h b/content/common/view_messages.h index 5f419a8..7a83198 100644 --- a/content/common/view_messages.h +++ b/content/common/view_messages.h
@@ -275,12 +275,6 @@ bool /* result */, std::string /* proxy list */) -// Used to go to the session history entry at the given offset (ie, -1 will -// return the "back" item). -IPC_MESSAGE_ROUTED2(ViewHostMsg_GoToEntryAtOffset, - int /* offset (from current) of history item to get */, - bool /* has_user_gesture */) - // Notifies that the preferred size of the content changed. IPC_MESSAGE_ROUTED1(ViewHostMsg_DidContentsPreferredSizeChange, gfx::Size /* pref_size */)
diff --git a/content/public/android/java/src/org/chromium/content/browser/framehost/NavigationControllerImpl.java b/content/public/android/java/src/org/chromium/content/browser/framehost/NavigationControllerImpl.java index 51442f62..7430c40 100644 --- a/content/public/android/java/src/org/chromium/content/browser/framehost/NavigationControllerImpl.java +++ b/content/public/android/java/src/org/chromium/content/browser/framehost/NavigationControllerImpl.java
@@ -259,9 +259,10 @@ @CalledByNative private static NavigationEntry createNavigationEntry(int index, String url, String virtualUrl, - String originalUrl, String referrerUrl, String title, Bitmap favicon, int transition) { - return new NavigationEntry( - index, url, virtualUrl, originalUrl, referrerUrl, title, favicon, transition); + String originalUrl, String referrerUrl, String title, Bitmap favicon, int transition, + long timestamp) { + return new NavigationEntry(index, url, virtualUrl, originalUrl, referrerUrl, title, favicon, + transition, timestamp); } private native boolean nativeCanGoBack(long nativeNavigationControllerAndroid);
diff --git a/content/public/android/java/src/org/chromium/content_public/browser/NavigationEntry.java b/content/public/android/java/src/org/chromium/content_public/browser/NavigationEntry.java index 6c8e481..706f5c2 100644 --- a/content/public/android/java/src/org/chromium/content_public/browser/NavigationEntry.java +++ b/content/public/android/java/src/org/chromium/content_public/browser/NavigationEntry.java
@@ -19,12 +19,13 @@ private final String mTitle; private Bitmap mFavicon; private int mTransition; + private long mTimestamp; /** * Default constructor. */ public NavigationEntry(int index, String url, String virtualUrl, String originalUrl, - String referrerUrl, String title, Bitmap favicon, int transition) { + String referrerUrl, String title, Bitmap favicon, int transition, long timestamp) { mIndex = index; mUrl = url; mVirtualUrl = virtualUrl; @@ -33,6 +34,7 @@ mTitle = title; mFavicon = favicon; mTransition = transition; + mTimestamp = timestamp; } /** @@ -107,4 +109,11 @@ public int getTransition() { return mTransition; } + + /** + * @return The Timestamp when the last navigation completed. + */ + public long getTimestamp() { + return mTimestamp; + } }
diff --git a/content/public/android/javatests/src/org/chromium/content/browser/scheduler/NativePostTaskTest.java b/content/public/android/javatests/src/org/chromium/content/browser/scheduler/NativePostTaskTest.java index 38641d1a..297f755 100644 --- a/content/public/android/javatests/src/org/chromium/content/browser/scheduler/NativePostTaskTest.java +++ b/content/public/android/javatests/src/org/chromium/content/browser/scheduler/NativePostTaskTest.java
@@ -21,6 +21,7 @@ import org.chromium.base.test.BaseJUnit4ClassRunner; import org.chromium.base.test.task.SchedulerTestHelpers; import org.chromium.base.test.task.TaskSchedulerTestHelpers; +import org.chromium.base.test.util.DisabledTest; import org.chromium.content.app.ContentMain; import org.chromium.content_public.browser.test.NativeLibraryTestRule; @@ -159,6 +160,7 @@ @Test @MediumTest + @DisabledTest public void testCreateTaskRunnerMigrationToNative() throws Exception { final Object lock = new Object(); final AtomicBoolean taskExecuted = new AtomicBoolean();
diff --git a/content/public/browser/background_tracing_manager.h b/content/public/browser/background_tracing_manager.h index dfbd33f..4c2872d 100644 --- a/content/public/browser/background_tracing_manager.h +++ b/content/public/browser/background_tracing_manager.h
@@ -92,8 +92,6 @@ // For tests virtual void AbortScenario() = 0; - virtual void InvalidateTriggerHandlesForTesting() = 0; - virtual void FireTimerForTesting() = 0; protected: virtual ~BackgroundTracingManager() {}
diff --git a/content/public/common/content_features.cc b/content/public/common/content_features.cc index 228843a..32e7f67 100644 --- a/content/public/common/content_features.cc +++ b/content/public/common/content_features.cc
@@ -683,6 +683,10 @@ const base::Feature kWipeCorruptV2IDBDatabases{ "WipeCorruptV2IDBDatabases", base::FEATURE_ENABLED_BY_DEFAULT}; +// Enabled scheduler use for script streaming. +const base::Feature kScheduledScriptStreaming{"ScheduledScriptStreaming", + base::FEATURE_ENABLED_BY_DEFAULT}; + // Start streaming scripts on script preload. const base::Feature kScriptStreamingOnPreload{ "ScriptStreamingOnPreload", base::FEATURE_DISABLED_BY_DEFAULT};
diff --git a/content/public/common/content_features.h b/content/public/common/content_features.h index 5f2f523..9fd281d 100644 --- a/content/public/common/content_features.h +++ b/content/public/common/content_features.h
@@ -149,6 +149,7 @@ CONTENT_EXPORT extern const base::Feature kWebXrGamepadSupport; CONTENT_EXPORT extern const base::Feature kWebXrHitTest; CONTENT_EXPORT extern const base::Feature kWipeCorruptV2IDBDatabases; +CONTENT_EXPORT extern const base::Feature kScheduledScriptStreaming; CONTENT_EXPORT extern const base::Feature kScriptStreamingOnPreload; #if defined(OS_ANDROID)
diff --git a/content/renderer/accessibility/ax_image_annotator.cc b/content/renderer/accessibility/ax_image_annotator.cc index af503de..611c1ce 100644 --- a/content/renderer/accessibility/ax_image_annotator.cc +++ b/content/renderer/accessibility/ax_image_annotator.cc
@@ -4,6 +4,7 @@ #include "content/renderer/accessibility/ax_image_annotator.h" +#include <ctype.h> #include <utility> #include <vector> @@ -295,15 +296,26 @@ if (message_id == 0) continue; - if (annotation->text.empty()) + int last_meaningful_char = annotation->text.length() - 1; + while (last_meaningful_char >= 0) { + bool is_whitespace_or_punct = + isspace(annotation->text[last_meaningful_char]) || + ispunct(annotation->text[last_meaningful_char]); + if (!is_whitespace_or_punct) + break; + last_meaningful_char--; + } + + if (annotation->text.empty() || last_meaningful_char < 0) continue; + std::string text = annotation->text.substr(0, last_meaningful_char + 1); if (GetContentClient()) { contextualized_strings.push_back( base::UTF16ToUTF8(GetContentClient()->GetLocalizedString( - message_id, base::UTF8ToUTF16(annotation->text)))); + message_id, base::UTF8ToUTF16(text)))); } else { - contextualized_strings.emplace_back(annotation->text); + contextualized_strings.push_back(text); } }
diff --git a/content/renderer/input/widget_input_handler_impl.cc b/content/renderer/input/widget_input_handler_impl.cc index 6e7a3d1a..cb27c9803 100644 --- a/content/renderer/input/widget_input_handler_impl.cc +++ b/content/renderer/input/widget_input_handler_impl.cc
@@ -53,14 +53,26 @@ void WidgetInputHandlerImpl::SetAssociatedBinding( mojom::WidgetInputHandlerAssociatedRequest request) { - associated_binding_.Bind(std::move(request)); + scoped_refptr<base::SingleThreadTaskRunner> task_runner; + if (content::RenderThreadImpl::current()) { + blink::scheduler::WebThreadScheduler* scheduler = + content::RenderThreadImpl::current()->GetWebMainThreadScheduler(); + task_runner = scheduler->DeprecatedDefaultTaskRunner(); + } + associated_binding_.Bind(std::move(request), std::move(task_runner)); associated_binding_.set_connection_error_handler( base::BindOnce(&WidgetInputHandlerImpl::Release, base::Unretained(this))); } void WidgetInputHandlerImpl::SetBinding( mojom::WidgetInputHandlerRequest request) { - binding_.Bind(std::move(request)); + scoped_refptr<base::SingleThreadTaskRunner> task_runner; + if (content::RenderThreadImpl::current()) { + blink::scheduler::WebThreadScheduler* scheduler = + content::RenderThreadImpl::current()->GetWebMainThreadScheduler(); + task_runner = scheduler->DeprecatedDefaultTaskRunner(); + } + binding_.Bind(std::move(request), std::move(task_runner)); binding_.set_connection_error_handler( base::BindOnce(&WidgetInputHandlerImpl::Release, base::Unretained(this))); }
diff --git a/content/renderer/media/webrtc/mock_peer_connection_impl.h b/content/renderer/media/webrtc/mock_peer_connection_impl.h index 389ca3c..f95fe28 100644 --- a/content/renderer/media/webrtc/mock_peer_connection_impl.h +++ b/content/renderer/media/webrtc/mock_peer_connection_impl.h
@@ -15,6 +15,7 @@ #include "testing/gmock/include/gmock/gmock.h" #include "third_party/webrtc/api/dtls_transport_interface.h" #include "third_party/webrtc/api/peer_connection_interface.h" +#include "third_party/webrtc/api/sctp_transport_interface.h" #include "third_party/webrtc/api/stats/rtc_stats_report.h" namespace content { @@ -166,6 +167,8 @@ const override; std::vector<rtc::scoped_refptr<webrtc::RtpReceiverInterface>> GetReceivers() const override; + MOCK_CONST_METHOD0(GetSctpTransport, + rtc::scoped_refptr<webrtc::SctpTransportInterface>()); rtc::scoped_refptr<webrtc::DataChannelInterface> CreateDataChannel(const std::string& label, const webrtc::DataChannelInit* config) override;
diff --git a/content/renderer/media/webrtc/mock_web_rtc_peer_connection_handler_client.h b/content/renderer/media/webrtc/mock_web_rtc_peer_connection_handler_client.h index 1736aa4..00026e3 100644 --- a/content/renderer/media/webrtc/mock_web_rtc_peer_connection_handler_client.h +++ b/content/renderer/media/webrtc/mock_web_rtc_peer_connection_handler_client.h
@@ -44,6 +44,8 @@ std::unique_ptr<blink::WebRTCRtpReceiver> web_rtp_receiver) override { DidRemoveReceiverPlanBForMock(&web_rtp_receiver); } + MOCK_METHOD1(DidModifySctpTransport, + void(blink::WebRTCSctpTransportSnapshot snapshot)); void DidModifyTransceivers( std::vector<std::unique_ptr<blink::WebRTCRtpTransceiver>> web_transceivers,
diff --git a/content/renderer/media/webrtc/rtc_peer_connection_handler.cc b/content/renderer/media/webrtc/rtc_peer_connection_handler.cc index a2e2306..d67ebe9 100644 --- a/content/renderer/media/webrtc/rtc_peer_connection_handler.cc +++ b/content/renderer/media/webrtc/rtc_peer_connection_handler.cc
@@ -786,6 +786,7 @@ WebRtcSetDescriptionObserver::States states) { DCHECK_EQ(sdp_semantics_, webrtc::SdpSemantics::kUnifiedPlan); if (handler_) { + handler_->OnModifySctpTransport(std::move(states.sctp_transport_state)); handler_->OnModifyTransceivers( std::move(states.transceiver_states), action_ == PeerConnectionTracker::ACTION_SET_REMOTE_DESCRIPTION); @@ -1137,8 +1138,8 @@ ? native_peer_connection_->GetTransceivers() : std::vector< rtc::scoped_refptr<webrtc::RtpTransceiverInterface>>(); - transceiver_state_surfacer->Initialize(track_adapter_map_, - std::move(transceivers)); + transceiver_state_surfacer->Initialize( + native_peer_connection_, track_adapter_map_, std::move(transceivers)); } void RTCPeerConnectionHandler::CreateAnswer( @@ -1604,7 +1605,8 @@ std::vector<rtc::scoped_refptr<webrtc::RtpTransceiverInterface>> transceivers; if (error_or_transceiver->ok()) transceivers.push_back(error_or_transceiver->value()); - transceiver_state_surfacer->Initialize(track_adapter_map_, transceivers); + transceiver_state_surfacer->Initialize(native_peer_connection_, + track_adapter_map_, transceivers); } webrtc::RTCErrorOr<std::unique_ptr<blink::WebRTCRtpTransceiver>> @@ -1657,7 +1659,8 @@ std::vector<rtc::scoped_refptr<webrtc::RtpTransceiverInterface>> transceivers; if (error_or_transceiver->ok()) transceivers.push_back(error_or_transceiver->value()); - transceiver_state_surfacer->Initialize(track_adapter_map_, transceivers); + transceiver_state_surfacer->Initialize(native_peer_connection_, + track_adapter_map_, transceivers); } webrtc::RTCErrorOr<std::unique_ptr<blink::WebRTCRtpTransceiver>> @@ -1765,8 +1768,8 @@ transceivers = {transceiver_for_sender}; } } - transceiver_state_surfacer->Initialize(track_adapter_map_, - std::move(transceivers)); + transceiver_state_surfacer->Initialize( + native_peer_connection_, track_adapter_map_, std::move(transceivers)); } webrtc::RTCErrorOr<std::unique_ptr<blink::WebRTCRtpTransceiver>> @@ -1885,8 +1888,8 @@ DCHECK(transceiver_for_sender); transceivers = {transceiver_for_sender}; } - transceiver_state_surfacer->Initialize(track_adapter_map_, - std::move(transceivers)); + transceiver_state_surfacer->Initialize( + native_peer_connection_, track_adapter_map_, std::move(transceivers)); } void RTCPeerConnectionHandler::CloseClientPeerConnection() { @@ -2168,6 +2171,11 @@ client_->DidRemoveReceiverPlanB(std::move(receiver)); } +void RTCPeerConnectionHandler::OnModifySctpTransport( + blink::WebRTCSctpTransportSnapshot state) { + client_->DidModifySctpTransport(state); +} + void RTCPeerConnectionHandler::OnModifyTransceivers( std::vector<RtpTransceiverState> transceiver_states, bool is_remote_description) {
diff --git a/content/renderer/media/webrtc/rtc_peer_connection_handler.h b/content/renderer/media/webrtc/rtc_peer_connection_handler.h index 1816e1b..7a0261f 100644 --- a/content/renderer/media/webrtc/rtc_peer_connection_handler.h +++ b/content/renderer/media/webrtc/rtc_peer_connection_handler.h
@@ -26,6 +26,7 @@ #include "content/renderer/media/webrtc/webrtc_media_stream_track_adapter_map.h" #include "third_party/blink/public/platform/web_media_stream_source.h" #include "third_party/blink/public/platform/web_rtc_peer_connection_handler.h" +#include "third_party/blink/public/platform/web_rtc_peer_connection_handler_client.h" #include "third_party/blink/public/platform/web_rtc_stats.h" #include "third_party/blink/public/platform/web_rtc_stats_request.h" #include "third_party/blink/public/platform/web_rtc_stats_response.h" @@ -223,6 +224,7 @@ void OnRenegotiationNeeded(); void OnAddReceiverPlanB(RtpReceiverState receiver_state); void OnRemoveReceiverPlanB(uintptr_t receiver_id); + void OnModifySctpTransport(blink::WebRTCSctpTransportSnapshot state); void OnModifyTransceivers(std::vector<RtpTransceiverState> transceiver_states, bool is_remote_description); void OnDataChannel(scoped_refptr<webrtc::DataChannelInterface> channel);
diff --git a/content/renderer/media/webrtc/rtc_video_decoder.cc b/content/renderer/media/webrtc/rtc_video_decoder.cc index 7705e72..55b5366 100644 --- a/content/renderer/media/webrtc/rtc_video_decoder.cc +++ b/content/renderer/media/webrtc/rtc_video_decoder.cc
@@ -247,12 +247,11 @@ // http://crosbug.com/p/21913 is fixed. DCHECK(new_frame_size.IsEmpty()); - // Increase the error counter, if we are already in an error state. Also, - // increase the counter if we keep receiving keyframes without size set. - vda_error_counter_ += - vda_error_counter_ || input_image._frameType == webrtc::kVideoFrameKey - ? 1 - : 0; + if (vda_error_counter_ || + input_image._frameType == webrtc::VideoFrameType::kVideoFrameKey) { + ++vda_error_counter_; + } + if (ShouldFallbackToSoftwareDecode()) return WEBRTC_VIDEO_CODEC_FALLBACK_SOFTWARE; DVLOG(1) << "The first frame should have resolution. Drop this.";
diff --git a/content/renderer/media/webrtc/rtc_video_decoder_adapter.cc b/content/renderer/media/webrtc/rtc_video_decoder_adapter.cc index ad53e97..92b8d97 100644 --- a/content/renderer/media/webrtc/rtc_video_decoder_adapter.cc +++ b/content/renderer/media/webrtc/rtc_video_decoder_adapter.cc
@@ -261,7 +261,7 @@ WebRtcToMediaVideoColorSpace(*input_image.ColorSpace())); if (!ReinitializeSync(config_)) return WEBRTC_VIDEO_CODEC_FALLBACK_SOFTWARE; - if (input_image._frameType != webrtc::kVideoFrameKey) + if (input_image._frameType != webrtc::VideoFrameType::kVideoFrameKey) return WEBRTC_VIDEO_CODEC_ERROR; }
diff --git a/content/renderer/media/webrtc/rtc_video_decoder_adapter_unittest.cc b/content/renderer/media/webrtc/rtc_video_decoder_adapter_unittest.cc index 5332faa4..9446c35 100644 --- a/content/renderer/media/webrtc/rtc_video_decoder_adapter_unittest.cc +++ b/content/renderer/media/webrtc/rtc_video_decoder_adapter_unittest.cc
@@ -199,7 +199,7 @@ uint32_t timestamp) { webrtc::EncodedImage input_image(buf, 1, 1); input_image._completeFrame = true; - input_image._frameType = webrtc::kVideoFrameKey; + input_image._frameType = webrtc::VideoFrameType::kVideoFrameKey; input_image.SetTimestamp(timestamp); webrtc::ColorSpace webrtc_color_space; webrtc_color_space.set_primaries_from_uint8(1);
diff --git a/content/renderer/media/webrtc/rtc_video_decoder_unittest.cc b/content/renderer/media/webrtc/rtc_video_decoder_unittest.cc index 15ff441..9cdf2c5 100644 --- a/content/renderer/media/webrtc/rtc_video_decoder_unittest.cc +++ b/content/renderer/media/webrtc/rtc_video_decoder_unittest.cc
@@ -369,7 +369,7 @@ input_image._completeFrame = true; input_image._encodedWidth = 0; input_image._encodedHeight = 0; - input_image._frameType = webrtc::kVideoFrameDelta; + input_image._frameType = webrtc::VideoFrameType::kVideoFrameDelta; input_image.set_buffer(buffer, sizeof(buffer)); input_image.set_size(sizeof(buffer)); EXPECT_EQ(WEBRTC_VIDEO_CODEC_ERROR, @@ -406,7 +406,7 @@ input_image._completeFrame = true; input_image._encodedWidth = 640; input_image._encodedHeight = 480; - input_image._frameType = webrtc::kVideoFrameKey; + input_image._frameType = webrtc::VideoFrameType::kVideoFrameKey; input_image.set_buffer(buffer, sizeof(buffer)); input_image.set_size(sizeof(buffer)); @@ -445,7 +445,7 @@ input_image._completeFrame = true; input_image._encodedWidth = 0; input_image._encodedHeight = 0; - input_image._frameType = webrtc::kVideoFrameKey; + input_image._frameType = webrtc::VideoFrameType::kVideoFrameKey; input_image.set_buffer(buffer, sizeof(buffer)); input_image.set_size(sizeof(buffer)); const int kNumDecodeRequests = 3; @@ -467,7 +467,7 @@ input_image._completeFrame = true; input_image._encodedWidth = 640; input_image._encodedHeight = 480; - input_image._frameType = webrtc::kVideoFrameKey; + input_image._frameType = webrtc::VideoFrameType::kVideoFrameKey; input_image.set_buffer(buffer, sizeof(buffer)); input_image.set_size(sizeof(buffer)); EXPECT_CALL(*mock_vda_, Decode(_)).Times(1);
diff --git a/content/renderer/media/webrtc/rtc_video_encoder.cc b/content/renderer/media/webrtc/rtc_video_encoder.cc index 6724b35..4e01153 100644 --- a/content/renderer/media/webrtc/rtc_video_encoder.cc +++ b/content/renderer/media/webrtc/rtc_video_encoder.cc
@@ -572,7 +572,8 @@ image.SetTimestamp(rtp_timestamp.value()); image.capture_time_ms_ = capture_timestamp_ms.value(); image._frameType = - (metadata.key_frame ? webrtc::kVideoFrameKey : webrtc::kVideoFrameDelta); + (metadata.key_frame ? webrtc::VideoFrameType::kVideoFrameKey + : webrtc::VideoFrameType::kVideoFrameDelta); image.content_type_ = video_content_type_; image._completeFrame = true; @@ -802,7 +803,7 @@ if (video_codec_type_ == webrtc::kVideoCodecVP8) { info.codecSpecific.VP8.keyIdx = -1; } else if (video_codec_type_ == webrtc::kVideoCodecVP9) { - bool key_frame = image._frameType == webrtc::kVideoFrameKey; + bool key_frame = image._frameType == webrtc::VideoFrameType::kVideoFrameKey; info.codecSpecific.VP9.inter_pic_predicted = key_frame ? false : true; info.codecSpecific.VP9.flexible_mode = false; info.codecSpecific.VP9.ss_data_available = key_frame ? true : false; @@ -918,8 +919,9 @@ return WEBRTC_VIDEO_CODEC_UNINITIALIZED; } - const bool want_key_frame = frame_types && frame_types->size() && - frame_types->front() == webrtc::kVideoFrameKey; + const bool want_key_frame = + frame_types && frame_types->size() && + frame_types->front() == webrtc::VideoFrameType::kVideoFrameKey; base::ScopedAllowBaseSyncPrimitivesOutsideBlockingScope allow_wait; base::WaitableEvent encode_waiter( base::WaitableEvent::ResetPolicy::MANUAL,
diff --git a/content/renderer/media/webrtc/transceiver_state_surfacer.cc b/content/renderer/media/webrtc/transceiver_state_surfacer.cc index 68b57de..cef5e59 100644 --- a/content/renderer/media/webrtc/transceiver_state_surfacer.cc +++ b/content/renderer/media/webrtc/transceiver_state_surfacer.cc
@@ -6,6 +6,7 @@ #include "content/renderer/media/webrtc/webrtc_util.h" #include "third_party/webrtc/api/rtp_transceiver_interface.h" +#include "third_party/webrtc/api/sctp_transport_interface.h" namespace content { @@ -26,6 +27,7 @@ signaling_task_runner_(other.signaling_task_runner_), is_initialized_(other.is_initialized_), states_obtained_(other.states_obtained_), + sctp_transport_snapshot_(other.sctp_transport_snapshot_), transceiver_states_(std::move(other.transceiver_states_)) { // Explicitly null |other|'s task runners for use in destructor. other.main_task_runner_ = nullptr; @@ -43,6 +45,7 @@ main_task_runner_ = other.main_task_runner_; signaling_task_runner_ = other.signaling_task_runner_; states_obtained_ = other.states_obtained_; + sctp_transport_snapshot_ = other.sctp_transport_snapshot_; transceiver_states_ = std::move(other.transceiver_states_); // Explicitly null |other|'s task runners for use in destructor. other.main_task_runner_ = nullptr; @@ -51,11 +54,25 @@ } void TransceiverStateSurfacer::Initialize( + scoped_refptr<webrtc::PeerConnectionInterface> native_peer_connection, scoped_refptr<WebRtcMediaStreamTrackAdapterMap> track_adapter_map, std::vector<rtc::scoped_refptr<webrtc::RtpTransceiverInterface>> webrtc_transceivers) { DCHECK(signaling_task_runner_->BelongsToCurrentThread()); DCHECK(!is_initialized_); + DCHECK(native_peer_connection); + sctp_transport_snapshot_.transport = + native_peer_connection->GetSctpTransport(); + if (sctp_transport_snapshot_.transport) { + sctp_transport_snapshot_.sctp_transport_state = + sctp_transport_snapshot_.transport->Information(); + if (sctp_transport_snapshot_.sctp_transport_state.dtls_transport()) { + sctp_transport_snapshot_.dtls_transport_state = + sctp_transport_snapshot_.sctp_transport_state.dtls_transport() + ->Information(); + } + } + for (auto& webrtc_transceiver : webrtc_transceivers) { // Create the sender state. base::Optional<RtpSenderState> sender_state; @@ -107,6 +124,13 @@ is_initialized_ = true; } +blink::WebRTCSctpTransportSnapshot +TransceiverStateSurfacer::SctpTransportSnapshot() { + DCHECK(main_task_runner_->BelongsToCurrentThread()); + DCHECK(is_initialized_); + return sctp_transport_snapshot_; +} + std::vector<RtpTransceiverState> TransceiverStateSurfacer::ObtainStates() { DCHECK(main_task_runner_->BelongsToCurrentThread()); DCHECK(is_initialized_);
diff --git a/content/renderer/media/webrtc/transceiver_state_surfacer.h b/content/renderer/media/webrtc/transceiver_state_surfacer.h index d49de68..133a206 100644 --- a/content/renderer/media/webrtc/transceiver_state_surfacer.h +++ b/content/renderer/media/webrtc/transceiver_state_surfacer.h
@@ -7,7 +7,9 @@ #include "content/renderer/media/webrtc/rtc_rtp_transceiver.h" #include "content/renderer/media/webrtc/webrtc_media_stream_track_adapter_map.h" +#include "third_party/blink/public/platform/web_rtc_peer_connection_handler_client.h" #include "third_party/webrtc/api/rtp_transceiver_interface.h" +#include "third_party/webrtc/api/sctp_transport_interface.h" #include "third_party/webrtc/rtc_base/ref_count.h" #include "third_party/webrtc/rtc_base/ref_counted_object.h" @@ -39,11 +41,13 @@ // Must be invoked on the signaling thread. void Initialize( + scoped_refptr<webrtc::PeerConnectionInterface> native_peer_connection, scoped_refptr<WebRtcMediaStreamTrackAdapterMap> track_adapter_map, std::vector<rtc::scoped_refptr<webrtc::RtpTransceiverInterface>> transceivers); // Must be invoked on the main thread. + blink::WebRTCSctpTransportSnapshot SctpTransportSnapshot(); std::vector<RtpTransceiverState> ObtainStates(); protected: @@ -51,6 +55,7 @@ scoped_refptr<base::SingleThreadTaskRunner> signaling_task_runner_; bool is_initialized_; bool states_obtained_; + blink::WebRTCSctpTransportSnapshot sctp_transport_snapshot_; std::vector<RtpTransceiverState> transceiver_states_; };
diff --git a/content/renderer/media/webrtc/transceiver_state_surfacer_unittest.cc b/content/renderer/media/webrtc/transceiver_state_surfacer_unittest.cc index 190acad..1b97d981 100644 --- a/content/renderer/media/webrtc/transceiver_state_surfacer_unittest.cc +++ b/content/renderer/media/webrtc/transceiver_state_surfacer_unittest.cc
@@ -25,8 +25,20 @@ #include "third_party/blink/public/platform/web_string.h" #include "third_party/blink/public/web/web_heap.h" +using testing::AnyNumber; +using testing::Return; + namespace content { +class MockSctpTransport : public webrtc::SctpTransportInterface { + public: + MOCK_CONST_METHOD0(dtls_transport, + rtc::scoped_refptr<webrtc::DtlsTransportInterface>()); + MOCK_CONST_METHOD0(Information, webrtc::SctpTransportInformation()); + MOCK_METHOD1(RegisterObserver, void(webrtc::SctpTransportObserverInterface*)); + MOCK_METHOD0(UnregisterObserver, void()); +}; + class TransceiverStateSurfacerTest : public ::testing::Test { public: void SetUp() override { @@ -36,6 +48,11 @@ dependency_factory_.get(), main_task_runner_); surfacer_.reset(new TransceiverStateSurfacer(main_task_runner_, signaling_task_runner())); + peer_connection_ = dependency_factory_->CreatePeerConnection( + webrtc::PeerConnectionInterface::RTCConfiguration(), nullptr, nullptr); + EXPECT_CALL(*(static_cast<MockPeerConnectionImpl*>(peer_connection_.get())), + GetSctpTransport()) + .Times(AnyNumber()); } void TearDown() override { @@ -136,6 +153,14 @@ void ObtainStatesAndExpectInitialized( rtc::scoped_refptr<webrtc::RtpTransceiverInterface> webrtc_transceiver) { + // Inspect SCTP transport + auto sctp_snapshot = surfacer_->SctpTransportSnapshot(); + EXPECT_EQ(peer_connection_->GetSctpTransport(), sctp_snapshot.transport); + if (peer_connection_->GetSctpTransport()) { + EXPECT_EQ(peer_connection_->GetSctpTransport()->dtls_transport(), + sctp_snapshot.sctp_transport_state.dtls_transport()); + } + // Inspect transceivers auto transceiver_states = surfacer_->ObtainStates(); EXPECT_EQ(1u, transceiver_states.size()); auto& transceiver_state = transceiver_states[0]; @@ -216,7 +241,8 @@ transceivers, base::WaitableEvent* waitable_event) { DCHECK(signaling_task_runner()->BelongsToCurrentThread()); - surfacer_->Initialize(track_adapter_map_, std::move(transceivers)); + surfacer_->Initialize(peer_connection_, track_adapter_map_, + std::move(transceivers)); waitable_event->Signal(); } @@ -226,7 +252,8 @@ base::OnceCallback<void()> callback, base::RunLoop* run_loop) { DCHECK(signaling_task_runner()->BelongsToCurrentThread()); - surfacer_->Initialize(track_adapter_map_, std::move(transceivers)); + surfacer_->Initialize(peer_connection_, track_adapter_map_, + std::move(transceivers)); main_task_runner_->PostTask( FROM_HERE, base::BindOnce(&TransceiverStateSurfacerTest:: @@ -246,6 +273,7 @@ base::test::ScopedTaskEnvironment scoped_task_environment_; protected: + scoped_refptr<webrtc::PeerConnectionInterface> peer_connection_; std::unique_ptr<MockPeerConnectionDependencyFactory> dependency_factory_; scoped_refptr<base::SingleThreadTaskRunner> main_task_runner_; scoped_refptr<WebRtcMediaStreamTrackAdapterMap> track_adapter_map_; @@ -332,4 +360,26 @@ EXPECT_FALSE(transceiver_state.current_direction()); } +TEST_F(TransceiverStateSurfacerTest, SurfaceTransceiverWithSctpTransport) { + auto local_track_adapter = CreateLocalTrackAndAdapter("local_track"); + auto webrtc_transceiver = CreateWebRtcTransceiver( + local_track_adapter->webrtc_track(), "local_stream", "remote_track", + "remote_stream", nullptr); + rtc::scoped_refptr<MockSctpTransport> mock_sctp_transport = + new rtc::RefCountedObject<MockSctpTransport>(); + webrtc::SctpTransportInformation sctp_transport_info( + webrtc::SctpTransportState::kNew); + EXPECT_CALL(*(static_cast<MockPeerConnectionImpl*>(peer_connection_.get())), + GetSctpTransport()) + .WillRepeatedly(Return(mock_sctp_transport)); + EXPECT_CALL(*mock_sctp_transport.get(), Information()) + .WillRepeatedly(Return(sctp_transport_info)); + EXPECT_CALL(*mock_sctp_transport.get(), dtls_transport()).Times(AnyNumber()); + auto waitable_event = + AsyncInitializeSurfacerWithWaitableEvent({webrtc_transceiver}); + waitable_event->Wait(); + EXPECT_TRUE(surfacer_->SctpTransportSnapshot().transport); + ObtainStatesAndExpectInitialized(webrtc_transceiver); +} + } // namespace content
diff --git a/content/renderer/media/webrtc/webrtc_set_description_observer.cc b/content/renderer/media/webrtc/webrtc_set_description_observer.cc index dcd7ff1..bb3a737 100644 --- a/content/renderer/media/webrtc/webrtc_set_description_observer.cc +++ b/content/renderer/media/webrtc/webrtc_set_description_observer.cc
@@ -15,6 +15,7 @@ WebRtcSetDescriptionObserver::States::States(States&& other) : signaling_state(other.signaling_state), + sctp_transport_state(std::move(other.sctp_transport_state)), transceiver_states(std::move(other.transceiver_states)) {} WebRtcSetDescriptionObserver::States::~States() = default; @@ -22,6 +23,7 @@ WebRtcSetDescriptionObserver::States& WebRtcSetDescriptionObserver::States:: operator=(States&& other) { signaling_state = other.signaling_state; + sctp_transport_state = std::move(other.sctp_transport_state); transceiver_states = std::move(other.transceiver_states); return *this; } @@ -70,7 +72,7 @@ } TransceiverStateSurfacer transceiver_state_surfacer(main_task_runner_, signaling_task_runner_); - transceiver_state_surfacer.Initialize(track_adapter_map_, + transceiver_state_surfacer.Initialize(pc_, track_adapter_map_, std::move(transceivers)); main_task_runner_->PostTask( FROM_HERE, base::BindOnce(&WebRtcSetDescriptionObserverHandlerImpl:: @@ -87,6 +89,8 @@ CHECK(main_task_runner_->BelongsToCurrentThread()); WebRtcSetDescriptionObserver::States states; states.signaling_state = signaling_state; + states.sctp_transport_state = + transceiver_state_surfacer.SctpTransportSnapshot(); states.transceiver_states = transceiver_state_surfacer.ObtainStates(); observer_->OnSetDescriptionComplete(std::move(error), std::move(states)); }
diff --git a/content/renderer/media/webrtc/webrtc_set_description_observer.h b/content/renderer/media/webrtc/webrtc_set_description_observer.h index 1dd218b8..7d8acef 100644 --- a/content/renderer/media/webrtc/webrtc_set_description_observer.h +++ b/content/renderer/media/webrtc/webrtc_set_description_observer.h
@@ -49,6 +49,7 @@ States& operator=(States&& other); webrtc::PeerConnectionInterface::SignalingState signaling_state; + blink::WebRTCSctpTransportSnapshot sctp_transport_state; std::vector<RtpTransceiverState> transceiver_states; DISALLOW_COPY_AND_ASSIGN(States);
diff --git a/content/renderer/mus/renderer_window_tree_client.cc b/content/renderer/mus/renderer_window_tree_client.cc index 004f583..3efa3d342 100644 --- a/content/renderer/mus/renderer_window_tree_client.cc +++ b/content/renderer/mus/renderer_window_tree_client.cc
@@ -298,9 +298,6 @@ void RendererWindowTreeClient::OnWindowVisibilityChanged(ws::Id window_id, bool visible) {} -void RendererWindowTreeClient::OnWindowOpacityChanged(ws::Id window_id, - float new_opacity) {} - void RendererWindowTreeClient::OnWindowDisplayChanged(ws::Id window_id, int64_t display_id) {}
diff --git a/content/renderer/mus/renderer_window_tree_client.h b/content/renderer/mus/renderer_window_tree_client.h index 8d26882a..0938ed3 100644 --- a/content/renderer/mus/renderer_window_tree_client.h +++ b/content/renderer/mus/renderer_window_tree_client.h
@@ -156,8 +156,6 @@ ws::mojom::OrderDirection direction) override; void OnWindowDeleted(ws::Id window_id) override; void OnWindowVisibilityChanged(ws::Id window_id, bool visible) override; - void OnWindowOpacityChanged(ws::Id window_id, - float new_opacity) override; void OnWindowDisplayChanged(ws::Id window_id, int64_t display_id) override; void OnWindowParentDrawnStateChanged(ws::Id window_id, bool drawn) override; void OnWindowSharedPropertyChanged(
diff --git a/content/renderer/render_frame_impl.cc b/content/renderer/render_frame_impl.cc index 45c1f0b..f90ff1b 100644 --- a/content/renderer/render_frame_impl.cc +++ b/content/renderer/render_frame_impl.cc
@@ -2330,10 +2330,14 @@ // This executes the unload handlers on this frame and its local descendants. bool success = frame_->Swap(proxy->web_frame()); - // For main frames, the swap should have cleared the RenderView's pointer to - // this frame. - if (is_main_frame) + if (is_main_frame) { + // TODO(crbug.com/939262): Looking for ways a main frame could be left in a + // provisional state and not deleted by the browser. + CHECK(success); + // For main frames, the swap should have cleared the RenderView's pointer to + // this frame. CHECK(!render_view->main_render_frame_); + } if (!success) { // The swap can fail when the frame is detached during swap (this can @@ -2451,10 +2455,16 @@ TRACE_EVENT_INSTANT0("test_tracing", "JavaScriptExecuteRequest", TRACE_EVENT_SCOPE_THREAD); + // Note that ExecuteScriptAndReturnValue may end up killing this object. + base::WeakPtr<RenderFrameImpl> weak_this = weak_factory_.GetWeakPtr(); + v8::HandleScope handle_scope(v8::Isolate::GetCurrent()); v8::Local<v8::Value> result = frame_->ExecuteScriptAndReturnValue( WebScriptSource(WebString::FromUTF16(javascript))); + if (!weak_this) + return; + std::move(callback).Run(GetJavaScriptExecutionResult(result)); } @@ -2465,6 +2475,9 @@ TRACE_EVENT_INSTANT0("test_tracing", "JavaScriptExecuteRequestForTests", TRACE_EVENT_SCOPE_THREAD); + // Note that ExecuteScriptAndReturnValue may end up killing this object. + base::WeakPtr<RenderFrameImpl> weak_this = weak_factory_.GetWeakPtr(); + // A bunch of tests expect to run code in the context of a user gesture, which // can grant additional privileges (e.g. the ability to create popups). base::Optional<blink::WebScopedUserGesture> gesture; @@ -2475,6 +2488,9 @@ v8::Local<v8::Value> result = frame_->ExecuteScriptAndReturnValue( WebScriptSource(WebString::FromUTF16(javascript))); + if (!weak_this) + return; + std::move(callback).Run(GetJavaScriptExecutionResult(result)); } @@ -2514,8 +2530,14 @@ void RenderFrameImpl::JavaScriptIsolatedWorldRequest::Completed( const blink::WebVector<v8::Local<v8::Value>>& result) { + if (!render_frame_impl_) { + // If the frame is gone, there's nothing that can be safely done; bail. + delete this; + return; + } + base::Value value; - if (render_frame_impl_.get() && !result.empty()) { + if (!result.empty()) { // It's safe to always use the main world context when converting // here. V8ValueConverterImpl shouldn't actually care about the // context scope, and it switches to v8::Object's creation context @@ -3917,14 +3939,13 @@ std::unique_ptr<blink::WebApplicationCacheHost> RenderFrameImpl::CreateApplicationCacheHost( + blink::WebDocumentLoader* document_loader, blink::WebApplicationCacheHostClient* client) { if (!frame_ || !frame_->View()) return nullptr; - NavigationState* navigation_state = NavigationState::FromDocumentLoader( - frame_->GetProvisionalDocumentLoader() - ? frame_->GetProvisionalDocumentLoader() - : frame_->GetDocumentLoader()); + NavigationState* navigation_state = + NavigationState::FromDocumentLoader(document_loader); scoped_refptr<base::SingleThreadTaskRunner> task_runner = frame_->GetTaskRunner(blink::TaskType::kNetworking); @@ -4988,6 +5009,13 @@ Send(new FrameHostMsg_DidBlockFramebust(GetRoutingID(), url)); } +void RenderFrameImpl::NavigateBackForwardSoon(int offset, + bool has_user_gesture) { + render_view()->NavigateBackForwardSoon(offset, has_user_gesture); + Send(new FrameHostMsg_GoToEntryAtOffset(GetRoutingID(), offset, + has_user_gesture)); +} + base::UnguessableToken RenderFrameImpl::GetDevToolsFrameToken() { return devtools_frame_token_; }
diff --git a/content/renderer/render_frame_impl.h b/content/renderer/render_frame_impl.h index acd45e2..888410ee 100644 --- a/content/renderer/render_frame_impl.h +++ b/content/renderer/render_frame_impl.h
@@ -662,6 +662,7 @@ const blink::WebString& sink_id, blink::WebLayerTreeView* layer_tree_view) override; std::unique_ptr<blink::WebApplicationCacheHost> CreateApplicationCacheHost( + blink::WebDocumentLoader* document_loader, blink::WebApplicationCacheHostClient* client) override; std::unique_ptr<blink::WebContentSettingsClient> CreateWorkerContentSettingsClient() override; @@ -773,6 +774,7 @@ blink::WebEffectiveConnectionType) override; blink::WebURLRequest::PreviewsState GetPreviewsStateForFrame() const override; void DidBlockFramebust(const blink::WebURL& url) override; + void NavigateBackForwardSoon(int offset, bool has_user_gesture) override; base::UnguessableToken GetDevToolsFrameToken() override; void RenderFallbackContentInParentProcess() override; void AbortClientNavigation() override;
diff --git a/content/renderer/render_view_impl.cc b/content/renderer/render_view_impl.cc index 0c6341e1..2002ea3d 100644 --- a/content/renderer/render_view_impl.cc +++ b/content/renderer/render_view_impl.cc
@@ -1728,8 +1728,6 @@ "NavigateBackForwardSoon", blink::WebScopedVirtualTimePauser::VirtualTaskDuration::kInstant); history_navigation_virtual_time_pauser_.PauseVirtualTime(); - Send(new ViewHostMsg_GoToEntryAtOffset(GetRoutingID(), offset, - has_user_gesture)); } void RenderViewImpl::DidCommitProvisionalHistoryLoad() {
diff --git a/content/renderer/render_view_impl.h b/content/renderer/render_view_impl.h index 552187d9..d8d10187 100644 --- a/content/renderer/render_view_impl.h +++ b/content/renderer/render_view_impl.h
@@ -210,6 +210,7 @@ // synchronously from the renderer. void SetFocusAndActivateForTesting(bool enable); + void NavigateBackForwardSoon(int offset, bool has_user_gesture); void DidCommitProvisionalHistoryLoad(); // Registers a watcher to observe changes in the @@ -251,7 +252,6 @@ bool CanUpdateLayout() override; void DidUpdateMainFrameLayout() override; blink::WebString AcceptLanguages() override; - void NavigateBackForwardSoon(int offset, bool has_user_gesture) override; int HistoryBackListCount() override; int HistoryForwardListCount() override; void ZoomLimitsChanged(double minimum_level, double maximum_level) override;
diff --git a/content/renderer/renderer_blink_platform_impl.cc b/content/renderer/renderer_blink_platform_impl.cc index 34b2c4da..c4b8ecb 100644 --- a/content/renderer/renderer_blink_platform_impl.cc +++ b/content/renderer/renderer_blink_platform_impl.cc
@@ -930,8 +930,10 @@ attributes.sample_buffers = 0; attributes.bind_generates_resource = false; attributes.enable_raster_interface = web_attributes.enable_raster_interface; - // Prefer discrete GPU for WebGL. - attributes.gpu_preference = gl::PreferDiscreteGpu; + + attributes.gpu_preference = web_attributes.prefer_integrated_gpu + ? gl::PreferIntegratedGpu + : gl::PreferDiscreteGpu; attributes.fail_if_major_perf_caveat = web_attributes.fail_if_major_performance_caveat;
diff --git a/content/test/gpu/gpu_tests/gpu_integration_test.py b/content/test/gpu/gpu_tests/gpu_integration_test.py index eeea2c9..10e87bac 100644 --- a/content/test/gpu/gpu_tests/gpu_integration_test.py +++ b/content/test/gpu/gpu_tests/gpu_integration_test.py
@@ -413,7 +413,7 @@ cmd_decoder = gpu_helper.GetCommandDecoder(gpu_info) # all spaces in the tag will be replaced by '-', and all letters will # be converted to its lower case form. - tags.extend([tag.lower().replace(' ', '-') for tag in [ + tags.extend([tag.lower().replace(' ', '-').replace('_', '-') for tag in [ gpu_vendor, gpu_device_tag, angle_renderer, cmd_decoder]]) return tags
diff --git a/content/test/gpu/gpu_tests/gpu_integration_test_unittest.py b/content/test/gpu/gpu_tests/gpu_integration_test_unittest.py index d81211a..017a1da 100644 --- a/content/test/gpu/gpu_tests/gpu_integration_test_unittest.py +++ b/content/test/gpu/gpu_tests/gpu_integration_test_unittest.py
@@ -14,6 +14,7 @@ from gpu_tests import path_util from gpu_tests import gpu_integration_test +from gpu_tests import webgl_conformance_integration_test path_util.AddDirToPathIfNeeded(path_util.GetChromiumSrcDir(), 'tools', 'perf') from chrome_telemetry_build import chromium_config @@ -68,7 +69,11 @@ class MockArgs(object): - pass + + def __init__(self, is_asan=False, webgl_version='1.0.0'): + self.is_asan = is_asan + self.webgl_conformance_version = webgl_version + self.webgl2_only = False class MockAbstractGpuTestClass(gpu_integration_test.GpuIntegrationTest): @@ -106,6 +111,22 @@ return self._returned_browser +def _generateNvidiaExampleTagsForTestClassAndArgs(test_class, args): + class MockTestCase(test_class, MockAbstractGpuTestClass): + + @classmethod + def ExpectationsFiles(cls): + return ['example_test_expectations.txt'] + + _ = [_ for _ in MockTestCase.GenerateGpuTests(args)] + platform = MockPlatform('win', 'win10') + browser = MockBrowser( + platform, VENDOR_NVIDIA, 0x1cb3, browser_type='release', + gl_renderer='ANGLE Direct3D9') + possible_browser = MockPossibleBrowser(browser) + return set(MockTestCase.GenerateTags(args, possible_browser)) + + class GpuIntegrationTestUnittest(unittest.TestCase): def setUp(self): self._test_state = {} @@ -120,9 +141,25 @@ self.assertFalse(MockTestCaseWithoutExpectationsFile.GenerateTags( args, possible_browser)) + def testGenerateWebglConformanceExampleTagsForWebglVersion1andAsan(self): + args = MockArgs(is_asan=True, webgl_version='1.0.0') + tag_set = _generateNvidiaExampleTagsForTestClassAndArgs( + webgl_conformance_integration_test.WebGLConformanceIntegrationTest, + args) + self.assertTrue(set(['asan', 'webgl-version-1']).issubset(tag_set)) + self.assertFalse(set(['no-asan', 'webgl-version-2']) & tag_set) + + def testGenerateWebglConformanceExampleTagsForWebglVersion2andNoAsan(self): + args = MockArgs(is_asan=False, webgl_version='2.0.0') + tag_set = _generateNvidiaExampleTagsForTestClassAndArgs( + webgl_conformance_integration_test.WebGLConformanceIntegrationTest, + args) + self.assertTrue(set(['no-asan', 'webgl-version-2']) .issubset(tag_set)) + self.assertFalse(set(['asan', 'webgl-version-1']) & tag_set) + def testGenerateNvidiaExampleTags(self): args = MockArgs() - platform = MockPlatform('mac', 'mojave') + platform = MockPlatform('win', 'win10') browser = MockBrowser( platform, VENDOR_NVIDIA, 0x1cb3, browser_type='release', gl_renderer='ANGLE Direct3D9') @@ -130,8 +167,8 @@ self.assertEqual( set(MockTestCaseWithExpectationsFile.GenerateTags( args, possible_browser)), - set(['mac', 'mojave', 'release', 'nvidia', 'nvidia-0x1cb3', - 'd3d9', 'no_passthrough'])) + set(['win', 'win10', 'release', 'nvidia', 'nvidia-0x1cb3', + 'd3d9', 'no-passthrough'])) def testGenerateVendorTagUsingVendorString(self): args = MockArgs() @@ -162,7 +199,7 @@ args, possible_browser)), set(['mac', 'mojave', 'release', 'imagination', 'imagination-triangle-monster-3000', - 'no_angle', 'no_passthrough'])) + 'no-angle', 'no-passthrough'])) def testSimpleIntegrationTest(self): self._RunIntegrationTest(
diff --git a/content/test/gpu/gpu_tests/webgl_conformance_expectations.py b/content/test/gpu/gpu_tests/webgl_conformance_expectations.py index 9e89229e..923069b 100644 --- a/content/test/gpu/gpu_tests/webgl_conformance_expectations.py +++ b/content/test/gpu/gpu_tests/webgl_conformance_expectations.py
@@ -548,6 +548,8 @@ ['mac', ('nvidia', 0xfe9)], bug=784817) self.Fail('conformance/uniforms/uniform-samplers-test.html', ['mac', 'debug', ('nvidia', 0xfe9)], bug=871352) + self.Flaky('conformance/glsl/misc/shader-with-non-reserved-words.html', + ['mac', 'debug', ('nvidia', 0xfe9)], bug=929009) # Already fixed with Mesa 17.1.6 self.Fail('conformance/extensions/webgl-compressed-texture-astc.html',
diff --git a/content/test/gpu/gpu_tests/webgl_conformance_integration_test.py b/content/test/gpu/gpu_tests/webgl_conformance_integration_test.py index a5367d4..d0d90f8 100644 --- a/content/test/gpu/gpu_tests/webgl_conformance_integration_test.py +++ b/content/test/gpu/gpu_tests/webgl_conformance_integration_test.py
@@ -473,6 +473,14 @@ return test_paths + @classmethod + def GetPlatformTags(cls, browser): + tags = super(WebGLConformanceIntegrationTest, cls).GetPlatformTags(browser) + tags.extend( + [['no-asan', 'asan'][cls._is_asan], + 'webgl-version-%d' % cls._webgl_version]) + return tags + def load_tests(loader, tests, pattern): del loader, tests, pattern # Unused.
diff --git a/device/vr/windows_mixed_reality/mixed_reality_renderloop.cc b/device/vr/windows_mixed_reality/mixed_reality_renderloop.cc index a5326123..c9b6d5f5 100644 --- a/device/vr/windows_mixed_reality/mixed_reality_renderloop.cc +++ b/device/vr/windows_mixed_reality/mixed_reality_renderloop.cc
@@ -332,6 +332,7 @@ pose_ = nullptr; rendering_params_ = nullptr; camera_ = nullptr; + spatial_interaction_manager_ = nullptr; if (window_) DestroyWindow(window_->hwnd());
diff --git a/device/vr/windows_mixed_reality/mixed_reality_statics.cc b/device/vr/windows_mixed_reality/mixed_reality_statics.cc index 42172ad..99c55a26 100644 --- a/device/vr/windows_mixed_reality/mixed_reality_statics.cc +++ b/device/vr/windows_mixed_reality/mixed_reality_statics.cc
@@ -12,7 +12,6 @@ #include "base/strings/utf_string_conversions.h" #include "base/win/core_winrt_util.h" #include "base/win/scoped_hstring.h" -#include "base/win/scoped_winrt_initializer.h" namespace device { @@ -31,8 +30,6 @@ bool IsApiAvailable() override; private: - base::win::ScopedWinrtInitializer initializer_; - // Adds get_IsAvailable and get_IsSupported to HolographicSpaceStatics. ComPtr<IHolographicSpaceStatics2> holographic_space_statics_; }; @@ -45,7 +42,7 @@ MixedRealityDeviceStatics::~MixedRealityDeviceStatics() {} MixedRealityDeviceStaticsImpl::MixedRealityDeviceStaticsImpl() { - if (!initializer_.Succeeded() || + if (FAILED(base::win::RoInitialize(RO_INIT_MULTITHREADED)) || !base::win::ScopedHString::ResolveCoreWinRTStringDelayload()) { return; } @@ -63,8 +60,12 @@ } MixedRealityDeviceStaticsImpl::~MixedRealityDeviceStaticsImpl() { - // Explicitly null this out before initializer_ is destroyed. + // Explicitly null this out before the COM thread is Uninitialized. holographic_space_statics_ = nullptr; + + // TODO(http://crbug.com/943250): Investigate why we get an AV in + // combase!CoUninitialize in Windows.Perception.Stubs if we Uninitialize COM + // here. Until then, let the system clean it up during process teardown. } bool MixedRealityDeviceStaticsImpl::IsHardwareAvailable() {
diff --git a/extensions/browser/api/socket/tcp_socket.cc b/extensions/browser/api/socket/tcp_socket.cc index 12a980ed..4845705 100644 --- a/extensions/browser/api/socket/tcp_socket.cc +++ b/extensions/browser/api/socket/tcp_socket.cc
@@ -45,6 +45,10 @@ *version_out = network::mojom::SSLVersion::kTLS12; return true; } + if (version_str == "tls1.3") { + *version_out = network::mojom::SSLVersion::kTLS13; + return true; + } return false; } @@ -528,8 +532,7 @@ network::mojom::TLSClientSocketOptionsPtr mojo_socket_options = network::mojom::TLSClientSocketOptions::New(); - // TODO(https://crbug.com/904470): Support TLS 1.3 in the extensions API. - mojo_socket_options->version_max = network::mojom::SSLVersion::kTLS12; + mojo_socket_options->version_max = network::mojom::SSLVersion::kTLS13; if (options && options->tls_version.get()) { network::mojom::SSLVersion version_min, version_max;
diff --git a/extensions/browser/api/system_power_source/system_power_source_api_unittest.cc b/extensions/browser/api/system_power_source/system_power_source_api_unittest.cc index e08502c4..c7605ed 100644 --- a/extensions/browser/api/system_power_source/system_power_source_api_unittest.cc +++ b/extensions/browser/api/system_power_source/system_power_source_api_unittest.cc
@@ -29,7 +29,7 @@ void SetUp() override { ApiUnitTest::SetUp(); - chromeos::PowerManagerClient::Initialize(); + chromeos::PowerManagerClient::InitializeFake(); } void TearDown() override {
diff --git a/extensions/browser/url_loader_factory_manager.cc b/extensions/browser/url_loader_factory_manager.cc index 911a2f4..e0cfb48 100644 --- a/extensions/browser/url_loader_factory_manager.cc +++ b/extensions/browser/url_loader_factory_manager.cc
@@ -65,6 +65,7 @@ "072D729E856B1F2C9894AEEC3A5DF65E519D6BEE", "07333481B7B8D7F57A9BA64FB98CF86EA87455FC", "086E69ED9071DCB20C93A081A68360963AB09385", + "0A8E468BCEAA5626207AB77C431C31C1F2A8F76A", "0C011D916B15E5451E1B84BD14397B8EC98F455B", "0CB16BAEE070B7617E9188B387C44964FB705D79", "0EAEA2FDEE025D95B3ABB37014EFF5A98AC4BEAE", @@ -96,6 +97,7 @@ "44943FADD66932EF56EE3D856A9FAAD4A8AF0FD9", "47ADBB376050C083FFC54CC28CD3D1F54BF0BFED", "4913450195D177430217CAB64B356DC6F6B0F483", + "49FFDF2212E50090963E33159DBF853B5C475340", "5053323D1F7B6EEC97A77A350DB6D0D8E51CD0AC", "505F2C1E723731B2C8C9182FEAA73D00525B2048", "50DDD8734521B61564FCE273F8E60547F88BBCBE", @@ -111,6 +113,7 @@ "6AE81EF3B13B15080A2DDB23A205A24C65CCC10B", "6BA5F75FFF75B69507BC4B09B7094926EF93DBD2", "6E49449D56D031B87835CC767734AF5A064E1A13", + "71351EAA5C16350EC5A86C23D7A288317309E53D", "71CB78C3334D5122E7F23C8525AD24100CDE7D4A", "71EE66C0F71CD89BEE340F8568A44101D4C3A9A7", "7527942941BFF13D66B46E7A2A56FDBA873FB9E6", @@ -122,11 +125,13 @@ "83B6C75264D5D2F81FDEFD681EDD2076DD8F0B9B", "88C372CE52E21560C17BFD52556E60D694E12CAC", "88F5F459139892C0F5DF3022676726BB3F01FB5C", + "896C60AC2F7F03B4F582027DD2107F3BB67DF69D", "89C9B32115F19A18E9BE4906DC59F24A934CB9F0", "89F40D84C0C72C6B02B320716E877FB1671218E9", "8A0634388BCBB6D073E1C97B14C024396ED32D12", "8CDD303D6C341D9CAB16713C3CD7587B90A7A84A", "8CE6227B4E53DF42FF93B24F49D15EDE31E97E79", + "8E14F3080EF0D8AB5006544894610C2E0315B317", "934B8F5753A3E5A276FC7D0EE5E575B335A0CC76", "973E35633030AD27DABEC99609424A61386C7309", "97E04C5632954E778306CAC40B3F95C470B463B6",
diff --git a/extensions/common/api/socket.idl b/extensions/common/api/socket.idl index 8a8559ee..6e88aa6 100644 --- a/extensions/common/api/socket.idl +++ b/extensions/common/api/socket.idl
@@ -113,7 +113,8 @@ dictionary TLSVersionConstraints { // The minimum and maximum acceptable versions of TLS. These will - // be <code>tls1</code>, <code>tls1.1</code>, or <code>tls1.2</code>. + // be <code>tls1</code>, <code>tls1.1</code>, <code>tls1.2</code>, or + // <code>tls1.3</code>. DOMString? min; DOMString? max; };
diff --git a/extensions/common/api/sockets_tcp.idl b/extensions/common/api/sockets_tcp.idl index 2dffa17..c4adae80 100644 --- a/extensions/common/api/sockets_tcp.idl +++ b/extensions/common/api/sockets_tcp.idl
@@ -82,7 +82,8 @@ dictionary TLSVersionConstraints { // The minimum and maximum acceptable versions of TLS. These will - // be <code>tls1</code>, <code>tls1.1</code>, or <code>tls1.2</code>. + // be <code>tls1</code>, <code>tls1.1</code>, <code>tls1.2</code>, or + // <code>tls1.3</code>. DOMString? min; DOMString? max; };
diff --git a/extensions/renderer/BUILD.gn b/extensions/renderer/BUILD.gn index a7f43659..c7f428e5 100644 --- a/extensions/renderer/BUILD.gn +++ b/extensions/renderer/BUILD.gn
@@ -186,8 +186,6 @@ "renderer_extension_registry.h", "renderer_messaging_service.cc", "renderer_messaging_service.h", - "request_sender.cc", - "request_sender.h", "resource_bundle_source_map.cc", "resource_bundle_source_map.h", "resources/app_runtime_custom_bindings.js",
diff --git a/extensions/renderer/dispatcher.cc b/extensions/renderer/dispatcher.cc index aa8495a..1624903 100644 --- a/extensions/renderer/dispatcher.cc +++ b/extensions/renderer/dispatcher.cc
@@ -78,7 +78,6 @@ #include "extensions/renderer/render_frame_observer_natives.h" #include "extensions/renderer/renderer_extension_registry.h" #include "extensions/renderer/renderer_messaging_service.h" -#include "extensions/renderer/request_sender.h" #include "extensions/renderer/runtime_custom_bindings.h" #include "extensions/renderer/safe_builtins.h" #include "extensions/renderer/script_context.h"
diff --git a/extensions/renderer/request_sender.cc b/extensions/renderer/request_sender.cc deleted file mode 100644 index 1705457..0000000 --- a/extensions/renderer/request_sender.cc +++ /dev/null
@@ -1,156 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "extensions/renderer/request_sender.h" - -#include "base/metrics/histogram_macros.h" -#include "base/timer/elapsed_timer.h" -#include "base/values.h" -#include "content/public/renderer/render_frame.h" -#include "extensions/common/constants.h" -#include "extensions/common/extension_messages.h" -#include "extensions/renderer/bindings/api_binding_types.h" -#include "extensions/renderer/ipc_message_sender.h" -#include "extensions/renderer/script_context.h" -#include "third_party/blink/public/mojom/service_worker/service_worker_registration.mojom.h" -#include "third_party/blink/public/web/web_document.h" -#include "third_party/blink/public/web/web_local_frame.h" -#include "third_party/blink/public/web/web_scoped_user_gesture.h" -#include "third_party/blink/public/web/web_user_gesture_indicator.h" -#include "third_party/blink/public/web/web_user_gesture_token.h" - -namespace extensions { - -// Contains info relevant to a pending API request. -struct PendingRequest { - public: - PendingRequest(const std::string& name, - RequestSender::Source* source, - blink::WebUserGestureToken token) - : name(name), source(source), token(token) {} - - std::string name; - RequestSender::Source* source; - blink::WebUserGestureToken token; -}; - -RequestSender::RequestSender(IPCMessageSender* ipc_message_sender) - : ipc_message_sender_(ipc_message_sender) {} - -RequestSender::~RequestSender() {} - -void RequestSender::InsertRequest( - int request_id, - std::unique_ptr<PendingRequest> pending_request) { - DCHECK_EQ(0u, pending_requests_.count(request_id)); - pending_requests_[request_id] = std::move(pending_request); -} - -std::unique_ptr<PendingRequest> RequestSender::RemoveRequest(int request_id) { - auto i = pending_requests_.find(request_id); - if (i == pending_requests_.end()) - return std::unique_ptr<PendingRequest>(); - std::unique_ptr<PendingRequest> result = std::move(i->second); - pending_requests_.erase(i); - return result; -} - -int RequestSender::GetNextRequestId() const { - static int next_request_id = 0; - return next_request_id++; -} - -bool RequestSender::StartRequest(Source* source, - const std::string& name, - int request_id, - bool has_callback, - bool for_io_thread, - base::ListValue* value_args) { - ScriptContext* context = source->GetContext(); - if (!context) - return false; - - bool for_service_worker = - context->context_type() == Feature::SERVICE_WORKER_CONTEXT; - // Get the current RenderFrame so that we can send a routed IPC message from - // the correct source. - // Note that |render_frame| would be nullptr for Service Workers. Service - // Workers use control IPC instead. - content::RenderFrame* render_frame = context->GetRenderFrame(); - if (!for_service_worker && !render_frame) { - // It is important to early exit here for non Service Worker contexts so - // that we do not create orphaned PendingRequests below. - return false; - } - - // TODO(koz): See if we can make this a CHECK. - if (!context->HasAccessOrThrowError(name)) - return false; - - GURL source_url; - blink::WebLocalFrame* webframe = context->web_frame(); - if (webframe) - source_url = webframe->GetDocument().Url(); - - InsertRequest(request_id, - std::make_unique<PendingRequest>( - name, source, - blink::WebUserGestureIndicator::CurrentUserGestureToken())); - - auto params = std::make_unique<ExtensionHostMsg_Request_Params>(); - params->name = name; - params->arguments.Swap(value_args); - params->extension_id = context->GetExtensionID(); - params->source_url = source_url; - params->request_id = request_id; - params->has_callback = has_callback; - - // TODO(mustaq): What to do with extension service workers without - // RenderFrames? crbug/733679 - params->user_gesture = - blink::WebUserGestureIndicator::IsProcessingUserGestureThreadSafe( - webframe); - - // Set Service Worker specific params to default values. - params->worker_thread_id = -1; - params->service_worker_version_id = - blink::mojom::kInvalidServiceWorkerVersionId; - - binding::RequestThread thread = - for_io_thread ? binding::RequestThread::IO : binding::RequestThread::UI; - ipc_message_sender_->SendRequestIPC(context, std::move(params), thread); - return true; -} - -void RequestSender::HandleResponse(int request_id, - bool success, - const base::ListValue& response, - const std::string& error) { - base::ElapsedTimer timer; - std::unique_ptr<PendingRequest> request = RemoveRequest(request_id); - - if (!request.get()) { - // This can happen if a context is destroyed while a request is in flight. - return; - } - - // TODO(devlin): Would it be useful to partition this data based on - // extension function once we have a suitable baseline? crbug.com/608561. - blink::WebScopedUserGesture gesture(request->token); - request->source->OnResponseReceived( - request->name, request_id, success, response, error); - UMA_HISTOGRAM_TIMES("Extensions.Functions.HandleResponseElapsedTime", - timer.Elapsed()); -} - -void RequestSender::InvalidateSource(Source* source) { - for (auto it = pending_requests_.begin(); it != pending_requests_.end();) { - if (it->second->source == source) - pending_requests_.erase(it++); - else - ++it; - } -} - -} // namespace extensions
diff --git a/extensions/renderer/request_sender.h b/extensions/renderer/request_sender.h deleted file mode 100644 index 67fa6e49..0000000 --- a/extensions/renderer/request_sender.h +++ /dev/null
@@ -1,94 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef EXTENSIONS_RENDERER_REQUEST_SENDER_H_ -#define EXTENSIONS_RENDERER_REQUEST_SENDER_H_ - -#include <map> -#include <string> - -#include "base/macros.h" -#include "v8/include/v8.h" - -namespace base { -class ListValue; -} - -namespace extensions { -class IPCMessageSender; -class ScriptContext; - -struct PendingRequest; - -// Responsible for sending requests for named extension API functions to the -// extension host and routing the responses back to the caller. -class RequestSender { - public: - // Source represents a user of RequestSender. Every request is associated with - // a Source object, which will be notified when the corresponding response - // arrives. When a Source object is going away and there are pending requests, - // it should call InvalidateSource() to make sure no notifications are sent to - // it later. - class Source { - public: - virtual ~Source() {} - - virtual ScriptContext* GetContext() = 0; - virtual void OnResponseReceived(const std::string& name, - int request_id, - bool success, - const base::ListValue& response, - const std::string& error) = 0; - }; - - explicit RequestSender(IPCMessageSender* ipc_message_sender); - ~RequestSender(); - - // In order to avoid collision, all |request_id|s passed into StartRequest() - // should be generated by this method. - int GetNextRequestId() const; - - // Makes a call to the API function |name| that is to be handled by the - // extension host. The response to this request will be received in - // HandleResponse(). - // TODO(koz): Remove |request_id| and generate that internally. - // There are multiple of these per render view though, so we'll - // need to vend the IDs centrally. - // Returns true if the request is successfully sent. - bool StartRequest(Source* source, - const std::string& name, - int request_id, - bool has_callback, - bool for_io_thread, - base::ListValue* value_args); - - // Handles responses from the extension host to calls made by StartRequest(). - void HandleResponse(int request_id, - bool success, - const base::ListValue& response, - const std::string& error); - - // Notifies this that a request source is no longer valid. - // TODO(kalman): Do this in a generic/safe way. - void InvalidateSource(Source* source); - - private: - friend class ScopedTabID; - using PendingRequestMap = std::map<int, std::unique_ptr<PendingRequest>>; - - void InsertRequest(int request_id, - std::unique_ptr<PendingRequest> pending_request); - std::unique_ptr<PendingRequest> RemoveRequest(int request_id); - - PendingRequestMap pending_requests_; - - // Guaranteed to outlive this object. - IPCMessageSender* const ipc_message_sender_; - - DISALLOW_COPY_AND_ASSIGN(RequestSender); -}; - -} // namespace extensions - -#endif // EXTENSIONS_RENDERER_REQUEST_SENDER_H_
diff --git a/extensions/renderer/script_context.cc b/extensions/renderer/script_context.cc index 9f182fc..9e87412 100644 --- a/extensions/renderer/script_context.cc +++ b/extensions/renderer/script_context.cc
@@ -8,30 +8,25 @@ #include "base/containers/flat_set.h" #include "base/logging.h" #include "base/stl_util.h" -#include "base/strings/string_split.h" #include "base/strings/string_util.h" #include "base/strings/stringprintf.h" #include "base/values.h" #include "content/public/common/content_switches.h" #include "content/public/common/url_constants.h" #include "content/public/renderer/render_frame.h" -#include "content/public/renderer/v8_value_converter.h" #include "extensions/common/constants.h" #include "extensions/common/extension.h" #include "extensions/common/extension_api.h" #include "extensions/common/extension_urls.h" -#include "extensions/common/features/feature_provider.h" #include "extensions/common/manifest_handlers/sandboxed_page_info.h" #include "extensions/common/permissions/permissions_data.h" #include "extensions/renderer/renderer_extension_registry.h" #include "extensions/renderer/v8_helpers.h" #include "third_party/blink/public/mojom/service_worker/service_worker_registration.mojom.h" #include "third_party/blink/public/platform/web_security_origin.h" -#include "third_party/blink/public/platform/web_url_request.h" #include "third_party/blink/public/web/web_document.h" #include "third_party/blink/public/web/web_document_loader.h" #include "third_party/blink/public/web/web_local_frame.h" -#include "third_party/blink/public/web/web_view.h" #include "v8/include/v8.h" namespace extensions { @@ -338,35 +333,6 @@ return document_url; } -ScriptContext* ScriptContext::GetContext() { - DCHECK(thread_checker_.CalledOnValidThread()); - return this; -} - -void ScriptContext::OnResponseReceived(const std::string& name, - int request_id, - bool success, - const base::ListValue& response, - const std::string& error) { - DCHECK(thread_checker_.CalledOnValidThread()); - v8::HandleScope handle_scope(isolate()); - - v8::Local<v8::Value> argv[] = { - v8::Integer::New(isolate(), request_id), - v8::String::NewFromUtf8(isolate(), name.c_str(), - v8::NewStringType::kNormal) - .ToLocalChecked(), - v8::Boolean::New(isolate(), success), - content::V8ValueConverter::Create()->ToV8Value( - &response, v8::Local<v8::Context>::New(isolate(), v8_context_)), - v8::String::NewFromUtf8(isolate(), error.c_str(), - v8::NewStringType::kNormal) - .ToLocalChecked()}; - - module_system()->CallModuleMethodSafe("sendRequest", "handleResponse", - base::size(argv), argv); -} - bool ScriptContext::HasAPIPermission(APIPermission::ID permission) const { DCHECK(thread_checker_.CalledOnValidThread()); if (effective_extension_.get()) {
diff --git a/extensions/renderer/script_context.h b/extensions/renderer/script_context.h index 55f3462d..f714d8d 100644 --- a/extensions/renderer/script_context.h +++ b/extensions/renderer/script_context.h
@@ -18,7 +18,6 @@ #include "extensions/common/features/feature.h" #include "extensions/common/permissions/api_permission_set.h" #include "extensions/renderer/module_system.h" -#include "extensions/renderer/request_sender.h" #include "extensions/renderer/safe_builtins.h" #include "extensions/renderer/script_injection_callback.h" #include "url/gurl.h" @@ -43,7 +42,7 @@ // // Note that ScriptContexts bound to worker threads will not have the full // functionality as those bound to the main RenderThread. -class ScriptContext : public RequestSender::Source { +class ScriptContext { public: using RunScriptExceptionHandler = base::Callback<void(const v8::TryCatch&)>; @@ -53,7 +52,7 @@ Feature::Context context_type, const Extension* effective_extension, Feature::Context effective_context_type); - ~ScriptContext() override; + ~ScriptContext(); // Returns whether |url| from any Extension in |extension_set| is sandboxed, // as declared in each Extension's manifest. @@ -194,14 +193,6 @@ const GURL& document_url, bool match_about_blank); - // RequestSender::Source implementation. - ScriptContext* GetContext() override; - void OnResponseReceived(const std::string& name, - int request_id, - bool success, - const base::ListValue& response, - const std::string& error) override; - // Grants a set of content capabilities to this context. void set_content_capabilities(APIPermissionSet capabilities) { content_capabilities_ = std::move(capabilities);
diff --git a/extensions/renderer/set_icon_natives.cc b/extensions/renderer/set_icon_natives.cc index 4dba7aa..6b2486b 100644 --- a/extensions/renderer/set_icon_natives.cc +++ b/extensions/renderer/set_icon_natives.cc
@@ -14,7 +14,6 @@ #include "base/macros.h" #include "base/strings/string_number_conversions.h" #include "content/public/common/common_param_traits.h" -#include "extensions/renderer/request_sender.h" #include "extensions/renderer/script_context.h" #include "ipc/ipc_message_utils.h" #include "third_party/blink/public/web/web_array_buffer_converter.h"
diff --git a/extensions/shell/browser/shell_browser_main_parts.cc b/extensions/shell/browser/shell_browser_main_parts.cc index a6ec8749..ef09855 100644 --- a/extensions/shell/browser/shell_browser_main_parts.cc +++ b/extensions/shell/browser/shell_browser_main_parts.cc
@@ -124,8 +124,13 @@ // helper classes so those classes' tests can initialize stub versions of the // D-Bus objects. chromeos::DBusThreadManager::Initialize(); - chromeos::PowerManagerClient::Initialize( - chromeos::DBusThreadManager::Get()->GetSystemBus()); + dbus::Bus* bus = chromeos::DBusThreadManager::Get()->GetSystemBus(); + if (bus) { + chromeos::PowerManagerClient::Initialize(bus); + } else { + chromeos::PowerManagerClient::InitializeFake(); + } + chromeos::disks::DiskMountManager::Initialize(); bluez::BluezDBusManager::Initialize();
diff --git a/extensions/shell/browser/shell_desktop_controller_aura_unittest.cc b/extensions/shell/browser/shell_desktop_controller_aura_unittest.cc index 6857b8ff..7667aeb 100644 --- a/extensions/shell/browser/shell_desktop_controller_aura_unittest.cc +++ b/extensions/shell/browser/shell_desktop_controller_aura_unittest.cc
@@ -60,7 +60,7 @@ display::DisplayList::Type::NOT_PRIMARY); #if defined(OS_CHROMEOS) - chromeos::PowerManagerClient::Initialize(); + chromeos::PowerManagerClient::InitializeFake(); #endif controller_ =
diff --git a/gpu/command_buffer/common/gpu_memory_buffer_support.cc b/gpu/command_buffer/common/gpu_memory_buffer_support.cc index cb44d0d..545e211 100644 --- a/gpu/command_buffer/common/gpu_memory_buffer_support.cc +++ b/gpu/command_buffer/common/gpu_memory_buffer_support.cc
@@ -112,7 +112,8 @@ #if defined(USE_OZONE) // Always use GL_TEXTURE_2D as the target for RGB textures. // https://crbug.com/916728 - if (format == gfx::BufferFormat::RGBA_8888 || + if (format == gfx::BufferFormat::R_8 || format == gfx::BufferFormat::RG_88 || + format == gfx::BufferFormat::RGBA_8888 || format == gfx::BufferFormat::BGRA_8888 || format == gfx::BufferFormat::RGBX_8888 || format == gfx::BufferFormat::BGRX_8888) {
diff --git a/gpu/command_buffer/service/gles2_cmd_decoder_passthrough.cc b/gpu/command_buffer/service/gles2_cmd_decoder_passthrough.cc index 2165fb9..2766bcb 100644 --- a/gpu/command_buffer/service/gles2_cmd_decoder_passthrough.cc +++ b/gpu/command_buffer/service/gles2_cmd_decoder_passthrough.cc
@@ -2177,10 +2177,22 @@ void GLES2DecoderPassthroughImpl::ReadBackBuffersIntoShadowCopies( const BufferShadowUpdateMap& updates) { + if (updates.empty()) { + return; + } + GLint old_binding = 0; api()->glGetIntegervFn(GL_ARRAY_BUFFER_BINDING, &old_binding); for (const auto& u : updates) { - GLuint service_id = u.first; + GLuint client_id = u.first; + GLuint service_id = 0; + if (!resources_->buffer_id_map.GetServiceID(client_id, &service_id)) { + // Buffer no longer exists, this shadow update should have been removed by + // DoDeleteBuffers + DCHECK(false); + continue; + } + const auto& update = u.second; void* shadow = update.shm->GetDataAddress(update.shm_offset, update.size);
diff --git a/gpu/command_buffer/service/gles2_cmd_decoder_passthrough_doers.cc b/gpu/command_buffer/service/gles2_cmd_decoder_passthrough_doers.cc index 3ab22de2..8ffc07d 100644 --- a/gpu/command_buffer/service/gles2_cmd_decoder_passthrough_doers.cc +++ b/gpu/command_buffer/service/gles2_cmd_decoder_passthrough_doers.cc
@@ -927,6 +927,9 @@ return update.first == client_id; }; base::EraseIf(buffer_shadow_updates_, is_the_deleted_buffer); + for (PendingQuery& pending_query : pending_queries_) { + base::EraseIf(pending_query.buffer_shadow_updates, is_the_deleted_buffer); + } } api()->glDeleteBuffersARBFn(n, service_ids.data()); @@ -5077,6 +5080,12 @@ update.shm_offset = shm_offset; update.size = size; + GLuint buffer_service_id = 0; + if (!resources_->buffer_id_map.GetServiceID(buffer_id, &buffer_service_id)) { + InsertError(GL_INVALID_OPERATION, "Invalid buffer ID"); + return error::kNoError; + } + if (!update.shm) { return error::kInvalidArguments; }
diff --git a/ios/chrome/browser/about_flags.mm b/ios/chrome/browser/about_flags.mm index 380c459..c952010 100644 --- a/ios/chrome/browser/about_flags.mm +++ b/ios/chrome/browser/about_flags.mm
@@ -21,6 +21,7 @@ #include "base/strings/sys_string_conversions.h" #include "base/system/sys_info.h" #include "components/autofill/core/common/autofill_features.h" +#include "components/autofill/core/common/autofill_payments_features.h" #include "components/autofill/core/common/autofill_switches.h" #include "components/autofill/ios/browser/autofill_switches.h" #include "components/dom_distiller/core/dom_distiller_switches.h"
diff --git a/ios/chrome/browser/browsing_data/browsing_data_remover_impl.mm b/ios/chrome/browser/browsing_data/browsing_data_remover_impl.mm index e8299e6..a4e98852 100644 --- a/ios/chrome/browser/browsing_data/browsing_data_remover_impl.mm +++ b/ios/chrome/browser/browsing_data/browsing_data_remover_impl.mm
@@ -26,7 +26,7 @@ #include "components/autofill/core/browser/payments/strike_database.h" #include "components/autofill/core/browser/personal_data_manager.h" #include "components/autofill/core/browser/webdata/autofill_webdata_service.h" -#include "components/autofill/core/common/autofill_features.h" +#include "components/autofill/core/common/autofill_payments_features.h" #include "components/history/core/browser/history_service.h" #include "components/keyed_service/core/service_access_type.h" #include "components/language/core/browser/url_language_histogram.h"
diff --git a/ios/chrome/browser/prefs/browser_prefs.mm b/ios/chrome/browser/prefs/browser_prefs.mm index fe7b911..73a63204 100644 --- a/ios/chrome/browser/prefs/browser_prefs.mm +++ b/ios/chrome/browser/prefs/browser_prefs.mm
@@ -110,7 +110,7 @@ FirstRun::RegisterProfilePrefs(registry); gcm::GCMChannelStatusSyncer::RegisterProfilePrefs(registry); HostContentSettingsMap::RegisterProfilePrefs(registry); - language::RegisterProfilePrefs(registry); + language::LanguagePrefs::RegisterProfilePrefs(registry); ntp_snippets::ClickBasedCategoryRanker::RegisterProfilePrefs(registry); ntp_snippets::ContentSuggestionsService::RegisterProfilePrefs(registry); ntp_snippets::RemoteSuggestionsProviderImpl::RegisterProfilePrefs(registry);
diff --git a/ios/chrome/browser/reading_list/offline_page_tab_helper.mm b/ios/chrome/browser/reading_list/offline_page_tab_helper.mm index 94ec161a..6bec2f8 100644 --- a/ios/chrome/browser/reading_list/offline_page_tab_helper.mm +++ b/ios/chrome/browser/reading_list/offline_page_tab_helper.mm
@@ -59,16 +59,19 @@ // Skip the root file. continue; } + std::string file_name = image_path.BaseName().value(); + if (file_name.size() != 32) { + // Resource file names are hashes with 32 hexadecimal characters. + continue; + } std::string image; if (!base::ReadFileToString(image_path, &image)) { continue; } base::Base64Encode(image, &image); - std::string src_with_file = base::StringPrintf( - "src=\\\"%s\\\"", image_path.BaseName().value().c_str()); - std::string src_with_data = base::StringPrintf( - "src=\\\"data:image/png;base64,%s\\\"", image.c_str()); - + std::string src_with_file = base::StringPrintf("%s", file_name.c_str()); + std::string src_with_data = + base::StringPrintf("data:image/png;base64,%s", image.c_str()); base::ReplaceSubstringsAfterOffset(&content, 0, src_with_file, src_with_data); }
diff --git a/ios/chrome/browser/signin/BUILD.gn b/ios/chrome/browser/signin/BUILD.gn index 6c9a54c..e4e0eea9 100644 --- a/ios/chrome/browser/signin/BUILD.gn +++ b/ios/chrome/browser/signin/BUILD.gn
@@ -55,8 +55,6 @@ "signin_client_factory.h", "signin_error_controller_factory.cc", "signin_error_controller_factory.h", - "signin_manager_factory.cc", - "signin_manager_factory.h", "signin_util.h", "signin_util.mm", ]
diff --git a/ios/chrome/browser/signin/feature_flags.mm b/ios/chrome/browser/signin/feature_flags.mm index 1ad4199..6374db8 100644 --- a/ios/chrome/browser/signin/feature_flags.mm +++ b/ios/chrome/browser/signin/feature_flags.mm
@@ -8,5 +8,8 @@ #error "This file requires ARC support." #endif +// This flag should be turned off by default until gmail.com can detect the +// user has been signed out. +// See: http://crbug.com/939508. const base::Feature kUseNSURLSessionForGaiaSigninRequests{ - "UseNSURLSessionForGaiaSigninRequests", base::FEATURE_ENABLED_BY_DEFAULT}; + "UseNSURLSessionForGaiaSigninRequests", base::FEATURE_DISABLED_BY_DEFAULT};
diff --git a/ios/chrome/browser/signin/identity_manager_factory.cc b/ios/chrome/browser/signin/identity_manager_factory.cc index 222b60b..b1e1258 100644 --- a/ios/chrome/browser/signin/identity_manager_factory.cc +++ b/ios/chrome/browser/signin/identity_manager_factory.cc
@@ -5,23 +5,44 @@ #include "ios/chrome/browser/signin/identity_manager_factory.h" #include <memory> +#include <utility> #include "components/keyed_service/core/keyed_service.h" #include "components/keyed_service/ios/browser_state_dependency_manager.h" +#include "components/pref_registry/pref_registry_syncable.h" +#include "components/signin/core/browser/account_consistency_method.h" #include "components/signin/core/browser/signin_manager.h" +#include "ios/chrome/browser/application_context.h" #include "ios/chrome/browser/browser_state/chrome_browser_state.h" #include "ios/chrome/browser/signin/account_fetcher_service_factory.h" #include "ios/chrome/browser/signin/account_tracker_service_factory.h" #include "ios/chrome/browser/signin/gaia_cookie_manager_service_factory.h" #include "ios/chrome/browser/signin/identity_manager_factory_observer.h" #include "ios/chrome/browser/signin/profile_oauth2_token_service_factory.h" -#include "ios/chrome/browser/signin/signin_manager_factory.h" +#include "ios/chrome/browser/signin/signin_client_factory.h" #include "services/identity/public/cpp/accounts_cookie_mutator_impl.h" #include "services/identity/public/cpp/accounts_mutator.h" #include "services/identity/public/cpp/diagnostics_provider_impl.h" #include "services/identity/public/cpp/identity_manager.h" #include "services/identity/public/cpp/primary_account_mutator_impl.h" +namespace { +std::unique_ptr<SigninManager> BuildSigninManager( + ios::ChromeBrowserState* chrome_browser_state) { + std::unique_ptr<SigninManager> service = std::make_unique<SigninManager>( + SigninClientFactory::GetForBrowserState(chrome_browser_state), + ProfileOAuth2TokenServiceFactory::GetForBrowserState( + chrome_browser_state), + ios::AccountTrackerServiceFactory::GetForBrowserState( + chrome_browser_state), + ios::GaiaCookieManagerServiceFactory::GetForBrowserState( + chrome_browser_state), + signin::AccountConsistencyMethod::kMirror); + service->Initialize(GetApplicationContext()->GetLocalState()); + return service; +} +} // namespace + // Subclass that wraps IdentityManager in a KeyedService (as IdentityManager is // a client-side library intended for use by any process, it would be a layering // violation for IdentityManager itself to have direct knowledge of @@ -32,9 +53,12 @@ class IdentityManagerWrapper : public KeyedService, public identity::IdentityManager { public: - explicit IdentityManagerWrapper(ios::ChromeBrowserState* browser_state) + IdentityManagerWrapper( + std::unique_ptr<SigninManagerBase> signin_manager, + std::unique_ptr<identity::PrimaryAccountMutator> primary_account_mutator, + ios::ChromeBrowserState* browser_state) : identity::IdentityManager( - ios::SigninManagerFactory::GetForBrowserState(browser_state), + std::move(signin_manager), ProfileOAuth2TokenServiceFactory::GetForBrowserState(browser_state), ios::AccountFetcherServiceFactory::GetForBrowserState( browser_state), @@ -42,11 +66,8 @@ browser_state), ios::GaiaCookieManagerServiceFactory::GetForBrowserState( browser_state), - std::make_unique<identity::PrimaryAccountMutatorImpl>( - ios::AccountTrackerServiceFactory::GetForBrowserState( - browser_state), - ios::SigninManagerFactory::GetForBrowserState(browser_state)), - nullptr, + std::move(primary_account_mutator), + /*accounts_mutator=*/nullptr, std::make_unique<identity::AccountsCookieMutatorImpl>( ios::GaiaCookieManagerServiceFactory::GetForBrowserState( browser_state)), @@ -57,6 +78,11 @@ browser_state))) {} }; +void IdentityManagerFactory::RegisterBrowserStatePrefs( + user_prefs::PrefRegistrySyncable* registry) { + SigninManagerBase::RegisterProfilePrefs(registry); +} + IdentityManagerFactory::IdentityManagerFactory() : BrowserStateKeyedServiceFactory( "IdentityManager", @@ -65,7 +91,7 @@ DependsOn(ios::AccountTrackerServiceFactory::GetInstance()); DependsOn(ios::GaiaCookieManagerServiceFactory::GetInstance()); DependsOn(ProfileOAuth2TokenServiceFactory::GetInstance()); - DependsOn(ios::SigninManagerFactory::GetInstance()); + DependsOn(SigninClientFactory::GetInstance()); } IdentityManagerFactory::~IdentityManagerFactory() {} @@ -96,7 +122,7 @@ ios::AccountTrackerServiceFactory::GetInstance(); ios::GaiaCookieManagerServiceFactory::GetInstance(); ProfileOAuth2TokenServiceFactory::GetInstance(); - ios::SigninManagerFactory::GetInstance(); + SigninClientFactory::GetInstance(); } void IdentityManagerFactory::AddObserver( @@ -111,8 +137,20 @@ std::unique_ptr<KeyedService> IdentityManagerFactory::BuildServiceInstanceFor( web::BrowserState* browser_state) const { + ios::ChromeBrowserState* chrome_browser_state = + ios::ChromeBrowserState::FromBrowserState(browser_state); + + // Construct the dependencies that IdentityManager will own. + std::unique_ptr<SigninManager> signin_manager = + BuildSigninManager(chrome_browser_state); + auto primary_account_mutator = + std::make_unique<identity::PrimaryAccountMutatorImpl>( + ios::AccountTrackerServiceFactory::GetForBrowserState( + chrome_browser_state), + signin_manager.get()); auto identity_manager = std::make_unique<IdentityManagerWrapper>( - ios::ChromeBrowserState::FromBrowserState(browser_state)); + std::move(signin_manager), std::move(primary_account_mutator), + chrome_browser_state); for (auto& observer : observer_list_) observer.IdentityManagerCreated(identity_manager.get());
diff --git a/ios/chrome/browser/signin/identity_manager_factory.h b/ios/chrome/browser/signin/identity_manager_factory.h index 1ee9767..db948865 100644 --- a/ios/chrome/browser/signin/identity_manager_factory.h +++ b/ios/chrome/browser/signin/identity_manager_factory.h
@@ -57,6 +57,8 @@ std::unique_ptr<KeyedService> BuildServiceInstanceFor( web::BrowserState* browser_state) const override; void BrowserStateShutdown(web::BrowserState* context) override; + void RegisterBrowserStatePrefs( + user_prefs::PrefRegistrySyncable* registry) override; DISALLOW_COPY_AND_ASSIGN(IdentityManagerFactory); };
diff --git a/ios/chrome/browser/signin/identity_test_environment_chrome_browser_state_adaptor.cc b/ios/chrome/browser/signin/identity_test_environment_chrome_browser_state_adaptor.cc index 4c8cc81..49edd8e 100644 --- a/ios/chrome/browser/signin/identity_test_environment_chrome_browser_state_adaptor.cc +++ b/ios/chrome/browser/signin/identity_test_environment_chrome_browser_state_adaptor.cc
@@ -18,7 +18,6 @@ #include "ios/chrome/browser/signin/profile_oauth2_token_service_factory.h" #include "ios/chrome/browser/signin/profile_oauth2_token_service_ios_provider_impl.h" #include "ios/chrome/browser/signin/signin_client_factory.h" -#include "ios/chrome/browser/signin/signin_manager_factory.h" namespace { @@ -128,7 +127,6 @@ static_cast<FakeProfileOAuth2TokenService*>( ProfileOAuth2TokenServiceFactory::GetForBrowserState( browser_state)), - ios::SigninManagerFactory::GetForBrowserState(browser_state), ios::GaiaCookieManagerServiceFactory::GetForBrowserState( browser_state), IdentityManagerFactory::GetForBrowserState(browser_state)) {}
diff --git a/ios/chrome/browser/signin/signin_manager_factory.cc b/ios/chrome/browser/signin/signin_manager_factory.cc deleted file mode 100644 index da6c822..0000000 --- a/ios/chrome/browser/signin/signin_manager_factory.cc +++ /dev/null
@@ -1,79 +0,0 @@ -// Copyright 2015 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ios/chrome/browser/signin/signin_manager_factory.h" - -#include <utility> - -#include "base/no_destructor.h" -#include "base/time/time.h" -#include "components/keyed_service/ios/browser_state_dependency_manager.h" -#include "components/pref_registry/pref_registry_syncable.h" -#include "components/signin/core/browser/account_consistency_method.h" -#include "components/signin/core/browser/signin_manager.h" -#include "components/signin/core/browser/signin_pref_names.h" -#include "ios/chrome/browser/application_context.h" -#include "ios/chrome/browser/browser_state/chrome_browser_state.h" -#include "ios/chrome/browser/signin/account_tracker_service_factory.h" -#include "ios/chrome/browser/signin/gaia_cookie_manager_service_factory.h" -#include "ios/chrome/browser/signin/profile_oauth2_token_service_factory.h" -#include "ios/chrome/browser/signin/signin_client_factory.h" - -namespace ios { - -SigninManagerFactory::SigninManagerFactory() - : BrowserStateKeyedServiceFactory( - "SigninManager", - BrowserStateDependencyManager::GetInstance()) { - DependsOn(SigninClientFactory::GetInstance()); - DependsOn(ios::GaiaCookieManagerServiceFactory::GetInstance()); - DependsOn(ProfileOAuth2TokenServiceFactory::GetInstance()); - DependsOn(ios::AccountTrackerServiceFactory::GetInstance()); -} - -SigninManagerFactory::~SigninManagerFactory() {} - -// static -SigninManager* SigninManagerFactory::GetForBrowserState( - ios::ChromeBrowserState* browser_state) { - return static_cast<SigninManager*>( - GetInstance()->GetServiceForBrowserState(browser_state, true)); -} - -// static -SigninManager* SigninManagerFactory::GetForBrowserStateIfExists( - ios::ChromeBrowserState* browser_state) { - return static_cast<SigninManager*>( - GetInstance()->GetServiceForBrowserState(browser_state, false)); -} - -// static -SigninManagerFactory* SigninManagerFactory::GetInstance() { - static base::NoDestructor<SigninManagerFactory> instance; - return instance.get(); -} - -void SigninManagerFactory::RegisterBrowserStatePrefs( - user_prefs::PrefRegistrySyncable* registry) { - SigninManagerBase::RegisterProfilePrefs(registry); -} - -std::unique_ptr<KeyedService> SigninManagerFactory::BuildServiceInstanceFor( - web::BrowserState* context) const { - ios::ChromeBrowserState* chrome_browser_state = - ios::ChromeBrowserState::FromBrowserState(context); - std::unique_ptr<SigninManager> service(new SigninManager( - SigninClientFactory::GetForBrowserState(chrome_browser_state), - ProfileOAuth2TokenServiceFactory::GetForBrowserState( - chrome_browser_state), - ios::AccountTrackerServiceFactory::GetForBrowserState( - chrome_browser_state), - ios::GaiaCookieManagerServiceFactory::GetForBrowserState( - chrome_browser_state), - signin::AccountConsistencyMethod::kMirror)); - service->Initialize(GetApplicationContext()->GetLocalState()); - return service; -} - -} // namespace ios
diff --git a/ios/chrome/browser/signin/signin_manager_factory.h b/ios/chrome/browser/signin/signin_manager_factory.h deleted file mode 100644 index eec5367..0000000 --- a/ios/chrome/browser/signin/signin_manager_factory.h +++ /dev/null
@@ -1,49 +0,0 @@ -// Copyright 2015 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef IOS_CHROME_BROWSER_SIGNIN_SIGNIN_MANAGER_FACTORY_H_ -#define IOS_CHROME_BROWSER_SIGNIN_SIGNIN_MANAGER_FACTORY_H_ - -#include <memory> - -#include "base/macros.h" -#include "base/no_destructor.h" -#include "components/keyed_service/ios/browser_state_keyed_service_factory.h" - -class SigninManager; - -namespace ios { - -class ChromeBrowserState; - -// Singleton that owns all SigninManagers and associates them with browser -// states. -class SigninManagerFactory : public BrowserStateKeyedServiceFactory { - public: - static SigninManager* GetForBrowserState( - ios::ChromeBrowserState* browser_state); - static SigninManager* GetForBrowserStateIfExists( - ios::ChromeBrowserState* browser_state); - - // Returns an instance of the SigninManagerFactory singleton. - static SigninManagerFactory* GetInstance(); - - // Implementation of BrowserStateKeyedServiceFactory (public so tests - // can call it). - void RegisterBrowserStatePrefs( - user_prefs::PrefRegistrySyncable* registry) override; - - private: - friend class base::NoDestructor<SigninManagerFactory>; - - SigninManagerFactory(); - ~SigninManagerFactory() override; - - // BrowserStateKeyedServiceFactory: - std::unique_ptr<KeyedService> BuildServiceInstanceFor( - web::BrowserState* context) const override; -}; -} - -#endif // IOS_CHROME_BROWSER_SIGNIN_SIGNIN_MANAGER_FACTORY_H_
diff --git a/ios/chrome/browser/sync/BUILD.gn b/ios/chrome/browser/sync/BUILD.gn index 7d58c83..a37bd58d 100644 --- a/ios/chrome/browser/sync/BUILD.gn +++ b/ios/chrome/browser/sync/BUILD.gn
@@ -92,20 +92,15 @@ source_set("test_support") { testonly = true sources = [ - "ios_chrome_profile_sync_test_util.cc", - "ios_chrome_profile_sync_test_util.h", "sync_setup_service_mock.cc", "sync_setup_service_mock.h", ] deps = [ ":sync", "//base", - "//components/browser_sync", - "//components/browser_sync:test_support", "//components/keyed_service/core", "//components/keyed_service/ios", "//components/sync", - "//components/sync:test_support_driver", "//ios/chrome/browser/browser_state", "//ios/chrome/browser/signin", "//ios/chrome/common",
diff --git a/ios/chrome/browser/sync/ios_chrome_profile_sync_test_util.cc b/ios/chrome/browser/sync/ios_chrome_profile_sync_test_util.cc deleted file mode 100644 index 2421b22..0000000 --- a/ios/chrome/browser/sync/ios_chrome_profile_sync_test_util.cc +++ /dev/null
@@ -1,41 +0,0 @@ -// Copyright 2015 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ios/chrome/browser/sync/ios_chrome_profile_sync_test_util.h" - -#include <string> -#include <utility> - -#include "base/bind_helpers.h" -#include "components/browser_sync/profile_sync_service_mock.h" -#include "components/browser_sync/profile_sync_test_util.h" -#include "ios/chrome/browser/browser_state/chrome_browser_state.h" -#include "ios/chrome/browser/signin/identity_manager_factory.h" -#include "ios/chrome/browser/sync/ios_chrome_sync_client.h" -#include "net/url_request/url_request_context_getter.h" -#include "services/network/public/cpp/shared_url_loader_factory.h" - -browser_sync::ProfileSyncService::InitParams -CreateProfileSyncServiceParamsForTest( - ios::ChromeBrowserState* browser_state) { - browser_sync::ProfileSyncService::InitParams init_params; - - init_params.identity_manager = - IdentityManagerFactory::GetForBrowserState(browser_state); - init_params.start_behavior = browser_sync::ProfileSyncService::MANUAL_START; - init_params.sync_client = - std::make_unique<IOSChromeSyncClient>(browser_state); - init_params.network_time_update_callback = base::DoNothing(); - init_params.url_loader_factory = browser_state->GetSharedURLLoaderFactory(); - init_params.debug_identifier = browser_state->GetDebugName(); - - return init_params; -} - -std::unique_ptr<KeyedService> BuildMockProfileSyncService( - web::BrowserState* context) { - return std::make_unique<browser_sync::ProfileSyncServiceMock>( - CreateProfileSyncServiceParamsForTest( - ios::ChromeBrowserState::FromBrowserState(context))); -}
diff --git a/ios/chrome/browser/sync/ios_chrome_profile_sync_test_util.h b/ios/chrome/browser/sync/ios_chrome_profile_sync_test_util.h deleted file mode 100644 index c41e03a..0000000 --- a/ios/chrome/browser/sync/ios_chrome_profile_sync_test_util.h +++ /dev/null
@@ -1,30 +0,0 @@ -// Copyright 2015 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef IOS_CHROME_BROWSER_SYNC_IOS_CHROME_PROFILE_SYNC_TEST_UTIL_H_ -#define IOS_CHROME_BROWSER_SYNC_IOS_CHROME_PROFILE_SYNC_TEST_UTIL_H_ - -#include <memory> - -#include "components/browser_sync/profile_sync_service.h" - -namespace ios { -class ChromeBrowserState; -} - -namespace web { -class BrowserState; -} - -// Helper method for constructing ProfileSyncService mocks. -browser_sync::ProfileSyncService::InitParams -CreateProfileSyncServiceParamsForTest( - ios::ChromeBrowserState* browser_state); - -// Helper routine to be used in conjunction with -// BrowserStateKeyedServiceFactory::SetTestingFactory(). -std::unique_ptr<KeyedService> BuildMockProfileSyncService( - web::BrowserState* context); - -#endif // IOS_CHROME_BROWSER_SYNC_IOS_CHROME_PROFILE_SYNC_TEST_UTIL_H_
diff --git a/ios/chrome/browser/translate/BUILD.gn b/ios/chrome/browser/translate/BUILD.gn index 112d99e..82b4c7bf8 100644 --- a/ios/chrome/browser/translate/BUILD.gn +++ b/ios/chrome/browser/translate/BUILD.gn
@@ -80,6 +80,7 @@ ":translate", "//base", "//base/test:test_support", + "//components/language/core/browser", "//components/translate/core/browser:test_support", "//components/translate/ios/browser", "//ios/chrome/browser",
diff --git a/ios/chrome/browser/translate/translate_infobar_controller.mm b/ios/chrome/browser/translate/translate_infobar_controller.mm index 93e4ec3..a39ce6b 100644 --- a/ios/chrome/browser/translate/translate_infobar_controller.mm +++ b/ios/chrome/browser/translate/translate_infobar_controller.mm
@@ -252,8 +252,6 @@ if ([self shouldIgnoreUserInteraction]) return; - self.infoBarDelegate->InfoBarDismissed(); - if (self.userAction == UserActionNone) { [self recordInfobarEvent:InfobarEvent::INFOBAR_DECLINE]; } @@ -268,6 +266,7 @@ notificationType: TranslateNotificationTypeAutoNeverTranslate]; } else { + self.infoBarDelegate->InfoBarDismissed(); self.delegate->RemoveInfoBar(); } } @@ -425,8 +424,10 @@ self.infoBarDelegate->ToggleAlwaysTranslate(); self.infoBarDelegate->Translate(); break; - case TranslateNotificationTypeNeverTranslate: case TranslateNotificationTypeAutoNeverTranslate: + self.infoBarDelegate->InfoBarDismissed(); + FALLTHROUGH; + case TranslateNotificationTypeNeverTranslate: self.infoBarDelegate->ToggleTranslatableLanguageByPrefs(); self.delegate->RemoveInfoBar(); break; @@ -457,6 +458,10 @@ case TranslateNotificationTypeAutoNeverTranslate: [self recordInfobarEvent:InfobarEvent::INFOBAR_SNACKBAR_CANCEL_AUTO_NEVER]; + // Remove the infobar even if the user tapped "Undo" since user explicitly + // dismissed the infobar. + self.infoBarDelegate->InfoBarDismissed(); + self.delegate->RemoveInfoBar(); break; case TranslateNotificationTypeNeverTranslateSite: [self
diff --git a/ios/chrome/browser/ui/autofill/manual_fill/manual_fill_card_cell.mm b/ios/chrome/browser/ui/autofill/manual_fill/manual_fill_card_cell.mm index 7726b45e..9abf38d 100644 --- a/ios/chrome/browser/ui/autofill/manual_fill/manual_fill_card_cell.mm +++ b/ios/chrome/browser/ui/autofill/manual_fill/manual_fill_card_cell.mm
@@ -67,6 +67,10 @@ @interface ManualFillCardCell () +// The dynamic constraints for all the lines (i.e. not set in createView). +@property(nonatomic, strong) + NSMutableArray<NSLayoutConstraint*>* dynamicConstraints; + // The label with bank name and network. @property(nonatomic, strong) UILabel* cardLabel; @@ -102,11 +106,19 @@ - (void)prepareForReuse { [super prepareForReuse]; + + [NSLayoutConstraint deactivateConstraints:self.dynamicConstraints]; + [self.dynamicConstraints removeAllObjects]; + self.cardLabel.text = @""; [self.cardNumberButton setTitle:@"" forState:UIControlStateNormal]; [self.cardholderButton setTitle:@"" forState:UIControlStateNormal]; [self.expirationMonthButton setTitle:@"" forState:UIControlStateNormal]; [self.expirationYearButton setTitle:@"" forState:UIControlStateNormal]; + + self.cardNumberButton.hidden = NO; + self.cardholderButton.hidden = NO; + self.contentDelegate = nil; self.navigationDelegate = nil; self.cardIcon.image = nil; @@ -116,6 +128,10 @@ - (void)setUpWithCreditCard:(ManualFillCreditCard*)card contentDelegate:(id<ManualFillContentDelegate>)contentDelegate navigationDelegate:(id<CardListDelegate>)navigationDelegate { + if (!self.dynamicConstraints) { + self.dynamicConstraints = [[NSMutableArray alloc] init]; + } + if (self.contentView.subviews.count == 0) { [self createViewHierarchy]; } @@ -152,6 +168,27 @@ forState:UIControlStateNormal]; [self.expirationYearButton setTitle:card.expirationYear forState:UIControlStateNormal]; + + NSMutableArray<UIView*>* verticalViews = + [[NSMutableArray alloc] initWithObjects:self.cardLabel, nil]; + + if (card.obfuscatedNumber.length) { + [verticalViews addObject:self.cardNumberButton]; + } else { + self.cardNumberButton.hidden = YES; + } + + [verticalViews addObject:self.expirationMonthButton]; + + if (card.cardHolder.length) { + [verticalViews addObject:self.cardholderButton]; + } else { + self.cardholderButton.hidden = YES; + } + + AppendVerticalConstraintsSpacingForViews(self.dynamicConstraints, + verticalViews, self.contentView); + [NSLayoutConstraint activateConstraints:self.dynamicConstraints]; } #pragma mark - Private @@ -200,6 +237,8 @@ CreateButtonWithSelectorAndTarget(@selector(userDidTapCardInfo:), self); [self.contentView addSubview:self.expirationYearButton]; UILabel* expirationSeparatorLabel = CreateLabel(); + expirationSeparatorLabel.font = + [UIFont preferredFontForTextStyle:UIFontTextStyleHeadline]; expirationSeparatorLabel.text = @"/"; [self.contentView addSubview:expirationSeparatorLabel]; AppendHorizontalConstraintsForViews( @@ -210,13 +249,6 @@ ], guide, 0, AppendConstraintsHorizontalSyncBaselines); - AppendVerticalConstraintsSpacingForViews( - staticConstraints, - @[ - self.cardLabel, self.cardNumberButton, self.expirationMonthButton, - self.cardholderButton - ], - self.contentView); // Without this set, Voice Over will read the content vertically instead of // horizontally.
diff --git a/ios/chrome/browser/ui/autofill/save_card_infobar_egtest.mm b/ios/chrome/browser/ui/autofill/save_card_infobar_egtest.mm index 3626889..e8700bb6 100644 --- a/ios/chrome/browser/ui/autofill/save_card_infobar_egtest.mm +++ b/ios/chrome/browser/ui/autofill/save_card_infobar_egtest.mm
@@ -12,7 +12,7 @@ #include "components/autofill/core/browser/autofill_metrics.h" #include "components/autofill/core/browser/form_data_importer.h" #include "components/autofill/core/browser/personal_data_manager.h" -#include "components/autofill/core/common/autofill_features.h" +#include "components/autofill/core/common/autofill_payments_features.h" #include "components/autofill/ios/browser/autofill_driver_ios.h" #import "components/autofill/ios/browser/credit_card_save_manager_test_observer_bridge.h" #include "components/autofill/ios/browser/ios_test_event_waiter.h"
diff --git a/ios/chrome/browser/ui/browser_view_controller.mm b/ios/chrome/browser/ui/browser_view_controller.mm index 280fae1..6c16efd 100644 --- a/ios/chrome/browser/ui/browser_view_controller.mm +++ b/ios/chrome/browser/ui/browser_view_controller.mm
@@ -3367,6 +3367,13 @@ NSData* imageData = data; UIImage* image = [UIImage imageWithData:data]; gfx::Image gfxImage(image); + // Converting to gfx::Image creates an empty image if UIImage is nil. However, + // we still want to do the image search with nil data because that gives + // the user the best error experience. + if (gfxImage.IsEmpty()) { + [self searchByResizedImageData:imageData atURL:&imageURL inNewTab:YES]; + return; + } UIImage* resizedImage = gfx::ResizedImageForSearchByImage(gfxImage).ToUIImage(); if (![image isEqual:resizedImage]) { @@ -4179,7 +4186,7 @@ NSString* script = @"document.documentElement.outerHTML;"; __weak Tab* weakTab = tab; __weak BrowserViewController* weakSelf = self; - web::JavaScriptResultBlock completionHandlerBlock = ^(id result, NSError*) { + auto completionHandlerBlock = ^(id result, NSError*) { Tab* strongTab = weakTab; if (!strongTab) return;
diff --git a/ios/chrome/browser/ui/location_bar/location_bar_generic_coordinator.h b/ios/chrome/browser/ui/location_bar/location_bar_generic_coordinator.h index 5fe2869..fde69bf 100644 --- a/ios/chrome/browser/ui/location_bar/location_bar_generic_coordinator.h +++ b/ios/chrome/browser/ui/location_bar/location_bar_generic_coordinator.h
@@ -58,10 +58,6 @@ // Indicates when the omnibox is the first responder. - (BOOL)isOmniboxFirstResponder; -// TODO(crbug.com/831506): Once legacy location bar is deleted, remove the -// @optional label and matching respondsToSelector: calls. -@optional - // Returns the location bar animatee. - (id<LocationBarAnimatee>)locationBarAnimatee;
diff --git a/ios/chrome/browser/ui/location_bar/location_bar_view_controller.mm b/ios/chrome/browser/ui/location_bar/location_bar_view_controller.mm index d9dba5d..0dc423df 100644 --- a/ios/chrome/browser/ui/location_bar/location_bar_view_controller.mm +++ b/ios/chrome/browser/ui/location_bar/location_bar_view_controller.mm
@@ -192,6 +192,9 @@ CGFloat alphaValue = fmax((progress - 0.85) / 0.15, 0); CGFloat scaleValue = 0.79 + 0.21 * progress; self.locationBarSteadyView.trailingButton.alpha = alphaValue; + if (IsInfobarUIRebootEnabled()) { + self.locationBarSteadyView.leadingButton.alpha = alphaValue; + } self.locationBarSteadyView.transform = CGAffineTransformMakeScale(scaleValue, scaleValue); }
diff --git a/ios/chrome/browser/ui/settings/google_services/google_services_settings_mediator.mm b/ios/chrome/browser/ui/settings/google_services/google_services_settings_mediator.mm index 7051d0f5..83fe7d2 100644 --- a/ios/chrome/browser/ui/settings/google_services/google_services_settings_mediator.mm +++ b/ios/chrome/browser/ui/settings/google_services/google_services_settings_mediator.mm
@@ -115,6 +115,8 @@ @property(nonatomic, strong) TableViewItem* syncErrorItem; // Sync your Chrome data switch item. @property(nonatomic, strong) SyncSwitchItem* syncChromeDataSwitchItem; +// Items to open "Manage sync" settings. +@property(nonatomic, strong) TableViewImageItem* manageSyncItem; // ** Non personalized section. // Preference value for the "Autocomplete searches and URLs" feature. @property(nonatomic, strong, readonly) @@ -243,6 +245,7 @@ - (void)loadSyncSection { self.syncErrorItem = nil; self.syncChromeDataSwitchItem = nil; + self.manageSyncItem = nil; TableViewModel* model = self.consumer.tableViewModel; [model addSectionWithIdentifier:SyncSectionIdentifier]; [self updateSyncSection:NO]; @@ -363,22 +366,33 @@ // reloaded. - (BOOL)updateManageSyncItem { TableViewModel* model = self.consumer.tableViewModel; - BOOL hasManageSyncItem = [model hasItemForItemType:ManageSyncItemType - sectionIdentifier:SyncSectionIdentifier]; if (self.isSyncCanBeAvailable) { - if (hasManageSyncItem) - return NO; - SettingsMultilineDetailItem* item = - [[SettingsMultilineDetailItem alloc] initWithType:ManageSyncItemType]; - item.accessoryType = UITableViewCellAccessoryDisclosureIndicator; - item.text = GetNSString(IDS_IOS_MANAGE_SYNC_SETTINGS_TITLE); - [model addItem:item toSectionWithIdentifier:SyncSectionIdentifier]; - return YES; + BOOL needsUpdate = NO; + if (!self.manageSyncItem) { + self.manageSyncItem = + [[TableViewImageItem alloc] initWithType:ManageSyncItemType]; + self.manageSyncItem.accessoryType = + UITableViewCellAccessoryDisclosureIndicator; + self.manageSyncItem.title = + GetNSString(IDS_IOS_MANAGE_SYNC_SETTINGS_TITLE); + [model addItem:self.manageSyncItem + toSectionWithIdentifier:SyncSectionIdentifier]; + needsUpdate = YES; + } + needsUpdate = + needsUpdate || self.manageSyncItem.enabled != !self.isSyncDisabled; + self.manageSyncItem.enabled = !self.isSyncDisabled; + self.manageSyncItem.textColor = + self.manageSyncItem.enabled + ? nil + : UIColorFromRGB(kTableViewSecondaryLabelLightGrayTextColor); + return needsUpdate; } - if (!hasManageSyncItem) + if (!self.manageSyncItem) return NO; [model removeItemWithType:ManageSyncItemType fromSectionWithIdentifier:SyncSectionIdentifier]; + self.manageSyncItem = nil; return YES; } @@ -465,6 +479,11 @@ syncer::SyncService::DISABLE_REASON_ENTERPRISE_POLICY) != 0; } +- (BOOL)isSyncDisabled { + return self.syncService->GetDisableReasons() != + syncer::SyncService::DISABLE_REASON_NONE; +} + - (BOOL)isSyncCanBeAvailable { return self.isAuthenticated && !self.isSyncDisabledByAdministrator; }
diff --git a/ios/chrome/browser/ui/settings/password/password_details_table_view_controller+testing.h b/ios/chrome/browser/ui/settings/password/password_details_table_view_controller+testing.h index 7950cb47..c8c1386b 100644 --- a/ios/chrome/browser/ui/settings/password/password_details_table_view_controller+testing.h +++ b/ios/chrome/browser/ui/settings/password/password_details_table_view_controller+testing.h
@@ -7,7 +7,7 @@ #import "ios/chrome/browser/ui/settings/password/password_details_table_view_controller.h" -// TODO(crbug.com/894791): Refactor the PasswordTableViewController and +// TODO(crbug.com/943523): Refactor the PasswordTableViewController and // PasswordsSettingsTestCase to remove this Category file. @interface PasswordDetailsTableViewController (Testing)
diff --git a/ios/chrome/browser/ui/settings/translate_table_view_controller_unittest.mm b/ios/chrome/browser/ui/settings/translate_table_view_controller_unittest.mm index 1dd6faa..de0270b 100644 --- a/ios/chrome/browser/ui/settings/translate_table_view_controller_unittest.mm +++ b/ios/chrome/browser/ui/settings/translate_table_view_controller_unittest.mm
@@ -10,7 +10,7 @@ #include "base/files/file_path.h" #include "base/test/scoped_task_environment.h" #include "base/threading/thread_task_runner_handle.h" -#include "components/language/core/browser/pref_names.h" +#include "components/language/core/browser/language_prefs.h" #include "components/pref_registry/pref_registry_syncable.h" #include "components/prefs/pref_member.h" #include "components/prefs/pref_service.h" @@ -59,10 +59,8 @@ scoped_refptr<PrefRegistrySyncable> registry = new PrefRegistrySyncable(); registry->RegisterBooleanPref(prefs::kOfferTranslateEnabled, false, PrefRegistrySyncable::SYNCABLE_PREF); + language::LanguagePrefs::RegisterProfilePrefs(registry.get()); translate::TranslatePrefs::RegisterProfilePrefs(registry.get()); - registry->RegisterStringPref( - language::prefs::kAcceptLanguages, - l10n_util::GetStringUTF8(IDS_ACCEPT_LANGUAGES)); base::FilePath path("TranslateTableViewControllerTest.pref"); sync_preferences::PrefServiceMockFactory factory; factory.SetUserPrefsFile(path, base::ThreadTaskRunnerHandle::Get().get());
diff --git a/ios/chrome/browser/ui/static_content/static_html_native_content.mm b/ios/chrome/browser/ui/static_content/static_html_native_content.mm index a6a4e01..d0fbe0c 100644 --- a/ios/chrome/browser/ui/static_content/static_html_native_content.mm +++ b/ios/chrome/browser/ui/static_content/static_html_native_content.mm
@@ -127,7 +127,7 @@ } - (void)executeJavaScript:(NSString*)script - completionHandler:(web::JavaScriptResultBlock)handler { + completionHandler:(void (^)(id, NSError*))handler { [_staticHTMLViewController executeJavaScript:script completionHandler:handler]; }
diff --git a/ios/chrome/browser/ui/static_content/static_html_view_controller.h b/ios/chrome/browser/ui/static_content/static_html_view_controller.h index c439f15..7f39326 100644 --- a/ios/chrome/browser/ui/static_content/static_html_view_controller.h +++ b/ios/chrome/browser/ui/static_content/static_html_view_controller.h
@@ -8,7 +8,6 @@ #import <UIKit/UIKit.h> #import <WebKit/WebKit.h> -#import "ios/web/public/block_types.h" #include "url/gurl.h" @protocol CRWNativeContentDelegate; @@ -82,7 +81,7 @@ // moment, |completionHandler| is called with an NSError. The // |completionHandler| can be nil. - (void)executeJavaScript:(NSString*)script - completionHandler:(web::JavaScriptResultBlock)completionHandler; + completionHandler:(void (^)(id, NSError*))completionHandler; // The web page title. Will return nil if not available. - (NSString*)title;
diff --git a/ios/chrome/browser/ui/static_content/static_html_view_controller.mm b/ios/chrome/browser/ui/static_content/static_html_view_controller.mm index be6900f..b1d4381 100644 --- a/ios/chrome/browser/ui/static_content/static_html_view_controller.mm +++ b/ios/chrome/browser/ui/static_content/static_html_view_controller.mm
@@ -135,7 +135,7 @@ } - (void)executeJavaScript:(NSString*)script - completionHandler:(web::JavaScriptResultBlock)handler { + completionHandler:(void (^)(id, NSError*))handler { [webView_ evaluateJavaScript:script completionHandler:handler]; }
diff --git a/ios/chrome/browser/ui/table_view/cells/table_view_text_item.mm b/ios/chrome/browser/ui/table_view/cells/table_view_text_item.mm index 8d3ab38..7b4feb2 100644 --- a/ios/chrome/browser/ui/table_view/cells/table_view_text_item.mm +++ b/ios/chrome/browser/ui/table_view/cells/table_view_text_item.mm
@@ -33,7 +33,6 @@ [super configureCell:tableCell withStyler:styler]; TableViewTextCell* cell = base::mac::ObjCCastStrict<TableViewTextCell>(tableCell); - // TODO(crbug.com/894791): set isAccessibilityElement = YES in TableViewItem. cell.isAccessibilityElement = YES; if (self.masked) {
diff --git a/ios/chrome/browser/ui/table_view/chrome_table_view_controller_test.mm b/ios/chrome/browser/ui/table_view/chrome_table_view_controller_test.mm index 280c225..50069511 100644 --- a/ios/chrome/browser/ui/table_view/chrome_table_view_controller_test.mm +++ b/ios/chrome/browser/ui/table_view/chrome_table_view_controller_test.mm
@@ -115,7 +115,7 @@ CheckSectionFooter(l10n_util::GetNSString(expected_text_id), section); } -// TODO(crbug.com/894791): There are some unittests that are using +// TODO(crbug.com/894800): There are some unittests that are using // CheckTextCellText to check Item with both "text" and "detailText". Change all // of them to CheckTextCellTextAndDetailText when the migration is finished. void ChromeTableViewControllerTest::CheckTextCellText(NSString* expected_text,
diff --git a/ios/chrome/test/earl_grey/chrome_matchers.mm b/ios/chrome/test/earl_grey/chrome_matchers.mm index b5535fe..3d3fd77 100644 --- a/ios/chrome/test/earl_grey/chrome_matchers.mm +++ b/ios/chrome/test/earl_grey/chrome_matchers.mm
@@ -36,7 +36,6 @@ #import "ios/chrome/browser/ui/util/uikit_ui_util.h" #include "ios/chrome/grit/ios_strings.h" #import "ios/chrome/test/app/chrome_test_util.h" -#import "ios/web/public/block_types.h" #import "ios/web/public/test/earl_grey/web_view_matchers.h" #include "ui/base/l10n/l10n_util.h" #include "ui/base/test/ios/ui_image_test_utils.h"
diff --git a/ios/web/interstitials/web_interstitial_impl.h b/ios/web/interstitials/web_interstitial_impl.h index 96aa7dc..831f237 100644 --- a/ios/web/interstitials/web_interstitial_impl.h +++ b/ios/web/interstitials/web_interstitial_impl.h
@@ -27,7 +27,7 @@ // has access to private ExecuteJavaScript method to be used for testing. void ExecuteScriptForTesting(WebInterstitialImpl*, NSString*, - JavaScriptResultBlock); + void (^)(id, NSError*)); // An abstract subclass of WebInterstitial that exposes the views necessary to // embed the interstitial into a WebState. @@ -63,7 +63,7 @@ // Calls |completionHandler| with results of the evaluation. // The |completionHandler| can be nil. Must be used only for testing. virtual void ExecuteJavaScript(NSString* script, - JavaScriptResultBlock completion_handler); + void (^completion_handler)(id, NSError*)); private: // The WebState this instance is observing. Will be null after @@ -91,9 +91,10 @@ CRWContentView* content_view_; // Must be implemented only for testing purposes. - friend void web::ExecuteScriptForTesting(WebInterstitialImpl*, - NSString*, - JavaScriptResultBlock); + friend void web::ExecuteScriptForTesting( + WebInterstitialImpl*, + NSString*, + void (^completion_handler)(id, NSError*)); }; } // namespace web
diff --git a/ios/web/interstitials/web_interstitial_impl.mm b/ios/web/interstitials/web_interstitial_impl.mm index 02bb0ce..49d99bf 100644 --- a/ios/web/interstitials/web_interstitial_impl.mm +++ b/ios/web/interstitials/web_interstitial_impl.mm
@@ -189,7 +189,7 @@ void WebInterstitialImpl::ExecuteJavaScript( NSString* script, - JavaScriptResultBlock completion_handler) { + void (^completion_handler)(id, NSError*)) { web::ExecuteJavaScript(web_view_, script, completion_handler); }
diff --git a/ios/web/public/BUILD.gn b/ios/web/public/BUILD.gn index e877913..cbdd0d0 100644 --- a/ios/web/public/BUILD.gn +++ b/ios/web/public/BUILD.gn
@@ -19,7 +19,6 @@ ] sources = [ - "block_types.h", "browser_state.h", "browser_url_rewriter.h", "browsing_data_removing_util.h",
diff --git a/ios/web/public/block_types.h b/ios/web/public/block_types.h deleted file mode 100644 index 4b0ee2368..0000000 --- a/ios/web/public/block_types.h +++ /dev/null
@@ -1,21 +0,0 @@ -// Copyright 2015 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef IOS_WEB_PUBLIC_BLOCK_TYPES_H_ -#define IOS_WEB_PUBLIC_BLOCK_TYPES_H_ - -#import <Foundation/Foundation.h> - -namespace web { - -// The type of the completion handler block that is called to inform about -// JavaScript execution completion. id will be backed up by different classes -// depending on resulting JS type: NSString (string), NSNumber (number or -// boolean), NSDictionary (object), NSArray (array), NSNull (null), -// NSDate (Date), nil (undefined). -typedef void (^JavaScriptResultBlock)(id, NSError*); - -} // namespace - -#endif // IOS_WEB_PUBLIC_BLOCK_TYPES_H_
diff --git a/ios/web/public/test/earl_grey/js_test_util.mm b/ios/web/public/test/earl_grey/js_test_util.mm index a0c2510..7adf7d8 100644 --- a/ios/web/public/test/earl_grey/js_test_util.mm +++ b/ios/web/public/test/earl_grey/js_test_util.mm
@@ -24,7 +24,7 @@ // Evaluates the given |script| on |interstitial|. void ExecuteScriptForTesting(web::WebInterstitialImpl* interstitial, NSString* script, - web::JavaScriptResultBlock handler) { + void (^handler)(id result, NSError*)) { DCHECK(interstitial); interstitial->ExecuteJavaScript(script, handler); }
diff --git a/ios/web/public/test/fakes/crw_test_js_injection_receiver.mm b/ios/web/public/test/fakes/crw_test_js_injection_receiver.mm index e97bd620..9ae27b5 100644 --- a/ios/web/public/test/fakes/crw_test_js_injection_receiver.mm +++ b/ios/web/public/test/fakes/crw_test_js_injection_receiver.mm
@@ -33,7 +33,7 @@ } - (void)executeJavaScript:(NSString*)script - completionHandler:(web::JavaScriptResultBlock)completionHandler { + completionHandler:(void (^)(id, NSError*))completionHandler { web::ExecuteJavaScript(_webView, script, completionHandler); }
diff --git a/ios/web/public/web_state/js/crw_js_injection_evaluator.h b/ios/web/public/web_state/js/crw_js_injection_evaluator.h index 6bbd08d..5fad8b1 100644 --- a/ios/web/public/web_state/js/crw_js_injection_evaluator.h +++ b/ios/web/public/web_state/js/crw_js_injection_evaluator.h
@@ -7,8 +7,6 @@ #import <Foundation/Foundation.h> -#import "ios/web/public/block_types.h" - @protocol CRWJSInjectionEvaluator // Executes the supplied JavaScript in the WebView. Calls |completionHandler| @@ -16,7 +14,7 @@ // has no way to run the execution or the execution returns a nil value) // or an NSError if there is an error. The |completionHandler| can be nil. - (void)executeJavaScript:(NSString*)script - completionHandler:(web::JavaScriptResultBlock)completionHandler; + completionHandler:(void (^)(id, NSError*))completionHandler; // Checks to see if the script for a class has been injected into the // current page already.
diff --git a/ios/web/public/web_state/js/crw_js_injection_manager.h b/ios/web/public/web_state/js/crw_js_injection_manager.h index 567c9e9..b9b29e4 100644 --- a/ios/web/public/web_state/js/crw_js_injection_manager.h +++ b/ios/web/public/web_state/js/crw_js_injection_manager.h
@@ -29,7 +29,7 @@ // with results of the execution (which may be nil) or an NSError if there is an // error. The |completionHandler| can be nil. - (void)executeJavaScript:(NSString*)script - completionHandler:(web::JavaScriptResultBlock)completionHandler; + completionHandler:(void (^)(id, NSError*))completionHandler; @end
diff --git a/ios/web/public/web_state/ui/crw_native_content.h b/ios/web/public/web_state/ui/crw_native_content.h index 42798dd..b85f004 100644 --- a/ios/web/public/web_state/ui/crw_native_content.h +++ b/ios/web/public/web_state/ui/crw_native_content.h
@@ -7,7 +7,6 @@ #import <UIKit/UIKit.h> -#import "ios/web/public/block_types.h" #include "url/gurl.h" namespace web { @@ -54,7 +53,7 @@ // of the evaluation. If the native view cannot evaluate JS at the moment, // |handler| is called with an NSError. - (void)executeJavaScript:(NSString*)script - completionHandler:(web::JavaScriptResultBlock)handler; + completionHandler:(void (^)(id, NSError*))handler; // Dismisses any outstanding modal interaction elements (e.g. modal view // controllers, context menus, etc).
diff --git a/ios/web/web_state/js/crw_js_injection_manager.mm b/ios/web/web_state/js/crw_js_injection_manager.mm index 7743c8c..960fcfa 100644 --- a/ios/web/web_state/js/crw_js_injection_manager.mm +++ b/ios/web/web_state/js/crw_js_injection_manager.mm
@@ -59,7 +59,7 @@ } - (void)executeJavaScript:(NSString*)script - completionHandler:(web::JavaScriptResultBlock)completionHandler { + completionHandler:(void (^)(id, NSError*))completionHandler { [_receiver executeJavaScript:script completionHandler:completionHandler]; }
diff --git a/ios/web/web_state/js/crw_js_injection_receiver.mm b/ios/web/web_state/js/crw_js_injection_receiver.mm index 75e27b8..b7572dc0 100644 --- a/ios/web/web_state/js/crw_js_injection_receiver.mm +++ b/ios/web/web_state/js/crw_js_injection_receiver.mm
@@ -35,7 +35,7 @@ #pragma mark CRWJSInjectionEvaluatorMethods - (void)executeJavaScript:(NSString*)script - completionHandler:(web::JavaScriptResultBlock)completionHandler { + completionHandler:(void (^)(id, NSError*))completionHandler { [_evaluator executeJavaScript:script completionHandler:completionHandler]; }
diff --git a/ios/web/web_state/ui/crw_context_menu_controller.h b/ios/web/web_state/ui/crw_context_menu_controller.h index dbf5c8d..5f11a30 100644 --- a/ios/web/web_state/ui/crw_context_menu_controller.h +++ b/ios/web/web_state/ui/crw_context_menu_controller.h
@@ -8,8 +8,6 @@ #import <Foundation/Foundation.h> #import <WebKit/WebKit.h> -#import "ios/web/public/block_types.h" - namespace web { class BrowserState; } // namespace web
diff --git a/ios/web/web_state/ui/crw_context_menu_controller.mm b/ios/web/web_state/ui/crw_context_menu_controller.mm index b87e9c7..0bea0a4 100644 --- a/ios/web/web_state/ui/crw_context_menu_controller.mm +++ b/ios/web/web_state/ui/crw_context_menu_controller.mm
@@ -139,7 +139,7 @@ // Forwards the execution of |script| to |javaScriptDelegate| and if it is nil, // to |webView|. - (void)executeJavaScript:(NSString*)script - completionHandler:(web::JavaScriptResultBlock)completionHandler; + completionHandler:(void (^)(id, NSError*))completionHandler; @end @implementation CRWContextMenuController { @@ -258,7 +258,7 @@ } - (void)executeJavaScript:(NSString*)script - completionHandler:(web::JavaScriptResultBlock)completionHandler { + completionHandler:(void (^)(id, NSError*))completionHandler { if (self.injectionEvaluator) { [self.injectionEvaluator executeJavaScript:script completionHandler:completionHandler];
diff --git a/ios/web/web_state/ui/crw_web_controller.h b/ios/web/web_state/ui/crw_web_controller.h index 7ba69f0..ef45cc9 100644 --- a/ios/web/web_state/ui/crw_web_controller.h +++ b/ios/web/web_state/ui/crw_web_controller.h
@@ -179,8 +179,11 @@ - (void)stopLoading; // Executes |script| in the web view, registering user interaction. +// |result| will be backed up by different classes depending on resulting JS +// type: NSString (string), NSNumber (number or boolean), NSDictionary (object), +// NSArray (array), NSNull (null), NSDate (Date), nil (undefined). - (void)executeUserJavaScript:(NSString*)script - completionHandler:(web::JavaScriptResultBlock)completion; + completionHandler:(void (^)(id result, NSError*))completion; // Requires that the next load rebuild the web view. This is expensive, and // should be used only in the case where something has changed that the web view
diff --git a/ios/web/web_state/ui/crw_web_controller.mm b/ios/web/web_state/ui/crw_web_controller.mm index 11709c53..750db75 100644 --- a/ios/web/web_state/ui/crw_web_controller.mm +++ b/ios/web/web_state/ui/crw_web_controller.mm
@@ -1399,7 +1399,7 @@ } - (void)executeUserJavaScript:(NSString*)script - completionHandler:(web::JavaScriptResultBlock)completion { + completionHandler:(void (^)(id, NSError*))completion { // For security reasons, executing JavaScript on pages with app-specific URLs // is not allowed, because those pages may have elevated privileges. GURL lastCommittedURL = self.webState->GetLastCommittedURL(); @@ -1580,7 +1580,7 @@ #pragma mark - CRWJSInjectionEvaluator (Public) - (void)executeJavaScript:(NSString*)script - completionHandler:(web::JavaScriptResultBlock)completionHandler { + completionHandler:(void (^)(id, NSError*))completionHandler { NSString* safeScript = [self scriptByAddingWindowIDCheckForScript:script]; web::ExecuteJavaScript(self.webView, safeScript, completionHandler); }
diff --git a/ios/web/web_state/ui/web_view_js_utils.h b/ios/web/web_state/ui/web_view_js_utils.h index a165ccb2..a0f2b90 100644 --- a/ios/web/web_state/ui/web_view_js_utils.h +++ b/ios/web/web_state/ui/web_view_js_utils.h
@@ -8,8 +8,6 @@ #import <Foundation/Foundation.h> #include <memory> -#import "ios/web/public/block_types.h" - @class WKWebView; namespace base { @@ -39,7 +37,7 @@ // moment, |completion_handler| is called with an NSError. void ExecuteJavaScript(WKWebView* web_view, NSString* script, - JavaScriptResultBlock completion_handler); + void (^completion_handler)(id, NSError*)); } // namespace web
diff --git a/ios/web/web_state/ui/web_view_js_utils.mm b/ios/web/web_state/ui/web_view_js_utils.mm index 121e576..f38950c 100644 --- a/ios/web/web_state/ui/web_view_js_utils.mm +++ b/ios/web/web_state/ui/web_view_js_utils.mm
@@ -87,7 +87,7 @@ void ExecuteJavaScript(WKWebView* web_view, NSString* script, - JavaScriptResultBlock completion_handler) { + void (^completion_handler)(id, NSError*)) { DCHECK([script length]); if (!web_view && completion_handler) { dispatch_async(dispatch_get_main_queue(), ^{
diff --git a/ios/web_view/BUILD.gn b/ios/web_view/BUILD.gn index bb6772a..7cd81fd 100644 --- a/ios/web_view/BUILD.gn +++ b/ios/web_view/BUILD.gn
@@ -178,8 +178,6 @@ "internal/signin/web_view_signin_client_factory.mm", "internal/signin/web_view_signin_error_controller_factory.h", "internal/signin/web_view_signin_error_controller_factory.mm", - "internal/signin/web_view_signin_manager_factory.h", - "internal/signin/web_view_signin_manager_factory.mm", "internal/sync/web_view_device_info_sync_service_factory.h", "internal/sync/web_view_device_info_sync_service_factory.mm", "internal/sync/web_view_model_type_store_service_factory.h",
diff --git a/ios/web_view/internal/DEPS b/ios/web_view/internal/DEPS index 4d13ee1..a76b520e 100644 --- a/ios/web_view/internal/DEPS +++ b/ios/web_view/internal/DEPS
@@ -25,7 +25,6 @@ "!components/signin/core/browser/fake_profile_oauth2_token_service.h", "!components/signin/core/browser/profile_oauth2_token_service.h", "!components/signin/core/browser/fake_signin_manager.h", - "!components/signin/core/browser/signin_manager.h", "!components/signin/core/browser/signin_manager_base.h", "+components/signin/ios", "+components/ssl_errors",
diff --git a/ios/web_view/internal/signin/web_view_identity_manager_factory.h b/ios/web_view/internal/signin/web_view_identity_manager_factory.h index 0fa7385..b2e2e764 100644 --- a/ios/web_view/internal/signin/web_view_identity_manager_factory.h +++ b/ios/web_view/internal/signin/web_view_identity_manager_factory.h
@@ -39,7 +39,9 @@ // BrowserStateKeyedServiceFactory: std::unique_ptr<KeyedService> BuildServiceInstanceFor( - web::BrowserState* browser_state) const override; + web::BrowserState* context) const override; + void RegisterBrowserStatePrefs( + user_prefs::PrefRegistrySyncable* registry) override; DISALLOW_COPY_AND_ASSIGN(WebViewIdentityManagerFactory); };
diff --git a/ios/web_view/internal/signin/web_view_identity_manager_factory.mm b/ios/web_view/internal/signin/web_view_identity_manager_factory.mm index 0e2ea9c..b4c352d0 100644 --- a/ios/web_view/internal/signin/web_view_identity_manager_factory.mm +++ b/ios/web_view/internal/signin/web_view_identity_manager_factory.mm
@@ -8,11 +8,18 @@ #include "components/keyed_service/core/keyed_service.h" #include "components/keyed_service/ios/browser_state_dependency_manager.h" +#include "components/pref_registry/pref_registry_syncable.h" +#include "components/prefs/pref_service.h" +#include "components/signin/core/browser/account_consistency_method.h" +#include "components/signin/core/browser/signin_manager.h" +#include "components/signin/core/browser/signin_pref_names.h" +#include "ios/web_view/internal/app/application_context.h" +#include "ios/web_view/internal/signin/ios_web_view_signin_client.h" #include "ios/web_view/internal/signin/web_view_account_fetcher_service_factory.h" #include "ios/web_view/internal/signin/web_view_account_tracker_service_factory.h" #include "ios/web_view/internal/signin/web_view_gaia_cookie_manager_service_factory.h" #include "ios/web_view/internal/signin/web_view_oauth2_token_service_factory.h" -#include "ios/web_view/internal/signin/web_view_signin_manager_factory.h" +#include "ios/web_view/internal/signin/web_view_signin_client_factory.h" #include "ios/web_view/internal/web_view_browser_state.h" #include "services/identity/public/cpp/accounts_cookie_mutator_impl.h" #include "services/identity/public/cpp/accounts_mutator.h" @@ -26,6 +33,27 @@ namespace ios_web_view { +namespace { +std::unique_ptr<SigninManager> BuildSigninManager( + WebViewBrowserState* browser_state) { + // Clearing the sign in state on start up greatly simplifies the management of + // ChromeWebView's signin state. + PrefService* pref_service = browser_state->GetPrefs(); + pref_service->ClearPref(prefs::kGoogleServicesAccountId); + pref_service->ClearPref(prefs::kGoogleServicesUsername); + pref_service->ClearPref(prefs::kGoogleServicesUserAccountId); + + std::unique_ptr<SigninManager> service = std::make_unique<SigninManager>( + WebViewSigninClientFactory::GetForBrowserState(browser_state), + WebViewOAuth2TokenServiceFactory::GetForBrowserState(browser_state), + WebViewAccountTrackerServiceFactory::GetForBrowserState(browser_state), + WebViewGaiaCookieManagerServiceFactory::GetForBrowserState(browser_state), + signin::AccountConsistencyMethod::kDisabled); + service->Initialize(ApplicationContext::GetInstance()->GetLocalState()); + return service; +} +} // namespace + // Subclass that wraps IdentityManager in a KeyedService (as IdentityManager is // a client-side library intended for use by any process, it would be a layering // violation for IdentityManager itself to have direct knowledge of @@ -36,9 +64,12 @@ class IdentityManagerWrapper : public KeyedService, public identity::IdentityManager { public: - explicit IdentityManagerWrapper(WebViewBrowserState* browser_state) + explicit IdentityManagerWrapper( + std::unique_ptr<SigninManagerBase> signin_manager, + std::unique_ptr<identity::PrimaryAccountMutator> primary_account_mutator, + WebViewBrowserState* browser_state) : identity::IdentityManager( - WebViewSigninManagerFactory::GetForBrowserState(browser_state), + std::move(signin_manager), WebViewOAuth2TokenServiceFactory::GetForBrowserState(browser_state), WebViewAccountFetcherServiceFactory::GetForBrowserState( browser_state), @@ -46,11 +77,8 @@ browser_state), WebViewGaiaCookieManagerServiceFactory::GetForBrowserState( browser_state), - std::make_unique<identity::PrimaryAccountMutatorImpl>( - WebViewAccountTrackerServiceFactory::GetForBrowserState( - browser_state), - WebViewSigninManagerFactory::GetForBrowserState(browser_state)), - nullptr, + std::move(primary_account_mutator), + /*accounts_mutator=*/nullptr, std::make_unique<identity::AccountsCookieMutatorImpl>( WebViewGaiaCookieManagerServiceFactory::GetForBrowserState( browser_state)), @@ -61,6 +89,11 @@ browser_state))) {} }; +void WebViewIdentityManagerFactory::RegisterBrowserStatePrefs( + user_prefs::PrefRegistrySyncable* registry) { + SigninManagerBase::RegisterProfilePrefs(registry); +} + WebViewIdentityManagerFactory::WebViewIdentityManagerFactory() : BrowserStateKeyedServiceFactory( "IdentityManager", @@ -69,7 +102,7 @@ DependsOn(WebViewAccountTrackerServiceFactory::GetInstance()); DependsOn(WebViewGaiaCookieManagerServiceFactory::GetInstance()); DependsOn(WebViewOAuth2TokenServiceFactory::GetInstance()); - DependsOn(WebViewSigninManagerFactory::GetInstance()); + DependsOn(WebViewSigninClientFactory::GetInstance()); } WebViewIdentityManagerFactory::~WebViewIdentityManagerFactory() {} @@ -93,14 +126,27 @@ WebViewAccountTrackerServiceFactory::GetInstance(); WebViewGaiaCookieManagerServiceFactory::GetInstance(); WebViewOAuth2TokenServiceFactory::GetInstance(); - WebViewSigninManagerFactory::GetInstance(); + WebViewSigninClientFactory::GetInstance(); } std::unique_ptr<KeyedService> WebViewIdentityManagerFactory::BuildServiceInstanceFor( - web::BrowserState* browser_state) const { - return std::make_unique<IdentityManagerWrapper>( - WebViewBrowserState::FromBrowserState(browser_state)); + web::BrowserState* context) const { + WebViewBrowserState* browser_state = + WebViewBrowserState::FromBrowserState(context); + + // Construct the dependencies that IdentityManager will own. + std::unique_ptr<SigninManager> signin_manager = + BuildSigninManager(browser_state); + auto primary_account_mutator = + std::make_unique<identity::PrimaryAccountMutatorImpl>( + WebViewAccountTrackerServiceFactory::GetForBrowserState( + browser_state), + signin_manager.get()); + auto identity_manager = std::make_unique<IdentityManagerWrapper>( + std::move(signin_manager), std::move(primary_account_mutator), + browser_state); + return identity_manager; } } // namespace ios_web_view
diff --git a/ios/web_view/internal/signin/web_view_signin_manager_factory.h b/ios/web_view/internal/signin/web_view_signin_manager_factory.h deleted file mode 100644 index f38331c3..0000000 --- a/ios/web_view/internal/signin/web_view_signin_manager_factory.h +++ /dev/null
@@ -1,52 +0,0 @@ -// Copyright 2017 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef IOS_WEB_VIEW_INTERNAL_SIGNIN_WEB_VIEW_SIGNIN_MANAGER_FACTORY_H_ -#define IOS_WEB_VIEW_INTERNAL_SIGNIN_WEB_VIEW_SIGNIN_MANAGER_FACTORY_H_ - -#include <memory> - -#include "base/macros.h" -#include "base/no_destructor.h" -#include "base/observer_list.h" -#include "components/keyed_service/ios/browser_state_keyed_service_factory.h" - -class SigninManager; - -namespace ios_web_view { - -class WebViewBrowserState; - -// Singleton that owns all SigninManagers and associates them with browser -// states. -class WebViewSigninManagerFactory : public BrowserStateKeyedServiceFactory { - public: - static SigninManager* GetForBrowserState( - ios_web_view::WebViewBrowserState* browser_state); - static SigninManager* GetForBrowserStateIfExists( - ios_web_view::WebViewBrowserState* browser_state); - - // Returns an instance of the SigninManagerFactory singleton. - static WebViewSigninManagerFactory* GetInstance(); - - // Implementation of BrowserStateKeyedServiceFactory (public so tests - // can call it). - void RegisterBrowserStatePrefs( - user_prefs::PrefRegistrySyncable* registry) override; - - private: - friend class base::NoDestructor<WebViewSigninManagerFactory>; - - WebViewSigninManagerFactory(); - ~WebViewSigninManagerFactory() override = default; - - // BrowserStateKeyedServiceFactory: - std::unique_ptr<KeyedService> BuildServiceInstanceFor( - web::BrowserState* context) const override; - void BrowserStateShutdown(web::BrowserState* context) override; -}; - -} // namespace ios_web_view - -#endif // IOS_WEB_VIEW_INTERNAL_SIGNIN_WEB_VIEW_SIGNIN_MANAGER_FACTORY_H_
diff --git a/ios/web_view/internal/signin/web_view_signin_manager_factory.mm b/ios/web_view/internal/signin/web_view_signin_manager_factory.mm deleted file mode 100644 index e3dcdf4..0000000 --- a/ios/web_view/internal/signin/web_view_signin_manager_factory.mm +++ /dev/null
@@ -1,94 +0,0 @@ -// Copyright 2017 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ios/web_view/internal/signin/web_view_signin_manager_factory.h" - -#include <utility> - -#include "base/no_destructor.h" -#include "base/time/time.h" -#include "components/keyed_service/ios/browser_state_dependency_manager.h" -#include "components/pref_registry/pref_registry_syncable.h" -#include "components/prefs/pref_service.h" -#include "components/signin/core/browser/account_consistency_method.h" -#include "components/signin/core/browser/signin_manager.h" -#include "components/signin/core/browser/signin_pref_names.h" -#include "ios/web_view/internal/app/application_context.h" -#include "ios/web_view/internal/signin/ios_web_view_signin_client.h" -#include "ios/web_view/internal/signin/web_view_account_tracker_service_factory.h" -#include "ios/web_view/internal/signin/web_view_gaia_cookie_manager_service_factory.h" -#include "ios/web_view/internal/signin/web_view_oauth2_token_service_factory.h" -#include "ios/web_view/internal/signin/web_view_signin_client_factory.h" -#include "ios/web_view/internal/web_view_browser_state.h" - -#if !defined(__has_feature) || !__has_feature(objc_arc) -#error "This file requires ARC support." -#endif - -namespace ios_web_view { - -WebViewSigninManagerFactory::WebViewSigninManagerFactory() - : BrowserStateKeyedServiceFactory( - "SigninManager", - BrowserStateDependencyManager::GetInstance()) { - DependsOn(WebViewSigninClientFactory::GetInstance()); - DependsOn(WebViewGaiaCookieManagerServiceFactory::GetInstance()); - DependsOn(WebViewOAuth2TokenServiceFactory::GetInstance()); - DependsOn(WebViewAccountTrackerServiceFactory::GetInstance()); -} - -// static -SigninManager* WebViewSigninManagerFactory::GetForBrowserState( - ios_web_view::WebViewBrowserState* browser_state) { - return static_cast<SigninManager*>( - GetInstance()->GetServiceForBrowserState(browser_state, true)); -} - -// static -SigninManager* WebViewSigninManagerFactory::GetForBrowserStateIfExists( - ios_web_view::WebViewBrowserState* browser_state) { - return static_cast<SigninManager*>( - GetInstance()->GetServiceForBrowserState(browser_state, false)); -} - -// static -WebViewSigninManagerFactory* WebViewSigninManagerFactory::GetInstance() { - static base::NoDestructor<WebViewSigninManagerFactory> instance; - return instance.get(); -} - -void WebViewSigninManagerFactory::RegisterBrowserStatePrefs( - user_prefs::PrefRegistrySyncable* registry) { - SigninManagerBase::RegisterProfilePrefs(registry); -} - -std::unique_ptr<KeyedService> -WebViewSigninManagerFactory::BuildServiceInstanceFor( - web::BrowserState* context) const { - WebViewBrowserState* browser_state = - WebViewBrowserState::FromBrowserState(context); - - // Clearing the sign in state on start up greatly simplifies the management of - // ChromeWebView's signin state. - PrefService* pref_service = browser_state->GetPrefs(); - pref_service->ClearPref(prefs::kGoogleServicesAccountId); - pref_service->ClearPref(prefs::kGoogleServicesUsername); - pref_service->ClearPref(prefs::kGoogleServicesUserAccountId); - - std::unique_ptr<SigninManager> service = std::make_unique<SigninManager>( - WebViewSigninClientFactory::GetForBrowserState(browser_state), - WebViewOAuth2TokenServiceFactory::GetForBrowserState(browser_state), - WebViewAccountTrackerServiceFactory::GetForBrowserState(browser_state), - WebViewGaiaCookieManagerServiceFactory::GetForBrowserState(browser_state), - signin::AccountConsistencyMethod::kDisabled); - service->Initialize(ApplicationContext::GetInstance()->GetLocalState()); - return service; -} - -void WebViewSigninManagerFactory::BrowserStateShutdown( - web::BrowserState* context) { - BrowserStateKeyedServiceFactory::BrowserStateShutdown(context); -} - -} // namespace ios_web_view
diff --git a/ios/web_view/internal/web_view_browser_state.mm b/ios/web_view/internal/web_view_browser_state.mm index 934ddf2..365c8e38 100644 --- a/ios/web_view/internal/web_view_browser_state.mm +++ b/ios/web_view/internal/web_view_browser_state.mm
@@ -166,10 +166,10 @@ void WebViewBrowserState::RegisterPrefs( user_prefs::PrefRegistrySyncable* pref_registry) { - language::RegisterProfilePrefs(pref_registry); pref_registry->RegisterBooleanPref(prefs::kOfferTranslateEnabled, true); pref_registry->RegisterBooleanPref(prefs::kSavingBrowserHistoryDisabled, true); + language::LanguagePrefs::RegisterProfilePrefs(pref_registry); translate::TranslatePrefs::RegisterProfilePrefs(pref_registry); #if BUILDFLAG(IOS_WEB_VIEW_ENABLE_AUTOFILL)
diff --git a/media/capture/video/video_capture_device_unittest.cc b/media/capture/video/video_capture_device_unittest.cc index ca983bb..fb39e510 100644 --- a/media/capture/video/video_capture_device_unittest.cc +++ b/media/capture/video/video_capture_device_unittest.cc
@@ -279,7 +279,7 @@ void SetUp() override { #if defined(OS_CHROMEOS) - chromeos::PowerManagerClient::Initialize(); + chromeos::PowerManagerClient::InitializeFake(); #endif #if defined(OS_ANDROID) static_cast<VideoCaptureDeviceFactoryAndroid*>(
diff --git a/media/formats/webm/webm_cluster_parser.cc b/media/formats/webm/webm_cluster_parser.cc index 297906c..52cca8b 100644 --- a/media/formats/webm/webm_cluster_parser.cc +++ b/media/formats/webm/webm_cluster_parser.cc
@@ -36,7 +36,7 @@ }; WebMClusterParser::WebMClusterParser( - int64_t timecode_scale, + int64_t timecode_scale_ns, int audio_track_num, base::TimeDelta audio_default_duration, int video_track_num, @@ -47,7 +47,7 @@ const std::string& video_encryption_key_id, const AudioCodec audio_codec, MediaLog* media_log) - : timecode_multiplier_(timecode_scale / 1000.0), + : timecode_multiplier_(timecode_scale_ns / 1000.0), ignored_tracks_(ignored_tracks), audio_encryption_key_id_(audio_encryption_key_id), video_encryption_key_id_(video_encryption_key_id),
diff --git a/media/formats/webm/webm_cluster_parser.h b/media/formats/webm/webm_cluster_parser.h index ffc5ae2..4eaa97e 100644 --- a/media/formats/webm/webm_cluster_parser.h +++ b/media/formats/webm/webm_cluster_parser.h
@@ -148,7 +148,7 @@ typedef std::map<int, Track> TextTrackMap; public: - WebMClusterParser(int64_t timecode_scale, + WebMClusterParser(int64_t timecode_scale_ns, int audio_track_num, base::TimeDelta audio_default_duration, int video_track_num,
diff --git a/media/formats/webm/webm_info_parser.cc b/media/formats/webm/webm_info_parser.cc index 3cd32c1..3e5eede 100644 --- a/media/formats/webm/webm_info_parser.cc +++ b/media/formats/webm/webm_info_parser.cc
@@ -9,19 +9,16 @@ namespace media { -// Default timecode scale if the TimecodeScale element is -// not specified in the INFO element. +// Default timecode scale, in nanoseconds, if the TimecodeScale element is not +// specified in the INFO element. static const int kWebMDefaultTimecodeScale = 1000000; -WebMInfoParser::WebMInfoParser() - : timecode_scale_(-1), - duration_(-1) { -} +WebMInfoParser::WebMInfoParser() : timecode_scale_ns_(-1), duration_(-1) {} WebMInfoParser::~WebMInfoParser() = default; int WebMInfoParser::Parse(const uint8_t* buf, int size) { - timecode_scale_ = -1; + timecode_scale_ns_ = -1; duration_ = -1; WebMListParser parser(kWebMIdInfo, this); @@ -37,10 +34,10 @@ WebMParserClient* WebMInfoParser::OnListStart(int id) { return this; } bool WebMInfoParser::OnListEnd(int id) { - if (id == kWebMIdInfo && timecode_scale_ == -1) { + if (id == kWebMIdInfo && timecode_scale_ns_ == -1) { // Set timecode scale to default value if it isn't present in // the Info element. - timecode_scale_ = kWebMDefaultTimecodeScale; + timecode_scale_ns_ = kWebMDefaultTimecodeScale; } return true; } @@ -54,12 +51,12 @@ return false; } - if (timecode_scale_ != -1) { + if (timecode_scale_ns_ != -1) { DVLOG(1) << "Multiple values for id " << std::hex << id << " specified"; return false; } - timecode_scale_ = val; + timecode_scale_ns_ = val; return true; }
diff --git a/media/formats/webm/webm_info_parser.h b/media/formats/webm/webm_info_parser.h index 7548ad21..1c6a518 100644 --- a/media/formats/webm/webm_info_parser.h +++ b/media/formats/webm/webm_info_parser.h
@@ -28,7 +28,7 @@ // Returns the number of bytes parsed on success. int Parse(const uint8_t* buf, int size); - int64_t timecode_scale() const { return timecode_scale_; } + int64_t timecode_scale_ns() const { return timecode_scale_ns_; } double duration() const { return duration_; } base::Time date_utc() const { return date_utc_; } @@ -41,7 +41,7 @@ bool OnBinary(int id, const uint8_t* data, int size) override; bool OnString(int id, const std::string& str) override; - int64_t timecode_scale_; + int64_t timecode_scale_ns_; double duration_; base::Time date_utc_;
diff --git a/media/formats/webm/webm_stream_parser.cc b/media/formats/webm/webm_stream_parser.cc index 7178beb6..9e3a0c9 100644 --- a/media/formats/webm/webm_stream_parser.cc +++ b/media/formats/webm/webm_stream_parser.cc
@@ -202,7 +202,8 @@ bytes_parsed += result; - double timecode_scale_in_us = info_parser.timecode_scale() / 1000.0; + int64_t timecode_scale_in_ns = info_parser.timecode_scale_ns(); + double timecode_scale_in_us = timecode_scale_in_ns / 1000.0; InitParameters params(kInfiniteDuration); if (info_parser.duration() > 0) { @@ -237,10 +238,10 @@ } cluster_parser_.reset(new WebMClusterParser( - info_parser.timecode_scale(), tracks_parser.audio_track_num(), - tracks_parser.GetAudioDefaultDuration(timecode_scale_in_us), + timecode_scale_in_ns, tracks_parser.audio_track_num(), + tracks_parser.GetAudioDefaultDuration(timecode_scale_in_ns), tracks_parser.video_track_num(), - tracks_parser.GetVideoDefaultDuration(timecode_scale_in_us), + tracks_parser.GetVideoDefaultDuration(timecode_scale_in_ns), tracks_parser.text_tracks(), tracks_parser.ignored_tracks(), tracks_parser.audio_encryption_key_id(), tracks_parser.video_encryption_key_id(), audio_config.codec(),
diff --git a/media/formats/webm/webm_tracks_parser.cc b/media/formats/webm/webm_tracks_parser.cc index 59838d9..22db0c7 100644 --- a/media/formats/webm/webm_tracks_parser.cc +++ b/media/formats/webm/webm_tracks_parser.cc
@@ -30,21 +30,6 @@ return kTextNone; } -static base::TimeDelta PrecisionCappedDefaultDuration( - const double timecode_scale_in_us, - const int64_t duration_in_ns) { - if (duration_in_ns <= 0) - return kNoTimestamp; - - int64_t mult = duration_in_ns / 1000; - mult /= timecode_scale_in_us; - if (mult == 0) - return kNoTimestamp; - - mult = static_cast<double>(mult) * timecode_scale_in_us; - return base::TimeDelta::FromMicroseconds(mult); -} - WebMTracksParser::WebMTracksParser(MediaLog* media_log, bool ignore_text_tracks) : ignore_text_tracks_(ignore_text_tracks), media_log_(media_log), @@ -55,6 +40,24 @@ WebMTracksParser::~WebMTracksParser() = default; +base::TimeDelta WebMTracksParser::PrecisionCappedDefaultDuration( + const int64_t timecode_scale_in_ns, + const int64_t duration_in_ns) const { + DCHECK_GT(timecode_scale_in_ns, 0); + if (duration_in_ns <= 0) + return kNoTimestamp; + + // Calculate the (integral) number of complete |timecode_scale_in_ns| + // intervals that fit within |duration_in_ns|. + int64_t intervals = duration_in_ns / timecode_scale_in_ns; + + int64_t result_us = (intervals * timecode_scale_in_ns) / 1000; + if (result_us == 0) + return kNoTimestamp; + + return base::TimeDelta::FromMicroseconds(result_us); +} + void WebMTracksParser::Reset() { ResetTrackEntry(); reset_on_next_parse_ = false; @@ -103,14 +106,14 @@ } base::TimeDelta WebMTracksParser::GetAudioDefaultDuration( - const double timecode_scale_in_us) const { - return PrecisionCappedDefaultDuration(timecode_scale_in_us, + const int64_t timecode_scale_in_ns) const { + return PrecisionCappedDefaultDuration(timecode_scale_in_ns, audio_default_duration_); } base::TimeDelta WebMTracksParser::GetVideoDefaultDuration( - const double timecode_scale_in_us) const { - return PrecisionCappedDefaultDuration(timecode_scale_in_us, + const int64_t timecode_scale_in_ns) const { + return PrecisionCappedDefaultDuration(timecode_scale_in_ns, video_default_duration_); }
diff --git a/media/formats/webm/webm_tracks_parser.h b/media/formats/webm/webm_tracks_parser.h index 1e8cb04..7299668 100644 --- a/media/formats/webm/webm_tracks_parser.h +++ b/media/formats/webm/webm_tracks_parser.h
@@ -46,12 +46,12 @@ // If TrackEntry DefaultDuration field existed for the associated audio or // video track, returns that value converted from ns to base::TimeDelta with - // precision not greater than |timecode_scale_in_us|. Defaults to + // precision not greater than |timecode_scale_in_ns|. Defaults to // kNoTimestamp. base::TimeDelta GetAudioDefaultDuration( - const double timecode_scale_in_us) const; + const int64_t timecode_scale_in_ns) const; base::TimeDelta GetVideoDefaultDuration( - const double timecode_scale_in_us) const; + const int64_t timecode_scale_in_ns) const; const std::set<int64_t>& ignored_tracks() const { return ignored_tracks_; } @@ -93,6 +93,19 @@ } private: + // To test PrecisionCappedDefaultDuration. + FRIEND_TEST_ALL_PREFIXES(WebMTracksParserTest, PrecisionCapping); + + // Returns the conversion of |duration_in_ns| to a microsecond-granularity + // TimeDelta with precision no greater than |timecode_scale_in_ns|. + // Returns kNoTimestamp if |duration_in_ns| is <= 0, or the capped precision + // of the converted |duration_in_ns| is < 1 microsecond. + // Commonly, |timecode_scale_in_ns| is 1000000 (1 millisecond), though the + // muxed stream could have used a different time scale. + base::TimeDelta PrecisionCappedDefaultDuration( + const int64_t timecode_scale_in_ns, + const int64_t duration_in_ns) const; + void Reset(); void ResetTrackEntry();
diff --git a/media/formats/webm/webm_tracks_parser_unittest.cc b/media/formats/webm/webm_tracks_parser_unittest.cc index 2d5c63e7..66520a0 100644 --- a/media/formats/webm/webm_tracks_parser_unittest.cc +++ b/media/formats/webm/webm_tracks_parser_unittest.cc
@@ -26,7 +26,8 @@ namespace media { -static const double kDefaultTimecodeScaleInUs = 1000.0; // 1 ms resolution +// WebM muxing commonly uses 1 millisecond resolution. +static const int64_t kOneMsInNs = 1000000; class WebMTracksParserTest : public testing::Test { public: @@ -152,10 +153,8 @@ EXPECT_LE(0, result); EXPECT_EQ(static_cast<int>(buf.size()), result); - EXPECT_EQ(kNoTimestamp, - parser->GetAudioDefaultDuration(kDefaultTimecodeScaleInUs)); - EXPECT_EQ(kNoTimestamp, - parser->GetVideoDefaultDuration(kDefaultTimecodeScaleInUs)); + EXPECT_EQ(kNoTimestamp, parser->GetAudioDefaultDuration(kOneMsInNs)); + EXPECT_EQ(kNoTimestamp, parser->GetVideoDefaultDuration(kOneMsInNs)); const VideoDecoderConfig& video_config = parser->video_decoder_config(); EXPECT_TRUE(video_config.IsValidConfig()); @@ -183,14 +182,14 @@ EXPECT_EQ(static_cast<int>(buf.size()), result); EXPECT_EQ(base::TimeDelta::FromMicroseconds(12000), - parser->GetAudioDefaultDuration(kDefaultTimecodeScaleInUs)); + parser->GetAudioDefaultDuration(kOneMsInNs)); EXPECT_EQ(base::TimeDelta::FromMicroseconds(985000), - parser->GetVideoDefaultDuration(5000.0)); // 5 ms resolution - EXPECT_EQ(kNoTimestamp, parser->GetAudioDefaultDuration(12346.0)); + parser->GetVideoDefaultDuration(5000000)); // 5 ms resolution + EXPECT_EQ(kNoTimestamp, parser->GetAudioDefaultDuration(12346000)); EXPECT_EQ(base::TimeDelta::FromMicroseconds(12345), - parser->GetAudioDefaultDuration(12345.0)); + parser->GetAudioDefaultDuration(12345000)); EXPECT_EQ(base::TimeDelta::FromMicroseconds(12003), - parser->GetAudioDefaultDuration(1000.3)); // 1.0003 ms resolution + parser->GetAudioDefaultDuration(1000300)); // 1.0003 ms resolution } TEST_F(WebMTracksParserTest, InvalidZeroDefaultDurationSet) { @@ -251,4 +250,49 @@ EXPECT_GT(parser->Parse(&buf[0], buf.size()),0); } +TEST_F(WebMTracksParserTest, PrecisionCapping) { + struct CappingCases { + int64_t scale_ns; + int64_t duration_ns; + base::TimeDelta expected_result; + }; + + const CappingCases kCappingCases[] = { + {kOneMsInNs, -1, kNoTimestamp}, + {kOneMsInNs, 0, kNoTimestamp}, + {kOneMsInNs, 1, kNoTimestamp}, + {kOneMsInNs, 999999, kNoTimestamp}, + {kOneMsInNs, 1000000, base::TimeDelta::FromMilliseconds(1)}, + {kOneMsInNs, 1000001, base::TimeDelta::FromMilliseconds(1)}, + {kOneMsInNs, 1999999, base::TimeDelta::FromMilliseconds(1)}, + {kOneMsInNs, 2000000, base::TimeDelta::FromMilliseconds(2)}, + {1, -1, kNoTimestamp}, + {1, 0, kNoTimestamp}, + + // Result < 1us, so kNoTimestamp + {1, 1, kNoTimestamp}, + {1, 999, kNoTimestamp}, + + {1, 1000, base::TimeDelta::FromMicroseconds(1)}, + {1, 1999, base::TimeDelta::FromMicroseconds(1)}, + {1, 2000, base::TimeDelta::FromMicroseconds(2)}, + + {64, 1792, base::TimeDelta::FromMicroseconds(1)}, + }; + + std::unique_ptr<WebMTracksParser> parser( + new WebMTracksParser(&media_log_, false)); + + for (size_t i = 0; i < base::size(kCappingCases); ++i) { + InSequence s; + int64_t scale_ns = kCappingCases[i].scale_ns; + int64_t duration_ns = kCappingCases[i].duration_ns; + base::TimeDelta expected_result = kCappingCases[i].expected_result; + + EXPECT_EQ(parser->PrecisionCappedDefaultDuration(scale_ns, duration_ns), + expected_result) + << i << ": " << scale_ns << ", " << duration_ns; + } +} + } // namespace media
diff --git a/net/BUILD.gn b/net/BUILD.gn index 64576ee..ec176bb 100644 --- a/net/BUILD.gn +++ b/net/BUILD.gn
@@ -1374,6 +1374,7 @@ "third_party/quiche/src/quic/core/crypto/crypto_utils.h", "third_party/quiche/src/quic/core/crypto/curve25519_key_exchange.cc", "third_party/quiche/src/quic/core/crypto/curve25519_key_exchange.h", + "third_party/quiche/src/quic/core/crypto/key_exchange.cc", "third_party/quiche/src/quic/core/crypto/key_exchange.h", "third_party/quiche/src/quic/core/crypto/null_decrypter.cc", "third_party/quiche/src/quic/core/crypto/null_decrypter.h", @@ -2351,8 +2352,6 @@ component("extras") { sources = [ "extras/sqlite/cookie_crypto_delegate.h", - "extras/sqlite/sqlite_channel_id_store.cc", - "extras/sqlite/sqlite_channel_id_store.h", "extras/sqlite/sqlite_persistent_cookie_store.cc", "extras/sqlite/sqlite_persistent_cookie_store.h", "extras/sqlite/sqlite_persistent_store_backend_base.cc", @@ -4904,7 +4903,6 @@ "disk_cache/simple/simple_test_util.h", "disk_cache/simple/simple_util_unittest.cc", "disk_cache/simple/simple_version_upgrade_unittest.cc", - "extras/sqlite/sqlite_channel_id_store_unittest.cc", "extras/sqlite/sqlite_persistent_cookie_store_unittest.cc", "filter/brotli_source_stream_unittest.cc", "filter/filter_source_stream_unittest.cc", @@ -5044,6 +5042,7 @@ "quic/quic_test_packet_maker.h", "quic/quic_utils_chromium_test.cc", "socket/client_socket_pool_base_unittest.cc", + "socket/client_socket_pool_unittest.cc", "socket/connect_job_test_util.cc", "socket/connect_job_test_util.h", "socket/connect_job_unittest.cc",
diff --git a/net/disk_cache/backend_unittest.cc b/net/disk_cache/backend_unittest.cc index 824dea7..81fe8d8 100644 --- a/net/disk_cache/backend_unittest.cc +++ b/net/disk_cache/backend_unittest.cc
@@ -84,6 +84,7 @@ std::make_unique<disk_cache::BackendImpl>(cache_path, /* cleanup_tracker = */ nullptr, /* cache_thread = */ nullptr, + net::DISK_CACHE, /* net_log = */ nullptr)); int rv = cache->Init(cb.callback()); if (cb.GetResult(rv) != net::OK) @@ -730,7 +731,7 @@ bool prev = base::ThreadRestrictions::SetIOAllowed(false); std::unique_ptr<disk_cache::BackendImpl> cache( std::make_unique<disk_cache::BackendImpl>(cache_path_, nullptr, nullptr, - nullptr)); + net::DISK_CACHE, nullptr)); int rv = cache->Init(cb.callback()); EXPECT_THAT(cb.GetResult(rv), IsError(net::ERR_FAILED)); base::ThreadRestrictions::SetIOAllowed(prev); @@ -2475,7 +2476,7 @@ std::unique_ptr<disk_cache::BackendImpl> cache( std::make_unique<disk_cache::BackendImpl>(cache_path_, nullptr, nullptr, - nullptr)); + net::DISK_CACHE, nullptr)); int rv = cache->Init(cb.callback()); ASSERT_THAT(cb.GetResult(rv), IsError(net::ERR_FAILED)); } @@ -2525,8 +2526,8 @@ const int kRestartCount = 5; for (int i = 0; i < kRestartCount; ++i) { - cache.reset( - new disk_cache::BackendImpl(cache_path_, nullptr, nullptr, nullptr)); + cache.reset(new disk_cache::BackendImpl(cache_path_, nullptr, nullptr, + net::DISK_CACHE, nullptr)); int rv = cache->Init(cb.callback()); ASSERT_THAT(cb.GetResult(rv), IsOk()); EXPECT_EQ(1, cache->GetEntryCount()); @@ -2567,7 +2568,7 @@ for (int i = 0; i < kRestartCount; ++i) { std::unique_ptr<disk_cache::BackendImpl> cache( std::make_unique<disk_cache::BackendImpl>(cache_path_, nullptr, nullptr, - nullptr)); + net::DISK_CACHE, nullptr)); int rv = cache->Init(cb.callback()); ASSERT_THAT(cb.GetResult(rv), IsOk()); EXPECT_EQ(1, cache->GetEntryCount()); @@ -3526,7 +3527,8 @@ // Want to use our thread since we call SyncInit ourselves. std::unique_ptr<disk_cache::BackendImpl> cache( std::make_unique<disk_cache::BackendImpl>( - cache_path_, nullptr, base::ThreadTaskRunnerHandle::Get(), nullptr)); + cache_path_, nullptr, base::ThreadTaskRunnerHandle::Get(), + net::DISK_CACHE, nullptr)); ASSERT_TRUE(nullptr != cache.get()); cache->SetUnitTestMode(); ASSERT_THAT(cache->SyncInit(), IsOk()); @@ -3542,7 +3544,8 @@ // Want to use our thread since we call SyncInit ourselves. std::unique_ptr<disk_cache::BackendImpl> cache( std::make_unique<disk_cache::BackendImpl>( - cache_path_, nullptr, base::ThreadTaskRunnerHandle::Get(), nullptr)); + cache_path_, nullptr, base::ThreadTaskRunnerHandle::Get(), + net::DISK_CACHE, nullptr)); ASSERT_TRUE(nullptr != cache.get()); cache->SetUnitTestMode(); ASSERT_NE(net::OK, cache->SyncInit()); @@ -4108,8 +4111,8 @@ cache_.reset(); // Check that the |BackendImpl| does not favor this structure. - disk_cache::BackendImpl* cache = - new disk_cache::BackendImpl(cache_path_, nullptr, nullptr, nullptr); + disk_cache::BackendImpl* cache = new disk_cache::BackendImpl( + cache_path_, nullptr, nullptr, net::DISK_CACHE, nullptr); cache->SetUnitTestMode(); net::TestCompletionCallback cb; int rv = cache->Init(cb.callback());
diff --git a/net/disk_cache/blockfile/backend_impl.cc b/net/disk_cache/blockfile/backend_impl.cc index a7e54f9..b7af71b 100644 --- a/net/disk_cache/blockfile/backend_impl.cc +++ b/net/disk_cache/blockfile/backend_impl.cc
@@ -150,15 +150,16 @@ const base::FilePath& path, scoped_refptr<BackendCleanupTracker> cleanup_tracker, const scoped_refptr<base::SingleThreadTaskRunner>& cache_thread, + net::CacheType cache_type, net::NetLog* net_log) - : cleanup_tracker_(std::move(cleanup_tracker)), + : Backend(cache_type), + cleanup_tracker_(std::move(cleanup_tracker)), background_queue_(this, FallbackToInternalIfNull(cache_thread)), path_(path), block_files_(path), mask_(0), max_size_(0), up_ticks_(0), - cache_type_(net::DISK_CACHE), uma_report_(0), user_flags_(0), init_(false), @@ -179,14 +180,15 @@ const base::FilePath& path, uint32_t mask, const scoped_refptr<base::SingleThreadTaskRunner>& cache_thread, + net::CacheType cache_type, net::NetLog* net_log) - : background_queue_(this, FallbackToInternalIfNull(cache_thread)), + : Backend(cache_type), + background_queue_(this, FallbackToInternalIfNull(cache_thread)), path_(path), block_files_(path), mask_(mask), max_size_(0), up_ticks_(0), - cache_type_(net::DISK_CACHE), uma_report_(0), user_flags_(kMask), init_(false), @@ -261,14 +263,14 @@ Trace("Init"); if (data_->header.experiment != NO_EXPERIMENT && - cache_type_ != net::DISK_CACHE) { + GetCacheType() != net::DISK_CACHE) { // No experiment for other caches. return net::ERR_FAILED; } if (!(user_flags_ & kNoRandom)) { // The unit test controls directly what to test. - new_eviction_ = (cache_type_ == net::DISK_CACHE); + new_eviction_ = (GetCacheType() == net::DISK_CACHE); } if (!CheckIndex()) { @@ -279,7 +281,7 @@ if (!restarted_ && (create_files || !data_->header.num_entries)) ReportError(ERR_CACHE_CREATED); - if (!(user_flags_ & kNoRandom) && cache_type_ == net::DISK_CACHE && + if (!(user_flags_ & kNoRandom) && GetCacheType() == net::DISK_CACHE && !InitExperiment(&data_->header, create_files)) { return net::ERR_FAILED; } @@ -299,10 +301,10 @@ return net::ERR_FAILED; // We want to minimize the changes to cache for an AppCache. - if (cache_type() == net::APP_CACHE) { + if (GetCacheType() == net::APP_CACHE) { DCHECK(!new_eviction_); read_only_ = true; - } else if (cache_type() == net::SHADER_CACHE) { + } else if (GetCacheType() == net::SHADER_CACHE) { DCHECK(!new_eviction_); } @@ -418,7 +420,7 @@ int BackendImpl::SyncDoomEntriesBetween(const base::Time initial_time, const base::Time end_time) { - DCHECK_NE(net::APP_CACHE, cache_type_); + DCHECK_NE(net::APP_CACHE, GetCacheType()); if (end_time.is_null()) return SyncDoomEntriesSince(initial_time); @@ -450,7 +452,7 @@ } int BackendImpl::SyncCalculateSizeOfAllEntries() { - DCHECK_NE(net::APP_CACHE, cache_type_); + DCHECK_NE(net::APP_CACHE, GetCacheType()); if (disabled_) return net::ERR_FAILED; @@ -460,7 +462,7 @@ // We use OpenNextEntryImpl to retrieve elements from the cache, until we get // entries that are too old. int BackendImpl::SyncDoomEntriesSince(const base::Time initial_time) { - DCHECK_NE(net::APP_CACHE, cache_type_); + DCHECK_NE(net::APP_CACHE, GetCacheType()); if (disabled_) return net::ERR_FAILED; @@ -504,7 +506,7 @@ scoped_refptr<EntryImpl> cache_entry = MatchEntry(key, hash, false, Addr(), &error); if (cache_entry && ENTRY_NORMAL == cache_entry->entry()->Data()->state) - UpdateRank(cache_entry.get(), cache_type() == net::SHADER_CACHE); + UpdateRank(cache_entry.get(), GetCacheType() == net::SHADER_CACHE); } scoped_refptr<EntryImpl> BackendImpl::OpenEntryImpl(const std::string& key) { @@ -730,11 +732,6 @@ return true; } -void BackendImpl::SetType(net::CacheType type) { - DCHECK_NE(net::MEMORY_CACHE, type); - cache_type_ = type; -} - base::FilePath BackendImpl::GetFileName(Addr address) const { if (!address.is_separate_file() || !address.is_initialized()) { NOTREACHED(); @@ -804,7 +801,7 @@ } void BackendImpl::UpdateRank(EntryImpl* entry, bool modified) { - if (read_only_ || (!modified && cache_type() == net::SHADER_CACHE)) + if (read_only_ || (!modified && GetCacheType() == net::SHADER_CACHE)) return; eviction_.UpdateRank(entry, modified); } @@ -943,7 +940,7 @@ } int64_t BackendImpl::MaxFileSize() const { - return cache_type() == net::PNACL_CACHE ? max_size_ : max_size_ / 8; + return GetCacheType() == net::PNACL_CACHE ? max_size_ : max_size_ / 8; } void BackendImpl::ModifyStorageSize(int32_t old_size, int32_t new_size) { @@ -993,9 +990,9 @@ std::string BackendImpl::HistogramName(const char* name, int experiment) const { if (!experiment) - return base::StringPrintf("DiskCache.%d.%s", cache_type_, name); - return base::StringPrintf("DiskCache.%d.%s_%d", cache_type_, - name, experiment); + return base::StringPrintf("DiskCache.%d.%s", GetCacheType(), name); + return base::StringPrintf("DiskCache.%d.%s_%d", GetCacheType(), name, + experiment); } base::WeakPtr<BackendImpl> BackendImpl::GetWeakPtr() { @@ -1234,10 +1231,6 @@ // ------------------------------------------------------------------------ -net::CacheType BackendImpl::GetCacheType() const { - return cache_type_; -} - int32_t BackendImpl::GetEntryCount() const { if (!index_.get() || disabled_) return 0; @@ -1518,7 +1511,7 @@ if (!stats_.Init(data.get(), size, address)) return false; - if (cache_type_ == net::DISK_CACHE && ShouldReportAgain()) + if (GetCacheType() == net::DISK_CACHE && ShouldReportAgain()) stats_.InitSizeHistogram(); return true; } @@ -2017,7 +2010,7 @@ stats_.ResetRatios(); stats_.SetCounter(Stats::TRIM_ENTRY, 0); - if (cache_type_ == net::DISK_CACHE) + if (GetCacheType() == net::DISK_CACHE) block_files_.ReportStats(); }
diff --git a/net/disk_cache/blockfile/backend_impl.h b/net/disk_cache/blockfile/backend_impl.h index e7a4ae9..99d28d7b 100644 --- a/net/disk_cache/blockfile/backend_impl.h +++ b/net/disk_cache/blockfile/backend_impl.h
@@ -58,12 +58,14 @@ BackendImpl(const base::FilePath& path, scoped_refptr<BackendCleanupTracker> cleanup_tracker, const scoped_refptr<base::SingleThreadTaskRunner>& cache_thread, + net::CacheType cache_type, net::NetLog* net_log); // mask can be used to limit the usable size of the hash table, for testing. BackendImpl(const base::FilePath& path, uint32_t mask, const scoped_refptr<base::SingleThreadTaskRunner>& cache_thread, + net::CacheType cache_type, net::NetLog* net_log); ~BackendImpl() override; @@ -100,9 +102,6 @@ // Sets the maximum size for the total amount of data stored by this instance. bool SetMaxSize(int64_t max_bytes); - // Sets the cache type for this backend. - void SetType(net::CacheType type); - // Returns the full name for an external storage file. base::FilePath GetFileName(Addr address) const; @@ -192,10 +191,6 @@ // is the cache type and e the provided |experiment|. std::string HistogramName(const char* name, int experiment) const; - net::CacheType cache_type() const { - return cache_type_; - } - bool read_only() const { return read_only_; } @@ -275,7 +270,6 @@ static void FlushForTesting(); // Backend implementation. - net::CacheType GetCacheType() const override; int32_t GetEntryCount() const override; net::Error OpenOrCreateEntry(const std::string& key, net::RequestPriority request_priority, @@ -416,7 +410,6 @@ int byte_count_; // Number of bytes read/written lately. int buffer_bytes_; // Total size of the temporary entries' buffers. int up_ticks_; // The number of timer ticks received (OnStatsTimer). - net::CacheType cache_type_; int uma_report_; // Controls transmission of UMA data. uint32_t user_flags_; // Flags set by the user. bool init_; // controls the initialization of the system.
diff --git a/net/disk_cache/blockfile/histogram_macros.h b/net/disk_cache/blockfile/histogram_macros.h index 9ae04cc..a2204b0 100644 --- a/net/disk_cache/blockfile/histogram_macros.h +++ b/net/disk_cache/blockfile/histogram_macros.h
@@ -91,7 +91,7 @@ { \ const std::string my_name = \ CACHE_UMA_BACKEND_IMPL_OBJ->HistogramName(name, experiment); \ - switch (CACHE_UMA_BACKEND_IMPL_OBJ->cache_type()) { \ + switch (CACHE_UMA_BACKEND_IMPL_OBJ->GetCacheType()) { \ default: \ NOTREACHED(); \ FALLTHROUGH; \
diff --git a/net/disk_cache/disk_cache.cc b/net/disk_cache/disk_cache.cc index 1bb5e648..b9fe811 100644 --- a/net/disk_cache/disk_cache.cc +++ b/net/disk_cache/disk_cache.cc
@@ -128,11 +128,11 @@ #if defined(OS_ANDROID) return net::ERR_FAILED; #else - disk_cache::BackendImpl* new_cache = new disk_cache::BackendImpl( - path_, cleanup_tracker_.get(), /*cache_thread = */ nullptr, net_log_); + disk_cache::BackendImpl* new_cache = + new disk_cache::BackendImpl(path_, cleanup_tracker_.get(), + /*cache_thread = */ nullptr, type_, net_log_); created_cache_.reset(new_cache); new_cache->SetMaxSize(max_bytes_); - new_cache->SetType(type_); net::Error rv = new_cache->Init( base::Bind(&CacheCreator::OnIOComplete, base::Unretained(this))); DCHECK_EQ(net::ERR_IO_PENDING, rv);
diff --git a/net/disk_cache/disk_cache.h b/net/disk_cache/disk_cache.h index 0c1f713..0ea3cee3 100644 --- a/net/disk_cache/disk_cache.h +++ b/net/disk_cache/disk_cache.h
@@ -152,10 +152,11 @@ // on what will succeed and what will fail. In particular the blockfile // backend will leak entries closed after backend deletion, while others // handle it properly. + Backend(net::CacheType cache_type) : cache_type_(cache_type) {} virtual ~Backend() {} // Returns the type of this cache. - virtual net::CacheType GetCacheType() const = 0; + net::CacheType GetCacheType() const { return cache_type_; } // Returns the number of entries in the cache. virtual int32_t GetEntryCount() const = 0; @@ -284,6 +285,9 @@ // Returns the maximum length an individual stream can have. virtual int64_t MaxFileSize() const = 0; + + private: + const net::CacheType cache_type_; }; // This interface represents an entry in the disk cache.
diff --git a/net/disk_cache/disk_cache_test_base.cc b/net/disk_cache/disk_cache_test_base.cc index f7ca9b2a..80d6ca0 100644 --- a/net/disk_cache/disk_cache_test_base.cc +++ b/net/disk_cache/disk_cache_test_base.cc
@@ -372,19 +372,18 @@ } if (mask_) - cache_impl_ = new disk_cache::BackendImpl(cache_path_, mask_, runner, + cache_impl_ = new disk_cache::BackendImpl(cache_path_, mask_, runner, type_, /* net_log = */ nullptr); else - cache_impl_ = new disk_cache::BackendImpl(cache_path_, - /* cleanup_tracker = */ nullptr, - runner, /* net_log = */ nullptr); + cache_impl_ = new disk_cache::BackendImpl( + cache_path_, /* cleanup_tracker = */ nullptr, runner, type_, + /* net_log = */ nullptr); cache_.reset(cache_impl_); ASSERT_TRUE(cache_); if (size_) EXPECT_TRUE(cache_impl_->SetMaxSize(size_)); if (new_eviction_) cache_impl_->SetNewEviction(); - cache_impl_->SetType(type_); cache_impl_->SetFlags(flags); net::TestCompletionCallback cb; int rv = cache_impl_->Init(cb.callback());
diff --git a/net/disk_cache/disk_cache_test_util.cc b/net/disk_cache/disk_cache_test_util.cc index 57741417..8af0da2e 100644 --- a/net/disk_cache/disk_cache_test_util.cc +++ b/net/disk_cache/disk_cache_test_util.cc
@@ -64,7 +64,8 @@ int max_size, uint32_t mask) { std::unique_ptr<disk_cache::BackendImpl> cache(new disk_cache::BackendImpl( - path, mask, base::ThreadTaskRunnerHandle::Get(), nullptr)); + path, mask, base::ThreadTaskRunnerHandle::Get(), net::DISK_CACHE, + nullptr)); if (max_size) cache->SetMaxSize(max_size); if (!cache.get())
diff --git a/net/disk_cache/memory/mem_backend_impl.cc b/net/disk_cache/memory/mem_backend_impl.cc index 480c978..a03c53d 100644 --- a/net/disk_cache/memory/mem_backend_impl.cc +++ b/net/disk_cache/memory/mem_backend_impl.cc
@@ -57,7 +57,8 @@ } // namespace MemBackendImpl::MemBackendImpl(net::NetLog* net_log) - : max_size_(0), + : Backend(net::MEMORY_CACHE), + max_size_(0), current_size_(0), net_log_(net_log), memory_pressure_listener_( @@ -160,10 +161,6 @@ post_cleanup_callback_ = std::move(cb); } -net::CacheType MemBackendImpl::GetCacheType() const { - return net::MEMORY_CACHE; -} - int32_t MemBackendImpl::GetEntryCount() const { return static_cast<int32_t>(entries_.size()); }
diff --git a/net/disk_cache/memory/mem_backend_impl.h b/net/disk_cache/memory/mem_backend_impl.h index f5d4c25..f79ef3320 100644 --- a/net/disk_cache/memory/mem_backend_impl.h +++ b/net/disk_cache/memory/mem_backend_impl.h
@@ -84,7 +84,6 @@ void SetPostCleanupCallback(base::OnceClosure cb); // Backend interface. - net::CacheType GetCacheType() const override; int32_t GetEntryCount() const override; net::Error OpenOrCreateEntry(const std::string& key, net::RequestPriority request_priority,
diff --git a/net/disk_cache/simple/simple_backend_impl.cc b/net/disk_cache/simple/simple_backend_impl.cc index d57fb5c..709369fd 100644 --- a/net/disk_cache/simple/simple_backend_impl.cc +++ b/net/disk_cache/simple/simple_backend_impl.cc
@@ -237,11 +237,11 @@ int64_t max_bytes, net::CacheType cache_type, net::NetLog* net_log) - : cleanup_tracker_(std::move(cleanup_tracker)), + : Backend(cache_type), + cleanup_tracker_(std::move(cleanup_tracker)), file_tracker_(file_tracker ? file_tracker : g_simple_file_tracker.Pointer()), path_(path), - cache_type_(cache_type), cache_runner_(base::CreateSequencedTaskRunnerWithTraits( {base::MayBlock(), base::TaskPriority::USER_BLOCKING, base::TaskShutdownBehavior::BLOCK_SHUTDOWN})), @@ -282,16 +282,16 @@ index_ = std::make_unique<SimpleIndex>( base::ThreadTaskRunnerHandle::Get(), cleanup_tracker_.get(), this, - cache_type_, + GetCacheType(), std::make_unique<SimpleIndexFile>(cache_runner_, worker_pool.get(), - cache_type_, path_)); + GetCacheType(), path_)); index_->ExecuteWhenReady( - base::BindOnce(&RecordIndexLoad, cache_type_, base::TimeTicks::Now())); + base::BindOnce(&RecordIndexLoad, GetCacheType(), base::TimeTicks::Now())); PostTaskAndReplyWithResult( cache_runner_.get(), FROM_HERE, base::BindOnce(&SimpleBackendImpl::InitCacheStructureOnDisk, path_, - orig_max_size_, cache_type_), + orig_max_size_, GetCacheType()), base::BindOnce(&SimpleBackendImpl::InitializeIndex, AsWeakPtr(), std::move(completion_callback))); return net::ERR_IO_PENDING; @@ -324,11 +324,11 @@ to_handle_waiters.swap(it->second); entries_pending_doom_.erase(it); - SIMPLE_CACHE_UMA(COUNTS_1000, "NumOpsBlockedByPendingDoom", cache_type_, + SIMPLE_CACHE_UMA(COUNTS_1000, "NumOpsBlockedByPendingDoom", GetCacheType(), to_handle_waiters.size()); for (PostDoomWaiter& post_doom : to_handle_waiters) { - SIMPLE_CACHE_UMA(TIMES, "QueueLatency.PendingDoom", cache_type_, + SIMPLE_CACHE_UMA(TIMES, "QueueLatency.PendingDoom", GetCacheType(), (base::TimeTicks::Now() - post_doom.time_queued)); std::move(post_doom.run_post_doom).Run(); } @@ -394,10 +394,6 @@ base::Passed(&mass_doom_entry_hashes), barrier_callback)); } -net::CacheType SimpleBackendImpl::GetCacheType() const { - return net::DISK_CACHE; -} - int32_t SimpleBackendImpl::GetEntryCount() const { // TODO(pasko): Use directory file count when index is not ready. return index_->GetEntryCount(); @@ -516,7 +512,7 @@ if (post_doom->empty() && entry_operations_mode_ == SimpleEntryImpl::OPTIMISTIC_OPERATIONS) { simple_entry = new SimpleEntryImpl( - cache_type_, path_, cleanup_tracker_.get(), entry_hash, + GetCacheType(), path_, cleanup_tracker_.get(), entry_hash, entry_operations_mode_, this, file_tracker_, net_log_, GetNewEntryPriority(request_priority)); simple_entry->SetKey(key); @@ -844,7 +840,7 @@ const bool did_insert = insert_result.second; if (did_insert) { SimpleEntryImpl* entry = it->second = new SimpleEntryImpl( - cache_type_, path_, cleanup_tracker_.get(), entry_hash, + GetCacheType(), path_, cleanup_tracker_.get(), entry_hash, entry_operations_mode_, this, file_tracker_, net_log_, GetNewEntryPriority(request_priority)); entry->SetKey(key); @@ -887,7 +883,7 @@ } scoped_refptr<SimpleEntryImpl> simple_entry = new SimpleEntryImpl( - cache_type_, path_, cleanup_tracker_.get(), entry_hash, + GetCacheType(), path_, cleanup_tracker_.get(), entry_hash, entry_operations_mode_, this, file_tracker_, net_log_, GetNewEntryPriority(net::HIGHEST)); CompletionOnceCallback backend_callback =
diff --git a/net/disk_cache/simple/simple_backend_impl.h b/net/disk_cache/simple/simple_backend_impl.h index 434d1f0..4237f85c 100644 --- a/net/disk_cache/simple/simple_backend_impl.h +++ b/net/disk_cache/simple/simple_backend_impl.h
@@ -74,7 +74,6 @@ ~SimpleBackendImpl() override; - net::CacheType cache_type() const { return cache_type_; } SimpleIndex* index() { return index_.get(); } void SetWorkerPoolForTesting(scoped_refptr<base::TaskRunner> task_runner); @@ -104,7 +103,6 @@ CompletionOnceCallback callback) override; // Backend: - net::CacheType GetCacheType() const override; int32_t GetEntryCount() const override; net::Error OpenEntry(const std::string& key, net::RequestPriority request_priority, @@ -283,7 +281,6 @@ SimpleFileTracker* const file_tracker_; const base::FilePath path_; - const net::CacheType cache_type_; std::unique_ptr<SimpleIndex> index_; // This is only used for initial open (including potential format upgrade)
diff --git a/net/extras/sqlite/sqlite_channel_id_store.cc b/net/extras/sqlite/sqlite_channel_id_store.cc deleted file mode 100644 index 865fb63..0000000 --- a/net/extras/sqlite/sqlite_channel_id_store.cc +++ /dev/null
@@ -1,615 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "net/extras/sqlite/sqlite_channel_id_store.h" - -#include <memory> -#include <set> -#include <utility> -#include <vector> - -#include "base/bind.h" -#include "base/files/file_path.h" -#include "base/files/file_util.h" -#include "base/location.h" -#include "base/logging.h" -#include "base/macros.h" -#include "base/metrics/histogram_macros.h" -#include "base/sequenced_task_runner.h" -#include "base/stl_util.h" -#include "base/strings/string_util.h" -#include "crypto/ec_private_key.h" -#include "net/cert/asn1_util.h" -#include "net/cert/x509_certificate.h" -#include "net/cookies/cookie_util.h" -#include "net/ssl/channel_id_service.h" -#include "net/ssl/ssl_client_cert_type.h" -#include "sql/error_delegate_util.h" -#include "sql/meta_table.h" -#include "sql/statement.h" -#include "sql/transaction.h" -#include "url/gurl.h" - -namespace { - -// Version number of the database. -const int kCurrentVersionNumber = 6; -const int kCompatibleVersionNumber = 6; - -// Used in the DomainBoundCerts.DBLoadStatus histogram to record the status of -// the Channel ID database when loading it from disk. It reports reasons why the -// db could fail to load, or that it was loaded successfully. -// Do not change or re-use values. -enum DbLoadStatus { - // The path for the directory containing the db doesn't exist and couldn't be - // created. - PATH_DOES_NOT_EXIST = 0, - // Unable to open the database. - FAILED_TO_OPEN = 1, - // Failed to migrate the db to the current version. - MIGRATION_FAILED = 2, - // Unable to execute SELECT statement to load contents from db. - INVALID_SELECT_STATEMENT = 3, - // New database successfully created. - NEW_DB = 4, - // Database successfully loaded. - LOADED = 5, - // Database loaded, but one or more keys were skipped. - LOADED_WITH_ERRORS = 6, - DB_LOAD_STATUS_MAX -}; - -void RecordDbLoadStatus(DbLoadStatus status) { - UMA_HISTOGRAM_ENUMERATION("DomainBoundCerts.DBLoadStatus", status, - DB_LOAD_STATUS_MAX); -} - -} // namespace - -namespace net { - -// This class is designed to be shared between any calling threads and the -// background task runner. It batches operations and commits them on a timer. -class SQLiteChannelIDStore::Backend - : public base::RefCountedThreadSafe<SQLiteChannelIDStore::Backend> { - public: - Backend( - const base::FilePath& path, - const scoped_refptr<base::SequencedTaskRunner>& background_task_runner) - : path_(path), - num_pending_(0), - force_keep_session_state_(false), - background_task_runner_(background_task_runner), - corruption_detected_(false) {} - - // Creates or loads the SQLite database. - void Load(const LoadedCallback& loaded_callback); - - // Batch a channel ID addition. - void AddChannelID(const DefaultChannelIDStore::ChannelID& channel_id); - - // Batch a channel ID deletion. - void DeleteChannelID(const DefaultChannelIDStore::ChannelID& channel_id); - - // Post background delete of all channel ids for |server_identifiers|. - void DeleteAllInList(const std::list<std::string>& server_identifiers); - - // Commit any pending operations and close the database. This must be called - // before the object is destructed. - void Close(); - - void SetForceKeepSessionState(); - - // Posts a task to flush pending operations to the database. - void Flush(); - - private: - friend class base::RefCountedThreadSafe<SQLiteChannelIDStore::Backend>; - - // You should call Close() before destructing this object. - virtual ~Backend() { - DCHECK(!db_.get()) << "Close should have already been called."; - DCHECK_EQ(0u, num_pending_); - DCHECK(pending_.empty()); - } - - void LoadInBackground( - std::vector<std::unique_ptr<DefaultChannelIDStore::ChannelID>>* - channel_ids); - - // Database upgrade statements. - bool EnsureDatabaseVersion(); - - class PendingOperation { - public: - enum OperationType { CHANNEL_ID_ADD, CHANNEL_ID_DELETE }; - - PendingOperation(OperationType op, - const DefaultChannelIDStore::ChannelID& channel_id) - : op_(op), channel_id_(channel_id) {} - - OperationType op() const { return op_; } - const DefaultChannelIDStore::ChannelID& channel_id() const { - return channel_id_; - } - - private: - OperationType op_; - DefaultChannelIDStore::ChannelID channel_id_; - }; - - private: - // Batch a channel id operation (add or delete). - void BatchOperation(PendingOperation::OperationType op, - const DefaultChannelIDStore::ChannelID& channel_id); - // Prunes the list of pending operations to remove any operations for an - // identifier in |server_identifiers|. - void PrunePendingOperationsForDeletes( - const std::list<std::string>& server_identifiers); - // Commit our pending operations to the database. - void Commit(); - // Close() executed on the background task runner. - void InternalBackgroundClose(); - - void BackgroundDeleteAllInList( - const std::list<std::string>& server_identifiers); - - void DatabaseErrorCallback(int error, sql::Statement* stmt); - void KillDatabase(); - - const base::FilePath path_; - std::unique_ptr<sql::Database> db_; - sql::MetaTable meta_table_; - - typedef std::list<std::unique_ptr<PendingOperation>> PendingOperationsList; - PendingOperationsList pending_; - PendingOperationsList::size_type num_pending_; - // True if the persistent store should skip clear on exit rules. - bool force_keep_session_state_; - // Guard |pending_|, |num_pending_| and |force_keep_session_state_|. - base::Lock lock_; - - scoped_refptr<base::SequencedTaskRunner> background_task_runner_; - - // Indicates if the kill-database callback has been scheduled. - bool corruption_detected_; - - DISALLOW_COPY_AND_ASSIGN(Backend); -}; - -void SQLiteChannelIDStore::Backend::Load( - const LoadedCallback& loaded_callback) { - // This function should be called only once per instance. - DCHECK(!db_.get()); - std::unique_ptr< - std::vector<std::unique_ptr<DefaultChannelIDStore::ChannelID>>> - channel_ids( - new std::vector<std::unique_ptr<DefaultChannelIDStore::ChannelID>>()); - std::vector<std::unique_ptr<DefaultChannelIDStore::ChannelID>>* - channel_ids_ptr = channel_ids.get(); - - background_task_runner_->PostTaskAndReply( - FROM_HERE, - base::Bind(&Backend::LoadInBackground, this, channel_ids_ptr), - base::Bind(loaded_callback, base::Passed(&channel_ids))); -} - -void SQLiteChannelIDStore::Backend::LoadInBackground( - std::vector<std::unique_ptr<DefaultChannelIDStore::ChannelID>>* - channel_ids) { - DCHECK(background_task_runner_->RunsTasksInCurrentSequence()); - - // This method should be called only once per instance. - DCHECK(!db_.get()); - - // Ensure the parent directory for storing certs is created before reading - // from it. - const base::FilePath dir = path_.DirName(); - if (!base::PathExists(dir) && !base::CreateDirectory(dir)) { - RecordDbLoadStatus(PATH_DOES_NOT_EXIST); - return; - } - - db_.reset(new sql::Database); - db_->set_histogram_tag("DomainBoundCerts"); - - // Unretained to avoid a ref loop with db_. - db_->set_error_callback( - base::Bind(&SQLiteChannelIDStore::Backend::DatabaseErrorCallback, - base::Unretained(this))); - - DbLoadStatus load_result = LOADED; - if (!base::PathExists(path_)) { - load_result = NEW_DB; - } - - if (!db_->Open(path_)) { - NOTREACHED() << "Unable to open cert DB."; - if (corruption_detected_) - KillDatabase(); - db_.reset(); - RecordDbLoadStatus(FAILED_TO_OPEN); - return; - } - - if (!EnsureDatabaseVersion()) { - NOTREACHED() << "Unable to open cert DB."; - if (corruption_detected_) - KillDatabase(); - meta_table_.Reset(); - db_.reset(); - RecordDbLoadStatus(MIGRATION_FAILED); - return; - } - - db_->Preload(); - - // Slurp all the certs into the out-vector. - sql::Statement smt(db_->GetUniqueStatement( - "SELECT host, private_key, creation_time FROM channel_id")); - if (!smt.is_valid()) { - if (corruption_detected_) - KillDatabase(); - meta_table_.Reset(); - db_.reset(); - RecordDbLoadStatus(INVALID_SELECT_STATEMENT); - return; - } - - while (smt.Step()) { - std::vector<uint8_t> private_key_from_db; - smt.ColumnBlobAsVector(1, &private_key_from_db); - std::unique_ptr<crypto::ECPrivateKey> key( - crypto::ECPrivateKey::CreateFromPrivateKeyInfo(private_key_from_db)); - if (!key) { - load_result = LOADED_WITH_ERRORS; - continue; - } - std::unique_ptr<DefaultChannelIDStore::ChannelID> channel_id( - new DefaultChannelIDStore::ChannelID( - smt.ColumnString(0), // host - base::Time::FromInternalValue(smt.ColumnInt64(2)), std::move(key))); - channel_ids->push_back(std::move(channel_id)); - } - - RecordDbLoadStatus(load_result); -} - -bool SQLiteChannelIDStore::Backend::EnsureDatabaseVersion() { - // Version check. - if (!meta_table_.Init( - db_.get(), kCurrentVersionNumber, kCompatibleVersionNumber)) { - return false; - } - - if (meta_table_.GetCompatibleVersionNumber() > kCurrentVersionNumber) { - LOG(WARNING) << "Server bound cert database is too new."; - return false; - } - - int cur_version = meta_table_.GetVersionNumber(); - UMA_HISTOGRAM_EXACT_LINEAR("DomainBoundCerts.DBVersion", cur_version, - kCurrentVersionNumber + 1); - - sql::Transaction transaction(db_.get()); - if (!transaction.Begin()) - return false; - - // Create new table if it doesn't already exist - if (!db_->DoesTableExist("channel_id")) { - if (!db_->Execute( - "CREATE TABLE channel_id (" - "host TEXT NOT NULL UNIQUE PRIMARY KEY," - "private_key BLOB NOT NULL," - "public_key BLOB NOT NULL," - "creation_time INTEGER)")) { - return false; - } - } - - if (cur_version < kCurrentVersionNumber) { - if (cur_version <= 4) { - sql::Statement statement( - db_->GetUniqueStatement("DROP TABLE origin_bound_certs")); - if (!statement.Run()) { - LOG(WARNING) << "Error dropping old origin_bound_certs table"; - return false; - } - } - if (cur_version < 6) { - // The old format had the private_key column in a format we no longer - // read. Just delete any entries in that format. - sql::Statement statement( - db_->GetUniqueStatement("DELETE FROM channel_id")); - if (!statement.Run()) { - LOG(WARNING) << "Error clearing channel_id table"; - return false; - } - } - meta_table_.SetVersionNumber(kCurrentVersionNumber); - meta_table_.SetCompatibleVersionNumber(kCompatibleVersionNumber); - } - transaction.Commit(); - - // Put future migration cases here. - - return true; -} - -void SQLiteChannelIDStore::Backend::DatabaseErrorCallback( - int error, - sql::Statement* stmt) { - DCHECK(background_task_runner_->RunsTasksInCurrentSequence()); - - if (!sql::IsErrorCatastrophic(error)) - return; - - // TODO(shess): Running KillDatabase() multiple times should be - // safe. - if (corruption_detected_) - return; - - corruption_detected_ = true; - - // TODO(shess): Consider just calling RazeAndClose() immediately. - // db_ may not be safe to reset at this point, but RazeAndClose() - // would cause the stack to unwind safely with errors. - background_task_runner_->PostTask( - FROM_HERE, base::BindOnce(&Backend::KillDatabase, this)); -} - -void SQLiteChannelIDStore::Backend::KillDatabase() { - DCHECK(background_task_runner_->RunsTasksInCurrentSequence()); - - if (db_) { - // This Backend will now be in-memory only. In a future run the database - // will be recreated. Hopefully things go better then! - bool success = db_->RazeAndClose(); - UMA_HISTOGRAM_BOOLEAN("DomainBoundCerts.KillDatabaseResult", success); - meta_table_.Reset(); - db_.reset(); - } -} - -void SQLiteChannelIDStore::Backend::AddChannelID( - const DefaultChannelIDStore::ChannelID& channel_id) { - BatchOperation(PendingOperation::CHANNEL_ID_ADD, channel_id); -} - -void SQLiteChannelIDStore::Backend::DeleteChannelID( - const DefaultChannelIDStore::ChannelID& channel_id) { - BatchOperation(PendingOperation::CHANNEL_ID_DELETE, channel_id); -} - -void SQLiteChannelIDStore::Backend::DeleteAllInList( - const std::list<std::string>& server_identifiers) { - if (server_identifiers.empty()) - return; - // Perform deletion on background task runner. - background_task_runner_->PostTask( - FROM_HERE, base::BindOnce(&Backend::BackgroundDeleteAllInList, this, - server_identifiers)); -} - -void SQLiteChannelIDStore::Backend::BatchOperation( - PendingOperation::OperationType op, - const DefaultChannelIDStore::ChannelID& channel_id) { - // These thresholds used to be 30 seconds or 512 outstanding operations (the - // same values used in CookieMonster). Since cookies can be bound to Channel - // IDs, it's possible for a cookie to get committed to the cookie database - // before the Channel ID it is bound to gets committed. Decreasing these - // thresholds increases the chance that the Channel ID will be committed - // before or at the same time as the cookie. - - // Commit every 2 seconds. - static const int kCommitIntervalMs = 2 * 1000; - // Commit right away if we have more than 3 outstanding operations. - static const size_t kCommitAfterBatchSize = 3; - - // We do a full copy of the cert here, and hopefully just here. - std::unique_ptr<PendingOperation> po(new PendingOperation(op, channel_id)); - - PendingOperationsList::size_type num_pending; - { - base::AutoLock locked(lock_); - pending_.push_back(std::move(po)); - num_pending = ++num_pending_; - } - - if (num_pending == 1) { - // We've gotten our first entry for this batch, fire off the timer. - background_task_runner_->PostDelayedTask( - FROM_HERE, base::BindOnce(&Backend::Commit, this), - base::TimeDelta::FromMilliseconds(kCommitIntervalMs)); - } else if (num_pending == kCommitAfterBatchSize) { - // We've reached a big enough batch, fire off a commit now. - background_task_runner_->PostTask(FROM_HERE, - base::BindOnce(&Backend::Commit, this)); - } -} - -void SQLiteChannelIDStore::Backend::PrunePendingOperationsForDeletes( - const std::list<std::string>& server_identifiers) { - DCHECK(background_task_runner_->RunsTasksInCurrentSequence()); - base::AutoLock locked(lock_); - - for (auto it = pending_.begin(); it != pending_.end();) { - if (base::ContainsValue(server_identifiers, - (*it)->channel_id().server_identifier())) { - std::unique_ptr<PendingOperation> po(std::move(*it)); - it = pending_.erase(it); - --num_pending_; - } else { - ++it; - } - } -} - -void SQLiteChannelIDStore::Backend::Flush() { - if (background_task_runner_->RunsTasksInCurrentSequence()) { - Commit(); - } else { - background_task_runner_->PostTask(FROM_HERE, - base::BindOnce(&Backend::Commit, this)); - } -} - -void SQLiteChannelIDStore::Backend::Commit() { - DCHECK(background_task_runner_->RunsTasksInCurrentSequence()); - - PendingOperationsList ops; - { - base::AutoLock locked(lock_); - pending_.swap(ops); - num_pending_ = 0; - } - - // Maybe an old timer fired or we are already Close()'ed. - if (!db_.get() || ops.empty()) - return; - - sql::Statement add_statement(db_->GetCachedStatement( - SQL_FROM_HERE, - "INSERT INTO channel_id (host, private_key, public_key, creation_time) " - "VALUES (?,?,\"\",?)")); - if (!add_statement.is_valid()) - return; - - sql::Statement del_statement(db_->GetCachedStatement( - SQL_FROM_HERE, "DELETE FROM channel_id WHERE host=?")); - if (!del_statement.is_valid()) - return; - - sql::Transaction transaction(db_.get()); - if (!transaction.Begin()) - return; - - for (auto it = ops.begin(); it != ops.end(); ++it) { - // Free the certs as we commit them to the database. - std::unique_ptr<PendingOperation> po(std::move(*it)); - switch (po->op()) { - case PendingOperation::CHANNEL_ID_ADD: { - add_statement.Reset(true); - add_statement.BindString(0, po->channel_id().server_identifier()); - std::vector<uint8_t> private_key; - if (!po->channel_id().key()->ExportPrivateKey(&private_key)) - continue; - add_statement.BindBlob( - 1, private_key.data(), static_cast<int>(private_key.size())); - add_statement.BindInt64( - 2, po->channel_id().creation_time().ToInternalValue()); - if (!add_statement.Run()) - NOTREACHED() << "Could not add a server bound cert to the DB."; - break; - } - case PendingOperation::CHANNEL_ID_DELETE: - del_statement.Reset(true); - del_statement.BindString(0, po->channel_id().server_identifier()); - if (!del_statement.Run()) - NOTREACHED() << "Could not delete a server bound cert from the DB."; - break; - - default: - NOTREACHED(); - break; - } - } - transaction.Commit(); -} - -// Fire off a close message to the background task runner. We could still have a -// pending commit timer that will be holding a reference on us, but if/when -// this fires we will already have been cleaned up and it will be ignored. -void SQLiteChannelIDStore::Backend::Close() { - // Must close the backend on the background task runner. - background_task_runner_->PostTask( - FROM_HERE, base::BindOnce(&Backend::InternalBackgroundClose, this)); -} - -void SQLiteChannelIDStore::Backend::InternalBackgroundClose() { - DCHECK(background_task_runner_->RunsTasksInCurrentSequence()); - // Commit any pending operations - Commit(); - db_.reset(); -} - -void SQLiteChannelIDStore::Backend::BackgroundDeleteAllInList( - const std::list<std::string>& server_identifiers) { - DCHECK(background_task_runner_->RunsTasksInCurrentSequence()); - - if (!db_.get()) - return; - - PrunePendingOperationsForDeletes(server_identifiers); - - sql::Statement del_smt(db_->GetCachedStatement( - SQL_FROM_HERE, "DELETE FROM channel_id WHERE host=?")); - if (!del_smt.is_valid()) { - LOG(WARNING) << "Unable to delete channel ids."; - return; - } - - sql::Transaction transaction(db_.get()); - if (!transaction.Begin()) { - LOG(WARNING) << "Unable to delete channel ids."; - return; - } - - for (auto it = server_identifiers.begin(); it != server_identifiers.end(); - ++it) { - del_smt.Reset(true); - del_smt.BindString(0, *it); - if (!del_smt.Run()) - NOTREACHED() << "Could not delete a channel id from the DB."; - } - - if (!transaction.Commit()) - LOG(WARNING) << "Unable to delete channel ids."; -} - -void SQLiteChannelIDStore::Backend::SetForceKeepSessionState() { - base::AutoLock locked(lock_); - force_keep_session_state_ = true; -} - -SQLiteChannelIDStore::SQLiteChannelIDStore( - const base::FilePath& path, - const scoped_refptr<base::SequencedTaskRunner>& background_task_runner) - : backend_(new Backend(path, background_task_runner)) { -} - -void SQLiteChannelIDStore::Load(const LoadedCallback& loaded_callback) { - backend_->Load(loaded_callback); -} - -void SQLiteChannelIDStore::AddChannelID( - const DefaultChannelIDStore::ChannelID& channel_id) { - backend_->AddChannelID(channel_id); -} - -void SQLiteChannelIDStore::DeleteChannelID( - const DefaultChannelIDStore::ChannelID& channel_id) { - backend_->DeleteChannelID(channel_id); -} - -void SQLiteChannelIDStore::DeleteAllInList( - const std::list<std::string>& server_identifiers) { - backend_->DeleteAllInList(server_identifiers); -} - -void SQLiteChannelIDStore::SetForceKeepSessionState() { - backend_->SetForceKeepSessionState(); -} - -void SQLiteChannelIDStore::Flush() { - backend_->Flush(); -} - -SQLiteChannelIDStore::~SQLiteChannelIDStore() { - backend_->Close(); - // We release our reference to the Backend, though it will probably still have - // a reference if the background task runner has not run Close() yet. -} - -} // namespace net
diff --git a/net/extras/sqlite/sqlite_channel_id_store.h b/net/extras/sqlite/sqlite_channel_id_store.h deleted file mode 100644 index b0fd0b9..0000000 --- a/net/extras/sqlite/sqlite_channel_id_store.h +++ /dev/null
@@ -1,62 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef NET_EXTRAS_SQLITE_SQLITE_CHANNEL_ID_STORE_H_ -#define NET_EXTRAS_SQLITE_SQLITE_CHANNEL_ID_STORE_H_ - -#include <list> -#include <string> - -#include "base/callback_forward.h" -#include "base/compiler_specific.h" -#include "base/component_export.h" -#include "base/macros.h" -#include "base/memory/ref_counted.h" -#include "net/ssl/default_channel_id_store.h" - -namespace base { -class FilePath; -class SequencedTaskRunner; -} - -namespace net { - -// Implements the DefaultChannelIDStore::PersistentStore interface -// in terms of a SQLite database. For documentation about the actual member -// functions consult the documentation of the parent class -// DefaultChannelIDStore::PersistentCertStore. -class COMPONENT_EXPORT(NET_EXTRAS) SQLiteChannelIDStore - : public DefaultChannelIDStore::PersistentStore { - public: - // Create or open persistent store in file |path|. All I/O tasks are performed - // in background using |background_task_runner|. - SQLiteChannelIDStore( - const base::FilePath& path, - const scoped_refptr<base::SequencedTaskRunner>& background_task_runner); - - // DefaultChannelIDStore::PersistentStore: - void Load(const LoadedCallback& loaded_callback) override; - void AddChannelID( - const DefaultChannelIDStore::ChannelID& channel_id) override; - void DeleteChannelID( - const DefaultChannelIDStore::ChannelID& channel_id) override; - void SetForceKeepSessionState() override; - void Flush() override; - - // Delete channel ids from servers in |server_identifiers|. - void DeleteAllInList(const std::list<std::string>& server_identifiers); - - private: - ~SQLiteChannelIDStore() override; - - class Backend; - - scoped_refptr<Backend> backend_; - - DISALLOW_COPY_AND_ASSIGN(SQLiteChannelIDStore); -}; - -} // namespace net - -#endif // NET_EXTRAS_SQLITE_SQLITE_CHANNEL_ID_STORE_H_
diff --git a/net/extras/sqlite/sqlite_channel_id_store_unittest.cc b/net/extras/sqlite/sqlite_channel_id_store_unittest.cc deleted file mode 100644 index 7d2e245..0000000 --- a/net/extras/sqlite/sqlite_channel_id_store_unittest.cc +++ /dev/null
@@ -1,611 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "net/extras/sqlite/sqlite_channel_id_store.h" - -#include <memory> -#include <vector> - -#include "base/bind.h" -#include "base/files/file_util.h" -#include "base/files/scoped_temp_dir.h" -#include "base/memory/ref_counted.h" -#include "base/run_loop.h" -#include "base/strings/string_number_conversions.h" -#include "base/threading/thread_task_runner_handle.h" -#include "crypto/ec_private_key.h" -#include "net/ssl/channel_id_service.h" -#include "net/ssl/ssl_client_cert_type.h" -#include "net/test/cert_test_util.h" -#include "net/test/channel_id_test_util.h" -#include "net/test/test_data_directory.h" -#include "net/test/test_with_scoped_task_environment.h" -#include "sql/statement.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace net { - -const base::FilePath::CharType kTestChannelIDFilename[] = - FILE_PATH_LITERAL("ChannelID"); - -class SQLiteChannelIDStoreTest : public TestWithScopedTaskEnvironment { - public: - void Load(std::vector<std::unique_ptr<DefaultChannelIDStore::ChannelID>>* - channel_ids) { - base::RunLoop run_loop; - store_->Load(base::Bind(&SQLiteChannelIDStoreTest::OnLoaded, - base::Unretained(this), - &run_loop)); - run_loop.Run(); - channel_ids->swap(channel_ids_); - channel_ids_.clear(); - } - - void OnLoaded( - base::RunLoop* run_loop, - std::unique_ptr<std::vector< - std::unique_ptr<DefaultChannelIDStore::ChannelID>>> channel_ids) { - channel_ids_.swap(*channel_ids); - run_loop->Quit(); - } - - protected: - static void ReadLegacyTestKeyAndCert(std::string* key_data, - std::string* cert_data) { - base::FilePath key_path = - GetTestCertsDirectory().AppendASCII("unittest.originbound.key.der"); - base::FilePath cert_path = - GetTestCertsDirectory().AppendASCII("unittest.originbound.der"); - ASSERT_TRUE(base::ReadFileToString(key_path, key_data)); - ASSERT_TRUE(base::ReadFileToString(cert_path, cert_data)); - } - - static base::Time GetTestCertExpirationTime() { - // Cert expiration time from 'openssl asn1parse -inform der -in - // unittest.originbound.der': - // UTCTIME :160507022239Z - // base::Time::FromUTCExploded can't generate values past 2038 on 32-bit - // linux, so we use the raw value here. - base::Time::Exploded exploded_time; - exploded_time.year = 2016; - exploded_time.month = 5; - exploded_time.day_of_week = 0; // Unused. - exploded_time.day_of_month = 7; - exploded_time.hour = 2; - exploded_time.minute = 22; - exploded_time.second = 39; - exploded_time.millisecond = 0; - base::Time out_time; - EXPECT_TRUE(base::Time::FromUTCExploded(exploded_time, &out_time)); - return out_time; - } - - static base::Time GetTestCertCreationTime() { - // UTCTIME :150508022239Z - base::Time::Exploded exploded_time; - exploded_time.year = 2015; - exploded_time.month = 5; - exploded_time.day_of_week = 0; // Unused. - exploded_time.day_of_month = 8; - exploded_time.hour = 2; - exploded_time.minute = 22; - exploded_time.second = 39; - exploded_time.millisecond = 0; - base::Time out_time; - EXPECT_TRUE(base::Time::FromUTCExploded(exploded_time, &out_time)); - return out_time; - } - - void SetUp() override { - ASSERT_TRUE(temp_dir_.CreateUniqueTempDir()); - store_ = new SQLiteChannelIDStore( - temp_dir_.GetPath().Append(kTestChannelIDFilename), - base::ThreadTaskRunnerHandle::Get()); - std::vector<std::unique_ptr<DefaultChannelIDStore::ChannelID>> channel_ids; - Load(&channel_ids); - ASSERT_EQ(0u, channel_ids.size()); - // Make sure the store gets written at least once. - google_key_ = crypto::ECPrivateKey::Create(); - store_->AddChannelID(DefaultChannelIDStore::ChannelID( - "google.com", base::Time::FromInternalValue(1), google_key_->Copy())); - } - - base::ScopedTempDir temp_dir_; - scoped_refptr<SQLiteChannelIDStore> store_; - std::vector<std::unique_ptr<DefaultChannelIDStore::ChannelID>> channel_ids_; - std::unique_ptr<crypto::ECPrivateKey> google_key_; -}; - -// Test if data is stored as expected in the SQLite database. -TEST_F(SQLiteChannelIDStoreTest, TestPersistence) { - std::unique_ptr<crypto::ECPrivateKey> foo_key(crypto::ECPrivateKey::Create()); - store_->AddChannelID(DefaultChannelIDStore::ChannelID( - "foo.com", base::Time::FromInternalValue(3), foo_key->Copy())); - - std::vector<std::unique_ptr<DefaultChannelIDStore::ChannelID>> channel_ids; - // Replace the store effectively destroying the current one and forcing it - // to write its data to disk. Then we can see if after loading it again it - // is still there. - store_ = nullptr; - // Make sure we wait until the destructor has run. - base::RunLoop().RunUntilIdle(); - store_ = new SQLiteChannelIDStore( - temp_dir_.GetPath().Append(kTestChannelIDFilename), - base::ThreadTaskRunnerHandle::Get()); - - // Reload and test for persistence - Load(&channel_ids); - ASSERT_EQ(2U, channel_ids.size()); - DefaultChannelIDStore::ChannelID* goog_channel_id; - DefaultChannelIDStore::ChannelID* foo_channel_id; - if (channel_ids[0]->server_identifier() == "google.com") { - goog_channel_id = channel_ids[0].get(); - foo_channel_id = channel_ids[1].get(); - } else { - goog_channel_id = channel_ids[1].get(); - foo_channel_id = channel_ids[0].get(); - } - ASSERT_EQ("google.com", goog_channel_id->server_identifier()); - EXPECT_TRUE(KeysEqual(google_key_.get(), goog_channel_id->key())); - ASSERT_EQ(1, goog_channel_id->creation_time().ToInternalValue()); - ASSERT_EQ("foo.com", foo_channel_id->server_identifier()); - EXPECT_TRUE(KeysEqual(foo_key.get(), foo_channel_id->key())); - ASSERT_EQ(3, foo_channel_id->creation_time().ToInternalValue()); - - // Now delete the keypair and check persistence again. - store_->DeleteChannelID(*channel_ids[0]); - store_->DeleteChannelID(*channel_ids[1]); - store_ = nullptr; - // Make sure we wait until the destructor has run. - base::RunLoop().RunUntilIdle(); - channel_ids.clear(); - store_ = new SQLiteChannelIDStore( - temp_dir_.GetPath().Append(kTestChannelIDFilename), - base::ThreadTaskRunnerHandle::Get()); - - // Reload and check if the keypair has been removed. - Load(&channel_ids); - ASSERT_EQ(0U, channel_ids.size()); - // Close the store. - store_ = nullptr; - // Make sure we wait until the destructor has run. - base::RunLoop().RunUntilIdle(); -} - -// Test if data is stored as expected in the SQLite database. -TEST_F(SQLiteChannelIDStoreTest, TestDeleteAll) { - store_->AddChannelID(DefaultChannelIDStore::ChannelID( - "foo.com", base::Time::FromInternalValue(3), - crypto::ECPrivateKey::Create())); - - std::vector<std::unique_ptr<DefaultChannelIDStore::ChannelID>> channel_ids; - // Replace the store effectively destroying the current one and forcing it - // to write its data to disk. Then we can see if after loading it again it - // is still there. - store_ = nullptr; - // Make sure we wait until the destructor has run. - base::RunLoop().RunUntilIdle(); - store_ = new SQLiteChannelIDStore( - temp_dir_.GetPath().Append(kTestChannelIDFilename), - base::ThreadTaskRunnerHandle::Get()); - - // Reload and test for persistence - Load(&channel_ids); - ASSERT_EQ(2U, channel_ids.size()); - // DeleteAll except foo.com (shouldn't fail if one is missing either). - std::list<std::string> delete_server_identifiers; - delete_server_identifiers.push_back("google.com"); - delete_server_identifiers.push_back("missing.com"); - store_->DeleteAllInList(delete_server_identifiers); - - // Now check persistence again. - store_ = nullptr; - // Make sure we wait until the destructor has run. - base::RunLoop().RunUntilIdle(); - channel_ids.clear(); - store_ = new SQLiteChannelIDStore( - temp_dir_.GetPath().Append(kTestChannelIDFilename), - base::ThreadTaskRunnerHandle::Get()); - - // Reload and check that only foo.com persisted in store. - Load(&channel_ids); - ASSERT_EQ(1U, channel_ids.size()); - ASSERT_EQ("foo.com", channel_ids[0]->server_identifier()); - // Close the store. - store_ = nullptr; - // Make sure we wait until the destructor has run. - base::RunLoop().RunUntilIdle(); -} - -TEST_F(SQLiteChannelIDStoreTest, TestUpgradeV1) { - // Reset the store. We'll be using a different database for this test. - store_ = nullptr; - - base::FilePath v1_db_path(temp_dir_.GetPath().AppendASCII("v1db")); - - std::string key_data; - std::string cert_data; - ASSERT_NO_FATAL_FAILURE(ReadLegacyTestKeyAndCert(&key_data, &cert_data)); - - // Create a version 1 database. - { - sql::Database db; - ASSERT_TRUE(db.Open(v1_db_path)); - ASSERT_TRUE(db.Execute( - "CREATE TABLE meta(key LONGVARCHAR NOT NULL UNIQUE PRIMARY KEY," - "value LONGVARCHAR);" - "INSERT INTO \"meta\" VALUES('version','1');" - "INSERT INTO \"meta\" VALUES('last_compatible_version','1');" - "CREATE TABLE origin_bound_certs (" - "origin TEXT NOT NULL UNIQUE PRIMARY KEY," - "private_key BLOB NOT NULL,cert BLOB NOT NULL);")); - - sql::Statement add_smt(db.GetUniqueStatement( - "INSERT INTO origin_bound_certs (origin, private_key, cert) " - "VALUES (?,?,?)")); - add_smt.BindString(0, "google.com"); - add_smt.BindBlob(1, key_data.data(), key_data.size()); - add_smt.BindBlob(2, cert_data.data(), cert_data.size()); - ASSERT_TRUE(add_smt.Run()); - - ASSERT_TRUE(db.Execute( - "INSERT INTO \"origin_bound_certs\" VALUES(" - "'foo.com',X'AA',X'BB');")); - } - - // Load and test the DB contents twice. The first time checks that the - // migration ran properly; the second time ensures that the DB is still - // readable post-migration. - // - // Since the V1 format is unsupported, the second load will be reading an - // empty database. - for (int i = 0; i < 2; ++i) { - SCOPED_TRACE(i); - - std::vector<std::unique_ptr<DefaultChannelIDStore::ChannelID>> channel_ids; - store_ = new SQLiteChannelIDStore(v1_db_path, - base::ThreadTaskRunnerHandle::Get()); - - // Load the database. Because the existing v1 certs are implicitly of type - // RSA, which is unsupported, they're discarded. - Load(&channel_ids); - ASSERT_EQ(0U, channel_ids.size()); - - store_ = nullptr; - base::RunLoop().RunUntilIdle(); - - // Verify the database version is updated. - { - sql::Database db; - ASSERT_TRUE(db.Open(v1_db_path)); - sql::Statement smt(db.GetUniqueStatement( - "SELECT value FROM meta WHERE key = \"version\"")); - ASSERT_TRUE(smt.Step()); - EXPECT_EQ(6, smt.ColumnInt(0)); - EXPECT_FALSE(smt.Step()); - } - } -} - -TEST_F(SQLiteChannelIDStoreTest, TestUpgradeV2) { - // Reset the store. We'll be using a different database for this test. - store_ = nullptr; - - base::FilePath v2_db_path(temp_dir_.GetPath().AppendASCII("v2db")); - - std::string key_data; - std::string cert_data; - ASSERT_NO_FATAL_FAILURE(ReadLegacyTestKeyAndCert(&key_data, &cert_data)); - - // Create a version 2 database. - { - sql::Database db; - ASSERT_TRUE(db.Open(v2_db_path)); - ASSERT_TRUE(db.Execute( - "CREATE TABLE meta(key LONGVARCHAR NOT NULL UNIQUE PRIMARY KEY," - "value LONGVARCHAR);" - "INSERT INTO \"meta\" VALUES('version','2');" - "INSERT INTO \"meta\" VALUES('last_compatible_version','1');" - "CREATE TABLE origin_bound_certs (" - "origin TEXT NOT NULL UNIQUE PRIMARY KEY," - "private_key BLOB NOT NULL," - "cert BLOB NOT NULL," - "cert_type INTEGER);")); - - sql::Statement add_smt(db.GetUniqueStatement( - "INSERT INTO origin_bound_certs (origin, private_key, cert, cert_type) " - "VALUES (?,?,?,?)")); - add_smt.BindString(0, "google.com"); - add_smt.BindBlob(1, key_data.data(), key_data.size()); - add_smt.BindBlob(2, cert_data.data(), cert_data.size()); - add_smt.BindInt64(3, 64); - ASSERT_TRUE(add_smt.Run()); - - // Malformed certs will be ignored and not migrated. - ASSERT_TRUE(db.Execute( - "INSERT INTO \"origin_bound_certs\" VALUES(" - "'foo.com',X'AA',X'BB',64);")); - } - - // Load and test the DB contents twice. The first time checks that the - // migration ran properly; the second time ensures that the DB is still - // readable post-migration. - // - // Since the V2 format is unsupported, the second load will be reading an - // empty database. - for (int i = 0; i < 2; ++i) { - SCOPED_TRACE(i); - - std::vector<std::unique_ptr<DefaultChannelIDStore::ChannelID>> channel_ids; - store_ = new SQLiteChannelIDStore(v2_db_path, - base::ThreadTaskRunnerHandle::Get()); - - // Load the database. V2 cert keys are stored in a format that is - // unsupported, so they will be discarded. - Load(&channel_ids); - ASSERT_EQ(0U, channel_ids.size()); - - store_ = nullptr; - // Make sure we wait until the destructor has run. - base::RunLoop().RunUntilIdle(); - - // Verify the database version is updated. - { - sql::Database db; - ASSERT_TRUE(db.Open(v2_db_path)); - sql::Statement smt(db.GetUniqueStatement( - "SELECT value FROM meta WHERE key = \"version\"")); - ASSERT_TRUE(smt.Step()); - EXPECT_EQ(6, smt.ColumnInt(0)); - EXPECT_FALSE(smt.Step()); - } - } -} - -TEST_F(SQLiteChannelIDStoreTest, TestUpgradeV3) { - // Reset the store. We'll be using a different database for this test. - store_ = nullptr; - - base::FilePath v3_db_path(temp_dir_.GetPath().AppendASCII("v3db")); - - std::string key_data; - std::string cert_data; - ASSERT_NO_FATAL_FAILURE(ReadLegacyTestKeyAndCert(&key_data, &cert_data)); - - // Create a version 3 database. - { - sql::Database db; - ASSERT_TRUE(db.Open(v3_db_path)); - ASSERT_TRUE(db.Execute( - "CREATE TABLE meta(key LONGVARCHAR NOT NULL UNIQUE PRIMARY KEY," - "value LONGVARCHAR);" - "INSERT INTO \"meta\" VALUES('version','3');" - "INSERT INTO \"meta\" VALUES('last_compatible_version','1');" - "CREATE TABLE origin_bound_certs (" - "origin TEXT NOT NULL UNIQUE PRIMARY KEY," - "private_key BLOB NOT NULL," - "cert BLOB NOT NULL," - "cert_type INTEGER," - "expiration_time INTEGER);")); - - sql::Statement add_smt(db.GetUniqueStatement( - "INSERT INTO origin_bound_certs (origin, private_key, cert, cert_type, " - "expiration_time) VALUES (?,?,?,?,?)")); - add_smt.BindString(0, "google.com"); - add_smt.BindBlob(1, key_data.data(), key_data.size()); - add_smt.BindBlob(2, cert_data.data(), cert_data.size()); - add_smt.BindInt64(3, 64); - add_smt.BindInt64(4, 1000); - ASSERT_TRUE(add_smt.Run()); - - // Malformed certs will be ignored and not migrated. - ASSERT_TRUE(db.Execute( - "INSERT INTO \"origin_bound_certs\" VALUES(" - "'foo.com',X'AA',X'BB',64,2000);")); - } - - // Load and test the DB contents twice. The first time checks that the - // migration ran properly; the second time ensures that the DB is still - // readable post-migration. - // - // Since the V3 format is unsupported, the second load will be reading an - // empty database. - for (int i = 0; i < 2; ++i) { - SCOPED_TRACE(i); - - std::vector<std::unique_ptr<DefaultChannelIDStore::ChannelID>> channel_ids; - store_ = new SQLiteChannelIDStore(v3_db_path, - base::ThreadTaskRunnerHandle::Get()); - - // Load the database. V3 cert keys are in a format that is no longer - // supported, so they are discarded. - Load(&channel_ids); - ASSERT_EQ(0U, channel_ids.size()); - - store_ = nullptr; - // Make sure we wait until the destructor has run. - base::RunLoop().RunUntilIdle(); - - // Verify the database version is updated. - { - sql::Database db; - ASSERT_TRUE(db.Open(v3_db_path)); - sql::Statement smt(db.GetUniqueStatement( - "SELECT value FROM meta WHERE key = \"version\"")); - ASSERT_TRUE(smt.Step()); - EXPECT_EQ(6, smt.ColumnInt(0)); - EXPECT_FALSE(smt.Step()); - } - } -} - -TEST_F(SQLiteChannelIDStoreTest, TestUpgradeV4) { - // Reset the store. We'll be using a different database for this test. - store_ = nullptr; - - base::FilePath v4_db_path(temp_dir_.GetPath().AppendASCII("v4db")); - - std::string key_data; - std::string cert_data; - ASSERT_NO_FATAL_FAILURE(ReadLegacyTestKeyAndCert(&key_data, &cert_data)); - - // Create a version 4 database. - { - sql::Database db; - ASSERT_TRUE(db.Open(v4_db_path)); - ASSERT_TRUE(db.Execute( - "CREATE TABLE meta(key LONGVARCHAR NOT NULL UNIQUE PRIMARY KEY," - "value LONGVARCHAR);" - "INSERT INTO \"meta\" VALUES('version','4');" - "INSERT INTO \"meta\" VALUES('last_compatible_version','1');" - "CREATE TABLE origin_bound_certs (" - "origin TEXT NOT NULL UNIQUE PRIMARY KEY," - "private_key BLOB NOT NULL," - "cert BLOB NOT NULL," - "cert_type INTEGER," - "expiration_time INTEGER," - "creation_time INTEGER);")); - - sql::Statement add_smt(db.GetUniqueStatement( - "INSERT INTO origin_bound_certs (origin, private_key, cert, cert_type, " - "expiration_time, creation_time) VALUES (?,?,?,?,?,?)")); - add_smt.BindString(0, "google.com"); - add_smt.BindBlob(1, key_data.data(), key_data.size()); - add_smt.BindBlob(2, cert_data.data(), cert_data.size()); - add_smt.BindInt64(3, 64); - add_smt.BindInt64(4, 1000); - add_smt.BindInt64(5, GetTestCertCreationTime().ToInternalValue()); - ASSERT_TRUE(add_smt.Run()); - - // Add an RSA cert to the db. This cert should be ignored in the migration. - add_smt.Clear(); - add_smt.Assign(db.GetUniqueStatement( - "INSERT INTO origin_bound_certs " - "(origin, private_key, cert, cert_type, expiration_time, creation_time)" - " VALUES (?,?,?,?,?,?)")); - add_smt.BindString(0, "foo.com"); - add_smt.BindBlob(1, key_data.data(), key_data.size()); - add_smt.BindBlob(2, cert_data.data(), cert_data.size()); - add_smt.BindInt64(3, 1); - add_smt.BindInt64(4, GetTestCertExpirationTime().ToInternalValue()); - add_smt.BindInt64(5, base::Time::Now().ToInternalValue()); - ASSERT_TRUE(add_smt.Run()); - - // Malformed certs will be ignored and not migrated. - ASSERT_TRUE(db.Execute( - "INSERT INTO \"origin_bound_certs\" VALUES(" - "'bar.com',X'AA',X'BB',64,2000,3000);")); - } - - // Load and test the DB contents twice. The first time checks that the - // migration ran properly; the second time ensures that the DB is still - // readable post-migration. - // - // Since the V4 format is unsupported, the second load will be reading an - // empty database. - for (int i = 0; i < 2; ++i) { - SCOPED_TRACE(i); - - std::vector<std::unique_ptr<DefaultChannelIDStore::ChannelID>> channel_ids; - store_ = new SQLiteChannelIDStore(v4_db_path, - base::ThreadTaskRunnerHandle::Get()); - - // Load the database. V4 cert keys are in a format that is no longer - // supported, so they are discarded. - Load(&channel_ids); - ASSERT_EQ(0U, channel_ids.size()); - - store_ = nullptr; - // Make sure we wait until the destructor has run. - base::RunLoop().RunUntilIdle(); - - // Verify the database version is updated. - { - sql::Database db; - ASSERT_TRUE(db.Open(v4_db_path)); - sql::Statement smt(db.GetUniqueStatement( - "SELECT value FROM meta WHERE key = \"version\"")); - ASSERT_TRUE(smt.Step()); - EXPECT_EQ(6, smt.ColumnInt(0)); - EXPECT_FALSE(smt.Step()); - } - } -} - -TEST_F(SQLiteChannelIDStoreTest, TestUpgradeV5) { - // Reset the store. We'll be using a different database for this test. - store_ = nullptr; - - base::FilePath v5_db_path(temp_dir_.GetPath().AppendASCII("v5db")); - - std::string key_data; - std::string cert_data; - ASSERT_NO_FATAL_FAILURE(ReadLegacyTestKeyAndCert(&key_data, &cert_data)); - - // Create a version 5 database. - { - sql::Database db; - ASSERT_TRUE(db.Open(v5_db_path)); - ASSERT_TRUE(db.Execute( - "CREATE TABLE meta(key LONGVARCHAR NOT NULL UNIQUE PRIMARY KEY," - "value LONGVARCHAR);" - "INSERT INTO \"meta\" VALUES('version','5');" - "INSERT INTO \"meta\" VALUES('last_compatible_version','5');" - "CREATE TABLE channel_id (" - "host TEXT NOT NULL UNIQUE PRIMARY KEY," - "private_key BLOB NOT NULL," - "public_key BLOB NOT NULL," - "creation_time INTEGER);")); - - sql::Statement add_smt(db.GetUniqueStatement( - "INSERT INTO channel_id (host, private_key, public_key, creation_time) " - "VALUES (?,?,?,?)")); - add_smt.BindString(0, "google.com"); - add_smt.BindBlob(1, key_data.data(), key_data.size()); - add_smt.BindBlob(2, "", 0); - add_smt.BindInt64(3, GetTestCertCreationTime().ToInternalValue()); - ASSERT_TRUE(add_smt.Run()); - - // Malformed keys will be ignored and not migrated. - ASSERT_TRUE( - db.Execute("INSERT INTO \"channel_id\" VALUES(" - "'bar.com',X'AA',X'BB',3000);")); - } - - // Load and test the DB contents twice. The first time checks that the - // migration ran properly; the second time ensures that the DB is still - // readable post-migration. - // - // Since the V5 format is unsupported, the second load will be reading an - // empty database. - for (int i = 0; i < 2; ++i) { - SCOPED_TRACE(i); - - std::vector<std::unique_ptr<DefaultChannelIDStore::ChannelID>> channel_ids; - store_ = new SQLiteChannelIDStore(v5_db_path, - base::ThreadTaskRunnerHandle::Get()); - - // Load the database. V5 private keys are in a format that is no longer - // supported, so the keys get deleted in the migration. - Load(&channel_ids); - ASSERT_EQ(0U, channel_ids.size()); - - store_ = nullptr; - // Make sure we wait until the destructor has run. - base::RunLoop().RunUntilIdle(); - - // Verify the database version is updated. - { - sql::Database db; - ASSERT_TRUE(db.Open(v5_db_path)); - sql::Statement smt(db.GetUniqueStatement( - "SELECT value FROM meta WHERE key = \"version\"")); - ASSERT_TRUE(smt.Step()); - EXPECT_EQ(6, smt.ColumnInt(0)); - EXPECT_FALSE(smt.Step()); - } - } -} - -} // namespace net
diff --git a/net/http/http_network_session.cc b/net/http/http_network_session.cc index 3a0f61a..771dbf6 100644 --- a/net/http/http_network_session.cc +++ b/net/http/http_network_session.cc
@@ -146,7 +146,6 @@ quic_race_cert_verification(false), quic_estimate_initial_rtt(false), quic_headers_include_h2_stream_dependency(false), - enable_channel_id(false), http_09_on_non_default_ports_enabled(false), disable_idle_sockets_close_on_memory_pressure(false) { quic_supported_versions.push_back(quic::QUIC_VERSION_43); @@ -453,12 +452,6 @@ GetAlpnProtos(&server_config->alpn_protos); server_config->ignore_certificate_errors = params_.ignore_certificate_errors; *proxy_config = *server_config; - if (request.privacy_mode == PRIVACY_MODE_ENABLED) { - server_config->channel_id_enabled = false; - } else { - server_config->channel_id_enabled = params_.enable_channel_id; - proxy_config->channel_id_enabled = params_.enable_channel_id; - } } void HttpNetworkSession::DumpMemoryStats(
diff --git a/net/http/http_network_session.h b/net/http/http_network_session.h index 9fe908a..f677756 100644 --- a/net/http/http_network_session.h +++ b/net/http/http_network_session.h
@@ -231,9 +231,6 @@ // If non-empty, QUIC will only be spoken to hosts in this list. base::flat_set<std::string> quic_host_whitelist; - // Enable Channel ID. Channel ID is being deprecated. - bool enable_channel_id; - // Enable HTTP/0.9 for HTTP/HTTPS on ports other than the default one for // each protocol. bool http_09_on_non_default_ports_enabled;
diff --git a/net/http/http_network_transaction_ssl_unittest.cc b/net/http/http_network_transaction_ssl_unittest.cc index fa77814..bb4fc5d 100644 --- a/net/http/http_network_transaction_ssl_unittest.cc +++ b/net/http/http_network_transaction_ssl_unittest.cc
@@ -105,21 +105,4 @@ std::vector<std::unique_ptr<HttpRequestInfo>> request_info_vector_; }; -TEST_F(HttpNetworkTransactionSSLTest, ChannelID) { - ChannelIDService channel_id_service(new DefaultChannelIDStore(nullptr)); - session_context_.channel_id_service = &channel_id_service; - - HttpNetworkSession::Params params; - params.enable_channel_id = true; - HttpNetworkSession session(params, session_context_); - - HttpNetworkTransaction trans(DEFAULT_PRIORITY, &session); - TestCompletionCallback callback; - EXPECT_EQ(ERR_IO_PENDING, - trans.Start(GetRequestInfo("https://example.com"), - callback.callback(), NetLogWithSource())); - - EXPECT_TRUE(trans.server_ssl_config_.channel_id_enabled); -} - } // namespace net
diff --git a/net/http/http_network_transaction_unittest.cc b/net/http/http_network_transaction_unittest.cc index 1eee082..d2dd0f6c 100644 --- a/net/http/http_network_transaction_unittest.cc +++ b/net/http/http_network_transaction_unittest.cc
@@ -641,20 +641,20 @@ } #endif // defined(NTLM_PORTABLE) -template<typename ParentPool> -class CaptureGroupNameSocketPool : public ParentPool { +template <typename ParentPool> +class CaptureGroupIdSocketPool : public ParentPool { public: - CaptureGroupNameSocketPool(HostResolver* host_resolver, - CertVerifier* cert_verifier); + CaptureGroupIdSocketPool(HostResolver* host_resolver, + CertVerifier* cert_verifier); - const std::string last_group_name_received() const { - return last_group_name_; + const ClientSocketPool::GroupId& last_group_id_received() const { + return last_group_id_; } bool socket_requested() const { return socket_requested_; } int RequestSocket( - const std::string& group_name, + const ClientSocketPool::GroupId& group_id, const void* socket_params, RequestPriority priority, const SocketTag& socket_tag, @@ -663,36 +663,38 @@ CompletionOnceCallback callback, const ClientSocketPool::ProxyAuthCallback& proxy_auth_callback, const NetLogWithSource& net_log) override { - last_group_name_ = group_name; + last_group_id_ = group_id; socket_requested_ = true; return ERR_IO_PENDING; } - void CancelRequest(const std::string& group_name, + void CancelRequest(const ClientSocketPool::GroupId& group_id, ClientSocketHandle* handle) override {} - void ReleaseSocket(const std::string& group_name, + void ReleaseSocket(const ClientSocketPool::GroupId& group_id, std::unique_ptr<StreamSocket> socket, int id) override {} void CloseIdleSockets() override {} - void CloseIdleSocketsInGroup(const std::string& group_name) override {} + void CloseIdleSocketsInGroup( + const ClientSocketPool::GroupId& group_id) override {} int IdleSocketCount() const override { return 0; } - size_t IdleSocketCountInGroup(const std::string& group_name) const override { + size_t IdleSocketCountInGroup( + const ClientSocketPool::GroupId& group_id) const override { return 0; } - LoadState GetLoadState(const std::string& group_name, + LoadState GetLoadState(const ClientSocketPool::GroupId& group_id, const ClientSocketHandle* handle) const override { return LOAD_STATE_IDLE; } private: - std::string last_group_name_; + ClientSocketPool::GroupId last_group_id_; bool socket_requested_ = false; }; -typedef CaptureGroupNameSocketPool<TransportClientSocketPool> -CaptureGroupNameTransportSocketPool; +typedef CaptureGroupIdSocketPool<TransportClientSocketPool> + CaptureGroupIdTransportSocketPool; template <typename ParentPool> -CaptureGroupNameSocketPool<ParentPool>::CaptureGroupNameSocketPool( +CaptureGroupIdSocketPool<ParentPool>::CaptureGroupIdSocketPool( HostResolver* host_resolver, CertVerifier* /* cert_verifier */) : ParentPool(0, @@ -11204,16 +11206,16 @@ namespace { -// Tests that for connection endpoints the group names are correctly set. +// Tests that for connection endpoints the group ids are correctly set. -struct GroupNameTest { +struct GroupIdTest { std::string proxy_server; std::string url; - std::string expected_group_name; + ClientSocketPool::GroupId expected_group_id; bool ssl; }; -std::unique_ptr<HttpNetworkSession> SetupSessionForGroupNameTests( +std::unique_ptr<HttpNetworkSession> SetupSessionForGroupIdTests( SpdySessionDependencies* session_deps_) { std::unique_ptr<HttpNetworkSession> session(CreateSession(session_deps_)); @@ -11228,8 +11230,8 @@ return session; } -int GroupNameTransactionHelper(const std::string& url, - HttpNetworkSession* session) { +int GroupIdTransactionHelper(const std::string& url, + HttpNetworkSession* session) { HttpRequestInfo request; request.method = "GET"; request.url = GURL(url); @@ -11246,39 +11248,49 @@ } // namespace -TEST_F(HttpNetworkTransactionTest, GroupNameForDirectConnections) { - const GroupNameTest tests[] = { +TEST_F(HttpNetworkTransactionTest, GroupIdForDirectConnections) { + const GroupIdTest tests[] = { { - "", // unused - "http://www.example.org/direct", - "www.example.org:80", - false, + "", // unused + "http://www.example.org/direct", + ClientSocketPool::GroupId(HostPortPair("www.example.org", 80), + ClientSocketPool::SocketType::kHttp, + false /* privacy_mode */), + false, }, { - "", // unused - "http://[2001:1418:13:1::25]/direct", - "[2001:1418:13:1::25]:80", - false, + "", // unused + "http://[2001:1418:13:1::25]/direct", + ClientSocketPool::GroupId(HostPortPair("2001:1418:13:1::25", 80), + ClientSocketPool::SocketType::kHttp, + false /* privacy_mode */), + false, }, // SSL Tests { - "", // unused - "https://www.example.org/direct_ssl", - "ssl/www.example.org:443", - true, + "", // unused + "https://www.example.org/direct_ssl", + ClientSocketPool::GroupId(HostPortPair("www.example.org", 443), + ClientSocketPool::SocketType::kSsl, + false /* privacy_mode */), + true, }, { - "", // unused - "https://[2001:1418:13:1::25]/direct", - "ssl/[2001:1418:13:1::25]:443", - true, + "", // unused + "https://[2001:1418:13:1::25]/direct", + ClientSocketPool::GroupId(HostPortPair("2001:1418:13:1::25", 443), + ClientSocketPool::SocketType::kSsl, + false /* privacy_mode */), + true, }, { - "", // unused - "https://host.with.alternate/direct", - "ssl/host.with.alternate:443", - true, + "", // unused + "https://host.with.alternate/direct", + ClientSocketPool::GroupId(HostPortPair("host.with.alternate", 443), + ClientSocketPool::SocketType::kSsl, + false /* privacy_mode */), + true, }, }; @@ -11287,30 +11299,32 @@ ProxyResolutionService::CreateFixed(tests[i].proxy_server, TRAFFIC_ANNOTATION_FOR_TESTS); std::unique_ptr<HttpNetworkSession> session( - SetupSessionForGroupNameTests(&session_deps_)); + SetupSessionForGroupIdTests(&session_deps_)); HttpNetworkSessionPeer peer(session.get()); - CaptureGroupNameTransportSocketPool* transport_conn_pool = - new CaptureGroupNameTransportSocketPool(nullptr, nullptr); + CaptureGroupIdTransportSocketPool* transport_conn_pool = + new CaptureGroupIdTransportSocketPool(nullptr, nullptr); auto mock_pool_manager = std::make_unique<MockClientSocketPoolManager>(); mock_pool_manager->SetSocketPool(ProxyServer::Direct(), base::WrapUnique(transport_conn_pool)); peer.SetClientSocketPoolManager(std::move(mock_pool_manager)); EXPECT_EQ(ERR_IO_PENDING, - GroupNameTransactionHelper(tests[i].url, session.get())); - EXPECT_EQ(tests[i].expected_group_name, - transport_conn_pool->last_group_name_received()); + GroupIdTransactionHelper(tests[i].url, session.get())); + EXPECT_EQ(tests[i].expected_group_id, + transport_conn_pool->last_group_id_received()); EXPECT_TRUE(transport_conn_pool->socket_requested()); } } -TEST_F(HttpNetworkTransactionTest, GroupNameForHTTPProxyConnections) { - const GroupNameTest tests[] = { +TEST_F(HttpNetworkTransactionTest, GroupIdForHTTPProxyConnections) { + const GroupIdTest tests[] = { { "http_proxy", "http://www.example.org/http_proxy_normal", - "www.example.org:80", + ClientSocketPool::GroupId(HostPortPair("www.example.org", 80), + ClientSocketPool::SocketType::kHttp, + false /* privacy_mode */), false, }, @@ -11318,21 +11332,27 @@ { "http_proxy", "https://www.example.org/http_connect_ssl", - "ssl/www.example.org:443", + ClientSocketPool::GroupId(HostPortPair("www.example.org", 443), + ClientSocketPool::SocketType::kSsl, + false /* privacy_mode */), true, }, { "http_proxy", "https://host.with.alternate/direct", - "ssl/host.with.alternate:443", + ClientSocketPool::GroupId(HostPortPair("host.with.alternate", 443), + ClientSocketPool::SocketType::kSsl, + false /* privacy_mode */), true, }, { "http_proxy", "ftp://ftp.google.com/http_proxy_normal", - "ftp/ftp.google.com:21", + ClientSocketPool::GroupId(HostPortPair("ftp.google.com", 21), + ClientSocketPool::SocketType::kFtp, + false /* privacy_mode */), false, }, }; @@ -11342,38 +11362,42 @@ ProxyResolutionService::CreateFixed(tests[i].proxy_server, TRAFFIC_ANNOTATION_FOR_TESTS); std::unique_ptr<HttpNetworkSession> session( - SetupSessionForGroupNameTests(&session_deps_)); + SetupSessionForGroupIdTests(&session_deps_)); HttpNetworkSessionPeer peer(session.get()); ProxyServer proxy_server(ProxyServer::SCHEME_HTTP, HostPortPair("http_proxy", 80)); - CaptureGroupNameTransportSocketPool* http_proxy_pool = - new CaptureGroupNameTransportSocketPool(nullptr, nullptr); + CaptureGroupIdTransportSocketPool* http_proxy_pool = + new CaptureGroupIdTransportSocketPool(nullptr, nullptr); auto mock_pool_manager = std::make_unique<MockClientSocketPoolManager>(); mock_pool_manager->SetSocketPool(proxy_server, base::WrapUnique(http_proxy_pool)); peer.SetClientSocketPoolManager(std::move(mock_pool_manager)); EXPECT_EQ(ERR_IO_PENDING, - GroupNameTransactionHelper(tests[i].url, session.get())); - EXPECT_EQ(tests[i].expected_group_name, - http_proxy_pool->last_group_name_received()); + GroupIdTransactionHelper(tests[i].url, session.get())); + EXPECT_EQ(tests[i].expected_group_id, + http_proxy_pool->last_group_id_received()); } } -TEST_F(HttpNetworkTransactionTest, GroupNameForSOCKSConnections) { - const GroupNameTest tests[] = { +TEST_F(HttpNetworkTransactionTest, GroupIdForSOCKSConnections) { + const GroupIdTest tests[] = { { "socks4://socks_proxy:1080", "http://www.example.org/socks4_direct", - "www.example.org:80", + ClientSocketPool::GroupId(HostPortPair("www.example.org", 80), + ClientSocketPool::SocketType::kHttp, + false /* privacy_mode */), false, }, { "socks5://socks_proxy:1080", "http://www.example.org/socks5_direct", - "www.example.org:80", + ClientSocketPool::GroupId(HostPortPair("www.example.org", 80), + ClientSocketPool::SocketType::kHttp, + false /* privacy_mode */), false, }, @@ -11381,20 +11405,26 @@ { "socks4://socks_proxy:1080", "https://www.example.org/socks4_ssl", - "ssl/www.example.org:443", + ClientSocketPool::GroupId(HostPortPair("www.example.org", 443), + ClientSocketPool::SocketType::kSsl, + false /* privacy_mode */), true, }, { "socks5://socks_proxy:1080", "https://www.example.org/socks5_ssl", - "ssl/www.example.org:443", + ClientSocketPool::GroupId(HostPortPair("www.example.org", 443), + ClientSocketPool::SocketType::kSsl, + false /* privacy_mode */), true, }, { "socks4://socks_proxy:1080", "https://host.with.alternate/direct", - "ssl/host.with.alternate:443", + ClientSocketPool::GroupId(HostPortPair("host.with.alternate", 443), + ClientSocketPool::SocketType::kSsl, + false /* privacy_mode */), true, }, }; @@ -11404,15 +11434,15 @@ ProxyResolutionService::CreateFixed(tests[i].proxy_server, TRAFFIC_ANNOTATION_FOR_TESTS); std::unique_ptr<HttpNetworkSession> session( - SetupSessionForGroupNameTests(&session_deps_)); + SetupSessionForGroupIdTests(&session_deps_)); HttpNetworkSessionPeer peer(session.get()); ProxyServer proxy_server( ProxyServer::FromURI(tests[i].proxy_server, ProxyServer::SCHEME_HTTP)); ASSERT_TRUE(proxy_server.is_valid()); - CaptureGroupNameTransportSocketPool* socks_conn_pool = - new CaptureGroupNameTransportSocketPool(nullptr, nullptr); + CaptureGroupIdTransportSocketPool* socks_conn_pool = + new CaptureGroupIdTransportSocketPool(nullptr, nullptr); auto mock_pool_manager = std::make_unique<MockClientSocketPoolManager>(); mock_pool_manager->SetSocketPool(proxy_server, base::WrapUnique(socks_conn_pool)); @@ -11421,9 +11451,9 @@ HttpNetworkTransaction trans(DEFAULT_PRIORITY, session.get()); EXPECT_EQ(ERR_IO_PENDING, - GroupNameTransactionHelper(tests[i].url, session.get())); - EXPECT_EQ(tests[i].expected_group_name, - socks_conn_pool->last_group_name_received()); + GroupIdTransactionHelper(tests[i].url, session.get())); + EXPECT_EQ(tests[i].expected_group_id, + socks_conn_pool->last_group_id_received()); } } @@ -14503,7 +14533,9 @@ StaticSocketDataProvider data_provider(reads, writes); session_deps_.socket_factory->AddSocketDataProvider(&data_provider); - const char kSocketGroup[] = "www.example.com:80"; + const ClientSocketPool::GroupId kSocketGroup( + HostPortPair("www.example.com", 80), ClientSocketPool::SocketType::kHttp, + false /* privacy_mode */); // First round of authentication. auth_handler->SetGenerateExpectation(false, OK);
diff --git a/net/http/http_proxy_client_socket_pool_unittest.cc b/net/http/http_proxy_client_socket_pool_unittest.cc index 1dd5a709..0c19f533 100644 --- a/net/http/http_proxy_client_socket_pool_unittest.cc +++ b/net/http/http_proxy_client_socket_pool_unittest.cc
@@ -147,28 +147,24 @@ // Returns the a correctly constructed HttpProxyParms // for the HTTP or HTTPS proxy. - scoped_refptr<TransportClientSocketPool::SocketParams> CreateParams( - bool tunnel) { + scoped_refptr<TransportClientSocketPool::SocketParams> CreateTunnelParams() { return TransportClientSocketPool::SocketParams:: CreateFromHttpProxySocketParams( base::MakeRefCounted<HttpProxySocketParams>( CreateHttpProxyParams(), CreateHttpsProxyParams(), quic::QUIC_VERSION_UNSUPPORTED, - HostPortPair("www.google.com", tunnel ? 443 : 80), + HostPortPair("www.google.com", 443), session_->http_auth_cache(), session_->http_auth_handler_factory(), session_->spdy_session_pool(), session_->quic_stream_factory(), - /*is_trusted_proxy=*/false, tunnel, + /*is_trusted_proxy=*/false, /*tunnel=*/true, TRAFFIC_ANNOTATION_FOR_TESTS)); } - scoped_refptr<TransportClientSocketPool::SocketParams> CreateTunnelParams() { - return CreateParams(true); - } - - scoped_refptr<TransportClientSocketPool::SocketParams> - CreateNoTunnelParams() { - return CreateParams(false); + static ClientSocketPool::GroupId group_id() { + return ClientSocketPool::GroupId(HostPortPair("www.google.com", 443), + ClientSocketPool::SocketType::kHttp, + false /* privacy_mode */); } MockTaggingClientSocketFactory* socket_factory() { return &socket_factory_; } @@ -243,7 +239,7 @@ socket_factory()->AddSSLSocketDataProvider(ssl_data_.get()); int rv = handle_.Init( - "a", CreateTunnelParams(), LOW, SocketTag(), + group_id(), CreateTunnelParams(), LOW, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, callback_.callback(), ClientSocketPool::ProxyAuthCallback(), pool_.get(), NetLogWithSource()); EXPECT_THAT(rv, IsError(ERR_IO_PENDING)); @@ -304,7 +300,7 @@ AddAuthToCache(); int rv = handle_.Init( - "a", CreateTunnelParams(), LOW, SocketTag(), + group_id(), CreateTunnelParams(), LOW, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, callback_.callback(), ClientSocketPool::ProxyAuthCallback(), pool_.get(), NetLogWithSource()); EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
diff --git a/net/http/http_response_headers.cc b/net/http/http_response_headers.cc index 670935c..6e7e753 100644 --- a/net/http/http_response_headers.cc +++ b/net/http/http_response_headers.cc
@@ -71,15 +71,11 @@ "clear-site-data", }; -// By default, do not cache Strict-Transport-Security or Public-Key-Pins. -// This avoids erroneously re-processing them on page loads from cache --- -// they are defined to be valid only on live and error-free HTTPS -// connections. -// TODO(https://crbug.com/893055): remove Public-Key-Pins from non-cachable -// headers? +// By default, do not cache Strict-Transport-Security. +// This avoids erroneously re-processing it on page loads from cache --- +// it is defined to be valid only on live and error-free HTTPS connections. const char* const kSecurityStateHeaders[] = { "strict-transport-security", - "public-key-pins" }; // These response headers are not copied from a 304/206 response to the cached
diff --git a/net/http/http_response_headers_unittest.cc b/net/http/http_response_headers_unittest.cc index 690a8f9a..f24fc6b1 100644 --- a/net/http/http_response_headers_unittest.cc +++ b/net/http/http_response_headers_unittest.cc
@@ -486,10 +486,7 @@ {HttpResponseHeaders::PERSIST_SANS_SECURITY_STATE, "HTTP/1.1 200 OK\n" "Strict-Transport-Security: max-age=1576800\n" - "Bar: 1\n" - "Public-Key-Pins: max-age=100000; " - "pin-sha256=\"1111111111111111111111111111111111111111111=\";" - "pin-sha256=\"2222222222222222222222222222222222222222222=\"", + "Bar: 1\n", "HTTP/1.1 200 OK\n" "Bar: 1\n"},
diff --git a/net/http/http_stream_factory_job.cc b/net/http/http_stream_factory_job.cc index 6e50a0a1..8bb8444 100644 --- a/net/http/http_stream_factory_job.cc +++ b/net/http/http_stream_factory_job.cc
@@ -1272,10 +1272,6 @@ // handshake; renegotiation on the proxy connection is unsupported. ssl_config->false_start_enabled = false; } - - // Disable Channel ID if privacy mode is enabled. - if (request_info_.privacy_mode == PRIVACY_MODE_ENABLED) - ssl_config->channel_id_enabled = false; } int HttpStreamFactory::Job::ReconsiderProxyAfterError(int error) {
diff --git a/net/http/http_stream_factory_unittest.cc b/net/http/http_stream_factory_unittest.cc index 32ca644f..3c6cb2e 100644 --- a/net/http/http_stream_factory_unittest.cc +++ b/net/http/http_stream_factory_unittest.cc
@@ -385,10 +385,15 @@ PreconnectHelperForURL(test.num_streams, url, session); } -std::string GetGroupName(const TestCase& test) { - if (test.ssl) - return "ssl/www.google.com:443"; - return "www.google.com:80"; +ClientSocketPool::GroupId GetGroupId(const TestCase& test) { + if (test.ssl) { + return ClientSocketPool::GroupId(HostPortPair("www.google.com", 443), + ClientSocketPool::SocketType::kSsl, + false /* privacy_mode */); + } + return ClientSocketPool::GroupId(HostPortPair("www.google.com", 80), + ClientSocketPool::SocketType::kHttp, + false /* privacy_mode */); } template <typename ParentPool> @@ -401,16 +406,22 @@ CTPolicyEnforcer* ct_policy_enforcer); int last_num_streams() const { return last_num_streams_; } - const std::string& last_group_name() const { return last_group_name_; } + const ClientSocketPool::GroupId& last_group_id() const { + return last_group_id_; + } - // Resets |last_num_streams_| and |last_group_name_| default values. + // Resets |last_num_streams_| and |last_group_id_| default values. void reset() { last_num_streams_ = -1; - last_group_name_.clear(); + // Group ID that shouldn't match much. + last_group_id_ = ClientSocketPool::GroupId( + HostPortPair(), + ClientSocketPool::SocketType::kSslVersionInterferenceProbe, + true /* privacy_mode */); } int RequestSocket( - const std::string& group_name, + const ClientSocketPool::GroupId& group_id, const void* socket_params, RequestPriority priority, const SocketTag& socket_tag, @@ -423,19 +434,19 @@ return ERR_UNEXPECTED; } - void RequestSockets(const std::string& group_name, + void RequestSockets(const ClientSocketPool::GroupId& group_id, const void* socket_params, int num_sockets, const NetLogWithSource& net_log) override { last_num_streams_ = num_sockets; - last_group_name_ = group_name; + last_group_id_ = group_id; } - void CancelRequest(const std::string& group_name, + void CancelRequest(const ClientSocketPool::GroupId& group_id, ClientSocketHandle* handle) override { ADD_FAILURE(); } - void ReleaseSocket(const std::string& group_name, + void ReleaseSocket(const ClientSocketPool::GroupId& group_id, std::unique_ptr<StreamSocket> socket, int id) override { ADD_FAILURE(); @@ -445,11 +456,12 @@ ADD_FAILURE(); return 0; } - size_t IdleSocketCountInGroup(const std::string& group_name) const override { + size_t IdleSocketCountInGroup( + const ClientSocketPool::GroupId& group_id) const override { ADD_FAILURE(); return 0; } - LoadState GetLoadState(const std::string& group_name, + LoadState GetLoadState(const ClientSocketPool::GroupId& group_id, const ClientSocketHandle* handle) const override { ADD_FAILURE(); return LOAD_STATE_IDLE; @@ -457,7 +469,7 @@ private: int last_num_streams_; - std::string last_group_name_; + ClientSocketPool::GroupId last_group_id_; }; typedef CapturePreconnectsSocketPool<TransportClientSocketPool> @@ -515,7 +527,7 @@ peer.SetClientSocketPoolManager(std::move(mock_pool_manager)); PreconnectHelper(kTests[i], session.get()); EXPECT_EQ(kTests[i].num_streams, transport_conn_pool->last_num_streams()); - EXPECT_EQ(GetGroupName(kTests[i]), transport_conn_pool->last_group_name()); + EXPECT_EQ(GetGroupId(kTests[i]), transport_conn_pool->last_group_id()); } } @@ -540,7 +552,7 @@ peer.SetClientSocketPoolManager(std::move(mock_pool_manager)); PreconnectHelper(kTests[i], session.get()); EXPECT_EQ(kTests[i].num_streams, http_proxy_pool->last_num_streams()); - EXPECT_EQ(GetGroupName(kTests[i]), http_proxy_pool->last_group_name()); + EXPECT_EQ(GetGroupId(kTests[i]), http_proxy_pool->last_group_id()); } } @@ -565,7 +577,7 @@ peer.SetClientSocketPoolManager(std::move(mock_pool_manager)); PreconnectHelper(kTests[i], session.get()); EXPECT_EQ(kTests[i].num_streams, socks_proxy_pool->last_num_streams()); - EXPECT_EQ(GetGroupName(kTests[i]), socks_proxy_pool->last_group_name()); + EXPECT_EQ(GetGroupId(kTests[i]), socks_proxy_pool->last_group_id()); } } @@ -1357,51 +1369,6 @@ namespace { -TEST_F(HttpStreamFactoryTest, PrivacyModeDisablesChannelId) { - SpdySessionDependencies session_deps(ProxyResolutionService::CreateDirect()); - - StaticSocketDataProvider socket_data; - socket_data.set_connect_data(MockConnect(ASYNC, OK)); - session_deps.socket_factory->AddSocketDataProvider(&socket_data); - - SSLSocketDataProvider ssl(ASYNC, OK); - session_deps.socket_factory->AddSSLSocketDataProvider(&ssl); - - std::unique_ptr<HttpNetworkSession> session( - SpdySessionDependencies::SpdyCreateSession(&session_deps)); - - // Set an existing SpdySession in the pool. - HostPortPair host_port_pair("www.google.com", 443); - SpdySessionKey key(host_port_pair, ProxyServer::Direct(), - PRIVACY_MODE_ENABLED, - SpdySessionKey::IsProxySession::kFalse, SocketTag()); - - HttpRequestInfo request_info; - request_info.method = "GET"; - request_info.url = GURL("https://www.google.com"); - request_info.load_flags = 0; - request_info.privacy_mode = PRIVACY_MODE_DISABLED; - request_info.traffic_annotation = - MutableNetworkTrafficAnnotationTag(TRAFFIC_ANNOTATION_FOR_TESTS); - - SSLConfig ssl_config; - StreamRequestWaiter waiter; - std::unique_ptr<HttpStreamRequest> request( - session->http_stream_factory()->RequestStream( - request_info, DEFAULT_PRIORITY, ssl_config, ssl_config, &waiter, - /* enable_ip_based_pooling = */ true, - /* enable_alternative_services = */ true, NetLogWithSource())); - waiter.WaitForStream(); - - // The stream shouldn't come from spdy as we are using different privacy mode - EXPECT_FALSE(request->using_spdy()); - - SSLConfig used_ssl_config = waiter.used_ssl_config(); - EXPECT_EQ(used_ssl_config.channel_id_enabled, ssl_config.channel_id_enabled); -} - -namespace { - // Return count of distinct groups in given socket pool. int GetSocketPoolGroupCount(ClientSocketPool* pool) { int count = 0; @@ -1446,8 +1413,6 @@ } #endif -} // namespace - TEST_F(HttpStreamFactoryTest, PrivacyModeUsesDifferentSocketPoolGroup) { SpdySessionDependencies session_deps(ProxyResolutionService::CreateDirect()); @@ -2084,9 +2049,11 @@ scoped_refptr<SSLSocketParams> ssl_params( new SSLSocketParams(transport_params, nullptr, nullptr, host_port_pair, ssl_config, PRIVACY_MODE_DISABLED)); - std::string group_name = "ssl/" + host_port_pair.ToString(); + ClientSocketPool::GroupId group_id(host_port_pair, + ClientSocketPool::SocketType::kSsl, + false /* privacy_mode */); int rv = connection->Init( - group_name, + group_id, TransportClientSocketPool::SocketParams::CreateFromSSLSocketParams( ssl_params), MEDIUM, SocketTag(), ClientSocketPool::RespectLimits::ENABLED,
diff --git a/net/http/mock_http_cache.cc b/net/http/mock_http_cache.cc index 6880ae4..7a0fba1 100644 --- a/net/http/mock_http_cache.cc +++ b/net/http/mock_http_cache.cc
@@ -404,7 +404,8 @@ //----------------------------------------------------------------------------- MockDiskCache::MockDiskCache() - : open_count_(0), + : Backend(DISK_CACHE), + open_count_(0), create_count_(0), doomed_count_(0), max_file_size_(std::numeric_limits<int>::max()), @@ -422,10 +423,6 @@ ReleaseAll(); } -CacheType MockDiskCache::GetCacheType() const { - return DISK_CACHE; -} - int32_t MockDiskCache::GetEntryCount() const { return static_cast<int32_t>(entries_.size()); }
diff --git a/net/http/mock_http_cache.h b/net/http/mock_http_cache.h index c4d026d..f4fa2e7 100644 --- a/net/http/mock_http_cache.h +++ b/net/http/mock_http_cache.h
@@ -151,7 +151,6 @@ MockDiskCache(); ~MockDiskCache() override; - CacheType GetCacheType() const override; int32_t GetEntryCount() const override; net::Error OpenOrCreateEntry(const std::string& key, net::RequestPriority request_priority,
diff --git a/net/http/transport_security_state_static.json b/net/http/transport_security_state_static.json index 0fd80a2..1feb128 100644 --- a/net/http/transport_security_state_static.json +++ b/net/http/transport_security_state_static.json
@@ -10201,7 +10201,6 @@ { "name": "nirada.info", "policy": "bulk-18-weeks", "mode": "force-https", "include_subdomains": true }, { "name": "nixien.fr", "policy": "bulk-18-weeks", "mode": "force-https", "include_subdomains": true }, { "name": "nl-ix.net", "policy": "bulk-18-weeks", "mode": "force-https", "include_subdomains": true }, - { "name": "nlegall.fr", "policy": "bulk-18-weeks", "mode": "force-https", "include_subdomains": true }, { "name": "nmsnj.com", "policy": "bulk-18-weeks", "mode": "force-https", "include_subdomains": true }, { "name": "nnqc.nl", "policy": "bulk-18-weeks", "mode": "force-https", "include_subdomains": true }, { "name": "no17sifangjie.cc", "policy": "bulk-18-weeks", "mode": "force-https", "include_subdomains": true }, @@ -12142,7 +12141,6 @@ { "name": "timcamara.com", "policy": "bulk-18-weeks", "mode": "force-https", "include_subdomains": true }, { "name": "theramo.re", "policy": "bulk-18-weeks", "mode": "force-https", "include_subdomains": true }, { "name": "tfcoms-sp-tracker-client.azurewebsites.net", "policy": "bulk-18-weeks", "mode": "force-https", "include_subdomains": true }, - { "name": "tech-clips.com", "policy": "bulk-18-weeks", "mode": "force-https", "include_subdomains": true }, { "name": "thephonecaseplace.com", "policy": "bulk-18-weeks", "mode": "force-https", "include_subdomains": true }, { "name": "tilikum.io", "policy": "bulk-18-weeks", "mode": "force-https", "include_subdomains": true }, { "name": "thisisacompletetest.ga", "policy": "bulk-18-weeks", "mode": "force-https", "include_subdomains": true }, @@ -12201,7 +12199,6 @@ { "name": "uniq.site", "policy": "bulk-18-weeks", "mode": "force-https", "include_subdomains": true }, { "name": "ungegamere.dk", "policy": "bulk-18-weeks", "mode": "force-https", "include_subdomains": true }, { "name": "utopiagalaxy.space", "policy": "bulk-18-weeks", "mode": "force-https", "include_subdomains": true }, - { "name": "usabackground.com", "policy": "bulk-18-weeks", "mode": "force-https", "include_subdomains": true }, { "name": "uslab.io", "policy": "bulk-18-weeks", "mode": "force-https", "include_subdomains": true }, { "name": "utopianrealms.org", "policy": "bulk-18-weeks", "mode": "force-https", "include_subdomains": true }, { "name": "upldr.pw", "policy": "bulk-18-weeks", "mode": "force-https", "include_subdomains": true }, @@ -18062,7 +18059,6 @@ { "name": "ascgathering.com", "policy": "bulk-18-weeks", "mode": "force-https", "include_subdomains": true }, { "name": "24sihu.com", "policy": "bulk-18-weeks", "mode": "force-https", "include_subdomains": true }, { "name": "axg.io", "policy": "bulk-18-weeks", "mode": "force-https", "include_subdomains": true }, - { "name": "38sihu.com", "policy": "bulk-18-weeks", "mode": "force-https", "include_subdomains": true }, { "name": "architectdirect.nl", "policy": "bulk-18-weeks", "mode": "force-https", "include_subdomains": true }, { "name": "arkaic.dyndns.org", "policy": "bulk-18-weeks", "mode": "force-https", "include_subdomains": true }, { "name": "astrea-voetbal-groningen.nl", "policy": "bulk-18-weeks", "mode": "force-https", "include_subdomains": true }, @@ -19238,9 +19234,7 @@ { "name": "mhjuma.com", "policy": "bulk-18-weeks", "mode": "force-https", "include_subdomains": true }, { "name": "martiestrimsalon.nl", "policy": "bulk-18-weeks", "mode": "force-https", "include_subdomains": true }, { "name": "marbinvest.com", "policy": "bulk-18-weeks", "mode": "force-https", "include_subdomains": true }, - { "name": "maestrano.com", "policy": "bulk-18-weeks", "mode": "force-https", "include_subdomains": true }, { "name": "mcga.media", "policy": "bulk-18-weeks", "mode": "force-https", "include_subdomains": true }, - { "name": "metalsculpture.co.uk", "policy": "bulk-18-weeks", "mode": "force-https", "include_subdomains": true }, { "name": "markuskeppeler.no-ip.biz", "policy": "bulk-18-weeks", "mode": "force-https", "include_subdomains": true }, { "name": "mclist.it", "policy": "bulk-18-weeks", "mode": "force-https", "include_subdomains": true }, { "name": "maxhoechtl.at", "policy": "bulk-18-weeks", "mode": "force-https", "include_subdomains": true }, @@ -22137,7 +22131,6 @@ { "name": "planktonholland.com", "policy": "bulk-18-weeks", "mode": "force-https", "include_subdomains": true }, { "name": "premiership-predictors.co.uk", "policy": "bulk-18-weeks", "mode": "force-https", "include_subdomains": true }, { "name": "pikeitservices.com.au", "policy": "bulk-18-weeks", "mode": "force-https", "include_subdomains": true }, - { "name": "pottshome.co.uk", "policy": "bulk-18-weeks", "mode": "force-https", "include_subdomains": true }, { "name": "philia-sa.com", "policy": "bulk-18-weeks", "mode": "force-https", "include_subdomains": true }, { "name": "proxybay.eu.org", "policy": "bulk-18-weeks", "mode": "force-https", "include_subdomains": true }, { "name": "projectte.ch", "policy": "bulk-18-weeks", "mode": "force-https", "include_subdomains": true }, @@ -23784,7 +23777,6 @@ { "name": "schmitt-max.com", "policy": "bulk-18-weeks", "mode": "force-https", "include_subdomains": true }, { "name": "schreinerei-wortmann.de", "policy": "bulk-18-weeks", "mode": "force-https", "include_subdomains": true }, { "name": "schroeder-immobilien-sundern.de", "policy": "bulk-18-weeks", "mode": "force-https", "include_subdomains": true }, - { "name": "schum.world", "policy": "bulk-18-weeks", "mode": "force-https", "include_subdomains": true }, { "name": "schwetz.net", "policy": "bulk-18-weeks", "mode": "force-https", "include_subdomains": true }, { "name": "scitopia.me", "policy": "bulk-18-weeks", "mode": "force-https", "include_subdomains": true }, { "name": "score-savers.com", "policy": "bulk-18-weeks", "mode": "force-https", "include_subdomains": true }, @@ -27893,7 +27885,6 @@ { "name": "wowinvasion.com", "policy": "bulk-18-weeks", "mode": "force-https", "include_subdomains": true }, { "name": "wp-rescue.com.au", "policy": "bulk-18-weeks", "mode": "force-https", "include_subdomains": true }, { "name": "wp-stack.pro", "policy": "bulk-18-weeks", "mode": "force-https", "include_subdomains": true }, - { "name": "wpinter.com", "policy": "bulk-18-weeks", "mode": "force-https", "include_subdomains": true }, { "name": "wptotal.com", "policy": "bulk-18-weeks", "mode": "force-https", "include_subdomains": true }, { "name": "wrc-results.com", "policy": "bulk-18-weeks", "mode": "force-https", "include_subdomains": true }, { "name": "wrfu.co.nz", "policy": "bulk-18-weeks", "mode": "force-https", "include_subdomains": true }, @@ -29743,7 +29734,6 @@ { "name": "improklinikken.dk", "policy": "bulk-18-weeks", "mode": "force-https", "include_subdomains": true }, { "name": "jaion.ml", "policy": "bulk-18-weeks", "mode": "force-https", "include_subdomains": true }, { "name": "italianshoemanufacturers.com", "policy": "bulk-18-weeks", "mode": "force-https", "include_subdomains": true }, - { "name": "jobtestprep.nl", "policy": "bulk-18-weeks", "mode": "force-https", "include_subdomains": true }, { "name": "jeffreymagee.com", "policy": "bulk-18-weeks", "mode": "force-https", "include_subdomains": true }, { "name": "jenprace.cz", "policy": "bulk-18-weeks", "mode": "force-https", "include_subdomains": true }, { "name": "jmarciniak.it", "policy": "bulk-18-weeks", "mode": "force-https", "include_subdomains": true }, @@ -29804,7 +29794,6 @@ { "name": "je-vends.fr", "policy": "bulk-18-weeks", "mode": "force-https", "include_subdomains": true }, { "name": "jsevilleja.org", "policy": "bulk-18-weeks", "mode": "force-https", "include_subdomains": true }, { "name": "keb.com.au", "policy": "bulk-18-weeks", "mode": "force-https", "include_subdomains": true }, - { "name": "jobtestprep.se", "policy": "bulk-18-weeks", "mode": "force-https", "include_subdomains": true }, { "name": "k1cp.com", "policy": "bulk-18-weeks", "mode": "force-https", "include_subdomains": true }, { "name": "jonathanmassacand.ch", "policy": "bulk-18-weeks", "mode": "force-https", "include_subdomains": true }, { "name": "hostfuture.co.in", "policy": "bulk-18-weeks", "mode": "force-https", "include_subdomains": true }, @@ -29825,7 +29814,6 @@ { "name": "kevinpirnie.com", "policy": "bulk-18-weeks", "mode": "force-https", "include_subdomains": true }, { "name": "kazy111.info", "policy": "bulk-18-weeks", "mode": "force-https", "include_subdomains": true }, { "name": "jstelecom.com.br", "policy": "bulk-18-weeks", "mode": "force-https", "include_subdomains": true }, - { "name": "jobtestprep.de", "policy": "bulk-18-weeks", "mode": "force-https", "include_subdomains": true }, { "name": "kevinmorssink.nl", "policy": "bulk-18-weeks", "mode": "force-https", "include_subdomains": true }, { "name": "kedibizworx.com", "policy": "bulk-18-weeks", "mode": "force-https", "include_subdomains": true }, { "name": "kenalsworld.com", "policy": "bulk-18-weeks", "mode": "force-https", "include_subdomains": true }, @@ -30145,7 +30133,6 @@ { "name": "mcgovernance.com", "policy": "bulk-18-weeks", "mode": "force-https", "include_subdomains": true }, { "name": "mcmillanskiclub.com.au", "policy": "bulk-18-weeks", "mode": "force-https", "include_subdomains": true }, { "name": "matthijssen.info", "policy": "bulk-18-weeks", "mode": "force-https", "include_subdomains": true }, - { "name": "mariogeckler.de", "policy": "bulk-18-weeks", "mode": "force-https", "include_subdomains": true }, { "name": "ma-plancha.ch", "policy": "bulk-18-weeks", "mode": "force-https", "include_subdomains": true }, { "name": "me-dc.com", "policy": "bulk-18-weeks", "mode": "force-https", "include_subdomains": true }, { "name": "memfrob.org", "policy": "bulk-18-weeks", "mode": "force-https", "include_subdomains": true }, @@ -31085,7 +31072,6 @@ { "name": "skylgenet.nl", "policy": "bulk-18-weeks", "mode": "force-https", "include_subdomains": true }, { "name": "smartwritingservice.com", "policy": "bulk-18-weeks", "mode": "force-https", "include_subdomains": true }, { "name": "skatingchina.com", "policy": "bulk-18-weeks", "mode": "force-https", "include_subdomains": true }, - { "name": "smol.cat", "policy": "bulk-18-weeks", "mode": "force-https", "include_subdomains": true }, { "name": "smallshopit.com", "policy": "bulk-18-weeks", "mode": "force-https", "include_subdomains": true }, { "name": "smiledirectsales.com", "policy": "bulk-18-weeks", "mode": "force-https", "include_subdomains": true }, { "name": "singee.site", "policy": "bulk-18-weeks", "mode": "force-https", "include_subdomains": true }, @@ -32757,7 +32743,6 @@ { "name": "heverhagen.rocks", "policy": "bulk-18-weeks", "mode": "force-https", "include_subdomains": true }, { "name": "horkel.cf", "policy": "bulk-18-weeks", "mode": "force-https", "include_subdomains": true }, { "name": "hfu.io", "policy": "bulk-18-weeks", "mode": "force-https", "include_subdomains": true }, - { "name": "hiyuki2578.net", "policy": "bulk-18-weeks", "mode": "force-https", "include_subdomains": true }, { "name": "hbkonsult.com", "policy": "bulk-18-weeks", "mode": "force-https", "include_subdomains": true }, { "name": "hukaloh.com", "policy": "bulk-18-weeks", "mode": "force-https", "include_subdomains": true }, { "name": "https.ps", "policy": "bulk-18-weeks", "mode": "force-https", "include_subdomains": true }, @@ -32878,7 +32863,6 @@ { "name": "jumbopan.net", "policy": "bulk-18-weeks", "mode": "force-https", "include_subdomains": true }, { "name": "jarniashop.se", "policy": "bulk-18-weeks", "mode": "force-https", "include_subdomains": true }, { "name": "jzbk.org", "policy": "bulk-18-weeks", "mode": "force-https", "include_subdomains": true }, - { "name": "jobtestprep.dk", "policy": "bulk-18-weeks", "mode": "force-https", "include_subdomains": true }, { "name": "jermann.biz", "policy": "bulk-18-weeks", "mode": "force-https", "include_subdomains": true }, { "name": "jumbopan.com", "policy": "bulk-18-weeks", "mode": "force-https", "include_subdomains": true }, { "name": "isidom.fr", "policy": "bulk-18-weeks", "mode": "force-https", "include_subdomains": true }, @@ -36338,7 +36322,6 @@ { "name": "jmsolodesigns.com", "policy": "bulk-18-weeks", "mode": "force-https", "include_subdomains": true }, { "name": "jmssg.jp", "policy": "bulk-18-weeks", "mode": "force-https", "include_subdomains": true }, { "name": "jobs-in-tech.com", "policy": "bulk-18-weeks", "mode": "force-https", "include_subdomains": true }, - { "name": "jobtestprep.fr", "policy": "bulk-18-weeks", "mode": "force-https", "include_subdomains": true }, { "name": "jobtestprep.it", "policy": "bulk-18-weeks", "mode": "force-https", "include_subdomains": true }, { "name": "jobzninja.com", "policy": "bulk-18-weeks", "mode": "force-https", "include_subdomains": true }, { "name": "joe262.com", "policy": "bulk-18-weeks", "mode": "force-https", "include_subdomains": true }, @@ -41946,7 +41929,6 @@ { "name": "clazzrooms.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, { "name": "cleansewellness.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, { "name": "clearbreezesecuritydoors.com.au", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, - { "name": "clicksaveandprint.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, { "name": "clinicminds.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, { "name": "clnc.to", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, { "name": "clorophilla.net", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, @@ -47171,7 +47153,6 @@ { "name": "highlightsfootball.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, { "name": "highspeedinternet.my", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, { "name": "hillcountryoralsurgery.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, - { "name": "hiring-process.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, { "name": "hlidacnajemneho.cz", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, { "name": "hollowpoint.xyz", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, { "name": "holstphoto.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, @@ -50112,7 +50093,6 @@ { "name": "iftarsaati.org", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, { "name": "ignacjanskiednimlodziezy.pl", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, { "name": "illumed.net", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, - { "name": "immo-agentur.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, { "name": "import-shopping.de", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, { "name": "imwnk.cn", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, { "name": "instant-thinking.de", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, @@ -53410,7 +53390,6 @@ { "name": "serwis-wroclaw.pl", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, { "name": "shanyhs.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, { "name": "shmunky.co.uk", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, - { "name": "shop.fr", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, { "name": "shreyansh26.me", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, { "name": "shuletime.ml", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, { "name": "simplepress.uk", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, @@ -57673,7 +57652,6 @@ { "name": "dailyrover.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, { "name": "dance-colleges.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, { "name": "dangr.zone", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, - { "name": "danielnaaman.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, { "name": "danzac.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, { "name": "dapps.earth", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, { "name": "darkwebnews.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, @@ -62349,7 +62327,6 @@ { "name": "djlinux.cz", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, { "name": "dontbeevil.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, { "name": "draadloze-noodstop.nl", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, - { "name": "dreamstream.mobi", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, { "name": "drhoseyni.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, { "name": "drmyco.net", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, { "name": "dstat.cc", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, @@ -67724,7 +67701,6 @@ { "name": "sun1378.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, { "name": "sun668.asia", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, { "name": "sun668.co", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, - { "name": "sunbingchen.cn", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, { "name": "suncity288.net", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, { "name": "suncity8118.cn", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, { "name": "suncity8118.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, @@ -67737,7 +67713,6 @@ { "name": "suncity8668.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, { "name": "suncity8998.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, { "name": "surfpacific.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, - { "name": "suzaku.xyz", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, { "name": "swc-cfc.gc.ca", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, { "name": "swingtimeinthegardens.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, { "name": "swissmadesecurity.net", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, @@ -68552,6 +68527,428 @@ { "name": "zdenekvecera.cz", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, { "name": "zhanglizhi.ml", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, { "name": "zhanglu.xyz", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "07stars.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "089818.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "131ks.net", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "162231.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "186kb.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "2468lhc.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "258877.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "267661.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "311186.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "351113.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "382225.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "4u.am", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "54.sb", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "592227.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "599980.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "6z0.cn", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "716227.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "716331.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "7pb.ru", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "911.gov", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "933325.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "a1autotransport.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "aattrans.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "adaptiveicons.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "agks5.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "airtec-france.fr", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "alan.moe", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "alexanderrans.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "alldolledupstore.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "alle-zonvakanties.nl", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "altrui.st", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "altweaver.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "americanwater.lk", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "an7hrax.se", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "anakin.ca", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "angelcloudworld.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "anitaxcph.dk", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "anjocerdena.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "antifilter.network", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "arnove.net", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "aschismatic.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "atmind.nl", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "attentigroup.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "attiremr.tk", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "autorijschooljohanbos.nl", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "available.direct", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "badgr.io", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "bakerviewdentalcentre.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "banka.space", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "barcelonabagels.cat", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "bavarianhiker.de", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "benstevinson.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "bestbrokerindia.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "blobemoji.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "blobs.gg", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "blueskydigitalstrategy.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "bonus.net.nz", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "bottinquebec.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "bouldercolorado.gov", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "bowtie.com.hk", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "branno.org", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "bufla.net", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "burkhardt.at", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "bvbmedia.nl", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "bwanglab.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "c-ma-copro.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "c00ke.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "c8ms113.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "calidadelectronica.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "cannabiscare.ca", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "caraccio.li", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "carlosjeurissen.nl", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "carmelglenane.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "castelannenberg.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "cellsheet.me", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "centralheating.hu", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "channelsurf.tv", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "checkpoint.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "chiledogphoto.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "christineblachford.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "clemens-bartz.de", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "clemensbartz.de", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "clite.ru", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "clubmarina.store", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "codemahrt.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "colantonio.homelinux.net", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "colectivos.org", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "commercia.srl", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "communitychurchafrica.co.za", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "companion-web.net", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "conference-expert.eu", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "coolvibe.org", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "copyshrug.ca", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "coupestanley.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "craft-me-in.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "crain.com.au", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "critterguard.org", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "cuminas.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "cuminas.jp", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "cursed.im", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "cwinfo.net", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "cyber-wolfs.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "d4b.in.ua", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "datvexehue.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "decayshop.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "deped.io", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "detao.org", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "determapp.de", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "dhelixnet.de", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "dhemant.de", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "die-pleners.de", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "direct.cz", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "directscripts.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "distraction.gov", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "dmoj.ca", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "dreamdestine.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "drgerthplasticsurgery.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "drjobs.com.au", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "dsgvo-addon.eu", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "e-beyond.de", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "e-labo.works", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "eblog.com.au", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "ebuyclub.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "ecoder.co", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "edapt.org.uk", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "ehdud8451.gq", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "eidelpes.info", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "ekre.club", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "emprendeperuano.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "energija-visiems.lt", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "enlyft.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "eropics.org", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "eurocertificazione.it", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "euroman.ga", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "eventosbgp.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "evote-ch.ch", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "evyn.eu", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "excel-mechanical.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "exchangers.top", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "fashion.bg", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "feiya.ng", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "feldbogenclub-hamburg.de", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "flexve.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "floodsmart.gov", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "floristmou.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "forever.cat", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "forthetoys.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "founderio.net", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "fuzenet.net", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "gabrielgn.com.br", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "gamejobs.co", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "garazskapuszereles.hu", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "geekbundle.org", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "geomac.gov", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "germanmasterpainters.nz", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "gervais-avocat.fr", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "geteventbox.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "gladdy.co.uk", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "gladdy.uk", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "gladdymedia.co.uk", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "gladdymedia.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "gladdymedia.uk", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "gocphongthuy.net", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "googleshortcuts.org", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "goso.ga", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "gummientchen.net", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "hangerphant.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "hangw.xyz", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "haskett.ca", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "healingourskin.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "heaven.moe", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "hellomedian.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "hengroenet.de", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "herealways.tk", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "hiimodel.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "hildebrand.group", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "hilden.ws", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "hopo.design", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "hotel-schiller.de", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "hspinc.ca", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "hywlovexyc.info", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "idar-oberstein.de", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "idatalabs.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "ifttl.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "ikymbo.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "infinipharm.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "infonote.ca", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "instagram.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "intrack.net.au", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "investinghacker.com.au", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "iowen.cn", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "j-softlab.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "jakubsindelar.cz", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "jarmatys.pl", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "jblackweb.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "jecjacshop.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "jeffpenchoff.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "jeurissen.co", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "joebobbriggs.net", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "jokequebec.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "jolo.software", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "jonssheds.direct", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "juozasveza.lt", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "kaizenjuku.org", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "kamilmagdziak.pl", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "katsunet.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "kb6767.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "kb786.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "kb88dc28.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "keypointfrancine.nl", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "kimkuhlmanphoto.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "kizzedbykelz.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "kolitel.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "kollegamenti.it", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "kowabit.de", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "kromax.it", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "krommo.pe", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "kulopo.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "kutip.id", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "labanote.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "lecannabis.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "legendcatz.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "lissauer.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "lmdexpresstransport.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "logical-invest.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "logtywardrobe.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "lorenz-hundler.co", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "loto-tele.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "makefoodrecipes.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "manipurmatka.net", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "manuall.cz", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "manuall.dk", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "manuall.es", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "manuall.fi", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "manuall.jp", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "manuall.kr", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "manuall.no", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "manuall.pl", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "manuall.pt", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "marandu.com.ar", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "marinershousecalstock.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "markiewicz.online", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "massagecoolangatta.com.au", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "matchmadeinstubton.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "mayhutmuibep.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "mediciventures.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "medtip.de", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "meilleurstrucs.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "mein-gehalt.at", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "mgdigitalmarketing.com.au", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "mgvideo.com.au", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "miaololi.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "midart.ro", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "midweb.ro", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "miku.ro", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "millionen-von-sonnen.de", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "mirazperu.tk", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "misini.fr", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "mjsacco-dwi.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "mpu-beratungsstellen.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "mtinz.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "mundoperfecto.net", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "mysteryshow.site", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "nakluky.cz", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "nalenders.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "namu.news", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "naplata.mk", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "nebl.cash", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "netz0.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "nostalgimidi.se", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "nudes.ovh", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "nwmd.nl", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "oceanofapk.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "oneminutetomindfulness.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "opture.ch", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "oswaldlabs.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "otprema.hr", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "outstack.vote", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "owddm.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "pacch.io", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "panascais.at", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "panascais.ch", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "panascais.cz", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "panascais.es", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "panascais.fi", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "panascais.fr", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "panascais.info", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "panascais.network", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "panascais.nl", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "panascais.org", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "panascais.pl", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "panascais.pt", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "panascais.ru", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "panascais.zone", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "passporttrails.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "patrick-omland.de", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "pepegym.cz", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "periodex.co", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "personalitymax.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "pirateproxy.id", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "playsprout.industries", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "pmbsteelbuildings.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "pocketpasta.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "pollev.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "port5060.net", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "postsubmeta.net", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "premiermortgageservices.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "prosafilosofica.com.br", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "proxybay.ist", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "prtscloud.ddns.net", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "pseek.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "pulizia.milano.it", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "pushpanel.io", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "pwoss.xyz", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "pyroballpcbs.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "q4profiles-france.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "quafe.tech", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "quebec.casa", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "quotedtale.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "racing-planet.cz", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "rakett.org", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "randallbollig.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "rannamoisaaiasalong.ee", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "redphi.dedyn.io", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "renoovodesign.ltd", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "replenology.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "retireearlyandtravel.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "reupo.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "richcat.tw", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "richecommecresus.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "rk.mk", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "robertcrain.com.au", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "rocket-resume.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "ruralsoba.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "ryois.me", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "rzegocki.pl", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "s-gong.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "s1-llc.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "sanovnikat.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "savanna.io", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "sbivc.jp", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "scouting-wageningen.nl", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "scungioborst.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "securitydriver.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "senjukannonreiki.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "serrature.roma.it", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "shuomingshu88.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "sjorsvanweert.nl", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "sobeelectronics.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "sshd.site", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "ssmic.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "stadtundbaum.de", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "startstunter.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "statistician-online.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "stoicatedy.ovh", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "sudya-dredd.ru", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "svenskapsalmer.se", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "synackrst.net", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "syncmindglobal.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "tabernastudios.pe", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "takenbydrone.com.au", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "talendipank.ee", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "tarkov-database.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "team-io.net", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "techlovers.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "tencent.xn--vuq861b", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "thaicurry.net", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "thebabypassport.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "theinnerprism.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "theoptechnation.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "thethreadofhope.org", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "ticketcity.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "timelimit.io", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "tomwellington.design", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "topmmogames.org", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "totalsport-bg.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "travelinghacker.com.au", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "tsunami.gov", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "tyroremotes.pt", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "u17go.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "ukuchordnamer.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "ukutabs.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "umartina.eu", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "unblocked.krd", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "uno.uk", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "usacitygames.org", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "vaganciatechnology.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "vamosbets.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "vanwa.ch", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "vertigo-rec.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "viantours.net", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "vizionnetwork.co.uk", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "vkikaku.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "vorbrodt.blog", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "vrifox.cc", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "vygeja.lt", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "wearepapermill.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "website-traffic.shop", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "wgdp.gov", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "whatsthisword.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "whoit.top", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "wir-machen-druck.de", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "with.de", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "woodminstermanagement.tk", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "worksmarter.tv", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "wp-france.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "wpdivitheme.nl", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "wpnuvem.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "wwc.ren", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "xilo.net", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "yanservices.be", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "yellowsquid.co.uk", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "yicipick.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "yolocamgirls.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "yourconscious.life", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "yrx.me", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "yt668899.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "yuweiji.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "zerosector.io", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "ziwa.ir", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "zlotonews.com", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, + { "name": "zselicivt.hu", "policy": "bulk-1-year", "mode": "force-https", "include_subdomains": true }, // END OF 1-YEAR BULK HSTS ENTRIES // Only eTLD+1 domains can be submitted automatically to hstspreload.org,
diff --git a/net/log/net_log_event_type_list.h b/net/log/net_log_event_type_list.h index 0688dd0..7c519f8 100644 --- a/net/log/net_log_event_type_list.h +++ b/net/log/net_log_event_type_list.h
@@ -714,12 +714,6 @@ // ------------------------------------------------------------------------ // The start/end of a ConnectJob. -// -// The BEGIN phase has these parameters: -// -// { -// "group_name": <The group name for the socket request.>, -// } EVENT_TYPE(CONNECT_JOB) // This event is logged whenever the ConnectJob gets a new socket @@ -775,14 +769,14 @@ // This event simply describes the host:port that were requested from the // socket pool. Its parameters are: // { -// "group_name": <The group name for the socket request>, +// "group_id": <The group id for the socket request>, // } EVENT_TYPE(TCP_CLIENT_SOCKET_POOL_REQUESTED_SOCKET) // This event simply describes the host:port that were requested from the // socket pool. Its parameters are: // { -// "group_name": <The group name for the socket request>, +// "group_id": <The group id for the socket request>, // } EVENT_TYPE(TCP_CLIENT_SOCKET_POOL_REQUESTED_SOCKETS) @@ -790,7 +784,7 @@ // { // "backup_job": <Whether this is a backup job created because the other // ConnectJob was taking too long>, -// "group_name": <The group name for the socket request>, +// "group_id": <The group id for the socket request>, // } EVENT_TYPE(SOCKET_POOL_CONNECT_JOB_CREATED)
diff --git a/net/quic/quic_chromium_client_session_test.cc b/net/quic/quic_chromium_client_session_test.cc index 93fbefe..11b6c09f 100644 --- a/net/quic/quic_chromium_client_session_test.cc +++ b/net/quic/quic_chromium_client_session_test.cc
@@ -761,7 +761,7 @@ TEST_P(QuicChromiumClientSessionTest, ConnectionCloseBeforeHandshakeConfirmed) { // Force the connection close packet to use long headers with connection ID. - server_maker_.SetEncryptionLevel(quic::ENCRYPTION_NONE); + server_maker_.SetEncryptionLevel(quic::ENCRYPTION_INITIAL); MockQuicData quic_data; quic_data.AddRead(ASYNC, ERR_IO_PENDING);
diff --git a/net/quic/quic_flags_list.h b/net/quic/quic_flags_list.h index 07f36a3..4d563fe 100644 --- a/net/quic/quic_flags_list.h +++ b/net/quic/quic_flags_list.h
@@ -304,3 +304,8 @@ // In QUIC, do not close connection if received an in-order ACK with decreased // largest_acked. QUIC_FLAG(bool, FLAGS_quic_reloadable_flag_quic_tolerate_reneging, false) + +QUIC_FLAG( + bool, + FLAGS_quic_reloadable_flag_quic_validate_packet_number_post_decryption, + false)
diff --git a/net/quic/quic_test_packet_maker.cc b/net/quic/quic_test_packet_maker.cc index ab7dffa3..7c3e6dd 100644 --- a/net/quic/quic_test_packet_maker.cc +++ b/net/quic/quic_test_packet_maker.cc
@@ -102,7 +102,7 @@ payloads, true, encryption_level_); } size_t encrypted_size = framer.EncryptInPlace( - quic::ENCRYPTION_NONE, header.packet_number, + quic::ENCRYPTION_INITIAL, header.packet_number, GetStartOfEncryptedData(framer.transport_version(), header), length, quic::kDefaultMaxPacketSize, buffer); EXPECT_EQ(quic::kDefaultMaxPacketSize, encrypted_size); @@ -138,7 +138,7 @@ std::unique_ptr<quic::QuicReceivedPacket> QuicTestPacketMaker::MakeDummyCHLOPacket(uint64_t packet_num) { - SetEncryptionLevel(quic::ENCRYPTION_NONE); + SetEncryptionLevel(quic::ENCRYPTION_INITIAL); InitializeHeader(packet_num, /*include_version=*/true); quic::CryptoHandshakeMessage message = @@ -156,8 +156,8 @@ frames.push_back(quic::QuicFrame(frame)); } else { crypto_frame = - quic::QuicCryptoFrame(quic::ENCRYPTION_NONE, 0, data.length()); - producer.SaveCryptoData(quic::ENCRYPTION_NONE, 0, data.AsStringPiece()); + quic::QuicCryptoFrame(quic::ENCRYPTION_INITIAL, 0, data.length()); + producer.SaveCryptoData(quic::ENCRYPTION_INITIAL, 0, data.AsStringPiece()); frames.push_back(quic::QuicFrame(&crypto_frame)); producer_p = &producer; } @@ -703,7 +703,7 @@ quic::test::BuildUnsizedDataPacket(&framer, header, frames)); char buffer[quic::kMaxPacketSize]; size_t encrypted_size = - framer.EncryptPayload(quic::ENCRYPTION_NONE, header.packet_number, + framer.EncryptPayload(quic::ENCRYPTION_INITIAL, header.packet_number, *packet, buffer, quic::kMaxPacketSize); EXPECT_NE(0u, encrypted_size); quic::QuicReceivedPacket encrypted(buffer, encrypted_size, clock_->Now(), @@ -1200,7 +1200,7 @@ &framer, header, frames, max_plaintext_size)); char buffer[quic::kMaxPacketSize]; size_t encrypted_size = - framer.EncryptPayload(quic::ENCRYPTION_NONE, header.packet_number, + framer.EncryptPayload(quic::ENCRYPTION_INITIAL, header.packet_number, *packet, buffer, quic::kMaxPacketSize); EXPECT_NE(0u, encrypted_size); quic::QuicReceivedPacket encrypted(buffer, encrypted_size, clock_->Now(), @@ -1346,7 +1346,7 @@ void QuicTestPacketMaker::SetEncryptionLevel(quic::EncryptionLevel level) { encryption_level_ = level; switch (level) { - case quic::ENCRYPTION_NONE: + case quic::ENCRYPTION_INITIAL: long_header_type_ = quic::INITIAL; break; case quic::ENCRYPTION_ZERO_RTT:
diff --git a/net/socket/client_socket_handle.cc b/net/socket/client_socket_handle.cc index cd9f6f2f..8ac7932 100644 --- a/net/socket/client_socket_handle.cc +++ b/net/socket/client_socket_handle.cc
@@ -37,7 +37,7 @@ } if (pool_) - pool_->SetPriority(group_name_, this, priority); + pool_->SetPriority(group_id_, this, priority); } void ClientSocketHandle::Reset() { @@ -47,7 +47,7 @@ void ClientSocketHandle::ResetInternal(bool cancel) { // Was Init called? - if (!group_name_.empty()) { + if (!group_id_.destination().IsEmpty()) { // If so, we must have a pool. CHECK(pool_); if (is_initialized()) { @@ -55,7 +55,7 @@ socket_->NetLog().EndEvent(NetLogEventType::SOCKET_IN_USE); // Release the socket back to the ClientSocketPool so it can be // deleted or reused. - pool_->ReleaseSocket(group_name_, std::move(socket_), pool_id_); + pool_->ReleaseSocket(group_id_, std::move(socket_), pool_id_); } else { // If the handle has been initialized, we should still have a // socket. @@ -64,12 +64,12 @@ } else if (cancel) { // If we did not get initialized yet and we have a socket // request pending, cancel it. - pool_->CancelRequest(group_name_, this); + pool_->CancelRequest(group_id_, this); } } is_initialized_ = false; socket_.reset(); - group_name_.clear(); + group_id_ = ClientSocketPool::GroupId(); reuse_type_ = ClientSocketHandle::UNUSED; callback_.Reset(); if (higher_pool_) @@ -94,12 +94,12 @@ LoadState ClientSocketHandle::GetLoadState() const { CHECK(!is_initialized()); - CHECK(!group_name_.empty()); + CHECK(!group_id_.destination().IsEmpty()); // Because of http://crbug.com/37810 we may not have a pool, but have // just a raw socket. if (!pool_) return LOAD_STATE_IDLE; - return pool_->GetLoadState(group_name_, this); + return pool_->GetLoadState(group_id_, this); } bool ClientSocketHandle::IsPoolStalled() const { @@ -132,7 +132,7 @@ void ClientSocketHandle::CloseIdleSocketsInGroup() { if (pool_) - pool_->CloseIdleSocketsInGroup(group_name_); + pool_->CloseIdleSocketsInGroup(group_id_); } bool ClientSocketHandle::GetLoadTimingInfo(
diff --git a/net/socket/client_socket_handle.h b/net/socket/client_socket_handle.h index 13eb2001..a4ddea6 100644 --- a/net/socket/client_socket_handle.h +++ b/net/socket/client_socket_handle.h
@@ -33,7 +33,7 @@ // A container for a StreamSocket. // -// The handle's |group_name| uniquely identifies the origin and type of the +// The handle's |group_id| uniquely identifies the origin and type of the // connection. It is used by the ClientSocketPool to group similar connected // client socket objects. // @@ -80,7 +80,7 @@ // Profiling information for the request is saved to |net_log| if non-NULL. // template <typename PoolType> - int Init(const std::string& group_name, + int Init(const ClientSocketPool::GroupId& group_id, const scoped_refptr<typename PoolType::SocketParams>& socket_params, RequestPriority priority, const SocketTag& socket_tag, @@ -94,7 +94,7 @@ // ClientSocketPool::RespectLimits. // TODO(mmenke): Remove once the socket pool refactor is complete. template <typename PoolType> - int Init(const std::string& group_name, + int Init(const std::string& group_id, const scoped_refptr<typename PoolType::SocketParams>& socket_params, RequestPriority priority, const SocketTag& socket_tag, @@ -103,7 +103,7 @@ const ClientSocketPool::ProxyAuthCallback& proxy_auth_callback, PoolType* pool, const NetLogWithSource& net_log) { - return Init(group_name, socket_params, priority, socket_tag, + return Init(group_id, socket_params, priority, socket_tag, respect_limits ? ClientSocketPool::RespectLimits::ENABLED : ClientSocketPool::RespectLimits::DISABLED, std::move(callback), proxy_auth_callback, pool, net_log); @@ -207,7 +207,7 @@ std::unique_ptr<StreamSocket> PassSocket(); // These may only be used if is_initialized() is true. - const std::string& group_name() const { return group_name_; } + const ClientSocketPool::GroupId& group_id() const { return group_id_; } int id() const { return pool_id_; } bool is_reused() const { return reuse_type_ == REUSED_IDLE; } base::TimeDelta idle_time() const { return idle_time_; } @@ -239,7 +239,7 @@ ClientSocketPool* pool_; HigherLayeredPool* higher_pool_; std::unique_ptr<StreamSocket> socket_; - std::string group_name_; + ClientSocketPool::GroupId group_id_; SocketReuseType reuse_type_; CompletionOnceCallback callback_; base::TimeDelta idle_time_; @@ -260,7 +260,7 @@ // Template function implementation: template <typename PoolType> int ClientSocketHandle::Init( - const std::string& group_name, + const ClientSocketPool::GroupId& group_id, const scoped_refptr<typename PoolType::SocketParams>& socket_params, RequestPriority priority, const SocketTag& socket_tag, @@ -271,15 +271,15 @@ const NetLogWithSource& net_log) { requesting_source_ = net_log.source(); - CHECK(!group_name.empty()); + CHECK(!group_id.destination().IsEmpty()); ResetInternal(true); ResetErrorState(); pool_ = pool; - group_name_ = group_name; + group_id_ = group_id; CompletionOnceCallback io_complete_callback = base::BindOnce(&ClientSocketHandle::OnIOComplete, base::Unretained(this)); int rv = pool_->RequestSocket( - group_name, &socket_params, priority, socket_tag, respect_limits, this, + group_id, &socket_params, priority, socket_tag, respect_limits, this, std::move(io_complete_callback), proxy_auth_callback, net_log); if (rv == ERR_IO_PENDING) { callback_ = std::move(callback);
diff --git a/net/socket/client_socket_pool.cc b/net/socket/client_socket_pool.cc index f68929d..7a7a8f5 100644 --- a/net/socket/client_socket_pool.cc +++ b/net/socket/client_socket_pool.cc
@@ -4,7 +4,10 @@ #include "net/socket/client_socket_pool.h" +#include <utility> + #include "base/logging.h" +#include "net/socket/stream_socket.h" namespace { @@ -15,6 +18,49 @@ namespace net { +ClientSocketPool::GroupId::GroupId() + : socket_type_(SocketType::kHttp), privacy_mode_(false) {} + +ClientSocketPool::GroupId::GroupId(const HostPortPair& destination, + SocketType socket_type, + bool privacy_mode) + : destination_(destination), + socket_type_(socket_type), + privacy_mode_(privacy_mode) {} + +ClientSocketPool::GroupId::GroupId(const GroupId& group_id) = default; + +ClientSocketPool::GroupId::~GroupId() = default; + +ClientSocketPool::GroupId& ClientSocketPool::GroupId::operator=( + const GroupId& group_id) = default; + +ClientSocketPool::GroupId& ClientSocketPool::GroupId::operator=( + GroupId&& group_id) = default; + +std::string ClientSocketPool::GroupId::ToString() const { + std::string result = destination_.ToString(); + switch (socket_type_) { + case ClientSocketPool::SocketType::kHttp: + break; + + case ClientSocketPool::SocketType::kSsl: + result = "ssl/" + result; + break; + + case ClientSocketPool::SocketType::kSslVersionInterferenceProbe: + result = "version-interference-probe/ssl/" + result; + break; + + case ClientSocketPool::SocketType::kFtp: + result = "ftp/" + result; + break; + } + if (privacy_mode_) + result = "pm/" + result; + return result; +} + // static base::TimeDelta ClientSocketPool::used_idle_socket_timeout() { return base::TimeDelta::FromSeconds(g_used_idle_socket_timeout_s);
diff --git a/net/socket/client_socket_pool.h b/net/socket/client_socket_pool.h index b824628..b138011 100644 --- a/net/socket/client_socket_pool.h +++ b/net/socket/client_socket_pool.h
@@ -83,7 +83,67 @@ base::OnceClosure restart_with_auth_callback)> ProxyAuthCallback; - // Requests a connected socket for a group_name. + enum class SocketType { + kHttp, + + // This is a connection that uses an SSL connection to the final + // destination, though not necessarily to the proxy, if there is one. + kSsl, + + // This is a connection for probing for SSL-breaking interference. + kSslVersionInterferenceProbe, + + // This is a connection through an HTTP proxy being used for FTP requests. + kFtp, + }; + + // Group ID for a socket request. Requests with the same group ID are + // considered indistinguishable. + class NET_EXPORT GroupId { + public: + GroupId(); + GroupId(const HostPortPair& destination, + SocketType socket_type, + bool privacy_mode); + GroupId(const GroupId& group_id); + + ~GroupId(); + + GroupId& operator=(const GroupId& group_id); + GroupId& operator=(GroupId&& group_id); + + const HostPortPair& destination() const { return destination_; } + + SocketType socket_type() const { return socket_type_; } + + bool privacy_mode() const { return privacy_mode_; } + + // Returns the group ID as a string, for logging. + std::string ToString() const; + + bool operator==(const GroupId& other) const { + return std::tie(destination_, socket_type_, privacy_mode_) == + std::tie(other.destination_, other.socket_type_, + other.privacy_mode_); + } + + bool operator<(const GroupId& other) const { + return std::tie(destination_, socket_type_, privacy_mode_) < + std::tie(other.destination_, other.socket_type_, + other.privacy_mode_); + } + + private: + // The host and port of the final destination (not the proxy). + HostPortPair destination_; + + SocketType socket_type_; + + // True if this request is for a privacy mode / uncredentials connection. + bool privacy_mode_; + }; + + // Requests a connected socket with a specified GroupId. // // There are five possible results from calling this function: // 1) RequestSocket returns OK and initializes |handle| with a reused socket. @@ -119,7 +179,7 @@ // challenge is seen while establishing a tunnel. It will never be invoked // synchronously when RequestSocket is called, and will be invoked once for // each challenge seen. - virtual int RequestSocket(const std::string& group_name, + virtual int RequestSocket(const GroupId& group_id, const void* params, RequestPriority priority, const SocketTag& socket_tag, @@ -130,7 +190,7 @@ const NetLogWithSource& net_log) = 0; // RequestSockets is used to request that |num_sockets| be connected in the - // connection group for |group_name|. If the connection group already has + // connection group for |group_id|. If the connection group already has // |num_sockets| idle sockets / active sockets / currently connecting sockets, // then this function doesn't do anything. Otherwise, it will start up as // many connections as necessary to reach |num_sockets| total sockets for the @@ -139,7 +199,7 @@ // This priority will probably be lower than all others, since this method // is intended to make sure ahead of time that |num_sockets| sockets are // available to talk to a host. - virtual void RequestSockets(const std::string& group_name, + virtual void RequestSockets(const GroupId& group_id, const void* params, int num_sockets, const NetLogWithSource& net_log) = 0; @@ -150,7 +210,7 @@ // RequestSocket call being modified. // This function is a no-op if |priority| is the same as the current // request priority. - virtual void SetPriority(const std::string& group_name, + virtual void SetPriority(const GroupId& group_id, ClientSocketHandle* handle, RequestPriority priority) = 0; @@ -158,7 +218,7 @@ // same handle parameter must be passed to this method as was passed to the // RequestSocket call being cancelled. The associated callback is not run. // However, for performance, we will let one ConnectJob complete and go idle. - virtual void CancelRequest(const std::string& group_name, + virtual void CancelRequest(const GroupId& group_id, ClientSocketHandle* handle) = 0; // Called to release a socket once the socket is no longer needed. If the @@ -168,7 +228,7 @@ // between updated versions of the same pool instance. The pool's id will // change when it flushes, so it can use this |id| to discard sockets with // mismatched ids. - virtual void ReleaseSocket(const std::string& group_name, + virtual void ReleaseSocket(const GroupId& group_id, std::unique_ptr<StreamSocket> socket, int id) = 0; @@ -183,17 +243,16 @@ virtual void CloseIdleSockets() = 0; // Called to close any idle connections held by the connection manager. - virtual void CloseIdleSocketsInGroup(const std::string& group_name) = 0; + virtual void CloseIdleSocketsInGroup(const GroupId& group_id) = 0; // The total number of idle sockets in the pool. virtual int IdleSocketCount() const = 0; // The total number of idle sockets in a connection group. - virtual size_t IdleSocketCountInGroup( - const std::string& group_name) const = 0; + virtual size_t IdleSocketCountInGroup(const GroupId& group_id) const = 0; // Determine the LoadState of a connecting ClientSocketHandle. - virtual LoadState GetLoadState(const std::string& group_name, + virtual LoadState GetLoadState(const GroupId& group_id, const ClientSocketHandle* handle) const = 0; // Retrieves information on the current state of the pool as a @@ -221,11 +280,11 @@ template <typename PoolType> void RequestSocketsForPool( PoolType* pool, - const std::string& group_name, + const ClientSocketPool::GroupId& group_id, const scoped_refptr<typename PoolType::SocketParams>& params, int num_sockets, const NetLogWithSource& net_log) { - pool->RequestSockets(group_name, ¶ms, num_sockets, net_log); + pool->RequestSockets(group_id, ¶ms, num_sockets, net_log); } } // namespace net
diff --git a/net/socket/client_socket_pool_base.cc b/net/socket/client_socket_pool_base.cc index 930311e..20c7c72 100644 --- a/net/socket/client_socket_pool_base.cc +++ b/net/socket/client_socket_pool_base.cc
@@ -38,11 +38,11 @@ std::unique_ptr<base::Value> NetLogCreateConnectJobCallback( bool backup_job, - const std::string* group_name, + const ClientSocketPool::GroupId* group_id, net::NetLogCaptureMode capture_mode) { auto dict = std::make_unique<base::DictionaryValue>(); dict->SetBoolean("backup_job", backup_job); - dict->SetString("group_name", *group_name); + dict->SetString("group_id", group_id->ToString()); return std::move(dict); } @@ -184,7 +184,7 @@ } int ClientSocketPoolBaseHelper::RequestSocket( - const std::string& group_name, + const ClientSocketPool::GroupId& group_id, std::unique_ptr<Request> request) { CHECK(request->has_callback()); CHECK(request->handle()); @@ -194,7 +194,7 @@ request->net_log().BeginEvent(NetLogEventType::SOCKET_POOL); - int rv = RequestSocketInternal(group_name, *request); + int rv = RequestSocketInternal(group_id, *request); if (rv != ERR_IO_PENDING) { if (rv == OK) { request->handle()->socket()->ApplySocketTag(request->socket_tag()); @@ -204,7 +204,7 @@ CHECK(!request->handle()->is_initialized()); request.reset(); } else { - Group* group = GetOrCreateGroup(group_name); + Group* group = GetOrCreateGroup(group_id); group->InsertUnboundRequest(std::move(request)); // Have to do this asynchronously, as closing sockets in higher level pools // call back in to |this|, which will cause all sorts of fun and exciting @@ -221,9 +221,10 @@ return rv; } -void ClientSocketPoolBaseHelper::RequestSockets(const std::string& group_name, - const Request& request, - int num_sockets) { +void ClientSocketPoolBaseHelper::RequestSockets( + const ClientSocketPool::GroupId& group_id, + const Request& request, + int num_sockets) { DCHECK(!request.has_callback()); DCHECK(!request.handle()); @@ -238,7 +239,7 @@ NetLogEventType::SOCKET_POOL_CONNECTING_N_SOCKETS, NetLog::IntCallback("num_sockets", num_sockets)); - Group* group = GetOrCreateGroup(group_name); + Group* group = GetOrCreateGroup(group_id); // RequestSocketsInternal() may delete the group. bool deleted_group = false; @@ -247,14 +248,14 @@ for (int num_iterations_left = num_sockets; group->NumActiveSocketSlots() < num_sockets && num_iterations_left > 0 ; num_iterations_left--) { - rv = RequestSocketInternal(group_name, request); + rv = RequestSocketInternal(group_id, request); if (rv < 0 && rv != ERR_IO_PENDING) { // We're encountering a synchronous error. Give up. - if (!base::ContainsKey(group_map_, group_name)) + if (!base::ContainsKey(group_map_, group_id)) deleted_group = true; break; } - if (!base::ContainsKey(group_map_, group_name)) { + if (!base::ContainsKey(group_map_, group_id)) { // Unexpected. The group should only be getting deleted on synchronous // error. NOTREACHED(); @@ -264,7 +265,7 @@ } if (!deleted_group && group->IsEmpty()) - RemoveGroup(group_name); + RemoveGroup(group_id); if (rv == ERR_IO_PENDING) rv = OK; @@ -273,13 +274,13 @@ } int ClientSocketPoolBaseHelper::RequestSocketInternal( - const std::string& group_name, + const ClientSocketPool::GroupId& group_id, const Request& request) { ClientSocketHandle* const handle = request.handle(); const bool preconnecting = !handle; Group* group = nullptr; - auto group_it = group_map_.find(group_name); + auto group_it = group_map_.find(group_id); if (group_it != group_map_.end()) { group = group_it->second; @@ -332,14 +333,14 @@ // We couldn't find a socket to reuse, and there's space to allocate one, // so allocate and connect a new one. - group = GetOrCreateGroup(group_name); + group = GetOrCreateGroup(group_id); connecting_socket_count_++; std::unique_ptr<ConnectJob> owned_connect_job( connect_job_factory_->NewConnectJob(request, group)); owned_connect_job->net_log().AddEvent( NetLogEventType::SOCKET_POOL_CONNECT_JOB_CREATED, base::BindRepeating(&NetLogCreateConnectJobCallback, - false /* backup_job */, &group_name)); + false /* backup_job */, base::Unretained(&group_id))); ConnectJob* connect_job = owned_connect_job.get(); bool was_group_empty = group->IsEmpty(); // Need to add the ConnectJob to the group before connecting, to ensure @@ -365,7 +366,7 @@ // creating a new one. If the SYN is lost, this backup socket may complete // before the slow socket, improving end user latency. if (connect_backup_jobs_enabled_ && was_group_empty) - group->StartBackupJobTimer(group_name); + group->StartBackupJobTimer(group_id); } else { LogBoundConnectJobToRequest(connect_job->net_log().source(), request); std::unique_ptr<StreamSocket> error_socket; @@ -381,7 +382,7 @@ } RemoveConnectJob(connect_job, group); if (group->IsEmpty()) - RemoveGroup(group_name); + RemoveGroup(group_id); } return rv; @@ -457,10 +458,11 @@ connect_job_source.ToEventParametersCallback()); } -void ClientSocketPoolBaseHelper::SetPriority(const std::string& group_name, - ClientSocketHandle* handle, - RequestPriority priority) { - auto group_it = group_map_.find(group_name); +void ClientSocketPoolBaseHelper::SetPriority( + const ClientSocketPool::GroupId& group_id, + ClientSocketHandle* handle, + RequestPriority priority) { + auto group_it = group_map_.find(group_id); if (group_it == group_map_.end()) { DCHECK(base::ContainsKey(pending_callback_map_, handle)); // The Request has already completed and been destroyed; nothing to @@ -472,7 +474,8 @@ } void ClientSocketPoolBaseHelper::CancelRequest( - const std::string& group_name, ClientSocketHandle* handle) { + const ClientSocketPool::GroupId& group_id, + ClientSocketHandle* handle) { auto callback_it = pending_callback_map_.find(handle); if (callback_it != pending_callback_map_.end()) { int result = callback_it->second.result; @@ -481,18 +484,18 @@ if (socket) { if (result != OK) socket->Disconnect(); - ReleaseSocket(handle->group_name(), std::move(socket), handle->id()); + ReleaseSocket(handle->group_id(), std::move(socket), handle->id()); } return; } - CHECK(base::ContainsKey(group_map_, group_name)); - Group* group = GetOrCreateGroup(group_name); + CHECK(base::ContainsKey(group_map_, group_id)); + Group* group = GetOrCreateGroup(group_id); std::unique_ptr<Request> request = group->FindAndRemoveBoundRequest(handle); if (request) { --connecting_socket_count_; - OnAvailableSocketSlot(group_name, group); + OnAvailableSocketSlot(group_id, group); CheckForStalledSocketGroups(); return; } @@ -513,8 +516,9 @@ } } -bool ClientSocketPoolBaseHelper::HasGroup(const std::string& group_name) const { - return base::ContainsKey(group_map_, group_name); +bool ClientSocketPoolBaseHelper::HasGroup( + const ClientSocketPool::GroupId& group_id) const { + return base::ContainsKey(group_map_, group_id); } void ClientSocketPoolBaseHelper::CloseIdleSockets() { @@ -523,10 +527,10 @@ } void ClientSocketPoolBaseHelper::CloseIdleSocketsInGroup( - const std::string& group_name) { + const ClientSocketPool::GroupId& group_id) { if (idle_socket_count_ == 0) return; - auto it = group_map_.find(group_name); + auto it = group_map_.find(group_id); if (it == group_map_.end()) return; CleanupIdleSocketsInGroup(true, it->second, base::TimeTicks::Now()); @@ -535,20 +539,20 @@ } size_t ClientSocketPoolBaseHelper::IdleSocketCountInGroup( - const std::string& group_name) const { - auto i = group_map_.find(group_name); + const ClientSocketPool::GroupId& group_id) const { + auto i = group_map_.find(group_id); CHECK(i != group_map_.end()); return i->second->idle_sockets().size(); } LoadState ClientSocketPoolBaseHelper::GetLoadState( - const std::string& group_name, + const ClientSocketPool::GroupId& group_id, const ClientSocketHandle* handle) const { if (base::ContainsKey(pending_callback_map_, handle)) return LOAD_STATE_CONNECTING; - auto group_it = group_map_.find(group_name); + auto group_it = group_map_.find(group_id); if (group_it == group_map_.end()) { // TODO(mmenke): This is actually reached in the wild, for unknown reasons. // Would be great to understand why, and if it's a bug, fix it. If not, @@ -621,7 +625,8 @@ group_dict->SetBoolean("backup_job_timer_is_running", group->BackupJobTimerIsRunning()); - all_groups_dict->SetWithoutPathExpansion(it->first, std::move(group_dict)); + all_groups_dict->SetWithoutPathExpansion(it->first.ToString(), + std::move(group_dict)); } dict->Set("groups", std::move(all_groups_dict)); return dict; @@ -718,17 +723,18 @@ } ClientSocketPoolBaseHelper::Group* ClientSocketPoolBaseHelper::GetOrCreateGroup( - const std::string& group_name) { - auto it = group_map_.find(group_name); + const ClientSocketPool::GroupId& group_id) { + auto it = group_map_.find(group_id); if (it != group_map_.end()) return it->second; - Group* group = new Group(group_name, this); - group_map_[group_name] = group; + Group* group = new Group(group_id, this); + group_map_[group_id] = group; return group; } -void ClientSocketPoolBaseHelper::RemoveGroup(const std::string& group_name) { - auto it = group_map_.find(group_name); +void ClientSocketPoolBaseHelper::RemoveGroup( + const ClientSocketPool::GroupId& group_id) { + auto it = group_map_.find(group_id); CHECK(it != group_map_.end()); RemoveGroup(it); @@ -764,10 +770,10 @@ } void ClientSocketPoolBaseHelper::ReleaseSocket( - const std::string& group_name, + const ClientSocketPool::GroupId& group_id, std::unique_ptr<StreamSocket> socket, int id) { - auto i = group_map_.find(group_name); + auto i = group_map_.find(group_id); CHECK(i != group_map_.end()); Group* group = i->second; @@ -783,7 +789,7 @@ if (can_reuse) { // Add it to the idle list. AddIdleSocket(std::move(socket), group); - OnAvailableSocketSlot(group_name, group); + OnAvailableSocketSlot(group_id, group); } else { socket.reset(); } @@ -795,9 +801,9 @@ // Loop until there's nothing more to do. while (true) { // If we have idle sockets, see if we can give one to the top-stalled group. - std::string top_group_name; + ClientSocketPool::GroupId top_group_id; Group* top_group = nullptr; - if (!FindTopStalledGroup(&top_group, &top_group_name)) + if (!FindTopStalledGroup(&top_group, &top_group_id)) return; if (ReachedMaxSocketsLimit()) { @@ -811,7 +817,7 @@ } // Note that this may delete top_group. - OnAvailableSocketSlot(top_group_name, top_group); + OnAvailableSocketSlot(top_group_id, top_group); } } @@ -821,10 +827,10 @@ // insertion order). bool ClientSocketPoolBaseHelper::FindTopStalledGroup( Group** group, - std::string* group_name) const { - CHECK((group && group_name) || (!group && !group_name)); + ClientSocketPool::GroupId* group_id) const { + CHECK((group && group_id) || (!group && !group_id)); Group* top_group = nullptr; - const std::string* top_group_name = nullptr; + const ClientSocketPool::GroupId* top_group_id = nullptr; bool has_stalled_group = false; for (auto i = group_map_.begin(); i != group_map_.end(); ++i) { Group* curr_group = i->second; @@ -838,7 +844,7 @@ curr_group->TopPendingPriority() > top_group->TopPendingPriority(); if (has_higher_priority) { top_group = curr_group; - top_group_name = &i->first; + top_group_id = &i->first; } } } @@ -846,7 +852,7 @@ if (top_group) { CHECK(group); *group = top_group; - *group_name = *top_group_name; + *group_id = *top_group_id; } else { CHECK(!has_stalled_group); } @@ -874,17 +880,19 @@ } void ClientSocketPoolBaseHelper::OnAvailableSocketSlot( - const std::string& group_name, Group* group) { - DCHECK(base::ContainsKey(group_map_, group_name)); + const ClientSocketPool::GroupId& group_id, + Group* group) { + DCHECK(base::ContainsKey(group_map_, group_id)); if (group->IsEmpty()) { - RemoveGroup(group_name); + RemoveGroup(group_id); } else if (group->has_unbound_requests()) { - ProcessPendingRequest(group_name, group); + ProcessPendingRequest(group_id, group); } } void ClientSocketPoolBaseHelper::ProcessPendingRequest( - const std::string& group_name, Group* group) { + const ClientSocketPool::GroupId& group_id, + Group* group) { const Request* next_request = group->GetNextUnboundRequest(); DCHECK(next_request); @@ -896,12 +904,12 @@ return; } - int rv = RequestSocketInternal(group_name, *next_request); + int rv = RequestSocketInternal(group_id, *next_request); if (rv != ERR_IO_PENDING) { std::unique_ptr<Request> request = group->PopNextUnboundRequest(); DCHECK(request); if (group->IsEmpty()) - RemoveGroup(group_name); + RemoveGroup(group_id); request->net_log().EndEventWithNetErrorCode(NetLogEventType::SOCKET_POOL, rv); @@ -1060,8 +1068,8 @@ int result, ConnectJob* job) { DCHECK_NE(ERR_IO_PENDING, result); - DCHECK(group_map_.find(group->group_name()) != group_map_.end()); - DCHECK_EQ(group, group_map_[group->group_name()]); + DCHECK(group_map_.find(group->group_id()) != group_map_.end()); + DCHECK_EQ(group, group_map_[group->group_id()]); std::unique_ptr<StreamSocket> socket = job->PassSocket(); @@ -1096,7 +1104,7 @@ InvokeUserCallbackLater(request->handle(), request->release_callback(), result, request->socket_tag()); if (!handed_out_socket) { - OnAvailableSocketSlot(group->group_name(), group); + OnAvailableSocketSlot(group->group_id(), group); CheckForStalledSocketGroups(); } return; @@ -1119,7 +1127,7 @@ result, request->socket_tag()); } else { AddIdleSocket(std::move(socket), group); - OnAvailableSocketSlot(group->group_name(), group); + OnAvailableSocketSlot(group->group_id(), group); CheckForStalledSocketGroups(); } } else { @@ -1145,7 +1153,7 @@ RemoveConnectJob(job, group); } if (!handed_out_socket) { - OnAvailableSocketSlot(group->group_name(), group); + OnAvailableSocketSlot(group->group_id(), group); CheckForStalledSocketGroups(); } } @@ -1157,8 +1165,8 @@ HttpAuthController* auth_controller, base::OnceClosure restart_with_auth_callback, ConnectJob* job) { - DCHECK(group_map_.find(group->group_name()) != group_map_.end()); - DCHECK_EQ(group, group_map_[group->group_name()]); + DCHECK(group_map_.find(group->group_id()) != group_map_.end()); + DCHECK_EQ(group, group_map_[group->group_id()]); const Request* request = group->BindRequestToConnectJob(job); // If can't bind the ConnectJob to a request, treat this as a ConnectJob @@ -1212,9 +1220,9 @@ } ClientSocketPoolBaseHelper::Group::Group( - const std::string& group_name, + const ClientSocketPool::GroupId& group_id, ClientSocketPoolBaseHelper* client_socket_pool_base_helper) - : group_name_(group_name), + : group_id_(group_id), client_socket_pool_base_helper_(client_socket_pool_base_helper), never_assigned_job_count_(0), unbound_requests_(NUM_PRIORITIES), @@ -1245,7 +1253,7 @@ } void ClientSocketPoolBaseHelper::Group::StartBackupJobTimer( - const std::string& group_name) { + const ClientSocketPool::GroupId& group_id) { // Only allow one timer to run at a time. if (BackupJobTimerIsRunning()) return; @@ -1255,7 +1263,7 @@ backup_job_timer_.Start( FROM_HERE, client_socket_pool_base_helper_->ConnectRetryInterval(), base::Bind(&Group::OnBackupJobTimerFired, base::Unretained(this), - group_name)); + group_id)); } bool ClientSocketPoolBaseHelper::Group::BackupJobTimerIsRunning() const { @@ -1327,7 +1335,7 @@ } void ClientSocketPoolBaseHelper::Group::OnBackupJobTimerFired( - std::string group_name) { + const ClientSocketPool::GroupId& group_id) { // If there are no more jobs pending, there is no work to do. // If we've done our cleanups correctly, this should not happen. if (jobs_.empty()) { @@ -1355,7 +1363,7 @@ !HasAvailableSocketSlot( client_socket_pool_base_helper_->max_sockets_per_group_) || (*jobs_.begin())->GetLoadState() == LOAD_STATE_RESOLVING_HOST) { - StartBackupJobTimer(group_name); + StartBackupJobTimer(group_id); return; } @@ -1368,7 +1376,7 @@ owned_backup_job->net_log().AddEvent( NetLogEventType::SOCKET_POOL_CONNECT_JOB_CREATED, base::BindRepeating(&NetLogCreateConnectJobCallback, - true /* backup_job */, &group_name_)); + true /* backup_job */, &group_id_)); ConnectJob* backup_job = owned_backup_job.get(); AddJob(std::move(owned_backup_job), false); client_socket_pool_base_helper_->connecting_socket_count_++;
diff --git a/net/socket/client_socket_pool_base.h b/net/socket/client_socket_pool_base.h index b32e351b..53d2ddd 100644 --- a/net/socket/client_socket_pool_base.h +++ b/net/socket/client_socket_pool_base.h
@@ -183,25 +183,25 @@ void RemoveHigherLayeredPool(HigherLayeredPool* higher_pool); // See ClientSocketPool::RequestSocket for documentation on this function. - int RequestSocket(const std::string& group_name, + int RequestSocket(const ClientSocketPool::GroupId& group_id, std::unique_ptr<Request> request); // See ClientSocketPool::RequestSockets for documentation on this function. - void RequestSockets(const std::string& group_name, + void RequestSockets(const ClientSocketPool::GroupId& group_id, const Request& request, int num_sockets); // See ClientSocketPool::SetPriority for documentation on this function. - void SetPriority(const std::string& group_name, + void SetPriority(const ClientSocketPool::GroupId& group_id, ClientSocketHandle* handle, RequestPriority priority); // See ClientSocketPool::CancelRequest for documentation on this function. - void CancelRequest(const std::string& group_name, + void CancelRequest(const ClientSocketPool::GroupId& group_id, ClientSocketHandle* handle); // See ClientSocketPool::ReleaseSocket for documentation on this function. - void ReleaseSocket(const std::string& group_name, + void ReleaseSocket(const ClientSocketPool::GroupId& group_id, std::unique_ptr<StreamSocket> socket, int id); @@ -212,7 +212,7 @@ void CloseIdleSockets(); // See ClientSocketPool::CloseIdleSocketsInGroup for documentation. - void CloseIdleSocketsInGroup(const std::string& group_name); + void CloseIdleSocketsInGroup(const ClientSocketPool::GroupId& group_id); // See ClientSocketPool::IdleSocketCount() for documentation on this function. int idle_socket_count() const { @@ -221,10 +221,11 @@ // See ClientSocketPool::IdleSocketCountInGroup() for documentation on this // function. - size_t IdleSocketCountInGroup(const std::string& group_name) const; + size_t IdleSocketCountInGroup( + const ClientSocketPool::GroupId& group_id) const; // See ClientSocketPool::GetLoadState() for documentation on this function. - LoadState GetLoadState(const std::string& group_name, + LoadState GetLoadState(const ClientSocketPool::GroupId& group_id, const ClientSocketHandle* handle) const; base::TimeDelta ConnectRetryInterval() const { @@ -236,30 +237,32 @@ // TODO(mmenke): de-inline these. size_t NumNeverAssignedConnectJobsInGroup( - const std::string& group_name) const { - return group_map_.find(group_name)->second->never_assigned_job_count(); + const ClientSocketPool::GroupId& group_id) const { + return group_map_.find(group_id)->second->never_assigned_job_count(); } - size_t NumUnassignedConnectJobsInGroup(const std::string& group_name) const { - return group_map_.find(group_name)->second->unassigned_job_count(); + size_t NumUnassignedConnectJobsInGroup( + const ClientSocketPool::GroupId& group_id) const { + return group_map_.find(group_id)->second->unassigned_job_count(); } - size_t NumConnectJobsInGroup(const std::string& group_name) const { - return group_map_.find(group_name)->second->ConnectJobCount(); + size_t NumConnectJobsInGroup( + const ClientSocketPool::GroupId& group_id) const { + return group_map_.find(group_id)->second->ConnectJobCount(); } - int NumActiveSocketsInGroup(const std::string& group_name) const { - return group_map_.find(group_name)->second->active_socket_count(); + int NumActiveSocketsInGroup(const ClientSocketPool::GroupId& group_id) const { + return group_map_.find(group_id)->second->active_socket_count(); } bool RequestInGroupWithHandleHasJobForTesting( - const std::string& group_name, + const ClientSocketPool::GroupId& group_id, const ClientSocketHandle* handle) const { - return group_map_.find(group_name) - ->second->RequestWithHandleHasJobForTesting(handle); + return group_map_.find(group_id)->second->RequestWithHandleHasJobForTesting( + handle); } - bool HasGroup(const std::string& group_name) const; + bool HasGroup(const ClientSocketPool::GroupId& group_id) const; // Closes all idle sockets if |force| is true. Else, only closes idle // sockets that timed out or can't be reused. Made public for testing. @@ -314,7 +317,7 @@ using RequestQueue = PriorityQueue<std::unique_ptr<Request>>; - // A Group is allocated per group_name when there are idle sockets, unbound + // A Group is allocated per GroupId when there are idle sockets, unbound // request, or bound requests. Otherwise, the Group object is removed from the // map. // @@ -342,7 +345,7 @@ public: using JobList = std::list<std::unique_ptr<ConnectJob>>; - Group(const std::string& group_name, + Group(const ClientSocketPool::GroupId& group_id, ClientSocketPoolBaseHelper* client_socket_pool_base_helper); ~Group() override; @@ -388,7 +391,7 @@ // Set a timer to create a backup job if it takes too long to // create one and if a timer isn't already running. - void StartBackupJobTimer(const std::string& group_name); + void StartBackupJobTimer(const ClientSocketPool::GroupId& group_id); bool BackupJobTimerIsRunning() const; @@ -469,7 +472,7 @@ bool RequestWithHandleHasJobForTesting( const ClientSocketHandle* handle) const; - const std::string& group_name() { return group_name_; } + const ClientSocketPool::GroupId& group_id() { return group_id_; } size_t unassigned_job_count() const { return unassigned_jobs_.size(); } const JobList& jobs() const { return jobs_; } const std::list<IdleSocket>& idle_sockets() const { return idle_sockets_; } @@ -544,7 +547,7 @@ void TransferJobBetweenRequests(Request* source, Request* dest); // Called when the backup socket timer fires. - void OnBackupJobTimerFired(std::string group_name); + void OnBackupJobTimerFired(const ClientSocketPool::GroupId& group_id); // Checks that: // - |unassigned_jobs_| is empty iff there are at least as many requests @@ -558,7 +561,7 @@ // - There are no duplicate entries in |unassigned_jobs_|. void SanityCheck() const; - const std::string group_name_; + const ClientSocketPool::GroupId group_id_; ClientSocketPoolBaseHelper* const client_socket_pool_base_helper_; // Total number of ConnectJobs that have never been assigned to a Request. @@ -586,7 +589,7 @@ std::vector<BoundRequest> bound_requests_; }; - using GroupMap = std::map<std::string, Group*>; + using GroupMap = std::map<ClientSocketPool::GroupId, Group*>; struct CallbackResultPair { CallbackResultPair(); @@ -609,8 +612,8 @@ Group* group, const base::TimeTicks& now); - Group* GetOrCreateGroup(const std::string& group_name); - void RemoveGroup(const std::string& group_name); + Group* GetOrCreateGroup(const ClientSocketPool::GroupId& group_id); + void RemoveGroup(const ClientSocketPool::GroupId& group_id); void RemoveGroup(GroupMap::iterator it); // Called when the number of idle sockets changes. @@ -619,18 +622,21 @@ // Scans the group map for groups which have an available socket slot and // at least one pending request. Returns true if any groups are stalled, and - // if so (and if both |group| and |group_name| are not NULL), fills |group| - // and |group_name| with data of the stalled group having highest priority. - bool FindTopStalledGroup(Group** group, std::string* group_name) const; + // if so (and if both |group| and |group_id| are not NULL), fills |group| + // and |group_id| with data of the stalled group having highest priority. + bool FindTopStalledGroup(Group** group, + ClientSocketPool::GroupId* group_id) const; // Removes |job| from |group|, which must already own |job|. void RemoveConnectJob(ConnectJob* job, Group* group); // Tries to see if we can handle any more requests for |group|. - void OnAvailableSocketSlot(const std::string& group_name, Group* group); + void OnAvailableSocketSlot(const ClientSocketPool::GroupId& group_id, + Group* group); // Process a pending socket request for a group. - void ProcessPendingRequest(const std::string& group_name, Group* group); + void ProcessPendingRequest(const ClientSocketPool::GroupId& group_id, + Group* group); // Assigns |socket| to |handle| and updates |group|'s counters appropriately. void HandOutSocket(std::unique_ptr<StreamSocket> socket, @@ -658,7 +664,7 @@ // This is the internal implementation of RequestSocket(). It differs in that // it does not handle logging into NetLog of the queueing status of // |request|. - int RequestSocketInternal(const std::string& group_name, + int RequestSocketInternal(const ClientSocketPool::GroupId& group_id, const Request& request); // Assigns an idle socket for the group to the request. @@ -827,7 +833,7 @@ // RequestSocket bundles up the parameters into a Request and then forwards to // ClientSocketPoolBaseHelper::RequestSocket(). int RequestSocket( - const std::string& group_name, + const ClientSocketPool::GroupId& group_id, const scoped_refptr<SocketParams>& params, RequestPriority priority, const SocketTag& socket_tag, @@ -840,13 +846,13 @@ handle, std::move(callback), proxy_auth_callback, priority, socket_tag, respect_limits, internal::ClientSocketPoolBaseHelper::NORMAL, params, net_log); - return helper_.RequestSocket(group_name, std::move(request)); + return helper_.RequestSocket(group_id, std::move(request)); } // RequestSockets bundles up the parameters into a Request and then forwards // to ClientSocketPoolBaseHelper::RequestSockets(). Note that it assigns the // priority to IDLE and specifies the NO_IDLE_SOCKETS flag. - void RequestSockets(const std::string& group_name, + void RequestSockets(const ClientSocketPool::GroupId& group_id, const scoped_refptr<SocketParams>& params, int num_sockets, const NetLogWithSource& net_log) { @@ -855,24 +861,24 @@ SocketTag(), ClientSocketPool::RespectLimits::ENABLED, internal::ClientSocketPoolBaseHelper::NO_IDLE_SOCKETS, params, net_log); - helper_.RequestSockets(group_name, request, num_sockets); + helper_.RequestSockets(group_id, request, num_sockets); } - void SetPriority(const std::string& group_name, + void SetPriority(const ClientSocketPool::GroupId& group_id, ClientSocketHandle* handle, RequestPriority priority) { - return helper_.SetPriority(group_name, handle, priority); + return helper_.SetPriority(group_id, handle, priority); } - void CancelRequest(const std::string& group_name, + void CancelRequest(const ClientSocketPool::GroupId& group_id, ClientSocketHandle* handle) { - return helper_.CancelRequest(group_name, handle); + return helper_.CancelRequest(group_id, handle); } - void ReleaseSocket(const std::string& group_name, + void ReleaseSocket(const ClientSocketPool::GroupId& group_id, std::unique_ptr<StreamSocket> socket, int id) { - return helper_.ReleaseSocket(group_name, std::move(socket), id); + return helper_.ReleaseSocket(group_id, std::move(socket), id); } void FlushWithError(int error) { helper_.FlushWithError(error); } @@ -881,19 +887,20 @@ void CloseIdleSockets() { return helper_.CloseIdleSockets(); } - void CloseIdleSocketsInGroup(const std::string& group_name) { - return helper_.CloseIdleSocketsInGroup(group_name); + void CloseIdleSocketsInGroup(const ClientSocketPool::GroupId& group_id) { + return helper_.CloseIdleSocketsInGroup(group_id); } int idle_socket_count() const { return helper_.idle_socket_count(); } - size_t IdleSocketCountInGroup(const std::string& group_name) const { - return helper_.IdleSocketCountInGroup(group_name); + size_t IdleSocketCountInGroup( + const ClientSocketPool::GroupId& group_id) const { + return helper_.IdleSocketCountInGroup(group_id); } - LoadState GetLoadState(const std::string& group_name, + LoadState GetLoadState(const ClientSocketPool::GroupId& group_id, const ClientSocketHandle* handle) const { - return helper_.GetLoadState(group_name, handle); + return helper_.GetLoadState(group_id, handle); } void DumpMemoryStats(base::trace_event::ProcessMemoryDump* pmd, @@ -902,30 +909,32 @@ } size_t NumNeverAssignedConnectJobsInGroup( - const std::string& group_name) const { - return helper_.NumNeverAssignedConnectJobsInGroup(group_name); + const ClientSocketPool::GroupId& group_id) const { + return helper_.NumNeverAssignedConnectJobsInGroup(group_id); } - size_t NumUnassignedConnectJobsInGroup(const std::string& group_name) const { - return helper_.NumUnassignedConnectJobsInGroup(group_name); + size_t NumUnassignedConnectJobsInGroup( + const ClientSocketPool::GroupId& group_id) const { + return helper_.NumUnassignedConnectJobsInGroup(group_id); } - size_t NumConnectJobsInGroup(const std::string& group_name) const { - return helper_.NumConnectJobsInGroup(group_name); + size_t NumConnectJobsInGroup( + const ClientSocketPool::GroupId& group_id) const { + return helper_.NumConnectJobsInGroup(group_id); } - int NumActiveSocketsInGroup(const std::string& group_name) const { - return helper_.NumActiveSocketsInGroup(group_name); + int NumActiveSocketsInGroup(const ClientSocketPool::GroupId& group_id) const { + return helper_.NumActiveSocketsInGroup(group_id); } bool RequestInGroupWithHandleHasJobForTesting( - const std::string& group_name, + const ClientSocketPool::GroupId& group_id, const ClientSocketHandle* handle) const { - return helper_.RequestInGroupWithHandleHasJobForTesting(group_name, handle); + return helper_.RequestInGroupWithHandleHasJobForTesting(group_id, handle); } - bool HasGroup(const std::string& group_name) const { - return helper_.HasGroup(group_name); + bool HasGroup(const ClientSocketPool::GroupId& group_id) const { + return helper_.HasGroup(group_id); } void CleanupIdleSockets(bool force) {
diff --git a/net/socket/client_socket_pool_base_unittest.cc b/net/socket/client_socket_pool_base_unittest.cc index 14bcc532..6cb8fbdf 100644 --- a/net/socket/client_socket_pool_base_unittest.cc +++ b/net/socket/client_socket_pool_base_unittest.cc
@@ -66,6 +66,15 @@ constexpr base::TimeDelta kUnusedIdleSocketTimeout = base::TimeDelta::FromSeconds(10); +ClientSocketPool::GroupId TestGroupId(const std::string& host, + int port = 80, + ClientSocketPool::SocketType socket_type = + ClientSocketPool::SocketType::kHttp, + bool privacy_mode = false) { + return ClientSocketPool::GroupId(HostPortPair(host, port), socket_type, + privacy_mode); +} + // Make sure |handle| sets load times correctly when it has been assigned a // reused socket. void TestLoadTimingInfoConnectedReused(const ClientSocketHandle& handle) { @@ -597,7 +606,7 @@ ~TestClientSocketPool() override = default; - int RequestSocket(const std::string& group_name, + int RequestSocket(const GroupId& group_id, const void* params, RequestPriority priority, const SocketTag& socket_tag, @@ -609,35 +618,35 @@ const scoped_refptr<TestSocketParams>* casted_socket_params = static_cast<const scoped_refptr<TestSocketParams>*>(params); return base_.RequestSocket( - group_name, *casted_socket_params, priority, socket_tag, respect_limits, + group_id, *casted_socket_params, priority, socket_tag, respect_limits, handle, std::move(callback), proxy_auth_callback, net_log); } - void RequestSockets(const std::string& group_name, + void RequestSockets(const GroupId& group_id, const void* params, int num_sockets, const NetLogWithSource& net_log) override { const scoped_refptr<TestSocketParams>* casted_params = static_cast<const scoped_refptr<TestSocketParams>*>(params); - base_.RequestSockets(group_name, *casted_params, num_sockets, net_log); + base_.RequestSockets(group_id, *casted_params, num_sockets, net_log); } - void SetPriority(const std::string& group_name, + void SetPriority(const GroupId& group_id, ClientSocketHandle* handle, RequestPriority priority) override { - base_.SetPriority(group_name, handle, priority); + base_.SetPriority(group_id, handle, priority); } - void CancelRequest(const std::string& group_name, + void CancelRequest(const GroupId& group_id, ClientSocketHandle* handle) override { - base_.CancelRequest(group_name, handle); + base_.CancelRequest(group_id, handle); } - void ReleaseSocket(const std::string& group_name, + void ReleaseSocket(const GroupId& group_id, std::unique_ptr<StreamSocket> socket, int id) override { - base_.ReleaseSocket(group_name, std::move(socket), id); + base_.ReleaseSocket(group_id, std::move(socket), id); } void FlushWithError(int error) override { base_.FlushWithError(error); } @@ -646,19 +655,19 @@ void CloseIdleSockets() override { base_.CloseIdleSockets(); } - void CloseIdleSocketsInGroup(const std::string& group_name) override { - base_.CloseIdleSocketsInGroup(group_name); + void CloseIdleSocketsInGroup(const GroupId& group_id) override { + base_.CloseIdleSocketsInGroup(group_id); } int IdleSocketCount() const override { return base_.idle_socket_count(); } - size_t IdleSocketCountInGroup(const std::string& group_name) const override { - return base_.IdleSocketCountInGroup(group_name); + size_t IdleSocketCountInGroup(const GroupId& group_id) const override { + return base_.IdleSocketCountInGroup(group_id); } - LoadState GetLoadState(const std::string& group_name, + LoadState GetLoadState(const GroupId& group_id, const ClientSocketHandle* handle) const override { - return base_.GetLoadState(group_name, handle); + return base_.GetLoadState(group_id, handle); } void AddHigherLayeredPool(HigherLayeredPool* higher_pool) override { @@ -677,31 +686,30 @@ const TestClientSocketPoolBase* base() const { return &base_; } - size_t NumNeverAssignedConnectJobsInGroup( - const std::string& group_name) const { - return base_.NumNeverAssignedConnectJobsInGroup(group_name); + size_t NumNeverAssignedConnectJobsInGroup(const GroupId& group_id) const { + return base_.NumNeverAssignedConnectJobsInGroup(group_id); } - size_t NumUnassignedConnectJobsInGroup(const std::string& group_name) const { - return base_.NumUnassignedConnectJobsInGroup(group_name); + size_t NumUnassignedConnectJobsInGroup(const GroupId& group_id) const { + return base_.NumUnassignedConnectJobsInGroup(group_id); } - size_t NumConnectJobsInGroup(const std::string& group_name) const { - return base_.NumConnectJobsInGroup(group_name); + size_t NumConnectJobsInGroup(const GroupId& group_id) const { + return base_.NumConnectJobsInGroup(group_id); } - int NumActiveSocketsInGroup(const std::string& group_name) const { - return base_.NumActiveSocketsInGroup(group_name); + int NumActiveSocketsInGroup(const GroupId& group_id) const { + return base_.NumActiveSocketsInGroup(group_id); } bool RequestInGroupWithHandleHasJobForTesting( - const std::string& group_name, + const GroupId& group_id, const ClientSocketHandle* handle) const { - return base_.RequestInGroupWithHandleHasJobForTesting(group_name, handle); + return base_.RequestInGroupWithHandleHasJobForTesting(group_id, handle); } - bool HasGroup(const std::string& group_name) const { - return base_.HasGroup(group_name); + bool HasGroup(const GroupId& group_id) const { + return base_.HasGroup(group_id); } void CleanupTimedOutIdleSockets() { base_.CleanupIdleSockets(false); } @@ -779,16 +787,17 @@ } int StartRequestWithIgnoreLimits( - const std::string& group_name, + const ClientSocketPool::GroupId& group_id, RequestPriority priority, ClientSocketPool::RespectLimits respect_limits) { - return test_base_.StartRequestUsingPool(pool_.get(), group_name, priority, + return test_base_.StartRequestUsingPool(pool_.get(), group_id, priority, respect_limits, params_); } - int StartRequest(const std::string& group_name, RequestPriority priority) { + int StartRequest(const ClientSocketPool::GroupId& group_id, + RequestPriority priority) { return StartRequestWithIgnoreLimits( - group_name, priority, ClientSocketPool::RespectLimits::ENABLED); + group_id, priority, ClientSocketPool::RespectLimits::ENABLED); } int GetOrderOfRequest(size_t index) const { @@ -829,11 +838,11 @@ BoundTestNetLog log; TestLoadTimingInfoNotConnected(handle); - EXPECT_EQ(OK, handle.Init("a", params_, DEFAULT_PRIORITY, SocketTag(), - ClientSocketPool::RespectLimits::ENABLED, - callback.callback(), - ClientSocketPool::ProxyAuthCallback(), pool_.get(), - log.bound())); + EXPECT_EQ( + OK, handle.Init( + TestGroupId("a"), params_, DEFAULT_PRIORITY, SocketTag(), + ClientSocketPool::RespectLimits::ENABLED, callback.callback(), + ClientSocketPool::ProxyAuthCallback(), pool_.get(), log.bound())); EXPECT_TRUE(handle.is_initialized()); EXPECT_TRUE(handle.socket()); TestLoadTimingInfoConnectedNotReused(handle); @@ -870,7 +879,7 @@ handle.set_ssl_error_response_info(info); EXPECT_EQ( ERR_CONNECTION_FAILED, - handle.Init("a", params_, DEFAULT_PRIORITY, SocketTag(), + handle.Init(TestGroupId("a"), params_, DEFAULT_PRIORITY, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, callback.callback(), ClientSocketPool::ProxyAuthCallback(), pool_.get(), log.bound())); @@ -890,23 +899,109 @@ EXPECT_TRUE(LogContainsEndEvent(entries, 2, NetLogEventType::SOCKET_POOL)); } +// Make sure different groups do not share sockets. +TEST_F(ClientSocketPoolBaseTest, GroupSeparation) { + CreatePool(1000 /* max_sockets */, 2 /* max_sockets_per_group */); + + const HostPortPair kHostPortPairs[] = { + {"a", 80}, + {"a", 443}, + {"b", 80}, + }; + + const ClientSocketPool::SocketType kSocketTypes[] = { + ClientSocketPool::SocketType::kHttp, + ClientSocketPool::SocketType::kSsl, + ClientSocketPool::SocketType::kSslVersionInterferenceProbe, + ClientSocketPool::SocketType::kFtp, + }; + + const bool kPrivacyModes[] = {false, true}; + + int total_idle_sockets = 0; + + // Walk through each GroupId, making sure that requesting a socket for one + // group does not return a previously connected socket for another group. + for (const auto& host_port_pair : kHostPortPairs) { + SCOPED_TRACE(host_port_pair.ToString()); + for (const auto& socket_type : kSocketTypes) { + SCOPED_TRACE(static_cast<int>(socket_type)); + for (const auto& privacy_mode : kPrivacyModes) { + SCOPED_TRACE(privacy_mode); + + connect_job_factory_->set_job_type(TestConnectJob::kMockPendingJob); + + ClientSocketPool::GroupId group_id(host_port_pair, socket_type, + privacy_mode); + + EXPECT_FALSE(pool_->HasGroup(group_id)); + + TestCompletionCallback callback; + ClientSocketHandle handle; + + // Since the group is empty, requesting a socket should not complete + // synchronously. + EXPECT_THAT( + handle.Init(group_id, params_, DEFAULT_PRIORITY, SocketTag(), + ClientSocketPool::RespectLimits::ENABLED, + callback.callback(), + ClientSocketPool::ProxyAuthCallback(), pool_.get(), + NetLogWithSource()), + IsError(ERR_IO_PENDING)); + EXPECT_TRUE(pool_->HasGroup(group_id)); + EXPECT_EQ(total_idle_sockets, pool_->IdleSocketCount()); + + EXPECT_THAT(callback.WaitForResult(), IsOk()); + EXPECT_TRUE(handle.socket()); + EXPECT_TRUE(pool_->HasGroup(group_id)); + EXPECT_EQ(total_idle_sockets, pool_->IdleSocketCount()); + + // Return socket to pool. + handle.Reset(); + EXPECT_EQ(total_idle_sockets + 1, pool_->IdleSocketCount()); + + // Requesting a socket again should return the same socket as before, so + // should complete synchronously. + EXPECT_THAT( + handle.Init(group_id, params_, DEFAULT_PRIORITY, SocketTag(), + ClientSocketPool::RespectLimits::ENABLED, + callback.callback(), + ClientSocketPool::ProxyAuthCallback(), pool_.get(), + NetLogWithSource()), + IsOk()); + EXPECT_TRUE(handle.socket()); + EXPECT_EQ(total_idle_sockets, pool_->IdleSocketCount()); + + // Return socket to pool again. + handle.Reset(); + EXPECT_EQ(total_idle_sockets + 1, pool_->IdleSocketCount()); + + ++total_idle_sockets; + } + } + } +} + TEST_F(ClientSocketPoolBaseTest, TotalLimit) { CreatePool(kDefaultMaxSockets, kDefaultMaxSocketsPerGroup); // TODO(eroman): Check that the NetLog contains this event. - EXPECT_THAT(StartRequest("a", DEFAULT_PRIORITY), IsOk()); - EXPECT_THAT(StartRequest("b", DEFAULT_PRIORITY), IsOk()); - EXPECT_THAT(StartRequest("c", DEFAULT_PRIORITY), IsOk()); - EXPECT_THAT(StartRequest("d", DEFAULT_PRIORITY), IsOk()); + EXPECT_THAT(StartRequest(TestGroupId("a"), DEFAULT_PRIORITY), IsOk()); + EXPECT_THAT(StartRequest(TestGroupId("b"), DEFAULT_PRIORITY), IsOk()); + EXPECT_THAT(StartRequest(TestGroupId("c"), DEFAULT_PRIORITY), IsOk()); + EXPECT_THAT(StartRequest(TestGroupId("d"), DEFAULT_PRIORITY), IsOk()); EXPECT_EQ(static_cast<int>(requests_size()), client_socket_factory_.allocation_count()); EXPECT_EQ(requests_size() - kDefaultMaxSockets, completion_count()); - EXPECT_THAT(StartRequest("e", DEFAULT_PRIORITY), IsError(ERR_IO_PENDING)); - EXPECT_THAT(StartRequest("f", DEFAULT_PRIORITY), IsError(ERR_IO_PENDING)); - EXPECT_THAT(StartRequest("g", DEFAULT_PRIORITY), IsError(ERR_IO_PENDING)); + EXPECT_THAT(StartRequest(TestGroupId("e"), DEFAULT_PRIORITY), + IsError(ERR_IO_PENDING)); + EXPECT_THAT(StartRequest(TestGroupId("f"), DEFAULT_PRIORITY), + IsError(ERR_IO_PENDING)); + EXPECT_THAT(StartRequest(TestGroupId("g"), DEFAULT_PRIORITY), + IsError(ERR_IO_PENDING)); ReleaseAllConnections(ClientSocketPoolTest::NO_KEEP_ALIVE); @@ -932,17 +1027,18 @@ // TODO(eroman): Check that the NetLog contains this event. // Reach all limits: max total sockets, and max sockets per group. - EXPECT_THAT(StartRequest("a", DEFAULT_PRIORITY), IsOk()); - EXPECT_THAT(StartRequest("a", DEFAULT_PRIORITY), IsOk()); - EXPECT_THAT(StartRequest("b", DEFAULT_PRIORITY), IsOk()); - EXPECT_THAT(StartRequest("b", DEFAULT_PRIORITY), IsOk()); + EXPECT_THAT(StartRequest(TestGroupId("a"), DEFAULT_PRIORITY), IsOk()); + EXPECT_THAT(StartRequest(TestGroupId("a"), DEFAULT_PRIORITY), IsOk()); + EXPECT_THAT(StartRequest(TestGroupId("b"), DEFAULT_PRIORITY), IsOk()); + EXPECT_THAT(StartRequest(TestGroupId("b"), DEFAULT_PRIORITY), IsOk()); EXPECT_EQ(static_cast<int>(requests_size()), client_socket_factory_.allocation_count()); EXPECT_EQ(requests_size() - kDefaultMaxSockets, completion_count()); // Now create a new group and verify that we don't starve it. - EXPECT_THAT(StartRequest("c", DEFAULT_PRIORITY), IsError(ERR_IO_PENDING)); + EXPECT_THAT(StartRequest(TestGroupId("c"), DEFAULT_PRIORITY), + IsError(ERR_IO_PENDING)); ReleaseAllConnections(ClientSocketPoolTest::NO_KEEP_ALIVE); @@ -963,17 +1059,17 @@ TEST_F(ClientSocketPoolBaseTest, TotalLimitRespectsPriority) { CreatePool(kDefaultMaxSockets, kDefaultMaxSocketsPerGroup); - EXPECT_THAT(StartRequest("b", LOWEST), IsOk()); - EXPECT_THAT(StartRequest("a", MEDIUM), IsOk()); - EXPECT_THAT(StartRequest("b", HIGHEST), IsOk()); - EXPECT_THAT(StartRequest("a", LOWEST), IsOk()); + EXPECT_THAT(StartRequest(TestGroupId("b"), LOWEST), IsOk()); + EXPECT_THAT(StartRequest(TestGroupId("a"), MEDIUM), IsOk()); + EXPECT_THAT(StartRequest(TestGroupId("b"), HIGHEST), IsOk()); + EXPECT_THAT(StartRequest(TestGroupId("a"), LOWEST), IsOk()); EXPECT_EQ(static_cast<int>(requests_size()), client_socket_factory_.allocation_count()); - EXPECT_THAT(StartRequest("c", LOWEST), IsError(ERR_IO_PENDING)); - EXPECT_THAT(StartRequest("a", MEDIUM), IsError(ERR_IO_PENDING)); - EXPECT_THAT(StartRequest("b", HIGHEST), IsError(ERR_IO_PENDING)); + EXPECT_THAT(StartRequest(TestGroupId("c"), LOWEST), IsError(ERR_IO_PENDING)); + EXPECT_THAT(StartRequest(TestGroupId("a"), MEDIUM), IsError(ERR_IO_PENDING)); + EXPECT_THAT(StartRequest(TestGroupId("b"), HIGHEST), IsError(ERR_IO_PENDING)); ReleaseAllConnections(ClientSocketPoolTest::NO_KEEP_ALIVE); @@ -985,8 +1081,8 @@ EXPECT_EQ(3, GetOrderOfRequest(3)); EXPECT_EQ(4, GetOrderOfRequest(4)); - // Request ("b", HIGHEST) has the highest priority, then ("a", MEDIUM), - // and then ("c", LOWEST). + // Request ("b", HIGHEST) has the highest priority, then (TestGroupId("a"), + // MEDIUM), and then ("c", LOWEST). EXPECT_EQ(7, GetOrderOfRequest(5)); EXPECT_EQ(6, GetOrderOfRequest(6)); EXPECT_EQ(5, GetOrderOfRequest(7)); @@ -1000,8 +1096,8 @@ TEST_F(ClientSocketPoolBaseTest, ReprioritizeOne) { CreatePool(kDefaultMaxSockets, 1); - EXPECT_THAT(StartRequest("a", LOWEST), IsError(OK)); - EXPECT_THAT(StartRequest("a", MEDIUM), IsError(ERR_IO_PENDING)); + EXPECT_THAT(StartRequest(TestGroupId("a"), LOWEST), IsError(OK)); + EXPECT_THAT(StartRequest(TestGroupId("a"), MEDIUM), IsError(ERR_IO_PENDING)); EXPECT_TRUE(request(0)->handle()->socket()); EXPECT_FALSE(request(1)->handle()->socket()); @@ -1017,9 +1113,9 @@ TEST_F(ClientSocketPoolBaseTest, ReprioritizeUpReorder) { CreatePool(kDefaultMaxSockets, 1); - EXPECT_THAT(StartRequest("a", LOWEST), IsError(OK)); - EXPECT_THAT(StartRequest("a", MEDIUM), IsError(ERR_IO_PENDING)); - EXPECT_THAT(StartRequest("a", LOWEST), IsError(ERR_IO_PENDING)); + EXPECT_THAT(StartRequest(TestGroupId("a"), LOWEST), IsError(OK)); + EXPECT_THAT(StartRequest(TestGroupId("a"), MEDIUM), IsError(ERR_IO_PENDING)); + EXPECT_THAT(StartRequest(TestGroupId("a"), LOWEST), IsError(ERR_IO_PENDING)); EXPECT_TRUE(request(0)->handle()->socket()); EXPECT_FALSE(request(1)->handle()->socket()); EXPECT_FALSE(request(2)->handle()->socket()); @@ -1038,9 +1134,9 @@ TEST_F(ClientSocketPoolBaseTest, ReprioritizeUpNoReorder) { CreatePool(kDefaultMaxSockets, 1); - EXPECT_THAT(StartRequest("a", LOWEST), IsError(OK)); - EXPECT_THAT(StartRequest("a", MEDIUM), IsError(ERR_IO_PENDING)); - EXPECT_THAT(StartRequest("a", LOW), IsError(ERR_IO_PENDING)); + EXPECT_THAT(StartRequest(TestGroupId("a"), LOWEST), IsError(OK)); + EXPECT_THAT(StartRequest(TestGroupId("a"), MEDIUM), IsError(ERR_IO_PENDING)); + EXPECT_THAT(StartRequest(TestGroupId("a"), LOW), IsError(ERR_IO_PENDING)); EXPECT_TRUE(request(0)->handle()->socket()); EXPECT_FALSE(request(1)->handle()->socket()); EXPECT_FALSE(request(2)->handle()->socket()); @@ -1059,9 +1155,9 @@ TEST_F(ClientSocketPoolBaseTest, ReprioritizeDownReorder) { CreatePool(kDefaultMaxSockets, 1); - EXPECT_THAT(StartRequest("a", LOWEST), IsError(OK)); - EXPECT_THAT(StartRequest("a", HIGHEST), IsError(ERR_IO_PENDING)); - EXPECT_THAT(StartRequest("a", MEDIUM), IsError(ERR_IO_PENDING)); + EXPECT_THAT(StartRequest(TestGroupId("a"), LOWEST), IsError(OK)); + EXPECT_THAT(StartRequest(TestGroupId("a"), HIGHEST), IsError(ERR_IO_PENDING)); + EXPECT_THAT(StartRequest(TestGroupId("a"), MEDIUM), IsError(ERR_IO_PENDING)); EXPECT_TRUE(request(0)->handle()->socket()); EXPECT_FALSE(request(1)->handle()->socket()); EXPECT_FALSE(request(2)->handle()->socket()); @@ -1080,9 +1176,9 @@ TEST_F(ClientSocketPoolBaseTest, ReprioritizeResetFIFO) { CreatePool(kDefaultMaxSockets, 1); - EXPECT_THAT(StartRequest("a", LOWEST), IsError(OK)); - EXPECT_THAT(StartRequest("a", HIGHEST), IsError(ERR_IO_PENDING)); - EXPECT_THAT(StartRequest("a", MEDIUM), IsError(ERR_IO_PENDING)); + EXPECT_THAT(StartRequest(TestGroupId("a"), LOWEST), IsError(OK)); + EXPECT_THAT(StartRequest(TestGroupId("a"), HIGHEST), IsError(ERR_IO_PENDING)); + EXPECT_THAT(StartRequest(TestGroupId("a"), MEDIUM), IsError(ERR_IO_PENDING)); EXPECT_TRUE(request(0)->handle()->socket()); EXPECT_FALSE(request(1)->handle()->socket()); EXPECT_FALSE(request(2)->handle()->socket()); @@ -1099,17 +1195,17 @@ TEST_F(ClientSocketPoolBaseTest, TotalLimitRespectsGroupLimit) { CreatePool(kDefaultMaxSockets, kDefaultMaxSocketsPerGroup); - EXPECT_THAT(StartRequest("a", LOWEST), IsOk()); - EXPECT_THAT(StartRequest("a", LOW), IsOk()); - EXPECT_THAT(StartRequest("b", HIGHEST), IsOk()); - EXPECT_THAT(StartRequest("b", MEDIUM), IsOk()); + EXPECT_THAT(StartRequest(TestGroupId("a"), LOWEST), IsOk()); + EXPECT_THAT(StartRequest(TestGroupId("a"), LOW), IsOk()); + EXPECT_THAT(StartRequest(TestGroupId("b"), HIGHEST), IsOk()); + EXPECT_THAT(StartRequest(TestGroupId("b"), MEDIUM), IsOk()); EXPECT_EQ(static_cast<int>(requests_size()), client_socket_factory_.allocation_count()); - EXPECT_THAT(StartRequest("c", MEDIUM), IsError(ERR_IO_PENDING)); - EXPECT_THAT(StartRequest("a", LOW), IsError(ERR_IO_PENDING)); - EXPECT_THAT(StartRequest("b", HIGHEST), IsError(ERR_IO_PENDING)); + EXPECT_THAT(StartRequest(TestGroupId("c"), MEDIUM), IsError(ERR_IO_PENDING)); + EXPECT_THAT(StartRequest(TestGroupId("a"), LOW), IsError(ERR_IO_PENDING)); + EXPECT_THAT(StartRequest(TestGroupId("b"), HIGHEST), IsError(ERR_IO_PENDING)); ReleaseAllConnections(ClientSocketPoolTest::NO_KEEP_ALIVE); @@ -1139,13 +1235,14 @@ TEST_F(ClientSocketPoolBaseTest, TotalLimitCountsConnectingSockets) { CreatePool(kDefaultMaxSockets, kDefaultMaxSocketsPerGroup); - EXPECT_THAT(StartRequest("a", DEFAULT_PRIORITY), IsOk()); - EXPECT_THAT(StartRequest("b", DEFAULT_PRIORITY), IsOk()); - EXPECT_THAT(StartRequest("c", DEFAULT_PRIORITY), IsOk()); + EXPECT_THAT(StartRequest(TestGroupId("a"), DEFAULT_PRIORITY), IsOk()); + EXPECT_THAT(StartRequest(TestGroupId("b"), DEFAULT_PRIORITY), IsOk()); + EXPECT_THAT(StartRequest(TestGroupId("c"), DEFAULT_PRIORITY), IsOk()); // Create one asynchronous request. connect_job_factory_->set_job_type(TestConnectJob::kMockPendingJob); - EXPECT_THAT(StartRequest("d", DEFAULT_PRIORITY), IsError(ERR_IO_PENDING)); + EXPECT_THAT(StartRequest(TestGroupId("d"), DEFAULT_PRIORITY), + IsError(ERR_IO_PENDING)); // We post all of our delayed tasks with a 2ms delay. I.e. they don't // actually become pending until 2ms after they have been created. In order @@ -1155,7 +1252,8 @@ // The next synchronous request should wait for its turn. connect_job_factory_->set_job_type(TestConnectJob::kMockJob); - EXPECT_THAT(StartRequest("e", DEFAULT_PRIORITY), IsError(ERR_IO_PENDING)); + EXPECT_THAT(StartRequest(TestGroupId("e"), DEFAULT_PRIORITY), + IsError(ERR_IO_PENDING)); ReleaseAllConnections(ClientSocketPoolTest::NO_KEEP_ALIVE); @@ -1176,17 +1274,19 @@ CreatePool(kDefaultMaxSockets, kDefaultMaxSockets); connect_job_factory_->set_job_type(TestConnectJob::kMockJob); - EXPECT_THAT(StartRequest("a", DEFAULT_PRIORITY), IsOk()); - EXPECT_THAT(StartRequest("a", DEFAULT_PRIORITY), IsOk()); - EXPECT_THAT(StartRequest("a", DEFAULT_PRIORITY), IsOk()); - EXPECT_THAT(StartRequest("a", DEFAULT_PRIORITY), IsOk()); + EXPECT_THAT(StartRequest(TestGroupId("a"), DEFAULT_PRIORITY), IsOk()); + EXPECT_THAT(StartRequest(TestGroupId("a"), DEFAULT_PRIORITY), IsOk()); + EXPECT_THAT(StartRequest(TestGroupId("a"), DEFAULT_PRIORITY), IsOk()); + EXPECT_THAT(StartRequest(TestGroupId("a"), DEFAULT_PRIORITY), IsOk()); connect_job_factory_->set_job_type(TestConnectJob::kMockWaitingJob); EXPECT_EQ(kDefaultMaxSockets, client_socket_factory_.allocation_count()); - EXPECT_THAT(StartRequest("b", DEFAULT_PRIORITY), IsError(ERR_IO_PENDING)); - EXPECT_THAT(StartRequest("c", DEFAULT_PRIORITY), IsError(ERR_IO_PENDING)); + EXPECT_THAT(StartRequest(TestGroupId("b"), DEFAULT_PRIORITY), + IsError(ERR_IO_PENDING)); + EXPECT_THAT(StartRequest(TestGroupId("c"), DEFAULT_PRIORITY), + IsError(ERR_IO_PENDING)); EXPECT_EQ(kDefaultMaxSockets, client_socket_factory_.allocation_count()); @@ -1207,7 +1307,7 @@ TestCompletionCallback callback; EXPECT_EQ( ERR_IO_PENDING, - handle.Init("a", params_, DEFAULT_PRIORITY, SocketTag(), + handle.Init(TestGroupId("a"), params_, DEFAULT_PRIORITY, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, callback.callback(), ClientSocketPool::ProxyAuthCallback(), pool_.get(), NetLogWithSource())); @@ -1216,11 +1316,11 @@ for (size_t i = 0; i < base::size(handles); ++i) { TestCompletionCallback callback; EXPECT_EQ(ERR_IO_PENDING, - handles[i].Init("b", params_, DEFAULT_PRIORITY, SocketTag(), - ClientSocketPool::RespectLimits::ENABLED, - callback.callback(), - ClientSocketPool::ProxyAuthCallback(), - pool_.get(), NetLogWithSource())); + handles[i].Init( + TestGroupId("b"), params_, DEFAULT_PRIORITY, SocketTag(), + ClientSocketPool::RespectLimits::ENABLED, callback.callback(), + ClientSocketPool::ProxyAuthCallback(), pool_.get(), + NetLogWithSource())); } // One will be stalled, cancel all the handles now. @@ -1238,8 +1338,8 @@ ClientSocketHandle handles[kDefaultMaxSockets]; TestCompletionCallback callbacks[kDefaultMaxSockets]; for (int i = 0; i < kDefaultMaxSockets; ++i) { - EXPECT_EQ(OK, handles[i].Init(base::NumberToString(i), params_, - DEFAULT_PRIORITY, SocketTag(), + EXPECT_EQ(OK, handles[i].Init(TestGroupId(base::NumberToString(i)), + params_, DEFAULT_PRIORITY, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, callbacks[i].callback(), ClientSocketPool::ProxyAuthCallback(), @@ -1250,11 +1350,11 @@ ClientSocketHandle stalled_handle; TestCompletionCallback callback; EXPECT_EQ(ERR_IO_PENDING, - stalled_handle.Init("foo", params_, DEFAULT_PRIORITY, SocketTag(), - ClientSocketPool::RespectLimits::ENABLED, - callback.callback(), - ClientSocketPool::ProxyAuthCallback(), - pool_.get(), NetLogWithSource())); + stalled_handle.Init( + TestGroupId("foo"), params_, DEFAULT_PRIORITY, SocketTag(), + ClientSocketPool::RespectLimits::ENABLED, callback.callback(), + ClientSocketPool::ProxyAuthCallback(), pool_.get(), + NetLogWithSource())); // Cancel the stalled request. stalled_handle.Reset(); @@ -1278,11 +1378,12 @@ for (int i = 0; i < kDefaultMaxSockets; ++i) { TestCompletionCallback callback; EXPECT_EQ(ERR_IO_PENDING, - handles[i].Init( - base::NumberToString(i), params_, DEFAULT_PRIORITY, - SocketTag(), ClientSocketPool::RespectLimits::ENABLED, - callback.callback(), ClientSocketPool::ProxyAuthCallback(), - pool_.get(), NetLogWithSource())); + handles[i].Init(TestGroupId(base::NumberToString(i)), params_, + DEFAULT_PRIORITY, SocketTag(), + ClientSocketPool::RespectLimits::ENABLED, + callback.callback(), + ClientSocketPool::ProxyAuthCallback(), + pool_.get(), NetLogWithSource())); } // Force a stalled group. @@ -1290,24 +1391,26 @@ ClientSocketHandle stalled_handle; TestCompletionCallback callback; EXPECT_EQ(ERR_IO_PENDING, - stalled_handle.Init("foo", params_, DEFAULT_PRIORITY, SocketTag(), - ClientSocketPool::RespectLimits::ENABLED, - callback.callback(), - ClientSocketPool::ProxyAuthCallback(), - pool_.get(), NetLogWithSource())); + stalled_handle.Init( + TestGroupId("foo"), params_, DEFAULT_PRIORITY, SocketTag(), + ClientSocketPool::RespectLimits::ENABLED, callback.callback(), + ClientSocketPool::ProxyAuthCallback(), pool_.get(), + NetLogWithSource())); // Since it is stalled, it should have no connect jobs. - EXPECT_EQ(0u, pool_->NumConnectJobsInGroup("foo")); - EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup("foo")); - EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup("foo")); + EXPECT_EQ(0u, pool_->NumConnectJobsInGroup(TestGroupId("foo"))); + EXPECT_EQ(0u, + pool_->NumNeverAssignedConnectJobsInGroup(TestGroupId("foo"))); + EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup(TestGroupId("foo"))); // Cancel the stalled request. handles[0].Reset(); // Now we should have a connect job. - EXPECT_EQ(1u, pool_->NumConnectJobsInGroup("foo")); - EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup("foo")); - EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup("foo")); + EXPECT_EQ(1u, pool_->NumConnectJobsInGroup(TestGroupId("foo"))); + EXPECT_EQ(0u, + pool_->NumNeverAssignedConnectJobsInGroup(TestGroupId("foo"))); + EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup(TestGroupId("foo"))); // The stalled socket should connect. EXPECT_THAT(callback.WaitForResult(), IsOk()); @@ -1315,9 +1418,10 @@ EXPECT_EQ(kDefaultMaxSockets + 1, client_socket_factory_.allocation_count()); EXPECT_EQ(0, pool_->IdleSocketCount()); - EXPECT_EQ(0u, pool_->NumConnectJobsInGroup("foo")); - EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup("foo")); - EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup("foo")); + EXPECT_EQ(0u, pool_->NumConnectJobsInGroup(TestGroupId("foo"))); + EXPECT_EQ(0u, + pool_->NumNeverAssignedConnectJobsInGroup(TestGroupId("foo"))); + EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup(TestGroupId("foo"))); // Dropping out of scope will close all handles and return them to idle. } @@ -1336,12 +1440,13 @@ ClientSocketHandle handles[kDefaultMaxSockets]; for (int i = 0; i < kDefaultMaxSockets; ++i) { TestCompletionCallback callback; - EXPECT_EQ(OK, handles[i].Init(base::StringPrintf("Take 2: %d", i), - params_, DEFAULT_PRIORITY, SocketTag(), - ClientSocketPool::RespectLimits::ENABLED, - callback.callback(), - ClientSocketPool::ProxyAuthCallback(), - pool_.get(), NetLogWithSource())); + EXPECT_EQ( + OK, handles[i].Init(TestGroupId(base::StringPrintf("Take 2: %d", i)), + params_, DEFAULT_PRIORITY, SocketTag(), + ClientSocketPool::RespectLimits::ENABLED, + callback.callback(), + ClientSocketPool::ProxyAuthCallback(), + pool_.get(), NetLogWithSource())); } EXPECT_EQ(kDefaultMaxSockets, client_socket_factory_.allocation_count()); @@ -1350,11 +1455,11 @@ // Now we will hit the socket limit. EXPECT_EQ(ERR_IO_PENDING, - stalled_handle.Init("foo", params_, DEFAULT_PRIORITY, SocketTag(), - ClientSocketPool::RespectLimits::ENABLED, - callback.callback(), - ClientSocketPool::ProxyAuthCallback(), - pool_.get(), NetLogWithSource())); + stalled_handle.Init( + TestGroupId("foo"), params_, DEFAULT_PRIORITY, SocketTag(), + ClientSocketPool::RespectLimits::ENABLED, callback.callback(), + ClientSocketPool::ProxyAuthCallback(), pool_.get(), + NetLogWithSource())); EXPECT_TRUE(pool_->IsStalled()); // Dropping out of scope will close all handles and return them to idle. @@ -1377,12 +1482,12 @@ for (int i = 0; i < kDefaultMaxSockets; ++i) { ClientSocketHandle handle; TestCompletionCallback callback; - EXPECT_EQ( - OK, - handle.Init(base::NumberToString(i), params_, DEFAULT_PRIORITY, - SocketTag(), ClientSocketPool::RespectLimits::ENABLED, - callback.callback(), ClientSocketPool::ProxyAuthCallback(), - pool_.get(), NetLogWithSource())); + EXPECT_EQ(OK, handle.Init(TestGroupId(base::NumberToString(i)), params_, + DEFAULT_PRIORITY, SocketTag(), + ClientSocketPool::RespectLimits::ENABLED, + callback.callback(), + ClientSocketPool::ProxyAuthCallback(), + pool_.get(), NetLogWithSource())); } // Flush all the DoReleaseSocket tasks. @@ -1397,11 +1502,11 @@ // "0" is special here, since it should be the first entry in the sorted map, // which is the one which we would close an idle socket for. We shouldn't // close an idle socket though, since we should reuse the idle socket. - EXPECT_EQ(OK, handle.Init("0", params_, DEFAULT_PRIORITY, SocketTag(), - ClientSocketPool::RespectLimits::ENABLED, - callback.callback(), - ClientSocketPool::ProxyAuthCallback(), pool_.get(), - NetLogWithSource())); + EXPECT_EQ(OK, handle.Init( + TestGroupId("0"), params_, DEFAULT_PRIORITY, SocketTag(), + ClientSocketPool::RespectLimits::ENABLED, + callback.callback(), ClientSocketPool::ProxyAuthCallback(), + pool_.get(), NetLogWithSource())); EXPECT_EQ(kDefaultMaxSockets, client_socket_factory_.allocation_count()); EXPECT_EQ(kDefaultMaxSockets - 1, pool_->IdleSocketCount()); @@ -1410,14 +1515,14 @@ TEST_F(ClientSocketPoolBaseTest, PendingRequests) { CreatePool(kDefaultMaxSockets, kDefaultMaxSocketsPerGroup); - EXPECT_THAT(StartRequest("a", DEFAULT_PRIORITY), IsOk()); - EXPECT_THAT(StartRequest("a", DEFAULT_PRIORITY), IsOk()); - EXPECT_THAT(StartRequest("a", IDLE), IsError(ERR_IO_PENDING)); - EXPECT_THAT(StartRequest("a", LOWEST), IsError(ERR_IO_PENDING)); - EXPECT_THAT(StartRequest("a", MEDIUM), IsError(ERR_IO_PENDING)); - EXPECT_THAT(StartRequest("a", HIGHEST), IsError(ERR_IO_PENDING)); - EXPECT_THAT(StartRequest("a", LOW), IsError(ERR_IO_PENDING)); - EXPECT_THAT(StartRequest("a", LOWEST), IsError(ERR_IO_PENDING)); + EXPECT_THAT(StartRequest(TestGroupId("a"), DEFAULT_PRIORITY), IsOk()); + EXPECT_THAT(StartRequest(TestGroupId("a"), DEFAULT_PRIORITY), IsOk()); + EXPECT_THAT(StartRequest(TestGroupId("a"), IDLE), IsError(ERR_IO_PENDING)); + EXPECT_THAT(StartRequest(TestGroupId("a"), LOWEST), IsError(ERR_IO_PENDING)); + EXPECT_THAT(StartRequest(TestGroupId("a"), MEDIUM), IsError(ERR_IO_PENDING)); + EXPECT_THAT(StartRequest(TestGroupId("a"), HIGHEST), IsError(ERR_IO_PENDING)); + EXPECT_THAT(StartRequest(TestGroupId("a"), LOW), IsError(ERR_IO_PENDING)); + EXPECT_THAT(StartRequest(TestGroupId("a"), LOWEST), IsError(ERR_IO_PENDING)); ReleaseAllConnections(ClientSocketPoolTest::KEEP_ALIVE); EXPECT_EQ(kDefaultMaxSocketsPerGroup, @@ -1441,13 +1546,13 @@ TEST_F(ClientSocketPoolBaseTest, PendingRequests_NoKeepAlive) { CreatePool(kDefaultMaxSockets, kDefaultMaxSocketsPerGroup); - EXPECT_THAT(StartRequest("a", DEFAULT_PRIORITY), IsOk()); - EXPECT_THAT(StartRequest("a", DEFAULT_PRIORITY), IsOk()); - EXPECT_THAT(StartRequest("a", LOWEST), IsError(ERR_IO_PENDING)); - EXPECT_THAT(StartRequest("a", MEDIUM), IsError(ERR_IO_PENDING)); - EXPECT_THAT(StartRequest("a", HIGHEST), IsError(ERR_IO_PENDING)); - EXPECT_THAT(StartRequest("a", LOW), IsError(ERR_IO_PENDING)); - EXPECT_THAT(StartRequest("a", LOWEST), IsError(ERR_IO_PENDING)); + EXPECT_THAT(StartRequest(TestGroupId("a"), DEFAULT_PRIORITY), IsOk()); + EXPECT_THAT(StartRequest(TestGroupId("a"), DEFAULT_PRIORITY), IsOk()); + EXPECT_THAT(StartRequest(TestGroupId("a"), LOWEST), IsError(ERR_IO_PENDING)); + EXPECT_THAT(StartRequest(TestGroupId("a"), MEDIUM), IsError(ERR_IO_PENDING)); + EXPECT_THAT(StartRequest(TestGroupId("a"), HIGHEST), IsError(ERR_IO_PENDING)); + EXPECT_THAT(StartRequest(TestGroupId("a"), LOW), IsError(ERR_IO_PENDING)); + EXPECT_THAT(StartRequest(TestGroupId("a"), LOWEST), IsError(ERR_IO_PENDING)); ReleaseAllConnections(ClientSocketPoolTest::NO_KEEP_ALIVE); @@ -1471,7 +1576,7 @@ TestCompletionCallback callback; EXPECT_EQ( ERR_IO_PENDING, - handle.Init("a", params_, DEFAULT_PRIORITY, SocketTag(), + handle.Init(TestGroupId("a"), params_, DEFAULT_PRIORITY, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, callback.callback(), ClientSocketPool::ProxyAuthCallback(), pool_.get(), NetLogWithSource())); @@ -1487,7 +1592,7 @@ EXPECT_EQ( ERR_IO_PENDING, - handle.Init("a", params_, DEFAULT_PRIORITY, SocketTag(), + handle.Init(TestGroupId("a"), params_, DEFAULT_PRIORITY, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, callback.callback(), ClientSocketPool::ProxyAuthCallback(), pool_.get(), NetLogWithSource())); @@ -1497,7 +1602,7 @@ TestCompletionCallback callback2; EXPECT_EQ( ERR_IO_PENDING, - handle.Init("a", params_, DEFAULT_PRIORITY, SocketTag(), + handle.Init(TestGroupId("a"), params_, DEFAULT_PRIORITY, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, callback2.callback(), ClientSocketPool::ProxyAuthCallback(), pool_.get(), NetLogWithSource())); @@ -1511,13 +1616,13 @@ TEST_F(ClientSocketPoolBaseTest, CancelRequest) { CreatePool(kDefaultMaxSockets, kDefaultMaxSocketsPerGroup); - EXPECT_THAT(StartRequest("a", DEFAULT_PRIORITY), IsOk()); - EXPECT_THAT(StartRequest("a", DEFAULT_PRIORITY), IsOk()); - EXPECT_THAT(StartRequest("a", LOWEST), IsError(ERR_IO_PENDING)); - EXPECT_THAT(StartRequest("a", MEDIUM), IsError(ERR_IO_PENDING)); - EXPECT_THAT(StartRequest("a", HIGHEST), IsError(ERR_IO_PENDING)); - EXPECT_THAT(StartRequest("a", LOW), IsError(ERR_IO_PENDING)); - EXPECT_THAT(StartRequest("a", LOWEST), IsError(ERR_IO_PENDING)); + EXPECT_THAT(StartRequest(TestGroupId("a"), DEFAULT_PRIORITY), IsOk()); + EXPECT_THAT(StartRequest(TestGroupId("a"), DEFAULT_PRIORITY), IsOk()); + EXPECT_THAT(StartRequest(TestGroupId("a"), LOWEST), IsError(ERR_IO_PENDING)); + EXPECT_THAT(StartRequest(TestGroupId("a"), MEDIUM), IsError(ERR_IO_PENDING)); + EXPECT_THAT(StartRequest(TestGroupId("a"), HIGHEST), IsError(ERR_IO_PENDING)); + EXPECT_THAT(StartRequest(TestGroupId("a"), LOW), IsError(ERR_IO_PENDING)); + EXPECT_THAT(StartRequest(TestGroupId("a"), LOWEST), IsError(ERR_IO_PENDING)); // Cancel a request. size_t index_to_cancel = kDefaultMaxSocketsPerGroup + 2; @@ -1567,7 +1672,7 @@ scoped_refptr<TestSocketParams> params(new TestSocketParams()); TestCompletionCallback callback; int rv = handle->Init( - "a", params, LOWEST, SocketTag(), + TestGroupId("a"), params, LOWEST, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, nested_callback->callback(), ClientSocketPool::ProxyAuthCallback(), pool, NetLogWithSource()); if (rv != ERR_IO_PENDING) { @@ -1588,7 +1693,7 @@ ClientSocketHandle handle; TestCompletionCallback second_result_callback; int rv = handle.Init( - "a", params_, DEFAULT_PRIORITY, SocketTag(), + TestGroupId("a"), params_, DEFAULT_PRIORITY, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, base::BindOnce(&RequestSocketOnComplete, &handle, pool_.get(), connect_job_factory_, TestConnectJob::kMockPendingJob, @@ -1609,7 +1714,7 @@ ClientSocketHandle handle; TestCompletionCallback second_result_callback; int rv = handle.Init( - "a", params_, DEFAULT_PRIORITY, SocketTag(), + TestGroupId("a"), params_, DEFAULT_PRIORITY, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, base::BindOnce(&RequestSocketOnComplete, &handle, pool_.get(), connect_job_factory_, TestConnectJob::kMockPendingJob, @@ -1627,13 +1732,20 @@ connect_job_factory_->set_job_type(TestConnectJob::kMockPendingJob); - EXPECT_THAT(StartRequest("a", DEFAULT_PRIORITY), IsError(ERR_IO_PENDING)); - EXPECT_THAT(StartRequest("a", DEFAULT_PRIORITY), IsError(ERR_IO_PENDING)); - EXPECT_THAT(StartRequest("a", DEFAULT_PRIORITY), IsError(ERR_IO_PENDING)); - EXPECT_THAT(StartRequest("a", DEFAULT_PRIORITY), IsError(ERR_IO_PENDING)); - EXPECT_THAT(StartRequest("a", DEFAULT_PRIORITY), IsError(ERR_IO_PENDING)); - EXPECT_THAT(StartRequest("a", DEFAULT_PRIORITY), IsError(ERR_IO_PENDING)); - EXPECT_THAT(StartRequest("a", DEFAULT_PRIORITY), IsError(ERR_IO_PENDING)); + EXPECT_THAT(StartRequest(TestGroupId("a"), DEFAULT_PRIORITY), + IsError(ERR_IO_PENDING)); + EXPECT_THAT(StartRequest(TestGroupId("a"), DEFAULT_PRIORITY), + IsError(ERR_IO_PENDING)); + EXPECT_THAT(StartRequest(TestGroupId("a"), DEFAULT_PRIORITY), + IsError(ERR_IO_PENDING)); + EXPECT_THAT(StartRequest(TestGroupId("a"), DEFAULT_PRIORITY), + IsError(ERR_IO_PENDING)); + EXPECT_THAT(StartRequest(TestGroupId("a"), DEFAULT_PRIORITY), + IsError(ERR_IO_PENDING)); + EXPECT_THAT(StartRequest(TestGroupId("a"), DEFAULT_PRIORITY), + IsError(ERR_IO_PENDING)); + EXPECT_THAT(StartRequest(TestGroupId("a"), DEFAULT_PRIORITY), + IsError(ERR_IO_PENDING)); // Now, kDefaultMaxSocketsPerGroup requests should be active. // Let's cancel them. @@ -1664,7 +1776,8 @@ // Queue up all the requests for (size_t i = 0; i < kNumberOfRequests; ++i) - EXPECT_THAT(StartRequest("a", DEFAULT_PRIORITY), IsError(ERR_IO_PENDING)); + EXPECT_THAT(StartRequest(TestGroupId("a"), DEFAULT_PRIORITY), + IsError(ERR_IO_PENDING)); for (size_t i = 0; i < kNumberOfRequests; ++i) EXPECT_THAT(request(i)->WaitForResult(), IsError(ERR_CONNECTION_FAILED)); @@ -1679,13 +1792,15 @@ connect_job_factory_->set_job_type(TestConnectJob::kMockPendingFailingJob); - EXPECT_THAT(StartRequest("a", DEFAULT_PRIORITY), IsError(ERR_IO_PENDING)); + EXPECT_THAT(StartRequest(TestGroupId("a"), DEFAULT_PRIORITY), + IsError(ERR_IO_PENDING)); connect_job_factory_->set_job_type(TestConnectJob::kMockFailingJob); // Queue up all the other requests for (size_t i = 1; i < kNumberOfRequests; ++i) - EXPECT_THAT(StartRequest("a", DEFAULT_PRIORITY), IsError(ERR_IO_PENDING)); + EXPECT_THAT(StartRequest(TestGroupId("a"), DEFAULT_PRIORITY), + IsError(ERR_IO_PENDING)); // Make sure all requests fail, instead of hanging. for (size_t i = 0; i < kNumberOfRequests; ++i) @@ -1700,7 +1815,7 @@ ClientSocketHandle handle; TestCompletionCallback callback; int rv = handle.Init( - "a", params_, DEFAULT_PRIORITY, SocketTag(), + TestGroupId("a"), params_, DEFAULT_PRIORITY, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, callback.callback(), ClientSocketPool::ProxyAuthCallback(), pool_.get(), NetLogWithSource()); EXPECT_THAT(rv, IsError(ERR_IO_PENDING)); @@ -1708,7 +1823,7 @@ // Cancel the active request. handle.Reset(); - rv = handle.Init("a", params_, DEFAULT_PRIORITY, SocketTag(), + rv = handle.Init(TestGroupId("a"), params_, DEFAULT_PRIORITY, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, callback.callback(), ClientSocketPool::ProxyAuthCallback(), pool_.get(), NetLogWithSource()); @@ -1726,7 +1841,7 @@ TestCompletionCallback callback; BoundTestNetLog log; int rv = handle.Init( - "a", params_, LOWEST, SocketTag(), + TestGroupId("a"), params_, LOWEST, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, callback.callback(), ClientSocketPool::ProxyAuthCallback(), pool_.get(), log.bound()); EXPECT_THAT(rv, IsOk()); @@ -1741,17 +1856,17 @@ BoundTestNetLog log; ClientSocketHandle handle1; int rv = handle1.Init( - "a", params_, LOWEST, SocketTag(), + TestGroupId("a"), params_, LOWEST, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, callback.callback(), ClientSocketPool::ProxyAuthCallback(), pool_.get(), log.bound()); EXPECT_THAT(rv, IsOk()); ClientSocketHandle handle2; - rv = handle2.Init("a", params_, LOWEST, SocketTag(), + rv = handle2.Init(TestGroupId("a"), params_, LOWEST, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, callback.callback(), ClientSocketPool::ProxyAuthCallback(), pool_.get(), log.bound()); ClientSocketHandle handle3; - rv = handle3.Init("b", params_, LOWEST, SocketTag(), + rv = handle3.Init(TestGroupId("b"), params_, LOWEST, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, callback.callback(), ClientSocketPool::ProxyAuthCallback(), pool_.get(), log.bound()); @@ -1760,7 +1875,7 @@ handle2.Reset(); handle3.Reset(); EXPECT_EQ(3, pool_->IdleSocketCount()); - pool_->CloseIdleSocketsInGroup("a"); + pool_->CloseIdleSocketsInGroup(TestGroupId("a")); EXPECT_EQ(1, pool_->IdleSocketCount()); } @@ -1770,7 +1885,7 @@ TestCompletionCallback callback; BoundTestNetLog log; int rv = handle.Init( - "a", params_, LOWEST, SocketTag(), + TestGroupId("a"), params_, LOWEST, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, callback.callback(), ClientSocketPool::ProxyAuthCallback(), pool_.get(), log.bound()); EXPECT_THAT(rv, IsOk()); @@ -1781,7 +1896,7 @@ // Disconnect socket now to make the socket unusable. socket->Disconnect(); ClientSocketHandle handle2; - rv = handle2.Init("a", params_, LOWEST, SocketTag(), + rv = handle2.Init(TestGroupId("a"), params_, LOWEST, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, callback.callback(), ClientSocketPool::ProxyAuthCallback(), pool_.get(), log.bound()); @@ -1797,29 +1912,32 @@ const RequestPriority kHighPriority = HIGHEST; - EXPECT_THAT(StartRequest("a", DEFAULT_PRIORITY), IsOk()); - EXPECT_THAT(StartRequest("a", DEFAULT_PRIORITY), IsOk()); + EXPECT_THAT(StartRequest(TestGroupId("a"), DEFAULT_PRIORITY), IsOk()); + EXPECT_THAT(StartRequest(TestGroupId("a"), DEFAULT_PRIORITY), IsOk()); // This is going to be a pending request in an otherwise empty group. - EXPECT_THAT(StartRequest("a", DEFAULT_PRIORITY), IsError(ERR_IO_PENDING)); + EXPECT_THAT(StartRequest(TestGroupId("a"), DEFAULT_PRIORITY), + IsError(ERR_IO_PENDING)); // Reach the maximum socket limit. - EXPECT_THAT(StartRequest("b", DEFAULT_PRIORITY), IsOk()); + EXPECT_THAT(StartRequest(TestGroupId("b"), DEFAULT_PRIORITY), IsOk()); // Create a stalled group with high priorities. - EXPECT_THAT(StartRequest("c", kHighPriority), IsError(ERR_IO_PENDING)); - EXPECT_THAT(StartRequest("c", kHighPriority), IsError(ERR_IO_PENDING)); + EXPECT_THAT(StartRequest(TestGroupId("c"), kHighPriority), + IsError(ERR_IO_PENDING)); + EXPECT_THAT(StartRequest(TestGroupId("c"), kHighPriority), + IsError(ERR_IO_PENDING)); - // Release the first two sockets from "a". Because this is a keepalive, - // the first release will unblock the pending request for "a". The - // second release will unblock a request for "c", becaue it is the next - // high priority socket. + // Release the first two sockets from TestGroupId("a"). Because this is a + // keepalive, the first release will unblock the pending request for + // TestGroupId("a"). The second release will unblock a request for "c", + // because it is the next high priority socket. EXPECT_TRUE(ReleaseOneConnection(ClientSocketPoolTest::KEEP_ALIVE)); EXPECT_TRUE(ReleaseOneConnection(ClientSocketPoolTest::KEEP_ALIVE)); // Closing idle sockets should not get us into trouble, but in the bug // we were hitting a CHECK here. - EXPECT_EQ(0u, pool_->IdleSocketCountInGroup("a")); + EXPECT_EQ(0u, pool_->IdleSocketCountInGroup(TestGroupId("a"))); pool_->CloseIdleSockets(); // Run the released socket wakeups. @@ -1834,11 +1952,12 @@ TestCompletionCallback callback; BoundTestNetLog log; int rv = handle.Init( - "a", params_, LOWEST, SocketTag(), + TestGroupId("a"), params_, LOWEST, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, callback.callback(), ClientSocketPool::ProxyAuthCallback(), pool_.get(), log.bound()); EXPECT_THAT(rv, IsError(ERR_IO_PENDING)); - EXPECT_EQ(LOAD_STATE_CONNECTING, pool_->GetLoadState("a", &handle)); + EXPECT_EQ(LOAD_STATE_CONNECTING, + pool_->GetLoadState(TestGroupId("a"), &handle)); TestLoadTimingInfoNotConnected(handle); EXPECT_THAT(callback.WaitForResult(), IsOk()); @@ -1878,11 +1997,12 @@ handle.set_ssl_error_response_info(info); EXPECT_EQ( ERR_IO_PENDING, - handle.Init("a", params_, DEFAULT_PRIORITY, SocketTag(), + handle.Init(TestGroupId("a"), params_, DEFAULT_PRIORITY, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, callback.callback(), ClientSocketPool::ProxyAuthCallback(), pool_.get(), log.bound())); - EXPECT_EQ(LOAD_STATE_CONNECTING, pool_->GetLoadState("a", &handle)); + EXPECT_EQ(LOAD_STATE_CONNECTING, + pool_->GetLoadState(TestGroupId("a"), &handle)); EXPECT_THAT(callback.WaitForResult(), IsError(ERR_CONNECTION_FAILED)); EXPECT_FALSE(handle.is_ssl_error()); EXPECT_TRUE(handle.ssl_error_response_info().headers.get() == nullptr); @@ -1905,8 +2025,10 @@ CreatePool(2, 2); connect_job_factory_->set_job_type(TestConnectJob::kMockPendingFailingJob); - EXPECT_THAT(StartRequest("a", DEFAULT_PRIORITY), IsError(ERR_IO_PENDING)); - EXPECT_THAT(StartRequest("a", DEFAULT_PRIORITY), IsError(ERR_IO_PENDING)); + EXPECT_THAT(StartRequest(TestGroupId("a"), DEFAULT_PRIORITY), + IsError(ERR_IO_PENDING)); + EXPECT_THAT(StartRequest(TestGroupId("a"), DEFAULT_PRIORITY), + IsError(ERR_IO_PENDING)); EXPECT_THAT(request(0)->WaitForResult(), IsError(ERR_CONNECTION_FAILED)); EXPECT_THAT(request(1)->WaitForResult(), IsError(ERR_CONNECTION_FAILED)); @@ -1927,14 +2049,14 @@ EXPECT_EQ( ERR_IO_PENDING, - handle.Init("a", params_, DEFAULT_PRIORITY, SocketTag(), + handle.Init(TestGroupId("a"), params_, DEFAULT_PRIORITY, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, callback.callback(), ClientSocketPool::ProxyAuthCallback(), pool_.get(), NetLogWithSource())); BoundTestNetLog log2; EXPECT_EQ( ERR_IO_PENDING, - handle2.Init("a", params_, DEFAULT_PRIORITY, SocketTag(), + handle2.Init(TestGroupId("a"), params_, DEFAULT_PRIORITY, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, callback2.callback(), ClientSocketPool::ProxyAuthCallback(), pool_.get(), NetLogWithSource())); @@ -1956,25 +2078,25 @@ connect_job_factory_->set_job_type(TestConnectJob::kMockPendingJob); - EXPECT_THAT(StartRequest("a", LOWEST), IsError(ERR_IO_PENDING)); - EXPECT_THAT(StartRequest("a", LOW), IsError(ERR_IO_PENDING)); - EXPECT_THAT(StartRequest("a", MEDIUM), IsError(ERR_IO_PENDING)); - EXPECT_THAT(StartRequest("a", HIGHEST), IsError(ERR_IO_PENDING)); + EXPECT_THAT(StartRequest(TestGroupId("a"), LOWEST), IsError(ERR_IO_PENDING)); + EXPECT_THAT(StartRequest(TestGroupId("a"), LOW), IsError(ERR_IO_PENDING)); + EXPECT_THAT(StartRequest(TestGroupId("a"), MEDIUM), IsError(ERR_IO_PENDING)); + EXPECT_THAT(StartRequest(TestGroupId("a"), HIGHEST), IsError(ERR_IO_PENDING)); EXPECT_EQ(kDefaultMaxSocketsPerGroup, - static_cast<int>(pool_->NumConnectJobsInGroup("a"))); + static_cast<int>(pool_->NumConnectJobsInGroup(TestGroupId("a")))); (*requests())[2]->handle()->Reset(); (*requests())[3]->handle()->Reset(); EXPECT_EQ(kDefaultMaxSocketsPerGroup, - static_cast<int>(pool_->NumConnectJobsInGroup("a"))); + static_cast<int>(pool_->NumConnectJobsInGroup(TestGroupId("a")))); (*requests())[1]->handle()->Reset(); EXPECT_EQ(kDefaultMaxSocketsPerGroup, - static_cast<int>(pool_->NumConnectJobsInGroup("a"))); + static_cast<int>(pool_->NumConnectJobsInGroup(TestGroupId("a")))); (*requests())[0]->handle()->Reset(); EXPECT_EQ(kDefaultMaxSocketsPerGroup, - static_cast<int>(pool_->NumConnectJobsInGroup("a"))); + static_cast<int>(pool_->NumConnectJobsInGroup(TestGroupId("a")))); } // When requests and ConnectJobs are not coupled, the request will get serviced @@ -1989,7 +2111,7 @@ size_t completion_count; // unused TestSocketRequest req1(&request_order, &completion_count); int rv = req1.handle()->Init( - "a", params_, DEFAULT_PRIORITY, SocketTag(), + TestGroupId("a"), params_, DEFAULT_PRIORITY, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, req1.callback(), ClientSocketPool::ProxyAuthCallback(), pool_.get(), NetLogWithSource()); EXPECT_THAT(rv, IsError(ERR_IO_PENDING)); @@ -2001,13 +2123,13 @@ TestSocketRequest req2(&request_order, &completion_count); rv = req2.handle()->Init( - "a", params_, DEFAULT_PRIORITY, SocketTag(), + TestGroupId("a"), params_, DEFAULT_PRIORITY, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, req2.callback(), ClientSocketPool::ProxyAuthCallback(), pool_.get(), NetLogWithSource()); EXPECT_THAT(rv, IsError(ERR_IO_PENDING)); TestSocketRequest req3(&request_order, &completion_count); rv = req3.handle()->Init( - "a", params_, DEFAULT_PRIORITY, SocketTag(), + TestGroupId("a"), params_, DEFAULT_PRIORITY, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, req3.callback(), ClientSocketPool::ProxyAuthCallback(), pool_.get(), NetLogWithSource()); EXPECT_THAT(rv, IsError(ERR_IO_PENDING)); @@ -2030,7 +2152,7 @@ EXPECT_EQ(&req1, request_order[0]); EXPECT_EQ(&req2, request_order[1]); EXPECT_EQ(&req3, request_order[2]); - EXPECT_EQ(0u, pool_->IdleSocketCountInGroup("a")); + EXPECT_EQ(0u, pool_->IdleSocketCountInGroup(TestGroupId("a"))); } // The requests are not coupled to the jobs. So, the requests should finish in @@ -2044,14 +2166,14 @@ size_t completion_count; // unused TestSocketRequest req1(&request_order, &completion_count); int rv = req1.handle()->Init( - "a", params_, DEFAULT_PRIORITY, SocketTag(), + TestGroupId("a"), params_, DEFAULT_PRIORITY, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, req1.callback(), ClientSocketPool::ProxyAuthCallback(), pool_.get(), NetLogWithSource()); EXPECT_THAT(rv, IsError(ERR_IO_PENDING)); TestSocketRequest req2(&request_order, &completion_count); rv = req2.handle()->Init( - "a", params_, DEFAULT_PRIORITY, SocketTag(), + TestGroupId("a"), params_, DEFAULT_PRIORITY, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, req2.callback(), ClientSocketPool::ProxyAuthCallback(), pool_.get(), NetLogWithSource()); EXPECT_THAT(rv, IsError(ERR_IO_PENDING)); @@ -2061,7 +2183,7 @@ TestSocketRequest req3(&request_order, &completion_count); rv = req3.handle()->Init( - "a", params_, DEFAULT_PRIORITY, SocketTag(), + TestGroupId("a"), params_, DEFAULT_PRIORITY, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, req3.callback(), ClientSocketPool::ProxyAuthCallback(), pool_.get(), NetLogWithSource()); EXPECT_THAT(rv, IsError(ERR_IO_PENDING)); @@ -2084,7 +2206,7 @@ ClientSocketHandle handle; TestCompletionCallback callback; int rv = handle.Init( - "a", params_, DEFAULT_PRIORITY, SocketTag(), + TestGroupId("a"), params_, DEFAULT_PRIORITY, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, callback.callback(), ClientSocketPool::ProxyAuthCallback(), pool_.get(), NetLogWithSource()); EXPECT_THAT(rv, IsError(ERR_IO_PENDING)); @@ -2105,7 +2227,7 @@ ClientSocketHandle handle; TestCompletionCallback callback; int rv = handle.Init( - "a", params_, DEFAULT_PRIORITY, SocketTag(), + TestGroupId("a"), params_, DEFAULT_PRIORITY, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, callback.callback(), ClientSocketPool::ProxyAuthCallback(), pool_.get(), NetLogWithSource()); EXPECT_THAT(rv, IsError(ERR_IO_PENDING)); @@ -2113,7 +2235,7 @@ ClientSocketHandle handle2; TestCompletionCallback callback2; - rv = handle2.Init("a", params_, DEFAULT_PRIORITY, SocketTag(), + rv = handle2.Init(TestGroupId("a"), params_, DEFAULT_PRIORITY, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, callback2.callback(), ClientSocketPool::ProxyAuthCallback(), pool_.get(), NetLogWithSource()); @@ -2153,7 +2275,7 @@ ClientSocketHandle handle; TestCompletionCallback callback; int rv = handle.Init( - "a", params_, MEDIUM, SocketTag(), + TestGroupId("a"), params_, MEDIUM, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, callback.callback(), ClientSocketPool::ProxyAuthCallback(), pool_.get(), NetLogWithSource()); EXPECT_THAT(rv, IsError(ERR_IO_PENDING)); @@ -2163,7 +2285,7 @@ // The first request should now be stalled at the socket group limit. ClientSocketHandle handle2; TestCompletionCallback callback2; - rv = handle2.Init("a", params_, HIGHEST, SocketTag(), + rv = handle2.Init(TestGroupId("a"), params_, HIGHEST, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, callback2.callback(), ClientSocketPool::ProxyAuthCallback(), pool_.get(), NetLogWithSource()); @@ -2197,7 +2319,7 @@ ClientSocketHandle handle; TestCompletionCallback callback; int rv = handle.Init( - "a", params_, DEFAULT_PRIORITY, SocketTag(), + TestGroupId("a"), params_, DEFAULT_PRIORITY, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, callback.callback(), ClientSocketPool::ProxyAuthCallback(), pool_.get(), NetLogWithSource()); EXPECT_THAT(rv, IsError(ERR_IO_PENDING)); @@ -2205,7 +2327,7 @@ // Request for socket from another pool. ClientSocketHandle handle2; TestCompletionCallback callback2; - rv = handle2.Init("b", params_, DEFAULT_PRIORITY, SocketTag(), + rv = handle2.Init(TestGroupId("b"), params_, DEFAULT_PRIORITY, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, callback2.callback(), ClientSocketPool::ProxyAuthCallback(), pool_.get(), NetLogWithSource()); @@ -2215,7 +2337,7 @@ // socket pool limit. ClientSocketHandle handle3; TestCompletionCallback callback3; - rv = handle3.Init("a", params_, DEFAULT_PRIORITY, SocketTag(), + rv = handle3.Init(TestGroupId("a"), params_, DEFAULT_PRIORITY, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, callback2.callback(), ClientSocketPool::ProxyAuthCallback(), pool_.get(), NetLogWithSource()); @@ -2250,7 +2372,7 @@ TestCompletionCallback callback; EXPECT_EQ( ERR_CERT_COMMON_NAME_INVALID, - handle.Init("a", params_, DEFAULT_PRIORITY, SocketTag(), + handle.Init(TestGroupId("a"), params_, DEFAULT_PRIORITY, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, callback.callback(), ClientSocketPool::ProxyAuthCallback(), pool_.get(), NetLogWithSource())); @@ -2266,11 +2388,12 @@ TestCompletionCallback callback; EXPECT_EQ( ERR_IO_PENDING, - handle.Init("a", params_, DEFAULT_PRIORITY, SocketTag(), + handle.Init(TestGroupId("a"), params_, DEFAULT_PRIORITY, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, callback.callback(), ClientSocketPool::ProxyAuthCallback(), pool_.get(), NetLogWithSource())); - EXPECT_EQ(LOAD_STATE_CONNECTING, pool_->GetLoadState("a", &handle)); + EXPECT_EQ(LOAD_STATE_CONNECTING, + pool_->GetLoadState(TestGroupId("a"), &handle)); EXPECT_THAT(callback.WaitForResult(), IsError(ERR_CERT_COMMON_NAME_INVALID)); EXPECT_TRUE(handle.is_initialized()); EXPECT_TRUE(handle.socket()); @@ -2285,7 +2408,7 @@ TestCompletionCallback callback; EXPECT_EQ( ERR_CONNECTION_FAILED, - handle.Init("a", params_, DEFAULT_PRIORITY, SocketTag(), + handle.Init(TestGroupId("a"), params_, DEFAULT_PRIORITY, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, callback.callback(), ClientSocketPool::ProxyAuthCallback(), pool_.get(), NetLogWithSource())); @@ -2304,11 +2427,12 @@ TestCompletionCallback callback; EXPECT_EQ( ERR_IO_PENDING, - handle.Init("a", params_, DEFAULT_PRIORITY, SocketTag(), + handle.Init(TestGroupId("a"), params_, DEFAULT_PRIORITY, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, callback.callback(), ClientSocketPool::ProxyAuthCallback(), pool_.get(), NetLogWithSource())); - EXPECT_EQ(LOAD_STATE_CONNECTING, pool_->GetLoadState("a", &handle)); + EXPECT_EQ(LOAD_STATE_CONNECTING, + pool_->GetLoadState(TestGroupId("a"), &handle)); EXPECT_THAT(callback.WaitForResult(), IsError(ERR_CONNECTION_FAILED)); EXPECT_FALSE(handle.is_initialized()); EXPECT_FALSE(handle.socket()); @@ -2328,11 +2452,12 @@ ClientSocketHandle handle; TestCompletionCallback callback; int rv = handle.Init( - "a", params_, LOWEST, SocketTag(), + TestGroupId("a"), params_, LOWEST, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, callback.callback(), ClientSocketPool::ProxyAuthCallback(), pool_.get(), NetLogWithSource()); ASSERT_THAT(rv, IsError(ERR_IO_PENDING)); - EXPECT_EQ(LOAD_STATE_CONNECTING, pool_->GetLoadState("a", &handle)); + EXPECT_EQ(LOAD_STATE_CONNECTING, + pool_->GetLoadState(TestGroupId("a"), &handle)); ASSERT_THAT(callback.WaitForResult(), IsOk()); // Use and release the socket. @@ -2348,16 +2473,16 @@ // synchronously. BoundTestNetLog log; rv = handle.Init( - "a", params_, LOWEST, SocketTag(), + TestGroupId("a"), params_, LOWEST, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, CompletionOnceCallback(), ClientSocketPool::ProxyAuthCallback(), pool_.get(), log.bound()); ASSERT_THAT(rv, IsOk()); EXPECT_TRUE(handle.is_reused()); TestLoadTimingInfoConnectedReused(handle); - ASSERT_TRUE(pool_->HasGroup("a")); - EXPECT_EQ(0u, pool_->IdleSocketCountInGroup("a")); - EXPECT_EQ(1, pool_->NumActiveSocketsInGroup("a")); + ASSERT_TRUE(pool_->HasGroup(TestGroupId("a"))); + EXPECT_EQ(0u, pool_->IdleSocketCountInGroup(TestGroupId("a"))); + EXPECT_EQ(1, pool_->NumActiveSocketsInGroup(TestGroupId("a"))); TestNetLogEntry::List entries; log.GetEntries(&entries); @@ -2379,20 +2504,22 @@ ClientSocketHandle handle; TestCompletionCallback callback; int rv = handle.Init( - "a", params_, LOWEST, SocketTag(), + TestGroupId("a"), params_, LOWEST, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, callback.callback(), ClientSocketPool::ProxyAuthCallback(), pool_.get(), NetLogWithSource()); ASSERT_THAT(rv, IsError(ERR_IO_PENDING)); - EXPECT_EQ(LOAD_STATE_CONNECTING, pool_->GetLoadState("a", &handle)); + EXPECT_EQ(LOAD_STATE_CONNECTING, + pool_->GetLoadState(TestGroupId("a"), &handle)); ClientSocketHandle handle2; TestCompletionCallback callback2; - rv = handle2.Init("a", params_, LOWEST, SocketTag(), + rv = handle2.Init(TestGroupId("a"), params_, LOWEST, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, callback2.callback(), ClientSocketPool::ProxyAuthCallback(), pool_.get(), NetLogWithSource()); ASSERT_THAT(rv, IsError(ERR_IO_PENDING)); - EXPECT_EQ(LOAD_STATE_CONNECTING, pool_->GetLoadState("a", &handle2)); + EXPECT_EQ(LOAD_STATE_CONNECTING, + pool_->GetLoadState(TestGroupId("a"), &handle2)); // Cancel one of the requests. Wait for the other, which will get the first // job. Release the socket. Run the loop again to make sure the second @@ -2419,7 +2546,7 @@ // A new socket will be created rather than reusing the idle one. BoundTestNetLog log; TestCompletionCallback callback3; - rv = handle.Init("a", params_, LOWEST, SocketTag(), + rv = handle.Init(TestGroupId("a"), params_, LOWEST, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, callback3.callback(), ClientSocketPool::ProxyAuthCallback(), pool_.get(), log.bound()); @@ -2428,9 +2555,9 @@ EXPECT_FALSE(handle.is_reused()); // Make sure the idle socket is closed. - ASSERT_TRUE(pool_->HasGroup("a")); - EXPECT_EQ(0u, pool_->IdleSocketCountInGroup("a")); - EXPECT_EQ(1, pool_->NumActiveSocketsInGroup("a")); + ASSERT_TRUE(pool_->HasGroup(TestGroupId("a"))); + EXPECT_EQ(0u, pool_->IdleSocketCountInGroup(TestGroupId("a"))); + EXPECT_EQ(1, pool_->NumActiveSocketsInGroup(TestGroupId("a"))); TestNetLogEntry::List entries; log.GetEntries(&entries); @@ -2453,14 +2580,14 @@ ClientSocketHandle handle; TestCompletionCallback callback; int rv = handle.Init( - "a", params_, LOWEST, SocketTag(), + TestGroupId("a"), params_, LOWEST, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, callback.callback(), ClientSocketPool::ProxyAuthCallback(), pool_.get(), NetLogWithSource()); EXPECT_THAT(rv, IsOk()); ClientSocketHandle handle2; TestCompletionCallback callback2; - rv = handle2.Init("a", params_, LOWEST, SocketTag(), + rv = handle2.Init(TestGroupId("a"), params_, LOWEST, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, callback2.callback(), ClientSocketPool::ProxyAuthCallback(), pool_.get(), NetLogWithSource()); @@ -2468,7 +2595,7 @@ ClientSocketHandle handle3; TestCompletionCallback callback3; - rv = handle3.Init("a", params_, LOWEST, SocketTag(), + rv = handle3.Init(TestGroupId("a"), params_, LOWEST, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, callback3.callback(), ClientSocketPool::ProxyAuthCallback(), pool_.get(), NetLogWithSource()); @@ -2476,7 +2603,7 @@ ClientSocketHandle handle4; TestCompletionCallback callback4; - rv = handle4.Init("a", params_, LOWEST, SocketTag(), + rv = handle4.Init(TestGroupId("a"), params_, LOWEST, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, callback4.callback(), ClientSocketPool::ProxyAuthCallback(), pool_.get(), NetLogWithSource()); @@ -2514,29 +2641,31 @@ TestCompletionCallback callback_b[4]; for (int i = 0; i < 2; ++i) { - EXPECT_EQ(OK, handle_a[i].Init("a", params_, LOWEST, SocketTag(), - ClientSocketPool::RespectLimits::ENABLED, - callback_a[i].callback(), - ClientSocketPool::ProxyAuthCallback(), - pool_.get(), NetLogWithSource())); - EXPECT_EQ(OK, handle_b[i].Init("b", params_, LOWEST, SocketTag(), - ClientSocketPool::RespectLimits::ENABLED, - callback_b[i].callback(), - ClientSocketPool::ProxyAuthCallback(), - pool_.get(), NetLogWithSource())); + EXPECT_EQ( + OK, handle_a[i].Init(TestGroupId("a"), params_, LOWEST, SocketTag(), + ClientSocketPool::RespectLimits::ENABLED, + callback_a[i].callback(), + ClientSocketPool::ProxyAuthCallback(), pool_.get(), + NetLogWithSource())); + EXPECT_EQ( + OK, handle_b[i].Init(TestGroupId("b"), params_, LOWEST, SocketTag(), + ClientSocketPool::RespectLimits::ENABLED, + callback_b[i].callback(), + ClientSocketPool::ProxyAuthCallback(), pool_.get(), + NetLogWithSource())); } // Make 4 pending requests, 2 per group. for (int i = 2; i < 4; ++i) { EXPECT_EQ(ERR_IO_PENDING, - handle_a[i].Init("a", params_, LOWEST, SocketTag(), + handle_a[i].Init(TestGroupId("a"), params_, LOWEST, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, callback_a[i].callback(), ClientSocketPool::ProxyAuthCallback(), pool_.get(), NetLogWithSource())); EXPECT_EQ(ERR_IO_PENDING, - handle_b[i].Init("b", params_, LOWEST, SocketTag(), + handle_b[i].Init(TestGroupId("b"), params_, LOWEST, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, callback_b[i].callback(), ClientSocketPool::ProxyAuthCallback(), @@ -2573,10 +2702,14 @@ connect_job_factory_->set_job_type(TestConnectJob::kMockPendingJob); - EXPECT_THAT(StartRequest("a", DEFAULT_PRIORITY), IsError(ERR_IO_PENDING)); - EXPECT_THAT(StartRequest("a", DEFAULT_PRIORITY), IsError(ERR_IO_PENDING)); - EXPECT_THAT(StartRequest("a", DEFAULT_PRIORITY), IsError(ERR_IO_PENDING)); - EXPECT_THAT(StartRequest("a", DEFAULT_PRIORITY), IsError(ERR_IO_PENDING)); + EXPECT_THAT(StartRequest(TestGroupId("a"), DEFAULT_PRIORITY), + IsError(ERR_IO_PENDING)); + EXPECT_THAT(StartRequest(TestGroupId("a"), DEFAULT_PRIORITY), + IsError(ERR_IO_PENDING)); + EXPECT_THAT(StartRequest(TestGroupId("a"), DEFAULT_PRIORITY), + IsError(ERR_IO_PENDING)); + EXPECT_THAT(StartRequest(TestGroupId("a"), DEFAULT_PRIORITY), + IsError(ERR_IO_PENDING)); EXPECT_THAT((*requests())[0]->WaitForResult(), IsOk()); EXPECT_THAT((*requests())[1]->WaitForResult(), IsOk()); @@ -2624,12 +2757,12 @@ handle_.Reset(); scoped_refptr<TestSocketParams> con_params(new TestSocketParams()); - EXPECT_EQ(expected_result_, - handle2_.Init("a", con_params, DEFAULT_PRIORITY, SocketTag(), - ClientSocketPool::RespectLimits::ENABLED, - CompletionOnceCallback(), - ClientSocketPool::ProxyAuthCallback(), pool_, - NetLogWithSource())); + EXPECT_EQ( + expected_result_, + handle2_.Init( + TestGroupId("a"), con_params, DEFAULT_PRIORITY, SocketTag(), + ClientSocketPool::RespectLimits::ENABLED, CompletionOnceCallback(), + ClientSocketPool::ProxyAuthCallback(), pool_, NetLogWithSource())); } TestClientSocketPool* const pool_; @@ -2643,9 +2776,9 @@ TEST_F(ClientSocketPoolBaseTest, AdditionalErrorSocketsDontUseSlot) { CreatePool(kDefaultMaxSockets, kDefaultMaxSocketsPerGroup); - EXPECT_THAT(StartRequest("b", DEFAULT_PRIORITY), IsOk()); - EXPECT_THAT(StartRequest("a", DEFAULT_PRIORITY), IsOk()); - EXPECT_THAT(StartRequest("b", DEFAULT_PRIORITY), IsOk()); + EXPECT_THAT(StartRequest(TestGroupId("b"), DEFAULT_PRIORITY), IsOk()); + EXPECT_THAT(StartRequest(TestGroupId("a"), DEFAULT_PRIORITY), IsOk()); + EXPECT_THAT(StartRequest(TestGroupId("b"), DEFAULT_PRIORITY), IsOk()); EXPECT_EQ(static_cast<int>(requests_size()), client_socket_factory_.allocation_count()); @@ -2655,8 +2788,8 @@ TestReleasingSocketRequest req(pool_.get(), OK, false); EXPECT_EQ( ERR_IO_PENDING, - req.handle()->Init("a", params_, DEFAULT_PRIORITY, SocketTag(), - ClientSocketPool::RespectLimits::ENABLED, + req.handle()->Init(TestGroupId("a"), params_, DEFAULT_PRIORITY, + SocketTag(), ClientSocketPool::RespectLimits::ENABLED, req.callback(), ClientSocketPool::ProxyAuthCallback(), pool_.get(), NetLogWithSource())); // The next job should complete synchronously @@ -2686,7 +2819,7 @@ TestCompletionCallback callback; EXPECT_EQ( ERR_IO_PENDING, - handle.Init("a", params_, DEFAULT_PRIORITY, SocketTag(), + handle.Init(TestGroupId("a"), params_, DEFAULT_PRIORITY, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, callback.callback(), ClientSocketPool::ProxyAuthCallback(), pool_.get(), NetLogWithSource())); @@ -2705,7 +2838,7 @@ TestCompletionCallback callback; EXPECT_EQ( ERR_IO_PENDING, - handle.Init("a", params_, DEFAULT_PRIORITY, SocketTag(), + handle.Init(TestGroupId("a"), params_, DEFAULT_PRIORITY, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, callback.callback(), ClientSocketPool::ProxyAuthCallback(), pool_.get(), NetLogWithSource())); @@ -2719,7 +2852,7 @@ EXPECT_EQ( ERR_IO_PENDING, - handle.Init("a", params_, DEFAULT_PRIORITY, SocketTag(), + handle.Init(TestGroupId("a"), params_, DEFAULT_PRIORITY, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, callback.callback(), ClientSocketPool::ProxyAuthCallback(), pool_.get(), NetLogWithSource())); @@ -2729,10 +2862,10 @@ class ConnectWithinCallback : public TestCompletionCallbackBase { public: - ConnectWithinCallback(const std::string& group_name, + ConnectWithinCallback(const ClientSocketPool::GroupId& group_id, const scoped_refptr<TestSocketParams>& params, TestClientSocketPool* pool) - : group_name_(group_name), params_(params), pool_(pool) {} + : group_id_(group_id), params_(params), pool_(pool) {} ~ConnectWithinCallback() override = default; @@ -2749,14 +2882,14 @@ void OnComplete(int result) { SetResult(result); EXPECT_EQ(ERR_IO_PENDING, - handle_.Init(group_name_, params_, DEFAULT_PRIORITY, SocketTag(), + handle_.Init(group_id_, params_, DEFAULT_PRIORITY, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, nested_callback_.callback(), ClientSocketPool::ProxyAuthCallback(), pool_, NetLogWithSource())); } - const std::string group_name_; + const ClientSocketPool::GroupId group_id_; const scoped_refptr<TestSocketParams> params_; TestClientSocketPool* const pool_; ClientSocketHandle handle_; @@ -2772,10 +2905,10 @@ connect_job_factory_->set_job_type(TestConnectJob::kMockWaitingJob); ClientSocketHandle handle; - ConnectWithinCallback callback("a", params_, pool_.get()); + ConnectWithinCallback callback(TestGroupId("a"), params_, pool_.get()); EXPECT_EQ( ERR_IO_PENDING, - handle.Init("a", params_, DEFAULT_PRIORITY, SocketTag(), + handle.Init(TestGroupId("a"), params_, DEFAULT_PRIORITY, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, callback.callback(), ClientSocketPool::ProxyAuthCallback(), pool_.get(), NetLogWithSource())); @@ -2797,7 +2930,7 @@ TestCompletionCallback callback; EXPECT_EQ( ERR_IO_PENDING, - handle.Init("bar", params_, DEFAULT_PRIORITY, SocketTag(), + handle.Init(TestGroupId("bar"), params_, DEFAULT_PRIORITY, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, callback.callback(), ClientSocketPool::ProxyAuthCallback(), pool_.get(), NetLogWithSource())); @@ -2827,7 +2960,7 @@ TestCompletionCallback callback; EXPECT_EQ( ERR_IO_PENDING, - handle.Init("bar", params_, DEFAULT_PRIORITY, SocketTag(), + handle.Init(TestGroupId("bar"), params_, DEFAULT_PRIORITY, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, callback.callback(), ClientSocketPool::ProxyAuthCallback(), pool_.get(), NetLogWithSource())); @@ -2859,7 +2992,7 @@ TestCompletionCallback callback; EXPECT_EQ( ERR_IO_PENDING, - handle.Init("bar", params_, DEFAULT_PRIORITY, SocketTag(), + handle.Init(TestGroupId("bar"), params_, DEFAULT_PRIORITY, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, callback.callback(), ClientSocketPool::ProxyAuthCallback(), pool_.get(), NetLogWithSource())); @@ -2869,7 +3002,8 @@ ClientSocketHandle handles[kDefaultMaxSockets]; for (int i = 1; i < kDefaultMaxSockets; ++i) { TestCompletionCallback callback; - EXPECT_EQ(OK, handles[i].Init("bar", params_, DEFAULT_PRIORITY, SocketTag(), + EXPECT_EQ(OK, handles[i].Init(TestGroupId("bar"), params_, DEFAULT_PRIORITY, + SocketTag(), ClientSocketPool::RespectLimits::ENABLED, callback.callback(), ClientSocketPool::ProxyAuthCallback(), @@ -2899,14 +3033,14 @@ TestCompletionCallback callback; EXPECT_EQ( ERR_IO_PENDING, - handle.Init("bar", params_, DEFAULT_PRIORITY, SocketTag(), + handle.Init(TestGroupId("bar"), params_, DEFAULT_PRIORITY, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, callback.callback(), ClientSocketPool::ProxyAuthCallback(), pool_.get(), NetLogWithSource())); - ASSERT_TRUE(pool_->HasGroup("bar")); - EXPECT_EQ(1u, pool_->NumConnectJobsInGroup("bar")); - EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup("bar")); - EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup("bar")); + ASSERT_TRUE(pool_->HasGroup(TestGroupId("bar"))); + EXPECT_EQ(1u, pool_->NumConnectJobsInGroup(TestGroupId("bar"))); + EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup(TestGroupId("bar"))); + EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup(TestGroupId("bar"))); // Cancel the socket request. This should cancel the backup timer. Wait for // the backup time to see if it indeed got canceled. @@ -2914,8 +3048,8 @@ // Wait for the backup timer to fire (add some slop to ensure it fires) FastForwardBy(base::TimeDelta::FromMilliseconds( ClientSocketPool::kMaxConnectRetryIntervalMs / 2 * 3)); - ASSERT_TRUE(pool_->HasGroup("bar")); - EXPECT_EQ(1u, pool_->NumConnectJobsInGroup("bar")); + ASSERT_TRUE(pool_->HasGroup(TestGroupId("bar"))); + EXPECT_EQ(1u, pool_->NumConnectJobsInGroup(TestGroupId("bar"))); } TEST_F(ClientSocketPoolBaseTest, CancelBackupSocketAfterFinishingAllRequests) { @@ -2929,7 +3063,7 @@ TestCompletionCallback callback; EXPECT_EQ( ERR_IO_PENDING, - handle.Init("bar", params_, DEFAULT_PRIORITY, SocketTag(), + handle.Init(TestGroupId("bar"), params_, DEFAULT_PRIORITY, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, callback.callback(), ClientSocketPool::ProxyAuthCallback(), pool_.get(), NetLogWithSource())); @@ -2938,12 +3072,12 @@ TestCompletionCallback callback2; EXPECT_EQ( ERR_IO_PENDING, - handle2.Init("bar", params_, DEFAULT_PRIORITY, SocketTag(), + handle2.Init(TestGroupId("bar"), params_, DEFAULT_PRIORITY, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, callback2.callback(), ClientSocketPool::ProxyAuthCallback(), pool_.get(), NetLogWithSource())); - ASSERT_TRUE(pool_->HasGroup("bar")); - EXPECT_EQ(2u, pool_->NumConnectJobsInGroup("bar")); + ASSERT_TRUE(pool_->HasGroup(TestGroupId("bar"))); + EXPECT_EQ(2u, pool_->NumConnectJobsInGroup(TestGroupId("bar"))); // Cancel request 1 and then complete request 2. With the requests finished, // the backup timer should be cancelled. @@ -2966,7 +3100,7 @@ TestCompletionCallback callback; EXPECT_EQ( ERR_IO_PENDING, - handle1.Init("a", params_, DEFAULT_PRIORITY, SocketTag(), + handle1.Init(TestGroupId("a"), params_, DEFAULT_PRIORITY, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, callback.callback(), ClientSocketPool::ProxyAuthCallback(), pool_.get(), NetLogWithSource())); @@ -2974,20 +3108,20 @@ // No idle sockets, no pending jobs. EXPECT_EQ(0, pool_->IdleSocketCount()); - EXPECT_EQ(0u, pool_->NumConnectJobsInGroup("a")); + EXPECT_EQ(0u, pool_->NumConnectJobsInGroup(TestGroupId("a"))); // Create a second socket to the same host, but this one will wait. connect_job_factory_->set_job_type(TestConnectJob::kMockWaitingJob); ClientSocketHandle handle2; EXPECT_EQ( ERR_IO_PENDING, - handle2.Init("a", params_, DEFAULT_PRIORITY, SocketTag(), + handle2.Init(TestGroupId("a"), params_, DEFAULT_PRIORITY, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, callback.callback(), ClientSocketPool::ProxyAuthCallback(), pool_.get(), NetLogWithSource())); // No idle sockets, and one connecting job. EXPECT_EQ(0, pool_->IdleSocketCount()); - EXPECT_EQ(1u, pool_->NumConnectJobsInGroup("a")); + EXPECT_EQ(1u, pool_->NumConnectJobsInGroup(TestGroupId("a"))); // Return the first handle to the pool. This will initiate the delayed // binding. @@ -2997,17 +3131,17 @@ // Still no idle sockets, still one pending connect job. EXPECT_EQ(0, pool_->IdleSocketCount()); - EXPECT_EQ(1u, pool_->NumConnectJobsInGroup("a")); + EXPECT_EQ(1u, pool_->NumConnectJobsInGroup(TestGroupId("a"))); // The second socket connected, even though it was a Waiting Job. EXPECT_THAT(callback.WaitForResult(), IsOk()); // And we can see there is still one job waiting. - EXPECT_EQ(1u, pool_->NumConnectJobsInGroup("a")); + EXPECT_EQ(1u, pool_->NumConnectJobsInGroup(TestGroupId("a"))); // Finally, signal the waiting Connect. client_socket_factory_.SignalJobs(); - EXPECT_EQ(0u, pool_->NumConnectJobsInGroup("a")); + EXPECT_EQ(0u, pool_->NumConnectJobsInGroup(TestGroupId("a"))); base::RunLoop().RunUntilIdle(); } @@ -3022,7 +3156,7 @@ TestCompletionCallback callback; EXPECT_EQ( ERR_IO_PENDING, - handle1.Init("a", params_, DEFAULT_PRIORITY, SocketTag(), + handle1.Init(TestGroupId("a"), params_, DEFAULT_PRIORITY, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, callback.callback(), ClientSocketPool::ProxyAuthCallback(), pool_.get(), NetLogWithSource())); @@ -3030,20 +3164,20 @@ // No idle sockets, no pending jobs. EXPECT_EQ(0, pool_->IdleSocketCount()); - EXPECT_EQ(0u, pool_->NumConnectJobsInGroup("a")); + EXPECT_EQ(0u, pool_->NumConnectJobsInGroup(TestGroupId("a"))); // Create a second socket to the same host, but this one will wait. connect_job_factory_->set_job_type(TestConnectJob::kMockWaitingJob); ClientSocketHandle handle2; EXPECT_EQ( ERR_IO_PENDING, - handle2.Init("a", params_, DEFAULT_PRIORITY, SocketTag(), + handle2.Init(TestGroupId("a"), params_, DEFAULT_PRIORITY, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, callback.callback(), ClientSocketPool::ProxyAuthCallback(), pool_.get(), NetLogWithSource())); // No idle sockets, and one connecting job. EXPECT_EQ(0, pool_->IdleSocketCount()); - EXPECT_EQ(1u, pool_->NumConnectJobsInGroup("a")); + EXPECT_EQ(1u, pool_->NumConnectJobsInGroup(TestGroupId("a"))); // Return the first handle to the pool. This will initiate the delayed // binding. @@ -3053,17 +3187,17 @@ // Still no idle sockets, still one pending connect job. EXPECT_EQ(0, pool_->IdleSocketCount()); - EXPECT_EQ(1u, pool_->NumConnectJobsInGroup("a")); + EXPECT_EQ(1u, pool_->NumConnectJobsInGroup(TestGroupId("a"))); // The second socket connected, even though it was a Waiting Job. EXPECT_THAT(callback.WaitForResult(), IsOk()); // And we can see there is still one job waiting. - EXPECT_EQ(1u, pool_->NumConnectJobsInGroup("a")); + EXPECT_EQ(1u, pool_->NumConnectJobsInGroup(TestGroupId("a"))); // Finally, signal the waiting Connect. client_socket_factory_.SignalJobs(); - EXPECT_EQ(0u, pool_->NumConnectJobsInGroup("a")); + EXPECT_EQ(0u, pool_->NumConnectJobsInGroup(TestGroupId("a"))); base::RunLoop().RunUntilIdle(); } @@ -3080,7 +3214,7 @@ TestCompletionCallback callback; EXPECT_EQ( ERR_IO_PENDING, - handle1.Init("a", params_, DEFAULT_PRIORITY, SocketTag(), + handle1.Init(TestGroupId("a"), params_, DEFAULT_PRIORITY, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, callback.callback(), ClientSocketPool::ProxyAuthCallback(), pool_.get(), NetLogWithSource())); @@ -3088,20 +3222,20 @@ // No idle sockets, no pending jobs. EXPECT_EQ(0, pool_->IdleSocketCount()); - EXPECT_EQ(0u, pool_->NumConnectJobsInGroup("a")); + EXPECT_EQ(0u, pool_->NumConnectJobsInGroup(TestGroupId("a"))); // Create a second socket to the same host, but this one will wait. connect_job_factory_->set_job_type(TestConnectJob::kMockWaitingJob); ClientSocketHandle handle2; EXPECT_EQ( ERR_IO_PENDING, - handle2.Init("a", params_, DEFAULT_PRIORITY, SocketTag(), + handle2.Init(TestGroupId("a"), params_, DEFAULT_PRIORITY, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, callback.callback(), ClientSocketPool::ProxyAuthCallback(), pool_.get(), NetLogWithSource())); // No idle sockets, and one connecting job. EXPECT_EQ(0, pool_->IdleSocketCount()); - EXPECT_EQ(1u, pool_->NumConnectJobsInGroup("a")); + EXPECT_EQ(1u, pool_->NumConnectJobsInGroup(TestGroupId("a"))); // Return the first handle to the pool. This will initiate the delayed // binding. @@ -3111,17 +3245,17 @@ // Still no idle sockets, still one pending connect job. EXPECT_EQ(0, pool_->IdleSocketCount()); - EXPECT_EQ(1u, pool_->NumConnectJobsInGroup("a")); + EXPECT_EQ(1u, pool_->NumConnectJobsInGroup(TestGroupId("a"))); // The second socket connected, even though it was a Waiting Job. EXPECT_THAT(callback.WaitForResult(), IsOk()); // And we can see there is still one job waiting. - EXPECT_EQ(1u, pool_->NumConnectJobsInGroup("a")); + EXPECT_EQ(1u, pool_->NumConnectJobsInGroup(TestGroupId("a"))); // Finally, signal the waiting Connect. client_socket_factory_.SignalJobs(); - EXPECT_EQ(0u, pool_->NumConnectJobsInGroup("a")); + EXPECT_EQ(0u, pool_->NumConnectJobsInGroup(TestGroupId("a"))); base::RunLoop().RunUntilIdle(); } @@ -3141,11 +3275,11 @@ TestCompletionCallback callback1; EXPECT_EQ( ERR_IO_PENDING, - handle1.Init("a", params_, DEFAULT_PRIORITY, SocketTag(), + handle1.Init(TestGroupId("a"), params_, DEFAULT_PRIORITY, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, callback1.callback(), ClientSocketPool::ProxyAuthCallback(), pool_.get(), NetLogWithSource())); - EXPECT_EQ(1u, pool_->NumConnectJobsInGroup("a")); + EXPECT_EQ(1u, pool_->NumConnectJobsInGroup(TestGroupId("a"))); // Make the second request synchronously fail. This should make the Group // empty. @@ -3156,16 +3290,16 @@ // when created. EXPECT_EQ( ERR_IO_PENDING, - handle2.Init("a", params_, DEFAULT_PRIORITY, SocketTag(), + handle2.Init(TestGroupId("a"), params_, DEFAULT_PRIORITY, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, callback2.callback(), ClientSocketPool::ProxyAuthCallback(), pool_.get(), NetLogWithSource())); - EXPECT_EQ(1u, pool_->NumConnectJobsInGroup("a")); + EXPECT_EQ(1u, pool_->NumConnectJobsInGroup(TestGroupId("a"))); EXPECT_THAT(callback1.WaitForResult(), IsError(ERR_CONNECTION_FAILED)); EXPECT_THAT(callback2.WaitForResult(), IsError(ERR_CONNECTION_FAILED)); - EXPECT_FALSE(pool_->HasGroup("a")); + EXPECT_FALSE(pool_->HasGroup(TestGroupId("a"))); } TEST_F(ClientSocketPoolBaseTest, PreferUsedSocketToUnusedSocket) { @@ -3177,7 +3311,7 @@ TestCompletionCallback callback1; EXPECT_EQ( ERR_IO_PENDING, - handle1.Init("a", params_, DEFAULT_PRIORITY, SocketTag(), + handle1.Init(TestGroupId("a"), params_, DEFAULT_PRIORITY, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, callback1.callback(), ClientSocketPool::ProxyAuthCallback(), pool_.get(), NetLogWithSource())); @@ -3186,7 +3320,7 @@ TestCompletionCallback callback2; EXPECT_EQ( ERR_IO_PENDING, - handle2.Init("a", params_, DEFAULT_PRIORITY, SocketTag(), + handle2.Init(TestGroupId("a"), params_, DEFAULT_PRIORITY, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, callback2.callback(), ClientSocketPool::ProxyAuthCallback(), pool_.get(), NetLogWithSource())); @@ -3194,7 +3328,7 @@ TestCompletionCallback callback3; EXPECT_EQ( ERR_IO_PENDING, - handle3.Init("a", params_, DEFAULT_PRIORITY, SocketTag(), + handle3.Init(TestGroupId("a"), params_, DEFAULT_PRIORITY, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, callback3.callback(), ClientSocketPool::ProxyAuthCallback(), pool_.get(), NetLogWithSource())); @@ -3213,21 +3347,21 @@ handle2.Reset(); handle3.Reset(); - EXPECT_EQ(OK, handle1.Init("a", params_, DEFAULT_PRIORITY, SocketTag(), - ClientSocketPool::RespectLimits::ENABLED, - callback1.callback(), - ClientSocketPool::ProxyAuthCallback(), pool_.get(), - NetLogWithSource())); - EXPECT_EQ(OK, handle2.Init("a", params_, DEFAULT_PRIORITY, SocketTag(), - ClientSocketPool::RespectLimits::ENABLED, - callback2.callback(), - ClientSocketPool::ProxyAuthCallback(), pool_.get(), - NetLogWithSource())); - EXPECT_EQ(OK, handle3.Init("a", params_, DEFAULT_PRIORITY, SocketTag(), - ClientSocketPool::RespectLimits::ENABLED, - callback3.callback(), - ClientSocketPool::ProxyAuthCallback(), pool_.get(), - NetLogWithSource())); + EXPECT_EQ(OK, handle1.Init( + TestGroupId("a"), params_, DEFAULT_PRIORITY, SocketTag(), + ClientSocketPool::RespectLimits::ENABLED, + callback1.callback(), ClientSocketPool::ProxyAuthCallback(), + pool_.get(), NetLogWithSource())); + EXPECT_EQ(OK, handle2.Init( + TestGroupId("a"), params_, DEFAULT_PRIORITY, SocketTag(), + ClientSocketPool::RespectLimits::ENABLED, + callback2.callback(), ClientSocketPool::ProxyAuthCallback(), + pool_.get(), NetLogWithSource())); + EXPECT_EQ(OK, handle3.Init( + TestGroupId("a"), params_, DEFAULT_PRIORITY, SocketTag(), + ClientSocketPool::RespectLimits::ENABLED, + callback3.callback(), ClientSocketPool::ProxyAuthCallback(), + pool_.get(), NetLogWithSource())); EXPECT_TRUE(handle1.socket()->WasEverUsed()); EXPECT_TRUE(handle2.socket()->WasEverUsed()); @@ -3238,19 +3372,19 @@ CreatePool(kDefaultMaxSockets, kDefaultMaxSocketsPerGroup); connect_job_factory_->set_job_type(TestConnectJob::kMockPendingJob); - pool_->RequestSockets("a", ¶ms_, 2, NetLogWithSource()); + pool_->RequestSockets(TestGroupId("a"), ¶ms_, 2, NetLogWithSource()); - ASSERT_TRUE(pool_->HasGroup("a")); - EXPECT_EQ(2u, pool_->NumConnectJobsInGroup("a")); - EXPECT_EQ(2u, pool_->NumNeverAssignedConnectJobsInGroup("a")); - EXPECT_EQ(2u, pool_->NumUnassignedConnectJobsInGroup("a")); - EXPECT_EQ(0u, pool_->IdleSocketCountInGroup("a")); + ASSERT_TRUE(pool_->HasGroup(TestGroupId("a"))); + EXPECT_EQ(2u, pool_->NumConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(2u, pool_->NumNeverAssignedConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(2u, pool_->NumUnassignedConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(0u, pool_->IdleSocketCountInGroup(TestGroupId("a"))); ClientSocketHandle handle1; TestCompletionCallback callback1; EXPECT_EQ( ERR_IO_PENDING, - handle1.Init("a", params_, DEFAULT_PRIORITY, SocketTag(), + handle1.Init(TestGroupId("a"), params_, DEFAULT_PRIORITY, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, callback1.callback(), ClientSocketPool::ProxyAuthCallback(), pool_.get(), NetLogWithSource())); @@ -3259,25 +3393,25 @@ TestCompletionCallback callback2; EXPECT_EQ( ERR_IO_PENDING, - handle2.Init("a", params_, DEFAULT_PRIORITY, SocketTag(), + handle2.Init(TestGroupId("a"), params_, DEFAULT_PRIORITY, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, callback2.callback(), ClientSocketPool::ProxyAuthCallback(), pool_.get(), NetLogWithSource())); - EXPECT_EQ(2u, pool_->NumConnectJobsInGroup("a")); - EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup("a")); - EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup("a")); - EXPECT_EQ(0u, pool_->IdleSocketCountInGroup("a")); + EXPECT_EQ(2u, pool_->NumConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(0u, pool_->IdleSocketCountInGroup(TestGroupId("a"))); EXPECT_THAT(callback1.WaitForResult(), IsOk()); EXPECT_THAT(callback2.WaitForResult(), IsOk()); handle1.Reset(); handle2.Reset(); - EXPECT_EQ(0u, pool_->NumConnectJobsInGroup("a")); - EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup("a")); - EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup("a")); - EXPECT_EQ(2u, pool_->IdleSocketCountInGroup("a")); + EXPECT_EQ(0u, pool_->NumConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(2u, pool_->IdleSocketCountInGroup(TestGroupId("a"))); } TEST_F(ClientSocketPoolBaseTest, RequestSocketsWhenAlreadyHaveAConnectJob) { @@ -3288,47 +3422,47 @@ TestCompletionCallback callback1; EXPECT_EQ( ERR_IO_PENDING, - handle1.Init("a", params_, DEFAULT_PRIORITY, SocketTag(), + handle1.Init(TestGroupId("a"), params_, DEFAULT_PRIORITY, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, callback1.callback(), ClientSocketPool::ProxyAuthCallback(), pool_.get(), NetLogWithSource())); - ASSERT_TRUE(pool_->HasGroup("a")); - EXPECT_EQ(1u, pool_->NumConnectJobsInGroup("a")); - EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup("a")); - EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup("a")); - EXPECT_EQ(0u, pool_->IdleSocketCountInGroup("a")); + ASSERT_TRUE(pool_->HasGroup(TestGroupId("a"))); + EXPECT_EQ(1u, pool_->NumConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(0u, pool_->IdleSocketCountInGroup(TestGroupId("a"))); - pool_->RequestSockets("a", ¶ms_, 2, NetLogWithSource()); + pool_->RequestSockets(TestGroupId("a"), ¶ms_, 2, NetLogWithSource()); - EXPECT_EQ(2u, pool_->NumConnectJobsInGroup("a")); - EXPECT_EQ(1u, pool_->NumNeverAssignedConnectJobsInGroup("a")); - EXPECT_EQ(1u, pool_->NumUnassignedConnectJobsInGroup("a")); - EXPECT_EQ(0u, pool_->IdleSocketCountInGroup("a")); + EXPECT_EQ(2u, pool_->NumConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(1u, pool_->NumNeverAssignedConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(1u, pool_->NumUnassignedConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(0u, pool_->IdleSocketCountInGroup(TestGroupId("a"))); ClientSocketHandle handle2; TestCompletionCallback callback2; EXPECT_EQ( ERR_IO_PENDING, - handle2.Init("a", params_, DEFAULT_PRIORITY, SocketTag(), + handle2.Init(TestGroupId("a"), params_, DEFAULT_PRIORITY, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, callback2.callback(), ClientSocketPool::ProxyAuthCallback(), pool_.get(), NetLogWithSource())); - EXPECT_EQ(2u, pool_->NumConnectJobsInGroup("a")); - EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup("a")); - EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup("a")); - EXPECT_EQ(0u, pool_->IdleSocketCountInGroup("a")); + EXPECT_EQ(2u, pool_->NumConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(0u, pool_->IdleSocketCountInGroup(TestGroupId("a"))); EXPECT_THAT(callback1.WaitForResult(), IsOk()); EXPECT_THAT(callback2.WaitForResult(), IsOk()); handle1.Reset(); handle2.Reset(); - EXPECT_EQ(0u, pool_->NumConnectJobsInGroup("a")); - EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup("a")); - EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup("a")); - EXPECT_EQ(2u, pool_->IdleSocketCountInGroup("a")); + EXPECT_EQ(0u, pool_->NumConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(2u, pool_->IdleSocketCountInGroup(TestGroupId("a"))); } TEST_F(ClientSocketPoolBaseTest, @@ -3340,7 +3474,7 @@ TestCompletionCallback callback1; EXPECT_EQ( ERR_IO_PENDING, - handle1.Init("a", params_, DEFAULT_PRIORITY, SocketTag(), + handle1.Init(TestGroupId("a"), params_, DEFAULT_PRIORITY, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, callback1.callback(), ClientSocketPool::ProxyAuthCallback(), pool_.get(), NetLogWithSource())); @@ -3349,7 +3483,7 @@ TestCompletionCallback callback2; EXPECT_EQ( ERR_IO_PENDING, - handle2.Init("a", params_, DEFAULT_PRIORITY, SocketTag(), + handle2.Init(TestGroupId("a"), params_, DEFAULT_PRIORITY, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, callback2.callback(), ClientSocketPool::ProxyAuthCallback(), pool_.get(), NetLogWithSource())); @@ -3358,23 +3492,23 @@ TestCompletionCallback callback3; EXPECT_EQ( ERR_IO_PENDING, - handle3.Init("a", params_, DEFAULT_PRIORITY, SocketTag(), + handle3.Init(TestGroupId("a"), params_, DEFAULT_PRIORITY, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, callback3.callback(), ClientSocketPool::ProxyAuthCallback(), pool_.get(), NetLogWithSource())); - ASSERT_TRUE(pool_->HasGroup("a")); - EXPECT_EQ(3u, pool_->NumConnectJobsInGroup("a")); - EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup("a")); - EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup("a")); - EXPECT_EQ(0u, pool_->IdleSocketCountInGroup("a")); + ASSERT_TRUE(pool_->HasGroup(TestGroupId("a"))); + EXPECT_EQ(3u, pool_->NumConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(0u, pool_->IdleSocketCountInGroup(TestGroupId("a"))); - pool_->RequestSockets("a", ¶ms_, 2, NetLogWithSource()); + pool_->RequestSockets(TestGroupId("a"), ¶ms_, 2, NetLogWithSource()); - EXPECT_EQ(3u, pool_->NumConnectJobsInGroup("a")); - EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup("a")); - EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup("a")); - EXPECT_EQ(0u, pool_->IdleSocketCountInGroup("a")); + EXPECT_EQ(3u, pool_->NumConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(0u, pool_->IdleSocketCountInGroup(TestGroupId("a"))); EXPECT_THAT(callback1.WaitForResult(), IsOk()); EXPECT_THAT(callback2.WaitForResult(), IsOk()); @@ -3383,59 +3517,66 @@ handle2.Reset(); handle3.Reset(); - EXPECT_EQ(0u, pool_->NumConnectJobsInGroup("a")); - EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup("a")); - EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup("a")); - EXPECT_EQ(3u, pool_->IdleSocketCountInGroup("a")); + EXPECT_EQ(0u, pool_->NumConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(3u, pool_->IdleSocketCountInGroup(TestGroupId("a"))); } TEST_F(ClientSocketPoolBaseTest, RequestSocketsAtMaxSocketLimit) { CreatePool(kDefaultMaxSockets, kDefaultMaxSockets); connect_job_factory_->set_job_type(TestConnectJob::kMockPendingJob); - ASSERT_FALSE(pool_->HasGroup("a")); + ASSERT_FALSE(pool_->HasGroup(TestGroupId("a"))); - pool_->RequestSockets("a", ¶ms_, kDefaultMaxSockets, NetLogWithSource()); + pool_->RequestSockets(TestGroupId("a"), ¶ms_, kDefaultMaxSockets, + NetLogWithSource()); - ASSERT_TRUE(pool_->HasGroup("a")); + ASSERT_TRUE(pool_->HasGroup(TestGroupId("a"))); EXPECT_EQ(kDefaultMaxSockets, - static_cast<int>(pool_->NumConnectJobsInGroup("a"))); + static_cast<int>(pool_->NumConnectJobsInGroup(TestGroupId("a")))); EXPECT_EQ(kDefaultMaxSockets, - static_cast<int>(pool_->NumNeverAssignedConnectJobsInGroup("a"))); + static_cast<int>( + pool_->NumNeverAssignedConnectJobsInGroup(TestGroupId("a")))); EXPECT_EQ(kDefaultMaxSockets, - static_cast<int>(pool_->NumUnassignedConnectJobsInGroup("a"))); + static_cast<int>( + pool_->NumUnassignedConnectJobsInGroup(TestGroupId("a")))); - ASSERT_FALSE(pool_->HasGroup("b")); + ASSERT_FALSE(pool_->HasGroup(TestGroupId("b"))); - pool_->RequestSockets("b", ¶ms_, kDefaultMaxSockets, NetLogWithSource()); + pool_->RequestSockets(TestGroupId("b"), ¶ms_, kDefaultMaxSockets, + NetLogWithSource()); - ASSERT_FALSE(pool_->HasGroup("b")); + ASSERT_FALSE(pool_->HasGroup(TestGroupId("b"))); } TEST_F(ClientSocketPoolBaseTest, RequestSocketsHitMaxSocketLimit) { CreatePool(kDefaultMaxSockets, kDefaultMaxSockets); connect_job_factory_->set_job_type(TestConnectJob::kMockPendingJob); - ASSERT_FALSE(pool_->HasGroup("a")); + ASSERT_FALSE(pool_->HasGroup(TestGroupId("a"))); - pool_->RequestSockets("a", ¶ms_, kDefaultMaxSockets - 1, + pool_->RequestSockets(TestGroupId("a"), ¶ms_, kDefaultMaxSockets - 1, NetLogWithSource()); - ASSERT_TRUE(pool_->HasGroup("a")); + ASSERT_TRUE(pool_->HasGroup(TestGroupId("a"))); EXPECT_EQ(kDefaultMaxSockets - 1, - static_cast<int>(pool_->NumConnectJobsInGroup("a"))); + static_cast<int>(pool_->NumConnectJobsInGroup(TestGroupId("a")))); EXPECT_EQ(kDefaultMaxSockets - 1, - static_cast<int>(pool_->NumNeverAssignedConnectJobsInGroup("a"))); + static_cast<int>( + pool_->NumNeverAssignedConnectJobsInGroup(TestGroupId("a")))); EXPECT_EQ(kDefaultMaxSockets - 1, - static_cast<int>(pool_->NumUnassignedConnectJobsInGroup("a"))); + static_cast<int>( + pool_->NumUnassignedConnectJobsInGroup(TestGroupId("a")))); EXPECT_FALSE(pool_->IsStalled()); - ASSERT_FALSE(pool_->HasGroup("b")); + ASSERT_FALSE(pool_->HasGroup(TestGroupId("b"))); - pool_->RequestSockets("b", ¶ms_, kDefaultMaxSockets, NetLogWithSource()); + pool_->RequestSockets(TestGroupId("b"), ¶ms_, kDefaultMaxSockets, + NetLogWithSource()); - ASSERT_TRUE(pool_->HasGroup("b")); - EXPECT_EQ(1u, pool_->NumConnectJobsInGroup("b")); + ASSERT_TRUE(pool_->HasGroup(TestGroupId("b"))); + EXPECT_EQ(1u, pool_->NumConnectJobsInGroup(TestGroupId("b"))); EXPECT_FALSE(pool_->IsStalled()); } @@ -3447,25 +3588,25 @@ TestCompletionCallback callback1; EXPECT_EQ( ERR_IO_PENDING, - handle1.Init("a", params_, DEFAULT_PRIORITY, SocketTag(), + handle1.Init(TestGroupId("a"), params_, DEFAULT_PRIORITY, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, callback1.callback(), ClientSocketPool::ProxyAuthCallback(), pool_.get(), NetLogWithSource())); ASSERT_THAT(callback1.WaitForResult(), IsOk()); handle1.Reset(); - ASSERT_TRUE(pool_->HasGroup("a")); - EXPECT_EQ(0u, pool_->NumConnectJobsInGroup("a")); - EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup("a")); - EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup("a")); - EXPECT_EQ(1u, pool_->IdleSocketCountInGroup("a")); + ASSERT_TRUE(pool_->HasGroup(TestGroupId("a"))); + EXPECT_EQ(0u, pool_->NumConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(1u, pool_->IdleSocketCountInGroup(TestGroupId("a"))); - pool_->RequestSockets("a", ¶ms_, 2, NetLogWithSource()); + pool_->RequestSockets(TestGroupId("a"), ¶ms_, 2, NetLogWithSource()); - EXPECT_EQ(1u, pool_->NumConnectJobsInGroup("a")); - EXPECT_EQ(1u, pool_->NumNeverAssignedConnectJobsInGroup("a")); - EXPECT_EQ(1u, pool_->NumUnassignedConnectJobsInGroup("a")); - EXPECT_EQ(1u, pool_->IdleSocketCountInGroup("a")); + EXPECT_EQ(1u, pool_->NumConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(1u, pool_->NumNeverAssignedConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(1u, pool_->NumUnassignedConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(1u, pool_->IdleSocketCountInGroup(TestGroupId("a"))); } TEST_F(ClientSocketPoolBaseTest, RequestSocketsCountActiveSockets) { @@ -3476,94 +3617,94 @@ TestCompletionCallback callback1; EXPECT_EQ( ERR_IO_PENDING, - handle1.Init("a", params_, DEFAULT_PRIORITY, SocketTag(), + handle1.Init(TestGroupId("a"), params_, DEFAULT_PRIORITY, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, callback1.callback(), ClientSocketPool::ProxyAuthCallback(), pool_.get(), NetLogWithSource())); ASSERT_THAT(callback1.WaitForResult(), IsOk()); - ASSERT_TRUE(pool_->HasGroup("a")); - EXPECT_EQ(0u, pool_->NumConnectJobsInGroup("a")); - EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup("a")); - EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup("a")); - EXPECT_EQ(0u, pool_->IdleSocketCountInGroup("a")); - EXPECT_EQ(1, pool_->NumActiveSocketsInGroup("a")); + ASSERT_TRUE(pool_->HasGroup(TestGroupId("a"))); + EXPECT_EQ(0u, pool_->NumConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(0u, pool_->IdleSocketCountInGroup(TestGroupId("a"))); + EXPECT_EQ(1, pool_->NumActiveSocketsInGroup(TestGroupId("a"))); - pool_->RequestSockets("a", ¶ms_, 2, NetLogWithSource()); + pool_->RequestSockets(TestGroupId("a"), ¶ms_, 2, NetLogWithSource()); - EXPECT_EQ(1u, pool_->NumConnectJobsInGroup("a")); - EXPECT_EQ(1u, pool_->NumNeverAssignedConnectJobsInGroup("a")); - EXPECT_EQ(1u, pool_->NumUnassignedConnectJobsInGroup("a")); - EXPECT_EQ(0u, pool_->IdleSocketCountInGroup("a")); - EXPECT_EQ(1, pool_->NumActiveSocketsInGroup("a")); + EXPECT_EQ(1u, pool_->NumConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(1u, pool_->NumNeverAssignedConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(1u, pool_->NumUnassignedConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(0u, pool_->IdleSocketCountInGroup(TestGroupId("a"))); + EXPECT_EQ(1, pool_->NumActiveSocketsInGroup(TestGroupId("a"))); } TEST_F(ClientSocketPoolBaseTest, RequestSocketsSynchronous) { CreatePool(kDefaultMaxSockets, kDefaultMaxSocketsPerGroup); connect_job_factory_->set_job_type(TestConnectJob::kMockJob); - pool_->RequestSockets("a", ¶ms_, kDefaultMaxSocketsPerGroup, + pool_->RequestSockets(TestGroupId("a"), ¶ms_, kDefaultMaxSocketsPerGroup, NetLogWithSource()); - ASSERT_TRUE(pool_->HasGroup("a")); - EXPECT_EQ(0u, pool_->NumConnectJobsInGroup("a")); - EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup("a")); - EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup("a")); + ASSERT_TRUE(pool_->HasGroup(TestGroupId("a"))); + EXPECT_EQ(0u, pool_->NumConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup(TestGroupId("a"))); EXPECT_EQ(kDefaultMaxSocketsPerGroup, - static_cast<int>(pool_->IdleSocketCountInGroup("a"))); + static_cast<int>(pool_->IdleSocketCountInGroup(TestGroupId("a")))); - pool_->RequestSockets("b", ¶ms_, kDefaultMaxSocketsPerGroup, + pool_->RequestSockets(TestGroupId("b"), ¶ms_, kDefaultMaxSocketsPerGroup, NetLogWithSource()); - EXPECT_EQ(0u, pool_->NumConnectJobsInGroup("b")); - EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup("b")); - EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup("b")); + EXPECT_EQ(0u, pool_->NumConnectJobsInGroup(TestGroupId("b"))); + EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup(TestGroupId("b"))); + EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup(TestGroupId("b"))); EXPECT_EQ(kDefaultMaxSocketsPerGroup, - static_cast<int>(pool_->IdleSocketCountInGroup("b"))); + static_cast<int>(pool_->IdleSocketCountInGroup(TestGroupId("b")))); } TEST_F(ClientSocketPoolBaseTest, RequestSocketsSynchronousError) { CreatePool(kDefaultMaxSockets, kDefaultMaxSocketsPerGroup); connect_job_factory_->set_job_type(TestConnectJob::kMockFailingJob); - pool_->RequestSockets("a", ¶ms_, kDefaultMaxSocketsPerGroup, + pool_->RequestSockets(TestGroupId("a"), ¶ms_, kDefaultMaxSocketsPerGroup, NetLogWithSource()); - ASSERT_FALSE(pool_->HasGroup("a")); + ASSERT_FALSE(pool_->HasGroup(TestGroupId("a"))); connect_job_factory_->set_job_type( TestConnectJob::kMockAdditionalErrorStateJob); - pool_->RequestSockets("a", ¶ms_, kDefaultMaxSocketsPerGroup, + pool_->RequestSockets(TestGroupId("a"), ¶ms_, kDefaultMaxSocketsPerGroup, NetLogWithSource()); - ASSERT_FALSE(pool_->HasGroup("a")); + ASSERT_FALSE(pool_->HasGroup(TestGroupId("a"))); } TEST_F(ClientSocketPoolBaseTest, RequestSocketsMultipleTimesDoesNothing) { CreatePool(4, 4); connect_job_factory_->set_job_type(TestConnectJob::kMockWaitingJob); - pool_->RequestSockets("a", ¶ms_, 2, NetLogWithSource()); + pool_->RequestSockets(TestGroupId("a"), ¶ms_, 2, NetLogWithSource()); - ASSERT_TRUE(pool_->HasGroup("a")); - EXPECT_EQ(2u, pool_->NumConnectJobsInGroup("a")); - EXPECT_EQ(2u, pool_->NumNeverAssignedConnectJobsInGroup("a")); - EXPECT_EQ(2u, pool_->NumUnassignedConnectJobsInGroup("a")); - EXPECT_EQ(0, pool_->NumActiveSocketsInGroup("a")); - EXPECT_EQ(0u, pool_->IdleSocketCountInGroup("a")); + ASSERT_TRUE(pool_->HasGroup(TestGroupId("a"))); + EXPECT_EQ(2u, pool_->NumConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(2u, pool_->NumNeverAssignedConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(2u, pool_->NumUnassignedConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(0, pool_->NumActiveSocketsInGroup(TestGroupId("a"))); + EXPECT_EQ(0u, pool_->IdleSocketCountInGroup(TestGroupId("a"))); - pool_->RequestSockets("a", ¶ms_, 2, NetLogWithSource()); - EXPECT_EQ(2u, pool_->NumConnectJobsInGroup("a")); - EXPECT_EQ(2u, pool_->NumNeverAssignedConnectJobsInGroup("a")); - EXPECT_EQ(2u, pool_->NumUnassignedConnectJobsInGroup("a")); - EXPECT_EQ(0, pool_->NumActiveSocketsInGroup("a")); - EXPECT_EQ(0u, pool_->IdleSocketCountInGroup("a")); + pool_->RequestSockets(TestGroupId("a"), ¶ms_, 2, NetLogWithSource()); + EXPECT_EQ(2u, pool_->NumConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(2u, pool_->NumNeverAssignedConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(2u, pool_->NumUnassignedConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(0, pool_->NumActiveSocketsInGroup(TestGroupId("a"))); + EXPECT_EQ(0u, pool_->IdleSocketCountInGroup(TestGroupId("a"))); ClientSocketHandle handle1; TestCompletionCallback callback1; EXPECT_EQ( ERR_IO_PENDING, - handle1.Init("a", params_, DEFAULT_PRIORITY, SocketTag(), + handle1.Init(TestGroupId("a"), params_, DEFAULT_PRIORITY, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, callback1.callback(), ClientSocketPool::ProxyAuthCallback(), pool_.get(), NetLogWithSource())); @@ -3571,118 +3712,118 @@ client_socket_factory_.SignalJob(0); EXPECT_THAT(callback1.WaitForResult(), IsOk()); - EXPECT_EQ(1u, pool_->NumConnectJobsInGroup("a")); - EXPECT_EQ(1u, pool_->NumNeverAssignedConnectJobsInGroup("a")); - EXPECT_EQ(1u, pool_->NumUnassignedConnectJobsInGroup("a")); - EXPECT_EQ(1, pool_->NumActiveSocketsInGroup("a")); - EXPECT_EQ(0u, pool_->IdleSocketCountInGroup("a")); + EXPECT_EQ(1u, pool_->NumConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(1u, pool_->NumNeverAssignedConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(1u, pool_->NumUnassignedConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(1, pool_->NumActiveSocketsInGroup(TestGroupId("a"))); + EXPECT_EQ(0u, pool_->IdleSocketCountInGroup(TestGroupId("a"))); ClientSocketHandle handle2; TestCompletionCallback callback2; EXPECT_EQ( ERR_IO_PENDING, - handle2.Init("a", params_, DEFAULT_PRIORITY, SocketTag(), + handle2.Init(TestGroupId("a"), params_, DEFAULT_PRIORITY, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, callback2.callback(), ClientSocketPool::ProxyAuthCallback(), pool_.get(), NetLogWithSource())); client_socket_factory_.SignalJob(0); EXPECT_THAT(callback2.WaitForResult(), IsOk()); - EXPECT_EQ(0u, pool_->NumConnectJobsInGroup("a")); - EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup("a")); - EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup("a")); - EXPECT_EQ(2, pool_->NumActiveSocketsInGroup("a")); - EXPECT_EQ(0u, pool_->IdleSocketCountInGroup("a")); + EXPECT_EQ(0u, pool_->NumConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(2, pool_->NumActiveSocketsInGroup(TestGroupId("a"))); + EXPECT_EQ(0u, pool_->IdleSocketCountInGroup(TestGroupId("a"))); handle1.Reset(); handle2.Reset(); - EXPECT_EQ(0u, pool_->NumConnectJobsInGroup("a")); - EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup("a")); - EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup("a")); - EXPECT_EQ(0, pool_->NumActiveSocketsInGroup("a")); - EXPECT_EQ(2u, pool_->IdleSocketCountInGroup("a")); + EXPECT_EQ(0u, pool_->NumConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(0, pool_->NumActiveSocketsInGroup(TestGroupId("a"))); + EXPECT_EQ(2u, pool_->IdleSocketCountInGroup(TestGroupId("a"))); - pool_->RequestSockets("a", ¶ms_, 2, NetLogWithSource()); - EXPECT_EQ(0u, pool_->NumConnectJobsInGroup("a")); - EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup("a")); - EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup("a")); - EXPECT_EQ(0, pool_->NumActiveSocketsInGroup("a")); - EXPECT_EQ(2u, pool_->IdleSocketCountInGroup("a")); + pool_->RequestSockets(TestGroupId("a"), ¶ms_, 2, NetLogWithSource()); + EXPECT_EQ(0u, pool_->NumConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(0, pool_->NumActiveSocketsInGroup(TestGroupId("a"))); + EXPECT_EQ(2u, pool_->IdleSocketCountInGroup(TestGroupId("a"))); } TEST_F(ClientSocketPoolBaseTest, RequestSocketsDifferentNumSockets) { CreatePool(4, 4); connect_job_factory_->set_job_type(TestConnectJob::kMockPendingJob); - pool_->RequestSockets("a", ¶ms_, 1, NetLogWithSource()); + pool_->RequestSockets(TestGroupId("a"), ¶ms_, 1, NetLogWithSource()); - ASSERT_TRUE(pool_->HasGroup("a")); - EXPECT_EQ(1u, pool_->NumConnectJobsInGroup("a")); - EXPECT_EQ(1u, pool_->NumNeverAssignedConnectJobsInGroup("a")); - EXPECT_EQ(1u, pool_->NumUnassignedConnectJobsInGroup("a")); - EXPECT_EQ(0u, pool_->IdleSocketCountInGroup("a")); + ASSERT_TRUE(pool_->HasGroup(TestGroupId("a"))); + EXPECT_EQ(1u, pool_->NumConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(1u, pool_->NumNeverAssignedConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(1u, pool_->NumUnassignedConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(0u, pool_->IdleSocketCountInGroup(TestGroupId("a"))); - pool_->RequestSockets("a", ¶ms_, 2, NetLogWithSource()); - EXPECT_EQ(2u, pool_->NumConnectJobsInGroup("a")); - EXPECT_EQ(2u, pool_->NumNeverAssignedConnectJobsInGroup("a")); - EXPECT_EQ(2u, pool_->NumUnassignedConnectJobsInGroup("a")); - EXPECT_EQ(0u, pool_->IdleSocketCountInGroup("a")); + pool_->RequestSockets(TestGroupId("a"), ¶ms_, 2, NetLogWithSource()); + EXPECT_EQ(2u, pool_->NumConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(2u, pool_->NumNeverAssignedConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(2u, pool_->NumUnassignedConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(0u, pool_->IdleSocketCountInGroup(TestGroupId("a"))); - pool_->RequestSockets("a", ¶ms_, 3, NetLogWithSource()); - EXPECT_EQ(3u, pool_->NumConnectJobsInGroup("a")); - EXPECT_EQ(3u, pool_->NumNeverAssignedConnectJobsInGroup("a")); - EXPECT_EQ(3u, pool_->NumUnassignedConnectJobsInGroup("a")); - EXPECT_EQ(0u, pool_->IdleSocketCountInGroup("a")); + pool_->RequestSockets(TestGroupId("a"), ¶ms_, 3, NetLogWithSource()); + EXPECT_EQ(3u, pool_->NumConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(3u, pool_->NumNeverAssignedConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(3u, pool_->NumUnassignedConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(0u, pool_->IdleSocketCountInGroup(TestGroupId("a"))); - pool_->RequestSockets("a", ¶ms_, 1, NetLogWithSource()); - EXPECT_EQ(3u, pool_->NumConnectJobsInGroup("a")); - EXPECT_EQ(3u, pool_->NumNeverAssignedConnectJobsInGroup("a")); - EXPECT_EQ(3u, pool_->NumUnassignedConnectJobsInGroup("a")); - EXPECT_EQ(0u, pool_->IdleSocketCountInGroup("a")); + pool_->RequestSockets(TestGroupId("a"), ¶ms_, 1, NetLogWithSource()); + EXPECT_EQ(3u, pool_->NumConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(3u, pool_->NumNeverAssignedConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(3u, pool_->NumUnassignedConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(0u, pool_->IdleSocketCountInGroup(TestGroupId("a"))); } TEST_F(ClientSocketPoolBaseTest, PreconnectJobsTakenByNormalRequests) { CreatePool(kDefaultMaxSockets, kDefaultMaxSocketsPerGroup); connect_job_factory_->set_job_type(TestConnectJob::kMockWaitingJob); - pool_->RequestSockets("a", ¶ms_, 1, NetLogWithSource()); + pool_->RequestSockets(TestGroupId("a"), ¶ms_, 1, NetLogWithSource()); - ASSERT_TRUE(pool_->HasGroup("a")); - EXPECT_EQ(1u, pool_->NumConnectJobsInGroup("a")); - EXPECT_EQ(1u, pool_->NumNeverAssignedConnectJobsInGroup("a")); - EXPECT_EQ(1u, pool_->NumUnassignedConnectJobsInGroup("a")); - EXPECT_EQ(0u, pool_->IdleSocketCountInGroup("a")); + ASSERT_TRUE(pool_->HasGroup(TestGroupId("a"))); + EXPECT_EQ(1u, pool_->NumConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(1u, pool_->NumNeverAssignedConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(1u, pool_->NumUnassignedConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(0u, pool_->IdleSocketCountInGroup(TestGroupId("a"))); ClientSocketHandle handle1; TestCompletionCallback callback1; EXPECT_EQ( ERR_IO_PENDING, - handle1.Init("a", params_, DEFAULT_PRIORITY, SocketTag(), + handle1.Init(TestGroupId("a"), params_, DEFAULT_PRIORITY, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, callback1.callback(), ClientSocketPool::ProxyAuthCallback(), pool_.get(), NetLogWithSource())); - EXPECT_EQ(1u, pool_->NumConnectJobsInGroup("a")); - EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup("a")); - EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup("a")); - EXPECT_EQ(0u, pool_->IdleSocketCountInGroup("a")); + EXPECT_EQ(1u, pool_->NumConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(0u, pool_->IdleSocketCountInGroup(TestGroupId("a"))); client_socket_factory_.SignalJobs(); EXPECT_THAT(callback1.WaitForResult(), IsOk()); - EXPECT_EQ(0u, pool_->NumConnectJobsInGroup("a")); - EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup("a")); - EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup("a")); - EXPECT_EQ(0u, pool_->IdleSocketCountInGroup("a")); - EXPECT_EQ(1, pool_->NumActiveSocketsInGroup("a")); + EXPECT_EQ(0u, pool_->NumConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(0u, pool_->IdleSocketCountInGroup(TestGroupId("a"))); + EXPECT_EQ(1, pool_->NumActiveSocketsInGroup(TestGroupId("a"))); // Make sure if a preconnected socket is not fully connected when a request // starts, it has a connect start time. TestLoadTimingInfoConnectedNotReused(handle1); handle1.Reset(); - EXPECT_EQ(1u, pool_->IdleSocketCountInGroup("a")); + EXPECT_EQ(1u, pool_->IdleSocketCountInGroup(TestGroupId("a"))); } // Checks that fully connected preconnect jobs have no connect times, and are @@ -3690,24 +3831,24 @@ TEST_F(ClientSocketPoolBaseTest, ConnectedPreconnectJobsHaveNoConnectTimes) { CreatePool(kDefaultMaxSockets, kDefaultMaxSocketsPerGroup); connect_job_factory_->set_job_type(TestConnectJob::kMockJob); - pool_->RequestSockets("a", ¶ms_, 1, NetLogWithSource()); + pool_->RequestSockets(TestGroupId("a"), ¶ms_, 1, NetLogWithSource()); - ASSERT_TRUE(pool_->HasGroup("a")); - EXPECT_EQ(0u, pool_->NumConnectJobsInGroup("a")); - EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup("a")); - EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup("a")); - EXPECT_EQ(1u, pool_->IdleSocketCountInGroup("a")); + ASSERT_TRUE(pool_->HasGroup(TestGroupId("a"))); + EXPECT_EQ(0u, pool_->NumConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(1u, pool_->IdleSocketCountInGroup(TestGroupId("a"))); ClientSocketHandle handle; TestCompletionCallback callback; - EXPECT_EQ(OK, handle.Init("a", params_, DEFAULT_PRIORITY, SocketTag(), - ClientSocketPool::RespectLimits::ENABLED, - callback.callback(), - ClientSocketPool::ProxyAuthCallback(), pool_.get(), - NetLogWithSource())); + EXPECT_EQ(OK, handle.Init( + TestGroupId("a"), params_, DEFAULT_PRIORITY, SocketTag(), + ClientSocketPool::RespectLimits::ENABLED, + callback.callback(), ClientSocketPool::ProxyAuthCallback(), + pool_.get(), NetLogWithSource())); // Make sure the idle socket was used. - EXPECT_EQ(0u, pool_->IdleSocketCountInGroup("a")); + EXPECT_EQ(0u, pool_->IdleSocketCountInGroup(TestGroupId("a"))); TestLoadTimingInfoConnectedReused(handle); handle.Reset(); @@ -3721,7 +3862,7 @@ CreatePool(kMaxTotalSockets, kMaxSocketsPerGroup); connect_job_factory_->set_job_type(TestConnectJob::kMockWaitingJob); - // Note that group name ordering matters here. "a" comes before "b", so + // Note that group id ordering matters here. "a" comes before "b", so // CloseOneIdleSocket() will try to close "a"'s idle socket. // Set up one idle socket in "a". @@ -3729,92 +3870,92 @@ TestCompletionCallback callback1; EXPECT_EQ( ERR_IO_PENDING, - handle1.Init("a", params_, DEFAULT_PRIORITY, SocketTag(), + handle1.Init(TestGroupId("a"), params_, DEFAULT_PRIORITY, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, callback1.callback(), ClientSocketPool::ProxyAuthCallback(), pool_.get(), NetLogWithSource())); - ASSERT_TRUE(pool_->HasGroup("a")); - EXPECT_EQ(1u, pool_->NumConnectJobsInGroup("a")); - EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup("a")); - EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup("a")); - EXPECT_EQ(0u, pool_->IdleSocketCountInGroup("a")); + ASSERT_TRUE(pool_->HasGroup(TestGroupId("a"))); + EXPECT_EQ(1u, pool_->NumConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(0u, pool_->IdleSocketCountInGroup(TestGroupId("a"))); client_socket_factory_.SignalJobs(); ASSERT_THAT(callback1.WaitForResult(), IsOk()); - EXPECT_EQ(0u, pool_->NumConnectJobsInGroup("a")); - EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup("a")); - EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup("a")); - EXPECT_EQ(1, pool_->NumActiveSocketsInGroup("a")); + EXPECT_EQ(0u, pool_->NumConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(1, pool_->NumActiveSocketsInGroup(TestGroupId("a"))); handle1.Reset(); - EXPECT_EQ(1u, pool_->IdleSocketCountInGroup("a")); + EXPECT_EQ(1u, pool_->IdleSocketCountInGroup(TestGroupId("a"))); // Set up two active sockets in "b". ClientSocketHandle handle2; TestCompletionCallback callback2; EXPECT_EQ( ERR_IO_PENDING, - handle1.Init("b", params_, DEFAULT_PRIORITY, SocketTag(), + handle1.Init(TestGroupId("b"), params_, DEFAULT_PRIORITY, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, callback1.callback(), ClientSocketPool::ProxyAuthCallback(), pool_.get(), NetLogWithSource())); EXPECT_EQ( ERR_IO_PENDING, - handle2.Init("b", params_, DEFAULT_PRIORITY, SocketTag(), + handle2.Init(TestGroupId("b"), params_, DEFAULT_PRIORITY, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, callback2.callback(), ClientSocketPool::ProxyAuthCallback(), pool_.get(), NetLogWithSource())); - ASSERT_TRUE(pool_->HasGroup("b")); - EXPECT_EQ(2u, pool_->NumConnectJobsInGroup("b")); - EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup("b")); - EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup("b")); - EXPECT_EQ(0u, pool_->IdleSocketCountInGroup("b")); + ASSERT_TRUE(pool_->HasGroup(TestGroupId("b"))); + EXPECT_EQ(2u, pool_->NumConnectJobsInGroup(TestGroupId("b"))); + EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup(TestGroupId("b"))); + EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup(TestGroupId("b"))); + EXPECT_EQ(0u, pool_->IdleSocketCountInGroup(TestGroupId("b"))); client_socket_factory_.SignalJobs(); ASSERT_THAT(callback1.WaitForResult(), IsOk()); ASSERT_THAT(callback2.WaitForResult(), IsOk()); - EXPECT_EQ(0u, pool_->IdleSocketCountInGroup("b")); - EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup("b")); - EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup("b")); - EXPECT_EQ(2, pool_->NumActiveSocketsInGroup("b")); + EXPECT_EQ(0u, pool_->IdleSocketCountInGroup(TestGroupId("b"))); + EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup(TestGroupId("b"))); + EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup(TestGroupId("b"))); + EXPECT_EQ(2, pool_->NumActiveSocketsInGroup(TestGroupId("b"))); // Now we have 1 idle socket in "a" and 2 active sockets in "b". This means // we've maxed out on sockets, since we set |kMaxTotalSockets| to 3. // Requesting 2 preconnected sockets for "a" should fail to allocate any more // sockets for "a", and "b" should still have 2 active sockets. - pool_->RequestSockets("a", ¶ms_, 2, NetLogWithSource()); - EXPECT_EQ(0u, pool_->NumConnectJobsInGroup("a")); - EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup("a")); - EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup("a")); - EXPECT_EQ(1u, pool_->IdleSocketCountInGroup("a")); - EXPECT_EQ(0, pool_->NumActiveSocketsInGroup("a")); - EXPECT_EQ(0u, pool_->NumConnectJobsInGroup("b")); - EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup("b")); - EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup("b")); - EXPECT_EQ(0u, pool_->IdleSocketCountInGroup("b")); - EXPECT_EQ(2, pool_->NumActiveSocketsInGroup("b")); + pool_->RequestSockets(TestGroupId("a"), ¶ms_, 2, NetLogWithSource()); + EXPECT_EQ(0u, pool_->NumConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(1u, pool_->IdleSocketCountInGroup(TestGroupId("a"))); + EXPECT_EQ(0, pool_->NumActiveSocketsInGroup(TestGroupId("a"))); + EXPECT_EQ(0u, pool_->NumConnectJobsInGroup(TestGroupId("b"))); + EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup(TestGroupId("b"))); + EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup(TestGroupId("b"))); + EXPECT_EQ(0u, pool_->IdleSocketCountInGroup(TestGroupId("b"))); + EXPECT_EQ(2, pool_->NumActiveSocketsInGroup(TestGroupId("b"))); // Now release the 2 active sockets for "b". This will give us 1 idle socket // in "a" and 2 idle sockets in "b". Requesting 2 preconnected sockets for // "a" should result in closing 1 for "b". handle1.Reset(); handle2.Reset(); - EXPECT_EQ(2u, pool_->IdleSocketCountInGroup("b")); - EXPECT_EQ(0, pool_->NumActiveSocketsInGroup("b")); + EXPECT_EQ(2u, pool_->IdleSocketCountInGroup(TestGroupId("b"))); + EXPECT_EQ(0, pool_->NumActiveSocketsInGroup(TestGroupId("b"))); - pool_->RequestSockets("a", ¶ms_, 2, NetLogWithSource()); - EXPECT_EQ(1u, pool_->NumConnectJobsInGroup("a")); - EXPECT_EQ(1u, pool_->NumNeverAssignedConnectJobsInGroup("a")); - EXPECT_EQ(1u, pool_->NumUnassignedConnectJobsInGroup("a")); - EXPECT_EQ(1u, pool_->IdleSocketCountInGroup("a")); - EXPECT_EQ(0, pool_->NumActiveSocketsInGroup("a")); - EXPECT_EQ(0u, pool_->NumConnectJobsInGroup("b")); - EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup("b")); - EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup("b")); - EXPECT_EQ(1u, pool_->IdleSocketCountInGroup("b")); - EXPECT_EQ(0, pool_->NumActiveSocketsInGroup("b")); + pool_->RequestSockets(TestGroupId("a"), ¶ms_, 2, NetLogWithSource()); + EXPECT_EQ(1u, pool_->NumConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(1u, pool_->NumNeverAssignedConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(1u, pool_->NumUnassignedConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(1u, pool_->IdleSocketCountInGroup(TestGroupId("a"))); + EXPECT_EQ(0, pool_->NumActiveSocketsInGroup(TestGroupId("a"))); + EXPECT_EQ(0u, pool_->NumConnectJobsInGroup(TestGroupId("b"))); + EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup(TestGroupId("b"))); + EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup(TestGroupId("b"))); + EXPECT_EQ(1u, pool_->IdleSocketCountInGroup(TestGroupId("b"))); + EXPECT_EQ(0, pool_->NumActiveSocketsInGroup(TestGroupId("b"))); } TEST_F(ClientSocketPoolBaseTest, PreconnectWithoutBackupJob) { @@ -3825,11 +3966,11 @@ connect_job_factory_->set_job_type(TestConnectJob::kMockWaitingJob); connect_job_factory_->set_timeout_duration( base::TimeDelta::FromMilliseconds(500)); - pool_->RequestSockets("a", ¶ms_, 1, NetLogWithSource()); - EXPECT_EQ(1u, pool_->NumConnectJobsInGroup("a")); - EXPECT_EQ(1u, pool_->NumNeverAssignedConnectJobsInGroup("a")); - EXPECT_EQ(1u, pool_->NumUnassignedConnectJobsInGroup("a")); - EXPECT_EQ(0u, pool_->IdleSocketCountInGroup("a")); + pool_->RequestSockets(TestGroupId("a"), ¶ms_, 1, NetLogWithSource()); + EXPECT_EQ(1u, pool_->NumConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(1u, pool_->NumNeverAssignedConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(1u, pool_->NumUnassignedConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(0u, pool_->IdleSocketCountInGroup(TestGroupId("a"))); // Verify the backup timer doesn't create a backup job, by making // the backup job a pending job instead of a waiting job, so it @@ -3839,7 +3980,7 @@ FROM_HERE, base::RunLoop::QuitCurrentWhenIdleClosureDeprecated(), base::TimeDelta::FromSeconds(1)); base::RunLoop().Run(); - EXPECT_FALSE(pool_->HasGroup("a")); + EXPECT_FALSE(pool_->HasGroup(TestGroupId("a"))); } TEST_F(ClientSocketPoolBaseTest, PreconnectWithBackupJob) { @@ -3848,11 +3989,11 @@ // Make the ConnectJob hang forever. connect_job_factory_->set_job_type(TestConnectJob::kMockWaitingJob); - pool_->RequestSockets("a", ¶ms_, 1, NetLogWithSource()); - EXPECT_EQ(1u, pool_->NumConnectJobsInGroup("a")); - EXPECT_EQ(1u, pool_->NumNeverAssignedConnectJobsInGroup("a")); - EXPECT_EQ(1u, pool_->NumUnassignedConnectJobsInGroup("a")); - EXPECT_EQ(0u, pool_->IdleSocketCountInGroup("a")); + pool_->RequestSockets(TestGroupId("a"), ¶ms_, 1, NetLogWithSource()); + EXPECT_EQ(1u, pool_->NumConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(1u, pool_->NumNeverAssignedConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(1u, pool_->NumUnassignedConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(0u, pool_->IdleSocketCountInGroup(TestGroupId("a"))); base::RunLoop().RunUntilIdle(); // Make the backup job be a pending job, so it completes normally. @@ -3861,25 +4002,25 @@ TestCompletionCallback callback; EXPECT_EQ( ERR_IO_PENDING, - handle.Init("a", params_, DEFAULT_PRIORITY, SocketTag(), + handle.Init(TestGroupId("a"), params_, DEFAULT_PRIORITY, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, callback.callback(), ClientSocketPool::ProxyAuthCallback(), pool_.get(), NetLogWithSource())); // Timer has started, but the backup connect job shouldn't be created yet. - EXPECT_EQ(1u, pool_->NumConnectJobsInGroup("a")); - EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup("a")); - EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup("a")); - EXPECT_EQ(0u, pool_->IdleSocketCountInGroup("a")); - EXPECT_EQ(0, pool_->NumActiveSocketsInGroup("a")); + EXPECT_EQ(1u, pool_->NumConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(0u, pool_->IdleSocketCountInGroup(TestGroupId("a"))); + EXPECT_EQ(0, pool_->NumActiveSocketsInGroup(TestGroupId("a"))); ASSERT_THAT(callback.WaitForResult(), IsOk()); // The hung connect job should still be there, but everything else should be // complete. - EXPECT_EQ(1u, pool_->NumConnectJobsInGroup("a")); - EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup("a")); - EXPECT_EQ(1u, pool_->NumUnassignedConnectJobsInGroup("a")); - EXPECT_EQ(0u, pool_->IdleSocketCountInGroup("a")); - EXPECT_EQ(1, pool_->NumActiveSocketsInGroup("a")); + EXPECT_EQ(1u, pool_->NumConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(1u, pool_->NumUnassignedConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(0u, pool_->IdleSocketCountInGroup(TestGroupId("a"))); + EXPECT_EQ(1, pool_->NumActiveSocketsInGroup(TestGroupId("a"))); } // Tests that a preconnect that starts out with unread data can still be used. @@ -3888,31 +4029,31 @@ CreatePool(kDefaultMaxSockets, kDefaultMaxSocketsPerGroup); connect_job_factory_->set_job_type(TestConnectJob::kMockUnreadDataJob); - pool_->RequestSockets("a", ¶ms_, 1, NetLogWithSource()); + pool_->RequestSockets(TestGroupId("a"), ¶ms_, 1, NetLogWithSource()); - ASSERT_TRUE(pool_->HasGroup("a")); - EXPECT_EQ(0u, pool_->NumConnectJobsInGroup("a")); - EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup("a")); - EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup("a")); - EXPECT_EQ(1u, pool_->IdleSocketCountInGroup("a")); + ASSERT_TRUE(pool_->HasGroup(TestGroupId("a"))); + EXPECT_EQ(0u, pool_->NumConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(1u, pool_->IdleSocketCountInGroup(TestGroupId("a"))); // Fail future jobs to be sure that handle receives the preconnected socket // rather than closing it and making a new one. connect_job_factory_->set_job_type(TestConnectJob::kMockFailingJob); ClientSocketHandle handle; TestCompletionCallback callback; - EXPECT_EQ(OK, handle.Init("a", params_, DEFAULT_PRIORITY, SocketTag(), - ClientSocketPool::RespectLimits::ENABLED, - callback.callback(), - ClientSocketPool::ProxyAuthCallback(), pool_.get(), - NetLogWithSource())); + EXPECT_EQ(OK, handle.Init( + TestGroupId("a"), params_, DEFAULT_PRIORITY, SocketTag(), + ClientSocketPool::RespectLimits::ENABLED, + callback.callback(), ClientSocketPool::ProxyAuthCallback(), + pool_.get(), NetLogWithSource())); - ASSERT_TRUE(pool_->HasGroup("a")); - EXPECT_EQ(0u, pool_->NumConnectJobsInGroup("a")); - EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup("a")); - EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup("a")); - EXPECT_EQ(0u, pool_->IdleSocketCountInGroup("a")); - EXPECT_EQ(1, pool_->NumActiveSocketsInGroup("a")); + ASSERT_TRUE(pool_->HasGroup(TestGroupId("a"))); + EXPECT_EQ(0u, pool_->NumConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(0u, pool_->IdleSocketCountInGroup(TestGroupId("a"))); + EXPECT_EQ(1, pool_->NumActiveSocketsInGroup(TestGroupId("a"))); // Drain the pending read. EXPECT_EQ(1, handle.socket()->Read(nullptr, 1, CompletionOnceCallback())); @@ -3921,7 +4062,7 @@ handle.Reset(); // The socket should be usable now that it's idle again. - EXPECT_EQ(1u, pool_->IdleSocketCountInGroup("a")); + EXPECT_EQ(1u, pool_->IdleSocketCountInGroup(TestGroupId("a"))); } TEST_F(ClientSocketPoolBaseTest, RequestGetsAssignedJob) { @@ -3932,17 +4073,18 @@ TestCompletionCallback callback1; EXPECT_EQ( ERR_IO_PENDING, - handle1.Init("a", params_, DEFAULT_PRIORITY, SocketTag(), + handle1.Init(TestGroupId("a"), params_, DEFAULT_PRIORITY, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, callback1.callback(), ClientSocketPool::ProxyAuthCallback(), pool_.get(), NetLogWithSource())); - EXPECT_EQ(1u, pool_->NumConnectJobsInGroup("a")); - EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup("a")); - EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup("a")); - EXPECT_EQ(0u, pool_->IdleSocketCountInGroup("a")); + EXPECT_EQ(1u, pool_->NumConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(0u, pool_->IdleSocketCountInGroup(TestGroupId("a"))); - EXPECT_TRUE(pool_->RequestInGroupWithHandleHasJobForTesting("a", &handle1)); + EXPECT_TRUE(pool_->RequestInGroupWithHandleHasJobForTesting(TestGroupId("a"), + &handle1)); } TEST_F(ClientSocketPoolBaseTest, MultipleRequestsGetAssignedJobs) { @@ -3953,73 +4095,77 @@ TestCompletionCallback callback1; EXPECT_EQ( ERR_IO_PENDING, - handle1.Init("a", params_, DEFAULT_PRIORITY, SocketTag(), + handle1.Init(TestGroupId("a"), params_, DEFAULT_PRIORITY, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, callback1.callback(), ClientSocketPool::ProxyAuthCallback(), pool_.get(), NetLogWithSource())); - EXPECT_EQ(1u, pool_->NumConnectJobsInGroup("a")); - EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup("a")); - EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup("a")); - EXPECT_EQ(0u, pool_->IdleSocketCountInGroup("a")); + EXPECT_EQ(1u, pool_->NumConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(0u, pool_->IdleSocketCountInGroup(TestGroupId("a"))); ClientSocketHandle handle2; TestCompletionCallback callback2; EXPECT_EQ( ERR_IO_PENDING, - handle2.Init("a", params_, DEFAULT_PRIORITY, SocketTag(), + handle2.Init(TestGroupId("a"), params_, DEFAULT_PRIORITY, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, callback2.callback(), ClientSocketPool::ProxyAuthCallback(), pool_.get(), NetLogWithSource())); - EXPECT_EQ(2u, pool_->NumConnectJobsInGroup("a")); - EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup("a")); - EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup("a")); - EXPECT_EQ(0u, pool_->IdleSocketCountInGroup("a")); + EXPECT_EQ(2u, pool_->NumConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(0u, pool_->IdleSocketCountInGroup(TestGroupId("a"))); - EXPECT_TRUE(pool_->RequestInGroupWithHandleHasJobForTesting("a", &handle1)); - EXPECT_TRUE(pool_->RequestInGroupWithHandleHasJobForTesting("a", &handle2)); + EXPECT_TRUE(pool_->RequestInGroupWithHandleHasJobForTesting(TestGroupId("a"), + &handle1)); + EXPECT_TRUE(pool_->RequestInGroupWithHandleHasJobForTesting(TestGroupId("a"), + &handle2)); // One job completes. The other request should still have its job. client_socket_factory_.SignalJob(0); EXPECT_THAT(callback1.WaitForResult(), IsOk()); - EXPECT_EQ(1u, pool_->NumConnectJobsInGroup("a")); - EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup("a")); - EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup("a")); - EXPECT_EQ(1, pool_->NumActiveSocketsInGroup("a")); - EXPECT_EQ(0u, pool_->IdleSocketCountInGroup("a")); + EXPECT_EQ(1u, pool_->NumConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(1, pool_->NumActiveSocketsInGroup(TestGroupId("a"))); + EXPECT_EQ(0u, pool_->IdleSocketCountInGroup(TestGroupId("a"))); - EXPECT_TRUE(pool_->RequestInGroupWithHandleHasJobForTesting("a", &handle2)); + EXPECT_TRUE(pool_->RequestInGroupWithHandleHasJobForTesting(TestGroupId("a"), + &handle2)); } TEST_F(ClientSocketPoolBaseTest, PreconnectJobGetsAssignedToRequest) { CreatePool(kDefaultMaxSockets, kDefaultMaxSocketsPerGroup); connect_job_factory_->set_job_type(TestConnectJob::kMockWaitingJob); - pool_->RequestSockets("a", ¶ms_, 1, NetLogWithSource()); + pool_->RequestSockets(TestGroupId("a"), ¶ms_, 1, NetLogWithSource()); - ASSERT_TRUE(pool_->HasGroup("a")); - EXPECT_EQ(1u, pool_->NumConnectJobsInGroup("a")); - EXPECT_EQ(1u, pool_->NumNeverAssignedConnectJobsInGroup("a")); - EXPECT_EQ(1u, pool_->NumUnassignedConnectJobsInGroup("a")); - EXPECT_EQ(0u, pool_->IdleSocketCountInGroup("a")); + ASSERT_TRUE(pool_->HasGroup(TestGroupId("a"))); + EXPECT_EQ(1u, pool_->NumConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(1u, pool_->NumNeverAssignedConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(1u, pool_->NumUnassignedConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(0u, pool_->IdleSocketCountInGroup(TestGroupId("a"))); ClientSocketHandle handle1; TestCompletionCallback callback1; EXPECT_EQ( ERR_IO_PENDING, - handle1.Init("a", params_, DEFAULT_PRIORITY, SocketTag(), + handle1.Init(TestGroupId("a"), params_, DEFAULT_PRIORITY, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, callback1.callback(), ClientSocketPool::ProxyAuthCallback(), pool_.get(), NetLogWithSource())); - EXPECT_EQ(1u, pool_->NumConnectJobsInGroup("a")); - EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup("a")); - EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup("a")); - EXPECT_EQ(0u, pool_->IdleSocketCountInGroup("a")); + EXPECT_EQ(1u, pool_->NumConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(0u, pool_->IdleSocketCountInGroup(TestGroupId("a"))); - EXPECT_TRUE(pool_->RequestInGroupWithHandleHasJobForTesting("a", &handle1)); + EXPECT_TRUE(pool_->RequestInGroupWithHandleHasJobForTesting(TestGroupId("a"), + &handle1)); } TEST_F(ClientSocketPoolBaseTest, HigherPriorityRequestStealsJob) { @@ -4030,37 +4176,40 @@ TestCompletionCallback callback1; EXPECT_EQ( ERR_IO_PENDING, - handle1.Init("a", params_, DEFAULT_PRIORITY, SocketTag(), + handle1.Init(TestGroupId("a"), params_, DEFAULT_PRIORITY, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, callback1.callback(), ClientSocketPool::ProxyAuthCallback(), pool_.get(), NetLogWithSource())); - EXPECT_EQ(1u, pool_->NumConnectJobsInGroup("a")); - EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup("a")); - EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup("a")); - EXPECT_EQ(0u, pool_->IdleSocketCountInGroup("a")); + EXPECT_EQ(1u, pool_->NumConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(0u, pool_->IdleSocketCountInGroup(TestGroupId("a"))); - EXPECT_TRUE(pool_->RequestInGroupWithHandleHasJobForTesting("a", &handle1)); + EXPECT_TRUE(pool_->RequestInGroupWithHandleHasJobForTesting(TestGroupId("a"), + &handle1)); // Insert a higher priority request ClientSocketHandle handle2; TestCompletionCallback callback2; EXPECT_EQ( ERR_IO_PENDING, - handle2.Init("a", params_, HIGHEST, SocketTag(), + handle2.Init(TestGroupId("a"), params_, HIGHEST, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, callback2.callback(), ClientSocketPool::ProxyAuthCallback(), pool_.get(), NetLogWithSource())); - EXPECT_EQ(1u, pool_->NumConnectJobsInGroup("a")); - EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup("a")); - EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup("a")); - EXPECT_EQ(0u, pool_->IdleSocketCountInGroup("a")); + EXPECT_EQ(1u, pool_->NumConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(0u, pool_->IdleSocketCountInGroup(TestGroupId("a"))); // The highest priority request should steal the job from the default priority // request. - EXPECT_TRUE(pool_->RequestInGroupWithHandleHasJobForTesting("a", &handle2)); - EXPECT_FALSE(pool_->RequestInGroupWithHandleHasJobForTesting("a", &handle1)); + EXPECT_TRUE(pool_->RequestInGroupWithHandleHasJobForTesting(TestGroupId("a"), + &handle2)); + EXPECT_FALSE(pool_->RequestInGroupWithHandleHasJobForTesting(TestGroupId("a"), + &handle1)); } TEST_F(ClientSocketPoolBaseTest, RequestStealsJobFromLowestRequestWithJob) { @@ -4070,94 +4219,94 @@ ClientSocketHandle handle_lowest; TestCompletionCallback callback_lowest; EXPECT_EQ(ERR_IO_PENDING, - handle_lowest.Init("a", params_, LOWEST, SocketTag(), + handle_lowest.Init(TestGroupId("a"), params_, LOWEST, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, callback_lowest.callback(), ClientSocketPool::ProxyAuthCallback(), pool_.get(), NetLogWithSource())); - EXPECT_EQ(1u, pool_->NumConnectJobsInGroup("a")); - EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup("a")); - EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup("a")); - EXPECT_EQ(0u, pool_->IdleSocketCountInGroup("a")); + EXPECT_EQ(1u, pool_->NumConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(0u, pool_->IdleSocketCountInGroup(TestGroupId("a"))); ClientSocketHandle handle_highest; TestCompletionCallback callback_highest; EXPECT_EQ(ERR_IO_PENDING, - handle_highest.Init("a", params_, HIGHEST, SocketTag(), + handle_highest.Init(TestGroupId("a"), params_, HIGHEST, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, callback_highest.callback(), ClientSocketPool::ProxyAuthCallback(), pool_.get(), NetLogWithSource())); - EXPECT_EQ(2u, pool_->NumConnectJobsInGroup("a")); - EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup("a")); - EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup("a")); - EXPECT_EQ(0u, pool_->IdleSocketCountInGroup("a")); + EXPECT_EQ(2u, pool_->NumConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(0u, pool_->IdleSocketCountInGroup(TestGroupId("a"))); ClientSocketHandle handle_low; TestCompletionCallback callback_low; EXPECT_EQ(ERR_IO_PENDING, - handle_low.Init("a", params_, LOW, SocketTag(), + handle_low.Init(TestGroupId("a"), params_, LOW, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, callback_low.callback(), ClientSocketPool::ProxyAuthCallback(), pool_.get(), NetLogWithSource())); - EXPECT_EQ(3u, pool_->NumConnectJobsInGroup("a")); - EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup("a")); - EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup("a")); - EXPECT_EQ(0u, pool_->IdleSocketCountInGroup("a")); + EXPECT_EQ(3u, pool_->NumConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(0u, pool_->IdleSocketCountInGroup(TestGroupId("a"))); ClientSocketHandle handle_lowest2; TestCompletionCallback callback_lowest2; EXPECT_EQ(ERR_IO_PENDING, - handle_lowest2.Init("a", params_, LOWEST, SocketTag(), + handle_lowest2.Init(TestGroupId("a"), params_, LOWEST, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, callback_lowest2.callback(), ClientSocketPool::ProxyAuthCallback(), pool_.get(), NetLogWithSource())); - EXPECT_EQ(3u, pool_->NumConnectJobsInGroup("a")); - EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup("a")); - EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup("a")); - EXPECT_EQ(0u, pool_->IdleSocketCountInGroup("a")); + EXPECT_EQ(3u, pool_->NumConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(0u, pool_->IdleSocketCountInGroup(TestGroupId("a"))); // The top three requests in the queue should have jobs. - EXPECT_TRUE( - pool_->RequestInGroupWithHandleHasJobForTesting("a", &handle_highest)); - EXPECT_TRUE( - pool_->RequestInGroupWithHandleHasJobForTesting("a", &handle_low)); - EXPECT_TRUE( - pool_->RequestInGroupWithHandleHasJobForTesting("a", &handle_lowest)); - EXPECT_FALSE( - pool_->RequestInGroupWithHandleHasJobForTesting("a", &handle_lowest2)); + EXPECT_TRUE(pool_->RequestInGroupWithHandleHasJobForTesting(TestGroupId("a"), + &handle_highest)); + EXPECT_TRUE(pool_->RequestInGroupWithHandleHasJobForTesting(TestGroupId("a"), + &handle_low)); + EXPECT_TRUE(pool_->RequestInGroupWithHandleHasJobForTesting(TestGroupId("a"), + &handle_lowest)); + EXPECT_FALSE(pool_->RequestInGroupWithHandleHasJobForTesting( + TestGroupId("a"), &handle_lowest2)); // Add another request with medium priority. It should steal the job from the // lowest priority request with a job. ClientSocketHandle handle_medium; TestCompletionCallback callback_medium; EXPECT_EQ(ERR_IO_PENDING, - handle_medium.Init("a", params_, MEDIUM, SocketTag(), + handle_medium.Init(TestGroupId("a"), params_, MEDIUM, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, callback_medium.callback(), ClientSocketPool::ProxyAuthCallback(), pool_.get(), NetLogWithSource())); - EXPECT_EQ(3u, pool_->NumConnectJobsInGroup("a")); - EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup("a")); - EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup("a")); - EXPECT_EQ(0u, pool_->IdleSocketCountInGroup("a")); - EXPECT_TRUE( - pool_->RequestInGroupWithHandleHasJobForTesting("a", &handle_highest)); - EXPECT_TRUE( - pool_->RequestInGroupWithHandleHasJobForTesting("a", &handle_medium)); - EXPECT_TRUE( - pool_->RequestInGroupWithHandleHasJobForTesting("a", &handle_low)); - EXPECT_FALSE( - pool_->RequestInGroupWithHandleHasJobForTesting("a", &handle_lowest)); - EXPECT_FALSE( - pool_->RequestInGroupWithHandleHasJobForTesting("a", &handle_lowest2)); + EXPECT_EQ(3u, pool_->NumConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(0u, pool_->IdleSocketCountInGroup(TestGroupId("a"))); + EXPECT_TRUE(pool_->RequestInGroupWithHandleHasJobForTesting(TestGroupId("a"), + &handle_highest)); + EXPECT_TRUE(pool_->RequestInGroupWithHandleHasJobForTesting(TestGroupId("a"), + &handle_medium)); + EXPECT_TRUE(pool_->RequestInGroupWithHandleHasJobForTesting(TestGroupId("a"), + &handle_low)); + EXPECT_FALSE(pool_->RequestInGroupWithHandleHasJobForTesting(TestGroupId("a"), + &handle_lowest)); + EXPECT_FALSE(pool_->RequestInGroupWithHandleHasJobForTesting( + TestGroupId("a"), &handle_lowest2)); } TEST_F(ClientSocketPoolBaseTest, ReprioritizeRequestStealsJob) { @@ -4168,39 +4317,43 @@ TestCompletionCallback callback1; EXPECT_EQ( ERR_IO_PENDING, - handle1.Init("a", params_, DEFAULT_PRIORITY, SocketTag(), + handle1.Init(TestGroupId("a"), params_, DEFAULT_PRIORITY, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, callback1.callback(), ClientSocketPool::ProxyAuthCallback(), pool_.get(), NetLogWithSource())); - EXPECT_EQ(1u, pool_->NumConnectJobsInGroup("a")); - EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup("a")); - EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup("a")); - EXPECT_EQ(0u, pool_->IdleSocketCountInGroup("a")); + EXPECT_EQ(1u, pool_->NumConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(0u, pool_->IdleSocketCountInGroup(TestGroupId("a"))); ClientSocketHandle handle2; TestCompletionCallback callback2; EXPECT_EQ( ERR_IO_PENDING, - handle2.Init("a", params_, DEFAULT_PRIORITY, SocketTag(), + handle2.Init(TestGroupId("a"), params_, DEFAULT_PRIORITY, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, callback2.callback(), ClientSocketPool::ProxyAuthCallback(), pool_.get(), NetLogWithSource())); - EXPECT_EQ(1u, pool_->NumConnectJobsInGroup("a")); - EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup("a")); - EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup("a")); - EXPECT_EQ(0u, pool_->IdleSocketCountInGroup("a")); + EXPECT_EQ(1u, pool_->NumConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(0u, pool_->IdleSocketCountInGroup(TestGroupId("a"))); // The second request doesn't get a job because we are at the limit. - EXPECT_TRUE(pool_->RequestInGroupWithHandleHasJobForTesting("a", &handle1)); - EXPECT_FALSE(pool_->RequestInGroupWithHandleHasJobForTesting("a", &handle2)); + EXPECT_TRUE(pool_->RequestInGroupWithHandleHasJobForTesting(TestGroupId("a"), + &handle1)); + EXPECT_FALSE(pool_->RequestInGroupWithHandleHasJobForTesting(TestGroupId("a"), + &handle2)); // Reprioritizing the second request places it above the first, and it steals // the job from the first request. - pool_->SetPriority("a", &handle2, HIGHEST); - EXPECT_TRUE(pool_->RequestInGroupWithHandleHasJobForTesting("a", &handle2)); - EXPECT_FALSE(pool_->RequestInGroupWithHandleHasJobForTesting("a", &handle1)); + pool_->SetPriority(TestGroupId("a"), &handle2, HIGHEST); + EXPECT_TRUE(pool_->RequestInGroupWithHandleHasJobForTesting(TestGroupId("a"), + &handle2)); + EXPECT_FALSE(pool_->RequestInGroupWithHandleHasJobForTesting(TestGroupId("a"), + &handle1)); } TEST_F(ClientSocketPoolBaseTest, CancelRequestReassignsJob) { @@ -4211,44 +4364,48 @@ TestCompletionCallback callback1; EXPECT_EQ( ERR_IO_PENDING, - handle1.Init("a", params_, DEFAULT_PRIORITY, SocketTag(), + handle1.Init(TestGroupId("a"), params_, DEFAULT_PRIORITY, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, callback1.callback(), ClientSocketPool::ProxyAuthCallback(), pool_.get(), NetLogWithSource())); - EXPECT_EQ(1u, pool_->NumConnectJobsInGroup("a")); - EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup("a")); - EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup("a")); - EXPECT_EQ(0u, pool_->IdleSocketCountInGroup("a")); + EXPECT_EQ(1u, pool_->NumConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(0u, pool_->IdleSocketCountInGroup(TestGroupId("a"))); - EXPECT_TRUE(pool_->RequestInGroupWithHandleHasJobForTesting("a", &handle1)); + EXPECT_TRUE(pool_->RequestInGroupWithHandleHasJobForTesting(TestGroupId("a"), + &handle1)); ClientSocketHandle handle2; TestCompletionCallback callback2; EXPECT_EQ( ERR_IO_PENDING, - handle2.Init("a", params_, DEFAULT_PRIORITY, SocketTag(), + handle2.Init(TestGroupId("a"), params_, DEFAULT_PRIORITY, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, callback2.callback(), ClientSocketPool::ProxyAuthCallback(), pool_.get(), NetLogWithSource())); - EXPECT_EQ(1u, pool_->NumConnectJobsInGroup("a")); - EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup("a")); - EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup("a")); - EXPECT_EQ(0u, pool_->IdleSocketCountInGroup("a")); + EXPECT_EQ(1u, pool_->NumConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(0u, pool_->IdleSocketCountInGroup(TestGroupId("a"))); // The second request doesn't get a job because we are the limit. - EXPECT_TRUE(pool_->RequestInGroupWithHandleHasJobForTesting("a", &handle1)); - EXPECT_FALSE(pool_->RequestInGroupWithHandleHasJobForTesting("a", &handle2)); + EXPECT_TRUE(pool_->RequestInGroupWithHandleHasJobForTesting(TestGroupId("a"), + &handle1)); + EXPECT_FALSE(pool_->RequestInGroupWithHandleHasJobForTesting(TestGroupId("a"), + &handle2)); // The second request should get a job upon cancelling the first request. handle1.Reset(); - EXPECT_EQ(1u, pool_->NumConnectJobsInGroup("a")); - EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup("a")); - EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup("a")); - EXPECT_EQ(0u, pool_->IdleSocketCountInGroup("a")); + EXPECT_EQ(1u, pool_->NumConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(0u, pool_->IdleSocketCountInGroup(TestGroupId("a"))); - EXPECT_TRUE(pool_->RequestInGroupWithHandleHasJobForTesting("a", &handle2)); + EXPECT_TRUE(pool_->RequestInGroupWithHandleHasJobForTesting(TestGroupId("a"), + &handle2)); } TEST_F(ClientSocketPoolBaseTest, JobCompletionReassignsJob) { @@ -4259,54 +4416,55 @@ TestCompletionCallback callback1; EXPECT_EQ( ERR_IO_PENDING, - handle1.Init("a", params_, HIGHEST, SocketTag(), + handle1.Init(TestGroupId("a"), params_, HIGHEST, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, callback1.callback(), ClientSocketPool::ProxyAuthCallback(), pool_.get(), NetLogWithSource())); - EXPECT_EQ(1u, pool_->NumConnectJobsInGroup("a")); - EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup("a")); - EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup("a")); - EXPECT_EQ(0u, pool_->IdleSocketCountInGroup("a")); + EXPECT_EQ(1u, pool_->NumConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(0u, pool_->IdleSocketCountInGroup(TestGroupId("a"))); ClientSocketHandle handle2; TestCompletionCallback callback2; EXPECT_EQ( ERR_IO_PENDING, - handle2.Init("a", params_, DEFAULT_PRIORITY, SocketTag(), + handle2.Init(TestGroupId("a"), params_, DEFAULT_PRIORITY, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, callback2.callback(), ClientSocketPool::ProxyAuthCallback(), pool_.get(), NetLogWithSource())); - EXPECT_EQ(2u, pool_->NumConnectJobsInGroup("a")); - EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup("a")); - EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup("a")); - EXPECT_EQ(0u, pool_->IdleSocketCountInGroup("a")); + EXPECT_EQ(2u, pool_->NumConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(0u, pool_->IdleSocketCountInGroup(TestGroupId("a"))); - EXPECT_TRUE(pool_->RequestInGroupWithHandleHasJobForTesting("a", &handle1)); - EXPECT_TRUE(pool_->RequestInGroupWithHandleHasJobForTesting("a", &handle2)); + EXPECT_TRUE(pool_->RequestInGroupWithHandleHasJobForTesting(TestGroupId("a"), + &handle1)); + EXPECT_TRUE(pool_->RequestInGroupWithHandleHasJobForTesting(TestGroupId("a"), + &handle2)); // The lower-priority job completes first. The higher-priority request should // get the socket, and the lower-priority request should get the remaining // job. client_socket_factory_.SignalJob(1); EXPECT_THAT(callback1.WaitForResult(), IsOk()); - EXPECT_EQ(1u, pool_->NumConnectJobsInGroup("a")); - EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup("a")); - EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup("a")); - EXPECT_EQ(1, pool_->NumActiveSocketsInGroup("a")); - EXPECT_EQ(0u, pool_->IdleSocketCountInGroup("a")); + EXPECT_EQ(1u, pool_->NumConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(0u, pool_->NumNeverAssignedConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(0u, pool_->NumUnassignedConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(1, pool_->NumActiveSocketsInGroup(TestGroupId("a"))); + EXPECT_EQ(0u, pool_->IdleSocketCountInGroup(TestGroupId("a"))); EXPECT_TRUE(handle1.socket()); - EXPECT_TRUE(pool_->RequestInGroupWithHandleHasJobForTesting("a", &handle2)); + EXPECT_TRUE(pool_->RequestInGroupWithHandleHasJobForTesting(TestGroupId("a"), + &handle2)); } class MockLayeredPool : public HigherLayeredPool { public: MockLayeredPool(TestClientSocketPool* pool, - const std::string& group_name) - : pool_(pool), - group_name_(group_name), - can_release_connection_(true) { + const ClientSocketPool::GroupId& group_id) + : pool_(pool), group_id_(group_id), can_release_connection_(true) { pool_->AddHigherLayeredPool(this); } @@ -4315,7 +4473,7 @@ int RequestSocket(TestClientSocketPool* pool) { scoped_refptr<TestSocketParams> params(new TestSocketParams()); return handle_.Init( - group_name_, params, DEFAULT_PRIORITY, SocketTag(), + group_id_, params, DEFAULT_PRIORITY, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, callback_.callback(), ClientSocketPool::ProxyAuthCallback(), pool, NetLogWithSource()); } @@ -4323,7 +4481,7 @@ int RequestSocketWithoutLimits(TestClientSocketPool* pool) { scoped_refptr<TestSocketParams> params(new TestSocketParams()); return handle_.Init( - group_name_, params, MAXIMUM_PRIORITY, SocketTag(), + group_id_, params, MAXIMUM_PRIORITY, SocketTag(), ClientSocketPool::RespectLimits::DISABLED, callback_.callback(), ClientSocketPool::ProxyAuthCallback(), pool, NetLogWithSource()); } @@ -4347,7 +4505,7 @@ TestClientSocketPool* const pool_; ClientSocketHandle handle_; TestCompletionCallback callback_; - const std::string group_name_; + const ClientSocketPool::GroupId group_id_; bool can_release_connection_; }; @@ -4357,7 +4515,7 @@ CreatePool(1, 1); connect_job_factory_->set_job_type(TestConnectJob::kMockJob); - MockLayeredPool mock_layered_pool(pool_.get(), "foo"); + MockLayeredPool mock_layered_pool(pool_.get(), TestGroupId("foo")); EXPECT_THAT(mock_layered_pool.RequestSocket(pool_.get()), IsOk()); EXPECT_CALL(mock_layered_pool, CloseOneIdleConnection()) .WillOnce(Invoke(&mock_layered_pool, @@ -4366,7 +4524,7 @@ TestCompletionCallback callback; EXPECT_EQ( ERR_IO_PENDING, - handle.Init("a", params_, DEFAULT_PRIORITY, SocketTag(), + handle.Init(TestGroupId("a"), params_, DEFAULT_PRIORITY, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, callback.callback(), ClientSocketPool::ProxyAuthCallback(), pool_.get(), NetLogWithSource())); @@ -4380,7 +4538,7 @@ CreatePool(1, 1); connect_job_factory_->set_job_type(TestConnectJob::kMockJob); - MockLayeredPool mock_layered_pool(pool_.get(), "foo"); + MockLayeredPool mock_layered_pool(pool_.get(), TestGroupId("foo")); mock_layered_pool.set_can_release_connection(false); EXPECT_THAT(mock_layered_pool.RequestSocket(pool_.get()), IsOk()); EXPECT_CALL(mock_layered_pool, CloseOneIdleConnection()) @@ -4390,7 +4548,7 @@ TestCompletionCallback callback; EXPECT_EQ( ERR_IO_PENDING, - handle.Init("a", params_, DEFAULT_PRIORITY, SocketTag(), + handle.Init(TestGroupId("a"), params_, DEFAULT_PRIORITY, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, callback.callback(), ClientSocketPool::ProxyAuthCallback(), pool_.get(), NetLogWithSource())); @@ -4412,13 +4570,13 @@ // has the maximum number of connections already, it's not stalled). ClientSocketHandle handle1; TestCompletionCallback callback1; - EXPECT_EQ(OK, handle1.Init("group1", params_, DEFAULT_PRIORITY, SocketTag(), - ClientSocketPool::RespectLimits::ENABLED, - callback1.callback(), - ClientSocketPool::ProxyAuthCallback(), pool_.get(), - NetLogWithSource())); + EXPECT_EQ(OK, handle1.Init( + TestGroupId("group1"), params_, DEFAULT_PRIORITY, + SocketTag(), ClientSocketPool::RespectLimits::ENABLED, + callback1.callback(), ClientSocketPool::ProxyAuthCallback(), + pool_.get(), NetLogWithSource())); - MockLayeredPool mock_layered_pool(pool_.get(), "group2"); + MockLayeredPool mock_layered_pool(pool_.get(), TestGroupId("group2")); EXPECT_THAT(mock_layered_pool.RequestSocket(pool_.get()), IsOk()); EXPECT_CALL(mock_layered_pool, CloseOneIdleConnection()) .WillOnce(Invoke(&mock_layered_pool, @@ -4427,7 +4585,7 @@ TestCompletionCallback callback2; EXPECT_EQ( ERR_IO_PENDING, - handle.Init("group2", params_, DEFAULT_PRIORITY, SocketTag(), + handle.Init(TestGroupId("group2"), params_, DEFAULT_PRIORITY, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, callback2.callback(), ClientSocketPool::ProxyAuthCallback(), pool_.get(), NetLogWithSource())); @@ -4448,13 +4606,13 @@ ClientSocketHandle handle1; TestCompletionCallback callback1; - EXPECT_EQ(OK, handle1.Init("group1", params_, DEFAULT_PRIORITY, SocketTag(), - ClientSocketPool::RespectLimits::ENABLED, - callback1.callback(), - ClientSocketPool::ProxyAuthCallback(), pool_.get(), - NetLogWithSource())); + EXPECT_EQ(OK, handle1.Init( + TestGroupId("group1"), params_, DEFAULT_PRIORITY, + SocketTag(), ClientSocketPool::RespectLimits::ENABLED, + callback1.callback(), ClientSocketPool::ProxyAuthCallback(), + pool_.get(), NetLogWithSource())); - MockLayeredPool mock_layered_pool(pool_.get(), "group2"); + MockLayeredPool mock_layered_pool(pool_.get(), TestGroupId("group2")); EXPECT_THAT(mock_layered_pool.RequestSocket(pool_.get()), IsOk()); EXPECT_CALL(mock_layered_pool, CloseOneIdleConnection()) .WillRepeatedly(Invoke(&mock_layered_pool, @@ -4466,8 +4624,8 @@ TestCompletionCallback callback3; EXPECT_EQ( ERR_IO_PENDING, - handle3.Init("group3", params_, DEFAULT_PRIORITY, SocketTag(), - ClientSocketPool::RespectLimits::ENABLED, + handle3.Init(TestGroupId("group3"), params_, DEFAULT_PRIORITY, + SocketTag(), ClientSocketPool::RespectLimits::ENABLED, callback3.callback(), ClientSocketPool::ProxyAuthCallback(), pool_.get(), NetLogWithSource())); @@ -4482,8 +4640,8 @@ TestCompletionCallback callback4; EXPECT_EQ( ERR_IO_PENDING, - handle4.Init("group3", params_, DEFAULT_PRIORITY, SocketTag(), - ClientSocketPool::RespectLimits::ENABLED, + handle4.Init(TestGroupId("group3"), params_, DEFAULT_PRIORITY, + SocketTag(), ClientSocketPool::RespectLimits::ENABLED, callback4.callback(), ClientSocketPool::ProxyAuthCallback(), pool_.get(), NetLogWithSource())); EXPECT_THAT(callback3.WaitForResult(), IsOk()); @@ -4512,13 +4670,13 @@ ClientSocketHandle handle1; TestCompletionCallback callback1; - EXPECT_EQ(OK, handle1.Init("group1", params_, DEFAULT_PRIORITY, SocketTag(), - ClientSocketPool::RespectLimits::ENABLED, - callback1.callback(), - ClientSocketPool::ProxyAuthCallback(), pool_.get(), - NetLogWithSource())); + EXPECT_EQ(OK, handle1.Init( + TestGroupId("group1"), params_, DEFAULT_PRIORITY, + SocketTag(), ClientSocketPool::RespectLimits::ENABLED, + callback1.callback(), ClientSocketPool::ProxyAuthCallback(), + pool_.get(), NetLogWithSource())); - MockLayeredPool mock_layered_pool(pool_.get(), "group2"); + MockLayeredPool mock_layered_pool(pool_.get(), TestGroupId("group2")); EXPECT_THAT(mock_layered_pool.RequestSocket(pool_.get()), IsOk()); EXPECT_CALL(mock_layered_pool, CloseOneIdleConnection()) .WillRepeatedly(Invoke(&mock_layered_pool, @@ -4530,7 +4688,7 @@ TestCompletionCallback callback3; EXPECT_EQ( ERR_IO_PENDING, - handle3.Init("group3", params_, MEDIUM, SocketTag(), + handle3.Init(TestGroupId("group3"), params_, MEDIUM, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, callback3.callback(), ClientSocketPool::ProxyAuthCallback(), pool_.get(), NetLogWithSource())); @@ -4545,7 +4703,7 @@ TestCompletionCallback callback4; EXPECT_EQ( ERR_IO_PENDING, - handle4.Init("group3", params_, HIGHEST, SocketTag(), + handle4.Init(TestGroupId("group3"), params_, HIGHEST, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, callback4.callback(), ClientSocketPool::ProxyAuthCallback(), pool_.get(), NetLogWithSource())); @@ -4562,12 +4720,12 @@ CreatePool(1, 1); connect_job_factory_->set_job_type(TestConnectJob::kMockJob); - MockLayeredPool mock_layered_pool1(pool_.get(), "foo"); + MockLayeredPool mock_layered_pool1(pool_.get(), TestGroupId("foo")); EXPECT_THAT(mock_layered_pool1.RequestSocket(pool_.get()), IsOk()); EXPECT_CALL(mock_layered_pool1, CloseOneIdleConnection()) .WillRepeatedly(Invoke(&mock_layered_pool1, &MockLayeredPool::ReleaseOneConnection)); - MockLayeredPool mock_layered_pool2(pool_.get(), "bar"); + MockLayeredPool mock_layered_pool2(pool_.get(), TestGroupId("bar")); EXPECT_THAT(mock_layered_pool2.RequestSocketWithoutLimits(pool_.get()), IsOk()); EXPECT_CALL(mock_layered_pool2, CloseOneIdleConnection()) @@ -4577,7 +4735,7 @@ TestCompletionCallback callback; EXPECT_EQ( ERR_IO_PENDING, - handle.Init("a", params_, DEFAULT_PRIORITY, SocketTag(), + handle.Init(TestGroupId("a"), params_, DEFAULT_PRIORITY, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, callback.callback(), ClientSocketPool::ProxyAuthCallback(), pool_.get(), NetLogWithSource())); @@ -4592,24 +4750,24 @@ CreatePool(1, 1); // Issue a request to reach the socket pool limit. - EXPECT_EQ( - OK, StartRequestWithIgnoreLimits( - "a", MAXIMUM_PRIORITY, ClientSocketPool::RespectLimits::ENABLED)); - EXPECT_EQ(0u, pool_->NumConnectJobsInGroup("a")); + EXPECT_EQ(OK, StartRequestWithIgnoreLimits( + TestGroupId("a"), MAXIMUM_PRIORITY, + ClientSocketPool::RespectLimits::ENABLED)); + EXPECT_EQ(0u, pool_->NumConnectJobsInGroup(TestGroupId("a"))); connect_job_factory_->set_job_type(TestConnectJob::kMockPendingJob); EXPECT_EQ(ERR_IO_PENDING, StartRequestWithIgnoreLimits( - "a", MAXIMUM_PRIORITY, + TestGroupId("a"), MAXIMUM_PRIORITY, ClientSocketPool::RespectLimits::ENABLED)); - EXPECT_EQ(0u, pool_->NumConnectJobsInGroup("a")); + EXPECT_EQ(0u, pool_->NumConnectJobsInGroup(TestGroupId("a"))); // Issue a request that ignores the limits, so a new ConnectJob is // created. EXPECT_EQ(ERR_IO_PENDING, StartRequestWithIgnoreLimits( - "a", MAXIMUM_PRIORITY, + TestGroupId("a"), MAXIMUM_PRIORITY, ClientSocketPool::RespectLimits::DISABLED)); - ASSERT_EQ(1u, pool_->NumConnectJobsInGroup("a")); + ASSERT_EQ(1u, pool_->NumConnectJobsInGroup(TestGroupId("a"))); EXPECT_THAT(request(2)->WaitForResult(), IsOk()); EXPECT_FALSE(request(1)->have_result()); @@ -4622,29 +4780,29 @@ CreatePool(1, 1); // Issue a request to reach the socket pool limit. - EXPECT_EQ( - OK, StartRequestWithIgnoreLimits( - "a", MAXIMUM_PRIORITY, ClientSocketPool::RespectLimits::ENABLED)); - EXPECT_EQ(0u, pool_->NumConnectJobsInGroup("a")); + EXPECT_EQ(OK, StartRequestWithIgnoreLimits( + TestGroupId("a"), MAXIMUM_PRIORITY, + ClientSocketPool::RespectLimits::ENABLED)); + EXPECT_EQ(0u, pool_->NumConnectJobsInGroup(TestGroupId("a"))); connect_job_factory_->set_job_type(TestConnectJob::kMockPendingJob); EXPECT_EQ(ERR_IO_PENDING, StartRequestWithIgnoreLimits( - "a", MAXIMUM_PRIORITY, + TestGroupId("a"), MAXIMUM_PRIORITY, ClientSocketPool::RespectLimits::ENABLED)); - EXPECT_EQ(0u, pool_->NumConnectJobsInGroup("a")); + EXPECT_EQ(0u, pool_->NumConnectJobsInGroup(TestGroupId("a"))); // Issue a request with RespectLimits::DISABLED, so a new ConnectJob is // created. EXPECT_EQ(ERR_IO_PENDING, StartRequestWithIgnoreLimits( - "a", MAXIMUM_PRIORITY, + TestGroupId("a"), MAXIMUM_PRIORITY, ClientSocketPool::RespectLimits::DISABLED)); - ASSERT_EQ(1u, pool_->NumConnectJobsInGroup("a")); + ASSERT_EQ(1u, pool_->NumConnectJobsInGroup(TestGroupId("a"))); // Cancel the pending request with RespectLimits::ENABLED. The ConnectJob // should not be cancelled. request(1)->handle()->Reset(); - ASSERT_EQ(1u, pool_->NumConnectJobsInGroup("a")); + ASSERT_EQ(1u, pool_->NumConnectJobsInGroup(TestGroupId("a"))); EXPECT_THAT(request(2)->WaitForResult(), IsOk()); EXPECT_FALSE(request(1)->have_result()); @@ -4659,19 +4817,19 @@ TestCompletionCallback callback; EXPECT_EQ( ERR_IO_PENDING, - handle.Init("a", params_, DEFAULT_PRIORITY, SocketTag(), + handle.Init(TestGroupId("a"), params_, DEFAULT_PRIORITY, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, callback.callback(), ClientSocketPool::ProxyAuthCallback(), pool_.get(), NetLogWithSource())); - EXPECT_EQ(1u, pool_->NumConnectJobsInGroup("a")); + EXPECT_EQ(1u, pool_->NumConnectJobsInGroup(TestGroupId("a"))); EXPECT_THAT(callback.WaitForResult(), IsError(ERR_PROXY_AUTH_REQUESTED)); EXPECT_FALSE(handle.is_initialized()); EXPECT_FALSE(handle.socket()); // The group should now be empty, and thus be deleted. - EXPECT_FALSE(pool_->HasGroup("a")); + EXPECT_FALSE(pool_->HasGroup(TestGroupId("a"))); } class TestAuthHelper { @@ -4679,14 +4837,15 @@ TestAuthHelper() = default; ~TestAuthHelper() = default; - void InitHandle(scoped_refptr<TestSocketParams> params, - TestClientSocketPool* pool, - RequestPriority priority = DEFAULT_PRIORITY, - ClientSocketPool::RespectLimits respect_limits = - ClientSocketPool::RespectLimits::ENABLED, - const char* group_name = "a") { + void InitHandle( + scoped_refptr<TestSocketParams> params, + TestClientSocketPool* pool, + RequestPriority priority = DEFAULT_PRIORITY, + ClientSocketPool::RespectLimits respect_limits = + ClientSocketPool::RespectLimits::ENABLED, + const ClientSocketPool::GroupId& group_id_in = TestGroupId("a")) { EXPECT_EQ(ERR_IO_PENDING, - handle_.Init(group_name, params.get(), priority, SocketTag(), + handle_.Init(group_id_in, params.get(), priority, SocketTag(), respect_limits, callback_.callback(), base::BindRepeating(&TestAuthHelper::AuthCallback, base::Unretained(this)), @@ -4775,25 +4934,25 @@ TestAuthHelper auth_helper; auth_helper.InitHandle(params_, pool_.get()); - EXPECT_EQ(1u, pool_->NumConnectJobsInGroup("a")); + EXPECT_EQ(1u, pool_->NumConnectJobsInGroup(TestGroupId("a"))); EXPECT_EQ(LOAD_STATE_CONNECTING, - pool_->GetLoadState("a", auth_helper.handle())); + pool_->GetLoadState(TestGroupId("a"), auth_helper.handle())); auth_helper.WaitForAuth(); - EXPECT_EQ(1u, pool_->NumConnectJobsInGroup("a")); + EXPECT_EQ(1u, pool_->NumConnectJobsInGroup(TestGroupId("a"))); EXPECT_EQ(LOAD_STATE_ESTABLISHING_PROXY_TUNNEL, - pool_->GetLoadState("a", auth_helper.handle())); + pool_->GetLoadState(TestGroupId("a"), auth_helper.handle())); auth_helper.RestartWithAuth(); - EXPECT_EQ(1u, pool_->NumConnectJobsInGroup("a")); + EXPECT_EQ(1u, pool_->NumConnectJobsInGroup(TestGroupId("a"))); EXPECT_EQ(LOAD_STATE_ESTABLISHING_PROXY_TUNNEL, - pool_->GetLoadState("a", auth_helper.handle())); + pool_->GetLoadState(TestGroupId("a"), auth_helper.handle())); EXPECT_THAT(auth_helper.WaitForResult(), IsOk()); EXPECT_EQ(1, auth_helper.auth_count()); - EXPECT_EQ(0u, pool_->NumConnectJobsInGroup("a")); - EXPECT_EQ(1, pool_->NumActiveSocketsInGroup("a")); - EXPECT_EQ(0u, pool_->IdleSocketCountInGroup("a")); + EXPECT_EQ(0u, pool_->NumConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(1, pool_->NumActiveSocketsInGroup(TestGroupId("a"))); + EXPECT_EQ(0u, pool_->IdleSocketCountInGroup(TestGroupId("a"))); EXPECT_EQ(0, pool_->IdleSocketCount()); } @@ -4803,20 +4962,20 @@ TestAuthHelper auth_helper; auth_helper.InitHandle(params_, pool_.get()); - EXPECT_EQ(1u, pool_->NumConnectJobsInGroup("a")); + EXPECT_EQ(1u, pool_->NumConnectJobsInGroup(TestGroupId("a"))); EXPECT_EQ(LOAD_STATE_CONNECTING, - pool_->GetLoadState("a", auth_helper.handle())); + pool_->GetLoadState(TestGroupId("a"), auth_helper.handle())); auth_helper.WaitForAuthAndRestartSync(); - EXPECT_EQ(1u, pool_->NumConnectJobsInGroup("a")); + EXPECT_EQ(1u, pool_->NumConnectJobsInGroup(TestGroupId("a"))); EXPECT_EQ(LOAD_STATE_ESTABLISHING_PROXY_TUNNEL, - pool_->GetLoadState("a", auth_helper.handle())); + pool_->GetLoadState(TestGroupId("a"), auth_helper.handle())); EXPECT_THAT(auth_helper.WaitForResult(), IsOk()); EXPECT_EQ(1, auth_helper.auth_count()); - EXPECT_EQ(0u, pool_->NumConnectJobsInGroup("a")); - EXPECT_EQ(1, pool_->NumActiveSocketsInGroup("a")); - EXPECT_EQ(0u, pool_->IdleSocketCountInGroup("a")); + EXPECT_EQ(0u, pool_->NumConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(1, pool_->NumActiveSocketsInGroup(TestGroupId("a"))); + EXPECT_EQ(0u, pool_->IdleSocketCountInGroup(TestGroupId("a"))); EXPECT_EQ(0, pool_->IdleSocketCount()); } @@ -4827,14 +4986,14 @@ TestAuthHelper auth_helper; auth_helper.InitHandle(params_, pool_.get()); - EXPECT_EQ(1u, pool_->NumConnectJobsInGroup("a")); + EXPECT_EQ(1u, pool_->NumConnectJobsInGroup(TestGroupId("a"))); auth_helper.WaitForAuth(); auth_helper.RestartWithAuth(); EXPECT_THAT(auth_helper.WaitForResult(), IsError(ERR_CONNECTION_FAILED)); EXPECT_EQ(1, auth_helper.auth_count()); - EXPECT_FALSE(pool_->HasGroup("a")); + EXPECT_FALSE(pool_->HasGroup(TestGroupId("a"))); EXPECT_EQ(0, pool_->IdleSocketCount()); } @@ -4845,13 +5004,13 @@ TestAuthHelper auth_helper; auth_helper.InitHandle(params_, pool_.get()); - EXPECT_EQ(1u, pool_->NumConnectJobsInGroup("a")); + EXPECT_EQ(1u, pool_->NumConnectJobsInGroup(TestGroupId("a"))); auth_helper.WaitForAuthAndRestartSync(); EXPECT_THAT(auth_helper.WaitForResult(), IsError(ERR_CONNECTION_FAILED)); EXPECT_EQ(1, auth_helper.auth_count()); - EXPECT_FALSE(pool_->HasGroup("a")); + EXPECT_FALSE(pool_->HasGroup(TestGroupId("a"))); EXPECT_EQ(0, pool_->IdleSocketCount()); } @@ -4861,15 +5020,15 @@ TestAuthHelper auth_helper; auth_helper.InitHandle(params_, pool_.get()); - EXPECT_EQ(1u, pool_->NumConnectJobsInGroup("a")); + EXPECT_EQ(1u, pool_->NumConnectJobsInGroup(TestGroupId("a"))); auth_helper.WaitForAuth(); - EXPECT_EQ(1u, pool_->NumConnectJobsInGroup("a")); + EXPECT_EQ(1u, pool_->NumConnectJobsInGroup(TestGroupId("a"))); auth_helper.handle()->Reset(); EXPECT_EQ(1, auth_helper.auth_count()); - EXPECT_FALSE(pool_->HasGroup("a")); + EXPECT_FALSE(pool_->HasGroup(TestGroupId("a"))); EXPECT_EQ(0, pool_->IdleSocketCount()); EXPECT_FALSE(auth_helper.handle()->is_initialized()); EXPECT_FALSE(auth_helper.handle()->socket()); @@ -4881,11 +5040,11 @@ TestAuthHelper auth_helper; auth_helper.InitHandle(params_, pool_.get()); - EXPECT_EQ(1u, pool_->NumConnectJobsInGroup("a")); + EXPECT_EQ(1u, pool_->NumConnectJobsInGroup(TestGroupId("a"))); auth_helper.WaitForAuthAndResetHandleSync(); EXPECT_EQ(1, auth_helper.auth_count()); - EXPECT_FALSE(pool_->HasGroup("a")); + EXPECT_FALSE(pool_->HasGroup(TestGroupId("a"))); EXPECT_EQ(0, pool_->IdleSocketCount()); EXPECT_FALSE(auth_helper.handle()->is_initialized()); EXPECT_FALSE(auth_helper.handle()->socket()); @@ -4897,7 +5056,7 @@ TestAuthHelper auth_helper; auth_helper.InitHandle(params_, pool_.get()); - EXPECT_EQ(1u, pool_->NumConnectJobsInGroup("a")); + EXPECT_EQ(1u, pool_->NumConnectJobsInGroup(TestGroupId("a"))); auth_helper.WaitForAuth(); @@ -4907,7 +5066,7 @@ // When flushing the socket pool, bound sockets should delay returning the // error until completion. EXPECT_FALSE(auth_helper.have_result()); - EXPECT_EQ(1u, pool_->NumConnectJobsInGroup("a")); + EXPECT_EQ(1u, pool_->NumConnectJobsInGroup(TestGroupId("a"))); EXPECT_EQ(0, pool_->IdleSocketCount()); auth_helper.RestartWithAuth(); @@ -4915,7 +5074,7 @@ EXPECT_FALSE(auth_helper.have_result()); EXPECT_THAT(auth_helper.WaitForResult(), IsError(ERR_FAILED)); - EXPECT_FALSE(pool_->HasGroup("a")); + EXPECT_FALSE(pool_->HasGroup(TestGroupId("a"))); EXPECT_EQ(0, pool_->IdleSocketCount()); } @@ -4926,34 +5085,34 @@ TestAuthHelper auth_helper; auth_helper.InitHandle(params_, pool_.get()); - EXPECT_EQ(1u, pool_->NumConnectJobsInGroup("a")); + EXPECT_EQ(1u, pool_->NumConnectJobsInGroup(TestGroupId("a"))); EXPECT_EQ(LOAD_STATE_CONNECTING, - pool_->GetLoadState("a", auth_helper.handle())); + pool_->GetLoadState(TestGroupId("a"), auth_helper.handle())); auth_helper.WaitForAuth(); auth_helper.RestartWithAuth(); - EXPECT_EQ(1u, pool_->NumConnectJobsInGroup("a")); + EXPECT_EQ(1u, pool_->NumConnectJobsInGroup(TestGroupId("a"))); EXPECT_EQ(1, auth_helper.auth_count()); EXPECT_EQ(LOAD_STATE_ESTABLISHING_PROXY_TUNNEL, - pool_->GetLoadState("a", auth_helper.handle())); + pool_->GetLoadState(TestGroupId("a"), auth_helper.handle())); auth_helper.WaitForAuth(); - EXPECT_EQ(1u, pool_->NumConnectJobsInGroup("a")); + EXPECT_EQ(1u, pool_->NumConnectJobsInGroup(TestGroupId("a"))); EXPECT_EQ(2, auth_helper.auth_count()); EXPECT_EQ(LOAD_STATE_ESTABLISHING_PROXY_TUNNEL, - pool_->GetLoadState("a", auth_helper.handle())); + pool_->GetLoadState(TestGroupId("a"), auth_helper.handle())); auth_helper.RestartWithAuth(); - EXPECT_EQ(1u, pool_->NumConnectJobsInGroup("a")); + EXPECT_EQ(1u, pool_->NumConnectJobsInGroup(TestGroupId("a"))); EXPECT_EQ(2, auth_helper.auth_count()); EXPECT_EQ(LOAD_STATE_ESTABLISHING_PROXY_TUNNEL, - pool_->GetLoadState("a", auth_helper.handle())); + pool_->GetLoadState(TestGroupId("a"), auth_helper.handle())); EXPECT_THAT(auth_helper.WaitForResult(), IsOk()); EXPECT_EQ(2, auth_helper.auth_count()); - EXPECT_EQ(0u, pool_->NumConnectJobsInGroup("a")); - EXPECT_EQ(1, pool_->NumActiveSocketsInGroup("a")); - EXPECT_EQ(0u, pool_->IdleSocketCountInGroup("a")); + EXPECT_EQ(0u, pool_->NumConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(1, pool_->NumActiveSocketsInGroup(TestGroupId("a"))); + EXPECT_EQ(0u, pool_->IdleSocketCountInGroup(TestGroupId("a"))); EXPECT_EQ(0, pool_->IdleSocketCount()); } @@ -4964,21 +5123,21 @@ TestAuthHelper auth_helper; auth_helper.InitHandle(params_, pool_.get()); - EXPECT_EQ(1u, pool_->NumConnectJobsInGroup("a")); + EXPECT_EQ(1u, pool_->NumConnectJobsInGroup(TestGroupId("a"))); auth_helper.WaitForAuth(); auth_helper.RestartWithAuth(); - EXPECT_EQ(1u, pool_->NumConnectJobsInGroup("a")); + EXPECT_EQ(1u, pool_->NumConnectJobsInGroup(TestGroupId("a"))); EXPECT_EQ(1, auth_helper.auth_count()); auth_helper.WaitForAuth(); auth_helper.RestartWithAuth(); - EXPECT_EQ(1u, pool_->NumConnectJobsInGroup("a")); + EXPECT_EQ(1u, pool_->NumConnectJobsInGroup(TestGroupId("a"))); EXPECT_EQ(2, auth_helper.auth_count()); EXPECT_THAT(auth_helper.WaitForResult(), IsError(ERR_CONNECTION_FAILED)); EXPECT_EQ(2, auth_helper.auth_count()); - EXPECT_FALSE(pool_->HasGroup("a")); + EXPECT_FALSE(pool_->HasGroup(TestGroupId("a"))); EXPECT_EQ(0, pool_->IdleSocketCount()); } @@ -4993,32 +5152,32 @@ // First request creates a ConnectJob. TestAuthHelper auth_helper1; auth_helper1.InitHandle(params_, pool_.get()); - EXPECT_EQ(1u, pool_->NumConnectJobsInGroup("a")); + EXPECT_EQ(1u, pool_->NumConnectJobsInGroup(TestGroupId("a"))); // A second request come in, but no new ConnectJob is needed, since the limit // has been reached. TestAuthHelper auth_helper2; auth_helper2.InitHandle(params_, pool_.get()); - EXPECT_EQ(1u, pool_->NumConnectJobsInGroup("a")); + EXPECT_EQ(1u, pool_->NumConnectJobsInGroup(TestGroupId("a"))); // Run until the auth callback for the first request is invoked. auth_helper1.WaitForAuth(); EXPECT_EQ(0, auth_helper2.auth_count()); - EXPECT_EQ(1u, pool_->NumConnectJobsInGroup("a")); - EXPECT_EQ(0, pool_->NumActiveSocketsInGroup("a")); - EXPECT_EQ(0u, pool_->IdleSocketCountInGroup("a")); + EXPECT_EQ(1u, pool_->NumConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(0, pool_->NumActiveSocketsInGroup(TestGroupId("a"))); + EXPECT_EQ(0u, pool_->IdleSocketCountInGroup(TestGroupId("a"))); // Make connect jobs succeed, then cancel the first request, which should // destroy the bound ConnectJob, and cause a new ConnectJob to start. connect_job_factory_->set_job_type(TestConnectJob::kMockPendingJob); auth_helper1.handle()->Reset(); EXPECT_EQ(0, auth_helper2.auth_count()); - EXPECT_EQ(1u, pool_->NumConnectJobsInGroup("a")); + EXPECT_EQ(1u, pool_->NumConnectJobsInGroup(TestGroupId("a"))); // The second ConnectJob should succeed. EXPECT_THAT(auth_helper2.WaitForResult(), IsOk()); EXPECT_EQ(0, auth_helper2.auth_count()); - EXPECT_EQ(0u, pool_->NumConnectJobsInGroup("a")); + EXPECT_EQ(0u, pool_->NumConnectJobsInGroup(TestGroupId("a"))); } // Makes sure that when a bound request is destroyed, a new ConnectJob is @@ -5032,25 +5191,26 @@ // First request creates a ConnectJob. TestAuthHelper auth_helper1; auth_helper1.InitHandle(params_, pool_.get(), DEFAULT_PRIORITY); - EXPECT_EQ(1u, pool_->NumConnectJobsInGroup("a")); + EXPECT_EQ(1u, pool_->NumConnectJobsInGroup(TestGroupId("a"))); // A second request come in, but no new ConnectJob is needed, since the limit // has been reached. TestAuthHelper auth_helper2; auth_helper2.InitHandle(params_, pool_.get(), DEFAULT_PRIORITY, - ClientSocketPool::RespectLimits::ENABLED, "b"); - EXPECT_EQ(1u, pool_->NumConnectJobsInGroup("a")); - EXPECT_EQ(0u, pool_->NumConnectJobsInGroup("b")); + ClientSocketPool::RespectLimits::ENABLED, + TestGroupId("b")); + EXPECT_EQ(1u, pool_->NumConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(0u, pool_->NumConnectJobsInGroup(TestGroupId("b"))); // Run until the auth callback for the first request is invoked. auth_helper1.WaitForAuth(); EXPECT_EQ(0, auth_helper2.auth_count()); - EXPECT_EQ(1u, pool_->NumConnectJobsInGroup("a")); - EXPECT_EQ(0, pool_->NumActiveSocketsInGroup("a")); - EXPECT_EQ(0u, pool_->IdleSocketCountInGroup("a")); - EXPECT_EQ(0u, pool_->NumConnectJobsInGroup("b")); - EXPECT_EQ(0, pool_->NumActiveSocketsInGroup("b")); - EXPECT_EQ(0u, pool_->IdleSocketCountInGroup("b")); + EXPECT_EQ(1u, pool_->NumConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(0, pool_->NumActiveSocketsInGroup(TestGroupId("a"))); + EXPECT_EQ(0u, pool_->IdleSocketCountInGroup(TestGroupId("a"))); + EXPECT_EQ(0u, pool_->NumConnectJobsInGroup(TestGroupId("b"))); + EXPECT_EQ(0, pool_->NumActiveSocketsInGroup(TestGroupId("b"))); + EXPECT_EQ(0u, pool_->IdleSocketCountInGroup(TestGroupId("b"))); // Make connect jobs succeed, then cancel the first request, which should // destroy the bound ConnectJob, and cause a new ConnectJob to start for the @@ -5058,14 +5218,14 @@ connect_job_factory_->set_job_type(TestConnectJob::kMockPendingJob); auth_helper1.handle()->Reset(); EXPECT_EQ(0, auth_helper2.auth_count()); - EXPECT_FALSE(pool_->HasGroup("a")); - EXPECT_EQ(1u, pool_->NumConnectJobsInGroup("b")); + EXPECT_FALSE(pool_->HasGroup(TestGroupId("a"))); + EXPECT_EQ(1u, pool_->NumConnectJobsInGroup(TestGroupId("b"))); // The second ConnectJob should succeed. EXPECT_THAT(auth_helper2.WaitForResult(), IsOk()); EXPECT_EQ(0, auth_helper2.auth_count()); - EXPECT_FALSE(pool_->HasGroup("a")); - EXPECT_EQ(0u, pool_->NumConnectJobsInGroup("b")); + EXPECT_FALSE(pool_->HasGroup(TestGroupId("a"))); + EXPECT_EQ(0u, pool_->NumConnectJobsInGroup(TestGroupId("b"))); } // Test that once an auth challenge is bound, that's the request that gets all @@ -5078,25 +5238,25 @@ // First request creates a ConnectJob. TestAuthHelper auth_helper1; auth_helper1.InitHandle(params_, pool_.get(), LOWEST); - EXPECT_EQ(1u, pool_->NumConnectJobsInGroup("a")); + EXPECT_EQ(1u, pool_->NumConnectJobsInGroup(TestGroupId("a"))); // A second, higher priority request is made. TestAuthHelper auth_helper2; auth_helper2.InitHandle(params_, pool_.get(), LOW); - EXPECT_EQ(1u, pool_->NumConnectJobsInGroup("a")); + EXPECT_EQ(1u, pool_->NumConnectJobsInGroup(TestGroupId("a"))); // Run until the auth callback for the second request is invoked. auth_helper2.WaitForAuth(); EXPECT_EQ(0, auth_helper1.auth_count()); - EXPECT_EQ(1u, pool_->NumConnectJobsInGroup("a")); - EXPECT_EQ(0, pool_->NumActiveSocketsInGroup("a")); - EXPECT_EQ(0u, pool_->IdleSocketCountInGroup("a")); + EXPECT_EQ(1u, pool_->NumConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(0, pool_->NumActiveSocketsInGroup(TestGroupId("a"))); + EXPECT_EQ(0u, pool_->IdleSocketCountInGroup(TestGroupId("a"))); // Start a higher priority job. It shouldn't be able to steal |auth_helper2|'s // ConnectJob. TestAuthHelper auth_helper3; auth_helper3.InitHandle(params_, pool_.get(), HIGHEST); - EXPECT_EQ(1u, pool_->NumConnectJobsInGroup("a")); + EXPECT_EQ(1u, pool_->NumConnectJobsInGroup(TestGroupId("a"))); // Start a higher job that ignores limits, creating a hanging socket. It // shouldn't be able to steal |auth_helper2|'s ConnectJob. @@ -5104,7 +5264,7 @@ TestAuthHelper auth_helper4; auth_helper4.InitHandle(params_, pool_.get(), HIGHEST, ClientSocketPool::RespectLimits::DISABLED); - EXPECT_EQ(2u, pool_->NumConnectJobsInGroup("a")); + EXPECT_EQ(2u, pool_->NumConnectJobsInGroup(TestGroupId("a"))); // Restart with auth, and |auth_helper2|'s auth method should be invoked // again. @@ -5124,8 +5284,8 @@ EXPECT_THAT(auth_helper2.WaitForResult(), IsOk()); // The hung ConnectJob for the RespectLimits::DISABLED request is still in the // socket pool. - EXPECT_EQ(1u, pool_->NumConnectJobsInGroup("a")); - EXPECT_EQ(1, pool_->NumActiveSocketsInGroup("a")); + EXPECT_EQ(1u, pool_->NumConnectJobsInGroup(TestGroupId("a"))); + EXPECT_EQ(1, pool_->NumActiveSocketsInGroup(TestGroupId("a"))); EXPECT_EQ(0, auth_helper1.auth_count()); EXPECT_FALSE(auth_helper1.have_result()); EXPECT_EQ(0, auth_helper3.auth_count());
diff --git a/net/socket/client_socket_pool_manager.cc b/net/socket/client_socket_pool_manager.cc index f3831a8..e9e73f78 100644 --- a/net/socket/client_socket_pool_manager.cc +++ b/net/socket/client_socket_pool_manager.cc
@@ -68,7 +68,7 @@ // The meat of the implementation for the InitSocketHandleForHttpRequest, // InitSocketHandleForRawConnect and PreconnectSocketsForHttpRequest methods. scoped_refptr<TransportClientSocketPool::SocketParams> -CreateSocketParamsAndGetGroupName( +CreateSocketParamsAndGetGroupId( ClientSocketPoolManager::SocketGroupType group_type, const HostPortPair& endpoint, int request_load_flags, @@ -80,7 +80,7 @@ bool force_tunnel, PrivacyMode privacy_mode, const OnHostResolutionCallback& resolution_callback, - std::string* connection_group) { + ClientSocketPool::GroupId* connection_group) { scoped_refptr<HttpProxySocketParams> http_proxy_params; scoped_refptr<SOCKSSocketParams> socks_params; @@ -99,22 +99,27 @@ // Build the string used to uniquely identify connections of this type. // Determine the host and port to connect to. - *connection_group = origin_host_port.ToString(); - DCHECK(!connection_group->empty()); + DCHECK(!origin_host_port.IsEmpty()); + ClientSocketPool::SocketType socket_type = + ClientSocketPool::SocketType::kHttp; + if (group_type == ClientSocketPoolManager::FTP_GROUP) { // Combining FTP with forced SPDY over SSL would be a "path to madness". // Make sure we never do that. DCHECK(!using_ssl); - *connection_group = "ftp/" + *connection_group; + socket_type = ClientSocketPool::SocketType::kFtp; } if (using_ssl) { - std::string prefix = "ssl/"; - if (ssl_config_for_origin.version_interference_probe) { - prefix += "version-interference-probe/"; + if (!ssl_config_for_origin.version_interference_probe) { + socket_type = ClientSocketPool::SocketType::kSsl; + } else { + socket_type = ClientSocketPool::SocketType::kSslVersionInterferenceProbe; } - *connection_group = prefix + *connection_group; } + *connection_group = ClientSocketPool::GroupId( + origin_host_port, socket_type, privacy_mode == PRIVACY_MODE_ENABLED); + if (!proxy_info.is_direct()) { ProxyServer proxy_server = proxy_info.proxy_server(); scoped_refptr<TransportSocketParams> proxy_tcp_params( @@ -153,10 +158,6 @@ } } - // Change group name if privacy mode is enabled. - if (privacy_mode == PRIVACY_MODE_ENABLED) - *connection_group = "pm/" + *connection_group; - // Deal with SSL - which layers on top of any given proxy. if (using_ssl) { scoped_refptr<TransportSocketParams> ssl_tcp_params; @@ -209,9 +210,9 @@ const OnHostResolutionCallback& resolution_callback, CompletionOnceCallback callback, const ClientSocketPool::ProxyAuthCallback& proxy_auth_callback) { - std::string connection_group; + ClientSocketPool::GroupId connection_group; scoped_refptr<TransportClientSocketPool::SocketParams> socket_params = - CreateSocketParamsAndGetGroupName( + CreateSocketParamsAndGetGroupId( group_type, endpoint, request_load_flags, session, proxy_info, quic_version, ssl_config_for_origin, ssl_config_for_proxy, force_tunnel, privacy_mode, resolution_callback, &connection_group);
diff --git a/net/socket/client_socket_pool_unittest.cc b/net/socket/client_socket_pool_unittest.cc new file mode 100644 index 0000000..cd0755a --- /dev/null +++ b/net/socket/client_socket_pool_unittest.cc
@@ -0,0 +1,128 @@ +// 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 "net/socket/client_socket_pool.h" + +#include <string> +#include <vector> + +#include "net/base/host_port_pair.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace net { + +namespace { + +TEST(ClientSocketPool, GroupIdOperators) { + // Each of these lists is in "<" order, as defined by Group::operator< on the + // corresponding field. + + // HostPortPair::operator< compares port before host. + const HostPortPair kHostPortPairs[] = { + {"b", 79}, {"a", 80}, {"b", 80}, {"c", 81}, {"a", 443}, {"c", 443}, + }; + + const ClientSocketPool::SocketType kSocketTypes[] = { + ClientSocketPool::SocketType::kHttp, + ClientSocketPool::SocketType::kSsl, + ClientSocketPool::SocketType::kSslVersionInterferenceProbe, + ClientSocketPool::SocketType::kFtp, + }; + + const bool kPrivacyModes[] = {false, true}; + + // All previously created |group_ids|. They should all be less than the + // current group under consideration. + std::vector<ClientSocketPool::GroupId> group_ids; + + // Iterate through all sets of group ids, from least to greatest. + for (const auto& host_port_pair : kHostPortPairs) { + SCOPED_TRACE(host_port_pair.ToString()); + for (const auto& socket_type : kSocketTypes) { + SCOPED_TRACE(static_cast<int>(socket_type)); + for (const auto& privacy_mode : kPrivacyModes) { + SCOPED_TRACE(privacy_mode); + + ClientSocketPool::GroupId group_id(host_port_pair, socket_type, + privacy_mode); + for (const auto& lower_group_id : group_ids) { + EXPECT_FALSE(lower_group_id == group_id); + EXPECT_TRUE(lower_group_id < group_id); + EXPECT_FALSE(group_id < lower_group_id); + } + + group_ids.push_back(group_id); + + // Compare |group_id| to itself. Use two different copies of + // |group_id|'s value, since to protect against bugs where an object + // only equals itself. + EXPECT_TRUE(group_ids.back() == group_id); + EXPECT_FALSE(group_ids.back() < group_id); + EXPECT_FALSE(group_id < group_ids.back()); + } + } + } +} + +TEST(ClientSocketPool, GroupIdToString) { + EXPECT_EQ("foo:80", + ClientSocketPool::GroupId(HostPortPair("foo", 80), + ClientSocketPool::SocketType::kHttp, + false /* privacy_mode */) + .ToString()); + EXPECT_EQ("bar:443", + ClientSocketPool::GroupId(HostPortPair("bar", 443), + ClientSocketPool::SocketType::kHttp, + false /* privacy_mode */) + .ToString()); + EXPECT_EQ("pm/bar:80", + ClientSocketPool::GroupId(HostPortPair("bar", 80), + ClientSocketPool::SocketType::kHttp, + true /* privacy_mode */) + .ToString()); + + EXPECT_EQ("ssl/foo:80", + ClientSocketPool::GroupId(HostPortPair("foo", 80), + ClientSocketPool::SocketType::kSsl, + false /* privacy_mode */) + .ToString()); + EXPECT_EQ("ssl/bar:443", + ClientSocketPool::GroupId(HostPortPair("bar", 443), + ClientSocketPool::SocketType::kSsl, + false /* privacy_mode */) + .ToString()); + EXPECT_EQ("pm/ssl/bar:80", + ClientSocketPool::GroupId(HostPortPair("bar", 80), + ClientSocketPool::SocketType::kSsl, + true /* privacy_mode */) + .ToString()); + + EXPECT_EQ("version-interference-probe/ssl/foo:443", + ClientSocketPool::GroupId( + HostPortPair("foo", 443), + ClientSocketPool::SocketType::kSslVersionInterferenceProbe, + false /* privacy_mode */) + .ToString()); + EXPECT_EQ("pm/version-interference-probe/ssl/bar:444", + ClientSocketPool::GroupId( + HostPortPair("bar", 444), + ClientSocketPool::SocketType::kSslVersionInterferenceProbe, + true /* privacy_mode */) + .ToString()); + + EXPECT_EQ("ftp/foo:80", + ClientSocketPool::GroupId(HostPortPair("foo", 80), + ClientSocketPool::SocketType::kFtp, + false /* privacy_mode */) + .ToString()); + EXPECT_EQ("pm/ftp/bar:81", + ClientSocketPool::GroupId(HostPortPair("bar", 81), + ClientSocketPool::SocketType::kFtp, + true /* privacy_mode */) + .ToString()); +} + +} // namespace + +} // namespace net
diff --git a/net/socket/socket_test_util.cc b/net/socket/socket_test_util.cc index a234ab5..f80db6c 100644 --- a/net/socket/socket_test_util.cc +++ b/net/socket/socket_test_util.cc
@@ -2098,7 +2098,7 @@ MockTransportClientSocketPool::~MockTransportClientSocketPool() = default; int MockTransportClientSocketPool::RequestSocket( - const std::string& group_name, + const ClientSocketPool::GroupId& group_id, const void* socket_params, RequestPriority priority, const SocketTag& socket_tag, @@ -2118,9 +2118,10 @@ return job->Connect(); } -void MockTransportClientSocketPool::SetPriority(const std::string& group_name, - ClientSocketHandle* handle, - RequestPriority priority) { +void MockTransportClientSocketPool::SetPriority( + const ClientSocketPool::GroupId& group_id, + ClientSocketHandle* handle, + RequestPriority priority) { for (auto& job : job_list_) { if (job->handle() == handle) { job->set_priority(priority); @@ -2130,8 +2131,9 @@ NOTREACHED(); } -void MockTransportClientSocketPool::CancelRequest(const std::string& group_name, - ClientSocketHandle* handle) { +void MockTransportClientSocketPool::CancelRequest( + const ClientSocketPool::GroupId& group_id, + ClientSocketHandle* handle) { for (std::unique_ptr<MockConnectJob>& it : job_list_) { if (it->CancelHandle(handle)) { cancel_count_++; @@ -2141,7 +2143,7 @@ } void MockTransportClientSocketPool::ReleaseSocket( - const std::string& group_name, + const ClientSocketPool::GroupId& group_id, std::unique_ptr<StreamSocket> socket, int id) { EXPECT_EQ(1, id);
diff --git a/net/socket/socket_test_util.h b/net/socket/socket_test_util.h index b08ca4a5..bf66bb4c 100644 --- a/net/socket/socket_test_util.h +++ b/net/socket/socket_test_util.h
@@ -35,6 +35,7 @@ #include "net/log/net_log_with_source.h" #include "net/socket/client_socket_factory.h" #include "net/socket/client_socket_handle.h" +#include "net/socket/client_socket_pool.h" #include "net/socket/connection_attempts.h" #include "net/socket/datagram_client_socket.h" #include "net/socket/socket_performance_watcher.h" @@ -1103,7 +1104,7 @@ template <typename PoolType> int StartRequestUsingPool( PoolType* socket_pool, - const std::string& group_name, + const ClientSocketPool::GroupId& group_id, RequestPriority priority, ClientSocketPool::RespectLimits respect_limits, const scoped_refptr<typename PoolType::SocketParams>& socket_params) { @@ -1112,7 +1113,7 @@ new TestSocketRequest(&request_order_, &completion_count_)); requests_.push_back(base::WrapUnique(request)); int rv = request->handle()->Init( - group_name, socket_params, priority, SocketTag(), respect_limits, + group_id, socket_params, priority, SocketTag(), respect_limits, request->callback(), ClientSocketPool::ProxyAuthCallback(), socket_pool, NetLogWithSource()); if (rv != ERR_IO_PENDING) @@ -1211,7 +1212,7 @@ int cancel_count() const { return cancel_count_; } // TransportClientSocketPool implementation. - int RequestSocket(const std::string& group_name, + int RequestSocket(const GroupId& group_id, const void* socket_params, RequestPriority priority, const SocketTag& socket_tag, @@ -1220,12 +1221,12 @@ CompletionOnceCallback callback, const ProxyAuthCallback& on_auth_callback, const NetLogWithSource& net_log) override; - void SetPriority(const std::string& group_name, + void SetPriority(const GroupId& group_id, ClientSocketHandle* handle, RequestPriority priority) override; - void CancelRequest(const std::string& group_name, + void CancelRequest(const GroupId& group_id, ClientSocketHandle* handle) override; - void ReleaseSocket(const std::string& group_name, + void ReleaseSocket(const GroupId& group_id, std::unique_ptr<StreamSocket> socket, int id) override;
diff --git a/net/socket/ssl_server_socket_unittest.cc b/net/socket/ssl_server_socket_unittest.cc index 967d384d..20f873f 100644 --- a/net/socket/ssl_server_socket_unittest.cc +++ b/net/socket/ssl_server_socket_unittest.cc
@@ -384,7 +384,6 @@ server_ssl_private_key_ = WrapOpenSSLPrivateKey(bssl::UpRef(key->key())); client_ssl_config_.false_start_enabled = false; - client_ssl_config_.channel_id_enabled = false; // Certificate provided by the host doesn't need authority. client_ssl_config_.allowed_bad_certs.emplace_back(
diff --git a/net/socket/transport_client_socket_pool.cc b/net/socket/transport_client_socket_pool.cc index 69b9224f..a348138cf 100644 --- a/net/socket/transport_client_socket_pool.cc +++ b/net/socket/transport_client_socket_pool.cc
@@ -4,6 +4,8 @@ #include "net/socket/transport_client_socket_pool.h" +#include <utility> + #include "base/bind.h" #include "base/compiler_specific.h" #include "base/logging.h" @@ -30,6 +32,15 @@ namespace { +std::unique_ptr<base::Value> NetLogGroupIdCallback( + const ClientSocketPool::GroupId* group_id, + NetLogCaptureMode /* capture_mode */) { + std::unique_ptr<base::DictionaryValue> event_params( + new base::DictionaryValue()); + event_params->SetString("group_id", group_id->ToString()); + return event_params; +} + // TODO(mmenke): Once the socket pool arguments are no longer needed, remove // this method and use TransportConnectJob::CreateTransportConnectJob() // directly. @@ -208,7 +219,7 @@ } int TransportClientSocketPool::RequestSocket( - const std::string& group_name, + const GroupId& group_id, const void* params, RequestPriority priority, const SocketTag& socket_tag, @@ -220,25 +231,26 @@ const scoped_refptr<SocketParams>* casted_params = static_cast<const scoped_refptr<SocketParams>*>(params); - NetLogTcpClientSocketPoolRequestedSocket(net_log, group_name); + NetLogTcpClientSocketPoolRequestedSocket(net_log, group_id); - return base_.RequestSocket(group_name, *casted_params, priority, socket_tag, + return base_.RequestSocket(group_id, *casted_params, priority, socket_tag, respect_limits, handle, std::move(callback), proxy_auth_callback, net_log); } void TransportClientSocketPool::NetLogTcpClientSocketPoolRequestedSocket( const NetLogWithSource& net_log, - const std::string& group_name) { + const GroupId& group_id) { if (net_log.IsCapturing()) { // TODO(eroman): Split out the host and port parameters. net_log.AddEvent(NetLogEventType::TCP_CLIENT_SOCKET_POOL_REQUESTED_SOCKET, - NetLog::StringCallback("group", &group_name)); + base::BindRepeating(&NetLogGroupIdCallback, + base::Unretained(&group_id))); } } void TransportClientSocketPool::RequestSockets( - const std::string& group_name, + const GroupId& group_id, const void* params, int num_sockets, const NetLogWithSource& net_log) { @@ -248,29 +260,29 @@ if (net_log.IsCapturing()) { // TODO(eroman): Split out the host and port parameters. net_log.AddEvent(NetLogEventType::TCP_CLIENT_SOCKET_POOL_REQUESTED_SOCKETS, - NetLog::StringCallback("group_name", &group_name)); + base::BindRepeating(&NetLogGroupIdCallback, + base::Unretained(&group_id))); } - base_.RequestSockets(group_name, *casted_params, num_sockets, net_log); + base_.RequestSockets(group_id, *casted_params, num_sockets, net_log); } -void TransportClientSocketPool::SetPriority(const std::string& group_name, +void TransportClientSocketPool::SetPriority(const GroupId& group_id, ClientSocketHandle* handle, RequestPriority priority) { - base_.SetPriority(group_name, handle, priority); + base_.SetPriority(group_id, handle, priority); } -void TransportClientSocketPool::CancelRequest( - const std::string& group_name, - ClientSocketHandle* handle) { - base_.CancelRequest(group_name, handle); +void TransportClientSocketPool::CancelRequest(const GroupId& group_id, + ClientSocketHandle* handle) { + base_.CancelRequest(group_id, handle); } void TransportClientSocketPool::ReleaseSocket( - const std::string& group_name, + const GroupId& group_id, std::unique_ptr<StreamSocket> socket, int id) { - base_.ReleaseSocket(group_name, std::move(socket), id); + base_.ReleaseSocket(group_id, std::move(socket), id); } void TransportClientSocketPool::FlushWithError(int error) { @@ -282,8 +294,8 @@ } void TransportClientSocketPool::CloseIdleSocketsInGroup( - const std::string& group_name) { - base_.CloseIdleSocketsInGroup(group_name); + const GroupId& group_id) { + base_.CloseIdleSocketsInGroup(group_id); } int TransportClientSocketPool::IdleSocketCount() const { @@ -291,13 +303,14 @@ } size_t TransportClientSocketPool::IdleSocketCountInGroup( - const std::string& group_name) const { - return base_.IdleSocketCountInGroup(group_name); + const GroupId& group_id) const { + return base_.IdleSocketCountInGroup(group_id); } LoadState TransportClientSocketPool::GetLoadState( - const std::string& group_name, const ClientSocketHandle* handle) const { - return base_.GetLoadState(group_name, handle); + const GroupId& group_id, + const ClientSocketHandle* handle) const { + return base_.GetLoadState(group_id, handle); } std::unique_ptr<base::DictionaryValue>
diff --git a/net/socket/transport_client_socket_pool.h b/net/socket/transport_client_socket_pool.h index eda35d4..2c800ba4 100644 --- a/net/socket/transport_client_socket_pool.h +++ b/net/socket/transport_client_socket_pool.h
@@ -115,7 +115,7 @@ ~TransportClientSocketPool() override; // ClientSocketPool implementation. - int RequestSocket(const std::string& group_name, + int RequestSocket(const GroupId& group_id, const void* resolve_info, RequestPriority priority, const SocketTag& socket_tag, @@ -124,25 +124,25 @@ CompletionOnceCallback callback, const ProxyAuthCallback& proxy_auth_callback, const NetLogWithSource& net_log) override; - void RequestSockets(const std::string& group_name, + void RequestSockets(const GroupId& group_id, const void* params, int num_sockets, const NetLogWithSource& net_log) override; - void SetPriority(const std::string& group_name, + void SetPriority(const GroupId& group_id, ClientSocketHandle* handle, RequestPriority priority) override; - void CancelRequest(const std::string& group_name, + void CancelRequest(const GroupId& group_id, ClientSocketHandle* handle) override; - void ReleaseSocket(const std::string& group_name, + void ReleaseSocket(const GroupId& group_id, std::unique_ptr<StreamSocket> socket, int id) override; void FlushWithError(int error) override; void CloseIdleSockets() override; - void CloseIdleSocketsInGroup(const std::string& group_name) override; + void CloseIdleSocketsInGroup(const GroupId& group_id) override; int IdleSocketCount() const override; - size_t IdleSocketCountInGroup(const std::string& group_name) const override; - LoadState GetLoadState(const std::string& group_name, + size_t IdleSocketCountInGroup(const GroupId& group_id) const override; + LoadState GetLoadState(const GroupId& group_id, const ClientSocketHandle* handle) const override; std::unique_ptr<base::DictionaryValue> GetInfoAsValue( const std::string& name, @@ -163,7 +163,7 @@ protected: // Methods shared with WebSocketTransportClientSocketPool void NetLogTcpClientSocketPoolRequestedSocket(const NetLogWithSource& net_log, - const std::string& group_name); + const GroupId& group_id); private: typedef ClientSocketPoolBase<SocketParams> PoolBase;
diff --git a/net/socket/transport_client_socket_pool_unittest.cc b/net/socket/transport_client_socket_pool_unittest.cc index 40b854e..d06415e 100644 --- a/net/socket/transport_client_socket_pool_unittest.cc +++ b/net/socket/transport_client_socket_pool_unittest.cc
@@ -4,6 +4,8 @@ #include "net/socket/transport_client_socket_pool.h" +#include <utility> + #include "base/bind.h" #include "base/bind_helpers.h" #include "base/callback.h" @@ -102,6 +104,9 @@ : WithScopedTaskEnvironment(type, now_source), connect_backup_jobs_enabled_( ClientSocketPoolBaseHelper::set_connect_backup_jobs_enabled(true)), + group_id_(HostPortPair("www.google.com", 80), + ClientSocketPool::SocketType::kHttp, + false /* privacy_mode */), params_(TransportClientSocketPool::SocketParams:: CreateFromTransportSocketParams( base::MakeRefCounted<TransportSocketParams>( @@ -165,15 +170,18 @@ connect_backup_jobs_enabled_); } - int StartRequest(const std::string& group_name, RequestPriority priority) { + int StartRequest(const std::string& host_name, RequestPriority priority) { + ClientSocketPool::GroupId group_id(HostPortPair(host_name, 80), + ClientSocketPool::SocketType::kHttp, + false /* privacy_mode */); scoped_refptr<TransportClientSocketPool::SocketParams> params( TransportClientSocketPool::SocketParams:: CreateFromTransportSocketParams( base::MakeRefCounted<TransportSocketParams>( - HostPortPair("www.google.com", 80), false, + group_id.destination(), false, OnHostResolutionCallback()))); return test_base_.StartRequestUsingPool( - pool_.get(), group_name, priority, + pool_.get(), group_id, priority, ClientSocketPool::RespectLimits::ENABLED, params); } @@ -202,7 +210,11 @@ bool connect_backup_jobs_enabled_; TestNetLog net_log_; + + // |group_id_| and |params_| correspond to the same group. + const ClientSocketPool::GroupId group_id_; scoped_refptr<TransportClientSocketPool::SocketParams> params_; + MockTransportClientSocketFactory client_socket_factory_; MockTaggingClientSocketFactory tagging_client_socket_factory_; @@ -231,9 +243,9 @@ TestCompletionCallback callback; ClientSocketHandle handle; int rv = handle.Init( - "a", params_, LOW, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, - callback.callback(), ClientSocketPool::ProxyAuthCallback(), pool_.get(), - NetLogWithSource()); + group_id_, params_, LOW, SocketTag(), + ClientSocketPool::RespectLimits::ENABLED, callback.callback(), + ClientSocketPool::ProxyAuthCallback(), pool_.get(), NetLogWithSource()); EXPECT_THAT(rv, IsError(ERR_IO_PENDING)); EXPECT_FALSE(handle.is_initialized()); EXPECT_FALSE(handle.socket()); @@ -254,7 +266,7 @@ ClientSocketHandle handle; EXPECT_EQ( ERR_IO_PENDING, - handle.Init("a", params_, priority, SocketTag(), + handle.Init(group_id_, params_, priority, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, callback.callback(), ClientSocketPool::ProxyAuthCallback(), pool_.get(), NetLogWithSource())); @@ -268,15 +280,15 @@ TestCompletionCallback callback1; ClientSocketHandle handle1; int rv1 = handle1.Init( - "a", params_, LOW, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, - callback1.callback(), ClientSocketPool::ProxyAuthCallback(), pool_.get(), - NetLogWithSource()); + group_id_, params_, LOW, SocketTag(), + ClientSocketPool::RespectLimits::ENABLED, callback1.callback(), + ClientSocketPool::ProxyAuthCallback(), pool_.get(), NetLogWithSource()); EXPECT_THAT(rv1, IsError(ERR_IO_PENDING)); TestCompletionCallback callback2; ClientSocketHandle handle2; int rv2 = handle2.Init( - "a", params_, HIGHEST, SocketTag(), + group_id_, params_, HIGHEST, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, callback2.callback(), ClientSocketPool::ProxyAuthCallback(), pool_.get(), NetLogWithSource()); EXPECT_THAT(rv2, IsError(ERR_IO_PENDING)); @@ -284,7 +296,7 @@ TestCompletionCallback callback3; ClientSocketHandle handle3; int rv3 = handle3.Init( - "a", params_, LOWEST, SocketTag(), + group_id_, params_, LOWEST, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, callback3.callback(), ClientSocketPool::ProxyAuthCallback(), pool_.get(), NetLogWithSource()); EXPECT_THAT(rv3, IsError(ERR_IO_PENDING)); @@ -292,7 +304,7 @@ TestCompletionCallback callback4; ClientSocketHandle handle4; int rv4 = handle4.Init( - "a", params_, MEDIUM, SocketTag(), + group_id_, params_, MEDIUM, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, callback4.callback(), ClientSocketPool::ProxyAuthCallback(), pool_.get(), NetLogWithSource()); EXPECT_THAT(rv4, IsError(ERR_IO_PENDING)); @@ -300,7 +312,7 @@ TestCompletionCallback callback5; ClientSocketHandle handle5; int rv5 = handle5.Init( - "a", params_, HIGHEST, SocketTag(), + group_id_, params_, HIGHEST, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, callback5.callback(), ClientSocketPool::ProxyAuthCallback(), pool_.get(), NetLogWithSource()); EXPECT_THAT(rv5, IsError(ERR_IO_PENDING)); @@ -308,9 +320,9 @@ TestCompletionCallback callback6; ClientSocketHandle handle6; int rv6 = handle6.Init( - "a", params_, LOW, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, - callback6.callback(), ClientSocketPool::ProxyAuthCallback(), pool_.get(), - NetLogWithSource()); + group_id_, params_, LOW, SocketTag(), + ClientSocketPool::RespectLimits::ENABLED, callback6.callback(), + ClientSocketPool::ProxyAuthCallback(), pool_.get(), NetLogWithSource()); EXPECT_THAT(rv6, IsError(ERR_IO_PENDING)); // New jobs are created for each of the first 6 requests with the @@ -337,7 +349,7 @@ TestCompletionCallback callback7; ClientSocketHandle handle7; int rv7 = handle7.Init( - "a", params_, HIGHEST, SocketTag(), + group_id_, params_, HIGHEST, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, callback7.callback(), ClientSocketPool::ProxyAuthCallback(), pool_.get(), NetLogWithSource()); EXPECT_THAT(rv7, IsError(ERR_IO_PENDING)); @@ -361,7 +373,7 @@ TestCompletionCallback callback8; ClientSocketHandle handle8; int rv8 = handle8.Init( - "a", params_, HIGHEST, SocketTag(), + group_id_, params_, HIGHEST, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, callback8.callback(), ClientSocketPool::ProxyAuthCallback(), pool_.get(), NetLogWithSource()); EXPECT_THAT(rv8, IsError(ERR_IO_PENDING)); @@ -426,7 +438,7 @@ EXPECT_EQ(HIGHEST, session_deps_.host_resolver->request_priority(6)); // Reprioritizing a request changes its job's priority. - pool_->SetPriority("a", &handle4, LOWEST); + pool_->SetPriority(group_id_, &handle4, LOWEST); // Request Job Priority // ======= === ======== // 8 6 HIGHEST @@ -441,7 +453,7 @@ EXPECT_EQ(LOW, session_deps_.host_resolver->request_priority(5)); EXPECT_EQ(HIGHEST, session_deps_.host_resolver->request_priority(6)); - pool_->SetPriority("a", &handle3, MEDIUM); + pool_->SetPriority(group_id_, &handle3, MEDIUM); // Request Job Priority // ======= === ======== // 8 6 HIGHEST @@ -519,7 +531,7 @@ TestCompletionCallback callback1; ClientSocketHandle handle1; int rv1 = handle1.Init( - "a", params_, MAXIMUM_PRIORITY, SocketTag(), + group_id_, params_, MAXIMUM_PRIORITY, SocketTag(), ClientSocketPool::RespectLimits::DISABLED, callback1.callback(), ClientSocketPool::ProxyAuthCallback(), &pool, NetLogWithSource()); EXPECT_THAT(rv1, IsError(ERR_IO_PENDING)); @@ -529,9 +541,9 @@ TestCompletionCallback callback2; ClientSocketHandle handle2; int rv2 = handle2.Init( - "a", params_, LOW, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, - callback2.callback(), ClientSocketPool::ProxyAuthCallback(), &pool, - NetLogWithSource()); + group_id_, params_, LOW, SocketTag(), + ClientSocketPool::RespectLimits::ENABLED, callback2.callback(), + ClientSocketPool::ProxyAuthCallback(), &pool, NetLogWithSource()); EXPECT_THAT(rv2, IsError(ERR_IO_PENDING)); // |handle2| gets assigned the job, which is reprioritized. @@ -541,17 +553,12 @@ TEST_F(TransportClientSocketPoolTest, InitHostResolutionFailure) { session_deps_.host_resolver->rules()->AddSimulatedFailure( - "unresolvable.host.name"); + group_id_.destination().host()); TestCompletionCallback callback; ClientSocketHandle handle; - HostPortPair host_port_pair("unresolvable.host.name", 80); - scoped_refptr<TransportClientSocketPool::SocketParams> dest( - TransportClientSocketPool::SocketParams::CreateFromTransportSocketParams( - base::MakeRefCounted<TransportSocketParams>( - host_port_pair, false, OnHostResolutionCallback()))); EXPECT_EQ( ERR_IO_PENDING, - handle.Init("a", dest, kDefaultPriority, SocketTag(), + handle.Init(group_id_, params_, kDefaultPriority, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, callback.callback(), ClientSocketPool::ProxyAuthCallback(), pool_.get(), NetLogWithSource())); @@ -569,7 +576,7 @@ ClientSocketHandle handle; EXPECT_EQ( ERR_IO_PENDING, - handle.Init("a", params_, kDefaultPriority, SocketTag(), + handle.Init(group_id_, params_, kDefaultPriority, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, callback.callback(), ClientSocketPool::ProxyAuthCallback(), pool_.get(), NetLogWithSource())); @@ -584,7 +591,7 @@ session_deps_.host_resolver->set_synchronous_mode(true); EXPECT_EQ( ERR_CONNECTION_FAILED, - handle.Init("a", params_, kDefaultPriority, SocketTag(), + handle.Init(group_id_, params_, kDefaultPriority, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, callback.callback(), ClientSocketPool::ProxyAuthCallback(), pool_.get(), NetLogWithSource())); @@ -699,7 +706,7 @@ ClientSocketHandle handle; EXPECT_EQ( ERR_IO_PENDING, - handle.Init("a", params_, kDefaultPriority, SocketTag(), + handle.Init(group_id_, params_, kDefaultPriority, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, callback.callback(), ClientSocketPool::ProxyAuthCallback(), pool_.get(), NetLogWithSource())); @@ -714,13 +721,13 @@ EXPECT_EQ( ERR_IO_PENDING, - handle.Init("a", params_, kDefaultPriority, SocketTag(), + handle.Init(group_id_, params_, kDefaultPriority, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, callback.callback(), ClientSocketPool::ProxyAuthCallback(), pool_.get(), NetLogWithSource())); EXPECT_EQ( ERR_IO_PENDING, - handle2.Init("a", params_, kDefaultPriority, SocketTag(), + handle2.Init(group_id_, params_, kDefaultPriority, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, callback2.callback(), ClientSocketPool::ProxyAuthCallback(), pool_.get(), NetLogWithSource())); @@ -738,7 +745,7 @@ TestCompletionCallback callback; EXPECT_EQ( ERR_IO_PENDING, - handle.Init("a", params_, kDefaultPriority, SocketTag(), + handle.Init(group_id_, params_, kDefaultPriority, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, callback.callback(), ClientSocketPool::ProxyAuthCallback(), pool_.get(), NetLogWithSource())); @@ -748,7 +755,7 @@ TestCompletionCallback callback2; EXPECT_EQ( ERR_IO_PENDING, - handle.Init("a", params_, kDefaultPriority, SocketTag(), + handle.Init(group_id_, params_, kDefaultPriority, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, callback2.callback(), ClientSocketPool::ProxyAuthCallback(), pool_.get(), NetLogWithSource())); @@ -830,9 +837,16 @@ class RequestSocketCallback : public TestCompletionCallbackBase { public: - RequestSocketCallback(ClientSocketHandle* handle, - TransportClientSocketPool* pool) - : handle_(handle), pool_(pool), within_callback_(false) {} + RequestSocketCallback( + const ClientSocketPool::GroupId& group_id, + scoped_refptr<TransportClientSocketPool::SocketParams> socket_params, + ClientSocketHandle* handle, + TransportClientSocketPool* pool) + : group_id_(group_id), + socket_params_(socket_params), + handle_(handle), + pool_(pool), + within_callback_(false) {} ~RequestSocketCallback() override = default; @@ -853,13 +867,7 @@ handle_->Reset(); base::RunLoop(base::RunLoop::Type::kNestableTasksAllowed).RunUntilIdle(); within_callback_ = true; - scoped_refptr<TransportClientSocketPool::SocketParams> dest( - TransportClientSocketPool::SocketParams:: - CreateFromTransportSocketParams( - base::MakeRefCounted<TransportSocketParams>( - HostPortPair("www.google.com", 80), false, - OnHostResolutionCallback()))); - int rv = handle_->Init("a", dest, LOWEST, SocketTag(), + int rv = handle_->Init(group_id_, socket_params_, LOWEST, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, callback(), ClientSocketPool::ProxyAuthCallback(), pool_, NetLogWithSource()); @@ -867,6 +875,8 @@ } } + const ClientSocketPool::GroupId group_id_; + scoped_refptr<TransportClientSocketPool::SocketParams> socket_params_; ClientSocketHandle* const handle_; TransportClientSocketPool* const pool_; bool within_callback_; @@ -876,16 +886,16 @@ TEST_F(TransportClientSocketPoolTest, RequestTwice) { ClientSocketHandle handle; - RequestSocketCallback callback(&handle, pool_.get()); + RequestSocketCallback callback(group_id_, params_, &handle, pool_.get()); scoped_refptr<TransportClientSocketPool::SocketParams> dest( TransportClientSocketPool::SocketParams::CreateFromTransportSocketParams( base::MakeRefCounted<TransportSocketParams>( HostPortPair("www.google.com", 80), false, OnHostResolutionCallback()))); int rv = handle.Init( - "a", dest, LOWEST, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, - callback.callback(), ClientSocketPool::ProxyAuthCallback(), pool_.get(), - NetLogWithSource()); + group_id_, params_, LOWEST, SocketTag(), + ClientSocketPool::RespectLimits::ENABLED, callback.callback(), + ClientSocketPool::ProxyAuthCallback(), pool_.get(), NetLogWithSource()); ASSERT_THAT(rv, IsError(ERR_IO_PENDING)); // The callback is going to request "www.google.com". We want it to complete @@ -949,9 +959,9 @@ TestCompletionCallback callback; ClientSocketHandle handle; int rv = handle.Init( - "a", params_, LOW, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, - callback.callback(), ClientSocketPool::ProxyAuthCallback(), pool_.get(), - NetLogWithSource()); + group_id_, params_, LOW, SocketTag(), + ClientSocketPool::RespectLimits::ENABLED, callback.callback(), + ClientSocketPool::ProxyAuthCallback(), pool_.get(), NetLogWithSource()); EXPECT_THAT(rv, IsError(ERR_IO_PENDING)); EXPECT_FALSE(handle.is_initialized()); EXPECT_FALSE(handle.socket()); @@ -968,7 +978,7 @@ // Now we should have 1 idle socket. EXPECT_EQ(1, pool_->IdleSocketCount()); - rv = handle.Init("a", params_, LOW, SocketTag(), + rv = handle.Init(group_id_, params_, LOW, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, callback.callback(), ClientSocketPool::ProxyAuthCallback(), pool_.get(), NetLogWithSource()); @@ -981,9 +991,9 @@ TestCompletionCallback callback; ClientSocketHandle handle; int rv = handle.Init( - "a", params_, LOW, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, - callback.callback(), ClientSocketPool::ProxyAuthCallback(), pool_.get(), - NetLogWithSource()); + group_id_, params_, LOW, SocketTag(), + ClientSocketPool::RespectLimits::ENABLED, callback.callback(), + ClientSocketPool::ProxyAuthCallback(), pool_.get(), NetLogWithSource()); EXPECT_THAT(rv, IsError(ERR_IO_PENDING)); EXPECT_FALSE(handle.is_initialized()); EXPECT_FALSE(handle.socket()); @@ -1026,7 +1036,9 @@ ClientSocketHandle handle; TestCompletionCallback callback; int rv = handle.Init( - "group_name", + ClientSocketPool::GroupId(kHostPortPair, + ClientSocketPool::SocketType::kSsl, + false /* privacy_mode */), TransportClientSocketPool::SocketParams::CreateFromSSLSocketParams( params), MEDIUM, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, @@ -1045,9 +1057,9 @@ TestCompletionCallback callback; ClientSocketHandle handle; int rv = handle.Init( - "a", params_, LOW, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, - callback.callback(), ClientSocketPool::ProxyAuthCallback(), pool_.get(), - NetLogWithSource()); + group_id_, params_, LOW, SocketTag(), + ClientSocketPool::RespectLimits::ENABLED, callback.callback(), + ClientSocketPool::ProxyAuthCallback(), pool_.get(), NetLogWithSource()); EXPECT_THAT(rv, IsError(ERR_IO_PENDING)); EXPECT_FALSE(handle.is_initialized()); EXPECT_FALSE(handle.socket()); @@ -1103,7 +1115,7 @@ TestCompletionCallback callback; ClientSocketHandle handle; int rv = handle.Init( - "b", params_, LOW, SocketTag(), + group_id_, params_, LOW, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, callback.callback(), ClientSocketPool::ProxyAuthCallback(), pool_.get(), NetLogWithSource()); EXPECT_THAT(rv, IsError(ERR_IO_PENDING)); @@ -1147,7 +1159,7 @@ TestCompletionCallback callback; ClientSocketHandle handle; int rv = handle.Init( - "c", params_, LOW, SocketTag(), + group_id_, params_, LOW, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, callback.callback(), ClientSocketPool::ProxyAuthCallback(), pool_.get(), NetLogWithSource()); EXPECT_THAT(rv, IsError(ERR_IO_PENDING)); @@ -1195,9 +1207,9 @@ TestCompletionCallback callback; ClientSocketHandle handle; int rv = handle.Init( - "b", params_, LOW, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, - callback.callback(), ClientSocketPool::ProxyAuthCallback(), pool_.get(), - NetLogWithSource()); + group_id_, params_, LOW, SocketTag(), + ClientSocketPool::RespectLimits::ENABLED, callback.callback(), + ClientSocketPool::ProxyAuthCallback(), pool_.get(), NetLogWithSource()); EXPECT_THAT(rv, IsError(ERR_IO_PENDING)); EXPECT_FALSE(handle.is_initialized()); EXPECT_FALSE(handle.socket()); @@ -1245,9 +1257,9 @@ TestCompletionCallback callback; ClientSocketHandle handle; int rv = handle.Init( - "b", params_, LOW, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, - callback.callback(), ClientSocketPool::ProxyAuthCallback(), pool_.get(), - NetLogWithSource()); + group_id_, params_, LOW, SocketTag(), + ClientSocketPool::RespectLimits::ENABLED, callback.callback(), + ClientSocketPool::ProxyAuthCallback(), pool_.get(), NetLogWithSource()); EXPECT_THAT(rv, IsError(ERR_IO_PENDING)); EXPECT_FALSE(handle.is_initialized()); EXPECT_FALSE(handle.socket()); @@ -1277,6 +1289,7 @@ // Test the case that SOCKSSocketParams are provided. TEST_F(TransportClientSocketPoolTest, SOCKS) { + const HostPortPair kDesination("host", 80); for (IoMode socket_io_mode : {SYNCHRONOUS, ASYNC}) { scoped_refptr<TransportSocketParams> tcp_params = base::MakeRefCounted<TransportSocketParams>( @@ -1284,7 +1297,7 @@ scoped_refptr<TransportClientSocketPool::SocketParams> socks_params( TransportClientSocketPool::SocketParams::CreateFromSOCKSSocketParams( base::MakeRefCounted<SOCKSSocketParams>( - tcp_params, true /* socks_v5 */, HostPortPair("host", 80), + tcp_params, true /* socks_v5 */, kDesination, TRAFFIC_ANNOTATION_FOR_TESTS))); SOCKS5MockData data(socket_io_mode); @@ -1293,7 +1306,10 @@ ClientSocketHandle handle; TestCompletionCallback callback; int rv = - handle.Init("a", socks_params, LOW, SocketTag(), + handle.Init(ClientSocketPool::GroupId( + kDesination, ClientSocketPool::SocketType::kSsl, + false /* privacy_mode */), + socks_params, LOW, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, callback.callback(), ClientSocketPool::ProxyAuthCallback(), tagging_pool_.get(), NetLogWithSource()); @@ -1390,11 +1406,14 @@ TransportClientSocketPool::SocketParams::CreateFromSSLSocketParams( endpoint_ssl_params); + ClientSocketPool::GroupId group_id( + kEndpoint, ClientSocketPool::SocketType::kSsl, false /* privacy_mode */); + // Start the first connection attempt. TestCompletionCallback callback1; ClientSocketHandle handle1; int rv1 = handle1.Init( - "a", pool_params, HIGHEST, SocketTag(), + group_id, pool_params, HIGHEST, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, callback1.callback(), ClientSocketPool::ProxyAuthCallback(), &pool, NetLogWithSource()); ASSERT_THAT(rv1, IsError(ERR_IO_PENDING)); @@ -1403,7 +1422,7 @@ TestCompletionCallback callback2; ClientSocketHandle handle2; int rv2 = handle2.Init( - "a", pool_params, LOWEST, SocketTag(), + group_id, pool_params, LOWEST, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, callback2.callback(), ClientSocketPool::ProxyAuthCallback(), &pool, NetLogWithSource()); ASSERT_THAT(rv2, IsError(ERR_IO_PENDING)); @@ -1519,11 +1538,14 @@ TransportClientSocketPool::SocketParams::CreateFromSSLSocketParams( endpoint_ssl_params); + ClientSocketPool::GroupId group_id( + kEndpoint, ClientSocketPool::SocketType::kSsl, false /* privacy_mode */); + // Start the first connection attempt. TestCompletionCallback callback1; ClientSocketHandle handle1; base::RunLoop run_loop; - int rv1 = handle1.Init("a", pool_params, HIGHEST, SocketTag(), + int rv1 = handle1.Init(group_id, pool_params, HIGHEST, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, callback1.callback(), base::BindLambdaForTesting( @@ -1539,7 +1561,7 @@ TestCompletionCallback callback2; ClientSocketHandle handle2; int rv2 = handle2.Init( - "a", pool_params, LOWEST, SocketTag(), + group_id, pool_params, LOWEST, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, callback2.callback(), ClientSocketPool::ProxyAuthCallback(), &pool, NetLogWithSource()); ASSERT_THAT(rv2, IsError(ERR_IO_PENDING)); @@ -1580,13 +1602,16 @@ // Test socket is tagged before connected. uint64_t old_traffic = GetTaggedBytes(tag_val1); + const ClientSocketPool::GroupId kGroupId(test_server.host_port_pair(), + ClientSocketPool::SocketType::kSsl, + false /* privacy_mode */); scoped_refptr<TransportClientSocketPool::SocketParams> params = TransportClientSocketPool::SocketParams::CreateFromTransportSocketParams( base::MakeRefCounted<TransportSocketParams>( test_server.host_port_pair(), false, OnHostResolutionCallback())); TestCompletionCallback callback; int rv = handle.Init( - "a", params, LOW, tag1, ClientSocketPool::RespectLimits::ENABLED, + kGroupId, params, LOW, tag1, ClientSocketPool::RespectLimits::ENABLED, callback.callback(), ClientSocketPool::ProxyAuthCallback(), pool_for_real_sockets_.get(), NetLogWithSource()); EXPECT_THAT(callback.GetResult(rv), IsOk()); @@ -1598,7 +1623,7 @@ StreamSocket* socket = handle.socket(); handle.Reset(); old_traffic = GetTaggedBytes(tag_val2); - rv = handle.Init("a", params, LOW, tag2, + rv = handle.Init(kGroupId, params, LOW, tag2, ClientSocketPool::RespectLimits::ENABLED, callback.callback(), ClientSocketPool::ProxyAuthCallback(), pool_for_real_sockets_.get(), NetLogWithSource()); @@ -1621,14 +1646,14 @@ // Test connect jobs that are orphaned and then adopted, appropriately apply // new tag. Request socket with |tag1|. TestCompletionCallback callback2; - rv = handle.Init("a", params, LOW, tag1, + rv = handle.Init(kGroupId, params, LOW, tag1, ClientSocketPool::RespectLimits::ENABLED, callback2.callback(), ClientSocketPool::ProxyAuthCallback(), pool_for_real_sockets_.get(), NetLogWithSource()); EXPECT_TRUE(rv == OK || rv == ERR_IO_PENDING) << "Result: " << rv; // Abort and request socket with |tag2|. handle.Reset(); - rv = handle.Init("a", params, LOW, tag2, + rv = handle.Init(kGroupId, params, LOW, tag2, ClientSocketPool::RespectLimits::ENABLED, callback.callback(), ClientSocketPool::ProxyAuthCallback(), pool_for_real_sockets_.get(), NetLogWithSource()); @@ -1647,7 +1672,7 @@ handle.Reset(); // Eat the left over connect job from the second request. // TODO(pauljensen): remove when crbug.com/800731 fixed. - rv = handle.Init("a", params, LOW, tag1, + rv = handle.Init(kGroupId, params, LOW, tag1, ClientSocketPool::RespectLimits::ENABLED, callback.callback(), ClientSocketPool::ProxyAuthCallback(), pool_for_real_sockets_.get(), NetLogWithSource()); @@ -1660,13 +1685,13 @@ // first but expect its socket to get vended to the higher priority request. ClientSocketHandle handle_high_pri; TestCompletionCallback callback_high_pri; - rv = handle.Init("a", params, LOW, tag1, + rv = handle.Init(kGroupId, params, LOW, tag1, ClientSocketPool::RespectLimits::ENABLED, callback.callback(), ClientSocketPool::ProxyAuthCallback(), pool_for_real_sockets_.get(), NetLogWithSource()); EXPECT_TRUE(rv == OK || rv == ERR_IO_PENDING) << "Result: " << rv; int rv_high_pri = handle_high_pri.Init( - "a", params, HIGHEST, tag2, ClientSocketPool::RespectLimits::ENABLED, + kGroupId, params, HIGHEST, tag2, ClientSocketPool::RespectLimits::ENABLED, callback_high_pri.callback(), ClientSocketPool::ProxyAuthCallback(), pool_for_real_sockets_.get(), NetLogWithSource()); EXPECT_THAT(callback_high_pri.GetResult(rv_high_pri), IsOk()); @@ -1696,13 +1721,17 @@ SocketTag tag1(SocketTag::UNSET_UID, 0x12345678); SocketTag tag2(getuid(), 0x87654321); + const HostPortPair kDestination("host", 80); + const ClientSocketPool::GroupId kGroupId(kDestination, + ClientSocketPool::SocketType::kHttp, + false /* privacy_mode */); scoped_refptr<TransportSocketParams> tcp_params = base::MakeRefCounted<TransportSocketParams>( HostPortPair("proxy", 80), false, OnHostResolutionCallback()); scoped_refptr<TransportClientSocketPool::SocketParams> socks_params( TransportClientSocketPool::SocketParams::CreateFromSOCKSSocketParams( base::MakeRefCounted<SOCKSSocketParams>( - tcp_params, true /* socks_v5 */, HostPortPair("host", 80), + tcp_params, true /* socks_v5 */, kDestination, TRAFFIC_ANNOTATION_FOR_TESTS))); // Test socket is tagged when created synchronously. @@ -1711,10 +1740,11 @@ tagging_client_socket_factory_.AddSocketDataProvider( data_sync.data_provider()); ClientSocketHandle handle; - int rv = handle.Init( - "a", socks_params, LOW, tag1, ClientSocketPool::RespectLimits::ENABLED, - CompletionOnceCallback(), ClientSocketPool::ProxyAuthCallback(), - tagging_pool_.get(), NetLogWithSource()); + int rv = handle.Init(kGroupId, socks_params, LOW, tag1, + ClientSocketPool::RespectLimits::ENABLED, + CompletionOnceCallback(), + ClientSocketPool::ProxyAuthCallback(), + tagging_pool_.get(), NetLogWithSource()); EXPECT_THAT(rv, IsOk()); EXPECT_TRUE(handle.is_initialized()); EXPECT_TRUE(handle.socket()); @@ -1726,10 +1756,11 @@ // Test socket is tagged when reused synchronously. StreamSocket* socket = handle.socket(); handle.Reset(); - rv = handle.Init( - "a", socks_params, LOW, tag2, ClientSocketPool::RespectLimits::ENABLED, - CompletionOnceCallback(), ClientSocketPool::ProxyAuthCallback(), - tagging_pool_.get(), NetLogWithSource()); + rv = handle.Init(kGroupId, socks_params, LOW, tag2, + ClientSocketPool::RespectLimits::ENABLED, + CompletionOnceCallback(), + ClientSocketPool::ProxyAuthCallback(), tagging_pool_.get(), + NetLogWithSource()); EXPECT_THAT(rv, IsOk()); EXPECT_TRUE(handle.socket()); EXPECT_TRUE(handle.socket()->IsConnected()); @@ -1744,7 +1775,7 @@ tagging_client_socket_factory_.AddSocketDataProvider( data_async.data_provider()); TestCompletionCallback callback; - rv = handle.Init("a", socks_params, LOW, tag1, + rv = handle.Init(kGroupId, socks_params, LOW, tag1, ClientSocketPool::RespectLimits::ENABLED, callback.callback(), ClientSocketPool::ProxyAuthCallback(), tagging_pool_.get(), NetLogWithSource()); @@ -1760,10 +1791,11 @@ // Test socket is tagged when reused after being created asynchronously. socket = handle.socket(); handle.Reset(); - rv = handle.Init( - "a", socks_params, LOW, tag2, ClientSocketPool::RespectLimits::ENABLED, - CompletionOnceCallback(), ClientSocketPool::ProxyAuthCallback(), - tagging_pool_.get(), NetLogWithSource()); + rv = handle.Init(kGroupId, socks_params, LOW, tag2, + ClientSocketPool::RespectLimits::ENABLED, + CompletionOnceCallback(), + ClientSocketPool::ProxyAuthCallback(), tagging_pool_.get(), + NetLogWithSource()); EXPECT_THAT(rv, IsOk()); EXPECT_TRUE(handle.socket()); EXPECT_TRUE(handle.socket()->IsConnected()); @@ -1778,8 +1810,6 @@ return; } - const char kGroupName[] = "group_name"; - // Start test server. EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS); test_server.SetSSLConfig(net::EmbeddedTestServer::CERT_OK, SSLServerConfig()); @@ -1798,6 +1828,9 @@ SocketTag tag1(SocketTag::UNSET_UID, tag_val1); int32_t tag_val2 = 0x87654321; SocketTag tag2(getuid(), tag_val2); + const ClientSocketPool::GroupId kGroupId(test_server.host_port_pair(), + ClientSocketPool::SocketType::kSsl, + false /* privacy_mode */); scoped_refptr<TransportSocketParams> tcp_params = base::MakeRefCounted<TransportSocketParams>( test_server.host_port_pair(), false, OnHostResolutionCallback()); @@ -1808,7 +1841,7 @@ // Test socket is tagged before connected. uint64_t old_traffic = GetTaggedBytes(tag_val1); int rv = handle.Init( - kGroupName, + kGroupId, TransportClientSocketPool::SocketParams::CreateFromSSLSocketParams( params), LOW, tag1, ClientSocketPool::RespectLimits::ENABLED, callback.callback(), @@ -1825,7 +1858,7 @@ old_traffic = GetTaggedBytes(tag_val2); TestCompletionCallback callback2; rv = handle.Init( - kGroupName, + kGroupId, TransportClientSocketPool::SocketParams::CreateFromSSLSocketParams( params), LOW, tag2, ClientSocketPool::RespectLimits::ENABLED, callback2.callback(), @@ -1859,8 +1892,6 @@ return; } - const char kGroupName[] = "group_name"; - // Start test server. EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS); test_server.SetSSLConfig(net::EmbeddedTestServer::CERT_OK, SSLServerConfig()); @@ -1872,6 +1903,9 @@ SocketTag tag1(SocketTag::UNSET_UID, tag_val1); int32_t tag_val2 = 0x87654321; SocketTag tag2(getuid(), tag_val2); + const ClientSocketPool::GroupId kGroupId(test_server.host_port_pair(), + ClientSocketPool::SocketType::kSsl, + false /* privacy_mode */); scoped_refptr<TransportSocketParams> tcp_params = base::MakeRefCounted<TransportSocketParams>( test_server.host_port_pair(), false, OnHostResolutionCallback()); @@ -1883,7 +1917,7 @@ // new tag. Request socket with |tag1|. TestCompletionCallback callback; int rv = handle.Init( - kGroupName, + kGroupId, TransportClientSocketPool::SocketParams::CreateFromSSLSocketParams( params), LOW, tag1, ClientSocketPool::RespectLimits::ENABLED, callback.callback(), @@ -1894,7 +1928,7 @@ handle.Reset(); TestCompletionCallback callback2; rv = handle.Init( - kGroupName, + kGroupId, TransportClientSocketPool::SocketParams::CreateFromSSLSocketParams( params), LOW, tag2, ClientSocketPool::RespectLimits::ENABLED, callback2.callback(), @@ -1926,8 +1960,6 @@ return; } - const char kGroupName[] = "group_name"; - // Start test server. EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS); test_server.SetSSLConfig(net::EmbeddedTestServer::CERT_OK, SSLServerConfig()); @@ -1940,6 +1972,9 @@ SocketTag tag1(SocketTag::UNSET_UID, tag_val1); int32_t tag_val2 = 0x87654321; SocketTag tag2(getuid(), tag_val2); + const ClientSocketPool::GroupId kGroupId(test_server.host_port_pair(), + ClientSocketPool::SocketType::kSsl, + false /* privacy_mode */); scoped_refptr<TransportSocketParams> tcp_params = base::MakeRefCounted<TransportSocketParams>( test_server.host_port_pair(), false, OnHostResolutionCallback()); @@ -1953,7 +1988,7 @@ ClientSocketHandle tcp_handles[kMaxSocketsPerGroup]; int rv; for (auto& tcp_handle : tcp_handles) { - rv = tcp_handle.Init(kGroupName, + rv = tcp_handle.Init(kGroupId, TransportClientSocketPool::SocketParams:: CreateFromTransportSocketParams(tcp_params), LOW, tag1, ClientSocketPool::RespectLimits::ENABLED, @@ -1967,7 +2002,7 @@ // Request two SSL sockets. ClientSocketHandle handle_to_be_canceled; rv = handle_to_be_canceled.Init( - kGroupName, + kGroupId, TransportClientSocketPool::SocketParams::CreateFromSSLSocketParams( params), LOW, tag1, ClientSocketPool::RespectLimits::ENABLED, callback.callback(), @@ -1975,7 +2010,7 @@ NetLogWithSource()); EXPECT_THAT(rv, IsError(ERR_IO_PENDING)); rv = handle.Init( - kGroupName, + kGroupId, TransportClientSocketPool::SocketParams::CreateFromSSLSocketParams( params), LOW, tag2, ClientSocketPool::RespectLimits::ENABLED, callback.callback(), @@ -2017,6 +2052,10 @@ socket_data.set_connect_data(MockConnect(SYNCHRONOUS, OK)); tagging_client_socket_factory_.AddSocketDataProvider(&socket_data); + const HostPortPair kDestination("www.google.com", 80); + const ClientSocketPool::GroupId kGroupId(kDestination, + ClientSocketPool::SocketType::kSsl, + false /* privacy_mode */); scoped_refptr<TransportClientSocketPool::SocketParams> params = TransportClientSocketPool::SocketParams::CreateFromHttpProxySocketParams( base::MakeRefCounted<HttpProxySocketParams>( @@ -2024,8 +2063,7 @@ HostPortPair("http.proxy.host", 80), false, OnHostResolutionCallback()), nullptr /* ssl_params */, quic::QUIC_VERSION_UNSUPPORTED, - HostPortPair("www.google.com", 80), - http_network_session_->http_auth_cache(), + kDestination, http_network_session_->http_auth_cache(), http_network_session_->http_auth_handler_factory(), http_network_session_->spdy_session_pool(), nullptr /* quic_stream_factory */, false /* is_trusted_proxy */, @@ -2034,7 +2072,7 @@ // Verify requested socket is tagged properly. ClientSocketHandle handle; int rv = handle.Init( - "a", params, LOW, tag1, ClientSocketPool::RespectLimits::ENABLED, + kGroupId, params, LOW, tag1, ClientSocketPool::RespectLimits::ENABLED, CompletionOnceCallback(), ClientSocketPool::ProxyAuthCallback(), tagging_pool_.get(), NetLogWithSource()); EXPECT_THAT(rv, IsOk()); @@ -2050,7 +2088,7 @@ StreamSocket* socket = handle.socket(); handle.Reset(); rv = handle.Init( - "a", params, LOW, tag2, ClientSocketPool::RespectLimits::ENABLED, + kGroupId, params, LOW, tag2, ClientSocketPool::RespectLimits::ENABLED, CompletionOnceCallback(), ClientSocketPool::ProxyAuthCallback(), tagging_pool_.get(), NetLogWithSource()); EXPECT_THAT(rv, IsOk()); @@ -2086,6 +2124,10 @@ SequencedSocketData socket_data(MockConnect(SYNCHRONOUS, OK), reads, writes); tagging_client_socket_factory_.AddSocketDataProvider(&socket_data); + const HostPortPair kDestination("www.google.com", 443); + const ClientSocketPool::GroupId kGroupId(kDestination, + ClientSocketPool::SocketType::kSsl, + false /* privacy_mode */); scoped_refptr<TransportClientSocketPool::SocketParams> params = TransportClientSocketPool::SocketParams::CreateFromHttpProxySocketParams( base::MakeRefCounted<HttpProxySocketParams>( @@ -2093,8 +2135,7 @@ HostPortPair("http.proxy.host", 80), false, OnHostResolutionCallback()), nullptr /* ssl_params */, quic::QUIC_VERSION_UNSUPPORTED, - HostPortPair("www.google.com", 443), - http_network_session_->http_auth_cache(), + kDestination, http_network_session_->http_auth_cache(), http_network_session_->http_auth_handler_factory(), http_network_session_->spdy_session_pool(), nullptr /* quic_stream_factory */, false /* is_trusted_proxy */, @@ -2103,7 +2144,7 @@ // Verify requested socket is tagged properly. ClientSocketHandle handle; int rv = handle.Init( - "a", params, LOW, tag1, ClientSocketPool::RespectLimits::ENABLED, + kGroupId, params, LOW, tag1, ClientSocketPool::RespectLimits::ENABLED, CompletionOnceCallback(), ClientSocketPool::ProxyAuthCallback(), tagging_pool_.get(), NetLogWithSource()); EXPECT_THAT(rv, IsOk()); @@ -2119,7 +2160,7 @@ StreamSocket* socket = handle.socket(); handle.Reset(); rv = handle.Init( - "a", params, LOW, tag2, ClientSocketPool::RespectLimits::ENABLED, + kGroupId, params, LOW, tag2, ClientSocketPool::RespectLimits::ENABLED, CompletionOnceCallback(), ClientSocketPool::ProxyAuthCallback(), tagging_pool_.get(), NetLogWithSource()); EXPECT_THAT(rv, IsOk()); @@ -2215,7 +2256,9 @@ ClientSocketHandle connection; TestCompletionCallback callback; int rv = connection.Init( - kHostPortPair1.ToString(), + ClientSocketPool::GroupId(kHostPortPair1, + ClientSocketPool::SocketType::kHttp, + false /* privacy_mode */), TransportClientSocketPool::SocketParams:: CreateFromTransportSocketParams(transport_params), MEDIUM, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, @@ -2260,7 +2303,9 @@ ClientSocketHandle connection; TestCompletionCallback callback; int rv = connection.Init( - kHostPortPair2.ToString(), + ClientSocketPool::GroupId(kHostPortPair2, + ClientSocketPool::SocketType::kHttp, + false /* privacy_mode */), TransportClientSocketPool::SocketParams:: CreateFromTransportSocketParams(transport_params), MEDIUM, SocketTag(), ClientSocketPool::RespectLimits::ENABLED,
diff --git a/net/socket/websocket_transport_client_socket_pool.cc b/net/socket/websocket_transport_client_socket_pool.cc index 87914b78..288c696 100644 --- a/net/socket/websocket_transport_client_socket_pool.cc +++ b/net/socket/websocket_transport_client_socket_pool.cc
@@ -111,7 +111,7 @@ } int WebSocketTransportClientSocketPool::RequestSocket( - const std::string& group_name, + const GroupId& group_id, const void* params, RequestPriority priority, const SocketTag& socket_tag, @@ -125,7 +125,7 @@ CHECK(handle); DCHECK(socket_tag == SocketTag()); - NetLogTcpClientSocketPoolRequestedSocket(request_net_log, group_name); + NetLogTcpClientSocketPoolRequestedSocket(request_net_log, group_id); request_net_log.BeginEvent(NetLogEventType::SOCKET_POOL); const scoped_refptr<SocketParams>& casted_params = @@ -134,8 +134,8 @@ if (ReachedMaxSocketsLimit() && respect_limits == ClientSocketPool::RespectLimits::ENABLED) { request_net_log.AddEvent(NetLogEventType::SOCKET_POOL_STALLED_MAX_SOCKETS); - stalled_request_queue_.emplace_back(casted_params, priority, handle, - std::move(callback), + stalled_request_queue_.emplace_back(group_id, casted_params, priority, + handle, std::move(callback), proxy_auth_callback, request_net_log); auto iterator = stalled_request_queue_.end(); --iterator; @@ -184,17 +184,16 @@ } void WebSocketTransportClientSocketPool::RequestSockets( - const std::string& group_name, + const GroupId& group_id, const void* params, int num_sockets, const NetLogWithSource& net_log) { NOTIMPLEMENTED(); } -void WebSocketTransportClientSocketPool::SetPriority( - const std::string& group_name, - ClientSocketHandle* handle, - RequestPriority priority) { +void WebSocketTransportClientSocketPool::SetPriority(const GroupId& group_id, + ClientSocketHandle* handle, + RequestPriority priority) { // Since sockets requested by RequestSocket are bound early and // stalled_request_{queue,map} don't take priorities into account, there's // nothing to do within the pool to change priority of the request. @@ -205,14 +204,14 @@ } void WebSocketTransportClientSocketPool::CancelRequest( - const std::string& group_name, + const GroupId& group_id, ClientSocketHandle* handle) { DCHECK(!handle->is_initialized()); if (DeleteStalledRequest(handle)) return; std::unique_ptr<StreamSocket> socket = handle->PassSocket(); if (socket) - ReleaseSocket(handle->group_name(), std::move(socket), handle->id()); + ReleaseSocket(handle->group_id(), std::move(socket), handle->id()); if (!DeleteJob(handle)) pending_callbacks_.erase(handle); @@ -220,7 +219,7 @@ } void WebSocketTransportClientSocketPool::ReleaseSocket( - const std::string& group_name, + const GroupId& group_id, std::unique_ptr<StreamSocket> socket, int id) { CHECK_GT(handed_out_socket_count_, 0); @@ -258,7 +257,7 @@ } void WebSocketTransportClientSocketPool::CloseIdleSocketsInGroup( - const std::string& group_name) { + const GroupId& group_id) { // We have no idle sockets. } @@ -267,12 +266,12 @@ } size_t WebSocketTransportClientSocketPool::IdleSocketCountInGroup( - const std::string& group_name) const { + const GroupId& group_id) const { return 0; } LoadState WebSocketTransportClientSocketPool::GetLoadState( - const std::string& group_name, + const GroupId& group_id, const ClientSocketHandle* handle) const { if (stalled_request_map_.find(handle) != stalled_request_map_.end()) return LOAD_STATE_WAITING_FOR_AVAILABLE_SOCKET; @@ -460,12 +459,12 @@ auto copyable_callback = base::AdaptCallbackForRepeating(std::move(request.callback)); - int rv = - RequestSocket("ignored", &request.params, request.priority, SocketTag(), - // Stalled requests can't have |respect_limits| - // DISABLED. - RespectLimits::ENABLED, request.handle, copyable_callback, - request.proxy_auth_callback, request.net_log); + int rv = RequestSocket( + request.group_id, &request.params, request.priority, SocketTag(), + // Stalled requests can't have |respect_limits| + // DISABLED. + RespectLimits::ENABLED, request.handle, copyable_callback, + request.proxy_auth_callback, request.net_log); // ActivateStalledRequest() never returns synchronously, so it is never // called re-entrantly. @@ -526,13 +525,15 @@ } WebSocketTransportClientSocketPool::StalledRequest::StalledRequest( + const GroupId& group_id, const scoped_refptr<SocketParams>& params, RequestPriority priority, ClientSocketHandle* handle, CompletionOnceCallback callback, const ProxyAuthCallback& proxy_auth_callback, const NetLogWithSource& net_log) - : params(params), + : group_id(group_id), + params(params), priority(priority), handle(handle), callback(std::move(callback)),
diff --git a/net/socket/websocket_transport_client_socket_pool.h b/net/socket/websocket_transport_client_socket_pool.h index 9a4b401..8e851dc0 100644 --- a/net/socket/websocket_transport_client_socket_pool.h +++ b/net/socket/websocket_transport_client_socket_pool.h
@@ -76,7 +76,7 @@ WebSocketEndpointLockManager* websocket_endpoint_lock_manager); // ClientSocketPool implementation. - int RequestSocket(const std::string& group_name, + int RequestSocket(const GroupId& group_id, const void* resolve_info, RequestPriority priority, const SocketTag& socket_tag, @@ -85,24 +85,24 @@ CompletionOnceCallback callback, const ProxyAuthCallback& proxy_auth_callback, const NetLogWithSource& net_log) override; - void RequestSockets(const std::string& group_name, + void RequestSockets(const GroupId& group_id, const void* params, int num_sockets, const NetLogWithSource& net_log) override; - void SetPriority(const std::string& group_name, + void SetPriority(const GroupId& group_id, ClientSocketHandle* handle, RequestPriority priority) override; - void CancelRequest(const std::string& group_name, + void CancelRequest(const GroupId& group_id, ClientSocketHandle* handle) override; - void ReleaseSocket(const std::string& group_name, + void ReleaseSocket(const GroupId& group_id, std::unique_ptr<StreamSocket> socket, int id) override; void FlushWithError(int error) override; void CloseIdleSockets() override; - void CloseIdleSocketsInGroup(const std::string& group_name) override; + void CloseIdleSocketsInGroup(const GroupId& group_id) override; int IdleSocketCount() const override; - size_t IdleSocketCountInGroup(const std::string& group_name) const override; - LoadState GetLoadState(const std::string& group_name, + size_t IdleSocketCountInGroup(const GroupId& group_id) const override; + LoadState GetLoadState(const GroupId& group_id, const ClientSocketHandle* handle) const override; std::unique_ptr<base::DictionaryValue> GetInfoAsValue( const std::string& name, @@ -152,7 +152,8 @@ // Store the arguments from a call to RequestSocket() that has stalled so we // can replay it when there are available socket slots. struct StalledRequest { - StalledRequest(const scoped_refptr<SocketParams>& params, + StalledRequest(const GroupId& group_id, + const scoped_refptr<SocketParams>& params, RequestPriority priority, ClientSocketHandle* handle, CompletionOnceCallback callback, @@ -161,6 +162,7 @@ StalledRequest(StalledRequest&& other); ~StalledRequest(); + const GroupId group_id; const scoped_refptr<SocketParams> params; const RequestPriority priority; ClientSocketHandle* const handle;
diff --git a/net/socket/websocket_transport_client_socket_pool_unittest.cc b/net/socket/websocket_transport_client_socket_pool_unittest.cc index bc01f68..cd71b2d 100644 --- a/net/socket/websocket_transport_client_socket_pool_unittest.cc +++ b/net/socket/websocket_transport_client_socket_pool_unittest.cc
@@ -61,7 +61,10 @@ : public TestWithScopedTaskEnvironment { protected: WebSocketTransportClientSocketPoolTest() - : params_(TransportClientSocketPool::SocketParams:: + : group_id_(HostPortPair("www.google.com", 80), + ClientSocketPool::SocketType::kHttp, + false /* privacy_mode */), + params_(TransportClientSocketPool::SocketParams:: CreateFromTransportSocketParams( base::MakeRefCounted<TransportSocketParams>( HostPortPair("www.google.com", 80), @@ -101,16 +104,10 @@ static void RunUntilIdle() { base::RunLoop().RunUntilIdle(); } - int StartRequest(const std::string& group_name, RequestPriority priority) { - scoped_refptr<TransportClientSocketPool::SocketParams> params( - TransportClientSocketPool::SocketParams:: - CreateFromTransportSocketParams( - base::MakeRefCounted<TransportSocketParams>( - HostPortPair("www.google.com", 80), false, - OnHostResolutionCallback()))); + int StartRequest(RequestPriority priority) { return test_base_.StartRequestUsingPool( - &pool_, group_name, priority, ClientSocketPool::RespectLimits::ENABLED, - params); + &pool_, group_id_, priority, ClientSocketPool::RespectLimits::ENABLED, + params_); } int GetOrderOfRequest(size_t index) { @@ -133,6 +130,8 @@ size_t completion_count() const { return test_base_.completion_count(); } TestNetLog net_log_; + // |group_id_| and |params_| correspond to the same socket parameters. + const ClientSocketPool::GroupId group_id_; scoped_refptr<TransportClientSocketPool::SocketParams> params_; std::unique_ptr<MockHostResolver> host_resolver_; MockTransportClientSocketFactory client_socket_factory_; @@ -148,9 +147,9 @@ TestCompletionCallback callback; ClientSocketHandle handle; int rv = handle.Init( - "a", params_, LOW, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, - callback.callback(), ClientSocketPool::ProxyAuthCallback(), &pool_, - NetLogWithSource()); + group_id_, params_, LOW, SocketTag(), + ClientSocketPool::RespectLimits::ENABLED, callback.callback(), + ClientSocketPool::ProxyAuthCallback(), &pool_, NetLogWithSource()); EXPECT_THAT(rv, IsError(ERR_IO_PENDING)); EXPECT_FALSE(handle.is_initialized()); EXPECT_FALSE(handle.socket()); @@ -170,7 +169,7 @@ ClientSocketHandle handle; EXPECT_EQ( ERR_IO_PENDING, - handle.Init("a", params_, priority, SocketTag(), + handle.Init(group_id_, params_, priority, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, callback.callback(), ClientSocketPool::ProxyAuthCallback(), &pool_, NetLogWithSource())); @@ -189,7 +188,7 @@ host_port_pair, false, OnHostResolutionCallback()))); EXPECT_EQ( ERR_IO_PENDING, - handle.Init("a", dest, kDefaultPriority, SocketTag(), + handle.Init(group_id_, dest, kDefaultPriority, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, callback.callback(), ClientSocketPool::ProxyAuthCallback(), &pool_, NetLogWithSource())); @@ -203,7 +202,7 @@ ClientSocketHandle handle; EXPECT_EQ( ERR_IO_PENDING, - handle.Init("a", params_, kDefaultPriority, SocketTag(), + handle.Init(group_id_, params_, kDefaultPriority, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, callback.callback(), ClientSocketPool::ProxyAuthCallback(), &pool_, NetLogWithSource())); @@ -213,7 +212,7 @@ host_resolver_->set_synchronous_mode(true); EXPECT_EQ( ERR_CONNECTION_FAILED, - handle.Init("a", params_, kDefaultPriority, SocketTag(), + handle.Init(group_id_, params_, kDefaultPriority, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, callback.callback(), ClientSocketPool::ProxyAuthCallback(), &pool_, NetLogWithSource())); @@ -221,18 +220,18 @@ TEST_F(WebSocketTransportClientSocketPoolTest, PendingRequestsFinishFifo) { // First request finishes asynchronously. - EXPECT_THAT(StartRequest("a", kDefaultPriority), IsError(ERR_IO_PENDING)); + EXPECT_THAT(StartRequest(kDefaultPriority), IsError(ERR_IO_PENDING)); EXPECT_THAT(request(0)->WaitForResult(), IsOk()); // Make all subsequent host resolutions complete synchronously. host_resolver_->set_synchronous_mode(true); // Rest of them wait for the first socket to be released. - EXPECT_THAT(StartRequest("a", kDefaultPriority), IsError(ERR_IO_PENDING)); - EXPECT_THAT(StartRequest("a", kDefaultPriority), IsError(ERR_IO_PENDING)); - EXPECT_THAT(StartRequest("a", kDefaultPriority), IsError(ERR_IO_PENDING)); - EXPECT_THAT(StartRequest("a", kDefaultPriority), IsError(ERR_IO_PENDING)); - EXPECT_THAT(StartRequest("a", kDefaultPriority), IsError(ERR_IO_PENDING)); + EXPECT_THAT(StartRequest(kDefaultPriority), IsError(ERR_IO_PENDING)); + EXPECT_THAT(StartRequest(kDefaultPriority), IsError(ERR_IO_PENDING)); + EXPECT_THAT(StartRequest(kDefaultPriority), IsError(ERR_IO_PENDING)); + EXPECT_THAT(StartRequest(kDefaultPriority), IsError(ERR_IO_PENDING)); + EXPECT_THAT(StartRequest(kDefaultPriority), IsError(ERR_IO_PENDING)); ReleaseAllConnections(ClientSocketPoolTest::KEEP_ALIVE); @@ -255,18 +254,18 @@ TEST_F(WebSocketTransportClientSocketPoolTest, PendingRequests_NoKeepAlive) { // First request finishes asynchronously. - EXPECT_THAT(StartRequest("a", kDefaultPriority), IsError(ERR_IO_PENDING)); + EXPECT_THAT(StartRequest(kDefaultPriority), IsError(ERR_IO_PENDING)); EXPECT_THAT(request(0)->WaitForResult(), IsOk()); // Make all subsequent host resolutions complete synchronously. host_resolver_->set_synchronous_mode(true); // Rest of them wait for the first socket to be released. - EXPECT_THAT(StartRequest("a", kDefaultPriority), IsError(ERR_IO_PENDING)); - EXPECT_THAT(StartRequest("a", kDefaultPriority), IsError(ERR_IO_PENDING)); - EXPECT_THAT(StartRequest("a", kDefaultPriority), IsError(ERR_IO_PENDING)); - EXPECT_THAT(StartRequest("a", kDefaultPriority), IsError(ERR_IO_PENDING)); - EXPECT_THAT(StartRequest("a", kDefaultPriority), IsError(ERR_IO_PENDING)); + EXPECT_THAT(StartRequest(kDefaultPriority), IsError(ERR_IO_PENDING)); + EXPECT_THAT(StartRequest(kDefaultPriority), IsError(ERR_IO_PENDING)); + EXPECT_THAT(StartRequest(kDefaultPriority), IsError(ERR_IO_PENDING)); + EXPECT_THAT(StartRequest(kDefaultPriority), IsError(ERR_IO_PENDING)); + EXPECT_THAT(StartRequest(kDefaultPriority), IsError(ERR_IO_PENDING)); ReleaseAllConnections(ClientSocketPoolTest::NO_KEEP_ALIVE); @@ -292,7 +291,7 @@ ClientSocketHandle handle; EXPECT_EQ( ERR_IO_PENDING, - handle.Init("a", params_, kDefaultPriority, SocketTag(), + handle.Init(group_id_, params_, kDefaultPriority, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, callback.callback(), ClientSocketPool::ProxyAuthCallback(), &pool_, NetLogWithSource())); @@ -307,13 +306,13 @@ EXPECT_EQ( ERR_IO_PENDING, - handle.Init("a", params_, kDefaultPriority, SocketTag(), + handle.Init(group_id_, params_, kDefaultPriority, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, callback.callback(), ClientSocketPool::ProxyAuthCallback(), &pool_, NetLogWithSource())); EXPECT_EQ( ERR_IO_PENDING, - handle2.Init("a", params_, kDefaultPriority, SocketTag(), + handle2.Init(group_id_, params_, kDefaultPriority, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, callback2.callback(), ClientSocketPool::ProxyAuthCallback(), &pool_, NetLogWithSource())); @@ -331,7 +330,7 @@ TestCompletionCallback callback; EXPECT_EQ( ERR_IO_PENDING, - handle.Init("a", params_, kDefaultPriority, SocketTag(), + handle.Init(group_id_, params_, kDefaultPriority, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, callback.callback(), ClientSocketPool::ProxyAuthCallback(), &pool_, NetLogWithSource())); @@ -341,7 +340,7 @@ TestCompletionCallback callback2; EXPECT_EQ( ERR_IO_PENDING, - handle.Init("a", params_, kDefaultPriority, SocketTag(), + handle.Init(group_id_, params_, kDefaultPriority, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, callback2.callback(), ClientSocketPool::ProxyAuthCallback(), &pool_, NetLogWithSource())); @@ -364,17 +363,17 @@ TEST_F(WebSocketTransportClientSocketPoolTest, CancelRequest) { // First request finishes asynchronously. - EXPECT_THAT(StartRequest("a", kDefaultPriority), IsError(ERR_IO_PENDING)); + EXPECT_THAT(StartRequest(kDefaultPriority), IsError(ERR_IO_PENDING)); EXPECT_THAT(request(0)->WaitForResult(), IsOk()); // Make all subsequent host resolutions complete synchronously. host_resolver_->set_synchronous_mode(true); - EXPECT_THAT(StartRequest("a", kDefaultPriority), IsError(ERR_IO_PENDING)); - EXPECT_THAT(StartRequest("a", kDefaultPriority), IsError(ERR_IO_PENDING)); - EXPECT_THAT(StartRequest("a", kDefaultPriority), IsError(ERR_IO_PENDING)); - EXPECT_THAT(StartRequest("a", kDefaultPriority), IsError(ERR_IO_PENDING)); - EXPECT_THAT(StartRequest("a", kDefaultPriority), IsError(ERR_IO_PENDING)); + EXPECT_THAT(StartRequest(kDefaultPriority), IsError(ERR_IO_PENDING)); + EXPECT_THAT(StartRequest(kDefaultPriority), IsError(ERR_IO_PENDING)); + EXPECT_THAT(StartRequest(kDefaultPriority), IsError(ERR_IO_PENDING)); + EXPECT_THAT(StartRequest(kDefaultPriority), IsError(ERR_IO_PENDING)); + EXPECT_THAT(StartRequest(kDefaultPriority), IsError(ERR_IO_PENDING)); // Cancel a request. const size_t index_to_cancel = 2; @@ -403,7 +402,8 @@ // request is expected to succeed asynchronously. // // |nested_callback| is called with the result of the second socket request. -void RequestSocketOnComplete(ClientSocketHandle* handle, +void RequestSocketOnComplete(const ClientSocketPool::GroupId& group_id, + ClientSocketHandle* handle, WebSocketTransportClientSocketPool* pool, TestCompletionCallback* nested_callback, int first_request_result) { @@ -419,9 +419,9 @@ HostPortPair("www.google.com", 80), false, OnHostResolutionCallback()))); int rv = handle->Init( - "a", dest, LOWEST, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, - nested_callback->callback(), ClientSocketPool::ProxyAuthCallback(), pool, - NetLogWithSource()); + group_id, dest, LOWEST, SocketTag(), + ClientSocketPool::RespectLimits::ENABLED, nested_callback->callback(), + ClientSocketPool::ProxyAuthCallback(), pool, NetLogWithSource()); EXPECT_THAT(rv, IsError(ERR_IO_PENDING)); if (ERR_IO_PENDING != rv) nested_callback->callback().Run(rv); @@ -438,11 +438,12 @@ HostPortPair("www.google.com", 80), false, OnHostResolutionCallback()))); TestCompletionCallback second_result_callback; - int rv = handle.Init( - "a", dest, LOWEST, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, - base::BindOnce(&RequestSocketOnComplete, &handle, &pool_, - &second_result_callback), - ClientSocketPool::ProxyAuthCallback(), &pool_, NetLogWithSource()); + int rv = handle.Init(group_id_, dest, LOWEST, SocketTag(), + ClientSocketPool::RespectLimits::ENABLED, + base::BindOnce(&RequestSocketOnComplete, group_id_, + &handle, &pool_, &second_result_callback), + ClientSocketPool::ProxyAuthCallback(), &pool_, + NetLogWithSource()); ASSERT_THAT(rv, IsError(ERR_IO_PENDING)); EXPECT_THAT(second_result_callback.WaitForResult(), IsOk()); @@ -457,15 +458,15 @@ MockTransportClientSocketFactory::MOCK_PENDING_CLIENT_SOCKET); // Queue up all the requests - EXPECT_THAT(StartRequest("a", kDefaultPriority), IsError(ERR_IO_PENDING)); - EXPECT_THAT(StartRequest("a", kDefaultPriority), IsError(ERR_IO_PENDING)); - EXPECT_THAT(StartRequest("a", kDefaultPriority), IsError(ERR_IO_PENDING)); - EXPECT_THAT(StartRequest("a", kDefaultPriority), IsError(ERR_IO_PENDING)); - EXPECT_THAT(StartRequest("a", kDefaultPriority), IsError(ERR_IO_PENDING)); - EXPECT_THAT(StartRequest("a", kDefaultPriority), IsError(ERR_IO_PENDING)); - EXPECT_THAT(StartRequest("a", kDefaultPriority), IsError(ERR_IO_PENDING)); - EXPECT_THAT(StartRequest("a", kDefaultPriority), IsError(ERR_IO_PENDING)); - EXPECT_THAT(StartRequest("a", kDefaultPriority), IsError(ERR_IO_PENDING)); + EXPECT_THAT(StartRequest(kDefaultPriority), IsError(ERR_IO_PENDING)); + EXPECT_THAT(StartRequest(kDefaultPriority), IsError(ERR_IO_PENDING)); + EXPECT_THAT(StartRequest(kDefaultPriority), IsError(ERR_IO_PENDING)); + EXPECT_THAT(StartRequest(kDefaultPriority), IsError(ERR_IO_PENDING)); + EXPECT_THAT(StartRequest(kDefaultPriority), IsError(ERR_IO_PENDING)); + EXPECT_THAT(StartRequest(kDefaultPriority), IsError(ERR_IO_PENDING)); + EXPECT_THAT(StartRequest(kDefaultPriority), IsError(ERR_IO_PENDING)); + EXPECT_THAT(StartRequest(kDefaultPriority), IsError(ERR_IO_PENDING)); + EXPECT_THAT(StartRequest(kDefaultPriority), IsError(ERR_IO_PENDING)); // Now, kMaxSocketsPerGroup requests should be active. Let's cancel them. ASSERT_LE(kMaxSocketsPerGroup, static_cast<int>(requests()->size())); @@ -492,7 +493,7 @@ // Queue up all the requests for (int i = 0; i < kNumRequests; i++) - EXPECT_THAT(StartRequest("a", kDefaultPriority), IsError(ERR_IO_PENDING)); + EXPECT_THAT(StartRequest(kDefaultPriority), IsError(ERR_IO_PENDING)); for (int i = 0; i < kNumRequests; i++) EXPECT_THAT(request(i)->WaitForResult(), IsError(ERR_CONNECTION_FAILED)); @@ -500,8 +501,8 @@ // The lock on the endpoint is released when a ClientSocketHandle is reset. TEST_F(WebSocketTransportClientSocketPoolTest, LockReleasedOnHandleReset) { - EXPECT_THAT(StartRequest("a", kDefaultPriority), IsError(ERR_IO_PENDING)); - EXPECT_THAT(StartRequest("a", kDefaultPriority), IsError(ERR_IO_PENDING)); + EXPECT_THAT(StartRequest(kDefaultPriority), IsError(ERR_IO_PENDING)); + EXPECT_THAT(StartRequest(kDefaultPriority), IsError(ERR_IO_PENDING)); EXPECT_THAT(request(0)->WaitForResult(), IsOk()); EXPECT_FALSE(request(1)->handle()->is_initialized()); request(0)->handle()->Reset(); @@ -514,12 +515,12 @@ TestCompletionCallback callback; std::unique_ptr<ClientSocketHandle> handle(new ClientSocketHandle); int rv = handle->Init( - "a", params_, LOW, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, - callback.callback(), ClientSocketPool::ProxyAuthCallback(), &pool_, - NetLogWithSource()); + group_id_, params_, LOW, SocketTag(), + ClientSocketPool::RespectLimits::ENABLED, callback.callback(), + ClientSocketPool::ProxyAuthCallback(), &pool_, NetLogWithSource()); EXPECT_THAT(rv, IsError(ERR_IO_PENDING)); - EXPECT_THAT(StartRequest("a", kDefaultPriority), IsError(ERR_IO_PENDING)); + EXPECT_THAT(StartRequest(kDefaultPriority), IsError(ERR_IO_PENDING)); EXPECT_THAT(callback.WaitForResult(), IsOk()); EXPECT_FALSE(request(0)->handle()->is_initialized()); handle.reset(); @@ -531,8 +532,8 @@ // explicitly released. TEST_F(WebSocketTransportClientSocketPoolTest, ConnectionProceedsOnExplicitRelease) { - EXPECT_THAT(StartRequest("a", kDefaultPriority), IsError(ERR_IO_PENDING)); - EXPECT_THAT(StartRequest("a", kDefaultPriority), IsError(ERR_IO_PENDING)); + EXPECT_THAT(StartRequest(kDefaultPriority), IsError(ERR_IO_PENDING)); + EXPECT_THAT(StartRequest(kDefaultPriority), IsError(ERR_IO_PENDING)); EXPECT_THAT(request(0)->WaitForResult(), IsOk()); EXPECT_FALSE(request(1)->handle()->is_initialized()); WebSocketTransportClientSocketPool::UnlockEndpoint( @@ -552,10 +553,10 @@ client_socket_factory_.set_client_socket_types(case_types, base::size(case_types)); - EXPECT_THAT(StartRequest("a", kDefaultPriority), IsError(ERR_IO_PENDING)); - EXPECT_THAT(StartRequest("a", kDefaultPriority), IsError(ERR_IO_PENDING)); + EXPECT_THAT(StartRequest(kDefaultPriority), IsError(ERR_IO_PENDING)); + EXPECT_THAT(StartRequest(kDefaultPriority), IsError(ERR_IO_PENDING)); RunUntilIdle(); - pool_.CancelRequest("a", request(0)->handle()); + pool_.CancelRequest(group_id_, request(0)->handle()); EXPECT_THAT(request(1)->WaitForResult(), IsOk()); } @@ -590,9 +591,9 @@ TestCompletionCallback callback; ClientSocketHandle handle; int rv = handle.Init( - "a", params_, LOW, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, - callback.callback(), ClientSocketPool::ProxyAuthCallback(), &pool, - NetLogWithSource()); + group_id_, params_, LOW, SocketTag(), + ClientSocketPool::RespectLimits::ENABLED, callback.callback(), + ClientSocketPool::ProxyAuthCallback(), &pool, NetLogWithSource()); EXPECT_THAT(rv, IsError(ERR_IO_PENDING)); EXPECT_FALSE(handle.is_initialized()); EXPECT_FALSE(handle.socket()); @@ -640,9 +641,9 @@ TestCompletionCallback callback; ClientSocketHandle handle; int rv = handle.Init( - "a", params_, LOW, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, - callback.callback(), ClientSocketPool::ProxyAuthCallback(), &pool, - NetLogWithSource()); + group_id_, params_, LOW, SocketTag(), + ClientSocketPool::RespectLimits::ENABLED, callback.callback(), + ClientSocketPool::ProxyAuthCallback(), &pool, NetLogWithSource()); EXPECT_THAT(rv, IsError(ERR_IO_PENDING)); EXPECT_FALSE(handle.is_initialized()); EXPECT_FALSE(handle.socket()); @@ -680,9 +681,9 @@ TestCompletionCallback callback; ClientSocketHandle handle; int rv = handle.Init( - "a", params_, LOW, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, - callback.callback(), ClientSocketPool::ProxyAuthCallback(), &pool, - NetLogWithSource()); + group_id_, params_, LOW, SocketTag(), + ClientSocketPool::RespectLimits::ENABLED, callback.callback(), + ClientSocketPool::ProxyAuthCallback(), &pool, NetLogWithSource()); EXPECT_THAT(rv, IsError(ERR_IO_PENDING)); EXPECT_FALSE(handle.is_initialized()); EXPECT_FALSE(handle.socket()); @@ -718,9 +719,9 @@ TestCompletionCallback callback; ClientSocketHandle handle; int rv = handle.Init( - "a", params_, LOW, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, - callback.callback(), ClientSocketPool::ProxyAuthCallback(), &pool, - NetLogWithSource()); + group_id_, params_, LOW, SocketTag(), + ClientSocketPool::RespectLimits::ENABLED, callback.callback(), + ClientSocketPool::ProxyAuthCallback(), &pool, NetLogWithSource()); EXPECT_THAT(rv, IsError(ERR_IO_PENDING)); EXPECT_FALSE(handle.is_initialized()); EXPECT_FALSE(handle.socket()); @@ -767,9 +768,9 @@ TestCompletionCallback callback; ClientSocketHandle handle; int rv = handle.Init( - "a", params_, LOW, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, - callback.callback(), ClientSocketPool::ProxyAuthCallback(), &pool, - NetLogWithSource()); + group_id_, params_, LOW, SocketTag(), + ClientSocketPool::RespectLimits::ENABLED, callback.callback(), + ClientSocketPool::ProxyAuthCallback(), &pool, NetLogWithSource()); EXPECT_THAT(rv, IsOk()); ASSERT_TRUE(handle.socket()); @@ -811,9 +812,9 @@ TestCompletionCallback callback; ClientSocketHandle handle; int rv = handle.Init( - "a", params_, LOW, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, - callback.callback(), ClientSocketPool::ProxyAuthCallback(), &pool, - NetLogWithSource()); + group_id_, params_, LOW, SocketTag(), + ClientSocketPool::RespectLimits::ENABLED, callback.callback(), + ClientSocketPool::ProxyAuthCallback(), &pool, NetLogWithSource()); EXPECT_THAT(rv, IsError(ERR_IO_PENDING)); EXPECT_FALSE(handle.socket()); @@ -855,9 +856,9 @@ TestCompletionCallback callback; ClientSocketHandle handle; int rv = handle.Init( - "a", params_, LOW, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, - callback.callback(), ClientSocketPool::ProxyAuthCallback(), &pool, - NetLogWithSource()); + group_id_, params_, LOW, SocketTag(), + ClientSocketPool::RespectLimits::ENABLED, callback.callback(), + ClientSocketPool::ProxyAuthCallback(), &pool, NetLogWithSource()); EXPECT_THAT(rv, IsError(ERR_IO_PENDING)); ASSERT_FALSE(handle.socket()); @@ -915,9 +916,9 @@ ClientSocketHandle handle; base::TimeTicks start(base::TimeTicks::Now()); int rv = handle.Init( - "a", params_, LOW, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, - callback.callback(), ClientSocketPool::ProxyAuthCallback(), &pool, - NetLogWithSource()); + group_id_, params_, LOW, SocketTag(), + ClientSocketPool::RespectLimits::ENABLED, callback.callback(), + ClientSocketPool::ProxyAuthCallback(), &pool, NetLogWithSource()); EXPECT_THAT(rv, IsError(ERR_IO_PENDING)); EXPECT_THAT(callback.WaitForResult(), IsError(ERR_CONNECTION_FAILED)); @@ -961,9 +962,9 @@ ClientSocketHandle handle; int rv = handle.Init( - "a", params_, LOW, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, - callback.callback(), ClientSocketPool::ProxyAuthCallback(), &pool, - NetLogWithSource()); + group_id_, params_, LOW, SocketTag(), + ClientSocketPool::RespectLimits::ENABLED, callback.callback(), + ClientSocketPool::ProxyAuthCallback(), &pool, NetLogWithSource()); EXPECT_THAT(rv, IsError(ERR_IO_PENDING)); EXPECT_THAT(callback.WaitForResult(), IsError(ERR_TIMED_OUT)); @@ -972,17 +973,17 @@ TEST_F(WebSocketTransportClientSocketPoolTest, MaxSocketsEnforced) { host_resolver_->set_synchronous_mode(true); for (int i = 0; i < kMaxSockets; ++i) { - ASSERT_THAT(StartRequest("a", kDefaultPriority), IsOk()); + ASSERT_THAT(StartRequest(kDefaultPriority), IsOk()); WebSocketTransportClientSocketPool::UnlockEndpoint( request(i)->handle(), &websocket_endpoint_lock_manager_); RunUntilIdle(); } - EXPECT_THAT(StartRequest("a", kDefaultPriority), IsError(ERR_IO_PENDING)); + EXPECT_THAT(StartRequest(kDefaultPriority), IsError(ERR_IO_PENDING)); } TEST_F(WebSocketTransportClientSocketPoolTest, MaxSocketsEnforcedWhenPending) { for (int i = 0; i < kMaxSockets + 1; ++i) { - EXPECT_THAT(StartRequest("a", kDefaultPriority), IsError(ERR_IO_PENDING)); + EXPECT_THAT(StartRequest(kDefaultPriority), IsError(ERR_IO_PENDING)); } // Now there are 32 sockets waiting to connect, and one stalled. for (int i = 0; i < kMaxSockets; ++i) { @@ -1001,13 +1002,13 @@ TEST_F(WebSocketTransportClientSocketPoolTest, StalledSocketReleased) { host_resolver_->set_synchronous_mode(true); for (int i = 0; i < kMaxSockets; ++i) { - ASSERT_THAT(StartRequest("a", kDefaultPriority), IsOk()); + ASSERT_THAT(StartRequest(kDefaultPriority), IsOk()); WebSocketTransportClientSocketPool::UnlockEndpoint( request(i)->handle(), &websocket_endpoint_lock_manager_); RunUntilIdle(); } - EXPECT_THAT(StartRequest("a", kDefaultPriority), IsError(ERR_IO_PENDING)); + EXPECT_THAT(StartRequest(kDefaultPriority), IsError(ERR_IO_PENDING)); ReleaseOneConnection(ClientSocketPoolTest::NO_KEEP_ALIVE); EXPECT_TRUE(request(kMaxSockets)->handle()->is_initialized()); EXPECT_TRUE(request(kMaxSockets)->handle()->socket()); @@ -1015,7 +1016,7 @@ TEST_F(WebSocketTransportClientSocketPoolTest, IsStalledTrueWhenStalled) { for (int i = 0; i < kMaxSockets + 1; ++i) { - EXPECT_THAT(StartRequest("a", kDefaultPriority), IsError(ERR_IO_PENDING)); + EXPECT_THAT(StartRequest(kDefaultPriority), IsError(ERR_IO_PENDING)); } EXPECT_THAT(request(0)->WaitForResult(), IsOk()); EXPECT_TRUE(pool_.IsStalled()); @@ -1024,7 +1025,7 @@ TEST_F(WebSocketTransportClientSocketPoolTest, CancellingPendingSocketUnstallsStalledSocket) { for (int i = 0; i < kMaxSockets + 1; ++i) { - EXPECT_THAT(StartRequest("a", kDefaultPriority), IsError(ERR_IO_PENDING)); + EXPECT_THAT(StartRequest(kDefaultPriority), IsError(ERR_IO_PENDING)); } EXPECT_THAT(request(0)->WaitForResult(), IsOk()); request(1)->handle()->Reset(); @@ -1035,16 +1036,16 @@ TEST_F(WebSocketTransportClientSocketPoolTest, LoadStateOfStalledSocketIsWaitingForAvailableSocket) { for (int i = 0; i < kMaxSockets + 1; ++i) { - EXPECT_THAT(StartRequest("a", kDefaultPriority), IsError(ERR_IO_PENDING)); + EXPECT_THAT(StartRequest(kDefaultPriority), IsError(ERR_IO_PENDING)); } EXPECT_EQ(LOAD_STATE_WAITING_FOR_AVAILABLE_SOCKET, - pool_.GetLoadState("a", request(kMaxSockets)->handle())); + pool_.GetLoadState(group_id_, request(kMaxSockets)->handle())); } TEST_F(WebSocketTransportClientSocketPoolTest, CancellingStalledSocketUnstallsPool) { for (int i = 0; i < kMaxSockets + 1; ++i) { - EXPECT_THAT(StartRequest("a", kDefaultPriority), IsError(ERR_IO_PENDING)); + EXPECT_THAT(StartRequest(kDefaultPriority), IsError(ERR_IO_PENDING)); } request(kMaxSockets)->handle()->Reset(); RunUntilIdle(); @@ -1053,7 +1054,7 @@ TEST_F(WebSocketTransportClientSocketPoolTest, FlushWithErrorFlushesPendingConnections) { - EXPECT_THAT(StartRequest("a", kDefaultPriority), IsError(ERR_IO_PENDING)); + EXPECT_THAT(StartRequest(kDefaultPriority), IsError(ERR_IO_PENDING)); pool_.FlushWithError(ERR_FAILED); EXPECT_THAT(request(0)->WaitForResult(), IsError(ERR_FAILED)); } @@ -1061,7 +1062,7 @@ TEST_F(WebSocketTransportClientSocketPoolTest, FlushWithErrorFlushesStalledConnections) { for (int i = 0; i < kMaxSockets + 1; ++i) { - EXPECT_THAT(StartRequest("a", kDefaultPriority), IsError(ERR_IO_PENDING)); + EXPECT_THAT(StartRequest(kDefaultPriority), IsError(ERR_IO_PENDING)); } pool_.FlushWithError(ERR_FAILED); EXPECT_THAT(request(kMaxSockets)->WaitForResult(), IsError(ERR_FAILED)); @@ -1070,11 +1071,11 @@ TEST_F(WebSocketTransportClientSocketPoolTest, AfterFlushWithErrorCanMakeNewConnections) { for (int i = 0; i < kMaxSockets + 1; ++i) { - EXPECT_THAT(StartRequest("a", kDefaultPriority), IsError(ERR_IO_PENDING)); + EXPECT_THAT(StartRequest(kDefaultPriority), IsError(ERR_IO_PENDING)); } pool_.FlushWithError(ERR_FAILED); host_resolver_->set_synchronous_mode(true); - EXPECT_THAT(StartRequest("a", kDefaultPriority), IsOk()); + EXPECT_THAT(StartRequest(kDefaultPriority), IsOk()); } // Deleting pending connections can release the lock on the endpoint, which can @@ -1093,7 +1094,7 @@ client_socket_factory_.set_default_client_socket_type( MockTransportClientSocketFactory::MOCK_CLIENT_SOCKET); for (int i = 0; i < kMaxSockets; ++i) { - EXPECT_THAT(StartRequest("a", kDefaultPriority), IsError(ERR_IO_PENDING)); + EXPECT_THAT(StartRequest(kDefaultPriority), IsError(ERR_IO_PENDING)); } // Now we have one socket in STATE_TRANSPORT_CONNECT and the rest in // STATE_OBTAIN_LOCK. If any of the sockets in STATE_OBTAIN_LOCK is given the @@ -1132,7 +1133,7 @@ "1.1.1.1", i + 1), std::string()); - EXPECT_THAT(StartRequest("a", kDefaultPriority), IsError(ERR_IO_PENDING)); + EXPECT_THAT(StartRequest(kDefaultPriority), IsError(ERR_IO_PENDING)); } // Now we have |kMaxSockets| IPv6 sockets stalled in connect. No IPv4 sockets // are started yet. @@ -1156,11 +1157,11 @@ MockTransportClientSocketFactory::MOCK_STALLED_CLIENT_SOCKET}; client_socket_factory_.set_client_socket_types(socket_types, base::size(socket_types)); - EXPECT_THAT(StartRequest("a", kDefaultPriority), IsOk()); + EXPECT_THAT(StartRequest(kDefaultPriority), IsOk()); // Socket has been "handed out". EXPECT_TRUE(request(0)->handle()->socket()); - EXPECT_THAT(StartRequest("a", kDefaultPriority), IsError(ERR_IO_PENDING)); + EXPECT_THAT(StartRequest(kDefaultPriority), IsError(ERR_IO_PENDING)); // Now we have one socket handed out, and one pending. pool_.FlushWithError(ERR_FAILED); EXPECT_THAT(request(1)->WaitForResult(), IsError(ERR_FAILED)); @@ -1181,7 +1182,7 @@ client_socket_factory_.set_client_socket_types(socket_types, base::size(socket_types)); - EXPECT_THAT(StartRequest("a", kDefaultPriority), IsError(ERR_IO_PENDING)); + EXPECT_THAT(StartRequest(kDefaultPriority), IsError(ERR_IO_PENDING)); base::Closure connect_trigger = client_socket_factory_.WaitForTriggerableSocketCreation(); @@ -1193,16 +1194,16 @@ RunUntilIdle(); // We should now be able to create a new connection without blocking on the // endpoint lock. - EXPECT_THAT(StartRequest("a", kDefaultPriority), IsOk()); + EXPECT_THAT(StartRequest(kDefaultPriority), IsOk()); } // A handshake completing and then the WebSocket closing should only release one // Endpoint, not two. TEST_F(WebSocketTransportClientSocketPoolTest, EndpointLockIsOnlyReleasedOnce) { host_resolver_->set_synchronous_mode(true); - ASSERT_THAT(StartRequest("a", kDefaultPriority), IsOk()); - EXPECT_THAT(StartRequest("a", kDefaultPriority), IsError(ERR_IO_PENDING)); - EXPECT_THAT(StartRequest("a", kDefaultPriority), IsError(ERR_IO_PENDING)); + ASSERT_THAT(StartRequest(kDefaultPriority), IsOk()); + EXPECT_THAT(StartRequest(kDefaultPriority), IsError(ERR_IO_PENDING)); + EXPECT_THAT(StartRequest(kDefaultPriority), IsError(ERR_IO_PENDING)); // First socket completes handshake. WebSocketTransportClientSocketPool::UnlockEndpoint( request(0)->handle(), &websocket_endpoint_lock_manager_);
diff --git a/net/spdy/spdy_session_unittest.cc b/net/spdy/spdy_session_unittest.cc index 0b86dc3..8817798 100644 --- a/net/spdy/spdy_session_unittest.cc +++ b/net/spdy/spdy_session_unittest.cc
@@ -3549,15 +3549,17 @@ scoped_refptr<TransportSocketParams> params2( new TransportSocketParams(host_port2, false, OnHostResolutionCallback())); auto connection2 = std::make_unique<ClientSocketHandle>(); - EXPECT_EQ(ERR_IO_PENDING, - connection2->Init(host_port2.ToString(), - TransportClientSocketPool::SocketParams:: - CreateFromTransportSocketParams(params2), - DEFAULT_PRIORITY, SocketTag(), - ClientSocketPool::RespectLimits::ENABLED, - callback2.callback(), - ClientSocketPool::ProxyAuthCallback(), pool, - NetLogWithSource())); + EXPECT_EQ( + ERR_IO_PENDING, + connection2->Init( + ClientSocketPool::GroupId(host_port2, + ClientSocketPool::SocketType::kHttp, + false /* privacy_mode */), + TransportClientSocketPool::SocketParams:: + CreateFromTransportSocketParams(params2), + DEFAULT_PRIORITY, SocketTag(), + ClientSocketPool::RespectLimits::ENABLED, callback2.callback(), + ClientSocketPool::ProxyAuthCallback(), pool, NetLogWithSource())); EXPECT_TRUE(pool->IsStalled()); // The socket pool should close the connection asynchronously and establish a @@ -3632,15 +3634,17 @@ scoped_refptr<TransportSocketParams> params3( new TransportSocketParams(host_port3, false, OnHostResolutionCallback())); auto connection3 = std::make_unique<ClientSocketHandle>(); - EXPECT_EQ(ERR_IO_PENDING, - connection3->Init(host_port3.ToString(), - TransportClientSocketPool::SocketParams:: - CreateFromTransportSocketParams(params3), - DEFAULT_PRIORITY, SocketTag(), - ClientSocketPool::RespectLimits::ENABLED, - callback3.callback(), - ClientSocketPool::ProxyAuthCallback(), pool, - NetLogWithSource())); + EXPECT_EQ( + ERR_IO_PENDING, + connection3->Init( + ClientSocketPool::GroupId(host_port3, + ClientSocketPool::SocketType::kHttp, + false /* privacy_mode */), + TransportClientSocketPool::SocketParams:: + CreateFromTransportSocketParams(params3), + DEFAULT_PRIORITY, SocketTag(), + ClientSocketPool::RespectLimits::ENABLED, callback3.callback(), + ClientSocketPool::ProxyAuthCallback(), pool, NetLogWithSource())); EXPECT_TRUE(pool->IsStalled()); // The socket pool should close the connection asynchronously and establish a @@ -3713,15 +3717,17 @@ scoped_refptr<TransportSocketParams> params2( new TransportSocketParams(host_port2, false, OnHostResolutionCallback())); auto connection2 = std::make_unique<ClientSocketHandle>(); - EXPECT_EQ(ERR_IO_PENDING, - connection2->Init(host_port2.ToString(), - TransportClientSocketPool::SocketParams:: - CreateFromTransportSocketParams(params2), - DEFAULT_PRIORITY, SocketTag(), - ClientSocketPool::RespectLimits::ENABLED, - callback2.callback(), - ClientSocketPool::ProxyAuthCallback(), pool, - NetLogWithSource())); + EXPECT_EQ( + ERR_IO_PENDING, + connection2->Init( + ClientSocketPool::GroupId(host_port2, + ClientSocketPool::SocketType::kHttp, + false /* privacy_mode */), + TransportClientSocketPool::SocketParams:: + CreateFromTransportSocketParams(params2), + DEFAULT_PRIORITY, SocketTag(), + ClientSocketPool::RespectLimits::ENABLED, callback2.callback(), + ClientSocketPool::ProxyAuthCallback(), pool, NetLogWithSource())); EXPECT_TRUE(pool->IsStalled()); // Running the message loop should cause the socket pool to ask the SPDY
diff --git a/net/spdy/spdy_test_util_common.cc b/net/spdy/spdy_test_util_common.cc index 823f678..bc9968c 100644 --- a/net/spdy/spdy_test_util_common.cc +++ b/net/spdy/spdy_test_util_common.cc
@@ -501,7 +501,9 @@ transport_params, nullptr, nullptr, key.host_port_pair(), ssl_config, key.privacy_mode()); int rv = connection->Init( - key.host_port_pair().ToString(), + ClientSocketPool::GroupId(key.host_port_pair(), + ClientSocketPool::SocketType::kSsl, + key.privacy_mode()), TransportClientSocketPool::SocketParams::CreateFromSSLSocketParams( ssl_params), MEDIUM, key.socket_tag(), ClientSocketPool::RespectLimits::ENABLED,
diff --git a/net/ssl/ssl_config.cc b/net/ssl/ssl_config.cc index a21037f..ce61dfb7 100644 --- a/net/ssl/ssl_config.cc +++ b/net/ssl/ssl_config.cc
@@ -26,7 +26,6 @@ version_max(kDefaultSSLVersionMax), early_data_enabled(false), version_interference_probe(false), - channel_id_enabled(false), false_start_enabled(true), require_ecdhe(false), ignore_certificate_errors(false),
diff --git a/net/ssl/ssl_config.h b/net/ssl/ssl_config.h index 8d660542..a1257dfb 100644 --- a/net/ssl/ssl_config.h +++ b/net/ssl/ssl_config.h
@@ -89,8 +89,6 @@ // ERR_SSL_VERSION_INTERFERENCE. bool version_interference_probe; - bool channel_id_enabled; // True if TLS channel ID extension is enabled. - bool false_start_enabled; // True if we'll use TLS False Start. // If true, causes only ECDHE cipher suites to be enabled.
diff --git a/net/ssl/ssl_config_service.cc b/net/ssl/ssl_config_service.cc index e81ffd90..3abd3289 100644 --- a/net/ssl/ssl_config_service.cc +++ b/net/ssl/ssl_config_service.cc
@@ -16,11 +16,11 @@ bool SSLConfigsAreEqual(const net::SSLConfig& config1, const net::SSLConfig& config2) { return std::tie(config1.version_min, config1.version_max, - config1.disabled_cipher_suites, config1.channel_id_enabled, - config1.false_start_enabled, config1.require_ecdhe) == + config1.disabled_cipher_suites, config1.false_start_enabled, + config1.require_ecdhe) == std::tie(config2.version_min, config2.version_max, - config2.disabled_cipher_suites, config2.channel_id_enabled, - config2.false_start_enabled, config2.require_ecdhe); + config2.disabled_cipher_suites, config2.false_start_enabled, + config2.require_ecdhe); } } // namespace
diff --git a/net/ssl/ssl_config_service.h b/net/ssl/ssl_config_service.h index 3ec9da49..9136a65 100644 --- a/net/ssl/ssl_config_service.h +++ b/net/ssl/ssl_config_service.h
@@ -29,7 +29,6 @@ // version_min // version_max // disabled_cipher_suites - // channel_id_enabled // false_start_enabled // require_ecdhe virtual void OnSSLConfigChanged() = 0;
diff --git a/net/tools/crash_cache/crash_cache.cc b/net/tools/crash_cache/crash_cache.cc index aea9609..e90f6c5 100644 --- a/net/tools/crash_cache/crash_cache.cc +++ b/net/tools/crash_cache/crash_cache.cc
@@ -143,9 +143,8 @@ int size = 1024 * 1024; disk_cache::BackendImpl* backend = new disk_cache::BackendImpl( path, /* cleanup_tracker = */ nullptr, thread->task_runner().get(), - /* net_log = */ nullptr); + net::DISK_CACHE, /* net_log = */ nullptr); backend->SetMaxSize(size); - backend->SetType(net::DISK_CACHE); backend->SetFlags(disk_cache::kNoRandom); int rv = backend->Init(cb->callback()); *cache = backend; @@ -272,7 +271,7 @@ // Work with a tiny index table (16 entries). disk_cache::BackendImpl* cache = new disk_cache::BackendImpl( - path, 0xf, cache_thread->task_runner().get(), nullptr); + path, 0xf, cache_thread->task_runner().get(), net::DISK_CACHE, nullptr); if (!cache->SetMaxSize(0x100000)) return GENERIC;
diff --git a/net/tools/stress_cache/stress_cache.cc b/net/tools/stress_cache/stress_cache.cc index e7ead12..f48d04a7 100644 --- a/net/tools/stress_cache/stress_cache.cc +++ b/net/tools/stress_cache/stress_cache.cc
@@ -312,7 +312,7 @@ g_data = new Data(); g_data->iteration = iteration; g_data->cache = new disk_cache::BackendImpl( - path, mask, cache_thread.task_runner().get(), nullptr); + path, mask, cache_thread.task_runner().get(), net::DISK_CACHE, nullptr); g_data->cache->SetMaxSize(cache_size); g_data->cache->SetFlags(disk_cache::kNoLoadProtection);
diff --git a/net/url_request/http_with_dns_over_https_unittest.cc b/net/url_request/http_with_dns_over_https_unittest.cc index cb877ff..e0149eb 100644 --- a/net/url_request/http_with_dns_over_https_unittest.cc +++ b/net/url_request/http_with_dns_over_https_unittest.cc
@@ -205,12 +205,13 @@ &request_delegate, false, false, NetLogWithSource())); loop.Run(); - std::string group_name(request_info.url.host() + ":" + - request_info.url.port()); + ClientSocketPool::GroupId group_id( + HostPortPair(request_info.url.host(), request_info.url.IntPort()), + ClientSocketPool::SocketType::kHttp, false /* privacy_mode */); EXPECT_EQ(network_session ->GetSocketPool(HttpNetworkSession::NORMAL_SOCKET_POOL, ProxyServer::Direct()) - ->IdleSocketCountInGroup(group_name), + ->IdleSocketCountInGroup(group_id), 1u); // Make a request that will trigger a DoH query as well.
diff --git a/net/websockets/websocket_basic_stream_adapters_test.cc b/net/websockets/websocket_basic_stream_adapters_test.cc index c1144c9..a8294fad 100644 --- a/net/websockets/websocket_basic_stream_adapters_test.cc +++ b/net/websockets/websocket_basic_stream_adapters_test.cc
@@ -52,8 +52,6 @@ namespace test { -const char* const kGroupName = "ssl/www.example.org:443"; - class WebSocketClientSocketHandleAdapterTest : public TestWithScopedTaskEnvironment { protected: @@ -94,7 +92,9 @@ bool InitClientSocketHandle(ClientSocketHandle* connection) { TestCompletionCallback callback; int rv = connection->Init( - kGroupName, + ClientSocketPool::GroupId(host_port_pair_, + ClientSocketPool::SocketType::kSsl, + false /* privacy_mode */), TransportClientSocketPool::SocketParams::CreateFromSSLSocketParams( ssl_params_), MEDIUM, SocketTag(), ClientSocketPool::RespectLimits::ENABLED,
diff --git a/net/websockets/websocket_basic_stream_test.cc b/net/websockets/websocket_basic_stream_test.cc index fc4bd5c..1cf54548 100644 --- a/net/websockets/websocket_basic_stream_test.cc +++ b/net/websockets/websocket_basic_stream_test.cc
@@ -123,8 +123,11 @@ auto transport_socket = std::make_unique<ClientSocketHandle>(); scoped_refptr<MockTransportSocketParams> params; + ClientSocketPool::GroupId group_id(HostPortPair("a", 80), + ClientSocketPool::SocketType::kHttp, + false /* privacy_mode */); transport_socket->Init( - "a", params, MEDIUM, SocketTag(), + group_id, params, MEDIUM, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, CompletionOnceCallback(), ClientSocketPool::ProxyAuthCallback(), &pool_, NetLogWithSource()); return transport_socket;
diff --git a/net/websockets/websocket_handshake_stream_create_helper_test.cc b/net/websockets/websocket_handshake_stream_create_helper_test.cc index 619dfaf..48a0f72 100644 --- a/net/websockets/websocket_handshake_stream_create_helper_test.cc +++ b/net/websockets/websocket_handshake_stream_create_helper_test.cc
@@ -11,6 +11,7 @@ #include "base/macros.h" #include "base/memory/scoped_refptr.h" #include "net/base/completion_once_callback.h" +#include "net/base/host_port_pair.h" #include "net/base/ip_endpoint.h" #include "net/base/net_errors.h" #include "net/base/proxy_server.h" @@ -69,7 +70,10 @@ socket_factory_maker_.SetExpectations(expect_written, return_to_read); auto socket_handle = std::make_unique<ClientSocketHandle>(); socket_handle->Init( - "a", scoped_refptr<MockTransportSocketParams>(), MEDIUM, SocketTag(), + ClientSocketPool::GroupId(HostPortPair("a", 80), + ClientSocketPool::SocketType::kHttp, + false /* privacy_mode */), + scoped_refptr<MockTransportSocketParams>(), MEDIUM, SocketTag(), ClientSocketPool::RespectLimits::ENABLED, CompletionOnceCallback(), ClientSocketPool::ProxyAuthCallback(), &pool_, NetLogWithSource()); return socket_handle;
diff --git a/printing/backend/cups_ipp_util.h b/printing/backend/cups_ipp_util.h index d01efd3..41c7a9f 100644 --- a/printing/backend/cups_ipp_util.h +++ b/printing/backend/cups_ipp_util.h
@@ -23,10 +23,14 @@ extern const char kIppDuplex[]; extern const char kIppDocumentName[]; extern const char kIppRequestingUserName[]; +extern const char kIppPin[]; +extern const char kIppPinEncryption[]; extern const char kCollated[]; extern const char kUncollated[]; +extern const char kPinEncryptionNone[]; + // Smart ptr wrapper for CUPS ipp_t using ScopedIppPtr = std::unique_ptr<ipp_t, void (*)(ipp_t*)>;
diff --git a/printing/print_job_constants.cc b/printing/print_job_constants.cc index babc7d7..04b7dcb 100644 --- a/printing/print_job_constants.cc +++ b/printing/print_job_constants.cc
@@ -139,6 +139,9 @@ const char kSettingPageWidth[] = "pageWidth"; const char kSettingPageHeight[] = "pageHeight"; +// PIN code entered by the user. +const char kSettingPinValue[] = "pinValue"; + // Policies affecting printing destination. const char kSettingPolicies[] = "policies";
diff --git a/printing/print_job_constants.h b/printing/print_job_constants.h index 9a45cad..70edcee3 100644 --- a/printing/print_job_constants.h +++ b/printing/print_job_constants.h
@@ -53,6 +53,7 @@ PRINTING_EXPORT extern const char kSettingPageWidth[]; PRINTING_EXPORT extern const char kSettingPageHeight[]; PRINTING_EXPORT extern const char kSettingPagesPerSheet[]; +PRINTING_EXPORT extern const char kSettingPinValue[]; PRINTING_EXPORT extern const char kSettingPolicies[]; PRINTING_EXPORT extern const char kSettingPreviewModifiable[]; PRINTING_EXPORT extern const char kSettingPrintToGoogleDrive[];
diff --git a/printing/print_settings.h b/printing/print_settings.h index dc931586..a12f392 100644 --- a/printing/print_settings.h +++ b/printing/print_settings.h
@@ -200,6 +200,9 @@ void set_username(const std::string& username) { username_ = username; } const std::string& username() const { return username_; } + + void set_pin_value(const std::string& pin_value) { pin_value_ = pin_value; } + const std::string& pin_value() const { return pin_value_; } #endif // Cookie generator. It is used to initialize PrintedDocument with its @@ -287,6 +290,9 @@ // Username if it's required by the printer. std::string username_; + + // PIN code entered by the user. + std::string pin_value_; #endif };
diff --git a/printing/print_settings_conversion.cc b/printing/print_settings_conversion.cc index cdf5724..2563ae6 100644 --- a/printing/print_settings_conversion.cc +++ b/printing/print_settings_conversion.cc
@@ -33,13 +33,13 @@ return; } page_size_margins->top = - custom_margins->FindKey(kSettingMarginTop)->GetDouble(); + custom_margins->FindIntKey(kSettingMarginTop).value_or(0); page_size_margins->bottom = - custom_margins->FindKey(kSettingMarginBottom)->GetDouble(); + custom_margins->FindIntKey(kSettingMarginBottom).value_or(0); page_size_margins->left = - custom_margins->FindKey(kSettingMarginLeft)->GetDouble(); + custom_margins->FindIntKey(kSettingMarginLeft).value_or(0); page_size_margins->right = - custom_margins->FindKey(kSettingMarginRight)->GetDouble(); + custom_margins->FindIntKey(kSettingMarginRight).value_or(0); } void SetMarginsToJobSettings(const std::string& json_path, @@ -218,6 +218,10 @@ if (username) settings->set_username(*username); } + + const std::string* pin_value = job_settings.FindStringKey(kSettingPinValue); + if (pin_value) + settings->set_pin_value(*pin_value); #endif return true;
diff --git a/printing/print_settings_conversion_unittest.cc b/printing/print_settings_conversion_unittest.cc index 56e5e0e9..e8a0a7c 100644 --- a/printing/print_settings_conversion_unittest.cc +++ b/printing/print_settings_conversion_unittest.cc
@@ -41,10 +41,11 @@ "dpiVertical": 300, "previewModifiable": true, "sendUserInfo": true, - "username": "username@domain.net" + "username": "username@domain.net", + "pinValue": "0000" })"; -} +} // namespace TEST(PrintSettingsConversionTest, ConversionTest) { std::unique_ptr<base::Value> value = @@ -57,6 +58,7 @@ #if defined(OS_CHROMEOS) EXPECT_TRUE(settings.send_user_info()); EXPECT_EQ("username@domain.net", settings.username()); + EXPECT_EQ("0000", settings.pin_value()); #endif }
diff --git a/printing/printing_context_chromeos.cc b/printing/printing_context_chromeos.cc index f6547ec..f8d8cf2e 100644 --- a/printing/printing_context_chromeos.cc +++ b/printing/printing_context_chromeos.cc
@@ -131,6 +131,10 @@ options.push_back( ConstructOption(kIppRequestingUserName, settings.username())); } + if (!settings.pin_value().empty()) { + options.push_back(ConstructOption(kIppPin, settings.pin_value())); + options.push_back(ConstructOption(kIppPinEncryption, kPinEncryptionNone)); + } return options; }
diff --git a/remoting/protocol/webrtc_dummy_video_encoder.cc b/remoting/protocol/webrtc_dummy_video_encoder.cc index f7b04768..3aae02d 100644 --- a/remoting/protocol/webrtc_dummy_video_encoder.cc +++ b/remoting/protocol/webrtc_dummy_video_encoder.cc
@@ -145,8 +145,9 @@ encoded_image._encodedWidth = frame.size.width(); encoded_image._encodedHeight = frame.size.height(); encoded_image._completeFrame = true; - encoded_image._frameType = - frame.key_frame ? webrtc::kVideoFrameKey : webrtc::kVideoFrameDelta; + encoded_image._frameType = frame.key_frame + ? webrtc::VideoFrameType::kVideoFrameKey + : webrtc::VideoFrameType::kVideoFrameDelta; int64_t capture_time_ms = (capture_time - base::TimeTicks()).InMilliseconds(); int64_t encode_started_time_ms = (encode_started_time - base::TimeTicks()).InMilliseconds();
diff --git a/sandbox/win/src/restricted_token.cc b/sandbox/win/src/restricted_token.cc index fdc1dbe7..b68ffd8 100644 --- a/sandbox/win/src/restricted_token.cc +++ b/sandbox/win/src/restricted_token.cc
@@ -117,13 +117,9 @@ bool result = true; HANDLE new_token_handle = nullptr; - // The SANDBOX_INERT flag did nothing in XP and it was just a way to tell - // if a token has ben restricted given the limiations of IsTokenRestricted() - // but it appears that in Windows 7 it hints the AppLocker subsystem to - // leave us alone. if (deny_size || restrict_size || privileges_size) { result = ::CreateRestrictedToken( - effective_token_.Get(), SANDBOX_INERT, static_cast<DWORD>(deny_size), + effective_token_.Get(), 0, static_cast<DWORD>(deny_size), deny_only_array, static_cast<DWORD>(privileges_size), privileges_to_disable_array, static_cast<DWORD>(restrict_size), sids_to_restrict_array, &new_token_handle);
diff --git a/services/device/generic_sensor/README.md b/services/device/generic_sensor/README.md index 1301cbd0..a61c56f7 100644 --- a/services/device/generic_sensor/README.md +++ b/services/device/generic_sensor/README.md
@@ -67,7 +67,7 @@ | AMBIENT_LIGHT | TYPE_LIGHT | in_illuminance | AppleLMUController | SENSOR_TYPE_AMBIENT_LIGHT | | PROXIMITY | | | | | | ACCELEROMETER | TYPE_ACCELEROMETER | in_accel | SMCMotionSensor | SENSOR_TYPE_ACCELEROMETER_3D | -| LINEAR_ACCELEROMETER | TYPE_LINEAR_ACCELEROMETER | ACCELEROMETER (*) | | ACCELEROMETER (*) | +| LINEAR_ACCELEROMETER | See below | ACCELEROMETER (*) | | ACCELEROMETER (*) | | GYROSCOPE | TYPE_GYROSCOPE | in_anglvel | | SENSOR_TYPE_GYROMETER_3D | | MAGNETOMETER | TYPE_MAGNETIC_FIELD | in_magn | | SENSOR_TYPE_COMPASS_3D | | PRESSURE | | | | | @@ -87,6 +87,10 @@ constants from the android.hardware.Sensor used to provide data for a SensorType. +For LINEAR_ACCELEROMETER, the following sensor fallback is used: +1. Use TYPE_LINEAR_ACCELERATION directly +2. ACCELEROMETER, with a low-pass filter to isolate the effect of gravity + For ABSOLUTE_ORIENTATION_EULER_ANGLES, the following sensor fallback is used: 1. ABSOLUTE_ORIENTATION_QUATERNION (if it uses TYPE_ROTATION_VECTOR directly)
diff --git a/services/device/generic_sensor/platform_sensor_provider_android.cc b/services/device/generic_sensor/platform_sensor_provider_android.cc index 752a114..787aefc 100644 --- a/services/device/generic_sensor/platform_sensor_provider_android.cc +++ b/services/device/generic_sensor/platform_sensor_provider_android.cc
@@ -12,6 +12,7 @@ #include "base/memory/singleton.h" #include "jni/PlatformSensorProvider_jni.h" #include "services/device/generic_sensor/absolute_orientation_euler_angles_fusion_algorithm_using_accelerometer_and_magnetometer.h" +#include "services/device/generic_sensor/linear_acceleration_fusion_algorithm_using_accelerometer.h" #include "services/device/generic_sensor/orientation_euler_angles_fusion_algorithm_using_quaternion.h" #include "services/device/generic_sensor/orientation_quaternion_fusion_algorithm_using_euler_angles.h" #include "services/device/generic_sensor/platform_sensor_android.h" @@ -52,6 +53,9 @@ // Android version, so the fallback ensures selection of the best possible // option. switch (type) { + case mojom::SensorType::LINEAR_ACCELERATION: + CreateLinearAccelerationSensor(env, reading_buffer, callback); + break; case mojom::SensorType::ABSOLUTE_ORIENTATION_EULER_ANGLES: CreateAbsoluteOrientationEulerAnglesSensor(env, reading_buffer, callback); break; @@ -79,6 +83,33 @@ } } +// For LINEAR_ACCELERATION we see if the platform supports it directly through +// TYPE_LINEAR_ACCELERATION. If not we use a fusion algorithm to remove the +// contribution of gravity from the raw ACCELEROMETER. +void PlatformSensorProviderAndroid::CreateLinearAccelerationSensor( + JNIEnv* env, + SensorReadingSharedBuffer* reading_buffer, + const CreateSensorCallback& callback) { + ScopedJavaLocalRef<jobject> sensor = Java_PlatformSensorProvider_createSensor( + env, j_object_, + static_cast<jint>(mojom::SensorType::LINEAR_ACCELERATION)); + + if (sensor.obj()) { + auto concrete_sensor = base::MakeRefCounted<PlatformSensorAndroid>( + mojom::SensorType::LINEAR_ACCELERATION, reading_buffer, this, sensor); + + callback.Run(concrete_sensor); + } else { + auto sensor_fusion_algorithm = + std::make_unique<LinearAccelerationFusionAlgorithmUsingAccelerometer>(); + + // If this PlatformSensorFusion object is successfully initialized, + // |callback| will be run with a reference to this object. + PlatformSensorFusion::Create(reading_buffer, this, + std::move(sensor_fusion_algorithm), callback); + } +} + // For ABSOLUTE_ORIENTATION_EULER_ANGLES we use a 3-way fallback approach // where up to 3 different sets of sensors are attempted if necessary. The // sensors to be used are determined in the following order:
diff --git a/services/device/generic_sensor/platform_sensor_provider_android.h b/services/device/generic_sensor/platform_sensor_provider_android.h index 5c4a311a..0ff21aed 100644 --- a/services/device/generic_sensor/platform_sensor_provider_android.h +++ b/services/device/generic_sensor/platform_sensor_provider_android.h
@@ -26,6 +26,9 @@ const CreateSensorCallback& callback) override; private: + void CreateLinearAccelerationSensor(JNIEnv* env, + SensorReadingSharedBuffer* reading_buffer, + const CreateSensorCallback& callback); void CreateAbsoluteOrientationEulerAnglesSensor( JNIEnv* env, SensorReadingSharedBuffer* reading_buffer,
diff --git a/services/identity/public/cpp/identity_manager.cc b/services/identity/public/cpp/identity_manager.cc index a1383631..f689fb9 100644 --- a/services/identity/public/cpp/identity_manager.cc +++ b/services/identity/public/cpp/identity_manager.cc
@@ -40,7 +40,7 @@ } // namespace IdentityManager::IdentityManager( - SigninManagerBase* signin_manager, + std::unique_ptr<SigninManagerBase> signin_manager, ProfileOAuth2TokenService* token_service, AccountFetcherService* account_fetcher_service, AccountTrackerService* account_tracker_service, @@ -49,7 +49,7 @@ std::unique_ptr<AccountsMutator> accounts_mutator, std::unique_ptr<AccountsCookieMutator> accounts_cookie_mutator, std::unique_ptr<DiagnosticsProvider> diagnostics_provider) - : signin_manager_(signin_manager), + : signin_manager_(std::move(signin_manager)), token_service_(token_service), account_fetcher_service_(account_fetcher_service), account_tracker_service_(account_tracker_service), @@ -70,6 +70,7 @@ IdentityManager::~IdentityManager() { signin_manager_->ClearObserver(); + signin_manager_->Shutdown(); token_service_->RemoveObserver(this); token_service_->RemoveDiagnosticsObserver(this); account_tracker_service_->RemoveObserver(this); @@ -379,7 +380,7 @@ } SigninManagerBase* IdentityManager::GetSigninManager() { - return signin_manager_; + return signin_manager_.get(); } ProfileOAuth2TokenService* IdentityManager::GetTokenService() {
diff --git a/services/identity/public/cpp/identity_manager.h b/services/identity/public/cpp/identity_manager.h index 5f68591..266f726 100644 --- a/services/identity/public/cpp/identity_manager.h +++ b/services/identity/public/cpp/identity_manager.h
@@ -197,7 +197,7 @@ }; IdentityManager( - SigninManagerBase* signin_manager, + std::unique_ptr<SigninManagerBase> signin_manager, ProfileOAuth2TokenService* token_service, AccountFetcherService* account_fetcher_service, AccountTrackerService* account_tracker_service, @@ -520,6 +520,21 @@ // TODO(https://crbug.com/889902): Delete this when conversion is done. friend SigninManagerAndroid; + // IdentityManagerTest reaches into IdentityManager internals in + // order to drive its behavior. + // TODO(https://crbug.com/943135): Find a better way to accomplish this. + FRIEND_TEST_ALL_PREFIXES(IdentityManagerTest, RemoveAccessTokenFromCache); + FRIEND_TEST_ALL_PREFIXES(IdentityManagerTest, + CreateAccessTokenFetcherWithCustomURLLoaderFactory); + FRIEND_TEST_ALL_PREFIXES(IdentityManagerTest, ObserveAccessTokenFetch); + FRIEND_TEST_ALL_PREFIXES(IdentityManagerTest, + ObserveAccessTokenRequestCompletionWithRefreshToken); + FRIEND_TEST_ALL_PREFIXES(IdentityManagerTest, + BatchChangeObserversAreNotifiedOnCredentialsUpdate); + FRIEND_TEST_ALL_PREFIXES(IdentityManagerTest, RemoveAccessTokenFromCache); + FRIEND_TEST_ALL_PREFIXES(IdentityManagerTest, + CreateAccessTokenFetcherWithCustomURLLoaderFactory); + // Private getters used for testing only (i.e. see identity_test_utils.h). SigninManagerBase* GetSigninManager(); ProfileOAuth2TokenService* GetTokenService(); @@ -577,7 +592,7 @@ // these classes in the IdentityManager implementation, as all such // synchronous access will become impossible when IdentityManager is // backed by the Identity Service. - SigninManagerBase* signin_manager_; + std::unique_ptr<SigninManagerBase> signin_manager_; ProfileOAuth2TokenService* token_service_; AccountFetcherService* account_fetcher_service_; AccountTrackerService* account_tracker_service_;
diff --git a/services/identity/public/cpp/identity_manager_unittest.cc b/services/identity/public/cpp/identity_manager_unittest.cc index 4b7ae63..7015c15 100644 --- a/services/identity/public/cpp/identity_manager_unittest.cc +++ b/services/identity/public/cpp/identity_manager_unittest.cc
@@ -277,9 +277,8 @@ &signin_client_, &token_service_, &account_tracker_, std::make_unique<image_fetcher::FakeImageDecoder>()); - RecreateSigninAndIdentityManager( - signin::AccountConsistencyMethod::kDisabled, - SigninManagerSetup::kWithAuthenticatedAccout); + RecreateIdentityManager(signin::AccountConsistencyMethod::kDisabled, + SigninManagerSetup::kWithAuthenticatedAccout); } ~IdentityManagerTest() override { @@ -305,7 +304,6 @@ } AccountTrackerService* account_tracker() { return &account_tracker_; } AccountFetcherService* account_fetcher() { return &account_fetcher_; } - SigninManagerBase* signin_manager() { return signin_manager_.get(); } CustomFakeProfileOAuth2TokenService* token_service() { return &token_service_; } @@ -313,39 +311,40 @@ return &gaia_cookie_manager_service_; } - // See RecreateSigninAndIdentityManager. + // See RecreateIdentityManager. enum class SigninManagerSetup { kWithAuthenticatedAccout, kNoAuthenticatedAccount }; - // Recreates SigninManager and IdentityManager with given - // |account_consistency| and optionally seeds with an authenticated account - // depending on |singin_manager_setup|. This process destroys any existing - // IdentityManager and its dependencies, then remakes them. Dependencies that - // outlive SigninManager (e.g. SigninClient) will be reused. - void RecreateSigninAndIdentityManager( + // Used by some tests that need to re-instantiate IdentityManager after + // performing some other setup. + void RecreateIdentityManager() { + RecreateIdentityManager(signin::AccountConsistencyMethod::kDisabled, + SigninManagerSetup::kNoAuthenticatedAccount); + } + + // Recreates IdentityManager with given |account_consistency| and optionally + // seeds with an authenticated account depending on |singin_manager_setup|. + // This process destroys any existing IdentityManager and its dependencies, + // then remakes them. Dependencies that outlive SigninManager (e.g. + // SigninClient) will be reused. + void RecreateIdentityManager( signin::AccountConsistencyMethod account_consistency, SigninManagerSetup signin_manager_setup) { - // Reset dependents to null first to ensure that they're destroyed, as - // otherwise destructors of SigninManager and dependents will DCHECK because - // they still having living observers. + // Remove observers first, otherwise IdentityManager destruction might + // trigger a DCHECK because there are still living observers. identity_manager_observer_.reset(); identity_manager_diagnostics_observer_.reset(); identity_manager_.reset(); - if (signin_manager_) { - signin_manager_->Shutdown(); - signin_manager_.reset(); - } - #if defined(OS_CHROMEOS) DCHECK_EQ(account_consistency, signin::AccountConsistencyMethod::kDisabled) << "AccountConsistency is not used by SigninManagerBase"; - signin_manager_ = std::make_unique<SigninManagerBase>( + auto signin_manager = std::make_unique<SigninManagerBase>( &signin_client_, &token_service_, &account_tracker_); #else - signin_manager_ = std::make_unique<SigninManager>( + auto signin_manager = std::make_unique<SigninManager>( &signin_client_, &token_service_, &account_tracker_, &gaia_cookie_manager_service_, account_consistency); #endif @@ -356,29 +355,14 @@ base::CommandLine* cmd_line = base::CommandLine::ForCurrentProcess(); cmd_line->AppendSwitch(switches::kClearTokenService); - signin_manager_->Initialize(&pref_service_); + signin_manager->Initialize(&pref_service_); if (signin_manager_setup == SigninManagerSetup::kWithAuthenticatedAccout) { - signin_manager()->SetAuthenticatedAccountInfo(kTestGaiaId, kTestEmail); + signin_manager->SetAuthenticatedAccountInfo(kTestGaiaId, kTestEmail); } - RecreateIdentityManager(); - } - - // Used by some tests that need to re-instantiate IdentityManager after - // performing some other setup. - void RecreateIdentityManager() { - DCHECK(signin_manager_) << "Create signin_manager_ first"; - - // Reset them all to null first to ensure that they're destroyed, as - // otherwise SigninManager ends up getting a new DiagnosticsObserver added - // before the old one is removed. - identity_manager_observer_.reset(); - identity_manager_diagnostics_observer_.reset(); - identity_manager_.reset(); - identity_manager_.reset(new IdentityManager( - signin_manager_.get(), &token_service_, &account_fetcher_, + std::move(signin_manager), &token_service_, &account_fetcher_, &account_tracker_, &gaia_cookie_manager_service_, nullptr, nullptr, std::make_unique<AccountsCookieMutatorImpl>( &gaia_cookie_manager_service_), @@ -430,7 +414,6 @@ CustomFakeProfileOAuth2TokenService token_service_; network::TestURLLoaderFactory test_url_loader_factory_; GaiaCookieManagerService gaia_cookie_manager_service_; - std::unique_ptr<SigninManagerBase> signin_manager_; std::unique_ptr<IdentityManager> identity_manager_; std::unique_ptr<TestIdentityManagerObserver> identity_manager_observer_; std::unique_ptr<TestIdentityManagerDiagnosticsObserver> @@ -652,7 +635,8 @@ // Recreate the IdentityManager and check that the newly-created instance // reflects the current state. - RecreateIdentityManager(); + RecreateIdentityManager(signin::AccountConsistencyMethod::kDisabled, + SigninManagerSetup::kWithAuthenticatedAccout); EXPECT_TRUE( identity_manager()->HasAccountWithRefreshToken(account_info.account_id)); @@ -1085,7 +1069,8 @@ std::set<std::string> scopes{"scope"}; std::string access_token = "access_token"; - signin_manager()->SetAuthenticatedAccountInfo(kTestGaiaId, kTestEmail); + identity_manager()->GetSigninManager()->SetAuthenticatedAccountInfo( + kTestGaiaId, kTestEmail); token_service()->UpdateCredentials(primary_account_id(), "refresh_token"); base::RunLoop run_loop; @@ -1123,7 +1108,8 @@ identity_manager_diagnostics_observer() ->set_on_access_token_requested_callback(run_loop.QuitClosure()); - signin_manager()->SetAuthenticatedAccountInfo(kTestGaiaId, kTestEmail); + identity_manager()->GetSigninManager()->SetAuthenticatedAccountInfo( + kTestGaiaId, kTestEmail); token_service()->UpdateCredentials(primary_account_id(), "refresh_token"); std::set<std::string> scopes{"scope"}; @@ -1209,7 +1195,8 @@ identity_manager_diagnostics_observer() ->set_on_access_token_requested_callback(run_loop.QuitClosure()); - signin_manager()->SetAuthenticatedAccountInfo(kTestGaiaId, kTestEmail); + identity_manager()->GetSigninManager()->SetAuthenticatedAccountInfo( + kTestGaiaId, kTestEmail); token_service()->UpdateCredentials(primary_account_id(), "refresh_token"); std::set<std::string> scopes{"scope"}; @@ -1261,7 +1248,8 @@ identity_manager_diagnostics_observer() ->set_on_access_token_request_completed_callback(run_loop.QuitClosure()); - signin_manager()->SetAuthenticatedAccountInfo(kTestGaiaId, kTestEmail); + identity_manager()->GetSigninManager()->SetAuthenticatedAccountInfo( + kTestGaiaId, kTestEmail); token_service()->UpdateCredentials(primary_account_id(), "refresh_token"); token_service()->set_auto_post_fetch_response_on_message_loop(true); @@ -1564,7 +1552,8 @@ // interacting with. Otherwise, even an implementation where they're // both TokenService::Observers would work as IdentityManager would // get notified first during the observer callbacks. - RecreateIdentityManager(); + RecreateIdentityManager(signin::AccountConsistencyMethod::kDisabled, + SigninManagerSetup::kWithAuthenticatedAccout); EXPECT_TRUE(identity_manager()->GetAccountsWithRefreshTokens().empty()); token_service_observer.set_identity_manager(identity_manager()); @@ -1589,7 +1578,8 @@ // interacting with. Otherwise, even an implementation where they're // both TokenService::Observers would work as IdentityManager would // get notified first during the observer callbacks. - RecreateIdentityManager(); + RecreateIdentityManager(signin::AccountConsistencyMethod::kDisabled, + SigninManagerSetup::kWithAuthenticatedAccout); token_service_observer.set_identity_manager(identity_manager()); token_service()->UpdateCredentials(primary_account_id(), "refresh_token"); @@ -2124,7 +2114,8 @@ TEST_F(IdentityManagerTest, BatchChangeObserversAreNotifiedOnCredentialsUpdate) { - signin_manager()->SetAuthenticatedAccountInfo(kTestGaiaId, kTestEmail); + identity_manager()->GetSigninManager()->SetAuthenticatedAccountInfo( + kTestGaiaId, kTestEmail); token_service()->UpdateCredentials(primary_account_id(), "refresh_token"); EXPECT_EQ(1ul, identity_manager_observer()->BatchChangeRecords().size());
diff --git a/services/identity/public/cpp/identity_test_environment.cc b/services/identity/public/cpp/identity_test_environment.cc index a72f1b5..665a56b 100644 --- a/services/identity/public/cpp/identity_test_environment.cc +++ b/services/identity/public/cpp/identity_test_environment.cc
@@ -44,7 +44,6 @@ IdentityManagerDependenciesOwner( network::TestURLLoaderFactory* test_url_loader_factory, sync_preferences::TestingPrefServiceSyncable* pref_service, - signin::AccountConsistencyMethod account_consistency, TestSigninClient* test_signin_client); ~IdentityManagerDependenciesOwner(); @@ -52,8 +51,6 @@ AccountFetcherService* account_fetcher_service(); - SigninManagerBase* signin_manager(); - FakeProfileOAuth2TokenService* token_service(); GaiaCookieManagerService* gaia_cookie_manager_service(); @@ -75,11 +72,6 @@ AccountTrackerService account_tracker_; AccountFetcherService account_fetcher_; FakeProfileOAuth2TokenService token_service_; -#if defined(OS_CHROMEOS) - SigninManagerBase signin_manager_; -#else - SigninManager signin_manager_; -#endif std::unique_ptr<GaiaCookieManagerService> gaia_cookie_manager_service_; DISALLOW_COPY_AND_ASSIGN(IdentityManagerDependenciesOwner); @@ -88,7 +80,6 @@ IdentityManagerDependenciesOwner::IdentityManagerDependenciesOwner( network::TestURLLoaderFactory* test_url_loader_factory, sync_preferences::TestingPrefServiceSyncable* pref_service_param, - signin::AccountConsistencyMethod account_consistency, TestSigninClient* signin_client_param) : owned_pref_service_( pref_service_param @@ -101,16 +92,7 @@ ? nullptr : std::make_unique<TestSigninClient>(pref_service())), raw_signin_client_(signin_client_param), - 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, - account_consistency) { -#endif + token_service_(pref_service()) { if (test_url_loader_factory != nullptr) { gaia_cookie_manager_service_ = std::make_unique<GaiaCookieManagerService>( &token_service_, signin_client(), @@ -134,11 +116,9 @@ account_fetcher_.Initialize( signin_client(), &token_service_, &account_tracker_, std::make_unique<image_fetcher::FakeImageDecoder>()); - signin_manager_.Initialize(pref_service()); } IdentityManagerDependenciesOwner::~IdentityManagerDependenciesOwner() { - signin_manager_.Shutdown(); account_fetcher_.Shutdown(); account_tracker_.Shutdown(); } @@ -153,10 +133,6 @@ return &account_fetcher_; } -SigninManagerBase* IdentityManagerDependenciesOwner::signin_manager() { - return &signin_manager_; -} - FakeProfileOAuth2TokenService* IdentityManagerDependenciesOwner::token_service() { return &token_service_; @@ -192,13 +168,12 @@ /*account_tracker_service=*/nullptr, /*account_fetcher_service=*/nullptr, /*token_service=*/nullptr, - /*signin_manager=*/nullptr, /*gaia_cookie_manager_service=*/nullptr, - /*test_url_loader_factory=*/test_url_loader_factory, + test_url_loader_factory, + account_consistency, std::make_unique<IdentityManagerDependenciesOwner>( test_url_loader_factory, pref_service, - account_consistency, test_signin_client), /*identity_manager=*/nullptr) {} @@ -207,17 +182,17 @@ 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) + network::TestURLLoaderFactory* test_url_loader_factory, + signin::AccountConsistencyMethod account_consistency) : IdentityTestEnvironment(pref_service, account_tracker_service, account_fetcher_service, token_service, - signin_manager, gaia_cookie_manager_service, test_url_loader_factory, + account_consistency, /*dependency_owner=*/nullptr, identity_manager) {} @@ -226,9 +201,9 @@ 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, + signin::AccountConsistencyMethod account_consistency, std::unique_ptr<IdentityManagerDependenciesOwner> dependencies_owner, IdentityManager* identity_manager) : pref_service_(pref_service), @@ -240,9 +215,10 @@ "IdentityTestEnvironment. Otherwise, use " "base::test::ScopedTaskEnvironment."; + TestSigninClient* test_signin_client = nullptr; if (dependencies_owner) { DCHECK(!(pref_service_ || account_tracker_service || - account_fetcher_service || token_service || signin_manager || + account_fetcher_service || token_service || gaia_cookie_manager_service || identity_manager)); dependencies_owner_ = std::move(dependencies_owner); @@ -250,20 +226,21 @@ account_tracker_service_ = dependencies_owner_->account_tracker_service(); account_fetcher_service_ = dependencies_owner_->account_fetcher_service(); token_service_ = dependencies_owner_->token_service(); - signin_manager_ = dependencies_owner_->signin_manager(); gaia_cookie_manager_service_ = dependencies_owner_->gaia_cookie_manager_service(); pref_service_ = dependencies_owner_->pref_service(); + test_signin_client = dependencies_owner_->signin_client(); } else { DCHECK(pref_service_ && account_tracker_service && - account_fetcher_service && token_service && signin_manager && + account_fetcher_service && token_service && gaia_cookie_manager_service); account_tracker_service_ = account_tracker_service; account_fetcher_service_ = account_fetcher_service; token_service_ = token_service; - signin_manager_ = signin_manager; gaia_cookie_manager_service_ = gaia_cookie_manager_service; + owned_signin_client_ = std::make_unique<TestSigninClient>(pref_service_); + test_signin_client = owned_signin_client_.get(); } // TODO(sdefresne): services should be initialized when this version of @@ -278,16 +255,30 @@ if (identity_manager) { raw_identity_manager_ = identity_manager; } else { +#if defined(OS_CHROMEOS) + std::unique_ptr<SigninManagerBase> signin_manager = + std::make_unique<SigninManagerBase>(test_signin_client, token_service_, + account_tracker_service_); +#else + std::unique_ptr<SigninManagerBase> signin_manager = + std::make_unique<SigninManager>(test_signin_client, token_service_, + account_tracker_service_, nullptr, + account_consistency); +#endif + signin_manager->Initialize(pref_service_); + std::unique_ptr<PrimaryAccountMutator> primary_account_mutator; std::unique_ptr<AccountsMutator> accounts_mutator; + #if !defined(OS_CHROMEOS) primary_account_mutator = std::make_unique<PrimaryAccountMutatorImpl>( - account_tracker_service_, static_cast<SigninManager*>(signin_manager_)); + account_tracker_service_, + static_cast<SigninManager*>(signin_manager.get())); #endif #if !defined(OS_ANDROID) && !defined(OS_IOS) accounts_mutator = std::make_unique<AccountsMutatorImpl>( - token_service_, account_tracker_service_, signin_manager_, + token_service_, account_tracker_service_, signin_manager.get(), pref_service_); #endif std::unique_ptr<DiagnosticsProvider> diagnostics_provider = @@ -299,7 +290,7 @@ gaia_cookie_manager_service_); owned_identity_manager_ = std::make_unique<IdentityManager>( - signin_manager_, token_service_, account_fetcher_service_, + std::move(signin_manager), token_service_, account_fetcher_service_, account_tracker_service_, gaia_cookie_manager_service_, std::move(primary_account_mutator), std::move(accounts_mutator), std::move(accounts_cookie_mutator), std::move(diagnostics_provider)); @@ -493,8 +484,8 @@ } } - // A requests came in for a request for which we are not waiting. Record that - // it's available. + // A requests came in for a request for which we are not waiting. Record + // that it's available. requesters_.emplace_back(); requesters_.back().state = AccessTokenRequestState::kAvailable; requesters_.back().account_id = account_id; @@ -574,8 +565,8 @@ void IdentityTestEnvironment::SimulateMergeSessionFailure( const GoogleServiceAuthError& auth_error) { // GaiaCookieManagerService changes the visibility of inherited method - // OnMergeSessionFailure from public to private. Cast to a base class pointer - // to use call the method. + // OnMergeSessionFailure from public to private. Cast to a base class + // pointer to call the method. static_cast<GaiaAuthConsumer*>(gaia_cookie_manager_service_) ->OnMergeSessionFailure(auth_error); }
diff --git a/services/identity/public/cpp/identity_test_environment.h b/services/identity/public/cpp/identity_test_environment.h index 32b87028..f1c30fe1 100644 --- a/services/identity/public/cpp/identity_test_environment.h +++ b/services/identity/public/cpp/identity_test_environment.h
@@ -306,10 +306,11 @@ 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 = nullptr); + network::TestURLLoaderFactory* test_url_loader_factory = nullptr, + signin::AccountConsistencyMethod account_consistency = + signin::AccountConsistencyMethod::kDisabled); // Constructs this object from the supplied // dependencies of IdentityManager and potentially IdentityManager itself. @@ -327,9 +328,9 @@ 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, + signin::AccountConsistencyMethod account_consistency, std::unique_ptr<IdentityManagerDependenciesOwner> dependencies_owner, IdentityManager* identity_manager); @@ -366,6 +367,10 @@ // This can be null if no TestURLLoaderFactory was passed via the constructor. network::TestURLLoaderFactory* test_url_loader_factory_ = nullptr; + // This will be null if a TestSigninClient was provided to + // IdentityTestEnvironment's constructor. + std::unique_ptr<TestSigninClient> owned_signin_client_; + // Depending on which constructor is used, exactly one of these will be // non-null. See the documentation on the constructor wherein IdentityManager // is passed in for required lifetime invariants in that case.
diff --git a/services/media_session/public/mojom/media_session.mojom b/services/media_session/public/mojom/media_session.mojom index 4be0ea83..fb0c2d6 100644 --- a/services/media_session/public/mojom/media_session.mojom +++ b/services/media_session/public/mojom/media_session.mojom
@@ -31,8 +31,11 @@ [Extensible] enum MediaSessionImageType { - // The artwork associated with the media session (e.g album art) + // The artwork associated with the media session (e.g album art). kArtwork, + + // The icon associated with the source of the media session. + kSourceIcon, }; // Album art in MediaMetadata
diff --git a/services/network/OWNERS b/services/network/OWNERS index 07a1ddb..0059fa66 100644 --- a/services/network/OWNERS +++ b/services/network/OWNERS
@@ -5,6 +5,7 @@ mmenke@chromium.org morlovich@chromium.org reillyg@chromium.org +rmcelrath@chromium.org tsepez@chromium.org yhirano@chromium.org
diff --git a/services/network/network_context.cc b/services/network/network_context.cc index 8e38c3b..f93240d5 100644 --- a/services/network/network_context.cc +++ b/services/network/network_context.cc
@@ -44,7 +44,6 @@ #include "net/cookies/cookie_monster.h" #include "net/dns/host_cache.h" #include "net/dns/mapped_host_resolver.h" -#include "net/extras/sqlite/sqlite_channel_id_store.h" #include "net/extras/sqlite/sqlite_persistent_cookie_store.h" #include "net/http/failing_http_transaction_factory.h" #include "net/http/http_auth_handler_factory.h"
diff --git a/services/shape_detection/BUILD.gn b/services/shape_detection/BUILD.gn index 65d2d61..baf0d09 100644 --- a/services/shape_detection/BUILD.gn +++ b/services/shape_detection/BUILD.gn
@@ -17,6 +17,8 @@ "barcode_detection_impl_mac.mm", "barcode_detection_impl_mac_vision.h", "barcode_detection_impl_mac_vision.mm", + "barcode_detection_impl_mac_vision_api.h", + "barcode_detection_impl_mac_vision_api.mm", "barcode_detection_provider_mac.h", "barcode_detection_provider_mac.mm", "detection_utils_mac.h",
diff --git a/services/shape_detection/barcode_detection_impl_mac.h b/services/shape_detection/barcode_detection_impl_mac.h index a2aeaa6..aaaa1f8 100644 --- a/services/shape_detection/barcode_detection_impl_mac.h +++ b/services/shape_detection/barcode_detection_impl_mac.h
@@ -5,9 +5,12 @@ #ifndef SERVICES_SHAPE_DETECTION_BARCODE_DETECTION_IMPL_MAC_H_ #define SERVICES_SHAPE_DETECTION_BARCODE_DETECTION_IMPL_MAC_H_ +#include <vector> + #include "base/mac/availability.h" #include "base/mac/scoped_nsobject.h" #include "services/shape_detection/public/mojom/barcodedetection.mojom.h" +#include "services/shape_detection/public/mojom/barcodedetection_provider.mojom.h" #include "third_party/skia/include/core/SkBitmap.h" @class CIDetector; @@ -24,6 +27,9 @@ shape_detection::mojom::BarcodeDetection::DetectCallback callback) override; + static std::vector<shape_detection::mojom::BarcodeFormat> + GetSupportedSymbologies(); + private: base::scoped_nsobject<CIDetector> detector_;
diff --git a/services/shape_detection/barcode_detection_impl_mac.mm b/services/shape_detection/barcode_detection_impl_mac.mm index 7a85af56..f99b6af 100644 --- a/services/shape_detection/barcode_detection_impl_mac.mm +++ b/services/shape_detection/barcode_detection_impl_mac.mm
@@ -53,4 +53,10 @@ std::move(callback).Run(std::move(results)); } +// static +std::vector<shape_detection::mojom::BarcodeFormat> +BarcodeDetectionImplMac::GetSupportedSymbologies() { + return {mojom::BarcodeFormat::QR_CODE}; +} + } // namespace shape_detection
diff --git a/services/shape_detection/barcode_detection_impl_mac_unittest.mm b/services/shape_detection/barcode_detection_impl_mac_unittest.mm index 762662c..b16e1ca 100644 --- a/services/shape_detection/barcode_detection_impl_mac_unittest.mm +++ b/services/shape_detection/barcode_detection_impl_mac_unittest.mm
@@ -124,16 +124,6 @@ } MOCK_METHOD0(Detection, void(void)); - void EnumerateSupportedFormatsCallback( - const std::vector<mojom::BarcodeFormat>& expected, - const std::vector<mojom::BarcodeFormat>& results) { - EXPECT_THAT(results, - testing::ElementsAreArray(expected.begin(), expected.end())); - - OnEnumerateSupportedFormats(); - } - MOCK_METHOD0(OnEnumerateSupportedFormats, void(void)); - std::unique_ptr<mojom::BarcodeDetection> impl_; const base::MessageLoop message_loop_; void* vision_framework_ = nullptr;
diff --git a/services/shape_detection/barcode_detection_impl_mac_vision.h b/services/shape_detection/barcode_detection_impl_mac_vision.h index beed4e5..cdb97e5 100644 --- a/services/shape_detection/barcode_detection_impl_mac_vision.h +++ b/services/shape_detection/barcode_detection_impl_mac_vision.h
@@ -7,17 +7,20 @@ #include <memory> #include <utility> +#include <vector> #include "base/mac/availability.h" #include "base/mac/sdk_forward_declarations.h" #include "base/macros.h" #include "base/memory/weak_ptr.h" #include "mojo/public/cpp/bindings/strong_binding.h" +#include "services/shape_detection/barcode_detection_impl_mac_vision_api.h" #include "services/shape_detection/detection_utils_mac.h" #include "services/shape_detection/public/mojom/barcodedetection.mojom.h" #include "services/shape_detection/public/mojom/barcodedetection_provider.mojom.h" class SkBitmap; +class VisionAPIInterface; namespace shape_detection { @@ -39,6 +42,9 @@ binding_ = std::move(binding); } + static std::vector<shape_detection::mojom::BarcodeFormat> + GetSupportedSymbologies(VisionAPIInterface* vision_api = nullptr); + private: void OnBarcodesDetected(VNRequest* request, NSError* error);
diff --git a/services/shape_detection/barcode_detection_impl_mac_vision.mm b/services/shape_detection/barcode_detection_impl_mac_vision.mm index fcedfec..98211bf 100644 --- a/services/shape_detection/barcode_detection_impl_mac_vision.mm +++ b/services/shape_detection/barcode_detection_impl_mac_vision.mm
@@ -9,6 +9,7 @@ #include "base/bind.h" #include "base/callback.h" +#include "base/containers/flat_set.h" #include "base/logging.h" #include "base/strings/sys_string_conversions.h" #include "third_party/skia/include/core/SkBitmap.h" @@ -22,18 +23,27 @@ return mojom::BarcodeFormat::AZTEC; if ([symbology isEqual:@"VNBarcodeSymbologyCode128"]) return mojom::BarcodeFormat::CODE_128; - if ([symbology isEqual:@"VNBarcodeSymbologyCode39"]) + if ([symbology isEqual:@"VNBarcodeSymbologyCode39"] || + [symbology isEqual:@"VNBarcodeSymbologyCode39Checksum"] || + [symbology isEqual:@"VNBarcodeSymbologyCode39FullASCII"] || + [symbology isEqual:@"VNBarcodeSymbologyCode39FullASCIIChecksum"]) { return mojom::BarcodeFormat::CODE_39; - if ([symbology isEqual:@"VNBarcodeSymbologyCode93"]) + } + if ([symbology isEqual:@"VNBarcodeSymbologyCode93"] || + [symbology isEqual:@"VNBarcodeSymbologyCode93i"]) { return mojom::BarcodeFormat::CODE_93; + } if ([symbology isEqual:@"VNBarcodeSymbologyDataMatrix"]) return mojom::BarcodeFormat::DATA_MATRIX; if ([symbology isEqual:@"VNBarcodeSymbologyEAN13"]) return mojom::BarcodeFormat::EAN_13; if ([symbology isEqual:@"VNBarcodeSymbologyEAN8"]) return mojom::BarcodeFormat::EAN_8; - if ([symbology isEqual:@"VNBarcodeSymbologyITF14"]) + if ([symbology isEqual:@"VNBarcodeSymbologyITF14"] || + [symbology isEqual:@"VNBarcodeSymbologyI2of5"] || + [symbology isEqual:@"VNBarcodeSymbologyI2of5Checksum"]) { return mojom::BarcodeFormat::ITF; + } if ([symbology isEqual:@"VNBarcodeSymbologyPDF417"]) return mojom::BarcodeFormat::PDF417; if ([symbology isEqual:@"VNBarcodeSymbologyQR"]) @@ -137,4 +147,30 @@ std::move(detected_callback_).Run(std::move(results)); } +// static +std::vector<shape_detection::mojom::BarcodeFormat> +BarcodeDetectionImplMacVision::GetSupportedSymbologies( + VisionAPIInterface* vision_api) { + std::unique_ptr<VisionAPIInterface> scoped_vision_api; + if (!vision_api) { + scoped_vision_api = VisionAPIInterface::Create(); + vision_api = scoped_vision_api.get(); + } + base::flat_set<shape_detection::mojom::BarcodeFormat> results; + NSArray<NSString*>* symbologies = vision_api->GetSupportedSymbologies(); + + results.reserve([symbologies count]); + for (NSString* symbology : symbologies) { + auto converted = ToBarcodeFormat(symbology); + if (converted == shape_detection::mojom::BarcodeFormat::UNKNOWN) { + DLOG(WARNING) << "Symbology " << base::SysNSStringToUTF8(symbology) + << " unknown to spec."; + continue; + } + results.insert(converted); + } + return std::vector<shape_detection::mojom::BarcodeFormat>(results.begin(), + results.end()); +} + } // namespace shape_detection
diff --git a/services/shape_detection/barcode_detection_impl_mac_vision_api.h b/services/shape_detection/barcode_detection_impl_mac_vision_api.h new file mode 100644 index 0000000..53c1cf3d --- /dev/null +++ b/services/shape_detection/barcode_detection_impl_mac_vision_api.h
@@ -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. + +#ifndef SERVICES_SHAPE_DETECTION_BARCODE_DETECTION_IMPL_MAC_VISION_API_H_ +#define SERVICES_SHAPE_DETECTION_BARCODE_DETECTION_IMPL_MAC_VISION_API_H_ + +#include <memory> + +#ifdef __OBJC__ + +#include <CoreFoundation/CoreFoundation.h> + +#include "base/mac/scoped_nsobject.h" + +namespace shape_detection { + +class VisionAPIInterface { + public: + VisionAPIInterface() {} + virtual ~VisionAPIInterface() {} + + static std::unique_ptr<VisionAPIInterface> Create(); + + virtual NSArray* GetSupportedSymbologies() const = 0; + + private: + DISALLOW_COPY_AND_ASSIGN(VisionAPIInterface); +}; + +} // namespace shape_detection + +#endif // __OBJC__ + +#endif // SERVICES_SHAPE_DETECTION_BARCODE_DETECTION_IMPL_MAC_VISION_API_H_
diff --git a/services/shape_detection/barcode_detection_impl_mac_vision_api.mm b/services/shape_detection/barcode_detection_impl_mac_vision_api.mm new file mode 100644 index 0000000..e35d6c6 --- /dev/null +++ b/services/shape_detection/barcode_detection_impl_mac_vision_api.mm
@@ -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. + +#include "services/shape_detection/barcode_detection_impl_mac_vision_api.h" +#include "base/logging.h" +#include "base/mac/sdk_forward_declarations.h" + +namespace shape_detection { + +namespace { + +class VisionAPI : public VisionAPIInterface { + public: + VisionAPI() = default; + + ~VisionAPI() override = default; + + NSArray* GetSupportedSymbologies() const override { + Class request_class = NSClassFromString(@"VNDetectBarcodesRequest"); + if (!request_class) { + DPLOG(ERROR) << "Failed to load VNDetectBarcodesRequest class"; + return [NSArray array]; + } + + SEL sel = NSSelectorFromString(@"supportedSymbologies"); + id symbologies = [request_class performSelector:sel]; + if (![symbologies isKindOfClass:[NSArray class]]) { + DLOG(ERROR) + << "Failed to get NSArray of supportedSymbologies (wrong type)"; + return [NSArray array]; + } + return symbologies; + } +}; + +} // anonymous namespace + +// static +std::unique_ptr<VisionAPIInterface> VisionAPIInterface::Create() { + return std::make_unique<VisionAPI>(); +} + +} // namespace shape_detection
diff --git a/services/shape_detection/barcode_detection_provider_mac.h b/services/shape_detection/barcode_detection_provider_mac.h index 309f6ea..7dcdf6b 100644 --- a/services/shape_detection/barcode_detection_provider_mac.h +++ b/services/shape_detection/barcode_detection_provider_mac.h
@@ -5,10 +5,16 @@ #ifndef SERVICES_SHAPE_DETECTION_BARCODE_DETECTION_PROVIDER_MAC_H_ #define SERVICES_SHAPE_DETECTION_BARCODE_DETECTION_PROVIDER_MAC_H_ +#include <memory> +#include <vector> + #include "base/macros.h" +#include "services/shape_detection/barcode_detection_impl_mac_vision_api.h" #include "services/shape_detection/public/mojom/barcodedetection.mojom.h" #include "services/shape_detection/public/mojom/barcodedetection_provider.mojom.h" +class VisionAPIInterface; + namespace shape_detection { // The BarcodeDetectionProviderMac class is a provider that binds an @@ -18,6 +24,7 @@ : public shape_detection::mojom::BarcodeDetectionProvider { public: BarcodeDetectionProviderMac(); + explicit BarcodeDetectionProviderMac(std::unique_ptr<VisionAPIInterface>); ~BarcodeDetectionProviderMac() override; // Binds BarcodeDetection provider request to the implementation of @@ -32,6 +39,9 @@ private: DISALLOW_COPY_AND_ASSIGN(BarcodeDetectionProviderMac); + + base::Optional<std::vector<mojom::BarcodeFormat>> supported_formats_; + std::unique_ptr<VisionAPIInterface> vision_api_; }; } // namespace shape_detection
diff --git a/services/shape_detection/barcode_detection_provider_mac.mm b/services/shape_detection/barcode_detection_provider_mac.mm index f0a7a39..17c16e6 100644 --- a/services/shape_detection/barcode_detection_provider_mac.mm +++ b/services/shape_detection/barcode_detection_provider_mac.mm
@@ -15,6 +15,9 @@ namespace shape_detection { BarcodeDetectionProviderMac::BarcodeDetectionProviderMac() = default; +BarcodeDetectionProviderMac::BarcodeDetectionProviderMac( + std::unique_ptr<VisionAPIInterface> vision_api) + : vision_api_(std::move(vision_api)) {} BarcodeDetectionProviderMac::~BarcodeDetectionProviderMac() = default; @@ -49,29 +52,38 @@ void BarcodeDetectionProviderMac::EnumerateSupportedFormats( EnumerateSupportedFormatsCallback callback) { + // If we have supported formats already cached, return them. + if (supported_formats_) { + DLOG_IF(WARNING, supported_formats_->empty()) + << "Supported formats requested previously but error or none " + << "recognized."; + + std::move(callback).Run(supported_formats_.value()); + return; + } + + if (!vision_api_) + vision_api_ = VisionAPIInterface::Create(); + // Vision Framework needs at least MAC OS X 10.13. if (@available(macOS 10.13, *)) { - if (!BarcodeDetectionImplMacVision::IsBlockedMacOSVersion()) { - // Vision recognizes more barcode symbologies than Core Image Framework. - std::move(callback).Run( - {mojom::BarcodeFormat::AZTEC, mojom::BarcodeFormat::CODE_128, - mojom::BarcodeFormat::CODE_39, mojom::BarcodeFormat::CODE_93, - mojom::BarcodeFormat::DATA_MATRIX, mojom::BarcodeFormat::EAN_13, - mojom::BarcodeFormat::EAN_8, mojom::BarcodeFormat::ITF, - mojom::BarcodeFormat::PDF417, mojom::BarcodeFormat::QR_CODE, - mojom::BarcodeFormat::UPC_E}); - return; - } + // Vision recognizes more barcode symbologies than Core Image Framework. + supported_formats_ = BarcodeDetectionImplMacVision::GetSupportedSymbologies( + vision_api_.get()); + std::move(callback).Run(supported_formats_.value()); + return; } // Barcode detection needs at least MAC OS X 10.10. if (@available(macOS 10.10, *)) { - // Mac implementation supports only one BarcodeFormat. - std::move(callback).Run({mojom::BarcodeFormat::QR_CODE}); + supported_formats_ = std::vector<mojom::BarcodeFormat>( + BarcodeDetectionImplMac::GetSupportedSymbologies()); + std::move(callback).Run(supported_formats_.value()); return; } - DLOG(ERROR) << "Platform not supported for Barcode Detection."; + DLOG(ERROR) << "Platform does not support Barcode Detection."; + supported_formats_.emplace(); std::move(callback).Run({}); }
diff --git a/services/shape_detection/barcode_detection_provider_mac_unittest.mm b/services/shape_detection/barcode_detection_provider_mac_unittest.mm index ad85660..da019e4c 100644 --- a/services/shape_detection/barcode_detection_provider_mac_unittest.mm +++ b/services/shape_detection/barcode_detection_provider_mac_unittest.mm
@@ -10,14 +10,16 @@ #include "base/bind.h" #include "base/callback_forward.h" +#include "base/mac/sdk_forward_declarations.h" #include "base/message_loop/message_loop.h" #include "base/run_loop.h" -#include "services/shape_detection/barcode_detection_impl_mac_vision.h" #include "services/shape_detection/barcode_detection_provider_mac.h" #include "services/shape_detection/public/mojom/barcodedetection_provider.mojom.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" +using ::testing::NiceMock; +using ::testing::Return; using ::testing::TestWithParam; using ::testing::ValuesIn; @@ -38,17 +40,55 @@ mojom::BarcodeFormat::EAN_8, mojom::BarcodeFormat::ITF, mojom::BarcodeFormat::PDF417, mojom::BarcodeFormat::QR_CODE, mojom::BarcodeFormat::UPC_E}; +static const std::vector<mojom::BarcodeFormat>& MockVisionSupportedFormats = { + mojom::BarcodeFormat::AZTEC, mojom::BarcodeFormat::DATA_MATRIX, + mojom::BarcodeFormat::QR_CODE}; -std::unique_ptr<mojom::BarcodeDetectionProvider> CreateBarcodeProviderMac() { - return std::make_unique<BarcodeDetectionProviderMac>(); +static NSArray* MockVisionSupportedSymbologyStrings = @[ + @"VNBarcodeSymbologyAztec", @"VNBarcodeSymbologyDataMatrix", + @"VNBarcodeSymbologyQR" +]; + +class MockVisionAPI : public VisionAPIInterface { + public: + MOCK_CONST_METHOD0(GetSupportedSymbologies, NSArray*(void)); +}; + +std::unique_ptr<mojom::BarcodeDetectionProvider> CreateBarcodeProviderMac( + std::unique_ptr<VisionAPIInterface> vision_api) { + return std::make_unique<BarcodeDetectionProviderMac>(std::move(vision_api)); } +std::unique_ptr<VisionAPIInterface> CreateNullVisionAPI() { + return nullptr; +} + +std::unique_ptr<VisionAPIInterface> CreateVisionAPI() { + return VisionAPIInterface::Create(); +} + +std::unique_ptr<VisionAPIInterface> CreateMockVisionAPI( + NSArray* returned_symbologies) { + std::unique_ptr<NiceMock<MockVisionAPI>> mock_vision_api = + std::make_unique<NiceMock<MockVisionAPI>>(); + ON_CALL(*mock_vision_api, GetSupportedSymbologies()) + .WillByDefault(Return(returned_symbologies)); + return mock_vision_api; +} + +using VisionAPIInterfaceFactory = + base::RepeatingCallback<std::unique_ptr<VisionAPIInterface>()>; + struct TestParams { const std::vector<mojom::BarcodeFormat> formats; bool test_vision_api; + VisionAPIInterfaceFactory vision_api; } kTestParams[] = { - {CISupportedFormats, false}, - {VisionSupportedFormats, true}, + {CISupportedFormats, false, base::BindRepeating(&CreateNullVisionAPI)}, + {VisionSupportedFormats, true, base::BindRepeating(&CreateVisionAPI)}, + {MockVisionSupportedFormats, true, + base::BindRepeating(&CreateMockVisionAPI, + MockVisionSupportedSymbologyStrings)}, }; } @@ -58,20 +98,10 @@ ~BarcodeDetectionProviderMacTest() override = default; void SetUp() override { - bool is_vision_available = false; - if (@available(macOS 10.13, *)) { - if (!BarcodeDetectionImplMacVision::IsBlockedMacOSVersion()) { - is_vision_available = true; - - // Only load Vision if we're testing it. - if (GetParam().test_vision_api) { - vision_framework_ = dlopen( - "/System/Library/Frameworks/Vision.framework/Vision", RTLD_LAZY); - } - } - } - valid_combination_ = is_vision_available == GetParam().test_vision_api; - provider_ = base::BindOnce(&CreateBarcodeProviderMac).Run(); + if (@available(macOS 10.13, *)) + is_vision_available_ = true; + ASSERT_EQ([MockVisionSupportedSymbologyStrings count], + MockVisionSupportedFormats.size()); } void TearDown() override { @@ -92,16 +122,24 @@ std::unique_ptr<mojom::BarcodeDetectionProvider> provider_; const base::MessageLoop message_loop_; void* vision_framework_ = nullptr; - bool valid_combination_ = false; + bool is_vision_available_ = false; }; TEST_P(BarcodeDetectionProviderMacTest, EnumerateSupportedBarcodes) { - if (!valid_combination_) { + if (is_vision_available_ != GetParam().test_vision_api) { LOG(WARNING) << "Barcode Detection for this (library, OS version) pair is " "not supported, skipping test."; return; } + // Only load Vision if we're testing it. + if (GetParam().test_vision_api) { + vision_framework_ = + dlopen("/System/Library/Frameworks/Vision.framework/Vision", RTLD_LAZY); + } + + provider_ = CreateBarcodeProviderMac(GetParam().vision_api.Run()); + base::RunLoop run_loop; base::RepeatingClosure quit_closure = run_loop.QuitClosure(); EXPECT_CALL(*this, OnEnumerateSupportedFormats()) @@ -116,4 +154,69 @@ BarcodeDetectionProviderMacTest, ValuesIn(kTestParams)); +TEST_F(BarcodeDetectionProviderMacTest, EnumerateSupportedBarcodesCached) { + if (!is_vision_available_) { + LOG(WARNING) << "Barcode Detection with Vision not supported before 10.13, " + << "skipping test."; + return; + } + + auto mock_vision_api = std::make_unique<MockVisionAPI>(); + ON_CALL(*mock_vision_api, GetSupportedSymbologies()) + .WillByDefault(Return(MockVisionSupportedSymbologyStrings)); + EXPECT_CALL(*mock_vision_api, GetSupportedSymbologies()); + + provider_ = CreateBarcodeProviderMac(std::move(mock_vision_api)); + provider_->EnumerateSupportedFormats(base::BindOnce( + &BarcodeDetectionProviderMacTest::EnumerateSupportedFormatsCallback, + base::Unretained(this), MockVisionSupportedFormats)); + provider_->EnumerateSupportedFormats(base::BindOnce( + &BarcodeDetectionProviderMacTest::EnumerateSupportedFormatsCallback, + base::Unretained(this), MockVisionSupportedFormats)); + provider_->EnumerateSupportedFormats(base::BindOnce( + &BarcodeDetectionProviderMacTest::EnumerateSupportedFormatsCallback, + base::Unretained(this), MockVisionSupportedFormats)); +} + +TEST_F(BarcodeDetectionProviderMacTest, EnumerateSupportedBarcodesUnknown) { + if (!is_vision_available_) { + LOG(WARNING) << "Barcode Detection with Vision not supported before 10.13, " + << "skipping test."; + return; + } + + NSMutableArray* mock_supported_symbologies = + [NSMutableArray arrayWithArray:MockVisionSupportedSymbologyStrings]; + [mock_supported_symbologies addObject:@"FooSymbology"]; + std::unique_ptr<VisionAPIInterface> mock_vision_api = + CreateMockVisionAPI(mock_supported_symbologies); + + provider_ = CreateBarcodeProviderMac(std::move(mock_vision_api)); + provider_->EnumerateSupportedFormats(base::BindOnce( + &BarcodeDetectionProviderMacTest::EnumerateSupportedFormatsCallback, + base::Unretained(this), MockVisionSupportedFormats)); +} + +TEST_F(BarcodeDetectionProviderMacTest, EnumerateSupportedBarcodesErrored) { + if (!is_vision_available_) { + LOG(WARNING) << "Barcode Detection with Vision not supported before 10.13, " + << "skipping test."; + return; + } + + std::unique_ptr<VisionAPIInterface> mock_vision_api = + CreateMockVisionAPI([NSArray array]); + + provider_ = CreateBarcodeProviderMac(std::move(mock_vision_api)); + provider_->EnumerateSupportedFormats(base::BindOnce( + &BarcodeDetectionProviderMacTest::EnumerateSupportedFormatsCallback, + base::Unretained(this), std::vector<mojom::BarcodeFormat>())); + provider_->EnumerateSupportedFormats(base::BindOnce( + &BarcodeDetectionProviderMacTest::EnumerateSupportedFormatsCallback, + base::Unretained(this), std::vector<mojom::BarcodeFormat>())); + provider_->EnumerateSupportedFormats(base::BindOnce( + &BarcodeDetectionProviderMacTest::EnumerateSupportedFormatsCallback, + base::Unretained(this), std::vector<mojom::BarcodeFormat>())); +} + } // shape_detection namespace
diff --git a/services/tracing/perfetto/json_trace_exporter.cc b/services/tracing/perfetto/json_trace_exporter.cc index 6e6b4af7..b1c29d5 100644 --- a/services/tracing/perfetto/json_trace_exporter.cc +++ b/services/tracing/perfetto/json_trace_exporter.cc
@@ -35,6 +35,12 @@ void JSONTraceExporter::OnTraceData(std::vector<perfetto::TracePacket> packets, bool has_more) { DCHECK(!packets.empty() || !has_more); + // Since we write each string before checking the limit, we'll + // always go slightly over and hence we reserve some extra space + // to avoid most reallocs. We do this in the callback to prevent this from + // being included in the memory dumps from tracing. + const size_t kReserveCapacity = kTraceEventBufferSizeInBytes * 5 / 4; + out_.reserve(kReserveCapacity); // TODO(eseckler): |label_filter_| seems broken for anything but // "traceEvents" (e.g. "systemTraceEvents" will output invalid JSON). @@ -213,11 +219,6 @@ JSONTraceExporter::StringBuffer::StringBuffer( JSONTraceExporter::OnTraceEventJSONCallback callback) : callback_(std::move(callback)) { - // Since we write each string before checking the limit, we'll - // always go slightly over and hence we reserve some extra space - // to avoid most reallocs. - const size_t kReserveCapacity = kTraceEventBufferSizeInBytes * 5 / 4; - out_.reserve(kReserveCapacity); } JSONTraceExporter::StringBuffer::~StringBuffer() {} @@ -251,6 +252,10 @@ return out_; } +void JSONTraceExporter::StringBuffer::reserve(size_t size) { + out_.reserve(size); +} + void JSONTraceExporter::StringBuffer::EscapeJSONAndAppend( const std::string& unescaped) { MaybeRunCallback();
diff --git a/services/tracing/perfetto/json_trace_exporter.h b/services/tracing/perfetto/json_trace_exporter.h index 2b1878b..8d5f484b 100644 --- a/services/tracing/perfetto/json_trace_exporter.h +++ b/services/tracing/perfetto/json_trace_exporter.h
@@ -81,6 +81,8 @@ std::string* mutable_out(); const std::string& out(); + void reserve(size_t size); + template <typename... Args> void AppendF(const char* format, Args&&... args) { MaybeRunCallback();
diff --git a/services/tracing/perfetto/perfetto_tracing_coordinator.cc b/services/tracing/perfetto/perfetto_tracing_coordinator.cc index 65bbd12..1f082ad 100644 --- a/services/tracing/perfetto/perfetto_tracing_coordinator.cc +++ b/services/tracing/perfetto/perfetto_tracing_coordinator.cc
@@ -286,7 +286,17 @@ void PerfettoTracingCoordinator::StartTracing(const std::string& config, StartTracingCallback callback) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - parsed_config_ = base::trace_event::TraceConfig(config); + base::trace_event::TraceConfig new_parsed_config(config); + bool waiting_for_tracing_start = !start_tracing_callback_.is_null(); + bool configs_are_identical = + (new_parsed_config.ToString() == parsed_config_.ToString()); + if (waiting_for_tracing_start || + (tracing_session_ && configs_are_identical)) { + std::move(callback).Run(configs_are_identical); + return; + } + + parsed_config_ = new_parsed_config; if (!tracing_session_) { tracing_session_ = std::make_unique<TracingSession>( parsed_config_,
diff --git a/services/tracing/public/cpp/base_agent.cc b/services/tracing/public/cpp/base_agent.cc index 116a8f0..661aac6 100644 --- a/services/tracing/public/cpp/base_agent.cc +++ b/services/tracing/public/cpp/base_agent.cc
@@ -7,6 +7,7 @@ #include <utility> #include "base/bind.h" +#include "base/trace_event/trace_log.h" #include "services/tracing/public/cpp/traced_process_impl.h" #include "services/tracing/public/mojom/constants.mojom.h" @@ -36,6 +37,13 @@ void BaseAgent::Disconnect() { binding_.Close(); + + // If we get disconnected it means the tracing service went down, most likely + // due to the process dying. In that case, stop any tracing in progress. + if (base::trace_event::TraceLog::GetInstance()->IsEnabled()) { + base::trace_event::TraceLog::GetInstance()->CancelTracing( + base::trace_event::TraceLog::OutputCallback()); + } } void BaseAgent::StartTracing(const std::string& config,
diff --git a/services/ws/client_root.cc b/services/ws/client_root.cc index aa31543..e4ef559 100644 --- a/services/ws/client_root.cc +++ b/services/ws/client_root.cc
@@ -14,6 +14,7 @@ #include "services/ws/client_change_tracker.h" #include "services/ws/common/switches.h" #include "services/ws/proxy_window.h" +#include "services/ws/top_level_proxy_window.h" #include "services/ws/window_service.h" #include "services/ws/window_tree.h" #include "ui/aura/env.h" @@ -94,6 +95,9 @@ } ClientRoot::~ClientRoot() { + if (force_visible_) + force_visible_->OnClientRootDestroyed(); + ProxyWindow* proxy_window = ProxyWindow::GetMayBeNull(window_); window_->RemoveObserver(this); if (window_->GetHost()) @@ -123,6 +127,11 @@ UpdateLocalSurfaceIdAndClientSurfaceEmbedder(); } +void ClientRoot::OnForceVisibleDestroyed() { + force_visible_ = nullptr; + NotifyClientOfVisibilityChange(); +} + void ClientRoot::GenerateLocalSurfaceIdIfNecessary() { if (!ShouldAssignLocalSurfaceId()) return; @@ -268,6 +277,17 @@ window_->GetHost()->GetDisplayId()); } +std::unique_ptr<ScopedForceVisible> ClientRoot::ForceWindowVisible() { + // At this time there is only a need for a single force visible. + DCHECK(!force_visible_); + // Use WrapUnique() as constructor is private. + std::unique_ptr<ScopedForceVisible> force_visible = + base::WrapUnique(new ScopedForceVisible(this)); + force_visible_ = force_visible.get(); + NotifyClientOfVisibilityChange(); + return force_visible; +} + void ClientRoot::UpdateLocalSurfaceIdAndClientSurfaceEmbedder() { GenerateLocalSurfaceIdIfNecessary(); ProxyWindow* proxy_window = ProxyWindow::GetMayBeNull(window_); @@ -312,8 +332,9 @@ ProxyWindow::GetMayBeNull(window_)->local_surface_id_allocation()); } -void ClientRoot::NotifyClientOfVisibilityChange(bool new_value) { - if (is_top_level_ || last_visible_ == new_value) +void ClientRoot::NotifyClientOfVisibilityChange(base::Optional<bool> visible) { + const bool new_value = visible.has_value() ? *visible : IsWindowVisible(); + if (last_visible_ == new_value) return; last_visible_ = new_value; @@ -331,6 +352,13 @@ NotifyClientOfNewBounds(); } +bool ClientRoot::IsWindowVisible() { + if (force_visible_) + return true; + + return is_top_level_ ? window_->TargetVisibility() : window_->IsVisible(); +} + void ClientRoot::OnWindowPropertyChanged(aura::Window* window, const void* key, intptr_t old) { @@ -385,7 +413,7 @@ else CheckForScaleFactorChange(); - NotifyClientOfVisibilityChange(window_->IsVisible()); + NotifyClientOfVisibilityChange(); } void ClientRoot::OnWindowRemovingFromRootWindow(aura::Window* window, @@ -413,11 +441,7 @@ } void ClientRoot::OnWindowVisibilityChanged(aura::Window* window, bool visible) { - if (!is_top_level_ && - !window_tree_->property_change_tracker_->IsProcessingChangeForWindow( - window, ClientChangeType::kVisibility)) { - NotifyClientOfVisibilityChange(window_->IsVisible()); - } + NotifyClientOfVisibilityChange(); } void ClientRoot::OnHostResized(aura::WindowTreeHost* host) {
diff --git a/services/ws/client_root.h b/services/ws/client_root.h index d7d834b..afbaf99 100644 --- a/services/ws/client_root.h +++ b/services/ws/client_root.h
@@ -35,6 +35,7 @@ namespace ws { class ProxyWindow; +class ScopedForceVisible; class WindowTree; // WindowTree creates a ClientRoot for each window the client is embedded in. A @@ -90,8 +91,14 @@ // Called when the display id changes. void NotifyClientOfDisplayIdChange(); + // See TopLevelProxyWindow::ForceWindowVisible() for details. + std::unique_ptr<ScopedForceVisible> ForceWindowVisible(); + private: friend class ClientRootTestHelper; + friend class ScopedForceVisible; + + void OnForceVisibleDestroyed(); // If necessary, this generates a new LocalSurfaceId. Generally you should // call UpdateLocalSurfaceIdAndClientSurfaceEmbedder(), not this. If you call @@ -114,14 +121,18 @@ void NotifyClientOfNewBounds(); - // If necessary, notifies the client that the visibility of the Window is - // |new_value|. This does nothing for top-levels. - void NotifyClientOfVisibilityChange(bool new_value); + // If necessary, notifies the client that the visibility changes. If |visible| + // has a value, it is used as the visibility, otherwise IsWindowVisible() is + // used. + void NotifyClientOfVisibilityChange( + base::Optional<bool> visible = base::nullopt); // Callback when the position of |window_|, relative to the root, changes. // This is *only* called for non-top-levels. void OnPositionInRootChanged(); + bool IsWindowVisible(); + // aura::WindowObserver: void OnWindowPropertyChanged(aura::Window* window, const void* key, @@ -187,6 +198,10 @@ base::Optional<viz::ParentLocalSurfaceIdAllocator> parent_local_surface_id_allocator_; + // If non-null the client is told the window is visible, regardless of + // whether the window is actually visible. + ScopedForceVisible* force_visible_ = nullptr; + DISALLOW_COPY_AND_ASSIGN(ClientRoot); };
diff --git a/services/ws/client_root_test_helper.cc b/services/ws/client_root_test_helper.cc index 7e660b0..20963b7 100644 --- a/services/ws/client_root_test_helper.cc +++ b/services/ws/client_root_test_helper.cc
@@ -17,4 +17,8 @@ return client_root_->client_surface_embedder_.get(); } +bool ClientRootTestHelper::IsWindowForcedVisible() { + return client_root_->force_visible_ != nullptr; +} + } // namespace ws
diff --git a/services/ws/client_root_test_helper.h b/services/ws/client_root_test_helper.h index c09abdf..250d099 100644 --- a/services/ws/client_root_test_helper.h +++ b/services/ws/client_root_test_helper.h
@@ -24,6 +24,8 @@ aura::ClientSurfaceEmbedder* GetClientSurfaceEmbedder(); + bool IsWindowForcedVisible(); + private: ClientRoot* client_root_;
diff --git a/services/ws/client_root_unittest.cc b/services/ws/client_root_unittest.cc index c5cd882..ac35881 100644 --- a/services/ws/client_root_unittest.cc +++ b/services/ws/client_root_unittest.cc
@@ -9,6 +9,7 @@ #include "services/ws/public/cpp/property_type_converters.h" #include "services/ws/public/mojom/window_manager.mojom.h" +#include "services/ws/top_level_proxy_window.h" #include "services/ws/window_service.h" #include "services/ws/window_service_test_setup.h" #include "services/ws/window_tree_test_helper.h" @@ -55,7 +56,7 @@ // Verifies a property change that occurs while servicing a property change from // the client results in notifying the client of the new property. -TEST(ClientRoot, CascadingPropertyChange) { +TEST(ClientRootTest, CascadingPropertyChange) { WindowServiceTestSetup setup; aura::Window* top_level = setup.window_tree_test_helper()->NewTopLevelWindow(); @@ -89,7 +90,7 @@ } // Verifies embedded clients are notified of changes in screen bounds. -TEST(ClientRoot, EmbedBoundsInScreen) { +TEST(ClientRootTest, EmbedBoundsInScreen) { WindowServiceTestSetup setup; aura::Window* embed_window = setup.window_tree_test_helper()->NewWindow(); embed_window->SetBounds(gfx::Rect(1, 2, 3, 4)); @@ -123,7 +124,7 @@ EXPECT_EQ(gfx::Rect(112, 64, 3, 4), iter->bounds); } -TEST(ClientRoot, EmbedWindowServerVisibilityChanges) { +TEST(ClientRootTest, EmbedWindowServerVisibilityChanges) { WindowServiceTestSetup setup; aura::Window* embed_window = setup.window_tree_test_helper()->NewWindow(); embed_window->SetBounds(gfx::Rect(1, 2, 3, 4)); @@ -222,7 +223,7 @@ } } -TEST(ClientRoot, EmbedWindowClientVisibilityChanges) { +TEST(ClientRootTest, EmbedWindowClientVisibilityChanges) { WindowServiceTestSetup setup; aura::Window* embed_window = setup.window_tree_test_helper()->NewWindow(); embed_window->SetBounds(gfx::Rect(1, 2, 3, 4)); @@ -249,7 +250,31 @@ EXPECT_TRUE(embedding_changes->empty()); } -TEST(ClientRoot, TransformShouldntAffectBounds) { +TEST(ClientRootTest, ForceVisible) { + WindowServiceTestSetup setup; + aura::Window* window = setup.window_tree_test_helper()->NewTopLevelWindow(); + setup.changes()->clear(); + EXPECT_FALSE(window->IsVisible()); + + { + // Verify calling ForceWindowVisible() results in notifying the client the + // window is visible (even though the underlying aura::Window is not). + auto force = setup.window_tree() + ->GetClientRootForWindow(window) + ->ForceWindowVisible(); + EXPECT_FALSE(window->IsVisible()); + EXPECT_EQ("VisibilityChanged window=0,1 visible=true", + SingleChangeToDescription(*setup.changes())); + setup.changes()->clear(); + } + + // Destroying |force| should notify the client the window is hidden. + EXPECT_FALSE(window->IsVisible()); + EXPECT_EQ("VisibilityChanged window=0,1 visible=false", + SingleChangeToDescription(*setup.changes())); +} + +TEST(ClientRootTest, TransformShouldntAffectBounds) { WindowServiceTestSetup setup; aura::Window* top_level = setup.window_tree_test_helper()->NewTopLevelWindow();
diff --git a/services/ws/proxy_window.h b/services/ws/proxy_window.h index d08ca5b..4fcfc40 100644 --- a/services/ws/proxy_window.h +++ b/services/ws/proxy_window.h
@@ -144,6 +144,9 @@ std::unique_ptr<DragDropDelegate> drag_drop_delegate); void SetTopLevelProxyWindow(std::unique_ptr<TopLevelProxyWindowImpl> window); + TopLevelProxyWindowImpl* top_level_proxy_window() { + return top_level_proxy_window_.get(); + } // Returns an id useful for debugging. This returns the id from the client // that created the window, otherwise |frame_sink_id_|.
diff --git a/services/ws/public/mojom/window_tree.mojom b/services/ws/public/mojom/window_tree.mojom index 21ab60d..18412a94 100644 --- a/services/ws/public/mojom/window_tree.mojom +++ b/services/ws/public/mojom/window_tree.mojom
@@ -554,9 +554,6 @@ // Invoked when the visibility of the specified window changes. OnWindowVisibilityChanged(uint64 window, bool visible); - // Invoked when the opacity of the specified window has changed. - OnWindowOpacityChanged(uint64 window, float new_opacity); - // Invoked when the window moves to a new display. This is only called on // a top-level window or an embedded root. OnWindowDisplayChanged(uint64 window, int64 display_id);
diff --git a/services/ws/test_change_tracker.cc b/services/ws/test_change_tracker.cc index 7d2a9564..74b7b9b 100644 --- a/services/ws/test_change_tracker.cc +++ b/services/ws/test_change_tracker.cc
@@ -189,10 +189,6 @@ change.change_id, WindowIdToString(change.window_id).c_str(), change.bool_value ? "true" : "false"); - case CHANGE_TYPE_OPACITY: - return base::StringPrintf("OpacityChanged window_id=%s opacity=%.2f", - WindowIdToString(change.window_id).c_str(), - change.float_value); case CHANGE_TYPE_REQUEST_CLOSE: return "RequestClose"; case CHANGE_TYPE_TRANSFORM_CHANGED: @@ -461,14 +457,6 @@ AddChange(change); } -void TestChangeTracker::OnWindowOpacityChanged(Id window_id, float opacity) { - Change change; - change.type = CHANGE_TYPE_OPACITY; - change.window_id = window_id; - change.float_value = opacity; - AddChange(change); -} - void TestChangeTracker::OnWindowDisplayChanged(Id window_id, int64_t display_id) { Change change;
diff --git a/services/ws/test_change_tracker.h b/services/ws/test_change_tracker.h index 80736184d..6a512b8 100644 --- a/services/ws/test_change_tracker.h +++ b/services/ws/test_change_tracker.h
@@ -44,7 +44,6 @@ CHANGE_TYPE_CURSOR_CHANGED, CHANGE_TYPE_ON_CHANGE_COMPLETED, CHANGE_TYPE_ON_TOP_LEVEL_CREATED, - CHANGE_TYPE_OPACITY, CHANGE_TYPE_REQUEST_CLOSE, CHANGE_TYPE_TRANSFORM_CHANGED, CHANGE_TYPE_DISPLAY_CHANGED, @@ -98,7 +97,6 @@ std::string embed_url; mojom::OrderDirection direction; bool bool_value = false; - float float_value = 0.f; std::string property_key; std::string property_value; ui::CursorType cursor_type = ui::CursorType::kNull; @@ -204,7 +202,6 @@ mojom::OrderDirection direction); void OnWindowDeleted(Id window_id); void OnWindowVisibilityChanged(Id window_id, bool visible); - void OnWindowOpacityChanged(Id window_id, float opacity); void OnWindowDisplayChanged(Id window_id, int64_t display_id); void OnWindowParentDrawnStateChanged(Id window_id, bool drawn); void OnWindowInputEvent(Id window_id,
diff --git a/services/ws/test_window_tree_client.cc b/services/ws/test_window_tree_client.cc index 28befd27..06caae4f 100644 --- a/services/ws/test_window_tree_client.cc +++ b/services/ws/test_window_tree_client.cc
@@ -174,11 +174,6 @@ tracker_.OnWindowVisibilityChanged(window, visible); } -void TestWindowTreeClient::OnWindowOpacityChanged(Id window, - float new_opacity) { - tracker_.OnWindowOpacityChanged(window, new_opacity); -} - void TestWindowTreeClient::OnWindowDisplayChanged(Id window_id, int64_t display_id) { tracker_.OnWindowDisplayChanged(window_id, display_id);
diff --git a/services/ws/test_window_tree_client.h b/services/ws/test_window_tree_client.h index 5ef7386..9065d74 100644 --- a/services/ws/test_window_tree_client.h +++ b/services/ws/test_window_tree_client.h
@@ -127,8 +127,6 @@ mojom::OrderDirection direction) override; void OnWindowDeleted(Id window) override; void OnWindowVisibilityChanged(Id window, bool visible) override; - void OnWindowOpacityChanged(Id window, - float new_opacity) override; void OnWindowDisplayChanged(Id window_id, int64_t display_id) override; void OnWindowParentDrawnStateChanged(Id window, bool drawn) override; void OnWindowInputEvent(uint32_t event_id,
diff --git a/services/ws/top_level_proxy_window.h b/services/ws/top_level_proxy_window.h index 3f00107..695760ae 100644 --- a/services/ws/top_level_proxy_window.h +++ b/services/ws/top_level_proxy_window.h
@@ -5,11 +5,17 @@ #ifndef SERVICES_WS_TOP_LEVEL_PROXY_WINDOW_H_ #define SERVICES_WS_TOP_LEVEL_PROXY_WINDOW_H_ +#include <memory> + #include "base/component_export.h" #include "base/macros.h" +#include "ui/aura/window_tracker.h" namespace ws { +class ClientRoot; +class ScopedForceVisible; + // Interface exposed to clients to interact with top-level windows. This is // indirectly owned by the aura::Window the TopLevelProxyWindow is associated // with. @@ -21,10 +27,31 @@ virtual void OnWindowResizeLoopEnded() = 0; virtual void RequestClose() = 0; + // Forces the client to think the window is visible while the return value is + // valid. + virtual std::unique_ptr<ScopedForceVisible> ForceVisible() = 0; + protected: virtual ~TopLevelProxyWindow() {} }; +// See ForceVisible for details. +class COMPONENT_EXPORT(WINDOW_SERVICE) ScopedForceVisible { + public: + ~ScopedForceVisible(); + + private: + friend class ClientRoot; + + explicit ScopedForceVisible(ClientRoot* client_root); + + void OnClientRootDestroyed(); + + ClientRoot* client_root_; + + DISALLOW_COPY_AND_ASSIGN(ScopedForceVisible); +}; + } // namespace ws #endif // SERVICES_WS_TOP_LEVEL_PROXY_WINDOW_H_
diff --git a/services/ws/top_level_proxy_window_impl.cc b/services/ws/top_level_proxy_window_impl.cc index 55d6559..f43e853 100644 --- a/services/ws/top_level_proxy_window_impl.cc +++ b/services/ws/top_level_proxy_window_impl.cc
@@ -4,6 +4,7 @@ #include "services/ws/top_level_proxy_window_impl.h" +#include "services/ws/client_root.h" #include "services/ws/public/mojom/window_tree.mojom.h" namespace ws { @@ -28,4 +29,20 @@ window_tree_client_->RequestClose(window_transport_id_); } +std::unique_ptr<ScopedForceVisible> TopLevelProxyWindowImpl::ForceVisible() { + return client_root_->ForceWindowVisible(); +} + +ScopedForceVisible::~ScopedForceVisible() { + if (client_root_) + client_root_->OnForceVisibleDestroyed(); +} + +ScopedForceVisible::ScopedForceVisible(ClientRoot* client_root) + : client_root_(client_root) {} + +void ScopedForceVisible::OnClientRootDestroyed() { + client_root_ = nullptr; +} + } // namespace ws
diff --git a/services/ws/top_level_proxy_window_impl.h b/services/ws/top_level_proxy_window_impl.h index 0bc4b559..a1b4ff69 100644 --- a/services/ws/top_level_proxy_window_impl.h +++ b/services/ws/top_level_proxy_window_impl.h
@@ -5,10 +5,15 @@ #ifndef SERVICES_WS_TOP_LEVEL_PROXY_WINDOW_IMPL_H_ #define SERVICES_WS_TOP_LEVEL_PROXY_WINDOW_IMPL_H_ +#include <memory> + #include "services/ws/common/types.h" #include "services/ws/top_level_proxy_window.h" namespace ws { + +class ClientRoot; + namespace mojom { class WindowTreeClient; } @@ -21,14 +26,18 @@ Id window_transport_id); ~TopLevelProxyWindowImpl() override; + void set_client_root(ClientRoot* client_root) { client_root_ = client_root; } + // TopLevelProxyWindowImpl: void OnWindowResizeLoopStarted() override; void OnWindowResizeLoopEnded() override; void RequestClose() override; + std::unique_ptr<ScopedForceVisible> ForceVisible() override; private: mojom::WindowTreeClient* window_tree_client_; const Id window_transport_id_; + ClientRoot* client_root_ = nullptr; DISALLOW_COPY_AND_ASSIGN(TopLevelProxyWindowImpl); };
diff --git a/services/ws/window_tree.cc b/services/ws/window_tree.cc index 63582717..2ffeef6 100644 --- a/services/ws/window_tree.cc +++ b/services/ws/window_tree.cc
@@ -1466,7 +1466,9 @@ void WindowTree::OnWindowVisibilityChanging(aura::Window* window, bool visible) { - if (property_change_tracker_->IsProcessingChangeForWindow( + // Visibility changes for top-levels are handled by ClientRoot. + if (IsTopLevel(window) || + property_change_tracker_->IsProcessingChangeForWindow( window, ClientChangeType::kVisibility)) { return; } @@ -1566,7 +1568,9 @@ // This passes null for the mojom::WindowTreePtr because the client has // already been given the mojom::WindowTreePtr that is backed by this // WindowTree. - CreateClientRoot(top_level, is_top_level)->RegisterVizEmbeddingSupport(); + ClientRoot* client_root = CreateClientRoot(top_level, is_top_level); + client_root->RegisterVizEmbeddingSupport(); + proxy_window->top_level_proxy_window()->set_client_root(client_root); // Creating the ClientRoot should trigger setting a LocalSurfaceIdAllocation. DCHECK(proxy_window->local_surface_id_allocation()); window_tree_client_->OnTopLevelCreated(
diff --git a/services/ws/window_tree_client_unittest.cc b/services/ws/window_tree_client_unittest.cc index 05159cf..f26bb68 100644 --- a/services/ws/window_tree_client_unittest.cc +++ b/services/ws/window_tree_client_unittest.cc
@@ -363,10 +363,6 @@ void OnWindowVisibilityChanged(Id window, bool visible) override { tracker()->OnWindowVisibilityChanged(window, visible); } - void OnWindowOpacityChanged(Id window, - float new_opacity) override { - tracker()->OnWindowOpacityChanged(window, new_opacity); - } void OnWindowParentDrawnStateChanged(Id window, bool drawn) override { tracker()->OnWindowParentDrawnStateChanged(window, drawn); }
diff --git a/testing/buildbot/chromium.android.json b/testing/buildbot/chromium.android.json index 5d31a8f..0e81db4 100644 --- a/testing/buildbot/chromium.android.json +++ b/testing/buildbot/chromium.android.json
@@ -17534,14 +17534,52 @@ "android-cronet-asan-arm-rel": { "additional_compile_targets": [ "cronet_package", - "cronet_perf_test_apk", - "cronet_sample_test_apk", - "cronet_smoketests_missing_native_library_instrumentation_apk", - "cronet_smoketests_platform_only_instrumentation_apk", - "cronet_test_instrumentation_apk", - "cronet_tests_android", - "cronet_unittests_android", - "net_unittests" + "cronet_perf_test_apk" + ], + "gtest_tests": [ + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "cronet_sample_test_apk" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "cronet_smoketests_missing_native_library_instrumentation_apk" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "cronet_smoketests_platform_only_instrumentation_apk" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "cronet_test_instrumentation_apk" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "cronet_tests_android" + }, + { + "swarming": { + "can_use_on_swarming_builders": true + }, + "test": "cronet_unittests_android" + }, + { + "swarming": { + "can_use_on_swarming_builders": true, + "shards": 4 + }, + "test": "net_unittests" + } ] }, "android-cronet-kitkat-arm-rel": {
diff --git a/testing/buildbot/chromium.gpu.fyi.json b/testing/buildbot/chromium.gpu.fyi.json index 0ae6dccb..46e778a 100644 --- a/testing/buildbot/chromium.gpu.fyi.json +++ b/testing/buildbot/chromium.gpu.fyi.json
@@ -21920,7 +21920,8 @@ { "args": [ "--use-gpu-in-tests", - "--test-launcher-retry-limit=0" + "--test-launcher-retry-limit=0", + "--gtest_filter=-TextureFunctionTest.NonConstantOffset" ], "should_retry_with_patch": false, "swarming": {
diff --git a/testing/buildbot/chromium.gpu.json b/testing/buildbot/chromium.gpu.json index 53edb0da..490524c 100644 --- a/testing/buildbot/chromium.gpu.json +++ b/testing/buildbot/chromium.gpu.json
@@ -2665,7 +2665,8 @@ { "args": [ "--use-gpu-in-tests", - "--test-launcher-retry-limit=0" + "--test-launcher-retry-limit=0", + "--gtest_filter=-TextureFunctionTest.NonConstantOffset" ], "should_retry_with_patch": false, "swarming": {
diff --git a/testing/buildbot/chromium.perf.json b/testing/buildbot/chromium.perf.json index 61ab4319..6c50e14 100644 --- a/testing/buildbot/chromium.perf.json +++ b/testing/buildbot/chromium.perf.json
@@ -1389,7 +1389,6 @@ "-v", "--browser=release", "--upload-results", - "--run-ref-build", "--test-shard-map-filename=mac-10_12_laptop_low_end-perf_map.json", "--assert-gpu-compositing" ], @@ -1619,7 +1618,6 @@ "-v", "--browser=release", "--upload-results", - "--run-ref-build", "--test-shard-map-filename=mac-10_13_laptop_high_end-perf_map.json", "--assert-gpu-compositing" ],
diff --git a/testing/buildbot/test_suite_exceptions.pyl b/testing/buildbot/test_suite_exceptions.pyl index 82a1f4b..c6d6650 100644 --- a/testing/buildbot/test_suite_exceptions.pyl +++ b/testing/buildbot/test_suite_exceptions.pyl
@@ -55,6 +55,18 @@ 'shards': 10, }, }, + 'Win7 FYI Debug (AMD)': { + 'args': [ + # TODO(https://crbug.com/943140): Debug, reenable. + '--gtest_filter=-TextureFunctionTest.NonConstantOffset', + ], + }, + 'Win10 Debug (NVIDIA)': { + 'args': [ + # TODO(https://crbug.com/943140): Debug, reenable. + '--gtest_filter=-TextureFunctionTest.NonConstantOffset', + ], + }, }, }, 'angle_white_box_tests': {
diff --git a/testing/buildbot/waterfalls.pyl b/testing/buildbot/waterfalls.pyl index 4087e13..b74dda2 100644 --- a/testing/buildbot/waterfalls.pyl +++ b/testing/buildbot/waterfalls.pyl
@@ -389,19 +389,13 @@ ], }, 'android-cronet-asan-arm-rel': { - # TODO(jbudorick): Run tests on this on swarming after - # implementing a reasonable mechanism for doing so w/ asan. 'additional_compile_targets': [ 'cronet_package', 'cronet_perf_test_apk', - 'cronet_sample_test_apk', - 'cronet_smoketests_missing_native_library_instrumentation_apk', - 'cronet_smoketests_platform_only_instrumentation_apk', - 'cronet_test_instrumentation_apk', - 'cronet_tests_android', - 'cronet_unittests_android', - 'net_unittests', ], + 'test_suites': { + 'gtest_tests': 'cronet_gtests', + }, }, 'android-cronet-kitkat-arm-rel': { 'test_suites': {
diff --git a/testing/variations/fieldtrial_testing_config.json b/testing/variations/fieldtrial_testing_config.json index 71a1eb8..ce4bc15 100644 --- a/testing/variations/fieldtrial_testing_config.json +++ b/testing/variations/fieldtrial_testing_config.json
@@ -471,6 +471,21 @@ ] } ], + "AndroidSurfaceControl": [ + { + "platforms": [ + "android" + ], + "experiments": [ + { + "name": "EnableAndroidSurfaceControl", + "enable_features": [ + "AndroidSurfaceControl" + ] + } + ] + } + ], "AppLauncherRefresh": [ { "platforms": [ @@ -650,6 +665,24 @@ ] } ], + "AutofillEnableLocalCardMigrationForNonSyncUser": [ + { + "platforms": [ + "chromeos", + "linux", + "mac", + "windows" + ], + "experiments": [ + { + "name": "Enabled", + "enable_features": [ + "AutofillEnableLocalCardMigrationForNonSyncUser" + ] + } + ] + } + ], "AutofillFieldMetadata": [ { "platforms": [ @@ -1970,18 +2003,6 @@ ] } ], - "ExtensionDeveloperModeWarning": [ - { - "platforms": [ - "mac" - ], - "experiments": [ - { - "name": "Enabled" - } - ] - } - ], "ExtensionInstallVerification": [ { "platforms": [ @@ -2497,6 +2518,12 @@ ], "experiments": [ { + "name": "Control", + "disable_features": [ + "InterestFeedContentSuggestions" + ] + }, + { "name": "Enabled", "enable_features": [ "InterestFeedContentSuggestions" @@ -4469,6 +4496,25 @@ ] } ], + "ScheduledScriptStreaming": [ + { + "platforms": [ + "android", + "chromeos", + "linux", + "mac", + "windows" + ], + "experiments": [ + { + "name": "ScheduledScriptStreaming", + "enable_features": [ + "ScheduledScriptStreaming" + ] + } + ] + } + ], "SearchEnginePromo": [ { "platforms": [
diff --git a/third_party/blink/common/BUILD.gn b/third_party/blink/common/BUILD.gn index 18f30a8..e25bd4b 100644 --- a/third_party/blink/common/BUILD.gn +++ b/third_party/blink/common/BUILD.gn
@@ -26,7 +26,6 @@ "client_hints/client_hints.cc", "device_memory/approximated_device_memory.cc", "dom_storage/session_storage_namespace_id.cc", - "download/download_stats.cc", "experiments/memory_ablation_experiment.cc", "feature_policy/feature_policy.cc", "feature_policy/policy_value.cc",
diff --git a/third_party/blink/common/download/download_stats.cc b/third_party/blink/common/download/download_stats.cc deleted file mode 100644 index 9db43e7..0000000 --- a/third_party/blink/common/download/download_stats.cc +++ /dev/null
@@ -1,63 +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 "third_party/blink/public/common/download/download_stats.h" - -#include "base/metrics/histogram_macros.h" -#include "services/metrics/public/cpp/ukm_builders.h" - -namespace blink { - -unsigned DownloadStats::MainFrameDownloadFlags::ToUmaValue() const { - unsigned value = 0; - if (has_sandbox) - value |= kMainFrameSandboxBit; - if (has_gesture) - value |= kMainFrameGestureBit; - return value; -} - -unsigned DownloadStats::SubframeDownloadFlags::ToUmaValue() const { - unsigned value = 0; - if (has_sandbox) - value |= kSubframeSandboxBit; - if (is_cross_origin) - value |= kSubframeCrossOriginBit; - if (is_ad_frame) - value |= kSubframeAdBit; - if (has_gesture) - value |= kSubframeGestureBit; - return value; -} - -void DownloadStats::RecordMainFrameDownloadFlags( - const MainFrameDownloadFlags& flags, - ukm::SourceId source_id, - ukm::UkmRecorder* ukm_recorder) { - UMA_HISTOGRAM_ENUMERATION("Download.MainFrame.SandboxGesture", - flags.ToUmaValue(), kCountSandboxGesture); - - ukm::builders::MainFrameDownload(source_id) - .SetHasSandbox(flags.has_sandbox) - .SetHasGesture(flags.has_gesture) - .Record(ukm_recorder); -} - -// static -void DownloadStats::RecordSubframeDownloadFlags( - const SubframeDownloadFlags& flags, - ukm::SourceId source_id, - ukm::UkmRecorder* ukm_recorder) { - UMA_HISTOGRAM_ENUMERATION("Download.Subframe.SandboxOriginAdGesture", - flags.ToUmaValue(), kCountSandboxOriginAdGesture); - - ukm::builders::SubframeDownload(source_id) - .SetHasSandbox(flags.has_sandbox) - .SetIsCrossOrigin(flags.is_cross_origin) - .SetIsAdFrame(flags.is_ad_frame) - .SetHasGesture(flags.has_gesture) - .Record(ukm_recorder); -} - -} // namespace blink
diff --git a/third_party/blink/common/origin_policy/origin_policy_parser.cc b/third_party/blink/common/origin_policy/origin_policy_parser.cc index 8c03c232..679dd22 100644 --- a/third_party/blink/common/origin_policy/origin_policy_parser.cc +++ b/third_party/blink/common/origin_policy/origin_policy_parser.cc
@@ -8,6 +8,8 @@ #include "base/logging.h" #include "base/memory/ptr_util.h" #include "base/values.h" +#include "url/gurl.h" +#include "url/origin.h" namespace blink { @@ -39,7 +41,11 @@ base::Value* features = json->FindKey("feature-policy"); bool features_ok = !features || ParseFeaturePolicies(*features); - return csp_ok && features_ok; + base::Value* first_party_set = json->FindKey("first-party-set"); + bool first_party_set_ok = + !first_party_set || ParseFirstPartySet(*first_party_set); + + return csp_ok && features_ok && first_party_set_ok; } bool OriginPolicyParser::ParseContentSecurityPolicies( @@ -88,4 +94,34 @@ return true; } +// This will not fail policy parsing, even if the first party set field can't +// be parsed. Therefore this function always returns true. +bool OriginPolicyParser::ParseFirstPartySet( + const base::Value& first_party_set) { + if (!first_party_set.is_list()) + return true; + + for (const auto& first_party : first_party_set.GetList()) { + if (!ParseFirstPartyOrigin(first_party)) { + policy_->first_party_set_.clear(); + return true; + } + } + + return true; +} + +bool OriginPolicyParser::ParseFirstPartyOrigin(const base::Value& first_party) { + if (!first_party.is_string()) + return false; + + GURL first_party_url(first_party.GetString()); + + if (!first_party_url.is_valid() || first_party_url.is_empty()) + return false; + + policy_->first_party_set_.insert(url::Origin::Create(first_party_url)); + return true; +} + } // namespace blink
diff --git a/third_party/blink/common/origin_policy/origin_policy_parser.h b/third_party/blink/common/origin_policy/origin_policy_parser.h index 5deb3bc..2e035424 100644 --- a/third_party/blink/common/origin_policy/origin_policy_parser.h +++ b/third_party/blink/common/origin_policy/origin_policy_parser.h
@@ -31,6 +31,8 @@ bool ParseContentSecurityPolicy(const base::Value&); bool ParseFeaturePolicies(const base::Value&); bool ParseFeaturePolicy(const base::Value&); + bool ParseFirstPartySet(const base::Value&); + bool ParseFirstPartyOrigin(const base::Value&); std::unique_ptr<OriginPolicy> policy_;
diff --git a/third_party/blink/common/origin_policy/origin_policy_unittest.cc b/third_party/blink/common/origin_policy/origin_policy_unittest.cc index 13f8dbc..a27115a7 100644 --- a/third_party/blink/common/origin_policy/origin_policy_unittest.cc +++ b/third_party/blink/common/origin_policy/origin_policy_unittest.cc
@@ -5,6 +5,7 @@ #include "third_party/blink/public/common/origin_policy/origin_policy.h" #include "testing/gtest/include/gtest/gtest.h" +#include "url/gurl.h" // Unit tests for OriginPolicy / OriginPolicyParser. // @@ -172,3 +173,144 @@ // TODO: Determine what to do with this case ! ASSERT_EQ(1U, policy->GetFeaturePolicies().size()); } + +TEST(OriginPolicy, FirstPartySetSimpleValid) { + auto policy = blink::OriginPolicy::From(R"( + { "first-party-set": ["https://example.com/", "https://not-example.com/"] } )"); + + ASSERT_TRUE(policy); + ASSERT_EQ(2U, policy->GetFirstPartySet().size()); + ASSERT_EQ(1U, policy->GetFirstPartySet().count( + url::Origin::Create(GURL("https://example.com/")))); + ASSERT_EQ(1U, policy->GetFirstPartySet().count( + url::Origin::Create(GURL("https://not-example.com/")))); +} + +TEST(OriginPolicy, FirstPartySetInvalidUrl) { + auto policy = blink::OriginPolicy::From(R"( + { "first-party-set": ["https://example.com/", "what even is this"] } )"); + + ASSERT_TRUE(policy); + ASSERT_EQ(0U, policy->GetFirstPartySet().size()); +} + +TEST(OriginPolicy, FirstPartySetEmptyList) { + auto policy = blink::OriginPolicy::From(R"( + { "first-party-set": [ ] } )"); + + ASSERT_TRUE(policy); + ASSERT_EQ(0U, policy->GetFirstPartySet().size()); +} + +TEST(OriginPolicy, FirstPartySetWithPath) { + auto policy = blink::OriginPolicy::From(R"( + { "first-party-set": ["https://example.com/some-path"] } )"); + + ASSERT_TRUE(policy); + ASSERT_EQ(1U, policy->GetFirstPartySet().size()); + ASSERT_EQ(1U, policy->GetFirstPartySet().count( + url::Origin::Create(GURL("https://example.com/")))); +} + +TEST(OriginPolicy, FirstPartySetWithPort) { + auto policy = blink::OriginPolicy::From(R"( + { "first-party-set": ["https://example.com:1000/", "https://not-example.com/"] } )"); + + ASSERT_TRUE(policy); + ASSERT_EQ(2U, policy->GetFirstPartySet().size()); + ASSERT_EQ(1U, policy->GetFirstPartySet().count( + url::Origin::Create(GURL("https://example.com:1000/")))); + ASSERT_EQ(1U, policy->GetFirstPartySet().count( + url::Origin::Create(GURL("https://not-example.com/")))); +} + +TEST(OriginPolicy, FirstPartySetMissingScheme) { + auto policy = blink::OriginPolicy::From(R"( + { "first-party-set": ["example.com/"] } )"); + + ASSERT_TRUE(policy); + ASSERT_EQ(0U, policy->GetFirstPartySet().size()); +} + +// Since we use json_parser, and it has the `KEEP_LAST_OF_DUPES` behaviour when +// parsing, the last "first-party-set" is the "true" one. +// TODO(andypaicu): figure out if this is fine, or if it needs to change +TEST(OriginPolicy, FirstPartySetMultipleLists) { + auto policy = blink::OriginPolicy::From(R"( + { "first-party-set": ["https://example.com/"], + "first-party-set": ["https://not-example.com/"] } )"); + + ASSERT_EQ(1U, policy->GetFirstPartySet().size()); + ASSERT_EQ(1U, policy->GetFirstPartySet().count( + url::Origin::Create(GURL("https://not-example.com/")))); +} + +TEST(OriginPolicy, FirstPartySetMultipleSameOrigin) { + auto policy = blink::OriginPolicy::From(R"( + { "first-party-set": ["https://example.com/", "https://example.com/some-path", "https://example.com:443/some-other-path"] } )"); + + ASSERT_EQ(1U, policy->GetFirstPartySet().size()); + ASSERT_EQ(1U, policy->GetFirstPartySet().count( + url::Origin::Create(GURL("https://example.com/")))); +} + +TEST(OriginPolicy, FirstPartySetListItemNotAString) { + struct { + const char* policy; + } tests[] = { + {R"({ "first-party-set": [ "https://example.com", { "https://example.com/": "https://example.com/" }, "https://example.com" ] } )"}, + {R"({ "first-party-set": [ "https://example.com", [ "https://example.com/" ], "https://example.com" ] } )"}, + {R"({ "first-party-set": [ "https://example.com", 123, "https://example.com" ] } )"}, + {R"({ "first-party-set": [ "https://example.com", 123.4, "https://example.com" ] } )"}, + {R"({ "first-party-set": [ "https://example.com", true, "https://example.com" ] } )"}, + }; + + for (const auto& test : tests) { + auto policy = blink::OriginPolicy::From(test.policy); + ASSERT_TRUE(policy); + ASSERT_EQ(0U, policy->GetFirstPartySet().size()); + } +} + +TEST(OriginPolicy, FirstPartySetNotAList) { + struct { + const char* policy; + } tests[] = { + {R"({ "first-party-set": "https://example.com/" } )"}, + {R"({ "first-party-set": { "https://example.com/": "https://example.com/" } } )"}, + {R"({ "first-party-set": 1234 } )"}, + {R"({ "first-party-set": 1234.6 } )"}, + {R"({ "first-party-set": true } )"}, + }; + + for (const auto& test : tests) { + auto policy = blink::OriginPolicy::From(test.policy); + ASSERT_TRUE(policy); + ASSERT_EQ(0U, policy->GetFirstPartySet().size()); + } +} + +TEST(OriginPolicy, FirstPartySetWithCSPAndFeatures) { + auto policy = blink::OriginPolicy::From(R"( + { "first-party-set": ["https://example.com/", "https://not-example.com/"], + "feature-policy": ["geolocation 'self' http://maps.google.com"], + "content-security-policy": [{ + "policy": "script-src 'self' 'unsafe-inline'" + }] + })"); + + ASSERT_TRUE(policy); + ASSERT_EQ(2U, policy->GetFirstPartySet().size()); + ASSERT_EQ(1U, policy->GetFirstPartySet().count( + url::Origin::Create(GURL("https://example.com/")))); + ASSERT_EQ(1U, policy->GetFirstPartySet().count( + url::Origin::Create(GURL("https://not-example.com/")))); + + ASSERT_EQ(policy->GetContentSecurityPolicies().size(), 1U); + ASSERT_EQ(policy->GetContentSecurityPolicies()[0].policy, + "script-src 'self' 'unsafe-inline'"); + + ASSERT_EQ(1U, policy->GetFeaturePolicies().size()); + ASSERT_EQ("geolocation 'self' http://maps.google.com", + policy->GetFeaturePolicies()[0]); +}
diff --git a/third_party/blink/public/common/BUILD.gn b/third_party/blink/public/common/BUILD.gn index 35d9a79..b9c3eba 100644 --- a/third_party/blink/public/common/BUILD.gn +++ b/third_party/blink/public/common/BUILD.gn
@@ -42,7 +42,6 @@ "css/preferred_color_scheme.h", "device_memory/approximated_device_memory.h", "dom_storage/session_storage_namespace_id.h", - "download/download_stats.h", "experiments/memory_ablation_experiment.h", "feature_policy/feature_policy.h", "feature_policy/policy_value.h",
diff --git a/third_party/blink/public/common/download/download_stats.h b/third_party/blink/public/common/download/download_stats.h deleted file mode 100644 index e11b2b3..0000000 --- a/third_party/blink/public/common/download/download_stats.h +++ /dev/null
@@ -1,81 +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 THIRD_PARTY_BLINK_PUBLIC_COMMON_DOWNLOAD_DOWNLOAD_STATS_H_ -#define THIRD_PARTY_BLINK_PUBLIC_COMMON_DOWNLOAD_DOWNLOAD_STATS_H_ - -#include <stdint.h> - -#include "base/macros.h" -#include "third_party/blink/public/common/common_export.h" - -namespace ukm { - -class UkmRecorder; - -typedef int64_t SourceId; - -} // namespace ukm - -namespace blink { - -class BLINK_COMMON_EXPORT DownloadStats { - public: - struct BLINK_COMMON_EXPORT MainFrameDownloadFlags { - bool has_sandbox; - bool has_gesture; - - MainFrameDownloadFlags() = default; - - unsigned ToUmaValue() const; - - private: - DISALLOW_COPY_AND_ASSIGN(MainFrameDownloadFlags); - }; - - struct BLINK_COMMON_EXPORT SubframeDownloadFlags { - bool has_sandbox; - bool is_cross_origin; - bool is_ad_frame; - bool has_gesture; - - SubframeDownloadFlags() = default; - - unsigned ToUmaValue() const; - - private: - DISALLOW_COPY_AND_ASSIGN(SubframeDownloadFlags); - }; - - // Log the bits in |flags| for a main frame download to UMA and UKM. - static void RecordMainFrameDownloadFlags(const MainFrameDownloadFlags& flags, - ukm::SourceId source_id, - ukm::UkmRecorder* ukm_recorder); - - // Log the bits in |flags| for a subframe download to UMA and UKM. - static void RecordSubframeDownloadFlags(const SubframeDownloadFlags& flags, - ukm::SourceId source_id, - ukm::UkmRecorder* ukm_recorder); - - private: - DISALLOW_IMPLICIT_CONSTRUCTORS(DownloadStats); - - // These values are used to construct an enum in UMA. They should never be - // changed. - static constexpr unsigned kSubframeGestureBit = 0x1 << 0; - static constexpr unsigned kSubframeAdBit = 0x1 << 1; - static constexpr unsigned kSubframeCrossOriginBit = 0x1 << 2; - static constexpr unsigned kSubframeSandboxBit = 0x1 << 3; - static constexpr unsigned kCountSandboxOriginAdGesture = 16; - - // These values are used to construct an enum in UMA. They should never be - // changed. - static constexpr unsigned kMainFrameGestureBit = 0x1 << 0; - static constexpr unsigned kMainFrameSandboxBit = 0x1 << 1; - static constexpr unsigned kCountSandboxGesture = 4; -}; - -} // namespace blink - -#endif // THIRD_PARTY_BLINK_PUBLIC_COMMON_DOWNLOAD_DOWNLOAD_STATS_H_
diff --git a/third_party/blink/public/common/origin_policy/origin_policy.h b/third_party/blink/public/common/origin_policy/origin_policy.h index 5c4583fb..b4ee595 100644 --- a/third_party/blink/public/common/origin_policy/origin_policy.h +++ b/third_party/blink/public/common/origin_policy/origin_policy.h
@@ -6,10 +6,13 @@ #define THIRD_PARTY_BLINK_PUBLIC_COMMON_ORIGIN_POLICY_ORIGIN_POLICY_H_ #include <memory> +#include <set> #include <string> +#include <vector> #include "base/strings/string_piece.h" #include "third_party/blink/public/common/common_export.h" +#include "url/origin.h" namespace blink { @@ -32,6 +35,10 @@ return features_; } + const std::set<url::Origin>& GetFirstPartySet() const { + return first_party_set_; + } + private: friend class OriginPolicyParser; @@ -39,6 +46,7 @@ std::vector<CSP> csp_; std::vector<std::string> features_; + std::set<url::Origin> first_party_set_; }; } // namespace blink
diff --git a/third_party/blink/public/mojom/BUILD.gn b/third_party/blink/public/mojom/BUILD.gn index 906c4ae..991bcfe 100644 --- a/third_party/blink/public/mojom/BUILD.gn +++ b/third_party/blink/public/mojom/BUILD.gn
@@ -84,7 +84,6 @@ "renderer_preferences.mojom", "reporting/reporting.mojom", "script/script_type.mojom", - "serial/serial.mojom", "service_worker/dispatch_fetch_event_params.mojom", "service_worker/navigation_preload_state.mojom", "service_worker/service_worker_client.mojom", @@ -116,6 +115,10 @@ "worker/worker_main_script_load_params.mojom", ] + if (!is_android) { + sources += [ "serial/serial.mojom" ] + } + if (is_win) { sources += [ "dwrite_font_proxy/dwrite_font_proxy.mojom" ] }
diff --git a/third_party/blink/public/mojom/web_feature/web_feature.mojom b/third_party/blink/public/mojom/web_feature/web_feature.mojom index 3f742f8..5e6e0e9 100644 --- a/third_party/blink/public/mojom/web_feature/web_feature.mojom +++ b/third_party/blink/public/mojom/web_feature/web_feature.mojom
@@ -905,7 +905,6 @@ kCSSValueAppearanceNotNone = 1352, kCSSValueAppearanceOthers = 1353, kCSSValueAppearanceButton = 1354, - kCSSValueAppearanceCaret = 1355, kCSSValueAppearanceCheckbox = 1356, kCSSValueAppearanceMenulist = 1357, kCSSValueAppearanceMenulistButton = 1358, @@ -2226,22 +2225,6 @@ kAnimationFrameCancelledWithinFrame = 2793, kSchedulingIsInputPending = 2794, kV8StringNormalize = 2795, - kCSSValueAppearanceButtonBevel = 2796, - kCSSValueAppearanceListitem = 2797, - kCSSValueAppearanceMediaControlsBackground = 2798, - kCSSValueAppearanceMediaControlsFullscreenBackground = 2799, - kCSSValueAppearanceMediaCurrentTimeDisplay = 2800, - kCSSValueAppearanceMediaEnterFullscreenButton = 2801, - kCSSValueAppearanceMediaExitFullscreenButton = 2802, - kCSSValueAppearanceMediaMuteButton = 2803, - kCSSValueAppearanceMediaOverlayPlayButton = 2804, - kCSSValueAppearanceMediaPlayButton = 2805, - kCSSValueAppearanceMediaTimeRemainingDisplay = 2806, - kCSSValueAppearanceMediaToggleClosedCaptionsButton = 2807, - kCSSValueAppearanceMediaVolumeSliderContainer = 2808, - kCSSValueAppearanceMenulistTextfield = 2809, - kCSSValueAppearanceMenulistText = 2810, - kCSSValueAppearanceProgressBarValue = 2811, kU2FCryptotokenRegister = 2812, kU2FCryptotokenSign = 2813, kCSSValueAppearanceInnerSpinButton = 2814, @@ -2265,6 +2248,7 @@ kCSSSelectorHostContextInLiveProfile = 2830, kImportMap = 2831, kRefreshHeader = 2832, + kSearchEventFired = 2833, // Add new features immediately above this line. Don't change assigned // numbers of any item, and don't reuse removed slots.
diff --git a/third_party/blink/public/platform/platform.h b/third_party/blink/public/platform/platform.h index 699b40d..ac297b2d 100644 --- a/third_party/blink/public/platform/platform.h +++ b/third_party/blink/public/platform/platform.h
@@ -526,6 +526,7 @@ kWebGPUContextType, // WebGPU context }; struct ContextAttributes { + bool prefer_integrated_gpu = false; bool fail_if_major_performance_caveat = false; ContextType context_type = kGLES2ContextType; // Offscreen contexts usually share a surface for the default frame buffer
diff --git a/third_party/blink/public/platform/scheduler/web_thread_scheduler.h b/third_party/blink/public/platform/scheduler/web_thread_scheduler.h index 7043dd4..d7afcd2 100644 --- a/third_party/blink/public/platform/scheduler/web_thread_scheduler.h +++ b/third_party/blink/public/platform/scheduler/web_thread_scheduler.h
@@ -84,6 +84,12 @@ // Returns the cleanup task runner, which is for cleaning up. virtual scoped_refptr<base::SingleThreadTaskRunner> CleanupTaskRunner(); + // Returns a default task runner. This is basically same as the default task + // runner, but is explicitly allowed to run JavaScript. For the detail, see + // the comment at blink::ThreadScheduler::DeprecatedDefaultTaskRunner. + virtual scoped_refptr<base::SingleThreadTaskRunner> + DeprecatedDefaultTaskRunner(); + // Creates a WebThread implementation for the renderer main thread. virtual std::unique_ptr<Thread> CreateMainThread();
diff --git a/third_party/blink/public/platform/web_content_decryption_module_result.h b/third_party/blink/public/platform/web_content_decryption_module_result.h index 4af42b1..0d65735c 100644 --- a/third_party/blink/public/platform/web_content_decryption_module_result.h +++ b/third_party/blink/public/platform/web_content_decryption_module_result.h
@@ -60,7 +60,7 @@ // Called when the operation fails. BLINK_PLATFORM_EXPORT void CompleteWithError( WebContentDecryptionModuleException, - unsigned long system_code, + uint32_t system_code, const WebString& message); #if INSIDE_BLINK
diff --git a/third_party/blink/public/platform/web_rtc_peer_connection_handler_client.h b/third_party/blink/public/platform/web_rtc_peer_connection_handler_client.h index 34e2264..65bbb1e 100644 --- a/third_party/blink/public/platform/web_rtc_peer_connection_handler_client.h +++ b/third_party/blink/public/platform/web_rtc_peer_connection_handler_client.h
@@ -37,6 +37,7 @@ #include "base/memory/scoped_refptr.h" #include "third_party/blink/public/platform/web_common.h" #include "third_party/webrtc/api/peer_connection_interface.h" +#include "third_party/webrtc/api/sctp_transport_interface.h" namespace blink { @@ -44,6 +45,14 @@ class WebRTCRtpReceiver; class WebRTCRtpTransceiver; +struct BLINK_PLATFORM_EXPORT WebRTCSctpTransportSnapshot { + rtc::scoped_refptr<webrtc::SctpTransportInterface> transport; + webrtc::SctpTransportInformation sctp_transport_state = + webrtc::SctpTransportInformation(webrtc::SctpTransportState::kNew); + webrtc::DtlsTransportInformation dtls_transport_state = + webrtc::DtlsTransportInformation(webrtc::DtlsTransportState::kNew); +}; + class BLINK_PLATFORM_EXPORT WebRTCPeerConnectionHandlerClient { public: virtual ~WebRTCPeerConnectionHandlerClient(); @@ -63,6 +72,7 @@ virtual void DidModifyTransceivers( std::vector<std::unique_ptr<WebRTCRtpTransceiver>>, bool is_remote_description) = 0; + virtual void DidModifySctpTransport(WebRTCSctpTransportSnapshot) = 0; virtual void DidAddRemoteDataChannel( scoped_refptr<webrtc::DataChannelInterface>) = 0; virtual void DidNoteInterestingUsage(int usage_pattern) = 0;
diff --git a/third_party/blink/public/platform/web_runtime_features.h b/third_party/blink/public/platform/web_runtime_features.h index 2b5127c..d7d6014 100644 --- a/third_party/blink/public/platform/web_runtime_features.h +++ b/third_party/blink/public/platform/web_runtime_features.h
@@ -174,7 +174,6 @@ BLINK_PLATFORM_EXPORT static void EnableScriptedSpeechSynthesis(bool); BLINK_PLATFORM_EXPORT static void EnableScrollAnchorSerialization(bool); BLINK_PLATFORM_EXPORT static void EnableSecMetadata(bool); - BLINK_PLATFORM_EXPORT static void EnableSerial(bool); BLINK_PLATFORM_EXPORT static void EnableSharedArrayBuffer(bool); BLINK_PLATFORM_EXPORT static void EnableSharedWorker(bool); BLINK_PLATFORM_EXPORT static void EnableTextFragmentAnchor(bool); @@ -223,6 +222,7 @@ BLINK_PLATFORM_EXPORT static void EnableMediaEngagementBypassAutoplayPolicies( bool); BLINK_PLATFORM_EXPORT static void EnableAutomationControlled(bool); + BLINK_PLATFORM_EXPORT static void EnableScheduledScriptStreaming(bool); BLINK_PLATFORM_EXPORT static void EnableScriptStreamingOnPreload(bool); BLINK_PLATFORM_EXPORT static void EnableExperimentalProductivityFeatures( bool);
diff --git a/third_party/blink/public/platform/web_thread_type.h b/third_party/blink/public/platform/web_thread_type.h index 38ace6b..7f0cf64 100644 --- a/third_party/blink/public/platform/web_thread_type.h +++ b/third_party/blink/public/platform/web_thread_type.h
@@ -21,7 +21,7 @@ kFileThread = 8, kDatabaseThread = 9, kWebAudioThread = 10, - // 11 was kScriptStreamerThread, which was deleted + kScriptStreamerThread = 11, kOfflineAudioRenderThread = 12, kReverbConvolutionBackgroundThread = 13, kHRTFDatabaseLoaderThread = 14,
diff --git a/third_party/blink/public/web/web_local_frame_client.h b/third_party/blink/public/web/web_local_frame_client.h index b16662ed..c3eed889 100644 --- a/third_party/blink/public/web/web_local_frame_client.h +++ b/third_party/blink/public/web/web_local_frame_client.h
@@ -154,6 +154,7 @@ // May return null. virtual std::unique_ptr<WebApplicationCacheHost> CreateApplicationCacheHost( + WebDocumentLoader*, WebApplicationCacheHostClient*) { return nullptr; } @@ -512,6 +513,12 @@ // ever having received a user gesture. virtual void DidBlockFramebust(const WebURL&) {} + // Tells the embedder to navigate back or forward in session history by + // the given offset (relative to the current position in session + // history). |has_user_gesture| tells whether or not this is the consequence + // of a user action. + virtual void NavigateBackForwardSoon(int offset, bool has_user_gesture) {} + // Returns token to be used as a frame id in the devtools protocol. // It is derived from the content's devtools_frame_token, is // defined by the browser and passed into Blink upon frame creation.
diff --git a/third_party/blink/public/web/web_origin_trials.h b/third_party/blink/public/web/web_origin_trials.h index 2c79a0f..0ab1c700 100644 --- a/third_party/blink/public/web/web_origin_trials.h +++ b/third_party/blink/public/web/web_origin_trials.h
@@ -16,6 +16,8 @@ // origin trials framework via origin trial tokens. class WebOriginTrials { public: + // This function returns true if the passed trial name is valid and ALL of the + // features with that trial name are enabled. CORE_EXPORT static bool isTrialEnabled(const WebDocument*, const WebString&); };
diff --git a/third_party/blink/public/web/web_view.h b/third_party/blink/public/web/web_view.h index 73f44bb..36d767e5 100644 --- a/third_party/blink/public/web/web_view.h +++ b/third_party/blink/public/web/web_view.h
@@ -336,7 +336,7 @@ // Returns next unused request identifier which is unique within the // parent Page. - virtual unsigned long CreateUniqueIdentifierForRequest() = 0; + virtual uint64_t CreateUniqueIdentifierForRequest() = 0; // Developer tools -----------------------------------------------------
diff --git a/third_party/blink/public/web/web_view_client.h b/third_party/blink/public/web/web_view_client.h index c435c4c..0b7fe77 100644 --- a/third_party/blink/public/web/web_view_client.h +++ b/third_party/blink/public/web/web_view_client.h
@@ -176,12 +176,6 @@ // Session history ----------------------------------------------------- - // Tells the embedder to navigate back or forward in session history by - // the given offset (relative to the current position in session - // history). |has_user_gesture| tells whether or not this is the consequence - // of a user action. - virtual void NavigateBackForwardSoon(int offset, bool has_user_gesture) {} - // Returns the number of history items before/after the current // history item. virtual int HistoryBackListCount() { return 0; }
diff --git a/third_party/blink/renderer/bindings/bindings.gni b/third_party/blink/renderer/bindings/bindings.gni index 0da42a9..89dc4ff 100644 --- a/third_party/blink/renderer/bindings/bindings.gni +++ b/third_party/blink/renderer/bindings/bindings.gni
@@ -99,6 +99,8 @@ "core/v8/script_source_location_type.h", "core/v8/script_streamer.cc", "core/v8/script_streamer.h", + "core/v8/script_streamer_thread.cc", + "core/v8/script_streamer_thread.h", "core/v8/script_value.cc", "core/v8/script_value.h", "core/v8/serialization/post_message_helper.cc",
diff --git a/third_party/blink/renderer/bindings/core/v8/local_window_proxy.cc b/third_party/blink/renderer/bindings/core/v8/local_window_proxy.cc index ea4d47e..a56856c 100644 --- a/third_party/blink/renderer/bindings/core/v8/local_window_proxy.cc +++ b/third_party/blink/renderer/bindings/core/v8/local_window_proxy.cc
@@ -153,8 +153,6 @@ ("Blink.Binding.InitializeNonMainLocalWindowProxy", 0, 10000000, 50)); ScopedUsHistogramTimer timer(GetFrame()->IsMainFrame() ? main_frame_hist : non_main_frame_hist); - // TODO(alph): Remove this temporary code for debugging - // https://crbug.com/728693. CHECK(!GetFrame()->IsProvisional()); ScriptForbiddenScope::AllowUserAgentScript allow_script;
diff --git a/third_party/blink/renderer/bindings/core/v8/script_streamer.cc b/third_party/blink/renderer/bindings/core/v8/script_streamer.cc index fa21f0f4..0b5f2d5 100644 --- a/third_party/blink/renderer/bindings/core/v8/script_streamer.cc +++ b/third_party/blink/renderer/bindings/core/v8/script_streamer.cc
@@ -8,6 +8,7 @@ #include "base/macros.h" #include "base/memory/ptr_util.h" +#include "third_party/blink/renderer/bindings/core/v8/script_streamer_thread.h" #include "third_party/blink/renderer/bindings/core/v8/v8_code_cache.h" #include "third_party/blink/renderer/core/dom/document.h" #include "third_party/blink/renderer/core/dom/element.h" @@ -351,6 +352,21 @@ streamer->StreamingCompleteOnBackgroundThread(); } +void RunBlockingScriptStreamingTask( + std::unique_ptr<v8::ScriptCompiler::ScriptStreamingTask> task, + ScriptStreamer* streamer, + std::atomic_flag* blocking_task_started_or_cancelled) { + if (blocking_task_started_or_cancelled->test_and_set()) + return; + RunScriptStreamingTask(std::move(task), streamer); +} + +void RunNonBlockingScriptStreamingTask( + std::unique_ptr<v8::ScriptCompiler::ScriptStreamingTask> task, + ScriptStreamer* streamer) { + RunScriptStreamingTask(std::move(task), streamer); +} + } // namespace bool ScriptStreamer::HasEnoughDataForStreaming(size_t resource_buffer_size) { @@ -399,6 +415,16 @@ } } + if (!RuntimeEnabledFeatures::ScheduledScriptStreamingEnabled() && + ScriptStreamerThread::Shared()->IsRunningTask()) { + // If scheduled script streaming is disabled, we only have one thread for + // running the tasks. A new task shouldn't be queued before the running + // task completes, because the running task can block and wait for data + // from the network. + SuppressStreaming(kThreadBusy); + return; + } + DCHECK(!stream_); DCHECK(!source_); stream_ = new SourceStream; @@ -425,16 +451,31 @@ inspector_parse_script_event::Data(this->ScriptResourceIdentifier(), this->ScriptURLString())); - // Script streaming tasks are high priority, as they can block the parser, - // and they can (and probably will) block during their own execution as - // they wait for more input. - // - // TODO(leszeks): Decrease the priority of these tasks where possible. - worker_pool::PostTaskWithTraits( - FROM_HERE, {base::TaskPriority::USER_BLOCKING, base::MayBlock()}, - CrossThreadBind(RunScriptStreamingTask, - WTF::Passed(std::move(script_streaming_task)), - WrapCrossThreadPersistent(this))); + if (RuntimeEnabledFeatures::ScheduledScriptStreamingEnabled()) { + // Script streaming tasks are high priority, as they can block the parser, + // and they can (and probably will) block during their own execution as + // they wait for more input. + // + // Pass through the atomic cancellation token which is set to true by the + // task when it is started, or set to true by the streamer if it wants to + // cancel the task. + // + // TODO(leszeks): Decrease the priority of these tasks where possible. + worker_pool::PostTaskWithTraits( + FROM_HERE, {base::TaskPriority::USER_BLOCKING, base::MayBlock()}, + CrossThreadBind(RunBlockingScriptStreamingTask, + WTF::Passed(std::move(script_streaming_task)), + WrapCrossThreadPersistent(this), + WTF::CrossThreadUnretained( + &blocking_task_started_or_cancelled_))); + } else { + blocking_task_started_or_cancelled_.test_and_set(); + ScriptStreamerThread::Shared()->PostTask( + CrossThreadBind(&ScriptStreamerThread::RunScriptStreamingTask, + WTF::Passed(std::move(script_streaming_task)), + WrapCrossThreadPersistent(this))); + } + } if (stream_) stream_->DidReceiveData(script_resource_, this); @@ -451,7 +492,34 @@ } if (stream_) { + // Mark the stream as finished loading before potentially re-posting the + // task to avoid a race between this finish and the task's first read. stream_->DidFinishLoading(); + + // If the corresponding blocking task hasn't started yet, cancel it and post + // a non-blocking task, since we know now that all the data is received and + // we will no longer block. + // + // TODO(874080): Remove this once blocking and non-blocking pools are + // merged. + if (RuntimeEnabledFeatures::ScheduledScriptStreamingEnabled() && + !RuntimeEnabledFeatures::MergeBlockingNonBlockingPoolsEnabled() && + !blocking_task_started_or_cancelled_.test_and_set()) { + std::unique_ptr<v8::ScriptCompiler::ScriptStreamingTask> + script_streaming_task( + base::WrapUnique(v8::ScriptCompiler::StartStreamingScript( + V8PerIsolateData::MainThreadIsolate(), source_.get(), + compile_options_))); + + // The task creation shouldn't fail, since it didn't fail before during + // NotifyAppendData. + CHECK(script_streaming_task); + worker_pool::PostTaskWithTraits( + FROM_HERE, {base::TaskPriority::USER_BLOCKING}, + CrossThreadBind(RunNonBlockingScriptStreamingTask, + WTF::Passed(std::move(script_streaming_task)), + WrapCrossThreadPersistent(this))); + } } loading_finished_ = true;
diff --git a/third_party/blink/renderer/bindings/core/v8/script_streamer.h b/third_party/blink/renderer/bindings/core/v8/script_streamer.h index a162366..1290225a 100644 --- a/third_party/blink/renderer/bindings/core/v8/script_streamer.h +++ b/third_party/blink/renderer/bindings/core/v8/script_streamer.h
@@ -5,6 +5,7 @@ #ifndef THIRD_PARTY_BLINK_RENDERER_BINDINGS_CORE_V8_SCRIPT_STREAMER_H_ #define THIRD_PARTY_BLINK_RENDERER_BINDINGS_CORE_V8_SCRIPT_STREAMER_H_ +#include <atomic> #include <memory> #include "base/macros.h" @@ -40,7 +41,8 @@ kRevalidate, kContextNotValid, // DEPRECATED kEncodingNotSupported, - kThreadBusy, // DEPRECATED + // TODO(leszeks): Deprecate once scheduled streaming is on by default + kThreadBusy, kV8CannotStream, kScriptTooSmall, kNoResourceBuffer, @@ -115,7 +117,7 @@ void StreamingCompleteOnBackgroundThread(); const String& ScriptURLString() const { return script_url_string_; } - unsigned long ScriptResourceIdentifier() const { + uint64_t ScriptResourceIdentifier() const { return script_resource_identifier_; } @@ -153,6 +155,11 @@ // Whether we have received enough data to start the streaming. bool have_enough_data_for_streaming_; + // Flag used to allow atomic cancelling and reposting of the streaming task + // when the load completes without the task yet starting. + // TODO(874080): Remove this once blocking and non-blocking pools are merged. + std::atomic_flag blocking_task_started_or_cancelled_ = ATOMIC_FLAG_INIT; + // Whether the script source code should be retrieved from the Resource // instead of the ScriptStreamer. bool streaming_suppressed_; @@ -165,7 +172,7 @@ const String script_url_string_; // Keep the script resource dentifier for event tracing. - const unsigned long script_resource_identifier_; + const uint64_t script_resource_identifier_; // Encoding of the streamed script. Saved for sanity checking purposes. v8::ScriptCompiler::StreamedSource::Encoding encoding_;
diff --git a/third_party/blink/renderer/bindings/core/v8/script_streamer_test.cc b/third_party/blink/renderer/bindings/core/v8/script_streamer_test.cc index dfd8165..8fd2036 100644 --- a/third_party/blink/renderer/bindings/core/v8/script_streamer_test.cc +++ b/third_party/blink/renderer/bindings/core/v8/script_streamer_test.cc
@@ -13,6 +13,7 @@ #include "third_party/blink/public/platform/web_url_loader_mock_factory.h" #include "third_party/blink/renderer/bindings/core/v8/referrer_script_info.h" #include "third_party/blink/renderer/bindings/core/v8/script_source_code.h" +#include "third_party/blink/renderer/bindings/core/v8/script_streamer_thread.h" #include "third_party/blink/renderer/bindings/core/v8/v8_binding_for_core.h" #include "third_party/blink/renderer/bindings/core/v8/v8_binding_for_testing.h" #include "third_party/blink/renderer/bindings/core/v8/v8_code_cache.h" @@ -28,7 +29,6 @@ #include "third_party/blink/renderer/platform/loader/fetch/resource_loader.h" #include "third_party/blink/renderer/platform/loader/fetch/script_fetch_options.h" #include "third_party/blink/renderer/platform/scheduler/public/thread_scheduler.h" -#include "third_party/blink/renderer/platform/testing/testing_platform_support_with_mock_scheduler.h" #include "third_party/blink/renderer/platform/testing/unit_test_helpers.h" #include "third_party/blink/renderer/platform/wtf/text/text_encoding.h" #include "v8/include/v8.h" @@ -40,7 +40,7 @@ class ScriptStreamingTest : public testing::Test { public: ScriptStreamingTest() - : loading_task_runner_(platform_->test_task_runner()), + : loading_task_runner_(scheduler::GetSingleThreadTaskRunnerForTesting()), dummy_page_holder_(DummyPageHolder::Create(IntSize(800, 600))) { dummy_page_holder_->GetPage().GetSettings().SetScriptEnabled(true); MockScriptElementBase* element = MockScriptElementBase::Create(); @@ -122,10 +122,16 @@ GetResource()->SetStatus(ResourceStatus::kCached); } - void ProcessTasksUntilStreamingComplete() { platform_->RunUntilIdle(); } - - ScopedTestingPlatformSupport<TestingPlatformSupportWithMockScheduler> - platform_; + void ProcessTasksUntilStreamingComplete() { + if (!RuntimeEnabledFeatures::ScheduledScriptStreamingEnabled()) { + while (ScriptStreamerThread::Shared()->IsRunningTask()) { + test::RunPendingTasks(); + } + } + // Once more, because the "streaming complete" notification might only + // now be in the task queue. + test::RunPendingTasks(); + } scoped_refptr<base::SingleThreadTaskRunner> loading_task_runner_; // The PendingScript where we stream from. These don't really
diff --git a/third_party/blink/renderer/bindings/core/v8/script_streamer_thread.cc b/third_party/blink/renderer/bindings/core/v8/script_streamer_thread.cc new file mode 100644 index 0000000..e1b3c34 --- /dev/null +++ b/third_party/blink/renderer/bindings/core/v8/script_streamer_thread.cc
@@ -0,0 +1,90 @@ +// Copyright 2014 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "third_party/blink/renderer/bindings/core/v8/script_streamer_thread.h" + +#include <memory> +#include "base/location.h" +#include "third_party/blink/public/platform/platform.h" +#include "third_party/blink/renderer/bindings/core/v8/script_streamer.h" +#include "third_party/blink/renderer/core/inspector/inspector_trace_events.h" +#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/scheduler/public/post_cross_thread_task.h" +#include "third_party/blink/renderer/platform/scheduler/public/thread.h" + +namespace blink { + +static ScriptStreamerThread* g_shared_thread = nullptr; +// Guards s_sharedThread. s_sharedThread is initialized and deleted in the main +// thread, but also used by the streamer thread. Races can occur during +// shutdown. +static Mutex* g_mutex = nullptr; + +void ScriptStreamerThread::Init() { + // Only enabled when ScheduledScriptStreaming is disabled. + if (!RuntimeEnabledFeatures::ScheduledScriptStreamingEnabled()) { + DCHECK(!g_shared_thread); + DCHECK(IsMainThread()); + // This is called in the main thread before any tasks are created, so no + // locking is needed. + g_mutex = new Mutex(); + g_shared_thread = new ScriptStreamerThread(); + } +} + +ScriptStreamerThread* ScriptStreamerThread::Shared() { + DCHECK(!RuntimeEnabledFeatures::ScheduledScriptStreamingEnabled()); + return g_shared_thread; +} + +void ScriptStreamerThread::PostTask(CrossThreadClosure task) { + DCHECK(!RuntimeEnabledFeatures::ScheduledScriptStreamingEnabled()); + DCHECK(IsMainThread()); + MutexLocker locker(mutex_); + DCHECK(!running_task_); + running_task_ = true; + PostCrossThreadTask(*PlatformThread().GetTaskRunner(), FROM_HERE, + std::move(task)); +} + +void ScriptStreamerThread::TaskDone() { + MutexLocker locker(mutex_); + DCHECK(running_task_); + running_task_ = false; +} + +Thread& ScriptStreamerThread::PlatformThread() { + if (!IsRunning()) { + thread_ = Platform::Current()->CreateThread( + ThreadCreationParams(WebThreadType::kScriptStreamerThread)); + } + return *thread_; +} + +void ScriptStreamerThread::RunScriptStreamingTask( + std::unique_ptr<v8::ScriptCompiler::ScriptStreamingTask> task, + ScriptStreamer* streamer) { + DCHECK(!RuntimeEnabledFeatures::ScheduledScriptStreamingEnabled()); + TRACE_EVENT1( + "v8,devtools.timeline", "v8.parseOnBackground", "data", + inspector_parse_script_event::Data(streamer->ScriptResourceIdentifier(), + streamer->ScriptURLString())); + TRACE_EVENT_WITH_FLOW1( + TRACE_DISABLED_BY_DEFAULT("v8.compile"), "v8.streamingCompile.run", + streamer, TRACE_EVENT_FLAG_FLOW_IN | TRACE_EVENT_FLAG_FLOW_OUT, "data", + inspector_parse_script_event::Data(streamer->ScriptResourceIdentifier(), + streamer->ScriptURLString())); + // Running the task can and will block: SourceStream::GetSomeData will get + // called and it will block and wait for data from the network. + task->Run(); + streamer->StreamingCompleteOnBackgroundThread(); + MutexLocker locker(*g_mutex); + ScriptStreamerThread* thread = Shared(); + if (thread) + thread->TaskDone(); + // If thread is 0, we're shutting down. +} + +} // namespace blink
diff --git a/third_party/blink/renderer/bindings/core/v8/script_streamer_thread.h b/third_party/blink/renderer/bindings/core/v8/script_streamer_thread.h new file mode 100644 index 0000000..664df34e --- /dev/null +++ b/third_party/blink/renderer/bindings/core/v8/script_streamer_thread.h
@@ -0,0 +1,60 @@ +// Copyright 2014 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef THIRD_PARTY_BLINK_RENDERER_BINDINGS_CORE_V8_SCRIPT_STREAMER_THREAD_H_ +#define THIRD_PARTY_BLINK_RENDERER_BINDINGS_CORE_V8_SCRIPT_STREAMER_THREAD_H_ + +#include <memory> + +#include "base/macros.h" +#include "third_party/blink/renderer/core/core_export.h" +#include "third_party/blink/renderer/platform/scheduler/public/thread.h" +#include "third_party/blink/renderer/platform/wtf/functional.h" +#include "third_party/blink/renderer/platform/wtf/threading_primitives.h" +#include "v8/include/v8.h" + +namespace blink { + +class ScriptStreamer; + +// A singleton thread for running background tasks for script streaming. +class CORE_EXPORT ScriptStreamerThread { + USING_FAST_MALLOC(ScriptStreamerThread); + + public: + static void Init(); + static ScriptStreamerThread* Shared(); + + void PostTask(CrossThreadClosure); + + bool IsRunningTask() const { + MutexLocker locker(mutex_); + return running_task_; + } + + void TaskDone(); + + static void RunScriptStreamingTask( + std::unique_ptr<v8::ScriptCompiler::ScriptStreamingTask>, + ScriptStreamer*); + + private: + ScriptStreamerThread() : running_task_(false) {} + + bool IsRunning() const { return !!thread_; } + + Thread& PlatformThread(); + + // At the moment, we only use one thread, so we can only stream one script + // at a time. FIXME: Use a thread pool and stream multiple scripts. + std::unique_ptr<Thread> thread_; + bool running_task_ GUARDED_BY(mutex_); + mutable Mutex mutex_; + + DISALLOW_COPY_AND_ASSIGN(ScriptStreamerThread); +}; + +} // namespace blink + +#endif // THIRD_PARTY_BLINK_RENDERER_BINDINGS_CORE_V8_SCRIPT_STREAMER_THREAD_H_
diff --git a/third_party/blink/renderer/bindings/scripts/generate_origin_trial_features.py b/third_party/blink/renderer/bindings/scripts/generate_origin_trial_features.py index 58da9c0e..6e4950e 100755 --- a/third_party/blink/renderer/bindings/scripts/generate_origin_trial_features.py +++ b/third_party/blink/renderer/bindings/scripts/generate_origin_trial_features.py
@@ -169,6 +169,7 @@ 'platform/bindings/origin_trial_features.h', 'platform/bindings/script_state.h', 'platform/bindings/v8_per_context_data.h', + 'platform/runtime_enabled_features.h', # TODO(iclelland): Remove the need to explicitly include this; it is # here because the ContextFeatureSettings code needs it. 'bindings/core/v8/v8_window.h', @@ -189,7 +190,7 @@ # functions to call, organized by interface. context['installers_by_feature'] = [ {'name': feature_name, - 'name_constant': 'origin_trials::k%sTrialName' % feature_name, + 'name_constant': 'OriginTrialFeature::k%s' % feature_name, 'installers': get_install_functions(interfaces, [feature_name])} for feature_name, interfaces in types_for_feature.items()] context['installers_by_feature'].sort(key=lambda x: x['name'])
diff --git a/third_party/blink/renderer/bindings/scripts/web_idl/.style.yapf b/third_party/blink/renderer/bindings/scripts/web_idl/.style.yapf new file mode 100644 index 0000000..0169b9a --- /dev/null +++ b/third_party/blink/renderer/bindings/scripts/web_idl/.style.yapf
@@ -0,0 +1,3 @@ +[style] +# https://www.chromium.org/blink/coding-style +based_on_style = pep8
diff --git a/third_party/blink/renderer/bindings/scripts/web_idl/argument.py b/third_party/blink/renderer/bindings/scripts/web_idl/argument.py index 8d0a70c..82773bf 100644 --- a/third_party/blink/renderer/bindings/scripts/web_idl/argument.py +++ b/third_party/blink/renderer/bindings/scripts/web_idl/argument.py
@@ -1,42 +1,52 @@ -# Copyright 2017 The Chromium Authors. All rights reserved. +# 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. -from .extended_attribute import ExtendedAttributeList -from .utilities import assert_no_extra_args +import exceptions +from .common import WithIdentifier +from .common import WithExtendedAttributes +from .common import WithCodeGeneratorInfo +from .common import WithOwner -class Argument(object): - - def __init__(self, **kwargs): - self._identifier = kwargs.pop('identifier') - self._type = kwargs.pop('type') - self._is_optional = kwargs.pop('is_optional', False) - self._is_variadic = kwargs.pop('is_variadic', False) - self._default_value = kwargs.pop('default_value', None) - self._extended_attribute_list = kwargs.pop('extended_attribute_list', ExtendedAttributeList()) - assert_no_extra_args(kwargs) - +class Argument(WithIdentifier, WithExtendedAttributes, WithCodeGeneratorInfo, + WithOwner): @property - def identifier(self): - return self._identifier - - @property - def type(self): - return self._type + def idl_type(self): + """ + Returns type of this argument. + @return IdlType + """ + raise exceptions.NotImplementedError() @property def is_optional(self): - return self._is_optional + """ + Returns True if this argument is optional. + @return bool + """ + raise exceptions.NotImplementedError() @property def is_variadic(self): - return self._is_variadic + """ + Returns True if this argument is variadic. + @return bool + """ + raise exceptions.NotImplementedError() @property def default_value(self): - return self._default_value + """ + Returns the default value if it is specified. Otherwise, None + @return DefaultValue + """ + raise exceptions.NotImplementedError() @property - def extended_attribute_list(self): - return self._extended_attribute_list + def index(self): + """ + Returns its index in an operation's arguments + @return int + """ + raise exceptions.NotImplementedError()
diff --git a/third_party/blink/renderer/bindings/scripts/web_idl/attribute.py b/third_party/blink/renderer/bindings/scripts/web_idl/attribute.py index 0e736db..75455c66 100644 --- a/third_party/blink/renderer/bindings/scripts/web_idl/attribute.py +++ b/third_party/blink/renderer/bindings/scripts/web_idl/attribute.py
@@ -1,44 +1,43 @@ -# Copyright 2017 The Chromium Authors. All rights reserved. +# 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. -from .extended_attribute import ExtendedAttributeList -from .idl_types import RecordType -from .idl_types import SequenceType -from .utilities import assert_no_extra_args +import exceptions +from .idl_member import IdlMember -# https://heycam.github.io/webidl/#idl-attributes -class Attribute(object): - _INVALID_TYPES = frozenset([SequenceType, RecordType]) - - def __init__(self, **kwargs): - self._identifier = kwargs.pop('identifier') - self._type = kwargs.pop('type') - self._is_static = kwargs.pop('is_static', False) - self._is_readonly = kwargs.pop('is_readonly', False) - self._extended_attribute_list = kwargs.pop('extended_attribute_list', ExtendedAttributeList()) - assert_no_extra_args(kwargs) - - if type(self.type) in Attribute._INVALID_TYPES: - raise ValueError('The type of an attribute must not be either of sequence<T> and record<K,V>.') +class Attribute(IdlMember): + """https://heycam.github.io/webidl/#idl-attributes""" @property - def identifier(self): - return self._identifier - - @property - def type(self): - return self._type + def idl_type(self): + """ + Returns type of this attribute. + @return IdlType + """ + raise exceptions.NotImplementedError() @property def is_static(self): - return self._is_static + """ + Returns True if this attriute is static. + @return bool + """ + raise exceptions.NotImplementedError() @property def is_readonly(self): - return self._is_readonly + """ + Returns True if this attribute is read only. + @return bool + """ + raise exceptions.NotImplementedError() @property - def extended_attribute_list(self): - return self._extended_attribute_list + def does_inherit_getter(self): + """ + Returns True if |self| inherits its getter. + https://heycam.github.io/webidl/#dfn-inherit-getter + @return bool + """ + raise exceptions.NotImplementedError()
diff --git a/third_party/blink/renderer/bindings/scripts/web_idl/callback_function.py b/third_party/blink/renderer/bindings/scripts/web_idl/callback_function.py index 438be019..78001a2 100644 --- a/third_party/blink/renderer/bindings/scripts/web_idl/callback_function.py +++ b/third_party/blink/renderer/bindings/scripts/web_idl/callback_function.py
@@ -1,33 +1,26 @@ -# Copyright 2017 The Chromium Authors. All rights reserved. +# 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. -from .extended_attribute import ExtendedAttributeList -from .utilities import assert_no_extra_args +import exceptions +from .idl_definition import IdlDefinition -# https://heycam.github.io/webidl/#idl-callback-functions -class CallbackFunction(object): - - def __init__(self, **kwargs): - self._identifier = kwargs.pop('identifier') - self._return_type = kwargs.pop('return_type') - self._arguments = tuple(kwargs.pop('arguments', [])) - self._extended_attribute_list = kwargs.pop('extended_attribute_list', ExtendedAttributeList()) - assert_no_extra_args(kwargs) - - @property - def identifier(self): - return self._identifier +class CallbackFunction(IdlDefinition): + """https://heycam.github.io/webidl/#idl-callback-functions""" @property def return_type(self): - return self._return_type + """ + Returns the type of return value. + @return IdlType + """ + raise exceptions.NotImplementedError() @property def arguments(self): - return self._arguments - - @property - def extended_attribute_list(self): - return self._extended_attribute_list + """ + Returns a list of arguments. + @return Argument + """ + raise exceptions.NotImplementedError()
diff --git a/third_party/blink/renderer/bindings/scripts/web_idl/callback_interface.py b/third_party/blink/renderer/bindings/scripts/web_idl/callback_interface.py index e086667..95b5114 100644 --- a/third_party/blink/renderer/bindings/scripts/web_idl/callback_interface.py +++ b/third_party/blink/renderer/bindings/scripts/web_idl/callback_interface.py
@@ -1,48 +1,35 @@ -# Copyright 2017 The Chromium Authors. All rights reserved. +# 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. -from .extended_attribute import ExtendedAttributeList -from .utilities import assert_no_extra_args +import exceptions +from .idl_definition import IdlDefinition -# https://heycam.github.io/webidl/#idl-interfaces -class CallbackInterface(object): - - def __init__(self, **kwargs): - self._identifier = kwargs.pop('identifier') - self._attributes = tuple(kwargs.pop('attributes', [])) - self._operations = tuple(kwargs.pop('operations', [])) - self._constants = tuple(kwargs.pop('constants', [])) - self._inherited_interface_name = kwargs.pop('inherited_interface_name', None) - self._extended_attribute_list = kwargs.pop('extended_attribute_list', ExtendedAttributeList()) - assert_no_extra_args(kwargs) - - if any(attribute.is_static for attribute in self.attributes): - raise ValueError('Static attributes must not be defined on a callback interface') - if any(operation.is_static for operation in self.operations): - raise ValueError('Static operations must not be defined on a callback interface') +class CallbackInterface(IdlDefinition): + """https://heycam.github.io/webidl/#idl-interfaces""" @property - def identifier(self): - return self._identifier + def inherited_callback_interface(self): + """ + Returns an CallbackInterface which this interface is inherited from. + @return CallbackInterface? + """ + raise exceptions.NotImplementedError() @property - def attributes(self): - return self._attributes - - @property - def operations(self): - return self._operations + def operation_groups(self): + """ + Returns a list of OperationGroup. Each OperationGroup may have an + operation or a set of overloaded operations. + @return tuple(OperationGroup) + """ + raise exceptions.NotImplementedError() @property def constants(self): - return self._constants - - @property - def inherited_interface_name(self): - return self._inherited_interface_name - - @property - def extended_attribute_list(self): - return self._extended_attribute_list + """ + Returns a list of constants. + @return tuple(Constant) + """ + raise exceptions.NotImplementedError()
diff --git a/third_party/blink/renderer/bindings/scripts/web_idl/common.py b/third_party/blink/renderer/bindings/scripts/web_idl/common.py new file mode 100644 index 0000000..0113be3 --- /dev/null +++ b/third_party/blink/renderer/bindings/scripts/web_idl/common.py
@@ -0,0 +1,120 @@ +# 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 exceptions + +Identifier = str + + +class WithIdentifier(object): + """WithIdentifier class is an interface that indicates the class has an + identifier.""" + + @property + def identifier(self): + """ + Returns the identifier. + @return Identifier + """ + raise exceptions.NotImplementedError() + + +# ExtendedAttribute and ExtendedAttributes are defined in extended_attribute.py +class WithExtendedAttributes(object): + """WithExtendedAttributes class is an interface that indicates the implemented + class can have extended attributes.""" + + @property + def extended_attributes(self): + """ + Returns the extended attributes. + @return ExtendedAttributes + """ + raise exceptions.NotImplementedError() + + +class WithCodeGeneratorInfo(object): + """WithCodeGeneratorInfo class is an interface that its inheritances can + provide some information for code generators.""" + + @property + def code_generator_info(self): + """ + Returns information for code generator. + @return dict(TBD) + """ + raise exceptions.NotImplementedError() + + +class WithExposure(object): + """WithExposure class is an interface that its inheritances can have Exposed + extended attributes.""" + + @property + def exposures(self): + """ + Returns a set of Exposure's that are applicable on an object. + https://heycam.github.io/webidl/#Exposed + @return tuple(Expsure) + """ + raise exceptions.NotImplementedError() + + +Component = str + + +class WithComponent(object): + """WithComponent class is an interface to show which components this + object belongs to.""" + + # The order of |_COMPONENTS| shows the order of their dependencies. + # DO NOT change the order. + _COMPONENTS = ( + 'core', + 'modules', + ) + + @property + def components(self): + """ + Returns a list of components' names where this definition is defined + @return tuple(Component) + """ + raise exceptions.NotImplementedError() + + +class DebugInfo(object): + """DebugInfo provides some information for debugging.""" + + @property + def filepaths(self): + """ + Returns a list of filepaths where this IDL definition comes from. + @return tuple(FilePath) + """ + raise exceptions.NotImplementedError() + + +class WithDebugInfo(object): + """WithDebugInfo class is an interface that its inheritances can have DebugInfo.""" + + @property + def debug_info(self): + """Returns DebugInfo.""" + raise exceptions.NotImplementedError() + + +class WithOwner(object): + """WithOwner class provides information about who owns this object. + If this object is a member, it points either of an interface, + a namespace, a dictionary, and so on. If this object is an argument, + it points a function like object.""" + + @property + def owner(self): + """ + Returns the owner of this instance. + @return object(TBD) + """ + raise exceptions.NotImplementedError()
diff --git a/third_party/blink/renderer/bindings/scripts/web_idl/constant.py b/third_party/blink/renderer/bindings/scripts/web_idl/constant.py index a7e4072..502077b 100644 --- a/third_party/blink/renderer/bindings/scripts/web_idl/constant.py +++ b/third_party/blink/renderer/bindings/scripts/web_idl/constant.py
@@ -1,42 +1,26 @@ -# Copyright 2017 The Chromium Authors. All rights reserved. +# 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. -from .extended_attribute import ExtendedAttributeList -from .idl_types import RecordType -from .idl_types import SequenceType -from .utilities import assert_no_extra_args +import exceptions +from .idl_member import IdlMember -# https://heycam.github.io/webidl/#idl-constants -class Constant(object): - _INVALID_IDENTIFIERS = frozenset(['length', 'name', 'prototype']) - _INVALID_TYPES = frozenset([SequenceType, RecordType]) - - def __init__(self, **kwargs): - self._identifier = kwargs.pop('identifier') - self._type = kwargs.pop('type') - self._value = kwargs.pop('value') - self._extended_attribute_list = kwargs.pop('extended_attribute_list', ExtendedAttributeList()) - assert_no_extra_args(kwargs) - - if self.identifier in Constant._INVALID_IDENTIFIERS: - raise ValueError('Invalid identifier for a constant: %s' % self.identifier) - if type(self.type) in Constant._INVALID_TYPES: - raise ValueError('sequence<T> must not be used as the type of a constant.') +class Constant(IdlMember): + """https://heycam.github.io/webidl/#idl-constants""" @property - def identifier(self): - return self._identifier - - @property - def type(self): - return self._type + def idl_type(self): + """ + Returns the type of this constant. + @return IdlType + """ + raise exceptions.NotImplementedError() @property def value(self): - return self._value - - @property - def extended_attribute_list(self): - return self._extended_attribute_list + """ + Returns the constant value. + @return ConstantValue + """ + raise exceptions.NotImplementedError()
diff --git a/third_party/blink/renderer/bindings/scripts/web_idl/constructor.py b/third_party/blink/renderer/bindings/scripts/web_idl/constructor.py new file mode 100644 index 0000000..af71e14a --- /dev/null +++ b/third_party/blink/renderer/bindings/scripts/web_idl/constructor.py
@@ -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. + +import exceptions +from .common import WithComponent +from .common import WithDebugInfo +from .common import WithOwner +from .idl_member import IdlMember + + +class Constrcutor(IdlMember): + def is_custom(self): + """ + Returns True if this Constructor is defined in the form of + [CustomConstructor=(...)] + @return bool + """ + raise exceptions.NotImplementedError() + + @property + def return_type(self): + """ + Returns IDL interface type to construct. + @return IdlInterfaceType + """ + raise exceptions.NotImplementedError() + + @property + def arguments(self): + """ + Returns a list of arguments + @return tuple(Argument) + """ + raise exceptions.NotImplementedError() + + @property + def overloaded_index(self): + """ + Returns its index in ConstructorGroup + @return int + """ + raise exceptions.NotImplementedError() + + +class ConstructorGroup(WithOwner, WithComponent, WithDebugInfo): + def constructors(self): + """ + Returns a list of constructors + @return tuple(Constructor) + """ + raise exceptions.NotImplementedError() + + +class NamedConstructor(WithOwner, WithComponent, WithDebugInfo): + @property + def return_type(self): + """ + Returns IDL type to construct. + @return IdlInterfaceType + """ + raise exceptions.NotImplementedError() + + @property + def name(self): + """ + Returns the name to be visible as. + @return Identifier + """ + raise exceptions.NotImplementedError() + + @property + def arguments(self): + """ + Returns a list of arguments. + @return tuple(Argument) + """ + raise exceptions.NotImplementedError()
diff --git a/third_party/blink/renderer/bindings/scripts/web_idl/dictionary.py b/third_party/blink/renderer/bindings/scripts/web_idl/dictionary.py index 238aaf0..f70a0dc 100644 --- a/third_party/blink/renderer/bindings/scripts/web_idl/dictionary.py +++ b/third_party/blink/renderer/bindings/scripts/web_idl/dictionary.py
@@ -1,69 +1,62 @@ -# Copyright 2017 The Chromium Authors. All rights reserved. +# 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. -from .extended_attribute import ExtendedAttributeList -from .utilities import assert_no_extra_args +import exceptions +from .idl_definition import IdlDefinition +from .idl_member import IdlMember -# https://heycam.github.io/webidl/#idl-dictionaries -class Dictionary(object): - - def __init__(self, **kwargs): - self._identifier = kwargs.pop('identifier') - self._members = kwargs.pop('members', {}) - self._inherited_dictionary_name = kwargs.pop('inherited_dictionary_name', None) - self._is_partial = kwargs.pop('is_partial', False) - self._extended_attribute_list = kwargs.pop('extended_attribute_list', ExtendedAttributeList()) - assert_no_extra_args(kwargs) +class Dictionary(IdlDefinition): + """https://heycam.github.io/webidl/#idl-dictionaries""" @property - def identifier(self): - return self._identifier + def inherited_dictionary(self): + """ + Returns an Dictionary which this dictionary is inherited from. + @return Dictionary + """ + raise exceptions.NotImplementedError() + + @property + def own_members(self): + """ + Returns dictionary members which do not include inherited + Dictionaries' members. + @return tuple(DictionaryMember) + """ + raise exceptions.NotImplementedError() @property def members(self): - return self._members + """ + Returns dictionary members including inherited Dictionaries' members. + @return tuple(DictionaryMember) + """ + raise exceptions.NotImplementedError() + +class DictionaryMember(IdlMember): @property - def inherited_dictionary_name(self): - return self._inherited_dictionary_name - - @property - def is_partial(self): - return self._is_partial - - @property - def extended_attribute_list(self): - return self._extended_attribute_list - - -class DictionaryMember(object): - - def __init__(self, **kwargs): - self._identifier = kwargs.pop('identifier') - self._type = kwargs.pop('type') - self._default_value = kwargs.pop('default_value', None) - self._is_required = kwargs.pop('is_required', False) - self._extended_attribute_list = kwargs.pop('extended_attribute_list', ExtendedAttributeList()) - assert_no_extra_args(kwargs) - - @property - def identifier(self): - return self._identifier - - @property - def type(self): - return self._type - - @property - def default_value(self): - return self._default_value + def idl_type(self): + """ + Returns type of this member. + @return IdlType + """ + raise exceptions.NotImplementedError() @property def is_required(self): - return self._is_required + """ + Returns if this member is required. + @return bool + """ + raise exceptions.NotImplementedError() @property - def extended_attribute_list(self): - return self._extended_attribute_list + def default_value(self): + """ + Returns the default value if it is specified. Otherwise, None + @return DefaultValue? + """ + raise exceptions.NotImplementedError()
diff --git a/third_party/blink/renderer/bindings/scripts/web_idl/enumeration.py b/third_party/blink/renderer/bindings/scripts/web_idl/enumeration.py index 6fccc6d..07fe0b1 100644 --- a/third_party/blink/renderer/bindings/scripts/web_idl/enumeration.py +++ b/third_party/blink/renderer/bindings/scripts/web_idl/enumeration.py
@@ -1,29 +1,18 @@ -# Copyright 2017 The Chromium Authors. All rights reserved. +# 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. -from .extended_attribute import ExtendedAttributeList -from .utilities import assert_no_extra_args +import exceptions +from .idl_definition import IdlDefinition -# https://heycam.github.io/webidl/#idl-enums -class Enumeration(object): - - def __init__(self, **kwargs): - self._identifier = kwargs.pop('identifier') - self._values = kwargs.pop('values', []) - # Extended attributes on enumerations are not allowed in spec, but Blink uses them. - self._extended_attribute_list = kwargs.pop('extended_attribute_list', ExtendedAttributeList()) - assert_no_extra_args(kwargs) - - @property - def identifier(self): - return self._identifier +class Enumeration(IdlDefinition): + """https://heycam.github.io/webidl/#idl-enums""" @property def values(self): - return self._values - - @property - def extended_attribute_list(self): - return self._extended_attribute_list + """ + Returns a list of values listed in this enumeration. + @return tuple(str) + """ + raise exceptions.NotImplementedError()
diff --git a/third_party/blink/renderer/bindings/scripts/web_idl/exposure.py b/third_party/blink/renderer/bindings/scripts/web_idl/exposure.py new file mode 100644 index 0000000..903da5f --- /dev/null +++ b/third_party/blink/renderer/bindings/scripts/web_idl/exposure.py
@@ -0,0 +1,42 @@ +# 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 exceptions + +# Exposure is a part of ExtendedAttribute in a concept, but it should be +# accessible from other classes easily. + + +class Exposure(object): + @property + def global_interfaces(self): + """ + Returns the global interface to be visible in. + @return tuple(Interface) + """ + raise exceptions.NotImplementedError() + + @property + def runtime_enabled_flags(self): + """ + Returns a list of runtime enabled featuers. + @return tuple(str) + """ + raise exceptions.NotImplementedError() + + @property + def origin_trials(self): + """ + Returns a list of origin trial features. + @return tuple(str) + """ + raise exceptions.NotImplementedError() + + @property + def is_secure_context(self): + """ + Return true if the exposure requires secure context. + @return bool + """ + raise exceptions.NotImplementedError()
diff --git a/third_party/blink/renderer/bindings/scripts/web_idl/extended_attribute.py b/third_party/blink/renderer/bindings/scripts/web_idl/extended_attribute.py index 07847734..d22b6e8 100644 --- a/third_party/blink/renderer/bindings/scripts/web_idl/extended_attribute.py +++ b/third_party/blink/renderer/bindings/scripts/web_idl/extended_attribute.py
@@ -1,108 +1,92 @@ -# Copyright 2017 The Chromium Authors. All rights reserved. +# 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. -from .utilities import assert_no_extra_args - - +# This file defines some classes to implement extended attributes # https://heycam.github.io/webidl/#idl-extended-attributes -# To work with [Exposed], [Constructor], [CustomConstrucotr], and [NamedConstructor] easily, we define some classes -# for them in this file. -class ExtendedAttributeList(object): - - def __init__(self, **kwargs): - self._extended_attributes = kwargs.pop('extended_attributes', {}) - self._exposures = tuple(kwargs.pop('exposures', [])) - constructors = kwargs.pop('constructors', []) - self._constructors = tuple([ctor for ctor in constructors if type(ctor) == Constructor]) - self._named_constructors = tuple([ctor for ctor in constructors if type(ctor) == NamedConstructor]) - - if self.exposures: - self._extended_attributes['Exposed'] = self.exposures - if self.named_constructors: - self._extended_attributes['NamedConstructor'] = self.named_constructors - if any(ctor.is_custom for ctor in self.constructors): - self._extended_attributes['CustomConstructor'] = [ctor for ctor in self.constructors if ctor.is_custom] - if any(not ctor.is_custom for ctor in self.constructors): - self._extended_attributes['CustomConstructor'] = [ctor for ctor in self.constructors if not ctor.is_custom] - - def get(self, key): - return self.extended_attributes.get(key) - - def has(self, key): - return key in self.extended_attributes - - @property - def extended_attributes(self): - """ - [Exposed], [Constructor], [CustomConstrucotr], and [NamedConstructor] can be taken with - other property methods, but the returned value of this method also includes them. - """ - return self._extended_attributes - - @property - def constructors(self): - return self._constructors - - @property - def named_constructors(self): - return self._named_constructors - - @property - def exposures(self): - return self._exposures +import exceptions -# https://heycam.github.io/webidl/#Constructor -class Constructor(object): - - def __init__(self, **kwargs): - self._arguments = kwargs.pop('arguments', []) - self._is_custom = kwargs.pop('is_custom', False) - assert_no_extra_args(kwargs) - - @property - def arguments(self): - return self._arguments - - @property - def is_custom(self): - return self._is_custom - - -# https://heycam.github.io/webidl/#NamedConstructor -class NamedConstructor(object): - - def __init__(self, **kwargs): - self._identifier = kwargs.pop('identifier', None) - self._arguments = kwargs.pop('arguments', []) - assert_no_extra_args(kwargs) - - @property - def identifier(self): - return self._identifier - - @property - def arguments(self): - return self._arguments - - -# https://heycam.github.io/webidl/#Exposed -class Exposure(object): - """Exposure holds an exposed target, and can hold a runtime enabled condition. - "[Exposed=global_interface]" is represented as Exposure(global_interface), and - "[Exposed(global_interface runtime_enabled_feature)] is represented as Exposure(global_interface, runtime_enabled_feature). +class ExtendedAttribute(object): + """ExtendedAttribute represents an exnteded attribute, except for attributes + that have their own classes. + i.e. [Constructor], [CustomConstructor], [NamedConstructor], and [Exposed]. + ExtendedAttribute assumes following formats as spec defines. + a. [Key] + b. [Key=Value] + c. [Key=(Value1,Value2,...)] + d. [Key(Type1 Value1, Type2 Value2,...)] + e. [Key=Name(Type1 Value1, Type2 Value2,...)] """ - def __init__(self, **kwargs): - self._global_interface = kwargs.pop('global_interface') - self._runtime_enabled_feature = kwargs.pop('runtime_enabled_feature', None) - assert_no_extra_args(kwargs) @property - def global_interface(self): - return self._global_interface + def key(self): + """ + Returns the key. + @return str + """ + raise exceptions.NotImplementedError() @property - def runtime_enabled_feature(self): - return self._runtime_enabled_feature + def value(self): + """ + Returns the value for (b). Returns None for (a). Crashes otherwise. + @return str + """ + raise exceptions.NotImplementedError() + + @property + def values(self): + """ + Returns a list of values for (b) and (c). Returns an empty list + for (a). Crashes otherwise. + @return tuple(str) + """ + raise exceptions.NotImplementedError() + + @property + def arguments(self): + """ + Returns a tuple of arguments for (d) and (e). Crashes otherwise. + @return tuple(Argument) + """ + raise exceptions.NotImplementedError() + + @property + def name(self): + """ + Returns |Name| for (e). Crashes otherwise. + @return str + """ + raise exceptions.NotImplementedError() + + +class ExtendedAttributes(object): + """ExtendedAttributes is a dict-like container for ExtendedAttribute instances.""" + + def has_key(self, _): + """ + Returns True if this has an extended attribute with the |key|. + @param str key + @return bool + """ + raise exceptions.NotImplementedError() + + def get(self, _): + """ + Returns an exnteded attribute whose key is |key|. + If |self| has no such elements, returns None, + and if |self| has multiple elements, raises an error. + @param str key + @return ExtendedAttriute? + """ + raise exceptions.NotImplementedError() + + def get_list_of(self, _): + """ + Returns a list of extended attributes whose keys are |identifier|. + @param str key + @return tuple(ExtendedAttribute) + """ + raise exceptions.NotImplementedError()
diff --git a/third_party/blink/renderer/bindings/scripts/web_idl/idl_database.py b/third_party/blink/renderer/bindings/scripts/web_idl/idl_database.py new file mode 100644 index 0000000..45ed431 --- /dev/null +++ b/third_party/blink/renderer/bindings/scripts/web_idl/idl_database.py
@@ -0,0 +1,63 @@ +# 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 exceptions + + +class IdlDatabase(object): + @property + def interfaces(self): + """ + Returns a list of non callback interfaces. + @return tuple(Interface) + """ + raise exceptions.NotImplementedError() + + @property + def dictionaries(self): + """ + Returns a list of dictionaries. + @return tuple(Dictionary) + """ + raise exceptions.NotImplementedError() + + @property + def namespaces(self): + """ + Returns a list of namespaces. + @return tuple(Namespace) + """ + raise exceptions.NotImplementedError() + + @property + def callback_functions(self): + """ + Returns a list of callback functions. + @return tuple(CallbackFunction) + """ + raise exceptions.NotImplementedError() + + @property + def callback_interfaces(self): + """ + Returns a list of callback interfaces. + @return tuple(CallbackInterface) + """ + raise exceptions.NotImplementedError() + + @property + def typedefs(self): + """ + Returns a list of typedefs. + @return tuple(Typedef) + """ + raise exceptions.NotImplementedError() + + @property + def union_types(self): + """ + Returns a list of union types. + @return tuple(IdlUnionType) + """ + raise exceptions.NotImplementedError()
diff --git a/third_party/blink/renderer/bindings/scripts/web_idl/idl_definition.py b/third_party/blink/renderer/bindings/scripts/web_idl/idl_definition.py new file mode 100644 index 0000000..7bf9f1c1 --- /dev/null +++ b/third_party/blink/renderer/bindings/scripts/web_idl/idl_definition.py
@@ -0,0 +1,66 @@ +# 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. + +from .common import WithCodeGeneratorInfo +from .common import WithComponent +from .common import WithDebugInfo +from .common import WithExposure +from .common import WithExtendedAttributes +from .common import WithIdentifier + + +class IdlDefinition(WithIdentifier, WithExtendedAttributes, WithExposure, + WithCodeGeneratorInfo, WithComponent, WithDebugInfo): + """ + IdlDefinition provides common APIs for IDL definitions; Interface, Dictionary, + Namespace, CallbackFunction, CallbackInterface, and Enumeration. + """ + + @property + def is_interface(self): + """ + Returns True if |self| is an Interface. + @return bool + """ + return False + + @property + def is_dictionary(self): + """ + Returns True if |self| is a Dictionary. + @return bool + """ + return False + + @property + def is_namespace(self): + """ + Returns True if |self| is a Namespace. + @return bool + """ + return False + + @property + def is_callback_function(self): + """ + Returns True if |self| is a CallbackFunction. + @return bool + """ + return False + + @property + def is_callback_interface(self): + """ + Returns True if |self| is a CallbackInterface. + @return bool + """ + return False + + @property + def is_enumeration(self): + """ + Returns True if |self| is an Enumeration. + @return bool + """ + return False
diff --git a/third_party/blink/renderer/bindings/scripts/web_idl/idl_member.py b/third_party/blink/renderer/bindings/scripts/web_idl/idl_member.py new file mode 100644 index 0000000..4ebf709e --- /dev/null +++ b/third_party/blink/renderer/bindings/scripts/web_idl/idl_member.py
@@ -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. + +from .common import WithCodeGeneratorInfo +from .common import WithComponent +from .common import WithDebugInfo +from .common import WithExposure +from .common import WithExtendedAttributes +from .common import WithIdentifier +from .common import WithOwner + + +class IdlMember(WithIdentifier, WithExtendedAttributes, WithCodeGeneratorInfo, + WithExposure, WithOwner, WithComponent, WithDebugInfo): + """IdlMember provides common APIs for IDL members; attributes, operations, + constants, dictionary members, etc.""" + pass
diff --git a/third_party/blink/renderer/bindings/scripts/web_idl/idl_types.py b/third_party/blink/renderer/bindings/scripts/web_idl/idl_types.py index ab1ead19..9d74125 100644 --- a/third_party/blink/renderer/bindings/scripts/web_idl/idl_types.py +++ b/third_party/blink/renderer/bindings/scripts/web_idl/idl_types.py
@@ -1,341 +1,466 @@ -# Copyright 2017 The Chromium Authors. All rights reserved. +# 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. -from .utilities import assert_no_extra_args +import exceptions +from .common import WithCodeGeneratorInfo +from .common import WithComponent +from .common import WithDebugInfo +from .common import WithExtendedAttributes +from .common import WithIdentifier + +# This file defines following classes to provide IDL types +# +# Classes: +# -IdlType +# - NumberType +# - IntegerType +# - RealNumberType +# - BooleanType +# - StringType +# - AnyType +# - ObjectType +# - VoidType +# - ArrayLikeType +# - SequenceType +# - FrozenArrayType +# - RecordType +# - PromiseType +# - UnionType +# - NullableType +# - AnnotatedType -# Details of each type is described in -# https://heycam.github.io/webidl/#idl-types - -class TypeBase(object): - """ - TypeBase is a base class for all classes for IDL types. - """ - +class IdlType(WithCodeGeneratorInfo): @property def type_name(self): - assert False, 'type_name() is not implemented' + """ + Returns type name as defined in WebIDL spec; e.g. LongLongOrNullClamp + for '[Clamp] long long?'. + @return Identifier + """ + # TODO(peria): Replace with exceptions.NotImplementedError() after shipping. + assert 'type_name() is not implemented for class %s' % (type(self)) - -class AnyType(TypeBase): + # These flags are used for types in args. + @property + def is_optional(self): + """ + Returns True if this type is used in an optional argument. + @return bool + """ + raise exceptions.NotImplementedError() @property - def type_name(self): - return 'Any' + def is_variadic(self): + """ + Returns True if this type is used in a variadic argument. + @return bool + """ + raise exceptions.NotImplementedError() - -class PrimitiveType(TypeBase): - """ - PrimitiveType represents either of integer types, float types, or 'boolean'. - * integer types: byte, octet, (unsigned) short, (unsigned) long, (unsigned) long long - * float types: (unrestricted) float, (unrestricted) double - @param string name : the name of a primitive type - @param bool is_nullable : True if the type is nullable (optional) - @param bool is_clamp : True if the type has [Clamp] annotation (optional) - @param bool is_enforce_range : True if the type has [EnforceRange] annotation (optional) - """ - - _INTEGER_TYPES = frozenset([ - 'byte', 'octet', 'short', 'unsigned short', 'long', 'unsigned long', 'long long', 'unsigned long long' - ]) - _FLOAT_TYPES = frozenset([ - 'float', 'unrestricted float', 'double', 'unrestricted double' - ]) - _PRIMITIVE_TYPES = _INTEGER_TYPES | _FLOAT_TYPES | frozenset(['boolean']) - - def __init__(self, **kwargs): - self._name = kwargs.pop('name') - self._is_nullable = kwargs.pop('is_nullable', False) - self._is_clamp = kwargs.pop('is_clamp', False) - self._is_enforce_range = kwargs.pop('is_enforce_range', False) - assert_no_extra_args(kwargs) - - if self._name not in PrimitiveType._PRIMITIVE_TYPES: - raise ValueError('Unknown type name: %s' % self._name) - if self.is_clamp and self.is_enforce_range: - raise ValueError('[Clamp] and [EnforceRange] cannot be associated together') - if (self.is_clamp or self.is_enforce_range) and not self.is_integer_type: - raise ValueError('[Clamp] or [EnforceRange] cannot be associated with %s' % self._name) - + # Some of following type checkers return True, if |this| meets the + # expectation. @property - def type_name(self): - return ''.join([word.capitalize() for word in self._name.split(' ')]) - - @property - def is_nullable(self): - return self._is_nullable - - @property - def is_clamp(self): - return self._is_clamp - - @property - def is_enforce_range(self): - return self._is_enforce_range + def is_number_type(self): + """ + Returns True if |self| is a NumberType. + @return bool + """ + raise exceptions.NotImplementedError() @property def is_integer_type(self): - return self._name in PrimitiveType._INTEGER_TYPES + """ + Returns True if |self| is an IntegerType. + @return bool + """ + raise exceptions.NotImplementedError() @property - def is_float_type(self): - return self._name in PrimitiveType._FLOAT_TYPES + def is_real_number_type(self): + """ + Returns True if |self| is a RealNumberType. + @return bool + """ + raise exceptions.NotImplementedError() @property - def is_numeric_type(self): - return self.is_integer_type or self.is_float_type - - -class StringType(TypeBase): - """ - StringType represents a string type. - @param StringType.Type string_type : a type of string - @param bool is_nullable : True if the string is nullable (optional) - @param StringType.TreatNullAs treat_null_as : argument of an extended attribute [TreatNullAs] (optional) - """ - STRING_TYPES = ('DOMString', 'ByteString', 'USVString') - TREAT_NULL_AS = ('EmptyString',) - - def __init__(self, **kwargs): - self._string_type = kwargs.pop('string_type') - self._is_nullable = kwargs.pop('is_nullable', False) - self._treat_null_as = kwargs.pop('treat_null_as', None) - assert_no_extra_args(kwargs) - - if self._string_type not in StringType.STRING_TYPES: - raise ValueError('Unknown string type: %s' % self._string_type) - if self.treat_null_as and self.treat_null_as not in StringType.TREAT_NULL_AS: - raise ValueError('Unknown TreatAsNull parameter: %s' % self.treat_null_as) + def is_boolean_type(self): + """ + Returns True if |self| is a BooleanType. + @return bool + """ + raise exceptions.NotImplementedError() @property - def type_name(self): - if self._string_type == 'DOMString': - return 'String' - return self._string_type + def is_string_type(self): + """ + Returns True if |self| is a StringType. + @return bool + """ + raise exceptions.NotImplementedError() @property - def is_nullable(self): - return self._is_nullable + def is_object_type(self): + """ + Returns True if |self| is an ObjectType. + @return bool + """ + raise exceptions.NotImplementedError() @property - def treat_null_as(self): - return self._treat_null_as - - -class ObjectType(TypeBase): - """ - ObjectType represents 'object' type in Web IDL spec. - @param bool is_nullable : True if the type is nullable (optional) - """ - - def __init__(self, **kwargs): - self._is_nullable = kwargs.pop('is_nullable', False) - assert_no_extra_args(kwargs) + def is_any_type(self): + """ + Returns True if |self| is an AnyType. + @return bool + """ + raise exceptions.NotImplementedError() @property - def type_name(self): - return 'Object' + def is_interface_type(self): + """ + Returns True if |self| is an InterfaceType. + @return bool + """ + raise exceptions.NotImplementedError() @property - def is_nullable(self): - return self._is_nullable - - -class SequenceType(TypeBase): - """ - SequenceType represents a sequence type 'sequence<T>' in Web IDL spec. - @param TypeBase element_type : Type of element T - @param bool is_nullable : True if the type is nullable (optional) - """ - - def __init__(self, **kwargs): - self._element_type = kwargs.pop('element_type') - self._is_nullable = kwargs.pop('is_nullable', False) - assert_no_extra_args(kwargs) - - if not isinstance(self.element_type, TypeBase): - raise ValueError('element_type must be an instance of TypeBase inheritances') + def is_dictionary_type(self): + """ + Returns True if |self| is a DictionaryType. + @return bool + """ + raise exceptions.NotImplementedError() @property - def type_name(self): - return self.element_type.type_name + 'Sequence' + def is_namespace_type(self): + """ + Returns True if |self| is a NamespaceType. + @return bool + """ + raise exceptions.NotImplementedError() @property - def is_nullable(self): - return self._is_nullable + def is_enumeration_type(self): + """ + Returns True if |self| is an EnumerationType. + @return bool + """ + raise exceptions.NotImplementedError() @property + def is_callback_interface_type(self): + """ + Returns True if |self| is a CallbackInterfaceType. + @return bool + """ + raise exceptions.NotImplementedError() + + @property + def is_callback_function_type(self): + """ + Returns True if |self| is a CallbackFunctionType. + @return bool + """ + raise exceptions.NotImplementedError() + + @property + def is_void_type(self): + """ + Returns True if |self| is a VoidType. + @return bool + """ + raise exceptions.NotImplementedError() + + @property + def is_nullable_type(self): + """ + Returns True if |self| is a NullableType. + @return bool + """ + raise exceptions.NotImplementedError() + + @property + def is_annotated_type(self): + """ + Returns True if |self| is an AnnotatedType. + @return bool + """ + raise exceptions.NotImplementedError() + + @property + def is_promise_type(self): + """ + Returns True if |self| is a PromiseType. + @return bool + """ + raise exceptions.NotImplementedError() + + @property + def is_record_type(self): + """ + Returns True if |self| is a RecordType. + @return bool + """ + raise exceptions.NotImplementedError() + + @property + def is_sequence_type(self): + """ + Returns True if |self| is a SequenceType. + @return bool + """ + raise exceptions.NotImplementedError() + + @property + def is_union_type(self): + """ + Returns True if |self| is a UnionType. + @return bool + """ + raise exceptions.NotImplementedError() + + @property + def typedefs(self): + """ + Returns Typedef instances which directly point this type. + @return tuple(Typedef) + """ + raise exceptions.NotImplementedError() + + @property + def inner_type(self): + """ + Returns inner type if |this| is a nullable or an annotated type. + @return IdlType? + """ + raise exceptions.NotImplementedError() + + # One of following methods returns an instance, if |this| refers a definition. + @property + def interface(self): + """ + Returns the interface that |self| points if |self| is an InterfaceType. + @return Interface + """ + raise exceptions.NotImplementedError() + + @property + def dictionary(self): + """ + Returns the dictionary that |self| points if |self| is an DictionaryType. + @return Dictionary + """ + raise exceptions.NotImplementedError() + + @property + def namespace(self): + """ + Returns the namespace that |self| points if |self| is an NamespaceType. + @return Namespace + """ + raise exceptions.NotImplementedError() + + @property + def enumeration(self): + """ + Returns the enumeration that |self| points if |self| is an EnumerationType. + @return Enumeration + """ + raise exceptions.NotImplementedError() + + @property + def callback_interface(self): + """ + Returns the callback interface that |self| points if |self| is an CallbackInterfaceType. + @return CallbackInterface + """ + raise exceptions.NotImplementedError() + + @property + def callback_function(self): + """ + Returns the callback function that |self| points if |self| is an CallbackFunctionType. + @return CallbackFunction + """ + raise exceptions.NotImplementedError() + + +class NumberType(IdlType, WithIdentifier): + """https://heycam.github.io/webidl/#idl-types""" + + # IdlType overrides + @property + def is_number_type(self): + raise exceptions.NotImplementedError() + + +class IntegerType(IdlType, WithIdentifier): + """https://heycam.github.io/webidl/#idl-types""" + + # IdlType overrides + @property + def is_integer_type(self): + raise exceptions.NotImplementedError() + + +class RealNumberType(IdlType, WithIdentifier): + """https://heycam.github.io/webidl/#idl-types""" + + @property + def is_unrestricted(self): + """ + Returns True if 'unrestricted' is specified. + @return bool + """ + raise exceptions.NotImplementedError() + + # IdlType overrides + @property + def is_real_number_type(self): + raise exceptions.NotImplementedError() + + +class BooleanType(IdlType, WithIdentifier): + """https://heycam.github.io/webidl/#idl-types""" + + # IdlType overrides + @property + def is_boolean_type(self): + raise exceptions.NotImplementedError() + + +class StringType(IdlType, WithIdentifier): + """https://heycam.github.io/webidl/#idl-types""" + + # IdlType overrides + @property + def is_string_type(self): + raise exceptions.NotImplementedError() + + +class AnyType(IdlType): + + # IdlType overrides + @property + def is_any_type(self): + raise exceptions.NotImplementedError() + + +class ObjectType(IdlType): + # IdlType overrides + @property + def is_object_type(self): + raise exceptions.NotImplementedError() + + +class VoidType(IdlType): + # IdlType overrides + @property + def is_void_type(self): + raise exceptions.NotImplementedError() + + +class ArrayLikeType(IdlType): + @property def element_type(self): - return self._element_type + raise exceptions.NotImplementedError() -class RecordType(TypeBase): - """ - RecordType represents a record type 'record<K, V>' in Web IDL spec. - @param StringType key_type : Type of key K - @param TypeBase value_type : Type of value V - @param bool is_nullable : True if the record type is nullable (optional) - """ - - def __init__(self, **kwargs): - self._key_type = kwargs.pop('key_type') - self._value_type = kwargs.pop('value_type') - self._is_nullable = kwargs.pop('is_nullable', False) - assert_no_extra_args(kwargs) - - if type(self.key_type) != StringType: - raise ValueError('key_type parameter must be an instance of StringType.') - if not isinstance(self.value_type, TypeBase): - raise ValueError('value_type parameter must be an instance of TypeBase inheritances.') - +class SequenceType(ArrayLikeType): + # IdlType overrides @property - def type_name(self): - return self.key_type.type_name + self.value_type.type_name + 'Record' + def is_sequence_type(self): + raise exceptions.NotImplementedError() + +class FrozenArrayType(ArrayLikeType): + # IdlType overrides + @property + def is_frozen_array_type(self): + raise exceptions.NotImplementedError() + + +class RecordType(IdlType): @property def key_type(self): - return self._key_type + """ + Returns the key type. + @return IdlType + """ + raise exceptions.NotImplementedError() @property def value_type(self): - return self._value_type + """ + Returns the value type. + @return IdlType + """ + raise exceptions.NotImplementedError() + # IdlType overrides @property - def is_nullable(self): - return self._is_nullable + def is_record_type(self): + raise exceptions.NotImplementedError() -class PromiseType(TypeBase): - """ - PromiseType represents a promise type 'promise<T>' in Web IDL spec. - @param TypeBase result_type : Type of the promise's result V - """ - - def __init__(self, **kwargs): - self._result_type = kwargs.pop('result_type') - assert_no_extra_args(kwargs) - - @property - def type_name(self): - return self.result_type.type_name + 'Promise' - +class PromiseType(IdlType): @property def result_type(self): - return self._result_type + """ + Returns the result type. + @return IdlType + """ + raise exceptions.NotImplementedError() - -class UnionType(TypeBase): - """ - UnionType represents a union type in Web IDL spec. - @param [TypeBase] member_types : List of member types - @param bool is_nullable : True if the type is nullable (optional) - """ - - def __init__(self, **kwargs): - def count_nullable_member_types(): - number = 0 - for member in self.member_types: - if type(member) == UnionType: - number = number + member.number_of_nullable_member_types - elif type(member) not in (AnyType, PromiseType) and member.is_nullable: - number = number + 1 - return number - - self._member_types = tuple(kwargs.pop('member_types')) - self._is_nullable = kwargs.pop('is_nullable', False) - self._number_of_nullable_member_types = count_nullable_member_types() # pylint: disable=invalid-name - assert_no_extra_args(kwargs) - - if len(self.member_types) < 2: - raise ValueError('Union type must have 2 or more member types, but got %d.' % len(self.member_types)) - if any(type(member) == AnyType for member in self.member_types): - raise ValueError('any type must not be used as a union member type.') - if self.number_of_nullable_member_types > 1: - raise ValueError('The number of nullable member types of a union type must be 0 or 1, but %d' % - self.number_of_nullable_member_types) - + # IdlType overrides @property - def type_name(self): - return 'Or'.join(member.type_name for member in self.member_types) + def is_promise_type(self): + raise exceptions.NotImplementedError() + +class UnionType(IdlType, WithComponent, WithDebugInfo): @property def member_types(self): - return self._member_types - - @property - def is_nullable(self): - return self._is_nullable - - @property - def number_of_nullable_member_types(self): - return self._number_of_nullable_member_types + """ + Returns a list of member types. + @return tuple(IdlType) + """ + raise exceptions.NotImplementedError() @property def flattened_member_types(self): - flattened = set() - # TODO(peria): In spec, we have to remove type annotations and nullable flags. - for member in self.member_types: - if type(member) != UnionType: - flattened.add(member) - else: - flattened.update(member.flattened_member_types) - return flattened + """ + Returns a set of flattened member types. + https://heycam.github.io/webidl/#dfn-flattened-union-member-types + @return set(IdlType) + """ + raise exceptions.NotImplementedError() + + # IdlType overrides + @property + def is_union_type(self): + raise exceptions.NotImplementedError() -class FrozenArrayType(TypeBase): - """ - FrozenArrayType represents a frozen array type 'FrozenArray<T>' in Web IDL. - @param TypeBase element_type : Type of element T - @param bool is_nullable : True if the type is nullable (optional) - """ - - def __init__(self, **kwargs): - self._element_type = kwargs.pop('element_type') - self._is_nullable = kwargs.pop('is_nullable', False) - assert_no_extra_args(kwargs) +class NullableType(IdlType): + # IdlType overrides + @property + def is_nullable_type(self): + raise exceptions.NotImplementedError() @property - def type_name(self): - return self.element_type.type_name + 'Array' + def inner_type(self): + raise exceptions.NotImplementedError() + + +class AnnotatedType(IdlType, WithExtendedAttributes): + # IdlType overrides + @property + def is_annotated_type(self): + raise exceptions.NotImplementedError() @property - def element_type(self): - return self._element_type - - @property - def is_nullable(self): - return self._is_nullable - - -class VoidType(TypeBase): - - @property - def type_name(self): - return 'Void' - - -class TypePlaceHolder(TypeBase): - """ - TypePlaceHolder is a pseudo type as a place holder of types which use identifers; - interface types, dictionary types, enumeration types, and callback function types. - Because it is not guaranteed that we have a definition of target defintions when - we meet the type used, we use this class as a place holder. - All place holders will be replaced with references after all the defintions in - all components are collected. - @param string identifier : the identifier of a named definition to refer - @param bool is_nullable : True if the type is nullable (optional) - """ - - def __init__(self, **kwargs): - self._identifier = kwargs.pop('identifier') - self._is_nullable = kwargs.pop('is_nullable', False) - assert_no_extra_args(kwargs) - - @property - def type_name(self): - return self._identifier - - @property - def is_nullable(self): - return self._is_nullable + def inner_type(self): + raise exceptions.NotImplementedError()
diff --git a/third_party/blink/renderer/bindings/scripts/web_idl/includes.py b/third_party/blink/renderer/bindings/scripts/web_idl/includes.py new file mode 100644 index 0000000..ab433fa --- /dev/null +++ b/third_party/blink/renderer/bindings/scripts/web_idl/includes.py
@@ -0,0 +1,27 @@ +# 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 exceptions +from .common import WithComponent +from .common import WithDebugInfo + + +class Includes(WithComponent, WithDebugInfo): + """https://heycam.github.io/webidl/#include""" + + @property + def interface(self): + """ + Returns the interface that includes the mixin. + @return Interface + """ + raise exceptions.NotImplementedError() + + @property + def mixin(self): + """ + Returns the interface mixin that is included by the other. + @return Interface + """ + raise exceptions.NotImplementedError()
diff --git a/third_party/blink/renderer/bindings/scripts/web_idl/interface.py b/third_party/blink/renderer/bindings/scripts/web_idl/interface.py index 573c2d87..90e031f 100644 --- a/third_party/blink/renderer/bindings/scripts/web_idl/interface.py +++ b/third_party/blink/renderer/bindings/scripts/web_idl/interface.py
@@ -1,176 +1,251 @@ -# Copyright 2017 The Chromium Authors. All rights reserved. +# 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. -from .extended_attribute import ExtendedAttributeList -from .utilities import assert_no_extra_args +import exceptions +from .idl_definition import IdlDefinition +from .idl_member import IdlMember -# https://heycam.github.io/webidl/#idl-interfaces -class Interface(object): +class Interface(IdlDefinition): + """A summarized interface definition in IDL. - def __init__(self, **kwargs): - self._identifier = kwargs.pop('identifier') - self._attributes = tuple(kwargs.pop('attributes', [])) - self._operations = tuple(kwargs.pop('operations', [])) - self._constants = tuple(kwargs.pop('constants', [])) - self._iterable = kwargs.pop('iterable', None) - self._maplike = kwargs.pop('maplike', None) - self._setlike = kwargs.pop('setlike', None) - # BUG(736332): Remove support of legacy serializer members. - self._serializer = kwargs.pop('serializer', None) - self._inherited_interface_name = kwargs.pop('inherited_interface_name', None) - self._is_partial = kwargs.pop('is_partial', False) - self._extended_attribute_list = kwargs.pop('extended_attribute_list', ExtendedAttributeList()) - assert_no_extra_args(kwargs) - - num_declaration = (1 if self.iterable else 0) + (1 if self.maplike else 0) + (1 if self.setlike else 0) - if num_declaration > 1: - raise ValueError('At most one of iterable<>, maplike<>, or setlike<> must be applied.') + Interface provides information about an interface, partial interfaces, + interface mixins, and partial interface mixins, as if they were all + gathered in an interface. + https://heycam.github.io/webidl/#idl-interfaces + """ @property - def identifier(self): - return self._identifier + def inherited_interface(self): + """ + Returns an Interface from which this interface inherits. If this + interface does not inherit, returns None. + @return Interface? + """ + raise exceptions.NotImplementedError() @property def attributes(self): - return self._attributes + """ + Returns a tuple of attributes including [Unforgeable] attributes in + ancestors. + @return tuple(Attribute) + """ + raise exceptions.NotImplementedError() @property - def operations(self): - return self._operations + def operation_groups(self): + """ + Returns a tuple of OperationGroup. Each OperationGroup has operation(s) + defined in this interface and [Unforgeable] operations in ancestors. + @return tuple(OperationGroup) + """ + raise exceptions.NotImplementedError() @property def constants(self): - return self._constants - - @property - def iterable(self): - return self._iterable - - @property - def maplike(self): - return self._maplike - - @property - def setlike(self): - return self._setlike - - @property - def serializer(self): - return self._serializer - - @property - def inherited_interface_name(self): - return self._inherited_interface_name - - @property - def is_partial(self): - return self._is_partial + """ + Returns a tuple of constants defined in this interface. + @return tuple(Constant) + """ + raise exceptions.NotImplementedError() @property def constructors(self): - return self.extended_attribute_list.constructors + """ + Returns ConstructorGroup instance for this interface. + @return tuple(ConstructorGroup) + """ + raise exceptions.NotImplementedError() @property - def named_constructors(self): - return self.extended_attribute_list.named_constructors + def named_constructor(self): + """ + Returns a named constructor, if this interface has it. Otherwise, returns + None. + @return NamedConstructor? + """ + raise exceptions.NotImplementedError() @property - def exposures(self): - return self.extended_attribute_list.exposures + def exposed_interfaces(self): + """ + Returns a tuple of Interfaces that are exposed to |self|. If |self| is + not a global interface, returns an empty tuple. + @return tuple(Interface) + """ + raise exceptions.NotImplementedError() + + # Special operations + @property + def indexed_property_handler(self): + """ + Returns a set of handlers (getter/setter/deleter) for the indexed + property. + @return IndexedPropertyHandler? + """ + # TODO: Include anonymous handlers of ancestors. https://crbug.com/695972 + raise exceptions.NotImplementedError() @property - def extended_attribute_list(self): - return self._extended_attribute_list + def named_property_handler(self): + """ + Returns a set of handlers (getter/setter/deleter) for the named + property. + @return NamedPropertyHandler? + """ + # TODO: Include anonymous handlers of ancestors. https://crbug.com/695972 + raise exceptions.NotImplementedError() + + @property + def stringifier(self): + """ + Returns stringifier if it is defined. Returns None otherwise. + @return TBD? + """ + raise exceptions.NotImplementedError() + + @property + def iterable(self): + """ + Returns iterable if it is defined. Returns None otherwise. + @return Iterable? + """ + raise exceptions.NotImplementedError() + + @property + def maplike(self): + """ + Returns maplike if it is defined. Returns None otherwise. + @return Maplike? + """ + raise exceptions.NotImplementedError() + + @property + def setlike(self): + """ + Returns setlike if it is defined. Returns None otherwise. + @return Setlike? + """ + raise exceptions.NotImplementedError() -# https://heycam.github.io/webidl/#idl-iterable -class Iterable(object): - - def __init__(self, **kwargs): - self._key_type = kwargs.pop('key_type', None) - self._value_type = kwargs.pop('value_type') - self._extended_attribute_list = kwargs.pop('extended_attribute_list', ExtendedAttributeList()) - assert_no_extra_args(kwargs) +class Iterable(IdlMember): + """https://heycam.github.io/webidl/#idl-iterable""" @property def key_type(self): - return self._key_type + """ + Returns its key type or None. + @return IdlType? + """ + raise exceptions.NotImplementedError() @property def value_type(self): - return self._value_type - - @property - def extended_attribute_list(self): - return self._extended_attribute_list + """ + Returns its value type. + @return IdlType + """ + raise exceptions.NotImplementedError() -# https://heycam.github.io/webidl/#idl-maplike class Maplike(object): - - def __init__(self, **kwargs): - self._key_type = kwargs.pop('key_type') - self._value_type = kwargs.pop('value_type') - self._is_readonly = kwargs.pop('is_readonly', False) - assert_no_extra_args(kwargs) + """https://heycam.github.io/webidl/#idl-maplike""" @property def key_type(self): - return self._key_type + """ + Returns its key type. + @return IdlType + """ + raise exceptions.NotImplementedError() @property def value_type(self): - return self._value_type + """ + Returns its value type. + @return IdlType + """ + raise exceptions.NotImplementedError() @property def is_readonly(self): - return self._is_readonly + """ + Returns True if it's readonly. + @return bool + """ + raise exceptions.NotImplementedError() -# https://heycam.github.io/webidl/#idl-setlike class Setlike(object): - - def __init__(self, **kwargs): - self._value_type = kwargs.pop('value_type') - self._is_readonly = kwargs.pop('is_readonly', False) - assert_no_extra_args(kwargs) + """https://heycam.github.io/webidl/#idl-setlike""" @property def value_type(self): - return self._value_type + """ + Returns its value type. + @return IdlType + """ + raise exceptions.NotImplementedError() @property def is_readonly(self): - return self._is_readonly + """ + Returns True if it's readonly. + @return bool + """ + raise exceptions.NotImplementedError() -# https://www.w3.org/TR/WebIDL-1/#idl-serializers -# BUG(736332): Remove support of legacy serializer. -# We support styles only used in production code. i.e. -# - serializer; -# - serializer = { attribute }; -# - serializer = { inherit, attribute }; -class Serializer(object): - - def __init__(self, **kwargs): - self._is_map = kwargs.pop('is_map', False) - self._has_attribute = kwargs.pop('has_attribute', False) - self._has_inherit = kwargs.pop('has_inherit', False) - assert_no_extra_args(kwargs) - - if (self.has_attribute or self.has_inherit) and not self._is_map: - raise ValueError('has_attribute and has_inherit must be set with is_map') +class IndexedPropertyHandler(IdlMember): + @property + def getter(self): + """ + Returns an Operation for indexed property getter. + @return Operation? + """ + raise exceptions.NotImplementedError() @property - def is_map(self): - return self._is_map + def setter(self): + """ + Returns an Operation for indexed property setter. + @return Operation? + """ + raise exceptions.NotImplementedError() @property - def has_attribute(self): - return self._has_attribute + def deleter(self): + """ + Returns an Operation for indexed property deleter. + @return Operation? + """ + raise exceptions.NotImplementedError() + + +class NamedPropertyHandler(IdlMember): + @property + def getter(self): + """ + Returns an Operation for named property getter. + @return Operation? + """ + raise exceptions.NotImplementedError() @property - def has_inherit(self): - return self._has_inherit + def setter(self): + """ + Returns an Operation for named property setter. + @return Operation? + """ + raise exceptions.NotImplementedError() + + @property + def deleter(self): + """ + Returns an Operation for named property deleter. + @return Operation? + """ + raise exceptions.NotImplementedError()
diff --git a/third_party/blink/renderer/bindings/scripts/web_idl/namespace.py b/third_party/blink/renderer/bindings/scripts/web_idl/namespace.py index ebafdc7..d339663 100644 --- a/third_party/blink/renderer/bindings/scripts/web_idl/namespace.py +++ b/third_party/blink/renderer/bindings/scripts/web_idl/namespace.py
@@ -1,42 +1,35 @@ -# Copyright 2017 The Chromium Authors. All rights reserved. +# 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. -from .extended_attribute import ExtendedAttributeList -from .utilities import assert_no_extra_args +import exceptions +from .idl_definition import IdlDefinition -# https://heycam.github.io/webidl/#idl-namespaces -class Namespace(object): - - def __init__(self, **kwargs): - self._identifier = kwargs.pop('identifier') - self._attributes = tuple(kwargs.pop('attributes', [])) - self._operations = tuple(kwargs.pop('operations', [])) - self._is_partial = kwargs.pop('is_partial', False) - self._extended_attribute_list = kwargs.pop('extended_attribute_list', ExtendedAttributeList()) - assert_no_extra_args(kwargs) - - @property - def identifier(self): - return self._identifier +class Namespace(IdlDefinition): + """https://heycam.github.io/webidl/#idl-namespaces""" @property def attributes(self): - return self._attributes + """ + Returns a list of attributes. + @return tuple(Attribute) + """ + raise exceptions.NotImplementedError() @property - def operations(self): - return self._operations + def operation_groups(self): + """ + Returns a list of OperationGroup. Each OperationGroup may have an operation + or a set of overloaded operations. + @return tuple(OperationGroup) + """ + raise exceptions.NotImplementedError() @property - def exposures(self): - return self.extended_attribute_list.exposures - - @property - def is_partial(self): - return self._is_partial - - @property - def extended_attribute_list(self): - return self._extended_attribute_list + def constants(self): + """ + Returns a list of constants. + @return tuple(Constant) + """ + raise exceptions.NotImplementedError()
diff --git a/third_party/blink/renderer/bindings/scripts/web_idl/operation.py b/third_party/blink/renderer/bindings/scripts/web_idl/operation.py index df46bc2..66faa99b 100644 --- a/third_party/blink/renderer/bindings/scripts/web_idl/operation.py +++ b/third_party/blink/renderer/bindings/scripts/web_idl/operation.py
@@ -1,56 +1,66 @@ -# Copyright 2017 The Chromium Authors. All rights reserved. +# 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. -from .extended_attribute import ExtendedAttributeList -from .utilities import assert_no_extra_args +import exceptions +from .common import WithCodeGeneratorInfo +from .common import WithComponent +from .common import WithDebugInfo +from .common import WithIdentifier +from .common import WithOwner +from .idl_member import IdlMember -# https://heycam.github.io/webidl/#idl-operations -class Operation(object): - # https://www.w3.org/TR/WebIDL-1/#idl-special-operations - _SPECIAL_KEYWORDS = frozenset(['deleter', 'getter', 'setter', 'stringifier', 'serializer']) - - def __init__(self, **kwargs): - self._identifier = kwargs.pop('identifier') - self._return_type = kwargs.pop('return_type') - self._arguments = tuple(kwargs.pop('arguments', [])) - self._special_keywords = frozenset(kwargs.pop('special_keywords', [])) - self._is_static = kwargs.pop('is_static', False) - self._extended_attribute_list = kwargs.pop('extended_attribute_list', ExtendedAttributeList()) - assert_no_extra_args(kwargs) - - if any(keyword not in Operation._SPECIAL_KEYWORDS for keyword in self._special_keywords): - raise ValueError('Unknown keyword is specified in special keywords') - - @property - def identifier(self): - return self._identifier - - @property - def return_type(self): - return self._return_type - - @property - def arguments(self): - return self._arguments - - @property - def special_keywords(self): - return self._special_keywords +class Operation(IdlMember): + """https://heycam.github.io/webidl/#idl-operations + https://www.w3.org/TR/WebIDL-1/#idl-special-operations""" @property def is_static(self): - return self._is_static + """ + Returns True if 'static' is specified. + @return bool + """ + raise exceptions.NotImplementedError() @property - def extended_attribute_list(self): - return self._extended_attribute_list + def return_type(self): + """ + Returns the type of return value. + @return IdlType + """ + raise exceptions.NotImplementedError() @property - def is_regular(self): - return self.identifier and not self.is_static + def arguments(self): + """ + Returns a list of arguments. + @return tuple(Argument) + """ + raise exceptions.NotImplementedError() @property - def is_special(self): - return bool(self.special_keywords) + def overloaded_index(self): + """ + Returns the index in the OperationGroup that |self| belongs to. + @return int + """ + raise exceptions.NotImplementedError() + + +class OperationGroup(WithIdentifier, WithCodeGeneratorInfo, WithOwner, + WithComponent, WithDebugInfo): + """ + OperationGroup class has all Operation's with a same identifier, even if the + operation is not overloaded. Then we can handle overloaded and + non-overloaded operations seamlessly. + From the ES bindings' view point, OperationGroup tells something for properties, + and Operation tells something for actual behaviors. + """ + + def operations(self): + """ + Returns a list of operations whose identifier is |identifier()| + @return tuple(Operation) + """ + raise exceptions.NotImplementedError()
diff --git a/third_party/blink/renderer/bindings/scripts/web_idl/typedef.py b/third_party/blink/renderer/bindings/scripts/web_idl/typedef.py index fd38ca99..912d153 100644 --- a/third_party/blink/renderer/bindings/scripts/web_idl/typedef.py +++ b/third_party/blink/renderer/bindings/scripts/web_idl/typedef.py
@@ -2,21 +2,21 @@ # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. -from .utilities import assert_no_extra_args +import exceptions +from .common import WithCodeGeneratorInfo +from .common import WithComponent +from .common import WithDebugInfo +from .common import WithIdentifier -# https://heycam.github.io/webidl/#idl-typedefs -class Typedef(object): - - def __init__(self, **kwargs): - self._identifier = kwargs.pop('identifier') - self._type = kwargs.pop('type') - assert_no_extra_args(kwargs) +class Typedef(WithIdentifier, WithCodeGeneratorInfo, WithComponent, + WithDebugInfo): + """https://heycam.github.io/webidl/#idl-typedefs""" @property - def identifier(self): - return self._identifier - - @property - def type(self): - return self._type + def idl_type(self): + """ + Returns the type to have an alias. + @return IdlType + """ + raise exceptions.NotImplementedError()
diff --git a/third_party/blink/renderer/bindings/scripts/web_idl/values.py b/third_party/blink/renderer/bindings/scripts/web_idl/values.py new file mode 100644 index 0000000..0cc446b --- /dev/null +++ b/third_party/blink/renderer/bindings/scripts/web_idl/values.py
@@ -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. + +import exceptions + + +class DefaultValue(object): + def idl_type(self): + """ + Returns either of string, number, boolean(true/false), null, and sequence[]. + @return IdlType + """ + raise exceptions.NotImplementedError() + + def value(self): + """ + Returns the default value. Actual type depends on the value itself. + @return object(TBD) + """ + raise exceptions.NotImplementedError() + + +class ConstantValue(object): + def idl_type(self): + """ + Returns either of string, number, boolean(true/false), null, and sequence[]. + @return IdlType + """ + raise exceptions.NotImplementedError() + + def value(self): + """ + Returns the default value. Actual type depends on the value itself. + @return object(TBD) + """ + raise exceptions.NotImplementedError()
diff --git a/third_party/blink/renderer/bindings/templates/origin_trial_features_for_core.cc.tmpl b/third_party/blink/renderer/bindings/templates/origin_trial_features_for_core.cc.tmpl index cb37e80..ddb012a1 100644 --- a/third_party/blink/renderer/bindings/templates/origin_trial_features_for_core.cc.tmpl +++ b/third_party/blink/renderer/bindings/templates/origin_trial_features_for_core.cc.tmpl
@@ -60,7 +60,7 @@ {% endfor %} } -void InstallPendingOriginTrialFeatureForCore(const String& feature, +void InstallPendingOriginTrialFeatureForCore(OriginTrialFeature feature, const ScriptState* script_state) { (*g_old_install_pending_origin_trial_feature_function)(feature, script_state); @@ -72,23 +72,28 @@ v8::Isolate* isolate = script_state->GetIsolate(); const DOMWrapperWorld& world = script_state->World(); V8PerContextData* context_data = script_state->PerContextData(); - {% for feature in installers_by_feature %} - if (feature == {{feature.name_constant}}) { - {% for installer in feature.installers %} - {% if installer.interface_is_global %} - {{installer.v8_class_or_partial}}::{{installer.install_method}}( - isolate, world, script_state->GetContext()->Global(), - v8::Local<v8::Object>(), v8::Local<v8::Function>()); - {% else %} - if (context_data->GetExistingConstructorAndPrototypeForType( - {{installer.v8_class}}::GetWrapperTypeInfo(), &prototype_object, &interface_object)) { + switch (feature) { + {% for feature in installers_by_feature %} + case {{feature.name_constant}}: { + {% for installer in feature.installers %} + {% if installer.interface_is_global %} {{installer.v8_class_or_partial}}::{{installer.install_method}}( - isolate, world, v8::Local<v8::Object>(), prototype_object, interface_object); + isolate, world, script_state->GetContext()->Global(), + v8::Local<v8::Object>(), v8::Local<v8::Function>()); + {% else %} + if (context_data->GetExistingConstructorAndPrototypeForType( + {{installer.v8_class}}::GetWrapperTypeInfo(), &prototype_object, &interface_object)) { + {{installer.v8_class_or_partial}}::{{installer.install_method}}( + isolate, world, v8::Local<v8::Object>(), prototype_object, interface_object); + } + {% endif %} + {% endfor %} + break; } - {% endif %} {% endfor %} + default: + break; } - {% endfor %} {% endif %} }
diff --git a/third_party/blink/renderer/bindings/templates/origin_trial_features_for_modules.cc.tmpl b/third_party/blink/renderer/bindings/templates/origin_trial_features_for_modules.cc.tmpl index dc8b78a..9f4921b 100644 --- a/third_party/blink/renderer/bindings/templates/origin_trial_features_for_modules.cc.tmpl +++ b/third_party/blink/renderer/bindings/templates/origin_trial_features_for_modules.cc.tmpl
@@ -51,7 +51,7 @@ } void InstallPendingOriginTrialFeatureForModules( - const String& feature, + OriginTrialFeature feature, const ScriptState* script_state) { (*g_original_install_pending_origin_trial_feature_function)(feature, script_state); @@ -64,23 +64,28 @@ v8::Isolate* isolate = script_state->GetIsolate(); const DOMWrapperWorld& world = script_state->World(); V8PerContextData* context_data = script_state->PerContextData(); - {% for feature in installers_by_feature %} - if (feature == {{feature.name_constant}}) { - {% for installer in feature.installers %} - {% if installer.interface_is_global %} - {{installer.v8_class_or_partial}}::{{installer.install_method}}( - isolate, world, script_state->GetContext()->Global(), - v8::Local<v8::Object>(), v8::Local<v8::Function>()); - {% else %} - if (context_data->GetExistingConstructorAndPrototypeForType( - {{installer.v8_class}}::GetWrapperTypeInfo(), &prototype_object, &interface_object)) { + switch (feature) { + {% for feature in installers_by_feature %} + case {{feature.name_constant}}: { + {% for installer in feature.installers %} + {% if installer.interface_is_global %} {{installer.v8_class_or_partial}}::{{installer.install_method}}( - isolate, world, v8::Local<v8::Object>(), prototype_object, interface_object); + isolate, world, script_state->GetContext()->Global(), + v8::Local<v8::Object>(), v8::Local<v8::Function>()); + {% else %} + if (context_data->GetExistingConstructorAndPrototypeForType( + {{installer.v8_class}}::GetWrapperTypeInfo(), &prototype_object, &interface_object)) { + {{installer.v8_class_or_partial}}::{{installer.install_method}}( + isolate, world, v8::Local<v8::Object>(), prototype_object, interface_object); + } + {% endif %} + {% endfor %} + break; } - {% endif %} {% endfor %} + default: + break; } - {% endfor %} {% endif %} }
diff --git a/third_party/blink/renderer/bindings/tests/results/core/origin_trial_features_for_core.cc b/third_party/blink/renderer/bindings/tests/results/core/origin_trial_features_for_core.cc index 33e78fb..9f2cb3a 100644 --- a/third_party/blink/renderer/bindings/tests/results/core/origin_trial_features_for_core.cc +++ b/third_party/blink/renderer/bindings/tests/results/core/origin_trial_features_for_core.cc
@@ -21,6 +21,7 @@ #include "third_party/blink/renderer/platform/bindings/origin_trial_features.h" #include "third_party/blink/renderer/platform/bindings/script_state.h" #include "third_party/blink/renderer/platform/bindings/v8_per_context_data.h" +#include "third_party/blink/renderer/platform/runtime_enabled_features.h" namespace blink { @@ -72,7 +73,7 @@ } } -void InstallPendingOriginTrialFeatureForCore(const String& feature, +void InstallPendingOriginTrialFeatureForCore(OriginTrialFeature feature, const ScriptState* script_state) { (*g_old_install_pending_origin_trial_feature_function)(feature, script_state); @@ -83,19 +84,25 @@ v8::Isolate* isolate = script_state->GetIsolate(); const DOMWrapperWorld& world = script_state->World(); V8PerContextData* context_data = script_state->PerContextData(); - if (feature == origin_trials::kFeatureNameTrialName) { - if (context_data->GetExistingConstructorAndPrototypeForType( - V8TestObject::GetWrapperTypeInfo(), &prototype_object, &interface_object)) { - V8TestObject::InstallFeatureName( - isolate, world, v8::Local<v8::Object>(), prototype_object, interface_object); + switch (feature) { + case OriginTrialFeature::kFeatureName: { + if (context_data->GetExistingConstructorAndPrototypeForType( + V8TestObject::GetWrapperTypeInfo(), &prototype_object, &interface_object)) { + V8TestObject::InstallFeatureName( + isolate, world, v8::Local<v8::Object>(), prototype_object, interface_object); + } + break; } - } - if (feature == origin_trials::kTestFeatureTrialName) { - if (context_data->GetExistingConstructorAndPrototypeForType( - V8TestInterface::GetWrapperTypeInfo(), &prototype_object, &interface_object)) { - V8TestInterface::InstallTestFeature( - isolate, world, v8::Local<v8::Object>(), prototype_object, interface_object); + case OriginTrialFeature::kTestFeature: { + if (context_data->GetExistingConstructorAndPrototypeForType( + V8TestInterface::GetWrapperTypeInfo(), &prototype_object, &interface_object)) { + V8TestInterface::InstallTestFeature( + isolate, world, v8::Local<v8::Object>(), prototype_object, interface_object); + } + break; } + default: + break; } }
diff --git a/third_party/blink/renderer/bindings/tests/results/modules/origin_trial_features_for_modules.cc b/third_party/blink/renderer/bindings/tests/results/modules/origin_trial_features_for_modules.cc index 546c2905..5264388 100644 --- a/third_party/blink/renderer/bindings/tests/results/modules/origin_trial_features_for_modules.cc +++ b/third_party/blink/renderer/bindings/tests/results/modules/origin_trial_features_for_modules.cc
@@ -20,6 +20,7 @@ #include "third_party/blink/renderer/platform/bindings/origin_trial_features.h" #include "third_party/blink/renderer/platform/bindings/script_state.h" #include "third_party/blink/renderer/platform/bindings/v8_per_context_data.h" +#include "third_party/blink/renderer/platform/runtime_enabled_features.h" namespace blink { @@ -39,7 +40,7 @@ } void InstallPendingOriginTrialFeatureForModules( - const String& feature, + OriginTrialFeature feature, const ScriptState* script_state) { (*g_original_install_pending_origin_trial_feature_function)(feature, script_state);
diff --git a/third_party/blink/renderer/build/scripts/make_origin_trials.py b/third_party/blink/renderer/build/scripts/make_origin_trials.py index 465636c0..cccb4b7e 100755 --- a/third_party/blink/renderer/build/scripts/make_origin_trials.py +++ b/third_party/blink/renderer/build/scripts/make_origin_trials.py
@@ -46,6 +46,10 @@ (self.file_basename + '.cc'): self.generate_implementation, (self.file_basename + '.h'): self.generate_header, } + self._implied_mappings = self._make_implied_mappings() + self._trial_to_features_map = self._make_trial_to_features_map() + + def _make_implied_mappings(self): # Set up the implied_by relationships between trials. implied_mappings = dict() for implied_feature in ( @@ -71,7 +75,17 @@ implied_feature['implied_by_origin_trials'] = implied_by_trials - self._implied_mappings = implied_mappings + return implied_mappings + + def _make_trial_to_features_map(self): + trial_feature_mappings = {} + for feature in self._origin_trial_features: + trial_name = feature['origin_trial_feature_name'] + if trial_name in trial_feature_mappings: + trial_feature_mappings[trial_name].append(feature) + else: + trial_feature_mappings[trial_name] = [feature] + return trial_feature_mappings @template_expander.use_jinja('templates/' + file_basename + '.cc.tmpl') def generate_implementation(self): @@ -79,6 +93,7 @@ 'features': self._features, 'origin_trial_features': self._origin_trial_features, 'implied_origin_trial_features': self._implied_mappings, + 'trial_to_features_map': self._trial_to_features_map, 'input_files': self._input_files, }
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 d072ef4..137742a 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
@@ -7,14 +7,44 @@ #include "third_party/blink/renderer/core/origin_trials/origin_trial_context.h" #include "third_party/blink/renderer/platform/runtime_enabled_features.h" +#include "third_party/blink/renderer/platform/wtf/hash_map.h" namespace blink { -{% for feature in features %} -{% if feature.origin_trial_feature_name %} -const char origin_trials::k{{feature.name}}TrialName[] = "{{feature.origin_trial_feature_name}}"; -{% endif %} -{% endfor %} +using TrialToFeaturesMap = HashMap<String, Vector<OriginTrialFeature>>; + +namespace { + +const TrialToFeaturesMap& GetTrialToFeaturesMap() { + // The object needs to be thread-safe because service workers can call this + // function as well. + DEFINE_THREAD_SAFE_STATIC_LOCAL(TrialToFeaturesMap, trial_to_features_map, ()); + if (trial_to_features_map.IsEmpty()) { + {% for trial_name, features_list in trial_to_features_map.items() %} + trial_to_features_map.Set("{{trial_name}}", + Vector<OriginTrialFeature>({ + {%- for trial_feature in features_list %} +OriginTrialFeature::k{{trial_feature.name}}, + {%- endfor %} + })); + {% endfor %} + // For testing + trial_to_features_map.Set("This trial does not exist", + Vector<OriginTrialFeature>({OriginTrialFeature::kNonExisting})); + } + return trial_to_features_map; +} + +} // namespace + +bool origin_trials::IsTrialValid(const String& trial_name) { + return GetTrialToFeaturesMap().Contains(trial_name); +} + +const Vector<OriginTrialFeature>& origin_trials::FeaturesForTrial(const String& trial_name) { + DCHECK(IsTrialValid(trial_name)); + return GetTrialToFeaturesMap().find(trial_name)->value; +} {% for feature in features %} {% if feature.origin_trial_feature_name %} @@ -29,59 +59,54 @@ const OriginTrialContext* context = OriginTrialContext::From(executionContext); if (!context) return false; - if (context->IsTrialEnabled(k{{feature.name}}TrialName)) + if (context->IsFeatureEnabled(OriginTrialFeature::k{{feature.name}})) return true; -{% for implied_by_name in feature.implied_by_origin_trials %} - // TODO(crbug.com/831346): This check should be redundant with - // GetImpliedTrials() being checked in OriginTrialContext::EnableTrialFromToken(). - // Remove when verified by further testing. - if (context->IsTrialEnabled(k{{implied_by_name}}TrialName)) - return true; -{% endfor %} return false; } {% endif %} {% endfor %} -Vector<AtomicString> origin_trials::GetImpliedTrials(const String& trial_name) { +Vector<OriginTrialFeature> origin_trials::GetImpliedFeatures(OriginTrialFeature feature) { {% for implied_by_name, implied_list in implied_origin_trial_features.items() %} - if (trial_name == k{{implied_by_name}}TrialName) { - Vector<AtomicString> implied_trials = { + if (feature == OriginTrialFeature::k{{implied_by_name}}) { + Vector<OriginTrialFeature> implied_features = { {%- for implied_name in implied_list %} -AtomicString(k{{implied_name}}TrialName), +OriginTrialFeature::k{{implied_name}}, {%- endfor %} }; - return implied_trials; + return implied_features; } {% endfor %} - return Vector<AtomicString>(); + return Vector<OriginTrialFeature>(); } -// 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 %} +bool origin_trials::FeatureEnabledForOS(OriginTrialFeature feature) { + switch (feature) { + {% for feature in features %} + {% if feature.origin_trial_feature_name %} + case OriginTrialFeature::k{{feature.name}}: + {% if feature.origin_trial_os %} #if -{%- for os in feature.origin_trial_os %} -{%- if not loop.first %} ||{% endif %} + {%- for os in feature.origin_trial_os %} + {%- if not loop.first %} ||{% endif %} defined(OS_{{os | upper}}) -{%- endfor %} + {%- endfor %} - return true; + return true; #else - return false; + return false; #endif - {% else %} - return true; + {% else %} + return true; + {% endif %} {% endif %} - {% endif %} - {% endfor %} - - return false; + {% endfor %} + // For testing + case OriginTrialFeature::kNonExisting: + return true; + } } } // 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 d53a7151..b9e7fd8 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
@@ -7,7 +7,7 @@ #define {{header_guard}} #include "third_party/blink/renderer/core/core_export.h" -#include "third_party/blink/renderer/platform/wtf/text/atomic_string.h" +#include "third_party/blink/renderer/platform/runtime_enabled_features.h" #include "third_party/blink/renderer/platform/wtf/text/wtf_string.h" #include "third_party/blink/renderer/platform/wtf/vector.h" @@ -24,11 +24,12 @@ // enabled by the origin trials framework via origin trial tokens. namespace origin_trials { -{% for feature in features %} -{% if feature.origin_trial_feature_name %} -CORE_EXPORT extern const char k{{feature.name}}TrialName[]; -{% endif %} -{% endfor %} +// Return true if there is a feature with the passed |trial_name|. +CORE_EXPORT bool IsTrialValid(const String& trial_name); + +// Return origin trials features that are enabled by the passed |trial_name|. +// The trial name MUST be valid (call IsTrialValid() before calling this function). +CORE_EXPORT const Vector<OriginTrialFeature>& FeaturesForTrial(const String& trial_name); {% for feature in features %} {% if feature.origin_trial_feature_name %} @@ -36,9 +37,11 @@ {% endif %} {% endfor %} -CORE_EXPORT Vector<AtomicString> GetImpliedTrials(const String& trial_name); +// Return the list of features which will also be enabled if the given +// |feature| is enabled. +Vector<OriginTrialFeature> GetImpliedFeatures(OriginTrialFeature feature); -bool TrialEnabledForOS(const String& trial_name); +bool FeatureEnabledForOS(OriginTrialFeature feature); } // namespace origin_trials
diff --git a/third_party/blink/renderer/build/scripts/templates/runtime_enabled_features.h.tmpl b/third_party/blink/renderer/build/scripts/templates/runtime_enabled_features.h.tmpl index b74af567..7361a5f 100644 --- a/third_party/blink/renderer/build/scripts/templates/runtime_enabled_features.h.tmpl +++ b/third_party/blink/renderer/build/scripts/templates/runtime_enabled_features.h.tmpl
@@ -13,6 +13,17 @@ namespace blink { +enum class OriginTrialFeature : int32_t { + // For testing + kNonExisting = 0, + + {% for feature in features %} + {% if feature.origin_trial_feature_name %} + k{{feature.name}}, + {% endif %} + {% endfor %} +}; + // A class that stores static enablers for all experimental features. class PLATFORM_EXPORT RuntimeEnabledFeatures {
diff --git a/third_party/blink/renderer/build/scripts/templates/web_origin_trials.cc.tmpl b/third_party/blink/renderer/build/scripts/templates/web_origin_trials.cc.tmpl index 6e234f3..69e1cf0 100644 --- a/third_party/blink/renderer/build/scripts/templates/web_origin_trials.cc.tmpl +++ b/third_party/blink/renderer/build/scripts/templates/web_origin_trials.cc.tmpl
@@ -14,13 +14,24 @@ bool WebOriginTrials::isTrialEnabled(const WebDocument* web_document, const WebString& trial) { if (!web_document) return false; -{% for feature in features %} -{% if feature.origin_trial_feature_name %} - if (trial == origin_trials::k{{feature.name}}TrialName) - return origin_trials::{{feature.name}}Enabled(*web_document); -{% endif %} -{% endfor %} - return false; + if (!origin_trials::IsTrialValid(trial)) + return false; + const Vector<OriginTrialFeature>& features = origin_trials::FeaturesForTrial(trial); + for (OriginTrialFeature feature : features) { + switch (feature) { + {% for feature in features %} + {% if feature.origin_trial_feature_name %} + case OriginTrialFeature::k{{feature.name}}: + if (!origin_trials::{{feature.name}}Enabled(*web_document)) + return false; + break; + {% endif %} + {% endfor %} + default: + break; + } + } + return true; }
diff --git a/third_party/blink/renderer/core/BUILD.gn b/third_party/blink/renderer/core/BUILD.gn index 4255b525..f54cad1 100644 --- a/third_party/blink/renderer/core/BUILD.gn +++ b/third_party/blink/renderer/core/BUILD.gn
@@ -2119,6 +2119,7 @@ "page/window_features_test.cc", "paint/block_painter_test.cc", "paint/box_paint_invalidator_test.cc", + "paint/box_painter_test.cc", "paint/clip_path_clipper_test.cc", "paint/clip_rect_test.cc", "paint/compositing/composited_layer_mapping_test.cc", @@ -2161,9 +2162,9 @@ "paint/video_painter_test.cc", "paint/view_painter_test.cc", "resize_observer/resize_observer_test.cc", - "scheduler/active_connection_throttling_test.cc", "scheduler/frame_scheduler_test.cc", "scheduler/frame_throttling_test.cc", + "scheduler/scheduler_affecting_features_test.cc", "scheduler/throttling_test.cc", "scheduler/virtual_time_test.cc", "script/document_modulator_impl_test.cc",
diff --git a/third_party/blink/renderer/core/animation/animation_effect.h b/third_party/blink/renderer/core/animation/animation_effect.h index feb3b47..1dc1b24 100644 --- a/third_party/blink/renderer/core/animation/animation_effect.h +++ b/third_party/blink/renderer/core/animation/animation_effect.h
@@ -118,6 +118,7 @@ double TimeToReverseEffectChange() const { return EnsureCalculated().time_to_reverse_effect_change; } + double LocalTime() const { return EnsureCalculated().local_time; } AnimationTimeDelta IterationDuration() const; double RepeatedDuration() const;
diff --git a/third_party/blink/renderer/core/animation/css/css_animations.cc b/third_party/blink/renderer/core/animation/css/css_animations.cc index c26c9ac..856dc6f 100644 --- a/third_party/blink/renderer/core/animation/css/css_animations.cc +++ b/third_party/blink/renderer/core/animation/css/css_animations.cc
@@ -45,6 +45,7 @@ #include "third_party/blink/renderer/core/animation/interpolation_type.h" #include "third_party/blink/renderer/core/animation/keyframe_effect.h" #include "third_party/blink/renderer/core/animation/keyframe_effect_model.h" +#include "third_party/blink/renderer/core/animation/timing_calculations.h" #include "third_party/blink/renderer/core/animation/transition_interpolation.h" #include "third_party/blink/renderer/core/animation/worklet_animation_base.h" #include "third_party/blink/renderer/core/css/css_keyframe_rule.h" @@ -798,8 +799,6 @@ *transition_type, start.interpolable_value->Clone(), start.non_interpolable_value)); start_keyframe->SetOffset(0); - start_keyframe->SetEasing(std::move(timing.timing_function)); - timing.timing_function = LinearTimingFunction::Shared(); keyframes.push_back(start_keyframe); TransitionKeyframe* end_keyframe = TransitionKeyframe::Create(property); @@ -1236,14 +1235,14 @@ if (GetDocument().HasListenerType(Document::kTransitionCancelListener)) { if (current_phase == AnimationEffect::kPhaseNone) { - double cancel_iteration_time = - animation_node.Progress().has_value() - ? animation_node.Progress().value() * - animation_node.SpecifiedTiming() - .iteration_duration->InSecondsF() - : StartTimeFromDelay( - animation_node.SpecifiedTiming().start_delay); - EnqueueEvent(event_type_names::kTransitioncancel, cancel_iteration_time); + // Per the css-transitions-2 spec, transitioncancel is fired with the + // "active time of the animation at the moment it was cancelled, + // calculated using a fill mode of both". + double cancel_active_time = CalculateActiveTime( + animation_node.RepeatedDuration(), Timing::FillMode::BOTH, + animation_node.LocalTime(), previous_phase_, + animation_node.SpecifiedTiming()); + EnqueueEvent(event_type_names::kTransitioncancel, cancel_active_time); } }
diff --git a/third_party/blink/renderer/core/clipboard/system_clipboard.cc b/third_party/blink/renderer/core/clipboard/system_clipboard.cc index babd584..91a5f3dd 100644 --- a/third_party/blink/renderer/core/clipboard/system_clipboard.cc +++ b/third_party/blink/renderer/core/clipboard/system_clipboard.cc
@@ -102,7 +102,7 @@ void SystemClipboard::WritePlainText(const String& plain_text, SmartReplaceOption smart_replace) { WritePlainTextNoCommit(plain_text, smart_replace); - clipboard_->CommitWrite(mojom::ClipboardBuffer::kStandard); + CommitWrite(); } void SystemClipboard::WritePlainTextNoCommit(const String& plain_text, @@ -137,6 +137,15 @@ const KURL& document_url, const String& plain_text, SmartReplaceOption smart_replace_option) { + WriteHTMLNoCommit(markup, document_url, plain_text, smart_replace_option); + CommitWrite(); +} + +void SystemClipboard::WriteHTMLNoCommit( + const String& markup, + const KURL& document_url, + const String& plain_text, + SmartReplaceOption smart_replace_option) { String text = plain_text; #if defined(OS_WIN) ReplaceNewlinesWithWindowsStyleNewlines(text); @@ -148,7 +157,6 @@ clipboard_->WriteText(mojom::ClipboardBuffer::kStandard, NonNullString(text)); if (smart_replace_option == kCanSmartReplace) clipboard_->WriteSmartPasteMarker(mojom::ClipboardBuffer::kStandard); - clipboard_->CommitWrite(mojom::ClipboardBuffer::kStandard); } String SystemClipboard::ReadRTF() { @@ -169,6 +177,13 @@ void SystemClipboard::WriteImageWithTag(Image* image, const KURL& url, const String& title) { + WriteImageWithTagNoCommit(image, url, title); + CommitWrite(); +} + +void SystemClipboard::WriteImageWithTagNoCommit(Image* image, + const KURL& url, + const String& title) { DCHECK(image); PaintImage paint_image = image->PaintImageForCurrentFrame(); @@ -194,7 +209,6 @@ clipboard_->WriteHtml(mojom::ClipboardBuffer::kStandard, URLToImageMarkup(url, title), KURL()); } - clipboard_->CommitWrite(mojom::ClipboardBuffer::kStandard); } void SystemClipboard::WriteImageNoCommit(const SkBitmap& bitmap) { @@ -210,6 +224,11 @@ } void SystemClipboard::WriteDataObject(DataObject* data_object) { + WriteDataObjectNoCommit(data_object); + CommitWrite(); +} + +void SystemClipboard::WriteDataObjectNoCommit(DataObject* data_object) { // This plagiarizes the logic in DropDataBuilder::Build, but only extracts the // data needed for the implementation of WriteDataObject. // @@ -240,7 +259,6 @@ clipboard_->WriteCustomData(mojom::ClipboardBuffer::kStandard, std::move(custom_data)); } - clipboard_->CommitWrite(mojom::ClipboardBuffer::kStandard); } void SystemClipboard::CommitWrite() {
diff --git a/third_party/blink/renderer/core/clipboard/system_clipboard.h b/third_party/blink/renderer/core/clipboard/system_clipboard.h index caf484c..9f14f88 100644 --- a/third_party/blink/renderer/core/clipboard/system_clipboard.h +++ b/third_party/blink/renderer/core/clipboard/system_clipboard.h
@@ -51,17 +51,25 @@ const KURL& document_url, const String& plain_text, SmartReplaceOption = kCannotSmartReplace); + void WriteHTMLNoCommit(const String& markup, + const KURL& document_url, + const String& plain_text, + SmartReplaceOption = kCannotSmartReplace); String ReadRTF(); SkBitmap ReadImage(mojom::ClipboardBuffer); + // Write the image and its associated tag (bookmark/HTML types). void WriteImageWithTag(Image*, const KURL&, const String& title); + // Write the image and its associated tag (bookmark/HTML types). + void WriteImageWithTagNoCommit(Image*, const KURL&, const String& title); // Write the image only. void WriteImageNoCommit(const SkBitmap&); String ReadCustomData(const String& type); void WriteDataObject(DataObject*); + void WriteDataObjectNoCommit(DataObject*); // Clipboard write functions that don't commit (explicitly labelled as // NoCommit) must use CommitWrite for changes to reach the OS clipboard.
diff --git a/third_party/blink/renderer/core/core_initializer.cc b/third_party/blink/renderer/core/core_initializer.cc index 45a820c..4b2cc24 100644 --- a/third_party/blink/renderer/core/core_initializer.cc +++ b/third_party/blink/renderer/core/core_initializer.cc
@@ -32,6 +32,7 @@ #include "third_party/blink/public/platform/platform.h" #include "third_party/blink/renderer/bindings/core/v8/binding_security.h" +#include "third_party/blink/renderer/bindings/core/v8/script_streamer_thread.h" #include "third_party/blink/renderer/bindings/core/v8/v8_throw_dom_exception.h" #include "third_party/blink/renderer/core/css/media_feature_names.h" #include "third_party/blink/renderer/core/css/media_query_evaluator.h" @@ -146,6 +147,7 @@ V8ThrowDOMException::Init(); BindingSecurity::Init(); + ScriptStreamerThread::Init(); } } // namespace blink
diff --git a/third_party/blink/renderer/core/css/css_primitive_value_mappings.h b/third_party/blink/renderer/core/css/css_primitive_value_mappings.h index c8fefe3..74bd883 100644 --- a/third_party/blink/renderer/core/css/css_primitive_value_mappings.h +++ b/third_party/blink/renderer/core/css/css_primitive_value_mappings.h
@@ -242,63 +242,24 @@ case kButtonPart: value_id_ = CSSValueButton; break; - case kButtonBevelPart: - value_id_ = CSSValueButtonBevel; - break; case kInnerSpinButtonPart: value_id_ = CSSValueInnerSpinButton; break; case kListboxPart: value_id_ = CSSValueListbox; break; - case kListItemPart: - value_id_ = CSSValueListitem; - break; - case kMediaEnterFullscreenButtonPart: - value_id_ = CSSValueMediaEnterFullscreenButton; - break; - case kMediaExitFullscreenButtonPart: - value_id_ = CSSValueMediaExitFullscreenButton; - break; - case kMediaPlayButtonPart: - value_id_ = CSSValueMediaPlayButton; - break; - case kMediaOverlayPlayButtonPart: - value_id_ = CSSValueMediaOverlayPlayButton; - break; - case kMediaMuteButtonPart: - value_id_ = CSSValueMediaMuteButton; - break; - case kMediaToggleClosedCaptionsButtonPart: - value_id_ = CSSValueMediaToggleClosedCaptionsButton; - break; case kMediaSliderPart: value_id_ = CSSValueMediaSlider; break; case kMediaSliderThumbPart: value_id_ = CSSValueMediaSliderthumb; break; - case kMediaVolumeSliderContainerPart: - value_id_ = CSSValueMediaVolumeSliderContainer; - break; case kMediaVolumeSliderPart: value_id_ = CSSValueMediaVolumeSlider; break; case kMediaVolumeSliderThumbPart: value_id_ = CSSValueMediaVolumeSliderthumb; break; - case kMediaControlsBackgroundPart: - value_id_ = CSSValueMediaControlsBackground; - break; - case kMediaControlsFullscreenBackgroundPart: - value_id_ = CSSValueMediaControlsFullscreenBackground; - break; - case kMediaCurrentTimePart: - value_id_ = CSSValueMediaCurrentTimeDisplay; - break; - case kMediaTimeRemainingPart: - value_id_ = CSSValueMediaTimeRemainingDisplay; - break; case kMediaControlPart: value_id_ = CSSValueInternalMediaControl; break; @@ -308,21 +269,12 @@ case kMenulistButtonPart: value_id_ = CSSValueMenulistButton; break; - case kMenulistTextPart: - value_id_ = CSSValueMenulistText; - break; - case kMenulistTextFieldPart: - value_id_ = CSSValueMenulistTextfield; - break; case kMeterPart: value_id_ = CSSValueMeter; break; case kProgressBarPart: value_id_ = CSSValueProgressBar; break; - case kProgressBarValuePart: - value_id_ = CSSValueProgressBarValue; - break; case kSliderHorizontalPart: value_id_ = CSSValueSliderHorizontal; break; @@ -335,9 +287,6 @@ case kSliderThumbVerticalPart: value_id_ = CSSValueSliderthumbVertical; break; - case kCaretPart: - value_id_ = CSSValueCaret; - break; case kSearchFieldPart: value_id_ = CSSValueSearchfield; break;
diff --git a/third_party/blink/renderer/core/css/css_value_keywords.json5 b/third_party/blink/renderer/core/css/css_value_keywords.json5 index fbb19cd..de57002 100644 --- a/third_party/blink/renderer/core/css/css_value_keywords.json5 +++ b/third_party/blink/renderer/core/css/css_value_keywords.json5
@@ -654,38 +654,21 @@ "push-button", "square-button", "button", - "button-bevel", "inner-spin-button", "listbox", - "listitem", - "media-enter-fullscreen-button", - "media-exit-fullscreen-button", - "media-mute-button", - "media-play-button", - "media-overlay-play-button", - "media-toggle-closed-captions-button", "media-slider", "media-sliderthumb", - "media-volume-slider-container", "media-volume-slider", "media-volume-sliderthumb", - "media-controls-background", - "media-controls-fullscreen-background", - "media-current-time-display", - "media-time-remaining-display", "-internal-media-control", "menulist", "menulist-button", - "menulist-text", - "menulist-textfield", "meter", "progress-bar", - "progress-bar-value", "slider-horizontal", "slider-vertical", "sliderthumb-horizontal", "sliderthumb-vertical", - "caret", "searchfield", "searchfield-cancel-button", "textfield",
diff --git a/third_party/blink/renderer/core/css/cssom/cross_thread_style_value_test.cc b/third_party/blink/renderer/core/css/cssom/cross_thread_style_value_test.cc index e4a6458..d0129a4c 100644 --- a/third_party/blink/renderer/core/css/cssom/cross_thread_style_value_test.cc +++ b/third_party/blink/renderer/core/css/cssom/cross_thread_style_value_test.cc
@@ -78,7 +78,7 @@ DCHECK(value); // Use a WebThreadSupportingGC to emulate worklet thread. - thread_ = WebThreadSupportingGC::Create( + thread_ = std::make_unique<WebThreadSupportingGC>( ThreadCreationParams(WebThreadType::kTestThread)); base::WaitableEvent waitable_event; thread_->PostTask( @@ -109,7 +109,7 @@ DCHECK(value); // Use a WebThreadSupportingGC to emulate worklet thread. - thread_ = WebThreadSupportingGC::Create( + thread_ = std::make_unique<WebThreadSupportingGC>( ThreadCreationParams(WebThreadType::kTestThread)); base::WaitableEvent waitable_event; thread_->PostTask( @@ -140,7 +140,7 @@ DCHECK(value); // Use a WebThreadSupportingGC to emulate worklet thread. - thread_ = WebThreadSupportingGC::Create( + thread_ = std::make_unique<WebThreadSupportingGC>( ThreadCreationParams(WebThreadType::kTestThread)); base::WaitableEvent waitable_event; thread_->PostTask(FROM_HERE,
diff --git a/third_party/blink/renderer/core/css/cssom/paint_worklet_style_property_map_test.cc b/third_party/blink/renderer/core/css/cssom/paint_worklet_style_property_map_test.cc index 71691b43..0d5d7ff9 100644 --- a/third_party/blink/renderer/core/css/cssom/paint_worklet_style_property_map_test.cc +++ b/third_party/blink/renderer/core/css/cssom/paint_worklet_style_property_map_test.cc
@@ -247,7 +247,7 @@ style_map); DCHECK(input); - thread_ = WebThreadSupportingGC::Create( + thread_ = std::make_unique<WebThreadSupportingGC>( ThreadCreationParams(WebThreadType::kTestThread)); base::WaitableEvent waitable_event; thread_->PostTask(
diff --git a/third_party/blink/renderer/core/css/invalidation/invalidation_set.cc b/third_party/blink/renderer/core/css/invalidation/invalidation_set.cc index 6d5c67c..10b68e71 100644 --- a/third_party/blink/renderer/core/css/invalidation/invalidation_set.cc +++ b/third_party/blink/renderer/core/css/invalidation/invalidation_set.cc
@@ -367,7 +367,7 @@ #ifndef NDEBUG void InvalidationSet::Show() const { - std::unique_ptr<TracedValue> value = TracedValue::Create(); + auto value = std::make_unique<TracedValue>(); value->BeginArray("InvalidationSet"); ToTracedValue(value.get()); value->EndArray();
diff --git a/third_party/blink/renderer/core/css/parser/css_property_parser_helpers.cc b/third_party/blink/renderer/core/css/parser/css_property_parser_helpers.cc index 8ccbdcf..8a57e98 100644 --- a/third_party/blink/renderer/core/css/parser/css_property_parser_helpers.cc +++ b/third_party/blink/renderer/core/css/parser/css_property_parser_helpers.cc
@@ -1804,8 +1804,6 @@ feature = WebFeature::kCSSValueAppearanceNotNone; if (value_id == CSSValueButton) feature = WebFeature::kCSSValueAppearanceButton; - else if (value_id == CSSValueCaret) - feature = WebFeature::kCSSValueAppearanceCaret; else if (value_id == CSSValueCheckbox) feature = WebFeature::kCSSValueAppearanceCheckbox; else if (value_id == CSSValueInnerSpinButton) @@ -1838,47 +1836,6 @@ feature = WebFeature::kCSSValueAppearanceOthers; } context.Count(feature); - - if (value_id == CSSValueButtonBevel) { - feature = WebFeature::kCSSValueAppearanceButtonBevel; - } else if (value_id == CSSValueCaret) { - feature = WebFeature::kCSSValueAppearanceCaret; - } else if (value_id == CSSValueListitem) { - feature = WebFeature::kCSSValueAppearanceListitem; - } else if (value_id == CSSValueMediaControlsBackground) { - feature = WebFeature::kCSSValueAppearanceMediaControlsBackground; - } else if (value_id == CSSValueMediaControlsFullscreenBackground) { - feature = - WebFeature::kCSSValueAppearanceMediaControlsFullscreenBackground; - } else if (value_id == CSSValueMediaCurrentTimeDisplay) { - feature = WebFeature::kCSSValueAppearanceMediaCurrentTimeDisplay; - } else if (value_id == CSSValueMediaEnterFullscreenButton) { - feature = WebFeature::kCSSValueAppearanceMediaEnterFullscreenButton; - } else if (value_id == CSSValueMediaExitFullscreenButton) { - feature = WebFeature::kCSSValueAppearanceMediaExitFullscreenButton; - } else if (value_id == CSSValueMediaMuteButton) { - feature = WebFeature::kCSSValueAppearanceMediaMuteButton; - } else if (value_id == CSSValueMediaOverlayPlayButton) { - feature = WebFeature::kCSSValueAppearanceMediaOverlayPlayButton; - } else if (value_id == CSSValueMediaPlayButton) { - feature = WebFeature::kCSSValueAppearanceMediaPlayButton; - } else if (value_id == CSSValueMediaTimeRemainingDisplay) { - feature = WebFeature::kCSSValueAppearanceMediaTimeRemainingDisplay; - } else if (value_id == CSSValueMediaToggleClosedCaptionsButton) { - feature = - WebFeature::kCSSValueAppearanceMediaToggleClosedCaptionsButton; - } else if (value_id == CSSValueMediaVolumeSliderContainer) { - feature = WebFeature::kCSSValueAppearanceMediaVolumeSliderContainer; - } else if (value_id == CSSValueMenulistTextfield) { - feature = WebFeature::kCSSValueAppearanceMenulistTextfield; - } else if (value_id == CSSValueMenulistText) { - feature = WebFeature::kCSSValueAppearanceMenulistText; - } else if (value_id == CSSValueProgressBarValue) { - feature = WebFeature::kCSSValueAppearanceProgressBarValue; - } else { - break; - } - context.CountDeprecation(feature); break; }
diff --git a/third_party/blink/renderer/core/css/resolver/style_resolver_stats.cc b/third_party/blink/renderer/core/css/resolver/style_resolver_stats.cc index 7c37a47..56d04c9 100644 --- a/third_party/blink/renderer/core/css/resolver/style_resolver_stats.cc +++ b/third_party/blink/renderer/core/css/resolver/style_resolver_stats.cc
@@ -53,7 +53,7 @@ } std::unique_ptr<TracedValue> StyleResolverStats::ToTracedValue() const { - std::unique_ptr<TracedValue> traced_value = TracedValue::Create(); + auto traced_value = std::make_unique<TracedValue>(); traced_value->SetInteger("matchedPropertyApply", matched_property_apply); traced_value->SetInteger("matchedPropertyCacheHit", matched_property_cache_hit);
diff --git a/third_party/blink/renderer/core/css/threaded/multi_threaded_test_util.h b/third_party/blink/renderer/core/css/threaded/multi_threaded_test_util.h index a65d8167..8c96f414 100644 --- a/third_party/blink/renderer/core/css/threaded/multi_threaded_test_util.h +++ b/third_party/blink/renderer/core/css/threaded/multi_threaded_test_util.h
@@ -58,7 +58,7 @@ Vector<std::unique_ptr<base::WaitableEvent>> waits; for (int i = 0; i < num_threads_; ++i) { - threads.push_back(WebThreadSupportingGC::Create( + threads.push_back(std::make_unique<WebThreadSupportingGC>( ThreadCreationParams(WebThreadType::kTestThread))); waits.push_back(std::make_unique<base::WaitableEvent>()); }
diff --git a/third_party/blink/renderer/core/dom/events/event_target.cc b/third_party/blink/renderer/core/dom/events/event_target.cc index 4848d06..5fefe76 100644 --- a/third_party/blink/renderer/core/dom/events/event_target.cc +++ b/third_party/blink/renderer/core/dom/events/event_target.cc
@@ -801,6 +801,9 @@ } else if (CheckTypeThenUseCount(event, event_type_names::kPointerout, WebFeature::kPointerOverOutFired, document)) { + } else if (CheckTypeThenUseCount(event, event_type_names::kSearch, + WebFeature::kSearchEventFired, + document)) { } else if (event.eventPhase() == Event::kCapturingPhase || event.eventPhase() == Event::kBubblingPhase) { if (CheckTypeThenUseCount(
diff --git a/third_party/blink/renderer/core/exported/local_frame_client_impl.cc b/third_party/blink/renderer/core/exported/local_frame_client_impl.cc index dfb7b9e..21aeb700 100644 --- a/third_party/blink/renderer/core/exported/local_frame_client_impl.cc +++ b/third_party/blink/renderer/core/exported/local_frame_client_impl.cc
@@ -659,8 +659,8 @@ bool LocalFrameClientImpl::NavigateBackForward(int offset) const { WebViewImpl* webview = web_frame_->ViewImpl(); - if (!webview->Client()) - return false; + DCHECK(webview->Client()); + DCHECK(web_frame_->Client()); DCHECK(offset); if (offset > webview->Client()->HistoryForwardListCount()) @@ -670,7 +670,7 @@ bool has_user_gesture = LocalFrame::HasTransientUserActivation(web_frame_->GetFrame()); - webview->Client()->NavigateBackForwardSoon(offset, has_user_gesture); + web_frame_->Client()->NavigateBackForwardSoon(offset, has_user_gesture); return true; } @@ -988,10 +988,12 @@ std::unique_ptr<WebApplicationCacheHost> LocalFrameClientImpl::CreateApplicationCacheHost( + DocumentLoader* loader, WebApplicationCacheHostClient* client) { if (!web_frame_->Client()) return nullptr; - return web_frame_->Client()->CreateApplicationCacheHost(client); + return web_frame_->Client()->CreateApplicationCacheHost( + WebDocumentLoaderImpl::FromDocumentLoader(loader), client); } void LocalFrameClientImpl::DispatchDidChangeManifest() {
diff --git a/third_party/blink/renderer/core/exported/local_frame_client_impl.h b/third_party/blink/renderer/core/exported/local_frame_client_impl.h index ad569d6..e0a600c 100644 --- a/third_party/blink/renderer/core/exported/local_frame_client_impl.h +++ b/third_party/blink/renderer/core/exported/local_frame_client_impl.h
@@ -225,6 +225,7 @@ WebContentSettingsClient* GetContentSettingsClient() override; std::unique_ptr<WebApplicationCacheHost> CreateApplicationCacheHost( + DocumentLoader*, WebApplicationCacheHostClient*) override; void DispatchDidChangeManifest() override;
diff --git a/third_party/blink/renderer/core/exported/web_associated_url_loader_impl.cc b/third_party/blink/renderer/core/exported/web_associated_url_loader_impl.cc index c378ef7..5308387 100644 --- a/third_party/blink/renderer/core/exported/web_associated_url_loader_impl.cc +++ b/third_party/blink/renderer/core/exported/web_associated_url_loader_impl.cc
@@ -109,11 +109,11 @@ // ThreadableLoaderClient void DidSendData(uint64_t /*bytesSent*/, uint64_t /*totalBytesToBeSent*/) override; - void DidReceiveResponse(unsigned long, const ResourceResponse&) override; + void DidReceiveResponse(uint64_t, const ResourceResponse&) override; void DidDownloadData(uint64_t /*dataLength*/) override; void DidReceiveData(const char*, unsigned /*dataLength*/) override; void DidReceiveCachedMetadata(const char*, int /*dataLength*/) override; - void DidFinishLoading(unsigned long /*identifier*/) override; + void DidFinishLoading(uint64_t /*identifier*/) override; void DidFail(const ResourceError&) override; void DidFailRedirectCheck() override; @@ -197,7 +197,7 @@ } void WebAssociatedURLLoaderImpl::ClientAdapter::DidReceiveResponse( - unsigned long, + uint64_t, const ResourceResponse& response) { if (!client_) return; @@ -264,7 +264,7 @@ } void WebAssociatedURLLoaderImpl::ClientAdapter::DidFinishLoading( - unsigned long identifier) { + uint64_t identifier) { if (!client_) return;
diff --git a/third_party/blink/renderer/core/exported/web_view_impl.cc b/third_party/blink/renderer/core/exported/web_view_impl.cc index 9d06e343..66616f3 100644 --- a/third_party/blink/renderer/core/exported/web_view_impl.cc +++ b/third_party/blink/renderer/core/exported/web_view_impl.cc
@@ -2804,7 +2804,7 @@ } } -unsigned long WebViewImpl::CreateUniqueIdentifierForRequest() { +uint64_t WebViewImpl::CreateUniqueIdentifierForRequest() { return CreateUniqueIdentifier(); }
diff --git a/third_party/blink/renderer/core/exported/web_view_impl.h b/third_party/blink/renderer/core/exported/web_view_impl.h index 52b62bac..9db8a50 100644 --- a/third_party/blink/renderer/core/exported/web_view_impl.h +++ b/third_party/blink/renderer/core/exported/web_view_impl.h
@@ -174,7 +174,7 @@ WebHitTestResult HitTestResultAt(const gfx::Point&) override; WebHitTestResult HitTestResultForTap(const gfx::Point&, const WebSize&) override; - unsigned long CreateUniqueIdentifierForRequest() override; + uint64_t CreateUniqueIdentifierForRequest() override; void EnableDeviceEmulation(const WebDeviceEmulationParams&) override; void DisableDeviceEmulation() override; void SetSelectionColors(unsigned active_background_color,
diff --git a/third_party/blink/renderer/core/exported/worker_shadow_page.cc b/third_party/blink/renderer/core/exported/worker_shadow_page.cc index 34c55cf..397bbc7 100644 --- a/third_party/blink/renderer/core/exported/worker_shadow_page.cc +++ b/third_party/blink/renderer/core/exported/worker_shadow_page.cc
@@ -79,6 +79,7 @@ std::unique_ptr<WebApplicationCacheHost> WorkerShadowPage::CreateApplicationCacheHost( + WebDocumentLoader*, WebApplicationCacheHostClient* appcache_host_client) { DCHECK(IsMainThread()); return client_->CreateApplicationCacheHost(appcache_host_client);
diff --git a/third_party/blink/renderer/core/exported/worker_shadow_page.h b/third_party/blink/renderer/core/exported/worker_shadow_page.h index 60fc03c..866311fe 100644 --- a/third_party/blink/renderer/core/exported/worker_shadow_page.h +++ b/third_party/blink/renderer/core/exported/worker_shadow_page.h
@@ -67,6 +67,7 @@ // WebLocalFrameClient overrides. std::unique_ptr<WebApplicationCacheHost> CreateApplicationCacheHost( + WebDocumentLoader*, WebApplicationCacheHostClient*) override; // Note: usually WebLocalFrameClient implementations override // WebLocalFrameClient to call Close() on the corresponding WebLocalFrame.
diff --git a/third_party/blink/renderer/core/fetch/fetch_manager.cc b/third_party/blink/renderer/core/fetch/fetch_manager.cc index d2d936ec..66a464d 100644 --- a/third_party/blink/renderer/core/fetch/fetch_manager.cc +++ b/third_party/blink/renderer/core/fetch/fetch_manager.cc
@@ -103,9 +103,9 @@ // ThreadableLoaderClient implementation. bool WillFollowRedirect(const KURL&, const ResourceResponse&) override; - void DidReceiveResponse(unsigned long, const ResourceResponse&) override; + void DidReceiveResponse(uint64_t, const ResourceResponse&) override; void DidStartLoadingResponseBody(BytesConsumer&) override; - void DidFinishLoading(unsigned long) override; + void DidFinishLoading(uint64_t) override; void DidFail(const ResourceError&) override; void DidFailRedirectCheck() override; @@ -293,7 +293,7 @@ } if (redirect_mode == network::mojom::FetchRedirectMode::kManual) { - const unsigned long unused = 0; + const uint64_t unused = 0; // There is no need to read the body of redirect response because there is // no way to read the body of opaque-redirect filtered response's internal // response. @@ -316,7 +316,7 @@ } void FetchManager::Loader::DidReceiveResponse( - unsigned long, + uint64_t, const ResourceResponse& response) { // TODO(horo): This check could be false when we will use the response url // in service worker responses. (crbug.com/553535) @@ -501,7 +501,7 @@ place_holder_body_ = nullptr; } -void FetchManager::Loader::DidFinishLoading(unsigned long) { +void FetchManager::Loader::DidFinishLoading(uint64_t) { DCHECK(!place_holder_body_); DCHECK(!failed_);
diff --git a/third_party/blink/renderer/core/frame/deprecation.cc b/third_party/blink/renderer/core/frame/deprecation.cc index 9cabebe..480f77a 100644 --- a/third_party/blink/renderer/core/frame/deprecation.cc +++ b/third_party/blink/renderer/core/frame/deprecation.cc
@@ -611,41 +611,6 @@ "native UI", kM75, "5825971391299584")}; -#define REMOVE_APPEARANCE_KEYWORD_M75(id, keyword) \ - case WebFeature::kCSSValueAppearance##id: \ - return {"CSSValueAppearance" #id, kM75, \ - WillBeRemoved("The keyword '" keyword \ - "' for -webkit-appearance CSS property", \ - kM75, "5075579829223424")} - - REMOVE_APPEARANCE_KEYWORD_M75(ButtonBevel, "button-bevel"); - REMOVE_APPEARANCE_KEYWORD_M75(Caret, "caret"); - REMOVE_APPEARANCE_KEYWORD_M75(Listitem, "listitem"); - REMOVE_APPEARANCE_KEYWORD_M75(MediaControlsBackground, - "media-controls-background"); - REMOVE_APPEARANCE_KEYWORD_M75(MediaControlsFullscreenBackground, - "media-controls-fullscreen-background"); - REMOVE_APPEARANCE_KEYWORD_M75(MediaCurrentTimeDisplay, - "media-current-time-display"); - REMOVE_APPEARANCE_KEYWORD_M75(MediaEnterFullscreenButton, - "media-enter-fullscreen-button"); - REMOVE_APPEARANCE_KEYWORD_M75(MediaExitFullscreenButton, - "media-exit-fullscreen-button"); - REMOVE_APPEARANCE_KEYWORD_M75(MediaMuteButton, "media-mute-button"); - REMOVE_APPEARANCE_KEYWORD_M75(MediaOverlayPlayButton, - "media-overlay-play-button"); - REMOVE_APPEARANCE_KEYWORD_M75(MediaPlayButton, "media-play-button"); - REMOVE_APPEARANCE_KEYWORD_M75(MediaTimeRemainingDisplay, - "media-time-remaining-display"); - REMOVE_APPEARANCE_KEYWORD_M75(MediaToggleClosedCaptionsButton, - "media-toggle-closed-captions-button"); - REMOVE_APPEARANCE_KEYWORD_M75(MediaVolumeSliderContainer, - "media-volume-slider-container"); - REMOVE_APPEARANCE_KEYWORD_M75(MenulistTextfield, "menulist-textfield"); - REMOVE_APPEARANCE_KEYWORD_M75(MenulistText, "menulist-text"); - REMOVE_APPEARANCE_KEYWORD_M75(ProgressBarValue, "progress-bar-value"); -#undef REMOVE_APPEARANCE_KEYWORD_M75 - case WebFeature::kV8AtomicsWake: return {"V8AtomicsWake", kM76, ReplacedWillBeRemoved("Atomics.wake", "Atomics.notify", kM76,
diff --git a/third_party/blink/renderer/core/frame/frame_console.cc b/third_party/blink/renderer/core/frame/frame_console.cc index 5e8cf02..baee3d2 100644 --- a/third_party/blink/renderer/core/frame/frame_console.cc +++ b/third_party/blink/renderer/core/frame/frame_console.cc
@@ -92,7 +92,7 @@ void FrameConsole::ReportResourceResponseReceived( DocumentLoader* loader, - unsigned long request_identifier, + uint64_t request_identifier, const ResourceResponse& response) { if (!loader) return; @@ -111,7 +111,7 @@ } void FrameConsole::DidFailLoading(DocumentLoader* loader, - unsigned long request_identifier, + uint64_t request_identifier, const ResourceError& error) { if (error.IsCancellation()) // Report failures only. return;
diff --git a/third_party/blink/renderer/core/frame/frame_console.h b/third_party/blink/renderer/core/frame/frame_console.h index 192da82..6555567 100644 --- a/third_party/blink/renderer/core/frame/frame_console.h +++ b/third_party/blink/renderer/core/frame/frame_console.h
@@ -74,11 +74,11 @@ SourceLocation*); void ReportResourceResponseReceived(DocumentLoader*, - unsigned long request_identifier, + uint64_t request_identifier, const ResourceResponse&); void DidFailLoading(DocumentLoader*, - unsigned long request_identifier, + uint64_t request_identifier, const ResourceError&); void Trace(blink::Visitor*) override;
diff --git a/third_party/blink/renderer/core/frame/history.cc b/third_party/blink/renderer/core/frame/history.cc index b7753d11..a25fcd4 100644 --- a/third_party/blink/renderer/core/frame/history.cc +++ b/third_party/blink/renderer/core/frame/history.cc
@@ -202,8 +202,7 @@ // Otherwise, navigation happens on the root frame. // This behavior is designed in the following spec. // https://html.spec.whatwg.org/C/#dom-history-go - GetFrame()->Reload(WebFrameLoadType::kReload, - ClientRedirectPolicy::kClientRedirect); + GetFrame()->Reload(WebFrameLoadType::kReload); } }
diff --git a/third_party/blink/renderer/core/frame/local_frame.cc b/third_party/blink/renderer/core/frame/local_frame.cc index 803d4e18..9cc03d60 100644 --- a/third_party/blink/renderer/core/frame/local_frame.cc +++ b/third_party/blink/renderer/core/frame/local_frame.cc
@@ -524,22 +524,19 @@ return frame; } -void LocalFrame::Reload(WebFrameLoadType load_type, - ClientRedirectPolicy client_redirect_policy) { +void LocalFrame::Reload(WebFrameLoadType load_type) { DCHECK(IsReloadLoadType(load_type)); if (!loader_.GetDocumentLoader()->GetHistoryItem()) return; FrameLoadRequest request = FrameLoadRequest( - nullptr, - loader_.ResourceRequestForReload(load_type, client_redirect_policy)); - request.SetClientRedirect(client_redirect_policy); + nullptr, loader_.ResourceRequestForReload( + load_type, ClientRedirectPolicy::kClientRedirect)); + request.SetClientRedirect(ClientRedirectPolicy::kClientRedirect); if (const WebInputEvent* input_event = CurrentInputEvent::Get()) request.SetInputStartTime(input_event->TimeStamp()); - if (client_redirect_policy == ClientRedirectPolicy::kClientRedirect) { - probe::FrameScheduledNavigation(this, request.GetResourceRequest().Url(), - 0.0, ClientNavigationReason::kReload); - probe::FrameClearedScheduledNavigation(this); - } + probe::FrameScheduledNavigation(this, request.GetResourceRequest().Url(), 0.0, + ClientNavigationReason::kReload); + probe::FrameClearedScheduledNavigation(this); loader_.StartNavigation(request, load_type); }
diff --git a/third_party/blink/renderer/core/frame/local_frame.h b/third_party/blink/renderer/core/frame/local_frame.h index c02a471..910be591 100644 --- a/third_party/blink/renderer/core/frame/local_frame.h +++ b/third_party/blink/renderer/core/frame/local_frame.h
@@ -164,7 +164,7 @@ Frame* FindFrameForNavigation(const AtomicString& name, LocalFrame& active_frame, const KURL& destination_url); - void Reload(WebFrameLoadType, ClientRedirectPolicy); + void Reload(WebFrameLoadType); // Note: these two functions are not virtual but intentionally shadow the // corresponding method in the Frame base class to return the
diff --git a/third_party/blink/renderer/core/frame/local_frame_client.h b/third_party/blink/renderer/core/frame/local_frame_client.h index 0f22851..3f29066 100644 --- a/third_party/blink/renderer/core/frame/local_frame_client.h +++ b/third_party/blink/renderer/core/frame/local_frame_client.h
@@ -355,6 +355,7 @@ virtual WebContentSettingsClient* GetContentSettingsClient() = 0; virtual std::unique_ptr<WebApplicationCacheHost> CreateApplicationCacheHost( + DocumentLoader*, WebApplicationCacheHostClient*) = 0; virtual void DispatchDidChangeManifest() {}
diff --git a/third_party/blink/renderer/core/frame/local_frame_ukm_aggregator.cc b/third_party/blink/renderer/core/frame/local_frame_ukm_aggregator.cc index feee735..54fa044 100644 --- a/third_party/blink/renderer/core/frame/local_frame_ukm_aggregator.cc +++ b/third_party/blink/renderer/core/frame/local_frame_ukm_aggregator.cc
@@ -4,6 +4,7 @@ #include "third_party/blink/renderer/core/frame/local_frame_ukm_aggregator.h" +#include "base/format_macros.h" #include "services/metrics/public/cpp/ukm_entry_builder.h" #include "services/metrics/public/cpp/ukm_recorder.h" #include "third_party/blink/renderer/platform/histogram.h" @@ -61,19 +62,17 @@ if (!bucket_thresholds().size()) { threshold_substrings.push_back(".All"); } else { - threshold_substrings.push_back( - String::Format(".LessThan%lums", - (unsigned long)bucket_thresholds()[0].InMilliseconds())); + threshold_substrings.push_back(String::Format( + ".LessThan%" PRId64 "ms", bucket_thresholds()[0].InMilliseconds())); for (wtf_size_t i = 1; i < bucket_thresholds().size(); ++i) { - threshold_substrings.push_back(String::Format( - ".%lumsTo%lums", - (unsigned long)bucket_thresholds()[i - 1].InMilliseconds(), - (unsigned long)bucket_thresholds()[i].InMilliseconds())); + threshold_substrings.push_back( + String::Format(".%" PRId64 "msTo%" PRId64 "ms", + bucket_thresholds()[i - 1].InMilliseconds(), + bucket_thresholds()[i].InMilliseconds())); } threshold_substrings.push_back(String::Format( - ".MoreThan%lums", - (unsigned long)bucket_thresholds()[bucket_thresholds().size() - 1] - .InMilliseconds())); + ".MoreThan%" PRId64 "ms", + bucket_thresholds()[bucket_thresholds().size() - 1].InMilliseconds())); } // Populate all the sub-metrics.
diff --git a/third_party/blink/renderer/core/frame/local_frame_view.cc b/third_party/blink/renderer/core/frame/local_frame_view.cc index 134edd7..acdf03b 100644 --- a/third_party/blink/renderer/core/frame/local_frame_view.cc +++ b/third_party/blink/renderer/core/frame/local_frame_view.cc
@@ -693,7 +693,7 @@ std::unique_ptr<TracedValue> LocalFrameView::AnalyzerCounters() { if (!analyzer_) - return TracedValue::Create(); + return std::make_unique<TracedValue>(); std::unique_ptr<TracedValue> value = analyzer_->ToTracedValue(); value->SetString("host", GetLayoutView()->GetDocument().location()->host()); value->SetString(
diff --git a/third_party/blink/renderer/core/frame/location.cc b/third_party/blink/renderer/core/frame/location.cc index fb8f1fd0c..3b76e909 100644 --- a/third_party/blink/renderer/core/frame/location.cc +++ b/third_party/blink/renderer/core/frame/location.cc
@@ -248,8 +248,7 @@ // local. To<LocalDOMWindow>(dom_window_.Get()) ->GetFrame() - ->Reload(WebFrameLoadType::kReload, - ClientRedirectPolicy::kClientRedirect); + ->Reload(WebFrameLoadType::kReload); } void Location::SetLocation(const String& url,
diff --git a/third_party/blink/renderer/core/geometry/dom_matrix_read_only.cc b/third_party/blink/renderer/core/geometry/dom_matrix_read_only.cc index 87e251c..fd98d66e 100644 --- a/third_party/blink/renderer/core/geometry/dom_matrix_read_only.cc +++ b/third_party/blink/renderer/core/geometry/dom_matrix_read_only.cc
@@ -320,7 +320,7 @@ DOMMatrixReadOnly::DOMMatrixReadOnly(const TransformationMatrix& matrix, bool is2d) { - matrix_ = TransformationMatrix::Create(matrix); + matrix_ = std::make_unique<TransformationMatrix>(matrix); is2d_ = is2d; }
diff --git a/third_party/blink/renderer/core/geometry/dom_matrix_read_only.h b/third_party/blink/renderer/core/geometry/dom_matrix_read_only.h index 5b64056..b823b1b 100644 --- a/third_party/blink/renderer/core/geometry/dom_matrix_read_only.h +++ b/third_party/blink/renderer/core/geometry/dom_matrix_read_only.h
@@ -47,12 +47,12 @@ template <typename T> DOMMatrixReadOnly(T sequence, int size) { if (size == 6) { - matrix_ = - TransformationMatrix::Create(sequence[0], sequence[1], sequence[2], - sequence[3], sequence[4], sequence[5]); + matrix_ = std::make_unique<TransformationMatrix>( + sequence[0], sequence[1], sequence[2], sequence[3], sequence[4], + sequence[5]); is2d_ = true; } else if (size == 16) { - matrix_ = TransformationMatrix::Create( + matrix_ = std::make_unique<TransformationMatrix>( sequence[0], sequence[1], sequence[2], sequence[3], sequence[4], sequence[5], sequence[6], sequence[7], sequence[8], sequence[9], sequence[10], sequence[11], sequence[12], sequence[13], sequence[14],
diff --git a/third_party/blink/renderer/core/html/canvas/canvas_context_creation_attributes_core.h b/third_party/blink/renderer/core/html/canvas/canvas_context_creation_attributes_core.h index 614e4e3..3ae0b2a8 100644 --- a/third_party/blink/renderer/core/html/canvas/canvas_context_creation_attributes_core.h +++ b/third_party/blink/renderer/core/html/canvas/canvas_context_creation_attributes_core.h
@@ -30,6 +30,7 @@ String pixel_format = "uint8"; bool premultiplied_alpha = true; bool preserve_drawing_buffer = false; + String power_preference = "default"; bool stencil = false; bool xr_compatible = false; };
diff --git a/third_party/blink/renderer/core/html/custom/custom_element_registry.cc b/third_party/blink/renderer/core/html/custom/custom_element_registry.cc index 42546eb..97cef38 100644 --- a/third_party/blink/renderer/core/html/custom/custom_element_registry.cc +++ b/third_party/blink/renderer/core/html/custom/custom_element_registry.cc
@@ -133,7 +133,7 @@ if (NameIsDefined(name) || V0NameIsDefined(name)) { exception_state.ThrowDOMException( DOMExceptionCode::kNotSupportedError, - "this name has already been used with this registry"); + "the name \"" + name + "\" has already been used with this registry"); return nullptr; }
diff --git a/third_party/blink/renderer/core/html/html_anchor_element.cc b/third_party/blink/renderer/core/html/html_anchor_element.cc index acfe7a2a..df357787 100644 --- a/third_party/blink/renderer/core/html/html_anchor_element.cc +++ b/third_party/blink/renderer/core/html/html_anchor_element.cc
@@ -25,7 +25,6 @@ #include "third_party/blink/renderer/core/html/html_anchor_element.h" #include "base/metrics/histogram_macros.h" -#include "third_party/blink/public/common/download/download_stats.h" #include "third_party/blink/renderer/bindings/core/v8/usv_string_or_trusted_url.h" #include "third_party/blink/renderer/core/dom/user_gesture_indicator.h" #include "third_party/blink/renderer/core/editing/editing_utilities.h" @@ -56,31 +55,6 @@ namespace blink { -namespace { - -void RecordDownloadMetrics(LocalFrame* frame) { - if (frame->IsMainFrame()) { - DownloadStats::MainFrameDownloadFlags flags; - flags.has_sandbox = frame->GetDocument()->IsSandboxed(kSandboxDownloads); - flags.has_gesture = LocalFrame::HasTransientUserActivation(frame); - DownloadStats::RecordMainFrameDownloadFlags( - flags, frame->GetDocument()->UkmSourceID(), - frame->GetDocument()->UkmRecorder()); - return; - } - - DownloadStats::SubframeDownloadFlags flags; - flags.has_sandbox = frame->GetDocument()->IsSandboxed(kSandboxDownloads); - flags.is_cross_origin = frame->IsCrossOriginSubframe(); - flags.is_ad_frame = frame->IsAdSubframe(); - flags.has_gesture = LocalFrame::HasTransientUserActivation(frame); - DownloadStats::RecordSubframeDownloadFlags( - flags, frame->GetDocument()->UkmSourceID(), - frame->GetDocument()->UkmRecorder()); -} - -} // namespace - using namespace html_names; HTMLAnchorElement::HTMLAnchorElement(const QualifiedName& tag_name, @@ -431,7 +405,6 @@ : WebFeature:: kHTMLAnchorElementDownloadInSandboxWithoutUserGesture); } - RecordDownloadMetrics(frame); request.SetSuggestedFilename( static_cast<String>(FastGetAttribute(kDownloadAttr))); request.SetRequestContext(mojom::RequestContextType::DOWNLOAD);
diff --git a/third_party/blink/renderer/core/inspector/console_message.cc b/third_party/blink/renderer/core/inspector/console_message.cc index 24674619..3214262 100644 --- a/third_party/blink/renderer/core/inspector/console_message.cc +++ b/third_party/blink/renderer/core/inspector/console_message.cc
@@ -23,7 +23,7 @@ const String& message, const String& url, DocumentLoader* loader, - unsigned long request_identifier) { + uint64_t request_identifier) { ConsoleMessage* console_message = ConsoleMessage::Create( source, level, message, SourceLocation::Capture(url, 0, 0)); console_message->request_identifier_ =
diff --git a/third_party/blink/renderer/core/inspector/console_message.h b/third_party/blink/renderer/core/inspector/console_message.h index 1e3165a6..90d6533 100644 --- a/third_party/blink/renderer/core/inspector/console_message.h +++ b/third_party/blink/renderer/core/inspector/console_message.h
@@ -41,7 +41,7 @@ const String& message, const String& url, DocumentLoader*, - unsigned long request_identifier); + uint64_t request_identifier); // This creates message from WorkerMessageSource. static ConsoleMessage* CreateFromWorker(mojom::ConsoleMessageLevel,
diff --git a/third_party/blink/renderer/core/inspector/identifiers_factory.cc b/third_party/blink/renderer/core/inspector/identifiers_factory.cc index 2bf77a1..ea4eaa8 100644 --- a/third_party/blink/renderer/core/inspector/identifiers_factory.cc +++ b/third_party/blink/renderer/core/inspector/identifiers_factory.cc
@@ -46,7 +46,7 @@ // static String IdentifiersFactory::RequestId(DocumentLoader* loader, - unsigned long identifier) { + uint64_t identifier) { if (!identifier) return String(); if (loader && loader->MainResourceIdentifier() == identifier) @@ -55,7 +55,7 @@ } // static -String IdentifiersFactory::SubresourceRequestId(unsigned long identifier) { +String IdentifiersFactory::SubresourceRequestId(uint64_t identifier) { return RequestId(nullptr, identifier); }
diff --git a/third_party/blink/renderer/core/inspector/identifiers_factory.h b/third_party/blink/renderer/core/inspector/identifiers_factory.h index 7a000af..53b70f736 100644 --- a/third_party/blink/renderer/core/inspector/identifiers_factory.h +++ b/third_party/blink/renderer/core/inspector/identifiers_factory.h
@@ -45,10 +45,10 @@ public: static String CreateIdentifier(); - static String RequestId(DocumentLoader*, unsigned long identifier); + static String RequestId(DocumentLoader*, uint64_t identifier); // Same as above, but can only be used on reuquests that are guaranteed // to be subresources, not main resource. - static String SubresourceRequestId(unsigned long identifier); + static String SubresourceRequestId(uint64_t identifier); // Returns embedder-provided frame token that is consistent across processes // and can be used for request / call attribution to the context frame.
diff --git a/third_party/blink/renderer/core/inspector/inspector_animation_agent.cc b/third_party/blink/renderer/core/inspector/inspector_animation_agent.cc index 2c651e2..23b54a5 100644 --- a/third_party/blink/renderer/core/inspector/inspector_animation_agent.cc +++ b/third_party/blink/renderer/core/inspector/inspector_animation_agent.cc
@@ -83,25 +83,12 @@ } static std::unique_ptr<protocol::Animation::AnimationEffect> -BuildObjectForAnimationEffect(KeyframeEffect* effect, bool is_transition) { +BuildObjectForAnimationEffect(KeyframeEffect* effect) { ComputedEffectTiming* computed_timing = effect->getComputedTiming(); double delay = computed_timing->delay(); double duration = computed_timing->duration().GetAsUnrestrictedDouble(); String easing = effect->SpecifiedTiming().timing_function->ToString(); - if (is_transition) { - // Obtain keyframes and convert keyframes back to delay - DCHECK(effect->Model()->IsKeyframeEffectModel()); - const KeyframeVector& keyframes = effect->Model()->GetFrames(); - if (keyframes.size() == 3) { - delay = keyframes.at(1)->CheckedOffset() * duration; - duration -= delay; - easing = keyframes.at(1)->Easing().ToString(); - } else { - easing = keyframes.at(0)->Easing().ToString(); - } - } - std::unique_ptr<protocol::Animation::AnimationEffect> animation_object = protocol::Animation::AnimationEffect::create() .setDelay(delay) @@ -188,9 +175,8 @@ } } - animation_effect_object = BuildObjectForAnimationEffect( - ToKeyframeEffect(animation.effect()), - animation_type == AnimationType::CSSTransition); + animation_effect_object = + BuildObjectForAnimationEffect(ToKeyframeEffect(animation.effect())); animation_effect_object->setKeyframesRule(std::move(keyframe_rule)); } @@ -364,36 +350,12 @@ animation = AnimationClone(animation); NonThrowableExceptionState exception_state; - String type = id_to_animation_type_.at(animation_id); - if (type == AnimationType::CSSTransition) { - KeyframeEffect* effect = ToKeyframeEffect(animation->effect()); - const TransitionKeyframeEffectModel* old_model = - ToTransitionKeyframeEffectModel(effect->Model()); - // Refer to CSSAnimations::calculateTransitionUpdateForProperty() for the - // structure of transitions. - const KeyframeVector& frames = old_model->GetFrames(); - DCHECK(frames.size() == 3); - KeyframeVector new_frames; - for (int i = 0; i < 3; i++) - new_frames.push_back(ToTransitionKeyframe(frames[i]->Clone())); - // Update delay, represented by the distance between the first two - // keyframes. - new_frames[1]->SetOffset(delay / (delay + duration)); - effect->Model()->SetFrames(new_frames); - - UnrestrictedDoubleOrString unrestricted_duration; - unrestricted_duration.SetUnrestrictedDouble(duration + delay); - OptionalEffectTiming* timing = OptionalEffectTiming::Create(); - timing->setDuration(unrestricted_duration); - effect->updateTiming(timing, exception_state); - } else { - OptionalEffectTiming* timing = OptionalEffectTiming::Create(); - UnrestrictedDoubleOrString unrestricted_duration; - unrestricted_duration.SetUnrestrictedDouble(duration); - timing->setDuration(unrestricted_duration); - timing->setDelay(delay); - animation->effect()->updateTiming(timing, exception_state); - } + OptionalEffectTiming* timing = OptionalEffectTiming::Create(); + UnrestrictedDoubleOrString unrestricted_duration; + unrestricted_duration.SetUnrestrictedDouble(duration); + timing->setDuration(unrestricted_duration); + timing->setDelay(delay); + animation->effect()->updateTiming(timing, exception_state); return Response::OK(); }
diff --git a/third_party/blink/renderer/core/inspector/inspector_network_agent.cc b/third_party/blink/renderer/core/inspector/inspector_network_agent.cc index a385019..a73712be 100644 --- a/third_party/blink/renderer/core/inspector/inspector_network_agent.cc +++ b/third_party/blink/renderer/core/inspector/inspector_network_agent.cc
@@ -713,7 +713,7 @@ const FetchInitiatorInfo& initiator_info, ResourceRequestBlockedReason reason, ResourceType resource_type) { - unsigned long identifier = CreateUniqueIdentifier(); + uint64_t identifier = CreateUniqueIdentifier(); InspectorPageAgent::ResourceType type = InspectorPageAgent::ToResourceType(resource_type); @@ -731,7 +731,7 @@ void InspectorNetworkAgent::DidChangeResourcePriority( DocumentLoader* loader, - unsigned long identifier, + uint64_t identifier, ResourceLoadPriority load_priority) { String request_id = IdentifiersFactory::RequestId(loader, identifier); GetFrontend()->resourceChangedPriority(request_id, @@ -740,7 +740,7 @@ } void InspectorNetworkAgent::WillSendRequestInternal( - unsigned long identifier, + uint64_t identifier, DocumentLoader* loader, const KURL& fetch_context_url, const ResourceRequest& request, @@ -819,7 +819,7 @@ } void InspectorNetworkAgent::WillSendNavigationRequest( - unsigned long identifier, + uint64_t identifier, DocumentLoader* loader, const KURL& url, const AtomicString& http_method, @@ -885,7 +885,7 @@ } void InspectorNetworkAgent::WillSendRequest( - unsigned long identifier, + uint64_t identifier, DocumentLoader* loader, const KURL& fetch_context_url, const ResourceRequest& request, @@ -904,13 +904,13 @@ } void InspectorNetworkAgent::MarkResourceAsCached(DocumentLoader* loader, - unsigned long identifier) { + uint64_t identifier) { GetFrontend()->requestServedFromCache( IdentifiersFactory::RequestId(loader, identifier)); } void InspectorNetworkAgent::DidReceiveResourceResponse( - unsigned long identifier, + uint64_t identifier, DocumentLoader* loader, const ResourceResponse& response, Resource* cached_resource) { @@ -983,7 +983,7 @@ return status_code >= 400; } -void InspectorNetworkAgent::DidReceiveData(unsigned long identifier, +void InspectorNetworkAgent::DidReceiveData(uint64_t identifier, DocumentLoader* loader, const char* data, uint64_t data_length) { @@ -1006,7 +1006,7 @@ resources_data_->GetAndClearPendingEncodedDataLength(request_id))); } -void InspectorNetworkAgent::DidReceiveBlob(unsigned long identifier, +void InspectorNetworkAgent::DidReceiveBlob(uint64_t identifier, DocumentLoader* loader, scoped_refptr<BlobDataHandle> blob) { String request_id = IdentifiersFactory::RequestId(loader, identifier); @@ -1015,13 +1015,13 @@ void InspectorNetworkAgent::DidReceiveEncodedDataLength( DocumentLoader* loader, - unsigned long identifier, + uint64_t identifier, size_t encoded_data_length) { String request_id = IdentifiersFactory::RequestId(loader, identifier); resources_data_->AddPendingEncodedDataLength(request_id, encoded_data_length); } -void InspectorNetworkAgent::DidFinishLoading(unsigned long identifier, +void InspectorNetworkAgent::DidFinishLoading(uint64_t identifier, DocumentLoader* loader, TimeTicks monotonic_finish_time, int64_t encoded_data_length, @@ -1057,7 +1057,7 @@ } void InspectorNetworkAgent::DidReceiveCorsRedirectResponse( - unsigned long identifier, + uint64_t identifier, DocumentLoader* loader, const ResourceResponse& response, Resource* resource) { @@ -1067,7 +1067,7 @@ WebURLLoaderClient::kUnknownEncodedDataLength, 0, false); } -void InspectorNetworkAgent::DidFailLoading(unsigned long identifier, +void InspectorNetworkAgent::DidFailLoading(uint64_t identifier, DocumentLoader* loader, const ResourceError& error) { String request_id = IdentifiersFactory::RequestId(loader, identifier); @@ -1086,13 +1086,13 @@ error.LocalizedDescription(), canceled, std::move(blocked_reason)); } -void InspectorNetworkAgent::ScriptImported(unsigned long identifier, +void InspectorNetworkAgent::ScriptImported(uint64_t identifier, const String& source_string) { resources_data_->SetResourceContent( IdentifiersFactory::SubresourceRequestId(identifier), source_string); } -void InspectorNetworkAgent::DidReceiveScriptResponse(unsigned long identifier) { +void InspectorNetworkAgent::DidReceiveScriptResponse(uint64_t identifier) { resources_data_->SetResourceType( IdentifiersFactory::SubresourceRequestId(identifier), InspectorPageAgent::kScriptResource); @@ -1100,7 +1100,7 @@ // static bool InspectorNetworkAgent::IsNavigation(DocumentLoader* loader, - unsigned long identifier) { + uint64_t identifier) { return loader && loader->MainResourceIdentifier() == identifier; } @@ -1129,7 +1129,7 @@ } void InspectorNetworkAgent::WillDispatchEventSourceEvent( - unsigned long identifier, + uint64_t identifier, const AtomicString& event_name, const AtomicString& event_id, const String& data) { @@ -1191,7 +1191,7 @@ void InspectorNetworkAgent::DidCreateWebSocket( ExecutionContext* execution_context, - unsigned long identifier, + uint64_t identifier, const KURL& request_url, const String&) { std::unique_ptr<v8_inspector::protocol::Runtime::API::StackTrace> @@ -1216,7 +1216,7 @@ void InspectorNetworkAgent::WillSendWebSocketHandshakeRequest( ExecutionContext*, - unsigned long identifier, + uint64_t identifier, network::mojom::blink::WebSocketHandshakeRequest* request) { DCHECK(request); HTTPHeaderMap headers; @@ -1233,7 +1233,7 @@ void InspectorNetworkAgent::DidReceiveWebSocketHandshakeResponse( ExecutionContext*, - unsigned long identifier, + uint64_t identifier, network::mojom::blink::WebSocketHandshakeRequest* request, network::mojom::blink::WebSocketHandshakeResponse* response) { DCHECK(response); @@ -1275,13 +1275,13 @@ } void InspectorNetworkAgent::DidCloseWebSocket(ExecutionContext*, - unsigned long identifier) { + uint64_t identifier) { GetFrontend()->webSocketClosed( IdentifiersFactory::SubresourceRequestId(identifier), CurrentTimeTicksInSeconds()); } -void InspectorNetworkAgent::DidReceiveWebSocketMessage(unsigned long identifier, +void InspectorNetworkAgent::DidReceiveWebSocketMessage(uint64_t identifier, int op_code, bool masked, const char* payload, @@ -1292,7 +1292,7 @@ WebSocketMessageToProtocol(op_code, masked, payload, payload_length)); } -void InspectorNetworkAgent::DidSendWebSocketMessage(unsigned long identifier, +void InspectorNetworkAgent::DidSendWebSocketMessage(uint64_t identifier, int op_code, bool masked, const char* payload, @@ -1304,7 +1304,7 @@ } void InspectorNetworkAgent::DidReceiveWebSocketMessageError( - unsigned long identifier, + uint64_t identifier, const String& error_message) { GetFrontend()->webSocketFrameError( IdentifiersFactory::RequestId(nullptr, identifier),
diff --git a/third_party/blink/renderer/core/inspector/inspector_network_agent.h b/third_party/blink/renderer/core/inspector/inspector_network_agent.h index 7d582424..b6614057 100644 --- a/third_party/blink/renderer/core/inspector/inspector_network_agent.h +++ b/third_party/blink/renderer/core/inspector/inspector_network_agent.h
@@ -92,55 +92,55 @@ ResourceRequestBlockedReason, ResourceType); void DidChangeResourcePriority(DocumentLoader*, - unsigned long identifier, + uint64_t identifier, ResourceLoadPriority); void PrepareRequest(DocumentLoader*, ResourceRequest&, const FetchInitiatorInfo&, ResourceType); - void WillSendRequest(unsigned long identifier, + void WillSendRequest(uint64_t identifier, DocumentLoader*, const KURL& fetch_context_url, const ResourceRequest&, const ResourceResponse& redirect_response, const FetchInitiatorInfo&, ResourceType); - void WillSendNavigationRequest(unsigned long identifier, + void WillSendNavigationRequest(uint64_t identifier, DocumentLoader*, const KURL&, const AtomicString& http_method, EncodedFormData* http_body); - void MarkResourceAsCached(DocumentLoader*, unsigned long identifier); - void DidReceiveResourceResponse(unsigned long identifier, + void MarkResourceAsCached(DocumentLoader*, uint64_t identifier); + void DidReceiveResourceResponse(uint64_t identifier, DocumentLoader*, const ResourceResponse&, Resource*); - void DidReceiveData(unsigned long identifier, + void DidReceiveData(uint64_t identifier, DocumentLoader*, const char* data, uint64_t data_length); - void DidReceiveBlob(unsigned long identifier, + void DidReceiveBlob(uint64_t identifier, DocumentLoader*, scoped_refptr<BlobDataHandle>); void DidReceiveEncodedDataLength(DocumentLoader*, - unsigned long identifier, + uint64_t identifier, size_t encoded_data_length); - void DidFinishLoading(unsigned long identifier, + void DidFinishLoading(uint64_t identifier, DocumentLoader*, TimeTicks monotonic_finish_time, int64_t encoded_data_length, int64_t decoded_body_length, bool should_report_corb_blocking); - void DidReceiveCorsRedirectResponse(unsigned long identifier, + void DidReceiveCorsRedirectResponse(uint64_t identifier, DocumentLoader*, const ResourceResponse&, Resource*); - void DidFailLoading(unsigned long identifier, + void DidFailLoading(uint64_t identifier, DocumentLoader*, const ResourceError&); void DidCommitLoad(LocalFrame*, DocumentLoader*); - void ScriptImported(unsigned long identifier, const String& source_string); - void DidReceiveScriptResponse(unsigned long identifier); + void ScriptImported(uint64_t identifier, const String& source_string); + void DidReceiveScriptResponse(uint64_t identifier); void ShouldForceCorsPreflight(bool* result); void ShouldBlockRequest(const KURL&, bool* result); void ShouldBypassServiceWorker(bool* result); @@ -155,7 +155,7 @@ void DidFinishXHR(XMLHttpRequest*); void WillSendEventSourceRequest(); - void WillDispatchEventSourceEvent(unsigned long identifier, + void WillDispatchEventSourceEvent(uint64_t identifier, const AtomicString& event_name, const AtomicString& event_id, const String& data); @@ -169,30 +169,30 @@ void FrameClearedScheduledNavigation(LocalFrame*); void DidCreateWebSocket(ExecutionContext*, - unsigned long identifier, + uint64_t identifier, const KURL& request_url, const String&); void WillSendWebSocketHandshakeRequest( ExecutionContext*, - unsigned long identifier, + uint64_t identifier, network::mojom::blink::WebSocketHandshakeRequest*); void DidReceiveWebSocketHandshakeResponse( ExecutionContext*, - unsigned long identifier, + uint64_t identifier, network::mojom::blink::WebSocketHandshakeRequest*, network::mojom::blink::WebSocketHandshakeResponse*); - void DidCloseWebSocket(ExecutionContext*, unsigned long identifier); - void DidReceiveWebSocketMessage(unsigned long identifier, + void DidCloseWebSocket(ExecutionContext*, uint64_t identifier); + void DidReceiveWebSocketMessage(uint64_t identifier, int op_code, bool masked, const char* payload, size_t payload_length); - void DidSendWebSocketMessage(unsigned long identifier, + void DidSendWebSocketMessage(uint64_t identifier, int op_code, bool masked, const char* payload, size_t payload_length); - void DidReceiveWebSocketMessageError(unsigned long identifier, const String&); + void DidReceiveWebSocketMessageError(uint64_t identifier, const String&); // Called from frontend protocol::Response enable(Maybe<int> total_buffer_size, @@ -246,7 +246,7 @@ private: void Enable(); - void WillSendRequestInternal(unsigned long identifier, + void WillSendRequestInternal(uint64_t identifier, DocumentLoader*, const KURL& fetch_context_url, const ResourceRequest&, @@ -261,7 +261,7 @@ static std::unique_ptr<protocol::Network::Initiator> BuildInitiatorObject( Document*, const FetchInitiatorInfo&); - static bool IsNavigation(DocumentLoader*, unsigned long identifier); + static bool IsNavigation(DocumentLoader*, uint64_t identifier); // This is null while inspecting workers. Member<InspectedFrames> inspected_frames_;
diff --git a/third_party/blink/renderer/core/inspector/inspector_overlay_agent.cc b/third_party/blink/renderer/core/inspector/inspector_overlay_agent.cc index 807435ce..9f4087b 100644 --- a/third_party/blink/renderer/core/inspector/inspector_overlay_agent.cc +++ b/third_party/blink/renderer/core/inspector/inspector_overlay_agent.cc
@@ -511,7 +511,9 @@ LocalFrame* frame = IdentifiersFactory::FrameById(inspected_frames_, frame_id); // FIXME: Inspector doesn't currently work cross process. - if (frame && frame->DeprecatedLocalOwner()) { + if (!frame) + return Response::Error("Invalid frame id"); + if (frame->DeprecatedLocalOwner()) { std::unique_ptr<InspectorHighlightConfig> highlight_config = std::make_unique<InspectorHighlightConfig>(); highlight_config->show_info = true; // Always show tooltips for frames. @@ -522,6 +524,8 @@ SetInspectTool(MakeGarbageCollected<NodeHighlightTool>( frame->DeprecatedLocalOwner(), String(), std::move(highlight_config))); + } else { + PickTheRightTool(); } return Response::OK(); }
diff --git a/third_party/blink/renderer/core/inspector/inspector_trace_events.cc b/third_party/blink/renderer/core/inspector/inspector_trace_events.cc index ccc8637..11af29e 100644 --- a/third_party/blink/renderer/core/inspector/inspector_trace_events.cc +++ b/third_party/blink/renderer/core/inspector/inspector_trace_events.cc
@@ -51,14 +51,14 @@ namespace { -void* AsyncId(unsigned long identifier) { +void* AsyncId(uint64_t identifier) { // This value should be odd to avoid collisions with regular pointers. return reinterpret_cast<void*>((identifier << 1) | 1); } std::unique_ptr<TracedValue> InspectorParseHtmlBeginData(Document* document, unsigned start_line) { - std::unique_ptr<TracedValue> value = TracedValue::Create(); + auto value = std::make_unique<TracedValue>(); value->SetInteger("startLine", start_line); value->SetString("frame", IdentifiersFactory::FrameId(document->GetFrame())); value->SetString("url", document->Url().GetString()); @@ -67,13 +67,13 @@ } std::unique_ptr<TracedValue> InspectorParseHtmlEndData(unsigned end_line) { - std::unique_ptr<TracedValue> value = TracedValue::Create(); + auto value = std::make_unique<TracedValue>(); value->SetInteger("endLine", end_line); return value; } std::unique_ptr<TracedValue> GetNavigationTracingData(Document* document) { - std::unique_ptr<TracedValue> data = TracedValue::Create(); + auto data = std::make_unique<TracedValue>(); data->SetString("navigationId", IdentifiersFactory::LoaderId(document->Loader())); @@ -102,7 +102,7 @@ } void InspectorTraceEvents::WillSendRequest( - unsigned long identifier, + uint64_t identifier, DocumentLoader* loader, const KURL& fetch_context_url, const ResourceRequest& request, @@ -117,7 +117,7 @@ } void InspectorTraceEvents::WillSendNavigationRequest( - unsigned long identifier, + uint64_t identifier, DocumentLoader* loader, const KURL& url, const AtomicString& http_method, @@ -130,7 +130,7 @@ } void InspectorTraceEvents::DidReceiveResourceResponse( - unsigned long identifier, + uint64_t identifier, DocumentLoader* loader, const ResourceResponse& response, Resource*) { @@ -141,7 +141,7 @@ loader, identifier, frame, response)); } -void InspectorTraceEvents::DidReceiveData(unsigned long identifier, +void InspectorTraceEvents::DidReceiveData(uint64_t identifier, DocumentLoader* loader, const char* data, uint64_t encoded_data_length) { @@ -154,7 +154,7 @@ AsyncId(identifier), "data"); } -void InspectorTraceEvents::DidFinishLoading(unsigned long identifier, +void InspectorTraceEvents::DidFinishLoading(uint64_t identifier, DocumentLoader* loader, TimeTicks finish_time, int64_t encoded_data_length, @@ -170,7 +170,7 @@ AsyncId(identifier)); } -void InspectorTraceEvents::DidFailLoading(unsigned long identifier, +void InspectorTraceEvents::DidFailLoading(uint64_t identifier, DocumentLoader* loader, const ResourceError&) { TRACE_EVENT_INSTANT1("devtools.timeline", "ResourceFinish", @@ -423,7 +423,7 @@ ContainerNode& node, const InvalidationSet& invalidation_set, const char* invalidated_selector) { - std::unique_ptr<TracedValue> value = TracedValue::Create(); + auto value = std::make_unique<TracedValue>(); value->SetString("frame", IdentifiersFactory::FrameId(node.GetDocument().GetFrame())); SetNodeInfo(value.get(), &node, "nodeId", "nodeName"); @@ -547,7 +547,7 @@ namespace inspector_style_invalidator_invalidate_event { std::unique_ptr<TracedValue> FillCommonPart(ContainerNode& node, const char* reason) { - std::unique_ptr<TracedValue> value = TracedValue::Create(); + auto value = std::make_unique<TracedValue>(); value->SetString("frame", IdentifiersFactory::FrameId(node.GetDocument().GetFrame())); SetNodeInfo(value.get(), &node, "nodeId", "nodeName"); @@ -595,7 +595,7 @@ const StyleChangeReasonForTracing& reason) { DCHECK(node); - std::unique_ptr<TracedValue> value = TracedValue::Create(); + auto value = std::make_unique<TracedValue>(); value->SetString("frame", IdentifiersFactory::FrameId(node->GetDocument().GetFrame())); SetNodeInfo(value.get(), node, "nodeId", "nodeName"); @@ -614,7 +614,7 @@ frame.View()->CountObjectsNeedingLayout(needs_layout_objects, total_objects, is_partial); - std::unique_ptr<TracedValue> value = TracedValue::Create(); + auto value = std::make_unique<TracedValue>(); value->SetInteger("dirtyObjects", needs_layout_objects); value->SetInteger("totalObjects", total_objects); value->SetBoolean("partialLayout", is_partial); @@ -656,7 +656,7 @@ Vector<FloatQuad> quads; root_for_this_layout->AbsoluteQuads(quads); - std::unique_ptr<TracedValue> value = TracedValue::Create(); + auto value = std::make_unique<TracedValue>(); if (quads.size() >= 1) { CreateQuad(value.get(), "root", quads[0]); SetGeneratingNodeInfo(value.get(), root_for_this_layout, "rootNode"); @@ -706,7 +706,7 @@ const LayoutObject* layout_object, LayoutInvalidationReasonForTracing reason) { DCHECK(layout_object); - std::unique_ptr<TracedValue> value = TracedValue::Create(); + auto value = std::make_unique<TracedValue>(); value->SetString("frame", IdentifiersFactory::FrameId(layout_object->GetFrame())); SetGeneratingNodeInfo(value.get(), layout_object, "nodeId", "nodeName"); @@ -717,7 +717,7 @@ std::unique_ptr<TracedValue> inspector_paint_invalidation_tracking_event::Data( const LayoutObject& layout_object) { - std::unique_ptr<TracedValue> value = TracedValue::Create(); + auto value = std::make_unique<TracedValue>(); value->SetString("frame", IdentifiersFactory::FrameId(layout_object.GetFrame())); const auto* paint_container = @@ -730,11 +730,11 @@ std::unique_ptr<TracedValue> inspector_change_resource_priority_event::Data( DocumentLoader* loader, - unsigned long identifier, + uint64_t identifier, const ResourceLoadPriority& load_priority) { String request_id = IdentifiersFactory::RequestId(loader, identifier); - std::unique_ptr<TracedValue> value = TracedValue::Create(); + auto value = std::make_unique<TracedValue>(); value->SetString("requestId", request_id); value->SetString("priority", ResourcePriorityString(load_priority)); return value; @@ -742,14 +742,14 @@ std::unique_ptr<TracedValue> inspector_send_request_event::Data( DocumentLoader* loader, - unsigned long identifier, + uint64_t identifier, LocalFrame* frame, const ResourceRequest& request) { String request_id = IdentifiersFactory::RequestId(loader, identifier); DCHECK_EQ(network::mojom::RequestContextFrameType::kNone, request.GetFrameType()); - std::unique_ptr<TracedValue> value = TracedValue::Create(); + auto value = std::make_unique<TracedValue>(); value->SetString("requestId", request_id); value->SetString("frame", IdentifiersFactory::FrameId(frame)); value->SetString("url", request.Url().GetString()); @@ -763,11 +763,11 @@ std::unique_ptr<TracedValue> inspector_send_navigation_request_event::Data( DocumentLoader* loader, - unsigned long identifier, + uint64_t identifier, LocalFrame* frame, const KURL& url, const AtomicString& http_method) { - std::unique_ptr<TracedValue> value = TracedValue::Create(); + auto value = std::make_unique<TracedValue>(); value->SetString("requestId", IdentifiersFactory::LoaderId(loader)); value->SetString("frame", IdentifiersFactory::FrameId(frame)); value->SetString("url", url.GetString()); @@ -815,12 +815,12 @@ std::unique_ptr<TracedValue> inspector_receive_response_event::Data( DocumentLoader* loader, - unsigned long identifier, + uint64_t identifier, LocalFrame* frame, const ResourceResponse& response) { String request_id = IdentifiersFactory::RequestId(loader, identifier); - std::unique_ptr<TracedValue> value = TracedValue::Create(); + auto value = std::make_unique<TracedValue>(); value->SetString("requestId", request_id); value->SetString("frame", IdentifiersFactory::FrameId(frame)); value->SetInteger("statusCode", response.HttpStatusCode()); @@ -840,12 +840,12 @@ std::unique_ptr<TracedValue> inspector_receive_data_event::Data( DocumentLoader* loader, - unsigned long identifier, + uint64_t identifier, LocalFrame* frame, uint64_t encoded_data_length) { String request_id = IdentifiersFactory::RequestId(loader, identifier); - std::unique_ptr<TracedValue> value = TracedValue::Create(); + auto value = std::make_unique<TracedValue>(); value->SetString("requestId", request_id); value->SetString("frame", IdentifiersFactory::FrameId(frame)); value->SetDouble("encodedDataLength", encoded_data_length); @@ -854,14 +854,14 @@ std::unique_ptr<TracedValue> inspector_resource_finish_event::Data( DocumentLoader* loader, - unsigned long identifier, + uint64_t identifier, TimeTicks finish_time, bool did_fail, int64_t encoded_data_length, int64_t decoded_body_length) { String request_id = IdentifiersFactory::RequestId(loader, identifier); - std::unique_ptr<TracedValue> value = TracedValue::Create(); + auto value = std::make_unique<TracedValue>(); value->SetString("requestId", request_id); value->SetBoolean("didFail", did_fail); value->SetDouble("encodedDataLength", encoded_data_length); @@ -879,7 +879,7 @@ static std::unique_ptr<TracedValue> GenericTimerData(ExecutionContext* context, int timer_id) { - std::unique_ptr<TracedValue> value = TracedValue::Create(); + auto value = std::make_unique<TracedValue>(); value->SetInteger("timerId", timer_id); if (LocalFrame* frame = FrameForExecutionContext(context)) value->SetString("frame", IdentifiersFactory::FrameId(frame)); @@ -915,7 +915,7 @@ std::unique_ptr<TracedValue> inspector_animation_frame_event::Data( ExecutionContext* context, int callback_id) { - std::unique_ptr<TracedValue> value = TracedValue::Create(); + auto value = std::make_unique<TracedValue>(); value->SetInteger("id", callback_id); if (auto* document = DynamicTo<Document>(context)) { value->SetString("frame", @@ -929,7 +929,7 @@ std::unique_ptr<TracedValue> GenericIdleCallbackEvent(ExecutionContext* context, int id) { - std::unique_ptr<TracedValue> value = TracedValue::Create(); + auto value = std::make_unique<TracedValue>(); value->SetInteger("id", id); if (LocalFrame* frame = FrameForExecutionContext(context)) value->SetString("frame", IdentifiersFactory::FrameId(frame)); @@ -965,7 +965,7 @@ std::unique_ptr<TracedValue> inspector_parse_author_style_sheet_event::Data( const CSSStyleSheetResource* cached_style_sheet) { - std::unique_ptr<TracedValue> value = TracedValue::Create(); + auto value = std::make_unique<TracedValue>(); value->SetString("styleSheetUrl", cached_style_sheet->Url().GetString()); return value; } @@ -973,7 +973,7 @@ std::unique_ptr<TracedValue> inspector_xhr_ready_state_change_event::Data( ExecutionContext* context, XMLHttpRequest* request) { - std::unique_ptr<TracedValue> value = TracedValue::Create(); + auto value = std::make_unique<TracedValue>(); value->SetString("url", request->Url().GetString()); value->SetInteger("readyState", request->readyState()); if (LocalFrame* frame = FrameForExecutionContext(context)) @@ -985,7 +985,7 @@ std::unique_ptr<TracedValue> inspector_xhr_load_event::Data( ExecutionContext* context, XMLHttpRequest* request) { - std::unique_ptr<TracedValue> value = TracedValue::Create(); + auto value = std::make_unique<TracedValue>(); value->SetString("url", request->Url().GetString()); if (LocalFrame* frame = FrameForExecutionContext(context)) value->SetString("frame", IdentifiersFactory::FrameId(frame)); @@ -1032,7 +1032,7 @@ const LayoutObject& paint_invalidation_container = layer->GetLayoutObject().ContainerForPaintInvalidation(); - std::unique_ptr<TracedValue> value = TracedValue::Create(); + auto value = std::make_unique<TracedValue>(); value->SetString("frame", IdentifiersFactory::FrameId( paint_invalidation_container.GetFrame())); SetGeneratingNodeInfo(value.get(), &paint_invalidation_container, "paintId"); @@ -1044,7 +1044,7 @@ LayoutObject* layout_object, const LayoutRect& clip_rect, const GraphicsLayer* graphics_layer) { - std::unique_ptr<TracedValue> value = TracedValue::Create(); + auto value = std::make_unique<TracedValue>(); value->SetString("frame", IdentifiersFactory::FrameId(layout_object->GetFrame())); FloatQuad quad; @@ -1058,7 +1058,7 @@ } std::unique_ptr<TracedValue> FrameEventData(LocalFrame* frame) { - std::unique_ptr<TracedValue> value = TracedValue::Create(); + auto value = std::make_unique<TracedValue>(); bool is_main_frame = frame && frame->IsMainFrame(); value->SetBoolean("isMainFrame", is_main_frame); // TODO(dgozman): this does not work with OOPIF, so everyone who @@ -1099,7 +1099,7 @@ std::unique_ptr<TracedValue> inspector_scroll_layer_event::Data( LayoutObject* layout_object) { - std::unique_ptr<TracedValue> value = TracedValue::Create(); + auto value = std::make_unique<TracedValue>(); value->SetString("frame", IdentifiersFactory::FrameId(layout_object->GetFrame())); SetGeneratingNodeInfo(value.get(), layout_object, "nodeId"); @@ -1108,7 +1108,7 @@ std::unique_ptr<TracedValue> inspector_update_layer_tree_event::Data( LocalFrame* frame) { - std::unique_ptr<TracedValue> value = TracedValue::Create(); + auto value = std::make_unique<TracedValue>(); value->SetString("frame", IdentifiersFactory::FrameId(frame)); return value; } @@ -1116,7 +1116,7 @@ namespace { std::unique_ptr<TracedValue> FillLocation(const String& url, const TextPosition& text_position) { - std::unique_ptr<TracedValue> value = TracedValue::Create(); + auto value = std::make_unique<TracedValue>(); value->SetString("url", url); value->SetInteger("lineNumber", text_position.line_.OneBasedInt()); value->SetInteger("columnNumber", text_position.column_.OneBasedInt()); @@ -1135,10 +1135,10 @@ } std::unique_ptr<TracedValue> inspector_parse_script_event::Data( - unsigned long identifier, + uint64_t identifier, const String& url) { String request_id = IdentifiersFactory::RequestId(nullptr, identifier); - std::unique_ptr<TracedValue> value = TracedValue::Create(); + auto value = std::make_unique<TracedValue>(); value->SetString("requestId", request_id); value->SetString("url", url); return value; @@ -1196,7 +1196,7 @@ std::unique_ptr<TracedValue> inspector_function_call_event::Data( ExecutionContext* context, const v8::Local<v8::Function>& function) { - std::unique_ptr<TracedValue> value = TracedValue::Create(); + auto value = std::make_unique<TracedValue>(); if (LocalFrame* frame = FrameForExecutionContext(context)) value->SetString("frame", IdentifiersFactory::FrameId(frame)); @@ -1222,7 +1222,7 @@ const LayoutImage& layout_image, const FloatRect& src_rect, const FloatRect& dest_rect) { - std::unique_ptr<TracedValue> value = TracedValue::Create(); + auto value = std::make_unique<TracedValue>(); SetGeneratingNodeInfo(value.get(), &layout_image, "nodeId"); if (const ImageResourceContent* resource = layout_image.CachedImage()) value->SetString("url", resource->Url().GetString()); @@ -1240,7 +1240,7 @@ std::unique_ptr<TracedValue> inspector_paint_image_event::Data( const LayoutObject& owning_layout_object, const StyleImage& style_image) { - std::unique_ptr<TracedValue> value = TracedValue::Create(); + auto value = std::make_unique<TracedValue>(); SetGeneratingNodeInfo(value.get(), &owning_layout_object, "nodeId"); if (const ImageResourceContent* resource = style_image.CachedImage()) value->SetString("url", resource->Url().GetString()); @@ -1252,7 +1252,7 @@ const StyleImage& style_image, const FloatRect& src_rect, const FloatRect& dest_rect) { - std::unique_ptr<TracedValue> value = TracedValue::Create(); + auto value = std::make_unique<TracedValue>(); if (node) SetNodeInfo(value.get(), node, "nodeId", nullptr); if (const ImageResourceContent* resource = style_image.CachedImage()) @@ -1271,7 +1271,7 @@ std::unique_ptr<TracedValue> inspector_paint_image_event::Data( const LayoutObject* owning_layout_object, const ImageResourceContent& image_resource) { - std::unique_ptr<TracedValue> value = TracedValue::Create(); + auto value = std::make_unique<TracedValue>(); SetGeneratingNodeInfo(value.get(), owning_layout_object, "nodeId"); value->SetString("url", image_resource.Url().GetString()); return value; @@ -1284,7 +1284,7 @@ } std::unique_ptr<TracedValue> inspector_update_counters_event::Data() { - std::unique_ptr<TracedValue> value = TracedValue::Create(); + auto value = std::make_unique<TracedValue>(); if (IsMainThread()) { value->SetInteger("documents", InstanceCounters::CounterValue( InstanceCounters::kDocumentCounter)); @@ -1300,7 +1300,7 @@ std::unique_ptr<TracedValue> inspector_invalidate_layout_event::Data( LocalFrame* frame) { - std::unique_ptr<TracedValue> value = TracedValue::Create(); + auto value = std::make_unique<TracedValue>(); value->SetString("frame", IdentifiersFactory::FrameId(frame)); SetCallStack(value.get()); return value; @@ -1308,7 +1308,7 @@ std::unique_ptr<TracedValue> inspector_recalculate_styles_event::Data( LocalFrame* frame) { - std::unique_ptr<TracedValue> value = TracedValue::Create(); + auto value = std::make_unique<TracedValue>(); value->SetString("frame", IdentifiersFactory::FrameId(frame)); SetCallStack(value.get()); return value; @@ -1316,7 +1316,7 @@ std::unique_ptr<TracedValue> inspector_event_dispatch_event::Data( const Event& event) { - std::unique_ptr<TracedValue> value = TracedValue::Create(); + auto value = std::make_unique<TracedValue>(); value->SetString("type", event.type()); SetCallStack(value.get()); return value; @@ -1325,7 +1325,7 @@ std::unique_ptr<TracedValue> inspector_time_stamp_event::Data( ExecutionContext* context, const String& message) { - std::unique_ptr<TracedValue> value = TracedValue::Create(); + auto value = std::make_unique<TracedValue>(); value->SetString("message", message); if (LocalFrame* frame = FrameForExecutionContext(context)) value->SetString("frame", IdentifiersFactory::FrameId(frame)); @@ -1338,7 +1338,7 @@ const base::UnguessableToken& parent_devtools_token, const KURL& url, PlatformThreadId worker_thread_id) { - std::unique_ptr<TracedValue> value = TracedValue::Create(); + auto value = std::make_unique<TracedValue>(); value->SetString("frame", IdentifiersFactory::IdFromToken(parent_devtools_token)); value->SetString("url", url.GetString()); @@ -1351,7 +1351,7 @@ std::unique_ptr<TracedValue> inspector_tracing_started_in_frame::Data( const String& session_id, LocalFrame* frame) { - std::unique_ptr<TracedValue> value = TracedValue::Create(); + auto value = std::make_unique<TracedValue>(); value->SetString("sessionId", session_id); value->SetString("page", IdentifiersFactory::FrameId(&frame->LocalFrameRoot())); @@ -1371,7 +1371,7 @@ std::unique_ptr<TracedValue> inspector_set_layer_tree_id::Data( LocalFrame* frame) { - std::unique_ptr<TracedValue> value = TracedValue::Create(); + auto value = std::make_unique<TracedValue>(); value->SetString("frame", IdentifiersFactory::FrameId(frame)); WebLayerTreeView* layerTreeView = frame->GetPage()->GetChromeClient().GetWebLayerTreeView(frame); @@ -1382,7 +1382,7 @@ std::unique_ptr<TracedValue> inspector_animation_event::Data( const Animation& animation) { - std::unique_ptr<TracedValue> value = TracedValue::Create(); + auto value = std::make_unique<TracedValue>(); value->SetString("id", String::Number(animation.SequenceNumber())); value->SetString("state", animation.playState()); if (const AnimationEffect* effect = animation.effect()) { @@ -1397,7 +1397,7 @@ std::unique_ptr<TracedValue> inspector_animation_state_event::Data( const Animation& animation) { - std::unique_ptr<TracedValue> value = TracedValue::Create(); + auto value = std::make_unique<TracedValue>(); value->SetString("state", animation.playState()); return value; } @@ -1406,7 +1406,7 @@ const HitTestRequest& request, const HitTestLocation& location, const HitTestResult& result) { - std::unique_ptr<TracedValue> value(TracedValue::Create()); + auto value(std::make_unique<TracedValue>()); value->SetInteger("x", location.RoundedPoint().X()); value->SetInteger("y", location.RoundedPoint().Y()); if (location.IsRectBasedTest()) @@ -1426,7 +1426,7 @@ std::unique_ptr<TracedValue> inspector_async_task::Data( const StringView& name) { - std::unique_ptr<TracedValue> value = TracedValue::Create(); + auto value = std::make_unique<TracedValue>(); value->SetString("name", name.ToString()); return value; }
diff --git a/third_party/blink/renderer/core/inspector/inspector_trace_events.h b/third_party/blink/renderer/core/inspector/inspector_trace_events.h index 2e25f35..fca953b 100644 --- a/third_party/blink/renderer/core/inspector/inspector_trace_events.h +++ b/third_party/blink/renderer/core/inspector/inspector_trace_events.h
@@ -83,33 +83,33 @@ public: InspectorTraceEvents() = default; - void WillSendRequest(unsigned long identifier, + void WillSendRequest(uint64_t identifier, DocumentLoader*, const KURL& fetch_context_url, const ResourceRequest&, const ResourceResponse& redirect_response, const FetchInitiatorInfo&, ResourceType); - void WillSendNavigationRequest(unsigned long identifier, + void WillSendNavigationRequest(uint64_t identifier, DocumentLoader*, const KURL&, const AtomicString& http_method, EncodedFormData*); - void DidReceiveResourceResponse(unsigned long identifier, + void DidReceiveResourceResponse(uint64_t identifier, DocumentLoader*, const ResourceResponse&, Resource*); - void DidReceiveData(unsigned long identifier, + void DidReceiveData(uint64_t identifier, DocumentLoader*, const char* data, uint64_t data_length); - void DidFinishLoading(unsigned long identifier, + void DidFinishLoading(uint64_t identifier, DocumentLoader*, TimeTicks monotonic_finish_time, int64_t encoded_data_length, int64_t decoded_body_length, bool should_report_corb_blocking); - void DidFailLoading(unsigned long identifier, + void DidFailLoading(uint64_t identifier, DocumentLoader*, const ResourceError&); @@ -266,20 +266,20 @@ namespace inspector_change_resource_priority_event { std::unique_ptr<TracedValue> Data(DocumentLoader*, - unsigned long identifier, + uint64_t identifier, const ResourceLoadPriority&); } namespace inspector_send_request_event { std::unique_ptr<TracedValue> Data(DocumentLoader*, - unsigned long identifier, + uint64_t identifier, LocalFrame*, const ResourceRequest&); } namespace inspector_send_navigation_request_event { std::unique_ptr<TracedValue> Data(DocumentLoader*, - unsigned long identifier, + uint64_t identifier, LocalFrame*, const KURL&, const AtomicString& http_method); @@ -287,21 +287,21 @@ namespace inspector_receive_response_event { std::unique_ptr<TracedValue> Data(DocumentLoader*, - unsigned long identifier, + uint64_t identifier, LocalFrame*, const ResourceResponse&); } namespace inspector_receive_data_event { std::unique_ptr<TracedValue> Data(DocumentLoader*, - unsigned long identifier, + uint64_t identifier, LocalFrame*, uint64_t encoded_data_length); } namespace inspector_resource_finish_event { std::unique_ptr<TracedValue> Data(DocumentLoader*, - unsigned long identifier, + uint64_t identifier, TimeTicks finish_time, bool did_fail, int64_t encoded_data_length, @@ -412,7 +412,7 @@ } namespace inspector_parse_script_event { -std::unique_ptr<TracedValue> Data(unsigned long identifier, const String& url); +std::unique_ptr<TracedValue> Data(uint64_t identifier, const String& url); } namespace inspector_compile_script_event {
diff --git a/third_party/blink/renderer/core/inspector/main_thread_debugger.cc b/third_party/blink/renderer/core/inspector/main_thread_debugger.cc index f8de980..54da09f 100644 --- a/third_party/blink/renderer/core/inspector/main_thread_debugger.cc +++ b/third_party/blink/renderer/core/inspector/main_thread_debugger.cc
@@ -282,8 +282,20 @@ v8::Local<v8::Context> MainThreadDebugger::ensureDefaultContextInGroup( int context_group_id) { LocalFrame* frame = WeakIdentifierMap<LocalFrame>::Lookup(context_group_id); - ScriptState* script_state = - frame ? ToScriptStateForMainWorld(frame) : nullptr; + if (!frame) + return v8::Local<v8::Context>(); + + // This is a workaround code with a bailout to avoid crashing in + // LocalWindowProxy::Initialize(). + // We cannot request a ScriptState on a provisional frame as it would lead + // to a context creation on it, which is not allowed. Remove this extra check + // when provisional frames concept gets eliminated. See crbug.com/897816 + // The DCHECK is kept to catch additional regressions earlier. + DCHECK(!frame->IsProvisional()); + if (frame->IsProvisional()) + return v8::Local<v8::Context>(); + + ScriptState* script_state = ToScriptStateForMainWorld(frame); return script_state ? script_state->GetContext() : v8::Local<v8::Context>(); }
diff --git a/third_party/blink/renderer/core/layout/jank_tracker.cc b/third_party/blink/renderer/core/layout/jank_tracker.cc index 2797c57..eda26ed 100644 --- a/third_party/blink/renderer/core/layout/jank_tracker.cc +++ b/third_party/blink/renderer/core/layout/jank_tracker.cc
@@ -282,7 +282,7 @@ std::unique_ptr<TracedValue> JankTracker::PerFrameTraceData( double jank_fraction, double granularity_scale) const { - std::unique_ptr<TracedValue> value = TracedValue::Create(); + auto value = std::make_unique<TracedValue>(); value->SetDouble("jank_fraction", jank_fraction); value->SetDouble("cumulative_score", score_); value->SetDouble("max_distance", max_distance_);
diff --git a/third_party/blink/renderer/core/layout/layout_analyzer.cc b/third_party/blink/renderer/core/layout/layout_analyzer.cc index 92ae9e1b..3778ade79 100644 --- a/third_party/blink/renderer/core/layout/layout_analyzer.cc +++ b/third_party/blink/renderer/core/layout/layout_analyzer.cc
@@ -96,7 +96,7 @@ } std::unique_ptr<TracedValue> LayoutAnalyzer::ToTracedValue() { - std::unique_ptr<TracedValue> traced_value(TracedValue::Create()); + auto traced_value(std::make_unique<TracedValue>()); for (size_t i = 0; i < kNumCounters; ++i) { if (counters_[i] > 0) { traced_value->SetIntegerWithCopiedName(
diff --git a/third_party/blink/renderer/core/layout/layout_box.cc b/third_party/blink/renderer/core/layout/layout_box.cc index 7ef03df..df88cc3 100644 --- a/third_party/blink/renderer/core/layout/layout_box.cc +++ b/third_party/blink/renderer/core/layout/layout_box.cc
@@ -492,6 +492,8 @@ SetFloating(!IsOutOfFlowPositioned() && style_to_use.IsFloating()); SetHasTransformRelatedProperty(style_to_use.HasTransformRelatedProperty()); SetHasReflection(style_to_use.BoxReflect()); + // LayoutTable and LayoutTableCell will overwrite this flag if needed. + SetHasNonCollapsedBorderDecoration(style_to_use.HasBorderDecoration()); } void LayoutBox::UpdateLayout() {
diff --git a/third_party/blink/renderer/core/layout/layout_box_test.cc b/third_party/blink/renderer/core/layout/layout_box_test.cc index 50dff4c2..5593215 100644 --- a/third_party/blink/renderer/core/layout/layout_box_test.cc +++ b/third_party/blink/renderer/core/layout/layout_box_test.cc
@@ -1354,4 +1354,15 @@ EXPECT_EQ(LayoutRect(90, 30, 385, 284), rtl_vrl->PhysicalContentBoxRect()); } +TEST_P(LayoutBoxTest, HasNonCollapsedBorderDecoration) { + SetBodyInnerHTML("<div id='div'></div>"); + auto* div = GetLayoutBoxByElementId("div"); + EXPECT_FALSE(div->HasNonCollapsedBorderDecoration()); + + ToElement(div->GetNode()) + ->setAttribute(html_names::kStyleAttr, "border: 1px solid black"); + GetDocument().View()->UpdateAllLifecyclePhasesExceptPaint(); + EXPECT_TRUE(div->HasNonCollapsedBorderDecoration()); +} + } // namespace blink
diff --git a/third_party/blink/renderer/core/layout/layout_geometry_map.cc b/third_party/blink/renderer/core/layout/layout_geometry_map.cc index e60bd3b8f..02e2d03 100644 --- a/third_party/blink/renderer/core/layout/layout_geometry_map.cc +++ b/third_party/blink/renderer/core/layout/layout_geometry_map.cc
@@ -322,7 +322,7 @@ step.offset_for_fixed_position_ = offset_for_fixed_position; if (!t.IsIntegerTranslation()) - step.transform_ = TransformationMatrix::Create(t); + step.transform_ = std::make_unique<TransformationMatrix>(t); else step.offset_ = LayoutSize(LayoutUnit(t.E()), LayoutUnit(t.F()));
diff --git a/third_party/blink/renderer/core/layout/layout_object.h b/third_party/blink/renderer/core/layout/layout_object.h index 208feaf..9568428 100644 --- a/third_party/blink/renderer/core/layout/layout_object.h +++ b/third_party/blink/renderer/core/layout/layout_object.h
@@ -2223,6 +2223,18 @@ context->DidPaint(); } + // This flag caches StyleRef().HasBorderDecoration() && + // !Table()->ShouldCollapseBorders(). + bool HasNonCollapsedBorderDecoration() const { + // We can only ensure this flag is up-to-date after PrePaint. + DCHECK_GE(GetDocument().Lifecycle().GetState(), + DocumentLifecycle::kPrePaintClean); + return bitfields_.HasNonCollapsedBorderDecoration(); + } + void SetHasNonCollapsedBorderDecoration(bool b) { + bitfields_.SetHasNonCollapsedBorderDecoration(b); + } + protected: enum LayoutObjectType { kLayoutObjectBr, @@ -2610,6 +2622,7 @@ is_global_root_scroller_(false), pending_update_first_line_image_observers_(false), is_html_legend_element_(false), + has_non_collapsed_border_decoration_(false), positioned_state_(kIsStaticallyPositioned), selection_state_(static_cast<unsigned>(SelectionState::kNone)), subtree_paint_property_update_reasons_( @@ -2856,6 +2869,11 @@ // performance of |IsRenderedLegend| which is performance sensitive. ADD_BOOLEAN_BITFIELD(is_html_legend_element_, IsHTMLLegendElement); + // Caches StyleRef().HasBorderDecoration() && + // !Table()->ShouldCollapseBorders(). + ADD_BOOLEAN_BITFIELD(has_non_collapsed_border_decoration_, + HasNonCollapsedBorderDecoration); + private: // This is the cached 'position' value of this object // (see ComputedStyle::position).
diff --git a/third_party/blink/renderer/core/layout/layout_table.cc b/third_party/blink/renderer/core/layout/layout_table.cc index 76c9fd2..eb508a1 100644 --- a/third_party/blink/renderer/core/layout/layout_table.cc +++ b/third_party/blink/renderer/core/layout/layout_table.cc
@@ -85,6 +85,9 @@ const ComputedStyle* old_style) { LayoutBlock::StyleDidChange(diff, old_style); + if (ShouldCollapseBorders()) + SetHasNonCollapsedBorderDecoration(false); + bool old_fixed_table_layout = old_style ? old_style->IsFixedTableLayout() : false; @@ -924,6 +927,8 @@ cell = cell->NextCell()) { DCHECK_EQ(cell->Table(), this); cell->InvalidateCollapsedBorderValues(); + cell->SetHasNonCollapsedBorderDecoration( + !ShouldCollapseBorders() && cell->StyleRef().HasBorderDecoration()); } } }
diff --git a/third_party/blink/renderer/core/layout/layout_table_cell.cc b/third_party/blink/renderer/core/layout/layout_table_cell.cc index 4bf0743..dcc12f7 100644 --- a/third_party/blink/renderer/core/layout/layout_table_cell.cc +++ b/third_party/blink/renderer/core/layout/layout_table_cell.cc
@@ -440,6 +440,9 @@ LayoutBlockFlow::StyleDidChange(diff, old_style); SetHasBoxDecorationBackground(true); + if (Row() && Section() && Table() && Table()->ShouldCollapseBorders()) + SetHasNonCollapsedBorderDecoration(false); + if (!old_style) return;
diff --git a/third_party/blink/renderer/core/layout/layout_table_cell_test.cc b/third_party/blink/renderer/core/layout/layout_table_cell_test.cc index b5a1258..9d0691c 100644 --- a/third_party/blink/renderer/core/layout/layout_table_cell_test.cc +++ b/third_party/blink/renderer/core/layout/layout_table_cell_test.cc
@@ -328,4 +328,33 @@ EXPECT_EQ(1u, cell2->CollapsedOuterBorderAfter()); } +TEST_F(LayoutTableCellTest, HasNonCollapsedBorderDecoration) { + SetBodyInnerHTML(R"HTML( + <table> + <tr><td id="cell"></td></tr> + </table> + )HTML"); + auto* cell = GetCellByElementId("cell"); + EXPECT_FALSE(cell->HasNonCollapsedBorderDecoration()); + + ToElement(cell->GetNode()) + ->setAttribute(html_names::kStyleAttr, "border: 1px solid black"); + GetDocument().View()->UpdateAllLifecyclePhasesExceptPaint(); + EXPECT_TRUE(cell->HasNonCollapsedBorderDecoration()); + + ToElement(cell->Table()->GetNode()) + ->setAttribute(html_names::kStyleAttr, "border-collapse: collapse"); + GetDocument().View()->UpdateAllLifecyclePhasesExceptPaint(); + EXPECT_FALSE(cell->HasNonCollapsedBorderDecoration()); + + ToElement(cell->GetNode()) + ->setAttribute(html_names::kStyleAttr, "border: 2px solid black"); + GetDocument().View()->UpdateAllLifecyclePhasesExceptPaint(); + EXPECT_FALSE(cell->HasNonCollapsedBorderDecoration()); + + ToElement(cell->Table()->GetNode())->setAttribute(html_names::kStyleAttr, ""); + GetDocument().View()->UpdateAllLifecyclePhasesExceptPaint(); + EXPECT_TRUE(cell->HasNonCollapsedBorderDecoration()); +} + } // namespace blink
diff --git a/third_party/blink/renderer/core/layout/layout_table_test.cc b/third_party/blink/renderer/core/layout/layout_table_test.cc index 2e6b9d1..f7fbb56 100644 --- a/third_party/blink/renderer/core/layout/layout_table_test.cc +++ b/third_party/blink/renderer/core/layout/layout_table_test.cc
@@ -337,6 +337,23 @@ EXPECT_EQ(LayoutRect(0, 0, 50, 50), table->SelfVisualOverflowRect()); } +TEST_F(LayoutTableTest, HasNonCollapsedBorderDecoration) { + SetBodyInnerHTML("<table id='table'></table>"); + auto* table = GetTableByElementId("table"); + EXPECT_FALSE(table->HasNonCollapsedBorderDecoration()); + + ToElement(table->GetNode()) + ->setAttribute(html_names::kStyleAttr, "border: 1px solid black"); + GetDocument().View()->UpdateAllLifecyclePhasesExceptPaint(); + EXPECT_TRUE(table->HasNonCollapsedBorderDecoration()); + + ToElement(table->GetNode()) + ->setAttribute(html_names::kStyleAttr, + "border: 1px solid black; border-collapse: collapse"); + GetDocument().View()->UpdateAllLifecyclePhasesExceptPaint(); + EXPECT_FALSE(table->HasNonCollapsedBorderDecoration()); +} + } // anonymous namespace } // namespace blink
diff --git a/third_party/blink/renderer/core/layout/ng/ng_block_node.cc b/third_party/blink/renderer/core/layout/ng/ng_block_node.cc index 24f9c29f..cea09049 100644 --- a/third_party/blink/renderer/core/layout/ng/ng_block_node.cc +++ b/third_party/blink/renderer/core/layout/ng/ng_block_node.cc
@@ -45,10 +45,17 @@ namespace { +inline LayoutMultiColumnFlowThread* GetFlowThread( + const LayoutBlockFlow* block_flow) { + if (!block_flow) + return nullptr; + return block_flow->MultiColumnFlowThread(); +} + inline LayoutMultiColumnFlowThread* GetFlowThread(const LayoutBox& box) { if (!box.IsLayoutBlockFlow()) return nullptr; - return ToLayoutBlockFlow(box).MultiColumnFlowThread(); + return GetFlowThread(&ToLayoutBlockFlow(box)); } // Parameters to pass when creating a layout algorithm for a block node. @@ -554,21 +561,22 @@ // layout object. Logical width will only be set at the first fragment and is // expected to remain the same throughout all subsequent fragments, since // legacy layout doesn't support non-uniform fragmentainer widths. - LayoutUnit logical_height; LayoutUnit intrinsic_content_logical_height; if (LIKELY(IsFirstFragment(constraint_space, physical_fragment))) { - box_->SetLogicalWidth(fragment_logical_size.inline_size); + box_->SetSize(LayoutSize(physical_fragment.Size().width, + physical_fragment.Size().height)); } else { DCHECK_EQ(box_->LogicalWidth(), fragment_logical_size.inline_size) << "Variable fragment inline size not supported"; - logical_height = - PreviouslyUsedBlockSpace(constraint_space, physical_fragment); + box_->SetLogicalHeight( + PreviouslyUsedBlockSpace(constraint_space, physical_fragment) + + fragment_logical_size.block_size); // TODO(layout-ng): We should store this on the break token instead of // relying on previously-stored data. Our relayout in NGBlockNode::Layout // will otherwise lead to wrong data. intrinsic_content_logical_height = box_->IntrinsicContentLogicalHeight(); } - logical_height += fragment_logical_size.block_size; + intrinsic_content_logical_height += layout_result.IntrinsicBlockSize(); NGBoxStrut borders = fragment.Borders(); @@ -578,20 +586,20 @@ if (LIKELY(IsLastFragment(physical_fragment))) intrinsic_content_logical_height -= border_scrollbar_padding.BlockSum(); - box_->SetLogicalHeight(logical_height); box_->SetIntrinsicContentLogicalHeight(intrinsic_content_logical_height); // TODO(mstensho): This should always be done by the parent algorithm, since // we may have auto margins, which only the parent is able to resolve. Remove // the following line when all layout modes do this properly. - if (box_->IsTableCell()) { + if (UNLIKELY(box_->IsTableCell())) { // Table-cell margins compute to zero. box_->SetMargin(NGPhysicalBoxStrut()); } else { box_->SetMargin(ComputePhysicalMargins(constraint_space, Style())); } - LayoutMultiColumnFlowThread* flow_thread = GetFlowThread(*box_); + LayoutBlockFlow* block_flow = ToLayoutBlockFlowOrNull(box_); + LayoutMultiColumnFlowThread* flow_thread = GetFlowThread(block_flow); if (UNLIKELY(flow_thread)) { PlaceChildrenInFlowThread(constraint_space, physical_fragment); } else { @@ -639,7 +647,6 @@ box_->ClearNeedsLayout(); // Overflow computation depends on this being set. - LayoutBlockFlow* block_flow = ToLayoutBlockFlowOrNull(box_); if (LIKELY(block_flow)) block_flow->UpdateIsSelfCollapsing(); }
diff --git a/third_party/blink/renderer/core/layout/ng/ng_container_fragment_builder.cc b/third_party/blink/renderer/core/layout/ng/ng_container_fragment_builder.cc index fa7688b..b5b33ff 100644 --- a/third_party/blink/renderer/core/layout/ng/ng_container_fragment_builder.cc +++ b/third_party/blink/renderer/core/layout/ng/ng_container_fragment_builder.cc
@@ -250,12 +250,6 @@ oof_positioned_candidates_.Shrink(0); } -void NGContainerFragmentBuilder:: - MoveOutOfFlowDescendantCandidatesToDescendants() { - GetAndClearOutOfFlowDescendantCandidates(&oof_positioned_descendants_, - nullptr); -} - #ifndef NDEBUG String NGContainerFragmentBuilder::ToString() const {
diff --git a/third_party/blink/renderer/core/layout/ng/ng_container_fragment_builder.h b/third_party/blink/renderer/core/layout/ng/ng_container_fragment_builder.h index 4fa0ab6..ebff9391 100644 --- a/third_party/blink/renderer/core/layout/ng/ng_container_fragment_builder.h +++ b/third_party/blink/renderer/core/layout/ng/ng_container_fragment_builder.h
@@ -141,7 +141,10 @@ // position OOF candidates yet, (as a containing box may be split over // multiple lines), instead we bubble all the descendants up to the parent // block layout algorithm, to perform the final OOF layout and positioning. - void MoveOutOfFlowDescendantCandidatesToDescendants(); + void MoveOutOfFlowDescendantCandidatesToDescendants() { + GetAndClearOutOfFlowDescendantCandidates(&oof_positioned_descendants_, + nullptr); + } NGContainerFragmentBuilder& SetIsPushedByFloats() { is_pushed_by_floats_ = true;
diff --git a/third_party/blink/renderer/core/layout/traced_layout_object.cc b/third_party/blink/renderer/core/layout/traced_layout_object.cc index 68c51e86..94d313e 100644 --- a/third_party/blink/renderer/core/layout/traced_layout_object.cc +++ b/third_party/blink/renderer/core/layout/traced_layout_object.cc
@@ -111,7 +111,7 @@ std::unique_ptr<TracedValue> TracedLayoutObject::Create(const LayoutView& view, bool trace_geometry) { - std::unique_ptr<TracedValue> traced_value = TracedValue::Create(); + auto traced_value = std::make_unique<TracedValue>(); DumpToTracedValue(view, trace_geometry, traced_value.get()); return traced_value; }
diff --git a/third_party/blink/renderer/core/loader/appcache/application_cache_host.cc b/third_party/blink/renderer/core/loader/appcache/application_cache_host.cc index f712f5e1..f6820bb7 100644 --- a/third_party/blink/renderer/core/loader/appcache/application_cache_host.cc +++ b/third_party/blink/renderer/core/loader/appcache/application_cache_host.cc
@@ -86,7 +86,8 @@ request.SetAppCacheHostID(host_id); } -void ApplicationCacheHost::WillStartLoadingMainResource(const KURL& url, +void ApplicationCacheHost::WillStartLoadingMainResource(DocumentLoader* loader, + const KURL& url, const String& method) { if (!IsApplicationCacheEnabled()) return; @@ -96,7 +97,7 @@ DCHECK(document_loader_->GetFrame()); LocalFrame& frame = *document_loader_->GetFrame(); - host_ = frame.Client()->CreateApplicationCacheHost(this); + host_ = frame.Client()->CreateApplicationCacheHost(loader, this); if (!host_) return;
diff --git a/third_party/blink/renderer/core/loader/appcache/application_cache_host.h b/third_party/blink/renderer/core/loader/appcache/application_cache_host.h index e8c678c..f806dcba 100644 --- a/third_party/blink/renderer/core/loader/appcache/application_cache_host.h +++ b/third_party/blink/renderer/core/loader/appcache/application_cache_host.h
@@ -113,7 +113,9 @@ // willStartLoadingMainResource if it's for frame resource or // willStartLoadingResource for subresource requests. void WillStartLoading(ResourceRequest&); - void WillStartLoadingMainResource(const KURL&, const String&); + void WillStartLoadingMainResource(DocumentLoader*, + const KURL&, + const String& method); void DidReceiveResponseForMainResource(const ResourceResponse&); void MainResourceDataReceived(const char* data, size_t length);
diff --git a/third_party/blink/renderer/core/loader/document_load_timing.cc b/third_party/blink/renderer/core/loader/document_load_timing.cc index 44c0f18..242abeb 100644 --- a/third_party/blink/renderer/core/loader/document_load_timing.cc +++ b/third_party/blink/renderer/core/loader/document_load_timing.cc
@@ -95,7 +95,7 @@ std::unique_ptr<TracedValue> DocumentLoadTiming::GetNavigationStartTracingData() const { - std::unique_ptr<TracedValue> data = TracedValue::Create(); + auto data = std::make_unique<TracedValue>(); data->SetString("documentLoaderURL", document_loader_ ? document_loader_->Url().GetString() : ""); data->SetBoolean("isLoadingMainFrame",
diff --git a/third_party/blink/renderer/core/loader/document_loader.cc b/third_party/blink/renderer/core/loader/document_loader.cc index 6e60b60..e956438 100644 --- a/third_party/blink/renderer/core/loader/document_loader.cc +++ b/third_party/blink/renderer/core/loader/document_loader.cc
@@ -307,7 +307,7 @@ visitor->Trace(use_counter_); } -unsigned long DocumentLoader::MainResourceIdentifier() const { +uint64_t DocumentLoader::MainResourceIdentifier() const { return main_resource_identifier_; } @@ -1101,8 +1101,10 @@ WebScopedVirtualTimePauser::VirtualTaskDuration::kNonInstant); virtual_time_pauser_.PauseVirtualTime(); - if (!archive_) - application_cache_host_->WillStartLoadingMainResource(url_, http_method_); + if (!archive_) { + application_cache_host_->WillStartLoadingMainResource(this, url_, + http_method_); + } // Many parties are interested in resource loading, so we will notify // them through various DispatchXXX methods on FrameFetchContext. @@ -1495,7 +1497,7 @@ if (document->GetSettings() ->GetForceTouchEventFeatureDetectionForInspector()) { OriginTrialContext::FromOrCreate(document)->AddFeature( - "ForceTouchEventFeatureDetectionForInspector"); + OriginTrialFeature::kTouchEventFeatureDetection); } #if defined(OS_CHROMEOS) @@ -1506,7 +1508,7 @@ origin.DomainIs("mhjfbmdgcfjbbpaeojofohoefgiehjai") && origin.port() == 0) { OriginTrialContext::FromOrCreate(document)->AddFeature( - origin_trials::kLowLatencyCanvasTrialName); + OriginTrialFeature::kLowLatencyCanvas); } // Enable Auto Picture-in-Picture feature for the built-in Chrome OS Video // Player app. @@ -1514,7 +1516,7 @@ origin.DomainIs("jcgeabjmjgoblfofpppfkcoakmfobdko") && origin.port() == 0) { OriginTrialContext::FromOrCreate(document)->AddFeature( - origin_trials::kAutoPictureInPictureTrialName); + OriginTrialFeature::kAutoPictureInPicture); } #endif
diff --git a/third_party/blink/renderer/core/loader/document_loader.h b/third_party/blink/renderer/core/loader/document_loader.h index 318aa0b..59549e0 100644 --- a/third_party/blink/renderer/core/loader/document_loader.h +++ b/third_party/blink/renderer/core/loader/document_loader.h
@@ -100,7 +100,7 @@ virtual void DetachFromFrame(bool flush_microtask_queue); - unsigned long MainResourceIdentifier() const; + uint64_t MainResourceIdentifier() const; void ReplaceDocumentWhileExecutingJavaScriptURL(const KURL&, Document* owner_document, @@ -434,7 +434,7 @@ bool loading_mhtml_archive_ = false; bool loading_srcdoc_ = false; bool loading_url_as_empty_document_ = false; - unsigned long main_resource_identifier_ = 0; + uint64_t main_resource_identifier_ = 0; scoped_refptr<ResourceTimingInfo> navigation_timing_info_; bool report_timing_info_to_parent_ = false; WebScopedVirtualTimePauser virtual_time_pauser_;
diff --git a/third_party/blink/renderer/core/loader/empty_clients.cc b/third_party/blink/renderer/core/loader/empty_clients.cc index 22135d5..e702026 100644 --- a/third_party/blink/renderer/core/loader/empty_clients.cc +++ b/third_party/blink/renderer/core/loader/empty_clients.cc
@@ -207,6 +207,7 @@ std::unique_ptr<WebApplicationCacheHost> EmptyLocalFrameClient::CreateApplicationCacheHost( + DocumentLoader*, WebApplicationCacheHostClient*) { return nullptr; }
diff --git a/third_party/blink/renderer/core/loader/empty_clients.h b/third_party/blink/renderer/core/loader/empty_clients.h index 24ae3b95..b8e78f2 100644 --- a/third_party/blink/renderer/core/loader/empty_clients.h +++ b/third_party/blink/renderer/core/loader/empty_clients.h
@@ -380,6 +380,7 @@ return nullptr; } std::unique_ptr<WebApplicationCacheHost> CreateApplicationCacheHost( + DocumentLoader*, WebApplicationCacheHostClient*) override; void SetTextCheckerClientForTesting(WebTextCheckClient*);
diff --git a/third_party/blink/renderer/core/loader/frame_fetch_context.cc b/third_party/blink/renderer/core/loader/frame_fetch_context.cc index cf877fff..75742ed7 100644 --- a/third_party/blink/renderer/core/loader/frame_fetch_context.cc +++ b/third_party/blink/renderer/core/loader/frame_fetch_context.cc
@@ -381,7 +381,7 @@ } void FrameFetchContext::DispatchDidChangeResourcePriority( - unsigned long identifier, + uint64_t identifier, ResourceLoadPriority load_priority, int intra_priority_value) { if (GetResourceFetcherProperties().IsDetached()) @@ -438,7 +438,7 @@ } void FrameFetchContext::DispatchWillSendRequest( - unsigned long identifier, + uint64_t identifier, const ResourceRequest& request, const ResourceResponse& redirect_response, ResourceType resource_type, @@ -463,7 +463,7 @@ } void FrameFetchContext::DispatchDidReceiveResponse( - unsigned long identifier, + uint64_t identifier, const ResourceRequest& request, const ResourceResponse& response, Resource* resource, @@ -532,7 +532,7 @@ identifier, response); } -void FrameFetchContext::DispatchDidReceiveData(unsigned long identifier, +void FrameFetchContext::DispatchDidReceiveData(uint64_t identifier, const char* data, uint64_t data_length) { if (GetResourceFetcherProperties().IsDetached()) @@ -544,7 +544,7 @@ } void FrameFetchContext::DispatchDidReceiveEncodedData( - unsigned long identifier, + uint64_t identifier, size_t encoded_data_length) { if (GetResourceFetcherProperties().IsDetached()) return; @@ -552,7 +552,7 @@ identifier, encoded_data_length); } -void FrameFetchContext::DispatchDidDownloadToBlob(unsigned long identifier, +void FrameFetchContext::DispatchDidDownloadToBlob(uint64_t identifier, BlobDataHandle* blob) { if (GetResourceFetcherProperties().IsDetached() || !blob) return; @@ -561,7 +561,7 @@ } void FrameFetchContext::DispatchDidFinishLoading( - unsigned long identifier, + uint64_t identifier, TimeTicks finish_time, int64_t encoded_data_length, int64_t decoded_body_length, @@ -589,7 +589,7 @@ } void FrameFetchContext::DispatchDidFail(const KURL& url, - unsigned long identifier, + uint64_t identifier, const ResourceError& error, int64_t encoded_data_length, bool is_internal_request) { @@ -792,7 +792,7 @@ http_rtt = GetNetworkStateNotifier().HttpRtt(); } - unsigned long rtt = + uint32_t rtt = GetNetworkStateNotifier().RoundRtt(request.Url().Host(), http_rtt); request.AddHTTPHeaderField( blink::kClientHintsHeaderMapping[static_cast<size_t>(
diff --git a/third_party/blink/renderer/core/loader/frame_fetch_context.h b/third_party/blink/renderer/core/loader/frame_fetch_context.h index 7691be2..5f7a38635 100644 --- a/third_party/blink/renderer/core/loader/frame_fetch_context.h +++ b/third_party/blink/renderer/core/loader/frame_fetch_context.h
@@ -83,7 +83,7 @@ const ResourceRequest&, ResourceType, FetchParameters::DeferOption) const override; - void DispatchDidChangeResourcePriority(unsigned long identifier, + void DispatchDidChangeResourcePriority(uint64_t identifier, ResourceLoadPriority, int intra_priority_value) override; void PrepareRequest(ResourceRequest&, @@ -91,31 +91,30 @@ WebScopedVirtualTimePauser&, ResourceType) override; void DispatchWillSendRequest( - unsigned long identifier, + uint64_t identifier, const ResourceRequest&, const ResourceResponse& redirect_response, ResourceType, const FetchInitiatorInfo& = FetchInitiatorInfo()) override; - void DispatchDidReceiveResponse(unsigned long identifier, + void DispatchDidReceiveResponse(uint64_t identifier, const ResourceRequest&, const ResourceResponse&, Resource*, ResourceResponseType) override; - void DispatchDidReceiveData(unsigned long identifier, + void DispatchDidReceiveData(uint64_t identifier, const char* data, uint64_t data_length) override; - void DispatchDidReceiveEncodedData(unsigned long identifier, + void DispatchDidReceiveEncodedData(uint64_t identifier, size_t encoded_data_length) override; - void DispatchDidDownloadToBlob(unsigned long identifier, - BlobDataHandle*) override; - void DispatchDidFinishLoading(unsigned long identifier, + void DispatchDidDownloadToBlob(uint64_t identifier, BlobDataHandle*) override; + void DispatchDidFinishLoading(uint64_t identifier, TimeTicks finish_time, int64_t encoded_data_length, int64_t decoded_body_length, bool should_report_corb_blocking, ResourceResponseType) override; void DispatchDidFail(const KURL&, - unsigned long identifier, + uint64_t identifier, const ResourceError&, int64_t encoded_data_length, bool is_internal_request) override;
diff --git a/third_party/blink/renderer/core/loader/frame_loader.cc b/third_party/blink/renderer/core/loader/frame_loader.cc index fef422f..3733bcc 100644 --- a/third_party/blink/renderer/core/loader/frame_loader.cc +++ b/third_party/blink/renderer/core/loader/frame_loader.cc
@@ -1768,7 +1768,7 @@ } std::unique_ptr<TracedValue> FrameLoader::ToTracedValue() const { - std::unique_ptr<TracedValue> traced_value = TracedValue::Create(); + auto traced_value = std::make_unique<TracedValue>(); traced_value->BeginDictionary("frame"); traced_value->SetString("id_ref", IdentifiersFactory::FrameId(frame_.Get())); traced_value->EndDictionary();
diff --git a/third_party/blink/renderer/core/loader/progress_tracker.cc b/third_party/blink/renderer/core/loader/progress_tracker.cc index d0c5c839..5b7bd5b 100644 --- a/third_party/blink/renderer/core/loader/progress_tracker.cc +++ b/third_party/blink/renderer/core/loader/progress_tracker.cc
@@ -142,7 +142,7 @@ GetLocalFrameClient()->ProgressEstimateChanged(progress_value_); } -void ProgressTracker::WillStartLoading(unsigned long identifier, +void ProgressTracker::WillStartLoading(uint64_t identifier, ResourceLoadPriority priority) { if (!frame_->IsLoading()) return; @@ -152,7 +152,7 @@ kProgressItemDefaultEstimatedLength)); } -void ProgressTracker::IncrementProgress(unsigned long identifier, +void ProgressTracker::IncrementProgress(uint64_t identifier, const ResourceResponse& response) { ProgressItem* item = progress_items_.at(identifier); if (!item) @@ -165,8 +165,7 @@ item->estimated_length = estimated_length; } -void ProgressTracker::IncrementProgress(unsigned long identifier, - uint64_t length) { +void ProgressTracker::IncrementProgress(uint64_t identifier, uint64_t length) { ProgressItem* item = progress_items_.at(identifier); if (!item) return; @@ -234,7 +233,7 @@ } } -void ProgressTracker::CompleteProgress(unsigned long identifier) { +void ProgressTracker::CompleteProgress(uint64_t identifier) { ProgressItem* item = progress_items_.at(identifier); if (!item) return;
diff --git a/third_party/blink/renderer/core/loader/progress_tracker.h b/third_party/blink/renderer/core/loader/progress_tracker.h index 55a339c..4675fcd 100644 --- a/third_party/blink/renderer/core/loader/progress_tracker.h +++ b/third_party/blink/renderer/core/loader/progress_tracker.h
@@ -65,10 +65,10 @@ void FinishedParsing(); void DidFirstContentfulPaint(); - void WillStartLoading(unsigned long identifier, ResourceLoadPriority); - void IncrementProgress(unsigned long identifier, const ResourceResponse&); - void IncrementProgress(unsigned long identifier, uint64_t); - void CompleteProgress(unsigned long identifier); + void WillStartLoading(uint64_t identifier, ResourceLoadPriority); + void IncrementProgress(uint64_t identifier, const ResourceResponse&); + void IncrementProgress(uint64_t identifier, uint64_t); + void CompleteProgress(uint64_t identifier); private: LocalFrameClient* GetLocalFrameClient() const; @@ -86,7 +86,7 @@ bool did_first_contentful_paint_; double progress_value_; - HashMap<unsigned long, std::unique_ptr<ProgressItem>> progress_items_; + HashMap<uint64_t, std::unique_ptr<ProgressItem>> progress_items_; DISALLOW_COPY_AND_ASSIGN(ProgressTracker); };
diff --git a/third_party/blink/renderer/core/loader/threadable_loader.cc b/third_party/blink/renderer/core/loader/threadable_loader.cc index 9eeb33e7..8a573da6 100644 --- a/third_party/blink/renderer/core/loader/threadable_loader.cc +++ b/third_party/blink/renderer/core/loader/threadable_loader.cc
@@ -113,7 +113,7 @@ : self_keep_alive_(this), loader_(loader) {} ~DetachedClient() override {} - void DidFinishLoading(unsigned long identifier) override { + void DidFinishLoading(uint64_t identifier) override { self_keep_alive_.Clear(); } void DidFail(const ResourceError&) override { self_keep_alive_.Clear(); } @@ -808,7 +808,7 @@ } void ThreadableLoader::ReportResponseReceived( - unsigned long identifier, + uint64_t identifier, const ResourceResponse& response) { LocalFrame* frame = GetDocument() ? GetDocument()->GetFrame() : nullptr; if (!frame)
diff --git a/third_party/blink/renderer/core/loader/threadable_loader.h b/third_party/blink/renderer/core/loader/threadable_loader.h index d52f555..64154b4 100644 --- a/third_party/blink/renderer/core/loader/threadable_loader.h +++ b/third_party/blink/renderer/core/loader/threadable_loader.h
@@ -167,8 +167,7 @@ // Notify Inspector and log to console about resource response. Use this // method if response is not going to be finished normally. - void ReportResponseReceived(unsigned long identifier, - const ResourceResponse&); + void ReportResponseReceived(uint64_t identifier, const ResourceResponse&); void DidTimeout(TimerBase*); // Calls the appropriate loading method according to policy and data about
diff --git a/third_party/blink/renderer/core/loader/threadable_loader_client.h b/third_party/blink/renderer/core/loader/threadable_loader_client.h index 9bbaaeb..f76aea4 100644 --- a/third_party/blink/renderer/core/loader/threadable_loader_client.h +++ b/third_party/blink/renderer/core/loader/threadable_loader_client.h
@@ -56,12 +56,12 @@ const ResourceResponse&) { return true; } - virtual void DidReceiveResponse(unsigned long /*identifier*/, + virtual void DidReceiveResponse(uint64_t /*identifier*/, const ResourceResponse&) {} virtual void DidStartLoadingResponseBody(BytesConsumer&) {} virtual void DidReceiveData(const char*, unsigned /*dataLength*/) {} virtual void DidReceiveCachedMetadata(const char*, int /*dataLength*/) {} - virtual void DidFinishLoading(unsigned long /*identifier*/) {} + virtual void DidFinishLoading(uint64_t /*identifier*/) {} virtual void DidFail(const ResourceError&) {} virtual void DidFailRedirectCheck() {} virtual void DidReceiveResourceTiming(const ResourceTimingInfo&) {}
diff --git a/third_party/blink/renderer/core/loader/threadable_loader_test.cc b/third_party/blink/renderer/core/loader/threadable_loader_test.cc index d44c210..16c40a6f 100644 --- a/third_party/blink/renderer/core/loader/threadable_loader_test.cc +++ b/third_party/blink/renderer/core/loader/threadable_loader_test.cc
@@ -60,11 +60,10 @@ public: MockThreadableLoaderClient() = default; MOCK_METHOD2(DidSendData, void(uint64_t, uint64_t)); - MOCK_METHOD2(DidReceiveResponse, - void(unsigned long, const ResourceResponse&)); + MOCK_METHOD2(DidReceiveResponse, void(uint64_t, const ResourceResponse&)); MOCK_METHOD2(DidReceiveData, void(const char*, unsigned)); MOCK_METHOD2(DidReceiveCachedMetadata, void(const char*, int)); - MOCK_METHOD1(DidFinishLoading, void(unsigned long)); + MOCK_METHOD1(DidFinishLoading, void(uint64_t)); MOCK_METHOD1(DidFail, void(const ResourceError&)); MOCK_METHOD0(DidFailRedirectCheck, void()); MOCK_METHOD1(DidReceiveResourceTiming, void(const ResourceTimingInfo&));
diff --git a/third_party/blink/renderer/core/loader/worker_fetch_context.cc b/third_party/blink/renderer/core/loader/worker_fetch_context.cc index ce66580..b52bf70 100644 --- a/third_party/blink/renderer/core/loader/worker_fetch_context.cc +++ b/third_party/blink/renderer/core/loader/worker_fetch_context.cc
@@ -217,7 +217,7 @@ } void WorkerFetchContext::DispatchWillSendRequest( - unsigned long identifier, + uint64_t identifier, const ResourceRequest& request, const ResourceResponse& redirect_response, ResourceType resource_type, @@ -227,7 +227,7 @@ } void WorkerFetchContext::DispatchDidReceiveResponse( - unsigned long identifier, + uint64_t identifier, const ResourceRequest& request, const ResourceResponse& response, Resource* resource, @@ -247,21 +247,21 @@ resource); } -void WorkerFetchContext::DispatchDidReceiveData(unsigned long identifier, +void WorkerFetchContext::DispatchDidReceiveData(uint64_t identifier, const char* data, uint64_t data_length) { probe::DidReceiveData(Probe(), identifier, nullptr, data, data_length); } void WorkerFetchContext::DispatchDidReceiveEncodedData( - unsigned long identifier, + uint64_t identifier, size_t encoded_data_length) { probe::DidReceiveEncodedDataLength(Probe(), nullptr, identifier, encoded_data_length); } void WorkerFetchContext::DispatchDidFinishLoading( - unsigned long identifier, + uint64_t identifier, TimeTicks finish_time, int64_t encoded_data_length, int64_t decoded_body_length, @@ -273,7 +273,7 @@ } void WorkerFetchContext::DispatchDidFail(const KURL& url, - unsigned long identifier, + uint64_t identifier, const ResourceError& error, int64_t encoded_data_length, bool is_internal_request) {
diff --git a/third_party/blink/renderer/core/loader/worker_fetch_context.h b/third_party/blink/renderer/core/loader/worker_fetch_context.h index 0e340ab..da3b64ce7 100644 --- a/third_party/blink/renderer/core/loader/worker_fetch_context.h +++ b/third_party/blink/renderer/core/loader/worker_fetch_context.h
@@ -77,29 +77,29 @@ WebScopedVirtualTimePauser&, ResourceType) override; void AddAdditionalRequestHeaders(ResourceRequest&) override; - void DispatchWillSendRequest(unsigned long, + void DispatchWillSendRequest(uint64_t, const ResourceRequest&, const ResourceResponse&, ResourceType, const FetchInitiatorInfo&) override; - void DispatchDidReceiveResponse(unsigned long identifier, + void DispatchDidReceiveResponse(uint64_t identifier, const ResourceRequest&, const ResourceResponse&, Resource*, ResourceResponseType) override; - void DispatchDidReceiveData(unsigned long identifier, + void DispatchDidReceiveData(uint64_t identifier, const char* data, uint64_t data_length) override; - void DispatchDidReceiveEncodedData(unsigned long identifier, + void DispatchDidReceiveEncodedData(uint64_t identifier, size_t encoded_data_length) override; - void DispatchDidFinishLoading(unsigned long identifier, + void DispatchDidFinishLoading(uint64_t identifier, TimeTicks finish_time, int64_t encoded_data_length, int64_t decoded_body_length, bool should_report_corb_blocking, ResourceResponseType) override; void DispatchDidFail(const KURL&, - unsigned long identifier, + uint64_t identifier, const ResourceError&, int64_t encoded_data_length, bool isInternalRequest) override;
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 c3cabb61..2639d6d 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
@@ -192,7 +192,7 @@ } void OriginTrialContext::InitializePendingFeatures() { - if (!enabled_trials_.size()) + if (!enabled_features_.size()) return; auto* document = DynamicTo<Document>(GetSupplementable()); if (!document) @@ -206,24 +206,24 @@ if (!script_state->ContextIsValid()) return; ScriptState::Scope scope(script_state); - for (auto enabled_trial : enabled_trials_) { - if (installed_trials_.Contains(enabled_trial)) + for (OriginTrialFeature enabled_feature : enabled_features_) { + if (installed_features_.Contains(enabled_feature)) continue; - InstallPendingOriginTrialFeature(enabled_trial, script_state); - installed_trials_.insert(enabled_trial); + InstallPendingOriginTrialFeature(enabled_feature, script_state); + installed_features_.insert(enabled_feature); } } -void OriginTrialContext::AddFeature(const String& feature) { - enabled_trials_.insert(feature); +void OriginTrialContext::AddFeature(OriginTrialFeature feature) { + enabled_features_.insert(feature); InitializePendingFeatures(); } -bool OriginTrialContext::IsTrialEnabled(const String& trial_name) const { +bool OriginTrialContext::IsFeatureEnabled(OriginTrialFeature feature) const { if (!RuntimeEnabledFeatures::OriginTrialsEnabled()) return false; - return enabled_trials_.Contains(trial_name); + return enabled_features_.Contains(feature); } bool OriginTrialContext::EnableTrialFromToken(const String& token) { @@ -270,14 +270,18 @@ if (token_result == OriginTrialTokenStatus::kSuccess) { String trial_name = String::FromUTF8(trial_name_str.data(), trial_name_str.size()); - 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); + if (origin_trials::IsTrialValid(trial_name)) { + for (OriginTrialFeature feature : + origin_trials::FeaturesForTrial(trial_name)) { + if (origin_trials::FeatureEnabledForOS(feature)) { + valid = true; + enabled_features_.insert(feature); + // Also enable any features implied by this feature. + for (OriginTrialFeature implied_feature : + origin_trials::GetImpliedFeatures(feature)) { + enabled_features_.insert(implied_feature); + } + } } } }
diff --git a/third_party/blink/renderer/core/origin_trials/origin_trial_context.h b/third_party/blink/renderer/core/origin_trials/origin_trial_context.h index 0a2ba6e..852e877c 100644 --- a/third_party/blink/renderer/core/origin_trials/origin_trial_context.h +++ b/third_party/blink/renderer/core/origin_trials/origin_trial_context.h
@@ -8,6 +8,7 @@ #include "third_party/blink/public/common/origin_trials/trial_token_validator.h" #include "third_party/blink/renderer/core/core_export.h" #include "third_party/blink/renderer/core/execution_context/execution_context.h" +#include "third_party/blink/renderer/core/origin_trials/origin_trials.h" #include "third_party/blink/renderer/platform/supplementable.h" #include "third_party/blink/renderer/platform/wtf/hash_set.h" #include "third_party/blink/renderer/platform/wtf/text/string_hash.h" @@ -70,11 +71,11 @@ // Forces a given origin-trial-enabled feature to be enabled in this context // and immediately adds required bindings to already initialized JS contexts. - void AddFeature(const String& feature); + void AddFeature(OriginTrialFeature feature); - // Returns true if the trial (and therefore the feature or features it - // controls) should be considered enabled for the current execution context. - bool IsTrialEnabled(const String& trial_name) const; + // Returns true if the feature should be considered enabled for the current + // execution context. + bool IsFeatureEnabled(OriginTrialFeature feature) const; // Installs JavaScript bindings on the relevant objects for any features which // should be enabled by the current set of trial tokens. This method is called @@ -96,8 +97,8 @@ bool EnableTrialFromToken(const String& token); Vector<String> tokens_; - HashSet<String> enabled_trials_; - HashSet<String> installed_trials_; + HashSet<OriginTrialFeature> enabled_features_; + HashSet<OriginTrialFeature> installed_features_; std::unique_ptr<TrialTokenValidator> trial_token_validator_; };
diff --git a/third_party/blink/renderer/core/origin_trials/origin_trial_context_test.cc b/third_party/blink/renderer/core/origin_trials/origin_trial_context_test.cc index 6928a57..36e5d774 100644 --- a/third_party/blink/renderer/core/origin_trials/origin_trial_context_test.cc +++ b/third_party/blink/renderer/core/origin_trials/origin_trial_context_test.cc
@@ -26,7 +26,6 @@ namespace blink { namespace { -const char kNonExistingTrialName[] = "This trial does not exist"; const char kFrobulateTrialName[] = "Frobulate"; const char kFrobulateEnabledOrigin[] = "https://www.example.com"; const char kFrobulateEnabledOriginUnsecure[] = "http://www.example.com"; @@ -93,11 +92,11 @@ execution_context_->SetIsSecureContext(SecurityOrigin::IsSecure(page_url)); } - bool IsTrialEnabled(const String& origin, const String& feature_name) { + bool IsFeatureEnabled(const String& origin, OriginTrialFeature feature) { UpdateSecurityOrigin(origin); // Need at least one token to ensure the token validator is called. origin_trial_context_->AddToken(kTokenPlaceholder); - return origin_trial_context_->IsTrialEnabled(feature_name); + return origin_trial_context_->IsFeatureEnabled(feature); } void ExpectStatusUniqueMetric(OriginTrialTokenStatus status, int count) { @@ -119,9 +118,9 @@ TEST_F(OriginTrialContextTest, EnabledNonExistingTrial) { TokenValidator()->SetResponse(OriginTrialTokenStatus::kSuccess, kFrobulateTrialName); - bool is_non_existing_trial_enabled = - IsTrialEnabled(kFrobulateEnabledOrigin, kNonExistingTrialName); - EXPECT_FALSE(is_non_existing_trial_enabled); + bool is_non_existing_feature_enabled = IsFeatureEnabled( + kFrobulateEnabledOrigin, OriginTrialFeature::kNonExisting); + EXPECT_FALSE(is_non_existing_feature_enabled); // Status metric should be updated. ExpectStatusUniqueMetric(OriginTrialTokenStatus::kSuccess, 1); @@ -131,8 +130,8 @@ TEST_F(OriginTrialContextTest, EnabledSecureRegisteredOrigin) { TokenValidator()->SetResponse(OriginTrialTokenStatus::kSuccess, kFrobulateTrialName); - bool is_origin_enabled = - IsTrialEnabled(kFrobulateEnabledOrigin, kFrobulateTrialName); + bool is_origin_enabled = IsFeatureEnabled( + kFrobulateEnabledOrigin, OriginTrialFeature::kOriginTrialsSampleAPI); EXPECT_TRUE(is_origin_enabled); EXPECT_EQ(1, TokenValidator()->CallCount()); @@ -145,8 +144,8 @@ TEST_F(OriginTrialContextTest, InvalidTokenResponseFromPlatform) { TokenValidator()->SetResponse(OriginTrialTokenStatus::kMalformed, kFrobulateTrialName); - bool is_origin_enabled = - IsTrialEnabled(kFrobulateEnabledOrigin, kFrobulateTrialName); + bool is_origin_enabled = IsFeatureEnabled( + kFrobulateEnabledOrigin, OriginTrialFeature::kOriginTrialsSampleAPI); EXPECT_FALSE(is_origin_enabled); EXPECT_EQ(1, TokenValidator()->CallCount()); @@ -160,7 +159,8 @@ TokenValidator()->SetResponse(OriginTrialTokenStatus::kSuccess, kFrobulateTrialName); bool is_origin_enabled = - IsTrialEnabled(kFrobulateEnabledOriginUnsecure, kFrobulateTrialName); + IsFeatureEnabled(kFrobulateEnabledOriginUnsecure, + OriginTrialFeature::kOriginTrialsSampleAPI); EXPECT_FALSE(is_origin_enabled); EXPECT_EQ(0, TokenValidator()->CallCount()); ExpectStatusUniqueMetric(OriginTrialTokenStatus::kInsecure, 1); @@ -231,9 +231,9 @@ OriginTrialContext* context = OriginTrialContext::FromOrCreate(document); // Enable the sample origin trial API ("Frobulate"). - context->AddFeature(origin_trials::kOriginTrialsSampleAPITrialName); + context->AddFeature(OriginTrialFeature::kOriginTrialsSampleAPI); EXPECT_TRUE( - context->IsTrialEnabled(origin_trials::kOriginTrialsSampleAPITrialName)); + context->IsFeatureEnabled(OriginTrialFeature::kOriginTrialsSampleAPI)); // Make a mock feature name map with "frobulate". FeatureNameMap feature_map;
diff --git a/third_party/blink/renderer/core/paint/box_decoration_data.cc b/third_party/blink/renderer/core/paint/box_decoration_data.cc index 54c6339..32422d7 100644 --- a/third_party/blink/renderer/core/paint/box_decoration_data.cc +++ b/third_party/blink/renderer/core/paint/box_decoration_data.cc
@@ -4,54 +4,13 @@ #include "third_party/blink/renderer/core/paint/box_decoration_data.h" -#include "third_party/blink/renderer/core/layout/layout_box.h" -#include "third_party/blink/renderer/core/layout/ng/ng_physical_box_fragment.h" -#include "third_party/blink/renderer/core/paint/box_painter.h" #include "third_party/blink/renderer/core/style/border_edge.h" -#include "third_party/blink/renderer/core/style/computed_style.h" -#include "third_party/blink/renderer/platform/graphics/graphics_context.h" namespace blink { -BoxDecorationData::BoxDecorationData(const LayoutBox& layout_box) - : BoxDecorationData(layout_box.StyleRef()) { - bleed_avoidance = ComputeBleedAvoidance(&layout_box); -} - -BoxDecorationData::BoxDecorationData(const NGPhysicalBoxFragment& fragment) - : BoxDecorationData(fragment.Style()) { - bleed_avoidance = ComputeBleedAvoidance(fragment.GetLayoutObject()); -} - -BoxDecorationData::BoxDecorationData(const ComputedStyle& style) { - background_color = - style.VisitedDependentColor(GetCSSPropertyBackgroundColor()); - has_background = background_color.Alpha() || style.HasBackgroundImage(); - DCHECK(has_background == style.HasBackground()); - has_border_decoration = style.HasBorderDecoration(); - has_appearance = style.HasAppearance(); -} - -BackgroundBleedAvoidance BoxDecorationData::ComputeBleedAvoidance( - const LayoutObject* layout_object) { - DCHECK(layout_object); - if (layout_object->IsDocumentElement()) - return kBackgroundBleedNone; - - bool background_should_always_be_clipped = - layout_object->IsBox() - ? ToLayoutBox(layout_object)->BackgroundShouldAlwaysBeClipped() - : false; - return DetermineBackgroundBleedAvoidance(layout_object->GetDocument(), - layout_object->StyleRef(), - background_should_always_be_clipped); -} - -namespace { - -bool BorderObscuresBackgroundEdge(const ComputedStyle& style) { +bool BoxDecorationData::BorderObscuresBackgroundEdge() const { BorderEdge edges[4]; - style.GetBorderEdgeInfo(edges); + style_.GetBorderEdgeInfo(edges); for (auto& edge : edges) { if (!edge.ObscuresBackgroundEdge()) @@ -61,37 +20,35 @@ return true; } -} // anonymous namespace - -BackgroundBleedAvoidance BoxDecorationData::DetermineBackgroundBleedAvoidance( - const Document& document, - const ComputedStyle& style, - bool background_should_always_be_clipped) { - if (!has_background) +BackgroundBleedAvoidance BoxDecorationData::ComputeBleedAvoidance() const { + if (!should_paint_background_ || is_painting_scrolling_background_ || + layout_box_.IsDocumentElement()) return kBackgroundBleedNone; - const bool has_border_radius = style.HasBorderRadius(); - if (!has_border_decoration || !has_border_radius || - style.CanRenderBorderImage()) { - if (background_should_always_be_clipped) + const bool has_border_radius = style_.HasBorderRadius(); + if (!should_paint_border_ || !has_border_radius || + style_.CanRenderBorderImage()) { + if (layout_box_.BackgroundShouldAlwaysBeClipped()) return kBackgroundBleedClipOnly; // Border radius clipping may require layer bleed avoidance if we are going // to draw an image over something else, because we do not want the // antialiasing to lead to bleeding - if (style.HasBackgroundImage() && has_border_radius) { + if (style_.HasBackgroundImage() && has_border_radius) { // But if the top layer is opaque for the purposes of background painting, // we do not need the bleed avoidance because we will not paint anything // behind the top layer. But only if we need to draw something // underneath. - const FillLayer& fill_layer = style.BackgroundLayers(); - if ((background_color.Alpha() || fill_layer.Next()) && - !fill_layer.ImageOccludesNextLayers(document, style)) + const FillLayer& fill_layer = style_.BackgroundLayers(); + if ((BackgroundColor().Alpha() || fill_layer.Next()) && + !fill_layer.ImageOccludesNextLayers(layout_box_.GetDocument(), + style_)) { return kBackgroundBleedClipLayer; + } } return kBackgroundBleedNone; } - if (BorderObscuresBackgroundEdge(style)) + if (BorderObscuresBackgroundEdge()) return kBackgroundBleedShrinkBackground; return kBackgroundBleedClipLayer;
diff --git a/third_party/blink/renderer/core/paint/box_decoration_data.h b/third_party/blink/renderer/core/paint/box_decoration_data.h index e601592..e81df54 100644 --- a/third_party/blink/renderer/core/paint/box_decoration_data.h +++ b/third_party/blink/renderer/core/paint/box_decoration_data.h
@@ -6,38 +6,112 @@ #define THIRD_PARTY_BLINK_RENDERER_CORE_PAINT_BOX_DECORATION_DATA_H_ #include "third_party/blink/renderer/core/layout/background_bleed_avoidance.h" +#include "third_party/blink/renderer/core/layout/layout_box.h" +#include "third_party/blink/renderer/core/layout/ng/ng_physical_box_fragment.h" +#include "third_party/blink/renderer/core/paint/paint_info.h" +#include "third_party/blink/renderer/core/style/computed_style.h" #include "third_party/blink/renderer/platform/graphics/color.h" namespace blink { -class LayoutBox; -class LayoutObject; -class Document; -class NGPhysicalBoxFragment; -class ComputedStyle; - -// Information extracted from ComputedStyle for box painting. -struct BoxDecorationData { +// Data for box decoration painting. +class BoxDecorationData { STACK_ALLOCATED(); public: - BoxDecorationData(const LayoutBox&); - BoxDecorationData(const NGPhysicalBoxFragment&); + BoxDecorationData(const PaintInfo& paint_info, const LayoutBox& layout_box) + : BoxDecorationData(paint_info, layout_box, layout_box.StyleRef()) {} - Color background_color; - BackgroundBleedAvoidance bleed_avoidance; - bool has_background; - bool has_border_decoration; - bool has_appearance; + BoxDecorationData(const PaintInfo& paint_info, + const NGPhysicalBoxFragment& fragment) + : BoxDecorationData(paint_info, + ToLayoutBox(*fragment.GetLayoutObject()), + fragment.Style()) {} + + bool IsPaintingScrollingBackground() const { + return is_painting_scrolling_background_; + } + bool HasAppearance() const { return has_appearance_; } + bool ShouldPaintBackground() const { return should_paint_background_; } + bool ShouldPaintBorder() const { return should_paint_border_; } + bool ShouldPaintShadow() const { return should_paint_shadow_; } + + BackgroundBleedAvoidance GetBackgroundBleedAvoidance() const { + if (!bleed_avoidance_) + bleed_avoidance_ = ComputeBleedAvoidance(); + return *bleed_avoidance_; + } + + bool ShouldPaint() const { + return HasAppearance() || ShouldPaintBackground() || ShouldPaintBorder() || + ShouldPaintShadow(); + } + + // This is not cached because the caller is unlikely to call this repeatedly. + Color BackgroundColor() const { + return style_.VisitedDependentColor(GetCSSPropertyBackgroundColor()); + } + + static bool IsPaintingScrollingBackground(const PaintInfo& paint_info, + const LayoutBox& layout_box) { + if (RuntimeEnabledFeatures::CompositeAfterPaintEnabled()) + return paint_info.IsPaintingScrollingBackground(); + return (paint_info.PaintFlags() & kPaintLayerPaintingOverflowContents) && + !(paint_info.PaintFlags() & + kPaintLayerPaintingCompositingBackgroundPhase) && + layout_box == paint_info.PaintContainer(); + } private: - BackgroundBleedAvoidance DetermineBackgroundBleedAvoidance( - const Document&, - const ComputedStyle&, - bool background_should_always_be_clipped); - BackgroundBleedAvoidance ComputeBleedAvoidance(const LayoutObject*); + BoxDecorationData(const PaintInfo& paint_info, + const LayoutBox& layout_box, + const ComputedStyle& style) + : paint_info_(paint_info), + layout_box_(layout_box), + style_(style), + is_painting_scrolling_background_( + IsPaintingScrollingBackground(paint_info, layout_box)), + has_appearance_(style.HasAppearance()), + should_paint_background_(ComputeShouldPaintBackground()), + should_paint_border_(ComputeShouldPaintBorder()), + should_paint_shadow_(ComputeShouldPaintShadow()) {} - BoxDecorationData(const ComputedStyle&); + bool ComputeShouldPaintBackground() const { + if (!style_.HasBackground()) + return false; + if (layout_box_.BackgroundTransfersToView()) + return false; + if (paint_info_.SkipRootBackground() && + paint_info_.PaintContainer() == &layout_box_) + return false; + return true; + } + + bool ComputeShouldPaintBorder() const { + if (is_painting_scrolling_background_) + return false; + return layout_box_.HasNonCollapsedBorderDecoration(); + } + + bool ComputeShouldPaintShadow() const { + return !is_painting_scrolling_background_ && style_.BoxShadow(); + } + + bool BorderObscuresBackgroundEdge() const; + BackgroundBleedAvoidance ComputeBleedAvoidance() const; + + // Inputs. + const PaintInfo& paint_info_; + const LayoutBox& layout_box_; + const ComputedStyle& style_; + // Outputs that are initialized in the constructor. + const bool is_painting_scrolling_background_; + const bool has_appearance_; + const bool should_paint_background_; + const bool should_paint_border_; + const bool should_paint_shadow_; + // This is lazily initialized. + mutable base::Optional<BackgroundBleedAvoidance> bleed_avoidance_; }; } // namespace blink
diff --git a/third_party/blink/renderer/core/paint/box_model_object_painter.cc b/third_party/blink/renderer/core/paint/box_model_object_painter.cc index b3c8024..7828ac83b 100644 --- a/third_party/blink/renderer/core/paint/box_model_object_painter.cc +++ b/third_party/blink/renderer/core/paint/box_model_object_painter.cc
@@ -8,6 +8,7 @@ #include "third_party/blink/renderer/core/layout/layout_box_model_object.h" #include "third_party/blink/renderer/core/layout/line/root_inline_box.h" #include "third_party/blink/renderer/core/paint/background_image_geometry.h" +#include "third_party/blink/renderer/core/paint/box_decoration_data.h" #include "third_party/blink/renderer/core/paint/object_painter.h" #include "third_party/blink/renderer/core/paint/paint_info.h" #include "third_party/blink/renderer/core/paint/paint_layer.h" @@ -56,20 +57,6 @@ box_model_(box), flow_box_(flow_box) {} -bool BoxModelObjectPainter::IsPaintingScrollingBackground( - const LayoutBoxModelObject* box_model_, - const PaintInfo& paint_info) { - if (RuntimeEnabledFeatures::CompositeAfterPaintEnabled()) { - // TODO(wangxianzhu): For CAP, remove this method and let callers use - // PaintInfo::IsPaintScrollingBackground() directly. - return paint_info.IsPaintingScrollingBackground(); - } - return paint_info.PaintFlags() & kPaintLayerPaintingOverflowContents && - !(paint_info.PaintFlags() & - kPaintLayerPaintingCompositingBackgroundPhase) && - box_model_ == paint_info.PaintContainer(); -} - void BoxModelObjectPainter::PaintTextClipMask(GraphicsContext& context, const IntRect& mask_rect, const LayoutPoint& paint_offset, @@ -100,26 +87,28 @@ const PaintInfo& paint_info, const BoxPainterBase::FillLayerInfo& info, const LayoutRect& rect) { + if (!info.is_clipped_with_local_scrolling) + return rect; + + const auto& this_box = ToLayoutBox(box_model_); + if (BoxDecorationData::IsPaintingScrollingBackground(paint_info, this_box)) + return rect; + LayoutRect scrolled_paint_rect = rect; GraphicsContext& context = paint_info.context; - if (info.is_clipped_with_local_scrolling && - !IsPaintingScrollingBackground(&box_model_, paint_info)) { - // Clip to the overflow area. - const LayoutBox& this_box = ToLayoutBox(box_model_); - // TODO(chrishtr): this should be pixel-snapped. - context.Clip(FloatRect(this_box.OverflowClipRect(rect.Location()))); + // Clip to the overflow area. + // TODO(chrishtr): this should be pixel-snapped. + context.Clip(FloatRect(this_box.OverflowClipRect(rect.Location()))); - // Adjust the paint rect to reflect a scrolled content box with borders at - // the ends. - IntSize offset = this_box.ScrolledContentOffset(); - scrolled_paint_rect.Move(-offset); - LayoutRectOutsets border = AdjustedBorderOutsets(info); - scrolled_paint_rect.SetWidth(border.Left() + this_box.ScrollWidth() + - border.Right()); - scrolled_paint_rect.SetHeight(this_box.BorderTop() + - this_box.ScrollHeight() + - this_box.BorderBottom()); - } + // Adjust the paint rect to reflect a scrolled content box with borders at + // the ends. + IntSize offset = this_box.ScrolledContentOffset(); + scrolled_paint_rect.Move(-offset); + LayoutRectOutsets border = AdjustedBorderOutsets(info); + scrolled_paint_rect.SetWidth(border.Left() + this_box.ScrollWidth() + + border.Right()); + scrolled_paint_rect.SetHeight(this_box.BorderTop() + this_box.ScrollHeight() + + this_box.BorderBottom()); return scrolled_paint_rect; }
diff --git a/third_party/blink/renderer/core/paint/box_model_object_painter.h b/third_party/blink/renderer/core/paint/box_model_object_painter.h index 73775e8..8515ce7 100644 --- a/third_party/blink/renderer/core/paint/box_model_object_painter.h +++ b/third_party/blink/renderer/core/paint/box_model_object_painter.h
@@ -27,9 +27,6 @@ BoxModelObjectPainter(const LayoutBoxModelObject&, const InlineFlowBox* = nullptr); - static bool IsPaintingScrollingBackground(const LayoutBoxModelObject*, - const PaintInfo&); - protected: LayoutRectOutsets ComputeBorders() const override; LayoutRectOutsets ComputePadding() const override;
diff --git a/third_party/blink/renderer/core/paint/box_painter.cc b/third_party/blink/renderer/core/paint/box_painter.cc index 97e7dbc..cb247fe6 100644 --- a/third_party/blink/renderer/core/paint/box_painter.cc +++ b/third_party/blink/renderer/core/paint/box_painter.cc
@@ -8,7 +8,6 @@ #include "third_party/blink/renderer/core/layout/background_bleed_avoidance.h" #include "third_party/blink/renderer/core/layout/layout_box.h" #include "third_party/blink/renderer/core/layout/layout_object.h" -#include "third_party/blink/renderer/core/layout/layout_table.h" #include "third_party/blink/renderer/core/layout/layout_theme.h" #include "third_party/blink/renderer/core/layout/svg/layout_svg_foreign_object.h" #include "third_party/blink/renderer/core/paint/background_image_geometry.h" @@ -57,8 +56,8 @@ LayoutRect paint_rect; const DisplayItemClient* background_client = nullptr; base::Optional<ScopedBoxContentsPaintState> contents_paint_state; - if (BoxModelObjectPainter::IsPaintingScrollingBackground(&layout_box_, - paint_info)) { + if (BoxDecorationData::IsPaintingScrollingBackground(paint_info, + layout_box_)) { // For the case where we are painting the background into the scrolling // contents layer of a composited scroller we need to include the entire // overflow rect. @@ -100,10 +99,10 @@ if (layout_box_.FirstFragment().NextFragment()) return false; - LayoutRect bounds = BoxModelObjectPainter::IsPaintingScrollingBackground( - &layout_box_, paint_info) - ? layout_box_.LayoutOverflowRect() - : layout_box_.SelfVisualOverflowRect(); + LayoutRect bounds = + BoxDecorationData::IsPaintingScrollingBackground(paint_info, layout_box_) + ? layout_box_.LayoutOverflowRect() + : layout_box_.SelfVisualOverflowRect(); return layout_box_.BackgroundIsKnownToBeOpaqueInRect(bounds); } @@ -111,9 +110,6 @@ const PaintInfo& paint_info, const LayoutRect& paint_rect, const DisplayItemClient& background_client) { - bool painting_scrolling_background = - BoxModelObjectPainter::IsPaintingScrollingBackground(&layout_box_, - paint_info); const ComputedStyle& style = layout_box_.StyleRef(); base::Optional<DisplayItemCacheSkipper> cache_skipper; @@ -129,6 +125,10 @@ cache_skipper.emplace(paint_info.context); } + BoxDecorationData box_decoration_data(paint_info, layout_box_); + if (!box_decoration_data.ShouldPaint()) + return; + if (DrawingRecorder::UseCachedDrawingIfPossible( paint_info.context, background_client, DisplayItem::kBoxDecorationBackground)) @@ -136,7 +136,6 @@ DrawingRecorder recorder(paint_info.context, background_client, DisplayItem::kBoxDecorationBackground); - BoxDecorationData box_decoration_data(layout_box_); GraphicsContextStateSaver state_saver(paint_info.context, false); if (RuntimeEnabledFeatures::CompositeAfterPaintEnabled() && @@ -144,27 +143,26 @@ BackgroundIsKnownToBeOpaque(paint_info)) recorder.SetKnownToBeOpaque(); - const auto skip_background = layout_box_.BackgroundTransfersToView() || - (paint_info.SkipRootBackground() && - paint_info.PaintContainer() == &layout_box_); - bool needs_end_layer = false; - if (!painting_scrolling_background) { - // FIXME: Should eventually give the theme control over whether the box - // shadow should paint, since controls could have custom shadows of their - // own. - BoxPainterBase::PaintNormalBoxShadow(paint_info, paint_rect, style, true, - true, skip_background); + // FIXME: Should eventually give the theme control over whether the box + // shadow should paint, since controls could have custom shadows of their + // own. + if (box_decoration_data.ShouldPaintShadow()) { + BoxPainterBase::PaintNormalBoxShadow( + paint_info, paint_rect, style, true, true, + !box_decoration_data.ShouldPaintBackground()); + } - if (BleedAvoidanceIsClipping(box_decoration_data.bleed_avoidance)) { - state_saver.Save(); - FloatRoundedRect border = style.GetRoundedBorderFor(paint_rect); - paint_info.context.ClipRoundedRect(border); + if (BleedAvoidanceIsClipping( + box_decoration_data.GetBackgroundBleedAvoidance())) { + state_saver.Save(); + FloatRoundedRect border = style.GetRoundedBorderFor(paint_rect); + paint_info.context.ClipRoundedRect(border); - if (box_decoration_data.bleed_avoidance == kBackgroundBleedClipLayer) { - paint_info.context.BeginLayer(); - needs_end_layer = true; - } + if (box_decoration_data.GetBackgroundBleedAvoidance() == + kBackgroundBleedClipLayer) { + paint_info.context.BeginLayer(); + needs_end_layer = true; } } @@ -174,36 +172,40 @@ IntRect snapped_paint_rect(PixelSnappedIntRect(paint_rect)); ThemePainter& theme_painter = LayoutTheme::GetTheme().Painter(); bool theme_painted = - box_decoration_data.has_appearance && + box_decoration_data.HasAppearance() && !theme_painter.Paint(layout_box_, paint_info, snapped_paint_rect); - if (!theme_painted && !skip_background) { - PaintBackground(paint_info, paint_rect, - box_decoration_data.background_color, - box_decoration_data.bleed_avoidance); - - if (box_decoration_data.has_appearance) { + if (!theme_painted) { + if (box_decoration_data.ShouldPaintBackground()) { + PaintBackground(paint_info, paint_rect, + box_decoration_data.BackgroundColor(), + box_decoration_data.GetBackgroundBleedAvoidance()); + } + if (box_decoration_data.HasAppearance()) { theme_painter.PaintDecorations(layout_box_.GetNode(), layout_box_.GetDocument(), style, paint_info, snapped_paint_rect); } } - if (!painting_scrolling_background) { + if (box_decoration_data.ShouldPaintShadow()) { BoxPainterBase::PaintInsetBoxShadowWithBorderRect(paint_info, paint_rect, style); + } - // The theme will tell us whether or not we should also paint the CSS - // border. - if (box_decoration_data.has_border_decoration && - (!box_decoration_data.has_appearance || - (!theme_painted && - LayoutTheme::GetTheme().Painter().PaintBorderOnly( - layout_box_.GetNode(), style, paint_info, snapped_paint_rect))) && - !(layout_box_.IsTable() && - ToLayoutTable(&layout_box_)->ShouldCollapseBorders())) { + // The theme will tell us whether or not we should also paint the CSS + // border. + if (box_decoration_data.ShouldPaintBorder()) { + if (!theme_painted) { + theme_painted = + box_decoration_data.HasAppearance() && + !theme_painter.PaintBorderOnly(layout_box_.GetNode(), style, + paint_info, snapped_paint_rect); + } + if (!theme_painted) { BoxPainterBase::PaintBorder( layout_box_, layout_box_.GetDocument(), layout_box_.GeneratingNode(), - paint_info, paint_rect, style, box_decoration_data.bleed_avoidance); + paint_info, paint_rect, style, + box_decoration_data.GetBackgroundBleedAvoidance()); } }
diff --git a/third_party/blink/renderer/core/paint/box_painter_test.cc b/third_party/blink/renderer/core/paint/box_painter_test.cc new file mode 100644 index 0000000..6d0e9a8 --- /dev/null +++ b/third_party/blink/renderer/core/paint/box_painter_test.cc
@@ -0,0 +1,36 @@ +// 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 "third_party/blink/renderer/core/paint/box_painter.h" + +#include "testing/gmock/include/gmock/gmock.h" +#include "third_party/blink/renderer/core/paint/paint_controller_paint_test.h" + +using testing::ElementsAre; + +namespace blink { + +using BoxPainterTest = PaintControllerPaintTest; + +INSTANTIATE_PAINT_TEST_SUITE_P(BoxPainterTest); + +TEST_P(BoxPainterTest, DontPaintEmptyDecorationBackground) { + SetBodyInnerHTML(R"HTML( + <div id="div1" style="width: 100px; height: 100px; background: green"> + </div> + <div id="div2" style="width: 100px; height: 100px; outline: 2px solid blue"> + </div> + )HTML"); + + auto* div1 = GetLayoutObjectByElementId("div1"); + auto* div2 = GetLayoutObjectByElementId("div2"); + EXPECT_THAT(RootPaintController().GetDisplayItemList(), + ElementsAre(IsSameId(&ViewScrollingBackgroundClient(), + kDocumentBackgroundType), + IsSameId(div1, kBackgroundType), + IsSameId(div2, DisplayItem::PaintPhaseToDrawingType( + PaintPhase::kSelfOutlineOnly)))); +} + +} // namespace blink
diff --git a/third_party/blink/renderer/core/paint/fieldset_painter.cc b/third_party/blink/renderer/core/paint/fieldset_painter.cc index 439c4b2f..770b76ba 100644 --- a/third_party/blink/renderer/core/paint/fieldset_painter.cc +++ b/third_party/blink/renderer/core/paint/fieldset_painter.cc
@@ -35,11 +35,14 @@ const LayoutPoint& paint_offset) { LayoutRect paint_rect(paint_offset, layout_fieldset_.Size()); LayoutBox* legend = layout_fieldset_.FindInFlowLegend(); - if (!legend) + if (!legend) { return BoxPainter(layout_fieldset_) .PaintBoxDecorationBackground(paint_info, paint_offset); + } - if (!DrawingRecorder::UseCachedDrawingIfPossible( + BoxDecorationData box_decoration_data(paint_info, layout_fieldset_); + if (box_decoration_data.ShouldPaint() && + !DrawingRecorder::UseCachedDrawingIfPossible( paint_info.context, layout_fieldset_, paint_info.phase)) { FieldsetPaintInfo fieldset_paint_info = CreateFieldsetPaintInfo(layout_fieldset_, *legend); @@ -47,19 +50,24 @@ DrawingRecorder recorder(paint_info.context, layout_fieldset_, paint_info.phase); - BoxDecorationData box_decoration_data(layout_fieldset_); - BoxPainterBase::PaintNormalBoxShadow(paint_info, paint_rect, - layout_fieldset_.StyleRef()); - BackgroundImageGeometry geometry(layout_fieldset_); - BoxModelObjectPainter(layout_fieldset_) - .PaintFillLayers(paint_info, box_decoration_data.background_color, - layout_fieldset_.StyleRef().BackgroundLayers(), - paint_rect, geometry); - BoxPainterBase::PaintInsetBoxShadowWithBorderRect( - paint_info, paint_rect, layout_fieldset_.StyleRef()); + if (box_decoration_data.ShouldPaintShadow()) { + BoxPainterBase::PaintNormalBoxShadow(paint_info, paint_rect, + layout_fieldset_.StyleRef()); + } + if (box_decoration_data.ShouldPaintBackground()) { + BackgroundImageGeometry geometry(layout_fieldset_); + BoxModelObjectPainter(layout_fieldset_) + .PaintFillLayers(paint_info, box_decoration_data.BackgroundColor(), + layout_fieldset_.StyleRef().BackgroundLayers(), + paint_rect, geometry); + } + if (box_decoration_data.ShouldPaintShadow()) { + BoxPainterBase::PaintInsetBoxShadowWithBorderRect( + paint_info, paint_rect, layout_fieldset_.StyleRef()); + } - if (box_decoration_data.has_border_decoration) { + if (box_decoration_data.ShouldPaintBorder()) { // Create a clipping region around the legend and paint the border as // normal GraphicsContext& graphics_context = paint_info.context;
diff --git a/third_party/blink/renderer/core/paint/image_paint_timing_detector.cc b/third_party/blink/renderer/core/paint/image_paint_timing_detector.cc index 548039c..fa79116 100644 --- a/third_party/blink/renderer/core/paint/image_paint_timing_detector.cc +++ b/third_party/blink/renderer/core/paint/image_paint_timing_detector.cc
@@ -143,7 +143,7 @@ DCHECK(largest_image_record); DCHECK(!largest_image_record->first_paint_time_after_loaded.is_null()); largest_image_paint_ = largest_image_record; - std::unique_ptr<TracedValue> value = TracedValue::Create(); + auto value = std::make_unique<TracedValue>(); PopulateTraceValue(*value, *largest_image_record, ++largest_image_candidate_index_max_); TRACE_EVENT_INSTANT_WITH_TIMESTAMP1( @@ -157,7 +157,7 @@ DCHECK(last_image_record); DCHECK(!last_image_record->first_paint_time_after_loaded.is_null()); last_image_paint_ = last_image_record; - std::unique_ptr<TracedValue> value = TracedValue::Create(); + auto value = std::make_unique<TracedValue>(); PopulateTraceValue(*value, *last_image_record, ++last_image_candidate_index_max_); TRACE_EVENT_INSTANT_WITH_TIMESTAMP1(
diff --git a/third_party/blink/renderer/core/paint/ng/ng_box_fragment_painter.cc b/third_party/blink/renderer/core/paint/ng/ng_box_fragment_painter.cc index fa617ec95..19d8417 100644 --- a/third_party/blink/renderer/core/paint/ng/ng_box_fragment_painter.cc +++ b/third_party/blink/renderer/core/paint/ng/ng_box_fragment_painter.cc
@@ -11,7 +11,6 @@ #include "third_party/blink/renderer/core/layout/hit_test_location.h" #include "third_party/blink/renderer/core/layout/hit_test_result.h" #include "third_party/blink/renderer/core/layout/layout_inline.h" -#include "third_party/blink/renderer/core/layout/layout_table.h" #include "third_party/blink/renderer/core/layout/layout_table_cell.h" #include "third_party/blink/renderer/core/layout/ng/geometry/ng_border_edges.h" #include "third_party/blink/renderer/core/layout/ng/geometry/ng_box_strut.h" @@ -54,14 +53,6 @@ LayoutUnit(box_strut.bottom), LayoutUnit(box_strut.left)); } -bool ShouldPaintBoxFragmentBorders(const LayoutObject& object) { - if (!object.IsTableCell()) - return true; - // Collapsed borders are painted by the containing table, not by each - // individual table cell. - return !ToLayoutTableCell(object).Table()->ShouldCollapseBorders(); -} - bool FragmentVisibleToHitTestRequest(const NGPaintFragment& fragment, const HitTestRequest& request) { return fragment.Style().Visibility() == EVisibility::kVisible && @@ -515,8 +506,6 @@ const LayoutObject& layout_object = *box_fragment_.GetLayoutObject(); const LayoutBox& layout_box = ToLayoutBox(layout_object); - bool painting_overflow_contents = - IsPaintingScrollingBackground(box_fragment_, paint_info); const ComputedStyle& style = box_fragment_.Style(); base::Optional<DisplayItemCacheSkipper> cache_skipper; @@ -532,8 +521,12 @@ cache_skipper.emplace(paint_info.context); } + BoxDecorationData box_decoration_data(paint_info, PhysicalFragment()); + if (!box_decoration_data.ShouldPaint()) + return; + const DisplayItemClient& display_item_client = - painting_overflow_contents + box_decoration_data.IsPaintingScrollingBackground() ? layout_box.GetScrollableArea() ->GetScrollingBackgroundDisplayItemClient() : box_fragment_; @@ -544,7 +537,6 @@ DrawingRecorder recorder(paint_info.context, display_item_client, DisplayItem::kBoxDecorationBackground); - BoxDecorationData box_decoration_data(PhysicalFragment()); GraphicsContextStateSaver state_saver(paint_info.context, false); if (RuntimeEnabledFeatures::CompositeAfterPaintEnabled() && @@ -553,14 +545,14 @@ recorder.SetKnownToBeOpaque(); const NGBorderEdges& border_edges = BorderEdges(); - bool needs_end_layer = false; - if (!painting_overflow_contents) { - bool skip_background = layout_box.BackgroundTransfersToView() || - (paint_info.SkipRootBackground() && - paint_info.PaintContainer() == layout_box); + if (box_decoration_data.ShouldPaintShadow()) { PaintNormalBoxShadow(paint_info, paint_rect, style, border_edges.line_left, - border_edges.line_right, skip_background); + border_edges.line_right, + !box_decoration_data.ShouldPaintBackground()); + } + bool needs_end_layer = false; + if (!box_decoration_data.IsPaintingScrollingBackground()) { if (box_fragment_.HasSelfPaintingLayer() && layout_box.IsTableCell() && ToLayoutTableCell(layout_box).Table()->ShouldCollapseBorders()) { // We have to clip here because the background would paint on top of the @@ -569,13 +561,15 @@ clip_rect.Expand(ToLayoutTableCell(layout_box).BorderInsets()); state_saver.Save(); paint_info.context.Clip(PixelSnappedIntRect(clip_rect)); - } else if (BleedAvoidanceIsClipping(box_decoration_data.bleed_avoidance)) { + } else if (BleedAvoidanceIsClipping( + box_decoration_data.GetBackgroundBleedAvoidance())) { state_saver.Save(); FloatRoundedRect border = style.GetRoundedBorderFor( paint_rect, border_edges.line_left, border_edges.line_right); paint_info.context.ClipRoundedRect(border); - if (box_decoration_data.bleed_avoidance == kBackgroundBleedClipLayer) { + if (box_decoration_data.GetBackgroundBleedAvoidance() == + kBackgroundBleedClipLayer) { paint_info.context.BeginLayer(); needs_end_layer = true; } @@ -585,42 +579,43 @@ IntRect snapped_paint_rect(PixelSnappedIntRect(paint_rect)); ThemePainter& theme_painter = LayoutTheme::GetTheme().Painter(); bool theme_painted = - box_decoration_data.has_appearance && + box_decoration_data.HasAppearance() && !theme_painter.Paint(layout_box, paint_info, snapped_paint_rect); - bool should_paint_background = - !theme_painted && (!paint_info.SkipRootBackground() || - paint_info.PaintContainer() != layout_box); - if (should_paint_background) { - PaintBackground(paint_info, paint_rect, - box_decoration_data.background_color, - box_decoration_data.bleed_avoidance); - - if (box_decoration_data.has_appearance) { + if (!theme_painted) { + if (box_decoration_data.ShouldPaintBackground()) { + PaintBackground(paint_info, paint_rect, + box_decoration_data.BackgroundColor(), + box_decoration_data.GetBackgroundBleedAvoidance()); + } + if (box_decoration_data.HasAppearance()) { theme_painter.PaintDecorations(layout_box.GetNode(), layout_box.GetDocument(), style, paint_info, snapped_paint_rect); } } - if (!painting_overflow_contents) { + if (box_decoration_data.ShouldPaintShadow()) { PaintInsetBoxShadowWithBorderRect(paint_info, paint_rect, style, border_edges.line_left, border_edges.line_right); + } // The theme will tell us whether or not we should also paint the CSS // border. - if (box_decoration_data.has_border_decoration && - (!box_decoration_data.has_appearance || - (!theme_painted && - LayoutTheme::GetTheme().Painter().PaintBorderOnly( - layout_box.GetNode(), style, paint_info, snapped_paint_rect))) && - ShouldPaintBoxFragmentBorders(layout_object)) { + if (box_decoration_data.ShouldPaintBorder()) { + if (!theme_painted) { + theme_painted = + box_decoration_data.HasAppearance() && + !LayoutTheme::GetTheme().Painter().PaintBorderOnly( + layout_box.GetNode(), style, paint_info, snapped_paint_rect); + } + if (!theme_painted) { Node* generating_node = layout_object.GeneratingNode(); const Document& document = layout_object.GetDocument(); PaintBorder(*box_fragment_.GetLayoutObject(), document, generating_node, paint_info, paint_rect, style, - box_decoration_data.bleed_avoidance, border_edges.line_left, - border_edges.line_right); + box_decoration_data.GetBackgroundBleedAvoidance(), + border_edges.line_left, border_edges.line_right); } }
diff --git a/third_party/blink/renderer/core/paint/ng/ng_fieldset_painter.cc b/third_party/blink/renderer/core/paint/ng/ng_fieldset_painter.cc index 34d98e9..15e24670 100644 --- a/third_party/blink/renderer/core/paint/ng/ng_fieldset_painter.cc +++ b/third_party/blink/renderer/core/paint/ng/ng_fieldset_painter.cc
@@ -45,13 +45,16 @@ const LayoutPoint paint_offset) { LayoutSize fieldset_size(fieldset_.Size().ToLayoutSize()); LayoutRect paint_rect(paint_offset, fieldset_size); + const NGPhysicalBoxFragment& fragment = + ToNGPhysicalBoxFragment(fieldset_.PhysicalFragment()); + BoxDecorationData box_decoration_data(paint_info, fragment); + if (!box_decoration_data.ShouldPaint()) + return; if (DrawingRecorder::UseCachedDrawingIfPossible(paint_info.context, fieldset_, paint_info.phase)) return; - const NGPhysicalBoxFragment& fragment = - ToNGPhysicalBoxFragment(fieldset_.PhysicalFragment()); LayoutRectOutsets fieldset_borders = fragment.Borders().ToLayoutRectOutsets(); const ComputedStyle& style = fieldset_.Style(); LayoutRect legend_border_box; @@ -65,37 +68,39 @@ contracted_rect.Contract(fieldset_paint_info.border_outsets); DrawingRecorder recorder(paint_info.context, fieldset_, paint_info.phase); - BoxDecorationData box_decoration_data(fragment); NGBoxFragmentPainter fragment_painter(fieldset_); - fragment_painter.PaintNormalBoxShadow(paint_info, contracted_rect, style); + if (box_decoration_data.ShouldPaintShadow()) { + fragment_painter.PaintNormalBoxShadow(paint_info, contracted_rect, style); + } + if (box_decoration_data.ShouldPaintBackground()) { + // TODO(eae): Switch to LayoutNG version of BackgroundImageGeometry. + BackgroundImageGeometry geometry( + *static_cast<const LayoutBoxModelObject*>(fieldset_.GetLayoutObject())); + fragment_painter.PaintFillLayers( + paint_info, box_decoration_data.BackgroundColor(), + style.BackgroundLayers(), contracted_rect, geometry); + } + if (box_decoration_data.ShouldPaintShadow()) { + fragment_painter.PaintInsetBoxShadowWithBorderRect( + paint_info, contracted_rect, fieldset_.Style()); + } + if (box_decoration_data.ShouldPaintBorder()) { + // Create a clipping region around the legend and paint the border as + // normal. + GraphicsContext& graphics_context = paint_info.context; + GraphicsContextStateSaver state_saver(graphics_context); - // TODO(eae): Switch to LayoutNG version of BackgroundImageGeometry. - BackgroundImageGeometry geometry( - *static_cast<const LayoutBoxModelObject*>(fieldset_.GetLayoutObject())); + LayoutRect legend_cutout_rect = fieldset_paint_info.legend_cutout_rect; + legend_cutout_rect.MoveBy(paint_rect.Location()); + graphics_context.ClipOut(PixelSnappedIntRect(legend_cutout_rect)); - fragment_painter.PaintFillLayers( - paint_info, box_decoration_data.background_color, - style.BackgroundLayers(), contracted_rect, geometry); - fragment_painter.PaintInsetBoxShadowWithBorderRect( - paint_info, contracted_rect, fieldset_.Style()); - - if (!box_decoration_data.has_border_decoration) - return; - - // Create a clipping region around the legend and paint the border as normal. - GraphicsContext& graphics_context = paint_info.context; - GraphicsContextStateSaver state_saver(graphics_context); - - LayoutRect legend_cutout_rect = fieldset_paint_info.legend_cutout_rect; - legend_cutout_rect.MoveBy(paint_rect.Location()); - graphics_context.ClipOut(PixelSnappedIntRect(legend_cutout_rect)); - - LayoutObject* layout_object = fieldset_.GetLayoutObject(); - Node* node = layout_object->GeneratingNode(); - fragment_painter.PaintBorder(*fieldset_.GetLayoutObject(), - layout_object->GetDocument(), node, paint_info, - contracted_rect, fieldset_.Style()); + LayoutObject* layout_object = fieldset_.GetLayoutObject(); + Node* node = layout_object->GeneratingNode(); + fragment_painter.PaintBorder(*fieldset_.GetLayoutObject(), + layout_object->GetDocument(), node, paint_info, + contracted_rect, fieldset_.Style()); + } } void NGFieldsetPainter::PaintLegend(const NGPaintFragment& legend,
diff --git a/third_party/blink/renderer/core/paint/paint_layer.cc b/third_party/blink/renderer/core/paint/paint_layer.cc index 8c15805..a3667b5 100644 --- a/third_party/blink/renderer/core/paint/paint_layer.cc +++ b/third_party/blink/renderer/core/paint/paint_layer.cc
@@ -435,7 +435,7 @@ bool had_transform = Transform(); if (has_transform != had_transform) { if (has_transform) - EnsureRareData().transform = TransformationMatrix::Create(); + EnsureRareData().transform = std::make_unique<TransformationMatrix>(); else rare_data_->transform.reset();
diff --git a/third_party/blink/renderer/core/paint/table_cell_painter.cc b/third_party/blink/renderer/core/paint/table_cell_painter.cc index 0af0c09d..333b77f 100644 --- a/third_party/blink/renderer/core/paint/table_cell_painter.cc +++ b/third_party/blink/renderer/core/paint/table_cell_painter.cc
@@ -7,6 +7,7 @@ #include "third_party/blink/renderer/core/layout/layout_table_cell.h" #include "third_party/blink/renderer/core/paint/background_image_geometry.h" #include "third_party/blink/renderer/core/paint/block_painter.h" +#include "third_party/blink/renderer/core/paint/box_decoration_data.h" #include "third_party/blink/renderer/core/paint/box_model_object_painter.h" #include "third_party/blink/renderer/core/paint/box_painter.h" #include "third_party/blink/renderer/core/paint/box_painter_base.h" @@ -76,13 +77,12 @@ !layout_table_cell_.FirstChild()) return; - bool is_painting_scrolling_background = - BoxModelObjectPainter::IsPaintingScrollingBackground(&layout_table_cell_, - paint_info); + BoxDecorationData box_decoration_data(paint_info, layout_table_cell_); + const DisplayItemClient* client = nullptr; LayoutRect paint_rect; base::Optional<ScopedBoxContentsPaintState> contents_paint_state; - if (is_painting_scrolling_background) { + if (box_decoration_data.IsPaintingScrollingBackground()) { // See BoxPainter::PaintBoxDecorationBackground() for explanations. // TODO(wangxianzhu): Perhaps we can merge them for CompositeAfterPaint. paint_rect = layout_table_cell_.PhysicalLayoutOverflowRect(); @@ -96,45 +96,36 @@ client = &layout_table_cell_; } - bool has_background = style.HasBackground(); - bool should_paint_box_shadow = - !is_painting_scrolling_background && style.BoxShadow(); - bool should_paint_border = !is_painting_scrolling_background && - style.HasBorderDecoration() && - !table->ShouldCollapseBorders(); + if (box_decoration_data.ShouldPaint() && + !DrawingRecorder::UseCachedDrawingIfPossible( + paint_info.context, *client, DisplayItem::kBoxDecorationBackground)) { + // TODO(chrishtr): the pixel-snapping here is likely incorrect. + DrawingRecorder recorder(paint_info.context, *client, + DisplayItem::kBoxDecorationBackground); - if (has_background || should_paint_box_shadow || should_paint_border) { - if (!DrawingRecorder::UseCachedDrawingIfPossible( - paint_info.context, *client, - DisplayItem::kBoxDecorationBackground)) { - // TODO(chrishtr): the pixel-snapping here is likely incorrect. - DrawingRecorder recorder(paint_info.context, *client, - DisplayItem::kBoxDecorationBackground); + if (box_decoration_data.ShouldPaintShadow()) + BoxPainterBase::PaintNormalBoxShadow(paint_info, paint_rect, style); - if (should_paint_box_shadow) - BoxPainterBase::PaintNormalBoxShadow(paint_info, paint_rect, style); + if (box_decoration_data.ShouldPaintBackground()) + PaintBackground(paint_info, paint_rect, layout_table_cell_); - if (has_background) - PaintBackground(paint_info, paint_rect, layout_table_cell_); + if (box_decoration_data.ShouldPaintShadow()) { + // If the table collapses borders, the inner rect is the border box rect + // inset by inner half widths of collapsed borders (which are returned + // from the overridden BorderXXX() methods). Otherwise the following code + // is equivalent to BoxPainterBase::PaintInsetBoxShadowWithBorderRect(). + auto inner_rect = paint_rect; + inner_rect.ContractEdges( + layout_table_cell_.BorderTop(), layout_table_cell_.BorderRight(), + layout_table_cell_.BorderBottom(), layout_table_cell_.BorderLeft()); + BoxPainterBase::PaintInsetBoxShadowWithInnerRect( + paint_info, inner_rect, layout_table_cell_.StyleRef()); + } - if (should_paint_box_shadow) { - // If the table collapses borders, the inner rect is the border box rect - // inset by inner half widths of collapsed borders (which are returned - // from the overriden BorderXXX() methods). Otherwise the following code - // is equivalent to BoxPainterBase::PaintInsetBoxShadowWithBorderRect(). - auto inner_rect = paint_rect; - inner_rect.ContractEdges( - layout_table_cell_.BorderTop(), layout_table_cell_.BorderRight(), - layout_table_cell_.BorderBottom(), layout_table_cell_.BorderLeft()); - BoxPainterBase::PaintInsetBoxShadowWithInnerRect( - paint_info, inner_rect, layout_table_cell_.StyleRef()); - } - - if (should_paint_border) { - BoxPainterBase::PaintBorder( - layout_table_cell_, layout_table_cell_.GetDocument(), - layout_table_cell_.GeneratingNode(), paint_info, paint_rect, style); - } + if (box_decoration_data.ShouldPaintBorder()) { + BoxPainterBase::PaintBorder( + layout_table_cell_, layout_table_cell_.GetDocument(), + layout_table_cell_.GeneratingNode(), paint_info, paint_rect, style); } }
diff --git a/third_party/blink/renderer/core/paint/table_painter_test.cc b/third_party/blink/renderer/core/paint/table_painter_test.cc index 6e59de3..9d4a750 100644 --- a/third_party/blink/renderer/core/paint/table_painter_test.cc +++ b/third_party/blink/renderer/core/paint/table_painter_test.cc
@@ -191,4 +191,31 @@ PaintPhase::kSelfOutlineOnly)))); } +TEST_P(TablePainterTest, DontPaintEmptyDecorationBackground) { + SetBodyInnerHTML(R"HTML( + <table id="table1" style="border: 1px solid yellow"> + <tr> + <td style="width: 100px; height: 100px; border: 2px solid blue"></td> + </tr> + </tr> + <table id="table2" + style="border-collapse: collapse; border: 1px solid yellow"> + <tr> + <td style="width: 100px; height: 100px; border: 2px solid blue"></td> + </tr> + </tr> + )HTML"); + + auto* table1 = ToLayoutTable(GetLayoutObjectByElementId("table1")); + auto* table2 = ToLayoutTable(GetLayoutObjectByElementId("table2")); + EXPECT_THAT(RootPaintController().GetDisplayItemList(), + ElementsAre(IsSameId(&ViewScrollingBackgroundClient(), + kDocumentBackgroundType), + IsSameId(table1, kBackgroundType), + IsSameId(table1->FirstBody()->FirstRow()->FirstCell(), + kBackgroundType), + IsSameId(table2->FirstBody()->FirstRow(), + DisplayItem::kTableCollapsedBorders))); +} + } // namespace blink
diff --git a/third_party/blink/renderer/core/paint/text_paint_timing_detector.cc b/third_party/blink/renderer/core/paint/text_paint_timing_detector.cc index f035b42..8b5ec37 100644 --- a/third_party/blink/renderer/core/paint/text_paint_timing_detector.cc +++ b/third_party/blink/renderer/core/paint/text_paint_timing_detector.cc
@@ -57,7 +57,7 @@ const TextRecord& largest_text_record) { largest_text_paint_ = largest_text_record.first_paint_time; largest_text_paint_size_ = largest_text_record.first_size; - std::unique_ptr<TracedValue> value = TracedValue::Create(); + auto value = std::make_unique<TracedValue>(); PopulateTraceValue(*value, largest_text_record, largest_text_candidate_index_max_++); TRACE_EVENT_INSTANT_WITH_TIMESTAMP1(
diff --git a/third_party/blink/renderer/core/paint/theme_painter.cc b/third_party/blink/renderer/core/paint/theme_painter.cc index 7d172e7b..9b87e00 100644 --- a/third_party/blink/renderer/core/paint/theme_painter.cc +++ b/third_party/blink/renderer/core/paint/theme_painter.cc
@@ -209,20 +209,10 @@ COUNT_APPEARANCE(doc, SliderThumbVerticalForOthers); return PaintSliderThumb(node, style, paint_info, r); } - case kMediaEnterFullscreenButtonPart: - case kMediaExitFullscreenButtonPart: - case kMediaPlayButtonPart: - case kMediaOverlayPlayButtonPart: - case kMediaMuteButtonPart: - case kMediaToggleClosedCaptionsButtonPart: case kMediaSliderPart: case kMediaSliderThumbPart: - case kMediaVolumeSliderContainerPart: case kMediaVolumeSliderPart: case kMediaVolumeSliderThumbPart: - case kMediaTimeRemainingPart: - case kMediaCurrentTimePart: - case kMediaControlsBackgroundPart: return true; case kMenulistButtonPart: case kTextFieldPart:
diff --git a/third_party/blink/renderer/core/paint/view_painter.cc b/third_party/blink/renderer/core/paint/view_painter.cc index 7df3dac..1fffac96 100644 --- a/third_party/blink/renderer/core/paint/view_painter.cc +++ b/third_party/blink/renderer/core/paint/view_painter.cc
@@ -10,6 +10,7 @@ #include "third_party/blink/renderer/core/layout/layout_view.h" #include "third_party/blink/renderer/core/paint/background_image_geometry.h" #include "third_party/blink/renderer/core/paint/block_painter.h" +#include "third_party/blink/renderer/core/paint/box_decoration_data.h" #include "third_party/blink/renderer/core/paint/box_model_object_painter.h" #include "third_party/blink/renderer/core/paint/box_painter.h" #include "third_party/blink/renderer/core/paint/compositing/composited_layer_mapping.h" @@ -50,8 +51,8 @@ const DisplayItemClient* background_client = &layout_view_; base::Optional<ScopedPaintChunkProperties> scoped_scroll_property; - if (BoxModelObjectPainter::IsPaintingScrollingBackground(&layout_view_, - paint_info)) { + if (BoxDecorationData::IsPaintingScrollingBackground(paint_info, + layout_view_)) { // Layout overflow, combined with the visible content size. auto document_rect = layout_view_.DocumentRect(); // DocumentRect is relative to ScrollOrigin. Add ScrollOrigin to let it be @@ -147,8 +148,8 @@ if (!root_object || !root_object->IsBox()) { background_renderable = false; } else if (root_object->HasLayer()) { - if (BoxModelObjectPainter::IsPaintingScrollingBackground(&layout_view_, - paint_info)) { + if (BoxDecorationData::IsPaintingScrollingBackground(paint_info, + layout_view_)) { transform.Translate(layout_view_.ScrolledContentOffset().Width(), layout_view_.ScrolledContentOffset().Height()); }
diff --git a/third_party/blink/renderer/core/paint/view_painter_test.cc b/third_party/blink/renderer/core/paint/view_painter_test.cc index bdfdb87..e83f95b 100644 --- a/third_party/blink/renderer/core/paint/view_painter_test.cc +++ b/third_party/blink/renderer/core/paint/view_painter_test.cc
@@ -55,18 +55,14 @@ EXPECT_THAT( display_items, ElementsAre(IsSameId(&GetLayoutView(), kDocumentBackgroundType), - IsSameId(&GetLayoutView(), DisplayItem::kScrollHitTest), - IsSameId(GetDocument().body()->GetLayoutObject(), - kBackgroundType))); + IsSameId(&GetLayoutView(), DisplayItem::kScrollHitTest))); background_display_item = &display_items[0]; } else { EXPECT_THAT( display_items, ElementsAre(IsSameId(&GetLayoutView(), DisplayItem::kScrollHitTest), IsSameId(&ViewScrollingBackgroundClient(), - kDocumentBackgroundType), - IsSameId(GetDocument().body()->GetLayoutObject(), - kBackgroundType))); + kDocumentBackgroundType))); background_display_item = &display_items[1]; } } else { @@ -87,9 +83,7 @@ const auto& display_items = RootPaintController().GetDisplayItemList(); EXPECT_THAT(display_items, ElementsAre(IsSameId(&ViewScrollingBackgroundClient(), - kDocumentBackgroundType), - IsSameId(GetDocument().body()->GetLayoutObject(), - kBackgroundType))); + kDocumentBackgroundType))); background_display_item = &display_items[0]; } } @@ -227,7 +221,7 @@ IsPaintChunk( 2, 4, PaintChunk::Id(scrolling_client, kDocumentBackgroundType), scrolling_properties, view_hit_test_data), - IsPaintChunk(4, 7, + IsPaintChunk(4, 6, PaintChunk::Id(*html->Layer(), kNonScrollingBackgroundChunkType), scrolling_properties, html_hit_test_data))); @@ -238,7 +232,7 @@ IsPaintChunk( 0, 2, PaintChunk::Id(scrolling_client, kDocumentBackgroundType), scrolling_properties, view_hit_test_data), - IsPaintChunk(2, 5, + IsPaintChunk(2, 4, PaintChunk::Id(*html->Layer(), kNonScrollingBackgroundChunkType), scrolling_properties, html_hit_test_data))); @@ -289,7 +283,7 @@ IsPaintChunk(2, 3, PaintChunk::Id(*view, DisplayItem::kScrollHitTest), non_scrolling_properties), - IsPaintChunk(3, 6, + IsPaintChunk(3, 5, PaintChunk::Id(*html->Layer(), kNonScrollingBackgroundChunkType), scrolling_properties, scrolling_hit_test_data))); @@ -305,7 +299,7 @@ EXPECT_THAT( RootPaintController().PaintChunks(), ElementsAre(IsPaintChunk( - 0, 3, + 0, 2, PaintChunk::Id(*html->Layer(), kNonScrollingBackgroundChunkType), scrolling_properties, scrolling_hit_test_data))); }
diff --git a/third_party/blink/renderer/core/probe/core_probes.pidl b/third_party/blink/renderer/core/probe/core_probes.pidl index 334ab1d6..a1cd2e6 100644 --- a/third_party/blink/renderer/core/probe/core_probes.pidl +++ b/third_party/blink/renderer/core/probe/core_probes.pidl
@@ -89,25 +89,25 @@ void ApplyAcceptLanguageOverride(ExecutionContext*, String* accept_language); void ApplyUserAgentOverride(CoreProbeSink*, String* user_agent); void DidBlockRequest(CoreProbeSink*, const ResourceRequest&, DocumentLoader*, const KURL& fetch_context_url, const FetchInitiatorInfo&, ResourceRequestBlockedReason, ResourceType); - void DidChangeResourcePriority(LocalFrame*, DocumentLoader*, unsigned long identifier, ResourceLoadPriority load_priority); + void DidChangeResourcePriority(LocalFrame*, DocumentLoader*, uint64_t identifier, ResourceLoadPriority load_priority); void PrepareRequest(CoreProbeSink*, DocumentLoader*, ResourceRequest&, const FetchInitiatorInfo&, ResourceType); - void WillSendRequest(CoreProbeSink*, unsigned long identifier, DocumentLoader*, const KURL& fetch_context_url, const ResourceRequest&, const ResourceResponse& redirect_response, const FetchInitiatorInfo&, ResourceType); - void WillSendNavigationRequest(CoreProbeSink*, unsigned long identifier, DocumentLoader*, const KURL&, const AtomicString& http_method, EncodedFormData*); - void MarkResourceAsCached(LocalFrame*, DocumentLoader*, unsigned long identifier); - void DidReceiveResourceResponse(CoreProbeSink*, unsigned long identifier, DocumentLoader*, const ResourceResponse&, Resource*); - void DidReceiveData(CoreProbeSink*, unsigned long identifier, DocumentLoader*, const char* data, uint64_t data_length); - void DidReceiveBlob(CoreProbeSink*, unsigned long identifier, DocumentLoader*, BlobDataHandle*); - void DidReceiveEncodedDataLength(CoreProbeSink*, DocumentLoader* loader, unsigned long identifier, size_t encoded_data_length); - void DidFinishLoading(CoreProbeSink*, unsigned long identifier, DocumentLoader*, TimeTicks finish_time, int64_t encoded_data_length, int64_t decoded_body_length, bool should_report_corb_blocking); - void DidReceiveCorsRedirectResponse(ExecutionContext*, unsigned long identifier, DocumentLoader*, const ResourceResponse&, Resource*); - void DidFailLoading(CoreProbeSink*, unsigned long identifier, DocumentLoader*, const ResourceError&); + void WillSendRequest(CoreProbeSink*, uint64_t identifier, DocumentLoader*, const KURL& fetch_context_url, const ResourceRequest&, const ResourceResponse& redirect_response, const FetchInitiatorInfo&, ResourceType); + void WillSendNavigationRequest(CoreProbeSink*, uint64_t identifier, DocumentLoader*, const KURL&, const AtomicString& http_method, EncodedFormData*); + void MarkResourceAsCached(LocalFrame*, DocumentLoader*, uint64_t identifier); + void DidReceiveResourceResponse(CoreProbeSink*, uint64_t identifier, DocumentLoader*, const ResourceResponse&, Resource*); + void DidReceiveData(CoreProbeSink*, uint64_t identifier, DocumentLoader*, const char* data, uint64_t data_length); + void DidReceiveBlob(CoreProbeSink*, uint64_t identifier, DocumentLoader*, BlobDataHandle*); + void DidReceiveEncodedDataLength(CoreProbeSink*, DocumentLoader* loader, uint64_t identifier, size_t encoded_data_length); + void DidFinishLoading(CoreProbeSink*, uint64_t identifier, DocumentLoader*, TimeTicks finish_time, int64_t encoded_data_length, int64_t decoded_body_length, bool should_report_corb_blocking); + void DidReceiveCorsRedirectResponse(ExecutionContext*, uint64_t identifier, DocumentLoader*, const ResourceResponse&, Resource*); + void DidFailLoading(CoreProbeSink*, uint64_t identifier, DocumentLoader*, const ResourceError&); void WillSendEventSourceRequest(ExecutionContext*); - void WillDispatchEventSourceEvent(ExecutionContext*, unsigned long identifier, const AtomicString& event_name, const AtomicString& event_id, const String& data); + void WillDispatchEventSourceEvent(ExecutionContext*, uint64_t identifier, const AtomicString& event_name, const AtomicString& event_id, const String& data); void WillLoadXHR([Keep] ExecutionContext*, const AtomicString& method, const KURL& url, bool async, EncodedFormData* form_data, const HTTPHeaderMap& headers, bool include_credentials); void DidFinishXHR(ExecutionContext*, XMLHttpRequest* xhr); - void ScriptImported(ExecutionContext*, unsigned long identifier, const String& source_string); + void ScriptImported(ExecutionContext*, uint64_t identifier, const String& source_string); void ScriptExecutionBlockedByCSP(ExecutionContext*, const String& directive_text); - void DidReceiveScriptResponse(ExecutionContext*, unsigned long identifier); + void DidReceiveScriptResponse(ExecutionContext*, uint64_t identifier); void DomContentLoadedEventFired([Keep] LocalFrame*); void LoadEventFired([Keep] LocalFrame*); void FrameAttachedToParent([Keep] LocalFrame*); @@ -123,13 +123,13 @@ void FrameStoppedLoading([Keep] LocalFrame*); void FrameScheduledNavigation([Keep] LocalFrame*, const KURL& url, double delay, ClientNavigationReason reason); void FrameClearedScheduledNavigation([Keep] LocalFrame*); - void DidCreateWebSocket([Keep] ExecutionContext*, unsigned long identifier, const KURL& request_url, const String& protocol); - void WillSendWebSocketHandshakeRequest([Keep] ExecutionContext*, unsigned long identifier, network::mojom::blink::WebSocketHandshakeRequest* request); - void DidReceiveWebSocketHandshakeResponse([Keep] ExecutionContext*, unsigned long identifier, network::mojom::blink::WebSocketHandshakeRequest* request, network::mojom::blink::WebSocketHandshakeResponse* response); - void DidCloseWebSocket([Keep] ExecutionContext*, unsigned long identifier); - void DidReceiveWebSocketMessage(ExecutionContext*, unsigned long identifier, int opcode, bool masked, const char* payload, size_t payload_length); - void DidSendWebSocketMessage(ExecutionContext*, unsigned long identifier, int opcode, bool masked, const char* payload, size_t payload_length); - void DidReceiveWebSocketMessageError(ExecutionContext*, unsigned long identifier, const String& error_message); + void DidCreateWebSocket([Keep] ExecutionContext*, uint64_t identifier, const KURL& request_url, const String& protocol); + void WillSendWebSocketHandshakeRequest([Keep] ExecutionContext*, uint64_t identifier, network::mojom::blink::WebSocketHandshakeRequest* request); + void DidReceiveWebSocketHandshakeResponse([Keep] ExecutionContext*, uint64_t identifier, network::mojom::blink::WebSocketHandshakeRequest* request, network::mojom::blink::WebSocketHandshakeResponse* response); + void DidCloseWebSocket([Keep] ExecutionContext*, uint64_t identifier); + void DidReceiveWebSocketMessage(ExecutionContext*, uint64_t identifier, int opcode, bool masked, const char* payload, size_t payload_length); + void DidSendWebSocketMessage(ExecutionContext*, uint64_t identifier, int opcode, bool masked, const char* payload, size_t payload_length); + void DidReceiveWebSocketMessageError(ExecutionContext*, uint64_t identifier, const String& error_message); void NetworkStateChanged([Keep] LocalFrame*, bool online); void UpdateApplicationCacheStatus([Keep] LocalFrame*); /* This is for pre-BlinkGenPropertyTrees. TODO(wangxianzhu): Remove this function for BlinkGenPropertyTrees. */
diff --git a/third_party/blink/renderer/core/scheduler/active_connection_throttling_test.cc b/third_party/blink/renderer/core/scheduler/active_connection_throttling_test.cc deleted file mode 100644 index 69c7cf8d..0000000 --- a/third_party/blink/renderer/core/scheduler/active_connection_throttling_test.cc +++ /dev/null
@@ -1,61 +0,0 @@ -// Copyright 2017 The Chromium Authors. All rights reserved. -// Use of this source code if governed by a BSD-style license that can be -// found in LICENSE file. - -#include "testing/gtest/include/gtest/gtest.h" -#include "third_party/blink/public/web/web_script_source.h" -#include "third_party/blink/renderer/core/exported/web_view_impl.h" -#include "third_party/blink/renderer/core/frame/web_local_frame_impl.h" -#include "third_party/blink/renderer/core/testing/sim/sim_request.h" -#include "third_party/blink/renderer/core/testing/sim/sim_test.h" -#include "third_party/blink/renderer/platform/scheduler/public/page_scheduler.h" -#include "third_party/blink/renderer/platform/testing/testing_platform_support.h" -#include "third_party/blink/renderer/platform/testing/testing_platform_support_with_web_rtc.h" - -using testing::_; - -namespace blink { - -class ActiveConnectionThrottlingTest : public SimTest {}; - -TEST_F(ActiveConnectionThrottlingTest, WebSocketStopsThrottling) { - SimRequest main_resource("https://example.com/", "text/html"); - - LoadURL("https://example.com/"); - - EXPECT_FALSE(WebView().Scheduler()->HasActiveConnectionForTest()); - - main_resource.Complete( - "(<script>" - " var socket = new WebSocket(\"ws://www.example.com/websocket\");" - "</script>)"); - - EXPECT_TRUE(WebView().Scheduler()->HasActiveConnectionForTest()); - - MainFrame().ExecuteScript(WebString("socket.close();")); - - EXPECT_FALSE(WebView().Scheduler()->HasActiveConnectionForTest()); -} - -TEST_F(ActiveConnectionThrottlingTest, WebRTCStopsThrottling) { - ScopedTestingPlatformSupport<TestingPlatformSupportWithWebRTC> platform; - - SimRequest main_resource("https://example.com/", "text/html"); - - LoadURL("https://example.com/"); - - EXPECT_FALSE(WebView().Scheduler()->HasActiveConnectionForTest()); - - main_resource.Complete( - "(<script>" - " var data_channel = new RTCPeerConnection();" - "</script>)"); - - EXPECT_TRUE(WebView().Scheduler()->HasActiveConnectionForTest()); - - MainFrame().ExecuteScript(WebString("data_channel.close();")); - - EXPECT_FALSE(WebView().Scheduler()->HasActiveConnectionForTest()); -} - -} // namespace blink
diff --git a/third_party/blink/renderer/core/scheduler/scheduler_affecting_features_test.cc b/third_party/blink/renderer/core/scheduler/scheduler_affecting_features_test.cc new file mode 100644 index 0000000..dfef2d0 --- /dev/null +++ b/third_party/blink/renderer/core/scheduler/scheduler_affecting_features_test.cc
@@ -0,0 +1,80 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code if governed by a BSD-style license that can be +// found in LICENSE file. + +#include "testing/gtest/include/gtest/gtest.h" +#include "third_party/blink/public/web/web_script_source.h" +#include "third_party/blink/renderer/core/dom/document.h" +#include "third_party/blink/renderer/core/frame/web_local_frame_impl.h" +#include "third_party/blink/renderer/core/testing/sim/sim_request.h" +#include "third_party/blink/renderer/core/testing/sim/sim_test.h" +#include "third_party/blink/renderer/platform/scheduler/public/page_scheduler.h" +#include "third_party/blink/renderer/platform/testing/testing_platform_support.h" +#include "third_party/blink/renderer/platform/testing/testing_platform_support_with_web_rtc.h" + +using testing::_; + +namespace blink { + +class SchedulingAffectingFeaturesTest : public SimTest { + public: + PageScheduler* PageScheduler() { + return MainFrame().Scheduler()->GetPageScheduler(); + } +}; + +TEST_F(SchedulingAffectingFeaturesTest, WebSocketStopsThrottling) { + SimRequest main_resource("https://example.com/", "text/html"); + + LoadURL("https://example.com/"); + + EXPECT_FALSE(PageScheduler()->OptedOutFromAggressiveThrottlingForTest()); + EXPECT_THAT(PageScheduler()->GetActiveFeaturesOptingOutFromBackForwardCache(), + testing::UnorderedElementsAre()); + + main_resource.Complete( + "(<script>" + " var socket = new WebSocket(\"ws://www.example.com/websocket\");" + "</script>)"); + + EXPECT_TRUE(PageScheduler()->OptedOutFromAggressiveThrottlingForTest()); + EXPECT_THAT( + PageScheduler()->GetActiveFeaturesOptingOutFromBackForwardCache(), + testing::UnorderedElementsAre(SchedulingPolicy::Feature::kWebSocket)); + + MainFrame().ExecuteScript(WebString("socket.close();")); + + EXPECT_FALSE(PageScheduler()->OptedOutFromAggressiveThrottlingForTest()); + EXPECT_THAT(PageScheduler()->GetActiveFeaturesOptingOutFromBackForwardCache(), + testing::UnorderedElementsAre()); +} + +TEST_F(SchedulingAffectingFeaturesTest, WebRTCStopsThrottling) { + ScopedTestingPlatformSupport<TestingPlatformSupportWithWebRTC> platform; + + SimRequest main_resource("https://example.com/", "text/html"); + + LoadURL("https://example.com/"); + + EXPECT_FALSE(PageScheduler()->OptedOutFromAggressiveThrottlingForTest()); + EXPECT_THAT(PageScheduler()->GetActiveFeaturesOptingOutFromBackForwardCache(), + testing::UnorderedElementsAre()); + + main_resource.Complete( + "(<script>" + " var data_channel = new RTCPeerConnection();" + "</script>)"); + + EXPECT_TRUE(PageScheduler()->OptedOutFromAggressiveThrottlingForTest()); + EXPECT_THAT( + PageScheduler()->GetActiveFeaturesOptingOutFromBackForwardCache(), + testing::UnorderedElementsAre(SchedulingPolicy::Feature::kWebRTC)); + + MainFrame().ExecuteScript(WebString("data_channel.close();")); + + EXPECT_FALSE(PageScheduler()->OptedOutFromAggressiveThrottlingForTest()); + EXPECT_THAT(PageScheduler()->GetActiveFeaturesOptingOutFromBackForwardCache(), + testing::UnorderedElementsAre()); +} + +} // namespace blink
diff --git a/third_party/blink/renderer/core/script/html_parser_script_runner.cc b/third_party/blink/renderer/core/script/html_parser_script_runner.cc index 5d9c294..2a22c04 100644 --- a/third_party/blink/renderer/core/script/html_parser_script_runner.cc +++ b/third_party/blink/renderer/core/script/html_parser_script_runner.cc
@@ -53,7 +53,7 @@ Document& document, const TextPosition& text_position, const KURL& url) { - std::unique_ptr<TracedValue> value = TracedValue::Create(); + auto value = std::make_unique<TracedValue>(); if (!url.IsNull()) value->SetString("url", url.GetString()); if (document.GetFrame()) {
diff --git a/third_party/blink/renderer/core/testing/internals.cc b/third_party/blink/renderer/core/testing/internals.cc index 478b5af..a212e4e 100644 --- a/third_party/blink/renderer/core/testing/internals.cc +++ b/third_party/blink/renderer/core/testing/internals.cc
@@ -2898,8 +2898,7 @@ return; GetFrame()->Reload(bypass_cache ? WebFrameLoadType::kReloadBypassingCache - : WebFrameLoadType::kReload, - ClientRedirectPolicy::kNotClientRedirect); + : WebFrameLoadType::kReload); } StaticSelection* Internals::getSelectionInFlatTree(
diff --git a/third_party/blink/renderer/core/testing/v8/web_core_test_support.cc b/third_party/blink/renderer/core/testing/v8/web_core_test_support.cc index f8aca28..793e2424 100644 --- a/third_party/blink/renderer/core/testing/v8/web_core_test_support.cc +++ b/third_party/blink/renderer/core/testing/v8/web_core_test_support.cc
@@ -127,33 +127,37 @@ } void InstallPendingOriginTrialFeatureForTesting( - const String& feature, + OriginTrialFeature feature, const ScriptState* script_state) { (*s_original_install_pending_origin_trial_feature_function)(feature, script_state); v8::Local<v8::Object> prototype_object; v8::Local<v8::Function> interface_object; - if (feature == origin_trials::kOriginTrialsSampleAPITrialName) { - if (script_state->PerContextData() - ->GetExistingConstructorAndPrototypeForType( - V8OriginTrialsTest::GetWrapperTypeInfo(), &prototype_object, - &interface_object)) { - V8OriginTrialsTest::InstallOriginTrialsSampleAPI( - script_state->GetIsolate(), script_state->World(), - v8::Local<v8::Object>(), prototype_object, interface_object); + switch (feature) { + case OriginTrialFeature::kOriginTrialsSampleAPI: { + if (script_state->PerContextData() + ->GetExistingConstructorAndPrototypeForType( + V8OriginTrialsTest::GetWrapperTypeInfo(), &prototype_object, + &interface_object)) { + V8OriginTrialsTest::InstallOriginTrialsSampleAPI( + script_state->GetIsolate(), script_state->World(), + v8::Local<v8::Object>(), prototype_object, interface_object); + } + break; } - return; - } - if (feature == origin_trials::kOriginTrialsSampleAPIImpliedTrialName) { - if (script_state->PerContextData() - ->GetExistingConstructorAndPrototypeForType( - V8OriginTrialsTest::GetWrapperTypeInfo(), &prototype_object, - &interface_object)) { - V8OriginTrialsTest::InstallOriginTrialsSampleAPIImplied( - script_state->GetIsolate(), script_state->World(), - v8::Local<v8::Object>(), prototype_object, interface_object); + case OriginTrialFeature::kOriginTrialsSampleAPIImplied: { + if (script_state->PerContextData() + ->GetExistingConstructorAndPrototypeForType( + V8OriginTrialsTest::GetWrapperTypeInfo(), &prototype_object, + &interface_object)) { + V8OriginTrialsTest::InstallOriginTrialsSampleAPIImplied( + script_state->GetIsolate(), script_state->World(), + v8::Local<v8::Object>(), prototype_object, interface_object); + } + break; } - return; + default: + break; } }
diff --git a/third_party/blink/renderer/core/timing/performance_timing.cc b/third_party/blink/renderer/core/timing/performance_timing.cc index 0b7b110..40ab139 100644 --- a/third_party/blink/renderer/core/timing/performance_timing.cc +++ b/third_party/blink/renderer/core/timing/performance_timing.cc
@@ -608,7 +608,7 @@ } std::unique_ptr<TracedValue> PerformanceTiming::GetNavigationTracingData() { - std::unique_ptr<TracedValue> data = TracedValue::Create(); + auto data = std::make_unique<TracedValue>(); data->SetString("navigationId", IdentifiersFactory::LoaderId(GetDocumentLoader())); return data;
diff --git a/third_party/blink/renderer/core/workers/worker_backing_thread.cc b/third_party/blink/renderer/core/workers/worker_backing_thread.cc index 18d07fe..e88187ba9 100644 --- a/third_party/blink/renderer/core/workers/worker_backing_thread.cc +++ b/third_party/blink/renderer/core/workers/worker_backing_thread.cc
@@ -61,7 +61,7 @@ } WorkerBackingThread::WorkerBackingThread(const ThreadCreationParams& params) - : backing_thread_(WebThreadSupportingGC::Create(params)) {} + : backing_thread_(std::make_unique<WebThreadSupportingGC>(params)) {} WorkerBackingThread::~WorkerBackingThread() = default;
diff --git a/third_party/blink/renderer/core/workers/worker_classic_script_loader.cc b/third_party/blink/renderer/core/workers/worker_classic_script_loader.cc index 4282bde..44ac6c42 100644 --- a/third_party/blink/renderer/core/workers/worker_classic_script_loader.cc +++ b/third_party/blink/renderer/core/workers/worker_classic_script_loader.cc
@@ -170,7 +170,7 @@ } void WorkerClassicScriptLoader::DidReceiveResponse( - unsigned long identifier, + uint64_t identifier, const ResourceResponse& response) { if (response.HttpStatusCode() / 100 != 2 && response.HttpStatusCode()) { NotifyError(); @@ -241,7 +241,7 @@ memcpy(cached_metadata_->data(), data, size); } -void WorkerClassicScriptLoader::DidFinishLoading(unsigned long identifier) { +void WorkerClassicScriptLoader::DidFinishLoading(uint64_t identifier) { need_to_cancel_ = false; if (!failed_ && decoder_) source_text_.Append(decoder_->Flush());
diff --git a/third_party/blink/renderer/core/workers/worker_classic_script_loader.h b/third_party/blink/renderer/core/workers/worker_classic_script_loader.h index ea4b6be..352c44e 100644 --- a/third_party/blink/renderer/core/workers/worker_classic_script_loader.h +++ b/third_party/blink/renderer/core/workers/worker_classic_script_loader.h
@@ -92,7 +92,7 @@ const KURL& ResponseURL() const; bool Failed() const { return failed_; } bool Canceled() const { return canceled_; } - unsigned long Identifier() const { return identifier_; } + uint64_t Identifier() const { return identifier_; } int64_t AppCacheID() const { return app_cache_id_; } std::unique_ptr<Vector<uint8_t>> ReleaseCachedMetadata() { @@ -114,11 +114,11 @@ } // ThreadableLoaderClient - void DidReceiveResponse(unsigned long /*identifier*/, + void DidReceiveResponse(uint64_t /*identifier*/, const ResourceResponse&) override; void DidReceiveData(const char* data, unsigned data_length) override; void DidReceiveCachedMetadata(const char*, int /*dataLength*/) override; - void DidFinishLoading(unsigned long identifier) override; + void DidFinishLoading(uint64_t identifier) override; void DidFail(const ResourceError&) override; void DidFailRedirectCheck() override; @@ -150,7 +150,7 @@ // false when LoadSynchronously() is called i.e. for importScripts(). bool is_top_level_script_ = false; - unsigned long identifier_ = 0; + uint64_t identifier_ = 0; int64_t app_cache_id_ = 0; std::unique_ptr<Vector<uint8_t>> cached_metadata_; Member<ContentSecurityPolicy> content_security_policy_;
diff --git a/third_party/blink/renderer/core/xmlhttprequest/xml_http_request.cc b/third_party/blink/renderer/core/xmlhttprequest/xml_http_request.cc index 7c7ff2b..98ffcbb 100644 --- a/third_party/blink/renderer/core/xmlhttprequest/xml_http_request.cc +++ b/third_party/blink/renderer/core/xmlhttprequest/xml_http_request.cc
@@ -1670,7 +1670,7 @@ HandleNetworkError(); } -void XMLHttpRequest::DidFinishLoading(unsigned long identifier) { +void XMLHttpRequest::DidFinishLoading(uint64_t identifier) { NETWORK_DVLOG(1) << this << " didFinishLoading(" << identifier << ")"; ScopedEventDispatchProtect protect(&event_dispatch_recursion_level_); @@ -1796,7 +1796,7 @@ } } -void XMLHttpRequest::DidReceiveResponse(unsigned long identifier, +void XMLHttpRequest::DidReceiveResponse(uint64_t identifier, const ResourceResponse& response) { // TODO(yhirano): Remove this CHECK: see https://crbug.com/570946. CHECK(&response);
diff --git a/third_party/blink/renderer/core/xmlhttprequest/xml_http_request.h b/third_party/blink/renderer/core/xmlhttprequest/xml_http_request.h index 8eee5af4..73a43ce 100644 --- a/third_party/blink/renderer/core/xmlhttprequest/xml_http_request.h +++ b/third_party/blink/renderer/core/xmlhttprequest/xml_http_request.h
@@ -182,14 +182,14 @@ void DidSendData(uint64_t bytes_sent, uint64_t total_bytes_to_be_sent) override; - void DidReceiveResponse(unsigned long identifier, + void DidReceiveResponse(uint64_t identifier, const ResourceResponse&) override; void DidReceiveData(const char* data, unsigned data_length) override; // When responseType is set to "blob", didDownloadData() is called instead // of didReceiveData(). void DidDownloadData(uint64_t data_length) override; void DidDownloadToBlob(scoped_refptr<BlobDataHandle>) override; - void DidFinishLoading(unsigned long identifier) override; + void DidFinishLoading(uint64_t identifier) override; void DidFail(const ResourceError&) override; void DidFailRedirectCheck() override;
diff --git a/third_party/blink/renderer/devtools/front_end/Tests.js b/third_party/blink/renderer/devtools/front_end/Tests.js index 6fa4ef30..49f2396 100644 --- a/third_party/blink/renderer/devtools/front_end/Tests.js +++ b/third_party/blink/renderer/devtools/front_end/Tests.js
@@ -1250,7 +1250,7 @@ this.releaseControl(); }; - TestSuite.prototype.testLoadResourceForFrontend = async function(baseURL) { + TestSuite.prototype.testLoadResourceForFrontend = async function(baseURL, fileURL) { const test = this; const loggedHeaders = new Set(['cache-control', 'pragma']); function testCase(url, headers, expectedStatus, expectedHeaders, expectedContent) { @@ -1294,6 +1294,8 @@ }); await testCase( baseURL + 'echoheader?Cookie', undefined, 200, ['cache-control'], 'devtools-test-cookie=same-site-cookie'); + await testCase('data:text/html,<body>hello</body>', undefined, 200, [], '<body>hello</body>'); + await testCase(fileURL, undefined, 200, [], '<html>\n<body>\nDummy page.\n</body>\n</html>\n'); this.releaseControl(); };
diff --git a/third_party/blink/renderer/devtools/front_end/elements/ElementsPanel.js b/third_party/blink/renderer/devtools/front_end/elements/ElementsPanel.js index bee736b..6835482 100644 --- a/third_party/blink/renderer/devtools/front_end/elements/ElementsPanel.js +++ b/third_party/blink/renderer/devtools/front_end/elements/ElementsPanel.js
@@ -676,6 +676,58 @@ this._treeOutlines[i].update(); } + /** + * @param {!Element} stylePaneWrapperElement + */ + _setupTextSelectionHack(stylePaneWrapperElement) { + // We "extend" the sidebar area when dragging, in order to keep smooth text + // selection. It should be replaced by 'user-select: contain' in the future. + const uninstallHackBound = uninstallHack.bind(this); + + // Fallback to cover unforeseen cases where text selection has ended. + const uninstallHackOnMousemove = event => { + if (event.buttons === 0) + uninstallHack.call(this); + }; + + stylePaneWrapperElement.addEventListener('mousedown', event => { + if (event.which !== 1) + return; + this._splitWidget.element.classList.add('disable-resizer-for-elements-hack'); + stylePaneWrapperElement.style.setProperty('height', `${stylePaneWrapperElement.offsetHeight}px`); + const largeLength = 1000000; + stylePaneWrapperElement.style.setProperty('left', `${- 1 * largeLength}px`); + stylePaneWrapperElement.style.setProperty('padding-left', `${largeLength}px`); + stylePaneWrapperElement.style.setProperty('width', `calc(100% + ${largeLength}px)`); + stylePaneWrapperElement.style.setProperty('position', `fixed`); + + stylePaneWrapperElement.window().addEventListener('blur', uninstallHackBound); + stylePaneWrapperElement.window().addEventListener('contextmenu', uninstallHackBound, true); + stylePaneWrapperElement.window().addEventListener('dragstart', uninstallHackBound, true); + stylePaneWrapperElement.window().addEventListener('mousemove', uninstallHackOnMousemove, true); + stylePaneWrapperElement.window().addEventListener('mouseup', uninstallHackBound, true); + stylePaneWrapperElement.window().addEventListener('visibilitychange', uninstallHackBound); + }, true); + + /** + * @this {!Elements.ElementsPanel} + */ + function uninstallHack() { + this._splitWidget.element.classList.remove('disable-resizer-for-elements-hack'); + stylePaneWrapperElement.style.removeProperty('left'); + stylePaneWrapperElement.style.removeProperty('padding-left'); + stylePaneWrapperElement.style.removeProperty('width'); + stylePaneWrapperElement.style.removeProperty('position'); + + stylePaneWrapperElement.window().removeEventListener('blur', uninstallHackBound); + stylePaneWrapperElement.window().removeEventListener('contextmenu', uninstallHackBound, true); + stylePaneWrapperElement.window().removeEventListener('dragstart', uninstallHackBound, true); + stylePaneWrapperElement.window().removeEventListener('mousemove', uninstallHackOnMousemove, true); + stylePaneWrapperElement.window().removeEventListener('mouseup', uninstallHackBound, true); + stylePaneWrapperElement.window().removeEventListener('visibilitychange', uninstallHackBound); + } + } + _updateSidebarPosition() { if (this.sidebarPaneView && this.sidebarPaneView.tabbedPane().shouldHideOnDetach()) return; // We can't reparent extension iframes. @@ -707,6 +759,7 @@ const matchedStylePanesWrapper = new UI.VBox(); matchedStylePanesWrapper.element.classList.add('style-panes-wrapper'); this._stylesWidget.show(matchedStylePanesWrapper.element); + this._setupTextSelectionHack(matchedStylePanesWrapper.element); const computedStylePanesWrapper = new UI.VBox(); computedStylePanesWrapper.element.classList.add('style-panes-wrapper');
diff --git a/third_party/blink/renderer/devtools/front_end/elements/StylesSidebarPane.js b/third_party/blink/renderer/devtools/front_end/elements/StylesSidebarPane.js index 17f1111..6892230 100644 --- a/third_party/blink/renderer/devtools/front_end/elements/StylesSidebarPane.js +++ b/third_party/blink/renderer/devtools/front_end/elements/StylesSidebarPane.js
@@ -732,7 +732,7 @@ } }; -Elements.StylesSidebarPane._maxLinkLength = 30; +Elements.StylesSidebarPane._maxLinkLength = 23; Elements.SectionBlock = class { /** @@ -844,9 +844,8 @@ this._selectorElement.addEventListener('mousemove', event => event.consume(), false); this._selectorElement.addEventListener('mouseleave', this._onMouseOutSelector.bind(this), false); - const openBrace = createElement('span'); + const openBrace = selectorContainer.createChild('span', 'sidebar-pane-open-brace'); openBrace.textContent = ' {'; - selectorContainer.appendChild(openBrace); selectorContainer.addEventListener('mousedown', this._handleEmptySpaceMouseDown.bind(this), false); selectorContainer.addEventListener('click', this._handleSelectorContainerClick.bind(this), false); @@ -929,7 +928,7 @@ if (header && header.ownerNode) { const link = Elements.DOMLinkifier.linkifyDeferredNodeReference(header.ownerNode); - link.textContent = '<style>…</style>'; + link.textContent = '<style>'; return link; }
diff --git a/third_party/blink/renderer/devtools/front_end/elements/stylesSidebarPane.css b/third_party/blink/renderer/devtools/front_end/elements/stylesSidebarPane.css index 47442464..d5be8fdc 100644 --- a/third_party/blink/renderer/devtools/front_end/elements/stylesSidebarPane.css +++ b/third_party/blink/renderer/devtools/front_end/elements/stylesSidebarPane.css
@@ -54,7 +54,7 @@ } .styles-section-title .media-list { - color: #888; + color: hsl(0, 0%, 46%); } .styles-section-title .media-list.media-matches .media.editable-media { @@ -68,13 +68,13 @@ .styles-section-title .media .subtitle { float: right; - color: rgb(85, 85, 85); + color: hsl(0, 0%, 34%); } .styles-section-subtitle { - color: rgb(85, 85, 85); + color: hsl(0, 0%, 44%); float: right; - margin-left: 5px; + padding-left: 15px; max-width: 100%; text-overflow: ellipsis; overflow: hidden; @@ -83,12 +83,18 @@ margin-bottom: -1px; } +.sidebar-pane-open-brace, +.sidebar-pane-closing-brace { + color: hsl(0, 0%, 46%); +} + .styles-section .styles-section-subtitle .devtools-link { - color: inherit; + color: hsl(0, 0%, 44%); + text-decoration-color: hsl(0, 0%, 60%); } .styles-section .selector { - color: #888; + color: hsl(0, 0%, 46%); } .styles-section .simple-selector.selector-matches, .styles-section.keyframe-key { @@ -192,7 +198,7 @@ background-color: var(--toolbar-bg-color); padding: 0 5px; border-bottom: 1px solid var(--divider-color); - color: rgb(50, 50, 50); + color: hsla(0, 0%, 32%, 1); white-space: nowrap; text-overflow: ellipsis; overflow: hidden; @@ -200,9 +206,12 @@ } .sidebar-separator > span.monospace { - background: rgb(255, 255, 255); - padding: 1px 3px; - border: 1px solid var(--divider-color); + max-width: 90px; + display: inline-block; + overflow: hidden; + text-overflow: ellipsis; + vertical-align: middle; + margin-left: 2px; } .sidebar-pane-section-toolbar {
diff --git a/third_party/blink/renderer/devtools/front_end/sdk/CSSMatchedStyles.js b/third_party/blink/renderer/devtools/front_end/sdk/CSSMatchedStyles.js index 89af71b9..eb3e595c 100644 --- a/third_party/blink/renderer/devtools/front_end/sdk/CSSMatchedStyles.js +++ b/third_party/blink/renderer/devtools/front_end/sdk/CSSMatchedStyles.js
@@ -39,12 +39,9 @@ /** @type {!Set<!SDK.CSSStyleDeclaration>} */ this._inheritedStyles = new Set(); - for (const result of matchedPayload) - cleanUserAgentSelectors(result); - for (const inheritedResult of inheritedPayload) { - for (const result of inheritedResult.matchedCSSRules) - cleanUserAgentSelectors(result); - } + matchedPayload = cleanUserAgentPayload(matchedPayload); + for (const inheritedResult of inheritedPayload) + inheritedResult.matchedCSSRules = cleanUserAgentPayload(inheritedResult.matchedCSSRules); this._mainDOMCascade = this._buildMainCascade(inlinePayload, attributesPayload, matchedPayload, inheritedPayload); this._pseudoDOMCascades = this._buildPseudoCascades(pseudoPayload); @@ -57,15 +54,67 @@ } /** - * @param {!Protocol.CSS.RuleMatch} ruleMatch + * @param {!Array<!Protocol.CSS.RuleMatch>} payload + * @return {!Array<!Protocol.CSS.RuleMatch>} */ - function cleanUserAgentSelectors(ruleMatch) { - const {matchingSelectors, rule} = ruleMatch; - if (rule.origin !== 'user-agent' || !matchingSelectors.length) - return; - rule.selectorList.selectors = rule.selectorList.selectors.filter((item, i) => matchingSelectors.includes(i)); - rule.selectorList.text = rule.selectorList.selectors.map(item => item.text).join(', '); - ruleMatch.matchingSelectors = matchingSelectors.map((item, i) => i); + function cleanUserAgentPayload(payload) { + for (const ruleMatch of payload) + cleanUserAgentSelectors(ruleMatch); + + // Merge UA rules that are sequential and have similar selector/media. + const cleanMatchedPayload = []; + for (const ruleMatch of payload) { + const lastMatch = cleanMatchedPayload.peekLast(); + if (!lastMatch || ruleMatch.rule.origin !== 'user-agent' || lastMatch.rule.origin !== 'user-agent' || + ruleMatch.rule.selectorList.text !== lastMatch.rule.selectorList.text || + mediaText(ruleMatch) !== mediaText(lastMatch)) { + cleanMatchedPayload.push(ruleMatch); + continue; + } + mergeRule(ruleMatch, lastMatch); + } + return cleanMatchedPayload; + + /** + * @param {!Protocol.CSS.RuleMatch} from + * @param {!Protocol.CSS.RuleMatch} to + */ + function mergeRule(from, to) { + const shorthands = /** @type {!Map<string, string>} */ (new Map()); + const properties = /** @type {!Map<string, string>} */ (new Map()); + for (const entry of to.rule.style.shorthandEntries) + shorthands.set(entry.name, entry.value); + for (const entry of to.rule.style.cssProperties) + properties.set(entry.name, entry.value); + for (const entry of from.rule.style.shorthandEntries) + shorthands.set(entry.name, entry.value); + for (const entry of from.rule.style.cssProperties) + properties.set(entry.name, entry.value); + to.rule.style.shorthandEntries = shorthands.keysArray().map(name => ({name, value: shorthands.get(name)})); + to.rule.style.cssProperties = properties.keysArray().map(name => ({name, value: properties.get(name)})); + } + + /** + * @param {!Protocol.CSS.RuleMatch} ruleMatch + * @return {?string} + */ + function mediaText(ruleMatch) { + if (!ruleMatch.rule.media) + return null; + return ruleMatch.rule.media.map(media => media.text).join(', '); + } + + /** + * @param {!Protocol.CSS.RuleMatch} ruleMatch + */ + function cleanUserAgentSelectors(ruleMatch) { + const {matchingSelectors, rule} = ruleMatch; + if (rule.origin !== 'user-agent' || !matchingSelectors.length) + return; + rule.selectorList.selectors = rule.selectorList.selectors.filter((item, i) => matchingSelectors.includes(i)); + rule.selectorList.text = rule.selectorList.selectors.map(item => item.text).join(', '); + ruleMatch.matchingSelectors = matchingSelectors.map((item, i) => i); + } } }
diff --git a/third_party/blink/renderer/devtools/front_end/timeline/TimelineFlameChartDataProvider.js b/third_party/blink/renderer/devtools/front_end/timeline/TimelineFlameChartDataProvider.js index 197a54c..b758eeb 100644 --- a/third_party/blink/renderer/devtools/front_end/timeline/TimelineFlameChartDataProvider.js +++ b/third_party/blink/renderer/devtools/front_end/timeline/TimelineFlameChartDataProvider.js
@@ -220,8 +220,14 @@ const eventEntryType = Timeline.TimelineFlameChartDataProvider.EntryType.Event; /** @type {!Multimap<!SDK.TracingModel.Process, !TimelineModel.TimelineModel.Track>} */ const tracksByProcess = new Multimap(); - for (const track of this._model.tracks()) - tracksByProcess.set(track.thread.process(), track); + for (const track of this._model.tracks()) { + if (track.thread !== null) { + tracksByProcess.set(track.thread.process(), track); + } else { + // The Timings track can reach this point, so we should probably do something more useful. + console.error('Failed to process track'); + } + } for (const process of tracksByProcess.keysArray()) { if (tracksByProcess.size > 1) { const name = `${process.name()} ${process.id()}`;
diff --git a/third_party/blink/renderer/devtools/front_end/ui/splitWidget.css b/third_party/blink/renderer/devtools/front_end/ui/splitWidget.css index b0171ca..58edda6c4 100644 --- a/third_party/blink/renderer/devtools/front_end/ui/splitWidget.css +++ b/third_party/blink/renderer/devtools/front_end/ui/splitWidget.css
@@ -93,3 +93,7 @@ border: 0; border-right: 1px solid var(--divider-color); } + +:host-context(.disable-resizer-for-elements-hack) .shadow-split-widget-resizer { + pointer-events: none; +}
diff --git a/third_party/blink/renderer/modules/BUILD.gn b/third_party/blink/renderer/modules/BUILD.gn index 9cd46b7..762da04 100644 --- a/third_party/blink/renderer/modules/BUILD.gn +++ b/third_party/blink/renderer/modules/BUILD.gn
@@ -141,7 +141,6 @@ "//third_party/blink/renderer/modules/remoteplayback", "//third_party/blink/renderer/modules/screen_orientation", "//third_party/blink/renderer/modules/sensor", - "//third_party/blink/renderer/modules/serial", "//third_party/blink/renderer/modules/service_worker", "//third_party/blink/renderer/modules/shapedetection", "//third_party/blink/renderer/modules/speech", @@ -168,6 +167,10 @@ "//third_party/zlib", ] + if (!is_android) { + deps += [ "//third_party/blink/renderer/modules/serial" ] + } + if (is_win) { cflags = [ "/wd4334" ] # Result of 32-bit shift implicitly converted to 64 bits. } @@ -325,6 +328,7 @@ "peerconnection/rtc_quic_stream_test.cc", "peerconnection/rtc_quic_transport_test.cc", "peerconnection/rtc_quic_transport_test.h", + "peerconnection/rtc_sctp_transport_test.cc", "picture_in_picture/picture_in_picture_controller_test.cc", "presentation/mock_presentation_service.h", "presentation/presentation_availability_state_test.cc",
diff --git a/third_party/blink/renderer/modules/background_fetch/background_fetch_icon_loader.cc b/third_party/blink/renderer/modules/background_fetch/background_fetch_icon_loader.cc index 4f62842..c344e1b 100644 --- a/third_party/blink/renderer/modules/background_fetch/background_fetch_icon_loader.cc +++ b/third_party/blink/renderer/modules/background_fetch/background_fetch_icon_loader.cc
@@ -32,7 +32,7 @@ namespace { -constexpr unsigned long kIconFetchTimeoutInMs = 30000; +constexpr uint32_t kIconFetchTimeoutInMs = 30000; constexpr int kMinimumIconSizeInPx = 0; // Because including base::ClampToRange would be a dependency violation. @@ -151,8 +151,7 @@ data_->Append(data, length); } -void BackgroundFetchIconLoader::DidFinishLoading( - unsigned long resource_identifier) { +void BackgroundFetchIconLoader::DidFinishLoading(uint64_t resource_identifier) { if (stopped_) return;
diff --git a/third_party/blink/renderer/modules/background_fetch/background_fetch_icon_loader.h b/third_party/blink/renderer/modules/background_fetch/background_fetch_icon_loader.h index 77005a6..8e18843 100644 --- a/third_party/blink/renderer/modules/background_fetch/background_fetch_icon_loader.h +++ b/third_party/blink/renderer/modules/background_fetch/background_fetch_icon_loader.h
@@ -48,7 +48,7 @@ // ThreadableLoaderClient interface. void DidReceiveData(const char* data, unsigned length) override; - void DidFinishLoading(unsigned long resource_identifier) override; + void DidFinishLoading(uint64_t resource_identifier) override; void DidFail(const ResourceError& error) override; void DidFailRedirectCheck() override;
diff --git a/third_party/blink/renderer/modules/cache_storage/cache_storage_trace_utils.cc b/third_party/blink/renderer/modules/cache_storage/cache_storage_trace_utils.cc index ae45457..3f815ef3 100644 --- a/third_party/blink/renderer/modules/cache_storage/cache_storage_trace_utils.cc +++ b/third_party/blink/renderer/modules/cache_storage/cache_storage_trace_utils.cc
@@ -24,14 +24,14 @@ } // namespace std::unique_ptr<TracedValue> CacheStorageTracedValue(const String& string) { - std::unique_ptr<TracedValue> value = TracedValue::Create(); + auto value = std::make_unique<TracedValue>(); value->SetString("string", string); return value; } std::unique_ptr<TracedValue> CacheStorageTracedValue( const mojom::blink::FetchAPIRequestPtr& request) { - std::unique_ptr<TracedValue> value = TracedValue::Create(); + auto value = std::make_unique<TracedValue>(); if (request) { value->SetString("url", request->url.GetString()); value->SetString("method", @@ -43,7 +43,7 @@ std::unique_ptr<TracedValue> CacheStorageTracedValue( const WTF::Vector<mojom::blink::FetchAPIRequestPtr>& requests) { - std::unique_ptr<TracedValue> value = TracedValue::Create(); + auto value = std::make_unique<TracedValue>(); value->SetInteger("count", requests.size()); if (!requests.IsEmpty()) { value->SetValue("first", CacheStorageTracedValue(requests.front()).get()); @@ -53,7 +53,7 @@ std::unique_ptr<TracedValue> CacheStorageTracedValue( const mojom::blink::CacheQueryOptionsPtr& options) { - std::unique_ptr<TracedValue> value = TracedValue::Create(); + auto value = std::make_unique<TracedValue>(); if (options) { value->SetBoolean("ignore_method", options->ignore_method); value->SetBoolean("ignore_search", options->ignore_search); @@ -65,7 +65,7 @@ std::unique_ptr<TracedValue> CacheStorageTracedValue( const mojom::blink::MultiCacheQueryOptionsPtr& options) { if (!options) - return TracedValue::Create(); + return std::make_unique<TracedValue>(); std::unique_ptr<TracedValue> value = CacheStorageTracedValue(options->query_options); if (!options->cache_name.IsNull()) { @@ -80,7 +80,7 @@ std::unique_ptr<TracedValue> CacheStorageTracedValue( const mojom::blink::FetchAPIResponsePtr& response) { - std::unique_ptr<TracedValue> value = TracedValue::Create(); + auto value = std::make_unique<TracedValue>(); if (response) { if (!response->url_list.IsEmpty()) { value->SetString("url", response->url_list.back().GetString()); @@ -93,7 +93,7 @@ std::unique_ptr<TracedValue> CacheStorageTracedValue( const WTF::Vector<mojom::blink::FetchAPIResponsePtr>& responses) { - std::unique_ptr<TracedValue> value = TracedValue::Create(); + auto value = std::make_unique<TracedValue>(); value->SetInteger("count", responses.size()); if (!responses.IsEmpty()) { value->SetValue("first", CacheStorageTracedValue(responses.front()).get()); @@ -103,7 +103,7 @@ std::unique_ptr<TracedValue> CacheStorageTracedValue( const mojom::blink::BatchOperationPtr& op) { - std::unique_ptr<TracedValue> value = TracedValue::Create(); + auto value = std::make_unique<TracedValue>(); if (op) { value->SetValue("request", CacheStorageTracedValue(op->request).get()); value->SetValue("response", CacheStorageTracedValue(op->response).get()); @@ -115,7 +115,7 @@ std::unique_ptr<TracedValue> CacheStorageTracedValue( const WTF::Vector<String>& string_list) { - std::unique_ptr<TracedValue> value = TracedValue::Create(); + auto value = std::make_unique<TracedValue>(); value->SetInteger("count", string_list.size()); if (!string_list.IsEmpty()) { value->SetString("first", string_list.front());
diff --git a/third_party/blink/renderer/modules/canvas/htmlcanvas/canvas_context_creation_attributes_helpers.cc b/third_party/blink/renderer/modules/canvas/htmlcanvas/canvas_context_creation_attributes_helpers.cc index 40c3bab..085a33f 100644 --- a/third_party/blink/renderer/modules/canvas/htmlcanvas/canvas_context_creation_attributes_helpers.cc +++ b/third_party/blink/renderer/modules/canvas/htmlcanvas/canvas_context_creation_attributes_helpers.cc
@@ -27,6 +27,7 @@ result.pixel_format = attrs->pixelFormat(); result.premultiplied_alpha = attrs->premultipliedAlpha(); result.preserve_drawing_buffer = attrs->preserveDrawingBuffer(); + result.power_preference = attrs->powerPreference(); result.stencil = attrs->stencil(); result.xr_compatible = attrs->xrCompatible(); return result;
diff --git a/third_party/blink/renderer/modules/canvas/htmlcanvas/canvas_context_creation_attributes_module.idl b/third_party/blink/renderer/modules/canvas/htmlcanvas/canvas_context_creation_attributes_module.idl index ad9f867..b4f97a0f 100644 --- a/third_party/blink/renderer/modules/canvas/htmlcanvas/canvas_context_creation_attributes_module.idl +++ b/third_party/blink/renderer/modules/canvas/htmlcanvas/canvas_context_creation_attributes_module.idl
@@ -28,6 +28,12 @@ "float16", }; +enum CanvasPowerPreference { + "default", + "low-power", + "high-performance", +}; + [PermissiveDictionaryConversion] dictionary CanvasContextCreationAttributesModule { // This is an experimental feature, but it is not hidden behind a flag in @@ -47,6 +53,7 @@ boolean antialias = true; boolean premultipliedAlpha = true; boolean preserveDrawingBuffer = false; + CanvasPowerPreference powerPreference = "default"; boolean failIfMajorPerformanceCaveat = false; [OriginTrialEnabled=WebXR] boolean xrCompatible = false; };
diff --git a/third_party/blink/renderer/modules/clipboard/clipboard_promise.cc b/third_party/blink/renderer/modules/clipboard/clipboard_promise.cc index b99b656f..3fc4e3d 100644 --- a/third_party/blink/renderer/modules/clipboard/clipboard_promise.cc +++ b/third_party/blink/renderer/modules/clipboard/clipboard_promise.cc
@@ -122,9 +122,9 @@ scoped_refptr<base::SingleThreadTaskRunner> ClipboardPromise::GetTaskRunner() { DCHECK_CALLED_ON_VALID_SEQUENCE(async_clipboard_sequence_checker); - // TODO(https://crbug.com/941835): Replace MiscPlatformAPI with TaskType - // specific to clipboard. - return GetExecutionContext()->GetTaskRunner(TaskType::kMiscPlatformAPI); + // Get the User Interaction task runner, as Async Clipboard API calls require + // user interaction, as specified in https://w3c.github.io/clipboard-apis/ + return GetExecutionContext()->GetTaskRunner(TaskType::kUserInteraction); } PermissionService* ClipboardPromise::GetPermissionService() {
diff --git a/third_party/blink/renderer/modules/encryptedmedia/content_decryption_module_result_promise.cc b/third_party/blink/renderer/modules/encryptedmedia/content_decryption_module_result_promise.cc index d159464..8b42bbd 100644 --- a/third_party/blink/renderer/modules/encryptedmedia/content_decryption_module_result_promise.cc +++ b/third_party/blink/renderer/modules/encryptedmedia/content_decryption_module_result_promise.cc
@@ -82,7 +82,7 @@ void ContentDecryptionModuleResultPromise::CompleteWithError( WebContentDecryptionModuleException exception_code, - unsigned long system_code, + uint32_t system_code, const WebString& error_message) { if (!IsValidToFulfillPromise()) return;
diff --git a/third_party/blink/renderer/modules/encryptedmedia/content_decryption_module_result_promise.h b/third_party/blink/renderer/modules/encryptedmedia/content_decryption_module_result_promise.h index 6f9076912..1ffcebe 100644 --- a/third_party/blink/renderer/modules/encryptedmedia/content_decryption_module_result_promise.h +++ b/third_party/blink/renderer/modules/encryptedmedia/content_decryption_module_result_promise.h
@@ -43,7 +43,7 @@ void CompleteWithKeyStatus( WebEncryptedMediaKeyInformation::KeyStatus) override; void CompleteWithError(WebContentDecryptionModuleException, - unsigned long system_code, + uint32_t system_code, const WebString&) override; // It is only valid to call this before completion.
diff --git a/third_party/blink/renderer/modules/encryptedmedia/html_media_element_encrypted_media.cc b/third_party/blink/renderer/modules/encryptedmedia/html_media_element_encrypted_media.cc index 4badd6d4..3ec04b9c 100644 --- a/third_party/blink/renderer/modules/encryptedmedia/html_media_element_encrypted_media.cc +++ b/third_party/blink/renderer/modules/encryptedmedia/html_media_element_encrypted_media.cc
@@ -102,7 +102,7 @@ } void CompleteWithError(WebContentDecryptionModuleException code, - unsigned long system_code, + uint32_t system_code, const WebString& message) override { // Non-zero |systemCode| is appended to the |message|. If the |message| // is empty, we'll report "Rejected with system code (systemCode)".
diff --git a/third_party/blink/renderer/modules/encryptedmedia/media_keys.cc b/third_party/blink/renderer/modules/encryptedmedia/media_keys.cc index 343c0d0..7550712a 100644 --- a/third_party/blink/renderer/modules/encryptedmedia/media_keys.cc +++ b/third_party/blink/renderer/modules/encryptedmedia/media_keys.cc
@@ -135,7 +135,7 @@ } void CompleteWithError(WebContentDecryptionModuleException exception_code, - unsigned long system_code, + uint32_t system_code, const WebString& error_message) override { if (!IsValidToFulfillPromise()) return;
diff --git a/third_party/blink/renderer/modules/event_target_modules_names.json5 b/third_party/blink/renderer/modules/event_target_modules_names.json5 index b2f6898..d8974877 100644 --- a/third_party/blink/renderer/modules/event_target_modules_names.json5 +++ b/third_party/blink/renderer/modules/event_target_modules_names.json5
@@ -34,6 +34,7 @@ "RTCDataChannel", "RTCDtlsTransport", "RTCPeerConnection", + "RTCSctpTransport", "NetworkInformation", "Notification", "PaymentRequest",
diff --git a/third_party/blink/renderer/modules/eventsource/event_source.cc b/third_party/blink/renderer/modules/eventsource/event_source.cc index 8802168..a79a1ee 100644 --- a/third_party/blink/renderer/modules/eventsource/event_source.cc +++ b/third_party/blink/renderer/modules/eventsource/event_source.cc
@@ -219,7 +219,7 @@ return ContextLifecycleObserver::GetExecutionContext(); } -void EventSource::DidReceiveResponse(unsigned long identifier, +void EventSource::DidReceiveResponse(uint64_t identifier, const ResourceResponse& response) { DCHECK_EQ(kConnecting, state_); DCHECK(loader_); @@ -284,7 +284,7 @@ parser_->AddBytes(data, length); } -void EventSource::DidFinishLoading(unsigned long) { +void EventSource::DidFinishLoading(uint64_t) { DCHECK_EQ(kOpen, state_); DCHECK(loader_);
diff --git a/third_party/blink/renderer/modules/eventsource/event_source.h b/third_party/blink/renderer/modules/eventsource/event_source.h index 815cd3e..c462a4d 100644 --- a/third_party/blink/renderer/modules/eventsource/event_source.h +++ b/third_party/blink/renderer/modules/eventsource/event_source.h
@@ -102,9 +102,9 @@ void Trace(blink::Visitor*) override; private: - void DidReceiveResponse(unsigned long, const ResourceResponse&) override; + void DidReceiveResponse(uint64_t, const ResourceResponse&) override; void DidReceiveData(const char*, unsigned) override; - void DidFinishLoading(unsigned long) override; + void DidFinishLoading(uint64_t) override; void DidFail(const ResourceError&) override; void DidFailRedirectCheck() override; @@ -135,7 +135,7 @@ uint64_t reconnect_delay_; String event_stream_origin_; - unsigned long resource_identifier_ = 0; + uint64_t resource_identifier_ = 0; }; } // namespace blink
diff --git a/third_party/blink/renderer/modules/filesystem/BUILD.gn b/third_party/blink/renderer/modules/filesystem/BUILD.gn index 02153462..ddf82bb5 100644 --- a/third_party/blink/renderer/modules/filesystem/BUILD.gn +++ b/third_party/blink/renderer/modules/filesystem/BUILD.gn
@@ -6,6 +6,7 @@ blink_modules_sources("filesystem") { sources = [ + "async_callback_helper.h", "data_transfer_item_file_system.cc", "data_transfer_item_file_system.h", "dev_tools_host_file_system.cc",
diff --git a/third_party/blink/renderer/modules/filesystem/async_callback_helper.h b/third_party/blink/renderer/modules/filesystem/async_callback_helper.h new file mode 100644 index 0000000..f7870df --- /dev/null +++ b/third_party/blink/renderer/modules/filesystem/async_callback_helper.h
@@ -0,0 +1,53 @@ +// 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 THIRD_PARTY_BLINK_RENDERER_MODULES_FILESYSTEM_ASYNC_CALLBACK_HELPER_H_ +#define THIRD_PARTY_BLINK_RENDERER_MODULES_FILESYSTEM_ASYNC_CALLBACK_HELPER_H_ + +#include "third_party/blink/renderer/core/execution_context/execution_context.h" +#include "third_party/blink/renderer/core/fileapi/file_error.h" +#include "third_party/blink/renderer/modules/filesystem/directory_entry.h" +#include "third_party/blink/renderer/modules/filesystem/file_system_callbacks.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/wtf/functional.h" + +namespace blink { + +class AsyncCallbackHelper { + STATIC_ONLY(AsyncCallbackHelper); + + public: + template <typename CallbackParam, typename V8Callback> + static base::OnceCallback<void(CallbackParam*)> SuccessCallback( + V8Callback* success_callback) { + auto success_callback_wrapper = WTF::Bind( + [](V8PersistentCallbackInterface<V8Callback>* persistent_callback, + CallbackParam* param) { + persistent_callback->InvokeAndReportException(nullptr, param); + }, + WrapPersistentIfNeeded( + ToV8PersistentCallbackInterface(success_callback))); + return success_callback_wrapper; + } + + static base::OnceCallback<void(base::File::Error)> ErrorCallback( + V8ErrorCallback* error_callback) { + if (!error_callback) + return base::OnceCallback<void(base::File::Error)>(); + + return WTF::Bind( + [](V8PersistentCallbackInterface<V8ErrorCallback>* persistent_callback, + base::File::Error error) { + persistent_callback->InvokeAndReportException( + nullptr, file_error::CreateDOMException(error)); + }, + WrapPersistentIfNeeded( + ToV8PersistentCallbackInterface(error_callback))); + } +}; + +} // namespace blink + +#endif // THIRD_PARTY_BLINK_RENDERER_MODULES_FILESYSTEM_ASYNC_CALLBACK_HELPER_H_
diff --git a/third_party/blink/renderer/modules/filesystem/dom_file_system_base.cc b/third_party/blink/renderer/modules/filesystem/dom_file_system_base.cc index a2a0235..818cb8e 100644 --- a/third_party/blink/renderer/modules/filesystem/dom_file_system_base.cc +++ b/third_party/blink/renderer/modules/filesystem/dom_file_system_base.cc
@@ -206,11 +206,11 @@ void DOMFileSystemBase::GetMetadata( const EntryBase* entry, - MetadataCallbacks::OnDidReadMetadataCallback* success_callback, - ErrorCallbackBase* error_callback, + MetadataCallbacks::SuccessCallback success_callback, + MetadataCallbacks::ErrorCallback error_callback, SynchronousType synchronous_type) { auto callbacks = std::make_unique<MetadataCallbacks>( - success_callback, error_callback, context_, this); + std::move(success_callback), std::move(error_callback), context_, this); FileSystemDispatcher& dispatcher = FileSystemDispatcher::From(context_); if (synchronous_type == kSynchronous) {
diff --git a/third_party/blink/renderer/modules/filesystem/dom_file_system_base.h b/third_party/blink/renderer/modules/filesystem/dom_file_system_base.h index 4e19500..a0cbd3b 100644 --- a/third_party/blink/renderer/modules/filesystem/dom_file_system_base.h +++ b/third_party/blink/renderer/modules/filesystem/dom_file_system_base.h
@@ -107,8 +107,8 @@ // Actual FileSystem API implementations. All the validity checks on virtual // paths are done at this level. void GetMetadata(const EntryBase*, - MetadataCallbacks::OnDidReadMetadataCallback*, - ErrorCallbackBase*, + MetadataCallbacks::SuccessCallback, + MetadataCallbacks::ErrorCallback, SynchronousType = kAsynchronous); void Move(const EntryBase* source, EntryBase* parent,
diff --git a/third_party/blink/renderer/modules/filesystem/entry.cc b/third_party/blink/renderer/modules/filesystem/entry.cc index 154ff61..f0eea525 100644 --- a/third_party/blink/renderer/modules/filesystem/entry.cc +++ b/third_party/blink/renderer/modules/filesystem/entry.cc
@@ -32,10 +32,12 @@ #include "third_party/blink/renderer/core/execution_context/execution_context.h" #include "third_party/blink/renderer/core/fileapi/file_error.h" #include "third_party/blink/renderer/core/frame/use_counter.h" +#include "third_party/blink/renderer/modules/filesystem/async_callback_helper.h" #include "third_party/blink/renderer/modules/filesystem/directory_entry.h" #include "third_party/blink/renderer/modules/filesystem/file_system_callbacks.h" #include "third_party/blink/renderer/platform/bindings/script_state.h" #include "third_party/blink/renderer/platform/weborigin/security_origin.h" +#include "third_party/blink/renderer/platform/wtf/functional.h" #include "third_party/blink/renderer/platform/wtf/text/string_builder.h" namespace blink { @@ -59,10 +61,14 @@ UseCounter::Count(ExecutionContext::From(script_state), WebFeature::kEntry_GetMetadata_Method_IsolatedFileSystem); } - file_system_->GetMetadata( - this, - MetadataCallbacks::OnDidReadMetadataV8Impl::Create(success_callback), - ScriptErrorCallback::Wrap(error_callback)); + + auto success_callback_wrapper = + AsyncCallbackHelper::SuccessCallback<Metadata>(success_callback); + auto error_callback_wrapper = + AsyncCallbackHelper::ErrorCallback(error_callback); + + file_system_->GetMetadata(this, std::move(success_callback_wrapper), + std::move(error_callback_wrapper)); } void Entry::moveTo(ScriptState* script_state,
diff --git a/third_party/blink/renderer/modules/filesystem/entry_sync.cc b/third_party/blink/renderer/modules/filesystem/entry_sync.cc index 7f64c12..f382696 100644 --- a/third_party/blink/renderer/modules/filesystem/entry_sync.cc +++ b/third_party/blink/renderer/modules/filesystem/entry_sync.cc
@@ -37,6 +37,7 @@ #include "third_party/blink/renderer/modules/filesystem/metadata.h" #include "third_party/blink/renderer/modules/filesystem/sync_callback_helper.h" #include "third_party/blink/renderer/platform/bindings/exception_state.h" +#include "third_party/blink/renderer/platform/wtf/functional.h" namespace blink { @@ -48,8 +49,15 @@ Metadata* EntrySync::getMetadata(ExceptionState& exception_state) { auto* sync_helper = MakeGarbageCollected<MetadataCallbacksSyncHelper>(); - file_system_->GetMetadata(this, sync_helper->GetSuccessCallback(), - sync_helper->GetErrorCallback(), + + auto success_callback_wrapper = + WTF::Bind(&MetadataCallbacksSyncHelper::OnSuccess, + WrapPersistentIfNeeded(sync_helper)); + auto error_callback_wrapper = WTF::Bind(&MetadataCallbacksSyncHelper::OnError, + WrapPersistentIfNeeded(sync_helper)); + + file_system_->GetMetadata(this, std::move(success_callback_wrapper), + std::move(error_callback_wrapper), DOMFileSystemBase::kSynchronous); return sync_helper->GetResultOrThrow(exception_state); }
diff --git a/third_party/blink/renderer/modules/filesystem/file_system_callbacks.cc b/third_party/blink/renderer/modules/filesystem/file_system_callbacks.cc index 334abf1cf..2cbaa0a 100644 --- a/third_party/blink/renderer/modules/filesystem/file_system_callbacks.cc +++ b/third_party/blink/renderer/modules/filesystem/file_system_callbacks.cc
@@ -31,6 +31,7 @@ #include "third_party/blink/renderer/modules/filesystem/file_system_callbacks.h" #include <memory> +#include <utility> #include "base/memory/ptr_util.h" #include "third_party/blink/renderer/bindings/core/v8/script_promise_resolver.h" @@ -306,36 +307,26 @@ // MetadataCallbacks ---------------------------------------------------------- -void MetadataCallbacks::OnDidReadMetadataV8Impl::Trace( - blink::Visitor* visitor) { - visitor->Trace(callback_); - OnDidReadMetadataCallback::Trace(visitor); -} - -void MetadataCallbacks::OnDidReadMetadataV8Impl::OnSuccess(Metadata* metadata) { - callback_->InvokeAndReportException(nullptr, metadata); -} - -MetadataCallbacks::MetadataCallbacks( - OnDidReadMetadataCallback* success_callback, - ErrorCallbackBase* error_callback, - ExecutionContext* context, - DOMFileSystemBase* file_system) - : FileSystemCallbacksBase(error_callback, file_system, context), - success_callback_(success_callback) {} +MetadataCallbacks::MetadataCallbacks(SuccessCallback success_callback, + ErrorCallback error_callback, + ExecutionContext* context, + DOMFileSystemBase* file_system) + : FileSystemCallbacksBase(/*error_callback=*/nullptr, file_system, context), + success_callback_(std::move(success_callback)), + error_callback_(std::move(error_callback)) {} void MetadataCallbacks::DidReadMetadata(const FileMetadata& metadata) { if (!success_callback_) return; - success_callback_.Release()->OnSuccess(Metadata::Create(metadata)); + std::move(success_callback_).Run(Metadata::Create(metadata)); } void MetadataCallbacks::DidFail(base::File::Error error) { if (!error_callback_) return; - error_callback_.Release()->Invoke(error); + std::move(error_callback_).Run(error); } // FileWriterCallbacks ----------------------------------------------------
diff --git a/third_party/blink/renderer/modules/filesystem/file_system_callbacks.h b/third_party/blink/renderer/modules/filesystem/file_system_callbacks.h index 9e43fec3..f8ddb78 100644 --- a/third_party/blink/renderer/modules/filesystem/file_system_callbacks.h +++ b/third_party/blink/renderer/modules/filesystem/file_system_callbacks.h
@@ -306,6 +306,13 @@ class MetadataCallbacks final : public FileSystemCallbacksBase { public: + using SuccessCallback = base::OnceCallback<void(Metadata* metadata)>; + using ErrorCallback = base::OnceCallback<void(base::File::Error error)>; + + // TODO(tonikitoo,mek): This class is not being effectively used anymore. + // Remove it when all classes have switched to simple success/error callbacks + // implementation, and there is no reference to it in sync_callback_helper.h + // anymore. class OnDidReadMetadataCallback : public GarbageCollectedFinalized<OnDidReadMetadataCallback> { public: @@ -317,25 +324,8 @@ OnDidReadMetadataCallback() = default; }; - class OnDidReadMetadataV8Impl : public OnDidReadMetadataCallback { - public: - static OnDidReadMetadataV8Impl* Create(V8MetadataCallback* callback) { - return callback ? MakeGarbageCollected<OnDidReadMetadataV8Impl>(callback) - : nullptr; - } - - OnDidReadMetadataV8Impl(V8MetadataCallback* callback) - : callback_(ToV8PersistentCallbackInterface(callback)) {} - - void Trace(blink::Visitor*) override; - void OnSuccess(Metadata*) override; - - private: - Member<V8PersistentCallbackInterface<V8MetadataCallback>> callback_; - }; - - MetadataCallbacks(OnDidReadMetadataCallback*, - ErrorCallbackBase*, + MetadataCallbacks(SuccessCallback, + ErrorCallback, ExecutionContext*, DOMFileSystemBase*); @@ -346,7 +336,8 @@ void DidFail(base::File::Error error); private: - Persistent<OnDidReadMetadataCallback> success_callback_; + SuccessCallback success_callback_; + ErrorCallback error_callback_; }; class FileWriterCallbacks final : public FileSystemCallbacksBase {
diff --git a/third_party/blink/renderer/modules/filesystem/sync_callback_helper.h b/third_party/blink/renderer/modules/filesystem/sync_callback_helper.h index 10bda92..5a94a76 100644 --- a/third_party/blink/renderer/modules/filesystem/sync_callback_helper.h +++ b/third_party/blink/renderer/modules/filesystem/sync_callback_helper.h
@@ -35,6 +35,7 @@ #include "third_party/blink/renderer/core/fileapi/file_error.h" #include "third_party/blink/renderer/modules/filesystem/file_system_callbacks.h" #include "third_party/blink/renderer/platform/heap/handle.h" +#include "third_party/blink/renderer/platform/wtf/functional.h" namespace blink { @@ -48,6 +49,10 @@ void Trace(blink::Visitor* visitor) { visitor->Trace(result_); } + // Deprecated success and error callback wrappers. + // + // NOTE: These will be removed when all wrapper callback classes switch to + // using the simple/new implementation (see below). SuccessCallback* GetSuccessCallback() { return MakeGarbageCollected<SuccessCallbackImpl>(this); } @@ -55,6 +60,13 @@ return MakeGarbageCollected<ErrorCallbackImpl>(this); } + // Simple/new success and error callback wrappers. + void OnSuccess(CallbackArg* arg) { + DCHECK(arg); + result_ = arg; + } + void OnError(base::File::Error error_code) { error_code_ = error_code; } + CallbackArg* GetResultOrThrow(ExceptionState& exception_state) { if (error_code_ != base::File::FILE_OK) { file_error::ThrowDOMException(exception_state, error_code_);
diff --git a/third_party/blink/renderer/modules/media_controls/media_controls_impl.cc b/third_party/blink/renderer/modules/media_controls/media_controls_impl.cc index 8b2c514..eae4e17 100644 --- a/third_party/blink/renderer/modules/media_controls/media_controls_impl.cc +++ b/third_party/blink/renderer/modules/media_controls/media_controls_impl.cc
@@ -40,6 +40,7 @@ #include "third_party/blink/renderer/core/events/gesture_event.h" #include "third_party/blink/renderer/core/events/keyboard_event.h" #include "third_party/blink/renderer/core/events/pointer_event.h" +#include "third_party/blink/renderer/core/frame/local_frame.h" #include "third_party/blink/renderer/core/frame/settings.h" #include "third_party/blink/renderer/core/frame/use_counter.h" #include "third_party/blink/renderer/core/fullscreen/fullscreen.h" @@ -1763,6 +1764,9 @@ DOMRect* rect = getBoundingClientRect(); double middle = rect->x() + (rect->width() / 2); + if (GetDocument().GetFrame()) + middle *= GetDocument().GetFrame()->PageZoomFactor(); + return tap_x < middle; }
diff --git a/third_party/blink/renderer/modules/media_controls/media_controls_impl_test.cc b/third_party/blink/renderer/modules/media_controls/media_controls_impl_test.cc index 0b92a45..d56dfda 100644 --- a/third_party/blink/renderer/modules/media_controls/media_controls_impl_test.cc +++ b/third_party/blink/renderer/modules/media_controls/media_controls_impl_test.cc
@@ -281,6 +281,9 @@ void MouseMoveTo(WebFloatPoint pos); void MouseUpAt(WebFloatPoint pos); + void GestureTapAt(WebFloatPoint pos); + void GestureDoubleTapAt(WebFloatPoint pos); + bool HasAvailabilityCallbacks(RemotePlayback& remote_playback) { return !remote_playback.availability_callbacks_.IsEmpty(); } @@ -332,6 +335,28 @@ mouse_up_event); } +void MediaControlsImplTest::GestureTapAt(WebFloatPoint pos) { + WebGestureEvent gesture_tap_event( + WebInputEvent::kGestureTap, WebInputEvent::kNoModifiers, + WebInputEvent::GetStaticTimeStampForTests()); + + // Adjust |pos| by current frame scale. + float frame_scale = GetDocument().GetFrame()->PageZoomFactor(); + gesture_tap_event.SetFrameScale(frame_scale); + pos.x = pos.x * frame_scale; + pos.y = pos.y * frame_scale; + gesture_tap_event.SetPositionInWidget(pos); + + // Fire the event. + GetDocument().GetFrame()->GetEventHandler().HandleGestureEvent( + gesture_tap_event); +} + +void MediaControlsImplTest::GestureDoubleTapAt(WebFloatPoint pos) { + GestureTapAt(pos); + GestureTapAt(pos); +} + TEST_F(MediaControlsImplTest, HideAndShow) { Element* panel = GetElementByShadowPseudoId(MediaControls(), "-webkit-media-controls-panel"); @@ -1346,4 +1371,67 @@ EXPECT_FALSE(TimelineElement()->hasAttribute(html_names::kDisabledAttr)); } +TEST_F(ModernMediaControlsImplTest, DoubleTouchChangesTime) { + double duration = 60; // 1 minute. + LoadMediaWithDuration(duration); + EnsureSizing(); + MediaControls().MediaElement().setCurrentTime(30); + test::RunPendingTasks(); + + // We've set the video to the halfway mark. + EXPECT_EQ(30, MediaControls().MediaElement().currentTime()); + + DOMRect* videoRect = MediaControls().MediaElement().getBoundingClientRect(); + ASSERT_LT(0, videoRect->width()); + WebFloatPoint leftOfCenter(videoRect->left() + (videoRect->width() / 2) - 5, + videoRect->top() + 5); + WebFloatPoint rightOfCenter(videoRect->left() + (videoRect->width() / 2) + 5, + videoRect->top() + 5); + + // Double-tapping left of center should shift the time backwards by 10 + // seconds. + GestureDoubleTapAt(leftOfCenter); + test::RunPendingTasks(); + EXPECT_EQ(20, MediaControls().MediaElement().currentTime()); + + // Double-tapping right of center should shift the time forwards by 10 + // seconds. + GestureDoubleTapAt(rightOfCenter); + test::RunPendingTasks(); + EXPECT_EQ(30, MediaControls().MediaElement().currentTime()); +} + +TEST_F(ModernMediaControlsImplTest, DoubleTouchChangesTimeWhenZoomed) { + double duration = 60; // 1 minute. + LoadMediaWithDuration(duration); + EnsureSizing(); + MediaControls().MediaElement().setCurrentTime(30); + test::RunPendingTasks(); + + // We've set the video to the halfway mark. + EXPECT_EQ(30, MediaControls().MediaElement().currentTime()); + + DOMRect* videoRect = MediaControls().MediaElement().getBoundingClientRect(); + ASSERT_LT(0, videoRect->width()); + WebFloatPoint leftOfCenter(videoRect->left() + (videoRect->width() / 2) - 5, + videoRect->top() + 10); + WebFloatPoint rightOfCenter(videoRect->left() + (videoRect->width() / 2) + 5, + videoRect->top() + 10); + + // Add a zoom factor and ensure that it's properly handled. + MediaControls().GetDocument().GetFrame()->SetPageZoomFactor(2); + + // Double-tapping left of center should shift the time backwards by 10 + // seconds. + GestureDoubleTapAt(leftOfCenter); + test::RunPendingTasks(); + EXPECT_EQ(20, MediaControls().MediaElement().currentTime()); + + // Double-tapping right of center should shift the time forwards by 10 + // seconds. + GestureDoubleTapAt(rightOfCenter); + test::RunPendingTasks(); + EXPECT_EQ(30, MediaControls().MediaElement().currentTime()); +} + } // namespace blink
diff --git a/third_party/blink/renderer/modules/modules_idl_files.gni b/third_party/blink/renderer/modules/modules_idl_files.gni index a7ea572f..f4373f5 100644 --- a/third_party/blink/renderer/modules/modules_idl_files.gni +++ b/third_party/blink/renderer/modules/modules_idl_files.gni
@@ -247,6 +247,7 @@ "peerconnection/rtc_rtp_receiver.idl", "peerconnection/rtc_rtp_sender.idl", "peerconnection/rtc_rtp_transceiver.idl", + "peerconnection/rtc_sctp_transport.idl", "peerconnection/rtc_session_description.idl", "peerconnection/rtc_stats_report.idl", "peerconnection/rtc_stats_response.idl", @@ -288,8 +289,6 @@ "sensor/relative_orientation_sensor.idl", "sensor/sensor.idl", "sensor/sensor_error_event.idl", - "serial/serial.idl", - "serial/serial_port.idl", "service_worker/client.idl", "service_worker/clients.idl", "service_worker/extendable_event.idl", @@ -482,6 +481,14 @@ ], "abspath") +if (!is_android) { + modules_idl_files += get_path_info([ + "serial/serial.idl", + "serial/serial_port.idl", + ], + "abspath") +} + if (support_webgl2_compute_context) { modules_idl_files += get_path_info([ "webgl/webgl2_compute_rendering_context.idl" ], "abspath") @@ -688,8 +695,6 @@ "sensor/sensor_error_event_init.idl", "sensor/sensor_options.idl", "sensor/spatial_sensor_options.idl", - "serial/serial_options.idl", - "serial/serial_port_request_options.idl", "service_worker/client_query_options.idl", "service_worker/extendable_event_init.idl", "service_worker/extendable_message_event_init.idl", @@ -757,6 +762,15 @@ ], "abspath") +if (!is_android) { + modules_dictionary_idl_files += + get_path_info([ + "serial/serial_options.idl", + "serial/serial_port_request_options.idl", + ], + "abspath") +} + # 'partial interface' or target (right side of) 'implements' modules_dependency_idl_files = get_path_info( @@ -841,8 +855,6 @@ "quota/worker_navigator_storage_quota.idl", "remoteplayback/html_media_element_remote_playback.idl", "screen_orientation/screen_screen_orientation.idl", - "serial/navigator_serial.idl", - "serial/worker_navigator_serial.idl", "service_worker/navigator_service_worker.idl", "speech/window_speech.idl", "speech/window_speech_synthesis.idl", @@ -863,6 +875,15 @@ ], "abspath") +if (!is_android) { + modules_dependency_idl_files += + get_path_info([ + "serial/navigator_serial.idl", + "serial/worker_navigator_serial.idl", + ], + "abspath") +} + if (support_webgl2_compute_context) { modules_dependency_idl_files += get_path_info( [
diff --git a/third_party/blink/renderer/modules/netinfo/network_information.cc b/third_party/blink/renderer/modules/netinfo/network_information.cc index da587a1d..fe7ed24 100644 --- a/third_party/blink/renderer/modules/netinfo/network_information.cc +++ b/third_party/blink/renderer/modules/netinfo/network_information.cc
@@ -122,7 +122,7 @@ return NetworkStateNotifier::EffectiveConnectionTypeToString(effective_type_); } -unsigned long NetworkInformation::rtt() { +uint32_t NetworkInformation::rtt() { MaybeShowWebHoldbackConsoleMsg(); base::Optional<TimeDelta> override_rtt = GetNetworkStateNotifier().GetWebHoldbackHttpRtt(); @@ -173,7 +173,7 @@ DCHECK(GetExecutionContext()->IsContextThread()); const String host = Host(); - unsigned long new_http_rtt_msec = + uint32_t new_http_rtt_msec = GetNetworkStateNotifier().RoundRtt(host, http_rtt); double new_downlink_mbps = GetNetworkStateNotifier().RoundMbps(host, downlink_mbps);
diff --git a/third_party/blink/renderer/modules/netinfo/network_information.h b/third_party/blink/renderer/modules/netinfo/network_information.h index 590ebb1c..6d53d4f 100644 --- a/third_party/blink/renderer/modules/netinfo/network_information.h +++ b/third_party/blink/renderer/modules/netinfo/network_information.h
@@ -35,7 +35,7 @@ String type() const; double downlinkMax() const; String effectiveType(); - unsigned long rtt(); + uint32_t rtt(); double downlink(); bool saveData() const; @@ -95,7 +95,7 @@ // HTTP RTT estimate. Rounded off to the nearest 25 msec. Touched only on // context thread. - unsigned long http_rtt_msec_; + uint32_t http_rtt_msec_; // Downlink throughput estimate. Rounded off to the nearest 25 kbps. Touched // only on context thread.
diff --git a/third_party/blink/renderer/modules/netinfo/testing/internals_net_info.cc b/third_party/blink/renderer/modules/netinfo/testing/internals_net_info.cc index 448d8e8..df7f64f 100644 --- a/third_party/blink/renderer/modules/netinfo/testing/internals_net_info.cc +++ b/third_party/blink/renderer/modules/netinfo/testing/internals_net_info.cc
@@ -19,7 +19,7 @@ bool on_line, const String& type, const String& effective_type, - unsigned long http_rtt_msec, + uint32_t http_rtt_msec, double downlink_max_mbps, ExceptionState& exception_state) { WebConnectionType webtype;
diff --git a/third_party/blink/renderer/modules/netinfo/testing/internals_net_info.h b/third_party/blink/renderer/modules/netinfo/testing/internals_net_info.h index 1937e61..5e51c99c 100644 --- a/third_party/blink/renderer/modules/netinfo/testing/internals_net_info.h +++ b/third_party/blink/renderer/modules/netinfo/testing/internals_net_info.h
@@ -20,7 +20,7 @@ bool on_line, const String& type, const String& effective_type, - unsigned long http_rtt_msec, + uint32_t http_rtt_msec, double downlink_max_mbps, ExceptionState& exception_state); static void setSaveDataEnabled(Internals&, bool enabled);
diff --git a/third_party/blink/renderer/modules/notifications/notification_image_loader.cc b/third_party/blink/renderer/modules/notifications/notification_image_loader.cc index 3b4dec59..65f6fd9 100644 --- a/third_party/blink/renderer/modules/notifications/notification_image_loader.cc +++ b/third_party/blink/renderer/modules/notifications/notification_image_loader.cc
@@ -42,7 +42,7 @@ namespace { // 99.9% of all images were fetched successfully in 90 seconds. -const unsigned long kImageFetchTimeoutInMs = 90000; +const uint32_t kImageFetchTimeoutInMs = 90000; } // namespace @@ -141,8 +141,7 @@ data_->Append(data, length); } -void NotificationImageLoader::DidFinishLoading( - unsigned long resource_identifier) { +void NotificationImageLoader::DidFinishLoading(uint64_t resource_identifier) { // If this has been stopped it is not desirable to trigger further work, // there is a shutdown of some sort in progress. if (stopped_)
diff --git a/third_party/blink/renderer/modules/notifications/notification_image_loader.h b/third_party/blink/renderer/modules/notifications/notification_image_loader.h index 1971cb6..e29a9e2 100644 --- a/third_party/blink/renderer/modules/notifications/notification_image_loader.h +++ b/third_party/blink/renderer/modules/notifications/notification_image_loader.h
@@ -57,7 +57,7 @@ // ThreadableLoaderClient interface. void DidReceiveData(const char* data, unsigned length) override; - void DidFinishLoading(unsigned long resource_identifier) override; + void DidFinishLoading(uint64_t resource_identifier) override; void DidFail(const ResourceError& error) override; void DidFailRedirectCheck() override;
diff --git a/third_party/blink/renderer/modules/notifications/notification_image_loader_test.cc b/third_party/blink/renderer/modules/notifications/notification_image_loader_test.cc index 8100242c..7e5d5d4 100644 --- a/third_party/blink/renderer/modules/notifications/notification_image_loader_test.cc +++ b/third_party/blink/renderer/modules/notifications/notification_image_loader_test.cc
@@ -27,7 +27,7 @@ constexpr char kNotificationImageLoaderIcon500x500[] = "500x500.png"; // This mirrors the definition in NotificationImageLoader.cpp. -constexpr unsigned long kImageFetchTimeoutInMs = 90000; +constexpr uint32_t kImageFetchTimeoutInMs = 90000; static_assert(kImageFetchTimeoutInMs > 1000.0, "kImageFetchTimeoutInMs must be greater than 1000ms.");
diff --git a/third_party/blink/renderer/modules/peerconnection/BUILD.gn b/third_party/blink/renderer/modules/peerconnection/BUILD.gn index b4150fc..066dfcb 100644 --- a/third_party/blink/renderer/modules/peerconnection/BUILD.gn +++ b/third_party/blink/renderer/modules/peerconnection/BUILD.gn
@@ -41,6 +41,8 @@ "adapters/quic_transport_host.h", "adapters/quic_transport_proxy.cc", "adapters/quic_transport_proxy.h", + "adapters/sctp_transport_proxy.cc", + "adapters/sctp_transport_proxy.h", "adapters/web_rtc_cross_thread_copier.cc", "adapters/web_rtc_cross_thread_copier.h", "byte_buffer_queue.cc", @@ -89,6 +91,8 @@ "rtc_rtp_sender.h", "rtc_rtp_transceiver.cc", "rtc_rtp_transceiver.h", + "rtc_sctp_transport.cc", + "rtc_sctp_transport.h", "rtc_session_description.cc", "rtc_session_description.h", "rtc_session_description_enums.h",
diff --git a/third_party/blink/renderer/modules/peerconnection/adapters/ice_transport_proxy.cc b/third_party/blink/renderer/modules/peerconnection/adapters/ice_transport_proxy.cc index d58b5da..80ea675 100644 --- a/third_party/blink/renderer/modules/peerconnection/adapters/ice_transport_proxy.cc +++ b/third_party/blink/renderer/modules/peerconnection/adapters/ice_transport_proxy.cc
@@ -24,7 +24,8 @@ delegate_(delegate), feature_handle_for_scheduler_(frame.GetFrameScheduler()->RegisterFeature( SchedulingPolicy::Feature::kWebRTC, - {SchedulingPolicy::DisableAggressiveThrottling()})), + {SchedulingPolicy::DisableAggressiveThrottling(), + SchedulingPolicy::DisableBackForwardCache()})), weak_ptr_factory_(this) { DCHECK(host_thread_); DCHECK(delegate_);
diff --git a/third_party/blink/renderer/modules/peerconnection/adapters/sctp_transport_proxy.cc b/third_party/blink/renderer/modules/peerconnection/adapters/sctp_transport_proxy.cc new file mode 100644 index 0000000..a9bfffe --- /dev/null +++ b/third_party/blink/renderer/modules/peerconnection/adapters/sctp_transport_proxy.cc
@@ -0,0 +1,72 @@ +// 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 "third_party/blink/renderer/modules/peerconnection/adapters/sctp_transport_proxy.h" + +#include <memory> +#include <utility> + +#include "base/location.h" +#include "third_party/blink/renderer/core/frame/local_frame.h" +#include "third_party/blink/renderer/modules/peerconnection/adapters/web_rtc_cross_thread_copier.h" +#include "third_party/blink/renderer/platform/cross_thread_functional.h" +#include "third_party/blink/renderer/platform/scheduler/public/post_cross_thread_task.h" + +namespace blink { + +// static +std::unique_ptr<SctpTransportProxy> SctpTransportProxy::Create( + LocalFrame& frame, + scoped_refptr<base::SingleThreadTaskRunner> proxy_thread, + scoped_refptr<base::SingleThreadTaskRunner> host_thread, + rtc::scoped_refptr<webrtc::SctpTransportInterface> sctp_transport, + Delegate* delegate) { + DCHECK(proxy_thread->BelongsToCurrentThread()); + std::unique_ptr<SctpTransportProxy> proxy = + base::WrapUnique(new SctpTransportProxy(frame, proxy_thread, host_thread, + sctp_transport, delegate)); + PostCrossThreadTask(*host_thread, FROM_HERE, + CrossThreadBind(&SctpTransportProxy::StartOnHostThread, + CrossThreadUnretained(proxy.get()))); + return proxy; +} + +SctpTransportProxy::SctpTransportProxy( + LocalFrame& frame, + scoped_refptr<base::SingleThreadTaskRunner> proxy_thread, + scoped_refptr<base::SingleThreadTaskRunner> host_thread, + rtc::scoped_refptr<webrtc::SctpTransportInterface> sctp_transport, + Delegate* delegate) + : proxy_thread_(std::move(proxy_thread)), + host_thread_(std::move(host_thread)), + sctp_transport_(std::move(sctp_transport)), + delegate_(delegate) {} + +void SctpTransportProxy::StartOnHostThread() { + DCHECK(host_thread_->BelongsToCurrentThread()); + sctp_transport_->RegisterObserver(this); + PostCrossThreadTask(*proxy_thread_, FROM_HERE, + CrossThreadBind(&Delegate::OnStartCompleted, delegate_, + sctp_transport_->Information())); +} + +void SctpTransportProxy::OnStateChange(webrtc::SctpTransportInformation info) { + DCHECK(host_thread_->BelongsToCurrentThread()); + DCHECK(delegate_); + // Closed is the last state that can happen, so unregister when we see this. + // Unregistering allows us to safely delete the proxy independent of the + // state of the webrtc::SctpTransport. + if (info.state() == webrtc::SctpTransportState::kClosed) { + sctp_transport_->UnregisterObserver(); + } + PostCrossThreadTask( + *proxy_thread_, FROM_HERE, + CrossThreadBind(&Delegate::OnStateChange, delegate_, info)); + if (info.state() == webrtc::SctpTransportState::kClosed) { + // Don't hold on to |delegate| any more. + delegate_ = nullptr; + } +} + +} // namespace blink
diff --git a/third_party/blink/renderer/modules/peerconnection/adapters/sctp_transport_proxy.h b/third_party/blink/renderer/modules/peerconnection/adapters/sctp_transport_proxy.h new file mode 100644 index 0000000..30d657b --- /dev/null +++ b/third_party/blink/renderer/modules/peerconnection/adapters/sctp_transport_proxy.h
@@ -0,0 +1,83 @@ +// 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 THIRD_PARTY_BLINK_RENDERER_MODULES_PEERCONNECTION_ADAPTERS_SCTP_TRANSPORT_PROXY_H_ +#define THIRD_PARTY_BLINK_RENDERER_MODULES_PEERCONNECTION_ADAPTERS_SCTP_TRANSPORT_PROXY_H_ + +#include <memory> + +#include "base/memory/scoped_refptr.h" +#include "base/single_thread_task_runner.h" +#include "third_party/blink/renderer/platform/heap/persistent.h" +#include "third_party/webrtc/api/sctp_transport_interface.h" + +// The SctpTransportProxy class takes care of thread-jumping when +// connecting callbacks from a webrtc::SctpTransport to a +// blink::RTCSctpTransport object. + +// Its design is modeled on the IceTransportProxy design, +// but does not use so many layers of indirection - there is +// no control, and all information is passed via callbacks on the Delegate. + +// The proxy thread = the Blink main thread +// The host thread = the webrtc signalling thread (the one that gets callbacks) + +namespace blink { + +class LocalFrame; + +class SctpTransportProxy : public webrtc::SctpTransportObserverInterface { + public: + // Delegate class for actions caused by the Proxy, but executed on the + // main thread. The Delegate must remain alive until it has observed + // the kClosed state, which is the last thing that can happen. + class Delegate : public blink::GarbageCollectedMixin { + public: + virtual ~Delegate() = default; + + // Called when the Create() function is complete. Sends current state, + // but does not indicate a state change. + virtual void OnStartCompleted(webrtc::SctpTransportInformation info) = 0; + // Called when a state change is signalled from transport. + virtual void OnStateChange(webrtc::SctpTransportInformation info) = 0; + void Trace(blink::Visitor* visitor) override {} + }; + + // Constructs a SctpTransportProxy. The caller is responsible for keeping + // |sctp_transport| alive until after the SctpTransportProxy is deleted. + // The SctpTransportProxy takes a <CrossThreadPersistent> reference to the + // Delegate, preventing it from being garbage collected until the |kClosed| + // state is reached. + // The SctpTransportProxy can only be safely deleted after seeing the state + // |kClosed|, since this is the last event that can happen on the transport. + static std::unique_ptr<SctpTransportProxy> Create( + LocalFrame& frame, + scoped_refptr<base::SingleThreadTaskRunner> proxy_thread, + scoped_refptr<base::SingleThreadTaskRunner> host_thread, + rtc::scoped_refptr<webrtc::SctpTransportInterface> sctp_transport, + Delegate* delegate); + + ~SctpTransportProxy() override {} + + private: + SctpTransportProxy( + LocalFrame& frame, + scoped_refptr<base::SingleThreadTaskRunner> proxy_thread, + scoped_refptr<base::SingleThreadTaskRunner> host_thread, + rtc::scoped_refptr<webrtc::SctpTransportInterface> sctp_transport, + Delegate* delegate); + // Implementation of webrtc::SctpTransportObserver + void OnStateChange(webrtc::SctpTransportInformation info) override; + + // Internal helper for Create() + void StartOnHostThread(); + + const scoped_refptr<base::SingleThreadTaskRunner> proxy_thread_; + const scoped_refptr<base::SingleThreadTaskRunner> host_thread_; + const rtc::scoped_refptr<webrtc::SctpTransportInterface> sctp_transport_; + CrossThreadPersistent<Delegate> delegate_; +}; + +} // namespace blink + +#endif // THIRD_PARTY_BLINK_RENDERER_MODULES_PEERCONNECTION_ADAPTERS_SCTP_TRANSPORT_PROXY_H_
diff --git a/third_party/blink/renderer/modules/peerconnection/adapters/web_rtc_cross_thread_copier.h b/third_party/blink/renderer/modules/peerconnection/adapters/web_rtc_cross_thread_copier.h index caf51a8..8cf5f92 100644 --- a/third_party/blink/renderer/modules/peerconnection/adapters/web_rtc_cross_thread_copier.h +++ b/third_party/blink/renderer/modules/peerconnection/adapters/web_rtc_cross_thread_copier.h
@@ -29,6 +29,7 @@ namespace webrtc { class DtlsTransportInformation; +class SctpTransportInformation; } namespace blink { @@ -106,6 +107,12 @@ }; template <> +struct CrossThreadCopier<webrtc::SctpTransportInformation> + : public CrossThreadCopierPassThrough<webrtc::SctpTransportInformation> { + STATIC_ONLY(CrossThreadCopier); +}; + +template <> struct CrossThreadCopier<P2PQuicTransport::StartConfig> : public CrossThreadCopierPassThrough<P2PQuicTransport::StartConfig> { STATIC_ONLY(CrossThreadCopier);
diff --git a/third_party/blink/renderer/modules/peerconnection/rtc_dtls_transport.cc b/third_party/blink/renderer/modules/peerconnection/rtc_dtls_transport.cc index 4a329d75..1b7716d 100644 --- a/third_party/blink/renderer/modules/peerconnection/rtc_dtls_transport.cc +++ b/third_party/blink/renderer/modules/peerconnection/rtc_dtls_transport.cc
@@ -11,23 +11,11 @@ #include "third_party/blink/renderer/core/frame/local_frame.h" #include "third_party/blink/renderer/core/typed_arrays/dom_array_buffer.h" #include "third_party/blink/renderer/modules/peerconnection/adapters/dtls_transport_proxy.h" -#include "third_party/blink/renderer/modules/peerconnection/adapters/ice_transport_adapter_cross_thread_factory.h" -#include "third_party/blink/renderer/modules/peerconnection/adapters/ice_transport_adapter_impl.h" #include "third_party/blink/renderer/modules/peerconnection/rtc_error_util.h" -#include "third_party/blink/renderer/modules/peerconnection/rtc_ice_candidate.h" -#include "third_party/blink/renderer/modules/peerconnection/rtc_ice_gather_options.h" #include "third_party/blink/renderer/modules/peerconnection/rtc_ice_transport.h" -#include "third_party/blink/renderer/modules/peerconnection/rtc_peer_connection_ice_event.h" -#include "third_party/blink/renderer/modules/peerconnection/rtc_peer_connection_ice_event_init.h" -#include "third_party/blink/renderer/modules/peerconnection/rtc_quic_transport.h" #include "third_party/blink/renderer/platform/scheduler/public/thread.h" #include "third_party/webrtc/api/dtls_transport_interface.h" -#include "third_party/webrtc/api/jsep_ice_candidate.h" #include "third_party/webrtc/api/peer_connection_interface.h" -#include "third_party/webrtc/p2p/base/port_allocator.h" -#include "third_party/webrtc/p2p/base/transport_description.h" -#include "third_party/webrtc/pc/ice_server_parsing.h" -#include "third_party/webrtc/pc/webrtc_sdp.h" namespace blink {
diff --git a/third_party/blink/renderer/modules/peerconnection/rtc_ice_transport_test.h b/third_party/blink/renderer/modules/peerconnection/rtc_ice_transport_test.h index 6a84ee5..be17c4d 100644 --- a/third_party/blink/renderer/modules/peerconnection/rtc_ice_transport_test.h +++ b/third_party/blink/renderer/modules/peerconnection/rtc_ice_transport_test.h
@@ -51,7 +51,7 @@ // letting it pass. MockEventListener* CreateMockEventListener(); - private: + protected: scoped_refptr<base::TestSimpleTaskRunner> main_thread_; scoped_refptr<base::TestSimpleTaskRunner> worker_thread_; std::vector<Persistent<MockEventListener>> mock_event_listeners_;
diff --git a/third_party/blink/renderer/modules/peerconnection/rtc_peer_connection.cc b/third_party/blink/renderer/modules/peerconnection/rtc_peer_connection.cc index 2d20e09e..e8302f9 100644 --- a/third_party/blink/renderer/modules/peerconnection/rtc_peer_connection.cc +++ b/third_party/blink/renderer/modules/peerconnection/rtc_peer_connection.cc
@@ -97,6 +97,7 @@ #include "third_party/blink/renderer/modules/peerconnection/rtc_rtp_sender.h" #include "third_party/blink/renderer/modules/peerconnection/rtc_rtp_transceiver.h" #include "third_party/blink/renderer/modules/peerconnection/rtc_rtp_transceiver_init.h" +#include "third_party/blink/renderer/modules/peerconnection/rtc_sctp_transport.h" #include "third_party/blink/renderer/modules/peerconnection/rtc_session_description.h" #include "third_party/blink/renderer/modules/peerconnection/rtc_session_description_init.h" #include "third_party/blink/renderer/modules/peerconnection/rtc_session_description_request_impl.h" @@ -781,7 +782,8 @@ feature_handle_for_scheduler_ = document->GetFrame()->GetFrameScheduler()->RegisterFeature( SchedulingPolicy::Feature::kWebRTC, - {SchedulingPolicy::DisableAggressiveThrottling()}); + {SchedulingPolicy::DisableAggressiveThrottling(), + SchedulingPolicy::DisableBackForwardCache()}); } RTCPeerConnection::~RTCPeerConnection() { @@ -2220,6 +2222,10 @@ } } +RTCSctpTransport* RTCPeerConnection::sctp() const { + return sctp_transport_; +} + RTCDataChannel* RTCPeerConnection::createDataChannel( ScriptState* script_state, String label, @@ -2690,6 +2696,27 @@ MediaStreamSource::kReadyStateMuted); } +void RTCPeerConnection::DidModifySctpTransport( + WebRTCSctpTransportSnapshot snapshot) { + if (!snapshot.transport) { + sctp_transport_ = nullptr; + return; + } + if (!sctp_transport_ || + sctp_transport_->native_transport() != snapshot.transport) { + sctp_transport_ = MakeGarbageCollected<RTCSctpTransport>( + GetExecutionContext(), snapshot.transport); + sctp_transport_->ChangeState(snapshot.sctp_transport_state); + } + if (!sctp_transport_->transport() || + sctp_transport_->transport()->native_transport() != + snapshot.sctp_transport_state.dtls_transport()) { + sctp_transport_->SetTransport(CreateOrUpdateDtlsTransport( + snapshot.sctp_transport_state.dtls_transport(), + snapshot.dtls_transport_state)); + } +} + void RTCPeerConnection::DidModifyTransceivers( std::vector<std::unique_ptr<WebRTCRtpTransceiver>> web_transceivers, bool is_remote_description) { @@ -3000,6 +3027,9 @@ for (auto& transceiver : transceivers_) { transceiver->OnPeerConnectionClosed(); } + if (sctp_transport_) { + sctp_transport_->Close(); + } Document* document = To<Document>(GetExecutionContext()); HostsUsingFeatures::CountAnyWorld( @@ -3077,6 +3107,7 @@ visitor->Trace(scheduled_events_); visitor->Trace(dtls_transports_by_native_transport_); visitor->Trace(ice_transports_by_native_transport_); + visitor->Trace(sctp_transport_); EventTargetWithInlineData::Trace(visitor); ContextLifecycleObserver::Trace(visitor); MediaStreamObserver::Trace(visitor);
diff --git a/third_party/blink/renderer/modules/peerconnection/rtc_peer_connection.h b/third_party/blink/renderer/modules/peerconnection/rtc_peer_connection.h index 2cd4164..0a49d21c 100644 --- a/third_party/blink/renderer/modules/peerconnection/rtc_peer_connection.h +++ b/third_party/blink/renderer/modules/peerconnection/rtc_peer_connection.h
@@ -73,6 +73,7 @@ class RTCRtpReceiver; class RTCRtpSender; class RTCRtpTransceiverInit; +class RTCSctpTransport; class RTCSessionDescription; class RTCSessionDescriptionInit; class ScriptState; @@ -227,6 +228,7 @@ void removeTrack(RTCRtpSender*, ExceptionState&); DEFINE_ATTRIBUTE_EVENT_LISTENER(track, kTrack) + RTCSctpTransport* sctp() const; RTCDataChannel* createDataChannel(ScriptState*, String label, const RTCDataChannelInit*, @@ -286,6 +288,7 @@ webrtc::PeerConnectionInterface::PeerConnectionState) override; void DidAddReceiverPlanB(std::unique_ptr<WebRTCRtpReceiver>) override; void DidRemoveReceiverPlanB(std::unique_ptr<WebRTCRtpReceiver>) override; + void DidModifySctpTransport(WebRTCSctpTransportSnapshot) override; void DidModifyTransceivers(std::vector<std::unique_ptr<WebRTCRtpTransceiver>>, bool is_remote_description) override; void DidAddRemoteDataChannel( @@ -519,6 +522,7 @@ String last_offer_; String last_answer_; + Member<RTCSctpTransport> sctp_transport_; bool has_data_channels_; // For RAPPOR metrics // In Plan B, senders and receivers are added or removed independently of one // another. In Unified Plan, senders and receivers are created in pairs as
diff --git a/third_party/blink/renderer/modules/peerconnection/rtc_peer_connection.idl b/third_party/blink/renderer/modules/peerconnection/rtc_peer_connection.idl index a95aa30e..2875bebc 100644 --- a/third_party/blink/renderer/modules/peerconnection/rtc_peer_connection.idl +++ b/third_party/blink/renderer/modules/peerconnection/rtc_peer_connection.idl
@@ -155,6 +155,7 @@ attribute EventHandler ontrack; // https://w3c.github.io/webrtc-pc/#peer-to-peer-data-api + [RuntimeEnabled=RTCSctpTransport] readonly attribute RTCSctpTransport? sctp; [CallWith=ScriptState, RaisesException] RTCDataChannel createDataChannel(USVString label, optional RTCDataChannelInit dataChannelDict); attribute EventHandler ondatachannel;
diff --git a/third_party/blink/renderer/modules/peerconnection/rtc_sctp_transport.cc b/third_party/blink/renderer/modules/peerconnection/rtc_sctp_transport.cc new file mode 100644 index 0000000..017b59c --- /dev/null +++ b/third_party/blink/renderer/modules/peerconnection/rtc_sctp_transport.cc
@@ -0,0 +1,175 @@ +// 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 "third_party/blink/renderer/modules/peerconnection/rtc_sctp_transport.h" + +#include <limits> +#include <memory> + +#include "third_party/blink/public/platform/platform.h" +#include "third_party/blink/public/web/web_local_frame.h" +#include "third_party/blink/renderer/core/dom/document.h" +#include "third_party/blink/renderer/core/dom/events/event.h" +#include "third_party/blink/renderer/core/frame/local_frame.h" +#include "third_party/blink/renderer/core/typed_arrays/dom_array_buffer.h" +#include "third_party/blink/renderer/modules/peerconnection/adapters/sctp_transport_proxy.h" +#include "third_party/blink/renderer/modules/peerconnection/rtc_dtls_transport.h" +#include "third_party/blink/renderer/modules/peerconnection/rtc_error_util.h" +#include "third_party/blink/renderer/platform/scheduler/public/thread.h" +#include "third_party/webrtc/api/peer_connection_interface.h" +#include "third_party/webrtc/api/sctp_transport_interface.h" + +namespace blink { + +namespace { +String TransportStateToString(webrtc::SctpTransportState state) { + switch (state) { + case webrtc::SctpTransportState::kNew: + // Not supposed to happen. DtlsTransport should + // only be visible after reaching "connecting" state. + NOTREACHED(); + return String("new"); + break; + case webrtc::SctpTransportState::kConnecting: + return String("connecting"); + break; + case webrtc::SctpTransportState::kConnected: + return String("connected"); + break; + case webrtc::SctpTransportState::kClosed: + return String("closed"); + break; + default: + NOTREACHED(); + return String("failed"); + break; + } +} + +std::unique_ptr<SctpTransportProxy> CreateProxy( + ExecutionContext* context, + webrtc::SctpTransportInterface* native_transport, + SctpTransportProxy::Delegate* delegate, + scoped_refptr<base::SingleThreadTaskRunner> main_thread, + scoped_refptr<base::SingleThreadTaskRunner> worker_thread) { + DCHECK(main_thread); + DCHECK(worker_thread); + LocalFrame* frame = To<Document>(context)->GetFrame(); + DCHECK(frame); + return SctpTransportProxy::Create(*frame, main_thread, worker_thread, + native_transport, delegate); +} + +} // namespace + +RTCSctpTransport::RTCSctpTransport( + ExecutionContext* context, + rtc::scoped_refptr<webrtc::SctpTransportInterface> native_transport) + : RTCSctpTransport(context, + native_transport, + To<Document>(context)->GetFrame()->GetTaskRunner( + TaskType::kNetworking), + Platform::Current()->GetWebRtcWorkerThread()) {} + +RTCSctpTransport::RTCSctpTransport( + ExecutionContext* context, + rtc::scoped_refptr<webrtc::SctpTransportInterface> native_transport, + scoped_refptr<base::SingleThreadTaskRunner> main_thread, + scoped_refptr<base::SingleThreadTaskRunner> worker_thread) + : ContextClient(context), + current_state_(webrtc::SctpTransportState::kNew), + native_transport_(native_transport), + proxy_(CreateProxy(context, + native_transport, + this, + main_thread, + worker_thread)) {} + +RTCSctpTransport::~RTCSctpTransport() {} + +String RTCSctpTransport::state() const { + if (closed_from_owner_) { + return TransportStateToString(webrtc::SctpTransportState::kClosed); + } + return TransportStateToString(current_state_.state()); +} + +double RTCSctpTransport::maxMessageSize() const { + if (current_state_.MaxMessageSize()) { + return *current_state_.MaxMessageSize(); + } + // Spec says: + // If local size is unlimited and remote side is unknown, return infinity. + // http://w3c.github.io/webrtc-pc/#dfn-update-the-data-max-message-size + return std::numeric_limits<double>::infinity(); +} + +int16_t RTCSctpTransport::maxChannels(bool& isNull) const { + if (!current_state_.MaxChannels()) { + isNull = true; + return 0; + } + isNull = false; + return *current_state_.MaxChannels(); +} + +RTCDtlsTransport* RTCSctpTransport::transport() const { + return dtls_transport_; +} + +rtc::scoped_refptr<webrtc::SctpTransportInterface> +RTCSctpTransport::native_transport() { + return native_transport_; +} + +void RTCSctpTransport::ChangeState(webrtc::SctpTransportInformation info) { + DCHECK(current_state_.state() != webrtc::SctpTransportState::kClosed); + current_state_ = info; +} + +void RTCSctpTransport::SetTransport(RTCDtlsTransport* transport) { + dtls_transport_ = transport; +} + +// Implementation of SctpTransportProxy::Delegate +void RTCSctpTransport::OnStartCompleted(webrtc::SctpTransportInformation info) { + current_state_ = info; + start_completed_ = true; +} + +void RTCSctpTransport::OnStateChange(webrtc::SctpTransportInformation info) { + // We depend on closed only happening once for safe garbage collection. + DCHECK(current_state_.state() != webrtc::SctpTransportState::kClosed); + current_state_ = info; + // When Close() has been called, we do not report the state change from the + // lower layer, but we keep the SctpTransport object alive until the + // lower layer has sent notice that the closing has been completed. + if (!closed_from_owner_) { + DispatchEvent(*Event::Create(event_type_names::kStatechange)); + } +} + +void RTCSctpTransport::Close() { + closed_from_owner_ = true; + if (current_state_.state() != webrtc::SctpTransportState::kClosed) { + DispatchEvent(*Event::Create(event_type_names::kStatechange)); + } +} + +const AtomicString& RTCSctpTransport::InterfaceName() const { + return event_target_names::kRTCSctpTransport; +} + +ExecutionContext* RTCSctpTransport::GetExecutionContext() const { + return ContextClient::GetExecutionContext(); +} + +void RTCSctpTransport::Trace(Visitor* visitor) { + visitor->Trace(dtls_transport_); + EventTargetWithInlineData::Trace(visitor); + ContextClient::Trace(visitor); + SctpTransportProxy::Delegate::Trace(visitor); +} + +} // namespace blink
diff --git a/third_party/blink/renderer/modules/peerconnection/rtc_sctp_transport.h b/third_party/blink/renderer/modules/peerconnection/rtc_sctp_transport.h new file mode 100644 index 0000000..2ecee06 --- /dev/null +++ b/third_party/blink/renderer/modules/peerconnection/rtc_sctp_transport.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 THIRD_PARTY_BLINK_RENDERER_MODULES_PEERCONNECTION_RTC_SCTP_TRANSPORT_H_ +#define THIRD_PARTY_BLINK_RENDERER_MODULES_PEERCONNECTION_RTC_SCTP_TRANSPORT_H_ + +#include <memory> + +#include "third_party/blink/renderer/bindings/core/v8/active_script_wrappable.h" +#include "third_party/blink/renderer/core/execution_context/context_lifecycle_observer.h" +#include "third_party/blink/renderer/modules/event_target_modules.h" +#include "third_party/blink/renderer/modules/peerconnection/adapters/sctp_transport_proxy.h" +#include "third_party/webrtc/api/scoped_refptr.h" +#include "third_party/webrtc/api/sctp_transport_interface.h" + +namespace blink { + +class SctpTransportProxy; +class RTCDtlsTransport; + +enum class RTCSctpTransportState { kChecking, kConnected, kClosed }; + +// Blink bindings for the RTCSctpTransport JavaScript object. +class MODULES_EXPORT RTCSctpTransport final + : public EventTargetWithInlineData, + public ContextClient, + public SctpTransportProxy::Delegate { + DEFINE_WRAPPERTYPEINFO(); + USING_GARBAGE_COLLECTED_MIXIN(RTCSctpTransport); + + public: + RTCSctpTransport( + ExecutionContext* context, + rtc::scoped_refptr<webrtc::SctpTransportInterface> native_transport); + // Constructor with explicit thread injection, used for testing. + RTCSctpTransport( + ExecutionContext* context, + rtc::scoped_refptr<webrtc::SctpTransportInterface> native_transport, + scoped_refptr<base::SingleThreadTaskRunner> main_thread, + scoped_refptr<base::SingleThreadTaskRunner> worker_thread); + ~RTCSctpTransport() override; + + // rtc_sctp_transport.idl + RTCDtlsTransport* transport() const; + String state() const; + double maxMessageSize() const; + int16_t maxChannels(bool& is_null) const; + + DEFINE_ATTRIBUTE_EVENT_LISTENER(statechange, kStatechange) + + // SctpTransportProxy::Delegate + void OnStartCompleted(webrtc::SctpTransportInformation info) override; + void OnStateChange(webrtc::SctpTransportInformation info) override; + + // EventTarget overrides. + const AtomicString& InterfaceName() const override; + ExecutionContext* GetExecutionContext() const override; + // Others + void ChangeState(webrtc::SctpTransportInformation info); + void SetTransport(RTCDtlsTransport*); + rtc::scoped_refptr<webrtc::SctpTransportInterface> native_transport(); + // Called from owning RtcPeerConnection when it is closed. + void Close(); + // For garbage collection. + void Trace(blink::Visitor* visitor) override; + + private: + webrtc::SctpTransportInformation current_state_; + rtc::scoped_refptr<webrtc::SctpTransportInterface> native_transport_; + std::unique_ptr<SctpTransportProxy> proxy_; + Member<RTCDtlsTransport> dtls_transport_; + bool start_completed_ = false; + bool closed_from_owner_ = false; +}; + +} // namespace blink +#endif // THIRD_PARTY_BLINK_RENDERER_MODULES_PEERCONNECTION_RTC_SCTP_TRANSPORT_H_
diff --git a/third_party/blink/renderer/modules/peerconnection/rtc_sctp_transport.idl b/third_party/blink/renderer/modules/peerconnection/rtc_sctp_transport.idl new file mode 100644 index 0000000..f99a289 --- /dev/null +++ b/third_party/blink/renderer/modules/peerconnection/rtc_sctp_transport.idl
@@ -0,0 +1,23 @@ +// Copyright 2018 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +// http://w3c.github.io/webrtc-pc/#dom-rtcsctptransportstate +enum RTCSctpTransportState { + "connecting", + "connected", + "closed" +}; + +// http://w3c.github.io/webrtc-pc/#rtcdtlstransport-interface + +[ + Exposed=Window, + RuntimeEnabled=RTCSctpTransport +] interface RTCSctpTransport { + readonly attribute RTCDtlsTransport transport; + readonly attribute RTCSctpTransportState state; + readonly attribute unrestricted double maxMessageSize; + readonly attribute unsigned short? maxChannels; + attribute EventHandler onstatechange; +};
diff --git a/third_party/blink/renderer/modules/peerconnection/rtc_sctp_transport_test.cc b/third_party/blink/renderer/modules/peerconnection/rtc_sctp_transport_test.cc new file mode 100644 index 0000000..d75aebb3 --- /dev/null +++ b/third_party/blink/renderer/modules/peerconnection/rtc_sctp_transport_test.cc
@@ -0,0 +1,76 @@ +// 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 "third_party/blink/renderer/modules/peerconnection/rtc_sctp_transport.h" + +#include "testing/gmock/include/gmock/gmock.h" +#include "testing/gtest/include/gtest/gtest.h" +#include "third_party/blink/public/web/web_heap.h" +#include "third_party/blink/renderer/bindings/core/v8/v8_binding_for_testing.h" +#include "third_party/blink/renderer/core/testing/null_execution_context.h" +#include "third_party/blink/renderer/modules/peerconnection/rtc_ice_transport_test.h" +#include "third_party/webrtc/api/sctp_transport_interface.h" +#include "third_party/webrtc/rtc_base/ref_counted_object.h" + +namespace blink { + +using testing::_; +using testing::Invoke; +using testing::NiceMock; +using testing::Return; + +class MockSctpTransport : public webrtc::SctpTransportInterface { + public: + MockSctpTransport() { + ON_CALL(*this, Information()).WillByDefault(Return(info_)); + ON_CALL(*this, RegisterObserver(_)) + .WillByDefault(Invoke(this, &MockSctpTransport::SetObserver)); + } + MOCK_CONST_METHOD0(dtls_transport, + rtc::scoped_refptr<webrtc::DtlsTransportInterface>()); + MOCK_CONST_METHOD0(Information, webrtc::SctpTransportInformation()); + MOCK_METHOD1(RegisterObserver, void(webrtc::SctpTransportObserverInterface*)); + MOCK_METHOD0(UnregisterObserver, void()); + + void SetObserver(webrtc::SctpTransportObserverInterface* observer) { + observer_ = observer; + } + + void SendClose() { + if (observer_) { + observer_->OnStateChange(webrtc::SctpTransportInformation( + webrtc::SctpTransportState::kClosed)); + } + } + + private: + webrtc::SctpTransportInformation info_ = + webrtc::SctpTransportInformation(webrtc::SctpTransportState::kNew); + webrtc::SctpTransportObserverInterface* observer_ = nullptr; +}; + +class RTCSctpTransportTest : public RTCIceTransportTest {}; + +TEST_F(RTCSctpTransportTest, CreateFromMocks) { + V8TestingScope scope; + + ExecutionContext* context = scope.GetExecutionContext(); + rtc::scoped_refptr<webrtc::SctpTransportInterface> mock_native_transport = + new rtc::RefCountedObject<NiceMock<MockSctpTransport>>(); + RTCSctpTransport* transport = MakeGarbageCollected<RTCSctpTransport>( + context, mock_native_transport, main_thread_, worker_thread_); + WeakPersistent<RTCSctpTransport> garbage_collection_observer = transport; + RunUntilIdle(); + transport = nullptr; + // An unclosed transport should not be garbage collected, since events + // might still trickle up. + ASSERT_TRUE(garbage_collection_observer); + // A closed transport should be garbage collected. + static_cast<MockSctpTransport*>(mock_native_transport.get())->SendClose(); + RunUntilIdle(); + WebHeap::CollectAllGarbageForTesting(); + EXPECT_FALSE(garbage_collection_observer); +} + +} // namespace blink
diff --git a/third_party/blink/renderer/modules/plugins/dom_plugin_array.cc b/third_party/blink/renderer/modules/plugins/dom_plugin_array.cc index 2f6f533b..5075f85c 100644 --- a/third_party/blink/renderer/modules/plugins/dom_plugin_array.cc +++ b/third_party/blink/renderer/modules/plugins/dom_plugin_array.cc
@@ -113,10 +113,8 @@ NavigatorPlugins::mimeTypes(navigator)->UpdatePluginData(); } - if (reload) { - GetFrame()->Reload(WebFrameLoadType::kReload, - ClientRedirectPolicy::kClientRedirect); - } + if (reload) + GetFrame()->Reload(WebFrameLoadType::kReload); } PluginData* DOMPluginArray::GetPluginData() const {
diff --git a/third_party/blink/renderer/modules/serial/BUILD.gn b/third_party/blink/renderer/modules/serial/BUILD.gn index f135be87..cf08466 100644 --- a/third_party/blink/renderer/modules/serial/BUILD.gn +++ b/third_party/blink/renderer/modules/serial/BUILD.gn
@@ -4,6 +4,10 @@ import("//third_party/blink/renderer/modules/modules.gni") +# The Serial API will not be supported on Android. Assert here to ensure it +# doesn't sneak back into the build. +assert(!is_android) + blink_modules_sources("serial") { sources = [ "navigator_serial.cc",
diff --git a/third_party/blink/renderer/modules/webaudio/audio_node.cc b/third_party/blink/renderer/modules/webaudio/audio_node.cc index a7a43e5..f54c330 100644 --- a/third_party/blink/renderer/modules/webaudio/audio_node.cc +++ b/third_party/blink/renderer/modules/webaudio/audio_node.cc
@@ -191,12 +191,13 @@ } void AudioHandler::AddInput() { - inputs_.push_back(AudioNodeInput::Create(*this)); + inputs_.push_back(std::make_unique<AudioNodeInput>(*this)); } void AudioHandler::AddOutput(unsigned number_of_channels) { DCHECK(IsMainThread()); - outputs_.push_back(AudioNodeOutput::Create(this, number_of_channels)); + outputs_.push_back( + std::make_unique<AudioNodeOutput>(this, number_of_channels)); GetNode()->DidAddOutput(NumberOfOutputs()); }
diff --git a/third_party/blink/renderer/modules/webaudio/audio_node_input.cc b/third_party/blink/renderer/modules/webaudio/audio_node_input.cc index 10ee03a..5af6a08d 100644 --- a/third_party/blink/renderer/modules/webaudio/audio_node_input.cc +++ b/third_party/blink/renderer/modules/webaudio/audio_node_input.cc
@@ -46,10 +46,6 @@ AudioNodeWiring::WillBeDestroyed(*this); } -std::unique_ptr<AudioNodeInput> AudioNodeInput::Create(AudioHandler& handler) { - return base::WrapUnique(new AudioNodeInput(handler)); -} - void AudioNodeInput::DidUpdate() { Handler().CheckNumberOfChannelsForInput(this); }
diff --git a/third_party/blink/renderer/modules/webaudio/audio_node_input.h b/third_party/blink/renderer/modules/webaudio/audio_node_input.h index 3245e4d..51db7a1b 100644 --- a/third_party/blink/renderer/modules/webaudio/audio_node_input.h +++ b/third_party/blink/renderer/modules/webaudio/audio_node_input.h
@@ -50,7 +50,7 @@ USING_FAST_MALLOC(AudioNodeInput); public: - static std::unique_ptr<AudioNodeInput> Create(AudioHandler&); + explicit AudioNodeInput(AudioHandler&); ~AudioNodeInput() override; // AudioSummingJunction @@ -82,8 +82,6 @@ unsigned NumberOfChannels() const; private: - explicit AudioNodeInput(AudioHandler&); - // This reference is safe because the AudioHandler owns this AudioNodeInput // object. AudioHandler& handler_;
diff --git a/third_party/blink/renderer/modules/webaudio/audio_node_input_test.cc b/third_party/blink/renderer/modules/webaudio/audio_node_input_test.cc index 3d00fb4..72c99cb 100644 --- a/third_party/blink/renderer/modules/webaudio/audio_node_input_test.cc +++ b/third_party/blink/renderer/modules/webaudio/audio_node_input_test.cc
@@ -24,8 +24,8 @@ DelayNode* node2 = context->createDelay(ASSERT_NO_EXCEPTION); auto& handler2 = node2->Handler(); - auto input = AudioNodeInput::Create(handler1); - auto output = AudioNodeOutput::Create(&handler2, 0); + auto input = std::make_unique<AudioNodeInput>(handler1); + auto output = std::make_unique<AudioNodeOutput>(&handler2, 0); { BaseAudioContext::GraphAutoLocker graph_lock(context); @@ -48,8 +48,8 @@ DelayNode* node2 = context->createDelay(ASSERT_NO_EXCEPTION); auto& handler2 = node2->Handler(); - auto input = AudioNodeInput::Create(handler1); - auto output = AudioNodeOutput::Create(&handler2, 0); + auto input = std::make_unique<AudioNodeInput>(handler1); + auto output = std::make_unique<AudioNodeOutput>(&handler2, 0); { BaseAudioContext::GraphAutoLocker graph_lock(context);
diff --git a/third_party/blink/renderer/modules/webaudio/audio_node_output.cc b/third_party/blink/renderer/modules/webaudio/audio_node_output.cc index 71019c0..1bc9a99 100644 --- a/third_party/blink/renderer/modules/webaudio/audio_node_output.cc +++ b/third_party/blink/renderer/modules/webaudio/audio_node_output.cc
@@ -35,8 +35,8 @@ namespace blink { -inline AudioNodeOutput::AudioNodeOutput(AudioHandler* handler, - unsigned number_of_channels) +AudioNodeOutput::AudioNodeOutput(AudioHandler* handler, + unsigned number_of_channels) : handler_(*handler), number_of_channels_(number_of_channels), desired_number_of_channels_(number_of_channels), @@ -51,12 +51,6 @@ audio_utilities::kRenderQuantumFrames); } -std::unique_ptr<AudioNodeOutput> AudioNodeOutput::Create( - AudioHandler* handler, - unsigned number_of_channels) { - return base::WrapUnique(new AudioNodeOutput(handler, number_of_channels)); -} - void AudioNodeOutput::Dispose() { did_call_dispose_ = true;
diff --git a/third_party/blink/renderer/modules/webaudio/audio_node_output.h b/third_party/blink/renderer/modules/webaudio/audio_node_output.h index dd84388..4fd70b1 100644 --- a/third_party/blink/renderer/modules/webaudio/audio_node_output.h +++ b/third_party/blink/renderer/modules/webaudio/audio_node_output.h
@@ -46,8 +46,8 @@ public: // It's OK to pass 0 for numberOfChannels in which case // setNumberOfChannels() must be called later on. - static std::unique_ptr<AudioNodeOutput> Create(AudioHandler*, - unsigned number_of_channels); + AudioNodeOutput(AudioHandler*, unsigned number_of_channels); + void Dispose(); // Causes our AudioNode to process if it hasn't already for this render @@ -91,7 +91,6 @@ void UpdateRenderingState(); private: - AudioNodeOutput(AudioHandler*, unsigned number_of_channels); // Can be called from any thread. AudioHandler& Handler() const { return handler_; } DeferredTaskHandler& GetDeferredTaskHandler() const {
diff --git a/third_party/blink/renderer/modules/webdatabase/database_thread.cc b/third_party/blink/renderer/modules/webdatabase/database_thread.cc index c7411f5a..c1dbe00 100644 --- a/third_party/blink/renderer/modules/webdatabase/database_thread.cc +++ b/third_party/blink/renderer/modules/webdatabase/database_thread.cc
@@ -59,7 +59,7 @@ DCHECK(IsMainThread()); if (thread_) return; - thread_ = WebThreadSupportingGC::Create( + thread_ = std::make_unique<WebThreadSupportingGC>( ThreadCreationParams(WebThreadType::kDatabaseThread)); thread_->PostTask(FROM_HERE, CrossThreadBind(&DatabaseThread::SetupDatabaseThread,
diff --git a/third_party/blink/renderer/modules/webgl/webgl_context_attribute_helpers.cc b/third_party/blink/renderer/modules/webgl/webgl_context_attribute_helpers.cc index 7a74942..9a868cd 100644 --- a/third_party/blink/renderer/modules/webgl/webgl_context_attribute_helpers.cc +++ b/third_party/blink/renderer/modules/webgl/webgl_context_attribute_helpers.cc
@@ -17,6 +17,7 @@ result->setAntialias(attrs.antialias); result->setPremultipliedAlpha(attrs.premultiplied_alpha); result->setPreserveDrawingBuffer(attrs.preserve_drawing_buffer); + result->setPowerPreference(attrs.power_preference); result->setFailIfMajorPerformanceCaveat( attrs.fail_if_major_performance_caveat); result->setXrCompatible(attrs.xr_compatible); @@ -29,6 +30,7 @@ Platform::ContextType context_type, bool support_own_offscreen_surface) { Platform::ContextAttributes result; + result.prefer_integrated_gpu = attrs.power_preference == "low-power"; result.fail_if_major_performance_caveat = attrs.fail_if_major_performance_caveat; result.context_type = context_type;
diff --git a/third_party/blink/renderer/modules/webgl/webgl_context_attributes.idl b/third_party/blink/renderer/modules/webgl/webgl_context_attributes.idl index 725dbfb..2e4df15a 100644 --- a/third_party/blink/renderer/modules/webgl/webgl_context_attributes.idl +++ b/third_party/blink/renderer/modules/webgl/webgl_context_attributes.idl
@@ -26,6 +26,12 @@ // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.2 +enum WebGLPowerPreference { + "default", + "low-power", + "high-performance", +}; + dictionary WebGLContextAttributes { boolean alpha = true; boolean depth = true; @@ -33,6 +39,7 @@ boolean antialias = true; boolean premultipliedAlpha = true; boolean preserveDrawingBuffer = false; + WebGLPowerPreference powerPreference = "default"; boolean failIfMajorPerformanceCaveat = false; [OriginTrialEnabled=WebXR] boolean xrCompatible = false; // TODO(crbug.com/788439): remove OriginTrialEnabled.
diff --git a/third_party/blink/renderer/modules/websockets/inspector_websocket_events.cc b/third_party/blink/renderer/modules/websockets/inspector_websocket_events.cc index bf5eff3..d311b27 100644 --- a/third_party/blink/renderer/modules/websockets/inspector_websocket_events.cc +++ b/third_party/blink/renderer/modules/websockets/inspector_websocket_events.cc
@@ -17,11 +17,11 @@ std::unique_ptr<TracedValue> InspectorWebSocketCreateEvent::Data( ExecutionContext* execution_context, - unsigned long identifier, + uint64_t identifier, const KURL& url, const String& protocol) { DCHECK(execution_context->IsContextThread()); - std::unique_ptr<TracedValue> value = TracedValue::Create(); + auto value = std::make_unique<TracedValue>(); value->SetInteger("identifier", static_cast<int>(identifier)); value->SetString("url", url.GetString()); if (auto* document = DynamicTo<Document>(execution_context)) { @@ -43,9 +43,9 @@ std::unique_ptr<TracedValue> InspectorWebSocketEvent::Data( ExecutionContext* execution_context, - unsigned long identifier) { + uint64_t identifier) { DCHECK(execution_context->IsContextThread()); - std::unique_ptr<TracedValue> value = TracedValue::Create(); + auto value = std::make_unique<TracedValue>(); value->SetInteger("identifier", static_cast<int>(identifier)); if (auto* document = DynamicTo<Document>(execution_context)) { value->SetString("frame",
diff --git a/third_party/blink/renderer/modules/websockets/inspector_websocket_events.h b/third_party/blink/renderer/modules/websockets/inspector_websocket_events.h index 397fb28..bb49b2e 100644 --- a/third_party/blink/renderer/modules/websockets/inspector_websocket_events.h +++ b/third_party/blink/renderer/modules/websockets/inspector_websocket_events.h
@@ -23,7 +23,7 @@ public: static std::unique_ptr<TracedValue> Data(ExecutionContext*, - unsigned long identifier, + uint64_t identifier, const KURL&, const String& protocol); }; @@ -33,7 +33,7 @@ public: static std::unique_ptr<TracedValue> Data(ExecutionContext*, - unsigned long identifier); + uint64_t identifier); }; } // namespace blink
diff --git a/third_party/blink/renderer/modules/websockets/websocket_channel_impl.cc b/third_party/blink/renderer/modules/websockets/websocket_channel_impl.cc index 7024b69..062d17e 100644 --- a/third_party/blink/renderer/modules/websockets/websocket_channel_impl.cc +++ b/third_party/blink/renderer/modules/websockets/websocket_channel_impl.cc
@@ -222,7 +222,8 @@ if (auto* scheduler = execution_context_->GetScheduler()) { feature_handle_for_scheduler_ = scheduler->RegisterFeature( SchedulingPolicy::Feature::kWebSocket, - {SchedulingPolicy::DisableAggressiveThrottling()}); + {SchedulingPolicy::DisableAggressiveThrottling(), + SchedulingPolicy::DisableBackForwardCache()}); } if (MixedContentChecker::IsMixedContent(
diff --git a/third_party/blink/renderer/modules/websockets/websocket_channel_impl.h b/third_party/blink/renderer/modules/websockets/websocket_channel_impl.h index 6ba794de..c4fd2bd 100644 --- a/third_party/blink/renderer/modules/websockets/websocket_channel_impl.h +++ b/third_party/blink/renderer/modules/websockets/websocket_channel_impl.h
@@ -192,7 +192,7 @@ // expects that disconnect() is called before the deletion. Member<WebSocketChannelClient> client_; KURL url_; - unsigned long identifier_; + uint64_t identifier_; Member<BlobLoader> blob_loader_; HeapDeque<Member<Message>> messages_; Vector<char> receiving_message_data_;
diff --git a/third_party/blink/renderer/modules/xr/xr_bounded_reference_space.cc b/third_party/blink/renderer/modules/xr/xr_bounded_reference_space.cc index 849b8455..32d97ec 100644 --- a/third_party/blink/renderer/modules/xr/xr_bounded_reference_space.cc +++ b/third_party/blink/renderer/modules/xr/xr_bounded_reference_space.cc
@@ -34,7 +34,7 @@ // Use the transform given by xrDisplayInfo's stageParameters if available. const WTF::Vector<float>& m = display_info->stageParameters->standingTransform; - floor_level_transform_ = TransformationMatrix::Create( + floor_level_transform_ = std::make_unique<TransformationMatrix>( m[0], m[1], m[2], m[3], m[4], m[5], m[6], m[7], m[8], m[9], m[10], m[11], m[12], m[13], m[14], m[15]); } else { @@ -62,7 +62,7 @@ // that, otherwise return null. if (floor_level_transform_) { std::unique_ptr<TransformationMatrix> pose( - TransformationMatrix::Create(*floor_level_transform_)); + std::make_unique<TransformationMatrix>(*floor_level_transform_)); pose->Multiply(base_pose); return pose; }
diff --git a/third_party/blink/renderer/modules/xr/xr_frame.cc b/third_party/blink/renderer/modules/xr/xr_frame.cc index e615fa5e..e3605fb 100644 --- a/third_party/blink/renderer/modules/xr/xr_frame.cc +++ b/third_party/blink/renderer/modules/xr/xr_frame.cc
@@ -61,7 +61,7 @@ // Account for any changes made to the reference space's origin offset so that // things like teleportation works. - pose = TransformationMatrix::Create( + pose = std::make_unique<TransformationMatrix>( reference_space->OriginOffsetMatrix().Inverse().Multiply(*pose)); return MakeGarbageCollected<XRViewerPose>(session(), std::move(pose)); @@ -91,7 +91,7 @@ // Account for any changes made to the reference space's origin offset so // that things like teleportation works. - grip_pose = TransformationMatrix::Create( + grip_pose = std::make_unique<TransformationMatrix>( reference_space->OriginOffsetMatrix().Inverse().Multiply(*grip_pose)); return MakeGarbageCollected<XRPose>(std::move(grip_pose), @@ -150,7 +150,7 @@ return nullptr; } - pointer_pose = TransformationMatrix::Create(*grip_pose); + pointer_pose = std::make_unique<TransformationMatrix>(*grip_pose); if (input_source->pointer_transform_matrix_) { pointer_pose->Multiply(*(input_source->pointer_transform_matrix_)); @@ -165,7 +165,7 @@ // Account for any changes made to the reference space's origin offset so that // things like teleportation works. - pointer_pose = TransformationMatrix::Create( + pointer_pose = std::make_unique<TransformationMatrix>( reference_space->OriginOffsetMatrix().Inverse().Multiply(*pointer_pose)); return MakeGarbageCollected<XRPose>(std::move(pointer_pose), @@ -231,12 +231,13 @@ // TODO(jacde): Update how EmulatedPosition is determined here once spec issue // https://github.com/immersive-web/webxr/issues/534 has been resolved. TransformationMatrix A_from_B = A_from_mojo.Multiply(*mojo_from_B); - return MakeGarbageCollected<XRPose>(TransformationMatrix::Create(A_from_B), - session_->EmulatedPosition()); + return MakeGarbageCollected<XRPose>( + std::make_unique<TransformationMatrix>(A_from_B), + session_->EmulatedPosition()); } void XRFrame::SetBasePoseMatrix(const TransformationMatrix& base_pose_matrix) { - base_pose_matrix_ = TransformationMatrix::Create(base_pose_matrix); + base_pose_matrix_ = std::make_unique<TransformationMatrix>(base_pose_matrix); } void XRFrame::Deactivate() {
diff --git a/third_party/blink/renderer/modules/xr/xr_frame_provider.cc b/third_party/blink/renderer/modules/xr/xr_frame_provider.cc index b1e21cf..021d894 100644 --- a/third_party/blink/renderer/modules/xr/xr_frame_provider.cc +++ b/third_party/blink/renderer/modules/xr/xr_frame_provider.cc
@@ -53,7 +53,7 @@ return nullptr; std::unique_ptr<TransformationMatrix> pose_matrix = - TransformationMatrix::Create(); + std::make_unique<TransformationMatrix>(); TransformationMatrix::DecomposedType decomp;
diff --git a/third_party/blink/renderer/modules/xr/xr_ray.cc b/third_party/blink/renderer/modules/xr/xr_ray.cc index b4cbd73..e8353bea 100644 --- a/third_party/blink/renderer/modules/xr/xr_ray.cc +++ b/third_party/blink/renderer/modules/xr/xr_ray.cc
@@ -97,7 +97,7 @@ // (0,0,0) with direction (0,0,-1) into ray originating at |origin_| with // direction |direction_|. - matrix_ = TransformationMatrix::Create(); + matrix_ = std::make_unique<TransformationMatrix>(); // Translation from 0 to |origin_| is simply translation by |origin_|. matrix_->Translate3d(origin_->x(), origin_->y(), origin_->z());
diff --git a/third_party/blink/renderer/modules/xr/xr_reference_space.cc b/third_party/blink/renderer/modules/xr/xr_reference_space.cc index 05a5ed2..220f349 100644 --- a/third_party/blink/renderer/modules/xr/xr_reference_space.cc +++ b/third_party/blink/renderer/modules/xr/xr_reference_space.cc
@@ -23,7 +23,7 @@ // identity reference spaces. std::unique_ptr<TransformationMatrix> XRReferenceSpace::DefaultPose() { // An identity reference space always returns an identity matrix. - return TransformationMatrix::Create(); + return std::make_unique<TransformationMatrix>(); } // Transforms a given pose from a "base" reference space used by the XR
diff --git a/third_party/blink/renderer/modules/xr/xr_rigid_transform.cc b/third_party/blink/renderer/modules/xr/xr_rigid_transform.cc index c4e4b2eb..adfb30fa 100644 --- a/third_party/blink/renderer/modules/xr/xr_rigid_transform.cc +++ b/third_party/blink/renderer/modules/xr/xr_rigid_transform.cc
@@ -11,7 +11,7 @@ // makes a deep copy of transformationMatrix XRRigidTransform::XRRigidTransform( const TransformationMatrix& transformationMatrix) - : matrix_(TransformationMatrix::Create(transformationMatrix)) { + : matrix_(std::make_unique<TransformationMatrix>(transformationMatrix)) { DecomposeMatrix(); } @@ -20,7 +20,7 @@ std::unique_ptr<TransformationMatrix> transformationMatrix) : matrix_(std::move(transformationMatrix)) { if (!matrix_) { - matrix_ = TransformationMatrix::Create(); + matrix_ = std::make_unique<TransformationMatrix>(); } DecomposeMatrix(); } @@ -64,7 +64,7 @@ other.orientation_->x(), other.orientation_->y(), other.orientation_->z(), other.orientation_->w()); if (other.matrix_) { - matrix_ = TransformationMatrix::Create(*(other.matrix_.get())); + matrix_ = std::make_unique<TransformationMatrix>(*(other.matrix_.get())); } return *this; @@ -100,6 +100,10 @@ return transformationMatrixToDOMFloat32Array(*matrix_); } +XRRigidTransform* XRRigidTransform::inverse() { + return MakeGarbageCollected<XRRigidTransform>(InverseTransformMatrix()); +} + TransformationMatrix XRRigidTransform::InverseTransformMatrix() { EnsureMatrix(); DCHECK(matrix_->IsInvertible()); @@ -113,7 +117,7 @@ void XRRigidTransform::EnsureMatrix() { if (!matrix_) { - matrix_ = TransformationMatrix::Create(); + matrix_ = std::make_unique<TransformationMatrix>(); TransformationMatrix::DecomposedType decomp; memset(&decomp, 0, sizeof(decomp)); decomp.perspective_w = 1;
diff --git a/third_party/blink/renderer/modules/xr/xr_rigid_transform.h b/third_party/blink/renderer/modules/xr/xr_rigid_transform.h index 13175de..0697decc 100644 --- a/third_party/blink/renderer/modules/xr/xr_rigid_transform.h +++ b/third_party/blink/renderer/modules/xr/xr_rigid_transform.h
@@ -37,6 +37,7 @@ DOMPointReadOnly* position() const { return position_; } DOMPointReadOnly* orientation() const { return orientation_; } DOMFloat32Array* matrix(); + XRRigidTransform* inverse(); TransformationMatrix InverseTransformMatrix(); TransformationMatrix TransformMatrix(); // copies matrix_
diff --git a/third_party/blink/renderer/modules/xr/xr_rigid_transform.idl b/third_party/blink/renderer/modules/xr/xr_rigid_transform.idl index 40dd716..29e3ad0 100644 --- a/third_party/blink/renderer/modules/xr/xr_rigid_transform.idl +++ b/third_party/blink/renderer/modules/xr/xr_rigid_transform.idl
@@ -13,4 +13,6 @@ readonly attribute DOMPointReadOnly position; readonly attribute DOMPointReadOnly orientation; readonly attribute Float32Array matrix; + + XRRigidTransform inverse(); };
diff --git a/third_party/blink/renderer/modules/xr/xr_rigid_transform_test.cc b/third_party/blink/renderer/modules/xr/xr_rigid_transform_test.cc index 4a09aa9..b50f050 100644 --- a/third_party/blink/renderer/modules/xr/xr_rigid_transform_test.cc +++ b/third_party/blink/renderer/modules/xr/xr_rigid_transform_test.cc
@@ -93,9 +93,9 @@ } TEST(XRRigidTransformTest, Decompose) { - XRRigidTransform transform( - TransformationMatrix::Create(1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, - -1.0, 0.0, 0.0, 1.0, 2.0, 3.0, 1.0)); + XRRigidTransform transform(std::make_unique<TransformationMatrix>( + 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, -1.0, 0.0, 0.0, 1.0, 2.0, + 3.0, 1.0)); const DOMPointReadOnly expected_position(1.0, 2.0, 3.0, 1.0); const DOMPointReadOnly expected_orientation(0.7071068, 0.0, 0.0, 0.7071068); AssertDOMPointsEqualForTest(transform.position(), &expected_position);
diff --git a/third_party/blink/renderer/modules/xr/xr_session.cc b/third_party/blink/renderer/modules/xr/xr_session.cc index d8b49c6..c8dd28c3 100644 --- a/third_party/blink/renderer/modules/xr/xr_session.cc +++ b/third_party/blink/renderer/modules/xr/xr_session.cc
@@ -421,8 +421,8 @@ HeapVector<Member<XRHitResult>> hit_results; for (const auto& mojom_result : results.value()) { - XRHitResult* hit_result = - MakeGarbageCollected<XRHitResult>(TransformationMatrix::Create( + XRHitResult* hit_result = MakeGarbageCollected<XRHitResult>( + std::make_unique<TransformationMatrix>( mojom_result->hit_matrix[0], mojom_result->hit_matrix[1], mojom_result->hit_matrix[2], mojom_result->hit_matrix[3], mojom_result->hit_matrix[4], mojom_result->hit_matrix[5], @@ -888,9 +888,9 @@ if (desc->pointer_offset && desc->pointer_offset->matrix.has_value()) { const WTF::Vector<float>& m = desc->pointer_offset->matrix.value(); std::unique_ptr<TransformationMatrix> pointer_matrix = - TransformationMatrix::Create(m[0], m[1], m[2], m[3], m[4], m[5], m[6], - m[7], m[8], m[9], m[10], m[11], m[12], - m[13], m[14], m[15]); + std::make_unique<TransformationMatrix>( + m[0], m[1], m[2], m[3], m[4], m[5], m[6], m[7], m[8], m[9], m[10], + m[11], m[12], m[13], m[14], m[15]); input_source->SetPointerTransformMatrix(std::move(pointer_matrix)); } } @@ -898,9 +898,9 @@ if (state->grip && state->grip->matrix.has_value()) { const Vector<float>& m = state->grip->matrix.value(); std::unique_ptr<TransformationMatrix> grip_matrix = - TransformationMatrix::Create(m[0], m[1], m[2], m[3], m[4], m[5], m[6], - m[7], m[8], m[9], m[10], m[11], m[12], - m[13], m[14], m[15]); + std::make_unique<TransformationMatrix>( + m[0], m[1], m[2], m[3], m[4], m[5], m[6], m[7], m[8], m[9], m[10], + m[11], m[12], m[13], m[14], m[15]); input_source->SetBasePoseMatrix(std::move(grip_matrix)); }
diff --git a/third_party/blink/renderer/modules/xr/xr_stationary_reference_space.cc b/third_party/blink/renderer/modules/xr/xr_stationary_reference_space.cc index 0ed1f0a..c9ae1a8 100644 --- a/third_party/blink/renderer/modules/xr/xr_stationary_reference_space.cc +++ b/third_party/blink/renderer/modules/xr/xr_stationary_reference_space.cc
@@ -42,12 +42,12 @@ // Use the transform given by xrDisplayInfo's stageParameters if available. const WTF::Vector<float>& m = display_info->stageParameters->standingTransform; - floor_level_transform_ = TransformationMatrix::Create( + floor_level_transform_ = std::make_unique<TransformationMatrix>( m[0], m[1], m[2], m[3], m[4], m[5], m[6], m[7], m[8], m[9], m[10], m[11], m[12], m[13], m[14], m[15]); } else { // Otherwise, create a transform based on the default emulated height. - floor_level_transform_ = TransformationMatrix::Create(); + floor_level_transform_ = std::make_unique<TransformationMatrix>(); floor_level_transform_->Translate3d(0, kDefaultEmulationHeight, 0); } @@ -67,7 +67,7 @@ switch (subtype_) { case kSubtypeEyeLevel: // Currently all base poses are 'eye-level' poses, so return directly. - return TransformationMatrix::Create(base_pose); + return std::make_unique<TransformationMatrix>(base_pose); break; case kSubtypeFloorLevel: // Currently all base poses are 'eye-level' space, so use of 'floor-level' @@ -83,7 +83,7 @@ // Apply the floor-level transform to the base pose. if (floor_level_transform_) { std::unique_ptr<TransformationMatrix> pose( - TransformationMatrix::Create(*floor_level_transform_)); + std::make_unique<TransformationMatrix>(*floor_level_transform_)); pose->Multiply(base_pose); return pose; } @@ -93,7 +93,7 @@ // and as a result the space the base pose is originally in doesn't matter // much. Strip out translation component and return. std::unique_ptr<TransformationMatrix> pose( - TransformationMatrix::Create(base_pose)); + std::make_unique<TransformationMatrix>(base_pose)); pose->SetM41(0.0); pose->SetM42(0.0); pose->SetM43(0.0); @@ -124,7 +124,7 @@ // Translate the controller by the same delta so that it shows up in the // right relative position. std::unique_ptr<TransformationMatrix> pose( - TransformationMatrix::Create(base_input_pose)); + std::make_unique<TransformationMatrix>(base_input_pose)); pose->SetM41(pose->M41() + dx); pose->SetM42(pose->M42() + dy); pose->SetM43(pose->M43() + dz);
diff --git a/third_party/blink/renderer/modules/xr/xr_unbounded_reference_space.cc b/third_party/blink/renderer/modules/xr/xr_unbounded_reference_space.cc index b17fb0d..c8bce50 100644 --- a/third_party/blink/renderer/modules/xr/xr_unbounded_reference_space.cc +++ b/third_party/blink/renderer/modules/xr/xr_unbounded_reference_space.cc
@@ -24,7 +24,7 @@ const TransformationMatrix& base_pose) { // For now we assume that poses returned by systems that support unbounded // reference spaces are already in the correct space. - return TransformationMatrix::Create(base_pose); + return std::make_unique<TransformationMatrix>(base_pose); } void XRUnboundedReferenceSpace::Trace(blink::Visitor* visitor) {
diff --git a/third_party/blink/renderer/modules/xr/xr_utils.cc b/third_party/blink/renderer/modules/xr/xr_utils.cc index 9ce45f0..8fbee2e5 100644 --- a/third_party/blink/renderer/modules/xr/xr_utils.cc +++ b/third_party/blink/renderer/modules/xr/xr_utils.cc
@@ -31,7 +31,7 @@ auto* data = m->Data(); - return TransformationMatrix::Create( + return std::make_unique<TransformationMatrix>( static_cast<double>(data[0]), static_cast<double>(data[1]), static_cast<double>(data[2]), static_cast<double>(data[3]), static_cast<double>(data[4]), static_cast<double>(data[5]),
diff --git a/third_party/blink/renderer/modules/xr/xr_view.cc b/third_party/blink/renderer/modules/xr/xr_view.cc index 6787906..8e4f7a2 100644 --- a/third_party/blink/renderer/modules/xr/xr_view.cc +++ b/third_party/blink/renderer/modules/xr/xr_view.cc
@@ -172,10 +172,11 @@ if (inv_projection_dirty_) { float* m = projection_matrix_->Data(); std::unique_ptr<TransformationMatrix> projection = - TransformationMatrix::Create(m[0], m[1], m[2], m[3], m[4], m[5], m[6], - m[7], m[8], m[9], m[10], m[11], m[12], - m[13], m[14], m[15]); - inv_projection_ = TransformationMatrix::Create(projection->Inverse()); + std::make_unique<TransformationMatrix>( + m[0], m[1], m[2], m[3], m[4], m[5], m[6], m[7], m[8], m[9], m[10], + m[11], m[12], m[13], m[14], m[15]); + inv_projection_ = + std::make_unique<TransformationMatrix>(projection->Inverse()); inv_projection_dirty_ = false; } @@ -212,7 +213,7 @@ // LookAt matrices are view matrices (inverted), so invert before returning. std::unique_ptr<TransformationMatrix> pointer = - TransformationMatrix::Create(inv_pointer.Inverse()); + std::make_unique<TransformationMatrix>(inv_pointer.Inverse()); return pointer; } @@ -230,7 +231,7 @@ // after taking the inverse // compute the inverse lazily DCHECK(inv_pose_matrix.IsInvertible()); - inv_pose_ = TransformationMatrix::Create(inv_pose_matrix); + inv_pose_ = std::make_unique<TransformationMatrix>(inv_pose_matrix); } XRRigidTransform* XRView::transform() {
diff --git a/third_party/blink/renderer/platform/bindings/origin_trial_features.cc b/third_party/blink/renderer/platform/bindings/origin_trial_features.cc index 169ef878..8227c0a 100644 --- a/third_party/blink/renderer/platform/bindings/origin_trial_features.cc +++ b/third_party/blink/renderer/platform/bindings/origin_trial_features.cc
@@ -6,6 +6,7 @@ #include "third_party/blink/renderer/platform/bindings/dom_wrapper_world.h" #include "third_party/blink/renderer/platform/bindings/script_state.h" +#include "third_party/blink/renderer/platform/runtime_enabled_features.h" namespace blink { @@ -15,7 +16,7 @@ v8::Local<v8::Object> prototype_object, v8::Local<v8::Function> interface_object) {} -void InstallPendingOriginTrialFeatureDefault(const String& feature, +void InstallPendingOriginTrialFeatureDefault(OriginTrialFeature feature, const ScriptState* script_state) {} namespace { @@ -56,7 +57,7 @@ type, script_state, prototype_object, interface_object); } -void InstallPendingOriginTrialFeature(const String& feature, +void InstallPendingOriginTrialFeature(OriginTrialFeature feature, const ScriptState* script_state) { DCHECK(script_state); DCHECK(script_state->GetContext() ==
diff --git a/third_party/blink/renderer/platform/bindings/origin_trial_features.h b/third_party/blink/renderer/platform/bindings/origin_trial_features.h index 46fa197..6149676f 100644 --- a/third_party/blink/renderer/platform/bindings/origin_trial_features.h +++ b/third_party/blink/renderer/platform/bindings/origin_trial_features.h
@@ -11,6 +11,7 @@ namespace blink { +enum class OriginTrialFeature; class ScriptState; struct WrapperTypeInfo; @@ -19,7 +20,7 @@ v8::Local<v8::Object>, v8::Local<v8::Function>); -using InstallPendingOriginTrialFeatureFunction = void (*)(const String&, +using InstallPendingOriginTrialFeatureFunction = void (*)(OriginTrialFeature, const ScriptState*); // Sets the function to be called by |InstallOriginTrialFeatures|. The function @@ -51,7 +52,7 @@ // objects. If the target object hasn't been created, nothing is installed. The // enabled feature will be instead be installed when the object is created // (avoids forcing the creation of objects prematurely). -PLATFORM_EXPORT void InstallPendingOriginTrialFeature(const String&, +PLATFORM_EXPORT void InstallPendingOriginTrialFeature(OriginTrialFeature, const ScriptState*); } // namespace blink
diff --git a/third_party/blink/renderer/platform/bindings/runtime_call_stats.cc b/third_party/blink/renderer/platform/bindings/runtime_call_stats.cc index 4bbe43d..4ecc21a 100644 --- a/third_party/blink/renderer/platform/bindings/runtime_call_stats.cc +++ b/third_party/blink/renderer/platform/bindings/runtime_call_stats.cc
@@ -211,7 +211,7 @@ } void RuntimeCallStatsScopedTracer::AddEndTraceEvent() { - std::unique_ptr<TracedValue> value = TracedValue::Create(); + auto value = std::make_unique<TracedValue>(); stats_->Dump(*value); stats_->SetInUse(false); TRACE_EVENT_END1(s_category_group_, s_name_, "runtime-call-stats",
diff --git a/third_party/blink/renderer/platform/content_decryption_module_result.h b/third_party/blink/renderer/platform/content_decryption_module_result.h index bdab63b..620f8393 100644 --- a/third_party/blink/renderer/platform/content_decryption_module_result.h +++ b/third_party/blink/renderer/platform/content_decryption_module_result.h
@@ -29,7 +29,7 @@ virtual void CompleteWithKeyStatus( WebEncryptedMediaKeyInformation::KeyStatus) = 0; virtual void CompleteWithError(WebContentDecryptionModuleException, - unsigned long system_code, + uint32_t system_code, const WebString&) = 0; WebContentDecryptionModuleResult Result() {
diff --git a/third_party/blink/renderer/platform/exported/web_content_decryption_module_result.cc b/third_party/blink/renderer/platform/exported/web_content_decryption_module_result.cc index 35c9b45..352d7b52 100644 --- a/third_party/blink/renderer/platform/exported/web_content_decryption_module_result.cc +++ b/third_party/blink/renderer/platform/exported/web_content_decryption_module_result.cc
@@ -33,7 +33,7 @@ void WebContentDecryptionModuleResult::CompleteWithError( WebContentDecryptionModuleException exception, - unsigned long system_code, + uint32_t system_code, const WebString& error_message) { impl_->CompleteWithError(exception, system_code, error_message); Reset();
diff --git a/third_party/blink/renderer/platform/exported/web_runtime_features.cc b/third_party/blink/renderer/platform/exported/web_runtime_features.cc index dd09129..1f13abe 100644 --- a/third_party/blink/renderer/platform/exported/web_runtime_features.cc +++ b/third_party/blink/renderer/platform/exported/web_runtime_features.cc
@@ -530,10 +530,6 @@ RuntimeEnabledFeatures::SetSecMetadataEnabled(enable); } -void WebRuntimeFeatures::EnableSerial(bool enable) { - RuntimeEnabledFeatures::SetSerialEnabled(enable); -} - void WebRuntimeFeatures::EnableTimerThrottlingForBackgroundTabs(bool enable) { RuntimeEnabledFeatures::SetTimerThrottlingForBackgroundTabsEnabled(enable); } @@ -602,6 +598,10 @@ RuntimeEnabledFeatures::SetAutomationControlledEnabled(enable); } +void WebRuntimeFeatures::EnableScheduledScriptStreaming(bool enable) { + RuntimeEnabledFeatures::SetScheduledScriptStreamingEnabled(enable); +} + void WebRuntimeFeatures::EnableScriptStreamingOnPreload(bool enable) { RuntimeEnabledFeatures::SetScriptStreamingOnPreloadEnabled(enable); }
diff --git a/third_party/blink/renderer/platform/fonts/script_run_iterator_test.cc b/third_party/blink/renderer/platform/fonts/script_run_iterator_test.cc index fbe65733..80bfbff 100644 --- a/third_party/blink/renderer/platform/fonts/script_run_iterator_test.cc +++ b/third_party/blink/renderer/platform/fonts/script_run_iterator_test.cc
@@ -315,7 +315,7 @@ const Vector<ScriptExpectedRun>& expect) { unsigned limit; UScriptCode code; - unsigned long run_count = 0; + size_t run_count = 0; while (script_run_iterator->Consume(&limit, &code)) { ASSERT_LT(run_count, expect.size()); ASSERT_EQ(expect[run_count].limit, limit);
diff --git a/third_party/blink/renderer/platform/fonts/shaping/run_segmenter_test.cc b/third_party/blink/renderer/platform/fonts/shaping/run_segmenter_test.cc index 480e1f7f..35c150d 100644 --- a/third_party/blink/renderer/platform/fonts/shaping/run_segmenter_test.cc +++ b/third_party/blink/renderer/platform/fonts/shaping/run_segmenter_test.cc
@@ -68,7 +68,7 @@ void VerifyRuns(RunSegmenter* run_segmenter, const Vector<SegmenterExpectedRun>& expect) { RunSegmenter::RunSegmenterRange segmenter_range; - unsigned long run_count = 0; + size_t run_count = 0; while (run_segmenter->Consume(&segmenter_range)) { ASSERT_LT(run_count, expect.size()); ASSERT_EQ(expect[run_count].start, segmenter_range.start);
diff --git a/third_party/blink/renderer/platform/fonts/small_caps_iterator_test.cc b/third_party/blink/renderer/platform/fonts/small_caps_iterator_test.cc index df2ffafb..ec0ccf03 100644 --- a/third_party/blink/renderer/platform/fonts/small_caps_iterator_test.cc +++ b/third_party/blink/renderer/platform/fonts/small_caps_iterator_test.cc
@@ -40,7 +40,7 @@ const Vector<SmallCapsExpectedRun>& expect) { unsigned limit; SmallCapsIterator::SmallCapsBehavior small_caps_behavior; - unsigned long run_count = 0; + size_t run_count = 0; while (small_caps_iterator->Consume(&limit, &small_caps_behavior)) { ASSERT_LT(run_count, expect.size()); ASSERT_EQ(expect[run_count].limit, limit);
diff --git a/third_party/blink/renderer/platform/fonts/symbols_iterator_test.cc b/third_party/blink/renderer/platform/fonts/symbols_iterator_test.cc index 3ec12d4..3f446c9 100644 --- a/third_party/blink/renderer/platform/fonts/symbols_iterator_test.cc +++ b/third_party/blink/renderer/platform/fonts/symbols_iterator_test.cc
@@ -44,7 +44,7 @@ const Vector<FallbackExpectedRun>& expect) { unsigned limit; FontFallbackPriority font_fallback_priority; - unsigned long run_count = 0; + size_t run_count = 0; while (symbols_iterator->Consume(&limit, &font_fallback_priority)) { ASSERT_LT(run_count, expect.size()); ASSERT_EQ(expect[run_count].limit, limit);
diff --git a/third_party/blink/renderer/platform/fonts/vdmx_parser.cc b/third_party/blink/renderer/platform/fonts/vdmx_parser.cc index a520527..842dcf2 100644 --- a/third_party/blink/renderer/platform/fonts/vdmx_parser.cc +++ b/third_party/blink/renderer/platform/fonts/vdmx_parser.cc
@@ -131,7 +131,7 @@ // of this second table. // // Range 6 <= x <= 262146 - unsigned long offset_table_offset = + size_t offset_table_offset = buf.Offset() + 4 /* sizeof struct ratio */ * num_ratios; unsigned desired_ratio = 0xffffffff;
diff --git a/third_party/blink/renderer/platform/heap/heap.cc b/third_party/blink/renderer/platform/heap/heap.cc index 666b1200..14cdfdf 100644 --- a/third_party/blink/renderer/platform/heap/heap.cc +++ b/third_party/blink/renderer/platform/heap/heap.cc
@@ -517,8 +517,7 @@ // gcInfoIndex. ThreadState::GCSnapshotInfo info(GCInfoTable::Get().GcInfoIndex() + 1); String thread_dump_name = - String::Format("blink_gc/thread_%lu", - static_cast<unsigned long>(thread_state_->ThreadId())); + String("blink_gc/thread_") + String::Number(thread_state_->ThreadId()); const String heaps_dump_name = thread_dump_name + "/heaps"; const String classes_dump_name = thread_dump_name + "/classes";
diff --git a/third_party/blink/renderer/platform/heap/heap_page.cc b/third_party/blink/renderer/platform/heap/heap_page.cc index 4c855f0c..d120b441 100644 --- a/third_party/blink/renderer/platform/heap/heap_page.cc +++ b/third_party/blink/renderer/platform/heap/heap_page.cc
@@ -136,9 +136,8 @@ size_t page_count = 0; BasePage::HeapSnapshotInfo heap_info; for (BasePage* page = first_unswept_page_; page; page = page->Next()) { - String dump_name = dump_base_name + - String::Format("/pages/page_%lu", - static_cast<unsigned long>(page_count++)); + String dump_name = + dump_base_name + String::Format("/pages/page_%zu", page_count++); base::trace_event::MemoryAllocatorDump* page_dump = BlinkGCMemoryDumpProvider::Instance() ->CreateMemoryAllocatorDumpForCurrentGC(dump_name); @@ -1237,8 +1236,7 @@ } String dump_name = - dump_base_name + String::Format("/buckets/bucket_%lu", - static_cast<unsigned long>(1 << i)); + dump_base_name + "/buckets/bucket_" + String::Number(1 << i); base::trace_event::MemoryAllocatorDump* bucket_dump = BlinkGCMemoryDumpProvider::Instance() ->CreateMemoryAllocatorDumpForCurrentGC(dump_name);
diff --git a/third_party/blink/renderer/platform/instrumentation/tracing/traced_value.cc b/third_party/blink/renderer/platform/instrumentation/tracing/traced_value.cc index 969fb02a..6d75c7df 100644 --- a/third_party/blink/renderer/platform/instrumentation/tracing/traced_value.cc +++ b/third_party/blink/renderer/platform/instrumentation/tracing/traced_value.cc
@@ -12,10 +12,6 @@ namespace blink { -std::unique_ptr<TracedValue> TracedValue::Create() { - return base::WrapUnique(new TracedValue()); -} - TracedValue::TracedValue() = default; TracedValue::~TracedValue() = default;
diff --git a/third_party/blink/renderer/platform/instrumentation/tracing/traced_value.h b/third_party/blink/renderer/platform/instrumentation/tracing/traced_value.h index bbcf52c3..d496bf52 100644 --- a/third_party/blink/renderer/platform/instrumentation/tracing/traced_value.h +++ b/third_party/blink/renderer/platform/instrumentation/tracing/traced_value.h
@@ -16,10 +16,9 @@ class PLATFORM_EXPORT TracedValue final : public base::trace_event::ConvertableToTraceFormat { public: + TracedValue(); ~TracedValue() override; - static std::unique_ptr<TracedValue> Create(); - void EndDictionary(); void EndArray(); @@ -48,8 +47,6 @@ String ToString() const; private: - TracedValue(); - // ConvertableToTraceFormat void AppendAsTraceFormat(std::string*) const final;
diff --git a/third_party/blink/renderer/platform/instrumentation/tracing/traced_value_test.cc b/third_party/blink/renderer/platform/instrumentation/tracing/traced_value_test.cc index 88489eff..6616955 100644 --- a/third_party/blink/renderer/platform/instrumentation/tracing/traced_value_test.cc +++ b/third_party/blink/renderer/platform/instrumentation/tracing/traced_value_test.cc
@@ -19,7 +19,7 @@ } TEST(TracedValueTest, FlatDictionary) { - std::unique_ptr<TracedValue> value = TracedValue::Create(); + auto value = std::make_unique<TracedValue>(); value->SetIntegerWithCopiedName("int", 2014); value->SetDoubleWithCopiedName("double", 0.0); value->SetBooleanWithCopiedName("bool", true); @@ -40,7 +40,7 @@ } TEST(TracedValueTest, Hierarchy) { - std::unique_ptr<TracedValue> value = TracedValue::Create(); + auto value = std::make_unique<TracedValue>(); value->SetIntegerWithCopiedName("i0", 2014); value->BeginDictionaryWithCopiedName("dict1"); value->SetIntegerWithCopiedName("i1", 2014); @@ -100,7 +100,7 @@ } TEST(TracedValueTest, Escape) { - std::unique_ptr<TracedValue> value = TracedValue::Create(); + auto value = std::make_unique<TracedValue>(); value->SetStringWithCopiedName("s0", "value0\\"); value->SetStringWithCopiedName("s1", "value\n1"); value->SetStringWithCopiedName("s2", "\"value2\""); @@ -128,7 +128,7 @@ } TEST(TracedValueTest, NonCopiedNames) { - std::unique_ptr<TracedValue> value = TracedValue::Create(); + auto value = std::make_unique<TracedValue>(); const char* int_str = "int"; const char* double_str = "double"; const char* bool_str = "bool";
diff --git a/third_party/blink/renderer/platform/loader/fetch/fetch_context.cc b/third_party/blink/renderer/platform/loader/fetch/fetch_context.cc index 93e91e7..0ee79558 100644 --- a/third_party/blink/renderer/platform/loader/fetch/fetch_context.cc +++ b/third_party/blink/renderer/platform/loader/fetch/fetch_context.cc
@@ -65,7 +65,7 @@ visitor->Trace(resource_fetcher_properties_); } -void FetchContext::DispatchDidChangeResourcePriority(unsigned long, +void FetchContext::DispatchDidChangeResourcePriority(uint64_t, ResourceLoadPriority, int) {} @@ -83,28 +83,26 @@ WebScopedVirtualTimePauser&, ResourceType) {} -void FetchContext::DispatchWillSendRequest(unsigned long, +void FetchContext::DispatchWillSendRequest(uint64_t, const ResourceRequest&, const ResourceResponse&, ResourceType, const FetchInitiatorInfo&) {} -void FetchContext::DispatchDidReceiveResponse(unsigned long, +void FetchContext::DispatchDidReceiveResponse(uint64_t, const ResourceRequest&, const ResourceResponse&, Resource*, ResourceResponseType) {} -void FetchContext::DispatchDidReceiveData(unsigned long, - const char*, - uint64_t) {} +void FetchContext::DispatchDidReceiveData(uint64_t, const char*, uint64_t) {} -void FetchContext::DispatchDidReceiveEncodedData(unsigned long, size_t) {} +void FetchContext::DispatchDidReceiveEncodedData(uint64_t, size_t) {} -void FetchContext::DispatchDidDownloadToBlob(unsigned long identifier, +void FetchContext::DispatchDidDownloadToBlob(uint64_t identifier, BlobDataHandle*) {} -void FetchContext::DispatchDidFinishLoading(unsigned long, +void FetchContext::DispatchDidFinishLoading(uint64_t, TimeTicks, int64_t, int64_t, @@ -112,7 +110,7 @@ ResourceResponseType) {} void FetchContext::DispatchDidFail(const KURL&, - unsigned long, + uint64_t, const ResourceError&, int64_t, bool) {}
diff --git a/third_party/blink/renderer/platform/loader/fetch/fetch_context.h b/third_party/blink/renderer/platform/loader/fetch/fetch_context.h index 1cde5db..e7d7024f 100644 --- a/third_party/blink/renderer/platform/loader/fetch/fetch_context.h +++ b/third_party/blink/renderer/platform/loader/fetch/fetch_context.h
@@ -109,7 +109,7 @@ ResourceType, FetchParameters::DeferOption) const; - virtual void DispatchDidChangeResourcePriority(unsigned long identifier, + virtual void DispatchDidChangeResourcePriority(uint64_t identifier, ResourceLoadPriority, int intra_priority_value); @@ -128,7 +128,7 @@ // The last callback before a request is actually sent to the browser process. // This is called on initial and every redirect request. virtual void DispatchWillSendRequest( - unsigned long identifier, + uint64_t identifier, const ResourceRequest&, const ResourceResponse& redirect_response, ResourceType, @@ -138,26 +138,25 @@ // the memory cache |request| and |resource->GetResourceRequest()| don't // match. |response| may not yet be set to |resource| when this function is // called. - virtual void DispatchDidReceiveResponse(unsigned long identifier, + virtual void DispatchDidReceiveResponse(uint64_t identifier, const ResourceRequest& request, const ResourceResponse& response, Resource* resource, ResourceResponseType); - virtual void DispatchDidReceiveData(unsigned long identifier, + virtual void DispatchDidReceiveData(uint64_t identifier, const char* data, uint64_t data_length); - virtual void DispatchDidReceiveEncodedData(unsigned long identifier, + virtual void DispatchDidReceiveEncodedData(uint64_t identifier, size_t encoded_data_length); - virtual void DispatchDidDownloadToBlob(unsigned long identifier, - BlobDataHandle*); - virtual void DispatchDidFinishLoading(unsigned long identifier, + virtual void DispatchDidDownloadToBlob(uint64_t identifier, BlobDataHandle*); + virtual void DispatchDidFinishLoading(uint64_t identifier, TimeTicks finish_time, int64_t encoded_data_length, int64_t decoded_body_length, bool should_report_corb_blocking, ResourceResponseType); virtual void DispatchDidFail(const KURL&, - unsigned long identifier, + uint64_t identifier, const ResourceError&, int64_t encoded_data_length, bool is_internal_request);
diff --git a/third_party/blink/renderer/platform/loader/fetch/resource.cc b/third_party/blink/renderer/platform/loader/fetch/resource.cc index b28da80..f60888c 100644 --- a/third_party/blink/renderer/platform/loader/fetch/resource.cc +++ b/third_party/blink/renderer/platform/loader/fetch/resource.cc
@@ -925,9 +925,9 @@ String Resource::GetMemoryDumpName() const { return String::Format( - "web_cache/%s_resources/%ld", - ResourceTypeToString(GetType(), Options().initiator_info.name), - identifier_); + "web_cache/%s_resources/", + ResourceTypeToString(GetType(), Options().initiator_info.name)) + + String::Number(identifier_); } void Resource::SetCachePolicyBypassingCache() {
diff --git a/third_party/blink/renderer/platform/loader/fetch/resource.h b/third_party/blink/renderer/platform/loader/fetch/resource.h index 1a72132..c22b9330 100644 --- a/third_party/blink/renderer/platform/loader/fetch/resource.h +++ b/third_party/blink/renderer/platform/loader/fetch/resource.h
@@ -168,8 +168,8 @@ return *error_; } - void SetIdentifier(unsigned long identifier) { identifier_ = identifier; } - unsigned long Identifier() const { return identifier_; } + void SetIdentifier(uint64_t identifier) { identifier_ = identifier; } + uint64_t Identifier() const { return identifier_; } virtual bool ShouldIgnoreHTTPStatusCodeErrors() const { return false; } @@ -533,7 +533,7 @@ TimeTicks load_response_end_; - unsigned long identifier_; + uint64_t identifier_; size_t encoded_size_; size_t encoded_size_memory_usage_;
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 7bd6eb81..fd8f5d0 100644 --- a/third_party/blink/renderer/platform/loader/fetch/resource_fetcher.cc +++ b/third_party/blink/renderer/platform/loader/fetch/resource_fetcher.cc
@@ -257,20 +257,20 @@ std::unique_ptr<TracedValue> BeginResourceLoadData( const blink::ResourceRequest& request) { - std::unique_ptr<TracedValue> value = TracedValue::Create(); + auto value = std::make_unique<TracedValue>(); value->SetString("url", request.Url().GetString()); return value; } std::unique_ptr<TracedValue> EndResourceLoadFailData() { - std::unique_ptr<TracedValue> value = TracedValue::Create(); + auto value = std::make_unique<TracedValue>(); value->SetString("outcome", "Fail"); return value; } std::unique_ptr<TracedValue> ResourcePrioritySetData( blink::ResourceLoadPriority priority) { - std::unique_ptr<TracedValue> value = TracedValue::Create(); + auto value = std::make_unique<TracedValue>(); value->SetInteger("priority", static_cast<int>(priority)); return value; } @@ -544,7 +544,7 @@ return policy != kUse || resource->StillNeedsLoad(); } -void ResourceFetcher::RequestLoadStarted(unsigned long identifier, +void ResourceFetcher::RequestLoadStarted(uint64_t identifier, Resource* resource, const FetchParameters& params, RevalidationPolicy policy, @@ -583,7 +583,7 @@ } void ResourceFetcher::DidLoadResourceFromMemoryCache( - unsigned long identifier, + uint64_t identifier, Resource* resource, const ResourceRequest& original_request) { ResourceRequest request = original_request; @@ -742,7 +742,7 @@ base::Optional<ResourceRequestBlockedReason> ResourceFetcher::PrepareRequest( FetchParameters& params, const ResourceFactory& factory, - unsigned long identifier, + uint64_t identifier, WebScopedVirtualTimePauser& virtual_time_pauser) { ResourceRequest& resource_request = params.MutableResourceRequest(); ResourceType resource_type = factory.GetType(); @@ -882,7 +882,7 @@ Resource* ResourceFetcher::RequestResource(FetchParameters& params, const ResourceFactory& factory, ResourceClient* client) { - unsigned long identifier = CreateUniqueIdentifier(); + uint64_t identifier = CreateUniqueIdentifier(); ResourceRequest& resource_request = params.MutableResourceRequest(); TRACE_EVENT_NESTABLE_ASYNC_BEGIN1( TRACE_DISABLED_BY_DEFAULT("network"), "ResourceLoad",
diff --git a/third_party/blink/renderer/platform/loader/fetch/resource_fetcher.h b/third_party/blink/renderer/platform/loader/fetch/resource_fetcher.h index 6ec99063..6145c62 100644 --- a/third_party/blink/renderer/platform/loader/fetch/resource_fetcher.h +++ b/third_party/blink/renderer/platform/loader/fetch/resource_fetcher.h
@@ -267,7 +267,7 @@ base::Optional<ResourceRequestBlockedReason> PrepareRequest( FetchParameters&, const ResourceFactory&, - unsigned long identifier, + uint64_t identifier, WebScopedVirtualTimePauser& virtual_time_pauser); Resource* ResourceForStaticData(const FetchParameters&, @@ -315,13 +315,13 @@ void MoveResourceLoaderToNonBlocking(ResourceLoader*); void RemoveResourceLoader(ResourceLoader*); - void RequestLoadStarted(unsigned long identifier, + void RequestLoadStarted(uint64_t identifier, Resource*, const FetchParameters&, RevalidationPolicy, bool is_static_data = false); - void DidLoadResourceFromMemoryCache(unsigned long identifier, + void DidLoadResourceFromMemoryCache(uint64_t identifier, Resource*, const ResourceRequest&);
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 5491f27..8bc6a4c1 100644 --- a/third_party/blink/renderer/platform/loader/fetch/resource_loader.cc +++ b/third_party/blink/renderer/platform/loader/fetch/resource_loader.cc
@@ -84,7 +84,7 @@ enum RequestOutcome { kSuccess, kFail }; std::unique_ptr<TracedValue> EndResourceLoadData(RequestOutcome outcome) { - std::unique_ptr<TracedValue> value = TracedValue::Create(); + auto value = std::make_unique<TracedValue>(); switch (outcome) { case RequestOutcome::kSuccess: value->SetString("outcome", "Success");
diff --git a/third_party/blink/renderer/platform/loader/fetch/unique_identifier.cc b/third_party/blink/renderer/platform/loader/fetch/unique_identifier.cc index 67cb66ab..6a581e6 100644 --- a/third_party/blink/renderer/platform/loader/fetch/unique_identifier.cc +++ b/third_party/blink/renderer/platform/loader/fetch/unique_identifier.cc
@@ -34,9 +34,9 @@ namespace blink { -static std::atomic_ulong g_unique_identifier(1); +static std::atomic_uint64_t g_unique_identifier(1); -unsigned long CreateUniqueIdentifier() { +uint64_t CreateUniqueIdentifier() { return g_unique_identifier.fetch_add(1, std::memory_order_relaxed); }
diff --git a/third_party/blink/renderer/platform/loader/fetch/unique_identifier.h b/third_party/blink/renderer/platform/loader/fetch/unique_identifier.h index b408454b..7427475 100644 --- a/third_party/blink/renderer/platform/loader/fetch/unique_identifier.h +++ b/third_party/blink/renderer/platform/loader/fetch/unique_identifier.h
@@ -35,7 +35,7 @@ namespace blink { -PLATFORM_EXPORT unsigned long CreateUniqueIdentifier(); +PLATFORM_EXPORT uint64_t CreateUniqueIdentifier(); } #endif // THIRD_PARTY_BLINK_RENDERER_PLATFORM_LOADER_FETCH_UNIQUE_IDENTIFIER_H_
diff --git a/third_party/blink/renderer/platform/loader/testing/mock_fetch_context.h b/third_party/blink/renderer/platform/loader/testing/mock_fetch_context.h index de4c5ba..8cf13a26 100644 --- a/third_party/blink/renderer/platform/loader/testing/mock_fetch_context.h +++ b/third_party/blink/renderer/platform/loader/testing/mock_fetch_context.h
@@ -41,7 +41,7 @@ // FetchContext: void DispatchWillSendRequest( - unsigned long identifier, + uint64_t identifier, const ResourceRequest& request, const ResourceResponse& redirect_response, ResourceType,
diff --git a/third_party/blink/renderer/platform/network/network_state_notifier.cc b/third_party/blink/renderer/platform/network/network_state_notifier.cc index 82d47a1..3e09249 100644 --- a/third_party/blink/renderer/platform/network/network_state_notifier.cc +++ b/third_party/blink/renderer/platform/network/network_state_notifier.cc
@@ -431,7 +431,7 @@ return random_multiplier; } -unsigned long NetworkStateNotifier::RoundRtt( +uint32_t NetworkStateNotifier::RoundRtt( const String& host, const base::Optional<TimeDelta>& rtt) const { // Limit the size of the buckets and the maximum reported value to reduce
diff --git a/third_party/blink/renderer/platform/network/network_state_notifier.h b/third_party/blink/renderer/platform/network/network_state_notifier.h index c8ec8d0df..92634c3b5 100644 --- a/third_party/blink/renderer/platform/network/network_state_notifier.h +++ b/third_party/blink/renderer/platform/network/network_state_notifier.h
@@ -255,8 +255,8 @@ // Returns |rtt| after adding host-specific random noise, and rounding it as // per the NetInfo spec to improve privacy. - unsigned long RoundRtt(const String& host, - const base::Optional<TimeDelta>& rtt) const; + uint32_t RoundRtt(const String& host, + const base::Optional<TimeDelta>& rtt) const; // Returns |downlink_mbps| after adding host-specific random noise, and // rounding it as per the NetInfo spec and to improve privacy.
diff --git a/third_party/blink/renderer/platform/partition_alloc_memory_dump_provider.cc b/third_party/blink/renderer/platform/partition_alloc_memory_dump_provider.cc index d4d5ec5..745da19 100644 --- a/third_party/blink/renderer/platform/partition_alloc_memory_dump_provider.cc +++ b/third_party/blink/renderer/platform/partition_alloc_memory_dump_provider.cc
@@ -7,6 +7,7 @@ #include <unordered_map> #include "base/allocator/partition_allocator/partition_alloc.h" +#include "base/format_macros.h" #include "base/strings/stringprintf.h" #include "base/trace_event/process_memory_dump.h" #include "third_party/blink/renderer/platform/wtf/allocator/partitions.h" @@ -47,7 +48,7 @@ private: base::trace_event::ProcessMemoryDump* memory_dump_; - unsigned long uid_; + uint64_t uid_; size_t total_active_bytes_; DISALLOW_COPY_AND_ASSIGN(PartitionStatsDumperImpl); @@ -80,10 +81,10 @@ DCHECK(memory_stats->is_valid); std::string dump_name = GetPartitionDumpName(partition_name); if (memory_stats->is_direct_map) { - dump_name.append(base::StringPrintf("/directMap_%lu", ++uid_)); + dump_name.append(base::StringPrintf("/directMap_%" PRIu64, ++uid_)); } else { - dump_name.append(base::StringPrintf( - "/bucket_%u", static_cast<unsigned>(memory_stats->bucket_slot_size))); + dump_name.append( + base::StringPrintf("/bucket_%" PRIu32, memory_stats->bucket_slot_size)); } base::trace_event::MemoryAllocatorDump* allocator_dump =
diff --git a/third_party/blink/renderer/platform/probe/platform_probes.pidl b/third_party/blink/renderer/platform/probe/platform_probes.pidl index 6f6ed59..5c07ec4 100644 --- a/third_party/blink/renderer/platform/probe/platform_probes.pidl +++ b/third_party/blink/renderer/platform/probe/platform_probes.pidl
@@ -8,5 +8,5 @@ class ResourceResponse; struct FetchInitiatorInfo; - PlatformSendRequest([Keep] FetchContext*, unsigned long identifier, ResourceRequest&, const ResourceResponse& redirect_response, const FetchInitiatorInfo&); + PlatformSendRequest([Keep] FetchContext*, uint64_t identifier, ResourceRequest&, const ResourceResponse& redirect_response, const FetchInitiatorInfo&); }
diff --git a/third_party/blink/renderer/platform/probe/platform_trace_events_agent.cc b/third_party/blink/renderer/platform/probe/platform_trace_events_agent.cc index da2a3d23..f57f049 100644 --- a/third_party/blink/renderer/platform/probe/platform_trace_events_agent.cc +++ b/third_party/blink/renderer/platform/probe/platform_trace_events_agent.cc
@@ -14,7 +14,7 @@ std::unique_ptr<TracedValue> BuildData( const probe::PlatformSendRequest& probe) { - std::unique_ptr<TracedValue> value = TracedValue::Create(); + auto value = std::make_unique<TracedValue>(); value->SetString("id", String::Number(probe.identifier)); return value; }
diff --git a/third_party/blink/renderer/platform/runtime_enabled_features.json5 b/third_party/blink/renderer/platform/runtime_enabled_features.json5 index 31427f58..61b56b1c 100644 --- a/third_party/blink/renderer/platform/runtime_enabled_features.json5 +++ b/third_party/blink/renderer/platform/runtime_enabled_features.json5
@@ -1214,6 +1214,11 @@ name: "RTCRtpSenderParameters", status: "stable", }, + // Enables the use of the RTCSctpTransport object. + { + name: "RTCSctpTransport", + status: "test", + }, { name: "RTCStatsRelativePacketArrivalDelay", origin_trial_feature_name: "RTCStatsRelativePacketArrivalDelay", @@ -1230,6 +1235,9 @@ { name: "RTCUnifiedPlanByDefault", }, + { + name: "ScheduledScriptStreaming", + }, // WebSpeech API with both speech recognition and synthesis functionality // is not fully enabled on all platforms. {
diff --git a/third_party/blink/renderer/platform/scheduler/BUILD.gn b/third_party/blink/renderer/platform/scheduler/BUILD.gn index 5668e06..d99d4da 100644 --- a/third_party/blink/renderer/platform/scheduler/BUILD.gn +++ b/third_party/blink/renderer/platform/scheduler/BUILD.gn
@@ -37,7 +37,6 @@ "common/thread_load_tracker.cc", "common/thread_load_tracker.h", "common/thread_scheduler.cc", - "common/thread_scheduler_impl.cc", "common/thread_scheduler_impl.h", "common/throttling/budget_pool.cc", "common/throttling/budget_pool.h",
diff --git a/third_party/blink/renderer/platform/scheduler/common/metrics_helper.cc b/third_party/blink/renderer/platform/scheduler/common/metrics_helper.cc index 1576919..2d57044 100644 --- a/third_party/blink/renderer/platform/scheduler/common/metrics_helper.cc +++ b/third_party/blink/renderer/platform/scheduler/common/metrics_helper.cc
@@ -35,6 +35,7 @@ case WebThreadType::kHRTFDatabaseLoaderThread: case WebThreadType::kOfflineAudioRenderThread: case WebThreadType::kReverbConvolutionBackgroundThread: + case WebThreadType::kScriptStreamerThread: case WebThreadType::kSharedWorkerThread: case WebThreadType::kUnspecifiedWorkerThread: case WebThreadType::kWebAudioThread:
diff --git a/third_party/blink/renderer/platform/scheduler/common/thread_scheduler_impl.cc b/third_party/blink/renderer/platform/scheduler/common/thread_scheduler_impl.cc deleted file mode 100644 index 8d3ec2f..0000000 --- a/third_party/blink/renderer/platform/scheduler/common/thread_scheduler_impl.cc +++ /dev/null
@@ -1,22 +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 "third_party/blink/renderer/platform/scheduler/common/thread_scheduler_impl.h" - -#include "third_party/blink/renderer/platform/scheduler/common/scheduler_helper.h" - -namespace blink { -namespace scheduler { - -ThreadSchedulerImpl::ThreadSchedulerImpl() {} - -ThreadSchedulerImpl::~ThreadSchedulerImpl() = default; - -scoped_refptr<base::SingleThreadTaskRunner> -ThreadSchedulerImpl::DeprecatedDefaultTaskRunner() { - return DefaultTaskRunner(); -} - -} // namespace scheduler -} // namespace blink
diff --git a/third_party/blink/renderer/platform/scheduler/common/thread_scheduler_impl.h b/third_party/blink/renderer/platform/scheduler/common/thread_scheduler_impl.h index 8c99a9b6..5943e5d 100644 --- a/third_party/blink/renderer/platform/scheduler/common/thread_scheduler_impl.h +++ b/third_party/blink/renderer/platform/scheduler/common/thread_scheduler_impl.h
@@ -51,12 +51,9 @@ virtual const base::TickClock* GetTickClock() = 0; - scoped_refptr<base::SingleThreadTaskRunner> DeprecatedDefaultTaskRunner() - override; - protected: - ThreadSchedulerImpl(); - ~ThreadSchedulerImpl() override; + ThreadSchedulerImpl() {} + ~ThreadSchedulerImpl() override = default; }; } // namespace scheduler
diff --git a/third_party/blink/renderer/platform/scheduler/common/web_thread_scheduler.cc b/third_party/blink/renderer/platform/scheduler/common/web_thread_scheduler.cc index 1646b092..81ae7652 100644 --- a/third_party/blink/renderer/platform/scheduler/common/web_thread_scheduler.cc +++ b/third_party/blink/renderer/platform/scheduler/common/web_thread_scheduler.cc
@@ -81,6 +81,12 @@ return nullptr; } +scoped_refptr<base::SingleThreadTaskRunner> +WebThreadScheduler::DeprecatedDefaultTaskRunner() { + NOTREACHED(); + return nullptr; +} + std::unique_ptr<Thread> WebThreadScheduler::CreateMainThread() { NOTREACHED(); return nullptr;
diff --git a/third_party/blink/renderer/platform/scheduler/main_thread/frame_scheduler_impl.cc b/third_party/blink/renderer/platform/scheduler/main_thread/frame_scheduler_impl.cc index fa9dabe3..a2e2d6e 100644 --- a/third_party/blink/renderer/platform/scheduler/main_thread/frame_scheduler_impl.cc +++ b/third_party/blink/renderer/platform/scheduler/main_thread/frame_scheduler_impl.cc
@@ -185,13 +185,20 @@ this, &tracing_controller_, YesNoStateToString), - active_connection_count_(0), + aggressive_throttling_opt_out_count(0), + opted_out_from_aggressive_throttling_( + false, + "FrameScheduler.AggressiveThrottlingDisabled", + this, + &tracing_controller_, + YesNoStateToString), subresource_loading_pause_count_(0u), - has_active_connection_(false, - "FrameScheduler.HasActiveConnection", - this, - &tracing_controller_, - YesNoStateToString), + opted_out_from_back_forward_cache_( + false, + "FrameScheduler.OptedOutFromBackForwardCache", + this, + &tracing_controller_, + YesNoStateToString), page_frozen_for_tracing_( parent_page_scheduler_ ? parent_page_scheduler_->IsFrozen() : true, "FrameScheduler.PageFrozen", @@ -232,7 +239,6 @@ queue->DetachFromMainThreadScheduler(); queue->DetachFromFrameScheduler(); queue->SetBlameContext(nullptr); - queue->ShutdownTaskQueueGracefully(); } } // namespace @@ -252,8 +258,8 @@ if (parent_page_scheduler_) { parent_page_scheduler_->Unregister(this); - if (has_active_connection()) - parent_page_scheduler_->OnConnectionUpdated(); + if (opted_out_from_aggressive_throttling()) + parent_page_scheduler_->OnAggressiveThrottlingStatusUpdated(); } } @@ -615,29 +621,54 @@ // TODO(altimin): Rename *ActiveConnection to // Enable/DisableAggressiveThrottling. if (policy.disable_aggressive_throttling) - DidOpenActiveConnection(); + OnAddedAggressiveThrottlingOptOut(); + if (policy.disable_back_forward_cache) + OnAddedBackForwardCacheOptOut(feature); } void FrameSchedulerImpl::OnStoppedUsingFeature( SchedulingPolicy::Feature feature, const SchedulingPolicy& policy) { if (policy.disable_aggressive_throttling) - DidCloseActiveConnection(); + OnRemovedAggressiveThrottlingOptOut(); + if (policy.disable_back_forward_cache) + OnRemovedBackForwardCacheOptOut(feature); } -void FrameSchedulerImpl::DidOpenActiveConnection() { - ++active_connection_count_; - has_active_connection_ = static_cast<bool>(active_connection_count_); +void FrameSchedulerImpl::OnAddedAggressiveThrottlingOptOut() { + ++aggressive_throttling_opt_out_count; + opted_out_from_aggressive_throttling_ = + static_cast<bool>(aggressive_throttling_opt_out_count); if (parent_page_scheduler_) - parent_page_scheduler_->OnConnectionUpdated(); + parent_page_scheduler_->OnAggressiveThrottlingStatusUpdated(); } -void FrameSchedulerImpl::DidCloseActiveConnection() { - DCHECK_GT(active_connection_count_, 0); - --active_connection_count_; - has_active_connection_ = static_cast<bool>(active_connection_count_); +void FrameSchedulerImpl::OnRemovedAggressiveThrottlingOptOut() { + DCHECK_GT(aggressive_throttling_opt_out_count, 0); + --aggressive_throttling_opt_out_count; + opted_out_from_aggressive_throttling_ = + static_cast<bool>(aggressive_throttling_opt_out_count); if (parent_page_scheduler_) - parent_page_scheduler_->OnConnectionUpdated(); + parent_page_scheduler_->OnAggressiveThrottlingStatusUpdated(); +} + +void FrameSchedulerImpl::OnAddedBackForwardCacheOptOut( + SchedulingPolicy::Feature feature) { + ++back_forward_cache_opt_out_counts_[feature]; + opted_out_from_back_forward_cache_ = true; +} + +void FrameSchedulerImpl::OnRemovedBackForwardCacheOptOut( + SchedulingPolicy::Feature feature) { + DCHECK_GT(back_forward_cache_opt_out_counts_[feature], 0); + auto it = back_forward_cache_opt_out_counts_.find(feature); + if (it->second == 1) { + back_forward_cache_opt_out_counts_.erase(it); + } else { + --it->second; + } + opted_out_from_back_forward_cache_ = + !back_forward_cache_opt_out_counts_.empty(); } void FrameSchedulerImpl::AsValueInto( @@ -755,7 +786,7 @@ if (subresource_loading_paused_ && type == ObserverType::kLoader) return SchedulingLifecycleState::kStopped; if (type == ObserverType::kLoader && - parent_page_scheduler_->HasActiveConnection()) { + parent_page_scheduler_->OptedOutFromAggressiveThrottling()) { return SchedulingLifecycleState::kNotThrottled; } if (parent_page_scheduler_->IsThrottled()) @@ -795,7 +826,7 @@ } bool FrameSchedulerImpl::IsExemptFromBudgetBasedThrottling() const { - return has_active_connection(); + return opted_out_from_aggressive_throttling(); } TaskQueue::QueuePriority FrameSchedulerImpl::ComputePriority( @@ -985,6 +1016,14 @@ } } +WTF::HashSet<SchedulingPolicy::Feature> +FrameSchedulerImpl::GetActiveFeaturesOptingOutFromBackForwardCache() { + WTF::HashSet<SchedulingPolicy::Feature> result; + for (const auto& it : back_forward_cache_opt_out_counts_) + result.insert(it.first); + return result; +} + // static MainThreadTaskQueue::QueueTraits FrameSchedulerImpl::ThrottleableTaskQueueTraits() {
diff --git a/third_party/blink/renderer/platform/scheduler/main_thread/frame_scheduler_impl.h b/third_party/blink/renderer/platform/scheduler/main_thread/frame_scheduler_impl.h index 5207abb..76d49b6 100644 --- a/third_party/blink/renderer/platform/scheduler/main_thread/frame_scheduler_impl.h +++ b/third_party/blink/renderer/platform/scheduler/main_thread/frame_scheduler_impl.h
@@ -9,6 +9,7 @@ #include <memory> #include <utility> +#include "base/containers/flat_map.h" #include "base/macros.h" #include "base/memory/scoped_refptr.h" #include "base/memory/weak_ptr.h" @@ -121,7 +122,9 @@ void UpdatePolicy(); - bool has_active_connection() const { return has_active_connection_; } + bool opted_out_from_aggressive_throttling() const { + return opted_out_from_aggressive_throttling_; + } void OnTraceLogEnabled() { tracing_controller_.OnTraceLogEnabled(); } @@ -157,6 +160,13 @@ static void InitializeTaskTypeQueueTraitsMap( FrameTaskTypeToQueueTraitsArray&); + WTF::HashSet<SchedulingPolicy::Feature> + GetActiveFeaturesOptingOutFromBackForwardCache(); + + // Expose for testing. + using FrameOrWorkerScheduler::OnStartedUsingFeature; + using FrameOrWorkerScheduler::OnStoppedUsingFeature; + protected: FrameSchedulerImpl(MainThreadSchedulerImpl* main_thread_scheduler, PageSchedulerImpl* parent_page_scheduler, @@ -220,8 +230,11 @@ void AddPauseSubresourceLoadingHandle(); void RemovePauseSubresourceLoadingHandle(); - void DidOpenActiveConnection(); - void DidCloseActiveConnection(); + void OnAddedAggressiveThrottlingOptOut(); + void OnRemovedAggressiveThrottlingOptOut(); + + void OnAddedBackForwardCacheOptOut(SchedulingPolicy::Feature feature); + void OnRemovedBackForwardCacheOptOut(SchedulingPolicy::Feature feature); std::unique_ptr<ResourceLoadingTaskRunnerHandleImpl> CreateResourceLoadingTaskRunnerHandleImpl(); @@ -274,10 +287,15 @@ StateTracer<TracingCategoryName::kInfo> url_tracer_; TraceableState<bool, TracingCategoryName::kInfo> task_queues_throttled_; // TODO(kraynov): https://crbug.com/827113 - // Trace active connection count. - int active_connection_count_; + // Trace the count of aggressive throttling opt outs. + int aggressive_throttling_opt_out_count; + TraceableState<bool, TracingCategoryName::kInfo> + opted_out_from_aggressive_throttling_; size_t subresource_loading_pause_count_; - TraceableState<bool, TracingCategoryName::kInfo> has_active_connection_; + base::flat_map<SchedulingPolicy::Feature, int> + back_forward_cache_opt_out_counts_; + TraceableState<bool, TracingCategoryName::kInfo> + opted_out_from_back_forward_cache_; // These are the states of the Page. // They should be accessed via GetPageScheduler()->SetPageState().
diff --git a/third_party/blink/renderer/platform/scheduler/main_thread/frame_scheduler_impl_unittest.cc b/third_party/blink/renderer/platform/scheduler/main_thread/frame_scheduler_impl_unittest.cc index 0e25125..432b944 100644 --- a/third_party/blink/renderer/platform/scheduler/main_thread/frame_scheduler_impl_unittest.cc +++ b/third_party/blink/renderer/platform/scheduler/main_thread/frame_scheduler_impl_unittest.cc
@@ -93,6 +93,7 @@ } void TearDown() override { + throttleable_task_queue_.reset(); frame_scheduler_.reset(); page_scheduler_.reset(); scheduler_->Shutdown(); @@ -269,9 +270,8 @@ ++*counter; } -void RecordQueueName(const scoped_refptr<TaskQueue> task_queue, - std::vector<std::string>* tasks) { - tasks->push_back(task_queue->GetName()); +void RecordQueueName(std::string name, std::vector<std::string>* tasks) { + tasks->push_back(std::move(name)); } // Simulate running a task of a particular length by fast forwarding the task @@ -568,18 +568,20 @@ TEST_F(FrameSchedulerImplTest, PageFreezeWithKeepActive) { std::vector<std::string> tasks; LoadingTaskQueue()->task_runner()->PostTask( - FROM_HERE, base::BindOnce(&RecordQueueName, LoadingTaskQueue(), &tasks)); + FROM_HERE, + base::BindOnce(&RecordQueueName, LoadingTaskQueue()->GetName(), &tasks)); ThrottleableTaskQueue()->task_runner()->PostTask( - FROM_HERE, - base::BindOnce(&RecordQueueName, ThrottleableTaskQueue(), &tasks)); + FROM_HERE, base::BindOnce(&RecordQueueName, + ThrottleableTaskQueue()->GetName(), &tasks)); DeferrableTaskQueue()->task_runner()->PostTask( - FROM_HERE, - base::BindOnce(&RecordQueueName, DeferrableTaskQueue(), &tasks)); + FROM_HERE, base::BindOnce(&RecordQueueName, + DeferrableTaskQueue()->GetName(), &tasks)); PausableTaskQueue()->task_runner()->PostTask( - FROM_HERE, base::BindOnce(&RecordQueueName, PausableTaskQueue(), &tasks)); - UnpausableTaskQueue()->task_runner()->PostTask( FROM_HERE, - base::BindOnce(&RecordQueueName, UnpausableTaskQueue(), &tasks)); + base::BindOnce(&RecordQueueName, PausableTaskQueue()->GetName(), &tasks)); + UnpausableTaskQueue()->task_runner()->PostTask( + FROM_HERE, base::BindOnce(&RecordQueueName, + UnpausableTaskQueue()->GetName(), &tasks)); page_scheduler_->SetKeepActive(true); // say we have a Service Worker page_scheduler_->SetPageVisible(false); @@ -596,7 +598,8 @@ tasks.clear(); LoadingTaskQueue()->task_runner()->PostTask( - FROM_HERE, base::BindOnce(&RecordQueueName, LoadingTaskQueue(), &tasks)); + FROM_HERE, + base::BindOnce(&RecordQueueName, LoadingTaskQueue()->GetName(), &tasks)); EXPECT_THAT(tasks, UnorderedElementsAre()); base::RunLoop().RunUntilIdle(); @@ -606,7 +609,8 @@ tasks.clear(); LoadingTaskQueue()->task_runner()->PostTask( - FROM_HERE, base::BindOnce(&RecordQueueName, LoadingTaskQueue(), &tasks)); + FROM_HERE, + base::BindOnce(&RecordQueueName, LoadingTaskQueue()->GetName(), &tasks)); // KeepActive is false when Service Worker stops. page_scheduler_->SetKeepActive(false); EXPECT_THAT(tasks, UnorderedElementsAre()); @@ -1779,8 +1783,8 @@ true)); task_queue = GetTaskQueue(TaskType::kDatabaseAccess); - EXPECT_EQ(task_queue->GetQueueTraits(), MainThreadTaskQueue::QueueTraits() - .SetCanBePaused(true)); + EXPECT_EQ(task_queue->GetQueueTraits(), + MainThreadTaskQueue::QueueTraits().SetCanBePaused(true)); task_queue = GetTaskQueue(TaskType::kDOMManipulation); EXPECT_EQ(task_queue->GetQueueTraits(), MainThreadTaskQueue::QueueTraits() @@ -1884,8 +1888,8 @@ MainThreadTaskQueue::QueueTraits().SetCanBePaused(true)); task_queue = GetTaskQueue(TaskType::kDatabaseAccess); - EXPECT_EQ(task_queue->GetQueueTraits(), MainThreadTaskQueue::QueueTraits() - .SetCanBePaused(true)); + EXPECT_EQ(task_queue->GetQueueTraits(), + MainThreadTaskQueue::QueueTraits().SetCanBePaused(true)); task_queue = GetTaskQueue(TaskType::kDOMManipulation); EXPECT_EQ(
diff --git a/third_party/blink/renderer/platform/scheduler/main_thread/main_thread_scheduler_helper.cc b/third_party/blink/renderer/platform/scheduler/main_thread/main_thread_scheduler_helper.cc index b410cfe..962954d 100644 --- a/third_party/blink/renderer/platform/scheduler/main_thread/main_thread_scheduler_helper.cc +++ b/third_party/blink/renderer/platform/scheduler/main_thread/main_thread_scheduler_helper.cc
@@ -16,6 +16,8 @@ MainThreadSchedulerImpl* main_thread_scheduler) : SchedulerHelper(std::move(sequence_manager)), main_thread_scheduler_(main_thread_scheduler), + // TODO(hajimehoshi): Forbid V8 execution at |default_task_queue_| + // (crbug.com/870606). default_task_queue_( NewTaskQueue(MainThreadTaskQueue::QueueCreationParams( MainThreadTaskQueue::QueueType::kDefault) @@ -52,6 +54,13 @@ return control_task_queue_; } +scoped_refptr<base::SingleThreadTaskRunner> +MainThreadSchedulerHelper::DeprecatedDefaultTaskRunner() { + // TODO(hajimehoshi): Introduce a different task queue from the default task + // queue and return the task runner created from it. + return DefaultTaskRunner(); +} + scoped_refptr<MainThreadTaskQueue> MainThreadSchedulerHelper::NewTaskQueue( const MainThreadTaskQueue::QueueCreationParams& params) { scoped_refptr<MainThreadTaskQueue> task_queue =
diff --git a/third_party/blink/renderer/platform/scheduler/main_thread/main_thread_scheduler_helper.h b/third_party/blink/renderer/platform/scheduler/main_thread/main_thread_scheduler_helper.h index f911d92..41e19c5 100644 --- a/third_party/blink/renderer/platform/scheduler/main_thread/main_thread_scheduler_helper.h +++ b/third_party/blink/renderer/platform/scheduler/main_thread/main_thread_scheduler_helper.h
@@ -26,6 +26,7 @@ scoped_refptr<MainThreadTaskQueue> DefaultMainThreadTaskQueue(); scoped_refptr<MainThreadTaskQueue> ControlMainThreadTaskQueue(); + scoped_refptr<base::SingleThreadTaskRunner> DeprecatedDefaultTaskRunner(); protected: scoped_refptr<base::sequence_manager::TaskQueue> DefaultTaskQueue() override;
diff --git a/third_party/blink/renderer/platform/scheduler/main_thread/main_thread_scheduler_impl.cc b/third_party/blink/renderer/platform/scheduler/main_thread/main_thread_scheduler_impl.cc index 4a16b91467..35aae64 100644 --- a/third_party/blink/renderer/platform/scheduler/main_thread/main_thread_scheduler_impl.cc +++ b/third_party/blink/renderer/platform/scheduler/main_thread/main_thread_scheduler_impl.cc
@@ -639,6 +639,11 @@ } scoped_refptr<base::SingleThreadTaskRunner> +MainThreadSchedulerImpl::DeprecatedDefaultTaskRunner() { + return helper_.DeprecatedDefaultTaskRunner(); +} + +scoped_refptr<base::SingleThreadTaskRunner> MainThreadSchedulerImpl::VirtualTimeControlTaskRunner() { return virtual_time_control_task_queue_->task_runner(); }
diff --git a/third_party/blink/renderer/platform/scheduler/main_thread/main_thread_scheduler_impl.h b/third_party/blink/renderer/platform/scheduler/main_thread/main_thread_scheduler_impl.h index 72fbf47..922ae59 100644 --- a/third_party/blink/renderer/platform/scheduler/main_thread/main_thread_scheduler_impl.h +++ b/third_party/blink/renderer/platform/scheduler/main_thread/main_thread_scheduler_impl.h
@@ -160,6 +160,8 @@ // Note: this is also shared by the ThreadScheduler interface. scoped_refptr<base::SingleThreadTaskRunner> IPCTaskRunner() override; scoped_refptr<base::SingleThreadTaskRunner> CleanupTaskRunner() override; + scoped_refptr<base::SingleThreadTaskRunner> DeprecatedDefaultTaskRunner() + override; std::unique_ptr<WebRenderWidgetSchedulingState> NewRenderWidgetSchedulingState() override; void WillBeginFrame(const viz::BeginFrameArgs& args) override;
diff --git a/third_party/blink/renderer/platform/scheduler/main_thread/main_thread_scheduler_impl_unittest.cc b/third_party/blink/renderer/platform/scheduler/main_thread/main_thread_scheduler_impl_unittest.cc index d75c6de..2fffdab 100644 --- a/third_party/blink/renderer/platform/scheduler/main_thread/main_thread_scheduler_impl_unittest.cc +++ b/third_party/blink/renderer/platform/scheduler/main_thread/main_thread_scheduler_impl_unittest.cc
@@ -370,6 +370,8 @@ } void TearDown() override { + loading_task_queue_.reset(); + timer_task_queue_.reset(); main_frame_scheduler_.reset(); page_scheduler_.reset(); scheduler_->Shutdown();
diff --git a/third_party/blink/renderer/platform/scheduler/main_thread/page_scheduler_impl.cc b/third_party/blink/renderer/platform/scheduler/main_thread/page_scheduler_impl.cc index 9737b18c..4ae82ef 100644 --- a/third_party/blink/renderer/platform/scheduler/main_thread/page_scheduler_impl.cc +++ b/third_party/blink/renderer/platform/scheduler/main_thread/page_scheduler_impl.cc
@@ -117,7 +117,7 @@ audio_state_(AudioState::kSilent), is_frozen_(false), reported_background_throttling_since_navigation_(false), - has_active_connection_(false), + opted_out_from_aggressive_throttling_(false), nested_runloop_(false), is_main_frame_local_(false), is_throttled_(false), @@ -396,16 +396,28 @@ } } +WTF::HashSet<SchedulingPolicy::Feature> +PageSchedulerImpl::GetActiveFeaturesOptingOutFromBackForwardCache() const { + WTF::HashSet<SchedulingPolicy::Feature> result; + for (FrameSchedulerImpl* frame_scheduler : frame_schedulers_) { + for (SchedulingPolicy::Feature feature : + frame_scheduler->GetActiveFeaturesOptingOutFromBackForwardCache()) { + result.insert(feature); + } + } + return result; +} + bool PageSchedulerImpl::IsExemptFromBudgetBasedThrottling() const { - return has_active_connection_; + return opted_out_from_aggressive_throttling_; } -bool PageSchedulerImpl::HasActiveConnectionForTest() const { - return HasActiveConnection(); +bool PageSchedulerImpl::OptedOutFromAggressiveThrottlingForTest() const { + return OptedOutFromAggressiveThrottling(); } -bool PageSchedulerImpl::HasActiveConnection() const { - return has_active_connection_; +bool PageSchedulerImpl::OptedOutFromAggressiveThrottling() const { + return opted_out_from_aggressive_throttling_; } bool PageSchedulerImpl::RequestBeginMainFrameNotExpected(bool new_state) { @@ -431,14 +443,17 @@ return is_throttled_; } -void PageSchedulerImpl::OnConnectionUpdated() { - bool has_active_connection = false; +void PageSchedulerImpl::OnAggressiveThrottlingStatusUpdated() { + bool opted_out_from_aggressive_throttling = false; for (FrameSchedulerImpl* frame_scheduler : frame_schedulers_) { - has_active_connection |= frame_scheduler->has_active_connection(); + opted_out_from_aggressive_throttling |= + frame_scheduler->opted_out_from_aggressive_throttling(); } - if (has_active_connection_ != has_active_connection) { - has_active_connection_ = has_active_connection; + if (opted_out_from_aggressive_throttling_ != + opted_out_from_aggressive_throttling) { + opted_out_from_aggressive_throttling_ = + opted_out_from_aggressive_throttling; UpdateBackgroundBudgetPoolSchedulingLifecycleState(); } } @@ -554,7 +569,7 @@ base::sequence_manager::LazyNow lazy_now( main_thread_scheduler_->tick_clock()); - if (is_throttled_ && !has_active_connection_) { + if (is_throttled_ && !opted_out_from_aggressive_throttling_) { background_time_budget_pool_->EnableThrottling(&lazy_now); } else { background_time_budget_pool_->DisableThrottling(&lazy_now);
diff --git a/third_party/blink/renderer/platform/scheduler/main_thread/page_scheduler_impl.h b/third_party/blink/renderer/platform/scheduler/main_thread/page_scheduler_impl.h index 74df996..4d99d82 100644 --- a/third_party/blink/renderer/platform/scheduler/main_thread/page_scheduler_impl.h +++ b/third_party/blink/renderer/platform/scheduler/main_thread/page_scheduler_impl.h
@@ -74,8 +74,10 @@ int max_task_starvation_count) override; void AudioStateChanged(bool is_audio_playing) override; bool IsAudioPlaying() const override; + WTF::HashSet<SchedulingPolicy::Feature> + GetActiveFeaturesOptingOutFromBackForwardCache() const override; bool IsExemptFromBudgetBasedThrottling() const override; - bool HasActiveConnectionForTest() const override; + bool OptedOutFromAggressiveThrottlingForTest() const override; bool RequestBeginMainFrameNotExpected(bool new_state) override; // Virtual for testing. @@ -83,9 +85,9 @@ bool IsPageVisible() const; bool IsFrozen() const; - // PageSchedulerImpl::HasActiveConnection can be used in non-test code, - // while PageScheduler::HasActiveConnectionForTest can't. - bool HasActiveConnection() const; + // PageSchedulerImpl::OptedOutFromAggressiveThrottling can be used in non-test + // code, while PageScheduler::OptedOutFromAggressiveThrottlingForTest can't. + bool OptedOutFromAggressiveThrottling() const; // Note that the frame can throttle queues even when the page is not throttled // (e.g. for offscreen frames or recently backgrounded pages). bool IsThrottled() const; @@ -104,7 +106,7 @@ void Unregister(FrameSchedulerImpl*); void OnNavigation(); - void OnConnectionUpdated(); + void OnAggressiveThrottlingStatusUpdated(); void OnTraceLogEnabled(); @@ -244,7 +246,7 @@ AudioState audio_state_; bool is_frozen_; bool reported_background_throttling_since_navigation_; - bool has_active_connection_; + bool opted_out_from_aggressive_throttling_; bool nested_runloop_; bool is_main_frame_local_; bool is_throttled_;
diff --git a/third_party/blink/renderer/platform/scheduler/main_thread/page_scheduler_impl_unittest.cc b/third_party/blink/renderer/platform/scheduler/main_thread/page_scheduler_impl_unittest.cc index f718d03..9642ce0 100644 --- a/third_party/blink/renderer/platform/scheduler/main_thread/page_scheduler_impl_unittest.cc +++ b/third_party/blink/renderer/platform/scheduler/main_thread/page_scheduler_impl_unittest.cc
@@ -29,9 +29,9 @@ #include "third_party/blink/renderer/platform/scheduler/main_thread/page_visibility_state.h" #include "third_party/blink/renderer/platform/testing/runtime_enabled_features_test_helpers.h" -using base::sequence_manager::TaskQueue; using base::sequence_manager::FakeTask; using base::sequence_manager::FakeTaskTiming; +using base::sequence_manager::TaskQueue; using testing::ElementsAre; using VirtualTimePolicy = blink::PageScheduler::VirtualTimePolicy; @@ -251,28 +251,27 @@ namespace { -void RunRepeatingTask(scoped_refptr<TaskQueue>, +void RunRepeatingTask(scoped_refptr<base::SingleThreadTaskRunner>, int* run_count, base::TimeDelta delay); -base::OnceClosure MakeRepeatingTask(scoped_refptr<TaskQueue> task_queue, - int* run_count, - base::TimeDelta delay) { - return base::BindOnce(&RunRepeatingTask, std::move(task_queue), +base::OnceClosure MakeRepeatingTask( + scoped_refptr<base::SingleThreadTaskRunner> task_runner, + int* run_count, + base::TimeDelta delay) { + return base::BindOnce(&RunRepeatingTask, std::move(task_runner), base::Unretained(run_count), delay); } -void RunRepeatingTask(scoped_refptr<TaskQueue> task_queue, +void RunRepeatingTask(scoped_refptr<base::SingleThreadTaskRunner> task_runner, int* run_count, base::TimeDelta delay) { // Limit the number of repetitions. // Test cases can make expectations against this number. if (++*run_count == 2000) return; - TaskQueue* task_queue_ptr = task_queue.get(); - task_queue_ptr->task_runner()->PostDelayedTask( - FROM_HERE, MakeRepeatingTask(std::move(task_queue_ptr), run_count, delay), - delay); + task_runner->PostDelayedTask( + FROM_HERE, MakeRepeatingTask(task_runner, run_count, delay), delay); } } // namespace @@ -283,7 +282,7 @@ int run_count = 0; ThrottleableTaskQueue()->task_runner()->PostDelayedTask( FROM_HERE, - MakeRepeatingTask(ThrottleableTaskQueue(), &run_count, + MakeRepeatingTask(ThrottleableTaskQueue()->task_runner(), &run_count, base::TimeDelta::FromMilliseconds(1)), base::TimeDelta::FromMilliseconds(1)); @@ -297,7 +296,7 @@ int run_count = 0; ThrottleableTaskQueue()->task_runner()->PostDelayedTask( FROM_HERE, - MakeRepeatingTask(ThrottleableTaskQueue(), &run_count, + MakeRepeatingTask(ThrottleableTaskQueue()->task_runner(), &run_count, base::TimeDelta::FromMilliseconds(20)), base::TimeDelta::FromMilliseconds(20)); @@ -319,7 +318,7 @@ int run_count = 0; LoadingTaskQueue()->task_runner()->PostDelayedTask( FROM_HERE, - MakeRepeatingTask(LoadingTaskQueue(), &run_count, + MakeRepeatingTask(LoadingTaskQueue()->task_runner(), &run_count, base::TimeDelta::FromMilliseconds(1)), base::TimeDelta::FromMilliseconds(1)); @@ -341,7 +340,7 @@ int run_count2 = 0; ThrottleableTaskQueue()->task_runner()->PostDelayedTask( FROM_HERE, - MakeRepeatingTask(ThrottleableTaskQueue(), &run_count1, + MakeRepeatingTask(ThrottleableTaskQueue()->task_runner(), &run_count1, base::TimeDelta::FromMilliseconds(20)), base::TimeDelta::FromMilliseconds(20)); ThrottleableTaskQueueForScheduler(frame_scheduler2.get()) @@ -349,7 +348,8 @@ ->PostDelayedTask( FROM_HERE, MakeRepeatingTask( - ThrottleableTaskQueueForScheduler(frame_scheduler2.get()), + ThrottleableTaskQueueForScheduler(frame_scheduler2.get()) + ->task_runner(), &run_count2, base::TimeDelta::FromMilliseconds(20)), base::TimeDelta::FromMilliseconds(20)); @@ -477,7 +477,7 @@ int run_count = 0; ThrottleableTaskQueue()->task_runner()->PostDelayedTask( FROM_HERE, - MakeRepeatingTask(ThrottleableTaskQueue(), &run_count, + MakeRepeatingTask(ThrottleableTaskQueue()->task_runner(), &run_count, base::TimeDelta::FromMilliseconds(1)), base::TimeDelta::FromMilliseconds(1)); @@ -497,13 +497,14 @@ out_run_order->push_back(index); } -void DelayedRunOrderTask(int index, - scoped_refptr<TaskQueue> task_queue, - std::vector<int>* out_run_order) { +void DelayedRunOrderTask( + int index, + scoped_refptr<base::SingleThreadTaskRunner> task_runner, + std::vector<int>* out_run_order) { out_run_order->push_back(index); - task_queue->task_runner()->PostTask( - FROM_HERE, base::BindOnce(&RunOrderTask, index + 1, - base::Unretained(out_run_order))); + task_runner->PostTask(FROM_HERE, + base::BindOnce(&RunOrderTask, index + 1, + base::Unretained(out_run_order))); } } // namespace @@ -519,13 +520,15 @@ ThrottleableTaskQueue()->task_runner()->PostDelayedTask( FROM_HERE, - base::BindOnce(&DelayedRunOrderTask, 1, ThrottleableTaskQueue(), + base::BindOnce(&DelayedRunOrderTask, 1, + ThrottleableTaskQueue()->task_runner(), base::Unretained(&run_order)), base::TimeDelta::FromMilliseconds(2)); ThrottleableTaskQueue()->task_runner()->PostDelayedTask( FROM_HERE, - base::BindOnce(&DelayedRunOrderTask, 3, ThrottleableTaskQueue(), + base::BindOnce(&DelayedRunOrderTask, 3, + ThrottleableTaskQueue()->task_runner(), base::Unretained(&run_order)), base::TimeDelta::FromMilliseconds(4)); @@ -547,13 +550,15 @@ ThrottleableTaskQueue()->task_runner()->PostDelayedTask( FROM_HERE, - base::BindOnce(&DelayedRunOrderTask, 1, ThrottleableTaskQueue(), + base::BindOnce(&DelayedRunOrderTask, 1, + ThrottleableTaskQueue()->task_runner(), base::Unretained(&run_order)), base::TimeDelta::FromMilliseconds(2)); ThrottleableTaskQueue()->task_runner()->PostDelayedTask( FROM_HERE, - base::BindOnce(&DelayedRunOrderTask, 3, ThrottleableTaskQueue(), + base::BindOnce(&DelayedRunOrderTask, 3, + ThrottleableTaskQueue()->task_runner(), base::Unretained(&run_order)), base::TimeDelta::FromMilliseconds(4)); @@ -569,7 +574,7 @@ int run_count = 0; ThrottleableTaskQueue()->task_runner()->PostDelayedTask( FROM_HERE, - MakeRepeatingTask(ThrottleableTaskQueue(), &run_count, + MakeRepeatingTask(ThrottleableTaskQueue()->task_runner(), &run_count, base::TimeDelta::FromMilliseconds(1)), base::TimeDelta::FromMilliseconds(1)); @@ -645,7 +650,7 @@ int run_count = 0; timer_task_queue->task_runner()->PostDelayedTask( FROM_HERE, - MakeRepeatingTask(timer_task_queue, &run_count, + MakeRepeatingTask(timer_task_queue->task_runner(), &run_count, base::TimeDelta::FromMilliseconds(100)), base::TimeDelta::FromMilliseconds(100)); @@ -916,15 +921,15 @@ } namespace { -void RepostingTask(scoped_refptr<TaskQueue> task_queue, +void RepostingTask(scoped_refptr<base::SingleThreadTaskRunner> task_runner, int max_count, int* count) { if (++(*count) >= max_count) return; - task_queue->task_runner()->PostTask( - FROM_HERE, base::BindOnce(&RepostingTask, task_queue, max_count, - base::Unretained(count))); + task_runner->PostTask(FROM_HERE, + base::BindOnce(&RepostingTask, task_runner, max_count, + base::Unretained(count))); } void DelayedTask(int* count_in, int* count_out) { @@ -940,7 +945,7 @@ int count = 0; int delayed_task_run_at_count = 0; - RepostingTask(ThrottleableTaskQueue(), 1000, &count); + RepostingTask(ThrottleableTaskQueue()->task_runner(), 1000, &count); ThrottleableTaskQueue()->task_runner()->PostDelayedTask( FROM_HERE, base::BindOnce(DelayedTask, base::Unretained(&count), @@ -975,7 +980,7 @@ int count = 0; int delayed_task_run_at_count = 0; - RepostingTask(ThrottleableTaskQueue(), 1000, &count); + RepostingTask(ThrottleableTaskQueue()->task_runner(), 1000, &count); ThrottleableTaskQueue()->task_runner()->PostDelayedTask( FROM_HERE, base::BindOnce(DelayedTask, base::Unretained(&count), @@ -1003,7 +1008,7 @@ int count = 0; int delayed_task_run_at_count = 0; - RepostingTask(ThrottleableTaskQueue(), 1000, &count); + RepostingTask(ThrottleableTaskQueue()->task_runner(), 1000, &count); ThrottleableTaskQueue()->task_runner()->PostDelayedTask( FROM_HERE, base::BindOnce(DelayedTask, base::Unretained(&count), @@ -1593,6 +1598,43 @@ UnorderedElementsAreArray(GetExpectedBuckets())); } +TEST_F(PageSchedulerImplTest, BackForwardCacheOptOut) { + EXPECT_THAT(page_scheduler_->GetActiveFeaturesOptingOutFromBackForwardCache(), + testing::UnorderedElementsAre()); + + frame_scheduler_->OnStartedUsingFeature( + SchedulingPolicy::Feature::kWebSocket, + {SchedulingPolicy::DisableBackForwardCache()}); + + EXPECT_THAT( + page_scheduler_->GetActiveFeaturesOptingOutFromBackForwardCache(), + testing::UnorderedElementsAre(SchedulingPolicy::Feature::kWebSocket)); + + frame_scheduler_->OnStartedUsingFeature( + SchedulingPolicy::Feature::kWebRTC, + {SchedulingPolicy::DisableBackForwardCache()}); + + EXPECT_THAT( + page_scheduler_->GetActiveFeaturesOptingOutFromBackForwardCache(), + testing::UnorderedElementsAre(SchedulingPolicy::Feature::kWebSocket, + SchedulingPolicy::Feature::kWebRTC)); + + frame_scheduler_->OnStoppedUsingFeature( + SchedulingPolicy::Feature::kWebSocket, + {SchedulingPolicy::DisableBackForwardCache()}); + + EXPECT_THAT( + page_scheduler_->GetActiveFeaturesOptingOutFromBackForwardCache(), + testing::UnorderedElementsAre(SchedulingPolicy::Feature::kWebRTC)); + + frame_scheduler_->OnStoppedUsingFeature( + SchedulingPolicy::Feature::kWebRTC, + {SchedulingPolicy::DisableBackForwardCache()}); + + EXPECT_THAT(page_scheduler_->GetActiveFeaturesOptingOutFromBackForwardCache(), + testing::UnorderedElementsAre()); +} + } // namespace page_scheduler_impl_unittest } // namespace scheduler } // namespace blink
diff --git a/third_party/blink/renderer/platform/scheduler/public/page_scheduler.h b/third_party/blink/renderer/platform/scheduler/public/page_scheduler.h index 9be6b54..6551978 100644 --- a/third_party/blink/renderer/platform/scheduler/public/page_scheduler.h +++ b/third_party/blink/renderer/platform/scheduler/public/page_scheduler.h
@@ -10,7 +10,9 @@ #include "third_party/blink/renderer/platform/platform_export.h" #include "third_party/blink/renderer/platform/scheduler/public/frame_scheduler.h" #include "third_party/blink/renderer/platform/scheduler/public/page_lifecycle_state.h" +#include "third_party/blink/renderer/platform/scheduler/public/scheduling_policy.h" #include "third_party/blink/renderer/platform/wtf/functional.h" +#include "third_party/blink/renderer/platform/wtf/hash_set.h" #include "third_party/blink/renderer/platform/wtf/text/wtf_string.h" namespace blink { @@ -127,7 +129,13 @@ // (e.g. due to a page maintaining an active connection). virtual bool IsExemptFromBudgetBasedThrottling() const = 0; - virtual bool HasActiveConnectionForTest() const = 0; + // Returns a set of features which at the moment prevent page from going into + // back-forward cache. If this list is empty, the page is eligible for + // back-forward cache. + virtual WTF::HashSet<SchedulingPolicy::Feature> + GetActiveFeaturesOptingOutFromBackForwardCache() const = 0; + + virtual bool OptedOutFromAggressiveThrottlingForTest() const = 0; // Returns true if the request has been succcessfully relayed to the // compositor.
diff --git a/third_party/blink/renderer/platform/scheduler/public/scheduling_policy.h b/third_party/blink/renderer/platform/scheduler/public/scheduling_policy.h index b2ed405a..64d8d6d 100644 --- a/third_party/blink/renderer/platform/scheduler/public/scheduling_policy.h +++ b/third_party/blink/renderer/platform/scheduler/public/scheduling_policy.h
@@ -24,9 +24,11 @@ // List of opt-outs which form a policy. struct DisableAggressiveThrottling {}; + struct DisableBackForwardCache {}; struct ValidPolicies { ValidPolicies(DisableAggressiveThrottling); + ValidPolicies(DisableBackForwardCache); }; template <class... ArgTypes, @@ -36,11 +38,14 @@ constexpr SchedulingPolicy(ArgTypes... args) : disable_aggressive_throttling( base::trait_helpers::HasTrait<DisableAggressiveThrottling>( - args...)) {} + args...)), + disable_back_forward_cache( + base::trait_helpers::HasTrait<DisableBackForwardCache>(args...)) {} SchedulingPolicy() {} bool disable_aggressive_throttling = false; + bool disable_back_forward_cache = false; }; } // namespace blink
diff --git a/third_party/blink/renderer/platform/scheduler/test/fake_page_scheduler.h b/third_party/blink/renderer/platform/scheduler/test/fake_page_scheduler.h index 85368ccb..9a419e10 100644 --- a/third_party/blink/renderer/platform/scheduler/test/fake_page_scheduler.h +++ b/third_party/blink/renderer/platform/scheduler/test/fake_page_scheduler.h
@@ -71,10 +71,16 @@ base::OnceClosure callback) override {} void SetMaxVirtualTimeTaskStarvationCount(int count) override {} void AudioStateChanged(bool is_audio_playing) override {} - bool HasActiveConnectionForTest() const override { return false; } + bool OptedOutFromAggressiveThrottlingForTest() const override { + return false; + } bool RequestBeginMainFrameNotExpected(bool new_state) override { return false; } + WTF::HashSet<SchedulingPolicy::Feature> + GetActiveFeaturesOptingOutFromBackForwardCache() const override { + return WTF::HashSet<SchedulingPolicy::Feature>(); + } private: bool is_audio_playing_;
diff --git a/third_party/blink/renderer/platform/scheduler/test/renderer_scheduler_test_support.cc b/third_party/blink/renderer/platform/scheduler/test/renderer_scheduler_test_support.cc index e68586c..2f91a86e 100644 --- a/third_party/blink/renderer/platform/scheduler/test/renderer_scheduler_test_support.cc +++ b/third_party/blink/renderer/platform/scheduler/test/renderer_scheduler_test_support.cc
@@ -126,8 +126,14 @@ void AudioStateChanged(bool is_audio_playing) override {} bool IsAudioPlaying() const override { return false; } bool IsExemptFromBudgetBasedThrottling() const override { return false; } - bool HasActiveConnectionForTest() const override { return false; } + bool OptedOutFromAggressiveThrottlingForTest() const override { + return false; + } bool RequestBeginMainFrameNotExpected(bool) override { return false; } + WTF::HashSet<SchedulingPolicy::Feature> + GetActiveFeaturesOptingOutFromBackForwardCache() const override { + return WTF::HashSet<SchedulingPolicy::Feature>(); + } private: DISALLOW_COPY_AND_ASSIGN(SimplePageScheduler);
diff --git a/third_party/blink/renderer/platform/scheduler/worker/non_main_thread_scheduler_impl.cc b/third_party/blink/renderer/platform/scheduler/worker/non_main_thread_scheduler_impl.cc index ec6f870d..84ea95f 100644 --- a/third_party/blink/renderer/platform/scheduler/worker/non_main_thread_scheduler_impl.cc +++ b/third_party/blink/renderer/platform/scheduler/worker/non_main_thread_scheduler_impl.cc
@@ -106,5 +106,10 @@ return helper_.GetClock(); } +scoped_refptr<base::SingleThreadTaskRunner> +NonMainThreadSchedulerImpl::DeprecatedDefaultTaskRunner() { + return DefaultTaskRunner(); +} + } // namespace scheduler } // namespace blink
diff --git a/third_party/blink/renderer/platform/scheduler/worker/non_main_thread_scheduler_impl.h b/third_party/blink/renderer/platform/scheduler/worker/non_main_thread_scheduler_impl.h index c83092c..466d1f72 100644 --- a/third_party/blink/renderer/platform/scheduler/worker/non_main_thread_scheduler_impl.h +++ b/third_party/blink/renderer/platform/scheduler/worker/non_main_thread_scheduler_impl.h
@@ -85,6 +85,9 @@ scoped_refptr<NonMainThreadTaskQueue> CreateTaskQueue(const char* name); + scoped_refptr<base::SingleThreadTaskRunner> DeprecatedDefaultTaskRunner() + override; + protected: static void RunIdleTask(Thread::IdleTask task, base::TimeTicks deadline);
diff --git a/third_party/blink/renderer/platform/theme_types.h b/third_party/blink/renderer/platform/theme_types.h index caf5d4b..76f20d1e 100644 --- a/third_party/blink/renderer/platform/theme_types.h +++ b/third_party/blink/renderer/platform/theme_types.h
@@ -44,7 +44,7 @@ typedef unsigned ControlStates; -// Must follow CSSValueKeywords.in order +// Must follow css_value_keywords.json5 order enum ControlPart { kNoControlPart, kCheckboxPart, @@ -52,38 +52,21 @@ kPushButtonPart, kSquareButtonPart, kButtonPart, - kButtonBevelPart, kInnerSpinButtonPart, kListboxPart, - kListItemPart, - kMediaEnterFullscreenButtonPart, - kMediaExitFullscreenButtonPart, - kMediaMuteButtonPart, - kMediaPlayButtonPart, - kMediaOverlayPlayButtonPart, - kMediaToggleClosedCaptionsButtonPart, kMediaSliderPart, kMediaSliderThumbPart, - kMediaVolumeSliderContainerPart, kMediaVolumeSliderPart, kMediaVolumeSliderThumbPart, - kMediaControlsBackgroundPart, - kMediaControlsFullscreenBackgroundPart, - kMediaCurrentTimePart, - kMediaTimeRemainingPart, kMediaControlPart, kMenulistPart, kMenulistButtonPart, - kMenulistTextPart, - kMenulistTextFieldPart, kMeterPart, kProgressBarPart, - kProgressBarValuePart, kSliderHorizontalPart, kSliderVerticalPart, kSliderThumbHorizontalPart, kSliderThumbVerticalPart, - kCaretPart, kSearchFieldPart, kSearchFieldCancelButtonPart, kTextFieldPart,
diff --git a/third_party/blink/renderer/platform/transforms/transform_state.cc b/third_party/blink/renderer/platform/transforms/transform_state.cc index ac6b544e..2274bd73 100644 --- a/third_party/blink/renderer/platform/transforms/transform_state.cc +++ b/third_party/blink/renderer/platform/transforms/transform_state.cc
@@ -41,9 +41,10 @@ accumulated_transform_.reset(); - if (other.accumulated_transform_) + if (other.accumulated_transform_) { accumulated_transform_ = - TransformationMatrix::Create(*other.accumulated_transform_); + std::make_unique<TransformationMatrix>(*other.accumulated_transform_); + } return *this; } @@ -131,14 +132,14 @@ // transform if (accumulated_transform_) { if (direction_ == kApplyTransformDirection) - accumulated_transform_ = TransformationMatrix::Create( + accumulated_transform_ = std::make_unique<TransformationMatrix>( transform_from_container * *accumulated_transform_); else accumulated_transform_->Multiply(transform_from_container); } else if (accumulate == kAccumulateTransform) { // Make one if we started to accumulate accumulated_transform_ = - TransformationMatrix::Create(transform_from_container); + std::make_unique<TransformationMatrix>(transform_from_container); } if (accumulate == kFlattenTransform) {
diff --git a/third_party/blink/renderer/platform/transforms/transform_state.h b/third_party/blink/renderer/platform/transforms/transform_state.h index 67ff5b0..fc534fa 100644 --- a/third_party/blink/renderer/platform/transforms/transform_state.h +++ b/third_party/blink/renderer/platform/transforms/transform_state.h
@@ -77,7 +77,7 @@ // Accumulate a transform but don't map any points directly. TransformState(TransformDirection mapping_direction) - : accumulated_transform_(TransformationMatrix::Create()), + : accumulated_transform_(std::make_unique<TransformationMatrix>()), accumulating_transform_(true), force_accumulating_transform_(true), map_point_(false),
diff --git a/third_party/blink/renderer/platform/transforms/transformation_matrix.h b/third_party/blink/renderer/platform/transforms/transformation_matrix.h index f039e1d2..bc6fb4c 100644 --- a/third_party/blink/renderer/platform/transforms/transformation_matrix.h +++ b/third_party/blink/renderer/platform/transforms/transformation_matrix.h
@@ -84,42 +84,6 @@ Column columns[4]; }; - static std::unique_ptr<TransformationMatrix> Create() { - return std::make_unique<TransformationMatrix>(); - } - static std::unique_ptr<TransformationMatrix> Create( - const TransformationMatrix& t) { - return std::make_unique<TransformationMatrix>(t); - } - static std::unique_ptr<TransformationMatrix> Create(double a, - double b, - double c, - double d, - double e, - double f) { - return std::make_unique<TransformationMatrix>(a, b, c, d, e, f); - } - static std::unique_ptr<TransformationMatrix> Create(double m11, - double m12, - double m13, - double m14, - double m21, - double m22, - double m23, - double m24, - double m31, - double m32, - double m33, - double m34, - double m41, - double m42, - double m43, - double m44) { - return std::make_unique<TransformationMatrix>(m11, m12, m13, m14, m21, m22, - m23, m24, m31, m32, m33, m34, - m41, m42, m43, m44); - } - TransformationMatrix() { CheckAlignment(); MakeIdentity();
diff --git a/third_party/blink/renderer/platform/web_thread_supporting_gc.cc b/third_party/blink/renderer/platform/web_thread_supporting_gc.cc index 5ad0322..00fe3b18 100644 --- a/third_party/blink/renderer/platform/web_thread_supporting_gc.cc +++ b/third_party/blink/renderer/platform/web_thread_supporting_gc.cc
@@ -13,11 +13,6 @@ namespace blink { -std::unique_ptr<WebThreadSupportingGC> WebThreadSupportingGC::Create( - const ThreadCreationParams& params) { - return base::WrapUnique(new WebThreadSupportingGC(params)); -} - WebThreadSupportingGC::WebThreadSupportingGC( const ThreadCreationParams& params) { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
diff --git a/third_party/blink/renderer/platform/web_thread_supporting_gc.h b/third_party/blink/renderer/platform/web_thread_supporting_gc.h index e4c927f70..275dd9c 100644 --- a/third_party/blink/renderer/platform/web_thread_supporting_gc.h +++ b/third_party/blink/renderer/platform/web_thread_supporting_gc.h
@@ -31,8 +31,7 @@ USING_FAST_MALLOC(WebThreadSupportingGC); public: - static std::unique_ptr<WebThreadSupportingGC> Create( - const ThreadCreationParams&); + explicit WebThreadSupportingGC(const ThreadCreationParams&); ~WebThreadSupportingGC(); void PostTask(const base::Location& location, base::OnceClosure task) { @@ -76,8 +75,6 @@ } private: - WebThreadSupportingGC(const ThreadCreationParams&); - std::unique_ptr<GCTaskRunner> gc_task_runner_; std::unique_ptr<Thread> thread_;
diff --git a/third_party/blink/renderer/platform/web_thread_type.cc b/third_party/blink/renderer/platform/web_thread_type.cc index 2c17a78..fd20b80 100644 --- a/third_party/blink/renderer/platform/web_thread_type.cc +++ b/third_party/blink/renderer/platform/web_thread_type.cc
@@ -33,6 +33,8 @@ return "Database thread"; case WebThreadType::kWebAudioThread: return "WebAudio thread"; + case WebThreadType::kScriptStreamerThread: + return "ScriptStreamer thread"; case WebThreadType::kOfflineAudioRenderThread: return "OfflineAudioRender thread"; case WebThreadType::kReverbConvolutionBackgroundThread:
diff --git a/third_party/blink/tools/blinkpy/web_tests/port/fuchsia.py b/third_party/blink/tools/blinkpy/web_tests/port/fuchsia.py index 5233f4d..dd5b0539 100644 --- a/third_party/blink/tools/blinkpy/web_tests/port/fuchsia.py +++ b/third_party/blink/tools/blinkpy/web_tests/port/fuchsia.py
@@ -146,24 +146,9 @@ ssh_args=forwarding_flags, stderr=subprocess.PIPE) - # Copy content_shell package to the device. - device_package_path = \ - os.path.join('/data', os.path.basename(CONTENT_SHELL_PACKAGE_PATH)) - self._target.PutFile( - os.path.join(build_path, CONTENT_SHELL_PACKAGE_PATH), - device_package_path) - - pm_install = self._target.RunCommandPiped( - ['pm', 'install', device_package_path], - stderr=subprocess.PIPE) - output = pm_install.stderr.readlines() - pm_install.wait() - - if pm_install.returncode != 0: - # Don't error out if the package already exists on the device. - if len(output) != 1 or 'ErrAlreadyExists' not in output[0]: - raise Exception('Failed to install content_shell: %s' % \ - '\n'.join(output)) + package_path = os.path.join(build_path, CONTENT_SHELL_PACKAGE_PATH) + self._target.InstallPackage(package_path, "content_shell", + package_deps=[]) # Process will be forked for each worker, which may make QemuTarget # unusable (e.g. waitpid() for qemu process returns ECHILD after
diff --git a/third_party/blink/web_tests/FlagExpectations/enable-blink-features=CompositeAfterPaint b/third_party/blink/web_tests/FlagExpectations/enable-blink-features=CompositeAfterPaint index b27e4cc..5da827ac 100644 --- a/third_party/blink/web_tests/FlagExpectations/enable-blink-features=CompositeAfterPaint +++ b/third_party/blink/web_tests/FlagExpectations/enable-blink-features=CompositeAfterPaint
@@ -170,6 +170,7 @@ Bug(none) paint/invalidation/compositing/should-not-repaint-composited-filter.html [ Failure ] Bug(none) paint/invalidation/compositing/should-not-repaint-composited-opacity.html [ Failure ] Bug(none) paint/invalidation/compositing/should-not-repaint-move-backface-hidden.html [ Failure ] +Bug(none) paint/invalidation/scroll/iframe-scroll-repaint.html [ Failure ] Bug(none) paint/invalidation/position/layout-state-only-positioned.html [ Failure ] Bug(none) paint/invalidation/position/relative-positioned-movement-repaint.html [ Failure ] Bug(none) paint/invalidation/svg/scrolling-embedded-svg-file-image-repaint-problem.html [ Failure ] @@ -263,7 +264,6 @@ crbug.com/738613 paint/invalidation/table/scroll-inside-table-cell.html [ Failure ] crbug.com/738613 paint/invalidation/table/table-overflow-auto-in-overflow-auto-scrolled.html [ Failure ] crbug.com/738613 paint/invalidation/table/table-overflow-scroll-in-overflow-scroll-scrolled.html [ Failure ] -crbug.com/738613 paint/invalidation/scroll/repaint-during-scroll-with-zoom.html [ Failure ] crbug.com/738613 paint/invalidation/scroll/resize-scrollable-iframe.html [ Failure ] crbug.com/738613 paint/invalidation/scroll/scrollbar-damage-and-full-viewport-repaint.html [ Failure ] crbug.com/738613 paint/invalidation/scroll/caret-invalidation-in-overflow-scroll.html [ Failure ] @@ -310,9 +310,8 @@ # content layers. crbug.com/931486 compositing/force-compositing-mode/overflow-iframe-enter-compositing.html [ Failure ] crbug.com/931486 compositing/force-compositing-mode/overflow-iframe-layer.html [ Failure ] +crbug.com/931486 compositing/iframes/overlapped-iframe-iframe.html [ Failure ] crbug.com/931486 compositing/overflow/scroll-parent-absolute-with-backdrop-filter.html [ Failure ] -crbug.com/931486 compositing/iframes/become-overlapped-iframe.html [ Failure ] -crbug.com/931486 compositing/iframes/resizer.html [ Failure ] crbug.com/931486 compositing/layer-creation/fixed-position-nonscrollable-body-mismatch-containers.html [ Failure ] crbug.com/931486 compositing/layer-creation/fixed-position-out-of-view-positioning.html [ Failure ] crbug.com/931486 compositing/layer-creation/overflow-scroll-overlap.html [ Failure ] @@ -325,7 +324,6 @@ crbug.com/931486 compositing/rtl/rtl-iframe-absolute-overflow.html [ Failure ] crbug.com/931486 paint/invalidation/scroll/fixed-child-move-after-scroll.html [ Failure ] crbug.com/931486 paint/invalidation/scroll/fixed-child-of-fixed-move-after-scroll.html [ Failure ] -crbug.com/931486 paint/invalidation/position/fixed-element-repaint-after-compositing-update.html [ Failure ] crbug.com/931486 paint/invalidation/position/fixed-tranformed.html [ Failure ] crbug.com/931486 paint/invalidation/scroll/inline-style-change-in-scrolled-view.html [ Failure ] crbug.com/931486 paint/invalidation/background/background-image-paint-invalidation.html [ Failure ]
diff --git a/third_party/blink/web_tests/FlagExpectations/enable-blink-features=LayoutNG b/third_party/blink/web_tests/FlagExpectations/enable-blink-features=LayoutNG index a602f09..3305c3f5e 100644 --- a/third_party/blink/web_tests/FlagExpectations/enable-blink-features=LayoutNG +++ b/third_party/blink/web_tests/FlagExpectations/enable-blink-features=LayoutNG
@@ -133,7 +133,7 @@ crbug.com/591099 external/wpt/css/CSS2/normal-flow/block-in-inline-remove-006.xht [ Pass ] crbug.com/591099 external/wpt/css/CSS2/text/white-space-mixed-003.xht [ Pass ] crbug.com/591099 external/wpt/css/css-animations/Element-getAnimations-dynamic-changes.tentative.html [ Failure ] -crbug.com/591099 external/wpt/css/css-animations/Element-getAnimations.tentative.html [ Failure Pass ] +crbug.com/591099 external/wpt/css/css-animations/Element-getAnimations.tentative.html [ Pass ] crbug.com/591099 external/wpt/css/css-contain/contain-size-grid-002.html [ Failure ] crbug.com/591099 external/wpt/css/css-contain/contain-size-multicol-001.html [ Failure ] crbug.com/591099 external/wpt/css/css-contain/contain-style-counters-004.html [ Failure ] @@ -142,6 +142,7 @@ crbug.com/591099 external/wpt/css/css-fonts/font-synthesis-05.html [ Failure ] crbug.com/591099 external/wpt/css/css-fonts/font-variant-alternates-03.html [ Failure ] crbug.com/591099 external/wpt/css/css-fonts/font-variant-position-01.html [ Failure ] +crbug.com/591099 external/wpt/css/css-grid/grid-items/grid-item-percentage-sizes-003.html [ Pass ] crbug.com/591099 external/wpt/css/css-grid/grid-model/grid-container-ignores-first-letter-002.html [ Failure ] crbug.com/919818 external/wpt/css/css-lists/list-and-block-textarea-001.html [ Failure ] crbug.com/591099 external/wpt/css/css-masking/clip-path-svg-content/mask-userspaceonuse-content-clip.svg [ Failure ] @@ -151,6 +152,7 @@ crbug.com/591099 external/wpt/css/css-multicol/multicol-span-all-005.html [ Failure ] crbug.com/591099 external/wpt/css/css-multicol/multicol-span-all-list-item-002.html [ Pass ] crbug.com/933054 external/wpt/css/css-position/position-absolute-container-dynamic-002.html [ Pass ] +crbug.com/591099 external/wpt/css/css-position/position-absolute-in-inline-001.html [ Pass ] crbug.com/591099 external/wpt/css/css-position/position-relative-table-tbody-top-absolute-child.html [ Failure ] crbug.com/591099 external/wpt/css/css-position/position-relative-table-tr-left-absolute-child.html [ Failure ] crbug.com/591099 external/wpt/css/css-position/static-position/htb-ltr-rtl.tentative.html [ Pass ] @@ -406,14 +408,13 @@ crbug.com/591099 external/wpt/referrer-policy/same-origin/http-rp/same-origin/http-http/shared-worker/keep-origin-redirect/same-origin-insecure.http.html [ Failure ] crbug.com/591099 external/wpt/screen-orientation/onchange-event.html [ Timeout ] crbug.com/591099 external/wpt/service-workers/service-worker/fetch-frame-resource.https.html [ Pass ] -crbug.com/591099 external/wpt/shadow-dom/untriaged/html-elements-in-shadow-trees/html-forms/test-003.html [ Failure Pass ] crbug.com/591099 external/wpt/svg/text/reftests/text-inline-size-101.svg [ Failure ] crbug.com/591099 external/wpt/wasm/webapi/rejected-arg.any.serviceworker.html [ Timeout ] crbug.com/591099 external/wpt/webauthn/createcredential-extensions.https.html [ Pass ] crbug.com/591099 external/wpt/webmessaging/with-ports/018.html [ Pass ] crbug.com/591099 external/wpt/webmessaging/without-ports/001.html [ Failure ] crbug.com/591099 external/wpt/webmessaging/without-ports/018.html [ Pass ] -crbug.com/591099 external/wpt/webrtc/RTCIceConnectionState-candidate-pair.https.html [ Timeout ] +crbug.com/591099 external/wpt/webrtc/RTCIceConnectionState-candidate-pair.https.html [ Pass Timeout ] crbug.com/591099 external/wpt/websockets/constructor/013.html [ Pass ] crbug.com/591099 external/wpt/websockets/constructor/013.html?wss [ Pass ] crbug.com/591099 external/wpt/websockets/interfaces/WebSocket/send/010.html [ Pass ] @@ -447,7 +448,7 @@ crbug.com/591099 fast/css-grid-layout/grid-baseline.html [ Failure ] crbug.com/591099 fast/css-intrinsic-dimensions/height-css-tables-collapsed.html [ Failure Pass ] crbug.com/591099 fast/css-intrinsic-dimensions/height-positioned.html [ Pass ] -crbug.com/591099 fast/css-intrinsic-dimensions/height-tables.html [ Failure Pass ] +crbug.com/591099 fast/css-intrinsic-dimensions/height-tables.html [ Pass ] crbug.com/591099 fast/css/absolute-inline-alignment-2.html [ Pass ] crbug.com/835484 fast/css/outline-narrowLine.html [ Failure ] crbug.com/855279 fast/css/text-overflow-ellipsis-vertical-hittest.html [ Pass ] @@ -455,7 +456,7 @@ crbug.com/591099 fast/dom/SelectorAPI/resig-SelectorsAPI-test.xhtml [ Pass ] crbug.com/591099 fast/dom/shadow/focus-controller-recursion-crash.html [ Pass ] crbug.com/591099 fast/dom/shadow/svg-style-in-shadow-tree-crash.html [ Pass ] -crbug.com/591099 fast/events/before-unload-return-value-from-listener.html [ Pass Timeout ] +crbug.com/591099 fast/events/before-unload-return-value-from-listener.html [ Pass ] crbug.com/591099 fast/events/touch/compositor-touch-hit-rects-continuation.html [ Failure ] crbug.com/591099 fast/events/touch/compositor-touch-hit-rects-list-translate.html [ Failure ] crbug.com/591099 fast/events/touch/compositor-touch-hit-rects.html [ Failure ] @@ -463,7 +464,8 @@ crbug.com/889721 fast/inline/outline-continuations.html [ Failure ] crbug.com/591099 fast/multicol/border-radius-clipped-layer.html [ Pass ] crbug.com/591099 fast/peerconnection/RTCPeerConnection-many.html [ Pass ] -crbug.com/591099 fast/replaced/replaced-breaking.html [ Failure Pass ] +crbug.com/591099 fast/replaced/replaced-breaking.html [ Failure ] +crbug.com/591099 fast/spatial-navigation/snav-keyboard-scrollers-search-origin-bug.html [ Crash ] crbug.com/899902 fast/text/ellipsis-with-self-painting-layer.html [ Pass ] crbug.com/591099 fast/text/emoji-vertical-origin-visual.html [ Failure ] crbug.com/591099 fast/text/font-format-support-color-cff2-vertical.html [ Failure ] @@ -481,6 +483,7 @@ crbug.com/591099 http/tests/devtools/elements/styles-1/edit-value-url-with-color.js [ Pass ] crbug.com/591099 http/tests/devtools/elements/user-properties.js [ Pass ] crbug.com/591099 http/tests/devtools/service-workers/service-worker-v8-cache.js [ Pass Timeout ] +crbug.com/591099 http/tests/devtools/sources/debugger-frameworks/frameworks-jquery.js [ Crash Pass ] crbug.com/591099 http/tests/devtools/sources/debugger/debugger-proto-property.js [ Pass ] crbug.com/591099 http/tests/devtools/tracing-session-id.js [ Pass ] crbug.com/591099 http/tests/devtools/tracing/console-timeline.js [ Pass ] @@ -496,9 +499,8 @@ crbug.com/591099 http/tests/html/validation-bubble-oopif-clip.html [ Pass ] crbug.com/591099 http/tests/images/feature-policy-unoptimized-images-cached-image.html [ Failure Pass ] crbug.com/591099 http/tests/images/image-decode-in-frame.html [ Pass ] -crbug.com/591099 http/tests/inspector-protocol/fetch/fetch-renderer.js [ Pass Timeout ] crbug.com/591099 http/tests/inspector-protocol/network/navigation-blocking-xorigin-iframe.js [ Failure Pass ] -crbug.com/591099 http/tests/media/autoplay/document-user-activation-cross-origin-feature-policy-disabled.html [ Failure Pass ] +crbug.com/591099 http/tests/media/autoplay/document-user-activation-cross-origin-feature-policy-disabled.html [ Failure ] crbug.com/591099 http/tests/media/video-load-metadata-decode-error.html [ Pass ] crbug.com/591099 http/tests/multipart/multipart-main-resource.html [ Pass ] crbug.com/591099 http/tests/security/isolatedWorld/media-query-wrapper-leaks.html [ Failure ] @@ -522,7 +524,7 @@ crbug.com/591099 storage/indexeddb/objectstore-cursor.html [ Pass ] crbug.com/591099 storage/indexeddb/structured-clone.html [ Pass ] crbug.com/591099 storage/websql/open-database-creation-callback-isolated-world.html [ Pass ] -crbug.com/591099 storage/websql/transaction-error-callback.html [ Pass Timeout ] +crbug.com/591099 storage/websql/transaction-error-callback.html [ Pass ] crbug.com/591099 svg/animations/svg-animation-policy-once.html [ Pass ] crbug.com/591099 svg/zoom/page/zoom-svg-float-border-padding.xml [ Pass ] crbug.com/591099 tables/mozilla/bugs/bug14159-1.html [ Pass ] @@ -530,7 +532,6 @@ crbug.com/591099 virtual/android/rootscroller/set-root-scroller.html [ Pass ] crbug.com/591099 virtual/android/rootscroller/set-rootscroller-before-load.html [ Pass ] crbug.com/591099 virtual/bidi-caret-affinity/editing/selection/modify_move/move-forward-after-line-break.html [ Failure ] -crbug.com/591099 virtual/bidi-caret-affinity/editing/selection/modify_move/move_left_character_23_ltr.html [ Failure Pass ] crbug.com/591099 virtual/bidi-caret-affinity/editing/selection/modify_move/move_left_word_05_ltr_multi_line.html [ Failure ] crbug.com/591099 virtual/bidi-caret-affinity/editing/selection/modify_move/move_left_word_09_ltr_multi_line.html [ Failure ] crbug.com/591099 virtual/bidi-caret-affinity/editing/selection/modify_move/move_left_word_09_rtl_multi_line.html [ Failure ]
diff --git a/third_party/blink/web_tests/SlowTests b/third_party/blink/web_tests/SlowTests index 9864cde..91473fb0 100644 --- a/third_party/blink/web_tests/SlowTests +++ b/third_party/blink/web_tests/SlowTests
@@ -234,6 +234,7 @@ crbug.com/372424 http/tests/serviceworker/registration-stress.html [ Slow ] crbug.com/448670 http/tests/serviceworker/register-different-script-many-times.html [ Slow ] crbug.com/516319 [ Win ] http/tests/fetch/ [ Slow ] +crbug.com/516319 [ Win ] virtual/outofblink-cors/http/tests/fetch/ [ Slow ] crbug.com/516319 [ Win ] virtual/streaming-preload/http/tests/fetch/ [ Slow ] # Most crypto/subtle tests are slow some or most of the time.
diff --git a/third_party/blink/web_tests/TestExpectations b/third_party/blink/web_tests/TestExpectations index f8dfa2d..8e258a7 100644 --- a/third_party/blink/web_tests/TestExpectations +++ b/third_party/blink/web_tests/TestExpectations
@@ -1800,6 +1800,9 @@ crbug.com/894651 virtual/bidi-caret-affinity/editing/selection/modify_move/move_left_word_08_rtl_multi_line.html [ Failure ] crbug.com/894651 virtual/bidi-caret-affinity/editing/selection/modify_move/move_left_word_09_ltr_multi_line.html [ Failure ] crbug.com/894651 virtual/bidi-caret-affinity/editing/selection/modify_move/move_left_word_09_rtl_multi_line.html [ Failure ] +crbug.com/894651 virtual/bidi-caret-affinity/editing/selection/modify_move/move_out_of_inline_block_multiline.html [ Failure ] +crbug.com/894651 virtual/bidi-caret-affinity/editing/selection/modify_move/move_out_of_inline_block_nested.html [ Failure ] +crbug.com/894651 virtual/bidi-caret-affinity/editing/selection/modify_move/move_out_of_inline_block_one_line.html [ Failure ] crbug.com/894651 virtual/bidi-caret-affinity/editing/selection/modify_move/move_right_word_01_ltr_multi_line.html [ Failure ] crbug.com/894651 virtual/bidi-caret-affinity/editing/selection/modify_move/move_right_word_01_rtl_multi_line.html [ Failure ] crbug.com/894651 virtual/bidi-caret-affinity/editing/selection/modify_move/move_right_word_02_ltr_multi_line.html [ Failure Crash ] @@ -3297,13 +3300,6 @@ crbug.com/626703 external/wpt/css/css-text/white-space/white-space-pre-wrap-trailing-spaces-003.html [ Failure ] crbug.com/626703 external/wpt/css/css-text/white-space/white-space-pre-wrap-trailing-spaces-002.html [ Failure ] crbug.com/626703 external/wpt/html/rendering/replaced-elements/the-select-element/select-1-line-height.html [ Failure ] -crbug.com/626703 external/wpt/wasm/webapi/rejected-arg.any.html [ Timeout ] -crbug.com/626703 external/wpt/wasm/webapi/rejected-arg.any.serviceworker.html [ Timeout ] -crbug.com/626703 external/wpt/wasm/webapi/rejected-arg.any.worker.html [ Timeout ] -crbug.com/626703 external/wpt/wasm/webapi/origin.sub.any.serviceworker.html [ Timeout ] -crbug.com/626703 external/wpt/wasm/webapi/rejected-arg.any.sharedworker.html [ Timeout ] -crbug.com/626703 external/wpt/wasm/webapi/abort.any.worker.html [ Timeout ] -crbug.com/626703 external/wpt/wasm/webapi/abort.any.html [ Timeout ] crbug.com/626703 external/wpt/css/css-will-change/will-change-abspos-cb-dynamic-001.html [ Failure ] crbug.com/626703 external/wpt/css/css-will-change/will-change-abspos-cb-001.html [ Failure ] crbug.com/626703 external/wpt/css/css-conditional/at-supports-040.html [ Failure ] @@ -4175,6 +4171,14 @@ crbug.com/626703 [ Win ] external/wpt/css/css-writing-modes/box-offsets-rel-pos-vlr-005.xht [ Failure ] crbug.com/626703 [ Win ] external/wpt/css/css-writing-modes/box-offsets-rel-pos-vrl-004.xht [ Failure ] +crbug.com/943487 external/wpt/wasm/webapi/rejected-arg.any.html [ Timeout ] +crbug.com/943487 external/wpt/wasm/webapi/rejected-arg.any.serviceworker.html [ Timeout ] +crbug.com/943487 external/wpt/wasm/webapi/rejected-arg.any.worker.html [ Timeout ] +crbug.com/943487 external/wpt/wasm/webapi/origin.sub.any.serviceworker.html [ Timeout ] +crbug.com/943487 external/wpt/wasm/webapi/rejected-arg.any.sharedworker.html [ Timeout ] +crbug.com/943487 external/wpt/wasm/webapi/abort.any.worker.html [ Timeout ] +crbug.com/943487 external/wpt/wasm/webapi/abort.any.html [ Timeout ] + crbug.com/792435 external/wpt/css/css-multicol/multicol-rule-004.xht [ Failure ] crbug.com/792437 external/wpt/css/css-multicol/multicol-rule-inset-000.xht [ Failure ] crbug.com/792437 external/wpt/css/css-multicol/multicol-rule-outset-000.xht [ Failure ] @@ -5162,7 +5166,8 @@ crbug.com/831685 [ Linux ] external/wpt/2dcontext/compositing/2d.composite.canvas.lighter.html [ Pass Timeout ] crbug.com/831673 http/tests/devtools/reveal-objects.js [ Pass Timeout ] crbug.com/831673 virtual/binary-for-devtools/http/tests/devtools/reveal-objects.js [ Pass Timeout ] -crbug.com/831496 virtual/gpu/fast/canvas/fillrect_gradient.html [ Pass Timeout ] +# Temporarily superceded to allow Failure for crbug.com/938592. +#crbug.com/831496 virtual/gpu/fast/canvas/fillrect_gradient.html [ Pass Timeout ] crbug.com/831482 [ Linux ] virtual/gpu-rasterization/images/cross-fade-background-size.html [ Pass Timeout ] crbug.com/831249 [ Linux ] virtual/gpu/fast/canvas/canvas-filter-svg-inline.html [ Pass Timeout ] crbug.com/829952 fast/webgl/texImage-imageBitmap-from-image-resize.html [ Pass Timeout ] @@ -6036,8 +6041,6 @@ crbug.com/934768 [ Mac ] virtual/binary-for-devtools/http/tests/devtools/tracing/worker-events.js [ Failure Pass ] crbug.com/934768 [ Mac ] virtual/threaded/http/tests/devtools/tracing/worker-events.js [ Failure Pass ] crbug.com/934818 virtual/threaded/http/tests/devtools/tracing/decode-resize.js [ Failure Pass ] -crbug.com/935027 http/tests/devtools/animation/animation-transition-setTiming-crash.js [ Crash Pass ] -crbug.com/935027 virtual/binary-for-devtools/http/tests/devtools/animation/animation-transition-setTiming-crash.js [ Crash Pass ] # Sheriff 2019-02-25 crbug.com/935587 [ Mac ] virtual/video-surface-layer/media/stable/video-object-fit-stable.html [ Failure Pass ] @@ -6129,9 +6132,6 @@ # Flaky failures due to <object> resources not always appearing in the timeline. crbug.com/941482 external/wpt/resource-timing/nested-context-navigations.html [ Pass Failure ] -# Sheriff 2019-03-11 -crbug.com/940136 virtual/outofblink-cors/http/tests/fetch/serviceworker/thorough/auth.html [ Pass Failure ] - # Test was blocking WPT importer crbug.com/941471 external/wpt/css/css-transforms/transform-flattening-001.html [ Pass Failure Crash ] @@ -6150,12 +6150,14 @@ crbug.com/942517 [ Linux ] virtual/binary-for-inspector-protocol/http/tests/inspector-protocol/fetch/fetch-renderer.js [ Timeout ] crbug.com/942517 [ Linux ] virtual/binary-for-inspector-protocol/http/tests/inspector-protocol/network/interception-multiclient.js [ Failure ] -crbug.com/943095 external/wpt/fetch/stale-while-revalidate/fetch.tentative.html [ Pass Timeout ] -crbug.com/943095 virtual/outofblink-cors/external/wpt/fetch/stale-while-revalidate/fetch.tentative.html [ Pass Timeout ] - # Trooper 2019-03-19 crbug.com/941482 [ Win ] virtual/omt-worker-fetch/external/wpt/resource-timing/nested-context-navigations.html [ Pass Failure ] crbug.com/943390 [ Win ] http/tests/security/mixedContent/empty-url-plugin-in-frame.html [ Pass Failure ] crbug.com/943390 [ Win ] virtual/outofblink-cors/http/tests/security/mixedContent/empty-url-plugin-in-frame.html [ Pass Failure ] crbug.com/943388 [ Win ] http/tests/devtools/network/network-recording-after-reload-with-screenshots-enabled.js [ Pass Failure ] crbug.com/943388 [ Win ] virtual/binary-for-devtools/http/tests/devtools/network/network-recording-after-reload-with-screenshots-enabled.js [ Pass Failure ] + +#Imperceptible gradient changes. Will rebaseline after Skia roll. +crbug.com/938592 virtual/gpu/fast/canvas/canvas-text-alignment.html [ Pass Failure ] +crbug.com/938592 virtual/gpu/fast/canvas/fillrect_gradient.html [ Pass Failure Timeout ] +
diff --git a/third_party/blink/web_tests/VirtualTestSuites b/third_party/blink/web_tests/VirtualTestSuites index 8963d3e..4ba8ae8 100644 --- a/third_party/blink/web_tests/VirtualTestSuites +++ b/third_party/blink/web_tests/VirtualTestSuites
@@ -470,6 +470,16 @@ "args": ["--blink-settings=darkMode=3,darkModeImagePolicy=2"] }, { + "prefix": "dark-mode", + "base": "paint/dark-mode/page-policy-all", + "args": ["--blink-settings=darkMode=3,darkModePagePolicy=0"] + }, + { + "prefix": "dark-mode", + "base": "paint/dark-mode/page-policy-background", + "args": ["--blink-settings=darkMode=3,darkModePagePolicy=1"] + }, + { "prefix": "outofblink-cors", "base": "external/wpt/fetch", "args": ["--enable-features=OutOfBlinkCors,NetworkService"]
diff --git a/third_party/blink/web_tests/animations/prefixed/animation-events-prefixed-01-expected.txt b/third_party/blink/web_tests/animations/prefixed/animation-events-prefixed-01-expected.txt deleted file mode 100644 index b259d6b4..0000000 --- a/third_party/blink/web_tests/animations/prefixed/animation-events-prefixed-01-expected.txt +++ /dev/null
@@ -1,2 +0,0 @@ -Tests that prefixed animation events are correctly fired. -PASS: All events have been received as expected.
diff --git a/third_party/blink/web_tests/animations/prefixed/animation-events-prefixed-01.html b/third_party/blink/web_tests/animations/prefixed/animation-events-prefixed-01.html index 649ce5a8..a6d8bba3 100644 --- a/third_party/blink/web_tests/animations/prefixed/animation-events-prefixed-01.html +++ b/third_party/blink/web_tests/animations/prefixed/animation-events-prefixed-01.html
@@ -1,70 +1,59 @@ <!DOCTYPE html> -<html> -<head> - <title>Tests that prefixed animation events are correctly fired.</title> - <style> - #box { - position: relative; - left: 100px; - top: 10px; - height: 100px; - width: 100px; - background-color: #999; - } +<title>Tests that prefixed animation events are correctly fired.</title> +<style> + #box { + position: relative; + left: 100px; + top: 10px; + height: 100px; + width: 100px; + background-color: #999; + } - .animate { - animation-duration: 0.3s; - animation-name: anim; - } + .animate { + animation-duration: 0.3s; + animation-name: anim; + } - @keyframes anim { - from { left: 200px; } - to { left: 300px; } - } - </style> - <script> - if (window.testRunner) { - testRunner.dumpAsText(); - testRunner.waitUntilDone(); - } + @keyframes anim { + from { left: 200px; } + to { left: 300px; } + } +</style> +<script src="../../resources/testharness.js"></script> +<script src="../../resources/testharnessreport.js"></script> +<script> +var startEventReceived = false; +var endEventReceived = false; - var startEventReceived = false; - var endEventReceived = false; +document.addEventListener('webkitAnimationStart', () => { + startEventReceived = true; +}); - document.addEventListener('webkitAnimationStart', function() { - startEventReceived = true; - }, false); +document.addEventListener('webkitAnimationEnd', () => { + endEventReceived = true; + document.getElementById('box').className = ''; + // Launch again the animation to catch the animation iteration events this time. + requestAnimationFrame(function () { + document.getElementById('box').style.webkitAnimationIterationCount = "infinite"; + document.getElementById('box').className = 'animate'; + }); +}); - document.addEventListener('webkitAnimationIteration', function() { - if (startEventReceived && endEventReceived) { - document.getElementById('result').innerHTML = 'PASS: All events have been received as expected.'; - if (window.testRunner) - testRunner.notifyDone(); - } - }, false); - - document.addEventListener('webkitAnimationEnd', function() { - endEventReceived = true; - document.getElementById('box').className = ''; - // Launch again the animation to catch the animation iteration events this time. - requestAnimationFrame(function () { - document.getElementById('box').style.webkitAnimationIterationCount = "infinite"; - document.getElementById('box').className = 'animate'; - }); - }, false); - - onload = function() - { +async_test(t => { + window.addEventListener("load", () => { + t.step(() => { // Animation begins once we append the DOM node to the document. var boxNode = document.createElement('div'); boxNode.id = 'box'; boxNode.className = 'animate'; document.body.appendChild(boxNode); - } - </script> -</head> -<body> -Tests that prefixed animation events are correctly fired. -<pre id="result">FAIL: No animation events received</pre> -</body> -</html> + + document.addEventListener('webkitAnimationIteration', () => { + assert_true (startEventReceived && endEventReceived); + t.done(); + }); + }); + }); +}, "Tests that prefixed animation events are correctly fired"); +</script>
diff --git a/third_party/blink/web_tests/animations/prefixed/animation-events-prefixed-02-expected.txt b/third_party/blink/web_tests/animations/prefixed/animation-events-prefixed-02-expected.txt deleted file mode 100644 index b8ce79b7..0000000 --- a/third_party/blink/web_tests/animations/prefixed/animation-events-prefixed-02-expected.txt +++ /dev/null
@@ -1,2 +0,0 @@ -Tests that unprefixed animation events are correctly fired when listeners are on both versions. -PASS: All events have been received as expected.
diff --git a/third_party/blink/web_tests/animations/prefixed/animation-events-prefixed-02.html b/third_party/blink/web_tests/animations/prefixed/animation-events-prefixed-02.html index 9a2ddeb..b601c1f 100644 --- a/third_party/blink/web_tests/animations/prefixed/animation-events-prefixed-02.html +++ b/third_party/blink/web_tests/animations/prefixed/animation-events-prefixed-02.html
@@ -1,90 +1,72 @@ <!DOCTYPE html> -<html> -<head> - <title>Tests that unprefixed animation events are correctly fired when listeners are on both versions.</title> - <style> - #box { - position: relative; - left: 100px; - top: 10px; - height: 100px; - width: 100px; - background-color: #999; - } +<title>Tests that unprefixed animation events are correctly fired when listeners are on both versions.</title> +<style> +#box { + position: relative; + left: 100px; + top: 10px; + height: 100px; + width: 100px; + background-color: #999; +} - .animate { - animation-duration: 0.3s; - animation-name: anim; - } +.animate { + animation-duration: 0.3s; + animation-name: anim; +} - @keyframes anim { - from { left: 200px; } - to { left: 300px; } - } - </style> - <script> - if (window.testRunner) { - testRunner.dumpAsText(); - testRunner.waitUntilDone(); - } +@keyframes anim { + from { left: 200px; } + to { left: 300px; } +} +</style> +<script src="../../resources/testharness.js"></script> +<script src="../../resources/testharnessreport.js"></script> +<script> +var startEventReceived = false; +var endEventReceived = false; +var prefixedEventReceived = 0; - function fail() { - document.getElementById('result').innerHTML = 'FAIL: Got ' + iterationEventReceived + ' animationCount events and ' - + prefixedEventReceived + ' prefixed events.'; - } +document.addEventListener('webkitAnimationStart', () => { + prefixedEventReceived++; +}); - var startEventReceived = false; - var endEventReceived = false; - var prefixedEventReceived = 0; +document.addEventListener('animationstart', () => { + startEventReceived = true; +}); - document.addEventListener('webkitAnimationStart', function() { - prefixedEventReceived++; - }, false); +document.addEventListener('webkitAnimationIteration', () => { + prefixedEventReceived++; +}); - document.addEventListener('animationstart', function() { - startEventReceived = true; - }, false); +document.addEventListener('webkitAnimationEnd', () => { + prefixedEventReceived++; +}); - document.addEventListener('animationiteration', function() { - if (startEventReceived && endEventReceived && prefixedEventReceived == 0) { - document.getElementById('result').innerHTML = 'PASS: All events have been received as expected.'; - } else - fail(); - if (window.testRunner) - testRunner.notifyDone(); - }, false); +document.addEventListener('animationend', () => { + endEventReceived = true; + document.getElementById('box').className = ''; - document.addEventListener('webkitAnimationIteration', function() { - prefixedEventReceived++; - }, false); + document.getElementById('box').offsetTop; // force style recalc - document.addEventListener('webkitAnimationEnd', function() { - prefixedEventReceived++; - }, false); + // Launch again the animation to catch the animation iteration events this time. + document.getElementById('box').style.animationIterationCount = "infinite"; + document.getElementById('box').className = 'animate'; +}); - document.addEventListener('animationend', function() { - endEventReceived = true; - document.getElementById('box').className = ''; - - document.getElementById('box').offsetTop; // force style recalc - - // Launch again the animation to catch the animation iteration events this time. - document.getElementById('box').style.animationIterationCount = "infinite"; - document.getElementById('box').className = 'animate'; - }, false); - - onload = function() - { +async_test(t => { + window.addEventListener("load", () => { + t.step(() => { // Animation begins once we append the DOM node to the document. var boxNode = document.createElement('div'); boxNode.id = 'box'; boxNode.className = 'animate'; document.body.appendChild(boxNode); - } - </script> -</head> -<body> -Tests that unprefixed animation events are correctly fired when listeners are on both versions. -<pre id="result">FAIL: No animation events received</pre> -</body> -</html> + document.addEventListener('animationiteration', () => { + assert_true(startEventReceived && endEventReceived && prefixedEventReceived == 0); + t.done(); + }); + }); + }); +}, "Tests that unprefixed animation events are correctly fired when listeners are on both versions"); +</script>
diff --git a/third_party/blink/web_tests/animations/prefixed/animation-events-prefixed-03-expected.txt b/third_party/blink/web_tests/animations/prefixed/animation-events-prefixed-03-expected.txt deleted file mode 100644 index 1dcdd352..0000000 --- a/third_party/blink/web_tests/animations/prefixed/animation-events-prefixed-03-expected.txt +++ /dev/null
@@ -1,2 +0,0 @@ -Tests that prefixed animation events are correctly fired when using html event listeners. -PASS: All events have been received as expected.
diff --git a/third_party/blink/web_tests/animations/prefixed/animation-events-prefixed-03.html b/third_party/blink/web_tests/animations/prefixed/animation-events-prefixed-03.html index 8d5e78f8..bafaef8c 100644 --- a/third_party/blink/web_tests/animations/prefixed/animation-events-prefixed-03.html +++ b/third_party/blink/web_tests/animations/prefixed/animation-events-prefixed-03.html
@@ -1,63 +1,57 @@ <!DOCTYPE html> -<html> -<head> - <title>Tests that prefixed animation events are correctly fired when using html event listeners.</title> - <style> - #box { - position: relative; - left: 100px; - top: 10px; - height: 100px; - width: 100px; - background-color: #999; - } +<title>Tests that prefixed animation events are correctly fired when using html event listeners.</title> +<style> +#box { + position: relative; + left: 100px; + top: 10px; + height: 100px; + width: 100px; + background-color: #999; +} - .animate { - animation-duration: 0.3s; - animation-name: anim; - } +.animate { + animation-duration: 0.3s; + animation-name: anim; +} - @keyframes anim { - from { left: 200px; } - to { left: 300px; } - } - </style> - <script> - if (window.testRunner) { - testRunner.dumpAsText(); - testRunner.waitUntilDone(); - } +@keyframes anim { + from { left: 200px; } + to { left: 300px; } +} +</style> +<script src="../../resources/testharness.js"></script> +<script src="../../resources/testharnessreport.js"></script> +<script> +var startEventReceived = false; +var endEventReceived = false; - var startEventReceived = false; - var endEventReceived = false; +function recordAnimationStart() { + startEventReceived = true; +} - function recordAnimationStart() { - startEventReceived = true; - } +function recordAnimationEnd() { + endEventReceived = true; + document.getElementById('box').className = ''; - function recordAnimationIteration() { - if (startEventReceived && endEventReceived) { - document.getElementById('result').innerHTML = 'PASS: All events have been received as expected.'; - if (window.testRunner) - testRunner.notifyDone(); - } - } + document.getElementById('box').offsetTop; // force style recalc - function recordAnimationEnd() { - endEventReceived = true; - document.getElementById('box').className = ''; + // Launch again the animation to catch the animation iteration events this time. + document.getElementById('box').style.animationIterationCount = "infinite"; + document.getElementById('box').className = 'animate'; +} - document.getElementById('box').offsetTop; // force style recalc - - // Launch again the animation to catch the animation iteration events this time. - document.getElementById('box').style.animationIterationCount = "infinite"; - document.getElementById('box').className = 'animate'; - } - </script> -</head> -<body> -Tests that prefixed animation events are correctly fired when using html event listeners. -<pre id="result">FAIL: No animation events received</pre> -<div id="box" onwebkitanimationstart="recordAnimationStart();" onwebkitanimationend="recordAnimationEnd();" onwebkitanimationiteration="recordAnimationIteration();" class="animate"></div> -</body> -</html> +async_test(t => { + window.addEventListener("load", () => { + const box = document.getElementById('box'); + box.addEventListener("animationiteration", () => { + t.step(() => { + assert_true(startEventReceived && endEventReceived); + t.done(); + }); + }); + }); +}, "Prefixed animation events should be fired with html event listeners"); +</script> +<div id="box" onwebkitanimationstart="recordAnimationStart();" +onwebkitanimationend="recordAnimationEnd();"class="animate"></div>
diff --git a/third_party/blink/web_tests/animations/prefixed/animation-events-prefixed-04-expected.txt b/third_party/blink/web_tests/animations/prefixed/animation-events-prefixed-04-expected.txt deleted file mode 100644 index 9724610..0000000 --- a/third_party/blink/web_tests/animations/prefixed/animation-events-prefixed-04-expected.txt +++ /dev/null
@@ -1,4 +0,0 @@ -Tests that custom events with prefixed animations names are correctly dispatched. -PASS: webkitAnimationStart event listener has been called. -PASS: webkitAnimationIteration event listener has been called. -PASS: webkitAnimationEnd event has been called.
diff --git a/third_party/blink/web_tests/animations/prefixed/animation-events-prefixed-04.html b/third_party/blink/web_tests/animations/prefixed/animation-events-prefixed-04.html index 0e1913cee..724cd8d 100644 --- a/third_party/blink/web_tests/animations/prefixed/animation-events-prefixed-04.html +++ b/third_party/blink/web_tests/animations/prefixed/animation-events-prefixed-04.html
@@ -1,48 +1,39 @@ <!DOCTYPE html> -<html> -<head> - <title>Tests that custom events with prefixed animations names are correctly dispatched.</title> - <script> - if (window.testRunner) { - testRunner.dumpAsText(); - testRunner.waitUntilDone(); - } - - document.addEventListener('animationstart', function(e) { - document.getElementById('result').innerHTML += 'FAIL: animationstart event listener should not have been called.<br>'; - }, false); - - document.addEventListener('webkitAnimationStart', function(e) { - document.getElementById('result').innerHTML += 'PASS: webkitAnimationStart event listener has been called.<br>'; - }, false); - - document.addEventListener('animationiteration', function(e) { - document.getElementById('result').innerHTML += 'FAIL: animationiteration event listener should not have been called.<br>'; - }, false); - - document.addEventListener('webkitAnimationIteration', function(e) { - document.getElementById('result').innerHTML += 'PASS: webkitAnimationIteration event listener has been called.<br>'; - }, false); - - document.addEventListener('animationend', function(e) { - document.getElementById('result').innerHTML += 'FAIL: animationend event listener should not have been called.'; - if (window.testRunner) - testRunner.notifyDone(); - }, false); - - document.addEventListener('webkitAnimationEnd', function(e) { - document.getElementById('result').innerHTML += 'PASS: webkitAnimationEnd event has been called.'; - if (window.testRunner) - testRunner.notifyDone(); - }, false); - - </script> -</head> -<body> -Tests that custom events with prefixed animations names are correctly dispatched. -<pre id="result"></pre> -</body> +<title>Tests that custom events with prefixed animations names are correctly dispatched.</title> +<script src="../../resources/testharness.js"></script> +<script src="../../resources/testharnessreport.js"></script> <script> +var webkitAnimationStartReceived = false; +var webkitAnimationIterationReceived = false; + +document.addEventListener('animationstart', () => { + assert_unreached("animationstart event listener should not have been called"); +}); + +document.addEventListener('webkitAnimationStart', () => { + webkitAnimationStartReceived = true; +}); + +document.addEventListener('animationiteration', () => { + assert_unreached("animationiteration event listener should not have been called"); +}); + +document.addEventListener('webkitAnimationIteration', () => { + webkitAnimationIterationReceived = true; +}); + +document.addEventListener('animationend', () => { + assert_unreached("animationend event listener should not have been called"); +}); + +async_test(t => { + document.addEventListener('webkitAnimationEnd', () => { + t.step(() => { + assert_true(webkitAnimationIterationReceived && webkitAnimationIterationReceived); + t.done(); + }); + }); + var custom = document.createEvent('CustomEvent'); custom.initCustomEvent('webkitAnimationStart', true, true, null); document.dispatchEvent(custom); @@ -52,5 +43,5 @@ custom = document.createEvent('CustomEvent'); custom.initCustomEvent('webkitAnimationEnd', true, true, null); document.dispatchEvent(custom); +}, "Tests that custom events with prefixed animations names are correctly dispatched"); </script> -</html>
diff --git a/third_party/blink/web_tests/animations/prefixed/animation-events-unprefixed-01-expected.txt b/third_party/blink/web_tests/animations/prefixed/animation-events-unprefixed-01-expected.txt deleted file mode 100644 index 4bea785..0000000 --- a/third_party/blink/web_tests/animations/prefixed/animation-events-unprefixed-01-expected.txt +++ /dev/null
@@ -1,2 +0,0 @@ -Tests that unprefixed animation events are correctly fired. -PASS: All events have been received as expected.
diff --git a/third_party/blink/web_tests/animations/prefixed/animation-events-unprefixed-01.html b/third_party/blink/web_tests/animations/prefixed/animation-events-unprefixed-01.html index 33a66c0..b71336c 100644 --- a/third_party/blink/web_tests/animations/prefixed/animation-events-unprefixed-01.html +++ b/third_party/blink/web_tests/animations/prefixed/animation-events-unprefixed-01.html
@@ -1,71 +1,58 @@ <!DOCTYPE html> -<html> -<head> - <title>Tests that unprefixed animation events are correctly fired.</title> - <style> - #box { - position: relative; - left: 100px; - top: 10px; - height: 100px; - width: 100px; - background-color: #999; - } +<title>Tests that unprefixed animation events are correctly fired.</title> +<style> +#box { + position: relative; + left: 100px; + top: 10px; + height: 100px; + width: 100px; + background-color: #999; +} - .animate { - animation-duration: 0.3s; - animation-name: anim; - } +.animate { + animation-duration: 0.3s; + animation-name: anim; +} - @keyframes anim { - from { left: 200px; } - to { left: 300px; } - } - </style> - <script> - if (window.testRunner) { - testRunner.dumpAsText(); - testRunner.waitUntilDone(); - } +@keyframes anim { + from { left: 200px; } + to { left: 300px; } +} +</style> +<script src="../../resources/testharness.js"></script> +<script src="../../resources/testharnessreport.js"></script> +<script> +var startEventReceived = false; +var endEventReceived = false; - var startEventReceived = false; - var endEventReceived = false; +document.addEventListener('animationstart', () => { + startEventReceived = true; +}); - document.addEventListener('animationstart', function() { - startEventReceived = true; - }, false); +document.addEventListener('animationend', () => { + endEventReceived = true; + document.getElementById('box').className = ''; + document.getElementById('box').offsetTop; // force style recalc - document.addEventListener('animationiteration', function() { - if (startEventReceived && endEventReceived) { - document.getElementById('result').innerHTML = 'PASS: All events have been received as expected.'; - if (window.testRunner) - testRunner.notifyDone(); - } - }, false); + // Launch again the animation to catch the animation iteration events this time. + document.getElementById('box').style.animationIterationCount = "infinite"; + document.getElementById('box').className = 'animate'; +}); - document.addEventListener('animationend', function() { - endEventReceived = true; - document.getElementById('box').className = ''; - - document.getElementById('box').offsetTop; // force style recalc - - // Launch again the animation to catch the animation iteration events this time. - document.getElementById('box').style.animationIterationCount = "infinite"; - document.getElementById('box').className = 'animate'; - }, false); - - onload = function() - { +async_test(t => { + window.addEventListener("load", () => { + t.step(() => { // Animation begins once we append the DOM node to the document. var boxNode = document.createElement('div'); boxNode.id = 'box'; boxNode.className = 'animate'; document.body.appendChild(boxNode); - } - </script> -</head> -<body> -Tests that unprefixed animation events are correctly fired. -<pre id="result">FAIL: No animation events received</pre> -</body> -</html> + document.addEventListener('animationiteration', () => { + assert_true(startEventReceived && endEventReceived); + t.done(); + }); + }); + }); +}, "Tests that unprefixed animation events are correctly fired"); +</script>
diff --git a/third_party/blink/web_tests/animations/prefixed/animation-events-unprefixed-02-expected.txt b/third_party/blink/web_tests/animations/prefixed/animation-events-unprefixed-02-expected.txt deleted file mode 100644 index 2a92bc4..0000000 --- a/third_party/blink/web_tests/animations/prefixed/animation-events-unprefixed-02-expected.txt +++ /dev/null
@@ -1,2 +0,0 @@ -Tests that unprefixed animation events are correctly fired when using html event listeners. -PASS: All events have been received as expected.
diff --git a/third_party/blink/web_tests/animations/prefixed/animation-events-unprefixed-02.html b/third_party/blink/web_tests/animations/prefixed/animation-events-unprefixed-02.html index 47bf7e7..cacbaae 100644 --- a/third_party/blink/web_tests/animations/prefixed/animation-events-unprefixed-02.html +++ b/third_party/blink/web_tests/animations/prefixed/animation-events-unprefixed-02.html
@@ -1,62 +1,55 @@ <!DOCTYPE html> -<html> -<head> - <title>Tests that unprefixed animation events are correctly fired when using html event listeners.</title> - <style> - #box { - position: relative; - left: 100px; - top: 10px; - height: 100px; - width: 100px; - background-color: #999; - } +<title>Tests that unprefixed animation events are correctly fired when using html event listeners.</title> +<style> +#box { + position: relative; + left: 100px; + top: 10px; + height: 100px; + width: 100px; + background-color: #999; +} - .animate { - animation-duration: 0.3s; - animation-name: anim; - } +.animate { + animation-duration: 0.3s; + animation-name: anim; +} - @keyframes anim { - from { left: 200px; } - to { left: 300px; } - } - </style> - <script> - if (window.testRunner) { - testRunner.dumpAsText(); - testRunner.waitUntilDone(); - } +@keyframes anim { + from { left: 200px; } + to { left: 300px; } +} +</style> +<script src="../../resources/testharness.js"></script> +<script src="../../resources/testharnessreport.js"></script> +<script> +var startEventReceived = false; +var endEventReceived = false; - var startEventReceived = false; - var endEventReceived = false; +function recordAnimationStart() { + startEventReceived = true; +} - function recordAnimationStart() { - startEventReceived = true; - } +function recordAnimationEnd() { + endEventReceived = true; + document.getElementById('box').className = ''; + // Launch again the animation to catch the animation iteration events this time. + requestAnimationFrame(function () { + document.getElementById('box').style.animationIterationCount = "infinite"; + document.getElementById('box').className = 'animate'; + }); +} - function recordAnimationIteration() { - if (startEventReceived && endEventReceived) { - document.getElementById('result').innerHTML = 'PASS: All events have been received as expected.'; - if (window.testRunner) - testRunner.notifyDone(); - } - } - - function recordAnimationEnd() { - endEventReceived = true; - document.getElementById('box').className = ''; - // Launch again the animation to catch the animation iteration events this time. - requestAnimationFrame(function () { - document.getElementById('box').style.animationIterationCount = "infinite"; - document.getElementById('box').className = 'animate'; +async_test(t => { + window.addEventListener("load", () => { + const box = document.getElementById('box'); + box.addEventListener("animationiteration", () => { + t.step(() => { + assert_true(startEventReceived && endEventReceived); + t.done(); }); - } - </script> -</head> -<body> -Tests that unprefixed animation events are correctly fired when using html event listeners. -<pre id="result">FAIL: No animation events received</pre> -<div id="box" onanimationstart="recordAnimationStart();" onanimationend="recordAnimationEnd();" onanimationiteration="recordAnimationIteration();" class="animate"></div> -</body> -</html> + }); + }); +}, "Tests that unprefixed animation events are correctly fired when using html event listeners"); +</script> +<div id="box" onanimationstart="recordAnimationStart();" onanimationend="recordAnimationEnd();" class="animate"></div>
diff --git a/third_party/blink/web_tests/animations/prefixed/animation-events-unprefixed-03-expected.txt b/third_party/blink/web_tests/animations/prefixed/animation-events-unprefixed-03-expected.txt deleted file mode 100644 index ff7a4008..0000000 --- a/third_party/blink/web_tests/animations/prefixed/animation-events-unprefixed-03-expected.txt +++ /dev/null
@@ -1,2 +0,0 @@ -Tests that unprefixed animation events are correctly fired when using html event listeners (only unprefixed should be fired). -PASS: All events have been received as expected.
diff --git a/third_party/blink/web_tests/animations/prefixed/animation-events-unprefixed-03.html b/third_party/blink/web_tests/animations/prefixed/animation-events-unprefixed-03.html index 3c6e6806..f5b18f0 100644 --- a/third_party/blink/web_tests/animations/prefixed/animation-events-unprefixed-03.html +++ b/third_party/blink/web_tests/animations/prefixed/animation-events-unprefixed-03.html
@@ -1,67 +1,60 @@ <!DOCTYPE html> -<html> -<head> - <title>Tests that unprefixed animation events are correctly fired when using html event listeners (only unprefixed should be fired).</title> - <style> - #box { - position: relative; - left: 100px; - top: 10px; - height: 100px; - width: 100px; - background-color: #999; - } +<title>Tests that unprefixed animation events are correctly fired when using html event listeners (only unprefixed should be fired).</title> +<style> +#box { + position: relative; + left: 100px; + top: 10px; + height: 100px; + width: 100px; + background-color: #999; +} - .animate { - animation-duration: 0.3s; - animation-name: anim; - } +.animate { + animation-duration: 0.3s; + animation-name: anim; +} - @keyframes anim { - from { left: 200px; } - to { left: 300px; } - } - </style> - <script> - if (window.testRunner) { - testRunner.dumpAsText(); - testRunner.waitUntilDone(); - } +@keyframes anim { + from { left: 200px; } + to { left: 300px; } +} +</style> +<script src="../../resources/testharness.js"></script> +<script src="../../resources/testharnessreport.js"></script> +<script> +var startEventReceived = false; +var endEventReceived = false; +var prefixedEventReceived = 0; - var startEventReceived = false; - var endEventReceived = false; - var prefixedEventReceived = 0; +function recordPrefixedEvent() { + prefixedEventReceived++; +} - function recordPrefixedEvent() { - prefixedEventReceived++; - } +function recordAnimationStart() { + startEventReceived = true; +} - function recordAnimationStart() { - startEventReceived = true; - } +function recordAnimationEnd() { + endEventReceived = true; + document.getElementById('box').className = ''; + // Launch again the animation to catch the animation iteration events this time. + requestAnimationFrame(function () { + document.getElementById('box').style.animationIterationCount = "infinite"; + document.getElementById('box').className = 'animate'; + }); +} - function recordAnimationIteration() { - if (startEventReceived && endEventReceived && prefixedEventReceived == 0) { - document.getElementById('result').innerHTML = 'PASS: All events have been received as expected.'; - if (window.testRunner) - testRunner.notifyDone(); - } - } - - function recordAnimationEnd() { - endEventReceived = true; - document.getElementById('box').className = ''; - // Launch again the animation to catch the animation iteration events this time. - requestAnimationFrame(function () { - document.getElementById('box').style.animationIterationCount = "infinite"; - document.getElementById('box').className = 'animate'; +async_test(t => { + window.addEventListener("load", () => { + const box = document.getElementById('box'); + box.addEventListener("animationiteration", () => { + t.step(() => { + assert_true(startEventReceived && endEventReceived && prefixedEventReceived == 0); + t.done(); }); - } - </script> -</head> -<body> -Tests that unprefixed animation events are correctly fired when using html event listeners (only unprefixed should be fired). -<pre id="result">FAIL: No animation events received</pre> -<div id="box" onwebkitanimationstart="recordPrefixedEvent();" onwebkitanimationend="recordPrefixedEvent();" onwebkitanimationiteration="recordPrefixedEvent();" onanimationstart="recordAnimationStart();" onanimationend="recordAnimationEnd();" onanimationiteration="recordAnimationIteration();" class="animate"></div> -</body> -</html> + }); + }); +}, "Tests that unprefixed animation events are correctly fired when using html event listeners (only unprefixed should be fired)"); +</script> +<div id="box" onwebkitanimationstart="recordPrefixedEvent();" onwebkitanimationend="recordPrefixedEvent();" onwebkitanimationiteration="recordPrefixedEvent();" onanimationstart="recordAnimationStart();" onanimationend="recordAnimationEnd();" class="animate"></div>
diff --git a/third_party/blink/web_tests/animations/prefixed/animation-events-unprefixed-04-expected.txt b/third_party/blink/web_tests/animations/prefixed/animation-events-unprefixed-04-expected.txt deleted file mode 100644 index ecbfc1f9c..0000000 --- a/third_party/blink/web_tests/animations/prefixed/animation-events-unprefixed-04-expected.txt +++ /dev/null
@@ -1,4 +0,0 @@ -Tests that custom events with unprefixed animations names are correctly dispatched. -PASS: animationstart event listener has been called. -PASS: animationiteration event listener has been called. -PASS: animationend event listener has been called.
diff --git a/third_party/blink/web_tests/animations/prefixed/animation-events-unprefixed-04.html b/third_party/blink/web_tests/animations/prefixed/animation-events-unprefixed-04.html index 9f85860..389ee7b6 100644 --- a/third_party/blink/web_tests/animations/prefixed/animation-events-unprefixed-04.html +++ b/third_party/blink/web_tests/animations/prefixed/animation-events-unprefixed-04.html
@@ -1,48 +1,39 @@ <!DOCTYPE html> -<html> -<head> - <title>Tests that custom events with unprefixed animations names are correctly dispatched.</title> - <script> - if (window.testRunner) { - testRunner.dumpAsText(); - testRunner.waitUntilDone(); - } - - document.addEventListener('animationstart', function(e) { - document.getElementById('result').innerHTML += 'PASS: animationstart event listener has been called.<br>'; - }, false); - - document.addEventListener('webkitAnimationStart', function(e) { - document.getElementById('result').innerHTML += 'FAIL: webkitAnimationStart event listener should not have been called.<br>'; - }, false); - - document.addEventListener('animationiteration', function(e) { - document.getElementById('result').innerHTML += 'PASS: animationiteration event listener has been called.<br>'; - }, false); - - document.addEventListener('webkitAnimationIteration', function(e) { - document.getElementById('result').innerHTML += 'FAIL: webkitAnimationIteration event listener should not have been called.<br>'; - }, false); - - document.addEventListener('animationend', function(e) { - document.getElementById('result').innerHTML += 'PASS: animationend event listener has been called.'; - if (window.testRunner) - testRunner.notifyDone(); - }, false); - - document.addEventListener('webkitAnimationEnd', function(e) { - document.getElementById('result').innerHTML += 'FAIL: webkitAnimationEnd event listener should not have been called.'; - if (window.testRunner) - testRunner.notifyDone(); - }, false); - - </script> -</head> -<body> -Tests that custom events with unprefixed animations names are correctly dispatched. -<pre id="result"></pre> -</body> +<title>Tests that custom events with unprefixed animations names are correctly dispatched.</title> +<script src="../../resources/testharness.js"></script> +<script src="../../resources/testharnessreport.js"></script> <script> +var animationStartReceived = false; +var animationIterationReceived = false; + +document.addEventListener('animationstart', () => { + animationStartReceived = true; +}); + +document.addEventListener('webkitAnimationStart', () => { + assert_unreached("webkitAnimationStart event listener should not have been called"); +}); + +document.addEventListener('animationiteration', () => { + animationIterationReceived = true; +}); + +document.addEventListener('webkitAnimationIteration', () => { + assert_unreached("webkitAnimationIteration event listener should not have been called"); +}); + +document.addEventListener('webkitAnimationEnd', function(e) { + assert_unreached("webkitAnimationEnd event listener should not have been called"); +}); + +async_test(t => { + document.addEventListener('animationend', () => { + t.step(() => { + assert_true(animationStartReceived && animationIterationReceived); + t.done(); + }); + }); + var custom = document.createEvent('CustomEvent'); custom.initCustomEvent('animationstart', true, true, null); document.dispatchEvent(custom); @@ -52,5 +43,5 @@ custom = document.createEvent('CustomEvent'); custom.initCustomEvent('animationend', true, true, null); document.dispatchEvent(custom); +}, "Tests that custom events with unprefixed animations names are correctly dispatched"); </script> -</html>
diff --git a/third_party/blink/web_tests/animations/prefixed/animation-inherit-initial-unprefixed-expected.txt b/third_party/blink/web_tests/animations/prefixed/animation-inherit-initial-unprefixed-expected.txt deleted file mode 100644 index a43e25a..0000000 --- a/third_party/blink/web_tests/animations/prefixed/animation-inherit-initial-unprefixed-expected.txt +++ /dev/null
@@ -1,38 +0,0 @@ -Test that inherit and initial works on unprefixed animations. - -On success, you will see a series of "PASS" messages, followed by "TEST COMPLETE". - -Testing inherit. -PASS computedStyle.animationName is 'anim' -PASS computedStyle.webkitAnimationName is 'anim' -PASS computedStyle.animationDuration is '5s' -PASS computedStyle.webkitAnimationDuration is '5s' -PASS computedStyle.animationTimingFunction is 'linear' -PASS computedStyle.webkitAnimationTimingFunction is 'linear' -PASS computedStyle.animationDelay is '2s' -PASS computedStyle.webkitAnimationDelay is '2s' -PASS computedStyle.animationIterationCount is 'infinite' -PASS computedStyle.webkitAnimationIterationCount is 'infinite' -PASS computedStyle.animationDirection is 'alternate' -PASS computedStyle.webkitAnimationDirection is 'alternate' -PASS computedStyle.animationPlayState is 'running' -PASS computedStyle.webkitAnimationPlayState is 'running' -Testing initial. -PASS computedStyle.animationName is 'none' -PASS computedStyle.webkitAnimationName is 'none' -PASS computedStyle.animationDuration is '0s' -PASS computedStyle.webkitAnimationDuration is '0s' -PASS computedStyle.animationTimingFunction is 'ease' -PASS computedStyle.webkitAnimationTimingFunction is 'ease' -PASS computedStyle.animationDelay is '0s' -PASS computedStyle.webkitAnimationDelay is '0s' -PASS computedStyle.animationIterationCount is '1' -PASS computedStyle.webkitAnimationIterationCount is '1' -PASS computedStyle.animationDirection is 'normal' -PASS computedStyle.webkitAnimationDirection is 'normal' -PASS computedStyle.animationPlayState is 'running' -PASS computedStyle.webkitAnimationPlayState is 'running' -PASS successfullyParsed is true - -TEST COMPLETE -
diff --git a/third_party/blink/web_tests/animations/prefixed/animation-inherit-initial-unprefixed.html b/third_party/blink/web_tests/animations/prefixed/animation-inherit-initial-unprefixed.html index 0b29c35..5b5e3541 100644 --- a/third_party/blink/web_tests/animations/prefixed/animation-inherit-initial-unprefixed.html +++ b/third_party/blink/web_tests/animations/prefixed/animation-inherit-initial-unprefixed.html
@@ -1,7 +1,4 @@ <!DOCTYPE html> -<html> -<head> -<script src="../../resources/js-test.js"></script> <style> #base { animation-name: anim; @@ -34,69 +31,65 @@ } </style> -</head> -<body> <div style="width:500px;height:500px" id="base"> <div id="inherit"></div> <div id="initial"></div> </div> +<script src="../../resources/testharness.js"></script> +<script src="../../resources/testharnessreport.js"></script> <script> -description("Test that inherit and initial works on unprefixed animations.") +test(() => { + var testContainer = document.createElement("div"); + document.body.appendChild(testContainer); -var testContainer = document.createElement("div"); -document.body.appendChild(testContainer); + e = document.getElementById('inherit'); + computedStyle = window.getComputedStyle(e, null); -e = document.getElementById('inherit'); -computedStyle = window.getComputedStyle(e, null); + assert_equals(computedStyle.animationName, "anim"); + assert_equals(computedStyle.webkitAnimationName, "anim"); -debug("Testing inherit."); -shouldBe("computedStyle.animationName", "'anim'"); -shouldBe("computedStyle.webkitAnimationName", "'anim'"); + assert_equals(computedStyle.animationDuration, "5s"); + assert_equals(computedStyle.webkitAnimationDuration, "5s"); -shouldBe("computedStyle.animationDuration", "'5s'"); -shouldBe("computedStyle.webkitAnimationDuration", "'5s'"); + assert_equals(computedStyle.animationTimingFunction, "linear"); + assert_equals(computedStyle.webkitAnimationTimingFunction, "linear"); -shouldBe("computedStyle.animationTimingFunction", "'linear'"); -shouldBe("computedStyle.webkitAnimationTimingFunction", "'linear'"); + assert_equals(computedStyle.animationDelay, "2s"); + assert_equals(computedStyle.webkitAnimationDelay, "2s"); -shouldBe("computedStyle.animationDelay", "'2s'"); -shouldBe("computedStyle.webkitAnimationDelay", "'2s'"); + assert_equals(computedStyle.animationIterationCount, "infinite"); + assert_equals(computedStyle.webkitAnimationIterationCount, "infinite"); -shouldBe("computedStyle.animationIterationCount", "'infinite'"); -shouldBe("computedStyle.webkitAnimationIterationCount", "'infinite'"); + assert_equals(computedStyle.animationDirection, "alternate"); + assert_equals(computedStyle.webkitAnimationDirection, "alternate"); -shouldBe("computedStyle.animationDirection", "'alternate'"); -shouldBe("computedStyle.webkitAnimationDirection", "'alternate'"); + assert_equals(computedStyle.animationPlayState, "running"); + assert_equals(computedStyle.webkitAnimationPlayState, "running"); -shouldBe("computedStyle.animationPlayState", "'running'"); -shouldBe("computedStyle.webkitAnimationPlayState", "'running'"); + e = document.getElementById('initial'); + computedStyle = window.getComputedStyle(e, null); -e = document.getElementById('initial'); -computedStyle = window.getComputedStyle(e, null); -debug("Testing initial."); + assert_equals(computedStyle.animationName, "none"); + assert_equals(computedStyle.webkitAnimationName, "none"); -shouldBe("computedStyle.animationName", "'none'"); -shouldBe("computedStyle.webkitAnimationName", "'none'"); + assert_equals(computedStyle.animationDuration, "0s"); + assert_equals(computedStyle.webkitAnimationDuration, "0s"); -shouldBe("computedStyle.animationDuration", "'0s'"); -shouldBe("computedStyle.webkitAnimationDuration", "'0s'"); + assert_equals(computedStyle.animationTimingFunction, "ease"); + assert_equals(computedStyle.webkitAnimationTimingFunction, "ease"); -shouldBe("computedStyle.animationTimingFunction", "'ease'"); -shouldBe("computedStyle.webkitAnimationTimingFunction", "'ease'"); + assert_equals(computedStyle.animationDelay, "0s"); + assert_equals(computedStyle.webkitAnimationDelay, "0s"); -shouldBe("computedStyle.animationDelay", "'0s'"); -shouldBe("computedStyle.webkitAnimationDelay", "'0s'"); + assert_equals(computedStyle.animationIterationCount, "1"); + assert_equals(computedStyle.webkitAnimationIterationCount, "1"); -shouldBe("computedStyle.animationIterationCount", "'1'"); -shouldBe("computedStyle.webkitAnimationIterationCount", "'1'"); + assert_equals(computedStyle.animationDirection, "normal"); + assert_equals(computedStyle.webkitAnimationDirection, "normal"); -shouldBe("computedStyle.animationDirection", "'normal'"); -shouldBe("computedStyle.webkitAnimationDirection", "'normal'"); + assert_equals(computedStyle.animationPlayState, "running"); + assert_equals(computedStyle.webkitAnimationPlayState, "running"); -shouldBe("computedStyle.animationPlayState", "'running'"); -shouldBe("computedStyle.webkitAnimationPlayState", "'running'"); - -document.body.removeChild(testContainer); + document.body.removeChild(testContainer); +}, "Test that inherit and initial works on unprefixed animations"); </script> -</body> -</html>
diff --git a/third_party/blink/web_tests/animations/prefixed/animation-shorthand-prefixed-expected.txt b/third_party/blink/web_tests/animations/prefixed/animation-shorthand-prefixed-expected.txt deleted file mode 100644 index f2610f5f..0000000 --- a/third_party/blink/web_tests/animations/prefixed/animation-shorthand-prefixed-expected.txt +++ /dev/null
@@ -1,71 +0,0 @@ -Testing webkitAnimationName on a: PASS -Testing webkitAnimationDuration on a: PASS -Testing webkitAnimationTimingFunction on a: PASS -Testing webkitAnimationDelay on a: PASS -Testing webkitAnimationIterationCount on a: PASS -Testing webkitAnimationDirection on a: PASS -Testing webkitAnimationFillMode on a: PASS -Testing webkitAnimationName on b: PASS -Testing webkitAnimationDuration on b: PASS -Testing webkitAnimationTimingFunction on b: PASS -Testing webkitAnimationDelay on b: PASS -Testing webkitAnimationIterationCount on b: PASS -Testing webkitAnimationDirection on b: PASS -Testing webkitAnimationFillMode on b: PASS -Testing webkitAnimationName on c: PASS -Testing webkitAnimationDuration on c: PASS -Testing webkitAnimationTimingFunction on c: PASS -Testing webkitAnimationDelay on c: PASS -Testing webkitAnimationIterationCount on c: PASS -Testing webkitAnimationDirection on c: PASS -Testing webkitAnimationFillMode on c: PASS -Testing webkitAnimationName on d: PASS -Testing webkitAnimationDuration on d: PASS -Testing webkitAnimationTimingFunction on d: PASS -Testing webkitAnimationDelay on d: PASS -Testing webkitAnimationIterationCount on d: PASS -Testing webkitAnimationDirection on d: PASS -Testing webkitAnimationFillMode on d: PASS -Testing webkitAnimationName on e: PASS -Testing webkitAnimationDuration on e: PASS -Testing webkitAnimationTimingFunction on e: PASS -Testing webkitAnimationDelay on e: PASS -Testing webkitAnimationIterationCount on e: PASS -Testing webkitAnimationDirection on e: PASS -Testing webkitAnimationFillMode on e: PASS -Testing webkitAnimationName on f: PASS -Testing webkitAnimationDuration on f: PASS -Testing webkitAnimationTimingFunction on f: PASS -Testing webkitAnimationDelay on f: PASS -Testing webkitAnimationIterationCount on f: PASS -Testing webkitAnimationDirection on f: PASS -Testing webkitAnimationFillMode on f: PASS -Testing webkitAnimationName on g: PASS -Testing webkitAnimationDuration on g: PASS -Testing webkitAnimationTimingFunction on g: PASS -Testing webkitAnimationDelay on g: PASS -Testing webkitAnimationIterationCount on g: PASS -Testing webkitAnimationDirection on g: PASS -Testing webkitAnimationFillMode on g: PASS -Testing webkitAnimationName on h: PASS -Testing webkitAnimationDuration on h: PASS -Testing webkitAnimationTimingFunction on h: PASS -Testing webkitAnimationDelay on h: PASS -Testing webkitAnimationIterationCount on h: PASS -Testing webkitAnimationDirection on h: PASS -Testing webkitAnimationFillMode on h: PASS -Testing webkitAnimationName on i: PASS -Testing webkitAnimationDuration on i: PASS -Testing webkitAnimationTimingFunction on i: PASS -Testing webkitAnimationDelay on i: PASS -Testing webkitAnimationIterationCount on i: PASS -Testing webkitAnimationDirection on i: PASS -Testing webkitAnimationFillMode on i: PASS -Testing webkitAnimationName on j: PASS -Testing webkitAnimationDuration on j: PASS -Testing webkitAnimationTimingFunction on j: PASS -Testing webkitAnimationDelay on j: PASS -Testing webkitAnimationIterationCount on j: PASS -Testing webkitAnimationDirection on j: PASS -Testing webkitAnimationFillMode on j: PASS -
diff --git a/third_party/blink/web_tests/animations/prefixed/animation-shorthand-prefixed.html b/third_party/blink/web_tests/animations/prefixed/animation-shorthand-prefixed.html index 805c835..b9adae70 100644 --- a/third_party/blink/web_tests/animations/prefixed/animation-shorthand-prefixed.html +++ b/third_party/blink/web_tests/animations/prefixed/animation-shorthand-prefixed.html
@@ -1,6 +1,5 @@ -<html> -<head> -<title>Test animation shorthand property</title> +<!DOCTYPE html> +<title>Test animation shorthand property</title> <style type="text/css" media="screen"> .box { height: 10px; @@ -40,58 +39,55 @@ @-webkit-keyframes anim1 { } @-webkit-keyframes anim2 { } </style> - <script type="text/javascript" charset="utf-8"> - if (window.testRunner) - testRunner.dumpAsText(); - - const kProperties = [ - "webkitAnimationName", - "webkitAnimationDuration", - "webkitAnimationTimingFunction", - "webkitAnimationDelay", - "webkitAnimationIterationCount", - "webkitAnimationDirection", - "webkitAnimationFillMode" - ]; - const kExpectedResults = [ - { id: 'a', values: [ "none", "0s", "ease", "0s", "1", "normal", "none" ] }, - { id: 'b', values: [ "none", "0s", "ease", "0s", "1", "normal", "none" ] }, - { id: 'c', values: [ "anim1", "10s", "ease", "0s", "1", "normal", "none" ] }, - { id: 'd', values: [ "anim1", "10s", "linear", "0s", "1", "normal", "none" ] }, - { id: 'e', values: [ "anim1", "10s", "linear", "5s", "1", "normal", "none" ] }, - { id: 'f', values: [ "anim1", "10s", "linear", "5s", "3", "normal", "none" ] }, - { id: 'g', values: [ "anim1", "10s", "linear", "5s", "infinite", "alternate", "none" ] }, - { id: 'h', values: [ "anim1", "10s", "linear", "5s", "infinite", "alternate", "forwards" ] }, - { id: 'i', values: [ "anim1", "10s", "linear", "0s", "1", "normal", "none" ] }, - { id: 'j', values: [ "anim1, anim2, anim3", "10s, 3s, 5s", "linear, ease, ease", "0s, 0s, 0s", "infinite, 1, 1", "normal, normal, normal", "backwards, none, both" ] } - ]; - - function start() - { - var resultsString = ""; - kExpectedResults.forEach(function(curItem) { - var el = document.getElementById(curItem.id); - var elStyle = window.getComputedStyle(el); - - for (var i=0; i < kProperties.length; i++) { - var computedValue = elStyle[kProperties[i]]; - var expectedValue = curItem.values[i]; - if (computedValue == expectedValue) - resultsString += "Testing " + kProperties[i] + " on " + curItem.id + ": PASS" + "<br>"; - else - resultsString += "Testing " + kProperties[i] + " on " + curItem.id + " expected <code>" + expectedValue + "</code> got <code>" + computedValue + "</code>: FAIL" + "<br>"; - - } - }); +<script src="../../resources/testharness.js"></script> +<script src="../../resources/testharnessreport.js"></script> +<script type="text/javascript" charset="utf-8"> +const kProperties = [ + "webkitAnimationName", + "webkitAnimationDuration", + "webkitAnimationTimingFunction", + "webkitAnimationDelay", + "webkitAnimationIterationCount", + "webkitAnimationDirection", + "webkitAnimationFillMode" +]; +const kExpectedResults = [ + { id: 'a', values: [ "none", "0s", "ease", "0s", "1", "normal", "none" ] }, + { id: 'b', values: [ "none", "0s", "ease", "0s", "1", "normal", "none" ] }, + { id: 'c', values: [ "anim1", "10s", "ease", "0s", "1", "normal", "none" ] }, + { id: 'd', values: [ "anim1", "10s", "linear", "0s", "1", "normal", "none" ] }, + { id: 'e', values: [ "anim1", "10s", "linear", "5s", "1", "normal", "none" ] }, + { id: 'f', values: [ "anim1", "10s", "linear", "5s", "3", "normal", "none" ] }, + { id: 'g', values: [ "anim1", "10s", "linear", "5s", "infinite", "alternate", "none" ] }, + { id: 'h', values: [ "anim1", "10s", "linear", "5s", "infinite", "alternate", "forwards" ] }, + { id: 'i', values: [ "anim1", "10s", "linear", "0s", "1", "normal", "none" ] }, + { id: 'j', values: [ "anim1, anim2, anim3", "10s, 3s, 5s", "linear, ease, ease", "0s, 0s, 0s", "infinite, 1, 1", "normal, normal, normal", "backwards, none, both" ] } +]; - var results = document.getElementById('result'); - results.innerHTML = resultsString; +function start() +{ + var resultsString = ""; + kExpectedResults.forEach(function(curItem) { + var el = document.getElementById(curItem.id); + var elStyle = window.getComputedStyle(el); + + for (var i=0; i < kProperties.length; i++) { + var computedValue = elStyle[kProperties[i]]; + var expectedValue = curItem.values[i]; + assert_true(computedValue == expectedValue); } - - window.addEventListener('load', start, false); - </script> -</head> -<body> + }); +} + +async_test(t => { + window.addEventListener("load", () => { + t.step(() => { + start(); + t.done(); + }); + }); +}, "Test animation shorthand property prefixed"); +</script> <div id="a" class="box"></div> <div id="b" class="box"></div> <div id="c" class="box"></div> @@ -102,7 +98,3 @@ <div id="h" class="box"></div> <div id="i" class="box"></div> <div id="j" class="box"></div> -<div id="result"> -</div> -</body> -</html>
diff --git a/third_party/blink/web_tests/animations/prefixed/animation-shorthand-unprefixed-expected.txt b/third_party/blink/web_tests/animations/prefixed/animation-shorthand-unprefixed-expected.txt deleted file mode 100644 index e1f1d8fbe..0000000 --- a/third_party/blink/web_tests/animations/prefixed/animation-shorthand-unprefixed-expected.txt +++ /dev/null
@@ -1,71 +0,0 @@ -Testing animationName on a: PASS -Testing animationDuration on a: PASS -Testing animationTimingFunction on a: PASS -Testing animationDelay on a: PASS -Testing animationIterationCount on a: PASS -Testing animationDirection on a: PASS -Testing animationFillMode on a: PASS -Testing animationName on b: PASS -Testing animationDuration on b: PASS -Testing animationTimingFunction on b: PASS -Testing animationDelay on b: PASS -Testing animationIterationCount on b: PASS -Testing animationDirection on b: PASS -Testing animationFillMode on b: PASS -Testing animationName on c: PASS -Testing animationDuration on c: PASS -Testing animationTimingFunction on c: PASS -Testing animationDelay on c: PASS -Testing animationIterationCount on c: PASS -Testing animationDirection on c: PASS -Testing animationFillMode on c: PASS -Testing animationName on d: PASS -Testing animationDuration on d: PASS -Testing animationTimingFunction on d: PASS -Testing animationDelay on d: PASS -Testing animationIterationCount on d: PASS -Testing animationDirection on d: PASS -Testing animationFillMode on d: PASS -Testing animationName on e: PASS -Testing animationDuration on e: PASS -Testing animationTimingFunction on e: PASS -Testing animationDelay on e: PASS -Testing animationIterationCount on e: PASS -Testing animationDirection on e: PASS -Testing animationFillMode on e: PASS -Testing animationName on f: PASS -Testing animationDuration on f: PASS -Testing animationTimingFunction on f: PASS -Testing animationDelay on f: PASS -Testing animationIterationCount on f: PASS -Testing animationDirection on f: PASS -Testing animationFillMode on f: PASS -Testing animationName on g: PASS -Testing animationDuration on g: PASS -Testing animationTimingFunction on g: PASS -Testing animationDelay on g: PASS -Testing animationIterationCount on g: PASS -Testing animationDirection on g: PASS -Testing animationFillMode on g: PASS -Testing animationName on h: PASS -Testing animationDuration on h: PASS -Testing animationTimingFunction on h: PASS -Testing animationDelay on h: PASS -Testing animationIterationCount on h: PASS -Testing animationDirection on h: PASS -Testing animationFillMode on h: PASS -Testing animationName on i: PASS -Testing animationDuration on i: PASS -Testing animationTimingFunction on i: PASS -Testing animationDelay on i: PASS -Testing animationIterationCount on i: PASS -Testing animationDirection on i: PASS -Testing animationFillMode on i: PASS -Testing animationName on j: PASS -Testing animationDuration on j: PASS -Testing animationTimingFunction on j: PASS -Testing animationDelay on j: PASS -Testing animationIterationCount on j: PASS -Testing animationDirection on j: PASS -Testing animationFillMode on j: PASS -
diff --git a/third_party/blink/web_tests/animations/prefixed/animation-shorthand-unprefixed.html b/third_party/blink/web_tests/animations/prefixed/animation-shorthand-unprefixed.html index 3841044..5e496bd 100644 --- a/third_party/blink/web_tests/animations/prefixed/animation-shorthand-unprefixed.html +++ b/third_party/blink/web_tests/animations/prefixed/animation-shorthand-unprefixed.html
@@ -1,5 +1,4 @@ -<html> -<head> +<!DOCTYPE html> <title>Test animation shorthand property</title> <style type="text/css" media="screen"> .box { @@ -40,58 +39,55 @@ @keyframes anim1 { } @keyframes anim2 { } </style> - <script type="text/javascript" charset="utf-8"> - if (window.testRunner) - testRunner.dumpAsText(); +<script src="../../resources/testharness.js"></script> +<script src="../../resources/testharnessreport.js"></script> +<script type="text/javascript" charset="utf-8"> +const kProperties = [ + "animationName", + "animationDuration", + "animationTimingFunction", + "animationDelay", + "animationIterationCount", + "animationDirection", + "animationFillMode" +]; +const kExpectedResults = [ + { id: 'a', values: [ "none", "0s", "ease", "0s", "1", "normal", "none" ] }, + { id: 'b', values: [ "none", "0s", "ease", "0s", "1", "normal", "none" ] }, + { id: 'c', values: [ "anim1", "10s", "ease", "0s", "1", "normal", "none" ] }, + { id: 'd', values: [ "anim1", "10s", "linear", "0s", "1", "normal", "none" ] }, + { id: 'e', values: [ "anim1", "10s", "linear", "5s", "1", "normal", "none" ] }, + { id: 'f', values: [ "anim1", "10s", "linear", "5s", "3", "normal", "none" ] }, + { id: 'g', values: [ "anim1", "10s", "linear", "5s", "infinite", "alternate", "none" ] }, + { id: 'h', values: [ "anim1", "10s", "linear", "5s", "infinite", "alternate", "forwards" ] }, + { id: 'i', values: [ "anim1", "10s", "linear", "0s", "1", "normal", "none" ] }, + { id: 'j', values: [ "anim1, anim2, anim3", "10s, 3s, 5s", "linear, ease, ease", "0s, 0s, 0s", "infinite, 1, 1", "normal, normal, normal", "backwards, none, both" ] } +]; - const kProperties = [ - "animationName", - "animationDuration", - "animationTimingFunction", - "animationDelay", - "animationIterationCount", - "animationDirection", - "animationFillMode" - ]; - const kExpectedResults = [ - { id: 'a', values: [ "none", "0s", "ease", "0s", "1", "normal", "none" ] }, - { id: 'b', values: [ "none", "0s", "ease", "0s", "1", "normal", "none" ] }, - { id: 'c', values: [ "anim1", "10s", "ease", "0s", "1", "normal", "none" ] }, - { id: 'd', values: [ "anim1", "10s", "linear", "0s", "1", "normal", "none" ] }, - { id: 'e', values: [ "anim1", "10s", "linear", "5s", "1", "normal", "none" ] }, - { id: 'f', values: [ "anim1", "10s", "linear", "5s", "3", "normal", "none" ] }, - { id: 'g', values: [ "anim1", "10s", "linear", "5s", "infinite", "alternate", "none" ] }, - { id: 'h', values: [ "anim1", "10s", "linear", "5s", "infinite", "alternate", "forwards" ] }, - { id: 'i', values: [ "anim1", "10s", "linear", "0s", "1", "normal", "none" ] }, - { id: 'j', values: [ "anim1, anim2, anim3", "10s, 3s, 5s", "linear, ease, ease", "0s, 0s, 0s", "infinite, 1, 1", "normal, normal, normal", "backwards, none, both" ] } - ]; +function start() +{ + var resultsString = ""; + kExpectedResults.forEach(function(curItem) { + var el = document.getElementById(curItem.id); + var elStyle = window.getComputedStyle(el); - function start() - { - var resultsString = ""; - kExpectedResults.forEach(function(curItem) { - var el = document.getElementById(curItem.id); - var elStyle = window.getComputedStyle(el); - - for (var i=0; i < kProperties.length; i++) { - var computedValue = elStyle[kProperties[i]]; - var expectedValue = curItem.values[i]; - if (computedValue == expectedValue) - resultsString += "Testing " + kProperties[i] + " on " + curItem.id + ": PASS" + "<br>"; - else - resultsString += "Testing " + kProperties[i] + " on " + curItem.id + " expected <code>" + expectedValue + "</code> got <code>" + computedValue + "</code>: FAIL" + "<br>"; - - } - }); - - var results = document.getElementById('result'); - results.innerHTML = resultsString; + for (var i=0; i < kProperties.length; i++) { + var computedValue = elStyle[kProperties[i]]; + var expectedValue = curItem.values[i]; + assert_true(computedValue == expectedValue); } + }); +} - window.addEventListener('load', start, false); - </script> -</head> -<body> +async_test(t => { + window.addEventListener("load", () => { + t.step(() => { + start(); + t.done(); + }); + }); +}, "Test animation shorthand property unprefixed"); +</script> <div id="a" class="box"></div> <div id="b" class="box"></div> <div id="c" class="box"></div> @@ -102,7 +98,3 @@ <div id="h" class="box"></div> <div id="i" class="box"></div> <div id="j" class="box"></div> -<div id="result"> -</div> -</body> -</html>
diff --git a/third_party/blink/web_tests/animations/prefixed/keyframes-cssom-prefixed-02-expected.txt b/third_party/blink/web_tests/animations/prefixed/keyframes-cssom-prefixed-02-expected.txt deleted file mode 100644 index 71cd799a..0000000 --- a/third_party/blink/web_tests/animations/prefixed/keyframes-cssom-prefixed-02-expected.txt +++ /dev/null
@@ -1,24 +0,0 @@ -Test the CSSOM of @-webkit-keyframes. - -On success, you will see a series of "PASS" messages, followed by "TEST COMPLETE". - -PASS keyframeRule.toString() is "[object CSSKeyframesRule]" -PASS keyframeRule.type is 7 -PASS keyframeRule.name is "anim" -PASS keyframeRule.findRule('from').cssText is "0% { left: 200px; }" -PASS keyframeRule.findRule('to').cssText is "100% { left: 300px; }" -PASS keyframeRule.findRule('from') is null -PASS keyframeRule.findRule('from').cssText is "0% { left: 200px; }" -PASS keyframeRule.cssRules[0].toString() is "[object CSSKeyframeRule]" -PASS keyframeRule.cssRules[0].cssText is "100% { left: 300px; }" -PASS keyframeRule.cssRules[0].keyText is "100%" -PASS keyframeRule.cssRules[0].style.cssText is "left: 300px;" -PASS keyframeRule.cssRules[1].toString() is "[object CSSKeyframeRule]" -PASS keyframeRule.cssRules[1].cssText is "0% { left: 200px; }" -PASS keyframeRule.cssRules[1].keyText is "0%" -PASS keyframeRule.cssRules[1].style.cssText is "left: 200px;" -PASS new CSSKeyframesRule().name threw exception TypeError: Illegal constructor. -PASS successfullyParsed is true - -TEST COMPLETE -
diff --git a/third_party/blink/web_tests/animations/prefixed/keyframes-cssom-prefixed-02.html b/third_party/blink/web_tests/animations/prefixed/keyframes-cssom-prefixed-02.html index 5a27907f1b..80dcac1 100644 --- a/third_party/blink/web_tests/animations/prefixed/keyframes-cssom-prefixed-02.html +++ b/third_party/blink/web_tests/animations/prefixed/keyframes-cssom-prefixed-02.html
@@ -1,60 +1,65 @@ <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> - -<html lang="en"> -<head> - <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> - <script src="../../resources/js-test.js"></script> - <style type="text/css" media="screen"> - #test { - position: absolute; - left: 0; - top: 100px; - height: 100px; - width: 100px; - background-color: blue; - animation-duration: 1s; - animation-timing-function: linear; - animation-name: anim; - animation-fill-mode: forwards; - } - </style> -</head> -<body> +<meta http-equiv="Content-Type" content="text/html; charset=utf-8"> +<style type="text/css" media="screen"> +#test { + position: absolute; + left: 0; + top: 100px; + height: 100px; + width: 100px; + background-color: blue; + animation-duration: 1s; + animation-timing-function: linear; + animation-name: anim; + animation-fill-mode: forwards; +} +</style> +<script src="../../resources/testharness.js"></script> +<script src="../../resources/testharnessreport.js"></script> <script> -description("Test the CSSOM of @-webkit-keyframes.") +async_test(t => { + window.addEventListener("load", () => { + t.step(() => { + var testContainer = document.createElement("div"); + document.body.appendChild(testContainer); -var testContainer = document.createElement("div"); -document.body.appendChild(testContainer); + testContainer.innerHTML = '<div style="width:500px;height:500px"><div id="test">hello</div></div>'; -testContainer.innerHTML = '<div style="width:500px;height:500px"><div id="test">hello</div></div>'; + e = document.getElementById('test'); + var lastSheet = document.styleSheets[document.styleSheets.length - 1]; + lastSheet.insertRule("@-webkit-keyframes anim { from { left: 200px; } to { left: 300px;} }", lastSheet.cssRules.length); -e = document.getElementById('test'); -var lastSheet = document.styleSheets[document.styleSheets.length - 1]; -lastSheet.insertRule("@-webkit-keyframes anim { from { left: 200px; } to { left: 300px;} }", lastSheet.cssRules.length); + var keyframeRule = lastSheet.cssRules[lastSheet.cssRules.length - 1]; + assert_equals(keyframeRule.toString(), "[object CSSKeyframesRule]"); + assert_equals(keyframeRule.type, 7); + assert_equals(keyframeRule.name, "anim"); + assert_equals(keyframeRule.findRule('from').cssText, "0% { left: 200px; }"); + assert_equals(keyframeRule.findRule('to').cssText, "100% { left: 300px; }"); + keyframeRule.deleteRule("from"); + assert_equals(keyframeRule.findRule('from'), null); + keyframeRule.appendRule("from { left: 200px; }"); + assert_equals(keyframeRule.findRule('from').cssText, "0% { left: 200px; }"); + assert_equals(keyframeRule.cssRules[0].toString(), "[object CSSKeyframeRule]"); + assert_equals(keyframeRule.cssRules[0].cssText, "100% { left: 300px; }"); + assert_equals(keyframeRule.cssRules[0].keyText, "100%"); + assert_equals(keyframeRule.cssRules[0].style.cssText, "left: 300px;"); + assert_equals(keyframeRule.cssRules[1].toString(), "[object CSSKeyframeRule]"); + assert_equals(keyframeRule.cssRules[1].cssText, "0% { left: 200px; }"); + assert_equals(keyframeRule.cssRules[1].keyText, "0%"); + assert_equals(keyframeRule.cssRules[1].style.cssText, "left: 200px;"); -var keyframeRule = lastSheet.cssRules[lastSheet.cssRules.length - 1]; -shouldBeEqualToString("keyframeRule.toString()", "[object CSSKeyframesRule]"); -shouldBe("keyframeRule.type", "7"); -shouldBeEqualToString("keyframeRule.name", "anim"); -shouldBeEqualToString("keyframeRule.findRule('from').cssText", "0% { left: 200px; }"); -shouldBeEqualToString("keyframeRule.findRule('to').cssText", "100% { left: 300px; }"); -keyframeRule.deleteRule("from"); -shouldBeNull("keyframeRule.findRule('from')"); -keyframeRule.appendRule("from { left: 200px; }"); -shouldBeEqualToString("keyframeRule.findRule('from').cssText", "0% { left: 200px; }"); -shouldBeEqualToString("keyframeRule.cssRules[0].toString()", "[object CSSKeyframeRule]"); -shouldBeEqualToString("keyframeRule.cssRules[0].cssText", "100% { left: 300px; }"); -shouldBeEqualToString("keyframeRule.cssRules[0].keyText", "100%"); -shouldBeEqualToString("keyframeRule.cssRules[0].style.cssText", "left: 300px;"); -shouldBeEqualToString("keyframeRule.cssRules[1].toString()", "[object CSSKeyframeRule]"); -shouldBeEqualToString("keyframeRule.cssRules[1].cssText", "0% { left: 200px; }"); -shouldBeEqualToString("keyframeRule.cssRules[1].keyText", "0%"); -shouldBeEqualToString("keyframeRule.cssRules[1].style.cssText", "left: 200px;"); + try { + new CSSKeyframesRule().name; + } catch (e) { + assert_equals(e.message, "Illegal constructor"); + } -shouldThrow("new CSSKeyframesRule().name", "'TypeError: Illegal constructor'"); - -document.body.removeChild(testContainer); + document.body.removeChild(testContainer); + t.done(); + }); + }); +}, "Test the CSSOM of @-webkit-keyframes"); </script> </body> </html>
diff --git a/third_party/blink/web_tests/animations/prefixed/keyframes-cssom-unprefixed-02-expected.txt b/third_party/blink/web_tests/animations/prefixed/keyframes-cssom-unprefixed-02-expected.txt deleted file mode 100644 index fcbeea1c..0000000 --- a/third_party/blink/web_tests/animations/prefixed/keyframes-cssom-unprefixed-02-expected.txt +++ /dev/null
@@ -1,24 +0,0 @@ -Test the CSSOM of @keyframes. - -On success, you will see a series of "PASS" messages, followed by "TEST COMPLETE". - -PASS keyframeRule.toString() is "[object CSSKeyframesRule]" -PASS keyframeRule.type is 7 -PASS keyframeRule.name is "anim" -PASS keyframeRule.findRule('from').cssText is "0% { left: 200px; }" -PASS keyframeRule.findRule('to').cssText is "100% { left: 300px; }" -PASS keyframeRule.findRule('from') is null -PASS keyframeRule.findRule('from').cssText is "0% { left: 200px; }" -PASS keyframeRule.cssRules[0].toString() is "[object CSSKeyframeRule]" -PASS keyframeRule.cssRules[0].cssText is "100% { left: 300px; }" -PASS keyframeRule.cssRules[0].keyText is "100%" -PASS keyframeRule.cssRules[0].style.cssText is "left: 300px;" -PASS keyframeRule.cssRules[1].toString() is "[object CSSKeyframeRule]" -PASS keyframeRule.cssRules[1].cssText is "0% { left: 200px; }" -PASS keyframeRule.cssRules[1].keyText is "0%" -PASS keyframeRule.cssRules[1].style.cssText is "left: 200px;" -PASS new CSSKeyframesRule().name threw exception TypeError: Illegal constructor. -PASS successfullyParsed is true - -TEST COMPLETE -
diff --git a/third_party/blink/web_tests/animations/prefixed/keyframes-cssom-unprefixed-02.html b/third_party/blink/web_tests/animations/prefixed/keyframes-cssom-unprefixed-02.html index d9a4fb0..3546b580 100644 --- a/third_party/blink/web_tests/animations/prefixed/keyframes-cssom-unprefixed-02.html +++ b/third_party/blink/web_tests/animations/prefixed/keyframes-cssom-unprefixed-02.html
@@ -1,57 +1,61 @@ <!DOCTYPE html> -<html lang="en"> -<head> - <script src="../../resources/js-test.js"></script> - <style type="text/css" media="screen"> - #test { - position: absolute; - left: 0; - top: 100px; - height: 100px; - width: 100px; - background-color: blue; - animation-duration: 1s; - animation-timing-function: linear; - animation-name: anim; - animation-fill-mode: forwards; - } - </style> -</head> -<body> +<style type="text/css" media="screen"> +#test { + position: absolute; + left: 0; + top: 100px; + height: 100px; + width: 100px; + background-color: blue; + animation-duration: 1s; + animation-timing-function: linear; + animation-name: anim; + animation-fill-mode: forwards; +} +</style> +<script src="../../resources/testharness.js"></script> +<script src="../../resources/testharnessreport.js"></script> <script> -description("Test the CSSOM of @keyframes.") +async_test(t => { + window.addEventListener("load", () => { + t.step(() => { + var testContainer = document.createElement("div"); + document.body.appendChild(testContainer); -var testContainer = document.createElement("div"); -document.body.appendChild(testContainer); + testContainer.innerHTML = '<div style="width:500px;height:500px"><div id="test">hello</div></div>'; -testContainer.innerHTML = '<div style="width:500px;height:500px"><div id="test">hello</div></div>'; + e = document.getElementById('test'); + var lastSheet = document.styleSheets[document.styleSheets.length - 1]; + lastSheet.insertRule("@keyframes anim { from { left: 200px; } to { left: 300px;} }", lastSheet.cssRules.length); -e = document.getElementById('test'); -var lastSheet = document.styleSheets[document.styleSheets.length - 1]; -lastSheet.insertRule("@keyframes anim { from { left: 200px; } to { left: 300px;} }", lastSheet.cssRules.length); + var keyframeRule = lastSheet.cssRules[lastSheet.cssRules.length - 1]; + assert_equals(keyframeRule.toString(), "[object CSSKeyframesRule]"); + assert_equals(keyframeRule.type, 7); + assert_equals(keyframeRule.name, "anim"); + assert_equals(keyframeRule.findRule('from').cssText, "0% { left: 200px; }"); + assert_equals(keyframeRule.findRule('to').cssText, "100% { left: 300px; }"); + keyframeRule.deleteRule("from"); + assert_equals(keyframeRule.findRule('from'), null); + keyframeRule.appendRule("from { left: 200px; }"); + assert_equals(keyframeRule.findRule('from').cssText, "0% { left: 200px; }"); + assert_equals(keyframeRule.cssRules[0].toString(), "[object CSSKeyframeRule]"); + assert_equals(keyframeRule.cssRules[0].cssText, "100% { left: 300px; }"); + assert_equals(keyframeRule.cssRules[0].keyText, "100%"); + assert_equals(keyframeRule.cssRules[0].style.cssText, "left: 300px;"); + assert_equals(keyframeRule.cssRules[1].toString(), "[object CSSKeyframeRule]"); + assert_equals(keyframeRule.cssRules[1].cssText, "0% { left: 200px; }"); + assert_equals(keyframeRule.cssRules[1].keyText, "0%"); + assert_equals(keyframeRule.cssRules[1].style.cssText, "left: 200px;"); -var keyframeRule = lastSheet.cssRules[lastSheet.cssRules.length - 1]; -shouldBeEqualToString("keyframeRule.toString()", "[object CSSKeyframesRule]"); -shouldBe("keyframeRule.type", "7"); -shouldBeEqualToString("keyframeRule.name", "anim"); -shouldBeEqualToString("keyframeRule.findRule('from').cssText", "0% { left: 200px; }"); -shouldBeEqualToString("keyframeRule.findRule('to').cssText", "100% { left: 300px; }"); -keyframeRule.deleteRule("from"); -shouldBeNull("keyframeRule.findRule('from')"); -keyframeRule.appendRule("from { left: 200px; }"); -shouldBeEqualToString("keyframeRule.findRule('from').cssText", "0% { left: 200px; }"); -shouldBeEqualToString("keyframeRule.cssRules[0].toString()", "[object CSSKeyframeRule]"); -shouldBeEqualToString("keyframeRule.cssRules[0].cssText", "100% { left: 300px; }"); -shouldBeEqualToString("keyframeRule.cssRules[0].keyText", "100%"); -shouldBeEqualToString("keyframeRule.cssRules[0].style.cssText", "left: 300px;"); -shouldBeEqualToString("keyframeRule.cssRules[1].toString()", "[object CSSKeyframeRule]"); -shouldBeEqualToString("keyframeRule.cssRules[1].cssText", "0% { left: 200px; }"); -shouldBeEqualToString("keyframeRule.cssRules[1].keyText", "0%"); -shouldBeEqualToString("keyframeRule.cssRules[1].style.cssText", "left: 200px;"); + try { + new CSSKeyframesRule().name; + } catch (e) { + assert_equals(e.message, "Illegal constructor"); + } -shouldThrow("new CSSKeyframesRule().name", "'TypeError: Illegal constructor'"); - -document.body.removeChild(testContainer); + document.body.removeChild(testContainer); + t.done(); + }); + }); +}, "Test the CSSOM of @keyframes"); </script> -</body> -</html>
diff --git a/third_party/blink/web_tests/animations/reverse-transition-with-easing.html b/third_party/blink/web_tests/animations/reverse-transition-with-easing.html index 7aa33cd..94b3599b 100644 --- a/third_party/blink/web_tests/animations/reverse-transition-with-easing.html +++ b/third_party/blink/web_tests/animations/reverse-transition-with-easing.html
@@ -50,7 +50,7 @@ animation.currentTime = 0; assert_px_approx_equals(getComputedStyle(box).width, 168.531, 0.01, 'width after className'); animation.currentTime = 200; - assert_px_approx_equals(getComputedStyle(box).width, 113.312, 0.01, 'width mid-reverse'); + assert_px_approx_equals(getComputedStyle(box).width, 134.438, 0.01, 'width mid-reverse'); // Go forward again. This tests the reversingAdjustedStartValue is set // properly the first time it's reversed. @@ -60,9 +60,9 @@ animation.pause(); // The animation is replaced, so pause it again. animation.currentTime = 0; - assert_px_approx_equals(getComputedStyle(box).width, 113.312, 0.01, 'width after second reverse'); + assert_px_approx_equals(getComputedStyle(box).width, 134.438, 0.01, 'width after second reverse'); animation.currentTime = 400; - assert_px_approx_equals(getComputedStyle(box).width, 183.141, 0.01, 'width mid-second-reverse'); + assert_px_approx_equals(getComputedStyle(box).width, 193.016, 0.01, 'width mid-second-reverse'); animation.currentTime = 800; assert_equals(getComputedStyle(box).width, '200px', 'width at end');
diff --git a/third_party/blink/web_tests/editing/selection/modify_move/move_out_of_inline_block_multiline.html b/third_party/blink/web_tests/editing/selection/modify_move/move_out_of_inline_block_multiline.html new file mode 100644 index 0000000..deae747 --- /dev/null +++ b/third_party/blink/web_tests/editing/selection/modify_move/move_out_of_inline_block_multiline.html
@@ -0,0 +1,399 @@ +<!DOCTYPE html> +<script src="../../../resources/testharness.js"></script> +<script src="../../../resources/testharnessreport.js"></script> +<script src="../../assert_selection.js"></script> +<script> +// Variations: +// 1. Whether in the first or second line +// 2. Whether at (logical) start or end of the line +// 3. Moving left or right +// 4. Resolved direction of the inline block in the parent context +// 5. Direction of the first line text inside the inline block +// 6. Direction of the last line text inside the inline block + +// Generated by: https://jsfiddle.net/z63vdhfe/ + +selection_test( + '<div contenteditable>foo<span style="display:inline-block">|bar<br>qux</span>baz</div>', + selection => selection.modify('move', 'left', 'character'), + '<div contenteditable>fo|o<span style="display:inline-block">bar<br>qux</span>baz</div>', + 'Start of line 1, move left, LTR resolved direction, LTR/LTR text inside'); + +selection_test( + '<div contenteditable>foo<span style="display:inline-block">|bar<br>יךכ</span>baz</div>', + selection => selection.modify('move', 'left', 'character'), + '<div contenteditable>fo|o<span style="display:inline-block">bar<br>יךכ</span>baz</div>', + 'Start of line 1, move left, LTR resolved direction, LTR/RTL text inside'); + +selection_test( + '<div contenteditable>foo<span style="display:inline-block">|אבג<br>qux</span>baz</div>', + selection => selection.modify('move', 'left', 'character'), + '<div contenteditable>fo|o<span style="display:inline-block">אבג<br>qux</span>baz</div>', + 'Start of line 1, move left, LTR resolved direction, RTL/LTR text inside'); + +selection_test( + '<div contenteditable>foo<span style="display:inline-block">|אבג<br>יךכ</span>baz</div>', + selection => selection.modify('move', 'left', 'character'), + '<div contenteditable>fo|o<span style="display:inline-block">אבג<br>יךכ</span>baz</div>', + 'Start of line 1, move left, LTR resolved direction, RTL/RTL text inside'); + +selection_test( + '<div contenteditable dir="rtl">דהו<span style="display:inline-block">|bar<br>qux</span>זחט</div>', + selection => selection.modify('move', 'left', 'character'), + '<div contenteditable dir="rtl">דהו<span style="display:inline-block">b|ar<br>qux</span>זחט</div>', + 'Start of line 1, move left, RTL resolved direction, LTR/LTR text inside'); + +selection_test( + '<div contenteditable dir="rtl">דהו<span style="display:inline-block">|bar<br>יךכ</span>זחט</div>', + selection => selection.modify('move', 'left', 'character'), + '<div contenteditable dir="rtl">דהו<span style="display:inline-block">b|ar<br>יךכ</span>זחט</div>', + 'Start of line 1, move left, RTL resolved direction, LTR/RTL text inside'); + +selection_test( + '<div contenteditable dir="rtl">דהו<span style="display:inline-block">|אבג<br>qux</span>זחט</div>', + selection => selection.modify('move', 'left', 'character'), + '<div contenteditable dir="rtl">דהו<span style="display:inline-block">א|בג<br>qux</span>זחט</div>', + 'Start of line 1, move left, RTL resolved direction, RTL/LTR text inside'); + +selection_test( + '<div contenteditable dir="rtl">דהו<span style="display:inline-block">|אבג<br>יךכ</span>זחט</div>', + selection => selection.modify('move', 'left', 'character'), + '<div contenteditable dir="rtl">דהו<span style="display:inline-block">א|בג<br>יךכ</span>זחט</div>', + 'Start of line 1, move left, RTL resolved direction, RTL/RTL text inside'); + +selection_test( + '<div contenteditable>foo<span style="display:inline-block">|bar<br>qux</span>baz</div>', + selection => selection.modify('move', 'right', 'character'), + '<div contenteditable>foo<span style="display:inline-block">b|ar<br>qux</span>baz</div>', + 'Start of line 1, move right, LTR resolved direction, LTR/LTR text inside'); + +selection_test( + '<div contenteditable>foo<span style="display:inline-block">|bar<br>יךכ</span>baz</div>', + selection => selection.modify('move', 'right', 'character'), + '<div contenteditable>foo<span style="display:inline-block">b|ar<br>יךכ</span>baz</div>', + 'Start of line 1, move right, LTR resolved direction, LTR/RTL text inside'); + +selection_test( + '<div contenteditable>foo<span style="display:inline-block">|אבג<br>qux</span>baz</div>', + selection => selection.modify('move', 'right', 'character'), + '<div contenteditable>foo<span style="display:inline-block">א|בג<br>qux</span>baz</div>', + 'Start of line 1, move right, LTR resolved direction, RTL/LTR text inside'); + +selection_test( + '<div contenteditable>foo<span style="display:inline-block">|אבג<br>יךכ</span>baz</div>', + selection => selection.modify('move', 'right', 'character'), + '<div contenteditable>foo<span style="display:inline-block">א|בג<br>יךכ</span>baz</div>', + 'Start of line 1, move right, LTR resolved direction, RTL/RTL text inside'); + +selection_test( + '<div contenteditable dir="rtl">דהו<span style="display:inline-block">|bar<br>qux</span>זחט</div>', + selection => selection.modify('move', 'right', 'character'), + '<div contenteditable dir="rtl">דה|ו<span style="display:inline-block">bar<br>qux</span>זחט</div>', + 'Start of line 1, move right, RTL resolved direction, LTR/LTR text inside'); + +selection_test( + '<div contenteditable dir="rtl">דהו<span style="display:inline-block">|bar<br>יךכ</span>זחט</div>', + selection => selection.modify('move', 'right', 'character'), + '<div contenteditable dir="rtl">דה|ו<span style="display:inline-block">bar<br>יךכ</span>זחט</div>', + 'Start of line 1, move right, RTL resolved direction, LTR/RTL text inside'); + +selection_test( + '<div contenteditable dir="rtl">דהו<span style="display:inline-block">|אבג<br>qux</span>זחט</div>', + selection => selection.modify('move', 'right', 'character'), + '<div contenteditable dir="rtl">דה|ו<span style="display:inline-block">אבג<br>qux</span>זחט</div>', + 'Start of line 1, move right, RTL resolved direction, RTL/LTR text inside'); + +selection_test( + '<div contenteditable dir="rtl">דהו<span style="display:inline-block">|אבג<br>יךכ</span>זחט</div>', + selection => selection.modify('move', 'right', 'character'), + '<div contenteditable dir="rtl">דה|ו<span style="display:inline-block">אבג<br>יךכ</span>זחט</div>', + 'Start of line 1, move right, RTL resolved direction, RTL/RTL text inside'); + +selection_test( + '<div contenteditable>foo<span style="display:inline-block">bar|<br>qux</span>baz</div>', + selection => selection.modify('move', 'left', 'character'), + '<div contenteditable>foo<span style="display:inline-block">ba|r<br>qux</span>baz</div>', + 'End of line 1, move left, LTR resolved direction, LTR/LTR text inside'); + +selection_test( + '<div contenteditable>foo<span style="display:inline-block">bar|<br>יךכ</span>baz</div>', + selection => selection.modify('move', 'left', 'character'), + '<div contenteditable>foo<span style="display:inline-block">ba|r<br>יךכ</span>baz</div>', + 'End of line 1, move left, LTR resolved direction, LTR/RTL text inside'); + +selection_test( + '<div contenteditable>foo<span style="display:inline-block">אבג|<br>qux</span>baz</div>', + selection => selection.modify('move', 'left', 'character'), + '<div contenteditable>foo<span style="display:inline-block">א|בג<br>qux</span>baz</div>', + 'End of line 1, move left, LTR resolved direction, RTL/LTR text inside'); + +selection_test( + '<div contenteditable>foo<span style="display:inline-block">אבג|<br>יךכ</span>baz</div>', + selection => selection.modify('move', 'left', 'character'), + '<div contenteditable>foo<span style="display:inline-block">א|בג<br>יךכ</span>baz</div>', + 'End of line 1, move left, LTR resolved direction, RTL/RTL text inside'); + +selection_test( + '<div contenteditable dir="rtl">דהו<span style="display:inline-block">bar|<br>qux</span>זחט</div>', + selection => selection.modify('move', 'left', 'character'), + '<div contenteditable dir="rtl">דהו<span style="display:inline-block">bar<br>|qux</span>זחט</div>', + 'End of line 1, move left, RTL resolved direction, LTR/LTR text inside'); + +selection_test( + '<div contenteditable dir="rtl">דהו<span style="display:inline-block">bar|<br>יךכ</span>זחט</div>', + selection => selection.modify('move', 'left', 'character'), + '<div contenteditable dir="rtl">דהו<span style="display:inline-block">bar<br>|יךכ</span>זחט</div>', + 'End of line 1, move left, RTL resolved direction, LTR/RTL text inside'); + +selection_test( + '<div contenteditable dir="rtl">דהו<span style="display:inline-block">אבג|<br>qux</span>זחט</div>', + selection => selection.modify('move', 'left', 'character'), + '<div contenteditable dir="rtl">דהו<span style="display:inline-block">אבג<br>|qux</span>זחט</div>', + 'End of line 1, move left, RTL resolved direction, RTL/LTR text inside'); + +selection_test( + '<div contenteditable dir="rtl">דהו<span style="display:inline-block">אבג|<br>יךכ</span>זחט</div>', + selection => selection.modify('move', 'left', 'character'), + '<div contenteditable dir="rtl">דהו<span style="display:inline-block">אבג<br>|יךכ</span>זחט</div>', + 'End of line 1, move left, RTL resolved direction, RTL/RTL text inside'); + +selection_test( + '<div contenteditable>foo<span style="display:inline-block">bar|<br>qux</span>baz</div>', + selection => selection.modify('move', 'right', 'character'), + '<div contenteditable>foo<span style="display:inline-block">bar<br>|qux</span>baz</div>', + 'End of line 1, move right, LTR resolved direction, LTR/LTR text inside'); + +selection_test( + '<div contenteditable>foo<span style="display:inline-block">bar|<br>יךכ</span>baz</div>', + selection => selection.modify('move', 'right', 'character'), + '<div contenteditable>foo<span style="display:inline-block">bar<br>|יךכ</span>baz</div>', + 'End of line 1, move right, LTR resolved direction, LTR/RTL text inside'); + +selection_test( + '<div contenteditable>foo<span style="display:inline-block">אבג|<br>qux</span>baz</div>', + selection => selection.modify('move', 'right', 'character'), + '<div contenteditable>foo<span style="display:inline-block">אבג<br>|qux</span>baz</div>', + 'End of line 1, move right, LTR resolved direction, RTL/LTR text inside'); + +selection_test( + '<div contenteditable>foo<span style="display:inline-block">אבג|<br>יךכ</span>baz</div>', + selection => selection.modify('move', 'right', 'character'), + '<div contenteditable>foo<span style="display:inline-block">אבג<br>|יךכ</span>baz</div>', + 'End of line 1, move right, LTR resolved direction, RTL/RTL text inside'); + +selection_test( + '<div contenteditable dir="rtl">דהו<span style="display:inline-block">bar|<br>qux</span>זחט</div>', + selection => selection.modify('move', 'right', 'character'), + '<div contenteditable dir="rtl">דהו<span style="display:inline-block">b|ar<br>qux</span>זחט</div>', + 'End of line 1, move right, RTL resolved direction, LTR/LTR text inside'); + +selection_test( + '<div contenteditable dir="rtl">דהו<span style="display:inline-block">bar|<br>יךכ</span>זחט</div>', + selection => selection.modify('move', 'right', 'character'), + '<div contenteditable dir="rtl">דהו<span style="display:inline-block">b|ar<br>יךכ</span>זחט</div>', + 'End of line 1, move right, RTL resolved direction, LTR/RTL text inside'); + +selection_test( + '<div contenteditable dir="rtl">דהו<span style="display:inline-block">אבג|<br>qux</span>זחט</div>', + selection => selection.modify('move', 'right', 'character'), + '<div contenteditable dir="rtl">דהו<span style="display:inline-block">אב|ג<br>qux</span>זחט</div>', + 'End of line 1, move right, RTL resolved direction, RTL/LTR text inside'); + +selection_test( + '<div contenteditable dir="rtl">דהו<span style="display:inline-block">אבג|<br>יךכ</span>זחט</div>', + selection => selection.modify('move', 'right', 'character'), + '<div contenteditable dir="rtl">דהו<span style="display:inline-block">אב|ג<br>יךכ</span>זחט</div>', + 'End of line 1, move right, RTL resolved direction, RTL/RTL text inside'); + +selection_test( + '<div contenteditable>foo<span style="display:inline-block">bar<br>|qux</span>baz</div>', + selection => selection.modify('move', 'left', 'character'), + '<div contenteditable>foo<span style="display:inline-block">bar|<br>qux</span>baz</div>', + 'Start of line 2, move left, LTR resolved direction, LTR/LTR text inside'); + +selection_test( + '<div contenteditable>foo<span style="display:inline-block">bar<br>|יךכ</span>baz</div>', + selection => selection.modify('move', 'left', 'character'), + '<div contenteditable>foo<span style="display:inline-block">bar|<br>יךכ</span>baz</div>', + 'Start of line 2, move left, LTR resolved direction, LTR/RTL text inside'); + +selection_test( + '<div contenteditable>foo<span style="display:inline-block">אבג<br>|qux</span>baz</div>', + selection => selection.modify('move', 'left', 'character'), + '<div contenteditable>foo<span style="display:inline-block">אבג|<br>qux</span>baz</div>', + 'Start of line 2, move left, LTR resolved direction, RTL/LTR text inside'); + +selection_test( + '<div contenteditable>foo<span style="display:inline-block">אבג<br>|יךכ</span>baz</div>', + selection => selection.modify('move', 'left', 'character'), + '<div contenteditable>foo<span style="display:inline-block">אבג|<br>יךכ</span>baz</div>', + 'Start of line 2, move left, LTR resolved direction, RTL/RTL text inside'); + +selection_test( + '<div contenteditable dir="rtl">דהו<span style="display:inline-block">bar<br>|qux</span>זחט</div>', + selection => selection.modify('move', 'left', 'character'), + '<div contenteditable dir="rtl">דהו<span style="display:inline-block">bar<br>qu|x</span>זחט</div>', + 'Start of line 2, move left, RTL resolved direction, LTR/LTR text inside'); + +selection_test( + '<div contenteditable dir="rtl">דהו<span style="display:inline-block">bar<br>|יךכ</span>זחט</div>', + selection => selection.modify('move', 'left', 'character'), + '<div contenteditable dir="rtl">דהו<span style="display:inline-block">bar<br>י|ךכ</span>זחט</div>', + 'Start of line 2, move left, RTL resolved direction, LTR/RTL text inside'); + +selection_test( + '<div contenteditable dir="rtl">דהו<span style="display:inline-block">אבג<br>|qux</span>זחט</div>', + selection => selection.modify('move', 'left', 'character'), + '<div contenteditable dir="rtl">דהו<span style="display:inline-block">אבג<br>qu|x</span>זחט</div>', + 'Start of line 2, move left, RTL resolved direction, RTL/LTR text inside'); + +selection_test( + '<div contenteditable dir="rtl">דהו<span style="display:inline-block">אבג<br>|יךכ</span>זחט</div>', + selection => selection.modify('move', 'left', 'character'), + '<div contenteditable dir="rtl">דהו<span style="display:inline-block">אבג<br>י|ךכ</span>זחט</div>', + 'Start of line 2, move left, RTL resolved direction, RTL/RTL text inside'); + +selection_test( + '<div contenteditable>foo<span style="display:inline-block">bar<br>|qux</span>baz</div>', + selection => selection.modify('move', 'right', 'character'), + '<div contenteditable>foo<span style="display:inline-block">bar<br>q|ux</span>baz</div>', + 'Start of line 2, move right, LTR resolved direction, LTR/LTR text inside'); + +selection_test( + '<div contenteditable>foo<span style="display:inline-block">bar<br>|יךכ</span>baz</div>', + selection => selection.modify('move', 'right', 'character'), + '<div contenteditable>foo<span style="display:inline-block">bar<br>יך|כ</span>baz</div>', + 'Start of line 2, move right, LTR resolved direction, LTR/RTL text inside'); + +selection_test( + '<div contenteditable>foo<span style="display:inline-block">אבג<br>|qux</span>baz</div>', + selection => selection.modify('move', 'right', 'character'), + '<div contenteditable>foo<span style="display:inline-block">אבג<br>q|ux</span>baz</div>', + 'Start of line 2, move right, LTR resolved direction, RTL/LTR text inside'); + +selection_test( + '<div contenteditable>foo<span style="display:inline-block">אבג<br>|יךכ</span>baz</div>', + selection => selection.modify('move', 'right', 'character'), + '<div contenteditable>foo<span style="display:inline-block">אבג<br>יך|כ</span>baz</div>', + 'Start of line 2, move right, LTR resolved direction, RTL/RTL text inside'); + +selection_test( + '<div contenteditable dir="rtl">דהו<span style="display:inline-block">bar<br>|qux</span>זחט</div>', + selection => selection.modify('move', 'right', 'character'), + '<div contenteditable dir="rtl">דהו<span style="display:inline-block">bar|<br>qux</span>זחט</div>', + 'Start of line 2, move right, RTL resolved direction, LTR/LTR text inside'); + +selection_test( + '<div contenteditable dir="rtl">דהו<span style="display:inline-block">bar<br>|יךכ</span>זחט</div>', + selection => selection.modify('move', 'right', 'character'), + '<div contenteditable dir="rtl">דהו<span style="display:inline-block">bar|<br>יךכ</span>זחט</div>', + 'Start of line 2, move right, RTL resolved direction, LTR/RTL text inside'); + +selection_test( + '<div contenteditable dir="rtl">דהו<span style="display:inline-block">אבג<br>|qux</span>זחט</div>', + selection => selection.modify('move', 'right', 'character'), + '<div contenteditable dir="rtl">דהו<span style="display:inline-block">אבג|<br>qux</span>זחט</div>', + 'Start of line 2, move right, RTL resolved direction, RTL/LTR text inside'); + +selection_test( + '<div contenteditable dir="rtl">דהו<span style="display:inline-block">אבג<br>|יךכ</span>זחט</div>', + selection => selection.modify('move', 'right', 'character'), + '<div contenteditable dir="rtl">דהו<span style="display:inline-block">אבג|<br>יךכ</span>זחט</div>', + 'Start of line 2, move right, RTL resolved direction, RTL/RTL text inside'); + +selection_test( + '<div contenteditable>foo<span style="display:inline-block">bar<br>qux|</span>baz</div>', + selection => selection.modify('move', 'left', 'character'), + '<div contenteditable>foo<span style="display:inline-block">bar<br>qu|x</span>baz</div>', + 'End of line 2, move left, LTR resolved direction, LTR/LTR text inside'); + +selection_test( + '<div contenteditable>foo<span style="display:inline-block">bar<br>יךכ|</span>baz</div>', + selection => selection.modify('move', 'left', 'character'), + '<div contenteditable>foo<span style="display:inline-block">bar<br>י|ךכ</span>baz</div>', + 'End of line 2, move left, LTR resolved direction, LTR/RTL text inside'); + +selection_test( + '<div contenteditable>foo<span style="display:inline-block">אבג<br>qux|</span>baz</div>', + selection => selection.modify('move', 'left', 'character'), + '<div contenteditable>foo<span style="display:inline-block">אבג<br>qu|x</span>baz</div>', + 'End of line 2, move left, LTR resolved direction, RTL/LTR text inside'); + +selection_test( + '<div contenteditable>foo<span style="display:inline-block">אבג<br>יךכ|</span>baz</div>', + selection => selection.modify('move', 'left', 'character'), + '<div contenteditable>foo<span style="display:inline-block">אבג<br>י|ךכ</span>baz</div>', + 'End of line 2, move left, LTR resolved direction, RTL/RTL text inside'); + +selection_test( + '<div contenteditable dir="rtl">דהו<span style="display:inline-block">bar<br>qux|</span>זחט</div>', + selection => selection.modify('move', 'left', 'character'), + '<div contenteditable dir="rtl">דהו<span style="display:inline-block">bar<br>qux</span>ז|חט</div>', + 'End of line 2, move left, RTL resolved direction, LTR/LTR text inside'); + +selection_test( + '<div contenteditable dir="rtl">דהו<span style="display:inline-block">bar<br>יךכ|</span>זחט</div>', + selection => selection.modify('move', 'left', 'character'), + '<div contenteditable dir="rtl">דהו<span style="display:inline-block">bar<br>יךכ</span>ז|חט</div>', + 'End of line 2, move left, RTL resolved direction, LTR/RTL text inside'); + +selection_test( + '<div contenteditable dir="rtl">דהו<span style="display:inline-block">אבג<br>qux|</span>זחט</div>', + selection => selection.modify('move', 'left', 'character'), + '<div contenteditable dir="rtl">דהו<span style="display:inline-block">אבג<br>qux</span>ז|חט</div>', + 'End of line 2, move left, RTL resolved direction, RTL/LTR text inside'); + +selection_test( + '<div contenteditable dir="rtl">דהו<span style="display:inline-block">אבג<br>יךכ|</span>זחט</div>', + selection => selection.modify('move', 'left', 'character'), + '<div contenteditable dir="rtl">דהו<span style="display:inline-block">אבג<br>יךכ</span>ז|חט</div>', + 'End of line 2, move left, RTL resolved direction, RTL/RTL text inside'); + +selection_test( + '<div contenteditable>foo<span style="display:inline-block">bar<br>qux|</span>baz</div>', + selection => selection.modify('move', 'right', 'character'), + '<div contenteditable>foo<span style="display:inline-block">bar<br>qux</span>b|az</div>', + 'End of line 2, move right, LTR resolved direction, LTR/LTR text inside'); + +selection_test( + '<div contenteditable>foo<span style="display:inline-block">bar<br>יךכ|</span>baz</div>', + selection => selection.modify('move', 'right', 'character'), + '<div contenteditable>foo<span style="display:inline-block">bar<br>יךכ</span>b|az</div>', + 'End of line 2, move right, LTR resolved direction, LTR/RTL text inside'); + +selection_test( + '<div contenteditable>foo<span style="display:inline-block">אבג<br>qux|</span>baz</div>', + selection => selection.modify('move', 'right', 'character'), + '<div contenteditable>foo<span style="display:inline-block">אבג<br>qux</span>b|az</div>', + 'End of line 2, move right, LTR resolved direction, RTL/LTR text inside'); + +selection_test( + '<div contenteditable>foo<span style="display:inline-block">אבג<br>יךכ|</span>baz</div>', + selection => selection.modify('move', 'right', 'character'), + '<div contenteditable>foo<span style="display:inline-block">אבג<br>יךכ</span>b|az</div>', + 'End of line 2, move right, LTR resolved direction, RTL/RTL text inside'); + +selection_test( + '<div contenteditable dir="rtl">דהו<span style="display:inline-block">bar<br>qux|</span>זחט</div>', + selection => selection.modify('move', 'right', 'character'), + '<div contenteditable dir="rtl">דהו<span style="display:inline-block">bar<br>q|ux</span>זחט</div>', + 'End of line 2, move right, RTL resolved direction, LTR/LTR text inside'); + +selection_test( + '<div contenteditable dir="rtl">דהו<span style="display:inline-block">bar<br>יךכ|</span>זחט</div>', + selection => selection.modify('move', 'right', 'character'), + '<div contenteditable dir="rtl">דהו<span style="display:inline-block">bar<br>יך|כ</span>זחט</div>', + 'End of line 2, move right, RTL resolved direction, LTR/RTL text inside'); + +selection_test( + '<div contenteditable dir="rtl">דהו<span style="display:inline-block">אבג<br>qux|</span>זחט</div>', + selection => selection.modify('move', 'right', 'character'), + '<div contenteditable dir="rtl">דהו<span style="display:inline-block">אבג<br>q|ux</span>זחט</div>', + 'End of line 2, move right, RTL resolved direction, RTL/LTR text inside'); + +selection_test( + '<div contenteditable dir="rtl">דהו<span style="display:inline-block">אבג<br>יךכ|</span>זחט</div>', + selection => selection.modify('move', 'right', 'character'), + '<div contenteditable dir="rtl">דהו<span style="display:inline-block">אבג<br>יך|כ</span>זחט</div>', + 'End of line 2, move right, RTL resolved direction, RTL/RTL text inside'); +</script>
diff --git a/third_party/blink/web_tests/editing/selection/modify_move/move_out_of_inline_block_nested.html b/third_party/blink/web_tests/editing/selection/modify_move/move_out_of_inline_block_nested.html new file mode 100644 index 0000000..63bdd6b --- /dev/null +++ b/third_party/blink/web_tests/editing/selection/modify_move/move_out_of_inline_block_nested.html
@@ -0,0 +1,101 @@ +<!DOCTYPE html> +<script src="../../../resources/testharness.js"></script> +<script src="../../../resources/testharnessreport.js"></script> +<script src="../../assert_selection.js"></script> +<script> +selection_test( + [ + '<div contenteditable>foo', + '<span style="display:inline-block">', + '<div>|bar</div><div>baz</div>', + '</span>qux</div>' + ].join(''), + selection => selection.modify('move', 'left', 'character'), + [ + '<div contenteditable>foo|', + '<span style="display:inline-block">', + '<div>bar</div><div>baz</div>', + '</span>qux</div>' + ].join(''), + 'Move left out of inline block with child blocks'); + +selection_test( + [ + '<div contenteditable>foo', + '<span style="display:inline-block">', + '<div>bar</div><div>baz|</div>', + '</span>qux</div>' + ].join(''), + selection => selection.modify('move', 'right', 'character'), + [ + '<div contenteditable>foo', + '<span style="display:inline-block">', + '<div>bar</div><div>baz</div>', + '</span>|qux</div>' + ].join(''), + 'Move right out of inline block with child blocks'); + +selection_test( + [ + '<div contenteditable>foo', + '<table style="display:inline"><tbody>', + '<tr><td>|bar</td></tr><tr><td>baz</td></tr>', + '</tbody></table>qux</div>' + ].join(''), + selection => selection.modify('move', 'left', 'character'), + [ + '<div contenteditable>foo|', + '<table style="display:inline"><tbody>', + '<tr><td>bar</td></tr><tr><td>baz</td></tr>', + '</tbody></table>qux</div>' + ].join(''), + 'Move left out of inline table'); + +selection_test( + [ + '<div contenteditable>foo', + '<table style="display:inline"><tbody>', + '<tr><td>bar</td></tr><tr><td>baz|</td></tr>', + '</tbody></table>qux</div>' + ].join(''), + selection => selection.modify('move', 'right', 'character'), + [ + '<div contenteditable>foo', + '<table style="display:inline"><tbody>', + '<tr><td>bar</td></tr><tr><td>baz</td></tr>', + '</tbody></table>|qux</div>' + ].join(''), + 'Move right out of inline table'); + +selection_test( + [ + '<div contenteditable>foo', + '<div style="display:inline-flex">', + '<div>|bar</div><div>baz</div>', + '</div>qux</div>' + ].join(''), + selection => selection.modify('move', 'left', 'character'), + [ + '<div contenteditable>foo|', + '<div style="display:inline-flex">', + '<div>bar</div><div>baz</div>', + '</div>qux</div>' + ].join(''), + 'Move left out of inline flex'); + +selection_test( + [ + '<div contenteditable>foo', + '<div style="display:inline-flex">', + '<div>bar</div><div>baz|</div>', + '</div>qux</div>' + ].join(''), + selection => selection.modify('move', 'right', 'character'), + [ + '<div contenteditable>foo', + '<div style="display:inline-flex">', + '<div>bar</div><div>baz</div>', + '</div>|qux</div>' + ].join(''), + 'Move right out of inline flex'); +</script>
diff --git a/third_party/blink/web_tests/editing/selection/modify_move/move_out_of_inline_block_one_line.html b/third_party/blink/web_tests/editing/selection/modify_move/move_out_of_inline_block_one_line.html new file mode 100644 index 0000000..4d0f495c --- /dev/null +++ b/third_party/blink/web_tests/editing/selection/modify_move/move_out_of_inline_block_one_line.html
@@ -0,0 +1,109 @@ +<!DOCTYPE html> +<script src="../../../resources/testharness.js"></script> +<script src="../../../resources/testharnessreport.js"></script> +<script src="../../assert_selection.js"></script> +<script> +// Variations: +// 1. Whether at start or end of the inline block +// 2. Moving left or right +// 2. Resolved direction of the inline block in the parent context +// 3. Direction of text inside the inline block + +const usesBidiAffinity = window.internals && internals.runtimeFlags.bidiCaretAffinityEnabled; + +selection_test( + '<div contenteditable>foo<span style="display:inline-block">|bar</span>baz</div>', + selection => selection.modify('move', 'right', 'character'), + '<div contenteditable>foo<span style="display:inline-block">b|ar</span>baz</div>', + 'From start, move right, LTR resolved direction, LTR text inside'); + +selection_test( + '<div contenteditable>foo<span style="display:inline-block">|bar</span>baz</div>', + selection => selection.modify('move', 'left', 'character'), + '<div contenteditable>fo|o<span style="display:inline-block">bar</span>baz</div>', + 'From start, move left, LTR resolved direction, LTR text inside'); + +selection_test( + '<div contenteditable>foo<span style="display:inline-block">bar|</span>baz</div>', + selection => selection.modify('move', 'right', 'character'), + '<div contenteditable>foo<span style="display:inline-block">bar</span>b|az</div>', + 'From end, move right, LTR resolved direction, LTR text inside'); + +selection_test( + '<div contenteditable>foo<span style="display:inline-block">bar|</span>baz</div>', + selection => selection.modify('move', 'left', 'character'), + '<div contenteditable>foo<span style="display:inline-block">ba|r</span>baz</div>', + 'From end, move left, LTR resolved direction, LTR text inside'); + +selection_test( + '<div contenteditable>foo<span style="display:inline-block">|\u05D0\u05D1\u05D2</span>baz</div>', + selection => selection.modify('move', 'right', 'character'), + '<div contenteditable>foo<span style="display:inline-block">\u05D0|\u05D1\u05D2</span>baz</div>', + 'From start, move right, LTR resolved direction, RTL text inside'); + +selection_test( + '<div contenteditable>foo<span style="display:inline-block">|\u05D0\u05D1\u05D2</span>baz</div>', + selection => selection.modify('move', 'left', 'character'), + '<div contenteditable>fo|o<span style="display:inline-block">\u05D0\u05D1\u05D2</span>baz</div>', + 'From start, move left, LTR resolved direction, RTL text inside'); + +selection_test( + '<div contenteditable>foo<span style="display:inline-block">\u05D0\u05D1\u05D2|</span>baz</div>', + selection => selection.modify('move', 'right', 'character'), + '<div contenteditable>foo<span style="display:inline-block">\u05D0\u05D1\u05D2</span>b|az</div>', + 'From end, move right, LTR resolved direction, RTL text inside'); + +selection_test( + '<div contenteditable>foo<span style="display:inline-block">\u05D0\u05D1\u05D2|</span>baz</div>', + selection => selection.modify('move', 'left', 'character'), + '<div contenteditable>foo<span style="display:inline-block">\u05D0|\u05D1\u05D2</span>baz</div>', + 'From end, move left, LTR resolved direction, RTL text inside'); + +selection_test( + '<div contenteditable dir="rtl">\u05D3\u05D4\u05D5<span style="display:inline-block">|bar</span>\u05D6\u05D7\u05D8</div>', + selection => selection.modify('move', 'right', 'character'), + '<div contenteditable dir="rtl">\u05D3\u05D4|\u05D5<span style="display:inline-block">bar</span>\u05D6\u05D7\u05D8</div>', + 'From start, move right, RTL resolved direction, LTR text inside'); + +selection_test( + '<div contenteditable dir="rtl">\u05D3\u05D4\u05D5<span style="display:inline-block">|bar</span>\u05D6\u05D7\u05D8</div>', + selection => selection.modify('move', 'left', 'character'), + '<div contenteditable dir="rtl">\u05D3\u05D4\u05D5<span style="display:inline-block">b|ar</span>\u05D6\u05D7\u05D8</div>', + 'From start, move left, RTL resolved direction, LTR text inside'); + +selection_test( + '<div contenteditable dir="rtl">\u05D3\u05D4\u05D5<span style="display:inline-block">bar|</span>\u05D6\u05D7\u05D8</div>', + selection => selection.modify('move', 'right', 'character'), + '<div contenteditable dir="rtl">\u05D3\u05D4\u05D5<span style="display:inline-block">b|ar</span>\u05D6\u05D7\u05D8</div>', + 'From end, move right, RTL resolved direction, LTR text inside'); + +selection_test( + '<div contenteditable dir="rtl">\u05D3\u05D4\u05D5<span style="display:inline-block">bar|</span>\u05D6\u05D7\u05D8</div>', + selection => selection.modify('move', 'left', 'character'), + '<div contenteditable dir="rtl">\u05D3\u05D4\u05D5<span style="display:inline-block">bar</span>\u05D6|\u05D7\u05D8</div>', + 'From end, move left, RTL resolved direction, LTR text inside'); + +selection_test( + '<div contenteditable dir="rtl">\u05D3\u05D4\u05D5<span style="display:inline-block">|\u05D0\u05D1\u05D2</span>\u05D6\u05D7\u05D8</div>', + selection => selection.modify('move', 'right', 'character'), + '<div contenteditable dir="rtl">\u05D3\u05D4|\u05D5<span style="display:inline-block">\u05D0\u05D1\u05D2</span>\u05D6\u05D7\u05D8</div>', + 'From start, move right, RTL resolved direction, RTL text inside'); + +selection_test( + '<div contenteditable dir="rtl">\u05D3\u05D4\u05D5<span style="display:inline-block">|\u05D0\u05D1\u05D2</span>\u05D6\u05D7\u05D8</div>', + selection => selection.modify('move', 'left', 'character'), + '<div contenteditable dir="rtl">\u05D3\u05D4\u05D5<span style="display:inline-block">\u05D0|\u05D1\u05D2</span>\u05D6\u05D7\u05D8</div>', + 'From start, move left, RTL resolved direction, RTL text inside'); + +selection_test( + '<div contenteditable dir="rtl">\u05D3\u05D4\u05D5<span style="display:inline-block">\u05D0\u05D1\u05D2|</span>\u05D6\u05D7\u05D8</div>', + selection => selection.modify('move', 'right', 'character'), + '<div contenteditable dir="rtl">\u05D3\u05D4\u05D5<span style="display:inline-block">\u05D0\u05D1|\u05D2</span>\u05D6\u05D7\u05D8</div>', + 'From end, move right, RTL resolved direction, RTL text inside'); + +selection_test( + '<div contenteditable dir="rtl">\u05D3\u05D4\u05D5<span style="display:inline-block">\u05D0\u05D1\u05D2|</span>\u05D6\u05D7\u05D8</div>', + selection => selection.modify('move', 'left', 'character'), + '<div contenteditable dir="rtl">\u05D3\u05D4\u05D5<span style="display:inline-block">\u05D0\u05D1\u05D2</span>\u05D6|\u05D7\u05D8</div>', + 'From end, move left, RTL resolved direction, RTL text inside'); +</script>
diff --git a/third_party/blink/web_tests/external/wpt/css/css-ui/appearance-cssom-001-expected.txt b/third_party/blink/web_tests/external/wpt/css/css-ui/appearance-cssom-001-expected.txt index ee395e8..5c7b72d 100644 --- a/third_party/blink/web_tests/external/wpt/css/css-ui/appearance-cssom-001-expected.txt +++ b/third_party/blink/web_tests/external/wpt/css/css-ui/appearance-cssom-001-expected.txt
@@ -1,17 +1,17 @@ This is a testharness.js-based test. -Found 344 tests; 157 PASS, 187 FAIL, 0 TIMEOUT, 0 NOTRUN. +Found 344 tests; 165 PASS, 179 FAIL, 0 TIMEOUT, 0 NOTRUN. PASS -webkit-appearance: none FAIL -webkit-appearance: auto assert_equals: style.WebkitAppearance (uppercase W) expected "auto" but got "" PASS -webkit-appearance: button -PASS -webkit-appearance: button-bevel -PASS -webkit-appearance: caret +FAIL -webkit-appearance: button-bevel assert_equals: style.WebkitAppearance (uppercase W) expected "button-bevel" but got "" +FAIL -webkit-appearance: caret assert_equals: style.WebkitAppearance (uppercase W) expected "caret" but got "" PASS -webkit-appearance: checkbox PASS -webkit-appearance: listbox -PASS -webkit-appearance: listitem +FAIL -webkit-appearance: listitem assert_equals: style.WebkitAppearance (uppercase W) expected "listitem" but got "" PASS -webkit-appearance: menulist PASS -webkit-appearance: menulist-button -PASS -webkit-appearance: menulist-text -PASS -webkit-appearance: menulist-textfield +FAIL -webkit-appearance: menulist-text assert_equals: style.WebkitAppearance (uppercase W) expected "menulist-text" but got "" +FAIL -webkit-appearance: menulist-textfield assert_equals: style.WebkitAppearance (uppercase W) expected "menulist-textfield" but got "" PASS -webkit-appearance: meter PASS -webkit-appearance: progress-bar PASS -webkit-appearance: push-button @@ -42,31 +42,31 @@ FAIL -webkit-appearance: inner-spin-button (invalid) assert_equals: style.WebkitAppearance (uppercase W) expected "" but got "inner-spin-button" PASS -webkit-appearance: image-controls-button (invalid) PASS -webkit-appearance: list-button (invalid) -FAIL -webkit-appearance: listitem (invalid) assert_equals: style.WebkitAppearance (uppercase W) expected "" but got "listitem" -FAIL -webkit-appearance: media-enter-fullscreen-button (invalid) assert_equals: style.WebkitAppearance (uppercase W) expected "" but got "media-enter-fullscreen-button" -FAIL -webkit-appearance: media-exit-fullscreen-button (invalid) assert_equals: style.WebkitAppearance (uppercase W) expected "" but got "media-exit-fullscreen-button" +PASS -webkit-appearance: listitem (invalid) +PASS -webkit-appearance: media-enter-fullscreen-button (invalid) +PASS -webkit-appearance: media-exit-fullscreen-button (invalid) PASS -webkit-appearance: media-fullscreen-volume-slider (invalid) PASS -webkit-appearance: media-fullscreen-volume-slider-thumb (invalid) -FAIL -webkit-appearance: media-mute-button (invalid) assert_equals: style.WebkitAppearance (uppercase W) expected "" but got "media-mute-button" -FAIL -webkit-appearance: media-play-button (invalid) assert_equals: style.WebkitAppearance (uppercase W) expected "" but got "media-play-button" -FAIL -webkit-appearance: media-overlay-play-button (invalid) assert_equals: style.WebkitAppearance (uppercase W) expected "" but got "media-overlay-play-button" +PASS -webkit-appearance: media-mute-button (invalid) +PASS -webkit-appearance: media-play-button (invalid) +PASS -webkit-appearance: media-overlay-play-button (invalid) PASS -webkit-appearance: media-return-to-realtime-button (invalid) PASS -webkit-appearance: media-rewind-button (invalid) PASS -webkit-appearance: media-seek-back-button (invalid) PASS -webkit-appearance: media-seek-forward-button (invalid) -FAIL -webkit-appearance: media-toggle-closed-captions-button (invalid) assert_equals: style.WebkitAppearance (uppercase W) expected "" but got "media-toggle-closed-captions-button" +PASS -webkit-appearance: media-toggle-closed-captions-button (invalid) FAIL -webkit-appearance: media-slider (invalid) assert_equals: style.WebkitAppearance (uppercase W) expected "" but got "media-slider" FAIL -webkit-appearance: media-sliderthumb (invalid) assert_equals: style.WebkitAppearance (uppercase W) expected "" but got "media-sliderthumb" -FAIL -webkit-appearance: media-volume-slider-container (invalid) assert_equals: style.WebkitAppearance (uppercase W) expected "" but got "media-volume-slider-container" +PASS -webkit-appearance: media-volume-slider-container (invalid) PASS -webkit-appearance: media-volume-slider-mute-button (invalid) FAIL -webkit-appearance: media-volume-slider (invalid) assert_equals: style.WebkitAppearance (uppercase W) expected "" but got "media-volume-slider" FAIL -webkit-appearance: media-volume-sliderthumb (invalid) assert_equals: style.WebkitAppearance (uppercase W) expected "" but got "media-volume-sliderthumb" -FAIL -webkit-appearance: media-controls-background (invalid) assert_equals: style.WebkitAppearance (uppercase W) expected "" but got "media-controls-background" +PASS -webkit-appearance: media-controls-background (invalid) PASS -webkit-appearance: media-controls-dark-bar-background (invalid) -FAIL -webkit-appearance: media-controls-fullscreen-background (invalid) assert_equals: style.WebkitAppearance (uppercase W) expected "" but got "media-controls-fullscreen-background" +PASS -webkit-appearance: media-controls-fullscreen-background (invalid) PASS -webkit-appearance: media-controls-light-bar-background (invalid) -FAIL -webkit-appearance: media-current-time-display (invalid) assert_equals: style.WebkitAppearance (uppercase W) expected "" but got "media-current-time-display" -FAIL -webkit-appearance: media-time-remaining-display (invalid) assert_equals: style.WebkitAppearance (uppercase W) expected "" but got "media-time-remaining-display" +PASS -webkit-appearance: media-current-time-display (invalid) +PASS -webkit-appearance: media-time-remaining-display (invalid) PASS -webkit-appearance: menuarrow (invalid) PASS -webkit-appearance: menubar (invalid) PASS -webkit-appearance: menucheckbox (invalid) @@ -79,7 +79,7 @@ PASS -webkit-appearance: meterbar (invalid) PASS -webkit-appearance: meterchunk (invalid) PASS -webkit-appearance: number-input (invalid) -FAIL -webkit-appearance: progress-bar-value (invalid) assert_equals: style.WebkitAppearance (uppercase W) expected "" but got "progress-bar-value" +PASS -webkit-appearance: progress-bar-value (invalid) PASS -webkit-appearance: progressbar (invalid) PASS -webkit-appearance: progressbar-vertical (invalid) PASS -webkit-appearance: progresschunk (invalid)
diff --git a/third_party/blink/web_tests/external/wpt/custom-elements/CustomElementRegistry-expected.txt b/third_party/blink/web_tests/external/wpt/custom-elements/CustomElementRegistry-expected.txt index d67fab0..a93d4f86 100644 --- a/third_party/blink/web_tests/external/wpt/custom-elements/CustomElementRegistry-expected.txt +++ b/third_party/blink/web_tests/external/wpt/custom-elements/CustomElementRegistry-expected.txt
@@ -9,7 +9,7 @@ PASS customElements.define must check IsConstructor on the constructor before checking the element definition is running flag PASS customElements.define must validate the custom element name before checking the element definition is running flag PASS customElements.define unset the element definition is running flag before upgrading custom elements -FAIL customElements.define must not throw when defining another custom element in a different global object during Get(constructor, "prototype") Failed to execute 'define' on 'CustomElementRegistry': this name has already been used with this registry +FAIL customElements.define must not throw when defining another custom element in a different global object during Get(constructor, "prototype") Failed to execute 'define' on 'CustomElementRegistry': the name "another-custom-element" has already been used with this registry PASS Custom Elements: CustomElementRegistry interface FAIL customElements.define must get "prototype" property of the constructor assert_array_equals: lengths differ, expected 1 got 3 PASS customElements.define must rethrow an exception thrown while getting "prototype" property of the constructor
diff --git a/third_party/blink/web_tests/external/wpt/fetch/stale-while-revalidate/stale-css.py b/third_party/blink/web_tests/external/wpt/fetch/stale-while-revalidate/stale-css.py index 9566833..a6ae546d 100644 --- a/third_party/blink/web_tests/external/wpt/fetch/stale-while-revalidate/stale-css.py +++ b/third_party/blink/web_tests/external/wpt/fetch/stale-while-revalidate/stale-css.py
@@ -1,18 +1,23 @@ def main(request, response): token = request.GET.first("token", None) - value = request.server.stash.take(token) - count = 0 - if value != None: - count = int(value) - if request.GET.first("query", None) != None: + is_query = request.GET.first("query", None) != None + with request.server.stash.lock: + value = request.server.stash.take(token) + count = 0 + if value != None: + count = int(value) + if is_query: + if count < 2: + request.server.stash.put(token, count) + else: + count = count + 1 + request.server.stash.put(token, count) + if is_query: headers = [("Count", count)] content = "" - if count < 2: - request.server.stash.put(token, count) return 200, headers, content else: - count = count + 1 content = "body { background: rgb(0, 128, 0); }" if count > 1: content = "body { background: rgb(255, 0, 0); }" @@ -20,5 +25,4 @@ headers = [("Content-Type", "text/css"), ("Cache-Control", "private, max-age=0, stale-while-revalidate=60")] - request.server.stash.put(token, count) return 200, headers, content
diff --git a/third_party/blink/web_tests/external/wpt/fetch/stale-while-revalidate/stale-image.py b/third_party/blink/web_tests/external/wpt/fetch/stale-while-revalidate/stale-image.py index e0cf94bc..4b671841 100644 --- a/third_party/blink/web_tests/external/wpt/fetch/stale-while-revalidate/stale-image.py +++ b/third_party/blink/web_tests/external/wpt/fetch/stale-while-revalidate/stale-image.py
@@ -3,18 +3,24 @@ def main(request, response): token = request.GET.first("token", None) - value = request.server.stash.take(token) - count = 0 - if value != None: - count = int(value) - if request.GET.first("query", None) != None: + is_query = request.GET.first("query", None) != None + with request.server.stash.lock: + value = request.server.stash.take(token) + count = 0 + if value != None: + count = int(value) + if is_query: + if count < 2: + request.server.stash.put(token, count) + else: + count = count + 1 + request.server.stash.put(token, count) + + if is_query: headers = [("Count", count)] content = "" - if count < 2: - request.server.stash.put(token, count) return 200, headers, content else: - count = count + 1 filename = "green-16x16.png" if count > 1: filename = "green-256x256.png" @@ -22,7 +28,6 @@ path = os.path.join(os.path.dirname(__file__), "../../images", filename) body = open(path, "rb").read() - request.server.stash.put(token, count) response.add_required_headers = False response.writer.write_status(200) response.writer.write_header("content-length", len(body))
diff --git a/third_party/blink/web_tests/external/wpt/fetch/stale-while-revalidate/stale-script.py b/third_party/blink/web_tests/external/wpt/fetch/stale-while-revalidate/stale-script.py index 5ea5987db..8ad5467 100644 --- a/third_party/blink/web_tests/external/wpt/fetch/stale-while-revalidate/stale-script.py +++ b/third_party/blink/web_tests/external/wpt/fetch/stale-while-revalidate/stale-script.py
@@ -6,23 +6,27 @@ def main(request, response): token = request.GET.first("token", None) - value = request.server.stash.take(token) - count = 0 - if value != None: - count = int(value) - if request.GET.first("query", None) != None: + is_query = request.GET.first("query", None) != None + with request.server.stash.lock: + value = request.server.stash.take(token) + count = 0 + if value != None: + count = int(value) + if is_query: + if count < 2: + request.server.stash.put(token, count) + else: + count = count + 1 + request.server.stash.put(token, count) + + if is_query: headers = [("Count", count)] content = "" - if count < 2: - request.server.stash.put(token, count) return 200, headers, content else: - count = count + 1 - unique_id = id_token() headers = [("Content-Type", "text/javascript"), ("Cache-Control", "private, max-age=0, stale-while-revalidate=60"), ("Unique-Id", unique_id)] content = "report('{}')".format(unique_id) - request.server.stash.put(token, count) return 200, headers, content
diff --git a/third_party/blink/web_tests/external/wpt/infrastructure/metadata/infrastructure/testdriver/actions/actionsWithKeyPressed.html.ini b/third_party/blink/web_tests/external/wpt/infrastructure/metadata/infrastructure/testdriver/actions/actionsWithKeyPressed.html.ini index 78bfa5f..5df5c1f 100644 --- a/third_party/blink/web_tests/external/wpt/infrastructure/metadata/infrastructure/testdriver/actions/actionsWithKeyPressed.html.ini +++ b/third_party/blink/web_tests/external/wpt/infrastructure/metadata/infrastructure/testdriver/actions/actionsWithKeyPressed.html.ini
@@ -1,3 +1,3 @@ [actionsWithKeyPressed.html] expected: - if product == "safari": ERROR + if product == "safari" or product == "firefox": ERROR
diff --git a/third_party/blink/web_tests/external/wpt/webrtc/RTCDtlsTransport-getRemoteCertificates-expected.txt b/third_party/blink/web_tests/external/wpt/webrtc/RTCDtlsTransport-getRemoteCertificates-expected.txt index eca828b..e4e58c43 100644 --- a/third_party/blink/web_tests/external/wpt/webrtc/RTCDtlsTransport-getRemoteCertificates-expected.txt +++ b/third_party/blink/web_tests/external/wpt/webrtc/RTCDtlsTransport-getRemoteCertificates-expected.txt
@@ -1,4 +1,4 @@ This is a testharness.js-based test. -FAIL RTCDtlsTransport.prototype.getRemoteCertificates RTCSctpTransport is not defined +FAIL RTCDtlsTransport.prototype.getRemoteCertificates dtlsTransport.getCertificates is not a function Harness: the test ran to completion.
diff --git a/third_party/blink/web_tests/external/wpt/webrtc/RTCIceTransport-expected.txt b/third_party/blink/web_tests/external/wpt/webrtc/RTCIceTransport-expected.txt index 8fcf2e2..5de6f8a 100644 --- a/third_party/blink/web_tests/external/wpt/webrtc/RTCIceTransport-expected.txt +++ b/third_party/blink/web_tests/external/wpt/webrtc/RTCIceTransport-expected.txt
@@ -1,5 +1,5 @@ This is a testharness.js-based test. -FAIL Two connected iceTransports should has matching local/remote candidates returned promise_test: Unhandled rejection with value: object "ReferenceError: RTCSctpTransport is not defined" -FAIL Unconnected iceTransport should have empty remote candidates and selected pair promise_test: Unhandled rejection with value: object "ReferenceError: RTCSctpTransport is not defined" +FAIL Two connected iceTransports should has matching local/remote candidates returned promise_test: Unhandled rejection with value: object "ReferenceError: RTCIceTransport is not defined" +FAIL Unconnected iceTransport should have empty remote candidates and selected pair promise_test: Unhandled rejection with value: object "ReferenceError: RTCIceTransport is not defined" Harness: the test ran to completion.
diff --git a/third_party/blink/web_tests/external/wpt/webrtc/RTCPeerConnection-connectionState-expected.txt b/third_party/blink/web_tests/external/wpt/webrtc/RTCPeerConnection-connectionState-expected.txt index 8b1b808..1aca75f 100644 --- a/third_party/blink/web_tests/external/wpt/webrtc/RTCPeerConnection-connectionState-expected.txt +++ b/third_party/blink/web_tests/external/wpt/webrtc/RTCPeerConnection-connectionState-expected.txt
@@ -2,6 +2,6 @@ PASS Initial connectionState should be new PASS Closing the connection should set connectionState to closed PASS connection with one data channel should eventually have connected connection state -FAIL connection with one data channel should eventually have transports in connected state Cannot read property 'transport' of undefined +FAIL connection with one data channel should eventually have transports in connected state assert_true: Expect ICE transport to be in connected or completed state expected true got false Harness: the test ran to completion.
diff --git a/third_party/blink/web_tests/external/wpt/webrtc/RTCPeerConnection-iceConnectionState.https-expected.txt b/third_party/blink/web_tests/external/wpt/webrtc/RTCPeerConnection-iceConnectionState.https-expected.txt index c5fd94e..96e7bba4 100644 --- a/third_party/blink/web_tests/external/wpt/webrtc/RTCPeerConnection-iceConnectionState.https-expected.txt +++ b/third_party/blink/web_tests/external/wpt/webrtc/RTCPeerConnection-iceConnectionState.https-expected.txt
@@ -2,7 +2,7 @@ PASS Initial iceConnectionState should be new PASS Closing the connection should set iceConnectionState to closed PASS connection with one data channel should eventually have connected or completed connection state -FAIL connection with one data channel should eventually have connected connection state Cannot read property 'transport' of undefined +FAIL connection with one data channel should eventually have connected connection state Cannot read property 'state' of undefined PASS ICE can connect in a recvonly usecase Harness: the test ran to completion.
diff --git a/third_party/blink/web_tests/external/wpt/webrtc/RTCPeerConnection-iceGatheringState-expected.txt b/third_party/blink/web_tests/external/wpt/webrtc/RTCPeerConnection-iceGatheringState-expected.txt index cf325d5..91d147a 100644 --- a/third_party/blink/web_tests/external/wpt/webrtc/RTCPeerConnection-iceGatheringState-expected.txt +++ b/third_party/blink/web_tests/external/wpt/webrtc/RTCPeerConnection-iceGatheringState-expected.txt
@@ -1,6 +1,6 @@ This is a testharness.js-based test. PASS Initial iceGatheringState should be new PASS iceGatheringState should eventually become complete after setLocalDescription -FAIL connection with one data channel should eventually have connected connection state Cannot read property 'transport' of undefined +FAIL connection with one data channel should eventually have connected connection state Cannot read property 'gatheringState' of undefined Harness: the test ran to completion.
diff --git a/third_party/blink/web_tests/external/wpt/webrtc/RTCSctpTransport-constructor-expected.txt b/third_party/blink/web_tests/external/wpt/webrtc/RTCSctpTransport-constructor-expected.txt deleted file mode 100644 index f4f36f4a..0000000 --- a/third_party/blink/web_tests/external/wpt/webrtc/RTCSctpTransport-constructor-expected.txt +++ /dev/null
@@ -1,5 +0,0 @@ -This is a testharness.js-based test. -FAIL setRemoteDescription() with answer containing data media should initialize pc.sctp assert_equals: expected (object) null but got (undefined) undefined -FAIL setLocalDescription() with answer containing data media should initialize pc.sctp assert_equals: expected (object) null but got (undefined) undefined -Harness: the test ran to completion. -
diff --git a/third_party/blink/web_tests/external/wpt/webrtc/RTCSctpTransport-constructor.html b/third_party/blink/web_tests/external/wpt/webrtc/RTCSctpTransport-constructor.html index 7d3df051..28dae05 100644 --- a/third_party/blink/web_tests/external/wpt/webrtc/RTCSctpTransport-constructor.html +++ b/third_party/blink/web_tests/external/wpt/webrtc/RTCSctpTransport-constructor.html
@@ -59,7 +59,7 @@ assert_true(sctp.transport instanceof RTCDtlsTransport, 'Expect sctp.transport to be instance of RTCDtlsTransport'); - assert_true(typeof sctp.maxMessageSize, 'number', + assert_true(typeof sctp.maxMessageSize == 'number', 'Expect sctp.maxMessageSize to be a number'); }); }, 'setRemoteDescription() with answer containing data media should initialize pc.sctp'); @@ -82,7 +82,7 @@ assert_true(sctp.transport instanceof RTCDtlsTransport, 'Expect sctp.transport to be instance of RTCDtlsTransport'); - assert_true(typeof sctp.maxMessageSize, 'number', + assert_true(typeof sctp.maxMessageSize == 'number', 'Expect sctp.maxMessageSize to be a number'); }); }, 'setLocalDescription() with answer containing data media should initialize pc.sctp');
diff --git a/third_party/blink/web_tests/external/wpt/webrtc/RTCSctpTransport-maxMessageSize-expected.txt b/third_party/blink/web_tests/external/wpt/webrtc/RTCSctpTransport-maxMessageSize-expected.txt index 4d1f9a1..95278159 100644 --- a/third_party/blink/web_tests/external/wpt/webrtc/RTCSctpTransport-maxMessageSize-expected.txt +++ b/third_party/blink/web_tests/external/wpt/webrtc/RTCSctpTransport-maxMessageSize-expected.txt
@@ -1,8 +1,8 @@ This is a testharness.js-based test. -FAIL Determine the local side send limitation (canSendSize) by offering a max-message-size of 0 assert_equals: expected (object) null but got (undefined) undefined -FAIL Remote offer SDP missing max-message-size attribute assert_equals: expected (object) null but got (undefined) undefined -FAIL max-message-size with a (non-zero) value provided by the remote peer assert_equals: expected (object) null but got (undefined) undefined -FAIL Renegotiate max-message-size with a (non-zero) value provided by the remote peer assert_equals: expected (object) null but got (undefined) undefined -FAIL max-message-size with a (non-zero) value larger than canSendSize provided by the remote peer assert_equals: expected (object) null but got (undefined) undefined +FAIL Determine the local side send limitation (canSendSize) by offering a max-message-size of 0 assert_not_equals: SDP should have max-message-size attribute got disallowed value null +FAIL Remote offer SDP missing max-message-size attribute assert_not_equals: SDP should have max-message-size attribute got disallowed value null +FAIL max-message-size with a (non-zero) value provided by the remote peer assert_not_equals: SDP should have max-message-size attribute got disallowed value null +FAIL Renegotiate max-message-size with a (non-zero) value provided by the remote peer assert_not_equals: SDP should have max-message-size attribute got disallowed value null +FAIL max-message-size with a (non-zero) value larger than canSendSize provided by the remote peer assert_not_equals: SDP should have max-message-size attribute got disallowed value null Harness: the test ran to completion.
diff --git a/third_party/blink/web_tests/external/wpt/webrtc/idlharness.https.window-expected.txt b/third_party/blink/web_tests/external/wpt/webrtc/idlharness.https.window-expected.txt index 8191ea2..3910ac5 100644 --- a/third_party/blink/web_tests/external/wpt/webrtc/idlharness.https.window-expected.txt +++ b/third_party/blink/web_tests/external/wpt/webrtc/idlharness.https.window-expected.txt
@@ -1,8 +1,8 @@ This is a testharness.js-based test. -Found 494 tests; 378 PASS, 116 FAIL, 0 TIMEOUT, 0 NOTRUN. +Found 494 tests; 412 PASS, 82 FAIL, 0 TIMEOUT, 0 NOTRUN. PASS idl_test setup PASS Test driver for asyncInitCertificate -FAIL Test driver for asyncInitTransports assert_unreached: Failed to run asyncInitTransports: ReferenceError: RTCSctpTransport is not defined Reached unreachable code +PASS Test driver for asyncInitTransports PASS Test driver for asyncInitMediaStreamTrack PASS Partial interface RTCPeerConnection: original interface defined PASS Partial dictionary RTCOfferOptions: original dictionary defined @@ -57,7 +57,7 @@ PASS RTCPeerConnection interface: operation removeTrack(RTCRtpSender) PASS RTCPeerConnection interface: operation addTransceiver([object Object],[object Object], RTCRtpTransceiverInit) PASS RTCPeerConnection interface: attribute ontrack -FAIL RTCPeerConnection interface: attribute sctp assert_true: The prototype object must have a property "sctp" expected true got false +PASS RTCPeerConnection interface: attribute sctp PASS RTCPeerConnection interface: operation createDataChannel(USVString, RTCDataChannelInit) PASS RTCPeerConnection interface: attribute ondatachannel PASS RTCPeerConnection interface: operation getStats(MediaStreamTrack) @@ -119,7 +119,7 @@ PASS RTCPeerConnection interface: new RTCPeerConnection() must inherit property "addTransceiver([object Object],[object Object], RTCRtpTransceiverInit)" with the proper type PASS RTCPeerConnection interface: calling addTransceiver([object Object],[object Object], RTCRtpTransceiverInit) on new RTCPeerConnection() with too few arguments must throw TypeError FAIL RTCPeerConnection interface: new RTCPeerConnection() must inherit property "ontrack" with the proper type Unrecognized type EventHandler -FAIL RTCPeerConnection interface: new RTCPeerConnection() must inherit property "sctp" with the proper type assert_inherits: property "sctp" not found in prototype chain +PASS RTCPeerConnection interface: new RTCPeerConnection() must inherit property "sctp" with the proper type PASS RTCPeerConnection interface: new RTCPeerConnection() must inherit property "createDataChannel(USVString, RTCDataChannelInit)" with the proper type PASS RTCPeerConnection interface: calling createDataChannel(USVString, RTCDataChannelInit) on new RTCPeerConnection() with too few arguments must throw TypeError FAIL RTCPeerConnection interface: new RTCPeerConnection() must inherit property "ondatachannel" with the proper type Unrecognized type EventHandler @@ -315,13 +315,13 @@ PASS RTCDtlsTransport interface: operation getRemoteCertificates() PASS RTCDtlsTransport interface: attribute onstatechange PASS RTCDtlsTransport interface: attribute onerror -FAIL RTCDtlsTransport must be primary interface of idlTestObjects.dtlsTransport assert_equals: wrong typeof object expected "object" but got "undefined" -FAIL Stringification of idlTestObjects.dtlsTransport assert_equals: wrong typeof object expected "object" but got "undefined" -FAIL RTCDtlsTransport interface: idlTestObjects.dtlsTransport must inherit property "iceTransport" with the proper type assert_equals: wrong typeof object expected "object" but got "undefined" -FAIL RTCDtlsTransport interface: idlTestObjects.dtlsTransport must inherit property "state" with the proper type assert_equals: wrong typeof object expected "object" but got "undefined" -FAIL RTCDtlsTransport interface: idlTestObjects.dtlsTransport must inherit property "getRemoteCertificates()" with the proper type assert_equals: wrong typeof object expected "object" but got "undefined" -FAIL RTCDtlsTransport interface: idlTestObjects.dtlsTransport must inherit property "onstatechange" with the proper type assert_equals: wrong typeof object expected "object" but got "undefined" -FAIL RTCDtlsTransport interface: idlTestObjects.dtlsTransport must inherit property "onerror" with the proper type assert_equals: wrong typeof object expected "object" but got "undefined" +PASS RTCDtlsTransport must be primary interface of idlTestObjects.dtlsTransport +PASS Stringification of idlTestObjects.dtlsTransport +PASS RTCDtlsTransport interface: idlTestObjects.dtlsTransport must inherit property "iceTransport" with the proper type +PASS RTCDtlsTransport interface: idlTestObjects.dtlsTransport must inherit property "state" with the proper type +PASS RTCDtlsTransport interface: idlTestObjects.dtlsTransport must inherit property "getRemoteCertificates()" with the proper type +FAIL RTCDtlsTransport interface: idlTestObjects.dtlsTransport must inherit property "onstatechange" with the proper type Unrecognized type EventHandler +FAIL RTCDtlsTransport interface: idlTestObjects.dtlsTransport must inherit property "onerror" with the proper type Unrecognized type EventHandler FAIL RTCIceTransport interface: existence and properties of interface object assert_throws: interface object didn't throw TypeError when called as a constructor function "function() { new interface_object(); }" did not throw @@ -342,20 +342,20 @@ PASS RTCIceTransport interface: attribute onstatechange PASS RTCIceTransport interface: attribute ongatheringstatechange PASS RTCIceTransport interface: attribute onselectedcandidatepairchange -FAIL RTCIceTransport must be primary interface of idlTestObjects.iceTransport assert_equals: wrong typeof object expected "object" but got "undefined" -FAIL Stringification of idlTestObjects.iceTransport assert_equals: wrong typeof object expected "object" but got "undefined" -FAIL RTCIceTransport interface: idlTestObjects.iceTransport must inherit property "role" with the proper type assert_equals: wrong typeof object expected "object" but got "undefined" -FAIL RTCIceTransport interface: idlTestObjects.iceTransport must inherit property "component" with the proper type assert_equals: wrong typeof object expected "object" but got "undefined" -FAIL RTCIceTransport interface: idlTestObjects.iceTransport must inherit property "state" with the proper type assert_equals: wrong typeof object expected "object" but got "undefined" -FAIL RTCIceTransport interface: idlTestObjects.iceTransport must inherit property "gatheringState" with the proper type assert_equals: wrong typeof object expected "object" but got "undefined" -FAIL RTCIceTransport interface: idlTestObjects.iceTransport must inherit property "getLocalCandidates()" with the proper type assert_equals: wrong typeof object expected "object" but got "undefined" -FAIL RTCIceTransport interface: idlTestObjects.iceTransport must inherit property "getRemoteCandidates()" with the proper type assert_equals: wrong typeof object expected "object" but got "undefined" -FAIL RTCIceTransport interface: idlTestObjects.iceTransport must inherit property "getSelectedCandidatePair()" with the proper type assert_equals: wrong typeof object expected "object" but got "undefined" -FAIL RTCIceTransport interface: idlTestObjects.iceTransport must inherit property "getLocalParameters()" with the proper type assert_equals: wrong typeof object expected "object" but got "undefined" -FAIL RTCIceTransport interface: idlTestObjects.iceTransport must inherit property "getRemoteParameters()" with the proper type assert_equals: wrong typeof object expected "object" but got "undefined" -FAIL RTCIceTransport interface: idlTestObjects.iceTransport must inherit property "onstatechange" with the proper type assert_equals: wrong typeof object expected "object" but got "undefined" -FAIL RTCIceTransport interface: idlTestObjects.iceTransport must inherit property "ongatheringstatechange" with the proper type assert_equals: wrong typeof object expected "object" but got "undefined" -FAIL RTCIceTransport interface: idlTestObjects.iceTransport must inherit property "onselectedcandidatepairchange" with the proper type assert_equals: wrong typeof object expected "object" but got "undefined" +PASS RTCIceTransport must be primary interface of idlTestObjects.iceTransport +PASS Stringification of idlTestObjects.iceTransport +FAIL RTCIceTransport interface: idlTestObjects.iceTransport must inherit property "role" with the proper type assert_equals: expected "string" but got "object" +FAIL RTCIceTransport interface: idlTestObjects.iceTransport must inherit property "component" with the proper type assert_inherits: property "component" not found in prototype chain +PASS RTCIceTransport interface: idlTestObjects.iceTransport must inherit property "state" with the proper type +PASS RTCIceTransport interface: idlTestObjects.iceTransport must inherit property "gatheringState" with the proper type +PASS RTCIceTransport interface: idlTestObjects.iceTransport must inherit property "getLocalCandidates()" with the proper type +PASS RTCIceTransport interface: idlTestObjects.iceTransport must inherit property "getRemoteCandidates()" with the proper type +PASS RTCIceTransport interface: idlTestObjects.iceTransport must inherit property "getSelectedCandidatePair()" with the proper type +PASS RTCIceTransport interface: idlTestObjects.iceTransport must inherit property "getLocalParameters()" with the proper type +PASS RTCIceTransport interface: idlTestObjects.iceTransport must inherit property "getRemoteParameters()" with the proper type +FAIL RTCIceTransport interface: idlTestObjects.iceTransport must inherit property "onstatechange" with the proper type Unrecognized type EventHandler +FAIL RTCIceTransport interface: idlTestObjects.iceTransport must inherit property "ongatheringstatechange" with the proper type Unrecognized type EventHandler +FAIL RTCIceTransport interface: idlTestObjects.iceTransport must inherit property "onselectedcandidatepairchange" with the proper type Unrecognized type EventHandler PASS RTCTrackEvent interface: existence and properties of interface object PASS RTCTrackEvent interface object length PASS RTCTrackEvent interface object name @@ -372,24 +372,24 @@ PASS RTCTrackEvent interface: initTrackEvent() must inherit property "track" with the proper type PASS RTCTrackEvent interface: initTrackEvent() must inherit property "streams" with the proper type PASS RTCTrackEvent interface: initTrackEvent() must inherit property "transceiver" with the proper type -FAIL RTCSctpTransport interface: existence and properties of interface object assert_own_property: self does not have own property "RTCSctpTransport" expected property "RTCSctpTransport" missing -FAIL RTCSctpTransport interface object length assert_own_property: self does not have own property "RTCSctpTransport" expected property "RTCSctpTransport" missing -FAIL RTCSctpTransport interface object name assert_own_property: self does not have own property "RTCSctpTransport" expected property "RTCSctpTransport" missing -FAIL RTCSctpTransport interface: existence and properties of interface prototype object assert_own_property: self does not have own property "RTCSctpTransport" expected property "RTCSctpTransport" missing -FAIL RTCSctpTransport interface: existence and properties of interface prototype object's "constructor" property assert_own_property: self does not have own property "RTCSctpTransport" expected property "RTCSctpTransport" missing -FAIL RTCSctpTransport interface: existence and properties of interface prototype object's @@unscopables property assert_own_property: self does not have own property "RTCSctpTransport" expected property "RTCSctpTransport" missing -FAIL RTCSctpTransport interface: attribute transport assert_own_property: self does not have own property "RTCSctpTransport" expected property "RTCSctpTransport" missing -FAIL RTCSctpTransport interface: attribute state assert_own_property: self does not have own property "RTCSctpTransport" expected property "RTCSctpTransport" missing -FAIL RTCSctpTransport interface: attribute maxMessageSize assert_own_property: self does not have own property "RTCSctpTransport" expected property "RTCSctpTransport" missing -FAIL RTCSctpTransport interface: attribute maxChannels assert_own_property: self does not have own property "RTCSctpTransport" expected property "RTCSctpTransport" missing -FAIL RTCSctpTransport interface: attribute onstatechange assert_own_property: self does not have own property "RTCSctpTransport" expected property "RTCSctpTransport" missing -FAIL RTCSctpTransport must be primary interface of idlTestObjects.sctpTransport assert_equals: wrong typeof object expected "object" but got "undefined" -FAIL Stringification of idlTestObjects.sctpTransport assert_equals: wrong typeof object expected "object" but got "undefined" -FAIL RTCSctpTransport interface: idlTestObjects.sctpTransport must inherit property "transport" with the proper type assert_equals: wrong typeof object expected "object" but got "undefined" -FAIL RTCSctpTransport interface: idlTestObjects.sctpTransport must inherit property "state" with the proper type assert_equals: wrong typeof object expected "object" but got "undefined" -FAIL RTCSctpTransport interface: idlTestObjects.sctpTransport must inherit property "maxMessageSize" with the proper type assert_equals: wrong typeof object expected "object" but got "undefined" -FAIL RTCSctpTransport interface: idlTestObjects.sctpTransport must inherit property "maxChannels" with the proper type assert_equals: wrong typeof object expected "object" but got "undefined" -FAIL RTCSctpTransport interface: idlTestObjects.sctpTransport must inherit property "onstatechange" with the proper type assert_equals: wrong typeof object expected "object" but got "undefined" +PASS RTCSctpTransport interface: existence and properties of interface object +PASS RTCSctpTransport interface object length +PASS RTCSctpTransport interface object name +PASS RTCSctpTransport interface: existence and properties of interface prototype object +PASS RTCSctpTransport interface: existence and properties of interface prototype object's "constructor" property +PASS RTCSctpTransport interface: existence and properties of interface prototype object's @@unscopables property +PASS RTCSctpTransport interface: attribute transport +PASS RTCSctpTransport interface: attribute state +PASS RTCSctpTransport interface: attribute maxMessageSize +PASS RTCSctpTransport interface: attribute maxChannels +PASS RTCSctpTransport interface: attribute onstatechange +PASS RTCSctpTransport must be primary interface of idlTestObjects.sctpTransport +PASS Stringification of idlTestObjects.sctpTransport +PASS RTCSctpTransport interface: idlTestObjects.sctpTransport must inherit property "transport" with the proper type +PASS RTCSctpTransport interface: idlTestObjects.sctpTransport must inherit property "state" with the proper type +PASS RTCSctpTransport interface: idlTestObjects.sctpTransport must inherit property "maxMessageSize" with the proper type +PASS RTCSctpTransport interface: idlTestObjects.sctpTransport must inherit property "maxChannels" with the proper type +FAIL RTCSctpTransport interface: idlTestObjects.sctpTransport must inherit property "onstatechange" with the proper type Unrecognized type EventHandler PASS RTCDataChannel interface: existence and properties of interface object PASS RTCDataChannel interface object length PASS RTCDataChannel interface object name
diff --git a/third_party/blink/web_tests/external/wpt/webxr/idlharness.https.window-expected.txt b/third_party/blink/web_tests/external/wpt/webxr/idlharness.https.window-expected.txt index 979535e..6c0f3b1 100644 --- a/third_party/blink/web_tests/external/wpt/webxr/idlharness.https.window-expected.txt +++ b/third_party/blink/web_tests/external/wpt/webxr/idlharness.https.window-expected.txt
@@ -1,5 +1,5 @@ This is a testharness.js-based test. -Found 216 tests; 199 PASS, 17 FAIL, 0 TIMEOUT, 0 NOTRUN. +Found 216 tests; 200 PASS, 16 FAIL, 0 TIMEOUT, 0 NOTRUN. PASS idl_test setup PASS Partial interface Navigator: original interface defined PASS Partial dictionary WebGLContextAttributes: original dictionary defined @@ -124,7 +124,7 @@ PASS XRRigidTransform interface: attribute position PASS XRRigidTransform interface: attribute orientation PASS XRRigidTransform interface: attribute matrix -FAIL XRRigidTransform interface: operation inverse() assert_own_property: interface prototype object missing non-static operation expected property "inverse" missing +PASS XRRigidTransform interface: operation inverse() PASS XRRay interface: existence and properties of interface object PASS XRRay interface object length PASS XRRay interface object name
diff --git a/third_party/blink/web_tests/external/wpt/webxr/xrRigidTransform_inverse.https.html b/third_party/blink/web_tests/external/wpt/webxr/xrRigidTransform_inverse.https.html new file mode 100644 index 0000000..ddae2af --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/webxr/xrRigidTransform_inverse.https.html
@@ -0,0 +1,108 @@ +<!DOCTYPE html> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<script src="resources/webxr_util.js"></script> +<script src="resources/webxr_test_constants.js"></script> +<canvas id="webgl-canvas"></canvas> + +<script> + +let testName = "XRRigidTransform inverse works"; +let fakeDeviceInitParams = { supportsImmersive: true }; +let requestSessionOptions = { mode: 'immersive-vr' }; + +let testFunction = + (session, fakeDeviceController, t) => new Promise((resolve, reject) => { + + function assert_point_approx_equals(a, b) { + assert_approx_equals(a.x, b.x, FLOAT_EPSILON); + assert_approx_equals(a.y, b.y, FLOAT_EPSILON); + assert_approx_equals(a.z, b.z, FLOAT_EPSILON); + assert_approx_equals(a.w, b.w, FLOAT_EPSILON); + }; + + function assert_transform_approx_equals(a, b) { + assert_point_approx_equals(a.position, b.position); + assert_point_approx_equals(a.orientation, b.orientation); + }; + + // An identity transform should be equal to it's inverse. + let identity_transform = new XRRigidTransform(); + t.step(() => { + assert_transform_approx_equals(identity_transform, identity_transform.inverse()); + }); + + // Inversed transforms should yield the expected results + let transform = new XRRigidTransform( + { x: 1.0, y: 2.0, z: 3.0 }, + { x: 0.0, y: 0.0, z: 0.0, w: 1.0 }); + let inverse_transform = transform.inverse(); + let expected_inverse = new XRRigidTransform( + { x: -1.0, y: -2.0, z: -3.0 }, + { x: 0.0, y: 0.0, z: 0.0, w: 1.0 }); + t.step(() => { + assert_transform_approx_equals(inverse_transform, expected_inverse); + }); + + transform = new XRRigidTransform( + { x: 0.0, y: 0.0, z: 0.0 }, + { x: 1.0, y: 0.0, z: 0.0, w: 1.0 }); + inverse_transform = transform.inverse(); + expected_inverse = new XRRigidTransform( + { x: 0.0, y: 0.0, z: 0.0 }, + { x: -1.0, y: 0.0, z: 0.0, w: 1.0 }); + t.step(() => { + assert_transform_approx_equals(inverse_transform, expected_inverse); + }); + + transform = new XRRigidTransform( + { x: 1.0, y: 2.0, z: 3.0 }, + { x: 0.0, y: 1.0, z: 0.0, w: 1.0 }); + inverse_transform = transform.inverse(); + expected_inverse = new XRRigidTransform( + { x: 3.0, y: -2.0, z: -1.0 }, + { x: 0.0, y: -1.0, z: 0.0, w: 1.0 }); + t.step(() => { + assert_transform_approx_equals(inverse_transform, expected_inverse); + }); + + // Transforms should be equal to the inverse of their inverse. + transform = new XRRigidTransform( + { x: 1.0, y: 2.0, z: 3.0 }, + { x: 1.0, y: 2.0, z: 3.0, w: 4.0 }); + inverse_transform = transform.inverse(); + t.step(() => { + assert_transform_approx_equals(transform, inverse_transform.inverse()); + }); + + transform = new XRRigidTransform( + { x: -9.0, y: 8.0, z: -7.0 }, + { x: 6.0, y: -5.0, z: 4.0, w: 3.0 }); + inverse_transform = transform.inverse(); + t.step(() => { + assert_transform_approx_equals(transform, inverse_transform.inverse()); + }); + + transform = new XRRigidTransform( + { x: -2.0, y: 1.0, z: -4.0 }, + { x: 0.0, y: 1.0, z: 0.0, w: 1.0 }); + inverse_transform = transform.inverse(); + t.step(() => { + assert_transform_approx_equals(transform, inverse_transform.inverse()); + }); + + transform = new XRRigidTransform( + { x: 2.0, y: -1.0, z: 4.0 }, + { x: 1.0, y: 0.0, z: 0.0, w: 1.0 }); + inverse_transform = transform.inverse(); + t.step(() => { + assert_transform_approx_equals(transform, inverse_transform.inverse()); + }); + + resolve(); +}); + +xr_session_promise_test(testName, testFunction, fakeDeviceInitParams, + requestSessionOptions); + +</script>
diff --git a/third_party/blink/web_tests/fast/workers/resources/worker-location.js b/third_party/blink/web_tests/fast/workers/resources/worker-location.js deleted file mode 100644 index dce325b6..0000000 --- a/third_party/blink/web_tests/fast/workers/resources/worker-location.js +++ /dev/null
@@ -1,34 +0,0 @@ -function log(message) -{ - document.getElementById("result").innerHTML += message + "<br>"; -} - -if (window.testRunner) { - testRunner.dumpAsText(); - testRunner.waitUntilDone(); -} - -var worker = createWorker(); -worker.postMessage("eval WorkerLocation"); -worker.postMessage("eval typeof location"); -worker.postMessage("eval location"); -worker.postMessage("eval location.href"); -worker.postMessage("eval location.origin"); -worker.postMessage("eval location.protocol"); -worker.postMessage("eval location.host"); -worker.postMessage("eval location.hostname"); -worker.postMessage("eval location.port"); -worker.postMessage("eval location.pathname"); -worker.postMessage("eval location.search"); -worker.postMessage("eval location.hash"); -worker.postMessage("eval foo//bar"); - -worker.onmessage = function(evt) { - if (!/foo\/\/bar/.test(evt.data)) - log(evt.data.replace(new RegExp("/.*(LayoutTests|web_tests)"), "<...>")); - else { - log("DONE"); - if (window.testRunner) - testRunner.notifyDone(); - } -}
diff --git a/third_party/blink/web_tests/fast/workers/resources/worker-navigator.js b/third_party/blink/web_tests/fast/workers/resources/worker-navigator.js deleted file mode 100644 index d6c467a3..0000000 --- a/third_party/blink/web_tests/fast/workers/resources/worker-navigator.js +++ /dev/null
@@ -1,31 +0,0 @@ -function log(message) -{ - document.getElementById("result").innerHTML += message + "<br>"; -} - -if (window.testRunner) { - testRunner.dumpAsText(); - testRunner.waitUntilDone(); -} - -var worker = createWorker(); -worker.postMessage("eval typeof navigator"); -worker.postMessage("eval navigator"); -worker.postMessage("eval navigator.appName"); -worker.postMessage("eval navigator.appVersion.indexOf('WebKit') != 0"); -worker.postMessage("eval typeof navigator.platform"); -worker.postMessage("eval navigator.userAgent.indexOf('WebKit') != 0"); -worker.postMessage("eval typeof navigator.onLine"); -worker.postMessage("eval navigator.appCodeName === 'Mozilla'"); -worker.postMessage("eval navigator.product === 'Gecko'"); -worker.postMessage("eval foo//bar"); - -worker.onmessage = function(evt) { - if (!/foo\/\/bar/.test(evt.data)) - log(evt.data.replace(new RegExp("/.*(LayoutTests|web_tests)"), "<...>")); - else { - log("DONE"); - if (window.testRunner) - testRunner.notifyDone(); - } -}
diff --git a/third_party/blink/web_tests/fast/workers/resources/worker-replace-global-constructor.js b/third_party/blink/web_tests/fast/workers/resources/worker-replace-global-constructor.js deleted file mode 100644 index 795d565..0000000 --- a/third_party/blink/web_tests/fast/workers/resources/worker-replace-global-constructor.js +++ /dev/null
@@ -1,24 +0,0 @@ - -function log(message) -{ - document.getElementById("result").innerHTML += message + "<br>"; -} - -if (window.testRunner) { - testRunner.dumpAsText(); - testRunner.waitUntilDone(); -} - -var worker = createWorker(); -worker.postMessage("eval self.MessageEvent = 'PASS'; MessageEvent;"); -worker.postMessage("eval foo//bar"); - -worker.onmessage = function(evt) { - if (!/foo\/\/bar/.test(evt.data)) - log(evt.data); - else { - log("DONE"); - if (window.testRunner) - testRunner.notifyDone(); - } -}
diff --git a/third_party/blink/web_tests/fast/workers/resources/worker-replace-self.js b/third_party/blink/web_tests/fast/workers/resources/worker-replace-self.js deleted file mode 100644 index 40b0cb74..0000000 --- a/third_party/blink/web_tests/fast/workers/resources/worker-replace-self.js +++ /dev/null
@@ -1,24 +0,0 @@ -function log(message) -{ - document.getElementById("result").innerHTML += message + "<br>"; -} - -if (window.testRunner) { - testRunner.dumpAsText(); - testRunner.waitUntilDone(); -} - -var worker = createWorker(); -worker.postMessage("eval self='PASS'"); -worker.postMessage("eval self"); -worker.postMessage("eval foo//bar"); - -worker.onmessage = function(evt) { - if (!/foo\/\/bar/.test(evt.data)) - log(evt.data.replace(new RegExp("/.*(LayoutTests|web_tests)"), "<...>")); - else { - log("DONE"); - if (window.testRunner) - testRunner.notifyDone(); - } -}
diff --git a/third_party/blink/web_tests/fast/workers/worker-location-expected.txt b/third_party/blink/web_tests/fast/workers/worker-location-expected.txt deleted file mode 100644 index 58c95cb..0000000 --- a/third_party/blink/web_tests/fast/workers/worker-location-expected.txt +++ /dev/null
@@ -1,16 +0,0 @@ -Test WorkerLocation properties. - -WorkerLocation: function WorkerLocation() { [native code] } -typeof location: object -location: file:<...>/fast/workers/resources/worker-common.js -location.href: file:<...>/fast/workers/resources/worker-common.js -location.origin: file:// -location.protocol: file: -location.host: -location.hostname: -location.port: -location.pathname: <...>/fast/workers/resources/worker-common.js -location.search: -location.hash: -DONE -
diff --git a/third_party/blink/web_tests/fast/workers/worker-location.html b/third_party/blink/web_tests/fast/workers/worker-location.html deleted file mode 100644 index 5476084..0000000 --- a/third_party/blink/web_tests/fast/workers/worker-location.html +++ /dev/null
@@ -1,8 +0,0 @@ -<body> -<p>Test WorkerLocation properties.</p> -<div id=result></div> -<script src="../../resources/gc.js"></script> -<script src="resources/worker-create-common.js"></script> -<script src="resources/worker-location.js"></script> -</body> -</html>
diff --git a/third_party/blink/web_tests/fast/workers/worker-navigator-expected.txt b/third_party/blink/web_tests/fast/workers/worker-navigator-expected.txt deleted file mode 100644 index ed1c57a..0000000 --- a/third_party/blink/web_tests/fast/workers/worker-navigator-expected.txt +++ /dev/null
@@ -1,13 +0,0 @@ -Test Navigator properties. - -typeof navigator: object -navigator: [object WorkerNavigator] -navigator.appName: Netscape -navigator.appVersion.indexOf('WebKit') != 0: true -typeof navigator.platform: string -navigator.userAgent.indexOf('WebKit') != 0: true -typeof navigator.onLine: boolean -navigator.appCodeName === 'Mozilla': true -navigator.product === 'Gecko': true -DONE -
diff --git a/third_party/blink/web_tests/fast/workers/worker-navigator.html b/third_party/blink/web_tests/fast/workers/worker-navigator.html deleted file mode 100644 index f2773bc..0000000 --- a/third_party/blink/web_tests/fast/workers/worker-navigator.html +++ /dev/null
@@ -1,6 +0,0 @@ -<body> -<p>Test Navigator properties.</p> -<div id=result></div> -<script src="resources/worker-create-common.js"></script> -<script src="resources/worker-navigator.js"></script> -</body>
diff --git a/third_party/blink/web_tests/fast/workers/worker-replace-global-constructor-expected.txt b/third_party/blink/web_tests/fast/workers/worker-replace-global-constructor-expected.txt deleted file mode 100644 index 49286a6..0000000 --- a/third_party/blink/web_tests/fast/workers/worker-replace-global-constructor-expected.txt +++ /dev/null
@@ -1,5 +0,0 @@ -Test replacing global constructors in a worker context. - -self.MessageEvent = 'PASS'; MessageEvent;: PASS -DONE -
diff --git a/third_party/blink/web_tests/fast/workers/worker-replace-global-constructor.html b/third_party/blink/web_tests/fast/workers/worker-replace-global-constructor.html deleted file mode 100644 index 7c808d0..0000000 --- a/third_party/blink/web_tests/fast/workers/worker-replace-global-constructor.html +++ /dev/null
@@ -1,7 +0,0 @@ -<body> -<p>Test replacing global constructors in a worker context.</p> -<div id=result></div> -<script src="resources/worker-create-common.js"></script> -<script src="resources/worker-replace-global-constructor.js"> -</script> -</body>
diff --git a/third_party/blink/web_tests/fast/workers/worker-replace-self-expected.txt b/third_party/blink/web_tests/fast/workers/worker-replace-self-expected.txt deleted file mode 100644 index 086a138..0000000 --- a/third_party/blink/web_tests/fast/workers/worker-replace-self-expected.txt +++ /dev/null
@@ -1,6 +0,0 @@ -Test that self is not replaceable. - -self='PASS': PASS -self: [object DedicatedWorkerGlobalScope] -DONE -
diff --git a/third_party/blink/web_tests/fast/workers/worker-replace-self.html b/third_party/blink/web_tests/fast/workers/worker-replace-self.html deleted file mode 100644 index f6cb372..0000000 --- a/third_party/blink/web_tests/fast/workers/worker-replace-self.html +++ /dev/null
@@ -1,6 +0,0 @@ -<body> -<p>Test that self is not replaceable.</p> -<div id=result></div> -<script src="resources/worker-create-common.js"></script> -<script src="resources/worker-replace-self.js"></script> -</body>
diff --git a/third_party/blink/web_tests/flag-specific/enable-blink-features=CompositeAfterPaint/compositing/contents-opaque/body-background-skipped-expected.txt b/third_party/blink/web_tests/flag-specific/enable-blink-features=CompositeAfterPaint/compositing/contents-opaque/body-background-skipped-expected.txt index a497ce1..6a43f9bd 100644 --- a/third_party/blink/web_tests/flag-specific/enable-blink-features=CompositeAfterPaint/compositing/contents-opaque/body-background-skipped-expected.txt +++ b/third_party/blink/web_tests/flag-specific/enable-blink-features=CompositeAfterPaint/compositing/contents-opaque/body-background-skipped-expected.txt
@@ -12,11 +12,6 @@ "contentsOpaque": true, "backgroundColor": "#008000", "transform": 1 - }, - { - "name": "LayoutBlockFlow HTML", - "position": [8, 8], - "bounds": [100, 100] } ], "transforms": [
diff --git a/third_party/blink/web_tests/flag-specific/enable-blink-features=CompositeAfterPaint/compositing/fixed-body-background-positioned-expected.txt b/third_party/blink/web_tests/flag-specific/enable-blink-features=CompositeAfterPaint/compositing/fixed-body-background-positioned-expected.txt index d738ad43..5bea1ac 100644 --- a/third_party/blink/web_tests/flag-specific/enable-blink-features=CompositeAfterPaint/compositing/fixed-body-background-positioned-expected.txt +++ b/third_party/blink/web_tests/flag-specific/enable-blink-features=CompositeAfterPaint/compositing/fixed-body-background-positioned-expected.txt
@@ -14,7 +14,8 @@ { "name": "LayoutBlockFlow HTML", "position": [100, 100], - "bounds": [640, 3500], + "bounds": [640, 440], + "backgroundColor": "#00000080", "transform": 1 } ],
diff --git a/third_party/blink/web_tests/flag-specific/enable-blink-features=CompositeAfterPaint/compositing/iframes/overlapped-iframe-iframe-expected.txt b/third_party/blink/web_tests/flag-specific/enable-blink-features=CompositeAfterPaint/compositing/iframes/become-overlapped-iframe-expected.txt similarity index 76% rename from third_party/blink/web_tests/flag-specific/enable-blink-features=CompositeAfterPaint/compositing/iframes/overlapped-iframe-iframe-expected.txt rename to third_party/blink/web_tests/flag-specific/enable-blink-features=CompositeAfterPaint/compositing/iframes/become-overlapped-iframe-expected.txt index ccd3ad7..500b3ee 100644 --- a/third_party/blink/web_tests/flag-specific/enable-blink-features=CompositeAfterPaint/compositing/iframes/overlapped-iframe-iframe-expected.txt +++ b/third_party/blink/web_tests/flag-specific/enable-blink-features=CompositeAfterPaint/compositing/iframes/become-overlapped-iframe-expected.txt
@@ -7,6 +7,19 @@ "backgroundColor": "#FFFFFF" }, { + "name": "Scrolling background of LayoutView #document", + "bounds": [305, 230], + "contentsOpaque": true, + "backgroundColor": "#C0C0C0", + "transform": 1 + }, + { + "name": "VerticalScrollbar", + "position": [305, 0], + "bounds": [15, 170], + "transform": 1 + }, + { "name": "LayoutBlockFlow DIV id='iframe-content' class='box'", "bounds": [210, 210], "contentsOpaque": true, @@ -14,17 +27,10 @@ "transform": 2 }, { - "name": "Scrolling background of LayoutView #document", - "bounds": [285, 1018], - "contentsOpaque": true, - "backgroundColor": "#C0C0C0", - "transform": 3 - }, - { - "name": "VerticalScrollbar", - "position": [8, 0], - "bounds": [292, 300], - "transform": 3 + "name": "LayoutBlockFlow HTML", + "position": [5, 5], + "bounds": [150, 150], + "backgroundColor": "#00000099" } ], "transforms": [ @@ -34,7 +40,7 @@ [1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], - [2, 2, 0, 1] + [73, 73, 0, 1] ] }, { @@ -46,15 +52,6 @@ [0, 0, 1, 0], [18, 10, 0, 1] ] - }, - { - "id": 3, - "transform": [ - [1, 0, 0, 0], - [0, 1, 0, 0], - [0, 0, 1, 0], - [252, 2, 0, 1] - ] } ] }
diff --git a/third_party/blink/web_tests/flag-specific/enable-blink-features=CompositeAfterPaint/compositing/iframes/composited-parent-iframe-expected.txt b/third_party/blink/web_tests/flag-specific/enable-blink-features=CompositeAfterPaint/compositing/iframes/composited-parent-iframe-expected.txt index 195f98e..f4e0e3a8 100644 --- a/third_party/blink/web_tests/flag-specific/enable-blink-features=CompositeAfterPaint/compositing/iframes/composited-parent-iframe-expected.txt +++ b/third_party/blink/web_tests/flag-specific/enable-blink-features=CompositeAfterPaint/compositing/iframes/composited-parent-iframe-expected.txt
@@ -21,8 +21,8 @@ }, { "name": "VerticalScrollbar", - "position": [8, 0], - "bounds": [292, 150], + "position": [285, 0], + "bounds": [15, 150], "transform": 2 }, {
diff --git a/third_party/blink/web_tests/flag-specific/enable-blink-features=CompositeAfterPaint/compositing/iframes/connect-compositing-iframe-delayed-expected.txt b/third_party/blink/web_tests/flag-specific/enable-blink-features=CompositeAfterPaint/compositing/iframes/connect-compositing-iframe-delayed-expected.txt index 8af92c2..394f409 100644 --- a/third_party/blink/web_tests/flag-specific/enable-blink-features=CompositeAfterPaint/compositing/iframes/connect-compositing-iframe-delayed-expected.txt +++ b/third_party/blink/web_tests/flag-specific/enable-blink-features=CompositeAfterPaint/compositing/iframes/connect-compositing-iframe-delayed-expected.txt
@@ -17,8 +17,8 @@ }, { "name": "VerticalScrollbar", - "position": [8, 0], - "bounds": [292, 150], + "position": [285, 0], + "bounds": [15, 150], "transform": 1 }, {
diff --git a/third_party/blink/web_tests/flag-specific/enable-blink-features=CompositeAfterPaint/compositing/iframes/connect-compositing-iframe-expected.txt b/third_party/blink/web_tests/flag-specific/enable-blink-features=CompositeAfterPaint/compositing/iframes/connect-compositing-iframe-expected.txt index aa66ce7..96cc70b 100644 --- a/third_party/blink/web_tests/flag-specific/enable-blink-features=CompositeAfterPaint/compositing/iframes/connect-compositing-iframe-expected.txt +++ b/third_party/blink/web_tests/flag-specific/enable-blink-features=CompositeAfterPaint/compositing/iframes/connect-compositing-iframe-expected.txt
@@ -21,8 +21,8 @@ }, { "name": "VerticalScrollbar", - "position": [8, 0], - "bounds": [292, 150], + "position": [285, 0], + "bounds": [15, 150], "transform": 2 }, {
diff --git a/third_party/blink/web_tests/flag-specific/enable-blink-features=CompositeAfterPaint/compositing/iframes/connect-compositing-iframe2-expected.txt b/third_party/blink/web_tests/flag-specific/enable-blink-features=CompositeAfterPaint/compositing/iframes/connect-compositing-iframe2-expected.txt index 813ea080..60c074b 100644 --- a/third_party/blink/web_tests/flag-specific/enable-blink-features=CompositeAfterPaint/compositing/iframes/connect-compositing-iframe2-expected.txt +++ b/third_party/blink/web_tests/flag-specific/enable-blink-features=CompositeAfterPaint/compositing/iframes/connect-compositing-iframe2-expected.txt
@@ -21,8 +21,8 @@ }, { "name": "VerticalScrollbar", - "position": [8, 0], - "bounds": [292, 150], + "position": [285, 0], + "bounds": [15, 150], "transform": 2 }, {
diff --git a/third_party/blink/web_tests/flag-specific/enable-blink-features=CompositeAfterPaint/compositing/iframes/connect-compositing-iframe3-expected.txt b/third_party/blink/web_tests/flag-specific/enable-blink-features=CompositeAfterPaint/compositing/iframes/connect-compositing-iframe3-expected.txt index c64b3b6..ab0a280 100644 --- a/third_party/blink/web_tests/flag-specific/enable-blink-features=CompositeAfterPaint/compositing/iframes/connect-compositing-iframe3-expected.txt +++ b/third_party/blink/web_tests/flag-specific/enable-blink-features=CompositeAfterPaint/compositing/iframes/connect-compositing-iframe3-expected.txt
@@ -21,8 +21,8 @@ }, { "name": "VerticalScrollbar", - "position": [8, 0], - "bounds": [292, 150], + "position": [285, 0], + "bounds": [15, 150], "transform": 2 }, {
diff --git a/third_party/blink/web_tests/flag-specific/enable-blink-features=CompositeAfterPaint/compositing/iframes/enter-compositing-iframe-expected.txt b/third_party/blink/web_tests/flag-specific/enable-blink-features=CompositeAfterPaint/compositing/iframes/enter-compositing-iframe-expected.txt index a984cf0..cdcfac1f8 100644 --- a/third_party/blink/web_tests/flag-specific/enable-blink-features=CompositeAfterPaint/compositing/iframes/enter-compositing-iframe-expected.txt +++ b/third_party/blink/web_tests/flag-specific/enable-blink-features=CompositeAfterPaint/compositing/iframes/enter-compositing-iframe-expected.txt
@@ -15,8 +15,8 @@ }, { "name": "VerticalScrollbar", - "position": [8, 0], - "bounds": [292, 150], + "position": [285, 0], + "bounds": [15, 150], "transform": 1 }, {
diff --git a/third_party/blink/web_tests/flag-specific/enable-blink-features=CompositeAfterPaint/compositing/iframes/iframe-resize-expected.txt b/third_party/blink/web_tests/flag-specific/enable-blink-features=CompositeAfterPaint/compositing/iframes/iframe-resize-expected.txt index 523188f..e467ce2 100644 --- a/third_party/blink/web_tests/flag-specific/enable-blink-features=CompositeAfterPaint/compositing/iframes/iframe-resize-expected.txt +++ b/third_party/blink/web_tests/flag-specific/enable-blink-features=CompositeAfterPaint/compositing/iframes/iframe-resize-expected.txt
@@ -15,8 +15,8 @@ }, { "name": "VerticalScrollbar", - "position": [8, 0], - "bounds": [392, 120], + "position": [385, 0], + "bounds": [15, 120], "transform": 1 }, {
diff --git a/third_party/blink/web_tests/flag-specific/enable-blink-features=CompositeAfterPaint/compositing/iframes/iframe-size-from-zero-expected.txt b/third_party/blink/web_tests/flag-specific/enable-blink-features=CompositeAfterPaint/compositing/iframes/iframe-size-from-zero-expected.txt index afa7606..1770ebf 100644 --- a/third_party/blink/web_tests/flag-specific/enable-blink-features=CompositeAfterPaint/compositing/iframes/iframe-size-from-zero-expected.txt +++ b/third_party/blink/web_tests/flag-specific/enable-blink-features=CompositeAfterPaint/compositing/iframes/iframe-size-from-zero-expected.txt
@@ -15,8 +15,8 @@ }, { "name": "VerticalScrollbar", - "position": [8, 0], - "bounds": [292, 150], + "position": [285, 0], + "bounds": [15, 150], "transform": 1 }, {
diff --git a/third_party/blink/web_tests/flag-specific/enable-blink-features=CompositeAfterPaint/compositing/iframes/overlapped-iframe-expected.txt b/third_party/blink/web_tests/flag-specific/enable-blink-features=CompositeAfterPaint/compositing/iframes/overlapped-iframe-expected.txt index afa7606..1770ebf 100644 --- a/third_party/blink/web_tests/flag-specific/enable-blink-features=CompositeAfterPaint/compositing/iframes/overlapped-iframe-expected.txt +++ b/third_party/blink/web_tests/flag-specific/enable-blink-features=CompositeAfterPaint/compositing/iframes/overlapped-iframe-expected.txt
@@ -15,8 +15,8 @@ }, { "name": "VerticalScrollbar", - "position": [8, 0], - "bounds": [292, 150], + "position": [285, 0], + "bounds": [15, 150], "transform": 1 }, {
diff --git a/third_party/blink/web_tests/flag-specific/enable-blink-features=CompositeAfterPaint/compositing/iframes/overlapped-iframe-iframe-expected.txt b/third_party/blink/web_tests/flag-specific/enable-blink-features=CompositeAfterPaint/compositing/iframes/resizer-expected.txt similarity index 71% copy from third_party/blink/web_tests/flag-specific/enable-blink-features=CompositeAfterPaint/compositing/iframes/overlapped-iframe-iframe-expected.txt copy to third_party/blink/web_tests/flag-specific/enable-blink-features=CompositeAfterPaint/compositing/iframes/resizer-expected.txt index ccd3ad7..8095755 100644 --- a/third_party/blink/web_tests/flag-specific/enable-blink-features=CompositeAfterPaint/compositing/iframes/overlapped-iframe-iframe-expected.txt +++ b/third_party/blink/web_tests/flag-specific/enable-blink-features=CompositeAfterPaint/compositing/iframes/resizer-expected.txt
@@ -7,24 +7,35 @@ "backgroundColor": "#FFFFFF" }, { + "name": "LayoutIFrame IFRAME class='container'", + "bounds": [304, 154], + "backgroundColor": "#9A9A9A", + "transform": 1 + }, + { + "name": "Scrolling background of LayoutView #document", + "bounds": [285, 230], + "contentsOpaque": true, + "backgroundColor": "#C0C0C0", + "transform": 2 + }, + { + "name": "VerticalScrollbar", + "position": [285, 0], + "bounds": [15, 150], + "transform": 2 + }, + { "name": "LayoutBlockFlow DIV id='iframe-content' class='box'", "bounds": [210, 210], "contentsOpaque": true, "backgroundColor": "#0000FF", - "transform": 2 - }, - { - "name": "Scrolling background of LayoutView #document", - "bounds": [285, 1018], - "contentsOpaque": true, - "backgroundColor": "#C0C0C0", "transform": 3 }, { - "name": "VerticalScrollbar", - "position": [8, 0], - "bounds": [292, 300], - "transform": 3 + "name": "LayoutIFrame IFRAME class='container'", + "bounds": [304, 154], + "transform": 1 } ], "transforms": [ @@ -34,7 +45,7 @@ [1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], - [2, 2, 0, 1] + [8, 8, 0, 1] ] }, { @@ -44,16 +55,17 @@ [1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], - [18, 10, 0, 1] + [2, 2, 0, 1] ] }, { "id": 3, + "parent": 2, "transform": [ [1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], - [252, 2, 0, 1] + [18, 10, 0, 1] ] } ]
diff --git a/third_party/blink/web_tests/flag-specific/enable-blink-features=CompositeAfterPaint/fast/multicol/composited-layer-expected.txt b/third_party/blink/web_tests/flag-specific/enable-blink-features=CompositeAfterPaint/fast/multicol/composited-layer-expected.txt index c9358a6..c6646772 100644 --- a/third_party/blink/web_tests/flag-specific/enable-blink-features=CompositeAfterPaint/fast/multicol/composited-layer-expected.txt +++ b/third_party/blink/web_tests/flag-specific/enable-blink-features=CompositeAfterPaint/fast/multicol/composited-layer-expected.txt
@@ -5,22 +5,6 @@ "bounds": [800, 600], "contentsOpaque": true, "backgroundColor": "#FFFFFF" -}, -{ -"name": "LayoutBlockFlow DIV id='multicol'", -"bounds": [200, 100], -"transform": 1 -} -], -"transforms": [ -{ -"id": 1, -"transform": [ -[1, 0, 0, 0], -[0, 1, 0, 0], -[0, 0, 1, 0], -[8, 8, 0, 1] -] } ] }
diff --git a/third_party/blink/web_tests/flag-specific/enable-blink-features=CompositeAfterPaint/paint/invalidation/background/viewport-gradient-background-html-resize-overflow-expected.txt b/third_party/blink/web_tests/flag-specific/enable-blink-features=CompositeAfterPaint/paint/invalidation/background/viewport-gradient-background-html-resize-overflow-expected.txt index a333d8f..b612375 100644 --- a/third_party/blink/web_tests/flag-specific/enable-blink-features=CompositeAfterPaint/paint/invalidation/background/viewport-gradient-background-html-resize-overflow-expected.txt +++ b/third_party/blink/web_tests/flag-specific/enable-blink-features=CompositeAfterPaint/paint/invalidation/background/viewport-gradient-background-html-resize-overflow-expected.txt
@@ -14,7 +14,7 @@ { "object": "LayoutBlockFlow HTML", "rect": [0, 0, 800, 200], - "reason": "disappeared" + "reason": "chunk disappeared" } ] }
diff --git a/third_party/blink/web_tests/flag-specific/enable-blink-features=CompositeAfterPaint/paint/invalidation/compositing/background-attachment-local-composited-expected.txt b/third_party/blink/web_tests/flag-specific/enable-blink-features=CompositeAfterPaint/paint/invalidation/compositing/background-attachment-local-composited-expected.txt index c088c5a3..2151cf0 100644 --- a/third_party/blink/web_tests/flag-specific/enable-blink-features=CompositeAfterPaint/paint/invalidation/compositing/background-attachment-local-composited-expected.txt +++ b/third_party/blink/web_tests/flag-specific/enable-blink-features=CompositeAfterPaint/paint/invalidation/compositing/background-attachment-local-composited-expected.txt
@@ -8,11 +8,6 @@ }, { "name": "LayoutBlockFlow DIV id='container'", - "bounds": [400, 400], - "transform": 1 - }, - { - "name": "LayoutBlockFlow DIV id='container'", "bounds": [400, 2000], "backgroundColor": "#0000FF", "paintInvalidations": [
diff --git a/third_party/blink/web_tests/flag-specific/enable-blink-features=CompositeAfterPaint/paint/invalidation/position/fixed-element-repaint-after-compositing-update-expected.txt b/third_party/blink/web_tests/flag-specific/enable-blink-features=CompositeAfterPaint/paint/invalidation/position/fixed-element-repaint-after-compositing-update-expected.txt new file mode 100644 index 0000000..f0c94efb --- /dev/null +++ b/third_party/blink/web_tests/flag-specific/enable-blink-features=CompositeAfterPaint/paint/invalidation/position/fixed-element-repaint-after-compositing-update-expected.txt
@@ -0,0 +1,23 @@ +{ + "layers": [ + { + "name": "Scrolling background of LayoutView #document", + "bounds": [800, 600], + "contentsOpaque": true, + "backgroundColor": "#FFFFFF", + "paintInvalidations": [ + { + "object": "LayoutBlockFlow (positioned) DIV id='moveMe'", + "rect": [150, 150, 100, 100], + "reason": "geometry" + }, + { + "object": "LayoutBlockFlow (positioned) DIV id='moveMe'", + "rect": [8, 88, 100, 100], + "reason": "geometry" + } + ] + } + ] +} +
diff --git a/third_party/blink/web_tests/flag-specific/enable-blink-features=CompositeAfterPaint/paint/invalidation/scroll/destroy-composited-scrollbar-expected.txt b/third_party/blink/web_tests/flag-specific/enable-blink-features=CompositeAfterPaint/paint/invalidation/scroll/destroy-composited-scrollbar-expected.txt index ed385f6..f1ea038 100644 --- a/third_party/blink/web_tests/flag-specific/enable-blink-features=CompositeAfterPaint/paint/invalidation/scroll/destroy-composited-scrollbar-expected.txt +++ b/third_party/blink/web_tests/flag-specific/enable-blink-features=CompositeAfterPaint/paint/invalidation/scroll/destroy-composited-scrollbar-expected.txt
@@ -15,7 +15,7 @@ { "object": "LayoutBlockFlow (positioned) DIV", "rect": [0, 0, 200, 200], - "reason": "appeared" + "reason": "full layer" } ], "transform": 1
diff --git a/third_party/blink/web_tests/flag-specific/enable-blink-features=CompositeAfterPaint/paint/invalidation/scroll/iframe-scroll-repaint-expected.txt b/third_party/blink/web_tests/flag-specific/enable-blink-features=CompositeAfterPaint/paint/invalidation/scroll/iframe-gradient-background-scroll-repaint-expected.txt similarity index 73% rename from third_party/blink/web_tests/flag-specific/enable-blink-features=CompositeAfterPaint/paint/invalidation/scroll/iframe-scroll-repaint-expected.txt rename to third_party/blink/web_tests/flag-specific/enable-blink-features=CompositeAfterPaint/paint/invalidation/scroll/iframe-gradient-background-scroll-repaint-expected.txt index 86c3ded..6a2dd2ebe 100644 --- a/third_party/blink/web_tests/flag-specific/enable-blink-features=CompositeAfterPaint/paint/invalidation/scroll/iframe-scroll-repaint-expected.txt +++ b/third_party/blink/web_tests/flag-specific/enable-blink-features=CompositeAfterPaint/paint/invalidation/scroll/iframe-gradient-background-scroll-repaint-expected.txt
@@ -7,11 +7,6 @@ "backgroundColor": "#FFFFFF", "paintInvalidations": [ { - "object": "LayoutBlockFlow HTML", - "rect": [10, 10, 300, 150], - "reason": "paint property change" - }, - { "object": "Scrolling background of LayoutView #document", "rect": [10, 10, 300, 150], "reason": "paint property change"
diff --git a/third_party/blink/web_tests/flag-specific/enable-blink-features=CompositeAfterPaint/paint/invalidation/scroll/overflow-scroll-local-background-text-color-change-expected.txt b/third_party/blink/web_tests/flag-specific/enable-blink-features=CompositeAfterPaint/paint/invalidation/scroll/overflow-scroll-local-background-text-color-change-expected.txt index bb3c8bd..3d990e2 100644 --- a/third_party/blink/web_tests/flag-specific/enable-blink-features=CompositeAfterPaint/paint/invalidation/scroll/overflow-scroll-local-background-text-color-change-expected.txt +++ b/third_party/blink/web_tests/flag-specific/enable-blink-features=CompositeAfterPaint/paint/invalidation/scroll/overflow-scroll-local-background-text-color-change-expected.txt
@@ -8,11 +8,6 @@ }, { "name": "LayoutBlockFlow DIV id='scroller'", - "bounds": [200, 200], - "transform": 1 - }, - { - "name": "LayoutBlockFlow DIV id='scroller'", "bounds": [185, 552], "backgroundColor": "#0000FF", "paintInvalidations": [
diff --git a/third_party/blink/web_tests/flag-specific/enable-blink-features=CompositeAfterPaint/paint/invalidation/scroll/repaint-during-scroll-with-zoom-expected.txt b/third_party/blink/web_tests/flag-specific/enable-blink-features=CompositeAfterPaint/paint/invalidation/scroll/repaint-during-scroll-with-zoom-expected.txt new file mode 100644 index 0000000..b1fee74 --- /dev/null +++ b/third_party/blink/web_tests/flag-specific/enable-blink-features=CompositeAfterPaint/paint/invalidation/scroll/repaint-during-scroll-with-zoom-expected.txt
@@ -0,0 +1,61 @@ +{ + "layers": [ + { + "name": "Scrolling background of LayoutView #document", + "bounds": [800, 600], + "contentsOpaque": true, + "backgroundColor": "#C0C0C0" + }, + { + "name": "Scrolling background of LayoutView #document", + "bounds": [2008, 2016], + "contentsOpaque": true, + "backgroundColor": "#FFFFFF", + "transform": 2 + }, + { + "name": "HorizontalScrollbar", + "bounds": [250, 250], + "paintInvalidations": [ + { + "object": "HorizontalScrollbar", + "rect": [0, 235, 235, 15], + "reason": "scroll control" + }, + { + "object": "LayoutBlockFlow HTML", + "rect": [0, 0, 55, 17], + "reason": "paint property change" + }, + { + "object": "VerticalScrollbar", + "rect": [235, 0, 15, 235], + "reason": "scroll control" + } + ], + "transform": 1 + } + ], + "transforms": [ + { + "id": 1, + "transform": [ + [1, 0, 0, 0], + [0, 1, 0, 0], + [0, 0, 1, 0], + [3, 65, 0, 1] + ] + }, + { + "id": 2, + "parent": 1, + "transform": [ + [1, 0, 0, 0], + [0, 1, 0, 0], + [0, 0, 1, 0], + [-10, -10, 0, 1] + ] + } + ] +} +
diff --git a/third_party/blink/web_tests/flag-specific/enable-blink-features=CompositeAfterPaint/paint/invalidation/selection/selection-within-composited-scroller-expected.txt b/third_party/blink/web_tests/flag-specific/enable-blink-features=CompositeAfterPaint/paint/invalidation/selection/selection-within-composited-scroller-expected.txt index 29601151..050d5c91 100644 --- a/third_party/blink/web_tests/flag-specific/enable-blink-features=CompositeAfterPaint/paint/invalidation/selection/selection-within-composited-scroller-expected.txt +++ b/third_party/blink/web_tests/flag-specific/enable-blink-features=CompositeAfterPaint/paint/invalidation/selection/selection-within-composited-scroller-expected.txt
@@ -8,11 +8,6 @@ }, { "name": "LayoutBlockFlow DIV id='scroller'", - "bounds": [200, 200], - "transform": 1 - }, - { - "name": "LayoutBlockFlow DIV id='scroller'", "bounds": [200, 1620], "backgroundColor": "#D3D3D3", "transform": 2
diff --git a/third_party/blink/web_tests/http/tests/devtools/elements/elements-panel-styles-expected.txt b/third_party/blink/web_tests/http/tests/devtools/elements/elements-panel-styles-expected.txt index f570cb1..470ddee 100644 --- a/third_party/blink/web_tests/http/tests/devtools/elements/elements-panel-styles-expected.txt +++ b/third_party/blink/web_tests/http/tests/devtools/elements/elements-panel-styles-expected.txt
@@ -60,24 +60,24 @@ -webkit-font-smoothing: subpixel-antialiased; [expanded] -#container .foo { (elements-panel-styles.css:17 -> elements-panel-styles.css:17:18) +#container .foo { (elements-pa…yles.css:17 -> elements-panel-styles.css:17:18) font-style: italic !important; [expanded] -body .foo { (elements-panel-styles.css:6 -> elements-panel-styles.css:6:12) +body .foo { (elements-pa…tyles.css:6 -> elements-panel-styles.css:6:12) /-- overloaded --/ text-indent: 10px; [expanded] -.foo { (elements-panel-styles.css:53 -> elements-panel-styles.css:53:7) +.foo { (elements-pa…yles.css:53 -> elements-panel-styles.css:53:7) [expanded] -.foo, .foo::before { (elements-panel-styles.css:34 -> elements-panel-styles.css:34:21) +.foo, .foo::before { (elements-pa…yles.css:34 -> elements-panel-styles.css:34:21) content: "[before Foo]"; color: blue; display: block !important; [expanded] -.foo { (elements-panel-styles.css:21 -> elements-panel-styles.css:21:7) +.foo { (elements-pa…yles.css:21 -> elements-panel-styles.css:21:7) /-- overloaded --/ color: black; margin-left: 1px; margin: 10px 0 2px; @@ -111,20 +111,20 @@ ======== Inherited from div#container ======== [expanded] -#container { (elements-panel-styles.css:10 -> elements-panel-styles.css:10:13) +#container { (elements-pa…yles.css:10 -> elements-panel-styles.css:10:13) font-family: serif; font-size: 14px; /-- overloaded --/ color: red; ======== Inherited from body ======== [expanded] -body { (elements-panel-styles.css:1 -> elements-panel-styles.css:1:7) +body { (elements-pa…tyles.css:1 -> elements-panel-styles.css:1:7) /-- overloaded --/ font-size: 12px; /-- overloaded --/ text-indent: 20px !important; ======== Inherited from html ======== [expanded] -html { (elements-panel-styles.css:61 -> elements-panel-styles.css:61:7) +html { (elements-pa…yles.css:61 -> elements-panel-styles.css:61:7) /-- overloaded --/ color: magenta !important; [expanded] @@ -133,26 +133,26 @@ ======== Pseudo ::before element ======== [expanded] -.foo::before { (elements-panel-styles.css:57 -> elements-panel-styles.css:57:15) +.foo::before { (elements-pa…yles.css:57 -> elements-panel-styles.css:57:15) [expanded] -.foo::before { (elements-panel-styles.css:40 -> elements-panel-styles.css:40:15) +.foo::before { (elements-pa…yles.css:40 -> elements-panel-styles.css:40:15) color: red; [expanded] -.foo, .foo::before { (elements-panel-styles.css:34 -> elements-panel-styles.css:34:21) +.foo, .foo::before { (elements-pa…yles.css:34 -> elements-panel-styles.css:34:21) content: "[before Foo]"; /-- overloaded --/ color: blue; display: block !important; ======== Pseudo ::after element ======== [expanded] -.foo::after { (elements-panel-styles.css:48 -> elements-panel-styles.css:48:14) +.foo::after { (elements-pa…yles.css:48 -> elements-panel-styles.css:48:14) font-family: courier; content: "[after Foo 2]"; [expanded] -.foo::after { (elements-panel-styles.css:44 -> elements-panel-styles.css:44:14) +.foo::after { (elements-pa…yles.css:44 -> elements-panel-styles.css:44:14) /-- overloaded --/ content: "[after Foo]"; color: green;
diff --git a/third_party/blink/web_tests/http/tests/devtools/elements/navigate-styles-sidebar-with-arrow-keys-expected.txt b/third_party/blink/web_tests/http/tests/devtools/elements/navigate-styles-sidebar-with-arrow-keys-expected.txt index 5da8cfb..5c165288 100644 --- a/third_party/blink/web_tests/http/tests/devtools/elements/navigate-styles-sidebar-with-arrow-keys-expected.txt +++ b/third_party/blink/web_tests/http/tests/devtools/elements/navigate-styles-sidebar-with-arrow-keys-expected.txt
@@ -9,19 +9,19 @@ Navigating with arrow keys Editing: false -<style>…</style>div#foo {} +<style>div#foo {} Editing: false -<style>…</style>#foo {} +<style>#foo {} Editing: false -<style>…</style>div {} +<style>div {} Editing: false user agent stylesheetdiv {} Editing: false -<style>…</style>div {} +<style>div {} Typing should start editing Editing: true @@ -29,7 +29,7 @@ Pressing escape again should restore focus Editing: false -<style>…</style>div {} +<style>div {} Pressing enter should start editing selector Editing: true
diff --git a/third_party/blink/web_tests/http/tests/devtools/elements/styles-1/commit-selector-expected.txt b/third_party/blink/web_tests/http/tests/devtools/elements/styles-1/commit-selector-expected.txt index a7c1c88..6b12233b 100644 --- a/third_party/blink/web_tests/http/tests/devtools/elements/styles-1/commit-selector-expected.txt +++ b/third_party/blink/web_tests/http/tests/devtools/elements/styles-1/commit-selector-expected.txt
@@ -6,7 +6,7 @@ color: red; [expanded] -#inspected { (<style>…</style>) +#inspected { (<style>) /-- overloaded --/ color: green; [expanded] @@ -24,7 +24,7 @@ color: red; [expanded] -hr, #inspected { (<style>…</style>) +hr, #inspected { (<style>) /-- overloaded --/ color: green; [expanded] @@ -42,7 +42,7 @@ color: red; [expanded] [no-affect] -#inspectedChanged { (<style>…</style>) +#inspectedChanged { (<style>) color: green; [expanded]
diff --git a/third_party/blink/web_tests/http/tests/devtools/elements/styles-1/cssom-media-insert-crash-expected.txt b/third_party/blink/web_tests/http/tests/devtools/elements/styles-1/cssom-media-insert-crash-expected.txt index 101d08a..e9d94629a 100644 --- a/third_party/blink/web_tests/http/tests/devtools/elements/styles-1/cssom-media-insert-crash-expected.txt +++ b/third_party/blink/web_tests/http/tests/devtools/elements/styles-1/cssom-media-insert-crash-expected.txt
@@ -4,12 +4,12 @@ element.style { () [expanded] -#box { (<style>…</style>) +#box { (<style>) color: white; background: red; [expanded] -div { (<style>…</style>) +div { (<style>) border: 1px solid black; /-- overloaded --/ background-color: white; padding: 20px;
diff --git a/third_party/blink/web_tests/http/tests/devtools/elements/styles-1/disable-property-workingcopy-update-expected.txt b/third_party/blink/web_tests/http/tests/devtools/elements/styles-1/disable-property-workingcopy-update-expected.txt index bbcc7de8..f0ba032 100644 --- a/third_party/blink/web_tests/http/tests/devtools/elements/styles-1/disable-property-workingcopy-update-expected.txt +++ b/third_party/blink/web_tests/http/tests/devtools/elements/styles-1/disable-property-workingcopy-update-expected.txt
@@ -24,7 +24,7 @@ element.style { () [expanded] -#inspected { (disable-propert…y-update.css:1 -> disable-property-workingcopy-update.css:1:13) +#inspected { (disable-pro…pdate.css:1 -> disable-property-workingcopy-update.css:1:13) /-- overloaded --/ /-- disabled --/ /* font-weight: bold; */ [expanded] @@ -50,7 +50,7 @@ element.style { () [expanded] -#inspected { (disable-propert…y-update.css:1 -> disable-property-workingcopy-update.css:1:13) +#inspected { (disable-pro…pdate.css:1 -> disable-property-workingcopy-update.css:1:13) font-weight: bold; [expanded]
diff --git a/third_party/blink/web_tests/http/tests/devtools/elements/styles-1/dynamic-style-tag-expected.txt b/third_party/blink/web_tests/http/tests/devtools/elements/styles-1/dynamic-style-tag-expected.txt index e7dc626..8381852 100644 --- a/third_party/blink/web_tests/http/tests/devtools/elements/styles-1/dynamic-style-tag-expected.txt +++ b/third_party/blink/web_tests/http/tests/devtools/elements/styles-1/dynamic-style-tag-expected.txt
@@ -58,27 +58,27 @@ color: red; [expanded] -.inline-style-created-by-script-with-source-url { (inlineStyleCrea…ByScript.css:1 -> inlineStyleCreatedByScript.css:1:50) +.inline-style-created-by-script-with-source-url { (inlineStyle…cript.css:1 -> inlineStyleCreatedByScript.css:1:50) /-- overloaded --/ color: grey; [expanded] -.inline-style-created-by-script { (<style>…</style>) +.inline-style-created-by-script { (<style>) /-- overloaded --/ color: orange; [expanded] -.inline-style-added-by-document-write-with-source-url { (inlineStyleAdde…entWrite.css:2 -> inlineStyleAddedByDocumentWrite.css:2:56) +.inline-style-added-by-document-write-with-source-url { (inlineStyle…Write.css:2 -> inlineStyleAddedByDocumentWrite.css:2:56) /-- overloaded --/ color: yellow; [expanded] -.inline-style-added-by-parser-in-document-write { (<style>…</style>) +.inline-style-added-by-parser-in-document-write { (<style>) /-- overloaded --/ color: blue; [expanded] -.inline-style-added-by-parser-with-source-url { (inlineStyleAddedByParser.css:2 -> inlineStyleAddedByParser.css:2:48) +.inline-style-added-by-parser-with-source-url { (inlineStyle…arser.css:2 -> inlineStyleAddedByParser.css:2:48) /-- overloaded --/ color: green; [expanded] -.inline-style-added-by-parser { (dynamic-style-tag.html:3 -> dynamic-style-tag.html:3:45) +.inline-style-added-by-parser { (dynamic-sty…-tag.html:3 -> dynamic-style-tag.html:3:45) /-- overloaded --/ color: red; [expanded]
diff --git a/third_party/blink/web_tests/http/tests/devtools/elements/styles-1/edit-media-text-expected.txt b/third_party/blink/web_tests/http/tests/devtools/elements/styles-1/edit-media-text-expected.txt index 9f66f5c..25b8e3b3 100644 --- a/third_party/blink/web_tests/http/tests/devtools/elements/styles-1/edit-media-text-expected.txt +++ b/third_party/blink/web_tests/http/tests/devtools/elements/styles-1/edit-media-text-expected.txt
@@ -7,12 +7,12 @@ [expanded] @media screen and (max-device-width: 100000px) -#inspected { (<style>…</style>) +#inspected { (<style>) /-- overloaded --/ color: blue; [expanded] @media screen and (max-device-width: 100000px) -#inspected { (<style>…</style>) +#inspected { (<style>) /-- overloaded --/ color: green; [expanded] @@ -31,12 +31,12 @@ [expanded] @media screen and (max-device-width: 99999px) -#inspected { (<style>…</style>) +#inspected { (<style>) /-- overloaded --/ color: blue; [expanded] @media screen and (max-device-width: 99999px) -#inspected { (<style>…</style>) +#inspected { (<style>) /-- overloaded --/ color: green; [expanded] @@ -54,11 +54,11 @@ color: red; [expanded] -#inspected { (<style>…</style>) +#inspected { (<style>) /-- overloaded --/ color: blue; [expanded] -#inspected { (<style>…</style>) +#inspected { (<style>) /-- overloaded --/ color: green; [expanded]
diff --git a/third_party/blink/web_tests/http/tests/devtools/elements/styles-1/empty-background-url-expected.txt b/third_party/blink/web_tests/http/tests/devtools/elements/styles-1/empty-background-url-expected.txt index e1db018..ea64886 100644 --- a/third_party/blink/web_tests/http/tests/devtools/elements/styles-1/empty-background-url-expected.txt +++ b/third_party/blink/web_tests/http/tests/devtools/elements/styles-1/empty-background-url-expected.txt
@@ -4,7 +4,7 @@ element.style { () [expanded] -#inspected { (<style>…</style>) +#inspected { (<style>) background-image: url(); [expanded]
diff --git a/third_party/blink/web_tests/http/tests/devtools/elements/styles-2/add-import-rule-expected.txt b/third_party/blink/web_tests/http/tests/devtools/elements/styles-2/add-import-rule-expected.txt index 67464ce..a20d013 100644 --- a/third_party/blink/web_tests/http/tests/devtools/elements/styles-2/add-import-rule-expected.txt +++ b/third_party/blink/web_tests/http/tests/devtools/elements/styles-2/add-import-rule-expected.txt
@@ -7,7 +7,7 @@ element.style { () [expanded] -span { (<style>…</style>) +span { (<style>) color: red; ======== Inherited from html ======== @@ -22,7 +22,7 @@ element.style { () [expanded] -span { (data:text/css,s…color:green}:1 -> data:text/css,span{color:green}:1:6) +span { (data:text/c…or:green}:1 -> data:text/css,span{color:green}:1:6) color: green; ======== Inherited from html ========
diff --git a/third_party/blink/web_tests/http/tests/devtools/elements/styles-2/cssom-shorthand-important-expected.txt b/third_party/blink/web_tests/http/tests/devtools/elements/styles-2/cssom-shorthand-important-expected.txt index 323d147..c6b9eb6 100644 --- a/third_party/blink/web_tests/http/tests/devtools/elements/styles-2/cssom-shorthand-important-expected.txt +++ b/third_party/blink/web_tests/http/tests/devtools/elements/styles-2/cssom-shorthand-important-expected.txt
@@ -4,7 +4,7 @@ element.style { () [expanded] -#inspected { (<style>…</style>) +#inspected { (<style>) margin-top: 10px; padding: 10px 50px !important; padding-top: 10px !important;
diff --git a/third_party/blink/web_tests/http/tests/devtools/elements/styles-2/force-pseudo-state-expected.txt b/third_party/blink/web_tests/http/tests/devtools/elements/styles-2/force-pseudo-state-expected.txt index 951be4a..9477dd0 100644 --- a/third_party/blink/web_tests/http/tests/devtools/elements/styles-2/force-pseudo-state-expected.txt +++ b/third_party/blink/web_tests/http/tests/devtools/elements/styles-2/force-pseudo-state-expected.txt
@@ -6,11 +6,11 @@ element.style { () [expanded] -div:active, a:active { (<style>…</style>) +div:active, a:active { (<style>) font-weight: bold; [expanded] -div:hover, a:hover { (<style>…</style>) +div:hover, a:hover { (<style>) color: red; [expanded] @@ -39,11 +39,11 @@ element.style { () [expanded] -div:active, a:active { (<style>…</style>) +div:active, a:active { (<style>) font-weight: bold; [expanded] -div:focus, a:focus { (<style>…</style>) +div:focus, a:focus { (<style>) border: 1px solid green; border-top-color: green; border-top-style: solid;
diff --git a/third_party/blink/web_tests/http/tests/devtools/elements/styles-2/inactive-properties-expected.txt b/third_party/blink/web_tests/http/tests/devtools/elements/styles-2/inactive-properties-expected.txt index ba85be0..03f57cb4 100644 --- a/third_party/blink/web_tests/http/tests/devtools/elements/styles-2/inactive-properties-expected.txt +++ b/third_party/blink/web_tests/http/tests/devtools/elements/styles-2/inactive-properties-expected.txt
@@ -5,13 +5,13 @@ display: block; block - div user agent stylesheet text-align: right; - right - #inspected <style>…</style> + right - #inspected <style> OVERLOADED -webkit-left - element.style [expanded] element.style { () [expanded] -#inspected { (<style>…</style>) +#inspected { (<style>) /-- overloaded --/ text-align: left; /-- overloaded --/ text-align: bar; text-align: right;
diff --git a/third_party/blink/web_tests/http/tests/devtools/elements/styles-2/inherited-mixed-case-properties-expected.txt b/third_party/blink/web_tests/http/tests/devtools/elements/styles-2/inherited-mixed-case-properties-expected.txt index b6989cc..139b8fb 100644 --- a/third_party/blink/web_tests/http/tests/devtools/elements/styles-2/inherited-mixed-case-properties-expected.txt +++ b/third_party/blink/web_tests/http/tests/devtools/elements/styles-2/inherited-mixed-case-properties-expected.txt
@@ -18,7 +18,7 @@ CoLoR: blAck; [expanded] -#container { (<style>…</style>) +#container { (<style>) -webkit-FONT-smoothing: antialiased; ======== Inherited from html ========
diff --git a/third_party/blink/web_tests/http/tests/devtools/elements/styles-2/inject-stylesheet-expected.txt b/third_party/blink/web_tests/http/tests/devtools/elements/styles-2/inject-stylesheet-expected.txt index 89480a46..342d16d9 100644 --- a/third_party/blink/web_tests/http/tests/devtools/elements/styles-2/inject-stylesheet-expected.txt +++ b/third_party/blink/web_tests/http/tests/devtools/elements/styles-2/inject-stylesheet-expected.txt
@@ -2,25 +2,25 @@ Main frame style: background-attachment: scroll; - initial - #main <style>…</style> + initial - #main <style> background-clip: border-box; - initial - #main <style>…</style> + initial - #main <style> background-color: rgb(0, 0, 255); - blue - #main <style>…</style> + blue - #main <style> background-image: none; - initial - #main <style>…</style> + initial - #main <style> background-origin: padding-box; - initial - #main <style>…</style> + initial - #main <style> background-position-x: 0%; - initial - #main <style>…</style> + initial - #main <style> background-position-y: 0%; - initial - #main <style>…</style> + initial - #main <style> background-repeat-x: ; - initial - #main <style>…</style> + initial - #main <style> background-repeat-y: ; - initial - #main <style>…</style> + initial - #main <style> background-size: auto; - initial - #main <style>…</style> + initial - #main <style> border-bottom-style: solid; solid - #main injected stylesheet border-left-style: solid; @@ -40,7 +40,7 @@ element.style { () [expanded] -#main { (<style>…</style>) +#main { (<style>) background: blue; background-image: initial; background-position-x: initial; @@ -133,7 +133,7 @@ background-color: red; [expanded] -body { (inject-styleshe…me-data.html:4 -> inject-stylesheet-iframe-data.html:4:9) +body { (inject-styl…data.html:4 -> inject-stylesheet-iframe-data.html:4:9) /-- overloaded --/ background: green; /-- overloaded --/ background-image: initial; /-- overloaded --/ background-position-x: initial;
diff --git a/third_party/blink/web_tests/http/tests/devtools/elements/styles-2/keyframes-rules-expected.txt b/third_party/blink/web_tests/http/tests/devtools/elements/styles-2/keyframes-rules-expected.txt index 78afa72..713a74e 100644 --- a/third_party/blink/web_tests/http/tests/devtools/elements/styles-2/keyframes-rules-expected.txt +++ b/third_party/blink/web_tests/http/tests/devtools/elements/styles-2/keyframes-rules-expected.txt
@@ -9,7 +9,7 @@ background-color: white; [expanded] -* { (<style>…</style>) +* { (<style>) /-- overloaded --/ background-color: papayawhip; [expanded]
diff --git a/third_party/blink/web_tests/http/tests/devtools/elements/styles-2/lazy-computed-style-expected.txt b/third_party/blink/web_tests/http/tests/devtools/elements/styles-2/lazy-computed-style-expected.txt index 91f8def..d9605b6 100644 --- a/third_party/blink/web_tests/http/tests/devtools/elements/styles-2/lazy-computed-style-expected.txt +++ b/third_party/blink/web_tests/http/tests/devtools/elements/styles-2/lazy-computed-style-expected.txt
@@ -5,7 +5,7 @@ element.style { () [expanded] -#inspected { (<style>…</style>) +#inspected { (<style>) background: gray; background-image: initial; background-position-x: initial; @@ -19,12 +19,12 @@ background-color: gray; [expanded] -#inspected { (<style>…</style>) +#inspected { (<style>) /-- overloaded --/ background-color: black; font-family: Courier; [expanded] -#inspected { (<style>…</style>) +#inspected { (<style>) /-- overloaded --/ background-color: green; /-- overloaded --/ font-family: Times; @@ -39,39 +39,39 @@ ==== All styles (computed should be there) ==== background-attachment: scroll; - initial - #inspected <style>…</style> + initial - #inspected <style> background-clip: border-box; - initial - #inspected <style>…</style> + initial - #inspected <style> background-color: rgb(128, 128, 128); - gray - #inspected <style>…</style> - OVERLOADED black - #inspected <style>…</style> - OVERLOADED green - #inspected <style>…</style> + gray - #inspected <style> + OVERLOADED black - #inspected <style> + OVERLOADED green - #inspected <style> background-image: none; - initial - #inspected <style>…</style> + initial - #inspected <style> background-origin: padding-box; - initial - #inspected <style>…</style> + initial - #inspected <style> background-position-x: 0%; - initial - #inspected <style>…</style> + initial - #inspected <style> background-position-y: 0%; - initial - #inspected <style>…</style> + initial - #inspected <style> background-repeat-x: ; - initial - #inspected <style>…</style> + initial - #inspected <style> background-repeat-y: ; - initial - #inspected <style>…</style> + initial - #inspected <style> background-size: auto; - initial - #inspected <style>…</style> + initial - #inspected <style> color: rgb(0, 0, 0); -internal-root-color - html user agent stylesheet display: block; block - div user agent stylesheet font-family: Courier; - Courier - #inspected <style>…</style> - OVERLOADED Times - #inspected <style>…</style> + Courier - #inspected <style> + OVERLOADED Times - #inspected <style> [expanded] element.style { () [expanded] -#inspected { (<style>…</style>) +#inspected { (<style>) background: gray; background-image: initial; background-position-x: initial; @@ -85,12 +85,12 @@ background-color: gray; [expanded] -#inspected { (<style>…</style>) +#inspected { (<style>) /-- overloaded --/ background-color: black; font-family: Courier; [expanded] -#inspected { (<style>…</style>) +#inspected { (<style>) /-- overloaded --/ background-color: green; /-- overloaded --/ font-family: Times;
diff --git a/third_party/blink/web_tests/http/tests/devtools/elements/styles-2/media-emulation-expected.txt b/third_party/blink/web_tests/http/tests/devtools/elements/styles-2/media-emulation-expected.txt index af5b22c..2e4ce87 100644 --- a/third_party/blink/web_tests/http/tests/devtools/elements/styles-2/media-emulation-expected.txt +++ b/third_party/blink/web_tests/http/tests/devtools/elements/styles-2/media-emulation-expected.txt
@@ -5,7 +5,7 @@ element.style { () [expanded] -#main { (<style>…</style>) +#main { (<style>) color: red; [expanded] @@ -23,11 +23,11 @@ [expanded] @media print -#main { (<style>…</style>) +#main { (<style>) color: black; [expanded] -#main { (<style>…</style>) +#main { (<style>) /-- overloaded --/ color: red; [expanded] @@ -44,11 +44,11 @@ element.style { () [expanded] -#main { (<style>…</style>) +#main { (<style>) color: green; [expanded] -#main { (<style>…</style>) +#main { (<style>) /-- overloaded --/ color: red; [expanded] @@ -65,7 +65,7 @@ element.style { () [expanded] -#main { (<style>…</style>) +#main { (<style>) color: red; [expanded]
diff --git a/third_party/blink/web_tests/http/tests/devtools/elements/styles-2/media-queries-expected.txt b/third_party/blink/web_tests/http/tests/devtools/elements/styles-2/media-queries-expected.txt index ea3139e..2375d0a 100644 --- a/third_party/blink/web_tests/http/tests/devtools/elements/styles-2/media-queries-expected.txt +++ b/third_party/blink/web_tests/http/tests/devtools/elements/styles-2/media-queries-expected.txt
@@ -13,7 +13,7 @@ border: 1px solid black; [expanded] -#main { (<style>…</style>) +#main { (<style>) background: blue; [expanded]
diff --git a/third_party/blink/web_tests/http/tests/devtools/elements/styles-2/media-using-same-url-expected.txt b/third_party/blink/web_tests/http/tests/devtools/elements/styles-2/media-using-same-url-expected.txt index f3f259d..ece61003 100644 --- a/third_party/blink/web_tests/http/tests/devtools/elements/styles-2/media-using-same-url-expected.txt +++ b/third_party/blink/web_tests/http/tests/devtools/elements/styles-2/media-using-same-url-expected.txt
@@ -5,11 +5,11 @@ element.style { () [expanded] -#main { (<style>…</style>) +#main { (<style>) color: white; [expanded] -#main { (<style>…</style>) +#main { (<style>) background: blue; [expanded]
diff --git a/third_party/blink/web_tests/http/tests/devtools/elements/styles-2/parse-comments-expected.txt b/third_party/blink/web_tests/http/tests/devtools/elements/styles-2/parse-comments-expected.txt index 4d3b33f..0250767 100644 --- a/third_party/blink/web_tests/http/tests/devtools/elements/styles-2/parse-comments-expected.txt +++ b/third_party/blink/web_tests/http/tests/devtools/elements/styles-2/parse-comments-expected.txt
@@ -5,13 +5,13 @@ element.style { () [expanded] -#main { (<style>…</style>) +#main { (<style>) /-- overloaded --/ /-- disabled --/ /* color: red; */ color/* color: red */:/* color: red */ green/* color: red */; /-- overloaded --/ /-- disabled --/ /* color: red; */ [expanded] -#main { (<style>…</style>) +#main { (<style>) /-- overloaded --/ /-- disabled --/ /* color: red; */ background /* color: red */ :/* color: red */blue/* color: red */; /-- overloaded --/ /-- disabled --/ /* color: red; */
diff --git a/third_party/blink/web_tests/http/tests/devtools/elements/styles-2/parse-utf8-bom-expected.txt b/third_party/blink/web_tests/http/tests/devtools/elements/styles-2/parse-utf8-bom-expected.txt index d7eec62..39465a95 100644 --- a/third_party/blink/web_tests/http/tests/devtools/elements/styles-2/parse-utf8-bom-expected.txt +++ b/third_party/blink/web_tests/http/tests/devtools/elements/styles-2/parse-utf8-bom-expected.txt
@@ -4,7 +4,7 @@ element.style { () [expanded] -h1 { (parse-utf8-bom-main.css:3 -> parse-utf8-bom-main.css:3:5) +h1 { (parse-utf8-…-main.css:3 -> parse-utf8-bom-main.css:3:5) color: red; [expanded]
diff --git a/third_party/blink/web_tests/http/tests/devtools/elements/styles-2/perform-undo-perform-of-mergable-action-expected.txt b/third_party/blink/web_tests/http/tests/devtools/elements/styles-2/perform-undo-perform-of-mergable-action-expected.txt index a734d1c..00688b6 100644 --- a/third_party/blink/web_tests/http/tests/devtools/elements/styles-2/perform-undo-perform-of-mergable-action-expected.txt +++ b/third_party/blink/web_tests/http/tests/devtools/elements/styles-2/perform-undo-perform-of-mergable-action-expected.txt
@@ -5,7 +5,7 @@ element.style { () [expanded] -.container { (<style>…</style>) +.container { (<style>) font-weight: bold; [expanded] @@ -22,7 +22,7 @@ element.style { () [expanded] -.container { (<style>…</style>) +.container { (<style>) font-weight: normal; [expanded] @@ -39,7 +39,7 @@ element.style { () [expanded] -.container { (<style>…</style>) +.container { (<style>) font-weight: bold; [expanded] @@ -56,7 +56,7 @@ element.style { () [expanded] -.container { (<style>…</style>) +.container { (<style>) font-weight: normal; [expanded]
diff --git a/third_party/blink/web_tests/http/tests/devtools/elements/styles-2/pseudo-elements-expected.txt b/third_party/blink/web_tests/http/tests/devtools/elements/styles-2/pseudo-elements-expected.txt index 7598177..75e211d 100644 --- a/third_party/blink/web_tests/http/tests/devtools/elements/styles-2/pseudo-elements-expected.txt +++ b/third_party/blink/web_tests/http/tests/devtools/elements/styles-2/pseudo-elements-expected.txt
@@ -30,24 +30,24 @@ ======== Pseudo ::before element ======== [expanded] -[$#inspected:before, $].some-other-selector { (<style>…</style>) +[$#inspected:before, $].some-other-selector { (<style>) content: "BEFORE"; ======== Pseudo ::after element ======== [expanded] -[$#inspected:after$] { (<style>…</style>) +[$#inspected:after$] { (<style>) content: "AFTER"; Running: dumpBeforeStyles [expanded] -[$#inspected:before, $].some-other-selector { (<style>…</style>) +[$#inspected:before, $].some-other-selector { (<style>) content: "BEFORE"; Running: dumpAfterStyles [expanded] -[$#inspected:after$] { (<style>…</style>) +[$#inspected:after$] { (<style>) content: "AFTER";
diff --git a/third_party/blink/web_tests/http/tests/devtools/elements/styles-2/region-style-crash-expected.txt b/third_party/blink/web_tests/http/tests/devtools/elements/styles-2/region-style-crash-expected.txt index 58a52cb..38afa8d 100644 --- a/third_party/blink/web_tests/http/tests/devtools/elements/styles-2/region-style-crash-expected.txt +++ b/third_party/blink/web_tests/http/tests/devtools/elements/styles-2/region-style-crash-expected.txt
@@ -1,7 +1,7 @@ Tests that webkit css region styling can be parsed correctly. Test passes if it doesn't crash. color: rgb(255, 0, 0); - #ff0000 - #p1 <style>…</style> + #ff0000 - #p1 <style> OVERLOADED -internal-root-color - html user agent stylesheet display: block; block - p user agent stylesheet @@ -17,7 +17,7 @@ element.style { () [expanded] -#p1 { (<style>…</style>) +#p1 { (<style>) color: #ff0000; [expanded]
diff --git a/third_party/blink/web_tests/http/tests/devtools/elements/styles-3/computed-properties-retain-expanded-expected.txt b/third_party/blink/web_tests/http/tests/devtools/elements/styles-3/computed-properties-retain-expanded-expected.txt index f62da1e..77e1487 100644 --- a/third_party/blink/web_tests/http/tests/devtools/elements/styles-3/computed-properties-retain-expanded-expected.txt +++ b/third_party/blink/web_tests/http/tests/devtools/elements/styles-3/computed-properties-retain-expanded-expected.txt
@@ -4,14 +4,14 @@ #inspected computed styles: color: rgb(0, 0, 255); display: flex; - flex - #inspected <style>…</style> - OVERLOADED block - div <style>…</style> + flex - #inspected <style> + OVERLOADED block - div <style> OVERLOADED block - div user agent stylesheet #other computed styles: color: rgb(0, 0, 0); display: inline; - inline - #other <style>…</style> - OVERLOADED block - div <style>…</style> + inline - #other <style> + OVERLOADED block - div <style> OVERLOADED block - div user agent stylesheet
diff --git a/third_party/blink/web_tests/http/tests/devtools/elements/styles-3/selector-list-expected.txt b/third_party/blink/web_tests/http/tests/devtools/elements/styles-3/selector-list-expected.txt index bc4ab296..eecd1644 100644 --- a/third_party/blink/web_tests/http/tests/devtools/elements/styles-3/selector-list-expected.txt +++ b/third_party/blink/web_tests/http/tests/devtools/elements/styles-3/selector-list-expected.txt
@@ -4,17 +4,17 @@ element.style { () [expanded] -FOO bAr, #inspected, MOO>BAR, htML div, Foo~Moo, MOO { (<style>…</style>) +FOO bAr, #inspected, MOO>BAR, htML div, Foo~Moo, MOO { (<style>) color: green; [expanded] -#inspected { (<style>…</style>) +#inspected { (<style>) [expanded] -#InSpEcTeD { (<style>…</style>) +#InSpEcTeD { (<style>) [expanded] -#inspected { (<style>…</style>) +#inspected { (<style>) [expanded] div { (user agent stylesheet)
diff --git a/third_party/blink/web_tests/http/tests/devtools/elements/styles-3/shadow-dom-rules-expected.txt b/third_party/blink/web_tests/http/tests/devtools/elements/styles-3/shadow-dom-rules-expected.txt index bdc4af8..614c1b5c 100644 --- a/third_party/blink/web_tests/http/tests/devtools/elements/styles-3/shadow-dom-rules-expected.txt +++ b/third_party/blink/web_tests/http/tests/devtools/elements/styles-3/shadow-dom-rules-expected.txt
@@ -8,7 +8,7 @@ element.style { () [expanded] -.red { (<style>…</style>) +.red { (<style>) color: red; [expanded]
diff --git a/third_party/blink/web_tests/http/tests/devtools/elements/styles-3/style-rule-from-imported-stylesheet-expected.txt b/third_party/blink/web_tests/http/tests/devtools/elements/styles-3/style-rule-from-imported-stylesheet-expected.txt index 079a042..00fa05584 100644 --- a/third_party/blink/web_tests/http/tests/devtools/elements/styles-3/style-rule-from-imported-stylesheet-expected.txt +++ b/third_party/blink/web_tests/http/tests/devtools/elements/styles-3/style-rule-from-imported-stylesheet-expected.txt
@@ -5,7 +5,7 @@ element.style { () [expanded] -.square { (imported-stylesheet.css:2 -> imported-stylesheet.css:2:2) +.square { (imported-st…sheet.css:2 -> imported-stylesheet.css:2:2) background-color: red; display: inline-block; @@ -23,7 +23,7 @@ element.style { () [expanded] -.square { (imported-stylesheet.css:2 -> imported-stylesheet.css:2:2) +.square { (imported-st…sheet.css:2 -> imported-stylesheet.css:2:2) /-- overloaded --/ /-- disabled --/ /* background-color: red; */ display: inline-block;
diff --git a/third_party/blink/web_tests/http/tests/devtools/elements/styles-3/styles-add-new-rule-to-stylesheet-expected.txt b/third_party/blink/web_tests/http/tests/devtools/elements/styles-3/styles-add-new-rule-to-stylesheet-expected.txt index e00d40b7..5bcb7de 100644 --- a/third_party/blink/web_tests/http/tests/devtools/elements/styles-3/styles-add-new-rule-to-stylesheet-expected.txt +++ b/third_party/blink/web_tests/http/tests/devtools/elements/styles-3/styles-add-new-rule-to-stylesheet-expected.txt
@@ -4,7 +4,7 @@ element.style { () [expanded] -#other, div { (different-rule-types.css:48 -> different-rule-types.css:48:14) +#other, div { (different-r…ypes.css:48 -> different-rule-types.css:48:14) [expanded] div { (user agent stylesheet)
diff --git a/third_party/blink/web_tests/http/tests/devtools/elements/styles-3/styles-computed-trace-expected.txt b/third_party/blink/web_tests/http/tests/devtools/elements/styles-3/styles-computed-trace-expected.txt index c7c5ed13..c165c4c 100644 --- a/third_party/blink/web_tests/http/tests/devtools/elements/styles-3/styles-computed-trace-expected.txt +++ b/third_party/blink/web_tests/http/tests/devtools/elements/styles-3/styles-computed-trace-expected.txt
@@ -2,62 +2,62 @@ ==== Computed style for ID1 ==== background-attachment: scroll; - initial - #id1 <style>…</style> + initial - #id1 <style> background-clip: border-box; - initial - #id1 <style>…</style> + initial - #id1 <style> background-color: rgb(128, 128, 128); - gray - #id1 <style>…</style> - OVERLOADED black - #id1 <style>…</style> - OVERLOADED green - #id1 <style>…</style> + gray - #id1 <style> + OVERLOADED black - #id1 <style> + OVERLOADED green - #id1 <style> background-image: none; - initial - #id1 <style>…</style> + initial - #id1 <style> background-origin: padding-box; - initial - #id1 <style>…</style> + initial - #id1 <style> background-position-x: 0%; - initial - #id1 <style>…</style> + initial - #id1 <style> background-position-y: 0%; - initial - #id1 <style>…</style> + initial - #id1 <style> background-repeat-x: ; - initial - #id1 <style>…</style> + initial - #id1 <style> background-repeat-y: ; - initial - #id1 <style>…</style> + initial - #id1 <style> background-size: auto; - initial - #id1 <style>…</style> + initial - #id1 <style> color: rgb(0, 0, 0); -internal-root-color - html user agent stylesheet display: block; block - div user agent stylesheet font-family: Courier; - Courier - #id1 <style>…</style> - OVERLOADED Times - #id1 <style>…</style> - OVERLOADED Arial - body <style>…</style> + Courier - #id1 <style> + OVERLOADED Times - #id1 <style> + OVERLOADED Arial - body <style> text-decoration-color: rgb(0, 0, 0); - initial - div <style>…</style> + initial - div <style> text-decoration-line: underline; - underline - div <style>…</style> + underline - div <style> text-decoration-style: solid; - initial - div <style>…</style> + initial - div <style> [expanded] element.style { () ==== Computed style for ID2 ==== background-color: rgb(0, 0, 255); - blue - #id2 <style>…</style> + blue - #id2 <style> color: rgb(0, 0, 0); -internal-root-color - html user agent stylesheet display: block; block - div user agent stylesheet font-family: Courier; - Courier - #id2 <style>…</style> - OVERLOADED Courier - #id1 <style>…</style> - OVERLOADED Times - #id1 <style>…</style> - OVERLOADED Arial - body <style>…</style> + Courier - #id2 <style> + OVERLOADED Courier - #id1 <style> + OVERLOADED Times - #id1 <style> + OVERLOADED Arial - body <style> text-decoration-color: rgb(0, 0, 0); - initial - div <style>…</style> + initial - div <style> text-decoration-line: underline; - underline - div <style>…</style> + underline - div <style> text-decoration-style: solid; - initial - div <style>…</style> + initial - div <style> [expanded] element.style { ()
diff --git a/third_party/blink/web_tests/http/tests/devtools/elements/styles-3/styles-cssom-important-property-expected.txt b/third_party/blink/web_tests/http/tests/devtools/elements/styles-3/styles-cssom-important-property-expected.txt index 333f5f5..91b3350 100644 --- a/third_party/blink/web_tests/http/tests/devtools/elements/styles-3/styles-cssom-important-property-expected.txt +++ b/third_party/blink/web_tests/http/tests/devtools/elements/styles-3/styles-cssom-important-property-expected.txt
@@ -3,7 +3,7 @@ element.style { () [expanded] -div { (<style>…</style>) +div { (<style>) color: red !important; [expanded]
diff --git a/third_party/blink/web_tests/http/tests/devtools/elements/styles-3/styles-disable-property-after-selector-edit-expected.txt b/third_party/blink/web_tests/http/tests/devtools/elements/styles-3/styles-disable-property-after-selector-edit-expected.txt index c03e05e6..4a178869 100644 --- a/third_party/blink/web_tests/http/tests/devtools/elements/styles-3/styles-disable-property-after-selector-edit-expected.txt +++ b/third_party/blink/web_tests/http/tests/devtools/elements/styles-3/styles-disable-property-after-selector-edit-expected.txt
@@ -15,7 +15,7 @@ element.style { () [expanded] -#inspected, .INSERTED-OTHER-SELECTOR { (<style>…</style>) +#inspected, .INSERTED-OTHER-SELECTOR { (<style>) /-- overloaded --/ /-- disabled --/ /* color: red; */ [expanded]
diff --git a/third_party/blink/web_tests/http/tests/devtools/elements/styles-3/styles-variables-expected.txt b/third_party/blink/web_tests/http/tests/devtools/elements/styles-3/styles-variables-expected.txt index b466f61..735c0ed 100644 --- a/third_party/blink/web_tests/http/tests/devtools/elements/styles-3/styles-variables-expected.txt +++ b/third_party/blink/web_tests/http/tests/devtools/elements/styles-3/styles-variables-expected.txt
@@ -9,7 +9,7 @@ element.style { () [expanded] -#id1 { (<style>…</style>) +#id1 { (<style>) --b: 44px; [expanded] @@ -18,7 +18,7 @@ ======== Inherited from body ======== [expanded] -body { (<style>…</style>) +body { (<style>) --a: red; ======== Inherited from html ======== @@ -36,7 +36,7 @@ element.style { () [expanded] -#id2 { (<style>…</style>) +#id2 { (<style>) --a: green; [expanded] @@ -45,12 +45,12 @@ ======== Inherited from div#id1 ======== [expanded] -#id1 { (<style>…</style>) +#id1 { (<style>) --b: 44px; ======== Inherited from body ======== [expanded] -body { (<style>…</style>) +body { (<style>) /-- overloaded --/ --a: red; ======== Inherited from html ======== @@ -68,7 +68,7 @@ element.style { () [expanded] -#id3 { (<style>…</style>) +#id3 { (<style>) --a: inherit; [expanded] @@ -77,17 +77,17 @@ ======== Inherited from div#id2 ======== [expanded] -#id2 { (<style>…</style>) +#id2 { (<style>) /-- overloaded --/ --a: green; ======== Inherited from div#id1 ======== [expanded] -#id1 { (<style>…</style>) +#id1 { (<style>) --b: 44px; ======== Inherited from body ======== [expanded] -body { (<style>…</style>) +body { (<style>) /-- overloaded --/ --a: red; ======== Inherited from html ======== @@ -105,7 +105,7 @@ element.style { () [expanded] -#id4 { (<style>…</style>) +#id4 { (<style>) --a: var(--z); [expanded] @@ -114,7 +114,7 @@ ======== Inherited from body ======== [expanded] -body { (<style>…</style>) +body { (<style>) /-- overloaded --/ --a: red; ======== Inherited from html ========
diff --git a/third_party/blink/web_tests/http/tests/devtools/elements/styles-4/styles-do-not-detach-sourcemap-on-edits-expected.txt b/third_party/blink/web_tests/http/tests/devtools/elements/styles-4/styles-do-not-detach-sourcemap-on-edits-expected.txt index 2c0fad4..1f63cc7 100644 --- a/third_party/blink/web_tests/http/tests/devtools/elements/styles-4/styles-do-not-detach-sourcemap-on-edits-expected.txt +++ b/third_party/blink/web_tests/http/tests/devtools/elements/styles-4/styles-do-not-detach-sourcemap-on-edits-expected.txt
@@ -7,7 +7,7 @@ [expanded] @media (min-width: 6px) -#container { (styles-do-not-d…n-edits.scss:3 -> styles-do-not-detach-sourcemap-on-edits.scss:3:9) +#container { (styles-do-n…dits.scss:3 -> styles-do-not-detach-sourcemap-on-edits.scss:3:9) border: 1px solid blue; color: blue; @@ -27,7 +27,7 @@ [expanded] @media (min-width: 6px) -#container { (styles-do-not-d…n-edits.scss:3 -> styles-do-not-detach-sourcemap-on-edits.scss:3:9) +#container { (styles-do-n…dits.scss:3 -> styles-do-not-detach-sourcemap-on-edits.scss:3:9) border: 1px solid blue; /-- overloaded --/ NAME: VALUE; @@ -47,7 +47,7 @@ [expanded] @media (min-width: 6px) -#container, SELECTOR { (styles-do-not-d…n-edits.scss:3 -> styles-do-not-detach-sourcemap-on-edits.scss:3:17) +#container, SELECTOR { (styles-do-n…dits.scss:3 -> styles-do-not-detach-sourcemap-on-edits.scss:3:17) border: 1px solid blue; /-- overloaded --/ NAME: VALUE; @@ -67,7 +67,7 @@ [expanded] @media (max-width: 9999999px) -#container, SELECTOR { (styles-do-not-d…n-edits.scss:3 -> styles-do-not-detach-sourcemap-on-edits.scss:3:17) +#container, SELECTOR { (styles-do-n…dits.scss:3 -> styles-do-not-detach-sourcemap-on-edits.scss:3:17) border: 1px solid blue; /-- overloaded --/ NAME: VALUE; @@ -86,11 +86,11 @@ element.style { () [expanded] [no-affect] -NEW-RULE { (styles-do-not-d…n-edits.scss:4 -> styles-do-not-detach-sourcemap-on-edits.scss:4:20) +NEW-RULE { (styles-do-n…dits.scss:4 -> styles-do-not-detach-sourcemap-on-edits.scss:4:20) [expanded] @media (max-width: 9999999px) -#container, SELECTOR { (styles-do-not-d…n-edits.scss:3 -> styles-do-not-detach-sourcemap-on-edits.scss:3:17) +#container, SELECTOR { (styles-do-n…dits.scss:3 -> styles-do-not-detach-sourcemap-on-edits.scss:3:17) border: 1px solid blue; /-- overloaded --/ NAME: VALUE;
diff --git a/third_party/blink/web_tests/http/tests/devtools/elements/styles-4/styles-edit-property-after-invalid-rule-expected.txt b/third_party/blink/web_tests/http/tests/devtools/elements/styles-4/styles-edit-property-after-invalid-rule-expected.txt index 55250d3..808c17b4 100644 --- a/third_party/blink/web_tests/http/tests/devtools/elements/styles-4/styles-edit-property-after-invalid-rule-expected.txt +++ b/third_party/blink/web_tests/http/tests/devtools/elements/styles-4/styles-edit-property-after-invalid-rule-expected.txt
@@ -5,7 +5,7 @@ element.style { () [expanded] -#container { (<style>…</style>) +#container { (<style>) padding: 15px; [expanded] @@ -22,7 +22,7 @@ element.style { () [expanded] -#container { (<style>…</style>) +#container { (<style>) padding: 20px; [expanded]
diff --git a/third_party/blink/web_tests/http/tests/devtools/elements/styles-4/styles-iframe-expected.txt b/third_party/blink/web_tests/http/tests/devtools/elements/styles-4/styles-iframe-expected.txt index 18d17b77..9c8ad63f 100644 --- a/third_party/blink/web_tests/http/tests/devtools/elements/styles-4/styles-iframe-expected.txt +++ b/third_party/blink/web_tests/http/tests/devtools/elements/styles-4/styles-iframe-expected.txt
@@ -22,7 +22,7 @@ element.style { () [expanded] -body { (styles-iframe-data.html:4 -> styles-iframe-data.html:4:9) +body { (styles-ifra…data.html:4 -> styles-iframe-data.html:4:9) background: green; [expanded]
diff --git a/third_party/blink/web_tests/http/tests/devtools/elements/styles-4/styles-inherited-same-source-expected.txt b/third_party/blink/web_tests/http/tests/devtools/elements/styles-4/styles-inherited-same-source-expected.txt index c5b495a..4180754 100644 --- a/third_party/blink/web_tests/http/tests/devtools/elements/styles-4/styles-inherited-same-source-expected.txt +++ b/third_party/blink/web_tests/http/tests/devtools/elements/styles-4/styles-inherited-same-source-expected.txt
@@ -4,7 +4,7 @@ element.style { () [expanded] -div { (<style>…</style>) +div { (<style>) color: red; [expanded]
diff --git a/third_party/blink/web_tests/http/tests/devtools/elements/styles-4/styles-keyframes-expected.txt b/third_party/blink/web_tests/http/tests/devtools/elements/styles-4/styles-keyframes-expected.txt index 46cf2f1..d6426e3 100644 --- a/third_party/blink/web_tests/http/tests/devtools/elements/styles-4/styles-keyframes-expected.txt +++ b/third_party/blink/web_tests/http/tests/devtools/elements/styles-4/styles-keyframes-expected.txt
@@ -27,12 +27,12 @@ ======== @keyframes animName ======== [expanded] -0%, 20% { (<style>…</style>) +0%, 20% { (<style>) margin-left: 200px; color: red; [expanded] -100% { (<style>…</style>) +100% { (<style>) margin-left: 500px; ======== @keyframes mediaAnim ======== @@ -84,12 +84,12 @@ ======== @keyframes animName ======== [expanded] -0%, 20% { (<style>…</style>) +0%, 20% { (<style>) margin-left: 200px; color: red; [expanded] -1% { (<style>…</style>) +1% { (<style>) margin-left: 500px; ======== @keyframes mediaAnim ======== @@ -141,12 +141,12 @@ ======== @keyframes animName ======== [expanded] -0%, 20% { (<style>…</style>) +0%, 20% { (<style>) margin-left: 200px; color: red; [expanded] -100% { (<style>…</style>) +100% { (<style>) margin-left: 500px; ======== @keyframes mediaAnim ======== @@ -198,12 +198,12 @@ ======== @keyframes animName ======== [expanded] -0%, 20% { (<style>…</style>) +0%, 20% { (<style>) margin-left: 200px; color: red; [expanded] -1% { (<style>…</style>) +1% { (<style>) margin-left: 500px; ======== @keyframes mediaAnim ======== @@ -255,12 +255,12 @@ ======== @keyframes animName ======== [expanded] -0%, 20% { (<style>…</style>) +0%, 20% { (<style>) margin-left: 200px; color: red; [expanded] -1% { (<style>…</style>) +1% { (<style>) margin-left: 500px; ======== @keyframes mediaAnim ========
diff --git a/third_party/blink/web_tests/http/tests/devtools/elements/styles-4/styles-overloaded-shorthand-expected.txt b/third_party/blink/web_tests/http/tests/devtools/elements/styles-4/styles-overloaded-shorthand-expected.txt index 9896aac..7e1e2e30 100644 --- a/third_party/blink/web_tests/http/tests/devtools/elements/styles-4/styles-overloaded-shorthand-expected.txt +++ b/third_party/blink/web_tests/http/tests/devtools/elements/styles-4/styles-overloaded-shorthand-expected.txt
@@ -4,7 +4,7 @@ element.style { () [expanded] -.foo { (<style>…</style>) +.foo { (<style>) font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; @@ -22,7 +22,7 @@ /-- overloaded --/ margin-left: 10px; [expanded] -div { (<style>…</style>) +div { (<style>) margin-left: 0px !important; margin-right: 0px !important; margin-top: 0px !important; @@ -34,7 +34,7 @@ ======== Inherited from body ======== [expanded] -body { (<style>…</style>) +body { (<style>) /-- overloaded --/ font: 1.2em "Arial", sans-serif; /-- overloaded --/ font-style: normal; /-- overloaded --/ font-variant-ligatures: normal;
diff --git a/third_party/blink/web_tests/http/tests/devtools/elements/styles-4/styles-overriden-properties-expected.txt b/third_party/blink/web_tests/http/tests/devtools/elements/styles-4/styles-overriden-properties-expected.txt index 4813ba0..94b737e9 100644 --- a/third_party/blink/web_tests/http/tests/devtools/elements/styles-4/styles-overriden-properties-expected.txt +++ b/third_party/blink/web_tests/http/tests/devtools/elements/styles-4/styles-overriden-properties-expected.txt
@@ -4,15 +4,15 @@ element.style { () [expanded] -#main { (<style>…</style>) +#main { (<style>) /-- overloaded --/ -x: ; [expanded] -#main { (<style>…</style>) +#main { (<style>) /-- overloaded --/ -x: ; [expanded] -#main { (<style>…</style>) +#main { (<style>) /-- overloaded --/ background: #000; background: #bada55;
diff --git a/third_party/blink/web_tests/http/tests/devtools/elements/styles-4/styles-properties-overload-expected.txt b/third_party/blink/web_tests/http/tests/devtools/elements/styles-4/styles-properties-overload-expected.txt index 45b5e6f0..c611b016 100644 --- a/third_party/blink/web_tests/http/tests/devtools/elements/styles-4/styles-properties-overload-expected.txt +++ b/third_party/blink/web_tests/http/tests/devtools/elements/styles-4/styles-properties-overload-expected.txt
@@ -4,7 +4,7 @@ element.style { () [expanded] -#inspect { (<style>…</style>) +#inspect { (<style>) margin-top: 1px; margin-left: 1px; margin-right: 1px; @@ -22,7 +22,7 @@ font-family: Arial; [expanded] -div { (<style>…</style>) +div { (<style>) /-- overloaded --/ margin: 1px; /-- overloaded --/ margin-top: 1px; /-- overloaded --/ margin-right: 1px; @@ -53,7 +53,7 @@ ======== Inherited from div.container ======== [expanded] -.container { (<style>…</style>) +.container { (<style>) /-- overloaded --/ font-size: 10px; ======== Inherited from html ========
diff --git a/third_party/blink/web_tests/http/tests/devtools/elements/styles-4/styles-source-lines-expected.txt b/third_party/blink/web_tests/http/tests/devtools/elements/styles-4/styles-source-lines-expected.txt index 14c54b1a..1ba28148 100644 --- a/third_party/blink/web_tests/http/tests/devtools/elements/styles-4/styles-source-lines-expected.txt +++ b/third_party/blink/web_tests/http/tests/devtools/elements/styles-4/styles-source-lines-expected.txt
@@ -4,22 +4,22 @@ element.style { () [expanded] -#main, .at_line_49 { (styles-source-l…helper.html:50 -> styles-source-lines-helper.html:50:2) +#main, .at_line_49 { (styles-sour…per.html:50 -> styles-source-lines-helper.html:50:2) border: 1px solid red; [expanded] -#main, .at_line_41 { (styles-source-l…helper.html:43 -> styles-source-lines-helper.html:43:2) +#main, .at_line_41 { (styles-sour…per.html:43 -> styles-source-lines-helper.html:43:2) font-size: 10px; [expanded] -#main, .at_line_26 { (styles-source-l…helper.html:29 -> styles-source-lines-helper.html:29:2) +#main, .at_line_26 { (styles-sour…per.html:29 -> styles-source-lines-helper.html:29:2) font-family: /* Comment in value */courier; /-- overloaded --/ color blue: ; [expanded] -#main, .at_line_11::before { (styles-source-l…helper.html:15 -> styles-source-lines-helper.html:15:2) +#main, .at_line_11::before { (styles-sour…per.html:15 -> styles-source-lines-helper.html:15:2) color: red; content: "Before";
diff --git a/third_party/blink/web_tests/http/tests/devtools/elements/styles-4/styles-source-lines-inline-expected.txt b/third_party/blink/web_tests/http/tests/devtools/elements/styles-4/styles-source-lines-inline-expected.txt index d3e1c166..3dd7591 100644 --- a/third_party/blink/web_tests/http/tests/devtools/elements/styles-4/styles-source-lines-inline-expected.txt +++ b/third_party/blink/web_tests/http/tests/devtools/elements/styles-4/styles-source-lines-inline-expected.txt
@@ -5,7 +5,7 @@ display: none; [expanded] -.foo { (styles-source-l…-helper.html:4 -> styles-source-lines-inline-helper.html:4:7) +.foo { (styles-sour…lper.html:4 -> styles-source-lines-inline-helper.html:4:7) color: blue; [expanded]
diff --git a/third_party/blink/web_tests/http/tests/devtools/elements/styles-4/styles-source-lines-recovery-expected.txt b/third_party/blink/web_tests/http/tests/devtools/elements/styles-4/styles-source-lines-recovery-expected.txt index 0aa69e7..b8be4a5 100644 --- a/third_party/blink/web_tests/http/tests/devtools/elements/styles-4/styles-source-lines-recovery-expected.txt +++ b/third_party/blink/web_tests/http/tests/devtools/elements/styles-4/styles-source-lines-recovery-expected.txt
@@ -4,15 +4,15 @@ element.style { () [expanded] -#main { (styles-source-l…helper.html:25 -> styles-source-lines-recovery-helper.html:25:8) +#main { (styles-sour…per.html:25 -> styles-source-lines-recovery-helper.html:25:8) color: white; [expanded] -#main { (styles-source-l…helper.html:16 -> styles-source-lines-recovery-helper.html:16:8) +#main { (styles-sour…per.html:16 -> styles-source-lines-recovery-helper.html:16:8) /-- overloaded --/ color: blue; [expanded] -#main { (styles-source-l…-helper.html:7 -> styles-source-lines-recovery-helper.html:7:8) +#main { (styles-sour…lper.html:7 -> styles-source-lines-recovery-helper.html:7:8) /-- overloaded --/ color: red; [expanded]
diff --git a/third_party/blink/web_tests/http/tests/devtools/elements/styles-4/styles-update-links-1-expected.txt b/third_party/blink/web_tests/http/tests/devtools/elements/styles-4/styles-update-links-1-expected.txt index c1445fc..9c1b88c 100644 --- a/third_party/blink/web_tests/http/tests/devtools/elements/styles-4/styles-update-links-1-expected.txt +++ b/third_party/blink/web_tests/http/tests/devtools/elements/styles-4/styles-update-links-1-expected.txt
@@ -9,32 +9,32 @@ [expanded] @media (min-device-width: 1px) -.should-change { (styles-update-links.css:11 -> styles-update-links.css:11:21) +.should-change { (styles-upda…inks.css:11 -> styles-update-links.css:11:21) font-family: monospace; [expanded] -.should-change { (styles-update-links.css:7 -> styles-update-links.css:7:79) +.should-change { (styles-upda…links.css:7 -> styles-update-links.css:7:79) position: relative; margin: 1em; [expanded] -.should-change { (styles-update-links.css:7 -> styles-update-links.css:7:35) +.should-change { (styles-upda…links.css:7 -> styles-update-links.css:7:35) border: 1px solid black; [expanded] -.should-change { (styles-update-links.css:6 -> styles-update-links.css:6:19) +.should-change { (styles-upda…links.css:6 -> styles-update-links.css:6:19) color: red; [expanded] -.left-intact { (styles-update-links.css:4 -> styles-update-links.css:4:15) +.left-intact { (styles-upda…links.css:4 -> styles-update-links.css:4:15) padding: 1em; [expanded] -.left-intact { (styles-update-links.css:1 -> styles-update-links.css:1:15) +.left-intact { (styles-upda…links.css:1 -> styles-update-links.css:1:15) box-sizing: border-box; [expanded] -.left-intact { (styles-update-links-2.css:19 -> styles-update-links-2.css:19:15) +.left-intact { (styles-upda…ks-2.css:19 -> styles-update-links-2.css:19:15) line-height: 1; [expanded] @@ -56,33 +56,33 @@ [expanded] @media (min-device-width: 1px) -.should-change { (styles-update-links.css:13 -> styles-update-links.css:13:21) +.should-change { (styles-upda…inks.css:13 -> styles-update-links.css:13:21) font-family: monospace; [expanded] -.should-change { (styles-update-links.css:9 -> styles-update-links.css:9:67) +.should-change { (styles-upda…links.css:9 -> styles-update-links.css:9:67) position: relative; margin: 1em; [expanded] -.should-change { (styles-update-links.css:9 -> styles-update-links.css:9:23) +.should-change { (styles-upda…links.css:9 -> styles-update-links.css:9:23) border: 1px solid black; [expanded] -.should-change { (styles-update-links.css:6 -> styles-update-links.css:6:19) +.should-change { (styles-upda…links.css:6 -> styles-update-links.css:6:19) color: red; /-- overloaded --/ PROPERTY: INSERTED; [expanded] -.left-intact { (styles-update-links.css:4 -> styles-update-links.css:4:15) +.left-intact { (styles-upda…links.css:4 -> styles-update-links.css:4:15) padding: 1em; [expanded] -.left-intact { (styles-update-links.css:1 -> styles-update-links.css:1:15) +.left-intact { (styles-upda…links.css:1 -> styles-update-links.css:1:15) box-sizing: border-box; [expanded] -.left-intact { (styles-update-links-2.css:19 -> styles-update-links-2.css:19:15) +.left-intact { (styles-upda…ks-2.css:19 -> styles-update-links-2.css:19:15) line-height: 1; [expanded]
diff --git a/third_party/blink/web_tests/http/tests/devtools/elements/styles-4/styles-update-links-2-expected.txt b/third_party/blink/web_tests/http/tests/devtools/elements/styles-4/styles-update-links-2-expected.txt index 37802cb..c3f72235 100644 --- a/third_party/blink/web_tests/http/tests/devtools/elements/styles-4/styles-update-links-2-expected.txt +++ b/third_party/blink/web_tests/http/tests/devtools/elements/styles-4/styles-update-links-2-expected.txt
@@ -14,32 +14,32 @@ [expanded] @media (min-device-width: 1px) -.should-change { (styles-update-links.css:11 -> styles-update-links.css:11:21) +.should-change { (styles-upda…inks.css:11 -> styles-update-links.css:11:21) font-family: monospace; [expanded] -.should-change { (styles-update-links.css:7 -> styles-update-links.css:7:105) +.should-change { (styles-upda…links.css:7 -> styles-update-links.css:7:105) position: relative; margin: 1em; [expanded] -.should-change, .INSERTED-OTHER-SELECTOR { (styles-update-links.css:7 -> styles-update-links.css:7:61) +.should-change, .INSERTED-OTHER-SELECTOR { (styles-upda…links.css:7 -> styles-update-links.css:7:61) border: 1px solid black; [expanded] -.should-change { (styles-update-links.css:6 -> styles-update-links.css:6:19) +.should-change { (styles-upda…links.css:6 -> styles-update-links.css:6:19) color: red; [expanded] -.left-intact { (styles-update-links.css:4 -> styles-update-links.css:4:15) +.left-intact { (styles-upda…links.css:4 -> styles-update-links.css:4:15) padding: 1em; [expanded] -.left-intact { (styles-update-links.css:1 -> styles-update-links.css:1:15) +.left-intact { (styles-upda…links.css:1 -> styles-update-links.css:1:15) box-sizing: border-box; [expanded] -.left-intact { (styles-update-links-2.css:19 -> styles-update-links-2.css:19:15) +.left-intact { (styles-upda…ks-2.css:19 -> styles-update-links-2.css:19:15) line-height: 1; [expanded]
diff --git a/third_party/blink/web_tests/http/tests/devtools/elements/styles-4/styles-update-links-3-expected.txt b/third_party/blink/web_tests/http/tests/devtools/elements/styles-4/styles-update-links-3-expected.txt index 42ebad4..6f67137 100644 --- a/third_party/blink/web_tests/http/tests/devtools/elements/styles-4/styles-update-links-3-expected.txt +++ b/third_party/blink/web_tests/http/tests/devtools/elements/styles-4/styles-update-links-3-expected.txt
@@ -14,32 +14,32 @@ [expanded] @media (min-device-width: 1px) -.should-change { (styles-update-links.css:11 -> styles-update-links.css:11:21) +.should-change { (styles-upda…inks.css:11 -> styles-update-links.css:11:21) font-family: monospace; [expanded] -.should-change { (styles-update-links.css:7 -> styles-update-links.css:7:83) +.should-change { (styles-upda…links.css:7 -> styles-update-links.css:7:83) position: relative; margin: 1em; [expanded] -.should-change { (styles-update-links.css:7 -> styles-update-links.css:7:35) +.should-change { (styles-upda…links.css:7 -> styles-update-links.css:7:35) /-- overloaded --/ /-- disabled --/ /* border: 1px solid black; */ [expanded] -.should-change { (styles-update-links.css:6 -> styles-update-links.css:6:19) +.should-change { (styles-upda…links.css:6 -> styles-update-links.css:6:19) color: red; [expanded] -.left-intact { (styles-update-links.css:4 -> styles-update-links.css:4:15) +.left-intact { (styles-upda…links.css:4 -> styles-update-links.css:4:15) padding: 1em; [expanded] -.left-intact { (styles-update-links.css:1 -> styles-update-links.css:1:15) +.left-intact { (styles-upda…links.css:1 -> styles-update-links.css:1:15) box-sizing: border-box; [expanded] -.left-intact { (styles-update-links-2.css:19 -> styles-update-links-2.css:19:15) +.left-intact { (styles-upda…ks-2.css:19 -> styles-update-links-2.css:19:15) line-height: 1; [expanded]
diff --git a/third_party/blink/web_tests/http/tests/devtools/elements/styles-4/styles-update-links-4-expected.txt b/third_party/blink/web_tests/http/tests/devtools/elements/styles-4/styles-update-links-4-expected.txt index 9a9c19f2..3a2020d8 100644 --- a/third_party/blink/web_tests/http/tests/devtools/elements/styles-4/styles-update-links-4-expected.txt +++ b/third_party/blink/web_tests/http/tests/devtools/elements/styles-4/styles-update-links-4-expected.txt
@@ -23,16 +23,16 @@ ======== Pseudo ::before element ======== [expanded] -#pseudo::before { (<style>…</style>) +#pseudo::before { (<style>) color: blue; ======== Pseudo ::after element ======== [expanded] -#pseudo::after { (<style>…</style>) +#pseudo::after { (<style>) border: 1px solid black; [expanded] -#pseudo::after { (<style>…</style>) +#pseudo::after { (<style>) /-- overloaded --/ pseudo-property: "12"; /-- overloaded --/ PROPERTY: INSERTED; color: red;
diff --git a/third_party/blink/web_tests/http/tests/devtools/elements/styles-4/undo-add-property-expected.txt b/third_party/blink/web_tests/http/tests/devtools/elements/styles-4/undo-add-property-expected.txt index 442ac5c..c2c80e8 100644 --- a/third_party/blink/web_tests/http/tests/devtools/elements/styles-4/undo-add-property-expected.txt +++ b/third_party/blink/web_tests/http/tests/devtools/elements/styles-4/undo-add-property-expected.txt
@@ -6,7 +6,7 @@ element.style { () [expanded] -.container { (<style>…</style>) +.container { (<style>) font-weight: bold; [expanded] @@ -23,7 +23,7 @@ element.style { () [expanded] -.container { (<style>…</style>) +.container { (<style>) font-weight: bold; margin-left: 2px; @@ -41,7 +41,7 @@ element.style { () [expanded] -.container { (<style>…</style>) +.container { (<style>) font-weight: bold; [expanded] @@ -58,7 +58,7 @@ element.style { () [expanded] -.container { (<style>…</style>) +.container { (<style>) font-weight: bold; margin-left: 2px; @@ -77,7 +77,7 @@ element.style { () [expanded] -.container { (<style>…</style>) +.container { (<style>) font-weight: bold; margin-left: 2px; @@ -95,7 +95,7 @@ element.style { () [expanded] -.container { (<style>…</style>) +.container { (<style>) margin-top: 0px; font-weight: bold; margin-left: 2px; @@ -114,7 +114,7 @@ element.style { () [expanded] -.container { (<style>…</style>) +.container { (<style>) font-weight: bold; margin-left: 2px; @@ -132,7 +132,7 @@ element.style { () [expanded] -.container { (<style>…</style>) +.container { (<style>) margin-top: 0px; font-weight: bold; margin-left: 2px; @@ -152,7 +152,7 @@ element.style { () [expanded] -.container { (<style>…</style>) +.container { (<style>) margin-top: 0px; font-weight: bold; margin-left: 2px; @@ -171,7 +171,7 @@ element.style { () [expanded] -.container { (<style>…</style>) +.container { (<style>) margin-top: 0px; margin-right: 1px; font-weight: bold; @@ -191,7 +191,7 @@ element.style { () [expanded] -.container { (<style>…</style>) +.container { (<style>) margin-top: 0px; font-weight: bold; margin-left: 2px; @@ -210,7 +210,7 @@ element.style { () [expanded] -.container { (<style>…</style>) +.container { (<style>) margin-top: 0px; margin-right: 1px; font-weight: bold;
diff --git a/third_party/blink/web_tests/http/tests/devtools/elements/styles/cancel-upon-invalid-property-expected.txt b/third_party/blink/web_tests/http/tests/devtools/elements/styles/cancel-upon-invalid-property-expected.txt index ebfbf66..e1e7aa7 100644 --- a/third_party/blink/web_tests/http/tests/devtools/elements/styles/cancel-upon-invalid-property-expected.txt +++ b/third_party/blink/web_tests/http/tests/devtools/elements/styles/cancel-upon-invalid-property-expected.txt
@@ -4,7 +4,7 @@ element.style { () [expanded] -#inspected { (<style>…</style>) +#inspected { (<style>) color: blue; [expanded] @@ -20,7 +20,7 @@ element.style { () [expanded] -#inspected { (<style>…</style>) +#inspected { (<style>) color: blue; : ;
diff --git a/third_party/blink/web_tests/http/tests/devtools/elements/styles/selector-line-deprecated-expected.txt b/third_party/blink/web_tests/http/tests/devtools/elements/styles/selector-line-deprecated-expected.txt index 80273b31..d916b1d 100644 --- a/third_party/blink/web_tests/http/tests/devtools/elements/styles/selector-line-deprecated-expected.txt +++ b/third_party/blink/web_tests/http/tests/devtools/elements/styles/selector-line-deprecated-expected.txt
@@ -8,7 +8,7 @@ color: green; [expanded] -#inspected { (<style>…</style>) +#inspected { (<style>) /-- overloaded --/ color: green; [expanded]
diff --git a/third_party/blink/web_tests/http/tests/devtools/elements/styles/selector-line-expected.txt b/third_party/blink/web_tests/http/tests/devtools/elements/styles/selector-line-expected.txt index 80273b31..d916b1d 100644 --- a/third_party/blink/web_tests/http/tests/devtools/elements/styles/selector-line-expected.txt +++ b/third_party/blink/web_tests/http/tests/devtools/elements/styles/selector-line-expected.txt
@@ -8,7 +8,7 @@ color: green; [expanded] -#inspected { (<style>…</style>) +#inspected { (<style>) /-- overloaded --/ color: green; [expanded]
diff --git a/third_party/blink/web_tests/http/tests/devtools/elements/styles/selector-line-sourcemap-header-deprecated-expected.txt b/third_party/blink/web_tests/http/tests/devtools/elements/styles/selector-line-sourcemap-header-deprecated-expected.txt index ff7bed6..75de86b9 100644 --- a/third_party/blink/web_tests/http/tests/devtools/elements/styles/selector-line-sourcemap-header-deprecated-expected.txt +++ b/third_party/blink/web_tests/http/tests/devtools/elements/styles/selector-line-sourcemap-header-deprecated-expected.txt
@@ -4,7 +4,7 @@ element.style { () [expanded] -#container #inspected { (selector-line-s…-header.scss:4 -> selector-line-sourcemap-header.scss:4:16) +#container #inspected { (selector-li…ader.scss:4 -> selector-line-sourcemap-header.scss:4:16) color: green; [expanded]
diff --git a/third_party/blink/web_tests/http/tests/devtools/elements/styles/selector-line-sourcemap-header-expected.txt b/third_party/blink/web_tests/http/tests/devtools/elements/styles/selector-line-sourcemap-header-expected.txt index ff7bed6..75de86b9 100644 --- a/third_party/blink/web_tests/http/tests/devtools/elements/styles/selector-line-sourcemap-header-expected.txt +++ b/third_party/blink/web_tests/http/tests/devtools/elements/styles/selector-line-sourcemap-header-expected.txt
@@ -4,7 +4,7 @@ element.style { () [expanded] -#container #inspected { (selector-line-s…-header.scss:4 -> selector-line-sourcemap-header.scss:4:16) +#container #inspected { (selector-li…ader.scss:4 -> selector-line-sourcemap-header.scss:4:16) color: green; [expanded]
diff --git a/third_party/blink/web_tests/http/tests/devtools/elements/styles/show-all-properties-expected.txt b/third_party/blink/web_tests/http/tests/devtools/elements/styles/show-all-properties-expected.txt index 45381de..9db810a3 100644 --- a/third_party/blink/web_tests/http/tests/devtools/elements/styles/show-all-properties-expected.txt +++ b/third_party/blink/web_tests/http/tests/devtools/elements/styles/show-all-properties-expected.txt
@@ -5,7 +5,7 @@ element.style { () [expanded] -#inspected { (<style>…</style>) +#inspected { (<style>) --var-0: 0px; --var-1: 1px; --var-2: 2px; @@ -72,7 +72,7 @@ element.style { () [expanded] -#inspected { (<style>…</style>) +#inspected { (<style>) --var-0: 0px; --var-1: 1px; --var-2: 2px;
diff --git a/third_party/blink/web_tests/http/tests/devtools/elements/styles/styles-parse-invalid-properties-expected.txt b/third_party/blink/web_tests/http/tests/devtools/elements/styles/styles-parse-invalid-properties-expected.txt index 39047cf..23be990 100644 --- a/third_party/blink/web_tests/http/tests/devtools/elements/styles/styles-parse-invalid-properties-expected.txt +++ b/third_party/blink/web_tests/http/tests/devtools/elements/styles/styles-parse-invalid-properties-expected.txt
@@ -5,7 +5,7 @@ /-- overloaded --/ 123: ; [expanded] -#inspected { (<style>…</style>) +#inspected { (<style>) /-- overloaded --/ before property: hey; /-- overloaded --/ after property: hey; /-- overloaded --/ background color: orange; @@ -19,7 +19,7 @@ /-- overloaded --/ bar: foo; [expanded] -#inspected { (<style>…</style>) +#inspected { (<style>) /-- overloaded --/ color: blue; /-- overloaded --/ a property with spaces: red; /-- overloaded --/ --a-property-with-no-value: ;
diff --git a/third_party/blink/web_tests/http/tests/devtools/elements/styles/undo-after-cancelled-editing-expected.txt b/third_party/blink/web_tests/http/tests/devtools/elements/styles/undo-after-cancelled-editing-expected.txt index 449775e..ad11ee26 100644 --- a/third_party/blink/web_tests/http/tests/devtools/elements/styles/undo-after-cancelled-editing-expected.txt +++ b/third_party/blink/web_tests/http/tests/devtools/elements/styles/undo-after-cancelled-editing-expected.txt
@@ -10,7 +10,7 @@ element.style { () [expanded] -#inspected { (<style>…</style>) +#inspected { (<style>) color: blue; : ; @@ -31,7 +31,7 @@ element.style { () [expanded] -#inspected { (<style>…</style>) +#inspected { (<style>) color: blue; [expanded] @@ -49,7 +49,7 @@ element.style { () [expanded] -#inspected { (<style>…</style>) +#inspected { (<style>) [expanded] div { (user agent stylesheet)
diff --git a/third_party/blink/web_tests/http/tests/devtools/elements/styles/undo-change-property-expected.txt b/third_party/blink/web_tests/http/tests/devtools/elements/styles/undo-change-property-expected.txt index 33303f49..124d7565 100644 --- a/third_party/blink/web_tests/http/tests/devtools/elements/styles/undo-change-property-expected.txt +++ b/third_party/blink/web_tests/http/tests/devtools/elements/styles/undo-change-property-expected.txt
@@ -5,7 +5,7 @@ element.style { () [expanded] -.container { (<style>…</style>) +.container { (<style>) font-weight: bold; [expanded] @@ -22,7 +22,7 @@ element.style { () [expanded] -.container { (<style>…</style>) +.container { (<style>) font-weight: normal; [expanded] @@ -39,7 +39,7 @@ element.style { () [expanded] -.container { (<style>…</style>) +.container { (<style>) font-weight: bold; [expanded] @@ -56,7 +56,7 @@ element.style { () [expanded] -.container { (<style>…</style>) +.container { (<style>) font-weight: normal; [expanded]
diff --git a/third_party/blink/web_tests/http/tests/devtools/elements/styles/undo-set-selector-text-expected.txt b/third_party/blink/web_tests/http/tests/devtools/elements/styles/undo-set-selector-text-expected.txt index cdfe9943..856f9aed 100644 --- a/third_party/blink/web_tests/http/tests/devtools/elements/styles/undo-set-selector-text-expected.txt +++ b/third_party/blink/web_tests/http/tests/devtools/elements/styles/undo-set-selector-text-expected.txt
@@ -5,7 +5,7 @@ element.style { () [expanded] -#inspected { (<style>…</style>) +#inspected { (<style>) color: green; [expanded] @@ -22,7 +22,7 @@ element.style { () [expanded] -#inspected, #other { (<style>…</style>) +#inspected, #other { (<style>) color: green; [expanded] @@ -39,7 +39,7 @@ element.style { () [expanded] -#inspected { (<style>…</style>) +#inspected { (<style>) color: green; [expanded] @@ -56,7 +56,7 @@ element.style { () [expanded] -#inspected, #other { (<style>…</style>) +#inspected, #other { (<style>) color: green; [expanded]
diff --git a/third_party/blink/web_tests/http/tests/devtools/startup/shadow-dom-rules-expected.txt b/third_party/blink/web_tests/http/tests/devtools/startup/shadow-dom-rules-expected.txt index bdc4af8..614c1b5c 100644 --- a/third_party/blink/web_tests/http/tests/devtools/startup/shadow-dom-rules-expected.txt +++ b/third_party/blink/web_tests/http/tests/devtools/startup/shadow-dom-rules-expected.txt
@@ -8,7 +8,7 @@ element.style { () [expanded] -.red { (<style>…</style>) +.red { (<style>) color: red; [expanded]
diff --git a/third_party/blink/web_tests/paint/dark-mode/page-policy-all/background-dark-color-expected.png b/third_party/blink/web_tests/paint/dark-mode/page-policy-all/background-dark-color-expected.png new file mode 100644 index 0000000..61855f9 --- /dev/null +++ b/third_party/blink/web_tests/paint/dark-mode/page-policy-all/background-dark-color-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/paint/dark-mode/page-policy-all/background-dark-color.html b/third_party/blink/web_tests/paint/dark-mode/page-policy-all/background-dark-color.html new file mode 100644 index 0000000..9359f114 --- /dev/null +++ b/third_party/blink/web_tests/paint/dark-mode/page-policy-all/background-dark-color.html
@@ -0,0 +1,2 @@ +<!DOCTYPE html> +<body style="background-color: #000080"></body>
diff --git a/third_party/blink/web_tests/paint/dark-mode/page-policy-all/background-light-color-expected.png b/third_party/blink/web_tests/paint/dark-mode/page-policy-all/background-light-color-expected.png new file mode 100644 index 0000000..d03c47e --- /dev/null +++ b/third_party/blink/web_tests/paint/dark-mode/page-policy-all/background-light-color-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/paint/dark-mode/page-policy-all/background-light-color.html b/third_party/blink/web_tests/paint/dark-mode/page-policy-all/background-light-color.html new file mode 100644 index 0000000..fe10c89 --- /dev/null +++ b/third_party/blink/web_tests/paint/dark-mode/page-policy-all/background-light-color.html
@@ -0,0 +1,3 @@ +<!DOCTYPE html> +<body style="background-color: #8080ff"></body> +
diff --git a/third_party/blink/web_tests/paint/dark-mode/page-policy-background/background-invert-expected.png b/third_party/blink/web_tests/paint/dark-mode/page-policy-background/background-invert-expected.png new file mode 100644 index 0000000..d03c47e --- /dev/null +++ b/third_party/blink/web_tests/paint/dark-mode/page-policy-background/background-invert-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/paint/dark-mode/page-policy-background/background-invert.html b/third_party/blink/web_tests/paint/dark-mode/page-policy-background/background-invert.html new file mode 100644 index 0000000..fe10c89 --- /dev/null +++ b/third_party/blink/web_tests/paint/dark-mode/page-policy-background/background-invert.html
@@ -0,0 +1,3 @@ +<!DOCTYPE html> +<body style="background-color: #8080ff"></body> +
diff --git a/third_party/blink/web_tests/paint/dark-mode/page-policy-background/background-noinvert-expected.png b/third_party/blink/web_tests/paint/dark-mode/page-policy-background/background-noinvert-expected.png new file mode 100644 index 0000000..61855f9 --- /dev/null +++ b/third_party/blink/web_tests/paint/dark-mode/page-policy-background/background-noinvert-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/paint/dark-mode/page-policy-background/background-noinvert.html b/third_party/blink/web_tests/paint/dark-mode/page-policy-background/background-noinvert.html new file mode 100644 index 0000000..9359f114 --- /dev/null +++ b/third_party/blink/web_tests/paint/dark-mode/page-policy-background/background-noinvert.html
@@ -0,0 +1,2 @@ +<!DOCTYPE html> +<body style="background-color: #000080"></body>
diff --git a/third_party/blink/web_tests/paint/invalidation/background/background-image-paint-invalidation-expected.txt b/third_party/blink/web_tests/paint/invalidation/background/background-image-paint-invalidation-expected.txt index b5c2099d..9b9ee4c 100644 --- a/third_party/blink/web_tests/paint/invalidation/background/background-image-paint-invalidation-expected.txt +++ b/third_party/blink/web_tests/paint/invalidation/background/background-image-paint-invalidation-expected.txt
@@ -21,11 +21,6 @@ "object": "Scrolling background of LayoutView #document", "rect": [0, 0, 808, 2016], "reason": "background" - }, - { - "object": "LayoutBlockFlow HTML", - "rect": [8, 8, 800, 2000], - "reason": "chunk appeared" } ] }
diff --git a/third_party/blink/web_tests/paint/invalidation/background/viewport-gradient-background-html-resize-overflow-expected.txt b/third_party/blink/web_tests/paint/invalidation/background/viewport-gradient-background-html-resize-overflow-expected.txt index b1310dcf..1919a2b 100644 --- a/third_party/blink/web_tests/paint/invalidation/background/viewport-gradient-background-html-resize-overflow-expected.txt +++ b/third_party/blink/web_tests/paint/invalidation/background/viewport-gradient-background-html-resize-overflow-expected.txt
@@ -25,7 +25,7 @@ { "object": "LayoutBlockFlow HTML", "rect": [0, 0, 800, 200], - "reason": "disappeared" + "reason": "chunk disappeared" } ] }
diff --git a/third_party/blink/web_tests/paint/invalidation/resources/iframe-gradient-background-scroll-repaint-iframe.html b/third_party/blink/web_tests/paint/invalidation/resources/iframe-gradient-background-scroll-repaint-iframe.html new file mode 100644 index 0000000..dc10403c --- /dev/null +++ b/third_party/blink/web_tests/paint/invalidation/resources/iframe-gradient-background-scroll-repaint-iframe.html
@@ -0,0 +1,10 @@ +<!DOCTYPE html> +<html style="background: linear-gradient(red, blue); overflow:hidden"> +<script src="text-based-repaint.js"></script> +<script> +function repaintTest() { + document.scrollingElement.scrollTop = 20; +} +</script> +<body onload="runRepaintTest()"> +<div style="height: 500px"></div>
diff --git a/third_party/blink/web_tests/paint/invalidation/resources/iframe-scroll-repaint-iframe.html b/third_party/blink/web_tests/paint/invalidation/resources/iframe-scroll-repaint-iframe.html index affb63f..475056ed 100644 --- a/third_party/blink/web_tests/paint/invalidation/resources/iframe-scroll-repaint-iframe.html +++ b/third_party/blink/web_tests/paint/invalidation/resources/iframe-scroll-repaint-iframe.html
@@ -7,5 +7,5 @@ } </script> <body onload="runRepaintTest()"> -<div style="height:500px"> +<div style="height:500px"></div>
diff --git a/third_party/blink/web_tests/paint/invalidation/scroll/iframe-gradient-background-scroll-repaint-expected.txt b/third_party/blink/web_tests/paint/invalidation/scroll/iframe-gradient-background-scroll-repaint-expected.txt new file mode 100644 index 0000000..8d60f5b --- /dev/null +++ b/third_party/blink/web_tests/paint/invalidation/scroll/iframe-gradient-background-scroll-repaint-expected.txt
@@ -0,0 +1,29 @@ +{ + "layers": [ + { + "name": "LayoutView #document", + "bounds": [800, 600], + "drawsContent": false, + "backgroundColor": "#FFFFFF" + }, + { + "name": "Scrolling Layer", + "bounds": [800, 600], + "drawsContent": false + }, + { + "name": "Scrolling Contents Layer", + "bounds": [800, 600], + "contentsOpaque": true, + "backgroundColor": "#FFFFFF", + "paintInvalidations": [ + { + "object": "LayoutView #document", + "rect": [10, 10, 300, 150], + "reason": "background" + } + ] + } + ] +} +
diff --git a/third_party/blink/web_tests/paint/invalidation/scroll/iframe-gradient-background-scroll-repaint.html b/third_party/blink/web_tests/paint/invalidation/scroll/iframe-gradient-background-scroll-repaint.html new file mode 100644 index 0000000..f3bbb96 --- /dev/null +++ b/third_party/blink/web_tests/paint/invalidation/scroll/iframe-gradient-background-scroll-repaint.html
@@ -0,0 +1,2 @@ +<!DOCTYPE html> +<iframe src="../resources/iframe-gradient-background-scroll-repaint-iframe.html">
diff --git a/third_party/blink/web_tests/paint/invalidation/scroll/iframe-scroll-repaint-expected.txt b/third_party/blink/web_tests/paint/invalidation/scroll/iframe-scroll-repaint-expected.txt index b4f6bd0..58ba65a 100644 --- a/third_party/blink/web_tests/paint/invalidation/scroll/iframe-scroll-repaint-expected.txt +++ b/third_party/blink/web_tests/paint/invalidation/scroll/iframe-scroll-repaint-expected.txt
@@ -15,14 +15,7 @@ "name": "Scrolling Contents Layer", "bounds": [800, 600], "contentsOpaque": true, - "backgroundColor": "#FFFFFF", - "paintInvalidations": [ - { - "object": "LayoutBlockFlow HTML", - "rect": [10, 10, 300, 150], - "reason": "paint property change" - } - ] + "backgroundColor": "#FFFFFF" } ] }
diff --git a/third_party/blink/web_tests/paint/invalidation/scroll/iframe-scroll-repaint.html b/third_party/blink/web_tests/paint/invalidation/scroll/iframe-scroll-repaint.html index d8b86c8..1df8a84d 100644 --- a/third_party/blink/web_tests/paint/invalidation/scroll/iframe-scroll-repaint.html +++ b/third_party/blink/web_tests/paint/invalidation/scroll/iframe-scroll-repaint.html
@@ -1,6 +1,2 @@ <!DOCTYPE html> -<html style='overflow:hidden'> -<body style='overflow:hidden'> <iframe src="../resources/iframe-scroll-repaint-iframe.html"> - -
diff --git a/third_party/blink/web_tests/platform/fuchsia/editing/selection/4402375-expected.png b/third_party/blink/web_tests/platform/fuchsia/editing/selection/4402375-expected.png deleted file mode 100644 index 0bfecee0..0000000 --- a/third_party/blink/web_tests/platform/fuchsia/editing/selection/4402375-expected.png +++ /dev/null Binary files differ
diff --git a/third_party/blink/web_tests/platform/fuchsia/external/wpt/web-animations/interfaces/Animatable/animate-expected.txt b/third_party/blink/web_tests/platform/fuchsia/external/wpt/web-animations/interfaces/Animatable/animate-expected.txt deleted file mode 100644 index 6bf47632..0000000 --- a/third_party/blink/web_tests/platform/fuchsia/external/wpt/web-animations/interfaces/Animatable/animate-expected.txt +++ /dev/null
@@ -1,144 +0,0 @@ -This is a testharness.js-based test. -Found 140 tests; 132 PASS, 8 FAIL, 0 TIMEOUT, 0 NOTRUN. -PASS Element.animate() creates an Animation object -PASS Element.animate() creates an Animation object in the relevant realm of the target element -PASS Element.animate() creates an Animation object with a KeyframeEffect -PASS Element.animate() creates an Animation object with a KeyframeEffect that is created in the relevant realm of the target element -PASS Element.animate() accepts empty keyframe lists (input: []) -PASS Element.animate() accepts empty keyframe lists (input: null) -PASS Element.animate() accepts empty keyframe lists (input: undefined) -PASS Element.animate() accepts a one property two value property-indexed keyframes specification -FAIL Element.animate() accepts a one shorthand property two value property-indexed keyframes specification assert_equals: properties on ComputedKeyframe #0 should match expected "composite,computedOffset,easing,margin,offset" but got "composite,computedOffset,easing,marginBottom,marginLeft,marginRight,marginTop,offset" -FAIL Element.animate() accepts a two property (one shorthand and one of its longhand components) two value property-indexed keyframes specification assert_equals: properties on ComputedKeyframe #0 should match expected "composite,computedOffset,easing,margin,marginTop,offset" but got "composite,computedOffset,easing,marginBottom,marginLeft,marginRight,marginTop,offset" -PASS Element.animate() accepts a two property two value property-indexed keyframes specification -PASS Element.animate() accepts a two property property-indexed keyframes specification with different numbers of values -PASS Element.animate() accepts a property-indexed keyframes specification with an invalid value -PASS Element.animate() accepts a one property two value property-indexed keyframes specification that needs to stringify its values -PASS Element.animate() accepts a property-indexed keyframes specification with a CSS variable reference -FAIL Element.animate() accepts a property-indexed keyframes specification with a CSS variable reference in a shorthand property assert_equals: properties on ComputedKeyframe #0 should match expected "composite,computedOffset,easing,margin,offset" but got "composite,computedOffset,easing,marginBottom,marginLeft,marginRight,marginTop,offset" -PASS Element.animate() accepts a one property one value property-indexed keyframes specification -PASS Element.animate() accepts a one property one non-array value property-indexed keyframes specification -PASS Element.animate() accepts a one property two value property-indexed keyframes specification where the first value is invalid -PASS Element.animate() accepts a one property two value property-indexed keyframes specification where the second value is invalid -PASS Element.animate() accepts a property-indexed keyframe with a single offset -PASS Element.animate() accepts a property-indexed keyframe with an array of offsets -PASS Element.animate() accepts a property-indexed keyframe with an array of offsets that is too short -PASS Element.animate() accepts a property-indexed keyframe with an array of offsets that is too long -PASS Element.animate() accepts a property-indexed keyframe with an empty array of offsets -PASS Element.animate() accepts a property-indexed keyframe with an array of offsets with an embedded null value -PASS Element.animate() accepts a property-indexed keyframe with an array of offsets with a trailing null value -PASS Element.animate() accepts a property-indexed keyframe with an array of offsets with leading and trailing null values -PASS Element.animate() accepts a property-indexed keyframe with an array of offsets with adjacent null values -PASS Element.animate() accepts a property-indexed keyframe with an array of offsets with all null values (and too many at that) -PASS Element.animate() accepts a property-indexed keyframe with a single null offset -PASS Element.animate() accepts a property-indexed keyframe with an array of offsets that is not strictly ascending in the unused part of the array -PASS Element.animate() accepts a property-indexed keyframe without any specified easing -PASS Element.animate() accepts a property-indexed keyframe with a single easing -PASS Element.animate() accepts a property-indexed keyframe with an array of easings -PASS Element.animate() accepts a property-indexed keyframe with an array of easings that is too short -PASS Element.animate() accepts a property-indexed keyframe with a single-element array of easings -PASS Element.animate() accepts a property-indexed keyframe with an empty array of easings -PASS Element.animate() accepts a property-indexed keyframe with an array of easings that is too long -PASS Element.animate() accepts a property-indexed keyframe with a single composite operation -FAIL Element.animate() accepts a property-indexed keyframe with a composite array assert_equals: value for 'composite' on ComputedKeyframe #2 expected "accumulate" but got "replace" -PASS Element.animate() accepts a property-indexed keyframe with a composite array that is too short -PASS Element.animate() accepts a property-indexed keyframe with a composite array that is too long -PASS Element.animate() accepts a property-indexed keyframe with a single-element composite array -PASS Element.animate() accepts a one property one keyframe sequence -PASS Element.animate() accepts a one property two keyframe sequence -PASS Element.animate() accepts a two property two keyframe sequence -FAIL Element.animate() accepts a one shorthand property two keyframe sequence assert_equals: properties on ComputedKeyframe #0 should match expected "composite,computedOffset,easing,margin,offset" but got "composite,computedOffset,easing,marginBottom,marginLeft,marginRight,marginTop,offset" -FAIL Element.animate() accepts a two property (a shorthand and one of its component longhands) two keyframe sequence assert_equals: properties on ComputedKeyframe #0 should match expected "composite,computedOffset,easing,margin,marginTop,offset" but got "composite,computedOffset,easing,marginBottom,marginLeft,marginRight,marginTop,offset" -PASS Element.animate() accepts a two property keyframe sequence where one property is missing from the first keyframe -PASS Element.animate() accepts a two property keyframe sequence where one property is missing from the last keyframe -PASS Element.animate() accepts a one property two keyframe sequence that needs to stringify its values -PASS Element.animate() accepts a keyframe sequence with a CSS variable reference -FAIL Element.animate() accepts a keyframe sequence with a CSS variable reference in a shorthand property assert_equals: properties on ComputedKeyframe #0 should match expected "composite,computedOffset,easing,margin,offset" but got "composite,computedOffset,easing,marginBottom,marginLeft,marginRight,marginTop,offset" -PASS Element.animate() accepts a keyframe sequence with duplicate values for a given interior offset -PASS Element.animate() accepts a keyframe sequence with duplicate values for offsets 0 and 1 -PASS Element.animate() accepts a two property four keyframe sequence -PASS Element.animate() accepts a single keyframe sequence with omitted offset -PASS Element.animate() accepts a single keyframe sequence with null offset -PASS Element.animate() accepts a single keyframe sequence with string offset -PASS Element.animate() accepts a one property keyframe sequence with some omitted offsets -PASS Element.animate() accepts a one property keyframe sequence with some null offsets -PASS Element.animate() accepts a two property keyframe sequence with some omitted offsets -PASS Element.animate() accepts a one property keyframe sequence with all omitted offsets -PASS Element.animate() accepts a keyframe sequence with different easing values, but the same easing value for a given offset -PASS Element.animate() accepts a keyframe sequence with different composite values, but the same composite value for a given offset -PASS Element.animate() does not accept keyframes with an out-of-bounded positive offset -PASS Element.animate() does not accept keyframes with an out-of-bounded negative offset -PASS Element.animate() does not accept property-indexed keyframes not loosely sorted by offset -PASS Element.animate() does not accept property-indexed keyframes not loosely sorted by offset even though not all offsets are specified -PASS Element.animate() does not accept property-indexed keyframes with offsets out of range -PASS Element.animate() does not accept keyframes not loosely sorted by offset -PASS Element.animate() does not accept property-indexed keyframes with an invalid easing value -PASS Element.animate() does not accept property-indexed keyframes with an invalid easing value as one of the array values -PASS Element.animate() does not accept property-indexed keyframe with an invalid easing in the unused part of the array of easings -PASS Element.animate() does not accept empty property-indexed keyframe with an invalid easing -PASS Element.animate() does not accept empty property-indexed keyframe with an invalid easings array -PASS Element.animate() does not accept a keyframe sequence with an invalid easing value -PASS Element.animate() does not accept property-indexed keyframes with an invalid composite value -PASS Element.animate() does not accept property-indexed keyframes with an invalid composite value as one of the array values -PASS Element.animate() does not accept keyframes with an invalid composite value -PASS Element.animate() accepts a double as an options argument -PASS Element.animate() accepts a KeyframeAnimationOptions argument -PASS Element.animate() accepts an absent options argument -PASS Element.animate() does not accept invalid delay value: NaN -PASS Element.animate() does not accept invalid delay value: Infinity -PASS Element.animate() does not accept invalid delay value: -Infinity -PASS Element.animate() accepts a duration of 'auto' using a dictionary object -PASS Element.animate() does not accept invalid duration value: -1 -PASS Element.animate() does not accept invalid duration value: NaN -PASS Element.animate() does not accept invalid duration value: -Infinity -PASS Element.animate() does not accept invalid duration value: "abc" -PASS Element.animate() does not accept invalid duration value: -1 using a dictionary object -PASS Element.animate() does not accept invalid duration value: NaN using a dictionary object -PASS Element.animate() does not accept invalid duration value: -Infinity using a dictionary object -PASS Element.animate() does not accept invalid duration value: "abc" using a dictionary object -PASS Element.animate() does not accept invalid duration value: "100" using a dictionary object -PASS Element.animate() does not accept invalid easing: '' -PASS Element.animate() does not accept invalid easing: '7' -PASS Element.animate() does not accept invalid easing: 'test' -PASS Element.animate() does not accept invalid easing: 'initial' -PASS Element.animate() does not accept invalid easing: 'inherit' -PASS Element.animate() does not accept invalid easing: 'unset' -PASS Element.animate() does not accept invalid easing: 'unrecognized' -PASS Element.animate() does not accept invalid easing: 'var(--x)' -PASS Element.animate() does not accept invalid easing: 'ease-in-out, ease-out' -PASS Element.animate() does not accept invalid easing: 'cubic-bezier(1.1, 0, 1, 1)' -PASS Element.animate() does not accept invalid easing: 'cubic-bezier(0, 0, 1.1, 1)' -PASS Element.animate() does not accept invalid easing: 'cubic-bezier(-0.1, 0, 1, 1)' -PASS Element.animate() does not accept invalid easing: 'cubic-bezier(0, 0, -0.1, 1)' -PASS Element.animate() does not accept invalid easing: 'cubic-bezier(0.1, 0, 4, 0.4)' -PASS Element.animate() does not accept invalid easing: 'steps(-1, start)' -PASS Element.animate() does not accept invalid easing: 'steps(0.1, start)' -PASS Element.animate() does not accept invalid easing: 'steps(3, nowhere)' -PASS Element.animate() does not accept invalid easing: 'steps(-3, end)' -PASS Element.animate() does not accept invalid easing: 'function (a){return a}' -PASS Element.animate() does not accept invalid easing: 'function (x){return x}' -PASS Element.animate() does not accept invalid easing: 'function(x, y){return 0.3}' -PASS Element.animate() does not accept invalid easing: 'frames(1)' -PASS Element.animate() does not accept invalid easing: 'frames' -PASS Element.animate() does not accept invalid easing: 'frames()' -PASS Element.animate() does not accept invalid easing: 'frames(,)' -PASS Element.animate() does not accept invalid easing: 'frames(a)' -PASS Element.animate() does not accept invalid easing: 'frames(2.0)' -PASS Element.animate() does not accept invalid easing: 'frames(2.5)' -PASS Element.animate() does not accept invalid easing: 'frames(2 3)' -PASS Element.animate() does not accept invalid iterationStart value: -1 -PASS Element.animate() does not accept invalid iterationStart value: NaN -PASS Element.animate() does not accept invalid iterationStart value: Infinity -PASS Element.animate() does not accept invalid iterationStart value: -Infinity -PASS Element.animate() does not accept invalid iterations value: -1 -PASS Element.animate() does not accept invalid iterations value: -Infinity -PASS Element.animate() does not accept invalid iterations value: NaN -PASS Element.animate() correctly sets the id attribute when no id is specified -PASS Element.animate() correctly sets the id attribute -PASS Element.animate() correctly sets the Animation's timeline -PASS Element.animate() correctly sets the Animation's timeline when triggered on an element in a different document -FAIL Element.animate() calls play on the Animation assert_equals: expected "running" but got "pending" -PASS CSSPseudoElement.animate() creates an Animation object -PASS CSSPseudoElement.animate() creates an Animation object targeting to the correct CSSPseudoElement object -Harness: the test ran to completion. -
diff --git a/third_party/blink/web_tests/platform/fuchsia/external/wpt/web-animations/interfaces/Animatable/getAnimations-expected.txt b/third_party/blink/web_tests/platform/fuchsia/external/wpt/web-animations/interfaces/Animatable/getAnimations-expected.txt deleted file mode 100644 index d5d1c3d7..0000000 --- a/third_party/blink/web_tests/platform/fuchsia/external/wpt/web-animations/interfaces/Animatable/getAnimations-expected.txt +++ /dev/null
@@ -1,19 +0,0 @@ -This is a testharness.js-based test. -PASS Returns an empty array for an element with no animations -PASS Returns both animations for an element with two animations -PASS Returns only the animations specific to each sibling element -PASS Returns only the animations specific to each parent/child element -PASS Does not return finished animations that do not fill forwards -PASS Returns finished animations that fill forwards -PASS Returns animations yet to reach their active phase -FAIL Does not return reversed finished animations that do not fill backwards assert_array_equals: lengths differ, expected 0 got 1 -PASS Returns reversed finished animations that fill backwards -FAIL Returns reversed animations yet to reach their active phase assert_array_equals: lengths differ, expected 1 got 0 -FAIL Does not return animations with zero playback rate in before phase assert_array_equals: lengths differ, expected 0 got 1 -PASS Does not return animations with zero playback rate in after phase -PASS Returns animations based on dynamic changes to individual animations' duration -PASS Returns animations based on dynamic changes to individual animations' end delay -PASS Returns animations based on dynamic changes to individual animations' iteration count -PASS Returns animations based on dynamic changes to individual animations' current time -Harness: the test ran to completion. -
diff --git a/third_party/blink/web_tests/platform/fuchsia/external/wpt/web-animations/interfaces/Document/getAnimations-expected.txt b/third_party/blink/web_tests/platform/fuchsia/external/wpt/web-animations/interfaces/Document/getAnimations-expected.txt deleted file mode 100644 index 92d85dc..0000000 --- a/third_party/blink/web_tests/platform/fuchsia/external/wpt/web-animations/interfaces/Document/getAnimations-expected.txt +++ /dev/null
@@ -1,9 +0,0 @@ -This is a testharness.js-based test. -PASS Test document.getAnimations for non-animated content -PASS Test document.getAnimations for script-generated animations -PASS Test the order of document.getAnimations with script generated animations -PASS Test document.getAnimations for a disconnected node -PASS Test document.getAnimations with null target -FAIL Test document.getAnimations for elements inside same-origin iframes assert_equals: expected 1 but got 0 -Harness: the test ran to completion. -
diff --git a/third_party/blink/web_tests/platform/fuchsia/external/wpt/web-animations/timing-model/time-transformations/transformed-progress-expected.txt b/third_party/blink/web_tests/platform/fuchsia/external/wpt/web-animations/timing-model/time-transformations/transformed-progress-expected.txt deleted file mode 100644 index 1046b2d..0000000 --- a/third_party/blink/web_tests/platform/fuchsia/external/wpt/web-animations/timing-model/time-transformations/transformed-progress-expected.txt +++ /dev/null
@@ -1,35 +0,0 @@ -This is a testharness.js-based test. -PASS Transformed progress for step-start function -PASS Transformed progress for steps(1, start) function -PASS Transformed progress for steps(2, start) function -PASS Transformed progress for step-end function -PASS Transformed progress for steps(1) function -PASS Transformed progress for steps(1, end) function -PASS Transformed progress for steps(2, end) function -PASS Transformed progress for frames function -PASS Transformed progress for linear function -FAIL Transformed progress for ease function assert_approx_equals: The progress should be approximately 0.40851059137130497 at 250ms expected 0.40851059137130497 +/- 0.01 but got 0.41869212962962965 -PASS Transformed progress for ease-in function -PASS Transformed progress for ease-in-out function -PASS Transformed progress for ease-out function -PASS Transformed progress for easing function which produces values greater than 1 -PASS Transformed progress for easing function which produces values less than 1 -FAIL Test bounds point of step-start easing assert_equals: Progress at 0ms expected 0 but got 0.5 -FAIL Test bounds point of step-start easing with reverse direction assert_equals: Progress at 2000ms expected 0 but got 0.5 -PASS Test bounds point of step-start easing with iterationStart not at a transition point -FAIL Test bounds point of step-start easing with iterationStart and delay assert_equals: Progress at 0ms expected 0.5 but got 1 -FAIL Test bounds point of step-start easing with iterationStart and reverse direction assert_equals: Progress at 2000ms expected 0.5 but got 1 -FAIL Test bounds point of step(4, start) easing with iterationStart 0.75 and delay assert_equals: Progress at 0ms expected 0.75 but got 1 -FAIL Test bounds point of step-start easing with alternate direction assert_equals: Progress at 3000ms expected 0.5 but got 1 -FAIL Test bounds point of step-start easing with alternate-reverse direction assert_equals: Progress at 3000ms expected 0.5 but got 1 -PASS Test bounds point of step-end easing -FAIL Test bounds point of step-end easing with iterationStart and delay assert_equals: Progress at 0ms expected 0 but got 0.5 -PASS Test bounds point of step-end easing with iterationStart not at a transition point -FAIL Test bounds point of steps(jump-both) easing Failed to execute 'animate' on 'Element': 'steps(2, jump-both)' is not a valid value for easing -FAIL Test bounds point of steps(jump-both) easing with iterationStart and delay Failed to execute 'animate' on 'Element': 'steps(2, jump-both)' is not a valid value for easing -FAIL Test bounds point of steps(jump-both) easing with iterationStart not at a transition point Failed to execute 'animate' on 'Element': 'steps(2, jump-both)' is not a valid value for easing -FAIL Test bounds point of steps(jump-none) easing Failed to execute 'animate' on 'Element': 'steps(2, jump-none)' is not a valid value for easing -FAIL Test bounds point of steps(jump-none) easing with iterationStart and delay Failed to execute 'animate' on 'Element': 'steps(2, jump-none)' is not a valid value for easing -FAIL Test bounds point of steps(jump-none) easing with iterationStart not at a transition point Failed to execute 'animate' on 'Element': 'steps(2, jump-none)' is not a valid value for easing -Harness: the test ran to completion. -
diff --git a/third_party/blink/web_tests/platform/fuchsia/fast/css3-text/css3-text-decoration/text-decoration-style-expected.png b/third_party/blink/web_tests/platform/fuchsia/fast/css3-text/css3-text-decoration/text-decoration-style-expected.png deleted file mode 100644 index c147371..0000000 --- a/third_party/blink/web_tests/platform/fuchsia/fast/css3-text/css3-text-decoration/text-decoration-style-expected.png +++ /dev/null Binary files differ
diff --git a/third_party/blink/web_tests/platform/fuchsia/fast/css3-text/css3-text-decoration/text-decoration-style-inherit-expected.png b/third_party/blink/web_tests/platform/fuchsia/fast/css3-text/css3-text-decoration/text-decoration-style-inherit-expected.png deleted file mode 100644 index 7c3fe92..0000000 --- a/third_party/blink/web_tests/platform/fuchsia/fast/css3-text/css3-text-decoration/text-decoration-style-inherit-expected.png +++ /dev/null Binary files differ
diff --git a/third_party/blink/web_tests/platform/fuchsia/fast/css3-text/css3-text-decoration/text-decoration-style-inherit-links-expected.png b/third_party/blink/web_tests/platform/fuchsia/fast/css3-text/css3-text-decoration/text-decoration-style-inherit-links-expected.png deleted file mode 100644 index e8a69d5..0000000 --- a/third_party/blink/web_tests/platform/fuchsia/fast/css3-text/css3-text-decoration/text-decoration-style-inherit-links-expected.png +++ /dev/null Binary files differ
diff --git a/third_party/blink/web_tests/platform/fuchsia/fast/css3-text/css3-text-decoration/text-decoration-style-inherit-not-propagated-by-out-of-flow-expected.png b/third_party/blink/web_tests/platform/fuchsia/fast/css3-text/css3-text-decoration/text-decoration-style-inherit-not-propagated-by-out-of-flow-expected.png deleted file mode 100644 index 09817f2..0000000 --- a/third_party/blink/web_tests/platform/fuchsia/fast/css3-text/css3-text-decoration/text-decoration-style-inherit-not-propagated-by-out-of-flow-expected.png +++ /dev/null Binary files differ
diff --git a/third_party/blink/web_tests/platform/fuchsia/fast/css3-text/css3-text-decoration/text-decoration-style-inherit-simple-underlines-expected.png b/third_party/blink/web_tests/platform/fuchsia/fast/css3-text/css3-text-decoration/text-decoration-style-inherit-simple-underlines-expected.png deleted file mode 100644 index 4e19d96..0000000 --- a/third_party/blink/web_tests/platform/fuchsia/fast/css3-text/css3-text-decoration/text-decoration-style-inherit-simple-underlines-expected.png +++ /dev/null Binary files differ
diff --git a/third_party/blink/web_tests/platform/fuchsia/fast/text/stroking-decorations-expected.png b/third_party/blink/web_tests/platform/fuchsia/fast/text/stroking-decorations-expected.png deleted file mode 100644 index 9c73bcd..0000000 --- a/third_party/blink/web_tests/platform/fuchsia/fast/text/stroking-decorations-expected.png +++ /dev/null Binary files differ
diff --git a/third_party/blink/web_tests/platform/fuchsia/tables/mozilla/collapsing_borders/bug41262-3-expected.png b/third_party/blink/web_tests/platform/fuchsia/tables/mozilla/collapsing_borders/bug41262-3-expected.png deleted file mode 100644 index afbd12b..0000000 --- a/third_party/blink/web_tests/platform/fuchsia/tables/mozilla/collapsing_borders/bug41262-3-expected.png +++ /dev/null Binary files differ
diff --git a/third_party/blink/web_tests/platform/fuchsia/transforms/transformed-caret-expected.png b/third_party/blink/web_tests/platform/fuchsia/transforms/transformed-caret-expected.png deleted file mode 100644 index a976df3..0000000 --- a/third_party/blink/web_tests/platform/fuchsia/transforms/transformed-caret-expected.png +++ /dev/null Binary files differ
diff --git a/third_party/blink/web_tests/paint/invalidation/scroll/repaint-during-scroll-with-zoom-expected.txt b/third_party/blink/web_tests/platform/linux/paint/invalidation/scroll/repaint-during-scroll-with-zoom-expected.txt similarity index 90% rename from third_party/blink/web_tests/paint/invalidation/scroll/repaint-during-scroll-with-zoom-expected.txt rename to third_party/blink/web_tests/platform/linux/paint/invalidation/scroll/repaint-during-scroll-with-zoom-expected.txt index eb9cab6..f40034e 100644 --- a/third_party/blink/web_tests/paint/invalidation/scroll/repaint-during-scroll-with-zoom-expected.txt +++ b/third_party/blink/web_tests/platform/linux/paint/invalidation/scroll/repaint-during-scroll-with-zoom-expected.txt
@@ -18,16 +18,16 @@ "backgroundColor": "#C0C0C0", "paintInvalidations": [ { - "object": "LayoutBlockFlow HTML", - "rect": [3, 65, 235, 235], - "reason": "paint property change" - }, - { "object": "HorizontalScrollbar", "rect": [3, 300, 235, 15], "reason": "scroll control" }, { + "object": "LayoutBlockFlow HTML", + "rect": [3, 65, 55, 17], + "reason": "chunk appeared" + }, + { "object": "VerticalScrollbar", "rect": [238, 65, 15, 235], "reason": "scroll control"
diff --git a/third_party/blink/web_tests/paint/invalidation/scroll/repaint-during-scroll-with-zoom-expected.txt b/third_party/blink/web_tests/platform/mac/paint/invalidation/scroll/repaint-during-scroll-with-zoom-expected.txt similarity index 90% copy from third_party/blink/web_tests/paint/invalidation/scroll/repaint-during-scroll-with-zoom-expected.txt copy to third_party/blink/web_tests/platform/mac/paint/invalidation/scroll/repaint-during-scroll-with-zoom-expected.txt index eb9cab6..7d04647 100644 --- a/third_party/blink/web_tests/paint/invalidation/scroll/repaint-during-scroll-with-zoom-expected.txt +++ b/third_party/blink/web_tests/platform/mac/paint/invalidation/scroll/repaint-during-scroll-with-zoom-expected.txt
@@ -18,16 +18,16 @@ "backgroundColor": "#C0C0C0", "paintInvalidations": [ { - "object": "LayoutBlockFlow HTML", - "rect": [3, 65, 235, 235], - "reason": "paint property change" - }, - { "object": "HorizontalScrollbar", "rect": [3, 300, 235, 15], "reason": "scroll control" }, { + "object": "LayoutBlockFlow HTML", + "rect": [3, 65, 58, 16], + "reason": "chunk appeared" + }, + { "object": "VerticalScrollbar", "rect": [238, 65, 15, 235], "reason": "scroll control"
diff --git a/third_party/blink/web_tests/paint/invalidation/scroll/repaint-during-scroll-with-zoom-expected.txt b/third_party/blink/web_tests/platform/win/paint/invalidation/scroll/repaint-during-scroll-with-zoom-expected.txt similarity index 90% copy from third_party/blink/web_tests/paint/invalidation/scroll/repaint-during-scroll-with-zoom-expected.txt copy to third_party/blink/web_tests/platform/win/paint/invalidation/scroll/repaint-during-scroll-with-zoom-expected.txt index eb9cab6..08178de 100644 --- a/third_party/blink/web_tests/paint/invalidation/scroll/repaint-during-scroll-with-zoom-expected.txt +++ b/third_party/blink/web_tests/platform/win/paint/invalidation/scroll/repaint-during-scroll-with-zoom-expected.txt
@@ -18,16 +18,16 @@ "backgroundColor": "#C0C0C0", "paintInvalidations": [ { - "object": "LayoutBlockFlow HTML", - "rect": [3, 65, 235, 235], - "reason": "paint property change" - }, - { "object": "HorizontalScrollbar", "rect": [3, 300, 235, 15], "reason": "scroll control" }, { + "object": "LayoutBlockFlow HTML", + "rect": [3, 65, 52, 17], + "reason": "chunk appeared" + }, + { "object": "VerticalScrollbar", "rect": [238, 65, 15, 235], "reason": "scroll control"
diff --git a/third_party/blink/web_tests/virtual/dark-mode/paint/dark-mode/page-policy-all/README.txt b/third_party/blink/web_tests/virtual/dark-mode/paint/dark-mode/page-policy-all/README.txt new file mode 100644 index 0000000..5d548a8 --- /dev/null +++ b/third_party/blink/web_tests/virtual/dark-mode/paint/dark-mode/page-policy-all/README.txt
@@ -0,0 +1,3 @@ +# This suite runs the tests in LayoutTests/paint/dark-mode +# with --blink-settings="highContrastMode=3,darkModePagePolicy=0" +# See the virtual_test_suites() method in tools/blinkpy/web_tests/port/base.py.
diff --git a/third_party/blink/web_tests/virtual/dark-mode/paint/dark-mode/page-policy-all/background-dark-color-expected.png b/third_party/blink/web_tests/virtual/dark-mode/paint/dark-mode/page-policy-all/background-dark-color-expected.png new file mode 100644 index 0000000..cbf6c45 --- /dev/null +++ b/third_party/blink/web_tests/virtual/dark-mode/paint/dark-mode/page-policy-all/background-dark-color-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/virtual/dark-mode/paint/dark-mode/page-policy-all/background-light-color-expected.png b/third_party/blink/web_tests/virtual/dark-mode/paint/dark-mode/page-policy-all/background-light-color-expected.png new file mode 100644 index 0000000..fa4f72b --- /dev/null +++ b/third_party/blink/web_tests/virtual/dark-mode/paint/dark-mode/page-policy-all/background-light-color-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/virtual/dark-mode/paint/dark-mode/page-policy-background/README.txt b/third_party/blink/web_tests/virtual/dark-mode/paint/dark-mode/page-policy-background/README.txt new file mode 100644 index 0000000..156dcb7 --- /dev/null +++ b/third_party/blink/web_tests/virtual/dark-mode/paint/dark-mode/page-policy-background/README.txt
@@ -0,0 +1,3 @@ +# This suite runs the tests in LayoutTests/paint/dark-mode +# with --blink-settings="highContrastMode=3,darkModePagePolicy=1" +# See the virtual_test_suites() method in tools/blinkpy/web_tests/port/base.py.
diff --git a/third_party/blink/web_tests/virtual/dark-mode/paint/dark-mode/page-policy-background/background-invert-expected.png b/third_party/blink/web_tests/virtual/dark-mode/paint/dark-mode/page-policy-background/background-invert-expected.png new file mode 100644 index 0000000..fa4f72b --- /dev/null +++ b/third_party/blink/web_tests/virtual/dark-mode/paint/dark-mode/page-policy-background/background-invert-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/virtual/webrtc-wpt-plan-b/external/wpt/webrtc/RTCDtlsTransport-getRemoteCertificates-expected.txt b/third_party/blink/web_tests/virtual/webrtc-wpt-plan-b/external/wpt/webrtc/RTCDtlsTransport-getRemoteCertificates-expected.txt new file mode 100644 index 0000000..81f49d68 --- /dev/null +++ b/third_party/blink/web_tests/virtual/webrtc-wpt-plan-b/external/wpt/webrtc/RTCDtlsTransport-getRemoteCertificates-expected.txt
@@ -0,0 +1,4 @@ +This is a testharness.js-based test. +FAIL RTCDtlsTransport.prototype.getRemoteCertificates assert_true: Expect pc.sctp to be set to valid RTCSctpTransport expected true got false +Harness: the test ran to completion. +
diff --git a/third_party/blink/web_tests/virtual/webrtc-wpt-plan-b/external/wpt/webrtc/RTCIceTransport-expected.txt b/third_party/blink/web_tests/virtual/webrtc-wpt-plan-b/external/wpt/webrtc/RTCIceTransport-expected.txt new file mode 100644 index 0000000..465184fe --- /dev/null +++ b/third_party/blink/web_tests/virtual/webrtc-wpt-plan-b/external/wpt/webrtc/RTCIceTransport-expected.txt
@@ -0,0 +1,5 @@ +This is a testharness.js-based test. +FAIL Two connected iceTransports should has matching local/remote candidates returned assert_true: Expect pc.sctp to be instantiated from RTCSctpTransport expected true got false +FAIL Unconnected iceTransport should have empty remote candidates and selected pair assert_true: Expect pc.sctp to be instantiated from RTCSctpTransport expected true got false +Harness: the test ran to completion. +
diff --git a/third_party/blink/web_tests/virtual/webrtc-wpt-plan-b/external/wpt/webrtc/RTCPeerConnection-connectionState-expected.txt b/third_party/blink/web_tests/virtual/webrtc-wpt-plan-b/external/wpt/webrtc/RTCPeerConnection-connectionState-expected.txt new file mode 100644 index 0000000..22eabf6c --- /dev/null +++ b/third_party/blink/web_tests/virtual/webrtc-wpt-plan-b/external/wpt/webrtc/RTCPeerConnection-connectionState-expected.txt
@@ -0,0 +1,7 @@ +This is a testharness.js-based test. +PASS Initial connectionState should be new +PASS Closing the connection should set connectionState to closed +PASS connection with one data channel should eventually have connected connection state +FAIL connection with one data channel should eventually have transports in connected state Cannot read property 'transport' of null +Harness: the test ran to completion. +
diff --git a/third_party/blink/web_tests/virtual/webrtc-wpt-plan-b/external/wpt/webrtc/RTCPeerConnection-iceConnectionState.https-expected.txt b/third_party/blink/web_tests/virtual/webrtc-wpt-plan-b/external/wpt/webrtc/RTCPeerConnection-iceConnectionState.https-expected.txt index 9e2c9a37..4eccf898 100644 --- a/third_party/blink/web_tests/virtual/webrtc-wpt-plan-b/external/wpt/webrtc/RTCPeerConnection-iceConnectionState.https-expected.txt +++ b/third_party/blink/web_tests/virtual/webrtc-wpt-plan-b/external/wpt/webrtc/RTCPeerConnection-iceConnectionState.https-expected.txt
@@ -2,7 +2,7 @@ PASS Initial iceConnectionState should be new PASS Closing the connection should set iceConnectionState to closed PASS connection with one data channel should eventually have connected or completed connection state -FAIL connection with one data channel should eventually have connected connection state Cannot read property 'transport' of undefined +FAIL connection with one data channel should eventually have connected connection state Cannot read property 'transport' of null FAIL ICE can connect in a recvonly usecase promise_test: Unhandled rejection with value: object "InvalidStateError: Failed to execute 'addTransceiver' on 'RTCPeerConnection': This operation is only supported in 'unified-plan'. 'unified-plan' will become the default behavior in the future, but it is currently experimental. To try it out, construct the RTCPeerConnection with sdpSemantics:'unified-plan' present in the RTCConfiguration argument." Harness: the test ran to completion.
diff --git a/third_party/blink/web_tests/virtual/webrtc-wpt-plan-b/external/wpt/webrtc/RTCPeerConnection-iceGatheringState-expected.txt b/third_party/blink/web_tests/virtual/webrtc-wpt-plan-b/external/wpt/webrtc/RTCPeerConnection-iceGatheringState-expected.txt new file mode 100644 index 0000000..61d27bf --- /dev/null +++ b/third_party/blink/web_tests/virtual/webrtc-wpt-plan-b/external/wpt/webrtc/RTCPeerConnection-iceGatheringState-expected.txt
@@ -0,0 +1,6 @@ +This is a testharness.js-based test. +PASS Initial iceGatheringState should be new +PASS iceGatheringState should eventually become complete after setLocalDescription +FAIL connection with one data channel should eventually have connected connection state Cannot read property 'transport' of null +Harness: the test ran to completion. +
diff --git a/third_party/blink/web_tests/virtual/webrtc-wpt-plan-b/external/wpt/webrtc/RTCSctpTransport-constructor-expected.txt b/third_party/blink/web_tests/virtual/webrtc-wpt-plan-b/external/wpt/webrtc/RTCSctpTransport-constructor-expected.txt new file mode 100644 index 0000000..cb1e2a05 --- /dev/null +++ b/third_party/blink/web_tests/virtual/webrtc-wpt-plan-b/external/wpt/webrtc/RTCSctpTransport-constructor-expected.txt
@@ -0,0 +1,5 @@ +This is a testharness.js-based test. +FAIL setRemoteDescription() with answer containing data media should initialize pc.sctp assert_not_equals: got disallowed value null +FAIL setLocalDescription() with answer containing data media should initialize pc.sctp assert_not_equals: got disallowed value null +Harness: the test ran to completion. +
diff --git a/third_party/blink/web_tests/virtual/webrtc-wpt-plan-b/external/wpt/webrtc/idlharness.https.window-expected.txt b/third_party/blink/web_tests/virtual/webrtc-wpt-plan-b/external/wpt/webrtc/idlharness.https.window-expected.txt index f366bea..def4c146 100644 --- a/third_party/blink/web_tests/virtual/webrtc-wpt-plan-b/external/wpt/webrtc/idlharness.https.window-expected.txt +++ b/third_party/blink/web_tests/virtual/webrtc-wpt-plan-b/external/wpt/webrtc/idlharness.https.window-expected.txt
@@ -1,8 +1,8 @@ This is a testharness.js-based test. -Found 494 tests; 341 PASS, 153 FAIL, 0 TIMEOUT, 0 NOTRUN. +Found 494 tests; 354 PASS, 140 FAIL, 0 TIMEOUT, 0 NOTRUN. PASS idl_test setup PASS Test driver for asyncInitCertificate -FAIL Test driver for asyncInitTransports assert_unreached: Failed to run asyncInitTransports: ReferenceError: RTCSctpTransport is not defined Reached unreachable code +FAIL Test driver for asyncInitTransports assert_unreached: Failed to run asyncInitTransports: Error: assert_true: Expect pc.sctp to be instance of RTCSctpTransport expected true got false Reached unreachable code PASS Test driver for asyncInitMediaStreamTrack PASS Partial interface RTCPeerConnection: original interface defined PASS Partial dictionary RTCOfferOptions: original dictionary defined @@ -57,7 +57,7 @@ PASS RTCPeerConnection interface: operation removeTrack(RTCRtpSender) PASS RTCPeerConnection interface: operation addTransceiver([object Object],[object Object], RTCRtpTransceiverInit) PASS RTCPeerConnection interface: attribute ontrack -FAIL RTCPeerConnection interface: attribute sctp assert_true: The prototype object must have a property "sctp" expected true got false +PASS RTCPeerConnection interface: attribute sctp PASS RTCPeerConnection interface: operation createDataChannel(USVString, RTCDataChannelInit) PASS RTCPeerConnection interface: attribute ondatachannel PASS RTCPeerConnection interface: operation getStats(MediaStreamTrack) @@ -119,7 +119,7 @@ PASS RTCPeerConnection interface: new RTCPeerConnection() must inherit property "addTransceiver([object Object],[object Object], RTCRtpTransceiverInit)" with the proper type PASS RTCPeerConnection interface: calling addTransceiver([object Object],[object Object], RTCRtpTransceiverInit) on new RTCPeerConnection() with too few arguments must throw TypeError FAIL RTCPeerConnection interface: new RTCPeerConnection() must inherit property "ontrack" with the proper type Unrecognized type EventHandler -FAIL RTCPeerConnection interface: new RTCPeerConnection() must inherit property "sctp" with the proper type assert_inherits: property "sctp" not found in prototype chain +PASS RTCPeerConnection interface: new RTCPeerConnection() must inherit property "sctp" with the proper type PASS RTCPeerConnection interface: new RTCPeerConnection() must inherit property "createDataChannel(USVString, RTCDataChannelInit)" with the proper type PASS RTCPeerConnection interface: calling createDataChannel(USVString, RTCDataChannelInit) on new RTCPeerConnection() with too few arguments must throw TypeError FAIL RTCPeerConnection interface: new RTCPeerConnection() must inherit property "ondatachannel" with the proper type Unrecognized type EventHandler @@ -372,17 +372,17 @@ FAIL RTCTrackEvent interface: initTrackEvent() must inherit property "track" with the proper type assert_equals: Unexpected exception when evaluating object expected null but got object "InvalidStateError: Failed to execute 'addTransceiver' on 'RTCPeerConnection': This operation is only supported in 'unified-plan'. 'unified-plan' will become the default behavior in the future, but it is currently experimental. To try it out, construct the RTCPeerConnection with sdpSemantics:'unified-plan' present in the RTCConfiguration argument." FAIL RTCTrackEvent interface: initTrackEvent() must inherit property "streams" with the proper type assert_equals: Unexpected exception when evaluating object expected null but got object "InvalidStateError: Failed to execute 'addTransceiver' on 'RTCPeerConnection': This operation is only supported in 'unified-plan'. 'unified-plan' will become the default behavior in the future, but it is currently experimental. To try it out, construct the RTCPeerConnection with sdpSemantics:'unified-plan' present in the RTCConfiguration argument." FAIL RTCTrackEvent interface: initTrackEvent() must inherit property "transceiver" with the proper type assert_equals: Unexpected exception when evaluating object expected null but got object "InvalidStateError: Failed to execute 'addTransceiver' on 'RTCPeerConnection': This operation is only supported in 'unified-plan'. 'unified-plan' will become the default behavior in the future, but it is currently experimental. To try it out, construct the RTCPeerConnection with sdpSemantics:'unified-plan' present in the RTCConfiguration argument." -FAIL RTCSctpTransport interface: existence and properties of interface object assert_own_property: self does not have own property "RTCSctpTransport" expected property "RTCSctpTransport" missing -FAIL RTCSctpTransport interface object length assert_own_property: self does not have own property "RTCSctpTransport" expected property "RTCSctpTransport" missing -FAIL RTCSctpTransport interface object name assert_own_property: self does not have own property "RTCSctpTransport" expected property "RTCSctpTransport" missing -FAIL RTCSctpTransport interface: existence and properties of interface prototype object assert_own_property: self does not have own property "RTCSctpTransport" expected property "RTCSctpTransport" missing -FAIL RTCSctpTransport interface: existence and properties of interface prototype object's "constructor" property assert_own_property: self does not have own property "RTCSctpTransport" expected property "RTCSctpTransport" missing -FAIL RTCSctpTransport interface: existence and properties of interface prototype object's @@unscopables property assert_own_property: self does not have own property "RTCSctpTransport" expected property "RTCSctpTransport" missing -FAIL RTCSctpTransport interface: attribute transport assert_own_property: self does not have own property "RTCSctpTransport" expected property "RTCSctpTransport" missing -FAIL RTCSctpTransport interface: attribute state assert_own_property: self does not have own property "RTCSctpTransport" expected property "RTCSctpTransport" missing -FAIL RTCSctpTransport interface: attribute maxMessageSize assert_own_property: self does not have own property "RTCSctpTransport" expected property "RTCSctpTransport" missing -FAIL RTCSctpTransport interface: attribute maxChannels assert_own_property: self does not have own property "RTCSctpTransport" expected property "RTCSctpTransport" missing -FAIL RTCSctpTransport interface: attribute onstatechange assert_own_property: self does not have own property "RTCSctpTransport" expected property "RTCSctpTransport" missing +PASS RTCSctpTransport interface: existence and properties of interface object +PASS RTCSctpTransport interface object length +PASS RTCSctpTransport interface object name +PASS RTCSctpTransport interface: existence and properties of interface prototype object +PASS RTCSctpTransport interface: existence and properties of interface prototype object's "constructor" property +PASS RTCSctpTransport interface: existence and properties of interface prototype object's @@unscopables property +PASS RTCSctpTransport interface: attribute transport +PASS RTCSctpTransport interface: attribute state +PASS RTCSctpTransport interface: attribute maxMessageSize +PASS RTCSctpTransport interface: attribute maxChannels +PASS RTCSctpTransport interface: attribute onstatechange FAIL RTCSctpTransport must be primary interface of idlTestObjects.sctpTransport assert_equals: wrong typeof object expected "object" but got "undefined" FAIL Stringification of idlTestObjects.sctpTransport assert_equals: wrong typeof object expected "object" but got "undefined" FAIL RTCSctpTransport interface: idlTestObjects.sctpTransport must inherit property "transport" with the proper type assert_equals: wrong typeof object expected "object" but got "undefined"
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 c546aef..5cc6e77 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
@@ -5733,6 +5733,7 @@ getter pendingLocalDescription getter pendingRemoteDescription getter remoteDescription + getter sctp getter signalingState method addIceCandidate method addStream @@ -5840,6 +5841,15 @@ getter stopped method constructor setter direction +interface RTCSctpTransport + attribute @@toStringTag + getter maxChannels + getter maxMessageSize + getter onstatechange + getter state + getter transport + method constructor + setter onstatechange interface RTCSessionDescription attribute @@toStringTag getter sdp @@ -10524,6 +10534,7 @@ getter orientation getter position method constructor + method inverse interface XRSession : EventTarget attribute @@toStringTag getter environmentBlendMode @@ -10648,6 +10659,7 @@ getter pendingLocalDescription getter pendingRemoteDescription getter remoteDescription + getter sctp getter signalingState method addIceCandidate method addStream
diff --git a/tools/clang/scripts/update.py b/tools/clang/scripts/update.py index 944c1eaf..8a368c2 100755 --- a/tools/clang/scripts/update.py +++ b/tools/clang/scripts/update.py
@@ -35,7 +35,7 @@ # Do NOT CHANGE this if you don't know what you're doing -- see # https://chromium.googlesource.com/chromium/src/+/master/docs/updating_clang.md # Reverting problematic clang rolls is safe, though. -CLANG_REVISION = '355581' +CLANG_REVISION = '356356' use_head_revision = bool(os.environ.get('LLVM_FORCE_HEAD_REVISION', '0') in ('1', 'YES'))
diff --git a/tools/cygprofile/orderfile_generator_backend.py b/tools/cygprofile/orderfile_generator_backend.py index 412fd7e..86658f12 100755 --- a/tools/cygprofile/orderfile_generator_backend.py +++ b/tools/cygprofile/orderfile_generator_backend.py
@@ -859,7 +859,7 @@ _StashOutputDirectory(self._uninstrumented_out_dir) orderfile_uploaded = True - if self._options._new_commit_flow: + if self._options.new_commit_flow: self._orderfile_updater._GitStash() else: if (self._options.buildbot and self._options.netrc @@ -1000,7 +1000,7 @@ if options.verify: generator._VerifySymbolOrder() elif options.commit_hashes: - if not options._new_commit_flow: + if not options.new_commit_flow: raise Exception('--commit-hashes requries --new-commit-flow') return generator.CommitStashedOrderfileHashes() elif options.upload_ready_orderfiles:
diff --git a/tools/mb/mb.py b/tools/mb/mb.py index 64d0845..056e8fb 100755 --- a/tools/mb/mb.py +++ b/tools/mb/mb.py
@@ -1169,7 +1169,10 @@ '--output-dir', '${ISOLATED_OUTDIR}', '--timeout', '3600'] elif is_android and test_type != "script": - cmdline = [ + cmdline = [] + if asan: + cmdline += [os.path.join('bin', 'run_with_asan')] + cmdline += [ '../../testing/test_env.py', '../../build/android/test_wrapper/logdog_wrapper.py', '--target', target,
diff --git a/tools/metrics/actions/actions.xml b/tools/metrics/actions/actions.xml index e3b75af..b529c498 100644 --- a/tools/metrics/actions/actions.xml +++ b/tools/metrics/actions/actions.xml
@@ -10000,6 +10000,12 @@ </description> </action> +<action name="LinkOpenedInNewTab"> + <owner>yusufo@chromium.org</owner> + <owner>wychen@chromium.org</owner> + <description>Users long pressed and opened in new tab.</description> +</action> + <action name="LoadURL"> <owner>Please list the metric's owners. Add more owner tags as needed.</owner> <description>Please enter the description of this user action.</description> @@ -12541,11 +12547,9 @@ </action> <action name="MobileTabReturnedToCurrentTab"> - <owner>rlanday@chromium.org</owner> - <description> - User in the Android tab switcher returned to the tab that was active when - the tab switcher was opened. - </description> + <owner>yusufo@chromium.org</owner> + <owner>wychen@chromium.org</owner> + <description>Users returned to the tab that was active.</description> </action> <action name="MobileTabStripCloseTab"> @@ -16322,6 +16326,14 @@ </description> </action> +<action name="PWAInstallIcon"> + <owner>alancutter@chromium.org</owner> + <description> + The plus icon shown in the omnibox when a site has passed the browser's PWA + promotability checks. + </description> +</action> + <action name="Redo"> <owner>Please list the metric's owners. Add more owner tags as needed.</owner> <description>Please enter the description of this user action.</description> @@ -20217,6 +20229,30 @@ <description>Please enter the description of this user action.</description> </action> +<action name="TabGroup.Created"> + <owner>yusufo@chromium.org</owner> + <owner>wychen@chromium.org</owner> + <description>Users created a new tab group.</description> +</action> + +<action name="TabGroup.ExpandedFromStrip"> + <owner>yusufo@chromium.org</owner> + <owner>wychen@chromium.org</owner> + <description> + Users tapped "^" button on the tab strip, causing tab group bottom + sheet to be shown. + </description> +</action> + +<action name="TabGroup.MinimizedFromGrid"> + <owner>yusufo@chromium.org</owner> + <owner>wychen@chromium.org</owner> + <description> + Users tapped "v" button on tab group bottom sheet toolbar, causing + tab group bottom sheet to be hidden. + </description> +</action> + <action name="Tablet.WindowDrag.OpenedOverview"> <owner>minch@chromium.org</owner> <description> @@ -21562,4 +21598,57 @@ <affected-action name="Accessibility.Autoclick"/> </action-suffix> +<action-suffix separator="." ordering="suffix"> + <suffix name="DeveloperRequestedNewTab" + label="Users tapped on a link with a target=_blank"/> + <suffix name="OpenInNewTab" + label="Users long pressed a link and opened in new tab."/> + <suffix name="TabSwitcher" + label="Users tapped the 'Create group' button in TabSwitcher."/> + <affected-action name="TabGroup.Created"/> +</action-suffix> + +<action-suffix separator="." ordering="suffix"> + <suffix name="GridTabSwitcher" + label="Users switched tabs from the grid layout TabSwitcher."/> + <suffix name="TabGridSheet" + label="Users switched tabs from the tab group in the bottom sheet + switcher."/> + <suffix name="TabStrip" label="Users switched tabs from the tab strip."/> + <affected-action name="MobileTabSwitched"/> +</action-suffix> + +<action-suffix separator="." ordering="suffix"> + <suffix name="TabGridSheet" + label="Users tapped '+' button on the tab group bottom sheet toolbar + causes a new tab to be created in the group."/> + <suffix name="TabStrip" + label="Users tapped '+' button on the tab strip, causing a new tab to + be created in the group."/> + <affected-action name="MobileNewTabOpened"/> +</action-suffix> + +<action-suffix separator="." ordering="suffix"> + <suffix name="GridTabSwitcher" + label="Users tapped 'x' button on the tab in grid layout TabSwitcher, + causing a tab to be closed."/> + <suffix name="TabGridSheet" + label="Users tapped 'x' button on the tab in tab group bottom sheet, + causing a tab to be closed in the group."/> + <suffix name="TabStrip" + label="Users tapped the currently selected tab's favicon on the tab + strip, causing a tab to be closed in the group."/> + <affected-action name="MobileTabClosed"/> +</action-suffix> + +<action-suffix separator="." ordering="suffix"> + <suffix name="GridTabSwitcher" + label="Users tapped the currently selected tab in grid layout + TabSwitcher."/> + <suffix name="TabGridSheet" + label="Users tapped the currently selected tab in tab group bottom + sheet."/> + <affected-action name="MobileTabReturnedToCurrentTab"/> +</action-suffix> + </actions>
diff --git a/tools/metrics/histograms/enums.xml b/tools/metrics/histograms/enums.xml index 55a9ba70..0c84c10f 100644 --- a/tools/metrics/histograms/enums.xml +++ b/tools/metrics/histograms/enums.xml
@@ -1710,8 +1710,10 @@ <int value="0" label="MOVE_INTO_FOLDER"/> <int value="1" label="MOVE_OUT_OF_FOLDER"/> <int value="2" label="MOVE_INTO_ANOTHER_FOLDER"/> - <int value="3" label="REORDER_IN_FOLDER"/> - <int value="4" label="REORDER_IN_TOP_LEVEL"/> + <int value="3" label="REORDER_BY_DRAG_IN_FOLDER"/> + <int value="4" label="REORDER_BY_DRAG_IN_TOP_LEVEL"/> + <int value="5" label="REORDER_BY_KEYBOARD_IN_FOLDER"/> + <int value="6" label="REORDER_BY_KEYBOARD_IN_TOP_LEVEL"/> </enum> <enum name="AppListAppType"> @@ -20700,7 +20702,7 @@ <int value="1352" label="CSSValueAppearanceNotNone"/> <int value="1353" label="CSSValueAppearanceOthers"/> <int value="1354" label="CSSValueAppearanceButton"/> - <int value="1355" label="CSSValueAppearanceCaret"/> + <int value="1355" label="OBSOLETE_CSSValueAppearanceCaret"/> <int value="1356" label="CSSValueAppearanceCheckbox"/> <int value="1357" label="CSSValueAppearanceMenulist"/> <int value="1358" label="CSSValueAppearanceMenulistButton"/> @@ -22198,23 +22200,28 @@ <int value="2793" label="AnimationFrameCancelledWithinFrame"/> <int value="2794" label="SchedulingIsInputPending"/> <int value="2795" label="V8StringNormalize"/> - <int value="2796" label="CSSValueAppearanceButtonBevel"/> - <int value="2797" label="CSSValueAppearanceListitem"/> - <int value="2798" label="CSSValueAppearanceMediaControlsBackground"/> + <int value="2796" label="OBSOLETE_CSSValueAppearanceButtonBevel"/> + <int value="2797" label="OBSOLETE_CSSValueAppearanceListitem"/> + <int value="2798" label="OBSOLETE_CSSValueAppearanceMediaControlsBackground"/> <int value="2799" - label="CSSValueAppearanceMediaControlsFullscreenBackground"/> - <int value="2800" label="CSSValueAppearanceMediaCurrentTimeDisplay"/> - <int value="2801" label="CSSValueAppearanceMediaEnterFullscreenButton"/> - <int value="2802" label="CSSValueAppearanceMediaExitFullscreenButton"/> - <int value="2803" label="CSSValueAppearanceMediaMuteButton"/> - <int value="2804" label="CSSValueAppearanceMediaOverlayPlayButton"/> - <int value="2805" label="CSSValueAppearanceMediaPlayButton"/> - <int value="2806" label="CSSValueAppearanceMediaTimeRemainingDisplay"/> - <int value="2807" label="CSSValueAppearanceMediaToggleClosedCaptionsButton"/> - <int value="2808" label="CSSValueAppearanceMediaVolumeSliderContainer"/> - <int value="2809" label="CSSValueAppearanceMenulistTextfield"/> - <int value="2810" label="CSSValueAppearanceMenulistText"/> - <int value="2811" label="CSSValueAppearanceProgressBarValue"/> + label="OBSOLETE_CSSValueAppearanceMediaControlsFullscreenBackground"/> + <int value="2800" label="OBSOLETE_CSSValueAppearanceMediaCurrentTimeDisplay"/> + <int value="2801" + label="OBSOLETE_CSSValueAppearanceMediaEnterFullscreenButton"/> + <int value="2802" + label="OBSOLETE_CSSValueAppearanceMediaExitFullscreenButton"/> + <int value="2803" label="OBSOLETE_CSSValueAppearanceMediaMuteButton"/> + <int value="2804" label="OBSOLETE_CSSValueAppearanceMediaOverlayPlayButton"/> + <int value="2805" label="OBSOLETE_CSSValueAppearanceMediaPlayButton"/> + <int value="2806" + label="OBSOLETE_CSSValueAppearanceMediaTimeRemainingDisplay"/> + <int value="2807" + label="OBSOLETE_CSSValueAppearanceMediaToggleClosedCaptionsButton"/> + <int value="2808" + label="OBSOLETE_CSSValueAppearanceMediaVolumeSliderContainer"/> + <int value="2809" label="OBSOLETE_CSSValueAppearanceMenulistTextfield"/> + <int value="2810" label="OBSOLETE_CSSValueAppearanceMenulistText"/> + <int value="2811" label="OBSOLETE_CSSValueAppearanceProgressBarValue"/> <int value="2812" label="U2FCryptotokenRegister"/> <int value="2813" label="U2FCryptotokenSign"/> <int value="2814" label="CSSValueAppearanceInnerSpinButton"/> @@ -22236,6 +22243,7 @@ <int value="2830" label="CSSSelectorHostContextInLiveProfile"/> <int value="2831" label="ImportMap"/> <int value="2832" label="RefreshHeader"/> + <int value="2833" label="SearchEventFired"/> </enum> <enum name="FeaturePolicyFeature"> @@ -32940,6 +32948,8 @@ <int value="283232244" label="OmniboxUIExperimentNarrowDropdown:enabled"/> <int value="287932297" label="AutofillSettingsCardTypeSplit:enabled"/> <int value="288012253" label="CrostiniFiles:enabled"/> + <int value="288755982" + label="AutofillEnableLocalCardMigrationForNonSyncUser:enabled"/> <int value="292560715" label="ViewsCastDialog:disabled"/> <int value="293134455" label="AutofillSendBillingCustomerNumber:disabled"/> <int value="293996306" label="ArrayPrototypeValues:disabled"/> @@ -33999,6 +34009,8 @@ <int value="1989877708" label="PostScriptPrinting:enabled"/> <int value="1990562608" label="LinkManagedNoticeToChromeUIManagementURL:enabled"/> + <int value="1990670943" + label="AutofillEnableLocalCardMigrationForNonSyncUser:disabled"/> <int value="1991771852" label="LeftToRightUrls:enabled"/> <int value="1991912338" label="ModuleScriptsDynamicImport:enabled"/> <int value="1992466116" label="enable-passive-event-listeners-due-to-fling"/> @@ -34682,6 +34694,9 @@ </enum> <enum name="MainFrameDownloadSandboxGesture"> + <obsolete> + Deprecated as of 03/2019. + </obsolete> <summary> For a download that occurs in top frame, record whether the frame is sandboxed and whether the download involves a transient user gesture. It is @@ -46819,7 +46834,7 @@ <int value="8" label="FileThread"/> <int value="9" label="DatabaseThread"/> <int value="10" label="WebAudioThread"/> - <int value="11" label="ScriptStreamerThread (obsolete)"/> + <int value="11" label="ScriptStreamerThread"/> <int value="12" label="OfflineAudioRenderThread"/> <int value="13" label="ReverbConvolutionBackgroundThread"/> <int value="14" label="HRTFDatabaseLoaderThread"/> @@ -51843,6 +51858,9 @@ </enum> <enum name="SubframeDownloadSandboxOriginAdGesture"> + <obsolete> + Deprecated as of 03/2019. + </obsolete> <summary> For a download that occurs in subframe, record whether the frame is sandboxed, whether the origin is same to the top frame, whether it's an ad @@ -56549,6 +56567,7 @@ <int value="5" label="WebContentsDestroyed"/> <int value="6" label="WriteDataFailed"/> <int value="7" label="UserInstallDeclined"/> + <int value="8" label="InstallManagerDestroyed"/> </enum> <enum name="WebAppInstallSource"> @@ -56974,6 +56993,7 @@ <enum name="WebRtcLoggingWebAppIdHash"> <int value="-100222544" label="Hangouts"/> <int value="0" label="Undefined"/> + <int value="2102772693" label="Duo"/> </enum> <enum name="WebRtcNativeRate">
diff --git a/tools/metrics/histograms/histograms.xml b/tools/metrics/histograms/histograms.xml index 0bf7bbc4..5ff7626d 100644 --- a/tools/metrics/histograms/histograms.xml +++ b/tools/metrics/histograms/histograms.xml
@@ -26401,6 +26401,9 @@ <histogram name="Download.MainFrame.SandboxGesture" enum="MainFrameDownloadSandboxGesture"> + <obsolete> + Deprecated as of 03/2019. + </obsolete> <owner>yaoxia@chromium.org</owner> <summary> For a download that occurs in top frame, record whether the frame is @@ -27113,6 +27116,9 @@ <histogram name="Download.Subframe.SandboxOriginAdGesture" enum="SubframeDownloadSandboxOriginAdGesture"> + <obsolete> + Deprecated as of 03/2019. + </obsolete> <owner>yaoxia@chromium.org</owner> <summary> For a download that occurs in subframe, record whether the frame is @@ -43368,7 +43374,7 @@ </histogram> <histogram name="InputMethod.Mojo.Extension.ActivateIMELatency" units="ms" - expires_after="2019-03-31"> + expires_after="2019-06-30"> <owner>googleo@chromium.org</owner> <owner>shuchen@chromium.org</owner> <summary> @@ -43386,7 +43392,7 @@ </histogram> <histogram name="InputMethod.Mojo.Extension.Rulebased.ProcessLatency" - units="ms" expires_after="2019-03-31"> + units="ms" expires_after="2019-06-30"> <owner>googleo@chromium.org</owner> <owner>shuchen@chromium.org</owner> <summary> @@ -43396,7 +43402,7 @@ </histogram> <histogram name="InputMethod.Mojo.Extension.ServiceInitLatency" units="ms" - expires_after="2019-03-31"> + expires_after="2019-06-30"> <owner>googleo@chromium.org</owner> <owner>shuchen@chromium.org</owner> <summary> @@ -54224,6 +54230,23 @@ <histogram name="Memory.NativeLibrary.MappedAndResidentMemoryFootprint" units="KB" expires_after="2019-07-01"> + <obsolete> + Deprecated 03/2019. Replaced by + Memory.NativeLibrary.MappedAndResidentMemoryFootprint2 to add more precision + to buckets. + </obsolete> + <owner>msalama@google.com</owner> + <owner>lizeb@chromium.org</owner> + <summary> + The size of the resident memory for the native library code across all + processes. This metric is computed by parsing proc/self/pagemap and counting + native library pages that are mapped and present in RAM for at least one + Chrome process. Recorded once per UMA ping. Available only on Android. + </summary> +</histogram> + +<histogram name="Memory.NativeLibrary.MappedAndResidentMemoryFootprint2" + units="KB" expires_after="2019-10-01"> <owner>msalama@google.com</owner> <owner>lizeb@chromium.org</owner> <summary> @@ -80558,7 +80581,7 @@ </histogram> <histogram - name="PageLoad.Experimental.PaintTiming.NavigationToLargestContentPaintAllFrames" + name="PageLoad.Experimental.PaintTiming.NavigationToLargestContentPaint.AllFrames" units="ms" expires_after="2019-04-23"> <owner>maxlg@chromium.org</owner> <owner>speed-metrics-dev@chromium.org</owner> @@ -121491,7 +121514,7 @@ </details> </histogram> -<histogram name="Tabs.TabOffsetOfSwitch"> +<histogram base="true" name="Tabs.TabOffsetOfSwitch"> <owner>yusufo@chromium.org</owner> <summary> How many tabs a user moved forward or backward in the Android tab switcher. @@ -123553,6 +123576,16 @@ </summary> </histogram> +<histogram name="UKM.MigratedClientIdInt64ToUInt64" enum="BooleanMigrated" + expires_after="M77"> + <owner>jwd@chromium.org</owner> + <summary> + The client id was migrated from an Int64 pref to a UInt64 pref. Not migrated + is recorded when a valid UInt64 value is loaded from prefs. Migration + started in M75. + </summary> +</histogram> + <histogram name="UKM.PersistentLogRecall.Status" enum="PersistedLogsLogReadStatus"> <owner>holte@chromium.org</owner> @@ -145377,7 +145410,11 @@ Incognito (used for DesktopMenu)"/> <suffix name="GAIAReAuth" label="GAIA-initiated interaction indicating a service type of - Reauthenticate this user"/> + Reauthenticate this user"> + <obsolete> + Deprecated 3/2019. + </obsolete> + </suffix> <suffix name="GAIASignout" label="GAIA-initiated interaction indicating a service type of Signout"/> <suffix name="GAIASignoutIncognito" @@ -148246,6 +148283,14 @@ <affected-histogram name="Tab.NewTabOnload"/> </histogram_suffixes> +<histogram_suffixes name="TabOffsetOfSwitchComponentList" separator="."> + <suffix name="GridTabSwitcher" label="Tab switcher in grid layout"/> + <suffix name="TabGridSheet" + label="The bottom sheet that show a list of Tabs in a grid"/> + <suffix name="TabStrip" label="The TabStrip componets"/> + <affected-histogram name="Tabs.TabOffsetOfSwitch"/> +</histogram_suffixes> + <histogram_suffixes name="Tabs.SwitchLatency" separator="_"> <suffix name="Actual" label="The time it takes to show a real live frame from the renderer on
diff --git a/tools/metrics/ukm/ukm.xml b/tools/metrics/ukm/ukm.xml index ea7fe75e..3d210c7 100644 --- a/tools/metrics/ukm/ukm.xml +++ b/tools/metrics/ukm/ukm.xml
@@ -2287,6 +2287,9 @@ </event> <event name="MainFrameDownload"> + <obsolete> + Deprecated as of 03/2019. + </obsolete> <owner>yaoxia@chromium.org</owner> <summary> Measurement for top frame download. It is only recorded for downloads @@ -5369,6 +5372,9 @@ </event> <event name="SubframeDownload"> + <obsolete> + Deprecated as of 03/2019. + </obsolete> <owner>yaoxia@chromium.org</owner> <summary> Measurement for subframe download. It is only recorded for downloads
diff --git a/tools/perf/benchmarks/smoothness.py b/tools/perf/benchmarks/smoothness.py index 179382b..c4a6c3e 100644 --- a/tools/perf/benchmarks/smoothness.py +++ b/tools/perf/benchmarks/smoothness.py
@@ -21,7 +21,10 @@ def CreateCoreTimelineBasedMeasurementOptions(self): category_filter = chrome_trace_category_filter.CreateLowOverheadFilter() options = timeline_based_measurement.Options(category_filter) - options.SetTimelineBasedMetrics(['renderingMetric']) + options.config.chrome_trace_config.EnableUMAHistograms( + 'Event.Latency.ScrollBegin.Touch.TimeToScrollUpdateSwapBegin4', + 'Event.Latency.ScrollUpdate.Touch.TimeToScrollUpdateSwapBegin4') + options.SetTimelineBasedMetrics(['renderingMetric', 'umaMetric']) return options
diff --git a/tools/perf/contrib/cluster_telemetry/rendering_ct.py b/tools/perf/contrib/cluster_telemetry/rendering_ct.py index 35c33ba8..e0b2670 100644 --- a/tools/perf/contrib/cluster_telemetry/rendering_ct.py +++ b/tools/perf/contrib/cluster_telemetry/rendering_ct.py
@@ -40,5 +40,8 @@ def CreateCoreTimelineBasedMeasurementOptions(self): category_filter = chrome_trace_category_filter.CreateLowOverheadFilter() options = timeline_based_measurement.Options(category_filter) - options.SetTimelineBasedMetrics(['renderingMetric']) + options.config.chrome_trace_config.EnableUMAHistograms( + 'Event.Latency.ScrollBegin.Touch.TimeToScrollUpdateSwapBegin4', + 'Event.Latency.ScrollUpdate.Touch.TimeToScrollUpdateSwapBegin4') + options.SetTimelineBasedMetrics(['renderingMetric', 'umaMetric']) return options
diff --git a/tools/perf/contrib/cluster_telemetry/repaint.py b/tools/perf/contrib/cluster_telemetry/repaint.py index ed88aa6..97f9133 100644 --- a/tools/perf/contrib/cluster_telemetry/repaint.py +++ b/tools/perf/contrib/cluster_telemetry/repaint.py
@@ -44,5 +44,8 @@ def CreateCoreTimelineBasedMeasurementOptions(self): category_filter = chrome_trace_category_filter.CreateLowOverheadFilter() options = timeline_based_measurement.Options(category_filter) - options.SetTimelineBasedMetrics(['renderingMetric']) + options.config.chrome_trace_config.EnableUMAHistograms( + 'Event.Latency.ScrollBegin.Touch.TimeToScrollUpdateSwapBegin4', + 'Event.Latency.ScrollUpdate.Touch.TimeToScrollUpdateSwapBegin4') + options.SetTimelineBasedMetrics(['renderingMetric', 'umaMetric']) return options
diff --git a/tools/perf/contrib/cros_benchmarks/ui_smoothness_bench.py b/tools/perf/contrib/cros_benchmarks/ui_smoothness_bench.py index 8838cbc..707f20db 100644 --- a/tools/perf/contrib/cros_benchmarks/ui_smoothness_bench.py +++ b/tools/perf/contrib/cros_benchmarks/ui_smoothness_bench.py
@@ -22,5 +22,8 @@ def CreateCoreTimelineBasedMeasurementOptions(self): category_filter = chrome_trace_category_filter.CreateLowOverheadFilter() options = timeline_based_measurement.Options(category_filter) - options.SetTimelineBasedMetrics(['renderingMetric']) + options.config.chrome_trace_config.EnableUMAHistograms( + 'Event.Latency.ScrollBegin.Touch.TimeToScrollUpdateSwapBegin4', + 'Event.Latency.ScrollUpdate.Touch.TimeToScrollUpdateSwapBegin4') + options.SetTimelineBasedMetrics(['renderingMetric', 'umaMetric']) return options
diff --git a/tools/perf/contrib/vr_benchmarks/vr_benchmarks.py b/tools/perf/contrib/vr_benchmarks/vr_benchmarks.py index ae56555..a68ba9c7 100644 --- a/tools/perf/contrib/vr_benchmarks/vr_benchmarks.py +++ b/tools/perf/contrib/vr_benchmarks/vr_benchmarks.py
@@ -249,7 +249,10 @@ def CreateCoreTimelineBasedMeasurementOptions(self): category_filter = chrome_trace_category_filter.CreateLowOverheadFilter() options = timeline_based_measurement.Options(category_filter) - options.SetTimelineBasedMetrics(['renderingMetric']) + options.config.chrome_trace_config.EnableUMAHistograms( + 'Event.Latency.ScrollBegin.Touch.TimeToScrollUpdateSwapBegin4', + 'Event.Latency.ScrollUpdate.Touch.TimeToScrollUpdateSwapBegin4') + options.SetTimelineBasedMetrics(['renderingMetric', 'umaMetric']) return options def CreateStorySet(self, options):
diff --git a/tools/perf/core/perf_data_generator.py b/tools/perf/core/perf_data_generator.py index 25e771bd..6474ea5 100755 --- a/tools/perf/core/perf_data_generator.py +++ b/tools/perf/core/perf_data_generator.py
@@ -429,7 +429,9 @@ 'isolate': 'performance_test_suite', 'num_shards': 26, 'extra_args': [ - '--run-ref-build', + # Temporarily disable reference builds on + # Mac to mitigate crbug.com/940075 + #'--run-ref-build', ('--test-shard-map-filename=' 'mac-10_12_laptop_low_end-perf_map.json'), '--assert-gpu-compositing', @@ -508,7 +510,9 @@ { 'isolate': 'performance_test_suite', 'extra_args': [ - '--run-ref-build', + # Temporarily disable reference builds on + # Mac to mitigate crbug.com/940075 + #'--run-ref-build', '--test-shard-map-filename=mac-10_13_laptop_high_end-perf_map.json', '--assert-gpu-compositing', ],
diff --git a/tools/perf/page_sets/rendering/rendering_stories.py b/tools/perf/page_sets/rendering/rendering_stories.py index eb64475..9cd818e 100644 --- a/tools/perf/page_sets/rendering/rendering_stories.py +++ b/tools/perf/page_sets/rendering/rendering_stories.py
@@ -63,17 +63,6 @@ if (platform == platforms.MOBILE and story_class.TAGS and - story_tags.GPU_RASTERIZATION in story_class.TAGS): - self.AddStory(story_class( - page_set=self, - shared_page_state_class=shared_page_state_class, - name_suffix='_desktop_gpu_raster', - extra_browser_args=required_args + [ - '--force-gpu-rasterization', - ])) - - if (platform == platforms.MOBILE and - story_class.TAGS and story_tags.IMAGE_DECODING in story_class.TAGS): self.AddStory(story_class( page_set=self,
diff --git a/ui/accessibility/platform/ax_platform_node_auralinux.cc b/ui/accessibility/platform/ax_platform_node_auralinux.cc index 2a95a27..50e973e7 100644 --- a/ui/accessibility/platform/ax_platform_node_auralinux.cc +++ b/ui/accessibility/platform/ax_platform_node_auralinux.cc
@@ -1571,9 +1571,9 @@ return nullptr; } -static const gchar* BuildDescriptionFromHeaders( +static const char* BuildDescriptionFromHeaders( AXPlatformNodeDelegate* delegate, - std::vector<int32_t>& ids) { + const std::vector<int32_t>& ids) { std::vector<std::string> names; for (const auto& node_id : ids) { if (AXPlatformNode* header = delegate->GetFromNodeID(node_id)) { @@ -3081,7 +3081,7 @@ } void AXPlatformNodeAuraLinux::UpdateHypertext() { - hypertext_ = ComputeHypertext(); + UpdateComputedHypertext(); text_unicode_adjustments_ = base::nullopt; }
diff --git a/ui/accessibility/platform/ax_platform_node_auralinux.h b/ui/accessibility/platform/ax_platform_node_auralinux.h index fb9125c..b67dfbe3 100644 --- a/ui/accessibility/platform/ax_platform_node_auralinux.h +++ b/ui/accessibility/platform/ax_platform_node_auralinux.h
@@ -115,8 +115,6 @@ void SetEmbeddingWindow(AtkObject* new_embedding_window); protected: - AXHypertext hypertext_; - // Offsets for the AtkText API are calculated in UTF-16 code point offsets, // but the ATK APIs want all offsets to be in "characters," which we // understand to be Unicode character offsets. We keep a lazily generated set
diff --git a/ui/accessibility/platform/ax_platform_node_base.cc b/ui/accessibility/platform/ax_platform_node_base.cc index ecefd97..577bf26 100644 --- a/ui/accessibility/platform/ax_platform_node_base.cc +++ b/ui/accessibility/platform/ax_platform_node_base.cc
@@ -1062,16 +1062,16 @@ AddAttributeToList(name, value.c_str(), attributes); } -AXHypertext::AXHypertext() {} +AXHypertext::AXHypertext() = default; AXHypertext::AXHypertext(const AXHypertext& other) = default; -AXHypertext::~AXHypertext() {} +AXHypertext::~AXHypertext() = default; -AXHypertext AXPlatformNodeBase::ComputeHypertext() { - AXHypertext result; +void AXPlatformNodeBase::UpdateComputedHypertext() { + hypertext_ = AXHypertext(); if (IsPlainTextField()) { - result.hypertext = GetValue(); - return result; + hypertext_.hypertext = GetValue(); + return; } int child_count = delegate_->GetChildCount(); @@ -1079,10 +1079,11 @@ if (!child_count) { if (IsRichTextField()) { // We don't want to expose any associated label in IA2 Hypertext. - return result; + return; } - result.hypertext = GetString16Attribute(ax::mojom::StringAttribute::kName); - return result; + hypertext_.hypertext = + GetString16Attribute(ax::mojom::StringAttribute::kName); + return; } // Construct the hypertext for this node, which contains the concatenation @@ -1097,19 +1098,17 @@ DCHECK(child); // Similar to Firefox, we don't expose text-only objects in IA2 hypertext. if (child->IsTextOnlyObject()) { - hypertext += + hypertext_.hypertext += child->GetString16Attribute(ax::mojom::StringAttribute::kName); } else { - int32_t char_offset = static_cast<int32_t>(hypertext.size()); + int32_t char_offset = static_cast<int32_t>(hypertext_.hypertext.size()); int32_t child_unique_id = child->GetUniqueId(); - int32_t index = static_cast<int32_t>(result.hyperlinks.size()); - result.hyperlink_offset_to_index[char_offset] = index; - result.hyperlinks.push_back(child_unique_id); - hypertext += kEmbeddedCharacter; + int32_t index = static_cast<int32_t>(hypertext_.hyperlinks.size()); + hypertext_.hyperlink_offset_to_index[char_offset] = index; + hypertext_.hyperlinks.push_back(child_unique_id); + hypertext_.hypertext += kEmbeddedCharacter; } } - result.hypertext = hypertext; - return result; } void AXPlatformNodeBase::AddAttributeToList(const char* name,
diff --git a/ui/accessibility/platform/ax_platform_node_base.h b/ui/accessibility/platform/ax_platform_node_base.h index fde6dc0..3ac7e189 100644 --- a/ui/accessibility/platform/ax_platform_node_base.h +++ b/ui/accessibility/platform/ax_platform_node_base.h
@@ -305,11 +305,13 @@ // Compute the hypertext for this node to be exposed via IA2 and ATK This // method is responsible for properly embedding children using the special // embedded element character. - AXHypertext ComputeHypertext(); + void UpdateComputedHypertext(); int32_t GetPosInSet() const; int32_t GetSetSize() const; + AXHypertext hypertext_; + private: DISALLOW_COPY_AND_ASSIGN(AXPlatformNodeBase); };
diff --git a/ui/accessibility/platform/ax_platform_node_win.h b/ui/accessibility/platform/ax_platform_node_win.h index 4c62904c..408cd723 100644 --- a/ui/accessibility/platform/ax_platform_node_win.h +++ b/ui/accessibility/platform/ax_platform_node_win.h
@@ -929,7 +929,6 @@ std::vector<Microsoft::WRL::ComPtr<AXPlatformRelationWin>> relations_; AXHypertext old_hypertext_; - AXHypertext hypertext_; // These protected methods are still used by BrowserAccessibilityComWin. At // some point post conversion, we can probably move these to be private
diff --git a/ui/android/java/src/org/chromium/ui/PhotoPickerListener.java b/ui/android/java/src/org/chromium/ui/PhotoPickerListener.java index 7dbc7d849..d6e8d90 100644 --- a/ui/android/java/src/org/chromium/ui/PhotoPickerListener.java +++ b/ui/android/java/src/org/chromium/ui/PhotoPickerListener.java
@@ -4,6 +4,7 @@ package org.chromium.ui; +import android.net.Uri; import android.support.annotation.IntDef; import java.lang.annotation.Retention; @@ -38,5 +39,5 @@ * * @param photos The photos that were selected. */ - void onPhotoPickerUserAction(@PhotoPickerAction int action, String[] photos); + void onPhotoPickerUserAction(@PhotoPickerAction int action, Uri[] photos); }
diff --git a/ui/android/java/src/org/chromium/ui/base/SelectFileDialog.java b/ui/android/java/src/org/chromium/ui/base/SelectFileDialog.java index 1c773bb..ed3466cf 100644 --- a/ui/android/java/src/org/chromium/ui/base/SelectFileDialog.java +++ b/ui/android/java/src/org/chromium/ui/base/SelectFileDialog.java
@@ -376,7 +376,7 @@ } @Override - public void onPhotoPickerUserAction(@PhotoPickerAction int action, String[] photos) { + public void onPhotoPickerUserAction(@PhotoPickerAction int action, Uri[] photos) { switch (action) { case PhotoPickerAction.CANCEL: onFileNotSelected(); @@ -388,21 +388,9 @@ return; } - if (photos.length == 1) { - GetDisplayNameTask task = - new GetDisplayNameTask(ContextUtils.getApplicationContext(), false, - new Uri[] {Uri.parse(photos[0])}); - task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); - return; - } else { - Uri[] filePathArray = new Uri[photos.length]; - for (int i = 0; i < photos.length; ++i) { - filePathArray[i] = Uri.parse(photos[i]); - } - GetDisplayNameTask task = new GetDisplayNameTask( - ContextUtils.getApplicationContext(), true, filePathArray); - task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); - } + GetDisplayNameTask task = new GetDisplayNameTask( + ContextUtils.getApplicationContext(), photos.length > 1, photos); + task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); break; case PhotoPickerAction.LAUNCH_GALLERY:
diff --git a/ui/aura/env.cc b/ui/aura/env.cc index 2f77b00..81a4212 100644 --- a/ui/aura/env.cc +++ b/ui/aura/env.cc
@@ -248,9 +248,15 @@ void Env::PauseWindowOcclusionTracking() { switch (mode_) { - case Mode::LOCAL: + case Mode::LOCAL: { + const bool was_paused = GetWindowOcclusionTracker(); GetWindowOcclusionTracker()->Pause(); + if (!was_paused) { + for (EnvObserver& observer : observers_) + observer.OnWindowOcclusionTrackingPaused(); + } break; + } case Mode::MUS: // |window_tree_client_| could be null in tests. // e.g. WindowTreeClientDestructionTest.* @@ -264,6 +270,10 @@ switch (mode_) { case Mode::LOCAL: GetWindowOcclusionTracker()->Unpause(); + if (!GetWindowOcclusionTracker()->IsPaused()) { + for (EnvObserver& observer : observers_) + observer.OnWindowOcclusionTrackingResumed(); + } break; case Mode::MUS: // |window_tree_client_| could be null in tests.
diff --git a/ui/aura/env_observer.h b/ui/aura/env_observer.h index 79c21d9..dcb3080 100644 --- a/ui/aura/env_observer.h +++ b/ui/aura/env_observer.h
@@ -15,14 +15,19 @@ class AURA_EXPORT EnvObserver { public: // Called when |window| has been initialized. - virtual void OnWindowInitialized(Window* window) = 0; + virtual void OnWindowInitialized(Window* window) {} - // Called when a WindowTreeHost is initialized. + // Called when a WindowTreeHost is initialized. virtual void OnHostInitialized(WindowTreeHost* host) {} // Called right before Env is destroyed. virtual void OnWillDestroyEnv() {} + // Called when occlusion tracker pauses/resumes. This is only called in + // Mode::LOCAL. + virtual void OnWindowOcclusionTrackingPaused() {} + virtual void OnWindowOcclusionTrackingResumed() {} + protected: virtual ~EnvObserver() {} };
diff --git a/ui/aura/mus/focus_synchronizer.cc b/ui/aura/mus/focus_synchronizer.cc index c797024..8d2e9cc 100644 --- a/ui/aura/mus/focus_synchronizer.cc +++ b/ui/aura/mus/focus_synchronizer.cc
@@ -48,6 +48,7 @@ SetActiveFocusClient(client::GetFocusClient(root), root); window->GetWindow()->Focus(); } else if (active_focus_client_) { + focused_window_ = nullptr; SetActiveFocusClient(nullptr, nullptr); } }
diff --git a/ui/aura/mus/focus_synchronizer_unittest.cc b/ui/aura/mus/focus_synchronizer_unittest.cc index 83feb7d..af85fb9 100644 --- a/ui/aura/mus/focus_synchronizer_unittest.cc +++ b/ui/aura/mus/focus_synchronizer_unittest.cc
@@ -64,4 +64,30 @@ window_tree_client_impl()->focus_synchronizer()->active_focus_client()); } +TEST_F(FocusSynchronizerTest, SetFocusFromServerNull) { + // Create a WindowTreeHostMus and make it active. + std::unique_ptr<WindowTreeHostMus> window_tree_host = + std::make_unique<WindowTreeHostMus>( + CreateInitParamsForTopLevel(window_tree_client_impl())); + window_tree_host->InitHost(); + wm::FocusController focus_controller(new TestFocusRules); + client::SetFocusClient(window_tree_host->window(), &focus_controller); + window_tree_host->Show(); + focus_controller.FocusWindow(window_tree_host->window()); + FocusSynchronizer* focus_synchronizer = + window_tree_client_impl()->focus_synchronizer(); + focus_synchronizer->SetActiveFocusClient(&focus_controller, + window_tree_host->window()); + EXPECT_EQ(&focus_controller, focus_synchronizer->active_focus_client()); + ASSERT_TRUE(focus_synchronizer->focused_window()); + EXPECT_EQ(focus_synchronizer->focused_window()->GetWindow(), + window_tree_host->window()); + + // Simulate the server clearing focus. + focus_synchronizer->SetFocusFromServer(nullptr); + + // FocusSynchronizer should no longer think there is a focused window. + EXPECT_FALSE(focus_synchronizer->focused_window()); +} + } // namespace aura
diff --git a/ui/aura/mus/in_flight_change.cc b/ui/aura/mus/in_flight_change.cc index 69287bf..a24ff32 100644 --- a/ui/aura/mus/in_flight_change.cc +++ b/ui/aura/mus/in_flight_change.cc
@@ -164,8 +164,10 @@ // CrashInFlightChange -------------------------------------------------------- -CrashInFlightChange::CrashInFlightChange(WindowMus* window, ChangeType type) - : InFlightChange(window, type) {} +CrashInFlightChange::CrashInFlightChange(const base::Location& from_here, + WindowMus* window, + ChangeType type) + : InFlightChange(window, type), location_(from_here) {} CrashInFlightChange::~CrashInFlightChange() {} @@ -174,10 +176,17 @@ } void CrashInFlightChange::ChangeFailed() { - // TODO(crbug.com/912228): remove LOG(). Used to figure out why this is being - // hit. - LOG(ERROR) << "change failed, type=" << static_cast<int>(change_type()); - CHECK(false); + // TODO(crbug.com/912228, crbug.com/940620): remove LOG(). Used to figure out + // why this is being hit. + LOG(FATAL) << "change failed, type=" << ChangeTypeToString(change_type()) + << "(" << static_cast<int>(change_type()) << ")" + << ", window=" + << (window() ? window()->GetWindow()->GetName() : "(null)") + << ", parent=" + << (window() && window()->GetWindow()->parent() + ? window()->GetWindow()->parent()->GetName() + : "(null)") + << ", from=" << location_.ToString(); } void CrashInFlightChange::Revert() { @@ -317,24 +326,6 @@ window_tree_client_->SetWindowVisibleFromServer(window(), revert_visible_); } -// InFlightOpacityChange ------------------------------------------------------- - -InFlightOpacityChange::InFlightOpacityChange(WindowMus* window, - float revert_value) - : InFlightChange(window, ChangeType::OPACITY), - revert_opacity_(revert_value) {} - -InFlightOpacityChange::~InFlightOpacityChange() {} - -void InFlightOpacityChange::SetRevertValueFrom(const InFlightChange& change) { - revert_opacity_ = - static_cast<const InFlightOpacityChange&>(change).revert_opacity_; -} - -void InFlightOpacityChange::Revert() { - window()->SetOpacityFromServer(revert_opacity_); -} - // InFlightSetModalTypeChange // ------------------------------------------------------
diff --git a/ui/aura/mus/in_flight_change.h b/ui/aura/mus/in_flight_change.h index 2c3591f6..9fd7f4a7 100644 --- a/ui/aura/mus/in_flight_change.h +++ b/ui/aura/mus/in_flight_change.h
@@ -11,6 +11,7 @@ #include <string> #include <vector> +#include "base/location.h" #include "base/macros.h" #include "base/memory/ptr_util.h" #include "base/optional.h" @@ -210,7 +211,9 @@ // expected to always complete. class CrashInFlightChange : public InFlightChange { public: - CrashInFlightChange(WindowMus* window, ChangeType type); + CrashInFlightChange(const base::Location& from_here, + WindowMus* window, + ChangeType type); ~CrashInFlightChange() override; // InFlightChange: @@ -219,6 +222,8 @@ void Revert() override; private: + const base::Location location_; + DISALLOW_COPY_AND_ASSIGN(CrashInFlightChange); }; @@ -338,21 +343,6 @@ DISALLOW_COPY_AND_ASSIGN(InFlightVisibleChange); }; -class InFlightOpacityChange : public InFlightChange { - public: - InFlightOpacityChange(WindowMus* window, float revert_value); - ~InFlightOpacityChange() override; - - // InFlightChange: - void SetRevertValueFrom(const InFlightChange& change) override; - void Revert() override; - - private: - float revert_opacity_; - - DISALLOW_COPY_AND_ASSIGN(InFlightOpacityChange); -}; - class InFlightSetModalTypeChange : public InFlightChange { public: InFlightSetModalTypeChange(WindowMus* window, ui::ModalType revert_value);
diff --git a/ui/aura/mus/window_mus.h b/ui/aura/mus/window_mus.h index 712a4b6..d73c38d 100644 --- a/ui/aura/mus/window_mus.h +++ b/ui/aura/mus/window_mus.h
@@ -84,7 +84,6 @@ virtual void SetBoundsFromServer(const gfx::Rect& bounds) = 0; virtual void SetTransformFromServer(const gfx::Transform& transform) = 0; virtual void SetVisibleFromServer(bool visible) = 0; - virtual void SetOpacityFromServer(float opacity) = 0; virtual void SetCursorFromServer(const ui::Cursor& cursor) = 0; virtual void SetPropertyFromServer(const std::string& property_name, const std::vector<uint8_t>* data) = 0;
diff --git a/ui/aura/mus/window_port_mus.cc b/ui/aura/mus/window_port_mus.cc index 7f4369c4..da3ad16 100644 --- a/ui/aura/mus/window_port_mus.cc +++ b/ui/aura/mus/window_port_mus.cc
@@ -419,10 +419,6 @@ window_->Hide(); } -void WindowPortMus::SetOpacityFromServer(float opacity) { - window_->layer()->SetOpacity(opacity); -} - void WindowPortMus::SetCursorFromServer(const ui::Cursor& cursor) { // As this does nothing more than set the cursor we don't need to use // ServerChange.
diff --git a/ui/aura/mus/window_port_mus.h b/ui/aura/mus/window_port_mus.h index 97cced4..87040b13 100644 --- a/ui/aura/mus/window_port_mus.h +++ b/ui/aura/mus/window_port_mus.h
@@ -253,7 +253,6 @@ void SetBoundsFromServer(const gfx::Rect& bounds) override; void SetTransformFromServer(const gfx::Transform& transform) override; void SetVisibleFromServer(bool visible) override; - void SetOpacityFromServer(float opacity) override; void SetCursorFromServer(const ui::Cursor& cursor) override; void SetPropertyFromServer( const std::string& property_name,
diff --git a/ui/aura/mus/window_tree_client.cc b/ui/aura/mus/window_tree_client.cc index bec8477..ab7fe63 100644 --- a/ui/aura/mus/window_tree_client.cc +++ b/ui/aura/mus/window_tree_client.cc
@@ -15,6 +15,7 @@ #include "base/bind_helpers.h" #include "base/callback_helpers.h" #include "base/command_line.h" +#include "base/location.h" #include "base/memory/ptr_util.h" #include "base/message_loop/message_loop.h" #include "base/run_loop.h" @@ -761,8 +762,9 @@ base::flat_map<std::string, std::vector<uint8_t>> transport_properties = property_converter->GetTransportProperties(window->GetWindow()); - const uint32_t change_id = ScheduleInFlightChange( - std::make_unique<CrashInFlightChange>(window, ChangeType::NEW_WINDOW)); + const uint32_t change_id = + ScheduleInFlightChange(std::make_unique<CrashInFlightChange>( + FROM_HERE, window, ChangeType::NEW_WINDOW)); tree_->NewWindow(change_id, window->server_id(), std::move(transport_properties)); if (window->GetWindow()->event_targeting_policy() != @@ -785,7 +787,7 @@ (WasCreatedByThisClient(window) || IsRoot(window))) { delete_change_id = ScheduleInFlightChange(std::make_unique<CrashInFlightChange>( - window, ChangeType::DELETE_WINDOW)); + FROM_HERE, window, ChangeType::DELETE_WINDOW)); tree_->DeleteWindow(delete_change_id.value(), window->server_id()); } @@ -830,16 +832,18 @@ void WindowTreeClient::OnWindowMusAddChild(WindowMus* parent, WindowMus* child) { // TODO: add checks to ensure this can work. - const uint32_t change_id = ScheduleInFlightChange( - std::make_unique<CrashInFlightChange>(parent, ChangeType::ADD_CHILD)); + const uint32_t change_id = + ScheduleInFlightChange(std::make_unique<CrashInFlightChange>( + FROM_HERE, parent, ChangeType::ADD_CHILD)); tree_->AddWindow(change_id, parent->server_id(), child->server_id()); } void WindowTreeClient::OnWindowMusRemoveChild(WindowMus* parent, WindowMus* child) { // TODO: add checks to ensure this can work. - const uint32_t change_id = ScheduleInFlightChange( - std::make_unique<CrashInFlightChange>(parent, ChangeType::REMOVE_CHILD)); + const uint32_t change_id = + ScheduleInFlightChange(std::make_unique<CrashInFlightChange>( + FROM_HERE, parent, ChangeType::REMOVE_CHILD)); tree_->RemoveWindowFromParent(change_id, child->server_id()); } @@ -848,8 +852,9 @@ size_t dest_index) { DCHECK_NE(current_index, dest_index); // TODO: add checks to ensure this can work, e.g. we own the parent. - const uint32_t change_id = ScheduleInFlightChange( - std::make_unique<CrashInFlightChange>(parent, ChangeType::REORDER)); + const uint32_t change_id = + ScheduleInFlightChange(std::make_unique<CrashInFlightChange>( + FROM_HERE, parent, ChangeType::REORDER)); WindowMus* window = WindowMus::Get(parent->GetWindow()->children()[current_index]); WindowMus* relative_window = nullptr; @@ -1356,19 +1361,6 @@ SetWindowVisibleFromServer(window, visible); } -void WindowTreeClient::OnWindowOpacityChanged(ws::Id window_id, - float new_opacity) { - WindowMus* window = GetWindowByServerId(window_id); - if (!window) - return; - - InFlightOpacityChange new_change(window, new_opacity); - if (ApplyServerChangeToExistingInFlightChange(new_change)) - return; - - window->SetOpacityFromServer(new_opacity); -} - void WindowTreeClient::OnWindowDisplayChanged(ws::Id window_id, int64_t display_id) { WindowMus* window = GetWindowByServerId(window_id); @@ -1704,8 +1696,9 @@ WindowTreeHostMus* window_tree_host, float opacity) { WindowMus* window = WindowMus::Get(window_tree_host->window()); - const uint32_t change_id = ScheduleInFlightChange( - std::make_unique<CrashInFlightChange>(window, ChangeType::OPACITY)); + const uint32_t change_id = + ScheduleInFlightChange(std::make_unique<CrashInFlightChange>( + FROM_HERE, window, ChangeType::OPACITY)); tree_->SetWindowOpacity(change_id, window->server_id(), opacity); } @@ -1720,16 +1713,18 @@ Window* window) { WindowMus* above = WindowMus::Get(window_tree_host->window()); WindowMus* below = WindowMus::Get(window); - const uint32_t change_id = ScheduleInFlightChange( - std::make_unique<CrashInFlightChange>(above, ChangeType::REORDER)); + const uint32_t change_id = + ScheduleInFlightChange(std::make_unique<CrashInFlightChange>( + FROM_HERE, above, ChangeType::REORDER)); tree_->StackAbove(change_id, above->server_id(), below->server_id()); } void WindowTreeClient::OnWindowTreeHostStackAtTop( WindowTreeHostMus* window_tree_host) { WindowMus* window = WindowMus::Get(window_tree_host->window()); - const uint32_t change_id = ScheduleInFlightChange( - std::make_unique<CrashInFlightChange>(window, ChangeType::REORDER)); + const uint32_t change_id = + ScheduleInFlightChange(std::make_unique<CrashInFlightChange>( + FROM_HERE, window, ChangeType::REORDER)); tree_->StackAtTop(change_id, window->server_id()); } @@ -1782,7 +1777,7 @@ const uint32_t change_id = ScheduleInFlightChange(std::make_unique<CrashInFlightChange>( - window_port.get(), ChangeType::NEW_TOP_LEVEL_WINDOW)); + FROM_HERE, window_port.get(), ChangeType::NEW_TOP_LEVEL_WINDOW)); tree_->NewTopLevelWindow(change_id, window_port->server_id(), transport_properties); return window_port; @@ -1814,7 +1809,7 @@ WindowMus* parent_mus = WindowMus::Get(parent); const uint32_t change_id = ScheduleInFlightChange(std::make_unique<CrashInFlightChange>( - parent_mus, ChangeType::ADD_TRANSIENT_WINDOW)); + FROM_HERE, parent_mus, ChangeType::ADD_TRANSIENT_WINDOW)); tree_->AddTransientWindow(change_id, parent_mus->server_id(), WindowMus::Get(transient_child)->server_id()); } @@ -1834,7 +1829,8 @@ WindowMus* child_mus = WindowMus::Get(transient_child); const uint32_t change_id = ScheduleInFlightChange(std::make_unique<CrashInFlightChange>( - child_mus, ChangeType::REMOVE_TRANSIENT_WINDOW_FROM_PARENT)); + FROM_HERE, child_mus, + ChangeType::REMOVE_TRANSIENT_WINDOW_FROM_PARENT)); tree_->RemoveTransientWindowFromParent(change_id, child_mus->server_id()); }
diff --git a/ui/aura/mus/window_tree_client.h b/ui/aura/mus/window_tree_client.h index ddaffb7..c9b3d24 100644 --- a/ui/aura/mus/window_tree_client.h +++ b/ui/aura/mus/window_tree_client.h
@@ -433,8 +433,6 @@ ws::mojom::OrderDirection direction) override; void OnWindowDeleted(ws::Id window_id) override; void OnWindowVisibilityChanged(ws::Id window_id, bool visible) override; - void OnWindowOpacityChanged(ws::Id window_id, - float new_opacity) override; void OnWindowDisplayChanged(ws::Id window_id, int64_t display_id) override; void OnWindowParentDrawnStateChanged(ws::Id window_id, bool drawn) override; void OnWindowSharedPropertyChanged(
diff --git a/ui/aura/mus/window_tree_client_unittest.cc b/ui/aura/mus/window_tree_client_unittest.cc index db34545..2252438 100644 --- a/ui/aura/mus/window_tree_client_unittest.cc +++ b/ui/aura/mus/window_tree_client_unittest.cc
@@ -2994,4 +2994,33 @@ EXPECT_EQ(updated_lsia, embed_root->window()->GetLocalSurfaceIdAllocation()); } +// Verifies a failed CrashInFlightChange dumps out window names. +TEST_F(WindowTreeClientTest, CrashInFlightChange) { + aura::Window root_window(nullptr); + root_window.SetName("RootWindow"); + root_window.Init(ui::LAYER_NOT_DRAWN); + + Window* w1 = new Window(nullptr); + w1->SetName("w1"); + w1->Init(ui::LAYER_NOT_DRAWN); + root_window.AddChild(w1); + + Window* w2 = new Window(nullptr); + w2->SetName("w2"); + w2->Init(ui::LAYER_NOT_DRAWN); + root_window.AddChild(w2); + + window_tree()->AckAllChanges(); + + // Client attempts to reorder |w1|. + root_window.StackChildAtTop(w1); + + // Server rejects the change and triggers a CrashInFlightChange crash. + EXPECT_DEATH_IF_SUPPORTED( + window_tree()->AckSingleChangeOfType(WindowTreeChangeType::REORDER, + false), + "change failed, type=REORDER\\(16\\), window=RootWindow, " + "parent=\\(null\\), from=OnWindowMusMoveChild@"); +} + } // namespace aura
diff --git a/ui/aura/window_occlusion_tracker.cc b/ui/aura/window_occlusion_tracker.cc index d1bd872e..6372cd2 100644 --- a/ui/aura/window_occlusion_tracker.cc +++ b/ui/aura/window_occlusion_tracker.cc
@@ -33,7 +33,7 @@ // occlusion states before they become stable. // // TODO(fdoray): This can be changed to 2 once showing/hiding a WebContents -// doesn't cause a call to Show()/Hide() on the aura::Window of a +// doesn't cause a call to Show()/Hide() on the Window of a // RenderWidgetHostViewAura. https://crbug.com/827268 constexpr int kMaxRecomputeOcclusion = 3; @@ -49,7 +49,7 @@ // |parent_transform_relative_to_root| is the transform of |window->parent()| // relative to its root. gfx::Transform GetWindowTransformRelativeToRoot( - aura::Window* window, + Window* window, const gfx::Transform& parent_transform_relative_to_root) { if (window->IsRootWindow()) return gfx::Transform(); @@ -72,7 +72,7 @@ // |transform_relative_to_root| is the transform of |window| relative to its // root. If |clipped_bounds| is not null, the returned bounds are clipped by it. SkIRect GetWindowBoundsInRootWindow( - aura::Window* window, + Window* window, const gfx::Transform& transform_relative_to_root, const SkIRect* clipped_bounds) { DCHECK(transform_relative_to_root.Preserves2dAxisAlignment()); @@ -107,8 +107,7 @@ Shutdown(); } -void WindowOcclusionTracker::ScopedExclude::OnWindowDestroying( - aura::Window* window) { +void WindowOcclusionTracker::ScopedExclude::OnWindowDestroying(Window* window) { DCHECK_EQ(window_, window); Shutdown(); } @@ -121,6 +120,31 @@ } } +WindowOcclusionTracker::ScopedForceVisible::ScopedForceVisible(Window* window) + : window_(window) { + window_->AddObserver(this); + window->env()->GetWindowOcclusionTracker()->ForceWindowVisible(window_); +} + +WindowOcclusionTracker::ScopedForceVisible::~ScopedForceVisible() { + Shutdown(); +} + +void WindowOcclusionTracker::ScopedForceVisible::OnWindowDestroying( + Window* window) { + DCHECK_EQ(window_, window); + Shutdown(); +} + +void WindowOcclusionTracker::ScopedForceVisible::Shutdown() { + if (window_) { + window_->RemoveObserver(this); + window_->env()->GetWindowOcclusionTracker()->RemoveForceWindowVisible( + window_); + window_ = nullptr; + } +} + void WindowOcclusionTracker::Track(Window* window) { DCHECK(window); DCHECK(window != window->GetRootWindow()); @@ -186,7 +210,8 @@ Window* root_window = root_window_pair.first; if (root_window_pair.second.occlusion_state == Window::OcclusionState::OCCLUDED) { - SetWindowAndDescendantsAreOccluded(root_window, true); + SetWindowAndDescendantsAreOccluded( + root_window, /* is_occluded */ true, root_window->IsVisible()); } else { SkRegion occluded_region; RecomputeOcclusionImpl(root_window, gfx::Transform(), nullptr, @@ -214,11 +239,10 @@ // Fallback to VISIBLE/HIDDEN if the maximum number of times that // occlusion can be recomputed was exceeded. if (exceeded_max_num_times_occlusion_recomputed) { - if (window->IsVisible()) { + if (WindowIsVisible(window)) it.second.occlusion_state = Window::OcclusionState::VISIBLE; - } else { + else it.second.occlusion_state = Window::OcclusionState::HIDDEN; - } it.second.occluded_region = SkRegion(); } @@ -239,13 +263,19 @@ SkRegion* occluded_region) { DCHECK(window); - if (!window->IsVisible()) { - SetWindowAndDescendantsAreOccluded(window, true); + const bool force_visible = WindowIsForcedVisible(window); + // This does not use Window::IsVisible() as that returns the wrong thing for + // any ancestors that are forced visible. + const bool is_visible = force_visible || window->layer()->visible(); + if (!is_visible) { + SetWindowAndDescendantsAreOccluded(window, /* is_occluded */ true, + /* is_parent_visible */ true); return false; } if (WindowIsAnimated(window) || WindowIsExcluded(window)) { - SetWindowAndDescendantsAreOccluded(window, false); + SetWindowAndDescendantsAreOccluded(window, /* is_occluded */ false, + /* is_parent_visible */ true); return true; } @@ -256,39 +286,50 @@ if (!transform_relative_to_root.Preserves2dAxisAlignment()) { // For simplicity, windows that are not axis-aligned are considered // unoccluded and do not occlude other windows. - SetWindowAndDescendantsAreOccluded(window, false); + SetWindowAndDescendantsAreOccluded(window, /* is_occluded */ false, + /* is_parent_visible */ true); return true; } - const SkIRect window_bounds = GetWindowBoundsInRootWindow( - window, transform_relative_to_root, clipped_bounds); + const SkIRect window_bounds = + GetWindowBoundsInRootWindow(window, transform_relative_to_root, + force_visible ? nullptr : clipped_bounds); // Compute children occlusion states. const SkIRect* clipped_bounds_for_children = window->layer()->GetMasksToBounds() ? &window_bounds : clipped_bounds; bool has_visible_child = false; SkRegion occluded_region_before_traversing_children = *occluded_region; + // Windows that are forced visible are always considered visible, so have no + // clip. + SkRegion region_for_forced_visible_windows; + SkRegion* occluded_region_for_children = + force_visible ? ®ion_for_forced_visible_windows : occluded_region; for (auto* child : base::Reversed(window->children())) { - has_visible_child |= - RecomputeOcclusionImpl(child, transform_relative_to_root, - clipped_bounds_for_children, occluded_region); + has_visible_child |= RecomputeOcclusionImpl( + child, transform_relative_to_root, clipped_bounds_for_children, + occluded_region_for_children); } // Window is fully occluded. - if (occluded_region->contains(window_bounds) && !has_visible_child) { - SetOccluded(window, true, SkRegion()); + if (!force_visible && occluded_region->contains(window_bounds) && + !has_visible_child) { + SetOccluded(window, /* is_occluded */ true, /* is_parent_visible */ true, + SkRegion()); return false; } - // Window is partially occluded or unoccluded. - SetOccluded(window, false, occluded_region_before_traversing_children); + // Window is partially occluded or unoccluded. Windows that are forced visible + // are considered completely visible (so they get an empty SkRegion()). + SetOccluded( + window, false, /* is_parent_visible */ true, + force_visible ? SkRegion() : occluded_region_before_traversing_children); - if (VisibleWindowIsOpaque(window)) + if (!force_visible && VisibleWindowIsOpaque(window)) occluded_region->op(window_bounds, SkRegion::kUnion_Op); return true; } bool WindowOcclusionTracker::VisibleWindowIsOpaque(Window* window) const { - DCHECK(window->IsVisible()); DCHECK(window->layer()); return !window->transparent() && WindowHasContent(window) && window->layer()->GetCombinedOpacity() == 1.0f && @@ -337,14 +378,18 @@ void WindowOcclusionTracker::SetWindowAndDescendantsAreOccluded( Window* window, - bool is_occluded) { - SetOccluded(window, is_occluded, SkRegion()); + bool is_occluded, + bool is_parent_visible) { + const bool is_visible = WindowIsForcedVisible(window) || + (is_parent_visible && window->layer()->visible()); + SetOccluded(window, is_occluded, is_visible, SkRegion()); for (Window* child_window : window->children()) - SetWindowAndDescendantsAreOccluded(child_window, is_occluded); + SetWindowAndDescendantsAreOccluded(child_window, is_occluded, is_visible); } void WindowOcclusionTracker::SetOccluded(Window* window, bool is_occluded, + bool is_parent_visible, const SkRegion& occluded_region) { auto tracked_window = tracked_windows_.find(window); if (tracked_window == tracked_windows_.end()) @@ -353,7 +398,9 @@ // Set the occluded region of the window. tracked_window->second.occluded_region = occluded_region; - if (!window->IsVisible()) + const bool is_visible = WindowIsForcedVisible(window) || + (is_parent_visible && window->layer()->visible()); + if (!is_visible) tracked_window->second.occlusion_state = Window::OcclusionState::HIDDEN; else if (is_occluded) tracked_window->second.occlusion_state = Window::OcclusionState::OCCLUDED; @@ -377,6 +424,24 @@ return base::ContainsKey(excluded_windows_, window); } +bool WindowOcclusionTracker::WindowIsVisible(Window* window) const { + if (forced_visible_count_map_.empty()) + return window->IsVisible(); + Window* w = window; + Window* last = w; + while (w) { + if (!w->layer()->visible() && !WindowIsForcedVisible(window)) + return false; + last = w; + w = w->parent(); + } + return last->IsRootWindow(); +} + +bool WindowOcclusionTracker::WindowIsForcedVisible(Window* window) const { + return forced_visible_count_map_.count(window) > 0; +} + template <typename Predicate> void WindowOcclusionTracker::MarkRootWindowAsDirtyAndMaybeComputeOcclusionIf( Window* window, @@ -414,7 +479,7 @@ root_window_state->dirty = true; } -bool WindowOcclusionTracker::MarkRootWindowAsDirty(aura::Window* root_window) { +bool WindowOcclusionTracker::MarkRootWindowAsDirty(Window* root_window) { auto root_window_state_it = root_windows_.find(root_window); if (root_window_state_it == root_windows_.end()) return false; @@ -430,7 +495,7 @@ bool WindowOcclusionTracker::WindowOrDescendantIsTrackedAndVisible( Window* window) const { - if (!window->IsVisible()) + if (!WindowIsVisible(window)) return false; if (WindowIsTracked(window)) return true; @@ -452,7 +517,7 @@ parent_window_is_opaque && (assume_window_opaque || window->layer()->opacity() == 1.0f); - if (!window->IsVisible() || !window->layer() || !window_is_opaque || + if (!WindowIsVisible(window) || !window->layer() || !window_is_opaque || WindowIsAnimated(window)) { return false; } @@ -472,7 +537,7 @@ // other windows in the tree if it is visible and not animated (animated // windows aren't considered in occlusion computations), unless it is // excluded. - return window->IsVisible() && !WindowOrParentIsAnimated(window) && + return WindowIsVisible(window) && !WindowOrParentIsAnimated(window) && !WindowIsExcluded(window); } @@ -558,7 +623,7 @@ // introduce the count. DCHECK(!WindowIsExcluded(window)); excluded_windows_.insert(window); - if (window->IsVisible()) { + if (WindowIsVisible(window)) { if (MarkRootWindowAsDirty(window->GetRootWindow())) MaybeComputeOcclusion(); } @@ -567,12 +632,31 @@ void WindowOcclusionTracker::Unexclude(Window* window) { DCHECK(WindowIsExcluded(window)); excluded_windows_.erase(window); - if (window->IsVisible()) { + if (WindowIsVisible(window)) { if (MarkRootWindowAsDirty(window->GetRootWindow())) MaybeComputeOcclusion(); } } +void WindowOcclusionTracker::ForceWindowVisible(Window* window) { + if (forced_visible_count_map_[window]++ == 0) { + Window* root_window = window->GetRootWindow(); + if (root_window && MarkRootWindowAsDirty(root_window)) + MaybeComputeOcclusion(); + } +} + +void WindowOcclusionTracker::RemoveForceWindowVisible(Window* window) { + auto iter = forced_visible_count_map_.find(window); + DCHECK(iter != forced_visible_count_map_.end()); + if (--iter->second == 0u) { + forced_visible_count_map_.erase(iter); + Window* root_window = window->GetRootWindow(); + if (root_window && MarkRootWindowAsDirty(root_window)) + MaybeComputeOcclusion(); + } +} + void WindowOcclusionTracker::OnLayerAnimationEnded( ui::LayerAnimationSequence* sequence) { CleanupAnimatedWindows(); @@ -616,7 +700,7 @@ // A child isn't visible when its parent isn't IsVisible(). Therefore, there // is no need to compute occlusion when Show() or Hide() is called on a // window with a hidden parent. - return (!window->parent() || window->parent()->IsVisible()) && + return (!window->parent() || WindowIsVisible(window->parent())) && !WindowOrParentIsAnimated(window); }); } @@ -720,7 +804,7 @@ void WindowOcclusionTracker::OnOcclusionStateChanged( WindowTreeHost* host, - aura::Window::OcclusionState new_state) { + Window::OcclusionState new_state) { UMA_HISTOGRAM_ENUMERATION("WindowOcclusionChanged", new_state); Window* root_window = host->window(); auto root_window_state_it = root_windows_.find(root_window);
diff --git a/ui/aura/window_occlusion_tracker.h b/ui/aura/window_occlusion_tracker.h index b4804a5cda..43b1ef0 100644 --- a/ui/aura/window_occlusion_tracker.h +++ b/ui/aura/window_occlusion_tracker.h
@@ -66,14 +66,15 @@ DISALLOW_COPY_AND_ASSIGN(ScopedPause); }; - // Exclude the window from occlusion tracking so that a window behind the - // given window is still considered visible. The excluded window itself and - // its descendant windows, if tracked, are considered visible. This is useful - // for a window being dragged or resized to avoid unnecessary occlusion state - // change triggered by these operation, because the window bounds are - // temporary until it is finished. - // Note that this is intended to be used by window manager and not by mus - // client process. + // Forces the occlusion state of a window and all its descendants to VISIBLE. + // Ignores the window that is forced VISIBLE and its descendants when + // computing the occlusion state of other windows is the tree. + // + // This is useful for a window being dragged or resized to avoid unnecessary + // occlusion state change triggered by these operation, because the window + // bounds are temporary until it is finished. + // + // Note that this is intended to be used by window manager, such as Ash. class AURA_EXPORT ScopedExclude : public WindowObserver { public: explicit ScopedExclude(Window* window); @@ -82,8 +83,8 @@ Window* window() { return window_; } private: - // aura::WindowObserver: - void OnWindowDestroying(aura::Window* window) override; + // WindowObserver: + void OnWindowDestroying(Window* window) override; void Shutdown(); @@ -91,6 +92,29 @@ DISALLOW_COPY_AND_ASSIGN(ScopedExclude); }; + // Forces the occlusion state of a window to VISIBLE. Causes the occlusion + // state of descendants of the window that is forced VISIBLE to be computed + // as if they were in an isolated tree with a root that is drawn. Ignores the + // window that is forced VISIBLE and its descendants when computing the + // occlusion state of other windows is the tree. + // + // This function is primarily useful for situations that show the contents of + // a hidden window, such as overview mode on ChromeOS. + class AURA_EXPORT ScopedForceVisible : public WindowObserver { + public: + explicit ScopedForceVisible(Window* window); + ~ScopedForceVisible() override; + + private: + // WindowObserver: + void OnWindowDestroying(Window* window) override; + + void Shutdown(); + + Window* window_; + DISALLOW_COPY_AND_ASSIGN(ScopedForceVisible); + }; + // Start tracking the occlusion state of |window|. void Track(Window* window); @@ -109,6 +133,8 @@ occlusion_change_builder_factory_ = std::move(factory); } + bool IsPaused() const { return num_pause_occlusion_tracking_; } + private: friend class test::WindowOcclusionTrackerTestApi; friend class Env; @@ -174,8 +200,10 @@ bool MaybeObserveAnimatedWindow(Window* window); // Calls SetOccluded() with |is_occluded| as argument for |window| and its - // descendants. - void SetWindowAndDescendantsAreOccluded(Window* window, bool is_occluded); + // descendants. |is_parent_visible| is true if the parent is visible. + void SetWindowAndDescendantsAreOccluded(Window* window, + bool is_occluded, + bool is_parent_visible); // Updates the occlusion state of |window| in |tracked_windows_|, based on // |is_occluded| and window->IsVisible(). Updates the occluded region of @@ -183,6 +211,7 @@ // |tracked_windows_|. void SetOccluded(Window* window, bool is_occluded, + bool is_parent_visible, const SkRegion& occluded_region); // Returns true if |window| is in |tracked_windows_|. @@ -194,6 +223,14 @@ // Returns true if |window| is in |excluded_windows_|. bool WindowIsExcluded(Window* window) const; + // Returns true if |window| is considered visible. Use this over IsVisible() + // to ensure forced visible windows are considered. + bool WindowIsVisible(Window* window) const; + + // Returns true if |window| is forced visible. This does *not* recurse and + // only checks |window|. Use WindowIsVisible() to consider parents. + bool WindowIsForcedVisible(Window* window) const; + // If the root of |window| is not dirty and |predicate| is true, marks the // root of |window| as dirty. Then, calls MaybeComputeOcclusion(). // |predicate| is not evaluated if the root of |window| is already dirty when @@ -207,7 +244,7 @@ // Marks |root_window| as dirty. Returns false if none of the descendent // windows in |root_window| are tracked. - bool MarkRootWindowAsDirty(aura::Window* root_window); + bool MarkRootWindowAsDirty(Window* root_window); // Returns true if |window| or one of its parents is in |animated_windows_|. bool WindowOrParentIsAnimated(Window* window) const; @@ -250,11 +287,15 @@ void Pause(); void Unpause(); - // Exclucde/Unexclude a window from occlusion tracking. See comment on + // Exclude/Unexclude a window from occlusion tracking. See comment on // ScopedExclude. void Exclude(Window* window); void Unexclude(Window* window); + // Called from ScopedForceVisible. + void ForceWindowVisible(Window* window); + void RemoveForceWindowVisible(Window* window); + // ui::LayerAnimationObserver: void OnLayerAnimationEnded(ui::LayerAnimationSequence* sequence) override; void OnLayerAnimationAborted(ui::LayerAnimationSequence* sequence) override; @@ -288,6 +329,9 @@ // Windows whose occlusion data is tracked. base::flat_map<Window*, OcclusionData> tracked_windows_; + // Windows whose target visibility is forced to true. + base::flat_map<Window*, size_t> forced_visible_count_map_; + // Windows whose bounds or transform are animated. // // To reduce the overhead of the WindowOcclusionTracker, windows in this set
diff --git a/ui/aura/window_occlusion_tracker_unittest.cc b/ui/aura/window_occlusion_tracker_unittest.cc index 81a2281..47e77638 100644 --- a/ui/aura/window_occlusion_tracker_unittest.cc +++ b/ui/aura/window_occlusion_tracker_unittest.cc
@@ -40,7 +40,7 @@ void SetName(const std::string& name) { window_->SetName(name); } void set_expectation(Window::OcclusionState occlusion_state, - const SkRegion& occluded_region) { + SkRegion occluded_region = SkRegion()) { expected_occlusion_state_ = occlusion_state; expected_occluded_region_ = occluded_region; } @@ -2170,4 +2170,102 @@ EXPECT_FALSE(delegate_a->is_expecting_call()); } +TEST_F(WindowOcclusionTrackerTest, ScopedForceVisible) { + MockWindowDelegate* delegate_a = new MockWindowDelegate(); + delegate_a->set_expectation(Window::OcclusionState::VISIBLE, SkRegion()); + Window* window = CreateTrackedWindow(delegate_a, gfx::Rect(0, 0, 10, 10)); + EXPECT_FALSE(delegate_a->is_expecting_call()); + + delegate_a->set_expectation(Window::OcclusionState::HIDDEN, SkRegion()); + window->Hide(); + EXPECT_FALSE(delegate_a->is_expecting_call()); + + // Using ScopedForceVisible when the window is hidden should force it visible. + delegate_a->set_expectation(Window::OcclusionState::VISIBLE, SkRegion()); + { + WindowOcclusionTracker::ScopedForceVisible force_visible(window); + EXPECT_FALSE(delegate_a->is_expecting_call()); + + // Destroying the ScopedForceVisible should return the window to hidden. + delegate_a->set_expectation(Window::OcclusionState::HIDDEN, SkRegion()); + } + EXPECT_FALSE(delegate_a->is_expecting_call()); +} + +TEST_F(WindowOcclusionTrackerTest, ScopedForceVisibleSiblingsIgnored) { + MockWindowDelegate* delegate_a = new MockWindowDelegate(); + delegate_a->set_expectation(Window::OcclusionState::VISIBLE, SkRegion()); + Window* window = CreateTrackedWindow(delegate_a, gfx::Rect(0, 0, 10, 10)); + EXPECT_FALSE(delegate_a->is_expecting_call()); + + delegate_a->set_expectation(Window::OcclusionState::OCCLUDED, SkRegion()); + CreateUntrackedWindow(gfx::Rect(0, 0, 100, 100), nullptr); + EXPECT_FALSE(delegate_a->is_expecting_call()); + + // Using ScopedForceVisible when the window is occluded should force it + // visible. + delegate_a->set_expectation(Window::OcclusionState::VISIBLE, SkRegion()); + { + WindowOcclusionTracker::ScopedForceVisible force_visible(window); + EXPECT_FALSE(delegate_a->is_expecting_call()); + + // Destroying the ScopedForceVisible should return the window to hidden. + delegate_a->set_expectation(Window::OcclusionState::OCCLUDED, SkRegion()); + } + EXPECT_FALSE(delegate_a->is_expecting_call()); +} + +TEST_F(WindowOcclusionTrackerTest, ScopedForceVisibleWithOccludedSibling) { + // Creates three windows, a parent with two children. Both children have + // the same bounds. + std::unique_ptr<WindowOcclusionTracker::ScopedPause> + pause_occlusion_tracking = + std::make_unique<WindowOcclusionTracker::ScopedPause>( + root_window()->env()); + MockWindowDelegate* parent_delegate = new MockWindowDelegate(); + Window* parent_window = + CreateTrackedWindow(parent_delegate, gfx::Rect(0, 0, 10, 10)); + EXPECT_FALSE(parent_delegate->is_expecting_call()); + MockWindowDelegate* occluded_child_delegate = new MockWindowDelegate(); + CreateTrackedWindow(occluded_child_delegate, gfx::Rect(0, 0, 10, 10), + parent_window); + EXPECT_FALSE(occluded_child_delegate->is_expecting_call()); + MockWindowDelegate* visible_child_delegate = new MockWindowDelegate(); + CreateTrackedWindow(visible_child_delegate, gfx::Rect(0, 0, 10, 10), + parent_window); + EXPECT_FALSE(visible_child_delegate->is_expecting_call()); + + // Initial state after creation. + parent_delegate->set_expectation(Window::OcclusionState::VISIBLE); + occluded_child_delegate->set_expectation(Window::OcclusionState::OCCLUDED); + visible_child_delegate->set_expectation(Window::OcclusionState::VISIBLE); + pause_occlusion_tracking.reset(); + EXPECT_FALSE(parent_delegate->is_expecting_call()); + EXPECT_FALSE(occluded_child_delegate->is_expecting_call()); + EXPECT_FALSE(visible_child_delegate->is_expecting_call()); + + // Hiding the parent should result in all windows being hidden. + parent_delegate->set_expectation(Window::OcclusionState::HIDDEN); + occluded_child_delegate->set_expectation(Window::OcclusionState::HIDDEN); + visible_child_delegate->set_expectation(Window::OcclusionState::HIDDEN); + parent_window->Hide(); + EXPECT_FALSE(parent_delegate->is_expecting_call()); + EXPECT_FALSE(occluded_child_delegate->is_expecting_call()); + EXPECT_FALSE(visible_child_delegate->is_expecting_call()); + + // Creating a ScopedForceVisible for the parent should return to the initial + // state. + parent_delegate->set_expectation(Window::OcclusionState::VISIBLE); + occluded_child_delegate->set_expectation(Window::OcclusionState::OCCLUDED); + visible_child_delegate->set_expectation(Window::OcclusionState::VISIBLE); + WindowOcclusionTracker::ScopedForceVisible force_visible(parent_window); + EXPECT_FALSE(parent_delegate->is_expecting_call()); + EXPECT_FALSE(occluded_child_delegate->is_expecting_call()); + EXPECT_FALSE(visible_child_delegate->is_expecting_call()); + + // Do another show, so that once the |force_visible| is destroyed the + // assertions in MockWindowDelegate aren't tripped. + parent_window->Show(); +} + } // namespace aura
diff --git a/ui/base/mojo/cursor_struct_traits.cc b/ui/base/mojo/cursor_struct_traits.cc index 1620bd8..8acf377 100644 --- a/ui/base/mojo/cursor_struct_traits.cc +++ b/ui/base/mojo/cursor_struct_traits.cc
@@ -328,12 +328,9 @@ if (!data.ReadHotspot(&hotspot) || !data.ReadBitmap(&bitmap)) return false; - // Clamp the scale factor to a reasonable value. TODO(estade): do we even need - // this field? It doesn't appear to be used anywhere and is a property of the - // display, not the cursor. + // TODO(estade): do we even need this field? It doesn't appear to be used + // anywhere and is a property of the display, not the cursor. float device_scale_factor = data.device_scale_factor(); - if (device_scale_factor < 1.f || device_scale_factor > 3.f) - return false; *out = ui::Cursor(type); out->set_custom_bitmap(bitmap);
diff --git a/ui/base/mojo/cursor_struct_traits_unittest.cc b/ui/base/mojo/cursor_struct_traits_unittest.cc index f37f01bd..d5c24ae 100644 --- a/ui/base/mojo/cursor_struct_traits_unittest.cc +++ b/ui/base/mojo/cursor_struct_traits_unittest.cc
@@ -88,4 +88,17 @@ EXPECT_TRUE(output.GetBitmap().empty()); } +// Test that various device scale factors are passed correctly over the wire. +TEST_F(CursorStructTraitsTest, TestDeviceScaleFactors) { + ui::Cursor input(ui::CursorType::kCustom); + ui::Cursor output; + + for (auto scale : {0.f, 0.525f, 0.75f, 0.9f, 1.f, 2.1f, 2.5f, 3.f, 10.f}) { + SCOPED_TRACE(testing::Message() << " scale: " << scale); + input.set_device_scale_factor(scale); + EXPECT_TRUE(EchoCursor(input, &output)); + EXPECT_EQ(scale, output.device_scale_factor()); + } +} + } // namespace ui
diff --git a/ui/base/now_playing/BUILD.gn b/ui/base/now_playing/BUILD.gn index 2870f65..8dca44bb 100644 --- a/ui/base/now_playing/BUILD.gn +++ b/ui/base/now_playing/BUILD.gn
@@ -2,6 +2,15 @@ # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. +config("media_player_weak_link") { + ldflags = [ + "-weak_framework", + "MediaPlayer", + ] + + visibility = [ ":now_playing" ] +} + component("now_playing") { sources = [ "now_playing_info_center_delegate.cc", @@ -26,10 +35,13 @@ "//base", ] - libs = [ - "Foundation.framework", - "MediaPlayer.framework", - ] + libs = [ "Foundation.framework" ] + + # MediaPlayer.framework is only available on macOS 10.12 and higher. In a + # release build, component() is a static_library, which does not transitively + # carry weak_link information. Ensure that all targets that directly or + # indirectly carry the weak_link on the framework. + all_dependent_configs = [ ":media_player_weak_link" ] } static_library("test_support") {
diff --git a/ui/base/ui_base_features.cc b/ui/base/ui_base_features.cc index 28bb7c0..66fb9a5 100644 --- a/ui/base/ui_base_features.cc +++ b/ui/base/ui_base_features.cc
@@ -81,7 +81,7 @@ base::FEATURE_ENABLED_BY_DEFAULT}; // Enables using TSF (over IMM32) for IME. const base::Feature kTSFImeSupport = {"TSFImeSupport", - base::FEATURE_DISABLED_BY_DEFAULT}; + base::FEATURE_ENABLED_BY_DEFAULT}; bool IsUsingWMPointerForTouch() { return base::win::GetVersion() >= base::win::VERSION_WIN8 &&
diff --git a/ui/compositor/OWNERS b/ui/compositor/OWNERS index 37217a38..9d04678d 100644 --- a/ui/compositor/OWNERS +++ b/ui/compositor/OWNERS
@@ -7,3 +7,5 @@ # Animation per-file *animat*=ajuma@chromium.org per-file *animat*=loyso@chromium.org + +# COMPONENT: Internals>Compositing
diff --git a/ui/gfx/image/image_util_ios.mm b/ui/gfx/image/image_util_ios.mm index cc66b24..038ac2a7 100644 --- a/ui/gfx/image/image_util_ios.mm +++ b/ui/gfx/image/image_util_ios.mm
@@ -27,6 +27,9 @@ } Image ResizedImageForSearchByImage(const Image& image) { + if (image.IsEmpty()) { + return image; + } UIImage* ui_image = image.ToUIImage(); if (ui_image &&
diff --git a/ui/message_center/message_center_impl.cc b/ui/message_center/message_center_impl.cc index c5684b21..f35cc787 100644 --- a/ui/message_center/message_center_impl.cc +++ b/ui/message_center/message_center_impl.cc
@@ -224,7 +224,7 @@ bool by_user) { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); - Notification* notification = FindVisibleNotificationById(id); + Notification* notification = notification_list_->GetNotificationById(id); if (!notification) return;
diff --git a/ui/message_center/message_center_impl_unittest.cc b/ui/message_center/message_center_impl_unittest.cc index 80214ba..a29e720 100644 --- a/ui/message_center/message_center_impl_unittest.cc +++ b/ui/message_center/message_center_impl_unittest.cc
@@ -859,6 +859,28 @@ EXPECT_FALSE(message_center()->FindVisibleNotificationById(id)); } +TEST_F(MessageCenterImplTest, RemoveNonVisibleNotification) { + // Add two notifications. + message_center()->AddNotification(CreateSimpleNotification("id1")); + message_center()->AddNotification(CreateSimpleNotification("id2")); + EXPECT_EQ(2u, message_center()->GetVisibleNotifications().size()); + + // Add a blocker to block all notifications. + NotifierId allowed_notifier_id(NotifierType::APPLICATION, "notifier"); + TotalNotificationBlocker blocker(message_center(), allowed_notifier_id); + blocker.SetNotificationsEnabled(false); + EXPECT_EQ(0u, message_center()->GetVisibleNotifications().size()); + + // Removing a non-visible notification should work. + message_center()->RemoveNotification("id1", false); + blocker.SetNotificationsEnabled(true); + EXPECT_EQ(1u, message_center()->GetVisibleNotifications().size()); + + // Also try removing a visible notification. + message_center()->RemoveNotification("id2", false); + EXPECT_EQ(0u, message_center()->GetVisibleNotifications().size()); +} + TEST_F(MessageCenterImplTest, FindNotificationsByAppId) { message_center()->SetHasMessageCenterView(true);
diff --git a/ui/message_center/views/notification_header_view.cc b/ui/message_center/views/notification_header_view.cc index b183797..4e6d92c 100644 --- a/ui/message_center/views/notification_header_view.cc +++ b/ui/message_center/views/notification_header_view.cc
@@ -376,6 +376,10 @@ return app_name_view_->text(); } +const gfx::ImageSkia& NotificationHeaderView::app_icon_for_testing() const { + return app_icon_view_->GetImage(); +} + void NotificationHeaderView::UpdateSummaryTextVisibility() { const bool visible = has_progress_ || has_overflow_indicator_; summary_text_divider_->SetVisible(visible);
diff --git a/ui/message_center/views/notification_header_view.h b/ui/message_center/views/notification_header_view.h index feb4ac4..7b607b6 100644 --- a/ui/message_center/views/notification_header_view.h +++ b/ui/message_center/views/notification_header_view.h
@@ -58,6 +58,8 @@ const base::string16& app_name_for_testing() const; + const gfx::ImageSkia& app_icon_for_testing() const; + private: // Update visibility for both |summary_text_view_| and |timestamp_view_|. void UpdateSummaryTextVisibility();
diff --git a/ui/message_center/views/notification_view_md.cc b/ui/message_center/views/notification_view_md.cc index 78036891..a57ccf5 100644 --- a/ui/message_center/views/notification_view_md.cc +++ b/ui/message_center/views/notification_view_md.cc
@@ -1142,7 +1142,7 @@ return true; } // Expandable if there is at least one inline action. - if (action_buttons_row_->has_children()) + if (!action_buttons_row_->children().empty()) return true; // Expandable if the notification has image. @@ -1171,7 +1171,8 @@ if (image_container_view_) image_container_view_->SetVisible(expanded); - actions_row_->SetVisible(expanded && (action_buttons_row_->has_children())); + actions_row_->SetVisible(expanded && + !action_buttons_row_->children().empty()); if (!expanded) { action_buttons_row_->SetVisible(true); inline_reply_->SetVisible(false);
diff --git a/ui/views/accessibility/ax_aura_obj_cache.cc b/ui/views/accessibility/ax_aura_obj_cache.cc index 5fdbf125..cc8ad5f 100644 --- a/ui/views/accessibility/ax_aura_obj_cache.cc +++ b/ui/views/accessibility/ax_aura_obj_cache.cc
@@ -178,7 +178,7 @@ // focus. if (focused_widget->non_client_view() && focused_widget->non_client_view()->client_view() && - focused_widget->non_client_view()->client_view()->has_children()) { + !focused_widget->non_client_view()->client_view()->children().empty()) { return focused_widget->non_client_view()->client_view()->child_at(0); }
diff --git a/ui/views/accessibility/ax_root_obj_wrapper.cc b/ui/views/accessibility/ax_root_obj_wrapper.cc index 3af0a25..05176d2c 100644 --- a/ui/views/accessibility/ax_root_obj_wrapper.cc +++ b/ui/views/accessibility/ax_root_obj_wrapper.cc
@@ -39,7 +39,7 @@ } views::AXAuraObjWrapper* AXRootObjWrapper::GetParent() { - return NULL; + return nullptr; } void AXRootObjWrapper::GetChildren(
diff --git a/ui/views/accessibility/ax_system_caret_win_interactive_uitest.cc b/ui/views/accessibility/ax_system_caret_win_interactive_uitest.cc index e90bf99..ff65501 100644 --- a/ui/views/accessibility/ax_system_caret_win_interactive_uitest.cc +++ b/ui/views/accessibility/ax_system_caret_win_interactive_uitest.cc
@@ -111,7 +111,7 @@ // static WinAccessibilityCaretEventMonitor* - WinAccessibilityCaretEventMonitor::instance_ = NULL; + WinAccessibilityCaretEventMonitor::instance_ = nullptr; WinAccessibilityCaretEventMonitor::WinAccessibilityCaretEventMonitor( UINT event_min, @@ -120,7 +120,7 @@ << " WinAccessibilityCaretEventMonitor at a time."; instance_ = this; win_event_hook_handle_ = - SetWinEventHook(event_min, event_max, NULL, + SetWinEventHook(event_min, event_max, nullptr, &WinAccessibilityCaretEventMonitor::WinEventHookThunk, GetCurrentProcessId(), 0, // Hook all threads @@ -129,7 +129,7 @@ WinAccessibilityCaretEventMonitor::~WinAccessibilityCaretEventMonitor() { UnhookWinEvent(win_event_hook_handle_); - instance_ = NULL; + instance_ = nullptr; } void WinAccessibilityCaretEventMonitor::WaitForNextEvent(DWORD* out_event,
diff --git a/ui/views/accessibility/ax_virtual_view_unittest.cc b/ui/views/accessibility/ax_virtual_view_unittest.cc index 0a88e41..cdb60ab 100644 --- a/ui/views/accessibility/ax_virtual_view_unittest.cc +++ b/ui/views/accessibility/ax_virtual_view_unittest.cc
@@ -22,7 +22,7 @@ class TestButton : public Button { public: - TestButton() : Button(NULL) {} + TestButton() : Button(nullptr) {} ~TestButton() override = default; private:
diff --git a/ui/views/accessibility/view_ax_platform_node_delegate_unittest.cc b/ui/views/accessibility/view_ax_platform_node_delegate_unittest.cc index 0f796ad1..fc8f6cf 100644 --- a/ui/views/accessibility/view_ax_platform_node_delegate_unittest.cc +++ b/ui/views/accessibility/view_ax_platform_node_delegate_unittest.cc
@@ -28,7 +28,7 @@ class TestButton : public Button { public: - TestButton() : Button(NULL) {} + TestButton() : Button(nullptr) {} ~TestButton() override = default; private:
diff --git a/ui/views/accessibility/view_ax_platform_node_delegate_win_unittest.cc b/ui/views/accessibility/view_ax_platform_node_delegate_win_unittest.cc index b1c6388..85f316c 100644 --- a/ui/views/accessibility/view_ax_platform_node_delegate_win_unittest.cc +++ b/ui/views/accessibility/view_ax_platform_node_delegate_win_unittest.cc
@@ -262,7 +262,7 @@ content->AddChildView(infobar2); View* root_view = content->parent(); - ASSERT_EQ(NULL, root_view->parent()); + ASSERT_EQ(nullptr, root_view->parent()); ComPtr<IAccessible2_2> root_view_accessible; GetIAccessible2InterfaceForView(root_view, &root_view_accessible);
diff --git a/ui/views/bubble/bubble_dialog_delegate_view.cc b/ui/views/bubble/bubble_dialog_delegate_view.cc index de7bb17..87033d7 100644 --- a/ui/views/bubble/bubble_dialog_delegate_view.cc +++ b/ui/views/bubble/bubble_dialog_delegate_view.cc
@@ -179,7 +179,7 @@ void BubbleDialogDelegateView::OnWidgetDestroying(Widget* widget) { if (anchor_widget() == widget) - SetAnchorView(NULL); + SetAnchorView(nullptr); } void BubbleDialogDelegateView::OnWidgetVisibilityChanging(Widget* widget, @@ -355,7 +355,7 @@ UpdateHighlightedButton(false); } anchor_widget_->RemoveObserver(this); - anchor_widget_ = NULL; + anchor_widget_ = nullptr; } if (anchor_view) { anchor_widget_ = anchor_view->GetWidget(); @@ -407,8 +407,8 @@ BubbleFrameView* BubbleDialogDelegateView::GetBubbleFrameView() const { const NonClientView* view = - GetWidget() ? GetWidget()->non_client_view() : NULL; - return view ? static_cast<BubbleFrameView*>(view->frame_view()) : NULL; + GetWidget() ? GetWidget()->non_client_view() : nullptr; + return view ? static_cast<BubbleFrameView*>(view->frame_view()) : nullptr; } void BubbleDialogDelegateView::UpdateColorsFromTheme(
diff --git a/ui/views/bubble/bubble_dialog_delegate_view_unittest.cc b/ui/views/bubble/bubble_dialog_delegate_view_unittest.cc index a7ba97b1..94ddd9f 100644 --- a/ui/views/bubble/bubble_dialog_delegate_view_unittest.cc +++ b/ui/views/bubble/bubble_dialog_delegate_view_unittest.cc
@@ -192,7 +192,7 @@ // is still kept, so that the bubble does not jump when the view gets deleted. anchor_widget->GetContentsView()->RemoveChildView(anchor_view.get()); anchor_view.reset(); - EXPECT_EQ(NULL, bubble_delegate->GetAnchorView()); + EXPECT_EQ(nullptr, bubble_delegate->GetAnchorView()); EXPECT_EQ(view_rect.ToString(), bubble_delegate->GetAnchorRect().ToString()); }
diff --git a/ui/views/button_drag_utils.cc b/ui/views/button_drag_utils.cc index c898239..56b8813 100644 --- a/ui/views/button_drag_utils.cc +++ b/ui/views/button_drag_utils.cc
@@ -46,9 +46,8 @@ const views::Widget& widget, ui::OSExchangeData* data) { // Create a button to render the drag image for us. - views::LabelButton button(NULL, - title.empty() ? base::UTF8ToUTF16(url.spec()) - : title); + views::LabelButton button( + nullptr, title.empty() ? base::UTF8ToUTF16(url.spec()) : title); button.SetTextSubpixelRenderingEnabled(false); const ui::NativeTheme* theme = widget.GetNativeTheme(); button.SetTextColor(views::Button::STATE_NORMAL,
diff --git a/ui/views/button_drag_utils.h b/ui/views/button_drag_utils.h index 360c3e4bc..02dbb807 100644 --- a/ui/views/button_drag_utils.h +++ b/ui/views/button_drag_utils.h
@@ -43,6 +43,6 @@ const views::Widget& widget, ui::OSExchangeData* data); -} // namespace drag_utils +} // namespace button_drag_utils #endif // UI_VIEWS_BUTTON_DRAG_UTILS_H_
diff --git a/ui/views/controls/button/image_button.cc b/ui/views/controls/button/image_button.cc index c366f55..eb262d2 100644 --- a/ui/views/controls/button/image_button.cc +++ b/ui/views/controls/button/image_button.cc
@@ -66,7 +66,7 @@ void ImageButton::SetBackgroundImage(SkColor color, const gfx::ImageSkia* image, const gfx::ImageSkia* mask) { - if (image == NULL || mask == NULL) { + if (image == nullptr || mask == nullptr) { background_image_ = gfx::ImageSkia(); return; }
diff --git a/ui/views/controls/button/image_button_factory.cc b/ui/views/controls/button/image_button_factory.cc index 479b7a1..7ee5b3b7 100644 --- a/ui/views/controls/button/image_button_factory.cc +++ b/ui/views/controls/button/image_button_factory.cc
@@ -103,4 +103,4 @@ button->SetToggledImage(Button::STATE_DISABLED, &disabled_image); } -} // views +} // namespace views
diff --git a/ui/views/controls/button/image_button_factory_unittest.cc b/ui/views/controls/button/image_button_factory_unittest.cc index 86d85eba..1a5f238c 100644 --- a/ui/views/controls/button/image_button_factory_unittest.cc +++ b/ui/views/controls/button/image_button_factory_unittest.cc
@@ -42,4 +42,4 @@ button->GetInkDropBaseColor()); delete button; } -} // views +} // namespace views
diff --git a/ui/views/controls/button/image_button_unittest.cc b/ui/views/controls/button/image_button_unittest.cc index 4c595a5d..dd25526 100644 --- a/ui/views/controls/button/image_button_unittest.cc +++ b/ui/views/controls/button/image_button_unittest.cc
@@ -49,7 +49,7 @@ typedef ViewsTestBase ImageButtonTest; TEST_F(ImageButtonTest, Basics) { - ImageButton button(NULL); + ImageButton button(nullptr); // Our image to paint starts empty. EXPECT_TRUE(button.GetImageToPaint().isNull()); @@ -97,7 +97,7 @@ } TEST_F(ImageButtonTest, SetAndGetImage) { - ImageButton button(NULL); + ImageButton button(nullptr); // Images start as null. EXPECT_TRUE(button.GetImage(Button::STATE_NORMAL).isNull()); @@ -118,12 +118,12 @@ EXPECT_TRUE(button.GetImage(Button::STATE_DISABLED).isNull()); // ImageButton supports NULL image pointers. - button.SetImage(Button::STATE_NORMAL, NULL); + button.SetImage(Button::STATE_NORMAL, nullptr); EXPECT_TRUE(button.GetImage(Button::STATE_NORMAL).isNull()); } TEST_F(ImageButtonTest, ImagePositionWithBorder) { - ImageButton button(NULL); + ImageButton button(nullptr); gfx::ImageSkia image = CreateTestImage(20, 30); button.SetImage(Button::STATE_NORMAL, &image); @@ -172,7 +172,7 @@ } TEST_F(ImageButtonTest, LeftAlignedMirrored) { - ImageButton button(NULL); + ImageButton button(nullptr); gfx::ImageSkia image = CreateTestImage(20, 30); button.SetImage(Button::STATE_NORMAL, &image); button.SetBounds(0, 0, 50, 30); @@ -190,7 +190,7 @@ } TEST_F(ImageButtonTest, RightAlignedMirrored) { - ImageButton button(NULL); + ImageButton button(nullptr); gfx::ImageSkia image = CreateTestImage(20, 30); button.SetImage(Button::STATE_NORMAL, &image); button.SetBounds(0, 0, 50, 30);
diff --git a/ui/views/controls/button/radio_button.cc b/ui/views/controls/button/radio_button.cc index 05cb8afe..72f955d 100644 --- a/ui/views/controls/button/radio_button.cc +++ b/ui/views/controls/button/radio_button.cc
@@ -40,7 +40,7 @@ Views views; GetViewsInGroupFromParent(group, &views); if (views.empty()) - return NULL; + return nullptr; for (Views::const_iterator i(views.begin()); i != views.end(); ++i) { // REVIEW: why don't we check the runtime type like is done above? @@ -48,7 +48,7 @@ if (radio_button->checked()) return radio_button; } - return NULL; + return nullptr; } bool RadioButton::IsGroupFocusTraversable() const {
diff --git a/ui/views/controls/focus_ring.h b/ui/views/controls/focus_ring.h index 226ce07..f5e22f6 100644 --- a/ui/views/controls/focus_ring.h +++ b/ui/views/controls/focus_ring.h
@@ -117,6 +117,6 @@ VIEWS_EXPORT SkPath GetHighlightPath(const View* view); -} // views +} // namespace views #endif // UI_VIEWS_CONTROLS_FOCUS_RING_H_
diff --git a/ui/views/controls/link.cc b/ui/views/controls/link.cc index b18b5a3..3e1f7fd 100644 --- a/ui/views/controls/link.cc +++ b/ui/views/controls/link.cc
@@ -219,7 +219,7 @@ } void Link::Init() { - listener_ = NULL; + listener_ = nullptr; pressed_ = false; underline_ = GetDefaultFocusStyle() != FocusStyle::UNDERLINE; RecalculateFont();
diff --git a/ui/views/controls/menu/display_change_listener_aura.cc b/ui/views/controls/menu/display_change_listener_aura.cc index 724bada87..d86bfbdb 100644 --- a/ui/views/controls/menu/display_change_listener_aura.cc +++ b/ui/views/controls/menu/display_change_listener_aura.cc
@@ -58,7 +58,7 @@ void AuraDisplayChangeListener::OnWindowDestroying(aura::Window* window) { DCHECK_EQ(window, root_window_); root_window_->RemoveObserver(this); - root_window_ = NULL; + root_window_ = nullptr; } // static
diff --git a/ui/views/controls/menu/menu_controller.cc b/ui/views/controls/menu/menu_controller.cc index df410ba..d6cc015 100644 --- a/ui/views/controls/menu/menu_controller.cc +++ b/ui/views/controls/menu/menu_controller.cc
@@ -115,7 +115,7 @@ // Returns the first descendant of |view| that is hot tracked. Button* GetFirstHotTrackedView(View* view) { if (!view) - return NULL; + return nullptr; Button* button = Button::AsButton(view); if (button && button->IsHotTracked()) return button; @@ -125,16 +125,17 @@ if (hot_view) return hot_view; } - return NULL; + return nullptr; } // Recurses through the child views of |view| returning the first view starting -// at |start| that is focusable. Children are considered first to last. +// at |pos| that is focusable. Children are considered first to last. // TODO(https://crbug.com/942358): This can also return |view|, which seems // incorrect. -View* GetFirstFocusableViewForward(View* view, int start) { - for (int i = start; i < view->child_count(); ++i) { - View* deepest = GetFirstFocusableViewForward(view->child_at(i), 0); +View* GetFirstFocusableViewForward(View* view, + View::Views::const_iterator pos) { + for (auto i = pos; i != view->children().cend(); ++i) { + View* deepest = GetFirstFocusableViewForward(*i, (*i)->children().cbegin()); if (deepest) return deepest; } @@ -142,10 +143,11 @@ } // As GetFirstFocusableViewForward(), but children are considered last to first. -View* GetFirstFocusableViewBackward(View* view, int start) { - for (int i = start; i >= 0; --i) { - View* deepest = GetFirstFocusableViewBackward(view->child_at(i), - view->child_count() - 1); +View* GetFirstFocusableViewBackward(View* view, + View::Views::const_reverse_iterator pos) { + for (auto i = pos; i != view->children().crend(); ++i) { + View* deepest = + GetFirstFocusableViewBackward(*i, (*i)->children().crbegin()); if (deepest) return deepest; } @@ -154,9 +156,9 @@ // Returns the first child of |start| that is focusable. View* GetInitialFocusableView(View* start, bool forward) { - return forward - ? GetFirstFocusableViewForward(start, 0) - : GetFirstFocusableViewBackward(start, start->child_count() - 1); + const auto& children = start->children(); + return forward ? GetFirstFocusableViewForward(start, children.cbegin()) + : GetFirstFocusableViewBackward(start, children.crbegin()); } // Returns the next view after |start_at| that is focusable. Returns null if @@ -166,9 +168,13 @@ View* parent = start_at; do { View* new_parent = parent->parent(); - int index = new_parent->GetIndexOf(parent); - View* next = forward ? GetFirstFocusableViewForward(new_parent, index + 1) - : GetFirstFocusableViewBackward(new_parent, index - 1); + const auto pos = new_parent->FindChild(parent); + // Subtle: make_reverse_iterator() will result in an iterator that refers to + // the element before its argument, which is what we want. + View* next = forward + ? GetFirstFocusableViewForward(new_parent, std::next(pos)) + : GetFirstFocusableViewBackward( + new_parent, std::make_reverse_iterator(pos)); if (next) return next; parent = new_parent; @@ -218,8 +224,8 @@ if (event->IsMouseEvent()) { HWND source_window = HWNDForNativeView(native_view); if (!target_window || !source_window || - GetWindowThreadProcessId(source_window, NULL) != - GetWindowThreadProcessId(target_window, NULL)) { + GetWindowThreadProcessId(source_window, nullptr) != + GetWindowThreadProcessId(target_window, nullptr)) { // Even though we have mouse capture, windows generates a mouse event if // the other window is in a separate thread. Only repost an event if // |target_window| and |source_window| were created on the same thread, @@ -300,7 +306,7 @@ class MenuController::MenuScrollTask { public: - MenuScrollTask() : submenu_(NULL), is_scrolling_up_(false), start_y_(0) { + MenuScrollTask() : submenu_(nullptr), is_scrolling_up_(false), start_y_(0) { pixels_per_second_ = MenuItemView::pref_menu_height() * 20; } @@ -330,7 +336,7 @@ void StopScrolling() { if (scrolling_timer_.IsRunning()) { scrolling_timer_.Stop(); - submenu_ = NULL; + submenu_ = nullptr; } } @@ -412,7 +418,7 @@ // MenuController ------------------------------------------------------------ // static -MenuController* MenuController::active_instance_ = NULL; +MenuController* MenuController::active_instance_ = nullptr; // static MenuController* MenuController::GetActiveInstance() { @@ -532,7 +538,7 @@ SendMouseCaptureLostToActiveView(); // Hide windows immediately. - SetSelection(NULL, SELECTION_UPDATE_IMMEDIATELY | SELECTION_EXIT); + SetSelection(nullptr, SELECTION_UPDATE_IMMEDIATELY | SELECTION_EXIT); if (for_drop_) { // If we didn't block the caller we need to notify the menu, which @@ -655,7 +661,7 @@ StartDrag(source, press_pt_); return true; } - MenuItemView* mouse_menu = NULL; + MenuItemView* mouse_menu = nullptr; if (part.type == MenuPart::MENU_ITEM) { // If there is no menu target, but a submenu target, then we are interacting // with an empty menu item within a submenu. These cannot become selection @@ -714,12 +720,12 @@ MenuItemView* menu = part.menu; // |menu| is NULL means this event is from an empty menu or a separator. // If it is from an empty menu, use parent context menu instead of that. - if (menu == NULL && part.submenu->child_count() == 1 && + if (menu == nullptr && part.submenu->child_count() == 1 && part.submenu->child_at(0)->id() == MenuItemView::kEmptyMenuItemViewID) { menu = part.parent; } - if (menu != NULL) { + if (menu != nullptr) { gfx::Point screen_location(event.location()); View::ConvertPointToScreen(source->GetScrollViewContainer(), &screen_location); @@ -1016,7 +1022,7 @@ if (drop_position == MenuDelegate::DROP_NONE || drop_operation == ui::DragDropTypes::DRAG_NONE) - menu_item = NULL; + menu_item = nullptr; } else { SetSelection(source->GetMenuItem(), SELECTION_OPEN_SUBMENU); } @@ -1030,7 +1036,7 @@ if (drop_target_) { StopShowTimer(); - SetDropMenuItem(NULL, MenuDelegate::DROP_NONE); + SetDropMenuItem(nullptr, MenuDelegate::DROP_NONE); } } @@ -1047,7 +1053,7 @@ MenuDelegate::DropPosition drop_position = drop_position_; // Close all menus, including any nested menus. - SetSelection(NULL, SELECTION_UPDATE_IMMEDIATELY | SELECTION_EXIT); + SetSelection(nullptr, SELECTION_UPDATE_IMMEDIATELY | SELECTION_EXIT); CloseAllNestedMenus(); // Set state such that we exit. @@ -1085,7 +1091,7 @@ void MenuController::OnDragExitedScrollButton(SubmenuView* source) { StartCancelAllTimer(); - SetDropMenuItem(NULL, MenuDelegate::DROP_NONE); + SetDropMenuItem(nullptr, MenuDelegate::DROP_NONE); StopScrolling(); } @@ -1217,7 +1223,7 @@ void MenuController::OnWidgetDestroying(Widget* widget) { DCHECK_EQ(owner_, widget); owner_->RemoveObserver(this); - owner_ = NULL; + owner_ = nullptr; } bool MenuController::IsCancelAllTimerRunningForTest() { @@ -1277,7 +1283,7 @@ // Notify the old path it isn't selected. MenuDelegate* current_delegate = - current_path.empty() ? NULL : current_path.front()->GetDelegate(); + current_path.empty() ? nullptr : current_path.front()->GetDelegate(); for (size_t i = paths_differ_at; i < current_size; ++i) { if (current_delegate && (current_path[i]->GetType() == MenuItemView::SUBMENU || @@ -1401,7 +1407,7 @@ did_initiate_drag_ = true; base::WeakPtr<MenuController> this_ref = AsWeakPtr(); // TODO(varunjain): Properly determine and send DRAG_EVENT_SOURCE below. - item->GetWidget()->RunShellDrag(NULL, data, widget_loc, drag_ops, + item->GetWidget()->RunShellDrag(nullptr, data, widget_loc, drag_ops, ui::DragDropTypes::DRAG_EVENT_SOURCE_MOUSE); // MenuController may have been deleted so check before accessing member // variables. @@ -1561,7 +1567,7 @@ if (owner_) owner_->RemoveObserver(this); if (active_instance_ == this) - active_instance_ = NULL; + active_instance_ = nullptr; StopShowTimer(); StopCancelAllTimer(); } @@ -1669,7 +1675,7 @@ View::ConvertPointToScreen(source_view, &screen_point); MenuAnchorPosition anchor; bool has_mnemonics; - MenuButton* button = NULL; + MenuButton* button = nullptr; MenuItemView* alt_menu = source->GetMenuItem()->GetDelegate()->GetSiblingMenu( source->GetMenuItem()->GetRootMenuItem(), screen_point, &anchor, &has_mnemonics, &button); @@ -1750,7 +1756,7 @@ child_under_mouse->id() == MenuItemView::kMenuItemViewID) { return static_cast<MenuItemView*>(child_under_mouse); } - return NULL; + return nullptr; } MenuItemView* MenuController::GetEmptyMenuItemAt(View* source, int x, int y) { @@ -1759,7 +1765,7 @@ child_under_mouse->id() == MenuItemView::kEmptyMenuItemViewID) { return static_cast<MenuItemView*>(child_under_mouse); } - return NULL; + return nullptr; } bool MenuController::IsScrollButtonAt(SubmenuView* source, @@ -2496,7 +2502,7 @@ } } - if (item->has_children()) { + if (!item->children().empty()) { Button* button = GetFirstHotTrackedView(item); if (button) { DCHECK_EQ(hot_button_, button); @@ -2539,7 +2545,7 @@ continue; bool found_focusable = false; - if (item->has_children()) { + if (!item->children().empty()) { for (View* child = GetInitialFocusableView(item, true); child; child = GetNextFocusableView(item, child, true)) { ordering.push_back(child); @@ -2622,7 +2628,7 @@ MenuItemView* item = pending_state_.item; if (!item->HasSubmenu() || !item->enabled()) return; - MenuItemView* to_select = NULL; + MenuItemView* to_select = nullptr; if (item->GetSubmenu()->GetMenuItemCount() > 0) to_select = FindInitialSelectableMenuItem(item, INCREMENT_SELECTION_DOWN); if (to_select) { @@ -2806,7 +2812,7 @@ if (drop_target_) { drop_target_->GetParentMenuItem()->GetSubmenu()->SetDropMenuItem( - NULL, MenuDelegate::DROP_NONE); + nullptr, MenuDelegate::DROP_NONE); } drop_target_ = new_target; drop_position_ = new_position; @@ -2826,15 +2832,15 @@ } void MenuController::StopScrolling() { - scroll_task_.reset(NULL); + scroll_task_.reset(nullptr); } void MenuController::UpdateActiveMouseView(SubmenuView* event_source, const ui::MouseEvent& event, View* target_menu) { - View* target = NULL; + View* target = nullptr; gfx::Point target_menu_loc(event.location()); - if (target_menu && target_menu->has_children()) { + if (target_menu && !target_menu->children().empty()) { // Locate the deepest child view to send events to. This code assumes we // don't have to walk up the tree to find a view interested in events. This // is currently true for the cases we are embedding views, but if we embed @@ -2844,7 +2850,7 @@ View::ConvertPointFromScreen(target_menu, &target_menu_loc); target = target_menu->GetEventHandlerForPoint(target_menu_loc); if (target == target_menu || !target->enabled()) - target = NULL; + target = nullptr; } View* active_mouse_view = active_mouse_view_tracker_->view(); if (target != active_mouse_view) {
diff --git a/ui/views/controls/menu/menu_controller_delegate.h b/ui/views/controls/menu/menu_controller_delegate.h index 273ec7b..e875413 100644 --- a/ui/views/controls/menu/menu_controller_delegate.h +++ b/ui/views/controls/menu/menu_controller_delegate.h
@@ -38,6 +38,6 @@ } // namespace internal -} // namespace view +} // namespace views #endif // UI_VIEWS_CONTROLS_MENU_MENU_CONTROLLER_DELEGATE_H_
diff --git a/ui/views/controls/menu/menu_delegate.cc b/ui/views/controls/menu/menu_delegate.cc index d6157d86..7dd6ba0 100644 --- a/ui/views/controls/menu/menu_delegate.cc +++ b/ui/views/controls/menu/menu_delegate.cc
@@ -125,7 +125,7 @@ MenuAnchorPosition* anchor, bool* has_mnemonics, MenuButton** button) { - return NULL; + return nullptr; } int MenuDelegate::GetMaxWidthForMenu(MenuItemView* menu) {
diff --git a/ui/views/controls/menu/menu_host_root_view.cc b/ui/views/controls/menu/menu_host_root_view.cc index bb72234..bbb1290 100644 --- a/ui/views/controls/menu/menu_host_root_view.cc +++ b/ui/views/controls/menu/menu_host_root_view.cc
@@ -85,7 +85,7 @@ } MenuController* MenuHostRootView::GetMenuController() { - return submenu_ ? submenu_->GetMenuItem()->GetMenuController() : NULL; + return submenu_ ? submenu_->GetMenuItem()->GetMenuController() : nullptr; } MenuController* MenuHostRootView::GetMenuControllerForInputEvents() {
diff --git a/ui/views/controls/menu/menu_host_root_view.h b/ui/views/controls/menu/menu_host_root_view.h index 401e6e9..cbc09c7 100644 --- a/ui/views/controls/menu/menu_host_root_view.h +++ b/ui/views/controls/menu/menu_host_root_view.h
@@ -23,7 +23,7 @@ public: MenuHostRootView(Widget* widget, SubmenuView* submenu); - void ClearSubmenu() { submenu_ = NULL; } + void ClearSubmenu() { submenu_ = nullptr; } // Overridden from View: bool OnMousePressed(const ui::MouseEvent& event) override;
diff --git a/ui/views/controls/menu/menu_item_view.cc b/ui/views/controls/menu/menu_item_view.cc index 0eab270..46d2e3be 100644 --- a/ui/views/controls/menu/menu_item_view.cc +++ b/ui/views/controls/menu/menu_item_view.cc
@@ -99,17 +99,17 @@ MenuItemView::MenuItemView(MenuDelegate* delegate) : delegate_(delegate), - controller_(NULL), + controller_(nullptr), canceled_(false), - parent_menu_item_(NULL), + parent_menu_item_(nullptr), type_(SUBMENU), selected_(false), command_(0), - submenu_(NULL), + submenu_(nullptr), has_mnemonics_(false), show_mnemonics_(false), has_icons_(false), - icon_view_(NULL), + icon_view_(nullptr), top_margin_(-1), bottom_margin_(-1), left_icon_margin_(0), @@ -119,7 +119,7 @@ use_right_margin_(true) { // NOTE: don't check the delegate for NULL, UpdateMenuPartSizes() supplies a // NULL delegate. - Init(NULL, 0, SUBMENU, delegate); + Init(nullptr, 0, SUBMENU, delegate); } void MenuItemView::ChildPreferredSizeChanged(View* child) { @@ -320,8 +320,8 @@ void MenuItemView::RemoveAllMenuItems() { DCHECK(submenu_); - for (int i = 0; i < submenu_->child_count(); ++i) - removed_items_.push_back(submenu_->child_at(i)); + removed_items_.insert(removed_items_.end(), submenu_->children().begin(), + submenu_->children().end()); submenu_->RemoveAllChildViews(false); } @@ -406,7 +406,7 @@ } bool MenuItemView::HasSubmenu() const { - return (submenu_ != NULL); + return (submenu_ != nullptr); } SubmenuView* MenuItemView::GetSubmenu() const { @@ -469,7 +469,7 @@ void MenuItemView::SetIcon(const gfx::ImageSkia& icon) { if (icon.isNull()) { - SetIconView(NULL); + SetIconView(nullptr); return; } @@ -482,7 +482,7 @@ if (icon_view_) { RemoveChildView(icon_view_); delete icon_view_; - icon_view_ = NULL; + icon_view_ = nullptr; } if (icon_view) { AddChildView(icon_view); @@ -588,7 +588,7 @@ if (GetCommand() == id) return this; if (!HasSubmenu()) - return NULL; + return nullptr; for (int i = 0; i < GetSubmenu()->child_count(); ++i) { View* child = GetSubmenu()->child_at(i); if (child->id() == MenuItemView::kMenuItemViewID) { @@ -598,7 +598,7 @@ return result; } } - return NULL; + return nullptr; } void MenuItemView::ChildrenChanged() { @@ -629,7 +629,7 @@ } void MenuItemView::Layout() { - if (!has_children()) + if (children().empty()) return; if (IsContainer()) { @@ -733,18 +733,18 @@ MenuItemView::MenuItemView(MenuItemView* parent, int command, MenuItemView::Type type) - : delegate_(NULL), - controller_(NULL), + : delegate_(nullptr), + controller_(nullptr), canceled_(false), parent_menu_item_(parent), type_(type), selected_(false), command_(command), - submenu_(NULL), + submenu_(nullptr), has_mnemonics_(false), show_mnemonics_(false), has_icons_(false), - icon_view_(NULL), + icon_view_(nullptr), top_margin_(-1), bottom_margin_(-1), left_icon_margin_(0), @@ -752,7 +752,7 @@ requested_menu_position_(POSITION_BEST_FIT), actual_menu_position_(requested_menu_position_), use_right_margin_(true) { - Init(parent, command, type, NULL); + Init(parent, command, type, nullptr); } MenuItemView::~MenuItemView() { @@ -942,7 +942,7 @@ } else if (child->id() == EmptyMenuMenuItem::kEmptyMenuItemViewID) { submenu_->RemoveChildView(child); delete child; - child = NULL; + child = nullptr; } } } @@ -1180,7 +1180,7 @@ } gfx::Size MenuItemView::GetChildPreferredSize() const { - if (!has_children()) + if (children().empty()) return gfx::Size(); if (IsContainer())
diff --git a/ui/views/controls/menu/menu_model_adapter_unittest.cc b/ui/views/controls/menu/menu_model_adapter_unittest.cc index 5e3850a0..93fb3421 100644 --- a/ui/views/controls/menu/menu_model_adapter_unittest.cc +++ b/ui/views/controls/menu/menu_model_adapter_unittest.cc
@@ -56,7 +56,7 @@ bool IsItemDynamicAt(int index) const override { return false; } const gfx::FontList* GetLabelFontListAt(int index) const override { - return NULL; + return nullptr; } bool GetAcceleratorAt(int index, @@ -71,7 +71,7 @@ bool GetIconAt(int index, gfx::Image* icon) override { return false; } ui::ButtonMenuItemModel* GetButtonMenuItemAt(int index) const override { - return NULL; + return nullptr; } bool IsEnabledAt(int index) const override { return items_[index].enabled; } @@ -142,8 +142,9 @@ class SubmenuModel : public MenuModelBase { public: SubmenuModel() : MenuModelBase(kSubmenuIdBase) { - items_.push_back(Item(TYPE_COMMAND, "submenu item 0", NULL, false, true)); - items_.push_back(Item(TYPE_COMMAND, "submenu item 1", NULL)); + items_.push_back( + Item(TYPE_COMMAND, "submenu item 0", nullptr, false, true)); + items_.push_back(Item(TYPE_COMMAND, "submenu item 1", nullptr)); } ~SubmenuModel() override {} @@ -155,8 +156,8 @@ class ActionableSubmenuModel : public MenuModelBase { public: ActionableSubmenuModel() : MenuModelBase(kActionableSubmenuIdBase) { - items_.push_back(Item(TYPE_COMMAND, "actionable submenu item 0", NULL)); - items_.push_back(Item(TYPE_COMMAND, "actionable submenu item 1", NULL)); + items_.push_back(Item(TYPE_COMMAND, "actionable submenu item 0", nullptr)); + items_.push_back(Item(TYPE_COMMAND, "actionable submenu item 1", nullptr)); } ~ActionableSubmenuModel() override = default; @@ -170,11 +171,11 @@ submenu_model_ = std::make_unique<SubmenuModel>(); actionable_submenu_model_ = std::make_unique<ActionableSubmenuModel>(); - items_.push_back(Item(TYPE_COMMAND, "command 0", NULL, false, false)); - items_.push_back(Item(TYPE_CHECK, "check 1", NULL)); - items_.push_back(Item(TYPE_SEPARATOR, "", NULL)); + items_.push_back(Item(TYPE_COMMAND, "command 0", nullptr, false, false)); + items_.push_back(Item(TYPE_CHECK, "check 1", nullptr)); + items_.push_back(Item(TYPE_SEPARATOR, "", nullptr)); items_.push_back(Item(TYPE_SUBMENU, "submenu 3", submenu_model_.get())); - items_.push_back(Item(TYPE_RADIO, "radio 4", NULL)); + items_.push_back(Item(TYPE_RADIO, "radio 4", nullptr)); items_.push_back(Item(TYPE_ACTIONABLE_SUBMENU, "actionable 5", actionable_submenu_model_.get())); }
diff --git a/ui/views/controls/menu/menu_runner.h b/ui/views/controls/menu/menu_runner.h index 4d8f79a..526c166 100644 --- a/ui/views/controls/menu/menu_runner.h +++ b/ui/views/controls/menu/menu_runner.h
@@ -61,6 +61,8 @@ class VIEWS_EXPORT MenuRunner { public: enum RunTypes { + NO_FLAGS = 0, + // The menu has mnemonics. HAS_MNEMONICS = 1 << 0,
diff --git a/ui/views/controls/menu/menu_runner_impl.cc b/ui/views/controls/menu/menu_runner_impl.cc index c96ba576..cc3ff7d 100644 --- a/ui/views/controls/menu/menu_runner_impl.cc +++ b/ui/views/controls/menu/menu_runner_impl.cc
@@ -38,7 +38,7 @@ running_(false), delete_after_run_(false), for_drop_(false), - controller_(NULL), + controller_(nullptr), owns_controller_(false), weak_factory_(this) {}
diff --git a/ui/views/controls/menu/submenu_view.cc b/ui/views/controls/menu/submenu_view.cc index 0796aec6..4cfed6c 100644 --- a/ui/views/controls/menu/submenu_view.cc +++ b/ui/views/controls/menu/submenu_view.cc
@@ -38,10 +38,10 @@ SubmenuView::SubmenuView(MenuItemView* parent) : parent_menu_item_(parent), - host_(NULL), - drop_item_(NULL), + host_(nullptr), + drop_item_(nullptr), drop_position_(MenuDelegate::DROP_NONE), - scroll_view_container_(NULL), + scroll_view_container_(nullptr), max_minor_text_width_(0), minimum_preferred_width_(0), resize_open_menu_(false), @@ -94,7 +94,7 @@ } } NOTREACHED(); - return NULL; + return nullptr; } PrefixSelector* SubmenuView::GetPrefixSelector() { @@ -144,7 +144,7 @@ } gfx::Size SubmenuView::CalculatePreferredSize() const { - if (!has_children()) + if (children().empty()) return gfx::Size(); max_minor_text_width_ = 0; @@ -423,7 +423,7 @@ ax::mojom::Event::kMenuEnd, true); host_->DestroyMenuHost(); - host_ = NULL; + host_ = nullptr; } } @@ -461,7 +461,7 @@ } bool SubmenuView::GetShowSelection(MenuItemView* item) { - if (drop_item_ == NULL) + if (drop_item_ == nullptr) return true; // Something is being dropped on one of this menus items. Show the // selection if the drop is on the passed in item and the drop position is @@ -487,7 +487,7 @@ } void SubmenuView::MenuHostDestroyed() { - host_ = NULL; + host_ = nullptr; MenuController* controller = GetMenuItem()->GetMenuController(); if (controller) controller->Cancel(MenuController::EXIT_DESTROYED); @@ -504,7 +504,7 @@ void SubmenuView::SchedulePaintForDropIndicator( MenuItemView* item, MenuDelegate::DropPosition position) { - if (item == NULL) + if (item == nullptr) return; if (position == MenuDelegate::DROP_ON) {
diff --git a/ui/views/controls/message_box_view.cc b/ui/views/controls/message_box_view.cc index 36db578..213b50cd 100644 --- a/ui/views/controls/message_box_view.cc +++ b/ui/views/controls/message_box_view.cc
@@ -84,9 +84,9 @@ } MessageBoxView::MessageBoxView(const InitParams& params) - : prompt_field_(NULL), - checkbox_(NULL), - link_(NULL), + : prompt_field_(nullptr), + checkbox_(nullptr), + link_(nullptr), message_width_(params.message_width) { Init(params); } @@ -120,7 +120,7 @@ if (text.empty()) { DCHECK(!listener); delete link_; - link_ = NULL; + link_ = nullptr; } else { DCHECK(listener); if (!link_) {
diff --git a/ui/views/controls/native/native_view_host.cc b/ui/views/controls/native/native_view_host.cc index f8c2e3e..5d9e3f60 100644 --- a/ui/views/controls/native/native_view_host.cc +++ b/ui/views/controls/native/native_view_host.cc
@@ -21,11 +21,10 @@ // NativeViewHost, public: NativeViewHost::NativeViewHost() - : native_view_(NULL), + : native_view_(nullptr), fast_resize_(false), fast_resize_at_last_layout_(false), - resize_background_color_(SK_ColorWHITE) { -} + resize_background_color_(SK_ColorWHITE) {} NativeViewHost::~NativeViewHost() { // As part of deleting NativeViewHostWrapper the native view is unparented. @@ -231,11 +230,11 @@ if (!destroyed) { Widget* widget = Widget::GetWidgetForNativeView(native_view_); if (widget) - widget->SetNativeWindowProperty(kWidgetNativeViewHostKey, NULL); + widget->SetNativeWindowProperty(kWidgetNativeViewHostKey, nullptr); ClearFocus(); } native_wrapper_->NativeViewDetaching(destroyed); - native_view_ = NULL; + native_view_ = nullptr; } }
diff --git a/ui/views/controls/native/native_view_host_aura.cc b/ui/views/controls/native/native_view_host_aura.cc index 293814b0..8e1180a 100644 --- a/ui/views/controls/native/native_view_host_aura.cc +++ b/ui/views/controls/native/native_view_host_aura.cc
@@ -28,7 +28,7 @@ class NativeViewHostAura::ClippingWindowDelegate : public aura::WindowDelegate { public: - ClippingWindowDelegate() : native_view_(NULL) {} + ClippingWindowDelegate() : native_view_(nullptr) {} ~ClippingWindowDelegate() override {} void set_native_view(aura::Window* native_view) { @@ -117,7 +117,7 @@ if (clipping_window_) pause_occlusion.emplace(clipping_window_->env()); - clipping_window_delegate_->set_native_view(NULL); + clipping_window_delegate_->set_native_view(nullptr); RemoveClippingWindow(); if (!destroyed) { host_->native_view()->RemoveObserver(this); @@ -129,7 +129,7 @@ host_->native_view()->SetTransform(original_transform_); host_->native_view()->Hide(); if (host_->native_view()->parent()) - Widget::ReparentNativeView(host_->native_view(), NULL); + Widget::ReparentNativeView(host_->native_view(), nullptr); } } @@ -248,7 +248,7 @@ } gfx::NativeViewAccessible NativeViewHostAura::GetNativeViewAccessible() { - return NULL; + return nullptr; } gfx::NativeCursor NativeViewHostAura::GetCursor(int x, int y) { @@ -282,7 +282,7 @@ void NativeViewHostAura::OnWindowDestroying(aura::Window* window) { DCHECK(window == host_->native_view()); - clipping_window_delegate_->set_native_view(NULL); + clipping_window_delegate_->set_native_view(nullptr); } void NativeViewHostAura::OnWindowDestroyed(aura::Window* window) {
diff --git a/ui/views/controls/native/native_view_host_unittest.cc b/ui/views/controls/native/native_view_host_unittest.cc index 0baba825..c5e1b52f 100644 --- a/ui/views/controls/native/native_view_host_unittest.cc +++ b/ui/views/controls/native/native_view_host_unittest.cc
@@ -76,11 +76,11 @@ // Overriden from NativeViewHost: void ViewHierarchyChanged( const ViewHierarchyChangedDetails& details) override { - gfx::NativeView parent_before = native_view() ? - GetNativeParent(native_view()) : NULL; + gfx::NativeView parent_before = + native_view() ? GetNativeParent(native_view()) : nullptr; NativeViewHost::ViewHierarchyChanged(details); - gfx::NativeView parent_after = native_view() ? - GetNativeParent(native_view()) : NULL; + gfx::NativeView parent_after = + native_view() ? GetNativeParent(native_view()) : nullptr; if (parent_before != parent_after) ++num_parent_changes_; }
diff --git a/ui/views/controls/scroll_view.cc b/ui/views/controls/scroll_view.cc index 0b467604..efa6393 100644 --- a/ui/views/controls/scroll_view.cc +++ b/ui/views/controls/scroll_view.cc
@@ -122,7 +122,7 @@ const char* GetClassName() const override { return "ScrollView::Viewport"; } void ScrollRectToVisible(const gfx::Rect& rect) override { - if (!has_children() || !parent()) + if (children().empty() || !parent()) return; View* contents = child_at(0); @@ -1007,7 +1007,7 @@ FixedRowHeightScrollHelper::FixedRowHeightScrollHelper(int top_margin, int row_height) - : VariableRowHeightScrollHelper(NULL), + : VariableRowHeightScrollHelper(nullptr), top_margin_(top_margin), row_height_(row_height) { DCHECK_GT(row_height, 0);
diff --git a/ui/views/controls/scroll_view_unittest.cc b/ui/views/controls/scroll_view_unittest.cc index 6f0a067b..ee73ff1 100644 --- a/ui/views/controls/scroll_view_unittest.cc +++ b/ui/views/controls/scroll_view_unittest.cc
@@ -451,7 +451,7 @@ CheckScrollbarVisibility(scroll_view_.get(), HORIZONTAL, false); EXPECT_TRUE(!scroll_view_->horizontal_scroll_bar() || !scroll_view_->horizontal_scroll_bar()->visible()); - ASSERT_TRUE(scroll_view_->vertical_scroll_bar() != NULL); + ASSERT_TRUE(scroll_view_->vertical_scroll_bar() != nullptr); EXPECT_TRUE(scroll_view_->vertical_scroll_bar()->visible()); // Size the contents such that horizontal scrollbar is needed. @@ -488,7 +488,7 @@ EXPECT_EQ(100 - kTopPadding - kBottomPadding, contents->parent()->height()); EXPECT_TRUE(!scroll_view_->horizontal_scroll_bar() || !scroll_view_->horizontal_scroll_bar()->visible()); - ASSERT_TRUE(scroll_view_->vertical_scroll_bar() != NULL); + ASSERT_TRUE(scroll_view_->vertical_scroll_bar() != nullptr); EXPECT_TRUE(scroll_view_->vertical_scroll_bar()->visible()); gfx::Rect bounds = scroll_view_->vertical_scroll_bar()->bounds(); EXPECT_EQ(100 - VerticalScrollBarWidth() - kRightPadding, bounds.x()); @@ -503,7 +503,7 @@ EXPECT_EQ(100 - scroll_view_->GetScrollBarLayoutHeight() - kTopPadding - kBottomPadding, contents->parent()->height()); - ASSERT_TRUE(scroll_view_->horizontal_scroll_bar() != NULL); + ASSERT_TRUE(scroll_view_->horizontal_scroll_bar() != nullptr); EXPECT_TRUE(scroll_view_->horizontal_scroll_bar()->visible()); EXPECT_TRUE(!scroll_view_->vertical_scroll_bar() || !scroll_view_->vertical_scroll_bar()->visible()); @@ -524,7 +524,7 @@ contents->parent()->height()); bounds = scroll_view_->horizontal_scroll_bar()->bounds(); // Check horiz. - ASSERT_TRUE(scroll_view_->horizontal_scroll_bar() != NULL); + ASSERT_TRUE(scroll_view_->horizontal_scroll_bar() != nullptr); EXPECT_TRUE(scroll_view_->horizontal_scroll_bar()->visible()); bounds = scroll_view_->horizontal_scroll_bar()->bounds(); EXPECT_EQ(kLeftPadding, bounds.x()); @@ -532,7 +532,7 @@ EXPECT_EQ(100 - kBottomPadding - HorizontalScrollBarHeight(), bounds.y()); EXPECT_EQ(100 - kBottomPadding, bounds.bottom()); // Check vert. - ASSERT_TRUE(scroll_view_->vertical_scroll_bar() != NULL); + ASSERT_TRUE(scroll_view_->vertical_scroll_bar() != nullptr); EXPECT_TRUE(scroll_view_->vertical_scroll_bar()->visible()); bounds = scroll_view_->vertical_scroll_bar()->bounds(); EXPECT_EQ(100 - VerticalScrollBarWidth() - kRightPadding, bounds.x()); @@ -576,9 +576,9 @@ EXPECT_EQ("0,0 0x0", contents->bounds().ToString()); // Remove the header. - scroll_view_->SetHeader(NULL); - // SetHeader(NULL) deletes header. - header = NULL; + scroll_view_->SetHeader(nullptr); + // SetHeader(nullptr) deletes header. + header = nullptr; EXPECT_EQ("0,0 100x0", header_parent->bounds().ToString()); EXPECT_EQ("0,0 100x100", contents->parent()->bounds().ToString()); } @@ -606,7 +606,7 @@ EXPECT_EQ(20, header->parent()->height()); EXPECT_TRUE(!scroll_view_->horizontal_scroll_bar() || !scroll_view_->horizontal_scroll_bar()->visible()); - ASSERT_TRUE(scroll_view_->vertical_scroll_bar() != NULL); + ASSERT_TRUE(scroll_view_->vertical_scroll_bar() != nullptr); EXPECT_TRUE(scroll_view_->vertical_scroll_bar()->visible()); // Make sure the vertical scrollbar overlaps the header for traditional // scrollbars and doesn't overlap the header for overlay scrollbars. @@ -629,7 +629,7 @@ EXPECT_EQ(0, header->parent()->y()); EXPECT_EQ(100, header->parent()->width()); EXPECT_EQ(20, header->parent()->height()); - ASSERT_TRUE(scroll_view_->horizontal_scroll_bar() != NULL); + ASSERT_TRUE(scroll_view_->horizontal_scroll_bar() != nullptr); EXPECT_TRUE(scroll_view_->horizontal_scroll_bar()->visible()); EXPECT_TRUE(!scroll_view_->vertical_scroll_bar() || !scroll_view_->vertical_scroll_bar()->visible()); @@ -648,9 +648,9 @@ EXPECT_EQ(100 - scroll_view_->GetScrollBarLayoutWidth(), header->parent()->width()); EXPECT_EQ(20, header->parent()->height()); - ASSERT_TRUE(scroll_view_->horizontal_scroll_bar() != NULL); + ASSERT_TRUE(scroll_view_->horizontal_scroll_bar() != nullptr); EXPECT_TRUE(scroll_view_->horizontal_scroll_bar()->visible()); - ASSERT_TRUE(scroll_view_->vertical_scroll_bar() != NULL); + ASSERT_TRUE(scroll_view_->vertical_scroll_bar() != nullptr); EXPECT_TRUE(scroll_view_->vertical_scroll_bar()->visible()); }
diff --git a/ui/views/controls/scrollbar/scroll_bar.cc b/ui/views/controls/scrollbar/scroll_bar.cc index be7c83e..3f13da4 100644 --- a/ui/views/controls/scrollbar/scroll_bar.cc +++ b/ui/views/controls/scrollbar/scroll_bar.cc
@@ -34,9 +34,6 @@ void ScrollBar::ObserveScrollEvent(const ui::ScrollEvent& event) {} ScrollBar::ScrollBar(bool is_horiz) - : is_horiz_(is_horiz), - controller_(NULL), - max_pos_(0) { -} + : is_horiz_(is_horiz), controller_(nullptr), max_pos_(0) {} } // namespace views
diff --git a/ui/views/controls/slider_unittest.cc b/ui/views/controls/slider_unittest.cc index 96900eb..9c3ded8 100644 --- a/ui/views/controls/slider_unittest.cc +++ b/ui/views/controls/slider_unittest.cc
@@ -82,24 +82,23 @@ }; TestSliderListener::TestSliderListener() - : last_event_epoch_(0), - last_drag_started_epoch_(-1), - last_drag_ended_epoch_(-1), - last_drag_started_sender_(NULL), - last_drag_ended_sender_(NULL) { -} + : last_event_epoch_(0), + last_drag_started_epoch_(-1), + last_drag_ended_epoch_(-1), + last_drag_started_sender_(nullptr), + last_drag_ended_sender_(nullptr) {} TestSliderListener::~TestSliderListener() { - last_drag_started_sender_ = NULL; - last_drag_ended_sender_ = NULL; + last_drag_started_sender_ = nullptr; + last_drag_ended_sender_ = nullptr; } void TestSliderListener::ResetCallHistory() { last_event_epoch_ = 0; last_drag_started_epoch_ = -1; last_drag_ended_epoch_ = -1; - last_drag_started_sender_ = NULL; - last_drag_ended_sender_ = NULL; + last_drag_started_sender_ = nullptr; + last_drag_ended_sender_ = nullptr; } void TestSliderListener::SliderValueChanged(views::Slider* sender,
diff --git a/ui/views/controls/styled_label_unittest.cc b/ui/views/controls/styled_label_unittest.cc index 9e70a550..4eafe19 100644 --- a/ui/views/controls/styled_label_unittest.cc +++ b/ui/views/controls/styled_label_unittest.cc
@@ -567,16 +567,16 @@ // controls should be created after layout // height should be the same as precalculated int real_height = styled()->GetHeightForWidth(styled()->width()); - View* first_child_after_layout = styled()->has_children() ? - styled()->child_at(0) : nullptr; + View* first_child_after_layout = + styled()->children().empty() ? nullptr : styled()->child_at(0); EXPECT_LT(0, styled()->child_count()); EXPECT_LT(0, real_height); EXPECT_EQ(real_height, precalculated_height); // another call to Layout should not kill and recreate all controls styled()->Layout(); - View* first_child_after_second_layout = styled()->has_children() ? - styled()->child_at(0) : nullptr; + View* first_child_after_second_layout = + styled()->children().empty() ? nullptr : styled()->child_at(0); EXPECT_EQ(first_child_after_layout, first_child_after_second_layout); // if text is changed: @@ -585,8 +585,8 @@ styled()->SetText(another_text); int updated_height = styled()->GetHeightForWidth(styled()->width()); EXPECT_NE(updated_height, real_height); - View* first_child_after_text_update = styled()->has_children() ? - styled()->child_at(0) : nullptr; + View* first_child_after_text_update = + styled()->children().empty() ? nullptr : styled()->child_at(0); EXPECT_NE(first_child_after_text_update, first_child_after_layout); }
diff --git a/ui/views/controls/tabbed_pane/tabbed_pane.cc b/ui/views/controls/tabbed_pane/tabbed_pane.cc index b7674192..e363b08 100644 --- a/ui/views/controls/tabbed_pane/tabbed_pane.cc +++ b/ui/views/controls/tabbed_pane/tabbed_pane.cc
@@ -671,7 +671,7 @@ TabbedPane::TabbedPane(TabbedPane::Orientation orientation, TabbedPane::TabStripStyle style) - : listener_(NULL), contents_(new View()) { + : listener_(nullptr), contents_(new View()) { DCHECK(orientation != TabbedPane::Orientation::kHorizontal || style != TabbedPane::TabStripStyle::kHighlight); tab_strip_ = new MdTabStrip(orientation, style);
diff --git a/ui/views/controls/table/table_grouper.h b/ui/views/controls/table/table_grouper.h index ce100e4c..ac879bd1 100644 --- a/ui/views/controls/table/table_grouper.h +++ b/ui/views/controls/table/table_grouper.h
@@ -25,6 +25,6 @@ virtual ~TableGrouper() {} }; -} +} // namespace views #endif // UI_VIEWS_CONTROLS_TABLE_GROUP_TABLE_VIEW_H_
diff --git a/ui/views/controls/table/table_header.cc b/ui/views/controls/table/table_header.cc index 4964194..3ca38608 100644 --- a/ui/views/controls/table/table_header.cc +++ b/ui/views/controls/table/table_header.cc
@@ -194,7 +194,7 @@ } void TableHeader::OnMouseReleased(const ui::MouseEvent& event) { - const bool was_resizing = resize_details_ != NULL; + const bool was_resizing = resize_details_ != nullptr; resize_details_.reset(); if (!was_resizing && event.IsOnlyLeftMouseButton()) ToggleSortOrder(event);
diff --git a/ui/views/controls/table/table_header.h b/ui/views/controls/table/table_header.h index 74b1dbb..76c7692 100644 --- a/ui/views/controls/table/table_header.h +++ b/ui/views/controls/table/table_header.h
@@ -76,7 +76,7 @@ // is not in the resize range of any columns. int GetResizeColumn(int x) const; - bool is_resizing() const { return resize_details_.get() != NULL; } + bool is_resizing() const { return resize_details_.get() != nullptr; } const gfx::FontList font_list_;
diff --git a/ui/views/controls/table/table_view.cc b/ui/views/controls/table/table_view.cc index d782796..627a970e 100644 --- a/ui/views/controls/table/table_view.cc +++ b/ui/views/controls/table/table_view.cc
@@ -145,17 +145,17 @@ const std::vector<ui::TableColumn>& columns, TableTypes table_type, bool single_selection) - : model_(NULL), + : model_(nullptr), columns_(columns), active_visible_column_index_(-1), header_(nullptr), table_type_(table_type), single_selection_(single_selection), select_on_remove_(true), - observer_(NULL), + observer_(nullptr), last_parent_width_(0), layout_width_(0), - grouper_(NULL), + grouper_(nullptr), in_set_visible_column_width_(false) { constexpr int kTextContext = style::CONTEXT_TABLE_ROW; constexpr int kTextStyle = style::STYLE_PRIMARY; @@ -178,7 +178,7 @@ TableView::~TableView() { if (model_) - model_->SetObserver(NULL); + model_->SetObserver(nullptr); } // TODO: this doesn't support arbitrarily changing the model, rename this to @@ -188,7 +188,7 @@ return; if (model_) - model_->SetObserver(NULL); + model_->SetObserver(nullptr); model_ = model; selection_model_.Clear(); if (model_) @@ -370,7 +370,7 @@ void TableView::Layout() { // parent()->parent() is the scrollview. When its width changes we force // recalculating column sizes. - View* scroll_view = parent() ? parent()->parent() : NULL; + View* scroll_view = parent() ? parent()->parent() : nullptr; if (scroll_view) { const int scroll_view_width = scroll_view->GetContentsBounds().width(); if (scroll_view_width != last_parent_width_) {
diff --git a/ui/views/controls/table/table_view_unittest.cc b/ui/views/controls/table/table_view_unittest.cc index 83e7a21..2610ed5 100644 --- a/ui/views/controls/table/table_view_unittest.cc +++ b/ui/views/controls/table/table_view_unittest.cc
@@ -125,7 +125,7 @@ DISALLOW_COPY_AND_ASSIGN(TestTableModel2); }; -TestTableModel2::TestTableModel2() : observer_(NULL) { +TestTableModel2::TestTableModel2() : observer_(nullptr) { AddRow(0, 0, 1); AddRow(1, 1, 1); AddRow(2, 2, 2); @@ -257,7 +257,7 @@ class TableViewTest : public ViewsTestBase { public: - TableViewTest() : table_(NULL) {} + TableViewTest() : table_(nullptr) {} void SetUp() override { ViewsTestBase::SetUp(); @@ -956,7 +956,7 @@ EXPECT_EQ(0, observer.GetChangedCountAndClear()); EXPECT_EQ("active=3 anchor=3 selection=3", SelectionStateAsString()); - table_->set_observer(NULL); + table_->set_observer(nullptr); } TEST_F(TableViewTest, RemoveUnselectedRows) { @@ -1046,7 +1046,7 @@ EXPECT_EQ(1, observer.GetChangedCountAndClear()); EXPECT_EQ("active=0 anchor=0 selection=0", SelectionStateAsString()); - table_->set_observer(NULL); + table_->set_observer(nullptr); } #endif @@ -1178,7 +1178,7 @@ EXPECT_EQ(0, observer.GetChangedCountAndClear()); EXPECT_EQ("active=2 anchor=2 selection=2", SelectionStateAsString()); - table_->set_observer(NULL); + table_->set_observer(nullptr); } // Verifies left/right correctly navigate through visible columns. @@ -1277,7 +1277,7 @@ EXPECT_EQ(0, observer.GetChangedCountAndClear()); EXPECT_EQ("active=1 anchor=1 selection=1", SelectionStateAsString()); - table_->set_observer(NULL); + table_->set_observer(nullptr); } // Verifies home/end do the right thing. @@ -1313,7 +1313,7 @@ EXPECT_EQ(1, observer.GetChangedCountAndClear()); EXPECT_EQ("active=0 anchor=0 selection=0 1", SelectionStateAsString()); - table_->set_observer(NULL); + table_->set_observer(nullptr); } // Verifies multiple selection gestures work (control-click, shift-click ...). @@ -1369,7 +1369,7 @@ EXPECT_EQ(1, observer.GetChangedCountAndClear()); EXPECT_EQ("active=4 anchor=4 selection=3 4", SelectionStateAsString()); - table_->set_observer(NULL); + table_->set_observer(nullptr); } // Verifies multiple selection gestures work when sorted. @@ -1468,7 +1468,7 @@ EXPECT_EQ("active=4 anchor=3 selection=1 3 4", SelectionStateAsString()); EXPECT_EQ("[1], [77], [0], [2], [3]", GetRowsInViewOrderAsString(table_)); - table_->set_observer(NULL); + table_->set_observer(nullptr); } TEST_F(TableViewTest, MoveRowsWithMultipleSelectionAndSort) { @@ -1527,7 +1527,7 @@ EXPECT_EQ("active=3 anchor=2 selection=2 3 4", SelectionStateAsString()); EXPECT_EQ(kViewOrder, GetRowsInViewOrderAsString(table_)); - table_->set_observer(NULL); + table_->set_observer(nullptr); } // Verifies we don't crash after removing the selected row when there is
diff --git a/ui/views/controls/table/test_table_model.cc b/ui/views/controls/table/test_table_model.cc index fde158e..34ee9db 100644 --- a/ui/views/controls/table/test_table_model.cc +++ b/ui/views/controls/table/test_table_model.cc
@@ -11,9 +11,7 @@ #include "ui/gfx/image/image_skia.h" TestTableModel::TestTableModel(int row_count) - : row_count_(row_count), - observer_(NULL) { -} + : row_count_(row_count), observer_(nullptr) {} TestTableModel::~TestTableModel() { }
diff --git a/ui/views/controls/textfield/textfield.cc b/ui/views/controls/textfield/textfield.cc index 839cd6e6..73c2f61d 100644 --- a/ui/views/controls/textfield/textfield.cc +++ b/ui/views/controls/textfield/textfield.cc
@@ -270,7 +270,7 @@ Textfield::Textfield() : model_(new TextfieldModel(this)), - controller_(NULL), + controller_(nullptr), scheduled_text_edit_command_(ui::TextEditCommand::INVALID_COMMAND), read_only_(false), default_width_in_chars_(0), @@ -829,7 +829,8 @@ event->SetHandled(); break; case ui::ET_GESTURE_SCROLL_BEGIN: - touch_handles_hidden_due_to_scroll_ = touch_selection_controller_ != NULL; + touch_handles_hidden_due_to_scroll_ = + touch_selection_controller_ != nullptr; DestroyTouchSelection(); drag_start_location_ = event->location(); drag_start_display_offset_ = @@ -1193,7 +1194,7 @@ const gfx::Point& point, ui::MenuSourceType source_type) { UpdateContextMenu(); - context_menu_runner_->RunMenuAt(GetWidget(), NULL, + context_menu_runner_->RunMenuAt(GetWidget(), nullptr, gfx::Rect(point, gfx::Size()), MENU_ANCHOR_TOPLEFT, source_type); }
diff --git a/ui/views/controls/textfield/textfield_model_unittest.cc b/ui/views/controls/textfield/textfield_model_unittest.cc index 75d45261..a252cd1f1 100644 --- a/ui/views/controls/textfield/textfield_model_unittest.cc +++ b/ui/views/controls/textfield/textfield_model_unittest.cc
@@ -75,7 +75,7 @@ }; TEST_F(TextfieldModelTest, EditString) { - TextfieldModel model(NULL); + TextfieldModel model(nullptr); // Append two strings. model.Append(base::ASCIIToUTF16("HILL")); EXPECT_STR_EQ("HILL", model.text()); @@ -118,7 +118,7 @@ } TEST_F(TextfieldModelTest, EditString_SimpleRTL) { - TextfieldModel model(NULL); + TextfieldModel model(nullptr); // Append two strings. model.Append(base::WideToUTF16(L"\x05d0\x05d1\x05d2")); EXPECT_EQ(base::WideToUTF16(L"\x05d0\x05d1\x05d2"), model.text()); @@ -148,7 +148,7 @@ } TEST_F(TextfieldModelTest, EditString_ComplexScript) { - TextfieldModel model(NULL); + TextfieldModel model(nullptr); // Append two Hindi strings. model.Append(base::WideToUTF16(L"\x0915\x093f\x0915\x094d\x0915")); @@ -267,7 +267,7 @@ } TEST_F(TextfieldModelTest, EmptyString) { - TextfieldModel model(NULL); + TextfieldModel model(nullptr); EXPECT_EQ(base::string16(), model.text()); EXPECT_EQ(base::string16(), model.GetSelectedText()); @@ -285,7 +285,7 @@ } TEST_F(TextfieldModelTest, Selection) { - TextfieldModel model(NULL); + TextfieldModel model(nullptr); model.Append(base::ASCIIToUTF16("HELLO")); model.MoveCursor(gfx::CHARACTER_BREAK, gfx::CURSOR_RIGHT, gfx::SELECTION_NONE); @@ -339,7 +339,7 @@ // the (logical) start and end points. Selection is simply defined as // the portion of text between the logical positions of the start and end // caret positions. - TextfieldModel model(NULL); + TextfieldModel model(nullptr); // TODO(xji): temporarily disable in platform Win since the complex script // characters turned into empty square due to font regression. So, not able // to test 2 characters belong to the same grapheme. @@ -437,7 +437,7 @@ } TEST_F(TextfieldModelTest, SelectionAndEdit) { - TextfieldModel model(NULL); + TextfieldModel model(nullptr); model.Append(base::ASCIIToUTF16("HELLO")); model.MoveCursor(gfx::CHARACTER_BREAK, gfx::CURSOR_RIGHT, gfx::SELECTION_NONE); @@ -475,7 +475,7 @@ } TEST_F(TextfieldModelTest, Word) { - TextfieldModel model(NULL); + TextfieldModel model(nullptr); model.Append( base::ASCIIToUTF16("The answer to Life, the Universe, and Everything")); #if defined(OS_WIN) // Move right by word includes space/punctuation. @@ -570,7 +570,7 @@ } TEST_F(TextfieldModelTest, SetText) { - TextfieldModel model(NULL); + TextfieldModel model(nullptr); model.Append(base::ASCIIToUTF16("HELLO")); model.MoveCursor(gfx::LINE_BREAK, gfx::CURSOR_RIGHT, gfx::SELECTION_NONE); model.SetText(base::ASCIIToUTF16("GOODBYE")); @@ -598,7 +598,7 @@ .WriteText(initial_clipboard_text); base::string16 clipboard_text; - TextfieldModel model(NULL); + TextfieldModel model(nullptr); model.Append(base::ASCIIToUTF16("HELLO WORLD")); // Cut with an empty selection should do nothing. @@ -672,7 +672,7 @@ } TEST_F(TextfieldModelTest, SelectWordTest) { - TextfieldModel model(NULL); + TextfieldModel model(nullptr); model.Append(base::ASCIIToUTF16(" HELLO !! WO RLD ")); // Test when cursor is at the beginning. @@ -745,7 +745,7 @@ #endif TEST_F(TextfieldModelTest, RangeTest) { - TextfieldModel model(NULL); + TextfieldModel model(nullptr); model.Append(base::ASCIIToUTF16("HELLO WORLD")); model.MoveCursor(gfx::LINE_BREAK, gfx::CURSOR_LEFT, gfx::SELECTION_NONE); gfx::Range range = model.render_text()->selection(); @@ -861,7 +861,7 @@ } TEST_F(TextfieldModelTest, SelectRangeTest) { - TextfieldModel model(NULL); + TextfieldModel model(nullptr); model.Append(base::ASCIIToUTF16("HELLO WORLD")); gfx::Range range(0, 6); EXPECT_FALSE(range.is_reversed()); @@ -905,7 +905,7 @@ } TEST_F(TextfieldModelTest, SelectionTest) { - TextfieldModel model(NULL); + TextfieldModel model(nullptr); model.Append(base::ASCIIToUTF16("HELLO WORLD")); model.MoveCursor(gfx::LINE_BREAK, gfx::CURSOR_LEFT, gfx::SELECTION_NONE); gfx::Range selection = model.render_text()->selection(); @@ -959,7 +959,7 @@ } TEST_F(TextfieldModelTest, SelectSelectionModelTest) { - TextfieldModel model(NULL); + TextfieldModel model(nullptr); model.Append(base::ASCIIToUTF16("HELLO WORLD")); model.SelectSelectionModel(gfx::SelectionModel(gfx::Range(0, 6), gfx::CURSOR_BACKWARD)); @@ -1193,7 +1193,7 @@ } TEST_F(TextfieldModelTest, UndoRedo_BasicTest) { - TextfieldModel model(NULL); + TextfieldModel model(nullptr); model.InsertChar('a'); EXPECT_FALSE(model.Redo()); // There is nothing to redo. EXPECT_TRUE(model.Undo()); @@ -1291,7 +1291,7 @@ TEST_F(TextfieldModelTest, UndoRedo_SetText) { // This is to test the undo/redo behavior of omnibox. - TextfieldModel model(NULL); + TextfieldModel model(nullptr); model.InsertChar('w'); EXPECT_STR_EQ("w", model.text()); EXPECT_EQ(1U, model.GetCursorPosition()); @@ -1353,7 +1353,7 @@ TEST_F(TextfieldModelTest, UndoRedo_BackspaceThenSetText) { // This is to test the undo/redo behavior of omnibox. - TextfieldModel model(NULL); + TextfieldModel model(nullptr); model.InsertChar('w'); EXPECT_STR_EQ("w", model.text()); EXPECT_EQ(1U, model.GetCursorPosition()); @@ -1376,7 +1376,7 @@ } TEST_F(TextfieldModelTest, UndoRedo_CutCopyPasteTest) { - TextfieldModel model(NULL); + TextfieldModel model(nullptr); model.SetText(base::ASCIIToUTF16("ABCDE")); EXPECT_FALSE(model.Redo()); // There is nothing to redo. // Test Cut. @@ -1518,7 +1518,7 @@ } TEST_F(TextfieldModelTest, UndoRedo_CursorTest) { - TextfieldModel model(NULL); + TextfieldModel model(nullptr); model.InsertChar('a'); model.MoveCursor(gfx::CHARACTER_BREAK, gfx::CURSOR_LEFT, gfx::SELECTION_NONE); model.MoveCursor(gfx::CHARACTER_BREAK, gfx::CURSOR_RIGHT, @@ -1628,28 +1628,28 @@ TEST_F(TextfieldModelTest, UndoRedo_ReplaceTest) { { SCOPED_TRACE("Select forwards and insert."); - TextfieldModel model(NULL); + TextfieldModel model(nullptr); model.SetText(base::ASCIIToUTF16("abcd")); model.SelectRange(gfx::Range(1, 3)); RunInsertReplaceTest(model); } { SCOPED_TRACE("Select reversed and insert."); - TextfieldModel model(NULL); + TextfieldModel model(nullptr); model.SetText(base::ASCIIToUTF16("abcd")); model.SelectRange(gfx::Range(3, 1)); RunInsertReplaceTest(model); } { SCOPED_TRACE("Select forwards and overwrite."); - TextfieldModel model(NULL); + TextfieldModel model(nullptr); model.SetText(base::ASCIIToUTF16("abcd")); model.SelectRange(gfx::Range(1, 3)); RunOverwriteReplaceTest(model); } { SCOPED_TRACE("Select reversed and overwrite."); - TextfieldModel model(NULL); + TextfieldModel model(nullptr); model.SetText(base::ASCIIToUTF16("abcd")); model.SelectRange(gfx::Range(3, 1)); RunOverwriteReplaceTest(model); @@ -1657,7 +1657,7 @@ } TEST_F(TextfieldModelTest, UndoRedo_CompositionText) { - TextfieldModel model(NULL); + TextfieldModel model(nullptr); ui::CompositionText composition; composition.text = base::ASCIIToUTF16("abc"); @@ -1743,7 +1743,7 @@ ui::ScopedClipboardWriter(ui::CLIPBOARD_TYPE_COPY_PASTE) .WriteText(base::ASCIIToUTF16("\tB")); - TextfieldModel model(NULL); + TextfieldModel model(nullptr); model.Append(base::ASCIIToUTF16("HELLO WORLD")); EXPECT_STR_EQ("HELLO WORLD", model.text()); model.MoveCursor(gfx::LINE_BREAK, gfx::CURSOR_RIGHT, gfx::SELECTION_NONE);
diff --git a/ui/views/controls/textfield/textfield_unittest.cc b/ui/views/controls/textfield/textfield_unittest.cc index a2d646e..5d9e17b 100644 --- a/ui/views/controls/textfield/textfield_unittest.cc +++ b/ui/views/controls/textfield/textfield_unittest.cc
@@ -392,10 +392,10 @@ class TextfieldTest : public ViewsTestBase, public TextfieldController { public: TextfieldTest() - : widget_(NULL), - textfield_(NULL), - model_(NULL), - input_method_(NULL), + : widget_(nullptr), + textfield_(nullptr), + model_(nullptr), + input_method_(nullptr), on_before_user_action_(0), on_after_user_action_(0), copied_to_clipboard_(ui::CLIPBOARD_TYPE_LAST) { @@ -1738,7 +1738,7 @@ bad_data.SetPickledData(fmt, base::Pickle()); bad_data.SetFileContents(base::FilePath(L"x"), "x"); bad_data.SetHtml(base::string16(ASCIIToUTF16("x")), GURL("x.org")); - ui::OSExchangeData::DownloadFileInfo download(base::FilePath(), NULL); + ui::OSExchangeData::DownloadFileInfo download(base::FilePath(), nullptr); bad_data.SetDownloadFileInfo(download); EXPECT_FALSE(textfield_->CanDrop(bad_data)); } @@ -1754,36 +1754,36 @@ const gfx::Range kStringRange(6, 12); textfield_->SelectRange(kStringRange); const gfx::Point kStringPoint(GetCursorPositionX(9), GetCursorYForTesting()); - textfield_->WriteDragDataForView(NULL, kStringPoint, &data); + textfield_->WriteDragDataForView(nullptr, kStringPoint, &data); EXPECT_TRUE(data.GetString(&string)); EXPECT_EQ(textfield_->GetSelectedText(), string); // Ensure that disabled textfields do not support drag operations. textfield_->SetEnabled(false); EXPECT_EQ(ui::DragDropTypes::DRAG_NONE, - textfield_->GetDragOperationsForView(NULL, kStringPoint)); + textfield_->GetDragOperationsForView(nullptr, kStringPoint)); textfield_->SetEnabled(true); // Ensure that textfields without selections do not support drag operations. textfield_->ClearSelection(); EXPECT_EQ(ui::DragDropTypes::DRAG_NONE, - textfield_->GetDragOperationsForView(NULL, kStringPoint)); + textfield_->GetDragOperationsForView(nullptr, kStringPoint)); textfield_->SelectRange(kStringRange); // Ensure that password textfields do not support drag operations. textfield_->SetTextInputType(ui::TEXT_INPUT_TYPE_PASSWORD); EXPECT_EQ(ui::DragDropTypes::DRAG_NONE, - textfield_->GetDragOperationsForView(NULL, kStringPoint)); + textfield_->GetDragOperationsForView(nullptr, kStringPoint)); textfield_->SetTextInputType(ui::TEXT_INPUT_TYPE_TEXT); MoveMouseTo(kStringPoint); PressLeftMouseButton(); // Ensure that textfields only initiate drag operations inside the selection. EXPECT_EQ(ui::DragDropTypes::DRAG_NONE, - textfield_->GetDragOperationsForView(NULL, gfx::Point())); - EXPECT_FALSE(textfield_->CanStartDragForView(NULL, gfx::Point(), - gfx::Point())); + textfield_->GetDragOperationsForView(nullptr, gfx::Point())); + EXPECT_FALSE( + textfield_->CanStartDragForView(nullptr, gfx::Point(), gfx::Point())); EXPECT_EQ(ui::DragDropTypes::DRAG_COPY, - textfield_->GetDragOperationsForView(NULL, kStringPoint)); - EXPECT_TRUE(textfield_->CanStartDragForView(NULL, kStringPoint, - gfx::Point())); + textfield_->GetDragOperationsForView(nullptr, kStringPoint)); + EXPECT_TRUE( + textfield_->CanStartDragForView(nullptr, kStringPoint, gfx::Point())); // Ensure that textfields support local moves. EXPECT_EQ(ui::DragDropTypes::DRAG_MOVE | ui::DragDropTypes::DRAG_COPY, textfield_->GetDragOperationsForView(textfield_, kStringPoint)); @@ -3021,8 +3021,8 @@ kStringPoint.y(), ui::GestureEventDetails(ui::ET_GESTURE_LONG_PRESS)); textfield_->OnGestureEvent(&long_press); - EXPECT_TRUE(textfield_->CanStartDragForView(NULL, kStringPoint, - kStringPoint)); + EXPECT_TRUE( + textfield_->CanStartDragForView(nullptr, kStringPoint, kStringPoint)); } TEST_F(TextfieldTest, GetTextfieldBaseline_FontFallbackTest) {
diff --git a/ui/views/controls/tree/tree_view.cc b/ui/views/controls/tree/tree_view.cc index b57f053..779d89b 100644 --- a/ui/views/controls/tree/tree_view.cc +++ b/ui/views/controls/tree/tree_view.cc
@@ -66,14 +66,14 @@ } // namespace TreeView::TreeView() - : model_(NULL), - selected_node_(NULL), + : model_(nullptr), + selected_node_(nullptr), editing_(false), - editor_(NULL), - focus_manager_(NULL), + editor_(nullptr), + focus_manager_(nullptr), auto_expand_children_(false), editable_(true), - controller_(NULL), + controller_(nullptr), root_shown_(true), row_height_(font_list_.GetHeight() + kTextVerticalPadding * 2), drawing_provider_(std::make_unique<TreeViewDrawingProvider>()) { @@ -115,7 +115,7 @@ if (focus_manager_) { focus_manager_->RemoveFocusChangeListener(this); - focus_manager_ = NULL; + focus_manager_ = nullptr; } } @@ -134,7 +134,7 @@ CancelEdit(); model_ = model; - selected_node_ = NULL; + selected_node_ = nullptr; icons_.clear(); if (model_) { model_->AddObserver(this); @@ -214,7 +214,7 @@ editing_ = false; if (focus_manager_) { focus_manager_->RemoveFocusChangeListener(this); - focus_manager_ = NULL; + focus_manager_ = nullptr; } editor_->SetVisible(false); SchedulePaint(); @@ -236,7 +236,7 @@ } TreeModelNode* TreeView::GetEditingNode() { - return editing_ ? selected_node_->model_node() : NULL; + return editing_ ? selected_node_->model_node() : nullptr; } void TreeView::SetSelectedNode(TreeModelNode* model_node) { @@ -246,15 +246,16 @@ Expand(model_->GetParent(model_node)); if (model_node && model_node == root_.model_node() && !root_shown_) return; // Ignore requests to select the root when not shown. - InternalNode* node = model_node ? GetInternalNodeForModelNode( - model_node, CREATE_IF_NOT_LOADED) : NULL; - bool was_empty_selection = (selected_node_ == NULL); + InternalNode* node = + model_node ? GetInternalNodeForModelNode(model_node, CREATE_IF_NOT_LOADED) + : nullptr; + bool was_empty_selection = (selected_node_ == nullptr); bool changed = (selected_node_ != node); if (changed) { SchedulePaintForNode(selected_node_); selected_node_ = node; if (selected_node_ == &root_ && !root_shown_) - selected_node_ = NULL; + selected_node_ = nullptr; if (selected_node_ && selected_node_ != &root_) Expand(model_->GetParent(selected_node_->model_node())); SchedulePaintForNode(selected_node_); @@ -280,7 +281,7 @@ } TreeModelNode* TreeView::GetSelectedNode() { - return selected_node_ ? selected_node_->model_node() : NULL; + return selected_node_ ? selected_node_->model_node() : nullptr; } void TreeView::Collapse(ui::TreeModelNode* model_node) { @@ -349,7 +350,7 @@ if (model_->GetChildCount(root_.model_node())) SetSelectedNode(model_->GetChild(root_.model_node(), 0)); else - SetSelectedNode(NULL); + SetSelectedNode(nullptr); } DrawnNodesChanged(); } @@ -357,7 +358,7 @@ ui::TreeModelNode* TreeView::GetNodeForRow(int row) { int depth = 0; InternalNode* node = GetNodeByRow(row, &depth); - return node ? node->model_node() : NULL; + return node ? node->model_node() : nullptr; } int TreeView::GetRowForNode(ui::TreeModelNode* node) { @@ -486,11 +487,12 @@ // its model_node() is likely deleted). Explicitly NULL out the field // rather than invoking SetSelectedNode() otherwise, we'll try and use a // deleted value. - selected_node_ = NULL; + selected_node_ = nullptr; TreeModelNode* to_select = parent; if (parent == root_.model_node() && !root_shown_) { - to_select = model_->GetChildCount(parent) > 0 ? - model_->GetChild(parent, 0) : NULL; + to_select = model_->GetChildCount(parent) > 0 + ? model_->GetChild(parent, 0) + : nullptr; } SetSelectedNode(to_select); } @@ -898,10 +900,10 @@ InternalNode* parent_internal_node = GetInternalNodeForModelNode(model_->GetParent(model_node), create_type); if (!parent_internal_node) - return NULL; + return nullptr; if (!parent_internal_node->loaded_children()) { if (create_type == DONT_CREATE_IF_NOT_LOADED) - return NULL; + return nullptr; LoadChildren(parent_internal_node); } return parent_internal_node->GetChild( @@ -1027,7 +1029,7 @@ return result; } } - return NULL; + return nullptr; } void TreeView::IncrementSelection(IncrementType type) { @@ -1137,11 +1139,10 @@ // InternalNode ---------------------------------------------------------------- TreeView::InternalNode::InternalNode() - : model_node_(NULL), + : model_node_(nullptr), loaded_children_(false), is_expanded_(false), - text_width_(0) { -} + text_width_(0) {} TreeView::InternalNode::~InternalNode() { }
diff --git a/ui/views/controls/tree/tree_view_unittest.cc b/ui/views/controls/tree/tree_view_unittest.cc index fa4c7bf..a53cd1e 100644 --- a/ui/views/controls/tree/tree_view_unittest.cc +++ b/ui/views/controls/tree/tree_view_unittest.cc
@@ -130,7 +130,7 @@ if (child) return child; } - return NULL; + return nullptr; } std::string TreeViewTest::InternalNodeAsString( @@ -162,7 +162,7 @@ EXPECT_EQ("root", GetSelectedNodeTitle()); // NULL should clear the selection. - tree_.SetSelectedNode(NULL); + tree_.SetSelectedNode(nullptr); EXPECT_EQ(std::string(), GetSelectedNodeTitle()); // Select 'c'. @@ -416,8 +416,8 @@ tree_.SetEditable(true); tree_.StartEditing(GetNodeByTitle("a")); tree_.editor()->SetText(ASCIIToUTF16("a changed")); - tree_.OnDidChangeFocus(NULL, NULL); - EXPECT_TRUE(GetNodeByTitle("a changed") != NULL); + tree_.OnDidChangeFocus(nullptr, nullptr); + EXPECT_TRUE(GetNodeByTitle("a changed") != nullptr); } } // namespace views
diff --git a/ui/views/controls/webview/webview.cc b/ui/views/controls/webview/webview.cc index c5e4525..c58c7e8 100644 --- a/ui/views/controls/webview/webview.cc +++ b/ui/views/controls/webview/webview.cc
@@ -62,7 +62,7 @@ } WebView::~WebView() { - SetWebContents(NULL); // Make sure all necessary tear-down takes place. + SetWebContents(nullptr); // Make sure all necessary tear-down takes place. } content::WebContents* WebView::GetWebContents() { @@ -435,8 +435,7 @@ } if (!contents) { - content::WebContents::CreateParams create_params( - browser_context, NULL); + content::WebContents::CreateParams create_params(browser_context, nullptr); return content::WebContents::Create(create_params); }
diff --git a/ui/views/controls/webview/webview_unittest.cc b/ui/views/controls/webview/webview_unittest.cc index 445e5f8..324a2f6 100644 --- a/ui/views/controls/webview/webview_unittest.cc +++ b/ui/views/controls/webview/webview_unittest.cc
@@ -50,13 +50,13 @@ ~WebViewTestWebContentsObserver() override { if (web_contents_) - content::WebContentsObserver::Observe(NULL); + content::WebContentsObserver::Observe(nullptr); } void WebContentsDestroyed() override { DCHECK(web_contents_); - content::WebContentsObserver::Observe(NULL); - web_contents_ = NULL; + content::WebContentsObserver::Observe(nullptr); + web_contents_ = nullptr; } void OnVisibilityChanged(content::Visibility visibility) override { @@ -64,7 +64,7 @@ case content::Visibility::VISIBLE: { #if defined(USE_AURA) valid_root_while_shown_ = - web_contents()->GetNativeView()->GetRootWindow() != NULL; + web_contents()->GetNativeView()->GetRootWindow() != nullptr; #endif was_shown_ = true; ++shown_count_; @@ -173,7 +173,7 @@ top_level_widget_->Close(); // Deletes all children and itself. RunPendingMessages(); - browser_context_.reset(NULL); + browser_context_.reset(nullptr); // Flush the message loop to execute pending relase tasks as this would // upset ASAN and Valgrind. RunPendingMessages();
diff --git a/ui/views/corewm/cursor_height_provider_win.cc b/ui/views/corewm/cursor_height_provider_win.cc index 93a8ced..2b4c803 100644 --- a/ui/views/corewm/cursor_height_provider_win.cc +++ b/ui/views/corewm/cursor_height_provider_win.cc
@@ -79,15 +79,15 @@ // Based on that get's what should be the vertical offset between cursor's // hot point and the tooltip. int CalculateCursorHeight(HCURSOR cursor_handle) { - base::win::ScopedGetDC hdc(NULL); + base::win::ScopedGetDC hdc(nullptr); ICONINFO icon = {0}; GetIconInfo(cursor_handle, &icon); BITMAPINFO bitmap_info = {}; bitmap_info.bmiHeader.biSize = sizeof(bitmap_info.bmiHeader); - if (GetDIBits(hdc, icon.hbmMask, 0, 0, NULL, &bitmap_info, DIB_RGB_COLORS) == - 0) + if (GetDIBits(hdc, icon.hbmMask, 0, 0, nullptr, &bitmap_info, + DIB_RGB_COLORS) == 0) return kDefaultHeight; // Rows are padded to full DWORDs. OR with this mask will set them to 1 @@ -103,7 +103,7 @@ const uint32_t row_size = (bitmap_info.bmiHeader.biWidth + kBitsPeruint32 - 1) / kBitsPeruint32; PixelData data(GetBitmapData(icon.hbmMask, bitmap_info, hdc)); - if (data == NULL) + if (data == nullptr) return kDefaultHeight; // There are 2 types of cursors: Ones that cover the area underneath @@ -160,7 +160,7 @@ cursor.cbSize = sizeof(cursor); GetCursorInfo(&cursor); - if (cached_heights == NULL) + if (cached_heights == nullptr) cached_heights = new HeightStorage; HeightStorage::const_iterator cached_height =
diff --git a/ui/views/corewm/desktop_capture_controller_unittest.cc b/ui/views/corewm/desktop_capture_controller_unittest.cc index b1b8e82..b5eeec9b 100644 --- a/ui/views/corewm/desktop_capture_controller_unittest.cc +++ b/ui/views/corewm/desktop_capture_controller_unittest.cc
@@ -77,12 +77,12 @@ EXPECT_FALSE(w1->HasCapture()); aura::WindowEventDispatcher* w1_dispatcher = w1->GetNativeView()->GetHost()->dispatcher(); - EXPECT_TRUE(w1_dispatcher->mouse_pressed_handler() != NULL); - EXPECT_TRUE(w1_dispatcher->mouse_moved_handler() != NULL); + EXPECT_TRUE(w1_dispatcher->mouse_pressed_handler() != nullptr); + EXPECT_TRUE(w1_dispatcher->mouse_moved_handler() != nullptr); w2->SetCapture(w2->GetRootView()); EXPECT_TRUE(w2->HasCapture()); - EXPECT_TRUE(w1_dispatcher->mouse_pressed_handler() == NULL); - EXPECT_TRUE(w1_dispatcher->mouse_moved_handler() == NULL); + EXPECT_TRUE(w1_dispatcher->mouse_pressed_handler() == nullptr); + EXPECT_TRUE(w1_dispatcher->mouse_moved_handler() == nullptr); w2->ReleaseCapture(); RunPendingMessages(); }
diff --git a/ui/views/corewm/tooltip_aura.cc b/ui/views/corewm/tooltip_aura.cc index 1caf51f1..bde6da7f 100644 --- a/ui/views/corewm/tooltip_aura.cc +++ b/ui/views/corewm/tooltip_aura.cc
@@ -157,9 +157,8 @@ TooltipAura::TooltipAura() : tooltip_view_(new TooltipView), - widget_(NULL), - tooltip_window_(NULL) { -} + widget_(nullptr), + tooltip_window_(nullptr) {} TooltipAura::~TooltipAura() { DestroyWidget(); @@ -196,7 +195,7 @@ if (widget_) { widget_->RemoveObserver(this); widget_->Close(); - widget_ = NULL; + widget_ = nullptr; } } @@ -239,7 +238,7 @@ } void TooltipAura::Hide() { - tooltip_window_ = NULL; + tooltip_window_ = nullptr; if (widget_) widget_->Hide(); } @@ -250,8 +249,8 @@ void TooltipAura::OnWidgetDestroying(views::Widget* widget) { DCHECK_EQ(widget_, widget); - widget_ = NULL; - tooltip_window_ = NULL; + widget_ = nullptr; + tooltip_window_ = nullptr; } } // namespace corewm
diff --git a/ui/views/corewm/tooltip_controller.cc b/ui/views/corewm/tooltip_controller.cc index 77d84cac..e0480d0 100644 --- a/ui/views/corewm/tooltip_controller.cc +++ b/ui/views/corewm/tooltip_controller.cc
@@ -64,14 +64,14 @@ case ui::ET_MOUSE_CAPTURE_CHANGED: // On windows we can get a capture changed without an exit. We need to // reset state when this happens else the tooltip may incorrectly show. - return NULL; + return nullptr; case ui::ET_MOUSE_EXITED: - return NULL; + return nullptr; case ui::ET_MOUSE_MOVED: case ui::ET_MOUSE_DRAGGED: { aura::Window* event_target = static_cast<aura::Window*>(event.target()); if (!event_target) - return NULL; + return nullptr; // If a window other than |event_target| has capture, ignore the event. // This can happen when RootWindow creates events when showing/hiding, or @@ -87,7 +87,7 @@ aura::Window* capture_window = capture_client->GetGlobalCaptureWindow(); if (capture_window && event_target != capture_window) - return NULL; + return nullptr; } } return event_target; @@ -99,13 +99,13 @@ display::Screen* screen = display::Screen::GetScreen(); aura::Window* target = screen->GetWindowAtScreenPoint(screen_loc); if (!target) - return NULL; + return nullptr; gfx::Point target_loc(screen_loc); aura::client::GetScreenPositionClient(target->GetRootWindow()) ->ConvertPointFromScreen(target, &target_loc); aura::Window* screen_target = target->GetEventHandlerForPoint(target_loc); if (!IsValidTarget(event_target, screen_target)) - return NULL; + return nullptr; aura::Window::ConvertPointToTarget(screen_target, target, &target_loc); *location = target_loc; @@ -115,7 +115,7 @@ NOTREACHED(); break; } - return NULL; + return nullptr; } } // namespace @@ -124,9 +124,9 @@ // TooltipController public: TooltipController::TooltipController(std::unique_ptr<Tooltip> tooltip) - : tooltip_window_(NULL), - tooltip_id_(NULL), - tooltip_window_at_mouse_press_(NULL), + : tooltip_window_(nullptr), + tooltip_id_(nullptr), + tooltip_window_at_mouse_press_(nullptr), tooltip_(std::move(tooltip)), tooltips_enabled_(true), tooltip_show_delayed_(true) {} @@ -152,7 +152,7 @@ if (tooltip_window_at_mouse_press_ && target == tooltip_window_at_mouse_press_ && wm::GetTooltipText(target) != tooltip_text_at_mouse_press_) { - tooltip_window_at_mouse_press_ = NULL; + tooltip_window_at_mouse_press_ = nullptr; } } @@ -193,7 +193,7 @@ case ui::ET_MOUSE_MOVED: case ui::ET_MOUSE_DRAGGED: { curr_mouse_loc_ = event->location(); - aura::Window* target = NULL; + aura::Window* target = nullptr; // Avoid a call to display::Screen::GetWindowAtScreenPoint() since it can // be very expensive on X11 in cases when the tooltip is hidden anyway. if (tooltips_enabled_ && @@ -232,13 +232,13 @@ void TooltipController::OnTouchEvent(ui::TouchEvent* event) { // Hide the tooltip for touch events. tooltip_->Hide(); - SetTooltipWindow(NULL); + SetTooltipWindow(nullptr); last_touch_loc_ = event->location(); } void TooltipController::OnCancelMode(ui::CancelModeEvent* event) { tooltip_->Hide(); - SetTooltipWindow(NULL); + SetTooltipWindow(nullptr); } void TooltipController::OnCursorVisibilityChanged(bool is_visible) { @@ -249,7 +249,7 @@ if (tooltip_window_ == window) { tooltip_->Hide(); tooltip_shown_timeout_map_.erase(tooltip_window_); - tooltip_window_ = NULL; + tooltip_window_ = nullptr; } } @@ -289,7 +289,7 @@ tooltip_->Hide(); return; } - tooltip_window_at_mouse_press_ = NULL; + tooltip_window_at_mouse_press_ = nullptr; } // If the uniqueness indicator is different from the previously encountered
diff --git a/ui/views/corewm/tooltip_controller_unittest.cc b/ui/views/corewm/tooltip_controller_unittest.cc index 94f6648..8d309c0b 100644 --- a/ui/views/corewm/tooltip_controller_unittest.cc +++ b/ui/views/corewm/tooltip_controller_unittest.cc
@@ -180,7 +180,7 @@ TEST_F(TooltipControllerTest, ViewTooltip) { view_->set_tooltip_text(ASCIIToUTF16("Tooltip Text")); EXPECT_EQ(base::string16(), helper_->GetTooltipText()); - EXPECT_EQ(NULL, helper_->GetTooltipWindow()); + EXPECT_EQ(nullptr, helper_->GetTooltipWindow()); generator_->MoveMouseToCenterOf(GetWindow()); @@ -203,7 +203,7 @@ TEST_F(TooltipControllerTest, HideEmptyTooltip) { view_->set_tooltip_text(ASCIIToUTF16("Tooltip Text")); EXPECT_EQ(base::string16(), helper_->GetTooltipText()); - EXPECT_EQ(NULL, helper_->GetTooltipWindow()); + EXPECT_EQ(nullptr, helper_->GetTooltipWindow()); generator_->MoveMouseToCenterOf(GetWindow()); generator_->MoveMouseBy(1, 0); @@ -258,7 +258,7 @@ TEST_F(TooltipControllerTest, TooltipsInMultipleViews) { view_->set_tooltip_text(ASCIIToUTF16("Tooltip Text")); EXPECT_EQ(base::string16(), helper_->GetTooltipText()); - EXPECT_EQ(NULL, helper_->GetTooltipWindow()); + EXPECT_EQ(nullptr, helper_->GetTooltipWindow()); PrepareSecondView(); aura::Window* window = GetWindow(); @@ -291,7 +291,7 @@ TEST_F(TooltipControllerTest, EnableOrDisableTooltips) { view_->set_tooltip_text(ASCIIToUTF16("Tooltip Text")); EXPECT_EQ(base::string16(), helper_->GetTooltipText()); - EXPECT_EQ(NULL, helper_->GetTooltipWindow()); + EXPECT_EQ(nullptr, helper_->GetTooltipWindow()); generator_->MoveMouseRelativeTo(GetWindow(), view_->bounds().CenterPoint()); EXPECT_TRUE(helper_->IsTooltipVisible()); @@ -313,7 +313,7 @@ TEST_F(TooltipControllerTest, DontShowEmptyTooltips) { view_->set_tooltip_text(ASCIIToUTF16(" ")); EXPECT_EQ(base::string16(), helper_->GetTooltipText()); - EXPECT_EQ(NULL, helper_->GetTooltipWindow()); + EXPECT_EQ(nullptr, helper_->GetTooltipWindow()); generator_->MoveMouseRelativeTo(GetWindow(), view_->bounds().CenterPoint()); EXPECT_FALSE(helper_->IsTooltipVisible()); @@ -322,7 +322,7 @@ TEST_F(TooltipControllerTest, TooltipHidesOnKeyPressAndStaysHiddenUntilChange) { view_->set_tooltip_text(ASCIIToUTF16("Tooltip Text for view 1")); EXPECT_EQ(base::string16(), helper_->GetTooltipText()); - EXPECT_EQ(NULL, helper_->GetTooltipWindow()); + EXPECT_EQ(nullptr, helper_->GetTooltipWindow()); TooltipTestView* view2 = PrepareSecondView(); view2->set_tooltip_text(ASCIIToUTF16("Tooltip Text for view 2")); @@ -365,7 +365,7 @@ TEST_F(TooltipControllerTest, TooltipHidesOnTimeoutAndStaysHiddenUntilChange) { view_->set_tooltip_text(ASCIIToUTF16("Tooltip Text for view 1")); EXPECT_EQ(base::string16(), helper_->GetTooltipText()); - EXPECT_EQ(NULL, helper_->GetTooltipWindow()); + EXPECT_EQ(nullptr, helper_->GetTooltipWindow()); TooltipTestView* view2 = PrepareSecondView(); view2->set_tooltip_text(ASCIIToUTF16("Tooltip Text for view 2")); @@ -479,7 +479,7 @@ } void TearDown() override { - aura::client::SetScreenPositionClient(GetRootWindow(), NULL); + aura::client::SetScreenPositionClient(GetRootWindow(), nullptr); TooltipControllerTest::TearDown(); } @@ -505,7 +505,7 @@ EXPECT_TRUE(helper_->IsTooltipVisible()); view_->GetWidget()->ReleaseCapture(); EXPECT_FALSE(helper_->IsTooltipVisible()); - EXPECT_TRUE(helper_->GetTooltipWindow() == NULL); + EXPECT_TRUE(helper_->GetTooltipWindow() == nullptr); } // Disabled on X11 as DesktopScreenX11::GetWindowAtScreenPoint() doesn't @@ -614,7 +614,7 @@ void TearDown() override { root_window()->RemovePreTargetHandler(controller_.get()); - wm::SetTooltipClient(root_window(), NULL); + wm::SetTooltipClient(root_window(), nullptr); controller_.reset(); generator_.reset(); helper_.reset(); @@ -666,7 +666,7 @@ ui::CancelModeEvent event; helper_->controller()->OnCancelMode(&event); EXPECT_FALSE(helper_->IsTooltipVisible()); - EXPECT_TRUE(helper_->GetTooltipWindow() == NULL); + EXPECT_TRUE(helper_->GetTooltipWindow() == nullptr); } // Use for tests that need both views and a TestTooltip. @@ -706,7 +706,7 @@ void TearDown() override { GetRootWindow()->RemovePreTargetHandler(controller_.get()); - wm::SetTooltipClient(GetRootWindow(), NULL); + wm::SetTooltipClient(GetRootWindow(), nullptr); controller_.reset(); generator_.reset();
diff --git a/ui/views/corewm/tooltip_win.cc b/ui/views/corewm/tooltip_win.cc index e6e1fd9..adf01d9c 100644 --- a/ui/views/corewm/tooltip_win.cc +++ b/ui/views/corewm/tooltip_win.cc
@@ -19,16 +19,14 @@ namespace corewm { TooltipWin::TooltipWin(HWND parent) - : parent_hwnd_(parent), - tooltip_hwnd_(NULL), - showing_(false) { + : parent_hwnd_(parent), tooltip_hwnd_(nullptr), showing_(false) { memset(&toolinfo_, 0, sizeof(toolinfo_)); toolinfo_.cbSize = sizeof(toolinfo_); toolinfo_.uFlags = TTF_IDISHWND | TTF_TRACK | TTF_ABSOLUTE; toolinfo_.uId = reinterpret_cast<UINT_PTR>(parent_hwnd_); toolinfo_.hwnd = parent_hwnd_; - toolinfo_.lpszText = NULL; - toolinfo_.lpReserved = NULL; + toolinfo_.lpszText = nullptr; + toolinfo_.lpReserved = nullptr; SetRectEmpty(&toolinfo_.rect); } @@ -38,7 +36,7 @@ } bool TooltipWin::HandleNotify(int w_param, NMHDR* l_param, LRESULT* l_result) { - if (tooltip_hwnd_ == NULL) + if (tooltip_hwnd_ == nullptr) return false; switch (l_param->code) { @@ -60,10 +58,10 @@ if (tooltip_hwnd_) return true; - tooltip_hwnd_ = CreateWindowEx( - WS_EX_TRANSPARENT | l10n_util::GetExtendedTooltipStyles(), - TOOLTIPS_CLASS, NULL, TTS_NOPREFIX | WS_POPUP, 0, 0, 0, 0, - parent_hwnd_, NULL, NULL, NULL); + tooltip_hwnd_ = + CreateWindowEx(WS_EX_TRANSPARENT | l10n_util::GetExtendedTooltipStyles(), + TOOLTIPS_CLASS, nullptr, TTS_NOPREFIX | WS_POPUP, 0, 0, 0, + 0, parent_hwnd_, nullptr, nullptr, nullptr); if (!tooltip_hwnd_) { PLOG(WARNING) << "tooltip creation failed, disabling tooltips"; return false; @@ -93,8 +91,8 @@ tooltip_bounds.AdjustToFit( display::win::ScreenWin::DIPToScreenRect(parent_hwnd_, display.work_area())); - SetWindowPos(tooltip_hwnd_, NULL, tooltip_bounds.x(), tooltip_bounds.y(), 0, - 0, SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE); + SetWindowPos(tooltip_hwnd_, nullptr, tooltip_bounds.x(), tooltip_bounds.y(), + 0, 0, SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE); MaybeOverrideFont(); }
diff --git a/ui/views/examples/examples_window.cc b/ui/views/examples/examples_window.cc index 5f76b6c..badcf73 100644 --- a/ui/views/examples/examples_window.cc +++ b/ui/views/examples/examples_window.cc
@@ -191,7 +191,7 @@ return base::ASCIIToUTF16("Views Examples"); } void WindowClosing() override { - instance_ = NULL; + instance_ = nullptr; if (on_close_) std::move(on_close_).Run(); } @@ -223,7 +223,7 @@ }; // static -ExamplesWindowContents* ExamplesWindowContents::instance_ = NULL; +ExamplesWindowContents* ExamplesWindowContents::instance_ = nullptr; void ShowExamplesWindow(base::OnceClosure on_close, gfx::NativeWindow window_context,
diff --git a/ui/views/examples/examples_with_content_main_exe.cc b/ui/views/examples/examples_with_content_main_exe.cc index f2d84ae..7f978ca 100644 --- a/ui/views/examples/examples_with_content_main_exe.cc +++ b/ui/views/examples/examples_with_content_main_exe.cc
@@ -29,7 +29,7 @@ // dlsym search path, which breaks (usually valid) assumptions made in // sandbox::InitLibcUrandomOverrides(). See http://crbug.com/374712. if (!browser_context) { - content::BrowserContext::SaveSessionState(NULL); + content::BrowserContext::SaveSessionState(nullptr); NOTREACHED(); } } @@ -38,7 +38,7 @@ #if defined(OS_WIN) int APIENTRY wWinMain(HINSTANCE instance, HINSTANCE, wchar_t*, int) { - sandbox::SandboxInterfaceInfo sandbox_info = {0}; + sandbox::SandboxInterfaceInfo sandbox_info = {nullptr}; content::InitializeSandboxInfo(&sandbox_info); ui::ViewsContentClient views_content_client(instance, &sandbox_info); #else
diff --git a/ui/views/examples/label_example.cc b/ui/views/examples/label_example.cc index c9cf287..3a77ad13 100644 --- a/ui/views/examples/label_example.cc +++ b/ui/views/examples/label_example.cc
@@ -60,13 +60,12 @@ LabelExample::LabelExample() : ExampleBase("Label"), - textfield_(NULL), - alignment_(NULL), - elide_behavior_(NULL), - multiline_(NULL), - shadows_(NULL), - custom_label_(NULL) { -} + textfield_(nullptr), + alignment_(nullptr), + elide_behavior_(nullptr), + multiline_(nullptr), + shadows_(nullptr), + custom_label_(nullptr) {} LabelExample::~LabelExample() = default;
diff --git a/ui/views/examples/multiline_example.cc b/ui/views/examples/multiline_example.cc index 02995b8..52a94d5 100644 --- a/ui/views/examples/multiline_example.cc +++ b/ui/views/examples/multiline_example.cc
@@ -123,11 +123,11 @@ MultilineExample::MultilineExample() : ExampleBase("Multiline RenderText"), - render_text_view_(NULL), - label_(NULL), - textfield_(NULL), - label_checkbox_(NULL), - elision_checkbox_(NULL) {} + render_text_view_(nullptr), + label_(nullptr), + textfield_(nullptr), + label_checkbox_(nullptr), + elision_checkbox_(nullptr) {} MultilineExample::~MultilineExample() { }
diff --git a/ui/views/examples/scroll_view_example.cc b/ui/views/examples/scroll_view_example.cc index 8dbebef9..921a0fe 100644 --- a/ui/views/examples/scroll_view_example.cc +++ b/ui/views/examples/scroll_view_example.cc
@@ -28,7 +28,7 @@ public: ScrollableView() { SetColor(SK_ColorRED, SK_ColorCYAN); - AddChildView(new LabelButton(NULL, ASCIIToUTF16("Button"))); + AddChildView(new LabelButton(nullptr, ASCIIToUTF16("Button"))); AddChildView(new RadioButton(ASCIIToUTF16("Radio Button"), 0)); }
diff --git a/ui/views/examples/slider_example.cc b/ui/views/examples/slider_example.cc index d08b944..a2df682 100644 --- a/ui/views/examples/slider_example.cc +++ b/ui/views/examples/slider_example.cc
@@ -16,10 +16,7 @@ namespace examples { SliderExample::SliderExample() - : ExampleBase("Slider"), - slider_(NULL), - label_(NULL) { -} + : ExampleBase("Slider"), slider_(nullptr), label_(nullptr) {} SliderExample::~SliderExample() { }
diff --git a/ui/views/examples/tabbed_pane_example.cc b/ui/views/examples/tabbed_pane_example.cc index 1c1bb2f..7fbbc74 100644 --- a/ui/views/examples/tabbed_pane_example.cc +++ b/ui/views/examples/tabbed_pane_example.cc
@@ -61,7 +61,7 @@ AddButton("Added"); } else if (sender == add_at_) { const base::string16 label = ASCIIToUTF16("Added at 1"); - tabbed_pane_->AddTabAtIndex(1, label, new LabelButton(NULL, label)); + tabbed_pane_->AddTabAtIndex(1, label, new LabelButton(nullptr, label)); } else if (sender == select_at_) { if (tabbed_pane_->GetTabCount() > 1) tabbed_pane_->SelectTabAt(1); @@ -81,7 +81,7 @@ } void TabbedPaneExample::AddButton(const std::string& label) { - LabelButton* button = new LabelButton(NULL, ASCIIToUTF16(label)); + LabelButton* button = new LabelButton(nullptr, ASCIIToUTF16(label)); tabbed_pane_->AddTab(ASCIIToUTF16(label), button); }
diff --git a/ui/views/examples/table_example.cc b/ui/views/examples/table_example.cc index 68b17a2..c2e4291f 100644 --- a/ui/views/examples/table_example.cc +++ b/ui/views/examples/table_example.cc
@@ -31,13 +31,12 @@ } // namespace -TableExample::TableExample() : ExampleBase("Table") , table_(NULL) { -} +TableExample::TableExample() : ExampleBase("Table"), table_(nullptr) {} TableExample::~TableExample() { // Delete the view before the model. delete table_; - table_ = NULL; + table_ = nullptr; } void TableExample::CreateExampleView(View* container) {
diff --git a/ui/views/examples/webview_example.cc b/ui/views/examples/webview_example.cc index 3910b87..205a465 100644 --- a/ui/views/examples/webview_example.cc +++ b/ui/views/examples/webview_example.cc
@@ -14,9 +14,8 @@ WebViewExample::WebViewExample(content::BrowserContext* browser_context) : ExampleBase("WebView"), - webview_(NULL), - browser_context_(browser_context) { -} + webview_(nullptr), + browser_context_(browser_context) {} WebViewExample::~WebViewExample() { }
diff --git a/ui/views/examples/widget_example.cc b/ui/views/examples/widget_example.cc index 960d5f6..fb014b2a 100644 --- a/ui/views/examples/widget_example.cc +++ b/ui/views/examples/widget_example.cc
@@ -123,14 +123,15 @@ ShowWidget(sender, Widget::InitParams(Widget::InitParams::TYPE_POPUP)); break; case DIALOG: { - DialogDelegate::CreateDialogWidget(new WidgetDialogExample(), NULL, + DialogDelegate::CreateDialogWidget(new WidgetDialogExample(), nullptr, sender->GetWidget()->GetNativeView()) ->Show(); break; } case MODAL_DIALOG: { - DialogDelegate::CreateDialogWidget(new ModalDialogExample(), NULL, - sender->GetWidget()->GetNativeView())->Show(); + DialogDelegate::CreateDialogWidget(new ModalDialogExample(), nullptr, + sender->GetWidget()->GetNativeView()) + ->Show(); break; } case CHILD:
diff --git a/ui/views/focus/focus_manager_unittest.cc b/ui/views/focus/focus_manager_unittest.cc index 6555179..4e10bdd9 100644 --- a/ui/views/focus/focus_manager_unittest.cc +++ b/ui/views/focus/focus_manager_unittest.cc
@@ -113,7 +113,7 @@ // Required for VS2010: // http://connect.microsoft.com/VisualStudio/feedback/details/520043/error-converting-from-null-to-a-pointer-type-in-std-pair - views::View* null_view = NULL; + views::View* null_view = nullptr; view1->RequestFocus(); ASSERT_EQ(1, static_cast<int>(listener.focus_changes().size())); @@ -419,7 +419,7 @@ class FocusManagerDtorTracked : public FocusManager { public: FocusManagerDtorTracked(Widget* widget, DtorTrackVector* dtor_tracker) - : FocusManager(widget, NULL /* delegate */), + : FocusManager(widget, nullptr /* delegate */), dtor_tracker_(dtor_tracker) {} ~FocusManagerDtorTracked() override { @@ -476,7 +476,7 @@ } void TearDown() override { - FocusManagerFactory::Install(NULL); + FocusManagerFactory::Install(nullptr); ViewsTestBase::TearDown(); } @@ -488,7 +488,7 @@ class FocusInAboutToRequestFocusFromTabTraversalView : public View { public: - FocusInAboutToRequestFocusFromTabTraversalView() : view_to_focus_(NULL) {} + FocusInAboutToRequestFocusFromTabTraversalView() : view_to_focus_(nullptr) {} void set_view_to_focus(View* view) { view_to_focus_ = view; } @@ -713,14 +713,14 @@ GetFocusManager()->SetFocusedView(view); GetFocusManager()->StoreFocusedView(false); - EXPECT_EQ(NULL, GetFocusManager()->GetFocusedView()); + EXPECT_EQ(nullptr, GetFocusManager()->GetFocusedView()); EXPECT_TRUE(GetFocusManager()->RestoreFocusedView()); EXPECT_EQ(view, GetFocusManager()->GetStoredFocusView()); // Repeat with |true|. GetFocusManager()->SetFocusedView(view); GetFocusManager()->StoreFocusedView(true); - EXPECT_EQ(NULL, GetFocusManager()->GetFocusedView()); + EXPECT_EQ(nullptr, GetFocusManager()->GetFocusedView()); EXPECT_TRUE(GetFocusManager()->RestoreFocusedView()); EXPECT_EQ(view, GetFocusManager()->GetStoredFocusView()); }
diff --git a/ui/views/focus/focus_search.cc b/ui/views/focus/focus_search.cc index 5c0b32d..c943ac3 100644 --- a/ui/views/focus/focus_search.cc +++ b/ui/views/focus/focus_search.cc
@@ -34,15 +34,11 @@ FocusSearch::AnchoredDialogPolicy can_go_into_anchored_dialog, FocusTraversable** focus_traversable, View** focus_traversable_view) { + DCHECK(!root_->children().empty()); + *focus_traversable = nullptr; *focus_traversable_view = nullptr; - if (!root_->has_children()) { - NOTREACHED(); - // Nothing to focus on here. - return nullptr; - } - View* initial_starting_view = starting_view; int starting_view_group = -1; if (starting_view) @@ -196,7 +192,7 @@ // First let's try the left child. if (can_go_down) { - if (starting_view->has_children()) { + if (!starting_view->children().empty()) { View* v = FindNextFocusableViewImpl( starting_view->child_at(0), StartingViewPolicy::kCheckStartingView, false, true, can_go_into_anchored_dialog, skip_group_id, seen_views, @@ -318,7 +314,7 @@ can_go_into_anchored_dialog = AnchoredDialogPolicy::kCanGoIntoAnchoredDialog; - if (starting_view->has_children()) { + if (!starting_view->children().empty()) { View* view = starting_view->child_at(starting_view->child_count() - 1); View* v = FindPreviousFocusableViewImpl(
diff --git a/ui/views/focus/focus_traversal_unittest.cc b/ui/views/focus/focus_traversal_unittest.cc index 25c8f124..daf0cae1 100644 --- a/ui/views/focus/focus_traversal_unittest.cc +++ b/ui/views/focus/focus_traversal_unittest.cc
@@ -102,7 +102,7 @@ // A View that can act as a pane. class PaneView : public View, public FocusTraversable { public: - PaneView() : focus_search_(NULL) {} + PaneView() : focus_search_(nullptr) {} // If this method is called, this view will use GetPaneFocusTraversable to // have this provided FocusSearch used instead of the default one, allowing @@ -116,13 +116,13 @@ if (focus_search_) return this; else - return NULL; + return nullptr; } // Overridden from FocusTraversable: views::FocusSearch* GetFocusSearch() override { return focus_search_; } - FocusTraversable* GetFocusTraversableParent() override { return NULL; } - View* GetFocusTraversableParentView() override { return NULL; } + FocusTraversable* GetFocusTraversableParent() override { return nullptr; } + View* GetFocusTraversableParentView() override { return nullptr; } private: FocusSearch* focus_search_; @@ -198,7 +198,7 @@ view = search_border_view_->GetContentsRootView()->GetViewByID(id); if (view) return view; - return NULL; + return nullptr; } protected: @@ -230,9 +230,7 @@ }; FocusTraversalTest::FocusTraversalTest() - : style_tab_(NULL), - search_border_view_(NULL) { -} + : style_tab_(nullptr), search_border_view_(nullptr) {} FocusTraversalTest::~FocusTraversalTest() { } @@ -375,7 +373,7 @@ y += label_height + gap_between_labels; - LabelButton* button = MdTextButton::Create(NULL, ASCIIToUTF16("Click me")); + LabelButton* button = MdTextButton::Create(nullptr, ASCIIToUTF16("Click me")); button->SetBounds(label_x, y + 10, 80, 30); button->set_id(FRUIT_BUTTON_ID); left_container_->AddChildView(button); @@ -470,27 +468,27 @@ y = 250; int width = 60; - button = MdTextButton::Create(NULL, ASCIIToUTF16("OK")); + button = MdTextButton::Create(nullptr, ASCIIToUTF16("OK")); button->set_id(OK_BUTTON_ID); button->SetIsDefault(true); GetContentsView()->AddChildView(button); button->SetBounds(150, y, width, 30); - button = MdTextButton::Create(NULL, ASCIIToUTF16("Cancel")); + button = MdTextButton::Create(nullptr, ASCIIToUTF16("Cancel")); button->set_id(CANCEL_BUTTON_ID); GetContentsView()->AddChildView(button); button->SetBounds(220, y, width, 30); - button = MdTextButton::Create(NULL, ASCIIToUTF16("Help")); + button = MdTextButton::Create(nullptr, ASCIIToUTF16("Help")); button->set_id(HELP_BUTTON_ID); GetContentsView()->AddChildView(button); button->SetBounds(290, y, width, 30); y += 40; - View* contents = NULL; - Link* link = NULL; + View* contents = nullptr; + Link* link = nullptr; // Left bottom box with style checkboxes. contents = new View(); @@ -535,7 +533,7 @@ text_field->SetBounds(10, 10, 100, 20); text_field->set_id(SEARCH_TEXTFIELD_ID); - button = MdTextButton::Create(NULL, ASCIIToUTF16("Search")); + button = MdTextButton::Create(nullptr, ASCIIToUTF16("Search")); contents->AddChildView(button); button->SetBounds(112, 5, 60, 30); button->set_id(SEARCH_BUTTON_ID); @@ -558,11 +556,11 @@ contents->SetFocusBehavior(View::FocusBehavior::ALWAYS); contents->SetBackground(CreateSolidBackground(SK_ColorBLUE)); contents->set_id(THUMBNAIL_CONTAINER_ID); - button = MdTextButton::Create(NULL, ASCIIToUTF16("Star")); + button = MdTextButton::Create(nullptr, ASCIIToUTF16("Star")); contents->AddChildView(button); button->SetBounds(5, 5, 50, 30); button->set_id(THUMBNAIL_STAR_ID); - button = MdTextButton::Create(NULL, ASCIIToUTF16("SuperStar")); + button = MdTextButton::Create(nullptr, ASCIIToUTF16("SuperStar")); contents->AddChildView(button); button->SetBounds(60, 5, 100, 30); button->set_id(THUMBNAIL_SUPER_STAR_ID); @@ -707,7 +705,7 @@ // Let's disable some views. for (size_t i = 0; i < base::size(kDisabledIDs); i++) { View* v = FindViewByID(kDisabledIDs[i]); - ASSERT_TRUE(v != NULL); + ASSERT_TRUE(v != nullptr); v->SetEnabled(false); } @@ -747,7 +745,7 @@ // Let's make some views invisible. for (size_t i = 0; i < base::size(kInvisibleIDs); i++) { View* v = FindViewByID(kInvisibleIDs[i]); - ASSERT_TRUE(v != NULL); + ASSERT_TRUE(v != nullptr); v->SetVisible(false); }
diff --git a/ui/views/layout/fill_layout.cc b/ui/views/layout/fill_layout.cc index 731504e2..8bbf6b78 100644 --- a/ui/views/layout/fill_layout.cc +++ b/ui/views/layout/fill_layout.cc
@@ -13,7 +13,7 @@ FillLayout::~FillLayout() {} void FillLayout::Layout(View* host) { - if (!host->has_children()) + if (host->children().empty()) return; for (int i = 0; i < host->child_count(); ++i) @@ -21,7 +21,7 @@ } gfx::Size FillLayout::GetPreferredSize(const View* host) const { - if (!host->has_children()) + if (host->children().empty()) return gfx::Size(); gfx::Size preferred_size; @@ -33,7 +33,7 @@ } int FillLayout::GetPreferredHeightForWidth(const View* host, int width) const { - if (!host->has_children()) + if (host->children().empty()) return 0; const gfx::Insets insets = host->GetInsets();
diff --git a/ui/views/mouse_watcher.h b/ui/views/mouse_watcher.h index d27dc09..e0bead0 100644 --- a/ui/views/mouse_watcher.h +++ b/ui/views/mouse_watcher.h
@@ -78,7 +78,7 @@ class Observer; // Are we currently observing events? - bool is_observing() const { return observer_.get() != NULL; } + bool is_observing() const { return observer_.get() != nullptr; } // Notifies the listener and stops watching events. void NotifyListener();
diff --git a/ui/views/test/combobox_test_api.cc b/ui/views/test/combobox_test_api.cc index b443d94..5a66d2d 100644 --- a/ui/views/test/combobox_test_api.cc +++ b/ui/views/test/combobox_test_api.cc
@@ -60,5 +60,5 @@ return combobox_->menu_model_.get(); } -} // test -} // views +} // namespace test +} // namespace views
diff --git a/ui/views/test/menu_runner_test_api.cc b/ui/views/test/menu_runner_test_api.cc index 0ad00ad8..13f1c6e 100644 --- a/ui/views/test/menu_runner_test_api.cc +++ b/ui/views/test/menu_runner_test_api.cc
@@ -24,5 +24,5 @@ menu_runner_->SetRunnerHandler(std::move(menu_runner_handler)); } -} // test -} // views +} // namespace test +} // namespace views
diff --git a/ui/views/test/test_widget_observer.cc b/ui/views/test/test_widget_observer.cc index 160f25b2..155353d 100644 --- a/ui/views/test/test_widget_observer.cc +++ b/ui/views/test/test_widget_observer.cc
@@ -22,7 +22,7 @@ void TestWidgetObserver::OnWidgetDestroying(Widget* widget) { DCHECK_EQ(widget_, widget); - widget_ = NULL; + widget_ = nullptr; } } // namespace test
diff --git a/ui/views/test/test_widget_observer.h b/ui/views/test/test_widget_observer.h index 5580bb6..4b828b9 100644 --- a/ui/views/test/test_widget_observer.h +++ b/ui/views/test/test_widget_observer.h
@@ -20,7 +20,7 @@ explicit TestWidgetObserver(Widget* widget); ~TestWidgetObserver() override; - bool widget_closed() const { return widget_ == NULL; } + bool widget_closed() const { return widget_ == nullptr; } private: // WidgetObserver overrides:
diff --git a/ui/views/test/views_test_helper.cc b/ui/views/test/views_test_helper.cc index 75588a6c..e0793f1 100644 --- a/ui/views/test/views_test_helper.cc +++ b/ui/views/test/views_test_helper.cc
@@ -19,7 +19,7 @@ } gfx::NativeWindow ViewsTestHelper::GetContext() { - return NULL; + return nullptr; } } // namespace views
diff --git a/ui/views/test/widget_test_unittest.cc b/ui/views/test/widget_test_unittest.cc index f810b36..416af4d7 100644 --- a/ui/views/test/widget_test_unittest.cc +++ b/ui/views/test/widget_test_unittest.cc
@@ -113,5 +113,5 @@ ExpectClose(&expected, {frameless}, "frameless"); } -} // namespace views } // namespace test +} // namespace views
diff --git a/ui/views/view.cc b/ui/views/view.cc index 6953d53..2070c2a2 100644 --- a/ui/views/view.cc +++ b/ui/views/view.cc
@@ -169,18 +169,17 @@ DCHECK(!iterating_); #endif children_.erase(i); + const auto pos = children_.insert(std::next(children_.begin(), index), view); - // Unlink the view first + // Update focus siblings. Unhook |view| from the focus cycle first so + // SetFocusSiblings() won't traverse through it. View* next_focusable = view->next_focusable_view_; View* prev_focusable = view->previous_focusable_view_; if (prev_focusable) prev_focusable->next_focusable_view_ = next_focusable; if (next_focusable) next_focusable->previous_focusable_view_ = prev_focusable; - - // Add it in the specified index now. - InitFocusSiblings(view, index); - children_.insert(children_.begin() + index, view); + SetFocusSiblings(view, pos); for (ViewObserver& observer : observers_) observer.OnChildViewReordered(this, view); @@ -208,8 +207,12 @@ return false; } +View::Views::const_iterator View::FindChild(const View* view) const { + return std::find(children_.cbegin(), children_.cend(), view); +} + int View::GetIndexOf(const View* view) const { - const auto i = std::find(children_.cbegin(), children_.cend(), view); + const auto i = FindChild(view); return i == children_.cend() ? -1 : static_cast<int>(std::distance(children_.cbegin(), i)); @@ -438,35 +441,41 @@ void View::SetTransform(const gfx::Transform& transform) { if (transform.IsIdentity()) { - if (layer()) { + if (layer()) layer()->SetTransform(transform); - if (!paint_to_layer_) - DestroyLayer(); - } else { - // Nothing. - } + paint_to_layer_for_transform_ = false; + CreateOrDestroyLayer(); } else { - if (!layer()) - CreateLayer(ui::LAYER_TEXTURED); + paint_to_layer_for_transform_ = true; + CreateOrDestroyLayer(); + DCHECK_NE(layer(), nullptr); layer()->SetTransform(transform); layer()->ScheduleDraw(); } } void View::SetPaintToLayer(ui::LayerType layer_type) { - if (paint_to_layer_ && (layer()->type() == layer_type)) - return; + // Avoid re-creating the layer if unnecessary. + if (paint_to_layer_explicitly_set_) { + DCHECK_NE(layer(), nullptr); + if (layer()->type() == layer_type) + return; + } DestroyLayerImpl(LayerChangeNotifyBehavior::DONT_NOTIFY); + paint_to_layer_explicitly_set_ = true; + + // We directly call |CreateLayer()| here to pass |layer_type|. A call to + // |CreateOrDestroyLayer()| is therefore not necessary. CreateLayer(layer_type); - paint_to_layer_ = true; // Notify the parent chain about the layer change. NotifyParentsOfLayerChange(); } void View::DestroyLayer() { - DestroyLayerImpl(LayerChangeNotifyBehavior::NOTIFY); + paint_to_layer_explicitly_set_ = false; + CreateOrDestroyLayer(); } std::unique_ptr<ui::Layer> View::RecreateLayer() { @@ -1564,10 +1573,6 @@ } void View::DestroyLayerImpl(LayerChangeNotifyBehavior notify_parents) { - if (!paint_to_layer_) - return; - - paint_to_layer_ = false; if (!layer()) return; @@ -1645,6 +1650,17 @@ } } +void View::CreateOrDestroyLayer() { + if (paint_to_layer_explicitly_set_ || paint_to_layer_for_transform_) { + // If we need to paint to a layer, make sure we have one. + if (!layer()) + CreateLayer(ui::LAYER_TEXTURED); + } else if (layer()) { + // If we don't, make sure we delete our layer. + DestroyLayerImpl(LayerChangeNotifyBehavior::NOTIFY); + } +} + void View::ReorderLayers() { View* v = this; while (v && !v->layer()) @@ -1918,14 +1934,13 @@ parent->DoRemoveChildView(view, true, true, false, this); } - // Sets the prev/next focus views. - InitFocusSiblings(view, index); - view->parent_ = this; #if DCHECK_IS_ON() DCHECK(!iterating_); #endif - children_.insert(children_.begin() + index, view); + const auto pos = children_.insert(std::next(children_.cbegin(), index), view); + + SetFocusSiblings(view, pos); // Ensure the layer tree matches the view tree before calling to any client // code. This way if client code further modifies the view tree we are in a @@ -2410,8 +2425,8 @@ (enabled_ && event.IsOnlyLeftMouseButton() && HitTestPoint(event.location())) ? GetDragOperations(event.location()) : 0; - ContextMenuController* context_menu_controller = event.IsRightMouseButton() ? - context_menu_controller_ : 0; + ContextMenuController* context_menu_controller = + event.IsRightMouseButton() ? context_menu_controller_ : nullptr; View::DragInfo* drag_info = GetDragInfo(); const bool enabled = enabled_; @@ -2534,49 +2549,40 @@ // Focus ----------------------------------------------------------------------- -void View::InitFocusSiblings(View* v, int index) { - int count = child_count(); +void View::SetFocusSiblings(View* view, Views::const_iterator pos) { + // |view| was just inserted at |pos|, so all of these conditions must hold. + DCHECK(!children_.empty()); + DCHECK(pos != children_.cend()); + DCHECK_EQ(view, *pos); - if (count == 0) { - v->next_focusable_view_ = nullptr; - v->previous_focusable_view_ = nullptr; - } else { - if (index == count) { - // We are inserting at the end, but the end of the child list may not be - // the last focusable element. Let's try to find an element with no next - // focusable element to link to. - View* last_focusable_view = nullptr; - { - internal::ScopedChildrenLock lock(this); - for (auto* child : children_) { - if (!child->next_focusable_view_) { - last_focusable_view = child; - break; - } - } + View* prev = nullptr; + View* next = nullptr; + if (children_.size() > 1) { + if (pos == std::prev(children_.cend())) { + // |view| was inserted at the end, but the end of the child list may not + // be the last focusable element. Try to hook in after the last focusable + // child. + prev = *std::find_if(children_.cbegin(), pos, + [](View* v) { return !v->next_focusable_view_; }); + if (prev == view) { + // There is a cycle in the focus list. Insert |view| after the last + // child. + prev = *std::prev(pos); } - if (last_focusable_view == nullptr) { - // Hum... there is a cycle in the focus list. Let's just insert ourself - // after the last child. - View* prev = children_[index - 1]; - v->previous_focusable_view_ = prev; - v->next_focusable_view_ = prev->next_focusable_view_; - prev->next_focusable_view_->previous_focusable_view_ = v; - prev->next_focusable_view_ = v; - } else { - last_focusable_view->next_focusable_view_ = v; - v->next_focusable_view_ = nullptr; - v->previous_focusable_view_ = last_focusable_view; - } + next = prev->next_focusable_view_; } else { - View* prev = children_[index]->GetPreviousFocusableView(); - v->previous_focusable_view_ = prev; - v->next_focusable_view_ = children_[index]; - if (prev) - prev->next_focusable_view_ = v; - children_[index]->previous_focusable_view_ = v; + // |view| was inserted somewhere other than the end. Hook in before the + // subsequent child. + next = *std::next(pos); + prev = next->GetPreviousFocusableView(); } } + if (prev) + prev->next_focusable_view_ = view; + view->previous_focusable_view_ = prev; + view->next_focusable_view_ = next; + if (next) + next->previous_focusable_view_ = view; } void View::AdvanceFocusIfNecessary() {
diff --git a/ui/views/view.h b/ui/views/view.h index 3fd9795..c017e0c 100644 --- a/ui/views/view.h +++ b/ui/views/view.h
@@ -137,10 +137,7 @@ struct ViewHierarchyChangedDetails { ViewHierarchyChangedDetails() - : is_add(false), - parent(NULL), - child(NULL), - move_view(NULL) {} + : is_add(false), parent(nullptr), child(nullptr), move_view(nullptr) {} ViewHierarchyChangedDetails(bool is_add, View* parent, @@ -295,8 +292,7 @@ // for new code. template <typename T> T* AddChildView(T* view) { - if (static_cast<View*>(view)->parent_ != this) - AddChildViewAtImpl(view, child_count()); + AddChildViewAtImpl(view, child_count()); return view; } template <typename T> @@ -316,10 +312,11 @@ // the views are deleted, unless marked as not parent owned. void RemoveAllChildViews(bool delete_children); + // TODO(https://crbug.com/940135): Remove child_count() and child_at() in + // favor of this. + const Views& children() const { return children_; } + int child_count() const { return static_cast<int>(children_.size()); } - // See also |GetChildrenInZOrder()| below that returns |children_| - // in reverse z-order. - bool has_children() const { return !children_.empty(); } // Returns the child view at |index|. const View* child_at(int index) const { @@ -339,6 +336,10 @@ // an indirect descendant. Will return true if child is also this view. bool Contains(const View* view) const; + // Returns an iterator pointing to |view|, or children_.cend() if |view| is + // not a child of this view. + Views::const_iterator FindChild(const View* view) const; + // Returns the index of |view|, or -1 if |view| is not a child of this view. int GetIndexOf(const View* view) const; @@ -480,8 +481,9 @@ // regardless of the ordering returned by GetChildrenInZOrder(). void SetPaintToLayer(ui::LayerType layer_type = ui::LAYER_TEXTURED); - // Please refer to the comments above the DestroyLayerImpl() function for - // details. + // Cancels layer painting triggered by a call to |SetPaintToLayer()|. Note + // that this will not actually destroy the layer if the view paints to a layer + // for another reason. void DestroyLayer(); // Overridden from ui::LayerOwner: @@ -1623,11 +1625,14 @@ // change is sent to the parents. void DestroyLayerImpl(LayerChangeNotifyBehavior notify_parents); + // Determines whether we need to be painting to a layer, checks whether we + // currently have a layer, and creates or destroys the layer if necessary. + void CreateOrDestroyLayer(); + // Notifies parents about layering changes in the view. This includes layer // creation and destruction. void NotifyParentsOfLayerChange(); - // Orphans the layers in this subtree that are parented to layers outside of // this subtree. void OrphanLayers(); @@ -1659,9 +1664,9 @@ // Focus --------------------------------------------------------------------- - // Initialize the previous/next focusable views of the specified view relative - // to the view at the specified index. - void InitFocusSiblings(View* view, int index); + // Sets previous/next focusable views for both |view| and other children + // assuming we've just inserted |view| at |pos|. + void SetFocusSiblings(View* view, Views::const_iterator pos); // Helper function to advance focus, in case the currently focused view has // become unfocusable. @@ -1812,7 +1817,11 @@ // Accelerated painting ------------------------------------------------------ - bool paint_to_layer_ = false; + // Whether layer painting was explicitly set by a call to |SetPaintToLayer()|. + bool paint_to_layer_explicitly_set_ = false; + + // Whether we are painting to a layer because of a non-identity transform. + bool paint_to_layer_for_transform_ = false; // Accelerators --------------------------------------------------------------
diff --git a/ui/views/view_model.h b/ui/views/view_model.h index 47a3808..9513bcf 100644 --- a/ui/views/view_model.h +++ b/ui/views/view_model.h
@@ -80,7 +80,7 @@ friend class ViewModelUtils; struct Entry { - Entry() : view(NULL) {} + Entry() : view(nullptr) {} View* view; gfx::Rect ideal_bounds;
diff --git a/ui/views/view_targeter.cc b/ui/views/view_targeter.cc index 641e286..ec82f84 100644 --- a/ui/views/view_targeter.cc +++ b/ui/views/view_targeter.cc
@@ -45,14 +45,14 @@ } NOTREACHED() << "ViewTargeter does not yet support this event type."; - return NULL; + return nullptr; } ui::EventTarget* ViewTargeter::FindNextBestTarget( ui::EventTarget* previous_target, ui::Event* event) { if (!previous_target) - return NULL; + return nullptr; if (event->IsGestureEvent()) { ui::GestureEvent* gesture = event->AsGestureEvent(); @@ -68,7 +68,7 @@ View* ViewTargeter::FindTargetForKeyEvent(View* root, const ui::KeyEvent& key) { if (root->GetFocusManager()) return root->GetFocusManager()->GetFocusedView(); - return NULL; + return nullptr; } View* ViewTargeter::FindTargetForScrollEvent(View* root, @@ -85,14 +85,14 @@ // here if we need to be able to perform gesture targeting // starting at an arbitrary node in a Views tree. NOTREACHED(); - return NULL; + return nullptr; } ui::EventTarget* ViewTargeter::FindNextBestTargetForGestureEvent( ui::EventTarget* previous_target, const ui::GestureEvent& gesture) { NOTREACHED(); - return NULL; + return nullptr; } } // namespace views
diff --git a/ui/views/view_targeter_delegate.cc b/ui/views/view_targeter_delegate.cc index 7347141..0d30956 100644 --- a/ui/views/view_targeter_delegate.cc +++ b/ui/views/view_targeter_delegate.cc
@@ -36,12 +36,12 @@ // |rect_view_distance| is used to keep track of the distance // between the center point of |rect_view| and the center // point of |rect|. - View* rect_view = NULL; + View* rect_view = nullptr; int rect_view_distance = INT_MAX; // |point_view| represents the view that would have been returned // from this function call if point-based targeting were used. - View* point_view = NULL; + View* point_view = nullptr; View::Views children = root->GetChildrenInZOrder(); DCHECK_EQ(root->child_count(), static_cast<int>(children.size()));
diff --git a/ui/views/view_targeter_unittest.cc b/ui/views/view_targeter_unittest.cc index 808f91a..f6aadbd 100644 --- a/ui/views/view_targeter_unittest.cc +++ b/ui/views/view_targeter_unittest.cc
@@ -159,7 +159,7 @@ EXPECT_EQ(widget.GetRootView(), static_cast<View*>(current_target)); current_target = targeter->FindNextBestTarget(widget.GetRootView(), &key_event); - EXPECT_EQ(NULL, static_cast<View*>(current_target)); + EXPECT_EQ(nullptr, static_cast<View*>(current_target)); } // Verifies that the the functions ViewTargeter::FindTargetForEvent() @@ -210,7 +210,7 @@ EXPECT_EQ(widget.GetRootView(), static_cast<View*>(current_target)); current_target = targeter->FindNextBestTarget(widget.GetRootView(), &scroll); - EXPECT_EQ(NULL, static_cast<View*>(current_target)); + EXPECT_EQ(nullptr, static_cast<View*>(current_target)); // The event falls outside of the original specified bounds of |content|, // |child|, and |grandchild|. But since |content| is the contents view, @@ -292,14 +292,14 @@ SetGestureHandlerSetBeforeProcessing(root_view, true); SetGestureHandler(root_view, grandchild); EXPECT_EQ(grandchild, targeter->FindTargetForEvent(root_view, &tap)); - EXPECT_EQ(NULL, targeter->FindNextBestTarget(grandchild, &tap)); + EXPECT_EQ(nullptr, targeter->FindNextBestTarget(grandchild, &tap)); EXPECT_EQ(grandchild, targeter->FindTargetForEvent(root_view, &scroll_begin)); EXPECT_EQ(child, targeter->FindNextBestTarget(grandchild, &scroll_begin)); // GESTURE_END events should be targeted to the existing gesture handler, // but re-targeting should be prohibited. EXPECT_EQ(grandchild, targeter->FindTargetForEvent(root_view, &end)); - EXPECT_EQ(NULL, targeter->FindNextBestTarget(grandchild, &end)); + EXPECT_EQ(nullptr, targeter->FindNextBestTarget(grandchild, &end)); // Assume that the view currently handling gestures is still set as // |grandchild|, but this was not done by a previous gesture. Thus we are @@ -313,18 +313,18 @@ // GESTURE_END events are not permitted to be re-targeted up the ancestor // chain; they are only ever targeted in the case where the gesture handler // was established by a previous gesture. - EXPECT_EQ(NULL, targeter->FindNextBestTarget(grandchild, &end)); + EXPECT_EQ(nullptr, targeter->FindNextBestTarget(grandchild, &end)); // Assume that the default gesture handler was set by the previous gesture, // but that this handler is currently NULL. No gesture events should be // re-targeted in this case (regardless of the view that is passed in to // FindNextBestTarget() as the previous target). - SetGestureHandler(root_view, NULL); + SetGestureHandler(root_view, nullptr); SetGestureHandlerSetBeforeProcessing(root_view, true); - EXPECT_EQ(NULL, targeter->FindNextBestTarget(child, &tap)); - EXPECT_EQ(NULL, targeter->FindNextBestTarget(NULL, &tap)); - EXPECT_EQ(NULL, targeter->FindNextBestTarget(content, &scroll_begin)); - EXPECT_EQ(NULL, targeter->FindNextBestTarget(content, &end)); + EXPECT_EQ(nullptr, targeter->FindNextBestTarget(child, &tap)); + EXPECT_EQ(nullptr, targeter->FindNextBestTarget(nullptr, &tap)); + EXPECT_EQ(nullptr, targeter->FindNextBestTarget(content, &scroll_begin)); + EXPECT_EQ(nullptr, targeter->FindNextBestTarget(content, &end)); // Reset the locations of the gesture events to be in the root view // coordinate space since we are about to call FindTargetForEvent() @@ -350,8 +350,8 @@ // If no default gesture handler is currently set, GESTURE_END events // should never be re-targeted to any View. - EXPECT_EQ(NULL, targeter->FindNextBestTarget(NULL, &end)); - EXPECT_EQ(NULL, targeter->FindNextBestTarget(child, &end)); + EXPECT_EQ(nullptr, targeter->FindNextBestTarget(nullptr, &end)); + EXPECT_EQ(nullptr, targeter->FindNextBestTarget(child, &end)); } // Tests that the contents view is targeted instead of the root view for @@ -526,7 +526,7 @@ // The next target should be NULL and the location of the event should // remain unchanged. - EXPECT_EQ(NULL, targeter->FindNextBestTarget(widget.GetRootView(), &tap)); + EXPECT_EQ(nullptr, targeter->FindNextBestTarget(widget.GetRootView(), &tap)); EXPECT_EQ(location_in_root, tap.location()); }
diff --git a/ui/views/view_unittest.cc b/ui/views/view_unittest.cc index b101a0a..cdcd340 100644 --- a/ui/views/view_unittest.cc +++ b/ui/views/view_unittest.cc
@@ -69,7 +69,7 @@ // Convenience functions for walking a View tree. const views::View* FirstView(const views::View* view) { const views::View* v = view; - while (v->has_children()) + while (!v->children().empty()) v = v->child_at(0); return v; } @@ -79,9 +79,8 @@ const views::View* parent = v->parent(); if (!parent) return nullptr; - const int next = parent->GetIndexOf(v) + 1; - return (next == parent->child_count()) ? parent - : FirstView(parent->child_at(next)); + const auto next = std::next(parent->FindChild(v)); + return (next == parent->children().cend()) ? parent : FirstView(*next); } // Convenience functions for walking a Layer tree. @@ -95,7 +94,7 @@ const ui::Layer* NextLayer(const ui::Layer* layer) { const ui::Layer* parent = layer->parent(); if (!parent) - return NULL; + return nullptr; const std::vector<ui::Layer*> children = parent->children(); size_t index; for (index = 0; index < children.size(); index++) { @@ -211,7 +210,7 @@ did_layout_(false), delete_on_pressed_(false), did_paint_(false), - native_theme_(NULL), + native_theme_(nullptr), can_process_events_within_subtree_(true) {} ~TestView() override {} @@ -1406,67 +1405,67 @@ gfx::Rect touch_rect(105, 105, 30, 45); View* result_view = root_view->GetEventHandlerForRect(touch_rect); EXPECT_EQ(root_view, result_view); - result_view = NULL; + result_view = nullptr; // Covers |v1| by at least 60%. touch_rect.SetRect(15, 15, 100, 100); result_view = root_view->GetEventHandlerForRect(touch_rect); EXPECT_EQ(v1, result_view); - result_view = NULL; + result_view = nullptr; // Intersects |v1| but does not cover it by at least 60%. The center // of |touch_rect| is within |v1|. touch_rect.SetRect(50, 50, 5, 10); result_view = root_view->GetEventHandlerForRect(touch_rect); EXPECT_EQ(v1, result_view); - result_view = NULL; + result_view = nullptr; // Intersects |v1| but does not cover it by at least 60%. The center // of |touch_rect| is not within |v1|. touch_rect.SetRect(95, 96, 21, 22); result_view = root_view->GetEventHandlerForRect(touch_rect); EXPECT_EQ(root_view, result_view); - result_view = NULL; + result_view = nullptr; // Intersects |v1| and |v2|, but only covers |v2| by at least 60%. touch_rect.SetRect(95, 10, 300, 120); result_view = root_view->GetEventHandlerForRect(touch_rect); EXPECT_EQ(v2, result_view); - result_view = NULL; + result_view = nullptr; // Covers both |v1| and |v2| by at least 60%, but the center point // of |touch_rect| is closer to the center point of |v2|. touch_rect.SetRect(20, 20, 400, 100); result_view = root_view->GetEventHandlerForRect(touch_rect); EXPECT_EQ(v2, result_view); - result_view = NULL; + result_view = nullptr; // Covers both |v1| and |v2| by at least 60%, but the center point // of |touch_rect| is closer to the center point of |v1|. touch_rect.SetRect(-700, -15, 1050, 110); result_view = root_view->GetEventHandlerForRect(touch_rect); EXPECT_EQ(v1, result_view); - result_view = NULL; + result_view = nullptr; // A mouse click within |v1| will target |v1|. touch_rect.SetRect(15, 15, 1, 1); result_view = root_view->GetEventHandlerForRect(touch_rect); EXPECT_EQ(v1, result_view); - result_view = NULL; + result_view = nullptr; // Intersects |v3| and |v31| by at least 60% and the center point // of |touch_rect| is closer to the center point of |v31|. touch_rect.SetRect(0, 200, 110, 100); result_view = root_view->GetEventHandlerForRect(touch_rect); EXPECT_EQ(v31, result_view); - result_view = NULL; + result_view = nullptr; // Intersects |v3| and |v31|, but neither by at least 60%. The // center point of |touch_rect| lies within |v31|. touch_rect.SetRect(80, 280, 15, 15); result_view = root_view->GetEventHandlerForRect(touch_rect); EXPECT_EQ(v31, result_view); - result_view = NULL; + result_view = nullptr; // Covers |v3|, |v31|, and |v32| all by at least 60%, and the // center point of |touch_rect| is closest to the center point @@ -1474,7 +1473,7 @@ touch_rect.SetRect(0, 200, 200, 100); result_view = root_view->GetEventHandlerForRect(touch_rect); EXPECT_EQ(v32, result_view); - result_view = NULL; + result_view = nullptr; // Intersects all of |v3|, |v31|, and |v32|, but only covers // |v31| and |v32| by at least 60%. The center point of @@ -1482,19 +1481,19 @@ touch_rect.SetRect(30, 225, 180, 115); result_view = root_view->GetEventHandlerForRect(touch_rect); EXPECT_EQ(v32, result_view); - result_view = NULL; + result_view = nullptr; // A mouse click at the corner of |v3| will target |v3|. touch_rect.SetRect(0, 200, 1, 1); result_view = root_view->GetEventHandlerForRect(touch_rect); EXPECT_EQ(v3, result_view); - result_view = NULL; + result_view = nullptr; // A mouse click within |v32| will target |v32|. touch_rect.SetRect(112, 211, 1, 1); result_view = root_view->GetEventHandlerForRect(touch_rect); EXPECT_EQ(v32, result_view); - result_view = NULL; + result_view = nullptr; // Covers all of |v4|, |v41|, and |v411| by at least 60%. // The center point of |touch_rect| is equally close to @@ -1502,14 +1501,14 @@ touch_rect.SetRect(310, 210, 80, 80); result_view = root_view->GetEventHandlerForRect(touch_rect); EXPECT_EQ(v41, result_view); - result_view = NULL; + result_view = nullptr; // Intersects all of |v4|, |v41|, and |v411| but only covers // |v411| by at least 60%. touch_rect.SetRect(370, 275, 7, 5); result_view = root_view->GetEventHandlerForRect(touch_rect); EXPECT_EQ(v411, result_view); - result_view = NULL; + result_view = nullptr; // Intersects |v4| and |v41| but covers neither by at least 60%. // The center point of |touch_rect| is equally close to the center @@ -1517,7 +1516,7 @@ touch_rect.SetRect(345, 245, 7, 7); result_view = root_view->GetEventHandlerForRect(touch_rect); EXPECT_EQ(v41, result_view); - result_view = NULL; + result_view = nullptr; // Intersects all of |v4|, |v41|, and |v411| and covers none of // them by at least 60%. The center point of |touch_rect| lies @@ -1525,7 +1524,7 @@ touch_rect.SetRect(368, 272, 4, 6); result_view = root_view->GetEventHandlerForRect(touch_rect); EXPECT_EQ(v411, result_view); - result_view = NULL; + result_view = nullptr; // Intersects all of |v4|, |v41|, and |v411| and covers none of // them by at least 60%. The center point of |touch_rect| lies @@ -1533,7 +1532,7 @@ touch_rect.SetRect(365, 270, 7, 7); result_view = root_view->GetEventHandlerForRect(touch_rect); EXPECT_EQ(v41, result_view); - result_view = NULL; + result_view = nullptr; // Intersects all of |v4|, |v41|, and |v411| and covers none of // them by at least 60%. The center point of |touch_rect| lies @@ -1541,26 +1540,26 @@ touch_rect.SetRect(205, 275, 200, 2); result_view = root_view->GetEventHandlerForRect(touch_rect); EXPECT_EQ(v4, result_view); - result_view = NULL; + result_view = nullptr; // Intersects all of |v4|, |v41|, and |v411| but only covers // |v41| by at least 60%. touch_rect.SetRect(310, 210, 61, 66); result_view = root_view->GetEventHandlerForRect(touch_rect); EXPECT_EQ(v41, result_view); - result_view = NULL; + result_view = nullptr; // A mouse click within |v411| will target |v411|. touch_rect.SetRect(372, 275, 1, 1); result_view = root_view->GetEventHandlerForRect(touch_rect); EXPECT_EQ(v411, result_view); - result_view = NULL; + result_view = nullptr; // A mouse click within |v41| will target |v41|. touch_rect.SetRect(350, 215, 1, 1); result_view = root_view->GetEventHandlerForRect(touch_rect); EXPECT_EQ(v41, result_view); - result_view = NULL; + result_view = nullptr; // Covers |v3|, |v4|, and all of their descendants by at // least 60%. The center point of |touch_rect| is closest @@ -1568,7 +1567,7 @@ touch_rect.SetRect(0, 200, 400, 100); result_view = root_view->GetEventHandlerForRect(touch_rect); EXPECT_EQ(v32, result_view); - result_view = NULL; + result_view = nullptr; // Intersects all of |v2|, |v3|, |v32|, |v4|, |v41|, and |v411|. // Covers |v2|, |v32|, |v4|, |v41|, and |v411| by at least 60%. @@ -1577,7 +1576,7 @@ touch_rect.SetRect(110, 15, 375, 450); result_view = root_view->GetEventHandlerForRect(touch_rect); EXPECT_EQ(root_view, result_view); - result_view = NULL; + result_view = nullptr; // Covers all views (except |v5| and |v51|) by at least 60%. The // center point of |touch_rect| is equally close to the center @@ -1588,7 +1587,7 @@ touch_rect.SetRect(0, 0, 400, 300); result_view = root_view->GetEventHandlerForRect(touch_rect); EXPECT_EQ(v32, result_view); - result_view = NULL; + result_view = nullptr; // Covers |v5| and |v51| by at least 60%, and the center point of // the touch is located within both views. Since both views share @@ -1596,7 +1595,7 @@ touch_rect.SetRect(440, 190, 40, 40); result_view = root_view->GetEventHandlerForRect(touch_rect); EXPECT_EQ(v51, result_view); - result_view = NULL; + result_view = nullptr; // Covers |v5| and |v51| by at least 60%, but the center point of // the touch is not located within either view. Since both views @@ -1604,47 +1603,47 @@ touch_rect.SetRect(455, 187, 60, 60); result_view = root_view->GetEventHandlerForRect(touch_rect); EXPECT_EQ(v51, result_view); - result_view = NULL; + result_view = nullptr; // Covers neither |v5| nor |v51| by at least 60%, but the center // of the touch is located within |v51|. touch_rect.SetRect(450, 197, 10, 10); result_view = root_view->GetEventHandlerForRect(touch_rect); EXPECT_EQ(v51, result_view); - result_view = NULL; + result_view = nullptr; // Covers neither |v5| nor |v51| by at least 60% but intersects both. // The center point is located outside of both views. touch_rect.SetRect(433, 180, 24, 24); result_view = root_view->GetEventHandlerForRect(touch_rect); EXPECT_EQ(root_view, result_view); - result_view = NULL; + result_view = nullptr; // Only intersects |v5| but does not cover it by at least 60%. The // center point of the touch region is located within |v5|. touch_rect.SetRect(449, 196, 3, 3); result_view = root_view->GetEventHandlerForRect(touch_rect); EXPECT_EQ(v5, result_view); - result_view = NULL; + result_view = nullptr; // A mouse click within |v5| (but not |v51|) should target |v5|. touch_rect.SetRect(462, 199, 1, 1); result_view = root_view->GetEventHandlerForRect(touch_rect); EXPECT_EQ(v5, result_view); - result_view = NULL; + result_view = nullptr; // A mouse click |v5| and |v51| should target the child view. touch_rect.SetRect(452, 226, 1, 1); result_view = root_view->GetEventHandlerForRect(touch_rect); EXPECT_EQ(v51, result_view); - result_view = NULL; + result_view = nullptr; // A mouse click on the center of |v5| and |v51| should target // the child view. touch_rect.SetRect(465, 215, 1, 1); result_view = root_view->GetEventHandlerForRect(touch_rect); EXPECT_EQ(v51, result_view); - result_view = NULL; + result_view = nullptr; widget->CloseNow(); } @@ -1695,24 +1694,24 @@ View* result_view = root_view->GetEventHandlerForRect(rect_in_v_grandchild); EXPECT_EQ(v_grandchild, result_view); - result_view = NULL; + result_view = nullptr; result_view = root_view->GetTooltipHandlerForPoint(point_in_v_grandchild); EXPECT_EQ(v_grandchild, result_view); - result_view = NULL; + result_view = nullptr; result_view = root_view->GetEventHandlerForRect(rect_in_v_child); EXPECT_EQ(v_child, result_view); - result_view = NULL; + result_view = nullptr; result_view = root_view->GetTooltipHandlerForPoint(point_in_v_child); EXPECT_EQ(v_child, result_view); - result_view = NULL; + result_view = nullptr; result_view = root_view->GetEventHandlerForRect(rect_in_v); EXPECT_EQ(v, result_view); - result_view = NULL; + result_view = nullptr; result_view = root_view->GetTooltipHandlerForPoint(point_in_v); EXPECT_EQ(v, result_view); - result_view = NULL; + result_view = nullptr; // When |v_grandchild| returns false when CanProcessEventsWithinSubtree() // is called, then |v_grandchild| cannot be returned as a target. @@ -1721,21 +1720,21 @@ result_view = root_view->GetEventHandlerForRect(rect_in_v_grandchild); EXPECT_EQ(v_child, result_view); - result_view = NULL; + result_view = nullptr; result_view = root_view->GetTooltipHandlerForPoint(point_in_v_grandchild); EXPECT_EQ(v_child, result_view); - result_view = NULL; + result_view = nullptr; result_view = root_view->GetEventHandlerForRect(rect_in_v_child); EXPECT_EQ(v_child, result_view); - result_view = NULL; + result_view = nullptr; result_view = root_view->GetTooltipHandlerForPoint(point_in_v_child); EXPECT_EQ(v_child, result_view); - result_view = NULL; + result_view = nullptr; result_view = root_view->GetEventHandlerForRect(rect_in_v); EXPECT_EQ(v, result_view); - result_view = NULL; + result_view = nullptr; result_view = root_view->GetTooltipHandlerForPoint(point_in_v); EXPECT_EQ(v, result_view); @@ -1747,8 +1746,8 @@ result_view = v_grandchild; result_view = v_grandchild->GetTooltipHandlerForPoint(gfx::Point(1, 1)); - EXPECT_EQ(NULL, result_view); - result_view = NULL; + EXPECT_EQ(nullptr, result_view); + result_view = nullptr; // When |v_child| returns false when CanProcessEventsWithinSubtree() // is called, then neither |v_child| nor |v_grandchild| can be returned @@ -1759,24 +1758,24 @@ result_view = root_view->GetEventHandlerForRect(rect_in_v_grandchild); EXPECT_EQ(v, result_view); - result_view = NULL; + result_view = nullptr; result_view = root_view->GetTooltipHandlerForPoint(point_in_v_grandchild); EXPECT_EQ(v, result_view); - result_view = NULL; + result_view = nullptr; result_view = root_view->GetEventHandlerForRect(rect_in_v_child); EXPECT_EQ(v, result_view); - result_view = NULL; + result_view = nullptr; result_view = root_view->GetTooltipHandlerForPoint(point_in_v_child); EXPECT_EQ(v, result_view); - result_view = NULL; + result_view = nullptr; result_view = root_view->GetEventHandlerForRect(rect_in_v); EXPECT_EQ(v, result_view); - result_view = NULL; + result_view = nullptr; result_view = root_view->GetTooltipHandlerForPoint(point_in_v); EXPECT_EQ(v, result_view); - result_view = NULL; + result_view = nullptr; // When |v| returns false when CanProcessEventsWithinSubtree() // is called, then none of |v|, |v_child|, and |v_grandchild| can be returned @@ -1787,21 +1786,21 @@ result_view = root_view->GetEventHandlerForRect(rect_in_v_grandchild); EXPECT_EQ(root_view, result_view); - result_view = NULL; + result_view = nullptr; result_view = root_view->GetTooltipHandlerForPoint(point_in_v_grandchild); EXPECT_EQ(root_view, result_view); - result_view = NULL; + result_view = nullptr; result_view = root_view->GetEventHandlerForRect(rect_in_v_child); EXPECT_EQ(root_view, result_view); - result_view = NULL; + result_view = nullptr; result_view = root_view->GetTooltipHandlerForPoint(point_in_v_child); EXPECT_EQ(root_view, result_view); - result_view = NULL; + result_view = nullptr; result_view = root_view->GetEventHandlerForRect(rect_in_v); EXPECT_EQ(root_view, result_view); - result_view = NULL; + result_view = nullptr; result_view = root_view->GetTooltipHandlerForPoint(point_in_v); EXPECT_EQ(root_view, result_view); @@ -2413,21 +2412,20 @@ //////////////////////////////////////////////////////////////////////////////// class ToplevelWidgetObserverView : public View { public: - ToplevelWidgetObserverView() : toplevel_(NULL) { - } + ToplevelWidgetObserverView() : toplevel_(nullptr) {} ~ToplevelWidgetObserverView() override {} // View overrides: void ViewHierarchyChanged( const ViewHierarchyChangedDetails& details) override { if (details.is_add) { - toplevel_ = GetWidget() ? GetWidget()->GetTopLevelWidget() : NULL; + toplevel_ = GetWidget() ? GetWidget()->GetTopLevelWidget() : nullptr; } else { - toplevel_ = NULL; + toplevel_ = nullptr; } } void NativeViewHierarchyChanged() override { - toplevel_ = GetWidget() ? GetWidget()->GetTopLevelWidget() : NULL; + toplevel_ = GetWidget() ? GetWidget()->GetTopLevelWidget() : nullptr; } Widget* toplevel() { return toplevel_; } @@ -2460,7 +2458,7 @@ ToplevelWidgetObserverView* observer_view = new ToplevelWidgetObserverView(); - EXPECT_EQ(NULL, observer_view->toplevel()); + EXPECT_EQ(nullptr, observer_view->toplevel()); child->SetContentsView(observer_view); EXPECT_EQ(toplevel1.get(), observer_view->toplevel()); @@ -2470,7 +2468,7 @@ EXPECT_EQ(toplevel2.get(), observer_view->toplevel()); observer_view->parent()->RemoveChildView(observer_view); - EXPECT_EQ(NULL, observer_view->toplevel()); + EXPECT_EQ(nullptr, observer_view->toplevel()); // Make |observer_view| |child|'s contents view again so that it gets deleted // with the widget. @@ -3219,13 +3217,13 @@ EXPECT_FALSE(v2->has_remove_details()); EXPECT_EQ(v2.get(), v2->add_details().parent); EXPECT_EQ(v3, v2->add_details().child); - EXPECT_EQ(NULL, v2->add_details().move_view); + EXPECT_EQ(nullptr, v2->add_details().move_view); EXPECT_TRUE(v3->has_add_details()); EXPECT_FALSE(v3->has_remove_details()); EXPECT_EQ(v2.get(), v3->add_details().parent); EXPECT_EQ(v3, v3->add_details().child); - EXPECT_EQ(NULL, v3->add_details().move_view); + EXPECT_EQ(nullptr, v3->add_details().move_view); // Reset everything to the initial state. v2->ResetTestState(); @@ -3240,19 +3238,19 @@ EXPECT_FALSE(v1.has_remove_details()); EXPECT_EQ(&v1, v1.add_details().parent); EXPECT_EQ(v2.get(), v1.add_details().child); - EXPECT_EQ(NULL, v1.add_details().move_view); + EXPECT_EQ(nullptr, v1.add_details().move_view); EXPECT_TRUE(v2->has_add_details()); EXPECT_FALSE(v2->has_remove_details()); EXPECT_EQ(&v1, v2->add_details().parent); EXPECT_EQ(v2.get(), v2->add_details().child); - EXPECT_EQ(NULL, v2->add_details().move_view); + EXPECT_EQ(nullptr, v2->add_details().move_view); EXPECT_TRUE(v3->has_add_details()); EXPECT_FALSE(v3->has_remove_details()); EXPECT_EQ(&v1, v3->add_details().parent); EXPECT_EQ(v2.get(), v3->add_details().child); - EXPECT_EQ(NULL, v3->add_details().move_view); + EXPECT_EQ(nullptr, v3->add_details().move_view); // Reset everything to the initial state. v1.ResetTestState(); @@ -3268,19 +3266,19 @@ EXPECT_TRUE(v1.has_remove_details()); EXPECT_EQ(&v1, v1.remove_details().parent); EXPECT_EQ(v2.get(), v1.remove_details().child); - EXPECT_EQ(NULL, v1.remove_details().move_view); + EXPECT_EQ(nullptr, v1.remove_details().move_view); EXPECT_FALSE(v2->has_add_details()); EXPECT_TRUE(v2->has_remove_details()); EXPECT_EQ(&v1, v2->remove_details().parent); EXPECT_EQ(v2.get(), v2->remove_details().child); - EXPECT_EQ(NULL, v2->remove_details().move_view); + EXPECT_EQ(nullptr, v2->remove_details().move_view); EXPECT_FALSE(v3->has_add_details()); EXPECT_TRUE(v3->has_remove_details()); EXPECT_EQ(&v1, v3->remove_details().parent); EXPECT_EQ(v3, v3->remove_details().child); - EXPECT_EQ(NULL, v3->remove_details().move_view); + EXPECT_EQ(nullptr, v3->remove_details().move_view); // Verifies notifications when reparenting a view. ObserverView* v4 = new ObserverView(); @@ -3505,7 +3503,7 @@ root.RemoveAllChildViews(true); EXPECT_EQ(0, root.child_count()); - EXPECT_FALSE(root.has_children()); + EXPECT_TRUE(root.children().empty()); } TEST_F(ViewTest, Contains) { @@ -3516,17 +3514,17 @@ v1.AddChildView(v2); v2->AddChildView(v3); - EXPECT_FALSE(v1.Contains(NULL)); + EXPECT_FALSE(v1.Contains(nullptr)); EXPECT_TRUE(v1.Contains(&v1)); EXPECT_TRUE(v1.Contains(v2)); EXPECT_TRUE(v1.Contains(v3)); - EXPECT_FALSE(v2->Contains(NULL)); + EXPECT_FALSE(v2->Contains(nullptr)); EXPECT_TRUE(v2->Contains(v2)); EXPECT_FALSE(v2->Contains(&v1)); EXPECT_TRUE(v2->Contains(v3)); - EXPECT_FALSE(v3->Contains(NULL)); + EXPECT_FALSE(v3->Contains(nullptr)); EXPECT_TRUE(v3->Contains(v3)); EXPECT_FALSE(v3->Contains(&v1)); EXPECT_FALSE(v3->Contains(v2)); @@ -3588,7 +3586,7 @@ ASSERT_EQ(2, child->GetIndexOf(foo3)); ASSERT_EQ(foo2, foo1->GetNextFocusableView()); ASSERT_EQ(foo3, foo2->GetNextFocusableView()); - ASSERT_EQ(NULL, foo3->GetNextFocusableView()); + ASSERT_EQ(nullptr, foo3->GetNextFocusableView()); // Move |foo2| at the end. child->ReorderChildView(foo2, -1); @@ -3597,14 +3595,14 @@ ASSERT_EQ(2, child->GetIndexOf(foo2)); ASSERT_EQ(foo3, foo1->GetNextFocusableView()); ASSERT_EQ(foo2, foo3->GetNextFocusableView()); - ASSERT_EQ(NULL, foo2->GetNextFocusableView()); + ASSERT_EQ(nullptr, foo2->GetNextFocusableView()); // Move |foo1| at the end. child->ReorderChildView(foo1, -1); ASSERT_EQ(0, child->GetIndexOf(foo3)); ASSERT_EQ(1, child->GetIndexOf(foo2)); ASSERT_EQ(2, child->GetIndexOf(foo1)); - ASSERT_EQ(NULL, foo1->GetNextFocusableView()); + ASSERT_EQ(nullptr, foo1->GetNextFocusableView()); ASSERT_EQ(foo2, foo1->GetPreviousFocusableView()); ASSERT_EQ(foo2, foo3->GetNextFocusableView()); ASSERT_EQ(foo1, foo2->GetNextFocusableView()); @@ -3614,7 +3612,7 @@ ASSERT_EQ(0, child->GetIndexOf(foo2)); ASSERT_EQ(1, child->GetIndexOf(foo3)); ASSERT_EQ(2, child->GetIndexOf(foo1)); - ASSERT_EQ(NULL, foo1->GetNextFocusableView()); + ASSERT_EQ(nullptr, foo1->GetNextFocusableView()); ASSERT_EQ(foo3, foo1->GetPreviousFocusableView()); ASSERT_EQ(foo3, foo2->GetNextFocusableView()); ASSERT_EQ(foo1, foo3->GetNextFocusableView()); @@ -3654,8 +3652,9 @@ EXPECT_EQ(&v2, v1.GetViewByID(kV2ID)); EXPECT_EQ(&v4, v1.GetViewByID(kV4ID)); - EXPECT_EQ(NULL, v1.GetViewByID(kV5ID)); // No V5 exists. - EXPECT_EQ(NULL, v2.GetViewByID(kV1ID)); // It can get only from child views. + EXPECT_EQ(nullptr, v1.GetViewByID(kV5ID)); // No V5 exists. + EXPECT_EQ(nullptr, + v2.GetViewByID(kV1ID)); // It can get only from child views. const int kGroup = 1; v3.SetGroup(kGroup); @@ -3798,7 +3797,7 @@ class ViewLayerTest : public ViewsTestBase { public: - ViewLayerTest() : widget_(NULL) {} + ViewLayerTest() : widget_(nullptr) {} ~ViewLayerTest() override {} @@ -3839,6 +3838,68 @@ base::test::ScopedFeatureList scoped_feature_list_; }; +TEST_F(ViewLayerTest, LayerCreationAndDestruction) { + View view; + EXPECT_EQ(nullptr, view.layer()); + + view.SetPaintToLayer(); + EXPECT_NE(nullptr, view.layer()); + + view.DestroyLayer(); + EXPECT_EQ(nullptr, view.layer()); +} + +TEST_F(ViewLayerTest, SetTransformCreatesAndDestroysLayer) { + View view; + EXPECT_EQ(nullptr, view.layer()); + + // Set an arbitrary non-identity transform, which should cause a layer to be + // created. + gfx::Transform transform; + transform.Translate(1.0, 1.0); + view.SetTransform(transform); + EXPECT_NE(nullptr, view.layer()); + + // Set the identity transform, which should destroy the layer. + view.SetTransform(gfx::Transform()); + EXPECT_EQ(nullptr, view.layer()); +} + +// Verify that setting an identity transform after SetPaintToLayer() has been +// called doesn't destroy the layer. +TEST_F(ViewLayerTest, IdentityTransformDoesntOverrideSetPaintToLayer) { + View view; + EXPECT_EQ(nullptr, view.layer()); + + view.SetPaintToLayer(); + EXPECT_NE(nullptr, view.layer()); + + gfx::Transform transform; + transform.Translate(1.0, 1.0); + view.SetTransform(transform); + EXPECT_NE(nullptr, view.layer()); + + view.SetTransform(transform); + EXPECT_NE(nullptr, view.layer()); +} + +// Verify that calling DestroyLayer() while a non-identity transform is present +// doesn't destroy the layer. +TEST_F(ViewLayerTest, DestroyLayerDoesntOverrideTransform) { + View view; + EXPECT_EQ(nullptr, view.layer()); + + view.SetPaintToLayer(); + EXPECT_NE(nullptr, view.layer()); + + gfx::Transform transform; + transform.Translate(1.0, 1.0); + view.SetTransform(transform); + EXPECT_NE(nullptr, view.layer()); + + view.DestroyLayer(); + EXPECT_NE(nullptr, view.layer()); +} TEST_F(ViewLayerTest, LayerToggling) { // Because we lazily create textures the calls to DrawTree are necessary to @@ -3850,28 +3911,28 @@ // Create v1, give it a bounds and verify everything is set up correctly. View* v1 = new View; v1->SetPaintToLayer(); - EXPECT_TRUE(v1->layer() != NULL); + EXPECT_TRUE(v1->layer() != nullptr); v1->SetBoundsRect(gfx::Rect(20, 30, 140, 150)); content_view->AddChildView(v1); - ASSERT_TRUE(v1->layer() != NULL); + ASSERT_TRUE(v1->layer() != nullptr); EXPECT_EQ(root_layer, v1->layer()->parent()); EXPECT_EQ(gfx::Rect(20, 30, 140, 150), v1->layer()->bounds()); // Create v2 as a child of v1 and do basic assertion testing. View* v2 = new View; v1->AddChildView(v2); - EXPECT_TRUE(v2->layer() == NULL); + EXPECT_TRUE(v2->layer() == nullptr); v2->SetBoundsRect(gfx::Rect(10, 20, 30, 40)); v2->SetPaintToLayer(); - ASSERT_TRUE(v2->layer() != NULL); + ASSERT_TRUE(v2->layer() != nullptr); EXPECT_EQ(v1->layer(), v2->layer()->parent()); EXPECT_EQ(gfx::Rect(10, 20, 30, 40), v2->layer()->bounds()); // Turn off v1s layer. v2 should still have a layer but its parent should have // changed. v1->DestroyLayer(); - EXPECT_TRUE(v1->layer() == NULL); - EXPECT_TRUE(v2->layer() != NULL); + EXPECT_TRUE(v1->layer() == nullptr); + EXPECT_TRUE(v2->layer() != nullptr); EXPECT_EQ(root_layer, v2->layer()->parent()); ASSERT_EQ(1u, root_layer->children().size()); EXPECT_EQ(root_layer->children()[0], v2->layer()); @@ -3883,8 +3944,8 @@ gfx::Transform transform; transform.Scale(2.0, 2.0); v1->SetTransform(transform); - EXPECT_TRUE(v1->layer() != NULL); - EXPECT_TRUE(v2->layer() != NULL); + EXPECT_TRUE(v1->layer() != nullptr); + EXPECT_TRUE(v2->layer() != nullptr); EXPECT_EQ(root_layer, v1->layer()->parent()); EXPECT_EQ(v1->layer(), v2->layer()->parent()); ASSERT_EQ(1u, root_layer->children().size()); @@ -3907,7 +3968,7 @@ View* v3 = v2->AddChildView(std::make_unique<View>()); v3->SetPaintToLayer(); - ASSERT_TRUE(v3->layer() != NULL); + ASSERT_TRUE(v3->layer() != nullptr); // At this point we have v1-v2-v3. v3 has a layer, v1 and v2 don't. @@ -3921,7 +3982,7 @@ View* v1 = content_view->AddChildView(std::make_unique<View>()); v1->SetPaintToLayer(); - EXPECT_TRUE(v1->layer() != NULL); + EXPECT_TRUE(v1->layer() != nullptr); TestLayerAnimator* animator = new TestLayerAnimator(); v1->layer()->SetAnimator(animator); @@ -3945,7 +4006,7 @@ View* v2 = v1->AddChildView(std::make_unique<View>()); v2->SetBoundsRect(gfx::Rect(10, 11, 40, 50)); v2->SetPaintToLayer(); - ASSERT_TRUE(v2->layer() != NULL); + ASSERT_TRUE(v2->layer() != nullptr); EXPECT_EQ(gfx::Rect(30, 41, 40, 50), v2->layer()->bounds()); v1->SetPosition(gfx::Point(25, 36)); @@ -4099,7 +4160,7 @@ view->SetTransform(transform); widget()->SetContentsView(view); EXPECT_EQ(2.0f, view->GetTransform().matrix().get(0, 0)); - ASSERT_TRUE(view->layer() != NULL); + ASSERT_TRUE(view->layer() != nullptr); EXPECT_EQ(2.0f, view->layer()->transform().matrix().get(0, 0)); View* parent = view->parent(); @@ -4107,7 +4168,7 @@ parent->AddChildView(view); EXPECT_EQ(2.0f, view->GetTransform().matrix().get(0, 0)); - ASSERT_TRUE(view->layer() != NULL); + ASSERT_TRUE(view->layer() != nullptr); EXPECT_EQ(2.0f, view->layer()->transform().matrix().get(0, 0)); } @@ -4169,7 +4230,7 @@ // Reparent |v2|. content_view->AddChildView(v2); delete v1; - v1 = NULL; + v1 = nullptr; EXPECT_TRUE(LayerIsAncestor(widget()->GetCompositor()->root_layer(), v2->layer())); EXPECT_TRUE(v2->layer()->IsDrawn()); @@ -4429,7 +4490,7 @@ View child; child.SetPaintToLayer(); v.AddChildView(&child); - ASSERT_TRUE(v.layer() != NULL); + ASSERT_TRUE(v.layer() != nullptr); ASSERT_EQ(1u, v.layer()->children().size()); EXPECT_EQ(v.layer()->children()[0], child.layer()); @@ -4440,11 +4501,11 @@ std::unique_ptr<ui::Layer> old_layer(v.RecreateLayer()); // All children should be moved from old layer to new layer. - ASSERT_TRUE(old_layer.get() != NULL); + ASSERT_TRUE(old_layer.get() != nullptr); EXPECT_TRUE(old_layer->children().empty()); // And new layer should have the two children. - ASSERT_TRUE(v.layer() != NULL); + ASSERT_TRUE(v.layer() != nullptr); ASSERT_EQ(2u, v.layer()->children().size()); EXPECT_EQ(v.layer()->children()[0], &layer); EXPECT_EQ(v.layer()->children()[1], child.layer());
diff --git a/ui/views/views_test_suite.h b/ui/views/views_test_suite.h index 73654b32..f186b2c 100644 --- a/ui/views/views_test_suite.h +++ b/ui/views/views_test_suite.h
@@ -48,6 +48,6 @@ DISALLOW_COPY_AND_ASSIGN(ViewsTestSuite); }; -} // namespace +} // namespace views #endif // UI_VIEWS_VIEWS_TEST_SUITE_H_
diff --git a/ui/views/widget/desktop_aura/desktop_drag_drop_client_win.cc b/ui/views/widget/desktop_aura/desktop_drag_drop_client_win.cc index 2800896f..2c829dc 100644 --- a/ui/views/widget/desktop_aura/desktop_drag_drop_client_win.cc +++ b/ui/views/widget/desktop_aura/desktop_drag_drop_client_win.cc
@@ -98,7 +98,7 @@ void DesktopDragDropClientWin::OnNativeWidgetDestroying(HWND window) { if (drop_target_.get()) { RevokeDragDrop(window); - drop_target_ = NULL; + drop_target_ = nullptr; } }
diff --git a/ui/views/widget/desktop_aura/desktop_focus_rules_unittest.cc b/ui/views/widget/desktop_aura/desktop_focus_rules_unittest.cc index 25694f348..8717379 100644 --- a/ui/views/widget/desktop_aura/desktop_focus_rules_unittest.cc +++ b/ui/views/widget/desktop_aura/desktop_focus_rules_unittest.cc
@@ -33,7 +33,7 @@ aura::client::GetFocusClient(w2->GetNativeView())->FocusWindow(w2_child); aura::Window* focused = aura::client::GetFocusClient(w2->GetNativeView())->GetFocusedWindow(); - EXPECT_TRUE((focused == NULL) || w2->GetNativeView()->Contains(focused)); + EXPECT_TRUE((focused == nullptr) || w2->GetNativeView()->Contains(focused)); wm::RemoveTransientChild(w1->GetNativeView(), w2_child); w1->CloseNow();
diff --git a/ui/views/widget/desktop_aura/desktop_native_widget_aura.cc b/ui/views/widget/desktop_aura/desktop_native_widget_aura.cc index c98222f8..217b2b0 100644 --- a/ui/views/widget/desktop_aura/desktop_native_widget_aura.cc +++ b/ui/views/widget/desktop_aura/desktop_native_widget_aura.cc
@@ -133,7 +133,7 @@ // destroy it again. if (top_level_widget_ && window == top_level_widget_->GetNativeView()) { - top_level_widget_ = NULL; + top_level_widget_ = nullptr; return; } @@ -144,7 +144,7 @@ // above is being destroyed we go ahead and initiate the destruction of // the corresponding widget. top_level_widget_->Close(); - top_level_widget_ = NULL; + top_level_widget_ = nullptr; } delete this; } @@ -162,8 +162,7 @@ private: DesktopNativeWidgetTopLevelHandler() - : top_level_widget_(NULL), - child_window_(NULL) {} + : top_level_widget_(nullptr), child_window_(nullptr) {} ~DesktopNativeWidgetTopLevelHandler() override {} @@ -182,7 +181,7 @@ aura::client::SetWindowParentingClient(root_window_, this); } ~DesktopNativeWidgetAuraWindowParentingClient() override { - aura::client::SetWindowParentingClient(root_window_, NULL); + aura::client::SetWindowParentingClient(root_window_, nullptr); } // Overridden from client::WindowParentingClient: @@ -237,12 +236,12 @@ int DesktopNativeWidgetAura::cursor_reference_count_ = 0; DesktopNativeCursorManager* DesktopNativeWidgetAura::native_cursor_manager_ = - NULL; -wm::CursorManager* DesktopNativeWidgetAura::cursor_manager_ = NULL; + nullptr; +wm::CursorManager* DesktopNativeWidgetAura::cursor_manager_ = nullptr; DesktopNativeWidgetAura::DesktopNativeWidgetAura( internal::NativeWidgetDelegate* delegate) - : desktop_window_tree_host_(NULL), + : desktop_window_tree_host_(nullptr), ownership_(Widget::InitParams::NATIVE_WIDGET_OWNS_WIDGET), content_window_(new aura::Window(this)), native_widget_delegate_(delegate), @@ -298,7 +297,7 @@ tooltip_manager_.reset(); if (tooltip_controller_.get()) { host_->window()->RemovePreTargetHandler(tooltip_controller_.get()); - wm::SetTooltipClient(host_->window(), NULL); + wm::SetTooltipClient(host_->window(), nullptr); tooltip_controller_.reset(); } @@ -313,8 +312,8 @@ // |content_window_| after it's been destroyed but before all child windows // have been destroyed. host_->window()->RemovePreTargetHandler(focus_client_.get()); - aura::client::SetFocusClient(host_->window(), NULL); - wm::SetActivationClient(host_->window(), NULL); + aura::client::SetFocusClient(host_->window(), nullptr); + wm::SetActivationClient(host_->window(), nullptr); focus_client_.reset(); host_->window()->RemovePreTargetHandler(root_window_event_filter_.get()); @@ -322,8 +321,8 @@ host_->RemoveObserver(this); host_.reset(); // WindowEventDispatcher owns |desktop_window_tree_host_|. - desktop_window_tree_host_ = NULL; - content_window_ = NULL; + desktop_window_tree_host_ = nullptr; + content_window_ = nullptr; // |OnNativeWidgetDestroyed| may delete |this| if the object does not own // itself. @@ -347,13 +346,13 @@ native_cursor_manager_->RemoveHost(host); } - aura::client::SetScreenPositionClient(host->window(), NULL); + aura::client::SetScreenPositionClient(host->window(), nullptr); position_client_.reset(); - aura::client::SetDragDropClient(host->window(), NULL); + aura::client::SetDragDropClient(host->window(), nullptr); drag_drop_client_.reset(); - aura::client::SetEventClient(host->window(), NULL); + aura::client::SetEventClient(host->window(), nullptr); event_client_.reset(); } @@ -608,11 +607,11 @@ } const ui::Compositor* DesktopNativeWidgetAura::GetCompositor() const { - return content_window_ ? content_window_->layer()->GetCompositor() : NULL; + return content_window_ ? content_window_->layer()->GetCompositor() : nullptr; } const ui::Layer* DesktopNativeWidgetAura::GetLayer() const { - return content_window_ ? content_window_->layer() : NULL; + return content_window_ ? content_window_->layer() : nullptr; } void DesktopNativeWidgetAura::ReorderNativeViews() { @@ -629,7 +628,7 @@ } void DesktopNativeWidgetAura::ViewRemoved(View* view) { - DCHECK(drop_helper_.get() != NULL); + DCHECK(drop_helper_.get() != nullptr); drop_helper_->ResetTargetViewIfEquals(view); } @@ -640,8 +639,8 @@ } void* DesktopNativeWidgetAura::GetNativeWindowProperty(const char* name) const { - return content_window_ ? - content_window_->GetNativeWindowProperty(name) : NULL; + return content_window_ ? content_window_->GetNativeWindowProperty(name) + : nullptr; } TooltipManager* DesktopNativeWidgetAura::GetTooltipManager() const { @@ -1179,25 +1178,25 @@ // DesktopNativeWidgetAura, aura::WindowDragDropDelegate implementation: void DesktopNativeWidgetAura::OnDragEntered(const ui::DropTargetEvent& event) { - DCHECK(drop_helper_.get() != NULL); + DCHECK(drop_helper_.get() != nullptr); last_drop_operation_ = drop_helper_->OnDragOver(event.data(), event.location(), event.source_operations()); } int DesktopNativeWidgetAura::OnDragUpdated(const ui::DropTargetEvent& event) { - DCHECK(drop_helper_.get() != NULL); + DCHECK(drop_helper_.get() != nullptr); last_drop_operation_ = drop_helper_->OnDragOver(event.data(), event.location(), event.source_operations()); return last_drop_operation_; } void DesktopNativeWidgetAura::OnDragExited() { - DCHECK(drop_helper_.get() != NULL); + DCHECK(drop_helper_.get() != nullptr); drop_helper_->OnDragExit(); } int DesktopNativeWidgetAura::OnPerformDrop(const ui::DropTargetEvent& event) { - DCHECK(drop_helper_.get() != NULL); + DCHECK(drop_helper_.get() != nullptr); if (ShouldActivate()) Activate(); return drop_helper_->OnDrop(event.data(), event.location(), @@ -1258,8 +1257,8 @@ // We are the last DesktopNativeWidgetAura instance, and we are responsible // for cleaning up |cursor_manager_|. delete cursor_manager_; - native_cursor_manager_ = NULL; - cursor_manager_ = NULL; + native_cursor_manager_ = nullptr; + cursor_manager_ = nullptr; } }
diff --git a/ui/views/widget/desktop_aura/desktop_native_widget_aura_unittest.cc b/ui/views/widget/desktop_aura/desktop_native_widget_aura_unittest.cc index bc93e06..c1b6b7b 100644 --- a/ui/views/widget/desktop_aura/desktop_native_widget_aura_unittest.cc +++ b/ui/views/widget/desktop_aura/desktop_native_widget_aura_unittest.cc
@@ -48,7 +48,7 @@ // Verifies creating a Widget with a parent that is not in a RootWindow doesn't // crash. TEST_F(DesktopNativeWidgetAuraTest, CreateWithParentNotInRootWindow) { - std::unique_ptr<aura::Window> window(new aura::Window(NULL)); + std::unique_ptr<aura::Window> window(new aura::Window(nullptr)); window->Init(ui::LAYER_NOT_DRAWN); Widget widget; Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_WINDOW); @@ -376,8 +376,8 @@ class DesktopAuraTopLevelWindowTest : public aura::WindowObserver { public: DesktopAuraTopLevelWindowTest() - : top_level_widget_(NULL), - owned_window_(NULL), + : top_level_widget_(nullptr), + owned_window_(nullptr), owner_destroyed_(false), owned_window_destroyed_(false), use_async_mode_(true) {} @@ -385,8 +385,8 @@ ~DesktopAuraTopLevelWindowTest() override { EXPECT_TRUE(owner_destroyed_); EXPECT_TRUE(owned_window_destroyed_); - top_level_widget_ = NULL; - owned_window_ = NULL; + top_level_widget_ = nullptr; + owned_window_ = nullptr; } void CreateTopLevelWindow(const gfx::Rect& bounds, bool fullscreen) { @@ -416,16 +416,16 @@ owned_window_->Show(); owned_window_->AddObserver(this); - ASSERT_TRUE(owned_window_->parent() != NULL); + ASSERT_TRUE(owned_window_->parent() != nullptr); owned_window_->parent()->AddObserver(this); top_level_widget_ = views::Widget::GetWidgetForNativeView(owned_window_->parent()); - ASSERT_TRUE(top_level_widget_ != NULL); + ASSERT_TRUE(top_level_widget_ != nullptr); } void DestroyOwnedWindow() { - ASSERT_TRUE(owned_window_ != NULL); + ASSERT_TRUE(owned_window_ != nullptr); // If async mode is off then clean up state here. if (!use_async_mode_) { owned_window_->RemoveObserver(this); @@ -437,7 +437,7 @@ } void DestroyOwnerWindow() { - ASSERT_TRUE(top_level_widget_ != NULL); + ASSERT_TRUE(top_level_widget_ != nullptr); top_level_widget_->CloseNow(); } @@ -678,7 +678,7 @@ ModalDialogDelegate* dialog_delegate = new ModalDialogDelegate; Widget* modal_dialog_widget = views::DialogDelegate::CreateDialogWidget( - dialog_delegate, NULL, top_level_widget.GetNativeView()); + dialog_delegate, nullptr, top_level_widget.GetNativeView()); modal_dialog_widget->SetBounds(gfx::Rect(100, 100, 200, 200)); EventCountView* dialog_widget_view = new EventCountView(); dialog_widget_view->SetBounds(0, 0, 50, 50); @@ -732,7 +732,7 @@ widget_delegate.SetCanActivate(false); Widget* modal_dialog_widget = views::DialogDelegate::CreateDialogWidget( - dialog_delegate, NULL, top_level_widget->GetNativeView()); + dialog_delegate, nullptr, top_level_widget->GetNativeView()); modal_dialog_widget->SetBounds(gfx::Rect(100, 100, 200, 200)); modal_dialog_widget->Show(); EXPECT_TRUE(modal_dialog_widget->IsVisible());
diff --git a/ui/views/widget/desktop_aura/desktop_screen_win.cc b/ui/views/widget/desktop_aura/desktop_screen_win.cc index f772f64..56fba6bc 100644 --- a/ui/views/widget/desktop_aura/desktop_screen_win.cc +++ b/ui/views/widget/desktop_aura/desktop_screen_win.cc
@@ -33,12 +33,13 @@ HWND DesktopScreenWin::GetHWNDFromNativeView(gfx::NativeView window) const { aura::WindowTreeHost* host = window->GetHost(); - return host ? host->GetAcceleratedWidget() : NULL; + return host ? host->GetAcceleratedWidget() : nullptr; } gfx::NativeWindow DesktopScreenWin::GetNativeWindowFromHWND(HWND hwnd) const { - return (::IsWindow(hwnd)) ? - DesktopWindowTreeHostWin::GetContentWindowForHWND(hwnd) : NULL; + return (::IsWindow(hwnd)) + ? DesktopWindowTreeHostWin::GetContentWindowForHWND(hwnd) + : nullptr; } ////////////////////////////////////////////////////////////////////////////////
diff --git a/ui/views/widget/desktop_aura/desktop_window_tree_host_win.cc b/ui/views/widget/desktop_aura/desktop_window_tree_host_win.cc index 383a234..f39115f9 100644 --- a/ui/views/widget/desktop_aura/desktop_window_tree_host_win.cc +++ b/ui/views/widget/desktop_aura/desktop_window_tree_host_win.cc
@@ -86,12 +86,11 @@ : message_handler_(new HWNDMessageHandler(this)), native_widget_delegate_(native_widget_delegate), desktop_native_widget_aura_(desktop_native_widget_aura), - drag_drop_client_(NULL), + drag_drop_client_(nullptr), should_animate_window_close_(false), pending_close_(false), has_non_client_view_(false), - tooltip_(NULL) { -} + tooltip_(nullptr) {} DesktopWindowTreeHostWin::~DesktopWindowTreeHostWin() { desktop_native_widget_aura_->OnDesktopWindowTreeHostDestroyed(this); @@ -123,7 +122,7 @@ GetWidget()->widget_delegate(), native_widget_delegate_); - HWND parent_hwnd = NULL; + HWND parent_hwnd = nullptr; if (params.parent && params.parent->GetHost()) parent_hwnd = params.parent->GetHost()->GetAcceleratedWidget(); @@ -932,8 +931,8 @@ POINT target_location(event->location().ToPOINT()); ClientToScreen(GetHWND(), &target_location); ScreenToClient(target->GetHWND(), &target_location); - ui::TouchEvent target_event(*event, static_cast<View*>(NULL), - static_cast<View*>(NULL)); + ui::TouchEvent target_event(*event, static_cast<View*>(nullptr), + static_cast<View*>(nullptr)); target_event.set_location(gfx::Point(target_location)); target_event.set_root_location(target_event.location()); target->SendEventToSink(&target_event);
diff --git a/ui/views/widget/desktop_widget_unittest.cc b/ui/views/widget/desktop_widget_unittest.cc index 6e17ae3..1ab32fe 100644 --- a/ui/views/widget/desktop_widget_unittest.cc +++ b/ui/views/widget/desktop_widget_unittest.cc
@@ -26,7 +26,7 @@ DialogDelegateView* dialog_delegate_view = new DialogDelegateView; // Owned by |parent_widget|. Widget* dialog = DialogDelegate::CreateDialogWidget( - dialog_delegate_view, NULL, parent_widget.GetNativeView()); + dialog_delegate_view, nullptr, parent_widget.GetNativeView()); dialog->SetBounds(gfx::Rect(11, 12, 200, 200)); EXPECT_EQ(gfx::Point(11, 12), dialog->GetWindowBoundsInScreen().origin()); }
diff --git a/ui/views/widget/drop_helper.cc b/ui/views/widget/drop_helper.cc index 65e97346..3cc8b29 100644 --- a/ui/views/widget/drop_helper.cc +++ b/ui/views/widget/drop_helper.cc
@@ -25,10 +25,7 @@ } // namespace DropHelper::DropHelper(View* root_view) - : root_view_(root_view), - target_view_(NULL), - deepest_view_(NULL) { -} + : root_view_(root_view), target_view_(nullptr), deepest_view_(nullptr) {} DropHelper::~DropHelper() { } @@ -43,9 +40,9 @@ void DropHelper::ResetTargetViewIfEquals(View* view) { if (target_view_ == view) - target_view_ = NULL; + target_view_ = nullptr; if (deepest_view_ == view) - deepest_view_ = NULL; + deepest_view_ = nullptr; } int DropHelper::OnDragOver(const OSExchangeData& data, @@ -76,14 +73,14 @@ void DropHelper::OnDragExit() { NotifyDragExit(); - deepest_view_ = target_view_ = NULL; + deepest_view_ = target_view_ = nullptr; } int DropHelper::OnDrop(const OSExchangeData& data, const gfx::Point& root_view_location, int drag_operation) { View* drop_view = target_view_; - deepest_view_ = target_view_ = NULL; + deepest_view_ = target_view_ = nullptr; if (!drop_view) return ui::DragDropTypes::DRAG_NONE; @@ -105,7 +102,7 @@ const OSExchangeData& data, bool check_can_drop) { return CalculateTargetViewImpl(root_view_location, data, check_can_drop, - NULL); + nullptr); } View* DropHelper::CalculateTargetViewImpl(
diff --git a/ui/views/widget/native_widget_aura.cc b/ui/views/widget/native_widget_aura.cc index c387601..bec92dca 100644 --- a/ui/views/widget/native_widget_aura.cc +++ b/ui/views/widget/native_widget_aura.cc
@@ -265,7 +265,7 @@ void NativeWidgetAura::OnWidgetInitDone() {} NonClientFrameView* NativeWidgetAura::CreateNonClientFrameView() { - return NULL; + return nullptr; } bool NativeWidgetAura::ShouldUseNativeFrame() const { @@ -302,15 +302,15 @@ Widget* NativeWidgetAura::GetTopLevelWidget() { NativeWidgetPrivate* native_widget = GetTopLevelNativeWidget(GetNativeView()); - return native_widget ? native_widget->GetWidget() : NULL; + return native_widget ? native_widget->GetWidget() : nullptr; } const ui::Compositor* NativeWidgetAura::GetCompositor() const { - return window_ ? window_->layer()->GetCompositor() : NULL; + return window_ ? window_->layer()->GetCompositor() : nullptr; } const ui::Layer* NativeWidgetAura::GetLayer() const { - return window_ ? window_->layer() : NULL; + return window_ ? window_->layer() : nullptr; } void NativeWidgetAura::ReorderNativeViews() { @@ -318,7 +318,7 @@ } void NativeWidgetAura::ViewRemoved(View* view) { - DCHECK(drop_helper_.get() != NULL); + DCHECK(drop_helper_.get() != nullptr); drop_helper_->ResetTargetViewIfEquals(view); } @@ -328,7 +328,7 @@ } void* NativeWidgetAura::GetNativeWindowProperty(const char* name) const { - return window_ ? window_->GetNativeWindowProperty(name) : NULL; + return window_ ? window_->GetNativeWindowProperty(name) : nullptr; } TooltipManager* NativeWidgetAura::GetTooltipManager() const { @@ -893,7 +893,7 @@ } void NativeWidgetAura::OnWindowDestroyed(aura::Window* window) { - window_ = NULL; + window_ = nullptr; // |OnNativeWidgetDestroyed| may delete |this| if the object does not own // itself. bool should_delete_this = @@ -1010,25 +1010,25 @@ // NativeWidgetAura, aura::WindowDragDropDelegate implementation: void NativeWidgetAura::OnDragEntered(const ui::DropTargetEvent& event) { - DCHECK(drop_helper_.get() != NULL); + DCHECK(drop_helper_.get() != nullptr); last_drop_operation_ = drop_helper_->OnDragOver(event.data(), event.location(), event.source_operations()); } int NativeWidgetAura::OnDragUpdated(const ui::DropTargetEvent& event) { - DCHECK(drop_helper_.get() != NULL); + DCHECK(drop_helper_.get() != nullptr); last_drop_operation_ = drop_helper_->OnDragOver(event.data(), event.location(), event.source_operations()); return last_drop_operation_; } void NativeWidgetAura::OnDragExited() { - DCHECK(drop_helper_.get() != NULL); + DCHECK(drop_helper_.get() != nullptr); drop_helper_->OnDragExit(); } int NativeWidgetAura::OnPerformDrop(const ui::DropTargetEvent& event) { - DCHECK(drop_helper_.get() != NULL); + DCHECK(drop_helper_.get() != nullptr); return drop_helper_->OnDrop(event.data(), event.location(), last_drop_operation_); } @@ -1140,7 +1140,7 @@ NativeWidgetPrivate* NativeWidgetPrivate::GetTopLevelNativeWidget( gfx::NativeView native_view) { aura::Window* window = native_view; - NativeWidgetPrivate* top_level_native_widget = NULL; + NativeWidgetPrivate* top_level_native_widget = nullptr; while (window) { NativeWidgetPrivate* native_widget = GetNativeWidgetForNativeView(window); if (native_widget)
diff --git a/ui/views/widget/root_view.cc b/ui/views/widget/root_view.cc index 674fa02..109328ed 100644 --- a/ui/views/widget/root_view.cc +++ b/ui/views/widget/root_view.cc
@@ -41,8 +41,8 @@ public: MouseEnterExitEvent(const ui::MouseEvent& event, ui::EventType type) : ui::MouseEvent(event, - static_cast<View*>(NULL), - static_cast<View*>(NULL)) { + static_cast<View*>(nullptr), + static_cast<View*>(nullptr)) { DCHECK(type == ui::ET_MOUSE_ENTERED || type == ui::ET_MOUSE_EXITED); SetType(type); @@ -71,7 +71,7 @@ if (event->handled()) return; - View* v = NULL; + View* v = nullptr; if (owner_->GetFocusManager()) // Can be NULL in unittests. v = owner_->GetFocusManager()->GetFocusedView(); // macOS doesn't have keyboard-triggered context menus. @@ -155,22 +155,22 @@ RootView::RootView(Widget* widget) : widget_(widget), - mouse_pressed_handler_(NULL), - mouse_move_handler_(NULL), - last_click_handler_(NULL), + mouse_pressed_handler_(nullptr), + mouse_move_handler_(nullptr), + last_click_handler_(nullptr), explicit_mouse_handler_(false), last_mouse_event_flags_(0), last_mouse_event_x_(-1), last_mouse_event_y_(-1), - gesture_handler_(NULL), + gesture_handler_(nullptr), gesture_handler_set_before_processing_(false), pre_dispatch_handler_(new internal::PreEventDispatchHandler(this)), post_dispatch_handler_(new internal::PostEventDispatchHandler), focus_search_(this, false, false), - focus_traversable_parent_(NULL), - focus_traversable_parent_view_(NULL), - event_dispatch_target_(NULL), - old_dispatch_target_(NULL) { + focus_traversable_parent_(nullptr), + focus_traversable_parent_view_(nullptr), + event_dispatch_target_(nullptr), + old_dispatch_target_(nullptr) { AddPostTargetHandler(post_dispatch_handler_.get()); SetEventTargeter( std::unique_ptr<ViewTargeter>(new RootViewTargeter(this, this))); @@ -179,7 +179,7 @@ RootView::~RootView() { // If we have children remove them explicitly so to make sure a remove // notification is sent for each one of them. - if (has_children()) + if (!children().empty()) RemoveAllChildViews(true); } @@ -191,13 +191,13 @@ // The ContentsView must be set up _after_ the window is created so that its // Widget pointer is valid. SetLayoutManager(std::make_unique<FillLayout>()); - if (has_children()) + if (!children().empty()) RemoveAllChildViews(true); AddChildView(contents_view); } View* RootView::GetContentsView() { - return child_count() > 0 ? child_at(0) : NULL; + return child_count() > 0 ? child_at(0) : nullptr; } void RootView::NotifyNativeViewHierarchyChanged() { @@ -309,7 +309,7 @@ if (event->IsGestureEvent() && !event->handled() && !gesture_handler_set_before_processing_) { - gesture_handler_ = NULL; + gesture_handler_ = nullptr; } } @@ -412,7 +412,7 @@ } // Reset mouse_pressed_handler_ to indicate that no processing is occurring. - mouse_pressed_handler_ = NULL; + mouse_pressed_handler_ = nullptr; // In the event that a double-click is not handled after traversing the // entire hierarchy (even as a single-click when sent to a different view), @@ -421,7 +421,7 @@ if (last_click_handler_ && (event.flags() & ui::EF_IS_DOUBLE_CLICK)) hit_disabled_view = true; - last_click_handler_ = NULL; + last_click_handler_ = nullptr; return hit_disabled_view; } @@ -448,7 +448,7 @@ // We allow the view to delete us from the event dispatch callback. As such, // configure state such that we're done first, then call View. View* mouse_pressed_handler = mouse_pressed_handler_; - SetMouseHandler(NULL); + SetMouseHandler(nullptr); ui::EventDispatchDetails dispatch_details = DispatchEvent(mouse_pressed_handler, &mouse_released); if (dispatch_details.dispatcher_destroyed) @@ -472,7 +472,7 @@ // configure state such that we're done first, then call View. View* mouse_pressed_handler = mouse_pressed_handler_; View* gesture_handler = gesture_handler_; - SetMouseHandler(NULL); + SetMouseHandler(nullptr); if (mouse_pressed_handler) mouse_pressed_handler->OnMouseCaptureLost(); else @@ -491,7 +491,7 @@ v = v->parent(); if (v && v != this) { if (v != mouse_move_handler_) { - if (mouse_move_handler_ != NULL && + if (mouse_move_handler_ != nullptr && (!mouse_move_handler_->notify_enter_exit_on_child() || !mouse_move_handler_->Contains(v))) { MouseEnterExitEvent exit(event, ui::ET_MOUSE_EXITED); @@ -541,7 +541,7 @@ // mousemove. See crbug.com/351469. if (!(moved_event.flags() & ui::EF_IS_NON_CLIENT)) widget_->SetCursor(mouse_move_handler_->GetCursor(moved_event)); - } else if (mouse_move_handler_ != NULL) { + } else if (mouse_move_handler_ != nullptr) { MouseEnterExitEvent exited(event, ui::ET_MOUSE_EXITED); ui::EventDispatchDetails dispatch_details = DispatchEvent(mouse_move_handler_, &exited); @@ -561,12 +561,12 @@ // as we do above. if (!(event.flags() & ui::EF_IS_NON_CLIENT)) widget_->SetCursor(gfx::kNullCursor); - mouse_move_handler_ = NULL; + mouse_move_handler_ = nullptr; } } void RootView::OnMouseExited(const ui::MouseEvent& event) { - if (mouse_move_handler_ != NULL) { + if (mouse_move_handler_ != nullptr) { MouseEnterExitEvent exited(event, ui::ET_MOUSE_EXITED); ui::EventDispatchDetails dispatch_details = DispatchEvent(mouse_move_handler_, &exited); @@ -576,12 +576,12 @@ // mouse exit event. if (!dispatch_details.target_destroyed) { CHECK(mouse_move_handler_); - dispatch_details = NotifyEnterExitOfDescendant(event, ui::ET_MOUSE_EXITED, - mouse_move_handler_, NULL); + dispatch_details = NotifyEnterExitOfDescendant( + event, ui::ET_MOUSE_EXITED, mouse_move_handler_, nullptr); if (dispatch_details.dispatcher_destroyed) return; } - mouse_move_handler_ = NULL; + mouse_move_handler_ = nullptr; } } @@ -600,7 +600,7 @@ void RootView::SetMouseHandler(View* new_mh) { // If we're clearing the mouse handler, clear explicit_mouse_handler_ as well. - explicit_mouse_handler_ = (new_mh != NULL); + explicit_mouse_handler_ = (new_mh != nullptr); mouse_pressed_handler_ = new_mh; gesture_handler_ = new_mh; drag_info_.Reset(); @@ -625,15 +625,15 @@ if (!details.is_add) { if (!explicit_mouse_handler_ && mouse_pressed_handler_ == details.child) - mouse_pressed_handler_ = NULL; + mouse_pressed_handler_ = nullptr; if (mouse_move_handler_ == details.child) - mouse_move_handler_ = NULL; + mouse_move_handler_ = nullptr; if (gesture_handler_ == details.child) - gesture_handler_ = NULL; + gesture_handler_ = nullptr; if (event_dispatch_target_ == details.child) - event_dispatch_target_ = NULL; + event_dispatch_target_ = nullptr; if (old_dispatch_target_ == details.child) - old_dispatch_target_ = NULL; + old_dispatch_target_ = nullptr; } } @@ -745,9 +745,9 @@ // In case a drag was in progress, reset all the handlers. Otherwise, just // reset the gesture handler. if (gesture_handler_ && gesture_handler_ == mouse_pressed_handler_) - SetMouseHandler(NULL); + SetMouseHandler(nullptr); else - gesture_handler_ = NULL; + gesture_handler_ = nullptr; } DispatchDetails details; @@ -755,7 +755,7 @@ details.target_destroyed = true; event_dispatch_target_ = old_dispatch_target_; - old_dispatch_target_ = NULL; + old_dispatch_target_ = nullptr; #ifndef NDEBUG DCHECK(!event_dispatch_target_ || Contains(event_dispatch_target_));
diff --git a/ui/views/widget/root_view_targeter.cc b/ui/views/widget/root_view_targeter.cc index 4f11b53..386d940 100644 --- a/ui/views/widget/root_view_targeter.cc +++ b/ui/views/widget/root_view_targeter.cc
@@ -51,14 +51,14 @@ // gesture handler set by a previous gesture, if one exists. Thus we do not // permit any re-targeting of ET_GESTURE_END events. if (gesture.type() == ui::ET_GESTURE_END) - return NULL; + return nullptr; // Prohibit re-targeting of gesture events (except for GESTURE_SCROLL_BEGIN // events) if the default gesture handler was set by the dispatch of a // previous gesture event. if (root_view_->gesture_handler_set_before_processing_ && gesture.type() != ui::ET_GESTURE_SCROLL_BEGIN) { - return NULL; + return nullptr; } // If |gesture_handler_| is NULL, it is either because the view was removed @@ -67,7 +67,7 @@ // point. In either case, no further re-targeting of |gesture| should be // permitted. if (!root_view_->gesture_handler_) - return NULL; + return nullptr; return previous_target->GetParentTarget(); }
diff --git a/ui/views/widget/root_view_unittest.cc b/ui/views/widget/root_view_unittest.cc index 2609a8c..ca1aa1d 100644 --- a/ui/views/widget/root_view_unittest.cc +++ b/ui/views/widget/root_view_unittest.cc
@@ -78,9 +78,8 @@ public: TestContextMenuController() : show_context_menu_calls_(0), - menu_source_view_(NULL), - menu_source_type_(ui::MENU_SOURCE_NONE) { - } + menu_source_view_(nullptr), + menu_source_type_(ui::MENU_SOURCE_NONE) {} ~TestContextMenuController() override {} int show_context_menu_calls() const { return show_context_menu_calls_; } @@ -89,7 +88,7 @@ void Reset() { show_context_menu_calls_ = 0; - menu_source_view_ = NULL; + menu_source_view_ = nullptr; menu_source_type_ = ui::MENU_SOURCE_NONE; } @@ -141,7 +140,7 @@ EXPECT_FALSE(details.target_destroyed); EXPECT_FALSE(details.dispatcher_destroyed); EXPECT_EQ(0, controller.show_context_menu_calls()); - EXPECT_EQ(NULL, controller.menu_source_view()); + EXPECT_EQ(nullptr, controller.menu_source_view()); EXPECT_EQ(ui::MENU_SOURCE_NONE, controller.menu_source_type()); controller.Reset(); @@ -399,7 +398,7 @@ root_view->OnMouseExited(exit_event); EXPECT_TRUE(view_destroyed); - EXPECT_FALSE(content->has_children()); + EXPECT_TRUE(content->children().empty()); } // Verifies deleting a View in OnMouseEntered() doesn't crash. @@ -440,7 +439,7 @@ root_view->OnMouseMoved(moved_event2); EXPECT_TRUE(view_destroyed); - EXPECT_FALSE(content->has_children()); + EXPECT_TRUE(content->children().empty()); } namespace {
diff --git a/ui/views/widget/tooltip_manager_aura.cc b/ui/views/widget/tooltip_manager_aura.cc index 161a8db5..3c4a4c11 100644 --- a/ui/views/widget/tooltip_manager_aura.cc +++ b/ui/views/widget/tooltip_manager_aura.cc
@@ -24,7 +24,7 @@ } TooltipManagerAura::~TooltipManagerAura() { - wm::SetTooltipText(GetWindow(), NULL); + wm::SetTooltipText(GetWindow(), nullptr); } // static @@ -90,7 +90,7 @@ aura::Window* root_window = GetWindow()->GetRootWindow(); if (wm::GetTooltipClient(root_window)) { if (!widget_->IsVisible()) { - UpdateTooltipForTarget(NULL, gfx::Point(), root_window); + UpdateTooltipForTarget(nullptr, gfx::Point(), root_window); return; } gfx::Point view_point = @@ -118,7 +118,7 @@ View* root_view = widget_->GetRootView(); if (root_view) return root_view->GetTooltipHandlerForPoint(point); - return NULL; + return nullptr; } void TooltipManagerAura::UpdateTooltipForTarget(View* target,
diff --git a/ui/views/widget/widget.cc b/ui/views/widget/widget.cc index c6c2673..8a26761 100644 --- a/ui/views/widget/widget.cc +++ b/ui/views/widget/widget.cc
@@ -236,7 +236,7 @@ Widget* Widget::GetWidgetForNativeView(gfx::NativeView native_view) { internal::NativeWidgetPrivate* native_widget = internal::NativeWidgetPrivate::GetNativeWidgetForNativeView(native_view); - return native_widget ? native_widget->GetWidget() : NULL; + return native_widget ? native_widget->GetWidget() : nullptr; } // static @@ -244,14 +244,14 @@ internal::NativeWidgetPrivate* native_widget = internal::NativeWidgetPrivate::GetNativeWidgetForNativeWindow( native_window); - return native_widget ? native_widget->GetWidget() : NULL; + return native_widget ? native_widget->GetWidget() : nullptr; } // static Widget* Widget::GetTopLevelWidgetForNativeView(gfx::NativeView native_view) { internal::NativeWidgetPrivate* native_widget = internal::NativeWidgetPrivate::GetTopLevelNativeWidget(native_view); - return native_widget ? native_widget->GetWidget() : NULL; + return native_widget ? native_widget->GetWidget() : nullptr; } // static @@ -432,7 +432,7 @@ const View::ViewHierarchyChangedDetails& details) { if (!details.is_add) { if (details.child == dragged_view_) - dragged_view_ = NULL; + dragged_view_ = nullptr; FocusManager* focus_manager = GetFocusManager(); if (focus_manager) focus_manager->ViewRemoved(details.child); @@ -493,7 +493,7 @@ // |non_client_view_|. If you get this error, either use a different type // when initializing the widget, or don't call SetContentsView(). DCHECK(!non_client_view_); - non_client_view_ = NULL; + non_client_view_ = nullptr; } } @@ -779,12 +779,12 @@ FocusManager* Widget::GetFocusManager() { Widget* toplevel_widget = GetTopLevelWidget(); - return toplevel_widget ? toplevel_widget->focus_manager_.get() : NULL; + return toplevel_widget ? toplevel_widget->focus_manager_.get() : nullptr; } const FocusManager* Widget::GetFocusManager() const { const Widget* toplevel_widget = GetTopLevelWidget(); - return toplevel_widget ? toplevel_widget->focus_manager_.get() : NULL; + return toplevel_widget ? toplevel_widget->focus_manager_.get() : nullptr; } ui::InputMethod* Widget::GetInputMethod() { @@ -824,7 +824,7 @@ // If the view is removed during the drag operation, dragged_view_ is set to // NULL. if (view && dragged_view_ == view) { - dragged_view_ = NULL; + dragged_view_ = nullptr; view->OnDragDone(); } OnDragComplete(); @@ -1452,14 +1452,14 @@ // We are a proxy to the root view, so we should be bypassed when traversing // up and as a result this should not be called. NOTREACHED(); - return NULL; + return nullptr; } View* Widget::GetFocusTraversableParentView() { // We are a proxy to the root view, so we should be bypassed when traversing // up and as a result this should not be called. NOTREACHED(); - return NULL; + return nullptr; } //////////////////////////////////////////////////////////////////////////////// @@ -1488,7 +1488,7 @@ if (is_top_level() && focus_manager_) focus_manager_->SetFocusedView(nullptr); NotifyWillRemoveView(root_view_.get()); - non_client_view_ = NULL; + non_client_view_ = nullptr; root_view_.reset(); }
diff --git a/ui/views/widget/widget.h b/ui/views/widget/widget.h index d04ca53..9660aa54 100644 --- a/ui/views/widget/widget.h +++ b/ui/views/widget/widget.h
@@ -709,7 +709,7 @@ } const ClientView* client_view() const { // non_client_view_ may be NULL, especially during creation. - return non_client_view_ ? non_client_view_->client_view() : NULL; + return non_client_view_ ? non_client_view_->client_view() : nullptr; } ui::Compositor* GetCompositor() {
diff --git a/ui/views/widget/widget_delegate.cc b/ui/views/widget/widget_delegate.cc index c27fb35..4a5a4b0 100644 --- a/ui/views/widget/widget_delegate.cc +++ b/ui/views/widget/widget_delegate.cc
@@ -171,11 +171,11 @@ } NonClientFrameView* WidgetDelegate::CreateNonClientFrameView(Widget* widget) { - return NULL; + return nullptr; } View* WidgetDelegate::CreateOverlayView() { - return NULL; + return nullptr; } bool WidgetDelegate::WillProcessWorkAreaChange() const {
diff --git a/ui/views/widget/widget_deletion_observer.cc b/ui/views/widget/widget_deletion_observer.cc index db3a44e7..15df9c3 100644 --- a/ui/views/widget/widget_deletion_observer.cc +++ b/ui/views/widget/widget_deletion_observer.cc
@@ -25,7 +25,7 @@ void WidgetDeletionObserver::CleanupWidget() { if (widget_) { widget_->RemoveObserver(this); - widget_ = NULL; + widget_ = nullptr; } }
diff --git a/ui/views/widget/widget_deletion_observer.h b/ui/views/widget/widget_deletion_observer.h index 8d8cdaa..035250da 100644 --- a/ui/views/widget/widget_deletion_observer.h +++ b/ui/views/widget/widget_deletion_observer.h
@@ -20,7 +20,7 @@ ~WidgetDeletionObserver() override; // Returns true if the widget passed in the constructor is still alive. - bool IsWidgetAlive() { return widget_ != NULL; } + bool IsWidgetAlive() { return widget_ != nullptr; } // Overridden from WidgetObserver. void OnWidgetDestroying(Widget* widget) override;
diff --git a/ui/views/widget/widget_interactive_uitest.cc b/ui/views/widget/widget_interactive_uitest.cc index 4c5b247..c674d13 100644 --- a/ui/views/widget/widget_interactive_uitest.cc +++ b/ui/views/widget/widget_interactive_uitest.cc
@@ -347,10 +347,10 @@ aura::Window* root_window1 = GetRootWindow(widget1); focusable_view1->RequestFocus(); - EXPECT_TRUE(root_window1 != NULL); + EXPECT_TRUE(root_window1 != nullptr); wm::ActivationClient* activation_client1 = wm::GetActivationClient(root_window1); - EXPECT_TRUE(activation_client1 != NULL); + EXPECT_TRUE(activation_client1 != nullptr); EXPECT_EQ(activation_client1->GetActiveWindow(), widget1->GetNativeView()); // Create widget 2 and expect the active window to be its window. @@ -364,7 +364,7 @@ wm::ActivationClient* activation_client2 = wm::GetActivationClient(root_window2); - EXPECT_TRUE(activation_client2 != NULL); + EXPECT_TRUE(activation_client2 != nullptr); EXPECT_EQ(activation_client2->GetActiveWindow(), widget2->GetNativeView()); EXPECT_EQ(activation_client1->GetActiveWindow(), reinterpret_cast<aura::Window*>(NULL)); @@ -455,7 +455,7 @@ toplevel->SetContentsView(container); EXPECT_FALSE(toplevel->HasCapture()); - toplevel->SetCapture(NULL); + toplevel->SetCapture(nullptr); EXPECT_TRUE(toplevel->HasCapture()); // By default, mouse release removes capture. @@ -468,7 +468,7 @@ // Now a mouse release shouldn't remove capture. toplevel->set_auto_release_capture(false); - toplevel->SetCapture(NULL); + toplevel->SetCapture(nullptr); EXPECT_TRUE(toplevel->HasCapture()); toplevel->OnMouseEvent(&release); EXPECT_TRUE(toplevel->HasCapture()); @@ -705,7 +705,7 @@ ShowSync(widget2); EXPECT_TRUE(widget2->IsActive()); EXPECT_FALSE(widget1->IsActive()); - EXPECT_EQ(NULL, widget1->GetFocusManager()->GetFocusedView()); + EXPECT_EQ(nullptr, widget1->GetFocusManager()->GetFocusedView()); view2a->RequestFocus(); EXPECT_EQ(view2a, widget2->GetFocusManager()->GetFocusedView()); view2b->RequestFocus(); @@ -715,13 +715,13 @@ EXPECT_TRUE(widget1->IsActive()); EXPECT_EQ(view1, widget1->GetFocusManager()->GetFocusedView()); EXPECT_FALSE(widget2->IsActive()); - EXPECT_EQ(NULL, widget2->GetFocusManager()->GetFocusedView()); + EXPECT_EQ(nullptr, widget2->GetFocusManager()->GetFocusedView()); ActivateSync(widget2); EXPECT_TRUE(widget2->IsActive()); EXPECT_EQ(view2b, widget2->GetFocusManager()->GetFocusedView()); EXPECT_FALSE(widget1->IsActive()); - EXPECT_EQ(NULL, widget1->GetFocusManager()->GetFocusedView()); + EXPECT_EQ(nullptr, widget1->GetFocusManager()->GetFocusedView()); widget1->CloseNow(); widget2->CloseNow(); @@ -1062,7 +1062,7 @@ ModalDialogDelegate* dialog_delegate = new ModalDialogDelegate(modal_type); Widget* modal_dialog_widget = views::DialogDelegate::CreateDialogWidget( - dialog_delegate, NULL, top_level_widget.GetNativeView()); + dialog_delegate, nullptr, top_level_widget.GetNativeView()); modal_dialog_widget->SetBounds(gfx::Rect(100, 100, 200, 200)); // Note the dialog widget doesn't need a ShowSync. Since it is modal, it gains @@ -1128,7 +1128,7 @@ focus_listener.focus_changes().back()); EXPECT_FALSE(top_level_widget.HasCapture()); - top_level_widget.SetCapture(NULL); + top_level_widget.SetCapture(nullptr); EXPECT_TRUE(top_level_widget.HasCapture()); // Create a modal dialog. @@ -1136,7 +1136,7 @@ new ModalDialogDelegate(ui::MODAL_TYPE_SYSTEM); Widget* modal_dialog_widget = views::DialogDelegate::CreateDialogWidget( - dialog_delegate, NULL, top_level_widget.GetNativeView()); + dialog_delegate, nullptr, top_level_widget.GetNativeView()); modal_dialog_widget->SetBounds(gfx::Rect(100, 100, 200, 200)); ShowSync(modal_dialog_widget); @@ -1768,7 +1768,7 @@ EXPECT_EQ(1, mouse_view1->EnteredCalls()); EXPECT_EQ(0, mouse_view1->ExitedCalls()); - widget2.SetCapture(NULL); + widget2.SetCapture(nullptr); EXPECT_EQ(0, mouse_view1->EnteredCalls()); // Grabbing native capture on Windows generates a ui::ET_MOUSE_EXITED event // in addition to the one generated by Chrome.
diff --git a/ui/views/widget/widget_unittest.cc b/ui/views/widget/widget_unittest.cc index 3c7604a..4d9000f2 100644 --- a/ui/views/widget/widget_unittest.cc +++ b/ui/views/widget/widget_unittest.cc
@@ -2144,9 +2144,7 @@ ~GetNativeThemeFromDestructorView() override { VerifyNativeTheme(); } private: - void VerifyNativeTheme() { - ASSERT_TRUE(GetNativeTheme() != NULL); - } + void VerifyNativeTheme() { ASSERT_TRUE(GetNativeTheme() != nullptr); } DISALLOW_COPY_AND_ASSIGN(GetNativeThemeFromDestructorView); }; @@ -2194,7 +2192,7 @@ std::move(quit_closure_).Run(); } - void Detach() { destroyed_ = NULL; } + void Detach() { destroyed_ = nullptr; } private: bool* destroyed_; @@ -2415,7 +2413,7 @@ // Check RootView::mouse_pressed_handler_. widget->Show(); - EXPECT_EQ(NULL, GetMousePressedHandler(root_view)); + EXPECT_EQ(nullptr, GetMousePressedHandler(root_view)); gfx::Point click_location(45, 15); ui::MouseEvent press(ui::ET_MOUSE_PRESSED, click_location, click_location, ui::EventTimeForNow(), ui::EF_LEFT_MOUSE_BUTTON, @@ -2423,28 +2421,28 @@ widget->OnMouseEvent(&press); EXPECT_EQ(view, GetMousePressedHandler(root_view)); widget->Hide(); - EXPECT_EQ(NULL, GetMousePressedHandler(root_view)); + EXPECT_EQ(nullptr, GetMousePressedHandler(root_view)); // Check RootView::mouse_move_handler_. widget->Show(); - EXPECT_EQ(NULL, GetMouseMoveHandler(root_view)); + EXPECT_EQ(nullptr, GetMouseMoveHandler(root_view)); gfx::Point move_location(45, 15); ui::MouseEvent move(ui::ET_MOUSE_MOVED, move_location, move_location, ui::EventTimeForNow(), 0, 0); widget->OnMouseEvent(&move); EXPECT_EQ(view, GetMouseMoveHandler(root_view)); widget->Hide(); - EXPECT_EQ(NULL, GetMouseMoveHandler(root_view)); + EXPECT_EQ(nullptr, GetMouseMoveHandler(root_view)); // Check RootView::gesture_handler_. widget->Show(); - EXPECT_EQ(NULL, GetGestureHandler(root_view)); + EXPECT_EQ(nullptr, GetGestureHandler(root_view)); ui::GestureEvent tap_down(15, 15, 0, base::TimeTicks(), ui::GestureEventDetails(ui::ET_GESTURE_TAP_DOWN)); widget->OnGestureEvent(&tap_down); EXPECT_EQ(view, GetGestureHandler(root_view)); widget->Hide(); - EXPECT_EQ(NULL, GetGestureHandler(root_view)); + EXPECT_EQ(nullptr, GetGestureHandler(root_view)); widget->Close(); } @@ -2480,10 +2478,10 @@ // If no gesture handler is set, a ui::ET_GESTURE_END event should not set // the gesture handler. - EXPECT_EQ(NULL, GetGestureHandler(root_view)); + EXPECT_EQ(nullptr, GetGestureHandler(root_view)); GestureEventForTest end(ui::ET_GESTURE_END, 15, 15); widget->OnGestureEvent(&end); - EXPECT_EQ(NULL, GetGestureHandler(root_view)); + EXPECT_EQ(nullptr, GetGestureHandler(root_view)); // Change the handle mode of |view| to indicate that it would like // to handle all events, then send a GESTURE_TAP to set the gesture handler. @@ -2505,7 +2503,7 @@ end = GestureEventForTest(ui::ET_GESTURE_END, 15, 15); widget->OnGestureEvent(&end); EXPECT_TRUE(end.handled()); - EXPECT_EQ(NULL, GetGestureHandler(root_view)); + EXPECT_EQ(nullptr, GetGestureHandler(root_view)); // Send a GESTURE_TAP to set the gesture handler, then change the handle // mode of |view| to indicate that it does not want to handle any @@ -2526,7 +2524,7 @@ end = GestureEventForTest(ui::ET_GESTURE_END, 15, 15); widget->OnGestureEvent(&end); EXPECT_FALSE(end.handled()); - EXPECT_EQ(NULL, GetGestureHandler(root_view)); + EXPECT_EQ(nullptr, GetGestureHandler(root_view)); widget->Close(); } @@ -2569,7 +2567,7 @@ EXPECT_EQ(0, v2->GetEventCount(ui::ET_GESTURE_BEGIN)); EXPECT_EQ(0, v3->GetEventCount(ui::ET_GESTURE_BEGIN)); EXPECT_EQ(0, v4->GetEventCount(ui::ET_GESTURE_BEGIN)); - EXPECT_EQ(NULL, GetGestureHandler(root_view)); + EXPECT_EQ(nullptr, GetGestureHandler(root_view)); EXPECT_TRUE(begin.handled()); v1->ResetCounts(); v2->ResetCounts(); @@ -2585,7 +2583,7 @@ EXPECT_EQ(0, v2->GetEventCount(ui::ET_GESTURE_END)); EXPECT_EQ(0, v3->GetEventCount(ui::ET_GESTURE_END)); EXPECT_EQ(0, v4->GetEventCount(ui::ET_GESTURE_END)); - EXPECT_EQ(NULL, GetGestureHandler(root_view)); + EXPECT_EQ(nullptr, GetGestureHandler(root_view)); EXPECT_TRUE(end.handled()); v1->ResetCounts(); v2->ResetCounts(); @@ -2603,7 +2601,7 @@ EXPECT_EQ(0, v2->GetEventCount(ui::ET_GESTURE_END)); EXPECT_EQ(0, v3->GetEventCount(ui::ET_GESTURE_END)); EXPECT_EQ(0, v4->GetEventCount(ui::ET_GESTURE_END)); - EXPECT_EQ(NULL, GetGestureHandler(root_view)); + EXPECT_EQ(nullptr, GetGestureHandler(root_view)); EXPECT_TRUE(end_second_touch_point.handled()); v1->ResetCounts(); v2->ResetCounts(); @@ -2619,7 +2617,7 @@ EXPECT_EQ(0, v2->GetEventCount(ui::ET_GESTURE_SCROLL_UPDATE)); EXPECT_EQ(0, v3->GetEventCount(ui::ET_GESTURE_SCROLL_UPDATE)); EXPECT_EQ(0, v4->GetEventCount(ui::ET_GESTURE_SCROLL_UPDATE)); - EXPECT_EQ(NULL, GetGestureHandler(root_view)); + EXPECT_EQ(nullptr, GetGestureHandler(root_view)); EXPECT_TRUE(scroll_update.handled()); v1->ResetCounts(); v2->ResetCounts(); @@ -2635,7 +2633,7 @@ EXPECT_EQ(0, v2->GetEventCount(ui::ET_GESTURE_SCROLL_END)); EXPECT_EQ(0, v3->GetEventCount(ui::ET_GESTURE_SCROLL_END)); EXPECT_EQ(0, v4->GetEventCount(ui::ET_GESTURE_SCROLL_END)); - EXPECT_EQ(NULL, GetGestureHandler(root_view)); + EXPECT_EQ(nullptr, GetGestureHandler(root_view)); EXPECT_TRUE(scroll_end.handled()); v1->ResetCounts(); v2->ResetCounts(); @@ -2651,7 +2649,7 @@ EXPECT_EQ(0, v2->GetEventCount(ui::ET_SCROLL_FLING_START)); EXPECT_EQ(0, v3->GetEventCount(ui::ET_SCROLL_FLING_START)); EXPECT_EQ(0, v4->GetEventCount(ui::ET_SCROLL_FLING_START)); - EXPECT_EQ(NULL, GetGestureHandler(root_view)); + EXPECT_EQ(nullptr, GetGestureHandler(root_view)); EXPECT_TRUE(scroll_fling_start.handled()); v1->ResetCounts(); v2->ResetCounts(); @@ -2696,13 +2694,13 @@ // event should be dispatched to all views in the hierarchy, the gesture // handler should remain unset, and the event should remain unhandled. GestureEventForTest tap(ui::ET_GESTURE_TAP, 5, 5); - EXPECT_EQ(NULL, GetGestureHandler(root_view)); + EXPECT_EQ(nullptr, GetGestureHandler(root_view)); widget->OnGestureEvent(&tap); EXPECT_EQ(1, v1->GetEventCount(ui::ET_GESTURE_TAP)); EXPECT_EQ(1, v2->GetEventCount(ui::ET_GESTURE_TAP)); EXPECT_EQ(1, v3->GetEventCount(ui::ET_GESTURE_TAP)); EXPECT_EQ(1, v4->GetEventCount(ui::ET_GESTURE_TAP)); - EXPECT_EQ(NULL, GetGestureHandler(root_view)); + EXPECT_EQ(nullptr, GetGestureHandler(root_view)); EXPECT_FALSE(tap.handled()); // No gesture handler is set in the root view and |v1|, |v2|, and |v3| all @@ -2810,7 +2808,7 @@ // When no gesture handler is set, dispatching a ui::ET_GESTURE_TAP_DOWN // should bubble up the views hierarchy until it reaches the first view // that will handle it (|v3|) and then sets the handler to |v3|. - EXPECT_EQ(NULL, GetGestureHandler(root_view)); + EXPECT_EQ(nullptr, GetGestureHandler(root_view)); GestureEventForTest tap_down(ui::ET_GESTURE_TAP_DOWN, 5, 5); widget->OnGestureEvent(&tap_down); EXPECT_EQ(0, v1->GetEventCount(ui::ET_GESTURE_TAP_DOWN)); @@ -2914,7 +2912,7 @@ EXPECT_EQ(0, v2->GetEventCount(ui::ET_GESTURE_END)); EXPECT_EQ(0, v3->GetEventCount(ui::ET_GESTURE_END)); EXPECT_EQ(0, v4->GetEventCount(ui::ET_GESTURE_END)); - EXPECT_EQ(NULL, GetGestureHandler(root_view)); + EXPECT_EQ(nullptr, GetGestureHandler(root_view)); EXPECT_TRUE(end.handled()); widget->Close(); @@ -3087,7 +3085,7 @@ EXPECT_EQ(0, v2->GetEventCount(ui::ET_GESTURE_END)); EXPECT_EQ(0, v3->GetEventCount(ui::ET_GESTURE_END)); EXPECT_EQ(0, v4->GetEventCount(ui::ET_GESTURE_END)); - EXPECT_EQ(NULL, GetGestureHandler(root_view)); + EXPECT_EQ(nullptr, GetGestureHandler(root_view)); EXPECT_TRUE(end.handled()); v1->ResetCounts(); v2->ResetCounts(); @@ -3124,7 +3122,7 @@ EXPECT_EQ(0, v2->GetEventCount(ui::ET_GESTURE_END)); EXPECT_EQ(0, v3->GetEventCount(ui::ET_GESTURE_END)); EXPECT_EQ(0, v4->GetEventCount(ui::ET_GESTURE_END)); - EXPECT_EQ(NULL, GetGestureHandler(root_view)); + EXPECT_EQ(nullptr, GetGestureHandler(root_view)); EXPECT_TRUE(end.handled()); widget->Close(); @@ -3695,7 +3693,7 @@ DISALLOW_COPY_AND_ASSIGN(ScaleFactorView); }; -} +} // namespace // Ensure scale factor changes are propagated from the native Widget. TEST_F(WidgetTest, OnDeviceScaleFactorChanged) { @@ -3738,7 +3736,7 @@ DISALLOW_COPY_AND_ASSIGN(TestWidgetRemovalsObserver); }; -} +} // namespace // Test that WidgetRemovalsObserver::OnWillRemoveView is called when deleting // a view.
diff --git a/ui/views/widget/window_reorderer.cc b/ui/views/widget/window_reorderer.cc index 2f459a86..b51ba17 100644 --- a/ui/views/widget/window_reorderer.cc +++ b/ui/views/widget/window_reorderer.cc
@@ -170,7 +170,7 @@ it != view_with_layer_order.rend(); ++it) { View* view = *it; ui::Layer* layer = view->layer(); - aura::Window* window = NULL; + aura::Window* window = nullptr; auto hosted_window_it = hosted_windows.find(view); if (hosted_window_it != hosted_windows.end()) { @@ -196,7 +196,7 @@ void WindowReorderer::OnWindowDestroying(aura::Window* window) { parent_window_->RemoveObserver(this); - parent_window_ = NULL; + parent_window_ = nullptr; association_observer_.reset(); }
diff --git a/ui/views/widget/window_reorderer_unittest.cc b/ui/views/widget/window_reorderer_unittest.cc index faecf6b..09ae69e 100644 --- a/ui/views/widget/window_reorderer_unittest.cc +++ b/ui/views/widget/window_reorderer_unittest.cc
@@ -143,7 +143,7 @@ parent->GetNativeWindow()); SetWindowAndLayerName(w1, "w1"); - aura::Window* w2 = aura::test::CreateTestWindowWithId(0, NULL); + aura::Window* w2 = aura::test::CreateTestWindowWithId(0, nullptr); SetWindowAndLayerName(w2, "w2"); View* host_view2 = new View();
diff --git a/ui/views/win/fullscreen_handler.cc b/ui/views/win/fullscreen_handler.cc index 7f13e846..eba915ea 100644 --- a/ui/views/win/fullscreen_handler.cc +++ b/ui/views/win/fullscreen_handler.cc
@@ -17,7 +17,7 @@ //////////////////////////////////////////////////////////////////////////////// // FullscreenHandler, public: -FullscreenHandler::FullscreenHandler() : hwnd_(NULL), fullscreen_(false) {} +FullscreenHandler::FullscreenHandler() : hwnd_(nullptr), fullscreen_(false) {} FullscreenHandler::~FullscreenHandler() { } @@ -32,7 +32,7 @@ void FullscreenHandler::MarkFullscreen(bool fullscreen) { if (!task_bar_list_) { HRESULT hr = - ::CoCreateInstance(CLSID_TaskbarList, NULL, CLSCTX_INPROC_SERVER, + ::CoCreateInstance(CLSID_TaskbarList, nullptr, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&task_bar_list_)); if (SUCCEEDED(hr) && FAILED(task_bar_list_->HrInit())) task_bar_list_ = nullptr; @@ -87,7 +87,7 @@ GetMonitorInfo(MonitorFromWindow(hwnd_, MONITOR_DEFAULTTONEAREST), &monitor_info); gfx::Rect window_rect(monitor_info.rcMonitor); - SetWindowPos(hwnd_, NULL, window_rect.x(), window_rect.y(), + SetWindowPos(hwnd_, nullptr, window_rect.x(), window_rect.y(), window_rect.width(), window_rect.height(), SWP_NOZORDER | SWP_NOACTIVATE | SWP_FRAMECHANGED); } else { @@ -99,7 +99,7 @@ // On restore, resize to the previous saved rect size. gfx::Rect new_rect(saved_window_info_.window_rect); - SetWindowPos(hwnd_, NULL, new_rect.x(), new_rect.y(), new_rect.width(), + SetWindowPos(hwnd_, nullptr, new_rect.x(), new_rect.y(), new_rect.width(), new_rect.height(), SWP_NOZORDER | SWP_NOACTIVATE | SWP_FRAMECHANGED); }
diff --git a/ui/views/win/hwnd_message_handler.cc b/ui/views/win/hwnd_message_handler.cc index b754ea2..ab1586fe 100644 --- a/ui/views/win/hwnd_message_handler.cc +++ b/ui/views/win/hwnd_message_handler.cc
@@ -104,26 +104,26 @@ }; // static -MoveLoopMouseWatcher* MoveLoopMouseWatcher::instance_ = NULL; +MoveLoopMouseWatcher* MoveLoopMouseWatcher::instance_ = nullptr; MoveLoopMouseWatcher::MoveLoopMouseWatcher(HWNDMessageHandler* host, bool hide_on_escape) : host_(host), hide_on_escape_(hide_on_escape), got_mouse_up_(false), - mouse_hook_(NULL), - key_hook_(NULL) { + mouse_hook_(nullptr), + key_hook_(nullptr) { // Only one instance can be active at a time. if (instance_) instance_->Unhook(); - mouse_hook_ = SetWindowsHookEx( - WH_MOUSE, &MouseHook, NULL, GetCurrentThreadId()); + mouse_hook_ = + SetWindowsHookEx(WH_MOUSE, &MouseHook, nullptr, GetCurrentThreadId()); if (mouse_hook_) { instance_ = this; // We don't care if setting the key hook succeeded. - key_hook_ = SetWindowsHookEx( - WH_KEYBOARD, &KeyHook, NULL, GetCurrentThreadId()); + key_hook_ = + SetWindowsHookEx(WH_KEYBOARD, &KeyHook, nullptr, GetCurrentThreadId()); } if (instance_ != this) { // Failed installation. Assume we got a mouse up in this case, otherwise @@ -144,9 +144,9 @@ UnhookWindowsHookEx(mouse_hook_); if (key_hook_) UnhookWindowsHookEx(key_hook_); - key_hook_ = NULL; - mouse_hook_ = NULL; - instance_ = NULL; + key_hook_ = nullptr; + mouse_hook_ = nullptr; + instance_ = nullptr; } // static @@ -181,7 +181,7 @@ int flags = RDW_INVALIDATE | RDW_NOCHILDREN | RDW_FRAME; if (process_id == GetCurrentProcessId()) flags |= RDW_UPDATENOW; - RedrawWindow(hwnd, NULL, NULL, flags); + RedrawWindow(hwnd, nullptr, nullptr, flags); return TRUE; } @@ -378,15 +378,15 @@ waiting_for_close_now_(false), use_system_default_icon_(false), restored_enabled_(false), - current_cursor_(NULL), - previous_cursor_(NULL), + current_cursor_(nullptr), + previous_cursor_(nullptr), dpi_(0), called_enable_non_client_dpi_scaling_(false), active_mouse_tracking_flags_(0), is_right_mouse_pressed_on_caption_(false), lock_updates_count_(0), ignore_window_pos_changes_(false), - last_monitor_(NULL), + last_monitor_(nullptr), is_first_nccalc_(true), menu_depth_(0), id_generator_(0), @@ -408,7 +408,7 @@ HWNDMessageHandler::~HWNDMessageHandler() { DCHECK(delegate_->GetHWNDMessageDelegateInputMethod()); delegate_->GetHWNDMessageDelegateInputMethod()->RemoveObserver(this); - delegate_ = NULL; + delegate_ = nullptr; // Prevent calls back into this class via WNDPROC now that we've been // destroyed. ClearUserData(); @@ -518,7 +518,7 @@ return fullscreen_handler_->GetRestoreBounds(); gfx::Rect bounds; - GetWindowPlacement(&bounds, NULL); + GetWindowPlacement(&bounds, nullptr); return bounds; } @@ -538,7 +538,7 @@ const bool succeeded = !!::GetWindowPlacement(hwnd(), &wp); DCHECK(succeeded); - if (bounds != NULL) { + if (bounds != nullptr) { if (wp.showCmd == SW_SHOWNORMAL) { // GetWindowPlacement can return misleading position if a normalized // window was resized using Aero Snap feature (see comment 9 in bug @@ -589,7 +589,7 @@ } void HWNDMessageHandler::SetSize(const gfx::Size& size) { - SetWindowPos(hwnd(), NULL, 0, 0, size.width(), size.height(), + SetWindowPos(hwnd(), nullptr, 0, 0, size.width(), size.height(), SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOMOVE); } @@ -689,9 +689,9 @@ // ShowWindow(SW_HIDE) will automatically activate another window). This // code can be called while a window is being deactivated, and activating // another window will screw up the activation that is already in progress. - SetWindowPos(hwnd(), NULL, 0, 0, 0, 0, + SetWindowPos(hwnd(), nullptr, 0, 0, 0, 0, SWP_HIDEWINDOW | SWP_NOACTIVATE | SWP_NOMOVE | - SWP_NOREPOSITION | SWP_NOSIZE | SWP_NOZORDER); + SWP_NOREPOSITION | SWP_NOSIZE | SWP_NOZORDER); } } @@ -701,7 +701,7 @@ void HWNDMessageHandler::Minimize() { ExecuteSystemMenuCommand(SC_MINIMIZE); - delegate_->HandleNativeBlur(NULL); + delegate_->HandleNativeBlur(nullptr); } void HWNDMessageHandler::Restore() { @@ -775,10 +775,10 @@ } void HWNDMessageHandler::SendFrameChanged() { - SetWindowPos(hwnd(), NULL, 0, 0, 0, 0, - SWP_FRAMECHANGED | SWP_NOACTIVATE | SWP_NOCOPYBITS | - SWP_NOMOVE | SWP_NOOWNERZORDER | SWP_NOREPOSITION | - SWP_NOSENDCHANGING | SWP_NOSIZE | SWP_NOZORDER); + SetWindowPos(hwnd(), nullptr, 0, 0, 0, 0, + SWP_FRAMECHANGED | SWP_NOACTIVATE | SWP_NOCOPYBITS | SWP_NOMOVE | + SWP_NOOWNERZORDER | SWP_NOREPOSITION | SWP_NOSENDCHANGING | + SWP_NOSIZE | SWP_NOZORDER); } void HWNDMessageHandler::FlashFrame(bool flash) { @@ -840,7 +840,7 @@ current_cursor_ = cursor; } else if (previous_cursor_) { ::SetCursor(previous_cursor_); - previous_cursor_ = NULL; + previous_cursor_ = nullptr; } } @@ -1237,7 +1237,7 @@ // This triggers querying WM_NCCALCSIZE again. RECT client; GetWindowRect(hwnd(), &client); - SetWindowPos(hwnd(), NULL, client.left, client.top, + SetWindowPos(hwnd(), nullptr, client.left, client.top, client.right - client.left, client.bottom - client.top, SWP_FRAMECHANGED); } @@ -1397,7 +1397,7 @@ if (!is_translucent_ && !custom_window_region_.is_valid() && (IsFrameSystemDrawn() || !delegate_->HasNonClientView())) { if (force) - SetWindowRgn(hwnd(), NULL, redraw); + SetWindowRgn(hwnd(), nullptr, redraw); return; } @@ -1411,7 +1411,8 @@ base::win::ScopedRegion new_region; if (custom_window_region_.is_valid()) { new_region.reset(CreateRectRgn(0, 0, 0, 0)); - CombineRgn(new_region.get(), custom_window_region_.get(), NULL, RGN_COPY); + CombineRgn(new_region.get(), custom_window_region_.get(), nullptr, + RGN_COPY); } else if (IsMaximized()) { HMONITOR monitor = MonitorFromWindow(hwnd(), MONITOR_DEFAULTTONEAREST); MONITORINFO mi; @@ -1429,8 +1430,8 @@ new_region.reset(gfx::CreateHRGNFromSkPath(window_mask)); } - const bool has_current_region = current_rgn != 0; - const bool has_new_region = new_region != 0; + const bool has_current_region = current_rgn != nullptr; + const bool has_new_region = new_region != nullptr; if (has_current_region != has_new_region || (has_current_region && !EqualRgn(current_rgn.get(), new_region.get()))) { // SetWindowRgn takes ownership of the HRGN. @@ -1493,7 +1494,7 @@ base::TimeDelta::FromMilliseconds(500)); return; } - InvalidateRect(hwnd(), NULL, FALSE); + InvalidateRect(hwnd(), nullptr, FALSE); } bool HWNDMessageHandler::IsFrameSystemDrawn() const { @@ -1998,7 +1999,7 @@ // themselves leading to issues like http://crbug.com/74604 // We redraw out-of-process HWNDs asynchronously to avoid hanging the // whole app if a child HWND belonging to a hung plugin is encountered. - RedrawWindow(hwnd(), NULL, NULL, + RedrawWindow(hwnd(), nullptr, nullptr, RDW_NOCHILDREN | RDW_INVALIDATE | RDW_UPDATENOW); EnumChildWindows(hwnd(), EnumChildWindowsForRedraw, NULL); } @@ -2374,7 +2375,7 @@ // Use the default value, IDC_ARROW. break; } - ::SetCursor(LoadCursor(NULL, cursor)); + ::SetCursor(LoadCursor(nullptr, cursor)); return 1; } @@ -2400,8 +2401,9 @@ !delegate_->WillProcessWorkAreaChange()) { // Fire a dummy SetWindowPos() call, so we'll trip the code in // OnWindowPosChanging() below that notices work area changes. - ::SetWindowPos(hwnd(), 0, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE | - SWP_NOZORDER | SWP_NOREDRAW | SWP_NOACTIVATE | SWP_NOOWNERZORDER); + ::SetWindowPos(hwnd(), nullptr, 0, 0, 0, 0, + SWP_NOSIZE | SWP_NOMOVE | SWP_NOZORDER | SWP_NOREDRAW | + SWP_NOACTIVATE | SWP_NOOWNERZORDER); SetMsgHandled(TRUE); } else { if (flags == SPI_SETWORKAREA) @@ -2422,7 +2424,7 @@ delegate_->HandleWindowMinimizedOrRestored(param != SIZE_MINIMIZED); last_size_param_ = param; - RedrawWindow(hwnd(), NULL, NULL, RDW_INVALIDATE | RDW_ALLCHILDREN); + RedrawWindow(hwnd(), nullptr, nullptr, RDW_INVALIDATE | RDW_ALLCHILDREN); // ResetWindowRegion is going to trigger WM_NCPAINT. By doing it after we've // invoked OnSize we ensure the RootView has been laid out. ResetWindowRegion(false, true); @@ -3139,8 +3141,8 @@ // we don't want windows stealing focus if they're not already active, we // set SWP_NOACTIVATE. UINT flags = SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE; - SetWindowPos(hwnd(), NULL, 0, 0, 0, 0, flags | SWP_HIDEWINDOW); - SetWindowPos(hwnd(), NULL, 0, 0, 0, 0, flags | SWP_SHOWWINDOW); + SetWindowPos(hwnd(), nullptr, 0, 0, 0, 0, flags | SWP_HIDEWINDOW); + SetWindowPos(hwnd(), nullptr, 0, 0, 0, 0, flags | SWP_SHOWWINDOW); } // WM_DWMCOMPOSITIONCHANGED is only sent to top level windows, however we want // to notify our children too, since we can have MDI child windows who need to @@ -3254,7 +3256,7 @@ // If the DWM is rendering the window controls, we need to give the DWM's // default window procedure the chance to repaint the window border icons if (HasSystemFrame()) - handled = DwmDefWindowProc(hwnd(), WM_NCMOUSELEAVE, 0, 0, NULL) != 0; + handled = DwmDefWindowProc(hwnd(), WM_NCMOUSELEAVE, 0, 0, nullptr) != 0; break; } @@ -3272,7 +3274,7 @@ SetWindowLong(hwnd(), GWL_STYLE, style & ~WS_MAXIMIZE); gfx::Size old_size = GetClientAreaBounds().size(); - SetWindowPos(hwnd(), NULL, bounds_in_pixels.x(), bounds_in_pixels.y(), + SetWindowPos(hwnd(), nullptr, bounds_in_pixels.x(), bounds_in_pixels.y(), bounds_in_pixels.width(), bounds_in_pixels.height(), SWP_NOACTIVATE | SWP_NOZORDER);
diff --git a/ui/views/win/hwnd_util.h b/ui/views/win/hwnd_util.h index ae2dc1d..6e3e2f0 100644 --- a/ui/views/win/hwnd_util.h +++ b/ui/views/win/hwnd_util.h
@@ -28,6 +28,6 @@ VIEWS_EXPORT gfx::Rect GetWindowBoundsForClientBounds( View* view, const gfx::Rect& client_bounds); -} +} // namespace views #endif // UI_VIEWS_WIN_HWND_UTIL_H_
diff --git a/ui/views/win/hwnd_util_aurawin.cc b/ui/views/win/hwnd_util_aurawin.cc index 37dca58..cbd06d0 100644 --- a/ui/views/win/hwnd_util_aurawin.cc +++ b/ui/views/win/hwnd_util_aurawin.cc
@@ -11,7 +11,7 @@ namespace views { HWND HWNDForView(const View* view) { - return view->GetWidget() ? HWNDForWidget(view->GetWidget()) : NULL; + return view->GetWidget() ? HWNDForWidget(view->GetWidget()) : nullptr; } HWND HWNDForWidget(const Widget* widget) { @@ -19,13 +19,14 @@ } HWND HWNDForNativeView(const gfx::NativeView view) { - return view && view->GetRootWindow() ? - view->GetHost()->GetAcceleratedWidget() : NULL; + return view && view->GetRootWindow() ? view->GetHost()->GetAcceleratedWidget() + : nullptr; } HWND HWNDForNativeWindow(const gfx::NativeWindow window) { - return window && window->GetRootWindow() ? - window->GetHost()->GetAcceleratedWidget() : NULL; + return window && window->GetRootWindow() + ? window->GetHost()->GetAcceleratedWidget() + : nullptr; } gfx::Rect GetWindowBoundsForClientBounds(View* view,
diff --git a/ui/views/win/scoped_fullscreen_visibility.cc b/ui/views/win/scoped_fullscreen_visibility.cc index b6fd33f1..309ba37 100644 --- a/ui/views/win/scoped_fullscreen_visibility.cc +++ b/ui/views/win/scoped_fullscreen_visibility.cc
@@ -9,7 +9,7 @@ namespace views { // static -std::map<HWND, int>* ScopedFullscreenVisibility::full_screen_windows_ = NULL; +std::map<HWND, int>* ScopedFullscreenVisibility::full_screen_windows_ = nullptr; ScopedFullscreenVisibility::ScopedFullscreenVisibility(HWND hwnd) : hwnd_(hwnd) { @@ -24,9 +24,9 @@ // ShowWindow(SW_HIDE) will automatically activate another window). This // code can be called while a window is being deactivated, and activating // another window will screw up the activation that is already in progress. - SetWindowPos(hwnd_, NULL, 0, 0, 0, 0, + SetWindowPos(hwnd_, nullptr, 0, 0, 0, 0, SWP_HIDEWINDOW | SWP_NOACTIVATE | SWP_NOMOVE | - SWP_NOREPOSITION | SWP_NOSIZE | SWP_NOZORDER); + SWP_NOREPOSITION | SWP_NOSIZE | SWP_NOZORDER); } } @@ -39,7 +39,7 @@ } if (full_screen_windows_->empty()) { delete full_screen_windows_; - full_screen_windows_ = NULL; + full_screen_windows_ = nullptr; } }
diff --git a/ui/views/window/client_view.cc b/ui/views/window/client_view.cc index 2b6a99a..88842b6 100644 --- a/ui/views/window/client_view.cc +++ b/ui/views/window/client_view.cc
@@ -28,11 +28,11 @@ } DialogClientView* ClientView::AsDialogClientView() { - return NULL; + return nullptr; } const DialogClientView* ClientView::AsDialogClientView() const { - return NULL; + return nullptr; } bool ClientView::CanClose() {
diff --git a/ui/views/window/custom_frame_view.cc b/ui/views/window/custom_frame_view.cc index fc08c30..15ad371 100644 --- a/ui/views/window/custom_frame_view.cc +++ b/ui/views/window/custom_frame_view.cc
@@ -85,16 +85,15 @@ // CustomFrameView, public: CustomFrameView::CustomFrameView() - : frame_(NULL), - window_icon_(NULL), - minimize_button_(NULL), - maximize_button_(NULL), - restore_button_(NULL), - close_button_(NULL), + : frame_(nullptr), + window_icon_(nullptr), + minimize_button_(nullptr), + maximize_button_(nullptr), + restore_button_(nullptr), + close_button_(nullptr), frame_background_(new FrameBackground()), minimum_title_bar_x_(0), - maximum_title_bar_x_(-1) { -} + maximum_title_bar_x_(-1) {} CustomFrameView::~CustomFrameView() { } @@ -521,7 +520,7 @@ const std::vector<views::FrameButton>& trailing_buttons = button_order->trailing_buttons(); - ImageButton* button = NULL; + ImageButton* button = nullptr; for (auto it = leading_buttons.begin(); it != leading_buttons.end(); ++it) { button = GetImageButton(*it); if (!button) @@ -558,7 +557,7 @@ // The window title position is calculated based on the icon position, even // when there is no icon. gfx::Rect icon_bounds(IconBounds()); - bool show_window_icon = window_icon_ != NULL; + bool show_window_icon = window_icon_ != nullptr; if (show_window_icon) window_icon_->SetBoundsRect(icon_bounds); @@ -612,7 +611,7 @@ } ImageButton* CustomFrameView::GetImageButton(views::FrameButton frame_button) { - ImageButton* button = NULL; + ImageButton* button = nullptr; switch (frame_button) { case views::FRAME_BUTTON_MINIMIZE: { button = minimize_button_; @@ -621,7 +620,7 @@ bool should_show = frame_->widget_delegate()->CanMinimize(); button->SetVisible(should_show); if (!should_show) - return NULL; + return nullptr; break; } @@ -634,7 +633,7 @@ bool should_show = frame_->widget_delegate()->CanMaximize(); button->SetVisible(should_show); if (!should_show) - return NULL; + return nullptr; break; }
diff --git a/ui/views/window/dialog_client_view_unittest.cc b/ui/views/window/dialog_client_view_unittest.cc index 4c4e67e..09c04b41 100644 --- a/ui/views/window/dialog_client_view_unittest.cc +++ b/ui/views/window/dialog_client_view_unittest.cc
@@ -183,8 +183,8 @@ TEST_F(DialogClientViewTest, UpdateButtons) { // This dialog should start with no buttons. EXPECT_EQ(GetDialogButtons(), ui::DIALOG_BUTTON_NONE); - EXPECT_EQ(NULL, client_view()->ok_button()); - EXPECT_EQ(NULL, client_view()->cancel_button()); + EXPECT_EQ(nullptr, client_view()->ok_button()); + EXPECT_EQ(nullptr, client_view()->cancel_button()); const int height_without_buttons = GetUpdatedClientBounds().height(); // Update to use both buttons. @@ -196,19 +196,19 @@ // Remove the dialog buttons. SetDialogButtons(ui::DIALOG_BUTTON_NONE); - EXPECT_EQ(NULL, client_view()->ok_button()); - EXPECT_EQ(NULL, client_view()->cancel_button()); + EXPECT_EQ(nullptr, client_view()->ok_button()); + EXPECT_EQ(nullptr, client_view()->cancel_button()); EXPECT_EQ(GetUpdatedClientBounds().height(), height_without_buttons); // Reset with just an ok button. SetDialogButtons(ui::DIALOG_BUTTON_OK); EXPECT_TRUE(client_view()->ok_button()->is_default()); - EXPECT_EQ(NULL, client_view()->cancel_button()); + EXPECT_EQ(nullptr, client_view()->cancel_button()); EXPECT_EQ(GetUpdatedClientBounds().height(), height_with_buttons); // Reset with just a cancel button. SetDialogButtons(ui::DIALOG_BUTTON_CANCEL); - EXPECT_EQ(NULL, client_view()->ok_button()); + EXPECT_EQ(nullptr, client_view()->ok_button()); EXPECT_EQ(client_view()->cancel_button()->is_default(), PlatformStyle::kDialogDefaultButtonCanBeCancel); EXPECT_EQ(GetUpdatedClientBounds().height(), height_with_buttons); @@ -218,9 +218,9 @@ // Removing buttons from another context should clear the local pointer. SetDialogButtons(ui::DIALOG_BUTTON_OK | ui::DIALOG_BUTTON_CANCEL); delete client_view()->ok_button(); - EXPECT_EQ(NULL, client_view()->ok_button()); + EXPECT_EQ(nullptr, client_view()->ok_button()); delete client_view()->cancel_button(); - EXPECT_EQ(NULL, client_view()->cancel_button()); + EXPECT_EQ(nullptr, client_view()->cancel_button()); // Updating should restore the requested buttons properly. SetDialogButtons(ui::DIALOG_BUTTON_OK | ui::DIALOG_BUTTON_CANCEL);
diff --git a/ui/views/window/dialog_delegate.cc b/ui/views/window/dialog_delegate.cc index 3c706c8..637d3a8 100644 --- a/ui/views/window/dialog_delegate.cc +++ b/ui/views/window/dialog_delegate.cc
@@ -71,7 +71,7 @@ #elif defined(OS_WIN) // The new style doesn't support unparented dialogs on Windows Classic themes. if (dialog && !ui::win::IsAeroGlassEnabled()) - dialog->supports_custom_frame_ &= parent != NULL; + dialog->supports_custom_frame_ &= parent != nullptr; #endif if (!dialog || dialog->ShouldUseCustomFrame()) { @@ -126,7 +126,7 @@ } View* DialogDelegate::CreateExtraView() { - return NULL; + return nullptr; } bool DialogDelegate::GetExtraViewPadding(int* padding) { @@ -134,7 +134,7 @@ } View* DialogDelegate::CreateFootnoteView() { - return NULL; + return nullptr; } bool DialogDelegate::Cancel() { @@ -178,19 +178,19 @@ const DialogClientView* dcv = GetDialogClientView(); int default_button = GetDefaultDialogButton(); if (default_button == ui::DIALOG_BUTTON_NONE) - return NULL; + return nullptr; if ((default_button & GetDialogButtons()) == 0) { // The default button is a button we don't have. NOTREACHED(); - return NULL; + return nullptr; } if (default_button & ui::DIALOG_BUTTON_OK) return dcv->ok_button(); if (default_button & ui::DIALOG_BUTTON_CANCEL) return dcv->cancel_button(); - return NULL; + return nullptr; } DialogDelegate* DialogDelegate::AsDialogDelegate() {
diff --git a/ui/views/window/window_button_order_provider.cc b/ui/views/window/window_button_order_provider.cc index b1ac70e4..678be8e6 100644 --- a/ui/views/window/window_button_order_provider.cc +++ b/ui/views/window/window_button_order_provider.cc
@@ -7,7 +7,7 @@ namespace views { // static -WindowButtonOrderProvider* WindowButtonOrderProvider::instance_ = NULL; +WindowButtonOrderProvider* WindowButtonOrderProvider::instance_ = nullptr; /////////////////////////////////////////////////////////////////////////////// // WindowButtonOrderProvider, public:
diff --git a/ui/webui/resources/webui_resources.grd b/ui/webui/resources/webui_resources.grd index 6d52540..2800071 100644 --- a/ui/webui/resources/webui_resources.grd +++ b/ui/webui/resources/webui_resources.grd
@@ -13,7 +13,9 @@ </outputs> <release seq="1"> <includes> - <include name="IDR_WEBUI_I18N_TEMPLATE_JS" file="js/i18n_template.js" flattenhtml="true" type="BINDATA" /> + <if expr="chromeos"> + <include name="IDR_WEBUI_I18N_TEMPLATE_JS" file="js/i18n_template.js" flattenhtml="true" type="BINDATA" /> + </if> <include name="IDR_WEBUI_JSTEMPLATE_JS" file="js/jstemplate_compiled.js" flattenhtml="true" type="BINDATA" /> <!-- Roboto Font. Roboto-Regular and Roboto-Light is already available on Android, and Roboto-Medium is not used on Android. All 6 weights of @@ -514,9 +516,6 @@ <structure name="IDR_WEBUI_JS_I18N_TEMPLATE_NO_PROCESS" file="js/i18n_template_no_process.js" type="chrome_html" compress="gzip" /> - <structure name="IDR_WEBUI_JS_I18N_TEMPLATE_PROCESS" - file="js/i18n_template_process.js" - type="chrome_html" compress="gzip" /> <structure name="IDR_WEBUI_JS_LOAD_TIME_DATA" file="js/load_time_data.js" type="chrome_html" /> <structure name="IDR_WEBUI_JS_PARSE_HTML_SUBSET"