diff --git a/DEPS b/DEPS index e7fc4413..cf2bb68 100644 --- a/DEPS +++ b/DEPS
@@ -40,11 +40,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': '0fa156fcfba3b430801b5448ddfc254732bf7386', + 'skia_revision': '921ebe5b736b068182ce5de1ab0e36add06d5e2c', # 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': 'a41f32d2aa7d677a89ba2c2b4a83d3c76895efd7', + 'v8_revision': 'fe9bb7e6e251159852770160cfb21dad3cf03523', # 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. @@ -60,11 +60,11 @@ # 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': 'f770c9916363b17ba928da7a6d7842dc9e39ae53', + 'swiftshader_revision': '2ed3149ac7f92d367b9629da29c45ffc0d6055d3', # 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': 'e6baec592965d6e7e8969ae22910306ff4fed98b', + 'pdfium_revision': 'd776c9764c7b4ae8fda801c8dc6c92fd7aa1fa87', # 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. @@ -96,7 +96,7 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling catapult # and whatever else without interference from each other. - 'catapult_revision': '9a55abab029cb9ae94f5160ded11b09a4638a955', + 'catapult_revision': '6e6baa037e67c164d489a5c6c97e07efa0d9e66f', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling libFuzzer # and whatever else without interference from each other. @@ -154,7 +154,7 @@ Var('chromium_git') + '/external/colorama.git' + '@' + '799604a1041e9b3bc5d2789ecbd7e8db2e18e6b8', 'src/third_party/icu': - Var('chromium_git') + '/chromium/deps/icu.git' + '@' + '450be73c9ee8ae29d43d4fdc82febb2a5f62bfb5', + Var('chromium_git') + '/chromium/deps/icu.git' + '@' + 'b34251f8b762f8e2112a89c587855ca4297fed96', 'src/third_party/hunspell_dictionaries': Var('chromium_git') + '/chromium/deps/hunspell_dictionaries.git' + '@' + 'dc6e7c25bf47cbfb466e0701fd2728b4a12e79d5', @@ -196,7 +196,7 @@ Var('chromium_git') + '/external/bidichecker/lib.git' + '@' + '97f2aa645b74c28c57eca56992235c79850fa9e0', 'src/third_party/webgl/src': - Var('chromium_git') + '/external/khronosgroup/webgl.git' + '@' + '32cfddc9e452c93bcbe443d6ddcc0c18ac556501', + Var('chromium_git') + '/external/khronosgroup/webgl.git' + '@' + 'fd73a606f94d1837eba4d165f1f5b3afd542fc08', 'src/third_party/webdriver/pylib': Var('chromium_git') + '/external/selenium/py.git' + '@' + '5fd78261a75fe08d27ca4835fb6c5ce4b42275bd', @@ -205,7 +205,7 @@ Var('chromium_git') + '/webm/libvpx.git' + '@' + '6af42f5102ad7c00d3fed389b186663a88d812ee', 'src/third_party/ffmpeg': - Var('chromium_git') + '/chromium/third_party/ffmpeg.git' + '@' + '9751ef06f90fb7ebf02b4e9ecc963a4e36a221d3', + Var('chromium_git') + '/chromium/third_party/ffmpeg.git' + '@' + '28a5cdde5c32bcf66715343c10f74e85713f7aaf', 'src/third_party/usrsctp/usrsctplib': Var('chromium_git') + '/external/github.com/sctplab/usrsctp' + '@' + '8679f2b0bf063ac894dc473debefd61dbbebf622', @@ -241,7 +241,7 @@ Var('chromium_git') + '/external/github.com/open-source-parsers/jsoncpp.git' + '@' + 'f572e8e42e22cfcf5ab0aea26574f408943edfa4', # from svn 248 'src/third_party/libyuv': - Var('chromium_git') + '/libyuv/libyuv.git' + '@' + '2adb84e39e360723d19c68f315d99e3e0f88318c', # from r1650 + Var('chromium_git') + '/libyuv/libyuv.git' + '@' + '8cab2e31d76246263206318f3568d452e7f3ff3e', # from r1651 'src/third_party/smhasher/src': Var('chromium_git') + '/external/smhasher.git' + '@' + 'e87738e57558e0ec472b2fc3a643b838e5b6e88f',
diff --git a/WATCHLISTS b/WATCHLISTS index 8d1d7ea8..d24d032 100644 --- a/WATCHLISTS +++ b/WATCHLISTS
@@ -2199,6 +2199,7 @@ 'tether': ['jlklein+watch-tether@chromium.org', 'khorimoto+watch-tether@chromium.org', 'hansberry+watch-tether@chromium.org', + 'lesliewatkins+watch-tether@chromium.org', 'tengs+watch-tether@chromium.org', 'jhawkins+watch-tether@chromium.org'], 'textinput': ['nona+watch@chromium.org',
diff --git a/android_webview/BUILD.gn b/android_webview/BUILD.gn index 452b178f..2cac47d 100644 --- a/android_webview/BUILD.gn +++ b/android_webview/BUILD.gn
@@ -483,7 +483,6 @@ "browser/renderer_host/aw_render_view_host_ext.h", "browser/renderer_host/aw_resource_dispatcher_host_delegate.cc", "browser/renderer_host/aw_resource_dispatcher_host_delegate.h", - "browser/scoped_allow_wait_for_legacy_web_view_api.h", "browser/scoped_app_gl_state_restore.cc", "browser/scoped_app_gl_state_restore.h", "browser/surfaces_instance.cc",
diff --git a/android_webview/browser/find_helper.cc b/android_webview/browser/find_helper.cc index 44939bd..da870d1 100644 --- a/android_webview/browser/find_helper.cc +++ b/android_webview/browser/find_helper.cc
@@ -4,7 +4,6 @@ #include "android_webview/browser/find_helper.h" -#include "android_webview/browser/scoped_allow_wait_for_legacy_web_view_api.h" #include "base/message_loop/message_loop.h" #include "content/public/browser/render_view_host.h" #include "content/public/browser/web_contents.h"
diff --git a/android_webview/browser/hardware_renderer.cc b/android_webview/browser/hardware_renderer.cc index 655dd44..ffb2a6f 100644 --- a/android_webview/browser/hardware_renderer.cc +++ b/android_webview/browser/hardware_renderer.cc
@@ -177,7 +177,11 @@ child_id_ = cc::LocalSurfaceId(); } -void HardwareRenderer::DidReceiveCompositorFrameAck() {} +void HardwareRenderer::DidReceiveCompositorFrameAck( + const cc::ReturnedResourceArray& resources) { + ReturnResourcesToCompositor(resources, compositor_id_, + last_submitted_compositor_frame_sink_id_); +} void HardwareRenderer::OnBeginFrame(const cc::BeginFrameArgs& args) { // TODO(tansell): Hook this up. @@ -256,11 +260,13 @@ } void HardwareRenderer::CreateNewCompositorFrameSinkSupport() { + constexpr bool is_root = false; + constexpr bool handles_frame_sink_id_invalidation = false; + constexpr bool needs_sync_points = true; support_.reset(); - support_ = base::MakeUnique<cc::CompositorFrameSinkSupport>( - this, surfaces_->GetSurfaceManager(), frame_sink_id_, false /* is_root */, - false /* handles_frame_sink_id_invalidation */, - true /* needs_sync_points */); + support_ = cc::CompositorFrameSinkSupport::Create( + this, surfaces_->GetSurfaceManager(), frame_sink_id_, is_root, + handles_frame_sink_id_invalidation, needs_sync_points); } } // namespace android_webview
diff --git a/android_webview/browser/hardware_renderer.h b/android_webview/browser/hardware_renderer.h index 03a0093c..511a8c5b 100644 --- a/android_webview/browser/hardware_renderer.h +++ b/android_webview/browser/hardware_renderer.h
@@ -50,7 +50,8 @@ private: // cc::CompositorFrameSinkSupportClient implementation. - void DidReceiveCompositorFrameAck() override; + void DidReceiveCompositorFrameAck( + const cc::ReturnedResourceArray& resources) override; void OnBeginFrame(const cc::BeginFrameArgs& args) override; void ReclaimResources(const cc::ReturnedResourceArray& resources) override; void WillDrawSurface(const cc::LocalSurfaceId& local_surface_id,
diff --git a/android_webview/browser/renderer_host/aw_render_view_host_ext.cc b/android_webview/browser/renderer_host/aw_render_view_host_ext.cc index c2d2c9d..985627b11 100644 --- a/android_webview/browser/renderer_host/aw_render_view_host_ext.cc +++ b/android_webview/browser/renderer_host/aw_render_view_host_ext.cc
@@ -5,7 +5,6 @@ #include "android_webview/browser/renderer_host/aw_render_view_host_ext.h" #include "android_webview/browser/aw_browser_context.h" -#include "android_webview/browser/scoped_allow_wait_for_legacy_web_view_api.h" #include "android_webview/common/render_view_messages.h" #include "base/android/scoped_java_ref.h" #include "base/callback.h"
diff --git a/android_webview/browser/scoped_allow_wait_for_legacy_web_view_api.h b/android_webview/browser/scoped_allow_wait_for_legacy_web_view_api.h deleted file mode 100644 index af2154b6..0000000 --- a/android_webview/browser/scoped_allow_wait_for_legacy_web_view_api.h +++ /dev/null
@@ -1,20 +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 ANDROID_WEBVIEW_BROWSER_SCOPED_ALLOW_WAIT_FOR_LEGACY_WEB_VIEW_API_H -#define ANDROID_WEBVIEW_BROWSER_SCOPED_ALLOW_WAIT_FOR_LEGACY_WEB_VIEW_API_H - -#include "base/threading/thread_restrictions.h" - -// This class is only available when building the chromium back-end for android -// webview: it is required where API backward compatibility demands that the UI -// thread must block waiting on other threads e.g. to obtain a synchronous -// return value. Long term, asynchronous overloads of all such methods will be -// added in the public API, and and no new uses of this will be allowed. -class ScopedAllowWaitForLegacyWebViewApi { - private: - base::ThreadRestrictions::ScopedAllowWait wait; -}; - -#endif // ANDROID_WEBVIEW_BROWSER_SCOPED_ALLOW_WAIT_FOR_LEGACY_WEB_VIEW_API_H
diff --git a/android_webview/browser/surfaces_instance.cc b/android_webview/browser/surfaces_instance.cc index 708cd33..109321f7 100644 --- a/android_webview/browser/surfaces_instance.cc +++ b/android_webview/browser/surfaces_instance.cc
@@ -59,9 +59,9 @@ constexpr bool is_root = true; constexpr bool handles_frame_sink_id_invalidation = true; constexpr bool needs_sync_points = true; - support_.reset(new cc::CompositorFrameSinkSupport( + support_ = cc::CompositorFrameSinkSupport::Create( this, surface_manager_.get(), frame_sink_id_, is_root, - handles_frame_sink_id_invalidation, needs_sync_points)); + handles_frame_sink_id_invalidation, needs_sync_points); begin_frame_source_.reset(new cc::StubBeginFrameSource); std::unique_ptr<cc::TextureMailboxDeleter> texture_mailbox_deleter( @@ -175,7 +175,10 @@ support_->SubmitCompositorFrame(root_id_, std::move(empty_frame)); } -void SurfacesInstance::DidReceiveCompositorFrameAck() {} +void SurfacesInstance::DidReceiveCompositorFrameAck( + const cc::ReturnedResourceArray& resources) { + ReclaimResources(resources); +} void SurfacesInstance::OnBeginFrame(const cc::BeginFrameArgs& args) {}
diff --git a/android_webview/browser/surfaces_instance.h b/android_webview/browser/surfaces_instance.h index 22d2c1b..13f75e8 100644 --- a/android_webview/browser/surfaces_instance.h +++ b/android_webview/browser/surfaces_instance.h
@@ -65,7 +65,8 @@ void DisplayDidDrawAndSwap() override {} // cc::CompositorFrameSinkSupportClient implementation. - void DidReceiveCompositorFrameAck() override; + void DidReceiveCompositorFrameAck( + const cc::ReturnedResourceArray& resources) override; void OnBeginFrame(const cc::BeginFrameArgs& args) override; void WillDrawSurface(const cc::LocalSurfaceId& local_surface_id, const gfx::Rect& damage_rect) override;
diff --git a/android_webview/java/src/org/chromium/android_webview/AwSettings.java b/android_webview/java/src/org/chromium/android_webview/AwSettings.java index 94cbd29b..9b9a1f36 100644 --- a/android_webview/java/src/org/chromium/android_webview/AwSettings.java +++ b/android_webview/java/src/org/chromium/android_webview/AwSettings.java
@@ -327,9 +327,7 @@ public void setAcceptThirdPartyCookies(boolean accept) { if (TRACE) Log.d(LOGTAG, "setAcceptThirdPartyCookies=" + accept); synchronized (mAwSettingsLock) { - if (mAcceptThirdPartyCookies != accept) { - mAcceptThirdPartyCookies = accept; - } + mAcceptThirdPartyCookies = accept; } } @@ -372,9 +370,7 @@ public void setAllowFileAccess(boolean allow) { if (TRACE) Log.d(LOGTAG, "setAllowFileAccess=" + allow); synchronized (mAwSettingsLock) { - if (mAllowFileUrlAccess != allow) { - mAllowFileUrlAccess = allow; - } + mAllowFileUrlAccess = allow; } } @@ -393,9 +389,7 @@ public void setAllowContentAccess(boolean allow) { if (TRACE) Log.d(LOGTAG, "setAllowContentAccess=" + allow); synchronized (mAwSettingsLock) { - if (mAllowContentUrlAccess != allow) { - mAllowContentUrlAccess = allow; - } + mAllowContentUrlAccess = allow; } } @@ -414,9 +408,7 @@ public void setCacheMode(int mode) { if (TRACE) Log.d(LOGTAG, "setCacheMode=" + mode); synchronized (mAwSettingsLock) { - if (mCacheMode != mode) { - mCacheMode = mode; - } + mCacheMode = mode; } } @@ -525,9 +517,7 @@ public void setGeolocationEnabled(boolean flag) { if (TRACE) Log.d(LOGTAG, "setGeolocationEnabled=" + flag); synchronized (mAwSettingsLock) { - if (mGeolocationEnabled != flag) { - mGeolocationEnabled = flag; - } + mGeolocationEnabled = flag; } } @@ -1720,9 +1710,7 @@ public void setDisabledActionModeMenuItems(int menuItems) { synchronized (mAwSettingsLock) { - if (menuItems != mDisabledMenuItems) { - mDisabledMenuItems = menuItems; - } + mDisabledMenuItems = menuItems; } }
diff --git a/android_webview/lib/main/aw_main_delegate.cc b/android_webview/lib/main/aw_main_delegate.cc index b76b9fe0..b9dc2490 100644 --- a/android_webview/lib/main/aw_main_delegate.cc +++ b/android_webview/lib/main/aw_main_delegate.cc
@@ -11,7 +11,6 @@ #include "android_webview/browser/browser_view_renderer.h" #include "android_webview/browser/command_line_helper.h" #include "android_webview/browser/deferred_gpu_command_service.h" -#include "android_webview/browser/scoped_allow_wait_for_legacy_web_view_api.h" #include "android_webview/common/aw_descriptors.h" #include "android_webview/common/aw_paths.h" #include "android_webview/common/aw_switches.h" @@ -55,14 +54,6 @@ namespace android_webview { -namespace { - -// TODO(boliu): Remove this global Allow once the underlying issues are -// resolved - http://crbug.com/240453. See AwMainDelegate::RunProcess below. -base::LazyInstance<std::unique_ptr<ScopedAllowWaitForLegacyWebViewApi>>:: - DestructorAtExit g_allow_wait_in_ui_thread = LAZY_INSTANCE_INITIALIZER; -} - AwMainDelegate::AwMainDelegate() { } @@ -238,9 +229,6 @@ crash_reporter::AddGpuFingerprintToMicrodumpCrashHandler( content_client_.gpu_fingerprint()); - g_allow_wait_in_ui_thread.Get().reset( - new ScopedAllowWaitForLegacyWebViewApi); - // Return 0 so that we do NOT trigger the default behavior. On Android, the // UI message loop is managed by the Java application. return 0;
diff --git a/android_webview/native/cookie_manager.cc b/android_webview/native/cookie_manager.cc index e5e66684..fc75336 100644 --- a/android_webview/native/cookie_manager.cc +++ b/android_webview/native/cookie_manager.cc
@@ -11,7 +11,6 @@ #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/scoped_allow_wait_for_legacy_web_view_api.h" #include "base/android/jni_string.h" #include "base/android/path_utils.h" #include "base/bind.h" @@ -148,6 +147,8 @@ } } +} // namespace + // CookieManager creates and owns Webview's CookieStore, in addition to handling // calls into the CookieStore from Java. // @@ -232,9 +233,9 @@ DISALLOW_COPY_AND_ASSIGN(CookieManager); }; +namespace { base::LazyInstance<CookieManager>::Leaky g_lazy_instance; - -} // namespace +} // static CookieManager* CookieManager::GetInstance() { @@ -271,7 +272,7 @@ base::WaitableEvent::InitialState::NOT_SIGNALED); ExecCookieTask( base::Bind(task, BoolCallbackAdapter(SignalEventClosure(&completion)))); - ScopedAllowWaitForLegacyWebViewApi wait; + base::ThreadRestrictions::ScopedAllowWait wait; completion.Wait(); } @@ -282,7 +283,7 @@ base::WaitableEvent::InitialState::NOT_SIGNALED); ExecCookieTask( base::Bind(task, IntCallbackAdapter(SignalEventClosure(&completion)))); - ScopedAllowWaitForLegacyWebViewApi wait; + base::ThreadRestrictions::ScopedAllowWait wait; completion.Wait(); } @@ -293,7 +294,7 @@ WaitableEvent completion(base::WaitableEvent::ResetPolicy::AUTOMATIC, base::WaitableEvent::InitialState::NOT_SIGNALED); ExecCookieTask(base::Bind(task, SignalEventClosure(&completion))); - ScopedAllowWaitForLegacyWebViewApi wait; + base::ThreadRestrictions::ScopedAllowWait wait; completion.Wait(); }
diff --git a/android_webview/renderer/aw_content_renderer_client.cc b/android_webview/renderer/aw_content_renderer_client.cc index a99d8bc..30aac4c 100644 --- a/android_webview/renderer/aw_content_renderer_client.cc +++ b/android_webview/renderer/aw_content_renderer_client.cc
@@ -170,6 +170,10 @@ autofill::PasswordAutofillAgent* password_autofill_agent = new autofill::PasswordAutofillAgent(render_frame); new autofill::AutofillAgent(render_frame, password_autofill_agent, NULL); + +#if BUILDFLAG(ENABLE_SPELLCHECK) + new SpellCheckProvider(render_frame, spellcheck_.get()); +#endif } void AwContentRendererClient::RenderViewCreated( @@ -177,7 +181,13 @@ AwRenderViewExt::RenderViewCreated(render_view); #if BUILDFLAG(ENABLE_SPELLCHECK) - new SpellCheckProvider(render_view, spellcheck_.get()); + // This is a workaround keeping the behavior that, the Blink side spellcheck + // enabled state is initialized on RenderView creation. + // TODO(xiaochengh): Design better way to sync between Chrome-side and + // Blink-side spellcheck enabled states. See crbug.com/710097. + if (SpellCheckProvider* provider = + SpellCheckProvider::Get(render_view->GetMainRenderFrame())) + provider->EnableSpellcheck(spellcheck_->IsSpellcheckEnabled()); #endif }
diff --git a/ash/BUILD.gn b/ash/BUILD.gn index c2789a9..7fd1372 100644 --- a/ash/BUILD.gn +++ b/ash/BUILD.gn
@@ -1462,6 +1462,7 @@ "//ash/strings:ash_test_strings", "//ash/resources:ash_test_resources_100_percent", "//ash/resources:ash_test_resources_200_percent", + "//testing/buildbot/filters:ash_unittests_filters", ] if (!use_x11) {
diff --git a/ash/laser/laser_pointer_view.cc b/ash/laser/laser_pointer_view.cc index aa39b88..82757635 100644 --- a/ash/laser/laser_pointer_view.cc +++ b/ash/laser/laser_pointer_view.cc
@@ -211,14 +211,15 @@ frame_sink_id_(aura::Env::GetInstance() ->context_factory_private() ->AllocateFrameSinkId()), - frame_sink_support_(this, - aura::Env::GetInstance() - ->context_factory_private() - ->GetSurfaceManager(), - frame_sink_id_, - false /* is_root */, - true /* handles_frame_sink_id_invalidation */, - true /* needs_sync_points */), + frame_sink_support_(cc::CompositorFrameSinkSupport::Create( + this, + aura::Env::GetInstance() + ->context_factory_private() + ->GetSurfaceManager(), + frame_sink_id_, + false /* is_root */, + true /* handles_frame_sink_id_invalidation */, + true /* needs_sync_points */)), weak_ptr_factory_(this) { widget_.reset(new views::Widget); views::Widget::InitParams params; @@ -378,25 +379,28 @@ } void LaserPointerView::SetNeedsBeginFrame(bool needs_begin_frame) { - frame_sink_support_.SetNeedsBeginFrame(needs_begin_frame); + frame_sink_support_->SetNeedsBeginFrame(needs_begin_frame); } void LaserPointerView::SubmitCompositorFrame( const cc::LocalSurfaceId& local_surface_id, cc::CompositorFrame frame) { - frame_sink_support_.SubmitCompositorFrame(local_surface_id, std::move(frame)); + frame_sink_support_->SubmitCompositorFrame(local_surface_id, + std::move(frame)); } void LaserPointerView::BeginFrameDidNotSwap( const cc::BeginFrameAck& begin_frame_ack) { - frame_sink_support_.BeginFrameDidNotSwap(begin_frame_ack); + frame_sink_support_->BeginFrameDidNotSwap(begin_frame_ack); } void LaserPointerView::EvictFrame() { - frame_sink_support_.EvictFrame(); + frame_sink_support_->EvictFrame(); } -void LaserPointerView::DidReceiveCompositorFrameAck() { +void LaserPointerView::DidReceiveCompositorFrameAck( + const cc::ReturnedResourceArray& resources) { + ReclaimResources(resources); base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::Bind(&LaserPointerView::OnDidDrawSurface, weak_ptr_factory_.GetWeakPtr()));
diff --git a/ash/laser/laser_pointer_view.h b/ash/laser/laser_pointer_view.h index 54221c4d..8b4bbc8 100644 --- a/ash/laser/laser_pointer_view.h +++ b/ash/laser/laser_pointer_view.h
@@ -63,7 +63,8 @@ void EvictFrame() override; // Overridden from cc::CompositorFrameSinkSupportClient: - void DidReceiveCompositorFrameAck() override; + void DidReceiveCompositorFrameAck( + const cc::ReturnedResourceArray& resources) override; void OnBeginFrame(const cc::BeginFrameArgs& args) override {} void ReclaimResources(const cc::ReturnedResourceArray& resources) override; void WillDrawSurface(const cc::LocalSurfaceId& local_surface_id, @@ -91,7 +92,7 @@ bool needs_update_surface_ = false; bool pending_draw_surface_ = false; const cc::FrameSinkId frame_sink_id_; - cc::CompositorFrameSinkSupport frame_sink_support_; + std::unique_ptr<cc::CompositorFrameSinkSupport> frame_sink_support_; cc::LocalSurfaceId local_surface_id_; cc::LocalSurfaceIdAllocator id_allocator_; int next_resource_id_ = 1;
diff --git a/ash/system/palette/palette_utils.cc b/ash/system/palette/palette_utils.cc index 9f65d72..7181d6c 100644 --- a/ash/system/palette/palette_utils.cc +++ b/ash/system/palette/palette_utils.cc
@@ -11,7 +11,6 @@ #include "ash/system/status_area_widget.h" #include "ash/wm_window.h" #include "base/command_line.h" -#include "base/sys_info.h" #include "ui/events/devices/input_device_manager.h" #include "ui/events/devices/touchscreen_device.h" #include "ui/gfx/geometry/point.h" @@ -19,18 +18,6 @@ namespace ash { namespace palette_utils { -namespace { -// Pyro firmware currently reports it has a stylus but it does not. -// TODO(jdufault): Remove this once firmware is fixed. See b/36367810. -const char* kBlacklistedDevices[] = {"pyro"}; - -bool IsBlacklisted(const std::string& name) { - return std::find(std::begin(kBlacklistedDevices), - std::end(kBlacklistedDevices), - name) != std::end(kBlacklistedDevices); -} -} // namespace - bool HasStylusInput() { // Allow the user to force enable or disable by passing a switch. If both are // present, enabling takes precedence over disabling. @@ -39,10 +26,6 @@ return true; } - // Disable stylus for any blacklisted devices. - if (IsBlacklisted(base::SysInfo::GetLsbReleaseBoard())) - return false; - // Check to see if the hardware reports it is stylus capable. for (const ui::TouchscreenDevice& device : ui::InputDeviceManager::GetInstance()->GetTouchscreenDevices()) {
diff --git a/base/allocator/partition_allocator/address_space_randomization.cc b/base/allocator/partition_allocator/address_space_randomization.cc index ca9efdd8..d54fb44 100644 --- a/base/allocator/partition_allocator/address_space_randomization.cc +++ b/base/allocator/partition_allocator/address_space_randomization.cc
@@ -16,6 +16,11 @@ #include <unistd.h> #endif +// VersionHelpers.h must be included after windows.h. +#if defined(OS_WIN) +#include <VersionHelpers.h> +#endif + namespace base { namespace { @@ -92,7 +97,13 @@ #if defined(OS_WIN) random &= 0x3ffffffffffUL; // Windows >= 8.1 has the full 47 bits. Use them where available. - if (base::win::GetVersion() < base::win::Version::VERSION_WIN8_1) { + static bool windows_81 = false; + static bool windows_81_initialized = false; + if (!windows_81_initialized) { + windows_81 = IsWindows8Point1OrGreater(); + windows_81_initialized = true; + } + if (!windows_81) { random += 0x10000000000UL; } #elif defined(MEMORY_TOOL_REPLACES_ALLOCATOR)
diff --git a/base/files/file_util_unittest.cc b/base/files/file_util_unittest.cc index 84a7a45..2d95be4 100644 --- a/base/files/file_util_unittest.cc +++ b/base/files/file_util_unittest.cc
@@ -2212,7 +2212,8 @@ FilePath foobar(data_dir.Append(FILE_PATH_LITERAL("foobar.txt"))); std::string data("hello"); - ASSERT_TRUE(WriteFile(foobar, data.c_str(), data.length())); + ASSERT_EQ(static_cast<int>(data.length()), + WriteFile(foobar, data.c_str(), data.length())); Time access_time; // This timestamp is divisible by one day (in local timezone), @@ -2247,7 +2248,8 @@ FilePath foo(empty_dir.Append(FILE_PATH_LITERAL("foo.txt"))); std::string bar("baz"); - ASSERT_TRUE(WriteFile(foo, bar.c_str(), bar.length())); + ASSERT_EQ(static_cast<int>(bar.length()), + WriteFile(foo, bar.c_str(), bar.length())); EXPECT_FALSE(IsDirectoryEmpty(empty_dir)); }
diff --git a/base/task_scheduler/task_tracker_unittest.cc b/base/task_scheduler/task_tracker_unittest.cc index 1c9b0a8..e1596f7 100644 --- a/base/task_scheduler/task_tracker_unittest.cc +++ b/base/task_scheduler/task_tracker_unittest.cc
@@ -43,7 +43,7 @@ namespace { -constexpr size_t kLoadTestNumIterations = 100; +constexpr size_t kLoadTestNumIterations = 75; // Invokes a closure asynchronously. class CallbackThread : public SimpleThread {
diff --git a/base/threading/thread_restrictions.h b/base/threading/thread_restrictions.h index 8f3beb1..1296edd 100644 --- a/base/threading/thread_restrictions.h +++ b/base/threading/thread_restrictions.h
@@ -12,7 +12,10 @@ class BrowserProcessImpl; class HistogramSynchronizer; class NativeBackendKWallet; -class ScopedAllowWaitForLegacyWebViewApi; + +namespace android_webview { +class CookieManager; +} namespace cc { class CompletionEvent; @@ -37,6 +40,9 @@ class ScopedAllowWaitForAndroidLayoutTests; class ScopedAllowWaitForDebugURL; class SoftwareOutputDeviceMus; +class SynchronousCompositor; +class SynchronousCompositorBrowserFilter; +class SynchronousCompositorHost; class TextInputClientMac; class CategorizedWorkerPool; } // namespace content @@ -174,15 +180,18 @@ private: // DO NOT ADD ANY OTHER FRIEND STATEMENTS, talk to jam or brettw first. // BEGIN ALLOWED USAGE. + friend class android_webview::CookieManager; friend class content::BrowserShutdownProfileDumper; friend class content::BrowserSurfaceViewManager; friend class content::BrowserTestBase; friend class content::NestedMessagePumpAndroid; friend class content::ScopedAllowWaitForAndroidLayoutTests; friend class content::ScopedAllowWaitForDebugURL; + friend class content::SynchronousCompositor; + friend class content::SynchronousCompositorBrowserFilter; + friend class content::SynchronousCompositorHost; friend class ::HistogramSynchronizer; friend class internal::TaskTracker; - friend class ::ScopedAllowWaitForLegacyWebViewApi; friend class cc::CompletionEvent; friend class cc::SingleThreadTaskGraphRunner; friend class content::CategorizedWorkerPool;
diff --git a/build/android/incremental_install/README.md b/build/android/incremental_install/README.md new file mode 100644 index 0000000..0916e07 --- /dev/null +++ b/build/android/incremental_install/README.md
@@ -0,0 +1,81 @@ +# Incremental Install + +Incremental Install is a way of building & deploying an APK that tries to +minimize the time it takes to make a change and see that change running on +device. They work best with `is_component_build=true`, and do *not* require a +rooted device. + +## Building + +**Option 1:** Add the gn arg: + + incremental_apk_by_default = true + +This causes all apks to be built as incremental (except for blacklisted ones). + +**Option 2:** Add `_incremental` to the apk target name. E.g.: + + ninja -C out/Debug chrome_public_apk_incremental + ninja -C out/Debug chrome_public_test_apk_incremental + +## Running + +It is not enough to `adb install` them. You must use a generated wrapper script: + + out/Debug/bin/install_chrome_public_apk_incremental + out/Debug/bin/run_chrome_public_test_apk_incremental # Automatically sets --fast-local-dev + +## Caveats + +Isolated processes (on L+) are incompatible with incremental install. As a +work-around, you can disable isolated processes only for incremental apks using +gn arg: + + disable_incremental_isolated_processes = true + +# How it Works + +## Overview + +The basic idea is to side-load .dex and .so files to `/data/local/tmp` rather +than bundling them in the .apk. Then, when making a change, only the changed +.dex / .so needs to be pushed to the device. + +Faster Builds: + + * No `final_dex` step (where all .dex files are merged into one) + * No need to rebuild .apk for code-only changes (but required for resources) + * Apks sign faster because they are smaller. + +Faster Installs: + + * The .apk is smaller, and so faster to verify. + * No need to run `adb install` for code-only changes. + * Only changed .so / .dex files are pushed. MD5s of existing on-device files + are cached on host computer. + +Slower Initial Runs: + + * The first time you run an incremental .apk, the `DexOpt` needs to run on all + .dex files. This step is normally done during `adb install`, but is done on + start-up for incremental apks. + * DexOpt results are cached, so subsequent runs are much faster + +## The Code + +All incremental apks have the same classes.dex, which is built from: + + //build/android/incremental_install:bootstrap_java + +They also have a transformed `AndroidManifest.xml`, which overrides the the +main application class and any instrumentation classes so that they instead +point to `BootstrapApplication`. This is built by: + + //build/android/incremental_install/generate_android_manifest.py + +Wrapper scripts and install logic is contained in: + + //build/android/incremental_install/create_install_script.py + //build/android/incremental_install/installer.py + +Finally, GN logic for incremental apks is sprinkled throughout.
diff --git a/build/android/lint/suppressions.xml b/build/android/lint/suppressions.xml index 0abc2963..b020fe1 100644 --- a/build/android/lint/suppressions.xml +++ b/build/android/lint/suppressions.xml
@@ -426,7 +426,7 @@ </issue> <issue id="UselessParent"> <ignore regexp="android_webview/tools/system_webview_shell/apk/res/layout/activity_webview_browser.xml"/> - <ignore regexp="chrome/android/java/res/layout/data_reduction_promo_screen.xml"/> + <ignore regexp="chrome/android/java/res/layout/data_usage_breakdown.xml"/> <ignore regexp="chromecast/internal"/> <ignore regexp="tools/android/kerberos/SpnegoAuthenticator/res/layout/activity_account_authenticator.xml"/> </issue>
diff --git a/build/config/chromecast/BUILD.gn b/build/config/chromecast/BUILD.gn index 60cb52c..3c99eba 100644 --- a/build/config/chromecast/BUILD.gn +++ b/build/config/chromecast/BUILD.gn
@@ -7,20 +7,22 @@ assert(is_chromecast) config("static_config") { - ldflags = [ - # Don't allow visible symbols from libraries that contain - # assembly code with symbols that aren't hidden properly. - # http://b/26390825 - "-Wl,--exclude-libs=libffmpeg.a", - ] - - if (!is_android) { - ldflags += [ - # We want to statically link libstdc++/libgcc on Linux. - # (On Android, libstdc++ and libgcc aren't used.) - "-static-libstdc++", - "-static-libgcc", + if (!is_clang) { + ldflags = [ + # Don't allow visible symbols from libraries that contain + # assembly code with symbols that aren't hidden properly. + # http://b/26390825 + "-Wl,--exclude-libs=libffmpeg.a", ] + + if (!is_android) { + ldflags += [ + # We want to statically link libstdc++/libgcc on Linux. + # (On Android, libstdc++ and libgcc aren't used.) + "-static-libstdc++", + "-static-libgcc", + ] + } } } @@ -75,7 +77,7 @@ config("shared_library_config") { configs = [ ":ldconfig" ] - if (!is_clang && current_cpu == "arm") { + if (current_cpu == "arm") { configs += [ ":static_config" ] } }
diff --git a/build/toolchain/win/setup_toolchain.py b/build/toolchain/win/setup_toolchain.py index e0fcb273..e8b0849 100644 --- a/build/toolchain/win/setup_toolchain.py +++ b/build/toolchain/win/setup_toolchain.py
@@ -139,7 +139,10 @@ raise Exception('%s is missing - make sure VC++ tools are installed.' % script_path) script_path = other_path - args = [script_path, 'amd64_x86' if cpu == 'x86' else 'amd64'] + # Chromium requires the 10.0.14393.0 SDK. Previous versions don't have all + # of the required declarations, and 10.0.15063.0 is buggy. + args = [script_path, 'amd64_x86' if cpu == 'x86' else 'amd64', + '10.0.14393.0'] variables = _LoadEnvFromBat(args) return _ExtractImportantEnvironment(variables)
diff --git a/cc/benchmarks/invalidation_benchmark.cc b/cc/benchmarks/invalidation_benchmark.cc index 6a61522..c44a157 100644 --- a/cc/benchmarks/invalidation_benchmark.cc +++ b/cc/benchmarks/invalidation_benchmark.cc
@@ -72,7 +72,7 @@ void InvalidationBenchmark::RunOnLayer(PictureLayer* layer) { gfx::Rect visible_layer_rect = gfx::Rect(layer->bounds()); gfx::Transform from_screen; - bool invertible = layer->screen_space_transform().GetInverse(&from_screen); + bool invertible = layer->ScreenSpaceTransform().GetInverse(&from_screen); if (!invertible) from_screen = gfx::Transform(); gfx::Rect viewport_rect = MathUtil::ProjectEnclosingClippedRect(
diff --git a/cc/blink/web_layer_impl_fixed_bounds_unittest.cc b/cc/blink/web_layer_impl_fixed_bounds_unittest.cc index 20993b3..3dd88c1 100644 --- a/cc/blink/web_layer_impl_fixed_bounds_unittest.cc +++ b/cc/blink/web_layer_impl_fixed_bounds_unittest.cc
@@ -70,10 +70,10 @@ void ExpectEqualLayerRectsInTarget(cc::Layer* layer1, cc::Layer* layer2) { gfx::RectF layer1_rect_in_target(gfx::SizeF(layer1->bounds())); - layer1->screen_space_transform().TransformRect(&layer1_rect_in_target); + layer1->ScreenSpaceTransform().TransformRect(&layer1_rect_in_target); gfx::RectF layer2_rect_in_target(gfx::SizeF(layer2->bounds())); - layer2->screen_space_transform().TransformRect(&layer2_rect_in_target); + layer2->ScreenSpaceTransform().TransformRect(&layer2_rect_in_target); EXPECT_FLOAT_RECT_EQ(layer1_rect_in_target, layer2_rect_in_target); }
diff --git a/cc/ipc/mojo_compositor_frame_sink.mojom b/cc/ipc/mojo_compositor_frame_sink.mojom index fd50bb1..1ad4ae1 100644 --- a/cc/ipc/mojo_compositor_frame_sink.mojom +++ b/cc/ipc/mojo_compositor_frame_sink.mojom
@@ -52,7 +52,7 @@ // TODO(fsamuel): This method ought not be necessary with unified BeginFrame. // However, there's a fair amount of cleanup and refactoring necessary to get // rid of it. - DidReceiveCompositorFrameAck(); + DidReceiveCompositorFrameAck(ReturnedResourceArray resources); // Notification for the client to generate a CompositorFrame. OnBeginFrame(BeginFrameArgs args);
diff --git a/cc/layers/layer.cc b/cc/layers/layer.cc index 4af2f0a5..b8e2a85 100644 --- a/cc/layers/layer.cc +++ b/cc/layers/layer.cc
@@ -1443,7 +1443,7 @@ ->num_copy_requests_in_subtree; } -gfx::Transform Layer::screen_space_transform() const { +gfx::Transform Layer::ScreenSpaceTransform() const { DCHECK_NE(transform_tree_index_, TransformTree::kInvalidNodeId); return draw_property_utils::ScreenSpaceTransform( this, layer_tree_host_->property_trees()->transform_tree);
diff --git a/cc/layers/layer.h b/cc/layers/layer.h index e95f744..58dde9c 100644 --- a/cc/layers/layer.h +++ b/cc/layers/layer.h
@@ -202,8 +202,7 @@ return clip_children_.get(); } - // TODO(enne): Fix style here (and everywhere) once LayerImpl does the same. - gfx::Transform screen_space_transform() const; + gfx::Transform ScreenSpaceTransform() const; void set_num_unclipped_descendants(size_t descendants) { num_unclipped_descendants_ = descendants;
diff --git a/cc/layers/surface_layer_impl.cc b/cc/layers/surface_layer_impl.cc index ed5b443a..5acd21efa 100644 --- a/cc/layers/surface_layer_impl.cc +++ b/cc/layers/surface_layer_impl.cc
@@ -73,7 +73,7 @@ if (primary && fallback_surface_info_.id() != primary_surface_info_.id()) { primary->fallback_quad = CreateSurfaceDrawQuad( render_pass, SurfaceDrawQuadType::FALLBACK, fallback_surface_info_, - &append_quads_data->embedded_surfaces); + nullptr /* embedded_surfaces */); } } @@ -121,7 +121,8 @@ render_pass->CreateAndAppendDrawQuad<SurfaceDrawQuad>(); surface_draw_quad->SetNew(shared_quad_state, quad_rect, visible_quad_rect, surface_info.id(), surface_draw_quad_type, nullptr); - embedded_surfaces->push_back(surface_info.id()); + if (embedded_surfaces) + embedded_surfaces->push_back(surface_info.id()); return surface_draw_quad; }
diff --git a/cc/layers/surface_layer_impl_unittest.cc b/cc/layers/surface_layer_impl_unittest.cc index a526a516..5c6f942 100644 --- a/cc/layers/surface_layer_impl_unittest.cc +++ b/cc/layers/surface_layer_impl_unittest.cc
@@ -240,8 +240,8 @@ std::unique_ptr<RenderPass> render_pass = RenderPass::Create(); AppendQuadsData data; surface_layer_impl->AppendQuads(render_pass.get(), &data); - EXPECT_THAT(data.embedded_surfaces, - UnorderedElementsAre(surface_id1, surface_id2)); + // The the primary SurfaceInfo will be added to embedded_surfaces. + EXPECT_THAT(data.embedded_surfaces, UnorderedElementsAre(surface_id1)); ASSERT_EQ(2u, render_pass->quad_list.size()); const SurfaceDrawQuad* surface_draw_quad1 =
diff --git a/cc/output/direct_renderer.cc b/cc/output/direct_renderer.cc index 51eebf4..e9b62d2 100644 --- a/cc/output/direct_renderer.cc +++ b/cc/output/direct_renderer.cc
@@ -408,16 +408,13 @@ if (render_pass_scissor.IsEmpty()) return true; - if (quad.shared_quad_state->is_clipped) { - gfx::Rect r = quad.shared_quad_state->clip_rect; - r.Intersect(render_pass_scissor); - return r.IsEmpty(); - } + gfx::Rect target_rect = MathUtil::MapEnclosingClippedRect( + quad.shared_quad_state->quad_to_target_transform, quad.visible_rect); + if (quad.shared_quad_state->is_clipped) + target_rect.Intersect(quad.shared_quad_state->clip_rect); - gfx::RectF intersection = MathUtil::MapClippedRect( - quad.shared_quad_state->quad_to_target_transform, gfx::RectF(quad.rect)); - intersection.Intersect(gfx::RectF(render_pass_scissor)); - return intersection.IsEmpty(); + target_rect.Intersect(render_pass_scissor); + return target_rect.IsEmpty(); } void DirectRenderer::SetScissorStateForQuad(
diff --git a/cc/output/gl_renderer_unittest.cc b/cc/output/gl_renderer_unittest.cc index 32a29fe..144b574 100644 --- a/cc/output/gl_renderer_unittest.cc +++ b/cc/output/gl_renderer_unittest.cc
@@ -1238,9 +1238,9 @@ DrawFrame(renderer_.get(), viewport_size); } -TEST_F(GLRendererSkipTest, SkipQuadRect) { +TEST_F(GLRendererSkipTest, SkipVisibleRect) { gfx::Size viewport_size(100, 100); - gfx::Rect quad_rect = gfx::Rect(20, 20, 20, 20); + gfx::Rect quad_rect = gfx::Rect(0, 0, 40, 40); int root_pass_id = 1; RenderPass* root_pass = AddRenderPass(&render_passes_in_draw_order_, @@ -1248,11 +1248,15 @@ gfx::Transform(), FilterOperations()); root_pass->damage_rect = gfx::Rect(0, 0, 10, 10); AddQuad(root_pass, quad_rect, SK_ColorGREEN); + root_pass->shared_quad_state_list.front()->is_clipped = true; + root_pass->shared_quad_state_list.front()->clip_rect = + gfx::Rect(0, 0, 40, 40); + root_pass->quad_list.front()->visible_rect = gfx::Rect(20, 20, 20, 20); renderer_->DecideRenderPassAllocationsForFrame(render_passes_in_draw_order_); DrawFrame(renderer_.get(), viewport_size); - // DrawElements should not be called because the quad rect is outside the - // scissor. + // DrawElements should not be called because the visible rect is outside the + // scissor, even though the clip rect and quad rect intersect the scissor. } TEST_F(GLRendererSkipTest, SkipClippedQuads) {
diff --git a/cc/surfaces/compositor_frame_sink_support.cc b/cc/surfaces/compositor_frame_sink_support.cc index 093c5b6..d1227031 100644 --- a/cc/surfaces/compositor_frame_sink_support.cc +++ b/cc/surfaces/compositor_frame_sink_support.cc
@@ -17,25 +17,19 @@ namespace cc { -CompositorFrameSinkSupport::CompositorFrameSinkSupport( +// static +std::unique_ptr<CompositorFrameSinkSupport> CompositorFrameSinkSupport::Create( CompositorFrameSinkSupportClient* client, SurfaceManager* surface_manager, const FrameSinkId& frame_sink_id, bool is_root, bool handles_frame_sink_id_invalidation, - bool needs_sync_points) - : client_(client), - surface_manager_(surface_manager), - frame_sink_id_(frame_sink_id), - surface_factory_(frame_sink_id_, surface_manager_, this), - reference_tracker_(frame_sink_id), - is_root_(is_root), - handles_frame_sink_id_invalidation_(handles_frame_sink_id_invalidation), - weak_factory_(this) { - surface_factory_.set_needs_sync_points(needs_sync_points); - if (handles_frame_sink_id_invalidation_) - surface_manager_->RegisterFrameSinkId(frame_sink_id_); - surface_manager_->RegisterSurfaceFactoryClient(frame_sink_id_, this); + bool needs_sync_points) { + std::unique_ptr<CompositorFrameSinkSupport> support = + base::WrapUnique(new CompositorFrameSinkSupport( + client, frame_sink_id, is_root, handles_frame_sink_id_invalidation)); + support->Init(surface_manager, needs_sync_points); + return support; } CompositorFrameSinkSupport::~CompositorFrameSinkSupport() { @@ -52,7 +46,7 @@ // SurfaceFactory's destructor will attempt to return resources which will // call back into here and access |client_| so we should destroy // |surface_factory_|'s resources early on. - surface_factory_.EvictSurface(); + surface_factory_->EvictSurface(); surface_manager_->UnregisterSurfaceFactoryClient(frame_sink_id_); if (handles_frame_sink_id_invalidation_) surface_manager_->InvalidateFrameSinkId(frame_sink_id_); @@ -60,8 +54,7 @@ void CompositorFrameSinkSupport::ReferencedSurfacesChanged( const LocalSurfaceId& local_surface_id, - const std::vector<SurfaceId>* active_referenced_surfaces, - const std::vector<SurfaceId>* pending_referenced_surfaces) { + const std::vector<SurfaceId>* active_referenced_surfaces) { if (!surface_manager_->using_surface_references()) return; @@ -72,8 +65,7 @@ // surface references includes references from both the pending and active // frame if any. reference_tracker_.UpdateReferences(local_surface_id, - active_referenced_surfaces, - pending_referenced_surfaces); + active_referenced_surfaces); UpdateSurfaceReferences(last_surface_id, local_surface_id); } @@ -110,7 +102,8 @@ } void CompositorFrameSinkSupport::EvictFrame() { - surface_factory_.EvictSurface(); + DCHECK(surface_factory_); + surface_factory_->EvictSurface(); } void CompositorFrameSinkSupport::SetNeedsBeginFrame(bool needs_begin_frame) { @@ -137,6 +130,7 @@ void CompositorFrameSinkSupport::SubmitCompositorFrame( const LocalSurfaceId& local_surface_id, CompositorFrame frame) { + DCHECK(surface_factory_); ++ack_pending_count_; if (frame.metadata.begin_frame_ack.sequence_number < @@ -150,7 +144,7 @@ frame.metadata.begin_frame_ack.has_damage = true; BeginFrameAck ack = frame.metadata.begin_frame_ack; - surface_factory_.SubmitCompositorFrame( + surface_factory_->SubmitCompositorFrame( local_surface_id, std::move(frame), base::Bind(&CompositorFrameSinkSupport::DidReceiveCompositorFrameAck, weak_factory_.GetWeakPtr())); @@ -212,21 +206,15 @@ void CompositorFrameSinkSupport::DidReceiveCompositorFrameAck() { DCHECK_GT(ack_pending_count_, 0); ack_pending_count_--; - if (!client_) return; - - // We return the resources before sending an ack so they can be reused in - // making the next CompositorFrame. - if (!surface_returned_resources_.empty()) { - client_->ReclaimResources(surface_returned_resources_); - surface_returned_resources_.clear(); - } - client_->DidReceiveCompositorFrameAck(); + client_->DidReceiveCompositorFrameAck(surface_returned_resources_); + surface_returned_resources_.clear(); } void CompositorFrameSinkSupport::ForceReclaimResources() { - surface_factory_.ClearSurface(); + DCHECK(surface_factory_); + surface_factory_->ClearSurface(); } void CompositorFrameSinkSupport::ClaimTemporaryReference( @@ -234,6 +222,29 @@ surface_manager_->AssignTemporaryReference(surface_id, frame_sink_id_); } +CompositorFrameSinkSupport::CompositorFrameSinkSupport( + CompositorFrameSinkSupportClient* client, + const FrameSinkId& frame_sink_id, + bool is_root, + bool handles_frame_sink_id_invalidation) + : client_(client), + frame_sink_id_(frame_sink_id), + reference_tracker_(frame_sink_id), + is_root_(is_root), + handles_frame_sink_id_invalidation_(handles_frame_sink_id_invalidation), + weak_factory_(this) {} + +void CompositorFrameSinkSupport::Init(SurfaceManager* surface_manager, + bool needs_sync_points) { + surface_manager_ = surface_manager; + surface_factory_ = + base::MakeUnique<SurfaceFactory>(frame_sink_id_, surface_manager_, this); + if (handles_frame_sink_id_invalidation_) + surface_manager_->RegisterFrameSinkId(frame_sink_id_); + surface_manager_->RegisterSurfaceFactoryClient(frame_sink_id_, this); + surface_factory_->set_needs_sync_points(needs_sync_points); +} + void CompositorFrameSinkSupport::OnBeginFrame(const BeginFrameArgs& args) { UpdateNeedsBeginFramesInternal(); last_begin_frame_args_ = args; @@ -264,7 +275,8 @@ void CompositorFrameSinkSupport::RequestCopyOfSurface( std::unique_ptr<CopyOutputRequest> request) { - surface_factory_.RequestCopyOfSurface(std::move(request)); + DCHECK(surface_factory_); + surface_factory_->RequestCopyOfSurface(std::move(request)); } } // namespace cc
diff --git a/cc/surfaces/compositor_frame_sink_support.h b/cc/surfaces/compositor_frame_sink_support.h index d3d3cbbe..977acdf 100644 --- a/cc/surfaces/compositor_frame_sink_support.h +++ b/cc/surfaces/compositor_frame_sink_support.h
@@ -28,19 +28,20 @@ : public SurfaceFactoryClient, public BeginFrameObserver { public: - CompositorFrameSinkSupport(CompositorFrameSinkSupportClient* client, - SurfaceManager* surface_manager, - const FrameSinkId& frame_sink_id, - bool is_root, - bool handles_frame_sink_id_invalidation, - bool needs_sync_points); + static std::unique_ptr<CompositorFrameSinkSupport> Create( + CompositorFrameSinkSupportClient* client, + SurfaceManager* surface_manager, + const FrameSinkId& frame_sink_id, + bool is_root, + bool handles_frame_sink_id_invalidation, + bool needs_sync_points); ~CompositorFrameSinkSupport() override; const FrameSinkId& frame_sink_id() const { return frame_sink_id_; } Surface* current_surface_for_testing() { - return surface_factory_.current_surface_for_testing(); + return surface_factory_->current_surface_for_testing(); } const ReferencedSurfaceTracker& ReferenceTrackerForTesting() const { @@ -50,8 +51,7 @@ // SurfaceFactoryClient implementation. void ReferencedSurfacesChanged( const LocalSurfaceId& local_surface_id, - const std::vector<SurfaceId>* active_referenced_surfaces, - const std::vector<SurfaceId>* pending_referenced_surfaces) override; + const std::vector<SurfaceId>* active_referenced_surfaces) override; void ReturnResources(const ReturnedResourceArray& resources) override; void SetBeginFrameSource(BeginFrameSource* begin_frame_source) override; void WillDrawSurface(const LocalSurfaceId& local_surface_id, @@ -66,6 +66,14 @@ void ForceReclaimResources(); void ClaimTemporaryReference(const SurfaceId& surface_id); + protected: + CompositorFrameSinkSupport(CompositorFrameSinkSupportClient* client, + const FrameSinkId& frame_sink_id, + bool is_root, + bool handles_frame_sink_id_invalidation); + + void Init(SurfaceManager* surface_manager, bool needs_sync_points); + private: // Update surface references with SurfaceManager for current CompositorFrame // that has |local_surface_id|. UpdateReferences() must be called on @@ -88,11 +96,11 @@ CompositorFrameSinkSupportClient* const client_; - SurfaceManager* const surface_manager_; + SurfaceManager* surface_manager_ = nullptr; const FrameSinkId frame_sink_id_; - SurfaceFactory surface_factory_; + std::unique_ptr<SurfaceFactory> surface_factory_; // Counts the number of CompositorFrames that have been submitted and have not // yet received an ACK. int ack_pending_count_ = 0;
diff --git a/cc/surfaces/compositor_frame_sink_support_client.h b/cc/surfaces/compositor_frame_sink_support_client.h index 905f6db..4fd3786 100644 --- a/cc/surfaces/compositor_frame_sink_support_client.h +++ b/cc/surfaces/compositor_frame_sink_support_client.h
@@ -26,7 +26,8 @@ // TODO(fsamuel): This method ought not be necessary with unified BeginFrame. // However, there's a fair amount of cleanup and refactoring necessary to get // rid of it. - virtual void DidReceiveCompositorFrameAck() = 0; + virtual void DidReceiveCompositorFrameAck( + const ReturnedResourceArray& resources) = 0; // Notification for the client to generate a CompositorFrame. virtual void OnBeginFrame(const BeginFrameArgs& args) = 0;
diff --git a/cc/surfaces/compositor_frame_sink_support_unittest.cc b/cc/surfaces/compositor_frame_sink_support_unittest.cc index 319471a..90ce105 100644 --- a/cc/surfaces/compositor_frame_sink_support_unittest.cc +++ b/cc/surfaces/compositor_frame_sink_support_unittest.cc
@@ -21,7 +21,7 @@ using testing::SizeIs; using testing::Invoke; using testing::_; -using testing::InSequence; +using testing::Eq; namespace cc { namespace test { @@ -41,6 +41,10 @@ .WillByDefault(Invoke( this, &MockCompositorFrameSinkSupportClient::ReclaimResourcesInternal)); + ON_CALL(*this, DidReceiveCompositorFrameAck(_)) + .WillByDefault(Invoke( + this, + &MockCompositorFrameSinkSupportClient::ReclaimResourcesInternal)); } ReturnedResourceArray& last_returned_resources() { @@ -48,7 +52,8 @@ } // CompositorFrameSinkSupportClient implementation. - MOCK_METHOD0(DidReceiveCompositorFrameAck, void()); + MOCK_METHOD1(DidReceiveCompositorFrameAck, + void(const ReturnedResourceArray&)); MOCK_METHOD1(OnBeginFrame, void(const BeginFrameArgs&)); MOCK_METHOD1(ReclaimResources, void(const ReturnedResourceArray&)); MOCK_METHOD2(WillDrawSurface, void(const LocalSurfaceId&, const gfx::Rect&)); @@ -180,27 +185,27 @@ // testing::Test: void SetUp() override { testing::Test::SetUp(); + constexpr bool is_root = true; + constexpr bool is_child_root = false; + constexpr bool handles_frame_sink_id_invalidation = true; + constexpr bool needs_sync_points = true; begin_frame_source_ = base::MakeUnique<FakeExternalBeginFrameSource>(0.f, false); surface_manager_.SetDependencyTracker( base::MakeUnique<SurfaceDependencyTracker>(&surface_manager_, begin_frame_source_.get())); - supports_.push_back(base::MakeUnique<CompositorFrameSinkSupport>( - &support_client_, &surface_manager_, kDisplayFrameSink, - true /* is_root */, true /* handles_frame_sink_id_invalidation */, - true /* needs_sync_points */)); - supports_.push_back(base::MakeUnique<CompositorFrameSinkSupport>( - &support_client_, &surface_manager_, kParentFrameSink, - false /* is_root */, true /* handles_frame_sink_id_invalidation */, - true /* needs_sync_points */)); - supports_.push_back(base::MakeUnique<CompositorFrameSinkSupport>( - &support_client_, &surface_manager_, kChildFrameSink1, - false /* is_root */, true /* handles_frame_sink_id_invalidation */, - true /* needs_sync_points */)); - supports_.push_back(base::MakeUnique<CompositorFrameSinkSupport>( - &support_client_, &surface_manager_, kChildFrameSink2, - false /* is_root */, true /* handles_frame_sink_id_invalidation */, - true /* needs_sync_points */)); + supports_.push_back(CompositorFrameSinkSupport::Create( + &support_client_, &surface_manager_, kDisplayFrameSink, is_root, + handles_frame_sink_id_invalidation, needs_sync_points)); + supports_.push_back(CompositorFrameSinkSupport::Create( + &support_client_, &surface_manager_, kParentFrameSink, is_child_root, + handles_frame_sink_id_invalidation, needs_sync_points)); + supports_.push_back(CompositorFrameSinkSupport::Create( + &support_client_, &surface_manager_, kChildFrameSink1, is_child_root, + handles_frame_sink_id_invalidation, needs_sync_points)); + supports_.push_back(CompositorFrameSinkSupport::Create( + &support_client_, &surface_manager_, kChildFrameSink2, is_child_root, + handles_frame_sink_id_invalidation, needs_sync_points)); // Normally, the BeginFrameSource would be registered by the Display. We // register it here so that BeginFrames are received by the display support, @@ -239,9 +244,8 @@ const SurfaceId display_id_second = MakeSurfaceId(kDisplayFrameSink, 2); // Submit a CompositorFrame for the first display root surface. - display_support().SubmitCompositorFrame( - display_id_first.local_surface_id(), - MakeCompositorFrame({MakeSurfaceId(kParentFrameSink, 1)})); + display_support().SubmitCompositorFrame(display_id_first.local_surface_id(), + MakeCompositorFrame()); // A surface reference from the top-level root is added and there shouldn't be // a temporary reference. @@ -250,9 +254,8 @@ UnorderedElementsAre(display_id_first)); // Submit a CompositorFrame for the second display root surface. - display_support().SubmitCompositorFrame( - display_id_second.local_surface_id(), - MakeCompositorFrame({MakeSurfaceId(kParentFrameSink, 2)})); + display_support().SubmitCompositorFrame(display_id_second.local_surface_id(), + MakeCompositorFrame()); // A surface reference from the top-level root to |display_id_second| should // be added and the reference to |display_root_first| removed. @@ -528,52 +531,60 @@ EXPECT_THAT(parent_surface()->blocking_surfaces(), IsEmpty()); } -// This test verifies that the set of references from a Surface includes both -// the pending and active CompositorFrames. +// This test verifies that a pending CompositorFrame does not affect surface +// references. A new surface from a child will continue to exist as a temporary +// reference until the parent's frame activates. TEST_F(CompositorFrameSinkSupportTest, - DisplayCompositorLockingReferencesFromPendingAndActiveFrames) { + OnlyActiveFramesAffectSurfaceReferences) { const SurfaceId parent_id = MakeSurfaceId(kParentFrameSink, 1); - const SurfaceId child_id = MakeSurfaceId(kChildFrameSink1, 1); - const SurfaceId arbitrary_id = MakeSurfaceId(kArbitraryFrameSink, 1); - const SurfaceReference parent_child_reference(parent_id, child_id); - const SurfaceReference parent_arbitrary_reference(parent_id, arbitrary_id); + const SurfaceId child_id1 = MakeSurfaceId(kChildFrameSink1, 1); + const SurfaceId child_id2 = MakeSurfaceId(kChildFrameSink2, 1); // child_support1 submits a CompositorFrame without any dependencies. - child_support1().SubmitCompositorFrame( - child_id.local_surface_id(), MakeCompositorFrame(empty_surface_ids())); + child_support1().SubmitCompositorFrame(child_id1.local_surface_id(), + MakeCompositorFrame()); // Verify that the child surface is not blocked. EXPECT_TRUE(child_surface1()->HasActiveFrame()); EXPECT_FALSE(child_surface1()->HasPendingFrame()); EXPECT_THAT(child_surface1()->blocking_surfaces(), IsEmpty()); + // Verify that there's a temporary reference for |child_id1|. + EXPECT_TRUE(HasTemporaryReference(child_id1)); + // parent_support submits a CompositorFrame that depends on |child_id1| - // which is already active. Thus, this CompositorFrame should activate - // immediately. - parent_support().SubmitCompositorFrame(parent_id.local_surface_id(), - MakeCompositorFrame({child_id})); + // (which is already active) and |child_id2|. Thus, the parent should not + // activate immediately. + parent_support().SubmitCompositorFrame( + parent_id.local_surface_id(), + MakeCompositorFrame({child_id1, child_id2})); + EXPECT_FALSE(parent_surface()->HasActiveFrame()); + EXPECT_TRUE(parent_surface()->HasPendingFrame()); + EXPECT_THAT(parent_surface()->blocking_surfaces(), + UnorderedElementsAre(child_id2)); + EXPECT_THAT(GetChildReferences(parent_id), IsEmpty()); + + // Verify that there's a temporary reference for |child_id1| that still + // exists. + EXPECT_TRUE(HasTemporaryReference(child_id1)); + + // child_support2 submits a CompositorFrame without any dependencies. + child_support2().SubmitCompositorFrame(child_id2.local_surface_id(), + MakeCompositorFrame()); + + // Verify that the child surface is not blocked. + EXPECT_TRUE(child_surface1()->HasActiveFrame()); + EXPECT_FALSE(child_surface1()->HasPendingFrame()); + EXPECT_THAT(child_surface1()->blocking_surfaces(), IsEmpty()); + + // Verify that the parent surface's CompositorFrame has activated and that the + // temporary reference has been replaced by a permanent one. EXPECT_TRUE(parent_surface()->HasActiveFrame()); EXPECT_FALSE(parent_surface()->HasPendingFrame()); EXPECT_THAT(parent_surface()->blocking_surfaces(), IsEmpty()); - // Verify that the parent will add a reference to the |child_id|. - EXPECT_THAT(parent_reference_tracker().references_to_add(), - UnorderedElementsAre(parent_child_reference)); - EXPECT_THAT(parent_reference_tracker().references_to_remove(), IsEmpty()); - - // parent_support now submits another CompositorFrame to the same surface - // but depends on arbitrary_id. The parent surface should now have both - // a pending and active CompositorFrame. - parent_support().SubmitCompositorFrame(parent_id.local_surface_id(), - MakeCompositorFrame({arbitrary_id})); - EXPECT_TRUE(parent_surface()->HasActiveFrame()); - EXPECT_TRUE(parent_surface()->HasPendingFrame()); - EXPECT_THAT(parent_surface()->blocking_surfaces(), - UnorderedElementsAre(arbitrary_id)); - // Verify that the parent will add a reference to |arbitrary_id| and will not - // remove a reference to |child_id|. - EXPECT_THAT(parent_reference_tracker().references_to_add(), - UnorderedElementsAre(parent_arbitrary_reference)); - EXPECT_THAT(parent_reference_tracker().references_to_remove(), IsEmpty()); + EXPECT_FALSE(HasTemporaryReference(child_id1)); + EXPECT_THAT(GetChildReferences(parent_id), + UnorderedElementsAre(child_id1, child_id2)); } // This test verifies that we do not double count returned resources when a @@ -627,43 +638,6 @@ UnorderedElementsAre(returned_resource)); } -// This test verifies that a SurfaceReference from parent to child can be added -// prior to the child submitting a CompositorFrame. This test also verifies that -// when the child later submits a CompositorFrame, -TEST_F(CompositorFrameSinkSupportTest, - DisplayCompositorLockingReferenceAddedBeforeChildExists) { - const SurfaceId parent_id = MakeSurfaceId(kParentFrameSink, 1); - const SurfaceId child_id = MakeSurfaceId(kChildFrameSink1, 1); - - // The parent submits a CompositorFrame that depends on |child_id| before the - // child submits a CompositorFrame. - parent_support().SubmitCompositorFrame(parent_id.local_surface_id(), - MakeCompositorFrame({child_id})); - - // Verify that the CompositorFrame is blocked on |child_id|. - EXPECT_FALSE(parent_surface()->HasActiveFrame()); - EXPECT_TRUE(parent_surface()->HasPendingFrame()); - EXPECT_THAT(parent_surface()->blocking_surfaces(), - UnorderedElementsAre(child_id)); - - // Verify that a SurfaceReference(parent_id, child_id) exists in the - // SurfaceManager. - EXPECT_THAT(GetChildReferences(parent_id), UnorderedElementsAre(child_id)); - - child_support1().SubmitCompositorFrame( - child_id.local_surface_id(), MakeCompositorFrame(empty_surface_ids())); - - // Verify that the child CompositorFrame activates immediately. - EXPECT_TRUE(child_surface1()->HasActiveFrame()); - EXPECT_FALSE(child_surface1()->HasPendingFrame()); - EXPECT_THAT(child_surface1()->blocking_surfaces(), IsEmpty()); - - // Verify that there is no temporary reference for the child and that - // the reference from the parent to the child still exists. - EXPECT_FALSE(HasTemporaryReference(child_id)); - EXPECT_THAT(GetChildReferences(parent_id), UnorderedElementsAre(child_id)); -} - // The parent Surface is blocked on |child_id2| which is blocked on |child_id3|. // child_support1 evicts its blocked Surface. The parent surface should // activate. @@ -724,9 +698,8 @@ EXPECT_THAT(parent_surface()->blocking_surfaces(), UnorderedElementsAre(child_id1)); - // Verify that a SurfaceReference(parent_id, child_id1) exists in the - // SurfaceManager. - EXPECT_THAT(GetChildReferences(parent_id), UnorderedElementsAre(child_id1)); + // Verify that no references are added while the CompositorFrame is pending. + EXPECT_THAT(GetChildReferences(parent_id), IsEmpty()); child_support1().SubmitCompositorFrame( child_id1.local_surface_id(), MakeCompositorFrame(empty_surface_ids())); @@ -752,13 +725,12 @@ // The parent surface should now have both a pending and activate // CompositorFrame. Verify that the set of child references from - // |parent_id| include both the pending and active CompositorFrames. + // |parent_id| are only from the active CompositorFrame. EXPECT_TRUE(parent_surface()->HasActiveFrame()); EXPECT_TRUE(parent_surface()->HasPendingFrame()); EXPECT_THAT(parent_surface()->blocking_surfaces(), UnorderedElementsAre(child_id2)); - EXPECT_THAT(GetChildReferences(parent_id), - UnorderedElementsAre(child_id1, child_id2)); + EXPECT_THAT(GetChildReferences(parent_id), UnorderedElementsAre(child_id1)); child_support2().SubmitCompositorFrame( child_id2.local_surface_id(), MakeCompositorFrame(empty_surface_ids())); @@ -1004,19 +976,19 @@ EXPECT_EQ(ack2, begin_frame_source()->LastAckForObserver(&display_support())); } -// Checks whether the resources are returned before we send an ack. -TEST_F(CompositorFrameSinkSupportTest, ReturnResourcesBeforeAck) { +// Checks that resources and ack are sent together if possible. +TEST_F(CompositorFrameSinkSupportTest, ReturnResourcesWithAck) { const SurfaceId parent_id = MakeSurfaceId(kParentFrameSink, 1); TransferableResource resource; resource.id = 1234; parent_support().SubmitCompositorFrame( parent_id.local_surface_id(), MakeCompositorFrameWithResources(empty_surface_ids(), {resource})); - { - InSequence x; - EXPECT_CALL(support_client_, ReclaimResources(_)); - EXPECT_CALL(support_client_, DidReceiveCompositorFrameAck()); - } + ReturnedResourceArray returned_resources; + TransferableResource::ReturnResources({resource}, &returned_resources); + EXPECT_CALL(support_client_, ReclaimResources(_)).Times(0); + EXPECT_CALL(support_client_, + DidReceiveCompositorFrameAck(Eq(returned_resources))); parent_support().SubmitCompositorFrame(parent_id.local_surface_id(), MakeCompositorFrame()); } @@ -1224,10 +1196,9 @@ // not |parent_id2|. EXPECT_THAT(display_surface()->blocking_surfaces(), UnorderedElementsAre(parent_id1)); - // Verify that the display CompositorFrame holds refernces to both - // |parent_id1| and |parent_id2|. - EXPECT_THAT(GetChildReferences(display_id), - UnorderedElementsAre(parent_id1, parent_id2)); + // Verify that the display surface holds no references while its + // CompositorFrame is pending. + EXPECT_THAT(GetChildReferences(display_id), IsEmpty()); // Submitting a CompositorFrame with |parent_id1| should unblock the display // CompositorFrame. @@ -1238,8 +1209,10 @@ EXPECT_FALSE(display_surface()->HasPendingFrame()); EXPECT_TRUE(display_surface()->HasActiveFrame()); EXPECT_THAT(display_surface()->blocking_surfaces(), IsEmpty()); - EXPECT_THAT(GetChildReferences(display_id), - UnorderedElementsAre(parent_id1, parent_id2)); + + // Only a reference to |parent_id1| is added because |parent_id2| does not + // exist. + EXPECT_THAT(GetChildReferences(display_id), UnorderedElementsAre(parent_id1)); } } // namespace test
diff --git a/cc/surfaces/direct_compositor_frame_sink.cc b/cc/surfaces/direct_compositor_frame_sink.cc index a3c55c0..13b6c62 100644 --- a/cc/surfaces/direct_compositor_frame_sink.cc +++ b/cc/surfaces/direct_compositor_frame_sink.cc
@@ -69,7 +69,7 @@ constexpr bool is_root = true; constexpr bool handles_frame_sink_id_invalidation = false; - support_ = base::MakeUnique<CompositorFrameSinkSupport>( + support_ = CompositorFrameSinkSupport::Create( this, surface_manager_, frame_sink_id_, is_root, handles_frame_sink_id_invalidation, capabilities_.delegated_sync_points_required); @@ -131,7 +131,9 @@ // be drawn. } -void DirectCompositorFrameSink::DidReceiveCompositorFrameAck() { +void DirectCompositorFrameSink::DidReceiveCompositorFrameAck( + const ReturnedResourceArray& resources) { + client_->ReclaimResources(resources); client_->DidReceiveCompositorFrameAck(); }
diff --git a/cc/surfaces/direct_compositor_frame_sink.h b/cc/surfaces/direct_compositor_frame_sink.h index 5f9f4bd..5aa021b4 100644 --- a/cc/surfaces/direct_compositor_frame_sink.h +++ b/cc/surfaces/direct_compositor_frame_sink.h
@@ -64,7 +64,8 @@ private: // CompositorFrameSinkSupportClient implementation: - void DidReceiveCompositorFrameAck() override; + void DidReceiveCompositorFrameAck( + const ReturnedResourceArray& resources) override; void OnBeginFrame(const BeginFrameArgs& args) override; void ReclaimResources(const ReturnedResourceArray& resources) override; void WillDrawSurface(const LocalSurfaceId& local_surface_id,
diff --git a/cc/surfaces/pending_frame_observer.h b/cc/surfaces/pending_frame_observer.h index 3efd6783..ec7acab 100644 --- a/cc/surfaces/pending_frame_observer.h +++ b/cc/surfaces/pending_frame_observer.h
@@ -19,12 +19,6 @@ // changes should implement this class. class CC_SURFACES_EXPORT PendingFrameObserver { public: - // Called when one or both of the sets of referenced surfaces have changed. - virtual void OnReferencedSurfacesChanged( - Surface* surface, - const std::vector<SurfaceId>* active_referenced_surfaces, - const std::vector<SurfaceId>* pending_referenced_surfaces) = 0; - // Called when a CompositorFrame within |surface| has activated. virtual void OnSurfaceActivated(Surface* surface) = 0;
diff --git a/cc/surfaces/referenced_surface_tracker.cc b/cc/surfaces/referenced_surface_tracker.cc index ce1bf61..5e440d8 100644 --- a/cc/surfaces/referenced_surface_tracker.cc +++ b/cc/surfaces/referenced_surface_tracker.cc
@@ -20,8 +20,7 @@ void ReferencedSurfaceTracker::UpdateReferences( const LocalSurfaceId& local_surface_id, - const std::vector<SurfaceId>* active_referenced_surfaces, - const std::vector<SurfaceId>* pending_referenced_surfaces) { + const std::vector<SurfaceId>* active_referenced_surfaces) { DCHECK(local_surface_id.is_valid()); // Clear references to add/remove from the last frame. @@ -43,11 +42,6 @@ active_referenced_surfaces->end()); } - if (pending_referenced_surfaces) { - referenced_surface_set.insert(pending_referenced_surfaces->begin(), - pending_referenced_surfaces->end()); - } - ProcessNewReferences(referenced_surface_set); }
diff --git a/cc/surfaces/referenced_surface_tracker.h b/cc/surfaces/referenced_surface_tracker.h index 8153b644f..bfb3f3c7 100644 --- a/cc/surfaces/referenced_surface_tracker.h +++ b/cc/surfaces/referenced_surface_tracker.h
@@ -41,8 +41,7 @@ // CompositorFrame. void UpdateReferences( const LocalSurfaceId& local_surface_id, - const std::vector<SurfaceId>* active_referenced_surfaces, - const std::vector<SurfaceId>* pending_referenced_surfaces); + const std::vector<SurfaceId>* active_referenced_surfaces); private: // Updates |referenced_surfaces_| based on a |new_referenced_surfaces| from a
diff --git a/cc/surfaces/referenced_surface_tracker_unittest.cc b/cc/surfaces/referenced_surface_tracker_unittest.cc index 70a33b1..05e79532 100644 --- a/cc/surfaces/referenced_surface_tracker_unittest.cc +++ b/cc/surfaces/referenced_surface_tracker_unittest.cc
@@ -63,7 +63,7 @@ EXPECT_FALSE(tracker().current_surface_id().is_valid()); // After setting current SurfaceId then current_surface_id() should be valid. - tracker().UpdateReferences(parent_id.local_surface_id(), nullptr, nullptr); + tracker().UpdateReferences(parent_id.local_surface_id(), nullptr); EXPECT_EQ(parent_id, tracker().current_surface_id()); } @@ -75,8 +75,7 @@ // First frame has a reference to |child_id1|, check that reference is added. std::vector<SurfaceId> active_referenced_surfaces = {child_id1}; tracker().UpdateReferences(parent_id.local_surface_id(), - &active_referenced_surfaces, - nullptr /* pending_referenced_surfaces */); + &active_referenced_surfaces); EXPECT_THAT(tracker().references_to_add(), UnorderedElementsAre(reference)); EXPECT_THAT(tracker().references_to_remove(), IsEmpty()); } @@ -89,16 +88,14 @@ // First frame has a reference to |child_id1|, check that reference is added. std::vector<SurfaceId> active_referenced_surfaces = {child_id1}; tracker().UpdateReferences(parent_id.local_surface_id(), - &active_referenced_surfaces, - nullptr /* pending_referenced_surfaces */); + &active_referenced_surfaces); EXPECT_THAT(tracker().references_to_remove(), IsEmpty()); EXPECT_THAT(tracker().references_to_add(), UnorderedElementsAre(reference)); // Second frame has same reference, check that no references are added or // removed. tracker().UpdateReferences(parent_id.local_surface_id(), - &active_referenced_surfaces, - nullptr /* pending_referenced_surfaces */); + &active_referenced_surfaces); EXPECT_THAT(tracker().references_to_remove(), IsEmpty()); EXPECT_THAT(tracker().references_to_add(), IsEmpty()); } @@ -110,14 +107,12 @@ std::vector<SurfaceId> active_referenced_surfaces = {child_id1}; tracker().UpdateReferences(parent_id.local_surface_id(), - &active_referenced_surfaces, - nullptr /* pending_referenced_surfaces */); + &active_referenced_surfaces); // Second frame no longer references |child_id1|, check that reference to is // removed. tracker().UpdateReferences(parent_id.local_surface_id(), - nullptr /* active_referenced_surfaces */, - nullptr /* pending_referenced_surfaces */); + nullptr /* active_referenced_surfaces */); EXPECT_THAT(tracker().references_to_add(), IsEmpty()); EXPECT_THAT(tracker().references_to_remove(), UnorderedElementsAre(reference)); @@ -133,8 +128,7 @@ // First frame has reference to |child_id1_first|. std::vector<SurfaceId> active_referenced_surfaces1 = {child_id1_first}; tracker().UpdateReferences(parent_id.local_surface_id(), - &active_referenced_surfaces1, - nullptr /* pending_referenced_surfaces */); + &active_referenced_surfaces1); EXPECT_THAT(tracker().references_to_add(), UnorderedElementsAre(reference_first)); @@ -143,8 +137,7 @@ // removed and second reference is added. std::vector<SurfaceId> active_referenced_surfaces2 = {child_id1_second}; tracker().UpdateReferences(parent_id.local_surface_id(), - &active_referenced_surfaces2, - nullptr /* pending_referenced_surfaces */); + &active_referenced_surfaces2); EXPECT_THAT(tracker().references_to_remove(), UnorderedElementsAre(reference_first)); EXPECT_THAT(tracker().references_to_add(), @@ -160,16 +153,14 @@ // First frame references |child_id1|. std::vector<SurfaceId> active_referenced_surfaces = {child_id1}; tracker().UpdateReferences(parent_id_first.local_surface_id(), - &active_referenced_surfaces, - nullptr /* pending_referenced_surfaces */); + &active_referenced_surfaces); EXPECT_THAT(tracker().references_to_add(), SizeIs(1)); // Second frame still reference |child_id1| but the parent SurfaceId has // changed. The new parent SurfaceId should have a reference added to // |child_id1|. tracker().UpdateReferences(parent_id_second.local_surface_id(), - &active_referenced_surfaces, - nullptr /* pending_referenced_surfaces */); + &active_referenced_surfaces); EXPECT_THAT(tracker().references_to_add(), UnorderedElementsAre(reference)); EXPECT_THAT(tracker().references_to_remove(), IsEmpty()); } @@ -184,8 +175,7 @@ // First frame references both surfaces. std::vector<SurfaceId> active_referenced_surfaces1 = {child_id1, child_id2}; tracker().UpdateReferences(parent_id.local_surface_id(), - &active_referenced_surfaces1, - nullptr /* pending_referenced_surfaces */); + &active_referenced_surfaces1); EXPECT_THAT(tracker().references_to_add(), UnorderedElementsAre(reference1, reference2)); @@ -193,8 +183,7 @@ // |child_id1| is removed. std::vector<SurfaceId> active_referenced_surfaces2 = {child_id2}; tracker().UpdateReferences(parent_id.local_surface_id(), - &active_referenced_surfaces2, - nullptr /* pending_referenced_surfaces */); + &active_referenced_surfaces2); EXPECT_THAT(tracker().references_to_remove(), UnorderedElementsAre(reference1)); EXPECT_THAT(tracker().references_to_add(), IsEmpty());
diff --git a/cc/surfaces/surface.cc b/cc/surfaces/surface.cc index 3290f84b..a161eee5 100644 --- a/cc/surfaces/surface.cc +++ b/cc/surfaces/surface.cc
@@ -73,13 +73,6 @@ // Ask the surface manager to inform |this| when its dependencies are // resolved. factory_->manager()->RequestSurfaceResolution(this); - - // We do not have to notify observers that referenced surfaces have changed - // in the else case because ActivateFrame will notify observers. - for (auto& observer : observers_) { - observer.OnReferencedSurfacesChanged(this, active_referenced_surfaces(), - pending_referenced_surfaces()); - } } else { // If there are no blockers, then immediately activate the frame. ActivateFrame(std::move(frame)); @@ -197,11 +190,6 @@ for (auto& observer : observers_) observer.OnSurfaceActivated(this); - - for (auto& observer : observers_) { - observer.OnReferencedSurfacesChanged(this, active_referenced_surfaces(), - pending_referenced_surfaces()); - } } void Surface::UpdateBlockingSurfaces(
diff --git a/cc/surfaces/surface.h b/cc/surfaces/surface.h index b930621..6cd9bbf 100644 --- a/cc/surfaces/surface.h +++ b/cc/surfaces/surface.h
@@ -106,11 +106,6 @@ : nullptr; } - const std::vector<SurfaceId>* pending_referenced_surfaces() const { - return pending_frame_ ? &pending_frame_->metadata.referenced_surfaces - : nullptr; - } - const SurfaceDependencies& blocking_surfaces() const { return blocking_surfaces_; }
diff --git a/cc/surfaces/surface_dependency_tracker.cc b/cc/surfaces/surface_dependency_tracker.cc index 9e05907..dbeafe4b 100644 --- a/cc/surfaces/surface_dependency_tracker.cc +++ b/cc/surfaces/surface_dependency_tracker.cc
@@ -103,11 +103,6 @@ void SurfaceDependencyTracker::OnBeginFrameSourcePausedChanged(bool paused) {} -void SurfaceDependencyTracker::OnReferencedSurfacesChanged( - Surface* surface, - const std::vector<SurfaceId>* active_referenced_surfaces, - const std::vector<SurfaceId>* pending_referenced_surfaces) {} - void SurfaceDependencyTracker::OnSurfaceDiscarded(Surface* surface) { // If the surface being destroyed doesn't have a pending frame then we have // nothing to do here.
diff --git a/cc/surfaces/surface_dependency_tracker.h b/cc/surfaces/surface_dependency_tracker.h index 6ba28fa..7643574 100644 --- a/cc/surfaces/surface_dependency_tracker.h +++ b/cc/surfaces/surface_dependency_tracker.h
@@ -50,10 +50,6 @@ void OnBeginFrameSourcePausedChanged(bool paused) override; // PendingFrameObserver implementation: - void OnReferencedSurfacesChanged( - Surface* surface, - const std::vector<SurfaceId>* active_referenced_surfaces, - const std::vector<SurfaceId>* pending_referenced_surfaces) override; void OnSurfaceActivated(Surface* surface) override; void OnSurfaceDependenciesChanged( Surface* surface,
diff --git a/cc/surfaces/surface_factory.cc b/cc/surfaces/surface_factory.cc index 880cb8c..f6a6e0ec 100644 --- a/cc/surfaces/surface_factory.cc +++ b/cc/surfaces/surface_factory.cc
@@ -105,32 +105,26 @@ holder_.UnrefResources(resources); } -void SurfaceFactory::OnReferencedSurfacesChanged( - Surface* surface, - const std::vector<SurfaceId>* active_referenced_surfaces, - const std::vector<SurfaceId>* pending_referenced_surfaces) { - client_->ReferencedSurfacesChanged(surface->surface_id().local_surface_id(), - active_referenced_surfaces, - pending_referenced_surfaces); -} - void SurfaceFactory::OnSurfaceActivated(Surface* surface) { DCHECK(surface->HasActiveFrame()); - if (seen_first_frame_activation_) - return; + if (!seen_first_frame_activation_) { + seen_first_frame_activation_ = true; - seen_first_frame_activation_ = true; + const CompositorFrame& frame = surface->GetActiveFrame(); + // CompositorFrames might not be populated with a RenderPass in unit tests. + gfx::Size frame_size; + if (!frame.render_pass_list.empty()) + frame_size = frame.render_pass_list.back()->output_rect.size(); - const CompositorFrame& frame = surface->GetActiveFrame(); - // CompositorFrames might not be populated with a RenderPass in unit tests. - gfx::Size frame_size; - if (!frame.render_pass_list.empty()) - frame_size = frame.render_pass_list.back()->output_rect.size(); - - // SurfaceCreated only applies for the first Surface activation. Thus, - // SurfaceFactory stops observing new activations after the first one. - manager_->SurfaceCreated(SurfaceInfo( - surface->surface_id(), frame.metadata.device_scale_factor, frame_size)); + // SurfaceCreated only applies for the first Surface activation. Thus, + // SurfaceFactory stops observing new activations after the first one. + manager_->SurfaceCreated(SurfaceInfo( + surface->surface_id(), frame.metadata.device_scale_factor, frame_size)); + } + // Fire SurfaceCreated first so that a temporary reference is added before it + // is potentially transformed into a real reference by the client. + client_->ReferencedSurfacesChanged(surface->surface_id().local_surface_id(), + surface->active_referenced_surfaces()); } void SurfaceFactory::OnSurfaceDependenciesChanged(
diff --git a/cc/surfaces/surface_factory.h b/cc/surfaces/surface_factory.h index 39a45fd..29b3e48 100644 --- a/cc/surfaces/surface_factory.h +++ b/cc/surfaces/surface_factory.h
@@ -85,10 +85,6 @@ private: // PendingFrameObserver implementation. - void OnReferencedSurfacesChanged( - Surface* surface, - const std::vector<SurfaceId>* active_referenced_surfaces, - const std::vector<SurfaceId>* pending_referenced_surfaces) override; void OnSurfaceActivated(Surface* surface) override; void OnSurfaceDependenciesChanged( Surface* surface,
diff --git a/cc/surfaces/surface_factory_client.h b/cc/surfaces/surface_factory_client.h index ea32344..57ecfed1 100644 --- a/cc/surfaces/surface_factory_client.h +++ b/cc/surfaces/surface_factory_client.h
@@ -21,8 +21,7 @@ virtual void ReferencedSurfacesChanged( const LocalSurfaceId& local_surface_id, - const std::vector<SurfaceId>* active_referenced_surfaces, - const std::vector<SurfaceId>* pending_referenced_surfaces) {} + const std::vector<SurfaceId>* active_referenced_surfaces) {} virtual void ReturnResources(const ReturnedResourceArray& resources) = 0;
diff --git a/cc/surfaces/surface_manager.cc b/cc/surfaces/surface_manager.cc index 2c2e2f6..d4b0d01 100644 --- a/cc/surfaces/surface_manager.cc +++ b/cc/surfaces/surface_manager.cc
@@ -319,6 +319,13 @@ return; } + // We trust that |parent_id| either exists or is about to exist, since is not + // sent over IPC. We don't trust |child_id|, since it is sent over IPC. + if (surface_map_.count(child_id) == 0) { + DLOG(ERROR) << "No surface in map for " << child_id.ToString(); + return; + } + parent_to_child_refs_[parent_id].insert(child_id); child_to_parent_refs_[child_id].insert(parent_id); @@ -461,14 +468,7 @@ // destroyed in SurfaceFactory and then if there are no references it will // be deleted during surface GC. A temporary reference, removed when a // real reference is received, is added to prevent this from happening. - auto it = child_to_parent_refs_.find(surface_info.id()); - // TODO(fsamuel): Tests create empty sets and so we also need to check that - // they're not empty here. Ideally tests shouldn't do that and we shouldn't - // use array notation into maps in tests (see https://crbug.com/691115). - bool has_real_reference = - it != child_to_parent_refs_.end() && !it->second.empty(); - if (!has_real_reference) - AddTemporaryReference(surface_info.id()); + AddTemporaryReference(surface_info.id()); } for (auto& observer : observer_list_)
diff --git a/cc/test/test_compositor_frame_sink.cc b/cc/test/test_compositor_frame_sink.cc index 523874f..419af4ea 100644 --- a/cc/test/test_compositor_frame_sink.cc +++ b/cc/test/test_compositor_frame_sink.cc
@@ -98,10 +98,12 @@ if (display_context_shared_with_compositor && context_provider()) context_provider()->SetLostContextCallback(base::Closure()); - support_ = base::MakeUnique<CompositorFrameSinkSupport>( - this, surface_manager_.get(), frame_sink_id_, false /* is_root */, - true /* handles_frame_sink_id_invalidation */, - true /* needs_sync_points */); + constexpr bool is_root = false; + constexpr bool handles_frame_sink_id_invalidation = true; + constexpr bool needs_sync_points = true; + support_ = CompositorFrameSinkSupport::Create( + this, surface_manager_.get(), frame_sink_id_, is_root, + handles_frame_sink_id_invalidation, needs_sync_points); client_->SetBeginFrameSource(&external_begin_frame_source_); display_->Initialize(this, surface_manager_.get()); @@ -164,7 +166,9 @@ } } -void TestCompositorFrameSink::DidReceiveCompositorFrameAck() { +void TestCompositorFrameSink::DidReceiveCompositorFrameAck( + const ReturnedResourceArray& resources) { + ReclaimResources(resources); // In synchronous mode, we manually send acks and this method should not be // used. if (!display_->has_scheduler())
diff --git a/cc/test/test_compositor_frame_sink.h b/cc/test/test_compositor_frame_sink.h index 9d97bc9..3b00ae0 100644 --- a/cc/test/test_compositor_frame_sink.h +++ b/cc/test/test_compositor_frame_sink.h
@@ -82,7 +82,8 @@ void ForceReclaimResources() override; // CompositorFrameSinkSupportClient implementation. - void DidReceiveCompositorFrameAck() override; + void DidReceiveCompositorFrameAck( + const ReturnedResourceArray& resources) override; void OnBeginFrame(const BeginFrameArgs& args) override; void ReclaimResources(const ReturnedResourceArray& resources) override; void WillDrawSurface(const LocalSurfaceId& local_surface_id,
diff --git a/cc/trees/layer_tree_host.cc b/cc/trees/layer_tree_host.cc index d50449d..e8a6f4b0 100644 --- a/cc/trees/layer_tree_host.cc +++ b/cc/trees/layer_tree_host.cc
@@ -363,7 +363,7 @@ void LayerTreeHost::UpdateDeferCommitsInternal() { proxy_->SetDeferCommits(defer_commits_ || - (settings_.needs_valid_local_surface_id && + (settings_.enable_surface_synchronization && !local_surface_id_.is_valid())); }
diff --git a/cc/trees/layer_tree_host_impl.cc b/cc/trees/layer_tree_host_impl.cc index 62654865..344eb45 100644 --- a/cc/trees/layer_tree_host_impl.cc +++ b/cc/trees/layer_tree_host_impl.cc
@@ -1624,13 +1624,14 @@ for (LayerImpl* surface_layer : active_tree_->SurfaceLayers()) { SurfaceLayerImpl* surface_layer_impl = static_cast<SurfaceLayerImpl*>(surface_layer); - metadata.referenced_surfaces.push_back( - surface_layer_impl->primary_surface_info().id()); - // We need to retain a reference to the fallback surface too so that it's - // guaranteed to be available when needed. - if (surface_layer_impl->fallback_surface_info().is_valid()) { + if (settings_.enable_surface_synchronization) { + if (surface_layer_impl->fallback_surface_info().is_valid()) { + metadata.referenced_surfaces.push_back( + surface_layer_impl->fallback_surface_info().id()); + } + } else { metadata.referenced_surfaces.push_back( - surface_layer_impl->fallback_surface_info().id()); + surface_layer_impl->primary_surface_info().id()); } } if (!InnerViewportScrollLayer())
diff --git a/cc/trees/layer_tree_impl.cc b/cc/trees/layer_tree_impl.cc index f57f8a22..f7f0304e 100644 --- a/cc/trees/layer_tree_impl.cc +++ b/cc/trees/layer_tree_impl.cc
@@ -1310,10 +1310,7 @@ // These manage ownership of the LayerImpl. void LayerTreeImpl::AddLayer(std::unique_ptr<LayerImpl> layer) { DCHECK(std::find(layers_->begin(), layers_->end(), layer) == layers_->end()); - - // TODO(ajuma): Change this to a DCHECK once we've figured out what's causing - // crbug.com/701279. - CHECK(layer); + DCHECK(layer); layers_->push_back(std::move(layer)); set_needs_update_draw_properties(); } @@ -1793,11 +1790,6 @@ surface_layers_.erase(it); } -template <typename LayerType> -static inline bool LayerClipsSubtree(LayerType* layer) { - return layer->masks_to_bounds() || layer->mask_layer(); -} - static bool PointHitsRect( const gfx::PointF& screen_space_point, const gfx::Transform& local_space_to_screen_space_transform,
diff --git a/cc/trees/layer_tree_settings.h b/cc/trees/layer_tree_settings.h index d54e05c..b6237c9 100644 --- a/cc/trees/layer_tree_settings.h +++ b/cc/trees/layer_tree_settings.h
@@ -109,7 +109,7 @@ // Indicates that the LayerTreeHost should defer commits unless it has a valid // LocalSurfaceId set. - bool needs_valid_local_surface_id = false; + bool enable_surface_synchronization = false; }; } // namespace cc
diff --git a/cc/trees/tree_synchronizer.cc b/cc/trees/tree_synchronizer.cc index 873a57bf..52f1bb38 100644 --- a/cc/trees/tree_synchronizer.cc +++ b/cc/trees/tree_synchronizer.cc
@@ -29,9 +29,7 @@ OwnedLayerImplMap old_layer_map; for (auto& it : *old_layers) { - // TODO(ajuma): Remove this once we've figured out what's causing - // crbug.com/701279. - CHECK(it); + DCHECK(it); old_layer_map[it->id()] = std::move(it); }
diff --git a/chrome/BUILD.gn b/chrome/BUILD.gn index 66c1e3ed..5b70b87c 100644 --- a/chrome/BUILD.gn +++ b/chrome/BUILD.gn
@@ -1606,6 +1606,12 @@ ] } + java_cpp_enum("offline_pages_enum_javagen") { + sources = [ + "browser/android/offline_pages/offline_page_utils.h", + ] + } + source_set("chrome_android_core") { sources = [ "app/android/chrome_android_initializer.cc",
diff --git a/chrome/VERSION b/chrome/VERSION index f90b0fa..e58a836 100644 --- a/chrome/VERSION +++ b/chrome/VERSION
@@ -1,4 +1,4 @@ MAJOR=59 MINOR=0 -BUILD=3068 +BUILD=3069 PATCH=0
diff --git a/chrome/android/BUILD.gn b/chrome/android/BUILD.gn index 9cac8a48..57b41d5d 100644 --- a/chrome/android/BUILD.gn +++ b/chrome/android/BUILD.gn
@@ -251,10 +251,11 @@ "//chrome:content_setting_javagen", "//chrome:content_settings_type_javagen", "//chrome:data_use_ui_message_enum_javagen", - "//chrome:signin_metrics_enum_javagen", - "//chrome:quick_action_category_enum_javagen", + "//chrome:offline_pages_enum_javagen", "//chrome:page_info_connection_type_javagen", "//chrome:page_info_action_javagen", + "//chrome:quick_action_category_enum_javagen", + "//chrome:signin_metrics_enum_javagen", "//components/browsing_data/core:browsing_data_utils_java", "//components/browsing_data/core:clear_browsing_data_tab_java", "//components/infobars/core:infobar_enums_java",
diff --git a/chrome/android/java/res/color/item_chooser_row_text_color.xml b/chrome/android/java/res/color/item_chooser_row_text_color.xml index 5e42aab..bb8c05c 100644 --- a/chrome/android/java/res/color/item_chooser_row_text_color.xml +++ b/chrome/android/java/res/color/item_chooser_row_text_color.xml
@@ -4,7 +4,7 @@ found in the LICENSE file. --> <selector xmlns:android="http://schemas.android.com/apk/res/android"> - <item android:color="@android:color/white" android:state_selected="true"/> - <item android:color="@color/primary_text_disabled_material_light" android:state_enabled="false"/> - <item android:color="@color/default_text_color"/> + <item android:color="@android:color/white" android:state_selected="true"/> + <item android:color="@color/primary_text_disabled_material_light" android:state_enabled="false"/> + <item android:color="@color/default_text_color"/> </selector>
diff --git a/chrome/android/java/res/layout/data_reduction_old_stats_layout.xml b/chrome/android/java/res/layout/data_reduction_old_stats_layout.xml new file mode 100644 index 0000000..592602e --- /dev/null +++ b/chrome/android/java/res/layout/data_reduction_old_stats_layout.xml
@@ -0,0 +1,132 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- 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. --> + +<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" + xmlns:tools="http://schemas.android.com/tools" + android:id="@+id/data_reduction_stats_container" + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:clipChildren="false" + android:clipToPadding="false" + android:orientation="vertical" > + + <TextView + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:fadingEdge="horizontal" + android:text="@string/data_reduction_stats_title" + android:textAppearance="@style/PreferenceCategoryTextStyle" /> + + <include layout="@layout/data_usage_chart" /> + + <LinearLayout + android:layout_width="match_parent" + android:layout_height="wrap_content" > + + <TextView + android:id="@+id/data_reduction_start_date" + android:layout_width="0dp" + android:layout_height="wrap_content" + android:layout_weight="1" + android:textAppearance="@style/PreferenceSummary" + android:textSize="14sp" /> + + <TextView + android:id="@+id/data_reduction_end_date" + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:textAppearance="@style/PreferenceSummary" + android:textSize="14sp" /> + + </LinearLayout> + + <LinearLayout + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:orientation="horizontal" > + + <TextView + android:id="@+id/data_reduction_percent" + android:layout_height="wrap_content" + android:layout_width="wrap_content" + android:layout_marginTop="0dp" + android:textColor="?android:attr/textColorPrimary" + android:textSize="50sp" /> + + <FrameLayout + android:layout_height="wrap_content" + android:layout_width="0dp" + android:layout_weight="1" + android:paddingEnd="6dp" + android:paddingStart="20dp" > + + <LinearLayout + android:layout_height="wrap_content" + android:layout_width="wrap_content" + android:layout_gravity="end" + android:orientation="vertical" + tools:ignore="UselessParent" > + + <TextView + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:layout_marginTop="14dp" + android:singleLine="true" + android:text="@string/data_reduction_original_size_label" + android:textColor="?android:attr/textColorPrimary" + android:textSize="14sp" /> + + <TextView + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:layout_marginTop="4dp" + android:singleLine="true" + android:text="@string/data_reduction_compressed_size_label" + android:textColor="?android:attr/textColorPrimary" + android:textSize="14sp" /> + </LinearLayout> + + </FrameLayout> + + <LinearLayout + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:orientation="vertical" + android:paddingStart="10dp" > + + <TextView + android:id="@+id/data_reduction_original_size" + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:layout_marginTop="14dp" + android:textColor="?android:attr/textColorPrimary" + android:textSize="14sp" + android:textStyle="bold" /> + + <TextView + android:id="@+id/data_reduction_compressed_size" + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:layout_marginTop="4dp" + android:textColor="?android:attr/textColorPrimary" + android:textSize="14sp" + android:textStyle="bold" /> + </LinearLayout> + + </LinearLayout> + + <TextView + android:id="@+id/data_reduction_proxy_unreachable" + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:layout_marginBottom="20dp" + android:layout_marginTop="20dp" + android:drawableStart="@drawable/exclamation_triangle" + android:drawablePadding="6dp" + android:text="@string/data_reduction_proxy_unreachable_warn" + android:textColor="?android:attr/textColorPrimary" + android:textSize="14sp" /> + +</LinearLayout> \ No newline at end of file
diff --git a/chrome/android/java/res/layout/data_reduction_stats_layout.xml b/chrome/android/java/res/layout/data_reduction_stats_layout.xml index 86092ed..8484734 100644 --- a/chrome/android/java/res/layout/data_reduction_stats_layout.xml +++ b/chrome/android/java/res/layout/data_reduction_stats_layout.xml
@@ -12,12 +12,75 @@ android:clipToPadding="false" android:orientation="vertical" > - <TextView + <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" - android:fadingEdge="horizontal" - android:text="@string/data_reduction_stats_title" - android:textAppearance="@style/PreferenceCategoryTextStyle" /> + android:baselineAligned="false" + android:orientation="horizontal" > + + <LinearLayout + android:layout_height="wrap_content" + android:layout_width="0dp" + android:layout_weight="1" + android:orientation="vertical" > + + <LinearLayout + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:layout_marginTop="8dp" + android:orientation="horizontal" > + + <TextView + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:singleLine="true" + android:text="@string/data_reduction_savings_label" + android:textAppearance="@style/PreferenceCategoryTextStyle" /> + + <TextView + android:id="@+id/data_reduction_savings" + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:paddingStart="3dp" + android:textAppearance="@style/PreferenceCategoryTextStyle" /> + + </LinearLayout> + + <LinearLayout + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:layout_marginTop="4dp" + android:orientation="horizontal" > + + <TextView + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:singleLine="true" + android:text="@string/data_reduction_usage_label" + android:textColor="?android:attr/textColorSecondary" + android:textSize="14sp" /> + + <TextView + android:id="@+id/data_reduction_usage" + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:paddingStart="3dp" + android:textColor="?android:attr/textColorSecondary" + android:textSize="14sp" /> + </LinearLayout> + + </LinearLayout> + + <TextView + android:id="@+id/data_reduction_percent" + android:layout_height="wrap_content" + android:layout_width="wrap_content" + android:layout_marginTop="0dp" + android:includeFontPadding="false" + android:textColor="@color/light_active_color" + android:textSize="50sp" /> + + </LinearLayout> <include layout="@layout/data_usage_chart" /> @@ -42,81 +105,6 @@ </LinearLayout> - <LinearLayout - android:layout_width="match_parent" - android:layout_height="wrap_content" - android:orientation="horizontal" > - - <TextView - android:id="@+id/data_reduction_percent" - android:layout_height="wrap_content" - android:layout_width="wrap_content" - android:layout_marginTop="0dp" - android:textColor="?android:attr/textColorPrimary" - android:textSize="50sp" /> - - <FrameLayout - android:layout_height="wrap_content" - android:layout_width="0dp" - android:layout_weight="1" - android:paddingEnd="6dp" - android:paddingStart="20dp" > - - <LinearLayout - android:layout_height="wrap_content" - android:layout_width="wrap_content" - android:layout_gravity="end" - android:orientation="vertical" - tools:ignore="UselessParent" > - - <TextView - android:layout_width="match_parent" - android:layout_height="wrap_content" - android:layout_marginTop="14dp" - android:singleLine="true" - android:text="@string/data_reduction_original_size_label" - android:textColor="?android:attr/textColorPrimary" - android:textSize="14sp" /> - - <TextView - android:layout_width="match_parent" - android:layout_height="wrap_content" - android:layout_marginTop="4dp" - android:singleLine="true" - android:text="@string/data_reduction_compressed_size_label" - android:textColor="?android:attr/textColorPrimary" - android:textSize="14sp" /> - </LinearLayout> - - </FrameLayout> - - <LinearLayout - android:layout_width="wrap_content" - android:layout_height="wrap_content" - android:orientation="vertical" - android:paddingStart="10dp" > - - <TextView - android:id="@+id/data_reduction_original_size" - android:layout_width="wrap_content" - android:layout_height="wrap_content" - android:layout_marginTop="14dp" - android:textColor="?android:attr/textColorPrimary" - android:textSize="14sp" - android:textStyle="bold" /> - - <TextView - android:id="@+id/data_reduction_compressed_size" - android:layout_width="wrap_content" - android:layout_height="wrap_content" - android:layout_marginTop="4dp" - android:textColor="?android:attr/textColorPrimary" - android:textSize="14sp" - android:textStyle="bold" /> - </LinearLayout> - - </LinearLayout> - <TextView android:id="@+id/data_reduction_proxy_unreachable" android:layout_width="match_parent" @@ -128,5 +116,7 @@ android:text="@string/data_reduction_proxy_unreachable_warn" android:textColor="?android:attr/textColorPrimary" android:textSize="14sp" /> + + <include layout="@layout/data_usage_breakdown" /> </LinearLayout>
diff --git a/chrome/android/java/res/layout/data_usage_breakdown.xml b/chrome/android/java/res/layout/data_usage_breakdown.xml new file mode 100644 index 0000000..fc49a18 --- /dev/null +++ b/chrome/android/java/res/layout/data_usage_breakdown.xml
@@ -0,0 +1,78 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- 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. --> + +<org.chromium.chrome.browser.preferences.datareduction.DataReductionSiteBreakdownView + xmlns:android="http://schemas.android.com/apk/res/android" + xmlns:settings="http://schemas.android.com/apk/res-auto" + android:id="@+id/breakdown" + android:layout_height="wrap_content" + android:layout_width="match_parent" + android:orientation="vertical" + android:visibility="gone"> + + <TextView + android:id="@+id/data_reduction_data_usage_breakdown_title" + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:layout_marginTop="26dp" + android:paddingBottom="10dp" + android:singleLine="true" + android:text="@string/data_reduction_data_usage_breakdown_title" + android:textAppearance="@style/PreferenceCategoryTextStyle" /> + + <TableLayout + android:id="@+id/data_reduction_proxy_breakdown_table" + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:divider="?android:attr/dividerHorizontal" + android:showDividers="middle" + android:stretchColumns="0"> + + <TableRow + android:id="@+id/data_reduction_proxy_breakdown_table_labels" + android:layout_height="wrap_content" + android:layout_width="match_parent" + android:orientation="horizontal"> + + <TextView + android:text="@string/data_reduction_breakdown_site_title" + android:layout_width="0dp" + android:layout_weight="1" + android:textColor="?android:attr/textColorSecondary" + style="@style/DataUsageBreakdownColumnLabel" /> + + <TextView + android:text="@string/data_reduction_breakdown_used_title" + android:layout_width="wrap_content" + android:gravity="end" + android:paddingStart="10dp" + android:textColor="?android:attr/textColorPrimary" + style="@style/DataUsageBreakdownColumnLabel" /> + + <TextView + android:text="@string/data_reduction_breakdown_saved_title" + android:layout_width="wrap_content" + android:gravity="end" + android:paddingStart="24dp" + android:textColor="?android:attr/textColorSecondary" + style="@style/DataUsageBreakdownColumnLabel" /> + + </TableRow> + + </TableLayout> + + <Button + android:id="@+id/data_reduction_reset_statistics" + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:layout_gravity="center" + android:layout_marginTop="24dp" + android:text="@string/data_reduction_usage_reset_statistics_button" + android:textAllCaps="true" + android:textColor="@color/light_active_color" + android:textSize="14sp" + style="@style/ButtonCompatBorderless" /> + +</org.chromium.chrome.browser.preferences.datareduction.DataReductionSiteBreakdownView>
diff --git a/chrome/android/java/res/layout/data_usage_breakdown_row.xml b/chrome/android/java/res/layout/data_usage_breakdown_row.xml new file mode 100644 index 0000000..11b488d5 --- /dev/null +++ b/chrome/android/java/res/layout/data_usage_breakdown_row.xml
@@ -0,0 +1,31 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- 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. --> + +<TableRow + xmlns:android="http://schemas.android.com/apk/res/android" + xmlns:settings="http://schemas.android.com/apk/res-auto" + android:id="@+id/site_row" + android:layout_width="match_parent"> + + <TextView + android:id="@+id/site_hostname" + android:layout_width="0dp" + android:layout_weight="0" + style="@style/DataUsageBreakdownColumnItem" /> + + <TextView + android:id="@+id/site_data_used" + android:layout_width="wrap_content" + android:gravity="end" + android:paddingStart="10dp" + style="@style/DataUsageBreakdownColumnItem" /> + + <TextView + android:id="@+id/site_data_saved" + android:layout_width="wrap_content" + android:gravity="end" + android:paddingStart="24dp" + style="@style/DataUsageBreakdownColumnItem" /> +</TableRow>
diff --git a/chrome/android/java/res/values-v17/styles.xml b/chrome/android/java/res/values-v17/styles.xml index cb67fee..3cfc6e2 100644 --- a/chrome/android/java/res/values-v17/styles.xml +++ b/chrome/android/java/res/values-v17/styles.xml
@@ -587,6 +587,22 @@ <item name="android:textSize">14sp</item> <item name="android:visibility">gone</item> </style> + <style name="DataUsageBreakdownColumnLabel"> + <item name="android:layout_height">wrap_content</item> + <item name="android:paddingBottom">10dp</item> + <item name="android:paddingTop">10dp</item> + <item name="android:singleLine">true</item> + <item name="android:textSize">16sp</item> + <item name="android:textAppearance">@style/RobotoMediumStyle</item> + </style> + <style name="DataUsageBreakdownColumnItem"> + <item name="android:layout_height">wrap_content</item> + <item name="android:paddingBottom">10dp</item> + <item name="android:paddingTop">10dp</item> + <item name="android:singleLine">true</item> + <item name="android:textColor">?android:attr/textColorPrimary</item> + <item name="android:textSize">14sp</item> + </style> <!-- New tab page RecyclerView overscroll color --> <style name="NewTabPageRecyclerView">
diff --git a/chrome/android/java/res/xml/single_website_preferences.xml b/chrome/android/java/res/xml/single_website_preferences.xml index 854d8d1..0d171442 100644 --- a/chrome/android/java/res/xml/single_website_preferences.xml +++ b/chrome/android/java/res/xml/single_website_preferences.xml
@@ -46,6 +46,8 @@ <org.chromium.chrome.browser.preferences.ChromeBaseListPreference android:key="popup_permission_list" /> <org.chromium.chrome.browser.preferences.ChromeBaseListPreference + android:key="subresource_filter_permission_list" /> + <org.chromium.chrome.browser.preferences.ChromeBaseListPreference android:key="background_sync_permission_list" /> <org.chromium.chrome.browser.preferences.ChromeBaseListPreference android:key="protected_media_identifier_permission_list" /> @@ -53,8 +55,6 @@ android:key="autoplay_permission_list" /> <org.chromium.chrome.browser.preferences.ChromeBaseListPreference android:key="midi_sysex_permission_list" /> - <org.chromium.chrome.browser.preferences.ChromeBaseListPreference - android:key="subresource_filter_permission_list" /> <org.chromium.chrome.browser.preferences.ButtonPreference android:key="reset_site_button"
diff --git a/chrome/android/java/res/xml/site_settings_preferences.xml b/chrome/android/java/res/xml/site_settings_preferences.xml index 34e524a..ae118abc 100644 --- a/chrome/android/java/res/xml/site_settings_preferences.xml +++ b/chrome/android/java/res/xml/site_settings_preferences.xml
@@ -39,6 +39,10 @@ <org.chromium.chrome.browser.preferences.website.SiteSettingsPreference android:fragment="org.chromium.chrome.browser.preferences.website.SingleCategoryPreferences" android:key="popups" /> + <!-- SubresourceFilter --> + <org.chromium.chrome.browser.preferences.website.SiteSettingsPreference + android:fragment="org.chromium.chrome.browser.preferences.website.SingleCategoryPreferences" + android:key="subresource_filter" /> <!-- Background sync --> <org.chromium.chrome.browser.preferences.website.SiteSettingsPreference android:fragment="org.chromium.chrome.browser.preferences.website.SingleCategoryPreferences" @@ -76,8 +80,4 @@ android:key="usb" android:title="@string/website_settings_usb" android:icon="@drawable/settings_usb" /> - <!-- SubresourceFilter --> - <org.chromium.chrome.browser.preferences.website.SiteSettingsPreference - android:fragment="org.chromium.chrome.browser.preferences.website.SingleCategoryPreferences" - android:key="subresource_filter" /> </PreferenceScreen>
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/ActivityTabTaskDescriptionHelper.java b/chrome/android/java/src/org/chromium/chrome/browser/ActivityTabTaskDescriptionHelper.java index 76b2fff..b55d065 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/ActivityTabTaskDescriptionHelper.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/ActivityTabTaskDescriptionHelper.java
@@ -162,7 +162,7 @@ } @Override - public void allTabsPendingClosure(List<Integer> tabIds) { + public void allTabsPendingClosure(List<Tab> tabs) { refreshSelectedTab(); } };
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/ChromeFeatureList.java b/chrome/android/java/src/org/chromium/chrome/browser/ChromeFeatureList.java index 2b5b237d..a3ac422 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/ChromeFeatureList.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/ChromeFeatureList.java
@@ -138,6 +138,7 @@ // Enables the Data Reduction Proxy menu item in the main menu rather than under Settings on // Android. public static final String DATA_REDUCTION_MAIN_MENU = "DataReductionProxyMainMenu"; + public static final String DATA_REDUCTION_SITE_BREAKDOWN = "DataReductionProxySiteBreakdown"; // When enabled, fullscreen WebContents will be moved to a new Activity. Coming soon... public static final String FULLSCREEN_ACTIVITY = "FullscreenActivity"; // Whether we show an important sites dialog in the "Clear Browsing Data" flow.
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/ChromeTabbedActivity.java b/chrome/android/java/src/org/chromium/chrome/browser/ChromeTabbedActivity.java index ff9504bc..8e454fe 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/ChromeTabbedActivity.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/ChromeTabbedActivity.java
@@ -363,7 +363,7 @@ } @Override - public void allTabsPendingClosure(List<Integer> tabIds) { + public void allTabsPendingClosure(List<Tab> tabs) { NewTabPageUma.recordNTPImpression( NewTabPageUma.NTP_IMPESSION_POTENTIAL_NOTAB); } @@ -1860,15 +1860,7 @@ // If Chrome Home is enabled, the super of this function is not called because it only // performs unnecessary transformations on the theme color. if (getBottomSheet() != null) { - color = ApiCompatibilityUtils.getColor(getResources(), R.color.default_primary_color); - getBottomSheet().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR); - - // Special case the incognito NTP and the tab switcher. - if ((tab != null && NewTabPage.isNTPUrl(tab.getUrl()) && tab.isIncognito()) - || isInOverviewMode()) { - color = Color.BLACK; - } - ApiCompatibilityUtils.setStatusBarColor(getWindow(), color); + getBottomSheet().setStatusBarColor(getWindow()); return; }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/contextualsearch/ContextualSearchTabHelper.java b/chrome/android/java/src/org/chromium/chrome/browser/contextualsearch/ContextualSearchTabHelper.java index 64b1b440..afee12cb 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/contextualsearch/ContextualSearchTabHelper.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/contextualsearch/ContextualSearchTabHelper.java
@@ -118,6 +118,9 @@ if (mTemplateUrlObserver != null) { TemplateUrlService.getInstance().removeObserver(mTemplateUrlObserver); } + if (NetworkChangeNotifier.isInitialized()) { + NetworkChangeNotifier.removeConnectionTypeObserver(this); + } removeContextualSearchHooks(mBaseContentViewCore); mBaseContentViewCore = null; }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/download/DownloadNotificationService.java b/chrome/android/java/src/org/chromium/chrome/browser/download/DownloadNotificationService.java index 129aaf58..471fdd5 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/download/DownloadNotificationService.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/download/DownloadNotificationService.java
@@ -1214,7 +1214,10 @@ assert entry == null; resumeAllPendingDownloads(); } else if (ACTION_DOWNLOAD_OPEN.equals(intent.getAction())) { - OfflinePageDownloadBridge.openDownloadedPage(getContentIdFromIntent(intent)); + ContentId id = getContentIdFromIntent(intent); + if (LegacyHelpers.isLegacyOfflinePage(id)) { + OfflinePageDownloadBridge.openDownloadedPage(id); + } } else { Log.e(TAG, "Unrecognized intent action.", intent); }
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 3c28280..e5dc7328 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
@@ -39,7 +39,7 @@ import org.chromium.chrome.browser.download.ui.BackendProvider.DownloadDelegate; import org.chromium.chrome.browser.download.ui.DownloadFilter; import org.chromium.chrome.browser.download.ui.DownloadHistoryItemWrapper; -import org.chromium.chrome.browser.offlinepages.ClientId; +import org.chromium.chrome.browser.offlinepages.DownloadUiActionFlags; import org.chromium.chrome.browser.offlinepages.OfflinePageBridge; import org.chromium.chrome.browser.offlinepages.downloads.OfflinePageDownloadBridge; import org.chromium.chrome.browser.tab.Tab; @@ -205,10 +205,9 @@ if (tab.isShowingErrorPage()) { // The download needs to be scheduled to happen at later time due to current network // error. - ClientId clientId = ClientId.createGuidClientIdForNamespace( - OfflinePageBridge.ASYNC_NAMESPACE); final OfflinePageBridge bridge = OfflinePageBridge.getForProfile(tab.getProfile()); - bridge.savePageLater(tab.getUrl(), clientId, true /* userRequested */); + bridge.scheduleDownload(tab.getWebContents(), OfflinePageBridge.ASYNC_NAMESPACE, + tab.getUrl(), DownloadUiActionFlags.PROMPT_DUPLICATE); } else { // Otherwise, the download can be started immediately. final OfflinePageDownloadBridge bridge =
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/infobar/DuplicateDownloadInfoBar.java b/chrome/android/java/src/org/chromium/chrome/browser/infobar/DuplicateDownloadInfoBar.java index 43b90c4..8072b03 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/infobar/DuplicateDownloadInfoBar.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/infobar/DuplicateDownloadInfoBar.java
@@ -26,7 +26,8 @@ import java.io.File; /** - * An infobar to ask whether to proceed downloading a file that already exists locally. + * An infobar to ask whether to proceed downloading a file that already exists locally or is still + * being downloaded. */ public class DuplicateDownloadInfoBar extends ConfirmInfoBar { private static final String TAG = "DuplicateDownloadInfoBar"; @@ -34,13 +35,13 @@ private final boolean mIsOfflinePage; private final String mPageUrl; private final boolean mIsIncognito; + private final boolean mDuplicateRequestExists; @CalledByNative - private static InfoBar createInfoBar( - String filePath, boolean isOfflinePage, String pageUrl, boolean isIncognito) { - return new DuplicateDownloadInfoBar( - ContextUtils.getApplicationContext(), filePath, isOfflinePage, pageUrl, - isIncognito); + private static InfoBar createInfoBar(String filePath, boolean isOfflinePage, String pageUrl, + boolean isIncognito, boolean duplicateRequestExists) { + return new DuplicateDownloadInfoBar(ContextUtils.getApplicationContext(), filePath, + isOfflinePage, pageUrl, isIncognito, duplicateRequestExists); } /** @@ -50,10 +51,10 @@ * @param isOfflinePage Whether the download is for offline page. * @param pageUrl Url of the page, ignored if this is a regular download. * @param isIncognito Whether download is Incognito. + * @param duplicateRequestExists Whether the duplicate is a download in progress. */ - private DuplicateDownloadInfoBar( - Context context, String filePath, boolean isOfflinePage, String pageUrl, - boolean isIncognito) { + private DuplicateDownloadInfoBar(Context context, String filePath, boolean isOfflinePage, + String pageUrl, boolean isIncognito, boolean duplicateRequestExists) { super(R.drawable.infobar_downloading, null, null, null, context.getString(R.string.duplicate_download_infobar_download_button), context.getString(R.string.cancel)); @@ -61,6 +62,7 @@ mIsOfflinePage = isOfflinePage; mPageUrl = pageUrl; mIsIncognito = isIncognito; + mDuplicateRequestExists = duplicateRequestExists; } /** @@ -148,12 +150,13 @@ public void createContent(InfoBarLayout layout) { super.createContent(layout); Context context = layout.getContext(); + String template = context.getString(mDuplicateRequestExists + ? R.string.duplicate_download_request_infobar_text + : R.string.duplicate_download_infobar_text); if (mIsOfflinePage) { - layout.setMessage(getOfflinePageMessageText( - context, context.getString(R.string.duplicate_download_infobar_text))); + layout.setMessage(getOfflinePageMessageText(context, template)); } else { - layout.setMessage(getDownloadMessageText( - context, context.getString(R.string.duplicate_download_infobar_text))); + layout.setMessage(getDownloadMessageText(context, template)); } } }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/instantapps/InstantAppsHandler.java b/chrome/android/java/src/org/chromium/chrome/browser/instantapps/InstantAppsHandler.java index ea732313..a4b384a6 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/instantapps/InstantAppsHandler.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/instantapps/InstantAppsHandler.java
@@ -225,7 +225,7 @@ } if (IntentUtils.safeGetBooleanExtra(intent, DO_NOT_LAUNCH_EXTRA, false) - || ((intent.getFlags() & FLAG_DO_NOT_LAUNCH) != 0)) { + || (BuildInfo.isAtLeastO() && (intent.getFlags() & FLAG_DO_NOT_LAUNCH) != 0)) { maybeRecordFallbackStats(intent); Log.i(TAG, "Not handling with Instant Apps (DO_NOT_LAUNCH_EXTRA)"); return false;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/media/router/OWNERS b/chrome/android/java/src/org/chromium/chrome/browser/media/router/OWNERS index 7816a76..e98d2ad 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/media/router/OWNERS +++ b/chrome/android/java/src/org/chromium/chrome/browser/media/router/OWNERS
@@ -1,4 +1,5 @@ avayvod@chromium.org mlamouri@chromium.org +# TEAM: media-dev@chromium.org # COMPONENT: Blink>PresentationAPI
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/media/ui/OWNERS b/chrome/android/java/src/org/chromium/chrome/browser/media/ui/OWNERS index 68dc47e..65f7dae 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/media/ui/OWNERS +++ b/chrome/android/java/src/org/chromium/chrome/browser/media/ui/OWNERS
@@ -1,4 +1,5 @@ avayvod@chromium.org mlamouri@chromium.org +# TEAM: media-dev@chromium.org # COMPONENT: Internals>Media>UI
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/net/spdyproxy/DataReductionProxySettings.java b/chrome/android/java/src/org/chromium/chrome/browser/net/spdyproxy/DataReductionProxySettings.java index 85c9587..2ccd407 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/net/spdyproxy/DataReductionProxySettings.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/net/spdyproxy/DataReductionProxySettings.java
@@ -9,15 +9,20 @@ import android.text.TextUtils; import android.webkit.URLUtil; +import org.chromium.base.Callback; import org.chromium.base.ContextUtils; import org.chromium.base.ThreadUtils; import org.chromium.base.VisibleForTesting; import org.chromium.base.annotations.CalledByNative; import org.chromium.chrome.browser.ChromeFeatureList; import org.chromium.chrome.browser.UrlConstants; +import org.chromium.chrome.browser.preferences.datareduction.DataReductionDataUseItem; +import org.chromium.chrome.browser.preferences.datareduction.DataReductionPromoUtils; import java.text.NumberFormat; +import java.util.ArrayList; import java.util.HashMap; +import java.util.List; import java.util.Locale; import java.util.Map; @@ -69,6 +74,8 @@ private static final String WEBLITE_QUERY_PARAM = "lite_url"; + private Callback<List<DataReductionDataUseItem>> mQueryDataUsageCallback; + /** * Returns whether the data reduction proxy is enabled. * @@ -196,6 +203,16 @@ } /** + * Clears all data saving statistics. + */ + public void clearDataSavingStatistics() { + // When the data saving statistics are cleared, reset the snackbar promo that tells the user + // how much data they have saved using Data Saver so far. + DataReductionPromoUtils.saveSnackbarPromoDisplayed(0); + nativeClearDataSavingStatistics(mNativeDataReductionProxySettings); + } + + /** * Returns aggregate original and received content lengths. * @return The content lengths. */ @@ -304,6 +321,35 @@ return nativeAreLoFiPreviewsEnabled(mNativeDataReductionProxySettings); } + /** + * Queries native Data Reduction Proxy to get data use statistics. On query completion provides + * a list of DataReductionDataUseItem to the callback. + * + * @param numDays Number of days to get stats for. + * @param queryDataUsageCallback Callback to give the list of DataReductionDataUseItems on query + * completion. + */ + public void queryDataUsage( + int numDays, Callback<List<DataReductionDataUseItem>> queryDataUsageCallback) { + mQueryDataUsageCallback = queryDataUsageCallback; + nativeQueryDataUsage(mNativeDataReductionProxySettings, + new ArrayList<DataReductionDataUseItem>(), numDays); + } + + @CalledByNative + public static void createDataUseItemAndAddToList(List<DataReductionDataUseItem> items, + String hostname, long dataUsed, long originalSize) { + items.add(new DataReductionDataUseItem(hostname, dataUsed, originalSize)); + } + + @CalledByNative + public void onQueryDataUsageComplete(List<DataReductionDataUseItem> items) { + if (mQueryDataUsageCallback != null) { + mQueryDataUsageCallback.onResult(items); + } + mQueryDataUsageCallback = null; + } + private native long nativeInit(); private native boolean nativeIsDataReductionProxyPromoAllowed( long nativeDataReductionProxySettingsAndroid); @@ -315,6 +361,8 @@ long nativeDataReductionProxySettingsAndroid, boolean enabled); private native long nativeGetDataReductionLastUpdateTime( long nativeDataReductionProxySettingsAndroid); + private native void nativeClearDataSavingStatistics( + long nativeDataReductionProxySettingsAndroid); private native ContentLengths nativeGetContentLengths( long nativeDataReductionProxySettingsAndroid); private native long nativeGetTotalHttpContentLengthSaved( @@ -329,4 +377,6 @@ long nativeDataReductionProxySettingsAndroid); private native String nativeGetHttpProxyList(long nativeDataReductionProxySettingsAndroid); private native String nativeGetLastBypassEvent(long nativeDataReductionProxySettingsAndroid); + private native void nativeQueryDataUsage(long nativeDataReductionProxySettingsAndroid, + List<DataReductionDataUseItem> items, int numDays); }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/offlinepages/OfflinePageBridge.java b/chrome/android/java/src/org/chromium/chrome/browser/offlinepages/OfflinePageBridge.java index 04ee162..c73a508 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/offlinepages/OfflinePageBridge.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/offlinepages/OfflinePageBridge.java
@@ -454,6 +454,20 @@ nativeUnregisterRecentTab(mNativeOfflinePageBridge, tabId); } + /** + * Schedules to download a page from |url| and categorize under |nameSpace|. + * The duplicate pages or requests will be checked. + * + * @param webContents Web contents upon which the infobar is shown. + * @param nameSpace Namespace of the page to save. + * @param url URL of the page to save. + * @param uiAction UI action, like showing infobar or toast on certain case. + */ + public void scheduleDownload( + WebContents webContents, String nameSpace, String url, int uiAction) { + nativeScheduleDownload(mNativeOfflinePageBridge, webContents, nameSpace, url, uiAction); + } + @VisibleForTesting static void setOfflineBookmarksEnabledForTesting(boolean enabled) { sOfflineBookmarksEnabled = enabled; @@ -557,4 +571,6 @@ long nativeOfflinePageBridge, WebContents webContents); private native boolean nativeIsShowingDownloadButtonInErrorPage( long nativeOfflinePageBridge, WebContents webContents); + private native void nativeScheduleDownload(long nativeOfflinePageBridge, + WebContents webContents, String nameSpace, String url, int uiAction); }
diff --git a/components/payments/content/android/java/src/org/chromium/components/payments/JourneyLogger.java b/chrome/android/java/src/org/chromium/chrome/browser/payments/JourneyLogger.java similarity index 88% rename from components/payments/content/android/java/src/org/chromium/components/payments/JourneyLogger.java rename to chrome/android/java/src/org/chromium/chrome/browser/payments/JourneyLogger.java index d8408df2..4e295e37c 100644 --- a/components/payments/content/android/java/src/org/chromium/components/payments/JourneyLogger.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/payments/JourneyLogger.java
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -package org.chromium.components.payments; +package org.chromium.chrome.browser.payments; import org.chromium.base.annotations.JNINamespace; @@ -37,6 +37,13 @@ public static final int CMP_SHOW_COULD_MAKE_PAYMENT = 1 << 1; public static final int CMP_SHOW_MAX = 4; + // The events that can occur during a Payment Request. + public static final int EVENT_INITIATED = 0; + public static final int EVENT_SHOWN = 1 << 0; + public static final int EVENT_PAY_CLICKED = 1 << 1; + public static final int EVENT_RECEIVED_INSTRUMENT_DETAILS = 1 << 2; + public static final int EVENT_MAX = 8; + // The minimum expected value of CustomCountHistograms is always set to 1. It is still possible // to log the value 0 to that type of histogram. private static final int MIN_EXPECTED_SAMPLE = 1; @@ -48,10 +55,10 @@ */ private long mJourneyLoggerAndroid; - public JourneyLogger(boolean isIncognito) { + public JourneyLogger(boolean isIncognito, String url) { // Note that this pointer could leak the native object. The called must call destroy() to // ensure that the native object is destroyed. - mJourneyLoggerAndroid = nativeInitJourneyLoggerAndroid(isIncognito); + mJourneyLoggerAndroid = nativeInitJourneyLoggerAndroid(isIncognito, url); } /** Will destroy the native object. This class shouldn't be used afterwards. */ @@ -119,6 +126,14 @@ nativeSetShowCalled(mJourneyLoggerAndroid); } + /** + * Records that an event occurred. + */ + public void setEventOccurred(int event) { + assert event < EVENT_MAX; + nativeSetEventOccurred(mJourneyLoggerAndroid, event); + } + /* * Records the histograms for all the sections that were requested by the merchant and for the * usage of the CanMakePayment method and its effect on the transaction. This method should be @@ -130,7 +145,7 @@ nativeRecordJourneyStatsHistograms(mJourneyLoggerAndroid, completionStatus); } - private native long nativeInitJourneyLoggerAndroid(boolean isIncognito); + private native long nativeInitJourneyLoggerAndroid(boolean isIncognito, String url); private native void nativeDestroy(long nativeJourneyLoggerAndroid); private native void nativeSetNumberOfSuggestionsShown( long nativeJourneyLoggerAndroid, int section, int number); @@ -141,6 +156,7 @@ private native void nativeSetCanMakePaymentValue( long nativeJourneyLoggerAndroid, boolean value); private native void nativeSetShowCalled(long nativeJourneyLoggerAndroid); + private native void nativeSetEventOccurred(long nativeJourneyLoggerAndroid, int event); private native void nativeRecordJourneyStatsHistograms( long nativeJourneyLoggerAndroid, int completionStatus); } \ No newline at end of file
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 41176e4d..843622c 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
@@ -45,7 +45,6 @@ import org.chromium.chrome.browser.tabmodel.TabModelSelector; import org.chromium.chrome.browser.tabmodel.TabModelSelectorObserver; import org.chromium.components.payments.CurrencyFormatter; -import org.chromium.components.payments.JourneyLogger; import org.chromium.components.payments.PaymentValidator; import org.chromium.components.url_formatter.UrlFormatter; import org.chromium.content_public.browser.RenderFrameHost; @@ -381,7 +380,7 @@ mIsIncognito = activity != null && activity.getCurrentTabModel() != null && activity.getCurrentTabModel().isIncognito(); - mJourneyLogger = new JourneyLogger(mIsIncognito); + mJourneyLogger = new JourneyLogger(mIsIncognito, mWebContents.getLastCommittedUrl()); if (sCanMakePaymentQueries == null) sCanMakePaymentQueries = new ArrayMap<>(); @@ -600,6 +599,7 @@ mDidRecordShowEvent = true; mShouldRecordAbortReason = true; recordSuccessFunnelHistograms("Shown"); + mJourneyLogger.setEventOccurred(JourneyLogger.EVENT_SHOWN); mJourneyLogger.setShowCalled(); onPayClicked(null /* selectedShippingAddress */, null /* selectedShippingOption */, @@ -1199,6 +1199,7 @@ Collections.unmodifiableMap(modifiers), this); recordSuccessFunnelHistograms("PayClicked"); + mJourneyLogger.setEventOccurred(JourneyLogger.EVENT_PAY_CLICKED); return !(instrument instanceof AutofillPaymentInstrument); } @@ -1512,6 +1513,7 @@ if (mShouldSkipShowingPaymentRequestUi) mUI.showProcessingMessageAfterUiSkip(); recordSuccessFunnelHistograms("ReceivedInstrumentDetails"); + mJourneyLogger.setEventOccurred(JourneyLogger.EVENT_RECEIVED_INSTRUMENT_DETAILS); mPaymentResponseHelper.onInstrumentDetailsReceived(methodName, stringifiedDetails); }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/preferences/PrefServiceBridge.java b/chrome/android/java/src/org/chromium/chrome/browser/preferences/PrefServiceBridge.java index 1f98d61..29e545e2 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/preferences/PrefServiceBridge.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/preferences/PrefServiceBridge.java
@@ -15,8 +15,6 @@ import org.chromium.chrome.browser.ContentSettingsType; import org.chromium.chrome.browser.preferences.website.ContentSetting; import org.chromium.chrome.browser.preferences.website.ContentSettingException; -import org.chromium.chrome.browser.preferences.website.GeolocationInfo; -import org.chromium.chrome.browser.preferences.website.WebsitePreferenceBridge; import org.chromium.chrome.browser.search_engines.TemplateUrlService; import java.util.ArrayList; @@ -56,10 +54,6 @@ private static final String CONTEXTUAL_SEARCH_DISABLED = "false"; private static final String CONTEXTUAL_SEARCH_ENABLED = "true"; - // The key to store whether the Location Permission was automatically added for the search - // engine set as default. - public static final String LOCATION_AUTO_ALLOWED = "search_engine_location_auto_allowed"; - /** * Structure that holds all the version information about the current Chrome browser. */ @@ -130,28 +124,6 @@ } /** - * Add a permission entry for Location for the default search engine. - * @param allowed Whether to create an Allowed permission or a Denied permission. - * @param context The current context to use. - */ - public static void maybeCreatePermissionForDefaultSearchEngine( - boolean allowed, Context context) { - TemplateUrlService templateUrlService = TemplateUrlService.getInstance(); - String url = templateUrlService.getSearchEngineUrlFromTemplateUrl( - templateUrlService.getDefaultSearchEngineTemplateUrl().getKeyword()); - if (allowed && !url.startsWith("https:")) return; - GeolocationInfo locationSettings = new GeolocationInfo(url, null, false); - ContentSetting locationPermission = locationSettings.getContentSetting(); - if (locationPermission == null || locationPermission == ContentSetting.ASK) { - WebsitePreferenceBridge.nativeSetGeolocationSettingForOrigin(url, url, - allowed ? ContentSetting.ALLOW.toInt() : ContentSetting.BLOCK.toInt(), false); - SharedPreferences sharedPreferences = - ContextUtils.getAppSharedPreferences(); - sharedPreferences.edit().putBoolean(LOCATION_AUTO_ALLOWED, true).apply(); - } - } - - /** * Returns whether a particular content setting type is enabled. * @param contentSettingsType The content setting type to check. */
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/preferences/SearchEngineAdapter.java b/chrome/android/java/src/org/chromium/chrome/browser/preferences/SearchEngineAdapter.java index c1f246e..785c6fa5 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/preferences/SearchEngineAdapter.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/preferences/SearchEngineAdapter.java
@@ -6,7 +6,6 @@ import android.content.Context; import android.content.Intent; -import android.content.SharedPreferences; import android.content.res.Resources; import android.os.Build; import android.os.Bundle; @@ -25,7 +24,6 @@ import android.widget.TextView; import org.chromium.base.ApiCompatibilityUtils; -import org.chromium.base.ContextUtils; import org.chromium.base.Log; import org.chromium.base.VisibleForTesting; import org.chromium.base.metrics.RecordUserAction; @@ -346,16 +344,15 @@ assert false; link.setVisibility(View.GONE); } else if (selected) { - if (getLocationPermissionType(templateUrl, true) == ContentSetting.ASK) { + if (getLocationPermissionType(templateUrl) == ContentSetting.ASK) { link.setVisibility(View.GONE); } else { ForegroundColorSpan linkSpan = new ForegroundColorSpan( ApiCompatibilityUtils.getColor(resources, R.color.google_blue_700)); if (LocationUtils.getInstance().isSystemLocationSettingEnabled()) { - String message = mContext.getString( - locationEnabled(templateUrl, true) - ? R.string.search_engine_location_allowed - : R.string.search_engine_location_blocked); + String message = mContext.getString(locationEnabled(templateUrl) + ? R.string.search_engine_location_allowed + : R.string.search_engine_location_blocked); SpannableString messageWithLink = new SpannableString(message); messageWithLink.setSpan(linkSpan, 0, messageWithLink.length(), 0); link.setText(messageWithLink); @@ -398,21 +395,6 @@ } private String searchEngineSelected(int position) { - // First clean up any automatically added permissions (if any) for the previously selected - // search engine. - SharedPreferences sharedPreferences = - ContextUtils.getAppSharedPreferences(); - if (sharedPreferences.getBoolean(PrefServiceBridge.LOCATION_AUTO_ALLOWED, false)) { - TemplateUrl templateUrl = (TemplateUrl) getItem(mSelectedSearchEnginePosition); - if (locationEnabled(templateUrl, false)) { - String url = TemplateUrlService.getInstance().getSearchEngineUrlFromTemplateUrl( - templateUrl.getKeyword()); - WebsitePreferenceBridge.nativeSetGeolocationSettingForOrigin( - url, url, ContentSetting.DEFAULT.toInt(), false); - } - sharedPreferences.edit().remove(PrefServiceBridge.LOCATION_AUTO_ALLOWED).apply(); - } - // Record the change in search engine. mSelectedSearchEnginePosition = position; @@ -440,14 +422,13 @@ toKeyword(mSelectedSearchEnginePosition)); Bundle fragmentArgs = SingleWebsitePreferences.createFragmentArgsForSite(url); fragmentArgs.putBoolean(SingleWebsitePreferences.EXTRA_LOCATION, - locationEnabled((TemplateUrl) getItem(mSelectedSearchEnginePosition), true)); + locationEnabled((TemplateUrl) getItem(mSelectedSearchEnginePosition))); settingsIntent.putExtra(Preferences.EXTRA_SHOW_FRAGMENT_ARGUMENTS, fragmentArgs); mContext.startActivity(settingsIntent); } } - private ContentSetting getLocationPermissionType( - TemplateUrl templateUrl, boolean checkGeoHeader) { + private ContentSetting getLocationPermissionType(TemplateUrl templateUrl) { if (templateUrl == null) { Log.e(TAG, "Invalid null template URL found"); assert false; @@ -465,23 +446,21 @@ ContentSetting locationPermission = locationSettings.getContentSetting(); if (locationPermission == ContentSetting.ASK) { // Handle the case where the geoHeader being sent when no permission has been specified. - if (checkGeoHeader) { - if (ChromeFeatureList.isEnabled(ChromeFeatureList.CONSISTENT_OMNIBOX_GEOLOCATION)) { - if (WebsitePreferenceBridge.shouldUseDSEGeolocationSetting(url, false)) { - locationPermission = WebsitePreferenceBridge.getDSEGeolocationSetting() - ? ContentSetting.ALLOW - : ContentSetting.BLOCK; - } - } else if (GeolocationHeader.isGeoHeaderEnabledForUrl(url, false)) { - locationPermission = ContentSetting.ALLOW; + if (ChromeFeatureList.isEnabled(ChromeFeatureList.CONSISTENT_OMNIBOX_GEOLOCATION)) { + if (WebsitePreferenceBridge.shouldUseDSEGeolocationSetting(url, false)) { + locationPermission = WebsitePreferenceBridge.getDSEGeolocationSetting() + ? ContentSetting.ALLOW + : ContentSetting.BLOCK; } + } else if (GeolocationHeader.isGeoHeaderEnabledForUrl(url, false)) { + locationPermission = ContentSetting.ALLOW; } } return locationPermission; } - private boolean locationEnabled(TemplateUrl templateUrl, boolean checkGeoHeader) { - return getLocationPermissionType(templateUrl, checkGeoHeader) == ContentSetting.ALLOW; + private boolean locationEnabled(TemplateUrl templateUrl) { + return getLocationPermissionType(templateUrl) == ContentSetting.ALLOW; } private int computeStartIndexForRecentSearchEngines() {
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/preferences/datareduction/DataReductionDataUseItem.java b/chrome/android/java/src/org/chromium/chrome/browser/preferences/datareduction/DataReductionDataUseItem.java new file mode 100644 index 0000000..762689bd --- /dev/null +++ b/chrome/android/java/src/org/chromium/chrome/browser/preferences/datareduction/DataReductionDataUseItem.java
@@ -0,0 +1,73 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package org.chromium.chrome.browser.preferences.datareduction; + +import android.content.Context; +import android.text.format.Formatter; + +/** + * Stores the data used and saved by a hostname. + */ +public class DataReductionDataUseItem { + private String mHostname; + private long mDataUsed; + private long mOriginalSize; + + /** + * Constructor for a DataReductionDataUseItem which associates a hostname with its data usage + * and savings. + * + * @param hostname The hostname associated with this data usage. + * @param dataUsed The amount of data used by the host. + * @param originalSize The original size of the data. + */ + public DataReductionDataUseItem(String hostname, long dataUsed, long originalSize) { + mHostname = hostname; + mDataUsed = dataUsed; + mOriginalSize = originalSize; + } + + /** + * Returns the hostname for this data use item. + * @return The hostname. + */ + public String getHostname() { + return mHostname; + } + + /** + * Returns the amount of data used by the associated hostname. + * @return The data used. + */ + public long getDataUsed() { + return mDataUsed; + } + + /** + * Returns the amount of data saved by the associated hostname. + * @return The data saved. + */ + public long getDataSaved() { + return mOriginalSize - mDataUsed; + } + + /** + * Returns a formatted String of the data used by the associated hostname. + * @param context An Android context. + * @return A formatted string of the data used. + */ + public String getFormattedDataUsed(Context context) { + return Formatter.formatFileSize(context, mDataUsed); + } + + /** + * Returns a formatted String of the data saved by the associated hostname. + * @param context An Android context. + * @return A formatted string of the data saved. + */ + public String getFormattedDataSaved(Context context) { + return Formatter.formatFileSize(context, mOriginalSize - mDataUsed); + } +} \ No newline at end of file
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/preferences/datareduction/DataReductionPreferences.java b/chrome/android/java/src/org/chromium/chrome/browser/preferences/datareduction/DataReductionPreferences.java index f39be50..767d0b7 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/preferences/datareduction/DataReductionPreferences.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/preferences/datareduction/DataReductionPreferences.java
@@ -4,14 +4,11 @@ package org.chromium.chrome.browser.preferences.datareduction; -import static org.chromium.third_party.android.datausagechart.ChartDataUsageView.DAYS_IN_CHART; - import android.content.res.Resources; import android.os.Bundle; import android.preference.Preference; import android.preference.Preference.OnPreferenceChangeListener; import android.preference.PreferenceFragment; -import android.text.format.DateUtils; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; @@ -26,8 +23,6 @@ import org.chromium.chrome.browser.profiles.Profile; import org.chromium.chrome.browser.snackbar.DataReductionPromoSnackbarController; import org.chromium.chrome.browser.util.IntentUtils; -import org.chromium.third_party.android.datausagechart.NetworkStats; -import org.chromium.third_party.android.datausagechart.NetworkStatsHistory; /** * Settings fragment that allows the user to configure Data Saver. @@ -36,7 +31,6 @@ public static final String FROM_MAIN_MENU = "FromMainMenu"; public static final String PREF_DATA_REDUCTION_SWITCH = "data_reduction_switch"; - private static final String PREF_DATA_REDUCTION_STATS = "data_reduction_stats"; // This is the same as Chromium data_reduction_proxy::switches::kEnableDataReductionProxy. private static final String ENABLE_DATA_REDUCTION_PROXY = "enable-spdy-proxy-auth"; @@ -132,7 +126,6 @@ createDataReductionSwitch(isEnabled); if (isEnabled) { addPreferencesFromResource(R.xml.data_reduction_preferences); - updateReductionStatistics(); } else { addPreferencesFromResource(R.xml.data_reduction_preferences_off); } @@ -140,22 +133,6 @@ } /** - * Updates the preference screen to convey current statistics on data reduction. - */ - public void updateReductionStatistics() { - DataReductionProxySettings config = DataReductionProxySettings.getInstance(); - - DataReductionStatsPreference statsPref = (DataReductionStatsPreference) - getPreferenceScreen().findPreference(PREF_DATA_REDUCTION_STATS); - long original[] = config.getOriginalNetworkStatsHistory(); - long received[] = config.getReceivedNetworkStatsHistory(); - statsPref.setReductionStats( - config.getDataReductionLastUpdateTime(), - getNetworkStatsHistory(original, DAYS_IN_CHART), - getNetworkStatsHistory(received, DAYS_IN_CHART)); - } - - /** * Returns summary string. */ public static String generateSummary(Resources resources) { @@ -169,25 +146,6 @@ } } - private static NetworkStatsHistory getNetworkStatsHistory(long[] history, int days) { - if (days > history.length) days = history.length; - NetworkStatsHistory networkStatsHistory = - new NetworkStatsHistory( - DateUtils.DAY_IN_MILLIS, days, NetworkStatsHistory.FIELD_RX_BYTES); - - DataReductionProxySettings config = DataReductionProxySettings.getInstance(); - long time = config.getDataReductionLastUpdateTime() - days * DateUtils.DAY_IN_MILLIS; - for (int i = history.length - days, bucket = 0; i < history.length; i++, bucket++) { - NetworkStats.Entry entry = new NetworkStats.Entry(); - entry.rxBytes = history[i]; - long startTime = time + (DateUtils.DAY_IN_MILLIS * bucket); - // Spread each day's record over the first hour of the day. - networkStatsHistory.recordData( - startTime, startTime + DateUtils.HOUR_IN_MILLIS, entry); - } - return networkStatsHistory; - } - private void createDataReductionSwitch(boolean isEnabled) { final ChromeSwitchPreference dataReductionSwitch = new ChromeSwitchPreference(getActivity(), null);
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/preferences/datareduction/DataReductionSiteBreakdownView.java b/chrome/android/java/src/org/chromium/chrome/browser/preferences/datareduction/DataReductionSiteBreakdownView.java new file mode 100644 index 0000000..a2a1f97 --- /dev/null +++ b/chrome/android/java/src/org/chromium/chrome/browser/preferences/datareduction/DataReductionSiteBreakdownView.java
@@ -0,0 +1,134 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package org.chromium.chrome.browser.preferences.datareduction; + +import android.content.Context; +import android.text.format.Formatter; +import android.util.AttributeSet; +import android.view.LayoutInflater; +import android.widget.LinearLayout; +import android.widget.TableLayout; +import android.widget.TableRow; +import android.widget.TextView; + +import org.chromium.base.ApiCompatibilityUtils; +import org.chromium.chrome.R; + +import java.io.Serializable; +import java.util.Collections; +import java.util.Comparator; +import java.util.List; + +/** + * A site breakdown view to be used by the Data Saver settings page. It displays the top ten sites + * with the most data use or data savings. + */ +public class DataReductionSiteBreakdownView extends LinearLayout { + private static final int NUM_DATA_USE_ITEMS_TO_DISPLAY = 10; + + private TableLayout mTableLayout; + + public DataReductionSiteBreakdownView(Context context, AttributeSet attrs) { + super(context, attrs); + } + + @Override + protected void onFinishInflate() { + super.onFinishInflate(); + mTableLayout = (TableLayout) findViewById(R.id.data_reduction_proxy_breakdown_table); + } + + /** + * Display the data use items once they have been fetched from the compression stats. + * @param items A list of items split by hostname to show in the breakdown. + */ + public void onQueryDataUsageComplete(List<DataReductionDataUseItem> items) { + updateSiteBreakdown(items); + } + + /** + * Sorts the DataReductionDataUseItems by most to least data used. + */ + private static final class DataUsedComparator + implements Comparator<DataReductionDataUseItem>, Serializable { + @Override + public int compare(DataReductionDataUseItem lhs, DataReductionDataUseItem rhs) { + if (lhs.getDataUsed() < rhs.getDataUsed()) { + return 1; + } else if (lhs.getDataUsed() > rhs.getDataUsed()) { + return -1; + } + return 0; + } + } + + /** + * Update the site breakdown to display the given date use items. + * @param items A list of items split by hostname to show in the breakdown. + */ + private void updateSiteBreakdown(List<DataReductionDataUseItem> items) { + if (items.size() == 0) { + setVisibility(GONE); + return; + } + + setVisibility(VISIBLE); + // Remove all old rows except the header. + mTableLayout.removeViews(1, mTableLayout.getChildCount() - 1); + final DataUsedComparator comp = new DataUsedComparator(); + Collections.sort(items, comp); + + int numRemainingSites = 0; + int everythingElseDataUsage = 0; + int everythingElseDataSavings = 0; + + for (int i = 0; i < items.size(); i++) { + if (i < NUM_DATA_USE_ITEMS_TO_DISPLAY) { + TableRow row = (TableRow) LayoutInflater.from(getContext()) + .inflate(R.layout.data_usage_breakdown_row, null); + + TextView hostnameView = (TextView) row.findViewById(R.id.site_hostname); + TextView dataUsedView = (TextView) row.findViewById(R.id.site_data_used); + TextView dataSavedView = (TextView) row.findViewById(R.id.site_data_saved); + + hostnameView.setText(items.get(i).getHostname()); + dataUsedView.setText(items.get(i).getFormattedDataUsed(getContext())); + dataSavedView.setText(items.get(i).getFormattedDataSaved(getContext())); + + mTableLayout.addView(row, i + 1); + } else { + numRemainingSites++; + everythingElseDataUsage += items.get(i).getDataUsed(); + everythingElseDataSavings += items.get(i).getDataSaved(); + } + } + + if (numRemainingSites > 0) { + TableRow row = (TableRow) LayoutInflater.from(getContext()) + .inflate(R.layout.data_usage_breakdown_row, null); + + TextView hostnameView = (TextView) row.findViewById(R.id.site_hostname); + TextView dataUsedView = (TextView) row.findViewById(R.id.site_data_used); + TextView dataSavedView = (TextView) row.findViewById(R.id.site_data_saved); + + hostnameView.setText(getResources().getString( + R.string.data_reduction_breakdown_remaining_sites_label, numRemainingSites)); + dataUsedView.setText(Formatter.formatFileSize(getContext(), everythingElseDataUsage)); + dataSavedView.setText( + Formatter.formatFileSize(getContext(), everythingElseDataSavings)); + + int lightActiveColor = ApiCompatibilityUtils.getColor( + getContext().getResources(), R.color.light_active_color); + + hostnameView.setTextColor(lightActiveColor); + dataUsedView.setTextColor(lightActiveColor); + dataSavedView.setTextColor(lightActiveColor); + + mTableLayout.addView(row, NUM_DATA_USE_ITEMS_TO_DISPLAY + 1); + } + + mTableLayout.requestLayout(); + } +} \ No newline at end of file
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/preferences/datareduction/DataReductionStatsPreference.java b/chrome/android/java/src/org/chromium/chrome/browser/preferences/datareduction/DataReductionStatsPreference.java index ee08ac48..4c3f177 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/preferences/datareduction/DataReductionStatsPreference.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/preferences/datareduction/DataReductionStatsPreference.java
@@ -16,13 +16,19 @@ import android.text.format.Formatter; import android.util.AttributeSet; import android.view.View; +import android.view.View.OnClickListener; +import android.widget.Button; import android.widget.TextView; +import org.chromium.base.Callback; import org.chromium.chrome.R; +import org.chromium.chrome.browser.ChromeFeatureList; import org.chromium.chrome.browser.net.spdyproxy.DataReductionProxySettings; import org.chromium.third_party.android.datausagechart.ChartDataUsageView; +import org.chromium.third_party.android.datausagechart.NetworkStats; import org.chromium.third_party.android.datausagechart.NetworkStatsHistory; +import java.util.List; import java.util.TimeZone; /** @@ -34,54 +40,32 @@ private TextView mOriginalSizeTextView; private TextView mReceivedSizeTextView; + private TextView mDataSavingsTextView; + private TextView mDataUsageTextView; private TextView mPercentReductionTextView; private TextView mStartDateTextView; private TextView mEndDateTextView; + private Button mResetStatisticsButton; private ChartDataUsageView mChartDataUsageView; + private DataReductionSiteBreakdownView mDataReductionBreakdownView; private long mLeftPosition; private long mRightPosition; private Long mCurrentTime; private String mOriginalTotalPhrase; + private String mSavingsTotalPhrase; private String mReceivedTotalPhrase; private String mPercentReductionPhrase; private String mStartDatePhrase; private String mEndDatePhrase; - public DataReductionStatsPreference( - Context context, AttributeSet attrs, int defStyle) { - super(context, attrs, defStyle); - setWidgetLayoutResource(R.layout.data_reduction_stats_layout); - } - public DataReductionStatsPreference(Context context, AttributeSet attrs) { super(context, attrs); - setWidgetLayoutResource(R.layout.data_reduction_stats_layout); - } - public DataReductionStatsPreference(Context context) { - super(context); - setWidgetLayoutResource(R.layout.data_reduction_stats_layout); - } - - /** - * Sets the current statistics for viewing. These include the original total daily size of - * received resources before compression, and the actual total daily size of received - * resources after compression. The last update time is specified in milliseconds since the - * epoch. - * @param lastUpdateTimeMillis The last time the statistics were updated. - * @param networkStatsHistoryOriginal The history of original content lengths. - * @param networkStatsHistoryReceived The history of received content lengths. - */ - public void setReductionStats( - long lastUpdateTimeMillis, - NetworkStatsHistory networkStatsHistoryOriginal, - NetworkStatsHistory networkStatsHistoryReceived) { - mCurrentTime = lastUpdateTimeMillis; - mRightPosition = mCurrentTime + DateUtils.HOUR_IN_MILLIS - - TimeZone.getDefault().getOffset(mCurrentTime); - mLeftPosition = lastUpdateTimeMillis - DateUtils.DAY_IN_MILLIS * DAYS_IN_CHART; - mOriginalNetworkStatsHistory = networkStatsHistoryOriginal; - mReceivedNetworkStatsHistory = networkStatsHistoryReceived; + if (ChromeFeatureList.isEnabled(ChromeFeatureList.DATA_REDUCTION_SITE_BREAKDOWN)) { + setWidgetLayoutResource(R.layout.data_reduction_stats_layout); + } else { + setWidgetLayoutResource(R.layout.data_reduction_old_stats_layout); + } } @Override @@ -90,23 +74,76 @@ } /** + * Updates the preference screen to convey current statistics on data reduction. + */ + public void updateReductionStatistics() { + long original[] = DataReductionProxySettings.getInstance().getOriginalNetworkStatsHistory(); + long received[] = DataReductionProxySettings.getInstance().getReceivedNetworkStatsHistory(); + + mCurrentTime = DataReductionProxySettings.getInstance().getDataReductionLastUpdateTime(); + mRightPosition = mCurrentTime + DateUtils.HOUR_IN_MILLIS + - TimeZone.getDefault().getOffset(mCurrentTime); + mLeftPosition = mCurrentTime - DateUtils.DAY_IN_MILLIS * DAYS_IN_CHART; + mOriginalNetworkStatsHistory = getNetworkStatsHistory(original, DAYS_IN_CHART); + mReceivedNetworkStatsHistory = getNetworkStatsHistory(received, DAYS_IN_CHART); + + if (mDataReductionBreakdownView != null) { + DataReductionProxySettings.getInstance().queryDataUsage( + DAYS_IN_CHART, new Callback<List<DataReductionDataUseItem>>() { + @Override + public void onResult(List<DataReductionDataUseItem> result) { + mDataReductionBreakdownView.onQueryDataUsageComplete(result); + } + }); + } + } + + private static NetworkStatsHistory getNetworkStatsHistory(long[] history, int days) { + if (days > history.length) days = history.length; + NetworkStatsHistory networkStatsHistory = new NetworkStatsHistory( + DateUtils.DAY_IN_MILLIS, days, NetworkStatsHistory.FIELD_RX_BYTES); + + DataReductionProxySettings config = DataReductionProxySettings.getInstance(); + long time = config.getDataReductionLastUpdateTime() - days * DateUtils.DAY_IN_MILLIS; + for (int i = history.length - days, bucket = 0; i < history.length; i++, bucket++) { + NetworkStats.Entry entry = new NetworkStats.Entry(); + entry.rxBytes = history[i]; + long startTime = time + (DateUtils.DAY_IN_MILLIS * bucket); + // Spread each day's record over the first hour of the day. + networkStatsHistory.recordData(startTime, startTime + DateUtils.HOUR_IN_MILLIS, entry); + } + return networkStatsHistory; + } + + private void setDetailText() { + updateDetailData(); + mPercentReductionTextView.setText(mPercentReductionPhrase); + mStartDateTextView.setText(mStartDatePhrase); + mEndDateTextView.setText(mEndDatePhrase); + if (mDataUsageTextView != null) mDataUsageTextView.setText(mReceivedTotalPhrase); + if (mDataSavingsTextView != null) mDataSavingsTextView.setText(mSavingsTotalPhrase); + if (mOriginalSizeTextView != null) mOriginalSizeTextView.setText(mOriginalTotalPhrase); + if (mReceivedSizeTextView != null) mReceivedSizeTextView.setText(mReceivedTotalPhrase); + } + + /** * Sets up a data usage chart and text views containing data reduction statistics. * @param view The current view. */ @Override protected void onBindView(View view) { super.onBindView(view); - if (mOriginalTotalPhrase == null) updateDetailData(); + mDataUsageTextView = (TextView) view.findViewById(R.id.data_reduction_usage); + mDataSavingsTextView = (TextView) view.findViewById(R.id.data_reduction_savings); mOriginalSizeTextView = (TextView) view.findViewById(R.id.data_reduction_original_size); - mOriginalSizeTextView.setText(mOriginalTotalPhrase); mReceivedSizeTextView = (TextView) view.findViewById(R.id.data_reduction_compressed_size); - mReceivedSizeTextView.setText(mReceivedTotalPhrase); mPercentReductionTextView = (TextView) view.findViewById(R.id.data_reduction_percent); - mPercentReductionTextView.setText(mPercentReductionPhrase); mStartDateTextView = (TextView) view.findViewById(R.id.data_reduction_start_date); - mStartDateTextView.setText(mStartDatePhrase); mEndDateTextView = (TextView) view.findViewById(R.id.data_reduction_end_date); - mEndDateTextView.setText(mEndDatePhrase); + mDataReductionBreakdownView = + (DataReductionSiteBreakdownView) view.findViewById(R.id.breakdown); + updateReductionStatistics(); + setDetailText(); mChartDataUsageView = (ChartDataUsageView) view.findViewById(R.id.chart); mChartDataUsageView.bindOriginalNetworkStats(mOriginalNetworkStatsHistory); @@ -122,6 +159,19 @@ } else { dataReductionProxyUnreachableWarning.setVisibility(View.GONE); } + + mResetStatisticsButton = (Button) view.findViewById(R.id.data_reduction_reset_statistics); + if (mResetStatisticsButton != null) { + mResetStatisticsButton.setOnClickListener(new OnClickListener() { + @Override + public void onClick(View view) { + DataReductionProxySettings.getInstance().clearDataSavingStatistics(); + updateReductionStatistics(); + setDetailText(); + notifyChanged(); + } + }); + } } /** @@ -140,18 +190,20 @@ final long now = mCurrentTime; final Context context = getContext(); - NetworkStatsHistory.Entry originalEntry = - mOriginalNetworkStatsHistory.getValues(start, end, now, null); - // Only received bytes are tracked. - final long originalTotalBytes = originalEntry.rxBytes; - mOriginalTotalPhrase = Formatter.formatFileSize(context, originalTotalBytes); - NetworkStatsHistory.Entry compressedEntry = mReceivedNetworkStatsHistory.getValues(start, end, now, null); // Only received bytes are tracked. final long compressedTotalBytes = compressedEntry.rxBytes; mReceivedTotalPhrase = Formatter.formatFileSize(context, compressedTotalBytes); + NetworkStatsHistory.Entry originalEntry = + mOriginalNetworkStatsHistory.getValues(start, end, now, null); + // Only received bytes are tracked. + final long originalTotalBytes = originalEntry.rxBytes; + mOriginalTotalPhrase = Formatter.formatFileSize(context, originalTotalBytes); + mSavingsTotalPhrase = + Formatter.formatFileSize(context, originalTotalBytes - compressedTotalBytes); + float percentage = 0.0f; if (originalTotalBytes > 0L && originalTotalBytes > compressedTotalBytes) { percentage = (originalTotalBytes - compressedTotalBytes) / (float) originalTotalBytes;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/snackbar/Snackbar.java b/chrome/android/java/src/org/chromium/chrome/browser/snackbar/Snackbar.java index 5109cee..6bb64410 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/snackbar/Snackbar.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/snackbar/Snackbar.java
@@ -6,6 +6,7 @@ import android.graphics.Bitmap; +import org.chromium.base.VisibleForTesting; import org.chromium.chrome.browser.snackbar.SnackbarManager.SnackbarController; /** @@ -146,7 +147,11 @@ return this; } - SnackbarController getController() { + /** + * @return The {@link SnackbarController} that controls this snackbar. + */ + @VisibleForTesting + public SnackbarController getController() { return mController; }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/snackbar/undo/UndoBarController.java b/chrome/android/java/src/org/chromium/chrome/browser/snackbar/undo/UndoBarController.java index 2c087f4..92a0ac9 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/snackbar/undo/UndoBarController.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/snackbar/undo/UndoBarController.java
@@ -85,9 +85,15 @@ } @Override - public void allTabsPendingClosure(List<Integer> tabIds) { + public void allTabsPendingClosure(List<Tab> tabs) { if (disableUndo()) return; - showUndoCloseAllBar(tabIds); + + if (tabs.size() == 1) { + tabPendingClosure(tabs.get(0)); + return; + } + + showUndoCloseAllBar(tabs); } @Override @@ -139,15 +145,14 @@ * for each tab in {@code closedTabIds}. This will happen unless * {@code SnackbarManager#removeFromStackForData(Object)} is called. * - * @param closedTabIds A list of ids corresponding to tabs that were closed + * @param closedTabs A list of tabs that were closed. */ - private void showUndoCloseAllBar(List<Integer> closedTabIds) { - String content = String.format(Locale.getDefault(), "%d", closedTabIds.size()); + private void showUndoCloseAllBar(List<Tab> closedTabs) { + String content = String.format(Locale.getDefault(), "%d", closedTabs.size()); mSnackbarManager.showSnackbar( Snackbar.make(content, this, Snackbar.TYPE_ACTION, Snackbar.UMA_TAB_CLOSE_ALL_UNDO) - .setTemplateText(mContext.getString(R.string.undo_bar_close_all_message)) - .setAction(mContext.getString(R.string.undo), closedTabIds)); - + .setTemplateText(mContext.getString(R.string.undo_bar_close_all_message)) + .setAction(mContext.getString(R.string.undo), closedTabs)); } /** @@ -162,8 +167,8 @@ if (actionData instanceof Integer) { cancelTabClosure((Integer) actionData); } else { - for (Integer id : (List<Integer>) actionData) { - cancelTabClosure(id); + for (Tab tab : (List<Tab>) actionData) { + cancelTabClosure(tab.getId()); } } } @@ -183,8 +188,8 @@ if (actionData instanceof Integer) { commitTabClosure((Integer) actionData); } else { - for (Integer tabId : (List<Integer>) actionData) { - commitTabClosure(tabId); + for (Tab tab : (List<Tab>) actionData) { + commitTabClosure(tab.getId()); } } }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/suggestions/SuggestionsNavigationDelegateImpl.java b/chrome/android/java/src/org/chromium/chrome/browser/suggestions/SuggestionsNavigationDelegateImpl.java index 4f2f0f4..3525b2ca4 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/suggestions/SuggestionsNavigationDelegateImpl.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/suggestions/SuggestionsNavigationDelegateImpl.java
@@ -15,9 +15,9 @@ import org.chromium.chrome.browser.ntp.NewTabPageUma; import org.chromium.chrome.browser.ntp.snippets.KnownCategories; import org.chromium.chrome.browser.ntp.snippets.SnippetArticle; +import org.chromium.chrome.browser.offlinepages.DownloadUiActionFlags; import org.chromium.chrome.browser.offlinepages.OfflinePageBridge; import org.chromium.chrome.browser.offlinepages.OfflinePageUtils; -import org.chromium.chrome.browser.offlinepages.downloads.OfflinePageNotificationBridge; import org.chromium.chrome.browser.preferences.PrefServiceBridge; import org.chromium.chrome.browser.profiles.Profile; import org.chromium.chrome.browser.tabmodel.TabModel; @@ -185,8 +185,8 @@ } private void saveUrlForOffline(String url) { - OfflinePageNotificationBridge.showDownloadingToast(); - OfflinePageBridge.getForProfile(mProfile).savePageLater( - url, "ntp_suggestions", true /* userRequested */); + OfflinePageBridge.getForProfile(mProfile).scheduleDownload( + mHost.getActiveTab().getWebContents(), "ntp_suggestions", url, + DownloadUiActionFlags.ALL); } }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/tabmodel/EmptyTabModelObserver.java b/chrome/android/java/src/org/chromium/chrome/browser/tabmodel/EmptyTabModelObserver.java index 2a087e9..04b51c07 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/tabmodel/EmptyTabModelObserver.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/tabmodel/EmptyTabModelObserver.java
@@ -14,52 +14,39 @@ * An empty base implementation of the TabModelObserver interface. */ public class EmptyTabModelObserver implements TabModelObserver { + @Override + public void didSelectTab(Tab tab, TabSelectionType type, int lastId) {} @Override - public void didSelectTab(Tab tab, TabSelectionType type, int lastId) { - } + public void willCloseTab(Tab tab, boolean animate) {} @Override - public void willCloseTab(Tab tab, boolean animate) { - } + public void didCloseTab(int tabId, boolean incognito) {} @Override - public void didCloseTab(int tabId, boolean incognito) { - } + public void willAddTab(Tab tab, TabLaunchType type) {} @Override - public void willAddTab(Tab tab, TabLaunchType type) { - } + public void didAddTab(Tab tab, TabLaunchType type) {} @Override - public void didAddTab(Tab tab, TabLaunchType type) { - } + public void didMoveTab(Tab tab, int newIndex, int curIndex) {} @Override - public void didMoveTab(Tab tab, int newIndex, int curIndex) { - } + public void tabPendingClosure(Tab tab) {} @Override - public void tabPendingClosure(Tab tab) { - } + public void tabClosureUndone(Tab tab) {} @Override - public void tabClosureUndone(Tab tab) { - } + public void tabClosureCommitted(Tab tab) {} @Override - public void tabClosureCommitted(Tab tab) { - } + public void allTabsPendingClosure(List<Tab> tabs) {} @Override - public void allTabsPendingClosure(List<Integer> tabIds) { - } + public void allTabsClosureCommitted() {} @Override - public void allTabsClosureCommitted() { - } - - @Override - public void tabRemoved(Tab tab) { - } + public void tabRemoved(Tab tab) {} }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/tabmodel/TabModelImpl.java b/chrome/android/java/src/org/chromium/chrome/browser/tabmodel/TabModelImpl.java index a3cd928..2d25b873 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/tabmodel/TabModelImpl.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/tabmodel/TabModelImpl.java
@@ -399,11 +399,6 @@ return; } - if (getCount() == 1) { - closeTab(getTabAt(0), true, false, true); - return; - } - closeAllTabs(true, false, true); } @@ -422,10 +417,10 @@ public void closeAllTabs(boolean animate, boolean uponExit, boolean canUndo) { for (int i = 0; i < getCount(); i++) getTabAt(i).setClosing(true); - ArrayList<Integer> closedTabs = new ArrayList<Integer>(); + List<Tab> closedTabs = new ArrayList<>(); while (getCount() > 0) { Tab tab = getTabAt(0); - closedTabs.add(tab.getId()); + closedTabs.add(tab); closeTab(tab, animate, uponExit, canUndo, false); }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/tabmodel/TabModelObserver.java b/chrome/android/java/src/org/chromium/chrome/browser/tabmodel/TabModelObserver.java index 63d44f1..44d94c3 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/tabmodel/TabModelObserver.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/tabmodel/TabModelObserver.java
@@ -92,9 +92,9 @@ /** * Called when "all tabs" are pending closure. * - * @param tabIds The list of tabs IDs that are pending closure. + * @param tabs The tabs that are pending closure. */ - void allTabsPendingClosure(List<Integer> tabIds); + void allTabsPendingClosure(List<Tab> tabs); /** * Called when an "all tabs" closure has been committed and can't be undone anymore.
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/toolbar/ToolbarManager.java b/chrome/android/java/src/org/chromium/chrome/browser/toolbar/ToolbarManager.java index 8a2374e..71b17dd 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/toolbar/ToolbarManager.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/toolbar/ToolbarManager.java
@@ -295,7 +295,7 @@ } @Override - public void allTabsPendingClosure(List<Integer> tabIds) { + public void allTabsPendingClosure(List<Tab> tabs) { updateTabCount(); refreshSelectedTab(); }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/widget/bottomsheet/BottomSheet.java b/chrome/android/java/src/org/chromium/chrome/browser/widget/bottomsheet/BottomSheet.java index 45ffb7f..0004325 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/widget/bottomsheet/BottomSheet.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/widget/bottomsheet/BottomSheet.java
@@ -9,7 +9,9 @@ import android.animation.ObjectAnimator; import android.animation.ValueAnimator; import android.content.Context; +import android.graphics.Color; import android.graphics.Region; +import android.os.Build; import android.support.annotation.IntDef; import android.support.annotation.Nullable; import android.util.AttributeSet; @@ -17,6 +19,7 @@ import android.view.MotionEvent; import android.view.VelocityTracker; import android.view.View; +import android.view.Window; import android.view.animation.DecelerateInterpolator; import android.view.animation.Interpolator; import android.widget.FrameLayout; @@ -29,6 +32,7 @@ import org.chromium.chrome.browser.TabLoadStatus; import org.chromium.chrome.browser.fullscreen.ChromeFullscreenManager; import org.chromium.chrome.browser.ntp.NativePageFactory; +import org.chromium.chrome.browser.ntp.NewTabPage; import org.chromium.chrome.browser.tab.Tab; import org.chromium.chrome.browser.tabmodel.TabModel; import org.chromium.chrome.browser.tabmodel.TabModelSelector; @@ -402,6 +406,32 @@ } /** + * Set the window's status bar color. On Android M and above, this will set the status bar color + * to the default theme color with dark icons except in the case of the tab switcher and + * incognito NTP. On Android versions < M, the status bar will always be black. + * @param window The Android window. + */ + public void setStatusBarColor(Window window) { + Tab tab = getActiveTab(); + boolean isInOverviewMode = tab != null && tab.getActivity().isInOverviewMode(); + boolean isIncognitoNtp = + tab != null && NewTabPage.isNTPUrl(tab.getUrl()) && tab.isIncognito(); + boolean isValidAndroidVersion = Build.VERSION.SDK_INT >= Build.VERSION_CODES.M; + + int color = ApiCompatibilityUtils.getColor(getResources(), R.color.default_primary_color); + setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR); + + // Special case the incognito NTP and the tab switcher. + if (!isValidAndroidVersion || isIncognitoNtp || isInOverviewMode) { + color = Color.BLACK; + // The light status bar flag is always set above, meaning XORing that value with the + // current flags will remove it. + setSystemUiVisibility(getSystemUiVisibility() ^ View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR); + } + ApiCompatibilityUtils.setStatusBarColor(window, color); + } + + /** * @return Whether or not the toolbar Android View is hidden due to being scrolled off-screen. */ private boolean isToolbarAndroidViewHidden() { @@ -508,7 +538,7 @@ @Override public Tab getActiveTab() { - return mTabModelSelector.getCurrentTab(); + return mTabModelSelector == null ? null : mTabModelSelector.getCurrentTab(); } @Override
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/widget/emptybackground/EmptyBackgroundViewWrapper.java b/chrome/android/java/src/org/chromium/chrome/browser/widget/emptybackground/EmptyBackgroundViewWrapper.java index fe230ff..cfe5b35 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/widget/emptybackground/EmptyBackgroundViewWrapper.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/widget/emptybackground/EmptyBackgroundViewWrapper.java
@@ -84,7 +84,7 @@ } @Override - public void allTabsPendingClosure(List<Integer> tabIds) { + public void allTabsPendingClosure(List<Tab> tabs) { updateEmptyContainerState(); }
diff --git a/chrome/android/java/strings/android_chrome_strings.grd b/chrome/android/java/strings/android_chrome_strings.grd index 372e2fb8..4cb829e 100644 --- a/chrome/android/java/strings/android_chrome_strings.grd +++ b/chrome/android/java/strings/android_chrome_strings.grd
@@ -978,6 +978,41 @@ <message name="IDS_DATA_REDUCTION_MENU_ITEM_SUMMARY" desc="Summary text for data reduction menu item."> <ph name="PERCENT">%1$s<ex>49%</ex></ph> data savings </message> + <message name="IDS_DATA_REDUCTION_SAVINGS_LABEL" desc="Data Reduction statistics data savings label"> + Data Savings: + </message> + <message name="IDS_DATA_REDUCTION_USAGE_LABEL" desc="Data Reduction statistics data usage label"> + Data Usage: + </message> + <message name="IDS_DATA_REDUCTION_PROXY_UNREACHABLE_WARN" desc="Warning message shown when Google data reduction proxy servers are not reachable."> + Chrome is unable to reach Google servers for data compression. Your data savings may be limited. + </message> + <message name="IDS_DATA_REDUCTION_DATA_USAGE_BREAKDOWN_TITLE" desc="Title for the data usage breakdown on the Data Reduction statistics page. The breakdown lists the top ten sites with the greatest amount of data usage or mobile data that was saved."> + Data Usage Breakdown + </message> + <message name="IDS_DATA_REDUCTION_BREAKDOWN_SITE_TITLE" desc="Title for the sites column on the Data Reduction statistics page. The breakdown lists the top ten sites with the greatest amount of data usage or mobile data that was saved."> + Site + </message> + <message name="IDS_DATA_REDUCTION_BREAKDOWN_USED_TITLE" desc="Title for the data used column on the Data Reduction statistics page. The breakdown lists the top ten sites with the greatest amount of data usage or mobile data that was saved."> + Used + </message> + <message name="IDS_DATA_REDUCTION_BREAKDOWN_SAVED_TITLE" desc="Title for the data saved column on the Data Reduction statistics page. The breakdown lists for the top ten sites with the greatest amount of data usage or mobile data that was saved. Data Saver allows users to to reduce their mobile data usage by compressing network traffic."> + Saved + </message> + <message name="IDS_DATA_REDUCTION_BREAKDOWN_REMAINING_SITES_LABEL" desc="Title for the the remaining sites on the Data Reduction statistics page. The breakdown lists the top ten sites with the greatest amount of data usage or mobile data that was saved and then groups the remaining sites together."> + Remaining sites (<ph name="NUMBER_OF_SITES">%1$d<ex>35</ex></ph>) + </message> + <message name="IDS_DATA_REDUCTION_USAGE_RESET_STATISTICS_BUTTON" desc="Text to be displayed on the button to reset the Data Reduction statistics."> + Reset Statistics + </message> + <message name="IDS_SAFE_BROWSING_DESCRIPTION" desc="Description text for safe browsing"> + Chrome’s Safe Browsing system will also be used to detect malicious pages and protect you from phishing, malware, and harmful downloads. + </message> + <message name="IDS_DATA_REDUCTION_CAVEATS_DESCRIPTION" desc="Description text for usage caveats"> + This feature may interfere with access to premium data services provided by your carrier. + </message> + + <!-- Old Data Saver stats page strings--> <message name="IDS_DATA_REDUCTION_STATS_TITLE" desc="Data reduction statistics title."> Data savings </message> @@ -987,15 +1022,6 @@ <message name="IDS_DATA_REDUCTION_COMPRESSED_SIZE_LABEL" desc="Data Reduction statistics compressed size label"> After compression </message> - <message name="IDS_DATA_REDUCTION_PROXY_UNREACHABLE_WARN" desc="Warning message shown when Google data reduction proxy servers are not reachable."> - Chrome is unable to reach Google servers for data compression. Your data savings may be limited. - </message> - <message name="IDS_SAFE_BROWSING_DESCRIPTION" desc="Description text for safe browsing"> - Chrome’s Safe Browsing system will also be used to detect malicious pages and protect you from phishing, malware, and harmful downloads. - </message> - <message name="IDS_DATA_REDUCTION_CAVEATS_DESCRIPTION" desc="Description text for usage caveats"> - This feature may interfere with access to premium data services provided by your carrier. - </message> <!-- Data Saver Promo and FRE card --> <message name="IDS_DATA_REDUCTION_PROMO_TITLE" desc="The title for the promo inviting users to enable Data Saver" > @@ -1464,6 +1490,9 @@ <message name="IDS_DUPLICATE_DOWNLOAD_INFOBAR_TEXT" desc="Prompt text for the confirmation dialog asking whether the user really wants to download a file when there already exists a file with the same name"> Do you want to download <ph name="FILE_NAME">^1<ex>specialfile.pdf</ex></ph> again? </message> + <message name="IDS_DUPLICATE_DOWNLOAD_REQUEST_INFOBAR_TEXT" desc="Prompt text for the confirmation dialog asking whether the user really wants to download a file when a file with the same name is still being downloaded"> + Do you want to start downloading <ph name="FILE_NAME">^1<ex>specialfile.pdf</ex></ph> again? + </message> <message name="IDS_DUPLICATE_DOWNLOAD_INFOBAR_DOWNLOAD_BUTTON" desc="Label for the button that confirms that a user wants to download the file again. [CHAR-LIMIT=32]"> Download </message>
diff --git a/chrome/android/java_sources.gni b/chrome/android/java_sources.gni index 8d9dd54c..981c04c 100644 --- a/chrome/android/java_sources.gni +++ b/chrome/android/java_sources.gni
@@ -725,6 +725,7 @@ "java/src/org/chromium/chrome/browser/payments/CardEditor.java", "java/src/org/chromium/chrome/browser/payments/ContactEditor.java", "java/src/org/chromium/chrome/browser/payments/EditorBase.java", + "java/src/org/chromium/chrome/browser/payments/JourneyLogger.java", "java/src/org/chromium/chrome/browser/payments/PackageManagerDelegate.java", "java/src/org/chromium/chrome/browser/payments/PaymentApp.java", "java/src/org/chromium/chrome/browser/payments/PaymentAppFactory.java", @@ -854,11 +855,13 @@ "java/src/org/chromium/chrome/browser/preferences/autofill/AutofillServerProfilePreferences.java", "java/src/org/chromium/chrome/browser/preferences/autofill/CreditCardNumberFormattingTextWatcher.java", "java/src/org/chromium/chrome/browser/preferences/datareduction/DataReductionMainMenuFooter.java", + "java/src/org/chromium/chrome/browser/preferences/datareduction/DataReductionSiteBreakdownView.java", "java/src/org/chromium/chrome/browser/preferences/datareduction/DataReductionPreferences.java", "java/src/org/chromium/chrome/browser/preferences/datareduction/DataReductionPromoScreen.java", "java/src/org/chromium/chrome/browser/preferences/datareduction/DataReductionPromoUtils.java", "java/src/org/chromium/chrome/browser/preferences/datareduction/DataReductionProxyUma.java", "java/src/org/chromium/chrome/browser/preferences/datareduction/DataReductionStatsPreference.java", + "java/src/org/chromium/chrome/browser/preferences/datareduction/DataReductionDataUseItem.java", "java/src/org/chromium/chrome/browser/preferences/password/PasswordEntryEditor.java", "java/src/org/chromium/chrome/browser/preferences/password/SavePasswordsPreferences.java", "java/src/org/chromium/chrome/browser/preferences/privacy/BandwidthType.java", @@ -1531,6 +1534,7 @@ "javatests/src/org/chromium/chrome/browser/signin/SigninTest.java", "javatests/src/org/chromium/chrome/browser/snackbar/DataReductionPromoSnackbarControllerTest.java", "javatests/src/org/chromium/chrome/browser/snackbar/SnackbarTest.java", + "javatests/src/org/chromium/chrome/browser/snackbar/undo/UndoBarControllerTest.java", "javatests/src/org/chromium/chrome/browser/suggestions/FakeMostVisitedSites.java", "javatests/src/org/chromium/chrome/browser/suggestions/SuggestionsBottomSheetTest.java", "javatests/src/org/chromium/chrome/browser/suggestions/TileGroupTest.java",
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/SmartClipProviderTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/SmartClipProviderTest.java index 3d522ce..2866e15 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/SmartClipProviderTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/SmartClipProviderTest.java
@@ -184,4 +184,32 @@ assertNotNull(mCallbackHelper.getText()); assertNotNull(mCallbackHelper.getHtml()); } + + @MediumTest + @Feature({"SmartClip"}) + @RetryOnFailure + public void testSmartClipNoHandlerDoesntCrash() throws InterruptedException, TimeoutException { + ThreadUtils.runOnUiThreadBlocking(new Runnable() { + @Override + public void run() { + Object scp = + findSmartClipProvider(getActivity().findViewById(android.R.id.content)); + assertNotNull(scp); + try { + // Galaxy Note 4 has a bug where it doesn't always set the handler first; in + // that case, we shouldn't crash: http://crbug.com/710147 + mExtractSmartClipDataMethod.invoke(scp, 10, 20, 100, 70); + + // Add a wait for a valid callback to make sure we have time to + // hit the crash from the above call if any. + mSetSmartClipResultHandlerMethod.invoke(scp, mHandler); + mExtractSmartClipDataMethod.invoke(scp, 10, 20, 100, 70); + } catch (Exception e) { + e.printStackTrace(); + fail(); + } + } + }); + mCallbackHelper.waitForCallback(0, 1); // call count: 0 --> 1 + } }
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/media/OWNERS b/chrome/android/javatests/src/org/chromium/chrome/browser/media/OWNERS index c8e9dde..81e001a 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/media/OWNERS +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/media/OWNERS
@@ -2,4 +2,5 @@ avayvod@chromium.org mlamouri@chromium.org +# TEAM: media-dev@chromium.org # COMPONENT: Internals>Media>UI
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/payments/PaymentRequestBasicCardTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/payments/PaymentRequestBasicCardTest.java index a2a2e533..317c0bc 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/payments/PaymentRequestBasicCardTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/payments/PaymentRequestBasicCardTest.java
@@ -77,7 +77,7 @@ expectResultContains(new String[] {"true"}); clickNodeAndWait("checkBasicMasterCard", mCanMakePaymentQueryResponded); - expectResultContains(new String[] {"Query quota exceeded"}); + expectResultContains(new String[] {"Not allowed to check whether can make payment"}); clickNodeAndWait("checkBasicVisa", mCanMakePaymentQueryResponded); expectResultContains(new String[] {"true"}); @@ -91,7 +91,7 @@ expectResultContains(new String[] {"true"}); clickNodeAndWait("checkBasicDebit", mCanMakePaymentQueryResponded); - expectResultContains(new String[] {"Query quota exceeded"}); + expectResultContains(new String[] {"Not allowed to check whether can make payment"}); clickNodeAndWait("checkBasicVisa", mCanMakePaymentQueryResponded); expectResultContains(new String[] {"true"});
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/payments/PaymentRequestCanMakePaymentMetricsTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/payments/PaymentRequestCanMakePaymentMetricsTest.java index 28e549ce..f664079 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/payments/PaymentRequestCanMakePaymentMetricsTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/payments/PaymentRequestCanMakePaymentMetricsTest.java
@@ -13,7 +13,6 @@ import org.chromium.chrome.R; import org.chromium.chrome.browser.autofill.AutofillTestHelper; import org.chromium.chrome.browser.autofill.PersonalDataManager.AutofillProfile; -import org.chromium.components.payments.JourneyLogger; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeoutException;
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/payments/PaymentRequestCcCanMakePaymentQueryTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/payments/PaymentRequestCcCanMakePaymentQueryTest.java index 9cb69a76..dd11ccbb 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/payments/PaymentRequestCcCanMakePaymentQueryTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/payments/PaymentRequestCcCanMakePaymentQueryTest.java
@@ -49,7 +49,7 @@ // Different queries are throttled for a period of time. clickNodeAndWait("other-buy", mCanMakePaymentQueryResponded); - expectResultContains(new String[]{"Query quota exceeded"}); + expectResultContains(new String[] {"Not allowed to check whether can make payment"}); // Repeating the same query again does not count against the quota. clickNodeAndWait("buy", mCanMakePaymentQueryResponded);
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/payments/PaymentRequestPaymentAppCanMakePaymentQueryTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/payments/PaymentRequestPaymentAppCanMakePaymentQueryTest.java index fd3b2502..92ce4bea 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/payments/PaymentRequestPaymentAppCanMakePaymentQueryTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/payments/PaymentRequestPaymentAppCanMakePaymentQueryTest.java
@@ -31,7 +31,7 @@ expectResultContains(new String[] {"false, false"}); clickNodeAndWait("otherBuy", mCanMakePaymentQueryResponded); - expectResultContains(new String[] {"false, QuotaExceededError"}); + expectResultContains(new String[] {"false, NotAllowedError"}); } @MediumTest @@ -44,7 +44,7 @@ installPaymentApp(HAVE_INSTRUMENTS, IMMEDIATE_RESPONSE); clickNodeAndWait("otherBuy", mCanMakePaymentQueryResponded); - expectResultContains(new String[] {"true, QuotaExceededError"}); + expectResultContains(new String[] {"true, NotAllowedError"}); } @MediumTest @@ -56,7 +56,7 @@ expectResultContains(new String[] {"false, false"}); clickNodeAndWait("otherBuy", mCanMakePaymentQueryResponded); - expectResultContains(new String[] {"false, QuotaExceededError"}); + expectResultContains(new String[] {"false, NotAllowedError"}); } @MediumTest @@ -68,7 +68,7 @@ expectResultContains(new String[] {"false, false"}); clickNodeAndWait("otherBuy", mCanMakePaymentQueryResponded); - expectResultContains(new String[] {"false, QuotaExceededError"}); + expectResultContains(new String[] {"false, NotAllowedError"}); } @MediumTest @@ -80,7 +80,7 @@ expectResultContains(new String[] {"true, true"}); clickNodeAndWait("otherBuy", mCanMakePaymentQueryResponded); - expectResultContains(new String[] {"true, QuotaExceededError"}); + expectResultContains(new String[] {"true, NotAllowedError"}); } @MediumTest @@ -92,6 +92,6 @@ expectResultContains(new String[] {"true, true"}); clickNodeAndWait("otherBuy", mCanMakePaymentQueryResponded); - expectResultContains(new String[] {"true, QuotaExceededError"}); + expectResultContains(new String[] {"true, NotAllowedError"}); } }
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/snackbar/undo/UndoBarControllerTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/snackbar/undo/UndoBarControllerTest.java new file mode 100644 index 0000000..e3fc7cc7 --- /dev/null +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/snackbar/undo/UndoBarControllerTest.java
@@ -0,0 +1,148 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package org.chromium.chrome.browser.snackbar.undo; + +import android.support.test.filters.SmallTest; +import android.widget.TextView; + +import org.chromium.base.ThreadUtils; +import org.chromium.chrome.R; +import org.chromium.chrome.browser.snackbar.Snackbar; +import org.chromium.chrome.browser.snackbar.SnackbarManager; +import org.chromium.chrome.browser.tabmodel.TabModel; +import org.chromium.chrome.test.ChromeTabbedActivityTestBase; +import org.chromium.chrome.test.util.ChromeTabUtils; + +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutionException; + +/** + * Tests for the UndoBarController. + */ +public class UndoBarControllerTest extends ChromeTabbedActivityTestBase { + private SnackbarManager mSnackbarManager; + private TabModel mTabModel; + + @Override + protected void setUp() throws Exception { + super.setUp(); + + mSnackbarManager = getActivity().getSnackbarManager(); + mTabModel = getActivity().getCurrentTabModel(); + } + + @Override + public void startMainActivity() throws InterruptedException { + startMainActivityOnBlankPage(); + } + + @SmallTest + public void testCloseAll_SingleTab_Undo() throws Exception { + assertNull(getCurrentSnackbar()); + assertEquals(1, mTabModel.getCount()); + + ChromeTabUtils.closeAllTabs(getInstrumentation(), getActivity()); + + Snackbar currentSnackbar = getCurrentSnackbar(); + assertEquals("Closed about:blank", getSnackbarText()); + assertTrue(currentSnackbar.getController() instanceof UndoBarController); + assertEquals(0, mTabModel.getCount()); + + clickSnackbar(); + + assertNull(getCurrentSnackbar()); + assertEquals(1, mTabModel.getCount()); + } + + @SmallTest + public void testCloseAll_SingleTab_Dismiss() throws Exception { + assertNull(getCurrentSnackbar()); + assertEquals(1, mTabModel.getCount()); + + ChromeTabUtils.closeAllTabs(getInstrumentation(), getActivity()); + + Snackbar currentSnackbar = getCurrentSnackbar(); + assertEquals("Closed about:blank", getSnackbarText()); + assertTrue(currentSnackbar.getController() instanceof UndoBarController); + assertEquals(0, mTabModel.getCount()); + + dismissSnackbars(); + + assertNull(getCurrentSnackbar()); + assertEquals(0, mTabModel.getCount()); + } + + @SmallTest + public void testCloseAll_MultipleTabs_Undo() throws Exception { + ChromeTabUtils.newTabFromMenu(getInstrumentation(), getActivity()); + + assertNull(getCurrentSnackbar()); + assertEquals(2, mTabModel.getCount()); + + ChromeTabUtils.closeAllTabs(getInstrumentation(), getActivity()); + + Snackbar currentSnackbar = getCurrentSnackbar(); + assertEquals("2 tabs closed", getSnackbarText()); + assertTrue(currentSnackbar.getController() instanceof UndoBarController); + assertEquals(0, mTabModel.getCount()); + + clickSnackbar(); + + assertNull(getCurrentSnackbar()); + assertEquals(2, mTabModel.getCount()); + } + + @SmallTest + public void testCloseAll_MultipleTabs_Dismiss() throws Exception { + ChromeTabUtils.newTabFromMenu(getInstrumentation(), getActivity()); + + assertNull(getCurrentSnackbar()); + assertEquals(2, mTabModel.getCount()); + + ChromeTabUtils.closeAllTabs(getInstrumentation(), getActivity()); + + Snackbar currentSnackbar = getCurrentSnackbar(); + assertEquals("2 tabs closed", getSnackbarText()); + assertTrue(currentSnackbar.getController() instanceof UndoBarController); + assertEquals(0, mTabModel.getCount()); + + dismissSnackbars(); + + assertNull(getCurrentSnackbar()); + assertEquals(0, mTabModel.getCount()); + } + + private void clickSnackbar() { + ThreadUtils.runOnUiThreadBlocking(new Runnable() { + @Override + public void run() { + mSnackbarManager.onClick(getActivity().findViewById(R.id.snackbar_button)); + } + }); + } + + private void dismissSnackbars() { + ThreadUtils.runOnUiThreadBlocking(new Runnable() { + @Override + public void run() { + mSnackbarManager.dismissSnackbars( + mSnackbarManager.getCurrentSnackbarForTesting().getController()); + } + }); + } + + private String getSnackbarText() { + return ((TextView) getActivity().findViewById(R.id.snackbar_message)).getText().toString(); + } + + private Snackbar getCurrentSnackbar() throws ExecutionException { + return ThreadUtils.runOnUiThreadBlocking(new Callable<Snackbar>() { + @Override + public Snackbar call() throws Exception { + return mSnackbarManager.getCurrentSnackbarForTesting(); + } + }); + } +}
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/tabmodel/TabPersistentStoreTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/tabmodel/TabPersistentStoreTest.java index 80065e9..dfdf883 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/tabmodel/TabPersistentStoreTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/tabmodel/TabPersistentStoreTest.java
@@ -710,8 +710,8 @@ final List<Integer> closedTabIds = new ArrayList<>(); TabModelObserver closeObserver = new EmptyTabModelObserver() { @Override - public void allTabsPendingClosure(List<Integer> tabIds) { - for (Integer id : tabIds) closedTabIds.add(id); + public void allTabsPendingClosure(List<Tab> tabs) { + for (Tab tab : tabs) closedTabIds.add(tab.getId()); } }; regularModel.addObserver(closeObserver);
diff --git a/chrome/android/junit/src/org/chromium/chrome/browser/media/router/OWNERS b/chrome/android/junit/src/org/chromium/chrome/browser/media/router/OWNERS index 7816a76..e98d2ad 100644 --- a/chrome/android/junit/src/org/chromium/chrome/browser/media/router/OWNERS +++ b/chrome/android/junit/src/org/chromium/chrome/browser/media/router/OWNERS
@@ -1,4 +1,5 @@ avayvod@chromium.org mlamouri@chromium.org +# TEAM: media-dev@chromium.org # COMPONENT: Blink>PresentationAPI
diff --git a/chrome/android/junit/src/org/chromium/chrome/browser/media/ui/OWNERS b/chrome/android/junit/src/org/chromium/chrome/browser/media/ui/OWNERS index a276f281..36a4886 100644 --- a/chrome/android/junit/src/org/chromium/chrome/browser/media/ui/OWNERS +++ b/chrome/android/junit/src/org/chromium/chrome/browser/media/ui/OWNERS
@@ -2,4 +2,5 @@ mlamouri@chromium.org zqzhang@chromium.org +# TEAM: media-dev@chromium.org # COMPONENT: Internals>Media>UI
diff --git a/chrome/app/chromeos_strings.grdp b/chrome/app/chromeos_strings.grdp index c85227e..79df369 100644 --- a/chrome/app/chromeos_strings.grdp +++ b/chrome/app/chromeos_strings.grdp
@@ -5798,6 +5798,12 @@ <message name="IDS_FIRST_RUN_NEXT_BUTTON" desc="Text on the first-run tutorial button leading to next step of tutorial."> Next </message> + <message name="IDS_FIRST_RUN_ACCESSIBLE_TITLE" desc="Accessible title of the first screen in the first run app."> + Welcome + </message> + <message name="IDS_FIRST_RUN_STEP_ACCESSIBLE_TITLE" desc="Accessible title for all first run app screens except for the first screen."> + Tour + </message> <!-- Network portal notification --> <message name="IDS_PORTAL_DETECTION_NOTIFICATION_TITLE_WIRED" desc="Title for the system notification that current wired network is behind captive portal">
diff --git a/chrome/app/generated_resources.grd b/chrome/app/generated_resources.grd index 3c02bc6..663cca3 100644 --- a/chrome/app/generated_resources.grd +++ b/chrome/app/generated_resources.grd
@@ -8974,7 +8974,7 @@ Google may use your browsing history to personalize Search and other Google services </message> <message name="IDS_SYNC_CONFIRMATION_SYNC_SETTINGS_LABEL" desc="Label of the checkbox that allows users to configure their sync settings on the settings page before signing in to Chrome."> - Control how this works in Settings + Manage Chrome Sync and personalization in Settings </message> <message name="IDS_SYNC_CONFIRMATION_CONFIRM_BUTTON_LABEL" desc="Label of the confirmation button in the sync confirmation dialog of the tab modal signin flow"> Ok, got it
diff --git a/chrome/app/nibs/MainMenu.xib b/chrome/app/nibs/MainMenu.xib index 5bd110d..3873f5c4 100644 --- a/chrome/app/nibs/MainMenu.xib +++ b/chrome/app/nibs/MainMenu.xib
@@ -313,7 +313,7 @@ <action selector="commandDispatch:" target="-1" id="531"/> </connections> </menuItem> - <menuItem title="^IDS_TOGGLE_FULLSCREEN_TOOLBAR_MAC" tag="40251" keyEquivalent="F" id="70p-NK-bpU"> + <menuItem title="^IDS_TOGGLE_FULLSCREEN_TOOLBAR_MAC" tag="40250" keyEquivalent="F" id="70p-NK-bpU"> <connections> <action selector="commandDispatch:" target="-1" id="0A7-Iy-65Q"/> </connections>
diff --git a/chrome/app/settings_strings.grdp b/chrome/app/settings_strings.grdp index fa726d4..4ab3d31 100644 --- a/chrome/app/settings_strings.grdp +++ b/chrome/app/settings_strings.grdp
@@ -1156,6 +1156,9 @@ <message name="IDS_SETTINGS_INTERNET_NETWORK_SECTION_WPAD" desc="Settings > Internet > Network details: Web Proxy Auto Discovery (WPAD) section label."> Web Proxy Auto Discovery URL: </message> + <message name="IDS_SETTINGS_SETTINGS_NETWORK_ALLOW_DATA_ROAMING" desc="Settings > Internet > Network details: Toggle label to allow mobile data roaming."> + Allow mobile data roaming + </message> <message name="IDS_SETTINGS_INTERNET_NETWORK_SHARED" desc="Settings > Internet > Network details: Text to show when a network is shared."> This network is shared with other users </message> @@ -2836,6 +2839,9 @@ <message name="IDS_SETTINGS_DISPLAY_MIRROR" desc="In Device Settings > Displays, the label for the control for mirroring."> Mirroring </message> + <message name="IDS_SETTINGS_DISPLAY_UNIFIED_DESKTOP" desc="In Device Settings > Displays, the label for the control for the unified desktop feature."> + Allow windows to span displays + </message> <message name="IDS_SETTINGS_DISPLAY_SCREEN" desc="In Device Settings > Displays, the label for the dropdown menu for changing the dispay type."> Screen </message> @@ -2884,12 +2890,6 @@ <message name="IDS_SETTINGS_DISPLAY_OVERSCAN_RESET" desc="Label for resetting overscan calibration."> Reset </message> - <message name="IDS_SETTINGS_DISPLAY_MIRRORING_ON" desc="Label indicating that the displays are currently mirrored"> - On - </message> - <message name="IDS_SETTINGS_DISPLAY_MIRRORING_OFF" desc="Label indicating that the displays are currently not mirrored"> - Off - </message> <message name="IDS_SETTINGS_DISPLAY_TOUCH_CALIBRATION_TITLE" desc="In Device Settings > Displays, the label for initiating touch calibration."> Calibrate touchscreen </message>
diff --git a/chrome/browser/BUILD.gn b/chrome/browser/BUILD.gn index 8022a99..10f3fced 100644 --- a/chrome/browser/BUILD.gn +++ b/chrome/browser/BUILD.gn
@@ -1121,6 +1121,8 @@ "resources_util.h", "safe_browsing/safe_browsing_tab_observer.cc", "safe_browsing/safe_browsing_tab_observer.h", + "safe_browsing/srt_chrome_prompt_impl.cc", + "safe_browsing/srt_chrome_prompt_impl.h", "safe_browsing/srt_client_info_win.cc", "safe_browsing/srt_client_info_win.h", "safe_browsing/srt_fetcher_win.cc", @@ -1444,6 +1446,7 @@ "//components/captive_portal", "//components/certificate_reporting", "//components/certificate_transparency", + "//components/chrome_cleaner/public/interfaces", "//components/cloud_devices/common", "//components/component_updater", "//components/content_settings/core/browser", @@ -3096,6 +3099,10 @@ "password_manager/save_password_infobar_delegate_android.h", "password_manager/update_password_infobar_delegate_android.cc", "password_manager/update_password_infobar_delegate_android.h", + "payments/android/chrome_payments_jni_registrar.cc", + "payments/android/chrome_payments_jni_registrar.h", + "payments/android/journey_logger_android.cc", + "payments/android/journey_logger_android.h", "permissions/grouped_permission_infobar_delegate_android.cc", "permissions/grouped_permission_infobar_delegate_android.h", "permissions/permission_dialog_delegate.cc", @@ -4172,6 +4179,7 @@ "../android/java/src/org/chromium/chrome/browser/password_manager/AccountChooserDialog.java", "../android/java/src/org/chromium/chrome/browser/password_manager/AutoSigninFirstRunDialog.java", "../android/java/src/org/chromium/chrome/browser/password_manager/Credential.java", + "../android/java/src/org/chromium/chrome/browser/payments/JourneyLogger.java", "../android/java/src/org/chromium/chrome/browser/payments/ServiceWorkerPaymentAppBridge.java", "../android/java/src/org/chromium/chrome/browser/permissions/PermissionDialogController.java", "../android/java/src/org/chromium/chrome/browser/permissions/PermissionDialogDelegate.java",
diff --git a/chrome/browser/about_flags.cc b/chrome/browser/about_flags.cc index d689ae41..aa20d19 100644 --- a/chrome/browser/about_flags.cc +++ b/chrome/browser/about_flags.cc
@@ -35,6 +35,7 @@ #include "chrome/common/chrome_features.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/features.h" +#include "chrome/common/pause_tabs_field_trial.h" #include "chrome/grit/chromium_strings.h" #include "components/autofill/core/browser/autofill_experiments.h" #include "components/autofill/core/common/autofill_switches.h" @@ -99,6 +100,7 @@ #if defined(OS_ANDROID) #include "chrome/browser/android/chrome_feature_list.h" +#include "components/feature_engagement_tracker/public/feature_constants.h" #else // OS_ANDROID #include "ui/message_center/message_center_switches.h" #endif // OS_ANDROID @@ -713,6 +715,36 @@ {"Learning", kSpeculativeResourcePrefetchingLearning, arraysize(kSpeculativeResourcePrefetchingLearning), nullptr}}; +#if defined(OS_CHROMEOS) || defined(OS_LINUX) || defined(OS_MACOSX) || \ + defined(OS_WIN) +const FeatureEntry::FeatureParam kPauseBackgroundTabsMinimalEngagment[] = { + {pausetabs::kFeatureName, pausetabs::kModeParamMinimal}}; + +const FeatureEntry::FeatureParam kPauseBackgroundTabsLowEngagment[] = { + {pausetabs::kFeatureName, pausetabs::kModeParamLow}}; + +const FeatureEntry::FeatureParam kPauseBackgroundTabsMediumEngagment[] = { + {pausetabs::kFeatureName, pausetabs::kModeParamMedium}}; + +const FeatureEntry::FeatureParam kPauseBackgroundTabsHighEngagment[] = { + {pausetabs::kFeatureName, pausetabs::kModeParamHigh}}; + +const FeatureEntry::FeatureParam kPauseBackgroundTabsMaxEngagment[] = { + {pausetabs::kFeatureName, pausetabs::kModeParamMax}}; + +const FeatureEntry::FeatureVariation kPauseBackgroundTabsVariations[] = { + {"minimal engagement", kPauseBackgroundTabsMinimalEngagment, + arraysize(kPauseBackgroundTabsMinimalEngagment), nullptr}, + {"low engagement", kPauseBackgroundTabsLowEngagment, + arraysize(kPauseBackgroundTabsLowEngagment), nullptr}, + {"medium engagement", kPauseBackgroundTabsMediumEngagment, + arraysize(kPauseBackgroundTabsMediumEngagment), nullptr}, + {"high engagement", kPauseBackgroundTabsHighEngagment, + arraysize(kPauseBackgroundTabsHighEngagment), nullptr}, + {"max engagement", kPauseBackgroundTabsMaxEngagment, + arraysize(kPauseBackgroundTabsMaxEngagment), nullptr}}; +#endif + #if defined(OS_ANDROID) const FeatureEntry::FeatureParam kAutofillCreditCardPopupLayoutFeatureVariationIconAtStart[] = { @@ -1529,6 +1561,11 @@ flag_descriptions::kChromeHomeDescription, kOsAndroid, FEATURE_VALUE_TYPE(chrome::android::kChromeHomeFeature)}, #endif // OS_ANDROID +#if defined(OS_ANDROID) + {"enable-iph-demo-mode", flag_descriptions::kEnableIphDemoMode, + flag_descriptions::kEnableIphDemoModeDescription, kOsAndroid, + FEATURE_VALUE_TYPE(feature_engagement_tracker::kIPHDemoMode)}, +#endif // OS_ANDROID {"num-raster-threads", flag_descriptions::kNumRasterThreadsName, flag_descriptions::kNumRasterThreadsDescription, kOsAll, MULTI_VALUE_TYPE(kNumRasterThreadsChoices)}, @@ -2576,6 +2613,15 @@ FEATURE_VALUE_TYPE(chrome::android::kCustomContextMenu)}, #endif // OS_ANDROID +#if defined(OS_CHROMEOS) || defined(OS_LINUX) || defined(OS_MACOSX) || \ + defined(OS_WIN) + {pausetabs::kFeatureName, flag_descriptions::kPauseBackgroundTabsName, + flag_descriptions::kPauseBackgroundTabsDescription, kOsDesktop, + FEATURE_WITH_PARAMS_VALUE_TYPE(pausetabs::kFeature, + kPauseBackgroundTabsVariations, + "PauseBackgroundTabs")}, +#endif + #if defined(USE_ASH) {"ash-enable-smooth-screen-rotation", flag_descriptions::kAshEnableSmoothScreenRotationName,
diff --git a/chrome/browser/android/chrome_feature_list.cc b/chrome/browser/android/chrome_feature_list.cc index e89f517..b1e79b3a 100644 --- a/chrome/browser/android/chrome_feature_list.cc +++ b/chrome/browser/android/chrome_feature_list.cc
@@ -59,6 +59,7 @@ &kCustomContextMenu, &kCustomFeedbackUi, &data_reduction_proxy::features::kDataReductionMainMenu, + &data_reduction_proxy::features::kDataReductionSiteBreakdown, &kFullscreenActivity, &kImportantSitesInCBD, &kImprovedA2HS,
diff --git a/chrome/browser/android/chrome_jni_registrar.cc b/chrome/browser/android/chrome_jni_registrar.cc index 9ed3315..7f8b350 100644 --- a/chrome/browser/android/chrome_jni_registrar.cc +++ b/chrome/browser/android/chrome_jni_registrar.cc
@@ -129,6 +129,7 @@ #include "chrome/browser/notifications/notification_platform_bridge_android.h" #include "chrome/browser/password_manager/account_chooser_dialog_android.h" #include "chrome/browser/password_manager/auto_signin_first_run_dialog_android.h" +#include "chrome/browser/payments/android/chrome_payments_jni_registrar.h" #include "chrome/browser/permissions/permission_dialog_delegate.h" #include "chrome/browser/permissions/permission_update_infobar_delegate_android.h" #include "chrome/browser/predictors/resource_prefetch_predictor_android.h" @@ -273,6 +274,7 @@ {"ChromeMediaRouterDialogController", media_router::MediaRouterDialogControllerAndroid::Register}, #endif + {"ChromePayments", payments::android::RegisterChromePayments}, {"ChromeWebApkHost", ChromeWebApkHost::Register}, {"CompositorView", RegisterCompositorView}, {"ConnectionInfoPopupAndroid",
diff --git a/chrome/browser/android/download/duplicate_download_infobar_delegate.cc b/chrome/browser/android/download/duplicate_download_infobar_delegate.cc index 598c204..a9e045cb 100644 --- a/chrome/browser/android/download/duplicate_download_infobar_delegate.cc +++ b/chrome/browser/android/download/duplicate_download_infobar_delegate.cc
@@ -19,6 +19,10 @@ return false; } +bool DuplicateDownloadInfoBarDelegate::DuplicateRequestExists() const { + return false; +} + base::string16 DuplicateDownloadInfoBarDelegate::GetMessageText() const { return base::string16(); }
diff --git a/chrome/browser/android/download/duplicate_download_infobar_delegate.h b/chrome/browser/android/download/duplicate_download_infobar_delegate.h index 645a7bf..8a66cfa 100644 --- a/chrome/browser/android/download/duplicate_download_infobar_delegate.h +++ b/chrome/browser/android/download/duplicate_download_infobar_delegate.h
@@ -27,6 +27,9 @@ virtual bool IsOffTheRecord() const; + // Whether the duplicate is an in-progress request or completed download. + virtual bool DuplicateRequestExists() const; + // ConfirmInfoBarDelegate implementation. base::string16 GetMessageText() const override; bool ShouldExpire(const NavigationDetails& details) const override;
diff --git a/chrome/browser/android/offline_pages/background_loader_offliner.cc b/chrome/browser/android/offline_pages/background_loader_offliner.cc index 603263f8..f8f86b6 100644 --- a/chrome/browser/android/offline_pages/background_loader_offliner.cc +++ b/chrome/browser/android/offline_pages/background_loader_offliner.cc
@@ -201,14 +201,11 @@ return false; } -void BackgroundLoaderOffliner::DocumentLoadedInFrame( - content::RenderFrameHost* render_host) { - // Inform snapshot controller if in main frame. - if (!render_host->GetParent()) - snapshot_controller_->DocumentAvailableInMainFrame(); +void BackgroundLoaderOffliner::DocumentAvailableInMainFrame() { + snapshot_controller_->DocumentAvailableInMainFrame(); } -void BackgroundLoaderOffliner::DidStopLoading() { +void BackgroundLoaderOffliner::DocumentOnLoadCompletedInMainFrame() { if (!pending_request_.get()) { DVLOG(1) << "DidStopLoading called even though no pending request."; return;
diff --git a/chrome/browser/android/offline_pages/background_loader_offliner.h b/chrome/browser/android/offline_pages/background_loader_offliner.h index 608e88b..8d63c3c3 100644 --- a/chrome/browser/android/offline_pages/background_loader_offliner.h +++ b/chrome/browser/android/offline_pages/background_loader_offliner.h
@@ -47,8 +47,8 @@ bool HandleTimeout(const SavePageRequest& request) override; // WebContentsObserver implementation. - void DocumentLoadedInFrame(content::RenderFrameHost* render_frame) override; - void DidStopLoading() override; + void DocumentAvailableInMainFrame() override; + void DocumentOnLoadCompletedInMainFrame() override; void RenderProcessGone(base::TerminationStatus status) override; void WebContentsDestroyed() override; void DidFinishNavigation(
diff --git a/chrome/browser/android/offline_pages/background_loader_offliner_unittest.cc b/chrome/browser/android/offline_pages/background_loader_offliner_unittest.cc index da2efcd4..d9078c4 100644 --- a/chrome/browser/android/offline_pages/background_loader_offliner_unittest.cc +++ b/chrome/browser/android/offline_pages/background_loader_offliner_unittest.cc
@@ -147,14 +147,13 @@ const base::HistogramTester& histograms() const { return histogram_tester_; } int64_t progress() { return progress_; } - void CompleteLoading() { - // For some reason, setting loading to True will call DidStopLoading - // on the observers. - offliner()->web_contents_tester()->TestSetIsLoading(true); - } - void PumpLoop() { base::RunLoop().RunUntilIdle(); } + void CompleteLoading() { + offliner()->DocumentOnLoadCompletedInMainFrame(); + PumpLoop(); + } + private: void OnCompletion(const SavePageRequest& request, Offliner::RequestStatus status); @@ -433,7 +432,7 @@ "OfflinePages.Background.BackgroundLoadingFailedCode.async_loading", 105, // ERR_NAME_NOT_RESOLVED 1); - offliner()->DidStopLoading(); + CompleteLoading(); PumpLoop(); EXPECT_TRUE(completion_callback_called()); @@ -457,7 +456,7 @@ offliner()->DidFinishNavigation(handle.get()); // NavigationHandle is always destroyed after finishing navigation. handle.reset(); - offliner()->DidStopLoading(); + CompleteLoading(); PumpLoop(); EXPECT_TRUE(completion_callback_called()); @@ -473,7 +472,7 @@ // First load CompleteLoading(); // Second load - offliner()->DidStopLoading(); + CompleteLoading(); PumpLoop(); model()->CompleteSavingAsSuccess(); PumpLoop();
diff --git a/chrome/browser/android/offline_pages/downloads/offline_page_download_bridge.cc b/chrome/browser/android/offline_pages/downloads/offline_page_download_bridge.cc index b78235c6..928418495 100644 --- a/chrome/browser/android/offline_pages/downloads/offline_page_download_bridge.cc +++ b/chrome/browser/android/offline_pages/downloads/offline_page_download_bridge.cc
@@ -11,7 +11,6 @@ #include "base/guid.h" #include "base/logging.h" #include "base/memory/ptr_util.h" -#include "base/metrics/histogram_macros.h" #include "chrome/browser/android/offline_pages/downloads/offline_page_infobar_delegate.h" #include "chrome/browser/android/offline_pages/downloads/offline_page_notification_bridge.h" #include "chrome/browser/android/offline_pages/offline_page_mhtml_archiver.h" @@ -152,67 +151,24 @@ notification_bridge.ShowDownloadingToast(); } -void RequestQueueDuplicateCheckDone( - const GURL& url, - const GURL& original_url, - const ScopedJavaGlobalRef<jobject>& j_tab_ref, - bool has_duplicates, - const base::Time& latest_request_time) { - if (has_duplicates) { - base::TimeDelta time_since_most_recent_duplicate = - base::Time::Now() - latest_request_time; - // Using CUSTOM_COUNTS instead of time-oriented histogram to record - // samples in seconds rather than milliseconds. - UMA_HISTOGRAM_CUSTOM_COUNTS( - "OfflinePages.DownloadRequestTimeSinceDuplicateRequested", - time_since_most_recent_duplicate.InSeconds(), - base::TimeDelta::FromSeconds(1).InSeconds(), - base::TimeDelta::FromDays(7).InSeconds(), 50); - - // TODO(fgorski): Additionally we could update existing request's expiration - // period, as it is still important. Alternative would be to actually take a - // snapshot on the spot, but that would only work if the page is loaded - // enough. - // This simply toasts that the item is downloading. - OfflinePageNotificationBridge notification_bridge; - notification_bridge.ShowDownloadingToast(); +void DuplicateCheckDone(const GURL& url, + const GURL& original_url, + const ScopedJavaGlobalRef<jobject>& j_tab_ref, + OfflinePageUtils::DuplicateCheckResult result) { + if (result == OfflinePageUtils::DuplicateCheckResult::NOT_FOUND) { + SavePageIfNotNavigatedAway(url, original_url, j_tab_ref); return; } - SavePageIfNotNavigatedAway(url, original_url, j_tab_ref); -} - -void ModelDuplicateCheckDone(const GURL& url, - const GURL& original_url, - const ScopedJavaGlobalRef<jobject>& j_tab_ref, - bool has_duplicates, - const base::Time& latest_saved_time) { content::WebContents* web_contents = GetWebContentsFromJavaTab(j_tab_ref); if (!web_contents) return; - if (has_duplicates) { - base::TimeDelta time_since_most_recent_duplicate = - base::Time::Now() - latest_saved_time; - // Using CUSTOM_COUNTS instead of time-oriented histogram to record - // samples in seconds rather than milliseconds. - UMA_HISTOGRAM_CUSTOM_COUNTS( - "OfflinePages.DownloadRequestTimeSinceDuplicateSaved", - time_since_most_recent_duplicate.InSeconds(), - base::TimeDelta::FromSeconds(1).InSeconds(), - base::TimeDelta::FromDays(7).InSeconds(), 50); - - OfflinePageInfoBarDelegate::Create( - base::Bind(&SavePageIfNotNavigatedAway, url, original_url, j_tab_ref), - url, web_contents); - return; - } - - OfflinePageUtils::CheckExistenceOfRequestsWithURL( - Profile::FromBrowserContext(web_contents->GetBrowserContext()) - ->GetOriginalProfile(), - kDownloadNamespace, url, base::Bind(&RequestQueueDuplicateCheckDone, url, - original_url, j_tab_ref)); + bool duplicate_request_exists = + result == OfflinePageUtils::DuplicateCheckResult::DUPLICATE_REQUEST_FOUND; + OfflinePageInfoBarDelegate::Create( + base::Bind(&SavePageIfNotNavigatedAway, url, original_url, j_tab_ref), + url, duplicate_request_exists, web_contents); } void ToJavaOfflinePageDownloadItemList( @@ -387,9 +343,9 @@ ScopedJavaGlobalRef<jobject> j_tab_ref(env, j_tab); - OfflinePageUtils::CheckExistenceOfPagesWithURL( - tab->GetProfile()->GetOriginalProfile(), kDownloadNamespace, url, - base::Bind(&ModelDuplicateCheckDone, url, original_url, j_tab_ref)); + OfflinePageUtils::CheckDuplicateDownloads( + tab->GetProfile()->GetOriginalProfile(), url, + base::Bind(&DuplicateCheckDone, url, original_url, j_tab_ref)); } void OfflinePageDownloadBridge::CancelDownload(
diff --git a/chrome/browser/android/offline_pages/downloads/offline_page_infobar_delegate.cc b/chrome/browser/android/offline_pages/downloads/offline_page_infobar_delegate.cc index 47c16c6..dd8a896 100644 --- a/chrome/browser/android/offline_pages/downloads/offline_page_infobar_delegate.cc +++ b/chrome/browser/android/offline_pages/downloads/offline_page_infobar_delegate.cc
@@ -17,6 +17,7 @@ void OfflinePageInfoBarDelegate::Create( const base::Closure& confirm_continuation, const GURL& page_to_download, + bool exists_duplicate_request, content::WebContents* web_contents) { // The URL could be very long, especially since we are including query // parameters, path, etc. Elide the URL to a shorter length because the @@ -37,10 +38,10 @@ gfx::ElideString(formatted_url, kMaxLengthOfDisplayedPageUrl, &elided_url); InfoBarService::FromWebContents(web_contents) - ->AddInfoBar(DuplicateDownloadInfoBar::CreateInfoBar(base::WrapUnique( - new OfflinePageInfoBarDelegate(confirm_continuation, - base::UTF16ToUTF8(elided_url), - page_to_download)))); + ->AddInfoBar(DuplicateDownloadInfoBar::CreateInfoBar( + base::WrapUnique(new OfflinePageInfoBarDelegate( + confirm_continuation, base::UTF16ToUTF8(elided_url), + page_to_download, exists_duplicate_request)))); } OfflinePageInfoBarDelegate::~OfflinePageInfoBarDelegate() {} @@ -48,10 +49,12 @@ OfflinePageInfoBarDelegate::OfflinePageInfoBarDelegate( const base::Closure& confirm_continuation, const std::string& page_name, - const GURL& page_to_download) + const GURL& page_to_download, + bool duplicate_request_exists) : confirm_continuation_(confirm_continuation), page_name_(page_name), - page_to_download_(page_to_download) {} + page_to_download_(page_to_download), + duplicate_request_exists_(duplicate_request_exists) {} infobars::InfoBarDelegate::InfoBarIdentifier OfflinePageInfoBarDelegate::GetIdentifier() const { @@ -91,6 +94,10 @@ return InfoBarDelegate::ShouldExpire(details); } +bool OfflinePageInfoBarDelegate::DuplicateRequestExists() const { + return duplicate_request_exists_; +} + OfflinePageInfoBarDelegate* OfflinePageInfoBarDelegate::AsOfflinePageInfoBarDelegate() { return this;
diff --git a/chrome/browser/android/offline_pages/downloads/offline_page_infobar_delegate.h b/chrome/browser/android/offline_pages/downloads/offline_page_infobar_delegate.h index b9649406..3e4a1ac 100644 --- a/chrome/browser/android/offline_pages/downloads/offline_page_infobar_delegate.h +++ b/chrome/browser/android/offline_pages/downloads/offline_page_infobar_delegate.h
@@ -30,14 +30,15 @@ // shown for this file in the infobar text. static void Create(const base::Closure& confirm_continuation, const GURL& page_to_download, + bool exists_duplicate_request, content::WebContents* web_contents); ~OfflinePageInfoBarDelegate() override; private: - OfflinePageInfoBarDelegate( - const base::Closure& confirm_continuation, - const std::string& page_name, - const GURL& page_to_download); + OfflinePageInfoBarDelegate(const base::Closure& confirm_continuation, + const std::string& page_name, + const GURL& page_to_download, + bool duplicate_request_exists); // DuplicateDownloadInfoBarDelegate: infobars::InfoBarDelegate::InfoBarIdentifier GetIdentifier() const override; @@ -48,6 +49,7 @@ bool IsOfflinePage() const override; std::string GetPageURL() const override; bool ShouldExpire(const NavigationDetails& details) const override; + bool DuplicateRequestExists() const override; OfflinePageInfoBarDelegate* AsOfflinePageInfoBarDelegate() override; // Continuation called when the user chooses to create a new file. @@ -55,6 +57,7 @@ std::string page_name_; GURL page_to_download_; + bool duplicate_request_exists_; DISALLOW_COPY_AND_ASSIGN(OfflinePageInfoBarDelegate); };
diff --git a/chrome/browser/android/offline_pages/downloads/resource_throttle.cc b/chrome/browser/android/offline_pages/downloads/resource_throttle.cc index a5399b10..a09b33c4 100644 --- a/chrome/browser/android/offline_pages/downloads/resource_throttle.cc +++ b/chrome/browser/android/offline_pages/downloads/resource_throttle.cc
@@ -6,6 +6,7 @@ #include "base/logging.h" #include "chrome/browser/android/offline_pages/offline_page_utils.h" +#include "components/offline_pages/core/client_namespace_constants.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/resource_request_info.h" #include "content/public/browser/web_contents.h" @@ -26,8 +27,9 @@ content::WebContents* web_contents = contents_getter.Run(); if (!web_contents) return; - offline_pages::OfflinePageUtils::StartOfflinePageDownload( - web_contents->GetBrowserContext(), url); + offline_pages::OfflinePageUtils::ScheduleDownload( + web_contents, offline_pages::kDownloadNamespace, url, + offline_pages::OfflinePageUtils::DownloadUIActionFlags::ALL); } } // namespace
diff --git a/chrome/browser/android/offline_pages/downloads/resource_throttle_unittest.cc b/chrome/browser/android/offline_pages/downloads/resource_throttle_unittest.cc deleted file mode 100644 index b6b617a..0000000 --- a/chrome/browser/android/offline_pages/downloads/resource_throttle_unittest.cc +++ /dev/null
@@ -1,100 +0,0 @@ -// Copyright 2016 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/android/offline_pages/downloads/resource_throttle.h" - -#include "base/run_loop.h" -#include "base/test/test_mock_time_task_runner.h" -#include "base/threading/thread_task_runner_handle.h" -#include "chrome/browser/android/offline_pages/offline_page_model_factory.h" -#include "chrome/browser/android/offline_pages/offline_page_utils.h" -#include "chrome/browser/android/offline_pages/request_coordinator_factory.h" -#include "chrome/browser/android/offline_pages/test_offline_page_model_builder.h" -#include "chrome/browser/android/offline_pages/test_request_coordinator_builder.h" -#include "chrome/test/base/chrome_render_view_host_test_harness.h" -#include "components/offline_pages/core/background/request_coordinator.h" -#include "components/offline_pages/core/offline_page_item.h" -#include "components/offline_pages/core/offline_page_model.h" -#include "components/offline_pages/core/offline_page_test_archiver.h" -#include "content/public/browser/web_contents.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace { - -const GURL kTestPageUrl("http://mystery.site/foo.html"); -const char kClientNamespace[] = "download"; - -} // namespace - -namespace offline_pages { -namespace downloads { - -class ResourceThrottleTest : public ChromeRenderViewHostTestHarness { - public: - ResourceThrottleTest(); - ~ResourceThrottleTest() override; - - void SetUp() override; - - // Runs default thread. - void RunUntilIdle(); - - const std::vector<std::unique_ptr<SavePageRequest>>& last_requests() const { - return last_requests_; - } - - // Callback for getting requests. - void GetRequestsDone(GetRequestsResult result, - std::vector<std::unique_ptr<SavePageRequest>> requests); - - private: - GetRequestsResult last_get_requests_result_; - std::vector<std::unique_ptr<SavePageRequest>> last_requests_; -}; - -ResourceThrottleTest::ResourceThrottleTest() {} - -ResourceThrottleTest::~ResourceThrottleTest() {} - -void ResourceThrottleTest::SetUp() { - ChromeRenderViewHostTestHarness::SetUp(); - - OfflinePageModelFactory::GetInstance()->SetTestingFactoryAndUse( - browser_context(), BuildTestOfflinePageModel); - RunUntilIdle(); - RequestCoordinatorFactory::GetInstance()->SetTestingFactoryAndUse( - browser_context(), BuildTestRequestCoordinator); - RunUntilIdle(); -} - -void ResourceThrottleTest::RunUntilIdle() { - base::RunLoop().RunUntilIdle(); -} - -void ResourceThrottleTest::GetRequestsDone( - GetRequestsResult result, - std::vector<std::unique_ptr<SavePageRequest>> requests) { - last_get_requests_result_ = result; - last_requests_ = std::move(requests); -} - -TEST_F(ResourceThrottleTest, StartOfflinePageDownload) { - OfflinePageUtils::StartOfflinePageDownload(browser_context(), kTestPageUrl); - RequestCoordinator* request_coordinator = - RequestCoordinatorFactory::GetForBrowserContext(browser_context()); - - request_coordinator->queue()->GetRequests(base::Bind( - &ResourceThrottleTest::GetRequestsDone, base::Unretained(this))); - - // Wait for callbacks to finish, both request queue and offliner. - RunUntilIdle(); - - // Check the request queue is as expected. - EXPECT_EQ(1UL, last_requests().size()); - EXPECT_EQ(kTestPageUrl, last_requests().at(0)->url()); - EXPECT_EQ(kClientNamespace, last_requests().at(0)->client_id().name_space); -} - -} // namespace downloads -} // namespace offline_pages
diff --git a/chrome/browser/android/offline_pages/offline_page_bridge.cc b/chrome/browser/android/offline_pages/offline_page_bridge.cc index 15bef35..9819635 100644 --- a/chrome/browser/android/offline_pages/offline_page_bridge.cc +++ b/chrome/browser/android/offline_pages/offline_page_bridge.cc
@@ -616,6 +616,21 @@ ui_adapter_delegate->UnregisterTab(tab_id); } +void OfflinePageBridge::ScheduleDownload( + JNIEnv* env, + const JavaParamRef<jobject>& obj, + const base::android::JavaParamRef<jobject>& j_web_contents, + const JavaParamRef<jstring>& j_namespace, + const JavaParamRef<jstring>& j_url, + int ui_action) { + content::WebContents* web_contents = + content::WebContents::FromJavaWebContents(j_web_contents); + OfflinePageUtils::ScheduleDownload( + web_contents, ConvertJavaStringToUTF8(env, j_namespace), + GURL(ConvertJavaStringToUTF8(env, j_url)), + static_cast<OfflinePageUtils::DownloadUIActionFlags>(ui_action)); +} + void OfflinePageBridge::NotifyIfDoneLoading() const { if (!offline_page_model_->is_loaded()) return;
diff --git a/chrome/browser/android/offline_pages/offline_page_bridge.h b/chrome/browser/android/offline_pages/offline_page_bridge.h index ddf12fe..c6a8b62 100644 --- a/chrome/browser/android/offline_pages/offline_page_bridge.h +++ b/chrome/browser/android/offline_pages/offline_page_bridge.h
@@ -134,6 +134,13 @@ void UnregisterRecentTab(JNIEnv* env, const base::android::JavaParamRef<jobject>& obj, int tab_id); + void ScheduleDownload( + JNIEnv* env, + const base::android::JavaParamRef<jobject>& obj, + const base::android::JavaParamRef<jobject>& j_web_contents, + const base::android::JavaParamRef<jstring>& j_namespace, + const base::android::JavaParamRef<jstring>& j_url, + int ui_action); base::android::ScopedJavaGlobalRef<jobject> java_ref() { return java_ref_; }
diff --git a/chrome/browser/android/offline_pages/offline_page_tab_helper.cc b/chrome/browser/android/offline_pages/offline_page_tab_helper.cc index 43abfe9..f5da4074 100644 --- a/chrome/browser/android/offline_pages/offline_page_tab_helper.cc +++ b/chrome/browser/android/offline_pages/offline_page_tab_helper.cc
@@ -5,10 +5,14 @@ #include "chrome/browser/android/offline_pages/offline_page_tab_helper.h" #include "base/bind.h" +#include "base/guid.h" #include "base/logging.h" #include "base/memory/ptr_util.h" +#include "chrome/browser/android/offline_pages/downloads/offline_page_infobar_delegate.h" +#include "chrome/browser/android/offline_pages/downloads/offline_page_notification_bridge.h" #include "chrome/browser/android/offline_pages/offline_page_request_job.h" -#include "chrome/browser/android/offline_pages/offline_page_utils.h" +#include "chrome/browser/android/offline_pages/request_coordinator_factory.h" +#include "components/offline_pages/core/background/request_coordinator.h" #include "components/offline_pages/core/offline_page_item.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/navigation_controller.h" @@ -185,4 +189,65 @@ offline_info_.is_showing_offline_preview; } +void OfflinePageTabHelper::ScheduleDownloadHelper( + content::WebContents* web_contents, + const std::string& name_space, + const GURL& url, + OfflinePageUtils::DownloadUIActionFlags ui_action) { + OfflinePageUtils::CheckDuplicateDownloads( + web_contents->GetBrowserContext(), url, + base::Bind(&OfflinePageTabHelper::DuplicateCheckDoneForScheduleDownload, + weak_ptr_factory_.GetWeakPtr(), web_contents, name_space, url, + ui_action)); +} + +void OfflinePageTabHelper::DuplicateCheckDoneForScheduleDownload( + content::WebContents* web_contents, + const std::string& name_space, + const GURL& url, + OfflinePageUtils::DownloadUIActionFlags ui_action, + OfflinePageUtils::DuplicateCheckResult result) { + if (result != OfflinePageUtils::DuplicateCheckResult::NOT_FOUND) { + if (static_cast<int>(ui_action) & + static_cast<int>( + OfflinePageUtils::DownloadUIActionFlags::PROMPT_DUPLICATE)) { + OfflinePageInfoBarDelegate::Create( + base::Bind(&OfflinePageTabHelper::DoDownloadPageLater, + weak_ptr_factory_.GetWeakPtr(), web_contents, name_space, + url, ui_action), + url, + result == + OfflinePageUtils::DuplicateCheckResult::DUPLICATE_REQUEST_FOUND, + web_contents); + return; + } + } + + DoDownloadPageLater(web_contents, name_space, url, ui_action); +} + +void OfflinePageTabHelper::DoDownloadPageLater( + content::WebContents* web_contents, + const std::string& name_space, + const GURL& url, + OfflinePageUtils::DownloadUIActionFlags ui_action) { + offline_pages::RequestCoordinator* request_coordinator = + offline_pages::RequestCoordinatorFactory::GetForBrowserContext( + web_contents->GetBrowserContext()); + if (!request_coordinator) + return; + + offline_pages::RequestCoordinator::SavePageLaterParams params; + params.url = url; + params.client_id = offline_pages::ClientId(name_space, base::GenerateGUID()); + request_coordinator->SavePageLater(params); + + if (static_cast<int>(ui_action) & + static_cast<int>(OfflinePageUtils::DownloadUIActionFlags:: + SHOW_TOAST_ON_NEW_DOWNLOAD)) { + android::OfflinePageNotificationBridge notification_bridge; + notification_bridge.ShowDownloadingToast(); + } +} + } // namespace offline_pages
diff --git a/chrome/browser/android/offline_pages/offline_page_tab_helper.h b/chrome/browser/android/offline_pages/offline_page_tab_helper.h index 8e64365..2765a4f 100644 --- a/chrome/browser/android/offline_pages/offline_page_tab_helper.h +++ b/chrome/browser/android/offline_pages/offline_page_tab_helper.h
@@ -8,6 +8,7 @@ #include "base/macros.h" #include "base/memory/weak_ptr.h" #include "base/time/time.h" +#include "chrome/browser/android/offline_pages/offline_page_utils.h" #include "components/offline_pages/core/request_header/offline_page_header.h" #include "content/public/browser/web_contents_observer.h" #include "content/public/browser/web_contents_user_data.h" @@ -48,6 +49,19 @@ // during unit tests. const OfflinePageItem* GetOfflinePageForTest() const; + // Helper function which normally should only be called by + // OfflinePageUtils::ScheduleDownload to do the work. This is because we need + // to ensure |web_contents| is still valid after returning from the + // asynchronous call of duplicate checking function. The lifetime of + // OfflinePageTabHelper instance is tied with the associated |web_contents| + // and thus the callback will be automatically invalidated if |web_contents| + // is gone. + void ScheduleDownloadHelper( + content::WebContents* web_contents, + const std::string& name_space, + const GURL& url, + OfflinePageUtils::DownloadUIActionFlags ui_action); + private: friend class content::WebContentsUserData<OfflinePageTabHelper>; @@ -79,6 +93,17 @@ void SelectPageForURLDone(const OfflinePageItem* offline_page); + void DuplicateCheckDoneForScheduleDownload( + content::WebContents* web_contents, + const std::string& name_space, + const GURL& url, + OfflinePageUtils::DownloadUIActionFlags ui_action, + OfflinePageUtils::DuplicateCheckResult result); + void DoDownloadPageLater(content::WebContents* web_contents, + const std::string& name_space, + const GURL& url, + OfflinePageUtils::DownloadUIActionFlags ui_action); + // The provisional info about the offline page being loaded. This is set when // the offline interceptor decides to serve the offline page and it will be // moved to |offline_info_| once the navigation is committed without error.
diff --git a/chrome/browser/android/offline_pages/offline_page_utils.cc b/chrome/browser/android/offline_pages/offline_page_utils.cc index f46ad48..1fdff62 100644 --- a/chrome/browser/android/offline_pages/offline_page_utils.cc +++ b/chrome/browser/android/offline_pages/offline_page_utils.cc
@@ -5,14 +5,13 @@ #include "chrome/browser/android/offline_pages/offline_page_utils.h" #include "base/bind.h" -#include "base/guid.h" #include "base/location.h" +#include "base/metrics/histogram_macros.h" #include "base/strings/string_number_conversions.h" #include "base/strings/string_piece.h" #include "base/strings/string_util.h" #include "base/threading/thread_task_runner_handle.h" #include "base/time/time.h" -#include "chrome/browser/android/offline_pages/downloads/offline_page_notification_bridge.h" #include "chrome/browser/android/offline_pages/offline_page_mhtml_archiver.h" #include "chrome/browser/android/offline_pages/offline_page_model_factory.h" #include "chrome/browser/android/offline_pages/offline_page_tab_helper.h" @@ -75,6 +74,60 @@ : selected_page_for_original_url); } +bool IsSupportedByDownload(content::BrowserContext* browser_context, + const std::string& name_space) { + OfflinePageModel* offline_page_model = + OfflinePageModelFactory::GetForBrowserContext(browser_context); + DCHECK(offline_page_model); + ClientPolicyController* policy_controller = + offline_page_model->GetPolicyController(); + DCHECK(policy_controller); + return policy_controller->IsSupportedByDownload(name_space); +} + +void CheckDuplicateOngoingDownloads( + content::BrowserContext* browser_context, + const GURL& url, + const OfflinePageUtils::DuplicateCheckCallback& callback) { + RequestCoordinator* request_coordinator = + RequestCoordinatorFactory::GetForBrowserContext(browser_context); + if (!request_coordinator) + return; + + auto request_coordinator_continuation = + [](content::BrowserContext* browser_context, const GURL& url, + const OfflinePageUtils::DuplicateCheckCallback& callback, + std::vector<std::unique_ptr<SavePageRequest>> requests) { + base::Time latest_request_time; + for (auto& request : requests) { + if (IsSupportedByDownload(browser_context, + request->client_id().name_space) && + request->url() == url && + latest_request_time < request->creation_time()) { + latest_request_time = request->creation_time(); + } + } + + if (latest_request_time.is_null()) { + callback.Run(OfflinePageUtils::DuplicateCheckResult::NOT_FOUND); + } else { + // Using CUSTOM_COUNTS instead of time-oriented histogram to record + // samples in seconds rather than milliseconds. + UMA_HISTOGRAM_CUSTOM_COUNTS( + "OfflinePages.DownloadRequestTimeSinceDuplicateRequested", + (base::Time::Now() - latest_request_time).InSeconds(), + base::TimeDelta::FromSeconds(1).InSeconds(), + base::TimeDelta::FromDays(7).InSeconds(), 50); + + callback.Run( + OfflinePageUtils::DuplicateCheckResult::DUPLICATE_REQUEST_FOUND); + } + }; + + request_coordinator->GetAllRequests(base::Bind( + request_coordinator_continuation, browser_context, url, callback)); +} + } // namespace // static @@ -166,68 +219,6 @@ } // static -void OfflinePageUtils::CheckExistenceOfPagesWithURL( - content::BrowserContext* browser_context, - const std::string name_space, - const GURL& offline_page_url, - const PagesExistCallback& callback) { - OfflinePageModel* offline_page_model = - OfflinePageModelFactory::GetForBrowserContext(browser_context); - DCHECK(offline_page_model); - auto continuation = []( - const std::string& name_space, - const base::Callback<void(bool, const base::Time&)>& callback, - const std::vector<OfflinePageItem>& pages) { - base::Time latest_saved_time; - for (auto& page : pages) { - // TODO(fgorski): We should use policy to check for namespaces visible in - // UI. - if (page.client_id.name_space == name_space && - latest_saved_time < page.creation_time) { - latest_saved_time = page.creation_time; - } - } - callback.Run(!latest_saved_time.is_null(), latest_saved_time); - }; - - offline_page_model->GetPagesByURL( - offline_page_url, - OfflinePageModel::URLSearchMode::SEARCH_BY_FINAL_URL_ONLY, - base::Bind(continuation, name_space, callback)); -} - -// static -void OfflinePageUtils::CheckExistenceOfRequestsWithURL( - content::BrowserContext* browser_context, - const std::string name_space, - const GURL& offline_page_url, - const PagesExistCallback& callback) { - RequestCoordinator* request_coordinator = - RequestCoordinatorFactory::GetForBrowserContext(browser_context); - if (!request_coordinator) - return; - - auto request_coordinator_continuation = []( - const std::string& name_space, const GURL& offline_page_url, - const PagesExistCallback& callback, - std::vector<std::unique_ptr<SavePageRequest>> requests) { - base::Time latest_request_time; - for (auto& request : requests) { - if (request->url() == offline_page_url && - request->client_id().name_space == name_space && - latest_request_time < request->creation_time()) { - latest_request_time = request->creation_time(); - } - } - callback.Run(!latest_request_time.is_null(), latest_request_time); - }; - - request_coordinator->GetAllRequests( - base::Bind(request_coordinator_continuation, name_space, offline_page_url, - callback)); -} - -// static bool OfflinePageUtils::EqualsIgnoringFragment(const GURL& lhs, const GURL& rhs) { GURL::Replacements remove_params; @@ -240,27 +231,6 @@ } // static -void OfflinePageUtils::StartOfflinePageDownload( - content::BrowserContext* context, - const GURL& url) { - RequestCoordinator* request_coordinator = - RequestCoordinatorFactory::GetForBrowserContext(context); - - // TODO(dimich): Enable in Incognito when Android Downloads implement - // Incognito story. - if (!request_coordinator) - return; - - RequestCoordinator::SavePageLaterParams params; - params.url = url; - params.client_id = ClientId(kDownloadNamespace, base::GenerateGUID()); - request_coordinator->SavePageLater(params); - - android::OfflinePageNotificationBridge notification_bridge; - notification_bridge.ShowDownloadingToast(); -} - -// static GURL OfflinePageUtils::GetOriginalURLFromWebContents( content::WebContents* web_contents) { content::NavigationEntry* entry = @@ -270,4 +240,62 @@ return entry->GetRedirectChain().front(); } +// static +void OfflinePageUtils::CheckDuplicateDownloads( + content::BrowserContext* browser_context, + const GURL& url, + const DuplicateCheckCallback& callback) { + // First check for finished downloads, that is, saved pages. + OfflinePageModel* offline_page_model = + OfflinePageModelFactory::GetForBrowserContext(browser_context); + if (!offline_page_model) + return; + + auto continuation = [](content::BrowserContext* browser_context, + const GURL& url, + const DuplicateCheckCallback& callback, + const std::vector<OfflinePageItem>& pages) { + base::Time latest_saved_time; + for (const auto& offline_page_item : pages) { + if (IsSupportedByDownload(browser_context, + offline_page_item.client_id.name_space) && + latest_saved_time < offline_page_item.creation_time) { + latest_saved_time = offline_page_item.creation_time; + } + } + if (latest_saved_time.is_null()) { + // Then check for ongoing downloads, that is, requests. + CheckDuplicateOngoingDownloads(browser_context, url, callback); + } else { + // Using CUSTOM_COUNTS instead of time-oriented histogram to record + // samples in seconds rather than milliseconds. + UMA_HISTOGRAM_CUSTOM_COUNTS( + "OfflinePages.DownloadRequestTimeSinceDuplicateSaved", + (base::Time::Now() - latest_saved_time).InSeconds(), + base::TimeDelta::FromSeconds(1).InSeconds(), + base::TimeDelta::FromDays(7).InSeconds(), 50); + + callback.Run(DuplicateCheckResult::DUPLICATE_PAGE_FOUND); + } + }; + + offline_page_model->GetPagesByURL( + url, OfflinePageModel::URLSearchMode::SEARCH_BY_ALL_URLS, + base::Bind(continuation, browser_context, url, callback)); +} + +// static +void OfflinePageUtils::ScheduleDownload(content::WebContents* web_contents, + const std::string& name_space, + const GURL& url, + DownloadUIActionFlags ui_action) { + DCHECK(web_contents); + + OfflinePageTabHelper* tab_helper = + OfflinePageTabHelper::FromWebContents(web_contents); + if (!tab_helper) + return; + tab_helper->ScheduleDownloadHelper(web_contents, name_space, url, ui_action); +} + } // namespace offline_pages
diff --git a/chrome/browser/android/offline_pages/offline_page_utils.h b/chrome/browser/android/offline_pages/offline_page_utils.h index 3f32c120..7a4c3b7 100644 --- a/chrome/browser/android/offline_pages/offline_page_utils.h +++ b/chrome/browser/android/offline_pages/offline_page_utils.h
@@ -11,10 +11,6 @@ #include "components/offline_pages/core/offline_page_model.h" #include "url/gurl.h" -namespace base { -class Time; -} - namespace content { class BrowserContext; class WebContents; @@ -24,15 +20,35 @@ struct OfflinePageHeader; struct OfflinePageItem; -// Callback used for checking if specific |pages_exist| and what is the -// |latest_saved_time| for those pages. The former being a basic return type, -// while the latter is meant to be used as a helper to report UMA. -using PagesExistCallback = - base::Callback<void(bool /* pages_exist */, - const base::Time& /* latest_saved_time */)>; - class OfflinePageUtils { public: + // The result of checking duplicate page or request. + enum class DuplicateCheckResult { + // Page with same URL is found. + DUPLICATE_PAGE_FOUND, + // Request with same URL is found. + DUPLICATE_REQUEST_FOUND, + // No page or request with same URL is found. + NOT_FOUND + }; + + // Controls the UI action that could be triggered during download. + // GENERATED_JAVA_ENUM_PACKAGE: org.chromium.chrome.browser.offlinepages + // GENERATED_JAVA_CLASS_NAME_OVERRIDE: DownloadUiActionFlags + enum class DownloadUIActionFlags { + NONE = 0x0, + // Shows an infobar to prompt the user for re-download when the duplicate + // page or request is found. + PROMPT_DUPLICATE = 0x1, + // Shows a toast when the new download starts. + SHOW_TOAST_ON_NEW_DOWNLOAD = 0x2, + // All actions. + ALL = 0xFFFF + }; + + // Callback to inform the duplicate checking result. + using DuplicateCheckCallback = base::Callback<void(DuplicateCheckResult)>; + // Returns via callback an offline page related to |url|, if any. The // page is chosen based on creation date; a more recently created offline // page will be preferred over an older one. The offline page captured from @@ -72,36 +88,27 @@ // custom tab. static bool CurrentlyShownInCustomTab(content::WebContents* web_contents); - // Performs a check, whether pages with specified |url| and |name_space| - // already exist. Result is returned in a |callback|, where first parameter - // indicates whether offline pages exist, while second is a helper value to - // report UMA, indicating the time the latest existing page with such - // parameters was saved. - static void CheckExistenceOfPagesWithURL( - content::BrowserContext* browser_context, - const std::string name_space, - const GURL& url, - const PagesExistCallback& callback); - - // Performs a check, whether requests with specified |url| and |name_space| - // already exist. Result is returned in a |callback|, where first parameter - // indicates whether requests exist, while second is a helper value to report - // UMA, indicating the time the latest existing request with such parameters - // was created. - static void CheckExistenceOfRequestsWithURL( - content::BrowserContext* browser_context, - const std::string name_space, - const GURL& url, - const PagesExistCallback& callback); - static bool EqualsIgnoringFragment(const GURL& lhs, const GURL& rhs); - static void StartOfflinePageDownload(content::BrowserContext* context, - const GURL& url); - // Returns original URL of the given web contents. Empty URL is returned if // no redirect occurred. static GURL GetOriginalURLFromWebContents(content::WebContents* web_contents); + + // Checks for duplicates in all finished or ongoing downloads. Only pages and + // requests that could result in showing in Download UI are searched for + // |url| match. Result is returned in |callback|. See DuplicateCheckCallback + // for more details. + static void CheckDuplicateDownloads(content::BrowserContext* browser_context, + const GURL& url, + const DuplicateCheckCallback& callback); + + // Schedules to download a page from |url| and categorize under |name_space|. + // The duplicate pages or requests will be checked. Note that |url| can be + // different from the one rendered in |web_contents|. + static void ScheduleDownload(content::WebContents* web_contents, + const std::string& name_space, + const GURL& url, + DownloadUIActionFlags ui_action); }; } // namespace offline_pages
diff --git a/chrome/browser/android/offline_pages/offline_page_utils_unittest.cc b/chrome/browser/android/offline_pages/offline_page_utils_unittest.cc index 8f55101..7c4eed2 100644 --- a/chrome/browser/android/offline_pages/offline_page_utils_unittest.cc +++ b/chrome/browser/android/offline_pages/offline_page_utils_unittest.cc
@@ -18,6 +18,7 @@ #include "base/threading/thread_task_runner_handle.h" #include "base/time/time.h" #include "chrome/browser/android/offline_pages/offline_page_model_factory.h" +#include "chrome/browser/android/offline_pages/offline_page_tab_helper.h" #include "chrome/browser/android/offline_pages/request_coordinator_factory.h" #include "chrome/browser/android/offline_pages/test_offline_page_model_builder.h" #include "chrome/browser/android/offline_pages/test_request_coordinator_builder.h" @@ -31,6 +32,7 @@ #include "components/offline_pages/core/offline_page_test_archiver.h" #include "components/offline_pages/core/offline_page_test_store.h" #include "components/offline_pages/core/offline_page_types.h" +#include "content/public/browser/web_contents.h" #include "content/public/test/test_browser_thread_bundle.h" #include "net/base/filename_util.h" #include "testing/gtest/include/gtest/gtest.h" @@ -48,14 +50,17 @@ const char* kTestPage2ClientId = "5678"; const char* kTestPage3ClientId = "7890"; -void HasDuplicatesCallback(bool* out_has_duplicates, - base::Time* out_latest_saved_time, - bool has_duplicates, - const base::Time& latest_saved_time) { - DCHECK(out_has_duplicates); - DCHECK(out_latest_saved_time); - *out_has_duplicates = has_duplicates; - *out_latest_saved_time = latest_saved_time; +void CheckDuplicateDownloadsCallback( + OfflinePageUtils::DuplicateCheckResult* out_result, + OfflinePageUtils::DuplicateCheckResult result) { + DCHECK(out_result); + *out_result = result; +} + +void GetAllRequestsCallback( + std::vector<std::unique_ptr<SavePageRequest>>* out_requests, + std::vector<std::unique_ptr<SavePageRequest>> requests) { + *out_requests = std::move(requests); } } // namespace @@ -75,6 +80,10 @@ const ClientId& client_id, std::unique_ptr<OfflinePageArchiver> archiver); + // Return number of matches found. + int FindRequestByNamespaceAndURL(const std::string& name_space, + const GURL& url); + // Necessary callbacks for the offline page model. void OnSavePageDone(SavePageResult result, int64_t offlineId); void OnClearAllDone(); @@ -85,6 +94,7 @@ void SetLastPathCreatedByArchiver(const base::FilePath& file_path) override; TestingProfile* profile() { return &profile_; } + content::WebContents* web_contents() const { return web_contents_.get(); } int64_t offline_id() const { return offline_id_; } @@ -99,6 +109,7 @@ int64_t offline_id_; GURL url_; TestingProfile profile_; + std::unique_ptr<content::WebContents> web_contents_; base::test::ScopedFeatureList scoped_feature_list_; }; @@ -112,6 +123,11 @@ scoped_feature_list_.InitAndEnableFeature( offline_pages::kOfflineBookmarksFeature); + // Create a test web contents. + web_contents_.reset(content::WebContents::Create( + content::WebContents::CreateParams(profile()))); + OfflinePageTabHelper::CreateForWebContents(web_contents_.get()); + // Set up the factory for testing. OfflinePageModelFactory::GetInstance()->SetTestingFactoryAndUse( &profile_, BuildTestOfflinePageModel); @@ -204,46 +220,80 @@ return archiver; } -TEST_F(OfflinePageUtilsTest, CheckExistenceOfPagesWithURL) { - bool has_duplicates = false; - base::Time latest_saved_time; - // This page should be available. - OfflinePageUtils::CheckExistenceOfPagesWithURL( - profile(), kDownloadNamespace, kTestPage1Url, - base::Bind(&HasDuplicatesCallback, base::Unretained(&has_duplicates), - base::Unretained(&latest_saved_time))); +int OfflinePageUtilsTest::FindRequestByNamespaceAndURL( + const std::string& name_space, + const GURL& url) { + RequestCoordinator* request_coordinator = + RequestCoordinatorFactory::GetForBrowserContext(profile()); + std::vector<std::unique_ptr<SavePageRequest>> requests; + request_coordinator->GetAllRequests( + base::Bind(&GetAllRequestsCallback, base::Unretained(&requests))); RunUntilIdle(); - EXPECT_TRUE(has_duplicates); - EXPECT_FALSE(latest_saved_time.is_null()); - // This one should be missing - OfflinePageUtils::CheckExistenceOfPagesWithURL( - profile(), kDownloadNamespace, kTestPage3Url, - base::Bind(&HasDuplicatesCallback, base::Unretained(&has_duplicates), - base::Unretained(&latest_saved_time))); - RunUntilIdle(); - EXPECT_FALSE(has_duplicates); - EXPECT_TRUE(latest_saved_time.is_null()); + + int matches = 0; + for (auto& request : requests) { + if (request->url() == url && + request->client_id().name_space == name_space) { + matches++; + } + } + return matches; } -TEST_F(OfflinePageUtilsTest, CheckExistenceOfRequestsWithURL) { - bool has_duplicates = false; - base::Time latest_saved_time; - // This page should be available. - OfflinePageUtils::CheckExistenceOfRequestsWithURL( - profile(), kDownloadNamespace, kTestPage3Url, - base::Bind(&HasDuplicatesCallback, base::Unretained(&has_duplicates), - base::Unretained(&latest_saved_time))); +TEST_F(OfflinePageUtilsTest, CheckDuplicateDownloads) { + OfflinePageUtils::DuplicateCheckResult result = + OfflinePageUtils::DuplicateCheckResult::NOT_FOUND; + + // The duplicate page should be found for this. + OfflinePageUtils::CheckDuplicateDownloads( + profile(), kTestPage1Url, + base::Bind(&CheckDuplicateDownloadsCallback, base::Unretained(&result))); RunUntilIdle(); - EXPECT_TRUE(has_duplicates); - EXPECT_FALSE(latest_saved_time.is_null()); - // This one should be missing - OfflinePageUtils::CheckExistenceOfRequestsWithURL( - profile(), kDownloadNamespace, kTestPage1Url, - base::Bind(&HasDuplicatesCallback, base::Unretained(&has_duplicates), - base::Unretained(&latest_saved_time))); + EXPECT_EQ(OfflinePageUtils::DuplicateCheckResult::DUPLICATE_PAGE_FOUND, + result); + + // The duplicate request should be found for this. + OfflinePageUtils::CheckDuplicateDownloads( + profile(), kTestPage3Url, + base::Bind(&CheckDuplicateDownloadsCallback, base::Unretained(&result))); RunUntilIdle(); - EXPECT_FALSE(has_duplicates); - EXPECT_TRUE(latest_saved_time.is_null()); + EXPECT_EQ(OfflinePageUtils::DuplicateCheckResult::DUPLICATE_REQUEST_FOUND, + result); + + // No duplicate should be found for this. + OfflinePageUtils::CheckDuplicateDownloads( + profile(), kTestPage4Url, + base::Bind(&CheckDuplicateDownloadsCallback, base::Unretained(&result))); + RunUntilIdle(); + EXPECT_EQ(OfflinePageUtils::DuplicateCheckResult::NOT_FOUND, result); +} + +TEST_F(OfflinePageUtilsTest, ScheduleDownload) { + // Pre-check. + ASSERT_EQ(0, FindRequestByNamespaceAndURL(kDownloadNamespace, kTestPage1Url)); + ASSERT_EQ(1, FindRequestByNamespaceAndURL(kDownloadNamespace, kTestPage3Url)); + ASSERT_EQ(0, FindRequestByNamespaceAndURL(kDownloadNamespace, kTestPage4Url)); + + // Re-downloading a page with duplicate page found. + OfflinePageUtils::ScheduleDownload( + web_contents(), kDownloadNamespace, kTestPage1Url, + OfflinePageUtils::DownloadUIActionFlags::NONE); + RunUntilIdle(); + EXPECT_EQ(1, FindRequestByNamespaceAndURL(kDownloadNamespace, kTestPage1Url)); + + // Re-downloading a page with duplicate request found. + OfflinePageUtils::ScheduleDownload( + web_contents(), kDownloadNamespace, kTestPage3Url, + OfflinePageUtils::DownloadUIActionFlags::NONE); + RunUntilIdle(); + EXPECT_EQ(2, FindRequestByNamespaceAndURL(kDownloadNamespace, kTestPage3Url)); + + // Downloading a page with no duplicate found. + OfflinePageUtils::ScheduleDownload( + web_contents(), kDownloadNamespace, kTestPage4Url, + OfflinePageUtils::DownloadUIActionFlags::NONE); + RunUntilIdle(); + EXPECT_EQ(1, FindRequestByNamespaceAndURL(kDownloadNamespace, kTestPage4Url)); } TEST_F(OfflinePageUtilsTest, EqualsIgnoringFragment) {
diff --git a/chrome/browser/android/search_geolocation/search_geolocation_service.cc b/chrome/browser/android/search_geolocation/search_geolocation_service.cc index 59f040a6..7977997b 100644 --- a/chrome/browser/android/search_geolocation/search_geolocation_service.cc +++ b/chrome/browser/android/search_geolocation/search_geolocation_service.cc
@@ -7,7 +7,6 @@ #include "base/callback.h" #include "base/feature_list.h" #include "base/values.h" -#include "chrome/browser/android/location_settings_impl.h" #include "chrome/browser/android/search_geolocation/search_geolocation_disclosure_tab_helper.h" #include "chrome/browser/content_settings/host_content_settings_map_factory.h" #include "chrome/browser/profiles/profile.h" @@ -135,8 +134,7 @@ : profile_(profile), pref_service_(profile_->GetPrefs()), host_content_settings_map_( - HostContentSettingsMapFactory::GetForProfile(profile_)), - location_settings_(new LocationSettingsImpl()) { + HostContentSettingsMapFactory::GetForProfile(profile_)) { // This class should never be constructed in incognito. DCHECK(!profile_->IsOffTheRecord()); @@ -173,9 +171,6 @@ return false; } - if (!location_settings_->HasAndroidLocationPermission()) - return false; - return true; } @@ -324,8 +319,3 @@ delegate_->SetDSEChangedCallback(base::Bind( &SearchGeolocationService::OnDSEChanged, base::Unretained(this))); } - -void SearchGeolocationService::SetLocationSettingsForTest( - std::unique_ptr<LocationSettings> settings) { - location_settings_ = std::move(settings); -}
diff --git a/chrome/browser/android/search_geolocation/search_geolocation_service.h b/chrome/browser/android/search_geolocation/search_geolocation_service.h index ee2ae977..9671179 100644 --- a/chrome/browser/android/search_geolocation/search_geolocation_service.h +++ b/chrome/browser/android/search_geolocation/search_geolocation_service.h
@@ -7,7 +7,6 @@ #include "base/callback_forward.h" #include "base/memory/singleton.h" -#include "chrome/browser/android/location_settings.h" #include "components/content_settings/core/common/content_settings.h" #include "components/keyed_service/content/browser_context_keyed_service_factory.h" #include "components/keyed_service/core/keyed_service.h" @@ -147,13 +146,10 @@ void SetSearchEngineDelegateForTest( std::unique_ptr<SearchEngineDelegate> delegate); - void SetLocationSettingsForTest(std::unique_ptr<LocationSettings> settings); - Profile* profile_; PrefService* pref_service_; HostContentSettingsMap* host_content_settings_map_; std::unique_ptr<SearchEngineDelegate> delegate_; - std::unique_ptr<LocationSettings> location_settings_; }; #endif // CHROME_BROWSER_ANDROID_SEARCH_GEOLOCATION_SEARCH_GEOLOCATION_SERVICE_H_
diff --git a/chrome/browser/android/search_geolocation/search_geolocation_service_unittest.cc b/chrome/browser/android/search_geolocation/search_geolocation_service_unittest.cc index d46864e..a74026e 100644 --- a/chrome/browser/android/search_geolocation/search_geolocation_service_unittest.cc +++ b/chrome/browser/android/search_geolocation/search_geolocation_service_unittest.cc
@@ -10,7 +10,6 @@ #include "base/callback.h" #include "base/memory/ptr_util.h" #include "base/test/scoped_feature_list.h" -#include "chrome/browser/android/mock_location_settings.h" #include "chrome/browser/content_settings/host_content_settings_map_factory.h" #include "chrome/common/chrome_features.h" #include "chrome/common/pref_names.h" @@ -77,12 +76,6 @@ auto test_delegate = base::MakeUnique<TestSearchEngineDelegate>(); test_delegate_ = test_delegate.get(); GetService()->SetSearchEngineDelegateForTest(std::move(test_delegate)); - - auto mock_settings = base::MakeUnique<MockLocationSettings>(); - mock_settings->SetLocationStatus( - true /* has_android_location_permission */, - true /* is_system_location_setting_enabled */); - GetService()->SetLocationSettingsForTest(std::move(mock_settings)); } void TearDown() override { @@ -155,8 +148,7 @@ EXPECT_TRUE(GetService()->UseDSEGeolocationSetting(ToOrigin(kGoogleURL))); EXPECT_FALSE(GetService()->GetDSEGeolocationSetting()); - // Nothing happens if the pref is already set when the service is - // initialized. + // Nothing happens if the pref is already set when the service is initialized. SetContentSetting(kGoogleURL, CONTENT_SETTING_ASK); ReinitializeService(false /* clear_pref */); EXPECT_TRUE(GetService()->UseDSEGeolocationSetting(ToOrigin(kGoogleURL)));
diff --git a/chrome/browser/android/vr_shell/BUILD.gn b/chrome/browser/android/vr_shell/BUILD.gn index 753ae749..d73399c 100644 --- a/chrome/browser/android/vr_shell/BUILD.gn +++ b/chrome/browser/android/vr_shell/BUILD.gn
@@ -47,8 +47,6 @@ "vr_gl_util.h", "vr_input_manager.cc", "vr_input_manager.h", - "vr_math.cc", - "vr_math.h", "vr_omnibox.cc", "vr_omnibox.h", "vr_shell.cc", @@ -128,9 +126,8 @@ # Ensure libgvr static library appears before gcc library in linking order. # See https://crbug.com/704305 for details. - libs = [ - "//third_party/gvr-android-sdk/libgvr_shim_static_${current_cpu}.a", - ] + libs = + [ "//third_party/gvr-android-sdk/libgvr_shim_static_${current_cpu}.a" ] data = [ "test/data/sample_inline.gltf",
diff --git a/chrome/browser/android/vr_shell/non_presenting_gvr_delegate.cc b/chrome/browser/android/vr_shell/non_presenting_gvr_delegate.cc index 79d92e3..f8cc3e1 100644 --- a/chrome/browser/android/vr_shell/non_presenting_gvr_delegate.cc +++ b/chrome/browser/android/vr_shell/non_presenting_gvr_delegate.cc
@@ -155,9 +155,9 @@ return; } - gvr::Sizei webvr_size = GvrDelegate::GetRecommendedWebVrSize(gvr_api_.get()); - DVLOG(1) << __FUNCTION__ << ": resize recommended to " << webvr_size.width - << "x" << webvr_size.height; + gfx::Size webvr_size = GvrDelegate::GetRecommendedWebVrSize(gvr_api_.get()); + DVLOG(1) << __FUNCTION__ << ": resize recommended to " << webvr_size.width() + << "x" << webvr_size.height(); callback.Run( GvrDelegate::CreateVRDisplayInfo(gvr_api_.get(), webvr_size, device_id)); }
diff --git a/chrome/browser/android/vr_shell/non_presenting_gvr_delegate.h b/chrome/browser/android/vr_shell/non_presenting_gvr_delegate.h index c384edf..d921ea4 100644 --- a/chrome/browser/android/vr_shell/non_presenting_gvr_delegate.h +++ b/chrome/browser/android/vr_shell/non_presenting_gvr_delegate.h
@@ -31,9 +31,9 @@ void SubmitWebVRFrame(int16_t frame_index, const gpu::MailboxHolder& mailbox) override {} void UpdateWebVRTextureBounds(int16_t frame_index, - const gvr::Rectf& left_bounds, - const gvr::Rectf& right_bounds, - const gvr::Sizei& source_size) override {} + const gfx::RectF& left_bounds, + const gfx::RectF& right_bounds, + const gfx::Size& source_size) override {} void OnVRVsyncProviderRequest( device::mojom::VRVSyncProviderRequest request) override; void UpdateVSyncInterval(int64_t timebase_nanos,
diff --git a/chrome/browser/android/vr_shell/ui_elements.cc b/chrome/browser/android/vr_shell/ui_elements.cc index 82d1cdb0..c223271 100644 --- a/chrome/browser/android/vr_shell/ui_elements.cc +++ b/chrome/browser/android/vr_shell/ui_elements.cc
@@ -10,25 +10,23 @@ #include "base/time/time.h" #include "chrome/browser/android/vr_shell/animation.h" #include "chrome/browser/android/vr_shell/easing.h" +#include "device/vr/vr_math.h" namespace vr_shell { namespace { -bool GetRayPlaneDistance(const gvr::Vec3f& ray_origin, - const gvr::Vec3f& ray_vector, - const gvr::Vec3f& plane_origin, - const gvr::Vec3f& plane_normal, +bool GetRayPlaneDistance(const gfx::Point3F& ray_origin, + const gfx::Vector3dF& ray_vector, + const gfx::Point3F& plane_origin, + const gfx::Vector3dF& plane_normal, float* distance) { - float denom = vr_shell::VectorDot(ray_vector, plane_normal); + float denom = gfx::DotProduct(ray_vector, plane_normal); if (denom == 0) { return false; } - gvr::Vec3f rel; - rel.x = ray_origin.x - plane_origin.x; - rel.y = ray_origin.y - plane_origin.y; - rel.z = ray_origin.z - plane_origin.z; - *distance = -vr_shell::VectorDot(plane_normal, rel) / denom; + gfx::Vector3dF rel = ray_origin - plane_origin; + *distance = -gfx::DotProduct(plane_normal, rel) / denom; return true; } @@ -39,59 +37,65 @@ } void Transform::MakeIdentity() { - SetIdentityM(to_world); + vr::SetIdentityM(&to_world); } -void Transform::Rotate(gvr::Quatf quat) { +void Transform::Rotate(const vr::Quatf& quat) { // TODO(klausw): use specialized rotation code? Constructing the matrix // via axis-angle quaternion is inefficient. - gvr::Mat4f forward = QuatToMatrix(quat); - to_world = MatrixMul(forward, to_world); + vr::Mat4f forward; + vr::QuatToMatrix(quat, &forward); + vr::MatrixMul(forward, to_world, &to_world); } -void Transform::Rotate(float ax, float ay, float az, float rad) { - Rotate(QuatFromAxisAngle({ax, ay, az}, rad)); +void Transform::Rotate(const vr::RotationAxisAngle& axis_angle) { + Rotate(vr::QuatFromAxisAngle(axis_angle)); } -void Transform::Translate(float tx, float ty, float tz) { - TranslateM(to_world, to_world, tx, ty, tz); +void Transform::Translate(const gfx::Vector3dF& translation) { + vr::TranslateM(to_world, translation, &to_world); } -void Transform::Scale(float sx, float sy, float sz) { - ScaleM(to_world, to_world, sx, sy, sz); +void Transform::Scale(const gfx::Vector3dF& scale) { + vr::ScaleM(to_world, scale, &to_world); } -const gvr::Mat4f& WorldRectangle::TransformMatrix() const { +const vr::Mat4f& WorldRectangle::TransformMatrix() const { return transform_.to_world; } -gvr::Vec3f WorldRectangle::GetCenter() const { - const gvr::Vec3f kOrigin = {0.0f, 0.0f, 0.0f}; - return MatrixVectorMul(transform_.to_world, kOrigin); +gfx::Point3F WorldRectangle::GetCenter() const { + const gfx::Point3F kOrigin(0.0f, 0.0f, 0.0f); + return kOrigin + vr::GetTranslation(transform_.to_world); } -gvr::Vec2f WorldRectangle::GetUnitRectangleCoordinates( - const gvr::Vec3f& world_point) { - const gvr::Mat4f& transform = transform_.to_world; - gvr::Vec3f origin = MatrixVectorMul(transform, gvr::Vec3f({0, 0, 0})); - gvr::Vec3f xAxis = MatrixVectorMul(transform, gvr::Vec3f({1, 0, 0})); - gvr::Vec3f yAxis = MatrixVectorMul(transform, gvr::Vec3f({0, 1, 0})); - xAxis = VectorSubtract(xAxis, origin); - yAxis = VectorSubtract(yAxis, origin); - gvr::Vec3f point = VectorSubtract(world_point, origin); +gfx::PointF WorldRectangle::GetUnitRectangleCoordinates( + const gfx::Point3F& world_point) { + // TODO(acondor): Simplify the math in this function. + const vr::Mat4f& transform = transform_.to_world; + gfx::Vector3dF origin = + vr::MatrixVectorMul(transform, gfx::Vector3dF(0, 0, 0)); + gfx::Vector3dF x_axis = + vr::MatrixVectorMul(transform, gfx::Vector3dF(1, 0, 0)); + gfx::Vector3dF y_axis = + vr::MatrixVectorMul(transform, gfx::Vector3dF(0, 1, 0)); + x_axis.Subtract(origin); + y_axis.Subtract(origin); + gfx::Point3F point = world_point - origin; + gfx::Vector3dF v_point(point.x(), point.y(), point.z()); - float x = VectorDot(point, xAxis) / VectorDot(xAxis, xAxis); - float y = VectorDot(point, yAxis) / VectorDot(yAxis, yAxis); - return {x, y}; + float x = gfx::DotProduct(v_point, x_axis) / gfx::DotProduct(x_axis, x_axis); + float y = gfx::DotProduct(v_point, y_axis) / gfx::DotProduct(y_axis, y_axis); + return gfx::PointF(x, y); } -gvr::Vec3f WorldRectangle::GetNormal() const { - const gvr::Vec3f kNormalOrig = {0.0f, 0.0f, -1.0f}; - return MatrixVectorRotate(transform_.to_world, kNormalOrig); +gfx::Vector3dF WorldRectangle::GetNormal() const { + const gfx::Vector3dF kNormalOrig = {0.0f, 0.0f, -1.0f}; + return vr::MatrixVectorRotate(transform_.to_world, kNormalOrig); } -bool WorldRectangle::GetRayDistance(const gvr::Vec3f& ray_origin, - const gvr::Vec3f& ray_vector, +bool WorldRectangle::GetRayDistance(const gfx::Point3F& ray_origin, + const gfx::Vector3dF& ray_vector, float* distance) const { return GetRayPlaneDistance(ray_origin, ray_vector, GetCenter(), GetNormal(), distance); @@ -111,19 +115,19 @@ if (animation.from.size() == 0) { switch (animation.property) { case Animation::COPYRECT: - animation.from.push_back(copy_rect.x); - animation.from.push_back(copy_rect.y); - animation.from.push_back(copy_rect.width); - animation.from.push_back(copy_rect.height); + animation.from.push_back(copy_rect.x()); + animation.from.push_back(copy_rect.y()); + animation.from.push_back(copy_rect.width()); + animation.from.push_back(copy_rect.height()); break; case Animation::SIZE: - animation.from.push_back(size.x); - animation.from.push_back(size.y); + animation.from.push_back(size.x()); + animation.from.push_back(size.y()); break; case Animation::SCALE: - animation.from.push_back(scale.x); - animation.from.push_back(scale.y); - animation.from.push_back(scale.z); + animation.from.push_back(scale.x()); + animation.from.push_back(scale.y()); + animation.from.push_back(scale.z()); break; case Animation::ROTATION: animation.from.push_back(rotation.x); @@ -132,9 +136,9 @@ animation.from.push_back(rotation.angle); break; case Animation::TRANSLATION: - animation.from.push_back(translation.x); - animation.from.push_back(translation.y); - animation.from.push_back(translation.z); + animation.from.push_back(translation.x()); + animation.from.push_back(translation.y()); + animation.from.push_back(translation.z()); break; case Animation::OPACITY: animation.from.push_back(opacity); @@ -159,21 +163,16 @@ switch (animation.property) { case Animation::COPYRECT: CHECK_EQ(animation.from.size(), 4u); - copy_rect.x = values[0]; - copy_rect.y = values[1]; - copy_rect.width = values[2]; - copy_rect.height = values[3]; + copy_rect.SetRect(values[0], values[1], values[2], values[3]); break; case Animation::SIZE: CHECK_EQ(animation.from.size(), 2u); - size.x = values[0]; - size.y = values[1]; + size.set_x(values[0]); + size.set_y(values[1]); break; case Animation::SCALE: CHECK_EQ(animation.from.size(), 3u); - scale.x = values[0]; - scale.y = values[1]; - scale.z = values[2]; + scale = {values[0], values[1], values[2]}; break; case Animation::ROTATION: CHECK_EQ(animation.from.size(), 4u); @@ -184,9 +183,7 @@ break; case Animation::TRANSLATION: CHECK_EQ(animation.from.size(), 3u); - translation.x = values[0]; - translation.y = values[1]; - translation.z = values[2]; + translation = {values[0], values[1], values[2]}; break; case Animation::OPACITY: CHECK_EQ(animation.from.size(), 1u);
diff --git a/chrome/browser/android/vr_shell/ui_elements.h b/chrome/browser/android/vr_shell/ui_elements.h index b502f5d..a5990688 100644 --- a/chrome/browser/android/vr_shell/ui_elements.h +++ b/chrome/browser/android/vr_shell/ui_elements.h
@@ -10,8 +10,7 @@ #include <vector> #include "base/macros.h" -#include "chrome/browser/android/vr_shell/vr_math.h" -#include "third_party/gvr-android-sdk/src/libraries/headers/vr/gvr/capi/include/gvr_types.h" +#include "device/vr/vr_types.h" namespace base { class TimeTicks; @@ -53,27 +52,27 @@ Transform(); void MakeIdentity(); - void Rotate(gvr::Quatf quat); - void Rotate(float ax, float ay, float az, float rad); - void Translate(float tx, float ty, float tz); - void Scale(float sx, float sy, float sz); + void Rotate(const vr::Quatf& quat); + void Rotate(const vr::RotationAxisAngle& axis_angle); + void Translate(const gfx::Vector3dF& translation); + void Scale(const gfx::Vector3dF& scale); - gvr::Mat4f to_world; + vr::Mat4f to_world; }; class WorldRectangle { public: - const gvr::Mat4f& TransformMatrix() const; + const vr::Mat4f& TransformMatrix() const; Transform* mutable_transform() { return &transform_; } - gvr::Vec3f GetCenter() const; - gvr::Vec3f GetNormal() const; + gfx::Point3F GetCenter() const; + gfx::Vector3dF GetNormal() const; // Computes the distance from |ray_origin| to this rectangles's plane, along // |ray_vector|. Returns true and populates |distance| if the calculation is // possible, and false if the ray is parallel to the plane. - bool GetRayDistance(const gvr::Vec3f& ray_origin, - const gvr::Vec3f& ray_vector, + bool GetRayDistance(const gfx::Point3F& ray_origin, + const gfx::Vector3dF& ray_vector, float* distance) const; // Projects a 3D world point onto the X and Y axes of the transformed @@ -81,7 +80,7 @@ // rectangle. This allows beam intersection points to be mapped to sprite // pixel coordinates. Points that fall onto the rectangle will generate X and // Y values on the interval [-0.5, 0.5]. - gvr::Vec2f GetUnitRectangleCoordinates(const gvr::Vec3f& world_point); + gfx::PointF GetUnitRectangleCoordinates(const gfx::Point3F& world_point); private: Transform transform_; @@ -120,20 +119,20 @@ bool lock_to_fov = false; // Specifies the region (in pixels) of a texture to render. - Recti copy_rect = {0, 0, 0, 0}; + gfx::Rect copy_rect = {0, 0, 0, 0}; // The size of the object. This does not affect children. - gvr::Vec3f size = {1.0f, 1.0f, 1.0f}; + gfx::Vector3dF size = {1.0f, 1.0f, 1.0f}; // The scale of the object, and its children. - gvr::Vec3f scale = {1.0f, 1.0f, 1.0f}; + gfx::Vector3dF scale = {1.0f, 1.0f, 1.0f}; // The rotation of the object, and its children. - RotationAxisAngle rotation = {1.0f, 0.0f, 0.0f, 0.0f}; + vr::RotationAxisAngle rotation = {1.0f, 0.0f, 0.0f, 0.0f}; // The translation of the object, and its children. Translation is applied // after rotation and scaling. - gvr::Vec3f translation = {0.0f, 0.0f, 0.0f}; + gfx::Vector3dF translation = {0.0f, 0.0f, 0.0f}; // The opacity of the object (between 0.0 and 1.0). float opacity = 1.0f; @@ -155,8 +154,8 @@ Fill fill = Fill::NONE; - Colorf edge_color = {1.0f, 1.0f, 1.0f, 1.0f}; - Colorf center_color = {1.0f, 1.0f, 1.0f, 1.0f}; + vr::Colorf edge_color = {1.0f, 1.0f, 1.0f, 1.0f}; + vr::Colorf center_color = {1.0f, 1.0f, 1.0f, 1.0f}; int gridline_count = 1;
diff --git a/chrome/browser/android/vr_shell/ui_elements_unittest.cc b/chrome/browser/android/vr_shell/ui_elements_unittest.cc index fd509d3..56f200e3 100644 --- a/chrome/browser/android/vr_shell/ui_elements_unittest.cc +++ b/chrome/browser/android/vr_shell/ui_elements_unittest.cc
@@ -9,18 +9,19 @@ #include "base/macros.h" #include "chrome/browser/android/vr_shell/animation.h" #include "chrome/browser/android/vr_shell/easing.h" +#include "device/vr/vr_types.h" #include "testing/gtest/include/gtest/gtest.h" -#define EXPECT_VEC3F_EQ(a, b) \ - EXPECT_FLOAT_EQ(a.x, b.x); \ - EXPECT_FLOAT_EQ(a.y, b.y); \ - EXPECT_FLOAT_EQ(a.z, b.z); +#define EXPECT_VEC3F_EQ(a, b) \ + EXPECT_FLOAT_EQ(a.x(), b.x()); \ + EXPECT_FLOAT_EQ(a.y(), b.y()); \ + EXPECT_FLOAT_EQ(a.z(), b.z()); -#define EXPECT_RECTF_EQ(a, b) \ - EXPECT_FLOAT_EQ(a.x, b.x); \ - EXPECT_FLOAT_EQ(a.y, b.y); \ - EXPECT_FLOAT_EQ(a.width, b.width); \ - EXPECT_FLOAT_EQ(a.height, b.height); +#define EXPECT_RECTF_EQ(a, b) \ + EXPECT_FLOAT_EQ(a.x(), b.x()); \ + EXPECT_FLOAT_EQ(a.y(), b.y()); \ + EXPECT_FLOAT_EQ(a.width(), b.width()); \ + EXPECT_FLOAT_EQ(a.height(), b.height()); #define EXPECT_ROTATION(a, b) \ EXPECT_FLOAT_EQ(a.x, b.x); \ @@ -51,23 +52,23 @@ {20, 200, 2000, 20000}, usToTicks(50000), usToDelta(10000))); rect.animations.emplace_back(std::move(animation)); rect.Animate(usToTicks(50000)); - EXPECT_RECTF_EQ(rect.copy_rect, Rectf({10, 100, 1000, 10000})); + EXPECT_RECTF_EQ(rect.copy_rect, gfx::RectF(10, 100, 1000, 10000)); rect.Animate(usToTicks(60000)); - EXPECT_RECTF_EQ(rect.copy_rect, Rectf({20, 200, 2000, 20000})); + EXPECT_RECTF_EQ(rect.copy_rect, gfx::RectF(20, 200, 2000, 20000)); } TEST(UiElements, AnimateSize) { ContentRectangle rect; - rect.size = {10, 100}; + rect.size = {10, 100, 1}; std::unique_ptr<Animation> animation( new Animation(0, Animation::Property::SIZE, std::unique_ptr<easing::Easing>(new easing::Linear()), {}, {20, 200}, usToTicks(50000), usToDelta(10000))); rect.animations.emplace_back(std::move(animation)); rect.Animate(usToTicks(50000)); - EXPECT_VEC3F_EQ(rect.size, gvr::Vec3f({10, 100})); + EXPECT_VEC3F_EQ(rect.size, gfx::Vector3dF(10, 100, 1)); rect.Animate(usToTicks(60000)); - EXPECT_VEC3F_EQ(rect.size, gvr::Vec3f({20, 200})); + EXPECT_VEC3F_EQ(rect.size, gfx::Vector3dF(20, 200, 1)); } TEST(UiElements, AnimateTranslation) { @@ -79,9 +80,9 @@ {20, 200, 2000}, usToTicks(50000), usToDelta(10000))); rect.animations.emplace_back(std::move(animation)); rect.Animate(usToTicks(50000)); - EXPECT_VEC3F_EQ(rect.translation, gvr::Vec3f({10, 100, 1000})); + EXPECT_VEC3F_EQ(rect.translation, gfx::Vector3dF(10, 100, 1000)); rect.Animate(usToTicks(60000)); - EXPECT_VEC3F_EQ(rect.translation, gvr::Vec3f({20, 200, 2000})); + EXPECT_VEC3F_EQ(rect.translation, gfx::Vector3dF(20, 200, 2000)); } TEST(UiElements, AnimateRotation) { @@ -93,9 +94,9 @@ {20, 200, 2000, 20000}, usToTicks(50000), usToDelta(10000))); rect.animations.emplace_back(std::move(animation)); rect.Animate(usToTicks(50000)); - EXPECT_ROTATION(rect.rotation, RotationAxisAngle({10, 100, 1000, 10000})); + EXPECT_ROTATION(rect.rotation, vr::RotationAxisAngle({10, 100, 1000, 10000})); rect.Animate(usToTicks(60000)); - EXPECT_ROTATION(rect.rotation, RotationAxisAngle({20, 200, 2000, 20000})); + EXPECT_ROTATION(rect.rotation, vr::RotationAxisAngle({20, 200, 2000, 20000})); } TEST(UiElements, AnimationHasNoEffectBeforeScheduledStart) { @@ -106,7 +107,7 @@ {20, 200, 2000}, usToTicks(50000), usToDelta(10000))); rect.animations.emplace_back(std::move(animation)); rect.Animate(usToTicks(49999)); - EXPECT_VEC3F_EQ(rect.translation, gvr::Vec3f({0, 0, 0})); + EXPECT_VEC3F_EQ(rect.translation, gfx::Vector3dF(0, 0, 0)); } TEST(UiElements, AnimationPurgedWhenDone) { @@ -128,11 +129,11 @@ {20, 200, 2000}, usToTicks(50000), usToDelta(10000))); rect.animations.emplace_back(std::move(animation)); rect.Animate(usToTicks(50000)); - EXPECT_VEC3F_EQ(rect.translation, gvr::Vec3f({10, 100, 1000})); + EXPECT_VEC3F_EQ(rect.translation, gfx::Vector3dF(10, 100, 1000)); rect.Animate(usToTicks(55000)); - EXPECT_VEC3F_EQ(rect.translation, gvr::Vec3f({15, 150, 1500})); + EXPECT_VEC3F_EQ(rect.translation, gfx::Vector3dF(15, 150, 1500)); rect.Animate(usToTicks(60000)); - EXPECT_VEC3F_EQ(rect.translation, gvr::Vec3f({20, 200, 2000})); + EXPECT_VEC3F_EQ(rect.translation, gfx::Vector3dF(20, 200, 2000)); } TEST(UiElements, AnimationStartFromSpecifiedLocation) { @@ -143,9 +144,9 @@ {20, 200, 2000}, usToTicks(50000), usToDelta(10000))); rect.animations.emplace_back(std::move(animation)); rect.Animate(usToTicks(50000)); - EXPECT_VEC3F_EQ(rect.translation, gvr::Vec3f({10, 100, 1000})); + EXPECT_VEC3F_EQ(rect.translation, gfx::Vector3dF(10, 100, 1000)); rect.Animate(usToTicks(60000)); - EXPECT_VEC3F_EQ(rect.translation, gvr::Vec3f({20, 200, 2000})); + EXPECT_VEC3F_EQ(rect.translation, gfx::Vector3dF(20, 200, 2000)); } // Ensure that when a new animation overlaps another of the same type, the @@ -166,11 +167,11 @@ rect.animations.emplace_back(std::move(animation)); rect.animations.emplace_back(std::move(animation2)); rect.Animate(usToTicks(55000)); - EXPECT_VEC3F_EQ(rect.translation, gvr::Vec3f({10, 100, 1000})); + EXPECT_VEC3F_EQ(rect.translation, gfx::Vector3dF(10, 100, 1000)); rect.Animate(usToTicks(60000)); - EXPECT_VEC3F_EQ(rect.translation, gvr::Vec3f({30, 300, 3000})); + EXPECT_VEC3F_EQ(rect.translation, gfx::Vector3dF(30, 300, 3000)); rect.Animate(usToTicks(65000)); - EXPECT_VEC3F_EQ(rect.translation, gvr::Vec3f({50, 500, 5000})); + EXPECT_VEC3F_EQ(rect.translation, gfx::Vector3dF(50, 500, 5000)); } } // namespace vr_shell
diff --git a/chrome/browser/android/vr_shell/ui_scene.cc b/chrome/browser/android/vr_shell/ui_scene.cc index e6e1620..e602648 100644 --- a/chrome/browser/android/vr_shell/ui_scene.cc +++ b/chrome/browser/android/vr_shell/ui_scene.cc
@@ -13,6 +13,7 @@ #include "chrome/browser/android/vr_shell/animation.h" #include "chrome/browser/android/vr_shell/easing.h" #include "chrome/browser/android/vr_shell/ui_elements.h" +#include "device/vr/vr_math.h" namespace vr_shell { @@ -46,7 +47,7 @@ bool ParseColorf(const base::DictionaryValue& dict, const std::string& key, - Colorf* output) { + vr::Colorf* output) { const base::DictionaryValue* item_dict; if (dict.GetDictionary(key, &item_dict)) { double value; @@ -149,10 +150,10 @@ float x_offset; switch (x_anchoring) { case XLEFT: - x_offset = -0.5f * parent.size.x; + x_offset = -0.5f * parent.size.x(); break; case XRIGHT: - x_offset = 0.5f * parent.size.x; + x_offset = 0.5f * parent.size.x(); break; case XNONE: x_offset = 0.0f; @@ -161,16 +162,16 @@ float y_offset; switch (y_anchoring) { case YTOP: - y_offset = 0.5f * parent.size.y; + y_offset = 0.5f * parent.size.y(); break; case YBOTTOM: - y_offset = -0.5f * parent.size.y; + y_offset = -0.5f * parent.size.y(); break; case YNONE: y_offset = 0.0f; break; } - transform->Translate(x_offset, y_offset, 0); + transform->Translate(gfx::Vector3dF(x_offset, y_offset, 0)); } } // namespace @@ -373,7 +374,7 @@ return !GetHeadLockedElements().empty(); } -const Colorf& UiScene::GetBackgroundColor() const { +const vr::Colorf& UiScene::GetBackgroundColor() const { return background_color_; } @@ -406,7 +407,7 @@ Transform* transform = element->mutable_transform(); transform->MakeIdentity(); - transform->Scale(element->size.x, element->size.y, element->size.z); + transform->Scale(element->size); element->computed_opacity = element->opacity; element->computed_lock_to_fov = element->lock_to_fov; @@ -414,23 +415,22 @@ // and it's children, if applicable. Transform* inheritable = &element->inheritable_transform; inheritable->MakeIdentity(); - inheritable->Scale(element->scale.x, element->scale.y, element->scale.z); - inheritable->Rotate(element->rotation.x, element->rotation.y, - element->rotation.z, element->rotation.angle); - inheritable->Translate(element->translation.x, element->translation.y, - element->translation.z); + inheritable->Scale(element->scale); + inheritable->Rotate(element->rotation); + inheritable->Translate(element->translation); if (parent) { ApplyAnchoring(*parent, element->x_anchoring, element->y_anchoring, inheritable); ApplyRecursiveTransforms(parent); - inheritable->to_world = MatrixMul(parent->inheritable_transform.to_world, - inheritable->to_world); + vr::MatrixMul(parent->inheritable_transform.to_world, inheritable->to_world, + &inheritable->to_world); element->computed_opacity *= parent->opacity; element->computed_lock_to_fov = parent->lock_to_fov; } - transform->to_world = MatrixMul(inheritable->to_world, transform->to_world); + vr::MatrixMul(inheritable->to_world, transform->to_world, + &transform->to_world); element->dirty = false; } @@ -452,19 +452,27 @@ ParseFloat(dict, "opacity", &element->opacity); DCHECK(!(element->lock_to_fov && element->parent_id != -1)); - - ParseFloat(dict, "sizeX", &element->size.x); - ParseFloat(dict, "sizeY", &element->size.y); - ParseFloat(dict, "scaleX", &element->scale.x); - ParseFloat(dict, "scaleY", &element->scale.y); - ParseFloat(dict, "scaleZ", &element->scale.z); + float val; + ParseFloat(dict, "sizeX", &val); + element->size.set_x(val); + ParseFloat(dict, "sizeY", &val); + element->size.set_y(val); + ParseFloat(dict, "scaleX", &val); + element->scale.set_x(val); + ParseFloat(dict, "scaleY", &val); + element->scale.set_y(val); + ParseFloat(dict, "scaleZ", &val); + element->scale.set_z(val); + ParseFloat(dict, "translationX", &val); + element->translation.set_x(val); + ParseFloat(dict, "translationY", &val); + element->translation.set_y(val); + ParseFloat(dict, "translationZ", &val); + element->translation.set_z(val); ParseFloat(dict, "rotationX", &element->rotation.x); ParseFloat(dict, "rotationY", &element->rotation.y); ParseFloat(dict, "rotationZ", &element->rotation.z); ParseFloat(dict, "rotationAngle", &element->rotation.angle); - ParseFloat(dict, "translationX", &element->translation.x); - ParseFloat(dict, "translationY", &element->translation.y); - ParseFloat(dict, "translationZ", &element->translation.z); if (ParseInt(dict, "xAnchoring", &element->x_anchoring)) { CHECK_GE(element->parent_id, 0); @@ -481,12 +489,17 @@ content_element_ = nullptr; } + int val; switch (element->fill) { case Fill::SPRITE: - CHECK(ParseInt(dict, "copyRectX", &element->copy_rect.x)); - CHECK(ParseInt(dict, "copyRectY", &element->copy_rect.y)); - CHECK(ParseInt(dict, "copyRectWidth", &element->copy_rect.width)); - CHECK(ParseInt(dict, "copyRectHeight", &element->copy_rect.height)); + CHECK(ParseInt(dict, "copyRectX", &val)); + element->copy_rect.set_x(val); + CHECK(ParseInt(dict, "copyRectY", &val)); + element->copy_rect.set_y(val); + CHECK(ParseInt(dict, "copyRectWidth", &val)); + element->copy_rect.set_width(val); + CHECK(ParseInt(dict, "copyRectHeight", &val)); + element->copy_rect.set_height(val); break; case Fill::OPAQUE_GRADIENT: CHECK(ParseColorf(dict, "edgeColor", &element->edge_color));
diff --git a/chrome/browser/android/vr_shell/ui_scene.h b/chrome/browser/android/vr_shell/ui_scene.h index 9d33480..91b0c3b 100644 --- a/chrome/browser/android/vr_shell/ui_scene.h +++ b/chrome/browser/android/vr_shell/ui_scene.h
@@ -9,7 +9,7 @@ #include <vector> #include "base/macros.h" -#include "chrome/browser/android/vr_shell/vr_math.h" +#include "device/vr/vr_types.h" namespace base { class DictionaryValue; @@ -73,7 +73,7 @@ std::vector<const ContentRectangle*> GetHeadLockedElements() const; bool HasVisibleHeadLockedElements() const; - const Colorf& GetBackgroundColor() const; + const vr::Colorf& GetBackgroundColor() const; float GetBackgroundDistance() const; bool GetWebVrRenderingEnabled() const; @@ -84,7 +84,7 @@ std::vector<std::unique_ptr<ContentRectangle>> ui_elements_; ContentRectangle* content_element_ = nullptr; - Colorf background_color_ = {0.1f, 0.1f, 0.1f, 1.0f}; + vr::Colorf background_color_ = {0.1f, 0.1f, 0.1f, 1.0f}; float background_distance_ = 10.0f; bool webvr_rendering_enabled_ = true;
diff --git a/chrome/browser/android/vr_shell/ui_scene_unittest.cc b/chrome/browser/android/vr_shell/ui_scene_unittest.cc index 36a1e52..427626c 100644 --- a/chrome/browser/android/vr_shell/ui_scene_unittest.cc +++ b/chrome/browser/android/vr_shell/ui_scene_unittest.cc
@@ -14,15 +14,16 @@ #include "chrome/browser/android/vr_shell/animation.h" #include "chrome/browser/android/vr_shell/easing.h" #include "chrome/browser/android/vr_shell/ui_elements.h" -#include "chrome/browser/android/vr_shell/vr_math.h" +#include "device/vr/vr_math.h" +#include "device/vr/vr_types.h" #include "testing/gtest/include/gtest/gtest.h" #define TOLERANCE 0.0001 -#define EXPECT_VEC3F_NEAR(a, b) \ - EXPECT_NEAR(a.x, b.x, TOLERANCE); \ - EXPECT_NEAR(a.y, b.y, TOLERANCE); \ - EXPECT_NEAR(a.z, b.z, TOLERANCE); +#define EXPECT_VEC3F_NEAR(a, b) \ + EXPECT_NEAR(a.x(), b.x(), TOLERANCE); \ + EXPECT_NEAR(a.y(), b.y(), TOLERANCE); \ + EXPECT_NEAR(a.z(), b.z(), TOLERANCE); namespace vr_shell { @@ -132,14 +133,14 @@ scene.AddUiElement(std::move(element)); const ContentRectangle* child = scene.GetUiElementById(1); - const gvr::Vec3f origin({0, 0, 0}); - const gvr::Vec3f point({1, 0, 0}); + const gfx::Vector3dF origin(0, 0, 0); + const gfx::Vector3dF point(1, 0, 0); scene.UpdateTransforms(usToTicks(0)); - auto new_origin = MatrixVectorMul(child->TransformMatrix(), origin); - auto new_point = MatrixVectorMul(child->TransformMatrix(), point); - EXPECT_VEC3F_NEAR(gvr::Vec3f({6, 10, 0}), new_origin); - EXPECT_VEC3F_NEAR(gvr::Vec3f({0, 10, 0}), new_point); + auto new_origin = vr::MatrixVectorMul(child->TransformMatrix(), origin); + auto new_point = vr::MatrixVectorMul(child->TransformMatrix(), point); + EXPECT_VEC3F_NEAR(gfx::Vector3dF(6, 10, 0), new_origin); + EXPECT_VEC3F_NEAR(gfx::Vector3dF(0, 10, 0), new_point); } TEST(UiScene, Opacity) { @@ -209,8 +210,8 @@ scene.UpdateTransforms(usToTicks(0)); const ContentRectangle* child = scene.GetUiElementById(1); - EXPECT_NEAR(child->GetCenter().x, GetParam().expected_x, TOLERANCE); - EXPECT_NEAR(child->GetCenter().y, GetParam().expected_y, TOLERANCE); + EXPECT_NEAR(child->GetCenter().x(), GetParam().expected_x, TOLERANCE); + EXPECT_NEAR(child->GetCenter().y(), GetParam().expected_y, TOLERANCE); scene.RemoveUiElement(1); } @@ -278,27 +279,27 @@ EXPECT_EQ(element->y_anchoring, YAnchoring::YTOP); EXPECT_FLOAT_EQ(element->opacity, 0.357); - EXPECT_EQ(element->copy_rect.x, 100); - EXPECT_EQ(element->copy_rect.y, 101); - EXPECT_EQ(element->copy_rect.width, 102); - EXPECT_EQ(element->copy_rect.height, 103); + EXPECT_EQ(element->copy_rect.x(), 100); + EXPECT_EQ(element->copy_rect.y(), 101); + EXPECT_EQ(element->copy_rect.width(), 102); + EXPECT_EQ(element->copy_rect.height(), 103); - EXPECT_FLOAT_EQ(element->size.x, 200); - EXPECT_FLOAT_EQ(element->size.y, 201); - EXPECT_FLOAT_EQ(element->size.z, 1); + EXPECT_FLOAT_EQ(element->size.x(), 200); + EXPECT_FLOAT_EQ(element->size.y(), 201); + EXPECT_FLOAT_EQ(element->size.z(), 1); - EXPECT_FLOAT_EQ(element->scale.x, 300); - EXPECT_FLOAT_EQ(element->scale.y, 301); - EXPECT_FLOAT_EQ(element->scale.z, 302); + EXPECT_FLOAT_EQ(element->scale.x(), 300); + EXPECT_FLOAT_EQ(element->scale.y(), 301); + EXPECT_FLOAT_EQ(element->scale.z(), 302); EXPECT_FLOAT_EQ(element->rotation.x, 400); EXPECT_FLOAT_EQ(element->rotation.y, 401); EXPECT_FLOAT_EQ(element->rotation.z, 402); EXPECT_FLOAT_EQ(element->rotation.angle, 403); - EXPECT_FLOAT_EQ(element->translation.x, 500); - EXPECT_FLOAT_EQ(element->translation.y, 501); - EXPECT_FLOAT_EQ(element->translation.z, 502); + EXPECT_FLOAT_EQ(element->translation.x(), 500); + EXPECT_FLOAT_EQ(element->translation.y(), 501); + EXPECT_FLOAT_EQ(element->translation.z(), 502); dict.Clear(); dict.SetInteger("id", 12); @@ -340,10 +341,10 @@ const auto* element = scene.GetUiElementById(9); EXPECT_EQ(element->fill, Fill::SPRITE); - EXPECT_EQ(element->copy_rect.x, 1); - EXPECT_EQ(element->copy_rect.y, 2); - EXPECT_EQ(element->copy_rect.width, 3); - EXPECT_EQ(element->copy_rect.height, 4); + EXPECT_EQ(element->copy_rect.x(), 1); + EXPECT_EQ(element->copy_rect.y(), 2); + EXPECT_EQ(element->copy_rect.width(), 3); + EXPECT_EQ(element->copy_rect.height(), 4); // Test OPAQUE_GRADIENT filling. dict.Clear();
diff --git a/chrome/browser/android/vr_shell/vr_controller.cc b/chrome/browser/android/vr_shell/vr_controller.cc index 25228b9..177b3b6 100644 --- a/chrome/browser/android/vr_shell/vr_controller.cc +++ b/chrome/browser/android/vr_shell/vr_controller.cc
@@ -10,7 +10,7 @@ #include "base/logging.h" #include "base/time/time.h" -#include "chrome/browser/android/vr_shell/vr_math.h" +#include "device/vr/vr_math.h" #include "third_party/gvr-android-sdk/src/libraries/headers/vr/gvr/capi/include/gvr.h" #include "third_party/gvr-android-sdk/src/libraries/headers/vr/gvr/capi/include/gvr_controller.h" @@ -41,46 +41,12 @@ constexpr int kMaxNumOfExtrapolations = 2; -static constexpr gvr::Vec3f kControllerPosition = {0.2f, -0.5f, -0.15f}; +static constexpr gfx::Point3F kControllerPosition = {0.2f, -0.5f, -0.15f}; -class Vector { - public: - static inline void ClampTouchpadPosition(gvr::Vec2f* position) { - position->x = std::min(std::max(0.0f, position->x), 1.0f); - position->y = std::min(std::max(0.0f, position->y), 1.0f); - } - - static inline void SetZero(gvr::Vec2f* v) { - v->x = 0; - v->y = 0; - } - - static inline gvr::Vec2f Subtract(gvr::Vec2f v1, gvr::Vec2f v2) { - gvr::Vec2f result; - result.x = v1.x - v2.x; - result.y = v1.y - v2.y; - return result; - } - - static inline gvr::Vec2f Add(gvr::Vec2f v1, gvr::Vec2f v2) { - gvr::Vec2f result; - result.x = v1.x + v2.x; - result.y = v1.y + v2.y; - return result; - } - - static inline bool Equal(const gvr::Vec2f v1, const gvr::Vec2f v2) { - return (std::abs(v1.x - v2.x) < kDelta) && (std::abs(v1.y - v2.y) < kDelta); - } - - static inline gvr::Vec2f ScalarMult(gvr::Vec2f v, float scalar) { - gvr::Vec2f vect_prod; - vect_prod.x = v.x * scalar; - vect_prod.y = v.y * scalar; - return vect_prod; - } - -}; // Vector +void ClampTouchpadPosition(gfx::Vector2dF* position) { + position->set_x(std::min(std::max(0.0f, position->x()), 1.0f)); + position->set_y(std::min(std::max(0.0f, position->y()), 1.0f)); +} } // namespace @@ -108,13 +74,19 @@ device::GvrGamepadData pad; pad.timestamp = controller_state_->GetLastOrientationTimestamp(); - pad.touch_pos = controller_state_->GetTouchPos(); - pad.orientation = controller_state_->GetOrientation(); + pad.touch_pos.set_x(TouchPosX()); + pad.touch_pos.set_y(TouchPosY()); + pad.orientation = Orientation(); // Use orientation to rotate acceleration/gyro into seated space. - gvr::Mat4f pose_mat = QuatToMatrix(pad.orientation); - pad.accel = MatrixVectorMul(pose_mat, controller_state_->GetAccel()); - pad.gyro = MatrixVectorMul(pose_mat, controller_state_->GetGyro()); + vr::Mat4f pose_mat; + vr::QuatToMatrix(pad.orientation, &pose_mat); + const gvr::Vec3f& accel = controller_state_->GetAccel(); + const gvr::Vec3f& gyro = controller_state_->GetGyro(); + pad.accel = + vr::MatrixVectorMul(pose_mat, gfx::Vector3dF(accel.x, accel.y, accel.z)); + pad.gyro = + vr::MatrixVectorMul(pose_mat, gfx::Vector3dF(gyro.x, gyro.y, gyro.z)); pad.is_touching = controller_state_->IsTouching(); pad.controller_button_pressed = @@ -136,22 +108,24 @@ return controller_state_->GetTouchPos().y; } -gvr::Quatf VrController::Orientation() const { - return controller_state_->GetOrientation(); +vr::Quatf VrController::Orientation() const { + const gvr::Quatf& orientation = controller_state_->GetOrientation(); + return *reinterpret_cast<vr::Quatf*>(const_cast<gvr::Quatf*>(&orientation)); } -gvr::Mat4f VrController::GetTransform() const { +void VrController::GetTransform(vr::Mat4f* out) const { // TODO(acondor): Position and orientation needs to be obtained // from an elbow model. // Placing the controller in a fixed position for now. - gvr::Mat4f mat; - SetIdentityM(mat); + vr::SetIdentityM(out); // Changing rotation point. - TranslateM(mat, mat, 0, 0, 0.05); - mat = MatrixMul(QuatToMatrix(Orientation()), mat); - TranslateM(mat, mat, kControllerPosition.x, kControllerPosition.y, - kControllerPosition.z - 0.05); - return mat; + vr::TranslateM(*out, gfx::Vector3dF(0, 0, 0.05), out); + vr::Mat4f quat_to_matrix; + vr::QuatToMatrix(Orientation(), &quat_to_matrix); + vr::MatrixMul(quat_to_matrix, *out, out); + gfx::Vector3dF translation(kControllerPosition.x(), kControllerPosition.y(), + kControllerPosition.z() - 0.05); + vr::TranslateM(*out, translation, out); } VrControllerModel::State VrController::GetModelState() const { @@ -206,8 +180,7 @@ CHECK(touch_info_ != nullptr) << "touch_info_ not initialized properly."; if (IsTouching() && state_ == SCROLLING && (controller_state_->GetLastTouchTimestamp() == last_touch_timestamp_ || - (Vector::Equal(cur_touch_point_->position, - prev_touch_point_->position) && + (cur_touch_point_->position == prev_touch_point_->position && extrapolated_touch_ < kMaxNumOfExtrapolations))) { extrapolated_touch_++; touch_position_changed_ = true; @@ -216,13 +189,13 @@ (gvr::GvrApi::GetTimePointNow().monotonic_system_time_nanos - last_timestamp_nanos_) / kNanoSecondsPerSecond; - touch_info_->touch_point.position.x = - cur_touch_point_->position.x + overall_velocity_.x * duration; - touch_info_->touch_point.position.y = - cur_touch_point_->position.y + overall_velocity_.y * duration; + touch_info_->touch_point.position.set_x(cur_touch_point_->position.x() + + overall_velocity_.x() * duration); + touch_info_->touch_point.position.set_y(cur_touch_point_->position.y() + + overall_velocity_.y() * duration); } else { if (extrapolated_touch_ == kMaxNumOfExtrapolations) { - Vector::SetZero(&overall_velocity_); + overall_velocity_ = {0, 0}; } extrapolated_touch_ = 0; } @@ -279,17 +252,17 @@ if (gesture_list.back()->GetType() == WebInputEvent::kGestureScrollEnd) { if (!ButtonDownHappened(gvr::kControllerButtonClick) && - (last_velocity_.x != 0.0 || last_velocity_.y != 0.0)) { + (last_velocity_.x() != 0.0 || last_velocity_.y() != 0.0)) { std::unique_ptr<WebGestureEvent> fling(new WebGestureEvent( WebInputEvent::kGestureFlingStart, WebInputEvent::kNoModifiers, gesture_list.back()->TimeStampSeconds())); fling->source_device = blink::kWebGestureDeviceTouchpad; if (IsHorizontalGesture()) { fling->data.fling_start.velocity_x = - last_velocity_.x * kDisplacementScaleFactor; + last_velocity_.x() * kDisplacementScaleFactor; } else { fling->data.fling_start.velocity_y = - last_velocity_.y * kDisplacementScaleFactor; + last_velocity_.y() * kDisplacementScaleFactor; } gesture_list.push_back(std::move(fling)); } @@ -352,9 +325,9 @@ gesture->SetType(WebInputEvent::kGestureScrollBegin); UpdateGestureParameters(); gesture->data.scroll_begin.delta_x_hint = - displacement_.x * kDisplacementScaleFactor; + displacement_.x() * kDisplacementScaleFactor; gesture->data.scroll_begin.delta_y_hint = - displacement_.y * kDisplacementScaleFactor; + displacement_.y() * kDisplacementScaleFactor; gesture->data.scroll_begin.delta_hint_units = blink::WebGestureEvent::ScrollUnits::kPrecisePixels; } @@ -372,23 +345,23 @@ UpdateGestureParameters(); if (IsHorizontalGesture()) { gesture->data.scroll_update.delta_x = - displacement_.x * kDisplacementScaleFactor; + displacement_.x() * kDisplacementScaleFactor; } else { gesture->data.scroll_update.delta_y = - displacement_.y * kDisplacementScaleFactor; + displacement_.y() * kDisplacementScaleFactor; } last_velocity_ = overall_velocity_; } } bool VrController::IsHorizontalGesture() { - return std::abs(last_velocity_.x) > std::abs(last_velocity_.y); + return std::abs(last_velocity_.x()) > std::abs(last_velocity_.y()); } -bool VrController::InSlop(const gvr::Vec2f touch_position) { - return (std::abs(touch_position.x - init_touch_point_->position.x) < +bool VrController::InSlop(const gfx::Vector2dF touch_position) { + return (std::abs(touch_position.x() - init_touch_point_->position.x()) < kSlopHorizontal) && - (std::abs(touch_position.y - init_touch_point_->position.y) < + (std::abs(touch_position.y() - init_touch_point_->position.y()) < kSlopVertical); } @@ -401,29 +374,28 @@ cur_touch_point_.reset(new TouchPoint); init_touch_point_.reset(new TouchPoint); touch_info_.reset(new TouchInfo); - Vector::SetZero(&overall_velocity_); - Vector::SetZero(&last_velocity_); + overall_velocity_ = {0, 0}; + last_velocity_ = {0, 0}; } void VrController::UpdateGestureParameters() { - displacement_ = Vector::Subtract(touch_info_->touch_point.position, - prev_touch_point_->position); + displacement_ = + touch_info_->touch_point.position - prev_touch_point_->position; } bool VrController::UpdateCurrentTouchpoint() { touch_info_->touch_up = TouchUpHappened(); touch_info_->touch_down = TouchDownHappened(); touch_info_->is_touching = IsTouching(); - touch_info_->touch_point.position.x = TouchPosX(); - touch_info_->touch_point.position.y = TouchPosY(); - Vector::ClampTouchpadPosition(&touch_info_->touch_point.position); + touch_info_->touch_point.position.set_x(TouchPosX()); + touch_info_->touch_point.position.set_y(TouchPosY()); + ClampTouchpadPosition(&touch_info_->touch_point.position); touch_info_->touch_point.timestamp = gvr::GvrApi::GetTimePointNow().monotonic_system_time_nanos; if (IsTouching() || TouchUpHappened()) { // Update the touch point when the touch position has changed. - if (!Vector::Equal(cur_touch_point_->position, - touch_info_->touch_point.position)) { + if (cur_touch_point_->position != touch_info_->touch_point.position) { prev_touch_point_.swap(cur_touch_point_); cur_touch_point_.reset(new TouchPoint); cur_touch_point_->position = touch_info_->touch_point.position; @@ -443,16 +415,15 @@ if (duration < kDelta) return; - gvr::Vec2f displacement = Vector::Subtract(touch_info_->touch_point.position, - prev_touch_point_->position); + const gfx::Vector2dF& displacement = + touch_info_->touch_point.position - prev_touch_point_->position; - gvr::Vec2f velocity = Vector::ScalarMult(displacement, 1 / duration); + const gfx::Vector2dF& velocity = ScaleVector2d(displacement, (1 / duration)); float weight = duration / (kRC + duration); - overall_velocity_ = - Vector::Add(Vector::ScalarMult(overall_velocity_, 1 - weight), - Vector::ScalarMult(velocity, weight)); + overall_velocity_ = ScaleVector2d(overall_velocity_, (1 - weight)) + + ScaleVector2d(velocity, weight); } } // namespace vr_shell
diff --git a/chrome/browser/android/vr_shell/vr_controller.h b/chrome/browser/android/vr_shell/vr_controller.h index 3b9ff1c..9cc0b3d 100644 --- a/chrome/browser/android/vr_shell/vr_controller.h +++ b/chrome/browser/android/vr_shell/vr_controller.h
@@ -11,6 +11,7 @@ #include "base/macros.h" #include "chrome/browser/android/vr_shell/vr_controller_model.h" #include "device/vr/android/gvr/gvr_gamepad_data_provider.h" +#include "device/vr/vr_types.h" #include "third_party/WebKit/public/platform/WebGestureEvent.h" #include "third_party/WebKit/public/platform/WebInputEvent.h" #include "third_party/gvr-android-sdk/src/libraries/headers/vr/gvr/capi/include/gvr_types.h" @@ -52,9 +53,9 @@ float TouchPosY(); - gvr::Quatf Orientation() const; + vr::Quatf Orientation() const; - gvr::Mat4f GetTransform() const; + void GetTransform(vr::Mat4f* out) const; VrControllerModel::State GetModelState() const; @@ -76,7 +77,7 @@ }; struct TouchPoint { - gvr::Vec2f position; + gfx::Vector2dF position; int64_t timestamp; }; @@ -111,7 +112,7 @@ // Returns true if the touch position is within the slop of the initial touch // point, false otherwise. - bool InSlop(const gvr::Vec2f touch_position); + bool InSlop(const gfx::Vector2dF touch_position); // Returns true if the gesture is in horizontal direction. bool IsHorizontalGesture(); @@ -155,13 +156,13 @@ std::unique_ptr<TouchPoint> init_touch_point_; // Overall velocity - gvr::Vec2f overall_velocity_; + gfx::Vector2dF overall_velocity_; // Last velocity that is used for fling and direction detection - gvr::Vec2f last_velocity_; + gfx::Vector2dF last_velocity_; // Displacement of the touch point from the previews to the current touch - gvr::Vec2f displacement_; + gfx::Vector2dF displacement_; int64_t last_touch_timestamp_ = 0; int64_t last_timestamp_nanos_ = 0;
diff --git a/chrome/browser/android/vr_shell/vr_gl_util.cc b/chrome/browser/android/vr_shell/vr_gl_util.cc index ad362a1..1c68ee1 100644 --- a/chrome/browser/android/vr_shell/vr_gl_util.cc +++ b/chrome/browser/android/vr_shell/vr_gl_util.cc
@@ -7,7 +7,7 @@ namespace vr_shell { // This code is adapted from the GVR Treasure Hunt demo source. -std::array<float, 16> MatrixToGLArray(const gvr::Mat4f& matrix) { +std::array<float, 16> MatrixToGLArray(const vr::Mat4f& matrix) { // Note that this performs a *transpose* to a column-major matrix array, as // expected by GL. The input matrix has translation components at [i][3] for // use with row vectors and premultiplied transforms. In the output, the @@ -15,29 +15,19 @@ std::array<float, 16> result; for (int i = 0; i < 4; ++i) { for (int j = 0; j < 4; ++j) { - result[j * 4 + i] = matrix.m[i][j]; + result[j * 4 + i] = matrix[i][j]; } } return result; } // This code is adapted from the GVR Treasure Hunt demo source. -gvr::Rectf ModulateRect(const gvr::Rectf& rect, float width, float height) { - gvr::Rectf result = {rect.left * width, rect.right * width, - rect.bottom * height, rect.top * height}; - return result; -} - -// This code is adapted from the GVR Treasure Hunt demo source. -gvr::Recti CalculatePixelSpaceRect(const gvr::Sizei& texture_size, - const gvr::Rectf& texture_rect) { - float width = static_cast<float>(texture_size.width); - float height = static_cast<float>(texture_size.height); - gvr::Rectf rect = ModulateRect(texture_rect, width, height); - gvr::Recti result = { - static_cast<int>(rect.left), static_cast<int>(rect.right), - static_cast<int>(rect.bottom), static_cast<int>(rect.top)}; - return result; +gfx::Rect CalculatePixelSpaceRect(const gfx::Size& texture_size, + const gfx::RectF& texture_rect) { + const gfx::RectF rect = + ScaleRect(texture_rect, static_cast<float>(texture_size.width()), + static_cast<float>(texture_size.height())); + return gfx::Rect(rect.x(), rect.y(), rect.width(), rect.height()); } GLuint CompileShader(GLenum shader_type,
diff --git a/chrome/browser/android/vr_shell/vr_gl_util.h b/chrome/browser/android/vr_shell/vr_gl_util.h index 61e8e99..59052929 100644 --- a/chrome/browser/android/vr_shell/vr_gl_util.h +++ b/chrome/browser/android/vr_shell/vr_gl_util.h
@@ -8,17 +8,15 @@ #include <array> #include <string> -#include "third_party/gvr-android-sdk/src/libraries/headers/vr/gvr/capi/include/gvr_types.h" +#include "device/vr/vr_types.h" #include "ui/gl/gl_bindings.h" namespace vr_shell { -std::array<float, 16> MatrixToGLArray(const gvr::Mat4f& matrix); +std::array<float, 16> MatrixToGLArray(const vr::Mat4f& matrix); -gvr::Rectf ModulateRect(const gvr::Rectf& rect, float width, float height); - -gvr::Recti CalculatePixelSpaceRect(const gvr::Sizei& texture_size, - const gvr::Rectf& texture_rect); +gfx::Rect CalculatePixelSpaceRect(const gfx::Size& texture_size, + const gfx::RectF& texture_rect); // Compile a shader. GLuint CompileShader(GLenum shader_type,
diff --git a/chrome/browser/android/vr_shell/vr_math.cc b/chrome/browser/android/vr_shell/vr_math.cc deleted file mode 100644 index 289a145..0000000 --- a/chrome/browser/android/vr_shell/vr_math.cc +++ /dev/null
@@ -1,250 +0,0 @@ -// Copyright 2016 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/android/vr_shell/vr_math.h" - -#include <cmath> - -#include "base/logging.h" - -namespace vr_shell { - -// Internal matrix layout: -// -// m[0][0], m[0][1], m[0][2], m[0][3], -// m[1][0], m[1][1], m[1][2], m[1][3], -// m[2][0], m[2][1], m[2][2], m[2][3], -// m[3][0], m[3][1], m[3][2], m[3][3], -// -// The translation component is in the right column m[i][3]. -// -// The bottom row m[3][i] is (0, 0, 0, 1) for non-perspective transforms. -// -// These matrices are intended to be used to premultiply column vectors -// for transforms, so successive transforms need to be left-multiplied. - -void SetIdentityM(gvr::Mat4f& mat) { - float* m = reinterpret_cast<float*>(mat.m); - for (int i = 0; i < 16; i++) { - m[i] = 0; - } - for (int i = 0; i < 16; i += 5) { - m[i] = 1.0f; - } -} - -// Left multiply a translation matrix. -void TranslateM(gvr::Mat4f& tmat, gvr::Mat4f& mat, float x, float y, float z) { - if (&tmat != &mat) { - for (int i = 0; i < 4; ++i) { - for (int j = 0; j < 4; ++j) { - tmat.m[i][j] = mat.m[i][j]; - } - } - } - tmat.m[0][3] += x; - tmat.m[1][3] += y; - tmat.m[2][3] += z; -} - -// Left multiply a scale matrix. -void ScaleM(gvr::Mat4f& tmat, - const gvr::Mat4f& mat, - float x, - float y, - float z) { - if (&tmat != &mat) { - for (int i = 0; i < 4; ++i) { - for (int j = 0; j < 3; ++j) { - tmat.m[i][j] = mat.m[i][j]; - } - } - } - // Multiply all rows including translation components. - for (int j = 0; j < 4; ++j) { - tmat.m[0][j] *= x; - tmat.m[1][j] *= y; - tmat.m[2][j] *= z; - } -} - -gvr::Vec3f MatrixVectorMul(const gvr::Mat4f& m, const gvr::Vec3f& v) { - gvr::Vec3f res; - res.x = m.m[0][0] * v.x + m.m[0][1] * v.y + m.m[0][2] * v.z + m.m[0][3]; - res.y = m.m[1][0] * v.x + m.m[1][1] * v.y + m.m[1][2] * v.z + m.m[1][3]; - res.z = m.m[2][0] * v.x + m.m[2][1] * v.y + m.m[2][2] * v.z + m.m[2][3]; - return res; -} - -// Rotation only, ignore translation components. -gvr::Vec3f MatrixVectorRotate(const gvr::Mat4f& m, const gvr::Vec3f& v) { - gvr::Vec3f res; - res.x = m.m[0][0] * v.x + m.m[0][1] * v.y + m.m[0][2] * v.z; - res.y = m.m[1][0] * v.x + m.m[1][1] * v.y + m.m[1][2] * v.z; - res.z = m.m[2][0] * v.x + m.m[2][1] * v.y + m.m[2][2] * v.z; - return res; -} - -gvr::Mat4f MatrixMul(const gvr::Mat4f& matrix1, const gvr::Mat4f& matrix2) { - gvr::Mat4f result; - for (int i = 0; i < 4; ++i) { - for (int j = 0; j < 4; ++j) { - result.m[i][j] = 0.0f; - for (int k = 0; k < 4; ++k) { - result.m[i][j] += matrix1.m[i][k] * matrix2.m[k][j]; - } - } - } - return result; -} - -gvr::Mat4f PerspectiveMatrixFromView(const gvr::Rectf& fov, - float z_near, - float z_far) { - gvr::Mat4f result; - const float x_left = -std::tan(fov.left * M_PI / 180.0f) * z_near; - const float x_right = std::tan(fov.right * M_PI / 180.0f) * z_near; - const float y_bottom = -std::tan(fov.bottom * M_PI / 180.0f) * z_near; - const float y_top = std::tan(fov.top * M_PI / 180.0f) * z_near; - - DCHECK(x_left < x_right && y_bottom < y_top && z_near < z_far && - z_near > 0.0f && z_far > 0.0f); - const float X = (2 * z_near) / (x_right - x_left); - const float Y = (2 * z_near) / (y_top - y_bottom); - const float A = (x_right + x_left) / (x_right - x_left); - const float B = (y_top + y_bottom) / (y_top - y_bottom); - const float C = (z_near + z_far) / (z_near - z_far); - const float D = (2 * z_near * z_far) / (z_near - z_far); - - for (int i = 0; i < 4; ++i) { - for (int j = 0; j < 4; ++j) { - result.m[i][j] = 0.0f; - } - } - result.m[0][0] = X; - result.m[0][2] = A; - result.m[1][1] = Y; - result.m[1][2] = B; - result.m[2][2] = C; - result.m[2][3] = D; - result.m[3][2] = -1; - - return result; -} - -gvr::Vec3f GetForwardVector(const gvr::Mat4f& matrix) { - // Same as multiplying the inverse of the rotation component of the matrix by - // (0, 0, -1, 0). - return {-matrix.m[2][0], -matrix.m[2][1], -matrix.m[2][2]}; -} - -gvr::Vec3f GetTranslation(const gvr::Mat4f& matrix) { - return {matrix.m[0][3], matrix.m[1][3], matrix.m[2][3]}; -} - -float VectorLength(const gvr::Vec3f& vec) { - return sqrt(vec.x * vec.x + vec.y * vec.y + vec.z * vec.z); -} - -gvr::Vec3f VectorSubtract(const gvr::Vec3f& a, const gvr::Vec3f& b) { - return {a.x - b.x, a.y - b.y, a.z - b.z}; -} - -float NormalizeVector(gvr::Vec3f& vec) { - float len = VectorLength(vec); - vec.x /= len; - vec.y /= len; - vec.z /= len; - return len; -} - -float VectorDot(const gvr::Vec3f& a, const gvr::Vec3f& b) { - return a.x * b.x + a.y * b.y + a.z * b.z; -} - -void NormalizeQuat(gvr::Quatf& quat) { - float len = sqrt(quat.qx * quat.qx + quat.qy * quat.qy + quat.qz * quat.qz + - quat.qw * quat.qw); - quat.qx /= len; - quat.qy /= len; - quat.qz /= len; - quat.qw /= len; -} - -gvr::Quatf QuatFromAxisAngle(const gvr::Vec3f& axis, float angle) { - // Rotation angle is the product of |angle| and the magnitude of |axis|. - gvr::Vec3f normal = axis; - float length = NormalizeVector(normal); - angle *= length; - - gvr::Quatf res; - float s = sin(angle / 2); - res.qx = normal.x * s; - res.qy = normal.y * s; - res.qz = normal.z * s; - res.qw = cos(angle / 2); - return res; -} - -gvr::Quatf QuatMultiply(const gvr::Quatf& a, const gvr::Quatf& b) { - gvr::Quatf res; - res.qw = a.qw * b.qw - a.qx * b.qx - a.qy * b.qy - a.qz * b.qz; - res.qx = a.qw * b.qx + a.qx * b.qw + a.qy * b.qz - a.qz * b.qy; - res.qy = a.qw * b.qy - a.qx * b.qz + a.qy * b.qw + a.qz * b.qx; - res.qz = a.qw * b.qz + a.qx * b.qy - a.qy * b.qx + a.qz * b.qw; - return res; -} - -gvr::Mat4f QuatToMatrix(const gvr::Quatf& quat) { - const float x2 = quat.qx * quat.qx; - const float y2 = quat.qy * quat.qy; - const float z2 = quat.qz * quat.qz; - const float xy = quat.qx * quat.qy; - const float xz = quat.qx * quat.qz; - const float xw = quat.qx * quat.qw; - const float yz = quat.qy * quat.qz; - const float yw = quat.qy * quat.qw; - const float zw = quat.qz * quat.qw; - - const float m11 = 1.0f - 2.0f * y2 - 2.0f * z2; - const float m12 = 2.0f * (xy - zw); - const float m13 = 2.0f * (xz + yw); - const float m21 = 2.0f * (xy + zw); - const float m22 = 1.0f - 2.0f * x2 - 2.0f * z2; - const float m23 = 2.0f * (yz - xw); - const float m31 = 2.0f * (xz - yw); - const float m32 = 2.0f * (yz + xw); - const float m33 = 1.0f - 2.0f * x2 - 2.0f * y2; - - return {{{m11, m12, m13, 0.0f}, - {m21, m22, m23, 0.0f}, - {m31, m32, m33, 0.0f}, - {0.0f, 0.0f, 0.0f, 1.0f}}}; -} - -gvr::Vec3f GetRayPoint(const gvr::Vec3f& rayOrigin, - const gvr::Vec3f& rayVector, - float scale) { - gvr::Vec3f v; - v.x = rayOrigin.x + scale * rayVector.x; - v.y = rayOrigin.y + scale * rayVector.y; - v.z = rayOrigin.z + scale * rayVector.z; - return v; -} - -float Distance(const gvr::Vec3f& vec1, const gvr::Vec3f& vec2) { - return VectorLength(VectorSubtract(vec1, vec2)); -} - -bool XZAngle(const gvr::Vec3f& vec1, const gvr::Vec3f& vec2, float* angle) { - float len1 = VectorLength(vec1); - float len2 = VectorLength(vec2); - if (len1 == 0 || len2 == 0) - return false; - float cross_p = vec1.x * vec2.z - vec1.z * vec2.x; - *angle = asin(cross_p / (len1 * len2)); - return true; -} - -} // namespace vr_shell
diff --git a/chrome/browser/android/vr_shell/vr_math.h b/chrome/browser/android/vr_shell/vr_math.h deleted file mode 100644 index 4b520c29..0000000 --- a/chrome/browser/android/vr_shell/vr_math.h +++ /dev/null
@@ -1,86 +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. - -#ifndef CHROME_BROWSER_ANDROID_VR_SHELL_VR_MATH_H_ -#define CHROME_BROWSER_ANDROID_VR_SHELL_VR_MATH_H_ - -#include <array> - -#include "third_party/gvr-android-sdk/src/libraries/headers/vr/gvr/capi/include/gvr_types.h" - -namespace vr_shell { - -// 2D rectangles. Unlike gvr::Rectf and gvr::Recti, these have width and height -// rather than right and top. -typedef struct Recti { - int x; - int y; - int width; - int height; -} Recti; - -typedef struct Rectf { - float x; - float y; - float width; - float height; -} Rectf; - -typedef struct RotationAxisAngle { - float x; - float y; - float z; - float angle; -} RotationAxisAngle; - -typedef struct Colorf { - float r; - float g; - float b; - float a; -} Colorf; - -void SetIdentityM(gvr::Mat4f& mat); -void TranslateM(gvr::Mat4f& tmat, gvr::Mat4f& mat, float x, float y, float z); -void ScaleM(gvr::Mat4f& tmat, const gvr::Mat4f& mat, float x, float y, float z); - -// Util functions that are copied from the treasure_hunt NDK demo in -// third_party/gvr-andoir-sdk/ folder. -gvr::Vec3f MatrixVectorMul(const gvr::Mat4f& m, const gvr::Vec3f& v); -gvr::Vec3f MatrixVectorRotate(const gvr::Mat4f& m, const gvr::Vec3f& v); -gvr::Mat4f MatrixMul(const gvr::Mat4f& matrix1, const gvr::Mat4f& matrix2); -gvr::Mat4f PerspectiveMatrixFromView(const gvr::Rectf& fov, - float z_near, - float z_far); - -// Provides the direction the head is looking towards as a 3x1 unit vector. -gvr::Vec3f GetForwardVector(const gvr::Mat4f& matrix); - -gvr::Vec3f GetTranslation(const gvr::Mat4f& matrix); - -gvr::Mat4f QuatToMatrix(const gvr::Quatf& quat); - -float VectorLength(const gvr::Vec3f& vec); -gvr::Vec3f VectorSubtract(const gvr::Vec3f& a, const gvr::Vec3f& b); -float VectorDot(const gvr::Vec3f& a, const gvr::Vec3f& b); - -// Normalize a vector, and return its original length. -float NormalizeVector(gvr::Vec3f& vec); - -void NormalizeQuat(gvr::Quatf& quat); - -gvr::Quatf QuatFromAxisAngle(const gvr::Vec3f& axis, float angle); - -gvr::Vec3f GetRayPoint(const gvr::Vec3f& rayOrigin, - const gvr::Vec3f& rayVector, - float scale); - -float Distance(const gvr::Vec3f& vec1, const gvr::Vec3f& vec2); - -// Angle between the vectors' projections to the XZ plane. -bool XZAngle(const gvr::Vec3f& vec1, const gvr::Vec3f& vec2, float* angle); - -} // namespace vr_shell - -#endif // CHROME_BROWSER_ANDROID_VR_SHELL_VR_MATH_H_
diff --git a/chrome/browser/android/vr_shell/vr_shell.cc b/chrome/browser/android/vr_shell/vr_shell.cc index f4547ff..eaedca5 100644 --- a/chrome/browser/android/vr_shell/vr_shell.cc +++ b/chrome/browser/android/vr_shell/vr_shell.cc
@@ -370,9 +370,9 @@ } void VrShell::UpdateWebVRTextureBounds(int16_t frame_index, - const gvr::Rectf& left_bounds, - const gvr::Rectf& right_bounds, - const gvr::Sizei& source_size) { + const gfx::RectF& left_bounds, + const gfx::RectF& right_bounds, + const gfx::Size& source_size) { PostToGlThreadWhenReady(base::Bind(&VrShellGl::UpdateWebVRTextureBounds, gl_thread_->GetVrShellGl(), frame_index, left_bounds, right_bounds, source_size));
diff --git a/chrome/browser/android/vr_shell/vr_shell.h b/chrome/browser/android/vr_shell/vr_shell.h index bf668d5..ae3d136 100644 --- a/chrome/browser/android/vr_shell/vr_shell.h +++ b/chrome/browser/android/vr_shell/vr_shell.h
@@ -202,9 +202,9 @@ void SubmitWebVRFrame(int16_t frame_index, const gpu::MailboxHolder& mailbox) override; void UpdateWebVRTextureBounds(int16_t frame_index, - const gvr::Rectf& left_bounds, - const gvr::Rectf& right_bounds, - const gvr::Sizei& source_size) override; + const gfx::RectF& left_bounds, + const gfx::RectF& right_bounds, + const gfx::Size& source_size) override; void OnVRVsyncProviderRequest( device::mojom::VRVSyncProviderRequest request) override; void UpdateVSyncInterval(int64_t timebase_nanos,
diff --git a/chrome/browser/android/vr_shell/vr_shell_gl.cc b/chrome/browser/android/vr_shell/vr_shell_gl.cc index 4191c59..a795a86f 100644 --- a/chrome/browser/android/vr_shell/vr_shell_gl.cc +++ b/chrome/browser/android/vr_shell/vr_shell_gl.cc
@@ -19,12 +19,12 @@ #include "chrome/browser/android/vr_shell/ui_scene.h" #include "chrome/browser/android/vr_shell/vr_controller.h" #include "chrome/browser/android/vr_shell/vr_gl_util.h" -#include "chrome/browser/android/vr_shell/vr_math.h" #include "chrome/browser/android/vr_shell/vr_shell.h" #include "chrome/browser/android/vr_shell/vr_shell_renderer.h" #include "device/vr/android/gvr/gvr_delegate.h" #include "device/vr/android/gvr/gvr_device.h" #include "device/vr/android/gvr/gvr_gamepad_data_provider.h" +#include "device/vr/vr_math.h" #include "third_party/WebKit/public/platform/WebInputEvent.h" #include "third_party/WebKit/public/platform/WebMouseEvent.h" #include "ui/gl/android/scoped_java_surface.h" @@ -48,11 +48,11 @@ // Angle (radians) the beam down from the controller axis, for wrist comfort. static constexpr float kErgoAngleOffset = 0.26f; -static constexpr gvr::Vec3f kOrigin = {0.0f, 0.0f, 0.0f}; +static constexpr gfx::Point3F kOrigin = {0.0f, 0.0f, 0.0f}; // In lieu of an elbow model, we assume a position for the user's hand. // TODO(mthiesse): Handedness options. -static constexpr gvr::Vec3f kHandPosition = {0.2f, -0.5f, -0.2f}; +static constexpr gfx::Point3F kHandPosition = {0.2f, -0.5f, -0.2f}; // Fraction of the distance to the object the cursor is drawn at to avoid // rounding errors drawing the cursor behind the object. @@ -68,7 +68,7 @@ // Pixel dimensions and field of view for the head-locked content. This // is currently sized to fit the WebVR "insecure transport" warnings, // adjust it as needed if there is additional content. -static constexpr gvr::Sizei kHeadlockedBufferDimensions = {1024, 1024}; +static constexpr gfx::Size kHeadlockedBufferDimensions = {1024, 1024}; static constexpr gvr::Rectf kHeadlockedBufferFov = {20.f, 20.f, 20.f, 20.f}; // The GVR viewport list has two entries (left eye and right eye) for each @@ -87,10 +87,10 @@ // Generate a quaternion representing the rotation from the negative Z axis // (0, 0, -1) to a specified vector. This is an optimized version of a more // general vector-to-vector calculation. -gvr::Quatf GetRotationFromZAxis(gvr::Vec3f vec) { - vr_shell::NormalizeVector(vec); - gvr::Quatf quat; - quat.qw = 1.0f - vec.z; +vr::Quatf GetRotationFromZAxis(gfx::Vector3dF vec) { + vr::NormalizeVector(&vec); + vr::Quatf quat; + quat.qw = 1.0f - vec.z(); if (quat.qw < 1e-6f) { // Degenerate case: vectors are exactly opposite. Replace by an // arbitrary 180 degree rotation to avoid invalid normalization. @@ -99,10 +99,10 @@ quat.qz = 0.0f; quat.qw = 0.0f; } else { - quat.qx = vec.y; - quat.qy = -vec.x; + quat.qx = vec.y(); + quat.qy = -vec.x(); quat.qz = 0.0f; - vr_shell::NormalizeQuat(quat); + vr::NormalizeQuat(&quat); } return quat; } @@ -133,6 +133,22 @@ callback.Run(std::move(info)); } +void MatfToGvrMat(const vr::Mat4f& in, gvr::Mat4f* out) { + // If our std::array implementation doesn't have any non-data members, we can + // just cast the gvr matrix to an std::array. + static_assert(sizeof(in) == sizeof(*out), + "Cannot reinterpret gvr::Mat4f as vr::Matf"); + *out = *reinterpret_cast<gvr::Mat4f*>(const_cast<vr::Mat4f*>(&in)); +} + +void GvrMatToMatf(const gvr::Mat4f& in, vr::Mat4f* out) { + // If our std::array implementation doesn't have any non-data members, we can + // just cast the gvr matrix to an std::array. + static_assert(sizeof(in) == sizeof(*out), + "Cannot reinterpret gvr::Mat4f as vr::Matf"); + *out = *reinterpret_cast<vr::Mat4f*>(const_cast<gvr::Mat4f*>(&in)); +} + } // namespace VrShellGl::VrShellGl( @@ -229,16 +245,16 @@ &VrShellGl::OnContentFrameAvailable, weak_ptr_factory_.GetWeakPtr())); webvr_surface_texture_->SetFrameAvailableCallback(base::Bind( &VrShellGl::OnWebVRFrameAvailable, weak_ptr_factory_.GetWeakPtr())); - ui_surface_texture_->SetDefaultBufferSize(ui_tex_physical_size_.width, - ui_tex_physical_size_.height); + ui_surface_texture_->SetDefaultBufferSize(ui_tex_physical_size_.width(), + ui_tex_physical_size_.height()); content_surface_texture_->SetDefaultBufferSize( - content_tex_physical_size_.width, content_tex_physical_size_.height); + content_tex_physical_size_.width(), content_tex_physical_size_.height()); InitializeRenderer(); - gvr::Sizei webvr_size = + gfx::Size webvr_size = device::GvrDelegate::GetRecommendedWebVrSize(gvr_api_.get()); - DVLOG(1) << __FUNCTION__ << ": resize initial to " << webvr_size.width << "x" - << webvr_size.height; + DVLOG(1) << __FUNCTION__ << ": resize initial to " << webvr_size.width() + << "x" << webvr_size.height(); CreateOrResizeWebVRSurface(webvr_size); @@ -264,7 +280,7 @@ ui_surface_->j_surface().obj())); } -void VrShellGl::CreateOrResizeWebVRSurface(const gvr::Sizei& size) { +void VrShellGl::CreateOrResizeWebVRSurface(const gfx::Size& size) { if (!webvr_surface_texture_) { DLOG(ERROR) << "No WebVR surface texture available"; return; @@ -276,16 +292,16 @@ return; } - if (!size.width || !size.height) { + if (!size.width() || !size.height()) { // Invalid size, defer until a new size arrives on a future bounds update. return; } - webvr_surface_texture_->SetDefaultBufferSize(size.width, size.height); + webvr_surface_texture_->SetDefaultBufferSize(size.width(), size.height()); webvr_surface_size_ = size; if (mailbox_bridge_) { - mailbox_bridge_->ResizeSurface(size.width, size.height); + mailbox_bridge_->ResizeSurface(size.width(), size.height()); } else { mailbox_bridge_ = base::MakeUnique<MailboxToSurfaceBridge>(); mailbox_bridge_->CreateSurface(webvr_surface_texture_.get()); @@ -389,21 +405,26 @@ void VrShellGl::InitializeRenderer() { gvr_api_->InitializeGl(); - webvr_head_pose_.assign(kPoseRingBufferSize, - gvr_api_->GetHeadSpaceFromStartSpaceRotation( - gvr::GvrApi::GetTimePointNow())); + vr::Mat4f head_pose; + device::GvrDelegate::GetGvrPoseWithNeckModel(gvr_api_.get(), &head_pose); + webvr_head_pose_.assign(kPoseRingBufferSize, head_pose); std::vector<gvr::BufferSpec> specs; // For kFramePrimaryBuffer (primary VrShell and WebVR content) specs.push_back(gvr_api_->CreateBufferSpec()); - render_size_primary_ = specs[kFramePrimaryBuffer].GetSize(); + gvr::Sizei render_size_primary = specs[kFramePrimaryBuffer].GetSize(); + render_size_primary_ = {render_size_primary.width, + render_size_primary.height}; render_size_vrshell_ = render_size_primary_; // For kFrameHeadlockedBuffer (for WebVR insecure content warning). // Set this up at fixed resolution, the (smaller) FOV gets set below. specs.push_back(gvr_api_->CreateBufferSpec()); - specs.back().SetSize(kHeadlockedBufferDimensions); - render_size_headlocked_ = specs[kFrameHeadlockedBuffer].GetSize(); + specs.back().SetSize({kHeadlockedBufferDimensions.width(), + kHeadlockedBufferDimensions.height()}); + gvr::Sizei render_size_headlocked = specs[kFrameHeadlockedBuffer].GetSize(); + render_size_headlocked_ = {render_size_headlocked.width, + render_size_headlocked.height}; swap_chain_.reset(new gvr::SwapChain(gvr_api_->CreateSwapChain(specs))); @@ -468,7 +489,7 @@ FROM_HERE, base::Bind(&VrShell::UpdateGamepadData, weak_vr_shell_, pad)); } -void VrShellGl::HandleControllerInput(const gvr::Vec3f& forward_vector) { +void VrShellGl::HandleControllerInput(const gfx::Vector3dF& forward_vector) { if (ShouldDrawWebVr()) { // Process screen touch events for Cardboard button compatibility. // Also send tap events for controller "touchpad click" events. @@ -487,7 +508,7 @@ } } - gvr::Vec3f ergo_neutral_pose; + gfx::Vector3dF ergo_neutral_pose; if (!controller_->IsConnected()) { // No controller detected, set up a gaze cursor that tracks the // forward direction. @@ -498,8 +519,10 @@ controller_quat_ = controller_->Orientation(); } - gvr::Mat4f mat = QuatToMatrix(controller_quat_); - gvr::Vec3f controller_direction = MatrixVectorMul(mat, ergo_neutral_pose); + vr::Mat4f mat; + QuatToMatrix(controller_quat_, &mat); + gfx::Vector3dF controller_direction = + vr::MatrixVectorMul(mat, ergo_neutral_pose); HandleControllerAppButtonActivity(controller_direction); @@ -522,13 +545,14 @@ // that the sphere is centered at the controller, rather than the eye, for // simplicity. float distance = scene_->GetBackgroundDistance(); - target_point_ = GetRayPoint(kHandPosition, controller_direction, distance); - gvr::Vec3f eye_to_target = target_point_; - NormalizeVector(eye_to_target); + target_point_ = + vr::GetRayPoint(kHandPosition, controller_direction, distance); + gfx::Vector3dF eye_to_target = target_point_ - kOrigin; + vr::NormalizeVector(&eye_to_target); // Determine which UI element (if any) intersects the line between the eyes // and the controller target position. - float closest_element_distance = VectorLength(target_point_); + float closest_element_distance = (target_point_ - kOrigin).Length(); target_element_ = nullptr; float target_x; float target_y; @@ -544,13 +568,13 @@ if (distance_to_plane < 0 || distance_to_plane >= closest_element_distance) continue; - gvr::Vec3f plane_intersection_point = - GetRayPoint(kOrigin, eye_to_target, distance_to_plane); - gvr::Vec2f unit_xy_point = + gfx::Point3F plane_intersection_point = + vr::GetRayPoint(kOrigin, eye_to_target, distance_to_plane); + gfx::PointF unit_xy_point = plane->GetUnitRectangleCoordinates(plane_intersection_point); - float x = 0.5f + unit_xy_point.x; - float y = 0.5f - unit_xy_point.y; + float x = 0.5f + unit_xy_point.x(); + float y = 0.5f - unit_xy_point.y(); if (x < 0.0f || x >= 1.0f || y < 0.0f || y >= 1.0f) continue; @@ -568,16 +592,17 @@ int pixel_y = 0; if (target_element_ != nullptr) { - Rectf pixel_rect; + gfx::RectF pixel_rect; if (target_element_->fill == Fill::CONTENT) { - pixel_rect = {0, 0, content_tex_css_width_, content_tex_css_height_}; + pixel_rect.SetRect(0, 0, content_tex_css_width_, content_tex_css_height_); } else { - pixel_rect = {target_element_->copy_rect.x, target_element_->copy_rect.y, - target_element_->copy_rect.width, - target_element_->copy_rect.height}; + pixel_rect.SetRect(target_element_->copy_rect.x(), + target_element_->copy_rect.y(), + target_element_->copy_rect.width(), + target_element_->copy_rect.height()); } - pixel_x = pixel_rect.x + pixel_rect.width * target_x; - pixel_y = pixel_rect.y + pixel_rect.height * target_y; + pixel_x = pixel_rect.x() + pixel_rect.width() * target_x; + pixel_y = pixel_rect.y() + pixel_rect.height() * target_y; switch (target_element_->fill) { case Fill::CONTENT: @@ -594,7 +619,7 @@ } void VrShellGl::HandleControllerAppButtonActivity( - const gvr::Vec3f& controller_direction) { + const gfx::Vector3dF& controller_direction) { // Note that button up/down state is transient, so ButtonDownHappened only // returns true for a single frame (and we're guaranteed not to miss it). if (controller_->ButtonDownHappened( @@ -610,8 +635,8 @@ // VrShellGl. UiInterface::Direction direction = UiInterface::NONE; float gesture_xz_angle; - if (XZAngle(controller_start_direction_, controller_direction, - &gesture_xz_angle)) { + if (vr::XZAngle(controller_start_direction_, controller_direction, + &gesture_xz_angle)) { if (fabs(gesture_xz_angle) > kMinAppButtonGestureAngleRad) { direction = gesture_xz_angle < 0 ? UiInterface::LEFT : UiInterface::RIGHT; @@ -746,10 +771,17 @@ break; const WebVrBounds& bounds = pending_bounds_.front().second; - webvr_left_viewport_->SetSourceUv(bounds.left_bounds); - webvr_right_viewport_->SetSourceUv(bounds.right_bounds); + const gfx::RectF& left = bounds.left_bounds; + const gfx::RectF& right = bounds.right_bounds; + gvr::Rectf gvr_left_bounds = {left.x(), left.x() + left.width(), + left.y() + left.height(), left.y()}; + webvr_left_viewport_->SetSourceUv(gvr_left_bounds); + gvr::Rectf gvr_right_bounds = {right.x(), right.x() + right.width(), + right.y() + right.height(), right.y()}; + webvr_right_viewport_->SetSourceUv(gvr_right_bounds); DVLOG(1) << __FUNCTION__ << ": resize from pending_bounds to " - << bounds.source_size.width << "x" << bounds.source_size.height; + << bounds.source_size.width() << "x" + << bounds.source_size.height(); CreateOrResizeWebVRSurface(bounds.source_size); pending_bounds_.pop(); } @@ -758,7 +790,7 @@ buffer_viewport_list_->SetBufferViewport(GVR_RIGHT_EYE, *webvr_right_viewport_); if (render_size_primary_ != webvr_surface_size_) { - if (!webvr_surface_size_.width) { + if (!webvr_surface_size_.width()) { // Don't try to resize to 0x0 pixels, drop frames until we get a // valid size. return; @@ -766,14 +798,18 @@ render_size_primary_ = webvr_surface_size_; DVLOG(1) << __FUNCTION__ << ": resize GVR to " - << render_size_primary_.width << "x" - << render_size_primary_.height; - swap_chain_->ResizeBuffer(kFramePrimaryBuffer, render_size_primary_); + << render_size_primary_.width() << "x" + << render_size_primary_.height(); + swap_chain_->ResizeBuffer( + kFramePrimaryBuffer, + {render_size_primary_.width(), render_size_primary_.height()}); } } else { if (render_size_primary_ != render_size_vrshell_) { render_size_primary_ = render_size_vrshell_; - swap_chain_->ResizeBuffer(kFramePrimaryBuffer, render_size_primary_); + swap_chain_->ResizeBuffer( + kFramePrimaryBuffer, + {render_size_primary_.width(), render_size_primary_.height()}); } } @@ -789,7 +825,7 @@ DrawWebVr(); } - gvr::Mat4f head_pose; + vr::Mat4f head_pose; // When using async reprojection, we need to know which pose was // used in the WebVR app for drawing this frame and supply it when @@ -801,7 +837,7 @@ "kPoseRingBufferSize must be a power of 2"); head_pose = webvr_head_pose_[frame_index % kPoseRingBufferSize]; } else { - head_pose = device::GvrDelegate::GetGvrPoseWithNeckModel(gvr_api_.get()); + device::GvrDelegate::GetGvrPoseWithNeckModel(gvr_api_.get(), &head_pose); } // Update the render position of all UI elements (including desktop). @@ -812,7 +848,7 @@ // for both the gamepad API and UI input handling. TRACE_EVENT0("gpu", "VrShellGl::UpdateController"); UpdateController(); - HandleControllerInput(GetForwardVector(head_pose)); + HandleControllerInput(vr::GetForwardVector(head_pose)); } DrawWorldElements(head_pose); @@ -828,7 +864,9 @@ { TRACE_EVENT0("gpu", "VrShellGl::Submit"); - frame.Submit(*buffer_viewport_list_, head_pose); + gvr::Mat4f mat; + MatfToGvrMat(head_pose, &mat); + frame.Submit(*buffer_viewport_list_, mat); } // No need to swap buffers for surfaceless rendering. @@ -839,7 +877,7 @@ } } -void VrShellGl::DrawWorldElements(const gvr::Mat4f& head_pose) { +void VrShellGl::DrawWorldElements(const vr::Mat4f& head_pose) { TRACE_EVENT0("gpu", "VrShellGl::DrawWorldElements"); if (ShouldDrawWebVr()) { @@ -856,7 +894,7 @@ glEnable(GL_DEPTH_TEST); glDepthMask(GL_TRUE); - const Colorf& backgroundColor = scene_->GetBackgroundColor(); + const vr::Colorf& backgroundColor = scene_->GetBackgroundColor(); glClearColor(backgroundColor.r, backgroundColor.g, backgroundColor.b, backgroundColor.a); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); @@ -881,15 +919,15 @@ glClearColor(0.0f, 0.0f, 0.0f, 0.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); - gvr::Mat4f identity_matrix; - SetIdentityM(identity_matrix); + vr::Mat4f identity_matrix; + vr::SetIdentityM(&identity_matrix); DrawUiView(identity_matrix, elements, render_size_headlocked_, kViewportListHeadlockedOffset, false); } -void VrShellGl::DrawUiView(const gvr::Mat4f& head_pose, +void VrShellGl::DrawUiView(const vr::Mat4f& head_pose, const std::vector<const ContentRectangle*>& elements, - const gvr::Sizei& render_size, + const gfx::Size& render_size, int viewport_offset, bool draw_cursor) { TRACE_EVENT0("gpu", "VrShellGl::DrawUiView"); @@ -900,19 +938,25 @@ buffer_viewport_list_->GetBufferViewport(eye + viewport_offset, buffer_viewport_.get()); - const gvr::Mat4f eye_view_matrix = - MatrixMul(gvr_api_->GetEyeFromHeadMatrix(eye), head_pose); + vr::Mat4f eye_view_matrix; + vr::Mat4f eye_matrix; + GvrMatToMatf(gvr_api_->GetEyeFromHeadMatrix(eye), &eye_matrix); + vr::MatrixMul(eye_matrix, head_pose, &eye_view_matrix); - gvr::Recti pixel_rect = - CalculatePixelSpaceRect(render_size, buffer_viewport_->GetSourceUv()); - glViewport(pixel_rect.left, pixel_rect.bottom, - pixel_rect.right - pixel_rect.left, - pixel_rect.top - pixel_rect.bottom); + gvr::Rectf gvr_rect = buffer_viewport_->GetSourceUv(); + gfx::RectF rect(gvr_rect.left, gvr_rect.top, gvr_rect.right - gvr_rect.left, + gvr_rect.bottom - gvr_rect.top); + gfx::Rect pixel_rect = CalculatePixelSpaceRect(render_size, rect); + glViewport(pixel_rect.x(), pixel_rect.y(), pixel_rect.width(), + pixel_rect.height()); - const gvr::Mat4f render_matrix = - MatrixMul(PerspectiveMatrixFromView(buffer_viewport_->GetSourceFov(), - kZNear, kZFar), - eye_view_matrix); + vr::Mat4f render_matrix; + vr::Mat4f perspective_matrix; + gvr::Rectf fov = buffer_viewport_->GetSourceFov(); + vr::PerspectiveMatrixFromView( + {fov.left, fov.top, fov.right - fov.left, fov.bottom - fov.top}, kZNear, + kZFar, &perspective_matrix); + vr::MatrixMul(perspective_matrix, eye_view_matrix, &render_matrix); DrawElements(render_matrix, elementsInDrawOrder); if (draw_cursor) { @@ -923,21 +967,19 @@ } void VrShellGl::DrawElements( - const gvr::Mat4f& view_proj_matrix, + const vr::Mat4f& view_proj_matrix, const std::vector<const ContentRectangle*>& elements) { for (const auto* rect : elements) { - gvr::Mat4f transform = MatrixMul(view_proj_matrix, rect->TransformMatrix()); + vr::Mat4f transform; + vr::MatrixMul(view_proj_matrix, rect->TransformMatrix(), &transform); switch (rect->fill) { case Fill::SPRITE: { - Rectf copy_rect; - copy_rect.x = static_cast<float>(rect->copy_rect.x) / ui_tex_css_width_; - copy_rect.y = - static_cast<float>(rect->copy_rect.y) / ui_tex_css_height_; - copy_rect.width = - static_cast<float>(rect->copy_rect.width) / ui_tex_css_width_; - copy_rect.height = - static_cast<float>(rect->copy_rect.height) / ui_tex_css_height_; + gfx::RectF copy_rect( + static_cast<float>(rect->copy_rect.x()) / ui_tex_css_width_, + static_cast<float>(rect->copy_rect.y()) / ui_tex_css_height_, + static_cast<float>(rect->copy_rect.width()) / ui_tex_css_width_, + static_cast<float>(rect->copy_rect.height()) / ui_tex_css_height_); jint texture_handle = ui_texture_id_; vr_shell_renderer_->GetTexturedQuadRenderer()->AddQuad( texture_handle, transform, copy_rect, rect->computed_opacity); @@ -958,7 +1000,7 @@ break; } case Fill::CONTENT: { - Rectf copy_rect = {0, 0, 1, 1}; + gfx::RectF copy_rect = {0, 0, 1, 1}; jint texture_handle = content_texture_id_; vr_shell_renderer_->GetTexturedQuadRenderer()->AddQuad( texture_handle, transform, copy_rect, rect->computed_opacity); @@ -973,7 +1015,7 @@ } std::vector<const ContentRectangle*> VrShellGl::GetElementsInDrawOrder( - const gvr::Mat4f& view_matrix, + const vr::Mat4f& view_matrix, const std::vector<const ContentRectangle*>& elements) { typedef std::pair<float, const ContentRectangle*> DistanceElementPair; std::vector<DistanceElementPair> zOrderedElementPairs; @@ -981,9 +1023,11 @@ for (const auto* element : elements) { // Distance is the abs(z) value in view space. - gvr::Vec3f element_position = GetTranslation(element->TransformMatrix()); + gfx::Vector3dF element_position = + vr::GetTranslation(element->TransformMatrix()); + float distance = - std::fabs(MatrixVectorMul(view_matrix, element_position).z); + std::fabs(vr::MatrixVectorMul(view_matrix, element_position).z()); zOrderedElementPairs.push_back(std::make_pair(distance, element)); } @@ -1007,81 +1051,90 @@ return zOrderedElements; } -void VrShellGl::DrawCursor(const gvr::Mat4f& render_matrix) { - gvr::Mat4f mat; - SetIdentityM(mat); +void VrShellGl::DrawCursor(const vr::Mat4f& render_matrix) { + vr::Mat4f mat; + vr::SetIdentityM(&mat); // Draw the reticle. // Scale the pointer to have a fixed FOV size at any distance. - const float eye_to_target = Distance(target_point_, kOrigin); - ScaleM(mat, mat, kReticleWidth * eye_to_target, - kReticleHeight * eye_to_target, 1.0f); + const float eye_to_target = + std::sqrt(target_point_.SquaredDistanceTo(kOrigin)); + vr::ScaleM( + mat, + {kReticleWidth * eye_to_target, kReticleHeight * eye_to_target, 1.0f}, + &mat); - gvr::Quatf rotation; + vr::Quatf rotation; if (target_element_ != nullptr) { // Make the reticle planar to the element it's hitting. rotation = GetRotationFromZAxis(target_element_->GetNormal()); } else { // Rotate the cursor to directly face the eyes. - rotation = GetRotationFromZAxis(target_point_); + rotation = GetRotationFromZAxis(target_point_ - kOrigin); } - mat = MatrixMul(QuatToMatrix(rotation), mat); + vr::Mat4f rotation_mat; + vr::QuatToMatrix(rotation, &rotation_mat); + vr::MatrixMul(rotation_mat, mat, &mat); + gfx::Point3F target_point = ScalePoint(target_point_, kReticleOffset); // Place the pointer slightly in front of the plane intersection point. - TranslateM(mat, mat, target_point_.x * kReticleOffset, - target_point_.y * kReticleOffset, - target_point_.z * kReticleOffset); + vr::TranslateM(mat, target_point - kOrigin, &mat); - gvr::Mat4f transform = MatrixMul(render_matrix, mat); + vr::Mat4f transform; + vr::MatrixMul(render_matrix, mat, &transform); vr_shell_renderer_->GetReticleRenderer()->Draw(transform); // Draw the laser. // Find the length of the beam (from hand to target). - const float laser_length = Distance(kHandPosition, target_point_); + const float laser_length = + std::sqrt(kHandPosition.SquaredDistanceTo(target_point)); // Build a beam, originating from the origin. - SetIdentityM(mat); + vr::SetIdentityM(&mat); // Move the beam half its height so that its end sits on the origin. - TranslateM(mat, mat, 0.0f, 0.5f, 0.0f); - ScaleM(mat, mat, kLaserWidth, laser_length, 1); + vr::TranslateM(mat, {0.0f, 0.5f, 0.0f}, &mat); + vr::ScaleM(mat, {kLaserWidth, laser_length, 1}, &mat); // Tip back 90 degrees to flat, pointing at the scene. - const gvr::Quatf q = QuatFromAxisAngle({1.0f, 0.0f, 0.0f}, -M_PI / 2); - mat = MatrixMul(QuatToMatrix(q), mat); + const vr::Quatf quat = vr::QuatFromAxisAngle({1.0f, 0.0f, 0.0f, -M_PI / 2}); + vr::QuatToMatrix(quat, &rotation_mat); + vr::MatrixMul(rotation_mat, mat, &mat); - const gvr::Vec3f beam_direction = {target_point_.x - kHandPosition.x, - target_point_.y - kHandPosition.y, - target_point_.z - kHandPosition.z}; - const gvr::Mat4f beam_direction_mat = - QuatToMatrix(GetRotationFromZAxis(beam_direction)); + const gfx::Vector3dF beam_direction = target_point_ - kHandPosition; + + vr::Mat4f beam_direction_mat; + vr::QuatToMatrix(GetRotationFromZAxis(beam_direction), &beam_direction_mat); // Render multiple faces to make the laser appear cylindrical. const int faces = 4; for (int i = 0; i < faces; i++) { // Rotate around Z. const float angle = M_PI * 2 * i / faces; - const gvr::Quatf rot = QuatFromAxisAngle({0.0f, 0.0f, 1.0f}, angle); - gvr::Mat4f face_transform = MatrixMul(QuatToMatrix(rot), mat); - + const vr::Quatf rot = vr::QuatFromAxisAngle({0.0f, 0.0f, 1.0f, angle}); + vr::Mat4f face_transform; + vr::QuatToMatrix(rot, &face_transform); + vr::MatrixMul(face_transform, mat, &face_transform); // Orient according to target direction. - face_transform = MatrixMul(beam_direction_mat, face_transform); + vr::MatrixMul(beam_direction_mat, face_transform, &face_transform); // Move the beam origin to the hand. - TranslateM(face_transform, face_transform, kHandPosition.x, kHandPosition.y, - kHandPosition.z); + vr::TranslateM(face_transform, kHandPosition - kOrigin, &face_transform); - transform = MatrixMul(render_matrix, face_transform); + vr::MatrixMul(render_matrix, face_transform, &transform); vr_shell_renderer_->GetLaserRenderer()->Draw(transform); } } -void VrShellGl::DrawController(const gvr::Mat4f& view_proj_matrix) { +void VrShellGl::DrawController(const vr::Mat4f& view_proj_matrix) { if (!vr_shell_renderer_->GetControllerRenderer()->IsSetUp()) return; - auto transform = MatrixMul(view_proj_matrix, controller_->GetTransform()); + vr::Mat4f controller_transform; + controller_->GetTransform(&controller_transform); + vr::Mat4f transform; + vr::MatrixMul(view_proj_matrix, controller_transform, &transform); auto state = controller_->GetModelState(); vr_shell_renderer_->GetControllerRenderer()->Draw(state, transform); } @@ -1108,7 +1161,7 @@ // it's not supported on older devices such as Nexus 5X. glClear(GL_COLOR_BUFFER_BIT); - glViewport(0, 0, webvr_surface_size_.width, webvr_surface_size_.height); + glViewport(0, 0, webvr_surface_size_.width(), webvr_surface_size_.height()); vr_shell_renderer_->GetWebVrRenderer()->Draw(webvr_texture_id_); } @@ -1138,12 +1191,16 @@ } void VrShellGl::UpdateWebVRTextureBounds(int16_t frame_index, - const gvr::Rectf& left_bounds, - const gvr::Rectf& right_bounds, - const gvr::Sizei& source_size) { + const gfx::RectF& left_bounds, + const gfx::RectF& right_bounds, + const gfx::Size& source_size) { if (frame_index < 0) { - webvr_left_viewport_->SetSourceUv(left_bounds); - webvr_right_viewport_->SetSourceUv(right_bounds); + gvr::Rectf left = {left_bounds.x(), left_bounds.right(), + left_bounds.bottom(), left_bounds.y()}; + webvr_left_viewport_->SetSourceUv(left); + gvr::Rectf right = {right_bounds.x(), right_bounds.right(), + right_bounds.bottom(), right_bounds.y()}; + webvr_right_viewport_->SetSourceUv(right); CreateOrResizeWebVRSurface(source_size); } else { pending_bounds_.emplace( @@ -1160,8 +1217,8 @@ void VrShellGl::ContentPhysicalBoundsChanged(int width, int height) { if (content_surface_texture_.get()) content_surface_texture_->SetDefaultBufferSize(width, height); - content_tex_physical_size_.width = width; - content_tex_physical_size_.height = height; + content_tex_physical_size_.set_width(width); + content_tex_physical_size_.set_height(height); } void VrShellGl::UIBoundsChanged(int width, int height) { @@ -1172,8 +1229,8 @@ void VrShellGl::UIPhysicalBoundsChanged(int width, int height) { if (ui_surface_texture_.get()) ui_surface_texture_->SetDefaultBufferSize(width, height); - ui_tex_physical_size_.width = width; - ui_tex_physical_size_.height = height; + ui_tex_physical_size_.set_width(width); + ui_tex_physical_size_.set_height(height); } base::WeakPtr<VrShellGl> VrShellGl::GetWeakPtr() { @@ -1259,7 +1316,7 @@ TRACE_EVENT1("input", "VrShellGl::SendVSync", "frame", frame_index); - gvr::Mat4f head_mat; + vr::Mat4f head_mat; device::mojom::VRPosePtr pose = device::GvrDelegate::GetVRPosePtrWithNeckModel(gvr_api_.get(), &head_mat);
diff --git a/chrome/browser/android/vr_shell/vr_shell_gl.h b/chrome/browser/android/vr_shell/vr_shell_gl.h index 68d7a5cd..97dbddf 100644 --- a/chrome/browser/android/vr_shell/vr_shell_gl.h +++ b/chrome/browser/android/vr_shell/vr_shell_gl.h
@@ -17,6 +17,7 @@ #include "base/single_thread_task_runner.h" #include "chrome/browser/android/vr_shell/vr_controller_model.h" #include "device/vr/vr_service.mojom.h" +#include "device/vr/vr_types.h" #include "mojo/public/cpp/bindings/binding.h" #include "third_party/gvr-android-sdk/src/libraries/headers/vr/gvr/capi/include/gvr.h" #include "third_party/gvr-android-sdk/src/libraries/headers/vr/gvr/capi/include/gvr_types.h" @@ -51,11 +52,13 @@ struct ContentRectangle; struct WebVrBounds { - WebVrBounds(gvr::Rectf left, gvr::Rectf right, gvr::Sizei size) + WebVrBounds(const gfx::RectF& left, + const gfx::RectF& right, + const gfx::Size& size) : left_bounds(left), right_bounds(right), source_size(size) {} - gvr::Rectf left_bounds; - gvr::Rectf right_bounds; - gvr::Sizei source_size; + gfx::RectF left_bounds; + gfx::RectF right_bounds; + gfx::Size source_size; }; // This class manages all GLThread owned objects and GL rendering for VrShell. @@ -83,7 +86,7 @@ void OnResume(); void SetWebVrMode(bool enabled); - void CreateOrResizeWebVRSurface(const gvr::Sizei& size); + void CreateOrResizeWebVRSurface(const gfx::Size& size); void CreateContentSurface(); void ContentBoundsChanged(int width, int height); void ContentPhysicalBoundsChanged(int width, int height); @@ -94,9 +97,9 @@ void SetControllerModel(std::unique_ptr<VrControllerModel> model); void UpdateWebVRTextureBounds(int16_t frame_index, - const gvr::Rectf& left_bounds, - const gvr::Rectf& right_bounds, - const gvr::Sizei& source_size); + const gfx::RectF& left_bounds, + const gfx::RectF& right_bounds, + const gfx::Size& source_size); void UpdateScene(std::unique_ptr<base::ListValue> commands); @@ -114,28 +117,28 @@ void GvrInit(gvr_context* gvr_api); void InitializeRenderer(); void DrawFrame(int16_t frame_index); - void DrawWorldElements(const gvr::Mat4f& head_pose); + void DrawWorldElements(const vr::Mat4f& head_pose); void DrawHeadLockedElements(); - void DrawUiView(const gvr::Mat4f& head_pose, + void DrawUiView(const vr::Mat4f& head_pose, const std::vector<const ContentRectangle*>& elements, - const gvr::Sizei& render_size, + const gfx::Size& render_size, int viewport_offset, bool draw_cursor); - void DrawElements(const gvr::Mat4f& view_proj_matrix, + void DrawElements(const vr::Mat4f& view_proj_matrix, const std::vector<const ContentRectangle*>& elements); std::vector<const ContentRectangle*> GetElementsInDrawOrder( - const gvr::Mat4f& view_matrix, + const vr::Mat4f& view_matrix, const std::vector<const ContentRectangle*>& elements); - void DrawCursor(const gvr::Mat4f& render_matrix); - void DrawController(const gvr::Mat4f& view_proj_matrix); + void DrawCursor(const vr::Mat4f& render_matrix); + void DrawController(const vr::Mat4f& view_proj_matrix); bool ShouldDrawWebVr(); void DrawWebVr(); bool WebVrPoseByteIsValid(int pose_index_byte); void UpdateController(); - void HandleControllerInput(const gvr::Vec3f& forward_vector); + void HandleControllerInput(const gfx::Vector3dF& forward_vector); void HandleControllerAppButtonActivity( - const gvr::Vec3f& controller_direction); + const gfx::Vector3dF& controller_direction); void SendEventsToTarget(InputTarget input_target, int pixel_x, int pixel_y); void SendGesture(InputTarget input_target, std::unique_ptr<blink::WebInputEvent> event); @@ -186,19 +189,19 @@ std::unique_ptr<MailboxToSurfaceBridge> mailbox_bridge_; // Current sizes for the render buffers. - gvr::Sizei render_size_primary_; - gvr::Sizei render_size_headlocked_; + gfx::Size render_size_primary_; + gfx::Size render_size_headlocked_; // Intended render_size_primary_ for use by VrShell, so that it // can be restored after exiting WebVR mode. - gvr::Sizei render_size_vrshell_; + gfx::Size render_size_vrshell_; std::unique_ptr<VrShellRenderer> vr_shell_renderer_; bool touch_pending_ = false; - gvr::Quatf controller_quat_; + vr::Quatf controller_quat_; - gvr::Vec3f target_point_; + gfx::Point3F target_point_; const ContentRectangle* target_element_ = nullptr; InputTarget current_input_target_ = InputTarget::NONE; InputTarget current_scroll_target = InputTarget::NONE; @@ -206,11 +209,11 @@ int ui_tex_css_height_ = 0; int content_tex_css_width_ = 0; int content_tex_css_height_ = 0; - gvr::Sizei content_tex_physical_size_ = {0, 0}; - gvr::Sizei webvr_surface_size_ = {0, 0}; - gvr::Sizei ui_tex_physical_size_ = {0, 0}; + gfx::Size content_tex_physical_size_ = {0, 0}; + gfx::Size webvr_surface_size_ = {0, 0}; + gfx::Size ui_tex_physical_size_ = {0, 0}; - std::vector<gvr::Mat4f> webvr_head_pose_; + std::vector<vr::Mat4f> webvr_head_pose_; bool web_vr_mode_; bool ready_to_draw_ = false; bool surfaceless_rendering_; @@ -237,7 +240,7 @@ uint16_t last_frame_index_ = -1; // Attributes for gesture detection while holding app button. - gvr::Vec3f controller_start_direction_; + gfx::Vector3dF controller_start_direction_; base::WeakPtrFactory<VrShellGl> weak_ptr_factory_;
diff --git a/chrome/browser/android/vr_shell/vr_shell_renderer.cc b/chrome/browser/android/vr_shell/vr_shell_renderer.cc index 0898d6c..7951074d 100644 --- a/chrome/browser/android/vr_shell/vr_shell_renderer.cc +++ b/chrome/browser/android/vr_shell/vr_shell_renderer.cc
@@ -267,7 +267,7 @@ BaseQuadRenderer::~BaseQuadRenderer() = default; void BaseQuadRenderer::PrepareToDraw(GLuint view_proj_matrix_handle, - const gvr::Mat4f& view_proj_matrix) { + const vr::Mat4f& view_proj_matrix) { glUseProgram(program_handle_); // Pass in model view project matrix. @@ -311,13 +311,14 @@ } void TexturedQuadRenderer::AddQuad(int texture_data_handle, - const gvr::Mat4f& view_proj_matrix, - const Rectf& copy_rect, + const vr::Mat4f& view_proj_matrix, + const gfx::RectF& copy_rect, float opacity) { TexturedQuad quad; quad.texture_data_handle = texture_data_handle; quad.view_proj_matrix = view_proj_matrix; - quad.copy_rect = copy_rect; + quad.copy_rect = {copy_rect.x(), copy_rect.y(), copy_rect.width(), + copy_rect.height()}; quad.opacity = opacity; quad_queue_.push(quad); } @@ -461,7 +462,7 @@ glGetUniformLocation(program_handle_, "mid_ring_opacity"); } -void ReticleRenderer::Draw(const gvr::Mat4f& view_proj_matrix) { +void ReticleRenderer::Draw(const vr::Mat4f& view_proj_matrix) { PrepareToDraw(model_view_proj_matrix_handle_, view_proj_matrix); glUniform4f(color_handle_, kReticleColor[0], kReticleColor[1], @@ -502,7 +503,7 @@ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); } -void LaserRenderer::Draw(const gvr::Mat4f& view_proj_matrix) { +void LaserRenderer::Draw(const vr::Mat4f& view_proj_matrix) { PrepareToDraw(model_view_proj_matrix_handle_, view_proj_matrix); // Link texture data with texture unit. @@ -577,7 +578,7 @@ } void ControllerRenderer::Draw(VrControllerModel::State state, - const gvr::Mat4f& view_proj_matrix) { + const vr::Mat4f& view_proj_matrix) { glUseProgram(program_handle_); glUniformMatrix4fv(model_view_proj_matrix_handle_, 1, false, @@ -617,9 +618,9 @@ opacity_handle_ = glGetUniformLocation(program_handle_, "u_Opacity"); } -void GradientQuadRenderer::Draw(const gvr::Mat4f& view_proj_matrix, - const Colorf& edge_color, - const Colorf& center_color, +void GradientQuadRenderer::Draw(const vr::Mat4f& view_proj_matrix, + const vr::Colorf& edge_color, + const vr::Colorf& center_color, float opacity) { PrepareToDraw(model_view_proj_matrix_handle_, view_proj_matrix); @@ -651,9 +652,9 @@ opacity_handle_ = glGetUniformLocation(program_handle_, "u_Opacity"); } -void GradientGridRenderer::Draw(const gvr::Mat4f& view_proj_matrix, - const Colorf& edge_color, - const Colorf& center_color, +void GradientGridRenderer::Draw(const vr::Mat4f& view_proj_matrix, + const vr::Colorf& edge_color, + const vr::Colorf& center_color, int gridline_count, float opacity) { // In case the tile number changed we have to regenerate the grid lines.
diff --git a/chrome/browser/android/vr_shell/vr_shell_renderer.h b/chrome/browser/android/vr_shell/vr_shell_renderer.h index 81811d3b..9871479 100644 --- a/chrome/browser/android/vr_shell/vr_shell_renderer.h +++ b/chrome/browser/android/vr_shell/vr_shell_renderer.h
@@ -11,8 +11,7 @@ #include "base/macros.h" #include "chrome/browser/android/vr_shell/vr_controller_model.h" -#include "chrome/browser/android/vr_shell/vr_math.h" -#include "third_party/gvr-android-sdk/src/libraries/headers/vr/gvr/capi/include/gvr_types.h" +#include "device/vr/vr_types.h" #include "ui/gl/gl_bindings.h" namespace vr_shell { @@ -47,6 +46,13 @@ float z; }; +struct RectF { + float x; + float y; + float width; + float height; +}; + struct Line3d { Vertex3d start; Vertex3d end; @@ -54,8 +60,8 @@ struct TexturedQuad { int texture_data_handle; - gvr::Mat4f view_proj_matrix; - Rectf copy_rect; + vr::Mat4f view_proj_matrix; + RectF copy_rect; float opacity; }; @@ -82,7 +88,7 @@ protected: void PrepareToDraw(GLuint view_proj_matrix_handle, - const gvr::Mat4f& view_proj_matrix); + const vr::Mat4f& view_proj_matrix); static GLuint vertex_buffer_; @@ -96,8 +102,8 @@ // Draw the content rect in the texture quad. void AddQuad(int texture_data_handle, - const gvr::Mat4f& view_proj_matrix, - const Rectf& copy_rect, + const vr::Mat4f& view_proj_matrix, + const gfx::RectF& copy_rect, float opacity); void Flush(); @@ -132,7 +138,7 @@ ReticleRenderer(); ~ReticleRenderer() override; - void Draw(const gvr::Mat4f& view_proj_matrix); + void Draw(const vr::Mat4f& view_proj_matrix); private: GLuint model_view_proj_matrix_handle_; @@ -152,7 +158,7 @@ LaserRenderer(); ~LaserRenderer() override; - void Draw(const gvr::Mat4f& view_proj_matrix); + void Draw(const vr::Mat4f& view_proj_matrix); private: GLuint model_view_proj_matrix_handle_; @@ -171,7 +177,7 @@ ~ControllerRenderer() override; void SetUp(std::unique_ptr<VrControllerModel> model); - void Draw(VrControllerModel::State state, const gvr::Mat4f& view_proj_matrix); + void Draw(VrControllerModel::State state, const vr::Mat4f& view_proj_matrix); bool IsSetUp() const { return setup_; } private: @@ -202,9 +208,9 @@ GradientQuadRenderer(); ~GradientQuadRenderer() override; - void Draw(const gvr::Mat4f& view_proj_matrix, - const Colorf& edge_color, - const Colorf& center_color, + void Draw(const vr::Mat4f& view_proj_matrix, + const vr::Colorf& edge_color, + const vr::Colorf& center_color, float opacity); private: @@ -222,9 +228,9 @@ GradientGridRenderer(); ~GradientGridRenderer() override; - void Draw(const gvr::Mat4f& view_proj_matrix, - const Colorf& edge_color, - const Colorf& center_color, + void Draw(const vr::Mat4f& view_proj_matrix, + const vr::Colorf& edge_color, + const vr::Colorf& center_color, int gridline_count, float opacity);
diff --git a/chrome/browser/banners/app_banner_manager.cc b/chrome/browser/banners/app_banner_manager.cc index 3c2bf84..af60409 100644 --- a/chrome/browser/banners/app_banner_manager.cc +++ b/chrome/browser/banners/app_banner_manager.cc
@@ -37,6 +37,13 @@ return InstallableParams(); } +// Returns whether or not the URLs match for everything except for the ref. +bool URLsAreForTheSamePage(const GURL& first, const GURL& second) { + return first.GetWithEmptyPath() == second.GetWithEmptyPath() && + first.path_piece() == second.path_piece() && + first.query_piece() == second.query_piece(); +} + } // anonymous namespace namespace banners { @@ -57,14 +64,6 @@ AppBannerSettingsHelper::SetTotalEngagementToTrigger(engagement); } -// static -bool AppBannerManager::URLsAreForTheSamePage(const GURL& first, - const GURL& second) { - return first.GetWithEmptyPath() == second.GetWithEmptyPath() && - first.path_piece() == second.path_piece() && - first.query_piece() == second.query_piece(); -} - void AppBannerManager::RequestAppBanner(const GURL& validated_url, bool is_debug_mode) { content::WebContents* contents = web_contents();
diff --git a/chrome/browser/banners/app_banner_manager.h b/chrome/browser/banners/app_banner_manager.h index 487592f..b9060538 100644 --- a/chrome/browser/banners/app_banner_manager.h +++ b/chrome/browser/banners/app_banner_manager.h
@@ -59,9 +59,6 @@ // Sets the total engagement required for triggering the banner in testing. static void SetTotalEngagementToTrigger(double engagement); - // Returns whether or not the URLs match for everything except for the ref. - static bool URLsAreForTheSamePage(const GURL& first, const GURL& second); - // Requests an app banner. If |is_debug_mode| is true, any failure in the // pipeline will be reported to the devtools console. virtual void RequestAppBanner(const GURL& validated_url, bool is_debug_mode);
diff --git a/chrome/browser/browser_resources.grd b/chrome/browser/browser_resources.grd index 7b32099..23b1f50 100644 --- a/chrome/browser/browser_resources.grd +++ b/chrome/browser/browser_resources.grd
@@ -453,7 +453,7 @@ <include name="IDR_PROFILER_JS" file="resources\profiler\profiler.js" flattenhtml="true" type="BINDATA" compress="gzip" /> <include name="IDR_SITE_ENGAGEMENT_HTML" file="resources\engagement\site_engagement.html" flattenhtml="true" type="BINDATA" compress="gzip" /> <include name="IDR_SITE_ENGAGEMENT_JS" file="resources\engagement\site_engagement.js" flattenhtml="true" type="BINDATA" compress="gzip" /> - <include name="IDR_SITE_ENGAGEMENT_MOJO_JS" file="${root_gen_dir}\chrome\browser\engagement\site_engagement.mojom.js" use_base_dir="false" type="BINDATA" compress="gzip" /> + <include name="IDR_SITE_ENGAGEMENT_MOJO_JS" file="${root_gen_dir}\chrome\browser\engagement\site_engagement_details.mojom.js" use_base_dir="false" type="BINDATA" compress="gzip" /> <include name="IDR_URL_MOJO_JS" file="${root_gen_dir}\url\mojo\url.mojom.js" use_base_dir="false" type="BINDATA" compress="gzip" /> <include name="IDR_SYNC_CONFIRMATION_CSS" file="resources\signin\sync_confirmation\sync_confirmation.css" type="BINDATA" /> <include name="IDR_SYNC_CONFIRMATION_HTML" file="resources\signin\sync_confirmation\sync_confirmation.html" flattenhtml="true" allowexternalscript="true" type="BINDATA" />
diff --git a/chrome/browser/chrome_content_browser_manifest_overlay.json b/chrome/browser/chrome_content_browser_manifest_overlay.json index 90322a9..8ff6293 100644 --- a/chrome/browser/chrome_content_browser_manifest_overlay.json +++ b/chrome/browser/chrome_content_browser_manifest_overlay.json
@@ -55,7 +55,7 @@ // TODO(beng): These should be moved to a separate capability. "mojom::OmniboxPageHandler", "mojom::PluginsPageHandler", - "mojom::SiteEngagementUIHandler", + "mojom::SiteEngagementDetailsProvider", "mojom::UsbInternalsPageHandler" ] }
diff --git a/chrome/browser/chromeos/BUILD.gn b/chrome/browser/chromeos/BUILD.gn index e549841b..1d0e4a4 100644 --- a/chrome/browser/chromeos/BUILD.gn +++ b/chrome/browser/chromeos/BUILD.gn
@@ -1228,12 +1228,11 @@ "printing/cups_print_job_notification.h", "printing/cups_print_job_notification_manager.cc", "printing/cups_print_job_notification_manager.h", - "printing/fake_printer_discoverer.cc", - "printing/fake_printer_discoverer.h", "printing/ppd_provider_factory.cc", "printing/ppd_provider_factory.h", "printing/printer_configurer.cc", "printing/printer_configurer.h", + "printing/printer_discoverer.cc", "printing/printer_discoverer.h", "printing/printers_manager.cc", "printing/printers_manager.h",
diff --git a/chrome/browser/chromeos/extensions/first_run_private_api.cc b/chrome/browser/chromeos/extensions/first_run_private_api.cc index 55e45fb0..53bf546e 100644 --- a/chrome/browser/chromeos/extensions/first_run_private_api.cc +++ b/chrome/browser/chromeos/extensions/first_run_private_api.cc
@@ -53,6 +53,9 @@ localized_strings->SetString( "closeButton", l10n_util::GetStringUTF16(IDS_CLOSE)); + localized_strings->SetString( + "accessibleTitle", + l10n_util::GetStringUTF16(IDS_FIRST_RUN_ACCESSIBLE_TITLE)); const std::string& app_locale = g_browser_process->GetApplicationLocale(); webui::SetLoadTimeDataDefaults(app_locale, localized_strings.get());
diff --git a/chrome/browser/chromeos/login/resource_loader_browsertest.cc b/chrome/browser/chromeos/login/resource_loader_browsertest.cc index ab0d23a..b806a154 100644 --- a/chrome/browser/chromeos/login/resource_loader_browsertest.cc +++ b/chrome/browser/chromeos/login/resource_loader_browsertest.cc
@@ -28,7 +28,8 @@ GURL CreateResource(const std::string& content) { base::FilePath path; EXPECT_TRUE(base::CreateTemporaryFile(&path)); - EXPECT_TRUE(base::WriteFile(path, content.c_str(), content.size())); + EXPECT_EQ(static_cast<int>(content.size()), + base::WriteFile(path, content.c_str(), content.size())); return GURL("file:///" + path.AsUTF8Unsafe()); }
diff --git a/chrome/browser/chromeos/login/saml/saml_browsertest.cc b/chrome/browser/chromeos/login/saml/saml_browsertest.cc index b46f31a6..743d699 100644 --- a/chrome/browser/chromeos/login/saml/saml_browsertest.cc +++ b/chrome/browser/chromeos/login/saml/saml_browsertest.cc
@@ -1346,9 +1346,18 @@ EXPECT_EQ(kSAMLIdPCookieValue2, GetCookieValue(kSAMLIdPCookieName)); } -// Flaky on Debug, ASan and MSan bots: crbug.com/683161. -IN_PROC_BROWSER_TEST_F(SAMLPolicyTest, - DISABLED_PRE_TransferCookiesUnaffiliated) { +// PRE_TransferCookiesUnaffiliated and TransferCookiesUnaffiliated are flaky on +// MSAN and ASAN, most probably timing out. See crbug.com/683161. +#if defined(MEMORY_SANITIZER) || defined(ADDRESS_SANITIZER) +#define MAYBE_PRE_TransferCookiesUnaffiliated \ + DISABLED_PRE_TransferCookiesUnaffiliated +#define MAYBE_TransferCookiesUnaffiliated DISABLED_TransferCookiesUnaffiliated +#else +#define MAYBE_PRE_TransferCookiesUnaffiliated PRE_TransferCookiesUnaffiliated +#define MAYBE_TransferCookiesUnaffiliated TransferCookiesUnaffiliated +#endif + +IN_PROC_BROWSER_TEST_F(SAMLPolicyTest, MAYBE_PRE_TransferCookiesUnaffiliated) { fake_saml_idp()->SetCookieValue(kSAMLIdPCookieValue1); LogInWithSAML(kDifferentDomainSAMLUserEmail, kTestAuthSIDCookie1, @@ -1364,8 +1373,7 @@ // IdP are not transferred to a user's profile on subsequent login if the user // does not belong to the domain that the device is enrolled into. Also verifies // that GAIA cookies are not transferred. -// Flaky on Debug, ASan and MSan bots: crbug.com/683161. -IN_PROC_BROWSER_TEST_F(SAMLPolicyTest, DISABLED_TransferCookiesUnaffiliated) { +IN_PROC_BROWSER_TEST_F(SAMLPolicyTest, MAYBE_TransferCookiesUnaffiliated) { fake_saml_idp()->SetCookieValue(kSAMLIdPCookieValue2); fake_saml_idp()->SetLoginHTMLTemplate("saml_login.html"); ShowGAIALoginForm();
diff --git a/chrome/browser/chromeos/login/session/user_session_manager.cc b/chrome/browser/chromeos/login/session/user_session_manager.cc index 68980b7..1d6b4e5 100644 --- a/chrome/browser/chromeos/login/session/user_session_manager.cc +++ b/chrome/browser/chromeos/login/session/user_session_manager.cc
@@ -29,7 +29,6 @@ #include "chrome/browser/browser_process_platform_part_chromeos.h" #include "chrome/browser/browser_shutdown.h" #include "chrome/browser/chrome_notification_types.h" -#include "chrome/browser/chromeos/accessibility/accessibility_manager.h" #include "chrome/browser/chromeos/arc/arc_service_launcher.h" #include "chrome/browser/chromeos/arc/arc_util.h" #include "chrome/browser/chromeos/base/locale_util.h" @@ -57,6 +56,7 @@ #include "chrome/browser/chromeos/login/users/chrome_user_manager.h" #include "chrome/browser/chromeos/login/users/supervised_user_manager.h" #include "chrome/browser/chromeos/login/wizard_controller.h" +#include "chrome/browser/chromeos/net/tether_notification_presenter.h" #include "chrome/browser/chromeos/policy/browser_policy_connector_chromeos.h" #include "chrome/browser/chromeos/profiles/profile_helper.h" #include "chrome/browser/chromeos/settings/cros_settings.h" @@ -73,6 +73,7 @@ #include "chrome/browser/profiles/profile_manager.h" #include "chrome/browser/signin/account_tracker_service_factory.h" #include "chrome/browser/signin/easy_unlock_service.h" +#include "chrome/browser/signin/profile_oauth2_token_service_factory.h" #include "chrome/browser/signin/signin_manager_factory.h" #include "chrome/browser/supervised_user/child_accounts/child_account_service.h" #include "chrome/browser/supervised_user/child_accounts/child_account_service_factory.h" @@ -91,6 +92,8 @@ #include "chromeos/dbus/dbus_thread_manager.h" #include "chromeos/dbus/session_manager_client.h" #include "chromeos/login/auth/stub_authenticator.h" +#include "chromeos/network/network_connect.h" +#include "chromeos/network/network_state_handler.h" #include "chromeos/network/portal_detector/network_portal_detector.h" #include "chromeos/network/portal_detector/network_portal_detector_strategy.h" #include "chromeos/settings/cros_settings_names.h" @@ -120,6 +123,7 @@ #include "rlz/features/features.h" #include "ui/base/ime/chromeos/input_method_descriptor.h" #include "ui/base/ime/chromeos/input_method_manager.h" +#include "ui/message_center/message_center.h" #include "url/gurl.h" #if BUILDFLAG(ENABLE_RLZ) @@ -139,12 +143,6 @@ // for, waiting for a session restore to finish. static const int kMaxRestartDelaySeconds = 10; -// ChromeVox tutorial URL (used in place of "getting started" url when -// accessibility is enabled). -const char kChromeVoxTutorialURLPattern[] = - "chrome-extension://mndnfokpggljbaajbnioimlmbfngpief/" - "cvox2/background/panel.html?tutorial"; - void InitLocaleAndInputMethodsForNewUser( UserSessionManager* session_manager, Profile* profile, @@ -1254,8 +1252,15 @@ if (base::CommandLine::ForCurrentProcess()->HasSwitch( chromeos::switches::kEnableTether)) { - chromeos::tether::Initializer::Initialize( - ChromeCryptAuthServiceFactory::GetForBrowserContext(profile)); + auto notification_presenter = + base::MakeUnique<tether::TetherNotificationPresenter>( + message_center::MessageCenter::Get(), NetworkConnect::Get()); + chromeos::tether::Initializer::Init( + ChromeCryptAuthServiceFactory::GetForBrowserContext(profile), + std::move(notification_presenter), profile->GetPrefs(), + ProfileOAuth2TokenServiceFactory::GetForProfile(profile), + NetworkHandler::Get()->network_state_handler(), + NetworkConnect::Get()); } } @@ -1313,15 +1318,6 @@ bool can_show_getstarted_guide = user_manager->GetActiveUser()->GetType() == user_manager::USER_TYPE_REGULAR; - // Skip the default first-run behavior for public accounts. - if (!user_manager->IsLoggedInAsPublicAccount()) { - if (AccessibilityManager::Get()->IsSpokenFeedbackEnabled()) { - const char* url = kChromeVoxTutorialURLPattern; - start_urls.push_back(url); - can_show_getstarted_guide = false; - } - } - // Only show getting started guide for a new user. const bool should_show_getstarted_guide = user_manager->IsCurrentUserNew(); @@ -1948,6 +1944,11 @@ } void UserSessionManager::Shutdown() { + if (base::CommandLine::ForCurrentProcess()->HasSwitch( + chromeos::switches::kEnableTether)) { + chromeos::tether::Initializer::Shutdown(); + } + token_handle_fetcher_.reset(); token_handle_util_.reset(); first_run::GoodiesDisplayer::Delete();
diff --git a/chrome/browser/chromeos/login/signin/device_id_browsertest.cc b/chrome/browser/chromeos/login/signin/device_id_browsertest.cc index e35ece8..0e26372 100644 --- a/chrome/browser/chromeos/login/signin/device_id_browsertest.cc +++ b/chrome/browser/chromeos/login/signin/device_id_browsertest.cc
@@ -167,8 +167,9 @@ dictionary.SetStringWithoutPathExpansion(kv.first, kv.second); std::string json; EXPECT_TRUE(base::JSONWriter::Write(dictionary, &json)); - EXPECT_TRUE(base::WriteFile(GetRefreshTokenToDeviceIdMapFilePath(), - json.c_str(), json.length())); + EXPECT_EQ(static_cast<int>(json.length()), + base::WriteFile(GetRefreshTokenToDeviceIdMapFilePath(), + json.c_str(), json.length())); } std::unique_ptr<base::RunLoop> user_removal_loop_;
diff --git a/chrome/browser/chromeos/policy/user_cloud_policy_manager_chromeos.cc b/chrome/browser/chromeos/policy/user_cloud_policy_manager_chromeos.cc index 8c16357..576de47 100644 --- a/chrome/browser/chromeos/policy/user_cloud_policy_manager_chromeos.cc +++ b/chrome/browser/chromeos/policy/user_cloud_policy_manager_chromeos.cc
@@ -103,14 +103,16 @@ policy_fetch_timeout_(false, false) { time_init_started_ = base::Time::Now(); - // Caller should pass a non-zero policy_fetch_timeout iff + // Caller must pass a non-zero policy_fetch_timeout iff // |wait_for_policy_fetch| is true. DCHECK_NE(wait_for_policy_fetch_, initial_policy_fetch_timeout.is_zero()); allow_failed_policy_fetches_ = base::CommandLine::ForCurrentProcess()->HasSwitch( chromeos::switches::kAllowFailedPolicyFetchForTest) || !initial_policy_fetch_timeout.is_max(); - if (wait_for_policy_fetch_ && allow_failed_policy_fetches_) { + // No need to set the timer when the timeout is infinite. + if (wait_for_policy_fetch_ && allow_failed_policy_fetches_ && + !initial_policy_fetch_timeout.is_max()) { policy_fetch_timeout_.Start( FROM_HERE, initial_policy_fetch_timeout,
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 e031a8d..3ebd5f3 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
@@ -127,8 +127,9 @@ void StoreUserPolicyKey(const std::string& public_key) { ASSERT_TRUE(base::CreateDirectory(user_policy_key_file().DirName())); - ASSERT_TRUE(base::WriteFile(user_policy_key_file(), public_key.data(), - public_key.size())); + ASSERT_EQ(static_cast<int>(public_key.size()), + base::WriteFile(user_policy_key_file(), public_key.data(), + public_key.size())); } // Stores the current |policy_| and verifies that it is published.
diff --git a/chrome/browser/chromeos/printer_detector/cups_printer_detector.cc b/chrome/browser/chromeos/printer_detector/cups_printer_detector.cc index 05369a7..a8b1e8f 100644 --- a/chrome/browser/chromeos/printer_detector/cups_printer_detector.cc +++ b/chrome/browser/chromeos/printer_detector/cups_printer_detector.cc
@@ -12,8 +12,11 @@ #include "base/bind_helpers.h" #include "base/macros.h" #include "base/memory/ptr_util.h" +#include "base/observer_list_threadsafe.h" #include "base/scoped_observer.h" #include "base/strings/utf_string_conversions.h" +#include "base/synchronization/lock.h" +#include "base/threading/sequenced_task_runner_handle.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/chromeos/printer_detector/printer_detector.h" #include "chrome/browser/chromeos/printing/ppd_provider_factory.h" @@ -72,18 +75,48 @@ public device::UsbService::Observer { public: explicit CupsPrinterDetectorImpl(Profile* profile) - : profile_(profile), observer_(this), weak_ptr_factory_(this) { + : profile_(profile), + usb_observer_(this), + observer_list_( + new base::ObserverListThreadSafe<PrinterDetector::Observer>), + weak_ptr_factory_(this) { device::UsbService* usb_service = device::DeviceClient::Get()->GetUsbService(); if (usb_service) { - observer_.Add(usb_service); + usb_observer_.Add(usb_service); usb_service->GetDevices(base::Bind(&CupsPrinterDetectorImpl::OnGetDevices, weak_ptr_factory_.GetWeakPtr())); } } ~CupsPrinterDetectorImpl() override = default; + // PrinterDetector interface function. + void AddObserver(PrinterDetector::Observer* observer) override { + observer_list_->AddObserver(observer); + } + + // PrinterDetector interface function. + void RemoveObserver(PrinterDetector::Observer* observer) override { + observer_list_->RemoveObserver(observer); + } + + // PrinterDetector interface function. + std::vector<Printer> GetPrinters() override { + base::AutoLock auto_lock(pp_lock_); + return GetPrintersLocked(); + } + private: + std::vector<Printer> GetPrintersLocked() { + pp_lock_.AssertAcquired(); + std::vector<Printer> printers; + printers.reserve(present_printers_.size()); + for (const auto& entry : present_printers_) { + printers.push_back(*entry.second); + } + return printers; + } + // Callback for initial enumeration of usb devices. void OnGetDevices( const std::vector<scoped_refptr<device::UsbDevice>>& devices) { @@ -105,24 +138,21 @@ if (!UsbDeviceIsPrinter(*device)) { return; } - known_printers_.erase(device->guid()); - // TODO(justincarlson): Update failed printers. - } - // Returns the existing printer using this URI, if one exists, or - // null otherwise. - std::unique_ptr<Printer> FindExistingPrinter(const std::string& uri) { - // TODO(justincarlson): add a GetPrinterByURI to PrintersManager. - // https://crbug.com/700602 - auto existing_printers = - PrintersManagerFactory::GetForBrowserContext(profile_)->GetPrinters(); - for (std::unique_ptr<Printer>& printer : existing_printers) { - if (printer->uri() == uri) { - // Found a match, so use the existing configuration. - return std::move(printer); - } + base::AutoLock auto_lock(pp_lock_); + if (base::ContainsKey(present_printers_, device->guid())) { + present_printers_.erase(device->guid()); + auto printers = GetPrintersLocked(); + // We already have pp_lock_, so need to call the pre-locked version of + // GetPrinters to prevent deadlock. + observer_list_->Notify( + FROM_HERE, &PrinterDetector::Observer::OnAvailableUsbPrintersChanged, + GetPrintersLocked()); + } else { + // If the device has been removed but it's not in present_printers_, it + // must still be in the setup flow. + deferred_printer_removals_.insert(device->guid()); } - return nullptr; } // If this device is a printer and we haven't already tried to set it up, @@ -132,20 +162,32 @@ bool hotplugged) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - if (!UsbDeviceIsPrinter(*device) || - base::ContainsKey(known_printers_, device->guid())) { + if (!UsbDeviceIsPrinter(*device)) { return; } - known_printers_.insert(device->guid()); + // If we got this far, we want to try to auto-configure this printer. auto data = base::MakeUnique<SetUpPrinterData>(); data->configurer = PrinterConfigurer::Create(profile_); data->device = device; data->hotplugged = hotplugged; - data->printer = FindExistingPrinter(UsbPrinterUri(*device)); - if (data->printer != nullptr) { + data->printer = UsbDeviceToPrinter(*device); + if (data->printer == nullptr) { + // We've failed to understand this printer device, an error will already + // have been logged, so just bail. + return; + } + + // If the user already has a configuration for this device, substitute that + // one for the one we generated automatically and skip the parts where we + // try to automagically figure out the driver. + std::unique_ptr<Printer> existing_printer_configuration = + PrintersManagerFactory::GetForBrowserContext(profile_)->GetPrinter( + data->printer->id()); + if (existing_printer_configuration != nullptr) { data->is_new = false; + data->printer = std::move(existing_printer_configuration); OnPrinterResolved(std::move(data)); return; } @@ -155,10 +197,6 @@ // TODO(justincarlson): Add a notification that we are attempting to set up // this printer at this point. data->is_new = true; - data->printer = UsbDeviceToPrinter(*device); - if (data->printer == nullptr) { - return; - } // Look for an exact match based on USB ids. scoped_refptr<PpdProvider> ppd_provider = @@ -214,18 +252,30 @@ DCHECK_CURRENTLY_ON(content::BrowserThread::UI); if (result == PrinterSetupResult::SUCCESS) { if (data->is_new) { + // We aren't done with data->printer yet, so we have to copy it instead + // of moving it. + auto printer_copy = base::MakeUnique<Printer>(*data->printer); PrintersManagerFactory::GetForBrowserContext(profile_)->RegisterPrinter( - std::move(data->printer)); + std::move(printer_copy)); } // TODO(justincarlson): If the device was hotplugged, pop a timed // notification that says the printer is now available for printing. } - // TODO(justincarlson): If this doesn't succeed, Pop a notification that + // TODO(justincarlson): If this doesn't succeed, pop a notification that // tells the user automatic setup failed and offers to open the CUPS printer // configuration settings. - // - // TODO(justincarlson): If this doesn't succeed, Update the list of printers - // that failed to set up. + + if (base::ContainsKey(deferred_printer_removals_, data->device->guid())) { + // The device was removed before we finished the flow, so just don't add + // it to present_printers_; + deferred_printer_removals_.erase(data->device->guid()); + } else { + base::AutoLock auto_lock(pp_lock_); + present_printers_.emplace(data->device->guid(), std::move(data->printer)); + observer_list_->Notify( + FROM_HERE, &PrinterDetector::Observer::OnAvailableUsbPrintersChanged, + GetPrintersLocked()); + } } void SetNotificationUIManagerForTesting( @@ -233,19 +283,33 @@ LOG(FATAL) << "Not implemented for CUPS"; } - // USB GUIDs of printers we've already dealt with. There's an inherent race - // between initially querying all usb devices and receiving a notification - // about a new device, so this set lets us guarantee that we handle a given - // printer exactly once. - std::set<std::string> known_printers_; + // Map from USB GUID to Printer that we have detected as being currently + // plugged in and have finished processing. Note present_printers_ may be + // accessed from multiple threads, so is protected by pp_lock_. + std::map<std::string, std::unique_ptr<Printer>> present_printers_; + base::Lock pp_lock_; + + // If the usb device is removed before we've finished processing it, we'll + // defer the cleanup until the setup flow finishes. This is the set of + // guids which have been removed before the flow finished. + std::set<std::string> deferred_printer_removals_; Profile* profile_; - ScopedObserver<device::UsbService, device::UsbService::Observer> observer_; + ScopedObserver<device::UsbService, device::UsbService::Observer> + usb_observer_; + scoped_refptr<base::ObserverListThreadSafe<PrinterDetector::Observer>> + observer_list_; base::WeakPtrFactory<CupsPrinterDetectorImpl> weak_ptr_factory_; }; } // namespace +// Nop base class implementation of GetPrinters(). Because this is non-empty we +// have to define it out-of-line. +std::vector<Printer> PrinterDetector::GetPrinters() { + return std::vector<Printer>(); +} + // static std::unique_ptr<PrinterDetector> PrinterDetector::CreateCups(Profile* profile) { return base::MakeUnique<CupsPrinterDetectorImpl>(profile);
diff --git a/chrome/browser/chromeos/printer_detector/printer_detector.h b/chrome/browser/chromeos/printer_detector/printer_detector.h index e7a5b3d5..1789377 100644 --- a/chrome/browser/chromeos/printer_detector/printer_detector.h +++ b/chrome/browser/chromeos/printer_detector/printer_detector.h
@@ -7,8 +7,10 @@ #include <memory> #include <string> +#include <vector> #include "base/macros.h" +#include "chromeos/printing/printer_configuration.h" #include "components/keyed_service/core/keyed_service.h" class NotificationUIManager; @@ -34,6 +36,15 @@ // CUPS backend. class PrinterDetector : public KeyedService { public: + class Observer { + public: + virtual ~Observer() = default; + + // The set of available printers has changed. + virtual void OnAvailableUsbPrintersChanged( + const std::vector<Printer>& printers) = 0; + }; + // Factory function for the Legacy implementation. static std::unique_ptr<PrinterDetector> CreateLegacy(Profile* profile); @@ -41,6 +52,16 @@ static std::unique_ptr<PrinterDetector> CreateCups(Profile* profile); ~PrinterDetector() override {} + // Observer management. Note these are only implemented for the cups backend. + // TODO(justincarlson) - Change these all to pure virtual functions when the + // legacy backend is retired. + + virtual void AddObserver(Observer* observer) {} + virtual void RemoveObserver(Observer* observer) {} + + // Get the current set of detected printers. + virtual std::vector<Printer> GetPrinters(); + protected: PrinterDetector() = default;
diff --git a/chrome/browser/chromeos/printing/fake_printer_discoverer.cc b/chrome/browser/chromeos/printing/fake_printer_discoverer.cc deleted file mode 100644 index a3b57e9..0000000 --- a/chrome/browser/chromeos/printing/fake_printer_discoverer.cc +++ /dev/null
@@ -1,107 +0,0 @@ -// Copyright 2016 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/chromeos/printing/fake_printer_discoverer.h" - -#include <algorithm> -#include <iterator> -#include <memory> - -#include "base/bind.h" -#include "base/memory/ptr_util.h" -#include "base/strings/stringprintf.h" -#include "base/threading/sequenced_task_runner_handle.h" -#include "base/time/time.h" -#include "chrome/browser/chromeos/printing/printer_discoverer.h" - -namespace chromeos { - -// static -std::unique_ptr<PrinterDiscoverer> PrinterDiscoverer::Create() { - return base::MakeUnique<FakePrinterDiscoverer>(); -} - -FakePrinterDiscoverer::~FakePrinterDiscoverer() {} - -bool FakePrinterDiscoverer::StartDiscovery() { - discovery_running_ = true; - - for (auto* observer : observers_) - observer->OnDiscoveryStarted(); - - base::SequencedTaskRunnerHandle::Get()->PostNonNestableDelayedTask( - FROM_HERE, base::Bind(&FakePrinterDiscoverer::EmitPrinters, - weak_ptr_factory_.GetWeakPtr(), 0, 2), - base::TimeDelta::FromMilliseconds(2000)); - return true; -} - -bool FakePrinterDiscoverer::StopDiscovery() { - discovery_running_ = false; - for (auto* observer : observers_) - observer->OnDiscoveryStopping(); - - return true; -} - -void FakePrinterDiscoverer::AddObserver(PrinterDiscoverer::Observer* observer) { - auto found = std::find(observers_.begin(), observers_.end(), observer); - if (found == observers_.end()) - observers_.push_back(observer); -} - -void FakePrinterDiscoverer::RemoveObserver( - PrinterDiscoverer::Observer* observer) { - auto found = std::find(observers_.begin(), observers_.end(), observer); - if (found != observers_.end()) - observers_.erase(found); -} - -FakePrinterDiscoverer::FakePrinterDiscoverer() - : discovery_running_(false), weak_ptr_factory_(this) { - for (int i = 0; i < 12; i++) { - // printer doesn't have a ppd - printers_.emplace_back(base::StringPrintf("GUID%2d", i)); - printers_[i].set_display_name(base::StringPrintf("PrinterName%2d", i)); - printers_[i].set_description( - base::StringPrintf("Printer%2dDescription", i)); - printers_[i].set_manufacturer("Chromium"); - printers_[i].set_model(i % 3 == 0 ? "Inkjet" : "Laser Maker"); - printers_[i].set_uri( - base::StringPrintf("lpd://192.168.1.%d:9100/bldg/printer", i)); - printers_[i].set_uuid( - base::StringPrintf("UUID-%4d-%4d-%4d-UUID", i * 3, i * 2, i)); - } -} - -void FakePrinterDiscoverer::EmitPrinters(size_t start, size_t end) { - if (!discovery_running_ || start >= printers_.size() || end < start) - return; - - size_t clipped_start = std::max(static_cast<size_t>(0), start); - size_t clipped_end = std::min(printers_.size(), end); - if (!observers_.empty()) { - std::vector<Printer> subset(printers_.cbegin() + clipped_start, - printers_.cbegin() + clipped_end); - - for (auto* observer : observers_) - observer->OnPrintersFound(subset); - } - - // schedule another emit if elements remain. - if (end < printers_.size()) { - base::SequencedTaskRunnerHandle::Get()->PostNonNestableDelayedTask( - FROM_HERE, - base::Bind(&FakePrinterDiscoverer::EmitPrinters, - weak_ptr_factory_.GetWeakPtr(), clipped_end, end + end), - base::TimeDelta::FromMilliseconds(2000)); - } else { - // We're done. Notify observers. - discovery_running_ = false; - for (auto* observer : observers_) - observer->OnDiscoveryDone(); - } -} - -} // namespace chromeos
diff --git a/chrome/browser/chromeos/printing/fake_printer_discoverer.h b/chrome/browser/chromeos/printing/fake_printer_discoverer.h deleted file mode 100644 index d7f857e..0000000 --- a/chrome/browser/chromeos/printing/fake_printer_discoverer.h +++ /dev/null
@@ -1,41 +0,0 @@ -// Copyright 2016 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROME_BROWSER_CHROMEOS_PRINTING_FAKE_PRINTER_DISCOVERER_H_ -#define CHROME_BROWSER_CHROMEOS_PRINTING_FAKE_PRINTER_DISCOVERER_H_ - -#include <vector> - -#include "base/macros.h" -#include "base/memory/weak_ptr.h" -#include "chrome/browser/chromeos/printing/printer_discoverer.h" -#include "chromeos/printing/printer_configuration.h" - -namespace chromeos { - -class FakePrinterDiscoverer : public PrinterDiscoverer { - public: - FakePrinterDiscoverer(); - ~FakePrinterDiscoverer() override; - - bool StartDiscovery() override; - bool StopDiscovery() override; - void AddObserver(PrinterDiscoverer::Observer* observer) override; - void RemoveObserver(PrinterDiscoverer::Observer* observer) override; - - private: - void EmitPrinters(size_t start, size_t end); - - std::vector<chromeos::Printer> printers_; - bool discovery_running_; - std::vector<PrinterDiscoverer::Observer*> observers_; - - base::WeakPtrFactory<FakePrinterDiscoverer> weak_ptr_factory_; - - DISALLOW_COPY_AND_ASSIGN(FakePrinterDiscoverer); -}; - -} // namespace chromeos - -#endif // CHROME_BROWSER_CHROMEOS_PRINTING_FAKE_PRINTER_DISCOVERER_H_
diff --git a/chrome/browser/chromeos/printing/printer_discoverer.cc b/chrome/browser/chromeos/printing/printer_discoverer.cc new file mode 100644 index 0000000..e6f9159 --- /dev/null +++ b/chrome/browser/chromeos/printing/printer_discoverer.cc
@@ -0,0 +1,119 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/chromeos/printing/printer_discoverer.h" + +#include "base/bind.h" +#include "base/memory/ptr_util.h" +#include "base/memory/weak_ptr.h" +#include "base/observer_list.h" +#include "base/scoped_observer.h" +#include "base/threading/sequenced_task_runner_handle.h" +#include "chrome/browser/chromeos/printer_detector/printer_detector.h" +#include "chrome/browser/chromeos/printer_detector/printer_detector_factory.h" +#include "chrome/browser/chromeos/printing/printers_manager.h" +#include "chrome/browser/chromeos/printing/printers_manager_factory.h" +#include "chrome/browser/profiles/profile.h" +#include "chromeos/printing/printer_configuration.h" + +namespace chromeos { +namespace { + +// Implementation of PrinterDiscoverer interface. +class PrinterDiscovererImpl : public PrinterDiscoverer, + public PrinterDetector::Observer { + public: + explicit PrinterDiscovererImpl(Profile* profile) + : detector_observer_(this), profile_(profile), weak_ptr_factory_(this) { + PrinterDetector* detector = + PrinterDetectorFactory::GetInstance()->Get(profile); + DCHECK(detector); + detector_observer_.Add(detector); + usb_printers_ = detector->GetPrinters(); + } + ~PrinterDiscovererImpl() override = default; + + // PrinterDiscoverer interface function. + void AddObserver(PrinterDiscoverer::Observer* observer) override { + observer_list_.AddObserver(observer); + // WrappedOnPrintersFound is a simple wrapper around + // Observer::OnPrintersFound which lets us safely do the initial + // OnPrintersFound call to the registered observer. This wrapper buys us + // weak_ptr semantics on 'this', and also guards against removal of the + // observer from the Discoverer before this callback is issued. + base::SequencedTaskRunnerHandle::Get()->PostTask( + FROM_HERE, base::Bind(&PrinterDiscovererImpl::WrappedOnPrintersFound, + weak_ptr_factory_.GetWeakPtr(), observer, + GetAvailablePrinters())); + } + + // PrinterDiscoverer interface function. + void RemoveObserver(PrinterDiscoverer::Observer* observer) override { + observer_list_.RemoveObserver(observer); + } + + // PrinterDetector::Observer interface function. + void OnAvailableUsbPrintersChanged( + const std::vector<Printer>& printers) override { + usb_printers_ = printers; + std::vector<Printer> all_printers = GetAvailablePrinters(); + for (PrinterDiscoverer::Observer& observer : observer_list_) { + observer.OnPrintersFound(all_printers); + } + } + + private: + // Wrapper for doing the initial OnPrintersFound call on an observer of this + // object. + void WrappedOnPrintersFound(PrinterDiscoverer::Observer* observer, + const std::vector<Printer>& printers) { + if (observer_list_.HasObserver(observer)) { + observer->OnPrintersFound(printers); + // Since USB is the only thing we're worried about at the moment, and we + // don't have to wait for those printers to be scanned, we can just tell + // the observer the initial scan is done now. This will change when we're + // also doing network discovery -- we'll hold off on issuing this callback + // until the network discovery is done as well. + observer->OnDiscoveryInitialScanDone(); + } + } + + // Get the current set of discovered printers that are not already known + // to the user's PrintersManager. + std::vector<Printer> GetAvailablePrinters() { + // Only know about usb printers for now. Eventually we'll add discovered + // network printers as well. + std::vector<Printer> ret; + PrintersManager* printers_manager = + PrintersManagerFactory::GetForBrowserContext(profile_); + if (!printers_manager) { + LOG(WARNING) << "Failing to get available printers because no " + "PrintersManager exists."; + return ret; + } + + for (const Printer& printer : usb_printers_) { + if (printers_manager->GetPrinter(printer.id()).get() == nullptr) { + ret.push_back(printer); + } + } + return ret; + } + + std::vector<Printer> usb_printers_; + base::ObserverList<PrinterDiscoverer::Observer> observer_list_; + ScopedObserver<PrinterDetector, PrinterDetector::Observer> detector_observer_; + Profile* profile_; + base::WeakPtrFactory<PrinterDiscovererImpl> weak_ptr_factory_; +}; + +} // namespace + +// static +std::unique_ptr<PrinterDiscoverer> PrinterDiscoverer::CreateForProfile( + Profile* profile) { + return base::MakeUnique<PrinterDiscovererImpl>(profile); +} + +} // namespace chromeos
diff --git a/chrome/browser/chromeos/printing/printer_discoverer.h b/chrome/browser/chromeos/printing/printer_discoverer.h index b0a8639..20fd8bc 100644 --- a/chrome/browser/chromeos/printing/printer_discoverer.h +++ b/chrome/browser/chromeos/printing/printer_discoverer.h
@@ -10,50 +10,45 @@ #include "chromeos/printing/printer_configuration.h" +class Profile; + namespace chromeos { // Interface for printer discovery. Constructs Printer objects from USB and -// zeroconf (DNS-SD) printers. +// zeroconf (DNS-SD) printers. All functions in this class must be called +// from a sequenced context. class CHROMEOS_EXPORT PrinterDiscoverer { public: // Interface for objects interested in detected printers. class Observer { public: - // Called after discovery has started. - virtual void OnDiscoveryStarted() {} + virtual ~Observer() = default; - // Called when discovery is stopping. OnPrintersFound will not be - // called after this occurs. - virtual void OnDiscoveryStopping() {} + // Called when we are done with the initial scan for printers. We may + // still call OnPrintersFound if the set of available printers + // changes, but the user can conclude that if a printer is currently + // available and not in the list, we're not still looking for it. + virtual void OnDiscoveryInitialScanDone() = 0; - // Called after all printers have been discovered and the observers - // notified. - virtual void OnDiscoveryDone() {} - - // Called with a collection of printers as they are discovered. Printer - // objects must be copied if they are retained outside of the scope of this - // function. - virtual void OnPrintersFound(const std::vector<Printer>& printers) {} + // Called with a collection of printers as they are discovered. On each + // call |printers| is the full set of known printers; it is not + // incremental; printers may be added or removed. + // + // Observers will get an OnPrintersFound callback after registration + // with the existing list of printers (which may be empty) and will get + // additional calls whenever the set of printers changes. + virtual void OnPrintersFound(const std::vector<Printer>& printers) = 0; }; // Static factory - static std::unique_ptr<PrinterDiscoverer> Create(); + static std::unique_ptr<PrinterDiscoverer> CreateForProfile(Profile* profile); - virtual ~PrinterDiscoverer() {} - - // Begin scanning for printers. Found printers will be reported to the - // attached observer. - virtual bool StartDiscovery() = 0; - - // Stop scanning for printers. Returns false if scanning could not be stopped - // and new results will continue to be be sent to observers. Returns true if - // scanning was stopped successfully. No calls to the attached observer will - // be made after this returns if it returned true. - virtual bool StopDiscovery() = 0; + virtual ~PrinterDiscoverer() = default; // Add an observer that will be notified of discovered printers. Ownership of // |observer| is not taken by the discoverer. It is an error to add an - // oberserver more than once. + // observer more than once. Calls to |observer| methods will take place on + // the thread PrinterDiscoverer was instantiated on. virtual void AddObserver(PrinterDiscoverer::Observer* observer) = 0; // Remove an observer of printer discovery.
diff --git a/chrome/browser/chromeos/printing/printers_manager.h b/chrome/browser/chromeos/printing/printers_manager.h index 04eb0dda..f31bd6c7d 100644 --- a/chrome/browser/chromeos/printing/printers_manager.h +++ b/chrome/browser/chromeos/printing/printers_manager.h
@@ -51,7 +51,8 @@ // Returns printers from enterprise policy. std::vector<std::unique_ptr<Printer>> GetRecommendedPrinters() const; - // Returns the printer with id |printer_id|. + // Returns the printer with id |printer_id|, or nullptr if no such + // printer exists. std::unique_ptr<Printer> GetPrinter(const std::string& printer_id) const; // Adds or updates a printer. Printers are identified by the id field. Use an
diff --git a/chrome/browser/chromeos/system/automatic_reboot_manager_unittest.cc b/chrome/browser/chromeos/system/automatic_reboot_manager_unittest.cc index 33070ea..837d283 100644 --- a/chrome/browser/chromeos/system/automatic_reboot_manager_unittest.cc +++ b/chrome/browser/chromeos/system/automatic_reboot_manager_unittest.cc
@@ -319,10 +319,10 @@ const base::FilePath& temp_dir = temp_dir_.GetPath(); const base::FilePath uptime_file = temp_dir.Append("uptime"); uptime_provider()->set_uptime_file_path(uptime_file); - ASSERT_FALSE(base::WriteFile(uptime_file, NULL, 0)); + ASSERT_EQ(0, base::WriteFile(uptime_file, NULL, 0)); update_reboot_needed_uptime_file_ = temp_dir.Append("update_reboot_needed_uptime"); - ASSERT_FALSE(base::WriteFile(update_reboot_needed_uptime_file_, NULL, 0)); + ASSERT_EQ(0, base::WriteFile(update_reboot_needed_uptime_file_, NULL, 0)); ASSERT_TRUE(PathService::Override(chromeos::FILE_UPTIME, uptime_file)); ASSERT_TRUE(PathService::Override(chromeos::FILE_UPDATE_REBOOT_NEEDED_UPTIME, update_reboot_needed_uptime_file_));
diff --git a/chrome/browser/engagement/BUILD.gn b/chrome/browser/engagement/BUILD.gn index d0da319..4315a90 100644 --- a/chrome/browser/engagement/BUILD.gn +++ b/chrome/browser/engagement/BUILD.gn
@@ -6,7 +6,7 @@ mojom("mojo_bindings") { sources = [ - "site_engagement.mojom", + "site_engagement_details.mojom", ] public_deps = [
diff --git a/chrome/browser/engagement/important_sites_util.cc b/chrome/browser/engagement/important_sites_util.cc index 96b8b01..d0280d5 100644 --- a/chrome/browser/engagement/important_sites_util.cc +++ b/chrome/browser/engagement/important_sites_util.cc
@@ -308,13 +308,19 @@ entry.url.GetOrigin(), blink::mojom::EngagementLevel::LOW); }); - std::sort(result_bookmarks.begin(), result_bookmarks.end(), - [&engagement_map](const BookmarkModel::URLAndTitle& a, - const BookmarkModel::URLAndTitle& b) { - double a_score = engagement_map.at(a.url.GetOrigin()); - double b_score = engagement_map.at(b.url.GetOrigin()); - return a_score > b_score; - }); + // TODO(dmurph): Simplify this (and probably much more) once + // SiteEngagementService::GetAllDetails lands (crbug/703848), as that will + // allow us to remove most of these lookups and merging of signals. + std::sort( + result_bookmarks.begin(), result_bookmarks.end(), + [&engagement_map](const BookmarkModel::URLAndTitle& a, + const BookmarkModel::URLAndTitle& b) { + auto a_it = engagement_map.find(a.url.GetOrigin()); + auto b_it = engagement_map.find(b.url.GetOrigin()); + double a_score = a_it == engagement_map.end() ? 0 : a_it->second; + double b_score = b_it == engagement_map.end() ? 0 : b_it->second; + return a_score > b_score; + }); if (result_bookmarks.size() > kMaxBookmarks) result_bookmarks.resize(kMaxBookmarks); } else {
diff --git a/chrome/browser/engagement/site_engagement.mojom b/chrome/browser/engagement/site_engagement.mojom deleted file mode 100644 index a1ccb2ef..0000000 --- a/chrome/browser/engagement/site_engagement.mojom +++ /dev/null
@@ -1,17 +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. - -module mojom; - -import "url/mojo/url.mojom"; - -struct SiteEngagementInfo { - url.mojom.Url origin; - double score; -}; - -interface SiteEngagementUIHandler { - GetSiteEngagementInfo() => (array<SiteEngagementInfo> info); - SetSiteEngagementScoreForOrigin(url.mojom.Url origin, double score); -};
diff --git a/chrome/browser/engagement/site_engagement_details.mojom b/chrome/browser/engagement/site_engagement_details.mojom new file mode 100644 index 0000000..cf49499 --- /dev/null +++ b/chrome/browser/engagement/site_engagement_details.mojom
@@ -0,0 +1,23 @@ +// 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. + +module mojom; + +import "url/mojo/url.mojom"; + +struct SiteEngagementDetails { + url.mojom.Url origin; + double total_score; + + // Details of the components which make up |score|. Note that these may + // sum to a value greater than |score| if it exceeds the maximum. + double base_score; + double installed_bonus; + double notifications_bonus; +}; + +interface SiteEngagementDetailsProvider { + GetSiteEngagementDetails() => (array<SiteEngagementDetails> info); + SetSiteEngagementBaseScoreForUrl(url.mojom.Url url, double score); +};
diff --git a/chrome/browser/engagement/site_engagement_score.cc b/chrome/browser/engagement/site_engagement_score.cc index 10fe452..cfedbf3 100644 --- a/chrome/browser/engagement/site_engagement_score.cc +++ b/chrome/browser/engagement/site_engagement_score.cc
@@ -46,7 +46,7 @@ std::unique_ptr<base::DictionaryValue> value = base::DictionaryValue::From(settings->GetWebsiteSetting( origin_url, origin_url, CONTENT_SETTINGS_TYPE_SITE_ENGAGEMENT, - std::string(), NULL)); + content_settings::ResourceIdentifier(), NULL)); if (value.get()) return value; @@ -270,8 +270,20 @@ last_engagement_time_ = now; } -double SiteEngagementScore::GetScore() const { - return std::min(DecayedScore() + BonusScore(), kMaxPoints); +double SiteEngagementScore::GetTotalScore() const { + return std::min( + DecayedScore() + BonusIfShortcutLaunched() + BonusIfHasNotifications(), + kMaxPoints); +} + +mojom::SiteEngagementDetails SiteEngagementScore::GetDetails() const { + mojom::SiteEngagementDetails engagement; + engagement.origin = origin_; + engagement.base_score = DecayedScore(); + engagement.installed_bonus = BonusIfShortcutLaunched(); + engagement.notifications_bonus = BonusIfHasNotifications(); + engagement.total_score = GetTotalScore(); + return engagement; } void SiteEngagementScore::Commit() { @@ -280,14 +292,14 @@ return; settings_map_->SetWebsiteSettingDefaultScope( - origin_, GURL(), CONTENT_SETTINGS_TYPE_SITE_ENGAGEMENT, std::string(), - std::move(score_dict_)); + origin_, GURL(), CONTENT_SETTINGS_TYPE_SITE_ENGAGEMENT, + content_settings::ResourceIdentifier(), std::move(score_dict_)); } blink::mojom::EngagementLevel SiteEngagementScore::GetEngagementLevel() const { DCHECK_LT(GetMediumEngagementBoundary(), GetHighEngagementBoundary()); - double score = GetScore(); + double score = GetTotalScore(); if (score == 0) return blink::mojom::EngagementLevel::NONE; @@ -400,20 +412,23 @@ periods * GetDecayPoints()); } -double SiteEngagementScore::BonusScore() const { - double bonus = 0; +double SiteEngagementScore::BonusIfShortcutLaunched() const { int days_since_shortcut_launch = (clock_->Now() - last_shortcut_launch_time_).InDays(); if (days_since_shortcut_launch <= kMaxDaysSinceShortcutLaunch) - bonus += GetWebAppInstalledPoints(); + return GetWebAppInstalledPoints(); + return 0; +} +double SiteEngagementScore::BonusIfHasNotifications() const { // TODO(dominickn, raymes): call PermissionManager::GetPermissionStatus when // the PermissionManager is thread-safe. - if (settings_map_ && settings_map_->GetContentSetting( - origin_, GURL(), CONTENT_SETTINGS_TYPE_NOTIFICATIONS, - std::string()) == CONTENT_SETTING_ALLOW) { - bonus += GetNotificationPermissionPoints(); + if (settings_map_ && + settings_map_->GetContentSetting( + origin_, GURL(), CONTENT_SETTINGS_TYPE_NOTIFICATIONS, + content_settings::ResourceIdentifier()) == CONTENT_SETTING_ALLOW) { + return GetNotificationPermissionPoints(); } - return bonus; + return 0; }
diff --git a/chrome/browser/engagement/site_engagement_score.h b/chrome/browser/engagement/site_engagement_score.h index 358f97d..517520a 100644 --- a/chrome/browser/engagement/site_engagement_score.h +++ b/chrome/browser/engagement/site_engagement_score.h
@@ -12,6 +12,7 @@ #include "base/macros.h" #include "base/time/time.h" #include "base/values.h" +#include "chrome/browser/engagement/site_engagement_details.mojom.h" #include "third_party/WebKit/public/platform/site_engagement.mojom.h" #include "url/gurl.h" @@ -137,7 +138,15 @@ // possible score. Decays the score if it has not been updated recently // enough. void AddPoints(double points); - double GetScore() const; + + // Returns the total score, taking into account the base, bonus and maximum + // values. + double GetTotalScore() const; + + // Returns a structure containing the origin URL and score, and details + // of the base and bonus scores. Note that the |score| is limited to + // kMaxPoints, while the detailed scores are returned raw. + mojom::SiteEngagementDetails GetDetails() const; // Writes the values in this score into |settings_map_|. void Commit(); @@ -196,8 +205,11 @@ // Determine the score, accounting for any decay. double DecayedScore() const; - // Determine any score bonus from having installed shortcuts. - double BonusScore() const; + // Determine bonus from being installed, and having been launched recently.. + double BonusIfShortcutLaunched() const; + + // Determine bonus from having been granted notifications permission. + double BonusIfHasNotifications() const; // Updates the content settings dictionary |score_dict| with the current score // fields. Returns true if |score_dict| changed, otherwise return false.
diff --git a/chrome/browser/engagement/site_engagement_score_unittest.cc b/chrome/browser/engagement/site_engagement_score_unittest.cc index 51e3225..96268a2 100644 --- a/chrome/browser/engagement/site_engagement_score_unittest.cc +++ b/chrome/browser/engagement/site_engagement_score_unittest.cc
@@ -9,7 +9,12 @@ #include "base/macros.h" #include "base/test/simple_test_clock.h" #include "base/values.h" +#include "chrome/browser/content_settings/host_content_settings_map_factory.h" #include "chrome/browser/engagement/site_engagement_service.h" +#include "chrome/browser/profiles/profile.h" +#include "chrome/test/base/chrome_render_view_host_test_harness.h" +#include "chrome/test/base/testing_profile.h" +#include "components/content_settings/core/browser/host_content_settings_map.h" #include "testing/gtest/include/gtest/gtest.h" namespace { @@ -42,12 +47,12 @@ } // namespace -class SiteEngagementScoreTest : public testing::Test { +class SiteEngagementScoreTest : public ChromeRenderViewHostTestHarness { public: SiteEngagementScoreTest() : score_(&test_clock_, GURL(), nullptr) {} void SetUp() override { - testing::Test::SetUp(); + ChromeRenderViewHostTestHarness::SetUp(); // Disable the first engagement bonus for tests. SiteEngagementScore::SetParamValuesForTesting(); } @@ -114,10 +119,10 @@ score_.AddPoints(SiteEngagementScore::GetNavigationPoints()); EXPECT_EQ(std::min(SiteEngagementScore::GetMaxPointsPerDay(), (i + 1) * SiteEngagementScore::GetNavigationPoints()), - score_.GetScore()); + score_.GetTotalScore()); } - EXPECT_EQ(SiteEngagementScore::GetMaxPointsPerDay(), score_.GetScore()); + EXPECT_EQ(SiteEngagementScore::GetMaxPointsPerDay(), score_.GetTotalScore()); } // Accumulate on the first day to max that day's engagement, then accumulate on @@ -130,7 +135,7 @@ for (int i = 0; i < kMoreAccumulationsThanNeededToMaxDailyEngagement; ++i) score_.AddPoints(SiteEngagementScore::GetNavigationPoints()); - EXPECT_EQ(SiteEngagementScore::GetMaxPointsPerDay(), score_.GetScore()); + EXPECT_EQ(SiteEngagementScore::GetMaxPointsPerDay(), score_.GetTotalScore()); test_clock_.SetNow(later_date); for (int i = 0; i < kMoreAccumulationsThanNeededToMaxDailyEngagement; ++i) { @@ -139,10 +144,11 @@ std::min(SiteEngagementScore::GetMaxPointsPerDay(), (i + 1) * SiteEngagementScore::GetNavigationPoints()); EXPECT_EQ(day_score + SiteEngagementScore::GetMaxPointsPerDay(), - score_.GetScore()); + score_.GetTotalScore()); } - EXPECT_EQ(2 * SiteEngagementScore::GetMaxPointsPerDay(), score_.GetScore()); + EXPECT_EQ(2 * SiteEngagementScore::GetMaxPointsPerDay(), + score_.GetTotalScore()); } // Accumulate score on many consecutive days and ensure the score doesn't exceed @@ -158,10 +164,10 @@ EXPECT_EQ(std::min(SiteEngagementScore::kMaxPoints, (i + 1) * SiteEngagementScore::GetMaxPointsPerDay()), - score_.GetScore()); + score_.GetTotalScore()); } - EXPECT_EQ(SiteEngagementScore::kMaxPoints, score_.GetScore()); + EXPECT_EQ(SiteEngagementScore::kMaxPoints, score_.GetTotalScore()); } // Accumulate a little on many consecutive days and ensure the score doesn't @@ -180,10 +186,10 @@ std::min(SiteEngagementScore::kMaxPoints, (i + 1) * kLessAccumulationsThanNeededToMaxDailyEngagement * SiteEngagementScore::GetNavigationPoints()), - score_.GetScore()); + score_.GetTotalScore()); } - EXPECT_EQ(SiteEngagementScore::kMaxPoints, score_.GetScore()); + EXPECT_EQ(SiteEngagementScore::kMaxPoints, score_.GetTotalScore()); } // Accumulate a bit, then check the score decays properly for a range of times. @@ -199,14 +205,14 @@ score_.AddPoints(SiteEngagementScore::GetNavigationPoints()); } - EXPECT_EQ(SiteEngagementScore::kMaxPoints, score_.GetScore()); + EXPECT_EQ(SiteEngagementScore::kMaxPoints, score_.GetTotalScore()); // The score should not have decayed before the first decay period has // elapsed. test_clock_.SetNow(current_day + base::TimeDelta::FromHours( SiteEngagementScore::GetDecayPeriodInHours() - 1)); - EXPECT_EQ(SiteEngagementScore::kMaxPoints, score_.GetScore()); + EXPECT_EQ(SiteEngagementScore::kMaxPoints, score_.GetTotalScore()); // The score should have decayed by one chunk after one decay period has // elapsed. @@ -215,7 +221,7 @@ base::TimeDelta::FromHours(SiteEngagementScore::GetDecayPeriodInHours())); EXPECT_EQ( SiteEngagementScore::kMaxPoints - SiteEngagementScore::GetDecayPoints(), - score_.GetScore()); + score_.GetTotalScore()); // The score should have decayed by the right number of chunks after a few // decay periods have elapsed. @@ -226,14 +232,14 @@ EXPECT_EQ(SiteEngagementScore::kMaxPoints - kLessPeriodsThanNeededToDecayMaxScore * SiteEngagementScore::GetDecayPoints(), - score_.GetScore()); + score_.GetTotalScore()); // The score should not decay below zero. test_clock_.SetNow( current_day + base::TimeDelta::FromHours(kMorePeriodsThanNeededToDecayMaxScore * SiteEngagementScore::GetDecayPeriodInHours())); - EXPECT_EQ(0, score_.GetScore()); + EXPECT_EQ(0, score_.GetTotalScore()); } // Test that any expected decays are applied before adding points. @@ -251,7 +257,7 @@ double initial_score = kLessDaysThanNeededToMaxTotalEngagement * SiteEngagementScore::GetMaxPointsPerDay(); - EXPECT_EQ(initial_score, score_.GetScore()); + EXPECT_EQ(initial_score, score_.GetTotalScore()); // Go forward a few decay periods. test_clock_.SetNow( @@ -262,12 +268,12 @@ double decayed_score = initial_score - kLessPeriodsThanNeededToDecayMaxScore * SiteEngagementScore::GetDecayPoints(); - EXPECT_EQ(decayed_score, score_.GetScore()); + EXPECT_EQ(decayed_score, score_.GetTotalScore()); // Now add some points. score_.AddPoints(SiteEngagementScore::GetNavigationPoints()); EXPECT_EQ(decayed_score + SiteEngagementScore::GetNavigationPoints(), - score_.GetScore()); + score_.GetTotalScore()); } // Test that going back in time is handled properly. @@ -278,7 +284,7 @@ for (int i = 0; i < kMoreAccumulationsThanNeededToMaxDailyEngagement; ++i) score_.AddPoints(SiteEngagementScore::GetNavigationPoints()); - EXPECT_EQ(SiteEngagementScore::GetMaxPointsPerDay(), score_.GetScore()); + EXPECT_EQ(SiteEngagementScore::GetMaxPointsPerDay(), score_.GetTotalScore()); // Adding to the score on an earlier date should be treated like another day, // and should not cause any decay. @@ -291,10 +297,11 @@ std::min(SiteEngagementScore::GetMaxPointsPerDay(), (i + 1) * SiteEngagementScore::GetNavigationPoints()); EXPECT_EQ(day_score + SiteEngagementScore::GetMaxPointsPerDay(), - score_.GetScore()); + score_.GetTotalScore()); } - EXPECT_EQ(2 * SiteEngagementScore::GetMaxPointsPerDay(), score_.GetScore()); + EXPECT_EQ(2 * SiteEngagementScore::GetMaxPointsPerDay(), + score_.GetTotalScore()); } // Test that scores are read / written correctly from / to empty score @@ -339,32 +346,32 @@ // The first engagement event gets the bonus. score1.AddPoints(0.5); - EXPECT_EQ(1.0, score1.GetScore()); + EXPECT_EQ(1.0, score1.GetTotalScore()); // Subsequent events do not. score1.AddPoints(0.5); - EXPECT_EQ(1.5, score1.GetScore()); + EXPECT_EQ(1.5, score1.GetTotalScore()); // Bonuses are awarded independently between scores. score2.AddPoints(1.0); - EXPECT_EQ(1.5, score2.GetScore()); + EXPECT_EQ(1.5, score2.GetTotalScore()); score2.AddPoints(1.0); - EXPECT_EQ(2.5, score2.GetScore()); + EXPECT_EQ(2.5, score2.GetTotalScore()); test_clock_.SetNow(current_day + base::TimeDelta::FromDays(1)); // The first event for the next day gets the bonus. score1.AddPoints(0.5); - EXPECT_EQ(2.5, score1.GetScore()); + EXPECT_EQ(2.5, score1.GetTotalScore()); // Subsequent events do not. score1.AddPoints(0.5); - EXPECT_EQ(3.0, score1.GetScore()); + EXPECT_EQ(3.0, score1.GetTotalScore()); score2.AddPoints(1.0); - EXPECT_EQ(4.0, score2.GetScore()); + EXPECT_EQ(4.0, score2.GetTotalScore()); score2.AddPoints(1.0); - EXPECT_EQ(5.0, score2.GetScore()); + EXPECT_EQ(5.0, score2.GetTotalScore()); } // Test that resetting a score has the correct properties. @@ -373,26 +380,27 @@ test_clock_.SetNow(current_day); score_.AddPoints(SiteEngagementScore::GetNavigationPoints()); - EXPECT_EQ(SiteEngagementScore::GetNavigationPoints(), score_.GetScore()); + EXPECT_EQ(SiteEngagementScore::GetNavigationPoints(), score_.GetTotalScore()); current_day += base::TimeDelta::FromDays(7); test_clock_.SetNow(current_day); score_.Reset(20.0, current_day); - EXPECT_DOUBLE_EQ(20.0, score_.GetScore()); + EXPECT_DOUBLE_EQ(20.0, score_.GetTotalScore()); EXPECT_DOUBLE_EQ(0, score_.points_added_today_); EXPECT_EQ(current_day, score_.last_engagement_time_); EXPECT_TRUE(score_.last_shortcut_launch_time_.is_null()); // Adding points after the reset should work as normal. score_.AddPoints(5); - EXPECT_EQ(25.0, score_.GetScore()); + EXPECT_EQ(25.0, score_.GetTotalScore()); // The decay should happen one decay period from the current time. test_clock_.SetNow(current_day + base::TimeDelta::FromHours( SiteEngagementScore::GetDecayPeriodInHours() + 1)); - EXPECT_EQ(25.0 - SiteEngagementScore::GetDecayPoints(), score_.GetScore()); + EXPECT_EQ(25.0 - SiteEngagementScore::GetDecayPoints(), + score_.GetTotalScore()); // Ensure that manually setting a time works as expected. score_.AddPoints(5); @@ -400,7 +408,7 @@ base::Time now = test_clock_.Now(); score_.Reset(10.0, now); - EXPECT_DOUBLE_EQ(10.0, score_.GetScore()); + EXPECT_DOUBLE_EQ(10.0, score_.GetTotalScore()); EXPECT_DOUBLE_EQ(0, score_.points_added_today_); EXPECT_EQ(now, score_.last_engagement_time_); EXPECT_TRUE(score_.last_shortcut_launch_time_.is_null()); @@ -413,7 +421,7 @@ score_.Reset(15.0, now); // 5 bonus from the last shortcut launch. - EXPECT_DOUBLE_EQ(20.0, score_.GetScore()); + EXPECT_DOUBLE_EQ(20.0, score_.GetTotalScore()); EXPECT_DOUBLE_EQ(0, score_.points_added_today_); EXPECT_EQ(now, score_.last_engagement_time_); EXPECT_EQ(old_now, score_.last_shortcut_launch_time_); @@ -431,19 +439,60 @@ score_.AddPoints(2.0); current_day += base::TimeDelta::FromDays(7); test_clock_.SetNow(current_day); - EXPECT_DOUBLE_EQ(1.0, score_.GetScore()); + EXPECT_DOUBLE_EQ(1.0, score_.GetTotalScore()); // 3 decay periods, expect the score to be halved 3 times. score_.AddPoints(15.0); current_day += base::TimeDelta::FromDays(21); test_clock_.SetNow(current_day); - EXPECT_DOUBLE_EQ(2.0, score_.GetScore()); + EXPECT_DOUBLE_EQ(2.0, score_.GetTotalScore()); // Ensure point removal happens after proportional decay. score_.AddPoints(4.0); - EXPECT_DOUBLE_EQ(6.0, score_.GetScore()); + EXPECT_DOUBLE_EQ(6.0, score_.GetTotalScore()); SetParamValue(SiteEngagementScore::DECAY_POINTS, 2.0); current_day += base::TimeDelta::FromDays(7); test_clock_.SetNow(current_day); - EXPECT_NEAR(1.0, score_.GetScore(), kMaxRoundingDeviation); + EXPECT_NEAR(1.0, score_.GetTotalScore(), kMaxRoundingDeviation); +} + +// Verify that GetDetails fills out all fields correctly. +TEST_F(SiteEngagementScoreTest, GetDetails) { + // Advance the clock, otherwise Now() is the same as the null Time value. + test_clock_.Advance(base::TimeDelta::FromDays(365)); + + GURL url("http://www.google.com/"); + + // Replace |score_| with one with an actual URL, and with a settings map. + HostContentSettingsMap* settings_map = + HostContentSettingsMapFactory::GetForProfile(profile()); + score_ = SiteEngagementScore(&test_clock_, url, settings_map); + + // Initially all component scores should be zero. + mojom::SiteEngagementDetails details = score_.GetDetails(); + EXPECT_DOUBLE_EQ(0.0, details.total_score); + EXPECT_DOUBLE_EQ(0.0, details.installed_bonus); + EXPECT_DOUBLE_EQ(0.0, details.notifications_bonus); + EXPECT_DOUBLE_EQ(0.0, details.base_score); + EXPECT_EQ(url, details.origin); + + // Add notifications permission and verify that impacts the correct bonus, + // and the total. + settings_map->SetContentSettingDefaultScope( + url, url, CONTENT_SETTINGS_TYPE_NOTIFICATIONS, std::string(), + CONTENT_SETTING_ALLOW); + details = score_.GetDetails(); + EXPECT_DOUBLE_EQ(details.notifications_bonus, details.total_score); + EXPECT_DOUBLE_EQ(0.0, details.installed_bonus); + EXPECT_LT(0.0, details.notifications_bonus); + EXPECT_DOUBLE_EQ(0.0, details.base_score); + + // Simulate the app having been launched. + score_.set_last_shortcut_launch_time(test_clock_.Now()); + details = score_.GetDetails(); + EXPECT_DOUBLE_EQ(details.installed_bonus + details.notifications_bonus, + details.total_score); + EXPECT_LT(0.0, details.installed_bonus); + EXPECT_LT(0.0, details.notifications_bonus); + EXPECT_DOUBLE_EQ(0.0, details.base_score); }
diff --git a/chrome/browser/engagement/site_engagement_service.cc b/chrome/browser/engagement/site_engagement_service.cc index 43b83532..360d90b 100644 --- a/chrome/browser/engagement/site_engagement_service.cc +++ b/chrome/browser/engagement/site_engagement_service.cc
@@ -8,7 +8,6 @@ #include <algorithm> #include <utility> -#include <vector> #include "base/command_line.h" #include "base/memory/ptr_util.h" @@ -52,13 +51,36 @@ // Length of time between metrics logging. const int kMetricsIntervalInMinutes = 60; -std::unique_ptr<ContentSettingsForOneType> GetEngagementContentSettings( - HostContentSettingsMap* settings_map) { - std::unique_ptr<ContentSettingsForOneType> engagement_settings( - new ContentSettingsForOneType); - settings_map->GetSettingsForOneType(CONTENT_SETTINGS_TYPE_SITE_ENGAGEMENT, - std::string(), engagement_settings.get()); - return engagement_settings; +// Helper for fetching content settings for one type. +ContentSettingsForOneType GetContentSettingsFromProfile( + Profile* profile, + ContentSettingsType type) { + ContentSettingsForOneType content_settings; + HostContentSettingsMapFactory::GetForProfile(profile)->GetSettingsForOneType( + type, content_settings::ResourceIdentifier(), &content_settings); + return content_settings; +} + +// Returns the combined list of origins which either have site engagement +// data stored, or have other settings that would provide a score bonus. +std::set<GURL> GetEngagementOriginsFromContentSettings(Profile* profile) { + std::set<GURL> urls; + + // Fetch URLs of sites with engagement details stored. + for (const auto& site : GetContentSettingsFromProfile( + profile, CONTENT_SETTINGS_TYPE_SITE_ENGAGEMENT)) { + urls.insert(GURL(site.primary_pattern.ToString())); + } + + // Fetch URLs of sites for which notifications are allowed. + for (const auto& site : GetContentSettingsFromProfile( + profile, CONTENT_SETTINGS_TYPE_NOTIFICATIONS)) { + if (site.setting != CONTENT_SETTING_ALLOW) + continue; + urls.insert(GURL(site.primary_pattern.ToString())); + } + + return urls; } // Only accept a navigation event for engagement if it is one of: @@ -104,8 +126,7 @@ HostContentSettingsMap* settings, const GURL& origin) { auto clock = base::MakeUnique<base::DefaultClock>(); - return SiteEngagementScore(clock.get(), origin, settings) - .GetScore(); + return SiteEngagementScore(clock.get(), origin, settings).GetTotalScore(); } SiteEngagementService::SiteEngagementService(Profile* profile) @@ -139,21 +160,28 @@ return CreateEngagementScore(url).GetEngagementLevel(); } -std::map<GURL, double> SiteEngagementService::GetScoreMap() const { - HostContentSettingsMap* settings_map = - HostContentSettingsMapFactory::GetForProfile(profile_); - std::unique_ptr<ContentSettingsForOneType> engagement_settings = - GetEngagementContentSettings(settings_map); +std::vector<mojom::SiteEngagementDetails> SiteEngagementService::GetAllDetails() + const { + std::set<GURL> origins = GetEngagementOriginsFromContentSettings(profile_); - std::map<GURL, double> score_map; - for (const auto& site : *engagement_settings) { - GURL origin(site.primary_pattern.ToString()); + std::vector<mojom::SiteEngagementDetails> details; + details.reserve(origins.size()); + for (const GURL& origin : origins) { if (!origin.is_valid()) continue; - - score_map[origin] = GetScore(origin); + details.push_back(GetDetails(origin)); } + return details; +} + +std::map<GURL, double> SiteEngagementService::GetScoreMap() const { + std::map<GURL, double> score_map; + for (const GURL& origin : GetEngagementOriginsFromContentSettings(profile_)) { + if (!origin.is_valid()) + continue; + score_map[origin] = GetScore(origin); + } return score_map; } @@ -244,12 +272,17 @@ } double SiteEngagementService::GetScore(const GURL& url) const { + return GetDetails(url).total_score; +} + +mojom::SiteEngagementDetails SiteEngagementService::GetDetails( + const GURL& url) const { // Ensure that if engagement is stale, we clean things up before fetching the // score. if (IsLastEngagementStale()) CleanupEngagementScores(true); - return CreateEngagementScore(url).GetScore(); + return CreateEngagementScore(url).GetDetails(); } double SiteEngagementService::GetTotalEngagementPoints() const { @@ -317,11 +350,6 @@ void SiteEngagementService::CleanupEngagementScores( bool update_last_engagement_time) const { - HostContentSettingsMap* settings_map = - HostContentSettingsMapFactory::GetForProfile(profile_); - std::unique_ptr<ContentSettingsForOneType> engagement_settings = - GetEngagementContentSettings(settings_map); - // We want to rebase last engagement times relative to MaxDecaysPerScore // periods of decay in the past. base::Time now = clock_->Now(); @@ -341,7 +369,10 @@ if (last_engagement_time > now) last_engagement_time = now; - for (const auto& site : *engagement_settings) { + HostContentSettingsMap* settings_map = + HostContentSettingsMapFactory::GetForProfile(profile_); + for (const auto& site : GetContentSettingsFromProfile( + profile_, CONTENT_SETTINGS_TYPE_SITE_ENGAGEMENT)) { GURL origin(site.primary_pattern.ToString()); if (origin.is_valid()) { @@ -376,14 +407,15 @@ score.Commit(); } - if (score.GetScore() > SiteEngagementScore::GetScoreCleanupThreshold()) + if (score.GetTotalScore() > + SiteEngagementScore::GetScoreCleanupThreshold()) continue; } // This origin has a score of 0. Wipe it from content settings. settings_map->SetWebsiteSettingDefaultScope( - origin, GURL(), CONTENT_SETTINGS_TYPE_SITE_ENGAGEMENT, std::string(), - nullptr); + origin, GURL(), CONTENT_SETTINGS_TYPE_SITE_ENGAGEMENT, + content_settings::ResourceIdentifier(), nullptr); } // Set the last engagement time to be consistent with the scores. This will @@ -577,16 +609,13 @@ } int SiteEngagementService::OriginsWithMaxDailyEngagement() const { - HostContentSettingsMap* settings_map = - HostContentSettingsMapFactory::GetForProfile(profile_); - std::unique_ptr<ContentSettingsForOneType> engagement_settings = - GetEngagementContentSettings(settings_map); - int total_origins = 0; // We cannot call GetScoreMap as we need the score objects, not raw scores. - for (const auto& site : *engagement_settings) { + for (const auto& site : GetContentSettingsFromProfile( + profile_, CONTENT_SETTINGS_TYPE_SITE_ENGAGEMENT)) { GURL origin(site.primary_pattern.ToString()); + if (!origin.is_valid()) continue; @@ -653,9 +682,11 @@ // engagement is next accessed, it will decay back to the proportionally // reduced value rather than being decayed once here, and then once again // when it is next accessed. + // TODO(703848): Move the proportional decay logic into SiteEngagementScore, + // so it can decay raw_score_ directly, without the double-decay issue. SiteEngagementScore engagement_score = CreateEngagementScore(origin); - double new_score = proportion_remaining * engagement_score.GetScore(); + double new_score = proportion_remaining * engagement_score.GetTotalScore(); int hours_since_engagement = (now - last_visit).InHours(); int periods = hours_since_engagement / SiteEngagementScore::GetDecayPeriodInHours();
diff --git a/chrome/browser/engagement/site_engagement_service.h b/chrome/browser/engagement/site_engagement_service.h index 35c005d..b47e6ca 100644 --- a/chrome/browser/engagement/site_engagement_service.h +++ b/chrome/browser/engagement/site_engagement_service.h
@@ -8,6 +8,7 @@ #include <map> #include <memory> #include <set> +#include <vector> #include "base/gtest_prod_util.h" #include "base/macros.h" @@ -15,6 +16,7 @@ #include "base/observer_list.h" #include "base/time/time.h" #include "build/build_config.h" +#include "chrome/browser/engagement/site_engagement_details.mojom.h" #include "chrome/browser/engagement/site_engagement_metrics.h" #include "chrome/browser/engagement/site_engagement_observer.h" #include "components/history/core/browser/history_service_observer.h" @@ -116,7 +118,13 @@ // Returns the engagement level of |url|. blink::mojom::EngagementLevel GetEngagementLevel(const GURL& url) const; + // Returns an array of engagement score details for all origins which have + // a score, whether due to direct engagement, or other factors that cause + // an engagement bonus to be applied. + std::vector<mojom::SiteEngagementDetails> GetAllDetails() const; + // Returns a map of all stored origins and their engagement scores. + // TODO(703848): Migrate important sites impl off this and remove it std::map<GURL, double> GetScoreMap() const; // Update the engagement score of |url| for a notification interaction. @@ -143,6 +151,9 @@ void HelperCreated(SiteEngagementService::Helper* helper); void HelperDeleted(SiteEngagementService::Helper* helper); + // Returns the site engagement details for the specified |url|. + mojom::SiteEngagementDetails GetDetails(const GURL& url) const; + // Overridden from SiteEngagementScoreProvider. double GetScore(const GURL& url) const override; double GetTotalEngagementPoints() const override;
diff --git a/chrome/browser/engagement/site_engagement_service_unittest.cc b/chrome/browser/engagement/site_engagement_service_unittest.cc index e6c39a5..c65e9d6 100644 --- a/chrome/browser/engagement/site_engagement_service_unittest.cc +++ b/chrome/browser/engagement/site_engagement_service_unittest.cc
@@ -548,16 +548,16 @@ HostContentSettingsMapFactory::GetForProfile(profile()); settings_map->SetContentSettingDefaultScope( - url1, url1, CONTENT_SETTINGS_TYPE_NOTIFICATIONS, std::string(), - CONTENT_SETTING_ALLOW); + url1, GURL(), CONTENT_SETTINGS_TYPE_NOTIFICATIONS, + content_settings::ResourceIdentifier(), CONTENT_SETTING_ALLOW); settings_map->SetContentSettingDefaultScope( - url2, url2, CONTENT_SETTINGS_TYPE_NOTIFICATIONS, std::string(), - CONTENT_SETTING_BLOCK); + url2, GURL(), CONTENT_SETTINGS_TYPE_NOTIFICATIONS, + content_settings::ResourceIdentifier(), CONTENT_SETTING_BLOCK); settings_map->SetContentSettingDefaultScope( - url3, url3, CONTENT_SETTINGS_TYPE_NOTIFICATIONS, std::string(), - CONTENT_SETTING_ASK); + url3, GURL(), CONTENT_SETTINGS_TYPE_NOTIFICATIONS, + content_settings::ResourceIdentifier(), CONTENT_SETTING_ASK); EXPECT_EQ(5, service_->GetScore(url1)); EXPECT_EQ(0, service_->GetScore(url2)); @@ -569,8 +569,8 @@ EXPECT_EQ(3, service_->GetScore(url2)); settings_map->SetContentSettingDefaultScope( - url1, url1, CONTENT_SETTINGS_TYPE_NOTIFICATIONS, std::string(), - CONTENT_SETTING_BLOCK); + url1, GURL(), CONTENT_SETTINGS_TYPE_NOTIFICATIONS, + content_settings::ResourceIdentifier(), CONTENT_SETTING_BLOCK); EXPECT_EQ(1, service_->GetScore(url1)); } @@ -1835,3 +1835,37 @@ EXPECT_EQ(3, CheckScoreFromSettingsOnThread(content::BrowserThread::IO, incognito_settings_map, url2)); } + +TEST_F(SiteEngagementServiceTest, GetAllDetailsIncludesBonusOnlyScores) { + GURL url1("http://www.google.com/"); + GURL url2("https://www.google.com/"); + GURL url3("https://drive.google.com/"); + GURL url4("https://nothing.google.com/"); + + std::vector<mojom::SiteEngagementDetails> details = service_->GetAllDetails(); + EXPECT_EQ(0u, details.size()); + + // Add a single site score via explicitly resetting the engagement score. + service_->ResetBaseScoreForURL(url1, 5); + + // Add a second site indirectly, via notifications permissions. + HostContentSettingsMap* settings_map = + HostContentSettingsMapFactory::GetForProfile(profile()); + settings_map->SetContentSettingDefaultScope( + url2, GURL(), CONTENT_SETTINGS_TYPE_NOTIFICATIONS, + content_settings::ResourceIdentifier(), CONTENT_SETTING_ALLOW); + + // Add third and fourth sites with notifications permission explicitly denied, + // to verify that they are not included. + settings_map->SetContentSettingDefaultScope( + url3, GURL(), CONTENT_SETTINGS_TYPE_NOTIFICATIONS, + content_settings::ResourceIdentifier(), CONTENT_SETTING_BLOCK); + settings_map->SetContentSettingDefaultScope( + url4, GURL(), CONTENT_SETTINGS_TYPE_NOTIFICATIONS, + content_settings::ResourceIdentifier(), CONTENT_SETTING_BLOCK); + + // Verify that the URLs with engagement, and with notifications permission + // boosted engagement total, are included. + details = service_->GetAllDetails(); + EXPECT_EQ(2u, details.size()); +}
diff --git a/chrome/browser/extensions/api/messaging/native_messaging_host_manifest_unittest.cc b/chrome/browser/extensions/api/messaging/native_messaging_host_manifest_unittest.cc index 41707f36..d8c9e69 100644 --- a/chrome/browser/extensions/api/messaging/native_messaging_host_manifest_unittest.cc +++ b/chrome/browser/extensions/api/messaging/native_messaging_host_manifest_unittest.cc
@@ -47,8 +47,9 @@ } bool WriteManifest(const std::string& manifest_content) { - return base::WriteFile( - manifest_path_, manifest_content.data(), manifest_content.size()); + return base::WriteFile(manifest_path_, manifest_content.data(), + manifest_content.size()) == + static_cast<int>(manifest_content.size()); } base::ScopedTempDir temp_dir_;
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 1c05df7..00c1c9e 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
@@ -681,9 +681,7 @@ } // TODO(stevenjb): Find a better way to set this up on Chrome OS. -// TODO(stevenjb): https://crbug.com/710241 -IN_PROC_BROWSER_TEST_F(NetworkingPrivateChromeOSApiTest, - DISABLED_GetManagedProperties) { +IN_PROC_BROWSER_TEST_F(NetworkingPrivateChromeOSApiTest, GetManagedProperties) { const std::string uidata_blob = "{ \"user_settings\": {" " \"WiFi\": {"
diff --git a/chrome/browser/extensions/api/settings_private/prefs_util.cc b/chrome/browser/extensions/api/settings_private/prefs_util.cc index 306d399..4ec2b89 100644 --- a/chrome/browser/extensions/api/settings_private/prefs_util.cc +++ b/chrome/browser/extensions/api/settings_private/prefs_util.cc
@@ -279,6 +279,8 @@ settings_private::PrefType::PREF_TYPE_BOOLEAN; (*s_whitelist)[::prefs::kWakeOnWifiDarkConnect] = settings_private::PrefType::PREF_TYPE_BOOLEAN; + (*s_whitelist)[::chromeos::kSignedDataRoamingEnabled] = + settings_private::PrefType::PREF_TYPE_BOOLEAN; // Timezone settings. (*s_whitelist)[chromeos::kSystemTimezone] =
diff --git a/chrome/browser/extensions/display_info_provider_chromeos.cc b/chrome/browser/extensions/display_info_provider_chromeos.cc index 949f4a4..d981386 100644 --- a/chrome/browser/extensions/display_info_provider_chromeos.cc +++ b/chrome/browser/extensions/display_info_provider_chromeos.cc
@@ -239,6 +239,18 @@ bool is_primary = id == primary_display_id || (info.is_primary && *info.is_primary); + if (info.is_unified) { + if (!is_primary) { + *error = "Unified desktop mode can only be set for the primary display."; + return false; + } + if (info.mirroring_source_id) { + *error = "Unified desktop mode can not be set with mirroringSourceId."; + return false; + } + return true; + } + // If mirroring source id is set, a display with the given id should exist, // and if should not be the same as the target display's id. if (info.mirroring_source_id && !info.mirroring_source_id->empty()) { @@ -417,15 +429,15 @@ } // namespace // static -const char DisplayInfoProviderChromeOS:: - kCustomTouchCalibrationInProgressError[] = +const char + DisplayInfoProviderChromeOS::kCustomTouchCalibrationInProgressError[] = "Another custom touch calibration already under progress."; // static -const char DisplayInfoProviderChromeOS:: - kCompleteCalibrationCalledBeforeStartError[] = +const char + DisplayInfoProviderChromeOS::kCompleteCalibrationCalledBeforeStartError[] = "system.display.completeCustomTouchCalibration called before " - "system.display.startCustomTouchCalibration before."; + "system.display.startCustomTouchCalibration before."; // static const char DisplayInfoProviderChromeOS::kTouchBoundsNegativeError[] = @@ -457,6 +469,7 @@ *error = "Not implemented for mash."; return false; } + display::DisplayManager* display_manager = ash::Shell::Get()->display_manager(); ash::DisplayConfigurationController* display_configuration_controller = @@ -478,6 +491,13 @@ return false; } + // Process 'isUnified' parameter if set. + if (info.is_unified) { + display_manager->SetDefaultMultiDisplayModeForCurrentDisplays( + *info.is_unified ? display::DisplayManager::UNIFIED + : display::DisplayManager::EXTENDED); + } + // Process 'isPrimary' parameter. if (info.is_primary && *info.is_primary && target.id() != primary.id()) display_configuration_controller->SetPrimaryDisplayId(display_id); @@ -619,7 +639,7 @@ } DisplayInfoProvider::DisplayUnitInfoList -DisplayInfoProviderChromeOS::GetAllDisplaysInfo() { +DisplayInfoProviderChromeOS::GetAllDisplaysInfo(bool single_unified) { if (ash_util::IsRunningInMash()) { // TODO(crbug.com/682402): Mash support. NOTIMPLEMENTED(); @@ -627,21 +647,31 @@ } display::DisplayManager* display_manager = ash::Shell::Get()->display_manager(); + if (!display_manager->IsInUnifiedMode()) - return DisplayInfoProvider::GetAllDisplaysInfo(); + return DisplayInfoProvider::GetAllDisplaysInfo(single_unified); - std::vector<display::Display> displays = - display_manager->software_mirroring_display_list(); - CHECK_GT(displays.size(), 0u); + // Chrome OS specific: get displays for unified mode. + std::vector<display::Display> displays; + int64_t primary_id; + if (single_unified) { + for (size_t i = 0; i < display_manager->GetNumDisplays(); ++i) + displays.push_back(display_manager->GetDisplayAt(i)); + primary_id = display::Screen::GetScreen()->GetPrimaryDisplay().id(); + } else { + displays = display_manager->software_mirroring_display_list(); + CHECK_GT(displays.size(), 0u); + // Use first display as primary. + primary_id = displays[0].id(); + } - // Use first display as primary. - int64_t primary_id = displays[0].id(); DisplayUnitInfoList all_displays; for (const display::Display& display : displays) { - system_display::DisplayUnitInfo unit = + system_display::DisplayUnitInfo unit_info = CreateDisplayUnitInfo(display, primary_id); - UpdateDisplayUnitInfoForPlatform(display, &unit); - all_displays.push_back(std::move(unit)); + UpdateDisplayUnitInfoForPlatform(display, &unit_info); + unit_info.is_unified = true; + all_displays.push_back(std::move(unit_info)); } return all_displays; } @@ -733,7 +763,8 @@ } bool DisplayInfoProviderChromeOS::ShowNativeTouchCalibration( - const std::string& id, std::string* error, + const std::string& id, + std::string* error, const DisplayInfoProvider::TouchCalibrationCallback& callback) { if (ash_util::IsRunningInMash()) { // TODO(crbug.com/682402): Mash support. @@ -805,8 +836,8 @@ custom_touch_calibration_active_ = false; - if (!ValidateParamsForTouchCalibration( - touch_calibration_target_id_, display, GetTouchCalibrator(), error)) { + if (!ValidateParamsForTouchCalibration(touch_calibration_target_id_, display, + GetTouchCalibrator(), error)) { return false; }
diff --git a/chrome/browser/extensions/display_info_provider_chromeos.h b/chrome/browser/extensions/display_info_provider_chromeos.h index b84b04a7..8b6b327e 100644 --- a/chrome/browser/extensions/display_info_provider_chromeos.h +++ b/chrome/browser/extensions/display_info_provider_chromeos.h
@@ -39,7 +39,7 @@ const display::Display& display, api::system_display::DisplayUnitInfo* unit) override; void EnableUnifiedDesktop(bool enable) override; - DisplayUnitInfoList GetAllDisplaysInfo() override; + DisplayUnitInfoList GetAllDisplaysInfo(bool single_unified) override; DisplayLayoutList GetDisplayLayout() override; bool OverscanCalibrationStart(const std::string& id) override; bool OverscanCalibrationAdjust(
diff --git a/chrome/browser/extensions/display_info_provider_chromeos_unittest.cc b/chrome/browser/extensions/display_info_provider_chromeos_unittest.cc index 2aeebe2..f4998a6 100644 --- a/chrome/browser/extensions/display_info_provider_chromeos_unittest.cc +++ b/chrome/browser/extensions/display_info_provider_chromeos_unittest.cc
@@ -84,13 +84,18 @@ "%d,%d %dx%d", bounds.left, bounds.top, bounds.width, bounds.height); } + DisplayUnitInfoList GetAllDisplaysInfo() { + return DisplayInfoProvider::Get()->GetAllDisplaysInfo( + false /* single unified */); + } + private: DISALLOW_COPY_AND_ASSIGN(DisplayInfoProviderChromeosTest); }; TEST_F(DisplayInfoProviderChromeosTest, GetBasic) { UpdateDisplay("500x600,400x520"); - DisplayUnitInfoList result = DisplayInfoProvider::Get()->GetAllDisplaysInfo(); + DisplayUnitInfoList result = GetAllDisplaysInfo(); ASSERT_EQ(2u, result.size()); @@ -131,7 +136,7 @@ // Check initial state. EXPECT_FALSE(GetDisplayManager()->IsInUnifiedMode()); - DisplayUnitInfoList result = DisplayInfoProvider::Get()->GetAllDisplaysInfo(); + DisplayUnitInfoList result = GetAllDisplaysInfo(); ASSERT_EQ(2u, result.size()); @@ -144,6 +149,7 @@ EXPECT_EQ("0,0,0,0", SystemInfoDisplayInsetsToString(result[0].overscan)); EXPECT_EQ(0, result[0].rotation); EXPECT_TRUE(result[0].is_primary); + EXPECT_FALSE(result[0].is_unified); EXPECT_EQ(96, result[0].dpi_x); EXPECT_EQ(96, result[0].dpi_y); EXPECT_TRUE(result[0].mirroring_source_id.empty()); @@ -161,6 +167,7 @@ EXPECT_EQ("0,0,0,0", SystemInfoDisplayInsetsToString(result[1].overscan)); EXPECT_EQ(0, result[1].rotation); EXPECT_FALSE(result[1].is_primary); + EXPECT_FALSE(result[0].is_unified); EXPECT_EQ(96, result[1].dpi_x); EXPECT_EQ(96, result[1].dpi_y); EXPECT_TRUE(result[1].mirroring_source_id.empty()); @@ -170,7 +177,7 @@ GetDisplayManager()->SetUnifiedDesktopEnabled(true); EXPECT_TRUE(GetDisplayManager()->IsInUnifiedMode()); - result = DisplayInfoProvider::Get()->GetAllDisplaysInfo(); + result = GetAllDisplaysInfo(); ASSERT_EQ(2u, result.size()); @@ -181,6 +188,7 @@ EXPECT_EQ("0,0,0,0", SystemInfoDisplayInsetsToString(result[0].overscan)); EXPECT_EQ(0, result[0].rotation); EXPECT_TRUE(result[0].is_primary); + EXPECT_TRUE(result[0].is_unified); EXPECT_EQ(96, result[0].dpi_x); EXPECT_EQ(96, result[0].dpi_y); EXPECT_TRUE(result[0].mirroring_source_id.empty()); @@ -198,6 +206,7 @@ EXPECT_EQ("0,0,0,0", SystemInfoDisplayInsetsToString(result[1].overscan)); EXPECT_EQ(0, result[1].rotation); EXPECT_FALSE(result[1].is_primary); + EXPECT_TRUE(result[1].is_unified); EXPECT_FLOAT_EQ(111, round(result[1].dpi_x)); EXPECT_FLOAT_EQ(111, round(result[1].dpi_y)); EXPECT_TRUE(result[1].mirroring_source_id.empty()); @@ -206,7 +215,7 @@ // Disable unified and check that once again it matches initial situation. GetDisplayManager()->SetUnifiedDesktopEnabled(false); EXPECT_FALSE(GetDisplayManager()->IsInUnifiedMode()); - result = DisplayInfoProvider::Get()->GetAllDisplaysInfo(); + result = GetAllDisplaysInfo(); ASSERT_EQ(2u, result.size()); @@ -218,6 +227,7 @@ EXPECT_EQ("0,0,0,0", SystemInfoDisplayInsetsToString(result[0].overscan)); EXPECT_EQ(0, result[0].rotation); EXPECT_TRUE(result[0].is_primary); + EXPECT_FALSE(result[0].is_unified); EXPECT_EQ(96, result[0].dpi_x); EXPECT_EQ(96, result[0].dpi_y); EXPECT_TRUE(result[0].mirroring_source_id.empty()); @@ -233,6 +243,113 @@ EXPECT_EQ("0,0,0,0", SystemInfoDisplayInsetsToString(result[1].overscan)); EXPECT_EQ(0, result[1].rotation); EXPECT_FALSE(result[1].is_primary); + EXPECT_FALSE(result[1].is_unified); + EXPECT_EQ(96, result[1].dpi_x); + EXPECT_EQ(96, result[1].dpi_y); + EXPECT_TRUE(result[1].mirroring_source_id.empty()); + EXPECT_TRUE(result[1].is_enabled); +} + +TEST_F(DisplayInfoProviderChromeosTest, GetWithUnifiedDesktopForSettings) { + UpdateDisplay("500x600,400x520"); + + // Check initial state. + EXPECT_FALSE(GetDisplayManager()->IsInUnifiedMode()); + DisplayUnitInfoList result = + DisplayInfoProvider::Get()->GetAllDisplaysInfo(true /* single unifed */); + + ASSERT_EQ(2u, result.size()); + + int64_t display_id; + ASSERT_TRUE(base::StringToInt64(result[0].id, &display_id)) + << "Display id must be convertable to integer: " << result[0].id; + + ASSERT_TRUE(DisplayExists(display_id)) << display_id << " not found"; + EXPECT_EQ("0,0 500x600", SystemInfoDisplayBoundsToString(result[0].bounds)); + EXPECT_EQ("0,0,0,0", SystemInfoDisplayInsetsToString(result[0].overscan)); + EXPECT_EQ(0, result[0].rotation); + EXPECT_TRUE(result[0].is_primary); + EXPECT_FALSE(result[0].is_unified); + EXPECT_EQ(96, result[0].dpi_x); + EXPECT_EQ(96, result[0].dpi_y); + EXPECT_TRUE(result[0].mirroring_source_id.empty()); + EXPECT_TRUE(result[0].is_enabled); + + ASSERT_TRUE(base::StringToInt64(result[1].id, &display_id)) + << "Display id must be convertable to integer: " << result[0].id; + + ASSERT_TRUE(DisplayExists(display_id)) << display_id << " not found"; + EXPECT_EQ(GetDisplayManager()->GetDisplayNameForId(display_id), + result[1].name); + + // Initial multipple display configuration. + EXPECT_EQ("500,0 400x520", SystemInfoDisplayBoundsToString(result[1].bounds)); + EXPECT_EQ("0,0,0,0", SystemInfoDisplayInsetsToString(result[1].overscan)); + EXPECT_EQ(0, result[1].rotation); + EXPECT_FALSE(result[1].is_primary); + EXPECT_FALSE(result[0].is_unified); + EXPECT_EQ(96, result[1].dpi_x); + EXPECT_EQ(96, result[1].dpi_y); + EXPECT_TRUE(result[1].mirroring_source_id.empty()); + EXPECT_TRUE(result[1].is_enabled); + + // Enable unified. + GetDisplayManager()->SetUnifiedDesktopEnabled(true); + EXPECT_TRUE(GetDisplayManager()->IsInUnifiedMode()); + + // For settings, GetAllDisplaysInfo will return a single unified display. The + // second display will be scaled to match the height of the first, so the + // height will be 600 and the new width will be 500 + [400 * 600/520 = 461] = + // 961. + result = + DisplayInfoProvider::Get()->GetAllDisplaysInfo(true /* single unified */); + + ASSERT_EQ(1u, result.size()); + ASSERT_TRUE(base::StringToInt64(result[0].id, &display_id)) + << "Display id must be convertable to integer: " << result[0].id; + + EXPECT_EQ("0,0 961x600", SystemInfoDisplayBoundsToString(result[0].bounds)); + EXPECT_EQ("0,0,0,0", SystemInfoDisplayInsetsToString(result[0].overscan)); + EXPECT_EQ(0, result[0].rotation); + EXPECT_TRUE(result[0].is_primary); + EXPECT_TRUE(result[0].is_unified); + EXPECT_EQ(96, result[0].dpi_x); + EXPECT_EQ(96, result[0].dpi_y); + EXPECT_TRUE(result[0].mirroring_source_id.empty()); + EXPECT_TRUE(result[0].is_enabled); + + // Disable unified and check that once again it matches initial situation. + GetDisplayManager()->SetUnifiedDesktopEnabled(false); + EXPECT_FALSE(GetDisplayManager()->IsInUnifiedMode()); + result = GetAllDisplaysInfo(); + + ASSERT_EQ(2u, result.size()); + + ASSERT_TRUE(base::StringToInt64(result[0].id, &display_id)) + << "Display id must be convertable to integer: " << result[0].id; + + ASSERT_TRUE(DisplayExists(display_id)) << display_id << " not found"; + EXPECT_EQ("0,0 500x600", SystemInfoDisplayBoundsToString(result[0].bounds)); + EXPECT_EQ("0,0,0,0", SystemInfoDisplayInsetsToString(result[0].overscan)); + EXPECT_EQ(0, result[0].rotation); + EXPECT_TRUE(result[0].is_primary); + EXPECT_FALSE(result[0].is_unified); + EXPECT_EQ(96, result[0].dpi_x); + EXPECT_EQ(96, result[0].dpi_y); + EXPECT_TRUE(result[0].mirroring_source_id.empty()); + EXPECT_TRUE(result[0].is_enabled); + + ASSERT_TRUE(base::StringToInt64(result[1].id, &display_id)) + << "Display id must be convertable to integer: " << result[0].id; + + ASSERT_TRUE(DisplayExists(display_id)) << display_id << " not found"; + EXPECT_EQ(GetDisplayManager()->GetDisplayNameForId(display_id), + result[1].name); + EXPECT_EQ("500,0 400x520", SystemInfoDisplayBoundsToString(result[1].bounds)); + EXPECT_EQ("0,0,0,0", SystemInfoDisplayInsetsToString(result[1].overscan)); + EXPECT_EQ(0, result[1].rotation); + EXPECT_FALSE(result[1].is_primary); + EXPECT_FALSE(result[1].is_unified); EXPECT_EQ(96, result[1].dpi_x); EXPECT_EQ(96, result[1].dpi_y); EXPECT_TRUE(result[1].mirroring_source_id.empty()); @@ -241,7 +358,7 @@ TEST_F(DisplayInfoProviderChromeosTest, GetRotation) { UpdateDisplay("500x600/r"); - DisplayUnitInfoList result = DisplayInfoProvider::Get()->GetAllDisplaysInfo(); + DisplayUnitInfoList result = GetAllDisplaysInfo(); ASSERT_EQ(1u, result.size()); @@ -257,7 +374,7 @@ display_id, display::Display::ROTATE_270, display::Display::ROTATION_SOURCE_ACTIVE); - result = DisplayInfoProvider::Get()->GetAllDisplaysInfo(); + result = GetAllDisplaysInfo(); ASSERT_EQ(1u, result.size()); @@ -269,7 +386,7 @@ display_id, display::Display::ROTATE_180, display::Display::ROTATION_SOURCE_ACTIVE); - result = DisplayInfoProvider::Get()->GetAllDisplaysInfo(); + result = GetAllDisplaysInfo(); ASSERT_EQ(1u, result.size()); @@ -281,7 +398,7 @@ display_id, display::Display::ROTATE_0, display::Display::ROTATION_SOURCE_ACTIVE); - result = DisplayInfoProvider::Get()->GetAllDisplaysInfo(); + result = GetAllDisplaysInfo(); ASSERT_EQ(1u, result.size()); @@ -293,7 +410,7 @@ TEST_F(DisplayInfoProviderChromeosTest, GetDPI) { UpdateDisplay("500x600,400x520*2"); DisplayUnitInfoList result; - result = DisplayInfoProvider::Get()->GetAllDisplaysInfo(); + result = GetAllDisplaysInfo(); ASSERT_EQ(2u, result.size()); @@ -309,7 +426,7 @@ SwapPrimaryDisplay(); - result = DisplayInfoProvider::Get()->GetAllDisplaysInfo(); + result = GetAllDisplaysInfo(); ASSERT_EQ(2u, result.size()); @@ -326,7 +443,7 @@ TEST_F(DisplayInfoProviderChromeosTest, GetVisibleArea) { UpdateDisplay("640x720*2/o, 400x520/o"); DisplayUnitInfoList result; - result = DisplayInfoProvider::Get()->GetAllDisplaysInfo(); + result = GetAllDisplaysInfo(); ASSERT_EQ(2u, result.size()); @@ -341,7 +458,7 @@ GetDisplayManager()->SetOverscanInsets(display_id, gfx::Insets(20, 30, 50, 60)); - result = DisplayInfoProvider::Get()->GetAllDisplaysInfo(); + result = GetAllDisplaysInfo(); ASSERT_EQ(2u, result.size()); @@ -359,7 +476,7 @@ GetDisplayManager()->SetOverscanInsets(display_id, gfx::Insets(10, 20, 30, 40)); - result = DisplayInfoProvider::Get()->GetAllDisplaysInfo(); + result = GetAllDisplaysInfo(); ASSERT_EQ(2u, result.size()); @@ -371,7 +488,7 @@ TEST_F(DisplayInfoProviderChromeosTest, GetMirroring) { UpdateDisplay("600x600, 400x520/o"); DisplayUnitInfoList result; - result = DisplayInfoProvider::Get()->GetAllDisplaysInfo(); + result = GetAllDisplaysInfo(); ASSERT_EQ(2u, result.size()); @@ -394,7 +511,7 @@ GetDisplayManager()->SetMirrorMode(true); ASSERT_TRUE(GetDisplayManager()->IsInMirrorMode()); - result = DisplayInfoProvider::Get()->GetAllDisplaysInfo(); + result = GetAllDisplaysInfo(); ASSERT_EQ(1u, result.size()); EXPECT_EQ(base::Int64ToString(display_id_primary), result[0].id); @@ -404,7 +521,7 @@ GetDisplayManager()->SetMirrorMode(false); ASSERT_FALSE(GetDisplayManager()->IsInMirrorMode()); - result = DisplayInfoProvider::Get()->GetAllDisplaysInfo(); + result = GetAllDisplaysInfo(); ASSERT_EQ(2u, result.size()); EXPECT_EQ(base::Int64ToString(display_id_primary), result[0].id); @@ -419,7 +536,7 @@ display::test::CreateDisplayLayout(display_manager(), display::DisplayPlacement::LEFT, -40)); - DisplayUnitInfoList result = DisplayInfoProvider::Get()->GetAllDisplaysInfo(); + DisplayUnitInfoList result = GetAllDisplaysInfo(); ASSERT_EQ(2u, result.size()); EXPECT_EQ("0,0 600x600", SystemInfoDisplayBoundsToString(result[0].bounds)); @@ -430,7 +547,7 @@ display::test::CreateDisplayLayout(display_manager(), display::DisplayPlacement::TOP, 40)); - result = DisplayInfoProvider::Get()->GetAllDisplaysInfo(); + result = GetAllDisplaysInfo(); ASSERT_EQ(2u, result.size()); EXPECT_EQ("0,0 600x600", SystemInfoDisplayBoundsToString(result[0].bounds)); @@ -441,7 +558,7 @@ display::test::CreateDisplayLayout( display_manager(), display::DisplayPlacement::BOTTOM, 80)); - result = DisplayInfoProvider::Get()->GetAllDisplaysInfo(); + result = GetAllDisplaysInfo(); ASSERT_EQ(2u, result.size()); EXPECT_EQ("0,0 600x600", SystemInfoDisplayBoundsToString(result[0].bounds)); EXPECT_EQ("80,600 400x520", @@ -451,8 +568,7 @@ TEST_F(DisplayInfoProviderChromeosTest, Layout) { UpdateDisplay("500x400,500x400,500x400"); - DisplayUnitInfoList displays = - DisplayInfoProvider::Get()->GetAllDisplaysInfo(); + DisplayUnitInfoList displays = GetAllDisplaysInfo(); std::string primary_id = displays[0].id; ASSERT_EQ(3u, displays.size()); @@ -1151,7 +1267,7 @@ TEST_F(DisplayInfoProviderChromeosTest, DisplayMode) { UpdateDisplay("1200x600,600x1000"); - DisplayUnitInfoList result = DisplayInfoProvider::Get()->GetAllDisplaysInfo(); + DisplayUnitInfoList result = GetAllDisplaysInfo(); ASSERT_GE(result.size(), 1u); const api::system_display::DisplayUnitInfo& primary_info = result[0]; // Ensure that we have two modes for the primary display so that we can
diff --git a/chrome/browser/extensions/extension_service_unittest.cc b/chrome/browser/extensions/extension_service_unittest.cc index 9080413e..ea632f2 100644 --- a/chrome/browser/extensions/extension_service_unittest.cc +++ b/chrome/browser/extensions/extension_service_unittest.cc
@@ -275,6 +275,17 @@ return extension; } +std::unique_ptr<ExternalInstallInfoFile> CreateExternalExtension( + const extensions::ExtensionId& extension_id, + const std::string& version_str, + const base::FilePath& path, + Manifest::Location location, + Extension::InitFromValueFlags flags) { + return base::MakeUnique<ExternalInstallInfoFile>( + extension_id, base::MakeUnique<base::Version>(version_str), path, + location, flags, false, false); +} + } // namespace class MockProviderVisitor @@ -524,9 +535,11 @@ AfterStartupTaskUtils::SetBrowserStartupIsCompleteForTesting(); } - void AddMockExternalProvider( - extensions::ExternalProviderInterface* provider) { - service()->AddProviderForTesting(base::WrapUnique(provider)); + MockExternalProvider* AddMockExternalProvider(Manifest::Location location) { + auto provider = base::MakeUnique<MockExternalProvider>(service(), location); + MockExternalProvider* provider_ptr = provider.get(); + service()->AddProviderForTesting(std::move(provider)); + return provider_ptr; } // Checks for external extensions and waits for one to complete installing. @@ -1083,16 +1096,14 @@ base::FilePath path = data_dir().AppendASCII("good.crx"); // Register and install an external extension. - std::unique_ptr<base::Version> version(new base::Version("1.0.0.0")); - content::WindowedNotificationObserver observer( - extensions::NOTIFICATION_CRX_INSTALLER_DONE, - content::NotificationService::AllSources()); - std::unique_ptr<ExternalInstallInfoFile> info(new ExternalInstallInfoFile( - good_crx, std::move(version), path, Manifest::EXTERNAL_PREF, - Extension::FROM_BOOKMARK, false /* mark_acknowledged */, - false /* install_immediately */)); - if (service()->OnExternalExtensionFileFound(*info)) - observer.Wait(); + std::string version_str = "1.0.0.0"; + std::unique_ptr<ExternalInstallInfoFile> info = CreateExternalExtension( + good_crx, version_str, path, Manifest::EXTERNAL_PREF, + Extension::FROM_BOOKMARK); + MockExternalProvider* provider = + AddMockExternalProvider(Manifest::EXTERNAL_POLICY_DOWNLOAD); + provider->UpdateOrAddExtension(std::move(info)); + WaitForExternalExtensionInstalled(); const Extension* extension = service()->GetExtensionById(good_crx, false); ASSERT_TRUE(extension); @@ -1114,16 +1125,15 @@ base::FilePath path = data_dir().AppendASCII("good.crx"); + std::string version_str = "1.0.0.0"; // Install an external extension. - content::WindowedNotificationObserver observer( - extensions::NOTIFICATION_CRX_INSTALLER_DONE, - content::NotificationService::AllSources()); - std::unique_ptr<base::Version> version(new base::Version("1.0.0.0")); - std::unique_ptr<ExternalInstallInfoFile> info(new ExternalInstallInfoFile( - good_crx, std::move(version), path, Manifest::EXTERNAL_PREF, - Extension::NO_FLAGS, false, false)); - if (service()->OnExternalExtensionFileFound(*info)) - observer.Wait(); + std::unique_ptr<ExternalInstallInfoFile> info = + CreateExternalExtension(good_crx, version_str, path, + Manifest::EXTERNAL_PREF, Extension::NO_FLAGS); + MockExternalProvider* provider = + AddMockExternalProvider(Manifest::EXTERNAL_PREF); + provider->UpdateOrAddExtension(std::move(info)); + WaitForExternalExtensionInstalled(); ASSERT_TRUE(service()->GetExtensionById(good_crx, false)); @@ -1133,19 +1143,20 @@ Extension::EXTERNAL_EXTENSION_UNINSTALLED); // Try to re-install it externally. This should fail because of the killbit. - service()->OnExternalExtensionFileFound(*info); + info = CreateExternalExtension(good_crx, version_str, path, + Manifest::EXTERNAL_PREF, Extension::NO_FLAGS); + provider->UpdateOrAddExtension(std::move(info)); base::RunLoop().RunUntilIdle(); ASSERT_TRUE(NULL == service()->GetExtensionById(good_crx, false)); ValidateIntegerPref(good_crx, "state", Extension::EXTERNAL_EXTENSION_UNINSTALLED); - version.reset(new base::Version("1.0.0.1")); + std::string newer_version = "1.0.0.1"; // Repeat the same thing with a newer version of the extension. path = data_dir().AppendASCII("good2.crx"); - info.reset(new ExternalInstallInfoFile(good_crx, std::move(version), path, - Manifest::EXTERNAL_PREF, - Extension::NO_FLAGS, false, false)); - service()->OnExternalExtensionFileFound(*info); + info = CreateExternalExtension(good_crx, newer_version, path, + Manifest::EXTERNAL_PREF, Extension::NO_FLAGS); + provider->UpdateOrAddExtension(std::move(info)); base::RunLoop().RunUntilIdle(); ASSERT_TRUE(NULL == service()->GetExtensionById(good_crx, false)); ValidateIntegerPref(good_crx, "state", @@ -1206,32 +1217,29 @@ InitializeEmptyExtensionService(); base::FilePath path = data_dir().AppendASCII("good.crx"); - std::unique_ptr<base::Version> version(new base::Version("1.0.0.0")); + std::string version_str = "1.0.0.0"; const std::string wrong_id = all_zero; const std::string correct_id = good_crx; ASSERT_NE(correct_id, wrong_id); + MockExternalProvider* provider = + AddMockExternalProvider(Manifest::EXTERNAL_PREF); + // Install an external extension with an ID from the external // source that is not equal to the ID in the extension manifest. - content::WindowedNotificationObserver observer( - extensions::NOTIFICATION_CRX_INSTALLER_DONE, - content::NotificationService::AllSources()); - std::unique_ptr<ExternalInstallInfoFile> info(new ExternalInstallInfoFile( - wrong_id, std::move(version), path, Manifest::EXTERNAL_PREF, - Extension::NO_FLAGS, false, false)); - service()->OnExternalExtensionFileFound(*info); - - observer.Wait(); + std::unique_ptr<ExternalInstallInfoFile> info = + CreateExternalExtension(wrong_id, version_str, path, + Manifest::EXTERNAL_PREF, Extension::NO_FLAGS); + provider->UpdateOrAddExtension(std::move(info)); + WaitForExternalExtensionInstalled(); ASSERT_FALSE(service()->GetExtensionById(good_crx, false)); // Try again with the right ID. Expect success. - content::WindowedNotificationObserver observer2( - extensions::NOTIFICATION_CRX_INSTALLER_DONE, - content::NotificationService::AllSources()); - info->extension_id = correct_id; - if (service()->OnExternalExtensionFileFound(*info)) - observer2.Wait(); + info = CreateExternalExtension(correct_id, version_str, path, + Manifest::EXTERNAL_PREF, Extension::NO_FLAGS); + provider->UpdateOrAddExtension(std::move(info)); + WaitForExternalExtensionInstalled(); ASSERT_TRUE(service()->GetExtensionById(good_crx, false)); } @@ -1239,30 +1247,26 @@ TEST_F(ExtensionServiceTest, FailOnWrongVersion) { InitializeEmptyExtensionService(); base::FilePath path = data_dir().AppendASCII("good.crx"); + MockExternalProvider* provider = + AddMockExternalProvider(Manifest::EXTERNAL_PREF); // Install an external extension with a version from the external // source that is not equal to the version in the extension manifest. - content::WindowedNotificationObserver observer( - extensions::NOTIFICATION_CRX_INSTALLER_DONE, - content::NotificationService::AllSources()); - std::unique_ptr<base::Version> wrong_version(new base::Version("1.2.3.4")); - std::unique_ptr<ExternalInstallInfoFile> info(new ExternalInstallInfoFile( - good_crx, std::move(wrong_version), path, Manifest::EXTERNAL_PREF, - Extension::NO_FLAGS, false, false)); - service()->OnExternalExtensionFileFound(*info); - - observer.Wait(); + std::string wrong_version_str = "1.2.3.4"; + std::unique_ptr<ExternalInstallInfoFile> wrong_info = + CreateExternalExtension(good_crx, wrong_version_str, path, + Manifest::EXTERNAL_PREF, Extension::NO_FLAGS); + provider->UpdateOrAddExtension(std::move(wrong_info)); + WaitForExternalExtensionInstalled(); ASSERT_FALSE(service()->GetExtensionById(good_crx, false)); // Try again with the right version. Expect success. service()->pending_extension_manager()->Remove(good_crx); - std::unique_ptr<base::Version> correct_version(new base::Version("1.0.0.0")); - info->version = std::move(correct_version); - content::WindowedNotificationObserver observer2( - extensions::NOTIFICATION_CRX_INSTALLER_DONE, - content::NotificationService::AllSources()); - if (service()->OnExternalExtensionFileFound(*info)) - observer2.Wait(); + std::unique_ptr<ExternalInstallInfoFile> correct_info = + CreateExternalExtension(good_crx, "1.0.0.0", path, + Manifest::EXTERNAL_PREF, Extension::NO_FLAGS); + provider->UpdateOrAddExtension(std::move(correct_info)); + WaitForExternalExtensionInstalled(); ASSERT_TRUE(service()->GetExtensionById(good_crx, false)); } @@ -1838,9 +1842,11 @@ // Try packing with an invalid manifest. std::string invalid_manifest_content = "I am not a manifest."; - ASSERT_TRUE(base::WriteFile( - temp_dir2.GetPath().Append(extensions::kManifestFilename), - invalid_manifest_content.c_str(), invalid_manifest_content.size())); + ASSERT_EQ( + static_cast<int>(invalid_manifest_content.size()), + base::WriteFile(temp_dir2.GetPath().Append(extensions::kManifestFilename), + invalid_manifest_content.c_str(), + invalid_manifest_content.size())); creator.reset(new ExtensionCreator()); ASSERT_FALSE(creator->Run(temp_dir2.GetPath(), crx_path, privkey_path, base::FilePath(), ExtensionCreator::kOverwriteCRX)); @@ -3451,18 +3457,13 @@ // Have policy force-install an extension. MockExternalProvider* provider = - new MockExternalProvider(service(), Manifest::EXTERNAL_POLICY_DOWNLOAD); - AddMockExternalProvider(provider); + AddMockExternalProvider(Manifest::EXTERNAL_POLICY_DOWNLOAD); provider->UpdateOrAddExtension( good_crx, "1.0.0.0", data_dir().AppendASCII("good_crx")); // Reloading extensions should find our externally registered extension // and install it. - content::WindowedNotificationObserver observer( - extensions::NOTIFICATION_CRX_INSTALLER_DONE, - content::NotificationService::AllSources()); - service()->CheckForExternalUpdates(); - observer.Wait(); + WaitForExternalExtensionInstalled(); AssertExtensionBlocksAndUnblocks(false, good_crx); } @@ -3666,18 +3667,13 @@ // Have policy force-install an extension. MockExternalProvider* provider = - new MockExternalProvider(service(), Manifest::EXTERNAL_POLICY_DOWNLOAD); - AddMockExternalProvider(provider); + AddMockExternalProvider(Manifest::EXTERNAL_POLICY_DOWNLOAD); provider->UpdateOrAddExtension( good_crx, "1.0.0.0", data_dir().AppendASCII("good.crx")); // Reloading extensions should find our externally registered extension // and install it. - content::WindowedNotificationObserver observer( - extensions::NOTIFICATION_CRX_INSTALLER_DONE, - content::NotificationService::AllSources()); - service()->CheckForExternalUpdates(); - observer.Wait(); + WaitForExternalExtensionInstalled(); // Extension should be installed despite blacklist. ASSERT_EQ(1u, registry()->enabled_extensions().size()); @@ -3923,18 +3919,11 @@ // Use MockExternalProvider to simulate force installing extension. MockExternalProvider* provider = - new MockExternalProvider(service(), Manifest::EXTERNAL_POLICY_DOWNLOAD); - AddMockExternalProvider(provider); + AddMockExternalProvider(Manifest::EXTERNAL_POLICY_DOWNLOAD); provider->UpdateOrAddExtension(permissions_blocklist, "1.0", crx_path); - { - // Attempts to force install this extension. - content::WindowedNotificationObserver observer( - extensions::NOTIFICATION_CRX_INSTALLER_DONE, - content::NotificationService::AllSources()); - service()->CheckForExternalUpdates(); - observer.Wait(); - } + // Attempts to force install this extension. + WaitForExternalExtensionInstalled(); // The extension should not be installed. ASSERT_FALSE(service()->GetInstalledExtension(permissions_blocklist)); @@ -3949,14 +3938,8 @@ pref.ClearBlockedPermissions("*"); } - { - // Attempts to force install this extension again. - content::WindowedNotificationObserver observer( - extensions::NOTIFICATION_CRX_INSTALLER_DONE, - content::NotificationService::AllSources()); - service()->CheckForExternalUpdates(); - observer.Wait(); - } + // Attempts to force install this extension again. + WaitForExternalExtensionInstalled(); const Extension* installed = service()->GetInstalledExtension(permissions_blocklist); @@ -4025,15 +4008,9 @@ // Force install another extension with known id and same manifest as 'ext2'. std::string ext2_forced = permissions_blocklist; MockExternalProvider* provider = - new MockExternalProvider(service(), Manifest::EXTERNAL_POLICY_DOWNLOAD); - AddMockExternalProvider(provider); + AddMockExternalProvider(Manifest::EXTERNAL_POLICY_DOWNLOAD); provider->UpdateOrAddExtension(ext2_forced, "2.0", crx_path); - - content::WindowedNotificationObserver observer( - extensions::NOTIFICATION_CRX_INSTALLER_DONE, - content::NotificationService::AllSources()); - service()->CheckForExternalUpdates(); - observer.Wait(); + WaitForExternalExtensionInstalled(); extensions::ExtensionRegistry* registry = extensions::ExtensionRegistry::Get(profile()); @@ -4088,16 +4065,14 @@ { // Register and install an external extension. MockExternalProvider* provider = - new MockExternalProvider(service(), Manifest::EXTERNAL_PREF); - AddMockExternalProvider(provider); + AddMockExternalProvider(Manifest::EXTERNAL_PREF); provider->UpdateOrAddExtension( good_crx, "1.0.0.0", data_dir().AppendASCII("good.crx")); } { // Have policy force-install an extension. MockExternalProvider* provider = - new MockExternalProvider(service(), Manifest::EXTERNAL_POLICY_DOWNLOAD); - AddMockExternalProvider(provider); + AddMockExternalProvider(Manifest::EXTERNAL_POLICY_DOWNLOAD); provider->UpdateOrAddExtension( page_action, "1.0.0.0", data_dir().AppendASCII("page_action.crx")); } @@ -4128,8 +4103,7 @@ // Register and install an external extension. MockExternalProvider* provider = - new MockExternalProvider(service(), Manifest::EXTERNAL_PREF); - AddMockExternalProvider(provider); // Takes ownership. + AddMockExternalProvider(Manifest::EXTERNAL_PREF); // Takes ownership. provider->UpdateOrAddExtension(good_crx, "1.0.0.0", data_dir().AppendASCII("good.crx")); @@ -4168,8 +4142,7 @@ // Register and install an external extension. MockExternalProvider* provider = - new MockExternalProvider(service(), Manifest::EXTERNAL_PREF); - AddMockExternalProvider(provider); + AddMockExternalProvider(Manifest::EXTERNAL_PREF); provider->UpdateOrAddExtension(good_crx, "1.0.0.0", data_dir().AppendASCII("good.crx")); @@ -4226,15 +4199,11 @@ Manifest::INVALID_LOCATION, Extension::FROM_WEBSTORE | Extension::WAS_INSTALLED_BY_DEFAULT); - AddMockExternalProvider(provider); + service()->AddProviderForTesting(base::WrapUnique(provider)); } ASSERT_EQ(0u, registry()->enabled_extensions().size()); - content::WindowedNotificationObserver observer( - extensions::NOTIFICATION_CRX_INSTALLER_DONE, - content::NotificationService::AllSources()); - service()->CheckForExternalUpdates(); - observer.Wait(); + WaitForExternalExtensionInstalled(); ASSERT_EQ(1u, registry()->enabled_extensions().size()); EXPECT_TRUE(service()->GetExtensionById(good_crx, false)); @@ -4939,11 +4908,7 @@ // Reloading extensions should find our externally registered extension // and install it. - content::WindowedNotificationObserver observer( - extensions::NOTIFICATION_CRX_INSTALLER_DONE, - content::NotificationService::AllSources()); - service()->CheckForExternalUpdates(); - observer.Wait(); + WaitForExternalExtensionInstalled(); ASSERT_EQ(0u, GetErrors().size()); ASSERT_EQ(1u, loaded_.size()); @@ -4969,11 +4934,7 @@ provider->UpdateOrAddExtension(good_crx, "1.0.0.1", source_path); loaded_.clear(); - content::WindowedNotificationObserver observer_2( - extensions::NOTIFICATION_CRX_INSTALLER_DONE, - content::NotificationService::AllSources()); - service()->CheckForExternalUpdates(); - observer_2.Wait(); + WaitForExternalExtensionInstalled(); ASSERT_EQ(0u, GetErrors().size()); ASSERT_EQ(1u, loaded_.size()); ASSERT_EQ("1.0.0.1", loaded_[0]->version()->GetString()); @@ -5012,11 +4973,7 @@ SetPrefInteg(good_crx, "state", Extension::ENABLED); loaded_.clear(); - content::WindowedNotificationObserver observer( - extensions::NOTIFICATION_CRX_INSTALLER_DONE, - content::NotificationService::AllSources()); - service()->CheckForExternalUpdates(); - observer.Wait(); + WaitForExternalExtensionInstalled(); ASSERT_EQ(1u, loaded_.size()); } ValidatePrefKeyCount(1); @@ -5041,12 +4998,8 @@ // Now test the case where user uninstalls and then the extension is removed // from the external provider. - content::WindowedNotificationObserver observer( - extensions::NOTIFICATION_CRX_INSTALLER_DONE, - content::NotificationService::AllSources()); provider->UpdateOrAddExtension(good_crx, "1.0.0.1", source_path); - service()->CheckForExternalUpdates(); - observer.Wait(); + WaitForExternalExtensionInstalled(); ASSERT_EQ(1u, loaded_.size()); ASSERT_EQ(0u, GetErrors().size()); @@ -5082,8 +5035,7 @@ // Now add providers. Extension system takes ownership of the objects. MockExternalProvider* reg_provider = - new MockExternalProvider(service(), Manifest::EXTERNAL_REGISTRY); - AddMockExternalProvider(reg_provider); + AddMockExternalProvider(Manifest::EXTERNAL_REGISTRY); TestExternalProvider(reg_provider, Manifest::EXTERNAL_REGISTRY); } #endif @@ -5093,9 +5045,8 @@ // Now add providers. Extension system takes ownership of the objects. MockExternalProvider* pref_provider = - new MockExternalProvider(service(), Manifest::EXTERNAL_PREF); + AddMockExternalProvider(Manifest::EXTERNAL_PREF); - AddMockExternalProvider(pref_provider); TestExternalProvider(pref_provider, Manifest::EXTERNAL_PREF); } @@ -5111,8 +5062,7 @@ // what the visitor does results in an extension being downloaded and // installed. MockExternalProvider* pref_provider = - new MockExternalProvider(service(), Manifest::EXTERNAL_PREF_DOWNLOAD); - AddMockExternalProvider(pref_provider); + AddMockExternalProvider(Manifest::EXTERNAL_PREF_DOWNLOAD); TestExternalProvider(pref_provider, Manifest::EXTERNAL_PREF_DOWNLOAD); } @@ -5128,8 +5078,7 @@ // what the visitor does results in an extension being downloaded and // installed. MockExternalProvider* pref_provider = - new MockExternalProvider(service(), Manifest::EXTERNAL_POLICY_DOWNLOAD); - AddMockExternalProvider(pref_provider); + AddMockExternalProvider(Manifest::EXTERNAL_POLICY_DOWNLOAD); TestExternalProvider(pref_provider, Manifest::EXTERNAL_POLICY_DOWNLOAD); } @@ -5156,8 +5105,7 @@ InitializeEmptyExtensionService(); MockExternalProvider* provider = - new MockExternalProvider(service(), Manifest::EXTERNAL_PREF); - AddMockExternalProvider(provider); + AddMockExternalProvider(Manifest::EXTERNAL_PREF); // Verify that starting with no providers loads no extensions. service()->Init(); @@ -6221,8 +6169,7 @@ InitializeEmptyExtensionService(); MockExternalProvider* provider = - new MockExternalProvider(service(), Manifest::EXTERNAL_PREF); - AddMockExternalProvider(provider); + AddMockExternalProvider(Manifest::EXTERNAL_PREF); service()->external_install_manager()->UpdateExternalExtensionAlert(); // Should return false, meaning there aren't any extensions that the user @@ -6243,11 +6190,7 @@ provider->UpdateOrAddExtension( hosted_app, "1.0.0.0", data_dir().AppendASCII("hosted_app.crx")); - content::WindowedNotificationObserver observer( - extensions::NOTIFICATION_CRX_INSTALLER_DONE, - content::NotificationService::AllSources()); - service()->CheckForExternalUpdates(); - observer.Wait(); + WaitForExternalExtensionInstalled(); EXPECT_FALSE(HasExternalInstallErrors(service())); // Another normal extension, but installed externally. @@ -6255,11 +6198,7 @@ provider->UpdateOrAddExtension( page_action, "1.0.0.0", data_dir().AppendASCII("page_action.crx")); - content::WindowedNotificationObserver observer2( - extensions::NOTIFICATION_CRX_INSTALLER_DONE, - content::NotificationService::AllSources()); - service()->CheckForExternalUpdates(); - observer2.Wait(); + WaitForExternalExtensionInstalled(); EXPECT_TRUE(HasExternalInstallErrors(service())); } @@ -6271,17 +6210,12 @@ InitializeEmptyExtensionService(); MockExternalProvider* provider = - new MockExternalProvider(service(), Manifest::EXTERNAL_PREF); - AddMockExternalProvider(provider); + AddMockExternalProvider(Manifest::EXTERNAL_PREF); provider->UpdateOrAddExtension( page_action, "1.0.0.0", data_dir().AppendASCII("page_action.crx")); + WaitForExternalExtensionInstalled(); - content::WindowedNotificationObserver observer( - extensions::NOTIFICATION_CRX_INSTALLER_DONE, - content::NotificationService::AllSources()); - service()->CheckForExternalUpdates(); - observer.Wait(); EXPECT_TRUE(HasExternalInstallErrors(service())); EXPECT_FALSE(service()->IsExtensionEnabled(page_action)); @@ -6340,8 +6274,7 @@ InitializeEmptyExtensionService(); MockExternalProvider* provider = - new MockExternalProvider(service(), Manifest::EXTERNAL_PREF); - AddMockExternalProvider(provider); + AddMockExternalProvider(Manifest::EXTERNAL_PREF); provider->UpdateOrAddExtension( page_action, "1.0.0.0", data_dir().AppendASCII("page_action.crx")); @@ -6389,8 +6322,7 @@ InitializeEmptyExtensionService(); MockExternalProvider* reg_provider = - new MockExternalProvider(service(), Manifest::EXTERNAL_REGISTRY); - AddMockExternalProvider(reg_provider); + AddMockExternalProvider(Manifest::EXTERNAL_REGISTRY); std::string extension_info[][3] = { // {id, path, version} @@ -6402,11 +6334,7 @@ reg_provider->UpdateOrAddExtension( extension_info[i][0], extension_info[i][1], data_dir().AppendASCII(extension_info[i][2])); - content::WindowedNotificationObserver observer( - extensions::NOTIFICATION_CRX_INSTALLER_DONE, - content::NotificationService::AllSources()); - service()->CheckForExternalUpdates(); - observer.Wait(); + WaitForExternalExtensionInstalled(); const size_t expected_error_count = i + 1u; EXPECT_EQ( expected_error_count, @@ -6457,8 +6385,7 @@ InitializeExtensionService(params); MockExternalProvider* provider = - new MockExternalProvider(service(), Manifest::EXTERNAL_PREF); - AddMockExternalProvider(provider); + AddMockExternalProvider(Manifest::EXTERNAL_PREF); std::vector<BubbleErrorsTestData> data; data.push_back(BubbleErrorsTestData( @@ -6485,13 +6412,9 @@ content::WindowedNotificationObserver global_error_observer( chrome::NOTIFICATION_GLOBAL_ERRORS_CHANGED, content::NotificationService::AllSources()); - content::WindowedNotificationObserver observer( - extensions::NOTIFICATION_CRX_INSTALLER_DONE, - content::NotificationService::AllSources()); provider->UpdateOrAddExtension(data[i].id, data[i].version, data[i].crx_path); - service()->CheckForExternalUpdates(); - observer.Wait(); + WaitForExternalExtensionInstalled(); // Make sure ExternalInstallError::OnDialogReady() fires. global_error_observer.Wait(); @@ -6538,14 +6461,10 @@ content::WindowedNotificationObserver global_error_observer( chrome::NOTIFICATION_GLOBAL_ERRORS_CHANGED, content::NotificationService::AllSources()); - content::WindowedNotificationObserver observer( - extensions::NOTIFICATION_CRX_INSTALLER_DONE, - content::NotificationService::AllSources()); provider->UpdateOrAddExtension( updates_from_webstore3, "1", temp_dir().GetPath().AppendASCII("webstore3.crx")); - service()->CheckForExternalUpdates(); - observer.Wait(); + WaitForExternalExtensionInstalled(); // Make sure ExternalInstallError::OnDialogReady() fires. global_error_observer.Wait(); @@ -6576,8 +6495,7 @@ InitializeExtensionService(params); MockExternalProvider* provider = - new MockExternalProvider(service(), Manifest::EXTERNAL_PREF); - AddMockExternalProvider(provider); + AddMockExternalProvider(Manifest::EXTERNAL_PREF); std::vector<BubbleErrorsTestData> data; data.push_back(BubbleErrorsTestData( @@ -6596,13 +6514,9 @@ content::WindowedNotificationObserver global_error_observer( chrome::NOTIFICATION_GLOBAL_ERRORS_CHANGED, content::NotificationService::AllSources()); - content::WindowedNotificationObserver observer( - extensions::NOTIFICATION_CRX_INSTALLER_DONE, - content::NotificationService::AllSources()); provider->UpdateOrAddExtension(data[0].id, data[0].version, data[0].crx_path); - service()->CheckForExternalUpdates(); - observer.Wait(); + WaitForExternalExtensionInstalled(); // Make sure ExternalInstallError::OnDialogReady() fires. global_error_observer.Wait(); @@ -6637,13 +6551,9 @@ content::WindowedNotificationObserver global_error_observer( chrome::NOTIFICATION_GLOBAL_ERRORS_CHANGED, content::NotificationService::AllSources()); - content::WindowedNotificationObserver observer( - extensions::NOTIFICATION_CRX_INSTALLER_DONE, - content::NotificationService::AllSources()); provider->UpdateOrAddExtension(data[1].id, data[1].version, data[1].crx_path); - service()->CheckForExternalUpdates(); - observer.Wait(); + WaitForExternalExtensionInstalled(); // Make sure ExternalInstallError::OnDialogReady() fires. global_error_observer.Wait(); @@ -6680,15 +6590,10 @@ crx_path); MockExternalProvider* provider = - new MockExternalProvider(service(), Manifest::EXTERNAL_PREF); - AddMockExternalProvider(provider); + AddMockExternalProvider(Manifest::EXTERNAL_PREF); provider->UpdateOrAddExtension(updates_from_webstore, "1", crx_path); + WaitForExternalExtensionInstalled(); - content::WindowedNotificationObserver observer( - extensions::NOTIFICATION_CRX_INSTALLER_DONE, - content::NotificationService::AllSources()); - service()->CheckForExternalUpdates(); - observer.Wait(); EXPECT_TRUE(HasExternalInstallErrors(service())); ASSERT_TRUE(GetError(updates_from_webstore)); EXPECT_EQ(ExternalInstallError::BUBBLE_ALERT, @@ -6709,15 +6614,10 @@ crx_path); MockExternalProvider* provider = - new MockExternalProvider(service(), Manifest::EXTERNAL_PREF); - AddMockExternalProvider(provider); + AddMockExternalProvider(Manifest::EXTERNAL_PREF); provider->UpdateOrAddExtension(updates_from_webstore, "1", crx_path); + WaitForExternalExtensionInstalled(); - content::WindowedNotificationObserver observer( - extensions::NOTIFICATION_CRX_INSTALLER_DONE, - content::NotificationService::AllSources()); - service()->CheckForExternalUpdates(); - observer.Wait(); EXPECT_TRUE(HasExternalInstallErrors(service())); ASSERT_TRUE(GetError(updates_from_webstore)); EXPECT_NE(ExternalInstallError::BUBBLE_ALERT, @@ -6741,15 +6641,10 @@ crx_path); MockExternalProvider* provider = - new MockExternalProvider(service_, Manifest::EXTERNAL_PREF); - AddMockExternalProvider(provider); + AddMockExternalProvider(Manifest::EXTERNAL_PREF); provider->UpdateOrAddExtension(updates_from_webstore, "1", crx_path); + WaitForExternalExtensionInstalled(); - content::WindowedNotificationObserver observer( - extensions::NOTIFICATION_CRX_INSTALLER_DONE, - content::NotificationService::AllSources()); - service_->CheckForExternalUpdates(); - observer.Wait(); EXPECT_TRUE(HasExternalInstallErrors(service_)); // We check both enabled and disabled, since these are "eventually exclusive" @@ -6784,15 +6679,10 @@ crx_path); MockExternalProvider* provider = - new MockExternalProvider(service_, Manifest::EXTERNAL_PREF); - AddMockExternalProvider(provider); + AddMockExternalProvider(Manifest::EXTERNAL_PREF); provider->UpdateOrAddExtension(updates_from_webstore, "1", crx_path); + WaitForExternalExtensionInstalled(); - content::WindowedNotificationObserver observer( - extensions::NOTIFICATION_CRX_INSTALLER_DONE, - content::NotificationService::AllSources()); - service_->CheckForExternalUpdates(); - observer.Wait(); EXPECT_TRUE(HasExternalInstallErrors(service_)); // We check both enabled and disabled, since these are "eventually exclusive" @@ -6826,8 +6716,7 @@ // Register and install an external extension. MockExternalProvider* provider = - new MockExternalProvider(service(), Manifest::EXTERNAL_PREF); - AddMockExternalProvider(provider); + AddMockExternalProvider(Manifest::EXTERNAL_PREF); provider->UpdateOrAddExtension(good_crx, "1.0.0.0", data_dir().AppendASCII("good.crx"));
diff --git a/chrome/browser/first_run/first_run_browsertest.cc b/chrome/browser/first_run/first_run_browsertest.cc index 321d37a..4aa424e 100644 --- a/chrome/browser/first_run/first_run_browsertest.cc +++ b/chrome/browser/first_run/first_run_browsertest.cc
@@ -93,7 +93,8 @@ ASSERT_TRUE(text_.get()); ASSERT_TRUE(base::CreateTemporaryFile(&prefs_file_)); - EXPECT_TRUE(base::WriteFile(prefs_file_, text_->c_str(), text_->size())); + EXPECT_EQ(static_cast<int>(text_->size()), + base::WriteFile(prefs_file_, text_->c_str(), text_->size())); first_run::SetMasterPrefsPathForTesting(prefs_file_); // This invokes BrowserMain, and does the import, so must be done last.
diff --git a/chrome/browser/flag_descriptions.cc b/chrome/browser/flag_descriptions.cc index e0ce219..0421950 100644 --- a/chrome/browser/flag_descriptions.cc +++ b/chrome/browser/flag_descriptions.cc
@@ -1951,6 +1951,17 @@ #endif // defined(OS_ANDROID) +// In-Product Help flags + +#if defined(OS_ANDROID) + +const char kEnableIphDemoMode[] = "In-Product Help Demo Mode"; + +const char kEnableIphDemoModeDescription[] = + "Enables In-Product Help demo mode on Android."; + +#endif // defined(OS_ANDROID) + // Settings window flags const char kSettingsWindowName[] = "Show settings in a window"; @@ -2759,6 +2770,10 @@ const char kOmniboxEntitySuggestionsDescription[] = "Enable receiving entity suggestions in Omnibox."; +const char kPauseBackgroundTabsName[] = "Pause background tabs"; +const char kPauseBackgroundTabsDescription[] = + "Pause timers in background tabs after 5 minutes on desktop."; + #endif // defined(OS_CHROMEOS) || defined(OS_LINUX) || defined(OS_MACOSX) || // defined(OS_WIN)
diff --git a/chrome/browser/flag_descriptions.h b/chrome/browser/flag_descriptions.h index b0bae0c..09f2ab69 100644 --- a/chrome/browser/flag_descriptions.h +++ b/chrome/browser/flag_descriptions.h
@@ -2149,6 +2149,18 @@ #endif // defined(OS_ANDROID) +// In-Product Help flags + +#if defined(OS_ANDROID) + +// The name of the In-Product Help demo mode in about:flags. +extern const char kEnableIphDemoMode[]; + +// Description of the In-Product Help demo mode in about:flags. +extern const char kEnableIphDemoModeDescription[]; + +#endif // defined(OS_ANDROID) + // Settings window flags // An about::flags experiment title to show settings in a separate window @@ -2980,6 +2992,9 @@ // Description of the flag that enables entity suggestions. extern const char kOmniboxEntitySuggestionsDescription[]; +extern const char kPauseBackgroundTabsName[]; +extern const char kPauseBackgroundTabsDescription[]; + #endif // defined(OS_CHROMEOS) || defined(OS_LINUX) || defined(OS_MACOSX) || // defined(OS_WIN)
diff --git a/chrome/browser/geolocation/geolocation_permission_context_unittest.cc b/chrome/browser/geolocation/geolocation_permission_context_unittest.cc index d2b6389..7ce6e59 100644 --- a/chrome/browser/geolocation/geolocation_permission_context_unittest.cc +++ b/chrome/browser/geolocation/geolocation_permission_context_unittest.cc
@@ -1340,8 +1340,6 @@ SearchGeolocationService::Factory::GetForBrowserContext(profile()); geo_service->SetSearchEngineDelegateForTest( base::MakeUnique<TestSearchEngineDelegate>()); - geo_service->SetLocationSettingsForTest( - base::MakeUnique<MockLocationSettings>()); Profile* otr_profile = profile()->GetOffTheRecordProfile();
diff --git a/chrome/browser/media/android/router/OWNERS b/chrome/browser/media/android/router/OWNERS index a1a8cd5..afc407e 100644 --- a/chrome/browser/media/android/router/OWNERS +++ b/chrome/browser/media/android/router/OWNERS
@@ -2,4 +2,5 @@ mfoltz@chromium.org mlamouri@chromium.org +# TEAM: media-dev@chromium.org # COMPONENT: Blink>PresentationAPI
diff --git a/chrome/browser/media_galleries/fileapi/native_media_file_util_unittest.cc b/chrome/browser/media_galleries/fileapi/native_media_file_util_unittest.cc index 99c1120b..ba8ffd5 100644 --- a/chrome/browser/media_galleries/fileapi/native_media_file_util_unittest.cc +++ b/chrome/browser/media_galleries/fileapi/native_media_file_util_unittest.cc
@@ -333,7 +333,8 @@ base::FilePath src_path = root_path().AppendASCII("foo.jpg"); FileSystemURL src_url = CreateURL(FPL("foo.jpg")); static const char kDummyData[] = "dummy"; - ASSERT_TRUE(base::WriteFile(src_path, kDummyData, strlen(kDummyData))); + ASSERT_EQ(static_cast<int>(strlen(kDummyData)), + base::WriteFile(src_path, kDummyData, strlen(kDummyData))); for (size_t i = 0; i < arraysize(kFilteringTestCases); ++i) { if (loop_count == 0 && kFilteringTestCases[i].is_directory) { @@ -445,8 +446,8 @@ base::FilePath src_path = root_path().AppendASCII("foo.jpg"); FileSystemURL src_url = CreateURL(FPL("foo.jpg")); static const char kDummyData[] = "dummy"; - ASSERT_TRUE( - base::WriteFile(src_path, kDummyData, strlen(kDummyData))); + ASSERT_EQ(static_cast<int>(strlen(kDummyData)), + base::WriteFile(src_path, kDummyData, strlen(kDummyData))); FileSystemURL root_url = CreateURL(FPL("")); FileSystemURL url = CreateURL(kFilteringTestCases[i].path);
diff --git a/chrome/browser/net/net_error_tab_helper.cc b/chrome/browser/net/net_error_tab_helper.cc index 7453d790..a7f9587 100644 --- a/chrome/browser/net/net_error_tab_helper.cc +++ b/chrome/browser/net/net_error_tab_helper.cc
@@ -26,9 +26,7 @@ #include "url/gurl.h" #if defined(OS_ANDROID) -#include "base/guid.h" -#include "chrome/browser/android/offline_pages/request_coordinator_factory.h" -#include "components/offline_pages/core/background/request_coordinator.h" +#include "chrome/browser/android/offline_pages/offline_page_utils.h" #include "components/offline_pages/core/client_namespace_constants.h" #endif // defined(OS_ANDROID) @@ -292,15 +290,9 @@ #if defined(OS_ANDROID) void NetErrorTabHelper::DownloadPageLaterHelper(const GURL& page_url) { - offline_pages::RequestCoordinator* request_coordinator = - offline_pages::RequestCoordinatorFactory::GetForBrowserContext( - web_contents()->GetBrowserContext()); - DCHECK(request_coordinator) << "No RequestCoordinator for SavePageLater"; - offline_pages::RequestCoordinator::SavePageLaterParams params; - params.url = page_url; - params.client_id = offline_pages::ClientId(offline_pages::kAsyncNamespace, - base::GenerateGUID()); - request_coordinator->SavePageLater(params); + offline_pages::OfflinePageUtils::ScheduleDownload( + web_contents(), offline_pages::kAsyncNamespace, page_url, + offline_pages::OfflinePageUtils::DownloadUIActionFlags::PROMPT_DUPLICATE); } #endif // defined(OS_ANDROID)
diff --git a/chrome/browser/net/spdyproxy/data_reduction_proxy_settings_android.cc b/chrome/browser/net/spdyproxy/data_reduction_proxy_settings_android.cc index d6370f98..c893493 100644 --- a/chrome/browser/net/spdyproxy/data_reduction_proxy_settings_android.cc +++ b/chrome/browser/net/spdyproxy/data_reduction_proxy_settings_android.cc
@@ -6,16 +6,23 @@ #include <stdint.h> +#include <map> +#include <string> + #include "base/android/jni_android.h" #include "base/android/jni_string.h" +#include "base/strings/string_piece.h" #include "base/values.h" #include "chrome/browser/net/spdyproxy/data_reduction_proxy_chrome_settings.h" #include "chrome/browser/net/spdyproxy/data_reduction_proxy_chrome_settings_factory.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/profiles/profile_manager.h" #include "chrome/common/pref_names.h" +#include "components/data_reduction_proxy/core/browser/data_reduction_proxy_compression_stats.h" #include "components/data_reduction_proxy/core/browser/data_reduction_proxy_metrics.h" +#include "components/data_reduction_proxy/core/browser/data_reduction_proxy_service.h" #include "components/data_reduction_proxy/core/browser/data_reduction_proxy_settings.h" +#include "components/data_reduction_proxy/core/browser/data_usage_store.h" #include "components/data_reduction_proxy/core/common/data_reduction_proxy_event_store.h" #include "components/data_reduction_proxy/core/common/data_reduction_proxy_params.h" #include "components/data_reduction_proxy/core/common/data_reduction_proxy_pref_names.h" @@ -29,7 +36,28 @@ using base::android::ScopedJavaLocalRef; using data_reduction_proxy::DataReductionProxySettings; -DataReductionProxySettingsAndroid::DataReductionProxySettingsAndroid() { +namespace { + +constexpr size_t kBucketsPerDay = + 24 * 60 / data_reduction_proxy::kDataUsageBucketLengthInMinutes; + +struct DataUsageForHost { + DataUsageForHost() : data_used(0), original_size(0) {} + + int64_t data_used; + int64_t original_size; +}; + +} // namespace + +DataReductionProxySettingsAndroid::DataReductionProxySettingsAndroid() + : weak_factory_(this) {} + +DataReductionProxySettingsAndroid::DataReductionProxySettingsAndroid( + JNIEnv* env, + const base::android::JavaParamRef<jobject>& obj) + : weak_factory_(this) { + j_settings_obj_ = JavaObjectWeakGlobalRef(env, obj); } DataReductionProxySettingsAndroid::~DataReductionProxySettingsAndroid() { @@ -66,6 +94,12 @@ return Settings()->GetDataReductionLastUpdateTime(); } +void DataReductionProxySettingsAndroid::ClearDataSavingStatistics( + JNIEnv* env, + const base::android::JavaParamRef<jobject>& obj) { + Settings()->ClearDataSavingStatistics(); +} + base::android::ScopedJavaLocalRef<jobject> DataReductionProxySettingsAndroid::GetContentLengths( JNIEnv* env, @@ -174,7 +208,63 @@ return ConvertUTF8ToJavaString(env, event_store->SanitizedLastBypassEvent()); } +void DataReductionProxySettingsAndroid::QueryDataUsage( + JNIEnv* env, + const JavaParamRef<jobject>& obj, + const JavaParamRef<jobject>& j_result_obj, + jint num_days) { + DCHECK(num_days <= data_reduction_proxy::kDataUsageHistoryNumDays); + j_query_result_obj_.Reset(env, j_result_obj); + num_day_for_query_ = num_days; + Settings() + ->data_reduction_proxy_service() + ->compression_stats() + ->GetHistoricalDataUsage(base::Bind( + &DataReductionProxySettingsAndroid::OnQueryDataUsageComplete, + weak_factory_.GetWeakPtr())); +} + +void DataReductionProxySettingsAndroid::OnQueryDataUsageComplete( + std::unique_ptr<std::vector<data_reduction_proxy::DataUsageBucket>> + data_usage) { + if (j_query_result_obj_.is_null()) + return; + + JNIEnv* env = base::android::AttachCurrentThread(); + + std::map<base::StringPiece, DataUsageForHost> per_site_usage_map; + + // Data usage is sorted chronologically with the last entry corresponding to + // |base::Time::Now()|. + const size_t num_buckets_to_display = num_day_for_query_ * kBucketsPerDay; + for (auto data_usage_it = data_usage->size() > num_buckets_to_display + ? data_usage->end() - num_buckets_to_display + : data_usage->begin(); + data_usage_it != data_usage->end(); ++data_usage_it) { + for (const auto& connection_usage : data_usage_it->connection_usage()) { + for (const auto& site_usage : connection_usage.site_usage()) { + DataUsageForHost& usage = per_site_usage_map[site_usage.hostname()]; + usage.data_used += site_usage.data_used(); + usage.original_size += site_usage.original_size(); + } + } + } + + for (const auto& site_bucket : per_site_usage_map) { + Java_DataReductionProxySettings_createDataUseItemAndAddToList( + env, j_query_result_obj_.obj(), + ConvertUTF8ToJavaString(env, site_bucket.first), + site_bucket.second.data_used, site_bucket.second.original_size); + } + + Java_DataReductionProxySettings_onQueryDataUsageComplete( + env, j_settings_obj_.get(env), j_query_result_obj_.obj()); + + j_query_result_obj_.Release(); +} + // Used by generated jni code. static jlong Init(JNIEnv* env, const JavaParamRef<jobject>& obj) { - return reinterpret_cast<intptr_t>(new DataReductionProxySettingsAndroid()); + return reinterpret_cast<intptr_t>( + new DataReductionProxySettingsAndroid(env, obj)); }
diff --git a/chrome/browser/net/spdyproxy/data_reduction_proxy_settings_android.h b/chrome/browser/net/spdyproxy/data_reduction_proxy_settings_android.h index 1d29614..835a5b7 100644 --- a/chrome/browser/net/spdyproxy/data_reduction_proxy_settings_android.h +++ b/chrome/browser/net/spdyproxy/data_reduction_proxy_settings_android.h
@@ -5,14 +5,20 @@ #ifndef CHROME_BROWSER_NET_SPDYPROXY_DATA_REDUCTION_PROXY_SETTINGS_ANDROID_H_ #define CHROME_BROWSER_NET_SPDYPROXY_DATA_REDUCTION_PROXY_SETTINGS_ANDROID_H_ -#include <memory> +#include <jni.h> +#include <memory> +#include <vector> + +#include "base/android/jni_android.h" #include "base/android/jni_string.h" #include "base/android/jni_weak_ref.h" #include "base/android/scoped_java_ref.h" #include "base/compiler_specific.h" #include "base/gtest_prod_util.h" #include "base/macros.h" +#include "base/memory/weak_ptr.h" +#include "components/data_reduction_proxy/proto/data_store.pb.h" #include "components/prefs/pref_member.h" using base::android::ScopedJavaLocalRef; @@ -28,7 +34,9 @@ // be called from there. class DataReductionProxySettingsAndroid { public: - DataReductionProxySettingsAndroid(); + DataReductionProxySettingsAndroid( + JNIEnv* env, + const base::android::JavaParamRef<jobject>& obj); virtual ~DataReductionProxySettingsAndroid(); @@ -51,6 +59,9 @@ jlong GetDataReductionLastUpdateTime( JNIEnv* env, const base::android::JavaParamRef<jobject>& obj); + void ClearDataSavingStatistics( + JNIEnv* env, + const base::android::JavaParamRef<jobject>& obj); jlong GetTotalHttpContentLengthSaved( JNIEnv* env, const base::android::JavaParamRef<jobject>& obj); @@ -96,19 +107,39 @@ JNIEnv* env, const base::android::JavaParamRef<jobject>& obj); + // Gets the historical data usage for |numDays| and adds them to a list that + // groups data use by hostname. + void QueryDataUsage(JNIEnv* env, + const base::android::JavaParamRef<jobject>& obj, + const base::android::JavaParamRef<jobject>& j_result_obj, + jint num_days); + void OnQueryDataUsageComplete( + std::unique_ptr<std::vector<data_reduction_proxy::DataUsageBucket>> + data_usage); + // Registers the native methods to be call from Java. static bool Register(JNIEnv* env); + JavaObjectWeakGlobalRef j_settings_obj_; + base::android::ScopedJavaGlobalRef<jobject> j_query_result_obj_; + int num_day_for_query_; + private: friend class DataReductionProxySettingsAndroidTest; + friend class TestDataReductionProxySettingsAndroid; FRIEND_TEST_ALL_PREFIXES(DataReductionProxySettingsAndroidTest, TestGetDailyContentLengths); + // For testing purposes. + DataReductionProxySettingsAndroid(); + ScopedJavaLocalRef<jlongArray> GetDailyContentLengths(JNIEnv* env, const char* pref_name); virtual data_reduction_proxy::DataReductionProxySettings* Settings(); + base::WeakPtrFactory<DataReductionProxySettingsAndroid> weak_factory_; + DISALLOW_COPY_AND_ASSIGN(DataReductionProxySettingsAndroid); };
diff --git a/chrome/browser/notifications/message_center_display_service.cc b/chrome/browser/notifications/message_center_display_service.cc index 8041092..8805f1c3 100644 --- a/chrome/browser/notifications/message_center_display_service.cc +++ b/chrome/browser/notifications/message_center_display_service.cc
@@ -37,7 +37,7 @@ } void MessageCenterDisplayService::GetDisplayed( - const DisplayedNotificationsCallback& callback) const { + const DisplayedNotificationsCallback& callback) { auto displayed_notifications = base::MakeUnique<std::set<std::string>>(ui_manager_->GetAllIdsByProfile( NotificationUIManager::GetProfileID(profile_)));
diff --git a/chrome/browser/notifications/message_center_display_service.h b/chrome/browser/notifications/message_center_display_service.h index 2dcf0e9..f475045 100644 --- a/chrome/browser/notifications/message_center_display_service.h +++ b/chrome/browser/notifications/message_center_display_service.h
@@ -27,8 +27,7 @@ const Notification& notification) override; void Close(NotificationCommon::Type notification_type, const std::string& notification_id) override; - void GetDisplayed( - const DisplayedNotificationsCallback& callback) const override; + void GetDisplayed(const DisplayedNotificationsCallback& callback) override; private: Profile* profile_;
diff --git a/chrome/browser/notifications/native_notification_display_service.cc b/chrome/browser/notifications/native_notification_display_service.cc index b9aa26d6..833fb970 100644 --- a/chrome/browser/notifications/native_notification_display_service.cc +++ b/chrome/browser/notifications/native_notification_display_service.cc
@@ -80,7 +80,7 @@ } void NativeNotificationDisplayService::GetDisplayed( - const DisplayedNotificationsCallback& callback) const { + const DisplayedNotificationsCallback& callback) { return notification_bridge_->GetDisplayed( GetProfileId(profile_), profile_->IsOffTheRecord(), callback); }
diff --git a/chrome/browser/notifications/native_notification_display_service.h b/chrome/browser/notifications/native_notification_display_service.h index 309777c..f5c8fee3 100644 --- a/chrome/browser/notifications/native_notification_display_service.h +++ b/chrome/browser/notifications/native_notification_display_service.h
@@ -38,8 +38,7 @@ const Notification& notification) override; void Close(NotificationCommon::Type notification_type, const std::string& notification_id) override; - void GetDisplayed( - const DisplayedNotificationsCallback& callback) const override; + void GetDisplayed(const DisplayedNotificationsCallback& callback) override; // Used by the notification bridge to propagate back events (click, close...). void ProcessNotificationOperation(NotificationCommon::Operation operation,
diff --git a/chrome/browser/notifications/notification_display_service.h b/chrome/browser/notifications/notification_display_service.h index 1eeada6..92cf5ece 100644 --- a/chrome/browser/notifications/notification_display_service.h +++ b/chrome/browser/notifications/notification_display_service.h
@@ -42,8 +42,7 @@ // Writes the ids of all currently displaying notifications and // invokes |callback| with the result once known. - virtual void GetDisplayed( - const DisplayedNotificationsCallback& callback) const = 0; + virtual void GetDisplayed(const DisplayedNotificationsCallback& callback) = 0; private: DISALLOW_COPY_AND_ASSIGN(NotificationDisplayService);
diff --git a/chrome/browser/notifications/platform_notification_service_unittest.cc b/chrome/browser/notifications/platform_notification_service_unittest.cc index 4812b40..840d32c 100644 --- a/chrome/browser/notifications/platform_notification_service_unittest.cc +++ b/chrome/browser/notifications/platform_notification_service_unittest.cc
@@ -113,7 +113,7 @@ void DidGetDisplayedNotifications( std::unique_ptr<std::set<std::string>> displayed_notifications, - bool supports_synchronization) const { + bool supports_synchronization) { displayed_notifications_ = std::move(displayed_notifications); } @@ -152,7 +152,7 @@ // Returns the Profile to be used for these tests. Profile* profile() const { return profile_; } - size_t GetNotificationCount() const { + size_t GetNotificationCount() { display_service()->GetDisplayed(base::Bind( &PlatformNotificationServiceTest::DidGetDisplayedNotifications, base::Unretained(this))); @@ -182,7 +182,7 @@ std::unique_ptr<TestingProfileManager> profile_manager_; TestingProfile* profile_; content::TestBrowserThreadBundle thread_bundle_; - mutable std::unique_ptr<std::set<std::string>> displayed_notifications_; + std::unique_ptr<std::set<std::string>> displayed_notifications_; }; TEST_F(PlatformNotificationServiceTest, DisplayPageDisplayedEvent) {
diff --git a/chrome/browser/notifications/stub_notification_display_service.cc b/chrome/browser/notifications/stub_notification_display_service.cc index 981d472..d8a8a10 100644 --- a/chrome/browser/notifications/stub_notification_display_service.cc +++ b/chrome/browser/notifications/stub_notification_display_service.cc
@@ -78,7 +78,7 @@ } void StubNotificationDisplayService::GetDisplayed( - const DisplayedNotificationsCallback& callback) const { + const DisplayedNotificationsCallback& callback) { std::unique_ptr<std::set<std::string>> notifications = base::MakeUnique<std::set<std::string>>();
diff --git a/chrome/browser/notifications/stub_notification_display_service.h b/chrome/browser/notifications/stub_notification_display_service.h index e87800c..55446688 100644 --- a/chrome/browser/notifications/stub_notification_display_service.h +++ b/chrome/browser/notifications/stub_notification_display_service.h
@@ -42,8 +42,7 @@ const Notification& notification) override; void Close(NotificationCommon::Type notification_type, const std::string& notification_id) override; - void GetDisplayed( - const DisplayedNotificationsCallback& callback) const override; + void GetDisplayed(const DisplayedNotificationsCallback& callback) override; private: // Data to store for a notification that's being shown through this service.
diff --git a/chrome/browser/page_load_metrics/observers/from_gws_page_load_metrics_observer.cc b/chrome/browser/page_load_metrics/observers/from_gws_page_load_metrics_observer.cc index 3cf2d12..934c8ce 100644 --- a/chrome/browser/page_load_metrics/observers/from_gws_page_load_metrics_observer.cc +++ b/chrome/browser/page_load_metrics/observers/from_gws_page_load_metrics_observer.cc
@@ -96,6 +96,14 @@ "PageLoad.Clients.FromGoogleSearch.Experimental.AbortTiming.Background." "AfterPaint.BeforeInteraction"; +const char kHistogramFromGWSForegroundDuration[] = + "PageLoad.Clients.FromGoogleSearch.PageTiming.ForegroundDuration"; +const char kHistogramFromGWSForegroundDurationAfterPaint[] = + "PageLoad.Clients.FromGoogleSearch.PageTiming.ForegroundDuration." + "AfterPaint"; +const char kHistogramFromGWSForegroundDurationNoCommit[] = + "PageLoad.Clients.FromGoogleSearch.PageTiming.ForegroundDuration.NoCommit"; + } // namespace internal namespace { @@ -214,6 +222,29 @@ } } +void LogForegroundDurations(const page_load_metrics::PageLoadTiming& timing, + const page_load_metrics::PageLoadExtraInfo& info, + base::TimeTicks app_background_time) { + base::Optional<base::TimeDelta> foreground_duration = + GetInitialForegroundDuration(info, app_background_time); + if (!foreground_duration) + return; + + if (info.did_commit) { + PAGE_LOAD_LONG_HISTOGRAM(internal::kHistogramFromGWSForegroundDuration, + foreground_duration.value()); + if (timing.first_paint && timing.first_paint < foreground_duration) { + PAGE_LOAD_LONG_HISTOGRAM( + internal::kHistogramFromGWSForegroundDurationAfterPaint, + foreground_duration.value() - timing.first_paint.value()); + } + } else { + PAGE_LOAD_LONG_HISTOGRAM( + internal::kHistogramFromGWSForegroundDurationNoCommit, + foreground_duration.value()); + } +} + bool WasAbortedInForeground( const page_load_metrics::PageLoadExtraInfo& info, const page_load_metrics::PageAbortInfo& abort_info) { @@ -455,6 +486,14 @@ return CONTINUE_OBSERVING; } +page_load_metrics::PageLoadMetricsObserver::ObservePolicy +FromGWSPageLoadMetricsObserver::FlushMetricsOnAppEnterBackground( + const page_load_metrics::PageLoadTiming& timing, + const page_load_metrics::PageLoadExtraInfo& extra_info) { + logger_.FlushMetricsOnAppEnterBackground(timing, extra_info); + return STOP_OBSERVING; +} + void FromGWSPageLoadMetricsObserver::OnDomContentLoadedEventStart( const page_load_metrics::PageLoadTiming& timing, const page_load_metrics::PageLoadExtraInfo& extra_info) { @@ -546,6 +585,8 @@ first_user_interaction_after_paint_)) { LogAbortsAfterPaintBeforeInteraction(abort_info); } + + LogForegroundDurations(timing, extra_info, base::TimeTicks()); } void FromGWSPageLoadMetricsLogger::OnFailedProvisionalLoad( @@ -559,6 +600,9 @@ return; LogProvisionalAborts(abort_info); + + LogForegroundDurations(page_load_metrics::PageLoadTiming(), extra_info, + base::TimeTicks()); } bool FromGWSPageLoadMetricsLogger::ShouldLogFailedProvisionalLoadMetrics() { @@ -705,3 +749,9 @@ base::TimeTicks::Now() - navigation_start_; } } + +void FromGWSPageLoadMetricsLogger::FlushMetricsOnAppEnterBackground( + const page_load_metrics::PageLoadTiming& timing, + const page_load_metrics::PageLoadExtraInfo& extra_info) { + LogForegroundDurations(timing, extra_info, base::TimeTicks::Now()); +}
diff --git a/chrome/browser/page_load_metrics/observers/from_gws_page_load_metrics_observer.h b/chrome/browser/page_load_metrics/observers/from_gws_page_load_metrics_observer.h index 90ae1d0..9f961807 100644 --- a/chrome/browser/page_load_metrics/observers/from_gws_page_load_metrics_observer.h +++ b/chrome/browser/page_load_metrics/observers/from_gws_page_load_metrics_observer.h
@@ -31,6 +31,9 @@ extern const char kHistogramFromGWSAbortNewNavigationBeforePaint[]; extern const char kHistogramFromGWSAbortNewNavigationBeforeInteraction[]; extern const char kHistogramFromGWSAbortReloadBeforeInteraction[]; +extern const char kHistogramFromGWSForegroundDuration[]; +extern const char kHistogramFromGWSForegroundDurationAfterPaint[]; +extern const char kHistogramFromGWSForegroundDurationNoCommit[]; } // namespace internal @@ -85,6 +88,9 @@ void OnParseStop(const page_load_metrics::PageLoadTiming& timing, const page_load_metrics::PageLoadExtraInfo& extra_info); void OnUserInput(const blink::WebInputEvent& event); + void FlushMetricsOnAppEnterBackground( + const page_load_metrics::PageLoadTiming& timing, + const page_load_metrics::PageLoadExtraInfo& extra_info); // The methods below are public only for testing. static bool IsGoogleSearchHostname(base::StringPiece host); @@ -144,6 +150,10 @@ bool started_in_foreground) override; ObservePolicy OnCommit(content::NavigationHandle* navigation_handle) override; + ObservePolicy FlushMetricsOnAppEnterBackground( + const page_load_metrics::PageLoadTiming& timing, + const page_load_metrics::PageLoadExtraInfo& extra_info) override; + void OnDomContentLoadedEventStart( const page_load_metrics::PageLoadTiming& timing, const page_load_metrics::PageLoadExtraInfo& extra_info) override;
diff --git a/chrome/browser/payments/android/chrome_payments_jni_registrar.cc b/chrome/browser/payments/android/chrome_payments_jni_registrar.cc new file mode 100644 index 0000000..bd40582 --- /dev/null +++ b/chrome/browser/payments/android/chrome_payments_jni_registrar.cc
@@ -0,0 +1,26 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/payments/android/chrome_payments_jni_registrar.h" + +#include "base/android/jni_android.h" +#include "base/android/jni_registrar.h" +#include "base/macros.h" +#include "chrome/browser/payments/android/journey_logger_android.h" + +namespace payments { +namespace android { + +static base::android::RegistrationMethod kChromePaymentsRegisteredMethods[] = { + {"JourneyLogger", JourneyLoggerAndroid::Register}, +}; + +bool RegisterChromePayments(JNIEnv* env) { + return base::android::RegisterNativeMethods( + env, kChromePaymentsRegisteredMethods, + arraysize(kChromePaymentsRegisteredMethods)); +} + +} // namespace android +} // namespace payments
diff --git a/chrome/browser/payments/android/chrome_payments_jni_registrar.h b/chrome/browser/payments/android/chrome_payments_jni_registrar.h new file mode 100644 index 0000000..92d3fa1 --- /dev/null +++ b/chrome/browser/payments/android/chrome_payments_jni_registrar.h
@@ -0,0 +1,19 @@ +// 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 CHROME_BROWSER_PAYMENTS_ANDROID_CHROME_PAYMENTS_JNI_REGISTRAR_H_ +#define CHROME_BROWSER_PAYMENTS_ANDROID_CHROME_PAYMENTS_JNI_REGISTRAR_H_ + +#include <jni.h> + +namespace payments { +namespace android { + +// Register all JNI bindings necessary for the chrome payments classes. +bool RegisterChromePayments(JNIEnv* env); + +} // namespace android +} // namespace payments + +#endif // CHROME_BROWSER_PAYMENTS_ANDROID_CHROME_PAYMENTS_JNI_REGISTRAR_H_
diff --git a/components/payments/content/android/journey_logger_android.cc b/chrome/browser/payments/android/journey_logger_android.cc similarity index 74% rename from components/payments/content/android/journey_logger_android.cc rename to chrome/browser/payments/android/journey_logger_android.cc index e373ae8..c13d9e2 100644 --- a/components/payments/content/android/journey_logger_android.cc +++ b/chrome/browser/payments/android/journey_logger_android.cc
@@ -2,10 +2,12 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "components/payments/content/android/journey_logger_android.h" +#include "chrome/browser/payments/android/journey_logger_android.h" #include "base/android/jni_string.h" +#include "chrome/browser/browser_process.h" #include "jni/JourneyLogger_jni.h" +#include "url/gurl.h" namespace payments { namespace { @@ -20,8 +22,11 @@ return RegisterNativesImpl(env); } -JourneyLoggerAndroid::JourneyLoggerAndroid(bool is_incognito) - : journey_logger_(is_incognito) {} +JourneyLoggerAndroid::JourneyLoggerAndroid(bool is_incognito, + const std::string& url) + : journey_logger_(is_incognito, + GURL(url), + g_browser_process->ukm_service()) {} JourneyLoggerAndroid::~JourneyLoggerAndroid() {} @@ -84,6 +89,15 @@ journey_logger_.SetShowCalled(); } +void JourneyLoggerAndroid::SetEventOccurred( + JNIEnv* env, + const base::android::JavaParamRef<jobject>& jcaller, + jint jevent) { + DCHECK_GE(jevent, 0); + DCHECK_LT(jevent, JourneyLogger::Event::EVENT_MAX); + journey_logger_.SetEventOccurred(static_cast<JourneyLogger::Event>(jevent)); +} + void JourneyLoggerAndroid::RecordJourneyStatsHistograms( JNIEnv* env, const base::android::JavaParamRef<jobject>& jcaller, @@ -95,10 +109,13 @@ static_cast<JourneyLogger::CompletionStatus>(jcompletion_status)); } -static jlong InitJourneyLoggerAndroid(JNIEnv* env, - const JavaParamRef<jobject>& jcaller, - jboolean jis_incognito) { - return reinterpret_cast<jlong>(new JourneyLoggerAndroid(jis_incognito)); +static jlong InitJourneyLoggerAndroid( + JNIEnv* env, + const JavaParamRef<jobject>& jcaller, + jboolean jis_incognito, + const base::android::JavaParamRef<jstring>& jurl) { + return reinterpret_cast<jlong>(new JourneyLoggerAndroid( + jis_incognito, ConvertJavaStringToUTF8(env, jurl))); } } // namespace payments
diff --git a/components/payments/content/android/journey_logger_android.h b/chrome/browser/payments/android/journey_logger_android.h similarity index 80% rename from components/payments/content/android/journey_logger_android.h rename to chrome/browser/payments/android/journey_logger_android.h index 69bbc23e..ff8c2c9 100644 --- a/components/payments/content/android/journey_logger_android.h +++ b/chrome/browser/payments/android/journey_logger_android.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 COMPONENTS_PAYMENTS_CONTENT_ANDROID_JOURNEY_LOGGER_ANDROID_H_ -#define COMPONENTS_PAYMENTS_CONTENT_ANDROID_JOURNEY_LOGGER_ANDROID_H_ +#ifndef CHROME_BROWSER_PAYMENTS_ANDROID_JOURNEY_LOGGER_ANDROID_H_ +#define CHROME_BROWSER_PAYMENTS_ANDROID_JOURNEY_LOGGER_ANDROID_H_ #include <jni.h> @@ -19,7 +19,7 @@ // Registers the JNI bindings for this class. static bool Register(JNIEnv* env); - explicit JourneyLoggerAndroid(bool is_incognito); + JourneyLoggerAndroid(bool is_incognito, const std::string& url); ~JourneyLoggerAndroid(); // Message from Java to destroy this object. @@ -49,6 +49,9 @@ jboolean jvalue); void SetShowCalled(JNIEnv* env, const base::android::JavaParamRef<jobject>& jcaller); + void SetEventOccurred(JNIEnv* env, + const base::android::JavaParamRef<jobject>& jcaller, + jint jevent); void RecordJourneyStatsHistograms( JNIEnv* env, const base::android::JavaParamRef<jobject>& jcaller, @@ -62,4 +65,4 @@ } // namespace payments -#endif // COMPONENTS_PAYMENTS_CONTENT_ANDROID_JOURNEY_LOGGER_ANDROID_H_ +#endif // CHROME_BROWSER_PAYMENTS_ANDROID_JOURNEY_LOGGER_ANDROID_H_
diff --git a/chrome/browser/profiles/profile_browsertest.cc b/chrome/browser/profiles/profile_browsertest.cc index 0eca419..2aa5692 100644 --- a/chrome/browser/profiles/profile_browsertest.cc +++ b/chrome/browser/profiles/profile_browsertest.cc
@@ -123,7 +123,8 @@ void CreatePrefsFileInDirectory(const base::FilePath& directory_path) { base::FilePath pref_path(directory_path.Append(chrome::kPreferencesFilename)); std::string data("{}"); - ASSERT_TRUE(base::WriteFile(pref_path, data.c_str(), data.size())); + ASSERT_EQ(static_cast<int>(data.size()), + base::WriteFile(pref_path, data.c_str(), data.size())); } void CheckChromeVersion(Profile *profile, bool is_new) {
diff --git a/chrome/browser/resources/chromeos/chromevox/cvox2/background/command_handler.js b/chrome/browser/resources/chromeos/chromevox/cvox2/background/command_handler.js index 9cc9cd7..fd27489 100644 --- a/chrome/browser/resources/chromeos/chromevox/cvox2/background/command_handler.js +++ b/chrome/browser/resources/chromeos/chromevox/cvox2/background/command_handler.js
@@ -860,4 +860,36 @@ } }; +/** + * Performs global initialization. + * @private + */ +CommandHandler.init_ = function() { + var firstRunId = 'jdgcneonijmofocbhmijhacgchbihela'; + chrome.runtime.onMessageExternal.addListener( + function(request, sender, sendResponse) { + if (sender.id != firstRunId) + return; + + if (request.openTutorial) { + var launchTutorial = function(desktop, evt) { + desktop.removeEventListener( + chrome.automation.EventType.FOCUS, launchTutorial, true); + CommandHandler.onCommand('help'); + }; + + // Since we get this command early on ChromeVox launch, the first run + // UI is not yet shown. Monitor for when first run gets focused, and + // show our tutorial. + chrome.automation.getDesktop(function(desktop) { + launchTutorial = launchTutorial.bind(this, desktop); + desktop.addEventListener( + chrome.automation.EventType.FOCUS, launchTutorial, true); + }); + } + }); +}; + +CommandHandler.init_(); + }); // goog.scope
diff --git a/chrome/browser/resources/chromeos/first_run/app/main.html b/chrome/browser/resources/chromeos/first_run/app/main.html index 32e52a3..8ce5527 100644 --- a/chrome/browser/resources/chromeos/first_run/app/main.html +++ b/chrome/browser/resources/chromeos/first_run/app/main.html
@@ -2,7 +2,7 @@ <html i18n-values="dir:textdirection;.style.fontFamily:fontfamily;lang:language"> <head> <meta charset=utf-8> - <title></title> + <title i18n-content="accessibleTitle"></title> <link rel="stylesheet" href="chrome://resources/css/text_defaults.css"> <link rel="stylesheet" href="chrome://resources/css/widgets.css"> <link rel="stylesheet" href="chrome://resources/css/apps/common.css">
diff --git a/chrome/browser/resources/chromeos/first_run/app/main.js b/chrome/browser/resources/chromeos/first_run/app/main.js index e1afc5b..893b7a0 100644 --- a/chrome/browser/resources/chromeos/first_run/app/main.js +++ b/chrome/browser/resources/chromeos/first_run/app/main.js
@@ -31,6 +31,14 @@ appWindow.close(); e.stopPropagation(); }); + + // If spoken feedback is enabled, also show its tutorial. + chrome.accessibilityFeatures.spokenFeedback.get({}, function(details) { + if (details.value) { + var chromeVoxId = 'mndnfokpggljbaajbnioimlmbfngpief'; + chrome.runtime.sendMessage(chromeVoxId, {openTutorial: true}); + } + }); } document.addEventListener('DOMContentLoaded', init);
diff --git a/chrome/browser/resources/chromeos/first_run/app/manifest.json b/chrome/browser/resources/chromeos/first_run/app/manifest.json index de6564b..b307748 100644 --- a/chrome/browser/resources/chromeos/first_run/app/manifest.json +++ b/chrome/browser/resources/chromeos/first_run/app/manifest.json
@@ -20,6 +20,7 @@ "content_security_policy": "default-src 'none'; script-src 'self' blob: filesystem: chrome://resources; style-src 'self' blob: filesystem: 'unsafe-inline' chrome://resources; img-src 'self' blob: filesystem: chrome://theme chrome://resources" }, "permissions": [ + "accessibilityFeatures.read", "firstRunPrivate", "chrome://theme/", "chrome://resources/"
diff --git a/chrome/browser/resources/chromeos/first_run/first_run.html b/chrome/browser/resources/chromeos/first_run/first_run.html index 29fe952b..184c631f 100644 --- a/chrome/browser/resources/chromeos/first_run/first_run.html +++ b/chrome/browser/resources/chromeos/first_run/first_run.html
@@ -2,7 +2,7 @@ <html i18n-values="dir:textdirection;shelf:shelfAlignment;.style.fontFamily:fontfamily;"> <head> <meta charset=utf-8> - <title></title> + <title i18n-content="accessibleTitle"></title> <link rel="stylesheet" href="chrome://resources/css/text_defaults.css"> <link rel="stylesheet" href="chrome://resources/css/widgets.css"> <link rel="stylesheet" href="chrome://resources/css/apps/common.css"> @@ -28,4 +28,3 @@ <script src="chrome://resources/js/i18n_template.js"></script> </body> </html> -
diff --git a/chrome/browser/resources/engagement/site_engagement.html b/chrome/browser/resources/engagement/site_engagement.html index 4a519fa..9a7f960 100644 --- a/chrome/browser/resources/engagement/site_engagement.html +++ b/chrome/browser/resources/engagement/site_engagement.html
@@ -61,7 +61,7 @@ box-shadow: 0 0 2px rgb(113, 158, 206); outline: none; } - + table tr:hover { background: rgb(255, 255, 187); } @@ -83,7 +83,7 @@ <th sort-key="origin"> Origin </th> - <th sort-key="score" class="sort-column" sort-reverse> + <th sort-key="total_score" class="sort-column" sort-reverse> Points </th> </tr>
diff --git a/chrome/browser/resources/engagement/site_engagement.js b/chrome/browser/resources/engagement/site_engagement.js index 8dab46a..0aaaf60 100644 --- a/chrome/browser/resources/engagement/site_engagement.js +++ b/chrome/browser/resources/engagement/site_engagement.js
@@ -16,18 +16,18 @@ } define('main', [ - 'chrome/browser/engagement/site_engagement.mojom', + 'chrome/browser/engagement/site_engagement_details.mojom', 'content/public/renderer/frame_interfaces', ], (siteEngagementMojom, frameInterfaces) => { return () => { - var uiHandler = new siteEngagementMojom.SiteEngagementUIHandlerPtr( + var uiHandler = new siteEngagementMojom.SiteEngagementDetailsProviderPtr( frameInterfaces.getInterface( - siteEngagementMojom.SiteEngagementUIHandler.name)); + siteEngagementMojom.SiteEngagementDetailsProvider.name)); var engagementTableBody = $('engagement-table-body'); var updateInterval = null; var info = null; - var sortKey = 'score'; + var sortKey = 'total_score'; var sortReverse = true; // Set table header sort handlers. @@ -55,7 +55,7 @@ /** * Creates a single row in the engagement table. - * @param {SiteEngagementInfo} info The info to create the row from. + * @param {SiteEngagementDetails} info The info to create the row from. * @return {HTMLElement} */ function createRow(info) { @@ -67,13 +67,13 @@ 'change', handleScoreChange.bind(undefined, info.origin)); scoreInput.addEventListener('focus', disableAutoupdate); scoreInput.addEventListener('blur', enableAutoupdate); - scoreInput.value = info.score; + scoreInput.value = info.total_score; var scoreCell = createElementWithClassName('td', 'score-cell'); scoreCell.appendChild(scoreInput); var engagementBar = createElementWithClassName('div', 'engagement-bar'); - engagementBar.style.width = (info.score * 4) + 'px'; + engagementBar.style.width = (info.total_score * 4) + 'px'; var engagementBarCell = createElementWithClassName('td', 'engagement-bar-cell'); @@ -111,7 +111,7 @@ */ function handleScoreChange(origin, e) { var scoreInput = e.target; - uiHandler.setSiteEngagementScoreForOrigin(origin, scoreInput.value); + uiHandler.setSiteEngagementScoreForUrl(origin, scoreInput.value); scoreInput.barCellRef.style.width = (scoreInput.value * 4) + 'px'; scoreInput.blur(); enableAutoupdate(); @@ -135,7 +135,7 @@ } /** - * Compares two SiteEngagementInfo objects based on |sortKey|. + * Compares two SiteEngagementDetails objects based on |sortKey|. * @param {string} sortKey The name of the property to sort by. * @return {number} A negative number if |a| should be ordered before |b|, a * positive number otherwise. @@ -148,7 +148,7 @@ if (sortKey == 'origin') return new URL(val1.url).host > new URL(val2.url).host ? 1 : -1; - if (sortKey == 'score') + if (sortKey == 'total_score') return val1 - val2; assertNotReached('Unsupported sort key: ' + sortKey); @@ -163,7 +163,7 @@ sortInfo(); // Round each score to 2 decimal places. info.forEach((info) => { - info.score = Number(Math.round(info.score * 100) / 100); + info.total_score = Number(Math.round(info.total_score * 100) / 100); engagementTableBody.appendChild(createRow(info)); }); @@ -175,7 +175,7 @@ */ function updateEngagementTable() { // Populate engagement table. - uiHandler.getSiteEngagementInfo().then((response) => { + uiHandler.getSiteEngagementDetails().then((response) => { info = response.info; renderTable(info); });
diff --git a/chrome/browser/resources/print_preview/print_preview.css b/chrome/browser/resources/print_preview/print_preview.css index 2f85f76e..fe76b9f 100644 --- a/chrome/browser/resources/print_preview/print_preview.css +++ b/chrome/browser/resources/print_preview/print_preview.css
@@ -73,14 +73,14 @@ padding-top: 10px; } -.right-column .radio input[type='radio'] { - height: 1.1em; - width: 1.1em; -} - +.right-column .radio input[type='radio'], .right-column label input[type='checkbox'] { - height: 1.1em; - width: 1.1em; + --min-size: 13.19px; + --size: 1.1em; + height: var(--size); + min-height: var(--min-size); + min-width: var(--min-size); + width: var(--size); } .left-column {
diff --git a/chrome/browser/resources/settings/a11y_page/manage_a11y_page.html b/chrome/browser/resources/settings/a11y_page/manage_a11y_page.html index e68a5f6..bcb42c73 100644 --- a/chrome/browser/resources/settings/a11y_page/manage_a11y_page.html +++ b/chrome/browser/resources/settings/a11y_page/manage_a11y_page.html
@@ -155,7 +155,7 @@ </settings-toggle-button> <div class="list-item settings-toggle-button-spacer"> <div>$i18n{delayBeforeClickLabel}</div> - <settings-dropdown-menu + <settings-dropdown-menu label="$i18n{delayBeforeClickLabel}" pref="{{prefs.settings.a11y.autoclick_delay_ms}}" menu-options="[[autoClickDelayOptions_]]" disabled="[[!prefs.settings.a11y.autoclick.value]]">
diff --git a/chrome/browser/resources/settings/about_page/about_page.html b/chrome/browser/resources/settings/about_page/about_page.html index 7eda97e..d24e89c 100644 --- a/chrome/browser/resources/settings/about_page/about_page.html +++ b/chrome/browser/resources/settings/about_page/about_page.html
@@ -85,7 +85,8 @@ </style> <div> <settings-section page-title="$i18n{aboutPageTitle}" section="about"> - <settings-animated-pages id="pages" section="about"> + <settings-animated-pages id="pages" section="about" + focus-config="[[focusConfig_]]"> <neon-animatable route-path="default"> <div class="settings-box two-line"> <img id="product-logo" on-tap="onProductLogoTap_" @@ -182,7 +183,8 @@ <div class="settings-box" on-tap="onDetailedBuildInfoTap_" actionable> <div class="start">$i18n{aboutDetailedBuildInfo}</div> - <button class="subpage-arrow" is="paper-icon-button-light" + <button id="detailed-build-info-trigger" class="subpage-arrow" + is="paper-icon-button-light" aria-label="$i18n{aboutDetailedBuildInfo}"> </button> </div>
diff --git a/chrome/browser/resources/settings/about_page/about_page.js b/chrome/browser/resources/settings/about_page/about_page.js index cb26f366..36f8b61 100644 --- a/chrome/browser/resources/settings/about_page/about_page.js +++ b/chrome/browser/resources/settings/about_page/about_page.js
@@ -73,6 +73,18 @@ type: Boolean, computed: 'computeShowCheckUpdates_(currentUpdateStatusEvent_)', }, + + /** @private {!Map<string, string>} */ + focusConfig_: { + type: Object, + value: function() { + var map = new Map(); + map.set( + settings.Route.DETAILED_BUILD_INFO.path, + '#detailed-build-info-trigger'); + return map; + }, + } // </if> },
diff --git a/chrome/browser/resources/settings/android_apps_page/android_apps_page.html b/chrome/browser/resources/settings/android_apps_page/android_apps_page.html index f3264d6..a072c1e 100644 --- a/chrome/browser/resources/settings/android_apps_page/android_apps_page.html +++ b/chrome/browser/resources/settings/android_apps_page/android_apps_page.html
@@ -16,7 +16,8 @@ <template> <style include="settings-shared"></style> - <settings-animated-pages id="pages" section="androidApps"> + <settings-animated-pages id="pages" section="androidApps" + focus-config="[[focusConfig_]]"> <neon-animatable route-path="default"> <div id="android-apps" class="settings-box two-line first" actionable on-tap="onSubpageTap_">
diff --git a/chrome/browser/resources/settings/android_apps_page/android_apps_page.js b/chrome/browser/resources/settings/android_apps_page/android_apps_page.js index b7fd76aa..8617317 100644 --- a/chrome/browser/resources/settings/android_apps_page/android_apps_page.js +++ b/chrome/browser/resources/settings/android_apps_page/android_apps_page.js
@@ -21,6 +21,18 @@ /** @private {!AndroidAppsInfo|undefined} */ androidAppsInfo_: Object, + + /** @private {!Map<string, string>} */ + focusConfig_: { + type: Object, + value: function() { + var map = new Map(); + map.set( + settings.Route.ANDROID_APPS_DETAILS.path, + '#android-apps .subpage-arrow'); + return map; + }, + }, }, /** @private {?settings.AndroidAppsBrowserProxy} */
diff --git a/chrome/browser/resources/settings/appearance_page/appearance_fonts_page.html b/chrome/browser/resources/settings/appearance_page/appearance_fonts_page.html index 7ce91b0..7b2fc2ff 100644 --- a/chrome/browser/resources/settings/appearance_page/appearance_fonts_page.html +++ b/chrome/browser/resources/settings/appearance_page/appearance_fonts_page.html
@@ -41,7 +41,7 @@ </div> <div class="list-frame"> <div class="list-item"> - <settings-dropdown-menu class="start" + <settings-dropdown-menu class="start" label="$i18n{standardFont}" pref="{{prefs.webkit.webprefs.fonts.standard.Zyyy}}" menu-options="[[fontOptions_]]"> </settings-dropdown-menu> @@ -62,7 +62,7 @@ </div> <div class="list-frame"> <div class="list-item"> - <settings-dropdown-menu class="start" + <settings-dropdown-menu class="start" label="$i18n{serifFont}" pref="{{prefs.webkit.webprefs.fonts.serif.Zyyy}}" menu-options="[[fontOptions_]]"> </settings-dropdown-menu> @@ -83,7 +83,7 @@ </div> <div class="list-frame"> <div class="list-item"> - <settings-dropdown-menu class="start" + <settings-dropdown-menu class="start" label="$i18n{sansSerifFont}" pref="{{prefs.webkit.webprefs.fonts.sansserif.Zyyy}}" menu-options="[[fontOptions_]]"> </settings-dropdown-menu> @@ -104,7 +104,7 @@ </div> <div class="list-frame"> <div class="list-item"> - <settings-dropdown-menu class="start" + <settings-dropdown-menu class="start" label="$i18n{fixedWidthFont}" pref="{{prefs.webkit.webprefs.fonts.fixed.Zyyy}}" menu-options="[[fontOptions_]]"> </settings-dropdown-menu>
diff --git a/chrome/browser/resources/settings/appearance_page/appearance_page.html b/chrome/browser/resources/settings/appearance_page/appearance_page.html index 1082903..66489b6 100644 --- a/chrome/browser/resources/settings/appearance_page/appearance_page.html +++ b/chrome/browser/resources/settings/appearance_page/appearance_page.html
@@ -159,7 +159,7 @@ <div class="settings-box"> </if> <div class="start">$i18n{fontSize}</div> - <settings-dropdown-menu id="defaultFontSize" + <settings-dropdown-menu id="defaultFontSize" label="$i18n{fontSize}" pref="{{prefs.webkit.webprefs.default_font_size}}" menu-options="[[fontSizeOptions_]]"> </settings-dropdown-menu>
diff --git a/chrome/browser/resources/settings/clear_browsing_data_dialog/clear_browsing_data_dialog.html b/chrome/browser/resources/settings/clear_browsing_data_dialog/clear_browsing_data_dialog.html index fed8c2d..453f9c2 100644 --- a/chrome/browser/resources/settings/clear_browsing_data_dialog/clear_browsing_data_dialog.html +++ b/chrome/browser/resources/settings/clear_browsing_data_dialog/clear_browsing_data_dialog.html
@@ -99,6 +99,7 @@ <div class="row"> $i18n{clearFollowingItemsFrom} <settings-dropdown-menu id="clearFrom" + label="$i18n{clearFollowingItemsFrom}" pref="{{prefs.browser.clear_data.time_period}}" menu-options="[[clearFromOptions_]]"> </settings-dropdown-menu>
diff --git a/chrome/browser/resources/settings/controls/settings_dropdown_menu.html b/chrome/browser/resources/settings/controls/settings_dropdown_menu.html index cf87ec1..c3fca94b 100644 --- a/chrome/browser/resources/settings/controls/settings_dropdown_menu.html +++ b/chrome/browser/resources/settings/controls/settings_dropdown_menu.html
@@ -29,6 +29,7 @@ </template> <div class="md-select-wrapper"> <select class="md-select" id="dropdownMenu" on-change="onChange_" + aria-label$="[[label]]" disabled="[[shouldDisableMenu_(disabled, menuOptions, pref.*)]]"> <template is="dom-repeat" items="[[menuOptions]]"> <option value="[[item.value]]">[[item.name]]</option>
diff --git a/chrome/browser/resources/settings/controls/settings_dropdown_menu.js b/chrome/browser/resources/settings/controls/settings_dropdown_menu.js index 74870c5..4bc6c655 100644 --- a/chrome/browser/resources/settings/controls/settings_dropdown_menu.js +++ b/chrome/browser/resources/settings/controls/settings_dropdown_menu.js
@@ -57,6 +57,9 @@ value: 'SETTINGS_DROPDOWN_NOT_FOUND_ITEM', readOnly: true, }, + + /** Label for a11y purposes */ + label: String, }, observers: [
diff --git a/chrome/browser/resources/settings/date_time_page/date_time_page.html b/chrome/browser/resources/settings/date_time_page/date_time_page.html index e482dfc..b221d10 100644 --- a/chrome/browser/resources/settings/date_time_page/date_time_page.html +++ b/chrome/browser/resources/settings/date_time_page/date_time_page.html
@@ -46,6 +46,7 @@ </div> <div class="settings-box continuation embedded"> <settings-dropdown-menu pref="{{prefs.cros.system.timezone}}" + label="$i18n{timeZone}" menu-options="[[timeZoneList_]]" disabled="[[timeZoneAutoDetect_]]"> </settings-dropdown-menu>
diff --git a/chrome/browser/resources/settings/device_page/device_page.html b/chrome/browser/resources/settings/device_page/device_page.html index 1ba15564..8a1f5b55 100644 --- a/chrome/browser/resources/settings/device_page/device_page.html +++ b/chrome/browser/resources/settings/device_page/device_page.html
@@ -19,7 +19,8 @@ <dom-module id="settings-device-page"> <template> <style include="settings-shared"></style> - <settings-animated-pages id="pages" section="device"> + <settings-animated-pages id="pages" section="device" + focus-config="[[focusConfig_]]"> <neon-animatable id="main" route-path="default"> <div id="pointersRow" class="settings-box first" on-tap="onPointersTap_" actionable>
diff --git a/chrome/browser/resources/settings/device_page/device_page.js b/chrome/browser/resources/settings/device_page/device_page.js index 9d452158..dc714a0 100644 --- a/chrome/browser/resources/settings/device_page/device_page.js +++ b/chrome/browser/resources/settings/device_page/device_page.js
@@ -51,6 +51,27 @@ }, readOnly: true, }, + + /** @private {!Map<string, string>} */ + focusConfig_: { + type: Object, + value: function() { + var map = new Map(); + map.set( + settings.Route.POINTERS.path, '#pointersRow .subpage-arrow'); + map.set( + settings.Route.KEYBOARD.path, '#keyboardRow .subpage-arrow'); + map.set( + settings.Route.STYLUS.path, '#stylusRow .subpage-arrow'); + map.set( + settings.Route.DISPLAY.path, '#displayRow .subpage-arrow'); + map.set( + settings.Route.STORAGE.path, '#storageRow .subpage-arrow'); + map.set( + settings.Route.POWER.path, '#powerRow .subpage-arrow'); + return map; + }, + }, }, observers: [
diff --git a/chrome/browser/resources/settings/device_page/display.html b/chrome/browser/resources/settings/device_page/display.html index 3993511..6491360f 100644 --- a/chrome/browser/resources/settings/device_page/display.html +++ b/chrome/browser/resources/settings/device_page/display.html
@@ -52,6 +52,9 @@ text-transform: uppercase; } + #controlsDiv > .settings-box:first-of-type { + border-top: none; + } </style> <div class="settings-box first layout vertical self-stretch"> <div class="title-text layout self-start"> @@ -76,31 +79,58 @@ </div> <div hidden="[[hasMultipleDisplays_(displays)]]" class="settings-box line-only"></div> - <div class="settings-box layout vertical first"> + + <div id="controlsDiv" class="settings-box layout vertical first"> <h2>[[selectedDisplay.name]]</h2> - <div class="settings-box embedded first two-line" - hidden$="[[!showMirror_(displays)]]"> - <div class="start"> - <div id="displayMirrorCheckboxLabel">$i18n{displayMirror}</div> - <div class="secondary">[[getDisplayMirrorText_(displays)]]</div> + + <template is="dom-if" if="[[showMirror_(unifiedDesktopMode_, displays)]]" + restamp> + <div class="settings-box embedded two-line"> + <div class="start"> + <div id="displayMirrorCheckboxLabel">$i18n{displayMirror}</div> + <div class="secondary">[[getDisplayMirrorText_(displays)]]</div> + </div> + <paper-toggle-button checked="[[isMirrored_(displays)]]" + on-tap="onMirroredTap_" + aria-labelledby="displayMirrorCheckboxLabel"> + </paper-toggle-button> </div> - <paper-toggle-button checked="[[isMirrored_(displays)]]" - on-tap="onMirroredTap_" - aria-labelledby="displayMirrorCheckboxLabel"> - </div> - <div class="settings-box embedded" - hidden$="[[!showDisplaySelectMenu_(displays, selectedDisplay)]]"> - <div class="start">$i18n{displayScreenTitle}</div> - <div class="md-select-wrapper"> - <select class="md-select" on-change="updatePrimaryDisplay_" - value="[[getDisplaySelectMenuIndex_( - selectedDisplay, primaryDisplayId)]]"> - <option value="0">$i18n{displayScreenPrimary}</option> - <option value="1">$i18n{displayScreenExtended}</option> - </select> - <span class="md-select-underline"></span> + </template> + + <template is="dom-if" if="[[showUnifiedDesktop_(unifiedDesktopAvailable_, + unifiedDesktopMode_, displays)]]" restamp> + <div class="settings-box embedded two-line"> + <div class="start"> + <div id="displayUnifiedDesktopCheckboxLabel"> + $i18n{displayUnfiedDesktop} + </div> + <div class="secondary"> + [[getUnifiedDesktopText_(unifiedDesktopMode_)]] + </div> + </div> + <paper-toggle-button checked="[[unifiedDesktopMode_]]" + on-tap="onUnifiedDesktopTap_" + aria-labelledby="displayUnifiedDesktopCheckboxLabel"> + </paper-toggle-button> </div> - </div> + </template> + + <template is="dom-if" restamp + if="[[showDisplaySelectMenu_(displays, selectedDisplay)]]"> + <div class="settings-box embedded"> + <div class="start">$i18n{displayScreenTitle}</div> + <div class="md-select-wrapper"> + <select class="md-select" on-change="updatePrimaryDisplay_" + value="[[getDisplaySelectMenuIndex_( + selectedDisplay, primaryDisplayId)]]"> + <option value="0">$i18n{displayScreenPrimary}</option> + <option value="1">$i18n{displayScreenExtended}</option> + </select> + <span class="md-select-underline"></span> + </div> + </div> + </template> + <div class="settings-box embedded two-line"> <div class="start textarea layout vertical"> <div>$i18n{displayResolutionTitle}</div> @@ -113,19 +143,23 @@ on-change="onSelectedModeChange_"> </settings-slider> </div> - <div class="settings-box embedded"> - <div class="start textarea">$i18n{displayOrientation}</div> - <div class="md-select-wrapper"> - <select class="md-select" value="[[selectedDisplay.rotation]]" - on-change="onOrientationChange_"> - <option value="0">$i18n{displayOrientationStandard}</option> - <option value="90">90</option> - <option value="180">180</option> - <option value="270">270</option> - </select> - <span class="md-select-underline"></span> + + <template is="dom-if" if="[[!unifiedDesktopMode_]]" restamp> + <div class="settings-box embedded"> + <div class="start textarea">$i18n{displayOrientation}</div> + <div class="md-select-wrapper"> + <select class="md-select" value="[[selectedDisplay.rotation]]" + on-change="onOrientationChange_"> + <option value="0">$i18n{displayOrientationStandard}</option> + <option value="90">90</option> + <option value="180">180</option> + <option value="270">270</option> + </select> + <span class="md-select-underline"></span> + </div> </div> - </div> + </template> + <div class="settings-box embedded two-line" on-tap="onOverscanTap_" hidden$="[[selectedDisplay.isInternal]]" actionable>
diff --git a/chrome/browser/resources/settings/device_page/display.js b/chrome/browser/resources/settings/device_page/display.js index eb4e5605..b8bf2e97 100644 --- a/chrome/browser/resources/settings/device_page/display.js +++ b/chrome/browser/resources/settings/device_page/display.js
@@ -70,6 +70,20 @@ /** @private {!Array<number>} Mode index values for slider. */ modeValues_: Array, + + /** @private */ + unifiedDesktopAvailable_: { + type: Boolean, + value: function() { + return loadTimeData.getBoolean('unifiedDesktopAvailable'); + } + }, + + /** @private */ + unifiedDesktopMode_: { + type: Boolean, + value: false, + }, }, /** @private {number} Selected mode index received from chrome. */ @@ -122,8 +136,11 @@ /** @private */ getDisplayInfo_: function() { + /** @type {chrome.system.display.GetInfoFlags} */ var flags = { + singleUnified: true + }; settings.display.systemDisplayApi.getInfo( - this.displayInfoFetched_.bind(this)); + flags, this.displayInfoFetched_.bind(this)); }, /** @@ -240,17 +257,41 @@ * @private */ getDisplayMirrorText_: function(displays) { - return this.i18n( - this.isMirrored_(displays) ? 'displayMirrorOn' : 'displayMirrorOff'); + return this.i18n(this.isMirrored_(displays) ? 'toggleOn' : 'toggleOff'); }, /** + * @param {boolean} unifiedDesktopAvailable + * @param {boolean} unifiedDesktopMode * @param {!Array<!chrome.system.display.DisplayUnitInfo>} displays * @return {boolean} * @private */ - showMirror_: function(displays) { - return this.isMirrored_(displays) || displays.length == 2; + showUnifiedDesktop_: function( + unifiedDesktopAvailable, unifiedDesktopMode, displays) { + return unifiedDesktopMode || + (unifiedDesktopAvailable && displays.length > 1 && + !this.isMirrored_(displays)); + }, + + /** + * @param {boolean} unifiedDesktopMode + * @return {string} + * @private + */ + getUnifiedDesktopText_: function(unifiedDesktopMode) { + return this.i18n(unifiedDesktopMode ? 'toggleOn' : 'toggleOff'); + }, + + /** + * @param {boolean} unifiedDesktopMode + * @param {!Array<!chrome.system.display.DisplayUnitInfo>} displays + * @return {boolean} + * @private + */ + showMirror_: function(unifiedDesktopMode, displays) { + return this.isMirrored_(displays) || + (!unifiedDesktopMode && displays.length == 2); }, /** @@ -423,6 +464,16 @@ id, properties, this.setPropertiesCallback_.bind(this)); }, + /** @private */ + onUnifiedDesktopTap_: function() { + /** @type {!chrome.system.display.DisplayProperties} */ var properties = { + isUnified: !this.unifiedDesktopMode_, + }; + settings.display.systemDisplayApi.setDisplayProperties( + this.primaryDisplayId, properties, + this.setPropertiesCallback_.bind(this)); + }, + /** * @param {!Event} e * @private @@ -454,6 +505,8 @@ (this.displays && this.displays[0]); this.setSelectedDisplay_(selectedDisplay); + this.unifiedDesktopMode_ = !!primaryDisplay && primaryDisplay.isUnified; + this.$.displayLayout.updateDisplays(this.displays, this.layouts); },
diff --git a/chrome/browser/resources/settings/device_page/keyboard.html b/chrome/browser/resources/settings/device_page/keyboard.html index e01157b..ecd014a 100644 --- a/chrome/browser/resources/settings/device_page/keyboard.html +++ b/chrome/browser/resources/settings/device_page/keyboard.html
@@ -14,21 +14,21 @@ <style include="settings-shared"></style> <div class="settings-box first"> <div class="start">$i18n{keyboardKeySearch}</div> - <settings-dropdown-menu + <settings-dropdown-menu label="$i18n{keyboardKeySearch}" pref="{{prefs.settings.language.xkb_remap_search_key_to}}" menu-options="[[keyMapTargets_]]"> </settings-dropdown-menu> </div> <div class="settings-box"> <div class="start">$i18n{keyboardKeyCtrl}</div> - <settings-dropdown-menu + <settings-dropdown-menu label="$i18n{keyboardKeyCtrl}" pref="{{prefs.settings.language.xkb_remap_control_key_to}}" menu-options="[[keyMapTargets_]]"> </settings-dropdown-menu> </div> <div class="settings-box"> <div class="start">$i18n{keyboardKeyAlt}</div> - <settings-dropdown-menu + <settings-dropdown-menu label="$i18n{keyboardKeyAlt}" pref="{{prefs.settings.language.xkb_remap_alt_key_to}}" menu-options="[[keyMapTargets_]]"> </settings-dropdown-menu> @@ -36,7 +36,7 @@ <template is="dom-if" if="[[showCapsLock_]]"> <div class="settings-box" id="capsLockKey"> <div class="start">$i18n{keyboardKeyCapsLock}</div> - <settings-dropdown-menu + <settings-dropdown-menu label="$i18n{keyboardKeyCapsLock}" pref="{{prefs.settings.language.remap_caps_lock_key_to}}" menu-options="[[keyMapTargets_]]"> </settings-dropdown-menu> @@ -45,7 +45,7 @@ <template is="dom-if" if="[[showDiamondKey_]]"> <div class="settings-box" id="diamondKey"> <div class="start">$i18n{keyboardKeyDiamond}</div> - <settings-dropdown-menu + <settings-dropdown-menu label="$i18n{keyboardKeyDiamond}" pref="{{prefs.settings.language.remap_diamond_key_to}}" menu-options="[[keyMapTargets_]]"> </settings-dropdown-menu> @@ -53,14 +53,14 @@ </template> <div class="settings-box"> <div class="start">$i18n{keyboardKeyEscape}</div> - <settings-dropdown-menu + <settings-dropdown-menu label="$i18n{keyboardKeyEscape}" pref="{{prefs.settings.language.remap_escape_key_to}}" menu-options="[[keyMapTargets_]]"> </settings-dropdown-menu> </div> <div class="settings-box"> <div class="start">$i18n{keyboardKeyBackspace}</div> - <settings-dropdown-menu + <settings-dropdown-menu label="$i18n{keyboardKeyBackspace}" pref="{{prefs.settings.language.remap_backspace_key_to}}" menu-options="[[keyMapTargets_]]"> </settings-dropdown-menu>
diff --git a/chrome/browser/resources/settings/internet_page/internet_detail_page.html b/chrome/browser/resources/settings/internet_page/internet_detail_page.html index 51b01ffd..59baa4bb 100644 --- a/chrome/browser/resources/settings/internet_page/internet_detail_page.html +++ b/chrome/browser/resources/settings/internet_page/internet_detail_page.html
@@ -12,6 +12,7 @@ <link rel="import" href="chrome://resources/polymer/v1_0/iron-icon/iron-icon.html"> <link rel="import" href="chrome://resources/polymer/v1_0/paper-button/paper-button.html"> <link rel="import" href="chrome://resources/polymer/v1_0/paper-toggle-button/paper-toggle-button.html"> +<link rel="import" href="../controls/settings_toggle_button.html"> <link rel="import" href="../prefs/prefs.html"> <link rel="import" href="../route.html"> <link rel="import" href="internet_shared_css.html"> @@ -112,7 +113,7 @@ <paper-button class="primary-button" on-tap="onConnectTap_" hidden$="[[!showConnect_(networkProperties, globalPolicy)]]" disabled="[[!enableConnect_(networkProperties, defaultNetwork, - globalPolicy)]]"> + globalPolicy)]]"> $i18n{networkButtonConnect} </paper-button> <paper-button class="primary-button" on-tap="onDisconnectTap_" @@ -156,7 +157,7 @@ </cr-policy-network-indicator> <paper-toggle-button checked="{{preferNetwork_}}" disabled="[[isNetworkPolicyEnforced( - networkProperties.Priority)]]" + networkProperties.Priority)]]" aria-labelledby="preferNetworkToggleLabel"> </paper-toggle-button> </div> @@ -177,6 +178,16 @@ </paper-toggle-button> </div> </template> + <!-- Data roaming (Cellular only). --> + <template is="dom-if" + if="[[isType_(NetworkType_.CELLULAR, networkProperties)]]"> + <div class="settings-box"> + <settings-toggle-button id="allowDataRoaming" class="start" + pref="{{prefs.cros.signed.data_roaming_enabled}}" + label="$i18n{networkAllowDataRoaming}"> + </settings-toggle-button> + </div> + </template> <!-- SIM Info (Cellular only). --> <template is="dom-if" if="[[showCellularSim_(networkProperties)]]"> <div class="settings-box single-column stretch">
diff --git a/chrome/browser/resources/settings/privacy_page/privacy_page.html b/chrome/browser/resources/settings/privacy_page/privacy_page.html index a747b1f3..add253bb 100644 --- a/chrome/browser/resources/settings/privacy_page/privacy_page.html +++ b/chrome/browser/resources/settings/privacy_page/privacy_page.html
@@ -42,7 +42,8 @@ on-close="onDialogClosed_"> </settings-clear-browsing-data-dialog> </template> - <settings-animated-pages id="pages" section="privacy"> + <settings-animated-pages id="pages" section="privacy" + focus-config="[[focusConfig_]]"> <neon-animatable route-path="default"> <div class="settings-box first"> <p class="privacy-explanation">$i18nRaw{improveBrowsingExperience}</p>
diff --git a/chrome/browser/resources/settings/privacy_page/privacy_page.js b/chrome/browser/resources/settings/privacy_page/privacy_page.js index 0afbf09..a8ac950 100644 --- a/chrome/browser/resources/settings/privacy_page/privacy_page.js +++ b/chrome/browser/resources/settings/privacy_page/privacy_page.js
@@ -101,6 +101,23 @@ return loadTimeData.getBoolean('enableSafeBrowsingSubresourceFilter'); } }, + + /** @private {!Map<string, string>} */ + focusConfig_: { + type: Object, + value: function() { + var map = new Map(); +// <if expr="use_nss_certs"> + map.set( + settings.Route.CERTIFICATES.path, + '#manageCertificates .subpage-arrow'); +// </if> + map.set( + settings.Route.SITE_SETTINGS.path, + '#site-settings-subpage-trigger .subpage-arrow'); + return map; + }, + }, }, listeners: {
diff --git a/chrome/browser/resources/settings/search_page/search_page.html b/chrome/browser/resources/settings/search_page/search_page.html index a23abd4..6728aa4f 100644 --- a/chrome/browser/resources/settings/search_page/search_page.html +++ b/chrome/browser/resources/settings/search_page/search_page.html
@@ -67,7 +67,7 @@ <template is="dom-if" if="[[googleNowAvailable_]]"> <!-- Google Now cards in the launcher --> - <div class="settings-box continuation"> + <div class="settings-box continuation indented"> <settings-toggle-button id="googleNowEnable" class="start" pref="{{prefs.google_now_launcher.enabled}}" label="$i18n{searchEnableGoogleNowLabel}">
diff --git a/chrome/browser/resources/settings/settings_page/main_page_behavior.js b/chrome/browser/resources/settings/settings_page/main_page_behavior.js index 9250fd2..6983546c 100644 --- a/chrome/browser/resources/settings/settings_page/main_page_behavior.js +++ b/chrome/browser/resources/settings/settings_page/main_page_behavior.js
@@ -80,9 +80,10 @@ // Scroll to the section except for back/forward. Also scroll for any // in-page back/forward navigations (from a section or the root page). - var scrollToSection = - !settings.lastRouteChangeWasPopstate() || oldRouteWasSection || - oldRoute == settings.Route.BASIC; + // Also always scroll when coming from either the About or root page. + var scrollToSection = !settings.lastRouteChangeWasPopstate() || + oldRouteWasSection || oldRoute == settings.Route.BASIC || + oldRoute == settings.Route.ABOUT; if (oldRoute && (oldRoute.isSubpage() || newRoute.isSubpage())) this.isSubpageAnimating = true;
diff --git a/chrome/browser/resources/settings/site_settings_page/site_settings_page.html b/chrome/browser/resources/settings/site_settings_page/site_settings_page.html index a4b27a2..7dee54ee 100644 --- a/chrome/browser/resources/settings/site_settings_page/site_settings_page.html +++ b/chrome/browser/resources/settings/site_settings_page/site_settings_page.html
@@ -184,6 +184,26 @@ aria-label="$i18n{siteSettingsPopups}" aria-describedby="popupsSecondary"></button> </div> + <template is="dom-if" if="[[enableSafeBrowsingSubresourceFilter_]]"> + <div class="settings-box two-line" + category$="[[ContentSettingsTypes.SUBRESOURCE_FILTER]]" + data-route="SITE_SETTINGS_SUBRESOURCE_FILTER" on-tap="onTapNavigate_" + actionable> + <iron-icon icon="cr:open-in-new"></iron-icon> + <div class="middle"> + $i18n{siteSettingsSubresourceFilter} + <div class="secondary" id="subresourceFilterSecondary"> + [[defaultSettingLabel_( + default_.subresourceFilter, + '$i18nPolymer{siteSettingsSubresourceFilterBlock}', + '$i18nPolymer{siteSettingsSubresourceFilterAllow}')]] + </div> + </div> + <button class="subpage-arrow" is="paper-icon-button-light" + aria-label="$i18n{siteSettingsSubresourceFilter}" + aria-describedby="subresourceFilterSecondary"></button> + </div> + </template> <div class="settings-box two-line" category$="[[ContentSettingsTypes.BACKGROUND_SYNC]]" data-route="SITE_SETTINGS_BACKGROUND_SYNC" on-tap="onTapNavigate_" @@ -276,26 +296,6 @@ aria-label="$i18n{siteSettingsMidiDevices}" aria-describedby="midiDevicesSecondary"></button> </div> - <template is="dom-if" if="[[enableSafeBrowsingSubresourceFilter_]]"> - <div class="settings-box two-line" - category$="[[ContentSettingsTypes.SUBRESOURCE_FILTER]]" - data-route="SITE_SETTINGS_SUBRESOURCE_FILTER" on-tap="onTapNavigate_" - actionable> - <iron-icon icon="cr:open-in-new"></iron-icon> - <div class="middle"> - $i18n{siteSettingsSubresourceFilter} - <div class="secondary" id="subresourceFilterSecondary"> - [[defaultSettingLabel_( - default_.subresourceFilter, - '$i18nPolymer{siteSettingsSubresourceFilterBlock}', - '$i18nPolymer{siteSettingsSubresourceFilterAllow}')]] - </div> - </div> - <button class="subpage-arrow" is="paper-icon-button-light" - aria-label="$i18n{siteSettingsSubresourceFilter}" - aria-describedby="subresourceFilterSecondary"></button> - </div> - </template> <div class="settings-box" category$="[[ContentSettingsTypes.ZOOM_LEVELS]]" data-route="SITE_SETTINGS_ZOOM_LEVELS" on-tap="onTapNavigate_" actionable>
diff --git a/chrome/browser/safe_browsing/DEPS b/chrome/browser/safe_browsing/DEPS new file mode 100644 index 0000000..1a00f99 --- /dev/null +++ b/chrome/browser/safe_browsing/DEPS
@@ -0,0 +1,4 @@ +include_rules = [ + "+mojo", + "+components/chrome_cleaner", +]
diff --git a/chrome/browser/safe_browsing/incident_reporting/download_metadata_manager_unittest.cc b/chrome/browser/safe_browsing/incident_reporting/download_metadata_manager_unittest.cc index d06c0f3..b4de98b 100644 --- a/chrome/browser/safe_browsing/incident_reporting/download_metadata_manager_unittest.cc +++ b/chrome/browser/safe_browsing/incident_reporting/download_metadata_manager_unittest.cc
@@ -143,7 +143,8 @@ void WriteTestMetadataFileForItem(uint32_t download_id) { std::string data; ASSERT_TRUE(GetTestMetadata(download_id)->SerializeToString(&data)); - ASSERT_TRUE(base::WriteFile(GetMetadataPath(), data.data(), data.size())); + ASSERT_EQ(static_cast<int>(data.size()), + base::WriteFile(GetMetadataPath(), data.data(), data.size())); } // Writes a test DownloadMetadata file for kTestDownloadId to the test profile
diff --git a/chrome/browser/safe_browsing/srt_chrome_prompt_impl.cc b/chrome/browser/safe_browsing/srt_chrome_prompt_impl.cc new file mode 100644 index 0000000..4e60db0 --- /dev/null +++ b/chrome/browser/safe_browsing/srt_chrome_prompt_impl.cc
@@ -0,0 +1,30 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/safe_browsing/srt_chrome_prompt_impl.h" + +#include "base/logging.h" + +namespace safe_browsing { + +using chrome_cleaner::mojom::ChromePrompt; +using chrome_cleaner::mojom::ChromePromptRequest; +using chrome_cleaner::mojom::PromptAcceptance; +using chrome_cleaner::mojom::UwSPtr; + +ChromePromptImpl::ChromePromptImpl(ChromePromptRequest request) + : binding_(this, std::move(request)) {} + +ChromePromptImpl::~ChromePromptImpl() {} + +void ChromePromptImpl::PromptUser( + std::vector<UwSPtr> removable_uws_found, + bool elevation_required, + const ChromePrompt::PromptUserCallback& callback) { + // Placeholder. The actual implementation will show the prompt dialog to the + // user and invoke this callback depending on the user's response. + callback.Run(PromptAcceptance::DENIED); +} + +} // namespace safe_browsing
diff --git a/chrome/browser/safe_browsing/srt_chrome_prompt_impl.h b/chrome/browser/safe_browsing/srt_chrome_prompt_impl.h new file mode 100644 index 0000000..fbba20c --- /dev/null +++ b/chrome/browser/safe_browsing/srt_chrome_prompt_impl.h
@@ -0,0 +1,31 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CHROME_BROWSER_SAFE_BROWSING_SRT_CHROME_PROMPT_IMPL_H_ +#define CHROME_BROWSER_SAFE_BROWSING_SRT_CHROME_PROMPT_IMPL_H_ + +#include "components/chrome_cleaner/public/interfaces/chrome_prompt.mojom.h" +#include "mojo/public/cpp/bindings/binding.h" + +namespace safe_browsing { + +// Implementation of the ChromePrompt Mojo interface. +class ChromePromptImpl : public chrome_cleaner::mojom::ChromePrompt { + public: + explicit ChromePromptImpl(chrome_cleaner::mojom::ChromePromptRequest request); + ~ChromePromptImpl() override; + + void PromptUser( + std::vector<chrome_cleaner::mojom::UwSPtr> removable_uws_found, + bool elevation_required, + const chrome_cleaner::mojom::ChromePrompt::PromptUserCallback& callback) + override; + + private: + mojo::Binding<chrome_cleaner::mojom::ChromePrompt> binding_; +}; + +} // namespace safe_browsing + +#endif // CHROME_BROWSER_SAFE_BROWSING_SRT_CHROME_PROMPT_IMPL_H_
diff --git a/chrome/browser/safe_browsing/srt_fetcher_browsertest_win.cc b/chrome/browser/safe_browsing/srt_fetcher_browsertest_win.cc index ad157be..60053da 100644 --- a/chrome/browser/safe_browsing/srt_fetcher_browsertest_win.cc +++ b/chrome/browser/safe_browsing/srt_fetcher_browsertest_win.cc
@@ -5,18 +5,24 @@ #include "chrome/browser/safe_browsing/srt_fetcher_win.h" #include <initializer_list> -#include <iterator> #include <set> +#include <tuple> +#include <utility> #include <vector> #include "base/bind.h" #include "base/bind_helpers.h" #include "base/callback.h" +#include "base/callback_helpers.h" #include "base/files/file_path.h" #include "base/memory/ref_counted.h" #include "base/message_loop/message_loop.h" +#include "base/run_loop.h" +#include "base/strings/string_number_conversions.h" +#include "base/test/multiprocess_test.h" #include "base/test/scoped_feature_list.h" #include "base/test/test_mock_time_task_runner.h" +#include "base/threading/sequenced_task_runner_handle.h" #include "base/threading/thread_task_runner_handle.h" #include "base/time/time.h" #include "base/version.h" @@ -30,23 +36,197 @@ #include "chrome/browser/ui/test/test_browser_dialog.h" #include "chrome/common/pref_names.h" #include "chrome/test/base/in_process_browser_test.h" +#include "components/chrome_cleaner/public/interfaces/chrome_prompt.mojom.h" #include "components/component_updater/pref_names.h" #include "components/prefs/pref_service.h" #include "components/safe_browsing_db/safe_browsing_prefs.h" +#include "mojo/edk/embedder/embedder.h" +#include "mojo/edk/embedder/scoped_ipc_support.h" +#include "mojo/edk/system/core.h" +#include "testing/multiprocess_func_list.h" namespace safe_browsing { namespace { -const char* const kExpectedSwitches[] = {kExtendedSafeBrowsingEnabledSwitch, - kChromeVersionSwitch, - kChromeChannelSwitch}; +using chrome_cleaner::mojom::PromptAcceptance; -class SRTFetcherTest : public InProcessBrowserTest, - public SwReporterTestingDelegate { +// Special switches passed by the parent process (test case) to the reporter +// child process to indicate the behavior that should be mocked. +constexpr char kExitCodeToReturnSwitch[] = "exit-code-to-return"; +constexpr char kReportUwSFoundSwitch[] = "report-uws-found"; +constexpr char kReportElevationRequiredSwitch[] = "report-elevation-required"; +constexpr char kExpectedPromptAcceptanceSwitch[] = "expected-prompt-acceptance"; + +// The exit code to be returned in case of failure in the child process. +// This should never be passed as the expected exit code to be reported by +// tests. +constexpr int kFailureExitCode = -1; + +// Pass the |prompt_acceptance| to the mock child process in command line +// switch kExpectedPromptAcceptanceSwitch. +void AddPromptAcceptanceToCommandLine(PromptAcceptance prompt_acceptance, + base::CommandLine* command_line) { + command_line->AppendSwitchASCII( + kExpectedPromptAcceptanceSwitch, + base::IntToString(static_cast<int>(prompt_acceptance))); +} + +// Parses and returns the prompt acceptance value passed by the parent process +// in command line switch kExpectedPromptAcceptanceSwitch. Returns +// PromptAcceptance::UNSPECIFIED if the switch doesn't exist or can't be +// parsed to a valid PromptAcceptance enumerator. +PromptAcceptance PromptAcceptanceFromCommandLine( + const base::CommandLine& command_line) { + const std::string& prompt_acceptance_str = + command_line.GetSwitchValueASCII(kExpectedPromptAcceptanceSwitch); + int val = -1; + if (base::StringToInt(prompt_acceptance_str, &val)) { + PromptAcceptance prompt_acceptance = static_cast<PromptAcceptance>(val); + if (chrome_cleaner::mojom::IsKnownEnumValue(prompt_acceptance)) + return prompt_acceptance; + } + return PromptAcceptance::UNSPECIFIED; +} + +// Pointer to ChromePromptPtr object to be used by the child process. The +// object must be created, deleted, and accessed on the IPC thread only. +chrome_cleaner::mojom::ChromePromptPtr* g_chrome_prompt_ptr = nullptr; + +// The callback function to be passed to ChromePrompt::PromptUser to check if +// the prompt accepted returned by the parent process is equal to +// |expected_prompt_acceptance|. Will set |expected_value_received| with the +// comparison result, so that the main thread can report failure. Will invoke +// |done| callback when done. +void PromptUserCallback(const base::Closure& done, + PromptAcceptance expected_prompt_acceptance, + bool* expected_value_received, + PromptAcceptance prompt_acceptance) { + *expected_value_received = prompt_acceptance == expected_prompt_acceptance; + // It's safe to delete the ChromePromptPtr object here, since it will not be + // used anymore by the child process. + delete g_chrome_prompt_ptr; + g_chrome_prompt_ptr = nullptr; + done.Run(); +} + +// Mocks the sending of scan results from the child process to the parent +// process. Obtains the behavior to be mocked from special switches in +// |command_line|. Sets |expected_value_received| as true if the parent +// process replies with the expected prompt acceptance value. +void SendScanResults(const std::string& chrome_mojo_pipe_token, + const base::CommandLine& command_line, + const base::Closure& done, + bool* expected_value_received) { + constexpr int kDefaultUwSId = 10; + constexpr char kDefaultUwSName[] = "RemovedUwS"; + + mojo::ScopedMessagePipeHandle message_pipe_handle = + mojo::edk::CreateChildMessagePipe(chrome_mojo_pipe_token); + // This pointer will be deleted by PromptUserCallback. + g_chrome_prompt_ptr = new chrome_cleaner::mojom::ChromePromptPtr(); + g_chrome_prompt_ptr->Bind(chrome_cleaner::mojom::ChromePromptPtrInfo( + std::move(message_pipe_handle), 0)); + + std::vector<chrome_cleaner::mojom::UwSPtr> removable_uws_found; + if (command_line.HasSwitch(kReportUwSFoundSwitch)) { + chrome_cleaner::mojom::UwSPtr uws = chrome_cleaner::mojom::UwS::New(); + uws->id = kDefaultUwSId; + uws->name = kDefaultUwSName; + uws->observed_behaviours = chrome_cleaner::mojom::ObservedBehaviours::New(); + removable_uws_found.push_back(std::move(uws)); + } + const bool elevation_required = + command_line.HasSwitch(kReportElevationRequiredSwitch); + const PromptAcceptance expected_prompt_acceptance = + PromptAcceptanceFromCommandLine(command_line); + + (*g_chrome_prompt_ptr) + ->PromptUser( + std::move(removable_uws_found), elevation_required, + base::Bind(&PromptUserCallback, done, expected_prompt_acceptance, + expected_value_received)); +} + +// Connects to the parent process and sends mocked scan results. Returns true +// if connection was successful and the prompt acceptance results sent by the +// parent process are the same as expected. +bool ConnectAndSendDataToParentProcess( + const std::string& chrome_mojo_pipe_token, + const base::CommandLine& command_line) { + DCHECK(!chrome_mojo_pipe_token.empty()); + + mojo::edk::Init(); + base::Thread::Options options(base::MessageLoop::TYPE_IO, 0); + base::Thread io_thread("IPCThread"); + if (!io_thread.StartWithOptions(options)) + return false; + mojo::edk::ScopedIPCSupport ipc_support( + io_thread.task_runner(), + mojo::edk::ScopedIPCSupport::ShutdownPolicy::CLEAN); + mojo::edk::SetParentPipeHandleFromCommandLine(); + base::MessageLoop message_loop; + base::RunLoop run_loop; + // After the response from the parent process is received, this will post a + // task to unblock the child process's main thread. + auto done = base::Bind( + [](scoped_refptr<base::SequencedTaskRunner> main_runner, + base::Closure quit_closure) { + main_runner->PostTask(FROM_HERE, std::move(quit_closure)); + }, + base::SequencedTaskRunnerHandle::Get(), + base::Passed(run_loop.QuitClosure())); + + bool expected_value_received = false; + io_thread.task_runner()->PostTask( + FROM_HERE, base::Bind(&SendScanResults, chrome_mojo_pipe_token, + command_line, done, &expected_value_received)); + run_loop.Run(); + + return expected_value_received; +} + +// Mocks a Software Reporter process that returns an exit code specified by +// command line switch kExitCodeToReturnSwitch. If a Mojo IPC is available, +// this will also connect to the parent process and send mocked scan results +// to the parent process using data passed as command line switches. +MULTIPROCESS_TEST_MAIN(MockSwReporterProcess) { + base::CommandLine* command_line = base::CommandLine::ForCurrentProcess(); + const std::string& str = + command_line->GetSwitchValueASCII(kExitCodeToReturnSwitch); + const std::string& chrome_mojo_pipe_token = + command_line->GetSwitchValueASCII(kChromeMojoPipeTokenSwitch); + int exit_code_to_report = kFailureExitCode; + bool success = base::StringToInt(str, &exit_code_to_report) && + (chrome_mojo_pipe_token.empty() || + ConnectAndSendDataToParentProcess(chrome_mojo_pipe_token, + *command_line)); + return success ? exit_code_to_report : kFailureExitCode; +} + +// Parameters for this test: +// - bool in_browser_cleaner_ui: indicates if InBrowserCleanerUI experiment +// is enabled; if so, the parent and the child processes will communicate +// via a Mojo IPC; +// - bool elevation_required: indicates if the scan results sent by the child +// process should consider that elevation will be required for cleanup. +class SRTFetcherTest + : public InProcessBrowserTest, + public SwReporterTestingDelegate, + public ::testing::WithParamInterface<std::tuple<bool, bool>> { public: void SetUpInProcessBrowserTestFixture() override { SetSwReporterTestingDelegate(this); + + std::tie(in_browser_cleaner_ui_, elevation_required_) = GetParam(); + // The config should only accept elevation_required_ if InBrowserCleanerUI + // feature is enabled. + ASSERT_TRUE(!elevation_required_ || in_browser_cleaner_ui_); + + if (in_browser_cleaner_ui_) + scoped_feature_list_.InitAndEnableFeature(kInBrowserCleanerUIFeature); + else + scoped_feature_list_.InitAndDisableFeature(kInBrowserCleanerUIFeature); } void SetUpOnMainThread() override { @@ -80,14 +260,37 @@ prompt_trigger_called_ = true; } - // Records that the reporter was launched with the parameters given in - // |invocation|. - int LaunchReporter(const SwReporterInvocation& invocation) override { + // Spawns and returns a subprocess to mock an execution of the reporter with + // the parameters given in |invocation| that will return + // |exit_code_to_report_|. If IPC communication needs to be mocked, this will + // also provide values that define the expected behavior of the child + // process. + // Records the launch and parameters used for further verification. + base::Process LaunchReporter( + const SwReporterInvocation& invocation, + const base::LaunchOptions& launch_options) override { ++reporter_launch_count_; reporter_launch_parameters_.push_back(invocation); if (first_launch_callback_) std::move(first_launch_callback_).Run(); - return exit_code_to_report_; + + base::CommandLine command_line( + base::GetMultiProcessTestChildBaseCommandLine()); + command_line.AppendArguments(invocation.command_line, + /*include_program=*/false); + command_line.AppendSwitchASCII(kExitCodeToReturnSwitch, + base::IntToString(exit_code_to_report_)); + if (in_browser_cleaner_ui_) { + AddPromptAcceptanceToCommandLine(PromptAcceptance::DENIED, &command_line); + if (exit_code_to_report_ == kSwReporterCleanupNeeded) { + command_line.AppendSwitch(kReportUwSFoundSwitch); + if (elevation_required_) + command_line.AppendSwitch(kReportElevationRequiredSwitch); + } + } + base::SpawnChildResult result = base::SpawnMultiProcessTestChild( + "MockSwReporterProcess", command_line, launch_options); + return std::move(result.process); } // Returns the test's idea of the current time. @@ -231,22 +434,20 @@ } // Expects |invocation|'s command line to contain all the switches required - // for reporter logging. + // for reporter logging if and only if |expect_switches| is true. void ExpectLoggingSwitches(const SwReporterInvocation& invocation, bool expect_switches) { + static const std::set<std::string> logging_switches{ + kExtendedSafeBrowsingEnabledSwitch, kChromeVersionSwitch, + kChromeChannelSwitch}; + const base::CommandLine::SwitchMap& invocation_switches = invocation.command_line.GetSwitches(); - std::set<std::string> expected_switches; - if (expect_switches) - expected_switches = {std::begin(kExpectedSwitches), - std::end(kExpectedSwitches)}; - EXPECT_EQ(expected_switches.size(), invocation_switches.size()); - // Checks if all expected switches are in the invocation switches. It's not - // necessary to check if all invocation switches are expected, since we - // checked if both sets should have the same size. - for (const std::string& expected_switch : expected_switches) { - EXPECT_NE(invocation_switches.end(), - invocation_switches.find(expected_switch)); + // Checks if switches that enable logging on the reporter are present on + // the invocation if and only if logging is allowed. + for (const std::string& logging_switch : logging_switches) { + EXPECT_EQ(expect_switches, invocation_switches.find(logging_switch) != + invocation_switches.end()); } } @@ -257,6 +458,9 @@ // The task runner that was in use before installing |mock_time_task_runner_|. scoped_refptr<base::SingleThreadTaskRunner> saved_task_runner_; + bool in_browser_cleaner_ui_; + bool elevation_required_; + bool prompt_trigger_called_ = false; int reporter_launch_count_ = 0; std::vector<SwReporterInvocation> reporter_launch_parameters_; @@ -266,6 +470,8 @@ // can be used to perform actions in the middle of a queue of reporters which // all launch on the same mock clock tick. base::OnceClosure first_launch_callback_; + + base::test::ScopedFeatureList scoped_feature_list_; }; class SRTFetcherPromptTest : public DialogBrowserTest { @@ -283,19 +489,19 @@ } // namespace -IN_PROC_BROWSER_TEST_F(SRTFetcherTest, NothingFound) { +IN_PROC_BROWSER_TEST_P(SRTFetcherTest, NothingFound) { RunReporter(kSwReporterNothingFound); ExpectReporterLaunches(0, 1, false); ExpectToRunAgain(kDaysBetweenSuccessfulSwReporterRuns); } -IN_PROC_BROWSER_TEST_F(SRTFetcherTest, CleanupNeeded) { +IN_PROC_BROWSER_TEST_P(SRTFetcherTest, CleanupNeeded) { RunReporter(kSwReporterCleanupNeeded); ExpectReporterLaunches(0, 1, true); ExpectToRunAgain(kDaysBetweenSuccessfulSwReporterRuns); } -IN_PROC_BROWSER_TEST_F(SRTFetcherTest, RanRecently) { +IN_PROC_BROWSER_TEST_P(SRTFetcherTest, RanRecently) { constexpr int kDaysLeft = 1; SetDaysSinceLastTriggered(kDaysBetweenSuccessfulSwReporterRuns - kDaysLeft); RunReporter(kSwReporterNothingFound); @@ -306,7 +512,7 @@ } // Test is flaky. crbug.com/705608 -IN_PROC_BROWSER_TEST_F(SRTFetcherTest, DISABLED_WaitForBrowser) { +IN_PROC_BROWSER_TEST_P(SRTFetcherTest, DISABLED_WaitForBrowser) { Profile* profile = browser()->profile(); // Ensure that even though we're closing the last browser, we don't enter the @@ -346,13 +552,13 @@ ExpectToRunAgain(kDaysBetweenSuccessfulSwReporterRuns); } -IN_PROC_BROWSER_TEST_F(SRTFetcherTest, Failure) { +IN_PROC_BROWSER_TEST_P(SRTFetcherTest, Failure) { RunReporter(kReporterFailureExitCode); ExpectReporterLaunches(0, 1, false); ExpectToRunAgain(kDaysBetweenSuccessfulSwReporterRuns); } -IN_PROC_BROWSER_TEST_F(SRTFetcherTest, RunDaily) { +IN_PROC_BROWSER_TEST_P(SRTFetcherTest, RunDaily) { PrefService* local_state = g_browser_process->local_state(); local_state->SetBoolean(prefs::kSwReporterPendingPrompt, true); SetDaysSinceLastTriggered(kDaysBetweenSuccessfulSwReporterRuns - 1); @@ -381,7 +587,7 @@ ExpectToRunAgain(kDaysBetweenSuccessfulSwReporterRuns); } -IN_PROC_BROWSER_TEST_F(SRTFetcherTest, ParameterChange) { +IN_PROC_BROWSER_TEST_P(SRTFetcherTest, ParameterChange) { // If the reporter is run several times with different parameters, it should // only be launched once, with the last parameter set. const base::FilePath path1(L"path1"); @@ -438,7 +644,7 @@ ExpectToRunAgain(kDaysBetweenSuccessfulSwReporterRuns); } -IN_PROC_BROWSER_TEST_F(SRTFetcherTest, MultipleLaunches) { +IN_PROC_BROWSER_TEST_P(SRTFetcherTest, MultipleLaunches) { const base::FilePath path1(L"path1"); const base::FilePath path2(L"path2"); const base::FilePath path3(L"path3"); @@ -506,8 +712,7 @@ } } -IN_PROC_BROWSER_TEST_F(SRTFetcherTest, ReporterLogging_NoSBExtendedReporting) { - base::test::ScopedFeatureList scoped_feature_list; +IN_PROC_BROWSER_TEST_P(SRTFetcherTest, ReporterLogging_NoSBExtendedReporting) { RunReporter(kSwReporterNothingFound); ExpectReporterLaunches(0, 1, false); ExpectLoggingSwitches(reporter_launch_parameters_.front(), false); @@ -515,8 +720,7 @@ ExpectToRunAgain(kDaysBetweenSuccessfulSwReporterRuns); } -IN_PROC_BROWSER_TEST_F(SRTFetcherTest, ReporterLogging_EnabledFirstRun) { - base::test::ScopedFeatureList scoped_feature_list; +IN_PROC_BROWSER_TEST_P(SRTFetcherTest, ReporterLogging_EnabledFirstRun) { EnableSBExtendedReporting(); // Note: don't set last time sent logs in the local state. // SBER is enabled and there is no record in the local state of the last time @@ -528,8 +732,7 @@ ExpectToRunAgain(kDaysBetweenSuccessfulSwReporterRuns); } -IN_PROC_BROWSER_TEST_F(SRTFetcherTest, ReporterLogging_EnabledNoRecentLogging) { - base::test::ScopedFeatureList scoped_feature_list; +IN_PROC_BROWSER_TEST_P(SRTFetcherTest, ReporterLogging_EnabledNoRecentLogging) { // SBER is enabled and last time logs were sent was more than // |kDaysBetweenReporterLogsSent| day ago, so we should send logs in this run. EnableSBExtendedReporting(); @@ -541,8 +744,7 @@ ExpectToRunAgain(kDaysBetweenSuccessfulSwReporterRuns); } -IN_PROC_BROWSER_TEST_F(SRTFetcherTest, ReporterLogging_EnabledRecentlyLogged) { - base::test::ScopedFeatureList scoped_feature_list; +IN_PROC_BROWSER_TEST_P(SRTFetcherTest, ReporterLogging_EnabledRecentlyLogged) { // SBER is enabled, but logs have been sent less than // |kDaysBetweenReporterLogsSent| day ago, so we shouldn't send any logs in // this run. @@ -556,8 +758,7 @@ ExpectToRunAgain(kDaysBetweenSuccessfulSwReporterRuns); } -IN_PROC_BROWSER_TEST_F(SRTFetcherTest, ReporterLogging_MultipleLaunches) { - base::test::ScopedFeatureList scoped_feature_list; +IN_PROC_BROWSER_TEST_P(SRTFetcherTest, ReporterLogging_MultipleLaunches) { EnableSBExtendedReporting(); SetLastTimeSentReport(kDaysBetweenReporterLogsSent + 3); @@ -593,6 +794,16 @@ ExpectToRunAgain(kDaysBetweenSuccessfulSwReporterRuns); } +INSTANTIATE_TEST_CASE_P(NoInBrowserCleanerUI, + SRTFetcherTest, + testing::Combine(testing::Values(false), + testing::Values(false))); + +INSTANTIATE_TEST_CASE_P(InBrowserCleanerUI, + SRTFetcherTest, + testing::Combine(testing::Values(true), + testing::Bool())); + // This provide tests which allows explicit invocation of the SRT Prompt // useful for checking dialog layout or any other interactive functionality // tests. See docs/testing/test_browser_dialog.md for description of the
diff --git a/chrome/browser/safe_browsing/srt_fetcher_win.cc b/chrome/browser/safe_browsing/srt_fetcher_win.cc index f2f9835..f3509738 100644 --- a/chrome/browser/safe_browsing/srt_fetcher_win.cc +++ b/chrome/browser/safe_browsing/srt_fetcher_win.cc
@@ -22,7 +22,6 @@ #include "base/metrics/field_trial.h" #include "base/metrics/histogram_macros.h" #include "base/metrics/sparse_histogram.h" -#include "base/process/launch.h" #include "base/strings/string_number_conversions.h" #include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" @@ -36,6 +35,7 @@ #include "chrome/browser/metrics/chrome_metrics_service_accessor.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/profiles/profile_io_data.h" +#include "chrome/browser/safe_browsing/srt_chrome_prompt_impl.h" #include "chrome/browser/safe_browsing/srt_client_info_win.h" #include "chrome/browser/safe_browsing/srt_global_error_win.h" #include "chrome/browser/ui/browser_finder.h" @@ -44,12 +44,17 @@ #include "chrome/browser/ui/global_error/global_error_service.h" #include "chrome/browser/ui/global_error/global_error_service_factory.h" #include "chrome/common/pref_names.h" +#include "components/chrome_cleaner/public/interfaces/chrome_prompt.mojom.h" #include "components/component_updater/pref_names.h" #include "components/data_use_measurement/core/data_use_user_data.h" #include "components/prefs/pref_service.h" #include "components/variations/net/variations_http_headers.h" #include "components/version_info/version_info.h" #include "content/public/browser/browser_thread.h" +#include "mojo/edk/embedder/connection_params.h" +#include "mojo/edk/embedder/pending_process_connection.h" +#include "mojo/edk/embedder/platform_channel_pair.h" +#include "mojo/public/cpp/system/message_pipe.h" #include "net/base/load_flags.h" #include "net/http/http_status_code.h" #include "net/url_request/url_fetcher.h" @@ -70,6 +75,11 @@ const wchar_t kEndTimeValueName[] = L"EndTime"; const wchar_t kStartTimeValueName[] = L"StartTime"; +const base::Feature kInBrowserCleanerUIFeature{ + "InBrowserCleanerUI", base::FEATURE_DISABLED_BY_DEFAULT}; + +const char kChromeMojoPipeTokenSwitch[] = "chrome-mojo-pipe-token"; + namespace { // Used to send UMA information about missing start and end time registry @@ -553,19 +563,83 @@ global_error->ShowBubbleView(browser); } -// This function is called from a worker thread to launch the SwReporter and -// wait for termination to collect its exit code. This task could be -// interrupted by a shutdown at any time, so it shouldn't depend on anything -// external that could be shut down beforehand. -int LaunchAndWaitForExit(const SwReporterInvocation& invocation) { - if (g_testing_delegate_) - return g_testing_delegate_->LaunchReporter(invocation); +// Class responsible for launching the reporter process and waiting for its +// completion. If feature InBrowserCleanerUI is enabled, this object will also +// be responsible for starting the ChromePromptImpl object on the IO thread and +// controlling its lifetime. +// +// Expected lifecycle of a SwReporterProcess: +// - created on the UI thread before the reporter process launch is posted +// (method ScheduleNextInvocation); +// - deleted on the UI thread once ReporterDone() finishes (the method is +// called after the reporter process exits). +// +// If feature InBrowserCleanerUI feature is enabled, the following tasks will +// be posted in sequence to the IO Thread and will retain the SwReporterProcess +// object: +// - creation of a ChromePromptImpl object right after the reporter process is +// launched (that object will be responsible for handling IPC requests from +// the reporter process); +// - deletion of the ChromePromptImpl object on ReporterDone(). +// As a consequence, the SwReporterProcess object can outlive ReporterDone() +// and will only be deleted after the ChromePromptImpl object is released on +// the IO thread. +class SwReporterProcess : public base::RefCountedThreadSafe<SwReporterProcess> { + public: + explicit SwReporterProcess(const SwReporterInvocation& invocation) + : invocation_(invocation) {} + + // This function is called from a worker thread to launch the SwReporter and + // wait for termination to collect its exit code. This task could be + // interrupted by a shutdown at any time, so it shouldn't depend on anything + // external that could be shut down beforehand. + int LaunchAndWaitForExitOnBackgroundThread(); + + // Schedules to release the instance of ChromePromptImpl on the IO thread. + void OnReporterDone(); + + const SwReporterInvocation& invocation() const { return invocation_; } + + private: + friend class base::RefCountedThreadSafe<SwReporterProcess>; + ~SwReporterProcess() = default; + + // Starts a new IPC service implementing the ChromePrompt interface and + // launches a new reporter process that can connect to the IPC. + base::Process LaunchConnectedReporterProcess(); + + // Starts a new instance of ChromePromptImpl to receive requests from the + // reporter. Must be run on the IO thread. + void CreateChromePromptImpl( + chrome_cleaner::mojom::ChromePromptRequest chrome_prompt_request); + + // Releases the instance of ChromePromptImpl. Must be run on the IO thread. + void ReleaseChromePromptImpl(); + + // Launches a new process with the command line in the invocation and + // provided launch options. Uses g_testing_delegate_ if not null. + base::Process LaunchReporterProcess( + const SwReporterInvocation& invocation, + const base::LaunchOptions& launch_options); + + // The invocation for the current reporter process. + SwReporterInvocation invocation_; + + // Implementation of the ChromePrompt service to be used by the current + // reporter process. Can only be accessed on the IO thread. + std::unique_ptr<ChromePromptImpl> chrome_prompt_impl_; +}; + +int SwReporterProcess::LaunchAndWaitForExitOnBackgroundThread() { base::Process reporter_process = - base::LaunchProcess(invocation.command_line, base::LaunchOptions()); + base::FeatureList::IsEnabled(kInBrowserCleanerUIFeature) + ? LaunchConnectedReporterProcess() + : LaunchReporterProcess(invocation_, base::LaunchOptions()); + // This exit code is used to identify that a reporter run didn't happen, so // the result should be ignored and a rerun scheduled for the usual delay. int exit_code = kReporterFailureExitCode; - UMAHistogramReporter uma(invocation.suffix); + UMAHistogramReporter uma(invocation_.suffix); if (reporter_process.IsValid()) { uma.RecordReporterStep(SW_REPORTER_START_EXECUTION); bool success = reporter_process.WaitForExit(&exit_code); @@ -576,6 +650,81 @@ return exit_code; } +void SwReporterProcess::OnReporterDone() { + if (base::FeatureList::IsEnabled(kInBrowserCleanerUIFeature)) { + BrowserThread::GetTaskRunnerForThread(BrowserThread::IO) + ->PostTask(FROM_HERE, + base::Bind(&SwReporterProcess::ReleaseChromePromptImpl, + base::RetainedRef(this))); + } +} + +base::Process SwReporterProcess::LaunchConnectedReporterProcess() { + DCHECK(base::FeatureList::IsEnabled(kInBrowserCleanerUIFeature)); + + mojo::edk::PendingProcessConnection pending_process_connection; + std::string mojo_pipe_token; + mojo::ScopedMessagePipeHandle mojo_pipe = + pending_process_connection.CreateMessagePipe(&mojo_pipe_token); + invocation_.command_line.AppendSwitchASCII(kChromeMojoPipeTokenSwitch, + mojo_pipe_token); + + mojo::edk::PlatformChannelPair channel; + base::HandlesToInheritVector handles_to_inherit; + channel.PrepareToPassClientHandleToChildProcess(&invocation_.command_line, + &handles_to_inherit); + + base::LaunchOptions launch_options; + launch_options.handles_to_inherit = &handles_to_inherit; + base::Process reporter_process = + LaunchReporterProcess(invocation_, launch_options); + + if (!reporter_process.IsValid()) + return reporter_process; + + pending_process_connection.Connect( + reporter_process.Handle(), + mojo::edk::ConnectionParams(channel.PassServerHandle())); + + chrome_cleaner::mojom::ChromePromptRequest chrome_prompt_request; + chrome_prompt_request.Bind(std::move(mojo_pipe)); + + // ChromePromptImpl tasks will need to run on the IO thread. There is no + // need to synchronize its creation, since the client end will wait for this + // initialization to be done before sending requests. + BrowserThread::GetTaskRunnerForThread(BrowserThread::IO) + ->PostTask(FROM_HERE, + base::BindOnce(&SwReporterProcess::CreateChromePromptImpl, + base::RetainedRef(this), + std::move(chrome_prompt_request))); + + return reporter_process; +} + +base::Process SwReporterProcess::LaunchReporterProcess( + const SwReporterInvocation& invocation, + const base::LaunchOptions& launch_options) { + return g_testing_delegate_ + ? g_testing_delegate_->LaunchReporter(invocation, launch_options) + : base::LaunchProcess(invocation.command_line, launch_options); +} + +void SwReporterProcess::CreateChromePromptImpl( + chrome_cleaner::mojom::ChromePromptRequest chrome_prompt_request) { + DCHECK_CURRENTLY_ON(BrowserThread::IO); + DCHECK(base::FeatureList::IsEnabled(kInBrowserCleanerUIFeature)); + + chrome_prompt_impl_ = + base::MakeUnique<ChromePromptImpl>(std::move(chrome_prompt_request)); +} + +void SwReporterProcess::ReleaseChromePromptImpl() { + DCHECK_CURRENTLY_ON(BrowserThread::IO); + DCHECK(base::FeatureList::IsEnabled(kInBrowserCleanerUIFeature)); + + chrome_prompt_impl_.release(); +} + } // namespace void DisplaySRTPromptForTesting(const base::FilePath& download_path) { @@ -771,11 +920,17 @@ base::TaskRunner* task_runner = g_testing_delegate_ ? g_testing_delegate_->BlockingTaskRunner() : blocking_task_runner_.get(); - base::PostTaskAndReplyWithResult( - task_runner, FROM_HERE, - base::Bind(&LaunchAndWaitForExit, next_invocation), + auto sw_reporter_process = + make_scoped_refptr(new SwReporterProcess(next_invocation)); + auto launch_and_wait = + base::Bind(&SwReporterProcess::LaunchAndWaitForExitOnBackgroundThread, + sw_reporter_process); + auto reporter_done = base::Bind(&ReporterRunner::ReporterDone, base::Unretained(this), Now(), - version_, next_invocation)); + version_, std::move(sw_reporter_process)); + base::PostTaskAndReplyWithResult(task_runner, FROM_HERE, + std::move(launch_and_wait), + std::move(reporter_done)); } // This method is called on the UI thread when an invocation of the reporter @@ -783,10 +938,12 @@ // thread so should be resilient to unexpected shutdown. void ReporterDone(const base::Time& reporter_start_time, const base::Version& version, - const SwReporterInvocation& finished_invocation, + scoped_refptr<SwReporterProcess> sw_reporter_process, int exit_code) { DCHECK_CURRENTLY_ON(BrowserThread::UI); + sw_reporter_process->OnReporterDone(); + base::Time now = Now(); base::TimeDelta reporter_running_time = now - reporter_start_time; @@ -809,10 +966,12 @@ // If the reporter failed to launch, do not process the results. (The exit // code itself doesn't need to be logged in this case because - // SW_REPORTER_FAILED_TO_START is logged in |LaunchAndWaitForExit|.) + // SW_REPORTER_FAILED_TO_START is logged in + // |LaunchAndWaitForExitOnBackgroundThread|.) if (exit_code == kReporterFailureExitCode) return; + const auto& finished_invocation = sw_reporter_process->invocation(); UMAHistogramReporter uma(finished_invocation.suffix); uma.ReportVersion(version); uma.ReportExitCode(exit_code); @@ -993,8 +1152,8 @@ scoped_refptr<base::TaskRunner> blocking_task_runner_ = base::CreateTaskRunnerWithTraits( - // LaunchAndWaitForExit() creates (MayBlock()) and joins - // (WithBaseSyncPrimitives()) a process. + // LaunchAndWaitForExitOnBackgroundThread() creates (MayBlock()) and + // joins (WithBaseSyncPrimitives()) a process. base::TaskTraits() .WithShutdownBehavior( base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN)
diff --git a/chrome/browser/safe_browsing/srt_fetcher_win.h b/chrome/browser/safe_browsing/srt_fetcher_win.h index 32f0ee40..a6e79e1 100644 --- a/chrome/browser/safe_browsing/srt_fetcher_win.h +++ b/chrome/browser/safe_browsing/srt_fetcher_win.h
@@ -12,6 +12,9 @@ #include <string> #include "base/command_line.h" +#include "base/feature_list.h" +#include "base/process/launch.h" +#include "base/process/process.h" #include "base/time/time.h" namespace base { @@ -44,6 +47,15 @@ // The number of days to wait before sending out reporter logs. const int kDaysBetweenReporterLogsSent = 7; +// When enabled, moves all user interaction with the Software Reporter and the +// Chrome Cleanup tool to Chrome. +extern const base::Feature kInBrowserCleanerUIFeature; + +// The switch to be passed to the Software Reporter process with the Mojo pipe +// token for the IPC communication with Chrome. +// TODO(crbug/709035) Move this to //components/chrome_cleaner. +extern const char kChromeMojoPipeTokenSwitch[]; + // Parameters used to invoke the sw_reporter component. struct SwReporterInvocation { base::CommandLine command_line; @@ -113,7 +125,9 @@ virtual ~SwReporterTestingDelegate() {} // Test mock for launching the reporter. - virtual int LaunchReporter(const SwReporterInvocation& invocation) = 0; + virtual base::Process LaunchReporter( + const SwReporterInvocation& invocation, + const base::LaunchOptions& launch_options) = 0; // Test mock for showing the prompt. virtual void TriggerPrompt(Browser* browser,
diff --git a/chrome/browser/sync/test/integration/sync_test.cc b/chrome/browser/sync/test/integration/sync_test.cc index ff0126c..d3e6e4b 100644 --- a/chrome/browser/sync/test/integration/sync_test.cc +++ b/chrome/browser/sync/test/integration/sync_test.cc
@@ -410,7 +410,8 @@ base::FilePath pref_path(profile_path.Append(chrome::kPreferencesFilename)); const char* contents = preexisting_preferences_file_contents_.c_str(); size_t contents_length = preexisting_preferences_file_contents_.size(); - if (!base::WriteFile(pref_path, contents, contents_length)) { + if (base::WriteFile(pref_path, contents, contents_length) != + static_cast<int>(contents_length)) { LOG(FATAL) << "Preexisting Preferences file could not be written."; } }
diff --git a/chrome/browser/sync_file_system/drive_backend/sync_task_manager_unittest.cc b/chrome/browser/sync_file_system/drive_backend/sync_task_manager_unittest.cc index b96a5e9..730cfad 100644 --- a/chrome/browser/sync_file_system/drive_backend/sync_task_manager_unittest.cc +++ b/chrome/browser/sync_file_system/drive_backend/sync_task_manager_unittest.cc
@@ -47,15 +47,6 @@ *status_out = status; } -template <typename T> -void IncrementAndAssignWithOwnedPointer(T* object, - int* counter, - SyncStatusCode* status_out, - SyncStatusCode status) { - ++(*counter); - *status_out = status; -} - class TaskManagerClient : public SyncTaskManager::Client, public base::SupportsWeakPtr<TaskManagerClient> {
diff --git a/chrome/browser/translate/translate_ranker_factory.cc b/chrome/browser/translate/translate_ranker_factory.cc index e86c3d2..fe44939 100644 --- a/chrome/browser/translate/translate_ranker_factory.cc +++ b/chrome/browser/translate/translate_ranker_factory.cc
@@ -4,6 +4,7 @@ #include "chrome/browser/translate/translate_ranker_factory.h" +#include "chrome/browser/browser_process.h" #include "chrome/browser/profiles/incognito_helpers.h" #include "components/keyed_service/content/browser_context_dependency_manager.h" #include "components/keyed_service/core/keyed_service.h" @@ -35,7 +36,7 @@ content::BrowserContext* browser_context) const { return new TranslateRankerImpl( TranslateRankerImpl::GetModelPath(browser_context->GetPath()), - TranslateRankerImpl::GetModelURL()); + TranslateRankerImpl::GetModelURL(), g_browser_process->ukm_service()); } content::BrowserContext* TranslateRankerFactory::GetBrowserContextToUse(
diff --git a/chrome/browser/ui/android/infobars/duplicate_download_infobar.cc b/chrome/browser/ui/android/infobars/duplicate_download_infobar.cc index 51990667..cdf7dd7 100644 --- a/chrome/browser/ui/android/infobars/duplicate_download_infobar.cc +++ b/chrome/browser/ui/android/infobars/duplicate_download_infobar.cc
@@ -38,7 +38,7 @@ base::android::ScopedJavaLocalRef<jobject> java_infobar( Java_DuplicateDownloadInfoBar_createInfoBar( env, j_file_path, delegate->IsOfflinePage(), j_page_url, - delegate->IsOffTheRecord())); + delegate->IsOffTheRecord(), delegate->DuplicateRequestExists())); return java_infobar; }
diff --git a/chrome/browser/ui/cocoa/OWNERS b/chrome/browser/ui/cocoa/OWNERS index 2b2fecee..ca6b82b 100644 --- a/chrome/browser/ui/cocoa/OWNERS +++ b/chrome/browser/ui/cocoa/OWNERS
@@ -6,7 +6,6 @@ mark@chromium.org rohitrao@chromium.org rsesek@chromium.org -shess@chromium.org tapted@chromium.org thakis@chromium.org
diff --git a/chrome/browser/ui/cocoa/toolbar/OWNERS b/chrome/browser/ui/cocoa/toolbar/OWNERS index ae0df7c..fdbfdb1 100644 --- a/chrome/browser/ui/cocoa/toolbar/OWNERS +++ b/chrome/browser/ui/cocoa/toolbar/OWNERS
@@ -1,3 +1,2 @@ avi@chromium.org rohitrao@chromium.org -shess@chromium.org
diff --git a/chrome/browser/ui/profile_error_browsertest.cc b/chrome/browser/ui/profile_error_browsertest.cc index 4f8a8b0..3de37298 100644 --- a/chrome/browser/ui/profile_error_browsertest.cc +++ b/chrome/browser/ui/profile_error_browsertest.cc
@@ -48,8 +48,9 @@ // Write either an empty or an invalid string to the user profile as // determined by the boolean parameter. const std::string kUserProfileData(do_corrupt_ ? "invalid json" : "{}"); - if (!base::WriteFile(pref_file, kUserProfileData.c_str(), - kUserProfileData.size())) { + if (base::WriteFile(pref_file, kUserProfileData.c_str(), + kUserProfileData.size()) != + static_cast<int>(kUserProfileData.size())) { ADD_FAILURE(); return false; }
diff --git a/chrome/browser/ui/views/srt_prompt_dialog.cc b/chrome/browser/ui/views/srt_prompt_dialog.cc index 1c33b70..21ccc1d 100644 --- a/chrome/browser/ui/views/srt_prompt_dialog.cc +++ b/chrome/browser/ui/views/srt_prompt_dialog.cc
@@ -6,6 +6,7 @@ #include <vector> +#include "base/memory/ptr_util.h" #include "base/strings/string16.h" #include "chrome/app/vector_icons/vector_icons.h" #include "chrome/browser/safe_browsing/srt_prompt_controller.h" @@ -17,6 +18,7 @@ #include "components/web_modal/web_contents_modal_dialog_host.h" #include "ui/base/ui_base_types.h" #include "ui/events/event.h" +#include "ui/gfx/animation/slide_animation.h" #include "ui/gfx/geometry/size.h" #include "ui/gfx/native_widget_types.h" #include "ui/gfx/paint_vector_icon.h" @@ -152,13 +154,70 @@ } // namespace //////////////////////////////////////////////////////////////////////////////// +// SRTPromptDialog::ExpandableMessageView +// +// A view, whose visibilty can be toggled, and will be used for the details +// section the main dialog. +class SRTPromptDialog::ExpandableMessageView : public views::View { + public: + explicit ExpandableMessageView(const std::vector<LabelInfo>& labels); + ~ExpandableMessageView() override; + + void AnimateToState(double state); + + // views::View overrides. + gfx::Size GetPreferredSize() const override; + int GetHeightForWidth(int width) const override; + + private: + // A number between 0 and 1 that determines how much of the view's preferred + // height should be visible. + double animation_state_; + + DISALLOW_COPY_AND_ASSIGN(ExpandableMessageView); +}; + +SRTPromptDialog::ExpandableMessageView::ExpandableMessageView( + const std::vector<LabelInfo>& labels) + : animation_state_(0.0) { + // Add the main message view inside a scroll view. + views::View* label_view = + CreateLabelView(views::kUnrelatedControlLargeHorizontalSpacing, labels); + views::ScrollView* scroll_view = new views::ScrollView(); + scroll_view->ClipHeightTo(kDetailsSectionMaxHeight, kDetailsSectionMaxHeight); + scroll_view->SetContents(label_view); + scroll_view->SetSize(gfx::Size(kDialogWidth, kDetailsSectionMaxHeight)); + AddChildView(scroll_view); +} + +SRTPromptDialog::ExpandableMessageView::~ExpandableMessageView() {} + +void SRTPromptDialog::ExpandableMessageView::AnimateToState(double state) { + DCHECK_LE(0.0, state); + DCHECK_GE(1.0, state); + + animation_state_ = state; + PreferredSizeChanged(); +} + +gfx::Size SRTPromptDialog::ExpandableMessageView::GetPreferredSize() const { + return gfx::Size(kDialogWidth, kDetailsSectionMaxHeight * animation_state_); +} + +int SRTPromptDialog::ExpandableMessageView::GetHeightForWidth(int width) const { + return GetPreferredSize().height(); +} + +//////////////////////////////////////////////////////////////////////////////// // SRTPromptDialog SRTPromptDialog::SRTPromptDialog(safe_browsing::SRTPromptController* controller) : browser_(nullptr), controller_(controller), - details_view_(new views::View()), - details_button_(nullptr) { + slide_animation_(base::MakeUnique<gfx::SlideAnimation>(this)), + details_view_(new ExpandableMessageView(controller_->GetDetailsText())), + details_button_( + new views::LabelButton(this, controller_->GetShowDetailsLabel())) { DCHECK(controller_); SetLayoutManager(new views::BoxLayout( @@ -170,15 +229,8 @@ AddChildView(CreateLabelView(0, controller_->GetMainText())); AddChildView(new views::Separator()); - // The details section starts off empty and will be populated when the user - // clicks the button to expand the details section. Its child views are - // removed when the section is closed. - details_view_->SetLayoutManager(new views::FillLayout()); - details_view_->SetVisible(false); AddChildView(details_view_); - details_button_ = - new views::LabelButton(this, controller_->GetShowDetailsLabel()); details_button_->SetEnabledTextColors(GetDetailsButtonColor()); UpdateDetailsButton(); AddChildView(CreateViewWithInsets( @@ -197,6 +249,7 @@ void SRTPromptDialog::Show(Browser* browser) { DCHECK(browser); DCHECK(!browser_); + DCHECK(controller_); browser_ = browser; constrained_window::CreateBrowserModalDialogViews( @@ -218,6 +271,7 @@ } base::string16 SRTPromptDialog::GetWindowTitle() const { + DCHECK(controller_); return controller_->GetWindowTitle(); } @@ -226,6 +280,7 @@ base::string16 SRTPromptDialog::GetDialogButtonLabel( ui::DialogButton button) const { DCHECK(button == ui::DIALOG_BUTTON_OK || button == ui::DIALOG_BUTTON_CANCEL); + DCHECK(controller_); if (button == ui::DIALOG_BUTTON_OK) return controller_->GetAcceptButtonLabel(); @@ -261,40 +316,39 @@ DCHECK_EQ(sender, details_button_); DCHECK(browser_); - details_view_->SetVisible(!details_view_->visible()); - if (details_view_->visible()) { - // Populate the details view adding the main message view inside a scroll - // view. - views::View* label_view = - CreateLabelView(views::kUnrelatedControlLargeHorizontalSpacing, - controller_->GetDetailsText()); - views::ScrollView* scroll_view = new views::ScrollView(); - scroll_view->ClipHeightTo(/*min_height=*/0, kDetailsSectionMaxHeight); - scroll_view->SetContents(label_view); - details_view_->AddChildView(scroll_view); - } else { - details_view_->RemoveAllChildViews(/*delete_children=*/true); - } + if (slide_animation_->IsShowing()) + slide_animation_->Hide(); + else + slide_animation_->Show(); +} - UpdateDetailsButton(); +void SRTPromptDialog::AnimationProgressed(const gfx::Animation* animation) { + DCHECK_EQ(slide_animation_.get(), animation); + details_view_->AnimateToState(animation->GetCurrentValue()); ChromeWebModalDialogManagerDelegate* manager = browser_; constrained_window::UpdateWidgetModalDialogPosition( GetWidget(), manager->GetWebContentsModalDialogHost()); } +void SRTPromptDialog::AnimationEnded(const gfx::Animation* animation) { + DCHECK_EQ(slide_animation_.get(), animation); + UpdateDetailsButton(); +} + SkColor SRTPromptDialog::GetDetailsButtonColor() { return GetNativeTheme()->GetSystemColor( ui::NativeTheme::kColorId_LinkEnabled); } void SRTPromptDialog::UpdateDetailsButton() { - details_button_->SetText(details_view_->visible() + DCHECK(controller_); + details_button_->SetText(slide_animation_->IsShowing() ? controller_->GetHideDetailsLabel() : controller_->GetShowDetailsLabel()); details_button_->SetImage( views::Button::STATE_NORMAL, - details_view_->visible() + slide_animation_->IsShowing() ? gfx::CreateVectorIcon(kCaretUpIcon, GetDetailsButtonColor()) : gfx::CreateVectorIcon(kCaretDownIcon, GetDetailsButtonColor())); }
diff --git a/chrome/browser/ui/views/srt_prompt_dialog.h b/chrome/browser/ui/views/srt_prompt_dialog.h index 9e2f4bb..59e1110e 100644 --- a/chrome/browser/ui/views/srt_prompt_dialog.h +++ b/chrome/browser/ui/views/srt_prompt_dialog.h
@@ -5,8 +5,11 @@ #ifndef CHROME_BROWSER_UI_VIEWS_SRT_PROMPT_DIALOG_H_ #define CHROME_BROWSER_UI_VIEWS_SRT_PROMPT_DIALOG_H_ +#include <memory> + #include "base/macros.h" #include "third_party/skia/include/core/SkColor.h" +#include "ui/gfx/animation/animation_delegate.h" #include "ui/gfx/image/image_skia.h" #include "ui/views/controls/button/button.h" #include "ui/views/controls/button/label_button.h" @@ -14,6 +17,10 @@ class Browser; +namespace gfx { +class SlideAnimation; +} + namespace safe_browsing { class SRTPromptController; } @@ -34,7 +41,8 @@ // interaction with the dialog. See the |SRTPromptController| class's // description for more details. class SRTPromptDialog : public views::DialogDelegateView, - public views::ButtonListener { + public views::ButtonListener, + public gfx::AnimationDelegate { public: // The |controller| object manages its own lifetime and is not owned by // |SRTPromptDialog|. See the description of the |SRTPromptController| class @@ -62,7 +70,13 @@ // views::ButtonListener overrides. void ButtonPressed(views::Button* sender, const ui::Event& event) override; + // gfx::AnimationDelegate overrides. + void AnimationProgressed(const gfx::Animation* animation) override; + void AnimationEnded(const gfx::Animation* animation) override; + private: + class ExpandableMessageView; + SkColor GetDetailsButtonColor(); void UpdateDetailsButton(); @@ -71,7 +85,8 @@ // user interaction since the controller can delete itself after that point. safe_browsing::SRTPromptController* controller_; - views::View* details_view_; + std::unique_ptr<gfx::SlideAnimation> slide_animation_; + ExpandableMessageView* details_view_; views::LabelButton* details_button_; DISALLOW_COPY_AND_ASSIGN(SRTPromptDialog);
diff --git a/chrome/browser/ui/webui/chromeos/first_run/first_run_ui.cc b/chrome/browser/ui/webui/chromeos/first_run/first_run_ui.cc index 85a73c1..9601a74 100644 --- a/chrome/browser/ui/webui/chromeos/first_run/first_run_ui.cc +++ b/chrome/browser/ui/webui/chromeos/first_run/first_run_ui.cc
@@ -63,6 +63,9 @@ "transitionsEnabled", base::CommandLine::ForCurrentProcess()->HasSwitch( chromeos::switches::kEnableFirstRunUITransitions)); + localized_strings->SetString( + "accessibleTitle", + l10n_util::GetStringUTF16(IDS_FIRST_RUN_STEP_ACCESSIBLE_TITLE)); ash::WmShelf* shelf = ash::WmShelf::ForWindow(ash::ShellPort::Get()->GetPrimaryRootWindow()); std::string shelf_alignment; @@ -109,4 +112,3 @@ } } // namespace chromeos -
diff --git a/chrome/browser/ui/webui/engagement/site_engagement_ui.cc b/chrome/browser/ui/webui/engagement/site_engagement_ui.cc index 2321fc1..d840187 100644 --- a/chrome/browser/ui/webui/engagement/site_engagement_ui.cc +++ b/chrome/browser/ui/webui/engagement/site_engagement_ui.cc
@@ -20,42 +20,41 @@ namespace { -// Implementation of mojom::SiteEngagementUIHandler that gets information from -// the -// SiteEngagementService to provide data for the WebUI. -class SiteEngagementUIHandlerImpl : public mojom::SiteEngagementUIHandler { +// Implementation of mojom::SiteEngagementDetailsProvider that gets information +// from the SiteEngagementService to provide data for the WebUI. +class SiteEngagementDetailsProviderImpl + : public mojom::SiteEngagementDetailsProvider { public: - // SiteEngagementUIHandlerImpl is deleted when the supplied pipe is destroyed. - SiteEngagementUIHandlerImpl( + // Instance is deleted when the supplied pipe is destroyed. + SiteEngagementDetailsProviderImpl( Profile* profile, - mojo::InterfaceRequest<mojom::SiteEngagementUIHandler> request) + mojo::InterfaceRequest<mojom::SiteEngagementDetailsProvider> request) : profile_(profile), binding_(this, std::move(request)) { DCHECK(profile_); } - ~SiteEngagementUIHandlerImpl() override {} + ~SiteEngagementDetailsProviderImpl() override {} - // mojom::SiteEngagementUIHandler overrides: - void GetSiteEngagementInfo( - const GetSiteEngagementInfoCallback& callback) override { + // mojom::SiteEngagementDetailsProvider overrides: + void GetSiteEngagementDetails( + const GetSiteEngagementDetailsCallback& callback) override { SiteEngagementService* service = SiteEngagementService::Get(profile_); - std::map<GURL, double> score_map = service->GetScoreMap(); + std::vector<mojom::SiteEngagementDetails> scores = service->GetAllDetails(); - std::vector<mojom::SiteEngagementInfoPtr> engagement_info; - engagement_info.reserve(score_map.size()); - for (const auto& info : score_map) { - mojom::SiteEngagementInfoPtr origin_info( - mojom::SiteEngagementInfo::New()); - origin_info->origin = info.first; - origin_info->score = info.second; + std::vector<mojom::SiteEngagementDetailsPtr> engagement_info; + engagement_info.reserve(scores.size()); + for (const auto& info : scores) { + mojom::SiteEngagementDetailsPtr origin_info( + mojom::SiteEngagementDetails::New()); + *origin_info = std::move(info); engagement_info.push_back(std::move(origin_info)); } callback.Run(std::move(engagement_info)); } - void SetSiteEngagementScoreForOrigin(const GURL& origin, - double score) override { + void SetSiteEngagementBaseScoreForUrl(const GURL& origin, + double score) override { if (!origin.is_valid() || score < 0 || score > SiteEngagementService::GetMaxPoints() || std::isnan(score)) { return; @@ -69,21 +68,22 @@ // The Profile* handed to us in our constructor. Profile* profile_; - mojo::Binding<mojom::SiteEngagementUIHandler> binding_; + mojo::Binding<mojom::SiteEngagementDetailsProvider> binding_; - DISALLOW_COPY_AND_ASSIGN(SiteEngagementUIHandlerImpl); + DISALLOW_COPY_AND_ASSIGN(SiteEngagementDetailsProviderImpl); }; } // namespace SiteEngagementUI::SiteEngagementUI(content::WebUI* web_ui) - : MojoWebUIController<mojom::SiteEngagementUIHandler>(web_ui) { + : MojoWebUIController<mojom::SiteEngagementDetailsProvider>(web_ui) { // Set up the chrome://site-engagement/ source. std::unique_ptr<content::WebUIDataSource> source( content::WebUIDataSource::Create(chrome::kChromeUISiteEngagementHost)); source->AddResourcePath("site_engagement.js", IDR_SITE_ENGAGEMENT_JS); - source->AddResourcePath("chrome/browser/engagement/site_engagement.mojom", - IDR_SITE_ENGAGEMENT_MOJO_JS); + source->AddResourcePath( + "chrome/browser/engagement/site_engagement_details.mojom", + IDR_SITE_ENGAGEMENT_MOJO_JS); source->AddResourcePath("url/mojo/url.mojom", IDR_URL_MOJO_JS); source->SetDefaultResource(IDR_SITE_ENGAGEMENT_HTML); source->UseGzip(std::unordered_set<std::string>()); @@ -93,7 +93,7 @@ SiteEngagementUI::~SiteEngagementUI() {} void SiteEngagementUI::BindUIHandler( - mojo::InterfaceRequest<mojom::SiteEngagementUIHandler> request) { - ui_handler_.reset(new SiteEngagementUIHandlerImpl( + mojo::InterfaceRequest<mojom::SiteEngagementDetailsProvider> request) { + ui_handler_.reset(new SiteEngagementDetailsProviderImpl( Profile::FromWebUI(web_ui()), std::move(request))); }
diff --git a/chrome/browser/ui/webui/engagement/site_engagement_ui.h b/chrome/browser/ui/webui/engagement/site_engagement_ui.h index 2580c89..98aa2c9 100644 --- a/chrome/browser/ui/webui/engagement/site_engagement_ui.h +++ b/chrome/browser/ui/webui/engagement/site_engagement_ui.h
@@ -6,12 +6,12 @@ #define CHROME_BROWSER_UI_WEBUI_ENGAGEMENT_SITE_ENGAGEMENT_UI_H_ #include "base/macros.h" -#include "chrome/browser/engagement/site_engagement.mojom.h" +#include "chrome/browser/engagement/site_engagement_details.mojom.h" #include "chrome/browser/ui/webui/mojo_web_ui_controller.h" // The UI for chrome://site-engagement/. class SiteEngagementUI - : public MojoWebUIController<mojom::SiteEngagementUIHandler> { + : public MojoWebUIController<mojom::SiteEngagementDetailsProvider> { public: explicit SiteEngagementUI(content::WebUI* web_ui); ~SiteEngagementUI() override; @@ -19,9 +19,10 @@ private: // MojoWebUIController overrides: void BindUIHandler( - mojo::InterfaceRequest<mojom::SiteEngagementUIHandler> request) override; + mojo::InterfaceRequest<mojom::SiteEngagementDetailsProvider> request) + override; - std::unique_ptr<mojom::SiteEngagementUIHandler> ui_handler_; + std::unique_ptr<mojom::SiteEngagementDetailsProvider> ui_handler_; DISALLOW_COPY_AND_ASSIGN(SiteEngagementUI); };
diff --git a/chrome/browser/ui/webui/engagement/site_engagement_ui_browsertest.cc b/chrome/browser/ui/webui/engagement/site_engagement_ui_browsertest.cc index b1d442e..7a437bd 100644 --- a/chrome/browser/ui/webui/engagement/site_engagement_ui_browsertest.cc +++ b/chrome/browser/ui/webui/engagement/site_engagement_ui_browsertest.cc
@@ -66,25 +66,50 @@ ASSERT_TRUE(page_is_populated_); } - // Verifies that a row exists for the specified site URL. - void ExpectPageContainsUrl(const GURL& url) { - ASSERT_TRUE(page_is_populated_); + // Expects that there will be the specified number of rows. + int NumberOfRows() { + EXPECT_TRUE(page_is_populated_); - bool found_url = false; - ASSERT_TRUE(content::ExecuteScriptAndExtractBool( + int number_of_rows = -1; + EXPECT_TRUE(content::ExecuteScriptAndExtractInt( browser()->tab_strip_model()->GetActiveWebContents(), - base::JoinString( - {"var origin_cells = " - " Array.from(document.getElementsByClassName('origin-cell'));" - "window.domAutomationController.send(origin_cells.reduce(" - " (found, element) => {" - " return found || (element.innerHTML == '", - url.spec(), - "');" - " }, false));"}, - ""), - &found_url)); - EXPECT_TRUE(found_url); + "window.domAutomationController.send(" + " document.getElementsByClassName('origin-cell').length);", + &number_of_rows)); + + return number_of_rows; + } + + // Returns the origin URL at the specified zero-based row index. + std::string OriginUrlAtRow(int index) { + EXPECT_TRUE(page_is_populated_); + + std::string origin_url; + EXPECT_TRUE(content::ExecuteScriptAndExtractString( + browser()->tab_strip_model()->GetActiveWebContents(), + base::JoinString({"window.domAutomationController.send(" + " document.getElementsByClassName('origin-cell')[", + base::IntToString(index), "].innerHTML);"}, + ""), + &origin_url)); + + return origin_url; + } + + // Returns the stringified score at the specified zero-based row index. + std::string ScoreAtRow(int index) { + EXPECT_TRUE(page_is_populated_); + + std::string score_string; + EXPECT_TRUE(content::ExecuteScriptAndExtractString( + browser()->tab_strip_model()->GetActiveWebContents(), + base::JoinString({"window.domAutomationController.send(" + " document.getElementsByClassName('score-input')[", + base::IntToString(index), "].value);"}, + ""), + &score_string)); + + return score_string; } private: @@ -98,5 +123,17 @@ NavigateToWebUi(); WaitUntilPagePopulated(); - ExpectPageContainsUrl(kExampleUrl); + EXPECT_EQ(1, NumberOfRows()); + EXPECT_EQ(kExampleUrl, OriginUrlAtRow(0)); +} + +IN_PROC_BROWSER_TEST_F(SiteEngagementUiBrowserTest, + ScoresHaveTwoDecimalPlaces) { + ResetBaseScore(kExampleUrl, 3.14159); + + NavigateToWebUi(); + WaitUntilPagePopulated(); + + EXPECT_EQ(1, NumberOfRows()); + EXPECT_EQ("3.14", ScoreAtRow(0)); }
diff --git a/chrome/browser/ui/webui/options/browser_options_handler.cc b/chrome/browser/ui/webui/options/browser_options_handler.cc index db8af7d..f851526ad 100644 --- a/chrome/browser/ui/webui/options/browser_options_handler.cc +++ b/chrome/browser/ui/webui/options/browser_options_handler.cc
@@ -738,8 +738,7 @@ values->SetBoolean("cupsPrintDisabled", base::CommandLine::ForCurrentProcess()->HasSwitch( ::switches::kDisableNativeCups)); - values->SetString("cupsPrintLearnMoreURL", - chrome::kChromeUIMdCupsSettingsURL); + values->SetString("cupsPrintLearnMoreURL", chrome::kCrosPrintingLearnMoreURL); #endif // defined(OS_CHROMEOS) #if BUILDFLAG(ENABLE_SERVICE_DISCOVERY)
diff --git a/chrome/browser/ui/webui/settings/chromeos/cups_printers_handler.cc b/chrome/browser/ui/webui/settings/chromeos/cups_printers_handler.cc index a08eb77d..8a8b009 100644 --- a/chrome/browser/ui/webui/settings/chromeos/cups_printers_handler.cc +++ b/chrome/browser/ui/webui/settings/chromeos/cups_printers_handler.cc
@@ -16,9 +16,9 @@ #include "base/threading/sequenced_task_runner_handle.h" #include "base/values.h" #include "chrome/browser/browser_process.h" -#include "chrome/browser/chromeos/printing/fake_printer_discoverer.h" #include "chrome/browser/chromeos/printing/ppd_provider_factory.h" #include "chrome/browser/chromeos/printing/printer_configurer.h" +#include "chrome/browser/chromeos/printing/printer_discoverer.h" #include "chrome/browser/chromeos/printing/printers_manager_factory.h" #include "chrome/browser/download/download_prefs.h" #include "chrome/browser/profiles/profile.h" @@ -378,23 +378,16 @@ } void CupsPrintersHandler::HandleStartDiscovery(const base::ListValue* args) { - if (!printer_discoverer_.get()) - printer_discoverer_ = chromeos::PrinterDiscoverer::Create(); + if (!printer_discoverer_.get()) { + printer_discoverer_ = + chromeos::PrinterDiscoverer::CreateForProfile(profile_); + } printer_discoverer_->AddObserver(this); - if (!printer_discoverer_->StartDiscovery()) { - CallJavascriptFunction("cr.webUIListenerCallback", - base::Value("on-printer-discovery-failed")); - printer_discoverer_->RemoveObserver(this); - } } void CupsPrintersHandler::HandleStopDiscovery(const base::ListValue* args) { - if (printer_discoverer_.get()) { - printer_discoverer_->RemoveObserver(this); - printer_discoverer_->StopDiscovery(); - printer_discoverer_.reset(); - } + printer_discoverer_.reset(); } void CupsPrintersHandler::OnPrintersFound( @@ -402,16 +395,14 @@ std::unique_ptr<base::ListValue> printers_list = base::MakeUnique<base::ListValue>(); for (const auto& printer : printers) { - std::unique_ptr<base::DictionaryValue> printer_info = - GetPrinterInfo(printer); - printers_list->Append(std::move(printer_info)); + printers_list->Append(GetPrinterInfo(printer)); } CallJavascriptFunction("cr.webUIListenerCallback", base::Value("on-printer-discovered"), *printers_list); } -void CupsPrintersHandler::OnDiscoveryDone() { +void CupsPrintersHandler::OnDiscoveryInitialScanDone() { CallJavascriptFunction("cr.webUIListenerCallback", base::Value("on-printer-discovery-done")); }
diff --git a/chrome/browser/ui/webui/settings/chromeos/cups_printers_handler.h b/chrome/browser/ui/webui/settings/chromeos/cups_printers_handler.h index 68f2cc1..847e001 100644 --- a/chrome/browser/ui/webui/settings/chromeos/cups_printers_handler.h +++ b/chrome/browser/ui/webui/settings/chromeos/cups_printers_handler.h
@@ -88,7 +88,7 @@ // chromeos::PrinterDiscoverer::Observer override: void OnPrintersFound(const std::vector<Printer>& printers) override; - void OnDiscoveryDone() override; + void OnDiscoveryInitialScanDone() override; // Invokes debugd to add the printer to CUPS. If |ipp_everywhere| is true, // automatic configuration will be attempted and |ppd_path| is ignored.
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 647c450..10038caf 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
@@ -46,6 +46,7 @@ #include "components/user_manager/user.h" #include "components/user_manager/user_manager.h" #include "ui/chromeos/strings/grit/ui_chromeos_strings.h" +#include "ui/display/display_switches.h" #else #include "chrome/browser/ui/webui/settings/system_handler.h" #endif @@ -642,8 +643,7 @@ {"displayArrangementText", IDS_SETTINGS_DISPLAY_ARRANGEMENT_TEXT}, {"displayArrangementTitle", IDS_SETTINGS_DISPLAY_ARRANGEMENT_TITLE}, {"displayMirror", IDS_SETTINGS_DISPLAY_MIRROR}, - {"displayMirrorOff", IDS_SETTINGS_DISPLAY_MIRRORING_OFF}, - {"displayMirrorOn", IDS_SETTINGS_DISPLAY_MIRRORING_ON}, + {"displayUnfiedDesktop", IDS_SETTINGS_DISPLAY_UNIFIED_DESKTOP}, {"displayResolutionTitle", IDS_SETTINGS_DISPLAY_RESOLUTION_TITLE}, {"displayResolutionText", IDS_SETTINGS_DISPLAY_RESOLUTION_TEXT}, {"displayResolutionTextBest", IDS_SETTINGS_DISPLAY_RESOLUTION_TEXT_BEST}, @@ -665,10 +665,12 @@ {"displayTouchCalibrationTitle", IDS_SETTINGS_DISPLAY_TOUCH_CALIBRATION_TITLE}, {"displayTouchCalibrationText", - IDS_SETTINGS_DISPLAY_TOUCH_CALIBRATION_TEXT} - }; + IDS_SETTINGS_DISPLAY_TOUCH_CALIBRATION_TEXT}}; AddLocalizedStringsBulk(html_source, display_strings, arraysize(display_strings)); + html_source->AddBoolean("unifiedDesktopAvailable", + base::CommandLine::ForCurrentProcess()->HasSwitch( + ::switches::kEnableUnifiedDesktop)); html_source->AddBoolean( "enableTouchCalibrationSetting", @@ -885,6 +887,8 @@ IDS_SETTINGS_INTERNET_KNOWN_NETWORKS_MENU_REMOVE_PREFERRED}, {"knownNetworksMenuForget", IDS_SETTINGS_INTERNET_KNOWN_NETWORKS_MENU_FORGET}, + {"networkAllowDataRoaming", + IDS_SETTINGS_SETTINGS_NETWORK_ALLOW_DATA_ROAMING}, {"networkAutoConnect", IDS_SETTINGS_INTERNET_NETWORK_AUTO_CONNECT}, {"networkButtonActivate", IDS_SETTINGS_INTERNET_BUTTON_ACTIVATE}, {"networkButtonConfigure", IDS_SETTINGS_INTERNET_BUTTON_CONFIGURE},
diff --git a/chrome/browser/ui/webui/settings/profile_info_handler.cc b/chrome/browser/ui/webui/settings/profile_info_handler.cc index 5bb0e95..17f8fc7 100644 --- a/chrome/browser/ui/webui/settings/profile_info_handler.cc +++ b/chrome/browser/ui/webui/settings/profile_info_handler.cc
@@ -206,15 +206,13 @@ ->GetProfileAttributesStorage() .GetProfileAttributesWithPath(profile_->GetPath(), &entry)) { name = base::UTF16ToUTF8(entry->GetName()); - - if (entry->IsUsingGAIAPicture() && entry->GetGAIAPicture()) { - constexpr int kAvatarIconSize = 40; - gfx::Image icon = profiles::GetSizedAvatarIcon( - entry->GetAvatarIcon(), true, kAvatarIconSize, kAvatarIconSize); - icon_url = webui::GetBitmapDataUrl(icon.AsBitmap()); - } else { - icon_url = profiles::GetDefaultAvatarIconUrl(entry->GetAvatarIconIndex()); - } + // TODO(crbug.com/710660): return chrome://theme/IDR_PROFILE_AVATAR_* + // and update theme_source.cc to get high res avatar icons. This does less + // work here, sends less over IPC, and is more stable with returned results. + constexpr int kAvatarIconSize = 40; + gfx::Image icon = profiles::GetSizedAvatarIcon( + entry->GetAvatarIcon(), true, kAvatarIconSize, kAvatarIconSize); + icon_url = webui::GetBitmapDataUrl(icon.AsBitmap()); } #endif // defined(OS_CHROMEOS)
diff --git a/chrome/browser/ui/webui/settings/profile_info_handler_unittest.cc b/chrome/browser/ui/webui/settings/profile_info_handler_unittest.cc index f94e03c..94a0b45 100644 --- a/chrome/browser/ui/webui/settings/profile_info_handler_unittest.cc +++ b/chrome/browser/ui/webui/settings/profile_info_handler_unittest.cc
@@ -14,7 +14,11 @@ #include "content/public/browser/web_ui_data_source.h" #include "content/public/test/test_browser_thread_bundle.h" #include "content/public/test/test_web_ui.h" +#include "net/base/data_url.h" #include "testing/gtest/include/gtest/gtest.h" +#include "third_party/skia/include/core/SkBitmap.h" +#include "ui/gfx/codec/png_codec.h" +#include "url/gurl.h" #if defined(OS_CHROMEOS) #include "chrome/browser/chromeos/login/users/fake_chrome_user_manager.h" @@ -78,7 +82,15 @@ EXPECT_FALSE(icon_url.empty()); #else EXPECT_EQ("Profile 1", name); - EXPECT_EQ("chrome://theme/IDR_PROFILE_AVATAR_0", icon_url); + + std::string mime, charset, data; + EXPECT_TRUE(net::DataURL::Parse(GURL(icon_url), &mime, &charset, &data)); + + EXPECT_EQ("image/png", mime); + SkBitmap bitmap; + EXPECT_TRUE(gfx::PNGCodec::Decode( + reinterpret_cast<const unsigned char*>(data.data()), data.size(), + &bitmap)); #endif }
diff --git a/chrome/browser/win/jumplist.cc b/chrome/browser/win/jumplist.cc index 5f464ca..071087a 100644 --- a/chrome/browser/win/jumplist.cc +++ b/chrome/browser/win/jumplist.cc
@@ -231,10 +231,11 @@ } // Updates the jumplist, once all the data has been fetched. -void RunUpdateJumpList(IncognitoModePrefs::Availability incognito_availability, - const std::wstring& app_id, - const base::FilePath& icon_dir, - base::RefCountedData<JumpListData>* ref_counted_data) { +void RunUpdateJumpListUserVisiblePriority( + IncognitoModePrefs::Availability incognito_availability, + const std::wstring& app_id, + const base::FilePath& icon_dir, + base::RefCountedData<JumpListData>* ref_counted_data) { JumpListData* data = &ref_counted_data->data; ShellLinkItemList local_most_visited_pages; ShellLinkItemList local_recently_closed_pages; @@ -284,7 +285,7 @@ task_id_(base::CancelableTaskTracker::kBadTaskId), update_jumplisticons_task_runner_(base::CreateCOMSTATaskRunnerWithTraits( base::TaskTraits() - .WithPriority(base::TaskPriority::BACKGROUND) + .WithPriority(base::TaskPriority::USER_VISIBLE) .WithShutdownBehavior( base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN) .MayBlock())), @@ -507,7 +508,7 @@ if (!waiting_for_icons) { // No more favicons are needed by the application JumpList. Schedule a - // RunUpdateJumpList call. + // RunUpdateJumpListUserVisiblePriority call. PostRunUpdate(); return; } @@ -533,7 +534,8 @@ JumpListData* data = &jumplist_data_->data; base::AutoLock auto_lock(data->list_lock_); // Attach the received data to the ShellLinkItem object. - // This data will be decoded by the RunUpdateJumpList method. + // This data will be decoded by the RunUpdateJumpListUserVisiblePriority + // method. if (!image_result.image.IsEmpty() && !data->icon_urls_.empty() && data->icon_urls_.front().second.get()) { gfx::ImageSkia image_skia = image_result.image.AsImageSkia(); @@ -594,13 +596,15 @@ // Post a task to delete the content in JumpListIcons folder and log the // results to UMA. update_jumplisticons_task_runner_->PostTask( - FROM_HERE, base::Bind(&DeleteDirectoryContentAndLogResults, icon_dir_, - kFileDeleteLimit)); + FROM_HERE, + base::Bind(&DeleteDirectoryContentAndLogResultsUserVisiblePriority, + icon_dir_, kFileDeleteLimit)); // Post a task to update the jumplist used by the shell. update_jumplisticons_task_runner_->PostTask( - FROM_HERE, base::Bind(&RunUpdateJumpList, incognito_availability, app_id_, - icon_dir_, base::RetainedRef(jumplist_data_))); + FROM_HERE, + base::Bind(&RunUpdateJumpListUserVisiblePriority, incognito_availability, + app_id_, icon_dir_, base::RetainedRef(jumplist_data_))); // Post a task to delete JumpListIconsOld folder and log the results to UMA. base::FilePath icon_dir_old = icon_dir_.DirName().Append(
diff --git a/chrome/browser/win/jumplist.h b/chrome/browser/win/jumplist.h index 225b49f..a66dbafd 100644 --- a/chrome/browser/win/jumplist.h +++ b/chrome/browser/win/jumplist.h
@@ -152,8 +152,8 @@ // Helper for RunUpdate() that determines its parameters. void PostRunUpdate(); - // Called on a timer to invoke RunUpdateJumpList() after requests storms - // have subsided. + // Called on a timer to invoke RunUpdateJumpListUserVisiblePriority() after + // requests storms have subsided. void DeferredRunUpdate(); // history::TopSitesObserver implementation.
diff --git a/chrome/browser/win/jumplist_file_util.cc b/chrome/browser/win/jumplist_file_util.cc index 7c98704..720896b 100644 --- a/chrome/browser/win/jumplist_file_util.cc +++ b/chrome/browser/win/jumplist_file_util.cc
@@ -123,8 +123,9 @@ dir_status, DIRECTORY_STATUS_END); } -void DeleteDirectoryContentAndLogResults(const base::FilePath& path, - int max_file_deleted) { +void DeleteDirectoryContentAndLogResultsUserVisiblePriority( + const base::FilePath& path, + int max_file_deleted) { DirectoryStatus dir_status = NON_EXIST; // Delete the content in |path|. If |path| doesn't exist, create one.
diff --git a/chrome/browser/win/jumplist_file_util.h b/chrome/browser/win/jumplist_file_util.h index f9ab7a8..cd51de5 100644 --- a/chrome/browser/win/jumplist_file_util.h +++ b/chrome/browser/win/jumplist_file_util.h
@@ -79,7 +79,8 @@ int max_file_deleted); // Deletes the content in the directory at |path| and records the result to UMA. -void DeleteDirectoryContentAndLogResults(const base::FilePath& path, - int max_file_deleted); +void DeleteDirectoryContentAndLogResultsUserVisiblePriority( + const base::FilePath& path, + int max_file_deleted); #endif // CHROME_BROWSER_WIN_JUMPLIST_FILE_UTIL_H_
diff --git a/chrome/common/BUILD.gn b/chrome/common/BUILD.gn index 79e8128d..bbf02bf2 100644 --- a/chrome/common/BUILD.gn +++ b/chrome/common/BUILD.gn
@@ -115,6 +115,7 @@ "page_load_metrics/page_track_decider.h", "partial_circular_buffer.cc", "partial_circular_buffer.h", + "pause_tabs_field_trial.h", "pref_names_util.cc", "pref_names_util.h", "prerender_types.h",
diff --git a/chrome/common/extensions/api/_api_features.json b/chrome/common/extensions/api/_api_features.json index 858a45d..7df3a10 100644 --- a/chrome/common/extensions/api/_api_features.json +++ b/chrome/common/extensions/api/_api_features.json
@@ -91,7 +91,7 @@ "dependencies": ["permission:autofillPrivate"], "contexts": ["blessed_extension"] }, { - "channel": "trunk", + "channel": "stable", "contexts": ["webui"], "matches": [ "chrome://md-settings/*", @@ -244,7 +244,7 @@ "contexts": ["blessed_extension"] }, { "internal": true, - "channel": "dev", + "channel": "stable", "contexts": ["webui"], "matches": [ "chrome://chrome-signin/*", @@ -439,7 +439,7 @@ "dependencies": ["permission:embeddedExtensionOptions"] }, { "internal": true, - "channel": "trunk", + "channel": "stable", "contexts": ["webui"], "matches": ["chrome://extensions-frame/*", "chrome://extensions/*"] }], @@ -637,7 +637,7 @@ "dependencies": ["permission:passwordsPrivate"], "contexts": ["blessed_extension"] }, { - "channel": "trunk", + "channel": "stable", "contexts": ["webui"], "matches": [ "chrome://md-settings/*", @@ -715,7 +715,7 @@ "dependencies": ["permission:settingsPrivate"], "contexts": ["blessed_extension"] }, { - "channel": "trunk", + "channel": "stable", "contexts": ["webui"], "matches": [ "chrome://md-settings/*", @@ -778,7 +778,7 @@ "dependencies": ["permission:usersPrivate"], "contexts": ["blessed_extension"] }, { - "channel": "trunk", + "channel": "stable", "contexts": ["webui"], "matches": [ "chrome://md-settings/*",
diff --git a/chrome/common/pause_tabs_field_trial.h b/chrome/common/pause_tabs_field_trial.h new file mode 100644 index 0000000..bbc8f69 --- /dev/null +++ b/chrome/common/pause_tabs_field_trial.h
@@ -0,0 +1,26 @@ +// 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_COMMON_PAUSE_TABS_FIELD_TRIAL_H_ +#define CHROME_COMMON_PAUSE_TABS_FIELD_TRIAL_H_ + +#include "base/feature_list.h" + +namespace pausetabs { + +const base::Feature kFeature{"PauseBackgroundTabs", + base::FEATURE_DISABLED_BY_DEFAULT}; + +const char kFeatureName[] = "pause-background-tabs"; + +// Mode values. +const char kModeParamMinimal[] = "minimal"; +const char kModeParamLow[] = "low"; +const char kModeParamMedium[] = "medium"; +const char kModeParamHigh[] = "high"; +const char kModeParamMax[] = "max"; + +} // namespace pausetabs + +#endif // CHROME_COMMON_PAUSE_TABS_FIELD_TRIAL_H_
diff --git a/chrome/common/url_constants.cc b/chrome/common/url_constants.cc index d854657..12829d3 100644 --- a/chrome/common/url_constants.cc +++ b/chrome/common/url_constants.cc
@@ -591,6 +591,11 @@ const char kSyncEverythingLearnMoreURL[] = "https://support.google.com/chrome/?p=settings_sync_all"; +#if defined(OS_CHROMEOS) +const char kCrosPrintingLearnMoreURL[] = + "https://support.google.com/chromebook?p=chromebook_printing"; +#endif + const char kCloudPrintLearnMoreURL[] = #if defined(OS_CHROMEOS) "https://support.google.com/chromebook/?p=settings_cloud_print";
diff --git a/chrome/common/url_constants.h b/chrome/common/url_constants.h index bc4762b..320a624f 100644 --- a/chrome/common/url_constants.h +++ b/chrome/common/url_constants.h
@@ -581,6 +581,11 @@ extern const char kAndroidAppScheme[]; #endif +#if defined(OS_CHROMEOS) +// "Learn more" URL for the Printing section under Options. +extern const char kCrosPrintingLearnMoreURL[]; +#endif + // "Learn more" URL for the Cloud Print section under Options. extern const char kCloudPrintLearnMoreURL[];
diff --git a/chrome/renderer/chrome_content_renderer_client.cc b/chrome/renderer/chrome_content_renderer_client.cc index 0c4f7b2..63230365 100644 --- a/chrome/renderer/chrome_content_renderer_client.cc +++ b/chrome/renderer/chrome_content_renderer_client.cc
@@ -28,6 +28,7 @@ #include "chrome/common/chrome_switches.h" #include "chrome/common/crash_keys.h" #include "chrome/common/features.h" +#include "chrome/common/pause_tabs_field_trial.h" #include "chrome/common/pepper_permission_util.h" #include "chrome/common/prerender_types.h" #include "chrome/common/render_messages.h" @@ -90,9 +91,9 @@ #include "content/public/common/url_constants.h" #include "content/public/renderer/plugin_instance_throttler.h" #include "content/public/renderer/render_frame.h" +#include "content/public/renderer/render_frame_visitor.h" #include "content/public/renderer/render_thread.h" #include "content/public/renderer/render_view.h" -#include "content/public/renderer/render_view_visitor.h" #include "extensions/common/constants.h" #include "extensions/features/features.h" #include "ipc/ipc_sync_channel.h" @@ -253,23 +254,27 @@ #endif // BUILDFLAG(ENABLE_PLUGINS) #if BUILDFLAG(ENABLE_SPELLCHECK) -class SpellCheckReplacer : public content::RenderViewVisitor { +class SpellCheckReplacer : public content::RenderFrameVisitor { public: explicit SpellCheckReplacer(SpellCheck* spellcheck) : spellcheck_(spellcheck) {} - bool Visit(content::RenderView* render_view) override; + ~SpellCheckReplacer() override; + bool Visit(content::RenderFrame* render_frame) override; private: - SpellCheck* spellcheck_; // New shared spellcheck for all views. Weak Ptr. + // New shared spellcheck for all frames. Weak Ptr. + SpellCheck* const spellcheck_; DISALLOW_COPY_AND_ASSIGN(SpellCheckReplacer); }; -bool SpellCheckReplacer::Visit(content::RenderView* render_view) { - SpellCheckProvider* provider = SpellCheckProvider::Get(render_view); +bool SpellCheckReplacer::Visit(content::RenderFrame* render_frame) { + SpellCheckProvider* provider = SpellCheckProvider::Get(render_frame); DCHECK(provider); provider->set_spellcheck(spellcheck_); return true; } + +SpellCheckReplacer::~SpellCheckReplacer() = default; #endif #if BUILDFLAG(ENABLE_EXTENSIONS) @@ -574,11 +579,7 @@ } #if BUILDFLAG(ENABLE_SPELLCHECK) - // TODO(xiaochengh): Use a different SpellCheckProvider for each RenderFrame. - if (SpellCheckProvider* provider = - SpellCheckProvider::Get(render_frame->GetRenderView())) { - render_frame->GetWebFrame()->SetTextCheckClient(provider); - } + new SpellCheckProvider(render_frame, spellcheck_.get()); #endif } @@ -588,16 +589,13 @@ ChromeExtensionsRendererClient::GetInstance()->RenderViewCreated(render_view); #endif #if BUILDFLAG(ENABLE_SPELLCHECK) - SpellCheckProvider* provider = - new SpellCheckProvider(render_view, spellcheck_.get()); - // For a main frame of a view, RenderFrameCreated is called earlier than - // RenderViewCreated. This workaround ensures that WebTextCheckClient is - // still set for any main frame. - // TODO(xiaochengh): Remove this workaround once SpellCheckProvider becomes - // a RenderFrameObserver. - if (content::RenderFrame* main_frame = render_view->GetMainRenderFrame()) - main_frame->GetWebFrame()->SetTextCheckClient(provider); - + // This is a workaround keeping the behavior that, the Blink side spellcheck + // enabled state is initialized on RenderView creation. + // TODO(xiaochengh): Design better way to sync between Chrome-side and + // Blink-side spellcheck enabled states. See crbug.com/710097. + if (SpellCheckProvider* provider = + SpellCheckProvider::Get(render_view->GetMainRenderFrame())) + provider->EnableSpellcheck(spellcheck_->IsSpellcheckEnabled()); new SpellCheckPanel(render_view); #endif new prerender::PrerendererClient(render_view); @@ -1098,7 +1096,8 @@ #if defined(OS_ANDROID) return true; #else - return false; + // TODO(ojan): Plumb the engagement values for this feature to WebViewImpl. + return base::FeatureList::IsEnabled(pausetabs::kFeature); #endif } @@ -1238,7 +1237,7 @@ thread->RemoveObserver(spellcheck_.get()); spellcheck_.reset(spellcheck); SpellCheckReplacer replacer(spellcheck_.get()); - content::RenderView::ForEach(&replacer); + content::RenderFrame::ForEach(&replacer); if (thread) thread->AddObserver(spellcheck_.get()); }
diff --git a/chrome/test/BUILD.gn b/chrome/test/BUILD.gn index b309509a..4b8fc59 100644 --- a/chrome/test/BUILD.gn +++ b/chrome/test/BUILD.gn
@@ -3586,7 +3586,6 @@ sources += [ # Offline pages are currently only on Android. "../browser/android/offline_pages/background_loader_offliner_unittest.cc", - "../browser/android/offline_pages/downloads/resource_throttle_unittest.cc", "../browser/android/offline_pages/offline_page_mhtml_archiver_unittest.cc", "../browser/android/offline_pages/offline_page_request_job_unittest.cc", "../browser/android/offline_pages/offline_page_utils_unittest.cc",
diff --git a/chrome/test/android/javatests/src/org/chromium/chrome/test/util/ChromeTabUtils.java b/chrome/test/android/javatests/src/org/chromium/chrome/test/util/ChromeTabUtils.java index 9b6f2bb..9422cdfc 100644 --- a/chrome/test/android/javatests/src/org/chromium/chrome/test/util/ChromeTabUtils.java +++ b/chrome/test/android/javatests/src/org/chromium/chrome/test/util/ChromeTabUtils.java
@@ -415,7 +415,7 @@ final CallbackHelper closeCallback = new CallbackHelper(); final TabModelObserver observer = new EmptyTabModelObserver() { @Override - public void allTabsPendingClosure(List<Integer> tabIds) { + public void allTabsPendingClosure(List<Tab> tabs) { closeCallback.notifyCalled(); } };
diff --git a/chrome/test/chromedriver/alert_commands.cc b/chrome/test/chromedriver/alert_commands.cc index 682ab962..b4bd3c10 100644 --- a/chrome/test/chromedriver/alert_commands.cc +++ b/chrome/test/chromedriver/alert_commands.cc
@@ -69,10 +69,22 @@ if (!params.GetString("text", &text)) return Status(kUnknownError, "missing or invalid 'text'"); - if (!web_view->GetJavaScriptDialogManager()->IsDialogOpen()) + JavaScriptDialogManager* dialog_manager = + web_view->GetJavaScriptDialogManager(); + + if (!dialog_manager->IsDialogOpen()) return Status(kNoAlertOpen); - session->prompt_text.reset(new std::string(text)); + std::string type; + Status status = dialog_manager->GetTypeOfDialog(&type); + if (status.IsError()) + return status; + + if (type == "prompt") + session->prompt_text.reset(new std::string(text)); + else + return Status(kElementNotVisible, + " User dialog does not have a text box input field."); return Status(kOk); }
diff --git a/chrome/test/chromedriver/chrome/javascript_dialog_manager.cc b/chrome/test/chromedriver/chrome/javascript_dialog_manager.cc index 7eff15d0..f8e72c1f 100644 --- a/chrome/test/chromedriver/chrome/javascript_dialog_manager.cc +++ b/chrome/test/chromedriver/chrome/javascript_dialog_manager.cc
@@ -27,6 +27,14 @@ return Status(kOk); } +Status JavaScriptDialogManager::GetTypeOfDialog(std::string* type) { + if (!IsDialogOpen()) + return Status(kNoAlertOpen); + + *type = dialog_type_queue_.front(); + return Status(kOk); +} + Status JavaScriptDialogManager::HandleDialog(bool accept, const std::string* text) { if (!IsDialogOpen()) @@ -50,11 +58,16 @@ // response. if (unhandled_dialog_queue_.size()) unhandled_dialog_queue_.pop_front(); + + if (dialog_type_queue_.size()) + dialog_type_queue_.pop_front(); + return Status(kOk); } Status JavaScriptDialogManager::OnConnected(DevToolsClient* client) { unhandled_dialog_queue_.clear(); + dialog_type_queue_.clear(); base::DictionaryValue params; return client_->SendCommand("Page.enable", params); } @@ -68,10 +81,17 @@ return Status(kUnknownError, "dialog event missing or invalid 'message'"); unhandled_dialog_queue_.push_back(message); + + std::string type; + if (!params.GetString("type", &type)) + return Status(kUnknownError, "dialog has invalid 'type'"); + + dialog_type_queue_.push_back(type); } else if (method == "Page.javascriptDialogClosed") { // Inspector only sends this event when all dialogs have been closed. // Clear the unhandled queue in case the user closed a dialog manually. unhandled_dialog_queue_.clear(); + dialog_type_queue_.clear(); } return Status(kOk); }
diff --git a/chrome/test/chromedriver/chrome/javascript_dialog_manager.h b/chrome/test/chromedriver/chrome/javascript_dialog_manager.h index 598e1b45..04c25a9 100644 --- a/chrome/test/chromedriver/chrome/javascript_dialog_manager.h +++ b/chrome/test/chromedriver/chrome/javascript_dialog_manager.h
@@ -29,6 +29,8 @@ Status GetDialogMessage(std::string* message); + Status GetTypeOfDialog(std::string* type); + Status HandleDialog(bool accept, const std::string* text); // Overridden from DevToolsEventListener: @@ -45,6 +47,8 @@ // the event, a script was injected via Inspector that triggered an alert. std::list<std::string> unhandled_dialog_queue_; + std::list<std::string> dialog_type_queue_; + DISALLOW_COPY_AND_ASSIGN(JavaScriptDialogManager); };
diff --git a/chrome/test/chromedriver/chrome/javascript_dialog_manager_unittest.cc b/chrome/test/chromedriver/chrome/javascript_dialog_manager_unittest.cc index ca163689..fd81238 100644 --- a/chrome/test/chromedriver/chrome/javascript_dialog_manager_unittest.cc +++ b/chrome/test/chromedriver/chrome/javascript_dialog_manager_unittest.cc
@@ -28,6 +28,7 @@ JavaScriptDialogManager manager(&client); base::DictionaryValue params; params.SetString("message", "hi"); + params.SetString("type", "prompt"); ASSERT_EQ( kOk, manager.OnEvent(&client, "Page.javascriptDialogOpening", params).code()); @@ -44,6 +45,7 @@ JavaScriptDialogManager manager(&client); base::DictionaryValue params; params.SetString("message", "hi"); + params.SetString("type", "prompt"); ASSERT_EQ( kOk, manager.OnEvent(&client, "Page.javascriptDialogOpening", params).code()); @@ -57,6 +59,7 @@ JavaScriptDialogManager manager(&client); base::DictionaryValue params; params.SetString("message", "hi"); + params.SetString("type", "alert"); ASSERT_EQ( kOk, manager.OnEvent(&client, "Page.javascriptDialogOpening", params).code()); @@ -113,6 +116,7 @@ JavaScriptDialogManager manager(&client); base::DictionaryValue params; params.SetString("message", "hi"); + params.SetString("type", "alert"); ASSERT_FALSE(manager.IsDialogOpen()); std::string message; ASSERT_EQ(kNoAlertOpen, manager.GetDialogMessage(&message).code()); @@ -123,6 +127,9 @@ ASSERT_TRUE(manager.IsDialogOpen()); ASSERT_EQ(kOk, manager.GetDialogMessage(&message).code()); ASSERT_EQ("hi", message); + std::string type; + ASSERT_EQ(kOk, manager.GetTypeOfDialog(&type).code()); + ASSERT_EQ("alert", type); client.set_closing_count(1); ASSERT_EQ(kOk, manager.HandleDialog(false, NULL).code()); @@ -136,23 +143,30 @@ JavaScriptDialogManager manager(&client); base::DictionaryValue params; params.SetString("message", "1"); + params.SetString("type", "confirm"); ASSERT_EQ( kOk, manager.OnEvent(&client, "Page.javascriptDialogOpening", params).code()); params.SetString("message", "2"); + params.SetString("type", "alert"); ASSERT_EQ( kOk, manager.OnEvent(&client, "Page.javascriptDialogOpening", params).code()); std::string message; + std::string type; ASSERT_EQ(kOk, manager.GetDialogMessage(&message).code()); + ASSERT_EQ(kOk, manager.GetTypeOfDialog(&type).code()); ASSERT_TRUE(manager.IsDialogOpen()); ASSERT_EQ("1", message); + ASSERT_EQ("confirm", type); ASSERT_EQ(kOk, manager.HandleDialog(false, NULL).code()); ASSERT_TRUE(manager.IsDialogOpen()); ASSERT_EQ(kOk, manager.GetDialogMessage(&message).code()); + ASSERT_EQ(kOk, manager.GetTypeOfDialog(&type).code()); ASSERT_EQ("2", message); + ASSERT_EQ("alert", type); client.set_closing_count(2); ASSERT_EQ(kOk, manager.HandleDialog(false, NULL).code()); @@ -166,6 +180,7 @@ JavaScriptDialogManager manager(&client); base::DictionaryValue params; params.SetString("message", "hi"); + params.SetString("type", "alert"); ASSERT_FALSE(manager.IsDialogOpen()); std::string message; ASSERT_EQ(kNoAlertOpen, manager.GetDialogMessage(&message).code()); @@ -176,6 +191,9 @@ ASSERT_TRUE(manager.IsDialogOpen()); ASSERT_EQ(kOk, manager.GetDialogMessage(&message).code()); ASSERT_EQ("hi", message); + std::string type; + ASSERT_EQ(kOk, manager.GetTypeOfDialog(&type).code()); + ASSERT_EQ("alert", type); ASSERT_EQ( kOk,
diff --git a/chrome/test/chromedriver/test/test_expectations b/chrome/test/chromedriver/test/test_expectations index 3ada83e..2f0a982 100644 --- a/chrome/test/chromedriver/test/test_expectations +++ b/chrome/test/chromedriver/test/test_expectations
@@ -13,7 +13,6 @@ _REVISION_NEGATIVE_FILTER = {} _REVISION_NEGATIVE_FILTER['HEAD'] = [ 'AlertsTest.testIncludesAlertTextInUnhandledAlertException', - 'AlertsTest.testSettingTheValueOfAnAlertThrows', 'AlertsTest.testShouldGetTextOfAlertOpenedInSetTimeout', 'AlertsTest.testShouldHandleAlertOnPageUnload', 'AlertsTest.testShouldHandleAlertOnWindowClose',
diff --git a/chrome/test/data/webui/settings/device_page_tests.js b/chrome/test/data/webui/settings/device_page_tests.js index 9b220e6..08eb210 100644 --- a/chrome/test/data/webui/settings/device_page_tests.js +++ b/chrome/test/data/webui/settings/device_page_tests.js
@@ -488,7 +488,7 @@ displayPage.displays[0].id, displayPage.selectedDisplay.id); expectEquals( displayPage.displays[0].id, displayPage.primaryDisplayId); - expectFalse(displayPage.showMirror_(displayPage.displays)); + expectFalse(displayPage.showMirror_(false, displayPage.displays)); expectFalse(displayPage.isMirrored_(displayPage.displays)); // Add a second display. @@ -507,7 +507,7 @@ expectEquals( displayPage.displays[0].id, displayPage.selectedDisplay.id); expectEquals(displayPage.displays[0].id, displayPage.primaryDisplayId); - expectTrue(displayPage.showMirror_(displayPage.displays)); + expectTrue(displayPage.showMirror_(false, displayPage.displays)); expectFalse(displayPage.isMirrored_(displayPage.displays)); // Select the second display and make it primary. Also change the @@ -554,7 +554,7 @@ expectEquals( displayPage.displays[0].id, displayPage.selectedDisplay.id); expectTrue(displayPage.displays[0].isPrimary); - expectTrue(displayPage.showMirror_(displayPage.displays)); + expectTrue(displayPage.showMirror_(false, displayPage.displays)); expectTrue(displayPage.isMirrored_(displayPage.displays)); }); });
diff --git a/chrome/test/data/webui/settings/fake_system_display.js b/chrome/test/data/webui/settings/fake_system_display.js index aca85cc..b182c2a 100644 --- a/chrome/test/data/webui/settings/fake_system_display.js +++ b/chrome/test/data/webui/settings/fake_system_display.js
@@ -31,7 +31,7 @@ // SystemDisplay overrides. /** @override */ - getInfo: function(callback) { + getInfo: function(flags, callback) { setTimeout(function() { // Create a shallow copy to trigger Polymer data binding updates. var displays;
diff --git a/chrome/tools/build/linux/FILES.cfg b/chrome/tools/build/linux/FILES.cfg index 3eed7b7..aff7afd3 100644 --- a/chrome/tools/build/linux/FILES.cfg +++ b/chrome/tools/build/linux/FILES.cfg
@@ -124,6 +124,15 @@ 'filename': 'libEGL.so', 'buildtype': ['dev'], }, + # SwiftShader files: + { + 'filename': 'swiftshader/libGLESv2.so', + 'buildtype': ['dev, 'official''], + }, + { + 'filename': 'swiftshader/libEGL.so', + 'buildtype': ['dev', 'official'], + }, # Native Client plugin files: { 'filename': 'nacl_irt_x86_32.nexe',
diff --git a/chrome/utility/image_writer/image_writer_unittest.cc b/chrome/utility/image_writer/image_writer_unittest.cc index d935c36..7de30b5 100644 --- a/chrome/utility/image_writer/image_writer_unittest.cc +++ b/chrome/utility/image_writer/image_writer_unittest.cc
@@ -44,7 +44,8 @@ std::unique_ptr<char[]> buffer(new char[kTestFileSize]); memset(buffer.get(), pattern, kTestFileSize); - ASSERT_TRUE(base::WriteFile(path, buffer.get(), kTestFileSize)); + ASSERT_EQ(static_cast<int>(kTestFileSize), + base::WriteFile(path, buffer.get(), kTestFileSize)); } void FillDefault(const base::FilePath& path) { FillFile(path, kTestPattern); }
diff --git a/chromeos/components/tether/BUILD.gn b/chromeos/components/tether/BUILD.gn index 7474fa2..e5bc418 100644 --- a/chromeos/components/tether/BUILD.gn +++ b/chromeos/components/tether/BUILD.gn
@@ -51,6 +51,8 @@ "tether_connector.h", "tether_host_fetcher.cc", "tether_host_fetcher.h", + "tether_network_disconnection_handler.cc", + "tether_network_disconnection_handler.h", "wifi_hotspot_connector.cc", "wifi_hotspot_connector.h", ] @@ -63,6 +65,7 @@ "//components/cryptauth/ble", "//components/prefs", "//components/proximity_auth/logging", + "//components/signin/core/browser", "//device/bluetooth", "//ui/gfx", "//ui/message_center", @@ -122,6 +125,7 @@ "host_scan_scheduler_unittest.cc", "host_scanner_operation_unittest.cc", "host_scanner_unittest.cc", + "initializer_unittest.cc", "keep_alive_operation_unittest.cc", "keep_alive_scheduler_unittest.cc", "local_device_data_provider_unittest.cc", @@ -129,6 +133,7 @@ "message_wrapper_unittest.cc", "tether_connector_unittest.cc", "tether_host_fetcher_unittest.cc", + "tether_network_disconnection_handler_unittest.cc", "wifi_hotspot_connector_unittest.cc", ] @@ -143,6 +148,7 @@ "//components/cryptauth:test_support", "//components/cryptauth/ble", "//components/prefs:test_support", + "//components/signin/core/browser:test_support", "//device/bluetooth", "//device/bluetooth:mocks", "//testing/gmock",
diff --git a/chromeos/components/tether/DEPS b/chromeos/components/tether/DEPS index 9203ca3..b32337e 100644 --- a/chromeos/components/tether/DEPS +++ b/chromeos/components/tether/DEPS
@@ -1,6 +1,7 @@ include_rules = [ "+components/cryptauth", "+components/proximity_auth/logging", + "+components/signin/core/browser", "+device/bluetooth", "+ui/gfx", "+ui/message_center",
diff --git a/chromeos/components/tether/active_host_network_state_updater.cc b/chromeos/components/tether/active_host_network_state_updater.cc index d05c41a..c6cfc1a 100644 --- a/chromeos/components/tether/active_host_network_state_updater.cc +++ b/chromeos/components/tether/active_host_network_state_updater.cc
@@ -15,12 +15,6 @@ namespace tether { ActiveHostNetworkStateUpdater::ActiveHostNetworkStateUpdater( - ActiveHost* active_host) - : ActiveHostNetworkStateUpdater( - active_host, - NetworkHandler::Get()->network_state_handler()) {} - -ActiveHostNetworkStateUpdater::ActiveHostNetworkStateUpdater( ActiveHost* active_host, NetworkStateHandler* network_state_handler) : active_host_(active_host), network_state_handler_(network_state_handler) {
diff --git a/chromeos/components/tether/active_host_network_state_updater.h b/chromeos/components/tether/active_host_network_state_updater.h index 13d4d6d..6f0c8b79 100644 --- a/chromeos/components/tether/active_host_network_state_updater.h +++ b/chromeos/components/tether/active_host_network_state_updater.h
@@ -19,7 +19,8 @@ // to the networking stack. class ActiveHostNetworkStateUpdater : public ActiveHost::Observer { public: - ActiveHostNetworkStateUpdater(ActiveHost* active_host); + ActiveHostNetworkStateUpdater(ActiveHost* active_host, + NetworkStateHandler* network_state_handler); ~ActiveHostNetworkStateUpdater(); // ActiveHost::Observer: @@ -27,11 +28,6 @@ const ActiveHost::ActiveHostChangeInfo& change_info) override; private: - friend class ActiveHostNetworkStateUpdaterTest; - - ActiveHostNetworkStateUpdater(ActiveHost* active_host, - NetworkStateHandler* network_state_handler); - ActiveHost* active_host_; NetworkStateHandler* network_state_handler_;
diff --git a/chromeos/components/tether/ble_scanner_unittest.cc b/chromeos/components/tether/ble_scanner_unittest.cc index e9ef84e4..3ba62019 100644 --- a/chromeos/components/tether/ble_scanner_unittest.cc +++ b/chromeos/components/tether/ble_scanner_unittest.cc
@@ -547,11 +547,9 @@ ble_scanner_->AdapterPoweredChanged(mock_adapter_.get(), true); InvokeDiscoveryStartedCallback(); - // A new session should have started, so the session objects should not be the - // same. + // A new session should have started. device::MockBluetoothDiscoverySession* session2 = mock_discovery_session_; EXPECT_NE(nullptr, session2); - EXPECT_NE(session1, session2); // Unregister device. EXPECT_TRUE(ble_scanner_->IsDeviceRegistered(test_devices_[0].GetDeviceId()));
diff --git a/chromeos/components/tether/fake_tether_host_fetcher.cc b/chromeos/components/tether/fake_tether_host_fetcher.cc index 79de8516..b8ea9f2 100644 --- a/chromeos/components/tether/fake_tether_host_fetcher.cc +++ b/chromeos/components/tether/fake_tether_host_fetcher.cc
@@ -13,7 +13,7 @@ FakeTetherHostFetcher::FakeTetherHostFetcher( std::vector<cryptauth::RemoteDevice> tether_hosts, bool synchronously_reply_with_results) - : TetherHostFetcher("", "", nullptr, nullptr), + : TetherHostFetcher(nullptr), tether_hosts_(tether_hosts), synchronously_reply_with_results_(synchronously_reply_with_results) {}
diff --git a/chromeos/components/tether/host_scanner.h b/chromeos/components/tether/host_scanner.h index e2a3e94b..fab8164 100644 --- a/chromeos/components/tether/host_scanner.h +++ b/chromeos/components/tether/host_scanner.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_COMPONENTS_TETHER_HOST_SCANNER_H -#define CHROMEOS_COMPONENTS_TETHER_HOST_SCANNER_H +#ifndef CHROMEOS_COMPONENTS_TETHER_HOST_SCANNER_H_ +#define CHROMEOS_COMPONENTS_TETHER_HOST_SCANNER_H_ #include <vector> @@ -25,7 +25,6 @@ // TODO(khorimoto): Add some sort of "staleness" timeout which removes scan // results which occurred long enough ago that they are no // longer valid. -// TODO(hansberry): Implement handling for scan results. class HostScanner : public HostScannerOperation::Observer { public: HostScanner(TetherHostFetcher* tether_host_fetcher, @@ -54,6 +53,7 @@ private: friend class HostScannerTest; + friend class HostScanSchedulerTest; void OnTetherHostsFetched(const cryptauth::RemoteDeviceList& tether_hosts); @@ -77,4 +77,4 @@ } // namespace chromeos -#endif // CHROMEOS_COMPONENTS_TETHER_HOST_SCANNER_H +#endif // CHROMEOS_COMPONENTS_TETHER_HOST_SCANNER_H_
diff --git a/chromeos/components/tether/host_scanner_unittest.cc b/chromeos/components/tether/host_scanner_unittest.cc index 0f80266b..6eedaec9 100644 --- a/chromeos/components/tether/host_scanner_unittest.cc +++ b/chromeos/components/tether/host_scanner_unittest.cc
@@ -15,6 +15,7 @@ #include "chromeos/components/tether/fake_notification_presenter.h" #include "chromeos/components/tether/fake_tether_host_fetcher.h" #include "chromeos/components/tether/host_scan_device_prioritizer.h" +#include "chromeos/components/tether/host_scanner.h" #include "chromeos/dbus/dbus_thread_manager.h" #include "chromeos/network/network_state.h" #include "chromeos/network/network_state_handler.h" @@ -153,16 +154,18 @@ fake_notification_presenter_ = base::MakeUnique<FakeNotificationPresenter>(); - host_scanner_ = base::MakeUnique<HostScanner>( + host_scanner_ = base::WrapUnique(new HostScanner( fake_tether_host_fetcher_.get(), fake_ble_connection_manager_.get(), fake_host_scan_device_prioritizer_.get(), network_state_handler(), - fake_notification_presenter_.get()); + fake_notification_presenter_.get())); } void TearDown() override { ShutdownNetworkState(); NetworkStateTest::TearDown(); DBusThreadManager::Shutdown(); + + HostScannerOperation::Factory::SetInstanceForTesting(nullptr); } // Causes |fake_operation| to receive the scan result in @@ -355,4 +358,4 @@ } // namespace tether -} // namespace cryptauth +} // namespace chromeos
diff --git a/chromeos/components/tether/initializer.cc b/chromeos/components/tether/initializer.cc index cc2d49c..4cb3cfa 100644 --- a/chromeos/components/tether/initializer.cc +++ b/chromeos/components/tether/initializer.cc
@@ -4,26 +4,190 @@ #include "chromeos/components/tether/initializer.h" +#include "base/bind.h" +#include "chromeos/components/tether/active_host.h" +#include "chromeos/components/tether/active_host_network_state_updater.h" +#include "chromeos/components/tether/ble_connection_manager.h" +#include "chromeos/components/tether/device_id_tether_network_guid_map.h" +#include "chromeos/components/tether/host_scan_device_prioritizer.h" +#include "chromeos/components/tether/host_scan_scheduler.h" +#include "chromeos/components/tether/host_scanner.h" +#include "chromeos/components/tether/local_device_data_provider.h" +#include "chromeos/components/tether/notification_presenter.h" +#include "chromeos/components/tether/tether_connector.h" +#include "chromeos/components/tether/tether_host_fetcher.h" +#include "chromeos/components/tether/wifi_hotspot_connector.h" +#include "chromeos/network/network_connect.h" +#include "chromeos/network/network_state_handler.h" +#include "components/cryptauth/bluetooth_throttler_impl.h" +#include "components/cryptauth/cryptauth_service.h" +#include "components/cryptauth/remote_beacon_seed_fetcher.h" +#include "components/prefs/pref_service.h" +#include "components/proximity_auth/logging/logging.h" +#include "device/bluetooth/bluetooth_adapter.h" +#include "device/bluetooth/bluetooth_adapter_factory.h" + namespace chromeos { namespace tether { +namespace { + +// TODO (hansberry): Experiment with intervals to determine ideal advertising +// interval parameters. +constexpr int64_t kMinAdvertisingIntervalMilliseconds = 100; +constexpr int64_t kMaxAdvertisingIntervalMilliseconds = 100; + +} // namespace + // static Initializer* Initializer::instance_ = nullptr; -void Initializer::Initialize(cryptauth::CryptAuthService* cryptauth_service) { +// static +void Initializer::Init( + cryptauth::CryptAuthService* cryptauth_service, + std::unique_ptr<NotificationPresenter> notification_presenter, + PrefService* pref_service, + ProfileOAuth2TokenService* token_service, + NetworkStateHandler* network_state_handler, + NetworkConnect* network_connect) { + if (!device::BluetoothAdapterFactory::IsBluetoothAdapterAvailable()) { + PA_LOG(WARNING) << "Bluetooth is unavailable on this device; cannot " + << "initialize tether feature."; + return; + } + if (instance_) { - // TODO(khorimoto): Determine if a new instance should be created. - instance_->cryptauth_service_ = cryptauth_service; - } else { - instance_ = new Initializer(cryptauth_service); + PA_LOG(WARNING) << "Tether initialization was triggered when the feature " + << "had already been initialized; exiting initialization " + << "early."; + return; + } + + instance_ = new Initializer( + cryptauth_service, std::move(notification_presenter), pref_service, + token_service, network_state_handler, network_connect); +} + +// static +void Initializer::Shutdown() { + if (instance_) { + PA_LOG(INFO) << "Shutting down tether feature."; + delete instance_; + instance_ = nullptr; } } -Initializer::Initializer(cryptauth::CryptAuthService* cryptauth_service) - : cryptauth_service_(cryptauth_service) {} +Initializer::Initializer( + cryptauth::CryptAuthService* cryptauth_service, + std::unique_ptr<NotificationPresenter> notification_presenter, + PrefService* pref_service, + ProfileOAuth2TokenService* token_service, + NetworkStateHandler* network_state_handler, + NetworkConnect* network_connect) + : cryptauth_service_(cryptauth_service), + notification_presenter_(std::move(notification_presenter)), + pref_service_(pref_service), + token_service_(token_service), + network_state_handler_(network_state_handler), + network_connect_(network_connect), + weak_ptr_factory_(this) { + if (!token_service_->RefreshTokenIsAvailable( + cryptauth_service_->GetAccountId())) { + PA_LOG(INFO) << "Refresh token not yet available; " + << "waiting for valid token to initializing tether feature."; + token_service_->AddObserver(this); + return; + } -Initializer::~Initializer() {} + PA_LOG(INFO) << "Refresh token is available; initializing tether feature."; + FetchBluetoothAdapter(); +} + +Initializer::~Initializer() { + token_service_->RemoveObserver(this); +} + +void Initializer::FetchBluetoothAdapter() { + device::BluetoothAdapterFactory::GetAdapter(base::Bind( + &Initializer::OnBluetoothAdapterFetched, weak_ptr_factory_.GetWeakPtr())); +} + +void Initializer::OnRefreshTokensLoaded() { + if (!token_service_->RefreshTokenIsAvailable( + cryptauth_service_->GetAccountId())) { + // If a token for the active account is still not available, continue + // waiting for a new token. + return; + } + + PA_LOG(INFO) << "Refresh token has loaded; initializing tether feature."; + + token_service_->RemoveObserver(this); + FetchBluetoothAdapter(); +} + +void Initializer::OnBluetoothAdapterFetched( + scoped_refptr<device::BluetoothAdapter> adapter) { + PA_LOG(INFO) << "Successfully fetched Bluetooth adapter. Setting advertising " + << "interval."; + + adapter->SetAdvertisingInterval( + base::TimeDelta::FromMilliseconds(kMinAdvertisingIntervalMilliseconds), + base::TimeDelta::FromMilliseconds(kMaxAdvertisingIntervalMilliseconds), + base::Bind(&Initializer::OnBluetoothAdapterAdvertisingIntervalSet, + weak_ptr_factory_.GetWeakPtr(), adapter), + base::Bind(&Initializer::OnBluetoothAdapterAdvertisingIntervalError, + weak_ptr_factory_.GetWeakPtr())); +} + +void Initializer::OnBluetoothAdapterAdvertisingIntervalSet( + scoped_refptr<device::BluetoothAdapter> adapter) { + PA_LOG(INFO) << "Successfully set Bluetooth advertisement interval. " + << "Initializing tether feature."; + + tether_host_fetcher_ = + base::MakeUnique<TetherHostFetcher>(cryptauth_service_); + local_device_data_provider_ = + base::MakeUnique<LocalDeviceDataProvider>(cryptauth_service_); + remote_beacon_seed_fetcher_ = + base::MakeUnique<cryptauth::RemoteBeaconSeedFetcher>( + cryptauth_service_->GetCryptAuthDeviceManager()); + ble_connection_manager_ = base::MakeUnique<BleConnectionManager>( + cryptauth_service_, adapter, local_device_data_provider_.get(), + remote_beacon_seed_fetcher_.get(), + cryptauth::BluetoothThrottlerImpl::GetInstance()); + host_scan_device_prioritizer_ = + base::MakeUnique<HostScanDevicePrioritizer>(pref_service_); + wifi_hotspot_connector_ = base::MakeUnique<WifiHotspotConnector>( + network_state_handler_, network_connect_); + active_host_ = + base::MakeUnique<ActiveHost>(tether_host_fetcher_.get(), pref_service_); + active_host_network_state_updater_ = + base::MakeUnique<ActiveHostNetworkStateUpdater>(active_host_.get(), + network_state_handler_); + device_id_tether_network_guid_map_ = + base::MakeUnique<DeviceIdTetherNetworkGuidMap>(); + tether_connector_ = base::MakeUnique<TetherConnector>( + network_connect_, network_state_handler_, wifi_hotspot_connector_.get(), + active_host_.get(), tether_host_fetcher_.get(), + ble_connection_manager_.get(), host_scan_device_prioritizer_.get(), + device_id_tether_network_guid_map_.get()); + host_scanner_ = base::MakeUnique<HostScanner>( + tether_host_fetcher_.get(), ble_connection_manager_.get(), + host_scan_device_prioritizer_.get(), network_state_handler_, + notification_presenter_.get()); + + // TODO(khorimoto): Hook up HostScanScheduler. Currently, we simply start a + // new scan once the user logs in. + host_scanner_->StartScan(); +} + +void Initializer::OnBluetoothAdapterAdvertisingIntervalError( + device::BluetoothAdvertisement::ErrorCode status) { + PA_LOG(ERROR) << "Failed to set Bluetooth advertisement interval; " + << "cannot use tether feature. Error code: " << status; +} } // namespace tether
diff --git a/chromeos/components/tether/initializer.h b/chromeos/components/tether/initializer.h index 76a98a97..01fe741 100644 --- a/chromeos/components/tether/initializer.h +++ b/chromeos/components/tether/initializer.h
@@ -5,29 +5,108 @@ #ifndef CHROMEOS_COMPONENTS_TETHER_INITIALIZER_H_ #define CHROMEOS_COMPONENTS_TETHER_INITIALIZER_H_ +#include <memory> + +#include "base/gtest_prod_util.h" #include "base/macros.h" +#include "base/memory/ref_counted.h" +#include "base/memory/weak_ptr.h" +#include "components/signin/core/browser/profile_oauth2_token_service.h" +#include "device/bluetooth/bluetooth_adapter.h" +#include "device/bluetooth/bluetooth_advertisement.h" + +class PrefService; namespace cryptauth { class CryptAuthService; +class RemoteBeaconSeedFetcher; } namespace chromeos { +class NetworkConnect; +class NetworkStateHandler; + namespace tether { +class ActiveHost; +class ActiveHostNetworkStateUpdater; +class BleConnectionManager; +class DeviceIdTetherNetworkGuidMap; +class HostScanner; +class HostScanDevicePrioritizer; +class LocalDeviceDataProvider; +class NotificationPresenter; +class TetherConnector; +class TetherHostFetcher; +class WifiHotspotConnector; + // Initializes the Tether Chrome OS component. -// TODO(khorimoto): Implement. -class Initializer { +class Initializer : public OAuth2TokenService::Observer { public: - static void Initialize(cryptauth::CryptAuthService* cryptauth_service); + // Initializes the tether feature. + static void Init( + cryptauth::CryptAuthService* cryptauth_service, + std::unique_ptr<NotificationPresenter> notification_presenter, + PrefService* pref_service, + ProfileOAuth2TokenService* token_service, + NetworkStateHandler* network_state_handler, + NetworkConnect* network_connect); + + // Shuts down the tether feature, destroying all internal classes. This should + // be called before the dependencies passed to Init() are destroyed. + static void Shutdown(); private: + friend class InitializerTest; + static Initializer* instance_; - explicit Initializer(cryptauth::CryptAuthService* cryptauth_service); - ~Initializer(); + Initializer(cryptauth::CryptAuthService* cryptauth_service, + std::unique_ptr<NotificationPresenter> notification_presenter, + PrefService* pref_service, + ProfileOAuth2TokenService* token_service, + NetworkStateHandler* network_state_handler, + NetworkConnect* network_connect); + ~Initializer() override; + + // OAuth2TokenService::Observer: + void OnRefreshTokensLoaded() override; + + void FetchBluetoothAdapter(); + void OnBluetoothAdapterFetched( + scoped_refptr<device::BluetoothAdapter> adapter); + void OnBluetoothAdapterAdvertisingIntervalSet( + scoped_refptr<device::BluetoothAdapter> adapter); + void OnBluetoothAdapterAdvertisingIntervalError( + device::BluetoothAdvertisement::ErrorCode status); cryptauth::CryptAuthService* cryptauth_service_; + std::unique_ptr<NotificationPresenter> notification_presenter_; + PrefService* pref_service_; + ProfileOAuth2TokenService* token_service_; + NetworkStateHandler* network_state_handler_; + NetworkConnect* network_connect_; + + // Declare new objects in the order that they will be created during + // initialization to ensure that they are destroyed in the correct order. This + // order will be enforced by InitializerTest.TestCreateAndDestroy. + std::unique_ptr<TetherHostFetcher> tether_host_fetcher_; + std::unique_ptr<LocalDeviceDataProvider> local_device_data_provider_; + std::unique_ptr<cryptauth::RemoteBeaconSeedFetcher> + remote_beacon_seed_fetcher_; + std::unique_ptr<BleConnectionManager> ble_connection_manager_; + std::unique_ptr<HostScanDevicePrioritizer> host_scan_device_prioritizer_; + std::unique_ptr<WifiHotspotConnector> wifi_hotspot_connector_; + std::unique_ptr<ActiveHost> active_host_; + std::unique_ptr<ActiveHostNetworkStateUpdater> + active_host_network_state_updater_; + std::unique_ptr<DeviceIdTetherNetworkGuidMap> + device_id_tether_network_guid_map_; + std::unique_ptr<TetherConnector> tether_connector_; + std::unique_ptr<HostScanner> host_scanner_; + + base::WeakPtrFactory<Initializer> weak_ptr_factory_; DISALLOW_COPY_AND_ASSIGN(Initializer); };
diff --git a/chromeos/components/tether/initializer_unittest.cc b/chromeos/components/tether/initializer_unittest.cc new file mode 100644 index 0000000..aae57a8 --- /dev/null +++ b/chromeos/components/tether/initializer_unittest.cc
@@ -0,0 +1,180 @@ +// 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 "chromeos/components/tether/initializer.h" + +#include <memory> + +#include "base/memory/ptr_util.h" +#include "base/message_loop/message_loop.h" +#include "base/test/scoped_task_environment.h" +#include "chromeos/components/tether/active_host.h" +#include "chromeos/components/tether/fake_notification_presenter.h" +#include "chromeos/components/tether/host_scan_device_prioritizer.h" +#include "chromeos/dbus/dbus_thread_manager.h" +#include "chromeos/network/network_connect.h" +#include "chromeos/network/network_handler.h" +#include "chromeos/network/network_state_test.h" +#include "components/cryptauth/cryptauth_device_manager.h" +#include "components/cryptauth/cryptauth_enroller.h" +#include "components/cryptauth/cryptauth_enrollment_manager.h" +#include "components/cryptauth/fake_cryptauth_gcm_manager.h" +#include "components/cryptauth/fake_cryptauth_service.h" +#include "components/cryptauth/proto/cryptauth_api.pb.h" +#include "components/cryptauth/secure_message_delegate.h" +#include "components/prefs/testing_pref_service.h" +#include "components/signin/core/browser/fake_profile_oauth2_token_service.h" +#include "device/bluetooth/test/mock_bluetooth_adapter.h" +#include "testing/gmock/include/gmock/gmock.h" +#include "testing/gtest/include/gtest/gtest.h" +#include "third_party/cros_system_api/dbus/shill/dbus-constants.h" + +using testing::NiceMock; + +namespace chromeos { + +namespace tether { + +namespace { + +class MockCryptAuthDeviceManager : public cryptauth::CryptAuthDeviceManager { + public: + ~MockCryptAuthDeviceManager() override {} + + MOCK_CONST_METHOD0(GetTetherHosts, + std::vector<cryptauth::ExternalDeviceInfo>()); +}; + +class MockCryptAuthEnrollmentManager + : public cryptauth::CryptAuthEnrollmentManager { + public: + explicit MockCryptAuthEnrollmentManager( + cryptauth::FakeCryptAuthGCMManager* fake_cryptauth_gcm_manager) + : cryptauth::CryptAuthEnrollmentManager( + nullptr /* clock */, + nullptr /* enroller_factory */, + nullptr /* secure_message_delegate */, + cryptauth::GcmDeviceInfo(), + fake_cryptauth_gcm_manager, + nullptr /* pref_service */) {} + ~MockCryptAuthEnrollmentManager() override {} + + MOCK_CONST_METHOD0(GetUserPrivateKey, std::string()); +}; + +class MockNetworkConnect : public NetworkConnect { + public: + MockNetworkConnect() : NetworkConnect() {} + ~MockNetworkConnect() override {} + + MOCK_METHOD1(ConnectToNetworkId, void(const std::string&)); + MOCK_METHOD1(DisconnectFromNetworkId, void(const std::string&)); + MOCK_METHOD2(MaybeShowConfigureUI, + bool(const std::string&, const std::string&)); + MOCK_METHOD2(SetTechnologyEnabled, + void(const chromeos::NetworkTypePattern&, bool)); + MOCK_METHOD1(ShowMobileSetup, void(const std::string&)); + MOCK_METHOD3(ConfigureNetworkIdAndConnect, + void(const std::string&, const base::DictionaryValue&, bool)); + MOCK_METHOD2(CreateConfigurationAndConnect, + void(base::DictionaryValue*, bool)); + MOCK_METHOD2(CreateConfiguration, void(base::DictionaryValue*, bool)); + MOCK_METHOD1(SetTetherDelegate, void(NetworkConnect::TetherDelegate*)); +}; + +} // namespace + +class InitializerTest : public NetworkStateTest { + protected: + InitializerTest() : NetworkStateTest() {} + ~InitializerTest() override {} + + void SetUp() override { + DBusThreadManager::Initialize(); + NetworkHandler::Initialize(); + NetworkStateTest::SetUp(); + + test_pref_service_ = base::MakeUnique<TestingPrefServiceSimple>(); + HostScanDevicePrioritizer::RegisterPrefs(test_pref_service_->registry()); + ActiveHost::RegisterPrefs(test_pref_service_->registry()); + } + + void TearDown() override { + ShutdownNetworkState(); + NetworkStateTest::TearDown(); + DBusThreadManager::Shutdown(); + } + + void InitializeAndDestroy( + cryptauth::CryptAuthService* cryptauth_service, + std::unique_ptr<NotificationPresenter> notification_presenter, + PrefService* pref_service, + ProfileOAuth2TokenService* token_service, + NetworkStateHandler* network_state_handler, + NetworkConnect* network_connect, + scoped_refptr<device::BluetoothAdapter> adapter) { + Initializer* initializer = new Initializer( + cryptauth_service, std::move(notification_presenter), pref_service, + token_service, network_state_handler, network_connect); + initializer->OnBluetoothAdapterAdvertisingIntervalSet(adapter); + delete initializer; + } + + base::test::ScopedTaskEnvironment scoped_task_environment_; + + std::unique_ptr<TestingPrefServiceSimple> test_pref_service_; + + private: + DISALLOW_COPY_AND_ASSIGN(InitializerTest); +}; + +// This test ensures that Initializer's destructor runs in the correct order and +// results in a correct clean-up of all created components. If the destructor +// were to result in an error being thrown, this test would fail. +TEST_F(InitializerTest, TestCreateAndDestroy) { + std::unique_ptr<NiceMock<MockCryptAuthDeviceManager>> mock_device_manager = + base::WrapUnique(new NiceMock<MockCryptAuthDeviceManager>()); + + std::unique_ptr<cryptauth::FakeCryptAuthGCMManager> + fake_cryptauth_gcm_manager = + base::MakeUnique<cryptauth::FakeCryptAuthGCMManager>( + "registrationId"); + + std::unique_ptr<NiceMock<MockCryptAuthEnrollmentManager>> + mock_enrollment_manager = + base::WrapUnique(new NiceMock<MockCryptAuthEnrollmentManager>( + fake_cryptauth_gcm_manager.get())); + + std::unique_ptr<cryptauth::FakeCryptAuthService> fake_cryptauth_service = + base::MakeUnique<cryptauth::FakeCryptAuthService>(); + fake_cryptauth_service->set_cryptauth_device_manager( + mock_device_manager.get()); + fake_cryptauth_service->set_cryptauth_enrollment_manager( + mock_enrollment_manager.get()); + + std::unique_ptr<TestingPrefServiceSimple> test_pref_service = + base::MakeUnique<TestingPrefServiceSimple>(); + + std::unique_ptr<FakeProfileOAuth2TokenService> fake_token_service = + base::MakeUnique<FakeProfileOAuth2TokenService>(); + + std::unique_ptr<MockNetworkConnect> mock_network_connect = + base::WrapUnique(new NiceMock<MockNetworkConnect>); + + scoped_refptr<NiceMock<device::MockBluetoothAdapter>> mock_adapter = + make_scoped_refptr(new NiceMock<device::MockBluetoothAdapter>()); + + // Call an instance method of the test instead of initializing and destroying + // here because the friend relationship between Initializer and + // InitializerTest only applies to the class itself, not these test functions. + InitializeAndDestroy(fake_cryptauth_service.get(), + base::MakeUnique<FakeNotificationPresenter>(), + test_pref_service_.get(), fake_token_service.get(), + network_state_handler(), mock_network_connect.get(), + mock_adapter); +} + +} // namespace tether + +} // namespace chromeos
diff --git a/chromeos/components/tether/local_device_data_provider.cc b/chromeos/components/tether/local_device_data_provider.cc index 12f0423..38fbcc10 100644 --- a/chromeos/components/tether/local_device_data_provider.cc +++ b/chromeos/components/tether/local_device_data_provider.cc
@@ -6,6 +6,7 @@ #include "components/cryptauth/cryptauth_device_manager.h" #include "components/cryptauth/cryptauth_enrollment_manager.h" +#include "components/cryptauth/cryptauth_service.h" #include "components/cryptauth/proto/cryptauth_api.pb.h" namespace chromeos { @@ -13,54 +14,24 @@ namespace tether { LocalDeviceDataProvider::LocalDeviceDataProvider( - const cryptauth::CryptAuthDeviceManager* cryptauth_device_manager, - const cryptauth::CryptAuthEnrollmentManager* cryptauth_enrollment_manager) - : LocalDeviceDataProvider( - base::MakeUnique<LocalDeviceDataProviderDelegateImpl>( - cryptauth_device_manager, - cryptauth_enrollment_manager)) {} - -LocalDeviceDataProvider::LocalDeviceDataProvider( - std::unique_ptr<LocalDeviceDataProviderDelegate> delegate) - : delegate_(std::move(delegate)) {} + cryptauth::CryptAuthService* cryptauth_service) + : cryptauth_service_(cryptauth_service) {} LocalDeviceDataProvider::~LocalDeviceDataProvider() {} -LocalDeviceDataProvider::LocalDeviceDataProviderDelegateImpl:: - LocalDeviceDataProviderDelegateImpl( - const cryptauth::CryptAuthDeviceManager* cryptauth_device_manager, - const cryptauth::CryptAuthEnrollmentManager* - cryptauth_enrollment_manager) - : cryptauth_device_manager_(cryptauth_device_manager), - cryptauth_enrollment_manager_(cryptauth_enrollment_manager) {} - -LocalDeviceDataProvider::LocalDeviceDataProviderDelegateImpl:: - ~LocalDeviceDataProviderDelegateImpl() {} - -std::string -LocalDeviceDataProvider::LocalDeviceDataProviderDelegateImpl::GetUserPublicKey() - const { - return cryptauth_enrollment_manager_->GetUserPublicKey(); -} - -std::vector<cryptauth::ExternalDeviceInfo> -LocalDeviceDataProvider::LocalDeviceDataProviderDelegateImpl::GetSyncedDevices() - const { - return cryptauth_device_manager_->GetSyncedDevices(); -} - bool LocalDeviceDataProvider::GetLocalDeviceData( std::string* public_key_out, std::vector<cryptauth::BeaconSeed>* beacon_seeds_out) const { DCHECK(public_key_out || beacon_seeds_out); - std::string public_key = delegate_->GetUserPublicKey(); + std::string public_key = + cryptauth_service_->GetCryptAuthEnrollmentManager()->GetUserPublicKey(); if (public_key.empty()) { return false; } std::vector<cryptauth::ExternalDeviceInfo> synced_devices = - delegate_->GetSyncedDevices(); + cryptauth_service_->GetCryptAuthDeviceManager()->GetSyncedDevices(); for (const auto& device : synced_devices) { if (device.has_public_key() && device.public_key() == public_key && device.beacon_seeds_size() > 0) { @@ -84,4 +55,4 @@ } // namespace tether -} // namespace cryptauth +} // namespace chromeos
diff --git a/chromeos/components/tether/local_device_data_provider.h b/chromeos/components/tether/local_device_data_provider.h index 4125049..a4e713dd 100644 --- a/chromeos/components/tether/local_device_data_provider.h +++ b/chromeos/components/tether/local_device_data_provider.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_COMPONENTS_TETHER_LOCAL_DEVICE_DATA_PROVIDER_H -#define CHROMEOS_COMPONENTS_TETHER_LOCAL_DEVICE_DATA_PROVIDER_H +#ifndef CHROMEOS_COMPONENTS_TETHER_LOCAL_DEVICE_DATA_PROVIDER_H_ +#define CHROMEOS_COMPONENTS_TETHER_LOCAL_DEVICE_DATA_PROVIDER_H_ #include <memory> #include <string> @@ -14,9 +14,7 @@ namespace cryptauth { class BeaconSeed; -class ExternalDeviceInfo; -class CryptAuthDeviceManager; -class CryptAuthEnrollmentManager; +class CryptAuthService; } namespace chromeos { @@ -27,10 +25,8 @@ // code is running) for the current user (i.e., the one which is logged-in). class LocalDeviceDataProvider { public: - LocalDeviceDataProvider( - const cryptauth::CryptAuthDeviceManager* cryptauth_device_manager, - const cryptauth::CryptAuthEnrollmentManager* - cryptauth_enrollment_manager); + explicit LocalDeviceDataProvider( + cryptauth::CryptAuthService* cryptauth_service); virtual ~LocalDeviceDataProvider(); // Fetches the public key and/or the beacon seeds for the local device. @@ -43,40 +39,7 @@ private: friend class LocalDeviceDataProviderTest; - class LocalDeviceDataProviderDelegate { - public: - virtual ~LocalDeviceDataProviderDelegate() {} - virtual std::string GetUserPublicKey() const = 0; - virtual std::vector<cryptauth::ExternalDeviceInfo> GetSyncedDevices() - const = 0; - }; - - class LocalDeviceDataProviderDelegateImpl - : public LocalDeviceDataProviderDelegate { - public: - LocalDeviceDataProviderDelegateImpl( - const cryptauth::CryptAuthDeviceManager* cryptauth_device_manager, - const cryptauth::CryptAuthEnrollmentManager* - cryptauth_enrollment_manager); - ~LocalDeviceDataProviderDelegateImpl() override; - - std::string GetUserPublicKey() const override; - std::vector<cryptauth::ExternalDeviceInfo> GetSyncedDevices() - const override; - - private: - // Not owned and must outlive this instance. - const cryptauth::CryptAuthDeviceManager* const cryptauth_device_manager_; - - // Not owned and must outlive this instance. - const cryptauth::CryptAuthEnrollmentManager* const - cryptauth_enrollment_manager_; - }; - - LocalDeviceDataProvider( - std::unique_ptr<LocalDeviceDataProviderDelegate> delegate); - - std::unique_ptr<LocalDeviceDataProviderDelegate> delegate_; + cryptauth::CryptAuthService* cryptauth_service_; DISALLOW_COPY_AND_ASSIGN(LocalDeviceDataProvider); }; @@ -85,4 +48,4 @@ } // namespace chromeos -#endif // CHROMEOS_COMPONENTS_TETHER_LOCAL_DEVICE_DATA_PROVIDER_H +#endif // CHROMEOS_COMPONENTS_TETHER_LOCAL_DEVICE_DATA_PROVIDER_H_
diff --git a/chromeos/components/tether/local_device_data_provider_unittest.cc b/chromeos/components/tether/local_device_data_provider_unittest.cc index eb8f4f9..8d4d5b8 100644 --- a/chromeos/components/tether/local_device_data_provider_unittest.cc +++ b/chromeos/components/tether/local_device_data_provider_unittest.cc
@@ -10,8 +10,12 @@ #include "base/logging.h" #include "base/memory/ptr_util.h" #include "components/cryptauth/cryptauth_device_manager.h" +#include "components/cryptauth/cryptauth_enroller.h" #include "components/cryptauth/cryptauth_enrollment_manager.h" +#include "components/cryptauth/fake_cryptauth_gcm_manager.h" +#include "components/cryptauth/fake_cryptauth_service.h" #include "components/cryptauth/proto/cryptauth_api.pb.h" +#include "components/cryptauth/secure_message_delegate.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" @@ -23,16 +27,43 @@ namespace tether { namespace { -const std::string kDefaultPublicKey = "publicKey"; -const std::string kBeaconSeed1Data = "beaconSeed1Data"; +const char kDefaultPublicKey[] = "publicKey"; + +const char kBeaconSeed1Data[] = "beaconSeed1Data"; const int64_t kBeaconSeed1StartMs = 1000L; const int64_t kBeaconSeed1EndMs = 2000L; -const std::string kBeaconSeed2Data = "beaconSeed2Data"; +const char kBeaconSeed2Data[] = "beaconSeed2Data"; const int64_t kBeaconSeed2StartMs = 2000L; const int64_t kBeaconSeed2EndMs = 3000L; +class MockCryptAuthDeviceManager : public cryptauth::CryptAuthDeviceManager { + public: + MockCryptAuthDeviceManager() {} + ~MockCryptAuthDeviceManager() override {} + + MOCK_CONST_METHOD0(GetSyncedDevices, + std::vector<cryptauth::ExternalDeviceInfo>()); +}; + +class MockCryptAuthEnrollmentManager + : public cryptauth::CryptAuthEnrollmentManager { + public: + explicit MockCryptAuthEnrollmentManager( + cryptauth::FakeCryptAuthGCMManager* fake_cryptauth_gcm_manager) + : cryptauth::CryptAuthEnrollmentManager( + nullptr /* clock */, + nullptr /* enroller_factory */, + nullptr /* secure_message_delegate */, + cryptauth::GcmDeviceInfo(), + fake_cryptauth_gcm_manager, + nullptr /* pref_service */) {} + ~MockCryptAuthEnrollmentManager() override {} + + MOCK_CONST_METHOD0(GetUserPublicKey, std::string()); +}; + cryptauth::BeaconSeed CreateBeaconSeed(const std::string& data, int64_t start_ms, int64_t end_ms) { @@ -42,21 +73,11 @@ seed.set_end_time_millis(end_ms); return seed; } + } // namespace class LocalDeviceDataProviderTest : public testing::Test { protected: - class MockProviderDelegate - : public LocalDeviceDataProvider::LocalDeviceDataProviderDelegate { - public: - MockProviderDelegate() {} - ~MockProviderDelegate() override {} - - MOCK_CONST_METHOD0(GetUserPublicKey, std::string()); - MOCK_CONST_METHOD0(GetSyncedDevices, - std::vector<cryptauth::ExternalDeviceInfo>()); - }; - LocalDeviceDataProviderTest() { fake_beacon_seeds_.push_back(CreateBeaconSeed( kBeaconSeed1Data, kBeaconSeed1StartMs, kBeaconSeed1EndMs)); @@ -105,26 +126,45 @@ } void SetUp() override { - mock_delegate_ = new NiceMock<MockProviderDelegate>(); + mock_device_manager_ = + base::WrapUnique(new NiceMock<MockCryptAuthDeviceManager>()); + fake_cryptauth_gcm_manager_ = + base::MakeUnique<cryptauth::FakeCryptAuthGCMManager>("registrationId"); + mock_enrollment_manager_ = + base::WrapUnique(new NiceMock<MockCryptAuthEnrollmentManager>( + fake_cryptauth_gcm_manager_.get())); + + fake_cryptauth_service_ = + base::MakeUnique<cryptauth::FakeCryptAuthService>(); + fake_cryptauth_service_->set_cryptauth_device_manager( + mock_device_manager_.get()); + fake_cryptauth_service_->set_cryptauth_enrollment_manager( + mock_enrollment_manager_.get()); provider_ = base::WrapUnique( - new LocalDeviceDataProvider(base::WrapUnique(mock_delegate_))); + new LocalDeviceDataProvider(fake_cryptauth_service_.get())); } - std::unique_ptr<LocalDeviceDataProvider> provider_; - NiceMock<MockProviderDelegate>* mock_delegate_; - std::vector<cryptauth::BeaconSeed> fake_beacon_seeds_; std::vector<cryptauth::ExternalDeviceInfo> fake_synced_devices_; + std::unique_ptr<cryptauth::FakeCryptAuthGCMManager> + fake_cryptauth_gcm_manager_; + std::unique_ptr<NiceMock<MockCryptAuthDeviceManager>> mock_device_manager_; + std::unique_ptr<NiceMock<MockCryptAuthEnrollmentManager>> + mock_enrollment_manager_; + std::unique_ptr<cryptauth::FakeCryptAuthService> fake_cryptauth_service_; + + std::unique_ptr<LocalDeviceDataProvider> provider_; + private: DISALLOW_COPY_AND_ASSIGN(LocalDeviceDataProviderTest); }; TEST_F(LocalDeviceDataProviderTest, TestGetLocalDeviceData_NoPublicKey) { - ON_CALL(*mock_delegate_, GetUserPublicKey()) + ON_CALL(*mock_enrollment_manager_, GetUserPublicKey()) .WillByDefault(Return(std::string())); - ON_CALL(*mock_delegate_, GetSyncedDevices()) + ON_CALL(*mock_device_manager_, GetSyncedDevices()) .WillByDefault(Return(fake_synced_devices_)); std::string public_key; @@ -134,9 +174,9 @@ } TEST_F(LocalDeviceDataProviderTest, TestGetLocalDeviceData_NoSyncedDevices) { - ON_CALL(*mock_delegate_, GetUserPublicKey()) + ON_CALL(*mock_enrollment_manager_, GetUserPublicKey()) .WillByDefault(Return(kDefaultPublicKey)); - ON_CALL(*mock_delegate_, GetSyncedDevices()) + ON_CALL(*mock_device_manager_, GetSyncedDevices()) .WillByDefault(Return(std::vector<cryptauth::ExternalDeviceInfo>())); std::string public_key; @@ -147,9 +187,9 @@ TEST_F(LocalDeviceDataProviderTest, TestGetLocalDeviceData_NoSyncedDeviceMatchingPublicKey) { - ON_CALL(*mock_delegate_, GetUserPublicKey()) + ON_CALL(*mock_enrollment_manager_, GetUserPublicKey()) .WillByDefault(Return(kDefaultPublicKey)); - ON_CALL(*mock_delegate_, GetSyncedDevices()) + ON_CALL(*mock_device_manager_, GetSyncedDevices()) .WillByDefault(Return(std::vector<cryptauth::ExternalDeviceInfo>{ fake_synced_devices_[0], fake_synced_devices_[1], fake_synced_devices_[2], fake_synced_devices_[3]})); @@ -162,9 +202,9 @@ TEST_F(LocalDeviceDataProviderTest, TestGetLocalDeviceData_SyncedDeviceIncludesPublicKeyButNoBeaconSeeds) { - ON_CALL(*mock_delegate_, GetUserPublicKey()) + ON_CALL(*mock_enrollment_manager_, GetUserPublicKey()) .WillByDefault(Return(kDefaultPublicKey)); - ON_CALL(*mock_delegate_, GetSyncedDevices()) + ON_CALL(*mock_device_manager_, GetSyncedDevices()) .WillByDefault(Return(std::vector<cryptauth::ExternalDeviceInfo>{ fake_synced_devices_[4], })); @@ -176,9 +216,9 @@ } TEST_F(LocalDeviceDataProviderTest, TestGetLocalDeviceData_Success) { - ON_CALL(*mock_delegate_, GetUserPublicKey()) + ON_CALL(*mock_enrollment_manager_, GetUserPublicKey()) .WillByDefault(Return(kDefaultPublicKey)); - ON_CALL(*mock_delegate_, GetSyncedDevices()) + ON_CALL(*mock_device_manager_, GetSyncedDevices()) .WillByDefault(Return(fake_synced_devices_)); std::string public_key;
diff --git a/chromeos/components/tether/mock_local_device_data_provider.cc b/chromeos/components/tether/mock_local_device_data_provider.cc index 9fe0a4b..736e620 100644 --- a/chromeos/components/tether/mock_local_device_data_provider.cc +++ b/chromeos/components/tether/mock_local_device_data_provider.cc
@@ -13,7 +13,7 @@ namespace tether { MockLocalDeviceDataProvider::MockLocalDeviceDataProvider() - : LocalDeviceDataProvider(nullptr, nullptr) {} + : LocalDeviceDataProvider(nullptr /* cryptauth_service */) {} MockLocalDeviceDataProvider::~MockLocalDeviceDataProvider() {} @@ -55,4 +55,4 @@ } // namespace tether -} // namespace cryptauth +} // namespace chromeos
diff --git a/chromeos/components/tether/mock_local_device_data_provider.h b/chromeos/components/tether/mock_local_device_data_provider.h index 40fa924..fa1a6c5 100644 --- a/chromeos/components/tether/mock_local_device_data_provider.h +++ b/chromeos/components/tether/mock_local_device_data_provider.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_COMPONENTS_TETHER_MOCK_LOCAL_DEVICE_DATA_PROVIDER_H -#define CHROMEOS_COMPONENTS_TETHER_MOCK_LOCAL_DEVICE_DATA_PROVIDER_H +#ifndef CHROMEOS_COMPONENTS_TETHER_MOCK_LOCAL_DEVICE_DATA_PROVIDER_H_ +#define CHROMEOS_COMPONENTS_TETHER_MOCK_LOCAL_DEVICE_DATA_PROVIDER_H_ #include <memory> #include <string> @@ -47,4 +47,4 @@ } // namespace chromeos -#endif // CHROMEOS_COMPONENTS_TETHER_MOCK_LOCAL_DEVICE_DATA_PROVIDER_H +#endif // CHROMEOS_COMPONENTS_TETHER_MOCK_LOCAL_DEVICE_DATA_PROVIDER_H_
diff --git a/chromeos/components/tether/tether_connector.cc b/chromeos/components/tether/tether_connector.cc index d7429a1..21da910f 100644 --- a/chromeos/components/tether/tether_connector.cc +++ b/chromeos/components/tether/tether_connector.cc
@@ -18,22 +18,6 @@ namespace tether { TetherConnector::TetherConnector( - WifiHotspotConnector* wifi_hotspot_connector, - ActiveHost* active_host, - TetherHostFetcher* tether_host_fetcher, - BleConnectionManager* connection_manager, - HostScanDevicePrioritizer* host_scan_device_prioritizer, - DeviceIdTetherNetworkGuidMap* device_id_tether_network_guid_map) - : TetherConnector(NetworkConnect::Get(), - NetworkHandler::Get()->network_state_handler(), - wifi_hotspot_connector, - active_host, - tether_host_fetcher, - connection_manager, - host_scan_device_prioritizer, - device_id_tether_network_guid_map) {} - -TetherConnector::TetherConnector( NetworkConnect* network_connect, NetworkStateHandler* network_state_handler, WifiHotspotConnector* wifi_hotspot_connector,
diff --git a/chromeos/components/tether/tether_connector.h b/chromeos/components/tether/tether_connector.h index 1282f16b..d896c45 100644 --- a/chromeos/components/tether/tether_connector.h +++ b/chromeos/components/tether/tether_connector.h
@@ -32,6 +32,8 @@ public ConnectTetheringOperation::Observer { public: TetherConnector( + NetworkConnect* network_connect, + NetworkStateHandler* network_state_handler, WifiHotspotConnector* wifi_hotspot_connector, ActiveHost* active_host, TetherHostFetcher* tether_host_fetcher, @@ -55,16 +57,6 @@ private: friend class TetherConnectorTest; - TetherConnector( - NetworkConnect* network_connect, - NetworkStateHandler* network_state_handler, - WifiHotspotConnector* wifi_hotspot_connector, - ActiveHost* active_host, - TetherHostFetcher* tether_host_fetcher, - BleConnectionManager* connection_manager, - HostScanDevicePrioritizer* host_scan_device_prioritizer, - DeviceIdTetherNetworkGuidMap* device_id_tether_network_guid_map); - void SetDisconnected(); void SetConnected(const std::string& device_id, const std::string& wifi_network_guid);
diff --git a/chromeos/components/tether/tether_connector_unittest.cc b/chromeos/components/tether/tether_connector_unittest.cc index bace055..7788183 100644 --- a/chromeos/components/tether/tether_connector_unittest.cc +++ b/chromeos/components/tether/tether_connector_unittest.cc
@@ -426,13 +426,6 @@ // A second operation should have been created. EXPECT_EQ(2u, fake_operation_factory_->created_operations().size()); - // The first operation replies successfully, but this response should be - // ignored since the active host has changed. - fake_operation_factory_->created_operations()[0]->SendSuccessfulResponse( - kSsid, kPassword); - EXPECT_EQ(test_devices_[1].GetDeviceId(), - fake_active_host_->GetActiveHostDeviceId()); - // No connection should have been started. EXPECT_TRUE(fake_wifi_hotspot_connector_->most_recent_ssid().empty()); EXPECT_TRUE(fake_wifi_hotspot_connector_->most_recent_password().empty());
diff --git a/chromeos/components/tether/tether_host_fetcher.cc b/chromeos/components/tether/tether_host_fetcher.cc index 4f13a3c8..2c98fccd 100644 --- a/chromeos/components/tether/tether_host_fetcher.cc +++ b/chromeos/components/tether/tether_host_fetcher.cc
@@ -7,6 +7,7 @@ #include "base/bind.h" #include "base/memory/ptr_util.h" #include "components/cryptauth/cryptauth_device_manager.h" +#include "components/cryptauth/cryptauth_enrollment_manager.h" #include "components/cryptauth/cryptauth_service.h" #include "components/cryptauth/remote_device_loader.h" #include "components/cryptauth/secure_message_delegate.h" @@ -33,15 +34,8 @@ TetherHostFetcher::TetherHostFetchRequest::~TetherHostFetchRequest() {} TetherHostFetcher::TetherHostFetcher( - const std::string& user_id, - const std::string& user_private_key, - cryptauth::CryptAuthService* cryptauth_service, - cryptauth::CryptAuthDeviceManager* device_manager) - : user_id_(user_id), - user_private_key_(user_private_key), - cryptauth_service_(cryptauth_service), - device_manager_(device_manager), - weak_ptr_factory_(this) {} + cryptauth::CryptAuthService* cryptauth_service) + : cryptauth_service_(cryptauth_service), weak_ptr_factory_(this) {} TetherHostFetcher::~TetherHostFetcher() {} @@ -64,7 +58,9 @@ } remote_device_loader_ = cryptauth::RemoteDeviceLoader::Factory::NewInstance( - device_manager_->GetTetherHosts(), user_id_, user_private_key_, + cryptauth_service_->GetCryptAuthDeviceManager()->GetTetherHosts(), + cryptauth_service_->GetAccountId(), + cryptauth_service_->GetCryptAuthEnrollmentManager()->GetUserPrivateKey(), cryptauth_service_->CreateSecureMessageDelegate()); remote_device_loader_->Load( base::Bind(&TetherHostFetcher::OnRemoteDevicesLoaded,
diff --git a/chromeos/components/tether/tether_host_fetcher.h b/chromeos/components/tether/tether_host_fetcher.h index d190758..a5ce6ae 100644 --- a/chromeos/components/tether/tether_host_fetcher.h +++ b/chromeos/components/tether/tether_host_fetcher.h
@@ -28,10 +28,7 @@ // synced via CryptAuth. class TetherHostFetcher { public: - TetherHostFetcher(const std::string& user_id, - const std::string& user_private_key, - cryptauth::CryptAuthService* cryptauth_service, - cryptauth::CryptAuthDeviceManager* device_manager); + explicit TetherHostFetcher(cryptauth::CryptAuthService* cryptauth_service); virtual ~TetherHostFetcher(); // Fetches all tether hosts. @@ -47,7 +44,8 @@ protected: struct TetherHostFetchRequest { - TetherHostFetchRequest(const TetherHostListCallback& list_callback); + explicit TetherHostFetchRequest( + const TetherHostListCallback& list_callback); TetherHostFetchRequest(const std::string& device_id, const TetherHostCallback& single_callback); TetherHostFetchRequest(const TetherHostFetchRequest& other); @@ -63,6 +61,11 @@ TetherHostCallback single_callback; }; + TetherHostFetcher(const std::string& user_id, + const std::string& user_private_key, + cryptauth::CryptAuthService* cryptauth_service, + cryptauth::CryptAuthDeviceManager* device_manager); + void OnRemoteDevicesLoaded(const cryptauth::RemoteDeviceList& remote_devices); std::vector<TetherHostFetchRequest> requests_; @@ -70,11 +73,7 @@ private: void StartLoadingDevicesIfNeeded(); - const std::string user_id_; - const std::string user_private_key_; - cryptauth::CryptAuthService* cryptauth_service_; - cryptauth::CryptAuthDeviceManager* device_manager_; std::unique_ptr<cryptauth::RemoteDeviceLoader> remote_device_loader_;
diff --git a/chromeos/components/tether/tether_host_fetcher_unittest.cc b/chromeos/components/tether/tether_host_fetcher_unittest.cc index 6c4a927..27e7a02 100644 --- a/chromeos/components/tether/tether_host_fetcher_unittest.cc +++ b/chromeos/components/tether/tether_host_fetcher_unittest.cc
@@ -10,6 +10,9 @@ #include "base/bind.h" #include "base/memory/ptr_util.h" #include "components/cryptauth/cryptauth_device_manager.h" +#include "components/cryptauth/cryptauth_enroller.h" +#include "components/cryptauth/cryptauth_enrollment_manager.h" +#include "components/cryptauth/fake_cryptauth_gcm_manager.h" #include "components/cryptauth/fake_cryptauth_service.h" #include "components/cryptauth/fake_secure_message_delegate.h" #include "components/cryptauth/proto/cryptauth_api.pb.h" @@ -32,6 +35,31 @@ const char kTestUserId[] = "testUserId"; const char kTestUserPrivateKey[] = "kTestUserPrivateKey"; +class MockCryptAuthDeviceManager : public cryptauth::CryptAuthDeviceManager { + public: + ~MockCryptAuthDeviceManager() override {} + + MOCK_CONST_METHOD0(GetTetherHosts, + std::vector<cryptauth::ExternalDeviceInfo>()); +}; + +class MockCryptAuthEnrollmentManager + : public cryptauth::CryptAuthEnrollmentManager { + public: + explicit MockCryptAuthEnrollmentManager( + cryptauth::FakeCryptAuthGCMManager* fake_cryptauth_gcm_manager) + : cryptauth::CryptAuthEnrollmentManager( + nullptr /* clock */, + nullptr /* enroller_factory */, + nullptr /* secure_message_delegate */, + cryptauth::GcmDeviceInfo(), + fake_cryptauth_gcm_manager, + nullptr /* pref_service */) {} + ~MockCryptAuthEnrollmentManager() override {} + + MOCK_CONST_METHOD0(GetUserPrivateKey, std::string()); +}; + class FakeCryptAuthServiceWithTracking : public cryptauth::FakeCryptAuthService { public: @@ -54,14 +82,6 @@ std::vector<cryptauth::FakeSecureMessageDelegate*> created_delegates_; }; -class MockDeviceManager : public cryptauth::CryptAuthDeviceManager { - public: - ~MockDeviceManager() override {} - - MOCK_CONST_METHOD0(GetTetherHosts, - std::vector<cryptauth::ExternalDeviceInfo>()); -}; - class MockDeviceLoader : public cryptauth::RemoteDeviceLoader { public: MockDeviceLoader() @@ -97,7 +117,8 @@ class TestRemoteDeviceLoaderFactory : public cryptauth::RemoteDeviceLoader::Factory { public: - TestRemoteDeviceLoaderFactory(TetherHostFetcherTest* test) : test_(test) {} + explicit TestRemoteDeviceLoaderFactory(TetherHostFetcherTest* test) + : test_(test) {} std::unique_ptr<cryptauth::RemoteDeviceLoader> BuildInstance( const std::vector<cryptauth::ExternalDeviceInfo>& device_info_list, @@ -145,21 +166,34 @@ device_list_list_.clear(); single_device_list_.clear(); - fake_cryptauth_service_ = - base::WrapUnique(new FakeCryptAuthServiceWithTracking()); - - mock_device_manager_ = base::WrapUnique(new NiceMock<MockDeviceManager>()); + mock_device_manager_ = + base::WrapUnique(new NiceMock<MockCryptAuthDeviceManager>()); ON_CALL(*mock_device_manager_, GetTetherHosts()) .WillByDefault(Return(test_device_infos_)); + fake_cryptauth_gcm_manager_ = + base::MakeUnique<cryptauth::FakeCryptAuthGCMManager>("registrationId"); + mock_enrollment_manager_ = + base::WrapUnique(new NiceMock<MockCryptAuthEnrollmentManager>( + fake_cryptauth_gcm_manager_.get())); + ON_CALL(*mock_enrollment_manager_, GetUserPrivateKey()) + .WillByDefault(Return(kTestUserPrivateKey)); + + fake_cryptauth_service_ = + base::WrapUnique(new FakeCryptAuthServiceWithTracking()); + fake_cryptauth_service_->set_account_id(kTestUserId); + fake_cryptauth_service_->set_cryptauth_device_manager( + mock_device_manager_.get()); + fake_cryptauth_service_->set_cryptauth_enrollment_manager( + mock_enrollment_manager_.get()); + test_device_loader_factory_ = base::WrapUnique(new TestRemoteDeviceLoaderFactory(this)); cryptauth::RemoteDeviceLoader::Factory::SetInstanceForTesting( test_device_loader_factory_.get()); - tether_host_fetcher_ = base::MakeUnique<TetherHostFetcher>( - std::string(kTestUserId), std::string(kTestUserPrivateKey), - fake_cryptauth_service_.get(), mock_device_manager_.get()); + tether_host_fetcher_ = + base::MakeUnique<TetherHostFetcher>(fake_cryptauth_service_.get()); } void OnTetherHostListFetched(const cryptauth::RemoteDeviceList& device_list) { @@ -178,7 +212,11 @@ std::vector<std::shared_ptr<cryptauth::RemoteDevice>> single_device_list_; std::unique_ptr<FakeCryptAuthServiceWithTracking> fake_cryptauth_service_; - std::unique_ptr<NiceMock<MockDeviceManager>> mock_device_manager_; + std::unique_ptr<cryptauth::FakeCryptAuthGCMManager> + fake_cryptauth_gcm_manager_; + std::unique_ptr<NiceMock<MockCryptAuthDeviceManager>> mock_device_manager_; + std::unique_ptr<NiceMock<MockCryptAuthEnrollmentManager>> + mock_enrollment_manager_; std::unique_ptr<TestRemoteDeviceLoaderFactory> test_device_loader_factory_; std::unique_ptr<TetherHostFetcher> tether_host_fetcher_; @@ -265,4 +303,4 @@ } // namespace tether -} // namespace cryptauth +} // namespace chromeos
diff --git a/chromeos/components/tether/tether_network_disconnection_handler.cc b/chromeos/components/tether/tether_network_disconnection_handler.cc new file mode 100644 index 0000000..71d273d --- /dev/null +++ b/chromeos/components/tether/tether_network_disconnection_handler.cc
@@ -0,0 +1,50 @@ +// 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 "chromeos/components/tether/tether_network_disconnection_handler.h" + +#include "base/memory/ptr_util.h" +#include "chromeos/network/network_handler.h" +#include "chromeos/network/network_state.h" +#include "chromeos/network/network_state_handler.h" +#include "components/proximity_auth/logging/logging.h" + +namespace chromeos { + +namespace tether { + +TetherNetworkDisconnectionHandler::TetherNetworkDisconnectionHandler( + ActiveHost* active_host) + : TetherNetworkDisconnectionHandler( + active_host, + NetworkHandler::Get()->network_state_handler()) {} + +TetherNetworkDisconnectionHandler::TetherNetworkDisconnectionHandler( + ActiveHost* active_host, + NetworkStateHandler* network_state_handler) + : active_host_(active_host), network_state_handler_(network_state_handler) { + network_state_handler_->AddObserver(this, FROM_HERE); +} + +TetherNetworkDisconnectionHandler::~TetherNetworkDisconnectionHandler() { + network_state_handler_->RemoveObserver(this, FROM_HERE); +} + +void TetherNetworkDisconnectionHandler::NetworkConnectionStateChanged( + const NetworkState* network) { + // Note: |active_host_->GetWifiNetworkGuid()| returns "" unless currently + // connected, so this if() statement is only entered on disconnections. + if (network->guid() == active_host_->GetWifiNetworkGuid() && + !network->IsConnectedState()) { + PA_LOG(INFO) << "Connection to active host (Wi-Fi network GUID " + << network->guid() << ") has been lost."; + active_host_->SetActiveHostDisconnected(); + + // TODO(hansberry): Remove Wi-Fi network from "known" networks. + } +} + +} // namespace tether + +} // namespace chromeos
diff --git a/chromeos/components/tether/tether_network_disconnection_handler.h b/chromeos/components/tether/tether_network_disconnection_handler.h new file mode 100644 index 0000000..a92ee99 --- /dev/null +++ b/chromeos/components/tether/tether_network_disconnection_handler.h
@@ -0,0 +1,49 @@ +// 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 CHROMEOS_COMPONENTS_TETHER_TETHER_NETWORK_DISCONNECTION_HANDLER_H_ +#define CHROMEOS_COMPONENTS_TETHER_TETHER_NETWORK_DISCONNECTION_HANDLER_H_ + +#include "base/macros.h" +#include "chromeos/components/tether/active_host.h" +#include "chromeos/network/network_state_handler_observer.h" + +namespace chromeos { + +class NetworkStateHandler; + +namespace tether { + +class ActiveHost; + +// Handles lost Wi-Fi connections for ongoing tether sessions. When a tether +// connection is in progress, the device is connected to an underlying Wi-Fi +// network. If the Wi-Fi connection is disrupted (e.g., by the tether host going +// out of Wi-Fi range), tether metadata must be updated accordingly. This class +// tracks ongoing connections and updates this metadata when necessary. +class TetherNetworkDisconnectionHandler : public NetworkStateHandlerObserver { + public: + TetherNetworkDisconnectionHandler(ActiveHost* active_host); + ~TetherNetworkDisconnectionHandler() override; + + // NetworkStateHandlerObserver: + void NetworkConnectionStateChanged(const NetworkState* network) override; + + private: + friend class TetherNetworkDisconnectionHandlerTest; + + TetherNetworkDisconnectionHandler(ActiveHost* active_host, + NetworkStateHandler* network_state_handler); + + ActiveHost* active_host_; + NetworkStateHandler* network_state_handler_; + + DISALLOW_COPY_AND_ASSIGN(TetherNetworkDisconnectionHandler); +}; + +} // namespace tether + +} // namespace chromeos + +#endif // CHROMEOS_COMPONENTS_TETHER_TETHER_NETWORK_DISCONNECTION_HANDLER_H_
diff --git a/chromeos/components/tether/tether_network_disconnection_handler_unittest.cc b/chromeos/components/tether/tether_network_disconnection_handler_unittest.cc new file mode 100644 index 0000000..4c4b3ed --- /dev/null +++ b/chromeos/components/tether/tether_network_disconnection_handler_unittest.cc
@@ -0,0 +1,98 @@ +// 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 "chromeos/components/tether/tether_network_disconnection_handler.h" + +#include <memory> + +#include "base/memory/ptr_util.h" +#include "base/test/scoped_task_environment.h" +#include "chromeos/components/tether/fake_active_host.h" +#include "chromeos/dbus/dbus_thread_manager.h" +#include "chromeos/network/network_state.h" +#include "chromeos/network/network_state_test.h" +#include "testing/gmock/include/gmock/gmock.h" +#include "testing/gtest/include/gtest/gtest.h" +#include "third_party/cros_system_api/dbus/shill/dbus-constants.h" + +namespace chromeos { + +namespace tether { + +namespace { + +const char kDeviceId[] = "deviceId"; +const char kWifiNetworkGuid[] = "wifiNetworkGuid"; +const char kTetherNetworkGuid[] = "tetherNetworkGuid"; + +std::string CreateConnectedWifiConfigurationJsonString() { + std::stringstream ss; + ss << "{" + << " \"GUID\": \"" << kWifiNetworkGuid << "\"," + << " \"Type\": \"" << shill::kTypeWifi << "\"," + << " \"State\": \"" << shill::kStateReady << "\"" + << "}"; + return ss.str(); +} + +} // namespace + +class TetherNetworkDisconnectionHandlerTest : public NetworkStateTest { + protected: + TetherNetworkDisconnectionHandlerTest() : NetworkStateTest() {} + ~TetherNetworkDisconnectionHandlerTest() override {} + + void SetUp() override { + DBusThreadManager::Initialize(); + NetworkStateTest::SetUp(); + + wifi_service_path_ = + ConfigureService(CreateConnectedWifiConfigurationJsonString()); + + fake_active_host_ = base::MakeUnique<FakeActiveHost>(); + + handler_ = base::WrapUnique(new TetherNetworkDisconnectionHandler( + fake_active_host_.get(), network_state_handler())); + } + + void TearDown() override { + // Delete handler before the NetworkStateHandler and |fake_active_host_|. + handler_.reset(); + ShutdownNetworkState(); + NetworkStateTest::TearDown(); + DBusThreadManager::Shutdown(); + } + + void NotifyDisconnected() { + SetServiceProperty(wifi_service_path_, std::string(shill::kStateProperty), + base::Value(shill::kStateIdle)); + } + + base::test::ScopedTaskEnvironment scoped_task_environment_; + std::string wifi_service_path_; + + std::unique_ptr<FakeActiveHost> fake_active_host_; + + std::unique_ptr<TetherNetworkDisconnectionHandler> handler_; + + private: + DISALLOW_COPY_AND_ASSIGN(TetherNetworkDisconnectionHandlerTest); +}; + +TEST_F(TetherNetworkDisconnectionHandlerTest, TestConnectAndDisconnect) { + // Connect to the network. |handler_| should start tracking the connection. + fake_active_host_->SetActiveHostConnecting(kDeviceId, kTetherNetworkGuid); + fake_active_host_->SetActiveHostConnected(kDeviceId, kTetherNetworkGuid, + kWifiNetworkGuid); + + // Now, disconnect the Wi-Fi network. This should result in + // |fake_active_host_| becoming disconnected. + NotifyDisconnected(); + EXPECT_EQ(ActiveHost::ActiveHostStatus::DISCONNECTED, + fake_active_host_->GetActiveHostStatus()); +} + +} // namespace tether + +} // namespace cryptauth
diff --git a/chromeos/network/managed_network_configuration_handler_unittest.cc b/chromeos/network/managed_network_configuration_handler_unittest.cc index 06c197c..abdf830 100644 --- a/chromeos/network/managed_network_configuration_handler_unittest.cc +++ b/chromeos/network/managed_network_configuration_handler_unittest.cc
@@ -549,9 +549,7 @@ EXPECT_EQ(1, policy_observer_.GetPoliciesAppliedCountAndReset()); } -// TODO(stevenjb): https://crbug.com/710241 -TEST_F(ManagedNetworkConfigurationHandlerTest, - DISABLED_PolicyApplicationRunning) { +TEST_F(ManagedNetworkConfigurationHandlerTest, PolicyApplicationRunning) { InitializeStandardProfiles(); EXPECT_CALL(*mock_profile_client_, GetProperties(_, _, _)).Times(AnyNumber()); EXPECT_CALL(*mock_manager_client_, ConfigureServiceForProfile(_, _, _, _)) @@ -582,9 +580,7 @@ EXPECT_FALSE(managed_handler()->IsAnyPolicyApplicationRunning()); } -// TODO(stevenjb): https://crbug.com/710241 -TEST_F(ManagedNetworkConfigurationHandlerTest, - DISABLED_UpdatePolicyAfterFinished) { +TEST_F(ManagedNetworkConfigurationHandlerTest, UpdatePolicyAfterFinished) { InitializeStandardProfiles(); EXPECT_CALL(*mock_profile_client_, GetProperties(_, _, _)); EXPECT_CALL(*mock_manager_client_, ConfigureServiceForProfile(_, _, _, _)); @@ -690,9 +686,7 @@ base::RunLoop().RunUntilIdle(); } -// TODO(stevenjb): https://crbug.com/710241 -TEST_F(ManagedNetworkConfigurationHandlerTest, - DISABLED_SetPolicyUpdateManagedNewGUID) { +TEST_F(ManagedNetworkConfigurationHandlerTest, SetPolicyUpdateManagedNewGUID) { InitializeStandardProfiles(); SetUpEntry("policy/shill_managed_wifi1.json", kUser1ProfilePath, @@ -753,9 +747,7 @@ VerifyAndClearExpectations(); } -// TODO(stevenjb): https://crbug.com/710241 -TEST_F(ManagedNetworkConfigurationHandlerTest, - DISABLED_SetPolicyReapplyToManaged) { +TEST_F(ManagedNetworkConfigurationHandlerTest, SetPolicyReapplyToManaged) { InitializeStandardProfiles(); SetUpEntry("policy/shill_policy_on_unmanaged_wifi1.json", kUser1ProfilePath,
diff --git a/chromeos/network/policy_util.cc b/chromeos/network/policy_util.cc index b28f30b..ebea93e 100644 --- a/chromeos/network/policy_util.cc +++ b/chromeos/network/policy_util.cc
@@ -35,18 +35,17 @@ void RemoveFakeCredentials( const onc::OncValueSignature& signature, base::DictionaryValue* onc_object) { - base::DictionaryValue::Iterator it(*onc_object); - while (!it.IsAtEnd()) { - base::Value* value = NULL; + std::vector<std::string> entries_to_remove; + for (base::DictionaryValue::Iterator it(*onc_object); !it.IsAtEnd(); + it.Advance()) { + base::Value* value = nullptr; std::string field_name = it.key(); // We need the non-const entry to remove nested values but DictionaryValue // has no non-const iterator. onc_object->GetWithoutPathExpansion(field_name, &value); - // Advance before delete. - it.Advance(); // If |value| is a dictionary, recurse. - base::DictionaryValue* nested_object = NULL; + base::DictionaryValue* nested_object = nullptr; if (value->GetAsDictionary(&nested_object)) { const onc::OncFieldSignature* field_signature = onc::GetFieldSignature(signature, field_name); @@ -64,12 +63,14 @@ if (string_value == kFakeCredential) { // The value wasn't modified by the UI, thus we remove the field to keep // the existing value that is stored in Shill. - onc_object->RemoveWithoutPathExpansion(field_name, NULL); + entries_to_remove.push_back(field_name); } // Otherwise, the value is set and modified by the UI, thus we keep that // value to overwrite whatever is stored in Shill. } } + for (auto field_name : entries_to_remove) + onc_object->RemoveWithoutPathExpansion(field_name, nullptr); } // Returns true if |policy| matches |actual_network|, which must be part of a
diff --git a/components/arc/power/arc_power_bridge.cc b/components/arc/power/arc_power_bridge.cc index 1e0ad9c..d63f49c4 100644 --- a/components/arc/power/arc_power_bridge.cc +++ b/components/arc/power/arc_power_bridge.cc
@@ -16,6 +16,11 @@ namespace arc { +// Delay for notifying Android about screen brightness changes, added in +// order to prevent spammy brightness updates. +constexpr base::TimeDelta kNotifyBrightnessDelay = + base::TimeDelta::FromMilliseconds(200); + ArcPowerBridge::ArcPowerBridge(ArcBridgeService* bridge_service) : ArcService(bridge_service), binding_(this), weak_ptr_factory_(this) { arc_bridge_service()->power()->AddObserver(this); @@ -69,7 +74,19 @@ } void ArcPowerBridge::BrightnessChanged(int level, bool user_initiated) { - UpdateAndroidScreenBrightness(static_cast<double>(level)); + double percent = static_cast<double>(level); + const base::TimeTicks now = base::TimeTicks::Now(); + if (last_brightness_changed_time_.is_null() || + (now - last_brightness_changed_time_) >= kNotifyBrightnessDelay) { + UpdateAndroidScreenBrightness(percent); + notify_brightness_timer_.Stop(); + } else { + notify_brightness_timer_.Start( + FROM_HERE, kNotifyBrightnessDelay, + base::Bind(&ArcPowerBridge::UpdateAndroidScreenBrightness, + weak_ptr_factory_.GetWeakPtr(), percent)); + } + last_brightness_changed_time_ = now; } void ArcPowerBridge::OnPowerStateChanged(
diff --git a/components/arc/power/arc_power_bridge.h b/components/arc/power/arc_power_bridge.h index 328ded9..e6a5c7a 100644 --- a/components/arc/power/arc_power_bridge.h +++ b/components/arc/power/arc_power_bridge.h
@@ -58,6 +58,12 @@ // held by ARC. std::multimap<mojom::DisplayWakeLockType, int> wake_locks_; + // Last time that the power manager notified about a brightness change. + base::TimeTicks last_brightness_changed_time_; + // Timer used to run UpdateAndroidScreenBrightness() to notify Android + // about brightness changes. + base::OneShotTimer notify_brightness_timer_; + base::WeakPtrFactory<ArcPowerBridge> weak_ptr_factory_; DISALLOW_COPY_AND_ASSIGN(ArcPowerBridge);
diff --git a/components/autofill/core/browser/BUILD.gn b/components/autofill/core/browser/BUILD.gn index 5412dc1..5293b93c 100644 --- a/components/autofill/core/browser/BUILD.gn +++ b/components/autofill/core/browser/BUILD.gn
@@ -189,6 +189,7 @@ "//components/autofill/core/browser/proto", "//components/autofill/core/common", "//components/resources", + "//skia", ] deps = [ "//base", @@ -211,7 +212,6 @@ "//components/webdata/common", "//google_apis", "//net", - "//skia", "//sql", "//third_party/fips181", "//third_party/icu",
diff --git a/components/cryptauth/cryptauth_enrollment_manager.h b/components/cryptauth/cryptauth_enrollment_manager.h index e621b9f..ce4c9da7 100644 --- a/components/cryptauth/cryptauth_enrollment_manager.h +++ b/components/cryptauth/cryptauth_enrollment_manager.h
@@ -112,8 +112,8 @@ // been completed, then an empty string will be returned. // Note: These keys are really serialized protocol buffer messages, and should // only be used by passing to SecureMessageDelegate. - std::string GetUserPublicKey() const; - std::string GetUserPrivateKey() const; + virtual std::string GetUserPublicKey() const; + virtual std::string GetUserPrivateKey() const; protected: // Creates a new SyncScheduler instance. Exposed for testing.
diff --git a/components/drive/file_write_watcher_unittest.cc b/components/drive/file_write_watcher_unittest.cc index 23f80485..d567c8f 100644 --- a/components/drive/file_write_watcher_unittest.cc +++ b/components/drive/file_write_watcher_unittest.cc
@@ -49,7 +49,8 @@ EXPECT_TRUE(watch_success) << path.value(); const char kDummy[] = "hello"; - ASSERT_TRUE(base::WriteFile(path, kDummy, arraysize(kDummy))); + ASSERT_EQ(static_cast<int>(arraysize(kDummy)), + base::WriteFile(path, kDummy, arraysize(kDummy))); } class FileWriteWatcherTest : public testing::Test {
diff --git a/components/exo/compositor_frame_sink.cc b/components/exo/compositor_frame_sink.cc index 9b7a34c..cee2955 100644 --- a/components/exo/compositor_frame_sink.cc +++ b/components/exo/compositor_frame_sink.cc
@@ -18,12 +18,13 @@ CompositorFrameSink::CompositorFrameSink(const cc::FrameSinkId& frame_sink_id, cc::SurfaceManager* surface_manager, CompositorFrameSinkHolder* client) - : support_(this, - surface_manager, - frame_sink_id, - false /* is_root */, - true /* handles_frame_sink_id_invalidation */, - true /* needs_sync_points */), + : support_(cc::CompositorFrameSinkSupport::Create( + this, + surface_manager, + frame_sink_id, + false /* is_root */, + true /* handles_frame_sink_id_invalidation */, + true /* needs_sync_points */)), client_(client) {} CompositorFrameSink::~CompositorFrameSink() {} @@ -32,29 +33,30 @@ // cc::mojom::MojoCompositorFrameSink overrides: void CompositorFrameSink::SetNeedsBeginFrame(bool needs_begin_frame) { - support_.SetNeedsBeginFrame(needs_begin_frame); + support_->SetNeedsBeginFrame(needs_begin_frame); } void CompositorFrameSink::SubmitCompositorFrame( const cc::LocalSurfaceId& local_surface_id, cc::CompositorFrame frame) { - support_.SubmitCompositorFrame(local_surface_id, std::move(frame)); + support_->SubmitCompositorFrame(local_surface_id, std::move(frame)); } void CompositorFrameSink::BeginFrameDidNotSwap( const cc::BeginFrameAck& begin_frame_ack) { - support_.BeginFrameDidNotSwap(begin_frame_ack); + support_->BeginFrameDidNotSwap(begin_frame_ack); } void CompositorFrameSink::EvictFrame() { - support_.EvictFrame(); + support_->EvictFrame(); } //////////////////////////////////////////////////////////////////////////////// // cc::CompositorFrameSinkSupportClient overrides: -void CompositorFrameSink::DidReceiveCompositorFrameAck() { - client_->DidReceiveCompositorFrameAck(); +void CompositorFrameSink::DidReceiveCompositorFrameAck( + const cc::ReturnedResourceArray& resources) { + client_->DidReceiveCompositorFrameAck(resources); } void CompositorFrameSink::OnBeginFrame(const cc::BeginFrameArgs& args) {
diff --git a/components/exo/compositor_frame_sink.h b/components/exo/compositor_frame_sink.h index 22de0208..7da2b6b 100644 --- a/components/exo/compositor_frame_sink.h +++ b/components/exo/compositor_frame_sink.h
@@ -33,14 +33,15 @@ void EvictFrame() override; // Overridden from cc::CompositorFrameSinkSupportClient: - void DidReceiveCompositorFrameAck() override; + void DidReceiveCompositorFrameAck( + const cc::ReturnedResourceArray& resources) override; void OnBeginFrame(const cc::BeginFrameArgs& args) override; void ReclaimResources(const cc::ReturnedResourceArray& resources) override; void WillDrawSurface(const cc::LocalSurfaceId& local_surface_id, const gfx::Rect& damage_rect) override {} private: - cc::CompositorFrameSinkSupport support_; + std::unique_ptr<cc::CompositorFrameSinkSupport> support_; CompositorFrameSinkHolder* const client_; DISALLOW_COPY_AND_ASSIGN(CompositorFrameSink);
diff --git a/components/exo/compositor_frame_sink_holder.cc b/components/exo/compositor_frame_sink_holder.cc index 80b3bb53..b516b84 100644 --- a/components/exo/compositor_frame_sink_holder.cc +++ b/components/exo/compositor_frame_sink_holder.cc
@@ -40,7 +40,9 @@ //////////////////////////////////////////////////////////////////////////////// // cc::mojom::MojoCompositorFrameSinkClient overrides: -void CompositorFrameSinkHolder::DidReceiveCompositorFrameAck() { +void CompositorFrameSinkHolder::DidReceiveCompositorFrameAck( + const cc::ReturnedResourceArray& resources) { + ReclaimResources(resources); if (surface_) surface_->DidReceiveCompositorFrameAck(); }
diff --git a/components/exo/compositor_frame_sink_holder.h b/components/exo/compositor_frame_sink_holder.h index 534cf90..a469929 100644 --- a/components/exo/compositor_frame_sink_holder.h +++ b/components/exo/compositor_frame_sink_holder.h
@@ -45,7 +45,8 @@ } // Overridden from cc::mojom::MojoCompositorFrameSinkClient: - void DidReceiveCompositorFrameAck() override; + void DidReceiveCompositorFrameAck( + const cc::ReturnedResourceArray& resources) override; void OnBeginFrame(const cc::BeginFrameArgs& args) override; void ReclaimResources(const cc::ReturnedResourceArray& resources) override;
diff --git a/components/favicon/core/large_icon_service.cc b/components/favicon/core/large_icon_service.cc index 5817bfcf..c202c244 100644 --- a/components/favicon/core/large_icon_service.cc +++ b/components/favicon/core/large_icon_service.cc
@@ -12,6 +12,7 @@ #include "base/macros.h" #include "base/memory/ptr_util.h" #include "base/memory/ref_counted.h" +#include "base/metrics/histogram_macros.h" #include "base/strings/stringprintf.h" #include "base/task_runner.h" #include "base/threading/sequenced_worker_pool.h" @@ -217,6 +218,10 @@ favicon_base::LargeIconImageResult(fallback_icon_style_.release())); } +void ReportDownloadedSize(int size) { + UMA_HISTOGRAM_COUNTS_1000("Favicons.LargeIconService.DownloadedSize", size); +} + void OnFetchIconFromGoogleServerComplete( FaviconService* favicon_service, const GURL& page_url, @@ -229,9 +234,12 @@ favicon_service->UnableToDownloadFavicon(GURL(server_request_url)); base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, base::Bind(callback, false)); + ReportDownloadedSize(0); return; } + ReportDownloadedSize(image.Width()); + // If given, use the original favicon URL from Content-Location http header. // Otherwise, use the request URL as fallback. std::string original_icon_url = metadata.content_location_header;
diff --git a/components/favicon/core/large_icon_service_unittest.cc b/components/favicon/core/large_icon_service_unittest.cc index 434baf1..bc27de1 100644 --- a/components/favicon/core/large_icon_service_unittest.cc +++ b/components/favicon/core/large_icon_service_unittest.cc
@@ -14,6 +14,7 @@ #include "base/message_loop/message_loop.h" #include "base/run_loop.h" #include "base/task/cancelable_task_tracker.h" +#include "base/test/histogram_tester.h" #include "base/test/mock_callback.h" #include "base/threading/thread_task_runner_handle.h" #include "components/favicon/core/favicon_client.h" @@ -35,6 +36,7 @@ namespace favicon { namespace { +using testing::IsEmpty; using testing::IsNull; using testing::Eq; using testing::NiceMock; @@ -128,6 +130,7 @@ NiceMock<MockImageFetcher>* mock_image_fetcher_; testing::NiceMock<MockFaviconService> mock_favicon_service_; LargeIconService large_icon_service_; + base::HistogramTester histogram_tester_; private: DISALLOW_COPY_AND_ASSIGN(LargeIconServiceTest); @@ -157,6 +160,8 @@ EXPECT_CALL(callback, Run(true)); base::RunLoop().RunUntilIdle(); + histogram_tester_.ExpectUniqueSample( + "Favicons.LargeIconService.DownloadedSize", 64, /*expected_count=*/1); } TEST_F(LargeIconServiceTest, ShouldGetFromGoogleServerWithOriginalUrl) { @@ -225,6 +230,9 @@ EXPECT_CALL(callback, Run(false)); base::RunLoop().RunUntilIdle(); + EXPECT_THAT(histogram_tester_.GetAllSamples( + "Favicons.LargeIconService.DownloadedSize"), + IsEmpty()); } TEST_F(LargeIconServiceTest, ShouldReportUnavailableIfFetchFromServerFails) { @@ -250,9 +258,12 @@ EXPECT_CALL(callback, Run(false)); base::RunLoop().RunUntilIdle(); + // Verify that download failure gets recorded. + histogram_tester_.ExpectUniqueSample( + "Favicons.LargeIconService.DownloadedSize", 0, /*expected_count=*/1); } -TEST_F(LargeIconServiceTest, ShoutNotGetFromGoogleServerIfUnavailable) { +TEST_F(LargeIconServiceTest, ShouldNotGetFromGoogleServerIfUnavailable) { ON_CALL( mock_favicon_service_, WasUnableToDownloadFavicon(GURL( @@ -274,6 +285,9 @@ EXPECT_CALL(callback, Run(false)); base::RunLoop().RunUntilIdle(); + EXPECT_THAT(histogram_tester_.GetAllSamples( + "Favicons.LargeIconService.DownloadedSize"), + IsEmpty()); } class LargeIconServiceGetterTest : public LargeIconServiceTest,
diff --git a/components/feature_engagement_tracker/internal/BUILD.gn b/components/feature_engagement_tracker/internal/BUILD.gn index 662d630..fcdd0828 100644 --- a/components/feature_engagement_tracker/internal/BUILD.gn +++ b/components/feature_engagement_tracker/internal/BUILD.gn
@@ -29,8 +29,12 @@ "model.h", "model_impl.cc", "model_impl.h", + "never_condition_validator.cc", + "never_condition_validator.h", "once_condition_validator.cc", "once_condition_validator.h", + "single_invalid_configuration.cc", + "single_invalid_configuration.h", "store.h", ] @@ -61,7 +65,9 @@ "feature_engagement_tracker_impl_unittest.cc", "in_memory_store_unittest.cc", "model_impl_unittest.cc", + "never_condition_validator_unittest.cc", "once_condition_validator_unittest.cc", + "single_invalid_configuration_unittest.cc", ] deps = [
diff --git a/components/feature_engagement_tracker/internal/feature_constants.cc b/components/feature_engagement_tracker/internal/feature_constants.cc index 7fb59c9..570ff107 100644 --- a/components/feature_engagement_tracker/internal/feature_constants.cc +++ b/components/feature_engagement_tracker/internal/feature_constants.cc
@@ -8,6 +8,9 @@ namespace feature_engagement_tracker { +const base::Feature kIPHDemoMode{"IPH_DemoMode", + base::FEATURE_DISABLED_BY_DEFAULT}; + const base::Feature kIPHDummyFeature{"IPH_DummyFeature", base::FEATURE_DISABLED_BY_DEFAULT};
diff --git a/components/feature_engagement_tracker/internal/feature_engagement_tracker_impl.cc b/components/feature_engagement_tracker/internal/feature_engagement_tracker_impl.cc index 5b48c708..24c499d 100644 --- a/components/feature_engagement_tracker/internal/feature_engagement_tracker_impl.cc +++ b/components/feature_engagement_tracker/internal/feature_engagement_tracker_impl.cc
@@ -11,24 +11,37 @@ #include "components/feature_engagement_tracker/internal/feature_list.h" #include "components/feature_engagement_tracker/internal/in_memory_store.h" #include "components/feature_engagement_tracker/internal/model_impl.h" +#include "components/feature_engagement_tracker/internal/never_condition_validator.h" #include "components/feature_engagement_tracker/internal/once_condition_validator.h" +#include "components/feature_engagement_tracker/internal/single_invalid_configuration.h" +#include "components/feature_engagement_tracker/public/feature_constants.h" namespace feature_engagement_tracker { -// Set up all feature configurations. -// TODO(nyquist): Create FinchConfiguration to parse configuration. -std::unique_ptr<Configuration> CreateAndParseConfiguration() { +namespace { + +// Creates a FeatureEngagementTrackerImpl that is usable for a demo mode. +std::unique_ptr<FeatureEngagementTracker> +CreateDemoModeFeatureEngagementTracker() { std::unique_ptr<EditableConfiguration> configuration = base::MakeUnique<EditableConfiguration>(); + + // Create valid configurations for all features to ensure that the + // OnceConditionValidator acknowledges that thet meet conditions once. std::vector<const base::Feature*> features = GetAllFeatures(); - for (auto* it : features) { + for (auto* feature : features) { FeatureConfig feature_config; feature_config.valid = true; - configuration->SetConfiguration(it, feature_config); + configuration->SetConfiguration(feature, feature_config); } - return std::move(configuration); + + return base::MakeUnique<FeatureEngagementTrackerImpl>( + base::MakeUnique<InMemoryStore>(), std::move(configuration), + base::MakeUnique<OnceConditionValidator>()); } +} // namespace + // This method is declared in //components/feature_engagement_tracker/public/ // feature_engagement_tracker.h // and should be linked in to any binary using FeatureEngagementTracker::Create. @@ -36,10 +49,15 @@ FeatureEngagementTracker* FeatureEngagementTracker::Create( const base::FilePath& storage_dir, const scoped_refptr<base::SequencedTaskRunner>& background__task_runner) { + if (base::FeatureList::IsEnabled(kIPHDemoMode)) + return CreateDemoModeFeatureEngagementTracker().release(); + std::unique_ptr<Store> store = base::MakeUnique<InMemoryStore>(); - std::unique_ptr<Configuration> configuration = CreateAndParseConfiguration(); + // TODO(nyquist): Create FinchConfiguration to parse configuration. + std::unique_ptr<Configuration> configuration = + base::MakeUnique<SingleInvalidConfiguration>(); std::unique_ptr<ConditionValidator> validator = - base::MakeUnique<OnceConditionValidator>(); + base::MakeUnique<NeverConditionValidator>(); return new FeatureEngagementTrackerImpl( std::move(store), std::move(configuration), std::move(validator));
diff --git a/components/feature_engagement_tracker/internal/never_condition_validator.cc b/components/feature_engagement_tracker/internal/never_condition_validator.cc new file mode 100644 index 0000000..317c66c0 --- /dev/null +++ b/components/feature_engagement_tracker/internal/never_condition_validator.cc
@@ -0,0 +1,20 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "components/feature_engagement_tracker/internal/never_condition_validator.h" + +#include "components/feature_engagement_tracker/internal/model.h" + +namespace feature_engagement_tracker { + +NeverConditionValidator::NeverConditionValidator() = default; + +NeverConditionValidator::~NeverConditionValidator() = default; + +bool NeverConditionValidator::MeetsConditions(const base::Feature& feature, + const Model& model) { + return false; +} + +} // namespace feature_engagement_tracker
diff --git a/components/feature_engagement_tracker/internal/never_condition_validator.h b/components/feature_engagement_tracker/internal/never_condition_validator.h new file mode 100644 index 0000000..b9fca64 --- /dev/null +++ b/components/feature_engagement_tracker/internal/never_condition_validator.h
@@ -0,0 +1,37 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef COMPONENTS_FEATURE_ENGAGEMENT_TRACKER_INTERNAL_NEVER_CONDITION_VALIDATOR_H_ +#define COMPONENTS_FEATURE_ENGAGEMENT_TRACKER_INTERNAL_NEVER_CONDITION_VALIDATOR_H_ + +#include <unordered_set> + +#include "base/macros.h" +#include "components/feature_engagement_tracker/internal/condition_validator.h" +#include "components/feature_engagement_tracker/internal/model.h" + +namespace base { +struct Feature; +} // namespace base + +namespace feature_engagement_tracker { + +// An ConditionValidator that never acknowledges that a feature has met its +// conditions. +class NeverConditionValidator : public ConditionValidator { + public: + NeverConditionValidator(); + ~NeverConditionValidator() override; + + // ConditionValidator implementation. + bool MeetsConditions(const base::Feature& feature, + const Model& model) override; + + private: + DISALLOW_COPY_AND_ASSIGN(NeverConditionValidator); +}; + +} // namespace feature_engagement_tracker + +#endif // COMPONENTS_FEATURE_ENGAGEMENT_TRACKER_INTERNAL_NEVER_CONDITION_VALIDATOR_H_
diff --git a/components/feature_engagement_tracker/internal/never_condition_validator_unittest.cc b/components/feature_engagement_tracker/internal/never_condition_validator_unittest.cc new file mode 100644 index 0000000..4bcd08e --- /dev/null +++ b/components/feature_engagement_tracker/internal/never_condition_validator_unittest.cc
@@ -0,0 +1,70 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "components/feature_engagement_tracker/internal/never_condition_validator.h" + +#include "base/feature_list.h" +#include "base/metrics/field_trial.h" +#include "base/test/scoped_feature_list.h" +#include "components/feature_engagement_tracker/internal/model.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace feature_engagement_tracker { + +namespace { + +const base::Feature kTestFeatureFoo{"test_foo", + base::FEATURE_DISABLED_BY_DEFAULT}; +const base::Feature kTestFeatureBar{"test_bar", + base::FEATURE_DISABLED_BY_DEFAULT}; + +// A Model that is always postive to show in-product help. +class TestModel : public Model { + public: + TestModel() { + feature_config_.valid = true; + feature_config_.feature_used_event = "foobar"; + } + + void Initialize(const OnModelInitializationFinished& callback) override {} + + bool IsReady() const override { return true; } + + const FeatureConfig& GetFeatureConfig( + const base::Feature& feature) const override { + return feature_config_; + } + + void SetIsCurrentlyShowing(bool is_showing) override {} + + bool IsCurrentlyShowing() const override { return false; } + + private: + FeatureConfig feature_config_; + + DISALLOW_COPY_AND_ASSIGN(TestModel); +}; + +class NeverConditionValidatorTest : public ::testing::Test { + public: + NeverConditionValidatorTest() = default; + + protected: + base::test::ScopedFeatureList scoped_feature_list_; + TestModel model_; + NeverConditionValidator validator_; + + private: + DISALLOW_COPY_AND_ASSIGN(NeverConditionValidatorTest); +}; + +} // namespace + +TEST_F(NeverConditionValidatorTest, ShouldNeverMeetConditions) { + scoped_feature_list_.InitWithFeatures({kTestFeatureFoo, kTestFeatureBar}, {}); + EXPECT_FALSE(validator_.MeetsConditions(kTestFeatureFoo, model_)); + EXPECT_FALSE(validator_.MeetsConditions(kTestFeatureBar, model_)); +} + +} // namespace feature_engagement_tracker
diff --git a/components/feature_engagement_tracker/internal/once_condition_validator.cc b/components/feature_engagement_tracker/internal/once_condition_validator.cc index 2e14015..1240766 100644 --- a/components/feature_engagement_tracker/internal/once_condition_validator.cc +++ b/components/feature_engagement_tracker/internal/once_condition_validator.cc
@@ -16,9 +16,6 @@ bool OnceConditionValidator::MeetsConditions(const base::Feature& feature, const Model& model) { - if (!base::FeatureList::IsEnabled(feature)) - return false; - if (!model.IsReady()) return false;
diff --git a/components/feature_engagement_tracker/internal/once_condition_validator.h b/components/feature_engagement_tracker/internal/once_condition_validator.h index 9cc0d54..83b265e 100644 --- a/components/feature_engagement_tracker/internal/once_condition_validator.h +++ b/components/feature_engagement_tracker/internal/once_condition_validator.h
@@ -20,16 +20,16 @@ // An ConditionValidator that will ensure that each base::Feature will meet // conditions maximum one time for any given session. // It has the following requirements: -// - The base::Feature is enabled // - The Model is ready. // - No other in-product help is currently showing. -// - FeatureServerConfig for the feature is valid. +// - FeatureConfig for the feature is valid. // - This is the first time the given base::Feature meets all above stated // conditions. // -// NOTE: This ConditionValidator fully ignores any other configuration specified -// in the FeatureServerConfig. In practice this leads this ConditionValidator -// to be well suited for a demonstration mode of in-product help. +// NOTE: This ConditionValidator fully ignores whether the base::Feature is +// enabled or not and any other configuration specified in the FeatureConfig. +// In practice this leads this ConditionValidator to be well suited for a +// demonstration mode of in-product help. class OnceConditionValidator : public ConditionValidator { public: OnceConditionValidator();
diff --git a/components/feature_engagement_tracker/internal/once_condition_validator_unittest.cc b/components/feature_engagement_tracker/internal/once_condition_validator_unittest.cc index ecc58e4c..c7c7598 100644 --- a/components/feature_engagement_tracker/internal/once_condition_validator_unittest.cc +++ b/components/feature_engagement_tracker/internal/once_condition_validator_unittest.cc
@@ -52,6 +52,8 @@ class OnceConditionValidatorTest : public ::testing::Test { public: + OnceConditionValidatorTest() = default; + void SetUp() override { // By default, model should be ready. model_.SetIsReady(true); @@ -67,6 +69,9 @@ base::test::ScopedFeatureList scoped_feature_list_; TestModel model_; OnceConditionValidator validator_; + + private: + DISALLOW_COPY_AND_ASSIGN(OnceConditionValidatorTest); }; } // namespace @@ -82,7 +87,8 @@ EXPECT_FALSE(validator_.MeetsConditions(kTestFeatureFoo, model_)); } -TEST_F(OnceConditionValidatorTest, OnlyEnabledFeaturesShouldTrigger) { +TEST_F(OnceConditionValidatorTest, + BothEnabledAndDisabledFeaturesShouldTrigger) { scoped_feature_list_.InitWithFeatures({kTestFeatureFoo}, {kTestFeatureBar}); // Initialize validator with one enabled and one disabled feature, both valid. @@ -93,11 +99,11 @@ // kTestFeatureBar is disabled. Ordering disabled feature first to ensure this // captures a different behavior than the // OnlyOneFeatureShouldTriggerPerSession test below. - EXPECT_FALSE(validator_.MeetsConditions(kTestFeatureBar, model_)); + EXPECT_TRUE(validator_.MeetsConditions(kTestFeatureBar, model_)); EXPECT_TRUE(validator_.MeetsConditions(kTestFeatureFoo, model_)); } -TEST_F(OnceConditionValidatorTest, NeverTriggerWhenAllFeaturesDisabled) { +TEST_F(OnceConditionValidatorTest, StillTriggerWhenAllFeaturesDisabled) { scoped_feature_list_.InitWithFeatures({}, {kTestFeatureFoo, kTestFeatureBar}); // Initialize validator with two enabled features, both valid. @@ -105,8 +111,8 @@ AddFeature(kTestFeatureBar, true); // No features should get to show enlightenment. - EXPECT_FALSE(validator_.MeetsConditions(kTestFeatureFoo, model_)); - EXPECT_FALSE(validator_.MeetsConditions(kTestFeatureBar, model_)); + EXPECT_TRUE(validator_.MeetsConditions(kTestFeatureFoo, model_)); + EXPECT_TRUE(validator_.MeetsConditions(kTestFeatureBar, model_)); } TEST_F(OnceConditionValidatorTest, OnlyTriggerWhenModelIsReady) {
diff --git a/components/feature_engagement_tracker/internal/single_invalid_configuration.cc b/components/feature_engagement_tracker/internal/single_invalid_configuration.cc new file mode 100644 index 0000000..ed20e661 --- /dev/null +++ b/components/feature_engagement_tracker/internal/single_invalid_configuration.cc
@@ -0,0 +1,23 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "components/feature_engagement_tracker/internal/single_invalid_configuration.h" + +#include "components/feature_engagement_tracker/internal/configuration.h" + +namespace feature_engagement_tracker { + +SingleInvalidConfiguration::SingleInvalidConfiguration() { + invalid_feature_config_.valid = false; + invalid_feature_config_.feature_used_event = "nothing_to_see_here"; +}; + +SingleInvalidConfiguration::~SingleInvalidConfiguration() = default; + +const FeatureConfig& SingleInvalidConfiguration::GetFeatureConfig( + const base::Feature& feature) const { + return invalid_feature_config_; +} + +} // namespace feature_engagement_tracker
diff --git a/components/feature_engagement_tracker/internal/single_invalid_configuration.h b/components/feature_engagement_tracker/internal/single_invalid_configuration.h new file mode 100644 index 0000000..449cee9 --- /dev/null +++ b/components/feature_engagement_tracker/internal/single_invalid_configuration.h
@@ -0,0 +1,39 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef COMPONENTS_FEATURE_ENGAGEMENT_TRACKER_INTERNAL_SINGLE_INVALID_CONFIGURATION_H_ +#define COMPONENTS_FEATURE_ENGAGEMENT_TRACKER_INTERNAL_SINGLE_INVALID_CONFIGURATION_H_ + +#include <unordered_set> + +#include "base/macros.h" +#include "components/feature_engagement_tracker/internal/configuration.h" + +namespace base { +struct Feature; +} // namespace base + +namespace feature_engagement_tracker { + +// An Configuration that always returns the same single invalid configuration, +// regardless of which feature. +class SingleInvalidConfiguration : public Configuration { + public: + SingleInvalidConfiguration(); + ~SingleInvalidConfiguration() override; + + // Configuration implementation. + const FeatureConfig& GetFeatureConfig( + const base::Feature& feature) const override; + + private: + // The invalid configuration to always return. + FeatureConfig invalid_feature_config_; + + DISALLOW_COPY_AND_ASSIGN(SingleInvalidConfiguration); +}; + +} // namespace feature_engagement_tracker + +#endif // COMPONENTS_FEATURE_ENGAGEMENT_TRACKER_INTERNAL_SINGLE_INVALID_CONFIGURATION_H_
diff --git a/components/feature_engagement_tracker/internal/single_invalid_configuration_unittest.cc b/components/feature_engagement_tracker/internal/single_invalid_configuration_unittest.cc new file mode 100644 index 0000000..d4c2666 --- /dev/null +++ b/components/feature_engagement_tracker/internal/single_invalid_configuration_unittest.cc
@@ -0,0 +1,46 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "components/feature_engagement_tracker/internal/single_invalid_configuration.h" + +#include "base/feature_list.h" +#include "base/metrics/field_trial.h" +#include "base/test/scoped_feature_list.h" +#include "components/feature_engagement_tracker/internal/configuration.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace feature_engagement_tracker { + +namespace { + +const base::Feature kTestFeatureFoo{"test_foo", + base::FEATURE_DISABLED_BY_DEFAULT}; +const base::Feature kTestFeatureBar{"test_bar", + base::FEATURE_DISABLED_BY_DEFAULT}; + +class SingleInvalidConfigurationTest : public ::testing::Test { + public: + SingleInvalidConfigurationTest() = default; + + protected: + base::test::ScopedFeatureList scoped_feature_list_; + SingleInvalidConfiguration configuration_; + + private: + DISALLOW_COPY_AND_ASSIGN(SingleInvalidConfigurationTest); +}; + +} // namespace + +TEST_F(SingleInvalidConfigurationTest, AllConfigurationsAreInvalid) { + scoped_feature_list_.InitWithFeatures({kTestFeatureFoo, kTestFeatureBar}, {}); + + FeatureConfig foo_config = configuration_.GetFeatureConfig(kTestFeatureFoo); + EXPECT_FALSE(foo_config.valid); + + FeatureConfig bar_config = configuration_.GetFeatureConfig(kTestFeatureBar); + EXPECT_FALSE(bar_config.valid); +} + +} // namespace feature_engagement_tracker
diff --git a/components/feature_engagement_tracker/public/feature_constants.h b/components/feature_engagement_tracker/public/feature_constants.h index 919d6005..c26608a 100644 --- a/components/feature_engagement_tracker/public/feature_constants.h +++ b/components/feature_engagement_tracker/public/feature_constants.h
@@ -8,7 +8,11 @@ #include "base/feature_list.h" namespace feature_engagement_tracker { -// All the features declared in this file should also be declared in the Java + +// A feature for enabling a demonstration mode for In-Product Help. +extern const base::Feature kIPHDemoMode; + +// All the features declared below should also be declared in the Java // version: org.chromium.components.feature_engagement_tracker.FeatureConstants. // A dummy feature until real features start using the backend.
diff --git a/components/history/core/browser/history_backend_unittest.cc b/components/history/core/browser/history_backend_unittest.cc index 4fba585..16455290 100644 --- a/components/history/core/browser/history_backend_unittest.cc +++ b/components/history/core/browser/history_backend_unittest.cc
@@ -3675,10 +3675,13 @@ // Setup dummy index database files. const char* data = "Dummy"; const size_t data_len = 5; - ASSERT_TRUE(base::WriteFile(db1, data, data_len)); - ASSERT_TRUE(base::WriteFile(db1_journal, data, data_len)); - ASSERT_TRUE(base::WriteFile(db1_wal, data, data_len)); - ASSERT_TRUE(base::WriteFile(db2_actual, data, data_len)); + ASSERT_EQ(static_cast<int>(data_len), base::WriteFile(db1, data, data_len)); + ASSERT_EQ(static_cast<int>(data_len), + base::WriteFile(db1_journal, data, data_len)); + ASSERT_EQ(static_cast<int>(data_len), + base::WriteFile(db1_wal, data, data_len)); + ASSERT_EQ(static_cast<int>(data_len), + base::WriteFile(db2_actual, data, data_len)); #if defined(OS_POSIX) EXPECT_TRUE(base::CreateSymbolicLink(db2_actual, db2_symlink)); #endif
diff --git a/components/ntp_snippets/remote/remote_suggestions_provider_impl_unittest.cc b/components/ntp_snippets/remote/remote_suggestions_provider_impl_unittest.cc index 6716ef4..4465246 100644 --- a/components/ntp_snippets/remote/remote_suggestions_provider_impl_unittest.cc +++ b/components/ntp_snippets/remote/remote_suggestions_provider_impl_unittest.cc
@@ -89,10 +89,6 @@ return arg.id().id_within_category() == expected_id; } -MATCHER_P(IsCategory, id, "") { - return arg.id() == static_cast<int>(id); -} - MATCHER_P(HasCode, code, "") { return arg.code == code; }
diff --git a/components/offline_items_collection/core/android/java/src/org/chromium/components/offline_items_collection/LegacyHelpers.java b/components/offline_items_collection/core/android/java/src/org/chromium/components/offline_items_collection/LegacyHelpers.java index e2c7971..92cd426c 100644 --- a/components/offline_items_collection/core/android/java/src/org/chromium/components/offline_items_collection/LegacyHelpers.java +++ b/components/offline_items_collection/core/android/java/src/org/chromium/components/offline_items_collection/LegacyHelpers.java
@@ -4,6 +4,7 @@ package org.chromium.components.offline_items_collection; +import android.support.annotation.Nullable; import android.text.TextUtils; /** @@ -34,8 +35,8 @@ * @param id The {@link ContentId} to inspect. * @return Whether or not {@code id} was built for a traditional download. */ - public static boolean isLegacyDownload(ContentId id) { - return TextUtils.equals(LEGACY_DOWNLOAD_NAMESPACE, id.namespace); + public static boolean isLegacyDownload(@Nullable ContentId id) { + return id != null && TextUtils.equals(LEGACY_DOWNLOAD_NAMESPACE, id.namespace); } /** @@ -45,8 +46,8 @@ * @param id The {@link ContentId} to inspect. * @return Whether or not {@code id} was built for a traditional offline page. */ - public static boolean isLegacyOfflinePage(ContentId id) { - return TextUtils.equals(LEGACY_OFFLINE_PAGE_NAMESPACE, id.namespace); + public static boolean isLegacyOfflinePage(@Nullable ContentId id) { + return id != null && TextUtils.equals(LEGACY_OFFLINE_PAGE_NAMESPACE, id.namespace); } private LegacyHelpers() {}
diff --git a/components/password_manager/core/browser/import/password_importer_unittest.cc b/components/password_manager/core/browser/import/password_importer_unittest.cc index 24ff2dc..26b0149 100644 --- a/components/password_manager/core/browser/import/password_importer_unittest.cc +++ b/components/password_manager/core/browser/import/password_importer_unittest.cc
@@ -78,8 +78,8 @@ base::FilePath input_path = temp_directory_.GetPath().AppendASCII(kTestFileName); - ASSERT_TRUE( - base::WriteFile(input_path, kTestCSVInput, strlen(kTestCSVInput))); + ASSERT_EQ(static_cast<int>(strlen(kTestCSVInput)), + base::WriteFile(input_path, kTestCSVInput, strlen(kTestCSVInput))); ASSERT_NO_FATAL_FAILURE(StartImportAndWaitForCompletion(input_path)); EXPECT_EQ(PasswordImporter::SUCCESS, result());
diff --git a/components/payments/content/android/BUILD.gn b/components/payments/content/android/BUILD.gn index 1978d227..609224f14 100644 --- a/components/payments/content/android/BUILD.gn +++ b/components/payments/content/android/BUILD.gn
@@ -12,8 +12,6 @@ "component_jni_registrar.h", "currency_formatter_android.cc", "currency_formatter_android.h", - "journey_logger_android.cc", - "journey_logger_android.h", "payment_details_validation_android.cc", "payment_details_validation_android.h", "payment_manifest_downloader_android.cc", @@ -35,7 +33,6 @@ generate_jni("jni_headers") { sources = [ "java/src/org/chromium/components/payments/CurrencyFormatter.java", - "java/src/org/chromium/components/payments/JourneyLogger.java", "java/src/org/chromium/components/payments/PaymentManifestDownloader.java", "java/src/org/chromium/components/payments/PaymentManifestParser.java", "java/src/org/chromium/components/payments/PaymentValidator.java", @@ -46,7 +43,6 @@ android_library("java") { java_files = [ "java/src/org/chromium/components/payments/CurrencyFormatter.java", - "java/src/org/chromium/components/payments/JourneyLogger.java", "java/src/org/chromium/components/payments/PaymentManifestDownloader.java", "java/src/org/chromium/components/payments/PaymentManifestParser.java", "java/src/org/chromium/components/payments/PaymentValidator.java",
diff --git a/components/payments/content/android/component_jni_registrar.cc b/components/payments/content/android/component_jni_registrar.cc index 4dbb97d..ef6c00a 100644 --- a/components/payments/content/android/component_jni_registrar.cc +++ b/components/payments/content/android/component_jni_registrar.cc
@@ -8,7 +8,6 @@ #include "base/android/jni_registrar.h" #include "base/macros.h" #include "components/payments/content/android/currency_formatter_android.h" -#include "components/payments/content/android/journey_logger_android.h" #include "components/payments/content/android/payment_details_validation_android.h" #include "components/payments/content/android/payment_manifest_downloader_android.h" #include "components/payments/content/android/payment_manifest_parser_android.h" @@ -18,7 +17,6 @@ static base::android::RegistrationMethod kPaymentsRegisteredMethods[] = { {"CurrencyFormatter", CurrencyFormatterAndroid::Register}, - {"JourneyLogger", JourneyLoggerAndroid::Register}, {"PaymentManifestDownloader", RegisterPaymentManifestDownloader}, {"PaymentManifestParser", RegisterPaymentManifestParser}, {"PaymentValidator", RegisterPaymentValidator},
diff --git a/components/payments/core/BUILD.gn b/components/payments/core/BUILD.gn index 0f6a6d3..99d9269 100644 --- a/components/payments/core/BUILD.gn +++ b/components/payments/core/BUILD.gn
@@ -34,7 +34,9 @@ "//base", "//components/autofill/core/browser", "//components/strings:components_strings_grit", + "//components/ukm", "//ui/base", + "//url", ] public_deps = [ @@ -63,6 +65,9 @@ "//base/test:test_support", "//components/autofill/core/browser", "//components/autofill/core/browser:test_support", + "//components/metrics/proto", + "//components/ukm", + "//components/ukm:test_support", "//testing/gmock", "//testing/gtest", "//third_party/libaddressinput:test_support",
diff --git a/components/payments/core/DEPS b/components/payments/core/DEPS index 0b6bf95..ad58bf35 100644 --- a/components/payments/core/DEPS +++ b/components/payments/core/DEPS
@@ -2,7 +2,9 @@ "-components/payments/content", "-content", "+components/autofill/core", + "+components/metrics", "+components/strings", + "+components/ukm", "+third_party/libaddressinput", "+ui/base", ]
diff --git a/components/payments/core/journey_logger.cc b/components/payments/core/journey_logger.cc index d8731c0..dc25cf6 100644 --- a/components/payments/core/journey_logger.cc +++ b/components/payments/core/journey_logger.cc
@@ -8,9 +8,19 @@ #include "base/metrics/histogram_functions.h" #include "base/metrics/histogram_macros.h" +#include "components/autofill/core/browser/autofill_experiments.h" +#include "components/ukm/ukm_entry_builder.h" +#include "components/ukm/ukm_service.h" namespace payments { +namespace internal { +extern const char kUKMCheckoutEventsEntryName[] = + "PaymentRequest.CheckoutEvents"; +extern const char kUKMCompletionStatusMetricName[] = "CompletionStatus"; +extern const char kUKMEventsMetricName[] = "Events"; +} // namespace internal + namespace { // Returns the JourneyLogger histograms name suffix based on the |section| and @@ -54,11 +64,16 @@ } // namespace -JourneyLogger::JourneyLogger(bool is_incognito) +JourneyLogger::JourneyLogger(bool is_incognito, + const GURL& url, + ukm::UkmService* ukm_service) : was_can_make_payments_used_(false), could_make_payment_(false), was_show_called_(false), - is_incognito_(is_incognito) {} + is_incognito_(is_incognito), + events_(EVENT_INITIATED), + url_(url), + ukm_service_(ukm_service) {} JourneyLogger::~JourneyLogger() {} @@ -92,6 +107,10 @@ was_show_called_ = true; } +void JourneyLogger::SetEventOccurred(Event event) { + events_ |= event; +} + void JourneyLogger::RecordJourneyStatsHistograms( CompletionStatus completion_status) { RecordSectionSpecificStats(completion_status); @@ -99,6 +118,8 @@ // Record the CanMakePayment metrics based on whether the transaction was // completed or aborted by the user (UserAborted) or otherwise (OtherAborted). RecordCanMakePaymentStats(completion_status); + + RecordUrlKeyedMetrics(completion_status); } void JourneyLogger::RecordSectionSpecificStats( @@ -199,4 +220,18 @@ COMPLETION_STATUS_MAX); } +void JourneyLogger::RecordUrlKeyedMetrics(CompletionStatus completion_status) { + if (!autofill::IsUkmLoggingEnabled() || !ukm_service_ || !url_.is_valid()) + return; + + // Record the Checkout Funnel UKM. + int32_t source_id = ukm_service_->GetNewSourceID(); + ukm_service_->UpdateSourceURL(source_id, url_); + std::unique_ptr<ukm::UkmEntryBuilder> builder = ukm_service_->GetEntryBuilder( + source_id, internal::kUKMCheckoutEventsEntryName); + builder->AddMetric(internal::kUKMCompletionStatusMetricName, + completion_status); + builder->AddMetric(internal::kUKMEventsMetricName, events_); +} + } // namespace payments
diff --git a/components/payments/core/journey_logger.h b/components/payments/core/journey_logger.h index 67401c1..85c850e 100644 --- a/components/payments/core/journey_logger.h +++ b/components/payments/core/journey_logger.h
@@ -8,9 +8,21 @@ #include <string> #include "base/macros.h" +#include "url/gurl.h" + +namespace ukm { +class UkmService; +} namespace payments { +namespace internal { +// Name constants are exposed here so they can be referenced from tests. +extern const char kUKMCheckoutEventsEntryName[]; +extern const char kUKMCompletionStatusMetricName[]; +extern const char kUKMEventsMetricName[]; +} // namespace internal + // A class to keep track of different stats during a Payment Request journey. It // collects different metrics during the course of the checkout flow, like the // number of credit cards that the user added or edited. The metrics will be @@ -46,6 +58,16 @@ COMPLETION_STATUS_MAX, }; + // Used to record the different events that happened during the Payment + // Request. + enum Event { + EVENT_INITIATED = 0, + EVENT_SHOWN = 1 << 0, + EVENT_PAY_CLICKED = 1 << 1, + EVENT_RECEIVED_INSTRUMENT_DETAILS = 1 << 2, + EVENT_MAX = 8, + }; + // Used to mesure the impact of the CanMakePayment return value on whether the // Payment Request is shown to the user. static const int CMP_SHOW_COULD_NOT_MAKE_PAYMENT_AND_DID_NOT_SHOW = 0; @@ -53,7 +75,9 @@ static const int CMP_SHOW_COULD_MAKE_PAYMENT = 1 << 1; static const int CMP_SHOW_MAX = 4; - explicit JourneyLogger(bool is_incognito); + JourneyLogger(bool is_incognito, + const GURL& url, + ukm::UkmService* ukm_service); ~JourneyLogger(); // Increments the number of selection adds for the specified section. @@ -75,6 +99,9 @@ // Records the fact that the Payment Request was shown to the user. void SetShowCalled(); + // Records that an event occurred. + void SetEventOccurred(Event event); + // Records the histograms for all the sections that were requested by the // merchant and for the usage of the CanMakePayment method and its effect on // the transaction. This method should be called when the Payment Request has @@ -125,12 +152,23 @@ void RecordCanMakePaymentEffectOnCompletion( CompletionStatus completion_status); + // Records the Payment Request Url Keyed Metrics. + void RecordUrlKeyedMetrics(CompletionStatus completion_status); + SectionStats sections_[NUMBER_OF_SECTIONS]; bool was_can_make_payments_used_; bool could_make_payment_; bool was_show_called_; bool is_incognito_; + // Accumulates the many events that have happened during the Payment Request. + int events_; + + const GURL url_; + + // Not owned, will outlive this object. + ukm::UkmService* ukm_service_; + DISALLOW_COPY_AND_ASSIGN(JourneyLogger); };
diff --git a/components/payments/core/journey_logger_unittest.cc b/components/payments/core/journey_logger_unittest.cc index 75372e9..fbb1efd 100644 --- a/components/payments/core/journey_logger_unittest.cc +++ b/components/payments/core/journey_logger_unittest.cc
@@ -4,7 +4,14 @@ #include "components/payments/core/journey_logger.h" +#include "base/metrics/metrics_hashes.h" #include "base/test/histogram_tester.h" +#include "base/test/scoped_feature_list.h" +#include "components/autofill/core/browser/autofill_experiments.h" +#include "components/metrics/proto/ukm/entry.pb.h" +#include "components/ukm/test_ukm_service.h" +#include "components/ukm/ukm_entry.h" +#include "components/ukm/ukm_source.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" @@ -12,12 +19,26 @@ namespace payments { +namespace { +// Finds the specified UKM metric by |name| in the specified UKM |metrics|. +const ukm::Entry_Metric* FindMetric( + const char* name, + const google::protobuf::RepeatedPtrField<ukm::Entry_Metric>& metrics) { + for (const auto& metric : metrics) { + if (metric.metric_hash() == base::HashMetricName(name)) + return &metric; + } + return nullptr; +} +} // namespace + // Tests the canMakePayment stats for the case where the merchant does not use // it and does not show the PaymentRequest to the user. TEST(JourneyLoggerTest, RecordJourneyStatsHistograms_CanMakePaymentNotCalled_NoShow) { base::HistogramTester histogram_tester; - JourneyLogger logger(/*is_incognito=*/false); + JourneyLogger logger(/*is_incognito=*/false, /*url=*/GURL(""), + /*ukm_service=*/nullptr); logger.RecordJourneyStatsHistograms( JourneyLogger::COMPLETION_STATUS_COMPLETED); @@ -38,7 +59,8 @@ TEST(JourneyLoggerTest, RecordJourneyStatsHistograms_CanMakePaymentNotCalled_ShowAndUserAbort) { base::HistogramTester histogram_tester; - JourneyLogger logger(/*is_incognito=*/false); + JourneyLogger logger(/*is_incognito=*/false, /*url=*/GURL(""), + /*ukm_service=*/nullptr); // Expect no log for CanMakePayment. EXPECT_THAT( @@ -67,7 +89,8 @@ TEST(JourneyLoggerTest, RecordJourneyStatsHistograms_CanMakePaymentNotCalled_ShowAndOtherAbort) { base::HistogramTester histogram_tester; - JourneyLogger logger(/*is_incognito=*/false); + JourneyLogger logger(/*is_incognito=*/false, /*url=*/GURL(""), + /*ukm_service=*/nullptr); // Expect no log for CanMakePayment. EXPECT_THAT( @@ -96,7 +119,8 @@ TEST(JourneyLoggerTest, RecordJourneyStatsHistograms_CanMakePaymentNotCalled_ShowAndComplete) { base::HistogramTester histogram_tester; - JourneyLogger logger(/*is_incognito=*/false); + JourneyLogger logger(/*is_incognito=*/false, /*url=*/GURL(""), + /*ukm_service=*/nullptr); // Expect no log for CanMakePayment. EXPECT_THAT( @@ -125,7 +149,8 @@ TEST(JourneyLoggerTest, RecordJourneyStatsHistograms_CanMakePaymentCalled_FalseAndNoShow) { base::HistogramTester histogram_tester; - JourneyLogger logger(/*is_incognito=*/false); + JourneyLogger logger(/*is_incognito=*/false, /*url=*/GURL(""), + /*ukm_service=*/nullptr); // Expect no log for CanMakePayment. EXPECT_THAT( @@ -158,7 +183,8 @@ TEST(JourneyLoggerTest, RecordJourneyStatsHistograms_CanMakePaymentCalled_TrueAndNoShow) { base::HistogramTester histogram_tester; - JourneyLogger logger(/*is_incognito=*/false); + JourneyLogger logger(/*is_incognito=*/false, /*url=*/GURL(""), + /*ukm_service=*/nullptr); // Expect no log for CanMakePayment. EXPECT_THAT( @@ -191,7 +217,8 @@ TEST(JourneyLoggerTest, RecordJourneyStatsHistograms_CanMakePaymentCalled_FalseShowAndUserAbort) { base::HistogramTester histogram_tester; - JourneyLogger logger(/*is_incognito=*/false); + JourneyLogger logger(/*is_incognito=*/false, /*url=*/GURL(""), + /*ukm_service=*/nullptr); // Expect no log for CanMakePayment. EXPECT_THAT( @@ -224,7 +251,8 @@ TEST(JourneyLoggerTest, RecordJourneyStatsHistograms_CanMakePaymentCalled_FalseShowAndOtherAbort) { base::HistogramTester histogram_tester; - JourneyLogger logger(/*is_incognito=*/false); + JourneyLogger logger(/*is_incognito=*/false, /*url=*/GURL(""), + /*ukm_service=*/nullptr); // Expect no log for CanMakePayment. EXPECT_THAT( @@ -257,7 +285,8 @@ TEST(JourneyLoggerTest, RecordJourneyStatsHistograms_CanMakePaymentCalled_FalseShowAndComplete) { base::HistogramTester histogram_tester; - JourneyLogger logger(/*is_incognito=*/false); + JourneyLogger logger(/*is_incognito=*/false, /*url=*/GURL(""), + /*ukm_service=*/nullptr); // Expect no log for CanMakePayment. EXPECT_THAT( @@ -291,7 +320,8 @@ TEST(JourneyLoggerTest, RecordJourneyStatsHistograms_CanMakePaymentCalled_TrueShowAndUserAbort) { base::HistogramTester histogram_tester; - JourneyLogger logger(/*is_incognito=*/false); + JourneyLogger logger(/*is_incognito=*/false, /*url=*/GURL(""), + /*ukm_service=*/nullptr); // Expect no log for CanMakePayment. EXPECT_THAT( @@ -326,7 +356,8 @@ TEST(JourneyLoggerTest, RecordJourneyStatsHistograms_CanMakePaymentCalled_TrueShowAndOtherAbort) { base::HistogramTester histogram_tester; - JourneyLogger logger(/*is_incognito=*/false); + JourneyLogger logger(/*is_incognito=*/false, /*url=*/GURL(""), + /*ukm_service=*/nullptr); // Expect no log for CanMakePayment. EXPECT_THAT( @@ -361,7 +392,8 @@ TEST(JourneyLoggerTest, RecordJourneyStatsHistograms_CanMakePaymentCalled_TrueShowAndComplete) { base::HistogramTester histogram_tester; - JourneyLogger logger(/*is_incognito=*/false); + JourneyLogger logger(/*is_incognito=*/false, /*url=*/GURL(""), + /*ukm_service=*/nullptr); // Expect no log for CanMakePayment. EXPECT_THAT( @@ -396,7 +428,8 @@ TEST(JourneyLoggerTest, RecordJourneyStatsHistograms_CanMakePayment_IncognitoTab) { base::HistogramTester histogram_tester; - JourneyLogger logger(/*is_incognito=*/true); + JourneyLogger logger(/*is_incognito=*/true, /*url=*/GURL(""), + /*ukm_service=*/nullptr); // Expect no log for CanMakePayment. EXPECT_THAT( @@ -420,7 +453,8 @@ TEST(JourneyLoggerTest, RecordJourneyStatsHistograms_SuggestionsForEverything_Completed) { base::HistogramTester histogram_tester; - JourneyLogger logger(/*is_incognito=*/false); + JourneyLogger logger(/*is_incognito=*/false, /*url=*/GURL(""), + /*ukm_service=*/nullptr); // Simulate that the user had suggestions for all the requested sections. logger.SetNumberOfSuggestionsShown(JourneyLogger::SECTION_CREDIT_CARDS, 1); @@ -444,7 +478,8 @@ TEST(JourneyLoggerTest, RecordJourneyStatsHistograms_SuggestionsForEverything_UserAborted) { base::HistogramTester histogram_tester; - JourneyLogger logger(/*is_incognito=*/false); + JourneyLogger logger(/*is_incognito=*/false, /*url=*/GURL(""), + /*ukm_service=*/nullptr); // Simulate that the user had suggestions for all the requested sections. logger.SetNumberOfSuggestionsShown(JourneyLogger::SECTION_CREDIT_CARDS, 1); @@ -468,7 +503,8 @@ TEST(JourneyLoggerTest, RecordJourneyStatsHistograms_SuggestionsForEverything_OtherAborted) { base::HistogramTester histogram_tester; - JourneyLogger logger(/*is_incognito=*/false); + JourneyLogger logger(/*is_incognito=*/false, /*url=*/GURL(""), + /*ukm_service=*/nullptr); // Simulate that the user had suggestions for all the requested sections. logger.SetNumberOfSuggestionsShown(JourneyLogger::SECTION_CREDIT_CARDS, 1); @@ -493,7 +529,8 @@ TEST(JourneyLoggerTest, RecordJourneyStatsHistograms_SuggestionsForEverything_Incognito) { base::HistogramTester histogram_tester; - JourneyLogger logger(/*is_incognito=*/true); + JourneyLogger logger(/*is_incognito=*/true, /*url=*/GURL(""), + /*ukm_service=*/nullptr); // Simulate that the user had suggestions for all the requested sections. logger.SetNumberOfSuggestionsShown(JourneyLogger::SECTION_CREDIT_CARDS, 1); @@ -517,7 +554,8 @@ TEST(JourneyLoggerTest, RecordJourneyStatsHistograms_NoSuggestionsForEverything_Completed) { base::HistogramTester histogram_tester; - JourneyLogger logger(/*is_incognito=*/false); + JourneyLogger logger(/*is_incognito=*/false, /*url=*/GURL(""), + /*ukm_service=*/nullptr); // Simulate that the user had suggestions for all the requested sections. logger.SetNumberOfSuggestionsShown(JourneyLogger::SECTION_CREDIT_CARDS, 0); @@ -542,7 +580,8 @@ TEST(JourneyLoggerTest, RecordJourneyStatsHistograms_NoSuggestionsForEverything_UserAborted) { base::HistogramTester histogram_tester; - JourneyLogger logger(/*is_incognito=*/false); + JourneyLogger logger(/*is_incognito=*/false, /*url=*/GURL(""), + /*ukm_service=*/nullptr); // Simulate that the user had suggestions for all the requested sections. logger.SetNumberOfSuggestionsShown(JourneyLogger::SECTION_CREDIT_CARDS, 0); @@ -567,7 +606,8 @@ TEST(JourneyLoggerTest, RecordJourneyStatsHistograms_NoSuggestionsForEverything_OtherAborted) { base::HistogramTester histogram_tester; - JourneyLogger logger(/*is_incognito=*/false); + JourneyLogger logger(/*is_incognito=*/false, /*url=*/GURL(""), + /*ukm_service=*/nullptr); // Simulate that the user had suggestions for all the requested sections. logger.SetNumberOfSuggestionsShown(JourneyLogger::SECTION_CREDIT_CARDS, 0); @@ -593,7 +633,8 @@ TEST(JourneyLoggerTest, RecordJourneyStatsHistograms_NoSuggestionsForEverything_Incognito) { base::HistogramTester histogram_tester; - JourneyLogger logger(/*is_incognito=*/true); + JourneyLogger logger(/*is_incognito=*/true, /*url=*/GURL(""), + /*ukm_service=*/nullptr); // Simulate that the user had suggestions for all the requested sections. logger.SetNumberOfSuggestionsShown(JourneyLogger::SECTION_CREDIT_CARDS, 0); @@ -617,8 +658,10 @@ // Requests. TEST(JourneyLoggerTest, RecordJourneyStatsHistograms_TwoPaymentRequests) { base::HistogramTester histogram_tester; - JourneyLogger logger1(/*is_incognito=*/false); - JourneyLogger logger2(/*is_incognito=*/false); + JourneyLogger logger1(/*is_incognito=*/false, /*url=*/GURL(""), + /*ukm_service=*/nullptr); + JourneyLogger logger2(/*is_incognito=*/false, /*url=*/GURL(""), + /*ukm_service=*/nullptr); // Make the two loggers have different data. logger1.SetShowCalled(); @@ -658,4 +701,53 @@ JourneyLogger::COMPLETION_STATUS_USER_ABORTED, 1); } +// Tests that the Payment Request UKMs are logged correctly. +TEST(JourneyLoggerTest, RecordJourneyStatsHistograms_CheckoutFunnelUkm) { + base::test::ScopedFeatureList scoped_feature_list_; + scoped_feature_list_.InitAndEnableFeature(autofill::kAutofillUkmLogging); + + ukm::UkmServiceTestingHarness ukm_service_test_harness; + ukm::TestUkmService* ukm_service = + ukm_service_test_harness.test_ukm_service(); + char test_url[] = "http://www.google.com/"; + + base::HistogramTester histogram_tester; + JourneyLogger logger(/*is_incognito=*/true, /*url=*/GURL(test_url), + /*ukm_service=*/ukm_service); + + // Simulate that the user aborts after being shown the Payment Request and + // clicking pay. + logger.SetEventOccurred(JourneyLogger::EVENT_SHOWN); + logger.SetEventOccurred(JourneyLogger::EVENT_PAY_CLICKED); + logger.RecordJourneyStatsHistograms( + JourneyLogger::COMPLETION_STATUS_USER_ABORTED); + + // Make sure the UKM was logged correctly. + ASSERT_EQ(1U, ukm_service->sources_count()); + const ukm::UkmSource* source = ukm_service->GetSourceForUrl(test_url); + ASSERT_NE(nullptr, source); + + ASSERT_EQ(1U, ukm_service->entries_count()); + const ukm::UkmEntry* entry = ukm_service->GetEntry(0); + EXPECT_EQ(source->id(), entry->source_id()); + + ukm::Entry entry_proto; + entry->PopulateProto(&entry_proto); + EXPECT_EQ(source->id(), entry_proto.source_id()); + EXPECT_EQ(base::HashMetricName(internal::kUKMCheckoutEventsEntryName), + entry_proto.event_hash()); + + const ukm::Entry_Metric* status_metric = FindMetric( + internal::kUKMCompletionStatusMetricName, entry_proto.metrics()); + ASSERT_NE(nullptr, status_metric); + EXPECT_EQ(JourneyLogger::COMPLETION_STATUS_USER_ABORTED, + status_metric->value()); + + const ukm::Entry_Metric* step_metric = + FindMetric(internal::kUKMEventsMetricName, entry_proto.metrics()); + ASSERT_NE(nullptr, step_metric); + EXPECT_EQ(JourneyLogger::EVENT_SHOWN | JourneyLogger::EVENT_PAY_CLICKED, + step_metric->value()); +} + } // namespace payments \ No newline at end of file
diff --git a/components/spellcheck/renderer/spellcheck.cc b/components/spellcheck/renderer/spellcheck.cc index 697e0ed..cd1a397 100644 --- a/components/spellcheck/renderer/spellcheck.cc +++ b/components/spellcheck/renderer/spellcheck.cc
@@ -26,6 +26,8 @@ #include "components/spellcheck/renderer/spellcheck_language.h" #include "components/spellcheck/renderer/spellcheck_provider.h" #include "components/spellcheck/spellcheck_build_features.h" +#include "content/public/renderer/render_frame.h" +#include "content/public/renderer/render_frame_visitor.h" #include "content/public/renderer/render_thread.h" #include "content/public/renderer/render_view.h" #include "content/public/renderer/render_view_visitor.h" @@ -46,18 +48,18 @@ const int kNoOffset = 0; const int kNoTag = 0; -class UpdateSpellcheckEnabled : public content::RenderViewVisitor { +class UpdateSpellcheckEnabled : public content::RenderFrameVisitor { public: explicit UpdateSpellcheckEnabled(bool enabled) : enabled_(enabled) {} - bool Visit(content::RenderView* render_view) override; + bool Visit(content::RenderFrame* render_frame) override; private: bool enabled_; // New spellcheck-enabled state. DISALLOW_COPY_AND_ASSIGN(UpdateSpellcheckEnabled); }; -bool UpdateSpellcheckEnabled::Visit(content::RenderView* render_view) { - SpellCheckProvider* provider = SpellCheckProvider::Get(render_view); +bool UpdateSpellcheckEnabled::Visit(content::RenderFrame* render_frame) { + SpellCheckProvider* provider = SpellCheckProvider::Get(render_frame); DCHECK(provider); provider->EnableSpellcheck(enabled_); return true; @@ -224,7 +226,7 @@ void SpellCheck::OnEnableSpellCheck(bool enable) { spellcheck_enabled_ = enable; UpdateSpellcheckEnabled updater(enable); - content::RenderView::ForEach(&updater); + content::RenderFrame::ForEach(&updater); } // TODO(groby): Make sure we always have a spelling engine, even before
diff --git a/components/spellcheck/renderer/spellcheck_provider.cc b/components/spellcheck/renderer/spellcheck_provider.cc index 964e1d7..abd2cd5 100644 --- a/components/spellcheck/renderer/spellcheck_provider.cc +++ b/components/spellcheck/renderer/spellcheck_provider.cc
@@ -11,7 +11,6 @@ #include "components/spellcheck/renderer/spellcheck_language.h" #include "components/spellcheck/spellcheck_build_features.h" #include "content/public/renderer/render_frame.h" -#include "content/public/renderer/render_view.h" #include "third_party/WebKit/public/platform/WebVector.h" #include "third_party/WebKit/public/web/WebDocument.h" #include "third_party/WebKit/public/web/WebElement.h" @@ -19,7 +18,6 @@ #include "third_party/WebKit/public/web/WebTextCheckingCompletion.h" #include "third_party/WebKit/public/web/WebTextCheckingResult.h" #include "third_party/WebKit/public/web/WebTextDecorationType.h" -#include "third_party/WebKit/public/web/WebView.h" using blink::WebElement; using blink::WebLocalFrame; @@ -36,16 +34,14 @@ int(SpellCheckResult::GRAMMAR), "mismatching enums"); -SpellCheckProvider::SpellCheckProvider( - content::RenderView* render_view, - SpellCheck* spellcheck) - : content::RenderViewObserver(render_view), - content::RenderViewObserverTracker<SpellCheckProvider>(render_view), +SpellCheckProvider::SpellCheckProvider(content::RenderFrame* render_frame, + SpellCheck* spellcheck) + : content::RenderFrameObserver(render_frame), + content::RenderFrameObserverTracker<SpellCheckProvider>(render_frame), spellcheck_(spellcheck) { DCHECK(spellcheck_); - if (render_view) { // NULL in unit tests. - EnableSpellcheck(spellcheck_->IsSpellcheckEnabled()); - } + if (render_frame) // NULL in unit tests. + render_frame->GetWebFrame()->SetTextCheckClient(this); } SpellCheckProvider::~SpellCheckProvider() { @@ -100,7 +96,7 @@ void SpellCheckProvider::FocusedNodeChanged(const blink::WebNode& unused) { #if BUILDFLAG(USE_BROWSER_SPELLCHECKER) - WebLocalFrame* frame = render_view()->GetWebView()->FocusedFrame(); + WebLocalFrame* frame = render_frame()->GetWebFrame(); WebElement element = frame->GetDocument().IsNull() ? WebElement() : frame->GetDocument().FocusedElement(); @@ -228,15 +224,7 @@ #endif void SpellCheckProvider::EnableSpellcheck(bool enable) { - if (!render_view()->GetWebView()) - return; - - WebLocalFrame* frame = render_view()->GetWebView()->FocusedFrame(); - // TODO(yabinh): The null check should be unnecessary. - // See crbug.com/625068 - if (!frame) - return; - + WebLocalFrame* frame = render_frame()->GetWebFrame(); frame->EnableSpellChecking(enable); if (!enable) frame->RemoveSpellingMarkers();
diff --git a/components/spellcheck/renderer/spellcheck_provider.h b/components/spellcheck/renderer/spellcheck_provider.h index 4503852..cead107 100644 --- a/components/spellcheck/renderer/spellcheck_provider.h +++ b/components/spellcheck/renderer/spellcheck_provider.h
@@ -13,8 +13,8 @@ #include "base/id_map.h" #include "base/macros.h" #include "components/spellcheck/spellcheck_build_features.h" -#include "content/public/renderer/render_view_observer.h" -#include "content/public/renderer/render_view_observer_tracker.h" +#include "content/public/renderer/render_frame_observer.h" +#include "content/public/renderer/render_frame_observer_tracker.h" #include "third_party/WebKit/public/web/WebTextCheckClient.h" class SpellCheck; @@ -25,17 +25,16 @@ struct WebTextCheckingResult; } -// TODO(xiaochengh): Make SpellCheckProvider a RenderFrameObserver. // This class deals with invoking browser-side spellcheck mechanism // which is done asynchronously. class SpellCheckProvider - : public content::RenderViewObserver, - public content::RenderViewObserverTracker<SpellCheckProvider>, + : public content::RenderFrameObserver, + public content::RenderFrameObserverTracker<SpellCheckProvider>, public blink::WebTextCheckClient { public: using WebTextCheckCompletions = IDMap<blink::WebTextCheckingCompletion*>; - SpellCheckProvider(content::RenderView* render_view, + SpellCheckProvider(content::RenderFrame* render_frame, SpellCheck* spellcheck); ~SpellCheckProvider() override; @@ -57,7 +56,7 @@ // Enables document-wide spellchecking. void EnableSpellcheck(bool enabled); - // RenderViewObserver implementation. + // RenderFrameObserver implementation. bool OnMessageReceived(const IPC::Message& message) override; void FocusedNodeChanged(const blink::WebNode& node) override; @@ -70,7 +69,7 @@ bool SatisfyRequestFromCache(const base::string16& text, blink::WebTextCheckingCompletion* completion); - // RenderViewObserver implementation. + // RenderFrameObserver implementation. void OnDestruct() override; // blink::WebTextCheckClient implementation.
diff --git a/components/sync/device_info/device_info_sync_service.cc b/components/sync/device_info/device_info_sync_service.cc index 3bad31fd..f6f2398 100644 --- a/components/sync/device_info/device_info_sync_service.cc +++ b/components/sync/device_info/device_info_sync_service.cc
@@ -285,12 +285,18 @@ const DeviceInfo* device_info = local_device_info_provider_->GetLocalDeviceInfo(); - const SyncData& data = CreateLocalData(device_info); - StoreSyncData(device_info->guid(), data); - SyncChangeList change_list; - change_list.push_back(SyncChange(FROM_HERE, change_type, data)); - sync_processor_->ProcessSyncChanges(FROM_HERE, change_list); + // While the |pulse_timer_| is shutdown eventually in StopSyncing(), our + // device info provider is ripped out from underneath us before that happens, + // and we need to guard against this. + if (device_info != nullptr) { + const SyncData& data = CreateLocalData(device_info); + StoreSyncData(device_info->guid(), data); + + SyncChangeList change_list; + change_list.push_back(SyncChange(FROM_HERE, change_type, data)); + sync_processor_->ProcessSyncChanges(FROM_HERE, change_list); + } pulse_timer_.Start( FROM_HERE, DeviceInfoUtil::kPulseInterval,
diff --git a/components/translate/core/browser/BUILD.gn b/components/translate/core/browser/BUILD.gn index 30bb6fb..1e56c7e 100644 --- a/components/translate/core/browser/BUILD.gn +++ b/components/translate/core/browser/BUILD.gn
@@ -62,6 +62,7 @@ "//components/strings", "//components/translate/core/browser/proto", "//components/translate/core/common", + "//components/ukm", "//components/variations", "//google_apis", "//net", @@ -116,6 +117,8 @@ "//components/sync_preferences:test_support", "//components/translate/core/browser/proto", "//components/translate/core/common", + "//components/ukm", + "//components/ukm:test_support", "//components/variations", "//net:test_support", "//testing/gtest",
diff --git a/components/translate/core/browser/DEPS b/components/translate/core/browser/DEPS index d7adaf63..5b24a63 100644 --- a/components/translate/core/browser/DEPS +++ b/components/translate/core/browser/DEPS
@@ -1,4 +1,5 @@ include_rules = [ "+components/keyed_service/core", "+components/metrics", + "+components/ukm", ]
diff --git a/components/translate/core/browser/mock_translate_ranker.cc b/components/translate/core/browser/mock_translate_ranker.cc index 252c88f..2c9418f8 100644 --- a/components/translate/core/browser/mock_translate_ranker.cc +++ b/components/translate/core/browser/mock_translate_ranker.cc
@@ -5,6 +5,7 @@ #include "components/translate/core/browser/mock_translate_ranker.h" #include "components/metrics/proto/translate_event.pb.h" +#include "url/gurl.h" namespace translate { namespace testing { @@ -37,7 +38,8 @@ } void MockTranslateRanker::AddTranslateEvent( - const metrics::TranslateEventProto& translate_event) { + const metrics::TranslateEventProto& translate_event, + const GURL& /* url */) { event_cache_.push_back(translate_event); }
diff --git a/components/translate/core/browser/mock_translate_ranker.h b/components/translate/core/browser/mock_translate_ranker.h index 218cc2c..ea71eb8e 100644 --- a/components/translate/core/browser/mock_translate_ranker.h +++ b/components/translate/core/browser/mock_translate_ranker.h
@@ -11,6 +11,8 @@ #include "components/translate/core/browser/translate_ranker.h" +class GURL; + namespace metrics { class TranslateEventProto; } @@ -42,8 +44,8 @@ bool ShouldOfferTranslation(const TranslatePrefs& translate_prefs, const std::string& src_lang, const std::string& dst_lang) override; - void AddTranslateEvent( - const metrics::TranslateEventProto& translate_event) override; + void AddTranslateEvent(const metrics::TranslateEventProto& translate_event, + const GURL& url) override; void FlushTranslateEvents( std::vector<metrics::TranslateEventProto>* events) override;
diff --git a/components/translate/core/browser/translate_manager.cc b/components/translate/core/browser/translate_manager.cc index 114a93fb..0f2e8e4 100644 --- a/components/translate/core/browser/translate_manager.cc +++ b/components/translate/core/browser/translate_manager.cc
@@ -606,7 +606,8 @@ static_cast<metrics::TranslateEventProto::EventType>(event_type)); translate_event_->set_event_timestamp_sec( (base::TimeTicks::Now() - base::TimeTicks()).InSeconds()); - translate_ranker_->AddTranslateEvent(*translate_event_); + translate_ranker_->AddTranslateEvent(*translate_event_, + translate_driver_->GetVisibleURL()); } } // namespace translate
diff --git a/components/translate/core/browser/translate_ranker.h b/components/translate/core/browser/translate_ranker.h index 0be5f5f..b10c303a 100644 --- a/components/translate/core/browser/translate_ranker.h +++ b/components/translate/core/browser/translate_ranker.h
@@ -12,6 +12,8 @@ #include "base/macros.h" #include "components/keyed_service/core/keyed_service.h" +class GURL; + namespace metrics { class TranslateEventProto; } // namespace metrics @@ -49,7 +51,8 @@ // Caches the translate event. virtual void AddTranslateEvent( - const metrics::TranslateEventProto& translate_event) = 0; + const metrics::TranslateEventProto& translate_event, + const GURL& url) = 0; // Transfers cached translate events to the given vector pointer and clears // the cache.
diff --git a/components/translate/core/browser/translate_ranker_impl.cc b/components/translate/core/browser/translate_ranker_impl.cc index 04abc20..7be53a8 100644 --- a/components/translate/core/browser/translate_ranker_impl.cc +++ b/components/translate/core/browser/translate_ranker_impl.cc
@@ -13,6 +13,7 @@ #include "base/files/file_util.h" #include "base/memory/ptr_util.h" #include "base/metrics/histogram_macros.h" +#include "base/metrics/metrics_hashes.h" #include "base/profiler/scoped_tracker.h" #include "base/strings/string_number_conversions.h" #include "base/strings/string_util.h" @@ -26,6 +27,8 @@ #include "components/translate/core/browser/translate_prefs.h" #include "components/translate/core/browser/translate_url_fetcher.h" #include "components/translate/core/common/translate_switches.h" +#include "components/ukm/ukm_entry_builder.h" +#include "components/ukm/ukm_service.h" #include "components/variations/variations_associated_data.h" #include "url/gurl.h" @@ -132,8 +135,10 @@ } TranslateRankerImpl::TranslateRankerImpl(const base::FilePath& model_path, - const GURL& model_url) - : is_logging_enabled_( + const GURL& model_url, + ukm::UkmService* ukm_service) + : ukm_service_(ukm_service), + is_logging_enabled_( base::FeatureList::IsEnabled(kTranslateRankerLogging)), is_query_enabled_(base::FeatureList::IsEnabled(kTranslateRankerQuery)), is_enforcement_enabled_( @@ -274,11 +279,43 @@ event_cache_.clear(); } +void TranslateRankerImpl::SendEventToUKM( + const metrics::TranslateEventProto& event, + const GURL& url) { + if (!ukm_service_) { + DVLOG(3) << "No UKM service."; + return; + } + DVLOG(3) << "Sending event for url: " << url.spec(); + int32_t source_id = ukm_service_->GetNewSourceID(); + ukm_service_->UpdateSourceURL(source_id, url); + std::unique_ptr<ukm::UkmEntryBuilder> builder = + ukm_service_->GetEntryBuilder(source_id, "Translate"); + // The metrics added here should be kept in sync with the documented + // metrics in tools/metrics/ukm/ukm.xml. + // TODO(hamelphi): Remove hashing functions once UKM accepts strings metrics. + builder->AddMetric("SourceLanguage", + base::HashMetricName(event.source_language())); + builder->AddMetric("TargetLanguage", + base::HashMetricName(event.target_language())); + builder->AddMetric("Country", base::HashMetricName(event.country())); + builder->AddMetric("AcceptCount", event.accept_count()); + builder->AddMetric("DeclineCount", event.decline_count()); + builder->AddMetric("IgnoreCount", event.ignore_count()); + builder->AddMetric("RankerVersion", event.ranker_version()); + builder->AddMetric("RankerResponse", event.ranker_response()); + builder->AddMetric("EventType", event.event_type()); +} + void TranslateRankerImpl::AddTranslateEvent( - const metrics::TranslateEventProto& event) { + const metrics::TranslateEventProto& event, + const GURL& url) { DCHECK(sequence_checker_.CalledOnValidSequence()); if (IsLoggingEnabled()) { DVLOG(3) << "Adding translate ranker event."; + if (url.is_valid()) { + SendEventToUKM(event, url); + } event_cache_.push_back(event); } }
diff --git a/components/translate/core/browser/translate_ranker_impl.h b/components/translate/core/browser/translate_ranker_impl.h index f233633..f9d71ab 100644 --- a/components/translate/core/browser/translate_ranker_impl.h +++ b/components/translate/core/browser/translate_ranker_impl.h
@@ -18,10 +18,16 @@ #include "components/translate/core/browser/translate_ranker.h" #include "url/gurl.h" +class GURL; + namespace chrome_intelligence { class RankerModel; } // namespace chrome_intelligence +namespace ukm { +class UkmService; +} // namespace ukm + namespace metrics { class TranslateEventProto; } // namespace metrics @@ -76,7 +82,9 @@ // whether the user should be given a translation prompt or not. class TranslateRankerImpl : public TranslateRanker { public: - TranslateRankerImpl(const base::FilePath& model_path, const GURL& model_url); + TranslateRankerImpl(const base::FilePath& model_path, + const GURL& model_url, + ukm::UkmService* ukm_service); ~TranslateRankerImpl() override; // Get the file path of the translate ranker model, by default with a fixed @@ -98,8 +106,8 @@ bool ShouldOfferTranslation(const TranslatePrefs& translate_prefs, const std::string& src_lang, const std::string& dst_lang) override; - void AddTranslateEvent( - const metrics::TranslateEventProto& translate_event) override; + void AddTranslateEvent(const metrics::TranslateEventProto& translate_event, + const GURL& url) override; void FlushTranslateEvents( std::vector<metrics::TranslateEventProto>* events) override; @@ -114,6 +122,12 @@ bool CheckModelLoaderForTesting(); private: + void SendEventToUKM(const metrics::TranslateEventProto& translate_event, + const GURL& url); + + // Used to log URL-keyed metrics. This pointer will outlive |this|. + ukm::UkmService* ukm_service_; + // Used to sanity check the threading of this ranker. base::SequenceChecker sequence_checker_;
diff --git a/components/translate/core/browser/translate_ranker_impl_unittest.cc b/components/translate/core/browser/translate_ranker_impl_unittest.cc index b4c2dcfe..a1fea536 100644 --- a/components/translate/core/browser/translate_ranker_impl_unittest.cc +++ b/components/translate/core/browser/translate_ranker_impl_unittest.cc
@@ -16,6 +16,7 @@ #include "base/test/scoped_feature_list.h" #include "base/test/scoped_task_scheduler.h" #include "components/metrics/proto/translate_event.pb.h" +#include "components/metrics/proto/ukm/source.pb.h" #include "components/prefs/scoped_user_pref_update.h" #include "components/sync_preferences/testing_pref_service_syncable.h" #include "components/translate/core/browser/proto/ranker_model.pb.h" @@ -23,9 +24,12 @@ #include "components/translate/core/browser/ranker_model.h" #include "components/translate/core/browser/translate_download_manager.h" #include "components/translate/core/browser/translate_prefs.h" +#include "components/ukm/test_ukm_service.h" +#include "components/ukm/ukm_source.h" #include "net/url_request/test_url_fetcher_factory.h" #include "net/url_request/url_request_test_util.h" #include "testing/gtest/include/gtest/gtest.h" +#include "url/gurl.h" namespace { @@ -72,7 +76,13 @@ std::unique_ptr<sync_preferences::TestingPrefServiceSyncable> prefs_; std::unique_ptr<translate::TranslatePrefs> translate_prefs_; + ukm::TestUkmService* GetTestUkmService() { + return ukm_service_test_harness_.test_ukm_service(); + } + private: + ukm::UkmServiceTestingHarness ukm_service_test_harness_; + // Override the default URL fetcher to return custom responses for tests. net::TestURLFetcherFactory url_fetcher_factory_; @@ -165,7 +175,8 @@ locale_weight["en-ca"] = 0.11f; locale_weight["zh-cn"] = 0.12f; // Normalized to lowercase. - auto impl = base::MakeUnique<TranslateRankerImpl>(base::FilePath(), GURL()); + auto impl = base::MakeUnique<TranslateRankerImpl>(base::FilePath(), GURL(), + GetTestUkmService()); impl->OnModelAvailable(std::move(model)); base::RunLoop().RunUntilIdle(); return impl; @@ -311,13 +322,16 @@ std::unique_ptr<translate::TranslateRanker> ranker = GetRankerForTest(0.0f); 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->AddTranslateEvent(CreateTranslateEvent("fr", "en", 1, 0, 3)); - ranker->AddTranslateEvent(CreateTranslateEvent("jp", "en", 2, 0, 3)); - ranker->AddTranslateEvent(CreateTranslateEvent("es", "de", 4, 5, 6)); + ranker->AddTranslateEvent(CreateTranslateEvent("fr", "en", 1, 0, 3), url0); + ranker->AddTranslateEvent(CreateTranslateEvent("jp", "en", 2, 0, 3), GURL()); + ranker->AddTranslateEvent(CreateTranslateEvent("es", "de", 4, 5, 6), url1); // Capture the data and verify that it is as expected. ranker->FlushTranslateEvents(&flushed_events); @@ -329,6 +343,14 @@ // Check that the cache has been cleared. ranker->FlushTranslateEvents(&flushed_events); EXPECT_EQ(0U, flushed_events.size()); + + ASSERT_EQ(2U, GetTestUkmService()->sources_count()); + EXPECT_EQ( + url0.spec(), + GetTestUkmService()->GetSourceForUrl(url0.spec().c_str())->url().spec()); + EXPECT_EQ( + url1.spec(), + GetTestUkmService()->GetSourceForUrl(url1.spec().c_str())->url().spec()); } TEST_F(TranslateRankerImplTest, LoggingDisabled) { @@ -339,13 +361,14 @@ ranker->FlushTranslateEvents(&flushed_events); EXPECT_EQ(0U, flushed_events.size()); - ranker->AddTranslateEvent(CreateTranslateEvent("fr", "en", 1, 0, 3)); - ranker->AddTranslateEvent(CreateTranslateEvent("jp", "en", 2, 0, 3)); - ranker->AddTranslateEvent(CreateTranslateEvent("es", "de", 4, 5, 6)); + ranker->AddTranslateEvent(CreateTranslateEvent("fr", "en", 1, 0, 3), GURL()); + ranker->AddTranslateEvent(CreateTranslateEvent("jp", "en", 2, 0, 3), GURL()); + ranker->AddTranslateEvent(CreateTranslateEvent("es", "de", 4, 5, 6), GURL()); // Logging is disabled, so no events should be cached. ranker->FlushTranslateEvents(&flushed_events); EXPECT_EQ(0U, flushed_events.size()); + EXPECT_EQ(0ul, GetTestUkmService()->sources_count()); } TEST_F(TranslateRankerImplTest, LoggingDisabledViaOverride) { @@ -357,9 +380,9 @@ ranker->FlushTranslateEvents(&flushed_events); EXPECT_EQ(0U, flushed_events.size()); - ranker->AddTranslateEvent(CreateTranslateEvent("fr", "en", 1, 0, 3)); - ranker->AddTranslateEvent(CreateTranslateEvent("jp", "en", 2, 0, 3)); - ranker->AddTranslateEvent(CreateTranslateEvent("es", "de", 4, 5, 6)); + ranker->AddTranslateEvent(CreateTranslateEvent("fr", "en", 1, 0, 3), GURL()); + ranker->AddTranslateEvent(CreateTranslateEvent("jp", "en", 2, 0, 3), GURL()); + ranker->AddTranslateEvent(CreateTranslateEvent("es", "de", 4, 5, 6), GURL()); // Logging is disabled, so no events should be cached. ranker->FlushTranslateEvents(&flushed_events); @@ -368,9 +391,9 @@ // Override the feature setting to disable logging. ranker->EnableLogging(false); - ranker->AddTranslateEvent(CreateTranslateEvent("fr", "en", 1, 0, 3)); - ranker->AddTranslateEvent(CreateTranslateEvent("jp", "en", 2, 0, 3)); - ranker->AddTranslateEvent(CreateTranslateEvent("es", "de", 4, 5, 6)); + ranker->AddTranslateEvent(CreateTranslateEvent("fr", "en", 1, 0, 3), GURL()); + ranker->AddTranslateEvent(CreateTranslateEvent("jp", "en", 2, 0, 3), GURL()); + ranker->AddTranslateEvent(CreateTranslateEvent("es", "de", 4, 5, 6), GURL()); // Logging is disabled, so no events should be cached. ranker->FlushTranslateEvents(&flushed_events);
diff --git a/components/ukm/ukm_service.h b/components/ukm/ukm_service.h index 7247e4d4..1f5bb378 100644 --- a/components/ukm/ukm_service.h +++ b/components/ukm/ukm_service.h
@@ -29,6 +29,14 @@ class AutofillMetrics; } // namespace autofill +namespace translate { +class TranslateRankerImpl; +} + +namespace payments { +class JourneyLogger; +} // namespace payments + namespace metrics { class MetricsServiceClient; } @@ -110,8 +118,10 @@ private: friend autofill::AutofillMetrics; + friend payments::JourneyLogger; friend PluginInfoMessageFilter; friend UkmPageLoadMetricsObserver; + friend translate::TranslateRankerImpl; FRIEND_TEST_ALL_PREFIXES(UkmServiceTest, AddEntryOnlyWithNonEmptyMetrics); FRIEND_TEST_ALL_PREFIXES(UkmServiceTest, EntryBuilderAndSerialization); FRIEND_TEST_ALL_PREFIXES(UkmServiceTest,
diff --git a/components/url_formatter/url_formatter.cc b/components/url_formatter/url_formatter.cc index b8a802c..d54b679 100644 --- a/components/url_formatter/url_formatter.cc +++ b/components/url_formatter/url_formatter.cc
@@ -324,8 +324,9 @@ non_ascii_latin_letters_.freeze(); // These letters are parts of |dangerous_patterns_|. - kana_letters_exceptions_ = icu::UnicodeSet(UNICODE_STRING_SIMPLE( - "[\\u3078-\\u307a\\u30d8-\\u30da\\u30fb\\u30fc]"), status); + kana_letters_exceptions_ = icu::UnicodeSet( + UNICODE_STRING_SIMPLE("[\\u3078-\\u307a\\u30d8-\\u30da\\u30fb-\\u30fe]"), + status); kana_letters_exceptions_.freeze(); // These Cyrillic letters look like Latin. A domain label entirely made of @@ -406,6 +407,8 @@ // TODO(jshin): adjust the pattern once the above ICU bug is fixed. // - Disallow U+30FB (Katakana Middle Dot) and U+30FC (Hiragana-Katakana // Prolonged Sound) used out-of-context. + // - Dislallow U+30FD/E (Katakana iteration mark/voiced iteration mark) + // unless they're preceded by a Katakana. // - Disallow three Hiragana letters (U+307[8-A]) or Katakana letters // (U+30D[8-A]) that look exactly like each other when they're used in a // label otherwise entirely in Katakna or Hiragana. @@ -417,15 +420,16 @@ "[^\\p{scx=kana}\\p{scx=hira}\\p{scx=hani}]" "[\\u30ce\\u30f3\\u30bd\\u30be]" "[^\\p{scx=kana}\\p{scx=hira}\\p{scx=hani}]|" - "[^\\p{scx=kana}\\p{scx=hira}]\\u30fc|" - "\\u30fc[^\\p{scx=kana}\\p{scx=hira}]|" + "[^\\p{scx=kana}\\p{scx=hira}]\\u30fc|^\\u30fc|" + "[^\\p{scx=kana}][\\u30fd\\u30fe]|^[\\u30fd\\u30fe]|" "^[\\p{scx=kana}]+[\\u3078-\\u307a][\\p{scx=kana}]+$|" "^[\\p{scx=hira}]+[\\u30d8-\\u30da][\\p{scx=hira}]+$|" "[a-z]\\u30fb|\\u30fb[a-z]|" "^[\\u0585\\u0581]+[a-z]|[a-z][\\u0585\\u0581]+$|" "[a-z][\\u0585\\u0581]+[a-z]|" "^[og]+[\\p{scx=armn}]|[\\p{scx=armn}][og]+$|" - "[\\p{scx=armn}][og]+[\\p{scx=armn}]", -1, US_INV), + "[\\p{scx=armn}][og]+[\\p{scx=armn}]", + -1, US_INV), 0, status); tls_index.Set(dangerous_pattern); }
diff --git a/components/url_formatter/url_formatter_unittest.cc b/components/url_formatter/url_formatter_unittest.cc index 5b2646c..a59b4b6 100644 --- a/components/url_formatter/url_formatter_unittest.cc +++ b/components/url_formatter/url_formatter_unittest.cc
@@ -187,6 +187,8 @@ {"xn--a-xbba.com", L"a\x0301\x0301.com", false}, // 'a' with acuted accent + another acute accent {"xn--1ca20i.com", L"\x00e1\x0301.com", false}, + // Combining mark at the beginning + {"xn--abc-fdc.jp", L"\x0300" L"abc.jp", false}, // Mixed script confusable // google with Armenian Small Letter Oh(U+0585) @@ -199,17 +201,51 @@ // Hiragana HE(U+3078) mixed with Katakana {"xn--49jxi3as0d0fpc.com", L"\x30e2\x30d2\x30fc\x30c8\x3078\x30d6\x30f3.com", false}, + + // U+30FC should be preceded by a Hiragana/Katakana. + // Katakana + U+30FC + Han + {"xn--lck0ip02qw5ya.jp", L"\x30ab\x30fc\x91ce\x7403.jp", true}, + // Hiragana + U+30FC + Han + {"xn--u8j5tr47nw5ya.jp", L"\x304b\x30fc\x91ce\x7403.jp", true}, // U+30FC + Han {"xn--weka801xo02a.com", L"\x30fc\x52d5\x753b\x30fc.com", false}, // Han + U+30FC + Han {"xn--wekz60nb2ay85atj0b.jp", L"\x65e5\x672c\x30fc\x91ce\x7403.jp", false}, + // U+30FC at the beginning + {"xn--wek060nb2a.jp", L"\x30fc\x65e5\x672c", false}, // Latin + U+30FC + Latin {"xn--abcdef-r64e.jp", L"abc\x30fc" L"def.jp", false}, + + // U+30FB (・) is not allowed next to Latin, but allowed otherwise. + // U+30FB + Han + {"xn--vekt920a.jp", L"\x30fb\x91ce.jp", true}, + // Han + U+30FB + Han + {"xn--vek160nb2ay85atj0b.jp", L"\x65e5\x672c\x30fb\x91ce\x7403.jp", true}, // Latin + U+30FB + Latin {"xn--abcdef-k64e.jp", L"abc\x30fb" L"def.jp", false}, // U+30FB + Latin {"xn--abc-os4b.jp", L"\x30fb" L"abc.jp", false}, + // U+30FD (ヽ) is allowed only after Katakana. + // Katakana + U+30FD + {"xn--lck2i.jp", L"\x30ab\x30fd.jp", true}, + // Hiragana + U+30FD + {"xn--u8j7t.jp", L"\x304b\x30fd.jp", false}, + // Han + U+30FD + {"xn--xek368f.jp", L"\x4e00\x30fd.jp", false}, + {"xn--aa-mju.jp", L"a\x30fd.jp", false}, + {"xn--a1-bo4a.jp", L"a1\x30fd.jp", false}, + + // U+30FE (ヾ) is allowed only after Katakana. + // Katakana + U+30FE + {"xn--lck4i.jp", L"\x30ab\x30fe.jp", true}, + // Hiragana + U+30FE + {"xn--u8j9t.jp", L"\x304b\x30fe.jp", false}, + // Han + U+30FE + {"xn--yek168f.jp", L"\x4e00\x30fe.jp", false}, + {"xn--a-oju.jp", L"a\x30fe.jp", false}, + {"xn--a1-eo4a.jp", L"a1\x30fe.jp", false}, + // Cyrillic labels made of Latin-look-alike Cyrillic letters. // ѕсоре.com with ѕсоре in Cyrillic {"xn--e1argc3h.com", L"\x0455\x0441\x043e\x0440\x0435.com", false},
diff --git a/components/viz/frame_sinks/gpu_compositor_frame_sink.cc b/components/viz/frame_sinks/gpu_compositor_frame_sink.cc index f3240e8b..683374f 100644 --- a/components/viz/frame_sinks/gpu_compositor_frame_sink.cc +++ b/components/viz/frame_sinks/gpu_compositor_frame_sink.cc
@@ -15,7 +15,7 @@ compositor_frame_sink_private_request, cc::mojom::MojoCompositorFrameSinkClientPtr client) : delegate_(delegate), - support_(base::MakeUnique<cc::CompositorFrameSinkSupport>( + support_(cc::CompositorFrameSinkSupport::Create( this, surface_manager, frame_sink_id, @@ -55,9 +55,10 @@ support_->BeginFrameDidNotSwap(begin_frame_ack); } -void GpuCompositorFrameSink::DidReceiveCompositorFrameAck() { +void GpuCompositorFrameSink::DidReceiveCompositorFrameAck( + const cc::ReturnedResourceArray& resources) { if (client_) - client_->DidReceiveCompositorFrameAck(); + client_->DidReceiveCompositorFrameAck(resources); } void GpuCompositorFrameSink::ClaimTemporaryReference(
diff --git a/components/viz/frame_sinks/gpu_compositor_frame_sink.h b/components/viz/frame_sinks/gpu_compositor_frame_sink.h index 5eac021..beb2bd2 100644 --- a/components/viz/frame_sinks/gpu_compositor_frame_sink.h +++ b/components/viz/frame_sinks/gpu_compositor_frame_sink.h
@@ -50,7 +50,8 @@ private: // cc::CompositorFrameSinkSupportClient implementation: - void DidReceiveCompositorFrameAck() override; + void DidReceiveCompositorFrameAck( + const cc::ReturnedResourceArray& resources) override; void OnBeginFrame(const cc::BeginFrameArgs& args) override; void ReclaimResources(const cc::ReturnedResourceArray& resources) override; void WillDrawSurface(const cc::LocalSurfaceId& local_surface_id,
diff --git a/components/viz/frame_sinks/gpu_root_compositor_frame_sink.cc b/components/viz/frame_sinks/gpu_root_compositor_frame_sink.cc index e0b93de..5aa6bad 100644 --- a/components/viz/frame_sinks/gpu_root_compositor_frame_sink.cc +++ b/components/viz/frame_sinks/gpu_root_compositor_frame_sink.cc
@@ -21,7 +21,7 @@ cc::mojom::MojoCompositorFrameSinkClientPtr client, cc::mojom::DisplayPrivateAssociatedRequest display_private_request) : delegate_(delegate), - support_(base::MakeUnique<cc::CompositorFrameSinkSupport>( + support_(cc::CompositorFrameSinkSupport::Create( this, surface_manager, frame_sink_id, @@ -115,9 +115,10 @@ void GpuRootCompositorFrameSink::DisplayDidDrawAndSwap() {} -void GpuRootCompositorFrameSink::DidReceiveCompositorFrameAck() { +void GpuRootCompositorFrameSink::DidReceiveCompositorFrameAck( + const cc::ReturnedResourceArray& resources) { if (client_) - client_->DidReceiveCompositorFrameAck(); + client_->DidReceiveCompositorFrameAck(resources); } void GpuRootCompositorFrameSink::OnBeginFrame(const cc::BeginFrameArgs& args) {
diff --git a/components/viz/frame_sinks/gpu_root_compositor_frame_sink.h b/components/viz/frame_sinks/gpu_root_compositor_frame_sink.h index 563ac10..5dceef59 100644 --- a/components/viz/frame_sinks/gpu_root_compositor_frame_sink.h +++ b/components/viz/frame_sinks/gpu_root_compositor_frame_sink.h
@@ -74,7 +74,8 @@ void DisplayDidDrawAndSwap() override; // cc::CompositorFrameSinkSupportClient: - void DidReceiveCompositorFrameAck() override; + void DidReceiveCompositorFrameAck( + const cc::ReturnedResourceArray& resources) override; void OnBeginFrame(const cc::BeginFrameArgs& args) override; void ReclaimResources(const cc::ReturnedResourceArray& resources) override; void WillDrawSurface(const cc::LocalSurfaceId& local_surface_id,
diff --git a/content/BUILD.gn b/content/BUILD.gn index 51c0570..1d7678c 100644 --- a/content/BUILD.gn +++ b/content/BUILD.gn
@@ -60,6 +60,7 @@ if (!is_nacl_nonsfi) { content_shared_components = [ "//content/gpu:gpu_sources", + "//content/network:network_sources", "//content/public/browser:browser_sources", "//content/public/child:child_sources", "//content/public/gpu:gpu_sources",
diff --git a/content/browser/BUILD.gn b/content/browser/BUILD.gn index 9a3211f4..5c55a852 100644 --- a/content/browser/BUILD.gn +++ b/content/browser/BUILD.gn
@@ -1061,6 +1061,8 @@ "renderer_host/font_utils_linux.h", "renderer_host/frame_metadata_util.cc", "renderer_host/frame_metadata_util.h", + "renderer_host/frame_sink_provider_impl.cc", + "renderer_host/frame_sink_provider_impl.h", "renderer_host/input/gesture_event_queue.cc", "renderer_host/input/gesture_event_queue.h", "renderer_host/input/input_ack_handler.h", @@ -1771,6 +1773,11 @@ deps += [ "//ui/gfx/x" ] } + if (is_linux && !is_chromeos && use_x11 && + (target_cpu == "x86" || target_cpu == "x64")) { + deps += [ "//third_party/swiftshader" ] + } + if (use_pango) { configs += [ "//build/config/linux/pangocairo" ] }
diff --git a/content/browser/accessibility/accessibility_win_browsertest.cc b/content/browser/accessibility/accessibility_win_browsertest.cc index 680176b..8eab2fc 100644 --- a/content/browser/accessibility/accessibility_win_browsertest.cc +++ b/content/browser/accessibility/accessibility_win_browsertest.cc
@@ -1701,7 +1701,8 @@ words.push_back(L"is \""); words.push_back(L"the "); words.push_back(L"study "); - words.push_back(L"of " + embedded_character + L' '); + words.push_back(L"of "); + words.push_back(embedded_character); words.push_back(L"of "); words.push_back(L"conflict "); words.push_back(L"and\n"); @@ -1719,6 +1720,12 @@ CheckTextAtOffset(paragraph_text, word_start_offset, IA2_TEXT_BOUNDARY_WORD, word_start_offset, word_end_offset, word); word_start_offset = word_end_offset; + // If the word boundary is inside an embedded object, |word_end_offset| + // should be one past the embedded object character. To get to the start of + // the next word, we have to skip the space between the embedded object + // character and the next word. + if (word == embedded_character) + ++word_start_offset; } }
diff --git a/content/browser/accessibility/ax_platform_position.cc b/content/browser/accessibility/ax_platform_position.cc index 34d3139..cf01ea9 100644 --- a/content/browser/accessibility/ax_platform_position.cc +++ b/content/browser/accessibility/ax_platform_position.cc
@@ -109,6 +109,10 @@ return INVALID_OFFSET; if (GetAnchor()->IsTextOnlyObject()) return MaxTextOffset(); + // Not all objects in the internal accessibility tree are exposed to platform + // APIs. + if (GetAnchor()->PlatformIsChildOfLeaf()) + return MaxTextOffset(); return 1; #else return MaxTextOffset();
diff --git a/content/browser/accessibility/browser_accessibility.cc b/content/browser/accessibility/browser_accessibility.cc index 1b2bf05..9639954 100644 --- a/content/browser/accessibility/browser_accessibility.cc +++ b/content/browser/accessibility/browser_accessibility.cc
@@ -527,197 +527,6 @@ return value; } -int BrowserAccessibility::GetLineStartBoundary( - int start, - ui::TextBoundaryDirection direction, - ui::AXTextAffinity affinity) const { - DCHECK_GE(start, 0); - DCHECK_LE(start, static_cast<int>(GetText().length())); - - if (IsSimpleTextControl()) { - return ui::FindAccessibleTextBoundary(GetText(), GetLineStartOffsets(), - ui::LINE_BOUNDARY, start, direction, - affinity); - } - - // Keeps track of the start offset of each consecutive line. - int line_start = 0; - // Keeps track of the length of each consecutive line. - int line_length = 0; - for (size_t i = 0; i < InternalChildCount(); ++i) { - const BrowserAccessibility* child = InternalGetChild(i); - DCHECK(child); - // Child objects are of length one, since they are represented by a - // single embedded object character. The exception is text-only objects. - int child_length = 1; - if (child->IsTextOnlyObject()) - child_length = static_cast<int>(child->GetText().length()); - - // Determine if |start| is within this child. As a special case, if - // the affinity is upstream, then the cursor position between two - // lines belongs to the previous line. - bool start_index_within_child = start < child_length; - if (start == child_length && - !child->IsNextSiblingOnSameLine() && - affinity == ui::AX_TEXT_AFFINITY_UPSTREAM) { - start_index_within_child = true; - } - - // Stop when we reach both the child containing our start offset and, in - // case we are searching forward, the child that is at the end of the line - // on which this object is located. - if (start_index_within_child && (direction == ui::BACKWARDS_DIRECTION || - !child->IsNextSiblingOnSameLine())) { - // Recurse into the inline text boxes. - if (child->GetRole() == ui::AX_ROLE_STATIC_TEXT) { - switch (direction) { - case ui::FORWARDS_DIRECTION: - line_length += child->GetLineStartBoundary( - std::max(start, 0), direction, affinity); - break; - case ui::BACKWARDS_DIRECTION: - line_start += child->GetLineStartBoundary( - std::max(start, 0), direction, affinity); - break; - } - } else { - line_length += child_length; - } - - break; - } - line_length += child_length; - - if (!child->IsNextSiblingOnSameLine()) { - // We are on a new line. - line_start += line_length; - line_length = 0; - } - - start -= child_length; - } - - switch (direction) { - case ui::FORWARDS_DIRECTION: - return line_start + line_length; - case ui::BACKWARDS_DIRECTION: - return line_start; - } - NOTREACHED(); - return 0; -} - -int BrowserAccessibility::GetWordStartBoundary( - int start, ui::TextBoundaryDirection direction) const { - DCHECK_GE(start, -1); - // Special offset that indicates that a word boundary has not been found. - int word_start_not_found = static_cast<int>(GetText().size()); - int word_start = word_start_not_found; - - switch (GetRole()) { - case ui::AX_ROLE_STATIC_TEXT: { - int prev_word_start = word_start_not_found; - int child_start = 0; - int child_end = 0; - - // Go through the inline text boxes. - for (size_t i = 0; i < InternalChildCount(); ++i) { - // The next child starts where the previous one ended. - child_start = child_end; - const BrowserAccessibility* child = InternalGetChild(i); - DCHECK_EQ(child->GetRole(), ui::AX_ROLE_INLINE_TEXT_BOX); - int child_len = static_cast<int>(child->GetText().size()); - child_end += child_len; // End is one past the last character. - - const std::vector<int32_t>& word_starts = - child->GetIntListAttribute(ui::AX_ATTR_WORD_STARTS); - if (word_starts.empty()) { - word_start = child_end; - continue; - } - - int local_start = start - child_start; - std::vector<int32_t>::const_iterator iter = std::upper_bound( - word_starts.begin(), word_starts.end(), local_start); - if (iter != word_starts.end()) { - if (direction == ui::FORWARDS_DIRECTION) { - word_start = child_start + *iter; - } else if (direction == ui::BACKWARDS_DIRECTION) { - if (iter == word_starts.begin()) { - // Return the position of the last word in the previous child. - word_start = prev_word_start; - } else { - word_start = child_start + *(iter - 1); - } - } else { - NOTREACHED(); - } - break; - } - - // No word start that is greater than the requested offset has been - // found. - prev_word_start = child_start + *(iter - 1); - if (direction == ui::FORWARDS_DIRECTION) { - word_start = child_end; - } else if (direction == ui::BACKWARDS_DIRECTION) { - word_start = prev_word_start; - } else { - NOTREACHED(); - } - } - return word_start; - } - - case ui::AX_ROLE_LINE_BREAK: - // Words never start at a line break. - return word_start_not_found; - - default: - // If there are no children, the word start boundary is still unknown or - // found previously depending on the direction. - if (!InternalChildCount()) - return word_start_not_found; - - const BrowserAccessibility* this_object = this; - // Standard text fields such as textarea have an embedded div inside them - // that should be skipped. - // TODO(nektar): This is fragile. Replace with code that flattens tree. - if (IsSimpleTextControl() && InternalChildCount() == 1) { - this_object = InternalGetChild(0); - } - int child_start = 0; - for (size_t i = 0; i < this_object->InternalChildCount(); ++i) { - BrowserAccessibility* child = this_object->InternalGetChild(i); - // Child objects are of length one, since they are represented by a - // single embedded object character. The exception is text-only objects. - int child_len = 1; - if (child->IsTextOnlyObject()) { - child_len = static_cast<int>(child->GetText().length()); - int child_word_start = child->GetWordStartBoundary(start, direction); - if (child_word_start < child_len) { - // We have found a possible word boundary. - word_start = child_start + child_word_start; - } - - // Decide when to stop searching. - if ((word_start != word_start_not_found && - direction == ui::FORWARDS_DIRECTION) || - (start < child_len && direction == ui::BACKWARDS_DIRECTION)) { - break; - } - } - - child_start += child_len; - if (start >= child_len) - start -= child_len; - else - start = -1; - } - return word_start; - } -} - BrowserAccessibility* BrowserAccessibility::ApproximateHitTest( const gfx::Point& point) { // The best result found that's a child of this object. @@ -1243,10 +1052,11 @@ } BrowserAccessibility::AXPlatformPositionInstance -BrowserAccessibility::CreatePositionAt(int offset) const { +BrowserAccessibility::CreatePositionAt(int offset, + ui::AXTextAffinity affinity) const { DCHECK(manager_); - return AXPlatformPosition::CreateTextPosition( - manager_->ax_tree_id(), GetId(), offset, ui::AX_TEXT_AFFINITY_DOWNSTREAM); + return AXPlatformPosition::CreateTextPosition(manager_->ax_tree_id(), GetId(), + offset, affinity); } base::string16 BrowserAccessibility::GetInnerText() const {
diff --git a/content/browser/accessibility/browser_accessibility.h b/content/browser/accessibility/browser_accessibility.h index 871d6b1d..89cafa8 100644 --- a/content/browser/accessibility/browser_accessibility.h +++ b/content/browser/accessibility/browser_accessibility.h
@@ -170,25 +170,6 @@ // be calculated from the object's inner text. virtual base::string16 GetValue() const; - // Starting at the given character offset, locates the start of the next or - // previous line and returns its character offset. - int GetLineStartBoundary(int start, - ui::TextBoundaryDirection direction, - ui::AXTextAffinity affinity) const; - - // Starting at the given character offset, locates the start of the next or - // previous word and returns its character offset. - // In case there is no word boundary before or after the given offset, it - // returns one past the last character. - // If the given offset is already at the start of a word, returns the start - // of the next word if the search is forwards, and the given offset if it is - // backwards. - // If the start offset is equal to -1 and the search is in the forwards - // direction, returns the start boundary of the first word. - // Start offsets that are not in the range -1 to text length are invalid. - int GetWordStartBoundary(int start, - ui::TextBoundaryDirection direction) const; - // This is an approximate hit test that only uses the information in // the browser process to compute the correct result. It will not return // correct results in many cases of z-index, overflow, and absolute @@ -401,11 +382,10 @@ // to compute a name from its descendants. std::string ComputeAccessibleNameFromDescendants(); - // Creates a position rooted at this object. - // This is a text position on all platforms except IA2 and ATK, where tree - // positions are created for non-text objects representing hypertext offsets. - virtual AXPlatformPosition::AXPositionInstance CreatePositionAt( - int offset) const; + // Creates a text position rooted at this object. + AXPlatformPosition::AXPositionInstance CreatePositionAt( + int offset, + ui::AXTextAffinity affinity = ui::AX_TEXT_AFFINITY_DOWNSTREAM) const; // Gets the text offsets where new lines start. std::vector<int> GetLineStartOffsets() const;
diff --git a/content/browser/accessibility/browser_accessibility_manager.cc b/content/browser/accessibility/browser_accessibility_manager.cc index 5dff169a..f84b62d 100644 --- a/content/browser/accessibility/browser_accessibility_manager.cc +++ b/content/browser/accessibility/browser_accessibility_manager.cc
@@ -11,6 +11,7 @@ #include "build/build_config.h" #include "content/browser/accessibility/browser_accessibility.h" #include "content/common/accessibility_messages.h" +#include "ui/accessibility/ax_tree_data.h" #include "ui/accessibility/ax_tree_serializer.h" namespace content { @@ -66,6 +67,11 @@ int32_t no_id = empty_data.id; ui::AXTreeUpdate update; + ui::AXTreeData tree_data; + tree_data.tree_id = 1; + tree_data.focused_tree_id = 1; + update.tree_data = tree_data; + update.has_tree_data = true; update.root_id = node1.id; update.nodes.push_back(node1); if (node2.id != no_id)
diff --git a/content/browser/accessibility/browser_accessibility_manager_unittest.cc b/content/browser/accessibility/browser_accessibility_manager_unittest.cc index 2bf46c29d..0ac8677 100644 --- a/content/browser/accessibility/browser_accessibility_manager_unittest.cc +++ b/content/browser/accessibility/browser_accessibility_manager_unittest.cc
@@ -1608,51 +1608,4 @@ ASSERT_EQ(3, manager->GetFocus()->GetId()); } -TEST(BrowserAccessibilityManagerTest, LineStartBoundary) { - ui::AXNodeData root; - root.id = 1; - root.role = ui::AX_ROLE_ROOT_WEB_AREA; - - ui::AXNodeData static_text; - static_text.id = 2; - static_text.SetName("1-2-3-4"); - static_text.role = ui::AX_ROLE_STATIC_TEXT; - root.child_ids.push_back(2); - - ui::AXNodeData inline_text1; - inline_text1.id = 3; - inline_text1.SetName("1-2-"); - inline_text1.role = ui::AX_ROLE_INLINE_TEXT_BOX; - static_text.child_ids.push_back(3); - - ui::AXNodeData inline_text2; - inline_text2.id = 4; - inline_text2.SetName("3-4"); - inline_text2.role = ui::AX_ROLE_INLINE_TEXT_BOX; - static_text.child_ids.push_back(4); - - std::unique_ptr<BrowserAccessibilityManager> manager( - BrowserAccessibilityManager::Create( - MakeAXTreeUpdate(root, static_text, inline_text1, inline_text2), - nullptr, new CountedBrowserAccessibilityFactory())); - - BrowserAccessibility* root_accessible = manager->GetRoot(); - ASSERT_NE(nullptr, root_accessible); - BrowserAccessibility* static_text_accessible = - root_accessible->PlatformGetChild(0); - ASSERT_NE(nullptr, static_text_accessible); - - // If the affinity is downstream, check that we get the second line. - ASSERT_EQ(4, static_text_accessible->GetLineStartBoundary( - 4, ui::BACKWARDS_DIRECTION, ui::AX_TEXT_AFFINITY_DOWNSTREAM)); - ASSERT_EQ(7, static_text_accessible->GetLineStartBoundary( - 4, ui::FORWARDS_DIRECTION, ui::AX_TEXT_AFFINITY_DOWNSTREAM)); - - // If the affinity is upstream, check that we get the second line. - ASSERT_EQ(0, static_text_accessible->GetLineStartBoundary( - 4, ui::BACKWARDS_DIRECTION, ui::AX_TEXT_AFFINITY_UPSTREAM)); - ASSERT_EQ(4, static_text_accessible->GetLineStartBoundary( - 4, ui::FORWARDS_DIRECTION, ui::AX_TEXT_AFFINITY_UPSTREAM)); -} - } // namespace content
diff --git a/content/browser/accessibility/browser_accessibility_win.cc b/content/browser/accessibility/browser_accessibility_win.cc index 87ae27f25..151aa68 100644 --- a/content/browser/accessibility/browser_accessibility_win.cc +++ b/content/browser/accessibility/browser_accessibility_win.cc
@@ -2262,11 +2262,11 @@ if (!start_offset || !end_offset || !text) return E_INVALIDARG; - const base::string16& text_str = GetText(); HandleSpecialTextOffset(&offset); if (offset < 0) return E_INVALIDARG; + const base::string16& text_str = GetText(); LONG text_len = text_str.length(); if (offset > text_len) return E_INVALIDARG; @@ -3665,8 +3665,9 @@ // |offset| could either be a text character or a child index in case of // non-text objects. +// TODO(nektar): Remove this function once selection bugs are fixed in Blink. BrowserAccessibilityWin::AXPlatformPositionInstance -BrowserAccessibilityWin::CreatePositionAt(int offset) const { +BrowserAccessibilityWin::CreatePositionForSelectionAt(int offset) const { if (!IsNativeTextControl() && !IsTextOnlyObject()) { DCHECK(manager_); const BrowserAccessibilityWin* child = this; @@ -3696,7 +3697,7 @@ } return position; } - return BrowserAccessibility::CreatePositionAt(offset); + return CreatePositionAt(offset); } base::string16 BrowserAccessibilityWin::GetText() const { @@ -4337,9 +4338,9 @@ HandleSpecialTextOffset(&start_offset); HandleSpecialTextOffset(&end_offset); AXPlatformPositionInstance start_position = - CreatePositionAt(static_cast<int>(start_offset)); + CreatePositionForSelectionAt(static_cast<int>(start_offset)); AXPlatformPositionInstance end_position = - CreatePositionAt(static_cast<int>(end_offset)); + CreatePositionForSelectionAt(static_cast<int>(end_offset)); manager_->SetSelection(AXPlatformRange(start_position->AsTextPosition(), end_position->AsTextPosition())); } @@ -4747,13 +4748,61 @@ : ui::AX_TEXT_AFFINITY_DOWNSTREAM; HandleSpecialTextOffset(&start_offset); - if (ia2_boundary == IA2_TEXT_BOUNDARY_WORD) - return GetWordStartBoundary(static_cast<int>(start_offset), direction); - if (ia2_boundary == IA2_TEXT_BOUNDARY_LINE) { - return GetLineStartBoundary( - static_cast<int>(start_offset), direction, affinity); + if (ia2_boundary == IA2_TEXT_BOUNDARY_WORD) { + switch (direction) { + case ui::FORWARDS_DIRECTION: { + AXPlatformPositionInstance position = + CreatePositionAt(static_cast<int>(start_offset), affinity); + AXPlatformPositionInstance next_word = + position->CreateNextWordStartPosition(); + if (next_word->anchor_id() != GetId()) + next_word = position->CreatePositionAtEndOfAnchor(); + return next_word->text_offset(); + } + case ui::BACKWARDS_DIRECTION: { + AXPlatformPositionInstance position = + CreatePositionAt(static_cast<int>(start_offset), affinity); + AXPlatformPositionInstance previous_word; + if (!position->AtStartOfWord()) { + previous_word = position->CreatePreviousWordStartPosition(); + if (previous_word->anchor_id() != GetId()) + previous_word = position->CreatePositionAtStartOfAnchor(); + } else { + previous_word = std::move(position); + } + return previous_word->text_offset(); + } + } } + if (ia2_boundary == IA2_TEXT_BOUNDARY_LINE) { + switch (direction) { + case ui::FORWARDS_DIRECTION: { + AXPlatformPositionInstance position = + CreatePositionAt(static_cast<int>(start_offset), affinity); + AXPlatformPositionInstance next_line = + position->CreateNextLineStartPosition(); + if (next_line->anchor_id() != GetId()) + next_line = position->CreatePositionAtEndOfAnchor(); + return next_line->text_offset(); + } + case ui::BACKWARDS_DIRECTION: { + AXPlatformPositionInstance position = + CreatePositionAt(static_cast<int>(start_offset), affinity); + AXPlatformPositionInstance previous_line; + if (!position->AtStartOfLine()) { + previous_line = position->CreatePreviousLineStartPosition(); + if (previous_line->anchor_id() != GetId()) + previous_line = position->CreatePositionAtStartOfAnchor(); + } else { + previous_line = std::move(position); + } + return previous_line->text_offset(); + } + } + } + + // TODO(nektar): |AXPosition| can handle other types of boundaries as well. ui::TextBoundaryType boundary = IA2TextBoundaryToTextBoundary(ia2_boundary); return ui::FindAccessibleTextBoundary(text, GetLineStartOffsets(), boundary, start_offset, direction, affinity);
diff --git a/content/browser/accessibility/browser_accessibility_win.h b/content/browser/accessibility/browser_accessibility_win.h index d563382b..a9f1f9cf 100644 --- a/content/browser/accessibility/browser_accessibility_win.h +++ b/content/browser/accessibility/browser_accessibility_win.h
@@ -722,8 +722,8 @@ // |offset| could either be a text character or a child index in case of // non-text objects. - CONTENT_EXPORT AXPlatformPosition::AXPositionInstance CreatePositionAt( - int offset) const override; + AXPlatformPosition::AXPositionInstance CreatePositionForSelectionAt( + int offset) const; CONTENT_EXPORT base::string16 GetText() const override;
diff --git a/content/browser/accessibility/browser_accessibility_win_unittest.cc b/content/browser/accessibility/browser_accessibility_win_unittest.cc index 5d31b377..2aea2d3f 100644 --- a/content/browser/accessibility/browser_accessibility_win_unittest.cc +++ b/content/browser/accessibility/browser_accessibility_win_unittest.cc
@@ -7,6 +7,7 @@ #include <stdint.h> #include <memory> +#include <utility> #include "base/macros.h" #include "base/strings/utf_string_conversions.h" @@ -1068,6 +1069,7 @@ textarea_text.state = 1 << ui::AX_STATE_EDITABLE; textarea.SetValue(base::UTF16ToUTF8(text)); textarea_text.SetName(base::UTF16ToUTF8(text)); + textarea.AddStringAttribute(ui::AX_ATTR_HTML_TAG, "textarea"); textarea.child_ids.push_back(textarea_div.id); textarea_div.child_ids.push_back(textarea_text.id); @@ -1100,6 +1102,8 @@ text_field_text.state = 1 << ui::AX_STATE_EDITABLE; text_field.SetValue(base::UTF16ToUTF8(line1)); text_field_text.SetName(base::UTF16ToUTF8(line1)); + text_field.AddStringAttribute(ui::AX_ATTR_HTML_TAG, "input"); + text_field.html_attributes.push_back(std::make_pair("type", "text")); text_field.child_ids.push_back(text_field_div.id); text_field_div.child_ids.push_back(text_field_text.id);
diff --git a/content/browser/accessibility/dump_accessibility_browsertest_base.cc b/content/browser/accessibility/dump_accessibility_browsertest_base.cc index 2976698e..4ab9633 100644 --- a/content/browser/accessibility/dump_accessibility_browsertest_base.cc +++ b/content/browser/accessibility/dump_accessibility_browsertest_base.cc
@@ -385,8 +385,9 @@ if (base::CommandLine::ForCurrentProcess()->HasSwitch( switches::kGenerateAccessibilityTestExpectations)) { base::ThreadRestrictions::ScopedAllowIO allow_io_to_write_expected_file; - CHECK(base::WriteFile( - expected_file, actual_contents.c_str(), actual_contents.size())); + CHECK(base::WriteFile(expected_file, actual_contents.c_str(), + actual_contents.size()) == + static_cast<int>(actual_contents.size())); LOG(INFO) << "Wrote expectations to: " << expected_file.LossyDisplayName(); }
diff --git a/content/browser/android/OWNERS b/content/browser/android/OWNERS index 482db7f..6006c70f 100644 --- a/content/browser/android/OWNERS +++ b/content/browser/android/OWNERS
@@ -2,4 +2,7 @@ tedchoc@chromium.org yfriedman@chromium.org +# ContentViewCore related +per-file content_view_*=jinsukkim@chromium.org + # COMPONENT: Content>WebApps
diff --git a/content/browser/android/synchronous_compositor_browser_filter.cc b/content/browser/android/synchronous_compositor_browser_filter.cc index 1db0063..c04a4fb3 100644 --- a/content/browser/android/synchronous_compositor_browser_filter.cc +++ b/content/browser/android/synchronous_compositor_browser_filter.cc
@@ -191,11 +191,14 @@ std::vector<SyncCompositorCommonRendererParams> params; params.reserve(compositor_host_pending_renderer_state_.size()); - if (!render_process_host_->Send( - new SyncCompositorMsg_SynchronizeRendererState(routing_ids, - ¶ms))) { - compositor_host_pending_renderer_state_.clear(); - return; + { + base::ThreadRestrictions::ScopedAllowWait wait; + if (!render_process_host_->Send( + new SyncCompositorMsg_SynchronizeRendererState(routing_ids, + ¶ms))) { + compositor_host_pending_renderer_state_.clear(); + return; + } } if (compositor_host_pending_renderer_state_.size() != params.size()) {
diff --git a/content/browser/android/synchronous_compositor_host.cc b/content/browser/android/synchronous_compositor_host.cc index 15a7488..8c35ae70 100644 --- a/content/browser/android/synchronous_compositor_host.cc +++ b/content/browser/android/synchronous_compositor_host.cc
@@ -10,6 +10,7 @@ #include "base/containers/hash_tables.h" #include "base/memory/ptr_util.h" #include "base/memory/shared_memory.h" +#include "base/threading/thread_restrictions.h" #include "base/trace_event/trace_event_argument.h" #include "content/browser/android/synchronous_compositor_browser_filter.h" #include "content/browser/renderer_host/render_widget_host_view_android.h" @@ -122,10 +123,13 @@ base::Optional<cc::CompositorFrame> compositor_frame; SyncCompositorCommonRendererParams common_renderer_params; - if (!sender_->Send(new SyncCompositorMsg_DemandDrawHw( - routing_id_, params, &common_renderer_params, - &compositor_frame_sink_id, &compositor_frame))) { - return SynchronousCompositor::Frame(); + { + base::ThreadRestrictions::ScopedAllowWait wait; + if (!sender_->Send(new SyncCompositorMsg_DemandDrawHw( + routing_id_, params, &common_renderer_params, + &compositor_frame_sink_id, &compositor_frame))) { + return SynchronousCompositor::Frame(); + } } ProcessCommonParams(common_renderer_params); @@ -176,10 +180,13 @@ std::unique_ptr<cc::CompositorFrame> frame(new cc::CompositorFrame); ScopedSetSkCanvas set_sk_canvas(canvas); SyncCompositorDemandDrawSwParams params; // Unused. - if (!sender_->Send(new SyncCompositorMsg_DemandDrawSw( - routing_id_, params, &success, &common_renderer_params, - frame.get()))) { - return false; + { + base::ThreadRestrictions::ScopedAllowWait wait; + if (!sender_->Send(new SyncCompositorMsg_DemandDrawSw( + routing_id_, params, &success, &common_renderer_params, + frame.get()))) { + return false; + } } if (!success) return false; @@ -239,10 +246,13 @@ std::unique_ptr<cc::CompositorFrame> frame(new cc::CompositorFrame); SyncCompositorCommonRendererParams common_renderer_params; bool success = false; - if (!sender_->Send(new SyncCompositorMsg_DemandDrawSw( - routing_id_, params, &success, &common_renderer_params, - frame.get()))) { - return false; + { + base::ThreadRestrictions::ScopedAllowWait wait; + if (!sender_->Send(new SyncCompositorMsg_DemandDrawSw( + routing_id_, params, &success, &common_renderer_params, + frame.get()))) { + return false; + } } ScopedSendZeroMemory send_zero_memory(this); if (!success) @@ -292,10 +302,13 @@ bool success = false; SyncCompositorCommonRendererParams common_renderer_params; - if (!sender_->Send(new SyncCompositorMsg_SetSharedMemory( - routing_id_, set_shm_params, &success, &common_renderer_params)) || - !success) { - return; + { + base::ThreadRestrictions::ScopedAllowWait wait; + if (!sender_->Send(new SyncCompositorMsg_SetSharedMemory( + routing_id_, set_shm_params, &success, &common_renderer_params)) || + !success) { + return; + } } software_draw_shm_ = std::move(software_draw_shm); ProcessCommonParams(common_renderer_params); @@ -336,9 +349,12 @@ void SynchronousCompositorHost::SynchronouslyZoomBy(float zoom_delta, const gfx::Point& anchor) { SyncCompositorCommonRendererParams common_renderer_params; - if (!sender_->Send(new SyncCompositorMsg_ZoomBy( - routing_id_, zoom_delta, anchor, &common_renderer_params))) { - return; + { + base::ThreadRestrictions::ScopedAllowWait wait; + if (!sender_->Send(new SyncCompositorMsg_ZoomBy( + routing_id_, zoom_delta, anchor, &common_renderer_params))) { + return; + } } ProcessCommonParams(common_renderer_params); }
diff --git a/content/browser/devtools/protocol/devtools_protocol_browsertest.cc b/content/browser/devtools/protocol/devtools_protocol_browsertest.cc index af97bb3..be6a517 100644 --- a/content/browser/devtools/protocol/devtools_protocol_browsertest.cc +++ b/content/browser/devtools/protocol/devtools_protocol_browsertest.cc
@@ -1316,13 +1316,7 @@ .size()); } -// TODO(701223): Enable this on android. -#if defined(OS_ANDROID) -#define MAYBE_VirtualTimeTest DISABLED_VirtualTimeTest -#else -#define MAYBE_VirtualTimeTest VirtualTimeTest -#endif -IN_PROC_BROWSER_TEST_F(DevToolsProtocolTest, MAYBE_VirtualTimeTest) { +IN_PROC_BROWSER_TEST_F(DevToolsProtocolTest, VirtualTimeTest) { NavigateToURLBlockUntilNavigationsComplete(shell(), GURL("about:blank"), 1); Attach(); @@ -1330,16 +1324,18 @@ params->SetString("policy", "pause"); SendCommand("Emulation.setVirtualTimePolicy", std::move(params), true); + // TODO(scheduler-dev): Revisit timing when we have strict ordering + // guarantees. params.reset(new base::DictionaryValue()); params->SetString("expression", "setTimeout(function(){console.log('before')}, 1000);" - "setTimeout(function(){console.log('after')}, 1001);"); + "setTimeout(function(){console.log('after')}, 1002);"); SendCommand("Runtime.evaluate", std::move(params), true); // Let virtual time advance for one second. params.reset(new base::DictionaryValue()); params->SetString("policy", "advance"); - params->SetInteger("budget", 1000); + params->SetInteger("budget", 1001); SendCommand("Emulation.setVirtualTimePolicy", std::move(params), true); WaitForNotification("Emulation.virtualTimeBudgetExpired");
diff --git a/content/browser/download/download_manager_impl_unittest.cc b/content/browser/download/download_manager_impl_unittest.cc index e76bb53..3e606c2 100644 --- a/content/browser/download/download_manager_impl_unittest.cc +++ b/content/browser/download/download_manager_impl_unittest.cc
@@ -70,13 +70,6 @@ namespace { -// Matches a DownloadCreateInfo* that points to the same object as |info| and -// has a |default_download_directory| that matches |download_directory|. -MATCHER_P2(DownloadCreateInfoWithDefaultPath, info, download_directory, "") { - return arg == info && - arg->default_download_directory == download_directory; -} - class MockDownloadManagerDelegate : public DownloadManagerDelegate { public: MockDownloadManagerDelegate();
diff --git a/content/browser/download/download_stats.h b/content/browser/download/download_stats.h index e4da2f4..a7d706a9 100644 --- a/content/browser/download/download_stats.h +++ b/content/browser/download/download_stats.h
@@ -174,6 +174,9 @@ // The HTTP connection type does not meet the requirement. FALLBACK_REASON_CONNECTION_TYPE, + // The remaining time does not meet the requirement. + FALLBACK_REASON_REMAINING_TIME, + // Last entry of the enum. COUNT, };
diff --git a/content/browser/download/parallel_download_job.cc b/content/browser/download/parallel_download_job.cc index 0dc7cdd..5a3af37 100644 --- a/content/browser/download/parallel_download_job.cc +++ b/content/browser/download/parallel_download_job.cc
@@ -4,7 +4,11 @@ #include "content/browser/download/parallel_download_job.h" +#include <algorithm> + #include "base/memory/ptr_util.h" +#include "base/metrics/histogram_macros.h" +#include "base/time/time.h" #include "content/browser/download/download_create_info.h" #include "content/browser/download/download_stats.h" #include "content/browser/download/parallel_download_utils.h" @@ -80,10 +84,15 @@ int ParallelDownloadJob::GetParallelRequestCount() const { return GetParallelRequestCountConfig(); } + int64_t ParallelDownloadJob::GetMinSliceSize() const { return GetMinSliceSizeConfig(); } +int ParallelDownloadJob::GetMinRemainingTimeInSeconds() const { + return GetParallelRequestRemainingTimeConfig().InSeconds(); +} + bool ParallelDownloadJob::UsesParallelRequests() const { return true; } @@ -149,15 +158,30 @@ // Create more slices for a new download. The initial request may generate // a received slice. - if (slices_to_download.size() <= 1 && - initial_request_offset_ <= first_slice_offset) { - // TODO(qinmin): Check the size of the last slice. If it is huge, we can - // split it into N pieces and pass the last N-1 pieces to different workers. - // Otherwise, just fork |slices_to_download.size()| number of workers. - slices_to_download = FindSlicesForRemainingContent( - first_slice_offset, - content_length_ - first_slice_offset + initial_request_offset_, - GetParallelRequestCount(), GetMinSliceSize()); + if (slices_to_download.size() <= 1 && download_item_->GetTotalBytes() > 0) { + int64_t current_bytes_per_second = + std::max(static_cast<int64_t>(1), download_item_->CurrentSpeed()); + int64_t remaining_bytes = + download_item_->GetTotalBytes() - download_item_->GetReceivedBytes(); + + int64_t remaining_time = remaining_bytes / current_bytes_per_second; + UMA_HISTOGRAM_CUSTOM_COUNTS( + "Download.ParallelDownload.RemainingTimeWhenBuildingRequests", + remaining_time, 0, base::TimeDelta::FromDays(1).InSeconds(), 50); + if (remaining_bytes / current_bytes_per_second > + GetMinRemainingTimeInSeconds()) { + // TODO(qinmin): Check the size of the last slice. If it is huge, we can + // split it into N pieces and pass the last N-1 pieces to different + // workers. Otherwise, just fork |slices_to_download.size()| number of + // workers. + slices_to_download = FindSlicesForRemainingContent( + first_slice_offset, + content_length_ - first_slice_offset + initial_request_offset_, + GetParallelRequestCount(), GetMinSliceSize()); + } else { + RecordParallelDownloadCreationEvent( + ParallelDownloadCreationEvent::FALLBACK_REASON_REMAINING_TIME); + } } DCHECK(!slices_to_download.empty());
diff --git a/content/browser/download/parallel_download_job.h b/content/browser/download/parallel_download_job.h index d2b5387..6ade0aeb 100644 --- a/content/browser/download/parallel_download_job.h +++ b/content/browser/download/parallel_download_job.h
@@ -40,6 +40,7 @@ // Virtual for testing. virtual int GetParallelRequestCount() const; virtual int64_t GetMinSliceSize() const; + virtual int GetMinRemainingTimeInSeconds() const; using WorkerMap = std::unordered_map<int64_t, std::unique_ptr<DownloadWorker>>;
diff --git a/content/browser/download/parallel_download_job_unittest.cc b/content/browser/download/parallel_download_job_unittest.cc index de6da07..0c730c3 100644 --- a/content/browser/download/parallel_download_job_unittest.cc +++ b/content/browser/download/parallel_download_job_unittest.cc
@@ -40,12 +40,14 @@ std::unique_ptr<DownloadRequestHandleInterface> request_handle, const DownloadCreateInfo& create_info, int request_count, - int64_t min_slice_size) + int64_t min_slice_size, + int min_remaining_time) : ParallelDownloadJob(download_item, std::move(request_handle), create_info), request_count_(request_count), - min_slice_size_(min_slice_size) {} + min_slice_size_(min_slice_size), + min_remaining_time_(min_remaining_time) {} void CreateRequest(int64_t offset, int64_t length) override { std::unique_ptr<DownloadWorker> worker = @@ -59,6 +61,9 @@ int GetParallelRequestCount() const override { return request_count_; } int64_t GetMinSliceSize() const override { return min_slice_size_; } + int GetMinRemainingTimeInSeconds() const override { + return min_remaining_time_; + } void OnByteStreamReady( DownloadWorker* worker, @@ -71,6 +76,7 @@ private: int request_count_; int min_slice_size_; + int min_remaining_time_; DISALLOW_COPY_AND_ASSIGN(ParallelDownloadJobForTest); }; @@ -80,10 +86,17 @@ int64_t content_length, const DownloadItem::ReceivedSlices& slices, int request_count, - int64_t min_slice_size) { + int64_t min_slice_size, + int min_remaining_time) { item_delegate_ = base::MakeUnique<DownloadItemImplDelegate>(); download_item_ = base::MakeUnique<NiceMock<MockDownloadItemImpl>>( item_delegate_.get(), slices); + EXPECT_CALL(*download_item_, GetTotalBytes()) + .WillRepeatedly( + testing::Return(initial_request_offset + content_length)); + EXPECT_CALL(*download_item_, GetReceivedBytes()) + .WillRepeatedly(testing::Return(initial_request_offset)); + DownloadCreateInfo info; info.offset = initial_request_offset; info.total_bytes = content_length; @@ -92,7 +105,7 @@ mock_request_handle_ = request_handle.get(); job_ = base::MakeUnique<ParallelDownloadJobForTest>( download_item_.get(), std::move(request_handle), info, request_count, - min_slice_size); + min_slice_size, min_remaining_time); } void DestroyParallelJob() { @@ -139,7 +152,7 @@ // Totally 2 requests for 100 bytes. // Original request: Range:0-49, for 50 bytes. // Task 1: Range:50-, for 50 bytes. - CreateParallelJob(0, 100, DownloadItem::ReceivedSlices(), 2, 1); + CreateParallelJob(0, 100, DownloadItem::ReceivedSlices(), 2, 1, 10); BuildParallelRequests(); EXPECT_EQ(1, static_cast<int>(job_->workers().size())); VerifyWorker(50, 0); @@ -149,7 +162,7 @@ // Original request: Range:0-32, for 33 bytes. // Task 1: Range:33-65, for 33 bytes. // Task 2: Range:66-, for 34 bytes. - CreateParallelJob(0, 100, DownloadItem::ReceivedSlices(), 3, 1); + CreateParallelJob(0, 100, DownloadItem::ReceivedSlices(), 3, 1, 10); BuildParallelRequests(); EXPECT_EQ(2, static_cast<int>(job_->workers().size())); VerifyWorker(33, 33); @@ -157,18 +170,18 @@ DestroyParallelJob(); // Less than 2 requests, do nothing. - CreateParallelJob(0, 100, DownloadItem::ReceivedSlices(), 1, 1); + CreateParallelJob(0, 100, DownloadItem::ReceivedSlices(), 1, 1, 10); BuildParallelRequests(); EXPECT_TRUE(job_->workers().empty()); DestroyParallelJob(); - CreateParallelJob(0, 100, DownloadItem::ReceivedSlices(), 0, 1); + CreateParallelJob(0, 100, DownloadItem::ReceivedSlices(), 0, 1, 10); BuildParallelRequests(); EXPECT_TRUE(job_->workers().empty()); DestroyParallelJob(); // Content-length is 0, do nothing. - CreateParallelJob(0, 0, DownloadItem::ReceivedSlices(), 3, 1); + CreateParallelJob(0, 0, DownloadItem::ReceivedSlices(), 3, 1, 10); BuildParallelRequests(); EXPECT_TRUE(job_->workers().empty()); DestroyParallelJob(); @@ -183,7 +196,7 @@ // Task 1: Range:44-70, for 27 bytes. // Task 2: Range:71-, for 29 bytes. DownloadItem::ReceivedSlices slices = {DownloadItem::ReceivedSlice(0, 17)}; - CreateParallelJob(12, 88, slices, 3, 1); + CreateParallelJob(12, 88, slices, 3, 1, 10); BuildParallelRequests(); EXPECT_EQ(2, static_cast<int>(job_->workers().size())); VerifyWorker(44, 27); @@ -191,21 +204,21 @@ DestroyParallelJob(); // File size: 100 bytes. - // Received slices: [0, 98], Range:0-97. - // Original request: Range:98-. Content-length: 2. - // 2 bytes left for 4 requests. Only 1 additional request. - // Original request: Range:98-99, for 1 bytes. - // Task 1: Range:99-, for 1 bytes. - slices = {DownloadItem::ReceivedSlice(0, 98)}; - CreateParallelJob(98, 2, slices, 4, 1); + // Received slices: [0, 60], Range:0-59. + // Original request: Range:60-. Content-length: 40. + // 40 bytes left for 4 requests. Only 1 additional request. + // Original request: Range:60-79, for 20 bytes. + // Task 1: Range:80-, for 20 bytes. + slices = {DownloadItem::ReceivedSlice(0, 60)}; + CreateParallelJob(60, 40, slices, 4, 20, 10); BuildParallelRequests(); EXPECT_EQ(1, static_cast<int>(job_->workers().size())); - VerifyWorker(99, 0); + VerifyWorker(80, 0); DestroyParallelJob(); // Content-Length is 0, no additional requests. slices = {DownloadItem::ReceivedSlice(0, 100)}; - CreateParallelJob(100, 0, slices, 3, 1); + CreateParallelJob(100, 0, slices, 3, 1, 10); BuildParallelRequests(); EXPECT_TRUE(job_->workers().empty()); DestroyParallelJob(); @@ -218,7 +231,7 @@ slices = { DownloadItem::ReceivedSlice(10, 10), DownloadItem::ReceivedSlice(20, 10), DownloadItem::ReceivedSlice(40, 10), DownloadItem::ReceivedSlice(90, 10)}; - CreateParallelJob(0, 12, slices, 2, 1); + CreateParallelJob(0, 12, slices, 2, 1, 10); BuildParallelRequests(); EXPECT_EQ(3, static_cast<int>(job_->workers().size())); VerifyWorker(30, 10); @@ -234,7 +247,7 @@ // Ensure cancel before building the requests will result in no requests are // built. TEST_F(ParallelDownloadJobTest, EarlyCancelBeforeBuildRequests) { - CreateParallelJob(0, 100, DownloadItem::ReceivedSlices(), 2, 1); + CreateParallelJob(0, 100, DownloadItem::ReceivedSlices(), 2, 1, 10); EXPECT_CALL(*mock_request_handle_, CancelRequest()); // Job is canceled before building parallel requests. @@ -250,7 +263,7 @@ // Ensure cancel before adding the byte stream will result in workers being // canceled. TEST_F(ParallelDownloadJobTest, EarlyCancelBeforeByteStreamReady) { - CreateParallelJob(0, 100, DownloadItem::ReceivedSlices(), 2, 1); + CreateParallelJob(0, 100, DownloadItem::ReceivedSlices(), 2, 1, 10); EXPECT_CALL(*mock_request_handle_, CancelRequest()); BuildParallelRequests(); @@ -274,7 +287,7 @@ // Ensure pause before adding the byte stream will result in workers being // paused. TEST_F(ParallelDownloadJobTest, EarlyPauseBeforeByteStreamReady) { - CreateParallelJob(0, 100, DownloadItem::ReceivedSlices(), 2, 1); + CreateParallelJob(0, 100, DownloadItem::ReceivedSlices(), 2, 1, 10); EXPECT_CALL(*mock_request_handle_, PauseRequest()); BuildParallelRequests(); @@ -296,4 +309,15 @@ DestroyParallelJob(); } +// Test that parallel request is not created if the remaining content can be +// finish downloading soon. +TEST_F(ParallelDownloadJobTest, RemainingContentWillFinishSoon) { + DownloadItem::ReceivedSlices slices = {DownloadItem::ReceivedSlice(0, 99)}; + CreateParallelJob(99, 1, slices, 3, 1, 10); + BuildParallelRequests(); + EXPECT_EQ(0, static_cast<int>(job_->workers().size())); + + DestroyParallelJob(); +} + } // namespace content
diff --git a/content/browser/download/parallel_download_utils.cc b/content/browser/download/parallel_download_utils.cc index 5fe90436..cf47408 100644 --- a/content/browser/download/parallel_download_utils.cc +++ b/content/browser/download/parallel_download_utils.cc
@@ -33,6 +33,15 @@ // parallel requests after response of the original request is handled. const char kParallelRequestDelayFinchKey[] = "parallel_request_delay"; +// Finch parameter key value for the remaining time in seconds that is required +// to send parallel requests. +const char kParallelRequestRemainingTimeFinchKey[] = + "parallel_request_remaining_time"; + +// The default remaining download time in seconds required for parallel request +// creation. +const int kDefaultRemainingTimeInSeconds = 10; + // TODO(qinmin): replace this with a comparator operator in // DownloadItem::ReceivedSlice. bool compareReceivedSlices(const DownloadItem::ReceivedSlice& lhs, @@ -141,6 +150,15 @@ : base::TimeDelta::FromMilliseconds(0); } +base::TimeDelta GetParallelRequestRemainingTimeConfig() { + std::string finch_value = base::GetFieldTrialParamValueByFeature( + features::kParallelDownloading, kParallelRequestRemainingTimeFinchKey); + int time_in_seconds = 0; + return base::StringToInt(finch_value, &time_in_seconds) + ? base::TimeDelta::FromSeconds(time_in_seconds) + : base::TimeDelta::FromSeconds(kDefaultRemainingTimeInSeconds); +} + void DebugSlicesInfo(const DownloadItem::ReceivedSlices& slices) { DVLOG(1) << "Received slices size : " << slices.size(); for (const auto& it : slices) {
diff --git a/content/browser/download/parallel_download_utils.h b/content/browser/download/parallel_download_utils.h index 2fdbed9..3e334f7 100644 --- a/content/browser/download/parallel_download_utils.h +++ b/content/browser/download/parallel_download_utils.h
@@ -51,6 +51,9 @@ // request is handled. CONTENT_EXPORT base::TimeDelta GetParallelRequestDelayConfig(); +// Get the required remaining time before creating parallel requests. +CONTENT_EXPORT base::TimeDelta GetParallelRequestRemainingTimeConfig(); + // Print the states of received slices for debugging. CONTENT_EXPORT void DebugSlicesInfo(const DownloadItem::ReceivedSlices& slices);
diff --git a/content/browser/frame_host/render_widget_host_view_child_frame.cc b/content/browser/frame_host/render_widget_host_view_child_frame.cc index cc31069f..d32665c 100644 --- a/content/browser/frame_host/render_widget_host_view_child_frame.cc +++ b/content/browser/frame_host/render_widget_host_view_child_frame.cc
@@ -347,15 +347,15 @@ frame_connector_->BubbleScrollEvent(event); } -void RenderWidgetHostViewChildFrame::DidReceiveCompositorFrameAck() { - if (!host_) - return; - host_->SendReclaimCompositorResources(true /* is_swap_ack */, - cc::ReturnedResourceArray()); +void RenderWidgetHostViewChildFrame::DidReceiveCompositorFrameAck( + const cc::ReturnedResourceArray& resources) { + renderer_compositor_frame_sink_->DidReceiveCompositorFrameAck(resources); } -void RenderWidgetHostViewChildFrame::DidCreateNewRendererCompositorFrameSink() { +void RenderWidgetHostViewChildFrame::DidCreateNewRendererCompositorFrameSink( + cc::mojom::MojoCompositorFrameSinkClient* renderer_compositor_frame_sink) { ResetCompositorFrameSinkSupport(); + renderer_compositor_frame_sink_ = renderer_compositor_frame_sink; CreateCompositorFrameSinkSupport(); has_frame_ = false; } @@ -624,9 +624,7 @@ void RenderWidgetHostViewChildFrame::ReclaimResources( const cc::ReturnedResourceArray& resources) { - if (!host_) - return; - host_->SendReclaimCompositorResources(false /* is_swap_ack */, resources); + renderer_compositor_frame_sink_->ReclaimResources(resources); } void RenderWidgetHostViewChildFrame::OnBeginFrame( @@ -689,10 +687,12 @@ void RenderWidgetHostViewChildFrame::CreateCompositorFrameSinkSupport() { DCHECK(!support_); - support_ = base::MakeUnique<cc::CompositorFrameSinkSupport>( - this, GetSurfaceManager(), frame_sink_id_, false /* is_root */, - false /* handles_frame_sink_id_invalidation */, - true /* needs_sync_points */); + constexpr bool is_root = false; + constexpr bool handles_frame_sink_id_invalidation = false; + constexpr bool needs_sync_points = true; + support_ = cc::CompositorFrameSinkSupport::Create( + this, GetSurfaceManager(), frame_sink_id_, is_root, + handles_frame_sink_id_invalidation, needs_sync_points); if (parent_frame_sink_id_.is_valid()) { GetSurfaceManager()->RegisterFrameSinkHierarchy(parent_frame_sink_id_, frame_sink_id_);
diff --git a/content/browser/frame_host/render_widget_host_view_child_frame.h b/content/browser/frame_host/render_widget_host_view_child_frame.h index 244b248c..213581d2 100644 --- a/content/browser/frame_host/render_widget_host_view_child_frame.h +++ b/content/browser/frame_host/render_widget_host_view_child_frame.h
@@ -107,7 +107,9 @@ bool HasAcceleratedSurface(const gfx::Size& desired_size) override; void GestureEventAck(const blink::WebGestureEvent& event, InputEventAckState ack_result) override; - void DidCreateNewRendererCompositorFrameSink() override; + void DidCreateNewRendererCompositorFrameSink( + cc::mojom::MojoCompositorFrameSinkClient* renderer_compositor_frame_sink) + override; void SubmitCompositorFrame(const cc::LocalSurfaceId& local_surface_id, cc::CompositorFrame frame) override; void OnBeginFrameDidNotSwap(const cc::BeginFrameAck& ack) override; @@ -158,7 +160,8 @@ BrowserAccessibilityDelegate* delegate, bool for_root_frame) override; // cc::CompositorFrameSinkSupportClient implementation. - void DidReceiveCompositorFrameAck() override; + void DidReceiveCompositorFrameAck( + const cc::ReturnedResourceArray& resources) override; void OnBeginFrame(const cc::BeginFrameArgs& args) override; void ReclaimResources(const cc::ReturnedResourceArray& resources) override; void WillDrawSurface(const cc::LocalSurfaceId& id, @@ -256,6 +259,8 @@ cc::FrameSinkId parent_frame_sink_id_; bool has_frame_ = false; + cc::mojom::MojoCompositorFrameSinkClient* renderer_compositor_frame_sink_ = + nullptr; // The background color of the widget. SkColor background_color_;
diff --git a/content/browser/frame_host/render_widget_host_view_child_frame_unittest.cc b/content/browser/frame_host/render_widget_host_view_child_frame_unittest.cc index 86493be1c..f0934df 100644 --- a/content/browser/frame_host/render_widget_host_view_child_frame_unittest.cc +++ b/content/browser/frame_host/render_widget_host_view_child_frame_unittest.cc
@@ -30,6 +30,7 @@ #include "content/public/browser/render_widget_host_view.h" #include "content/public/test/mock_render_process_host.h" #include "content/public/test/test_browser_context.h" +#include "content/test/fake_renderer_compositor_frame_sink.h" #include "content/test/test_render_view_host.h" #include "testing/gtest/include/gtest/gtest.h" #include "ui/compositor/compositor.h" @@ -93,6 +94,17 @@ test_frame_connector_ = new MockCrossProcessFrameConnector(); view_->SetCrossProcessFrameConnector(test_frame_connector_); + + cc::mojom::MojoCompositorFrameSinkPtr sink; + cc::mojom::MojoCompositorFrameSinkRequest sink_request = + mojo::MakeRequest(&sink); + cc::mojom::MojoCompositorFrameSinkClientRequest client_request = + mojo::MakeRequest(&renderer_compositor_frame_sink_ptr_); + renderer_compositor_frame_sink_ = + base::MakeUnique<FakeRendererCompositorFrameSink>( + std::move(sink), std::move(client_request)); + view_->DidCreateNewRendererCompositorFrameSink( + renderer_compositor_frame_sink_ptr_.get()); } void TearDown() override { @@ -137,8 +149,13 @@ RenderWidgetHostImpl* widget_host_; RenderWidgetHostViewChildFrame* view_; MockCrossProcessFrameConnector* test_frame_connector_; + std::unique_ptr<FakeRendererCompositorFrameSink> + renderer_compositor_frame_sink_; private: + cc::mojom::MojoCompositorFrameSinkClientPtr + renderer_compositor_frame_sink_ptr_; + DISALLOW_COPY_AND_ASSIGN(RenderWidgetHostViewChildFrameTest); };
diff --git a/content/browser/frame_host/render_widget_host_view_guest.cc b/content/browser/frame_host/render_widget_host_view_guest.cc index 30321c4..fc720a7 100644 --- a/content/browser/frame_host/render_widget_host_view_guest.cc +++ b/content/browser/frame_host/render_widget_host_view_guest.cc
@@ -443,6 +443,14 @@ return platform_view_->UnlockMouse(); } +void RenderWidgetHostViewGuest::DidCreateNewRendererCompositorFrameSink( + cc::mojom::MojoCompositorFrameSinkClient* renderer_compositor_frame_sink) { + RenderWidgetHostViewChildFrame::DidCreateNewRendererCompositorFrameSink( + renderer_compositor_frame_sink); + platform_view_->DidCreateNewRendererCompositorFrameSink( + renderer_compositor_frame_sink); +} + #if defined(OS_MACOSX) void RenderWidgetHostViewGuest::SetActive(bool active) { platform_view_->SetActive(active);
diff --git a/content/browser/frame_host/render_widget_host_view_guest.h b/content/browser/frame_host/render_widget_host_view_guest.h index 963bb13..e2db9b1 100644 --- a/content/browser/frame_host/render_widget_host_view_guest.h +++ b/content/browser/frame_host/render_widget_host_view_guest.h
@@ -105,6 +105,9 @@ bool LockMouse() override; void UnlockMouse() override; + void DidCreateNewRendererCompositorFrameSink( + cc::mojom::MojoCompositorFrameSinkClient* renderer_compositor_frame_sink) + override; #if defined(OS_MACOSX) // RenderWidgetHostView implementation.
diff --git a/content/browser/frame_host/render_widget_host_view_guest_unittest.cc b/content/browser/frame_host/render_widget_host_view_guest_unittest.cc index 0a24bdeb..e2eff57 100644 --- a/content/browser/frame_host/render_widget_host_view_guest_unittest.cc +++ b/content/browser/frame_host/render_widget_host_view_guest_unittest.cc
@@ -26,6 +26,7 @@ #include "content/public/browser/render_widget_host_view.h" #include "content/public/test/mock_render_process_host.h" #include "content/public/test/test_browser_context.h" +#include "content/test/fake_renderer_compositor_frame_sink.h" #include "content/test/test_render_view_host.h" #include "content/test/test_web_contents.h" #include "testing/gtest/include/gtest/gtest.h" @@ -168,6 +169,16 @@ view_ = RenderWidgetHostViewGuest::Create( widget_host_, browser_plugin_guest_, (new TestRenderWidgetHostView(widget_host_))->GetWeakPtr()); + cc::mojom::MojoCompositorFrameSinkPtr sink; + cc::mojom::MojoCompositorFrameSinkRequest sink_request = + mojo::MakeRequest(&sink); + cc::mojom::MojoCompositorFrameSinkClientRequest client_request = + mojo::MakeRequest(&renderer_compositor_frame_sink_ptr_); + renderer_compositor_frame_sink_ = + base::MakeUnique<FakeRendererCompositorFrameSink>( + std::move(sink), std::move(client_request)); + view_->DidCreateNewRendererCompositorFrameSink( + renderer_compositor_frame_sink_ptr_.get()); } void TearDown() override { @@ -205,8 +216,12 @@ // destruction. RenderWidgetHostImpl* widget_host_; RenderWidgetHostViewGuest* view_; + std::unique_ptr<FakeRendererCompositorFrameSink> + renderer_compositor_frame_sink_; private: + cc::mojom::MojoCompositorFrameSinkClientPtr + renderer_compositor_frame_sink_ptr_; DISALLOW_COPY_AND_ASSIGN(RenderWidgetHostViewGuestSurfaceTest); };
diff --git a/content/browser/gpu/gpu_data_manager_impl_private.cc b/content/browser/gpu/gpu_data_manager_impl_private.cc index 335958f..4dbdce1 100644 --- a/content/browser/gpu/gpu_data_manager_impl_private.cc +++ b/content/browser/gpu/gpu_data_manager_impl_private.cc
@@ -386,6 +386,7 @@ // TODO(zmo): Other features might also be OK to ignore here. feature_diffs.erase(gpu::GPU_FEATURE_TYPE_ACCELERATED_WEBGL); feature_diffs.erase(gpu::GPU_FEATURE_TYPE_WEBGL2); + feature_diffs.erase(gpu::GPU_FEATURE_TYPE_ACCELERATED_2D_CANVAS); } if (feature_diffs.size()) { if (reason) { @@ -1266,12 +1267,33 @@ switches::kDisableSoftwareRasterizer)) { use_swiftshader_ = true; - // Remove all previously recorded GPU info - gpu_info_ = gpu::GPUInfo(); - // Set some basic info to identify the GPU as SwiftShader + // Adjust GPU info for SwiftShader. Most of this data only affects the + // chrome://gpu page, so it doesn't require querying the implementation. + // It is important to reset the video and image decode/encode capabilities, + // to prevent attempts to use them (crbug.com/702417). + gpu_info_.driver_vendor = "Google Inc."; + gpu_info_.driver_version = "3.3.0.2"; + gpu_info_.driver_date = "2017/04/07"; + gpu_info_.pixel_shader_version = "3.0"; + gpu_info_.vertex_shader_version = "3.0"; + gpu_info_.max_msaa_samples = "4"; + gpu_info_.gl_version = "OpenGL ES 2.0 SwiftShader"; gpu_info_.gl_vendor = "Google Inc."; gpu_info_.gl_renderer = "Google SwiftShader"; + gpu_info_.gl_extensions = ""; + gpu_info_.gl_reset_notification_strategy = 0; gpu_info_.software_rendering = true; + gpu_info_.passthrough_cmd_decoder = false; + gpu_info_.supports_overlays = false; + gpu_info_.basic_info_state = gpu::kCollectInfoSuccess; + gpu_info_.context_info_state = gpu::kCollectInfoSuccess; + gpu_info_.video_decode_accelerator_capabilities = {}; + gpu_info_.video_encode_accelerator_supported_profiles = {}; + gpu_info_.jpeg_decode_accelerator_supported = false; + + gpu_info_.gpu.active = false; + for (auto& secondary_gpu : gpu_info_.secondary_gpus) + secondary_gpu.active = false; for (auto& status : gpu_feature_info_.status_values) status = gpu::kGpuFeatureStatusBlacklisted;
diff --git a/content/browser/gpu/gpu_data_manager_impl_private_unittest.cc b/content/browser/gpu/gpu_data_manager_impl_private_unittest.cc index 86c525d..137e9ca 100644 --- a/content/browser/gpu/gpu_data_manager_impl_private_unittest.cc +++ b/content/browser/gpu/gpu_data_manager_impl_private_unittest.cc
@@ -185,8 +185,8 @@ manager->GetBlacklistedFeatureCount()); EXPECT_TRUE(manager->IsFeatureBlacklisted(gpu::GPU_FEATURE_TYPE_WEBGL2)); } else { - EXPECT_FALSE(manager->GpuAccessAllowed(&reason)); - EXPECT_FALSE(reason.empty()); + EXPECT_TRUE(manager->GpuAccessAllowed(&reason)); + EXPECT_TRUE(reason.empty()); EXPECT_EQ(2u, manager->GetBlacklistedFeatureCount()); EXPECT_FALSE(manager->IsFeatureBlacklisted(gpu::GPU_FEATURE_TYPE_WEBGL2)); } @@ -570,7 +570,12 @@ // Not enough GPUInfo. EXPECT_TRUE(manager->GpuAccessAllowed(NULL)); - EXPECT_EQ(1u, manager->GetBlacklistedFeatureCount()); + if (manager->ShouldUseSwiftShader()) { + EXPECT_EQ(static_cast<size_t>(gpu::NUMBER_OF_GPU_FEATURE_TYPES), + manager->GetBlacklistedFeatureCount()); + } else { + EXPECT_EQ(1u, manager->GetBlacklistedFeatureCount()); + } // Now assume browser gets GL strings from local state. // The entry applies, blacklist more features than from the preliminary step. @@ -578,7 +583,12 @@ // happens before renderer launching. manager->SetGLStrings(kGLVendorMesa, kGLRendererMesa, kGLVersionMesa801); EXPECT_TRUE(manager->GpuAccessAllowed(NULL)); - EXPECT_EQ(1u, manager->GetBlacklistedFeatureCount()); + if (manager->ShouldUseSwiftShader()) { + EXPECT_EQ(static_cast<size_t>(gpu::NUMBER_OF_GPU_FEATURE_TYPES), + manager->GetBlacklistedFeatureCount()); + } else { + EXPECT_EQ(1u, manager->GetBlacklistedFeatureCount()); + } EXPECT_TRUE( manager->IsFeatureBlacklisted(gpu::GPU_FEATURE_TYPE_ACCELERATED_WEBGL)); } @@ -611,7 +621,12 @@ // Full GPUInfo, the entry applies. EXPECT_TRUE(manager->GpuAccessAllowed(NULL)); - EXPECT_EQ(1u, manager->GetBlacklistedFeatureCount()); + if (manager->ShouldUseSwiftShader()) { + EXPECT_EQ(static_cast<size_t>(gpu::NUMBER_OF_GPU_FEATURE_TYPES), + manager->GetBlacklistedFeatureCount()); + } else { + EXPECT_EQ(1u, manager->GetBlacklistedFeatureCount()); + } EXPECT_TRUE( manager->IsFeatureBlacklisted(gpu::GPU_FEATURE_TYPE_ACCELERATED_WEBGL)); @@ -620,7 +635,12 @@ // (Otherwise the entry should not apply.) manager->SetGLStrings(kGLVendorMesa, kGLRendererMesa, kGLVersionMesa802); EXPECT_TRUE(manager->GpuAccessAllowed(NULL)); - EXPECT_EQ(1u, manager->GetBlacklistedFeatureCount()); + if (manager->ShouldUseSwiftShader()) { + EXPECT_EQ(static_cast<size_t>(gpu::NUMBER_OF_GPU_FEATURE_TYPES), + manager->GetBlacklistedFeatureCount()); + } else { + EXPECT_EQ(1u, manager->GetBlacklistedFeatureCount()); + } EXPECT_TRUE( manager->IsFeatureBlacklisted(gpu::GPU_FEATURE_TYPE_ACCELERATED_WEBGL)); } @@ -651,7 +671,13 @@ manager->InitializeForTesting(kData, gpu_info); EXPECT_TRUE(manager->GpuAccessAllowed(NULL)); - EXPECT_EQ(1u, manager->GetBlacklistedFeatureCount()); + if (manager->ShouldUseSwiftShader()) { + EXPECT_EQ(static_cast<size_t>(gpu::NUMBER_OF_GPU_FEATURE_TYPES), + manager->GetBlacklistedFeatureCount()); + } else { + EXPECT_EQ(1u, manager->GetBlacklistedFeatureCount()); + } + EXPECT_TRUE( manager->IsFeatureBlacklisted(gpu::GPU_FEATURE_TYPE_ACCELERATED_WEBGL)); } @@ -745,20 +771,18 @@ run_loop.RunUntilIdle(); } EXPECT_TRUE(observer.gpu_info_updated()); - EXPECT_EQ(static_cast<size_t>(gpu::NUMBER_OF_GPU_FEATURE_TYPES), manager->GetBlacklistedFeatureCount()); } else { EXPECT_EQ(1u, manager->GetBlacklistedFeatureCount()); - // Update with the same Intel GPU active. + // Update to previous Intel GPU. EXPECT_FALSE(manager->UpdateActiveGpu(0x8086, 0x04a1)); { base::RunLoop run_loop; run_loop.RunUntilIdle(); } EXPECT_FALSE(observer.gpu_info_updated()); - EXPECT_EQ(1u, manager->GetBlacklistedFeatureCount()); } @@ -779,24 +803,18 @@ observer.Reset(); EXPECT_FALSE(observer.gpu_info_updated()); + // Update to previous NVIDIA GPU. + EXPECT_FALSE(manager->UpdateActiveGpu(0x10de, 0x0640)); + { + base::RunLoop run_loop; + run_loop.RunUntilIdle(); + } + EXPECT_FALSE(observer.gpu_info_updated()); + if (manager->ShouldUseSwiftShader()) { - // Update to previous NVIDIA GPU. - EXPECT_TRUE(manager->UpdateActiveGpu(0x10de, 0x0640)); - { - base::RunLoop run_loop; - run_loop.RunUntilIdle(); - } - EXPECT_TRUE(observer.gpu_info_updated()); EXPECT_EQ(static_cast<size_t>(gpu::NUMBER_OF_GPU_FEATURE_TYPES), manager->GetBlacklistedFeatureCount()); } else { - // Update with the same NVIDIA GPU active. - EXPECT_FALSE(manager->UpdateActiveGpu(0x10de, 0x0640)); - { - base::RunLoop run_loop; - run_loop.RunUntilIdle(); - } - EXPECT_FALSE(observer.gpu_info_updated()); EXPECT_EQ(0u, manager->GetBlacklistedFeatureCount()); }
diff --git a/content/browser/gpu/gpu_process_host.cc b/content/browser/gpu/gpu_process_host.cc index 7e11be1b..39d00af7 100644 --- a/content/browser/gpu/gpu_process_host.cc +++ b/content/browser/gpu/gpu_process_host.cc
@@ -171,7 +171,8 @@ switches::kGpuTestingGLVersion, switches::kDisableGpuDriverBugWorkarounds, switches::kUsePassthroughCmdDecoder, - switches::kEnableHDR}; + switches::kEnableHDR, + switches::kIgnoreGpuBlacklist}; enum GPUProcessLifetimeEvent { LAUNCHED,
diff --git a/content/browser/indexed_db/cursor_impl.cc b/content/browser/indexed_db/cursor_impl.cc index 86d0e8f..15382eb 100644 --- a/content/browser/indexed_db/cursor_impl.cc +++ b/content/browser/indexed_db/cursor_impl.cc
@@ -5,13 +5,14 @@ #include "content/browser/indexed_db/cursor_impl.h" #include "base/memory/ptr_util.h" -#include "base/threading/thread_task_runner_handle.h" +#include "base/sequenced_task_runner.h" #include "content/browser/indexed_db/indexed_db_callbacks.h" #include "content/browser/indexed_db/indexed_db_cursor.h" #include "content/browser/indexed_db/indexed_db_dispatcher_host.h" namespace content { +// Expected to be constructed on IO thread, and used/destroyed on IDB thread. class CursorImpl::IDBThreadHelper { public: explicit IDBThreadHelper(std::unique_ptr<IndexedDBCursor> cursor); @@ -25,20 +26,19 @@ void PrefetchReset(int32_t used_prefetches, int32_t unused_prefetches); private: - scoped_refptr<IndexedDBDispatcherHost> dispatcher_host_; std::unique_ptr<IndexedDBCursor> cursor_; - const url::Origin origin_; DISALLOW_COPY_AND_ASSIGN(IDBThreadHelper); }; CursorImpl::CursorImpl(std::unique_ptr<IndexedDBCursor> cursor, const url::Origin& origin, - scoped_refptr<IndexedDBDispatcherHost> dispatcher_host) + IndexedDBDispatcherHost* dispatcher_host, + scoped_refptr<base::SequencedTaskRunner> idb_runner) : helper_(new IDBThreadHelper(std::move(cursor))), - dispatcher_host_(std::move(dispatcher_host)), + dispatcher_host_(dispatcher_host), origin_(origin), - idb_runner_(base::ThreadTaskRunnerHandle::Get()) {} + idb_runner_(std::move(idb_runner)) {} CursorImpl::~CursorImpl() { idb_runner_->DeleteSoon(FROM_HERE, helper_); @@ -47,8 +47,9 @@ void CursorImpl::Advance( uint32_t count, ::indexed_db::mojom::CallbacksAssociatedPtrInfo callbacks_info) { - scoped_refptr<IndexedDBCallbacks> callbacks(new IndexedDBCallbacks( - dispatcher_host_.get(), origin_, std::move(callbacks_info))); + scoped_refptr<IndexedDBCallbacks> callbacks( + new IndexedDBCallbacks(dispatcher_host_->AsWeakPtr(), origin_, + std::move(callbacks_info), idb_runner_)); idb_runner_->PostTask(FROM_HERE, base::Bind(&IDBThreadHelper::Advance, base::Unretained(helper_), count, base::Passed(&callbacks))); @@ -58,8 +59,9 @@ const IndexedDBKey& key, const IndexedDBKey& primary_key, ::indexed_db::mojom::CallbacksAssociatedPtrInfo callbacks_info) { - scoped_refptr<IndexedDBCallbacks> callbacks(new IndexedDBCallbacks( - dispatcher_host_.get(), origin_, std::move(callbacks_info))); + scoped_refptr<IndexedDBCallbacks> callbacks( + new IndexedDBCallbacks(dispatcher_host_->AsWeakPtr(), origin_, + std::move(callbacks_info), idb_runner_)); idb_runner_->PostTask( FROM_HERE, base::Bind(&IDBThreadHelper::Continue, base::Unretained(helper_), key, @@ -69,8 +71,9 @@ void CursorImpl::Prefetch( int32_t count, ::indexed_db::mojom::CallbacksAssociatedPtrInfo callbacks_info) { - scoped_refptr<IndexedDBCallbacks> callbacks(new IndexedDBCallbacks( - dispatcher_host_.get(), origin_, std::move(callbacks_info))); + scoped_refptr<IndexedDBCallbacks> callbacks( + new IndexedDBCallbacks(dispatcher_host_->AsWeakPtr(), origin_, + std::move(callbacks_info), idb_runner_)); idb_runner_->PostTask(FROM_HERE, base::Bind(&IDBThreadHelper::Prefetch, base::Unretained(helper_), count, base::Passed(&callbacks)));
diff --git a/content/browser/indexed_db/cursor_impl.h b/content/browser/indexed_db/cursor_impl.h index 69254289c..9806765 100644 --- a/content/browser/indexed_db/cursor_impl.h +++ b/content/browser/indexed_db/cursor_impl.h
@@ -11,7 +11,7 @@ #include "content/common/indexed_db/indexed_db.mojom.h" namespace base { -class SingleThreadTaskRunner; +class SequencedTaskRunner; } namespace content { @@ -20,11 +20,13 @@ class IndexedDBDispatcherHost; class IndexedDBKey; +// Expected to be constructed, called, and destructed on the IO thread. class CursorImpl : public ::indexed_db::mojom::Cursor { public: CursorImpl(std::unique_ptr<IndexedDBCursor> cursor, const url::Origin& origin, - scoped_refptr<IndexedDBDispatcherHost> dispatcher_host); + IndexedDBDispatcherHost* dispatcher_host, + scoped_refptr<base::SequencedTaskRunner> idb_runner); ~CursorImpl() override; // ::indexed_db::mojom::Cursor implementation @@ -47,9 +49,11 @@ class IDBThreadHelper; IDBThreadHelper* helper_; - scoped_refptr<IndexedDBDispatcherHost> dispatcher_host_; + // This raw pointer is safe because all CursorImpl instances are owned by an + // IndexedDBDispatcherHost. + IndexedDBDispatcherHost* dispatcher_host_; const url::Origin origin_; - scoped_refptr<base::SingleThreadTaskRunner> idb_runner_; + scoped_refptr<base::SequencedTaskRunner> idb_runner_; DISALLOW_COPY_AND_ASSIGN(CursorImpl); };
diff --git a/content/browser/indexed_db/database_impl.cc b/content/browser/indexed_db/database_impl.cc index 4a22cda5..beb3da9 100644 --- a/content/browser/indexed_db/database_impl.cc +++ b/content/browser/indexed_db/database_impl.cc
@@ -6,6 +6,8 @@ #include "base/memory/ptr_util.h" #include "base/metrics/histogram_macros.h" +#include "base/sequenced_task_runner.h" +#include "base/threading/thread_checker.h" #include "base/threading/thread_task_runner_handle.h" #include "content/browser/bad_message.h" #include "content/browser/child_process_security_policy_impl.h" @@ -28,13 +30,16 @@ const char kInvalidBlobFilePath[] = "Blob file path is invalid"; } // namespace +// Expect to be created on IO thread, and called/destroyed on IDB thread. class DatabaseImpl::IDBThreadHelper { public: IDBThreadHelper(std::unique_ptr<IndexedDBConnection> connection, const url::Origin& origin, - scoped_refptr<IndexedDBDispatcherHost> dispatcher_host); + scoped_refptr<IndexedDBContextImpl> indexed_db_context); ~IDBThreadHelper(); + void ConnectionOpened(); + void CreateObjectStore(int64_t transaction_id, int64_t object_store_id, const base::string16& name, @@ -130,21 +135,26 @@ void AckReceivedBlobs(const std::vector<std::string>& uuids); private: - scoped_refptr<IndexedDBDispatcherHost> dispatcher_host_; + scoped_refptr<IndexedDBContextImpl> indexed_db_context_; std::unique_ptr<IndexedDBConnection> connection_; const url::Origin origin_; + base::ThreadChecker idb_thread_checker_; base::WeakPtrFactory<IDBThreadHelper> weak_factory_; }; -DatabaseImpl::DatabaseImpl( - std::unique_ptr<IndexedDBConnection> connection, - const url::Origin& origin, - scoped_refptr<IndexedDBDispatcherHost> dispatcher_host) +DatabaseImpl::DatabaseImpl(std::unique_ptr<IndexedDBConnection> connection, + const url::Origin& origin, + IndexedDBDispatcherHost* dispatcher_host, + scoped_refptr<base::SequencedTaskRunner> idb_runner) : dispatcher_host_(dispatcher_host), origin_(origin), - idb_runner_(base::ThreadTaskRunnerHandle::Get()) { + idb_runner_(std::move(idb_runner)) { + DCHECK(connection); helper_ = new IDBThreadHelper(std::move(connection), origin, - std::move(dispatcher_host)); + dispatcher_host->context()); + idb_runner_->PostTask(FROM_HERE, + base::Bind(&IDBThreadHelper::ConnectionOpened, + base::Unretained(helper_))); } DatabaseImpl::~DatabaseImpl() { @@ -226,8 +236,9 @@ const IndexedDBKeyRange& key_range, bool key_only, ::indexed_db::mojom::CallbacksAssociatedPtrInfo callbacks_info) { - scoped_refptr<IndexedDBCallbacks> callbacks(new IndexedDBCallbacks( - dispatcher_host_.get(), origin_, std::move(callbacks_info))); + scoped_refptr<IndexedDBCallbacks> callbacks( + new IndexedDBCallbacks(dispatcher_host_->AsWeakPtr(), origin_, + std::move(callbacks_info), idb_runner_)); idb_runner_->PostTask( FROM_HERE, base::Bind(&IDBThreadHelper::Get, base::Unretained(helper_), transaction_id, object_store_id, index_id, @@ -242,8 +253,9 @@ bool key_only, int64_t max_count, ::indexed_db::mojom::CallbacksAssociatedPtrInfo callbacks_info) { - scoped_refptr<IndexedDBCallbacks> callbacks(new IndexedDBCallbacks( - dispatcher_host_.get(), origin_, std::move(callbacks_info))); + scoped_refptr<IndexedDBCallbacks> callbacks( + new IndexedDBCallbacks(dispatcher_host_->AsWeakPtr(), origin_, + std::move(callbacks_info), idb_runner_)); idb_runner_->PostTask( FROM_HERE, base::Bind(&IDBThreadHelper::GetAll, base::Unretained(helper_), @@ -262,8 +274,9 @@ ChildProcessSecurityPolicyImpl* policy = ChildProcessSecurityPolicyImpl::GetInstance(); - scoped_refptr<IndexedDBCallbacks> callbacks(new IndexedDBCallbacks( - dispatcher_host_.get(), origin_, std::move(callbacks_info))); + scoped_refptr<IndexedDBCallbacks> callbacks( + new IndexedDBCallbacks(dispatcher_host_->AsWeakPtr(), origin_, + std::move(callbacks_info), idb_runner_)); std::vector<std::unique_ptr<storage::BlobDataHandle>> handles( value->blob_or_file_info.size()); @@ -351,8 +364,9 @@ bool key_only, blink::WebIDBTaskType task_type, ::indexed_db::mojom::CallbacksAssociatedPtrInfo callbacks_info) { - scoped_refptr<IndexedDBCallbacks> callbacks(new IndexedDBCallbacks( - dispatcher_host_.get(), origin_, std::move(callbacks_info))); + scoped_refptr<IndexedDBCallbacks> callbacks( + new IndexedDBCallbacks(dispatcher_host_->AsWeakPtr(), origin_, + std::move(callbacks_info), idb_runner_)); idb_runner_->PostTask( FROM_HERE, base::Bind(&IDBThreadHelper::OpenCursor, base::Unretained(helper_), @@ -366,8 +380,9 @@ int64_t index_id, const IndexedDBKeyRange& key_range, ::indexed_db::mojom::CallbacksAssociatedPtrInfo callbacks_info) { - scoped_refptr<IndexedDBCallbacks> callbacks(new IndexedDBCallbacks( - dispatcher_host_.get(), origin_, std::move(callbacks_info))); + scoped_refptr<IndexedDBCallbacks> callbacks( + new IndexedDBCallbacks(dispatcher_host_->AsWeakPtr(), origin_, + std::move(callbacks_info), idb_runner_)); idb_runner_->PostTask( FROM_HERE, base::Bind(&IDBThreadHelper::Count, base::Unretained(helper_), transaction_id, object_store_id, index_id, @@ -379,8 +394,9 @@ int64_t object_store_id, const IndexedDBKeyRange& key_range, ::indexed_db::mojom::CallbacksAssociatedPtrInfo callbacks_info) { - scoped_refptr<IndexedDBCallbacks> callbacks(new IndexedDBCallbacks( - dispatcher_host_.get(), origin_, std::move(callbacks_info))); + scoped_refptr<IndexedDBCallbacks> callbacks( + new IndexedDBCallbacks(dispatcher_host_->AsWeakPtr(), origin_, + std::move(callbacks_info), idb_runner_)); idb_runner_->PostTask( FROM_HERE, base::Bind(&IDBThreadHelper::DeleteRange, base::Unretained(helper_), @@ -392,8 +408,9 @@ int64_t transaction_id, int64_t object_store_id, ::indexed_db::mojom::CallbacksAssociatedPtrInfo callbacks_info) { - scoped_refptr<IndexedDBCallbacks> callbacks(new IndexedDBCallbacks( - dispatcher_host_.get(), origin_, std::move(callbacks_info))); + scoped_refptr<IndexedDBCallbacks> callbacks( + new IndexedDBCallbacks(dispatcher_host_->AsWeakPtr(), origin_, + std::move(callbacks_info), idb_runner_)); idb_runner_->PostTask( FROM_HERE, base::Bind(&IDBThreadHelper::Clear, base::Unretained(helper_), @@ -453,18 +470,25 @@ DatabaseImpl::IDBThreadHelper::IDBThreadHelper( std::unique_ptr<IndexedDBConnection> connection, const url::Origin& origin, - scoped_refptr<IndexedDBDispatcherHost> dispatcher_host) - : dispatcher_host_(std::move(dispatcher_host)), + scoped_refptr<IndexedDBContextImpl> indexed_db_context) + : indexed_db_context_(indexed_db_context), connection_(std::move(connection)), origin_(origin), weak_factory_(this) { - dispatcher_host_->context()->ConnectionOpened(origin_, connection.get()); + DCHECK_CURRENTLY_ON(BrowserThread::IO); + idb_thread_checker_.DetachFromThread(); } DatabaseImpl::IDBThreadHelper::~IDBThreadHelper() { + DCHECK(idb_thread_checker_.CalledOnValidThread()); if (connection_->IsConnected()) connection_->Close(); - dispatcher_host_->context()->ConnectionClosed(origin_, connection_.get()); + indexed_db_context_->ConnectionClosed(origin_, connection_.get()); +} + +void DatabaseImpl::IDBThreadHelper::ConnectionOpened() { + DCHECK(idb_thread_checker_.CalledOnValidThread()); + indexed_db_context_->ConnectionOpened(origin_, connection_.get()); } void DatabaseImpl::IDBThreadHelper::CreateObjectStore( @@ -473,6 +497,7 @@ const base::string16& name, const IndexedDBKeyPath& key_path, bool auto_increment) { + DCHECK(idb_thread_checker_.CalledOnValidThread()); if (!connection_->IsConnected()) return; @@ -487,6 +512,7 @@ void DatabaseImpl::IDBThreadHelper::DeleteObjectStore(int64_t transaction_id, int64_t object_store_id) { + DCHECK(idb_thread_checker_.CalledOnValidThread()); if (!connection_->IsConnected()) return; @@ -502,6 +528,7 @@ int64_t transaction_id, int64_t object_store_id, const base::string16& new_name) { + DCHECK(idb_thread_checker_.CalledOnValidThread()); if (!connection_->IsConnected()) return; @@ -518,6 +545,7 @@ int64_t transaction_id, const std::vector<int64_t>& object_store_ids, blink::WebIDBTransactionMode mode) { + DCHECK(idb_thread_checker_.CalledOnValidThread()); if (!connection_->IsConnected()) return; @@ -526,6 +554,7 @@ } void DatabaseImpl::IDBThreadHelper::Close() { + DCHECK(idb_thread_checker_.CalledOnValidThread()); if (!connection_->IsConnected()) return; @@ -533,6 +562,7 @@ } void DatabaseImpl::IDBThreadHelper::VersionChangeIgnored() { + DCHECK(idb_thread_checker_.CalledOnValidThread()); if (!connection_->IsConnected()) return; @@ -545,6 +575,7 @@ bool no_records, bool values, uint16_t operation_types) { + DCHECK(idb_thread_checker_.CalledOnValidThread()); if (!connection_->IsConnected()) return; @@ -561,6 +592,7 @@ void DatabaseImpl::IDBThreadHelper::RemoveObservers( const std::vector<int32_t>& observers) { + DCHECK(idb_thread_checker_.CalledOnValidThread()); if (!connection_->IsConnected()) return; @@ -574,6 +606,7 @@ const IndexedDBKeyRange& key_range, bool key_only, scoped_refptr<IndexedDBCallbacks> callbacks) { + DCHECK(idb_thread_checker_.CalledOnValidThread()); if (!connection_->IsConnected()) return; @@ -595,6 +628,7 @@ bool key_only, int64_t max_count, scoped_refptr<IndexedDBCallbacks> callbacks) { + DCHECK(idb_thread_checker_.CalledOnValidThread()); if (!connection_->IsConnected()) return; @@ -619,6 +653,7 @@ blink::WebIDBPutMode mode, const std::vector<IndexedDBIndexKeys>& index_keys, scoped_refptr<IndexedDBCallbacks> callbacks) { + DCHECK(idb_thread_checker_.CalledOnValidThread()); if (!connection_->IsConnected()) return; @@ -645,6 +680,7 @@ int64_t object_store_id, const IndexedDBKey& primary_key, const std::vector<IndexedDBIndexKeys>& index_keys) { + DCHECK(idb_thread_checker_.CalledOnValidThread()); if (!connection_->IsConnected()) return; @@ -662,6 +698,7 @@ int64_t transaction_id, int64_t object_store_id, const std::vector<int64_t>& index_ids) { + DCHECK(idb_thread_checker_.CalledOnValidThread()); if (!connection_->IsConnected()) return; @@ -683,6 +720,7 @@ bool key_only, blink::WebIDBTaskType task_type, scoped_refptr<IndexedDBCallbacks> callbacks) { + DCHECK(idb_thread_checker_.CalledOnValidThread()); if (!connection_->IsConnected()) return; @@ -703,6 +741,7 @@ int64_t index_id, const IndexedDBKeyRange& key_range, scoped_refptr<IndexedDBCallbacks> callbacks) { + DCHECK(idb_thread_checker_.CalledOnValidThread()); if (!connection_->IsConnected()) return; @@ -738,6 +777,7 @@ int64_t transaction_id, int64_t object_store_id, scoped_refptr<IndexedDBCallbacks> callbacks) { + DCHECK(idb_thread_checker_.CalledOnValidThread()); if (!connection_->IsConnected()) return; @@ -757,6 +797,7 @@ const IndexedDBKeyPath& key_path, bool unique, bool multi_entry) { + DCHECK(idb_thread_checker_.CalledOnValidThread()); if (!connection_->IsConnected()) return; @@ -772,6 +813,7 @@ void DatabaseImpl::IDBThreadHelper::DeleteIndex(int64_t transaction_id, int64_t object_store_id, int64_t index_id) { + DCHECK(idb_thread_checker_.CalledOnValidThread()); if (!connection_->IsConnected()) return; @@ -788,6 +830,7 @@ int64_t object_store_id, int64_t index_id, const base::string16& new_name) { + DCHECK(idb_thread_checker_.CalledOnValidThread()); if (!connection_->IsConnected()) return; @@ -801,6 +844,7 @@ } void DatabaseImpl::IDBThreadHelper::Abort(int64_t transaction_id) { + DCHECK(idb_thread_checker_.CalledOnValidThread()); if (!connection_->IsConnected()) return; @@ -815,6 +859,7 @@ void DatabaseImpl::IDBThreadHelper::AbortWithError( int64_t transaction_id, const IndexedDBDatabaseError& error) { + DCHECK(idb_thread_checker_.CalledOnValidThread()); if (!connection_->IsConnected()) return; @@ -827,6 +872,7 @@ } void DatabaseImpl::IDBThreadHelper::Commit(int64_t transaction_id) { + DCHECK(idb_thread_checker_.CalledOnValidThread()); if (!connection_->IsConnected()) return; @@ -841,8 +887,8 @@ return; } - dispatcher_host_->context()->quota_manager_proxy()->GetUsageAndQuota( - dispatcher_host_->context()->TaskRunner(), origin_.GetURL(), + indexed_db_context_->quota_manager_proxy()->GetUsageAndQuota( + indexed_db_context_->TaskRunner(), origin_.GetURL(), storage::kStorageTypeTemporary, base::Bind(&IDBThreadHelper::OnGotUsageAndQuotaForCommit, weak_factory_.GetWeakPtr(), transaction_id)); @@ -853,6 +899,7 @@ storage::QuotaStatusCode status, int64_t usage, int64_t quota) { + DCHECK(idb_thread_checker_.CalledOnValidThread()); // May have disconnected while quota check was pending. if (!connection_->IsConnected()) return;
diff --git a/content/browser/indexed_db/database_impl.h b/content/browser/indexed_db/database_impl.h index bb5e9f0..e0bb029 100644 --- a/content/browser/indexed_db/database_impl.h +++ b/content/browser/indexed_db/database_impl.h
@@ -9,16 +9,22 @@ #include "base/memory/ref_counted.h" #include "content/common/indexed_db/indexed_db.mojom.h" +namespace base { +class SequencedTaskRunner; +} + namespace content { class IndexedDBConnection; class IndexedDBDispatcherHost; +// Expected to be constructed, called, and destructed on the IO thread. class DatabaseImpl : public ::indexed_db::mojom::Database { public: explicit DatabaseImpl(std::unique_ptr<IndexedDBConnection> connection, const url::Origin& origin, - scoped_refptr<IndexedDBDispatcherHost> dispatcher_host); + IndexedDBDispatcherHost* dispatcher_host, + scoped_refptr<base::SequencedTaskRunner> idb_runner); ~DatabaseImpl() override; // ::indexed_db::mojom::Database implementation @@ -60,7 +66,7 @@ ::indexed_db::mojom::CallbacksAssociatedPtrInfo callbacks) override; void Put(int64_t transaction_id, int64_t object_store_id, - indexed_db::mojom::ValuePtr value, + ::indexed_db::mojom::ValuePtr value, const IndexedDBKey& key, blink::WebIDBPutMode mode, const std::vector<IndexedDBIndexKeys>& index_keys, @@ -118,9 +124,11 @@ class IDBThreadHelper; IDBThreadHelper* helper_; - scoped_refptr<IndexedDBDispatcherHost> dispatcher_host_; + // This raw pointer is safe because all DatabaseImpl instances are owned by + // an IndexedDBDispatcherHost. + IndexedDBDispatcherHost* dispatcher_host_; const url::Origin origin_; - scoped_refptr<base::SingleThreadTaskRunner> idb_runner_; + scoped_refptr<base::SequencedTaskRunner> idb_runner_; DISALLOW_COPY_AND_ASSIGN(DatabaseImpl); };
diff --git a/content/browser/indexed_db/indexed_db_callbacks.cc b/content/browser/indexed_db/indexed_db_callbacks.cc index ceb8e13..3cd348c5 100644 --- a/content/browser/indexed_db/indexed_db_callbacks.cc +++ b/content/browser/indexed_db/indexed_db_callbacks.cc
@@ -7,11 +7,14 @@ #include <stddef.h> #include <algorithm> +#include <memory> #include <utility> #include "base/memory/ptr_util.h" #include "base/metrics/histogram_macros.h" +#include "base/sequenced_task_runner.h" #include "base/strings/utf_string_conversions.h" +#include "base/threading/thread_task_runner_handle.h" #include "base/time/time.h" #include "content/browser/child_process_security_policy_impl.h" #include "content/browser/fileapi/fileapi_message_filter.h" @@ -27,6 +30,7 @@ #include "content/browser/indexed_db/indexed_db_value.h" #include "content/common/indexed_db/indexed_db_constants.h" #include "content/common/indexed_db/indexed_db_metadata.h" +#include "content/public/browser/browser_thread.h" #include "mojo/public/cpp/bindings/strong_associated_binding.h" #include "storage/browser/blob/blob_storage_context.h" #include "storage/browser/blob/shareable_file_reference.h" @@ -40,6 +44,34 @@ namespace { +// If this is destructed with the connection still living inside it, we assume +// we have been killed due to IO thread shutdown, and we need to safely schedule +// the destruction of the connection on the IDB thread, as we should still be in +// a transaction's operation queue, where we cannot destroy the transaction. +struct SafeIOThreadConnectionWrapper { + SafeIOThreadConnectionWrapper(std::unique_ptr<IndexedDBConnection> connection) + : connection(std::move(connection)), + idb_runner(base::ThreadTaskRunnerHandle::Get()) {} + ~SafeIOThreadConnectionWrapper() { + if (connection) { + idb_runner->PostTask( + FROM_HERE, base::Bind( + [](std::unique_ptr<IndexedDBConnection> connection) { + connection->ForceClose(); + }, + base::Passed(&connection))); + } + } + SafeIOThreadConnectionWrapper(SafeIOThreadConnectionWrapper&& other) = + default; + + std::unique_ptr<IndexedDBConnection> connection; + scoped_refptr<base::SequencedTaskRunner> idb_runner; + + private: + DISALLOW_COPY_AND_ASSIGN(SafeIOThreadConnectionWrapper); +}; + void ConvertBlobInfo( const std::vector<IndexedDBBlobInfo>& blob_info, std::vector<::indexed_db::mojom::BlobInfoPtr>* blob_or_file_info) { @@ -78,23 +110,26 @@ } // namespace +// Expected to be created and called from IO thread. class IndexedDBCallbacks::IOThreadHelper { public: IOThreadHelper(CallbacksAssociatedPtrInfo callbacks_info, - scoped_refptr<IndexedDBDispatcherHost> dispatcher_host); + base::WeakPtr<IndexedDBDispatcherHost> dispatcher_host, + url::Origin origin, + scoped_refptr<base::SequencedTaskRunner> idb_runner); ~IOThreadHelper(); void SendError(const IndexedDBDatabaseError& error); void SendSuccessStringList(const std::vector<base::string16>& value); void SendBlocked(int64_t existing_version); - void SendUpgradeNeeded(std::unique_ptr<DatabaseImpl> database, + void SendUpgradeNeeded(SafeIOThreadConnectionWrapper connection, int64_t old_version, blink::WebIDBDataLoss data_loss, const std::string& data_loss_message, const content::IndexedDBDatabaseMetadata& metadata); - void SendSuccessDatabase(std::unique_ptr<DatabaseImpl> database, + void SendSuccessDatabase(SafeIOThreadConnectionWrapper connection, const content::IndexedDBDatabaseMetadata& metadata); - void SendSuccessCursor(std::unique_ptr<CursorImpl> cursor, + void SendSuccessCursor(std::unique_ptr<IndexedDBCursor> cursor, const IndexedDBKey& key, const IndexedDBKey& primary_key, ::indexed_db::mojom::ValuePtr value, @@ -125,8 +160,10 @@ void OnConnectionError(); private: - scoped_refptr<IndexedDBDispatcherHost> dispatcher_host_; + base::WeakPtr<IndexedDBDispatcherHost> dispatcher_host_; ::indexed_db::mojom::CallbacksAssociatedPtr callbacks_; + url::Origin origin_; + scoped_refptr<base::SequencedTaskRunner> idb_runner_; DISALLOW_COPY_AND_ASSIGN(IOThreadHelper); }; @@ -142,15 +179,15 @@ } IndexedDBCallbacks::IndexedDBCallbacks( - scoped_refptr<IndexedDBDispatcherHost> dispatcher_host, + base::WeakPtr<IndexedDBDispatcherHost> dispatcher_host, const url::Origin& origin, - ::indexed_db::mojom::CallbacksAssociatedPtrInfo callbacks_info) - : dispatcher_host_(std::move(dispatcher_host)), - origin_(origin), - data_loss_(blink::kWebIDBDataLossNone), - sent_blocked_(false), - io_helper_( - new IOThreadHelper(std::move(callbacks_info), dispatcher_host_)) { + ::indexed_db::mojom::CallbacksAssociatedPtrInfo callbacks_info, + scoped_refptr<base::SequencedTaskRunner> idb_runner) + : data_loss_(blink::kWebIDBDataLossNone), + io_helper_(new IOThreadHelper(std::move(callbacks_info), + std::move(dispatcher_host), + origin, + std::move(idb_runner))) { DCHECK_CURRENTLY_ON(BrowserThread::IO); thread_checker_.DetachFromThread(); } @@ -161,13 +198,13 @@ void IndexedDBCallbacks::OnError(const IndexedDBDatabaseError& error) { DCHECK(thread_checker_.CalledOnValidThread()); - DCHECK(dispatcher_host_); + DCHECK(!complete_); BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, base::Bind(&IOThreadHelper::SendError, base::Unretained(io_helper_.get()), error)); - dispatcher_host_ = nullptr; + complete_ = true; if (!connection_open_start_time_.is_null()) { UMA_HISTOGRAM_MEDIUM_TIMES( @@ -179,19 +216,19 @@ void IndexedDBCallbacks::OnSuccess(const std::vector<base::string16>& value) { DCHECK(thread_checker_.CalledOnValidThread()); - DCHECK(dispatcher_host_); + DCHECK(!complete_); DCHECK(io_helper_); BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, base::Bind(&IOThreadHelper::SendSuccessStringList, base::Unretained(io_helper_.get()), value)); - dispatcher_host_ = nullptr; + complete_ = true; } void IndexedDBCallbacks::OnBlocked(int64_t existing_version) { DCHECK(thread_checker_.CalledOnValidThread()); - DCHECK(dispatcher_host_); + DCHECK(!complete_); DCHECK(io_helper_); if (sent_blocked_) @@ -218,20 +255,19 @@ const IndexedDBDatabaseMetadata& metadata, const IndexedDBDataLossInfo& data_loss_info) { DCHECK(thread_checker_.CalledOnValidThread()); - DCHECK(dispatcher_host_); + DCHECK(!complete_); DCHECK(io_helper_); - DCHECK(!database_sent_); + DCHECK(!connection_created_); data_loss_ = data_loss_info.status; - database_sent_ = true; - auto database = base::MakeUnique<DatabaseImpl>(std::move(connection), origin_, - dispatcher_host_); + connection_created_ = true; + SafeIOThreadConnectionWrapper wrapper(std::move(connection)); BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, base::Bind(&IOThreadHelper::SendUpgradeNeeded, - base::Unretained(io_helper_.get()), base::Passed(&database), + base::Unretained(io_helper_.get()), base::Passed(&wrapper), old_version, data_loss_info.status, data_loss_info.message, metadata)); @@ -247,26 +283,25 @@ std::unique_ptr<IndexedDBConnection> connection, const IndexedDBDatabaseMetadata& metadata) { DCHECK(thread_checker_.CalledOnValidThread()); - DCHECK(dispatcher_host_); + DCHECK(!complete_); DCHECK(io_helper_); - DCHECK_EQ(database_sent_, !connection); + DCHECK_EQ(connection_created_, !connection); scoped_refptr<IndexedDBCallbacks> self(this); - // Only send a new Database if the connection was not previously sent in + // Only create a new connection if one was not previously sent in // OnUpgradeNeeded. - std::unique_ptr<DatabaseImpl> database; - if (!database_sent_) { - database.reset( - new DatabaseImpl(std::move(connection), origin_, dispatcher_host_)); - } + std::unique_ptr<IndexedDBConnection> database_connection; + if (!connection_created_) + database_connection = std::move(connection); + SafeIOThreadConnectionWrapper wrapper(std::move(database_connection)); BrowserThread::PostTask(BrowserThread::IO, FROM_HERE, base::Bind(&IOThreadHelper::SendSuccessDatabase, base::Unretained(io_helper_.get()), - base::Passed(&database), metadata)); - dispatcher_host_ = nullptr; + base::Passed(&wrapper), metadata)); + complete_ = true; if (!connection_open_start_time_.is_null()) { UMA_HISTOGRAM_MEDIUM_TIMES( @@ -281,14 +316,11 @@ const IndexedDBKey& primary_key, IndexedDBValue* value) { DCHECK(thread_checker_.CalledOnValidThread()); - DCHECK(dispatcher_host_); + DCHECK(!complete_); DCHECK(io_helper_); DCHECK_EQ(blink::kWebIDBDataLossNone, data_loss_); - auto cursor_impl = base::MakeUnique<CursorImpl>(std::move(cursor), origin_, - dispatcher_host_); - ::indexed_db::mojom::ValuePtr mojo_value; std::vector<IndexedDBBlobInfo> blob_info; if (value) { @@ -299,17 +331,17 @@ BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, base::Bind(&IOThreadHelper::SendSuccessCursor, - base::Unretained(io_helper_.get()), base::Passed(&cursor_impl), - key, primary_key, base::Passed(&mojo_value), + base::Unretained(io_helper_.get()), base::Passed(&cursor), key, + primary_key, base::Passed(&mojo_value), base::Passed(&blob_info))); - dispatcher_host_ = nullptr; + complete_ = true; } void IndexedDBCallbacks::OnSuccess(const IndexedDBKey& key, const IndexedDBKey& primary_key, IndexedDBValue* value) { DCHECK(thread_checker_.CalledOnValidThread()); - DCHECK(dispatcher_host_); + DCHECK(!complete_); DCHECK(io_helper_); DCHECK_EQ(blink::kWebIDBDataLossNone, data_loss_); @@ -326,7 +358,7 @@ base::Bind(&IOThreadHelper::SendSuccessCursorContinue, base::Unretained(io_helper_.get()), key, primary_key, base::Passed(&mojo_value), base::Passed(&blob_info))); - dispatcher_host_ = nullptr; + complete_ = true; } void IndexedDBCallbacks::OnSuccessWithPrefetch( @@ -334,7 +366,7 @@ const std::vector<IndexedDBKey>& primary_keys, std::vector<IndexedDBValue>* values) { DCHECK(thread_checker_.CalledOnValidThread()); - DCHECK(dispatcher_host_); + DCHECK(!complete_); DCHECK(io_helper_); DCHECK_EQ(keys.size(), primary_keys.size()); DCHECK_EQ(keys.size(), values->size()); @@ -351,12 +383,12 @@ base::Bind(&IOThreadHelper::SendSuccessCursorPrefetch, base::Unretained(io_helper_.get()), keys, primary_keys, base::Passed(&mojo_values), *values)); - dispatcher_host_ = nullptr; + complete_ = true; } void IndexedDBCallbacks::OnSuccess(IndexedDBReturnValue* value) { DCHECK(thread_checker_.CalledOnValidThread()); - DCHECK(dispatcher_host_); + DCHECK(!complete_); DCHECK_EQ(blink::kWebIDBDataLossNone, data_loss_); @@ -372,13 +404,13 @@ base::Bind(&IOThreadHelper::SendSuccessValue, base::Unretained(io_helper_.get()), base::Passed(&mojo_value), base::Passed(&blob_info))); - dispatcher_host_ = nullptr; + complete_ = true; } void IndexedDBCallbacks::OnSuccessArray( std::vector<IndexedDBReturnValue>* values) { DCHECK(thread_checker_.CalledOnValidThread()); - DCHECK(dispatcher_host_); + DCHECK(!complete_); DCHECK(io_helper_); DCHECK_EQ(blink::kWebIDBDataLossNone, data_loss_); @@ -392,12 +424,12 @@ base::Bind(&IOThreadHelper::SendSuccessArray, base::Unretained(io_helper_.get()), base::Passed(&mojo_values), *values)); - dispatcher_host_ = nullptr; + complete_ = true; } void IndexedDBCallbacks::OnSuccess(const IndexedDBKey& value) { DCHECK(thread_checker_.CalledOnValidThread()); - DCHECK(dispatcher_host_); + DCHECK(!complete_); DCHECK(io_helper_); DCHECK_EQ(blink::kWebIDBDataLossNone, data_loss_); @@ -406,23 +438,23 @@ BrowserThread::IO, FROM_HERE, base::Bind(&IOThreadHelper::SendSuccessKey, base::Unretained(io_helper_.get()), value)); - dispatcher_host_ = nullptr; + complete_ = true; } void IndexedDBCallbacks::OnSuccess(int64_t value) { DCHECK(thread_checker_.CalledOnValidThread()); - DCHECK(dispatcher_host_); + DCHECK(!complete_); BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, base::Bind(&IOThreadHelper::SendSuccessInteger, base::Unretained(io_helper_.get()), value)); - dispatcher_host_ = nullptr; + complete_ = true; } void IndexedDBCallbacks::OnSuccess() { DCHECK(thread_checker_.CalledOnValidThread()); - DCHECK(dispatcher_host_); + DCHECK(!complete_); DCHECK(io_helper_); DCHECK_EQ(blink::kWebIDBDataLossNone, data_loss_); @@ -430,7 +462,7 @@ BrowserThread::PostTask(BrowserThread::IO, FROM_HERE, base::Bind(&IOThreadHelper::SendSuccess, base::Unretained(io_helper_.get()))); - dispatcher_host_ = nullptr; + complete_ = true; } void IndexedDBCallbacks::SetConnectionOpenStartTime( @@ -440,8 +472,12 @@ IndexedDBCallbacks::IOThreadHelper::IOThreadHelper( CallbacksAssociatedPtrInfo callbacks_info, - scoped_refptr<IndexedDBDispatcherHost> dispatcher_host) - : dispatcher_host_(std::move(dispatcher_host)) { + base::WeakPtr<IndexedDBDispatcherHost> dispatcher_host, + url::Origin origin, + scoped_refptr<base::SequencedTaskRunner> idb_runner) + : dispatcher_host_(std::move(dispatcher_host)), + origin_(origin), + idb_runner_(idb_runner) { DCHECK_CURRENTLY_ON(BrowserThread::IO); if (callbacks_info.is_valid()) { callbacks_.Bind(std::move(callbacks_info)); @@ -450,70 +486,116 @@ } } -IndexedDBCallbacks::IOThreadHelper::~IOThreadHelper() {} +IndexedDBCallbacks::IOThreadHelper::~IOThreadHelper() { + DCHECK_CURRENTLY_ON(BrowserThread::IO); +} void IndexedDBCallbacks::IOThreadHelper::SendError( const IndexedDBDatabaseError& error) { - if (callbacks_) - callbacks_->Error(error.code(), error.message()); + DCHECK_CURRENTLY_ON(BrowserThread::IO); + if (!callbacks_) + return; + if (!dispatcher_host_) { + OnConnectionError(); + return; + } + callbacks_->Error(error.code(), error.message()); } void IndexedDBCallbacks::IOThreadHelper::SendSuccessStringList( const std::vector<base::string16>& value) { - if (callbacks_) - callbacks_->SuccessStringList(value); + DCHECK_CURRENTLY_ON(BrowserThread::IO); + if (!callbacks_) + return; + if (!dispatcher_host_) { + OnConnectionError(); + return; + } + callbacks_->SuccessStringList(value); } void IndexedDBCallbacks::IOThreadHelper::SendBlocked(int64_t existing_version) { + DCHECK_CURRENTLY_ON(BrowserThread::IO); + if (!dispatcher_host_) { + OnConnectionError(); + return; + } if (callbacks_) callbacks_->Blocked(existing_version); } void IndexedDBCallbacks::IOThreadHelper::SendUpgradeNeeded( - std::unique_ptr<DatabaseImpl> database, + SafeIOThreadConnectionWrapper connection_wrapper, int64_t old_version, blink::WebIDBDataLoss data_loss, const std::string& data_loss_message, const content::IndexedDBDatabaseMetadata& metadata) { + DCHECK_CURRENTLY_ON(BrowserThread::IO); if (!callbacks_) return; + if (!dispatcher_host_) { + OnConnectionError(); + return; + } + + auto database = base::MakeUnique<DatabaseImpl>( + std::move(connection_wrapper.connection), origin_, dispatcher_host_.get(), + idb_runner_); ::indexed_db::mojom::DatabaseAssociatedPtrInfo ptr_info; auto request = mojo::MakeRequest(&ptr_info); - mojo::MakeStrongAssociatedBinding(std::move(database), std::move(request)); + + dispatcher_host_->AddDatabaseBinding(std::move(database), std::move(request)); callbacks_->UpgradeNeeded(std::move(ptr_info), old_version, data_loss, data_loss_message, metadata); } void IndexedDBCallbacks::IOThreadHelper::SendSuccessDatabase( - std::unique_ptr<DatabaseImpl> database, + SafeIOThreadConnectionWrapper connection_wrapper, const content::IndexedDBDatabaseMetadata& metadata) { + DCHECK_CURRENTLY_ON(BrowserThread::IO); if (!callbacks_) return; - + if (!dispatcher_host_) { + OnConnectionError(); + return; + } ::indexed_db::mojom::DatabaseAssociatedPtrInfo ptr_info; - if (database) { + if (connection_wrapper.connection) { + auto database = base::MakeUnique<DatabaseImpl>( + std::move(connection_wrapper.connection), origin_, + dispatcher_host_.get(), idb_runner_); + auto request = mojo::MakeRequest(&ptr_info); - mojo::MakeStrongAssociatedBinding(std::move(database), std::move(request)); + dispatcher_host_->AddDatabaseBinding(std::move(database), + std::move(request)); } callbacks_->SuccessDatabase(std::move(ptr_info), metadata); } void IndexedDBCallbacks::IOThreadHelper::SendSuccessCursor( - std::unique_ptr<CursorImpl> cursor, + std::unique_ptr<IndexedDBCursor> cursor, const IndexedDBKey& key, const IndexedDBKey& primary_key, ::indexed_db::mojom::ValuePtr value, const std::vector<IndexedDBBlobInfo>& blob_info) { + DCHECK_CURRENTLY_ON(BrowserThread::IO); if (!callbacks_) return; + if (!dispatcher_host_) { + OnConnectionError(); + return; + } + auto cursor_impl = base::MakeUnique<CursorImpl>( + std::move(cursor), origin_, dispatcher_host_.get(), idb_runner_); if (value && !CreateAllBlobs(blob_info, &value->blob_or_file_info)) return; ::indexed_db::mojom::CursorAssociatedPtrInfo ptr_info; auto request = mojo::MakeRequest(&ptr_info); - mojo::MakeStrongAssociatedBinding(std::move(cursor), std::move(request)); + dispatcher_host_->AddCursorBinding(std::move(cursor_impl), + std::move(request)); callbacks_->SuccessCursor(std::move(ptr_info), key, primary_key, std::move(value)); } @@ -521,8 +603,13 @@ void IndexedDBCallbacks::IOThreadHelper::SendSuccessValue( ::indexed_db::mojom::ReturnValuePtr value, const std::vector<IndexedDBBlobInfo>& blob_info) { + DCHECK_CURRENTLY_ON(BrowserThread::IO); if (!callbacks_) return; + if (!dispatcher_host_) { + OnConnectionError(); + return; + } if (!value || CreateAllBlobs(blob_info, &value->value->blob_or_file_info)) callbacks_->SuccessValue(std::move(value)); @@ -531,10 +618,15 @@ void IndexedDBCallbacks::IOThreadHelper::SendSuccessArray( std::vector<::indexed_db::mojom::ReturnValuePtr> mojo_values, const std::vector<IndexedDBReturnValue>& values) { + DCHECK_CURRENTLY_ON(BrowserThread::IO); DCHECK_EQ(mojo_values.size(), values.size()); if (!callbacks_) return; + if (!dispatcher_host_) { + OnConnectionError(); + return; + } for (size_t i = 0; i < mojo_values.size(); ++i) { if (!CreateAllBlobs(values[i].blob_info, @@ -549,8 +641,13 @@ const IndexedDBKey& primary_key, ::indexed_db::mojom::ValuePtr value, const std::vector<IndexedDBBlobInfo>& blob_info) { + DCHECK_CURRENTLY_ON(BrowserThread::IO); if (!callbacks_) return; + if (!dispatcher_host_) { + OnConnectionError(); + return; + } if (!value || CreateAllBlobs(blob_info, &value->blob_or_file_info)) callbacks_->SuccessCursorContinue(key, primary_key, std::move(value)); @@ -561,10 +658,15 @@ const std::vector<IndexedDBKey>& primary_keys, std::vector<::indexed_db::mojom::ValuePtr> mojo_values, const std::vector<IndexedDBValue>& values) { + DCHECK_CURRENTLY_ON(BrowserThread::IO); DCHECK_EQ(mojo_values.size(), values.size()); if (!callbacks_) return; + if (!dispatcher_host_) { + OnConnectionError(); + return; + } for (size_t i = 0; i < mojo_values.size(); ++i) { if (!CreateAllBlobs(values[i].blob_info, @@ -578,22 +680,41 @@ void IndexedDBCallbacks::IOThreadHelper::SendSuccessKey( const IndexedDBKey& value) { - if (callbacks_) - callbacks_->SuccessKey(value); + DCHECK_CURRENTLY_ON(BrowserThread::IO); + if (!callbacks_) + return; + if (!dispatcher_host_) { + OnConnectionError(); + return; + } + callbacks_->SuccessKey(value); } void IndexedDBCallbacks::IOThreadHelper::SendSuccessInteger(int64_t value) { - if (callbacks_) - callbacks_->SuccessInteger(value); + DCHECK_CURRENTLY_ON(BrowserThread::IO); + if (!callbacks_) + return; + if (!dispatcher_host_) { + OnConnectionError(); + return; + } + callbacks_->SuccessInteger(value); } void IndexedDBCallbacks::IOThreadHelper::SendSuccess() { - if (callbacks_) - callbacks_->Success(); + DCHECK_CURRENTLY_ON(BrowserThread::IO); + if (!callbacks_) + return; + if (!dispatcher_host_) { + OnConnectionError(); + return; + } + callbacks_->Success(); } std::string IndexedDBCallbacks::IOThreadHelper::CreateBlobData( const IndexedDBBlobInfo& blob_info) { + DCHECK_CURRENTLY_ON(BrowserThread::IO); if (!blob_info.uuid().empty()) { // We're sending back a live blob, not a reference into our backing store. return dispatcher_host_->HoldBlobData(blob_info); @@ -614,6 +735,11 @@ bool IndexedDBCallbacks::IOThreadHelper::CreateAllBlobs( const std::vector<IndexedDBBlobInfo>& blob_info, std::vector<::indexed_db::mojom::BlobInfoPtr>* blob_or_file_info) { + DCHECK_CURRENTLY_ON(BrowserThread::IO); + if (!dispatcher_host_) { + OnConnectionError(); + return false; + } IDB_TRACE("IndexedDBCallbacks::CreateAllBlobs"); DCHECK_EQ(blob_info.size(), blob_or_file_info->size()); if (!dispatcher_host_->blob_storage_context()) @@ -624,6 +750,7 @@ } void IndexedDBCallbacks::IOThreadHelper::OnConnectionError() { + DCHECK_CURRENTLY_ON(BrowserThread::IO); callbacks_.reset(); dispatcher_host_ = nullptr; }
diff --git a/content/browser/indexed_db/indexed_db_callbacks.h b/content/browser/indexed_db/indexed_db_callbacks.h index b72fc60..45d9e0d 100644 --- a/content/browser/indexed_db/indexed_db_callbacks.h +++ b/content/browser/indexed_db/indexed_db_callbacks.h
@@ -13,7 +13,7 @@ #include "base/logging.h" #include "base/macros.h" -#include "base/memory/ref_counted.h" +#include "base/memory/weak_ptr.h" #include "base/strings/string16.h" #include "base/threading/thread_checker.h" #include "content/browser/indexed_db/indexed_db_database_error.h" @@ -23,6 +23,10 @@ #include "content/common/indexed_db/indexed_db_key_path.h" #include "url/origin.h" +namespace base { +class SequencedTaskRunner; +} + namespace content { class IndexedDBConnection; class IndexedDBCursor; @@ -32,6 +36,7 @@ struct IndexedDBReturnValue; struct IndexedDBValue; +// Expected to be constructed on IO thread and called/deleted from IDB thread. class CONTENT_EXPORT IndexedDBCallbacks : public base::RefCounted<IndexedDBCallbacks> { public: @@ -40,9 +45,10 @@ IndexedDBValue* value); IndexedDBCallbacks( - scoped_refptr<IndexedDBDispatcherHost> dispatcher_host, + base::WeakPtr<IndexedDBDispatcherHost> dispatcher_host, const url::Origin& origin, - ::indexed_db::mojom::CallbacksAssociatedPtrInfo callbacks_info); + ::indexed_db::mojom::CallbacksAssociatedPtrInfo callbacks_info, + scoped_refptr<base::SequencedTaskRunner> idb_runner); virtual void OnError(const IndexedDBDatabaseError& error); @@ -106,18 +112,19 @@ class IOThreadHelper; - // Originally from IndexedDBCallbacks: - scoped_refptr<IndexedDBDispatcherHost> dispatcher_host_; + // Stores if this callbacks object is complete and should not be called again. + bool complete_ = false; - // IndexedDBDatabase callbacks ------------------------ - url::Origin origin_; - bool database_sent_ = false; + // Depending on whether the database needs upgrading, we create connections in + // different spots. This stores if we've already created the connection so + // OnSuccess(Connection) doesn't create an extra one. + bool connection_created_ = false; // Used to assert that OnSuccess is only called if there was no data loss. blink::WebIDBDataLoss data_loss_; // The "blocked" event should be sent at most once per request. - bool sent_blocked_; + bool sent_blocked_ = false; base::TimeTicks connection_open_start_time_; std::unique_ptr<IOThreadHelper, BrowserThread::DeleteOnIOThread> io_helper_;
diff --git a/content/browser/indexed_db/indexed_db_database_callbacks.cc b/content/browser/indexed_db/indexed_db_database_callbacks.cc index bc7e6b9..d9a4981 100644 --- a/content/browser/indexed_db/indexed_db_database_callbacks.cc +++ b/content/browser/indexed_db/indexed_db_database_callbacks.cc
@@ -23,6 +23,7 @@ void SendAbort(int64_t transaction_id, const IndexedDBDatabaseError& error); void SendComplete(int64_t transaction_id); void SendChanges(::indexed_db::mojom::ObserverChangesPtr changes); + void OnConnectionError(); private: ::indexed_db::mojom::DatabaseCallbacksAssociatedPtr callbacks_; @@ -31,9 +32,9 @@ }; IndexedDBDatabaseCallbacks::IndexedDBDatabaseCallbacks( - scoped_refptr<IndexedDBDispatcherHost> dispatcher_host, + scoped_refptr<IndexedDBContextImpl> context, DatabaseCallbacksAssociatedPtrInfo callbacks_info) - : dispatcher_host_(std::move(dispatcher_host)), + : indexed_db_context_(std::move(context)), io_helper_(new IOThreadHelper(std::move(callbacks_info))) { DCHECK_CURRENTLY_ON(BrowserThread::IO); thread_checker_.DetachFromThread(); @@ -45,20 +46,20 @@ void IndexedDBDatabaseCallbacks::OnForcedClose() { DCHECK(thread_checker_.CalledOnValidThread()); - if (!dispatcher_host_) + if (complete_) return; DCHECK(io_helper_); BrowserThread::PostTask(BrowserThread::IO, FROM_HERE, base::Bind(&IOThreadHelper::SendForcedClose, base::Unretained(io_helper_.get()))); - dispatcher_host_ = NULL; + complete_ = true; } void IndexedDBDatabaseCallbacks::OnVersionChange(int64_t old_version, int64_t new_version) { DCHECK(thread_checker_.CalledOnValidThread()); - if (!dispatcher_host_) + if (complete_) return; DCHECK(io_helper_); @@ -72,7 +73,7 @@ const IndexedDBTransaction& transaction, const IndexedDBDatabaseError& error) { DCHECK(thread_checker_.CalledOnValidThread()); - if (!dispatcher_host_) + if (complete_) return; DCHECK(io_helper_); @@ -85,11 +86,10 @@ void IndexedDBDatabaseCallbacks::OnComplete( const IndexedDBTransaction& transaction) { DCHECK(thread_checker_.CalledOnValidThread()); - if (!dispatcher_host_) + if (complete_) return; - dispatcher_host_->context()->TransactionComplete( - transaction.database()->origin()); + indexed_db_context_->TransactionComplete(transaction.database()->origin()); DCHECK(io_helper_); BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, @@ -109,35 +109,48 @@ IndexedDBDatabaseCallbacks::IOThreadHelper::IOThreadHelper( DatabaseCallbacksAssociatedPtrInfo callbacks_info) { + if (!callbacks_info.is_valid()) + return; callbacks_.Bind(std::move(callbacks_info)); + callbacks_.set_connection_error_handler( + base::Bind(&IOThreadHelper::OnConnectionError, base::Unretained(this))); } IndexedDBDatabaseCallbacks::IOThreadHelper::~IOThreadHelper() {} void IndexedDBDatabaseCallbacks::IOThreadHelper::SendForcedClose() { - callbacks_->ForcedClose(); + if (callbacks_) + callbacks_->ForcedClose(); } void IndexedDBDatabaseCallbacks::IOThreadHelper::SendVersionChange( int64_t old_version, int64_t new_version) { - callbacks_->VersionChange(old_version, new_version); + if (callbacks_) + callbacks_->VersionChange(old_version, new_version); } void IndexedDBDatabaseCallbacks::IOThreadHelper::SendAbort( int64_t transaction_id, const IndexedDBDatabaseError& error) { - callbacks_->Abort(transaction_id, error.code(), error.message()); + if (callbacks_) + callbacks_->Abort(transaction_id, error.code(), error.message()); } void IndexedDBDatabaseCallbacks::IOThreadHelper::SendComplete( int64_t transaction_id) { - callbacks_->Complete(transaction_id); + if (callbacks_) + callbacks_->Complete(transaction_id); } void IndexedDBDatabaseCallbacks::IOThreadHelper::SendChanges( ::indexed_db::mojom::ObserverChangesPtr changes) { - callbacks_->Changes(std::move(changes)); + if (callbacks_) + callbacks_->Changes(std::move(changes)); +} + +void IndexedDBDatabaseCallbacks::IOThreadHelper::OnConnectionError() { + callbacks_.reset(); } } // namespace content
diff --git a/content/browser/indexed_db/indexed_db_database_callbacks.h b/content/browser/indexed_db/indexed_db_database_callbacks.h index 1978d72..654195a18 100644 --- a/content/browser/indexed_db/indexed_db_database_callbacks.h +++ b/content/browser/indexed_db/indexed_db_database_callbacks.h
@@ -8,22 +8,23 @@ #include <stdint.h> #include "base/macros.h" -#include "base/memory/ref_counted.h" +#include "base/memory/weak_ptr.h" #include "base/threading/thread_checker.h" #include "content/common/content_export.h" #include "content/common/indexed_db/indexed_db.mojom.h" #include "content/public/browser/browser_thread.h" namespace content { +class IndexedDBContextImpl; class IndexedDBDatabaseError; -class IndexedDBDispatcherHost; class IndexedDBTransaction; +// Expected to be constructed on IO thread and called/deleted from IDB thread. class CONTENT_EXPORT IndexedDBDatabaseCallbacks : public base::RefCounted<IndexedDBDatabaseCallbacks> { public: IndexedDBDatabaseCallbacks( - scoped_refptr<IndexedDBDispatcherHost> dispatcher_host, + scoped_refptr<IndexedDBContextImpl> context, ::indexed_db::mojom::DatabaseCallbacksAssociatedPtrInfo callbacks_info); virtual void OnForcedClose(); @@ -43,7 +44,8 @@ class IOThreadHelper; - scoped_refptr<IndexedDBDispatcherHost> dispatcher_host_; + bool complete_ = false; + scoped_refptr<IndexedDBContextImpl> indexed_db_context_; std::unique_ptr<IOThreadHelper, BrowserThread::DeleteOnIOThread> io_helper_; base::ThreadChecker thread_checker_;
diff --git a/content/browser/indexed_db/indexed_db_database_unittest.cc b/content/browser/indexed_db/indexed_db_database_unittest.cc index 7a4923c..d1cfeb9 100644 --- a/content/browser/indexed_db/indexed_db_database_unittest.cc +++ b/content/browser/indexed_db/indexed_db_database_unittest.cc
@@ -15,6 +15,7 @@ #include "base/run_loop.h" #include "base/strings/string16.h" #include "base/strings/utf_string_conversions.h" +#include "base/threading/thread_task_runner_handle.h" #include "content/browser/indexed_db/indexed_db.h" #include "content/browser/indexed_db/indexed_db_backing_store.h" #include "content/browser/indexed_db/indexed_db_callbacks.h" @@ -150,7 +151,11 @@ class MockCallbacks : public IndexedDBCallbacks { public: - MockCallbacks() : IndexedDBCallbacks(nullptr, url::Origin(), nullptr) {} + MockCallbacks() + : IndexedDBCallbacks(nullptr, + url::Origin(), + nullptr, + base::ThreadTaskRunnerHandle::Get()) {} void OnBlocked(int64_t existing_version) override { blocked_called_ = true; } void OnSuccess(int64_t result) override { success_called_ = true; }
diff --git a/content/browser/indexed_db/indexed_db_dispatcher_host.cc b/content/browser/indexed_db/indexed_db_dispatcher_host.cc index f1663a5d..2ecd7b1 100644 --- a/content/browser/indexed_db/indexed_db_dispatcher_host.cc +++ b/content/browser/indexed_db/indexed_db_dispatcher_host.cc
@@ -9,6 +9,7 @@ #include "base/guid.h" #include "base/memory/ptr_util.h" #include "base/process/process.h" +#include "base/sequenced_task_runner.h" #include "base/stl_util.h" #include "base/strings/utf_string_conversions.h" #include "content/browser/indexed_db/indexed_db_callbacks.h" @@ -34,25 +35,80 @@ } // namespace +class IndexedDBDispatcherHost::IDBThreadHelper { + public: + IDBThreadHelper( + int ipc_process_id, + scoped_refptr<net::URLRequestContextGetter> request_context_getter, + scoped_refptr<IndexedDBContextImpl> indexed_db_context) + : ipc_process_id_(ipc_process_id), + request_context_getter_(std::move(request_context_getter)), + indexed_db_context_(std::move(indexed_db_context)) {} + ~IDBThreadHelper() {} + + 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); + + private: + const int ipc_process_id_; + scoped_refptr<net::URLRequestContextGetter> request_context_getter_; + scoped_refptr<IndexedDBContextImpl> indexed_db_context_; + + DISALLOW_COPY_AND_ASSIGN(IDBThreadHelper); +}; + IndexedDBDispatcherHost::IndexedDBDispatcherHost( int ipc_process_id, - net::URLRequestContextGetter* request_context_getter, - IndexedDBContextImpl* indexed_db_context, - ChromeBlobStorageContext* blob_storage_context) - : request_context_getter_(request_context_getter), - indexed_db_context_(indexed_db_context), - blob_storage_context_(blob_storage_context), - ipc_process_id_(ipc_process_id) { + scoped_refptr<net::URLRequestContextGetter> request_context_getter, + scoped_refptr<IndexedDBContextImpl> indexed_db_context, + scoped_refptr<ChromeBlobStorageContext> blob_storage_context) + : indexed_db_context_(std::move(indexed_db_context)), + blob_storage_context_(std::move(blob_storage_context)), + idb_runner_(indexed_db_context_->TaskRunner()), + ipc_process_id_(ipc_process_id), + weak_factory_(this) { + // Can be null in unittests. + idb_helper_ = idb_runner_ + ? new IDBThreadHelper(ipc_process_id_, + std::move(request_context_getter), + indexed_db_context_) + : nullptr; DCHECK(indexed_db_context_.get()); } -IndexedDBDispatcherHost::~IndexedDBDispatcherHost() {} +IndexedDBDispatcherHost::~IndexedDBDispatcherHost() { + if (idb_helper_) + idb_runner_->DeleteSoon(FROM_HERE, idb_helper_); +} void IndexedDBDispatcherHost::AddBinding( ::indexed_db::mojom::FactoryAssociatedRequest request) { bindings_.AddBinding(this, std::move(request)); } +void IndexedDBDispatcherHost::AddDatabaseBinding( + std::unique_ptr<::indexed_db::mojom::Database> database, + ::indexed_db::mojom::DatabaseAssociatedRequest request) { + database_bindings_.AddBinding(std::move(database), std::move(request)); +} + +void IndexedDBDispatcherHost::AddCursorBinding( + std::unique_ptr<::indexed_db::mojom::Cursor> cursor, + ::indexed_db::mojom::CursorAssociatedRequest request) { + cursor_bindings_.AddBinding(std::move(cursor), std::move(request)); +} + std::string IndexedDBDispatcherHost::HoldBlobData( const IndexedDBBlobInfo& blob_info) { DCHECK_CURRENTLY_ON(BrowserThread::IO); @@ -95,6 +151,16 @@ --iter->second.second; } +void IndexedDBDispatcherHost::RenderProcessExited( + RenderProcessHost* host, + base::TerminationStatus status, + int exit_code) { + BrowserThread::PostTask( + BrowserThread::IO, FROM_HERE, + base::Bind(&IndexedDBDispatcherHost::InvalidateWeakPtrsAndClearBindings, + base::Unretained(this))); +} + void IndexedDBDispatcherHost::GetDatabaseNames( ::indexed_db::mojom::CallbacksAssociatedPtrInfo callbacks_info, const url::Origin& origin) { @@ -105,12 +171,12 @@ return; } - scoped_refptr<IndexedDBCallbacks> callbacks( - new IndexedDBCallbacks(this, origin, std::move(callbacks_info))); - indexed_db_context_->TaskRunner()->PostTask( - FROM_HERE, - base::Bind(&IndexedDBDispatcherHost::GetDatabaseNamesOnIDBThread, this, - base::Passed(&callbacks), origin)); + scoped_refptr<IndexedDBCallbacks> callbacks(new IndexedDBCallbacks( + this->AsWeakPtr(), origin, std::move(callbacks_info), idb_runner_)); + idb_runner_->PostTask( + FROM_HERE, base::Bind(&IDBThreadHelper::GetDatabaseNamesOnIDBThread, + base::Unretained(idb_helper_), + base::Passed(&callbacks), origin)); } void IndexedDBDispatcherHost::Open( @@ -128,15 +194,17 @@ return; } - scoped_refptr<IndexedDBCallbacks> callbacks( - new IndexedDBCallbacks(this, origin, std::move(callbacks_info))); + scoped_refptr<IndexedDBCallbacks> callbacks(new IndexedDBCallbacks( + this->AsWeakPtr(), origin, std::move(callbacks_info), idb_runner_)); scoped_refptr<IndexedDBDatabaseCallbacks> database_callbacks( - new IndexedDBDatabaseCallbacks(this, std::move(database_callbacks_info))); - indexed_db_context_->TaskRunner()->PostTask( + new IndexedDBDatabaseCallbacks(indexed_db_context_, + std::move(database_callbacks_info))); + idb_runner_->PostTask( FROM_HERE, - base::Bind(&IndexedDBDispatcherHost::OpenOnIDBThread, this, - base::Passed(&callbacks), base::Passed(&database_callbacks), - origin, name, version, transaction_id)); + base::Bind(&IDBThreadHelper::OpenOnIDBThread, + base::Unretained(idb_helper_), base::Passed(&callbacks), + base::Passed(&database_callbacks), origin, name, version, + transaction_id)); } void IndexedDBDispatcherHost::DeleteDatabase( @@ -151,25 +219,32 @@ return; } - scoped_refptr<IndexedDBCallbacks> callbacks( - new IndexedDBCallbacks(this, origin, std::move(callbacks_info))); - indexed_db_context_->TaskRunner()->PostTask( - FROM_HERE, base::Bind(&IndexedDBDispatcherHost::DeleteDatabaseOnIDBThread, - this, base::Passed(&callbacks), origin, name, - force_close)); + scoped_refptr<IndexedDBCallbacks> callbacks(new IndexedDBCallbacks( + this->AsWeakPtr(), origin, std::move(callbacks_info), idb_runner_)); + idb_runner_->PostTask( + FROM_HERE, + base::Bind(&IDBThreadHelper::DeleteDatabaseOnIDBThread, + base::Unretained(idb_helper_), base::Passed(&callbacks), + origin, name, force_close)); } -void IndexedDBDispatcherHost::GetDatabaseNamesOnIDBThread( +void IndexedDBDispatcherHost::InvalidateWeakPtrsAndClearBindings() { + weak_factory_.InvalidateWeakPtrs(); + cursor_bindings_.CloseAllBindings(); + database_bindings_.CloseAllBindings(); +} + +void IndexedDBDispatcherHost::IDBThreadHelper::GetDatabaseNamesOnIDBThread( scoped_refptr<IndexedDBCallbacks> callbacks, const url::Origin& origin) { DCHECK(indexed_db_context_->TaskRunner()->RunsTasksOnCurrentThread()); base::FilePath indexed_db_path = indexed_db_context_->data_path(); - context()->GetIDBFactory()->GetDatabaseNames( + indexed_db_context_->GetIDBFactory()->GetDatabaseNames( callbacks, origin, indexed_db_path, request_context_getter_); } -void IndexedDBDispatcherHost::OpenOnIDBThread( +void IndexedDBDispatcherHost::IDBThreadHelper::OpenOnIDBThread( scoped_refptr<IndexedDBCallbacks> callbacks, scoped_refptr<IndexedDBDatabaseCallbacks> database_callbacks, const url::Origin& origin, @@ -189,12 +264,12 @@ callbacks, database_callbacks, ipc_process_id_, transaction_id, version); DCHECK(request_context_getter_); - context()->GetIDBFactory()->Open(name, std::move(connection), - request_context_getter_, origin, - indexed_db_path); + indexed_db_context_->GetIDBFactory()->Open(name, std::move(connection), + request_context_getter_, origin, + indexed_db_path); } -void IndexedDBDispatcherHost::DeleteDatabaseOnIDBThread( +void IndexedDBDispatcherHost::IDBThreadHelper::DeleteDatabaseOnIDBThread( scoped_refptr<IndexedDBCallbacks> callbacks, const url::Origin& origin, const base::string16& name, @@ -203,7 +278,7 @@ base::FilePath indexed_db_path = indexed_db_context_->data_path(); DCHECK(request_context_getter_); - context()->GetIDBFactory()->DeleteDatabase( + indexed_db_context_->GetIDBFactory()->DeleteDatabase( name, request_context_getter_, callbacks, origin, indexed_db_path, force_close); }
diff --git a/content/browser/indexed_db/indexed_db_dispatcher_host.h b/content/browser/indexed_db/indexed_db_dispatcher_host.h index e24caf71..c64c71f 100644 --- a/content/browser/indexed_db/indexed_db_dispatcher_host.h +++ b/content/browser/indexed_db/indexed_db_dispatcher_host.h
@@ -18,34 +18,47 @@ #include "content/browser/blob_storage/chrome_blob_storage_context.h" #include "content/common/indexed_db/indexed_db.mojom.h" #include "content/public/browser/browser_thread.h" +#include "content/public/browser/render_process_host_observer.h" #include "mojo/public/cpp/bindings/associated_binding_set.h" +#include "mojo/public/cpp/bindings/strong_associated_binding_set.h" #include "net/url_request/url_request_context_getter.h" #include "storage/browser/blob/blob_data_handle.h" +namespace base { +class SequencedTaskRunner; +} + namespace url { class Origin; } namespace content { class IndexedDBBlobInfo; -class IndexedDBCallbacks; class IndexedDBContextImpl; -class IndexedDBDatabaseCallbacks; // Handles all IndexedDB related messages from a particular renderer process. -class IndexedDBDispatcherHost - : public base::RefCountedThreadSafe<IndexedDBDispatcherHost, - BrowserThread::DeleteOnIOThread>, - public ::indexed_db::mojom::Factory { +// Constructed on UI thread, expects all other calls (including destruction) on +// IO thread. +class CONTENT_EXPORT IndexedDBDispatcherHost + : public ::indexed_db::mojom::Factory, + public RenderProcessHostObserver { public: // Only call the constructor from the UI thread. - IndexedDBDispatcherHost(int ipc_process_id, - net::URLRequestContextGetter* request_context_getter, - IndexedDBContextImpl* indexed_db_context, - ChromeBlobStorageContext* blob_storage_context); + IndexedDBDispatcherHost( + int ipc_process_id, + scoped_refptr<net::URLRequestContextGetter> request_context_getter, + scoped_refptr<IndexedDBContextImpl> indexed_db_context, + scoped_refptr<ChromeBlobStorageContext> blob_storage_context); void AddBinding(::indexed_db::mojom::FactoryAssociatedRequest request); + void AddDatabaseBinding( + std::unique_ptr<::indexed_db::mojom::Database> database, + ::indexed_db::mojom::DatabaseAssociatedRequest request); + + void AddCursorBinding(std::unique_ptr<::indexed_db::mojom::Cursor> cursor, + ::indexed_db::mojom::CursorAssociatedRequest request); + // A shortcut for accessing our context. IndexedDBContextImpl* context() const { return indexed_db_context_.get(); } storage::BlobStorageContext* blob_storage_context() const { @@ -56,7 +69,19 @@ std::string HoldBlobData(const IndexedDBBlobInfo& blob_info); void DropBlobData(const std::string& uuid); + // Must be called on the IO thread. + base::WeakPtr<IndexedDBDispatcherHost> AsWeakPtr() { + return weak_factory_.GetWeakPtr(); + } + + // Called by UI thread. Used to kill outstanding bindings and weak pointers + // in callbacks. + void RenderProcessExited(RenderProcessHost* host, + base::TerminationStatus status, + int exit_code) override; + private: + class IDBThreadHelper; // Friends to enable OnDestruct() delegation. friend class BrowserThread; friend class base::DeleteHelper<IndexedDBDispatcherHost>; @@ -80,25 +105,11 @@ const base::string16& name, bool force_close) override; - 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 InvalidateWeakPtrsAndClearBindings(); - void ResetDispatcherHosts(); - - scoped_refptr<net::URLRequestContextGetter> request_context_getter_; scoped_refptr<IndexedDBContextImpl> indexed_db_context_; scoped_refptr<ChromeBlobStorageContext> blob_storage_context_; + scoped_refptr<base::SequencedTaskRunner> idb_runner_; // Maps blob uuid to a pair (handle, ref count). Entry is added and/or count // is incremented in HoldBlobData(), and count is decremented and/or entry @@ -112,6 +123,16 @@ mojo::AssociatedBindingSet<::indexed_db::mojom::Factory> bindings_; + mojo::StrongAssociatedBindingSet<::indexed_db::mojom::Database> + database_bindings_; + + mojo::StrongAssociatedBindingSet<::indexed_db::mojom::Cursor> + cursor_bindings_; + + IDBThreadHelper* idb_helper_; + + base::WeakPtrFactory<IndexedDBDispatcherHost> weak_factory_; + DISALLOW_IMPLICIT_CONSTRUCTORS(IndexedDBDispatcherHost); };
diff --git a/content/browser/indexed_db/indexed_db_factory_unittest.cc b/content/browser/indexed_db/indexed_db_factory_unittest.cc index a305938..3320bf5 100644 --- a/content/browser/indexed_db/indexed_db_factory_unittest.cc +++ b/content/browser/indexed_db/indexed_db_factory_unittest.cc
@@ -13,6 +13,7 @@ #include "base/run_loop.h" #include "base/strings/utf_string_conversions.h" #include "base/test/test_simple_task_runner.h" +#include "base/threading/thread_task_runner_handle.h" #include "content/browser/indexed_db/indexed_db_connection.h" #include "content/browser/indexed_db/indexed_db_context_impl.h" #include "content/browser/indexed_db/indexed_db_factory_impl.h" @@ -228,7 +229,10 @@ class LookingForQuotaErrorMockCallbacks : public IndexedDBCallbacks { public: LookingForQuotaErrorMockCallbacks() - : IndexedDBCallbacks(nullptr, url::Origin(), nullptr), + : IndexedDBCallbacks(nullptr, + url::Origin(), + nullptr, + base::ThreadTaskRunnerHandle::Get()), error_called_(false) {} void OnError(const IndexedDBDatabaseError& error) override { error_called_ = true;
diff --git a/content/browser/indexed_db/indexed_db_unittest.cc b/content/browser/indexed_db/indexed_db_unittest.cc index ddf9854..ab41645 100644 --- a/content/browser/indexed_db/indexed_db_unittest.cc +++ b/content/browser/indexed_db/indexed_db_unittest.cc
@@ -12,6 +12,7 @@ #include "base/run_loop.h" #include "base/test/test_simple_task_runner.h" #include "base/threading/thread.h" +#include "base/threading/thread_task_runner_handle.h" #include "content/browser/indexed_db/indexed_db_connection.h" #include "content/browser/indexed_db/indexed_db_context_impl.h" #include "content/browser/indexed_db/indexed_db_factory_impl.h" @@ -129,7 +130,10 @@ public: ForceCloseDBCallbacks(scoped_refptr<IndexedDBContextImpl> idb_context, const Origin& origin) - : IndexedDBCallbacks(nullptr, origin, nullptr), + : IndexedDBCallbacks(nullptr, + origin, + nullptr, + base::ThreadTaskRunnerHandle::Get()), idb_context_(idb_context), origin_(origin) {}
diff --git a/content/browser/indexed_db/mock_indexed_db_callbacks.cc b/content/browser/indexed_db/mock_indexed_db_callbacks.cc index 56221ed..af55ca19 100644 --- a/content/browser/indexed_db/mock_indexed_db_callbacks.cc +++ b/content/browser/indexed_db/mock_indexed_db_callbacks.cc
@@ -11,10 +11,10 @@ namespace content { MockIndexedDBCallbacks::MockIndexedDBCallbacks() - : IndexedDBCallbacks(nullptr, url::Origin(), nullptr), + : IndexedDBCallbacks(nullptr, url::Origin(), nullptr, nullptr), expect_connection_(true) {} MockIndexedDBCallbacks::MockIndexedDBCallbacks(bool expect_connection) - : IndexedDBCallbacks(nullptr, url::Origin(), nullptr), + : IndexedDBCallbacks(nullptr, url::Origin(), nullptr, nullptr), expect_connection_(expect_connection) {} MockIndexedDBCallbacks::~MockIndexedDBCallbacks() {
diff --git a/content/browser/indexed_db/mock_indexed_db_database_callbacks.cc b/content/browser/indexed_db/mock_indexed_db_database_callbacks.cc index ceabc8b5b..a9209f3a 100644 --- a/content/browser/indexed_db/mock_indexed_db_database_callbacks.cc +++ b/content/browser/indexed_db/mock_indexed_db_database_callbacks.cc
@@ -4,12 +4,14 @@ #include "content/browser/indexed_db/mock_indexed_db_database_callbacks.h" +#include "content/browser/indexed_db/indexed_db_context_impl.h" #include "testing/gtest/include/gtest/gtest.h" namespace content { MockIndexedDBDatabaseCallbacks::MockIndexedDBDatabaseCallbacks() - : IndexedDBDatabaseCallbacks(nullptr, nullptr), + : IndexedDBDatabaseCallbacks(scoped_refptr<IndexedDBContextImpl>(nullptr), + nullptr), abort_called_(false), forced_close_called_(false) {}
diff --git a/content/browser/media/session/OWNERS b/content/browser/media/session/OWNERS index 3fdb002..7b427c5 100644 --- a/content/browser/media/session/OWNERS +++ b/content/browser/media/session/OWNERS
@@ -1,4 +1,5 @@ avayvod@chromium.org mlamouri@chromium.org +# TEAM: media-dev@chromium.org # COMPONENT: Internals>Media>Session
diff --git a/content/browser/renderer_host/browser_compositor_view_mac.h b/content/browser/renderer_host/browser_compositor_view_mac.h index 54eee88..1c73b7f3 100644 --- a/content/browser/renderer_host/browser_compositor_view_mac.h +++ b/content/browser/renderer_host/browser_compositor_view_mac.h
@@ -26,9 +26,6 @@ public: virtual NSView* BrowserCompositorMacGetNSView() const = 0; virtual SkColor BrowserCompositorMacGetGutterColor(SkColor color) const = 0; - virtual void BrowserCompositorMacSendReclaimCompositorResources( - bool is_swap_ack, - const cc::ReturnedResourceArray& resources) = 0; virtual void BrowserCompositorMacSendBeginFrame( const cc::BeginFrameArgs& args) = 0; }; @@ -59,7 +56,8 @@ // ui::Compositor. ui::AcceleratedWidgetMac* GetAcceleratedWidgetMac(); - void DidCreateNewRendererCompositorFrameSink(); + void DidCreateNewRendererCompositorFrameSink( + cc::mojom::MojoCompositorFrameSinkClient* renderer_compositor_frame_sink); void SubmitCompositorFrame(const cc::LocalSurfaceId& local_surface_id, cc::CompositorFrame frame); void OnBeginFrameDidNotSwap(const cc::BeginFrameAck& ack); @@ -105,9 +103,6 @@ bool DelegatedFrameCanCreateResizeLock() const override; std::unique_ptr<CompositorResizeLock> DelegatedFrameHostCreateResizeLock() override; - void DelegatedFrameHostSendReclaimCompositorResources( - bool is_swap_ack, - const cc::ReturnedResourceArray& resources) override; void OnBeginFrame(const cc::BeginFrameArgs& args) override; bool IsAutoResizeEnabled() const override; @@ -169,6 +164,8 @@ std::unique_ptr<ui::Layer> root_layer_; bool has_transparent_background_ = false; + cc::mojom::MojoCompositorFrameSinkClient* renderer_compositor_frame_sink_ = + nullptr; base::WeakPtrFactory<BrowserCompositorMac> weak_factory_; };
diff --git a/content/browser/renderer_host/browser_compositor_view_mac.mm b/content/browser/renderer_host/browser_compositor_view_mac.mm index ec07e4f3..fe8ab8c0 100644 --- a/content/browser/renderer_host/browser_compositor_view_mac.mm +++ b/content/browser/renderer_host/browser_compositor_view_mac.mm
@@ -268,8 +268,11 @@ src_subrect, std::move(target), callback_with_decrement); } -void BrowserCompositorMac::DidCreateNewRendererCompositorFrameSink() { - delegated_frame_host_->DidCreateNewRendererCompositorFrameSink(); +void BrowserCompositorMac::DidCreateNewRendererCompositorFrameSink( + cc::mojom::MojoCompositorFrameSinkClient* renderer_compositor_frame_sink) { + renderer_compositor_frame_sink_ = renderer_compositor_frame_sink; + delegated_frame_host_->DidCreateNewRendererCompositorFrameSink( + renderer_compositor_frame_sink_); } void BrowserCompositorMac::SubmitCompositorFrame( @@ -432,13 +435,6 @@ return nullptr; } -void BrowserCompositorMac::DelegatedFrameHostSendReclaimCompositorResources( - bool is_swap_ack, - const cc::ReturnedResourceArray& resources) { - client_->BrowserCompositorMacSendReclaimCompositorResources(is_swap_ack, - resources); -} - void BrowserCompositorMac::OnBeginFrame(const cc::BeginFrameArgs& args) { client_->BrowserCompositorMacSendBeginFrame(args); }
diff --git a/content/browser/renderer_host/delegated_frame_host.cc b/content/browser/renderer_host/delegated_frame_host.cc index a4dbbc7..975a7501 100644 --- a/content/browser/renderer_host/delegated_frame_host.cc +++ b/content/browser/renderer_host/delegated_frame_host.cc
@@ -377,8 +377,10 @@ } } -void DelegatedFrameHost::DidCreateNewRendererCompositorFrameSink() { +void DelegatedFrameHost::DidCreateNewRendererCompositorFrameSink( + cc::mojom::MojoCompositorFrameSinkClient* renderer_compositor_frame_sink) { ResetCompositorFrameSinkSupport(); + renderer_compositor_frame_sink_ = renderer_compositor_frame_sink; CreateCompositorFrameSinkSupport(); has_frame_ = false; } @@ -413,8 +415,8 @@ frame.metadata.latency_info.begin(), frame.metadata.latency_info.end()); - client_->DelegatedFrameHostSendReclaimCompositorResources( - true /* is_swap_ack*/, resources); + renderer_compositor_frame_sink_->DidReceiveCompositorFrameAck(resources); + skipped_frames_ = true; BeginFrameDidNotSwap(ack); return; @@ -492,15 +494,14 @@ EvictDelegatedFrame(); } -void DelegatedFrameHost::DidReceiveCompositorFrameAck() { - client_->DelegatedFrameHostSendReclaimCompositorResources( - true /* is_swap_ack */, cc::ReturnedResourceArray()); +void DelegatedFrameHost::DidReceiveCompositorFrameAck( + const cc::ReturnedResourceArray& resources) { + renderer_compositor_frame_sink_->DidReceiveCompositorFrameAck(resources); } void DelegatedFrameHost::ReclaimResources( const cc::ReturnedResourceArray& resources) { - client_->DelegatedFrameHostSendReclaimCompositorResources( - false /* is_swap_ack */, resources); + renderer_compositor_frame_sink_->ReclaimResources(resources); } void DelegatedFrameHost::WillDrawSurface(const cc::LocalSurfaceId& id, @@ -833,12 +834,14 @@ void DelegatedFrameHost::CreateCompositorFrameSinkSupport() { DCHECK(!support_); + constexpr bool is_root = false; + constexpr bool handles_frame_sink_id_invalidation = false; + constexpr bool needs_sync_points = true; ImageTransportFactory* factory = ImageTransportFactory::GetInstance(); - support_ = base::MakeUnique<cc::CompositorFrameSinkSupport>( + support_ = cc::CompositorFrameSinkSupport::Create( this, factory->GetContextFactoryPrivate()->GetSurfaceManager(), - frame_sink_id_, false /* is_root */, - false /* handles_frame_sink_id_invalidation */, - true /* needs_sync_points */); + frame_sink_id_, is_root, handles_frame_sink_id_invalidation, + needs_sync_points); if (compositor_) compositor_->AddFrameSink(frame_sink_id_); if (needs_begin_frame_)
diff --git a/content/browser/renderer_host/delegated_frame_host.h b/content/browser/renderer_host/delegated_frame_host.h index faa46b7..6857a9a0 100644 --- a/content/browser/renderer_host/delegated_frame_host.h +++ b/content/browser/renderer_host/delegated_frame_host.h
@@ -70,10 +70,6 @@ virtual std::unique_ptr<CompositorResizeLock> DelegatedFrameHostCreateResizeLock() = 0; - virtual void DelegatedFrameHostSendReclaimCompositorResources( - bool is_swap_ack, - const cc::ReturnedResourceArray& resources) = 0; - virtual void OnBeginFrame(const cc::BeginFrameArgs& args) = 0; virtual bool IsAutoResizeEnabled() const = 0; }; @@ -112,7 +108,8 @@ void EvictDelegatedFrame() override; // cc::CompositorFrameSinkSupportClient implementation. - void DidReceiveCompositorFrameAck() override; + void DidReceiveCompositorFrameAck( + const cc::ReturnedResourceArray& resources) override; void OnBeginFrame(const cc::BeginFrameArgs& args) override; void ReclaimResources(const cc::ReturnedResourceArray& resources) override; void WillDrawSurface(const cc::LocalSurfaceId& id, @@ -120,7 +117,8 @@ // Public interface exposed to RenderWidgetHostView. - void DidCreateNewRendererCompositorFrameSink(); + void DidCreateNewRendererCompositorFrameSink( + cc::mojom::MojoCompositorFrameSinkClient* renderer_compositor_frame_sink); void SubmitCompositorFrame(const cc::LocalSurfaceId& local_surface_id, cc::CompositorFrame frame); void ClearDelegatedFrame(); @@ -322,6 +320,8 @@ cc::BeginFrameArgs::kInvalidFrameNumber; bool has_frame_ = false; + cc::mojom::MojoCompositorFrameSinkClient* renderer_compositor_frame_sink_ = + nullptr; std::unique_ptr<DelegatedFrameEvictor> delegated_frame_evictor_; };
diff --git a/content/browser/renderer_host/delegated_frame_host_client_aura.cc b/content/browser/renderer_host/delegated_frame_host_client_aura.cc index fc6519f4..5df61ef 100644 --- a/content/browser/renderer_host/delegated_frame_host_client_aura.cc +++ b/content/browser/renderer_host/delegated_frame_host_client_aura.cc
@@ -73,14 +73,6 @@ return base::MakeUnique<CompositorResizeLock>(this, desired_size); } -void DelegatedFrameHostClientAura:: - DelegatedFrameHostSendReclaimCompositorResources( - bool is_swap_ack, - const cc::ReturnedResourceArray& resources) { - render_widget_host_view_->host_->SendReclaimCompositorResources(is_swap_ack, - resources); -} - void DelegatedFrameHostClientAura::OnBeginFrame( const cc::BeginFrameArgs& args) { render_widget_host_view_->OnBeginFrame(args);
diff --git a/content/browser/renderer_host/delegated_frame_host_client_aura.h b/content/browser/renderer_host/delegated_frame_host_client_aura.h index ab66699..fd66b2b6 100644 --- a/content/browser/renderer_host/delegated_frame_host_client_aura.h +++ b/content/browser/renderer_host/delegated_frame_host_client_aura.h
@@ -36,9 +36,6 @@ bool DelegatedFrameCanCreateResizeLock() const override; std::unique_ptr<CompositorResizeLock> DelegatedFrameHostCreateResizeLock() override; - void DelegatedFrameHostSendReclaimCompositorResources( - bool is_swap_ack, - const cc::ReturnedResourceArray& resources) override; void OnBeginFrame(const cc::BeginFrameArgs& args) override; bool IsAutoResizeEnabled() const override;
diff --git a/content/browser/renderer_host/frame_sink_provider_impl.cc b/content/browser/renderer_host/frame_sink_provider_impl.cc new file mode 100644 index 0000000..d01ace8 --- /dev/null +++ b/content/browser/renderer_host/frame_sink_provider_impl.cc
@@ -0,0 +1,42 @@ +// 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 "content/browser/renderer_host/frame_sink_provider_impl.h" +#include "content/browser/renderer_host/render_widget_host_impl.h" + +namespace content { + +FrameSinkProviderImpl::FrameSinkProviderImpl(int32_t process_id) + : process_id_(process_id), binding_(this) {} + +FrameSinkProviderImpl::~FrameSinkProviderImpl() = default; + +void FrameSinkProviderImpl::Bind(mojom::FrameSinkProviderRequest request) { + if (binding_.is_bound()) { + DLOG(ERROR) << "Received multiple requests for FrameSinkProvider. " + << "There should be only one instance per renderer."; + return; + } + binding_.Bind(std::move(request)); +} + +void FrameSinkProviderImpl::Unbind() { + binding_.Close(); +} + +void FrameSinkProviderImpl::CreateForWidget( + int32_t widget_id, + cc::mojom::MojoCompositorFrameSinkRequest request, + cc::mojom::MojoCompositorFrameSinkClientPtr client) { + RenderWidgetHostImpl* render_widget_host_impl = + RenderWidgetHostImpl::FromID(process_id_, widget_id); + if (!render_widget_host_impl) { + DLOG(ERROR) << "No RenderWidgetHost exists with id " << widget_id + << "in process " << process_id_; + return; + } + render_widget_host_impl->RequestMojoCompositorFrameSink(std::move(request), + std::move(client)); +} + +} // namespace content
diff --git a/content/browser/renderer_host/frame_sink_provider_impl.h b/content/browser/renderer_host/frame_sink_provider_impl.h new file mode 100644 index 0000000..7823a6e5 --- /dev/null +++ b/content/browser/renderer_host/frame_sink_provider_impl.h
@@ -0,0 +1,39 @@ +// 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 CONTENT_BROWSER_RENDER_WIDGET_COMPOSITOR_FRAME_SINK_PROVIDER_H_ +#define CONTENT_BROWSER_RENDER_WIDGET_COMPOSITOR_FRAME_SINK_PROVIDER_H_ + +#include "content/common/frame_sink_provider.mojom.h" +#include "mojo/public/cpp/bindings/binding.h" + +namespace content { + +// This class lives in the browser and provides MojoCompositorFrameSink for the +// renderer. To access this class in the renderer, call: +// RenderThreadImpl::current()->GetFrameSinkProvider(). +class FrameSinkProviderImpl : public mojom::FrameSinkProvider { + public: + explicit FrameSinkProviderImpl(int32_t process_id); + ~FrameSinkProviderImpl() override; + + void Bind(mojom::FrameSinkProviderRequest request); + void Unbind(); + + // mojom::FrameSinkProvider implementation. + void CreateForWidget( + int32_t widget_id, + cc::mojom::MojoCompositorFrameSinkRequest request, + cc::mojom::MojoCompositorFrameSinkClientPtr client) override; + + private: + const int32_t process_id_; + mojo::Binding<mojom::FrameSinkProvider> binding_; + + DISALLOW_COPY_AND_ASSIGN(FrameSinkProviderImpl); +}; + +} // namespace content + +#endif // CONTENT_BROWSER_RENDER_WIDGET_COMPOSITOR_FRAME_SINK_PROVIDER_H_
diff --git a/content/browser/renderer_host/offscreen_canvas_compositor_frame_sink.cc b/content/browser/renderer_host/offscreen_canvas_compositor_frame_sink.cc index 7dd5c26..97f1fcf 100644 --- a/content/browser/renderer_host/offscreen_canvas_compositor_frame_sink.cc +++ b/content/browser/renderer_host/offscreen_canvas_compositor_frame_sink.cc
@@ -18,12 +18,13 @@ cc::mojom::MojoCompositorFrameSinkRequest request, cc::mojom::MojoCompositorFrameSinkClientPtr client) : provider_(provider), - support_(this, - provider->GetSurfaceManager(), - frame_sink_id, - false /* is_root */, - true /* handles_frame_sink_id_invalidation */, - true /* needs_sync_points */), + support_(cc::CompositorFrameSinkSupport::Create( + this, + provider->GetSurfaceManager(), + frame_sink_id, + false /* is_root */, + true /* handles_frame_sink_id_invalidation */, + true /* needs_sync_points */)), client_(std::move(client)), binding_(this, std::move(request)) { binding_.set_connection_error_handler( @@ -32,12 +33,12 @@ } OffscreenCanvasCompositorFrameSink::~OffscreenCanvasCompositorFrameSink() { - provider_->OnCompositorFrameSinkClientDestroyed(support_.frame_sink_id()); + provider_->OnCompositorFrameSinkClientDestroyed(support_->frame_sink_id()); } void OffscreenCanvasCompositorFrameSink::SetNeedsBeginFrame( bool needs_begin_frame) { - support_.SetNeedsBeginFrame(needs_begin_frame); + support_->SetNeedsBeginFrame(needs_begin_frame); } void OffscreenCanvasCompositorFrameSink::SubmitCompositorFrame( @@ -45,21 +46,22 @@ cc::CompositorFrame frame) { // TODO(samans): This will need to do something similar to // GpuCompositorFrameSink. - support_.SubmitCompositorFrame(local_surface_id, std::move(frame)); + support_->SubmitCompositorFrame(local_surface_id, std::move(frame)); } void OffscreenCanvasCompositorFrameSink::BeginFrameDidNotSwap( const cc::BeginFrameAck& begin_frame_ack) { - support_.BeginFrameDidNotSwap(begin_frame_ack); + support_->BeginFrameDidNotSwap(begin_frame_ack); } void OffscreenCanvasCompositorFrameSink::EvictFrame() { - support_.EvictFrame(); + support_->EvictFrame(); } -void OffscreenCanvasCompositorFrameSink::DidReceiveCompositorFrameAck() { +void OffscreenCanvasCompositorFrameSink::DidReceiveCompositorFrameAck( + const cc::ReturnedResourceArray& resources) { if (client_) - client_->DidReceiveCompositorFrameAck(); + client_->DidReceiveCompositorFrameAck(resources); } void OffscreenCanvasCompositorFrameSink::OnBeginFrame( @@ -80,7 +82,7 @@ void OffscreenCanvasCompositorFrameSink::OnClientConnectionLost() { provider_->OnCompositorFrameSinkClientConnectionLost( - support_.frame_sink_id()); + support_->frame_sink_id()); } } // namespace content
diff --git a/content/browser/renderer_host/offscreen_canvas_compositor_frame_sink.h b/content/browser/renderer_host/offscreen_canvas_compositor_frame_sink.h index 12a3532..3110b32b 100644 --- a/content/browser/renderer_host/offscreen_canvas_compositor_frame_sink.h +++ b/content/browser/renderer_host/offscreen_canvas_compositor_frame_sink.h
@@ -36,7 +36,8 @@ void EvictFrame() override; // Overridden from cc::CompositorFrameSinkSupportClient: - void DidReceiveCompositorFrameAck() override; + void DidReceiveCompositorFrameAck( + const cc::ReturnedResourceArray& resources) override; void OnBeginFrame(const cc::BeginFrameArgs& args) override; void ReclaimResources(const cc::ReturnedResourceArray& resources) override; void WillDrawSurface(const cc::LocalSurfaceId& local_surface_id, @@ -47,7 +48,7 @@ OffscreenCanvasCompositorFrameSinkProviderImpl* const provider_; - cc::CompositorFrameSinkSupport support_; + std::unique_ptr<cc::CompositorFrameSinkSupport> support_; cc::mojom::MojoCompositorFrameSinkClientPtr client_; cc::ReturnedResourceArray surface_returned_resources_; mojo::Binding<cc::mojom::MojoCompositorFrameSink> binding_;
diff --git a/content/browser/renderer_host/render_message_filter.cc b/content/browser/renderer_host/render_message_filter.cc index 8ca44c7..0d6f9e348 100644 --- a/content/browser/renderer_host/render_message_filter.cc +++ b/content/browser/renderer_host/render_message_filter.cc
@@ -160,18 +160,11 @@ bool handled = true; IPC_BEGIN_MESSAGE_MAP(RenderMessageFilter, message) #if defined(OS_MACOSX) - // On Mac, the IPCs ViewHostMsg_SwapCompositorFrame, ViewHostMsg_UpdateRect, - // and GpuCommandBufferMsg_SwapBuffersCompleted need to be handled in a - // nested message loop during resize. - IPC_MESSAGE_HANDLER_GENERIC( - ViewHostMsg_SwapCompositorFrame, - ResizeHelperPostMsgToUIThread(render_process_id_, message)) + // On Mac, ViewHostMsg_UpdateRect needs to be handled in a nested message + // loop during resize. IPC_MESSAGE_HANDLER_GENERIC( ViewHostMsg_UpdateRect, ResizeHelperPostMsgToUIThread(render_process_id_, message)) - IPC_MESSAGE_HANDLER_GENERIC( - ViewHostMsg_SetNeedsBeginFrames, - ResizeHelperPostMsgToUIThread(render_process_id_, message)) #endif IPC_MESSAGE_HANDLER_DELAY_REPLY(ChildProcessHostMsg_HasGpuProcess, OnHasGpuProcess)
diff --git a/content/browser/renderer_host/render_process_host_impl.cc b/content/browser/renderer_host/render_process_host_impl.cc index b9f0d3a..4c027b5 100644 --- a/content/browser/renderer_host/render_process_host_impl.cc +++ b/content/browser/renderer_host/render_process_host_impl.cc
@@ -703,6 +703,7 @@ #endif instance_weak_factory_( new base::WeakPtrFactory<RenderProcessHostImpl>(this)), + frame_sink_provider_(id_), weak_factory_(this) { widget_helper_ = new RenderWidgetHelper(); @@ -725,6 +726,7 @@ push_messaging_manager_.reset(new PushMessagingManager( GetID(), storage_partition_impl_->GetServiceWorkerContext())); + AddObserver(indexed_db_factory_.get()); #if defined(OS_MACOSX) if (BootstrapSandboxManager::ShouldEnable()) AddObserver(BootstrapSandboxManager::GetInstance()); @@ -1192,7 +1194,8 @@ auto registry = base::MakeUnique<service_manager::BinderRegistry>(); channel_->AddAssociatedInterfaceForIOThread( - base::Bind(&IndexedDBDispatcherHost::AddBinding, indexed_db_factory_)); + base::Bind(&IndexedDBDispatcherHost::AddBinding, + base::Unretained(indexed_db_factory_.get()))); #if defined(OS_ANDROID) AddUIThreadInterface( @@ -1241,6 +1244,10 @@ base::Unretained(this))); AddUIThreadInterface(registry.get(), + base::Bind(&RenderProcessHostImpl::BindFrameSinkProvider, + base::Unretained(this))); + + AddUIThreadInterface(registry.get(), base::Bind(&OffscreenCanvasSurfaceFactoryImpl::Create)); AddUIThreadInterface( registry.get(), @@ -1367,6 +1374,11 @@ offscreen_canvas_provider_->Add(std::move(request)); } +void RenderProcessHostImpl::BindFrameSinkProvider( + mojom::FrameSinkProviderRequest request) { + frame_sink_provider_.Bind(std::move(request)); +} + void RenderProcessHostImpl::CreateStoragePartitionService( mojo::InterfaceRequest<mojom::StoragePartitionService> request) { // DO NOT REMOVE THIS COMMAND LINE CHECK WITHOUT SECURITY REVIEW! @@ -2756,6 +2768,11 @@ if (delayed_cleanup_needed_) Cleanup(); + // If RenderProcessHostImpl is reused, the next renderer will send a new + // request for FrameSinkProvider so make sure frame_sink_provider_ is ready + // for that. + frame_sink_provider_.Unbind(); + // This object is not deleted at this point and might be reused later. // TODO(darin): clean this up }
diff --git a/content/browser/renderer_host/render_process_host_impl.h b/content/browser/renderer_host/render_process_host_impl.h index 4405d66..e36e8146 100644 --- a/content/browser/renderer_host/render_process_host_impl.h +++ b/content/browser/renderer_host/render_process_host_impl.h
@@ -23,6 +23,7 @@ #include "build/build_config.h" #include "content/browser/child_process_launcher.h" #include "content/browser/dom_storage/session_storage_namespace_impl.h" +#include "content/browser/renderer_host/frame_sink_provider_impl.h" #include "content/browser/renderer_host/offscreen_canvas_compositor_frame_sink_provider_impl.h" #include "content/browser/webrtc/webrtc_eventlog_host.h" #include "content/common/associated_interfaces.mojom.h" @@ -347,6 +348,7 @@ void CreateMusGpuRequest(ui::mojom::GpuRequest request); void CreateOffscreenCanvasCompositorFrameSinkProvider( blink::mojom::OffscreenCanvasCompositorFrameSinkProviderRequest request); + void BindFrameSinkProvider(mojom::FrameSinkProviderRequest request); void CreateStoragePartitionService( mojo::InterfaceRequest<mojom::StoragePartitionService> request); @@ -583,7 +585,8 @@ // The memory allocator, if any, in which the renderer will write its metrics. std::unique_ptr<base::SharedPersistentMemoryAllocator> metrics_allocator_; - scoped_refptr<IndexedDBDispatcherHost> indexed_db_factory_; + std::unique_ptr<IndexedDBDispatcherHost, BrowserThread::DeleteOnIOThread> + indexed_db_factory_; bool channel_connected_; bool sent_render_process_ready_; @@ -617,6 +620,8 @@ std::unique_ptr<base::WeakPtrFactory<RenderProcessHostImpl>> instance_weak_factory_; + FrameSinkProviderImpl frame_sink_provider_; + base::WeakPtrFactory<RenderProcessHostImpl> weak_factory_; DISALLOW_COPY_AND_ASSIGN(RenderProcessHostImpl);
diff --git a/content/browser/renderer_host/render_widget_host_impl.cc b/content/browser/renderer_host/render_widget_host_impl.cc index 8f605720..01b7e26 100644 --- a/content/browser/renderer_host/render_widget_host_impl.cc +++ b/content/browser/renderer_host/render_widget_host_impl.cc
@@ -296,6 +296,7 @@ base::TimeDelta::FromMilliseconds(kNewContentRenderingDelayMs)), current_content_source_id_(0), monitoring_composition_info_(false), + compositor_frame_sink_binding_(this), weak_factory_(this) { CHECK(delegate_); CHECK_NE(MSG_ROUTING_NONE, routing_id_); @@ -411,6 +412,10 @@ void RenderWidgetHostImpl::SetView(RenderWidgetHostViewBase* view) { if (view) { view_ = view->GetWeakPtr(); + if (renderer_compositor_frame_sink_.is_bound()) { + view->DidCreateNewRendererCompositorFrameSink( + renderer_compositor_frame_sink_.get()); + } // Views start out not needing begin frames, so only update its state // if the value has changed. if (needs_begin_frames_) @@ -556,10 +561,7 @@ OnUpdateScreenRectsAck) IPC_MESSAGE_HANDLER(ViewHostMsg_RequestMove, OnRequestMove) IPC_MESSAGE_HANDLER(ViewHostMsg_SetTooltipText, OnSetTooltipText) - IPC_MESSAGE_HANDLER_GENERIC(ViewHostMsg_SwapCompositorFrame, - OnSwapCompositorFrame(msg)) - IPC_MESSAGE_HANDLER(ViewHostMsg_BeginFrameDidNotSwap, - OnBeginFrameDidNotSwap) + IPC_MESSAGE_HANDLER(ViewHostMsg_BeginFrameDidNotSwap, BeginFrameDidNotSwap) IPC_MESSAGE_HANDLER(ViewHostMsg_UpdateRect, OnUpdateRect) IPC_MESSAGE_HANDLER(ViewHostMsg_SetCursor, OnSetCursor) IPC_MESSAGE_HANDLER(ViewHostMsg_TextInputStateChanged, @@ -868,6 +870,9 @@ if (!repaint_ack_pending_ && !resize_ack_pending_) return false; + if (!renderer_compositor_frame_sink_.is_bound()) + return false; + return true; } @@ -1899,32 +1904,7 @@ } } -bool RenderWidgetHostImpl::OnSwapCompositorFrame( - const IPC::Message& message) { - // This trace event is used in - // chrome/browser/extensions/api/cast_streaming/performance_test.cc - TRACE_EVENT0("test_fps,benchmark", "OnSwapCompositorFrame"); - - ViewHostMsg_SwapCompositorFrame::Param param; - if (!ViewHostMsg_SwapCompositorFrame::Read(&message, ¶m)) - return false; - uint32_t compositor_frame_sink_id = std::get<0>(param); - cc::LocalSurfaceId local_surface_id = std::get<1>(param); - cc::CompositorFrame frame(std::move(std::get<2>(param))); - - if (compositor_frame_sink_id != last_compositor_frame_sink_id_) { - if (view_) - view_->DidCreateNewRendererCompositorFrameSink(); - last_compositor_frame_sink_id_ = compositor_frame_sink_id; - } - - SubmitCompositorFrame(local_surface_id, std::move(frame)); - - return true; -} - -void RenderWidgetHostImpl::OnBeginFrameDidNotSwap( - const cc::BeginFrameAck& ack) { +void RenderWidgetHostImpl::BeginFrameDidNotSwap(const cc::BeginFrameAck& ack) { if (ack.sequence_number < cc::BeginFrameArgs::kStartingFrameNumber) { // Received an invalid ack, renderer misbehaved. bad_message::ReceivedBadMessage( @@ -2367,13 +2347,6 @@ return true; } -void RenderWidgetHostImpl::SendReclaimCompositorResources( - bool is_swap_ack, - const cc::ReturnedResourceArray& resources) { - Send(new ViewMsg_ReclaimCompositorResources( - routing_id_, last_compositor_frame_sink_id_, is_swap_ack, resources)); -} - void RenderWidgetHostImpl::DelayedAutoResized() { gfx::Size new_size = new_auto_size_; // Clear the new_auto_size_ since the empty value is used as a flag to @@ -2609,6 +2582,31 @@ monitor_updates)); } +void RenderWidgetHostImpl::RequestMojoCompositorFrameSink( + cc::mojom::MojoCompositorFrameSinkRequest request, + cc::mojom::MojoCompositorFrameSinkClientPtr client) { + if (compositor_frame_sink_binding_.is_bound()) + compositor_frame_sink_binding_.Close(); +#if defined(OS_MACOSX) + scoped_refptr<base::SingleThreadTaskRunner> task_runner = + ui::WindowResizeHelperMac::Get()->task_runner(); + // In tests, task_runner might not be initialized. + if (task_runner) + compositor_frame_sink_binding_.Bind(std::move(request), task_runner); + else + compositor_frame_sink_binding_.Bind(std::move(request)); +#else + compositor_frame_sink_binding_.Bind(std::move(request)); +#endif + if (view_) + view_->DidCreateNewRendererCompositorFrameSink(client.get()); + renderer_compositor_frame_sink_ = std::move(client); +} + +void RenderWidgetHostImpl::SetNeedsBeginFrame(bool needs_begin_frame) { + OnSetNeedsBeginFrames(needs_begin_frame); +} + void RenderWidgetHostImpl::SubmitCompositorFrame( const cc::LocalSurfaceId& local_surface_id, cc::CompositorFrame frame) { @@ -2679,7 +2677,7 @@ } else { cc::ReturnedResourceArray resources; cc::TransferableResource::ReturnResources(frame.resource_list, &resources); - SendReclaimCompositorResources(true /* is_swap_ack */, resources); + renderer_compositor_frame_sink_->DidReceiveCompositorFrameAck(resources); } // After navigation, if a frame belonging to the new page is received, stop
diff --git a/content/browser/renderer_host/render_widget_host_impl.h b/content/browser/renderer_host/render_widget_host_impl.h index c6c682f..365950b 100644 --- a/content/browser/renderer_host/render_widget_host_impl.h +++ b/content/browser/renderer_host/render_widget_host_impl.h
@@ -25,6 +25,7 @@ #include "base/time/time.h" #include "base/timer/elapsed_timer.h" #include "build/build_config.h" +#include "cc/ipc/mojo_compositor_frame_sink.mojom.h" #include "cc/resources/shared_bitmap.h" #include "cc/surfaces/frame_sink_id.h" #include "content/browser/renderer_host/event_with_latency_info.h" @@ -43,6 +44,7 @@ #include "content/public/common/page_zoom.h" #include "content/public/common/url_constants.h" #include "ipc/ipc_listener.h" +#include "mojo/public/cpp/bindings/binding.h" #include "third_party/WebKit/public/platform/WebDisplayMode.h" #include "ui/base/ime/text_input_mode.h" #include "ui/base/ime/text_input_type.h" @@ -93,11 +95,13 @@ // This implements the RenderWidgetHost interface that is exposed to // embedders of content, and adds things only visible to content. -class CONTENT_EXPORT RenderWidgetHostImpl : public RenderWidgetHost, - public InputRouterClient, - public InputAckHandler, - public TouchEmulatorClient, - public IPC::Listener { +class CONTENT_EXPORT RenderWidgetHostImpl + : public RenderWidgetHost, + public InputRouterClient, + public InputAckHandler, + public TouchEmulatorClient, + public NON_EXPORTED_BASE(cc::mojom::MojoCompositorFrameSink), + public IPC::Listener { public: // |routing_id| must not be MSG_ROUTING_NONE. // If this object outlives |delegate|, DetachDelegate() must be called when @@ -453,11 +457,6 @@ // locked. bool GotResponseToLockMouseRequest(bool allowed); - // Called by the view in response to OnSwapCompositorFrame. - void SendReclaimCompositorResources( - bool is_swap_ack, - const cc::ReturnedResourceArray& resources); - void set_allow_privileged_mouse_lock(bool allow) { allow_privileged_mouse_lock_ = allow; } @@ -572,14 +571,21 @@ // renderer unless it is for an immediate request. void RequestCompositionUpdates(bool immediate_request, bool monitor_updates); - // Submits the frame received from RenderWidget. - void SubmitCompositorFrame(const cc::LocalSurfaceId& local_surface_id, - cc::CompositorFrame frame); + void RequestMojoCompositorFrameSink( + cc::mojom::MojoCompositorFrameSinkRequest request, + cc::mojom::MojoCompositorFrameSinkClientPtr client); const cc::CompositorFrameMetadata& last_frame_metadata() { return last_frame_metadata_; } + // cc::mojom::MojoCompositorFrameSink implementation. + void SetNeedsBeginFrame(bool needs_begin_frame) override; + void SubmitCompositorFrame(const cc::LocalSurfaceId& local_surface_id, + cc::CompositorFrame frame) override; + void BeginFrameDidNotSwap(const cc::BeginFrameAck& ack) override; + void EvictFrame() override {} + protected: // --------------------------------------------------------------------------- // The following method is overridden by RenderViewHost to send upwards to @@ -638,7 +644,6 @@ void OnRequestMove(const gfx::Rect& pos); void OnSetTooltipText(const base::string16& tooltip_text, blink::WebTextDirection text_direction_hint); - bool OnSwapCompositorFrame(const IPC::Message& message); void OnBeginFrameDidNotSwap(const cc::BeginFrameAck& ack); void OnUpdateRect(const ViewHostMsg_UpdateRect_Params& params); void OnQueueSyntheticGesture(const SyntheticGesturePacket& gesture_packet); @@ -958,10 +963,9 @@ gfx::Size last_frame_size_; float last_device_scale_factor_; - // Each instance of RendererCompositorFrameSink has an ID that we keep track - // of so we can tell when a new instance has been created for the purpose of - // not returning stale resources. - uint32_t last_compositor_frame_sink_id_ = 0; + mojo::Binding<cc::mojom::MojoCompositorFrameSink> + compositor_frame_sink_binding_; + cc::mojom::MojoCompositorFrameSinkClientPtr renderer_compositor_frame_sink_; cc::CompositorFrameMetadata last_frame_metadata_;
diff --git a/content/browser/renderer_host/render_widget_host_unittest.cc b/content/browser/renderer_host/render_widget_host_unittest.cc index 41e969e..2b146c05 100644 --- a/content/browser/renderer_host/render_widget_host_unittest.cc +++ b/content/browser/renderer_host/render_widget_host_unittest.cc
@@ -34,7 +34,9 @@ #include "content/public/test/mock_render_process_host.h" #include "content/public/test/test_browser_context.h" #include "content/public/test/test_browser_thread_bundle.h" +#include "content/test/fake_renderer_compositor_frame_sink.h" #include "content/test/test_render_view_host.h" +#include "mojo/public/cpp/bindings/interface_request.h" #include "testing/gtest/include/gtest/gtest.h" #include "ui/display/screen.h" #include "ui/events/base_event_utils.h" @@ -562,6 +564,18 @@ SetInitialRenderSizeParams(); host_->Init(); host_->DisableGestureDebounce(); + + cc::mojom::MojoCompositorFrameSinkPtr sink; + cc::mojom::MojoCompositorFrameSinkRequest sink_request = + mojo::MakeRequest(&sink); + cc::mojom::MojoCompositorFrameSinkClientRequest client_request = + mojo::MakeRequest(&renderer_compositor_frame_sink_ptr_); + renderer_compositor_frame_sink_ = + base::MakeUnique<FakeRendererCompositorFrameSink>( + std::move(sink), std::move(client_request)); + host_->RequestMojoCompositorFrameSink( + std::move(sink_request), + std::move(renderer_compositor_frame_sink_ptr_)); } void TearDown() override { @@ -730,12 +744,16 @@ double last_simulated_event_time_seconds_; double simulated_event_time_delta_seconds_; IPC::TestSink* sink_; + std::unique_ptr<FakeRendererCompositorFrameSink> + renderer_compositor_frame_sink_; private: SyntheticWebTouchEvent touch_event_; TestBrowserThreadBundle thread_bundle_; base::test::ScopedFeatureList feature_list_; + cc::mojom::MojoCompositorFrameSinkClientPtr + renderer_compositor_frame_sink_ptr_; DISALLOW_COPY_AND_ASSIGN(RenderWidgetHostTest); }; @@ -1930,56 +1948,6 @@ ASSERT_FALSE(host_->input_router()->HasPendingEvents()); } -// Checks whether RWHI properly keeps track of the last compositor_frame_sink_id -// and notifies the view_ when it changes. -TEST_F(RenderWidgetHostTest, CompositorFrameSinkIdChanges) { - const gfx::Size frame_size(50, 50); - const cc::LocalSurfaceId local_surface_id(1, - base::UnguessableToken::Create()); - - // Ignore any IPC message sent so far. - sink_->ClearMessages(); - - // Submit a frame with compositor_frame_sink_id=1 - cc::CompositorFrame frame = MakeCompositorFrame(1.f, frame_size); - host_->OnMessageReceived( - ViewHostMsg_SwapCompositorFrame(0, 1, local_surface_id, frame)); - - // Send an ack. The right compositor_frame_sink_id must be sent. - host_->SendReclaimCompositorResources(true /* is_swap_ack */, - cc::ReturnedResourceArray()); - ASSERT_EQ(1u, sink_->message_count()); - { - const IPC::Message* msg = sink_->GetMessageAt(0); - EXPECT_EQ(ViewMsg_ReclaimCompositorResources::ID, msg->type()); - ViewMsg_ReclaimCompositorResources::Param params; - ViewMsg_ReclaimCompositorResources::Read(msg, ¶ms); - EXPECT_EQ(1u, std::get<0>(params)); // compositor_frame_sink_id - } - sink_->ClearMessages(); - - // Submit a frame with compositor_frame_sink_id=2. Verify that view_ is - // notified of the change in id. - view_->reset_did_change_compositor_frame_sink(); - frame = MakeCompositorFrame(1.f, frame_size); - host_->OnMessageReceived( - ViewHostMsg_SwapCompositorFrame(2, 2, local_surface_id, frame)); - EXPECT_TRUE(view_->did_change_compositor_frame_sink()); - - // Send an ack. The right compositor_frame_sink_id must be sent. - host_->SendReclaimCompositorResources(true /* is_swap_ack */, - cc::ReturnedResourceArray()); - ASSERT_EQ(1u, sink_->message_count()); - { - const IPC::Message* msg = sink_->GetMessageAt(0); - EXPECT_EQ(ViewMsg_ReclaimCompositorResources::ID, msg->type()); - ViewMsg_ReclaimCompositorResources::Param params; - ViewMsg_ReclaimCompositorResources::Read(msg, ¶ms); - EXPECT_EQ(2u, std::get<0>(params)); // compositor_frame_sink_id - } - sink_->ClearMessages(); -} - // Check that if messages of a frame arrive earlier than the frame itself, we // queue the messages until the frame arrives and then process them. TEST_F(RenderWidgetHostTest, FrameToken_MessageThenFrame) {
diff --git a/content/browser/renderer_host/render_widget_host_view_android.cc b/content/browser/renderer_host/render_widget_host_view_android.cc index 10998d2..ad4fc6e7 100644 --- a/content/browser/renderer_host/render_widget_host_view_android.cc +++ b/content/browser/renderer_host/render_widget_host_view_android.cc
@@ -1107,8 +1107,13 @@ void RenderWidgetHostViewAndroid::SendReclaimCompositorResources( bool is_swap_ack) { DCHECK(host_); - host_->SendReclaimCompositorResources(is_swap_ack, - surface_returned_resources_); + if (is_swap_ack) { + renderer_compositor_frame_sink_->DidReceiveCompositorFrameAck( + surface_returned_resources_); + } else { + renderer_compositor_frame_sink_->ReclaimResources( + surface_returned_resources_); + } surface_returned_resources_.clear(); } @@ -1126,8 +1131,10 @@ SendReclaimCompositorResources(false /* is_swap_ack */); } -void RenderWidgetHostViewAndroid::DidCreateNewRendererCompositorFrameSink() { +void RenderWidgetHostViewAndroid::DidCreateNewRendererCompositorFrameSink( + cc::mojom::MojoCompositorFrameSinkClient* renderer_compositor_frame_sink) { delegated_frame_host_->CompositorFrameSinkChanged(); + renderer_compositor_frame_sink_ = renderer_compositor_frame_sink; // Accumulated resources belong to the old RendererCompositorFrameSink and // should not be returned. surface_returned_resources_.clear();
diff --git a/content/browser/renderer_host/render_widget_host_view_android.h b/content/browser/renderer_host/render_widget_host_view_android.h index 0c69b818..cd3964b2 100644 --- a/content/browser/renderer_host/render_widget_host_view_android.h +++ b/content/browser/renderer_host/render_widget_host_view_android.h
@@ -129,7 +129,9 @@ BrowserAccessibilityDelegate* delegate, bool for_root_frame) override; bool LockMouse() override; void UnlockMouse() override; - void DidCreateNewRendererCompositorFrameSink() override; + void DidCreateNewRendererCompositorFrameSink( + cc::mojom::MojoCompositorFrameSinkClient* renderer_compositor_frame_sink) + override; void SubmitCompositorFrame(const cc::LocalSurfaceId& local_surface_id, cc::CompositorFrame frame) override; void OnBeginFrameDidNotSwap(const cc::BeginFrameAck& ack) override; @@ -399,6 +401,9 @@ float prev_top_shown_pix_; float prev_bottom_shown_pix_; + cc::mojom::MojoCompositorFrameSinkClient* renderer_compositor_frame_sink_ = + nullptr; + base::WeakPtrFactory<RenderWidgetHostViewAndroid> weak_ptr_factory_; DISALLOW_COPY_AND_ASSIGN(RenderWidgetHostViewAndroid);
diff --git a/content/browser/renderer_host/render_widget_host_view_aura.cc b/content/browser/renderer_host/render_widget_host_view_aura.cc index 61b60b053..3e49165 100644 --- a/content/browser/renderer_host/render_widget_host_view_aura.cc +++ b/content/browser/renderer_host/render_widget_host_view_aura.cc
@@ -890,9 +890,13 @@ } #endif -void RenderWidgetHostViewAura::DidCreateNewRendererCompositorFrameSink() { - if (delegated_frame_host_) - delegated_frame_host_->DidCreateNewRendererCompositorFrameSink(); +void RenderWidgetHostViewAura::DidCreateNewRendererCompositorFrameSink( + cc::mojom::MojoCompositorFrameSinkClient* renderer_compositor_frame_sink) { + renderer_compositor_frame_sink_ = renderer_compositor_frame_sink; + if (delegated_frame_host_) { + delegated_frame_host_->DidCreateNewRendererCompositorFrameSink( + renderer_compositor_frame_sink_); + } } void RenderWidgetHostViewAura::SubmitCompositorFrame( @@ -1938,6 +1942,10 @@ } delegated_frame_host_ = base::MakeUnique<DelegatedFrameHost>( frame_sink_id, delegated_frame_host_client_.get()); + if (renderer_compositor_frame_sink_) { + delegated_frame_host_->DidCreateNewRendererCompositorFrameSink( + renderer_compositor_frame_sink_); + } UpdateNeedsBeginFramesInternal(); // Let the page-level input event router know about our surface ID
diff --git a/content/browser/renderer_host/render_widget_host_view_aura.h b/content/browser/renderer_host/render_widget_host_view_aura.h index b5baff81..e57aa37 100644 --- a/content/browser/renderer_host/render_widget_host_view_aura.h +++ b/content/browser/renderer_host/render_widget_host_view_aura.h
@@ -164,7 +164,9 @@ void SetMainFrameAXTreeID(ui::AXTreeIDRegistry::AXTreeID id) override; bool LockMouse() override; void UnlockMouse() override; - void DidCreateNewRendererCompositorFrameSink() override; + void DidCreateNewRendererCompositorFrameSink( + cc::mojom::MojoCompositorFrameSinkClient* renderer_compositor_frame_sink) + override; void SubmitCompositorFrame(const cc::LocalSurfaceId& local_surface_id, cc::CompositorFrame frame) override; void OnBeginFrameDidNotSwap(const cc::BeginFrameAck& ack) override; @@ -580,6 +582,9 @@ float device_scale_factor_; + cc::mojom::MojoCompositorFrameSinkClient* renderer_compositor_frame_sink_ = + nullptr; + // While this is a ui::EventHandler for targetting, |event_handler_| actually // provides an implementation, and directs events to |host_|. std::unique_ptr<RenderWidgetHostViewEventHandler> event_handler_;
diff --git a/content/browser/renderer_host/render_widget_host_view_aura_unittest.cc b/content/browser/renderer_host/render_widget_host_view_aura_unittest.cc index 0eb0b68..ce0f2d4 100644 --- a/content/browser/renderer_host/render_widget_host_view_aura_unittest.cc +++ b/content/browser/renderer_host/render_widget_host_view_aura_unittest.cc
@@ -61,6 +61,7 @@ #include "content/public/common/context_menu_params.h" #include "content/public/test/mock_render_process_host.h" #include "content/public/test/test_browser_context.h" +#include "content/test/fake_renderer_compositor_frame_sink.h" #include "content/test/test_render_view_host.h" #include "content/test/test_web_contents.h" #include "ipc/ipc_message.h" @@ -412,10 +413,24 @@ new FakeDelegatedFrameHostClientAura(this)) { InstallDelegatedFrameHostClient( this, base::WrapUnique(delegated_frame_host_client_)); + CreateNewRendererCompositorFrameSink(); } ~FakeRenderWidgetHostViewAura() override {} + void CreateNewRendererCompositorFrameSink() { + cc::mojom::MojoCompositorFrameSinkPtr sink; + cc::mojom::MojoCompositorFrameSinkRequest sink_request = + mojo::MakeRequest(&sink); + cc::mojom::MojoCompositorFrameSinkClientRequest client_request = + mojo::MakeRequest(&renderer_compositor_frame_sink_ptr_); + renderer_compositor_frame_sink_ = + base::MakeUnique<FakeRendererCompositorFrameSink>( + std::move(sink), std::move(client_request)); + DidCreateNewRendererCompositorFrameSink( + renderer_compositor_frame_sink_ptr_.get()); + } + void DisableResizeLock() { delegated_frame_host_client_->DisableResizeLock(); } @@ -477,9 +492,13 @@ gfx::Size last_frame_size_; std::unique_ptr<cc::CopyOutputRequest> last_copy_request_; FakeWindowEventDispatcher* dispatcher_; + std::unique_ptr<FakeRendererCompositorFrameSink> + renderer_compositor_frame_sink_; private: FakeDelegatedFrameHostClientAura* delegated_frame_host_client_; + cc::mojom::MojoCompositorFrameSinkClientPtr + renderer_compositor_frame_sink_ptr_; DISALLOW_COPY_AND_ASSIGN(FakeRenderWidgetHostViewAura); }; @@ -2044,15 +2063,13 @@ cc::ReturnedResource resource; resource.id = 1; resources.push_back(resource); + view_->renderer_compositor_frame_sink_->Reset(); view_->ReclaimResources(resources); - EXPECT_EQ(1u, sink_->message_count()); - { - const IPC::Message* msg = sink_->GetMessageAt(0); - EXPECT_EQ(ViewMsg_ReclaimCompositorResources::ID, msg->type()); - ViewMsg_ReclaimCompositorResources::Param params; - ViewMsg_ReclaimCompositorResources::Read(msg, ¶ms); - EXPECT_FALSE(std::get<1>(params)); // is_swap_ack - } + view_->renderer_compositor_frame_sink_->Flush(); + EXPECT_FALSE(view_->renderer_compositor_frame_sink_->did_receive_ack()); + EXPECT_FALSE( + view_->renderer_compositor_frame_sink_->last_reclaimed_resources() + .empty()); } // This test verifies that when the compositor_frame_sink_id changes, the old @@ -2084,7 +2101,7 @@ EXPECT_EQ(0u, sink_->message_count()); // Signal that a new RendererCompositorFrameSink was created by the renderer. - view_->DidCreateNewRendererCompositorFrameSink(); + view_->CreateNewRendererCompositorFrameSink(); // Submit another frame. The resources for the previous frame belong to the // old RendererCompositorFrameSink and should not be returned. @@ -2093,17 +2110,12 @@ EXPECT_EQ(0u, sink_->message_count()); // Report that the surface is drawn to trigger an ACK. + view_->renderer_compositor_frame_sink_->Reset(); cc::Surface* surface = manager->GetSurfaceForId(view_->surface_id()); EXPECT_TRUE(surface); surface->RunDrawCallbacks(); - EXPECT_EQ(1u, sink_->message_count()); - { - const IPC::Message* msg = sink_->GetMessageAt(0); - EXPECT_EQ(ViewMsg_ReclaimCompositorResources::ID, msg->type()); - ViewMsg_ReclaimCompositorResources::Param params; - ViewMsg_ReclaimCompositorResources::Read(msg, ¶ms); - EXPECT_EQ(true, std::get<1>(params)); // is_swap_ack - } + view_->renderer_compositor_frame_sink_->Flush(); + EXPECT_TRUE(view_->renderer_compositor_frame_sink_->did_receive_ack()); manager->RemoveObserver(&manager_observer); } @@ -2336,28 +2348,29 @@ // Receive a frame of the new size, should be skipped and not produce a Resize // message. + view_->renderer_compositor_frame_sink_->Reset(); view_->SubmitCompositorFrame( kArbitraryLocalSurfaceId, MakeDelegatedFrame(1.f, size3, gfx::Rect(size3))); + view_->renderer_compositor_frame_sink_->Flush(); // Expect the frame ack; - EXPECT_EQ(1u, sink_->message_count()); - EXPECT_EQ(ViewMsg_ReclaimCompositorResources::ID, - sink_->GetMessageAt(0)->type()); - sink_->ClearMessages(); + EXPECT_TRUE(view_->renderer_compositor_frame_sink_->did_receive_ack()); EXPECT_EQ(size2.ToString(), view_->GetRequestedRendererSize().ToString()); // Receive a frame of the correct size, should not be skipped and, and should // produce a Resize message after the commit. + view_->renderer_compositor_frame_sink_->Reset(); view_->SubmitCompositorFrame( kArbitraryLocalSurfaceId, MakeDelegatedFrame(1.f, size2, gfx::Rect(size2))); + view_->renderer_compositor_frame_sink_->Flush(); cc::SurfaceId surface_id = view_->surface_id(); if (!surface_id.is_valid()) { // No frame ack yet. - EXPECT_EQ(0u, sink_->message_count()); + EXPECT_FALSE(view_->renderer_compositor_frame_sink_->did_receive_ack()); } else { // Frame isn't desired size, so early ack. - EXPECT_EQ(1u, sink_->message_count()); + EXPECT_TRUE(view_->renderer_compositor_frame_sink_->did_receive_ack()); } EXPECT_EQ(size2.ToString(), view_->GetRequestedRendererSize().ToString()); @@ -2382,8 +2395,6 @@ EXPECT_EQ(blink::WebInputEvent::kMouseMove, event->GetType()); break; } - case ViewMsg_ReclaimCompositorResources::ID: - break; case ViewMsg_Resize::ID: { EXPECT_FALSE(has_resize); ViewMsg_Resize::Param params; @@ -2623,7 +2634,7 @@ view_->RunOnCompositingDidCommit(); // Signal that a new RendererCompositorFrameSink was created. - view_->DidCreateNewRendererCompositorFrameSink(); + view_->CreateNewRendererCompositorFrameSink(); // Submit a frame from the new RendererCompositorFrameSink. EXPECT_CALL(observer, OnDelegatedFrameDamage(view_->window_, view_rect)); @@ -2633,7 +2644,7 @@ view_->RunOnCompositingDidCommit(); // Signal that a new RendererCompositorFrameSink was created. - view_->DidCreateNewRendererCompositorFrameSink(); + view_->CreateNewRendererCompositorFrameSink(); // Submit a frame from the new RendererCompositorFrameSink. view_->SubmitCompositorFrame( @@ -2643,7 +2654,7 @@ view_->RunOnCompositingDidCommit(); // Signal that a new RendererCompositorFrameSink was created. - view_->DidCreateNewRendererCompositorFrameSink(); + view_->CreateNewRendererCompositorFrameSink(); // Swap another frame, with a different surface id. EXPECT_CALL(observer, OnDelegatedFrameDamage(view_->window_, view_rect));
diff --git a/content/browser/renderer_host/render_widget_host_view_base.h b/content/browser/renderer_host/render_widget_host_view_base.h index 54bf4ab..3f0cdab 100644 --- a/content/browser/renderer_host/render_widget_host_view_base.h +++ b/content/browser/renderer_host/render_widget_host_view_base.h
@@ -19,6 +19,7 @@ #include "base/strings/string16.h" #include "base/timer/timer.h" #include "build/build_config.h" +#include "cc/ipc/mojo_compositor_frame_sink.mojom.h" #include "cc/output/compositor_frame.h" #include "cc/surfaces/surface_id.h" #include "content/browser/renderer_host/event_with_latency_info.h" @@ -222,7 +223,9 @@ // RendererCompositorFrameSink is created in the renderer. The view is // expected not to return resources belonging to the old // RendererCompositorFrameSink after this method finishes. - virtual void DidCreateNewRendererCompositorFrameSink() = 0; + virtual void DidCreateNewRendererCompositorFrameSink( + cc::mojom::MojoCompositorFrameSinkClient* + renderer_compositor_frame_sink) = 0; virtual void SubmitCompositorFrame(const cc::LocalSurfaceId& local_surface_id, cc::CompositorFrame frame) = 0;
diff --git a/content/browser/renderer_host/render_widget_host_view_mac.h b/content/browser/renderer_host/render_widget_host_view_mac.h index d72039d..5437503 100644 --- a/content/browser/renderer_host/render_widget_host_view_mac.h +++ b/content/browser/renderer_host/render_widget_host_view_mac.h
@@ -306,7 +306,9 @@ ui::AcceleratedWidgetMac* GetAcceleratedWidgetMac() const override; void FocusedNodeChanged(bool is_editable_node, const gfx::Rect& node_bounds_in_screen) override; - void DidCreateNewRendererCompositorFrameSink() override; + void DidCreateNewRendererCompositorFrameSink( + cc::mojom::MojoCompositorFrameSinkClient* renderer_compositor_frame_sink) + override; void SubmitCompositorFrame(const cc::LocalSurfaceId& local_surface_id, cc::CompositorFrame frame) override; void OnBeginFrameDidNotSwap(const cc::BeginFrameAck& ack) override; @@ -451,9 +453,6 @@ // BrowserCompositorMacClient implementation. NSView* BrowserCompositorMacGetNSView() const override; SkColor BrowserCompositorMacGetGutterColor(SkColor color) const override; - void BrowserCompositorMacSendReclaimCompositorResources( - bool is_swap_ack, - const cc::ReturnedResourceArray& resources) override; void BrowserCompositorMacSendBeginFrame( const cc::BeginFrameArgs& args) override;
diff --git a/content/browser/renderer_host/render_widget_host_view_mac.mm b/content/browser/renderer_host/render_widget_host_view_mac.mm index 0a2865a..896170a 100644 --- a/content/browser/renderer_host/render_widget_host_view_mac.mm +++ b/content/browser/renderer_host/render_widget_host_view_mac.mm
@@ -400,13 +400,6 @@ return color; } -void RenderWidgetHostViewMac:: - BrowserCompositorMacSendReclaimCompositorResources( - bool is_swap_ack, - const cc::ReturnedResourceArray& resources) { - render_widget_host_->SendReclaimCompositorResources(is_swap_ack, resources); -} - void RenderWidgetHostViewMac::BrowserCompositorMacSendBeginFrame( const cc::BeginFrameArgs& args) { needs_flush_input_ = false; @@ -1425,8 +1418,10 @@ } } -void RenderWidgetHostViewMac::DidCreateNewRendererCompositorFrameSink() { - browser_compositor_->DidCreateNewRendererCompositorFrameSink(); +void RenderWidgetHostViewMac::DidCreateNewRendererCompositorFrameSink( + cc::mojom::MojoCompositorFrameSinkClient* renderer_compositor_frame_sink) { + browser_compositor_->DidCreateNewRendererCompositorFrameSink( + renderer_compositor_frame_sink); } void RenderWidgetHostViewMac::SubmitCompositorFrame(
diff --git a/content/browser/screen_orientation/OWNERS b/content/browser/screen_orientation/OWNERS index 2d28246..20b13b9 100644 --- a/content/browser/screen_orientation/OWNERS +++ b/content/browser/screen_orientation/OWNERS
@@ -1 +1,2 @@ -mlamouri@chromium.org +file://third_party/WebKit/Source/modules/screen_orientation/OWNERS +
diff --git a/content/browser/service_manager/service_manager_context.cc b/content/browser/service_manager/service_manager_context.cc index a818801..42f0624 100644 --- a/content/browser/service_manager/service_manager_context.cc +++ b/content/browser/service_manager/service_manager_context.cc
@@ -9,6 +9,7 @@ #include <utility> #include "base/bind.h" +#include "base/command_line.h" #include "base/json/json_reader.h" #include "base/lazy_instance.h" #include "base/macros.h" @@ -28,6 +29,7 @@ #include "content/public/browser/utility_process_host.h" #include "content/public/browser/utility_process_host_client.h" #include "content/public/common/content_client.h" +#include "content/public/common/content_switches.h" #include "content/public/common/service_manager_connection.h" #include "content/public/common/service_names.mojom.h" #include "mojo/edk/embedder/embedder.h" @@ -331,6 +333,12 @@ GetContentClient() ->browser() ->RegisterUnsandboxedOutOfProcessServices(&unsandboxed_services); + if (base::CommandLine::ForCurrentProcess()->HasSwitch( + switches::kEnableNetworkService)) { + unsandboxed_services.insert( + std::make_pair(content::mojom::kNetworkServiceName, + base::ASCIIToUTF16("Network Service"))); + } for (const auto& service : unsandboxed_services) { packaged_services_connection_->AddServiceRequestHandler( service.first, base::Bind(&StartServiceInUtilityProcess, service.first,
diff --git a/content/browser/utility_process_host_impl.cc b/content/browser/utility_process_host_impl.cc index 4afd9e93..ea61cbf 100644 --- a/content/browser/utility_process_host_impl.cc +++ b/content/browser/utility_process_host_impl.cc
@@ -314,6 +314,7 @@ // Browser command-line switches to propagate to the utility process. static const char* const kSwitchNames[] = { + switches::kEnableNetworkService, switches::kNoSandbox, switches::kProfilerTiming, #if defined(OS_MACOSX)
diff --git a/content/common/BUILD.gn b/content/common/BUILD.gn index 2f80aacb..fd5c0dc 100644 --- a/content/common/BUILD.gn +++ b/content/common/BUILD.gn
@@ -585,6 +585,7 @@ "child_memory_coordinator.mojom", "field_trial_recorder.mojom", "frame.mojom", + "frame_sink_provider.mojom", "host_zoom.mojom", "image_downloader/image_downloader.mojom", "indexed_db/indexed_db.mojom",
diff --git a/content/common/frame_sink_provider.mojom b/content/common/frame_sink_provider.mojom new file mode 100644 index 0000000..5c2b129 --- /dev/null +++ b/content/common/frame_sink_provider.mojom
@@ -0,0 +1,10 @@ +module content.mojom; + +import "cc/ipc/mojo_compositor_frame_sink.mojom"; + +// This interface provides MojoCompositorFrameSink for the renderer. +interface FrameSinkProvider { + CreateForWidget( + int32 widget_id, cc.mojom.MojoCompositorFrameSink& request, + cc.mojom.MojoCompositorFrameSinkClient client); +};
diff --git a/content/common/swapped_out_messages.cc b/content/common/swapped_out_messages.cc index 233d07d..442cd3e 100644 --- a/content/common/swapped_out_messages.cc +++ b/content/common/swapped_out_messages.cc
@@ -28,7 +28,6 @@ case ViewHostMsg_Focus::ID: case ViewHostMsg_ShowFullscreenWidget::ID: case ViewHostMsg_ShowWidget::ID: - case ViewHostMsg_SwapCompositorFrame::ID: // Handled by SharedWorkerMessageFilter. case ViewHostMsg_DocumentDetached::ID: // Allow cross-process JavaScript calls.
diff --git a/content/common/view_messages.h b/content/common/view_messages.h index 4b14ed9..82ffcc94 100644 --- a/content/common/view_messages.h +++ b/content/common/view_messages.h
@@ -596,14 +596,6 @@ #endif -// Sent by browser to tell renderer compositor that some resources that were -// given to the browser in a swap are not being used anymore. -// If this message is in response to a swap then is_swap_ack is set. -IPC_MESSAGE_ROUTED3(ViewMsg_ReclaimCompositorResources, - uint32_t /* compositor_frame_sink_id */, - bool /* is_swap_ack */, - cc::ReturnedResourceArray /* resources */) - IPC_MESSAGE_ROUTED0(ViewMsg_SelectWordAroundCaret) // Sent by the browser to ask the renderer to redraw. Robust to events that can @@ -804,11 +796,6 @@ int /* minimum_percent */, int /* maximum_percent */) -IPC_MESSAGE_ROUTED3(ViewHostMsg_SwapCompositorFrame, - uint32_t /* compositor_frame_sink_id */, - cc::LocalSurfaceId /* local_surface_id */, - cc::CompositorFrame /* frame */) - IPC_MESSAGE_ROUTED2(ViewHostMsg_FrameSwapMessages, uint32_t /* frame_token */, std::vector<IPC::Message> /* messages */)
diff --git a/content/network/BUILD.gn b/content/network/BUILD.gn new file mode 100644 index 0000000..e351e7f --- /dev/null +++ b/content/network/BUILD.gn
@@ -0,0 +1,59 @@ +# Copyright 2017 The Chromium Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +import("//services/service_manager/public/service_manifest.gni") + +group("network") { + visibility = [ "//content/*" ] # This is an internal content API. + + if (is_component_build) { + public_deps = [ + "//content", + ] + } else { + public_deps = [ + ":network_sources", + ] + } +} + +source_set("network_sources") { + # Depend on via ":network above. + visibility = [ + ":network", + "//content", # For the component build. + "//content/app:*", + "//content/utility:utility", + ] + + sources = [ + "net_adapters.cc", + "net_adapters.h", + "network_context.cc", + "network_context.h", + "network_service.cc", + "network_service.h", + "url_loader_impl.cc", + "url_loader_impl.h", + ] + + configs += [ "//content:content_implementation" ] + + deps = [ + "//base", + "//content:export", + "//content/common", + "//content/common:mojo_bindings", + "//content/public/common:common_sources", + "//mojo/public/cpp/bindings", + "//net", + "//services/service_manager/public/interfaces", + "//services/service_manager/public/cpp", + ] +} + +service_manifest("manifest") { + name = "network" + source = "manifest.json" +}
diff --git a/content/network/DEPS b/content/network/DEPS new file mode 100644 index 0000000..4b23d290 --- /dev/null +++ b/content/network/DEPS
@@ -0,0 +1,19 @@ +# Tight rules since this will move to services/network. See README. +include_rules = [ + "-content", + "+content/common/content_export.h", + "+content/common/url_loader.mojom.h", + "+content/common/url_loader_factory.mojom.h", + "+content/network", + "+content/public/common/content_client.h", + "+content/public/common/referrer.h", + "+content/public/common/resource_response.h", + "+services/service_manager/public", +] + +specific_include_rules = { + '.*_[a-z]*test.*': [ + "+content/browser/loader/test_url_loader_client.h", + "+content/public/common/content_paths.h", + ], +}
diff --git a/content/network/README.md b/content/network/README.md new file mode 100644 index 0000000..cffabdd --- /dev/null +++ b/content/network/README.md
@@ -0,0 +1 @@ +content/network is a temporary location for the Network Service. While it will eventually end up in services/network, we can't move it now until content/common/url_loader.mojom can move. That is blocked on removing the old non-mojom IPC loading path (see LoadingWithMojo feature flag). Once that happens, the mojom can be self contained and we can move it and this code. \ No newline at end of file
diff --git a/content/network/manifest.json b/content/network/manifest.json new file mode 100644 index 0000000..daa39ec --- /dev/null +++ b/content/network/manifest.json
@@ -0,0 +1,16 @@ +{ + "name": "network", + "display_name": "Network Service", + "interface_provider_specs": { + "service_manager:connector": { + "provides": { + "url_loader": [ + "content::mojom::URLLoaderFactory" + ] + }, + "requires": { + "service_manager": [ "service_manager:all_users" ] + } + } + } +}
diff --git a/content/network/net_adapters.cc b/content/network/net_adapters.cc new file mode 100644 index 0000000..ee0bc33 --- /dev/null +++ b/content/network/net_adapters.cc
@@ -0,0 +1,54 @@ +// 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 "content/network/net_adapters.h" + +#include "net/base/net_errors.h" + +namespace content { + +namespace { +const uint32_t kMaxBufSize = 64 * 1024; +} + +NetToMojoPendingBuffer::NetToMojoPendingBuffer( + mojo::ScopedDataPipeProducerHandle handle, + void* buffer) + : handle_(std::move(handle)), buffer_(buffer) {} + +NetToMojoPendingBuffer::~NetToMojoPendingBuffer() { + if (handle_.is_valid()) + EndWriteDataRaw(handle_.get(), 0); +} + +MojoResult NetToMojoPendingBuffer::BeginWrite( + mojo::ScopedDataPipeProducerHandle* handle, + scoped_refptr<NetToMojoPendingBuffer>* pending, + uint32_t* num_bytes) { + void* buf; + *num_bytes = 0; + MojoResult result = BeginWriteDataRaw(handle->get(), &buf, num_bytes, + MOJO_WRITE_DATA_FLAG_NONE); + if (result == MOJO_RESULT_OK) { + if (*num_bytes > kMaxBufSize) + *num_bytes = kMaxBufSize; + *pending = new NetToMojoPendingBuffer(std::move(*handle), buf); + } + return result; +} + +mojo::ScopedDataPipeProducerHandle NetToMojoPendingBuffer::Complete( + uint32_t num_bytes) { + EndWriteDataRaw(handle_.get(), num_bytes); + buffer_ = NULL; + return std::move(handle_); +} + +NetToMojoIOBuffer::NetToMojoIOBuffer(NetToMojoPendingBuffer* pending_buffer) + : net::WrappedIOBuffer(pending_buffer->buffer()), + pending_buffer_(pending_buffer) {} + +NetToMojoIOBuffer::~NetToMojoIOBuffer() {} + +} // namespace content
diff --git a/content/network/net_adapters.h b/content/network/net_adapters.h new file mode 100644 index 0000000..ab6a496 --- /dev/null +++ b/content/network/net_adapters.h
@@ -0,0 +1,71 @@ +// 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 CONTENT_NETWORK_NET_ADAPTERS_ +#define CONTENT_NETWORK_NET_ADAPTERS_ + +#include <stdint.h> + +#include "base/macros.h" +#include "mojo/public/cpp/system/data_pipe.h" +#include "net/base/io_buffer.h" + +namespace content { + +// These adapters are used to transfer data between a Mojo pipe and the net +// library. +// +// Mojo pipe Data flow Network library +// ---------------------------------------------------------- +// NetToMojoPendingBuffer <--- NetToMojoIOBuffer +// +// While the operation is in progress, the Mojo-side objects keep ownership +// of the Mojo pipe, which in turn is kept alive by the IOBuffer. This allows +// the request to potentially outlive the object managing the translation. +// Mojo side of a Net -> Mojo copy. The buffer is allocated by Mojo. +class NetToMojoPendingBuffer + : public base::RefCountedThreadSafe<NetToMojoPendingBuffer> { + public: + // Begins a two-phase write to the data pipe. + // + // On success, MOJO_RESULT_OK will be returned. The ownership of the given + // producer handle will be transferred to the new NetToMojoPendingBuffer that + // will be placed into *pending, and the size of the buffer will be in + // *num_bytes. + // + // On failure or MOJO_RESULT_SHOULD_WAIT, there will be no change to the + // handle, and *pending and *num_bytes will be unused. + static MojoResult BeginWrite(mojo::ScopedDataPipeProducerHandle* handle, + scoped_refptr<NetToMojoPendingBuffer>* pending, + uint32_t* num_bytes); + // Called to indicate the buffer is done being written to. Passes ownership + // of the pipe back to the caller. + mojo::ScopedDataPipeProducerHandle Complete(uint32_t num_bytes); + char* buffer() { return static_cast<char*>(buffer_); } + + private: + friend class base::RefCountedThreadSafe<NetToMojoPendingBuffer>; + // Takes ownership of the handle. + NetToMojoPendingBuffer(mojo::ScopedDataPipeProducerHandle handle, + void* buffer); + ~NetToMojoPendingBuffer(); + mojo::ScopedDataPipeProducerHandle handle_; + void* buffer_; + DISALLOW_COPY_AND_ASSIGN(NetToMojoPendingBuffer); +}; + +// Net side of a Net -> Mojo copy. The data will be read from the network and +// copied into the buffer associated with the pending mojo write. +class NetToMojoIOBuffer : public net::WrappedIOBuffer { + public: + explicit NetToMojoIOBuffer(NetToMojoPendingBuffer* pending_buffer); + + private: + ~NetToMojoIOBuffer() override; + scoped_refptr<NetToMojoPendingBuffer> pending_buffer_; +}; + +} // namespace content + +#endif // CONTENT_NETWORK_NET_ADAPTERS_
diff --git a/content/network/network_context.cc b/content/network/network_context.cc new file mode 100644 index 0000000..5637a659 --- /dev/null +++ b/content/network/network_context.cc
@@ -0,0 +1,128 @@ +// 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 "content/network/network_context.h" + +#include "base/command_line.h" +#include "base/logging.h" +#include "content/network/url_loader_impl.h" +#include "content/public/common/content_client.h" +#include "net/dns/host_resolver.h" +#include "net/dns/mapped_host_resolver.h" +#include "net/log/net_log_util.h" +#include "net/log/write_to_file_net_log_observer.h" +#include "net/proxy/proxy_service.h" +#include "net/url_request/url_request_context.h" +#include "net/url_request/url_request_context_builder.h" + +namespace content { + +namespace { +// Logs network information to the specified file. +const char kLogNetLog[] = "log-net-log"; + +// Applies the specified mapping rules when resolving hosts. Please see the +// comment of net::MappedHostResolver::AddRulesFromString() for rule format. +const char kHostResolverRules[] = "host-resolver-rules"; + +// Ignores certificate-related errors. +const char kIgnoreCertificateErrors[] = "ignore-certificate-errors"; + +std::unique_ptr<net::URLRequestContext> MakeURLRequestContext() { + net::URLRequestContextBuilder builder; + net::URLRequestContextBuilder::HttpNetworkSessionParams params; + const base::CommandLine* command_line = + base::CommandLine::ForCurrentProcess(); + if (command_line->HasSwitch(kIgnoreCertificateErrors)) + params.ignore_certificate_errors = true; + builder.set_http_network_session_params(params); + if (command_line->HasSwitch(kHostResolverRules)) { + std::unique_ptr<net::HostResolver> host_resolver( + net::HostResolver::CreateDefaultResolver(nullptr)); + std::unique_ptr<net::MappedHostResolver> remapped_host_resolver( + new net::MappedHostResolver(std::move(host_resolver))); + remapped_host_resolver->SetRulesFromString( + command_line->GetSwitchValueASCII(kHostResolverRules)); + builder.set_host_resolver(std::move(remapped_host_resolver)); + } + builder.set_accept_language("en-us,en"); + builder.set_user_agent(GetContentClient()->GetUserAgent()); + builder.set_proxy_service(net::ProxyService::CreateDirect()); + net::URLRequestContextBuilder::HttpCacheParams cache_params; + + // We store the cache in memory so we can run many shells in parallel when + // running tests, otherwise the network services in each shell will corrupt + // the disk cache. + cache_params.type = net::URLRequestContextBuilder::HttpCacheParams::IN_MEMORY; + + builder.EnableHttpCache(cache_params); + builder.set_file_enabled(true); + return builder.Build(); +} + +} // namespace + +class NetworkContext::MojoNetLog : public net::NetLog { + public: + MojoNetLog() { + const base::CommandLine* command_line = + base::CommandLine::ForCurrentProcess(); + if (!command_line->HasSwitch(kLogNetLog)) + return; + base::FilePath log_path = command_line->GetSwitchValuePath(kLogNetLog); + base::ScopedFILE file; +#if defined(OS_WIN) + file.reset(_wfopen(log_path.value().c_str(), L"w")); +#elif defined(OS_POSIX) + file.reset(fopen(log_path.value().c_str(), "w")); +#endif + if (!file) { + LOG(ERROR) << "Could not open file " << log_path.value() + << " for net logging"; + } else { + write_to_file_observer_.reset(new net::WriteToFileNetLogObserver()); + write_to_file_observer_->set_capture_mode( + net::NetLogCaptureMode::IncludeCookiesAndCredentials()); + write_to_file_observer_->StartObserving(this, std::move(file), nullptr, + nullptr); + } + } + ~MojoNetLog() override { + if (write_to_file_observer_) + write_to_file_observer_->StopObserving(nullptr); + } + + private: + std::unique_ptr<net::WriteToFileNetLogObserver> write_to_file_observer_; + DISALLOW_COPY_AND_ASSIGN(MojoNetLog); +}; + +NetworkContext::NetworkContext() + : net_log_(new MojoNetLog), + url_request_context_(MakeURLRequestContext()), + in_shutdown_(false) {} + +NetworkContext::~NetworkContext() { + in_shutdown_ = true; + // Call each URLLoaderImpl and ask it to release its net::URLRequest, as the + // corresponding net::URLRequestContext is going away with this + // NetworkContext. The loaders can be deregistering themselves in Cleanup(), + // so iterate over a copy. + for (auto* url_loader : url_loaders_) + url_loader->Cleanup(); +} + +void NetworkContext::RegisterURLLoader(URLLoaderImpl* url_loader) { + DCHECK(url_loaders_.count(url_loader) == 0); + url_loaders_.insert(url_loader); +} + +void NetworkContext::DeregisterURLLoader(URLLoaderImpl* url_loader) { + if (!in_shutdown_) { + size_t removed_count = url_loaders_.erase(url_loader); + DCHECK(removed_count); + } +} + +} // namespace content
diff --git a/content/network/network_context.h b/content/network/network_context.h new file mode 100644 index 0000000..324ac8e --- /dev/null +++ b/content/network/network_context.h
@@ -0,0 +1,58 @@ +// 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 CONTENT_NETWORK_NETWORK_CONTEXT_H_ +#define CONTENT_NETWORK_NETWORK_CONTEXT_H_ + +#include <stdint.h> + +#include <memory> +#include <set> + +#include "base/macros.h" +#include "content/common/content_export.h" + +namespace net { +class URLRequestContext; +} + +namespace content { +class URLLoaderImpl; + +class CONTENT_EXPORT NetworkContext { + public: + NetworkContext(); + ~NetworkContext(); + + net::URLRequestContext* url_request_context() { + return url_request_context_.get(); + } + + // These are called by individual url loaders as they are being created and + // destroyed. + void RegisterURLLoader(URLLoaderImpl* url_loader); + void DeregisterURLLoader(URLLoaderImpl* url_loader); + + private: + class MojoNetLog; + std::unique_ptr<MojoNetLog> net_log_; + + std::unique_ptr<net::URLRequestContext> url_request_context_; + + // URLLoaderImpls register themselves with the NetworkContext so that they can + // be cleaned up when the NetworkContext goes away. This is needed as + // net::URLRequests held by URLLoaderImpls have to be gone when + // net::URLRequestContext (held by NetworkContext) is destroyed. + std::set<URLLoaderImpl*> url_loaders_; + + // Set when entering the destructor, in order to avoid manipulations of the + // |url_loaders_| (as a url_loader might delete itself in Cleanup()). + bool in_shutdown_; + + DISALLOW_COPY_AND_ASSIGN(NetworkContext); +}; + +} // namespace content + +#endif // CONTENT_NETWORK_NETWORK_CONTEXT_H_
diff --git a/content/network/network_service.cc b/content/network/network_service.cc new file mode 100644 index 0000000..2e7a4f9 --- /dev/null +++ b/content/network/network_service.cc
@@ -0,0 +1,39 @@ +// 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 "content/network/network_service.h" + +#include "base/logging.h" +#include "base/memory/ptr_util.h" +#include "services/service_manager/public/cpp/service_info.h" + +namespace content { + +NetworkService::NetworkService() { + registry_.AddInterface<mojom::URLLoaderFactory>(this); +} + +NetworkService::~NetworkService() = default; + +// static +std::unique_ptr<service_manager::Service> +NetworkService::CreateNetworkService() { + return base::MakeUnique<NetworkService>(); +} + +void NetworkService::OnBindInterface( + const service_manager::ServiceInfo& source_info, + const std::string& interface_name, + mojo::ScopedMessagePipeHandle interface_pipe) { + registry_.BindInterface(source_info.identity, interface_name, + std::move(interface_pipe)); +} + +void NetworkService::Create(const service_manager::Identity& remote_identity, + mojom::URLLoaderFactoryRequest request) { + // TODO(yzshen): Create URLLoaderFactoryImpl. + NOTIMPLEMENTED(); +} + +} // namespace content
diff --git a/content/network/network_service.h b/content/network/network_service.h new file mode 100644 index 0000000..4b705a2 --- /dev/null +++ b/content/network/network_service.h
@@ -0,0 +1,44 @@ +// 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 CONTENT_NETWORK_NETWORK_SERVICE_H_ +#define CONTENT_NETWORK_NETWORK_SERVICE_H_ + +#include <memory> + +#include "base/macros.h" +#include "content/common/url_loader_factory.mojom.h" +#include "services/service_manager/public/cpp/binder_registry.h" +#include "services/service_manager/public/cpp/interface_factory.h" +#include "services/service_manager/public/cpp/service.h" + +namespace content { + +class NetworkService + : public service_manager::Service, + public service_manager::InterfaceFactory<mojom::URLLoaderFactory> { + public: + NetworkService(); + ~NetworkService() override; + + static std::unique_ptr<service_manager::Service> CreateNetworkService(); + + private: + // service_manager::Service implementation. + void OnBindInterface(const service_manager::ServiceInfo& source_info, + const std::string& interface_name, + mojo::ScopedMessagePipeHandle interface_pipe) override; + + // service_manager::InterfaceFactory<mojom::UrlLoaderFactory>: + void Create(const service_manager::Identity& remote_identity, + mojom::URLLoaderFactoryRequest request) override; + + service_manager::BinderRegistry registry_; + + DISALLOW_COPY_AND_ASSIGN(NetworkService); +}; + +} // namespace content + +#endif // CONTENT_NETWORK_NETWORK_SERVICE_H_
diff --git a/content/network/url_loader_impl.cc b/content/network/url_loader_impl.cc new file mode 100644 index 0000000..04b6198e --- /dev/null +++ b/content/network/url_loader_impl.cc
@@ -0,0 +1,391 @@ +// 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 "content/network/url_loader_impl.h" + +#include "base/task_scheduler/post_task.h" +#include "base/threading/thread_task_runner_handle.h" +#include "content/network/net_adapters.h" +#include "content/network/network_context.h" +#include "content/public/common/referrer.h" +#include "content/public/common/resource_response.h" +#include "net/base/elements_upload_data_stream.h" +#include "net/base/load_flags.h" +#include "net/base/upload_bytes_element_reader.h" +#include "net/base/upload_file_element_reader.h" +#include "net/url_request/url_request_context.h" + +namespace content { + +namespace { +constexpr size_t kDefaultAllocationSize = 512 * 1024; + +// TODO: this duplicates ResourceDispatcherHostImpl::BuildLoadFlagsForRequest. +int BuildLoadFlagsForRequest(const ResourceRequest& request, + bool is_sync_load) { + int load_flags = request.load_flags; + + // Although EV status is irrelevant to sub-frames and sub-resources, we have + // to perform EV certificate verification on all resources because an HTTP + // keep-alive connection created to load a sub-frame or a sub-resource could + // be reused to load a main frame. + load_flags |= net::LOAD_VERIFY_EV_CERT; + if (request.resource_type == RESOURCE_TYPE_MAIN_FRAME) { + load_flags |= net::LOAD_MAIN_FRAME_DEPRECATED; + } else if (request.resource_type == RESOURCE_TYPE_PREFETCH) { + load_flags |= net::LOAD_PREFETCH; + } + + if (is_sync_load) + load_flags |= net::LOAD_IGNORE_LIMITS; + + return load_flags; +} + +// TODO: this duplicates some of PopulateResourceResponse in +// content/browser/loader/resource_loader.cc +void PopulateResourceResponse(net::URLRequest* request, + ResourceResponse* response) { + response->head.request_time = request->request_time(); + response->head.response_time = request->response_time(); + response->head.headers = request->response_headers(); + request->GetCharset(&response->head.charset); + response->head.content_length = request->GetExpectedContentSize(); + request->GetMimeType(&response->head.mime_type); + net::HttpResponseInfo response_info = request->response_info(); + response->head.was_fetched_via_spdy = response_info.was_fetched_via_spdy; + response->head.was_alpn_negotiated = response_info.was_alpn_negotiated; + response->head.alpn_negotiated_protocol = + response_info.alpn_negotiated_protocol; + response->head.connection_info = response_info.connection_info; + response->head.socket_address = response_info.socket_address; + + response->head.effective_connection_type = + net::EFFECTIVE_CONNECTION_TYPE_UNKNOWN; +} + +// A subclass of net::UploadBytesElementReader which owns +// ResourceRequestBodyImpl. +class BytesElementReader : public net::UploadBytesElementReader { + public: + BytesElementReader(ResourceRequestBodyImpl* resource_request_body, + const ResourceRequestBodyImpl::Element& element) + : net::UploadBytesElementReader(element.bytes(), element.length()), + resource_request_body_(resource_request_body) { + DCHECK_EQ(ResourceRequestBodyImpl::Element::TYPE_BYTES, element.type()); + } + + ~BytesElementReader() override {} + + private: + scoped_refptr<ResourceRequestBodyImpl> resource_request_body_; + + DISALLOW_COPY_AND_ASSIGN(BytesElementReader); +}; + +// A subclass of net::UploadFileElementReader which owns +// ResourceRequestBodyImpl. +// This class is necessary to ensure the BlobData and any attached shareable +// files survive until upload completion. +class FileElementReader : public net::UploadFileElementReader { + public: + FileElementReader(ResourceRequestBodyImpl* resource_request_body, + base::TaskRunner* task_runner, + const ResourceRequestBodyImpl::Element& element) + : net::UploadFileElementReader(task_runner, + element.path(), + element.offset(), + element.length(), + element.expected_modification_time()), + resource_request_body_(resource_request_body) { + DCHECK_EQ(ResourceRequestBodyImpl::Element::TYPE_FILE, element.type()); + } + + ~FileElementReader() override {} + + private: + scoped_refptr<ResourceRequestBodyImpl> resource_request_body_; + + DISALLOW_COPY_AND_ASSIGN(FileElementReader); +}; + +// TODO: copied from content/browser/loader/upload_data_stream_builder.cc. +std::unique_ptr<net::UploadDataStream> CreateUploadDataStream( + ResourceRequestBodyImpl* body, + base::SequencedTaskRunner* file_task_runner) { + std::vector<std::unique_ptr<net::UploadElementReader>> element_readers; + for (const auto& element : *body->elements()) { + switch (element.type()) { + case ResourceRequestBodyImpl::Element::TYPE_BYTES: + element_readers.push_back( + base::MakeUnique<BytesElementReader>(body, element)); + break; + case ResourceRequestBodyImpl::Element::TYPE_FILE: + element_readers.push_back(base::MakeUnique<FileElementReader>( + body, file_task_runner, element)); + break; + case ResourceRequestBodyImpl::Element::TYPE_FILE_FILESYSTEM: + NOTIMPLEMENTED(); + break; + case ResourceRequestBodyImpl::Element::TYPE_BLOB: { + NOTIMPLEMENTED(); + break; + } + case ResourceRequestBodyImpl::Element::TYPE_DISK_CACHE_ENTRY: + case ResourceRequestBodyImpl::Element::TYPE_BYTES_DESCRIPTION: + case ResourceRequestBodyImpl::Element::TYPE_UNKNOWN: + NOTREACHED(); + break; + } + } + + return base::MakeUnique<net::ElementsUploadDataStream>( + std::move(element_readers), body->identifier()); +} + +} // namespace + +URLLoaderImpl::URLLoaderImpl(NetworkContext* context, + mojom::URLLoaderRequest url_loader_request, + const ResourceRequest& request, + mojom::URLLoaderClientPtr url_loader_client) + : context_(context), + connected_(true), + binding_(this, std::move(url_loader_request)), + url_loader_client_(std::move(url_loader_client)), + writable_handle_watcher_(FROM_HERE, + mojo::SimpleWatcher::ArmingPolicy::MANUAL), + peer_closed_handle_watcher_(FROM_HERE, + mojo::SimpleWatcher::ArmingPolicy::MANUAL), + weak_ptr_factory_(this) { + binding_.set_connection_error_handler( + base::Bind(&URLLoaderImpl::OnConnectionError, base::Unretained(this))); + + url_request_ = context_->url_request_context()->CreateRequest( + GURL(request.url), net::DEFAULT_PRIORITY, this); + url_request_->set_method(request.method); + + const Referrer referrer(request.referrer, request.referrer_policy); + Referrer::SetReferrerForRequest(url_request_.get(), referrer); + + net::HttpRequestHeaders headers; + headers.AddHeadersFromString(request.headers); + url_request_->SetExtraRequestHeaders(headers); + + // Resolve elements from request_body and prepare upload data. + if (request.request_body.get()) { + scoped_refptr<base::SequencedTaskRunner> task_runner = + base::CreateSequencedTaskRunnerWithTraits( + base::TaskTraits().MayBlock().WithPriority( + base::TaskPriority::USER_VISIBLE)); + url_request_->set_upload( + CreateUploadDataStream(request.request_body.get(), task_runner.get())); + } + + int load_flags = BuildLoadFlagsForRequest(request, false); + url_request_->SetLoadFlags(load_flags); + + url_request_->Start(); +} + +URLLoaderImpl::~URLLoaderImpl() {} + +void URLLoaderImpl::Cleanup() { + // The associated network context is going away and we have to destroy + // net::URLRequest hold by this loader. + delete this; +} + +void URLLoaderImpl::FollowRedirect() { + if (!url_request_) { + NotifyCompleted(net::ERR_UNEXPECTED); + return; + } + + url_request_->FollowDeferredRedirect(); +} + +void URLLoaderImpl::SetPriority(net::RequestPriority priority, + int32_t intra_priority_value) { + NOTIMPLEMENTED(); +} + +void URLLoaderImpl::OnReceivedRedirect(net::URLRequest* url_request, + const net::RedirectInfo& redirect_info, + bool* defer_redirect) { + DCHECK(url_request == url_request_.get()); + DCHECK(url_request->status().is_success()); + + // Send the redirect response to the client, allowing them to inspect it and + // optionally follow the redirect. + *defer_redirect = true; + + scoped_refptr<ResourceResponse> response = new ResourceResponse(); + PopulateResourceResponse(url_request_.get(), response.get()); + + url_loader_client_->OnReceiveRedirect(redirect_info, response->head); +} + +void URLLoaderImpl::OnResponseStarted(net::URLRequest* url_request) { + DCHECK(url_request == url_request_.get()); + + // TODO: Add support for optional MIME sniffing. + + scoped_refptr<ResourceResponse> response = new ResourceResponse(); + PopulateResourceResponse(url_request_.get(), response.get()); + + mojom::DownloadedTempFilePtr downloaded_file_ptr; + url_loader_client_->OnReceiveResponse(response->head, + std::move(downloaded_file_ptr)); + + net::IOBufferWithSize* metadata = url_request->response_info().metadata.get(); + if (metadata) { + const uint8_t* data = reinterpret_cast<const uint8_t*>(metadata->data()); + + url_loader_client_->OnReceiveCachedMetadata( + std::vector<uint8_t>(data, data + metadata->size())); + } + + MojoCreateDataPipeOptions options; + options.struct_size = sizeof(MojoCreateDataPipeOptions); + options.flags = MOJO_CREATE_DATA_PIPE_OPTIONS_FLAG_NONE; + options.element_num_bytes = 1; + options.capacity_num_bytes = kDefaultAllocationSize; + mojo::DataPipe data_pipe(options); + + DCHECK(data_pipe.producer_handle.is_valid()); + DCHECK(data_pipe.consumer_handle.is_valid()); + + response_body_stream_ = std::move(data_pipe.producer_handle); + response_body_consumer_handle_ = std::move(data_pipe.consumer_handle); + peer_closed_handle_watcher_.Watch( + response_body_stream_.get(), MOJO_HANDLE_SIGNAL_PEER_CLOSED, + base::Bind(&URLLoaderImpl::OnResponseBodyStreamClosed, + base::Unretained(this))); + peer_closed_handle_watcher_.ArmOrNotify(); + + writable_handle_watcher_.Watch( + response_body_stream_.get(), MOJO_HANDLE_SIGNAL_WRITABLE, + base::Bind(&URLLoaderImpl::OnResponseBodyStreamReady, + base::Unretained(this))); + + // Start reading... + ReadMore(); +} + +void URLLoaderImpl::ReadMore() { + DCHECK(!pending_write_.get()); + + uint32_t num_bytes; + // TODO: we should use the abstractions in MojoAsyncResourceHandler. + MojoResult result = NetToMojoPendingBuffer::BeginWrite( + &response_body_stream_, &pending_write_, &num_bytes); + if (result == MOJO_RESULT_SHOULD_WAIT) { + // The pipe is full. We need to wait for it to have more space. + writable_handle_watcher_.ArmOrNotify(); + return; + } else if (result != MOJO_RESULT_OK) { + // The response body stream is in a bad state. Bail. + // TODO: How should this be communicated to our client? + writable_handle_watcher_.Cancel(); + response_body_stream_.reset(); + DeleteIfNeeded(); + return; + } + + CHECK_GT(static_cast<uint32_t>(std::numeric_limits<int>::max()), num_bytes); + scoped_refptr<net::IOBuffer> buf(new NetToMojoIOBuffer(pending_write_.get())); + int bytes_read; + url_request_->Read(buf.get(), static_cast<int>(num_bytes), &bytes_read); + if (url_request_->status().is_io_pending()) { + // Wait for OnReadCompleted. + } else if (url_request_->status().is_success() && bytes_read > 0) { + SendDataPipeIfNecessary(); + DidRead(static_cast<uint32_t>(bytes_read), true); + } else { + NotifyCompleted(net::OK); + writable_handle_watcher_.Cancel(); + pending_write_->Complete(0); + pending_write_ = nullptr; // This closes the data pipe. + DeleteIfNeeded(); + return; + } +} + +void URLLoaderImpl::DidRead(uint32_t num_bytes, bool completed_synchronously) { + DCHECK(url_request_->status().is_success()); + response_body_stream_ = pending_write_->Complete(num_bytes); + pending_write_ = nullptr; + if (completed_synchronously) { + base::ThreadTaskRunnerHandle::Get()->PostTask( + FROM_HERE, + base::Bind(&URLLoaderImpl::ReadMore, weak_ptr_factory_.GetWeakPtr())); + } else { + ReadMore(); + } +} + +void URLLoaderImpl::OnReadCompleted(net::URLRequest* url_request, + int bytes_read) { + DCHECK(url_request == url_request_.get()); + + if (!url_request->status().is_success()) { + writable_handle_watcher_.Cancel(); + pending_write_ = nullptr; // This closes the data pipe. + DeleteIfNeeded(); + return; + } + + SendDataPipeIfNecessary(); + + DidRead(static_cast<uint32_t>(bytes_read), false); +} + +void URLLoaderImpl::NotifyCompleted(int error_code) { + ResourceRequestCompletionStatus request_complete_data; + request_complete_data.error_code = error_code; + request_complete_data.exists_in_cache = + url_request_->response_info().was_cached; + request_complete_data.completion_time = base::TimeTicks::Now(); + request_complete_data.encoded_data_length = + url_request_->GetTotalReceivedBytes(); + request_complete_data.encoded_body_length = url_request_->GetRawBodyBytes(); + + url_loader_client_->OnComplete(request_complete_data); + DeleteIfNeeded(); +} + +void URLLoaderImpl::SendDataPipeIfNecessary() { + if (response_body_consumer_handle_.is_valid()) { + // Send the data pipe on the first OnReadCompleted call. + url_loader_client_->OnStartLoadingResponseBody( + std::move(response_body_consumer_handle_)); + } +} + +void URLLoaderImpl::OnConnectionError() { + connected_ = false; + DeleteIfNeeded(); +} + +void URLLoaderImpl::OnResponseBodyStreamClosed(MojoResult result) { + url_request_.reset(); + response_body_stream_.reset(); + pending_write_ = nullptr; + DeleteIfNeeded(); +} + +void URLLoaderImpl::OnResponseBodyStreamReady(MojoResult result) { + // TODO: Handle a bad |result| value. + DCHECK_EQ(result, MOJO_RESULT_OK); + ReadMore(); +} + +void URLLoaderImpl::DeleteIfNeeded() { + bool has_data_pipe = pending_write_.get() || response_body_stream_.is_valid(); + if (!connected_ && !has_data_pipe) + delete this; +} + +} // namespace content
diff --git a/content/network/url_loader_impl.h b/content/network/url_loader_impl.h new file mode 100644 index 0000000..129eb9b --- /dev/null +++ b/content/network/url_loader_impl.h
@@ -0,0 +1,77 @@ +// 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 CONTENT_NETWORK_URL_LOADER_IMPL_H_ +#define CONTENT_NETWORK_URL_LOADER_IMPL_H_ + +#include <stdint.h> + +#include <memory> + +#include "base/memory/weak_ptr.h" +#include "content/common/content_export.h" +#include "content/common/url_loader.mojom.h" +#include "mojo/public/cpp/bindings/binding.h" +#include "mojo/public/cpp/system/simple_watcher.h" +#include "net/url_request/url_request.h" + +namespace content { + +class NetworkContext; +class NetToMojoPendingBuffer; + +class CONTENT_EXPORT URLLoaderImpl : public mojom::URLLoader, + public net::URLRequest::Delegate { + public: + URLLoaderImpl(NetworkContext* context, + mojom::URLLoaderRequest url_loader_request, + const ResourceRequest& request, + mojom::URLLoaderClientPtr url_loader_client); + ~URLLoaderImpl() override; + + // Called when the associated NetworkContext is going away. + void Cleanup(); + + // mojom::URLLoader implementation: + void FollowRedirect() override; + void SetPriority(net::RequestPriority priority, + int32_t intra_priority_value) override; + + // net::URLRequest::Delegate methods: + void OnReceivedRedirect(net::URLRequest* url_request, + const net::RedirectInfo& redirect_info, + bool* defer_redirect) override; + void OnResponseStarted(net::URLRequest* url_request) override; + void OnReadCompleted(net::URLRequest* url_request, int bytes_read) override; + + private: + void ReadMore(); + void DidRead(uint32_t num_bytes, bool completed_synchronously); + void NotifyCompleted(int error_code); + void SendDataPipeIfNecessary(); + void OnConnectionError(); + void OnResponseBodyStreamClosed(MojoResult result); + void OnResponseBodyStreamReady(MojoResult result); + void DeleteIfNeeded(); + + NetworkContext* context_; + bool connected_; + std::unique_ptr<net::URLRequest> url_request_; + mojo::Binding<mojom::URLLoader> binding_; + mojom::URLLoaderClientPtr url_loader_client_; + + mojo::ScopedDataPipeProducerHandle response_body_stream_; + mojo::ScopedDataPipeConsumerHandle response_body_consumer_handle_; + scoped_refptr<NetToMojoPendingBuffer> pending_write_; + mojo::SimpleWatcher writable_handle_watcher_; + mojo::SimpleWatcher peer_closed_handle_watcher_; + + base::WeakPtrFactory<URLLoaderImpl> weak_ptr_factory_; + + DISALLOW_COPY_AND_ASSIGN(URLLoaderImpl); +}; + +} // namespace content + +#endif // CONTENT_NETWORK_URL_LOADER_IMPL_H_
diff --git a/content/network/url_loader_unittest.cc b/content/network/url_loader_unittest.cc new file mode 100644 index 0000000..cac3ae5 --- /dev/null +++ b/content/network/url_loader_unittest.cc
@@ -0,0 +1,113 @@ +// 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 "base/files/file_util.h" +#include "base/message_loop/message_loop.h" +#include "base/path_service.h" +#include "base/run_loop.h" +#include "base/threading/thread_task_runner_handle.h" +#include "content/browser/loader/test_url_loader_client.h" +#include "content/network/network_context.h" +#include "content/network/url_loader_impl.h" +#include "content/public/common/content_paths.h" +#include "mojo/public/c/system/data_pipe.h" +#include "mojo/public/cpp/system/wait.h" +#include "net/test/embedded_test_server/embedded_test_server.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace content { + +namespace { + +static ResourceRequest CreateResourceRequest(const char* method, + ResourceType type, + const GURL& url) { + ResourceRequest request; + request.method = std::string(method); + request.url = url; + request.first_party_for_cookies = url; // bypass third-party cookie blocking + request.request_initiator = url::Origin(url); // ensure initiator is set + request.referrer_policy = blink::kWebReferrerPolicyDefault; + request.load_flags = 0; + request.origin_pid = 0; + request.resource_type = type; + request.request_context = 0; + request.appcache_host_id = kAppCacheNoHostId; + request.download_to_file = false; + request.should_reset_appcache = false; + request.is_main_frame = true; + request.parent_is_main_frame = false; + request.transition_type = ui::PAGE_TRANSITION_LINK; + request.allow_download = true; + return request; +} + +std::string ReadData(MojoHandle consumer, size_t size) { + CHECK_EQ(mojo::Wait(mojo::Handle(consumer), MOJO_HANDLE_SIGNAL_READABLE), + MOJO_RESULT_OK); + std::vector<char> buffer(size); + uint32_t num_bytes = static_cast<uint32_t>(size); + CHECK_EQ(MojoReadData(consumer, buffer.data(), &num_bytes, + MOJO_WRITE_DATA_FLAG_ALL_OR_NONE), + MOJO_RESULT_OK); + CHECK_EQ(num_bytes, static_cast<uint32_t>(size)); + + return std::string(buffer.data(), buffer.size()); +} + +} // namespace + +class URLLoaderImplTest : public testing::Test { + public: + URLLoaderImplTest() {} + ~URLLoaderImplTest() override {} + + void SetUp() override { + test_server_.ServeFilesFromSourceDirectory( + base::FilePath(FILE_PATH_LITERAL("content/test/data"))); + ASSERT_TRUE(test_server_.Start()); + } + + void LoadAndCompareFile(const std::string& path) { + TestURLLoaderClient client; + mojom::URLLoaderPtr loader; + + ResourceRequest request = + CreateResourceRequest("GET", RESOURCE_TYPE_MAIN_FRAME, + test_server()->GetURL(std::string("/") + path)); + + URLLoaderImpl loader_impl(context(), mojo::MakeRequest(&loader), request, + client.CreateInterfacePtr()); + + client.RunUntilComplete(); + + base::FilePath file; + PathService::Get(content::DIR_TEST_DATA, &file); + file = file.AppendASCII(path); + + std::string file_contents; + if (!base::ReadFileToString(file, &file_contents)) { + ADD_FAILURE() << "File not found: " << file.value(); + return; + } + + std::string data = + ReadData(client.response_body().value(), file_contents.size()); + CHECK_EQ(data, file_contents); + } + + net::EmbeddedTestServer* test_server() { return &test_server_; } + NetworkContext* context() { return &context_; } + + private: + base::MessageLoopForIO message_loop_; + net::EmbeddedTestServer test_server_; + NetworkContext context_; +}; + +TEST_F(URLLoaderImplTest, Basic) { + LoadAndCompareFile("simple_page.html"); +} + +} // namespace content
diff --git a/content/public/android/BUILD.gn b/content/public/android/BUILD.gn index 278c8a6..e3372a73 100644 --- a/content/public/android/BUILD.gn +++ b/content/public/android/BUILD.gn
@@ -113,11 +113,13 @@ "java/src/org/chromium/content/browser/BindingManager.java", "java/src/org/chromium/content/browser/BindingManagerImpl.java", "java/src/org/chromium/content/browser/BrowserStartupController.java", + "java/src/org/chromium/content/browser/ChildConnectionAllocator.java", "java/src/org/chromium/content/browser/ChildProcessConnection.java", "java/src/org/chromium/content/browser/ChildProcessConnectionImpl.java", "java/src/org/chromium/content/browser/ChildProcessConstants.java", "java/src/org/chromium/content/browser/ChildProcessLauncher.java", "java/src/org/chromium/content/browser/ChildProcessLauncherHelper.java", + "java/src/org/chromium/content/browser/ChildSpawnData.java", "java/src/org/chromium/content/browser/ContentClassFactory.java", "java/src/org/chromium/content/browser/ContentFeatureList.java", "java/src/org/chromium/content/browser/ContentVideoView.java", @@ -383,8 +385,6 @@ "//content/shell/android:content_shell_test_java", "//device/geolocation:geolocation_java", "//device/geolocation:geolocation_java_test_support", - "//device/vibration:mojo_bindings_java", - "//device/vibration/android:vibration_manager_java", "//media/base/android:media_java", "//media/capture/content/android:screen_capture_java", "//media/capture/video/android:capture_java", @@ -436,7 +436,6 @@ "javatests/src/org/chromium/content/browser/VideoFullscreenOrientationLockTest.java", "javatests/src/org/chromium/content/browser/VSyncMonitorTest.java", "javatests/src/org/chromium/content/browser/VSyncPausedTest.java", - "javatests/src/org/chromium/content/browser/VibrationManagerImplTest.java", "javatests/src/org/chromium/content/browser/ViewportTest.java", "javatests/src/org/chromium/content/browser/WebContentsObserverAndroidTest.java", "javatests/src/org/chromium/content/browser/accessibility/captioning/CaptioningChangeDelegateTest.java",
diff --git a/content/public/android/java/src/org/chromium/content/browser/ChildConnectionAllocator.java b/content/public/android/java/src/org/chromium/content/browser/ChildConnectionAllocator.java new file mode 100644 index 0000000..2587232 --- /dev/null +++ b/content/public/android/java/src/org/chromium/content/browser/ChildConnectionAllocator.java
@@ -0,0 +1,262 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package org.chromium.content.browser; + +import android.content.ComponentName; +import android.content.Context; +import android.content.pm.ApplicationInfo; +import android.content.pm.PackageManager; +import android.os.Bundle; +import android.text.TextUtils; + +import org.chromium.base.Log; +import org.chromium.base.VisibleForTesting; +import org.chromium.content.app.PrivilegedProcessService; +import org.chromium.content.app.SandboxedProcessService; + +import java.util.ArrayList; +import java.util.LinkedList; +import java.util.Map; +import java.util.Queue; +import java.util.concurrent.ConcurrentHashMap; + +import javax.annotation.concurrent.GuardedBy; + +/** + * This class is responsible for allocating and managing connections to child + * process services. These connections are in a pool (the services are defined + * in the AndroidManifest.xml). + */ +public class ChildConnectionAllocator { + private static final String TAG = "ChildConnAllocator"; + + private static final String NUM_SANDBOXED_SERVICES_KEY = + "org.chromium.content.browser.NUM_SANDBOXED_SERVICES"; + private static final String NUM_PRIVILEGED_SERVICES_KEY = + "org.chromium.content.browser.NUM_PRIVILEGED_SERVICES"; + private static final String SANDBOXED_SERVICES_NAME_KEY = + "org.chromium.content.browser.SANDBOXED_SERVICES_NAME"; + + private static final Object sAllocatorLock = new Object(); + + // Map from package name to ChildConnectionAllocator. + @GuardedBy("sAllocatorLock") + private static Map<String, ChildConnectionAllocator> sSandboxedChildConnectionAllocatorMap; + + // Allocator used for non-sandboxed services. + @GuardedBy("sAllocatorLock") + private static ChildConnectionAllocator sPrivilegedChildConnectionAllocator; + + // Used by test to override the default sandboxed service settings. + private static int sSandboxedServicesCountForTesting = -1; + private static String sSandboxedServicesNameForTesting; + + // Connections to services. Indices of the array correspond to the service numbers. + private final ChildProcessConnection[] mChildProcessConnections; + + private final String mChildClassName; + private final boolean mInSandbox; + + private final Object mConnectionLock = new Object(); + + // The list of free (not bound) service indices. + @GuardedBy("mConnectionLock") + private final ArrayList<Integer> mFreeConnectionIndices; + + // Each Allocator keeps a queue for the pending spawn data. Once a connection is free, we + // dequeue the pending spawn data from the same allocator as the connection. + @GuardedBy("mConnectionLock") + private final Queue<ChildSpawnData> mPendingSpawnQueue = new LinkedList<>(); + + public static ChildConnectionAllocator getAllocator( + Context context, String packageName, boolean inSandbox) { + synchronized (sAllocatorLock) { + if (!inSandbox) { + if (sPrivilegedChildConnectionAllocator == null) { + sPrivilegedChildConnectionAllocator = new ChildConnectionAllocator(false, + getNumberOfServices(context, false, packageName), + getClassNameOfService(context, false, packageName)); + } + return sPrivilegedChildConnectionAllocator; + } + + if (sSandboxedChildConnectionAllocatorMap == null) { + sSandboxedChildConnectionAllocatorMap = + new ConcurrentHashMap<String, ChildConnectionAllocator>(); + } + if (!sSandboxedChildConnectionAllocatorMap.containsKey(packageName)) { + Log.w(TAG, + "Create a new ChildConnectionAllocator with package name = %s," + + " inSandbox = true", + packageName); + sSandboxedChildConnectionAllocatorMap.put(packageName, + new ChildConnectionAllocator(true, + getNumberOfServices(context, true, packageName), + getClassNameOfService(context, true, packageName))); + } + return sSandboxedChildConnectionAllocatorMap.get(packageName); + // TODO(pkotwicz|hanxi): Figure out when old allocators should be removed from + // {@code sSandboxedChildConnectionAllocatorMap}. + } + } + + private static String getClassNameOfService( + Context context, boolean inSandbox, String packageName) { + if (!inSandbox) { + return PrivilegedProcessService.class.getName(); + } + + if (!TextUtils.isEmpty(sSandboxedServicesNameForTesting)) { + return sSandboxedServicesNameForTesting; + } + + String serviceName = null; + try { + PackageManager packageManager = context.getPackageManager(); + ApplicationInfo appInfo = + packageManager.getApplicationInfo(packageName, PackageManager.GET_META_DATA); + if (appInfo.metaData != null) { + serviceName = appInfo.metaData.getString(SANDBOXED_SERVICES_NAME_KEY); + } + } catch (PackageManager.NameNotFoundException e) { + throw new RuntimeException("Could not get application info."); + } + + if (serviceName != null) { + // Check that the service exists. + try { + PackageManager packageManager = context.getPackageManager(); + // PackageManager#getServiceInfo() throws an exception if the service does not + // exist. + packageManager.getServiceInfo(new ComponentName(packageName, serviceName + "0"), 0); + return serviceName; + } catch (PackageManager.NameNotFoundException e) { + throw new RuntimeException( + "Illegal meta data value: the child service doesn't exist"); + } + } + return SandboxedProcessService.class.getName(); + } + + static int getNumberOfServices(Context context, boolean inSandbox, String packageName) { + int numServices = -1; + if (inSandbox && sSandboxedServicesCountForTesting != -1) { + numServices = sSandboxedServicesCountForTesting; + } else { + try { + PackageManager packageManager = context.getPackageManager(); + ApplicationInfo appInfo = packageManager.getApplicationInfo( + packageName, PackageManager.GET_META_DATA); + if (appInfo.metaData != null) { + numServices = appInfo.metaData.getInt( + inSandbox ? NUM_SANDBOXED_SERVICES_KEY : NUM_PRIVILEGED_SERVICES_KEY, + -1); + } + } catch (PackageManager.NameNotFoundException e) { + throw new RuntimeException("Could not get application info"); + } + } + if (numServices < 0) { + throw new RuntimeException("Illegal meta data value for number of child services"); + } + return numServices; + } + + @VisibleForTesting + public static void setSanboxServicesSettingsForTesting(int serviceCount, String serviceName) { + sSandboxedServicesCountForTesting = serviceCount; + sSandboxedServicesNameForTesting = serviceName; + } + + private ChildConnectionAllocator( + boolean inSandbox, int numChildServices, String serviceClassName) { + mChildProcessConnections = new ChildProcessConnectionImpl[numChildServices]; + mFreeConnectionIndices = new ArrayList<Integer>(numChildServices); + for (int i = 0; i < numChildServices; i++) { + mFreeConnectionIndices.add(i); + } + mChildClassName = serviceClassName; + mInSandbox = inSandbox; + } + + // Allocates or enqueues. If there are no free slots, returns null and enqueues the spawn data. + public ChildProcessConnection allocate(ChildSpawnData spawnData, + ChildProcessConnection.DeathCallback deathCallback, Bundle childProcessCommonParameters, + boolean queueIfNoSlotAvailable) { + assert spawnData.isInSandbox() == mInSandbox; + synchronized (mConnectionLock) { + if (mFreeConnectionIndices.isEmpty()) { + Log.d(TAG, "Ran out of services to allocate."); + if (queueIfNoSlotAvailable) { + mPendingSpawnQueue.add(spawnData); + } + return null; + } + int slot = mFreeConnectionIndices.remove(0); + assert mChildProcessConnections[slot] == null; + mChildProcessConnections[slot] = new ChildProcessConnectionImpl(spawnData.getContext(), + slot, mInSandbox, deathCallback, mChildClassName, childProcessCommonParameters, + spawnData.isAlwaysInForeground(), spawnData.getCreationParams()); + Log.d(TAG, "Allocator allocated a connection, sandbox: %b, slot: %d", mInSandbox, slot); + return mChildProcessConnections[slot]; + } + } + + // Also return the first ChildSpawnData in the pending queue, if any. + public ChildSpawnData free(ChildProcessConnection connection) { + synchronized (mConnectionLock) { + int slot = connection.getServiceNumber(); + if (mChildProcessConnections[slot] != connection) { + int occupier = mChildProcessConnections[slot] == null + ? -1 + : mChildProcessConnections[slot].getServiceNumber(); + Log.e(TAG, + "Unable to find connection to free in slot: %d " + + "already occupied by service: %d", + slot, occupier); + assert false; + } else { + mChildProcessConnections[slot] = null; + assert !mFreeConnectionIndices.contains(slot); + mFreeConnectionIndices.add(slot); + Log.d(TAG, "Allocator freed a connection, sandbox: %b, slot: %d", mInSandbox, slot); + } + return mPendingSpawnQueue.poll(); + } + } + + public boolean isFreeConnectionAvailable() { + synchronized (mConnectionLock) { + return !mFreeConnectionIndices.isEmpty(); + } + } + + /** @return the count of connections managed by the allocator */ + @VisibleForTesting + int allocatedConnectionsCountForTesting() { + synchronized (mConnectionLock) { + return mChildProcessConnections.length - mFreeConnectionIndices.size(); + } + } + + @VisibleForTesting + ChildProcessConnection[] connectionArrayForTesting() { + return mChildProcessConnections; + } + + @VisibleForTesting + void enqueuePendingQueueForTesting(ChildSpawnData spawnData) { + synchronized (mConnectionLock) { + mPendingSpawnQueue.add(spawnData); + } + } + + @VisibleForTesting + int pendingSpawnsCountForTesting() { + synchronized (mConnectionLock) { + return mPendingSpawnQueue.size(); + } + } +}
diff --git a/content/public/android/java/src/org/chromium/content/browser/ChildProcessLauncher.java b/content/public/android/java/src/org/chromium/content/browser/ChildProcessLauncher.java index db717bf..6fbc3ed 100644 --- a/content/public/android/java/src/org/chromium/content/browser/ChildProcessLauncher.java +++ b/content/public/android/java/src/org/chromium/content/browser/ChildProcessLauncher.java
@@ -4,14 +4,10 @@ package org.chromium.content.browser; -import android.content.ComponentName; import android.content.Context; -import android.content.pm.ApplicationInfo; -import android.content.pm.PackageManager; import android.os.Bundle; import android.os.IBinder; import android.os.RemoteException; -import android.text.TextUtils; import org.chromium.base.CpuFeatures; import org.chromium.base.Log; @@ -22,14 +18,9 @@ import org.chromium.base.process_launcher.ChildProcessCreationParams; import org.chromium.base.process_launcher.FileDescriptorInfo; import org.chromium.content.app.ChromiumLinkerParams; -import org.chromium.content.app.PrivilegedProcessService; -import org.chromium.content.app.SandboxedProcessService; import org.chromium.content.common.ContentSwitches; -import java.util.ArrayList; -import java.util.LinkedList; import java.util.Map; -import java.util.Queue; import java.util.concurrent.ConcurrentHashMap; /** @@ -42,310 +33,15 @@ public class ChildProcessLauncher { private static final String TAG = "ChildProcLauncher"; - private static class ChildConnectionAllocator { - // Connections to services. Indices of the array correspond to the service numbers. - private final ChildProcessConnection[] mChildProcessConnections; - - // The list of free (not bound) service indices. - // SHOULD BE ACCESSED WITH mConnectionLock. - private final ArrayList<Integer> mFreeConnectionIndices; - private final Object mConnectionLock = new Object(); - - private final String mChildClassName; - private final boolean mInSandbox; - // Each Allocator keeps a queue for the pending spawn data. Once a connection is free, we - // dequeue the pending spawn data from the same allocator as the connection. - // SHOULD BE ACCESSED WITH mConnectionLock. - private final Queue<SpawnData> mPendingSpawnQueue = new LinkedList<>(); - - public ChildConnectionAllocator(boolean inSandbox, int numChildServices, - String serviceClassName) { - mChildProcessConnections = new ChildProcessConnectionImpl[numChildServices]; - mFreeConnectionIndices = new ArrayList<Integer>(numChildServices); - for (int i = 0; i < numChildServices; i++) { - mFreeConnectionIndices.add(i); - } - mChildClassName = serviceClassName; - mInSandbox = inSandbox; - } - - // Allocate or enqueue. If there are no free slots, return null and enqueue the spawn data. - public ChildProcessConnection allocate(SpawnData spawnData, - ChildProcessConnection.DeathCallback deathCallback, - Bundle childProcessCommonParameters) { - assert spawnData.isInSandbox() == mInSandbox; - synchronized (mConnectionLock) { - if (mFreeConnectionIndices.isEmpty()) { - Log.d(TAG, "Ran out of services to allocate."); - if (!spawnData.isForWarmUp()) { - mPendingSpawnQueue.add(spawnData); - } - return null; - } - int slot = mFreeConnectionIndices.remove(0); - assert mChildProcessConnections[slot] == null; - mChildProcessConnections[slot] = - new ChildProcessConnectionImpl(spawnData.getContext(), slot, mInSandbox, - deathCallback, mChildClassName, childProcessCommonParameters, - spawnData.isAlwaysInForeground(), spawnData.getCreationParams()); - Log.d(TAG, "Allocator allocated a connection, sandbox: %b, slot: %d", mInSandbox, - slot); - return mChildProcessConnections[slot]; - } - } - - // Also return the first SpawnData in the pending queue, if any. - public SpawnData free(ChildProcessConnection connection) { - synchronized (mConnectionLock) { - int slot = connection.getServiceNumber(); - if (mChildProcessConnections[slot] != connection) { - int occupier = mChildProcessConnections[slot] == null - ? -1 : mChildProcessConnections[slot].getServiceNumber(); - Log.e(TAG, "Unable to find connection to free in slot: %d " - + "already occupied by service: %d", slot, occupier); - assert false; - } else { - mChildProcessConnections[slot] = null; - assert !mFreeConnectionIndices.contains(slot); - mFreeConnectionIndices.add(slot); - Log.d(TAG, "Allocator freed a connection, sandbox: %b, slot: %d", mInSandbox, - slot); - } - return mPendingSpawnQueue.poll(); - } - } - - public boolean isFreeConnectionAvailable() { - synchronized (mConnectionLock) { - return !mFreeConnectionIndices.isEmpty(); - } - } - - /** @return the count of connections managed by the allocator */ - @VisibleForTesting - int allocatedConnectionsCountForTesting() { - return mChildProcessConnections.length - mFreeConnectionIndices.size(); - } - - @VisibleForTesting - ChildProcessConnection[] connectionArrayForTesting() { - return mChildProcessConnections; - } - - @VisibleForTesting - void enqueuePendingQueueForTesting(SpawnData spawnData) { - synchronized (mConnectionLock) { - mPendingSpawnQueue.add(spawnData); - } - } - - @VisibleForTesting - int pendingSpawnsCountForTesting() { - synchronized (mConnectionLock) { - return mPendingSpawnQueue.size(); - } - } - } - - private static class SpawnData { - private final boolean mForWarmup; // Do not queue up if failed. - private final Context mContext; - private final String[] mCommandLine; - private final int mChildProcessId; - private final FileDescriptorInfo[] mFilesToBeMapped; - private final LaunchCallback mLaunchCallback; - private final IBinder mChildProcessCallback; - private final boolean mInSandbox; - private final boolean mAlwaysInForeground; - private final ChildProcessCreationParams mCreationParams; - - private SpawnData(boolean forWarmUp, Context context, String[] commandLine, - int childProcessId, FileDescriptorInfo[] filesToBeMapped, - LaunchCallback launchCallback, IBinder childProcessCallback, boolean inSandbox, - boolean alwaysInForeground, ChildProcessCreationParams creationParams) { - mForWarmup = forWarmUp; - mContext = context; - mCommandLine = commandLine; - mChildProcessId = childProcessId; - mFilesToBeMapped = filesToBeMapped; - mLaunchCallback = launchCallback; - mChildProcessCallback = childProcessCallback; - mInSandbox = inSandbox; - mAlwaysInForeground = alwaysInForeground; - mCreationParams = creationParams; - } - - private boolean isForWarmUp() { - return mForWarmup; - } - private Context getContext() { - return mContext; - } - private String[] getCommandLine() { - return mCommandLine; - } - private int getChildProcessId() { - return mChildProcessId; - } - private FileDescriptorInfo[] getFilesToBeMapped() { - return mFilesToBeMapped; - } - private LaunchCallback getLaunchCallback() { - return mLaunchCallback; - } - private IBinder getChildProcessCallback() { - return mChildProcessCallback; - } - private boolean isInSandbox() { - return mInSandbox; - } - private boolean isAlwaysInForeground() { - return mAlwaysInForeground; - } - private ChildProcessCreationParams getCreationParams() { - return mCreationParams; - } - } - /** * Implemented by ChildProcessLauncherHelper. */ public interface LaunchCallback { void onChildProcessStarted(int pid); } - // Service class for child process. - // Map from package name to ChildConnectionAllocator. - private static Map<String, ChildConnectionAllocator> sSandboxedChildConnectionAllocatorMap; - // As the default value it uses PrivilegedProcessService0. - private static ChildConnectionAllocator sPrivilegedChildConnectionAllocator; - private static final boolean SPARE_CONNECTION_ALWAYS_IN_FOREGROUND = false; - private static final String NUM_SANDBOXED_SERVICES_KEY = - "org.chromium.content.browser.NUM_SANDBOXED_SERVICES"; - private static final String NUM_PRIVILEGED_SERVICES_KEY = - "org.chromium.content.browser.NUM_PRIVILEGED_SERVICES"; - private static final String SANDBOXED_SERVICES_NAME_KEY = - "org.chromium.content.browser.SANDBOXED_SERVICES_NAME"; - - // Used by tests to override the default sandboxed service settings. - private static int sSandboxedServicesCountForTesting = -1; - private static String sSandboxedServicesNameForTesting; - - @VisibleForTesting - public static void setSanboxServicesSettingsForTesting(int serviceCount, String serviceName) { - sSandboxedServicesCountForTesting = serviceCount; - sSandboxedServicesNameForTesting = serviceName; - } - - static int getNumberOfServices(Context context, boolean inSandbox, String packageName) { - int numServices = -1; - if (inSandbox && sSandboxedServicesCountForTesting != -1) { - numServices = sSandboxedServicesCountForTesting; - } else { - try { - PackageManager packageManager = context.getPackageManager(); - ApplicationInfo appInfo = packageManager.getApplicationInfo(packageName, - PackageManager.GET_META_DATA); - if (appInfo.metaData != null) { - numServices = appInfo.metaData.getInt(inSandbox - ? NUM_SANDBOXED_SERVICES_KEY : NUM_PRIVILEGED_SERVICES_KEY, -1); - } - } catch (PackageManager.NameNotFoundException e) { - throw new RuntimeException("Could not get application info"); - } - } - if (numServices < 0) { - throw new RuntimeException("Illegal meta data value for number of child services"); - } - return numServices; - } - - private static String getClassNameOfService(Context context, boolean inSandbox, - String packageName) { - if (!inSandbox) { - return PrivilegedProcessService.class.getName(); - } - - if (!TextUtils.isEmpty(sSandboxedServicesNameForTesting)) { - return sSandboxedServicesNameForTesting; - } - - String serviceName = null; - try { - PackageManager packageManager = context.getPackageManager(); - ApplicationInfo appInfo = - packageManager.getApplicationInfo(packageName, PackageManager.GET_META_DATA); - if (appInfo.metaData != null) { - serviceName = appInfo.metaData.getString(SANDBOXED_SERVICES_NAME_KEY); - } - } catch (PackageManager.NameNotFoundException e) { - throw new RuntimeException("Could not get application info."); - } - - if (serviceName != null) { - // Check that the service exists. - try { - PackageManager packageManager = context.getPackageManager(); - // PackageManager#getServiceInfo() throws an exception if the service does not - // exist. - packageManager.getServiceInfo(new ComponentName(packageName, serviceName + "0"), 0); - return serviceName; - } catch (PackageManager.NameNotFoundException e) { - throw new RuntimeException( - "Illegal meta data value: the child service doesn't exist"); - } - } - return SandboxedProcessService.class.getName(); - } - - private static void initConnectionAllocatorsIfNecessary( - Context context, boolean inSandbox, String packageName) { - // TODO(mariakhomenko): Uses an Object to lock the access. - synchronized (ChildProcessLauncher.class) { - if (inSandbox) { - if (sSandboxedChildConnectionAllocatorMap == null) { - sSandboxedChildConnectionAllocatorMap = - new ConcurrentHashMap<String, ChildConnectionAllocator>(); - } - if (!sSandboxedChildConnectionAllocatorMap.containsKey(packageName)) { - Log.w(TAG, "Create a new ChildConnectionAllocator with package name = %s," - + " inSandbox = true", - packageName); - sSandboxedChildConnectionAllocatorMap.put(packageName, - new ChildConnectionAllocator(true, - getNumberOfServices(context, true, packageName), - getClassNameOfService(context, true, packageName))); - } - } else if (sPrivilegedChildConnectionAllocator == null) { - sPrivilegedChildConnectionAllocator = new ChildConnectionAllocator(false, - getNumberOfServices(context, false, packageName), - getClassNameOfService(context, false, packageName)); - } - // TODO(pkotwicz|hanxi): Figure out when old allocators should be removed from - // {@code sSandboxedChildConnectionAllocatorMap}. - } - } - - /** - * Note: please make sure that the Allocator has been initialized before calling this function. - * Otherwise, always calls {@link initConnectionAllocatorsIfNecessary} first. - */ - private static ChildConnectionAllocator getConnectionAllocator( - String packageName, boolean inSandbox) { - if (!inSandbox) { - return sPrivilegedChildConnectionAllocator; - } - return sSandboxedChildConnectionAllocatorMap.get(packageName); - } - - private static ChildConnectionAllocator getAllocatorForTesting( - Context context, String packageName, boolean inSandbox) { - initConnectionAllocatorsIfNecessary(context, inSandbox, packageName); - return getConnectionAllocator(packageName, inSandbox); - } - private static ChildProcessConnection allocateConnection( - SpawnData spawnData, Bundle childProcessCommonParams) { + ChildSpawnData spawnData, Bundle childProcessCommonParams, boolean forWarmUp) { ChildProcessConnection.DeathCallback deathCallback = new ChildProcessConnection.DeathCallback() { @Override @@ -362,9 +58,8 @@ final boolean inSandbox = spawnData.isInSandbox(); String packageName = creationParams != null ? creationParams.getPackageName() : context.getPackageName(); - initConnectionAllocatorsIfNecessary(context, inSandbox, packageName); - return getConnectionAllocator(packageName, inSandbox) - .allocate(spawnData, deathCallback, childProcessCommonParams); + return ChildConnectionAllocator.getAllocator(context, packageName, inSandbox) + .allocate(spawnData, deathCallback, childProcessCommonParams, !forWarmUp); } private static boolean sLinkerInitialized; @@ -406,20 +101,21 @@ return commonParams; } - private static ChildProcessConnection allocateBoundConnection( - SpawnData spawnData, ChildProcessConnection.StartCallback startCallback) { + private static ChildProcessConnection allocateBoundConnection(ChildSpawnData spawnData, + ChildProcessConnection.StartCallback startCallback, boolean forWarmUp) { final Context context = spawnData.getContext(); final boolean inSandbox = spawnData.isInSandbox(); final ChildProcessCreationParams creationParams = spawnData.getCreationParams(); + ChildProcessConnection connection = allocateConnection( - spawnData, createCommonParamsBundle(spawnData.getCreationParams())); + spawnData, createCommonParamsBundle(spawnData.getCreationParams()), forWarmUp); if (connection != null) { connection.start(startCallback); String packageName = creationParams != null ? creationParams.getPackageName() : context.getPackageName(); if (inSandbox - && !getConnectionAllocator(packageName, inSandbox) + && !ChildConnectionAllocator.getAllocator(context, packageName, inSandbox) .isFreeConnectionAvailable()) { // Proactively releases all the moderate bindings once all the sandboxed services // are allocated, which will be very likely to have some of them killed by OOM @@ -446,7 +142,7 @@ ThreadUtils.postOnUiThreadDelayed(new Runnable() { @Override public void run() { - final SpawnData pendingSpawn = freeConnectionAndDequeuePending(conn); + final ChildSpawnData pendingSpawn = freeConnectionAndDequeuePending(conn); if (pendingSpawn != null) { LauncherThread.post(new Runnable() { @Override @@ -465,9 +161,14 @@ }, FREE_CONNECTION_DELAY_MILLIS); } - private static SpawnData freeConnectionAndDequeuePending(ChildProcessConnection conn) { - ChildConnectionAllocator allocator = getConnectionAllocator( - conn.getPackageName(), conn.isInSandbox()); + private static ChildSpawnData freeConnectionAndDequeuePending(ChildProcessConnection conn) { + // TODO(jcivelli): it should be safe to pass a null Context here as it is used to initialize + // the ChildConnectionAllocator object and if we are freeing a connection, we must have + // allocated one previously guaranteeing it is already initialized. + // When we consolidate ChildProcessLauncher and ChildProcessLauncherHelper, we'll have a + // context around that we can pass in there. + ChildConnectionAllocator allocator = ChildConnectionAllocator.getAllocator( + null /* context */, conn.getPackageName(), conn.isInSandbox()); assert allocator != null; return allocator.free(conn); } @@ -533,8 +234,9 @@ * sent to the background. */ public static void startModerateBindingManagement(Context context) { - sBindingManager.startModerateBindingManagement( - context, getNumberOfServices(context, true, context.getPackageName())); + sBindingManager.startModerateBindingManagement(context, + ChildConnectionAllocator.getNumberOfServices( + context, true, context.getPackageName())); } /** @@ -587,13 +289,13 @@ } } }; - SpawnData spawnData = new SpawnData(true /* forWarmUp*/, context, + ChildSpawnData spawnData = new ChildSpawnData(context, null /* commandLine */, -1 /* child process id */, null /* filesToBeMapped */, null /* launchCallback */, null /* child process callback */, true /* inSandbox */, SPARE_CONNECTION_ALWAYS_IN_FOREGROUND, params); - sSpareSandboxedConnection = - allocateBoundConnection(spawnData, startCallback); + sSpareSandboxedConnection = allocateBoundConnection( + spawnData, startCallback, true /* forWarmUp */); } } } @@ -707,10 +409,11 @@ } }; - SpawnData spawnData = new SpawnData(false /* forWarmUp */, context, commandLine, - childProcessId, filesToBeMapped, launchCallback, childProcessCallback, - inSandbox, alwaysInForeground, creationParams); - allocatedConnection = allocateBoundConnection(spawnData, startCallback); + ChildSpawnData spawnData = new ChildSpawnData(context, commandLine, childProcessId, + filesToBeMapped, launchCallback, childProcessCallback, inSandbox, + alwaysInForeground, creationParams); + allocatedConnection = + allocateBoundConnection(spawnData, startCallback, false /* forWarmUp */); if (allocatedConnection == null) { return null; } @@ -798,22 +501,22 @@ static ChildProcessConnection allocateBoundConnectionForTesting(Context context, ChildProcessCreationParams creationParams) { return allocateBoundConnection( - new SpawnData(false /* forWarmUp */, context, null /* commandLine */, - 0 /* childProcessId */, null /* filesToBeMapped */, - null /* LaunchCallback */, null /* childProcessCallback */, - true /* inSandbox */, false /* alwaysInForeground */, creationParams), - null /* startCallback */); + new ChildSpawnData(context, null /* commandLine */, 0 /* childProcessId */, + null /* filesToBeMapped */, null /* LaunchCallback */, + null /* childProcessCallback */, true /* inSandbox */, + false /* alwaysInForeground */, creationParams), + null /* startCallback */, false /* forWarmUp */); } @VisibleForTesting static ChildProcessConnection allocateConnectionForTesting( Context context, ChildProcessCreationParams creationParams) { return allocateConnection( - new SpawnData(false /* forWarmUp */, context, null /* commandLine */, - 0 /* childProcessId */, null /* filesToBeMapped */, - null /* launchCallback */, null /* childProcessCallback */, - true /* inSandbox */, false /* alwaysInForeground */, creationParams), - createCommonParamsBundle(creationParams)); + new ChildSpawnData(context, null /* commandLine */, 0 /* childProcessId */, + null /* filesToBeMapped */, null /* launchCallback */, + null /* childProcessCallback */, true /* inSandbox */, + false /* alwaysInForeground */, creationParams), + createCommonParamsBundle(creationParams), false /* forWarmUp */); } /** @@ -825,10 +528,10 @@ String packageName = creationParams != null ? creationParams.getPackageName() : context.getPackageName(); ChildConnectionAllocator allocator = - getAllocatorForTesting(context, packageName, inSandbox); - allocator.enqueuePendingQueueForTesting(new SpawnData(false /* forWarmUp*/, context, - commandLine, 1 /* childProcessId */, new FileDescriptorInfo[0], - null /* launchCallback */, null /* childProcessCallback */, true /* inSandbox */, + ChildConnectionAllocator.getAllocator(context, packageName, inSandbox); + allocator.enqueuePendingQueueForTesting(new ChildSpawnData(context, commandLine, + 1 /* childProcessId */, new FileDescriptorInfo[0], null /* launchCallback */, + null /* childProcessCallback */, true /* inSandbox */, false /* alwaysInForeground */, creationParams)); } @@ -838,8 +541,7 @@ */ @VisibleForTesting static int allocatedSandboxedConnectionsCountForTesting(Context context, String packageName) { - initConnectionAllocatorsIfNecessary(context, true, packageName); - return sSandboxedChildConnectionAllocatorMap.get(packageName) + return ChildConnectionAllocator.getAllocator(context, packageName, true /*isSandboxed */) .allocatedConnectionsCountForTesting(); } @@ -847,8 +549,10 @@ * @return gets the service connection array for a specific package name. */ @VisibleForTesting - static ChildProcessConnection[] getSandboxedConnectionArrayForTesting(String packageName) { - return sSandboxedChildConnectionAllocatorMap.get(packageName).connectionArrayForTesting(); + static ChildProcessConnection[] getSandboxedConnectionArrayForTesting( + Context context, String packageName) { + return ChildConnectionAllocator.getAllocator(context, packageName, true /*isSandboxed */) + .connectionArrayForTesting(); } /** @return the count of services set up and working */ @@ -866,9 +570,8 @@ @VisibleForTesting static int pendingSpawnsCountForTesting( Context context, String packageName, boolean inSandbox) { - ChildConnectionAllocator allocator = - getAllocatorForTesting(context, packageName, inSandbox); - return allocator.pendingSpawnsCountForTesting(); + return ChildConnectionAllocator.getAllocator(context, packageName, inSandbox) + .pendingSpawnsCountForTesting(); } /**
diff --git a/content/public/android/java/src/org/chromium/content/browser/ChildProcessLauncherHelper.java b/content/public/android/java/src/org/chromium/content/browser/ChildProcessLauncherHelper.java index fada089..da5e8d2 100644 --- a/content/public/android/java/src/org/chromium/content/browser/ChildProcessLauncherHelper.java +++ b/content/public/android/java/src/org/chromium/content/browser/ChildProcessLauncherHelper.java
@@ -101,7 +101,7 @@ final String packageName = params == null ? context.getPackageName() : params.getPackageName(); try { - return ChildProcessLauncher.getNumberOfServices(context, inSandbox, packageName); + return ChildConnectionAllocator.getNumberOfServices(context, inSandbox, packageName); } catch (RuntimeException e) { // Unittest packages do not declare services. Some tests require a realistic number // to test child process policies, so pick a high-ish number here.
diff --git a/content/public/android/java/src/org/chromium/content/browser/ChildSpawnData.java b/content/public/android/java/src/org/chromium/content/browser/ChildSpawnData.java new file mode 100644 index 0000000..4f1d9275 --- /dev/null +++ b/content/public/android/java/src/org/chromium/content/browser/ChildSpawnData.java
@@ -0,0 +1,76 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package org.chromium.content.browser; + +import android.content.Context; +import android.os.IBinder; + +import org.chromium.base.process_launcher.ChildProcessCreationParams; +import org.chromium.base.process_launcher.FileDescriptorInfo; +import org.chromium.content.browser.ChildProcessLauncher.LaunchCallback; + +/** Contains the information necessary to start a child process. */ +class ChildSpawnData { + private final Context mContext; + private final String[] mCommandLine; + private final int mChildProcessId; + private final FileDescriptorInfo[] mFilesToBeMapped; + private final LaunchCallback mLaunchCallback; + private final IBinder mChildProcessCallback; + private final boolean mInSandbox; + private final boolean mAlwaysInForeground; + private final ChildProcessCreationParams mCreationParams; + + ChildSpawnData(Context context, String[] commandLine, int childProcessId, + FileDescriptorInfo[] filesToBeMapped, LaunchCallback launchCallback, + IBinder childProcessCallback, boolean inSandbox, boolean alwaysInForeground, + ChildProcessCreationParams creationParams) { + mContext = context; + mCommandLine = commandLine; + mChildProcessId = childProcessId; + mFilesToBeMapped = filesToBeMapped; + mLaunchCallback = launchCallback; + mChildProcessCallback = childProcessCallback; + mInSandbox = inSandbox; + mAlwaysInForeground = alwaysInForeground; + mCreationParams = creationParams; + } + + Context getContext() { + return mContext; + } + + String[] getCommandLine() { + return mCommandLine; + } + + int getChildProcessId() { + return mChildProcessId; + } + + FileDescriptorInfo[] getFilesToBeMapped() { + return mFilesToBeMapped; + } + + LaunchCallback getLaunchCallback() { + return mLaunchCallback; + } + + IBinder getChildProcessCallback() { + return mChildProcessCallback; + } + + boolean isInSandbox() { + return mInSandbox; + } + + boolean isAlwaysInForeground() { + return mAlwaysInForeground; + } + + ChildProcessCreationParams getCreationParams() { + return mCreationParams; + } +}
diff --git a/content/public/android/java/src/org/chromium/content/browser/OWNERS b/content/public/android/java/src/org/chromium/content/browser/OWNERS index 5e1b79f..63c98f49 100644 --- a/content/public/android/java/src/org/chromium/content/browser/OWNERS +++ b/content/public/android/java/src/org/chromium/content/browser/OWNERS
@@ -18,3 +18,6 @@ # BackgroundSync related per-file BackgroundSync*.java=jkarlin@chromium.org + +# ContentViewCore related +per-file ContentView*.java=jinsukkim@chromium.org
diff --git a/content/public/android/java/src/org/chromium/content/browser/webcontents/WebContentsImpl.java b/content/public/android/java/src/org/chromium/content/browser/webcontents/WebContentsImpl.java index cb0fece..e2eebaba 100644 --- a/content/public/android/java/src/org/chromium/content/browser/webcontents/WebContentsImpl.java +++ b/content/public/android/java/src/org/chromium/content/browser/webcontents/WebContentsImpl.java
@@ -401,7 +401,7 @@ @Override public void requestSmartClipExtract(int x, int y, int width, int height) { - assert mSmartClipCallback != null; + if (mSmartClipCallback == null) return; nativeRequestSmartClipExtract( mNativeWebContentsAndroid, mSmartClipCallback, x, y, width, height); }
diff --git a/content/public/android/javatests/src/org/chromium/content/browser/ChildProcessLauncherTest.java b/content/public/android/javatests/src/org/chromium/content/browser/ChildProcessLauncherTest.java index 8d9b33a6..a81f9ed 100644 --- a/content/public/android/javatests/src/org/chromium/content/browser/ChildProcessLauncherTest.java +++ b/content/public/android/javatests/src/org/chromium/content/browser/ChildProcessLauncherTest.java
@@ -406,7 +406,7 @@ final ChildProcessConnection[] sandboxedConnections = ChildProcessLauncher.getSandboxedConnectionArrayForTesting( - context.getPackageName()); + context, context.getPackageName()); // Wait for the retry to succeed. CriteriaHelper.pollInstrumentationThread(
diff --git a/content/public/android/javatests/src/org/chromium/content/browser/VibrationManagerImplTest.java b/content/public/android/javatests/src/org/chromium/content/browser/VibrationManagerImplTest.java deleted file mode 100644 index 7db250a..0000000 --- a/content/public/android/javatests/src/org/chromium/content/browser/VibrationManagerImplTest.java +++ /dev/null
@@ -1,128 +0,0 @@ -// Copyright 2015 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -package org.chromium.content.browser; - -import android.os.Vibrator; -import android.support.test.filters.MediumTest; - -import org.junit.Assert; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; - -import org.chromium.base.test.BaseJUnit4ClassRunner; -import org.chromium.base.test.util.DisabledTest; -import org.chromium.base.test.util.Feature; -import org.chromium.base.test.util.UrlUtils; -import org.chromium.content.browser.test.util.Criteria; -import org.chromium.content.browser.test.util.CriteriaHelper; -import org.chromium.content_shell_apk.ContentShellActivityTestRule; -import org.chromium.device.vibration.VibrationManagerImpl; - -/** - * Tests java implementation of VibrationManager mojo service on android. - */ -@RunWith(BaseJUnit4ClassRunner.class) -public class VibrationManagerImplTest { - @Rule - public ContentShellActivityTestRule mActivityTestRule = new ContentShellActivityTestRule(); - - private static final String URL_VIBRATOR_VIBRATE = UrlUtils.encodeHtmlDataUri("<html><body>" - + " <script type=\"text/javascript\">" - + " navigator.vibrate(3000);" - + " </script>" - + "</body></html>"); - private static final String URL_VIBRATOR_CANCEL = UrlUtils.encodeHtmlDataUri("<html><body>" - + " <script type=\"text/javascript\">" - + " navigator.vibrate(10000);" - + " navigator.vibrate(0);" - + " </script>" - + "</body></html>"); - - private FakeAndroidVibratorWrapper mFakeWrapper; - - // Override AndroidVibratorWrapper API to record the calling. - private static class FakeAndroidVibratorWrapper - extends VibrationManagerImpl.AndroidVibratorWrapper { - // Record the parameters of vibrate() and cancel(). - public long mMilliSeconds; - public boolean mCancelled; - - protected FakeAndroidVibratorWrapper() { - super(); - mMilliSeconds = -1; - mCancelled = false; - } - - @Override - public void vibrate(Vibrator vibrator, long milliseconds) { - mMilliSeconds = milliseconds; - } - - @Override - public void cancel(Vibrator vibrator) { - mCancelled = true; - } - } - - @Before - public void setUp() throws Exception { - mActivityTestRule.launchContentShellWithUrl("about:blank"); - mActivityTestRule.waitForActiveShellToBeDoneLoading(); - - mFakeWrapper = new FakeAndroidVibratorWrapper(); - VibrationManagerImpl.setVibratorWrapperForTesting(mFakeWrapper); - Assert.assertEquals(-1, mFakeWrapper.mMilliSeconds); - Assert.assertFalse(mFakeWrapper.mCancelled); - } - - /** - * Inject our fake wrapper into VibrationManagerImpl, - * load the webpage which will request vibrate for 3000 milliseconds, - * the fake wrapper vibrate() should be called and 3000 milliseconds should be recorded - * correctly. - */ - // @MediumTest - // @Feature({"Vibration"}) - @Test - @DisabledTest - public void testVibrate() throws Throwable { - mActivityTestRule.loadNewShell(URL_VIBRATOR_VIBRATE); - - // Waits until VibrationManagerImpl.Vibrate() got called. - CriteriaHelper.pollUiThread(new Criteria() { - @Override - public boolean isSatisfied() { - return mFakeWrapper.mMilliSeconds != -1; - } - }); - - Assert.assertEquals( - "Did not get vibrate mMilliSeconds correctly", 3000, mFakeWrapper.mMilliSeconds); - } - - /** - * Inject our fake wrapper into VibrationManagerImpl, - * load the webpage which will request vibrate and then request cancel, - * the fake wrapper cancel() should be called. - */ - @Test - @MediumTest - @Feature({"Vibration"}) - public void testCancel() throws Throwable { - mActivityTestRule.loadNewShell(URL_VIBRATOR_CANCEL); - - // Waits until VibrationManagerImpl.Cancel() got called. - CriteriaHelper.pollUiThread(new Criteria() { - @Override - public boolean isSatisfied() { - return mFakeWrapper.mCancelled; - } - }); - - Assert.assertTrue("Did not get cancelled", mFakeWrapper.mCancelled); - } -}
diff --git a/content/public/app/BUILD.gn b/content/public/app/BUILD.gn index 782cd3a9..82f65ba0 100644 --- a/content/public/app/BUILD.gn +++ b/content/public/app/BUILD.gn
@@ -178,6 +178,7 @@ name = "content_packaged_services" source = "mojo/content_packaged_services_manifest.json" packaged_services = [ + "//content/network:manifest", "//media/mojo/services:media_manifest", "//services/data_decoder:manifest", "//services/device:manifest",
diff --git a/content/public/app/mojo/content_browser_manifest.json b/content/public/app/mojo/content_browser_manifest.json index 38fbcc5..bf6b7ba 100644 --- a/content/public/app/mojo/content_browser_manifest.json +++ b/content/public/app/mojo/content_browser_manifest.json
@@ -28,6 +28,7 @@ "content::mojom::FieldTrialRecorder", "content::mojom::MemoryCoordinatorHandle", "content::mojom::PushMessaging", + "content::mojom::FrameSinkProvider", "content::mojom::ServiceWorkerDispatcherHost", "content::mojom::StoragePartitionService", "content::mojom::URLLoaderFactory",
diff --git a/content/public/browser/android/synchronous_compositor.cc b/content/public/browser/android/synchronous_compositor.cc index 2b9f39b..f1fdfee 100644 --- a/content/public/browser/android/synchronous_compositor.cc +++ b/content/public/browser/android/synchronous_compositor.cc
@@ -6,6 +6,7 @@ #include <utility> +#include "base/threading/thread_restrictions.h" #include "cc/output/compositor_frame.h" namespace content { @@ -36,6 +37,7 @@ DCHECK(!waited_); waited_ = true; #endif + base::ThreadRestrictions::ScopedAllowWait wait; waitable_event_.Wait(); return std::move(frame_); }
diff --git a/content/public/common/content_switches.cc b/content/public/common/content_switches.cc index 4230229..1704d64d 100644 --- a/content/public/common/content_switches.cc +++ b/content/public/common/content_switches.cc
@@ -419,6 +419,9 @@ // Enables the network information API. const char kEnableNetworkInformation[] = "enable-network-information"; +// Enables the network service. +const char kEnableNetworkService[] = "enable-network-service"; + // Disables the video decoder from drawing to an NV12 textures instead of ARGB. const char kDisableNv12DxgiVideo[] = "disable-nv12-dxgi-video";
diff --git a/content/public/common/content_switches.h b/content/public/common/content_switches.h index 3b9f899..545ec54 100644 --- a/content/public/common/content_switches.h +++ b/content/public/common/content_switches.h
@@ -135,6 +135,7 @@ CONTENT_EXPORT extern const char kEnableLCDText[]; CONTENT_EXPORT extern const char kEnableLogging[]; CONTENT_EXPORT extern const char kEnableNetworkInformation[]; +CONTENT_EXPORT extern const char kEnableNetworkService[]; CONTENT_EXPORT extern const char kDisableNv12DxgiVideo[]; CONTENT_EXPORT extern const char kEnablePinch[]; CONTENT_EXPORT extern const char kEnablePluginPlaceholderTesting[];
diff --git a/content/public/common/service_names.mojom b/content/public/common/service_names.mojom index d2bffb3b..7064122 100644 --- a/content/public/common/service_names.mojom +++ b/content/public/common/service_names.mojom
@@ -33,3 +33,6 @@ // them to the Service Manager. This must match the name in // src/content/public/app/mojo/content_utility_manifest.json. const string kUtilityServiceName = "content_utility"; + +// The name for the network service running in the utility process. +const string kNetworkServiceName = "network";
diff --git a/content/public/renderer/BUILD.gn b/content/public/renderer/BUILD.gn index d03316b..9f66a566 100644 --- a/content/public/renderer/BUILD.gn +++ b/content/public/renderer/BUILD.gn
@@ -49,6 +49,7 @@ "render_frame_observer.cc", "render_frame_observer.h", "render_frame_observer_tracker.h", + "render_frame_visitor.h", "render_thread.cc", "render_thread.h", "render_thread_observer.cc",
diff --git a/content/public/renderer/render_frame.h b/content/public/renderer/render_frame.h index 686d4771..4202f0d 100644 --- a/content/public/renderer/render_frame.h +++ b/content/public/renderer/render_frame.h
@@ -58,6 +58,7 @@ class ContextMenuClient; class PluginInstanceThrottler; class RenderAccessibility; +class RenderFrameVisitor; class RenderView; struct ContextMenuParams; struct WebPluginInfo; @@ -98,6 +99,9 @@ // Returns the RenderFrame given a routing id. static RenderFrame* FromRoutingID(int routing_id); + // Visit all live RenderFrames. + static void ForEach(RenderFrameVisitor* visitor); + // Returns the RenderView associated with this frame. virtual RenderView* GetRenderView() = 0;
diff --git a/content/public/renderer/render_frame_visitor.h b/content/public/renderer/render_frame_visitor.h new file mode 100644 index 0000000..8977fed --- /dev/null +++ b/content/public/renderer/render_frame_visitor.h
@@ -0,0 +1,23 @@ +// 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 CONTENT_PUBLIC_RENDERER_RENDER_FRAME_VISITOR_H_ +#define CONTENT_PUBLIC_RENDERER_RENDER_FRAME_VISITOR_H_ + +namespace content { + +class RenderFrame; + +class RenderFrameVisitor { + public: + // Return true to continue visiting RenderFrames or false to stop. + virtual bool Visit(RenderFrame* render_frame) = 0; + + protected: + virtual ~RenderFrameVisitor() {} +}; + +} // namespace content + +#endif // CONTENT_PUBLIC_RENDERER_RENDER_FRAME_VISITOR_H_
diff --git a/content/public/test/android/javatests/src/org/chromium/content/browser/test/ChildProcessAllocatorSettingsHook.java b/content/public/test/android/javatests/src/org/chromium/content/browser/test/ChildProcessAllocatorSettingsHook.java index f27badd4..ab42403 100644 --- a/content/public/test/android/javatests/src/org/chromium/content/browser/test/ChildProcessAllocatorSettingsHook.java +++ b/content/public/test/android/javatests/src/org/chromium/content/browser/test/ChildProcessAllocatorSettingsHook.java
@@ -7,7 +7,7 @@ import android.content.Context; import org.chromium.base.test.BaseTestResult.PreTestHook; -import org.chromium.content.browser.ChildProcessLauncher; +import org.chromium.content.browser.ChildConnectionAllocator; import java.lang.reflect.Method; @@ -18,7 +18,7 @@ ChildProcessAllocatorSettings annotation = testMethod.getAnnotation(ChildProcessAllocatorSettings.class); if (annotation != null) { - ChildProcessLauncher.setSanboxServicesSettingsForTesting( + ChildConnectionAllocator.setSanboxServicesSettingsForTesting( annotation.sandboxedServiceCount(), annotation.sandboxedServiceName()); } }
diff --git a/content/renderer/android/synchronous_compositor_frame_sink.cc b/content/renderer/android/synchronous_compositor_frame_sink.cc index e234565..ad0e358 100644 --- a/content/renderer/android/synchronous_compositor_frame_sink.cc +++ b/content/renderer/android/synchronous_compositor_frame_sink.cc
@@ -175,12 +175,12 @@ constexpr bool child_support_is_root = false; constexpr bool handles_frame_sink_id_invalidation = true; constexpr bool needs_sync_points = true; - root_support_.reset(new cc::CompositorFrameSinkSupport( + root_support_ = cc::CompositorFrameSinkSupport::Create( this, surface_manager_.get(), kRootFrameSinkId, root_support_is_root, - handles_frame_sink_id_invalidation, needs_sync_points)); - child_support_.reset(new cc::CompositorFrameSinkSupport( + handles_frame_sink_id_invalidation, needs_sync_points); + child_support_ = cc::CompositorFrameSinkSupport::Create( this, surface_manager_.get(), kChildFrameSinkId, child_support_is_root, - handles_frame_sink_id_invalidation, needs_sync_points)); + handles_frame_sink_id_invalidation, needs_sync_points); cc::RendererSettings software_renderer_settings; @@ -462,7 +462,10 @@ return thread_checker_.CalledOnValidThread(); } -void SynchronousCompositorFrameSink::DidReceiveCompositorFrameAck() {} +void SynchronousCompositorFrameSink::DidReceiveCompositorFrameAck( + const cc::ReturnedResourceArray& resources) { + ReclaimResources(resources); +} void SynchronousCompositorFrameSink::OnBeginFrame( const cc::BeginFrameArgs& args) {}
diff --git a/content/renderer/android/synchronous_compositor_frame_sink.h b/content/renderer/android/synchronous_compositor_frame_sink.h index e35a892..579fc717 100644 --- a/content/renderer/android/synchronous_compositor_frame_sink.h +++ b/content/renderer/android/synchronous_compositor_frame_sink.h
@@ -95,7 +95,8 @@ void DemandDrawSw(SkCanvas* canvas); // CompositorFrameSinkSupportClient implementation. - void DidReceiveCompositorFrameAck() override; + void DidReceiveCompositorFrameAck( + const cc::ReturnedResourceArray& resources) override; void OnBeginFrame(const cc::BeginFrameArgs& args) override; void ReclaimResources(const cc::ReturnedResourceArray& resources) override; void WillDrawSurface(const cc::LocalSurfaceId& local_surface_id,
diff --git a/content/renderer/gpu/compositor_forwarding_message_filter.cc b/content/renderer/gpu/compositor_forwarding_message_filter.cc index 72327e31..0d05718 100644 --- a/content/renderer/gpu/compositor_forwarding_message_filter.cc +++ b/content/renderer/gpu/compositor_forwarding_message_filter.cc
@@ -49,7 +49,6 @@ switch (message.type()) { case ViewMsg_SetBeginFramePaused::ID: case ViewMsg_BeginFrame::ID: - case ViewMsg_ReclaimCompositorResources::ID: break; default: return false;
diff --git a/content/renderer/gpu/render_widget_compositor.cc b/content/renderer/gpu/render_widget_compositor.cc index ab08fe1..3d535c5 100644 --- a/content/renderer/gpu/render_widget_compositor.cc +++ b/content/renderer/gpu/render_widget_compositor.cc
@@ -369,7 +369,7 @@ settings.initial_debug_state.SetRecordRenderingStats( cmd.HasSwitch(cc::switches::kEnableGpuBenchmarking)); - settings.needs_valid_local_surface_id = + settings.enable_surface_synchronization = cmd.HasSwitch(cc::switches::kEnableSurfaceSynchronization); if (cmd.HasSwitch(cc::switches::kSlowDownRasterScaleFactor)) {
diff --git a/content/renderer/gpu/renderer_compositor_frame_sink.cc b/content/renderer/gpu/renderer_compositor_frame_sink.cc index 77a5d205a..1d28f32 100644 --- a/content/renderer/gpu/renderer_compositor_frame_sink.cc +++ b/content/renderer/gpu/renderer_compositor_frame_sink.cc
@@ -28,7 +28,6 @@ RendererCompositorFrameSink::RendererCompositorFrameSink( int32_t routing_id, - uint32_t compositor_frame_sink_id, std::unique_ptr<cc::SyntheticBeginFrameSource> synthetic_begin_frame_source, scoped_refptr<cc::ContextProvider> context_provider, scoped_refptr<cc::ContextProvider> worker_context_provider, @@ -39,7 +38,6 @@ std::move(worker_context_provider), gpu_memory_buffer_manager, shared_bitmap_manager), - compositor_frame_sink_id_(compositor_frame_sink_id), compositor_frame_sink_filter_( RenderThreadImpl::current()->compositor_message_filter()), message_sender_(RenderThreadImpl::current()->sync_message_filter()), @@ -49,21 +47,21 @@ synthetic_begin_frame_source_ ? nullptr : base::MakeUnique<cc::ExternalBeginFrameSource>(this)), - routing_id_(routing_id) { + routing_id_(routing_id), + sink_client_binding_(this) { DCHECK(compositor_frame_sink_filter_); DCHECK(frame_swap_message_queue_); DCHECK(message_sender_); thread_checker_.DetachFromThread(); + EstablishMojoConnection(); } RendererCompositorFrameSink::RendererCompositorFrameSink( int32_t routing_id, - uint32_t compositor_frame_sink_id, std::unique_ptr<cc::SyntheticBeginFrameSource> synthetic_begin_frame_source, scoped_refptr<cc::VulkanContextProvider> vulkan_context_provider, scoped_refptr<FrameSwapMessageQueue> swap_frame_message_queue) : CompositorFrameSink(std::move(vulkan_context_provider)), - compositor_frame_sink_id_(compositor_frame_sink_id), compositor_frame_sink_filter_( RenderThreadImpl::current()->compositor_message_filter()), message_sender_(RenderThreadImpl::current()->sync_message_filter()), @@ -73,11 +71,13 @@ synthetic_begin_frame_source_ ? nullptr : base::MakeUnique<cc::ExternalBeginFrameSource>(this)), - routing_id_(routing_id) { + routing_id_(routing_id), + sink_client_binding_(this) { DCHECK(compositor_frame_sink_filter_); DCHECK(frame_swap_message_queue_); DCHECK(message_sender_); thread_checker_.DetachFromThread(); + EstablishMojoConnection(); } RendererCompositorFrameSink::~RendererCompositorFrameSink() { @@ -92,6 +92,9 @@ if (!cc::CompositorFrameSink::BindToClient(client)) return false; + sink_.Bind(std::move(sink_ptr_info_)); + sink_client_binding_.Bind(std::move(sink_client_request_)); + if (synthetic_begin_frame_source_) client_->SetBeginFrameSource(synthetic_begin_frame_source_.get()); else @@ -103,6 +106,7 @@ compositor_frame_sink_proxy_); compositor_frame_sink_filter_->AddHandlerOnCompositorThread( routing_id_, compositor_frame_sink_filter_handler_); + bound_ = true; return true; } @@ -117,7 +121,8 @@ compositor_frame_sink_proxy_->ClearCompositorFrameSink(); compositor_frame_sink_filter_->RemoveHandlerOnCompositorThread( routing_id_, compositor_frame_sink_filter_handler_); - + sink_.reset(); + sink_client_binding_.Close(); cc::CompositorFrameSink::DetachFromClient(); bound_ = false; } @@ -143,11 +148,10 @@ if (!messages_to_send.empty()) frame_token = frame_swap_message_queue_->AllocateFrameToken(); frame.metadata.frame_token = frame_token; - Send(new ViewHostMsg_SwapCompositorFrame( - routing_id_, compositor_frame_sink_id_, local_surface_id_, frame)); + sink_->SubmitCompositorFrame(local_surface_id_, std::move(frame)); if (frame_token) { - Send(new ViewHostMsg_FrameSwapMessages(routing_id_, frame_token, - messages_to_send)); + message_sender_->Send(new ViewHostMsg_FrameSwapMessages( + routing_id_, frame_token, messages_to_send)); } // ~send_message_scope. } @@ -157,41 +161,16 @@ const IPC::Message& message) { DCHECK(thread_checker_.CalledOnValidThread()); IPC_BEGIN_MESSAGE_MAP(RendererCompositorFrameSink, message) - IPC_MESSAGE_HANDLER(ViewMsg_ReclaimCompositorResources, - OnReclaimCompositorResources) - IPC_MESSAGE_HANDLER(ViewMsg_SetBeginFramePaused, - OnSetBeginFrameSourcePaused) - IPC_MESSAGE_HANDLER(ViewMsg_BeginFrame, OnBeginFrame) + IPC_MESSAGE_HANDLER(ViewMsg_BeginFrame, OnBeginFrameIPC) IPC_END_MESSAGE_MAP() } -void RendererCompositorFrameSink::OnReclaimCompositorResources( - uint32_t compositor_frame_sink_id, - bool is_swap_ack, - const cc::ReturnedResourceArray& resources) { - // Ignore message if it's a stale one coming from a different output surface - // (e.g. after a lost context). - if (compositor_frame_sink_id != compositor_frame_sink_id_) - return; - client_->ReclaimResources(resources); - if (is_swap_ack) - client_->DidReceiveCompositorFrameAck(); -} - -void RendererCompositorFrameSink::OnSetBeginFrameSourcePaused(bool paused) { - if (external_begin_frame_source_) - external_begin_frame_source_->OnSetBeginFrameSourcePaused(paused); -} - -void RendererCompositorFrameSink::OnBeginFrame(const cc::BeginFrameArgs& args) { +void RendererCompositorFrameSink::OnBeginFrameIPC( + const cc::BeginFrameArgs& args) { if (external_begin_frame_source_) external_begin_frame_source_->OnBeginFrame(args); } -bool RendererCompositorFrameSink::Send(IPC::Message* message) { - return message_sender_->Send(message); -} - bool RendererCompositorFrameSink::ShouldAllocateNewLocalSurfaceId( const cc::CompositorFrame& frame) { cc::RenderPass* root_pass = frame.render_pass_list.back().get(); @@ -239,8 +218,24 @@ #endif } +void RendererCompositorFrameSink::DidReceiveCompositorFrameAck( + const cc::ReturnedResourceArray& resources) { + ReclaimResources(resources); + client_->DidReceiveCompositorFrameAck(); +} + +void RendererCompositorFrameSink::OnBeginFrame(const cc::BeginFrameArgs& args) { + // See crbug.com/709689. + NOTREACHED() << "BeginFrames are delivered using Chrome IPC."; +} + +void RendererCompositorFrameSink::ReclaimResources( + const cc::ReturnedResourceArray& resources) { + client_->ReclaimResources(resources); +} + void RendererCompositorFrameSink::OnNeedsBeginFrames(bool needs_begin_frames) { - Send(new ViewHostMsg_SetNeedsBeginFrames(routing_id_, needs_begin_frames)); + sink_->SetNeedsBeginFrame(needs_begin_frames); } void RendererCompositorFrameSink::OnDidFinishFrame( @@ -248,7 +243,18 @@ DCHECK_LE(cc::BeginFrameArgs::kStartingFrameNumber, ack.sequence_number); // If there was damage, ViewHostMsg_SwapCompositorFrame includes the ack. if (!ack.has_damage) - Send(new ViewHostMsg_BeginFrameDidNotSwap(routing_id_, ack)); + sink_->BeginFrameDidNotSwap(ack); +} + +void RendererCompositorFrameSink::EstablishMojoConnection() { + cc::mojom::MojoCompositorFrameSinkPtr sink; + cc::mojom::MojoCompositorFrameSinkRequest sink_request = + mojo::MakeRequest(&sink); + cc::mojom::MojoCompositorFrameSinkClientPtr sink_client; + sink_client_request_ = mojo::MakeRequest(&sink_client); + RenderThreadImpl::current()->GetFrameSinkProvider()->CreateForWidget( + routing_id_, std::move(sink_request), std::move(sink_client)); + sink_ptr_info_ = sink.PassInterface(); } } // namespace content
diff --git a/content/renderer/gpu/renderer_compositor_frame_sink.h b/content/renderer/gpu/renderer_compositor_frame_sink.h index 07826f0..f57dbeb 100644 --- a/content/renderer/gpu/renderer_compositor_frame_sink.h +++ b/content/renderer/gpu/renderer_compositor_frame_sink.h
@@ -18,6 +18,7 @@ #include "base/time/time.h" #include "build/build_config.h" #include "cc/input/selection.h" +#include "cc/ipc/mojo_compositor_frame_sink.mojom.h" #include "cc/output/begin_frame_args.h" #include "cc/output/compositor_frame_sink.h" #include "cc/scheduler/begin_frame_source.h" @@ -25,6 +26,7 @@ #include "cc/surfaces/local_surface_id_allocator.h" #include "content/renderer/gpu/compositor_forwarding_message_filter.h" #include "ipc/ipc_sync_message_filter.h" +#include "mojo/public/cpp/bindings/binding.h" #include "ui/gfx/selection_bound.h" namespace IPC { @@ -44,11 +46,11 @@ class RendererCompositorFrameSink : NON_EXPORTED_BASE(public cc::CompositorFrameSink), NON_EXPORTED_BASE(public base::NonThreadSafe), + NON_EXPORTED_BASE(public cc::mojom::MojoCompositorFrameSinkClient), public cc::ExternalBeginFrameSourceClient { public: RendererCompositorFrameSink( int32_t routing_id, - uint32_t compositor_frame_sink_id, std::unique_ptr<cc::SyntheticBeginFrameSource> synthetic_begin_frame_source, scoped_refptr<cc::ContextProvider> context_provider, @@ -58,7 +60,6 @@ scoped_refptr<FrameSwapMessageQueue> swap_frame_message_queue); RendererCompositorFrameSink( int32_t routing_id, - uint32_t compositor_frame_sink_id, std::unique_ptr<cc::SyntheticBeginFrameSource> synthetic_begin_frame_source, scoped_refptr<cc::VulkanContextProvider> vulkan_context_provider, @@ -70,9 +71,6 @@ void DetachFromClient() override; void SubmitCompositorFrame(cc::CompositorFrame frame) override; - protected: - uint32_t compositor_frame_sink_id_; - private: class RendererCompositorFrameSinkProxy : public base::RefCountedThreadSafe<RendererCompositorFrameSinkProxy> { @@ -95,20 +93,23 @@ }; void OnMessageReceived(const IPC::Message& message); - void OnReclaimCompositorResources(uint32_t compositor_frame_sink_id, - bool is_swap_ack, - const cc::ReturnedResourceArray& resources); - void OnSetBeginFrameSourcePaused(bool paused); - void OnBeginFrame(const cc::BeginFrameArgs& args); - bool Send(IPC::Message* message); + void OnBeginFrameIPC(const cc::BeginFrameArgs& args); bool ShouldAllocateNewLocalSurfaceId(const cc::CompositorFrame& frame); void UpdateFrameData(const cc::CompositorFrame& frame); + // cc::mojom::MojoCompositorFrameSinkClient implementation. + void DidReceiveCompositorFrameAck( + const cc::ReturnedResourceArray& resources) override; + void OnBeginFrame(const cc::BeginFrameArgs& args) override; + void ReclaimResources(const cc::ReturnedResourceArray& resources) override; + // cc::ExternalBeginFrameSourceClient implementation. void OnNeedsBeginFrames(bool need_begin_frames) override; void OnDidFinishFrame(const cc::BeginFrameAck& ack) override; + void EstablishMojoConnection(); + scoped_refptr<CompositorForwardingMessageFilter> compositor_frame_sink_filter_; CompositorForwardingMessageFilter::Handler @@ -136,6 +137,12 @@ } current_frame_data_; base::ThreadChecker thread_checker_; + + cc::mojom::MojoCompositorFrameSinkPtr sink_; + cc::mojom::MojoCompositorFrameSinkPtrInfo sink_ptr_info_; + cc::mojom::MojoCompositorFrameSinkClientRequest sink_client_request_; + mojo::Binding<cc::mojom::MojoCompositorFrameSinkClient> sink_client_binding_; + bool bound_ = false; };
diff --git a/content/renderer/presentation/presentation_dispatcher.cc b/content/renderer/presentation/presentation_dispatcher.cc index 6a37530f..2bb5bb0 100644 --- a/content/renderer/presentation/presentation_dispatcher.cc +++ b/content/renderer/presentation/presentation_dispatcher.cc
@@ -384,8 +384,13 @@ void PresentationDispatcher::SetReceiver( blink::WebPresentationReceiver* receiver) { - ConnectToPresentationServiceIfNeeded(); receiver_ = receiver; + + // Create receiver PSImpl after loading document. + if (render_frame() && render_frame()->GetWebFrame() && + !render_frame()->GetWebFrame()->IsLoading()) { + ConnectToPresentationServiceIfNeeded(); + } } void PresentationDispatcher::DidCommitProvisionalLoad( @@ -401,6 +406,11 @@ std::swap(message_request_queue_, empty); } +void PresentationDispatcher::DidFinishDocumentLoad() { + if (receiver_) + ConnectToPresentationServiceIfNeeded(); +} + void PresentationDispatcher::OnDestruct() { delete this; }
diff --git a/content/renderer/presentation/presentation_dispatcher.h b/content/renderer/presentation/presentation_dispatcher.h index c7ae4a7c..e717cb1 100644 --- a/content/renderer/presentation/presentation_dispatcher.h +++ b/content/renderer/presentation/presentation_dispatcher.h
@@ -153,6 +153,7 @@ // RenderFrameObserver implementation. void DidCommitProvisionalLoad(bool is_new_navigation, bool is_same_document_navigation) override; + void DidFinishDocumentLoad() override; void OnDestruct() override; void WidgetWillClose() override;
diff --git a/content/renderer/render_frame_impl.cc b/content/renderer/render_frame_impl.cc index f67f5c5..334cdba 100644 --- a/content/renderer/render_frame_impl.cc +++ b/content/renderer/render_frame_impl.cc
@@ -90,6 +90,7 @@ #include "content/public/renderer/document_state.h" #include "content/public/renderer/navigation_state.h" #include "content/public/renderer/render_frame_observer.h" +#include "content/public/renderer/render_frame_visitor.h" #include "content/public/renderer/renderer_ppapi_host.h" #include "content/renderer/accessibility/render_accessibility_impl.h" #include "content/renderer/browser_plugin/browser_plugin.h" @@ -1051,6 +1052,15 @@ } // static +void RenderFrame::ForEach(RenderFrameVisitor* visitor) { + FrameMap* frames = g_frame_map.Pointer(); + for (FrameMap::iterator it = frames->begin(); it != frames->end(); ++it) { + if (!visitor->Visit(it->second)) + return; + } +} + +// static RenderFrameImpl* RenderFrameImpl::FromWebFrame(blink::WebFrame* web_frame) { FrameMap::iterator iter = g_frame_map.Get().find(web_frame); if (iter != g_frame_map.Get().end())
diff --git a/content/renderer/render_thread_impl.cc b/content/renderer/render_thread_impl.cc index 6c478d38..43fb6ba 100644 --- a/content/renderer/render_thread_impl.cc +++ b/content/renderer/render_thread_impl.cc
@@ -250,8 +250,10 @@ // allocation that exceeds this limit. const size_t kImageCacheSingleAllocationByteLimit = 64 * 1024 * 1024; +#if defined(OS_ANDROID) // Unique identifier for each output surface created. uint32_t g_next_compositor_frame_sink_id = 1; +#endif // An implementation of mojom::RenderMessageFilter which can be mocked out // for tests which may indirectly send messages over this interface. @@ -892,6 +894,9 @@ // redirection experiment concludes https://crbug.com/622400. if (!command_line.HasSwitch(switches::kSingleProcess)) base::SequencedWorkerPool::EnableForProcess(); + + GetConnector()->BindInterface(mojom::kBrowserServiceName, + mojo::MakeRequest(&frame_sink_provider_)); } RenderThreadImpl::~RenderThreadImpl() { @@ -1895,16 +1900,13 @@ } #endif - uint32_t compositor_frame_sink_id = g_next_compositor_frame_sink_id++; - if (command_line.HasSwitch(switches::kEnableVulkan)) { scoped_refptr<cc::VulkanContextProvider> vulkan_context_provider = cc::VulkanInProcessContextProvider::Create(); if (vulkan_context_provider) { DCHECK(!layout_test_mode()); callback.Run(base::MakeUnique<RendererCompositorFrameSink>( - routing_id, compositor_frame_sink_id, - std::move(synthetic_begin_frame_source), + routing_id, std::move(synthetic_begin_frame_source), std::move(vulkan_context_provider), std::move(frame_swap_message_queue))); return; @@ -1930,9 +1932,8 @@ if (use_software) { DCHECK(!layout_test_mode()); callback.Run(base::MakeUnique<RendererCompositorFrameSink>( - routing_id, compositor_frame_sink_id, - std::move(synthetic_begin_frame_source), nullptr, nullptr, nullptr, - shared_bitmap_manager(), std::move(frame_swap_message_queue))); + routing_id, std::move(synthetic_begin_frame_source), nullptr, nullptr, + nullptr, shared_bitmap_manager(), std::move(frame_swap_message_queue))); return; } @@ -1993,16 +1994,16 @@ callback.Run(base::MakeUnique<SynchronousCompositorFrameSink>( std::move(context_provider), std::move(worker_context_provider), GetGpuMemoryBufferManager(), shared_bitmap_manager(), routing_id, - compositor_frame_sink_id, std::move(begin_frame_source), + g_next_compositor_frame_sink_id++, std::move(begin_frame_source), sync_compositor_message_filter_.get(), std::move(frame_swap_message_queue))); return; } #endif callback.Run(base::WrapUnique(new RendererCompositorFrameSink( - routing_id, compositor_frame_sink_id, - std::move(synthetic_begin_frame_source), std::move(context_provider), - std::move(worker_context_provider), GetGpuMemoryBufferManager(), nullptr, + routing_id, std::move(synthetic_begin_frame_source), + std::move(context_provider), std::move(worker_context_provider), + GetGpuMemoryBufferManager(), nullptr, std::move(frame_swap_message_queue)))); }
diff --git a/content/renderer/render_thread_impl.h b/content/renderer/render_thread_impl.h index 83960ac..b46d2dc 100644 --- a/content/renderer/render_thread_impl.h +++ b/content/renderer/render_thread_impl.h
@@ -32,6 +32,7 @@ #include "content/common/content_export.h" #include "content/common/frame.mojom.h" #include "content/common/frame_replication_state.h" +#include "content/common/frame_sink_provider.mojom.h" #include "content/common/render_frame_message_filter.mojom.h" #include "content/common/render_message_filter.mojom.h" #include "content/common/renderer.mojom.h" @@ -504,6 +505,10 @@ return needs_to_record_first_active_paint_; } + mojom::FrameSinkProvider* GetFrameSinkProvider() { + return frame_sink_provider_.get(); + } + protected: RenderThreadImpl( const InProcessChildThreadParams& params, @@ -786,6 +791,8 @@ variations::ChildProcessFieldTrialSyncer field_trial_syncer_; + mojom::FrameSinkProviderPtr frame_sink_provider_; + DISALLOW_COPY_AND_ASSIGN(RenderThreadImpl); };
diff --git a/content/renderer/screen_orientation/OWNERS b/content/renderer/screen_orientation/OWNERS index 2d28246..20b13b9 100644 --- a/content/renderer/screen_orientation/OWNERS +++ b/content/renderer/screen_orientation/OWNERS
@@ -1 +1,2 @@ -mlamouri@chromium.org +file://third_party/WebKit/Source/modules/screen_orientation/OWNERS +
diff --git a/content/test/BUILD.gn b/content/test/BUILD.gn index 0a43bbcc..5537adb 100644 --- a/content/test/BUILD.gn +++ b/content/test/BUILD.gn
@@ -165,6 +165,8 @@ "fake_compositor_dependencies.h", "fake_plugin_service.cc", "fake_plugin_service.h", + "fake_renderer_compositor_frame_sink.cc", + "fake_renderer_compositor_frame_sink.h", "mock_background_sync_controller.cc", "mock_background_sync_controller.h", "mock_google_streaming_server.cc", @@ -245,6 +247,7 @@ "//cc:test_support", "//cc/blink", "//cc/ipc", + "//cc/ipc:interfaces", "//cc/surfaces", "//components/display_compositor", "//components/leveldb/public/interfaces", @@ -1389,6 +1392,7 @@ "../common/service_manager/service_manager_connection_impl_unittest.cc", "../common/service_worker/service_worker_utils_unittest.cc", "../common/webplugininfo_unittest.cc", + "../network/url_loader_unittest.cc", "../public/test/referrer_unittest.cc", "../renderer/android/disambiguation_popup_helper_unittest.cc", "../renderer/bmp_image_decoder_unittest.cc", @@ -1483,6 +1487,7 @@ "//content/browser/speech/proto", "//content/child:for_content_tests", "//content/gpu", + "//content/network", "//content/public/browser", "//content/public/child", "//content/public/common",
diff --git a/content/test/data/gpu/pixel_offscreenCanvas_2d_commit_main.html b/content/test/data/gpu/pixel_offscreenCanvas_2d_commit_main.html index 193d1cd..4a008142 100644 --- a/content/test/data/gpu/pixel_offscreenCanvas_2d_commit_main.html +++ b/content/test/data/gpu/pixel_offscreenCanvas_2d_commit_main.html
@@ -16,11 +16,11 @@ </style> </head> <body onload="main()"> -<div style="position:relative; width:400px; height:200px; background-color:white"> +<div style="position:relative; width:360px; height:200px; background-color:white"> </div> <div id="container" style="position:absolute; top:0px; left:0px"> -<canvas id="canvas1" width="200" height="200" class="nomargin"></canvas> -<canvas id="canvas2" width="200" height="200" class="nomargin"></canvas> +<canvas id="canvas1" width="180" height="200" class="nomargin"></canvas> +<canvas id="canvas2" width="180" height="200" class="nomargin"></canvas> </div> <script> /* This pixel test checks the following: @@ -47,12 +47,12 @@ var ctx2 = getOffscreenContext("canvas2"); ctx1.fillStyle = "green"; - ctx1.fillRect(0, 0, 200, 200); + ctx1.fillRect(0, 0, 180, 200); // The promise returned by this ctx1.commit() must be resolved at // about the same time as the other ctx2.commit() below as they are in the // same JS task. ctx1.commit().then(function() { - ctx2.fillRect(0, 0, 200, 200); + ctx2.fillRect(0, 0, 180, 200); // This ctx2.commit() must happen after the other ctx2.commit() below. ctx2.commit(); if (--g_asyncCallbackNumber == 0) waitForFinish(); @@ -88,18 +88,18 @@ // Do something complex to ctx2. ctx2.fillStyle = "blue"; - ctx2.fillRect(0, 0, 200, 200); - drawStar(ctx2, 100, 100, 25, 60, 40); + ctx2.fillRect(0, 0, 180, 200); + drawStar(ctx2, 90, 100, 25, 60, 40); // This ctx2.commit() must be resolved at about the same time as the first // ctx1.commit() above because they are in the same JS task, no matter how // complex the drawing operation is. ctx2.commit().then(function() { - drawStar(ctx1, 80, 80, 7, 60, 30); + drawStar(ctx1, 70, 80, 7, 60, 30); ctx1.commit(); // The following fill is never committed ctx1.fillStyle = "red"; - ctx1.fillRect(0, 0, 200, 200); + ctx1.fillRect(0, 0, 180, 200); if (--g_asyncCallbackNumber == 0) waitForFinish(); });
diff --git a/content/test/data/gpu/pixel_offscreenCanvas_2d_commit_worker.html b/content/test/data/gpu/pixel_offscreenCanvas_2d_commit_worker.html index feced124..0ceb819 100644 --- a/content/test/data/gpu/pixel_offscreenCanvas_2d_commit_worker.html +++ b/content/test/data/gpu/pixel_offscreenCanvas_2d_commit_worker.html
@@ -38,12 +38,12 @@ function startTest() { g_ctx1.fillStyle = "green"; - g_ctx1.fillRect(0, 0, 200, 200); + g_ctx1.fillRect(0, 0, 180, 200); // The promise returned by this g_ctx1.commit() must be resolved at // about the same time as the other g_ctx2.commit() below as they are in the // same JS task. g_ctx1.commit().then(function() { - g_ctx2.fillRect(0, 0, 200, 200); + g_ctx2.fillRect(0, 0, 180, 200); // This g_ctx2.commit() must happen after the other g_ctx2.commit() below. g_ctx2.commit(); if (--g_asyncCallbackNumber == 0) self.postMessage(""); @@ -79,18 +79,18 @@ // Do something complex to g_ctx2. g_ctx2.fillStyle = "blue"; - g_ctx2.fillRect(0, 0, 200, 200); - drawStar(g_ctx2, 100, 100, 25, 60, 40); + g_ctx2.fillRect(0, 0, 180, 200); + drawStar(g_ctx2, 90, 100, 25, 60, 40); // This g_ctx2.commit() must be resolved at about the same time as the first // g_ctx1.commit() above because they are in the same JS task, no matter how // complex the drawing operation is. g_ctx2.commit().then(function() { - drawStar(g_ctx1, 80, 80, 7, 60, 30); + drawStar(g_ctx1, 70, 80, 7, 60, 30); g_ctx1.commit(); // The following fill is never committed g_ctx1.fillStyle = "red"; - g_ctx1.fillRect(0, 0, 200, 200); + g_ctx1.fillRect(0, 0, 180, 200); if (--g_asyncCallbackNumber == 0) self.postMessage(""); }); @@ -135,11 +135,11 @@ </script> </head> <body onload="main()"> -<div style="position:relative; width:400px; height:200px; background-color:white"> +<div style="position:relative; width:360px; height:200px; background-color:white"> </div> <div id="container" style="position:absolute; top:0px; left:0px"> -<canvas id="canvas1" width="200" height="200" class="nomargin"></canvas> -<canvas id="canvas2" width="200" height="200" class="nomargin"></canvas> +<canvas id="canvas1" width="180" height="200" class="nomargin"></canvas> +<canvas id="canvas2" width="180" height="200" class="nomargin"></canvas> </div> </body> </html>
diff --git a/content/test/data/gpu/pixel_offscreenCanvas_webgl_commit_main.html b/content/test/data/gpu/pixel_offscreenCanvas_webgl_commit_main.html index 3f0895d2..d314ffc 100644 --- a/content/test/data/gpu/pixel_offscreenCanvas_webgl_commit_main.html +++ b/content/test/data/gpu/pixel_offscreenCanvas_webgl_commit_main.html
@@ -127,11 +127,11 @@ </script> </head> <body onload="main()"> -<div style="position:relative; width:400px; height:200px; background-color:white"> +<div style="position:relative; width:360px; height:200px; background-color:white"> </div> <div id="container" style="position:absolute; top:0px; left:0px"> -<canvas id="canvas1" width="200" height="200" class="nomargin"></canvas> -<canvas id="canvas2" width="200" height="200" class="nomargin"></canvas> +<canvas id="canvas1" width="180" height="200" class="nomargin"></canvas> +<canvas id="canvas2" width="180" height="200" class="nomargin"></canvas> </div> </body> </html>
diff --git a/content/test/data/gpu/pixel_offscreenCanvas_webgl_commit_worker.html b/content/test/data/gpu/pixel_offscreenCanvas_webgl_commit_worker.html index a3f916bb..d6b4ca5 100644 --- a/content/test/data/gpu/pixel_offscreenCanvas_webgl_commit_worker.html +++ b/content/test/data/gpu/pixel_offscreenCanvas_webgl_commit_worker.html
@@ -147,11 +147,11 @@ </script> </head> <body onload="main()"> -<div style="position:relative; width:400px; height:200px; background-color:white"> +<div style="position:relative; width:360px; height:200px; background-color:white"> </div> <div id="container" style="position:absolute; top:0px; left:0px"> -<canvas id="canvas1" width="200" height="200" class="nomargin"></canvas> -<canvas id="canvas2" width="200" height="200" class="nomargin"></canvas> +<canvas id="canvas1" width="180" height="200" class="nomargin"></canvas> +<canvas id="canvas2" width="180" height="200" class="nomargin"></canvas> </div> </body> </html>
diff --git a/content/test/fake_renderer_compositor_frame_sink.cc b/content/test/fake_renderer_compositor_frame_sink.cc new file mode 100644 index 0000000..1fa897a --- /dev/null +++ b/content/test/fake_renderer_compositor_frame_sink.cc
@@ -0,0 +1,36 @@ +// 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 "content/test/fake_renderer_compositor_frame_sink.h" + +namespace content { + +FakeRendererCompositorFrameSink::FakeRendererCompositorFrameSink( + cc::mojom::MojoCompositorFrameSinkPtr sink, + cc::mojom::MojoCompositorFrameSinkClientRequest request) + : binding_(this, std::move(request)), sink_(std::move(sink)) {} + +FakeRendererCompositorFrameSink::~FakeRendererCompositorFrameSink() = default; + +void FakeRendererCompositorFrameSink::DidReceiveCompositorFrameAck( + const cc::ReturnedResourceArray& resources) { + ReclaimResources(resources); + did_receive_ack_ = true; +} + +void FakeRendererCompositorFrameSink::ReclaimResources( + const cc::ReturnedResourceArray& resources) { + last_reclaimed_resources_ = resources; +} + +void FakeRendererCompositorFrameSink::Reset() { + did_receive_ack_ = false; + last_reclaimed_resources_.clear(); +} + +void FakeRendererCompositorFrameSink::Flush() { + binding_.FlushForTesting(); +} + +} // namespace content
diff --git a/content/test/fake_renderer_compositor_frame_sink.h b/content/test/fake_renderer_compositor_frame_sink.h new file mode 100644 index 0000000..5bcdfa3 --- /dev/null +++ b/content/test/fake_renderer_compositor_frame_sink.h
@@ -0,0 +1,51 @@ +// 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 CONTENT_TEST_FAKE_RENDERER_COMPOSITOR_FRAME_SINK_H_ +#define CONTENT_TEST_FAKE_RENDERER_COMPOSITOR_FRAME_SINK_H_ + +#include "cc/ipc/mojo_compositor_frame_sink.mojom.h" +#include "mojo/public/cpp/bindings/binding.h" + +namespace content { + +// This class is given to RenderWidgetHost/RenderWidgetHostView unit tests +// instead of RendererCompositorFrameSink. +class FakeRendererCompositorFrameSink + : public cc::mojom::MojoCompositorFrameSinkClient { + public: + FakeRendererCompositorFrameSink( + cc::mojom::MojoCompositorFrameSinkPtr sink, + cc::mojom::MojoCompositorFrameSinkClientRequest request); + ~FakeRendererCompositorFrameSink() override; + + bool did_receive_ack() { return did_receive_ack_; } + cc::ReturnedResourceArray& last_reclaimed_resources() { + return last_reclaimed_resources_; + } + + // cc::mojom::MojoCompositorFrameSinkClient implementation. + void DidReceiveCompositorFrameAck( + const cc::ReturnedResourceArray& resources) override; + void OnBeginFrame(const cc::BeginFrameArgs& args) override {} + void ReclaimResources(const cc::ReturnedResourceArray& resources) override; + + // Resets test data. + void Reset(); + + // Runs all queued messages. + void Flush(); + + private: + mojo::Binding<cc::mojom::MojoCompositorFrameSinkClient> binding_; + cc::mojom::MojoCompositorFrameSinkPtr sink_; + bool did_receive_ack_ = false; + cc::ReturnedResourceArray last_reclaimed_resources_; + + DISALLOW_COPY_AND_ASSIGN(FakeRendererCompositorFrameSink); +}; + +} // namespace content + +#endif // CONTENT_TEST_FAKE_RENDERER_COMPOSITOR_FRAME_SINK_H_
diff --git a/content/test/gpu/gpu_tests/gpu_process_expectations.py b/content/test/gpu/gpu_tests/gpu_process_expectations.py index 1706628b..b459316 100644 --- a/content/test/gpu/gpu_tests/gpu_process_expectations.py +++ b/content/test/gpu/gpu_tests/gpu_process_expectations.py
@@ -17,16 +17,15 @@ self.Skip('GpuProcess_no_gpu_process', ['android'], bug=643282) self.Skip('GpuProcess_skip_gpu_process', ['android'], bug=(610951, 610023)) - # Chrome on Windows creates a GPU process that uses SwiftShader when using - # either --disable-gpu or a blacklisted GPU. + # Chrome on Windows and Linux create a GPU process that uses SwiftShader + # when using either --disable-gpu or a blacklisted GPU. self.Skip('GpuProcess_no_gpu_process', ['win', 'debug'], bug=630728) - self.Skip('GpuProcess_skip_gpu_process', ['win'], bug=630728) + self.Skip('GpuProcess_skip_gpu_process', ['win', 'linux'], bug=630728) - # Currently SwiftShader's integrated only on Windows. Remove - # platforms from this suppression as it is integrated on more - # platforms. + # Currently SwiftShader is integrated only on Windows and Linux. Remove + # platforms from this suppression as it is integrated on more platforms. self.Skip('GpuProcess_swiftshader_for_webgl', - ['mac', 'linux', 'android', 'chromeos'], bug=630728) + ['mac', 'android', 'chromeos'], bug=630728) # There is no Android multi-gpu configuration and the helper # gpu_info_collector.cc::IdentifyActiveGPU is not even called.
diff --git a/content/test/gpu/gpu_tests/gpu_process_integration_test.py b/content/test/gpu/gpu_tests/gpu_process_integration_test.py index bb144a4..207bbad 100644 --- a/content/test/gpu/gpu_tests/gpu_process_integration_test.py +++ b/content/test/gpu/gpu_tests/gpu_process_integration_test.py
@@ -469,7 +469,8 @@ '--gpu-testing-device-id=0x040a', '--gpu-testing-secondary-vendor-ids=0x10de', '--gpu-testing-secondary-device-ids=0x0de1', - '--gpu-testing-gl-vendor=nouveau']) + '--gpu-testing-gl-vendor=nouveau', + '--disable-software-rasterizer']) self._Navigate(test_path) self._VerifyActiveAndInactiveGPUs( ['VENDOR = 0x10de, DEVICE= 0x0de1 *ACTIVE*'], @@ -481,7 +482,8 @@ '--gpu-testing-device-id=0x040a', '--gpu-testing-secondary-vendor-ids=0x10de', '--gpu-testing-secondary-device-ids=0x0de1', - '--gpu-testing-gl-vendor=Intel']) + '--gpu-testing-gl-vendor=Intel', + '--disable-software-rasterizer']) self._Navigate(test_path) self._VerifyActiveAndInactiveGPUs( ['VENDOR = 0x8086, DEVICE= 0x040a *ACTIVE*'], @@ -494,7 +496,8 @@ '--gpu-testing-secondary-vendor-ids=0x10de;0x1002', '--gpu-testing-secondary-device-ids=0x0de1;0x6779', '--gpu-testing-gl-vendor=X.Org', - '--gpu-testing-gl-renderer=AMD R600']) + '--gpu-testing-gl-renderer=AMD R600', + '--disable-software-rasterizer']) self._Navigate(test_path) self._VerifyActiveAndInactiveGPUs( ['VENDOR = 0x1002, DEVICE= 0x6779 *ACTIVE*'], @@ -507,7 +510,8 @@ '--gpu-testing-device-id=0x0de1', '--gpu-testing-secondary-vendor-ids=', '--gpu-testing-secondary-device-ids=', - '--gpu-testing-gl-vendor=nouveau']) + '--gpu-testing-gl-vendor=nouveau', + '--disable-software-rasterizer']) self._Navigate(test_path) self._VerifyActiveAndInactiveGPUs( ['VENDOR = 0x10de, DEVICE= 0x0de1 *ACTIVE*'], @@ -561,10 +565,6 @@ device = gpu.devices[0] if not device: self.fail("System Info doesn't have a device") - if device.vendor_id != 0: - self.fail("Wrong vendor ID. Expected 0, got " + hex(device.vendor_id)) - if device.device_id != 0: - self.fail("Wrong device ID. Expected 0, got " + hex(device.device_id)) def load_tests(loader, tests, pattern): del loader, tests, pattern # Unused.
diff --git a/content/test/gpu/gpu_tests/pixel_expectations.py b/content/test/gpu/gpu_tests/pixel_expectations.py index 511b009..681236c 100644 --- a/content/test/gpu/gpu_tests/pixel_expectations.py +++ b/content/test/gpu/gpu_tests/pixel_expectations.py
@@ -53,17 +53,17 @@ # TODO(jbauman): Re-enable when references images created. self.Fail('Pixel_DirectComposition_Video_*', ['win'], bug=704389) - # TODO(xlai): Remove this after test dimension is shrunk - # Intended to skip only Nexus 5 - self.Skip('Pixel_OffscreenCanvasAccelerated2D', - ['android', ('qualcomm', 'Adreno (TM) 330')], bug=706647) - self.Skip('Pixel_OffscreenCanvasAccelerated2DWorker', - ['android', ('qualcomm', 'Adreno (TM) 330')], bug=706647) - self.Skip('Pixel_OffscreenCanvasUnaccelerated2DGPUCompositing', - ['android', ('qualcomm', 'Adreno (TM) 330')], bug=706647) - self.Skip('Pixel_OffscreenCanvasUnaccelerated2DGPUCompositingWorker', - ['android', ('qualcomm', 'Adreno (TM) 330')], bug=706647) - self.Skip('Pixel_OffscreenCanvasWebGLDefault', - ['android', ('qualcomm', 'Adreno (TM) 330')], bug=706647) - self.Skip('Pixel_OffscreenCanvasWebGLDefaultWorker', - ['android', ('qualcomm', 'Adreno (TM) 330')], bug=706647) + # TODO(xlai): Remove this after verifying reference images. + self.Fail('Pixel_OffscreenCanvasAccelerated2D', bug=706647) + self.Fail('Pixel_OffscreenCanvasAccelerated2DWorker', bug=706647) + self.Fail('Pixel_OffscreenCanvasUnaccelerated2D', bug=706647) + self.Fail('Pixel_OffscreenCanvasUnaccelerated2DWorker', bug=706647) + self.Fail('Pixel_OffscreenCanvasUnaccelerated2DGPUCompositing', + bug=706647) + self.Fail('Pixel_OffscreenCanvasUnaccelerated2DGPUCompositingWorker', + bug=706647) + self.Fail('Pixel_OffscreenCanvasWebGLDefault', bug=706647) + self.Fail('Pixel_OffscreenCanvasWebGLDefaultWorker', bug=706647) + self.Fail('Pixel_OffscreenCanvasWebGLSoftwareCompositing', bug=706647) + self.Fail('Pixel_OffscreenCanvasWebGLSoftwareCompositingWorker', + bug=706647)
diff --git a/content/test/gpu/gpu_tests/pixel_test_pages.py b/content/test/gpu/gpu_tests/pixel_test_pages.py index acc40096..5d85784 100644 --- a/content/test/gpu/gpu_tests/pixel_test_pages.py +++ b/content/test/gpu/gpu_tests/pixel_test_pages.py
@@ -319,71 +319,71 @@ PixelTestPage( 'pixel_offscreenCanvas_webgl_commit_main.html', base_name + '_OffscreenCanvasWebGLDefault', - test_rect=[0, 0, 400, 200], - revision=3, + test_rect=[0, 0, 360, 200], + revision=4, browser_args=browser_args), PixelTestPage( 'pixel_offscreenCanvas_webgl_commit_worker.html', base_name + '_OffscreenCanvasWebGLDefaultWorker', - test_rect=[0, 0, 400, 200], - revision=3, + test_rect=[0, 0, 360, 200], + revision=4, browser_args=browser_args), PixelTestPage( 'pixel_offscreenCanvas_webgl_commit_main.html', base_name + '_OffscreenCanvasWebGLSoftwareCompositing', - test_rect=[0, 0, 400, 200], - revision=4, + test_rect=[0, 0, 360, 200], + revision=5, browser_args=browser_args + ['--disable-gpu-compositing']), PixelTestPage( 'pixel_offscreenCanvas_webgl_commit_worker.html', base_name + '_OffscreenCanvasWebGLSoftwareCompositingWorker', - test_rect=[0, 0, 400, 200], - revision=4, + test_rect=[0, 0, 360, 200], + revision=5, browser_args=browser_args + ['--disable-gpu-compositing']), PixelTestPage( 'pixel_offscreenCanvas_2d_commit_main.html', base_name + '_OffscreenCanvasAccelerated2D', - test_rect=[0, 0, 400, 200], - revision=5, + test_rect=[0, 0, 360, 200], + revision=6, browser_args=browser_args), PixelTestPage( 'pixel_offscreenCanvas_2d_commit_worker.html', base_name + '_OffscreenCanvasAccelerated2DWorker', - test_rect=[0, 0, 400, 200], - revision=5, + test_rect=[0, 0, 360, 200], + revision=6, browser_args=browser_args), PixelTestPage( 'pixel_offscreenCanvas_2d_commit_main.html', base_name + '_OffscreenCanvasUnaccelerated2D', - test_rect=[0, 0, 400, 200], - revision=4, + test_rect=[0, 0, 360, 200], + revision=5, browser_args=browser_args + unaccelerated_args), PixelTestPage( 'pixel_offscreenCanvas_2d_commit_worker.html', base_name + '_OffscreenCanvasUnaccelerated2DWorker', - test_rect=[0, 0, 400, 200], - revision=4, + test_rect=[0, 0, 360, 200], + revision=5, browser_args=browser_args + unaccelerated_args), PixelTestPage( 'pixel_offscreenCanvas_2d_commit_main.html', base_name + '_OffscreenCanvasUnaccelerated2DGPUCompositing', - test_rect=[0, 0, 400, 200], - revision=6, + test_rect=[0, 0, 360, 200], + revision=7, browser_args=browser_args + ['--disable-accelerated-2d-canvas']), PixelTestPage( 'pixel_offscreenCanvas_2d_commit_worker.html', base_name + '_OffscreenCanvasUnaccelerated2DGPUCompositingWorker', - test_rect=[0, 0, 400, 200], - revision=6, + test_rect=[0, 0, 360, 200], + revision=7, browser_args=browser_args + ['--disable-accelerated-2d-canvas']), PixelTestPage(
diff --git a/content/test/gpu/gpu_tests/webgl2_conformance_expectations.py b/content/test/gpu/gpu_tests/webgl2_conformance_expectations.py index f4cd54b4..507f23b 100644 --- a/content/test/gpu/gpu_tests/webgl2_conformance_expectations.py +++ b/content/test/gpu/gpu_tests/webgl2_conformance_expectations.py
@@ -719,6 +719,9 @@ self.Fail('conformance2/textures/canvas_sub_rectangle/' + 'tex-2d-rgb16f-rgb-half_float.html', ['linux', 'nvidia'], bug=694359) + self.Flaky('conformance2/textures/canvas_sub_rectangle/' + + 'tex-2d-rgb565-rgb-unsigned_byte.html', + ['linux', 'nvidia'], bug=694359) self.Fail('conformance2/textures/image_bitmap_from_canvas/' + 'tex-3d-srgb8_alpha8-rgba-unsigned_byte.html', ['linux', 'nvidia'], bug=679677)
diff --git a/content/test/gpu/gpu_tests/webgl_conformance_revision.txt b/content/test/gpu/gpu_tests/webgl_conformance_revision.txt index b820de1..62564a4 100644 --- a/content/test/gpu/gpu_tests/webgl_conformance_revision.txt +++ b/content/test/gpu/gpu_tests/webgl_conformance_revision.txt
@@ -1,3 +1,3 @@ # AUTOGENERATED FILE - DO NOT EDIT # SEE roll_webgl_conformance.py -Current webgl revision 32cfddc9e452c93bcbe443d6ddcc0c18ac556501 +Current webgl revision fd73a606f94d1837eba4d165f1f5b3afd542fc08
diff --git a/content/test/test_render_view_host.cc b/content/test/test_render_view_host.cc index d2cb871..9496f6c 100644 --- a/content/test/test_render_view_host.cc +++ b/content/test/test_render_view_host.cc
@@ -180,7 +180,8 @@ return gfx::Rect(); } -void TestRenderWidgetHostView::DidCreateNewRendererCompositorFrameSink() { +void TestRenderWidgetHostView::DidCreateNewRendererCompositorFrameSink( + cc::mojom::MojoCompositorFrameSinkClient* renderer_compositor_frame_sink) { did_change_compositor_frame_sink_ = true; }
diff --git a/content/test/test_render_view_host.h b/content/test/test_render_view_host.h index 577b141..9bbee74 100644 --- a/content/test/test_render_view_host.h +++ b/content/test/test_render_view_host.h
@@ -88,7 +88,9 @@ bool IsSpeaking() const override; void StopSpeaking() override; #endif // defined(OS_MACOSX) - void DidCreateNewRendererCompositorFrameSink() override; + void DidCreateNewRendererCompositorFrameSink( + cc::mojom::MojoCompositorFrameSinkClient* renderer_compositor_frame_sink) + override; void SubmitCompositorFrame(const cc::LocalSurfaceId& local_surface_id, cc::CompositorFrame frame) override; void ClearCompositorFrame() override {}
diff --git a/content/utility/BUILD.gn b/content/utility/BUILD.gn index a589df1..2368cf8 100644 --- a/content/utility/BUILD.gn +++ b/content/utility/BUILD.gn
@@ -31,6 +31,7 @@ "//base", "//content:export", "//content/child", + "//content/network:network_sources", "//content/public/child:child_sources", "//content/public/common:common_sources", "//mojo/common",
diff --git a/content/utility/DEPS b/content/utility/DEPS index 74ac29f..26456d68 100644 --- a/content/utility/DEPS +++ b/content/utility/DEPS
@@ -1,6 +1,7 @@ include_rules = [ "+components/scheduler/child", "+content/child", + "+content/network", "+content/public/utility", "+services/data_decoder", "+services/service_manager",
diff --git a/content/utility/utility_service_factory.cc b/content/utility/utility_service_factory.cc index 9a28ba4..a1c8336 100644 --- a/content/utility/utility_service_factory.cc +++ b/content/utility/utility_service_factory.cc
@@ -5,7 +5,11 @@ #include "content/utility/utility_service_factory.h" #include "base/bind.h" +#include "base/command_line.h" +#include "content/network/network_service.h" #include "content/public/common/content_client.h" +#include "content/public/common/content_switches.h" +#include "content/public/common/service_names.mojom.h" #include "content/public/utility/content_utility_client.h" #include "content/public/utility/utility_thread.h" #include "content/utility/utility_thread_impl.h" @@ -51,6 +55,14 @@ data_decoder_info.factory = base::Bind(&CreateDataDecoderService); services->insert( std::make_pair(data_decoder::mojom::kServiceName, data_decoder_info)); + + if (base::CommandLine::ForCurrentProcess()->HasSwitch( + switches::kEnableNetworkService)) { + ServiceInfo network_info; + network_info.factory = base::Bind(&NetworkService::CreateNetworkService); + services->insert( + std::make_pair(content::mojom::kNetworkServiceName, network_info)); + } } void UtilityServiceFactory::OnServiceQuit() {
diff --git a/content/utility/utility_thread_impl.cc b/content/utility/utility_thread_impl.cc index e86c06c1..36e0e1d 100644 --- a/content/utility/utility_thread_impl.cc +++ b/content/utility/utility_thread_impl.cc
@@ -29,17 +29,6 @@ namespace content { -namespace { - -template<typename SRC, typename DEST> -void ConvertVector(const SRC& src, DEST* dest) { - dest->reserve(src.size()); - for (typename SRC::const_iterator i = src.begin(); i != src.end(); ++i) - dest->push_back(typename DEST::value_type(*i)); -} - -} // namespace - UtilityThreadImpl::UtilityThreadImpl() : ChildThreadImpl(ChildThreadImpl::Options::Builder().Build()) { Init();
diff --git a/device/bluetooth/bluetooth_low_energy_device_mac.h b/device/bluetooth/bluetooth_low_energy_device_mac.h index 0b1aafd..e2823d1 100644 --- a/device/bluetooth/bluetooth_low_energy_device_mac.h +++ b/device/bluetooth/bluetooth_low_energy_device_mac.h
@@ -28,6 +28,7 @@ class BluetoothAdapterMac; class BluetoothRemoteGattServiceMac; +class BluetoothRemoteGattDescriptorMac; class DEVICE_BLUETOOTH_EXPORT BluetoothLowEnergyDeviceMac : public BluetoothDeviceMac { @@ -90,6 +91,8 @@ void DidUpdateNotificationState(CBCharacteristic* characteristic, NSError* error); void DidDiscoverDescriptors(CBCharacteristic* characteristic, NSError* error); + void DidUpdateValueForDescriptor(CBDescriptor* cb_descriptor, NSError* error); + void DidWriteValueForDescriptor(CBDescriptor* descriptor, NSError* error); static std::string GetPeripheralIdentifier(CBPeripheral* peripheral); @@ -123,6 +126,10 @@ BluetoothRemoteGattServiceMac* GetBluetoothRemoteGattService( CBService* service) const; + // Returns BluetoothRemoteGattDescriptorMac based on the CBDescriptor. + BluetoothRemoteGattDescriptorMac* GetBluetoothRemoteGattDescriptor( + CBDescriptor* cb_descriptor) const; + // Callback used when the CoreBluetooth Peripheral is disconnected. void DidDisconnectPeripheral(NSError* error);
diff --git a/device/bluetooth/bluetooth_low_energy_device_mac.mm b/device/bluetooth/bluetooth_low_energy_device_mac.mm index b5777be..20694e4 100644 --- a/device/bluetooth/bluetooth_low_energy_device_mac.mm +++ b/device/bluetooth/bluetooth_low_energy_device_mac.mm
@@ -16,6 +16,8 @@ #include "device/bluetooth/bluetooth_adapter_mac.h" #include "device/bluetooth/bluetooth_device.h" #include "device/bluetooth/bluetooth_low_energy_peripheral_delegate.h" +#include "device/bluetooth/bluetooth_remote_gatt_characteristic_mac.h" +#include "device/bluetooth/bluetooth_remote_gatt_descriptor_mac.h" #include "device/bluetooth/bluetooth_remote_gatt_service_mac.h" using device::BluetoothDevice; @@ -332,6 +334,24 @@ SendNotificationIfDiscoveryComplete(); } +void BluetoothLowEnergyDeviceMac::DidUpdateValueForDescriptor( + CBDescriptor* cb_descriptor, + NSError* error) { + BluetoothRemoteGattDescriptorMac* gatt_descriptor = + GetBluetoothRemoteGattDescriptor(cb_descriptor); + DCHECK(gatt_descriptor); + gatt_descriptor->DidUpdateValueForDescriptor(error); +} + +void BluetoothLowEnergyDeviceMac::DidWriteValueForDescriptor( + CBDescriptor* cb_descriptor, + NSError* error) { + BluetoothRemoteGattDescriptorMac* gatt_descriptor = + GetBluetoothRemoteGattDescriptor(cb_descriptor); + DCHECK(gatt_descriptor); + gatt_descriptor->DidWriteValueForDescriptor(error); +} + // static std::string BluetoothLowEnergyDeviceMac::GetPeripheralIdentifier( CBPeripheral* peripheral) { @@ -400,6 +420,20 @@ return nullptr; } +device::BluetoothRemoteGattDescriptorMac* +BluetoothLowEnergyDeviceMac::GetBluetoothRemoteGattDescriptor( + CBDescriptor* cb_descriptor) const { + CBCharacteristic* cb_characteristic = cb_descriptor.characteristic; + device::BluetoothRemoteGattServiceMac* gatt_service = + GetBluetoothRemoteGattService(cb_characteristic.service); + DCHECK(gatt_service); + device::BluetoothRemoteGattCharacteristicMac* gatt_characteristic = + gatt_service->GetBluetoothRemoteGattCharacteristicMac(cb_characteristic); + DCHECK(gatt_characteristic); + return gatt_characteristic->GetBluetoothRemoteGattDescriptorMac( + cb_descriptor); +} + void BluetoothLowEnergyDeviceMac::DidDisconnectPeripheral(NSError* error) { VLOG(1) << *this << ": Disconnected from peripheral."; if (error) {
diff --git a/device/bluetooth/bluetooth_low_energy_peripheral_delegate.mm b/device/bluetooth/bluetooth_low_energy_peripheral_delegate.mm index 4f8a1b85..e0287fff 100644 --- a/device/bluetooth/bluetooth_low_energy_peripheral_delegate.mm +++ b/device/bluetooth/bluetooth_low_energy_peripheral_delegate.mm
@@ -49,6 +49,14 @@ device_mac_->DidDiscoverDescriptors(characteristic, error); } + void DidUpdateValueForDescriptor(CBDescriptor* descriptor, NSError* error) { + device_mac_->DidUpdateValueForDescriptor(descriptor, error); + } + + void DidWriteValueForDescriptor(CBDescriptor* descriptor, NSError* error) { + device_mac_->DidWriteValueForDescriptor(descriptor, error); + } + CBPeripheral* GetPeripheral() { return device_mac_->GetPeripheral(); } private: @@ -113,4 +121,16 @@ bridge_->DidDiscoverDescriptors(characteristic, error); } +- (void)peripheral:(CBPeripheral*)peripheral + didUpdateValueForDescriptor:(CBDescriptor*)descriptor + error:(nullable NSError*)error { + bridge_->DidUpdateValueForDescriptor(descriptor, error); +} + +- (void)peripheral:(CBPeripheral*)peripheral + didWriteValueForDescriptor:(CBDescriptor*)descriptor + error:(nullable NSError*)error { + bridge_->DidWriteValueForDescriptor(descriptor, error); +} + @end
diff --git a/device/bluetooth/bluetooth_remote_gatt_characteristic_mac.h b/device/bluetooth/bluetooth_remote_gatt_characteristic_mac.h index 229daff6..384c2658 100644 --- a/device/bluetooth/bluetooth_remote_gatt_characteristic_mac.h +++ b/device/bluetooth/bluetooth_remote_gatt_characteristic_mac.h
@@ -7,18 +7,12 @@ #include "device/bluetooth/bluetooth_remote_gatt_characteristic.h" +#import <CoreBluetooth/CoreBluetooth.h> #include <unordered_map> #include "base/mac/scoped_nsobject.h" #include "base/memory/weak_ptr.h" -#if defined(__OBJC__) -#import <CoreBluetooth/CoreBluetooth.h> -#else -@class CBCharacteristic; -typedef NS_ENUM(NSInteger, CBCharacteristicWriteType); -#endif // defined(__OBJC__) - namespace device { class BluetoothAdapterMac; @@ -66,6 +60,7 @@ const ErrorCallback& error_callback) override; private: + friend class BluetoothLowEnergyDeviceMac; friend class BluetoothRemoteGattDescriptorMac; friend class BluetoothRemoteGattServiceMac; friend class BluetoothTestMac;
diff --git a/device/bluetooth/bluetooth_remote_gatt_descriptor_mac.h b/device/bluetooth/bluetooth_remote_gatt_descriptor_mac.h index 60d4062..e7c10354 100644 --- a/device/bluetooth/bluetooth_remote_gatt_descriptor_mac.h +++ b/device/bluetooth/bluetooth_remote_gatt_descriptor_mac.h
@@ -44,8 +44,19 @@ const ErrorCallback& error_callback) override; private: + friend class BluetoothLowEnergyDeviceMac; friend class BluetoothRemoteGattCharacteristicMac; + friend class BluetoothTestMac; + // Calls callbacks, when -[id<CBPeripheralDelegate> + // peripheral:didUpdateValueForDescriptor:error:] is called. + void DidUpdateValueForDescriptor(NSError* error); + // Calls callbacks, when -[id<CBPeripheralDelegate> + // peripheral:didWriteValueForDescriptor:error:] is called. + void DidWriteValueForDescriptor(NSError* error); + + // Returns CoreBluetooth peripheral. + CBPeripheral* GetCBPeripheral() const; // Returns CoreBluetooth descriptor. CBDescriptor* GetCBDescriptor() const; // gatt_characteristic_ owns instances of this class. @@ -58,6 +69,12 @@ BluetoothUUID uuid_; // Descriptor value. std::vector<uint8_t> value_; + // True if a gatt read or write request is in progress. + bool value_read_or_write_in_progress_; + // ReadRemoteDescriptor request callbacks. + std::pair<ValueCallback, ErrorCallback> read_value_callbacks_; + // WriteRemoteDescriptor request callbacks. + std::pair<base::Closure, ErrorCallback> write_value_callbacks_; }; // Stream operator for logging.
diff --git a/device/bluetooth/bluetooth_remote_gatt_descriptor_mac.mm b/device/bluetooth/bluetooth_remote_gatt_descriptor_mac.mm index 76cda0c..d7c5d6c7 100644 --- a/device/bluetooth/bluetooth_remote_gatt_descriptor_mac.mm +++ b/device/bluetooth/bluetooth_remote_gatt_descriptor_mac.mm
@@ -4,19 +4,51 @@ #include "device/bluetooth/bluetooth_remote_gatt_descriptor_mac.h" +#include "base/bind.h" +#import "base/mac/foundation_util.h" #include "base/strings/sys_string_conversions.h" -#include "device/bluetooth/bluetooth_adapter_mac.h" -#include "device/bluetooth/bluetooth_remote_gatt_characteristic_mac.h" +#include "base/threading/thread_task_runner_handle.h" +#import "device/bluetooth/bluetooth_adapter_mac.h" +#import "device/bluetooth/bluetooth_remote_gatt_characteristic_mac.h" + +using base::mac::ObjCCast; namespace device { +std::vector<uint8_t> VectorValueFromObjC(id objc_value) { + // According to + // https://developer.apple.com/reference/corebluetooth/cbdescriptor some + // descriptor values can be NSData, NSString or NSNumber. + std::vector<uint8_t> value; + NSData* data = ObjCCast<NSData>(objc_value); + NSString* as_string = ObjCCast<NSString>(objc_value); + NSNumber* as_number = ObjCCast<NSNumber>(objc_value); + + if (!data && !as_string && as_number) { + unsigned short descriptor = [as_number shortValue]; + data = [NSData dataWithBytes:&descriptor length:sizeof(descriptor)]; + } + + if (!data && as_string) + data = [as_string dataUsingEncoding:NSUTF8StringEncoding]; + + if (data) { + value.resize([data length]); + [data getBytes:value.data() length:value.size()]; + } else { + LOG(WARNING) << "Unexpected value: " + << base::SysNSStringToUTF8([objc_value description]); + } + return value; +} + BluetoothRemoteGattDescriptorMac::BluetoothRemoteGattDescriptorMac( BluetoothRemoteGattCharacteristicMac* characteristic, CBDescriptor* descriptor) : gatt_characteristic_(characteristic), - cb_descriptor_(descriptor, base::scoped_policy::RETAIN) { - uuid_ = - BluetoothAdapterMac::BluetoothUUIDWithCBUUID([cb_descriptor_.get() UUID]); + cb_descriptor_(descriptor, base::scoped_policy::RETAIN), + value_read_or_write_in_progress_(false) { + uuid_ = BluetoothAdapterMac::BluetoothUUIDWithCBUUID([cb_descriptor_ UUID]); identifier_ = base::SysNSStringToUTF8( [NSString stringWithFormat:@"%s-%p", uuid_.canonical_value().c_str(), (void*)cb_descriptor_]); @@ -40,10 +72,19 @@ return value_; } -BluetoothRemoteGattDescriptorMac::~BluetoothRemoteGattDescriptorMac() {} +BluetoothRemoteGattDescriptorMac::~BluetoothRemoteGattDescriptorMac() { + if (!read_value_callbacks_.first.is_null()) { + std::pair<ValueCallback, ErrorCallback> callbacks; + callbacks.swap(read_value_callbacks_); + callbacks.second.Run(BluetoothGattService::GATT_ERROR_FAILED); + } + if (!write_value_callbacks_.first.is_null()) { + std::pair<base::Closure, ErrorCallback> callbacks; + callbacks.swap(write_value_callbacks_); + callbacks.second.Run(BluetoothGattService::GATT_ERROR_FAILED); + } +} -// Returns a pointer to the GATT characteristic that this characteristic -// descriptor belongs to. BluetoothRemoteGattCharacteristic* BluetoothRemoteGattDescriptorMac::GetCharacteristic() const { return static_cast<BluetoothRemoteGattCharacteristic*>(gatt_characteristic_); @@ -55,23 +96,91 @@ void BluetoothRemoteGattDescriptorMac::ReadRemoteDescriptor( const ValueCallback& callback, const ErrorCallback& error_callback) { - NOTIMPLEMENTED(); + if (value_read_or_write_in_progress_) { + VLOG(1) << *this << ": Read failed, already in progress."; + base::ThreadTaskRunnerHandle::Get()->PostTask( + FROM_HERE, + base::Bind(error_callback, + BluetoothRemoteGattService::GATT_ERROR_IN_PROGRESS)); + return; + } + VLOG(1) << *this << ": Read value."; + value_read_or_write_in_progress_ = true; + read_value_callbacks_ = std::make_pair(callback, error_callback); + [GetCBPeripheral() readValueForDescriptor:cb_descriptor_]; } -// Sends a write request to a remote characteristic descriptor, to modify the -// value of the descriptor with the new value |new_value|. |callback| is -// called to signal success and |error_callback| for failures. This method -// only applies to remote descriptors and will fail for those that are locally -// hosted. void BluetoothRemoteGattDescriptorMac::WriteRemoteDescriptor( - const std::vector<uint8_t>& new_value, + const std::vector<uint8_t>& value, const base::Closure& callback, const ErrorCallback& error_callback) { - NOTIMPLEMENTED(); + if (value_read_or_write_in_progress_) { + VLOG(1) << *this << ": Write failed, already in progress."; + base::ThreadTaskRunnerHandle::Get()->PostTask( + FROM_HERE, + base::Bind(error_callback, + BluetoothRemoteGattService::GATT_ERROR_IN_PROGRESS)); + return; + } + VLOG(1) << *this << ": Write value."; + value_read_or_write_in_progress_ = true; + write_value_callbacks_ = std::make_pair(callback, error_callback); + base::scoped_nsobject<NSData> nsdata_value( + [[NSData alloc] initWithBytes:value.data() length:value.size()]); + [GetCBPeripheral() writeValue:nsdata_value forDescriptor:GetCBDescriptor()]; +} + +void BluetoothRemoteGattDescriptorMac::DidUpdateValueForDescriptor( + NSError* error) { + if (!value_read_or_write_in_progress_) { + VLOG(1) << *this << ": Value updated, no read in progress."; + return; + } + std::pair<ValueCallback, ErrorCallback> callbacks; + callbacks.swap(read_value_callbacks_); + value_read_or_write_in_progress_ = false; + if (error) { + BluetoothGattService::GattErrorCode error_code = + BluetoothDeviceMac::GetGattErrorCodeFromNSError(error); + VLOG(1) << *this << ": Read value failed with error: " + << BluetoothAdapterMac::String(error) + << ", converted to error code: " << error_code; + callbacks.second.Run(error_code); + return; + } + VLOG(1) << *this << ": Value read."; + value_ = VectorValueFromObjC([cb_descriptor_ value]); + callbacks.first.Run(value_); +} + +void BluetoothRemoteGattDescriptorMac::DidWriteValueForDescriptor( + NSError* error) { + if (!value_read_or_write_in_progress_) { + VLOG(1) << *this << ": Value written, no write in progress."; + return; + } + std::pair<base::Closure, ErrorCallback> callbacks; + callbacks.swap(write_value_callbacks_); + value_read_or_write_in_progress_ = false; + if (error) { + BluetoothGattService::GattErrorCode error_code = + BluetoothDeviceMac::GetGattErrorCodeFromNSError(error); + VLOG(1) << *this << ": Write value failed with error: " + << BluetoothAdapterMac::String(error) + << ", converted to error code: " << error_code; + callbacks.second.Run(error_code); + return; + } + VLOG(1) << *this << ": Value written."; + callbacks.first.Run(); +} + +CBPeripheral* BluetoothRemoteGattDescriptorMac::GetCBPeripheral() const { + return gatt_characteristic_->GetCBPeripheral(); } CBDescriptor* BluetoothRemoteGattDescriptorMac::GetCBDescriptor() const { - return cb_descriptor_.get(); + return cb_descriptor_; } DEVICE_BLUETOOTH_EXPORT std::ostream& operator<<(
diff --git a/device/bluetooth/bluetooth_remote_gatt_descriptor_unittest.cc b/device/bluetooth/bluetooth_remote_gatt_descriptor_unittest.cc index 3b886bb..a43c0e7 100644 --- a/device/bluetooth/bluetooth_remote_gatt_descriptor_unittest.cc +++ b/device/bluetooth/bluetooth_remote_gatt_descriptor_unittest.cc
@@ -184,9 +184,13 @@ } #endif // defined(OS_ANDROID) || defined(OS_MACOSX) -#if defined(OS_ANDROID) +#if defined(OS_ANDROID) || defined(OS_MACOSX) // Tests ReadRemoteDescriptor and GetValue with empty value buffer. TEST_F(BluetoothRemoteGattDescriptorTest, ReadRemoteDescriptor_Empty) { + if (!PlatformSupportsLowEnergy()) { + LOG(WARNING) << "Low Energy Bluetooth unavailable, skipping unit test."; + return; + } ASSERT_NO_FATAL_FAILURE(FakeDescriptorBoilerplate()); descriptor1_->ReadRemoteDescriptor(GetReadValueCallback(Call::EXPECTED), @@ -203,11 +207,15 @@ EXPECT_EQ(empty_vector, last_read_value_); EXPECT_EQ(empty_vector, descriptor1_->GetValue()); } -#endif // defined(OS_ANDROID) +#endif // defined(OS_ANDROID) || defined(OS_MACOSX) -#if defined(OS_ANDROID) +#if defined(OS_ANDROID) || defined(OS_MACOSX) // Tests WriteRemoteDescriptor with empty value buffer. TEST_F(BluetoothRemoteGattDescriptorTest, WriteRemoteDescriptor_Empty) { + if (!PlatformSupportsLowEnergy()) { + LOG(WARNING) << "Low Energy Bluetooth unavailable, skipping unit test."; + return; + } ASSERT_NO_FATAL_FAILURE(FakeDescriptorBoilerplate()); std::vector<uint8_t> empty_vector; @@ -223,11 +231,17 @@ EXPECT_EQ(empty_vector, last_write_value_); } -#endif // defined(OS_ANDROID) +#endif // defined(OS_ANDROID) || defined(OS_MACOSX) #if defined(OS_ANDROID) // Tests ReadRemoteDescriptor completing after Chrome objects are deleted. +// macOS: Not applicable: This can never happen if CBPeripheral delegate is set +// to nil. TEST_F(BluetoothRemoteGattDescriptorTest, ReadRemoteDescriptor_AfterDeleted) { + if (!PlatformSupportsLowEnergy()) { + LOG(WARNING) << "Low Energy Bluetooth unavailable, skipping unit test."; + return; + } ASSERT_NO_FATAL_FAILURE(FakeDescriptorBoilerplate()); descriptor1_->ReadRemoteDescriptor(GetReadValueCallback(Call::NOT_EXPECTED), @@ -246,7 +260,13 @@ #if defined(OS_ANDROID) // Tests WriteRemoteDescriptor completing after Chrome objects are deleted. +// macOS: Not applicable: This can never happen if CBPeripheral delegate is set +// to nil. TEST_F(BluetoothRemoteGattDescriptorTest, WriteRemoteDescriptor_AfterDeleted) { + if (!PlatformSupportsLowEnergy()) { + LOG(WARNING) << "Low Energy Bluetooth unavailable, skipping unit test."; + return; + } ASSERT_NO_FATAL_FAILURE(FakeDescriptorBoilerplate()); std::vector<uint8_t> empty_vector; @@ -263,9 +283,13 @@ } #endif // defined(OS_ANDROID) -#if defined(OS_ANDROID) +#if defined(OS_ANDROID) || defined(OS_MACOSX) // Tests ReadRemoteDescriptor and GetValue with non-empty value buffer. TEST_F(BluetoothRemoteGattDescriptorTest, ReadRemoteDescriptor) { + if (!PlatformSupportsLowEnergy()) { + LOG(WARNING) << "Low Energy Bluetooth unavailable, skipping unit test."; + return; + } ASSERT_NO_FATAL_FAILURE(FakeDescriptorBoilerplate()); descriptor1_->ReadRemoteDescriptor(GetReadValueCallback(Call::EXPECTED), @@ -285,11 +309,15 @@ EXPECT_EQ(test_vector, last_read_value_); EXPECT_EQ(test_vector, descriptor1_->GetValue()); } -#endif // defined(OS_ANDROID) +#endif // defined(OS_ANDROID) || defined(OS_MACOSX) -#if defined(OS_ANDROID) +#if defined(OS_ANDROID) || defined(OS_MACOSX) // Tests WriteRemoteDescriptor with non-empty value buffer. TEST_F(BluetoothRemoteGattDescriptorTest, WriteRemoteDescriptor) { + if (!PlatformSupportsLowEnergy()) { + LOG(WARNING) << "Low Energy Bluetooth unavailable, skipping unit test."; + return; + } ASSERT_NO_FATAL_FAILURE(FakeDescriptorBoilerplate()); uint8_t values[] = {0, 1, 2, 3, 4, 0xf, 0xf0, 0xff}; @@ -303,11 +331,15 @@ EXPECT_EQ(test_vector, last_write_value_); } -#endif // defined(OS_ANDROID) +#endif // defined(OS_ANDROID) || defined(OS_MACOSX) -#if defined(OS_ANDROID) +#if defined(OS_ANDROID) || defined(OS_MACOSX) // Tests ReadRemoteDescriptor and GetValue multiple times. TEST_F(BluetoothRemoteGattDescriptorTest, ReadRemoteDescriptor_Twice) { + if (!PlatformSupportsLowEnergy()) { + LOG(WARNING) << "Low Energy Bluetooth unavailable, skipping unit test."; + return; + } ASSERT_NO_FATAL_FAILURE(FakeDescriptorBoilerplate()); descriptor1_->ReadRemoteDescriptor(GetReadValueCallback(Call::EXPECTED), @@ -336,11 +368,15 @@ EXPECT_EQ(empty_vector, last_read_value_); EXPECT_EQ(empty_vector, descriptor1_->GetValue()); } -#endif // defined(OS_ANDROID) +#endif // defined(OS_ANDROID) || defined(OS_MACOSX) -#if defined(OS_ANDROID) +#if defined(OS_ANDROID) || defined(OS_MACOSX) // Tests WriteRemoteDescriptor multiple times. TEST_F(BluetoothRemoteGattDescriptorTest, WriteRemoteDescriptor_Twice) { + if (!PlatformSupportsLowEnergy()) { + LOG(WARNING) << "Low Energy Bluetooth unavailable, skipping unit test."; + return; + } ASSERT_NO_FATAL_FAILURE(FakeDescriptorBoilerplate()); uint8_t values[] = {0, 1, 2, 3, 4, 0xf, 0xf0, 0xff}; @@ -367,12 +403,16 @@ EXPECT_EQ(0, error_callback_count_); EXPECT_EQ(empty_vector, last_write_value_); } -#endif // defined(OS_ANDROID) +#endif // defined(OS_ANDROID) || defined(OS_MACOSX) -#if defined(OS_ANDROID) +#if defined(OS_ANDROID) || defined(OS_MACOSX) // Tests ReadRemoteDescriptor on two descriptors. TEST_F(BluetoothRemoteGattDescriptorTest, ReadRemoteDescriptor_MultipleDescriptors) { + if (!PlatformSupportsLowEnergy()) { + LOG(WARNING) << "Low Energy Bluetooth unavailable, skipping unit test."; + return; + } ASSERT_NO_FATAL_FAILURE(FakeDescriptorBoilerplate()); descriptor1_->ReadRemoteDescriptor(GetReadValueCallback(Call::EXPECTED), @@ -400,12 +440,16 @@ EXPECT_EQ(test_vector1, descriptor1_->GetValue()); EXPECT_EQ(test_vector2, descriptor2_->GetValue()); } -#endif // defined(OS_ANDROID) +#endif // defined(OS_ANDROID) || defined(OS_MACOSX) -#if defined(OS_ANDROID) +#if defined(OS_ANDROID) || defined(OS_MACOSX) // Tests WriteRemoteDescriptor on two descriptors. TEST_F(BluetoothRemoteGattDescriptorTest, WriteRemoteDescriptor_MultipleDescriptors) { + if (!PlatformSupportsLowEnergy()) { + LOG(WARNING) << "Low Energy Bluetooth unavailable, skipping unit test."; + return; + } ASSERT_NO_FATAL_FAILURE(FakeDescriptorBoilerplate()); std::vector<uint8_t> test_vector1; @@ -431,11 +475,15 @@ EXPECT_EQ(2, callback_count_); EXPECT_EQ(0, error_callback_count_); } -#endif // defined(OS_ANDROID) +#endif // defined(OS_ANDROID) || defined(OS_MACOSX) -#if defined(OS_ANDROID) +#if defined(OS_ANDROID) || defined(OS_MACOSX) // Tests ReadRemoteDescriptor asynchronous error. TEST_F(BluetoothRemoteGattDescriptorTest, ReadError) { + if (!PlatformSupportsLowEnergy()) { + LOG(WARNING) << "Low Energy Bluetooth unavailable, skipping unit test."; + return; + } ASSERT_NO_FATAL_FAILURE(FakeDescriptorBoilerplate()); descriptor1_->ReadRemoteDescriptor(GetReadValueCallback(Call::NOT_EXPECTED), @@ -448,11 +496,15 @@ EXPECT_EQ(BluetoothRemoteGattService::GATT_ERROR_INVALID_LENGTH, last_gatt_error_code_); } -#endif // defined(OS_ANDROID) +#endif // defined(OS_ANDROID) || defined(OS_MACOSX) -#if defined(OS_ANDROID) +#if defined(OS_ANDROID) || defined(OS_MACOSX) // Tests WriteRemoteDescriptor asynchronous error. TEST_F(BluetoothRemoteGattDescriptorTest, WriteError) { + if (!PlatformSupportsLowEnergy()) { + LOG(WARNING) << "Low Energy Bluetooth unavailable, skipping unit test."; + return; + } ASSERT_NO_FATAL_FAILURE(FakeDescriptorBoilerplate()); std::vector<uint8_t> empty_vector; @@ -468,11 +520,17 @@ EXPECT_EQ(BluetoothRemoteGattService::GATT_ERROR_INVALID_LENGTH, last_gatt_error_code_); } -#endif // defined(OS_ANDROID) +#endif // defined(OS_ANDROID) || defined(OS_MACOSX) #if defined(OS_ANDROID) // Tests ReadRemoteDescriptor synchronous error. +// Test not relevant for macOS since descriptor read cannot generate +// synchronous error. TEST_F(BluetoothRemoteGattDescriptorTest, ReadSynchronousError) { + if (!PlatformSupportsLowEnergy()) { + LOG(WARNING) << "Low Energy Bluetooth unavailable, skipping unit test."; + return; + } ASSERT_NO_FATAL_FAILURE(FakeDescriptorBoilerplate()); SimulateGattDescriptorReadWillFailSynchronouslyOnce(descriptor1_); @@ -500,7 +558,13 @@ #if defined(OS_ANDROID) // Tests WriteRemoteDescriptor synchronous error. +// Test not relevant for macOS since descriptor write cannot generate +// synchronous error. TEST_F(BluetoothRemoteGattDescriptorTest, WriteSynchronousError) { + if (!PlatformSupportsLowEnergy()) { + LOG(WARNING) << "Low Energy Bluetooth unavailable, skipping unit test."; + return; + } ASSERT_NO_FATAL_FAILURE(FakeDescriptorBoilerplate()); SimulateGattDescriptorWriteWillFailSynchronouslyOnce(descriptor1_); @@ -527,9 +591,13 @@ } #endif // defined(OS_ANDROID) -#if defined(OS_ANDROID) +#if defined(OS_ANDROID) || defined(OS_MACOSX) // Tests ReadRemoteDescriptor error with a pending read operation. TEST_F(BluetoothRemoteGattDescriptorTest, ReadRemoteDescriptor_ReadPending) { + if (!PlatformSupportsLowEnergy()) { + LOG(WARNING) << "Low Energy Bluetooth unavailable, skipping unit test."; + return; + } ASSERT_NO_FATAL_FAILURE(FakeDescriptorBoilerplate()); descriptor1_->ReadRemoteDescriptor(GetReadValueCallback(Call::EXPECTED), @@ -552,11 +620,15 @@ EXPECT_EQ(1, callback_count_); EXPECT_EQ(0, error_callback_count_); } -#endif // defined(OS_ANDROID) +#endif // defined(OS_ANDROID) || defined(OS_MACOSX) -#if defined(OS_ANDROID) +#if defined(OS_ANDROID) || defined(OS_MACOSX) // Tests WriteRemoteDescriptor error with a pending write operation. TEST_F(BluetoothRemoteGattDescriptorTest, WriteRemoteDescriptor_WritePending) { + if (!PlatformSupportsLowEnergy()) { + LOG(WARNING) << "Low Energy Bluetooth unavailable, skipping unit test."; + return; + } ASSERT_NO_FATAL_FAILURE(FakeDescriptorBoilerplate()); std::vector<uint8_t> empty_vector; @@ -580,11 +652,15 @@ EXPECT_EQ(1, callback_count_); EXPECT_EQ(0, error_callback_count_); } -#endif // defined(OS_ANDROID) +#endif // defined(OS_ANDROID) || defined(OS_MACOSX) -#if defined(OS_ANDROID) +#if defined(OS_ANDROID) || defined(OS_MACOSX) // Tests ReadRemoteDescriptor error with a pending write operation. TEST_F(BluetoothRemoteGattDescriptorTest, ReadRemoteDescriptor_WritePending) { + if (!PlatformSupportsLowEnergy()) { + LOG(WARNING) << "Low Energy Bluetooth unavailable, skipping unit test."; + return; + } ASSERT_NO_FATAL_FAILURE(FakeDescriptorBoilerplate()); std::vector<uint8_t> empty_vector; @@ -607,11 +683,15 @@ EXPECT_EQ(1, callback_count_); EXPECT_EQ(0, error_callback_count_); } -#endif // defined(OS_ANDROID) +#endif // defined(OS_ANDROID) || defined(OS_MACOSX) -#if defined(OS_ANDROID) +#if defined(OS_ANDROID) || defined(OS_MACOSX) // Tests WriteRemoteDescriptor error with a pending Read operation. TEST_F(BluetoothRemoteGattDescriptorTest, WriteRemoteDescriptor_ReadPending) { + if (!PlatformSupportsLowEnergy()) { + LOG(WARNING) << "Low Energy Bluetooth unavailable, skipping unit test."; + return; + } ASSERT_NO_FATAL_FAILURE(FakeDescriptorBoilerplate()); std::vector<uint8_t> empty_vector; @@ -634,7 +714,7 @@ EXPECT_EQ(1, callback_count_); EXPECT_EQ(0, error_callback_count_); } -#endif // defined(OS_ANDROID) +#endif // defined(OS_ANDROID) || defined(OS_MACOSX) #if defined(OS_ANDROID) // Tests that read requests after a device disconnects but before the @@ -685,4 +765,51 @@ } #endif // defined(OS_ANDROID) +#if defined(OS_MACOSX) +// Tests NSString for descriptor value for macOS. +// https://developer.apple.com/reference/corebluetooth/cbdescriptor +TEST_F(BluetoothRemoteGattDescriptorTest, ReadRemoteDescriptor_NSString) { + if (!PlatformSupportsLowEnergy()) { + LOG(WARNING) << "Low Energy Bluetooth unavailable, skipping unit test."; + return; + } + ASSERT_NO_FATAL_FAILURE(FakeDescriptorBoilerplate()); + + descriptor1_->ReadRemoteDescriptor(GetReadValueCallback(Call::EXPECTED), + GetGattErrorCallback(Call::NOT_EXPECTED)); + EXPECT_EQ(1, gatt_read_descriptor_attempts_); + + std::string test_string = "Hello"; + SimulateGattDescriptorReadNSString(descriptor1_, test_string); + base::RunLoop().RunUntilIdle(); + + std::vector<uint8_t> test_vector(test_string.begin(), test_string.end()); + EXPECT_EQ(test_vector, last_read_value_); + EXPECT_EQ(test_vector, descriptor1_->GetValue()); +} + +// Tests NSNumber for descriptor value for macOS. +// https://developer.apple.com/reference/corebluetooth/cbdescriptor +TEST_F(BluetoothRemoteGattDescriptorTest, ReadRemoteDescriptor_NSNumber) { + if (!PlatformSupportsLowEnergy()) { + LOG(WARNING) << "Low Energy Bluetooth unavailable, skipping unit test."; + return; + } + ASSERT_NO_FATAL_FAILURE(FakeDescriptorBoilerplate()); + + descriptor1_->ReadRemoteDescriptor(GetReadValueCallback(Call::EXPECTED), + GetGattErrorCallback(Call::NOT_EXPECTED)); + EXPECT_EQ(1, gatt_read_descriptor_attempts_); + + const short test_number = 0x1234; + SimulateGattDescriptorReadNSNumber(descriptor1_, test_number); + base::RunLoop().RunUntilIdle(); + + uint8_t values[] = {0x34, 0x12}; + std::vector<uint8_t> test_vector(values, values + arraysize(values)); + EXPECT_EQ(test_vector, last_read_value_); + EXPECT_EQ(test_vector, descriptor1_->GetValue()); +} +#endif // defined(OS_MACOSX) + } // namespace device
diff --git a/device/bluetooth/test/bluetooth_test_mac.h b/device/bluetooth/test/bluetooth_test_mac.h index 46e168a..5eb00426 100644 --- a/device/bluetooth/test/bluetooth_test_mac.h +++ b/device/bluetooth/test/bluetooth_test_mac.h
@@ -11,9 +11,11 @@ #include "device/bluetooth/test/bluetooth_test.h" #if __OBJC__ +@class MockCBDescriptor; @class MockCBCharacteristic; @class MockCBPeripheral; #else // __OBJC__ +class MockCBDescriptor; class MockCBCharacteristic; class MockCBPeripheral; #endif // __OBJC__ @@ -85,6 +87,16 @@ void SimulateGattCharacteristicRemoved( BluetoothRemoteGattService* service, BluetoothRemoteGattCharacteristic* characteristic) override; + void SimulateGattDescriptorRead(BluetoothRemoteGattDescriptor* descriptor, + const std::vector<uint8_t>& value) override; + void SimulateGattDescriptorReadError( + BluetoothRemoteGattDescriptor* descriptor, + BluetoothRemoteGattService::GattErrorCode error_code) override; + void SimulateGattDescriptorWrite( + BluetoothRemoteGattDescriptor* descriptor) override; + void SimulateGattDescriptorWriteError( + BluetoothRemoteGattDescriptor* descriptor, + BluetoothRemoteGattService::GattErrorCode error_code) override; void ExpectedChangeNotifyValueAttempts(int attempts) override; void ExpectedNotifyValue(NotifyValueState expected_value_state) override; @@ -93,6 +105,21 @@ // set of attributes. void SimulateDidDiscoverServices(BluetoothDevice* device, const std::vector<std::string>& uuids); + // CoreBluetooth can return NSData when reading remote gatt descriptors. + // This methods simulate receiving NSData from CoreBluetooth. + void SimulateGattDescriptorReadNSData( + BluetoothRemoteGattDescriptor* descriptor, + const std::vector<uint8_t>& value); + // CoreBluetooth can return NSString when reading remote gatt descriptors. + // This methods simulate receiving NSString from CoreBluetooth. + void SimulateGattDescriptorReadNSString( + BluetoothRemoteGattDescriptor* descriptor, + const std::string& value); + // CoreBluetooth can return NSString when reading remote gatt descriptors. + // This methods simulate receiving NSString from CoreBluetooth. + void SimulateGattDescriptorReadNSNumber( + BluetoothRemoteGattDescriptor* descriptor, + short value); // Callback for the bluetooth central manager mock. void OnFakeBluetoothDeviceConnectGattCalled(); @@ -104,6 +131,8 @@ void OnFakeBluetoothCharacteristicReadValue(); void OnFakeBluetoothCharacteristicWriteValue(std::vector<uint8_t> value); void OnFakeBluetoothGattSetCharacteristicNotification(bool notify_value); + void OnFakeBluetoothDescriptorReadValue(); + void OnFakeBluetoothDescriptorWriteValue(std::vector<uint8_t> value); // Returns the service UUIDs used to retrieve connected peripherals. BluetoothDevice::UUIDSet RetrieveConnectedPeripheralServiceUUIDs(); @@ -121,9 +150,15 @@ // Returns MockCBPeripheral from BluetoothRemoteGattCharacteristic. MockCBPeripheral* GetMockCBPeripheral( BluetoothRemoteGattCharacteristic* characteristic) const; + // Returns MockCBPeripheral from BluetoothRemoteGattDescriptor. + MockCBPeripheral* GetMockCBPeripheral( + BluetoothRemoteGattDescriptor* descriptor) const; // Returns MockCBCharacteristic from BluetoothRemoteGattCharacteristic. MockCBCharacteristic* GetCBMockCharacteristic( BluetoothRemoteGattCharacteristic* characteristic) const; + // Returns MockCBDescriptor from BluetoothRemoteGattDescriptor. + MockCBDescriptor* GetCBMockDescriptor( + BluetoothRemoteGattDescriptor* descriptor) const; // Adds services in MockCBPeripheral. void AddServicesToDevice(BluetoothDevice* device, const std::vector<std::string>& uuids);
diff --git a/device/bluetooth/test/bluetooth_test_mac.mm b/device/bluetooth/test/bluetooth_test_mac.mm index 04c61e3..b308802d 100644 --- a/device/bluetooth/test/bluetooth_test_mac.mm +++ b/device/bluetooth/test/bluetooth_test_mac.mm
@@ -13,8 +13,10 @@ #include "device/bluetooth/bluetooth_adapter_mac.h" #include "device/bluetooth/bluetooth_device_mac.h" #include "device/bluetooth/bluetooth_remote_gatt_characteristic_mac.h" +#include "device/bluetooth/bluetooth_remote_gatt_descriptor_mac.h" #include "device/bluetooth/bluetooth_remote_gatt_service_mac.h" #include "device/bluetooth/test/mock_bluetooth_cbcharacteristic_mac.h" +#include "device/bluetooth/test/mock_bluetooth_cbdescriptor_mac.h" #include "device/bluetooth/test/mock_bluetooth_cbperipheral_mac.h" #include "device/bluetooth/test/mock_bluetooth_cbservice_mac.h" #include "device/bluetooth/test/mock_bluetooth_central_manager_mac.h" @@ -446,6 +448,31 @@ [peripheral_mock mockDidDiscoverEvents]; } +void BluetoothTestMac::SimulateGattDescriptorRead( + BluetoothRemoteGattDescriptor* descriptor, + const std::vector<uint8_t>& value) { + SimulateGattDescriptorReadNSData(descriptor, value); +} + +void BluetoothTestMac::SimulateGattDescriptorReadError( + BluetoothRemoteGattDescriptor* descriptor, + BluetoothRemoteGattService::GattErrorCode error_code) { + NSError* error = BluetoothDeviceMac::GetNSErrorFromGattErrorCode(error_code); + [GetCBMockDescriptor(descriptor) simulateReadWithValue:nil error:error]; +} + +void BluetoothTestMac::SimulateGattDescriptorWrite( + BluetoothRemoteGattDescriptor* descriptor) { + [GetCBMockDescriptor(descriptor) simulateWriteWithError:nil]; +} + +void BluetoothTestMac::SimulateGattDescriptorWriteError( + BluetoothRemoteGattDescriptor* descriptor, + BluetoothRemoteGattService::GattErrorCode error_code) { + NSError* error = BluetoothDeviceMac::GetNSErrorFromGattErrorCode(error_code); + [GetCBMockDescriptor(descriptor) simulateWriteWithError:error]; +} + void BluetoothTestMac::ExpectedChangeNotifyValueAttempts(int attempts) { EXPECT_EQ(attempts, gatt_notify_characteristic_attempts_); } @@ -470,6 +497,28 @@ [GetMockCBPeripheral(device) mockDidDiscoverServices]; } +void BluetoothTestMac::SimulateGattDescriptorReadNSData( + BluetoothRemoteGattDescriptor* descriptor, + const std::vector<uint8_t>& value) { + scoped_nsobject<NSData> data( + [[NSData alloc] initWithBytes:value.data() length:value.size()]); + [GetCBMockDescriptor(descriptor) simulateReadWithValue:data error:nil]; +} + +void BluetoothTestMac::SimulateGattDescriptorReadNSString( + BluetoothRemoteGattDescriptor* descriptor, + const std::string& value) { + NSString* string = base::SysUTF8ToNSString(value); + [GetCBMockDescriptor(descriptor) simulateReadWithValue:string error:nil]; +} + +void BluetoothTestMac::SimulateGattDescriptorReadNSNumber( + BluetoothRemoteGattDescriptor* descriptor, + short value) { + NSNumber* number = [NSNumber numberWithShort:value]; + [GetCBMockDescriptor(descriptor) simulateReadWithValue:number error:nil]; +} + void BluetoothTestMac::OnFakeBluetoothDeviceConnectGattCalled() { gatt_connection_attempts_++; } @@ -502,6 +551,16 @@ gatt_notify_characteristic_attempts_++; } +void BluetoothTest::OnFakeBluetoothDescriptorReadValue() { + gatt_read_descriptor_attempts_++; +} + +void BluetoothTest::OnFakeBluetoothDescriptorWriteValue( + std::vector<uint8_t> value) { + last_write_value_ = value; + gatt_write_descriptor_attempts_++; +} + BluetoothDevice::UUIDSet BluetoothTestMac::RetrieveConnectedPeripheralServiceUUIDs() { BluetoothDevice::UUIDSet service_uuids; @@ -540,6 +599,11 @@ return GetMockCBPeripheral(characteristic->GetService()); } +MockCBPeripheral* BluetoothTestMac::GetMockCBPeripheral( + BluetoothRemoteGattDescriptor* descriptor) const { + return GetMockCBPeripheral(descriptor->GetCharacteristic()); +} + MockCBCharacteristic* BluetoothTest::GetCBMockCharacteristic( BluetoothRemoteGattCharacteristic* characteristic) const { device::BluetoothRemoteGattCharacteristicMac* mac_gatt_characteristic = @@ -550,6 +614,14 @@ return ObjCCast<MockCBCharacteristic>(cb_characteristic); } +MockCBDescriptor* BluetoothTest::GetCBMockDescriptor( + BluetoothRemoteGattDescriptor* descriptor) const { + device::BluetoothRemoteGattDescriptorMac* mac_gatt_descriptor = + static_cast<device::BluetoothRemoteGattDescriptorMac*>(descriptor); + CBDescriptor* cb_descriptor = mac_gatt_descriptor->GetCBDescriptor(); + return ObjCCast<MockCBDescriptor>(cb_descriptor); +} + void BluetoothTest::AddServicesToDevice(BluetoothDevice* device, const std::vector<std::string>& uuids) { scoped_nsobject<NSMutableArray> services([[NSMutableArray alloc] init]);
diff --git a/device/bluetooth/test/mock_bluetooth_cbcharacteristic_mac.h b/device/bluetooth/test/mock_bluetooth_cbcharacteristic_mac.h index e3bbabf..825d168 100644 --- a/device/bluetooth/test/mock_bluetooth_cbcharacteristic_mac.h +++ b/device/bluetooth/test/mock_bluetooth_cbcharacteristic_mac.h
@@ -22,7 +22,7 @@ properties:(int)properties; // Methods for faking events. -- (void)simulateReadWithValue:(NSData*)value error:(NSError*)error; +- (void)simulateReadWithValue:(id)value error:(NSError*)error; - (void)simulateWriteWithError:(NSError*)error; - (void)simulateGattNotifySessionStarted; - (void)simulateGattNotifySessionFailedWithError:(NSError*)error;
diff --git a/device/bluetooth/test/mock_bluetooth_cbcharacteristic_mac.mm b/device/bluetooth/test/mock_bluetooth_cbcharacteristic_mac.mm index 2cc9eb7b..1cf1d18 100644 --- a/device/bluetooth/test/mock_bluetooth_cbcharacteristic_mac.mm +++ b/device/bluetooth/test/mock_bluetooth_cbcharacteristic_mac.mm
@@ -96,7 +96,7 @@ CBCharacteristicProperties _cb_properties; scoped_nsobject<NSMutableArray> _simulatedDescriptors; scoped_nsobject<NSArray> _descriptors; - scoped_nsobject<NSData> _value; + scoped_nsobject<NSObject> _value; BOOL _notifying; } @end @@ -134,7 +134,7 @@ return [super isKindOfClass:aClass]; } -- (void)simulateReadWithValue:(NSData*)value error:(NSError*)error { +- (void)simulateReadWithValue:(id)value error:(NSError*)error { _value.reset([value copy]); CBPeripheral* peripheral = _service.peripheral; [peripheral.delegate peripheral:peripheral @@ -220,7 +220,7 @@ return _descriptors; } -- (NSData*)value { +- (id)value { return _value.get(); }
diff --git a/device/bluetooth/test/mock_bluetooth_cbdescriptor_mac.h b/device/bluetooth/test/mock_bluetooth_cbdescriptor_mac.h index 7a0caaa..0a2baed4 100644 --- a/device/bluetooth/test/mock_bluetooth_cbdescriptor_mac.h +++ b/device/bluetooth/test/mock_bluetooth_cbdescriptor_mac.h
@@ -19,6 +19,9 @@ - (instancetype)initWithCharacteristic:(CBCharacteristic*)characteristic CBUUID:(CBUUID*)uuid; +- (void)simulateReadWithValue:(id)value error:(NSError*)error; +- (void)simulateWriteWithError:(NSError*)error; + @end #endif // DEVICE_BLUETOOTH_TEST_MOCK_BLUETOOTH_CBDESCRIPTOR_MAC_H_
diff --git a/device/bluetooth/test/mock_bluetooth_cbdescriptor_mac.mm b/device/bluetooth/test/mock_bluetooth_cbdescriptor_mac.mm index 9c8512b5..3a2f6152 100644 --- a/device/bluetooth/test/mock_bluetooth_cbdescriptor_mac.mm +++ b/device/bluetooth/test/mock_bluetooth_cbdescriptor_mac.mm
@@ -15,6 +15,7 @@ // Owner of this instance. CBCharacteristic* _characteristic; scoped_nsobject<CBUUID> _UUID; + scoped_nsobject<NSData> _value; } @end @@ -50,6 +51,10 @@ return _UUID.get(); } +- (NSData*)value { + return _value.get(); +} + - (CBDescriptor*)descriptor { return ObjCCast<CBDescriptor>(self); } @@ -58,4 +63,19 @@ return _characteristic; } +- (void)simulateReadWithValue:(id)value error:(NSError*)error { + _value.reset([value copy]); + CBPeripheral* peripheral = _characteristic.service.peripheral; + [peripheral.delegate peripheral:peripheral + didUpdateValueForDescriptor:self.descriptor + error:error]; +} + +- (void)simulateWriteWithError:(NSError*)error { + CBPeripheral* peripheral = _characteristic.service.peripheral; + [peripheral.delegate peripheral:peripheral + didWriteValueForDescriptor:self.descriptor + error:error]; +} + @end
diff --git a/device/bluetooth/test/mock_bluetooth_cbperipheral_mac.mm b/device/bluetooth/test/mock_bluetooth_cbperipheral_mac.mm index 637ffee..f0a4a733 100644 --- a/device/bluetooth/test/mock_bluetooth_cbperipheral_mac.mm +++ b/device/bluetooth/test/mock_bluetooth_cbperipheral_mac.mm
@@ -8,6 +8,7 @@ #include "base/mac/scoped_nsobject.h" #include "device/bluetooth/test/bluetooth_test_mac.h" #include "device/bluetooth/test/mock_bluetooth_cbcharacteristic_mac.h" +#include "device/bluetooth/test/mock_bluetooth_cbdescriptor_mac.h" #include "device/bluetooth/test/mock_bluetooth_cbservice_mac.h" using base::mac::ObjCCast; @@ -112,6 +113,18 @@ _bluetoothTestMac->OnFakeBluetoothCharacteristicWriteValue(value); } +- (void)readValueForDescriptor:(CBDescriptor*)descriptor { + DCHECK(_bluetoothTestMac); + _bluetoothTestMac->OnFakeBluetoothDescriptorReadValue(); +} + +- (void)writeValue:(NSData*)data forDescriptor:(CBDescriptor*)descriptor { + DCHECK(_bluetoothTestMac); + const uint8_t* buffer = static_cast<const uint8_t*>(data.bytes); + std::vector<uint8_t> value(buffer, buffer + data.length); + _bluetoothTestMac->OnFakeBluetoothDescriptorWriteValue(value); +} + - (void)removeAllServices { [_services.get() removeAllObjects]; }
diff --git a/device/geolocation/location_api_adapter_android.cc b/device/geolocation/location_api_adapter_android.cc index 166018f1..61f4790 100644 --- a/device/geolocation/location_api_adapter_android.cc +++ b/device/geolocation/location_api_adapter_android.cc
@@ -45,7 +45,7 @@ bool LocationApiAdapterAndroid::Start(OnGeopositionCB on_geoposition_callback, bool high_accuracy) { - DCHECK(task_runner_->BelongsToCurrentThread()); + DCHECK(thread_checker_.CalledOnValidThread()); DCHECK(on_geoposition_callback); JNIEnv* env = AttachCurrentThread(); @@ -68,7 +68,7 @@ } void LocationApiAdapterAndroid::Stop() { - DCHECK(task_runner_->BelongsToCurrentThread()); + DCHECK(thread_checker_.CalledOnValidThread()); if (!on_geoposition_callback_) return; @@ -108,7 +108,11 @@ position.heading = heading; if (has_speed) position.speed = speed; - GetInstance()->OnNewGeopositionInternal(position); + + LocationApiAdapterAndroid* self = GetInstance(); + self->task_runner_->PostTask( + FROM_HERE, base::Bind(&LocationApiAdapterAndroid::NotifyNewGeoposition, + base::Unretained(self), position)); } // static @@ -118,7 +122,11 @@ position_error.error_code = Geoposition::ERROR_CODE_POSITION_UNAVAILABLE; position_error.error_message = base::android::ConvertJavaStringToUTF8(env, message); - GetInstance()->OnNewGeopositionInternal(position_error); + + LocationApiAdapterAndroid* self = GetInstance(); + self->task_runner_->PostTask( + FROM_HERE, base::Bind(&LocationApiAdapterAndroid::NotifyNewGeoposition, + base::Unretained(self), position_error)); } // static @@ -127,19 +135,17 @@ } LocationApiAdapterAndroid::LocationApiAdapterAndroid() - : task_runner_(base::ThreadTaskRunnerHandle::Get()) { - jni_thread_checker_.DetachFromThread(); -} + : task_runner_(base::ThreadTaskRunnerHandle::Get()) {} LocationApiAdapterAndroid::~LocationApiAdapterAndroid() { - DCHECK(task_runner_->BelongsToCurrentThread()); + DCHECK(thread_checker_.CalledOnValidThread()); } -void LocationApiAdapterAndroid::OnNewGeopositionInternal( +void LocationApiAdapterAndroid::NotifyNewGeoposition( const Geoposition& geoposition) { - DCHECK(jni_thread_checker_.CalledOnValidThread()); - task_runner_->PostTask(FROM_HERE, - base::Bind(on_geoposition_callback_, geoposition)); + DCHECK(thread_checker_.CalledOnValidThread()); + if (on_geoposition_callback_) + on_geoposition_callback_.Run(geoposition); } } // namespace device
diff --git a/device/geolocation/location_api_adapter_android.h b/device/geolocation/location_api_adapter_android.h index 46a7851..de36f4d 100644 --- a/device/geolocation/location_api_adapter_android.h +++ b/device/geolocation/location_api_adapter_android.h
@@ -66,8 +66,8 @@ LocationApiAdapterAndroid(); ~LocationApiAdapterAndroid(); - // Called on the JNI thread looper. - void OnNewGeopositionInternal(const Geoposition& geoposition); + // Calls |on_geoposition_callback_| with the new location. + void NotifyNewGeoposition(const Geoposition& geoposition); base::android::ScopedJavaGlobalRef<jobject> java_location_provider_adapter_; @@ -76,7 +76,7 @@ const scoped_refptr<base::SingleThreadTaskRunner> task_runner_; - base::ThreadChecker jni_thread_checker_; + base::ThreadChecker thread_checker_; }; } // namespace device
diff --git a/device/screen_orientation/OWNERS b/device/screen_orientation/OWNERS index 88b3579..60c92e4 100644 --- a/device/screen_orientation/OWNERS +++ b/device/screen_orientation/OWNERS
@@ -1,2 +1,4 @@ blundell@chromium.org mlamouri@chromium.org + +# COMPONENT: Blink>ScreenOrientation
diff --git a/device/vibration/android/BUILD.gn b/device/vibration/android/BUILD.gn index 3833b18b..5b3ae0a 100644 --- a/device/vibration/android/BUILD.gn +++ b/device/vibration/android/BUILD.gn
@@ -5,6 +5,13 @@ import("//build/config/android/config.gni") import("//build/config/android/rules.gni") +generate_jni("vibration_jni_headers") { + sources = [ + "java/src/org/chromium/device/vibration/VibrationManagerImpl.java", + ] + jni_package = "vibration" +} + android_library("vibration_manager_java") { java_files = [ "java/src/org/chromium/device/vibration/VibrationManagerImpl.java" ]
diff --git a/device/vibration/android/java/src/org/chromium/device/vibration/VibrationManagerImpl.java b/device/vibration/android/java/src/org/chromium/device/vibration/VibrationManagerImpl.java index 98c24ec..e781f71d 100644 --- a/device/vibration/android/java/src/org/chromium/device/vibration/VibrationManagerImpl.java +++ b/device/vibration/android/java/src/org/chromium/device/vibration/VibrationManagerImpl.java
@@ -10,7 +10,8 @@ import android.os.Vibrator; import android.util.Log; -import org.chromium.base.VisibleForTesting; +import org.chromium.base.annotations.CalledByNative; +import org.chromium.base.annotations.JNINamespace; import org.chromium.device.mojom.VibrationManager; import org.chromium.mojo.system.MojoException; import org.chromium.services.service_manager.InterfaceFactory; @@ -19,6 +20,7 @@ * Android implementation of the vibration manager service defined in * device/vibration/vibration_manager.mojom. */ +@JNINamespace("device") public class VibrationManagerImpl implements VibrationManager { private static final String TAG = "VibrationManagerImpl"; @@ -29,35 +31,12 @@ private final Vibrator mVibrator; private final boolean mHasVibratePermission; - private static AndroidVibratorWrapper sVibratorWrapper; - - /** - * Android Vibrator wrapper class provided to test code to extend. - */ - @VisibleForTesting - public static class AndroidVibratorWrapper { - protected AndroidVibratorWrapper() {} - - public void vibrate(Vibrator vibrator, long milliseconds) { - vibrator.vibrate(milliseconds); - } - - public void cancel(Vibrator vibrator) { - vibrator.cancel(); - } - } - - // Test code can use this function to inject other wrapper for testing. - public static void setVibratorWrapperForTesting(AndroidVibratorWrapper wrapper) { - sVibratorWrapper = wrapper; - } + private static long sVibrateMilliSecondsForTesting = -1; + private static boolean sVibrateCancelledForTesting = false; public VibrationManagerImpl(Context context) { mAudioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE); mVibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE); - if (sVibratorWrapper == null) { - sVibratorWrapper = new AndroidVibratorWrapper(); - } // TODO(mvanouwerkerk): What happens if permission is revoked? Handle this better. mHasVibratePermission = context.checkCallingOrSelfPermission(android.Manifest.permission.VIBRATE) @@ -82,14 +61,18 @@ if (mAudioManager.getRingerMode() != AudioManager.RINGER_MODE_SILENT && mHasVibratePermission) { - sVibratorWrapper.vibrate(mVibrator, sanitizedMilliseconds); + mVibrator.vibrate(sanitizedMilliseconds); } + setVibrateMilliSecondsForTesting(sanitizedMilliseconds); callback.call(); } @Override public void cancel(CancelResponse callback) { - if (mHasVibratePermission) sVibratorWrapper.cancel(mVibrator); + if (mHasVibratePermission) { + mVibrator.cancel(); + } + setVibrateCancelledForTesting(true); callback.call(); } @@ -107,4 +90,22 @@ return new VibrationManagerImpl(mContext); } } + + static void setVibrateMilliSecondsForTesting(long milliseconds) { + sVibrateMilliSecondsForTesting = milliseconds; + } + + static void setVibrateCancelledForTesting(boolean cancelled) { + sVibrateCancelledForTesting = cancelled; + } + + @CalledByNative + static long getVibrateMilliSecondsForTesting() { + return sVibrateMilliSecondsForTesting; + } + + @CalledByNative + static boolean getVibrateCancelledForTesting() { + return sVibrateCancelledForTesting; + } }
diff --git a/device/vibration/vibration_manager_impl.h b/device/vibration/vibration_manager_impl.h index de9a0617..75260a2 100644 --- a/device/vibration/vibration_manager_impl.h +++ b/device/vibration/vibration_manager_impl.h
@@ -14,6 +14,9 @@ public: DEVICE_VIBRATION_EXPORT static void Create( mojo::InterfaceRequest<mojom::VibrationManager> request); + + DEVICE_VIBRATION_EXPORT static int64_t milli_seconds_for_testing_; + DEVICE_VIBRATION_EXPORT static bool cancelled_for_testing_; }; } // namespace device
diff --git a/device/vibration/vibration_manager_impl_default.cc b/device/vibration/vibration_manager_impl_default.cc index 642ddbb7..c073f69a 100644 --- a/device/vibration/vibration_manager_impl_default.cc +++ b/device/vibration/vibration_manager_impl_default.cc
@@ -11,6 +11,9 @@ namespace device { +int64_t VibrationManagerImpl::milli_seconds_for_testing_ = -1; +bool VibrationManagerImpl::cancelled_for_testing_ = false; + namespace { class VibrationManagerEmptyImpl : public mojom::VibrationManager { @@ -19,10 +22,14 @@ ~VibrationManagerEmptyImpl() override {} void Vibrate(int64_t milliseconds, const VibrateCallback& callback) override { + VibrationManagerImpl::milli_seconds_for_testing_ = milliseconds; callback.Run(); } - void Cancel(const CancelCallback& callback) override { callback.Run(); } + void Cancel(const CancelCallback& callback) override { + VibrationManagerImpl::cancelled_for_testing_ = true; + callback.Run(); + } }; } // namespace
diff --git a/device/vr/BUILD.gn b/device/vr/BUILD.gn index 6445234b..2e40989d 100644 --- a/device/vr/BUILD.gn +++ b/device/vr/BUILD.gn
@@ -47,8 +47,11 @@ "vr_display_impl.cc", "vr_display_impl.h", "vr_export.h", + "vr_math.cc", + "vr_math.h", "vr_service_impl.cc", "vr_service_impl.h", + "vr_types.h", ] deps += [
diff --git a/device/vr/android/gvr/gvr_delegate.cc b/device/vr/android/gvr/gvr_delegate.cc index 5358f73b..9b05efc 100644 --- a/device/vr/android/gvr/gvr_delegate.cc +++ b/device/vr/android/gvr/gvr_delegate.cc
@@ -5,7 +5,9 @@ #include "device/vr/android/gvr/gvr_delegate.h" #include "base/trace_event/trace_event.h" +#include "device/vr/vr_math.h" #include "third_party/gvr-android-sdk/src/libraries/headers/vr/gvr/capi/include/gvr.h" +#include "third_party/gvr-android-sdk/src/libraries/headers/vr/gvr/capi/include/gvr_types.h" #include "ui/gfx/transform.h" #include "ui/gfx/transform_util.h" @@ -28,35 +30,17 @@ // less than a frame. static constexpr int64_t kAngularVelocityEpsilonNanos = 1000000; -// Matrix math copied from vr_shell's vr_math.cc, can't use that here -// due to dependency ordering. TODO(mthiesse): move the vr_math code -// to this directory so that both locations can use it. - -// Rotation only, ignore translation components. -gvr::Vec3f MatrixVectorRotate(const gvr::Mat4f& m, const gvr::Vec3f& v) { - gvr::Vec3f res; - res.x = m.m[0][0] * v.x + m.m[0][1] * v.y + m.m[0][2] * v.z; - res.y = m.m[1][0] * v.x + m.m[1][1] * v.y + m.m[1][2] * v.z; - res.z = m.m[2][0] * v.x + m.m[2][1] * v.y + m.m[2][2] * v.z; - return res; +void GvrMatToMatf(const gvr::Mat4f& in, vr::Mat4f* out) { + // If our std::array implementation doesn't have any non-data members, we can + // just cast the gvr matrix to an std::array. + static_assert(sizeof(in) == sizeof(*out), + "Cannot reinterpret gvr::Mat4f as vr::Matf"); + *out = *reinterpret_cast<vr::Mat4f*>(const_cast<gvr::Mat4f*>(&in)); } -gvr::Mat4f MatrixMul(const gvr::Mat4f& matrix1, const gvr::Mat4f& matrix2) { - gvr::Mat4f result; - for (int i = 0; i < 4; ++i) { - for (int j = 0; j < 4; ++j) { - result.m[i][j] = 0.0f; - for (int k = 0; k < 4; ++k) { - result.m[i][j] += matrix1.m[i][k] * matrix2.m[k][j]; - } - } - } - return result; -} - -gvr::Vec3f GetAngularVelocityFromPoses(gvr::Mat4f head_mat, - gvr::Mat4f head_mat_2, - double epsilon_seconds) { +gfx::Vector3dF GetAngularVelocityFromPoses(vr::Mat4f head_mat, + vr::Mat4f head_mat_2, + double epsilon_seconds) { // The angular velocity is a 3-element vector pointing along the rotation // axis with magnitude equal to rotation speed in radians/second, expressed // in the seated frame of reference. @@ -74,8 +58,8 @@ // See: // https://en.wikipedia.org/wiki/Angular_velocity#Calculation_from_the_orientation_matrix - gvr::Mat4f delta_mat; - gvr::Mat4f inverse_head_mat; + vr::Mat4f delta_mat; + vr::Mat4f inverse_head_mat; // Calculate difference matrix, and inverse head matrix rotation. // For the inverse rotation, just transpose the 3x3 subsection. // @@ -83,41 +67,35 @@ // provided by the caller. for (int j = 0; j < 3; ++j) { for (int i = 0; i < 3; ++i) { - delta_mat.m[j][i] = - (head_mat_2.m[j][i] - head_mat.m[j][i]) / epsilon_seconds; - inverse_head_mat.m[j][i] = head_mat.m[i][j]; + delta_mat[j][i] = (head_mat_2[j][i] - head_mat[j][i]) / epsilon_seconds; + inverse_head_mat[j][i] = head_mat[i][j]; } - delta_mat.m[j][3] = delta_mat.m[3][j] = 0.0; - inverse_head_mat.m[j][3] = inverse_head_mat.m[3][j] = 0.0; + delta_mat[j][3] = delta_mat[3][j] = 0.0; + inverse_head_mat[j][3] = inverse_head_mat[3][j] = 0.0; } - delta_mat.m[3][3] = 1.0; - inverse_head_mat.m[3][3] = 1.0; - gvr::Mat4f omega_mat = device::MatrixMul(delta_mat, inverse_head_mat); - gvr::Vec3f omega_vec; - omega_vec.x = -omega_mat.m[2][1]; - omega_vec.y = omega_mat.m[2][0]; - omega_vec.z = -omega_mat.m[1][0]; + delta_mat[3][3] = 1.0; + inverse_head_mat[3][3] = 1.0; + vr::Mat4f omega_mat; + vr::MatrixMul(delta_mat, inverse_head_mat, &omega_mat); + gfx::Vector3dF omega_vec(-omega_mat[2][1], omega_mat[2][0], -omega_mat[1][0]); // Rotate by inverse head matrix to bring into seated space. - gvr::Vec3f angular_velocity = - device::MatrixVectorRotate(inverse_head_mat, omega_vec); - - return angular_velocity; + return vr::MatrixVectorRotate(inverse_head_mat, omega_vec); } } // namespace /* static */ -mojom::VRPosePtr GvrDelegate::VRPosePtrFromGvrPose(gvr::Mat4f head_mat) { +mojom::VRPosePtr GvrDelegate::VRPosePtrFromGvrPose(const vr::Mat4f& head_mat) { mojom::VRPosePtr pose = mojom::VRPose::New(); pose->orientation.emplace(4); gfx::Transform inv_transform( - head_mat.m[0][0], head_mat.m[0][1], head_mat.m[0][2], head_mat.m[0][3], - head_mat.m[1][0], head_mat.m[1][1], head_mat.m[1][2], head_mat.m[1][3], - head_mat.m[2][0], head_mat.m[2][1], head_mat.m[2][2], head_mat.m[2][3], - head_mat.m[3][0], head_mat.m[3][1], head_mat.m[3][2], head_mat.m[3][3]); + head_mat[0][0], head_mat[0][1], head_mat[0][2], head_mat[0][3], + head_mat[1][0], head_mat[1][1], head_mat[1][2], head_mat[1][3], + head_mat[2][0], head_mat[2][1], head_mat[2][2], head_mat[2][3], + head_mat[3][0], head_mat[3][1], head_mat[3][2], head_mat[3][3]); gfx::Transform transform; if (inv_transform.GetInverse(&transform)) { @@ -139,50 +117,56 @@ } /* static */ -gvr::Mat4f GvrDelegate::GetGvrPoseWithNeckModel(gvr::GvrApi* gvr_api) { +void GvrDelegate::GetGvrPoseWithNeckModel(gvr::GvrApi* gvr_api, + vr::Mat4f* out) { gvr::ClockTimePoint target_time = gvr::GvrApi::GetTimePointNow(); target_time.monotonic_system_time_nanos += kPredictionTimeWithoutVsyncNanos; gvr::Mat4f head_mat = gvr_api->ApplyNeckModel( gvr_api->GetHeadSpaceFromStartSpaceRotation(target_time), 1.0f); - return head_mat; + GvrMatToMatf(head_mat, out); } /* static */ mojom::VRPosePtr GvrDelegate::GetVRPosePtrWithNeckModel( gvr::GvrApi* gvr_api, - gvr::Mat4f* head_mat_out) { + vr::Mat4f* head_mat_out) { gvr::ClockTimePoint target_time = gvr::GvrApi::GetTimePointNow(); target_time.monotonic_system_time_nanos += kPredictionTimeWithoutVsyncNanos; - gvr::Mat4f head_mat = gvr_api->ApplyNeckModel( + gvr::Mat4f gvr_head_mat = gvr_api->ApplyNeckModel( gvr_api->GetHeadSpaceFromStartSpaceRotation(target_time), 1.0f); - if (head_mat_out) - *head_mat_out = head_mat; + vr::Mat4f* head_mat_ptr = head_mat_out; + vr::Mat4f head_mat; + if (!head_mat_ptr) + head_mat_ptr = &head_mat; + GvrMatToMatf(gvr_head_mat, head_mat_ptr); - mojom::VRPosePtr pose = GvrDelegate::VRPosePtrFromGvrPose(head_mat); + mojom::VRPosePtr pose = GvrDelegate::VRPosePtrFromGvrPose(*head_mat_ptr); // Get a second pose a bit later to calculate angular velocity. target_time.monotonic_system_time_nanos += kAngularVelocityEpsilonNanos; - gvr::Mat4f head_mat_2 = + gvr::Mat4f gvr_head_mat_2 = gvr_api->GetHeadSpaceFromStartSpaceRotation(target_time); + vr::Mat4f head_mat_2; + GvrMatToMatf(gvr_head_mat_2, &head_mat_2); // Add headset angular velocity to the pose. pose->angularVelocity.emplace(3); double epsilon_seconds = kAngularVelocityEpsilonNanos * 1e-9; - gvr::Vec3f angular_velocity = - GetAngularVelocityFromPoses(head_mat, head_mat_2, epsilon_seconds); - pose->angularVelocity.value()[0] = angular_velocity.x; - pose->angularVelocity.value()[1] = angular_velocity.y; - pose->angularVelocity.value()[2] = angular_velocity.z; + gfx::Vector3dF angular_velocity = + GetAngularVelocityFromPoses(*head_mat_ptr, head_mat_2, epsilon_seconds); + pose->angularVelocity.value()[0] = angular_velocity.x(); + pose->angularVelocity.value()[1] = angular_velocity.y(); + pose->angularVelocity.value()[2] = angular_velocity.z(); return pose; } /* static */ -gvr::Sizei GvrDelegate::GetRecommendedWebVrSize(gvr::GvrApi* gvr_api) { +gfx::Size GvrDelegate::GetRecommendedWebVrSize(gvr::GvrApi* gvr_api) { // Pick a reasonable default size for the WebVR transfer surface // based on a downscaled 1:1 render resolution. This size will also // be reported to the client via CreateVRDisplayInfo as the @@ -192,10 +176,11 @@ // framebuffer to match. gvr::Sizei render_target_size = gvr_api->GetMaximumEffectiveRenderTargetSize(); - gvr::Sizei webvr_size = {static_cast<int>(render_target_size.width * - kWebVrRecommendedResolutionScale), - static_cast<int>(render_target_size.height * - kWebVrRecommendedResolutionScale)}; + + gfx::Size webvr_size( + render_target_size.width * kWebVrRecommendedResolutionScale, + render_target_size.height * kWebVrRecommendedResolutionScale); + // Ensure that the width is an even number so that the eyes each // get the same size, the recommended renderWidth is per eye // and the client will use the sum of the left and right width. @@ -203,15 +188,14 @@ // TODO(klausw,crbug.com/699350): should we round the recommended // size to a multiple of 2^N pixels to be friendlier to the GPU? The // exact size doesn't matter, and it might be more efficient. - webvr_size.width &= ~1; - + webvr_size.set_width(webvr_size.width() & ~1); return webvr_size; } /* static */ mojom::VRDisplayInfoPtr GvrDelegate::CreateVRDisplayInfo( gvr::GvrApi* gvr_api, - gvr::Sizei recommended_size, + gfx::Size recommended_size, uint32_t device_id) { TRACE_EVENT0("input", "GvrDelegate::CreateVRDisplayInfo"); @@ -239,8 +223,8 @@ (eye == GVR_LEFT_EYE) ? device->leftEye : device->rightEye; eye_params->fieldOfView = mojom::VRFieldOfView::New(); eye_params->offset.resize(3); - eye_params->renderWidth = recommended_size.width / 2; - eye_params->renderHeight = recommended_size.height; + eye_params->renderWidth = recommended_size.width() / 2; + eye_params->renderHeight = recommended_size.height(); gvr::BufferViewport eye_viewport = gvr_api->CreateBufferViewport(); gvr_buffer_viewports.GetBufferViewport(eye, &eye_viewport);
diff --git a/device/vr/android/gvr/gvr_delegate.h b/device/vr/android/gvr/gvr_delegate.h index 9a21aba..d5158193 100644 --- a/device/vr/android/gvr/gvr_delegate.h +++ b/device/vr/android/gvr/gvr_delegate.h
@@ -9,30 +9,34 @@ #include "device/vr/vr_export.h" #include "device/vr/vr_service.mojom.h" +#include "device/vr/vr_types.h" #include "gpu/command_buffer/common/mailbox_holder.h" #include "third_party/gvr-android-sdk/src/libraries/headers/vr/gvr/capi/include/gvr_types.h" +namespace gvr { +class GvrApi; +} + namespace device { class DEVICE_VR_EXPORT GvrDelegate { public: - static mojom::VRPosePtr VRPosePtrFromGvrPose(gvr::Mat4f head_mat); - static gvr::Mat4f GetGvrPoseWithNeckModel(gvr::GvrApi* gvr_api); + static mojom::VRPosePtr VRPosePtrFromGvrPose(const vr::Mat4f& head_mat); + static void GetGvrPoseWithNeckModel(gvr::GvrApi* gvr_api, vr::Mat4f* out); static mojom::VRPosePtr GetVRPosePtrWithNeckModel(gvr::GvrApi* gvr_api, - gvr::Mat4f* head_mat_out); - static gvr::Sizei GetRecommendedWebVrSize(gvr::GvrApi* gvr_api); - static mojom::VRDisplayInfoPtr CreateVRDisplayInfo( - gvr::GvrApi* gvr_api, - gvr::Sizei recommended_size, - uint32_t device_id); + vr::Mat4f* head_mat_out); + static gfx::Size GetRecommendedWebVrSize(gvr::GvrApi* gvr_api); + static mojom::VRDisplayInfoPtr CreateVRDisplayInfo(gvr::GvrApi* gvr_api, + gfx::Size recommended_size, + uint32_t device_id); virtual void SetWebVRSecureOrigin(bool secure_origin) = 0; virtual void SubmitWebVRFrame(int16_t frame_index, const gpu::MailboxHolder& mailbox) = 0; virtual void UpdateWebVRTextureBounds(int16_t frame_index, - const gvr::Rectf& left_bounds, - const gvr::Rectf& right_bounds, - const gvr::Sizei& source_size) = 0; + const gfx::RectF& left_bounds, + const gfx::RectF& right_bounds, + const gfx::Size& source_size) = 0; virtual void OnVRVsyncProviderRequest( mojom::VRVSyncProviderRequest request) = 0; virtual void UpdateVSyncInterval(int64_t timebase_nanos,
diff --git a/device/vr/android/gvr/gvr_device.cc b/device/vr/android/gvr/gvr_device.cc index 9f60361..bf48f6b8 100644 --- a/device/vr/android/gvr/gvr_device.cc +++ b/device/vr/android/gvr/gvr_device.cc
@@ -13,8 +13,7 @@ #include "device/vr/android/gvr/gvr_delegate_provider.h" #include "device/vr/android/gvr/gvr_device_provider.h" #include "device/vr/vr_device_manager.h" -#include "third_party/gvr-android-sdk/src/libraries/headers/vr/gvr/capi/include/gvr.h" -#include "third_party/gvr-android-sdk/src/libraries/headers/vr/gvr/capi/include/gvr_types.h" +#include "device/vr/vr_types.h" #include "ui/gfx/transform.h" #include "ui/gfx/transform_util.h" @@ -69,19 +68,11 @@ if (!delegate) return; - gvr::Rectf left_gvr_bounds; - left_gvr_bounds.left = left_bounds->left; - left_gvr_bounds.top = 1.0f - left_bounds->top; - left_gvr_bounds.right = left_bounds->left + left_bounds->width; - left_gvr_bounds.bottom = 1.0f - (left_bounds->top + left_bounds->height); - - gvr::Rectf right_gvr_bounds; - right_gvr_bounds.left = right_bounds->left; - right_gvr_bounds.top = 1.0f - right_bounds->top; - right_gvr_bounds.right = right_bounds->left + right_bounds->width; - right_gvr_bounds.bottom = 1.0f - (right_bounds->top + right_bounds->height); - - gvr::Sizei source_size = {source_width, source_height}; + gfx::RectF left_gvr_bounds(left_bounds->left, left_bounds->top, + left_bounds->width, left_bounds->height); + gfx::RectF right_gvr_bounds(right_bounds->left, right_bounds->top, + right_bounds->width, right_bounds->height); + gfx::Size source_size(source_width, source_height); delegate->UpdateWebVRTextureBounds(frame_index, left_gvr_bounds, right_gvr_bounds, source_size); }
diff --git a/device/vr/android/gvr/gvr_gamepad_data_fetcher.cc b/device/vr/android/gvr/gvr_gamepad_data_fetcher.cc index 1f4f503e..a18b6c6 100644 --- a/device/vr/android/gvr/gvr_gamepad_data_fetcher.cc +++ b/device/vr/android/gvr/gvr_gamepad_data_fetcher.cc
@@ -6,8 +6,8 @@ #include "base/memory/ptr_util.h" #include "base/strings/utf_string_conversions.h" - #include "device/vr/android/gvr/gvr_gamepad_data_provider.h" +#include "device/vr/vr_types.h" #include "third_party/WebKit/public/platform/WebGamepads.h" namespace device { @@ -106,9 +106,9 @@ pad.timestamp = provided_data.timestamp; if (provided_data.is_touching) { - gvr_vec2f touch_position = provided_data.touch_pos; - pad.axes[0] = (touch_position.x * 2.0f) - 1.0f; - pad.axes[1] = (touch_position.y * 2.0f) - 1.0f; + gfx::Vector2dF touch_position = provided_data.touch_pos; + pad.axes[0] = (touch_position.x() * 2.0f) - 1.0f; + pad.axes[1] = (touch_position.y() * 2.0f) - 1.0f; } else { pad.axes[0] = 0.0f; pad.axes[1] = 0.0f; @@ -122,24 +122,24 @@ pad.pose.has_orientation = true; pad.pose.has_position = false; - gvr_quatf orientation = provided_data.orientation; + vr::Quatf orientation = provided_data.orientation; pad.pose.orientation.not_null = true; pad.pose.orientation.x = orientation.qx; pad.pose.orientation.y = orientation.qy; pad.pose.orientation.z = orientation.qz; pad.pose.orientation.w = orientation.qw; - gvr_vec3f accel = provided_data.accel; + gfx::Vector3dF accel = provided_data.accel; pad.pose.linear_acceleration.not_null = true; - pad.pose.linear_acceleration.x = accel.x; - pad.pose.linear_acceleration.y = accel.y; - pad.pose.linear_acceleration.z = accel.z; + pad.pose.linear_acceleration.x = accel.x(); + pad.pose.linear_acceleration.y = accel.y(); + pad.pose.linear_acceleration.z = accel.z(); - gvr_vec3f gyro = provided_data.gyro; + gfx::Vector3dF gyro = provided_data.gyro; pad.pose.angular_velocity.not_null = true; - pad.pose.angular_velocity.x = gyro.x; - pad.pose.angular_velocity.y = gyro.y; - pad.pose.angular_velocity.z = gyro.z; + pad.pose.angular_velocity.x = gyro.x(); + pad.pose.angular_velocity.y = gyro.y(); + pad.pose.angular_velocity.z = gyro.z(); } void GvrGamepadDataFetcher::PauseHint(bool paused) {}
diff --git a/device/vr/android/gvr/gvr_gamepad_data_provider.h b/device/vr/android/gvr/gvr_gamepad_data_provider.h index 7aa09e9..fcfcf68 100644 --- a/device/vr/android/gvr/gvr_gamepad_data_provider.h +++ b/device/vr/android/gvr/gvr_gamepad_data_provider.h
@@ -5,7 +5,7 @@ #ifndef DEVICE_VR_ANDROID_GVR_GAMEPAD_DATA_PROVIDER_H #define DEVICE_VR_ANDROID_GVR_GAMEPAD_DATA_PROVIDER_H -#include "third_party/gvr-android-sdk/src/libraries/headers/vr/gvr/capi/include/gvr_types.h" +#include "device/vr/vr_types.h" namespace device { @@ -15,10 +15,10 @@ // by vr_shell's VrController and consumed by GvrGamepadDataFetcher. struct GvrGamepadData { int64_t timestamp; - gvr_vec2f touch_pos; - gvr_quatf orientation; - gvr_vec3f accel; - gvr_vec3f gyro; + gfx::Vector2dF touch_pos; + vr::Quatf orientation; + gfx::Vector3dF accel; + gfx::Vector3dF gyro; bool is_touching; bool controller_button_pressed; bool right_handed;
diff --git a/device/vr/vr_export.h b/device/vr/vr_export.h index a450834..0afc127 100644 --- a/device/vr/vr_export.h +++ b/device/vr/vr_export.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 DEVICE_VR_DEVICE_VR_EXPORT_H_ -#define DEVICE_VR_DEVICE_VR_EXPORT_H_ +#ifndef DEVICE_VR_VR_EXPORT_H_ +#define DEVICE_VR_VR_EXPORT_H_ #if defined(COMPONENT_BUILD) && defined(WIN32) @@ -25,4 +25,4 @@ #define DEVICE_VR_EXPORT #endif -#endif // DEVICE_VR_DEVICE_VR_EXPORT_H_ +#endif // DEVICE_VR_VR_EXPORT_H_
diff --git a/device/vr/vr_math.cc b/device/vr/vr_math.cc new file mode 100644 index 0000000..77613963 --- /dev/null +++ b/device/vr/vr_math.cc
@@ -0,0 +1,232 @@ +// Copyright 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "device/vr/vr_math.h" + +#include <cmath> + +#include "base/logging.h" + +namespace vr { + +namespace { +Mat4f CopyMat(const Mat4f& mat) { + Mat4f ret = mat; + return ret; +} +} + +// Internal matrix layout: +// +// m[0][0], m[0][1], m[0][2], m[0][3], +// m[1][0], m[1][1], m[1][2], m[1][3], +// m[2][0], m[2][1], m[2][2], m[2][3], +// m[3][0], m[3][1], m[3][2], m[3][3], +// +// The translation component is in the right column m[i][3]. +// +// The bottom row m[3][i] is (0, 0, 0, 1) for non-perspective transforms. +// +// These matrices are intended to be used to premultiply column vectors +// for transforms, so successive transforms need to be left-multiplied. + +void SetIdentityM(Mat4f* mat) { + for (int i = 0; i < 4; i++) { + for (int j = 0; j < 4; j++) { + (*mat)[i][j] = i == j ? 1 : 0; + } + } +} + +// Left multiply a translation matrix. +void TranslateM(const Mat4f& mat, + const gfx::Vector3dF& translation, + Mat4f* out) { + if (out != &mat) { + for (int i = 0; i < 4; ++i) { + for (int j = 0; j < 4; ++j) { + (*out)[i][j] = mat[i][j]; + } + } + } + (*out)[0][3] += translation.x(); + (*out)[1][3] += translation.y(); + (*out)[2][3] += translation.z(); +} + +// Left multiply a scale matrix. +void ScaleM(const Mat4f& mat, const gfx::Vector3dF& scale, Mat4f* out) { + if (out != &mat) { + for (int i = 0; i < 4; ++i) { + for (int j = 0; j < 3; ++j) { + (*out)[i][j] = mat[i][j]; + } + } + } + // Multiply all rows including translation components. + for (int j = 0; j < 4; ++j) { + (*out)[0][j] *= scale.x(); + (*out)[1][j] *= scale.y(); + (*out)[2][j] *= scale.z(); + } +} + +gfx::Vector3dF MatrixVectorMul(const Mat4f& m, const gfx::Vector3dF& v) { + return gfx::Vector3dF( + m[0][0] * v.x() + m[0][1] * v.y() + m[0][2] * v.z() + m[0][3], + m[1][0] * v.x() + m[1][1] * v.y() + m[1][2] * v.z() + m[1][3], + m[2][0] * v.x() + m[2][1] * v.y() + m[2][2] * v.z() + m[2][3]); +} + +// Rotation only, ignore translation components. +gfx::Vector3dF MatrixVectorRotate(const Mat4f& m, const gfx::Vector3dF& v) { + return gfx::Vector3dF(m[0][0] * v.x() + m[0][1] * v.y() + m[0][2] * v.z(), + m[1][0] * v.x() + m[1][1] * v.y() + m[1][2] * v.z(), + m[2][0] * v.x() + m[2][1] * v.y() + m[2][2] * v.z()); +} + +void MatrixMul(const Mat4f& matrix1, const Mat4f& matrix2, Mat4f* out) { + const Mat4f& mat1 = (out == &matrix1) ? CopyMat(matrix1) : matrix1; + const Mat4f& mat2 = (out == &matrix2) ? CopyMat(matrix2) : matrix2; + for (int i = 0; i < 4; ++i) { + for (int j = 0; j < 4; ++j) { + (*out)[i][j] = 0.0f; + for (int k = 0; k < 4; ++k) { + (*out)[i][j] += mat1[i][k] * mat2[k][j]; + } + } + } +} + +void PerspectiveMatrixFromView(const gfx::RectF& fov, + float z_near, + float z_far, + Mat4f* out) { + const float x_left = -std::tan(fov.x() * M_PI / 180.0f) * z_near; + const float x_right = std::tan(fov.right() * M_PI / 180.0f) * z_near; + const float y_bottom = -std::tan(fov.bottom() * M_PI / 180.0f) * z_near; + const float y_top = std::tan(fov.y() * M_PI / 180.0f) * z_near; + + DCHECK(x_left < x_right && y_bottom < y_top && z_near < z_far && + z_near > 0.0f && z_far > 0.0f); + const float X = (2 * z_near) / (x_right - x_left); + const float Y = (2 * z_near) / (y_top - y_bottom); + const float A = (x_right + x_left) / (x_right - x_left); + const float B = (y_top + y_bottom) / (y_top - y_bottom); + const float C = (z_near + z_far) / (z_near - z_far); + const float D = (2 * z_near * z_far) / (z_near - z_far); + + for (int i = 0; i < 4; ++i) { + (*out)[i].fill(0.0f); + } + (*out)[0][0] = X; + (*out)[0][2] = A; + (*out)[1][1] = Y; + (*out)[1][2] = B; + (*out)[2][2] = C; + (*out)[2][3] = D; + (*out)[3][2] = -1; +} + +gfx::Vector3dF GetForwardVector(const Mat4f& matrix) { + // Same as multiplying the inverse of the rotation component of the matrix by + // (0, 0, -1, 0). + return gfx::Vector3dF(-matrix[2][0], -matrix[2][1], -matrix[2][2]); +} + +gfx::Vector3dF GetTranslation(const Mat4f& matrix) { + return gfx::Vector3dF(matrix[0][3], matrix[1][3], matrix[2][3]); +} + +float NormalizeVector(gfx::Vector3dF* vec) { + float len = vec->Length(); + if (len == 0) + return 0; + vec->Scale(1.0f / len); + return len; +} + +void NormalizeQuat(Quatf* quat) { + float len = sqrt(quat->qx * quat->qx + quat->qy * quat->qy + + quat->qz * quat->qz + quat->qw * quat->qw); + quat->qx /= len; + quat->qy /= len; + quat->qz /= len; + quat->qw /= len; +} + +Quatf QuatFromAxisAngle(const RotationAxisAngle& axis_angle) { + // Rotation angle is the product of |angle| and the magnitude of |axis|. + gfx::Vector3dF normal(axis_angle.x, axis_angle.y, axis_angle.z); + float length = NormalizeVector(&normal); + float angle = axis_angle.angle * length; + + Quatf res; + float s = sin(angle / 2); + res.qx = normal.x() * s; + res.qy = normal.y() * s; + res.qz = normal.z() * s; + res.qw = cos(angle / 2); + return res; +} + +Quatf QuatMultiply(const Quatf& a, const Quatf& b) { + Quatf res; + res.qw = a.qw * b.qw - a.qx * b.qx - a.qy * b.qy - a.qz * b.qz; + res.qx = a.qw * b.qx + a.qx * b.qw + a.qy * b.qz - a.qz * b.qy; + res.qy = a.qw * b.qy - a.qx * b.qz + a.qy * b.qw + a.qz * b.qx; + res.qz = a.qw * b.qz + a.qx * b.qy - a.qy * b.qx + a.qz * b.qw; + return res; +} + +void QuatToMatrix(const Quatf& quat, Mat4f* out) { + const float x2 = quat.qx * quat.qx; + const float y2 = quat.qy * quat.qy; + const float z2 = quat.qz * quat.qz; + const float xy = quat.qx * quat.qy; + const float xz = quat.qx * quat.qz; + const float xw = quat.qx * quat.qw; + const float yz = quat.qy * quat.qz; + const float yw = quat.qy * quat.qw; + const float zw = quat.qz * quat.qw; + + const float m11 = 1.0f - 2.0f * y2 - 2.0f * z2; + const float m12 = 2.0f * (xy - zw); + const float m13 = 2.0f * (xz + yw); + const float m21 = 2.0f * (xy + zw); + const float m22 = 1.0f - 2.0f * x2 - 2.0f * z2; + const float m23 = 2.0f * (yz - xw); + const float m31 = 2.0f * (xz - yw); + const float m32 = 2.0f * (yz + xw); + const float m33 = 1.0f - 2.0f * x2 - 2.0f * y2; + + *out = {{{{m11, m12, m13, 0.0f}}, + {{m21, m22, m23, 0.0f}}, + {{m31, m32, m33, 0.0f}}, + {{0.0f, 0.0f, 0.0f, 1.0f}}}}; +} + +gfx::Point3F GetRayPoint(const gfx::Point3F& rayOrigin, + const gfx::Vector3dF& rayVector, + float scale) { + return rayOrigin + gfx::ScaleVector3d(rayVector, scale); +} + +float Distance(const gfx::Point3F& p1, const gfx::Point3F& p2) { + return std::sqrt(p1.SquaredDistanceTo(p2)); +} + +bool XZAngle(const gfx::Vector3dF& vec1, + const gfx::Vector3dF& vec2, + float* angle) { + float len1 = vec1.Length(); + float len2 = vec2.Length(); + if (len1 == 0 || len2 == 0) + return false; + float cross_p = vec1.x() * vec2.z() - vec1.z() * vec2.x(); + *angle = asin(cross_p / (len1 * len2)); + return true; +} + +} // namespace vr
diff --git a/device/vr/vr_math.h b/device/vr/vr_math.h new file mode 100644 index 0000000..72e21808 --- /dev/null +++ b/device/vr/vr_math.h
@@ -0,0 +1,58 @@ +// Copyright 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef DEVICE_VR_VR_MATH_H_ +#define DEVICE_VR_VR_MATH_H_ + +#include "device/vr/vr_export.h" +#include "device/vr/vr_types.h" + +namespace vr { + +void DEVICE_VR_EXPORT SetIdentityM(Mat4f* mat); +void DEVICE_VR_EXPORT TranslateM(const Mat4f& mat, + const gfx::Vector3dF& translation, + Mat4f* out); +void DEVICE_VR_EXPORT ScaleM(const Mat4f& mat, + const gfx::Vector3dF& scale, + Mat4f* out); + +gfx::Vector3dF DEVICE_VR_EXPORT MatrixVectorMul(const Mat4f& m, + const gfx::Vector3dF& v); +gfx::Vector3dF DEVICE_VR_EXPORT MatrixVectorRotate(const Mat4f& m, + const gfx::Vector3dF& v); +void DEVICE_VR_EXPORT MatrixMul(const Mat4f& matrix1, + const Mat4f& matrix2, + Mat4f* out); +void DEVICE_VR_EXPORT PerspectiveMatrixFromView(const gfx::RectF& fov, + float z_near, + float z_far, + Mat4f* out); + +// Provides the direction the head is looking towards as a 3x1 unit vector. +gfx::Vector3dF DEVICE_VR_EXPORT GetForwardVector(const Mat4f& matrix); + +gfx::Vector3dF DEVICE_VR_EXPORT GetTranslation(const Mat4f& matrix); + +void DEVICE_VR_EXPORT QuatToMatrix(const Quatf& quat, Mat4f* out); + +// Normalize a vector, and return its original length. +float DEVICE_VR_EXPORT NormalizeVector(gfx::Vector3dF* vec); + +void DEVICE_VR_EXPORT NormalizeQuat(Quatf* quat); + +Quatf DEVICE_VR_EXPORT QuatFromAxisAngle(const RotationAxisAngle& axis_angle); + +gfx::Point3F DEVICE_VR_EXPORT GetRayPoint(const gfx::Point3F& rayOrigin, + const gfx::Vector3dF& rayVector, + float scale); + +// Angle between the vectors' projections to the XZ plane. +bool DEVICE_VR_EXPORT XZAngle(const gfx::Vector3dF& vec1, + const gfx::Vector3dF& vec2, + float* angle); + +} // namespace vr + +#endif // DEVICE_VR_VR_MATH_H_
diff --git a/device/vr/vr_types.h b/device/vr/vr_types.h new file mode 100644 index 0000000..a030bd9 --- /dev/null +++ b/device/vr/vr_types.h
@@ -0,0 +1,47 @@ +// 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 DEVICE_VR_VR_TYPES_H_ +#define DEVICE_VR_VR_TYPES_H_ + +#include <array> + +#include "ui/gfx/geometry/point3_f.h" +#include "ui/gfx/geometry/point_f.h" +#include "ui/gfx/geometry/rect.h" +#include "ui/gfx/geometry/rect_f.h" +#include "ui/gfx/geometry/size.h" +#include "ui/gfx/geometry/vector3d_f.h" + +namespace vr { + +using Mat4f = std::array<std::array<float, 4>, 4>; + +typedef struct RotationAxisAngle { + float x; + float y; + float z; + float angle; +} RotationAxisAngle; + +typedef struct Colorf { + float r; + float g; + float b; + float a; +} Colorf; + +// A floating point quaternion, in JPL format. +typedef struct Quatf { + /// qx, qy, qz are the vector component. + float qx; + float qy; + float qz; + /// qw is the linear component. + float qw; +} Quatf; + +} // namespace vr + +#endif // DEVICE_VR_VR_TYPES_H_
diff --git a/extensions/BUILD.gn b/extensions/BUILD.gn index b0215fc..0046866f 100644 --- a/extensions/BUILD.gn +++ b/extensions/BUILD.gn
@@ -52,6 +52,7 @@ deps = [ "//chrome/browser/media/router:mojo_bindings__generator", + "//chrome/browser/media/router:mojo_bindings_common__generator", "//device/serial:serial_mojo__generator", "//extensions/common:mojo__generator", "//extensions/common/api:mojom__generator",
diff --git a/extensions/browser/api/bluetooth/bluetooth_event_router_unittest.cc b/extensions/browser/api/bluetooth/bluetooth_event_router_unittest.cc index 2b402d5a..474a85e 100644 --- a/extensions/browser/api/bluetooth/bluetooth_event_router_unittest.cc +++ b/extensions/browser/api/bluetooth/bluetooth_event_router_unittest.cc
@@ -8,6 +8,7 @@ #include <string> #include <utility> +#include "base/memory/ptr_util.h" #include "base/memory/ref_counted.h" #include "base/run_loop.h" #include "content/public/test/test_browser_context.h" @@ -40,8 +41,12 @@ class BluetoothEventRouterTest : public ExtensionsTest { public: BluetoothEventRouterTest() - : mock_adapter_(new testing::StrictMock<device::MockBluetoothAdapter>()), - router_(new BluetoothEventRouter(browser_context())) { + : mock_adapter_(new testing::StrictMock<device::MockBluetoothAdapter>()) { + } + + void SetUp() override { + ExtensionsTest::SetUp(); + router_ = base::MakeUnique<BluetoothEventRouter>(browser_context()); router_->SetAdapterForTest(mock_adapter_); }
diff --git a/extensions/browser/api/file_handlers/mime_util_unittest.cc b/extensions/browser/api/file_handlers/mime_util_unittest.cc index 758134e..f1a8f48 100644 --- a/extensions/browser/api/file_handlers/mime_util_unittest.cc +++ b/extensions/browser/api/file_handlers/mime_util_unittest.cc
@@ -55,13 +55,15 @@ ~FileHandlersMimeUtilTest() override {} void SetUp() override { + ExtensionsTest::SetUp(); file_system_context_ = content::CreateFileSystemContextForTesting( NULL, browser_context()->GetPath()); EXPECT_TRUE(base::CreateTemporaryFile(&html_mime_file_path_)); const std::string kSampleContent = "<html><body></body></html>"; - EXPECT_TRUE(base::WriteFile(html_mime_file_path_, kSampleContent.c_str(), - kSampleContent.size())); + EXPECT_EQ(static_cast<int>(kSampleContent.size()), + base::WriteFile(html_mime_file_path_, kSampleContent.c_str(), + kSampleContent.size())); } content::TestBrowserThreadBundle thread_bundle_;
diff --git a/extensions/browser/api/system_display/display_info_provider.cc b/extensions/browser/api/system_display/display_info_provider.cc index e6c75ef..7d1d4fa 100644 --- a/extensions/browser/api/system_display/display_info_provider.cc +++ b/extensions/browser/api/system_display/display_info_provider.cc
@@ -61,6 +61,7 @@ unit.is_primary = (display.id() == primary_display_id); unit.is_internal = display.IsInternal(); unit.is_enabled = true; + unit.is_unified = false; unit.rotation = RotationToDegrees(display.rotation()); unit.bounds.left = bounds.x(); unit.bounds.top = bounds.y(); @@ -83,7 +84,7 @@ void DisplayInfoProvider::EnableUnifiedDesktop(bool enable) {} DisplayInfoProvider::DisplayUnitInfoList -DisplayInfoProvider::GetAllDisplaysInfo() { +DisplayInfoProvider::GetAllDisplaysInfo(bool /* single_unified*/) { display::Screen* screen = display::Screen::GetScreen(); int64_t primary_id = screen->GetPrimaryDisplay().id(); std::vector<display::Display> displays = screen->GetAllDisplays();
diff --git a/extensions/browser/api/system_display/display_info_provider.h b/extensions/browser/api/system_display/display_info_provider.h index e0c2a5f8..e6c4db5 100644 --- a/extensions/browser/api/system_display/display_info_provider.h +++ b/extensions/browser/api/system_display/display_info_provider.h
@@ -60,8 +60,10 @@ // Enables the unified desktop feature. virtual void EnableUnifiedDesktop(bool enable); - // Gets display information. - virtual DisplayUnitInfoList GetAllDisplaysInfo(); + // Returns a list of information for all displays. If |single_unified| is + // true, when in unified mode a single display will be returned representing + // the single unified desktop. + virtual DisplayUnitInfoList GetAllDisplaysInfo(bool single_unified); // Gets display layout information. virtual DisplayLayoutList GetDisplayLayout();
diff --git a/extensions/browser/api/system_display/system_display_api.cc b/extensions/browser/api/system_display/system_display_api.cc index c6149a33..66198aca 100644 --- a/extensions/browser/api/system_display/system_display_api.cc +++ b/extensions/browser/api/system_display/system_display_api.cc
@@ -179,8 +179,12 @@ } ExtensionFunction::ResponseAction SystemDisplayGetInfoFunction::Run() { + std::unique_ptr<display::GetInfo::Params> params( + display::GetInfo::Params::Create(*args_)); + bool single_unified = params->flags && params->flags->single_unified && + *params->flags->single_unified; DisplayInfoProvider::DisplayUnitInfoList all_displays_info = - DisplayInfoProvider::Get()->GetAllDisplaysInfo(); + DisplayInfoProvider::Get()->GetAllDisplaysInfo(single_unified); return RespondNow( ArgumentList(display::GetInfo::Results::Create(all_displays_info))); }
diff --git a/extensions/browser/extensions_test.cc b/extensions/browser/extensions_test.cc index e3aaba3..7cec642 100644 --- a/extensions/browser/extensions_test.cc +++ b/extensions/browser/extensions_test.cc
@@ -32,24 +32,21 @@ namespace extensions { -// This class does work in the constructor instead of SetUp() to give subclasses -// a valid BrowserContext to use while initializing their members. For example: -// -// class MyExtensionsTest : public ExtensionsTest { -// MyExtensionsTest() -// : my_object_(browser_context())) { -// } -// }; -// TODO(crbug.com/708256): All these instances are setup in the constructor, but -// destroyed in TearDown(), which may cause problems. Move this initialization -// to SetUp(). -ExtensionsTest::ExtensionsTest() - : content_browser_client_(new TestContentBrowserClient), - content_utility_client_(new TestContentUtilityClient), - browser_context_(new content::TestBrowserContext), - incognito_context_(CreateTestIncognitoContext()), - extensions_browser_client_( - new TestExtensionsBrowserClient(browser_context_.get())) { +ExtensionsTest::ExtensionsTest() {} + +ExtensionsTest::~ExtensionsTest() { + content::SetBrowserClientForTesting(nullptr); + content::SetUtilityClientForTesting(nullptr); +} + +void ExtensionsTest::SetUp() { + content_browser_client_ = base::MakeUnique<TestContentBrowserClient>(); + content_utility_client_ = base::MakeUnique<TestContentUtilityClient>(); + browser_context_ = base::MakeUnique<content::TestBrowserContext>(); + incognito_context_ = CreateTestIncognitoContext(); + extensions_browser_client_ = + base::MakeUnique<TestExtensionsBrowserClient>(browser_context_.get()); + BrowserContextDependencyManager::GetInstance()->MarkBrowserContextLive( browser_context_.get()); content::SetBrowserClientForTesting(content_browser_client_.get()); @@ -78,15 +75,7 @@ ExtensionPrefsFactory::GetInstance()->SetInstanceForTesting( browser_context(), std::move(extension_prefs)); -} -ExtensionsTest::~ExtensionsTest() { - ExtensionsBrowserClient::Set(nullptr); - content::SetBrowserClientForTesting(nullptr); - content::SetUtilityClientForTesting(nullptr); -} - -void ExtensionsTest::SetUp() { // Crashing here? Don't use this class in Chrome's unit_tests. See header. BrowserContextDependencyManager::GetInstance() ->CreateBrowserContextServicesForTest(browser_context_.get()); @@ -99,10 +88,9 @@ BrowserContextDependencyManager::GetInstance()->DestroyBrowserContextServices( browser_context_.get()); - // TODO(crbug.com/708256): |extension_browser_client_| is reset here but not - // unset as the singleton until the destructor. This can lead to use after - // free errors. extensions_browser_client_.reset(); + ExtensionsBrowserClient::Set(nullptr); + browser_context_.reset(); incognito_context_.reset(); pref_service_.reset();
diff --git a/extensions/browser/lazy_background_task_queue_unittest.cc b/extensions/browser/lazy_background_task_queue_unittest.cc index ae2c41b..be75177 100644 --- a/extensions/browser/lazy_background_task_queue_unittest.cc +++ b/extensions/browser/lazy_background_task_queue_unittest.cc
@@ -114,6 +114,7 @@ protected: void SetUp() override { + ExtensionsTest::SetUp(); user_prefs::UserPrefs::Set(browser_context(), &testing_pref_service_); }
diff --git a/extensions/browser/mock_external_provider.cc b/extensions/browser/mock_external_provider.cc index 66e02bc..53d0494 100644 --- a/extensions/browser/mock_external_provider.cc +++ b/extensions/browser/mock_external_provider.cc
@@ -18,9 +18,19 @@ MockExternalProvider::~MockExternalProvider() {} void MockExternalProvider::UpdateOrAddExtension(const ExtensionId& id, - const std::string& version, + const std::string& version_str, const base::FilePath& path) { - extension_map_[id] = std::make_pair(version, path); + auto version = base::MakeUnique<base::Version>(version_str); + auto info = base::MakeUnique<ExternalInstallInfoFile>( + id, std::move(version), path, location_, Extension::NO_FLAGS, false, + false); + extension_map_[id] = std::move(info); +} + +void MockExternalProvider::UpdateOrAddExtension( + std::unique_ptr<ExternalInstallInfoFile> info) { + std::string id = info->extension_id; + extension_map_[id] = std::move(info); } void MockExternalProvider::RemoveExtension(const ExtensionId& id) { @@ -29,15 +39,8 @@ void MockExternalProvider::VisitRegisteredExtension() { visit_count_++; - for (const auto& extension_kv : extension_map_) { - std::unique_ptr<base::Version> version = - base::MakeUnique<base::Version>(extension_kv.second.first); - std::unique_ptr<ExternalInstallInfoFile> info = - base::MakeUnique<ExternalInstallInfoFile>( - extension_kv.first, std::move(version), extension_kv.second.second, - location_, Extension::NO_FLAGS, false, false); - visitor_->OnExternalExtensionFileFound(*info); - } + for (const auto& extension_kv : extension_map_) + visitor_->OnExternalExtensionFileFound(*extension_kv.second); visitor_->OnExternalProviderReady(this); } @@ -54,7 +57,7 @@ return false; if (version) - version->reset(new base::Version(it->second.first)); + version->reset(new base::Version(it->second->version->GetString())); if (location) *location = location_;
diff --git a/extensions/browser/mock_external_provider.h b/extensions/browser/mock_external_provider.h index 7418eda..bc94c4ba 100644 --- a/extensions/browser/mock_external_provider.h +++ b/extensions/browser/mock_external_provider.h
@@ -30,7 +30,7 @@ void UpdateOrAddExtension(const ExtensionId& id, const std::string& version, const base::FilePath& path); - + void UpdateOrAddExtension(std::unique_ptr<ExternalInstallInfoFile> info); void RemoveExtension(const ExtensionId& id); // ExternalProviderInterface implementation: @@ -47,7 +47,8 @@ void set_visit_count(int visit_count) { visit_count_ = visit_count; } private: - using DataMap = std::map<ExtensionId, std::pair<std::string, base::FilePath>>; + using DataMap = + std::map<ExtensionId, std::unique_ptr<ExternalInstallInfoFile>>; DataMap extension_map_; Manifest::Location location_; VisitorInterface* visitor_;
diff --git a/extensions/browser/policy_check_unittest.cc b/extensions/browser/policy_check_unittest.cc index 8b8af30..7d192b4 100644 --- a/extensions/browser/policy_check_unittest.cc +++ b/extensions/browser/policy_check_unittest.cc
@@ -66,16 +66,16 @@ class PolicyCheckTest : public ExtensionsTest { public: - PolicyCheckTest() { - // Replace the MockExtensionSystemFactory set by ExtensionsTest. - extensions_browser_client()->set_extension_system_factory(&factory_); - } + PolicyCheckTest() {} ~PolicyCheckTest() override {} void SetUp() override { ExtensionsTest::SetUp(); + // Replace the MockExtensionSystemFactory set by ExtensionsTest. + extensions_browser_client()->set_extension_system_factory(&factory_); + base::DictionaryValue manifest_dict; manifest_dict.SetString("name", "dummy name"); manifest_dict.SetString("version", "1");
diff --git a/extensions/browser/process_manager_unittest.cc b/extensions/browser/process_manager_unittest.cc index 1bc35076..8057631 100644 --- a/extensions/browser/process_manager_unittest.cc +++ b/extensions/browser/process_manager_unittest.cc
@@ -5,6 +5,7 @@ #include "extensions/browser/process_manager.h" #include "base/macros.h" +#include "base/memory/ptr_util.h" #include "content/public/browser/content_browser_client.h" #include "content/public/browser/notification_service.h" #include "content/public/browser/site_instance.h" @@ -55,16 +56,21 @@ class ProcessManagerTest : public ExtensionsTest { public: - ProcessManagerTest() : extension_registry_(browser_context()) { + ProcessManagerTest() {} + + ~ProcessManagerTest() override {} + + void SetUp() override { + ExtensionsTest::SetUp(); + extension_registry_ = + base::MakeUnique<ExtensionRegistry>(browser_context()); extensions_browser_client()->set_process_manager_delegate( &process_manager_delegate_); } - ~ProcessManagerTest() override {} - // Use original_context() to make it clear it is a non-incognito context. BrowserContext* original_context() { return browser_context(); } - ExtensionRegistry* extension_registry() { return &extension_registry_; } + ExtensionRegistry* extension_registry() { return extension_registry_.get(); } TestProcessManagerDelegate* process_manager_delegate() { return &process_manager_delegate_; } @@ -79,7 +85,8 @@ } private: - ExtensionRegistry extension_registry_; // Shared between BrowserContexts. + std::unique_ptr<ExtensionRegistry> + extension_registry_; // Shared between BrowserContexts. TestProcessManagerDelegate process_manager_delegate_; DISALLOW_COPY_AND_ASSIGN(ProcessManagerTest);
diff --git a/extensions/browser/updater/update_service_unittest.cc b/extensions/browser/updater/update_service_unittest.cc index 402ab02..3c03909 100644 --- a/extensions/browser/updater/update_service_unittest.cc +++ b/extensions/browser/updater/update_service_unittest.cc
@@ -148,10 +148,7 @@ class UpdateServiceTest : public ExtensionsTest { public: - UpdateServiceTest() { - extensions_browser_client()->set_extension_system_factory( - &fake_extension_system_factory_); - } + UpdateServiceTest() {} ~UpdateServiceTest() override {} void SetUp() override { @@ -159,6 +156,8 @@ browser_threads_.reset(new content::TestBrowserThreadBundle( content::TestBrowserThreadBundle::DEFAULT)); + extensions_browser_client()->set_extension_system_factory( + &fake_extension_system_factory_); extensions_browser_client()->SetUpdateClientFactory(base::Bind( &UpdateServiceTest::CreateUpdateClient, base::Unretained(this)));
diff --git a/extensions/common/api/_api_features.json b/extensions/common/api/_api_features.json index 808d979..3c12e67 100644 --- a/extensions/common/api/_api_features.json +++ b/extensions/common/api/_api_features.json
@@ -180,7 +180,7 @@ "contexts": ["blessed_extension"] }, { "internal": true, - "channel": "trunk", + "channel": "stable", "contexts": ["webui"], "matches": [ "chrome://cast/*", @@ -241,7 +241,7 @@ "contexts": ["blessed_extension"], "default_parent": true }, { - "channel": "trunk", + "channel": "stable", "contexts": ["webui"], "matches": [ "chrome://md-settings/*", @@ -519,7 +519,7 @@ "contexts": ["blessed_extension"] }, { "internal": true, - "channel": "dev", + "channel": "stable", "contexts": ["webui"], "matches": [ "chrome://chrome-signin/*",
diff --git a/extensions/common/api/_permission_features.json b/extensions/common/api/_permission_features.json index de72ed4..967f3cb 100644 --- a/extensions/common/api/_permission_features.json +++ b/extensions/common/api/_permission_features.json
@@ -233,7 +233,11 @@ "496B6890097EB6E19809ADEADD095A8721FBB2E0", // FIDO U2F APIs "AD8ED80B705E1818AAD4684F9FF62B43D6D79620", // FIDO U2F APIs (dev) "E24F1786D842E91E74C27929B0B3715A4689A473", // CryptoToken - "A28C9619C4C41306FA5236FB4D94DA812F504DE8" // CryptoToken (dev) + "A28C9619C4C41306FA5236FB4D94DA812F504DE8", // CryptoToken (dev) + "D7CD4B3956B1F6E970E4AFCBCD4094B1EF4D07B9", // http://crbug.com/710541 + "D4EFCCC0CC612380762758BB96C7997224BD6395", // http://crbug.com/710541 + "4839A26B29CD1BD021B2E126EF6D28C9CB84018B", // http://crbug.com/710541 + "8F44FBB4474CCDF23450B166C9E83E85BD03AE24" // http://crbug.com/710541 ] } ], @@ -504,7 +508,11 @@ "496B6890097EB6E19809ADEADD095A8721FBB2E0", // FIDO U2F APIs "AD8ED80B705E1818AAD4684F9FF62B43D6D79620", // FIDO U2F APIs (dev) "E24F1786D842E91E74C27929B0B3715A4689A473", // CryptoToken - "A28C9619C4C41306FA5236FB4D94DA812F504DE8" // CryptoToken (dev) + "A28C9619C4C41306FA5236FB4D94DA812F504DE8", // CryptoToken (dev) + "D7CD4B3956B1F6E970E4AFCBCD4094B1EF4D07B9", // http://crbug.com/710541 + "D4EFCCC0CC612380762758BB96C7997224BD6395", // http://crbug.com/710541 + "4839A26B29CD1BD021B2E126EF6D28C9CB84018B", // http://crbug.com/710541 + "8F44FBB4474CCDF23450B166C9E83E85BD03AE24" // http://crbug.com/710541 ] } ],
diff --git a/extensions/common/api/system_display.idl b/extensions/common/api/system_display.idl index 6a1a921..1674d1b 100644 --- a/extensions/common/api/system_display.idl +++ b/extensions/common/api/system_display.idl
@@ -129,6 +129,10 @@ // True if this display is enabled. boolean isEnabled; + // True for all displays when in unified desktop mode. See documentation + // for $(ref:enableUnifiedDesktop). + boolean isUnified; + // The number of pixels per inch along the x-axis. double dpiX; @@ -163,6 +167,13 @@ }; dictionary DisplayProperties { + // Chrome OS only. If set to true, changes the display mode to unified + // desktop (see $(ref:enableUnifiedDesktop) for details). If set to false, + // unified desktop mode will be disabled. This is only valid for the + // primary display. If provided, mirroringSourceId must not be provided and + // other properties may not apply. This is has no effect if not provided. + boolean? isUnified; + // Chrome OS only. If set and not empty, enables mirroring for this display. // Otherwise disables mirroring for this display. This value should indicate // the id of the source display to mirror, which must not be the same as the @@ -203,6 +214,13 @@ DisplayMode? displayMode; }; + dictionary GetInfoFlags { + // If set to true, only a single $(ref:DisplayUnitInfo) will be returned + // by $(ref:getInfo) when in unified desktop mode (see + // $(ref:enableUnifiedDesktop)). Defaults to false. + boolean? singleUnified; + }; + callback DisplayInfoCallback = void (DisplayUnitInfo[] displayInfo); callback DisplayLayoutCallback = void (DisplayLayout[] layouts); callback SetDisplayUnitInfoCallback = void(); @@ -210,11 +228,15 @@ callback NativeTouchCalibrationCallback = void(boolean success); interface Functions { - // Get the information of all attached display devices. - static void getInfo(DisplayInfoCallback callback); + // Requests the information for all attached display devices. + // |flags|: Options affecting how the information is returned. + // |callback|: The callback to invoke with the results. + static void getInfo(optional GetInfoFlags flags, + DisplayInfoCallback callback); - // Get the layout info for all displays. + // Requests the layout info for all displays. // NOTE: This is only available to Chrome OS Kiosk apps and Web UI. + // |callback|: The callback to invoke with the results. static void getDisplayLayout(DisplayLayoutCallback callback); // Updates the properties for the display specified by |id|, according to
diff --git a/extensions/common/extension_l10n_util_unittest.cc b/extensions/common/extension_l10n_util_unittest.cc index 81d7d78f..abe80f2 100644 --- a/extensions/common/extension_l10n_util_unittest.cc +++ b/extensions/common/extension_l10n_util_unittest.cc
@@ -39,7 +39,8 @@ base::FilePath messages_file = locale.Append(kMessagesFilename); std::string data = "{ \"name\":"; - ASSERT_TRUE(base::WriteFile(messages_file, data.c_str(), data.length())); + ASSERT_EQ(static_cast<int>(data.length()), + base::WriteFile(messages_file, data.c_str(), data.length())); base::DictionaryValue manifest; manifest.SetString(keys::kDefaultLocale, "en"); @@ -92,8 +93,9 @@ base::FilePath locale_1 = src_path.AppendASCII("sr"); ASSERT_TRUE(base::CreateDirectory(locale_1)); std::string data("whatever"); - ASSERT_TRUE(base::WriteFile( - locale_1.Append(kMessagesFilename), data.c_str(), data.length())); + ASSERT_EQ(static_cast<int>(data.length()), + base::WriteFile(locale_1.Append(kMessagesFilename), data.c_str(), + data.length())); // Unsupported locale. ASSERT_TRUE(base::CreateDirectory(src_path.AppendASCII("xxx_yyy"))); @@ -165,7 +167,8 @@ std::string data = "{ \"name\":"; base::FilePath messages_file = locale.Append(kMessagesFilename); - ASSERT_TRUE(base::WriteFile(messages_file, data.c_str(), data.length())); + ASSERT_EQ(static_cast<int>(data.length()), + base::WriteFile(messages_file, data.c_str(), data.length())); std::string error; EXPECT_TRUE(NULL == extension_l10n_util::LoadMessageCatalogs( @@ -190,14 +193,16 @@ std::string data = "{ \"name\": { \"message\": \"something\" }, " "\"name\": { \"message\": \"something else\" } }"; - ASSERT_TRUE(base::WriteFile( - locale_1.Append(kMessagesFilename), data.c_str(), data.length())); + ASSERT_EQ(static_cast<int>(data.length()), + base::WriteFile(locale_1.Append(kMessagesFilename), data.c_str(), + data.length())); base::FilePath locale_2 = src_path.AppendASCII("sr"); ASSERT_TRUE(base::CreateDirectory(locale_2)); - ASSERT_TRUE(base::WriteFile( - locale_2.Append(kMessagesFilename), data.c_str(), data.length())); + ASSERT_EQ(static_cast<int>(data.length()), + base::WriteFile(locale_2.Append(kMessagesFilename), data.c_str(), + data.length())); std::string error; // JSON parser hides duplicates. We are going to get only one key/value
diff --git a/extensions/common/extension_resource_unittest.cc b/extensions/common/extension_resource_unittest.cc index 27bd56c..659d7f1d 100644 --- a/extensions/common/extension_resource_unittest.cc +++ b/extensions/common/extension_resource_unittest.cc
@@ -58,8 +58,8 @@ ASSERT_TRUE(base::CreateDirectory(sub_dir)); base::FilePath inner_file = inner_dir.AppendASCII("inner"); base::FilePath outer_file = temp.GetPath().AppendASCII("outer"); - ASSERT_TRUE(base::WriteFile(outer_file, "X", 1)); - ASSERT_TRUE(base::WriteFile(inner_file, "X", 1)); + ASSERT_EQ(1, base::WriteFile(outer_file, "X", 1)); + ASSERT_EQ(1, base::WriteFile(inner_file, "X", 1)); std::string extension_id = crx_file::id_util::GenerateId("test"); #if defined(OS_POSIX) @@ -126,7 +126,8 @@ const char* filename = "res.ico"; base::FilePath root_resource = temp.GetPath().AppendASCII(filename); std::string data = "some foo"; - ASSERT_TRUE(base::WriteFile(root_resource, data.c_str(), data.length())); + ASSERT_EQ(static_cast<int>(data.length()), + base::WriteFile(root_resource, data.c_str(), data.length())); // Create l10n resources (for current locale and its parents). base::FilePath l10n_path = temp.GetPath().Append(kLocaleFolder); @@ -140,8 +141,9 @@ base::FilePath make_path; make_path = l10n_path.AppendASCII(locales[i]); ASSERT_TRUE(base::CreateDirectory(make_path)); - ASSERT_TRUE(base::WriteFile(make_path.AppendASCII(filename), - data.c_str(), data.length())); + ASSERT_EQ(static_cast<int>(data.length()), + base::WriteFile(make_path.AppendASCII(filename), data.c_str(), + data.length())); } base::FilePath path;
diff --git a/extensions/common/features/simple_feature.cc b/extensions/common/features/simple_feature.cc index d901cd9..bb5aa6a8 100644 --- a/extensions/common/features/simple_feature.cc +++ b/extensions/common/features/simple_feature.cc
@@ -164,8 +164,8 @@ return display_name_list; } -bool IsCommandLineSwitchEnabled(const std::string& switch_name) { - base::CommandLine* command_line = base::CommandLine::ForCurrentProcess(); +bool IsCommandLineSwitchEnabled(base::CommandLine* command_line, + const std::string& switch_name) { if (command_line->HasSwitch(switch_name + "=1")) return true; if (command_line->HasSwitch(std::string("enable-") + switch_name)) @@ -215,55 +215,15 @@ Manifest::Location location, int manifest_version, Platform platform) const { - // Check extension type first to avoid granting platform app permissions - // to component extensions. - // HACK(kalman): user script -> extension. Solve this in a more generic way - // when we compile feature files. - Manifest::Type type_to_check = (type == Manifest::TYPE_USER_SCRIPT) ? - Manifest::TYPE_EXTENSION : type; - if (!extension_types_.empty() && - !base::ContainsValue(extension_types_, type_to_check)) { - return CreateAvailability(INVALID_TYPE, type); - } - - if (IsIdInBlacklist(extension_id)) - return CreateAvailability(FOUND_IN_BLACKLIST, type); - - // TODO(benwells): don't grant all component extensions. - // See http://crbug.com/370375 for more details. - // Component extensions can access any feature. - // NOTE: Deliberately does not match EXTERNAL_COMPONENT. - if (component_extensions_auto_granted_ && location == Manifest::COMPONENT) - return CreateAvailability(IS_AVAILABLE, type); - - if (!whitelist_.empty() && !IsIdInWhitelist(extension_id) && - !IsWhitelistedForTest(extension_id)) { - return CreateAvailability(NOT_FOUND_IN_WHITELIST, type); - } - - if (!MatchesManifestLocation(location)) - return CreateAvailability(INVALID_LOCATION, type); - - if (!platforms_.empty() && !base::ContainsValue(platforms_, platform)) - return CreateAvailability(INVALID_PLATFORM, type); - - if (min_manifest_version_ != 0 && manifest_version < min_manifest_version_) - return CreateAvailability(INVALID_MIN_MANIFEST_VERSION, type); - - if (max_manifest_version_ != 0 && manifest_version > max_manifest_version_) - return CreateAvailability(INVALID_MAX_MANIFEST_VERSION, type); - - if (!command_line_switch_.empty() && - !IsCommandLineSwitchEnabled(command_line_switch_)) { - return CreateAvailability(MISSING_COMMAND_LINE_SWITCH, type); - } - - if (channel_ && *channel_ < GetCurrentChannel()) - return CreateAvailability(UNSUPPORTED_CHANNEL, *channel_); - - const FeatureSessionType session_type = GetCurrentFeatureSessionType(); - if (!MatchesSessionTypes(session_type)) - return CreateAvailability(INVALID_SESSION_TYPE, session_type); + Availability environment_availability = GetEnvironmentAvailability( + platform, GetCurrentChannel(), GetCurrentFeatureSessionType(), + base::CommandLine::ForCurrentProcess()); + if (!environment_availability.is_available()) + return environment_availability; + Availability manifest_availability = + GetManifestAvailability(extension_id, type, location, manifest_version); + if (!manifest_availability.is_available()) + return manifest_availability; return CheckDependencies(base::Bind(&IsAvailableToManifestForBind, extension_id, @@ -277,36 +237,24 @@ const Extension* extension, Feature::Context context, const GURL& url, - SimpleFeature::Platform platform) const { + Platform platform) const { + Availability environment_availability = GetEnvironmentAvailability( + platform, GetCurrentChannel(), GetCurrentFeatureSessionType(), + base::CommandLine::ForCurrentProcess()); + if (!environment_availability.is_available()) + return environment_availability; + if (extension) { - Availability result = IsAvailableToManifest(extension->id(), - extension->GetType(), - extension->location(), - extension->manifest_version(), - platform); - if (!result.is_available()) - return result; + Availability manifest_availability = GetManifestAvailability( + extension->id(), extension->GetType(), extension->location(), + extension->manifest_version()); + if (!manifest_availability.is_available()) + return manifest_availability; } - // TODO(lazyboy): This isn't quite right for Extension Service Worker - // extension API calls, since there's no guarantee that the extension is - // "active" in current renderer process when the API permission check is - // done. - if (!contexts_.empty() && !base::ContainsValue(contexts_, context)) - return CreateAvailability(INVALID_CONTEXT, context); - - // TODO(kalman): Consider checking |matches_| regardless of context type. - // Fewer surprises, and if the feature configuration wants to isolate - // "matches" from say "blessed_extension" then they can use complex features. - if ((context == WEB_PAGE_CONTEXT || context == WEBUI_CONTEXT) && - !matches_.MatchesURL(url)) { - return CreateAvailability(INVALID_URL, url); - } - - const FeatureSessionType session_type = GetCurrentFeatureSessionType(); - if (!MatchesSessionTypes(session_type)) { - return CreateAvailability(INVALID_SESSION_TYPE, session_type); - } + Availability context_availability = GetContextAvailability(context, url); + if (!context_availability.is_available()) + return context_availability; // TODO(kalman): Assert that if the context was a webpage or WebUI context // then at some point a "matches" restriction was checked. @@ -579,4 +527,90 @@ whitelist_.assign(whitelist.begin(), whitelist.end()); } +Feature::Availability SimpleFeature::GetEnvironmentAvailability( + Platform platform, + version_info::Channel channel, + FeatureSessionType session_type, + base::CommandLine* command_line) const { + if (!platforms_.empty() && !base::ContainsValue(platforms_, platform)) + return CreateAvailability(INVALID_PLATFORM); + + if (channel_ && *channel_ < GetCurrentChannel()) + return CreateAvailability(UNSUPPORTED_CHANNEL, *channel_); + + if (!command_line_switch_.empty() && + !IsCommandLineSwitchEnabled(command_line, command_line_switch_)) { + return CreateAvailability(MISSING_COMMAND_LINE_SWITCH); + } + + if (!MatchesSessionTypes(session_type)) + return CreateAvailability(INVALID_SESSION_TYPE, session_type); + + return CreateAvailability(IS_AVAILABLE); +} + +Feature::Availability SimpleFeature::GetManifestAvailability( + const std::string& extension_id, + Manifest::Type type, + Manifest::Location location, + int manifest_version) const { + // Check extension type first to avoid granting platform app permissions + // to component extensions. + // HACK(kalman): user script -> extension. Solve this in a more generic way + // when we compile feature files. + Manifest::Type type_to_check = + (type == Manifest::TYPE_USER_SCRIPT) ? Manifest::TYPE_EXTENSION : type; + if (!extension_types_.empty() && + !base::ContainsValue(extension_types_, type_to_check)) { + return CreateAvailability(INVALID_TYPE, type); + } + + if (IsIdInBlacklist(extension_id)) + return CreateAvailability(FOUND_IN_BLACKLIST); + + // TODO(benwells): don't grant all component extensions. + // See http://crbug.com/370375 for more details. + // Component extensions can access any feature. + // NOTE: Deliberately does not match EXTERNAL_COMPONENT. + if (component_extensions_auto_granted_ && location == Manifest::COMPONENT) + return CreateAvailability(IS_AVAILABLE); + + if (!whitelist_.empty() && !IsIdInWhitelist(extension_id) && + !IsWhitelistedForTest(extension_id)) { + return CreateAvailability(NOT_FOUND_IN_WHITELIST); + } + + if (!MatchesManifestLocation(location)) + return CreateAvailability(INVALID_LOCATION); + + if (min_manifest_version_ != 0 && manifest_version < min_manifest_version_) + return CreateAvailability(INVALID_MIN_MANIFEST_VERSION); + + if (max_manifest_version_ != 0 && manifest_version > max_manifest_version_) + return CreateAvailability(INVALID_MAX_MANIFEST_VERSION); + + return CreateAvailability(IS_AVAILABLE); +} + +Feature::Availability SimpleFeature::GetContextAvailability( + Feature::Context context, + const GURL& url) const { + // TODO(lazyboy): This isn't quite right for Extension Service Worker + // extension API calls, since there's no guarantee that the extension is + // "active" in current renderer process when the API permission check is + // done. + if (!contexts_.empty() && !base::ContainsValue(contexts_, context)) + return CreateAvailability(INVALID_CONTEXT, context); + + // TODO(kalman): Consider checking |matches_| regardless of context type. + // Fewer surprises, and if the feature configuration wants to isolate + // "matches" from say "blessed_extension" then they can use complex features. + if ((context == WEB_PAGE_CONTEXT || context == WEBUI_CONTEXT) && + !matches_.MatchesURL(url)) { + return CreateAvailability(INVALID_URL, url); + } + + return CreateAvailability(IS_AVAILABLE); +} + } // namespace extensions
diff --git a/extensions/common/features/simple_feature.h b/extensions/common/features/simple_feature.h index 343282e..13199e86 100644 --- a/extensions/common/features/simple_feature.h +++ b/extensions/common/features/simple_feature.h
@@ -24,6 +24,10 @@ #include "extensions/common/features/feature_session_type.h" #include "extensions/common/manifest.h" +namespace base { +class CommandLine; +} + namespace extensions { class FeatureProviderTest; @@ -215,6 +219,24 @@ static bool IsValidExtensionId(const std::string& extension_id); + // Returns the availability of the feature with respect to the basic + // environment Chrome is running in. + Availability GetEnvironmentAvailability( + Platform platform, + version_info::Channel channel, + FeatureSessionType session_type, + base::CommandLine* command_line) const; + + // Returns the availability of the feature with respect to a given extension's + // properties. + Availability GetManifestAvailability(const std::string& extension_id, + Manifest::Type type, + Manifest::Location location, + int manifest_version) const; + + // Returns the availability of the feature with respect to a given context. + Availability GetContextAvailability(Context context, const GURL& url) const; + // For clarity and consistency, we handle the default value of each of these // members the same way: it matches everything. It is up to the higher level // code that reads Features out of static data to validate that data and set
diff --git a/extensions/common/features/simple_feature_unittest.cc b/extensions/common/features/simple_feature_unittest.cc index a570248..f446042 100644 --- a/extensions/common/features/simple_feature_unittest.cc +++ b/extensions/common/features/simple_feature_unittest.cc
@@ -860,4 +860,34 @@ } } +TEST(SimpleFeatureUnitTest, TestChannelsWithoutExtension) { + // Create a webui feature available on trunk. + SimpleFeature feature; + feature.set_contexts({Feature::WEBUI_CONTEXT}); + feature.set_matches({"chrome://settings/*"}); + feature.set_channel(version_info::Channel::UNKNOWN); + + const GURL kWhitelistedUrl("chrome://settings/foo"); + const GURL kOtherUrl("https://example.com"); + + { + // It should be available on trunk. + ScopedCurrentChannel current_channel(Channel::UNKNOWN); + EXPECT_EQ(Feature::IS_AVAILABLE, + feature + .IsAvailableToContext(nullptr, Feature::WEBUI_CONTEXT, + kWhitelistedUrl) + .result()); + } + { + // It should be unavailable on beta. + ScopedCurrentChannel current_channel(Channel::BETA); + EXPECT_EQ(Feature::UNSUPPORTED_CHANNEL, + feature + .IsAvailableToContext(nullptr, Feature::WEBUI_CONTEXT, + kWhitelistedUrl) + .result()); + } +} + } // namespace extensions
diff --git a/extensions/common/file_util_unittest.cc b/extensions/common/file_util_unittest.cc index 4aea12c..c1bba33 100644 --- a/extensions/common/file_util_unittest.cc +++ b/extensions/common/file_util_unittest.cc
@@ -152,8 +152,9 @@ ASSERT_TRUE(base::CreateDirectory(src_path)); std::string data = "{ \"name\": { \"message\": \"foobar\" } }"; - ASSERT_TRUE(base::WriteFile( - src_path.AppendASCII("some_file.txt"), data.c_str(), data.length())); + ASSERT_EQ(static_cast<int>(data.length()), + base::WriteFile(src_path.AppendASCII("some_file.txt"), data.c_str(), + data.length())); std::string error; EXPECT_TRUE(file_util::CheckForIllegalFilenames(temp.GetPath(), &error)); } @@ -213,8 +214,9 @@ ASSERT_TRUE(base::CreateDirectory(src_path)); std::string data = "{ \"name\": { \"message\": \"foobar\" } }"; - ASSERT_TRUE(base::WriteFile(src_path.AppendASCII("lpt1.txt"), data.c_str(), - data.length())); + ASSERT_EQ(static_cast<int>(data.length()), + base::WriteFile(src_path.AppendASCII("lpt1.txt"), data.c_str(), + data.length())); std::string error; EXPECT_FALSE( @@ -350,19 +352,20 @@ base::FilePath src_path = temp.GetPath().AppendASCII("some_dir"); ASSERT_TRUE(base::CreateDirectory(src_path)); - ASSERT_TRUE(base::WriteFile( - src_path.AppendASCII("a_key.pem"), private_key, arraysize(private_key))); - ASSERT_TRUE(base::WriteFile(src_path.AppendASCII("second_key.pem"), - private_key, - arraysize(private_key))); + ASSERT_EQ(static_cast<int>(arraysize(private_key)), + base::WriteFile(src_path.AppendASCII("a_key.pem"), private_key, + arraysize(private_key))); + ASSERT_EQ(static_cast<int>(arraysize(private_key)), + base::WriteFile(src_path.AppendASCII("second_key.pem"), private_key, + arraysize(private_key))); // Shouldn't find a key with a different extension. - ASSERT_TRUE(base::WriteFile(src_path.AppendASCII("key.diff_ext"), - private_key, - arraysize(private_key))); + ASSERT_EQ(static_cast<int>(arraysize(private_key)), + base::WriteFile(src_path.AppendASCII("key.diff_ext"), private_key, + arraysize(private_key))); // Shouldn't find a key that isn't parsable. - ASSERT_TRUE(base::WriteFile(src_path.AppendASCII("unparsable_key.pem"), - private_key, - arraysize(private_key) - 30)); + ASSERT_EQ(static_cast<int>(arraysize(private_key)) - 30, + base::WriteFile(src_path.AppendASCII("unparsable_key.pem"), + private_key, arraysize(private_key) - 30)); std::vector<base::FilePath> private_keys = file_util::FindPrivateKeyFiles(temp.GetPath()); EXPECT_EQ(2U, private_keys.size()); @@ -386,10 +389,12 @@ " \"manifest_version\": 2,\n" " \"description\": \"The first extension that I made.\"\n" "}\n"; - ASSERT_TRUE(base::WriteFile( - ext_path.AppendASCII("manifest.json"), manifest, strlen(manifest))); - ASSERT_TRUE(base::WriteFile( - ext_path.AppendASCII("a_key.pem"), private_key, strlen(private_key))); + ASSERT_EQ(static_cast<int>(strlen(manifest)), + base::WriteFile(ext_path.AppendASCII("manifest.json"), manifest, + strlen(manifest))); + ASSERT_EQ(static_cast<int>(strlen(private_key)), + base::WriteFile(ext_path.AppendASCII("a_key.pem"), private_key, + strlen(private_key))); std::string error; scoped_refptr<Extension> extension(
diff --git a/extensions/renderer/argument_spec.cc b/extensions/renderer/argument_spec.cc index 1836714..da9b4e7 100644 --- a/extensions/renderer/argument_spec.cc +++ b/extensions/renderer/argument_spec.cc
@@ -92,6 +92,20 @@ if (dict->GetInteger("minimum", &min)) minimum_ = min; + int min_length = 0; + if (dict->GetInteger("minLength", &min_length) || + dict->GetInteger("minItems", &min_length)) { + DCHECK_GE(min_length, 0); + min_length_ = min_length; + } + + int max_length = 0; + if (dict->GetInteger("maxLength", &max_length) || + dict->GetInteger("maxItems", &max_length)) { + DCHECK_GE(max_length, 0); + max_length_ = max_length; + } + if (type_ == ArgumentType::OBJECT) { const base::DictionaryValue* properties_value = nullptr; if (dict->GetDictionary("properties", &properties_value)) { @@ -234,6 +248,19 @@ case ArgumentType::STRING: { if (!value->IsString()) return false; + + v8::Local<v8::String> v8_string = value.As<v8::String>(); + size_t length = static_cast<size_t>(v8_string->Length()); + if (min_length_ && length < *min_length_) { + *error = "Less than min length"; + return false; + } + + if (max_length_ && length > *max_length_) { + *error = "Greater than max length"; + return false; + } + // If we don't need to match enum values and don't need to convert, we're // done... if (!out_value && enum_values_.empty()) @@ -392,11 +419,23 @@ std::unique_ptr<base::Value>* out_value, std::string* error) const { DCHECK_EQ(ArgumentType::LIST, type_); + + uint32_t length = value->Length(); + if (min_length_ && length < *min_length_) { + *error = "Less than min length"; + return false; + } + + if (max_length_ && length > *max_length_) { + *error = "Greater than max length"; + return false; + } + std::unique_ptr<base::ListValue> result; // Only construct the result if we have an |out_value| to populate. if (out_value) result = base::MakeUnique<base::ListValue>(); - uint32_t length = value->Length(); + for (uint32_t i = 0; i < length; ++i) { v8::MaybeLocal<v8::Value> maybe_subvalue = value->Get(context, i); v8::Local<v8::Value> subvalue;
diff --git a/extensions/renderer/argument_spec.h b/extensions/renderer/argument_spec.h index 39af8d31..f264e25e 100644 --- a/extensions/renderer/argument_spec.h +++ b/extensions/renderer/argument_spec.h
@@ -134,6 +134,12 @@ // A minimum, if any. base::Optional<int> minimum_; + // A minimium length for strings or arrays. + base::Optional<size_t> min_length_; + + // A maximum length for strings or arrays. + base::Optional<size_t> max_length_; + // A map of required properties; present only for objects. Note that any // properties *not* defined in this map will be dropped during conversion. std::map<std::string, std::unique_ptr<ArgumentSpec>> properties_;
diff --git a/extensions/renderer/argument_spec_unittest.cc b/extensions/renderer/argument_spec_unittest.cc index a580a74..5cf0706 100644 --- a/extensions/renderer/argument_spec_unittest.cc +++ b/extensions/renderer/argument_spec_unittest.cc
@@ -210,6 +210,10 @@ ExpectFailure(spec, "'foo'"); ExpectFailure(spec, "[1, 2]"); ExpectFailure(spec, "['foo', 1]"); + ExpectFailure(spec, + "var x = ['a', 'b', 'c'];" + "x[4] = 'd';" // x[3] is undefined, violating the spec. + "x;"); ExpectThrow( spec, "var x = [];" @@ -598,4 +602,44 @@ } } +TEST_F(ArgumentSpecUnitTest, MinAndMaxLengths) { + { + const char kMinLengthString[] = "{'type': 'string', 'minLength': 3}"; + ArgumentSpec spec(*ValueFromString(kMinLengthString)); + ExpectSuccess(spec, "'aaa'", "'aaa'"); + ExpectSuccess(spec, "'aaaa'", "'aaaa'"); + ExpectFailure(spec, "'aa'"); + ExpectFailure(spec, "''"); + } + + { + const char kMaxLengthString[] = "{'type': 'string', 'maxLength': 3}"; + ArgumentSpec spec(*ValueFromString(kMaxLengthString)); + ExpectSuccess(spec, "'aaa'", "'aaa'"); + ExpectSuccess(spec, "'aa'", "'aa'"); + ExpectSuccess(spec, "''", "''"); + ExpectFailure(spec, "'aaaa'"); + } + + { + const char kMinLengthArray[] = + "{'type': 'array', 'items': {'type': 'integer'}, 'minItems': 3}"; + ArgumentSpec spec(*ValueFromString(kMinLengthArray)); + ExpectSuccess(spec, "[1, 2, 3]", "[1,2,3]"); + ExpectSuccess(spec, "[1, 2, 3, 4]", "[1,2,3,4]"); + ExpectFailure(spec, "[1, 2]"); + ExpectFailure(spec, "[]"); + } + + { + const char kMaxLengthArray[] = + "{'type': 'array', 'items': {'type': 'integer'}, 'maxItems': 3}"; + ArgumentSpec spec(*ValueFromString(kMaxLengthArray)); + ExpectSuccess(spec, "[1, 2, 3]", "[1,2,3]"); + ExpectSuccess(spec, "[1, 2]", "[1,2]"); + ExpectSuccess(spec, "[]", "[]"); + ExpectFailure(spec, "[1, 2, 3, 4]"); + } +} + } // namespace extensions
diff --git a/gpu/ipc/service/direct_composition_surface_win.cc b/gpu/ipc/service/direct_composition_surface_win.cc index a28ad40..c6b5737 100644 --- a/gpu/ipc/service/direct_composition_surface_win.cc +++ b/gpu/ipc/service/direct_composition_surface_win.cc
@@ -7,6 +7,7 @@ #include <d3d11_1.h> #include <dcomptypes.h> +#include "base/feature_list.h" #include "base/memory/ptr_util.h" #include "base/metrics/histogram_macros.h" #include "base/optional.h" @@ -18,6 +19,7 @@ #include "gpu/ipc/service/gpu_channel_manager_delegate.h" #include "gpu/ipc/service/switches.h" #include "ui/display/display_switches.h" +#include "ui/gfx/color_space_win.h" #include "ui/gfx/geometry/size_conversions.h" #include "ui/gfx/native_widget_types.h" #include "ui/gfx/transform.h" @@ -42,6 +44,11 @@ namespace gpu { namespace { +// Some drivers fail to correctly handle BT.709 video in overlays. This flag +// converts them to BT.601 in the video processor. +const base::Feature kFallbackBT709VideoToBT601{ + "FallbackBT709VideoToBT601", base::FEATURE_DISABLED_BY_DEFAULT}; + // This class is used to make sure a specified surface isn't current, and upon // destruction it will make the surface current again if it had been before. class ScopedReleaseCurrent { @@ -179,6 +186,7 @@ gfx::Size swap_chain_size_; gfx::Size processor_input_size_; gfx::Size processor_output_size_; + bool is_yuy2_swapchain_ = false; // This is the scale from the swapchain size to the size of the contents // onscreen. @@ -327,6 +335,47 @@ out_view_.Receive()); CHECK(SUCCEEDED(hr)); } + + // TODO(jbauman): Use correct colorspace. + gfx::ColorSpace src_color_space = gfx::ColorSpace::CreateREC709(); + base::win::ScopedComPtr<ID3D11VideoContext1> context1; + if (SUCCEEDED(video_context_.QueryInterface(context1.Receive()))) { + context1->VideoProcessorSetStreamColorSpace1( + video_processor_.get(), 0, + gfx::ColorSpaceWin::GetDXGIColorSpace(src_color_space)); + } else { + // This can't handle as many different types of color spaces, so use it + // only if ID3D11VideoContext1 isn't available. + D3D11_VIDEO_PROCESSOR_COLOR_SPACE color_space = + gfx::ColorSpaceWin::GetD3D11ColorSpace(src_color_space); + video_context_->VideoProcessorSetStreamColorSpace(video_processor_.get(), 0, + &color_space); + } + + gfx::ColorSpace output_color_space = + is_yuy2_swapchain_ ? src_color_space : gfx::ColorSpace::CreateSRGB(); + if (base::FeatureList::IsEnabled(kFallbackBT709VideoToBT601) && + (output_color_space == gfx::ColorSpace::CreateREC709())) { + output_color_space = gfx::ColorSpace::CreateREC601(); + } + + base::win::ScopedComPtr<IDXGISwapChain3> swap_chain3; + if (SUCCEEDED(swap_chain_.QueryInterface(swap_chain3.Receive()))) { + DXGI_COLOR_SPACE_TYPE color_space = + gfx::ColorSpaceWin::GetDXGIColorSpace(output_color_space); + HRESULT hr = swap_chain3->SetColorSpace1(color_space); + CHECK(SUCCEEDED(hr)); + if (context1) { + context1->VideoProcessorSetOutputColorSpace1(video_processor_.get(), + color_space); + } else { + D3D11_VIDEO_PROCESSOR_COLOR_SPACE d3d11_color_space = + gfx::ColorSpaceWin::GetD3D11ColorSpace(output_color_space); + video_context_->VideoProcessorSetOutputColorSpace(video_processor_.get(), + &d3d11_color_space); + } + } + { D3D11_VIDEO_PROCESSOR_INPUT_VIEW_DESC in_desc = {}; in_desc.ViewDimension = D3D11_VPIV_DIMENSION_TEXTURE2D; @@ -426,37 +475,28 @@ &handle); swap_chain_handle_.Set(handle); + is_yuy2_swapchain_ = true; // The composition surface handle isn't actually used, but // CreateSwapChainForComposition can't create YUY2 swapchains. HRESULT hr = media_factory->CreateSwapChainForCompositionSurfaceHandle( d3d11_device_.get(), swap_chain_handle_.Get(), &desc, nullptr, swap_chain_.Receive()); - bool yuy2_swapchain = true; - if (FAILED(hr)) { // This should not be hit in production but is a simple fallback for // testing on systems without YUY2 swapchain support. DLOG(ERROR) << "YUY2 creation failed with " << std::hex << hr << ". Falling back to BGRA"; + is_yuy2_swapchain_ = false; desc.Format = DXGI_FORMAT_B8G8R8A8_UNORM; desc.Flags = 0; hr = media_factory->CreateSwapChainForCompositionSurfaceHandle( d3d11_device_.get(), swap_chain_handle_.Get(), &desc, nullptr, swap_chain_.Receive()); CHECK(SUCCEEDED(hr)); - yuy2_swapchain = false; - } else { - // This is a sensible default colorspace for most videos. - // TODO(jbauman): Use correct colorspace. - base::win::ScopedComPtr<IDXGISwapChain3> swap_chain3; - swap_chain_.QueryInterface(swap_chain3.Receive()); - hr = swap_chain3->SetColorSpace1( - DXGI_COLOR_SPACE_YCBCR_STUDIO_G22_LEFT_P709); - CHECK(SUCCEEDED(hr)); } UMA_HISTOGRAM_BOOLEAN("GPU.DirectComposition.SwapchainFormat", - yuy2_swapchain); + is_yuy2_swapchain_); out_view_.Reset(); }
diff --git a/infra/config/cq.cfg b/infra/config/cq.cfg index 7cfb95a..903732636 100644 --- a/infra/config/cq.cfg +++ b/infra/config/cq.cfg
@@ -34,9 +34,19 @@ try_job { buckets { name: "luci.chromium.try" + # Builders in this bucket are defined in + # https://chromium.googlesource.com/chromium/src/+/infra/config/cr-buildbucket.cfg builders { name: "LUCI linux_chromium_rel_ng" - experiment_percentage: 1 + experiment_percentage: 5 + } + builders { + name: "LUCI mac_chromium_rel_ng" + experiment_percentage: 5 + } + builders { + name: "LUCI win_chromium_rel_ng" + experiment_percentage: 5 } } buckets {
diff --git a/ios/build/bots/scripts/test_runner.py b/ios/build/bots/scripts/test_runner.py index 69b81820..5f1b538 100644 --- a/ios/build/bots/scripts/test_runner.py +++ b/ios/build/bots/scripts/test_runner.py
@@ -351,9 +351,8 @@ else: raise - # Retry failed test cases. Currently, XCTests don't support retries - # because there are no arguments to select specific tests to run. - if self.retries and failed and not self.xctest_path: + # Retry failed test cases. + if self.retries and failed: print '%s tests failed and will be retried.' % len(failed) print for i in xrange(self.retries):
diff --git a/ios/chrome/browser/passwords/password_controller_unittest.mm b/ios/chrome/browser/passwords/password_controller_unittest.mm index 7e45473..9a6ddbd 100644 --- a/ios/chrome/browser/passwords/password_controller_unittest.mm +++ b/ios/chrome/browser/passwords/password_controller_unittest.mm
@@ -749,6 +749,49 @@ " }" "}; result"; +// Test html content and expected result for __gCrWeb.hasPasswordField call. +struct TestDataForPasswordFormDetection { + NSString* page_content; + BOOL contains_password; +}; + +// Tests that the existence of (or the lack of) a password field in the page is +// detected correctly. +TEST_F(PasswordControllerTest, HasPasswordField) { + TestDataForPasswordFormDetection test_data[] = { + // Form without a password field. + {@"<form><input type='text' name='password'></form>", NO}, + // Form with a password field. + {@"<form><input type='password' name='password'></form>", YES}}; + for (size_t i = 0; i < arraysize(test_data); i++) { + TestDataForPasswordFormDetection& data = test_data[i]; + LoadHtml(data.page_content); + id result = ExecuteJavaScript(@"__gCrWeb.hasPasswordField()"); + EXPECT_NSEQ(@(data.contains_password), result) + << " in test " << i << ": " + << base::SysNSStringToUTF8(data.page_content); + } +} + +// Tests that the existence a password field in a nested iframe/ is detected +// correctly. +TEST_F(PasswordControllerTest, HasPasswordFieldinFrame) { + TestDataForPasswordFormDetection data = { + // Form with a password field in a nested iframe. + @"<iframe name='pf'></iframe>" + "<script>" + " var doc = frames['pf'].document.open();" + " doc.write('<form><input type=\\'password\\'></form>');" + " doc.close();" + "</script>", + YES + }; + LoadHtml(data.page_content); + id result = ExecuteJavaScript(@"__gCrWeb.hasPasswordField()"); + EXPECT_NSEQ(@(data.contains_password), result) + << base::SysNSStringToUTF8(data.page_content); +} + struct FillPasswordFormTestData { const std::string origin; const std::string action; @@ -760,10 +803,14 @@ NSString* expected_result; }; -// Test that filling password forms works correctly. +// Tests that filling password forms works correctly. TEST_F(PasswordControllerTest, FillPasswordForm) { LoadHtml(kHtmlWithMultiplePasswordForms); + // TODO(crbug.com/614092): can we remove this assertion? This call is the only + // reason why hasPasswordField is a public API on gCrWeb. If the page does + // not contain a password field, shouldn't one of the expectations of the + // remaining tests also fail? EXPECT_NSEQ(@YES, ExecuteJavaScript(@"__gCrWeb.hasPasswordField()")); const std::string base_url = BaseUrl();
diff --git a/ios/chrome/browser/passwords/resources/password_controller.js b/ios/chrome/browser/passwords/resources/password_controller.js index f3bb421..c04af67c 100644 --- a/ios/chrome/browser/passwords/resources/password_controller.js +++ b/ios/chrome/browser/passwords/resources/password_controller.js
@@ -28,13 +28,54 @@ */ __gCrWeb['findPasswordForms'] = function() { var formDataList = []; - if (__gCrWeb.hasPasswordField()) { + if (hasPasswordField_(window)) { __gCrWeb.getPasswordFormDataList(formDataList, window); } return __gCrWeb.stringify(formDataList); }; /** + * Returns true if the top window or any frames inside contain an input field + * of type 'password'. This method is only used for unit tests and are only + * kept for legacy reasons. Prefer to use the private + * {@code hasPasswordField_} within this file. + * @return {boolean} Whether a password field exists. + * + * TODO(crbug.com/614092): investigate if this method can be completely + * removed from the gCrWeb public interface. + */ + __gCrWeb['hasPasswordField'] = function() { + return hasPasswordField_(window); + }; + + /** Returns true if the supplied window or any frames inside contain an input + * field of type 'password'. + * @private + */ + var hasPasswordField_ = function(win) { + var doc = win.document; + + // We may will not be allowed to read the 'document' property from a frame + // that is in a different domain. + if (!doc) { + return false; + } + + if (doc.querySelector('input[type=password]')) { + return true; + } + + var frames = win.frames; + for (var i = 0; i < frames.length; i++) { + if (hasPasswordField_(frames[i])) { + return true; + } + } + + return false; + }; + + /** * Returns the password form with the given |name| as a JSON string. * @param {string} name The name of the form to extract. * @return {string} The password form.
diff --git a/ios/chrome/browser/payments/payment_request.mm b/ios/chrome/browser/payments/payment_request.mm index e138bae..2a7d7ff 100644 --- a/ios/chrome/browser/payments/payment_request.mm +++ b/ios/chrome/browser/payments/payment_request.mm
@@ -11,6 +11,7 @@ #include "components/autofill/core/browser/personal_data_manager.h" #include "components/payments/core/currency_formatter.h" #include "components/payments/core/payment_request_data_util.h" +#include "components/payments/core/profile_util.h" #include "ios/chrome/browser/application_context.h" #include "ios/web/public/payments/payment_request.h" @@ -90,12 +91,15 @@ for (const auto* profile : profiles_to_suggest) { profile_cache_.push_back(*profile); shipping_profiles_.push_back(&profile_cache_.back()); - // TODO(crbug.com/602666): Implement deduplication rules for profiles. contact_profiles_.push_back(&profile_cache_.back()); } - // TODO(crbug.com/602666): Implement prioritization rules for shipping and - // contact profiles. + // TODO(crbug.com/602666): Implement deduplication and prioritization rules + // for shipping profiles. + + contact_profiles_ = payments::profile_util::FilterProfilesForContact( + contact_profiles_, GetApplicationContext()->GetApplicationLocale(), + *this); if (!shipping_profiles_.empty()) selected_shipping_profile_ = shipping_profiles_[0];
diff --git a/ios/chrome/browser/payments/payment_request_test_util.mm b/ios/chrome/browser/payments/payment_request_test_util.mm index 706ec3e..c8f31f8d 100644 --- a/ios/chrome/browser/payments/payment_request_test_util.mm +++ b/ios/chrome/browser/payments/payment_request_test_util.mm
@@ -43,6 +43,9 @@ shipping_option2.selected = false; web_payment_request.details.shipping_options.push_back(shipping_option2); web_payment_request.options.request_shipping = true; + web_payment_request.options.request_payer_name = true; + web_payment_request.options.request_payer_email = true; + web_payment_request.options.request_payer_phone = true; return web_payment_request; }
diff --git a/ios/chrome/browser/translate/translate_ranker_factory.cc b/ios/chrome/browser/translate/translate_ranker_factory.cc index d55799d8..b6268a8 100644 --- a/ios/chrome/browser/translate/translate_ranker_factory.cc +++ b/ios/chrome/browser/translate/translate_ranker_factory.cc
@@ -39,7 +39,7 @@ ios::ChromeBrowserState::FromBrowserState(context); return base::MakeUnique<TranslateRankerImpl>( TranslateRankerImpl::GetModelPath(browser_state->GetStatePath()), - TranslateRankerImpl::GetModelURL()); + TranslateRankerImpl::GetModelURL(), nullptr /* ukm::UkmService */); } web::BrowserState* TranslateRankerFactory::GetBrowserStateToUse(
diff --git a/ios/showcase/tab/sc_tab_egtest.mm b/ios/showcase/tab/sc_tab_egtest.mm index e419061..5da16e7 100644 --- a/ios/showcase/tab/sc_tab_egtest.mm +++ b/ios/showcase/tab/sc_tab_egtest.mm
@@ -18,13 +18,15 @@ @implementation SCTabTestCase // Tests launching TopToolbarTabViewController. -- (void)testLaunchWithTopToolbar { +// TODO(crbug.com/710662): re-enable this test. +- (void)FLAKY_testLaunchWithTopToolbar { showcase_utils::Open(@"TopToolbarTabViewController"); showcase_utils::Close(); } // Tests launching BottomToolbarTabViewController. -- (void)testLaunchWithBottomToolbar { +// TODO(crbug.com/710662): re-enable this test. +- (void)FLAKY_testLaunchWithBottomToolbar { showcase_utils::Open(@"BottomToolbarTabViewController"); showcase_utils::Close(); }
diff --git a/ios/showcase/tab_grid/sc_tab_grid_egtest.mm b/ios/showcase/tab_grid/sc_tab_grid_egtest.mm index 3ad3b5e..45bf653 100644 --- a/ios/showcase/tab_grid/sc_tab_grid_egtest.mm +++ b/ios/showcase/tab_grid/sc_tab_grid_egtest.mm
@@ -18,7 +18,8 @@ @implementation SCTabGridTestCase // Tests launching TabGridViewController and tapping a cell. -- (void)testLaunchAndTappingCell { +// TODO(crbug.com/710662): re-enable this test. +- (void)FLAKY_testLaunchAndTappingCell { showcase_utils::Open(@"TabGridViewController"); [[EarlGrey selectElementWithMatcher:grey_accessibilityID(@"Tab 0_button")] performAction:grey_tap()];
diff --git a/ios/web/BUILD.gn b/ios/web/BUILD.gn index de52bb0..f3892b0f 100644 --- a/ios/web/BUILD.gn +++ b/ios/web/BUILD.gn
@@ -608,7 +608,6 @@ "web_state/error_translation_util_unittest.mm", "web_state/js/common_js_unittest.mm", "web_state/js/context_menu_js_unittest.mm", - "web_state/js/core_js_unittest.mm", "web_state/js/credential_util_unittest.mm", "web_state/js/crw_js_injection_manager_unittest.mm", "web_state/js/crw_js_post_request_loader_unittest.mm",
diff --git a/ios/web/web_state/js/core_js_unittest.mm b/ios/web/web_state/js/core_js_unittest.mm deleted file mode 100644 index 7420220..0000000 --- a/ios/web/web_state/js/core_js_unittest.mm +++ /dev/null
@@ -1,59 +0,0 @@ -// Copyright 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 <vector> - -#include "base/macros.h" -#include "base/strings/stringprintf.h" -#include "base/strings/sys_string_conversions.h" -#import "ios/web/public/test/web_test_with_web_state.h" -#include "testing/gtest/include/gtest/gtest.h" -#include "testing/gtest_mac.h" - -// Unit tests for ios/web/web_state/js/resources/core.js. - -namespace web { - -// Test fixture to test core.js. -typedef web::WebTestWithWebState CoreJsTest; - -struct TestDataForPasswordFormDetection { - NSString* pageContent; - NSNumber* containsPassword; -}; - -TEST_F(CoreJsTest, HasPasswordField) { - TestDataForPasswordFormDetection testData[] = { - // Form without a password field. - {@"<form><input type='text' name='password'></form>", @NO}, - // Form with a password field. - {@"<form><input type='password' name='password'></form>", @YES}}; - for (size_t i = 0; i < arraysize(testData); i++) { - TestDataForPasswordFormDetection& data = testData[i]; - LoadHtml(data.pageContent); - id result = ExecuteJavaScript(@"__gCrWeb.hasPasswordField()"); - EXPECT_NSEQ(data.containsPassword, result) - << " in test " << i << ": " - << base::SysNSStringToUTF8(data.pageContent); - } -} - -TEST_F(CoreJsTest, HasPasswordFieldinFrame) { - TestDataForPasswordFormDetection data = { - // Form with a password field in a nested iframe. - @"<iframe name='pf'></iframe>" - "<script>" - " var doc = frames['pf'].document.open();" - " doc.write('<form><input type=\\'password\\'></form>');" - " doc.close();" - "</script>", - @YES - }; - LoadHtml(data.pageContent); - id result = ExecuteJavaScript(@"__gCrWeb.hasPasswordField()"); - EXPECT_NSEQ(data.containsPassword, result) - << base::SysNSStringToUTF8(data.pageContent); -} - -} // namespace web
diff --git a/ios/web/web_state/js/resources/core.js b/ios/web/web_state/js/resources/core.js index 878481a8..6ec37f02 100644 --- a/ios/web/web_state/js/resources/core.js +++ b/ios/web/web_state/js/resources/core.js
@@ -40,40 +40,6 @@ {'command': 'window.error', 'message': event.message.toString()}); }); - - // Returns true if the top window or any frames inside contain an input - // field of type 'password'. - __gCrWeb['hasPasswordField'] = function() { - return hasPasswordField_(window); - }; - - - // Returns true if the supplied window or any frames inside contain an input - // field of type 'password'. - // @private - var hasPasswordField_ = function(win) { - var doc = win.document; - - // We may will not be allowed to read the 'document' property from a frame - // that is in a different domain. - if (!doc) { - return false; - } - - if (doc.querySelector('input[type=password]')) { - return true; - } - - var frames = win.frames; - for (var i = 0; i < frames.length; i++) { - if (hasPasswordField_(frames[i])) { - return true; - } - } - - return false; - }; - __gCrWeb['sendFaviconsToHost'] = function() { __gCrWeb.message.invokeOnHost({'command': 'document.favicons', 'favicons': __gCrWeb.common.getFavicons()});
diff --git a/ios/web_view/internal/translate/web_view_translate_ranker_factory.cc b/ios/web_view/internal/translate/web_view_translate_ranker_factory.cc index ca08603..0d0de7e 100644 --- a/ios/web_view/internal/translate/web_view_translate_ranker_factory.cc +++ b/ios/web_view/internal/translate/web_view_translate_ranker_factory.cc
@@ -44,7 +44,8 @@ base::MakeUnique<translate::TranslateRankerImpl>( translate::TranslateRankerImpl::GetModelPath( web_view_browser_state->GetStatePath()), - translate::TranslateRankerImpl::GetModelURL()); + translate::TranslateRankerImpl::GetModelURL(), + nullptr /* ukm::UkmService */); // WebView has no consumer of translate ranker events, so don't generate them. ranker->EnableLogging(false);
diff --git a/ipc/README.md b/ipc/README.md index ba08e075..2b1f9f2 100644 --- a/ipc/README.md +++ b/ipc/README.md
@@ -50,9 +50,13 @@ We have a small but growing number of services defined in [`//services`](https://cs.chromium.org/chromium/src/services), each of which has some set of public interfaces defined in their `public/interfaces` subdirectory. -In the limit we want all IPC interfaces to be defined by some Mojom in these -directories, so this is the preferred destination for any new message -conversions. +In the limit, this is the preferred destination for any message conversions +pertaining to foundational system services (more info at +[https://www.chromium.org/servicification](https://www.chromium.org/servicification).) +For other code it may make sense to introduce services elsewhere (*e.g.*, in +`//chrome/services` or `//components/foo/service`), or to simply +avoid using services altogether for now and instead define some one-off Mojom +interface alongside the old messages file. If you need help deciding where a message should live, or if you feel it would be appropriate to introduce a new service to implement some feature or large set
diff --git a/media/audio/android/opensles_output.cc b/media/audio/android/opensles_output.cc index e6062362..d8eb72ff 100644 --- a/media/audio/android/opensles_output.cc +++ b/media/audio/android/opensles_output.cc
@@ -4,11 +4,13 @@ #include "media/audio/android/opensles_output.h" +#include "base/android/build_info.h" #include "base/logging.h" #include "base/macros.h" #include "base/time/time.h" #include "base/trace_event/trace_event.h" #include "media/audio/android/audio_manager_android.h" +#include "media/base/audio_sample_types.h" #include "media/base/audio_timestamp_helper.h" #define LOG_ON_FAILURE_AND_RETURN(op, ...) \ @@ -32,15 +34,38 @@ simple_buffer_queue_(NULL), audio_data_(), active_buffer_index_(0), - bytes_per_frame_(params.GetBytesPerFrame()), - buffer_size_bytes_(params.GetBytesPerBuffer()), started_(false), muted_(false), volume_(1.0), samples_per_second_(params.sample_rate()), + have_float_output_(base::android::BuildInfo::GetInstance()->sdk_int() >= + base::android::SDK_VERSION_LOLLIPOP), + bytes_per_frame_(have_float_output_ ? params.channels() * sizeof(float) + : params.GetBytesPerFrame()), + buffer_size_bytes_(have_float_output_ + ? bytes_per_frame_ * params.frames_per_buffer() + : params.GetBytesPerBuffer()), delay_calculator_(samples_per_second_) { DVLOG(2) << "OpenSLESOutputStream::OpenSLESOutputStream(" << "stream_type=" << stream_type << ")"; + + audio_bus_ = AudioBus::Create(params); + + if (have_float_output_) { + float_format_.formatType = SL_ANDROID_DATAFORMAT_PCM_EX; + float_format_.numChannels = static_cast<SLuint32>(params.channels()); + // Despite the name, this field is actually the sampling rate in millihertz. + float_format_.sampleRate = + static_cast<SLuint32>(samples_per_second_ * 1000); + float_format_.bitsPerSample = 32; + float_format_.containerSize = 32; + float_format_.endianness = SL_BYTEORDER_LITTLEENDIAN; + float_format_.channelMask = + ChannelCountToSLESChannelMask(params.channels()); + float_format_.representation = SL_ANDROID_PCM_REPRESENTATION_FLOAT; + return; + } + format_.formatType = SL_DATAFORMAT_PCM; format_.numChannels = static_cast<SLuint32>(params.channels()); // Despite the name, this field is actually the sampling rate in millihertz :| @@ -49,7 +74,6 @@ format_.containerSize = params.bits_per_sample(); format_.endianness = SL_BYTEORDER_LITTLEENDIAN; format_.channelMask = ChannelCountToSLESChannelMask(params.channels()); - audio_bus_ = AudioBus::Create(params); } OpenSLESOutputStream::~OpenSLESOutputStream() { @@ -241,7 +265,11 @@ SLDataLocator_AndroidSimpleBufferQueue simple_buffer_queue = { SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE, static_cast<SLuint32>(kMaxNumOfBuffersInQueue)}; - SLDataSource audio_source = {&simple_buffer_queue, &format_}; + SLDataSource audio_source; + if (have_float_output_) + audio_source = {&simple_buffer_queue, &float_format_}; + else + audio_source = {&simple_buffer_queue, &format_}; // Audio sink configuration. SLDataLocator_OutputMix locator_output_mix = {SL_DATALOCATOR_OUTPUTMIX, @@ -373,8 +401,14 @@ // raw float, the data must be clipped and sanitized since it may come // from an untrusted source such as NaCl. audio_bus_->Scale(muted_ ? 0.0f : volume_); - audio_bus_->ToInterleaved(frames_filled, format_.bitsPerSample / 8, - audio_data_[active_buffer_index_]); + if (!have_float_output_) { + audio_bus_->ToInterleaved(frames_filled, format_.bitsPerSample / 8, + audio_data_[active_buffer_index_]); + } else { + audio_bus_->ToInterleaved<Float32SampleTypeTraits>( + frames_filled, + reinterpret_cast<float*>(audio_data_[active_buffer_index_])); + } delay_calculator_.AddFrames(frames_filled); const int num_filled_bytes = frames_filled * bytes_per_frame_; @@ -393,9 +427,8 @@ void OpenSLESOutputStream::SetupAudioBuffer() { DCHECK(thread_checker_.CalledOnValidThread()); DCHECK(!audio_data_[0]); - for (int i = 0; i < kMaxNumOfBuffersInQueue; ++i) { + for (int i = 0; i < kMaxNumOfBuffersInQueue; ++i) audio_data_[i] = new uint8_t[buffer_size_bytes_]; - } } void OpenSLESOutputStream::ReleaseAudioBuffer() {
diff --git a/media/audio/android/opensles_output.h b/media/audio/android/opensles_output.h index 671dbdec..80d8929 100644 --- a/media/audio/android/opensles_output.h +++ b/media/audio/android/opensles_output.h
@@ -21,6 +21,25 @@ #include "media/base/audio_parameters.h" #include "media/base/audio_timestamp_helper.h" +// On L+, we want to use floating point output for better fidelity. +#if __ANDROID_API__ < 21 +#define SL_ANDROID_PCM_REPRESENTATION_SIGNED_INT ((SLuint32)0x00000001) +#define SL_ANDROID_PCM_REPRESENTATION_UNSIGNED_INT ((SLuint32)0x00000002) +#define SL_ANDROID_PCM_REPRESENTATION_FLOAT ((SLuint32)0x00000003) +#define SL_ANDROID_DATAFORMAT_PCM_EX ((SLuint32)0x00000004) + +typedef struct SLAndroidDataFormat_PCM_EX_ { + SLuint32 formatType; + SLuint32 numChannels; + SLuint32 sampleRate; + SLuint32 bitsPerSample; + SLuint32 containerSize; + SLuint32 channelMask; + SLuint32 endianness; + SLuint32 representation; +} SLAndroidDataFormat_PCM_EX; +#endif + namespace media { class AudioManagerAndroid; @@ -101,14 +120,13 @@ SLAndroidSimpleBufferQueueItf simple_buffer_queue_; SLDataFormat_PCM format_; + SLAndroidDataFormat_PCM_EX float_format_; // Audio buffers that are allocated during Open() based on parameters given // during construction. uint8_t* audio_data_[kMaxNumOfBuffersInQueue]; int active_buffer_index_; - int bytes_per_frame_; - size_t buffer_size_bytes_; bool started_; @@ -123,6 +141,12 @@ int samples_per_second_; + // On Android 5.0+ we can output directly to float instead of in integer. + bool have_float_output_; + + int bytes_per_frame_; + size_t buffer_size_bytes_; + // Used to calculate the delay value for each OnMoreData() call. AudioTimestampHelper delay_calculator_;
diff --git a/media/base/container_names.cc b/media/base/container_names.cc index 4eb91d82..34875b5 100644 --- a/media/base/container_names.cc +++ b/media/base/container_names.cc
@@ -1090,32 +1090,20 @@ return (bitrate > 0 && sampling_rate > 0); } -// Extract a size encoded the MP3 way. -static int GetMp3HeaderSize(const uint8_t* buffer, int buffer_size) { - DCHECK_GE(buffer_size, 9); - int size = ((buffer[6] & 0x7f) << 21) + ((buffer[7] & 0x7f) << 14) + - ((buffer[8] & 0x7f) << 7) + (buffer[9] & 0x7f) + 10; - if (buffer[5] & 0x10) // Footer added? - size += 10; - return size; -} - // Additional checks for a MP3 container. -static bool CheckMp3(const uint8_t* buffer, int buffer_size, bool seenHeader) { - RCHECK(buffer_size >= 10); // Must be enough to read the initial header. - - int framesize; +static bool CheckMp3(const uint8_t* buffer, int buffer_size) { + // This function assumes that the ID3 header is not present in the file and + // simply checks for several valid MPEG audio buffers after skipping any + // optional padding characters. int numSeen = 0; int offset = 0; - if (seenHeader) { - offset = GetMp3HeaderSize(buffer, buffer_size); - } else { - // Skip over leading 0's. - while (offset < buffer_size && buffer[offset] == 0) - ++offset; - } + + // Skip over any padding (0's). + while (offset < buffer_size && buffer[offset] == 0) + ++offset; while (offset + 3 < buffer_size) { + int framesize; RCHECK(ValidMpegAudioFrameHeader( buffer + offset, buffer_size - offset, &framesize)); @@ -1600,9 +1588,7 @@ return CONTAINER_SWF; case TAG('I','D','3',0): - if (CheckMp3(buffer, buffer_size, true)) - return CONTAINER_MP3; - break; + return CONTAINER_MP3; } // Maybe the first 2 characters are something we can use. @@ -1624,8 +1610,8 @@ break; } - // Check if the file is in MP3 format without the header. - if (CheckMp3(buffer, buffer_size, false)) + // Check if the file is in MP3 format without the ID3 header. + if (CheckMp3(buffer, buffer_size)) return CONTAINER_MP3; return CONTAINER_UNKNOWN;
diff --git a/media/base/container_names_unittest.cc b/media/base/container_names_unittest.cc index cb70a2f1..cc3f9c13 100644 --- a/media/base/container_names_unittest.cc +++ b/media/base/container_names_unittest.cc
@@ -173,7 +173,10 @@ } TEST(ContainerNamesTest, FileCheckMP3) { + TestFile(CONTAINER_MP3, GetTestDataFilePath("bear-audio-10s-CBR-no-TOC.mp3")); + TestFile(CONTAINER_MP3, GetTestDataFilePath("id3_png_test.mp3")); TestFile(CONTAINER_MP3, GetTestDataFilePath("id3_test.mp3")); + TestFile(CONTAINER_MP3, GetTestDataFilePath("midstream_config_change.mp3")); TestFile(CONTAINER_MP3, GetTestDataFilePath("sfx.mp3")); }
diff --git a/media/filters/decrypting_audio_decoder_unittest.cc b/media/filters/decrypting_audio_decoder_unittest.cc index 94d388b..70166bf 100644 --- a/media/filters/decrypting_audio_decoder_unittest.cc +++ b/media/filters/decrypting_audio_decoder_unittest.cc
@@ -52,16 +52,6 @@ return buffer; } -// Use anonymous namespace here to prevent the actions to be defined multiple -// times across multiple test files. Sadly we can't use static for them. -namespace { - -ACTION_P(ReturnBuffer, buffer) { - return buffer; -} - -} // namespace - class DecryptingAudioDecoderTest : public testing::Test { public: DecryptingAudioDecoderTest()
diff --git a/media/filters/decrypting_video_decoder_unittest.cc b/media/filters/decrypting_video_decoder_unittest.cc index 0e3b169..7f1b029 100644 --- a/media/filters/decrypting_video_decoder_unittest.cc +++ b/media/filters/decrypting_video_decoder_unittest.cc
@@ -45,16 +45,6 @@ return buffer; } -// Use anonymous namespace here to prevent the actions to be defined multiple -// times across multiple test files. Sadly we can't use static for them. -namespace { - -ACTION_P3(ResetAndRunCallback, callback, p1, p2) { - base::ResetAndReturn(callback).Run(p1, p2); -} - -} // namespace - class DecryptingVideoDecoderTest : public testing::Test { public: DecryptingVideoDecoderTest()
diff --git a/media/filters/gpu_video_decoder.cc b/media/filters/gpu_video_decoder.cc index 2a8a704..953a414 100644 --- a/media/filters/gpu_video_decoder.cc +++ b/media/filters/gpu_video_decoder.cc
@@ -184,20 +184,6 @@ cb.Run(success); } -// static -void ReleaseMailboxTrampoline( - const scoped_refptr<base::SingleThreadTaskRunner>& task_runner, - const VideoFrame::ReleaseMailboxCB& release_mailbox_cb, - const gpu::SyncToken& release_sync_token) { - if (task_runner->BelongsToCurrentThread()) { - release_mailbox_cb.Run(release_sync_token); - return; - } - - task_runner->PostTask(FROM_HERE, - base::Bind(release_mailbox_cb, release_sync_token)); -} - std::string GpuVideoDecoder::GetDisplayName() const { return kDecoderName; } @@ -673,11 +659,11 @@ scoped_refptr<VideoFrame> frame(VideoFrame::WrapNativeTextures( pixel_format_, mailbox_holders, - base::Bind( - &ReleaseMailboxTrampoline, factories_->GetTaskRunner(), - base::Bind(&GpuVideoDecoder::ReleaseMailbox, - weak_factory_.GetWeakPtr(), factories_, - picture.picture_buffer_id(), pb.client_texture_ids())), + // Always post ReleaseMailbox to avoid deadlock with the compositor when + // releasing video frames on the media thread; http://crbug.com/710209. + BindToCurrentLoop(base::Bind( + &GpuVideoDecoder::ReleaseMailbox, weak_factory_.GetWeakPtr(), + factories_, picture.picture_buffer_id(), pb.client_texture_ids())), pb.size(), visible_rect, natural_size, timestamp)); if (!frame) { DLOG(ERROR) << "Create frame failed for: " << picture.picture_buffer_id();
diff --git a/mojo/README.md b/mojo/README.md index e1e7583f..64d129f 100644 --- a/mojo/README.md +++ b/mojo/README.md
@@ -1,4 +1,4 @@ -#  Mojo +#  Mojo This document is a subset of the [Mojo documentation](/mojo). [TOC] @@ -29,7 +29,7 @@ and libraries comprising the system. The basic hierarchy of features is as follows: - + ## Embedder Development Kit (EDK) Every process to be interconnected via Mojo IPC is called a **Mojo embedder**
diff --git a/mojo/edk/embedder/README.md b/mojo/edk/embedder/README.md index fc53bece..6fc2cce 100644 --- a/mojo/edk/embedder/README.md +++ b/mojo/edk/embedder/README.md
@@ -1,4 +1,4 @@ -#  Mojo Embedder Development Kit (EDK) +#  Mojo Embedder Development Kit (EDK) This document is a subset of the [Mojo documentation](/mojo). [TOC]
diff --git a/mojo/edk/system/node_channel.cc b/mojo/edk/system/node_channel.cc index b0f770d90..bed3848 100644 --- a/mojo/edk/system/node_channel.cc +++ b/mojo/edk/system/node_channel.cc
@@ -23,12 +23,6 @@ namespace { -template <typename T> -T Align(T t) { - const auto k = kChannelMessageAlignment; - return t + (k - (t % k)) % k; -} - // NOTE: Please ONLY append messages to the end of this enum. enum class MessageType : uint32_t { ACCEPT_CHILD,
diff --git a/mojo/public/c/system/README.md b/mojo/public/c/system/README.md index 2abe80ff..6e4ad3d9 100644 --- a/mojo/public/c/system/README.md +++ b/mojo/public/c/system/README.md
@@ -1,4 +1,4 @@ -#  Mojo C System API +#  Mojo C System API This document is a subset of the [Mojo documentation](/mojo). [TOC]
diff --git a/mojo/public/cpp/bindings/README.md b/mojo/public/cpp/bindings/README.md index b37267a..9a8e2b04 100644 --- a/mojo/public/cpp/bindings/README.md +++ b/mojo/public/cpp/bindings/README.md
@@ -1,4 +1,4 @@ -#  Mojo C++ Bindings API +#  Mojo C++ Bindings API This document is a subset of the [Mojo documentation](/mojo). [TOC] @@ -143,7 +143,7 @@ doesn't actually *do* anything other than hold onto a pipe endpoint and carry useful compile-time type information. - + So how do we create a strongly-typed message pipe? @@ -210,7 +210,7 @@ This actually writes a `Log` message to the pipe. - + But as mentioned above, `InterfaceRequest` *doesn't actually do anything*, so that message will just sit on the pipe forever. We need a way to read messages @@ -277,7 +277,7 @@ 3. The `Log` message is read and deserialized, causing the `Binding` to invoke the `Logger::Log` implementation on its bound `LoggerImpl`. - + As a result, our implementation will eventually log the client's `"Hello!"` message via `LOG(ERROR)`.
diff --git a/mojo/public/cpp/bindings/associated_binding.h b/mojo/public/cpp/bindings/associated_binding.h index 5941166..b4c828b 100644 --- a/mojo/public/cpp/bindings/associated_binding.h +++ b/mojo/public/cpp/bindings/associated_binding.h
@@ -96,9 +96,10 @@ // Constructs an incomplete associated binding that will use the // implementation |impl|. It may be completed with a subsequent call to the - // |Bind| method. Does not take ownership of |impl|, which must outlive this - // object. - explicit AssociatedBinding(ImplPointerType impl) { stub_.set_sink(impl); } + // |Bind| method. + explicit AssociatedBinding(ImplPointerType impl) { + stub_.set_sink(std::move(impl)); + } // Constructs a completed associated binding of |impl|. The output |ptr_info| // should be sent by another interface. |impl| must outlive this object.
diff --git a/mojo/public/cpp/bindings/strong_associated_binding_set.h b/mojo/public/cpp/bindings/strong_associated_binding_set.h new file mode 100644 index 0000000..8c769698 --- /dev/null +++ b/mojo/public/cpp/bindings/strong_associated_binding_set.h
@@ -0,0 +1,25 @@ +// 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 MOJO_PUBLIC_CPP_BINDINGS_STRONG_ASSOCIATED_BINDING_SET_H_ +#define MOJO_PUBLIC_CPP_BINDINGS_STRONG_ASSOCIATED_BINDING_SET_H_ + +#include "mojo/public/cpp/bindings/associated_binding.h" +#include "mojo/public/cpp/bindings/associated_binding_set.h" +#include "mojo/public/cpp/bindings/associated_interface_ptr.h" +#include "mojo/public/cpp/bindings/associated_interface_request.h" +#include "mojo/public/cpp/bindings/binding_set.h" +#include "mojo/public/cpp/bindings/unique_ptr_impl_ref_traits.h" + +namespace mojo { + +template <typename Interface, typename ContextType = void> +using StrongAssociatedBindingSet = BindingSetBase< + Interface, + AssociatedBinding<Interface, UniquePtrImplRefTraits<Interface>>, + ContextType>; + +} // namespace mojo + +#endif // MOJO_PUBLIC_CPP_BINDINGS_STRONG_ASSOCIATED_BINDING_SET_H_
diff --git a/mojo/public/cpp/system/README.md b/mojo/public/cpp/system/README.md index 782744f0..f169411 100644 --- a/mojo/public/cpp/system/README.md +++ b/mojo/public/cpp/system/README.md
@@ -1,4 +1,4 @@ -#  Mojo C++ System API +#  Mojo C++ System API This document is a subset of the [Mojo documentation](/mojo). [TOC] @@ -225,7 +225,7 @@ * `MANUAL` mode requires the user to manually call `Arm` and/or `ArmOrNotify` before any notifications will fire regarding the state of the watched handle. Every time the notification callback is run, the `SimpleWatcher` must be - rearmed again before the next one can fire. See + rearmed again before the next one can fire. See [Arming a Watcher](/mojo/public/c/system#Arming-a-Watcher) and the documentation in `SimpleWatcher`'s header. @@ -286,7 +286,7 @@ While these API features should be used sparingly, they are sometimes necessary. -See the documentation in +See the documentation in [wait.h](https://cs.chromium.org/chromium/src/mojo/public/cpp/system/wait.h) and [wait_set.h](https://cs.chromium.org/chromium/src/mojo/public/cpp/system/wait_set.h) for a more detailed API reference. @@ -335,7 +335,7 @@ ``` Similar to `mojo::Wait`, `mojo::WaitMany` is primarily useful in testing. When -waiting on multiple handles in production code, you should almost always instead +waiting on multiple handles in production code, you should almost always instead use a more efficient and more flexible `mojo::WaitSet` as described in the next section.
diff --git a/mojo/public/java/bindings/README.md b/mojo/public/java/bindings/README.md index 821a230e..2831344f 100644 --- a/mojo/public/java/bindings/README.md +++ b/mojo/public/java/bindings/README.md
@@ -1,4 +1,4 @@ -#  Mojo Java Bindings API +#  Mojo Java Bindings API This document is a subset of the [Mojo documentation](/mojo). [TOC]
diff --git a/mojo/public/java/system/README.md b/mojo/public/java/system/README.md index 3213e4c..c62f30b 100644 --- a/mojo/public/java/system/README.md +++ b/mojo/public/java/system/README.md
@@ -1,4 +1,4 @@ -#  Mojo Java System API +#  Mojo Java System API This document is a subset of the [Mojo documentation](/mojo). [TOC]
diff --git a/mojo/public/js/README.md b/mojo/public/js/README.md index b6eafe9c..f510b03 100644 --- a/mojo/public/js/README.md +++ b/mojo/public/js/README.md
@@ -1,4 +1,4 @@ -#  Mojo JavaScript System and Bindings APIs +#  Mojo JavaScript System and Bindings APIs This document is a subset of the [Mojo documentation](/mojo). **NOTE:** The JavaScript APIs are currently in flux and will stabilize soon.
diff --git a/mojo/public/tools/bindings/README.md b/mojo/public/tools/bindings/README.md index 737c7e61..7a62d7e 100644 --- a/mojo/public/tools/bindings/README.md +++ b/mojo/public/tools/bindings/README.md
@@ -1,4 +1,4 @@ -#  Mojom IDL and Bindings Generator +#  Mojom IDL and Bindings Generator This document is a subset of the [Mojo documentation](/mojo). [TOC]
diff --git a/net/BUILD.gn b/net/BUILD.gn index 2a7a44f..36c0fa4 100644 --- a/net/BUILD.gn +++ b/net/BUILD.gn
@@ -1340,6 +1340,7 @@ "quic/platform/api/quic_clock.h", "quic/platform/api/quic_containers.h", "quic/platform/api/quic_endian.h", + "quic/platform/api/quic_estimate_memory_usage.h", "quic/platform/api/quic_export.h", "quic/platform/api/quic_flag_utils.h", "quic/platform/api/quic_hostname_utils.cc", @@ -1370,6 +1371,7 @@ "quic/platform/impl/quic_chromium_clock.h", "quic/platform/impl/quic_containers_impl.h", "quic/platform/impl/quic_endian_impl.h", + "quic/platform/impl/quic_estimate_memory_usage_impl.h", "quic/platform/impl/quic_export_impl.h", "quic/platform/impl/quic_flag_utils_impl.h", "quic/platform/impl/quic_hostname_utils_impl.cc", @@ -4578,7 +4580,6 @@ "quic/core/quic_write_blocked_list_test.cc", "quic/core/spdy_utils_test.cc", "quic/platform/api/quic_endian_test.cc", - "quic/platform/api/quic_estimate_memory_usage.h", "quic/platform/api/quic_hostname_utils_test.cc", "quic/platform/api/quic_lru_cache_test.cc", "quic/platform/api/quic_reference_counted_test.cc", @@ -4586,7 +4587,6 @@ "quic/platform/api/quic_text_utils_test.cc", "quic/platform/api/quic_url_test.cc", "quic/platform/impl/quic_chromium_clock_test.cc", - "quic/platform/impl/quic_estimate_memory_usage_impl.h", "quic/quartc/quartc_alarm_factory_test.cc", "quic/quartc/quartc_session_test.cc", "quic/quartc/quartc_stream_test.cc",
diff --git a/net/http/disk_cache_based_quic_server_info.cc b/net/http/disk_cache_based_quic_server_info.cc index 2d4251b..b149fc9 100644 --- a/net/http/disk_cache_based_quic_server_info.cc +++ b/net/http/disk_cache_based_quic_server_info.cc
@@ -10,6 +10,7 @@ #include "base/logging.h" #include "base/metrics/histogram_macros.h" #include "base/stl_util.h" +#include "base/trace_event/memory_usage_estimator.h" #include "net/base/completion_callback.h" #include "net/base/io_buffer.h" #include "net/base/net_errors.h" @@ -185,6 +186,15 @@ backend_->OnExternalCacheHit(key()); } +size_t DiskCacheBasedQuicServerInfo::EstimateMemoryUsage() const { + return base::trace_event::EstimateMemoryUsage(new_data_) + + base::trace_event::EstimateMemoryUsage(pending_write_data_) + + base::trace_event::EstimateMemoryUsage(server_id_) + + (read_buffer_ == nullptr ? 0 : read_buffer_->size()) + + (write_buffer_ == nullptr ? 0 : write_buffer_->size()) + + base::trace_event::EstimateMemoryUsage(data_); +} + std::string DiskCacheBasedQuicServerInfo::key() const { return "quicserverinfo:" + server_id_.ToString(); } @@ -335,14 +345,14 @@ return OK; } - read_buffer_ = new IOBuffer(size); + read_buffer_ = new IOBufferWithSize(size); state_ = READ_COMPLETE; return entry_->ReadData( 0 /* index */, 0 /* offset */, read_buffer_.get(), size, io_callback_); } int DiskCacheBasedQuicServerInfo::DoWrite() { - write_buffer_ = new IOBuffer(new_data_.size()); + write_buffer_ = new IOBufferWithSize(new_data_.size()); memcpy(write_buffer_->data(), new_data_.data(), new_data_.size()); state_ = WRITE_COMPLETE;
diff --git a/net/http/disk_cache_based_quic_server_info.h b/net/http/disk_cache_based_quic_server_info.h index 4b0ee091..2396f8c 100644 --- a/net/http/disk_cache_based_quic_server_info.h +++ b/net/http/disk_cache_based_quic_server_info.h
@@ -20,7 +20,7 @@ namespace net { class HttpCache; -class IOBuffer; +class IOBufferWithSize; class QuicServerId; // DiskCacheBasedQuicServerInfo fetches information about a QUIC server from @@ -43,6 +43,7 @@ bool IsReadyToPersist() override; void Persist() override; void OnExternalCacheHit() override; + size_t EstimateMemoryUsage() const override; private: struct CacheOperationDataShim; @@ -118,8 +119,8 @@ disk_cache::Backend* backend_; disk_cache::Entry* entry_; CompletionCallback wait_for_ready_callback_; - scoped_refptr<IOBuffer> read_buffer_; - scoped_refptr<IOBuffer> write_buffer_; + scoped_refptr<IOBufferWithSize> read_buffer_; + scoped_refptr<IOBufferWithSize> write_buffer_; std::string data_; base::TimeTicks load_start_time_; FailureReason last_failure_;
diff --git a/net/http/http_network_transaction_unittest.cc b/net/http/http_network_transaction_unittest.cc index 0314f62..363ae401 100644 --- a/net/http/http_network_transaction_unittest.cc +++ b/net/http/http_network_transaction_unittest.cc
@@ -9813,8 +9813,9 @@ base::FilePath temp_file; ASSERT_TRUE(base::CreateTemporaryFile(&temp_file)); std::string temp_file_content("Unreadable file."); - ASSERT_TRUE(base::WriteFile(temp_file, temp_file_content.c_str(), - temp_file_content.length())); + ASSERT_EQ(static_cast<int>(temp_file_content.length()), + base::WriteFile(temp_file, temp_file_content.c_str(), + temp_file_content.length())); ASSERT_TRUE(base::MakeFileUnreadable(temp_file)); std::vector<std::unique_ptr<UploadElementReader>> element_readers;
diff --git a/net/http/transport_security_persister_unittest.cc b/net/http/transport_security_persister_unittest.cc index c48f3c0..6e7e804 100644 --- a/net/http/transport_security_persister_unittest.cc +++ b/net/http/transport_security_persister_unittest.cc
@@ -144,7 +144,8 @@ // than block.) Use a different basename just for cleanliness. base::FilePath path = temp_dir_.GetPath().AppendASCII("TransportSecurityPersisterTest"); - EXPECT_TRUE(base::WriteFile(path, serialized.c_str(), serialized.size())); + EXPECT_EQ(static_cast<int>(serialized.size()), + base::WriteFile(path, serialized.c_str(), serialized.size())); // Read the data back. std::string persisted;
diff --git a/net/quic/chromium/properties_based_quic_server_info.cc b/net/quic/chromium/properties_based_quic_server_info.cc index efe6f84..e90331fd7 100644 --- a/net/quic/chromium/properties_based_quic_server_info.cc +++ b/net/quic/chromium/properties_based_quic_server_info.cc
@@ -94,6 +94,10 @@ RecordQuicServerInfoStatus(QUIC_SERVER_INFO_EXTERNAL_CACHE_HIT); } +size_t PropertiesBasedQuicServerInfo::EstimateMemoryUsage() const { + return 0; +} + PropertiesBasedQuicServerInfoFactory::PropertiesBasedQuicServerInfoFactory( HttpServerProperties* http_server_properties) : http_server_properties_(http_server_properties) {}
diff --git a/net/quic/chromium/properties_based_quic_server_info.h b/net/quic/chromium/properties_based_quic_server_info.h index c9b0075a..35ebb9b7 100644 --- a/net/quic/chromium/properties_based_quic_server_info.h +++ b/net/quic/chromium/properties_based_quic_server_info.h
@@ -38,6 +38,7 @@ bool IsReadyToPersist() override; void Persist() override; void OnExternalCacheHit() override; + size_t EstimateMemoryUsage() const override; private: HttpServerProperties* http_server_properties_;
diff --git a/net/quic/chromium/quic_server_info.h b/net/quic/chromium/quic_server_info.h index 77fb0fc1..eab5366 100644 --- a/net/quic/chromium/quic_server_info.h +++ b/net/quic/chromium/quic_server_info.h
@@ -102,6 +102,9 @@ // Called whenever an external cache reuses quic server config. virtual void OnExternalCacheHit() = 0; + // Returns the size of dynamically allocated memory in bytes. + virtual size_t EstimateMemoryUsage() const = 0; + struct State { State(); ~State();
diff --git a/net/quic/chromium/quic_stream_factory.cc b/net/quic/chromium/quic_stream_factory.cc index 1172e14..80388c5 100644 --- a/net/quic/chromium/quic_stream_factory.cc +++ b/net/quic/chromium/quic_stream_factory.cc
@@ -67,6 +67,12 @@ namespace net { +// Returns the estimate of dynamically allocated memory of an IPEndPoint in +// bytes. Used in tracking IPAliasMap. +size_t EstimateMemoryUsage(const IPEndPoint& end_point) { + return 0; +} + namespace { enum CreateSessionFailure { @@ -290,6 +296,12 @@ const QuicServerId& server_id() const { return server_id_; } + size_t EstimateMemoryUsage() const { + // TODO(xunjieli): crbug.com/669108. Track |verify_context_| and + // |verify_details_|. + return base::trace_event::EstimateMemoryUsage(verify_error_details_); + } + private: const QuicServerId server_id_; ProofVerifierCallbackImpl* verify_callback_; @@ -349,6 +361,9 @@ base::WeakPtr<Job> GetWeakPtr() { return weak_factory_.GetWeakPtr(); } + // Returns the estimate of dynamically allocated memory in bytes. + size_t EstimateMemoryUsage() const; + private: enum IoState { STATE_NONE, @@ -495,6 +510,11 @@ OnIOComplete(OK); } +size_t QuicStreamFactory::Job::EstimateMemoryUsage() const { + return base::trace_event::EstimateMemoryUsage(key_) + + base::trace_event::EstimateMemoryUsage(server_info_); +} + int QuicStreamFactory::Job::DoResolveHost() { dns_resolution_start_time_ = base::TimeTicks::Now(); // Start loading the data now, and wait for it after we resolve the host. @@ -926,19 +946,32 @@ void QuicStreamFactory::DumpMemoryStats( base::trace_event::ProcessMemoryDump* pmd, const std::string& parent_absolute_name) const { - if (all_sessions_.empty()) + if (all_sessions_.empty() && active_jobs_.empty()) return; base::trace_event::MemoryAllocatorDump* factory_dump = pmd->CreateAllocatorDump(parent_absolute_name + "/quic_stream_factory"); size_t memory_estimate = - base::trace_event::EstimateMemoryUsage(all_sessions_); + base::trace_event::EstimateMemoryUsage(all_sessions_) + + base::trace_event::EstimateMemoryUsage(active_sessions_) + + base::trace_event::EstimateMemoryUsage(session_aliases_) + + base::trace_event::EstimateMemoryUsage(ip_aliases_) + + base::trace_event::EstimateMemoryUsage(session_peer_ip_) + + base::trace_event::EstimateMemoryUsage(gone_away_aliases_) + + base::trace_event::EstimateMemoryUsage(active_jobs_) + + base::trace_event::EstimateMemoryUsage(job_requests_map_) + + base::trace_event::EstimateMemoryUsage(active_cert_verifier_jobs_); factory_dump->AddScalar(base::trace_event::MemoryAllocatorDump::kNameSize, base::trace_event::MemoryAllocatorDump::kUnitsBytes, memory_estimate); - factory_dump->AddScalar( - base::trace_event::MemoryAllocatorDump::kNameObjectCount, - base::trace_event::MemoryAllocatorDump::kUnitsObjects, - all_sessions_.size()); + factory_dump->AddScalar("all_sessions", + base::trace_event::MemoryAllocatorDump::kUnitsObjects, + all_sessions_.size()); + factory_dump->AddScalar("active_jobs", + base::trace_event::MemoryAllocatorDump::kUnitsObjects, + active_jobs_.size()); + factory_dump->AddScalar("active_cert_jobs", + base::trace_event::MemoryAllocatorDump::kUnitsObjects, + active_cert_verifier_jobs_.size()); } bool QuicStreamFactory::CanUseExistingSession(const QuicServerId& server_id,
diff --git a/net/quic/chromium/quic_stream_factory.h b/net/quic/chromium/quic_stream_factory.h index 7edae1300f..fdd2943 100644 --- a/net/quic/chromium/quic_stream_factory.h +++ b/net/quic/chromium/quic_stream_factory.h
@@ -564,9 +564,10 @@ // Map from QuicServerId to a set of non-owning QuicStreamRequest pointers. ServerIDRequestsMap job_requests_map_; + // Map of QuicServerId to owning CertVerifierJob. CertVerifierJobMap active_cert_verifier_jobs_; - QuicVersionVector supported_versions_; + const QuicVersionVector supported_versions_; // Set if we always require handshake confirmation. If true, this will // introduce at least one RTT for the handshake before the client sends data.
diff --git a/net/quic/chromium/quic_stream_factory_test.cc b/net/quic/chromium/quic_stream_factory_test.cc index c3a1927ed..4b02d542 100644 --- a/net/quic/chromium/quic_stream_factory_test.cc +++ b/net/quic/chromium/quic_stream_factory_test.cc
@@ -10,6 +10,7 @@ #include "base/bind.h" #include "base/callback.h" +#include "base/macros.h" #include "base/memory/ptr_util.h" #include "base/run_loop.h" #include "base/strings/string_util.h" @@ -195,6 +196,11 @@ void Persist() override {} void OnExternalCacheHit() override {} + + size_t EstimateMemoryUsage() const override { + NOTREACHED(); + return 0; + } }; class MockQuicServerInfoFactory : public QuicServerInfoFactory {
diff --git a/net/quic/core/quic_server_id.cc b/net/quic/core/quic_server_id.cc index 62397061..8efb8815 100644 --- a/net/quic/core/quic_server_id.cc +++ b/net/quic/core/quic_server_id.cc
@@ -6,6 +6,7 @@ #include <tuple> +#include "net/quic/platform/api/quic_estimate_memory_usage.h" #include "net/quic/platform/api/quic_str_cat.h" using std::string; @@ -43,4 +44,8 @@ (privacy_mode_ == PRIVACY_MODE_ENABLED ? "/private" : "")); } +size_t QuicServerId::EstimateMemoryUsage() const { + return QuicEstimateMemoryUsage(host_port_pair_); +} + } // namespace net
diff --git a/net/quic/core/quic_server_id.h b/net/quic/core/quic_server_id.h index 580789c..880afd2 100644 --- a/net/quic/core/quic_server_id.h +++ b/net/quic/core/quic_server_id.h
@@ -44,6 +44,8 @@ PrivacyMode privacy_mode() const { return privacy_mode_; } + size_t EstimateMemoryUsage() const; + private: HostPortPair host_port_pair_; PrivacyMode privacy_mode_;
diff --git a/net/url_request/url_request_unittest.cc b/net/url_request/url_request_unittest.cc index 2e51d6ac..9a6eaa0 100644 --- a/net/url_request/url_request_unittest.cc +++ b/net/url_request/url_request_unittest.cc
@@ -968,7 +968,8 @@ base::FilePath temp_path; EXPECT_TRUE(base::CreateTemporaryFile(&temp_path)); GURL temp_url = FilePathToFileURL(temp_path); - EXPECT_TRUE(base::WriteFile(temp_path, buffer.get(), buffer_size)); + EXPECT_EQ(static_cast<int>(buffer_size), + base::WriteFile(temp_path, buffer.get(), buffer_size)); int64_t file_size; EXPECT_TRUE(base::GetFileSize(temp_path, &file_size));
diff --git a/printing/image_mac.cc b/printing/image_mac.cc index 423b1fc..7edcfd7 100644 --- a/printing/image_mac.cc +++ b/printing/image_mac.cc
@@ -5,11 +5,13 @@ #include "printing/image.h" #include <ApplicationServices/ApplicationServices.h> +#include <CoreFoundation/CoreFoundation.h> #include <stddef.h> #include <stdint.h> #include "base/mac/scoped_cftyperef.h" #include "printing/metafile.h" +#include "printing/pdf_metafile_cg_mac.h" #include "ui/gfx/geometry/rect.h" namespace printing { @@ -39,12 +41,13 @@ kCGImageAlphaPremultipliedLast)); DCHECK(bitmap_context.get()); - struct Metafile::MacRenderPageParams params; + PdfMetafileCg::RenderPageParams params; params.shrink_to_fit = true; - metafile.RenderPage(page_number, bitmap_context, - CGRectMake(0, 0, size_.width(), size_.height()), params); - - return true; + CGRect cg_rect = CGRectMake(0, 0, size_.width(), size_.height()); + std::vector<char> buffer; + return metafile.GetDataAsVector(&buffer) && + PdfMetafileCg::RenderPage(buffer, page_number, bitmap_context, cg_rect, + params); } } // namespace printing
diff --git a/printing/metafile.h b/printing/metafile.h index 2f208ed..98eaa39 100644 --- a/printing/metafile.h +++ b/printing/metafile.h
@@ -16,10 +16,6 @@ #if defined(OS_WIN) #include <windows.h> -#elif defined(OS_MACOSX) -#include <ApplicationServices/ApplicationServices.h> -#include <CoreFoundation/CoreFoundation.h> -#include "base/mac/scoped_cftyperef.h" #endif namespace base { @@ -36,36 +32,6 @@ // This class plays metafiles from data stream (usually PDF or EMF). class PRINTING_EXPORT MetafilePlayer { public: -#if defined(OS_MACOSX) - // |shrink_to_fit| specifies whether the output should be shrunk to fit a - // destination page if the source PDF is bigger than the destination page in - // any dimension. If this is false, parts of the source PDF page that lie - // outside the bounds will be clipped. - // |stretch_to_fit| specifies whether the output should be stretched to fit - // the destination page if the source page size is smaller in all dimensions. - // |center_horizontally| specifies whether the output (after any scaling is - // done) should be centered horizontally within the destination page. - // |center_vertically| specifies whether the output (after any scaling is - // done) should be centered vertically within the destination page. - // Note that all scaling preserves the original aspect ratio of the page. - // |autorotate| specifies whether the source PDF should be autorotated to fit - // on the destination page. - struct MacRenderPageParams { - MacRenderPageParams() - : shrink_to_fit(false), - stretch_to_fit(false), - center_horizontally(false), - center_vertically(false), - autorotate(false) { - } - - bool shrink_to_fit; - bool stretch_to_fit; - bool center_horizontally; - bool center_vertically; - bool autorotate; - }; -#endif // defined(OS_MACOSX) MetafilePlayer(); virtual ~MetafilePlayer(); @@ -75,15 +41,6 @@ // issue with some printers. See Emf::Record::SafePlayback implementation for // details. virtual bool SafePlayback(skia::NativeDrawingContext hdc) const = 0; - -#elif defined(OS_MACOSX) - // Renders the given page into |rect| in the given context. - // Pages use a 1-based index. The rendering uses the arguments in - // |params| to determine scaling, translation, and rotation. - virtual bool RenderPage(unsigned int page_number, - skia::NativeDrawingContext context, - const CGRect rect, - const MacRenderPageParams& params) const = 0; #endif // if defined(OS_WIN) // Populates the buffer with the underlying data. This function should ONLY be
diff --git a/printing/pdf_metafile_cg_mac.cc b/printing/pdf_metafile_cg_mac.cc index 16744bf..898e795 100644 --- a/printing/pdf_metafile_cg_mac.cc +++ b/printing/pdf_metafile_cg_mac.cc
@@ -157,11 +157,24 @@ return true; } -bool PdfMetafileCg::RenderPage(unsigned int page_number, +/* TODO(caryclark): The set up of PluginInstance::PrintPDFOutput may result in + rasterized output. Even if that flow uses PdfMetafileCg::RenderPage, + the drawing of the PDF into the canvas may result in a rasterized output. + PDFMetafileSkia::RenderPage should be not implemented as shown and instead + should do something like the following CL in PluginInstance::PrintPDFOutput: + http://codereview.chromium.org/7200040/diff/1/webkit/plugins/ppapi/ppapi_plugin_instance.cc +*/ +bool PdfMetafileCg::RenderPage(const std::vector<char>& src_buffer, + unsigned int page_number, CGContextRef context, const CGRect rect, - const MacRenderPageParams& params) const { - CGPDFDocumentRef pdf_doc = GetPDFDocument(); + const PdfMetafileCg::RenderPageParams& params) { + PdfMetafileCg metafile; + if (!metafile.InitFromData(src_buffer.data(), src_buffer.size())) { + LOG(ERROR) << "Unable to initialize PDF document from data"; + return false; + } + CGPDFDocumentRef pdf_doc = metafile.GetPDFDocument(); if (!pdf_doc) { LOG(ERROR) << "Unable to create PDF document from data"; return false;
diff --git a/printing/pdf_metafile_cg_mac.h b/printing/pdf_metafile_cg_mac.h index f68ac4f..8992a8c66 100644 --- a/printing/pdf_metafile_cg_mac.h +++ b/printing/pdf_metafile_cg_mac.h
@@ -45,10 +45,38 @@ // the data returned from GetData will not be valid PDF data. CGContextRef context() const override; - bool RenderPage(unsigned int page_number, - skia::NativeDrawingContext context, - const CGRect rect, - const MacRenderPageParams& params) const override; + // |shrink_to_fit| specifies whether the output should be shrunk to fit a + // destination page if the source PDF is bigger than the destination page in + // any dimension. If this is false, parts of the source PDF page that lie + // outside the bounds will be clipped. + // + // |stretch_to_fit| specifies whether the output should be stretched to fit + // the destination page if the source page size is smaller in all dimensions. + // + // |center_horizontally| specifies whether the output (after any scaling is + // done) should be centered horizontally within the destination page. + // + // |center_vertically| specifies whether the output (after any scaling is + // done) should be centered vertically within the destination page. + // Note that all scaling preserves the original aspect ratio of the page. + // + // |autorotate| specifies whether the source PDF should be autorotated to fit + // on the destination page. + struct RenderPageParams { + bool shrink_to_fit = false; + bool stretch_to_fit = false; + bool center_horizontally = false; + bool center_vertically = false; + bool autorotate = false; + }; + // Renders the given page from |src_buffer| into |rect| in the given context. + // Pages use a 1-based index. The rendering uses the arguments in + // |params| to determine scaling, translation, and rotation. + static bool RenderPage(const std::vector<char>& src_buffer, + unsigned int page_number, + CGContextRef context, + const CGRect rect, + const RenderPageParams& params); private: // Returns a CGPDFDocumentRef version of |pdf_data_|.
diff --git a/printing/pdf_metafile_skia.cc b/printing/pdf_metafile_skia.cc index dd91494..54c1cf35 100644 --- a/printing/pdf_metafile_skia.cc +++ b/printing/pdf_metafile_skia.cc
@@ -24,14 +24,6 @@ #include "ui/gfx/geometry/safe_integer_conversions.h" #include "ui/gfx/skia_util.h" -#if defined(OS_MACOSX) -#include "printing/pdf_metafile_cg_mac.h" -#endif - -#if defined(OS_POSIX) -#include "base/file_descriptor_posix.h" -#endif - namespace { bool WriteAssetToBuffer(const SkStreamAsset* asset, @@ -104,10 +96,6 @@ float scale_factor_; SkSize size_; SkiaDocumentType type_; - -#if defined(OS_MACOSX) - PdfMetafileCg pdf_cg_; -#endif }; PdfMetafileSkia::~PdfMetafileSkia() {} @@ -255,30 +243,6 @@ NOTREACHED(); return false; } - -#elif defined(OS_MACOSX) -/* TODO(caryclark): The set up of PluginInstance::PrintPDFOutput may result in - rasterized output. Even if that flow uses PdfMetafileCg::RenderPage, - the drawing of the PDF into the canvas may result in a rasterized output. - PDFMetafileSkia::RenderPage should be not implemented as shown and instead - should do something like the following CL in PluginInstance::PrintPDFOutput: -http://codereview.chromium.org/7200040/diff/1/webkit/plugins/ppapi/ppapi_plugin_instance.cc -*/ -bool PdfMetafileSkia::RenderPage(unsigned int page_number, - CGContextRef context, - const CGRect rect, - const MacRenderPageParams& params) const { - DCHECK_GT(GetDataSize(), 0U); - if (data_->pdf_cg_.GetDataSize() == 0) { - if (GetDataSize() == 0) - return false; - size_t length = data_->pdf_data_->getLength(); - std::vector<uint8_t> buffer(length); - (void)WriteAssetToBuffer(data_->pdf_data_.get(), &buffer[0], length); - data_->pdf_cg_.InitFromData(&buffer[0], length); - } - return data_->pdf_cg_.RenderPage(page_number, context, rect, params); -} #endif bool PdfMetafileSkia::SaveTo(base::File* file) const {
diff --git a/printing/pdf_metafile_skia.h b/printing/pdf_metafile_skia.h index 948e27f..e27da152 100644 --- a/printing/pdf_metafile_skia.h +++ b/printing/pdf_metafile_skia.h
@@ -57,11 +57,6 @@ bool Playback(skia::NativeDrawingContext hdc, const RECT* rect) const override; bool SafePlayback(skia::NativeDrawingContext hdc) const override; -#elif defined(OS_MACOSX) - bool RenderPage(unsigned int page_number, - skia::NativeDrawingContext context, - const CGRect rect, - const MacRenderPageParams& params) const override; #endif bool SaveTo(base::File* file) const override;
diff --git a/printing/printed_document_mac.cc b/printing/printed_document_mac.cc index 73286966..0cd00e0 100644 --- a/printing/printed_document_mac.cc +++ b/printing/printed_document_mac.cc
@@ -4,11 +4,12 @@ #include "printing/printed_document.h" -#import <ApplicationServices/ApplicationServices.h> -#import <CoreFoundation/CoreFoundation.h> +#include <ApplicationServices/ApplicationServices.h> +#include <CoreFoundation/CoreFoundation.h> #include "base/logging.h" #include "printing/page_number.h" +#include "printing/pdf_metafile_cg_mac.h" #include "printing/printed_page.h" namespace printing { @@ -31,11 +32,16 @@ page.GetCenteredPageContentRect(page_setup.physical_size(), &content_area); const MetafilePlayer* metafile = page.metafile(); + // Each Metafile is a one-page PDF, and pages use 1-based indexing. const int page_number = 1; - struct Metafile::MacRenderPageParams params; + PdfMetafileCg::RenderPageParams params; params.autorotate = true; - metafile->RenderPage(page_number, context, content_area.ToCGRect(), params); + std::vector<char> buffer; + if (metafile->GetDataAsVector(&buffer)) { + PdfMetafileCg::RenderPage(buffer, page_number, context, + content_area.ToCGRect(), params); + } } } // namespace printing
diff --git a/remoting/client/chromoting_client.cc b/remoting/client/chromoting_client.cc index 8e8e77db..8029477 100644 --- a/remoting/client/chromoting_client.cc +++ b/remoting/client/chromoting_client.cc
@@ -233,7 +233,7 @@ DCHECK(thread_checker_.CalledOnValidThread()); if (state == SignalStrategy::CONNECTED) { - VLOG(1) << "Connected as: " << signal_strategy_->GetLocalJid(); + VLOG(1) << "Connected as: " << signal_strategy_->GetLocalAddress().jid(); // After signaling has been connected we can try connecting to the host. if (connection_ && connection_->state() == protocol::ConnectionToHost::INITIALIZING) { @@ -255,9 +255,10 @@ void ChromotingClient::StartConnection() { DCHECK(thread_checker_.CalledOnValidThread()); auto session = session_manager_->Connect( - host_jid_, base::MakeUnique<protocol::NegotiatingClientAuthenticator>( - NormalizeJid(signal_strategy_->GetLocalJid()), host_jid_, - client_auth_config_)); + SignalingAddress(host_jid_), + base::MakeUnique<protocol::NegotiatingClientAuthenticator>( + signal_strategy_->GetLocalAddress().id(), host_jid_, + client_auth_config_)); if (host_experiment_sender_) { session->AddPlugin(host_experiment_sender_.get()); }
diff --git a/remoting/client/plugin/chromoting_instance.cc b/remoting/client/plugin/chromoting_instance.cc index e586b50ac..8315903 100644 --- a/remoting/client/plugin/chromoting_instance.cc +++ b/remoting/client/plugin/chromoting_instance.cc
@@ -675,7 +675,7 @@ // Setup the signal strategy. signal_strategy_.reset(new DelegatingSignalStrategy( - local_jid, plugin_task_runner_, + SignalingAddress(local_jid), plugin_task_runner_, base::Bind(&ChromotingInstance::SendOutgoingIq, weak_factory_.GetWeakPtr())));
diff --git a/remoting/host/gcd_state_updater.cc b/remoting/host/gcd_state_updater.cc index d7d57c9..a49f7e2 100644 --- a/remoting/host/gcd_state_updater.cc +++ b/remoting/host/gcd_state_updater.cc
@@ -14,6 +14,7 @@ #include "base/values.h" #include "remoting/base/constants.h" #include "remoting/base/logging.h" +#include "remoting/signaling/signaling_address.h" namespace remoting { @@ -79,7 +80,7 @@ } if (result == GcdRestClient::NETWORK_ERROR || - pending_request_jid_ != signal_strategy_->GetLocalJid()) { + pending_request_jid_ != signal_strategy_->GetLocalAddress().jid()) { // Continue exponential backoff. return; } @@ -115,7 +116,7 @@ // Construct an update to the remote state. std::unique_ptr<base::DictionaryValue> patch(new base::DictionaryValue); std::unique_ptr<base::DictionaryValue> base_state(new base::DictionaryValue); - pending_request_jid_ = signal_strategy_->GetLocalJid(); + pending_request_jid_ = signal_strategy_->GetLocalAddress().jid(); base_state->SetString("_jabberId", pending_request_jid_); base_state->SetString("_hostVersion", STRINGIZE(VERSION)); patch->Set("base", std::move(base_state));
diff --git a/remoting/host/gcd_state_updater_unittest.cc b/remoting/host/gcd_state_updater_unittest.cc index adcf65d..160bd65 100644 --- a/remoting/host/gcd_state_updater_unittest.cc +++ b/remoting/host/gcd_state_updater_unittest.cc
@@ -35,12 +35,11 @@ token_getter_(OAuthTokenGetter::SUCCESS, "<fake_user_email>", "<fake_access_token>"), - rest_client_(new GcdRestClient( - "http://gcd_base_url", - "<gcd_device_id>", - nullptr, - &token_getter_)), - signal_strategy_("local_jid") { + rest_client_(new GcdRestClient("http://gcd_base_url", + "<gcd_device_id>", + nullptr, + &token_getter_)), + signal_strategy_(SignalingAddress("local_jid")) { rest_client_->SetClockForTest(base::WrapUnique(new base::SimpleTestClock)); } @@ -96,7 +95,7 @@ task_runner_->RunUntilIdle(); signal_strategy_.Disconnect(); task_runner_->RunUntilIdle(); - signal_strategy_.SetLocalJid("local_jid2"); + signal_strategy_.SetLocalAddress(SignalingAddress("local_jid2")); signal_strategy_.Connect(); task_runner_->RunUntilIdle();
diff --git a/remoting/host/heartbeat_sender.cc b/remoting/host/heartbeat_sender.cc index e452b5e..8df8890f5 100644 --- a/remoting/host/heartbeat_sender.cc +++ b/remoting/host/heartbeat_sender.cc
@@ -19,9 +19,9 @@ #include "remoting/host/host_details.h" #include "remoting/host/server_log_entry_host.h" #include "remoting/signaling/iq_sender.h" -#include "remoting/signaling/jid_util.h" #include "remoting/signaling/server_log_entry.h" #include "remoting/signaling/signal_strategy.h" +#include "remoting/signaling/signaling_address.h" #include "third_party/libjingle_xmpp/xmllite/xmlelement.h" #include "third_party/libjingle_xmpp/xmpp/constants.h" @@ -349,7 +349,7 @@ std::unique_ptr<XmlElement> signature_tag( new XmlElement(QName(kChromotingXmlNamespace, kHeartbeatSignatureTag))); - std::string message = NormalizeJid(signal_strategy_->GetLocalJid()) + ' ' + + std::string message = signal_strategy_->GetLocalAddress().jid() + ' ' + base::IntToString(sequence_id_); std::string signature(host_key_pair_->SignMessage(message)); signature_tag->AddText(signature);
diff --git a/remoting/host/heartbeat_sender_unittest.cc b/remoting/host/heartbeat_sender_unittest.cc index 06fab1c3..18f9126 100644 --- a/remoting/host/heartbeat_sender_unittest.cc +++ b/remoting/host/heartbeat_sender_unittest.cc
@@ -57,6 +57,8 @@ class HeartbeatSenderTest : public testing::Test { protected: + HeartbeatSenderTest() : signal_strategy_(SignalingAddress(kTestJid)) {} + void SetUp() override { key_pair_ = RsaKeyPair::FromString(kTestRsaKeyPair); ASSERT_TRUE(key_pair_.get()); @@ -66,8 +68,6 @@ .WillRepeatedly(AddListener(&signal_strategy_listeners_)); EXPECT_CALL(signal_strategy_, RemoveListener(NotNull())) .WillRepeatedly(RemoveListener(&signal_strategy_listeners_)); - EXPECT_CALL(signal_strategy_, GetLocalJid()) - .WillRepeatedly(Return(kTestJid)); EXPECT_CALL(mock_unknown_host_id_error_callback_, Run()) .Times(0); @@ -102,8 +102,6 @@ // Call Start() followed by Stop(), and make sure a valid heartbeat is sent. TEST_F(HeartbeatSenderTest, DoSendStanza) { XmlElement* sent_iq = nullptr; - EXPECT_CALL(signal_strategy_, GetLocalJid()) - .WillRepeatedly(Return(kTestJid)); EXPECT_CALL(signal_strategy_, GetNextId()) .WillOnce(Return(kStanzaId)); EXPECT_CALL(signal_strategy_, SendStanzaPtr(NotNull())) @@ -126,8 +124,6 @@ // are sent, with the correct sequence IDs. TEST_F(HeartbeatSenderTest, DoSendStanzaTwice) { XmlElement* sent_iq = nullptr; - EXPECT_CALL(signal_strategy_, GetLocalJid()) - .WillRepeatedly(Return(kTestJid)); EXPECT_CALL(signal_strategy_, GetNextId()) .WillOnce(Return(kStanzaId)); EXPECT_CALL(signal_strategy_, SendStanzaPtr(NotNull())) @@ -145,8 +141,6 @@ heartbeat_sender_->OnSignalStrategyStateChange(SignalStrategy::DISCONNECTED); base::RunLoop().RunUntilIdle(); - EXPECT_CALL(signal_strategy_, GetLocalJid()) - .WillRepeatedly(Return(kTestJid)); EXPECT_CALL(signal_strategy_, GetNextId()) .WillOnce(Return(kStanzaId + 1)); EXPECT_CALL(signal_strategy_, SendStanzaPtr(NotNull())) @@ -167,8 +161,6 @@ // are sent, with the correct sequence IDs. TEST_F(HeartbeatSenderTest, DoSendStanzaWithExpectedSequenceId) { XmlElement* sent_iq = nullptr; - EXPECT_CALL(signal_strategy_, GetLocalJid()) - .WillRepeatedly(Return(kTestJid)); EXPECT_CALL(signal_strategy_, GetNextId()) .WillOnce(Return(kStanzaId)); EXPECT_CALL(signal_strategy_, SendStanzaPtr(NotNull())) @@ -184,8 +176,6 @@ ValidateHeartbeatStanza(stanza.get(), "0", nullptr); XmlElement* sent_iq2 = nullptr; - EXPECT_CALL(signal_strategy_, GetLocalJid()) - .WillRepeatedly(Return(kTestJid)); EXPECT_CALL(signal_strategy_, GetNextId()) .WillOnce(Return(kStanzaId + 1)); EXPECT_CALL(signal_strategy_, SendStanzaPtr(NotNull())) @@ -248,8 +238,6 @@ XmlElement* sent_iq = nullptr; base::MockCallback<base::Callback<void(bool success)>> mock_ack_callback; - EXPECT_CALL(signal_strategy_, GetLocalJid()) - .WillRepeatedly(Return(kTestJid)); EXPECT_CALL(signal_strategy_, GetNextId()) .WillOnce(Return(kStanzaId)); EXPECT_CALL(signal_strategy_, SendStanzaPtr(NotNull())) @@ -276,8 +264,6 @@ TEST_F(HeartbeatSenderTest, ProcessHostOfflineResponses) { base::MockCallback<base::Callback<void(bool success)>> mock_ack_callback; - EXPECT_CALL(signal_strategy_, GetLocalJid()) - .WillRepeatedly(Return(kTestJid)); EXPECT_CALL(signal_strategy_, GetNextId()) .WillOnce(Return(kStanzaId)); EXPECT_CALL(signal_strategy_, SendStanzaPtr(NotNull())) @@ -321,8 +307,6 @@ // The first heartbeat should include host OS information. TEST_F(HeartbeatSenderTest, HostOsInfo) { XmlElement* sent_iq = nullptr; - EXPECT_CALL(signal_strategy_, GetLocalJid()) - .WillRepeatedly(Return(kTestJid)); EXPECT_CALL(signal_strategy_, GetNextId()) .WillOnce(Return(kStanzaId)); EXPECT_CALL(signal_strategy_, SendStanzaPtr(NotNull()))
diff --git a/remoting/host/host_change_notification_listener.cc b/remoting/host/host_change_notification_listener.cc index 3c079f1..c80af519 100644 --- a/remoting/host/host_change_notification_listener.cc +++ b/remoting/host/host_change_notification_listener.cc
@@ -55,9 +55,13 @@ const std::string& host_id = host_changed_element->Attr(QName(kChromotingXmlNamespace, "hostid")); const std::string& from = stanza->Attr(buzz::QN_FROM); - const std::string& to = stanza->Attr(buzz::QN_TO); + + std::string to_error; + SignalingAddress to = + SignalingAddress::Parse(stanza, SignalingAddress::TO, &to_error); + if (host_id == host_id_ && from == directory_bot_jid_ && - to == signal_strategy_->GetLocalJid()) { + to == signal_strategy_->GetLocalAddress()) { const std::string& operation = host_changed_element->Attr(QName(kChromotingXmlNamespace, "operation")); if (operation == "delete") {
diff --git a/remoting/host/host_change_notification_listener_unittest.cc b/remoting/host/host_change_notification_listener_unittest.cc index 7bbf290b..aea4233 100644 --- a/remoting/host/host_change_notification_listener_unittest.cc +++ b/remoting/host/host_change_notification_listener_unittest.cc
@@ -14,6 +14,7 @@ #include "base/strings/string_number_conversions.h" #include "remoting/base/constants.h" #include "remoting/signaling/mock_signal_strategy.h" +#include "remoting/signaling/signaling_address.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/libjingle_xmpp/xmllite/xmlelement.h" @@ -45,6 +46,8 @@ class HostChangeNotificationListenerTest : public testing::Test { protected: + HostChangeNotificationListenerTest() + : signal_strategy_(SignalingAddress(kTestJid)) {} class MockListener : public HostChangeNotificationListener::Listener { public: MOCK_METHOD0(OnHostDeleted, void()); @@ -55,8 +58,6 @@ .WillRepeatedly(AddListener(&signal_strategy_listeners_)); EXPECT_CALL(signal_strategy_, RemoveListener(NotNull())) .WillRepeatedly(RemoveListener(&signal_strategy_listeners_)); - EXPECT_CALL(signal_strategy_, GetLocalJid()) - .WillRepeatedly(Return(kTestJid)); host_change_notification_listener_.reset(new HostChangeNotificationListener( &mock_listener_, kHostId, &signal_strategy_, kTestBotJid));
diff --git a/remoting/host/host_status_logger_unittest.cc b/remoting/host/host_status_logger_unittest.cc index fee9ae4..01160ee 100644 --- a/remoting/host/host_status_logger_unittest.cc +++ b/remoting/host/host_status_logger_unittest.cc
@@ -124,7 +124,7 @@ class HostStatusLoggerTest : public testing::Test { public: - HostStatusLoggerTest() {} + HostStatusLoggerTest() : signal_strategy_(SignalingAddress(kHostJid)) {} void SetUp() override { EXPECT_CALL(signal_strategy_, AddListener(_)); host_status_logger_.reset( @@ -146,8 +146,6 @@ base::RunLoop run_loop; { InSequence s; - EXPECT_CALL(signal_strategy_, GetLocalJid()) - .WillRepeatedly(Return(kHostJid)); EXPECT_CALL(signal_strategy_, AddListener(_)); EXPECT_CALL(signal_strategy_, GetNextId()); EXPECT_CALL(signal_strategy_, SendStanzaPtr(IsClientConnected("direct"))) @@ -174,10 +172,9 @@ host_status_logger_->OnClientRouteChange(kClientJid1, "video", route); host_status_logger_->OnClientAuthenticated(kClientJid1); host_status_logger_->OnClientConnected(kClientJid1); + { InSequence s; - EXPECT_CALL(signal_strategy_, GetLocalJid()) - .WillRepeatedly(Return(kHostJid)); EXPECT_CALL(signal_strategy_, AddListener(_)); EXPECT_CALL(signal_strategy_, GetNextId()); EXPECT_CALL(signal_strategy_, SendStanzaPtr(IsClientConnected("direct"))) @@ -203,10 +200,9 @@ host_status_logger_->OnClientRouteChange(kClientJid2, "video", route2); host_status_logger_->OnClientAuthenticated(kClientJid2); host_status_logger_->OnClientConnected(kClientJid2); + { InSequence s; - EXPECT_CALL(signal_strategy_, GetLocalJid()) - .WillRepeatedly(Return(kHostJid)); EXPECT_CALL(signal_strategy_, AddListener(_)); EXPECT_CALL(signal_strategy_, GetNextId()); EXPECT_CALL(signal_strategy_, @@ -223,10 +219,9 @@ TEST_F(HostStatusLoggerTest, HandleRouteChangeInUnusualOrder) { base::RunLoop run_loop; + { InSequence s; - EXPECT_CALL(signal_strategy_, GetLocalJid()) - .WillRepeatedly(Return(kHostJid)); EXPECT_CALL(signal_strategy_, AddListener(_)); EXPECT_CALL(signal_strategy_, GetNextId()); EXPECT_CALL(signal_strategy_, SendStanzaPtr(IsClientConnected("direct")))
diff --git a/remoting/host/it2me/it2me_host_unittest.cc b/remoting/host/it2me/it2me_host_unittest.cc index ef11fbd9..22a719a1 100644 --- a/remoting/host/it2me/it2me_host_unittest.cc +++ b/remoting/host/it2me/it2me_host_unittest.cc
@@ -188,11 +188,12 @@ std::unique_ptr<FakeIt2MeDialogFactory> dialog_factory( new FakeIt2MeDialogFactory()); dialog_factory_ = dialog_factory.get(); - it2me_host_ = - new It2MeHost(std::move(host_context), /*policy_watcher=*/nullptr, - std::move(dialog_factory), weak_factory_.GetWeakPtr(), - base::WrapUnique(new FakeSignalStrategy("fake_local_jid")), - "fake_user_name", "fake_bot_jid"); + it2me_host_ = new It2MeHost( + std::move(host_context), /*policy_watcher=*/nullptr, + std::move(dialog_factory), weak_factory_.GetWeakPtr(), + base::WrapUnique( + new FakeSignalStrategy(SignalingAddress("fake_local_jid"))), + "fake_user_name", "fake_bot_jid"); } void It2MeHostTest::TearDown() {
diff --git a/remoting/host/it2me/it2me_native_messaging_host.cc b/remoting/host/it2me/it2me_native_messaging_host.cc index 0b3a716..9580d3d5 100644 --- a/remoting/host/it2me/it2me_native_messaging_host.cc +++ b/remoting/host/it2me/it2me_native_messaging_host.cc
@@ -298,7 +298,7 @@ auto delegating_signal_strategy = base::MakeUnique<DelegatingSignalStrategy>( - local_jid, host_context_->network_task_runner(), + SignalingAddress(local_jid), host_context_->network_task_runner(), base::Bind(&It2MeNativeMessagingHost::SendOutgoingIq, weak_factory_.GetWeakPtr())); incoming_message_callback_ =
diff --git a/remoting/host/linux/certificate_watcher_unittest.cc b/remoting/host/linux/certificate_watcher_unittest.cc index 10cb564..6738812 100644 --- a/remoting/host/linux/certificate_watcher_unittest.cc +++ b/remoting/host/linux/certificate_watcher_unittest.cc
@@ -90,8 +90,9 @@ EXPECT_TRUE(base::AppendToFile(path, testWriteString.c_str(), testWriteString.length())); } else { - EXPECT_TRUE(base::WriteFile(path, testWriteString.c_str(), - testWriteString.length())); + EXPECT_EQ(static_cast<int>(testWriteString.length()), + base::WriteFile(path, testWriteString.c_str(), + testWriteString.length())); } }
diff --git a/remoting/host/register_support_host_request.cc b/remoting/host/register_support_host_request.cc index 786c3119..72c2345 100644 --- a/remoting/host/register_support_host_request.cc +++ b/remoting/host/register_support_host_request.cc
@@ -17,6 +17,7 @@ #include "remoting/signaling/iq_sender.h" #include "remoting/signaling/jid_util.h" #include "remoting/signaling/signal_strategy.h" +#include "remoting/signaling/signaling_address.h" #include "third_party/libjingle_xmpp/xmllite/xmlelement.h" #include "third_party/libjingle_xmpp/xmpp/constants.h" @@ -65,7 +66,7 @@ request_ = iq_sender_->SendIq( buzz::STR_SET, directory_bot_jid_, - CreateRegistrationRequest(signal_strategy_->GetLocalJid()), + CreateRegistrationRequest(signal_strategy_->GetLocalAddress().jid()), base::Bind(&RegisterSupportHostRequest::ProcessResponse, base::Unretained(this))); } else if (state == SignalStrategy::DISCONNECTED) {
diff --git a/remoting/host/register_support_host_request_unittest.cc b/remoting/host/register_support_host_request_unittest.cc index a23a59e..b97c192 100644 --- a/remoting/host/register_support_host_request_unittest.cc +++ b/remoting/host/register_support_host_request_unittest.cc
@@ -18,6 +18,7 @@ #include "remoting/base/test_rsa_key_pair.h" #include "remoting/signaling/iq_sender.h" #include "remoting/signaling/mock_signal_strategy.h" +#include "remoting/signaling/signaling_address.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/libjingle_xmpp/xmllite/xmlelement.h" @@ -54,6 +55,9 @@ class RegisterSupportHostRequestTest : public testing::Test { public: protected: + RegisterSupportHostRequestTest() + : signal_strategy_(SignalingAddress(kTestJid)) {} + void SetUp() override { key_pair_ = RsaKeyPair::FromString(kTestRsaKeyPair); ASSERT_TRUE(key_pair_.get()); @@ -62,8 +66,6 @@ .WillRepeatedly(AddListener(&signal_strategy_listeners_)); EXPECT_CALL(signal_strategy_, RemoveListener(NotNull())) .WillRepeatedly(RemoveListener(&signal_strategy_listeners_)); - EXPECT_CALL(signal_strategy_, GetLocalJid()) - .WillRepeatedly(Return(kTestJid)); } base::MessageLoop message_loop_;
diff --git a/remoting/host/signaling_connector.cc b/remoting/host/signaling_connector.cc index 1309403..1b617f4 100644 --- a/remoting/host/signaling_connector.cc +++ b/remoting/host/signaling_connector.cc
@@ -14,6 +14,7 @@ #include "net/url_request/url_request_context_getter.h" #include "remoting/base/logging.h" #include "remoting/host/dns_blackhole_checker.h" +#include "remoting/signaling/signaling_address.h" namespace remoting { @@ -70,7 +71,7 @@ if (state == SignalStrategy::CONNECTED) { HOST_LOG << "Signaling connected. New JID: " - << signal_strategy_->GetLocalJid(); + << signal_strategy_->GetLocalAddress().jid(); reconnect_attempts_ = 0; } else if (state == SignalStrategy::DISCONNECTED) { HOST_LOG << "Signaling disconnected. error="
diff --git a/remoting/protocol/fake_authenticator.cc b/remoting/protocol/fake_authenticator.cc index a57845c..4dbde8d 100644 --- a/remoting/protocol/fake_authenticator.cc +++ b/remoting/protocol/fake_authenticator.cc
@@ -89,11 +89,25 @@ base::ResetAndReturn(&done_callback_).Run(result_, std::move(socket_)); } +FakeAuthenticator::Config::Config() {} +FakeAuthenticator::Config::Config(Action action) : action(action) {} +FakeAuthenticator::Config::Config(int round_trips, Action action, bool async) + : round_trips(round_trips), action(action), async(async) {} + FakeAuthenticator::FakeAuthenticator(Type type, - int round_trips, - Action action, - bool async) - : type_(type), round_trips_(round_trips), action_(action), async_(async) {} + FakeAuthenticator::Config config, + const std::string& local_id, + const std::string& remote_id) + : type_(type), config_(config), local_id_(local_id), remote_id_(remote_id) { + EXPECT_TRUE((!local_id_.empty() && !remote_id_.empty()) || + config.round_trips == 0); +} + +FakeAuthenticator::FakeAuthenticator(Action action) + : FakeAuthenticator(CLIENT, + FakeAuthenticator::Config(0, action, true), + std::string(), + std::string()) {} FakeAuthenticator::~FakeAuthenticator() {} @@ -106,13 +120,13 @@ } Authenticator::State FakeAuthenticator::state() const { - EXPECT_LE(messages_, round_trips_ * 2); + EXPECT_LE(messages_, config_.round_trips * 2); if (messages_ == pause_message_index_ && !resume_closure_.is_null()) return PROCESSING_MESSAGE; - if (messages_ >= round_trips_ * 2) { - if (action_ == REJECT) { + if (messages_ >= config_.round_trips * 2) { + if (config_.action == REJECT) { return REJECTED; } else { return ACCEPTED; @@ -121,8 +135,8 @@ // Don't send the last message if this is a host that wants to // reject a connection. - if (messages_ == round_trips_ * 2 - 1 && - type_ == HOST && action_ == REJECT) { + if (messages_ == config_.round_trips * 2 - 1 && type_ == HOST && + config_.action == REJECT) { return REJECTED; } @@ -152,13 +166,18 @@ EXPECT_EQ(id, base::IntToString(messages_)); // On the client receive the key in the last message. - if (type_ == CLIENT && messages_ == round_trips_ * 2 - 1) { + if (type_ == CLIENT && messages_ == config_.round_trips * 2 - 1) { std::string key_base64 = message->TextNamed(buzz::QName(kChromotingXmlNamespace, "key")); EXPECT_TRUE(!key_base64.empty()); EXPECT_TRUE(base::Base64Decode(key_base64, &auth_key_)); } + // Receive peer's id. + if (messages_ < 2) { + EXPECT_EQ(remote_id_, message->Attr(buzz::QName("", "id"))); + } + ++messages_; if (messages_ == pause_message_index_) { resume_closure_ = resume_callback; @@ -177,8 +196,13 @@ id->AddText(base::IntToString(messages_)); result->AddElement(id); + // Send local id in the first outgoing message. + if (messages_ < 2) { + result->AddAttr(buzz::QName("", "id"), local_id_); + } + // Add authentication key in the last message sent from host to client. - if (type_ == HOST && messages_ == round_trips_ * 2 - 1) { + if (type_ == HOST && messages_ == config_.round_trips * 2 - 1) { auth_key_ = base::RandBytesAsString(16); buzz::XmlElement* key = new buzz::XmlElement( buzz::QName(kChromotingXmlNamespace, "key")); @@ -201,19 +225,14 @@ std::unique_ptr<ChannelAuthenticator> FakeAuthenticator::CreateChannelAuthenticator() const { EXPECT_EQ(ACCEPTED, state()); - return base::MakeUnique<FakeChannelAuthenticator>(action_ != REJECT_CHANNEL, - async_); + return base::MakeUnique<FakeChannelAuthenticator>( + config_.action != REJECT_CHANNEL, config_.async); } FakeHostAuthenticatorFactory::FakeHostAuthenticatorFactory( - int round_trips, int messages_till_started, - FakeAuthenticator::Action action, - bool async) - : round_trips_(round_trips), - messages_till_started_(messages_till_started), - action_(action), - async_(async) {} + FakeAuthenticator::Config config) + : messages_till_started_(messages_till_started), config_(config) {} FakeHostAuthenticatorFactory::~FakeHostAuthenticatorFactory() {} std::unique_ptr<Authenticator> @@ -221,7 +240,7 @@ const std::string& local_jid, const std::string& remote_jid) { std::unique_ptr<FakeAuthenticator> authenticator(new FakeAuthenticator( - FakeAuthenticator::HOST, round_trips_, action_, async_)); + FakeAuthenticator::HOST, config_, local_jid, remote_jid)); authenticator->set_messages_till_started(messages_till_started_); return std::move(authenticator); }
diff --git a/remoting/protocol/fake_authenticator.h b/remoting/protocol/fake_authenticator.h index 8d0ac2f..3c61e735 100644 --- a/remoting/protocol/fake_authenticator.h +++ b/remoting/protocol/fake_authenticator.h
@@ -56,7 +56,24 @@ REJECT_CHANNEL }; - FakeAuthenticator(Type type, int round_trips, Action action, bool async); + struct Config { + Config(); + Config(Action action); + Config(int round_trips, Action action, bool async); + + int round_trips = 1; + Action action = Action::ACCEPT; + bool async = true; + }; + + FakeAuthenticator(Type type, + Config config, + const std::string& local_id, + const std::string& remote_id); + + // Special constructor for authenticators in ACCEPTED or REJECTED state that + // don't exchange any messages. + FakeAuthenticator(Action action); ~FakeAuthenticator() override; @@ -89,9 +106,9 @@ protected: const Type type_; - const int round_trips_; - const Action action_; - const bool async_; + const Config config_; + const std::string local_id_; + const std::string remote_id_; // Total number of messages that have been processed. int messages_ = 0; @@ -109,9 +126,8 @@ class FakeHostAuthenticatorFactory : public AuthenticatorFactory { public: - FakeHostAuthenticatorFactory( - int round_trips, int messages_till_start, - FakeAuthenticator::Action action, bool async); + FakeHostAuthenticatorFactory(int messages_till_start, + FakeAuthenticator::Config config); ~FakeHostAuthenticatorFactory() override; // AuthenticatorFactory interface. @@ -120,10 +136,8 @@ const std::string& remote_jid) override; private: - const int round_trips_; const int messages_till_started_; - const FakeAuthenticator::Action action_; - const bool async_; + const FakeAuthenticator::Config config_; DISALLOW_COPY_AND_ASSIGN(FakeHostAuthenticatorFactory); };
diff --git a/remoting/protocol/fake_session.cc b/remoting/protocol/fake_session.cc index 5c6d1806..b2076b0 100644 --- a/remoting/protocol/fake_session.cc +++ b/remoting/protocol/fake_session.cc
@@ -34,16 +34,14 @@ peer->event_handler_->OnSessionStateChange(AUTHENTICATING); // Initialize transport and authenticator on the client. - authenticator_.reset(new FakeAuthenticator(FakeAuthenticator::CLIENT, 0, - FakeAuthenticator::ACCEPT, false)); + authenticator_.reset(new FakeAuthenticator(FakeAuthenticator::ACCEPT)); authenticator_->set_auth_key(kTestAuthKey); transport_->Start(authenticator_.get(), base::Bind(&FakeSession::SendTransportInfo, weak_factory_.GetWeakPtr())); // Initialize transport and authenticator on the host. - peer->authenticator_.reset(new FakeAuthenticator( - FakeAuthenticator::HOST, 0, FakeAuthenticator::ACCEPT, false)); + peer->authenticator_.reset(new FakeAuthenticator(FakeAuthenticator::ACCEPT)); peer->authenticator_->set_auth_key(kTestAuthKey); peer->transport_->Start(peer->authenticator_.get(), base::Bind(&FakeSession::SendTransportInfo, peer_));
diff --git a/remoting/protocol/ice_transport_unittest.cc b/remoting/protocol/ice_transport_unittest.cc index 8c5abd3..c754435 100644 --- a/remoting/protocol/ice_transport_unittest.cc +++ b/remoting/protocol/ice_transport_unittest.cc
@@ -119,8 +119,8 @@ nullptr, network_settings_, TransportRole::SERVER), &host_event_handler_)); if (!host_authenticator_) { - host_authenticator_.reset(new FakeAuthenticator( - FakeAuthenticator::HOST, 0, FakeAuthenticator::ACCEPT, true)); + host_authenticator_.reset( + new FakeAuthenticator(FakeAuthenticator::ACCEPT)); } client_transport_.reset(new IceTransport( @@ -129,8 +129,8 @@ nullptr, network_settings_, TransportRole::CLIENT), &client_event_handler_)); if (!client_authenticator_) { - client_authenticator_.reset(new FakeAuthenticator( - FakeAuthenticator::CLIENT, 0, FakeAuthenticator::ACCEPT, true)); + client_authenticator_.reset( + new FakeAuthenticator(FakeAuthenticator::ACCEPT)); } host_event_handler_.set_error_callback(base::Bind( @@ -243,8 +243,8 @@ TEST_F(IceTransportTest, FailedChannelAuth) { // Use host authenticator with one that rejects channel authentication. - host_authenticator_.reset(new FakeAuthenticator( - FakeAuthenticator::HOST, 0, FakeAuthenticator::REJECT_CHANNEL, true)); + host_authenticator_.reset( + new FakeAuthenticator(FakeAuthenticator::REJECT_CHANNEL)); InitializeConnection();
diff --git a/remoting/protocol/jingle_session.cc b/remoting/protocol/jingle_session.cc index 72043a9..14d3350 100644 --- a/remoting/protocol/jingle_session.cc +++ b/remoting/protocol/jingle_session.cc
@@ -197,13 +197,13 @@ } void JingleSession::StartConnection( - const std::string& peer_jid, + const SignalingAddress& peer_address, std::unique_ptr<Authenticator> authenticator) { DCHECK(thread_checker_.CalledOnValidThread()); DCHECK(authenticator.get()); DCHECK_EQ(authenticator->state(), Authenticator::MESSAGE_READY); - peer_address_ = SignalingAddress(peer_jid); + peer_address_ = peer_address; authenticator_ = std::move(authenticator); // Generate random session ID. There are usually not more than 1 @@ -792,7 +792,8 @@ } std::unique_ptr<JingleMessage> message(new JingleMessage( peer_address_, JingleMessage::SESSION_INITIATE, session_id_)); - message->initiator = session_manager_->signal_strategy_->GetLocalJid(); + message->initiator = + session_manager_->signal_strategy_->GetLocalAddress().jid(); message->description.reset(new ContentDescription( session_manager_->protocol_config_->Clone(), authenticator_->GetNextMessage()));
diff --git a/remoting/protocol/jingle_session.h b/remoting/protocol/jingle_session.h index 00a7b1e2..3b9c1fe0 100644 --- a/remoting/protocol/jingle_session.h +++ b/remoting/protocol/jingle_session.h
@@ -53,7 +53,7 @@ explicit JingleSession(JingleSessionManager* session_manager); // Start connection by sending session-initiate message. - void StartConnection(const std::string& peer_jid, + void StartConnection(const SignalingAddress& peer_address, std::unique_ptr<Authenticator> authenticator); // Called by JingleSessionManager for incoming connections.
diff --git a/remoting/protocol/jingle_session_manager.cc b/remoting/protocol/jingle_session_manager.cc index 5d564f7..c13cdb09 100644 --- a/remoting/protocol/jingle_session_manager.cc +++ b/remoting/protocol/jingle_session_manager.cc
@@ -46,10 +46,10 @@ } std::unique_ptr<Session> JingleSessionManager::Connect( - const std::string& host_jid, + const SignalingAddress& peer_address, std::unique_ptr<Authenticator> authenticator) { std::unique_ptr<JingleSession> session(new JingleSession(this)); - session->StartConnection(host_jid, std::move(authenticator)); + session->StartConnection(peer_address, std::move(authenticator)); sessions_[session->session_id_] = session.get(); return std::move(session); } @@ -84,7 +84,7 @@ std::unique_ptr<Authenticator> authenticator = authenticator_factory_->CreateAuthenticator( - signal_strategy_->GetLocalJid(), message->from.id()); + signal_strategy_->GetLocalAddress().id(), message->from.id()); JingleSession* session = new JingleSession(this); session->InitializeIncomingConnection(*message,
diff --git a/remoting/protocol/jingle_session_manager.h b/remoting/protocol/jingle_session_manager.h index c1d7311..2024a7a4 100644 --- a/remoting/protocol/jingle_session_manager.h +++ b/remoting/protocol/jingle_session_manager.h
@@ -41,7 +41,7 @@ void set_protocol_config( std::unique_ptr<CandidateSessionConfig> config) override; std::unique_ptr<Session> Connect( - const std::string& host_jid, + const SignalingAddress& peer_address, std::unique_ptr<Authenticator> authenticator) override; void set_authenticator_factory( std::unique_ptr<AuthenticatorFactory> authenticator_factory) override;
diff --git a/remoting/protocol/jingle_session_unittest.cc b/remoting/protocol/jingle_session_unittest.cc index 4575e6e1..2c3c61b 100644 --- a/remoting/protocol/jingle_session_unittest.cc +++ b/remoting/protocol/jingle_session_unittest.cc
@@ -52,8 +52,11 @@ namespace { -const char kHostJid[] = "host@gmail.com/123"; -const char kClientJid[] = "client@gmail.com/321"; +const char kHostJid[] = "Host@gmail.com/123"; +const char kClientJid[] = "Client@gmail.com/321"; + +// kHostJid the way it would be stored in the directory. +const char kNormalizedHostJid[] = "host@gmail.com/123"; class MockSessionManagerListener { public: @@ -182,12 +185,13 @@ client_session_.reset(); } - void CreateSessionManagers(int auth_round_trips, int messages_till_start, - FakeAuthenticator::Action auth_action) { - if (!host_signal_strategy_) - host_signal_strategy_.reset(new FakeSignalStrategy(kHostJid)); - if (!client_signal_strategy_) - client_signal_strategy_.reset(new FakeSignalStrategy(kClientJid)); + void CreateSessionManagers(FakeAuthenticator::Config auth_config, + int messages_till_start) { + host_signal_strategy_ = + base::MakeUnique<FakeSignalStrategy>(SignalingAddress(kHostJid)); + client_signal_strategy_ = + base::MakeUnique<FakeSignalStrategy>(SignalingAddress(kClientJid)); + FakeSignalStrategy::Connect(host_signal_strategy_.get(), client_signal_strategy_.get()); @@ -197,17 +201,15 @@ base::Unretained(&host_server_listener_))); std::unique_ptr<AuthenticatorFactory> factory( - new FakeHostAuthenticatorFactory(auth_round_trips, messages_till_start, - auth_action, true)); + new FakeHostAuthenticatorFactory(messages_till_start, auth_config)); host_server_->set_authenticator_factory(std::move(factory)); client_server_.reset( new JingleSessionManager(client_signal_strategy_.get())); } - void CreateSessionManagers(int auth_round_trips, - FakeAuthenticator::Action auth_action) { - CreateSessionManagers(auth_round_trips, 0, auth_action); + void CreateSessionManagers(FakeAuthenticator::Config auth_config) { + CreateSessionManagers(auth_config, 0); } void CloseSessionManager() { @@ -273,21 +275,25 @@ } void ConnectClient(std::unique_ptr<Authenticator> authenticator) { - client_session_ = - client_server_->Connect(host_jid_, std::move(authenticator)); + client_session_ = client_server_->Connect( + SignalingAddress(kNormalizedHostJid), std::move(authenticator)); client_session_->SetEventHandler(&client_session_event_handler_); client_session_->SetTransport(&client_transport_); client_session_->AddPlugin(&client_plugin_); base::RunLoop().RunUntilIdle(); } - void InitiateConnection(int auth_round_trips, - FakeAuthenticator::Action auth_action, + void ConnectClient(FakeAuthenticator::Config auth_config) { + ConnectClient(base::MakeUnique<FakeAuthenticator>( + FakeAuthenticator::CLIENT, auth_config, + client_signal_strategy_->GetLocalAddress().id(), kNormalizedHostJid)); + } + + void InitiateConnection(FakeAuthenticator::Config auth_config, bool expect_fail) { SetHostExpectation(expect_fail); SetClientExpectation(expect_fail); - ConnectClient(base::MakeUnique<FakeAuthenticator>( - FakeAuthenticator::CLIENT, auth_round_trips, auth_action, true)); + ConnectClient(auth_config); } void ExpectRouteChange(const std::string& channel_name) { @@ -322,8 +328,6 @@ std::unique_ptr<FakeSignalStrategy> host_signal_strategy_; std::unique_ptr<FakeSignalStrategy> client_signal_strategy_; - std::string host_jid_ = kHostJid; - std::unique_ptr<JingleSessionManager> host_server_; MockSessionManagerListener host_server_listener_; std::unique_ptr<JingleSessionManager> client_server_; @@ -343,13 +347,13 @@ // Verify that we can create and destroy session managers without a // connection. TEST_F(JingleSessionTest, CreateAndDestoy) { - CreateSessionManagers(1, FakeAuthenticator::ACCEPT); + CreateSessionManagers(FakeAuthenticator::Config(FakeAuthenticator::ACCEPT)); } // Verify that an incoming session can be rejected, and that the // status of the connection is set to FAILED in this case. TEST_F(JingleSessionTest, RejectConnection) { - CreateSessionManagers(1, FakeAuthenticator::ACCEPT); + CreateSessionManagers(FakeAuthenticator::Config(FakeAuthenticator::ACCEPT)); // Reject incoming session. EXPECT_CALL(host_server_listener_, OnIncomingSession(_, _)) @@ -362,9 +366,7 @@ .Times(1); } - std::unique_ptr<Authenticator> authenticator(new FakeAuthenticator( - FakeAuthenticator::CLIENT, 1, FakeAuthenticator::ACCEPT, true)); - client_session_ = client_server_->Connect(kHostJid, std::move(authenticator)); + ConnectClient(FakeAuthenticator::Config(FakeAuthenticator::ACCEPT)); client_session_->SetEventHandler(&client_session_event_handler_); base::RunLoop().RunUntilIdle(); @@ -372,8 +374,8 @@ // Verify that we can connect two endpoints with single-step authentication. TEST_F(JingleSessionTest, Connect) { - CreateSessionManagers(1, FakeAuthenticator::ACCEPT); - InitiateConnection(1, FakeAuthenticator::ACCEPT, false); + CreateSessionManagers(FakeAuthenticator::Config(FakeAuthenticator::ACCEPT)); + InitiateConnection(FakeAuthenticator::Config(), false); // Verify that the client specified correct initiator value. ASSERT_GT(host_signal_strategy_->received_messages().size(), 0U); @@ -382,37 +384,22 @@ const buzz::XmlElement* jingle_element = initiate_xml->FirstNamed(buzz::QName("urn:xmpp:jingle:1", "jingle")); ASSERT_TRUE(jingle_element); - ASSERT_EQ(kClientJid, + ASSERT_EQ(client_signal_strategy_->GetLocalAddress().id(), jingle_element->Attr(buzz::QName(std::string(), "initiator"))); } -TEST_F(JingleSessionTest, MixedCaseHostJid) { - std::string host_jid = std::string("A") + kHostJid; - host_signal_strategy_.reset(new FakeSignalStrategy(host_jid)); - - // Imitate host JID being lower-cased when stored in the directory. - host_jid_ = base::ToLowerASCII(host_jid); - - CreateSessionManagers(1, FakeAuthenticator::ACCEPT); - InitiateConnection(1, FakeAuthenticator::ACCEPT, false); -} - -TEST_F(JingleSessionTest, MixedCaseClientJid) { - client_signal_strategy_.reset( - new FakeSignalStrategy(std::string("A") + kClientJid)); - CreateSessionManagers(1, FakeAuthenticator::ACCEPT); - InitiateConnection(1, FakeAuthenticator::ACCEPT, false); -} - // Verify that we can connect two endpoints with multi-step authentication. TEST_F(JingleSessionTest, ConnectWithMultistep) { - CreateSessionManagers(3, FakeAuthenticator::ACCEPT); - InitiateConnection(3, FakeAuthenticator::ACCEPT, false); + const int kAuthRoundtrips = 3; + FakeAuthenticator::Config auth_config(kAuthRoundtrips, + FakeAuthenticator::ACCEPT, true); + CreateSessionManagers(auth_config); + InitiateConnection(auth_config, false); } TEST_F(JingleSessionTest, ConnectWithOutOfOrderIqs) { - CreateSessionManagers(1, FakeAuthenticator::ACCEPT); - InitiateConnection(1, FakeAuthenticator::ACCEPT, false); + CreateSessionManagers(FakeAuthenticator::Config(FakeAuthenticator::ACCEPT)); + InitiateConnection(FakeAuthenticator::Config(), false); client_signal_strategy_->SimulateMessageReordering(); // Verify that out of order transport messages are received correctly. @@ -428,8 +415,8 @@ // Verify that out-of-order messages are handled correctly when the session is // torn down after the first message. TEST_F(JingleSessionTest, ConnectWithOutOfOrderIqsDestroyOnFirstMessage) { - CreateSessionManagers(1, FakeAuthenticator::ACCEPT); - InitiateConnection(1, FakeAuthenticator::ACCEPT, false); + CreateSessionManagers(FakeAuthenticator::Config(FakeAuthenticator::ACCEPT)); + InitiateConnection(FakeAuthenticator::Config(), false); client_signal_strategy_->SimulateMessageReordering(); // Verify that out of order transport messages are received correctly. @@ -448,19 +435,23 @@ // Verify that connection is terminated when single-step auth fails. TEST_F(JingleSessionTest, ConnectWithBadAuth) { - CreateSessionManagers(1, FakeAuthenticator::REJECT); - InitiateConnection(1, FakeAuthenticator::ACCEPT, true); + CreateSessionManagers(FakeAuthenticator::Config(FakeAuthenticator::REJECT)); + InitiateConnection(FakeAuthenticator::Config(), true); } // Verify that connection is terminated when multi-step auth fails. TEST_F(JingleSessionTest, ConnectWithBadMultistepAuth) { - CreateSessionManagers(3, FakeAuthenticator::REJECT); - InitiateConnection(3, FakeAuthenticator::ACCEPT, true); + const int kAuthRoundtrips = 3; + CreateSessionManagers(FakeAuthenticator::Config( + kAuthRoundtrips, FakeAuthenticator::REJECT, false)); + InitiateConnection(FakeAuthenticator::Config( + kAuthRoundtrips, FakeAuthenticator::ACCEPT, false), + true); } // Verify that incompatible protocol configuration is handled properly. TEST_F(JingleSessionTest, TestIncompatibleProtocol) { - CreateSessionManagers(1, FakeAuthenticator::ACCEPT); + CreateSessionManagers(FakeAuthenticator::Config(FakeAuthenticator::ACCEPT)); EXPECT_CALL(host_server_listener_, OnIncomingSession(_, _)).Times(0); @@ -468,18 +459,12 @@ OnSessionStateChange(Session::FAILED)) .Times(1); - std::unique_ptr<Authenticator> authenticator(new FakeAuthenticator( - FakeAuthenticator::CLIENT, 1, FakeAuthenticator::ACCEPT, true)); - std::unique_ptr<CandidateSessionConfig> config = CandidateSessionConfig::CreateDefault(); // Disable all video codecs so the host will reject connection. config->mutable_video_configs()->clear(); client_server_->set_protocol_config(std::move(config)); - client_session_ = client_server_->Connect(kHostJid, std::move(authenticator)); - client_session_->SetEventHandler(&client_session_event_handler_); - - base::RunLoop().RunUntilIdle(); + ConnectClient(FakeAuthenticator::Config(FakeAuthenticator::ACCEPT)); EXPECT_EQ(INCOMPATIBLE_PROTOCOL, client_session_->error()); EXPECT_FALSE(host_session_); @@ -487,7 +472,7 @@ // Verify that GICE-only client is rejected with an appropriate error code. TEST_F(JingleSessionTest, TestLegacyIceConnection) { - CreateSessionManagers(1, FakeAuthenticator::ACCEPT); + CreateSessionManagers(FakeAuthenticator::Config(FakeAuthenticator::ACCEPT)); EXPECT_CALL(host_server_listener_, OnIncomingSession(_, _)).Times(0); @@ -495,24 +480,21 @@ OnSessionStateChange(Session::FAILED)) .Times(1); - std::unique_ptr<Authenticator> authenticator(new FakeAuthenticator( - FakeAuthenticator::CLIENT, 1, FakeAuthenticator::ACCEPT, true)); - std::unique_ptr<CandidateSessionConfig> config = CandidateSessionConfig::CreateDefault(); config->set_ice_supported(false); client_server_->set_protocol_config(std::move(config)); - client_session_ = client_server_->Connect(kHostJid, std::move(authenticator)); - client_session_->SetEventHandler(&client_session_event_handler_); - - base::RunLoop().RunUntilIdle(); + ConnectClient(FakeAuthenticator::Config(FakeAuthenticator::ACCEPT)); EXPECT_EQ(INCOMPATIBLE_PROTOCOL, client_session_->error()); EXPECT_FALSE(host_session_); } TEST_F(JingleSessionTest, DeleteSessionOnIncomingConnection) { - CreateSessionManagers(3, FakeAuthenticator::ACCEPT); + const int kAuthRoundtrips = 3; + FakeAuthenticator::Config auth_config(kAuthRoundtrips, + FakeAuthenticator::ACCEPT, true); + CreateSessionManagers(auth_config); EXPECT_CALL(host_server_listener_, OnIncomingSession(_, _)) .WillOnce(DoAll( @@ -527,19 +509,19 @@ OnSessionStateChange(Session::AUTHENTICATING)) .WillOnce(InvokeWithoutArgs(this, &JingleSessionTest::DeleteHostSession)); - std::unique_ptr<Authenticator> authenticator(new FakeAuthenticator( - FakeAuthenticator::CLIENT, 3, FakeAuthenticator::ACCEPT, true)); - - client_session_ = client_server_->Connect(kHostJid, std::move(authenticator)); - - base::RunLoop().RunUntilIdle(); + ConnectClient(auth_config); } TEST_F(JingleSessionTest, DeleteSessionOnAuth) { // Same as the previous test, but set messages_till_started to 2 in // CreateSessionManagers so that the session will goes into the // AUTHENTICATING state after two message exchanges. - CreateSessionManagers(3, 2, FakeAuthenticator::ACCEPT); + const int kMessagesTillStarted = 2; + + const int kAuthRoundtrips = 3; + FakeAuthenticator::Config auth_config(kAuthRoundtrips, + FakeAuthenticator::ACCEPT, true); + CreateSessionManagers(auth_config, kMessagesTillStarted); EXPECT_CALL(host_server_listener_, OnIncomingSession(_, _)) .WillOnce( @@ -554,24 +536,17 @@ OnSessionStateChange(Session::AUTHENTICATING)) .WillOnce(InvokeWithoutArgs(this, &JingleSessionTest::DeleteHostSession)); - std::unique_ptr<Authenticator> authenticator(new FakeAuthenticator( - FakeAuthenticator::CLIENT, 3, FakeAuthenticator::ACCEPT, true)); - - client_session_ = client_server_->Connect(kHostJid, std::move(authenticator)); - base::RunLoop().RunUntilIdle(); -} - -// Verify that we can connect with multistep authentication. -TEST_F(JingleSessionTest, TestMultistepAuth) { - CreateSessionManagers(3, FakeAuthenticator::ACCEPT); - ASSERT_NO_FATAL_FAILURE( - InitiateConnection(3, FakeAuthenticator::ACCEPT, false)); + ConnectClient(auth_config); } // Verify that incoming transport-info messages are handled correctly while in // AUTHENTICATING state. TEST_F(JingleSessionTest, TransportInfoDuringAuthentication) { - CreateSessionManagers(2, FakeAuthenticator::ACCEPT); + const int kAuthRoundtrips = 2; + FakeAuthenticator::Config auth_config(kAuthRoundtrips, + FakeAuthenticator::ACCEPT, true); + + CreateSessionManagers(auth_config); SetHostExpectation(false); { @@ -587,7 +562,8 @@ // Create connection and pause it before authentication is finished. FakeAuthenticator* authenticator = new FakeAuthenticator( - FakeAuthenticator::CLIENT, 2, FakeAuthenticator::ACCEPT, true); + FakeAuthenticator::CLIENT, auth_config, + client_signal_strategy_->GetLocalAddress().id(), kNormalizedHostJid); authenticator->set_pause_message_index(4); ConnectClient(base::WrapUnique(authenticator)); @@ -618,17 +594,21 @@ TEST_F(JingleSessionTest, TestSessionPlugin) { host_plugin_.Clear(); client_plugin_.Clear(); - CreateSessionManagers(3, FakeAuthenticator::ACCEPT); - ASSERT_NO_FATAL_FAILURE( - InitiateConnection(3, FakeAuthenticator::ACCEPT, false)); + + const int kAuthRoundtrips = 3; + FakeAuthenticator::Config auth_config(kAuthRoundtrips, + FakeAuthenticator::ACCEPT, true); + + CreateSessionManagers(auth_config); + ASSERT_NO_FATAL_FAILURE(InitiateConnection(auth_config, false)); ExpectPluginMessagesEqual(); } TEST_F(JingleSessionTest, SessionPluginShouldNotBeInvolvedInSessionTerminate) { host_plugin_.Clear(); client_plugin_.Clear(); - CreateSessionManagers(1, FakeAuthenticator::REJECT); - InitiateConnection(1, FakeAuthenticator::ACCEPT, true); + CreateSessionManagers(FakeAuthenticator::Config(FakeAuthenticator::REJECT)); + InitiateConnection(FakeAuthenticator::Config(), true); // It's expected the client sends one more plugin message than host, the host // won't send plugin message in the SESSION_TERMINATE message. ASSERT_EQ(client_plugin_.outgoing_messages().size() - 1, @@ -637,10 +617,16 @@ } TEST_F(JingleSessionTest, ImmediatelyCloseSessionAfterConnect) { - CreateSessionManagers(3, FakeAuthenticator::ACCEPT); - client_session_ = client_server_->Connect(host_jid_, + const int kAuthRoundtrips = 3; + FakeAuthenticator::Config auth_config(kAuthRoundtrips, + FakeAuthenticator::ACCEPT, true); + CreateSessionManagers(auth_config); + client_session_ = client_server_->Connect( + SignalingAddress(kNormalizedHostJid), base::MakeUnique<FakeAuthenticator>( - FakeAuthenticator::CLIENT, 3, FakeAuthenticator::ACCEPT, true)); + FakeAuthenticator::CLIENT, auth_config, + client_signal_strategy_->GetLocalAddress().id(), kNormalizedHostJid)); + client_session_->Close(HOST_OVERLOAD); base::RunLoop().RunUntilIdle(); // We should only send a SESSION_TERMINATE message if the session has been
diff --git a/remoting/protocol/protocol_mock_objects.cc b/remoting/protocol/protocol_mock_objects.cc index 70581e4..10ffb35 100644 --- a/remoting/protocol/protocol_mock_objects.cc +++ b/remoting/protocol/protocol_mock_objects.cc
@@ -11,55 +11,43 @@ #include "base/threading/thread_task_runner_handle.h" #include "remoting/protocol/session_plugin.h" #include "remoting/protocol/video_stream.h" +#include "remoting/signaling/signaling_address.h" namespace remoting { namespace protocol { MockAuthenticator::MockAuthenticator() {} - MockAuthenticator::~MockAuthenticator() {} MockConnectionToClientEventHandler::MockConnectionToClientEventHandler() {} - MockConnectionToClientEventHandler::~MockConnectionToClientEventHandler() {} MockClipboardStub::MockClipboardStub() {} - MockClipboardStub::~MockClipboardStub() {} MockInputStub::MockInputStub() {} - MockInputStub::~MockInputStub() {} MockHostStub::MockHostStub() {} - MockHostStub::~MockHostStub() {} MockClientStub::MockClientStub() {} - MockClientStub::~MockClientStub() {} MockCursorShapeStub::MockCursorShapeStub() {} - MockCursorShapeStub::~MockCursorShapeStub() {} MockVideoStub::MockVideoStub() {} - MockVideoStub::~MockVideoStub() {} MockSession::MockSession() {} - MockSession::~MockSession() {} MockSessionManager::MockSessionManager() {} - MockSessionManager::~MockSessionManager() {} -MockPairingRegistryDelegate::MockPairingRegistryDelegate() { -} - -MockPairingRegistryDelegate::~MockPairingRegistryDelegate() { -} +MockPairingRegistryDelegate::MockPairingRegistryDelegate() {} +MockPairingRegistryDelegate::~MockPairingRegistryDelegate() {} std::unique_ptr<base::ListValue> MockPairingRegistryDelegate::LoadAll() { std::unique_ptr<base::ListValue> result(new base::ListValue());
diff --git a/remoting/protocol/protocol_mock_objects.h b/remoting/protocol/protocol_mock_objects.h index a39d619b..391eb4d 100644 --- a/remoting/protocol/protocol_mock_objects.h +++ b/remoting/protocol/protocol_mock_objects.h
@@ -30,6 +30,7 @@ #include "remoting/protocol/session_manager.h" #include "remoting/protocol/transport.h" #include "remoting/protocol/video_stub.h" +#include "remoting/signaling/signaling_address.h" #include "testing/gmock/include/gmock/gmock.h" #include "third_party/libjingle_xmpp/xmllite/xmlelement.h" @@ -206,15 +207,15 @@ void set_protocol_config( std::unique_ptr<CandidateSessionConfig> config) override {} MOCK_METHOD2(ConnectPtr, - Session*(const std::string& host_jid, + Session*(const SignalingAddress& peer_address, Authenticator* authenticator)); MOCK_METHOD0(Close, void()); MOCK_METHOD1(set_authenticator_factory_ptr, void(AuthenticatorFactory* factory)); std::unique_ptr<Session> Connect( - const std::string& host_jid, + const SignalingAddress& peer_address, std::unique_ptr<Authenticator> authenticator) override { - return base::WrapUnique(ConnectPtr(host_jid, authenticator.get())); + return base::WrapUnique(ConnectPtr(peer_address, authenticator.get())); } void set_authenticator_factory( std::unique_ptr<AuthenticatorFactory> authenticator_factory) override {
diff --git a/remoting/protocol/session_manager.h b/remoting/protocol/session_manager.h index 71c5007..b8cd08f0 100644 --- a/remoting/protocol/session_manager.h +++ b/remoting/protocol/session_manager.h
@@ -62,6 +62,7 @@ namespace remoting { +class SignalingAddress; class SignalStrategy; namespace protocol { @@ -108,12 +109,12 @@ virtual void set_protocol_config( std::unique_ptr<CandidateSessionConfig> config) = 0; - // Tries to create a session to the host |jid|. + // Creates a new outgoing session. // - // |host_jid| is the full jid of the host to connect to. - // |authenticator| is a client authenticator for the session. + // |peer_address| - full SignalingAddress to connect to. + // |authenticator| - client authenticator for the session. virtual std::unique_ptr<Session> Connect( - const std::string& host_jid, + const SignalingAddress& peer_address, std::unique_ptr<Authenticator> authenticator) = 0; // Set authenticator factory that should be used to authenticate
diff --git a/remoting/protocol/webrtc_transport_unittest.cc b/remoting/protocol/webrtc_transport_unittest.cc index a2200c03..fc0b96b 100644 --- a/remoting/protocol/webrtc_transport_unittest.cc +++ b/remoting/protocol/webrtc_transport_unittest.cc
@@ -183,16 +183,15 @@ new WebrtcTransport(jingle_glue::JingleThreadWrapper::current(), TransportContext::ForTests(TransportRole::SERVER), &host_event_handler_)); - host_authenticator_.reset(new FakeAuthenticator( - FakeAuthenticator::HOST, 0, FakeAuthenticator::ACCEPT, false)); + host_authenticator_.reset(new FakeAuthenticator(FakeAuthenticator::ACCEPT)); host_authenticator_->set_auth_key(kAuthKey); client_transport_.reset( new WebrtcTransport(jingle_glue::JingleThreadWrapper::current(), TransportContext::ForTests(TransportRole::CLIENT), &client_event_handler_)); - client_authenticator_.reset(new FakeAuthenticator( - FakeAuthenticator::CLIENT, 0, FakeAuthenticator::ACCEPT, false)); + client_authenticator_.reset( + new FakeAuthenticator(FakeAuthenticator::ACCEPT)); client_authenticator_->set_auth_key(kAuthKey); }
diff --git a/remoting/signaling/delegating_signal_strategy.cc b/remoting/signaling/delegating_signal_strategy.cc index 0f6dc7d..c4340ac 100644 --- a/remoting/signaling/delegating_signal_strategy.cc +++ b/remoting/signaling/delegating_signal_strategy.cc
@@ -14,10 +14,10 @@ namespace remoting { DelegatingSignalStrategy::DelegatingSignalStrategy( - std::string local_jid, + const SignalingAddress& local_address, scoped_refptr<base::SingleThreadTaskRunner> client_task_runner, const IqCallback& send_iq_callback) - : local_jid_(local_jid), + : local_address_(local_address), delegate_task_runner_(base::ThreadTaskRunnerHandle::Get()), client_task_runner_(client_task_runner), send_iq_callback_(send_iq_callback), @@ -83,9 +83,9 @@ return OK; } -std::string DelegatingSignalStrategy::GetLocalJid() const { +const SignalingAddress& DelegatingSignalStrategy::GetLocalAddress() const { DCHECK(client_task_runner_->BelongsToCurrentThread()); - return local_jid_; + return local_address_; } void DelegatingSignalStrategy::AddListener(Listener* listener) { @@ -101,7 +101,7 @@ bool DelegatingSignalStrategy::SendStanza( std::unique_ptr<buzz::XmlElement> stanza) { DCHECK(client_task_runner_->BelongsToCurrentThread()); - stanza->SetAttr(buzz::QN_FROM, GetLocalJid()); + GetLocalAddress().SetInMessage(stanza.get(), SignalingAddress::FROM); delegate_task_runner_->PostTask(FROM_HERE, base::Bind(send_iq_callback_, stanza->Str())); return true;
diff --git a/remoting/signaling/delegating_signal_strategy.h b/remoting/signaling/delegating_signal_strategy.h index d41de42..7b997877 100644 --- a/remoting/signaling/delegating_signal_strategy.h +++ b/remoting/signaling/delegating_signal_strategy.h
@@ -10,6 +10,7 @@ #include "base/memory/weak_ptr.h" #include "base/observer_list_threadsafe.h" #include "remoting/signaling/signal_strategy.h" +#include "remoting/signaling/signaling_address.h" namespace base { class SingleThreadTaskRunner; @@ -35,7 +36,7 @@ typedef base::RepeatingCallback<void(const std::string&)> IqCallback; DelegatingSignalStrategy( - std::string local_jid, + const SignalingAddress& local_address, scoped_refptr<base::SingleThreadTaskRunner> client_task_runner, const IqCallback& send_iq_callback); ~DelegatingSignalStrategy() override; @@ -47,7 +48,7 @@ void Disconnect() override; State GetState() const override; Error GetError() const override; - std::string GetLocalJid() const override; + const SignalingAddress& GetLocalAddress() const override; void AddListener(Listener* listener) override; void RemoveListener(Listener* listener) override; bool SendStanza(std::unique_ptr<buzz::XmlElement> stanza) override; @@ -61,7 +62,7 @@ void OnIncomingMessage(const std::string& message); - std::string local_jid_; + SignalingAddress local_address_; scoped_refptr<base::SingleThreadTaskRunner> delegate_task_runner_; scoped_refptr<base::SingleThreadTaskRunner> client_task_runner_;
diff --git a/remoting/signaling/fake_signal_strategy.cc b/remoting/signaling/fake_signal_strategy.cc index fed04e5..dc4db99 100644 --- a/remoting/signaling/fake_signal_strategy.cc +++ b/remoting/signaling/fake_signal_strategy.cc
@@ -28,9 +28,9 @@ peer2->ConnectTo(peer1); } -FakeSignalStrategy::FakeSignalStrategy(const std::string& jid) +FakeSignalStrategy::FakeSignalStrategy(const SignalingAddress& address) : main_thread_(base::ThreadTaskRunnerHandle::Get()), - jid_(jid), + address_(address), last_id_(0), weak_factory_(this) { DetachFromThread(); @@ -59,9 +59,9 @@ } } -void FakeSignalStrategy::SetLocalJid(const std::string& jid) { +void FakeSignalStrategy::SetLocalAddress(const SignalingAddress& address) { DCHECK(CalledOnValidThread()); - jid_ = jid; + address_ = address; } void FakeSignalStrategy::SimulateMessageReordering() { @@ -89,9 +89,9 @@ return OK; } -std::string FakeSignalStrategy::GetLocalJid() const { +const SignalingAddress& FakeSignalStrategy::GetLocalAddress() const { DCHECK(CalledOnValidThread()); - return jid_; + return address_; } void FakeSignalStrategy::AddListener(Listener* listener) { @@ -107,7 +107,7 @@ bool FakeSignalStrategy::SendStanza(std::unique_ptr<buzz::XmlElement> stanza) { DCHECK(CalledOnValidThread()); - stanza->SetAttr(buzz::QN_FROM, jid_); + address_.SetInMessage(stanza.get(), SignalingAddress::FROM); if (peer_callback_.is_null()) return false; @@ -164,10 +164,12 @@ buzz::XmlElement* stanza_ptr = stanza.get(); received_messages_.push_back(stanza.release()); - const std::string& to_field = stanza_ptr->Attr(buzz::QN_TO); - if (NormalizeJid(to_field) != NormalizeJid(jid_)) { - LOG(WARNING) << "Dropping stanza that is addressed to " << to_field - << ". Local jid: " << jid_ + std::string to_error; + SignalingAddress to = + SignalingAddress::Parse(stanza_ptr, SignalingAddress::TO, &to_error); + if (to != address_) { + LOG(WARNING) << "Dropping stanza that is addressed to " << to.id() + << ". Local address: " << address_.id() << ". Message content: " << stanza_ptr->Str(); return; }
diff --git a/remoting/signaling/fake_signal_strategy.h b/remoting/signaling/fake_signal_strategy.h index 0b5d912..c4da7e4 100644 --- a/remoting/signaling/fake_signal_strategy.h +++ b/remoting/signaling/fake_signal_strategy.h
@@ -15,6 +15,7 @@ #include "base/threading/non_thread_safe.h" #include "remoting/signaling/iq_sender.h" #include "remoting/signaling/signal_strategy.h" +#include "remoting/signaling/signaling_address.h" namespace base { class SingleThreadTaskRunner; @@ -29,7 +30,7 @@ // must belong to the current thread. static void Connect(FakeSignalStrategy* peer1, FakeSignalStrategy* peer2); - FakeSignalStrategy(const std::string& jid); + FakeSignalStrategy(const SignalingAddress& address); ~FakeSignalStrategy() override; const std::list<buzz::XmlElement*>& received_messages() { @@ -43,7 +44,7 @@ // Connects current FakeSignalStrategy to receive messages from |peer|. void ConnectTo(FakeSignalStrategy* peer); - void SetLocalJid(const std::string& jid); + void SetLocalAddress(const SignalingAddress& address); // Simulate IQ messages re-ordering by swapping the delivery order of // next pair of messages. @@ -54,7 +55,7 @@ void Disconnect() override; State GetState() const override; Error GetError() const override; - std::string GetLocalJid() const override; + const SignalingAddress& GetLocalAddress() const override; void AddListener(Listener* listener) override; void RemoveListener(Listener* listener) override; bool SendStanza(std::unique_ptr<buzz::XmlElement> stanza) override; @@ -76,7 +77,7 @@ scoped_refptr<base::SingleThreadTaskRunner> main_thread_; - std::string jid_; + SignalingAddress address_; PeerCallback peer_callback_; base::ObserverList<Listener, true> listeners_;
diff --git a/remoting/signaling/iq_sender_unittest.cc b/remoting/signaling/iq_sender_unittest.cc index 8ef1041..1b52305 100644 --- a/remoting/signaling/iq_sender_unittest.cc +++ b/remoting/signaling/iq_sender_unittest.cc
@@ -47,7 +47,7 @@ class IqSenderTest : public testing::Test { public: - IqSenderTest() { + IqSenderTest() : signal_strategy_(SignalingAddress("local_jid@domain.com")) { EXPECT_CALL(signal_strategy_, AddListener(NotNull())); sender_.reset(new IqSender(&signal_strategy_)); EXPECT_CALL(signal_strategy_, RemoveListener(
diff --git a/remoting/signaling/log_to_server_unittest.cc b/remoting/signaling/log_to_server_unittest.cc index 772a33e..856f69c 100644 --- a/remoting/signaling/log_to_server_unittest.cc +++ b/remoting/signaling/log_to_server_unittest.cc
@@ -8,6 +8,7 @@ #include "base/run_loop.h" #include "remoting/signaling/mock_signal_strategy.h" #include "remoting/signaling/server_log_entry_unittest.h" +#include "remoting/signaling/signaling_address.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" @@ -38,7 +39,7 @@ class LogToServerTest : public testing::Test { public: - LogToServerTest() {} + LogToServerTest() : signal_strategy_(SignalingAddress(kClientJid)) {} void SetUp() override { EXPECT_CALL(signal_strategy_, AddListener(_)); EXPECT_CALL(signal_strategy_, RemoveListener(_)); @@ -56,8 +57,6 @@ TEST_F(LogToServerTest, LogWhenConnected) { { InSequence s; - EXPECT_CALL(signal_strategy_, GetLocalJid()) - .WillRepeatedly(Return(kClientJid)); EXPECT_CALL(signal_strategy_, AddListener(_)); EXPECT_CALL(signal_strategy_, GetNextId()); EXPECT_CALL(signal_strategy_, SendStanzaPtr(IsLogEntry("a", "1"))) @@ -80,8 +79,6 @@ } TEST_F(LogToServerTest, DontLogWhenDisconnected) { - EXPECT_CALL(signal_strategy_, GetLocalJid()) - .WillRepeatedly(Return(kClientJid)); EXPECT_CALL(signal_strategy_, SendStanzaPtr(_)).Times(0); ServerLogEntry entry;
diff --git a/remoting/signaling/mock_signal_strategy.cc b/remoting/signaling/mock_signal_strategy.cc index 7133587..2dd562b3 100644 --- a/remoting/signaling/mock_signal_strategy.cc +++ b/remoting/signaling/mock_signal_strategy.cc
@@ -6,7 +6,12 @@ namespace remoting { -MockSignalStrategy::MockSignalStrategy() { } -MockSignalStrategy::~MockSignalStrategy() { } +MockSignalStrategy::MockSignalStrategy(const SignalingAddress& address) + : local_address_(address) {} +MockSignalStrategy::~MockSignalStrategy() {} + +const SignalingAddress& MockSignalStrategy::GetLocalAddress() const { + return local_address_; +} } // namespace remoting
diff --git a/remoting/signaling/mock_signal_strategy.h b/remoting/signaling/mock_signal_strategy.h index e4455f4..5fd40f8 100644 --- a/remoting/signaling/mock_signal_strategy.h +++ b/remoting/signaling/mock_signal_strategy.h
@@ -6,6 +6,7 @@ #include "remoting/signaling/iq_sender.h" #include "remoting/signaling/signal_strategy.h" +#include "remoting/signaling/signaling_address.h" #include "testing/gmock/include/gmock/gmock.h" #include "third_party/libjingle_xmpp/xmllite/xmlelement.h" @@ -13,14 +14,13 @@ class MockSignalStrategy : public SignalStrategy { public: - MockSignalStrategy(); + MockSignalStrategy(const SignalingAddress& address); ~MockSignalStrategy() override; MOCK_METHOD0(Connect, void()); MOCK_METHOD0(Disconnect, void()); MOCK_CONST_METHOD0(GetState, State()); MOCK_CONST_METHOD0(GetError, Error()); - MOCK_CONST_METHOD0(GetLocalJid, std::string()); MOCK_METHOD1(AddListener, void(Listener* listener)); MOCK_METHOD1(RemoveListener, void(Listener* listener)); MOCK_METHOD0(GetNextId, std::string()); @@ -31,6 +31,11 @@ bool SendStanza(std::unique_ptr<buzz::XmlElement> stanza) override { return SendStanzaPtr(stanza.release()); } + + const SignalingAddress& GetLocalAddress() const override; + + private: + SignalingAddress local_address_; }; } // namespace remoting
diff --git a/remoting/signaling/push_notification_subscriber.cc b/remoting/signaling/push_notification_subscriber.cc index bbeb02b..734d1de 100644 --- a/remoting/signaling/push_notification_subscriber.cc +++ b/remoting/signaling/push_notification_subscriber.cc
@@ -10,6 +10,7 @@ #include "remoting/base/logging.h" #include "remoting/signaling/iq_sender.h" #include "remoting/signaling/jid_util.h" +#include "remoting/signaling/signaling_address.h" #include "third_party/libjingle_xmpp/xmllite/xmlelement.h" namespace remoting { @@ -20,11 +21,8 @@ } // namespace -PushNotificationSubscriber::Subscription::Subscription() { -} - -PushNotificationSubscriber::Subscription::~Subscription() { -} +PushNotificationSubscriber::Subscription::Subscription() {} +PushNotificationSubscriber::Subscription::~Subscription() {} PushNotificationSubscriber::PushNotificationSubscriber( SignalStrategy* signal_strategy, @@ -58,7 +56,8 @@ << subscription.channel << "."; std::string bare_jid; - SplitJidResource(signal_strategy_->GetLocalJid(), &bare_jid, nullptr); + SplitJidResource(signal_strategy_->GetLocalAddress().jid(), &bare_jid, + nullptr); // Build a subscription request. buzz::XmlElement* subscribe_element =
diff --git a/remoting/signaling/push_notification_subscriber_unittest.cc b/remoting/signaling/push_notification_subscriber_unittest.cc index 6536f9c..a7ef2ed 100644 --- a/remoting/signaling/push_notification_subscriber_unittest.cc +++ b/remoting/signaling/push_notification_subscriber_unittest.cc
@@ -5,6 +5,7 @@ #include "remoting/signaling/push_notification_subscriber.h" #include "remoting/signaling/mock_signal_strategy.h" +#include "remoting/signaling/signaling_address.h" #include "testing/gmock/include/gmock/gmock.h" using testing::_; @@ -16,7 +17,7 @@ namespace remoting { TEST(PushNotificationSubscriberTest, Create) { - MockSignalStrategy signal_strategy; + MockSignalStrategy signal_strategy(SignalingAddress("user@domain/resource")); EXPECT_CALL(signal_strategy, AddListener(_)); EXPECT_CALL(signal_strategy, RemoveListener(_)); @@ -25,9 +26,7 @@ } TEST(PushNotificationSubscriberTest, Subscribe) { - MockSignalStrategy signal_strategy; - EXPECT_CALL(signal_strategy, GetLocalJid()) - .WillRepeatedly(Return("user@domain/resource")); + MockSignalStrategy signal_strategy(SignalingAddress("user@domain/resource")); EXPECT_CALL(signal_strategy, GetNextId()).WillOnce(Return("next_id")); EXPECT_CALL(signal_strategy, AddListener(_)).Times(AtLeast(1)); EXPECT_CALL(signal_strategy, RemoveListener(_)).Times(AtLeast(1));
diff --git a/remoting/signaling/signal_strategy.h b/remoting/signaling/signal_strategy.h index 479f8b7..1edeeba 100644 --- a/remoting/signaling/signal_strategy.h +++ b/remoting/signaling/signal_strategy.h
@@ -16,6 +16,8 @@ namespace remoting { +class SignalingAddress; + class SignalStrategy { public: enum State { @@ -75,8 +77,8 @@ // Returns the last error. Set when state changes to DISCONNECT. virtual Error GetError() const = 0; - // Returns local JID or an empty string when not connected. - virtual std::string GetLocalJid() const = 0; + // Local address. An empty value is returned when not connected. + virtual const SignalingAddress& GetLocalAddress() const = 0; // Add a |listener| that can listen to all incoming // messages. Doesn't take ownership of the |listener|. All listeners
diff --git a/remoting/signaling/xmpp_signal_strategy.cc b/remoting/signaling/xmpp_signal_strategy.cc index 32ab100..a493ab1 100644 --- a/remoting/signaling/xmpp_signal_strategy.cc +++ b/remoting/signaling/xmpp_signal_strategy.cc
@@ -30,6 +30,7 @@ #include "net/url_request/url_request_context_getter.h" #include "remoting/base/buffered_socket_writer.h" #include "remoting/base/logging.h" +#include "remoting/signaling/signaling_address.h" #include "remoting/signaling/xmpp_login_handler.h" #include "remoting/signaling/xmpp_stream_parser.h" #include "third_party/libjingle_xmpp/xmllite/xmlelement.h" @@ -67,7 +68,7 @@ void Disconnect(); State GetState() const; Error GetError() const; - std::string GetLocalJid() const; + const SignalingAddress& GetLocalAddress() const; void AddListener(Listener* listener); void RemoveListener(Listener* listener); bool SendStanza(std::unique_ptr<buzz::XmlElement> stanza); @@ -135,7 +136,7 @@ std::unique_ptr<XmppLoginHandler> login_handler_; std::unique_ptr<XmppStreamParser> stream_parser_; - std::string jid_; + SignalingAddress local_address_; Error error_ = OK; @@ -226,9 +227,9 @@ return error_; } -std::string XmppSignalStrategy::Core::GetLocalJid() const { +const SignalingAddress& XmppSignalStrategy::Core::GetLocalAddress() const { DCHECK(thread_checker_.CalledOnValidThread()); - return jid_; + return local_address_; } void XmppSignalStrategy::Core::AddListener(Listener* listener) { @@ -327,7 +328,7 @@ std::unique_ptr<XmppStreamParser> parser) { DCHECK(thread_checker_.CalledOnValidThread()); - jid_ = jid; + local_address_ = SignalingAddress(jid); stream_parser_ = std::move(parser); stream_parser_->SetCallbacks( base::Bind(&Core::OnStanza, base::Unretained(this)), @@ -532,8 +533,8 @@ return core_->GetError(); } -std::string XmppSignalStrategy::GetLocalJid() const { - return core_->GetLocalJid(); +const SignalingAddress& XmppSignalStrategy::GetLocalAddress() const { + return core_->GetLocalAddress(); } void XmppSignalStrategy::AddListener(Listener* listener) {
diff --git a/remoting/signaling/xmpp_signal_strategy.h b/remoting/signaling/xmpp_signal_strategy.h index c6252be8..fb259fda 100644 --- a/remoting/signaling/xmpp_signal_strategy.h +++ b/remoting/signaling/xmpp_signal_strategy.h
@@ -50,7 +50,7 @@ void Disconnect() override; State GetState() const override; Error GetError() const override; - std::string GetLocalJid() const override; + const SignalingAddress& GetLocalAddress() const override; void AddListener(Listener* listener) override; void RemoveListener(Listener* listener) override; bool SendStanza(std::unique_ptr<buzz::XmlElement> stanza) override;
diff --git a/remoting/test/protocol_perftest.cc b/remoting/test/protocol_perftest.cc index 2645690..202b4e3 100644 --- a/remoting/test/protocol_perftest.cc +++ b/remoting/test/protocol_perftest.cc
@@ -242,7 +242,8 @@ void StartHostAndClient(bool use_webrtc) { fake_network_dispatcher_ = new FakeNetworkDispatcher(); - client_signaling_.reset(new FakeSignalStrategy(kClientJid)); + client_signaling_.reset( + new FakeSignalStrategy(SignalingAddress(kClientJid))); jingle_glue::JingleThreadWrapper::EnsureForCurrentMessageLoop(); @@ -261,7 +262,7 @@ jingle_glue::JingleThreadWrapper::EnsureForCurrentMessageLoop(); - host_signaling_.reset(new FakeSignalStrategy(kHostJid)); + host_signaling_.reset(new FakeSignalStrategy(SignalingAddress(kHostJid))); host_signaling_->set_send_delay(GetParam().signaling_latency); host_signaling_->ConnectTo(client_signaling_.get());
diff --git a/remoting/test/test_chromoting_client_unittest.cc b/remoting/test/test_chromoting_client_unittest.cc index 29a242ad..17b35fee 100644 --- a/remoting/test/test_chromoting_client_unittest.cc +++ b/remoting/test/test_chromoting_client_unittest.cc
@@ -70,7 +70,8 @@ // remain valid until |test_chromoting_client_| is destroyed. fake_connection_to_host_ = new FakeConnectionToHost(); test_chromoting_client_->SetSignalStrategyForTests( - base::MakeUnique<FakeSignalStrategy>("test_user@faux_address.com/123")); + base::MakeUnique<FakeSignalStrategy>( + SignalingAddress("test_user@faux_address.com/123"))); test_chromoting_client_->SetConnectionToHostForTests( base::WrapUnique(fake_connection_to_host_));
diff --git a/services/BUILD.gn b/services/BUILD.gn index 7ac2551..52a819f 100644 --- a/services/BUILD.gn +++ b/services/BUILD.gn
@@ -23,8 +23,12 @@ ] if (is_android) { - # Some tests need to initialize V8. - deps += [ "//v8:v8_external_startup_data_assets" ] + deps += [ + "//services/device:java", + + # Some tests need to initialize V8. + "//v8:v8_external_startup_data_assets", + ] } else { # NOTE: We do not currently support standalone service binaries on Android, # so any tests which use the ServiceTest framework to connect to standalone @@ -38,6 +42,7 @@ catalog("service_unittests_catalog") { testonly = true catalog_deps = [ + "//services/device:tests_catalog", "//services/preferences:tests_catalog", "//services/video_capture:tests_catalog", ]
diff --git a/services/device/BUILD.gn b/services/device/BUILD.gn index fbcee0c..6a146e7a 100644 --- a/services/device/BUILD.gn +++ b/services/device/BUILD.gn
@@ -3,6 +3,7 @@ # found in the LICENSE file. import("//build/config/features.gni") +import("//services/catalog/public/tools/catalog.gni") import("//services/service_manager/public/cpp/service.gni") import("//services/service_manager/public/service_manifest.gni") @@ -13,7 +14,10 @@ source_set("lib") { # This should be visible only to embedders of the Device Service, and the # dependence should only be for the purpose of embedding the Device Service. - visibility = [ "//content/browser" ] + visibility = [ + ":test_support", + "//content/browser", + ] sources = [ "device_service.cc", "device_service.h", @@ -23,6 +27,7 @@ "//base", "//device/battery:mojo_bindings", "//device/sensors", + "//device/sensors/public/interfaces", "//device/vibration:mojo_bindings", "//device/wake_lock", "//services/device/fingerprint", @@ -53,11 +58,14 @@ sources = [ "power_monitor/power_monitor_message_broadcaster_unittest.cc", "public/cpp/power_monitor/power_monitor_broadcast_source_unittest.cc", + "vibration/vibration_manager_impl_unittest.cc", ] deps = [ + ":test_support", "//base", "//base/test:test_support", + "//device/vibration:mojo_bindings", "//mojo/public/cpp/bindings", "//services/device/power_monitor", "//services/device/public/cpp/power_monitor", @@ -70,9 +78,15 @@ } if (is_android) { - deps += [ ":device_service_jni_headers" ] + deps += [ + ":device_service_jni_headers", + "//device/vibration/android:vibration_jni_headers", + ] } else { - deps += [ "//device/battery" ] + deps += [ + "//device/battery", + "//device/vibration", + ] } } @@ -81,6 +95,36 @@ source = "manifest.json" } +service_manifest("unittest_manifest") { + name = "device_unittests" + source = "unittest_manifest.json" + packaged_services = [ ":manifest" ] +} + +catalog("tests_catalog") { + testonly = true + embedded_services = [ ":unittest_manifest" ] +} + +source_set("test_support") { + testonly = true + + sources = [ + "device_service_test_base.cc", + "device_service_test_base.h", + ] + + deps = [ + ":lib", + "//base", + "//base/test:test_support", + "//mojo/public/cpp/bindings", + "//services/device/public/interfaces:constants", + "//services/service_manager/public/cpp:service_test_support", + "//services/service_manager/public/cpp:sources", + ] +} + if (is_android) { generate_jni("device_service_jni_headers") { sources = [ @@ -95,7 +139,12 @@ # //content/public/android:* here actually wants to identify the # //content/public/android:content_java target and all of its generated # targets which also need to see this target as well. - visibility = [ "//content/public/android:*" ] + # //services:* identifies //services:service_unittests and all of its + # generated targets. + visibility = [ + "//content/public/android:*", + "//services:*", + ] java_files = [ "android/java/src/org/chromium/services/device/InterfaceRegistrar.java" ] deps = [ "//base:base_java",
diff --git a/services/device/device_service_test_base.cc b/services/device/device_service_test_base.cc new file mode 100644 index 0000000..e967c17 --- /dev/null +++ b/services/device/device_service_test_base.cc
@@ -0,0 +1,91 @@ +// 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 "services/device/device_service_test_base.h" + +#include <memory> + +#include "base/memory/ptr_util.h" +#include "base/threading/thread.h" +#include "mojo/public/cpp/bindings/binding_set.h" +#include "services/device/device_service.h" +#include "services/device/public/interfaces/constants.mojom.h" +#include "services/service_manager/public/cpp/interface_factory.h" +#include "services/service_manager/public/cpp/interface_registry.h" +#include "services/service_manager/public/cpp/service_context.h" +#include "services/service_manager/public/interfaces/service_factory.mojom.h" + +namespace device { + +namespace { + +const char kTestServiceName[] = "device_unittests"; + +// The test service responsible to package Device Service. +class ServiceTestClient : public service_manager::test::ServiceTestClient, + public service_manager::mojom::ServiceFactory, + public service_manager::InterfaceFactory< + service_manager::mojom::ServiceFactory> { + public: + explicit ServiceTestClient(service_manager::test::ServiceTest* test) + : service_manager::test::ServiceTestClient(test), + io_thread_("DeviceServiceTestIOThread"), + file_thread_("DeviceServiceTestFileThread") {} + ~ServiceTestClient() override {} + + protected: + bool OnConnect(const service_manager::ServiceInfo& remote_info, + service_manager::InterfaceRegistry* registry) override { + registry->AddInterface<service_manager::mojom::ServiceFactory>(this); + return true; + } + + void CreateService(service_manager::mojom::ServiceRequest request, + const std::string& name) override { + if (name == device::mojom::kServiceName) { + io_thread_.Start(); + file_thread_.Start(); +#if defined(OS_ANDROID) + device_service_context_.reset(new service_manager::ServiceContext( + CreateDeviceService(file_thread_.task_runner(), + io_thread_.task_runner(), + wake_lock_context_callback_), + std::move(request))); +#else + device_service_context_.reset(new service_manager::ServiceContext( + CreateDeviceService(file_thread_.task_runner(), + io_thread_.task_runner()), + std::move(request))); +#endif + } + } + + void Create(const service_manager::Identity& remote_identity, + service_manager::mojom::ServiceFactoryRequest request) override { + service_factory_bindings_.AddBinding(this, std::move(request)); + } + + private: + base::Thread io_thread_; + base::Thread file_thread_; + mojo::BindingSet<service_manager::mojom::ServiceFactory> + service_factory_bindings_; + std::unique_ptr<service_manager::ServiceContext> device_service_context_; + + WakeLockContextCallback wake_lock_context_callback_; +}; + +} // namespace + +DeviceServiceTestBase::DeviceServiceTestBase() + : ServiceTest(kTestServiceName) {} + +DeviceServiceTestBase::~DeviceServiceTestBase() {} + +std::unique_ptr<service_manager::Service> +DeviceServiceTestBase::CreateService() { + return base::MakeUnique<ServiceTestClient>(this); +} + +} // namespace device
diff --git a/services/device/device_service_test_base.h b/services/device/device_service_test_base.h new file mode 100644 index 0000000..4df7d1e --- /dev/null +++ b/services/device/device_service_test_base.h
@@ -0,0 +1,28 @@ +// 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 SERVICES_DEVICE_DEVICE_SERVICE_TEST_BASE_H_ +#define SERVICES_DEVICE_DEVICE_SERVICE_TEST_BASE_H_ + +#include "base/macros.h" +#include "services/service_manager/public/cpp/service_test.h" + +namespace device { + +// Base class responsible to setup Device Service for test. +class DeviceServiceTestBase : public service_manager::test::ServiceTest { + public: + DeviceServiceTestBase(); + ~DeviceServiceTestBase() override; + + private: + // service_manager::test::ServiceTest: + std::unique_ptr<service_manager::Service> CreateService() override; + + DISALLOW_COPY_AND_ASSIGN(DeviceServiceTestBase); +}; + +} // namespace device + +#endif // SERVICES_DEVICE_DEVICE_SERVICE_TEST_BASE_H_
diff --git a/services/device/screen_orientation/OWNERS b/services/device/screen_orientation/OWNERS index 88b3579..33ac3a28 100644 --- a/services/device/screen_orientation/OWNERS +++ b/services/device/screen_orientation/OWNERS
@@ -1,2 +1,2 @@ -blundell@chromium.org -mlamouri@chromium.org +file://device/screen_orientation/OWNERS +
diff --git a/services/device/unittest_manifest.json b/services/device/unittest_manifest.json new file mode 100644 index 0000000..c743b7b9 --- /dev/null +++ b/services/device/unittest_manifest.json
@@ -0,0 +1,16 @@ +{ + "name": "device_unittests", + "display_name": "Device Service Unittests", + "interface_provider_specs": { + "service_manager:connector": { + "provides": { + "service_manager:service_factory": [ + "service_manager::mojom::ServiceFactory" + ] + }, + "requires": { + "device": [ "device:vibration" ] + } + } + } +}
diff --git a/services/device/vibration/vibration_manager_impl_unittest.cc b/services/device/vibration/vibration_manager_impl_unittest.cc new file mode 100644 index 0000000..d54a771c --- /dev/null +++ b/services/device/vibration/vibration_manager_impl_unittest.cc
@@ -0,0 +1,81 @@ +// Copyright (c) 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 "base/run_loop.h" +#include "device/vibration/vibration_manager.mojom.h" +#include "services/device/device_service_test_base.h" +#include "services/device/public/interfaces/constants.mojom.h" + +#if defined(OS_ANDROID) +#include "base/android/jni_android.h" +#include "jni/VibrationManagerImpl_jni.h" +#else +#include "device/vibration/vibration_manager_impl.h" +#endif + +namespace device { + +namespace { + +class VibrationManagerImplTest : public DeviceServiceTestBase { + public: + VibrationManagerImplTest() = default; + ~VibrationManagerImplTest() override = default; + + protected: + void SetUp() override { + DeviceServiceTestBase::SetUp(); + + connector()->BindInterface(mojom::kServiceName, &vibration_manager_); + } + + void Vibrate(int64_t milliseconds) { + base::RunLoop run_loop; + vibration_manager_->Vibrate(milliseconds, run_loop.QuitClosure()); + run_loop.Run(); + } + + void Cancel() { + base::RunLoop run_loop; + vibration_manager_->Cancel(run_loop.QuitClosure()); + run_loop.Run(); + } + + int64_t GetVibrationMilliSeconds() { +#if defined(OS_ANDROID) + return Java_VibrationManagerImpl_getVibrateMilliSecondsForTesting( + base::android::AttachCurrentThread()); +#else + return VibrationManagerImpl::milli_seconds_for_testing_; +#endif + } + + bool GetVibrationCancelled() { +#if defined(OS_ANDROID) + return Java_VibrationManagerImpl_getVibrateCancelledForTesting( + base::android::AttachCurrentThread()); +#else + return VibrationManagerImpl::cancelled_for_testing_; +#endif + } + + private: + mojom::VibrationManagerPtr vibration_manager_; + + DISALLOW_COPY_AND_ASSIGN(VibrationManagerImplTest); +}; + +TEST_F(VibrationManagerImplTest, VibrateThenCancel) { + EXPECT_NE(10000, GetVibrationMilliSeconds()); + Vibrate(10000); + EXPECT_EQ(10000, GetVibrationMilliSeconds()); + + EXPECT_FALSE(GetVibrationCancelled()); + Cancel(); + EXPECT_TRUE(GetVibrationCancelled()); +} + +} // namespace + +} // namespace device
diff --git a/services/service_manager/public/cpp/test/BUILD.gn b/services/service_manager/public/cpp/test/BUILD.gn index c1adadf..c1697a3 100644 --- a/services/service_manager/public/cpp/test/BUILD.gn +++ b/services/service_manager/public/cpp/test/BUILD.gn
@@ -21,4 +21,8 @@ "//services/catalog:lib", "//services/service_manager/background:lib", ] + + if (is_android) { + deps += [ "//mojo/android:libsystem_java" ] + } }
diff --git a/services/service_manager/public/cpp/test/run_all_service_tests.cc b/services/service_manager/public/cpp/test/run_all_service_tests.cc index 449d8ebc..badfcb3 100644 --- a/services/service_manager/public/cpp/test/run_all_service_tests.cc +++ b/services/service_manager/public/cpp/test/run_all_service_tests.cc
@@ -12,6 +12,11 @@ #include "services/catalog/catalog.h" #include "services/service_manager/public/cpp/test/service_test_catalog.h" +#if defined(OS_ANDROID) +#include "base/android/jni_android.h" +#include "mojo/android/system/mojo_jni_registrar.h" +#endif + int main(int argc, char** argv) { base::TestSuite test_suite(argc, argv); @@ -20,6 +25,10 @@ mojo::edk::Init(); +#if defined(OS_ANDROID) + mojo::android::RegisterSystemJni(base::android::AttachCurrentThread()); +#endif + base::Thread ipc_thread("IPC thread"); ipc_thread.StartWithOptions( base::Thread::Options(base::MessageLoop::TYPE_IO, 0));
diff --git a/services/ui/gpu/gpu_service.cc b/services/ui/gpu/gpu_service.cc index 2bd0603c..03c8823 100644 --- a/services/ui/gpu/gpu_service.cc +++ b/services/ui/gpu/gpu_service.cc
@@ -76,9 +76,10 @@ runner, callback); } -void DestroyBinding( - std::unique_ptr<mojo::BindingSet<mojom::GpuService>> binding) { +void DestroyBinding(mojo::BindingSet<mojom::GpuService>* binding, + base::WaitableEvent* wait) { binding->CloseAllBindings(); + wait->Signal(); } } // namespace @@ -97,6 +98,7 @@ sync_point_manager_(nullptr), bindings_(base::MakeUnique<mojo::BindingSet<mojom::GpuService>>()), weak_ptr_factory_(this) { + DCHECK(!io_runner_->BelongsToCurrentThread()); weak_ptr_ = weak_ptr_factory_.GetWeakPtr(); } @@ -106,6 +108,12 @@ logging::SetLogMessageHandler(nullptr); g_log_callback.Get() = base::Callback<void(int, size_t, const std::string&)>(); + base::WaitableEvent wait(base::WaitableEvent::ResetPolicy::MANUAL, + base::WaitableEvent::InitialState::NOT_SIGNALED); + if (io_runner_->PostTask( + FROM_HERE, base::Bind(&DestroyBinding, bindings_.get(), &wait))) { + wait.Wait(); + } media_gpu_channel_manager_.reset(); gpu_channel_manager_.reset(); owned_sync_point_manager_.reset(); @@ -116,8 +124,6 @@ // process begins waiting for them to exit. if (owned_shutdown_event_) owned_shutdown_event_->Signal(); - io_runner_->PostTask(FROM_HERE, - base::Bind(&DestroyBinding, base::Passed(&bindings_))); } void GpuService::UpdateGPUInfoFromPreferences(
diff --git a/services/ui/gpu/gpu_service_unittest.cc b/services/ui/gpu/gpu_service_unittest.cc index 0a72c5e..f79e1ac 100644 --- a/services/ui/gpu/gpu_service_unittest.cc +++ b/services/ui/gpu/gpu_service_unittest.cc
@@ -78,8 +78,8 @@ // the binding happens on the IO thread. BlockIOThread(); gpu_service()->Bind(std::move(request)); - DestroyService(); UnblockIOThread(); + DestroyService(); } // Tests ghat GpuService can be destroyed after Bind() succeeds on the IO
diff --git a/services/ui/public/cpp/client_compositor_frame_sink.cc b/services/ui/public/cpp/client_compositor_frame_sink.cc index 26c60516..8a132ae2 100644 --- a/services/ui/public/cpp/client_compositor_frame_sink.cc +++ b/services/ui/public/cpp/client_compositor_frame_sink.cc
@@ -112,11 +112,13 @@ cc::switches::kEnableSurfaceSynchronization); } -void ClientCompositorFrameSink::DidReceiveCompositorFrameAck() { +void ClientCompositorFrameSink::DidReceiveCompositorFrameAck( + const cc::ReturnedResourceArray& resources) { DCHECK(thread_checker_); DCHECK(thread_checker_->CalledOnValidThread()); if (!client_) return; + client_->ReclaimResources(resources); client_->DidReceiveCompositorFrameAck(); }
diff --git a/services/ui/public/cpp/client_compositor_frame_sink.h b/services/ui/public/cpp/client_compositor_frame_sink.h index 671efddf..af5f13a 100644 --- a/services/ui/public/cpp/client_compositor_frame_sink.h +++ b/services/ui/public/cpp/client_compositor_frame_sink.h
@@ -48,7 +48,8 @@ cc::mojom::MojoCompositorFrameSinkClientRequest client_request); // cc::mojom::MojoCompositorFrameSinkClient implementation: - void DidReceiveCompositorFrameAck() override; + void DidReceiveCompositorFrameAck( + const cc::ReturnedResourceArray& resources) override; void OnBeginFrame(const cc::BeginFrameArgs& begin_frame_args) override; void ReclaimResources(const cc::ReturnedResourceArray& resources) override;
diff --git a/services/ui/ws/display_client_compositor_frame_sink.cc b/services/ui/ws/display_client_compositor_frame_sink.cc index 7083b48..65c0fc9 100644 --- a/services/ui/ws/display_client_compositor_frame_sink.cc +++ b/services/ui/ws/display_client_compositor_frame_sink.cc
@@ -67,10 +67,12 @@ last_submitted_frame_size_ = frame_size; } -void DisplayClientCompositorFrameSink::DidReceiveCompositorFrameAck() { +void DisplayClientCompositorFrameSink::DidReceiveCompositorFrameAck( + const cc::ReturnedResourceArray& resources) { DCHECK(thread_checker_->CalledOnValidThread()); if (!client_) return; + client_->ReclaimResources(resources); client_->DidReceiveCompositorFrameAck(); }
diff --git a/services/ui/ws/display_client_compositor_frame_sink.h b/services/ui/ws/display_client_compositor_frame_sink.h index 233ea7d8..4a98ad13 100644 --- a/services/ui/ws/display_client_compositor_frame_sink.h +++ b/services/ui/ws/display_client_compositor_frame_sink.h
@@ -44,7 +44,8 @@ private: // cc::mojom::MojoCompositorFrameSinkClient implementation: - void DidReceiveCompositorFrameAck() override; + void DidReceiveCompositorFrameAck( + const cc::ReturnedResourceArray& resources) override; void OnBeginFrame(const cc::BeginFrameArgs& begin_frame_args) override; void ReclaimResources(const cc::ReturnedResourceArray& resources) override;
diff --git a/services/ui/ws/gpu_host_unittest.cc b/services/ui/ws/gpu_host_unittest.cc index e1cded7..e3c1c68 100644 --- a/services/ui/ws/gpu_host_unittest.cc +++ b/services/ui/ws/gpu_host_unittest.cc
@@ -44,24 +44,29 @@ // GpuClient class TestGpuService : public GpuService { public: - TestGpuService(); + explicit TestGpuService( + scoped_refptr<base::SingleThreadTaskRunner> io_runner); ~TestGpuService() override {} private: DISALLOW_COPY_AND_ASSIGN(TestGpuService); }; -TestGpuService::TestGpuService() +TestGpuService::TestGpuService( + scoped_refptr<base::SingleThreadTaskRunner> io_runner) : GpuService(gpu::GPUInfo(), nullptr /* watchdog_thread */, - base::ThreadTaskRunnerHandle::Get(), + std::move(io_runner), gpu::GpuFeatureInfo()) {} } // namespace class GpuHostTest : public testing::Test { public: - GpuHostTest() {} + GpuHostTest() : io_thread_("IOThread") { + CHECK(io_thread_.Start()); + gpu_service_ = base::MakeUnique<TestGpuService>(io_thread_.task_runner()); + } ~GpuHostTest() override {} GpuHost* gpu_host() { return gpu_host_.get(); } @@ -77,8 +82,9 @@ base::WeakPtr<GpuClient> client_ref_; + base::Thread io_thread_; TestGpuHostDelegate gpu_host_delegate_; - TestGpuService gpu_service_; + std::unique_ptr<TestGpuService> gpu_service_; ui::mojom::GpuServicePtr gpu_service_ptr_; std::unique_ptr<GpuHost> gpu_host_; @@ -100,7 +106,7 @@ gpu_host_ = base::MakeUnique<GpuHost>(&gpu_host_delegate_); ui::mojom::GpuServiceRequest request(&gpu_service_ptr_); - gpu_service_.Bind(std::move(request)); + gpu_service_->Bind(std::move(request)); gpu_host_->gpu_service_ = std::move(gpu_service_ptr_); }
diff --git a/skia/config/SkUserConfig.h b/skia/config/SkUserConfig.h index 820fe5b9..66fc0eb 100644 --- a/skia/config/SkUserConfig.h +++ b/skia/config/SkUserConfig.h
@@ -216,6 +216,10 @@ # define SK_USE_LEGACY_DISTANCE_FIELDS #endif +#ifndef SK_SUPPORT_LEGACY_NO_ADDR_PIXELREF +#define SK_SUPPORT_LEGACY_NO_ADDR_PIXELREF +#endif + #ifndef SK_DISABLE_DEFERRED_PROXIES #define SK_DISABLE_DEFERRED_PROXIES #endif
diff --git a/testing/buildbot/chromium.android.json b/testing/buildbot/chromium.android.json index 523e759c..0e013c71 100644 --- a/testing/buildbot/chromium.android.json +++ b/testing/buildbot/chromium.android.json
@@ -1577,7 +1577,7 @@ } ], "expiration": 10800, - "hard_timeout": 960, + "hard_timeout": 1200, "output_links": [ { "link": [ @@ -2640,9 +2640,6 @@ "test": "blink_heap_unittests" }, { - "override_compile_targets": [ - "breakpad_unittests_deps" - ], "override_isolate_target": "breakpad_unittests", "swarming": { "can_use_on_swarming_builders": true, @@ -3528,9 +3525,6 @@ "test": "net_unittests" }, { - "override_compile_targets": [ - "sandbox_linux_unittests_deps" - ], "override_isolate_target": "sandbox_linux_unittests", "swarming": { "can_use_on_swarming_builders": true,
diff --git a/testing/buildbot/filters/BUILD.gn b/testing/buildbot/filters/BUILD.gn index 7c54b68..bb2115ca 100644 --- a/testing/buildbot/filters/BUILD.gn +++ b/testing/buildbot/filters/BUILD.gn
@@ -44,3 +44,11 @@ "//testing/buildbot/filters/site-per-process.interactive_ui_tests.filter", ] } + +source_set("ash_unittests_filters") { + testonly = true + + data = [ + "//testing/buildbot/filters/ash_mus_unittests.filter", + ] +}
diff --git a/testing/buildbot/filters/ash_mus_unittests.filter b/testing/buildbot/filters/ash_mus_unittests.filter index 5ee0bfc..f19a780 100644 --- a/testing/buildbot/filters/ash_mus_unittests.filter +++ b/testing/buildbot/filters/ash_mus_unittests.filter
@@ -248,8 +248,10 @@ -ScreenPositionControllerTest.ConvertHostPointToScreenRotate -ScreenPositionControllerTest.ConvertHostPointToScreenUIScale -ScreenPositionControllerTest.ConvertToScreenWhileRemovingSecondaryDisplay +-ScreenRotationAnimatorTest.RemoveSecondaryDisplayAfterCopyCallback -ScreenRotationAnimatorTest.RotatesDuringRotation -ScreenRotationAnimatorTest.RotatesToDifferentRotation +-ScreenRotationAnimatorTest.RotatesToDifferentRotationWithCopyCallback -ScreenRotationAnimatorTest.ShouldCompleteAnimations -ScreenRotationAnimatorTest.ShouldNotifyObserver -ScreenRotationAnimatorTest.ShouldNotifyObserverOnce
diff --git a/testing/variations/fieldtrial_testing_config.json b/testing/variations/fieldtrial_testing_config.json index 047ef88..b31a18c8 100644 --- a/testing/variations/fieldtrial_testing_config.json +++ b/testing/variations/fieldtrial_testing_config.json
@@ -424,6 +424,21 @@ ] } ], + "CopylessPaste": [ + { + "platforms": [ + "android" + ], + "experiments": [ + { + "name": "Enabled", + "enable_features": [ + "CopylessPaste" + ] + } + ] + } + ], "DataCompressionProxyDevRollout": [ { "platforms": [ @@ -2554,7 +2569,7 @@ ], "experiments": [ { - "name": "EnableNewShow3Each1Day", + "name": "EnableExperiment", "enable_features": [ "ConsistentOmniboxGeolocation" ]
diff --git a/third_party/.gitignore b/third_party/.gitignore index 176819f..c79ea463 100644 --- a/third_party/.gitignore +++ b/third_party/.gitignore
@@ -49,7 +49,7 @@ /drmemory/unpacked /elfutils/src /errorprone/lib -/espresso/lib/*.jar +/espresso/lib/*-2.2.1-*.jar /eyesfree/src /ffmpeg /findbugs
diff --git a/third_party/WebKit/LayoutTests/FlagExpectations/enable-slimming-paint-v2 b/third_party/WebKit/LayoutTests/FlagExpectations/enable-slimming-paint-v2 index 32274ee..dd900c90 100644 --- a/third_party/WebKit/LayoutTests/FlagExpectations/enable-slimming-paint-v2 +++ b/third_party/WebKit/LayoutTests/FlagExpectations/enable-slimming-paint-v2
@@ -602,6 +602,7 @@ Bug(none) fast/events/touch/touch-rect-crash-on-unpromote-layer.html [ Failure ] Bug(none) fast/events/wheel/wheelevent-in-horizontal-scrollbar-in-rtl.html [ Failure ] Bug(none) fast/events/wheel/wheelevent-in-vertical-scrollbar-in-rtl.html [ Failure ] +Bug(none) fast/forms/select-popup/popup-menu-position.html [ Failure ] Bug(none) fast/forms/button-default-title.html [ Failure ] Bug(none) fast/forms/fieldset/fieldset-align.html [ Failure ] Bug(none) fast/forms/huge-mac-input-clamped-height.html [ Failure ] @@ -1459,7 +1460,7 @@ crbug.com/702805 fast/loader/scroll-restore-target-pseudo.html [ Crash ] crbug.com/702805 fast/loader/scroll-restore-overrides-fragment.html [ Crash ] crbug.com/702805 fast/frames/invalid-frameset.html [ Crash ] -crbug.com/702805 fast/forms/select-popup/popup-menu-appearance-coarse.html [ Crash ] +crbug.com/702805 fast/forms/select-popup/popup-menu-appearance-coarse.html [ Crash Timeout ] crbug.com/702805 css3/blending/svg-blend-layer-mask.html [ Crash ] crbug.com/702805 fast/borders/border-radius-mask-video-crash.html [ Crash ] crbug.com/702805 fast/css/getComputedStyle/invalid-url-double-recalc-serialization.html [ Crash ]
diff --git a/third_party/WebKit/LayoutTests/FlagExpectations/site-per-process b/third_party/WebKit/LayoutTests/FlagExpectations/site-per-process index 6e2633a..4030c7c 100644 --- a/third_party/WebKit/LayoutTests/FlagExpectations/site-per-process +++ b/third_party/WebKit/LayoutTests/FlagExpectations/site-per-process
@@ -7,10 +7,6 @@ # https://crbug.com/697111: assert failures in test added in r451938. crbug.com/697111 svg/dom/getScreenCTM-ancestor-transform.html [ Failure ] -# https://crbug.com/670105: uninvestigated test timeout caused by r435352. -crbug.com/670105 http/tests/security/opened-document-security-origin-resets-on-navigation.html [ Timeout ] -crbug.com/670105 virtual/mojo-loading/http/tests/security/opened-document-security-origin-resets-on-navigation.html [ Timeout ] - # https://crbug.com/669083: console messages mismatch (origin-only VS full-URI) crbug.com/669083 http/tests/security/frameNavigation/xss-DENIED-top-navigation-without-user-gesture.html [ Failure ] crbug.com/669083 virtual/mojo-loading/http/tests/security/frameNavigation/xss-DENIED-top-navigation-without-user-gesture.html [ Failure ] @@ -89,7 +85,6 @@ # https://crbug.com/611232 - CSP checks from remote parent frame do not properly report violations crbug.com/611232 http/tests/security/contentSecurityPolicy/frame-src-child-frame-navigates-to-blocked-origin.html [ Timeout ] crbug.com/611232 virtual/mojo-loading/http/tests/security/contentSecurityPolicy/frame-src-child-frame-navigates-to-blocked-origin.html [ Timeout ] -crbug.com/611232 http/tests/security/contentSecurityPolicy/1.1/plugintypes-affects-cross-site-child-disallowed.html [ Failure ] # https://crbug.com/616626 - allow_universal_access_from_file_urls doesn't work with --site-per-process. # https://crbug.com/665058 - EventSender drag-and-drop simulation doesn't support OOPIFs. @@ -163,10 +158,6 @@ crbug.com/24182 http/tests/perf/large-inlined-script.html [ Timeout Pass ] crbug.com/24182 virtual/mojo-loading/http/tests/perf/large-inlined-script.html [ Timeout Pass ] -# https://crbug.com/680201: referrer-policy-attribute-import-no-referrer.html fails w/ --site-per-process -crbug.com/680201 http/tests/security/referrer-policy-attribute-import-no-referrer.html [ Failure ] -crbug.com/680201 virtual/mojo-loading/http/tests/security/referrer-policy-attribute-import-no-referrer.html [ Failure ] - # https://crbug.com/680307: blob-url-in-iframe.html is missing PASS w/ --site-per-process crbug.com/680307 http/tests/security/mixedContent/blob-url-in-iframe.html [ Failure ] crbug.com/680307 virtual/mojo-loading/http/tests/security/mixedContent/blob-url-in-iframe.html [ Failure ]
diff --git a/third_party/WebKit/LayoutTests/NeverFixTests b/third_party/WebKit/LayoutTests/NeverFixTests index eaa095a..58e3340 100644 --- a/third_party/WebKit/LayoutTests/NeverFixTests +++ b/third_party/WebKit/LayoutTests/NeverFixTests
@@ -39,6 +39,7 @@ # This test only applies to overlay scrollbar platforms. [ Win Linux ] fast/dom/partial-layout-overlay-scrollbars.html [ WontFix ] +[ Win Linux ] virtual/sharedarraybuffer/fast/dom/partial-layout-overlay-scrollbars.html [ WontFix ] # Mac's popup behavior is different. [ Mac ] fast/forms/select/menulist-onchange-fired-with-key-up-down.html [ WontFix ] @@ -101,6 +102,12 @@ [ Android ] virtual/mojo-loading/http/tests/media/media-source/mediasource-config-change-mp4-v-bitrate.html [ WontFix ] [ Android ] virtual/mojo-loading/http/tests/media/media-source/mediasource-config-change-mp4-v-framerate.html [ WontFix ] [ Android ] virtual/mojo-loading/http/tests/media/media-source/mediasource-config-change-mp4-v-framesize.html [ WontFix ] +[ Android ] virtual/sharedarraybuffer/http/tests/media/media-source/mediasource-config-change-mp4-av-audio-bitrate.html [ WontFix ] +[ Android ] virtual/sharedarraybuffer/http/tests/media/media-source/mediasource-config-change-mp4-av-framesize.html [ WontFix ] +[ Android ] virtual/sharedarraybuffer/http/tests/media/media-source/mediasource-config-change-mp4-av-video-bitrate.html [ WontFix ] +[ Android ] virtual/sharedarraybuffer/http/tests/media/media-source/mediasource-config-change-mp4-v-bitrate.html [ WontFix ] +[ Android ] virtual/sharedarraybuffer/http/tests/media/media-source/mediasource-config-change-mp4-v-framerate.html [ WontFix ] +[ Android ] virtual/sharedarraybuffer/http/tests/media/media-source/mediasource-config-change-mp4-v-framesize.html [ WontFix ] # Only run fake-Android tests on Linux [ Mac Win ] virtual/android [ WontFix ] @@ -215,6 +222,8 @@ # these tests can still be run manually with --skiped=ignore. webaudio/codec-tests/mp3 [ WontFix ] webaudio/codec-tests/aac [ WontFix ] +virtual/sharedarraybuffer/webaudio/codec-tests/mp3 [ WontFix ] +virtual/sharedarraybuffer/webaudio/codec-tests/aac [ WontFix ] # WPT subdirectories without owners. external/wpt/accelerometer [ WontFix ]
diff --git a/third_party/WebKit/LayoutTests/SlowTests b/third_party/WebKit/LayoutTests/SlowTests index 4abba26..32b60bb 100644 --- a/third_party/WebKit/LayoutTests/SlowTests +++ b/third_party/WebKit/LayoutTests/SlowTests
@@ -24,6 +24,7 @@ crbug.com/24182 editing/selection/modify_move/move-by-word-visually-multi-space.html [ Slow ] crbug.com/24182 editing/selection/modify_move/move-by-word-visually-crash-test-5.html [ Slow ] crbug.com/24182 fast/dom/SelectorAPI/resig-SelectorsAPI-test.xhtml [ Slow ] +crbug.com/24182 virtual/sharedarraybuffer/fast/dom/SelectorAPI/resig-SelectorsAPI-test.xhtml [ Slow ] crbug.com/24182 fast/frames/cached-frame-counter.html [ Slow ] crbug.com/24182 fast/frames/frame-limit.html [ Slow ] crbug.com/24182 fast/overflow/lots-of-sibling-inline-boxes.html [ Slow ] # Particularly slow in Debug: >12x slower! @@ -35,6 +36,7 @@ crbug.com/24182 virtual/mojo-loading/http/tests/cache/subresource-expiration-2.html [ Slow ] crbug.com/24182 [ Release Win7 ] http/tests/media/media-source/mediasource-addsourcebuffer.html [ Slow ] crbug.com/24182 [ Release Win7 ] virtual/mojo-loading/http/tests/media/media-source/mediasource-addsourcebuffer.html [ Slow ] +crbug.com/24182 [ Release Win7 ] virtual/sharedarraybuffer/http/tests/media/media-source/mediasource-addsourcebuffer.html [ Slow ] crbug.com/24182 http/tests/misc/acid3.html [ Slow ] crbug.com/24182 virtual/mojo-loading/http/tests/misc/acid3.html [ Slow ] crbug.com/24182 http/tests/misc/object-embedding-svg-delayed-size-negotiation-2.htm [ Slow ] @@ -81,10 +83,13 @@ crbug.com/24182 virtual/gpu/fast/canvas/canvas-strokeRect-gradient-shadow.html [ Slow ] crbug.com/24182 virtual/gpu/fast/canvas/canvas-toDataURL-jpeg-crash.html [ Slow ] crbug.com/24182 fast/dom/timer-throttling-background-page-near-alignment-interval.html [ Slow ] +crbug.com/24182 virtual/sharedarraybuffer/fast/dom/timer-throttling-background-page-near-alignment-interval.html [ Slow ] crbug.com/24182 http/tests/perf/large-inlined-script.html [ Slow ] crbug.com/24182 virtual/mojo-loading/http/tests/perf/large-inlined-script.html [ Slow ] crbug.com/24182 fast/css/should-not-insert-stylesheet-into-detached-document.html [ Slow ] +crbug.com/24182 virtual/sharedarraybuffer/fast/css/should-not-insert-stylesheet-into-detached-document.html [ Slow ] crbug.com/24182 fast/dom/shadow/svg-style-in-shadow-tree-crash.html [ Slow ] +crbug.com/24182 virtual/sharedarraybuffer/fast/dom/shadow/svg-style-in-shadow-tree-crash.html [ Slow ] crbug.com/24182 fast/encoding/char-encoding.html [ Slow ] crbug.com/24182 fast/frames/sandboxed-iframe-navigation-targetlink.html [ Slow ] crbug.com/24182 html/marquee/marquee-destroyed-without-removed-from-crash.html [ Slow ] @@ -95,6 +100,7 @@ crbug.com/24182 svg/hixie/perf/005.xml [ Slow ] crbug.com/24182 svg/hixie/perf/006.xml [ Slow ] crbug.com/451577 [ Debug ] fast/dom/gc-treescope.html [ Slow ] +crbug.com/451577 [ Debug ] virtual/sharedarraybuffer/fast/dom/gc-treescope.html [ Slow ] crbug.com/451577 [ Debug ] fast/frames/calculate-round.html [ Slow ] crbug.com/451577 external/wpt/IndexedDB/idbindex-multientry-big.htm [ Slow ] crbug.com/451577 [ Mac ] inspector/extensions/extensions-reload.html [ Slow ] @@ -220,6 +226,7 @@ crbug.com/24182 http/tests/xmlhttprequest/simple-cross-origin-progress-events.html [ Slow ] crbug.com/24182 virtual/mojo-loading/http/tests/xmlhttprequest/simple-cross-origin-progress-events.html [ Slow ] crbug.com/237270 [ Win7 ] fast/css/custom-font-xheight.html [ Slow ] +crbug.com/237270 [ Win7 ] virtual/sharedarraybuffer/fast/css/custom-font-xheight.html [ Slow ] crbug.com/241576 [ Win ] http/tests/appcache/404-manifest.html [ Slow ] crbug.com/241576 [ Win ] virtual/mojo-loading/http/tests/appcache/404-manifest.html [ Slow ] crbug.com/241869 [ Debug ] css3/flexbox/multiline-justify-content.html [ Slow ] @@ -229,6 +236,7 @@ # This test takes 5+ seconds as intended because it tests connection throttling. crbug.com/459377 http/tests/websocket/multiple-connections-throttled.html [ Slow ] crbug.com/459377 virtual/mojo-loading/http/tests/websocket/multiple-connections-throttled.html [ Slow ] +crbug.com/459377 virtual/sharedarraybuffer/http/tests/websocket/multiple-connections-throttled.html [ Slow ] # These tests are slow to measure bounding box of every single Unicode character. #crbug.com/492664 external/csswg-test/css-writing-modes-3/text-orientation-script-001a.html [ Slow ] @@ -250,6 +258,7 @@ crbug.com/336481 inspector/jump-to-previous-editing-location.html [ Slow ] crbug.com/346259 http/tests/websocket/no-crash-on-cookie-flood.html [ Slow ] crbug.com/346259 virtual/mojo-loading/http/tests/websocket/no-crash-on-cookie-flood.html [ Slow ] +crbug.com/346259 virtual/sharedarraybuffer/http/tests/websocket/no-crash-on-cookie-flood.html [ Slow ] crbug.com/522646 http/tests/media/encrypted-media/encrypted-media-encrypted-event-different-origin.html [ Slow ] crbug.com/522646 virtual/mojo-loading/http/tests/media/encrypted-media/encrypted-media-encrypted-event-different-origin.html [ Slow ] @@ -277,6 +286,7 @@ crbug.com/548765 virtual/mojo-loading/http/tests/inspector/console-fetch-logging.html [ Slow ] crbug.com/419993 [ Debug ] fast/css/giant-stylesheet-crash.html [ Slow ] +crbug.com/419993 [ Debug ] virtual/sharedarraybuffer/fast/css/giant-stylesheet-crash.html [ Slow ] crbug.com/331186 [ Debug ] css3/flexbox/position-absolute-child.html [ Slow ] crbug.com/362509 [ Debug ] fast/parser/xml-error-adopted.xml [ Slow ] @@ -285,6 +295,7 @@ crbug.com/364225 virtual/gpu/fast/canvas/canvas-composite-text-alpha.html [ Slow ] crbug.com/372424 fast/dom/DOMImplementation/createDocument-with-used-doctype.html [ Slow ] +crbug.com/372424 virtual/sharedarraybuffer/fast/dom/DOMImplementation/createDocument-with-used-doctype.html [ Slow ] crbug.com/372424 http/tests/serviceworker/chromium/registration-stress.html [ Slow ] crbug.com/372424 virtual/mojo-loading/http/tests/serviceworker/chromium/registration-stress.html [ Slow ] @@ -295,6 +306,7 @@ # Most crypto/subtle tests are slow some or most of the time. crbug.com/459009 crypto/subtle/ [ Slow ] +crbug.com/459009 virtual/sharedarraybuffer/crypto/subtle/ [ Slow ] crbug.com/24182 [ Debug ] animations/interpolation/transform-interpolation.html [ Slow ] crbug.com/24182 [ Debug ] animations/interpolation/webkit-transform-interpolation.html [ Slow ] @@ -312,6 +324,7 @@ crbug.com/658211 [ Win7 Debug ] fast/text/line-break-ascii.html [ Slow ] crbug.com/445194 fast/dom/shadow/focus-controller-recursion-crash.html [ Slow ] +crbug.com/445194 virtual/sharedarraybuffer/fast/dom/shadow/focus-controller-recursion-crash.html [ Slow ] crbug.com/697735 external/wpt/editing/run/backcolor.html [ Slow ] crbug.com/697735 external/wpt/editing/run/bold.html [ Slow ] crbug.com/697735 external/wpt/editing/run/createlink.html [ Slow ] @@ -359,6 +372,7 @@ crbug.com/623798 virtual/disable-spinvalidation/paint/images/animated-gif-last-frame-crash.html [ Slow ] crbug.com/606649 fast/dom/gc-dom-tree-lifetime.html [ Slow ] +crbug.com/606649 virtual/sharedarraybuffer/fast/dom/gc-dom-tree-lifetime.html [ Slow ] # Slow on Win Debug in part due to incremental linking. crbug.com/647192 [ Win Debug ] fast/css3-text/css3-word-break/word-break-all-ascii.html [ Slow ]
diff --git a/third_party/WebKit/LayoutTests/TestExpectations b/third_party/WebKit/LayoutTests/TestExpectations index 76e9613..dc24637a 100644 --- a/third_party/WebKit/LayoutTests/TestExpectations +++ b/third_party/WebKit/LayoutTests/TestExpectations
@@ -737,6 +737,7 @@ crbug.com/520739 [ Mac ] http/tests/websocket/close-code-and-reason.html [ Failure Pass Timeout ] crbug.com/520739 [ Mac ] virtual/mojo-loading/http/tests/websocket/close-code-and-reason.html [ Failure Pass Timeout ] +crbug.com/520739 [ Mac ] virtual/sharedarraybuffer/http/tests/websocket/close-code-and-reason.html [ Failure Pass Timeout ] #crbug.com/520737 [ Mac ] external/wpt/css/css-writing-modes-3/writing-mode-vertical-rl-001.xht [ Failure Pass Timeout ] crbug.com/520736 [ Win7 ] media/W3C/video/networkState/networkState_during_progress.html [ Failure Pass ] @@ -812,10 +813,12 @@ crbug.com/389648 crbug.com/517123 crbug.com/410145 fast/text-autosizing/table-inflation-crash.html [ Pass Crash Timeout ] crbug.com/636207 [ Win Debug ] fast/dom/HTMLImageElement/image-srcset-w-onerror.html [ Failure Pass ] +crbug.com/636207 [ Win Debug ] virtual/sharedarraybuffer/fast/dom/HTMLImageElement/image-srcset-w-onerror.html [ Failure Pass ] crbug.com/569139 fast/js/string-replace-2.html [ Failure ] crbug.com/569139 fast/js/regexp-caching.html [ Failure ] crbug.com/597221 fast/dom/Window/window-postmessage-clone-deep-array.html [ Failure ] +crbug.com/597221 virtual/sharedarraybuffer/fast/dom/Window/window-postmessage-clone-deep-array.html [ Failure ] crbug.com/498539 [ Win ] inspector/tracing/decode-resize.html [ Failure Timeout ] crbug.com/498539 inspector/tracing/timeline-misc/timeline-bound-function.html [ Pass Failure ] crbug.com/498539 virtual/threaded/inspector/tracing/timeline-misc/timeline-bound-function.html [ Pass Failure ] @@ -870,6 +873,7 @@ crbug.com/688613 external/wpt/mediacapture-streams/MediaStreamTrack-MediaElement-disabled-audio-is-silence.https.html [ Skip ] crbug.com/542660 fast/css/absolute-inline-alignment-2.html [ Failure ] +crbug.com/542660 virtual/sharedarraybuffer/fast/css/absolute-inline-alignment-2.html [ Failure ] # Ref tests that needs investigation. crbug.com/404597 [ Mac ] fast/css3-text/css3-text-justify/text-justify-crash.html [ Failure ] @@ -1087,6 +1091,7 @@ #crbug.com/571531 external/wpt/css/css-flexbox-1/css-flexbox-height-animation-stretch.html [ Pass Failure ] crbug.com/637055 fast/css/outline-offset-large.html [ Skip ] +crbug.com/637055 virtual/sharedarraybuffer/fast/css/outline-offset-large.html [ Skip ] # Either "combo" or split should run: http://testthewebforward.org/docs/css-naming.html #crbug.com/410320 external/wpt/css/css-writing-modes-3/orthogonal-parent-shrink-to-fit-001.html [ Skip ] @@ -1174,6 +1179,7 @@ crbug.com/381684 [ Mac Win ] fonts/family-fallback-gardiner.html [ Skip ] crbug.com/467635 fast/dom/HTMLImageElement/image-sizes-meta-viewport.html [ Skip ] +crbug.com/467635 virtual/sharedarraybuffer/fast/dom/HTMLImageElement/image-sizes-meta-viewport.html [ Skip ] crbug.com/636239 [ Win7 ] media/video-zoom-controls.html [ Failure ] @@ -1217,12 +1223,14 @@ crbug.com/524160 [ Debug ] http/tests/media/media-source/stream_memory_tests/mediasource-appendbuffer-quota-exceeded-default-buffers.html [ Timeout ] crbug.com/524160 [ Debug ] virtual/mojo-loading/http/tests/media/media-source/stream_memory_tests/mediasource-appendbuffer-quota-exceeded-default-buffers.html [ Timeout ] +crbug.com/524160 [ Debug ] virtual/sharedarraybuffer/http/tests/media/media-source/stream_memory_tests/mediasource-appendbuffer-quota-exceeded-default-buffers.html [ Timeout ] # Run the tests with the default MSE buffer sizes in the main test suite and the tests for 1MB buffers set via command line in a virtual test suite # with the --mse-audio-buffer-size-limit=1048576 and --mse-video-buffer-size-limit=1048576 command-line parameters. crbug.com/630342 virtual/mse-1mb-buffers/http/tests/media/media-source/stream_memory_tests/mediasource-appendbuffer-quota-exceeded-default-buffers.html [ Skip ] crbug.com/630342 http/tests/media/media-source/stream_memory_tests/mediasource-appendbuffer-quota-exceeded-1mb-buffers.html [ Skip ] crbug.com/630342 virtual/mojo-loading/http/tests/media/media-source/stream_memory_tests/mediasource-appendbuffer-quota-exceeded-1mb-buffers.html [ Skip ] +crbug.com/630342 virtual/sharedarraybuffer/http/tests/media/media-source/stream_memory_tests/mediasource-appendbuffer-quota-exceeded-1mb-buffers.html [ Skip ] # On these platforms (all but Android) media tests don't currently use gpu-accelerated (proprietary) codecs, so no # benefit to running them again with gpu acceleration enabled. @@ -1486,6 +1494,7 @@ # These need a rebaseline due crbug.com/504745 on Windows when they are activated again. crbug.com/521124 crbug.com/410145 [ Win7 ] fast/css/font-weight-1.html [ Pass Failure ] +crbug.com/521124 crbug.com/410145 [ Win7 ] virtual/sharedarraybuffer/fast/css/font-weight-1.html [ Pass Failure ] # Temporary, until we stop use_system_harfbuzz on Linux including non-official builds crbug.com/462689 [ Linux ] fast/text/unicode-variation-selector.html [ Failure ] @@ -1514,6 +1523,7 @@ # Ref tests that fail due to differences in inline box structure, even though they contain the same text. # This happens because inline box layout uses fixed-point measurements, which can cause rounding differences. crbug.com/321237 [ Mac ] fast/dom/shadow/shadow-insertion-point-rendering-multiple-shadow-roots.html [ Failure ] +crbug.com/321237 [ Mac ] virtual/sharedarraybuffer/fast/dom/shadow/shadow-insertion-point-rendering-multiple-shadow-roots.html [ Failure ] crbug.com/321237 [ Mac ] fast/selectors/007a.html [ Failure ] crbug.com/321237 [ Mac Win ] fast/text-autosizing/inherited-multiplier.html [ Failure ] crbug.com/321237 [ Mac ] virtual/stable/fast/css3-text/css3-text-decoration/stable/first-letter-text-decoration.html [ Failure ] @@ -1525,6 +1535,7 @@ crbug.com/501659 http/tests/security/xss-DENIED-xml-external-entity.xhtml [ Failure ] crbug.com/501659 virtual/mojo-loading/http/tests/security/xss-DENIED-xml-external-entity.xhtml [ Failure ] crbug.com/501659 fast/css/stylesheet-candidate-nodes-crash.xhtml [ Failure ] +crbug.com/501659 virtual/sharedarraybuffer/fast/css/stylesheet-candidate-nodes-crash.xhtml [ Failure ] crbug.com/686470 http/tests/security/xss-DENIED-window-name-navigator.html [ Pass Failure ] crbug.com/686470 virtual/mojo-loading/http/tests/security/xss-DENIED-window-name-navigator.html [ Pass Failure ] @@ -1534,6 +1545,7 @@ # If you see wider INPUT elements or narrower TEXTAREA elements, you may do just # rebaseline. See crbug.com/508768#c6 crbug.com/509025 [ Mac10.10 ] fast/css/css2-system-fonts.html [ Failure ] +crbug.com/509025 [ Mac10.10 ] virtual/sharedarraybuffer/fast/css/css2-system-fonts.html [ Failure ] crbug.com/509025 [ Mac10.10 ] fast/forms/select/hidden-listbox.html [ Failure ] crbug.com/509025 [ Mac10.10 ] fast/forms/textarea/textarea-newline.html [ Failure ] @@ -1605,6 +1617,7 @@ crbug.com/459056 [ Win7 ] fast/text/font-fallback-win.html [ Failure ] crbug.com/525296 fast/css/font-load-while-styleresolver-missing.html [ Crash Failure Pass ] +crbug.com/525296 virtual/sharedarraybuffer/fast/css/font-load-while-styleresolver-missing.html [ Crash Failure Pass ] crbug.com/240576 external/wpt/fullscreen/api/element-ready-check-containing-iframe-manual.html [ Timeout Failure Pass ] @@ -1618,10 +1631,12 @@ crbug.com/457273 [ Mac ] http/tests/websocket/close.html [ Pass Timeout ] crbug.com/457273 [ Mac ] virtual/mojo-loading/http/tests/websocket/close.html [ Pass Timeout ] +crbug.com/457273 [ Mac ] virtual/sharedarraybuffer/http/tests/websocket/close.html [ Pass Timeout ] crbug.com/596752 virtual/threaded/inspector/tracing/decode-resize.html [ Pass Failure ] crbug.com/524646 [ Mac10.10 ] fast/dom/shadow/shadowdom-for-button.html [ Failure ] +crbug.com/524646 [ Mac10.10 ] virtual/sharedarraybuffer/fast/dom/shadow/shadowdom-for-button.html [ Failure ] crbug.com/538717 [ Win Mac Linux ] http/tests/permissions/chromium/test-request-multiple-window.html [ Failure Pass Timeout ] crbug.com/538717 [ Win Mac Linux ] http/tests/permissions/chromium/test-request-multiple-worker.html [ Failure Pass Timeout ] @@ -1678,7 +1693,6 @@ crbug.com/600248 external/wpt/web-animations/interfaces/Animation/oncancel.html [ Pass Failure ] crbug.com/600248 external/wpt/web-animations/interfaces/Animation/onfinish.html [ Failure ] -crbug.com/600248 external/wpt/web-animations/interfaces/Animation/cancel.html [ Pass Failure Crash ] crbug.com/600248 external/wpt/web-animations/timing-model/animations/updating-the-finished-state.html [ Timeout ] crbug.com/600248 external/wpt/web-animations/animation-model/animation-types/interpolation-per-property.html [ Timeout ] crbug.com/600248 external/wpt/web-animations/animation-model/animation-types/addition-per-property.html [ Timeout ] @@ -1689,6 +1703,9 @@ crbug.com/605059 [ Retina ] fast/text/international/rtl-negative-letter-spacing.html [ Failure ] +crbug.com/704077 paint/invalidation/svg/feImage-target-attribute-change-with-use-indirection-2.svg [ NeedsRebaseline ] +crbug.com/704077 paint/invalidation/svg/marker-viewBox-changes.svg [ NeedsRebaseline ] + crbug.com/610464 [ Linux Win7 Debug ] inspector/components/throttler.html [ Failure Pass ] crbug.com/487344 [ Linux Mac Win7 ] paint/invalidation/video-paint-invalidation.html [ Failure ] crbug.com/487344 [ Linux Mac Win7 ] virtual/disable-spinvalidation/paint/invalidation/video-paint-invalidation.html [ Failure ] @@ -1732,6 +1749,7 @@ # Note: this test was previously marked as slow on Debug builds. Skipping until crash is fixed crbug.com/619978 fast/css/giant-stylesheet-crash.html [ Skip ] +crbug.com/619978 virtual/sharedarraybuffer/fast/css/giant-stylesheet-crash.html [ Skip ] crbug.com/624430 [ Win10 ] fast/text/font-features/caps-casemapping.html [ Failure ] @@ -2536,6 +2554,7 @@ crbug.com/642376 virtual/gpu/fast/canvas/canvas-incremental-repaint.html [ NeedsManualRebaseline ] crbug.com/706375 virtual/gpu/fast/canvas/canvas-lost-gpu-context.html [ Failure ] crbug.com/706375 virtual/display_list_2d_canvas/fast/canvas/canvas-lost-gpu-context.html [ Failure ] +crbug.com/706375 virtual/sharedarraybuffer/fast/canvas/canvas-lost-gpu-context.html [ Failure ] # Added 2016-12-12 crbug.com/610835 http/tests/security/XFrameOptions/x-frame-options-deny-multiple-clients.html [ Failure Pass ] @@ -2549,6 +2568,7 @@ # Added 2016-12-22 crbug.com/676537 fast/css/imageTileOpacity.html [ Pass Failure ] +crbug.com/676537 virtual/sharedarraybuffer/fast/css/imageTileOpacity.html [ Pass Failure ] # ====== Random order flaky tests from here ====== # These tests are flaky when run in random order, which is the default on Linux & Mac since since 2016-12-16. @@ -2615,6 +2635,7 @@ crbug.com/676229 [ Linux ] plugins/mouse-click-plugin-clears-selection.html [ Failure Pass ] crbug.com/678346 [ Win7 Debug ] fast/dom/shadow/selections-in-shadow.html [ Pass Timeout ] +crbug.com/678346 [ Win7 Debug ] virtual/sharedarraybuffer/fast/dom/shadow/selections-in-shadow.html [ Pass Timeout ] crbug.com/678346 [ Win7 Debug ] storage/indexeddb/index-cursor.html [ Pass Timeout ] crbug.com/678346 [ Win7 Debug ] storage/indexeddb/mozilla/test_objectStore_openKeyCursor.html [ Pass Timeout ] crbug.com/678346 [ Win7 Debug ] storage/indexeddb/structured-clone.html [ Pass Timeout ] @@ -2633,6 +2654,7 @@ crbug.com/689781 http/tests/media/media-source/mediasource-duration.html [ Failure Pass ] crbug.com/689781 virtual/mojo-loading/http/tests/media/media-source/mediasource-duration.html [ Failure Pass ] +crbug.com/689781 virtual/sharedarraybuffer/http/tests/media/media-source/mediasource-duration.html [ Failure Pass ] crbug.com/701445 external/wpt/dom/events/EventListener-invoke-legacy.html [ Timeout Pass ] @@ -2682,6 +2704,7 @@ crbug.com/697342 http/tests/push_messaging/permission-state-granted-in-document.html [ Pass Failure ] crbug.com/697342 virtual/mojo-loading/http/tests/push_messaging/permission-state-granted-in-document.html [ Pass Failure ] +crbug.com/697342 virtual/sharedarraybuffer/http/tests/push_messaging/permission-state-granted-in-document.html [ Pass Failure ] crbug.com/698520 external/wpt/preload/fetch-destination.https.html [ Failure Pass ]
diff --git a/third_party/WebKit/LayoutTests/VirtualTestSuites b/third_party/WebKit/LayoutTests/VirtualTestSuites index c782e8c..2375ea98 100644 --- a/third_party/WebKit/LayoutTests/VirtualTestSuites +++ b/third_party/WebKit/LayoutTests/VirtualTestSuites
@@ -121,7 +121,7 @@ { "prefix": "origin-trials-runtimeflags-disabled", "base": "http/tests/origin_trials/webexposed", - "args": ["--disable-blink-features=ForeignFetch,ImageCapture,InstalledApp,LinkServiceWorker,LongTaskObserver,ServiceWorkerNavigationPreload,SetRootScroller,WebUSB,WebVR,WebShare"] + "args": ["--disable-blink-features=ForeignFetch,InstalledApp,LinkServiceWorker,LongTaskObserver,ServiceWorkerNavigationPreload,SetRootScroller,WebUSB,WebVR,WebShare"] }, { "prefix": "android", @@ -216,11 +216,101 @@ }, { "prefix": "sharedarraybuffer", + "base": "fast/beacon", + "args": ["--js-flags=--harmony-sharedarraybuffer", + "--enable-blink-features=SharedArrayBuffer"] + }, + { + "prefix": "sharedarraybuffer", + "base": "fast/canvas", + "args": ["--js-flags=--harmony-sharedarraybuffer", + "--enable-blink-features=SharedArrayBuffer"] + }, + { + "prefix": "sharedarraybuffer", + "base": "fast/css", + "args": ["--js-flags=--harmony-sharedarraybuffer", + "--enable-blink-features=SharedArrayBuffer"] + }, + { + "prefix": "sharedarraybuffer", + "base": "fast/dom", + "args": ["--js-flags=--harmony-sharedarraybuffer", + "--enable-blink-features=SharedArrayBuffer"] + }, + { + "prefix": "sharedarraybuffer", + "base": "fast/encoding/api", + "args": ["--js-flags=--harmony-sharedarraybuffer", + "--enable-blink-features=SharedArrayBuffer"] + }, + { + "prefix": "sharedarraybuffer", + "base": "fast/events/constructors", + "args": ["--js-flags=--harmony-sharedarraybuffer", + "--enable-blink-features=SharedArrayBuffer"] + }, + { + "prefix": "sharedarraybuffer", + "base": "fast/files", + "args": ["--js-flags=--harmony-sharedarraybuffer", + "--enable-blink-features=SharedArrayBuffer"] + }, + { + "prefix": "sharedarraybuffer", + "base": "fast/peerconnection", + "args": ["--js-flags=--harmony-sharedarraybuffer", + "--enable-blink-features=SharedArrayBuffer"] + }, + { + "prefix": "sharedarraybuffer", "base": "fast/workers", "args": ["--js-flags=--harmony-sharedarraybuffer", "--enable-blink-features=SharedArrayBuffer"] }, { + "prefix": "sharedarraybuffer", + "base": "crypto", + "args": ["--js-flags=--harmony-sharedarraybuffer", + "--enable-blink-features=SharedArrayBuffer"] + }, + { + "prefix": "sharedarraybuffer", + "base": "http/tests/media/media-source", + "args": ["--js-flags=--harmony-sharedarraybuffer", + "--enable-blink-features=SharedArrayBuffer"] + }, + { + "prefix": "sharedarraybuffer", + "base": "http/tests/push_messaging", + "args": ["--js-flags=--harmony-sharedarraybuffer", + "--enable-blink-features=SharedArrayBuffer"] + }, + { + "prefix": "sharedarraybuffer", + "base": "http/tests/websocket", + "args": ["--js-flags=--harmony-sharedarraybuffer", + "--enable-blink-features=SharedArrayBuffer"] + }, + { + "prefix": "sharedarraybuffer", + "base": "sensor", + "args": ["--js-flags=--harmony-sharedarraybuffer", + "--enable-blink-features=SharedArrayBuffer"] + }, + { + "prefix": "sharedarraybuffer", + "base": "webaudio", + "args": ["--js-flags=--harmony-sharedarraybuffer", + "--enable-blink-features=SharedArrayBuffer"] + }, + { + "prefix": "sharedarraybuffer", + "base": "webmidi", + "args": ["--js-flags=--harmony-sharedarraybuffer", + "--enable-blink-features=SharedArrayBuffer"] + }, + { "prefix": "threaded", "base": "fast/idle-callback", "args": ["--enable-threaded-compositing"]
diff --git a/third_party/WebKit/LayoutTests/crypto/random-values.js b/third_party/WebKit/LayoutTests/crypto/random-values.js index 0fb26bd..f87e1ca 100644 --- a/third_party/WebKit/LayoutTests/crypto/random-values.js +++ b/third_party/WebKit/LayoutTests/crypto/random-values.js
@@ -37,4 +37,8 @@ debug(ex); } +if (self.SharedArrayBuffer) { + shouldThrow("crypto.getRandomValues(new Uint8Array(new SharedArrayBuffer(100)))"); +} + finishJSTest();
diff --git a/third_party/WebKit/LayoutTests/crypto/subtle/importKey-badParameters-expected.txt b/third_party/WebKit/LayoutTests/crypto/subtle/importKey-badParameters-expected.txt index de9526d..73949bf 100644 --- a/third_party/WebKit/LayoutTests/crypto/subtle/importKey-badParameters-expected.txt +++ b/third_party/WebKit/LayoutTests/crypto/subtle/importKey-badParameters-expected.txt
@@ -11,6 +11,7 @@ error is: TypeError: Invalid keyFormat argument error is: TypeError: HmacImportParams: hash: Missing or not an AlgorithmIdentifier error is: NotSupportedError: SHA-1: Unsupported operation: importKey +error is: SharedArrayBuffers not enabled. PASS successfullyParsed is true TEST COMPLETE
diff --git a/third_party/WebKit/LayoutTests/crypto/subtle/importKey-badParameters.html b/third_party/WebKit/LayoutTests/crypto/subtle/importKey-badParameters.html index 9052c10..303f4e2 100644 --- a/third_party/WebKit/LayoutTests/crypto/subtle/importKey-badParameters.html +++ b/third_party/WebKit/LayoutTests/crypto/subtle/importKey-badParameters.html
@@ -62,6 +62,16 @@ return crypto.subtle.importKey('raw', new Uint8Array(20), {name: 'sha-1'}, extractable, ['sign']); }).then(failAndFinishJSTest, function(result) { logError(result); + + // SharedArrayBuffer-backed view is not allowed. + if (window.SharedArrayBuffer) { + var bytes = new Uint8Array(new SharedArrayBuffer(16)); + return crypto.subtle.importKey('raw', bytes, aesCbc, extractable, ['encrypt']); + } else { + return Promise.reject('SharedArrayBuffers not enabled.'); + } +}).then(failAndFinishJSTest, function(result) { + logError(result); }).then(finishJSTest, failAndFinishJSTest); </script>
diff --git a/third_party/WebKit/LayoutTests/external/wpt/.gitmodules b/third_party/WebKit/LayoutTests/external/wpt/.gitmodules new file mode 100644 index 0000000..5eb46bc --- /dev/null +++ b/third_party/WebKit/LayoutTests/external/wpt/.gitmodules
@@ -0,0 +1,14 @@ +[submodule "resources"] + path = resources + url = https://github.com/w3c/testharness.js.git + ignore = dirty +[submodule "tools"] + path = tools + url = https://github.com/w3c/wpt-tools.git + ignore = dirty +[submodule "css/tools/apiclient"] + path = css/tools/apiclient + url = https://github.com/w3c/csswg-apiclient.git +[submodule "css/tools/w3ctestlib"] + path = css/tools/w3ctestlib + url = https://github.com/w3c/csswg-w3ctestlib.git
diff --git a/third_party/WebKit/LayoutTests/external/wpt/.travis.yml b/third_party/WebKit/LayoutTests/external/wpt/.travis.yml new file mode 100644 index 0000000..a558820 --- /dev/null +++ b/third_party/WebKit/LayoutTests/external/wpt/.travis.yml
@@ -0,0 +1,64 @@ +dist: trusty +sudo: required +language: python +addons: + hosts: + - web-platform.test + - www.web-platform.test + - www1.web-platform.test + - www2.web-platform.test + - xn--n8j6ds53lwwkrqhv28a.web-platform.test + - xn--lve-6lad.web-platform.test +before_install: + - git submodule update --init --recursive + - export DISPLAY=:99.0 + - sh -e /etc/init.d/xvfb start +install: + - pip install -U setuptools + - pip install -U requests +env: # required at the top-level for allow_failures to work below +matrix: + include: + - os: linux + python: "2.7" + env: SCRIPT=ci_lint.sh + - os: linux + python: "2.7" + env: SCRIPT=ci_built_diff.sh + - os: linux + python: "2.7" + env: SCRIPT=css/build-css-testsuites.sh + - os: linux + python: "2.7" + addons: + apt: + packages: + - libnss3-tools + env: + - secure: "YTSXPwI0DyCA1GhYrLT9KMEV6b7QQKuEeaQgeFDP38OTzJ1+cIj3CC4SRNqbnJ/6SJwPGcdqSxLuV8m4e5HFFnyCcQnJe6h8EMsTehZ7W3j/fP9UYrJqYqvGpe3Vj3xblO5pwBYmq7sg3jAmmuCgAgOW6VGf7cRMucrsmFeo7VM=" + - SCRIPT=ci_stability.sh PRODUCT=firefox:nightly + - os: linux + sudo: required + python: "2.7" + addons: + apt: + packages: + - libappindicator1 + - fonts-liberation + env: + - secure: "YTSXPwI0DyCA1GhYrLT9KMEV6b7QQKuEeaQgeFDP38OTzJ1+cIj3CC4SRNqbnJ/6SJwPGcdqSxLuV8m4e5HFFnyCcQnJe6h8EMsTehZ7W3j/fP9UYrJqYqvGpe3Vj3xblO5pwBYmq7sg3jAmmuCgAgOW6VGf7cRMucrsmFeo7VM=" + - SCRIPT=ci_stability.sh PRODUCT=chrome:unstable + exclude: + - env: # exclude empty env from the top-level above + allow_failures: + - env: SCRIPT=css/build-css-testsuites.sh +script: + - bash $SCRIPT +cache: + directories: + - $HOME/.cache/pip +notifications: + email: + on_success: never + on_failure: always + webhooks: https://w3c-test.org/prbuildbot.py
diff --git a/third_party/WebKit/LayoutTests/external/wpt/css/CSS2/.htaccess b/third_party/WebKit/LayoutTests/external/wpt/css/CSS2/.htaccess new file mode 100644 index 0000000..538fddd8 --- /dev/null +++ b/third_party/WebKit/LayoutTests/external/wpt/css/CSS2/.htaccess
@@ -0,0 +1,24 @@ +# Define some types +AddType application/xhtml+xml .xht +AddType text/html .htm +AddType text/css .css +AddType image/png .png +AddType text/plain .data .list + +# Set the default character set +AddDefaultCharset utf-8 + +# Indexing Options +Options +Indexes +IndexOptions DescriptionWidth=* NameWidth=* FancyIndexing FoldersFirst ScanHTMLTitles +IndexIgnore .htaccess *~ .#* #*# CVS README +ReadmeName README + +# Set up the README files to be plain text +<files README> + ForceType text/plain + SetHandler default-handler +</files> + +# Add some default descriptions +AddDescription "Information about the files in this directory" README
diff --git a/third_party/WebKit/LayoutTests/external/wpt/css/css-ui-3/support/cursors/.htaccess b/third_party/WebKit/LayoutTests/external/wpt/css/css-ui-3/support/cursors/.htaccess new file mode 100644 index 0000000..016048b7 --- /dev/null +++ b/third_party/WebKit/LayoutTests/external/wpt/css/css-ui-3/support/cursors/.htaccess
@@ -0,0 +1,3 @@ +<Files "woolly-64.svgz"> + Header set Content-Encoding gzip +</Files>
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/browsers/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/browsers/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/browsers/browsing-the-web/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/browsers/browsing-the-web/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/browsers/browsing-the-web/aborting-a-document-load/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/browsers/browsing-the-web/aborting-a-document-load/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/browsers/browsing-the-web/history-traversal/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/browsers/browsing-the-web/history-traversal/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/browsers/browsing-the-web/navigating-across-documents/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/browsers/browsing-the-web/navigating-across-documents/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/browsers/browsing-the-web/read-html/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/browsers/browsing-the-web/read-html/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/browsers/browsing-the-web/read-media/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/browsers/browsing-the-web/read-media/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/browsers/browsing-the-web/read-multipart-x-mixed-replace/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/browsers/browsing-the-web/read-multipart-x-mixed-replace/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/browsers/browsing-the-web/read-plugin/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/browsers/browsing-the-web/read-plugin/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/browsers/browsing-the-web/read-text/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/browsers/browsing-the-web/read-text/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/browsers/browsing-the-web/read-ua-inline/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/browsers/browsing-the-web/read-ua-inline/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/browsers/browsing-the-web/read-xml/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/browsers/browsing-the-web/read-xml/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/browsers/browsing-the-web/scroll-to-fragid/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/browsers/browsing-the-web/scroll-to-fragid/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/browsers/browsing-the-web/unloading-documents/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/browsers/browsing-the-web/unloading-documents/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/browsers/history/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/browsers/history/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/browsers/history/history-notes/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/browsers/history/history-notes/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/browsers/history/the-history-interface/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/browsers/history/the-history-interface/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/browsers/history/the-location-interface/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/browsers/history/the-location-interface/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/browsers/history/the-session-history-of-browsing-contexts/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/browsers/history/the-session-history-of-browsing-contexts/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/browsers/offline/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/browsers/offline/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/browsers/offline/appcache/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/browsers/offline/appcache/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/browsers/offline/application-cache-api/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/browsers/offline/application-cache-api/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/browsers/offline/browser-state/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/browsers/offline/browser-state/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/browsers/offline/changestonetworkingmodel/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/browsers/offline/changestonetworkingmodel/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/browsers/offline/disk-space/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/browsers/offline/disk-space/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/browsers/offline/downloading-or-updating-an-application-cache/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/browsers/offline/downloading-or-updating-an-application-cache/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/browsers/offline/expiring-application-caches/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/browsers/offline/expiring-application-caches/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/browsers/offline/introduction-4/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/browsers/offline/introduction-4/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/browsers/offline/manifests/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/browsers/offline/manifests/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/browsers/offline/the-application-cache-selection-algorithm/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/browsers/offline/the-application-cache-selection-algorithm/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/browsers/origin/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/browsers/origin/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/browsers/origin/relaxing-the-same-origin-restriction/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/browsers/origin/relaxing-the-same-origin-restriction/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/browsers/sandboxing/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/browsers/sandboxing/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/browsers/the-window-object/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/browsers/the-window-object/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/browsers/the-window-object/accessing-other-browsing-contexts/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/browsers/the-window-object/accessing-other-browsing-contexts/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/browsers/the-window-object/apis-for-creating-and-navigating-browsing-contexts-by-name/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/browsers/the-window-object/apis-for-creating-and-navigating-browsing-contexts-by-name/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/browsers/the-window-object/browser-interface-elements/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/browsers/the-window-object/browser-interface-elements/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/browsers/the-window-object/closing-browsing-contexts/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/browsers/the-window-object/closing-browsing-contexts/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/browsers/the-window-object/garbage-collection-and-browsing-contexts/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/browsers/the-window-object/garbage-collection-and-browsing-contexts/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/browsers/the-window-object/named-access-on-the-window-object/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/browsers/the-window-object/named-access-on-the-window-object/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/browsers/the-window-object/security-window/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/browsers/the-window-object/security-window/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/browsers/the-window-object/the-windowproxy-object/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/browsers/the-window-object/the-windowproxy-object/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/browsers/windows/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/browsers/windows/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/browsers/windows/auxiliary-browsing-contexts/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/browsers/windows/auxiliary-browsing-contexts/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/browsers/windows/browsing-context-names/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/browsers/windows/browsing-context-names/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/browsers/windows/groupings-of-browsing-contexts/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/browsers/windows/groupings-of-browsing-contexts/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/browsers/windows/nested-browsing-contexts/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/browsers/windows/nested-browsing-contexts/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/browsers/windows/secondary-browsing-contexts/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/browsers/windows/secondary-browsing-contexts/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/browsers/windows/security-nav/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/browsers/windows/security-nav/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/dom/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/dom/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/dom/documents/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/dom/documents/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/dom/documents/dom-tree-accessors/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/dom/documents/dom-tree-accessors/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/dom/documents/loading-xml-documents/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/dom/documents/loading-xml-documents/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/dom/documents/resource-metadata-management/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/dom/documents/resource-metadata-management/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/dom/documents/security-document/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/dom/documents/security-document/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/dom/documents/the-document-object/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/dom/documents/the-document-object/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/dom/dynamic-markup-insertion/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/dom/dynamic-markup-insertion/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/dom/dynamic-markup-insertion/closing-the-input-stream/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/dom/dynamic-markup-insertion/closing-the-input-stream/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/dom/dynamic-markup-insertion/document-write/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/dom/dynamic-markup-insertion/document-write/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/dom/dynamic-markup-insertion/document-writeln/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/dom/dynamic-markup-insertion/document-writeln/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/dom/dynamic-markup-insertion/opening-the-input-stream/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/dom/dynamic-markup-insertion/opening-the-input-stream/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/dom/elements/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/dom/elements/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/dom/elements/content-models/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/dom/elements/content-models/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/dom/elements/element-definitions/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/dom/elements/element-definitions/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/dom/elements/elements-in-the-dom/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/dom/elements/elements-in-the-dom/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/dom/elements/global-attributes/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/dom/elements/global-attributes/.gitkeep
diff --git a/third_party/WebKit/LayoutTests/external/wpt/html/dom/elements/global-attributes/.htaccess b/third_party/WebKit/LayoutTests/external/wpt/html/dom/elements/global-attributes/.htaccess new file mode 100644 index 0000000..94e9a4f --- /dev/null +++ b/third_party/WebKit/LayoutTests/external/wpt/html/dom/elements/global-attributes/.htaccess
@@ -0,0 +1,16 @@ +AddType 'text/html; charset=UTF-8' html +<Files 'the-lang-attribute-003.html'> +AddLanguage 'ko' .html +</Files> +<Files 'the-lang-attribute-005.html'> +AddLanguage 'zh' .html +</Files> +<Files 'the-lang-attribute-006.html'> +AddLanguage 'zh' .html +</Files> +<Files 'the-lang-attribute-009.html'> +AddLanguage 'ko' .html +</Files> +<Files 'the-lang-attribute-011.html'> +AddLanguage 'ko,zh,ja' .html +</Files>
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/dom/elements/requirements-relating-to-bidirectional-algorithm-formatting-characters/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/dom/elements/requirements-relating-to-bidirectional-algorithm-formatting-characters/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/dom/elements/semantics-0/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/dom/elements/semantics-0/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/dom/elements/wai-aria/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/dom/elements/wai-aria/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/dom/interactions-with-xpath-and-xslt/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/dom/interactions-with-xpath-and-xslt/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/editing/.gitkeep similarity index 100% rename from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt rename to third_party/WebKit/LayoutTests/external/wpt/html/editing/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/editing/activation/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/editing/activation/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/editing/assigning-keyboard-shortcuts/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/editing/assigning-keyboard-shortcuts/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/editing/assigning-keyboard-shortcuts/introduction-6/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/editing/assigning-keyboard-shortcuts/introduction-6/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/editing/assigning-keyboard-shortcuts/processing-model-4/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/editing/assigning-keyboard-shortcuts/processing-model-4/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/editing/assigning-keyboard-shortcuts/the-accesskey-attribute/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/editing/assigning-keyboard-shortcuts/the-accesskey-attribute/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/editing/editing-0/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/editing/editing-0/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/editing/editing-0/best-practices-for-in-page-editors/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/editing/editing-0/best-practices-for-in-page-editors/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/editing/editing-0/contenteditable/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/editing/editing-0/contenteditable/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/editing/editing-0/editing-apis/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/editing/editing-0/editing-apis/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/editing/editing-0/making-entire-documents-editable-the-designmode-idl-attribute/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/editing/editing-0/making-entire-documents-editable-the-designmode-idl-attribute/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/editing/editing-0/spelling-and-grammar-checking/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/editing/editing-0/spelling-and-grammar-checking/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/editing/focus/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/editing/focus/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/editing/focus/document-level-focus-apis/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/editing/focus/document-level-focus-apis/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/editing/focus/element-level-focus-apis/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/editing/focus/element-level-focus-apis/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/editing/focus/focus-management/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/editing/focus/focus-management/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/editing/focus/sequential-focus-navigation-and-the-tabindex-attribute/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/editing/focus/sequential-focus-navigation-and-the-tabindex-attribute/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/editing/inert-subtrees/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/editing/inert-subtrees/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/editing/inert-subtrees/the-inert-attribute/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/editing/inert-subtrees/the-inert-attribute/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/editing/the-hidden-attribute/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/editing/the-hidden-attribute/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/iana/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/iana/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/iana/application-x-www-form-urlencoded/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/iana/application-x-www-form-urlencoded/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/iana/application-xhtml-xml/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/iana/application-xhtml-xml/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/iana/multipart-x-mixed-replace/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/iana/multipart-x-mixed-replace/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/iana/ping-to/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/iana/ping-to/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/iana/text-cache-manifest/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/iana/text-cache-manifest/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/iana/text-html/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/iana/text-html/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/iana/web-scheme-prefix/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/iana/web-scheme-prefix/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/infrastructure/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/infrastructure/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/infrastructure/case-sensitivity-and-string-comparison/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/infrastructure/case-sensitivity-and-string-comparison/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/infrastructure/common-dom-interfaces/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/infrastructure/common-dom-interfaces/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/infrastructure/common-dom-interfaces/collections/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/infrastructure/common-dom-interfaces/collections/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/infrastructure/common-dom-interfaces/domstringmap/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/infrastructure/common-dom-interfaces/domstringmap/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/infrastructure/common-dom-interfaces/garbage-collection/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/infrastructure/common-dom-interfaces/garbage-collection/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/infrastructure/common-dom-interfaces/reflecting-content-attributes-in-idl-attributes/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/infrastructure/common-dom-interfaces/reflecting-content-attributes-in-idl-attributes/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/infrastructure/common-dom-interfaces/safe-passing-of-structured-data/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/infrastructure/common-dom-interfaces/safe-passing-of-structured-data/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/infrastructure/common-dom-interfaces/transferable-objects/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/infrastructure/common-dom-interfaces/transferable-objects/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/infrastructure/common-microsyntaxes/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/infrastructure/common-microsyntaxes/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/infrastructure/common-microsyntaxes/boolean-attributes/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/infrastructure/common-microsyntaxes/boolean-attributes/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/infrastructure/common-microsyntaxes/colors/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/infrastructure/common-microsyntaxes/colors/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/infrastructure/common-microsyntaxes/comma-separated-tokens/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/infrastructure/common-microsyntaxes/comma-separated-tokens/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/infrastructure/common-microsyntaxes/common-parser-idioms/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/infrastructure/common-microsyntaxes/common-parser-idioms/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/infrastructure/common-microsyntaxes/dates-and-times/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/infrastructure/common-microsyntaxes/dates-and-times/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/infrastructure/common-microsyntaxes/keywords-and-enumerated-attributes/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/infrastructure/common-microsyntaxes/keywords-and-enumerated-attributes/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/infrastructure/common-microsyntaxes/mq/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/infrastructure/common-microsyntaxes/mq/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/infrastructure/common-microsyntaxes/numbers/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/infrastructure/common-microsyntaxes/numbers/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/infrastructure/common-microsyntaxes/space-separated-tokens/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/infrastructure/common-microsyntaxes/space-separated-tokens/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/infrastructure/common-microsyntaxes/syntax-references/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/infrastructure/common-microsyntaxes/syntax-references/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/infrastructure/conformance-requirements/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/infrastructure/conformance-requirements/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/infrastructure/conformance-requirements/conformance-classes/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/infrastructure/conformance-requirements/conformance-classes/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/infrastructure/conformance-requirements/dependencies/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/infrastructure/conformance-requirements/dependencies/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/infrastructure/conformance-requirements/extensibility/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/infrastructure/conformance-requirements/extensibility/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/infrastructure/fetching-resources/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/infrastructure/fetching-resources/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/infrastructure/fetching-resources/content-type-sniffing/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/infrastructure/fetching-resources/content-type-sniffing/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/infrastructure/fetching-resources/cors-enabled-fetch/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/infrastructure/fetching-resources/cors-enabled-fetch/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/infrastructure/fetching-resources/cors-settings-attributes/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/infrastructure/fetching-resources/cors-settings-attributes/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/infrastructure/fetching-resources/encrypted-http-and-related-security-concerns/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/infrastructure/fetching-resources/encrypted-http-and-related-security-concerns/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/infrastructure/fetching-resources/extracting-character-encodings-from-meta-elements/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/infrastructure/fetching-resources/extracting-character-encodings-from-meta-elements/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/infrastructure/fetching-resources/processing-model/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/infrastructure/fetching-resources/processing-model/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/infrastructure/fetching-resources/terminology-1/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/infrastructure/fetching-resources/terminology-1/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/infrastructure/namespaces/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/infrastructure/namespaces/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/infrastructure/terminology/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/infrastructure/terminology/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/infrastructure/terminology/character-encodings/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/infrastructure/terminology/character-encodings/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/infrastructure/terminology/dom-trees/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/infrastructure/terminology/dom-trees/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/infrastructure/terminology/plugins/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/infrastructure/terminology/plugins/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/infrastructure/terminology/resources/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/infrastructure/terminology/resources/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/infrastructure/terminology/scripting-0/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/infrastructure/terminology/scripting-0/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/infrastructure/terminology/xml/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/infrastructure/terminology/xml/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/infrastructure/urls/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/infrastructure/urls/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/infrastructure/urls/base-urls/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/infrastructure/urls/base-urls/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/infrastructure/urls/dynamic-changes-to-base-urls/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/infrastructure/urls/dynamic-changes-to-base-urls/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/infrastructure/urls/interfaces-for-url-manipulation/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/infrastructure/urls/interfaces-for-url-manipulation/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/infrastructure/urls/parsing-urls/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/infrastructure/urls/parsing-urls/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/infrastructure/urls/resolving-urls/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/infrastructure/urls/resolving-urls/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/infrastructure/urls/terminology-0/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/infrastructure/urls/terminology-0/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/infrastructure/urls/url-manipulation-and-creation/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/infrastructure/urls/url-manipulation-and-creation/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/infrastructure/utf-8/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/infrastructure/utf-8/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/introduction/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/introduction/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/introduction/a-quick-introduction-to-html/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/introduction/a-quick-introduction-to-html/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/introduction/a-quick-introduction-to-html/common-pitfalls-to-avoid-when-using-the-scripting-apis/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/introduction/a-quick-introduction-to-html/common-pitfalls-to-avoid-when-using-the-scripting-apis/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/introduction/a-quick-introduction-to-html/writing-secure-applications-with-html/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/introduction/a-quick-introduction-to-html/writing-secure-applications-with-html/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/introduction/audience/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/introduction/audience/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/introduction/background/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/introduction/background/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/introduction/conformance-requirements-for-authors/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/introduction/conformance-requirements-for-authors/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/introduction/conformance-requirements-for-authors/presentational-markup/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/introduction/conformance-requirements-for-authors/presentational-markup/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/introduction/conformance-requirements-for-authors/restrictions-on-content-models-and-on-attribute-values/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/introduction/conformance-requirements-for-authors/restrictions-on-content-models-and-on-attribute-values/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/introduction/conformance-requirements-for-authors/syntax-errors/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/introduction/conformance-requirements-for-authors/syntax-errors/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/introduction/design-notes/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/introduction/design-notes/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/introduction/design-notes/compliance-with-other-specifications/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/introduction/design-notes/compliance-with-other-specifications/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/introduction/design-notes/serializability-of-script-execution/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/introduction/design-notes/serializability-of-script-execution/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/introduction/fingerprint/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/introduction/fingerprint/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/introduction/history-0/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/introduction/history-0/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/introduction/html-vs-xhtml/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/introduction/html-vs-xhtml/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/introduction/scope/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/introduction/scope/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/introduction/structure-of-this-specification/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/introduction/structure-of-this-specification/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/introduction/structure-of-this-specification/how-to-read-this-specification/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/introduction/structure-of-this-specification/how-to-read-this-specification/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/introduction/structure-of-this-specification/typographic-conventions/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/introduction/structure-of-this-specification/typographic-conventions/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/introduction/suggested-reading/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/introduction/suggested-reading/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/obsolete/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/obsolete/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/obsolete/non-conforming-features/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/obsolete/non-conforming-features/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/obsolete/obsolete-but-conforming-features/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/obsolete/obsolete-but-conforming-features/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/obsolete/obsolete-but-conforming-features/warnings-for-obsolete-but-conforming-features/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/obsolete/obsolete-but-conforming-features/warnings-for-obsolete-but-conforming-features/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/obsolete/requirements-for-implementations/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/obsolete/requirements-for-implementations/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/obsolete/requirements-for-implementations/frames/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/obsolete/requirements-for-implementations/frames/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/obsolete/requirements-for-implementations/other-elements-attributes-and-apis/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/obsolete/requirements-for-implementations/other-elements-attributes-and-apis/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/obsolete/requirements-for-implementations/the-applet-element/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/obsolete/requirements-for-implementations/the-applet-element/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/obsolete/requirements-for-implementations/the-marquee-element-0/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/obsolete/requirements-for-implementations/the-marquee-element-0/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/rendering/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/rendering/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/rendering/bindings/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/rendering/bindings/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/rendering/bindings/introduction-9/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/rendering/bindings/introduction-9/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/rendering/bindings/the-details-element-0/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/rendering/bindings/the-details-element-0/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/rendering/bindings/the-input-element-as-a-button/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/rendering/bindings/the-input-element-as-a-button/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/rendering/bindings/the-input-element-as-a-checkbox-and-radio-button-widgets/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/rendering/bindings/the-input-element-as-a-checkbox-and-radio-button-widgets/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/rendering/bindings/the-input-element-as-a-color-well/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/rendering/bindings/the-input-element-as-a-color-well/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/rendering/bindings/the-input-element-as-a-file-upload-control/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/rendering/bindings/the-input-element-as-a-file-upload-control/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/rendering/bindings/the-input-element-as-a-range-control/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/rendering/bindings/the-input-element-as-a-range-control/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/rendering/bindings/the-input-element-as-a-text-entry-widget/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/rendering/bindings/the-input-element-as-a-text-entry-widget/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/rendering/bindings/the-input-element-as-domain-specific-widgets/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/rendering/bindings/the-input-element-as-domain-specific-widgets/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/rendering/bindings/the-marquee-element/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/rendering/bindings/the-marquee-element/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/rendering/bindings/the-meter-element-0/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/rendering/bindings/the-meter-element-0/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/rendering/bindings/the-progress-element-0/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/rendering/bindings/the-progress-element-0/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/rendering/bindings/the-select-element-0/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/rendering/bindings/the-select-element-0/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/rendering/bindings/the-textarea-element-0/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/rendering/bindings/the-textarea-element-0/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/rendering/frames-and-framesets/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/rendering/frames-and-framesets/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/rendering/interactive-media/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/rendering/interactive-media/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/rendering/interactive-media/editing-hosts/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/rendering/interactive-media/editing-hosts/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/rendering/interactive-media/links-forms-and-navigation/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/rendering/interactive-media/links-forms-and-navigation/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/rendering/interactive-media/text-rendered-in-native-user-interfaces/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/rendering/interactive-media/text-rendered-in-native-user-interfaces/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/rendering/interactive-media/the-title-attribute-0/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/rendering/interactive-media/the-title-attribute-0/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/rendering/introduction-8/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/rendering/introduction-8/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/rendering/non-replaced-elements/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/rendering/non-replaced-elements/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/rendering/non-replaced-elements/bidirectional-text/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/rendering/non-replaced-elements/bidirectional-text/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/rendering/non-replaced-elements/flow-content-0/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/rendering/non-replaced-elements/flow-content-0/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/rendering/non-replaced-elements/form-controls/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/rendering/non-replaced-elements/form-controls/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/rendering/non-replaced-elements/hidden-elements/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/rendering/non-replaced-elements/hidden-elements/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/rendering/non-replaced-elements/lists/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/rendering/non-replaced-elements/lists/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/rendering/non-replaced-elements/phrasing-content-0/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/rendering/non-replaced-elements/phrasing-content-0/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/rendering/non-replaced-elements/quotes/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/rendering/non-replaced-elements/quotes/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/rendering/non-replaced-elements/sections-and-headings/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/rendering/non-replaced-elements/sections-and-headings/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/rendering/non-replaced-elements/tables/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/rendering/non-replaced-elements/tables/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/rendering/non-replaced-elements/the-fieldset-element-0/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/rendering/non-replaced-elements/the-fieldset-element-0/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/rendering/non-replaced-elements/the-hr-element-0/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/rendering/non-replaced-elements/the-hr-element-0/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/rendering/non-replaced-elements/the-page/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/rendering/non-replaced-elements/the-page/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/rendering/print-media/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/rendering/print-media/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/rendering/replaced-elements/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/rendering/replaced-elements/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/rendering/replaced-elements/attributes-for-embedded-content-and-images/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/rendering/replaced-elements/attributes-for-embedded-content-and-images/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/rendering/replaced-elements/embedded-content-rendering-rules/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/rendering/replaced-elements/embedded-content-rendering-rules/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/rendering/replaced-elements/image-maps-0/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/rendering/replaced-elements/image-maps-0/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/rendering/replaced-elements/images/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/rendering/replaced-elements/images/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/rendering/replaced-elements/toolbars-0/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/rendering/replaced-elements/toolbars-0/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/rendering/the-css-user-agent-style-sheet-and-presentational-hints/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/rendering/the-css-user-agent-style-sheet-and-presentational-hints/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/rendering/unstyled-xml-documents/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/rendering/unstyled-xml-documents/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/semantics/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/common-idioms/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/semantics/common-idioms/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/common-idioms/conversations/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/semantics/common-idioms/conversations/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/common-idioms/footnotes/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/semantics/common-idioms/footnotes/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/common-idioms/rel-up/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/semantics/common-idioms/rel-up/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/common-idioms/tag-clouds/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/semantics/common-idioms/tag-clouds/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/common-idioms/the-main-part-of-the-content/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/semantics/common-idioms/the-main-part-of-the-content/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/disabled-elements/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/semantics/disabled-elements/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/document-metadata/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/semantics/document-metadata/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/document-metadata/styling/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/semantics/document-metadata/styling/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/document-metadata/the-base-element/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/semantics/document-metadata/the-base-element/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/document-metadata/the-head-element/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/semantics/document-metadata/the-head-element/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/document-metadata/the-link-element/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/semantics/document-metadata/the-link-element/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/document-metadata/the-meta-element/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/semantics/document-metadata/the-meta-element/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/document-metadata/the-style-element/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/semantics/document-metadata/the-style-element/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/document-metadata/the-title-element/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/semantics/document-metadata/the-title-element/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/edits/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/semantics/edits/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/edits/attributes-common-to-ins-and-del-elements/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/semantics/edits/attributes-common-to-ins-and-del-elements/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/edits/edits-and-lists/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/semantics/edits/edits-and-lists/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/edits/edits-and-paragraphs/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/semantics/edits/edits-and-paragraphs/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/edits/edits-and-tables/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/semantics/edits/edits-and-tables/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/edits/the-del-element/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/semantics/edits/the-del-element/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/edits/the-ins-element/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/semantics/edits/the-ins-element/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/embedded-content/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/semantics/embedded-content/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/embedded-content/dimension-attributes/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/semantics/embedded-content/dimension-attributes/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/embedded-content/image-maps/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/semantics/embedded-content/image-maps/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/embedded-content/mathml/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/semantics/embedded-content/mathml/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/embedded-content/media-elements/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/semantics/embedded-content/media-elements/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/embedded-content/svg/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/semantics/embedded-content/svg/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/embedded-content/the-area-element/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/semantics/embedded-content/the-area-element/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/embedded-content/the-audio-element/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/semantics/embedded-content/the-audio-element/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/embedded-content/the-embed-element/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/semantics/embedded-content/the-embed-element/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/embedded-content/the-iframe-element/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/semantics/embedded-content/the-iframe-element/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/embedded-content/the-img-element/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/semantics/embedded-content/the-img-element/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/embedded-content/the-map-element/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/semantics/embedded-content/the-map-element/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/embedded-content/the-object-element/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/semantics/embedded-content/the-object-element/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/embedded-content/the-param-element/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/semantics/embedded-content/the-param-element/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/embedded-content/the-source-element/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/semantics/embedded-content/the-source-element/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/embedded-content/the-track-element/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/semantics/embedded-content/the-track-element/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/embedded-content/the-video-element/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/semantics/embedded-content/the-video-element/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/forms/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/semantics/forms/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/forms/attributes-common-to-form-controls/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/semantics/forms/attributes-common-to-form-controls/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/forms/categories/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/semantics/forms/categories/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/forms/constraints/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/semantics/forms/constraints/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/forms/form-control-infrastructure/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/semantics/forms/form-control-infrastructure/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/forms/form-submission-0/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/semantics/forms/form-submission-0/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/forms/introduction-1/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/semantics/forms/introduction-1/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/forms/resetting-a-form/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/semantics/forms/resetting-a-form/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/forms/textfieldselection/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/semantics/forms/textfieldselection/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/forms/the-button-element/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/semantics/forms/the-button-element/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/forms/the-datalist-element/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/semantics/forms/the-datalist-element/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/forms/the-fieldset-element/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/semantics/forms/the-fieldset-element/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/forms/the-form-element/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/semantics/forms/the-form-element/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/forms/the-input-element/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/semantics/forms/the-input-element/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/forms/the-label-element/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/semantics/forms/the-label-element/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/forms/the-legend-element/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/semantics/forms/the-legend-element/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/forms/the-meter-element/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/semantics/forms/the-meter-element/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/forms/the-optgroup-element/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/semantics/forms/the-optgroup-element/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/forms/the-option-element/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/semantics/forms/the-option-element/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/forms/the-output-element/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/semantics/forms/the-output-element/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/forms/the-progress-element/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/semantics/forms/the-progress-element/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/forms/the-select-element/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/semantics/forms/the-select-element/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/forms/the-textarea-element/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/semantics/forms/the-textarea-element/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/grouping-content/the-blockquote-element/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/semantics/grouping-content/the-blockquote-element/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/grouping-content/the-dd-element/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/semantics/grouping-content/the-dd-element/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/grouping-content/the-div-element/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/semantics/grouping-content/the-div-element/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/grouping-content/the-dl-element/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/semantics/grouping-content/the-dl-element/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/grouping-content/the-dt-element/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/semantics/grouping-content/the-dt-element/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/grouping-content/the-figcaption-element/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/semantics/grouping-content/the-figcaption-element/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/grouping-content/the-figure-element/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/semantics/grouping-content/the-figure-element/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/grouping-content/the-hr-element/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/semantics/grouping-content/the-hr-element/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/grouping-content/the-p-element/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/semantics/grouping-content/the-p-element/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/grouping-content/the-pre-element/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/semantics/grouping-content/the-pre-element/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/grouping-content/the-ul-element/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/semantics/grouping-content/the-ul-element/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/interactive-elements/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/semantics/interactive-elements/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/interactive-elements/commands/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/semantics/interactive-elements/commands/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/interactive-elements/the-command-element/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/semantics/interactive-elements/the-command-element/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/interactive-elements/the-details-element/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/semantics/interactive-elements/the-details-element/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/interactive-elements/the-menu-element/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/semantics/interactive-elements/the-menu-element/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/interactive-elements/the-summary-element/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/semantics/interactive-elements/the-summary-element/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/links/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/semantics/links/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/links/downloading-resources/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/semantics/links/downloading-resources/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/links/following-hyperlinks/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/semantics/links/following-hyperlinks/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/links/introduction-3/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/semantics/links/introduction-3/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/links/links-created-by-a-and-area-elements/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/semantics/links/links-created-by-a-and-area-elements/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/links/linktypes/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/semantics/links/linktypes/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/scripting-1/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/semantics/scripting-1/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/scripting-1/the-noscript-element/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/semantics/scripting-1/the-noscript-element/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/scripting-1/the-script-element/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/semantics/scripting-1/the-script-element/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/sections/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/semantics/sections/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/sections/headings-and-sections/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/semantics/sections/headings-and-sections/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/sections/the-address-element/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/semantics/sections/the-address-element/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/sections/the-article-element/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/semantics/sections/the-article-element/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/sections/the-aside-element/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/semantics/sections/the-aside-element/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/sections/the-body-element/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/semantics/sections/the-body-element/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/sections/the-footer-element/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/semantics/sections/the-footer-element/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/sections/the-h1-h2-h3-h4-h5-and-h6-elements/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/semantics/sections/the-h1-h2-h3-h4-h5-and-h6-elements/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/sections/the-header-element/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/semantics/sections/the-header-element/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/sections/the-hgroup-element/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/semantics/sections/the-hgroup-element/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/sections/the-nav-element/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/semantics/sections/the-nav-element/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/sections/the-section-element/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/semantics/sections/the-section-element/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/sections/usage-summary-0/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/semantics/sections/usage-summary-0/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/selectors/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/semantics/selectors/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/selectors/case-sensitivity/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/semantics/selectors/case-sensitivity/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/tabular-data/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/semantics/tabular-data/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/tabular-data/attributes-common-to-td-and-th-elements/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/semantics/tabular-data/attributes-common-to-td-and-th-elements/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/tabular-data/examples/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/semantics/tabular-data/examples/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/tabular-data/processing-model-1/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/semantics/tabular-data/processing-model-1/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/tabular-data/the-caption-element/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/semantics/tabular-data/the-caption-element/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/tabular-data/the-col-element/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/semantics/tabular-data/the-col-element/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/tabular-data/the-colgroup-element/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/semantics/tabular-data/the-colgroup-element/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/tabular-data/the-table-element/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/semantics/tabular-data/the-table-element/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/tabular-data/the-tbody-element/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/semantics/tabular-data/the-tbody-element/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/tabular-data/the-td-element/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/semantics/tabular-data/the-td-element/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/tabular-data/the-tfoot-element/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/semantics/tabular-data/the-tfoot-element/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/tabular-data/the-th-element/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/semantics/tabular-data/the-th-element/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/tabular-data/the-thead-element/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/semantics/tabular-data/the-thead-element/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/tabular-data/the-tr-element/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/semantics/tabular-data/the-tr-element/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/text-level-semantics/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/semantics/text-level-semantics/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/text-level-semantics/the-a-element/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/semantics/text-level-semantics/the-a-element/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/text-level-semantics/the-abbr-element/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/semantics/text-level-semantics/the-abbr-element/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/text-level-semantics/the-b-element/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/semantics/text-level-semantics/the-b-element/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/text-level-semantics/the-bdi-element/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/semantics/text-level-semantics/the-bdi-element/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/text-level-semantics/the-bdo-element/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/semantics/text-level-semantics/the-bdo-element/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/text-level-semantics/the-br-element/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/semantics/text-level-semantics/the-br-element/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/text-level-semantics/the-cite-element/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/semantics/text-level-semantics/the-cite-element/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/text-level-semantics/the-code-element/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/semantics/text-level-semantics/the-code-element/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/text-level-semantics/the-dfn-element/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/semantics/text-level-semantics/the-dfn-element/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/text-level-semantics/the-em-element/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/semantics/text-level-semantics/the-em-element/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/text-level-semantics/the-i-element/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/semantics/text-level-semantics/the-i-element/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/text-level-semantics/the-kbd-element/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/semantics/text-level-semantics/the-kbd-element/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/text-level-semantics/the-mark-element/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/semantics/text-level-semantics/the-mark-element/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/text-level-semantics/the-q-element/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/semantics/text-level-semantics/the-q-element/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/text-level-semantics/the-rp-element/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/semantics/text-level-semantics/the-rp-element/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/text-level-semantics/the-rt-element/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/semantics/text-level-semantics/the-rt-element/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/text-level-semantics/the-ruby-element/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/semantics/text-level-semantics/the-ruby-element/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/text-level-semantics/the-s-element/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/semantics/text-level-semantics/the-s-element/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/text-level-semantics/the-samp-element/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/semantics/text-level-semantics/the-samp-element/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/text-level-semantics/the-small-element/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/semantics/text-level-semantics/the-small-element/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/text-level-semantics/the-span-element/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/semantics/text-level-semantics/the-span-element/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/text-level-semantics/the-strong-element/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/semantics/text-level-semantics/the-strong-element/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/text-level-semantics/the-sub-and-sup-elements/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/semantics/text-level-semantics/the-sub-and-sup-elements/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/text-level-semantics/the-time-element/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/semantics/text-level-semantics/the-time-element/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/text-level-semantics/the-u-element/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/semantics/text-level-semantics/the-u-element/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/text-level-semantics/the-var-element/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/semantics/text-level-semantics/the-var-element/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/text-level-semantics/usage-summary/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/semantics/text-level-semantics/usage-summary/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/the-root-element/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/semantics/the-root-element/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/the-root-element/the-html-element/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/semantics/the-root-element/the-html-element/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/syntax/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/syntax/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/syntax/parsing-html-fragments/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/syntax/parsing-html-fragments/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/syntax/parsing/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/syntax/parsing/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/syntax/serializing-html-fragments/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/syntax/serializing-html-fragments/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/syntax/writing/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/syntax/writing/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/syntax/writing/cdata-sections/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/syntax/writing/cdata-sections/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/syntax/writing/character-references/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/syntax/writing/character-references/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/syntax/writing/comments/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/syntax/writing/comments/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/syntax/writing/elements-0/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/syntax/writing/elements-0/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/syntax/writing/text/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/syntax/writing/text/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/syntax/writing/the-doctype/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/syntax/writing/the-doctype/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/the-xhtml-syntax/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/the-xhtml-syntax/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/the-xhtml-syntax/parsing-xhtml-documents/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/the-xhtml-syntax/parsing-xhtml-documents/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/the-xhtml-syntax/parsing-xhtml-fragments/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/the-xhtml-syntax/parsing-xhtml-fragments/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/the-xhtml-syntax/serializing-xhtml-fragments/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/the-xhtml-syntax/serializing-xhtml-fragments/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/the-xhtml-syntax/writing-xhtml-documents/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/the-xhtml-syntax/writing-xhtml-documents/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/webappapis/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/webappapis/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/webappapis/atob/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/webappapis/atob/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/webappapis/scripting/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/webappapis/scripting/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/webappapis/scripting/enabling-and-disabling-scripting/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/webappapis/scripting/enabling-and-disabling-scripting/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/webappapis/scripting/event-loops/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/webappapis/scripting/event-loops/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/webappapis/scripting/events/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/webappapis/scripting/events/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/webappapis/scripting/introduction-5/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/webappapis/scripting/introduction-5/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/webappapis/scripting/javascript-protocol/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/webappapis/scripting/javascript-protocol/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/webappapis/scripting/processing-model-2/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/webappapis/scripting/processing-model-2/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/webappapis/system-state-and-capabilities/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/webappapis/system-state-and-capabilities/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/webappapis/system-state-and-capabilities/the-external-interface/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/webappapis/system-state-and-capabilities/the-external-interface/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/webappapis/system-state-and-capabilities/the-navigator-object/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/webappapis/system-state-and-capabilities/the-navigator-object/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/webappapis/timers/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/webappapis/timers/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/webappapis/user-prompts/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/webappapis/user-prompts/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/webappapis/user-prompts/dialogs-implemented-using-separate-documents/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/webappapis/user-prompts/dialogs-implemented-using-separate-documents/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/webappapis/user-prompts/printing/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/webappapis/user-prompts/printing/.gitkeep
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt b/third_party/WebKit/LayoutTests/external/wpt/html/webappapis/user-prompts/simple-dialogs/.gitkeep similarity index 100% copy from tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.txt copy to third_party/WebKit/LayoutTests/external/wpt/html/webappapis/user-prompts/simple-dialogs/.gitkeep
diff --git a/third_party/WebKit/LayoutTests/external/wpt/resources/.gitmodules b/third_party/WebKit/LayoutTests/external/wpt/resources/.gitmodules new file mode 100644 index 0000000..8903572 --- /dev/null +++ b/third_party/WebKit/LayoutTests/external/wpt/resources/.gitmodules
@@ -0,0 +1,3 @@ +[submodule "webidl2"] + path = webidl2 + url = https://github.com/darobin/webidl2.js.git
diff --git a/third_party/WebKit/LayoutTests/external/wpt/resources/.htaccess b/third_party/WebKit/LayoutTests/external/wpt/resources/.htaccess new file mode 100644 index 0000000..fd46101c --- /dev/null +++ b/third_party/WebKit/LayoutTests/external/wpt/resources/.htaccess
@@ -0,0 +1,2 @@ +# make tests that use utf-16 not inherit the encoding for testharness.js et. al. +AddCharset utf-8 .css .js
diff --git a/third_party/WebKit/LayoutTests/external/wpt/resources/webidl2/.gitmodules b/third_party/WebKit/LayoutTests/external/wpt/resources/webidl2/.gitmodules new file mode 100644 index 0000000..a3f5485c --- /dev/null +++ b/third_party/WebKit/LayoutTests/external/wpt/resources/webidl2/.gitmodules
@@ -0,0 +1,3 @@ +[submodule "test/widlproc"] + path = test/widlproc + url = https://github.com/dontcallmedom/widlproc.git
diff --git a/third_party/WebKit/LayoutTests/external/wpt/resources/webidl2/.travis.yml b/third_party/WebKit/LayoutTests/external/wpt/resources/webidl2/.travis.yml new file mode 100644 index 0000000..6e5919d --- /dev/null +++ b/third_party/WebKit/LayoutTests/external/wpt/resources/webidl2/.travis.yml
@@ -0,0 +1,3 @@ +language: node_js +node_js: + - "0.10"
diff --git a/third_party/WebKit/LayoutTests/external/wpt/web-animations/interfaces/Animation/finish-expected.txt b/third_party/WebKit/LayoutTests/external/wpt/web-animations/interfaces/Animation/finish-expected.txt index db99c1b9..bd053d2e 100644 --- a/third_party/WebKit/LayoutTests/external/wpt/web-animations/interfaces/Animation/finish-expected.txt +++ b/third_party/WebKit/LayoutTests/external/wpt/web-animations/interfaces/Animation/finish-expected.txt
@@ -11,7 +11,7 @@ PASS Test finish() while play-pending PASS Test finish() during aborted pause PASS Test resetting of computed style -FAIL Test finish() resolves finished promise synchronously assert_true: Animation.finished should be resolved soon after Animation.finish() expected true got false +PASS Test finish() resolves finished promise synchronously FAIL Test finish() resolves finished promise synchronously with an animation without a target Animation is not defined FAIL Test normally finished animation resolves finished promise synchronously with an animation without a target Animation is not defined Harness: the test ran to completion.
diff --git a/third_party/WebKit/LayoutTests/external/wpt/web-animations/interfaces/Animation/finished-expected.txt b/third_party/WebKit/LayoutTests/external/wpt/web-animations/interfaces/Animation/finished-expected.txt index f6c6decf..35246c6 100644 --- a/third_party/WebKit/LayoutTests/external/wpt/web-animations/interfaces/Animation/finished-expected.txt +++ b/third_party/WebKit/LayoutTests/external/wpt/web-animations/interfaces/Animation/finished-expected.txt
@@ -15,9 +15,9 @@ PASS Test finished promise changes when a prior finished promise resolved and the animation falls out finished state PASS Test no new finished promise generated when finished state is checked asynchronously PASS Test new finished promise generated when finished state is checked synchronously -FAIL Test synchronous finished promise resolved even if finished state is changed soon assert_true: Animation.finished should be resolved even if the finished state is changed soon expected true got false -FAIL Test synchronous finished promise resolved even if asynchronous finished promise happens just before synchronous promise assert_true: Animation.finished should be resolved soon after finish() is called even if there are other asynchronous promises just before it expected true got false -PASS Test finished promise is not resolved when the animation falls out finished state immediately +PASS Test synchronous finished promise resolved even if finished state is changed soon +PASS Test synchronous finished promise resolved even if asynchronous finished promise happens just before synchronous promise +FAIL Test finished promise is not resolved when the animation falls out finished state immediately assert_unreached: Animation.finished should not be resolved Reached unreachable code FAIL Test finished promise is not resolved once the animation falls out finished state even though the current finished promise is generated soon after animation state became finished assert_unreached: Animation.finished should not be resolved Reached unreachable code PASS Finished promise should be resolved after the ready promise is resolved PASS Finished promise should be rejected after the ready promise is rejected
diff --git a/third_party/WebKit/LayoutTests/fast/beacon/beacon-basic.html b/third_party/WebKit/LayoutTests/fast/beacon/beacon-basic.html index 6450c6ef..faa5fa2 100644 --- a/third_party/WebKit/LayoutTests/fast/beacon/beacon-basic.html +++ b/third_party/WebKit/LayoutTests/fast/beacon/beacon-basic.html
@@ -8,4 +8,9 @@ shouldThrow("navigator.sendBeacon()"); shouldThrow("navigator.sendBeacon('http:')"); shouldThrow("navigator.sendBeacon('javascript:alert(1);')"); + +if (window.SharedArrayBuffer) { + shouldThrow("navigator.sendBeacon('https:', new Uint8Array(new SharedArrayBuffer(10)))"); +} + </script>
diff --git a/third_party/WebKit/LayoutTests/fast/canvas/canvas-ImageData-constructor.html b/third_party/WebKit/LayoutTests/fast/canvas/canvas-ImageData-constructor.html index 16c788d6..c5b0e58 100644 --- a/third_party/WebKit/LayoutTests/fast/canvas/canvas-ImageData-constructor.html +++ b/third_party/WebKit/LayoutTests/fast/canvas/canvas-ImageData-constructor.html
@@ -74,6 +74,10 @@ assert_array_equals(getRGBA(imageDataFromData.data, 2), getRGBA(data, 2)); setRGBA(imageDataFromData.data, 2, testColor); assert_array_equals(getRGBA(imageDataFromData.data, 2), getRGBA(data, 2)); + + if (window.SharedArrayBuffer) { + assert_throws(null, function() {new ImageData(new Uint16Array(new SharedArrayBuffer(32)), 4, 2)}); + } }, 'Test ImageData constructor'); </script>
diff --git a/third_party/WebKit/LayoutTests/fast/css/fontface-arraybuffer.html b/third_party/WebKit/LayoutTests/fast/css/fontface-arraybuffer.html index 1bbcd1ca..31457b6 100644 --- a/third_party/WebKit/LayoutTests/fast/css/fontface-arraybuffer.html +++ b/third_party/WebKit/LayoutTests/fast/css/fontface-arraybuffer.html
@@ -23,6 +23,16 @@ shouldBeEqualToString('face2.status', 'loaded'); document.fonts.add(face2); +if (window.SharedArrayBuffer) { + try { + new FontFace('FontFromSharedArrayBufferView', + new Uint8Array(new SharedArrayBuffer(4))); + } catch (e) { + rejectionValue = e; + shouldBeEqualToString('rejectionValue.name', 'TypeError'); + } +} + var face3 = new FontFace('FontFromEmptyArrayBuffer', new ArrayBuffer(0)); shouldBeEqualToString('face3.status', 'error'); face3.load().catch(function(v) {
diff --git a/third_party/WebKit/LayoutTests/fast/dom/geometry-interfaces-dom-matrix-readonly.html b/third_party/WebKit/LayoutTests/fast/dom/geometry-interfaces-dom-matrix-readonly.html index 72c1c8fb..3aa6eb3 100644 --- a/third_party/WebKit/LayoutTests/fast/dom/geometry-interfaces-dom-matrix-readonly.html +++ b/third_party/WebKit/LayoutTests/fast/dom/geometry-interfaces-dom-matrix-readonly.html
@@ -177,6 +177,15 @@ "fromFloat64Array function only accepts 1 Float64Array with 6 or 16 elements"); }, "DOMMatrixReadOnly fromFloat*Array - invalid array size"); +if (window.SharedArrayBuffer) { + test(() => { + assert_throws(new TypeError(), () => { DOMMatrixReadOnly.fromFloat32Array(new Float32Array(new SharedArrayBuffer(24))); }, + ""); + assert_throws(new TypeError(), () => { DOMMatrixReadOnly.fromFloat64Array(new Float64Array(new SharedArrayBuffer(32))); }, + ""); + }, "DOMMatrixReadOnly fromFloat*Array - can't use SharedArrayBuffer view"); +} + test(() => { var matrix = DOMMatrixReadOnly.fromMatrix(); assert_identity_2d_matrix(matrix);
diff --git a/third_party/WebKit/LayoutTests/fast/dom/geometry-interfaces-dom-matrix.html b/third_party/WebKit/LayoutTests/fast/dom/geometry-interfaces-dom-matrix.html index 998c3da..525425f 100644 --- a/third_party/WebKit/LayoutTests/fast/dom/geometry-interfaces-dom-matrix.html +++ b/third_party/WebKit/LayoutTests/fast/dom/geometry-interfaces-dom-matrix.html
@@ -120,6 +120,15 @@ "fromFloat64Array function only accepts 1 Float64Array with 6 or 16 elements"); }, "DOMMatrix fromFloat*Array - invalid array size"); +if (window.SharedArrayBuffer) { + test(() => { + assert_throws(new TypeError(), () => { DOMMatrix.fromFloat32Array(new Float32Array(new SharedArrayBuffer(24))); }, + ""); + assert_throws(new TypeError(), () => { DOMMatrix.fromFloat64Array(new Float64Array(new SharedArrayBuffer(32))); }, + ""); + }, "DOMMatrix fromFloat*Array - can't use SharedArrayBuffer view"); +} + test(() => { assert_identity_2d_matrix(DOMMatrix.fromMatrix()); }, "DOMMatrix.fromMatrix() with no parameter");
diff --git a/third_party/WebKit/LayoutTests/fast/encoding/api/sharedarraybuffer.html b/third_party/WebKit/LayoutTests/fast/encoding/api/sharedarraybuffer.html new file mode 100644 index 0000000..161b546 --- /dev/null +++ b/third_party/WebKit/LayoutTests/fast/encoding/api/sharedarraybuffer.html
@@ -0,0 +1,16 @@ +<!DOCTYPE html> +<script src="../../../resources/testharness.js"></script> +<script src="../../../resources/testharnessreport.js"></script> +<script> + +if (window.SharedArrayBuffer) { + test(() => { + const decoder = new TextDecoder('utf-8'); + assert_throws(null, () => { + decoder.decode(new Uint8Array(new SharedArrayBuffer(4))); + }, 'constructing TextDecoder with SharedArrayBuffer view should throw'); + }, 'decoding SharedArrayBuffer'); +} +done(); + +</script>
diff --git a/third_party/WebKit/LayoutTests/fast/events/constructors/midi-message-event-constructor.html b/third_party/WebKit/LayoutTests/fast/events/constructors/midi-message-event-constructor.html index 0631a39..46e2da7 100644 --- a/third_party/WebKit/LayoutTests/fast/events/constructors/midi-message-event-constructor.html +++ b/third_party/WebKit/LayoutTests/fast/events/constructors/midi-message-event-constructor.html
@@ -31,6 +31,11 @@ shouldBe("new MIDIMessageEvent('eventType', { bubbles: true, cancelable: true, data: data }).cancelable", "true"); shouldEvaluateTo("new MIDIMessageEvent('eventType', { bubbles: true, cancelable: true, data: data }).data", data); +if (window.SharedArrayBuffer) { + data = new Uint8Array(new SharedArrayBuffer(3)); + shouldThrow("new MIDIMessageEvent('eventType', { data: data })"); +} + </script> </body> </html>
diff --git a/third_party/WebKit/LayoutTests/fast/files/blob-constructor.html b/third_party/WebKit/LayoutTests/fast/files/blob-constructor.html index 5261d19..df34b9c 100644 --- a/third_party/WebKit/LayoutTests/fast/files/blob-constructor.html +++ b/third_party/WebKit/LayoutTests/fast/files/blob-constructor.html
@@ -123,6 +123,11 @@ shouldBe("new Blob([(new Float64Array(100)).buffer, (new Int32Array(100)).buffer, (new Uint8Array(100)).buffer, (new DataView(new ArrayBuffer(100))).buffer]).size", "1400"); shouldBe("new Blob([new Blob([(new Int32Array(100)).buffer]), (new Uint8Array(100)).buffer, (new Float32Array(100)).buffer, (new DataView(new ArrayBuffer(100))).buffer]).size", "1000"); +if (window.SharedArrayBuffer) { + // Test SharedArrayBuffer parameters. + shouldThrow("new Blob([new Uint8Array(new SharedArrayBuffer(4))])", '"TypeError: Failed to construct \'Blob\': The provided ArrayBufferView value must not be shared."'); +} + // Test passing blob parts in objects with indexed properties. // (This depends on the bindings code handling of sequence<T>) shouldBe("new Blob({length: 0}).size", "0");
diff --git a/third_party/WebKit/LayoutTests/fast/peerconnection/RTCPeerConnection-datachannel.html b/third_party/WebKit/LayoutTests/fast/peerconnection/RTCPeerConnection-datachannel.html index 21e7dc6..260f377 100644 --- a/third_party/WebKit/LayoutTests/fast/peerconnection/RTCPeerConnection-datachannel.html +++ b/third_party/WebKit/LayoutTests/fast/peerconnection/RTCPeerConnection-datachannel.html
@@ -19,6 +19,15 @@ finishJSTest(); } +function dc_onmessage_sharedarraybuffer_view() { + if (window.SharedArrayBuffer) { + shouldThrow("dc.send(new Uint8Array(new SharedArrayBuffer(16)));"); + } + + dc.onclose = dc_onclose; + dc.close(); +} + function dc_onmessage_dataview(e) { testPassed("dc_onmessage_dataview was called"); data = e.data; @@ -27,8 +36,7 @@ shouldBe("array[0]", "1"); shouldBe("array[9]", "10"); - dc.onclose = dc_onclose; - dc.close(); + dc_onmessage_sharedarraybuffer_view(); } function dc_onmessage_arraybuffer(e) {
diff --git a/third_party/WebKit/LayoutTests/fast/xmlhttprequest/xmlhttprequest-send-sharedarraybuffer.html b/third_party/WebKit/LayoutTests/fast/xmlhttprequest/xmlhttprequest-send-sharedarraybuffer.html new file mode 100644 index 0000000..9f02118 --- /dev/null +++ b/third_party/WebKit/LayoutTests/fast/xmlhttprequest/xmlhttprequest-send-sharedarraybuffer.html
@@ -0,0 +1,18 @@ +<!DOCTYPE html> +<script src="../../resources/testharness.js"></script> +<script src="../../resources/testharnessreport.js"></script> +<script> + +if (window.SharedArrayBuffer) { + test(() => { + const xhr = new XMLHttpRequest(); + xhr.open('POST', '/foo.html'); + + assert_throws(null, () => { + xhr.send(new Uint8Array(new SharedArrayBuffer(32))); + }, 'send() of SharedArrayBuffer view should throw'); + }, 'sending SharedArrayBuffer'); +} +done(); + +</script>
diff --git a/third_party/WebKit/LayoutTests/http/tests/inspector/resources-test.js b/third_party/WebKit/LayoutTests/http/tests/inspector/resources-test.js index 43e4d96..2aa4f591 100644 --- a/third_party/WebKit/LayoutTests/http/tests/inspector/resources-test.js +++ b/third_party/WebKit/LayoutTests/http/tests/inspector/resources-test.js
@@ -3,6 +3,11 @@ InspectorTest.preloadPanel("sources"); InspectorTest.preloadPanel("resources"); +InspectorTest.createWebSQLDatabase = function(name) +{ + return InspectorTest.evaluateInPageAsync(`_openWebSQLDatabase("${name}")`); +} + InspectorTest.requestURLComparer = function(r1, r2) { return r1.request.url.localeCompare(r2.request.url); @@ -93,3 +98,8 @@ } } + +function _openWebSQLDatabase(name) +{ + return new Promise(resolve => openDatabase(name, "1.0", "", 1024 * 1024, resolve)); +}
diff --git a/third_party/WebKit/LayoutTests/http/tests/inspector/resources/resources-panel-on-navigation-expected.txt b/third_party/WebKit/LayoutTests/http/tests/inspector/resources/resources-panel-on-navigation-expected.txt new file mode 100644 index 0000000..d81d947 --- /dev/null +++ b/third_party/WebKit/LayoutTests/http/tests/inspector/resources/resources-panel-on-navigation-expected.txt
@@ -0,0 +1,65 @@ +CONSOLE MESSAGE: line 112: InspectorTest.IndexedDB_callback1 +Tests Application Panel response to a main frame navigation. + +Initial state: +Application + Manifest + Service Workers + Clear storage +Storage + Local Storage + http://127.0.0.1:8000 + Session Storage + http://127.0.0.1:8000 + IndexedDB + Database1 - http://127.0.0.1:8000 + Web SQL + database-for-test + Cookies + http://127.0.0.1:8000 +Cache + Cache Storage + Application Cache +Frames + top + Scripts + console-test.js + indexeddb-test.js + inspector-test.js + resources-test.js + resources-panel-on-navigation.html +Visible view is a query view: true +Page reloaded. +After navigation: +Application + Manifest + Service Workers + Clear storage +Storage + Local Storage + http://127.0.0.1:8000 + Session Storage + http://127.0.0.1:8000 + IndexedDB + Database1 - http://127.0.0.1:8000 + Web SQL + Cookies + http://127.0.0.1:8000 +Cache + Cache Storage + Application Cache +Frames + top + Scripts + console-test.js + console-test.js + indexeddb-test.js + indexeddb-test.js + inspector-test.js + inspector-test.js + resources-test.js + resources-test.js + resources-panel-on-navigation.html + resources-panel-on-navigation.html +Visible view is a query view: false +
diff --git a/third_party/WebKit/LayoutTests/http/tests/inspector/resources/resources-panel-on-navigation.html b/third_party/WebKit/LayoutTests/http/tests/inspector/resources/resources-panel-on-navigation.html new file mode 100644 index 0000000..01bcd6af --- /dev/null +++ b/third_party/WebKit/LayoutTests/http/tests/inspector/resources/resources-panel-on-navigation.html
@@ -0,0 +1,58 @@ +<html> +<head> +<script src="../inspector-test.js"></script> +<script src="../resources-test.js"></script> +<script src="../console-test.js"></script> +<script src="../indexeddb/indexeddb-test.js"></script> +<script> + +async function test() +{ + + function createIndexedDB(callback) { + var mainFrameId = InspectorTest.resourceTreeModel.mainFrame.id; + var model = InspectorTest.mainTarget.model(Resources.IndexedDBModel); + InspectorTest.createDatabase(mainFrameId, 'Database1', () => { + var event = model.addEventListener(Resources.IndexedDBModel.Events.DatabaseAdded, () => { + Common.EventTarget.removeEventListeners([event]); + callback(); + }); + model.refreshDatabaseNames(); + }); + } + + function dump(node, prefix) + { + for (var child of node.children()) { + InspectorTest.addResult(prefix + child.listItemElement.textContent); + dump(child, prefix + ' '); + } + } + + function dumpCurrentState(label) { + var view = UI.panels.resources; + InspectorTest.addResult(label); + dump(view._sidebar._sidebarTree.rootElement(), ''); + InspectorTest.addResult('Visible view is a query view: ' + (view.visibleView instanceof Resources.DatabaseQueryView)); + } + + function fireFrameNavigated() { + var rtm = InspectorTest.resourceTreeModel; + rtm.dispatchEventToListeners(SDK.ResourceTreeModel.Events.FrameNavigated, rtm.mainFrame); + } + + await new Promise(createIndexedDB); + await InspectorTest.createWebSQLDatabase('database-for-test'); + UI.viewManager.showView('resources'); + UI.panels.resources._sidebar.databasesListTreeElement.firstChild().select(false, true); + dumpCurrentState('Initial state:'); + await InspectorTest.navigatePromise('http://127.0.0.1:8000/inspector/resources/resources-panel-on-navigation.html'); + dumpCurrentState('After navigation:'); + InspectorTest.completeTest(); +} +</script> +</head> +<body onload="runTest()"> +<p>Tests Application Panel response to a main frame navigation.</p> +</body> +</html>
diff --git a/third_party/WebKit/LayoutTests/http/tests/media/media-source/mediasource-append-buffer.html b/third_party/WebKit/LayoutTests/http/tests/media/media-source/mediasource-append-buffer.html index ce60447..1d25402 100644 --- a/third_party/WebKit/LayoutTests/http/tests/media/media-source/mediasource-append-buffer.html +++ b/third_party/WebKit/LayoutTests/http/tests/media/media-source/mediasource-append-buffer.html
@@ -550,6 +550,22 @@ test.done(); }, 'Test appending null.'); + if (window.SharedArrayBuffer) { + mediasource_test(function(test, mediaElement, mediaSource) + { + var sourceBuffer = mediaSource.addSourceBuffer(MediaSourceUtil.VIDEO_ONLY_TYPE); + + test.expectEvent(sourceBuffer, 'updatestart', 'Append started.'); + test.expectEvent(sourceBuffer, 'update', 'Append success.'); + test.expectEvent(sourceBuffer, 'updateend', 'Append ended.'); + + assert_throws( { name: 'TypeError'} , + function() { sourceBuffer.appendBuffer(new Uint8Array(new SharedArrayBuffer(16))); }, + 'appendBuffer() of SharedArrayBuffer view throws an exception.'); + test.done(); + }, 'Test appending SharedArrayBuffer view.'); + } + mediasource_testafterdataloaded(function(test, mediaElement, mediaSource, segmentInfo, sourceBuffer, mediaData) { mediaSource.removeSourceBuffer(sourceBuffer);
diff --git a/third_party/WebKit/LayoutTests/http/tests/origin_trials/webexposed/imagecapture-origin-trial-interfaces-script-added-expected.txt b/third_party/WebKit/LayoutTests/http/tests/origin_trials/webexposed/imagecapture-origin-trial-interfaces-script-added-expected.txt deleted file mode 100644 index 2ae8be4..0000000 --- a/third_party/WebKit/LayoutTests/http/tests/origin_trials/webexposed/imagecapture-origin-trial-interfaces-script-added-expected.txt +++ /dev/null
@@ -1,5 +0,0 @@ -This is a testharness.js-based test. -FAIL ImageCapture related interfaces before adding trial token via script. assert_equals: Interface ImageCapture exists on provided object expected false but got true -PASS ImageCapture related interfaces after adding trial token via script. -Harness: the test ran to completion. -
diff --git a/third_party/WebKit/LayoutTests/http/tests/origin_trials/webexposed/imagecapture-origin-trial-interfaces-script-added.html b/third_party/WebKit/LayoutTests/http/tests/origin_trials/webexposed/imagecapture-origin-trial-interfaces-script-added.html deleted file mode 100644 index 9c47344..0000000 --- a/third_party/WebKit/LayoutTests/http/tests/origin_trials/webexposed/imagecapture-origin-trial-interfaces-script-added.html +++ /dev/null
@@ -1,23 +0,0 @@ -<!DOCTYPE html> -<meta charset="utf-8"> -<title>ImageCapture - origin trial is enabled by script-added meta tag</title> -<script src="../../resources/testharness.js"></script> -<script src="../../resources/testharnessreport.js"></script> -<script src="../../resources/origin-trials-helper.js"></script> -<script> -// Generate token with the command: -// generate_token.py http://127.0.0.1:8000 ImageCapture --expire-timestamp=2000000000 -var token = "AgnhzY0dhvMKsSPYNWHltCxTsLpVFzM/H0rZdpY4DeVo7ry4xm8VLRJU5aVLy+wSgnUa34pTTR017JFu4qnUAQwAAABUeyJvcmlnaW4iOiAiaHR0cDovLzEyNy4wLjAuMTo4MDAwIiwgImZlYXR1cmUiOiAiSW1hZ2VDYXB0dXJlIiwgImV4cGlyeSI6IDIwMDAwMDAwMDB9"; - -let interfaces_to_check = ['ImageCapture','MediaSettingsRange','PhotoCapabilities']; - -test(t => { - OriginTrialsHelper.check_interfaces_missing(this, interfaces_to_check); -}, "ImageCapture related interfaces before adding trial token via script."); - -OriginTrialsHelper.add_token(token); - -test(t => { - OriginTrialsHelper.check_interfaces(this, interfaces_to_check); -}, "ImageCapture related interfaces after adding trial token via script."); -</script>
diff --git a/third_party/WebKit/LayoutTests/http/tests/origin_trials/webexposed/imagecapture-origin-trial-interfaces.html b/third_party/WebKit/LayoutTests/http/tests/origin_trials/webexposed/imagecapture-origin-trial-interfaces.html deleted file mode 100644 index dad2b4d..0000000 --- a/third_party/WebKit/LayoutTests/http/tests/origin_trials/webexposed/imagecapture-origin-trial-interfaces.html +++ /dev/null
@@ -1,18 +0,0 @@ -<!DOCTYPE html> -<meta charset="utf-8"> -<!-- Generate token with the command: -generate_token.py http://127.0.0.1:8000 ImageCapture --expire-timestamp=2000000000 ---> -<meta http-equiv="origin-trial" content="AgnhzY0dhvMKsSPYNWHltCxTsLpVFzM/H0rZdpY4DeVo7ry4xm8VLRJU5aVLy+wSgnUa34pTTR017JFu4qnUAQwAAABUeyJvcmlnaW4iOiAiaHR0cDovLzEyNy4wLjAuMTo4MDAwIiwgImZlYXR1cmUiOiAiSW1hZ2VDYXB0dXJlIiwgImV4cGlyeSI6IDIwMDAwMDAwMDB9" /> -<title>ImageCapture - interfaces exposed by origin trial</title> -<script src="../../resources/testharness.js"></script> -<script src="../../resources/testharnessreport.js"></script> -<script src="../../resources/origin-trials-helper.js"></script> -<script> -test(t => { - OriginTrialsHelper.check_interfaces(this, - ['ImageCapture', - 'MediaSettingsRange', - 'PhotoCapabilities']); -}, "ImageCapture related interfaces in Origin-Trial enabled document."); -</script>
diff --git a/third_party/WebKit/LayoutTests/http/tests/push_messaging/resources/pushmessagedata-worker.js b/third_party/WebKit/LayoutTests/http/tests/push_messaging/resources/pushmessagedata-worker.js index 36fa4437..6b9a49f 100644 --- a/third_party/WebKit/LayoutTests/http/tests/push_messaging/resources/pushmessagedata-worker.js +++ b/third_party/WebKit/LayoutTests/http/tests/push_messaging/resources/pushmessagedata-worker.js
@@ -108,3 +108,11 @@ assert_equals(data.text(), s, 'String should not be NFC-normalized.'); }, 'PushEventInit data is not normalized'); + +if (self.SharedArrayBuffer) { + test(function() { + assert_throws(null, () => { + createPushMessageData(new Uint8Array(new SharedArrayBuffer(16))); + }); + }, 'PushMessageData throws when passed SharedArrayBuffer view.'); +}
diff --git a/third_party/WebKit/LayoutTests/http/tests/websocket/send-arraybufferview.html b/third_party/WebKit/LayoutTests/http/tests/websocket/send-arraybufferview.html index b85476f8f..a25a2468 100644 --- a/third_party/WebKit/LayoutTests/http/tests/websocket/send-arraybufferview.html +++ b/third_party/WebKit/LayoutTests/http/tests/websocket/send-arraybufferview.html
@@ -40,6 +40,11 @@ return array; } +function createSharedArrayBufferView() +{ + return new Uint8Array(new SharedArrayBuffer(16)); +} + var url = "ws://127.0.0.1:8880/check-binary-messages"; var ws = new WebSocket(url); var closeEvent; @@ -49,6 +54,10 @@ ws.send(createArrayBufferViewContainingHelloWorld()); ws.send(createEmptyArrayBufferView()); ws.send(createArrayBufferViewContainingAllDistinctBytes()); + + if (window.SharedArrayBuffer) { + shouldThrow("ws.send(createSharedArrayBufferView())"); + } }; ws.onmessage = function(event)
diff --git a/third_party/WebKit/LayoutTests/inspector/coverage/coverage-test.js b/third_party/WebKit/LayoutTests/inspector/coverage/coverage-test.js index 73fa5ba..1277fe3b 100644 --- a/third_party/WebKit/LayoutTests/inspector/coverage/coverage-test.js +++ b/third_party/WebKit/LayoutTests/inspector/coverage/coverage-test.js
@@ -30,6 +30,17 @@ InspectorTest.dumpDecorationsInSourceFrame(sourceFrame); } +InspectorTest.findCoverageNodeForURL = function(url) +{ + var coverageListView = self.runtime.sharedInstance(Coverage.CoverageView)._listView; + var rootNode = coverageListView._dataGrid.rootNode(); + for (var child of rootNode.children) { + if (child._coverageInfo.url().endsWith(url)) + return child; + } + return null; +} + InspectorTest.dumpDecorationsInSourceFrame = function(sourceFrame) { var markerMap = new Map([['used', '+'], ['unused', '-'], ['mixed', '*']]);
diff --git a/third_party/WebKit/LayoutTests/inspector/coverage/resources/long-mangled.css b/third_party/WebKit/LayoutTests/inspector/coverage/resources/long-mangled.css new file mode 100644 index 0000000..5029ca9 --- /dev/null +++ b/third_party/WebKit/LayoutTests/inspector/coverage/resources/long-mangled.css
@@ -0,0 +1 @@ +.this-line-needs-to-be-longer-than-five-hundred-symbols {} body { background-color: lightblue; } .class { color: red; } .class2 { color:green;font-style: italic; } #id { color: blue } notUsed {color: black} notUsed2 { color: white} #this-line-needs-to-be-longer-than-five-hundred-symbols.this-line-needs-to-be-longer-than-five-hundred-symbols { content: "words don\'t come easy to me, how can I find a way to make a longer line"; color: lightgoldenrodyellow; background-color: lightgoldenrodyellow; border-color: lightgoldenrodyellow; }
diff --git a/third_party/WebKit/LayoutTests/inspector/coverage/reveal-autoformat-expected.txt b/third_party/WebKit/LayoutTests/inspector/coverage/reveal-autoformat-expected.txt new file mode 100644 index 0000000..dc0dfc3a --- /dev/null +++ b/third_party/WebKit/LayoutTests/inspector/coverage/reveal-autoformat-expected.txt
@@ -0,0 +1,62 @@ +PASS + +Tests the CSS highlight in sources after the Pretty print formatting. + +The below should be formatted +0: - .this-line-needs-to-be-longer-than-five-hundred-symbols { +1: - } +2: - +3: * body { +4: + background-color: lightblue; +5: * } +6: - +7: - .class { +8: - color: red; +9: - } +10: - +11: - .class2 { +12: - color: green; +13: - font-style: italic; +14: - } +15: - +16: * #id { +17: + color: blue +18: * } +19: - +20: - notUsed { +21: - color: black +22: - } +23: - +24: - notUsed2 { +25: - color: white +26: - } +27: - +28: - #this-line-needs-to-be-longer-than-five-hundred-symbols.this-line-needs-to-be-longer-than-five-hundred-symbols { +29: - content: "words don\'t come easy to me, how can I find a way to make a longer line"; +30: - color: lightgoldenrodyellow; +31: - background-color: lightgoldenrodyellow; +32: - border-color: lightgoldenrodyellow; +33: - } +34: - +The below should NOT be formatted +0: + body { +1: + background-color: lightblue; +2: * } +3: - +4: - .class { +5: - color: red; +6: - } +7: - +8: - .class2 { color:green;font-style: italic; +9: - } +10: - +11: * #id { color: blue +12: * } +13: - +14: - notUsed {color: black} +15: - +16: - notUsed2 { +17: - color: white +18: - } +19: - +
diff --git a/third_party/WebKit/LayoutTests/inspector/coverage/reveal-autoformat.html b/third_party/WebKit/LayoutTests/inspector/coverage/reveal-autoformat.html new file mode 100644 index 0000000..0d1ee9e9 --- /dev/null +++ b/third_party/WebKit/LayoutTests/inspector/coverage/reveal-autoformat.html
@@ -0,0 +1,41 @@ +<html> +<head> +<script src="../../http/tests/inspector/inspector-test.js"></script> +<script src="../../http/tests/inspector/debugger-test.js"></script> +<script src="../../http/tests/inspector/sources-test.js"></script> +<script src="coverage-test.js"></script> + +<link rel="stylesheet" type="text/css" href="resources/decorations-after-inplace-formatter.css"> +<link rel="stylesheet" type="text/css" href="resources/long-mangled.css"> + +<script> +async function test() +{ + InspectorTest.startCoverage(); + await InspectorTest.evaluateInPagePromise("performActions()"); + await InspectorTest.stopCoverage(); + var node = InspectorTest.findCoverageNodeForURL("long-mangled.css"); + var coverageListView = self.runtime.sharedInstance(Coverage.CoverageView)._listView; + var decoratePromise = InspectorTest.addSnifferPromise(Coverage.CoverageView.LineDecorator.prototype, "decorate"); + coverageListView._revealSourceForNode(node); + await decoratePromise; + InspectorTest.addResult("The below should be formatted"); + InspectorTest.dumpDecorationsInSourceFrame(UI.panels.sources.visibleView); + + + node = InspectorTest.findCoverageNodeForURL("decorations-after-inplace-formatter.css"); + decoratePromise = InspectorTest.addSnifferPromise(Coverage.CoverageView.LineDecorator.prototype, "decorate"); + coverageListView._revealSourceForNode(node); + await decoratePromise; + InspectorTest.addResult("The below should NOT be formatted"); + InspectorTest.dumpDecorationsInSourceFrame(UI.panels.sources.visibleView); + + InspectorTest.completeTest(); +} +</script> +</head> +<p id="id">PASS</p> +<body onload="runTest()"> +<p>Tests the CSS highlight in sources after the Pretty print formatting.</p> +</body> +</html> \ No newline at end of file
diff --git a/third_party/WebKit/LayoutTests/inspector/sources/formatter-css-expected.txt b/third_party/WebKit/LayoutTests/inspector/sources/formatter-css-expected.txt new file mode 100644 index 0000000..7862ad01 --- /dev/null +++ b/third_party/WebKit/LayoutTests/inspector/sources/formatter-css-expected.txt
@@ -0,0 +1,34 @@ +Tests how SourceFormatter handles CSS sources + +Formatted: +@media screen { + html { + color: green; + foo-property: bar-value + } +} +} + +body { + background-color: black; +} + +Location mapping with formatted source: +Mapped locations: +0:15 -> 0:14 +0:22 -> 1:9 +0:65 -> 8:5 +Live locations (updated: 3): +0:14 +1:9 +8:5 +Location mapping without formatted source: +Mapped locations: +0:15 -> 0:15 +0:22 -> 0:22 +0:65 -> 0:65 +Live locations (updated: 6): +0:15 +0:22 +0:65 +
diff --git a/third_party/WebKit/LayoutTests/inspector/sources/formatter-css.html b/third_party/WebKit/LayoutTests/inspector/sources/formatter-css.html new file mode 100644 index 0000000..bf81aa10 --- /dev/null +++ b/third_party/WebKit/LayoutTests/inspector/sources/formatter-css.html
@@ -0,0 +1,59 @@ +<html> +<head> +<script src="../../http/tests/inspector/inspector-test.js"></script> +<script src="../../http/tests/inspector/debugger-test.js"></script> +<link rel="stylesheet" href="resources/style-formatter-obfuscated.css"> + +<script> +async function test() +{ + var uiSourceCode = await InspectorTest.waitForUISourceCode("style-formatter-obfuscated.css"); + var formatData = await Sources.sourceFormatter.format(uiSourceCode); + var targetContent = await formatData.formattedSourceCode.requestContent(); + + InspectorTest.addResult(`Formatted:\n${targetContent}`); + + var originalContent = await uiSourceCode.requestContent(); + var styleHeader = Bindings.NetworkProject.styleHeaderForUISourceCode(uiSourceCode); + var text = new TextUtils.Text(originalContent); + var liveLocationsPool = new Bindings.LiveLocationPool(); + var locationUpdateCount = 0; + var rawLocations = []; + var liveLocations = []; + for (var offset = originalContent.indexOf("{"); offset >= 0; offset = originalContent.indexOf("{", offset + 1)) { + var position = text.positionFromOffset(offset); + var rawLocation = new SDK.CSSLocation(styleHeader, position.lineNumber, position.columnNumber); + rawLocations.push(rawLocation); + liveLocations.push(Bindings.cssWorkspaceBinding.createLiveLocation(rawLocation, () => { locationUpdateCount++; }, liveLocationsPool)); + } + + InspectorTest.addResult("Location mapping with formatted source:"); + dumpLocations(); + + Sources.sourceFormatter.discardFormattedUISourceCode(formatData.formattedSourceCode); + + InspectorTest.addResult("Location mapping without formatted source:"); + dumpLocations(); + + InspectorTest.completeTest(); + + function dumpLocations() { + InspectorTest.addResult("Mapped locations:"); + for (var rawLocation of rawLocations) { + var uiLocation = Bindings.cssWorkspaceBinding.rawLocationToUILocation(rawLocation); + InspectorTest.addResult(`${rawLocation.lineNumber}:${rawLocation.columnNumber} -> ${uiLocation.lineNumber}:${uiLocation.columnNumber}`); + } + InspectorTest.addResult(`Live locations (updated: ${locationUpdateCount}):`); + for (var liveLocation of liveLocations) { + var uiLocation = liveLocation.uiLocation(); + InspectorTest.addResult(`${uiLocation.lineNumber}:${uiLocation.columnNumber}`); + } + } +} +</script> + +</head> +<body onload="runTest()"> +<p>Tests how SourceFormatter handles CSS sources</p> +</body> +</html>
diff --git a/third_party/WebKit/LayoutTests/inspector/sources/formatter-js-expected.txt b/third_party/WebKit/LayoutTests/inspector/sources/formatter-js-expected.txt new file mode 100644 index 0000000..be61ee0 --- /dev/null +++ b/third_party/WebKit/LayoutTests/inspector/sources/formatter-js-expected.txt
@@ -0,0 +1,101 @@ +Tests how SourceFormatter handles JS sources + +Formatted: +function formatted1() { + var variable1 = 0; +} + +function withComments() { + // comment + return "functionWithComments"; +} + +try { + onmessage = function(event) { + var source = event.data; + var formattedSource = beautify(source); + var mapping = buildMapping(source, formattedSource); + postMessage({ + formattedSource: formattedSource, + mapping: mapping + }) + } + ; + function beautify(source) { + var ast = parse.parse(source); + var beautifyOptions = { + indent_level: 4, + indent_start: 0, + quote_keys: false, + space_colon: false + }; + return process.gen_code(ast, beautifyOptions) + } + function buildMapping(source, formattedSource) { + var mapping = { + original: [], + formatted: [] + }; + var lastPosition = 0; + var regexp = /(^|[^\\])\b((?=\D)[\$\.\w]+)\b/g; + while (true) { + var match = regexp.exec(formattedSource); + if (!match) + break; + var position = source.indexOf(match[2], lastPosition); + if (position === -1) + throw "No match found in original source for " + match[2]; + mapping.original.push(position); + mapping.formatted.push(match.index + match[1].length); + lastPosition = position + match[2].length + } + return mapping + } + function require() { + return parse + } + var exports = {}; + importScripts("UglifyJS/parse-js.js"); + var parse = exports; + var exports = {}; + importScripts("UglifyJS/process.js"); + var process = exports; +} catch (e) {} + +function formatted2() { + var variable2 = 0; +} + +Location mapping with formatted source: +1:0 -> 0:22 +6:0 -> 4:24 +11:3 -> 9:4 +11:29 -> 10:32 +11:150 -> 14:20 +11:227 -> 20:30 +12:0 -> 22:30 +12:157 -> 30:51 +12:170 -> 31:22 +13:0 -> 37:21 +14:71 -> 50:23 +14:97 -> 53:18 +14:168 -> 56:18 +14:237 -> 59:12 +17:0 -> 61:22 +Location mapping without formatted source: +1:0 -> 1:0 +6:0 -> 6:0 +11:3 -> 11:3 +11:29 -> 11:29 +11:150 -> 11:150 +11:227 -> 11:227 +12:0 -> 12:0 +12:157 -> 12:157 +12:170 -> 12:170 +13:0 -> 13:0 +14:71 -> 14:71 +14:97 -> 14:97 +14:168 -> 14:168 +14:237 -> 14:237 +17:0 -> 17:0 +
diff --git a/third_party/WebKit/LayoutTests/inspector/sources/formatter-js.html b/third_party/WebKit/LayoutTests/inspector/sources/formatter-js.html new file mode 100644 index 0000000..8f22c08 --- /dev/null +++ b/third_party/WebKit/LayoutTests/inspector/sources/formatter-js.html
@@ -0,0 +1,47 @@ +<html> +<head> +<script src="../../http/tests/inspector/inspector-test.js"></script> +<script src="../../http/tests/inspector/debugger-test.js"></script> +<script src="debugger/resources/obfuscated.js"></script> + +<script> +async function test() +{ + var uiSourceCode = await InspectorTest.waitForUISourceCode("obfuscated.js"); + var formatData = await Sources.sourceFormatter.format(uiSourceCode); + var targetContent = await formatData.formattedSourceCode.requestContent(); + + InspectorTest.addResult(`Formatted:\n${targetContent}`); + + var originalContent = await uiSourceCode.requestContent(); + var text = new TextUtils.Text(originalContent); + var positions = []; + for (var offset = originalContent.indexOf("{"); offset >= 0; offset = originalContent.indexOf("{", offset + 1)) + positions.push(text.positionFromOffset(offset)); + var script = Bindings.debuggerWorkspaceBinding.uiLocationToRawLocation(uiSourceCode, 0, 0).script(); + + InspectorTest.addResult("Location mapping with formatted source:"); + dumpLocations(positions); + + Sources.sourceFormatter.discardFormattedUISourceCode(formatData.formattedSourceCode); + + InspectorTest.addResult("Location mapping without formatted source:"); + dumpLocations(positions); + + InspectorTest.completeTest(); + + function dumpLocations(positions) { + for (var position of positions) { + var rawLocation = InspectorTest.debuggerModel.createRawLocation(script, position.lineNumber, position.columnNumber); + var uiLocation = Bindings.debuggerWorkspaceBinding.rawLocationToUILocation(rawLocation); + InspectorTest.addResult(`${rawLocation.lineNumber}:${rawLocation.columnNumber} -> ${uiLocation.lineNumber}:${uiLocation.columnNumber}`); + } + } +} +</script> + +</head> +<body onload="runTest()"> +<p>Tests how SourceFormatter handles JS sources</p> +</body> +</html>
diff --git a/third_party/WebKit/LayoutTests/paint/invalidation/svg/feImage-target-attribute-change-with-use-indirection-2-expected.txt b/third_party/WebKit/LayoutTests/paint/invalidation/svg/feImage-target-attribute-change-with-use-indirection-2-expected.txt index 008556b..15896343 100644 --- a/third_party/WebKit/LayoutTests/paint/invalidation/svg/feImage-target-attribute-change-with-use-indirection-2-expected.txt +++ b/third_party/WebKit/LayoutTests/paint/invalidation/svg/feImage-target-attribute-change-with-use-indirection-2-expected.txt
@@ -20,6 +20,10 @@ "reason": "full" }, { + "object": "LayoutSVGRect rect id='rect'", + "reason": "bounds change" + }, + { "object": "LayoutSVGResourceFilterPrimitive feImage id='feimage'", "reason": "full" },
diff --git a/third_party/WebKit/LayoutTests/paint/invalidation/svg/marker-viewBox-changes-expected.txt b/third_party/WebKit/LayoutTests/paint/invalidation/svg/marker-viewBox-changes-expected.txt index e98bff5..d838dcf 100644 --- a/third_party/WebKit/LayoutTests/paint/invalidation/svg/marker-viewBox-changes-expected.txt +++ b/third_party/WebKit/LayoutTests/paint/invalidation/svg/marker-viewBox-changes-expected.txt
@@ -25,6 +25,10 @@ "reason": "full" }, { + "object": "LayoutSVGRect rect", + "reason": "bounds change" + }, + { "object": "LayoutSVGContainer g", "reason": "bounds change" },
diff --git a/third_party/WebKit/LayoutTests/paint/transparency/compositing-alpha-fold-crash-expected.png b/third_party/WebKit/LayoutTests/paint/transparency/compositing-alpha-fold-crash-expected.png new file mode 100644 index 0000000..f9f0ec5c --- /dev/null +++ b/third_party/WebKit/LayoutTests/paint/transparency/compositing-alpha-fold-crash-expected.png Binary files differ
diff --git a/third_party/WebKit/LayoutTests/paint/transparency/compositing-alpha-fold-crash-expected.txt b/third_party/WebKit/LayoutTests/paint/transparency/compositing-alpha-fold-crash-expected.txt new file mode 100644 index 0000000..a2c72a81 --- /dev/null +++ b/third_party/WebKit/LayoutTests/paint/transparency/compositing-alpha-fold-crash-expected.txt
@@ -0,0 +1,12 @@ +layer at (0,0) size 800x600 + LayoutView at (0,0) size 800x600 +layer at (0,0) size 800x17 + LayoutBlockFlow {HTML} at (0,0) size 800x17 +layer at (8,8) size 784x1 transparent + LayoutBlockFlow {BODY} at (8,8) size 784x1 +layer at (8,8) size 784x0 transparent + LayoutBlockFlow {DIV} at (0,0) size 784x0 +layer at (8,8) size 784x1 + LayoutBlockFlow {DIV} at (0,0) size 784x1 +layer at (8,9) size 784x0 + LayoutBlockFlow {DIV} at (0,1) size 784x0
diff --git a/third_party/WebKit/LayoutTests/paint/transparency/compositing-alpha-fold-crash.html b/third_party/WebKit/LayoutTests/paint/transparency/compositing-alpha-fold-crash.html new file mode 100644 index 0000000..7aae271 --- /dev/null +++ b/third_party/WebKit/LayoutTests/paint/transparency/compositing-alpha-fold-crash.html
@@ -0,0 +1,8 @@ +<!doctype HTML> +<!-- Test passes if it does not crash. --> + <body style="opacity:0.5"> +<div style=" -webkit-mask-box-image-source: url();" > +</div> +<div style="box-shadow: 1px 1px black; -webkit-padding-before: 1px; isolation: isolate"> +<div style="isolation: isolate"></div> +</body>
diff --git a/third_party/WebKit/LayoutTests/platform/mac/virtual/stable/webexposed/global-interface-listing-expected.txt b/third_party/WebKit/LayoutTests/platform/mac/virtual/stable/webexposed/global-interface-listing-expected.txt index 208513a..b0313705 100644 --- a/third_party/WebKit/LayoutTests/platform/mac/virtual/stable/webexposed/global-interface-listing-expected.txt +++ b/third_party/WebKit/LayoutTests/platform/mac/virtual/stable/webexposed/global-interface-listing-expected.txt
@@ -3135,6 +3135,14 @@ getter canvas method constructor method transferFromImageBitmap +interface ImageCapture + attribute @@toStringTag + getter track + method constructor + method getPhotoCapabilities + method grabFrame + method setOptions + method takePhoto interface ImageData attribute @@toStringTag getter data @@ -3376,6 +3384,12 @@ setter onresume setter onstart setter onstop +interface MediaSettingsRange + attribute @@toStringTag + getter max + getter min + getter step + method constructor interface MediaSource : EventTarget static method isTypeSupported attribute @@toStringTag @@ -3437,8 +3451,10 @@ getter onmute getter onunmute getter readyState + method applyConstraints method clone method constructor + method getCapabilities method getConstraints method getSettings method stop @@ -3940,6 +3956,13 @@ attribute @@toStringTag method constructor method query +interface PhotoCapabilities + attribute @@toStringTag + getter fillLightMode + getter imageHeight + getter imageWidth + getter redEyeReduction + method constructor interface Plugin attribute @@toStringTag getter description
diff --git a/third_party/WebKit/LayoutTests/platform/win/virtual/stable/webexposed/global-interface-listing-expected.txt b/third_party/WebKit/LayoutTests/platform/win/virtual/stable/webexposed/global-interface-listing-expected.txt index d35a263..5160b0d 100644 --- a/third_party/WebKit/LayoutTests/platform/win/virtual/stable/webexposed/global-interface-listing-expected.txt +++ b/third_party/WebKit/LayoutTests/platform/win/virtual/stable/webexposed/global-interface-listing-expected.txt
@@ -3064,6 +3064,14 @@ getter canvas method constructor method transferFromImageBitmap +interface ImageCapture + attribute @@toStringTag + getter track + method constructor + method getPhotoCapabilities + method grabFrame + method setOptions + method takePhoto interface ImageData attribute @@toStringTag getter data @@ -3305,6 +3313,12 @@ setter onresume setter onstart setter onstop +interface MediaSettingsRange + attribute @@toStringTag + getter max + getter min + getter step + method constructor interface MediaSource : EventTarget static method isTypeSupported attribute @@toStringTag @@ -3366,8 +3380,10 @@ getter onmute getter onunmute getter readyState + method applyConstraints method clone method constructor + method getCapabilities method getConstraints method getSettings method stop @@ -3868,6 +3884,13 @@ attribute @@toStringTag method constructor method query +interface PhotoCapabilities + attribute @@toStringTag + getter fillLightMode + getter imageHeight + getter imageWidth + getter redEyeReduction + method constructor interface Plugin attribute @@toStringTag getter description
diff --git a/third_party/WebKit/LayoutTests/plugins/focus-change-2-change-focus-expected.txt b/third_party/WebKit/LayoutTests/plugins/focus-change-2-change-focus-expected.txt index 2d12191..84b7166 100644 --- a/third_party/WebKit/LayoutTests/plugins/focus-change-2-change-focus-expected.txt +++ b/third_party/WebKit/LayoutTests/plugins/focus-change-2-change-focus-expected.txt
@@ -1,4 +1,6 @@ CONSOLE MESSAGE: Blink Test Plugin: initializing +CONSOLE MESSAGE: Blink Test Plugin: DidChangeFocus(true) +CONSOLE MESSAGE: Blink Test Plugin: DidChangeFocus(false) i1focus i1blur pfocus-change-2
diff --git a/third_party/WebKit/LayoutTests/plugins/focus-change-4-change-focus-and-blur-expected.txt b/third_party/WebKit/LayoutTests/plugins/focus-change-4-change-focus-and-blur-expected.txt index 8c0f22a..1675894 100644 --- a/third_party/WebKit/LayoutTests/plugins/focus-change-4-change-focus-and-blur-expected.txt +++ b/third_party/WebKit/LayoutTests/plugins/focus-change-4-change-focus-and-blur-expected.txt
@@ -1,4 +1,6 @@ CONSOLE MESSAGE: Blink Test Plugin: initializing +CONSOLE MESSAGE: Blink Test Plugin: DidChangeFocus(true) +CONSOLE MESSAGE: Blink Test Plugin: DidChangeFocus(false) i1focus i1blur pfocus-change-2
diff --git a/third_party/WebKit/LayoutTests/sensor/absolute-orientation-sensor.html b/third_party/WebKit/LayoutTests/sensor/absolute-orientation-sensor.html index 8e563b65..f05c52a 100644 --- a/third_party/WebKit/LayoutTests/sensor/absolute-orientation-sensor.html +++ b/third_party/WebKit/LayoutTests/sensor/absolute-orientation-sensor.html
@@ -48,6 +48,11 @@ // Throws if no orientation data available. assert_throws({ name: 'NotReadableError' }, () => sensorObject.populateMatrix(new Float32Array(16))); + if (window.SharedArrayBuffer) { + // Throws if passed SharedArrayBuffer view. + assert_throws({ name: 'TypeError' }, () => sensorObject.populateMatrix(new Float32Array(new SharedArrayBuffer(16)))); + } + sensorObject.start(); return sensor.mockSensorProvider.getCreatedSensor()
diff --git a/third_party/WebKit/LayoutTests/virtual/origin-trials-runtimeflags-disabled/http/tests/origin_trials/webexposed/imagecapture-origin-trial-interfaces-script-added-expected.txt b/third_party/WebKit/LayoutTests/virtual/origin-trials-runtimeflags-disabled/http/tests/origin_trials/webexposed/imagecapture-origin-trial-interfaces-script-added-expected.txt deleted file mode 100644 index ae75c20..0000000 --- a/third_party/WebKit/LayoutTests/virtual/origin-trials-runtimeflags-disabled/http/tests/origin_trials/webexposed/imagecapture-origin-trial-interfaces-script-added-expected.txt +++ /dev/null
@@ -1,5 +0,0 @@ -This is a testharness.js-based test. -PASS ImageCapture related interfaces before adding trial token via script. -PASS ImageCapture related interfaces after adding trial token via script. -Harness: the test ran to completion. -
diff --git a/third_party/WebKit/LayoutTests/virtual/sharedarraybuffer/crypto/README.txt b/third_party/WebKit/LayoutTests/virtual/sharedarraybuffer/crypto/README.txt new file mode 100644 index 0000000..51001f0f --- /dev/null +++ b/third_party/WebKit/LayoutTests/virtual/sharedarraybuffer/crypto/README.txt
@@ -0,0 +1,3 @@ +# This suite runs the tests in with --js-flags=--harmony-sharedarraybuffer +# This enables the SharedArrayBuffer language feature in V8. +# See https://github.com/tc39/ecmascript_sharedmem for more information.
diff --git a/third_party/WebKit/LayoutTests/virtual/sharedarraybuffer/crypto/random-values-expected.txt b/third_party/WebKit/LayoutTests/virtual/sharedarraybuffer/crypto/random-values-expected.txt new file mode 100644 index 0000000..1334f1f --- /dev/null +++ b/third_party/WebKit/LayoutTests/virtual/sharedarraybuffer/crypto/random-values-expected.txt
@@ -0,0 +1,14 @@ +Tests crypto.randomValues. + +On success, you will see a series of "PASS" messages, followed by "TEST COMPLETE". + + +PASS 'crypto' in self is true +PASS 'getRandomValues' in self.crypto is true +PASS self.crypto.__proto__.hasOwnProperty('getRandomValues') is true +PASS matchingBytes < 100 is true +PASS crypto.getRandomValues(new Uint8Array(new SharedArrayBuffer(100))) threw exception TypeError: Failed to execute 'getRandomValues' on 'Crypto': The provided ArrayBufferView value must not be shared.. +PASS successfullyParsed is true + +TEST COMPLETE +
diff --git a/third_party/WebKit/LayoutTests/virtual/sharedarraybuffer/crypto/subtle/importKey-badParameters-expected.txt b/third_party/WebKit/LayoutTests/virtual/sharedarraybuffer/crypto/subtle/importKey-badParameters-expected.txt new file mode 100644 index 0000000..f3e09a7 --- /dev/null +++ b/third_party/WebKit/LayoutTests/virtual/sharedarraybuffer/crypto/subtle/importKey-badParameters-expected.txt
@@ -0,0 +1,18 @@ +Tests calling cypto.subtle.importKey with bad parameters + +On success, you will see a series of "PASS" messages, followed by "TEST COMPLETE". + + +error is: TypeError: Key data must be a BufferSource for non-JWK formats +error is: TypeError: Key data must be a BufferSource for non-JWK formats +error is: TypeError: Algorithm: Not an object +error is: TypeError: Invalid keyFormat argument +error is: TypeError: Invalid keyUsages argument +error is: TypeError: Invalid keyFormat argument +error is: TypeError: HmacImportParams: hash: Missing or not an AlgorithmIdentifier +error is: NotSupportedError: SHA-1: Unsupported operation: importKey +error is: TypeError: Failed to execute 'importKey' on 'SubtleCrypto': The provided ArrayBufferView value must not be shared. +PASS successfullyParsed is true + +TEST COMPLETE +
diff --git a/third_party/WebKit/LayoutTests/virtual/sharedarraybuffer/crypto/worker-random-values-expected.txt b/third_party/WebKit/LayoutTests/virtual/sharedarraybuffer/crypto/worker-random-values-expected.txt new file mode 100644 index 0000000..47f33e1 --- /dev/null +++ b/third_party/WebKit/LayoutTests/virtual/sharedarraybuffer/crypto/worker-random-values-expected.txt
@@ -0,0 +1,15 @@ +[Worker] Tests crypto.randomValues. + +On success, you will see a series of "PASS" messages, followed by "TEST COMPLETE". + + +Starting worker: random-values.js +PASS [Worker] 'crypto' in self is true +PASS [Worker] 'getRandomValues' in self.crypto is true +PASS [Worker] self.crypto.__proto__.hasOwnProperty('getRandomValues') is true +PASS [Worker] matchingBytes < 100 is true +PASS [Worker] crypto.getRandomValues(new Uint8Array(new SharedArrayBuffer(100))) threw exception TypeError: Failed to execute 'getRandomValues' on 'Crypto': The provided ArrayBufferView value must not be shared.. +PASS successfullyParsed is true + +TEST COMPLETE +
diff --git a/third_party/WebKit/LayoutTests/virtual/sharedarraybuffer/fast/beacon/README.txt b/third_party/WebKit/LayoutTests/virtual/sharedarraybuffer/fast/beacon/README.txt new file mode 100644 index 0000000..de49eb0 --- /dev/null +++ b/third_party/WebKit/LayoutTests/virtual/sharedarraybuffer/fast/beacon/README.txt
@@ -0,0 +1,3 @@ +# This suite runs the tests in --js-flags=--harmony-sharedarraybuffer +# This enables the SharedArrayBuffer language feature in V8. +# See https://github.com/tc39/ecmascript_sharedmem for more information.
diff --git a/third_party/WebKit/LayoutTests/virtual/sharedarraybuffer/fast/beacon/beacon-basic-expected.txt b/third_party/WebKit/LayoutTests/virtual/sharedarraybuffer/fast/beacon/beacon-basic-expected.txt new file mode 100644 index 0000000..4353a79b --- /dev/null +++ b/third_party/WebKit/LayoutTests/virtual/sharedarraybuffer/fast/beacon/beacon-basic-expected.txt
@@ -0,0 +1,15 @@ +Exercising the Beacon API + +On success, you will see a series of "PASS" messages, followed by "TEST COMPLETE". + + +PASS Object.getPrototypeOf(navigator).hasOwnProperty('sendBeacon') is true +PASS typeof navigator.sendBeacon is "function" +PASS navigator.sendBeacon() threw exception TypeError: Failed to execute 'sendBeacon' on 'Navigator': 1 argument required, but only 0 present.. +PASS navigator.sendBeacon('http:') threw exception SyntaxError: Failed to execute 'sendBeacon' on 'Navigator': The URL argument is ill-formed or unsupported.. +PASS navigator.sendBeacon('javascript:alert(1);') threw exception SyntaxError: Failed to execute 'sendBeacon' on 'Navigator': Beacons are only supported over HTTP(S).. +PASS navigator.sendBeacon('https:', new Uint8Array(new SharedArrayBuffer(10))) threw exception TypeError: Failed to execute 'sendBeacon' on 'Navigator': The provided ArrayBufferView value must not be shared.. +PASS successfullyParsed is true + +TEST COMPLETE +
diff --git a/third_party/WebKit/LayoutTests/virtual/sharedarraybuffer/fast/canvas/README.txt b/third_party/WebKit/LayoutTests/virtual/sharedarraybuffer/fast/canvas/README.txt new file mode 100644 index 0000000..de49eb0 --- /dev/null +++ b/third_party/WebKit/LayoutTests/virtual/sharedarraybuffer/fast/canvas/README.txt
@@ -0,0 +1,3 @@ +# This suite runs the tests in --js-flags=--harmony-sharedarraybuffer +# This enables the SharedArrayBuffer language feature in V8. +# See https://github.com/tc39/ecmascript_sharedmem for more information.
diff --git a/third_party/WebKit/LayoutTests/virtual/sharedarraybuffer/fast/canvas/canvas-lost-gpu-context-expected.txt b/third_party/WebKit/LayoutTests/virtual/sharedarraybuffer/fast/canvas/canvas-lost-gpu-context-expected.txt new file mode 100644 index 0000000..83502ff --- /dev/null +++ b/third_party/WebKit/LayoutTests/virtual/sharedarraybuffer/fast/canvas/canvas-lost-gpu-context-expected.txt
@@ -0,0 +1,13 @@ +Test the behavior of canvas recovery after a gpu context loss + +On success, you will see a series of "PASS" messages, followed by "TEST COMPLETE". + + +PASS contextLostTest is false +PASS ctx.isContextLost() is false +PASS ctx.isContextLost() is false +Aborting test: Graphics context loss did not destroy canvas contents. This is expected if canvas is not accelerated. +PASS successfullyParsed is true + +TEST COMPLETE +
diff --git a/third_party/WebKit/LayoutTests/virtual/sharedarraybuffer/fast/css/README.txt b/third_party/WebKit/LayoutTests/virtual/sharedarraybuffer/fast/css/README.txt new file mode 100644 index 0000000..de49eb0 --- /dev/null +++ b/third_party/WebKit/LayoutTests/virtual/sharedarraybuffer/fast/css/README.txt
@@ -0,0 +1,3 @@ +# This suite runs the tests in --js-flags=--harmony-sharedarraybuffer +# This enables the SharedArrayBuffer language feature in V8. +# See https://github.com/tc39/ecmascript_sharedmem for more information.
diff --git a/third_party/WebKit/LayoutTests/virtual/sharedarraybuffer/fast/css/fontface-arraybuffer-expected.txt b/third_party/WebKit/LayoutTests/virtual/sharedarraybuffer/fast/css/fontface-arraybuffer-expected.txt new file mode 100644 index 0000000..26e246e5 --- /dev/null +++ b/third_party/WebKit/LayoutTests/virtual/sharedarraybuffer/fast/css/fontface-arraybuffer-expected.txt
@@ -0,0 +1,18 @@ +Tests ArrayBuffer / ArrayBufferView constructors of FontFace. + +On success, you will see a series of "PASS" messages, followed by "TEST COMPLETE". + + +PASS face1.status is "loaded" +PASS face2.status is "loaded" +PASS rejectionValue.name is "TypeError" +PASS face3.status is "error" +PASS rejectionValue.name is "SyntaxError" +PASS document.getElementById('FontFromArrayBuffer').offsetWidth is document.getElementById('ref').offsetWidth +PASS document.getElementById('FontFromArrayBufferView').offsetWidth is document.getElementById('ref').offsetWidth +PASS successfullyParsed is true + +TEST COMPLETE +abc +abc +abc
diff --git a/third_party/WebKit/LayoutTests/virtual/sharedarraybuffer/fast/dom/README.txt b/third_party/WebKit/LayoutTests/virtual/sharedarraybuffer/fast/dom/README.txt new file mode 100644 index 0000000..de49eb0 --- /dev/null +++ b/third_party/WebKit/LayoutTests/virtual/sharedarraybuffer/fast/dom/README.txt
@@ -0,0 +1,3 @@ +# This suite runs the tests in --js-flags=--harmony-sharedarraybuffer +# This enables the SharedArrayBuffer language feature in V8. +# See https://github.com/tc39/ecmascript_sharedmem for more information.
diff --git a/third_party/WebKit/LayoutTests/virtual/sharedarraybuffer/fast/dom/geometry-interfaces-dom-matrix-expected.txt b/third_party/WebKit/LayoutTests/virtual/sharedarraybuffer/fast/dom/geometry-interfaces-dom-matrix-expected.txt new file mode 100644 index 0000000..9b8652c --- /dev/null +++ b/third_party/WebKit/LayoutTests/virtual/sharedarraybuffer/fast/dom/geometry-interfaces-dom-matrix-expected.txt
@@ -0,0 +1,31 @@ +This is a testharness.js-based test. +Harness Error. harness_status.status = 1 , harness_status.message = 1 duplicate test name: "DOMMatrix(numberSequence) constructor" +PASS DOMMatrix() constructor +PASS DOMMatrix fromFloat32Array - 2D matrix +PASS DOMMatrix fromFloat64Array - 2D matrix +PASS DOMMatrix fromFloat32Array - 3D matrix +PASS DOMMatrix fromFloat64Array - 3D matrix +PASS DOMMatrix(transformList) - emptyString +PASS DOMMatrix(transformList) - transformList +PASS DOMMatrix(numberSequence) constructor +PASS DOMMatrix(numberSequence) constructor +PASS DOMMatrix attributes +PASS DOMMatrix.is2D can never be set to 'true' when it was set to 'false' before calling setMatrixValue() +PASS DOMMatrix fromFloat*Array - invalid array size of nearby 6 +PASS DOMMatrix fromFloat*Array - invalid array size of nearby 16 +PASS DOMMatrix fromFloat*Array - invalid array size +PASS DOMMatrix fromFloat*Array - can't use SharedArrayBuffer view +PASS DOMMatrix.fromMatrix() with no parameter +PASS DOMMatrix.fromMatrix() with null +PASS DOMMatrix.fromMatrix() with undefined +PASS DOMMatrix.fromMatrix() with empty object +PASS DOMMatrix.fromMatrix({a: 1, b: 2, c: 3, d: 4, e: 5, f: 6}) should create a 2D DOMMatrix +PASS DOMMatrix.fromMatrix({m11: 1, m22: 2, m33: 3, m44: 4, m23: 5, m43: 6}) should create a 3D DOMMatrix +PASS If 2d related properties don't be set, should set to fallback +PASS DOMMatrix.fromMatrix(): NaN test +PASS DOMMatrix toJSON() - identity matrix +PASS DOMMatrix toJSON() - 2D matrix +PASS DOMMatrix toJSON() - 3D matrix +PASS DOMMatrix.fromMatrix(): Exception test +Harness: the test ran to completion. +
diff --git a/third_party/WebKit/LayoutTests/virtual/sharedarraybuffer/fast/encoding/api/README.txt b/third_party/WebKit/LayoutTests/virtual/sharedarraybuffer/fast/encoding/api/README.txt new file mode 100644 index 0000000..de49eb0 --- /dev/null +++ b/third_party/WebKit/LayoutTests/virtual/sharedarraybuffer/fast/encoding/api/README.txt
@@ -0,0 +1,3 @@ +# This suite runs the tests in --js-flags=--harmony-sharedarraybuffer +# This enables the SharedArrayBuffer language feature in V8. +# See https://github.com/tc39/ecmascript_sharedmem for more information.
diff --git a/third_party/WebKit/LayoutTests/virtual/sharedarraybuffer/fast/events/constructors/README.txt b/third_party/WebKit/LayoutTests/virtual/sharedarraybuffer/fast/events/constructors/README.txt new file mode 100644 index 0000000..de49eb0 --- /dev/null +++ b/third_party/WebKit/LayoutTests/virtual/sharedarraybuffer/fast/events/constructors/README.txt
@@ -0,0 +1,3 @@ +# This suite runs the tests in --js-flags=--harmony-sharedarraybuffer +# This enables the SharedArrayBuffer language feature in V8. +# See https://github.com/tc39/ecmascript_sharedmem for more information.
diff --git a/third_party/WebKit/LayoutTests/virtual/sharedarraybuffer/fast/events/constructors/midi-message-event-constructor-expected.txt b/third_party/WebKit/LayoutTests/virtual/sharedarraybuffer/fast/events/constructors/midi-message-event-constructor-expected.txt new file mode 100644 index 0000000..14b8b2b --- /dev/null +++ b/third_party/WebKit/LayoutTests/virtual/sharedarraybuffer/fast/events/constructors/midi-message-event-constructor-expected.txt
@@ -0,0 +1,21 @@ +This tests the constructor for the MIDIMessageEvent DOM class. + +On success, you will see a series of "PASS" messages, followed by "TEST COMPLETE". + + +PASS new MIDIMessageEvent('eventType').bubbles is false +PASS new MIDIMessageEvent('eventType').cancelable is false +PASS new MIDIMessageEvent('eventType').data is null +PASS new MIDIMessageEvent('eventType', { bubbles: false }).bubbles is false +PASS new MIDIMessageEvent('eventType', { bubbles: true }).bubbles is true +PASS new MIDIMessageEvent('eventType', { cancelable: false }).cancelable is false +PASS new MIDIMessageEvent('eventType', { cancelable: true }).cancelable is true +PASS new MIDIMessageEvent('eventType', { data: data }).data == '0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0' is true +PASS new MIDIMessageEvent('eventType', { bubbles: true, cancelable: true, data: data }).bubbles is true +PASS new MIDIMessageEvent('eventType', { bubbles: true, cancelable: true, data: data }).cancelable is true +PASS new MIDIMessageEvent('eventType', { bubbles: true, cancelable: true, data: data }).data == '0,0,0' is true +PASS new MIDIMessageEvent('eventType', { data: data }) threw exception TypeError: Failed to construct 'MIDIMessageEvent': The provided ArrayBufferView value must not be shared.. +PASS successfullyParsed is true + +TEST COMPLETE +
diff --git a/third_party/WebKit/LayoutTests/virtual/sharedarraybuffer/fast/files/README.txt b/third_party/WebKit/LayoutTests/virtual/sharedarraybuffer/fast/files/README.txt new file mode 100644 index 0000000..de49eb0 --- /dev/null +++ b/third_party/WebKit/LayoutTests/virtual/sharedarraybuffer/fast/files/README.txt
@@ -0,0 +1,3 @@ +# This suite runs the tests in --js-flags=--harmony-sharedarraybuffer +# This enables the SharedArrayBuffer language feature in V8. +# See https://github.com/tc39/ecmascript_sharedmem for more information.
diff --git a/third_party/WebKit/LayoutTests/virtual/sharedarraybuffer/fast/files/blob-constructor-expected.txt b/third_party/WebKit/LayoutTests/virtual/sharedarraybuffer/fast/files/blob-constructor-expected.txt new file mode 100644 index 0000000..195ef38 --- /dev/null +++ b/third_party/WebKit/LayoutTests/virtual/sharedarraybuffer/fast/files/blob-constructor-expected.txt
@@ -0,0 +1,96 @@ +Test the Blob constructor. + +On success, you will see a series of "PASS" messages, followed by "TEST COMPLETE". + + +PASS (new Blob()) instanceof window.Blob is true +PASS (new Blob(undefined)) instanceof window.Blob is true +PASS (new Blob([])) instanceof window.Blob is true +PASS (new Blob(['hello'])) instanceof window.Blob is true +PASS (new Blob(['hello'], {})) instanceof window.Blob is true +PASS (new Blob(['hello'], {type:'text/html'})) instanceof window.Blob is true +PASS (new Blob(['hello'], {type:'text/html', endings:'native'})) instanceof window.Blob is true +PASS (new Blob(['hello'], {type:'text/html', endings:'transparent'})) instanceof window.Blob is true +PASS (new Blob()).size is 0 +PASS (new Blob(undefined)).size is 0 +PASS (new Blob()).type is "" +PASS (new Blob(undefined)).type is "" +PASS new Blob('hello') threw exception TypeError: Failed to construct 'Blob': The 1st argument is neither an array, nor does it have indexed properties.. +PASS new Blob(0) threw exception TypeError: Failed to construct 'Blob': The 1st argument is neither an array, nor does it have indexed properties.. +PASS new Blob(null) threw exception TypeError: Failed to construct 'Blob': The 1st argument is neither an array, nor does it have indexed properties.. +PASS (new Blob([])) instanceof window.Blob is true +PASS (new Blob(['stringPrimitive'])) instanceof window.Blob is true +PASS (new Blob([String('stringObject')])) instanceof window.Blob is true +PASS (new Blob([new Blob])) instanceof window.Blob is true +PASS (new Blob([new Blob([new Blob])])) instanceof window.Blob is true +PASS (new Blob([12])).size is 2 +PASS (new Blob([[]])).size is 0 +PASS (new Blob([{}])).size is 15 +PASS (new Blob([document])).size is 21 +PASS (new Blob([toStringingObj])).size is 8 +PASS new Blob([throwingObj]) threw exception Error. +PASS (new Blob([], {unknownKey:'value'})) instanceof window.Blob is true +PASS new Blob([], {endings:'illegalValue'}) threw exception TypeError: Failed to construct 'Blob': The provided value 'illegalValue' is not a valid enum value of type NormalizeLineEndings.. +PASS new Blob([], {endings:throwingObj}) threw exception Error. +PASS new Blob([], {type:throwingObj}) threw exception Error. +PASS new Blob([], {endings:throwingObj1, type:throwingObj2}) threw exception Error 1. +PASS new Blob([], {type:throwingObj2, endings:throwingObj1}) threw exception Error 1. +PASS new Blob([], {type:throwingObj2, endings:'illegal'}) threw exception TypeError: Failed to construct 'Blob': The provided value 'illegal' is not a valid enum value of type NormalizeLineEndings.. +PASS new Blob([], {type:'hello\u00EE'}).type is "" +PASS new Blob([], {type:'hello\u001F'}).type is "" +PASS new Blob([], {type:'hello\u007F'}).type is "" +PASS new Blob([], {type:'ABC/abc'}).type is "abc/abc" +PASS new Blob([], {type:'123ABCabc'}).type is "123abcabc" +PASS (new Blob([], null)) instanceof window.Blob is true +PASS (new Blob([], undefined)) instanceof window.Blob is true +PASS (new Blob([], 123)) instanceof window.Blob threw exception TypeError: Failed to construct 'Blob': parameter 2 ('options') is not an object.. +PASS (new Blob([], 123.4)) instanceof window.Blob threw exception TypeError: Failed to construct 'Blob': parameter 2 ('options') is not an object.. +PASS (new Blob([], true)) instanceof window.Blob threw exception TypeError: Failed to construct 'Blob': parameter 2 ('options') is not an object.. +PASS (new Blob([], 'abc')) instanceof window.Blob threw exception TypeError: Failed to construct 'Blob': parameter 2 ('options') is not an object.. +PASS (new Blob([], [])) instanceof window.Blob is true +PASS (new Blob([], /abc/)) instanceof window.Blob is true +PASS (new Blob([], function () {})) instanceof window.Blob is true +PASS (new Blob([], {type:'text/html'})).type is 'text/html' +PASS (new Blob([], {type:'text/html'})).size is 0 +PASS (new Blob([], {type:'text/plain;charset=UTF-8'})).type is 'text/plain;charset=utf-8' +PASS (new Blob([])).lastModified is undefined +PASS (new Blob([], {})).lastModified is undefined +PASS (new Blob([], {lastModified: new Date()})).lastModified is undefined +PASS window.Blob.length is 0 +PASS new Blob([new DataView(new ArrayBuffer(100))]).size is 100 +PASS new Blob([new Uint8Array(100)]).size is 100 +PASS new Blob([new Uint8ClampedArray(100)]).size is 100 +PASS new Blob([new Uint16Array(100)]).size is 200 +PASS new Blob([new Uint32Array(100)]).size is 400 +PASS new Blob([new Int8Array(100)]).size is 100 +PASS new Blob([new Int16Array(100)]).size is 200 +PASS new Blob([new Int32Array(100)]).size is 400 +PASS new Blob([new Float32Array(100)]).size is 400 +PASS new Blob([new Float64Array(100)]).size is 800 +PASS new Blob([new Float64Array(100), new Int32Array(100), new Uint8Array(100), new DataView(new ArrayBuffer(100))]).size is 1400 +PASS new Blob([new Blob([new Int32Array(100)]), new Uint8Array(100), new Float32Array(100), new DataView(new ArrayBuffer(100))]).size is 1000 +PASS new Blob([(new DataView(new ArrayBuffer(100))).buffer]).size is 100 +PASS new Blob([(new Uint8Array(100)).buffer]).size is 100 +PASS new Blob([(new Uint8ClampedArray(100)).buffer]).size is 100 +PASS new Blob([(new Uint16Array(100)).buffer]).size is 200 +PASS new Blob([(new Uint32Array(100)).buffer]).size is 400 +PASS new Blob([(new Int8Array(100)).buffer]).size is 100 +PASS new Blob([(new Int16Array(100)).buffer]).size is 200 +PASS new Blob([(new Int32Array(100)).buffer]).size is 400 +PASS new Blob([(new Float32Array(100)).buffer]).size is 400 +PASS new Blob([(new Float64Array(100)).buffer]).size is 800 +PASS new Blob([(new Float64Array(100)).buffer, (new Int32Array(100)).buffer, (new Uint8Array(100)).buffer, (new DataView(new ArrayBuffer(100))).buffer]).size is 1400 +PASS new Blob([new Blob([(new Int32Array(100)).buffer]), (new Uint8Array(100)).buffer, (new Float32Array(100)).buffer, (new DataView(new ArrayBuffer(100))).buffer]).size is 1000 +PASS new Blob([new Uint8Array(new SharedArrayBuffer(4))]) threw exception TypeError: Failed to construct 'Blob': The provided ArrayBufferView value must not be shared.. +PASS new Blob({length: 0}).size is 0 +PASS new Blob({length: 1, 0: 'string'}).size is 6 +PASS OMICRON_WITH_OXIA.charCodeAt(0) is 0x1F79 +PASS reader.result.charCodeAt(0) is 0x1F79 +PASS CONTAINS_UNPAIRED_SURROGATES.charCodeAt(3) is 0xDC00 +PASS CONTAINS_UNPAIRED_SURROGATES.charCodeAt(7) is 0xD800 +PASS reader.result.charCodeAt(3) is 0xFFFD +PASS reader.result.charCodeAt(7) is 0xFFFD +PASS successfullyParsed is true + +TEST COMPLETE +
diff --git a/third_party/WebKit/LayoutTests/virtual/sharedarraybuffer/fast/peerconnection/README.txt b/third_party/WebKit/LayoutTests/virtual/sharedarraybuffer/fast/peerconnection/README.txt new file mode 100644 index 0000000..de49eb0 --- /dev/null +++ b/third_party/WebKit/LayoutTests/virtual/sharedarraybuffer/fast/peerconnection/README.txt
@@ -0,0 +1,3 @@ +# This suite runs the tests in --js-flags=--harmony-sharedarraybuffer +# This enables the SharedArrayBuffer language feature in V8. +# See https://github.com/tc39/ecmascript_sharedmem for more information.
diff --git a/third_party/WebKit/LayoutTests/virtual/sharedarraybuffer/fast/peerconnection/RTCPeerConnection-datachannel-expected.txt b/third_party/WebKit/LayoutTests/virtual/sharedarraybuffer/fast/peerconnection/RTCPeerConnection-datachannel-expected.txt new file mode 100644 index 0000000..a625818 --- /dev/null +++ b/third_party/WebKit/LayoutTests/virtual/sharedarraybuffer/fast/peerconnection/RTCPeerConnection-datachannel-expected.txt
@@ -0,0 +1,45 @@ +Tests RTCDataChannel. + +On success, you will see a series of "PASS" messages, followed by "TEST COMPLETE". + + +PASS dc = pc.createDataChannel("label1"); did not throw exception. +PASS dc.reliable is true +PASS dc = pc.createDataChannel("label2", {}); did not throw exception. +PASS dc.reliable is true +PASS dc = pc.createDataChannel("label3", {ordered:true}); did not throw exception. +PASS dc.reliable is true +PASS dc = pc.createDataChannel("label3", {ordered:false}); did not throw exception. +PASS dc.reliable is false +PASS dc = pc.createDataChannel("label3", {maxRetransmits:0}); did not throw exception. +PASS dc.reliable is false +PASS dc = pc.createDataChannel("label3", {maxRetransmitTime:0}); did not throw exception. +PASS dc.reliable is false +PASS pc is connected +PASS dc = pc.createDataChannel("label"); did not throw exception. +PASS dc.readyState is 'connecting' +PASS pc_ondatachannel was called +PASS dc_onopen was called +PASS dc.readyState is 'open' +PASS dc.label is 'label' +PASS dc.send('xyzzy'); did not throw exception. +PASS dc_onmessage_string was called +PASS data is 'xyzzy' +PASS dc.send(buffer); did not throw exception. +PASS dc_onmessage_arraybuffer was called +PASS data.byteLength is 2 +PASS array[0] is 17 +PASS array[1] is 19 +PASS data.byteLength is 12 +PASS dc.send(shrunkView); did not throw exception. +PASS dc_onmessage_dataview was called +PASS data.byteLength is 10 +PASS array[0] is 1 +PASS array[9] is 10 +PASS dc.send(new Uint8Array(new SharedArrayBuffer(16))); threw exception TypeError: Failed to execute 'send' on 'RTCDataChannel': The provided ArrayBufferView value must not be shared.. +PASS dc_onclose was called +PASS dc.readyState is 'closed' +PASS successfullyParsed is true + +TEST COMPLETE +
diff --git a/third_party/WebKit/LayoutTests/virtual/sharedarraybuffer/fast/workers/README.txt b/third_party/WebKit/LayoutTests/virtual/sharedarraybuffer/fast/workers/README.txt index cb3dbc97..de49eb0 100644 --- a/third_party/WebKit/LayoutTests/virtual/sharedarraybuffer/fast/workers/README.txt +++ b/third_party/WebKit/LayoutTests/virtual/sharedarraybuffer/fast/workers/README.txt
@@ -1,5 +1,3 @@ -# This suite runs the tests in fast/workers with -# --js-flags=--harmony-sharedarraybuffer -# This enables the experimental SharedArrayBuffer language feature in V8. -# See -# https://github.com/lars-t-hansen/ecmascript_sharedmem for more information. +# This suite runs the tests in --js-flags=--harmony-sharedarraybuffer +# This enables the SharedArrayBuffer language feature in V8. +# See https://github.com/tc39/ecmascript_sharedmem for more information.
diff --git a/third_party/WebKit/LayoutTests/virtual/sharedarraybuffer/http/tests/media/media-source/README.txt b/third_party/WebKit/LayoutTests/virtual/sharedarraybuffer/http/tests/media/media-source/README.txt new file mode 100644 index 0000000..de49eb0 --- /dev/null +++ b/third_party/WebKit/LayoutTests/virtual/sharedarraybuffer/http/tests/media/media-source/README.txt
@@ -0,0 +1,3 @@ +# This suite runs the tests in --js-flags=--harmony-sharedarraybuffer +# This enables the SharedArrayBuffer language feature in V8. +# See https://github.com/tc39/ecmascript_sharedmem for more information.
diff --git a/third_party/WebKit/LayoutTests/virtual/sharedarraybuffer/http/tests/push_messaging/README.txt b/third_party/WebKit/LayoutTests/virtual/sharedarraybuffer/http/tests/push_messaging/README.txt new file mode 100644 index 0000000..de49eb0 --- /dev/null +++ b/third_party/WebKit/LayoutTests/virtual/sharedarraybuffer/http/tests/push_messaging/README.txt
@@ -0,0 +1,3 @@ +# This suite runs the tests in --js-flags=--harmony-sharedarraybuffer +# This enables the SharedArrayBuffer language feature in V8. +# See https://github.com/tc39/ecmascript_sharedmem for more information.
diff --git a/third_party/WebKit/LayoutTests/virtual/sharedarraybuffer/http/tests/websocket/README.txt b/third_party/WebKit/LayoutTests/virtual/sharedarraybuffer/http/tests/websocket/README.txt new file mode 100644 index 0000000..de49eb0 --- /dev/null +++ b/third_party/WebKit/LayoutTests/virtual/sharedarraybuffer/http/tests/websocket/README.txt
@@ -0,0 +1,3 @@ +# This suite runs the tests in --js-flags=--harmony-sharedarraybuffer +# This enables the SharedArrayBuffer language feature in V8. +# See https://github.com/tc39/ecmascript_sharedmem for more information.
diff --git a/third_party/WebKit/LayoutTests/virtual/sharedarraybuffer/http/tests/websocket/send-arraybufferview-expected.txt b/third_party/WebKit/LayoutTests/virtual/sharedarraybuffer/http/tests/websocket/send-arraybufferview-expected.txt new file mode 100644 index 0000000..f4970fe --- /dev/null +++ b/third_party/WebKit/LayoutTests/virtual/sharedarraybuffer/http/tests/websocket/send-arraybufferview-expected.txt
@@ -0,0 +1,13 @@ +WebSocket: Send ArrayBufferViews. + +On success, you will see a series of "PASS" messages, followed by "TEST COMPLETE". + +PASS ws.send(createSharedArrayBufferView()) threw exception TypeError: Failed to execute 'send' on 'WebSocket': The provided ArrayBufferView value must not be shared.. +PASS PASS: Message #0. +PASS PASS: Message #1. +PASS PASS: Message #2. +PASS closeEvent.wasClean is true +PASS successfullyParsed is true + +TEST COMPLETE +
diff --git a/third_party/WebKit/LayoutTests/virtual/sharedarraybuffer/sensor/README.txt b/third_party/WebKit/LayoutTests/virtual/sharedarraybuffer/sensor/README.txt new file mode 100644 index 0000000..de49eb0 --- /dev/null +++ b/third_party/WebKit/LayoutTests/virtual/sharedarraybuffer/sensor/README.txt
@@ -0,0 +1,3 @@ +# This suite runs the tests in --js-flags=--harmony-sharedarraybuffer +# This enables the SharedArrayBuffer language feature in V8. +# See https://github.com/tc39/ecmascript_sharedmem for more information.
diff --git a/third_party/WebKit/LayoutTests/virtual/sharedarraybuffer/webaudio/README.txt b/third_party/WebKit/LayoutTests/virtual/sharedarraybuffer/webaudio/README.txt new file mode 100644 index 0000000..de49eb0 --- /dev/null +++ b/third_party/WebKit/LayoutTests/virtual/sharedarraybuffer/webaudio/README.txt
@@ -0,0 +1,3 @@ +# This suite runs the tests in --js-flags=--harmony-sharedarraybuffer +# This enables the SharedArrayBuffer language feature in V8. +# See https://github.com/tc39/ecmascript_sharedmem for more information.
diff --git a/third_party/WebKit/LayoutTests/virtual/sharedarraybuffer/webaudio/dom-exceptions-expected.txt b/third_party/WebKit/LayoutTests/virtual/sharedarraybuffer/webaudio/dom-exceptions-expected.txt new file mode 100644 index 0000000..82728fbe --- /dev/null +++ b/third_party/WebKit/LayoutTests/virtual/sharedarraybuffer/webaudio/dom-exceptions-expected.txt
@@ -0,0 +1,250 @@ +CONSOLE WARNING: line 341: The provided value 'fancy' is not a valid enum value of type ChannelCountMode. +CONSOLE WARNING: line 347: The provided value 'undefined' is not a valid enum value of type ChannelInterpretation. +CONSOLE WARNING: line 502: The provided value '9x' is not a valid enum value of type OverSampleType. +CONSOLE WARNING: line 717: The provided value 'junk' is not a valid enum value of type ChannelCountMode. +CONSOLE WARNING: line 746: The provided value 'junk' is not a valid enum value of type ChannelCountMode. +This is a testharness.js-based test. +PASS # AUDIT TASK RUNNER STARTED. +PASS > [initialize] Initialize contexts for testing +PASS context = new AudioContext() did not throw an exception. +PASS otherContext = new AudioContext() did not throw an exception. +PASS < [initialize] All assertions passed. (total 2 assertions) +PASS > [createBuffer] +PASS context.createBuffer(99, 1, context.sampleRate) threw NotSupportedError: "Failed to execute 'createBuffer' on 'BaseAudioContext': The number of channels provided (99) is outside the range [1, 32].". +PASS context.createBuffer(0, 1, context.sampleRate) threw NotSupportedError: "Failed to execute 'createBuffer' on 'BaseAudioContext': The number of channels provided (0) is outside the range [1, 32].". +PASS context.createBuffer(1, 1, 1) threw NotSupportedError: "Failed to execute 'createBuffer' on 'BaseAudioContext': The sample rate provided (1) is outside the range [3000, 384000].". +PASS context.createBuffer(1, 1, 2999) threw NotSupportedError: "Failed to execute 'createBuffer' on 'BaseAudioContext': The sample rate provided (2999) is outside the range [3000, 384000].". +PASS context.createBuffer(1, 1, 384001) threw NotSupportedError: "Failed to execute 'createBuffer' on 'BaseAudioContext': The sample rate provided (384001) is outside the range [3000, 384000].". +PASS context.createBuffer(1, 1, 1e6) threw NotSupportedError: "Failed to execute 'createBuffer' on 'BaseAudioContext': The sample rate provided (1.00000e+6) is outside the range [3000, 384000].". +PASS context.createBuffer(1, 1, 3000) did not throw an exception. +PASS context.createBuffer(1, 1, 192000) did not throw an exception. +PASS context.createBuffer(1, 1, 384000) did not throw an exception. +PASS context.createBuffer(1, 0, context.sampleRate) threw NotSupportedError: "Failed to execute 'createBuffer' on 'BaseAudioContext': The number of frames provided (0) is less than or equal to the minimum bound (0).". +PASS context.createBuffer(new ArrayBuffer(100), true) threw TypeError: "Failed to execute 'createBuffer' on 'BaseAudioContext': 3 arguments required, but only 2 present.". +PASS < [createBuffer] All assertions passed. (total 11 assertions) +PASS > [createMediaElementSource] +PASS context.createMediaElementSource(null) threw TypeError: "Failed to execute 'createMediaElementSource' on 'BaseAudioContext': parameter 1 is not of type 'HTMLMediaElement'.". +PASS < [createMediaElementSource] All assertions passed. (total 1 assertions) +PASS > [createMediaStreamSource] +PASS context.createMediaStreamSource(null) threw TypeError: "Failed to execute 'createMediaStreamSource' on 'BaseAudioContext': parameter 1 is not of type 'MediaStream'.". +PASS < [createMediaStreamSource] All assertions passed. (total 1 assertions) +PASS > [createScriptProcessor] +PASS context.createScriptProcessor(1, 1, 1) threw IndexSizeError: "Failed to execute 'createScriptProcessor' on 'BaseAudioContext': buffer size (1) must be 0 or a power of two between 256 and 16384.". +PASS context.createScriptProcessor(4096, 100, 1) threw IndexSizeError: "Failed to execute 'createScriptProcessor' on 'BaseAudioContext': number of input channels (100) exceeds maximum (32).". +PASS context.createScriptProcessor(4096, 1, 100) threw IndexSizeError: "Failed to execute 'createScriptProcessor' on 'BaseAudioContext': number of output channels (100) exceeds maximum (32).". +PASS context.createScriptProcessor() did not throw an exception. +PASS context.createScriptProcessor(0) did not throw an exception. +PASS < [createScriptProcessor] All assertions passed. (total 5 assertions) +PASS > [createChannelSplitter] +PASS context.createChannelSplitter(0) threw IndexSizeError: "Failed to execute 'createChannelSplitter' on 'BaseAudioContext': The number of outputs provided (0) is outside the range [1, 32].". +PASS context.createChannelSplitter(99) threw IndexSizeError: "Failed to execute 'createChannelSplitter' on 'BaseAudioContext': The number of outputs provided (99) is outside the range [1, 32].". +PASS context.createChannelMerger(0) threw IndexSizeError: "Failed to execute 'createChannelMerger' on 'BaseAudioContext': The number of inputs provided (0) is outside the range [1, 32].". +PASS < [createChannelSplitter] All assertions passed. (total 3 assertions) +PASS > [createChannelMerger] +PASS context.createChannelMerger(99) threw IndexSizeError: "Failed to execute 'createChannelMerger' on 'BaseAudioContext': The number of inputs provided (99) is outside the range [1, 32].". +PASS < [createChannelMerger] All assertions passed. (total 1 assertions) +PASS > [createPeriodicWave] +PASS context.createPeriodicWave(null, null) threw TypeError: "Failed to execute 'createPeriodicWave' on 'BaseAudioContext': parameter 1 is not of type 'Float32Array'.". +PASS context.createPeriodicWave(new Float32Array(10), null) threw TypeError: "Failed to execute 'createPeriodicWave' on 'BaseAudioContext': parameter 2 is not of type 'Float32Array'.". +PASS context.createPeriodicWave(new Float32Array(4100), new Float32Array(4100)) did not throw an exception. +PASS context.createPeriodicWave(new Float32Array(8192), new Float32Array(8192)) did not throw an exception. +PASS context.createPeriodicWave(new Float32Array(10000), new Float32Array(10000)) did not throw an exception. +PASS context.createPeriodicWave(new Float32Array(10), new Float32Array(7)) threw IndexSizeError: "Failed to execute 'createPeriodicWave' on 'BaseAudioContext': length of real array (10) and length of imaginary array (7) must match.". +PASS context.createPeriodicWave(shared_view, nonshared_view) threw TypeError: "Failed to execute 'createPeriodicWave' on 'BaseAudioContext': The provided ArrayBufferView value must not be shared.". +PASS context.createPeriodicWave(nonshared_view, shared_view) threw TypeError: "Failed to execute 'createPeriodicWave' on 'BaseAudioContext': The provided ArrayBufferView value must not be shared.". +PASS < [createPeriodicWave] All assertions passed. (total 8 assertions) +PASS > [createAnalyser] +PASS AnalyserNode.fftSize = 42 threw IndexSizeError: "Failed to set the 'fftSize' property on 'AnalyserNode': The value provided (42) is not a power of two.". +PASS AnalyserNode.fftSize is not equal to 42. +PASS AnalyserNode.fftSize = 16 threw IndexSizeError: "Failed to set the 'fftSize' property on 'AnalyserNode': The FFT size provided (16) is outside the range [32, 32768].". +PASS AnalyserNode.fftSize is not equal to 16. +PASS AnalyserNode.fftSize = 32768 did not throw an exception. +PASS AnalyserNode.fftSize = 65536 threw IndexSizeError: "Failed to set the 'fftSize' property on 'AnalyserNode': The FFT size provided (65536) is outside the range [32, 32768].". +PASS AnalyserNode.fftSize is not equal to 65536. +PASS AnalyserNode.minDecibels = -10 threw IndexSizeError: "Failed to set the 'minDecibels' property on 'AnalyserNode': The minDecibels provided (-10) is greater than the maximum bound (-30).". +PASS AnalyserNode.minDecibels is not equal to -10. +PASS AnalyserNode.maxDecibels = -150 threw IndexSizeError: "Failed to set the 'maxDecibels' property on 'AnalyserNode': The maxDecibels provided (-150) is less than the minimum bound (-100).". +PASS AnalyserNode.maxDecibels is not equal to -150. +PASS AnalyserNode.minDecibels = -30 threw IndexSizeError: "Failed to set the 'minDecibels' property on 'AnalyserNode': The minDecibels provided (-30) is greater than or equal to the maximum bound (-30).". +PASS AnalyserNode.minDecibels is not equal to -30. +PASS AnalyserNode.maxDecibels = -100 threw IndexSizeError: "Failed to set the 'maxDecibels' property on 'AnalyserNode': The maxDecibels provided (-100) is less than or equal to the minimum bound (-100).". +PASS AnalyserNode.maxDecibels is not equal to -100. +PASS AnalyserNode.smoothingTimeConstant = -0.1 threw IndexSizeError: "Failed to set the 'smoothingTimeConstant' property on 'AnalyserNode': The smoothing value provided (-0.1) is outside the range [0, 1].". +PASS AnalyserNode.smoothingTimeConstant is not equal to -0.1. +PASS AnalyserNode.smoothingTimeConstant = 1.5 threw IndexSizeError: "Failed to set the 'smoothingTimeConstant' property on 'AnalyserNode': The smoothing value provided (1.5) is outside the range [0, 1].". +PASS AnalyserNode.smoothingTimeConstant is not equal to 1.5. +PASS AnalyserNode.getFloatFrequencyData(null) threw TypeError: "Failed to execute 'getFloatFrequencyData' on 'AnalyserNode': parameter 1 is not of type 'Float32Array'.". +PASS AnalyserNode.getByteFrequencyData(null) threw TypeError: "Failed to execute 'getByteFrequencyData' on 'AnalyserNode': parameter 1 is not of type 'Uint8Array'.". +PASS AnalyserNode.getFloatTimeDomainData(null) threw TypeError: "Failed to execute 'getFloatTimeDomainData' on 'AnalyserNode': parameter 1 is not of type 'Float32Array'.". +PASS AnalyserNode.getByteTimeDomainData(null) threw TypeError: "Failed to execute 'getByteTimeDomainData' on 'AnalyserNode': parameter 1 is not of type 'Uint8Array'.". +PASS AnalyserNode.getFloatFrequencyData(SharedArrayBuffer view) threw TypeError: "Failed to execute 'getFloatFrequencyData' on 'AnalyserNode': The provided ArrayBufferView value must not be shared.". +PASS AnalyserNode.getByteFrequencyData(SharedArrayBuffer view) threw TypeError: "Failed to execute 'getByteFrequencyData' on 'AnalyserNode': The provided ArrayBufferView value must not be shared.". +PASS AnalyserNode.getFloatTimeDomainData(SharedArrayBuffer view) threw TypeError: "Failed to execute 'getFloatTimeDomainData' on 'AnalyserNode': The provided ArrayBufferView value must not be shared.". +PASS AnalyserNode.getByteTimeDomainData(SharedArrayBuffer view) threw TypeError: "Failed to execute 'getByteTimeDomainData' on 'AnalyserNode': The provided ArrayBufferView value must not be shared.". +PASS AudioBuffer.getChannelData(2) threw IndexSizeError: "Failed to execute 'getChannelData' on 'AudioBuffer': channel index (2) exceeds number of channels (1)". +PASS < [createAnalyser] All assertions passed. (total 28 assertions) +PASS > [Init test nodes] Create test nodes for the following tests +PASS node = context.createGain() did not throw an exception. +PASS node2 = context.createGain() did not throw an exception. +PASS < [Init test nodes] All assertions passed. (total 2 assertions) +PASS > [connections] AudioNode connections +PASS node.connect(null, 0, 0) threw TypeError: "Failed to execute 'connect' on 'AudioNode': parameter 1 is not of type 'AudioNode'.". +PASS node.connect(context.destination, 100, 0) threw IndexSizeError: "Failed to execute 'connect' on 'AudioNode': output index (100) exceeds number of outputs (1).". +PASS node.connect(context.destination, 0, 100) threw IndexSizeError: "Failed to execute 'connect' on 'AudioNode': input index (100) exceeds number of inputs (1).". +PASS node.connect(node2.gain, 100) threw IndexSizeError: "Failed to execute 'connect' on 'AudioNode': output index (100) exceeds number of outputs (1).". +PASS node.disconnect(99) threw IndexSizeError: "Failed to execute 'disconnect' on 'AudioNode': The output index provided (99) is outside the range [0, 0].". +PASS node.connect(otherContext.destination) threw InvalidAccessError: "Failed to execute 'connect' on 'AudioNode': cannot connect to a destination belonging to a different audio context.". +PASS < [connections] All assertions passed. (total 6 assertions) +PASS > [channel-stuff] channelCount, channelCountMode, channelInterpretation +PASS GainNode.channelCount = 99 threw NotSupportedError: "Failed to set the 'channelCount' property on 'AudioNode': The channel count provided (99) is outside the range [1, 32].". +PASS GainNode.channelCount is not equal to 99. +PASS node.channelCountMode = "fancy" did not throw an exception. +PASS node.channelCountMode is equal to max. +PASS node.channelInterpretation = mode did not throw an exception. +PASS node.channelInterpretation is equal to speakers. +PASS context.destination.channelCount = 99 threw IndexSizeError: [error message omitted]. +PASS < [channel-stuff] All assertions passed. (total 7 assertions) +PASS > [audioparam] +PASS param.setValueCurveAtTime(null, 0, 0) threw TypeError: "Failed to execute 'setValueCurveAtTime' on 'AudioParam': parameter 1 is not of type 'Float32Array'.". +PASS param.setValueCurveAtTime(SharedArrayBuffer view, 0, 0) threw TypeError: "Failed to execute 'setValueCurveAtTime' on 'AudioParam': The provided ArrayBufferView value must not be shared.". +PASS node.gain.exponentialRampToValueAtTime(-1, 0.1) did not throw an exception. +PASS node.gain.exponentialRampToValueAtTime(0, 0.1) threw InvalidAccessError: "Failed to execute 'exponentialRampToValueAtTime' on 'AudioParam': The float target value provided (0) should not be in the range (-1.40130e-45, 1.40130e-45).". +PASS node.gain.exponentialRampToValueAtTime(1e-100, 0.1) threw InvalidAccessError: "Failed to execute 'exponentialRampToValueAtTime' on 'AudioParam': The float target value provided (0) should not be in the range (-1.40130e-45, 1.40130e-45).". +PASS node.gain.exponentialRampToValueAtTime(Math.pow(2, -149), 0.1) did not throw an exception. +PASS node.gain.exponentialRampToValueAtTime(Math.pow(2, -150), 0.1) threw InvalidAccessError: "Failed to execute 'exponentialRampToValueAtTime' on 'AudioParam': The float target value provided (0) should not be in the range (-1.40130e-45, 1.40130e-45).". +PASS < [audioparam] All assertions passed. (total 7 assertions) +PASS > [biquad] +PASS node.getFrequencyResponse(new Float32Array(1), new Float32Array(1), new Float32Array(1)) did not throw an exception. +PASS node.getFrequencyResponse(null, new Float32Array(1), new Float32Array(1)) threw TypeError: "Failed to execute 'getFrequencyResponse' on 'BiquadFilterNode': parameter 1 is not of type 'Float32Array'.". +PASS node.getFrequencyResponse(new Float32Array(1), null, new Float32Array(1)) threw TypeError: "Failed to execute 'getFrequencyResponse' on 'BiquadFilterNode': parameter 2 is not of type 'Float32Array'.". +PASS node.getFrequencyResponse(new Float32Array(1), new Float32Array(1), null) threw TypeError: "Failed to execute 'getFrequencyResponse' on 'BiquadFilterNode': parameter 3 is not of type 'Float32Array'.". +PASS node.getFrequencyResponse(shared_view, nonshared_view, nonshared_view) threw TypeError: "Failed to execute 'getFrequencyResponse' on 'BiquadFilterNode': The provided ArrayBufferView value must not be shared.". +PASS node.getFrequencyResponse(nonshared_view, shared_view, nonshared_view) threw TypeError: "Failed to execute 'getFrequencyResponse' on 'BiquadFilterNode': The provided ArrayBufferView value must not be shared.". +PASS node.getFrequencyResponse(nonshared_view, nonshared_view, shared_view) threw TypeError: "Failed to execute 'getFrequencyResponse' on 'BiquadFilterNode': The provided ArrayBufferView value must not be shared.". +PASS < [biquad] All assertions passed. (total 7 assertions) +PASS > [offline-audio-context] +PASS new OfflineAudioContext(32, 100, context.sampleRate) did not throw an exception. +PASS new OfflineAudioContext(0, 100, context.sampleRate) threw NotSupportedError: "Failed to construct 'OfflineAudioContext': The number of channels provided (0) is outside the range [1, 32].". +PASS new OfflineAudioContext(99, 100, context.sampleRate) threw NotSupportedError: "Failed to construct 'OfflineAudioContext': The number of channels provided (99) is outside the range [1, 32].". +PASS new OfflineAudioContext(1, 100, 1) threw NotSupportedError: "Failed to construct 'OfflineAudioContext': The sampleRate provided (1) is outside the range [3000, 384000].". +PASS new OfflineAudioContext(1, 100, 1e6) threw NotSupportedError: "Failed to construct 'OfflineAudioContext': The sampleRate provided (1.00000e+6) is outside the range [3000, 384000].". +PASS new OfflineAudioContext(1, -88200000000000, 44100) threw NotSupportedError: "Failed to construct 'OfflineAudioContext': OfflineAudioContext(1, 1448390656, 44100)". +PASS new OfflineAudioContext(1, 0, 44100) threw NotSupportedError: "Failed to construct 'OfflineAudioContext': The number of frames provided (0) is less than the minimum bound (1).". +PASS < [offline-audio-context] All assertions passed. (total 7 assertions) +PASS > [waveshaper] +PASS node.oversample = "9x" did not throw an exception. +PASS node.oversample is equal to none. +PASS node.curve = {} threw TypeError: "Failed to set the 'curve' property on 'WaveShaperNode': The provided value is not of type 'Float32Array'.". +PASS node.curve = new Float32Array(1) threw InvalidAccessError: "Failed to set the 'curve' property on 'WaveShaperNode': The curve length provided (1) is less than the minimum bound (2).". +PASS node.curve is equal to ${expected}. +PASS node.curve = new Float32Array(2) did not throw an exception. +PASS node.curve = null did not throw an exception. +PASS < [waveshaper] All assertions passed. (total 7 assertions) +PASS > [audio-buffer-source] AudioBufferSource start/stop +PASS source = context.createBufferSource() did not throw an exception. +PASS source.buffer = buffer did not throw an exception. +PASS source.buffer = context.createBuffer(1, 10, context.sampleRate) threw InvalidStateError: "Failed to set the 'buffer' property on 'AudioBufferSourceNode': Cannot set buffer after it has been already been set". +PASS source.start(-1) threw InvalidAccessError: "Failed to execute 'start' on 'AudioBufferSourceNode': The start time provided (-1) is less than the minimum bound (0).". +PASS source.start(Infinity) threw TypeError: "Failed to execute 'start' on 'AudioBufferSourceNode': The provided double value is non-finite.". +PASS source.start(-Infinity) threw TypeError: "Failed to execute 'start' on 'AudioBufferSourceNode': The provided double value is non-finite.". +PASS source.start(NaN) threw TypeError: "Failed to execute 'start' on 'AudioBufferSourceNode': The provided double value is non-finite.". +PASS source.start(1, Infinity) threw TypeError: "Failed to execute 'start' on 'AudioBufferSourceNode': The provided double value is non-finite.". +PASS source.start(1, -Infinity) threw TypeError: "Failed to execute 'start' on 'AudioBufferSourceNode': The provided double value is non-finite.". +PASS source.start(1, NaN) threw TypeError: "Failed to execute 'start' on 'AudioBufferSourceNode': The provided double value is non-finite.". +PASS source.start(1, -1) threw InvalidStateError: "Failed to execute 'start' on 'AudioBufferSourceNode': The offset provided (-1) is less than the minimum bound (0).". +PASS source.start(1, -Number.MIN_VALUE) threw InvalidStateError: "Failed to execute 'start' on 'AudioBufferSourceNode': The offset provided (-4.94066e-324) is less than the minimum bound (0).". +PASS source.start(1, 1, Infinity) threw TypeError: "Failed to execute 'start' on 'AudioBufferSourceNode': The provided double value is non-finite.". +PASS source.start(1, 1, -Infinity) threw TypeError: "Failed to execute 'start' on 'AudioBufferSourceNode': The provided double value is non-finite.". +PASS source.start(1, 1, NaN) threw TypeError: "Failed to execute 'start' on 'AudioBufferSourceNode': The provided double value is non-finite.". +PASS source.start(1, 1, -1) threw InvalidStateError: "Failed to execute 'start' on 'AudioBufferSourceNode': The duration provided (-1) is less than the minimum bound (0).". +PASS source.start(1, 1, -Number.MIN_VALUE) threw InvalidStateError: "Failed to execute 'start' on 'AudioBufferSourceNode': The duration provided (-4.94066e-324) is less than the minimum bound (0).". +PASS source.start() did not throw an exception. +PASS source.stop(-Number.MIN_VALUE) threw InvalidAccessError: "Failed to execute 'stop' on 'AudioScheduledSourceNode': The stop time provided (-4.94066e-324) is less than the minimum bound (0).". +PASS source.stop(Infinity) threw TypeError: "Failed to execute 'stop' on 'AudioScheduledSourceNode': The provided double value is non-finite.". +PASS source.stop(-Infinity) threw TypeError: "Failed to execute 'stop' on 'AudioScheduledSourceNode': The provided double value is non-finite.". +PASS source.stop(NaN) threw TypeError: "Failed to execute 'stop' on 'AudioScheduledSourceNode': The provided double value is non-finite.". +PASS source.stop() did not throw an exception. +PASS source2 = context.createBufferSource() did not throw an exception. +PASS source2.buffer = buffer did not throw an exception. +PASS source2.start(0, 0) did not throw an exception. +PASS source3 = context.createBufferSource() did not throw an exception. +PASS source3.buffer = buffer did not throw an exception. +PASS source3.start(0, -1/Infinity) did not throw an exception. +PASS source4 = context.createBufferSource() did not throw an exception. +PASS source4.start() did not throw an exception. +PASS source5 = context.createBufferSource() did not throw an exception. +PASS source5.buffer = buffer did not throw an exception. +PASS source5.stop() threw InvalidStateError: "Failed to execute 'stop' on 'AudioScheduledSourceNode': cannot call stop without calling start first.". +PASS source6 = context.createBufferSource() did not throw an exception. +PASS source6.buffer = buffer did not throw an exception. +PASS source6.start() did not throw an exception. +PASS source6.start() threw InvalidStateError: "Failed to execute 'start' on 'AudioBufferSourceNode': cannot call start more than once.". +PASS source7 = context.createBufferSource() did not throw an exception. +PASS source7.buffer = buffer did not throw an exception. +PASS source7.start() did not throw an exception. +PASS source7.stop() did not throw an exception. +PASS < [audio-buffer-source] All assertions passed. (total 42 assertions) +PASS > [oscillator] start/stop +PASS source8 = context.createOscillator() did not throw an exception. +PASS source8.start(-Number.MIN_VALUE) threw InvalidAccessError: "Failed to execute 'start' on 'AudioScheduledSourceNode': The start time provided (-4.94066e-324) is less than the minimum bound (0).". +PASS source8.start(Infinity) threw TypeError: "Failed to execute 'start' on 'AudioScheduledSourceNode': The provided double value is non-finite.". +PASS source8.start(-Infinity) threw TypeError: "Failed to execute 'start' on 'AudioScheduledSourceNode': The provided double value is non-finite.". +PASS source8.start(NaN) threw TypeError: "Failed to execute 'start' on 'AudioScheduledSourceNode': The provided double value is non-finite.". +PASS source8.start() did not throw an exception. +PASS source8.stop(-Number.MIN_VALUE) threw InvalidAccessError: "Failed to execute 'stop' on 'AudioScheduledSourceNode': The stop time provided (-4.94066e-324) is less than the minimum bound (0).". +PASS source8.stop(Infinity) threw TypeError: "Failed to execute 'stop' on 'AudioScheduledSourceNode': The provided double value is non-finite.". +PASS source8.stop(-Infinity) threw TypeError: "Failed to execute 'stop' on 'AudioScheduledSourceNode': The provided double value is non-finite.". +PASS source8.stop(NaN) threw TypeError: "Failed to execute 'stop' on 'AudioScheduledSourceNode': The provided double value is non-finite.". +PASS source8.stop() did not throw an exception. +PASS osc = context.createOscillator() did not throw an exception. +PASS osc.stop() threw InvalidStateError: "Failed to execute 'stop' on 'AudioScheduledSourceNode': cannot call stop without calling start first.". +PASS osc1 = context.createOscillator() did not throw an exception. +PASS osc1.start() did not throw an exception. +PASS osc1.stop() did not throw an exception. +PASS osc.setPeriodicWave(null) threw TypeError: "Failed to execute 'setPeriodicWave' on 'OscillatorNode': parameter 1 is not of type 'PeriodicWave'.". +PASS < [oscillator] All assertions passed. (total 17 assertions) +PASS > [convolver] +PASS oc = new OfflineAudioContext(1, 44100, 44100) did not throw an exception. +PASS conv = oc.createConvolver() did not throw an exception. +PASS conv.buffer = {} threw TypeError: "Failed to set the 'buffer' property on 'ConvolverNode': The provided value is not of type 'AudioBuffer'.". +PASS conv.buffer = oc.createBuffer(1, 100, 22050) threw NotSupportedError: "Failed to set the 'buffer' property on 'ConvolverNode': The buffer sample rate of 22050 does not match the context rate of 44100 Hz.". +PASS conv.buffer is equal to ${expected}. +PASS < [convolver] All assertions passed. (total 5 assertions) +PASS > [panner] +PASS panner.channelCount = 1 did not throw an exception. +PASS panner.channelCount = 2 did not throw an exception. +PASS PannerNode.channelCount = 0 threw NotSupportedError: "Failed to set the 'channelCount' property on 'AudioNode': The channelCount provided (0) is outside the range [1, 2].". +PASS PannerNode.channelCount is not equal to 0. +PASS PannerNode.channelCount = 3 threw NotSupportedError: "Failed to set the 'channelCount' property on 'AudioNode': The channelCount provided (3) is outside the range [1, 2].". +PASS PannerNode.channelCount is not equal to 3. +PASS PannerNode.channelCountMode = max threw NotSupportedError: "Failed to set the 'channelCountMode' property on 'AudioNode': Panner: 'max' is not allowed". +PASS PannerNode.channelCountMode is not equal to max. +PASS panner.channelCountMode = "explicit" did not throw an exception. +PASS panner.channelCountMode = "clamped-max" did not throw an exception. +PASS panner.channelCountMode = "junk" did not throw an exception. +PASS < [panner] All assertions passed. (total 11 assertions) +PASS > [script-processor] +PASS script = context.createScriptProcessor(256, 3) did not throw an exception. +PASS script.channelCount is equal to 3. +PASS script.channelCountMode is equal to explicit. +PASS script.channelCount = 3 did not throw an exception. +PASS ScriptProcessorNode.channelCount = 1 threw NotSupportedError: "Failed to set the 'channelCount' property on 'AudioNode': channelCount cannot be changed from 3 to 1". +PASS ScriptProcessorNode.channelCount is not equal to 1. +PASS ScriptProcessorNode.channelCount = 7 threw NotSupportedError: "Failed to set the 'channelCount' property on 'AudioNode': channelCount cannot be changed from 3 to 7". +PASS ScriptProcessorNode.channelCount is not equal to 7. +PASS script.channelCountMode = "explicit" did not throw an exception. +PASS ScriptProcessorNode.channelCountMode = max threw NotSupportedError: "Failed to set the 'channelCountMode' property on 'AudioNode': channelCountMode cannot be changed from 'explicit' to 'max'". +PASS ScriptProcessorNode.channelCountMode is not equal to max. +PASS ScriptProcessorNode.channelCountMode = clamped-max threw NotSupportedError: "Failed to set the 'channelCountMode' property on 'AudioNode': channelCountMode cannot be changed from 'explicit' to 'clamped-max'". +PASS ScriptProcessorNode.channelCountMode is not equal to clamped-max. +PASS script.channelCountMode = "junk" did not throw an exception. +PASS < [script-processor] All assertions passed. (total 14 assertions) +PASS > [misc] Miscellaneous tests +PASS osc.noteOn is equal to undefined. +PASS osc.noteOff is equal to undefined. +PASS source.noteOn is equal to undefined. +PASS source.noteOff is equal to undefined. +PASS < [misc] All assertions passed. (total 4 assertions) +PASS # AUDIT TASK RUNNER FINISHED: 22 tasks ran successfully. +Harness: the test ran to completion. +
diff --git a/third_party/WebKit/LayoutTests/virtual/sharedarraybuffer/webmidi/README.txt b/third_party/WebKit/LayoutTests/virtual/sharedarraybuffer/webmidi/README.txt new file mode 100644 index 0000000..de49eb0 --- /dev/null +++ b/third_party/WebKit/LayoutTests/virtual/sharedarraybuffer/webmidi/README.txt
@@ -0,0 +1,3 @@ +# This suite runs the tests in --js-flags=--harmony-sharedarraybuffer +# This enables the SharedArrayBuffer language feature in V8. +# See https://github.com/tc39/ecmascript_sharedmem for more information.
diff --git a/third_party/WebKit/LayoutTests/virtual/sharedarraybuffer/webmidi/send-messages-expected.txt b/third_party/WebKit/LayoutTests/virtual/sharedarraybuffer/webmidi/send-messages-expected.txt new file mode 100644 index 0000000..27b298d --- /dev/null +++ b/third_party/WebKit/LayoutTests/virtual/sharedarraybuffer/webmidi/send-messages-expected.txt
@@ -0,0 +1,48 @@ +Test if various kinds of MIDI messages can be validated. + +On success, you will see a series of "PASS" messages, followed by "TEST COMPLETE". + + +PASS navigator.requestMIDIAccess is defined. +PASS output.send([0x00, 0x01]) threw exception TypeError: Failed to execute 'send' on 'MIDIOutput': Running status is not allowed at index 0 (0).. +PASS output.send([0xf7]) threw exception TypeError: Failed to execute 'send' on 'MIDIOutput': Unexpected end of system exclusive message at index 0 (247).. +PASS output.send([0xf4]) threw exception TypeError: Failed to execute 'send' on 'MIDIOutput': Reserved status is not allowed at index 0 (244).. +PASS output.send([0xf5]) threw exception TypeError: Failed to execute 'send' on 'MIDIOutput': Reserved status is not allowed at index 0 (245).. +PASS output.send([0xf9]) threw exception TypeError: Failed to execute 'send' on 'MIDIOutput': Reserved status is not allowed at index 0 (249).. +PASS output.send([0xfd]) threw exception TypeError: Failed to execute 'send' on 'MIDIOutput': Reserved status is not allowed at index 0 (253).. +PASS output.send([0x80]) threw exception TypeError: Failed to execute 'send' on 'MIDIOutput': Message is incomplete.. +PASS output.send([0x80, 0x00]) threw exception TypeError: Failed to execute 'send' on 'MIDIOutput': Message is incomplete.. +PASS output.send([0x90]) threw exception TypeError: Failed to execute 'send' on 'MIDIOutput': Message is incomplete.. +PASS output.send([0x90, 0x00]) threw exception TypeError: Failed to execute 'send' on 'MIDIOutput': Message is incomplete.. +PASS output.send([0xa0]) threw exception TypeError: Failed to execute 'send' on 'MIDIOutput': Message is incomplete.. +PASS output.send([0xa0, 0x00]) threw exception TypeError: Failed to execute 'send' on 'MIDIOutput': Message is incomplete.. +PASS output.send([0xb0]) threw exception TypeError: Failed to execute 'send' on 'MIDIOutput': Message is incomplete.. +PASS output.send([0xb0, 0x00]) threw exception TypeError: Failed to execute 'send' on 'MIDIOutput': Message is incomplete.. +PASS output.send([0xc0]) threw exception TypeError: Failed to execute 'send' on 'MIDIOutput': Message is incomplete.. +PASS output.send([0xd0]) threw exception TypeError: Failed to execute 'send' on 'MIDIOutput': Message is incomplete.. +PASS output.send([0xe0]) threw exception TypeError: Failed to execute 'send' on 'MIDIOutput': Message is incomplete.. +PASS output.send([0xe0, 0x00]) threw exception TypeError: Failed to execute 'send' on 'MIDIOutput': Message is incomplete.. +PASS output.send([0xf1]) threw exception TypeError: Failed to execute 'send' on 'MIDIOutput': Message is incomplete.. +PASS output.send([0xf2]) threw exception TypeError: Failed to execute 'send' on 'MIDIOutput': Message is incomplete.. +PASS output.send([0xf2, 0x00]) threw exception TypeError: Failed to execute 'send' on 'MIDIOutput': Message is incomplete.. +PASS output.send([0xf3]) threw exception TypeError: Failed to execute 'send' on 'MIDIOutput': Message is incomplete.. +PASS output.send([0x80, 0x80, 0x00]) threw exception TypeError: Failed to execute 'send' on 'MIDIOutput': Unexpected status byte at index 1 (128).. +PASS output.send([0x80, 0x00, 0x80]) threw exception TypeError: Failed to execute 'send' on 'MIDIOutput': Unexpected status byte at index 2 (128).. +PASS output.send([0xf0, 0x80, 0xf7]) threw exception TypeError: Failed to execute 'send' on 'MIDIOutput': System exclusive message contains a status byte at index 1 (128).. +PASS output.send([0xf0, 0xf0, 0xf7]) threw exception TypeError: Failed to execute 'send' on 'MIDIOutput': System exclusive message contains a status byte at index 1 (240).. +PASS output.send([0xf0, 0xff, 0xf7, 0xf7]) threw exception TypeError: Failed to execute 'send' on 'MIDIOutput': Unexpected end of system exclusive message at index 3 (247).. +PASS output.send([0xf4, 0x80, 0x00, 0x00]) threw exception TypeError: Failed to execute 'send' on 'MIDIOutput': Reserved status is not allowed at index 0 (244).. +PASS output.send([0x80, 0xf4, 0x00, 0x00]) threw exception TypeError: Failed to execute 'send' on 'MIDIOutput': Unexpected status byte at index 1 (244).. +PASS output.send([0x80, 0x00, 0xf4, 0x00]) threw exception TypeError: Failed to execute 'send' on 'MIDIOutput': Unexpected status byte at index 2 (244).. +PASS output.send([0x80, 0x00, 0x00, 0xf4]) threw exception TypeError: Failed to execute 'send' on 'MIDIOutput': Reserved status is not allowed at index 3 (244).. +PASS output.send([0xf0, 0xff, 0xf4, 0xf7]) threw exception TypeError: Failed to execute 'send' on 'MIDIOutput': System exclusive message contains a status byte at index 2 (244).. +PASS output.send([], NaN) threw exception TypeError: Failed to execute 'send' on 'MIDIOutput': The provided double value is non-finite.. +PASS output.send([], Infinity) threw exception TypeError: Failed to execute 'send' on 'MIDIOutput': The provided double value is non-finite.. +PASS output.send(new Uint8Array(), NaN) threw exception TypeError: Failed to execute 'send' on 'MIDIOutput': The provided double value is non-finite.. +PASS output.send(new Uint8Array(), Infinity) threw exception TypeError: Failed to execute 'send' on 'MIDIOutput': The provided double value is non-finite.. +PASS output.send(new Uint8Array(new SharedArrayBuffer(4))) threw exception TypeError: Failed to execute 'send' on 'MIDIOutput': The provided ArrayBufferView value must not be shared.. +PASS output.send(new Uint8Array(new SharedArrayBuffer(4), 0)) threw exception TypeError: Failed to execute 'send' on 'MIDIOutput': The provided ArrayBufferView value must not be shared.. +PASS successfullyParsed is true + +TEST COMPLETE +
diff --git a/third_party/WebKit/LayoutTests/webaudio/AudioBuffer/audiobuffer-copy-channel.html b/third_party/WebKit/LayoutTests/webaudio/AudioBuffer/audiobuffer-copy-channel.html index 2b1db0a..dfd55bdd 100644 --- a/third_party/WebKit/LayoutTests/webaudio/AudioBuffer/audiobuffer-copy-channel.html +++ b/third_party/WebKit/LayoutTests/webaudio/AudioBuffer/audiobuffer-copy-channel.html
@@ -146,6 +146,19 @@ }, "7: buffer.copyFromChannel(x, 3)") .throw("IndexSizeError"); + if (window.SharedArrayBuffer) { + var shared_buffer = new Float32Array(new SharedArrayBuffer(32)); + should(() => { + buffer.copyFromChannel(shared_buffer, 0); + }, "8: buffer.copyFromChannel(SharedArrayBuffer view, 0)") + .throw("TypeError"); + + should(() => { + buffer.copyFromChannel(shared_buffer, 0, 0); + }, "9: buffer.copyFromChannel(SharedArrayBuffer view, 0, 0)") + .throw("TypeError"); + } + task.done(); }); @@ -184,6 +197,19 @@ }, "6: buffer.copyToChannel(x, 3)") .throw("IndexSizeError"); + if (window.SharedArrayBuffer) { + var shared_buffer = new Float32Array(new SharedArrayBuffer(32)); + should(() => { + buffer.copyToChannel(shared_buffer, 0); + }, "7: buffer.copyToChannel(SharedArrayBuffer view, 0)") + .throw("TypeError"); + + should(() => { + buffer.copyToChannel(shared_buffer, 0, 0); + }, "8: buffer.copyToChannel(SharedArrayBuffer view, 0, 0)") + .throw("TypeError"); + } + task.done(); });
diff --git a/third_party/WebKit/LayoutTests/webaudio/IIRFilter/iirfilter-basic.html b/third_party/WebKit/LayoutTests/webaudio/IIRFilter/iirfilter-basic.html index 43ffe81..9c693e4 100644 --- a/third_party/WebKit/LayoutTests/webaudio/IIRFilter/iirfilter-basic.html +++ b/third_party/WebKit/LayoutTests/webaudio/IIRFilter/iirfilter-basic.html
@@ -188,6 +188,27 @@ 30)); }).notThrow() && success; + if (window.SharedArrayBuffer) { + var shared_view = new Float32Array(new SharedArrayBuffer(4)); + var nonshared_view = new Float32Array(1); + + success = Should( + "getFrequencyResponse(shared_view, nonshared_view, nonshared_view)", + function () { + f.getFrequencyResponse(shared_view, nonshared_view, nonshared_view); + }).throw("TypeError") && success; + success = Should( + "getFrequencyResponse(nonshared_view, shared_view, nonshared_view)", + function () { + f.getFrequencyResponse(nonshared_view, shared_view, nonshared_view); + }).throw("TypeError") && success; + success = Should( + "getFrequencyResponse(nonshared_view, nonshared_view, shared_view)", + function () { + f.getFrequencyResponse(nonshared_view, nonshared_view, shared_view); + }).throw("TypeError") && success; + } + Should("getFrequencyResponse exceptions handled", success) .summarize("correctly", "incorrectly"); done();
diff --git a/third_party/WebKit/LayoutTests/webaudio/constructor/waveshaper.html b/third_party/WebKit/LayoutTests/webaudio/constructor/waveshaper.html index 40c2624..2968b1c 100644 --- a/third_party/WebKit/LayoutTests/webaudio/constructor/waveshaper.html +++ b/third_party/WebKit/LayoutTests/webaudio/constructor/waveshaper.html
@@ -96,6 +96,17 @@ taskDone(); }); + if (window.SharedArrayBuffer) { + audit.defineTask("invalid setCurve", function (taskDone) { + var node = new WaveShaperNode(context); + + Should("WaveShaper.curve = SharedArrayBuffer view", function () { + node.curve = new Float32Array(new SharedArrayBuffer(16)); + }).throw("TypeError"); + taskDone(); + }); + } + audit.runTasks(); </script> </body>
diff --git a/third_party/WebKit/LayoutTests/webaudio/dom-exceptions-expected.txt b/third_party/WebKit/LayoutTests/webaudio/dom-exceptions-expected.txt index b2b85c9..34e9429b 100644 --- a/third_party/WebKit/LayoutTests/webaudio/dom-exceptions-expected.txt +++ b/third_party/WebKit/LayoutTests/webaudio/dom-exceptions-expected.txt
@@ -1,8 +1,8 @@ -CONSOLE WARNING: line 308: The provided value 'fancy' is not a valid enum value of type ChannelCountMode. -CONSOLE WARNING: line 314: The provided value 'undefined' is not a valid enum value of type ChannelInterpretation. -CONSOLE WARNING: line 444: The provided value '9x' is not a valid enum value of type OverSampleType. -CONSOLE WARNING: line 659: The provided value 'junk' is not a valid enum value of type ChannelCountMode. -CONSOLE WARNING: line 688: The provided value 'junk' is not a valid enum value of type ChannelCountMode. +CONSOLE WARNING: line 341: The provided value 'fancy' is not a valid enum value of type ChannelCountMode. +CONSOLE WARNING: line 347: The provided value 'undefined' is not a valid enum value of type ChannelInterpretation. +CONSOLE WARNING: line 502: The provided value '9x' is not a valid enum value of type OverSampleType. +CONSOLE WARNING: line 717: The provided value 'junk' is not a valid enum value of type ChannelCountMode. +CONSOLE WARNING: line 746: The provided value 'junk' is not a valid enum value of type ChannelCountMode. This is a testharness.js-based test. PASS # AUDIT TASK RUNNER STARTED. PASS > [initialize] Initialize contexts for testing
diff --git a/third_party/WebKit/LayoutTests/webaudio/dom-exceptions.html b/third_party/WebKit/LayoutTests/webaudio/dom-exceptions.html index 436fd83a..72a36d1f 100644 --- a/third_party/WebKit/LayoutTests/webaudio/dom-exceptions.html +++ b/third_party/WebKit/LayoutTests/webaudio/dom-exceptions.html
@@ -2,7 +2,7 @@ <html> <head> <script src="../resources/testharness.js"></script> -<script src="../resources/testharnessreport.js"></script> +<script src="../resources/testharnessreport.js"></script> <script src="resources/audit-util.js"></script> <script src="resources/audit.js"></script> <script src="resources/biquad-testing.js"></script> @@ -197,6 +197,20 @@ 'context.createPeriodicWave(new Float32Array(10), new Float32Array(7))') .throw('IndexSizeError'); + if (window.SharedArrayBuffer) { + let shared_view = new Float32Array(new SharedArrayBuffer(4100 * 4)); + let nonshared_view = new Float32Array(4100); + should( + () => context.createPeriodicWave(shared_view, nonshared_view), + 'context.createPeriodicWave(shared_view, nonshared_view)') + .throw('TypeError'); + + should( + () => context.createPeriodicWave(nonshared_view, shared_view), + 'context.createPeriodicWave(nonshared_view, shared_view)') + .throw('TypeError'); + } + task.done(); }); @@ -234,6 +248,25 @@ node.constructor.name + '.getByteTimeDomainData(null)') .throw(); + if (window.SharedArrayBuffer) { + should( + () => node.getFloatFrequencyData(new Float32Array(new SharedArrayBuffer(16))), + 'AnalyserNode.getFloatFrequencyData(SharedArrayBuffer view)') + .throw(); + should( + () => node.getByteFrequencyData(new Uint8Array(new SharedArrayBuffer(16))), + node.constructor.name + '.getByteFrequencyData(SharedArrayBuffer view)') + .throw(); + should( + () => node.getFloatTimeDomainData(new Float32Array(new SharedArrayBuffer(16))), + node.constructor.name + '.getFloatTimeDomainData(SharedArrayBuffer view)') + .throw(); + should( + () => node.getByteTimeDomainData(new Uint8Array(new SharedArrayBuffer(16))), + node.constructor.name + '.getByteTimeDomainData(SharedArrayBuffer view)') + .throw(); + } + // AudioBuffers node = context.createBuffer(1, 1, context.sampleRate); // Invalid channel index: IndexSizeError @@ -336,6 +369,13 @@ 'param.setValueCurveAtTime(null, 0, 0)') .throw(); + if (window.SharedArrayBuffer) { + should( + () => param.setValueCurveAtTime(new Float32Array(new SharedArrayBuffer(16)), 0, 0), + 'param.setValueCurveAtTime(SharedArrayBuffer view, 0, 0)') + .throw(); + } + // exponentialRampToValue should throw only for "zero" target values. should( () => node.gain.exponentialRampToValueAtTime(-1, 0.1), @@ -396,6 +436,24 @@ 'node.getFrequencyResponse(new Float32Array(1), new Float32Array(1), null)') .throw(); + if (window.SharedArrayBuffer) { + let shared_view = new Float32Array(new SharedArrayBuffer(4)); + let nonshared_view = new Float32Array(1); + + should( + () => node.getFrequencyResponse(shared_view, nonshared_view, nonshared_view), + 'node.getFrequencyResponse(shared_view, nonshared_view, nonshared_view)') + .throw(); + should( + () => node.getFrequencyResponse(nonshared_view, shared_view, nonshared_view), + 'node.getFrequencyResponse(nonshared_view, shared_view, nonshared_view)') + .throw(); + should( + () => node.getFrequencyResponse(nonshared_view, nonshared_view, shared_view), + 'node.getFrequencyResponse(nonshared_view, nonshared_view, shared_view)') + .throw(); + } + task.done(); });
diff --git a/third_party/WebKit/LayoutTests/webaudio/internals/README.md b/third_party/WebKit/LayoutTests/webaudio/internals/README.md new file mode 100644 index 0000000..5c35e2b --- /dev/null +++ b/third_party/WebKit/LayoutTests/webaudio/internals/README.md
@@ -0,0 +1,3 @@ +# WebAudio Layout tests using |window.internals| + +Certain features in "resources/js-test.js" depends on special hooks from Chromium test runner, and the test using these features cannot be upstreamed. This directory is a collection of such test files.
diff --git a/third_party/WebKit/LayoutTests/webaudio/AudioContext/audiocontext-close.html b/third_party/WebKit/LayoutTests/webaudio/internals/audiocontext-close.html similarity index 100% rename from third_party/WebKit/LayoutTests/webaudio/AudioContext/audiocontext-close.html rename to third_party/WebKit/LayoutTests/webaudio/internals/audiocontext-close.html
diff --git a/third_party/WebKit/LayoutTests/webaudio/AudioContext/audiocontext-lock-threading-race-expected.txt b/third_party/WebKit/LayoutTests/webaudio/internals/audiocontext-lock-threading-race-expected.txt similarity index 100% rename from third_party/WebKit/LayoutTests/webaudio/AudioContext/audiocontext-lock-threading-race-expected.txt rename to third_party/WebKit/LayoutTests/webaudio/internals/audiocontext-lock-threading-race-expected.txt
diff --git a/third_party/WebKit/LayoutTests/webaudio/AudioContext/audiocontext-lock-threading-race.html b/third_party/WebKit/LayoutTests/webaudio/internals/audiocontext-lock-threading-race.html similarity index 100% rename from third_party/WebKit/LayoutTests/webaudio/AudioContext/audiocontext-lock-threading-race.html rename to third_party/WebKit/LayoutTests/webaudio/internals/audiocontext-lock-threading-race.html
diff --git a/third_party/WebKit/LayoutTests/webaudio/AudioBufferSource/audiosource-premature-gc.html b/third_party/WebKit/LayoutTests/webaudio/internals/audiosource-premature-gc.html similarity index 100% rename from third_party/WebKit/LayoutTests/webaudio/AudioBufferSource/audiosource-premature-gc.html rename to third_party/WebKit/LayoutTests/webaudio/internals/audiosource-premature-gc.html
diff --git a/third_party/WebKit/LayoutTests/webaudio/audiosummingjunction-crash.html b/third_party/WebKit/LayoutTests/webaudio/internals/audiosummingjunction-crash.html similarity index 78% rename from third_party/WebKit/LayoutTests/webaudio/audiosummingjunction-crash.html rename to third_party/WebKit/LayoutTests/webaudio/internals/audiosummingjunction-crash.html index 3074e49..2d211d32 100644 --- a/third_party/WebKit/LayoutTests/webaudio/audiosummingjunction-crash.html +++ b/third_party/WebKit/LayoutTests/webaudio/internals/audiosummingjunction-crash.html
@@ -1,7 +1,7 @@ <body> -<script src="../resources/testharness.js"></script> -<script src="../resources/testharnessreport.js"></script> -<script src="resources/audit.js"></script> +<script src="../../resources/testharness.js"></script> +<script src="../../resources/testharnessreport.js"></script> +<script src="../resources/audit.js"></script> <script> let audit = Audit.createTaskRunner();
diff --git a/third_party/WebKit/LayoutTests/webaudio/AudioNode/cycle-connection-gc-expected.txt b/third_party/WebKit/LayoutTests/webaudio/internals/cycle-connection-gc-expected.txt similarity index 100% rename from third_party/WebKit/LayoutTests/webaudio/AudioNode/cycle-connection-gc-expected.txt rename to third_party/WebKit/LayoutTests/webaudio/internals/cycle-connection-gc-expected.txt
diff --git a/third_party/WebKit/LayoutTests/webaudio/AudioNode/cycle-connection-gc.html b/third_party/WebKit/LayoutTests/webaudio/internals/cycle-connection-gc.html similarity index 100% rename from third_party/WebKit/LayoutTests/webaudio/AudioNode/cycle-connection-gc.html rename to third_party/WebKit/LayoutTests/webaudio/internals/cycle-connection-gc.html
diff --git a/third_party/WebKit/LayoutTests/webaudio/MediaElementAudioSource/mediaelementaudiosourcenode-gc-expected.txt b/third_party/WebKit/LayoutTests/webaudio/internals/mediaelementaudiosourcenode-gc-expected.txt similarity index 100% rename from third_party/WebKit/LayoutTests/webaudio/MediaElementAudioSource/mediaelementaudiosourcenode-gc-expected.txt rename to third_party/WebKit/LayoutTests/webaudio/internals/mediaelementaudiosourcenode-gc-expected.txt
diff --git a/third_party/WebKit/LayoutTests/webaudio/MediaElementAudioSource/mediaelementaudiosourcenode-gc.html b/third_party/WebKit/LayoutTests/webaudio/internals/mediaelementaudiosourcenode-gc.html similarity index 100% rename from third_party/WebKit/LayoutTests/webaudio/MediaElementAudioSource/mediaelementaudiosourcenode-gc.html rename to third_party/WebKit/LayoutTests/webaudio/internals/mediaelementaudiosourcenode-gc.html
diff --git a/third_party/WebKit/LayoutTests/webaudio/MediaElementAudioSource/mediaelementaudiosourcenode-wrapper-expected.txt b/third_party/WebKit/LayoutTests/webaudio/internals/mediaelementaudiosourcenode-wrapper-expected.txt similarity index 100% rename from third_party/WebKit/LayoutTests/webaudio/MediaElementAudioSource/mediaelementaudiosourcenode-wrapper-expected.txt rename to third_party/WebKit/LayoutTests/webaudio/internals/mediaelementaudiosourcenode-wrapper-expected.txt
diff --git a/third_party/WebKit/LayoutTests/webaudio/MediaElementAudioSource/mediaelementaudiosourcenode-wrapper.html b/third_party/WebKit/LayoutTests/webaudio/internals/mediaelementaudiosourcenode-wrapper.html similarity index 100% rename from third_party/WebKit/LayoutTests/webaudio/MediaElementAudioSource/mediaelementaudiosourcenode-wrapper.html rename to third_party/WebKit/LayoutTests/webaudio/internals/mediaelementaudiosourcenode-wrapper.html
diff --git a/third_party/WebKit/LayoutTests/webaudio/ScriptProcessor/scriptprocessornode-premature-death-expected.txt b/third_party/WebKit/LayoutTests/webaudio/internals/scriptprocessornode-premature-death-expected.txt similarity index 100% rename from third_party/WebKit/LayoutTests/webaudio/ScriptProcessor/scriptprocessornode-premature-death-expected.txt rename to third_party/WebKit/LayoutTests/webaudio/internals/scriptprocessornode-premature-death-expected.txt
diff --git a/third_party/WebKit/LayoutTests/webaudio/ScriptProcessor/scriptprocessornode-premature-death.html b/third_party/WebKit/LayoutTests/webaudio/internals/scriptprocessornode-premature-death.html similarity index 100% rename from third_party/WebKit/LayoutTests/webaudio/ScriptProcessor/scriptprocessornode-premature-death.html rename to third_party/WebKit/LayoutTests/webaudio/internals/scriptprocessornode-premature-death.html
diff --git a/third_party/WebKit/LayoutTests/webmidi/send-messages.html b/third_party/WebKit/LayoutTests/webmidi/send-messages.html index 2073dce..53d9367 100644 --- a/third_party/WebKit/LayoutTests/webmidi/send-messages.html +++ b/third_party/WebKit/LayoutTests/webmidi/send-messages.html
@@ -98,6 +98,11 @@ shouldThrow('output.send(new Uint8Array(), NaN)'); shouldThrow('output.send(new Uint8Array(), Infinity)'); + if (window.SharedArrayBuffer) { + shouldThrow('output.send(new Uint8Array(new SharedArrayBuffer(4)))'); + shouldThrow('output.send(new Uint8Array(new SharedArrayBuffer(4), 0))'); + } + finishJSTest(); }).catch(function () { testFailed("requestMIDIAccess() return an error.");
diff --git a/third_party/WebKit/PRESUBMIT.py b/third_party/WebKit/PRESUBMIT.py index b04e9a8..22ffdc9c 100644 --- a/third_party/WebKit/PRESUBMIT.py +++ b/third_party/WebKit/PRESUBMIT.py
@@ -294,43 +294,19 @@ return False -def _AreLayoutNGDirectoriesModified(change): # pylint: disable=C0103 - """Checks whether CL has changes to a layout ng directory.""" - layout_ng_paths = [ - os.path.join('third_party', 'WebKit', 'Source', 'core', 'layout', - 'ng'), - ] - for affected_file in change.AffectedFiles(): - file_path = affected_file.LocalPath() - if any(x in file_path for x in layout_ng_paths): - return True - return False - - def PostUploadHook(cl, change, output_api): # pylint: disable=C0103 """git cl upload will call this hook after the issue is created/modified. This hook adds extra try bots to the CL description in order to run slimming - paint v2 tests or LayoutNG tests in addition to the CQ try bots if the - change contains changes in a relevant direcotry (see: - _ArePaintOrCompositingDirectoriesModified and - _AreLayoutNGDirectoriesModified). For more information about - slimming-paint-v2 tests see https://crbug.com/601275 and for information - about the LayoutNG tests see https://crbug.com/706183. + paint v2 tests in addition to the CQ try bots if the change contains paint + or compositing changes (see: _ArePaintOrCompositingDirectoriesModified). For + more information about slimming-paint-v2 tests see https://crbug.com/601275. """ - results = [] - if _ArePaintOrCompositingDirectoriesModified(change): - results.extend(output_api.EnsureCQIncludeTrybotsAreAdded( - cl, - ['master.tryserver.chromium.linux:' - 'linux_layout_tests_slimming_paint_v2'], - 'Automatically added slimming-paint-v2 tests to run on CQ due to ' - 'changes in paint or compositing directories.')) - if _AreLayoutNGDirectoriesModified(change): - results.extend(output_api.EnsureCQIncludeTrybotsAreAdded( - cl, - ['master.tryserver.chromium.linux:' - 'linux_layout_tests_layout_ng'], - 'Automatically added linux_layout_tests_layout_ng to run on CQ due ' - 'to changes in LayoutNG directories.')) - return results + if not _ArePaintOrCompositingDirectoriesModified(change): + return [] + return output_api.EnsureCQIncludeTrybotsAreAdded( + cl, + ['master.tryserver.chromium.linux:' + 'linux_layout_tests_slimming_paint_v2'], + 'Automatically added slimming-paint-v2 tests to run on CQ due to ' + 'changes in paint or compositing directories.')
diff --git a/third_party/WebKit/Source/bindings/core/v8/ExceptionMessages.cpp b/third_party/WebKit/Source/bindings/core/v8/ExceptionMessages.cpp index c145537..a075ee1 100644 --- a/third_party/WebKit/Source/bindings/core/v8/ExceptionMessages.cpp +++ b/third_party/WebKit/Source/bindings/core/v8/ExceptionMessages.cpp
@@ -35,6 +35,10 @@ namespace blink { +String ExceptionMessages::FailedToConvertJSValue(const char* type) { + return String::Format("Failed to convert value to '%s'.", type); +} + String ExceptionMessages::FailedToConstruct(const char* type, const String& detail) { return "Failed to construct '" + String(type) +
diff --git a/third_party/WebKit/Source/bindings/core/v8/ExceptionMessages.h b/third_party/WebKit/Source/bindings/core/v8/ExceptionMessages.h index 60f020b1..ce6ed05 100644 --- a/third_party/WebKit/Source/bindings/core/v8/ExceptionMessages.h +++ b/third_party/WebKit/Source/bindings/core/v8/ExceptionMessages.h
@@ -54,6 +54,8 @@ const String& expected_type); static String ConstructorNotCallableAsFunction(const char* type); + static String FailedToConvertJSValue(const char* type); + static String FailedToConstruct(const char* type, const String& detail); static String FailedToEnumerate(const char* type, const String& detail); static String FailedToExecute(const char* method,
diff --git a/third_party/WebKit/Source/bindings/core/v8/NativeValueTraitsImplTest.cpp b/third_party/WebKit/Source/bindings/core/v8/NativeValueTraitsImplTest.cpp index b6e750d..062d7ff 100644 --- a/third_party/WebKit/Source/bindings/core/v8/NativeValueTraitsImplTest.cpp +++ b/third_party/WebKit/Source/bindings/core/v8/NativeValueTraitsImplTest.cpp
@@ -31,7 +31,7 @@ scope.GetIsolate(), v8::Number::New(scope.GetIsolate(), 42), exception_state); EXPECT_TRUE(exception_state.HadException()); - EXPECT_EQ("Unable to convert value to Internals.", + EXPECT_EQ("Failed to convert value to 'Internals'.", exception_state.Message()); EXPECT_EQ(nullptr, internals); } @@ -42,7 +42,7 @@ scope.GetIsolate(), v8::Undefined(scope.GetIsolate()), exception_state); EXPECT_TRUE(exception_state.HadException()); - EXPECT_EQ("Unable to convert value to TestSequenceCallback.", + EXPECT_EQ("Failed to convert value to 'TestSequenceCallback'.", exception_state.Message()); EXPECT_EQ(nullptr, callback_function); }
diff --git a/third_party/WebKit/Source/bindings/core/v8/ToV8.h b/third_party/WebKit/Source/bindings/core/v8/ToV8.h index b443d20..e96c472b 100644 --- a/third_party/WebKit/Source/bindings/core/v8/ToV8.h +++ b/third_party/WebKit/Source/bindings/core/v8/ToV8.h
@@ -17,6 +17,7 @@ #include "bindings/core/v8/ScriptWrappable.h" #include "bindings/core/v8/V8Binding.h" #include "core/CoreExport.h" +#include "core/dom/NotShared.h" #include "platform/heap/Handle.h" #include "platform/wtf/Forward.h" #include "v8/include/v8.h" @@ -275,6 +276,13 @@ return object; } +template <typename T> +inline v8::Local<v8::Value> ToV8(NotShared<T> value, + v8::Local<v8::Object> creation_context, + v8::Isolate* isolate) { + return ToV8(value.View(), creation_context, isolate); +} + template <typename Sequence> inline v8::Local<v8::Value> ToV8SequenceInternal( const Sequence& sequence,
diff --git a/third_party/WebKit/Source/bindings/core/v8/V8Binding.h b/third_party/WebKit/Source/bindings/core/v8/V8Binding.h index 208eee28..a1f218f 100644 --- a/third_party/WebKit/Source/bindings/core/v8/V8Binding.h +++ b/third_party/WebKit/Source/bindings/core/v8/V8Binding.h
@@ -47,6 +47,7 @@ #include "bindings/core/v8/V8ThrowException.h" #include "bindings/core/v8/V8ValueCache.h" #include "core/CoreExport.h" +#include "core/dom/NotShared.h" #include "platform/heap/Handle.h" #include "platform/wtf/text/AtomicString.h" #include "platform/wtf/text/StringView.h" @@ -216,6 +217,12 @@ V8SetReturnValue(callback_info, impl.Get()); } +template <typename CallbackInfo, typename T> +inline void V8SetReturnValue(const CallbackInfo& callbackInfo, + NotShared<T> notShared) { + V8SetReturnValue(callbackInfo, notShared.View()); +} + template <typename CallbackInfo> inline void V8SetReturnValueForMainWorld(const CallbackInfo& callback_info, ScriptWrappable* impl) { @@ -334,6 +341,13 @@ V8SetReturnValue(callback_info, handle); } +template <typename CallbackInfo, typename T> +inline void V8SetReturnValueFast(const CallbackInfo& callbackInfo, + NotShared<T> notShared, + const ScriptWrappable* wrappable) { + V8SetReturnValueFast(callbackInfo, notShared.View(), wrappable); +} + // Convert v8::String to a WTF::String. If the V8 string is not already // an external string then it is transformed into an external string at this // point to avoid repeated conversions. @@ -1163,6 +1177,25 @@ CORE_EXPORT v8::Local<v8::Value> FromJSONString(v8::Isolate*, const String& stringified_json, ExceptionState&); + +// Ensure that a typed array value is not backed by a SharedArrayBuffer. If it +// is, an exception will be thrown. The return value will use the NotShared +// wrapper type. +template <typename NotSharedType> +NotSharedType ToNotShared(v8::Isolate* isolate, + v8::Local<v8::Value> value, + ExceptionState& exception_state) { + using DOMTypedArray = typename NotSharedType::TypedArrayType; + DOMTypedArray* dom_typed_array = + V8TypeOf<DOMTypedArray>::Type::toImplWithTypeCheck(isolate, value); + if (dom_typed_array && dom_typed_array->IsShared()) { + exception_state.ThrowTypeError( + "The provided ArrayBufferView value must not be shared."); + return NotSharedType(); + } + return NotSharedType(dom_typed_array); +} + } // namespace blink #endif // V8Binding_h
diff --git a/third_party/WebKit/Source/bindings/modules/v8/ConditionalFeaturesForModules.cpp b/third_party/WebKit/Source/bindings/modules/v8/ConditionalFeaturesForModules.cpp index 55aa4ab..29d83a9 100644 --- a/third_party/WebKit/Source/bindings/modules/v8/ConditionalFeaturesForModules.cpp +++ b/third_party/WebKit/Source/bindings/modules/v8/ConditionalFeaturesForModules.cpp
@@ -79,10 +79,6 @@ } else if (wrapper_type_info == &V8Window::wrapperTypeInfo) { v8::Local<v8::Object> instance_object = script_state->GetContext()->Global(); - if (OriginTrials::imageCaptureEnabled(execution_context)) { - V8WindowPartial::installImageCapture(isolate, world, instance_object, - prototype_object, interface_object); - } // Mimics the [SecureContext] extended attribute. Work-around for // https://crbug.com/695123. if (OriginTrials::webUSBEnabled(execution_context) && @@ -195,13 +191,6 @@ } return; } - if (feature == "ImageCapture") { - global_instance_object = script_state->GetContext()->Global(); - V8WindowPartial::installImageCapture(isolate, world, global_instance_object, - v8::Local<v8::Object>(), - v8::Local<v8::Function>()); - return; - } if (feature == "InstalledApp") { if (context_data->GetExistingConstructorAndPrototypeForType( &V8Navigator::wrapperTypeInfo, &prototype_object,
diff --git a/third_party/WebKit/Source/bindings/scripts/v8_attributes.py b/third_party/WebKit/Source/bindings/scripts/v8_attributes.py index ecc6277f..2ab1aecf1 100644 --- a/third_party/WebKit/Source/bindings/scripts/v8_attributes.py +++ b/third_party/WebKit/Source/bindings/scripts/v8_attributes.py
@@ -286,8 +286,13 @@ cpp_value, extended_attributes=extended_attributes, script_wrappable='impl', for_main_world=for_main_world, is_static=attribute.is_static) + cpp_value_to_script_wrappable = cpp_value + if idl_type.is_array_buffer_view_or_typed_array: + cpp_value_to_script_wrappable += '.View()' + context.update({ 'cpp_value': cpp_value, + 'cpp_value_to_script_wrappable': cpp_value_to_script_wrappable, 'cpp_value_to_v8_value': idl_type.cpp_value_to_v8_value( cpp_value=cpp_value, creation_context='holder', extended_attributes=extended_attributes), @@ -318,7 +323,8 @@ expression = '%s(%s)' % (getter_name, ', '.join(arguments)) # Needed to handle getter expressions returning Type& as the # use site for |expression| expects Type*. - if attribute.idl_type.is_interface_type and len(arguments) == 0: + if (attribute.idl_type.is_interface_type and len(arguments) == 0 and + not attribute.idl_type.is_array_buffer_view_or_typed_array): return 'WTF::GetPtr(%s)' % expression return expression
diff --git a/third_party/WebKit/Source/bindings/scripts/v8_dictionary.py b/third_party/WebKit/Source/bindings/scripts/v8_dictionary.py index 66fd18f..92d310d 100644 --- a/third_party/WebKit/Source/bindings/scripts/v8_dictionary.py +++ b/third_party/WebKit/Source/bindings/scripts/v8_dictionary.py
@@ -231,6 +231,10 @@ else: header_includes.update(idl_type.impl_includes_for_type(interfaces_info)) + setter_value = 'value' + if idl_type.is_array_buffer_view_or_typed_array: + setter_value += '.View()' + return { 'cpp_default_value': cpp_default_value, 'cpp_name': cpp_name, @@ -245,4 +249,5 @@ 'nullable_indicator_name': nullable_indicator_name, 'rvalue_cpp_type': idl_type.cpp_type_args(used_as_rvalue_type=True), 'setter_name': setter_name_for_dictionary_member(member), + 'setter_value': setter_value, }
diff --git a/third_party/WebKit/Source/bindings/scripts/v8_types.py b/third_party/WebKit/Source/bindings/scripts/v8_types.py index 3e3cf39..32c6b85 100644 --- a/third_party/WebKit/Source/bindings/scripts/v8_types.py +++ b/third_party/WebKit/Source/bindings/scripts/v8_types.py
@@ -74,6 +74,9 @@ 'Uint16Array', 'Uint32Array', ]) +ARRAY_BUFFER_VIEW_AND_TYPED_ARRAY_TYPES = TYPED_ARRAY_TYPES.union(frozenset([ + 'ArrayBufferView' +])) ARRAY_BUFFER_AND_VIEW_TYPES = TYPED_ARRAY_TYPES.union(frozenset([ 'ArrayBuffer', 'ArrayBufferView', @@ -85,6 +88,9 @@ IdlType.is_array_buffer_or_view = property( lambda self: self.base_type in ARRAY_BUFFER_AND_VIEW_TYPES) +IdlType.is_array_buffer_view_or_typed_array = property( + lambda self: self.base_type in ARRAY_BUFFER_VIEW_AND_TYPED_ARRAY_TYPES) + IdlType.is_typed_array = property( lambda self: self.base_type in TYPED_ARRAY_TYPES) @@ -202,6 +208,9 @@ return 'FlexibleArrayBufferView' if base_idl_type in TYPED_ARRAY_TYPES and 'FlexibleArrayBufferView' in extended_attributes: return 'Flexible' + base_idl_type + 'View' + if base_idl_type in ARRAY_BUFFER_VIEW_AND_TYPED_ARRAY_TYPES: + if not used_in_cpp_sequence: + return cpp_template_type('NotShared', idl_type.implemented_as) if idl_type.is_interface_type: implemented_as_class = idl_type.implemented_as if raw_type or (used_as_rvalue_type and idl_type.is_garbage_collected) or not used_in_cpp_sequence: @@ -343,6 +352,7 @@ INCLUDES_FOR_TYPE = { 'object': set(), 'ArrayBufferView': set(['bindings/core/v8/V8ArrayBufferView.h', + 'core/dom/NotShared.h', 'core/dom/FlexibleArrayBufferView.h']), 'Dictionary': set(['bindings/core/v8/Dictionary.h']), 'EventHandler': set(['bindings/core/v8/V8AbstractEventListener.h', @@ -459,8 +469,8 @@ includes_for_type.add(interface_info['include_path']) if base_idl_type in INCLUDES_FOR_TYPE: includes_for_type.update(INCLUDES_FOR_TYPE[base_idl_type]) - if idl_type.is_typed_array: - return set(['core/dom/DOMTypedArray.h']) + if idl_type.is_array_buffer_view_or_typed_array: + return set(['core/dom/DOMTypedArray.h', 'core/dom/NotShared.h']) return includes_for_type @@ -519,6 +529,7 @@ return (idl_type.is_numeric_type or idl_type.is_enum or idl_type.is_dictionary or + idl_type.is_array_buffer_view_or_typed_array or idl_type.name in ('Boolean', 'ByteString', 'Date', 'Dictionary', 'USVString', 'SerializedScriptValue')) IdlType.v8_conversion_needs_exception_state = property(v8_conversion_needs_exception_state) @@ -581,7 +592,7 @@ base_idl_type = idl_type.as_union_type.name if idl_type.is_union_type else idl_type.base_type if 'FlexibleArrayBufferView' in extended_attributes: - if base_idl_type not in TYPED_ARRAY_TYPES.union(set(['ArrayBufferView'])): + if base_idl_type not in ARRAY_BUFFER_VIEW_AND_TYPED_ARRAY_TYPES: raise ValueError("Unrecognized base type for extended attribute 'FlexibleArrayBufferView': %s" % (idl_type.base_type)) base_idl_type = 'FlexibleArrayBufferView' @@ -599,10 +610,13 @@ if base_idl_type in V8_VALUE_TO_CPP_VALUE: cpp_expression_format = V8_VALUE_TO_CPP_VALUE[base_idl_type] - elif idl_type.is_array_buffer_or_view: + elif idl_type.name == 'ArrayBuffer': cpp_expression_format = ( '{v8_value}->Is{idl_type}() ? ' 'V8{idl_type}::toImpl(v8::Local<v8::{idl_type}>::Cast({v8_value})) : 0') + elif idl_type.is_array_buffer_view_or_typed_array: + this_cpp_type = idl_type.cpp_type + cpp_expression_format = ('ToNotShared<%s>({isolate}, {v8_value}, exceptionState)' % this_cpp_type) elif idl_type.is_union_type: nullable = 'UnionTypeConversionMode::kNullable' if idl_type.includes_nullable_type \ else 'UnionTypeConversionMode::kNotNullable' @@ -677,7 +691,11 @@ # meaningful if 'check_expression' is not None. return_expression = bailout_return_value - if idl_type.is_string_type or idl_type.v8_conversion_needs_exception_state: + if 'FlexibleArrayBufferView' in extended_attributes: + if idl_type.base_type not in ARRAY_BUFFER_VIEW_AND_TYPED_ARRAY_TYPES: + raise ValueError("Unrecognized base type for extended attribute 'FlexibleArrayBufferView': %s" % (idl_type.base_type)) + set_expression = cpp_value + elif idl_type.is_string_type or idl_type.v8_conversion_needs_exception_state: # Types for which conversion can fail and that need error handling. check_expression = 'exceptionState.HadException()' @@ -699,10 +717,6 @@ return { 'error_message': 'no V8 -> C++ conversion for IDL type: %s' % idl_type.name } - elif 'FlexibleArrayBufferView' in extended_attributes: - if idl_type.base_type not in TYPED_ARRAY_TYPES.union(set(['ArrayBufferView'])): - raise ValueError("Unrecognized base type for extended attribute 'FlexibleArrayBufferView': %s" % (idl_type.base_type)) - set_expression = cpp_value else: assign_expression = cpp_value
diff --git a/third_party/WebKit/Source/bindings/scripts/v8_union.py b/third_party/WebKit/Source/bindings/scripts/v8_union.py index 35477a1a..1723495 100644 --- a/third_party/WebKit/Source/bindings/scripts/v8_union.py +++ b/third_party/WebKit/Source/bindings/scripts/v8_union.py
@@ -129,7 +129,7 @@ cpp_includes.update(interface_info.get( 'dependencies_include_paths', [])) # We need complete types for IDL dictionaries in union containers. - if member.is_dictionary or member.is_typed_array: + if member.is_dictionary or member.is_array_buffer_view_or_typed_array: header_includes.update(member.includes_for_type()) else: cpp_includes.update(member.includes_for_type()) @@ -161,6 +161,7 @@ creation_context='creationContext'), 'enum_values': member.enum_values, 'is_array_buffer_or_view_type': member.is_array_buffer_or_view, + 'is_array_buffer_view_or_typed_array': member.is_array_buffer_view_or_typed_array, 'is_traceable': member.is_traceable, 'rvalue_cpp_type': member.cpp_type_args(used_as_rvalue_type=True), 'specific_type_enum': 'SpecificType' + member.name,
diff --git a/third_party/WebKit/Source/bindings/templates/attributes.cpp.tmpl b/third_party/WebKit/Source/bindings/templates/attributes.cpp.tmpl index 55fa01b..93dd7c8 100644 --- a/third_party/WebKit/Source/bindings/templates/attributes.cpp.tmpl +++ b/third_party/WebKit/Source/bindings/templates/attributes.cpp.tmpl
@@ -151,9 +151,9 @@ {% if attribute.is_keep_alive_for_gc %} // Keep the wrapper object for the return value alive as long as |this| // object is alive in order to save creation time of the wrapper object. - if ({{attribute.cpp_value}} && DOMDataStore::SetReturnValue{{world_suffix}}(info.GetReturnValue(), {{attribute.cpp_value}})) + if ({{attribute.cpp_value}} && DOMDataStore::SetReturnValue{{world_suffix}}(info.GetReturnValue(), {{attribute.cpp_value_to_script_wrappable}})) return; - v8::Local<v8::Value> v8Value(ToV8({{attribute.cpp_value}}, holder, info.GetIsolate())); + v8::Local<v8::Value> v8Value(ToV8({{attribute.cpp_value_to_script_wrappable}}, holder, info.GetIsolate())); V8PrivateProperty::GetSymbol( info.GetIsolate(), "KeepAlive#{{interface_name}}#{{attribute.name}}") .Set(holder, v8Value);
diff --git a/third_party/WebKit/Source/bindings/templates/callback_function.cpp.tmpl b/third_party/WebKit/Source/bindings/templates/callback_function.cpp.tmpl index 75d62af..65856a3 100644 --- a/third_party/WebKit/Source/bindings/templates/callback_function.cpp.tmpl +++ b/third_party/WebKit/Source/bindings/templates/callback_function.cpp.tmpl
@@ -82,8 +82,10 @@ {{cpp_class}}* NativeValueTraits<{{cpp_class}}>::NativeValue(v8::Isolate* isolate, v8::Local<v8::Value> value, ExceptionState& exceptionState) { {{cpp_class}}* nativeValue = {{cpp_class}}::Create(ScriptState::Current(isolate), value); - if (!nativeValue) - exceptionState.ThrowTypeError("Unable to convert value to {{callback_function_name}}."); + if (!nativeValue) { + exceptionState.ThrowTypeError(ExceptionMessages::FailedToConvertJSValue( + "{{callback_function_name}}")); + } return nativeValue; }
diff --git a/third_party/WebKit/Source/bindings/templates/callback_interface.cpp.tmpl b/third_party/WebKit/Source/bindings/templates/callback_interface.cpp.tmpl index c417aaa..e308643 100644 --- a/third_party/WebKit/Source/bindings/templates/callback_interface.cpp.tmpl +++ b/third_party/WebKit/Source/bindings/templates/callback_interface.cpp.tmpl
@@ -26,8 +26,8 @@ if method.idl_type == 'boolean' else 'return' %}{# void #} ExecutionContext* executionContext = ExecutionContext::From(m_scriptState.Get()); - if (!executionContext || executionContext->IsContextSuspended() || - executionContext->IsContextDestroyed()) + DCHECK(!executionContext->IsContextSuspended()); + if (!executionContext || executionContext->IsContextDestroyed()) {{return_default}}; if (!m_scriptState->ContextIsValid()) {{return_default}};
diff --git a/third_party/WebKit/Source/bindings/templates/dictionary_impl.cpp.tmpl b/third_party/WebKit/Source/bindings/templates/dictionary_impl.cpp.tmpl index f9865bb..dc7b9af 100644 --- a/third_party/WebKit/Source/bindings/templates/dictionary_impl.cpp.tmpl +++ b/third_party/WebKit/Source/bindings/templates/dictionary_impl.cpp.tmpl
@@ -33,7 +33,7 @@ return {{member.getter_expression}}; } void {{cpp_class}}::{{member.setter_name}}({{member.rvalue_cpp_type}} value) { - m_{{member.cpp_name}} = value; + m_{{member.cpp_name}} = {{member.setter_value}}; {% if member.nullable_indicator_name %} {{member.nullable_indicator_name}} = true; {% endif %}
diff --git a/third_party/WebKit/Source/bindings/templates/interface.cpp.tmpl b/third_party/WebKit/Source/bindings/templates/interface.cpp.tmpl index 289ea7e..bbd979c 100644 --- a/third_party/WebKit/Source/bindings/templates/interface.cpp.tmpl +++ b/third_party/WebKit/Source/bindings/templates/interface.cpp.tmpl
@@ -893,8 +893,10 @@ {% block native_value_traits %} {{cpp_class}}* NativeValueTraits<{{cpp_class}}>::NativeValue(v8::Isolate* isolate, v8::Local<v8::Value> value, ExceptionState& exceptionState) { {{cpp_class}}* nativeValue = {{v8_class}}::toImplWithTypeCheck(isolate, value); - if (!nativeValue) - exceptionState.ThrowTypeError("Unable to convert value to {{interface_name}}."); + if (!nativeValue) { + exceptionState.ThrowTypeError(ExceptionMessages::FailedToConvertJSValue( + "{{interface_name}}")); + } return nativeValue; }
diff --git a/third_party/WebKit/Source/bindings/templates/union_container.cpp.tmpl b/third_party/WebKit/Source/bindings/templates/union_container.cpp.tmpl index 02dca6c..e361c1b 100644 --- a/third_party/WebKit/Source/bindings/templates/union_container.cpp.tmpl +++ b/third_party/WebKit/Source/bindings/templates/union_container.cpp.tmpl
@@ -7,7 +7,13 @@ {% else %} if (V8{{member.type_name}}::hasInstance(v8Value, isolate)) { {% endif %} +{% if member.is_array_buffer_view_or_typed_array %} + {{member.cpp_local_type}} cppValue = ToNotShared<{{member.cpp_local_type}}>(isolate, v8Value, exceptionState); + if (exceptionState.HadException()) + return; +{% else %} {{member.cpp_local_type}} cppValue = V8{{member.type_name}}::toImpl(v8::Local<v8::Object>::Cast(v8Value)); +{% endif %} impl.set{{member.type_name}}(cppValue); return; } @@ -41,7 +47,11 @@ return; } {% endif %} + {% if member.is_array_buffer_view_or_typed_array %} + m_{{member.cpp_name}} = {{member.cpp_type}}(value.View()); + {% else %} m_{{member.cpp_name}} = value; + {% endif %} m_type = {{member.specific_type_enum}}; }
diff --git a/third_party/WebKit/Source/bindings/tests/idls/core/TestObject.idl b/third_party/WebKit/Source/bindings/tests/idls/core/TestObject.idl index 3757b87..704db79 100644 --- a/third_party/WebKit/Source/bindings/tests/idls/core/TestObject.idl +++ b/third_party/WebKit/Source/bindings/tests/idls/core/TestObject.idl
@@ -285,6 +285,7 @@ // Typed arrays ArrayBuffer arrayBufferMethod(); ArrayBufferView arrayBufferViewMethod(); + [RaisesException] ArrayBufferView arrayBufferViewMethodRaisesException(); Float32Array float32ArrayMethod(); Int32Array int32ArrayMethod(); Uint8Array uint8ArrayMethod();
diff --git a/third_party/WebKit/Source/bindings/tests/results/core/AnyCallbackFunctionOptionalAnyArg.cpp b/third_party/WebKit/Source/bindings/tests/results/core/AnyCallbackFunctionOptionalAnyArg.cpp index 89a9fb9..af786cba 100644 --- a/third_party/WebKit/Source/bindings/tests/results/core/AnyCallbackFunctionOptionalAnyArg.cpp +++ b/third_party/WebKit/Source/bindings/tests/results/core/AnyCallbackFunctionOptionalAnyArg.cpp
@@ -84,8 +84,10 @@ AnyCallbackFunctionOptionalAnyArg* NativeValueTraits<AnyCallbackFunctionOptionalAnyArg>::NativeValue(v8::Isolate* isolate, v8::Local<v8::Value> value, ExceptionState& exceptionState) { AnyCallbackFunctionOptionalAnyArg* nativeValue = AnyCallbackFunctionOptionalAnyArg::Create(ScriptState::Current(isolate), value); - if (!nativeValue) - exceptionState.ThrowTypeError("Unable to convert value to AnyCallbackFunctionOptionalAnyArg."); + if (!nativeValue) { + exceptionState.ThrowTypeError(ExceptionMessages::FailedToConvertJSValue( + "AnyCallbackFunctionOptionalAnyArg")); + } return nativeValue; }
diff --git a/third_party/WebKit/Source/bindings/tests/results/core/ArrayBufferOrArrayBufferViewOrDictionary.cpp b/third_party/WebKit/Source/bindings/tests/results/core/ArrayBufferOrArrayBufferViewOrDictionary.cpp index ec2b13a3..f38af45 100644 --- a/third_party/WebKit/Source/bindings/tests/results/core/ArrayBufferOrArrayBufferViewOrDictionary.cpp +++ b/third_party/WebKit/Source/bindings/tests/results/core/ArrayBufferOrArrayBufferViewOrDictionary.cpp
@@ -14,8 +14,6 @@ #include "bindings/core/v8/Dictionary.h" #include "bindings/core/v8/ToV8.h" #include "bindings/core/v8/V8ArrayBuffer.h" -#include "bindings/core/v8/V8ArrayBufferView.h" -#include "core/dom/FlexibleArrayBufferView.h" namespace blink { @@ -38,18 +36,18 @@ return container; } -TestArrayBufferView* ArrayBufferOrArrayBufferViewOrDictionary::getAsArrayBufferView() const { +NotShared<TestArrayBufferView> ArrayBufferOrArrayBufferViewOrDictionary::getAsArrayBufferView() const { DCHECK(isArrayBufferView()); return m_arrayBufferView; } -void ArrayBufferOrArrayBufferViewOrDictionary::setArrayBufferView(TestArrayBufferView* value) { +void ArrayBufferOrArrayBufferViewOrDictionary::setArrayBufferView(NotShared<TestArrayBufferView> value) { DCHECK(isNull()); - m_arrayBufferView = value; + m_arrayBufferView = Member<TestArrayBufferView>(value.View()); m_type = SpecificTypeArrayBufferView; } -ArrayBufferOrArrayBufferViewOrDictionary ArrayBufferOrArrayBufferViewOrDictionary::fromArrayBufferView(TestArrayBufferView* value) { +ArrayBufferOrArrayBufferViewOrDictionary ArrayBufferOrArrayBufferViewOrDictionary::fromArrayBufferView(NotShared<TestArrayBufferView> value) { ArrayBufferOrArrayBufferViewOrDictionary container; container.setArrayBufferView(value); return container; @@ -95,7 +93,9 @@ } if (v8Value->IsArrayBufferView()) { - TestArrayBufferView* cppValue = V8ArrayBufferView::toImpl(v8::Local<v8::Object>::Cast(v8Value)); + NotShared<TestArrayBufferView> cppValue = ToNotShared<NotShared<TestArrayBufferView>>(isolate, v8Value, exceptionState); + if (exceptionState.HadException()) + return; impl.setArrayBufferView(cppValue); return; }
diff --git a/third_party/WebKit/Source/bindings/tests/results/core/ArrayBufferOrArrayBufferViewOrDictionary.h b/third_party/WebKit/Source/bindings/tests/results/core/ArrayBufferOrArrayBufferViewOrDictionary.h index c81a1bd..826a920b 100644 --- a/third_party/WebKit/Source/bindings/tests/results/core/ArrayBufferOrArrayBufferViewOrDictionary.h +++ b/third_party/WebKit/Source/bindings/tests/results/core/ArrayBufferOrArrayBufferViewOrDictionary.h
@@ -15,14 +15,16 @@ #include "bindings/core/v8/Dictionary.h" #include "bindings/core/v8/ExceptionState.h" #include "bindings/core/v8/NativeValueTraits.h" +#include "bindings/core/v8/V8ArrayBufferView.h" #include "bindings/core/v8/V8Binding.h" #include "core/CoreExport.h" +#include "core/dom/FlexibleArrayBufferView.h" +#include "core/dom/NotShared.h" #include "platform/heap/Handle.h" namespace blink { class TestArrayBuffer; -class TestArrayBufferView; class CORE_EXPORT ArrayBufferOrArrayBufferViewOrDictionary final { DISALLOW_NEW_EXCEPT_PLACEMENT_NEW(); @@ -36,9 +38,9 @@ static ArrayBufferOrArrayBufferViewOrDictionary fromArrayBuffer(TestArrayBuffer*); bool isArrayBufferView() const { return m_type == SpecificTypeArrayBufferView; } - TestArrayBufferView* getAsArrayBufferView() const; - void setArrayBufferView(TestArrayBufferView*); - static ArrayBufferOrArrayBufferViewOrDictionary fromArrayBufferView(TestArrayBufferView*); + NotShared<TestArrayBufferView> getAsArrayBufferView() const; + void setArrayBufferView(NotShared<TestArrayBufferView>); + static ArrayBufferOrArrayBufferViewOrDictionary fromArrayBufferView(NotShared<TestArrayBufferView>); bool isDictionary() const { return m_type == SpecificTypeDictionary; } Dictionary getAsDictionary() const;
diff --git a/third_party/WebKit/Source/bindings/tests/results/core/LongCallbackFunction.cpp b/third_party/WebKit/Source/bindings/tests/results/core/LongCallbackFunction.cpp index 32ca61f..84ae62e 100644 --- a/third_party/WebKit/Source/bindings/tests/results/core/LongCallbackFunction.cpp +++ b/third_party/WebKit/Source/bindings/tests/results/core/LongCallbackFunction.cpp
@@ -88,8 +88,10 @@ LongCallbackFunction* NativeValueTraits<LongCallbackFunction>::NativeValue(v8::Isolate* isolate, v8::Local<v8::Value> value, ExceptionState& exceptionState) { LongCallbackFunction* nativeValue = LongCallbackFunction::Create(ScriptState::Current(isolate), value); - if (!nativeValue) - exceptionState.ThrowTypeError("Unable to convert value to LongCallbackFunction."); + if (!nativeValue) { + exceptionState.ThrowTypeError(ExceptionMessages::FailedToConvertJSValue( + "LongCallbackFunction")); + } return nativeValue; }
diff --git a/third_party/WebKit/Source/bindings/tests/results/core/StringOrArrayBufferOrArrayBufferView.cpp b/third_party/WebKit/Source/bindings/tests/results/core/StringOrArrayBufferOrArrayBufferView.cpp index 82ca4fc..71fb6df1 100644 --- a/third_party/WebKit/Source/bindings/tests/results/core/StringOrArrayBufferOrArrayBufferView.cpp +++ b/third_party/WebKit/Source/bindings/tests/results/core/StringOrArrayBufferOrArrayBufferView.cpp
@@ -15,8 +15,6 @@ #include "bindings/core/v8/NativeValueTraitsImpl.h" #include "bindings/core/v8/ToV8.h" #include "bindings/core/v8/V8ArrayBuffer.h" -#include "bindings/core/v8/V8ArrayBufferView.h" -#include "core/dom/FlexibleArrayBufferView.h" namespace blink { @@ -39,18 +37,18 @@ return container; } -TestArrayBufferView* StringOrArrayBufferOrArrayBufferView::getAsArrayBufferView() const { +NotShared<TestArrayBufferView> StringOrArrayBufferOrArrayBufferView::getAsArrayBufferView() const { DCHECK(isArrayBufferView()); return m_arrayBufferView; } -void StringOrArrayBufferOrArrayBufferView::setArrayBufferView(TestArrayBufferView* value) { +void StringOrArrayBufferOrArrayBufferView::setArrayBufferView(NotShared<TestArrayBufferView> value) { DCHECK(isNull()); - m_arrayBufferView = value; + m_arrayBufferView = Member<TestArrayBufferView>(value.View()); m_type = SpecificTypeArrayBufferView; } -StringOrArrayBufferOrArrayBufferView StringOrArrayBufferOrArrayBufferView::fromArrayBufferView(TestArrayBufferView* value) { +StringOrArrayBufferOrArrayBufferView StringOrArrayBufferOrArrayBufferView::fromArrayBufferView(NotShared<TestArrayBufferView> value) { StringOrArrayBufferOrArrayBufferView container; container.setArrayBufferView(value); return container; @@ -96,7 +94,9 @@ } if (v8Value->IsArrayBufferView()) { - TestArrayBufferView* cppValue = V8ArrayBufferView::toImpl(v8::Local<v8::Object>::Cast(v8Value)); + NotShared<TestArrayBufferView> cppValue = ToNotShared<NotShared<TestArrayBufferView>>(isolate, v8Value, exceptionState); + if (exceptionState.HadException()) + return; impl.setArrayBufferView(cppValue); return; }
diff --git a/third_party/WebKit/Source/bindings/tests/results/core/StringOrArrayBufferOrArrayBufferView.h b/third_party/WebKit/Source/bindings/tests/results/core/StringOrArrayBufferOrArrayBufferView.h index b04bab9..9d3c93e 100644 --- a/third_party/WebKit/Source/bindings/tests/results/core/StringOrArrayBufferOrArrayBufferView.h +++ b/third_party/WebKit/Source/bindings/tests/results/core/StringOrArrayBufferOrArrayBufferView.h
@@ -15,14 +15,16 @@ #include "bindings/core/v8/Dictionary.h" #include "bindings/core/v8/ExceptionState.h" #include "bindings/core/v8/NativeValueTraits.h" +#include "bindings/core/v8/V8ArrayBufferView.h" #include "bindings/core/v8/V8Binding.h" #include "core/CoreExport.h" +#include "core/dom/FlexibleArrayBufferView.h" +#include "core/dom/NotShared.h" #include "platform/heap/Handle.h" namespace blink { class TestArrayBuffer; -class TestArrayBufferView; class CORE_EXPORT StringOrArrayBufferOrArrayBufferView final { DISALLOW_NEW_EXCEPT_PLACEMENT_NEW(); @@ -36,9 +38,9 @@ static StringOrArrayBufferOrArrayBufferView fromArrayBuffer(TestArrayBuffer*); bool isArrayBufferView() const { return m_type == SpecificTypeArrayBufferView; } - TestArrayBufferView* getAsArrayBufferView() const; - void setArrayBufferView(TestArrayBufferView*); - static StringOrArrayBufferOrArrayBufferView fromArrayBufferView(TestArrayBufferView*); + NotShared<TestArrayBufferView> getAsArrayBufferView() const; + void setArrayBufferView(NotShared<TestArrayBufferView>); + static StringOrArrayBufferOrArrayBufferView fromArrayBufferView(NotShared<TestArrayBufferView>); bool isString() const { return m_type == SpecificTypeString; } String getAsString() const;
diff --git a/third_party/WebKit/Source/bindings/tests/results/core/StringSequenceCallbackFunctionLongSequenceArg.cpp b/third_party/WebKit/Source/bindings/tests/results/core/StringSequenceCallbackFunctionLongSequenceArg.cpp index 149073d..904a2d0 100644 --- a/third_party/WebKit/Source/bindings/tests/results/core/StringSequenceCallbackFunctionLongSequenceArg.cpp +++ b/third_party/WebKit/Source/bindings/tests/results/core/StringSequenceCallbackFunctionLongSequenceArg.cpp
@@ -87,8 +87,10 @@ StringSequenceCallbackFunctionLongSequenceArg* NativeValueTraits<StringSequenceCallbackFunctionLongSequenceArg>::NativeValue(v8::Isolate* isolate, v8::Local<v8::Value> value, ExceptionState& exceptionState) { StringSequenceCallbackFunctionLongSequenceArg* nativeValue = StringSequenceCallbackFunctionLongSequenceArg::Create(ScriptState::Current(isolate), value); - if (!nativeValue) - exceptionState.ThrowTypeError("Unable to convert value to StringSequenceCallbackFunctionLongSequenceArg."); + if (!nativeValue) { + exceptionState.ThrowTypeError(ExceptionMessages::FailedToConvertJSValue( + "StringSequenceCallbackFunctionLongSequenceArg")); + } return nativeValue; }
diff --git a/third_party/WebKit/Source/bindings/tests/results/core/TestDictionary.cpp b/third_party/WebKit/Source/bindings/tests/results/core/TestDictionary.cpp index 69af3f64..6d96d38b 100644 --- a/third_party/WebKit/Source/bindings/tests/results/core/TestDictionary.cpp +++ b/third_party/WebKit/Source/bindings/tests/results/core/TestDictionary.cpp
@@ -400,11 +400,11 @@ bool TestDictionary::hasUint8ArrayMember() const { return m_uint8ArrayMember; } -DOMUint8Array* TestDictionary::uint8ArrayMember() const { +NotShared<DOMUint8Array> TestDictionary::uint8ArrayMember() const { return m_uint8ArrayMember; } -void TestDictionary::setUint8ArrayMember(DOMUint8Array* value) { - m_uint8ArrayMember = value; +void TestDictionary::setUint8ArrayMember(NotShared<DOMUint8Array> value) { + m_uint8ArrayMember = value.View(); } bool TestDictionary::hasUnionInRecordMember() const { return m_hasUnionInRecordMember;
diff --git a/third_party/WebKit/Source/bindings/tests/results/core/TestDictionary.h b/third_party/WebKit/Source/bindings/tests/results/core/TestDictionary.h index 0c37adb0..951f536 100644 --- a/third_party/WebKit/Source/bindings/tests/results/core/TestDictionary.h +++ b/third_party/WebKit/Source/bindings/tests/results/core/TestDictionary.h
@@ -22,6 +22,7 @@ #include "bindings/tests/idls/core/TestInterface2.h" #include "core/CoreExport.h" #include "core/dom/DOMTypedArray.h" +#include "core/dom/NotShared.h" #include "core/testing/InternalDictionary.h" #include "platform/heap/Handle.h" #include "platform/wtf/Vector.h" @@ -186,8 +187,8 @@ void setTestObjectSequenceMember(const HeapVector<Member<TestObject>>&); bool hasUint8ArrayMember() const; - DOMUint8Array* uint8ArrayMember() const; - void setUint8ArrayMember(DOMUint8Array*); + NotShared<DOMUint8Array> uint8ArrayMember() const; + void setUint8ArrayMember(NotShared<DOMUint8Array>); bool hasUnionInRecordMember() const; const HeapVector<std::pair<String, LongOrBoolean>>& unionInRecordMember() const;
diff --git a/third_party/WebKit/Source/bindings/tests/results/core/TestInterface2OrUint8Array.cpp b/third_party/WebKit/Source/bindings/tests/results/core/TestInterface2OrUint8Array.cpp index daeda9dc..2fef52b 100644 --- a/third_party/WebKit/Source/bindings/tests/results/core/TestInterface2OrUint8Array.cpp +++ b/third_party/WebKit/Source/bindings/tests/results/core/TestInterface2OrUint8Array.cpp
@@ -35,18 +35,18 @@ return container; } -DOMUint8Array* TestInterface2OrUint8Array::getAsUint8Array() const { +NotShared<DOMUint8Array> TestInterface2OrUint8Array::getAsUint8Array() const { DCHECK(isUint8Array()); return m_uint8Array; } -void TestInterface2OrUint8Array::setUint8Array(DOMUint8Array* value) { +void TestInterface2OrUint8Array::setUint8Array(NotShared<DOMUint8Array> value) { DCHECK(isNull()); - m_uint8Array = value; + m_uint8Array = Member<DOMUint8Array>(value.View()); m_type = SpecificTypeUint8Array; } -TestInterface2OrUint8Array TestInterface2OrUint8Array::fromUint8Array(DOMUint8Array* value) { +TestInterface2OrUint8Array TestInterface2OrUint8Array::fromUint8Array(NotShared<DOMUint8Array> value) { TestInterface2OrUint8Array container; container.setUint8Array(value); return container; @@ -75,7 +75,9 @@ } if (v8Value->IsUint8Array()) { - DOMUint8Array* cppValue = V8Uint8Array::toImpl(v8::Local<v8::Object>::Cast(v8Value)); + NotShared<DOMUint8Array> cppValue = ToNotShared<NotShared<DOMUint8Array>>(isolate, v8Value, exceptionState); + if (exceptionState.HadException()) + return; impl.setUint8Array(cppValue); return; }
diff --git a/third_party/WebKit/Source/bindings/tests/results/core/TestInterface2OrUint8Array.h b/third_party/WebKit/Source/bindings/tests/results/core/TestInterface2OrUint8Array.h index 4192249..ae0f637 100644 --- a/third_party/WebKit/Source/bindings/tests/results/core/TestInterface2OrUint8Array.h +++ b/third_party/WebKit/Source/bindings/tests/results/core/TestInterface2OrUint8Array.h
@@ -20,6 +20,7 @@ #include "bindings/core/v8/V8Uint8Array.h" #include "core/CoreExport.h" #include "core/dom/FlexibleArrayBufferView.h" +#include "core/dom/NotShared.h" #include "platform/heap/Handle.h" namespace blink { @@ -38,9 +39,9 @@ static TestInterface2OrUint8Array fromTestInterface2(TestInterface2*); bool isUint8Array() const { return m_type == SpecificTypeUint8Array; } - DOMUint8Array* getAsUint8Array() const; - void setUint8Array(DOMUint8Array*); - static TestInterface2OrUint8Array fromUint8Array(DOMUint8Array*); + NotShared<DOMUint8Array> getAsUint8Array() const; + void setUint8Array(NotShared<DOMUint8Array>); + static TestInterface2OrUint8Array fromUint8Array(NotShared<DOMUint8Array>); TestInterface2OrUint8Array(const TestInterface2OrUint8Array&); ~TestInterface2OrUint8Array();
diff --git a/third_party/WebKit/Source/bindings/tests/results/core/V8ArrayBuffer.cpp b/third_party/WebKit/Source/bindings/tests/results/core/V8ArrayBuffer.cpp index f50da1b..598d706 100644 --- a/third_party/WebKit/Source/bindings/tests/results/core/V8ArrayBuffer.cpp +++ b/third_party/WebKit/Source/bindings/tests/results/core/V8ArrayBuffer.cpp
@@ -81,8 +81,10 @@ TestArrayBuffer* NativeValueTraits<TestArrayBuffer>::NativeValue(v8::Isolate* isolate, v8::Local<v8::Value> value, ExceptionState& exceptionState) { TestArrayBuffer* nativeValue = V8ArrayBuffer::toImplWithTypeCheck(isolate, value); - if (!nativeValue) - exceptionState.ThrowTypeError("Unable to convert value to ArrayBuffer."); + if (!nativeValue) { + exceptionState.ThrowTypeError(ExceptionMessages::FailedToConvertJSValue( + "ArrayBuffer")); + } return nativeValue; }
diff --git a/third_party/WebKit/Source/bindings/tests/results/core/V8ArrayBufferView.cpp b/third_party/WebKit/Source/bindings/tests/results/core/V8ArrayBufferView.cpp index df9d2ee9..9c0bdf0 100644 --- a/third_party/WebKit/Source/bindings/tests/results/core/V8ArrayBufferView.cpp +++ b/third_party/WebKit/Source/bindings/tests/results/core/V8ArrayBufferView.cpp
@@ -101,8 +101,10 @@ TestArrayBufferView* NativeValueTraits<TestArrayBufferView>::NativeValue(v8::Isolate* isolate, v8::Local<v8::Value> value, ExceptionState& exceptionState) { TestArrayBufferView* nativeValue = V8ArrayBufferView::toImplWithTypeCheck(isolate, value); - if (!nativeValue) - exceptionState.ThrowTypeError("Unable to convert value to ArrayBufferView."); + if (!nativeValue) { + exceptionState.ThrowTypeError(ExceptionMessages::FailedToConvertJSValue( + "ArrayBufferView")); + } return nativeValue; }
diff --git a/third_party/WebKit/Source/bindings/tests/results/core/V8DataView.cpp b/third_party/WebKit/Source/bindings/tests/results/core/V8DataView.cpp index 21cb4fd..0e9a43d 100644 --- a/third_party/WebKit/Source/bindings/tests/results/core/V8DataView.cpp +++ b/third_party/WebKit/Source/bindings/tests/results/core/V8DataView.cpp
@@ -81,8 +81,10 @@ TestDataView* NativeValueTraits<TestDataView>::NativeValue(v8::Isolate* isolate, v8::Local<v8::Value> value, ExceptionState& exceptionState) { TestDataView* nativeValue = V8DataView::toImplWithTypeCheck(isolate, value); - if (!nativeValue) - exceptionState.ThrowTypeError("Unable to convert value to DataView."); + if (!nativeValue) { + exceptionState.ThrowTypeError(ExceptionMessages::FailedToConvertJSValue( + "DataView")); + } return nativeValue; }
diff --git a/third_party/WebKit/Source/bindings/tests/results/core/V8DataView.h b/third_party/WebKit/Source/bindings/tests/results/core/V8DataView.h index c45d0b5..e27504c3 100644 --- a/third_party/WebKit/Source/bindings/tests/results/core/V8DataView.h +++ b/third_party/WebKit/Source/bindings/tests/results/core/V8DataView.h
@@ -23,6 +23,7 @@ #include "bindings/tests/idls/core/TestDataView.h" #include "core/CoreExport.h" #include "core/dom/FlexibleArrayBufferView.h" +#include "core/dom/NotShared.h" #include "platform/heap/Handle.h" namespace blink {
diff --git a/third_party/WebKit/Source/bindings/tests/results/core/V8SVGTestInterface.cpp b/third_party/WebKit/Source/bindings/tests/results/core/V8SVGTestInterface.cpp index ee7f6b1..12b1de4 100644 --- a/third_party/WebKit/Source/bindings/tests/results/core/V8SVGTestInterface.cpp +++ b/third_party/WebKit/Source/bindings/tests/results/core/V8SVGTestInterface.cpp
@@ -132,8 +132,10 @@ SVGTestInterface* NativeValueTraits<SVGTestInterface>::NativeValue(v8::Isolate* isolate, v8::Local<v8::Value> value, ExceptionState& exceptionState) { SVGTestInterface* nativeValue = V8SVGTestInterface::toImplWithTypeCheck(isolate, value); - if (!nativeValue) - exceptionState.ThrowTypeError("Unable to convert value to SVGTestInterface."); + if (!nativeValue) { + exceptionState.ThrowTypeError(ExceptionMessages::FailedToConvertJSValue( + "SVGTestInterface")); + } return nativeValue; }
diff --git a/third_party/WebKit/Source/bindings/tests/results/core/V8TestCallbackFunctions.cpp b/third_party/WebKit/Source/bindings/tests/results/core/V8TestCallbackFunctions.cpp index f2664b0..10a3fc8 100644 --- a/third_party/WebKit/Source/bindings/tests/results/core/V8TestCallbackFunctions.cpp +++ b/third_party/WebKit/Source/bindings/tests/results/core/V8TestCallbackFunctions.cpp
@@ -336,8 +336,10 @@ TestCallbackFunctions* NativeValueTraits<TestCallbackFunctions>::NativeValue(v8::Isolate* isolate, v8::Local<v8::Value> value, ExceptionState& exceptionState) { TestCallbackFunctions* nativeValue = V8TestCallbackFunctions::toImplWithTypeCheck(isolate, value); - if (!nativeValue) - exceptionState.ThrowTypeError("Unable to convert value to TestCallbackFunctions."); + if (!nativeValue) { + exceptionState.ThrowTypeError(ExceptionMessages::FailedToConvertJSValue( + "TestCallbackFunctions")); + } return nativeValue; }
diff --git a/third_party/WebKit/Source/bindings/tests/results/core/V8TestCallbackInterface.cpp b/third_party/WebKit/Source/bindings/tests/results/core/V8TestCallbackInterface.cpp index 7435cec9..69ea2fa 100644 --- a/third_party/WebKit/Source/bindings/tests/results/core/V8TestCallbackInterface.cpp +++ b/third_party/WebKit/Source/bindings/tests/results/core/V8TestCallbackInterface.cpp
@@ -37,8 +37,8 @@ void V8TestCallbackInterface::voidMethod() { ExecutionContext* executionContext = ExecutionContext::From(m_scriptState.Get()); - if (!executionContext || executionContext->IsContextSuspended() || - executionContext->IsContextDestroyed()) + DCHECK(!executionContext->IsContextSuspended()); + if (!executionContext || executionContext->IsContextDestroyed()) return; if (!m_scriptState->ContextIsValid()) return; @@ -59,8 +59,8 @@ bool V8TestCallbackInterface::booleanMethod() { ExecutionContext* executionContext = ExecutionContext::From(m_scriptState.Get()); - if (!executionContext || executionContext->IsContextSuspended() || - executionContext->IsContextDestroyed()) + DCHECK(!executionContext->IsContextSuspended()); + if (!executionContext || executionContext->IsContextDestroyed()) return true; if (!m_scriptState->ContextIsValid()) return true; @@ -84,8 +84,8 @@ void V8TestCallbackInterface::voidMethodBooleanArg(bool boolArg) { ExecutionContext* executionContext = ExecutionContext::From(m_scriptState.Get()); - if (!executionContext || executionContext->IsContextSuspended() || - executionContext->IsContextDestroyed()) + DCHECK(!executionContext->IsContextSuspended()); + if (!executionContext || executionContext->IsContextDestroyed()) return; if (!m_scriptState->ContextIsValid()) return; @@ -107,8 +107,8 @@ void V8TestCallbackInterface::voidMethodSequenceArg(const HeapVector<Member<TestInterfaceEmpty>>& sequenceArg) { ExecutionContext* executionContext = ExecutionContext::From(m_scriptState.Get()); - if (!executionContext || executionContext->IsContextSuspended() || - executionContext->IsContextDestroyed()) + DCHECK(!executionContext->IsContextSuspended()); + if (!executionContext || executionContext->IsContextDestroyed()) return; if (!m_scriptState->ContextIsValid()) return; @@ -130,8 +130,8 @@ void V8TestCallbackInterface::voidMethodFloatArg(float floatArg) { ExecutionContext* executionContext = ExecutionContext::From(m_scriptState.Get()); - if (!executionContext || executionContext->IsContextSuspended() || - executionContext->IsContextDestroyed()) + DCHECK(!executionContext->IsContextSuspended()); + if (!executionContext || executionContext->IsContextDestroyed()) return; if (!m_scriptState->ContextIsValid()) return; @@ -153,8 +153,8 @@ void V8TestCallbackInterface::voidMethodTestInterfaceEmptyArg(TestInterfaceEmpty* testInterfaceEmptyArg) { ExecutionContext* executionContext = ExecutionContext::From(m_scriptState.Get()); - if (!executionContext || executionContext->IsContextSuspended() || - executionContext->IsContextDestroyed()) + DCHECK(!executionContext->IsContextSuspended()); + if (!executionContext || executionContext->IsContextDestroyed()) return; if (!m_scriptState->ContextIsValid()) return; @@ -176,8 +176,8 @@ void V8TestCallbackInterface::voidMethodTestInterfaceEmptyStringArg(TestInterfaceEmpty* testInterfaceEmptyArg, const String& stringArg) { ExecutionContext* executionContext = ExecutionContext::From(m_scriptState.Get()); - if (!executionContext || executionContext->IsContextSuspended() || - executionContext->IsContextDestroyed()) + DCHECK(!executionContext->IsContextSuspended()); + if (!executionContext || executionContext->IsContextDestroyed()) return; if (!m_scriptState->ContextIsValid()) return; @@ -200,8 +200,8 @@ void V8TestCallbackInterface::callbackWithThisValueVoidMethodStringArg(ScriptValue thisValue, const String& stringArg) { ExecutionContext* executionContext = ExecutionContext::From(m_scriptState.Get()); - if (!executionContext || executionContext->IsContextSuspended() || - executionContext->IsContextDestroyed()) + DCHECK(!executionContext->IsContextSuspended()); + if (!executionContext || executionContext->IsContextDestroyed()) return; if (!m_scriptState->ContextIsValid()) return;
diff --git a/third_party/WebKit/Source/bindings/tests/results/core/V8TestConstants.cpp b/third_party/WebKit/Source/bindings/tests/results/core/V8TestConstants.cpp index 4757657..ea03305 100644 --- a/third_party/WebKit/Source/bindings/tests/results/core/V8TestConstants.cpp +++ b/third_party/WebKit/Source/bindings/tests/results/core/V8TestConstants.cpp
@@ -199,8 +199,10 @@ TestConstants* NativeValueTraits<TestConstants>::NativeValue(v8::Isolate* isolate, v8::Local<v8::Value> value, ExceptionState& exceptionState) { TestConstants* nativeValue = V8TestConstants::toImplWithTypeCheck(isolate, value); - if (!nativeValue) - exceptionState.ThrowTypeError("Unable to convert value to TestConstants."); + if (!nativeValue) { + exceptionState.ThrowTypeError(ExceptionMessages::FailedToConvertJSValue( + "TestConstants")); + } return nativeValue; }
diff --git a/third_party/WebKit/Source/bindings/tests/results/core/V8TestDictionary.cpp b/third_party/WebKit/Source/bindings/tests/results/core/V8TestDictionary.cpp index d41d7e2..f841653f 100644 --- a/third_party/WebKit/Source/bindings/tests/results/core/V8TestDictionary.cpp +++ b/third_party/WebKit/Source/bindings/tests/results/core/V8TestDictionary.cpp
@@ -26,6 +26,7 @@ #include "bindings/core/v8/V8TestObject.h" #include "bindings/core/v8/V8Uint8Array.h" #include "core/dom/FlexibleArrayBufferView.h" +#include "core/dom/NotShared.h" #include "core/frame/Deprecation.h" #include "platform/RuntimeEnabledFeatures.h" @@ -643,7 +644,9 @@ if (uint8ArrayMemberValue.IsEmpty() || uint8ArrayMemberValue->IsUndefined()) { // Do nothing. } else { - DOMUint8Array* uint8ArrayMember = uint8ArrayMemberValue->IsUint8Array() ? V8Uint8Array::toImpl(v8::Local<v8::Uint8Array>::Cast(uint8ArrayMemberValue)) : 0; + NotShared<DOMUint8Array> uint8ArrayMember = ToNotShared<NotShared<DOMUint8Array>>(isolate, uint8ArrayMemberValue, exceptionState); + if (exceptionState.HadException()) + return; if (!uint8ArrayMember) { exceptionState.ThrowTypeError("member uint8ArrayMember is not of type Uint8Array."); return;
diff --git a/third_party/WebKit/Source/bindings/tests/results/core/V8TestException.cpp b/third_party/WebKit/Source/bindings/tests/results/core/V8TestException.cpp index 7910b468..2049192b 100644 --- a/third_party/WebKit/Source/bindings/tests/results/core/V8TestException.cpp +++ b/third_party/WebKit/Source/bindings/tests/results/core/V8TestException.cpp
@@ -172,8 +172,10 @@ TestException* NativeValueTraits<TestException>::NativeValue(v8::Isolate* isolate, v8::Local<v8::Value> value, ExceptionState& exceptionState) { TestException* nativeValue = V8TestException::toImplWithTypeCheck(isolate, value); - if (!nativeValue) - exceptionState.ThrowTypeError("Unable to convert value to TestException."); + if (!nativeValue) { + exceptionState.ThrowTypeError(ExceptionMessages::FailedToConvertJSValue( + "TestException")); + } return nativeValue; }
diff --git a/third_party/WebKit/Source/bindings/tests/results/core/V8TestIntegerIndexed.cpp b/third_party/WebKit/Source/bindings/tests/results/core/V8TestIntegerIndexed.cpp index 5e19ae7..d812c6c3 100644 --- a/third_party/WebKit/Source/bindings/tests/results/core/V8TestIntegerIndexed.cpp +++ b/third_party/WebKit/Source/bindings/tests/results/core/V8TestIntegerIndexed.cpp
@@ -215,8 +215,10 @@ TestIntegerIndexed* NativeValueTraits<TestIntegerIndexed>::NativeValue(v8::Isolate* isolate, v8::Local<v8::Value> value, ExceptionState& exceptionState) { TestIntegerIndexed* nativeValue = V8TestIntegerIndexed::toImplWithTypeCheck(isolate, value); - if (!nativeValue) - exceptionState.ThrowTypeError("Unable to convert value to TestIntegerIndexed."); + if (!nativeValue) { + exceptionState.ThrowTypeError(ExceptionMessages::FailedToConvertJSValue( + "TestIntegerIndexed")); + } return nativeValue; }
diff --git a/third_party/WebKit/Source/bindings/tests/results/core/V8TestIntegerIndexedGlobal.cpp b/third_party/WebKit/Source/bindings/tests/results/core/V8TestIntegerIndexedGlobal.cpp index 5f4b6f0f..b77637e 100644 --- a/third_party/WebKit/Source/bindings/tests/results/core/V8TestIntegerIndexedGlobal.cpp +++ b/third_party/WebKit/Source/bindings/tests/results/core/V8TestIntegerIndexedGlobal.cpp
@@ -236,8 +236,10 @@ TestIntegerIndexedGlobal* NativeValueTraits<TestIntegerIndexedGlobal>::NativeValue(v8::Isolate* isolate, v8::Local<v8::Value> value, ExceptionState& exceptionState) { TestIntegerIndexedGlobal* nativeValue = V8TestIntegerIndexedGlobal::toImplWithTypeCheck(isolate, value); - if (!nativeValue) - exceptionState.ThrowTypeError("Unable to convert value to TestIntegerIndexedGlobal."); + if (!nativeValue) { + exceptionState.ThrowTypeError(ExceptionMessages::FailedToConvertJSValue( + "TestIntegerIndexedGlobal")); + } return nativeValue; }
diff --git a/third_party/WebKit/Source/bindings/tests/results/core/V8TestIntegerIndexedPrimaryGlobal.cpp b/third_party/WebKit/Source/bindings/tests/results/core/V8TestIntegerIndexedPrimaryGlobal.cpp index 1d7a347..12835f1 100644 --- a/third_party/WebKit/Source/bindings/tests/results/core/V8TestIntegerIndexedPrimaryGlobal.cpp +++ b/third_party/WebKit/Source/bindings/tests/results/core/V8TestIntegerIndexedPrimaryGlobal.cpp
@@ -236,8 +236,10 @@ TestIntegerIndexedPrimaryGlobal* NativeValueTraits<TestIntegerIndexedPrimaryGlobal>::NativeValue(v8::Isolate* isolate, v8::Local<v8::Value> value, ExceptionState& exceptionState) { TestIntegerIndexedPrimaryGlobal* nativeValue = V8TestIntegerIndexedPrimaryGlobal::toImplWithTypeCheck(isolate, value); - if (!nativeValue) - exceptionState.ThrowTypeError("Unable to convert value to TestIntegerIndexedPrimaryGlobal."); + if (!nativeValue) { + exceptionState.ThrowTypeError(ExceptionMessages::FailedToConvertJSValue( + "TestIntegerIndexedPrimaryGlobal")); + } return nativeValue; }
diff --git a/third_party/WebKit/Source/bindings/tests/results/core/V8TestInterface.cpp b/third_party/WebKit/Source/bindings/tests/results/core/V8TestInterface.cpp index 6901e10..fff5df3 100644 --- a/third_party/WebKit/Source/bindings/tests/results/core/V8TestInterface.cpp +++ b/third_party/WebKit/Source/bindings/tests/results/core/V8TestInterface.cpp
@@ -3062,8 +3062,10 @@ TestInterfaceImplementation* NativeValueTraits<TestInterfaceImplementation>::NativeValue(v8::Isolate* isolate, v8::Local<v8::Value> value, ExceptionState& exceptionState) { TestInterfaceImplementation* nativeValue = V8TestInterface::toImplWithTypeCheck(isolate, value); - if (!nativeValue) - exceptionState.ThrowTypeError("Unable to convert value to TestInterface."); + if (!nativeValue) { + exceptionState.ThrowTypeError(ExceptionMessages::FailedToConvertJSValue( + "TestInterface")); + } return nativeValue; }
diff --git a/third_party/WebKit/Source/bindings/tests/results/core/V8TestInterface2.cpp b/third_party/WebKit/Source/bindings/tests/results/core/V8TestInterface2.cpp index 68098e3f..9cbc1bf8 100644 --- a/third_party/WebKit/Source/bindings/tests/results/core/V8TestInterface2.cpp +++ b/third_party/WebKit/Source/bindings/tests/results/core/V8TestInterface2.cpp
@@ -665,8 +665,10 @@ TestInterface2* NativeValueTraits<TestInterface2>::NativeValue(v8::Isolate* isolate, v8::Local<v8::Value> value, ExceptionState& exceptionState) { TestInterface2* nativeValue = V8TestInterface2::toImplWithTypeCheck(isolate, value); - if (!nativeValue) - exceptionState.ThrowTypeError("Unable to convert value to TestInterface2."); + if (!nativeValue) { + exceptionState.ThrowTypeError(ExceptionMessages::FailedToConvertJSValue( + "TestInterface2")); + } return nativeValue; }
diff --git a/third_party/WebKit/Source/bindings/tests/results/core/V8TestInterface3.cpp b/third_party/WebKit/Source/bindings/tests/results/core/V8TestInterface3.cpp index 1a171d0..03caa8b6 100644 --- a/third_party/WebKit/Source/bindings/tests/results/core/V8TestInterface3.cpp +++ b/third_party/WebKit/Source/bindings/tests/results/core/V8TestInterface3.cpp
@@ -222,8 +222,10 @@ TestInterface3* NativeValueTraits<TestInterface3>::NativeValue(v8::Isolate* isolate, v8::Local<v8::Value> value, ExceptionState& exceptionState) { TestInterface3* nativeValue = V8TestInterface3::toImplWithTypeCheck(isolate, value); - if (!nativeValue) - exceptionState.ThrowTypeError("Unable to convert value to TestInterface3."); + if (!nativeValue) { + exceptionState.ThrowTypeError(ExceptionMessages::FailedToConvertJSValue( + "TestInterface3")); + } return nativeValue; }
diff --git a/third_party/WebKit/Source/bindings/tests/results/core/V8TestInterfaceCheckSecurity.cpp b/third_party/WebKit/Source/bindings/tests/results/core/V8TestInterfaceCheckSecurity.cpp index 942a43905..ae947c347 100644 --- a/third_party/WebKit/Source/bindings/tests/results/core/V8TestInterfaceCheckSecurity.cpp +++ b/third_party/WebKit/Source/bindings/tests/results/core/V8TestInterfaceCheckSecurity.cpp
@@ -556,8 +556,10 @@ TestInterfaceCheckSecurity* NativeValueTraits<TestInterfaceCheckSecurity>::NativeValue(v8::Isolate* isolate, v8::Local<v8::Value> value, ExceptionState& exceptionState) { TestInterfaceCheckSecurity* nativeValue = V8TestInterfaceCheckSecurity::toImplWithTypeCheck(isolate, value); - if (!nativeValue) - exceptionState.ThrowTypeError("Unable to convert value to TestInterfaceCheckSecurity."); + if (!nativeValue) { + exceptionState.ThrowTypeError(ExceptionMessages::FailedToConvertJSValue( + "TestInterfaceCheckSecurity")); + } return nativeValue; }
diff --git a/third_party/WebKit/Source/bindings/tests/results/core/V8TestInterfaceConstructor.cpp b/third_party/WebKit/Source/bindings/tests/results/core/V8TestInterfaceConstructor.cpp index 314daf6..00b22cb 100644 --- a/third_party/WebKit/Source/bindings/tests/results/core/V8TestInterfaceConstructor.cpp +++ b/third_party/WebKit/Source/bindings/tests/results/core/V8TestInterfaceConstructor.cpp
@@ -444,8 +444,10 @@ TestInterfaceConstructor* NativeValueTraits<TestInterfaceConstructor>::NativeValue(v8::Isolate* isolate, v8::Local<v8::Value> value, ExceptionState& exceptionState) { TestInterfaceConstructor* nativeValue = V8TestInterfaceConstructor::toImplWithTypeCheck(isolate, value); - if (!nativeValue) - exceptionState.ThrowTypeError("Unable to convert value to TestInterfaceConstructor."); + if (!nativeValue) { + exceptionState.ThrowTypeError(ExceptionMessages::FailedToConvertJSValue( + "TestInterfaceConstructor")); + } return nativeValue; }
diff --git a/third_party/WebKit/Source/bindings/tests/results/core/V8TestInterfaceConstructor2.cpp b/third_party/WebKit/Source/bindings/tests/results/core/V8TestInterfaceConstructor2.cpp index b1e83bc..c7802d3 100644 --- a/third_party/WebKit/Source/bindings/tests/results/core/V8TestInterfaceConstructor2.cpp +++ b/third_party/WebKit/Source/bindings/tests/results/core/V8TestInterfaceConstructor2.cpp
@@ -268,8 +268,10 @@ TestInterfaceConstructor2* NativeValueTraits<TestInterfaceConstructor2>::NativeValue(v8::Isolate* isolate, v8::Local<v8::Value> value, ExceptionState& exceptionState) { TestInterfaceConstructor2* nativeValue = V8TestInterfaceConstructor2::toImplWithTypeCheck(isolate, value); - if (!nativeValue) - exceptionState.ThrowTypeError("Unable to convert value to TestInterfaceConstructor2."); + if (!nativeValue) { + exceptionState.ThrowTypeError(ExceptionMessages::FailedToConvertJSValue( + "TestInterfaceConstructor2")); + } return nativeValue; }
diff --git a/third_party/WebKit/Source/bindings/tests/results/core/V8TestInterfaceConstructor3.cpp b/third_party/WebKit/Source/bindings/tests/results/core/V8TestInterfaceConstructor3.cpp index d960556..ca090d78 100644 --- a/third_party/WebKit/Source/bindings/tests/results/core/V8TestInterfaceConstructor3.cpp +++ b/third_party/WebKit/Source/bindings/tests/results/core/V8TestInterfaceConstructor3.cpp
@@ -121,8 +121,10 @@ TestInterfaceConstructor3* NativeValueTraits<TestInterfaceConstructor3>::NativeValue(v8::Isolate* isolate, v8::Local<v8::Value> value, ExceptionState& exceptionState) { TestInterfaceConstructor3* nativeValue = V8TestInterfaceConstructor3::toImplWithTypeCheck(isolate, value); - if (!nativeValue) - exceptionState.ThrowTypeError("Unable to convert value to TestInterfaceConstructor3."); + if (!nativeValue) { + exceptionState.ThrowTypeError(ExceptionMessages::FailedToConvertJSValue( + "TestInterfaceConstructor3")); + } return nativeValue; }
diff --git a/third_party/WebKit/Source/bindings/tests/results/core/V8TestInterfaceConstructor4.cpp b/third_party/WebKit/Source/bindings/tests/results/core/V8TestInterfaceConstructor4.cpp index 292e415..5b99fde1 100644 --- a/third_party/WebKit/Source/bindings/tests/results/core/V8TestInterfaceConstructor4.cpp +++ b/third_party/WebKit/Source/bindings/tests/results/core/V8TestInterfaceConstructor4.cpp
@@ -154,8 +154,10 @@ TestInterfaceConstructor4* NativeValueTraits<TestInterfaceConstructor4>::NativeValue(v8::Isolate* isolate, v8::Local<v8::Value> value, ExceptionState& exceptionState) { TestInterfaceConstructor4* nativeValue = V8TestInterfaceConstructor4::toImplWithTypeCheck(isolate, value); - if (!nativeValue) - exceptionState.ThrowTypeError("Unable to convert value to TestInterfaceConstructor4."); + if (!nativeValue) { + exceptionState.ThrowTypeError(ExceptionMessages::FailedToConvertJSValue( + "TestInterfaceConstructor4")); + } return nativeValue; }
diff --git a/third_party/WebKit/Source/bindings/tests/results/core/V8TestInterfaceCustomConstructor.cpp b/third_party/WebKit/Source/bindings/tests/results/core/V8TestInterfaceCustomConstructor.cpp index e57fb80d..550ce5017 100644 --- a/third_party/WebKit/Source/bindings/tests/results/core/V8TestInterfaceCustomConstructor.cpp +++ b/third_party/WebKit/Source/bindings/tests/results/core/V8TestInterfaceCustomConstructor.cpp
@@ -102,8 +102,10 @@ TestInterfaceCustomConstructor* NativeValueTraits<TestInterfaceCustomConstructor>::NativeValue(v8::Isolate* isolate, v8::Local<v8::Value> value, ExceptionState& exceptionState) { TestInterfaceCustomConstructor* nativeValue = V8TestInterfaceCustomConstructor::toImplWithTypeCheck(isolate, value); - if (!nativeValue) - exceptionState.ThrowTypeError("Unable to convert value to TestInterfaceCustomConstructor."); + if (!nativeValue) { + exceptionState.ThrowTypeError(ExceptionMessages::FailedToConvertJSValue( + "TestInterfaceCustomConstructor")); + } return nativeValue; }
diff --git a/third_party/WebKit/Source/bindings/tests/results/core/V8TestInterfaceDocument.cpp b/third_party/WebKit/Source/bindings/tests/results/core/V8TestInterfaceDocument.cpp index acf18ea3..907e876 100644 --- a/third_party/WebKit/Source/bindings/tests/results/core/V8TestInterfaceDocument.cpp +++ b/third_party/WebKit/Source/bindings/tests/results/core/V8TestInterfaceDocument.cpp
@@ -134,8 +134,10 @@ TestInterfaceDocument* NativeValueTraits<TestInterfaceDocument>::NativeValue(v8::Isolate* isolate, v8::Local<v8::Value> value, ExceptionState& exceptionState) { TestInterfaceDocument* nativeValue = V8TestInterfaceDocument::toImplWithTypeCheck(isolate, value); - if (!nativeValue) - exceptionState.ThrowTypeError("Unable to convert value to TestInterfaceDocument."); + if (!nativeValue) { + exceptionState.ThrowTypeError(ExceptionMessages::FailedToConvertJSValue( + "TestInterfaceDocument")); + } return nativeValue; }
diff --git a/third_party/WebKit/Source/bindings/tests/results/core/V8TestInterfaceEmpty.cpp b/third_party/WebKit/Source/bindings/tests/results/core/V8TestInterfaceEmpty.cpp index 2dd0a69..b150665 100644 --- a/third_party/WebKit/Source/bindings/tests/results/core/V8TestInterfaceEmpty.cpp +++ b/third_party/WebKit/Source/bindings/tests/results/core/V8TestInterfaceEmpty.cpp
@@ -85,8 +85,10 @@ TestInterfaceEmpty* NativeValueTraits<TestInterfaceEmpty>::NativeValue(v8::Isolate* isolate, v8::Local<v8::Value> value, ExceptionState& exceptionState) { TestInterfaceEmpty* nativeValue = V8TestInterfaceEmpty::toImplWithTypeCheck(isolate, value); - if (!nativeValue) - exceptionState.ThrowTypeError("Unable to convert value to TestInterfaceEmpty."); + if (!nativeValue) { + exceptionState.ThrowTypeError(ExceptionMessages::FailedToConvertJSValue( + "TestInterfaceEmpty")); + } return nativeValue; }
diff --git a/third_party/WebKit/Source/bindings/tests/results/core/V8TestInterfaceEventInitConstructor.cpp b/third_party/WebKit/Source/bindings/tests/results/core/V8TestInterfaceEventInitConstructor.cpp index 0b3a76e20..6c656cc 100644 --- a/third_party/WebKit/Source/bindings/tests/results/core/V8TestInterfaceEventInitConstructor.cpp +++ b/third_party/WebKit/Source/bindings/tests/results/core/V8TestInterfaceEventInitConstructor.cpp
@@ -164,8 +164,10 @@ TestInterfaceEventInitConstructor* NativeValueTraits<TestInterfaceEventInitConstructor>::NativeValue(v8::Isolate* isolate, v8::Local<v8::Value> value, ExceptionState& exceptionState) { TestInterfaceEventInitConstructor* nativeValue = V8TestInterfaceEventInitConstructor::toImplWithTypeCheck(isolate, value); - if (!nativeValue) - exceptionState.ThrowTypeError("Unable to convert value to TestInterfaceEventInitConstructor."); + if (!nativeValue) { + exceptionState.ThrowTypeError(ExceptionMessages::FailedToConvertJSValue( + "TestInterfaceEventInitConstructor")); + } return nativeValue; }
diff --git a/third_party/WebKit/Source/bindings/tests/results/core/V8TestInterfaceEventTarget.cpp b/third_party/WebKit/Source/bindings/tests/results/core/V8TestInterfaceEventTarget.cpp index 09a0848..2c36e3dc 100644 --- a/third_party/WebKit/Source/bindings/tests/results/core/V8TestInterfaceEventTarget.cpp +++ b/third_party/WebKit/Source/bindings/tests/results/core/V8TestInterfaceEventTarget.cpp
@@ -161,8 +161,10 @@ TestInterfaceEventTarget* NativeValueTraits<TestInterfaceEventTarget>::NativeValue(v8::Isolate* isolate, v8::Local<v8::Value> value, ExceptionState& exceptionState) { TestInterfaceEventTarget* nativeValue = V8TestInterfaceEventTarget::toImplWithTypeCheck(isolate, value); - if (!nativeValue) - exceptionState.ThrowTypeError("Unable to convert value to TestInterfaceEventTarget."); + if (!nativeValue) { + exceptionState.ThrowTypeError(ExceptionMessages::FailedToConvertJSValue( + "TestInterfaceEventTarget")); + } return nativeValue; }
diff --git a/third_party/WebKit/Source/bindings/tests/results/core/V8TestInterfaceGarbageCollected.cpp b/third_party/WebKit/Source/bindings/tests/results/core/V8TestInterfaceGarbageCollected.cpp index 82c05801..c0292cdd 100644 --- a/third_party/WebKit/Source/bindings/tests/results/core/V8TestInterfaceGarbageCollected.cpp +++ b/third_party/WebKit/Source/bindings/tests/results/core/V8TestInterfaceGarbageCollected.cpp
@@ -415,8 +415,10 @@ TestInterfaceGarbageCollected* NativeValueTraits<TestInterfaceGarbageCollected>::NativeValue(v8::Isolate* isolate, v8::Local<v8::Value> value, ExceptionState& exceptionState) { TestInterfaceGarbageCollected* nativeValue = V8TestInterfaceGarbageCollected::toImplWithTypeCheck(isolate, value); - if (!nativeValue) - exceptionState.ThrowTypeError("Unable to convert value to TestInterfaceGarbageCollected."); + if (!nativeValue) { + exceptionState.ThrowTypeError(ExceptionMessages::FailedToConvertJSValue( + "TestInterfaceGarbageCollected")); + } return nativeValue; }
diff --git a/third_party/WebKit/Source/bindings/tests/results/core/V8TestInterfaceNamedConstructor.cpp b/third_party/WebKit/Source/bindings/tests/results/core/V8TestInterfaceNamedConstructor.cpp index 022892a..59f04aa0 100644 --- a/third_party/WebKit/Source/bindings/tests/results/core/V8TestInterfaceNamedConstructor.cpp +++ b/third_party/WebKit/Source/bindings/tests/results/core/V8TestInterfaceNamedConstructor.cpp
@@ -237,8 +237,10 @@ TestInterfaceNamedConstructor* NativeValueTraits<TestInterfaceNamedConstructor>::NativeValue(v8::Isolate* isolate, v8::Local<v8::Value> value, ExceptionState& exceptionState) { TestInterfaceNamedConstructor* nativeValue = V8TestInterfaceNamedConstructor::toImplWithTypeCheck(isolate, value); - if (!nativeValue) - exceptionState.ThrowTypeError("Unable to convert value to TestInterfaceNamedConstructor."); + if (!nativeValue) { + exceptionState.ThrowTypeError(ExceptionMessages::FailedToConvertJSValue( + "TestInterfaceNamedConstructor")); + } return nativeValue; }
diff --git a/third_party/WebKit/Source/bindings/tests/results/core/V8TestInterfaceNamedConstructor2.cpp b/third_party/WebKit/Source/bindings/tests/results/core/V8TestInterfaceNamedConstructor2.cpp index eadd365..5260443 100644 --- a/third_party/WebKit/Source/bindings/tests/results/core/V8TestInterfaceNamedConstructor2.cpp +++ b/third_party/WebKit/Source/bindings/tests/results/core/V8TestInterfaceNamedConstructor2.cpp
@@ -172,8 +172,10 @@ TestInterfaceNamedConstructor2* NativeValueTraits<TestInterfaceNamedConstructor2>::NativeValue(v8::Isolate* isolate, v8::Local<v8::Value> value, ExceptionState& exceptionState) { TestInterfaceNamedConstructor2* nativeValue = V8TestInterfaceNamedConstructor2::toImplWithTypeCheck(isolate, value); - if (!nativeValue) - exceptionState.ThrowTypeError("Unable to convert value to TestInterfaceNamedConstructor2."); + if (!nativeValue) { + exceptionState.ThrowTypeError(ExceptionMessages::FailedToConvertJSValue( + "TestInterfaceNamedConstructor2")); + } return nativeValue; }
diff --git a/third_party/WebKit/Source/bindings/tests/results/core/V8TestInterfaceNode.cpp b/third_party/WebKit/Source/bindings/tests/results/core/V8TestInterfaceNode.cpp index d111f07..d137329 100644 --- a/third_party/WebKit/Source/bindings/tests/results/core/V8TestInterfaceNode.cpp +++ b/third_party/WebKit/Source/bindings/tests/results/core/V8TestInterfaceNode.cpp
@@ -401,8 +401,10 @@ TestInterfaceNode* NativeValueTraits<TestInterfaceNode>::NativeValue(v8::Isolate* isolate, v8::Local<v8::Value> value, ExceptionState& exceptionState) { TestInterfaceNode* nativeValue = V8TestInterfaceNode::toImplWithTypeCheck(isolate, value); - if (!nativeValue) - exceptionState.ThrowTypeError("Unable to convert value to TestInterfaceNode."); + if (!nativeValue) { + exceptionState.ThrowTypeError(ExceptionMessages::FailedToConvertJSValue( + "TestInterfaceNode")); + } return nativeValue; }
diff --git a/third_party/WebKit/Source/bindings/tests/results/core/V8TestInterfaceOriginTrialEnabled.cpp b/third_party/WebKit/Source/bindings/tests/results/core/V8TestInterfaceOriginTrialEnabled.cpp index e9276f80..a3a161d 100644 --- a/third_party/WebKit/Source/bindings/tests/results/core/V8TestInterfaceOriginTrialEnabled.cpp +++ b/third_party/WebKit/Source/bindings/tests/results/core/V8TestInterfaceOriginTrialEnabled.cpp
@@ -317,8 +317,10 @@ TestInterfaceOriginTrialEnabled* NativeValueTraits<TestInterfaceOriginTrialEnabled>::NativeValue(v8::Isolate* isolate, v8::Local<v8::Value> value, ExceptionState& exceptionState) { TestInterfaceOriginTrialEnabled* nativeValue = V8TestInterfaceOriginTrialEnabled::toImplWithTypeCheck(isolate, value); - if (!nativeValue) - exceptionState.ThrowTypeError("Unable to convert value to TestInterfaceOriginTrialEnabled."); + if (!nativeValue) { + exceptionState.ThrowTypeError(ExceptionMessages::FailedToConvertJSValue( + "TestInterfaceOriginTrialEnabled")); + } return nativeValue; }
diff --git a/third_party/WebKit/Source/bindings/tests/results/core/V8TestInterfaceSecureContext.cpp b/third_party/WebKit/Source/bindings/tests/results/core/V8TestInterfaceSecureContext.cpp index 562e4491..28bcd5f 100644 --- a/third_party/WebKit/Source/bindings/tests/results/core/V8TestInterfaceSecureContext.cpp +++ b/third_party/WebKit/Source/bindings/tests/results/core/V8TestInterfaceSecureContext.cpp
@@ -382,8 +382,10 @@ TestInterfaceSecureContext* NativeValueTraits<TestInterfaceSecureContext>::NativeValue(v8::Isolate* isolate, v8::Local<v8::Value> value, ExceptionState& exceptionState) { TestInterfaceSecureContext* nativeValue = V8TestInterfaceSecureContext::toImplWithTypeCheck(isolate, value); - if (!nativeValue) - exceptionState.ThrowTypeError("Unable to convert value to TestInterfaceSecureContext."); + if (!nativeValue) { + exceptionState.ThrowTypeError(ExceptionMessages::FailedToConvertJSValue( + "TestInterfaceSecureContext")); + } return nativeValue; }
diff --git a/third_party/WebKit/Source/bindings/tests/results/core/V8TestNode.cpp b/third_party/WebKit/Source/bindings/tests/results/core/V8TestNode.cpp index 261e59d..53ac540 100644 --- a/third_party/WebKit/Source/bindings/tests/results/core/V8TestNode.cpp +++ b/third_party/WebKit/Source/bindings/tests/results/core/V8TestNode.cpp
@@ -257,8 +257,10 @@ TestNode* NativeValueTraits<TestNode>::NativeValue(v8::Isolate* isolate, v8::Local<v8::Value> value, ExceptionState& exceptionState) { TestNode* nativeValue = V8TestNode::toImplWithTypeCheck(isolate, value); - if (!nativeValue) - exceptionState.ThrowTypeError("Unable to convert value to TestNode."); + if (!nativeValue) { + exceptionState.ThrowTypeError(ExceptionMessages::FailedToConvertJSValue( + "TestNode")); + } return nativeValue; }
diff --git a/third_party/WebKit/Source/bindings/tests/results/core/V8TestObject.cpp b/third_party/WebKit/Source/bindings/tests/results/core/V8TestObject.cpp index b0e8d99..32f4791 100644 --- a/third_party/WebKit/Source/bindings/tests/results/core/V8TestObject.cpp +++ b/third_party/WebKit/Source/bindings/tests/results/core/V8TestObject.cpp
@@ -61,6 +61,7 @@ #include "core/dom/DOMArrayBufferBase.h" #include "core/dom/Document.h" #include "core/dom/FlexibleArrayBufferView.h" +#include "core/dom/NotShared.h" #include "core/dom/TagCollection.h" #include "core/dom/custom/V0CustomElementProcessingStack.h" #include "core/frame/Deprecation.h" @@ -1099,7 +1100,7 @@ TestObject* impl = V8TestObject::toImpl(holder); - V8SetReturnValueFast(info, WTF::GetPtr(impl->float32ArrayAttribute()), impl); + V8SetReturnValueFast(info, impl->float32ArrayAttribute(), impl); } static void float32ArrayAttributeAttributeSetter(v8::Local<v8::Value> v8Value, const v8::FunctionCallbackInfo<v8::Value>& info) { @@ -1112,7 +1113,9 @@ ExceptionState exceptionState(isolate, ExceptionState::kSetterContext, "TestObject", "float32ArrayAttribute"); // Prepare the value to be set. - DOMFloat32Array* cppValue = v8Value->IsFloat32Array() ? V8Float32Array::toImpl(v8::Local<v8::Float32Array>::Cast(v8Value)) : 0; + NotShared<DOMFloat32Array> cppValue = ToNotShared<NotShared<DOMFloat32Array>>(info.GetIsolate(), v8Value, exceptionState); + if (exceptionState.HadException()) + return; // Type check per: http://heycam.github.io/webidl/#es-interface if (!cppValue) { @@ -1128,7 +1131,7 @@ TestObject* impl = V8TestObject::toImpl(holder); - V8SetReturnValueFast(info, WTF::GetPtr(impl->uint8ArrayAttribute()), impl); + V8SetReturnValueFast(info, impl->uint8ArrayAttribute(), impl); } static void uint8ArrayAttributeAttributeSetter(v8::Local<v8::Value> v8Value, const v8::FunctionCallbackInfo<v8::Value>& info) { @@ -1141,7 +1144,9 @@ ExceptionState exceptionState(isolate, ExceptionState::kSetterContext, "TestObject", "uint8ArrayAttribute"); // Prepare the value to be set. - DOMUint8Array* cppValue = v8Value->IsUint8Array() ? V8Uint8Array::toImpl(v8::Local<v8::Uint8Array>::Cast(v8Value)) : 0; + NotShared<DOMUint8Array> cppValue = ToNotShared<NotShared<DOMUint8Array>>(info.GetIsolate(), v8Value, exceptionState); + if (exceptionState.HadException()) + return; // Type check per: http://heycam.github.io/webidl/#es-interface if (!cppValue) { @@ -4663,6 +4668,18 @@ V8SetReturnValue(info, impl->arrayBufferViewMethod()); } +static void arrayBufferViewMethodRaisesExceptionMethod(const v8::FunctionCallbackInfo<v8::Value>& info) { + ExceptionState exceptionState(info.GetIsolate(), ExceptionState::kExecutionContext, "TestObject", "arrayBufferViewMethodRaisesException"); + + TestObject* impl = V8TestObject::toImpl(info.Holder()); + + NotShared<TestArrayBufferView> result = impl->arrayBufferViewMethodRaisesException(exceptionState); + if (exceptionState.HadException()) { + return; + } + V8SetReturnValue(info, result); +} + static void float32ArrayMethodMethod(const v8::FunctionCallbackInfo<v8::Value>& info) { TestObject* impl = V8TestObject::toImpl(info.Holder()); @@ -4709,7 +4726,7 @@ } TestArrayBuffer* arrayBufferArg; - arrayBufferArg = info[0]->IsArrayBuffer() ? V8ArrayBuffer::toImpl(v8::Local<v8::ArrayBuffer>::Cast(info[0])) : 0; + arrayBufferArg = V8ArrayBuffer::toImplWithTypeCheck(info.GetIsolate(), info[0]); if (!arrayBufferArg && !IsUndefinedOrNull(info[0])) { V8ThrowException::ThrowTypeError(info.GetIsolate(), ExceptionMessages::FailedToExecute("voidMethodArrayBufferOrNullArg", "TestObject", "parameter 1 is not of type 'ArrayBuffer'.")); @@ -4720,17 +4737,21 @@ } static void voidMethodArrayBufferViewArgMethod(const v8::FunctionCallbackInfo<v8::Value>& info) { + ExceptionState exceptionState(info.GetIsolate(), ExceptionState::kExecutionContext, "TestObject", "voidMethodArrayBufferViewArg"); + TestObject* impl = V8TestObject::toImpl(info.Holder()); if (UNLIKELY(info.Length() < 1)) { - V8ThrowException::ThrowTypeError(info.GetIsolate(), ExceptionMessages::FailedToExecute("voidMethodArrayBufferViewArg", "TestObject", ExceptionMessages::NotEnoughArguments(1, info.Length()))); + exceptionState.ThrowTypeError(ExceptionMessages::NotEnoughArguments(1, info.Length())); return; } - TestArrayBufferView* arrayBufferViewArg; - arrayBufferViewArg = info[0]->IsArrayBufferView() ? V8ArrayBufferView::toImpl(v8::Local<v8::ArrayBufferView>::Cast(info[0])) : 0; + NotShared<TestArrayBufferView> arrayBufferViewArg; + arrayBufferViewArg = ToNotShared<NotShared<TestArrayBufferView>>(info.GetIsolate(), info[0], exceptionState); + if (exceptionState.HadException()) + return; if (!arrayBufferViewArg) { - V8ThrowException::ThrowTypeError(info.GetIsolate(), ExceptionMessages::FailedToExecute("voidMethodArrayBufferViewArg", "TestObject", "parameter 1 is not of type 'ArrayBufferView'.")); + exceptionState.ThrowTypeError("parameter 1 is not of type 'ArrayBufferView'."); return; } @@ -4739,17 +4760,19 @@ } static void voidMethodFlexibleArrayBufferViewArgMethod(const v8::FunctionCallbackInfo<v8::Value>& info) { + ExceptionState exceptionState(info.GetIsolate(), ExceptionState::kExecutionContext, "TestObject", "voidMethodFlexibleArrayBufferViewArg"); + TestObject* impl = V8TestObject::toImpl(info.Holder()); if (UNLIKELY(info.Length() < 1)) { - V8ThrowException::ThrowTypeError(info.GetIsolate(), ExceptionMessages::FailedToExecute("voidMethodFlexibleArrayBufferViewArg", "TestObject", ExceptionMessages::NotEnoughArguments(1, info.Length()))); + exceptionState.ThrowTypeError(ExceptionMessages::NotEnoughArguments(1, info.Length())); return; } FlexibleArrayBufferView arrayBufferViewArg; ToFlexibleArrayBufferView(info.GetIsolate(), info[0], arrayBufferViewArg, allocateFlexibleArrayBufferViewStorage(info[0])); if (!arrayBufferViewArg) { - V8ThrowException::ThrowTypeError(info.GetIsolate(), ExceptionMessages::FailedToExecute("voidMethodFlexibleArrayBufferViewArg", "TestObject", "parameter 1 is not of type 'ArrayBufferView'.")); + exceptionState.ThrowTypeError("parameter 1 is not of type 'ArrayBufferView'."); return; } @@ -4758,17 +4781,19 @@ } static void voidMethodFlexibleArrayBufferViewTypedArgMethod(const v8::FunctionCallbackInfo<v8::Value>& info) { + ExceptionState exceptionState(info.GetIsolate(), ExceptionState::kExecutionContext, "TestObject", "voidMethodFlexibleArrayBufferViewTypedArg"); + TestObject* impl = V8TestObject::toImpl(info.Holder()); if (UNLIKELY(info.Length() < 1)) { - V8ThrowException::ThrowTypeError(info.GetIsolate(), ExceptionMessages::FailedToExecute("voidMethodFlexibleArrayBufferViewTypedArg", "TestObject", ExceptionMessages::NotEnoughArguments(1, info.Length()))); + exceptionState.ThrowTypeError(ExceptionMessages::NotEnoughArguments(1, info.Length())); return; } FlexibleFloat32ArrayView typedArrayBufferViewArg; ToFlexibleArrayBufferView(info.GetIsolate(), info[0], typedArrayBufferViewArg, allocateFlexibleArrayBufferViewStorage(info[0])); if (!typedArrayBufferViewArg) { - V8ThrowException::ThrowTypeError(info.GetIsolate(), ExceptionMessages::FailedToExecute("voidMethodFlexibleArrayBufferViewTypedArg", "TestObject", "parameter 1 is not of type 'Float32Array'.")); + exceptionState.ThrowTypeError("parameter 1 is not of type 'Float32Array'."); return; } @@ -4777,17 +4802,21 @@ } static void voidMethodFloat32ArrayArgMethod(const v8::FunctionCallbackInfo<v8::Value>& info) { + ExceptionState exceptionState(info.GetIsolate(), ExceptionState::kExecutionContext, "TestObject", "voidMethodFloat32ArrayArg"); + TestObject* impl = V8TestObject::toImpl(info.Holder()); if (UNLIKELY(info.Length() < 1)) { - V8ThrowException::ThrowTypeError(info.GetIsolate(), ExceptionMessages::FailedToExecute("voidMethodFloat32ArrayArg", "TestObject", ExceptionMessages::NotEnoughArguments(1, info.Length()))); + exceptionState.ThrowTypeError(ExceptionMessages::NotEnoughArguments(1, info.Length())); return; } - DOMFloat32Array* float32ArrayArg; - float32ArrayArg = info[0]->IsFloat32Array() ? V8Float32Array::toImpl(v8::Local<v8::Float32Array>::Cast(info[0])) : 0; + NotShared<DOMFloat32Array> float32ArrayArg; + float32ArrayArg = ToNotShared<NotShared<DOMFloat32Array>>(info.GetIsolate(), info[0], exceptionState); + if (exceptionState.HadException()) + return; if (!float32ArrayArg) { - V8ThrowException::ThrowTypeError(info.GetIsolate(), ExceptionMessages::FailedToExecute("voidMethodFloat32ArrayArg", "TestObject", "parameter 1 is not of type 'Float32Array'.")); + exceptionState.ThrowTypeError("parameter 1 is not of type 'Float32Array'."); return; } @@ -4796,17 +4825,21 @@ } static void voidMethodInt32ArrayArgMethod(const v8::FunctionCallbackInfo<v8::Value>& info) { + ExceptionState exceptionState(info.GetIsolate(), ExceptionState::kExecutionContext, "TestObject", "voidMethodInt32ArrayArg"); + TestObject* impl = V8TestObject::toImpl(info.Holder()); if (UNLIKELY(info.Length() < 1)) { - V8ThrowException::ThrowTypeError(info.GetIsolate(), ExceptionMessages::FailedToExecute("voidMethodInt32ArrayArg", "TestObject", ExceptionMessages::NotEnoughArguments(1, info.Length()))); + exceptionState.ThrowTypeError(ExceptionMessages::NotEnoughArguments(1, info.Length())); return; } - DOMInt32Array* int32ArrayArg; - int32ArrayArg = info[0]->IsInt32Array() ? V8Int32Array::toImpl(v8::Local<v8::Int32Array>::Cast(info[0])) : 0; + NotShared<DOMInt32Array> int32ArrayArg; + int32ArrayArg = ToNotShared<NotShared<DOMInt32Array>>(info.GetIsolate(), info[0], exceptionState); + if (exceptionState.HadException()) + return; if (!int32ArrayArg) { - V8ThrowException::ThrowTypeError(info.GetIsolate(), ExceptionMessages::FailedToExecute("voidMethodInt32ArrayArg", "TestObject", "parameter 1 is not of type 'Int32Array'.")); + exceptionState.ThrowTypeError("parameter 1 is not of type 'Int32Array'."); return; } @@ -4815,17 +4848,21 @@ } static void voidMethodUint8ArrayArgMethod(const v8::FunctionCallbackInfo<v8::Value>& info) { + ExceptionState exceptionState(info.GetIsolate(), ExceptionState::kExecutionContext, "TestObject", "voidMethodUint8ArrayArg"); + TestObject* impl = V8TestObject::toImpl(info.Holder()); if (UNLIKELY(info.Length() < 1)) { - V8ThrowException::ThrowTypeError(info.GetIsolate(), ExceptionMessages::FailedToExecute("voidMethodUint8ArrayArg", "TestObject", ExceptionMessages::NotEnoughArguments(1, info.Length()))); + exceptionState.ThrowTypeError(ExceptionMessages::NotEnoughArguments(1, info.Length())); return; } - DOMUint8Array* uint8ArrayArg; - uint8ArrayArg = info[0]->IsUint8Array() ? V8Uint8Array::toImpl(v8::Local<v8::Uint8Array>::Cast(info[0])) : 0; + NotShared<DOMUint8Array> uint8ArrayArg; + uint8ArrayArg = ToNotShared<NotShared<DOMUint8Array>>(info.GetIsolate(), info[0], exceptionState); + if (exceptionState.HadException()) + return; if (!uint8ArrayArg) { - V8ThrowException::ThrowTypeError(info.GetIsolate(), ExceptionMessages::FailedToExecute("voidMethodUint8ArrayArg", "TestObject", "parameter 1 is not of type 'Uint8Array'.")); + exceptionState.ThrowTypeError("parameter 1 is not of type 'Uint8Array'."); return; } @@ -10904,6 +10941,10 @@ TestObjectV8Internal::arrayBufferViewMethodMethod(info); } +void V8TestObject::arrayBufferViewMethodRaisesExceptionMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info) { + TestObjectV8Internal::arrayBufferViewMethodRaisesExceptionMethod(info); +} + void V8TestObject::float32ArrayMethodMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info) { TestObjectV8Internal::float32ArrayMethodMethod(info); } @@ -12010,6 +12051,7 @@ {"voidMethodNodeArg", V8TestObject::voidMethodNodeArgMethodCallback, 1, v8::None, V8DOMConfiguration::kOnPrototype, V8DOMConfiguration::kCheckHolder, V8DOMConfiguration::kDoNotCheckAccess, V8DOMConfiguration::kAllWorlds}, {"arrayBufferMethod", V8TestObject::arrayBufferMethodMethodCallback, 0, v8::None, V8DOMConfiguration::kOnPrototype, V8DOMConfiguration::kCheckHolder, V8DOMConfiguration::kDoNotCheckAccess, V8DOMConfiguration::kAllWorlds}, {"arrayBufferViewMethod", V8TestObject::arrayBufferViewMethodMethodCallback, 0, v8::None, V8DOMConfiguration::kOnPrototype, V8DOMConfiguration::kCheckHolder, V8DOMConfiguration::kDoNotCheckAccess, V8DOMConfiguration::kAllWorlds}, + {"arrayBufferViewMethodRaisesException", V8TestObject::arrayBufferViewMethodRaisesExceptionMethodCallback, 0, v8::None, V8DOMConfiguration::kOnPrototype, V8DOMConfiguration::kCheckHolder, V8DOMConfiguration::kDoNotCheckAccess, V8DOMConfiguration::kAllWorlds}, {"float32ArrayMethod", V8TestObject::float32ArrayMethodMethodCallback, 0, v8::None, V8DOMConfiguration::kOnPrototype, V8DOMConfiguration::kCheckHolder, V8DOMConfiguration::kDoNotCheckAccess, V8DOMConfiguration::kAllWorlds}, {"int32ArrayMethod", V8TestObject::int32ArrayMethodMethodCallback, 0, v8::None, V8DOMConfiguration::kOnPrototype, V8DOMConfiguration::kCheckHolder, V8DOMConfiguration::kDoNotCheckAccess, V8DOMConfiguration::kAllWorlds}, {"uint8ArrayMethod", V8TestObject::uint8ArrayMethodMethodCallback, 0, v8::None, V8DOMConfiguration::kOnPrototype, V8DOMConfiguration::kCheckHolder, V8DOMConfiguration::kDoNotCheckAccess, V8DOMConfiguration::kAllWorlds}, @@ -12342,8 +12384,10 @@ TestObject* NativeValueTraits<TestObject>::NativeValue(v8::Isolate* isolate, v8::Local<v8::Value> value, ExceptionState& exceptionState) { TestObject* nativeValue = V8TestObject::toImplWithTypeCheck(isolate, value); - if (!nativeValue) - exceptionState.ThrowTypeError("Unable to convert value to TestObject."); + if (!nativeValue) { + exceptionState.ThrowTypeError(ExceptionMessages::FailedToConvertJSValue( + "TestObject")); + } return nativeValue; }
diff --git a/third_party/WebKit/Source/bindings/tests/results/core/V8TestObject.h b/third_party/WebKit/Source/bindings/tests/results/core/V8TestObject.h index 39b5333..b4e77b9 100644 --- a/third_party/WebKit/Source/bindings/tests/results/core/V8TestObject.h +++ b/third_party/WebKit/Source/bindings/tests/results/core/V8TestObject.h
@@ -425,6 +425,7 @@ CORE_EXPORT static void voidMethodNodeArgMethodCallback(const v8::FunctionCallbackInfo<v8::Value>&); CORE_EXPORT static void arrayBufferMethodMethodCallback(const v8::FunctionCallbackInfo<v8::Value>&); CORE_EXPORT static void arrayBufferViewMethodMethodCallback(const v8::FunctionCallbackInfo<v8::Value>&); + CORE_EXPORT static void arrayBufferViewMethodRaisesExceptionMethodCallback(const v8::FunctionCallbackInfo<v8::Value>&); CORE_EXPORT static void float32ArrayMethodMethodCallback(const v8::FunctionCallbackInfo<v8::Value>&); CORE_EXPORT static void int32ArrayMethodMethodCallback(const v8::FunctionCallbackInfo<v8::Value>&); CORE_EXPORT static void uint8ArrayMethodMethodCallback(const v8::FunctionCallbackInfo<v8::Value>&);
diff --git a/third_party/WebKit/Source/bindings/tests/results/core/V8TestSpecialOperations.cpp b/third_party/WebKit/Source/bindings/tests/results/core/V8TestSpecialOperations.cpp index 8173b94..a91db457 100644 --- a/third_party/WebKit/Source/bindings/tests/results/core/V8TestSpecialOperations.cpp +++ b/third_party/WebKit/Source/bindings/tests/results/core/V8TestSpecialOperations.cpp
@@ -214,8 +214,10 @@ TestSpecialOperations* NativeValueTraits<TestSpecialOperations>::NativeValue(v8::Isolate* isolate, v8::Local<v8::Value> value, ExceptionState& exceptionState) { TestSpecialOperations* nativeValue = V8TestSpecialOperations::toImplWithTypeCheck(isolate, value); - if (!nativeValue) - exceptionState.ThrowTypeError("Unable to convert value to TestSpecialOperations."); + if (!nativeValue) { + exceptionState.ThrowTypeError(ExceptionMessages::FailedToConvertJSValue( + "TestSpecialOperations")); + } return nativeValue; }
diff --git a/third_party/WebKit/Source/bindings/tests/results/core/V8TestSpecialOperationsNotEnumerable.cpp b/third_party/WebKit/Source/bindings/tests/results/core/V8TestSpecialOperationsNotEnumerable.cpp index 48c66545..03542db6 100644 --- a/third_party/WebKit/Source/bindings/tests/results/core/V8TestSpecialOperationsNotEnumerable.cpp +++ b/third_party/WebKit/Source/bindings/tests/results/core/V8TestSpecialOperationsNotEnumerable.cpp
@@ -128,8 +128,10 @@ TestSpecialOperationsNotEnumerable* NativeValueTraits<TestSpecialOperationsNotEnumerable>::NativeValue(v8::Isolate* isolate, v8::Local<v8::Value> value, ExceptionState& exceptionState) { TestSpecialOperationsNotEnumerable* nativeValue = V8TestSpecialOperationsNotEnumerable::toImplWithTypeCheck(isolate, value); - if (!nativeValue) - exceptionState.ThrowTypeError("Unable to convert value to TestSpecialOperationsNotEnumerable."); + if (!nativeValue) { + exceptionState.ThrowTypeError(ExceptionMessages::FailedToConvertJSValue( + "TestSpecialOperationsNotEnumerable")); + } return nativeValue; }
diff --git a/third_party/WebKit/Source/bindings/tests/results/core/V8TestTypedefs.cpp b/third_party/WebKit/Source/bindings/tests/results/core/V8TestTypedefs.cpp index b47994a..f8bc673 100644 --- a/third_party/WebKit/Source/bindings/tests/results/core/V8TestTypedefs.cpp +++ b/third_party/WebKit/Source/bindings/tests/results/core/V8TestTypedefs.cpp
@@ -532,8 +532,10 @@ TestTypedefs* NativeValueTraits<TestTypedefs>::NativeValue(v8::Isolate* isolate, v8::Local<v8::Value> value, ExceptionState& exceptionState) { TestTypedefs* nativeValue = V8TestTypedefs::toImplWithTypeCheck(isolate, value); - if (!nativeValue) - exceptionState.ThrowTypeError("Unable to convert value to TestTypedefs."); + if (!nativeValue) { + exceptionState.ThrowTypeError(ExceptionMessages::FailedToConvertJSValue( + "TestTypedefs")); + } return nativeValue; }
diff --git a/third_party/WebKit/Source/bindings/tests/results/core/V8Uint8ClampedArray.cpp b/third_party/WebKit/Source/bindings/tests/results/core/V8Uint8ClampedArray.cpp index ae096db7..9bfcf56b 100644 --- a/third_party/WebKit/Source/bindings/tests/results/core/V8Uint8ClampedArray.cpp +++ b/third_party/WebKit/Source/bindings/tests/results/core/V8Uint8ClampedArray.cpp
@@ -74,8 +74,10 @@ TestUint8ClampedArray* NativeValueTraits<TestUint8ClampedArray>::NativeValue(v8::Isolate* isolate, v8::Local<v8::Value> value, ExceptionState& exceptionState) { TestUint8ClampedArray* nativeValue = V8Uint8ClampedArray::toImplWithTypeCheck(isolate, value); - if (!nativeValue) - exceptionState.ThrowTypeError("Unable to convert value to Uint8ClampedArray."); + if (!nativeValue) { + exceptionState.ThrowTypeError(ExceptionMessages::FailedToConvertJSValue( + "Uint8ClampedArray")); + } return nativeValue; }
diff --git a/third_party/WebKit/Source/bindings/tests/results/core/V8Uint8ClampedArray.h b/third_party/WebKit/Source/bindings/tests/results/core/V8Uint8ClampedArray.h index 5595eed..806bac0 100644 --- a/third_party/WebKit/Source/bindings/tests/results/core/V8Uint8ClampedArray.h +++ b/third_party/WebKit/Source/bindings/tests/results/core/V8Uint8ClampedArray.h
@@ -23,6 +23,7 @@ #include "core/CoreExport.h" #include "core/dom/DOMTypedArray.h" #include "core/dom/FlexibleArrayBufferView.h" +#include "core/dom/NotShared.h" #include "platform/heap/Handle.h" namespace blink {
diff --git a/third_party/WebKit/Source/bindings/tests/results/core/VoidCallbackFunction.cpp b/third_party/WebKit/Source/bindings/tests/results/core/VoidCallbackFunction.cpp index 162383d..e0f871c 100644 --- a/third_party/WebKit/Source/bindings/tests/results/core/VoidCallbackFunction.cpp +++ b/third_party/WebKit/Source/bindings/tests/results/core/VoidCallbackFunction.cpp
@@ -80,8 +80,10 @@ VoidCallbackFunction* NativeValueTraits<VoidCallbackFunction>::NativeValue(v8::Isolate* isolate, v8::Local<v8::Value> value, ExceptionState& exceptionState) { VoidCallbackFunction* nativeValue = VoidCallbackFunction::Create(ScriptState::Current(isolate), value); - if (!nativeValue) - exceptionState.ThrowTypeError("Unable to convert value to VoidCallbackFunction."); + if (!nativeValue) { + exceptionState.ThrowTypeError(ExceptionMessages::FailedToConvertJSValue( + "VoidCallbackFunction")); + } return nativeValue; }
diff --git a/third_party/WebKit/Source/bindings/tests/results/core/VoidCallbackFunctionInterfaceArg.cpp b/third_party/WebKit/Source/bindings/tests/results/core/VoidCallbackFunctionInterfaceArg.cpp index 4f51ed91b..1d7c61b 100644 --- a/third_party/WebKit/Source/bindings/tests/results/core/VoidCallbackFunctionInterfaceArg.cpp +++ b/third_party/WebKit/Source/bindings/tests/results/core/VoidCallbackFunctionInterfaceArg.cpp
@@ -82,8 +82,10 @@ VoidCallbackFunctionInterfaceArg* NativeValueTraits<VoidCallbackFunctionInterfaceArg>::NativeValue(v8::Isolate* isolate, v8::Local<v8::Value> value, ExceptionState& exceptionState) { VoidCallbackFunctionInterfaceArg* nativeValue = VoidCallbackFunctionInterfaceArg::Create(ScriptState::Current(isolate), value); - if (!nativeValue) - exceptionState.ThrowTypeError("Unable to convert value to VoidCallbackFunctionInterfaceArg."); + if (!nativeValue) { + exceptionState.ThrowTypeError(ExceptionMessages::FailedToConvertJSValue( + "VoidCallbackFunctionInterfaceArg")); + } return nativeValue; }
diff --git a/third_party/WebKit/Source/bindings/tests/results/core/VoidCallbackFunctionTypedef.cpp b/third_party/WebKit/Source/bindings/tests/results/core/VoidCallbackFunctionTypedef.cpp index bb6480bf..c366b8840 100644 --- a/third_party/WebKit/Source/bindings/tests/results/core/VoidCallbackFunctionTypedef.cpp +++ b/third_party/WebKit/Source/bindings/tests/results/core/VoidCallbackFunctionTypedef.cpp
@@ -83,8 +83,10 @@ VoidCallbackFunctionTypedef* NativeValueTraits<VoidCallbackFunctionTypedef>::NativeValue(v8::Isolate* isolate, v8::Local<v8::Value> value, ExceptionState& exceptionState) { VoidCallbackFunctionTypedef* nativeValue = VoidCallbackFunctionTypedef::Create(ScriptState::Current(isolate), value); - if (!nativeValue) - exceptionState.ThrowTypeError("Unable to convert value to VoidCallbackFunctionTypedef."); + if (!nativeValue) { + exceptionState.ThrowTypeError(ExceptionMessages::FailedToConvertJSValue( + "VoidCallbackFunctionTypedef")); + } return nativeValue; }
diff --git a/third_party/WebKit/Source/bindings/tests/results/modules/V8TestInterface5.cpp b/third_party/WebKit/Source/bindings/tests/results/modules/V8TestInterface5.cpp index bc00c37..c451091 100644 --- a/third_party/WebKit/Source/bindings/tests/results/modules/V8TestInterface5.cpp +++ b/third_party/WebKit/Source/bindings/tests/results/modules/V8TestInterface5.cpp
@@ -879,8 +879,10 @@ TestInterface5Implementation* NativeValueTraits<TestInterface5Implementation>::NativeValue(v8::Isolate* isolate, v8::Local<v8::Value> value, ExceptionState& exceptionState) { TestInterface5Implementation* nativeValue = V8TestInterface5::toImplWithTypeCheck(isolate, value); - if (!nativeValue) - exceptionState.ThrowTypeError("Unable to convert value to TestInterface5."); + if (!nativeValue) { + exceptionState.ThrowTypeError(ExceptionMessages::FailedToConvertJSValue( + "TestInterface5")); + } return nativeValue; }
diff --git a/third_party/WebKit/Source/bindings/tests/results/modules/VoidCallbackFunctionModules.cpp b/third_party/WebKit/Source/bindings/tests/results/modules/VoidCallbackFunctionModules.cpp index 0b89961..fdfd5fef 100644 --- a/third_party/WebKit/Source/bindings/tests/results/modules/VoidCallbackFunctionModules.cpp +++ b/third_party/WebKit/Source/bindings/tests/results/modules/VoidCallbackFunctionModules.cpp
@@ -80,8 +80,10 @@ VoidCallbackFunctionModules* NativeValueTraits<VoidCallbackFunctionModules>::NativeValue(v8::Isolate* isolate, v8::Local<v8::Value> value, ExceptionState& exceptionState) { VoidCallbackFunctionModules* nativeValue = VoidCallbackFunctionModules::Create(ScriptState::Current(isolate), value); - if (!nativeValue) - exceptionState.ThrowTypeError("Unable to convert value to VoidCallbackFunctionModules."); + if (!nativeValue) { + exceptionState.ThrowTypeError(ExceptionMessages::FailedToConvertJSValue( + "VoidCallbackFunctionModules")); + } return nativeValue; }
diff --git a/third_party/WebKit/Source/build/scripts/make_computed_style_base.py b/third_party/WebKit/Source/build/scripts/make_computed_style_base.py index 29475a0a..3043c71 100755 --- a/third_party/WebKit/Source/build/scripts/make_computed_style_base.py +++ b/third_party/WebKit/Source/build/scripts/make_computed_style_base.py
@@ -58,19 +58,19 @@ 'inherited': False, 'independent': False}, # These properties only have generated storage, and their methods are handwritten in ComputedStyle. # TODO(shend): Remove these fields and delete the 'storage_only' template. - {'name': 'EmptyState', 'field_template': 'storage_only', 'size': 1, 'default_value': 'false', + {'name': 'EmptyState', 'field_template': 'storage_only', 'field_size': 1, 'default_value': 'false', 'type_name': 'bool', 'inherited': False, 'independent': False}, - {'name': 'StyleType', 'field_template': 'storage_only', 'size': 6, 'default_value': '0', + {'name': 'StyleType', 'field_template': 'storage_only', 'field_size': 6, 'default_value': '0', 'type_name': 'PseudoId', 'inherited': False, 'independent': False}, - {'name': 'PseudoBits', 'field_template': 'storage_only', 'size': 8, 'default_value': 'kPseudoIdNone', + {'name': 'PseudoBits', 'field_template': 'storage_only', 'field_size': 8, 'default_value': 'kPseudoIdNone', 'type_name': 'PseudoId', 'inherited': False, 'independent': False}, # True if 'underline solid' is the only text decoration on this element. - {'name': 'HasSimpleUnderline', 'field_template': 'storage_only', 'size': 1, 'default_value': 'false', + {'name': 'HasSimpleUnderline', 'field_template': 'storage_only', 'field_size': 1, 'default_value': 'false', 'type_name': 'bool', 'inherited': True, 'independent': False}, # TODO(shend): vertical align is actually a CSS property, but since we don't support union fields # which can be either a keyword or Length, this is generated as a nonproperty for now. Remove this # once we can support union fields and groups. - {'name': 'VerticalAlign', 'field_template': 'storage_only', 'size': 4, 'default_value': 'EVerticalAlign::kBaseline', + {'name': 'VerticalAlign', 'field_template': 'storage_only', 'field_size': 4, 'default_value': 'EVerticalAlign::kBaseline', 'type_name': 'EVerticalAlign', 'inherited': False, 'independent': False}, ] @@ -199,7 +199,7 @@ # 'storage_only' fields need to specify a size, type_name and default_value type_name = property_['type_name'] default_value = property_['default_value'] - size = property_['size'] + size = property_['field_size'] elif property_['field_template'] == 'external': type_name = property_['type_name'] default_value = property_['default_value'] @@ -317,10 +317,12 @@ property_values = self._properties.values() - # Override the type name when field_type_path is specified for property_ in property_values: + # Override the type name when field_type_path is specified if property_['field_type_path']: property_['type_name'] = property_['field_type_path'].split('/')[-1] + # CSS properties are not allowed to explicitly specify their field_size. + property_['field_size'] = None self._generated_enums = _create_enums(property_values + NONPROPERTIES)
diff --git a/third_party/WebKit/Source/core/animation/Animation.cpp b/third_party/WebKit/Source/core/animation/Animation.cpp index a8cde62..b6aa9fa 100644 --- a/third_party/WebKit/Source/core/animation/Animation.cpp +++ b/third_party/WebKit/Source/core/animation/Animation.cpp
@@ -45,6 +45,7 @@ #include "core/inspector/InspectorTraceEvents.h" #include "core/probe/CoreProbes.h" #include "platform/RuntimeEnabledFeatures.h" +#include "platform/ScriptForbiddenScope.h" #include "platform/WebTaskRunner.h" #include "platform/animation/CompositorAnimationPlayer.h" #include "platform/heap/Persistent.h" @@ -1040,9 +1041,9 @@ animation_->ready_promise_->Reject(DOMException::Create(kAbortError)); } animation_->ready_promise_->Reset(); - animation_->ResolvePromiseAsync(animation_->ready_promise_.Get()); + animation_->ResolvePromiseMaybeAsync(animation_->ready_promise_.Get()); } else if (old_play_state == kPending) { - animation_->ResolvePromiseAsync(animation_->ready_promise_.Get()); + animation_->ResolvePromiseMaybeAsync(animation_->ready_promise_.Get()); } else if (new_play_state == kPending) { DCHECK_NE(animation_->ready_promise_->GetState(), AnimationPromise::kPending); @@ -1059,7 +1060,7 @@ } animation_->finished_promise_->Reset(); } else if (new_play_state == kFinished) { - animation_->ResolvePromiseAsync(animation_->finished_promise_.Get()); + animation_->ResolvePromiseMaybeAsync(animation_->finished_promise_.Get()); } else if (old_play_state == kFinished) { animation_->finished_promise_->Reset(); } @@ -1138,11 +1139,15 @@ StyleChangeReason::kStyleSheetChange)); } -void Animation::ResolvePromiseAsync(AnimationPromise* promise) { - TaskRunnerHelper::Get(TaskType::kDOMManipulation, GetExecutionContext()) - ->PostTask(BLINK_FROM_HERE, - WTF::Bind(&AnimationPromise::Resolve<Animation*>, - WrapPersistent(promise), WrapPersistent(this))); +void Animation::ResolvePromiseMaybeAsync(AnimationPromise* promise) { + if (ScriptForbiddenScope::IsScriptForbidden()) { + TaskRunnerHelper::Get(TaskType::kDOMManipulation, GetExecutionContext()) + ->PostTask(BLINK_FROM_HERE, + WTF::Bind(&AnimationPromise::Resolve<Animation*>, + WrapPersistent(promise), WrapPersistent(this))); + } else { + promise->Resolve(this); + } } DEFINE_TRACE(Animation) {
diff --git a/third_party/WebKit/Source/core/animation/Animation.h b/third_party/WebKit/Source/core/animation/Animation.h index 2663bdb46..9ef0b5f6a1 100644 --- a/third_party/WebKit/Source/core/animation/Animation.h +++ b/third_party/WebKit/Source/core/animation/Animation.h
@@ -237,7 +237,7 @@ using AnimationPromise = ScriptPromiseProperty<Member<Animation>, Member<Animation>, Member<DOMException>>; - void ResolvePromiseAsync(AnimationPromise*); + void ResolvePromiseMaybeAsync(AnimationPromise*); String id_;
diff --git a/third_party/WebKit/Source/core/animation/CompositorAnimationsTest.cpp b/third_party/WebKit/Source/core/animation/CompositorAnimationsTest.cpp index 15d3dfd..50c2643 100644 --- a/third_party/WebKit/Source/core/animation/CompositorAnimationsTest.cpp +++ b/third_party/WebKit/Source/core/animation/CompositorAnimationsTest.cpp
@@ -313,7 +313,7 @@ static void Dispose(LayoutObjectProxy* proxy) { proxy->Destroy(); } const char* GetName() const override { return nullptr; } - void GetLayout() override {} + void UpdateLayout() override {} FloatRect LocalBoundingBoxRectForAccessibility() const { return FloatRect(); } private:
diff --git a/third_party/WebKit/Source/core/css/CSSProperties.json5 b/third_party/WebKit/Source/core/css/CSSProperties.json5 index 77e1a94..152fa377 100644 --- a/third_party/WebKit/Source/core/css/CSSProperties.json5 +++ b/third_party/WebKit/Source/core/css/CSSProperties.json5
@@ -78,6 +78,8 @@ // Field has type specified at field_type_path and has a getter/setter. // Also has a setter taking an rvalue reference. Cannot be packed. "external", + // Only the storage is generated. The interface is handwritten. + "storage_only", ], },
diff --git a/third_party/WebKit/Source/core/css/FontFace.cpp b/third_party/WebKit/Source/core/css/FontFace.cpp index 8070741..9b9d25e 100644 --- a/third_party/WebKit/Source/core/css/FontFace.cpp +++ b/third_party/WebKit/Source/core/css/FontFace.cpp
@@ -82,8 +82,10 @@ return Create(context, family, source.getAsString(), descriptors); if (source.isArrayBuffer()) return Create(context, family, source.getAsArrayBuffer(), descriptors); - if (source.isArrayBufferView()) - return Create(context, family, source.getAsArrayBufferView(), descriptors); + if (source.isArrayBufferView()) { + return Create(context, family, source.getAsArrayBufferView().View(), + descriptors); + } NOTREACHED(); return nullptr; }
diff --git a/third_party/WebKit/Source/core/dom/ContainerNode.cpp b/third_party/WebKit/Source/core/dom/ContainerNode.cpp index 399b9b80..4565ca7 100644 --- a/third_party/WebKit/Source/core/dom/ContainerNode.cpp +++ b/third_party/WebKit/Source/core/dom/ContainerNode.cpp
@@ -1027,13 +1027,13 @@ kFocusControlState); } -void ContainerNode::SetFocused(bool received) { +void ContainerNode::SetFocused(bool received, WebFocusType focus_type) { // Recurse up author shadow trees to mark shadow hosts if it matches :focus. // TODO(kochi): Handle UA shadows which marks multiple nodes as focused such // as <input type="date"> the same way as author shadow. if (ShadowRoot* root = ContainingShadowRoot()) { if (root->GetType() != ShadowRootType::kUserAgent) - OwnerShadowHost()->SetFocused(received); + OwnerShadowHost()->SetFocused(received, focus_type); } // If this is an author shadow host and indirectly focused (has focused @@ -1048,7 +1048,7 @@ if (IsFocused() == received) return; - Node::SetFocused(received); + Node::SetFocused(received, focus_type); FocusStateChanged();
diff --git a/third_party/WebKit/Source/core/dom/ContainerNode.h b/third_party/WebKit/Source/core/dom/ContainerNode.h index e91ca9b..f315231 100644 --- a/third_party/WebKit/Source/core/dom/ContainerNode.h +++ b/third_party/WebKit/Source/core/dom/ContainerNode.h
@@ -30,6 +30,7 @@ #include "core/CoreExport.h" #include "core/dom/Node.h" #include "core/html/CollectionType.h" +#include "public/platform/WebFocusType.h" #include "wtf/Vector.h" namespace blink { @@ -136,7 +137,7 @@ void AttachLayoutTree(const AttachContext& = AttachContext()) override; void DetachLayoutTree(const AttachContext& = AttachContext()) override; LayoutRect BoundingBox() const final; - void SetFocused(bool) override; + void SetFocused(bool, WebFocusType) override; void FocusStateChanged(); void SetActive(bool = true) override; void SetDragged(bool) override;
diff --git a/third_party/WebKit/Source/core/dom/DOMArrayPiece.cpp b/third_party/WebKit/Source/core/dom/DOMArrayPiece.cpp index 30f25b6dd..f95b19e 100644 --- a/third_party/WebKit/Source/core/dom/DOMArrayPiece.cpp +++ b/third_party/WebKit/Source/core/dom/DOMArrayPiece.cpp
@@ -16,7 +16,7 @@ InitWithData(array_buffer->Data(), array_buffer->ByteLength()); } else if (array_buffer_or_view.isArrayBufferView()) { DOMArrayBufferView* array_buffer_view = - array_buffer_or_view.getAsArrayBufferView(); + array_buffer_or_view.getAsArrayBufferView().View(); InitWithData(array_buffer_view->BaseAddress(), array_buffer_view->byteLength()); } else if (array_buffer_or_view.isNull() &&
diff --git a/third_party/WebKit/Source/core/dom/Document.cpp b/third_party/WebKit/Source/core/dom/Document.cpp index 900666f..df11c236 100644 --- a/third_party/WebKit/Source/core/dom/Document.cpp +++ b/third_party/WebKit/Source/core/dom/Document.cpp
@@ -2228,7 +2228,7 @@ return; if (frame_view->NeedsLayout()) - frame_view->Layout(); + frame_view->UpdateLayout(); if (Lifecycle().GetState() < DocumentLifecycle::kLayoutClean) Lifecycle().AdvanceTo(DocumentLifecycle::kLayoutClean); @@ -3038,7 +3038,7 @@ if (View() && !GetLayoutViewItem().IsNull() && (!GetLayoutViewItem().FirstChild() || GetLayoutViewItem().NeedsLayout())) - View()->Layout(); + View()->UpdateLayout(); } load_event_progress_ = kLoadEventCompleted; @@ -4056,7 +4056,7 @@ // Remove focus from the existing focus node (if any) if (old_focused_element) { - old_focused_element->SetFocused(false); + old_focused_element->SetFocused(false, params.type); // Dispatch the blur event and let the node do any other blur related // activities (important for text fields) @@ -4088,12 +4088,6 @@ new_focused_element = nullptr; } } - - if (IsHTMLPlugInElement(old_focused_element)) { - if (PluginView* plugin = - ToHTMLPlugInElement(old_focused_element)->Plugin()) - plugin->SetFocused(false, params.type); - } } if (new_focused_element) @@ -4109,7 +4103,7 @@ focused_element_ = new_focused_element; SetSequentialFocusNavigationStartingPoint(focused_element_.Get()); - focused_element_->SetFocused(true); + focused_element_->SetFocused(true, params.type); // Element::setFocused for frames can dispatch events. if (focused_element_ != new_focused_element) { focus_change_blocked = true; @@ -4158,11 +4152,6 @@ if (IsRootEditableElement(*focused_element_)) GetFrame()->GetSpellChecker().DidBeginEditing(focused_element_.Get()); - - if (IsHTMLPlugInElement(focused_element_)) { - if (PluginView* plugin = ToHTMLPlugInElement(focused_element_)->Plugin()) - plugin->SetFocused(true, params.type); - } } if (!focus_change_blocked && focused_element_) {
diff --git a/third_party/WebKit/Source/core/dom/Node.cpp b/third_party/WebKit/Source/core/dom/Node.cpp index b91538e..3fdf979 100644 --- a/third_party/WebKit/Source/core/dom/Node.cpp +++ b/third_party/WebKit/Source/core/dom/Node.cpp
@@ -1288,7 +1288,7 @@ } } -String Node::textContent(bool convert_b_rs_to_newlines) const { +String Node::textContent(bool convert_brs_to_newlines) const { // This covers ProcessingInstruction and Comment that should return their // value when .textContent is accessed on them, but should be ignored when // iterated over as a descendant of a ContainerNode. @@ -1306,7 +1306,7 @@ StringBuilder content; for (const Node& node : NodeTraversal::InclusiveDescendantsOf(*this)) { - if (isHTMLBRElement(node) && convert_b_rs_to_newlines) { + if (isHTMLBRElement(node) && convert_brs_to_newlines) { content.Append('\n'); } else if (node.IsTextNode()) { content.Append(ToText(node).data()); @@ -2347,7 +2347,7 @@ return nullptr; } -void Node::SetFocused(bool flag) { +void Node::SetFocused(bool flag, WebFocusType focus_type) { GetDocument().UserActionElements().SetFocused(this, flag); }
diff --git a/third_party/WebKit/Source/core/dom/Node.h b/third_party/WebKit/Source/core/dom/Node.h index ff4263d..1d0e255d 100644 --- a/third_party/WebKit/Source/core/dom/Node.h +++ b/third_party/WebKit/Source/core/dom/Node.h
@@ -36,6 +36,7 @@ #include "core/events/EventTarget.h" #include "core/style/ComputedStyleConstants.h" #include "platform/geometry/LayoutRect.h" +#include "public/platform/WebFocusType.h" // This needs to be here because Element.cpp also depends on it. #define DUMP_NODE_STATISTICS 0 @@ -233,7 +234,7 @@ const AtomicString& lookupPrefix(const AtomicString& namespace_uri) const; const AtomicString& lookupNamespaceURI(const String& prefix) const; - String textContent(bool convert_b_rs_to_newlines = false) const; + String textContent(bool convert_brs_to_newlines = false) const; void setTextContent(const String&); bool SupportsAltText(); @@ -476,7 +477,7 @@ SetFlag(flag, kHasEventTargetDataFlag); } - virtual void SetFocused(bool flag); + virtual void SetFocused(bool flag, WebFocusType); virtual void SetActive(bool flag = true); virtual void SetDragged(bool flag); virtual void SetHovered(bool flag = true);
diff --git a/third_party/WebKit/Source/core/dom/NotShared.h b/third_party/WebKit/Source/core/dom/NotShared.h new file mode 100644 index 0000000..69173aa --- /dev/null +++ b/third_party/WebKit/Source/core/dom/NotShared.h
@@ -0,0 +1,68 @@ +// 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 NotShared_h +#define NotShared_h + +// A wrapper template type that is used to ensure that a TypedArray is not +// backed by a SharedArrayBuffer. +// +// Typically this is used as an annotation on C++ functions that are called by +// the bindings layer, e.g.: +// +// void Foo(NotShared<DOMUint32Array> param) { +// DOMUint32Array* array = param.View(); +// ... +// } + +#include "platform/heap/Handle.h" + +namespace blink { + +template <typename T> +class NotShared { + STACK_ALLOCATED(); + + public: + using TypedArrayType = T; + + NotShared() {} + + explicit NotShared(T* typedArray) : typed_array_(typedArray) { + DCHECK(!(typedArray && typedArray->View()->IsShared())); + } + NotShared(const NotShared& other) = default; + template <typename U> + NotShared(const NotShared<U>& other) : typed_array_(other.View()) {} + template <typename U> + NotShared(const Member<U>& other) { + DCHECK(!other->View()->IsShared()); + typed_array_ = other.Get(); + } + + NotShared& operator=(const NotShared& other) = default; + template <typename U> + NotShared& operator=(const NotShared<U>& other) { + typed_array_ = other.View(); + return *this; + } + + T* View() const { return typed_array_.Get(); } + + bool operator!() const { return !typed_array_; } + explicit operator bool() const { return !!typed_array_; } + + private: + // Must use an untraced member here since this object may be constructed on a + // thread without a ThreadState (e.g. an Audio worklet). It is safe in that + // case because the pointed-to ArrayBuffer is being kept alive another way + // (e.g. CrossThreadPersistent). + // + // TODO(binji): update to using Member, see crbug.com/710295. + UntracedMember<T> typed_array_; +}; + +} // namespace blink + +#endif // NotShared_h
diff --git a/third_party/WebKit/Source/core/editing/markers/DocumentMarkerControllerTest.cpp b/third_party/WebKit/Source/core/editing/markers/DocumentMarkerControllerTest.cpp index aa77692..a750be5 100644 --- a/third_party/WebKit/Source/core/editing/markers/DocumentMarkerControllerTest.cpp +++ b/third_party/WebKit/Source/core/editing/markers/DocumentMarkerControllerTest.cpp
@@ -30,6 +30,7 @@ #include "core/editing/markers/DocumentMarkerController.h" +#include <memory> #include "bindings/core/v8/ExceptionState.h" #include "core/dom/Document.h" #include "core/dom/Range.h" @@ -41,7 +42,6 @@ #include "testing/gtest/include/gtest/gtest.h" #include "wtf/PassRefPtr.h" #include "wtf/RefPtr.h" -#include <memory> namespace blink { @@ -264,4 +264,148 @@ EXPECT_TRUE(MarkerController().SetMarkersActive(range, true)); } +TEST_F(DocumentMarkerControllerTest, + RemoveStartOfMarkerDoRemovePartiallyOverlapping) { + SetBodyInnerHTML("<b>abc</b>"); + GetDocument().UpdateStyleAndLayout(); + Node* b_element = GetDocument().body()->FirstChild(); + Node* text = b_element->firstChild(); + + // Add marker under "abc" + EphemeralRange marker_range = + EphemeralRange(Position(text, 0), Position(text, 3)); + GetDocument().Markers().AddTextMatchMarker( + marker_range, DocumentMarker::MatchStatus::kInactive); + + // Remove markers that overlap "a" + marker_range = EphemeralRange(Position(text, 0), Position(text, 1)); + GetDocument().Markers().RemoveMarkers( + marker_range, DocumentMarker::AllMarkers(), + DocumentMarkerController::kRemovePartiallyOverlappingMarker); + + EXPECT_EQ(0u, MarkerController().Markers().size()); +} + +TEST_F(DocumentMarkerControllerTest, + RemoveStartOfMarkerDontRemovePartiallyOverlapping) { + SetBodyInnerHTML("<b>abc</b>"); + GetDocument().UpdateStyleAndLayout(); + Node* b_element = GetDocument().body()->FirstChild(); + Node* text = b_element->firstChild(); + + // Add marker under "abc" + EphemeralRange marker_range = + EphemeralRange(Position(text, 0), Position(text, 3)); + GetDocument().Markers().AddTextMatchMarker( + marker_range, DocumentMarker::MatchStatus::kInactive); + + // Remove portion of marker that overlaps "a" + marker_range = EphemeralRange(Position(text, 0), Position(text, 1)); + GetDocument().Markers().RemoveMarkers( + marker_range, DocumentMarker::AllMarkers(), + DocumentMarkerController::kDoNotRemovePartiallyOverlappingMarker); + + EXPECT_EQ(1u, MarkerController().Markers().size()); + + EXPECT_EQ(1u, MarkerController().Markers()[0]->StartOffset()); + EXPECT_EQ(3u, MarkerController().Markers()[0]->EndOffset()); +} + +TEST_F(DocumentMarkerControllerTest, + RemoveMiddleOfMarkerDoRemovePartiallyOverlapping) { + SetBodyInnerHTML("<b>abc</b>"); + GetDocument().UpdateStyleAndLayout(); + Node* b_element = GetDocument().body()->FirstChild(); + Node* text = b_element->firstChild(); + + // Add marker under "abc" + EphemeralRange marker_range = + EphemeralRange(Position(text, 0), Position(text, 3)); + GetDocument().Markers().AddTextMatchMarker( + marker_range, DocumentMarker::MatchStatus::kInactive); + + // Remove markers that overlap "b" + marker_range = EphemeralRange(Position(text, 1), Position(text, 2)); + GetDocument().Markers().RemoveMarkers( + marker_range, DocumentMarker::AllMarkers(), + DocumentMarkerController::kRemovePartiallyOverlappingMarker); + + EXPECT_EQ(0u, MarkerController().Markers().size()); +} + +TEST_F(DocumentMarkerControllerTest, + RemoveMiddleOfMarkerDontRemovePartiallyOverlapping) { + SetBodyInnerHTML("<b>abc</b>"); + GetDocument().UpdateStyleAndLayout(); + Node* b_element = GetDocument().body()->FirstChild(); + Node* text = b_element->firstChild(); + + // Add marker under "abc" + EphemeralRange marker_range = + EphemeralRange(Position(text, 0), Position(text, 3)); + GetDocument().Markers().AddTextMatchMarker( + marker_range, DocumentMarker::MatchStatus::kInactive); + + // Remove portion of marker that overlaps "b" + marker_range = EphemeralRange(Position(text, 1), Position(text, 2)); + GetDocument().Markers().RemoveMarkers( + marker_range, DocumentMarker::AllMarkers(), + DocumentMarkerController::kDoNotRemovePartiallyOverlappingMarker); + + EXPECT_EQ(2u, MarkerController().Markers().size()); + + EXPECT_EQ(0u, MarkerController().Markers()[0]->StartOffset()); + EXPECT_EQ(1u, MarkerController().Markers()[0]->EndOffset()); + + EXPECT_EQ(2u, MarkerController().Markers()[1]->StartOffset()); + EXPECT_EQ(3u, MarkerController().Markers()[1]->EndOffset()); +} + +TEST_F(DocumentMarkerControllerTest, + RemoveEndOfMarkerDoRemovePartiallyOverlapping) { + SetBodyInnerHTML("<b>abc</b>"); + GetDocument().UpdateStyleAndLayout(); + Node* b_element = GetDocument().body()->FirstChild(); + Node* text = b_element->firstChild(); + + // Add marker under "abc" + EphemeralRange marker_range = + EphemeralRange(Position(text, 0), Position(text, 3)); + GetDocument().Markers().AddTextMatchMarker( + marker_range, DocumentMarker::MatchStatus::kInactive); + + // Remove markers that overlap "c" + marker_range = EphemeralRange(Position(text, 2), Position(text, 3)); + GetDocument().Markers().RemoveMarkers( + marker_range, DocumentMarker::AllMarkers(), + DocumentMarkerController::kRemovePartiallyOverlappingMarker); + + EXPECT_EQ(0u, MarkerController().Markers().size()); +} + +TEST_F(DocumentMarkerControllerTest, + RemoveEndOfMarkerDontRemovePartiallyOverlapping) { + SetBodyInnerHTML("<b>abc</b>"); + GetDocument().UpdateStyleAndLayout(); + Node* b_element = GetDocument().body()->FirstChild(); + Node* text = b_element->firstChild(); + + // Add marker under "abc" + EphemeralRange marker_range = + EphemeralRange(Position(text, 0), Position(text, 3)); + GetDocument().Markers().AddTextMatchMarker( + marker_range, DocumentMarker::MatchStatus::kInactive); + + // Remove portion of marker that overlaps "c" + marker_range = EphemeralRange(Position(text, 2), Position(text, 3)); + GetDocument().Markers().RemoveMarkers( + marker_range, DocumentMarker::AllMarkers(), + DocumentMarkerController::kDoNotRemovePartiallyOverlappingMarker); + + EXPECT_EQ(1u, MarkerController().Markers().size()); + + EXPECT_EQ(0u, MarkerController().Markers()[0]->StartOffset()); + EXPECT_EQ(2u, MarkerController().Markers()[0]->EndOffset()); +} + } // namespace blink
diff --git a/third_party/WebKit/Source/core/fileapi/Blob.cpp b/third_party/WebKit/Source/core/fileapi/Blob.cpp index 79f2741c..dfb0b18d 100644 --- a/third_party/WebKit/Source/core/fileapi/Blob.cpp +++ b/third_party/WebKit/Source/core/fileapi/Blob.cpp
@@ -132,7 +132,8 @@ DOMArrayBuffer* array_buffer = item.getAsArrayBuffer(); blob_data->AppendBytes(array_buffer->Data(), array_buffer->ByteLength()); } else if (item.isArrayBufferView()) { - DOMArrayBufferView* array_buffer_view = item.getAsArrayBufferView(); + DOMArrayBufferView* array_buffer_view = + item.getAsArrayBufferView().View(); blob_data->AppendBytes(array_buffer_view->BaseAddress(), array_buffer_view->byteLength()); } else if (item.isBlob()) {
diff --git a/third_party/WebKit/Source/core/frame/Deprecation.cpp b/third_party/WebKit/Source/core/frame/Deprecation.cpp index 61d203d2..e6426cf0 100644 --- a/third_party/WebKit/Source/core/frame/Deprecation.cpp +++ b/third_party/WebKit/Source/core/frame/Deprecation.cpp
@@ -15,11 +15,10 @@ namespace { enum Milestone { - M56, - M57, M58, M59, M60, + M61, }; const char* milestoneString(Milestone milestone) { @@ -27,16 +26,14 @@ // https://www.chromium.org/developers/calendar switch (milestone) { - case M56: - return "M56, around January 2017"; - case M57: - return "M57, around March 2017"; case M58: return "M58, around April 2017"; case M59: return "M59, around June 2017"; case M60: return "M60, around August 2017"; + case M61: + return "M61, around September 2017"; } ASSERT_NOT_REACHED(); @@ -354,7 +351,16 @@ "deprecated and will be removed in %s. You should consider " "switching your application to a secure origin, such as HTTPS. See " "https://goo.gl/rStTGz for more details.", - milestoneString(M60)); + milestoneString(M61)); + + case UseCounter::kNotificationPermissionRequestedIframe: + return String::Format( + "Using the Notification API from an iframe is deprecated and will " + "be removed in %s. You should consider requesting permission from " + "the top-level frame or opening a new window instead. See " + "https://www.chromestatus.com/feature/6451284559265792 for more " + "details.", + milestoneString(M61)); case UseCounter::kElementCreateShadowRootMultiple: return "Calling Element.createShadowRoot() for an element which already "
diff --git a/third_party/WebKit/Source/core/frame/FrameView.cpp b/third_party/WebKit/Source/core/frame/FrameView.cpp index ab683ed..4d17f62 100644 --- a/third_party/WebKit/Source/core/frame/FrameView.cpp +++ b/third_party/WebKit/Source/core/frame/FrameView.cpp
@@ -739,7 +739,7 @@ const IntPoint origin(-rect.X(), -rect.Y()); if (ScrollOrigin() != origin) { - ScrollableArea::SetScrollOrigin(origin); + SetScrollOrigin(origin); // setContentSize (below) also calls updateScrollbars so we can avoid // updating scrollbars twice by skipping the call here when the content // size does not change. @@ -755,7 +755,7 @@ if (NeedsLayout()) { AutoReset<bool> suppress_adjust_view_size(&suppress_adjust_view_size_, true); - Layout(); + UpdateLayout(); } } @@ -988,7 +988,7 @@ // Synchronously enter layout, to layout the view containing the host // object/embed/iframe. ASSERT(frame_view); - frame_view->Layout(); + frame_view->UpdateLayout(); } void FrameView::PerformPreLayoutTasks() { @@ -1046,7 +1046,7 @@ static inline void LayoutFromRootObject(LayoutObject& root) { LayoutState layout_state(root); - root.GetLayout(); + root.UpdateLayout(); } void FrameView::PrepareLayoutAnalyzer() { @@ -1135,7 +1135,7 @@ if (HasOrthogonalWritingModeRoots() && !RuntimeEnabledFeatures::layoutNGEnabled()) LayoutOrthogonalWritingModeRoots(); - GetLayoutView()->GetLayout(); + GetLayoutView()->UpdateLayout(); } frame_->GetDocument()->Fetcher()->UpdateAllImageResourcePriorities(); @@ -1170,11 +1170,11 @@ // here. post_layout_tasks_timer_.StartOneShot(0, BLINK_FROM_HERE); if (NeedsLayout()) - Layout(); + UpdateLayout(); } } -void FrameView::Layout() { +void FrameView::UpdateLayout() { // We should never layout a Document which is not in a LocalFrame. ASSERT(frame_); ASSERT(frame_->View() == this); @@ -1955,7 +1955,7 @@ // scroll immediately. LayoutViewItem layout_view_item = this->GetLayoutViewItem(); if (!layout_view_item.IsNull() && layout_view_item.NeedsLayout()) - Layout(); + UpdateLayout(); else ScrollToFragmentAnchor(); } @@ -2164,7 +2164,7 @@ // but before performLayout(), causing double-layout. See also // crbug.com/429242. if (!uses_overlay_scrollbars && NeedsLayout()) - Layout(); + UpdateLayout(); if (!GetLayoutViewItem().IsNull() && GetLayoutViewItem().UsesCompositing()) { GetLayoutViewItem().Compositor()->FrameViewScrollbarsExistenceDidChange(); @@ -3340,7 +3340,7 @@ CHECK(!nested_layout_count_); if (NeedsLayout()) - Layout(); + UpdateLayout(); CheckDoesNotNeedLayout(); @@ -3489,7 +3489,7 @@ layout_view->SetPageLogicalHeight(floored_page_logical_height); layout_view->SetNeedsLayoutAndPrefWidthsRecalcAndFullPaintInvalidation( LayoutInvalidationReason::kPrintingChanged); - Layout(); + UpdateLayout(); // If we don't fit in the given page width, we'll lay out again. If we don't // fit in the page width when shrunk, we will lay out at maximum shrink and @@ -3523,7 +3523,7 @@ layout_view->SetPageLogicalHeight(floored_page_logical_height); layout_view->SetNeedsLayoutAndPrefWidthsRecalcAndFullPaintInvalidation( LayoutInvalidationReason::kPrintingChanged); - Layout(); + UpdateLayout(); const LayoutRect& updated_document_rect = LayoutRect(layout_view->DocumentRect()); @@ -4348,10 +4348,8 @@ void FrameView::AdjustScrollOffsetFromUpdateScrollbars() { ScrollOffset clamped = ClampScrollOffset(GetScrollOffset()); - if (clamped != GetScrollOffset() || ScrollOriginChanged()) { - ScrollableArea::SetScrollOffset(clamped, kClampingScroll); - ResetScrollOriginChanged(); - } + if (clamped != GetScrollOffset() || ScrollOriginChanged()) + SetScrollOffset(clamped, kClampingScroll); } void FrameView::ScrollContentsIfNeeded() { @@ -4534,6 +4532,18 @@ PositionScrollCornerLayer(LayerForScrollCorner(), ScrollCornerRect()); } +bool FrameView::UpdateAfterCompositingChange() { + if (ScrollOriginChanged()) { + // If the scroll origin changed, we need to update the layer position on + // the compositor since the offset itself might not have changed. + LayoutViewItem layout_view_item = this->GetLayoutViewItem(); + if (!layout_view_item.IsNull() && layout_view_item.UsesCompositing()) + layout_view_item.Compositor()->FrameViewDidScroll(); + ResetScrollOriginChanged(); + } + return false; +} + bool FrameView::UserInputScrollable(ScrollbarOrientation orientation) const { Document* document = GetFrame().GetDocument(); Element* fullscreen_element = Fullscreen::FullscreenElementFrom(*document);
diff --git a/third_party/WebKit/Source/core/frame/FrameView.h b/third_party/WebKit/Source/core/frame/FrameView.h index ecb5bbfb..827969c8 100644 --- a/third_party/WebKit/Source/core/frame/FrameView.h +++ b/third_party/WebKit/Source/core/frame/FrameView.h
@@ -135,7 +135,7 @@ void SetContentsSize(const IntSize&); - void Layout(); + void UpdateLayout(); bool DidFirstLayout() const; void ScheduleRelayout(); void ScheduleRelayoutOfSubtree(LayoutObject*); @@ -436,6 +436,7 @@ GraphicsLayer* LayerForScrollCorner() const override; int ScrollSize(ScrollbarOrientation) const override; bool IsScrollCornerVisible() const override; + bool UpdateAfterCompositingChange() override; bool UserInputScrollable(ScrollbarOrientation) const override; bool ShouldPlaceVerticalScrollbarOnLeft() const override; FrameViewBase* GetFrameViewBase() override;
diff --git a/third_party/WebKit/Source/core/frame/ImageBitmapTest.cpp b/third_party/WebKit/Source/core/frame/ImageBitmapTest.cpp index a59e6a6e..96ebafa3 100644 --- a/third_party/WebKit/Source/core/frame/ImageBitmapTest.cpp +++ b/third_party/WebKit/Source/core/frame/ImageBitmapTest.cpp
@@ -498,7 +498,8 @@ TEST_F(ImageBitmapTest, ImageBitmapColorSpaceConversionImageData) { unsigned char data_buffer[4] = {255, 0, 0, 255}; DOMUint8ClampedArray* data = DOMUint8ClampedArray::Create(data_buffer, 4); - ImageData* image_data = ImageData::Create(IntSize(1, 1), data); + ImageData* image_data = + ImageData::Create(IntSize(1, 1), NotShared<DOMUint8ClampedArray>(data)); std::unique_ptr<uint8_t[]> src_pixel(new uint8_t[4]()); memcpy(src_pixel.get(), image_data->data()->Data(), 4);
diff --git a/third_party/WebKit/Source/core/frame/LocalFrame.cpp b/third_party/WebKit/Source/core/frame/LocalFrame.cpp index 8f18e6b..aa819521 100644 --- a/third_party/WebKit/Source/core/frame/LocalFrame.cpp +++ b/third_party/WebKit/Source/core/frame/LocalFrame.cpp
@@ -606,7 +606,7 @@ layout_view->SetNeedsLayout(LayoutInvalidationReason::kPrintingChanged); layout_view->SetShouldDoFullPaintInvalidationForViewAndAllDescendants(); } - View()->Layout(); + View()->UpdateLayout(); View()->AdjustViewSize(); }
diff --git a/third_party/WebKit/Source/core/frame/csp/CSPDirectiveList.cpp b/third_party/WebKit/Source/core/frame/csp/CSPDirectiveList.cpp index 053ddde..392d868 100644 --- a/third_party/WebKit/Source/core/frame/csp/CSPDirectiveList.cpp +++ b/third_party/WebKit/Source/core/frame/csp/CSPDirectiveList.cpp
@@ -40,11 +40,6 @@ digest.size(), kBase64DoNotInsertLFs); } -template <typename CharType> -inline bool IsASCIIAlphanumericOrHyphen(CharType c) { - return IsASCIIAlphanumeric(c) || c == '-'; -} - ContentSecurityPolicyHashAlgorithm ConvertHashAlgorithmToCSPHashAlgorithm( HashAlgorithm algorithm) { switch (algorithm) {
diff --git a/third_party/WebKit/Source/core/geometry/DOMMatrix.cpp b/third_party/WebKit/Source/core/geometry/DOMMatrix.cpp index 799107e0..3dc15d7 100644 --- a/third_party/WebKit/Source/core/geometry/DOMMatrix.cpp +++ b/third_party/WebKit/Source/core/geometry/DOMMatrix.cpp
@@ -39,26 +39,30 @@ return new DOMMatrix(sequence, sequence.size()); } -DOMMatrix* DOMMatrix::fromFloat32Array(DOMFloat32Array* float32_array, +DOMMatrix* DOMMatrix::fromFloat32Array(NotShared<DOMFloat32Array> float32_array, ExceptionState& exception_state) { - if (float32_array->length() != 6 && float32_array->length() != 16) { + if (float32_array.View()->length() != 6 && + float32_array.View()->length() != 16) { exception_state.ThrowTypeError( "The sequence must contain 6 elements for a 2D matrix or 16 elements " "for a 3D matrix."); return nullptr; } - return new DOMMatrix(float32_array->Data(), float32_array->length()); + return new DOMMatrix(float32_array.View()->Data(), + float32_array.View()->length()); } -DOMMatrix* DOMMatrix::fromFloat64Array(DOMFloat64Array* float64_array, +DOMMatrix* DOMMatrix::fromFloat64Array(NotShared<DOMFloat64Array> float64_array, ExceptionState& exception_state) { - if (float64_array->length() != 6 && float64_array->length() != 16) { + if (float64_array.View()->length() != 6 && + float64_array.View()->length() != 16) { exception_state.ThrowTypeError( "The sequence must contain 6 elements for a 2D matrix or 16 elements " "for a 3D matrix."); return nullptr; } - return new DOMMatrix(float64_array->Data(), float64_array->length()); + return new DOMMatrix(float64_array.View()->Data(), + float64_array.View()->length()); } template <typename T>
diff --git a/third_party/WebKit/Source/core/geometry/DOMMatrix.h b/third_party/WebKit/Source/core/geometry/DOMMatrix.h index eb0a338..eede89ef 100644 --- a/third_party/WebKit/Source/core/geometry/DOMMatrix.h +++ b/third_party/WebKit/Source/core/geometry/DOMMatrix.h
@@ -6,6 +6,7 @@ #define DOMMatrix_h #include "bindings/core/v8/ExceptionState.h" +#include "core/dom/NotShared.h" #include "core/geometry/DOMMatrixInit.h" #include "core/geometry/DOMMatrixReadOnly.h" @@ -21,8 +22,10 @@ static DOMMatrix* Create(const SkMatrix44&, ExceptionState&); static DOMMatrix* Create(const String&, ExceptionState&); static DOMMatrix* Create(Vector<double>, ExceptionState&); - static DOMMatrix* fromFloat32Array(DOMFloat32Array*, ExceptionState&); - static DOMMatrix* fromFloat64Array(DOMFloat64Array*, ExceptionState&); + static DOMMatrix* fromFloat32Array(NotShared<DOMFloat32Array>, + ExceptionState&); + static DOMMatrix* fromFloat64Array(NotShared<DOMFloat64Array>, + ExceptionState&); static DOMMatrix* fromMatrix(DOMMatrixInit&, ExceptionState&); void setA(double value) { matrix_->SetM11(value); }
diff --git a/third_party/WebKit/Source/core/geometry/DOMMatrixReadOnly.cpp b/third_party/WebKit/Source/core/geometry/DOMMatrixReadOnly.cpp index 0d788c76..fd09781 100644 --- a/third_party/WebKit/Source/core/geometry/DOMMatrixReadOnly.cpp +++ b/third_party/WebKit/Source/core/geometry/DOMMatrixReadOnly.cpp
@@ -115,27 +115,31 @@ } DOMMatrixReadOnly* DOMMatrixReadOnly::fromFloat32Array( - DOMFloat32Array* float32_array, + NotShared<DOMFloat32Array> float32_array, ExceptionState& exception_state) { - if (float32_array->length() != 6 && float32_array->length() != 16) { + if (float32_array.View()->length() != 6 && + float32_array.View()->length() != 16) { exception_state.ThrowTypeError( "The sequence must contain 6 elements for a 2D matrix or 16 elements a " "for 3D matrix."); return nullptr; } - return new DOMMatrixReadOnly(float32_array->Data(), float32_array->length()); + return new DOMMatrixReadOnly(float32_array.View()->Data(), + float32_array.View()->length()); } DOMMatrixReadOnly* DOMMatrixReadOnly::fromFloat64Array( - DOMFloat64Array* float64_array, + NotShared<DOMFloat64Array> float64_array, ExceptionState& exception_state) { - if (float64_array->length() != 6 && float64_array->length() != 16) { + if (float64_array.View()->length() != 6 && + float64_array.View()->length() != 16) { exception_state.ThrowTypeError( "The sequence must contain 6 elements for a 2D matrix or 16 elements " "for a 3D matrix."); return nullptr; } - return new DOMMatrixReadOnly(float64_array->Data(), float64_array->length()); + return new DOMMatrixReadOnly(float64_array.View()->Data(), + float64_array.View()->length()); } DOMMatrixReadOnly* DOMMatrixReadOnly::fromMatrix( @@ -275,7 +279,7 @@ is2d_ = is2d; } -DOMFloat32Array* DOMMatrixReadOnly::toFloat32Array() const { +NotShared<DOMFloat32Array> DOMMatrixReadOnly::toFloat32Array() const { float array[] = { static_cast<float>(matrix_->M11()), static_cast<float>(matrix_->M12()), static_cast<float>(matrix_->M13()), static_cast<float>(matrix_->M14()), @@ -286,17 +290,17 @@ static_cast<float>(matrix_->M41()), static_cast<float>(matrix_->M42()), static_cast<float>(matrix_->M43()), static_cast<float>(matrix_->M44())}; - return DOMFloat32Array::Create(array, 16); + return NotShared<DOMFloat32Array>(DOMFloat32Array::Create(array, 16)); } -DOMFloat64Array* DOMMatrixReadOnly::toFloat64Array() const { +NotShared<DOMFloat64Array> DOMMatrixReadOnly::toFloat64Array() const { double array[] = { matrix_->M11(), matrix_->M12(), matrix_->M13(), matrix_->M14(), matrix_->M21(), matrix_->M22(), matrix_->M23(), matrix_->M24(), matrix_->M31(), matrix_->M32(), matrix_->M33(), matrix_->M34(), matrix_->M41(), matrix_->M42(), matrix_->M43(), matrix_->M44()}; - return DOMFloat64Array::Create(array, 16); + return NotShared<DOMFloat64Array>(DOMFloat64Array::Create(array, 16)); } const String DOMMatrixReadOnly::toString() const {
diff --git a/third_party/WebKit/Source/core/geometry/DOMMatrixReadOnly.h b/third_party/WebKit/Source/core/geometry/DOMMatrixReadOnly.h index dcb42ea..708a07e 100644 --- a/third_party/WebKit/Source/core/geometry/DOMMatrixReadOnly.h +++ b/third_party/WebKit/Source/core/geometry/DOMMatrixReadOnly.h
@@ -9,6 +9,7 @@ #include "bindings/core/v8/ExceptionState.h" #include "bindings/core/v8/ScriptWrappable.h" #include "core/dom/DOMTypedArray.h" +#include "core/dom/NotShared.h" #include "platform/heap/Handle.h" #include "platform/transforms/TransformationMatrix.h" @@ -28,8 +29,10 @@ static DOMMatrixReadOnly* Create(ExceptionState&); static DOMMatrixReadOnly* Create(const String&, ExceptionState&); static DOMMatrixReadOnly* Create(Vector<double>, ExceptionState&); - static DOMMatrixReadOnly* fromFloat32Array(DOMFloat32Array*, ExceptionState&); - static DOMMatrixReadOnly* fromFloat64Array(DOMFloat64Array*, ExceptionState&); + static DOMMatrixReadOnly* fromFloat32Array(NotShared<DOMFloat32Array>, + ExceptionState&); + static DOMMatrixReadOnly* fromFloat64Array(NotShared<DOMFloat64Array>, + ExceptionState&); static DOMMatrixReadOnly* fromMatrix(DOMMatrixInit&, ExceptionState&); virtual ~DOMMatrixReadOnly(); @@ -89,8 +92,8 @@ DOMPoint* transformPoint(const DOMPointInit&); - DOMFloat32Array* toFloat32Array() const; - DOMFloat64Array* toFloat64Array() const; + NotShared<DOMFloat32Array> toFloat32Array() const; + NotShared<DOMFloat64Array> toFloat64Array() const; const String toString() const;
diff --git a/third_party/WebKit/Source/core/html/HTMLAreaElement.cpp b/third_party/WebKit/Source/core/html/HTMLAreaElement.cpp index ba005351..473710c 100644 --- a/third_party/WebKit/Source/core/html/HTMLAreaElement.cpp +++ b/third_party/WebKit/Source/core/html/HTMLAreaElement.cpp
@@ -203,11 +203,12 @@ return SupportsFocus() && Element::tabIndex() >= 0; } -void HTMLAreaElement::SetFocused(bool should_be_focused) { +void HTMLAreaElement::SetFocused(bool should_be_focused, + WebFocusType focus_type) { if (IsFocused() == should_be_focused) return; - HTMLAnchorElement::SetFocused(should_be_focused); + HTMLAnchorElement::SetFocused(should_be_focused, focus_type); HTMLImageElement* image_element = this->ImageElement(); if (!image_element)
diff --git a/third_party/WebKit/Source/core/html/HTMLAreaElement.h b/third_party/WebKit/Source/core/html/HTMLAreaElement.h index b7c7797..18de31b93 100644 --- a/third_party/WebKit/Source/core/html/HTMLAreaElement.h +++ b/third_party/WebKit/Source/core/html/HTMLAreaElement.h
@@ -23,10 +23,11 @@ #ifndef HTMLAreaElement_h #define HTMLAreaElement_h +#include <memory> #include "core/CoreExport.h" #include "core/html/HTMLAnchorElement.h" #include "platform/geometry/LayoutRect.h" -#include <memory> +#include "public/platform/WebFocusType.h" namespace blink { @@ -65,7 +66,7 @@ bool IsMouseFocusable() const override; bool LayoutObjectIsFocusable() const override; void UpdateFocusAppearance(SelectionBehaviorOnFocus) override; - void SetFocused(bool) override; + void SetFocused(bool, WebFocusType) override; enum Shape { kDefault, kPoly, kRect, kCircle }; void InvalidateCachedPath();
diff --git a/third_party/WebKit/Source/core/html/HTMLFrameElementBase.cpp b/third_party/WebKit/Source/core/html/HTMLFrameElementBase.cpp index f5728ab..9ca4b775 100644 --- a/third_party/WebKit/Source/core/html/HTMLFrameElementBase.cpp +++ b/third_party/WebKit/Source/core/html/HTMLFrameElementBase.cpp
@@ -213,8 +213,8 @@ return true; } -void HTMLFrameElementBase::SetFocused(bool received) { - HTMLFrameOwnerElement::SetFocused(received); +void HTMLFrameElementBase::SetFocused(bool received, WebFocusType focus_type) { + HTMLFrameOwnerElement::SetFocused(received, focus_type); if (Page* page = GetDocument().GetPage()) { if (received) { page->GetFocusController().SetFocusedFrame(ContentFrame());
diff --git a/third_party/WebKit/Source/core/html/HTMLFrameElementBase.h b/third_party/WebKit/Source/core/html/HTMLFrameElementBase.h index 6f95790..631685f 100644 --- a/third_party/WebKit/Source/core/html/HTMLFrameElementBase.h +++ b/third_party/WebKit/Source/core/html/HTMLFrameElementBase.h
@@ -26,6 +26,7 @@ #include "core/CoreExport.h" #include "core/html/HTMLFrameOwnerElement.h" +#include "public/platform/WebFocusType.h" namespace blink { @@ -52,7 +53,7 @@ private: bool SupportsFocus() const final; - void SetFocused(bool) final; + void SetFocused(bool, WebFocusType) final; bool IsURLAttribute(const Attribute&) const final; bool HasLegalLinkAttribute(const QualifiedName&) const final;
diff --git a/third_party/WebKit/Source/core/html/HTMLPlugInElement.cpp b/third_party/WebKit/Source/core/html/HTMLPlugInElement.cpp index 780bf147..43fe90a 100644 --- a/third_party/WebKit/Source/core/html/HTMLPlugInElement.cpp +++ b/third_party/WebKit/Source/core/html/HTMLPlugInElement.cpp
@@ -155,6 +155,12 @@ persisted_plugin_ = plugin; } +void HTMLPlugInElement::SetFocused(bool focused, WebFocusType focus_type) { + if (plugin_) + plugin_->SetFocused(focused, focus_type); + HTMLFrameOwnerElement::SetFocused(focused, focus_type); +} + bool HTMLPlugInElement::RequestObjectInternal( const String& url, const String& mime_type,
diff --git a/third_party/WebKit/Source/core/html/HTMLPlugInElement.h b/third_party/WebKit/Source/core/html/HTMLPlugInElement.h index cc1d4cfe..5932b28 100644 --- a/third_party/WebKit/Source/core/html/HTMLPlugInElement.h +++ b/third_party/WebKit/Source/core/html/HTMLPlugInElement.h
@@ -46,6 +46,7 @@ ~HTMLPlugInElement() override; DECLARE_VIRTUAL_TRACE(); + void SetFocused(bool, WebFocusType) override; void ResetInstance(); // TODO(dcheng): Consider removing this, since HTMLEmbedElementLegacyCall // and HTMLObjectElementLegacyCall usage is extremely low.
diff --git a/third_party/WebKit/Source/core/html/ImageData.cpp b/third_party/WebKit/Source/core/html/ImageData.cpp index 91a16a09..b42e161b 100644 --- a/third_party/WebKit/Source/core/html/ImageData.cpp +++ b/third_party/WebKit/Source/core/html/ImageData.cpp
@@ -229,12 +229,13 @@ } ImageData* ImageData::Create(const IntSize& size, - DOMArrayBufferView* data_array, + NotShared<DOMArrayBufferView> data_array, const ImageDataColorSettings* color_settings) { - if (!ImageData::ValidateConstructorArguments( - kParamSize | kParamData, &size, 0, 0, data_array, color_settings)) + if (!ImageData::ValidateConstructorArguments(kParamSize | kParamData, &size, + 0, 0, data_array.View(), + color_settings)) return nullptr; - return new ImageData(size, data_array, color_settings); + return new ImageData(size, data_array.View(), color_settings); } ImageData* ImageData::Create(unsigned width, @@ -251,28 +252,28 @@ : nullptr; } -ImageData* ImageData::Create(DOMUint8ClampedArray* data, +ImageData* ImageData::Create(NotShared<DOMUint8ClampedArray> data, unsigned width, ExceptionState& exception_state) { if (!ImageData::ValidateConstructorArguments(kParamData | kParamWidth, - nullptr, width, 0, data, nullptr, - &exception_state)) + nullptr, width, 0, data.View(), + nullptr, &exception_state)) return nullptr; - unsigned height = data->length() / (width * 4); - return new ImageData(IntSize(width, height), data); + unsigned height = data.View()->length() / (width * 4); + return new ImageData(IntSize(width, height), data.View()); } -ImageData* ImageData::Create(DOMUint8ClampedArray* data, +ImageData* ImageData::Create(NotShared<DOMUint8ClampedArray> data, unsigned width, unsigned height, ExceptionState& exception_state) { if (!ImageData::ValidateConstructorArguments( - kParamData | kParamWidth | kParamHeight, nullptr, width, height, data, - nullptr, &exception_state)) + kParamData | kParamWidth | kParamHeight, nullptr, width, height, + data.View(), nullptr, &exception_state)) return nullptr; - return new ImageData(IntSize(width, height), data); + return new ImageData(IntSize(width, height), data.View()); } ImageData* ImageData::createImageData( @@ -308,13 +309,13 @@ String storage_format_name; if (data.isUint8ClampedArray()) { - buffer_view = data.getAsUint8ClampedArray(); + buffer_view = data.getAsUint8ClampedArray().View(); storage_format_name = kUint8ClampedArrayStorageFormatName; } else if (data.isUint16Array()) { - buffer_view = data.getAsUint16Array(); + buffer_view = data.getAsUint16Array().View(); storage_format_name = kUint16ArrayStorageFormatName; } else if (data.isFloat32Array()) { - buffer_view = data.getAsFloat32Array(); + buffer_view = data.getAsFloat32Array().View(); storage_format_name = kFloat32ArrayStorageFormatName; } else { NOTREACHED();
diff --git a/third_party/WebKit/Source/core/html/ImageData.h b/third_party/WebKit/Source/core/html/ImageData.h index e0ffd1d2..86f5a59 100644 --- a/third_party/WebKit/Source/core/html/ImageData.h +++ b/third_party/WebKit/Source/core/html/ImageData.h
@@ -33,6 +33,7 @@ #include "bindings/core/v8/Uint8ClampedArrayOrUint16ArrayOrFloat32Array.h" #include "core/CoreExport.h" #include "core/dom/DOMTypedArray.h" +#include "core/dom/NotShared.h" #include "core/html/ImageDataColorSettings.h" #include "core/html/canvas/CanvasRenderingContext.h" #include "core/imagebitmap/ImageBitmapSource.h" @@ -77,14 +78,14 @@ static ImageData* Create(const IntSize&, const ImageDataColorSettings* = nullptr); static ImageData* Create(const IntSize&, - DOMArrayBufferView*, + NotShared<DOMArrayBufferView>, const ImageDataColorSettings* = nullptr); static ImageData* Create(unsigned width, unsigned height, ExceptionState&); - static ImageData* Create(DOMUint8ClampedArray*, + static ImageData* Create(NotShared<DOMUint8ClampedArray>, unsigned width, ExceptionState&); - static ImageData* Create(DOMUint8ClampedArray*, + static ImageData* Create(NotShared<DOMUint8ClampedArray>, unsigned width, unsigned height, ExceptionState&);
diff --git a/third_party/WebKit/Source/core/html/LinkStyle.cpp b/third_party/WebKit/Source/core/html/LinkStyle.cpp index 2886697..76d5a78 100644 --- a/third_party/WebKit/Source/core/html/LinkStyle.cpp +++ b/third_party/WebKit/Source/core/html/LinkStyle.cpp
@@ -113,13 +113,6 @@ CSSParserContext* parser_context = CSSParserContext::Create( owner_->GetDocument(), base_url, referrer_policy, charset); - DEFINE_STATIC_LOCAL(EnumerationHistogram, - restored_cached_style_sheet_histogram, - ("Blink.RestoredCachedStyleSheet", 2)); - DEFINE_STATIC_LOCAL( - EnumerationHistogram, restored_cached_style_sheet2_histogram, - ("Blink.RestoredCachedStyleSheet2", kStyleSheetCacheStatusCount)); - if (StyleSheetContents* restored_sheet = const_cast<CSSStyleSheetResource*>(cached_style_sheet) ->RestoreParsedStyleSheet(parser_context)) { @@ -137,15 +130,8 @@ loading_ = false; restored_sheet->CheckLoaded(); - restored_cached_style_sheet_histogram.Count(true); - restored_cached_style_sheet2_histogram.Count(kStyleSheetInMemoryCache); return; } - restored_cached_style_sheet_histogram.Count(false); - StyleSheetCacheStatus cache_status = - cached_style_sheet->GetResponse().WasCached() ? kStyleSheetInDiskCache - : kStyleSheetNewEntry; - restored_cached_style_sheet2_histogram.Count(cache_status); StyleSheetContents* style_sheet = StyleSheetContents::Create(href, parser_context);
diff --git a/third_party/WebKit/Source/core/html/OWNERS b/third_party/WebKit/Source/core/html/OWNERS index 3c0b44b..cced8a8 100644 --- a/third_party/WebKit/Source/core/html/OWNERS +++ b/third_party/WebKit/Source/core/html/OWNERS
@@ -1,7 +1,6 @@ -per-file Autoplay*=mlamouri@chromium.org -per-file AutoplayUmaHelper*=zqzhang@chromium.org -per-file Media*=mlamouri@chromium.org +per-file HTMLAudio*=mlamouri@chromium.org per-file HTMLMedia*=mlamouri@chromium.org +per-file HTMLVideo*=mlamouri@chromium.org # TEAM: dom-dev@chromium.org # COMPONENT: Blink>HTML
diff --git a/third_party/WebKit/Source/core/html/TextControlElement.cpp b/third_party/WebKit/Source/core/html/TextControlElement.cpp index ade35db..fc473b4 100644 --- a/third_party/WebKit/Source/core/html/TextControlElement.cpp +++ b/third_party/WebKit/Source/core/html/TextControlElement.cpp
@@ -212,8 +212,8 @@ value_before_first_user_edit_ = String(); } -void TextControlElement::SetFocused(bool flag) { - HTMLFormControlElementWithState::SetFocused(flag); +void TextControlElement::SetFocused(bool flag, WebFocusType focus_type) { + HTMLFormControlElementWithState::SetFocused(flag, focus_type); if (!flag) DispatchFormControlChangeEvent();
diff --git a/third_party/WebKit/Source/core/html/TextControlElement.h b/third_party/WebKit/Source/core/html/TextControlElement.h index 29eafc1..536967f 100644 --- a/third_party/WebKit/Source/core/html/TextControlElement.h +++ b/third_party/WebKit/Source/core/html/TextControlElement.h
@@ -31,6 +31,7 @@ #include "core/editing/SelectionTemplate.h" #include "core/editing/VisiblePosition.h" #include "core/html/HTMLFormControlElementWithState.h" +#include "public/platform/WebFocusType.h" namespace blink { @@ -63,7 +64,7 @@ void ForwardEvent(Event*); - void SetFocused(bool flag) override; + void SetFocused(bool, WebFocusType) override; // The derived class should return true if placeholder processing is needed. virtual bool IsPlaceholderVisible() const = 0;
diff --git a/third_party/WebKit/Source/core/html/forms/MultipleFieldsTemporalInputTypeView.cpp b/third_party/WebKit/Source/core/html/forms/MultipleFieldsTemporalInputTypeView.cpp index 349375c..ea10f00 100644 --- a/third_party/WebKit/Source/core/html/forms/MultipleFieldsTemporalInputTypeView.cpp +++ b/third_party/WebKit/Source/core/html/forms/MultipleFieldsTemporalInputTypeView.cpp
@@ -165,7 +165,8 @@ GetElement().GetDocument().FocusedElement()); } -void MultipleFieldsTemporalInputTypeView::DidBlurFromControl() { +void MultipleFieldsTemporalInputTypeView::DidBlurFromControl( + WebFocusType focus_type) { // We don't need to call blur(). This function is called when control // lost focus. @@ -173,12 +174,13 @@ return; EventQueueScope scope; // Remove focus ring by CSS "focus" pseudo class. - GetElement().SetFocused(false); + GetElement().SetFocused(false, focus_type); if (SpinButtonElement* spin_button = GetSpinButtonElement()) spin_button->ReleaseCapture(); } -void MultipleFieldsTemporalInputTypeView::DidFocusOnControl() { +void MultipleFieldsTemporalInputTypeView::DidFocusOnControl( + WebFocusType focus_type) { // We don't need to call focus(). This function is called when control // got focus. @@ -186,7 +188,7 @@ return; // Add focus ring by CSS "focus" pseudo class. // FIXME: Setting the focus flag to non-focused element is too tricky. - GetElement().SetFocused(true); + GetElement().SetFocused(true, focus_type); } void MultipleFieldsTemporalInputTypeView::EditControlValueChanged() {
diff --git a/third_party/WebKit/Source/core/html/forms/MultipleFieldsTemporalInputTypeView.h b/third_party/WebKit/Source/core/html/forms/MultipleFieldsTemporalInputTypeView.h index 0dfa163a..58525078 100644 --- a/third_party/WebKit/Source/core/html/forms/MultipleFieldsTemporalInputTypeView.h +++ b/third_party/WebKit/Source/core/html/forms/MultipleFieldsTemporalInputTypeView.h
@@ -36,6 +36,7 @@ #include "core/html/shadow/DateTimeEditElement.h" #include "core/html/shadow/PickerIndicatorElement.h" #include "core/html/shadow/SpinButtonElement.h" +#include "public/platform/WebFocusType.h" namespace blink { @@ -62,8 +63,8 @@ BaseTemporalInputType&); // DateTimeEditElement::EditControlOwner functions - void DidBlurFromControl() final; - void DidFocusOnControl() final; + void DidBlurFromControl(WebFocusType) final; + void DidFocusOnControl(WebFocusType) final; void EditControlValueChanged() final; String FormatDateTimeFieldsState(const DateTimeFieldsState&) const override; bool IsEditControlOwnerDisabled() const final;
diff --git a/third_party/WebKit/Source/core/html/shadow/DateTimeEditElement.cpp b/third_party/WebKit/Source/core/html/shadow/DateTimeEditElement.cpp index d8b9024..7260fff6 100644 --- a/third_party/WebKit/Source/core/html/shadow/DateTimeEditElement.cpp +++ b/third_party/WebKit/Source/core/html/shadow/DateTimeEditElement.cpp
@@ -592,14 +592,14 @@ return style.Release(); } -void DateTimeEditElement::DidBlurFromField() { +void DateTimeEditElement::DidBlurFromField(WebFocusType focus_type) { if (edit_control_owner_) - edit_control_owner_->DidBlurFromControl(); + edit_control_owner_->DidBlurFromControl(focus_type); } -void DateTimeEditElement::DidFocusOnField() { +void DateTimeEditElement::DidFocusOnField(WebFocusType focus_type) { if (edit_control_owner_) - edit_control_owner_->DidFocusOnControl(); + edit_control_owner_->DidFocusOnControl(focus_type); } void DateTimeEditElement::DisabledStateChanged() {
diff --git a/third_party/WebKit/Source/core/html/shadow/DateTimeEditElement.h b/third_party/WebKit/Source/core/html/shadow/DateTimeEditElement.h index 14ad3ee..6231609f 100644 --- a/third_party/WebKit/Source/core/html/shadow/DateTimeEditElement.h +++ b/third_party/WebKit/Source/core/html/shadow/DateTimeEditElement.h
@@ -29,6 +29,7 @@ #include "core/html/forms/StepRange.h" #include "core/html/shadow/DateTimeFieldElement.h" #include "platform/DateComponents.h" +#include "public/platform/WebFocusType.h" #include "wtf/Allocator.h" namespace blink { @@ -52,8 +53,8 @@ class EditControlOwner : public GarbageCollectedMixin { public: virtual ~EditControlOwner(); - virtual void DidBlurFromControl() = 0; - virtual void DidFocusOnControl() = 0; + virtual void DidBlurFromControl(WebFocusType) = 0; + virtual void DidFocusOnControl(WebFocusType) = 0; virtual void EditControlValueChanged() = 0; virtual String FormatDateTimeFieldsState( const DateTimeFieldsState&) const = 0; @@ -139,8 +140,8 @@ bool IsDateTimeEditElement() const override; // DateTimeFieldElement::FieldOwner functions. - void DidBlurFromField() override; - void DidFocusOnField() override; + void DidBlurFromField(WebFocusType) override; + void DidFocusOnField(WebFocusType) override; void FieldValueChanged() override; bool FocusOnNextField(const DateTimeFieldElement&) override; bool FocusOnPreviousField(const DateTimeFieldElement&) override;
diff --git a/third_party/WebKit/Source/core/html/shadow/DateTimeFieldElement.cpp b/third_party/WebKit/Source/core/html/shadow/DateTimeFieldElement.cpp index 8ea2a29..05b9256 100644 --- a/third_party/WebKit/Source/core/html/shadow/DateTimeFieldElement.cpp +++ b/third_party/WebKit/Source/core/html/shadow/DateTimeFieldElement.cpp
@@ -131,10 +131,16 @@ } } -void DateTimeFieldElement::SetFocused(bool value) { - if (field_owner_) - value ? field_owner_->DidFocusOnField() : field_owner_->DidBlurFromField(); - ContainerNode::SetFocused(value); +void DateTimeFieldElement::SetFocused(bool value, WebFocusType focus_type) { + if (field_owner_) { + if (value) { + field_owner_->DidFocusOnField(focus_type); + } else { + field_owner_->DidBlurFromField(focus_type); + } + } + + ContainerNode::SetFocused(value, focus_type); } void DateTimeFieldElement::FocusOnNextField() {
diff --git a/third_party/WebKit/Source/core/html/shadow/DateTimeFieldElement.h b/third_party/WebKit/Source/core/html/shadow/DateTimeFieldElement.h index 286dc6fc..5bbbe560 100644 --- a/third_party/WebKit/Source/core/html/shadow/DateTimeFieldElement.h +++ b/third_party/WebKit/Source/core/html/shadow/DateTimeFieldElement.h
@@ -28,6 +28,7 @@ #include "core/html/HTMLDivElement.h" #include "core/html/HTMLSpanElement.h" +#include "public/platform/WebFocusType.h" namespace blink { @@ -49,8 +50,8 @@ class FieldOwner : public GarbageCollectedMixin { public: virtual ~FieldOwner(); - virtual void DidBlurFromField() = 0; - virtual void DidFocusOnField() = 0; + virtual void DidBlurFromField(WebFocusType) = 0; + virtual void DidFocusOnField(WebFocusType) = 0; virtual void FieldValueChanged() = 0; virtual bool FocusOnNextField(const DateTimeFieldElement&) = 0; virtual bool FocusOnPreviousField(const DateTimeFieldElement&) = 0; @@ -94,7 +95,7 @@ virtual int ValueForARIAValueNow() const; // Node functions. - void SetFocused(bool) override; + void SetFocused(bool, WebFocusType) override; private: void DefaultKeyboardEventHandler(KeyboardEvent*);
diff --git a/third_party/WebKit/Source/core/html/shadow/DateTimeNumericFieldElement.cpp b/third_party/WebKit/Source/core/html/shadow/DateTimeNumericFieldElement.cpp index ee0b4038..776ce01 100644 --- a/third_party/WebKit/Source/core/html/shadow/DateTimeNumericFieldElement.cpp +++ b/third_party/WebKit/Source/core/html/shadow/DateTimeNumericFieldElement.cpp
@@ -92,14 +92,15 @@ return range_.minimum; } -void DateTimeNumericFieldElement::SetFocused(bool value) { +void DateTimeNumericFieldElement::SetFocused(bool value, + WebFocusType focus_type) { if (!value) { int value = TypeAheadValue(); type_ahead_buffer_.Clear(); if (value >= 0) SetValueAsInteger(value, kDispatchEvent); } - DateTimeFieldElement::SetFocused(value); + DateTimeFieldElement::SetFocused(value, focus_type); } String DateTimeNumericFieldElement::FormatValue(int value) const {
diff --git a/third_party/WebKit/Source/core/html/shadow/DateTimeNumericFieldElement.h b/third_party/WebKit/Source/core/html/shadow/DateTimeNumericFieldElement.h index add44029..da257cf4 100644 --- a/third_party/WebKit/Source/core/html/shadow/DateTimeNumericFieldElement.h +++ b/third_party/WebKit/Source/core/html/shadow/DateTimeNumericFieldElement.h
@@ -27,6 +27,7 @@ #define DateTimeNumericFieldElement_h #include "core/html/shadow/DateTimeFieldElement.h" +#include "public/platform/WebFocusType.h" #include "wtf/Allocator.h" #include "wtf/text/StringBuilder.h" #include "wtf/text/WTFString.h" @@ -93,7 +94,7 @@ String Value() const final; // Node functions. - void SetFocused(bool) final; + void SetFocused(bool, WebFocusType) final; String FormatValue(int) const; int RoundUp(int) const;
diff --git a/third_party/WebKit/Source/core/html/shadow/MediaControlElements.cpp b/third_party/WebKit/Source/core/html/shadow/MediaControlElements.cpp index 117b283..cfbc784 100644 --- a/third_party/WebKit/Source/core/html/shadow/MediaControlElements.cpp +++ b/third_party/WebKit/Source/core/html/shadow/MediaControlElements.cpp
@@ -1033,36 +1033,4 @@ overlay_histogram.Count(static_cast<int>(metric)); } -// ---------------------------- - -MediaControlTimeRemainingDisplayElement:: - MediaControlTimeRemainingDisplayElement(MediaControls& media_controls) - : MediaControlTimeDisplayElement(media_controls, - kMediaTimeRemainingDisplay) {} - -MediaControlTimeRemainingDisplayElement* -MediaControlTimeRemainingDisplayElement::Create(MediaControls& media_controls) { - MediaControlTimeRemainingDisplayElement* element = - new MediaControlTimeRemainingDisplayElement(media_controls); - element->SetShadowPseudoId( - AtomicString("-webkit-media-controls-time-remaining-display")); - return element; -} - -// ---------------------------- - -MediaControlCurrentTimeDisplayElement::MediaControlCurrentTimeDisplayElement( - MediaControls& media_controls) - : MediaControlTimeDisplayElement(media_controls, kMediaCurrentTimeDisplay) { -} - -MediaControlCurrentTimeDisplayElement* -MediaControlCurrentTimeDisplayElement::Create(MediaControls& media_controls) { - MediaControlCurrentTimeDisplayElement* element = - new MediaControlCurrentTimeDisplayElement(media_controls); - element->SetShadowPseudoId( - AtomicString("-webkit-media-controls-current-time-display")); - return element; -} - } // namespace blink
diff --git a/third_party/WebKit/Source/core/html/shadow/MediaControlElements.h b/third_party/WebKit/Source/core/html/shadow/MediaControlElements.h index 537ef46..eaf89e2d 100644 --- a/third_party/WebKit/Source/core/html/shadow/MediaControlElements.h +++ b/third_party/WebKit/Source/core/html/shadow/MediaControlElements.h
@@ -336,28 +336,6 @@ bool KeepEventInNode(Event*) override; }; -// ---------------------------- - -class CORE_EXPORT MediaControlTimeRemainingDisplayElement final - : public MediaControlTimeDisplayElement { - public: - static MediaControlTimeRemainingDisplayElement* Create(MediaControls&); - - private: - explicit MediaControlTimeRemainingDisplayElement(MediaControls&); -}; - -// ---------------------------- - -class CORE_EXPORT MediaControlCurrentTimeDisplayElement final - : public MediaControlTimeDisplayElement { - public: - static MediaControlCurrentTimeDisplayElement* Create(MediaControls&); - - private: - explicit MediaControlCurrentTimeDisplayElement(MediaControls&); -}; - } // namespace blink #endif // MediaControlElements_h
diff --git a/third_party/WebKit/Source/core/inspector/InspectorNetworkAgent.cpp b/third_party/WebKit/Source/core/inspector/InspectorNetworkAgent.cpp index 8e5e630..577836f 100644 --- a/third_party/WebKit/Source/core/inspector/InspectorNetworkAgent.cpp +++ b/third_party/WebKit/Source/core/inspector/InspectorNetworkAgent.cpp
@@ -550,8 +550,8 @@ DEFINE_TRACE(InspectorNetworkAgent) { visitor->Trace(inspected_frames_); visitor->Trace(resources_data_); - visitor->Trace(replay_xh_rs_); - visitor->Trace(replay_xh_rs_to_be_deleted_); + visitor->Trace(replay_xhrs_); + visitor->Trace(replay_xhrs_to_be_deleted_); visitor->Trace(pending_xhr_replay_data_); InspectorBaseAgent::Trace(visitor); } @@ -937,10 +937,10 @@ } void InspectorNetworkAgent::DelayedRemoveReplayXHR(XMLHttpRequest* xhr) { - if (!replay_xh_rs_.Contains(xhr)) + if (!replay_xhrs_.Contains(xhr)) return; - replay_xh_rs_to_be_deleted_.insert(xhr); - replay_xh_rs_.erase(xhr); + replay_xhrs_to_be_deleted_.insert(xhr); + replay_xhrs_.erase(xhr); remove_finished_replay_xhr_timer_.StartOneShot(0, BLINK_FROM_HERE); } @@ -1387,7 +1387,7 @@ xhr->SendForInspectorXHRReplay(xhr_replay_data->FormData(), IGNORE_EXCEPTION_FOR_TESTING); - replay_xh_rs_.insert(xhr); + replay_xhrs_.insert(xhr); return Response::OK(); } @@ -1550,7 +1550,7 @@ } void InspectorNetworkAgent::RemoveFinishedReplayXHRFired(TimerBase*) { - replay_xh_rs_to_be_deleted_.Clear(); + replay_xhrs_to_be_deleted_.Clear(); } InspectorNetworkAgent::InspectorNetworkAgent(InspectedFrames* inspected_frames)
diff --git a/third_party/WebKit/Source/core/inspector/InspectorNetworkAgent.h b/third_party/WebKit/Source/core/inspector/InspectorNetworkAgent.h index c7578a0a..49f51daa 100644 --- a/third_party/WebKit/Source/core/inspector/InspectorNetworkAgent.h +++ b/third_party/WebKit/Source/core/inspector/InspectorNetworkAgent.h
@@ -276,8 +276,8 @@ HashSet<String> frames_with_scheduled_navigation_; HashSet<String> frames_with_scheduled_client_navigation_; - HeapHashSet<Member<XMLHttpRequest>> replay_xh_rs_; - HeapHashSet<Member<XMLHttpRequest>> replay_xh_rs_to_be_deleted_; + HeapHashSet<Member<XMLHttpRequest>> replay_xhrs_; + HeapHashSet<Member<XMLHttpRequest>> replay_xhrs_to_be_deleted_; TaskRunnerTimer<InspectorNetworkAgent> remove_finished_replay_xhr_timer_; };
diff --git a/third_party/WebKit/Source/core/inspector/InspectorPageAgent.cpp b/third_party/WebKit/Source/core/inspector/InspectorPageAgent.cpp index f0c0512..d951006 100644 --- a/third_party/WebKit/Source/core/inspector/InspectorPageAgent.cpp +++ b/third_party/WebKit/Source/core/inspector/InspectorPageAgent.cpp
@@ -472,7 +472,7 @@ static void CachedResourcesForDocument(Document* document, HeapVector<Member<Resource>>& result, - bool skip_xh_rs) { + bool skip_xhrs) { const ResourceFetcher::DocumentResourceMap& all_resources = document->Fetcher()->AllResources(); for (const auto& resource : all_resources) { @@ -484,7 +484,7 @@ // agent), fonts that were referenced in CSS but never used/downloaded, etc. if (cached_resource->StillNeedsLoad()) continue; - if (cached_resource->GetType() == Resource::kRaw && skip_xh_rs) + if (cached_resource->GetType() == Resource::kRaw && skip_xhrs) continue; result.push_back(cached_resource); } @@ -507,15 +507,15 @@ } static HeapVector<Member<Resource>> CachedResourcesForFrame(LocalFrame* frame, - bool skip_xh_rs) { + bool skip_xhrs) { HeapVector<Member<Resource>> result; Document* root_document = frame->GetDocument(); HeapVector<Member<Document>> loaders = InspectorPageAgent::ImportsForFrame(frame); - CachedResourcesForDocument(root_document, result, skip_xh_rs); + CachedResourcesForDocument(root_document, result, skip_xhrs); for (size_t i = 0; i < loaders.size(); ++i) - CachedResourcesForDocument(loaders[i], result, skip_xh_rs); + CachedResourcesForDocument(loaders[i], result, skip_xhrs); return result; }
diff --git a/third_party/WebKit/Source/core/layout/LayoutBlock.cpp b/third_party/WebKit/Source/core/layout/LayoutBlock.cpp index 4ff390e1..0e87a67 100644 --- a/third_party/WebKit/Source/core/layout/LayoutBlock.cpp +++ b/third_party/WebKit/Source/core/layout/LayoutBlock.cpp
@@ -418,7 +418,7 @@ Layer()->GetScrollableArea()->UpdateAfterLayout(); } -void LayoutBlock::GetLayout() { +void LayoutBlock::UpdateLayout() { DCHECK(!GetScrollableArea() || GetScrollableArea()->GetScrollAnchor()); LayoutAnalyzer::Scope analyzer(*this); @@ -430,7 +430,7 @@ // Table cells call layoutBlock directly, so don't add any logic here. Put // code into layoutBlock(). - GetLayoutBlock(false); + UpdateBlockLayout(false); // It's safe to check for control clip here, since controls can never be table // cells. If we have a lightweight clip, there can never be any overflow from @@ -467,7 +467,7 @@ return old_width != LogicalWidth() || WidthAvailableToChildrenHasChanged(); } -void LayoutBlock::GetLayoutBlock(bool) { +void LayoutBlock::UpdateBlockLayout(bool) { NOTREACHED(); ClearNeedsLayout(); }
diff --git a/third_party/WebKit/Source/core/layout/LayoutBlock.h b/third_party/WebKit/Source/core/layout/LayoutBlock.h index e8cfe68c..e2d442a 100644 --- a/third_party/WebKit/Source/core/layout/LayoutBlock.h +++ b/third_party/WebKit/Source/core/layout/LayoutBlock.h
@@ -154,7 +154,7 @@ void AddChild(LayoutObject* new_child, LayoutObject* before_child = nullptr) override; - virtual void GetLayoutBlock(bool relayout_children); + virtual void UpdateBlockLayout(bool relayout_children); void InsertPositionedObject(LayoutBox*); static void RemovePositionedObject(LayoutBox*); @@ -350,7 +350,7 @@ void DirtyForLayoutFromPercentageHeightDescendants(SubtreeLayoutScope&); - void GetLayout() override; + void UpdateLayout() override; enum PositionedLayoutBehavior { kDefaultLayout,
diff --git a/third_party/WebKit/Source/core/layout/LayoutBlockFlow.cpp b/third_party/WebKit/Source/core/layout/LayoutBlockFlow.cpp index a09f7ecb..1bac19f 100644 --- a/third_party/WebKit/Source/core/layout/LayoutBlockFlow.cpp +++ b/third_party/WebKit/Source/core/layout/LayoutBlockFlow.cpp
@@ -397,7 +397,7 @@ } DISABLE_CFI_PERF -void LayoutBlockFlow::GetLayoutBlock(bool relayout_children) { +void LayoutBlockFlow::UpdateBlockLayout(bool relayout_children) { DCHECK(NeedsLayout()); DCHECK(IsInlineBlockOrInlineTable() || !IsInline()); @@ -740,7 +740,7 @@ bool needed_layout = child.NeedsLayout(); if (needed_layout) - child.GetLayout(); + child.UpdateLayout(); if (View()->GetLayoutState()->IsPaginated()) UpdateFragmentationInfoForChild(child); return needed_layout; @@ -3734,14 +3734,14 @@ // adjacent floats which we don't fit beside, or pushed by fragmentation // if we need to break before the top margin edge of the float. SetLogicalTopForChild(child, logical_top_margin_edge + margin_before); - child.GetLayout(); + child.UpdateLayout(); // May need to push the float to the next fragmentainer before attempting // to place it. logical_top_margin_edge = AdjustFloatLogicalTopForPagination(child, logical_top_margin_edge); } else { - child.GetLayout(); + child.UpdateLayout(); } }
diff --git a/third_party/WebKit/Source/core/layout/LayoutBlockFlow.h b/third_party/WebKit/Source/core/layout/LayoutBlockFlow.h index fbf59e8..cce21118 100644 --- a/third_party/WebKit/Source/core/layout/LayoutBlockFlow.h +++ b/third_party/WebKit/Source/core/layout/LayoutBlockFlow.h
@@ -99,7 +99,7 @@ bool IsLayoutBlockFlow() const final { return true; } - void GetLayoutBlock(bool relayout_children) override; + void UpdateBlockLayout(bool relayout_children) override; void ComputeOverflow(LayoutUnit old_client_after_edge, bool recompute_floats = false) override;
diff --git a/third_party/WebKit/Source/core/layout/LayoutBox.cpp b/third_party/WebKit/Source/core/layout/LayoutBox.cpp index ae9feda..b4325a9d 100644 --- a/third_party/WebKit/Source/core/layout/LayoutBox.cpp +++ b/third_party/WebKit/Source/core/layout/LayoutBox.cpp
@@ -485,7 +485,7 @@ SetHasReflection(style_to_use.BoxReflect()); } -void LayoutBox::GetLayout() { +void LayoutBox::UpdateLayout() { DCHECK(NeedsLayout()); LayoutAnalyzer::Scope analyzer(*this); @@ -2608,7 +2608,7 @@ LayoutBox* item_marker = ToLayoutBox(item_child); // Make sure to compute the autosized width. if (item_marker->NeedsLayout()) - item_marker->GetLayout(); + item_marker->UpdateLayout(); max_width = std::max<float>( max_width, ToLayoutListMarker(item_marker)->LogicalWidth().ToFloat()); break;
diff --git a/third_party/WebKit/Source/core/layout/LayoutBox.h b/third_party/WebKit/Source/core/layout/LayoutBox.h index 78cd43b..0c932307 100644 --- a/third_party/WebKit/Source/core/layout/LayoutBox.h +++ b/third_party/WebKit/Source/core/layout/LayoutBox.h
@@ -695,7 +695,7 @@ MapCoordinatesFlags mode = 0) const override; FloatRect LocalBoundingBoxRectForAccessibility() const final; - void GetLayout() override; + void UpdateLayout() override; void Paint(const PaintInfo&, const LayoutPoint&) const override; bool NodeAtPoint(HitTestResult&, const HitTestLocation& location_in_container,
diff --git a/third_party/WebKit/Source/core/layout/LayoutBoxModelObject.cpp b/third_party/WebKit/Source/core/layout/LayoutBoxModelObject.cpp index b14965c..c62b507 100644 --- a/third_party/WebKit/Source/core/layout/LayoutBoxModelObject.cpp +++ b/third_party/WebKit/Source/core/layout/LayoutBoxModelObject.cpp
@@ -235,7 +235,7 @@ LayoutBoxModelObject::~LayoutBoxModelObject() { // Our layer should have been destroyed and cleared by now DCHECK(!HasLayer()); - DCHECK(!layer_); + DCHECK(!Layer()); } void LayoutBoxModelObject::WillBeDestroyed() { @@ -257,7 +257,8 @@ LayoutObject::WillBeDestroyed(); - DestroyLayer(); + if (HasLayer()) + DestroyLayer(); } void LayoutBoxModelObject::StyleWillChange(StyleDifference diff, @@ -328,7 +329,7 @@ if (!Layer() && LayerCreationAllowedForSubtree()) { if (was_floating_before_style_changed && IsFloating()) SetChildNeedsLayout(); - CreateLayer(); + CreateLayerAfterStyleChange(); if (Parent() && !NeedsLayout()) { // FIXME: We should call a specialized version of this function. Layer()->UpdateLayerPositionsAfterLayout(); @@ -342,7 +343,7 @@ SetHasReflection(false); Layer()->UpdateFilters(old_style, StyleRef()); Layer()->UpdateClipPath(old_style, StyleRef()); - // Calls destroyLayer() which clears m_layer. + // Calls DestroyLayer() which clears the layer. Layer()->RemoveOnlyThisLayerAfterStyleChange(); if (was_floating_before_style_changed && IsFloating()) SetChildNeedsLayout(); @@ -502,24 +503,25 @@ ->InvalidateAllStickyConstraints(); } -void LayoutBoxModelObject::CreateLayer() { - DCHECK(!layer_); - layer_ = WTF::MakeUnique<PaintLayer>(*this); +void LayoutBoxModelObject::CreateLayerAfterStyleChange() { + DCHECK(!HasLayer() && !Layer()); + EnsureRarePaintData().SetLayer(WTF::MakeUnique<PaintLayer>(*this)); SetHasLayer(true); - layer_->InsertOnlyThisLayerAfterStyleChange(); + Layer()->InsertOnlyThisLayerAfterStyleChange(); } void LayoutBoxModelObject::DestroyLayer() { + DCHECK(HasLayer() && Layer()); SetHasLayer(false); - layer_ = nullptr; + GetRarePaintData()->SetLayer(nullptr); } bool LayoutBoxModelObject::HasSelfPaintingLayer() const { - return layer_ && layer_->IsSelfPaintingLayer(); + return Layer() && Layer()->IsSelfPaintingLayer(); } PaintLayerScrollableArea* LayoutBoxModelObject::GetScrollableArea() const { - return layer_ ? layer_->GetScrollableArea() : 0; + return Layer() ? Layer()->GetScrollableArea() : nullptr; } void LayoutBoxModelObject::AddLayerHitTestRects(
diff --git a/third_party/WebKit/Source/core/layout/LayoutBoxModelObject.h b/third_party/WebKit/Source/core/layout/LayoutBoxModelObject.h index 2d62d3f..ec257ea7 100644 --- a/third_party/WebKit/Source/core/layout/LayoutBoxModelObject.h +++ b/third_party/WebKit/Source/core/layout/LayoutBoxModelObject.h
@@ -81,13 +81,11 @@ // // The reason for this partial implementation is that the 2 classes inheriting // from it (LayoutBox and LayoutInline) have different requirements but need to -// have a PaintLayer. -// For a full implementation of the box model, see LayoutBox. +// have a PaintLayer. For a full implementation of the box model, see LayoutBox. // -// An important member of this class is PaintLayer. This class is -// central to painting and hit-testing (see its class comment). -// PaintLayers are instantiated for several reasons based on the -// return value of layerTypeRequired(). +// An important member of this class is PaintLayer, which is stored in a rare- +// data pattern (see: Layer()). PaintLayers are instantiated for several reasons +// based on the return value of layerTypeRequired(). // Interestingly, most SVG objects inherit from LayoutSVGModelObject and thus // can't have a PaintLayer. This is an unfortunate artifact of our // design as it limits code sharing and prevents hardware accelerating SVG @@ -178,15 +176,16 @@ virtual int PixelSnappedOffsetHeight(const Element*) const; bool HasSelfPaintingLayer() const; - PaintLayer* Layer() const { return layer_.get(); } + PaintLayer* Layer() const { + return GetRarePaintData() ? GetRarePaintData()->Layer() : nullptr; + } + // The type of PaintLayer to instantiate. Any value returned from this + // function other than NoPaintLayer will lead to a PaintLayer being created. + virtual PaintLayerType LayerTypeRequired() const = 0; PaintLayerScrollableArea* GetScrollableArea() const; virtual void UpdateFromStyle(); - // The type of PaintLayer to instantiate. Any value returned from this - // function other than NoPaintLayer will populate |m_layer|. - virtual PaintLayerType LayerTypeRequired() const = 0; - // This will work on inlines to return the bounding box of all of the lines' // border boxes. virtual IntRect BorderBoundingBox() const = 0; @@ -535,7 +534,7 @@ bool full_remove_insert = false); private: - void CreateLayer(); + void CreateLayerAfterStyleChange(); LayoutUnit ComputedCSSPadding(const Length&) const; bool IsBoxModelObject() const final { return true; } @@ -546,10 +545,6 @@ return *rare_data_.get(); } - // The PaintLayer associated with this object. |m_layer| can be nullptr - // depending on the return value of layerTypeRequired(). - std::unique_ptr<PaintLayer> layer_; - std::unique_ptr<LayoutBoxModelObjectRareData> rare_data_; };
diff --git a/third_party/WebKit/Source/core/layout/LayoutDeprecatedFlexibleBox.cpp b/third_party/WebKit/Source/core/layout/LayoutDeprecatedFlexibleBox.cpp index 82f3e28c..ac4a5f8 100644 --- a/third_party/WebKit/Source/core/layout/LayoutDeprecatedFlexibleBox.cpp +++ b/third_party/WebKit/Source/core/layout/LayoutDeprecatedFlexibleBox.cpp
@@ -360,7 +360,7 @@ min_logical_width += scrollbar_width; } -void LayoutDeprecatedFlexibleBox::GetLayoutBlock(bool relayout_children) { +void LayoutDeprecatedFlexibleBox::UpdateBlockLayout(bool relayout_children) { DCHECK(NeedsLayout()); if (!relayout_children && SimplifiedLayout())
diff --git a/third_party/WebKit/Source/core/layout/LayoutDeprecatedFlexibleBox.h b/third_party/WebKit/Source/core/layout/LayoutDeprecatedFlexibleBox.h index 5cd6df8..7dfc6e4 100644 --- a/third_party/WebKit/Source/core/layout/LayoutDeprecatedFlexibleBox.h +++ b/third_party/WebKit/Source/core/layout/LayoutDeprecatedFlexibleBox.h
@@ -39,7 +39,7 @@ void StyleWillChange(StyleDifference, const ComputedStyle& new_style) override; - void GetLayoutBlock(bool relayout_children) override; + void UpdateBlockLayout(bool relayout_children) override; void LayoutHorizontalBox(bool relayout_children); void LayoutVerticalBox(bool relayout_children);
diff --git a/third_party/WebKit/Source/core/layout/LayoutEmbeddedObject.cpp b/third_party/WebKit/Source/core/layout/LayoutEmbeddedObject.cpp index a60df869..9263bd5 100644 --- a/third_party/WebKit/Source/core/layout/LayoutEmbeddedObject.cpp +++ b/third_party/WebKit/Source/core/layout/LayoutEmbeddedObject.cpp
@@ -126,7 +126,7 @@ .InvalidatePaintIfNeeded(); } -void LayoutEmbeddedObject::GetLayout() { +void LayoutEmbeddedObject::UpdateLayout() { DCHECK(NeedsLayout()); LayoutAnalyzer::Scope analyzer(*this);
diff --git a/third_party/WebKit/Source/core/layout/LayoutEmbeddedObject.h b/third_party/WebKit/Source/core/layout/LayoutEmbeddedObject.h index 7554523..d5f3c2e5 100644 --- a/third_party/WebKit/Source/core/layout/LayoutEmbeddedObject.h +++ b/third_party/WebKit/Source/core/layout/LayoutEmbeddedObject.h
@@ -56,7 +56,7 @@ PaintInvalidationReason InvalidatePaintIfNeeded( const PaintInvalidatorContext&) const final; - void GetLayout() final; + void UpdateLayout() final; bool IsOfType(LayoutObjectType type) const override { return type == kLayoutObjectEmbeddedObject || LayoutPart::IsOfType(type);
diff --git a/third_party/WebKit/Source/core/layout/LayoutFlexibleBox.cpp b/third_party/WebKit/Source/core/layout/LayoutFlexibleBox.cpp index a9bb92e..4632c52 100644 --- a/third_party/WebKit/Source/core/layout/LayoutFlexibleBox.cpp +++ b/third_party/WebKit/Source/core/layout/LayoutFlexibleBox.cpp
@@ -354,7 +354,7 @@ } } -void LayoutFlexibleBox::GetLayoutBlock(bool relayout_children) { +void LayoutFlexibleBox::UpdateBlockLayout(bool relayout_children) { DCHECK(NeedsLayout()); if (!relayout_children && SimplifiedLayout())
diff --git a/third_party/WebKit/Source/core/layout/LayoutFlexibleBox.h b/third_party/WebKit/Source/core/layout/LayoutFlexibleBox.h index b20428bf..a066de1 100644 --- a/third_party/WebKit/Source/core/layout/LayoutFlexibleBox.h +++ b/third_party/WebKit/Source/core/layout/LayoutFlexibleBox.h
@@ -49,7 +49,7 @@ const char* GetName() const override { return "LayoutFlexibleBox"; } bool IsFlexibleBox() const final { return true; } - void GetLayoutBlock(bool relayout_children) final; + void UpdateBlockLayout(bool relayout_children) final; int BaselinePosition( FontBaseline,
diff --git a/third_party/WebKit/Source/core/layout/LayoutFlowThread.cpp b/third_party/WebKit/Source/core/layout/LayoutFlowThread.cpp index 600a4ee..e5cd79f 100644 --- a/third_party/WebKit/Source/core/layout/LayoutFlowThread.cpp +++ b/third_party/WebKit/Source/core/layout/LayoutFlowThread.cpp
@@ -109,9 +109,9 @@ ancestor, transform_state, visual_rect_flags); } -void LayoutFlowThread::GetLayout() { +void LayoutFlowThread::UpdateLayout() { page_logical_size_changed_ = column_sets_invalidated_ && EverHadLayout(); - LayoutBlockFlow::GetLayout(); + LayoutBlockFlow::UpdateLayout(); page_logical_size_changed_ = false; }
diff --git a/third_party/WebKit/Source/core/layout/LayoutFlowThread.h b/third_party/WebKit/Source/core/layout/LayoutFlowThread.h index 168418f..f5c5712 100644 --- a/third_party/WebKit/Source/core/layout/LayoutFlowThread.h +++ b/third_party/WebKit/Source/core/layout/LayoutFlowThread.h
@@ -90,7 +90,7 @@ const LayoutObject&, AncestorSearchConstraint); - void GetLayout() override; + void UpdateLayout() override; // Always create a Layer for the LayoutFlowThread so that we // can easily avoid drawing the children directly.
diff --git a/third_party/WebKit/Source/core/layout/LayoutFrameSet.cpp b/third_party/WebKit/Source/core/layout/LayoutFrameSet.cpp index 81aa776..8298ea0 100644 --- a/third_party/WebKit/Source/core/layout/LayoutFrameSet.cpp +++ b/third_party/WebKit/Source/core/layout/LayoutFrameSet.cpp
@@ -353,7 +353,7 @@ return result; } -void LayoutFrameSet::GetLayout() { +void LayoutFrameSet::UpdateLayout() { DCHECK(NeedsLayout()); if (!Parent()->IsFrameSet() && !GetDocument().Printing()) { @@ -377,7 +377,7 @@ PositionFrames(); - LayoutBox::GetLayout(); + LayoutBox::UpdateLayout(); ComputeEdgeInfo(); @@ -422,7 +422,7 @@ child->SetSize(size); child->SetNeedsLayoutAndFullPaintInvalidation( LayoutInvalidationReason::kSizeChanged); - child->GetLayout(); + child->UpdateLayout(); } position.SetX(position.X() + size.Width() + border_thickness);
diff --git a/third_party/WebKit/Source/core/layout/LayoutFrameSet.h b/third_party/WebKit/Source/core/layout/LayoutFrameSet.h index bcda1675..2de8da5c 100644 --- a/third_party/WebKit/Source/core/layout/LayoutFrameSet.h +++ b/third_party/WebKit/Source/core/layout/LayoutFrameSet.h
@@ -125,7 +125,7 @@ return type == kLayoutObjectFrameSet || LayoutBox::IsOfType(type); } - void GetLayout() override; + void UpdateLayout() override; void Paint(const PaintInfo&, const LayoutPoint&) const override; void ComputePreferredLogicalWidths() override; bool IsChildAllowed(LayoutObject*, const ComputedStyle&) const override;
diff --git a/third_party/WebKit/Source/core/layout/LayoutGrid.cpp b/third_party/WebKit/Source/core/layout/LayoutGrid.cpp index 7e29a9d..36ebdd06 100644 --- a/third_party/WebKit/Source/core/layout/LayoutGrid.cpp +++ b/third_party/WebKit/Source/core/layout/LayoutGrid.cpp
@@ -211,7 +211,7 @@ } } -void LayoutGrid::GetLayoutBlock(bool relayout_children) { +void LayoutGrid::UpdateBlockLayout(bool relayout_children) { DCHECK(NeedsLayout()); // We cannot perform a simplifiedLayout() on a dirty grid that
diff --git a/third_party/WebKit/Source/core/layout/LayoutGrid.h b/third_party/WebKit/Source/core/layout/LayoutGrid.h index ba80bbb3..ac55656 100644 --- a/third_party/WebKit/Source/core/layout/LayoutGrid.h +++ b/third_party/WebKit/Source/core/layout/LayoutGrid.h
@@ -51,7 +51,7 @@ static LayoutGrid* CreateAnonymous(Document*); const char* GetName() const override { return "LayoutGrid"; } - void GetLayoutBlock(bool relayout_children) override; + void UpdateBlockLayout(bool relayout_children) override; void DirtyGrid();
diff --git a/third_party/WebKit/Source/core/layout/LayoutIFrame.cpp b/third_party/WebKit/Source/core/layout/LayoutIFrame.cpp index beb264f..7f96b48 100644 --- a/third_party/WebKit/Source/core/layout/LayoutIFrame.cpp +++ b/third_party/WebKit/Source/core/layout/LayoutIFrame.cpp
@@ -45,7 +45,7 @@ return LayoutPart::LayerTypeRequired(); } -void LayoutIFrame::GetLayout() { +void LayoutIFrame::UpdateLayout() { DCHECK(NeedsLayout()); LayoutAnalyzer::Scope analyzer(*this);
diff --git a/third_party/WebKit/Source/core/layout/LayoutIFrame.h b/third_party/WebKit/Source/core/layout/LayoutIFrame.h index 4ff524f8..56bda2e8 100644 --- a/third_party/WebKit/Source/core/layout/LayoutIFrame.h +++ b/third_party/WebKit/Source/core/layout/LayoutIFrame.h
@@ -40,7 +40,7 @@ bool ShouldComputeSizeAsReplaced() const override; bool IsInlineBlockOrInlineTable() const override; - void GetLayout() override; + void UpdateLayout() override; bool IsOfType(LayoutObjectType type) const override { return type == kLayoutObjectLayoutIFrame || LayoutPart::IsOfType(type);
diff --git a/third_party/WebKit/Source/core/layout/LayoutInline.h b/third_party/WebKit/Source/core/layout/LayoutInline.h index 8364c5a9..3b3348b3 100644 --- a/third_party/WebKit/Source/core/layout/LayoutInline.h +++ b/third_party/WebKit/Source/core/layout/LayoutInline.h
@@ -276,7 +276,7 @@ LayoutObject* new_child, LayoutBoxModelObject* old_cont); - void GetLayout() final { NOTREACHED(); } // Do nothing for layout() + void UpdateLayout() final { NOTREACHED(); } // Do nothing for layout() void Paint(const PaintInfo&, const LayoutPoint&) const final;
diff --git a/third_party/WebKit/Source/core/layout/LayoutListMarker.cpp b/third_party/WebKit/Source/core/layout/LayoutListMarker.cpp index 4e32b13..fdca9de 100644 --- a/third_party/WebKit/Source/core/layout/LayoutListMarker.cpp +++ b/third_party/WebKit/Source/core/layout/LayoutListMarker.cpp
@@ -135,7 +135,7 @@ ListMarkerPainter(*this).Paint(paint_info, paint_offset); } -void LayoutListMarker::GetLayout() { +void LayoutListMarker::UpdateLayout() { DCHECK(NeedsLayout()); LayoutAnalyzer::Scope analyzer(*this);
diff --git a/third_party/WebKit/Source/core/layout/LayoutListMarker.h b/third_party/WebKit/Source/core/layout/LayoutListMarker.h index 33749f0..fb59bde 100644 --- a/third_party/WebKit/Source/core/layout/LayoutListMarker.h +++ b/third_party/WebKit/Source/core/layout/LayoutListMarker.h
@@ -78,7 +78,7 @@ void Paint(const PaintInfo&, const LayoutPoint&) const override; - void GetLayout() override; + void UpdateLayout() override; void ImageChanged(WrappedImagePtr, const IntRect* = nullptr) override;
diff --git a/third_party/WebKit/Source/core/layout/LayoutMedia.cpp b/third_party/WebKit/Source/core/layout/LayoutMedia.cpp index ed53fc2..b78615d 100644 --- a/third_party/WebKit/Source/core/layout/LayoutMedia.cpp +++ b/third_party/WebKit/Source/core/layout/LayoutMedia.cpp
@@ -44,10 +44,10 @@ return ToHTMLMediaElement(GetNode()); } -void LayoutMedia::GetLayout() { +void LayoutMedia::UpdateLayout() { LayoutSize old_size = ContentBoxRect().size(); - LayoutImage::GetLayout(); + LayoutImage::UpdateLayout(); LayoutRect new_rect = ContentBoxRect();
diff --git a/third_party/WebKit/Source/core/layout/LayoutMedia.h b/third_party/WebKit/Source/core/layout/LayoutMedia.h index 47de518..f5a0c24d 100644 --- a/third_party/WebKit/Source/core/layout/LayoutMedia.h +++ b/third_party/WebKit/Source/core/layout/LayoutMedia.h
@@ -59,7 +59,7 @@ const char* GetName() const override { return "LayoutMedia"; } protected: - void GetLayout() override; + void UpdateLayout() override; bool IsOfType(LayoutObjectType type) const override { return type == kLayoutObjectMedia || LayoutImage::IsOfType(type);
diff --git a/third_party/WebKit/Source/core/layout/LayoutMultiColumnFlowThread.cpp b/third_party/WebKit/Source/core/layout/LayoutMultiColumnFlowThread.cpp index 8ecbbfd8..bc5b01e 100644 --- a/third_party/WebKit/Source/core/layout/LayoutMultiColumnFlowThread.cpp +++ b/third_party/WebKit/Source/core/layout/LayoutMultiColumnFlowThread.cpp
@@ -567,7 +567,7 @@ column_heights_changed_ = false; InvalidateColumnSets(); - GetLayout(); + UpdateLayout(); ValidateColumnSets(); } @@ -1313,12 +1313,12 @@ SetLogicalWidth(column_width); } -void LayoutMultiColumnFlowThread::GetLayout() { +void LayoutMultiColumnFlowThread::UpdateLayout() { DCHECK(!last_set_worked_on_); last_set_worked_on_ = FirstMultiColumnSet(); if (last_set_worked_on_) last_set_worked_on_->BeginFlow(LayoutUnit()); - LayoutFlowThread::GetLayout(); + LayoutFlowThread::UpdateLayout(); if (LayoutMultiColumnSet* last_set = LastMultiColumnSet()) { DCHECK_EQ(last_set, last_set_worked_on_); if (!last_set->NextSiblingMultiColumnSet()) {
diff --git a/third_party/WebKit/Source/core/layout/LayoutMultiColumnFlowThread.h b/third_party/WebKit/Source/core/layout/LayoutMultiColumnFlowThread.h index 468bf5c..a0d92ee14 100644 --- a/third_party/WebKit/Source/core/layout/LayoutMultiColumnFlowThread.h +++ b/third_party/WebKit/Source/core/layout/LayoutMultiColumnFlowThread.h
@@ -290,7 +290,7 @@ progression_is_inline_ = is_inline; } - void GetLayout() override; + void UpdateLayout() override; private: void CalculateColumnHeightAvailable();
diff --git a/third_party/WebKit/Source/core/layout/LayoutMultiColumnSet.cpp b/third_party/WebKit/Source/core/layout/LayoutMultiColumnSet.cpp index b195e54..865422d 100644 --- a/third_party/WebKit/Source/core/layout/LayoutMultiColumnSet.cpp +++ b/third_party/WebKit/Source/core/layout/LayoutMultiColumnSet.cpp
@@ -443,10 +443,10 @@ SetHasBoxDecorationBackground(true); } -void LayoutMultiColumnSet::GetLayout() { +void LayoutMultiColumnSet::UpdateLayout() { if (RecalculateColumnHeight()) MultiColumnFlowThread()->SetColumnHeightsChanged(); - LayoutBlockFlow::GetLayout(); + LayoutBlockFlow::UpdateLayout(); } void LayoutMultiColumnSet::ComputeIntrinsicLogicalWidths(
diff --git a/third_party/WebKit/Source/core/layout/LayoutMultiColumnSet.h b/third_party/WebKit/Source/core/layout/LayoutMultiColumnSet.h index 525b895a..e5d8d57 100644 --- a/third_party/WebKit/Source/core/layout/LayoutMultiColumnSet.h +++ b/third_party/WebKit/Source/core/layout/LayoutMultiColumnSet.h
@@ -205,7 +205,7 @@ void EndFlow(LayoutUnit offset_in_flow_thread); void StyleDidChange(StyleDifference, const ComputedStyle* old_style) override; - void GetLayout() override; + void UpdateLayout() override; void ComputeIntrinsicLogicalWidths(LayoutUnit& min_logical_width, LayoutUnit& max_logical_width) const final;
diff --git a/third_party/WebKit/Source/core/layout/LayoutMultiColumnSpannerPlaceholder.cpp b/third_party/WebKit/Source/core/layout/LayoutMultiColumnSpannerPlaceholder.cpp index 02f8c326..47a443c 100644 --- a/third_party/WebKit/Source/core/layout/LayoutMultiColumnSpannerPlaceholder.cpp +++ b/third_party/WebKit/Source/core/layout/LayoutMultiColumnSpannerPlaceholder.cpp
@@ -105,7 +105,7 @@ return layout_object_in_flow_thread_->MaxPreferredLogicalWidth(); } -void LayoutMultiColumnSpannerPlaceholder::GetLayout() { +void LayoutMultiColumnSpannerPlaceholder::UpdateLayout() { DCHECK(NeedsLayout()); // The placeholder, like any other block level object, has its logical top
diff --git a/third_party/WebKit/Source/core/layout/LayoutMultiColumnSpannerPlaceholder.h b/third_party/WebKit/Source/core/layout/LayoutMultiColumnSpannerPlaceholder.h index 7225928e..6f1c1c55 100644 --- a/third_party/WebKit/Source/core/layout/LayoutMultiColumnSpannerPlaceholder.h +++ b/third_party/WebKit/Source/core/layout/LayoutMultiColumnSpannerPlaceholder.h
@@ -55,7 +55,7 @@ bool NeedsPreferredWidthsRecalculation() const override; LayoutUnit MinPreferredLogicalWidth() const override; LayoutUnit MaxPreferredLogicalWidth() const override; - void GetLayout() override; + void UpdateLayout() override; void ComputeLogicalHeight(LayoutUnit logical_height, LayoutUnit logical_top, LogicalExtentComputedValues&) const override;
diff --git a/third_party/WebKit/Source/core/layout/LayoutObject.cpp b/third_party/WebKit/Source/core/layout/LayoutObject.cpp index f5dbd8baa..465007f 100644 --- a/third_party/WebKit/Source/core/layout/LayoutObject.cpp +++ b/third_party/WebKit/Source/core/layout/LayoutObject.cpp
@@ -3031,7 +3031,7 @@ void LayoutObject::ForceLayout() { SetSelfNeedsLayout(true); SetShouldDoFullPaintInvalidation(); - GetLayout(); + UpdateLayout(); } // FIXME: Does this do anything different than forceLayout given that we don't @@ -3039,7 +3039,7 @@ // forceLayout. void LayoutObject::ForceChildLayout() { SetNormalChildNeedsLayout(true); - GetLayout(); + UpdateLayout(); } enum StyleCacheState { kCached, kUncached };
diff --git a/third_party/WebKit/Source/core/layout/LayoutObject.h b/third_party/WebKit/Source/core/layout/LayoutObject.h index d1d382e..76b84e2 100644 --- a/third_party/WebKit/Source/core/layout/LayoutObject.h +++ b/third_party/WebKit/Source/core/layout/LayoutObject.h
@@ -417,9 +417,6 @@ PropertyTreeState ContentsProperties() const; private: - RarePaintData& EnsureRarePaintData(); - RarePaintData* GetRarePaintData() { return rare_paint_data_.get(); } - ////////////////////////////////////////// // Helper functions. Dangerous to use! void SetPreviousSibling(LayoutObject* previous) { previous_ = previous; } @@ -1089,7 +1086,7 @@ // In some cases, layout has to force laying out more children. An example is // when the width of the LayoutObject changes as this impacts children with // 'width' set to auto. - virtual void GetLayout() = 0; + virtual void UpdateLayout() = 0; virtual bool UpdateImageLoadingPriorities() { return false; } void HandleSubtreeModifications(); @@ -1120,7 +1117,7 @@ /* This function performs a layout only if one is needed. */ DISABLE_CFI_PERF void LayoutIfNeeded() { if (NeedsLayout()) - GetLayout(); + UpdateLayout(); } void ForceLayout(); @@ -2108,6 +2105,9 @@ bitfields_.SetPreviousOutlineMayBeAffectedByDescendants(b); } + RarePaintData& EnsureRarePaintData(); + RarePaintData* GetRarePaintData() const { return rare_paint_data_.get(); } + private: // Used only by applyFirstLineChanges to get a first line style based off of a // given new style, without accessing the cache.
diff --git a/third_party/WebKit/Source/core/layout/LayoutPagedFlowThread.cpp b/third_party/WebKit/Source/core/layout/LayoutPagedFlowThread.cpp index a07d6a2..bfe72a3 100644 --- a/third_party/WebKit/Source/core/layout/LayoutPagedFlowThread.cpp +++ b/third_party/WebKit/Source/core/layout/LayoutPagedFlowThread.cpp
@@ -36,11 +36,11 @@ LayoutFlowThread::UpdateLogicalWidth(); } -void LayoutPagedFlowThread::GetLayout() { +void LayoutPagedFlowThread::UpdateLayout() { // There should either be zero or one of those for paged layout. DCHECK_EQ(FirstMultiColumnBox(), LastMultiColumnBox()); SetProgressionIsInline(PagedBlockFlow()->Style()->HasInlinePaginationAxis()); - LayoutMultiColumnFlowThread::GetLayout(); + LayoutMultiColumnFlowThread::UpdateLayout(); LayoutMultiColumnSet* column_set = FirstMultiColumnSet(); if (!column_set)
diff --git a/third_party/WebKit/Source/core/layout/LayoutPagedFlowThread.h b/third_party/WebKit/Source/core/layout/LayoutPagedFlowThread.h index 27ce2b4..e83af7e 100644 --- a/third_party/WebKit/Source/core/layout/LayoutPagedFlowThread.h +++ b/third_party/WebKit/Source/core/layout/LayoutPagedFlowThread.h
@@ -31,7 +31,7 @@ const char* GetName() const override { return "LayoutPagedFlowThread"; } bool NeedsNewWidth() const override; void UpdateLogicalWidth() override; - virtual void GetLayout(); + void UpdateLayout() override; private: bool DescendantIsValidColumnSpanner(
diff --git a/third_party/WebKit/Source/core/layout/LayoutPart.cpp b/third_party/WebKit/Source/core/layout/LayoutPart.cpp index 97212dd..a0aaeeb 100644 --- a/third_party/WebKit/Source/core/layout/LayoutPart.cpp +++ b/third_party/WebKit/Source/core/layout/LayoutPart.cpp
@@ -271,7 +271,7 @@ } } -void LayoutPart::GetLayout() { +void LayoutPart::UpdateLayout() { DCHECK(NeedsLayout()); LayoutAnalyzer::Scope analyzer(*this); ClearNeedsLayout(); @@ -358,7 +358,7 @@ // FrameViewBase size. if (frame_view && frame_view->NeedsLayout() && frame_view->GetFrame().GetPage()) - frame_view->Layout(); + frame_view->UpdateLayout(); frame_view_base->GeometryMayHaveChanged(); }
diff --git a/third_party/WebKit/Source/core/layout/LayoutPart.h b/third_party/WebKit/Source/core/layout/LayoutPart.h index a1577ce..1d2f1253 100644 --- a/third_party/WebKit/Source/core/layout/LayoutPart.h +++ b/third_party/WebKit/Source/core/layout/LayoutPart.h
@@ -71,7 +71,7 @@ PaintLayerType LayerTypeRequired() const override; void StyleDidChange(StyleDifference, const ComputedStyle* old_style) final; - void GetLayout() override; + void UpdateLayout() override; void Paint(const PaintInfo&, const LayoutPoint&) const override; CursorDirective GetCursor(const LayoutPoint&, Cursor&) const final;
diff --git a/third_party/WebKit/Source/core/layout/LayoutReplaced.cpp b/third_party/WebKit/Source/core/layout/LayoutReplaced.cpp index 9bb100c9..6af1fdf 100644 --- a/third_party/WebKit/Source/core/layout/LayoutReplaced.cpp +++ b/third_party/WebKit/Source/core/layout/LayoutReplaced.cpp
@@ -76,7 +76,7 @@ IntrinsicSizeChanged(); } -void LayoutReplaced::GetLayout() { +void LayoutReplaced::UpdateLayout() { DCHECK(NeedsLayout()); LayoutAnalyzer::Scope analyzer(*this);
diff --git a/third_party/WebKit/Source/core/layout/LayoutReplaced.h b/third_party/WebKit/Source/core/layout/LayoutReplaced.h index e277866..fa42425 100644 --- a/third_party/WebKit/Source/core/layout/LayoutReplaced.h +++ b/third_party/WebKit/Source/core/layout/LayoutReplaced.h
@@ -97,7 +97,7 @@ protected: void WillBeDestroyed() override; - void GetLayout() override; + void UpdateLayout() override; LayoutSize IntrinsicSize() const final { return intrinsic_size_; } virtual void ComputeIntrinsicSizingInfo(IntrinsicSizingInfo&) const;
diff --git a/third_party/WebKit/Source/core/layout/LayoutRubyRun.cpp b/third_party/WebKit/Source/core/layout/LayoutRubyRun.cpp index e3685e01..1c7245d4 100644 --- a/third_party/WebKit/Source/core/layout/LayoutRubyRun.cpp +++ b/third_party/WebKit/Source/core/layout/LayoutRubyRun.cpp
@@ -215,8 +215,8 @@ return rt; } -void LayoutRubyRun::GetLayout() { - LayoutBlockFlow::GetLayout(); +void LayoutRubyRun::UpdateLayout() { + LayoutBlockFlow::UpdateLayout(); LayoutRubyText* rt = RubyText(); if (!rt)
diff --git a/third_party/WebKit/Source/core/layout/LayoutRubyRun.h b/third_party/WebKit/Source/core/layout/LayoutRubyRun.h index f574b0d..74ad811 100644 --- a/third_party/WebKit/Source/core/layout/LayoutRubyRun.h +++ b/third_party/WebKit/Source/core/layout/LayoutRubyRun.h
@@ -56,7 +56,7 @@ LayoutObject* LayoutSpecialExcludedChild(bool relayout_children, SubtreeLayoutScope&) override; - void GetLayout() override; + void UpdateLayout() override; bool IsChildAllowed(LayoutObject*, const ComputedStyle&) const override; void AddChild(LayoutObject* child,
diff --git a/third_party/WebKit/Source/core/layout/LayoutScrollbar.cpp b/third_party/WebKit/Source/core/layout/LayoutScrollbar.cpp index de98cc0..a1e7ea8 100644 --- a/third_party/WebKit/Source/core/layout/LayoutScrollbar.cpp +++ b/third_party/WebKit/Source/core/layout/LayoutScrollbar.cpp
@@ -63,7 +63,7 @@ IntRect rect(0, 0, 0, 0); UpdateScrollbarPart(kScrollbarBGPart); if (LayoutScrollbarPart* part = parts_.at(kScrollbarBGPart)) { - part->GetLayout(); + part->UpdateLayout(); rect.SetSize(FlooredIntSize(part->size())); } else if (this->Orientation() == kHorizontalScrollbar) { rect.SetWidth(this->Width()); @@ -174,7 +174,7 @@ int new_thickness = 0; LayoutScrollbarPart* part = parts_.at(kScrollbarBGPart); if (part) { - part->GetLayout(); + part->UpdateLayout(); new_thickness = (is_horizontal ? part->size().Height() : part->size().Width()).ToInt(); } @@ -286,7 +286,7 @@ if (!part_layout_object) return IntRect(); - part_layout_object->GetLayout(); + part_layout_object->UpdateLayout(); bool is_horizontal = Orientation() == kHorizontalScrollbar; if (part_type == kBackButtonStartPart) @@ -331,7 +331,7 @@ IntRect LayoutScrollbar::TrackRect(int start_length, int end_length) const { LayoutScrollbarPart* part = parts_.at(kTrackBGPart); if (part) - part->GetLayout(); + part->UpdateLayout(); if (Orientation() == kHorizontalScrollbar) { int margin_left = part ? part->MarginLeft().ToInt() : 0; @@ -358,7 +358,7 @@ if (!part_layout_object) return old_rect; - part_layout_object->GetLayout(); + part_layout_object->UpdateLayout(); IntRect rect = old_rect; if (Orientation() == kHorizontalScrollbar) { @@ -376,7 +376,7 @@ LayoutScrollbarPart* part_layout_object = parts_.at(kThumbPart); if (!part_layout_object) return 0; - part_layout_object->GetLayout(); + part_layout_object->UpdateLayout(); return (Orientation() == kHorizontalScrollbar ? part_layout_object->size().Width() : part_layout_object->size().Height())
diff --git a/third_party/WebKit/Source/core/layout/LayoutScrollbarPart.cpp b/third_party/WebKit/Source/core/layout/LayoutScrollbarPart.cpp index 02cdbbc2..6772fb1 100644 --- a/third_party/WebKit/Source/core/layout/LayoutScrollbarPart.cpp +++ b/third_party/WebKit/Source/core/layout/LayoutScrollbarPart.cpp
@@ -93,7 +93,7 @@ return layout_object; } -void LayoutScrollbarPart::GetLayout() { +void LayoutScrollbarPart::UpdateLayout() { // We don't worry about positioning ourselves. We're just determining our // minimum width/height. SetLocation(LayoutPoint());
diff --git a/third_party/WebKit/Source/core/layout/LayoutScrollbarPart.h b/third_party/WebKit/Source/core/layout/LayoutScrollbarPart.h index c416037a..565e349 100644 --- a/third_party/WebKit/Source/core/layout/LayoutScrollbarPart.h +++ b/third_party/WebKit/Source/core/layout/LayoutScrollbarPart.h
@@ -46,7 +46,7 @@ PaintLayerType LayerTypeRequired() const override { return kNoPaintLayer; } - void GetLayout() override; + void UpdateLayout() override; // Scrollbar parts needs to be rendered at device pixel boundaries. LayoutRectOutsets MarginBoxOutsets() const override {
diff --git a/third_party/WebKit/Source/core/layout/LayoutSlider.cpp b/third_party/WebKit/Source/core/layout/LayoutSlider.cpp index fbe825a..194ff624 100644 --- a/third_party/WebKit/Source/core/layout/LayoutSlider.cpp +++ b/third_party/WebKit/Source/core/layout/LayoutSlider.cpp
@@ -63,14 +63,14 @@ ShadowElementNames::SliderThumb())); } -void LayoutSlider::GetLayout() { +void LayoutSlider::UpdateLayout() { // FIXME: Find a way to cascade appearance. // http://webkit.org/b/62535 LayoutBox* thumb_box = GetSliderThumbElement()->GetLayoutBox(); if (thumb_box && thumb_box->IsSliderThumb()) ToLayoutSliderThumb(thumb_box)->UpdateAppearance(StyleRef()); - LayoutFlexibleBox::GetLayout(); + LayoutFlexibleBox::UpdateLayout(); } bool LayoutSlider::InDragMode() const {
diff --git a/third_party/WebKit/Source/core/layout/LayoutSlider.h b/third_party/WebKit/Source/core/layout/LayoutSlider.h index 397c1998..3aceac2 100644 --- a/third_party/WebKit/Source/core/layout/LayoutSlider.h +++ b/third_party/WebKit/Source/core/layout/LayoutSlider.h
@@ -52,7 +52,7 @@ void ComputeIntrinsicLogicalWidths( LayoutUnit& min_logical_width, LayoutUnit& max_logical_width) const override; - void GetLayout() override; + void UpdateLayout() override; SliderThumbElement* GetSliderThumbElement() const; };
diff --git a/third_party/WebKit/Source/core/layout/LayoutSliderContainer.cpp b/third_party/WebKit/Source/core/layout/LayoutSliderContainer.cpp index 9736f9d..213d375b 100644 --- a/third_party/WebKit/Source/core/layout/LayoutSliderContainer.cpp +++ b/third_party/WebKit/Source/core/layout/LayoutSliderContainer.cpp
@@ -96,7 +96,7 @@ LayoutBox::ComputeLogicalHeight(logical_height, logical_top, computed_values); } -void LayoutSliderContainer::GetLayout() { +void LayoutSliderContainer::UpdateLayout() { HTMLInputElement* input = toHTMLInputElement(GetNode()->OwnerShadowHost()); bool is_vertical = HasVerticalAppearance(input); MutableStyleRef().SetFlexDirection(is_vertical ? kFlowColumn : kFlowRow); @@ -123,7 +123,7 @@ if (track) layout_scope.SetChildNeedsLayout(track); - LayoutFlexibleBox::GetLayout(); + LayoutFlexibleBox::UpdateLayout(); MutableStyleRef().SetDirection(old_text_direction); // These should always exist, unless someone mutates the shadow DOM (e.g., in
diff --git a/third_party/WebKit/Source/core/layout/LayoutSliderContainer.h b/third_party/WebKit/Source/core/layout/LayoutSliderContainer.h index 9b36d13..abb606b 100644 --- a/third_party/WebKit/Source/core/layout/LayoutSliderContainer.h +++ b/third_party/WebKit/Source/core/layout/LayoutSliderContainer.h
@@ -48,7 +48,7 @@ LogicalExtentComputedValues&) const override; private: - void GetLayout() override; + void UpdateLayout() override; }; } // namespace blink
diff --git a/third_party/WebKit/Source/core/layout/LayoutTable.cpp b/third_party/WebKit/Source/core/layout/LayoutTable.cpp index 61d5aad..ab15cfc 100644 --- a/third_party/WebKit/Source/core/layout/LayoutTable.cpp +++ b/third_party/WebKit/Source/core/layout/LayoutTable.cpp
@@ -461,7 +461,7 @@ MarkChildForPaginationRelayoutIfNeeded(section, layouter); bool needed_layout = section.NeedsLayout(); if (needed_layout) - section.GetLayout(); + section.UpdateLayout(); if (needed_layout || table_height_changing == kTableHeightChanging) section.SetLogicalHeight(LayoutUnit(section.CalcRowLogicalHeight())); @@ -559,7 +559,7 @@ children_overflow_changed; } -void LayoutTable::GetLayout() { +void LayoutTable::UpdateLayout() { DCHECK(NeedsLayout()); LayoutAnalyzer::Scope analyzer(*this); @@ -597,7 +597,7 @@ // layout that tells us if something has changed in the min max // calculations to do it correctly. // if ( oldWidth != width() || columns.size() + 1 != columnPos.size() ) - table_layout_->GetLayout(); + table_layout_->UpdateLayout(); // Lay out top captions. // FIXME: Collapse caption margin.
diff --git a/third_party/WebKit/Source/core/layout/LayoutTable.h b/third_party/WebKit/Source/core/layout/LayoutTable.h index 1ecef1aa..0fbb8db 100644 --- a/third_party/WebKit/Source/core/layout/LayoutTable.h +++ b/third_party/WebKit/Source/core/layout/LayoutTable.h
@@ -481,7 +481,7 @@ } void PaintObject(const PaintInfo&, const LayoutPoint&) const override; - void GetLayout() override; + void UpdateLayout() override; void ComputeIntrinsicLogicalWidths(LayoutUnit& min_width, LayoutUnit& max_width) const override; void ComputePreferredLogicalWidths() override;
diff --git a/third_party/WebKit/Source/core/layout/LayoutTableCell.cpp b/third_party/WebKit/Source/core/layout/LayoutTableCell.cpp index 6a53a19..651f157f 100644 --- a/third_party/WebKit/Source/core/layout/LayoutTableCell.cpp +++ b/third_party/WebKit/Source/core/layout/LayoutTableCell.cpp
@@ -300,12 +300,12 @@ SetCellWidthChanged(true); } -void LayoutTableCell::GetLayout() { +void LayoutTableCell::UpdateLayout() { DCHECK(NeedsLayout()); LayoutAnalyzer::Scope analyzer(*this); int old_cell_baseline = CellBaselinePosition(); - GetLayoutBlock(CellWidthChanged()); + UpdateBlockLayout(CellWidthChanged()); // If we have replaced content, the intrinsic height of our content may have // changed since the last time we laid out. If that's the case the intrinsic @@ -324,7 +324,7 @@ SetIntrinsicPaddingBefore(new_intrinsic_padding_before); SubtreeLayoutScope layouter(*this); layouter.SetNeedsLayout(this, LayoutInvalidationReason::kTableChanged); - GetLayoutBlock(CellWidthChanged()); + UpdateBlockLayout(CellWidthChanged()); } // FIXME: This value isn't the intrinsic content logical height, but we need
diff --git a/third_party/WebKit/Source/core/layout/LayoutTableCell.h b/third_party/WebKit/Source/core/layout/LayoutTableCell.h index f89440f..fa4c3be 100644 --- a/third_party/WebKit/Source/core/layout/LayoutTableCell.h +++ b/third_party/WebKit/Source/core/layout/LayoutTableCell.h
@@ -190,7 +190,7 @@ void CollectBorderValues(LayoutTable::CollapsedBorderValues&); static void SortBorderValues(LayoutTable::CollapsedBorderValues&); - void GetLayout() override; + void UpdateLayout() override; void Paint(const PaintInfo&, const LayoutPoint&) const override;
diff --git a/third_party/WebKit/Source/core/layout/LayoutTableRow.cpp b/third_party/WebKit/Source/core/layout/LayoutTableRow.cpp index ebd5f49..43ce123 100644 --- a/third_party/WebKit/Source/core/layout/LayoutTableRow.cpp +++ b/third_party/WebKit/Source/core/layout/LayoutTableRow.cpp
@@ -186,7 +186,7 @@ Section()->SetNeedsCellRecalc(); } -void LayoutTableRow::GetLayout() { +void LayoutTableRow::UpdateLayout() { DCHECK(NeedsLayout()); LayoutAnalyzer::Scope analyzer(*this); bool paginated = View()->GetLayoutState()->IsPaginated(); @@ -197,7 +197,7 @@ if (!cell->NeedsLayout()) Section()->MarkChildForPaginationRelayoutIfNeeded(*cell, layouter); if (cell->NeedsLayout()) - cell->GetLayout(); + cell->UpdateLayout(); if (paginated) Section()->UpdateFragmentationInfoForChild(*cell); }
diff --git a/third_party/WebKit/Source/core/layout/LayoutTableRow.h b/third_party/WebKit/Source/core/layout/LayoutTableRow.h index da14a65..38c748d3 100644 --- a/third_party/WebKit/Source/core/layout/LayoutTableRow.h +++ b/third_party/WebKit/Source/core/layout/LayoutTableRow.h
@@ -154,7 +154,7 @@ void AddChild(LayoutObject* child, LayoutObject* before_child = nullptr) override; - void GetLayout() override; + void UpdateLayout() override; PaintLayerType LayerTypeRequired() const override { if (HasTransformRelatedProperty() || HasHiddenBackface() || HasClipPath() ||
diff --git a/third_party/WebKit/Source/core/layout/LayoutTableSection.cpp b/third_party/WebKit/Source/core/layout/LayoutTableSection.cpp index a3cdee8..88ff3a5 100644 --- a/third_party/WebKit/Source/core/layout/LayoutTableSection.cpp +++ b/third_party/WebKit/Source/core/layout/LayoutTableSection.cpp
@@ -949,7 +949,7 @@ return row_pos_[grid_.size()]; } -void LayoutTableSection::GetLayout() { +void LayoutTableSection::UpdateLayout() { DCHECK(NeedsLayout()); LayoutAnalyzer::Scope analyzer(*this); CHECK(!NeedsCellRecalc());
diff --git a/third_party/WebKit/Source/core/layout/LayoutTableSection.h b/third_party/WebKit/Source/core/layout/LayoutTableSection.h index a20c32bf..dfdc4c1 100644 --- a/third_party/WebKit/Source/core/layout/LayoutTableSection.h +++ b/third_party/WebKit/Source/core/layout/LayoutTableSection.h
@@ -350,7 +350,7 @@ bool IsRepeatingHeaderGroup() const; - void GetLayout() override; + void UpdateLayout() override; CellSpan FullSectionRowSpan() const { return CellSpan(0, grid_.size()); } CellSpan FullTableEffectiveColumnSpan() const {
diff --git a/third_party/WebKit/Source/core/layout/LayoutText.h b/third_party/WebKit/Source/core/layout/LayoutText.h index 84b9a48..8727272 100644 --- a/third_party/WebKit/Source/core/layout/LayoutText.h +++ b/third_party/WebKit/Source/core/layout/LayoutText.h
@@ -261,7 +261,7 @@ // See the class comment as to why we shouldn't call this function directly. void Paint(const PaintInfo&, const LayoutPoint&) const final { NOTREACHED(); } - void GetLayout() final { NOTREACHED(); } + void UpdateLayout() final { NOTREACHED(); } bool NodeAtPoint(HitTestResult&, const HitTestLocation&, const LayoutPoint&,
diff --git a/third_party/WebKit/Source/core/layout/LayoutTextControlSingleLine.cpp b/third_party/WebKit/Source/core/layout/LayoutTextControlSingleLine.cpp index 18a923d1..4442f4fd 100644 --- a/third_party/WebKit/Source/core/layout/LayoutTextControlSingleLine.cpp +++ b/third_party/WebKit/Source/core/layout/LayoutTextControlSingleLine.cpp
@@ -94,10 +94,10 @@ } } -void LayoutTextControlSingleLine::GetLayout() { +void LayoutTextControlSingleLine::UpdateLayout() { LayoutAnalyzer::Scope analyzer(*this); - LayoutBlockFlow::GetLayoutBlock(true); + LayoutBlockFlow::UpdateBlockLayout(true); LayoutBox* inner_editor_layout_object = InnerEditorElement()->GetLayoutBox(); Element* container = ContainerElement();
diff --git a/third_party/WebKit/Source/core/layout/LayoutTextControlSingleLine.h b/third_party/WebKit/Source/core/layout/LayoutTextControlSingleLine.h index 00256c1..92853b8 100644 --- a/third_party/WebKit/Source/core/layout/LayoutTextControlSingleLine.h +++ b/third_party/WebKit/Source/core/layout/LayoutTextControlSingleLine.h
@@ -54,7 +54,7 @@ } void Paint(const PaintInfo&, const LayoutPoint&) const override; - void GetLayout() override; + void UpdateLayout() override; bool NodeAtPoint(HitTestResult&, const HitTestLocation& location_in_container,
diff --git a/third_party/WebKit/Source/core/layout/LayoutVTTCue.cpp b/third_party/WebKit/Source/core/layout/LayoutVTTCue.cpp index fc525f3f..78b3af6e 100644 --- a/third_party/WebKit/Source/core/layout/LayoutVTTCue.cpp +++ b/third_party/WebKit/Source/core/layout/LayoutVTTCue.cpp
@@ -46,7 +46,7 @@ margin_ = settings->GetTextTrackMarginPercentage() / 100.0; } - void GetLayout(); + void UpdateLayout(); private: bool IsOutside(const IntRect&) const; @@ -166,7 +166,7 @@ return false; } -void SnapToLinesLayouter::GetLayout() { +void SnapToLinesLayouter::UpdateLayout() { // http://dev.w3.org/html5/webvtt/#dfn-apply-webvtt-cue-settings // Step 13, "If cue's text track cue snap-to-lines flag is set". @@ -359,8 +359,8 @@ ToLayoutBox(*controls->ContainerLayoutObject())); } -void LayoutVTTCue::GetLayout() { - LayoutBlockFlow::GetLayout(); +void LayoutVTTCue::UpdateLayout() { + LayoutBlockFlow::UpdateLayout(); DCHECK(FirstChild()); @@ -368,7 +368,7 @@ // http://dev.w3.org/html5/webvtt/#dfn-apply-webvtt-cue-settings - step 13. if (!std::isnan(snap_to_lines_position_)) - SnapToLinesLayouter(*this, ComputeControlsRect()).GetLayout(); + SnapToLinesLayouter(*this, ComputeControlsRect()).UpdateLayout(); else RepositionCueSnapToLinesNotSet(); }
diff --git a/third_party/WebKit/Source/core/layout/LayoutVTTCue.h b/third_party/WebKit/Source/core/layout/LayoutVTTCue.h index 4bc3f0412..59b71e39 100644 --- a/third_party/WebKit/Source/core/layout/LayoutVTTCue.h +++ b/third_party/WebKit/Source/core/layout/LayoutVTTCue.h
@@ -41,7 +41,7 @@ float SnapToLinesPosition() { return snap_to_lines_position_; } private: - void GetLayout() override; + void UpdateLayout() override; IntRect ComputeControlsRect() const; void RepositionCueSnapToLinesNotSet();
diff --git a/third_party/WebKit/Source/core/layout/LayoutVideo.cpp b/third_party/WebKit/Source/core/layout/LayoutVideo.cpp index 8cee1d9..86ef484 100644 --- a/third_party/WebKit/Source/core/layout/LayoutVideo.cpp +++ b/third_party/WebKit/Source/core/layout/LayoutVideo.cpp
@@ -132,9 +132,9 @@ VideoPainter(*this).PaintReplaced(paint_info, paint_offset); } -void LayoutVideo::GetLayout() { +void LayoutVideo::UpdateLayout() { UpdatePlayer(); - LayoutMedia::GetLayout(); + LayoutMedia::UpdateLayout(); } HTMLVideoElement* LayoutVideo::VideoElement() const {
diff --git a/third_party/WebKit/Source/core/layout/LayoutVideo.h b/third_party/WebKit/Source/core/layout/LayoutVideo.h index a6aca2b..625a3d6 100644 --- a/third_party/WebKit/Source/core/layout/LayoutVideo.h +++ b/third_party/WebKit/Source/core/layout/LayoutVideo.h
@@ -63,7 +63,7 @@ void PaintReplaced(const PaintInfo&, const LayoutPoint&) const override; - void GetLayout() override; + void UpdateLayout() override; LayoutUnit ComputeReplacedLogicalWidth( ShouldComputePreferred = kComputeActual) const override;
diff --git a/third_party/WebKit/Source/core/layout/LayoutView.cpp b/third_party/WebKit/Source/core/layout/LayoutView.cpp index 3920df6e..e0c741a 100644 --- a/third_party/WebKit/Source/core/layout/LayoutView.cpp +++ b/third_party/WebKit/Source/core/layout/LayoutView.cpp
@@ -219,7 +219,7 @@ void LayoutView::LayoutContent() { DCHECK(NeedsLayout()); - LayoutBlockFlow::GetLayout(); + LayoutBlockFlow::UpdateLayout(); #if DCHECK_IS_ON() CheckLayoutState(); @@ -250,7 +250,7 @@ } } -void LayoutView::GetLayout() { +void LayoutView::UpdateLayout() { if (!GetDocument().Paginated()) SetPageLogicalHeight(LayoutUnit());
diff --git a/third_party/WebKit/Source/core/layout/LayoutView.h b/third_party/WebKit/Source/core/layout/LayoutView.h index 036fbee..78ca1da1 100644 --- a/third_party/WebKit/Source/core/layout/LayoutView.h +++ b/third_party/WebKit/Source/core/layout/LayoutView.h
@@ -86,7 +86,7 @@ bool IsChildAllowed(LayoutObject*, const ComputedStyle&) const override; - void GetLayout() override; + void UpdateLayout() override; void UpdateLogicalWidth() override; void ComputeLogicalHeight(LayoutUnit logical_height, LayoutUnit logical_top,
diff --git a/third_party/WebKit/Source/core/layout/ListMarkerText.cpp b/third_party/WebKit/Source/core/layout/ListMarkerText.cpp index efa6853..046563a 100644 --- a/third_party/WebKit/Source/core/layout/ListMarkerText.cpp +++ b/third_party/WebKit/Source/core/layout/ListMarkerText.cpp
@@ -119,25 +119,6 @@ } template <typename CharacterType> -static String ToSymbolic(int number, - const CharacterType* symbols, - unsigned symbols_size) { - DCHECK_GT(number, 0); - DCHECK_GE(symbols_size, 1u); - unsigned number_shadow = number; - --number_shadow; - - // The asterisks list-style-type is the worst case; we show |numberShadow| - // asterisks. - StringBuilder letters; - letters.Append(symbols[number_shadow % symbols_size]); - unsigned num_symbols = number_shadow / symbols_size; - while (num_symbols--) - letters.Append(symbols[number_shadow % symbols_size]); - return letters.ToString(); -} - -template <typename CharacterType> static String ToAlphabetic(int number, const CharacterType* alphabet, unsigned alphabet_size) { @@ -165,12 +146,6 @@ return ToNumeric(number, alphabet, size); } -template <typename CharacterType, size_t size> -static inline String ToSymbolic(int number, - const CharacterType (&alphabet)[size]) { - return ToSymbolic(number, alphabet, size); -} - static void ToHebrewUnder1000(int number, Vector<UChar>& letters) { // FIXME: CSS3 mentions various refinements not implemented here. // FIXME: Should take a look at Mozilla's HebrewToText function (in
diff --git a/third_party/WebKit/Source/core/layout/TableLayoutAlgorithm.h b/third_party/WebKit/Source/core/layout/TableLayoutAlgorithm.h index bf565fd..9a4545a 100644 --- a/third_party/WebKit/Source/core/layout/TableLayoutAlgorithm.h +++ b/third_party/WebKit/Source/core/layout/TableLayoutAlgorithm.h
@@ -44,7 +44,7 @@ virtual void ApplyPreferredLogicalWidthQuirks( LayoutUnit& min_width, LayoutUnit& max_width) const = 0; - virtual void GetLayout() = 0; + virtual void UpdateLayout() = 0; virtual void WillChangeTableLayout() = 0; protected:
diff --git a/third_party/WebKit/Source/core/layout/TableLayoutAlgorithmAuto.cpp b/third_party/WebKit/Source/core/layout/TableLayoutAlgorithmAuto.cpp index 65e9093..655a2c6 100644 --- a/third_party/WebKit/Source/core/layout/TableLayoutAlgorithmAuto.cpp +++ b/third_party/WebKit/Source/core/layout/TableLayoutAlgorithmAuto.cpp
@@ -635,7 +635,7 @@ span_cells_[pos] = cell; } -void TableLayoutAlgorithmAuto::GetLayout() { +void TableLayoutAlgorithmAuto::UpdateLayout() { // table layout based on the values collected in the layout structure. int table_logical_width = (table_->LogicalWidth() - table_->BordersPaddingAndSpacingInRowDirection())
diff --git a/third_party/WebKit/Source/core/layout/TableLayoutAlgorithmAuto.h b/third_party/WebKit/Source/core/layout/TableLayoutAlgorithmAuto.h index a1fff18..0afab85 100644 --- a/third_party/WebKit/Source/core/layout/TableLayoutAlgorithmAuto.h +++ b/third_party/WebKit/Source/core/layout/TableLayoutAlgorithmAuto.h
@@ -49,7 +49,7 @@ } void ApplyPreferredLogicalWidthQuirks(LayoutUnit& min_width, LayoutUnit& max_width) const override; - void GetLayout() override; + void UpdateLayout() override; void WillChangeTableLayout() override {} private:
diff --git a/third_party/WebKit/Source/core/layout/TableLayoutAlgorithmFixed.cpp b/third_party/WebKit/Source/core/layout/TableLayoutAlgorithmFixed.cpp index 807fc818..b62edf7 100644 --- a/third_party/WebKit/Source/core/layout/TableLayoutAlgorithmFixed.cpp +++ b/third_party/WebKit/Source/core/layout/TableLayoutAlgorithmFixed.cpp
@@ -222,7 +222,7 @@ max_width = LayoutUnit(kTableMaxWidth); } -void TableLayoutAlgorithmFixed::GetLayout() { +void TableLayoutAlgorithmFixed::UpdateLayout() { int table_logical_width = (table_->LogicalWidth() - table_->BordersPaddingAndSpacingInRowDirection()) .ToInt();
diff --git a/third_party/WebKit/Source/core/layout/TableLayoutAlgorithmFixed.h b/third_party/WebKit/Source/core/layout/TableLayoutAlgorithmFixed.h index 411997f..d12e6e2 100644 --- a/third_party/WebKit/Source/core/layout/TableLayoutAlgorithmFixed.h +++ b/third_party/WebKit/Source/core/layout/TableLayoutAlgorithmFixed.h
@@ -37,7 +37,7 @@ LayoutUnit& max_width) override; void ApplyPreferredLogicalWidthQuirks(LayoutUnit& min_width, LayoutUnit& max_width) const override; - void GetLayout() override; + void UpdateLayout() override; void WillChangeTableLayout() override; private:
diff --git a/third_party/WebKit/Source/core/layout/api/LayoutItem.h b/third_party/WebKit/Source/core/layout/api/LayoutItem.h index 72d41b5..1befffab 100644 --- a/third_party/WebKit/Source/core/layout/api/LayoutItem.h +++ b/third_party/WebKit/Source/core/layout/api/LayoutItem.h
@@ -81,7 +81,7 @@ bool NeedsLayout() { return layout_object_->NeedsLayout(); } - void GetLayout() { layout_object_->GetLayout(); } + void UpdateLayout() { layout_object_->UpdateLayout(); } LayoutItem Container() const { return LayoutItem(layout_object_->Container());
diff --git a/third_party/WebKit/Source/core/layout/compositing/PaintLayerCompositor.cpp b/third_party/WebKit/Source/core/layout/compositing/PaintLayerCompositor.cpp index 5d639a1..7f384d9b 100644 --- a/third_party/WebKit/Source/core/layout/compositing/PaintLayerCompositor.cpp +++ b/third_party/WebKit/Source/core/layout/compositing/PaintLayerCompositor.cpp
@@ -412,6 +412,8 @@ for (ScrollableArea* scrollable_area : *scrollable_areas) layers_changed |= scrollable_area->UpdateAfterCompositingChange(); } + layers_changed |= + layout_view_.GetFrameView()->UpdateAfterCompositingChange(); } if (layers_changed) {
diff --git a/third_party/WebKit/Source/core/layout/ng/layout_ng_block_flow.cc b/third_party/WebKit/Source/core/layout/ng/layout_ng_block_flow.cc index 4c096cc..07ce05e 100644 --- a/third_party/WebKit/Source/core/layout/ng/layout_ng_block_flow.cc +++ b/third_party/WebKit/Source/core/layout/ng/layout_ng_block_flow.cc
@@ -17,7 +17,7 @@ return type == kLayoutObjectNGBlockFlow || LayoutBlockFlow::IsOfType(type); } -void LayoutNGBlockFlow::GetLayoutBlock(bool relayout_children) { +void LayoutNGBlockFlow::UpdateBlockLayout(bool relayout_children) { LayoutAnalyzer::BlockScope analyzer(*this); RefPtr<NGConstraintSpace> constraint_space =
diff --git a/third_party/WebKit/Source/core/layout/ng/layout_ng_block_flow.h b/third_party/WebKit/Source/core/layout/ng/layout_ng_block_flow.h index c6292a4b..e7718f2 100644 --- a/third_party/WebKit/Source/core/layout/ng/layout_ng_block_flow.h +++ b/third_party/WebKit/Source/core/layout/ng/layout_ng_block_flow.h
@@ -16,7 +16,7 @@ explicit LayoutNGBlockFlow(Element*); ~LayoutNGBlockFlow() override = default; - void GetLayoutBlock(bool relayout_children) override; + void UpdateBlockLayout(bool relayout_children) override; NGBlockNode* BoxForTesting() const { return box_.Get(); } private:
diff --git a/third_party/WebKit/Source/core/layout/ng/ng_block_node.cc b/third_party/WebKit/Source/core/layout/ng/ng_block_node.cc index ae698eb..37475de60 100644 --- a/third_party/WebKit/Source/core/layout/ng/ng_block_node.cc +++ b/third_party/WebKit/Source/core/layout/ng/ng_block_node.cc
@@ -350,7 +350,7 @@ } if (layout_box_->IsLayoutNGBlockFlow() && layout_box_->NeedsLayout()) { - ToLayoutNGBlockFlow(layout_box_)->LayoutBlockFlow::GetLayoutBlock(true); + ToLayoutNGBlockFlow(layout_box_)->LayoutBlockFlow::UpdateBlockLayout(true); } else { layout_box_->ForceLayout(); }
diff --git a/third_party/WebKit/Source/core/layout/svg/LayoutSVGContainer.cpp b/third_party/WebKit/Source/core/layout/svg/LayoutSVGContainer.cpp index 3f2b718..7c9e714 100644 --- a/third_party/WebKit/Source/core/layout/svg/LayoutSVGContainer.cpp +++ b/third_party/WebKit/Source/core/layout/svg/LayoutSVGContainer.cpp
@@ -42,7 +42,7 @@ LayoutSVGContainer::~LayoutSVGContainer() {} -void LayoutSVGContainer::GetLayout() { +void LayoutSVGContainer::UpdateLayout() { DCHECK(NeedsLayout()); LayoutAnalyzer::Scope analyzer(*this);
diff --git a/third_party/WebKit/Source/core/layout/svg/LayoutSVGContainer.h b/third_party/WebKit/Source/core/layout/svg/LayoutSVGContainer.h index 665c46f..7c59c551 100644 --- a/third_party/WebKit/Source/core/layout/svg/LayoutSVGContainer.h +++ b/third_party/WebKit/Source/core/layout/svg/LayoutSVGContainer.h
@@ -74,7 +74,7 @@ return type == kLayoutObjectSVGContainer || LayoutSVGModelObject::IsOfType(type); } - void GetLayout() override; + void UpdateLayout() override; void AddChild(LayoutObject* child, LayoutObject* before_child = nullptr) final;
diff --git a/third_party/WebKit/Source/core/layout/svg/LayoutSVGForeignObject.cpp b/third_party/WebKit/Source/core/layout/svg/LayoutSVGForeignObject.cpp index 931ad5e58..0595e460 100644 --- a/third_party/WebKit/Source/core/layout/svg/LayoutSVGForeignObject.cpp +++ b/third_party/WebKit/Source/core/layout/svg/LayoutSVGForeignObject.cpp
@@ -86,7 +86,7 @@ computed_values.position_ = logical_top; } -void LayoutSVGForeignObject::GetLayout() { +void LayoutSVGForeignObject::UpdateLayout() { DCHECK(NeedsLayout()); SVGForeignObjectElement* foreign = toSVGForeignObjectElement(GetNode()); @@ -110,7 +110,7 @@ SetY(ElementY()); bool layout_changed = EverHadLayout() && SelfNeedsLayout(); - LayoutBlock::GetLayout(); + LayoutBlock::UpdateLayout(); DCHECK(!NeedsLayout()); // If our bounds changed, notify the parents.
diff --git a/third_party/WebKit/Source/core/layout/svg/LayoutSVGForeignObject.h b/third_party/WebKit/Source/core/layout/svg/LayoutSVGForeignObject.h index 0586d6b..799554c 100644 --- a/third_party/WebKit/Source/core/layout/svg/LayoutSVGForeignObject.h +++ b/third_party/WebKit/Source/core/layout/svg/LayoutSVGForeignObject.h
@@ -50,7 +50,7 @@ void Paint(const PaintInfo&, const LayoutPoint&) const override; - void GetLayout() override; + void UpdateLayout() override; FloatRect ObjectBoundingBox() const override { return FloatRect(FrameRect());
diff --git a/third_party/WebKit/Source/core/layout/svg/LayoutSVGGradientStop.cpp b/third_party/WebKit/Source/core/layout/svg/LayoutSVGGradientStop.cpp index 28404d9..f3977321 100644 --- a/third_party/WebKit/Source/core/layout/svg/LayoutSVGGradientStop.cpp +++ b/third_party/WebKit/Source/core/layout/svg/LayoutSVGGradientStop.cpp
@@ -52,7 +52,7 @@ container->RemoveAllClientsFromCache(); } -void LayoutSVGGradientStop::GetLayout() { +void LayoutSVGGradientStop::UpdateLayout() { ClearNeedsLayout(); }
diff --git a/third_party/WebKit/Source/core/layout/svg/LayoutSVGGradientStop.h b/third_party/WebKit/Source/core/layout/svg/LayoutSVGGradientStop.h index b1e7adf..0ab155b 100644 --- a/third_party/WebKit/Source/core/layout/svg/LayoutSVGGradientStop.h +++ b/third_party/WebKit/Source/core/layout/svg/LayoutSVGGradientStop.h
@@ -40,7 +40,7 @@ LayoutObject::IsOfType(type); } - void GetLayout() override; + void UpdateLayout() override; // These overrides are needed to prevent NOTREACHED on <svg><stop /></svg> in // LayoutObject's default implementations.
diff --git a/third_party/WebKit/Source/core/layout/svg/LayoutSVGHiddenContainer.cpp b/third_party/WebKit/Source/core/layout/svg/LayoutSVGHiddenContainer.cpp index dc75631..c7cb982 100644 --- a/third_party/WebKit/Source/core/layout/svg/LayoutSVGHiddenContainer.cpp +++ b/third_party/WebKit/Source/core/layout/svg/LayoutSVGHiddenContainer.cpp
@@ -27,7 +27,7 @@ LayoutSVGHiddenContainer::LayoutSVGHiddenContainer(SVGElement* element) : LayoutSVGContainer(element) {} -void LayoutSVGHiddenContainer::GetLayout() { +void LayoutSVGHiddenContainer::UpdateLayout() { DCHECK(NeedsLayout()); LayoutAnalyzer::Scope analyzer(*this);
diff --git a/third_party/WebKit/Source/core/layout/svg/LayoutSVGHiddenContainer.h b/third_party/WebKit/Source/core/layout/svg/LayoutSVGHiddenContainer.h index 1ed51ebd..483121b 100644 --- a/third_party/WebKit/Source/core/layout/svg/LayoutSVGHiddenContainer.h +++ b/third_party/WebKit/Source/core/layout/svg/LayoutSVGHiddenContainer.h
@@ -35,7 +35,7 @@ const char* GetName() const override { return "LayoutSVGHiddenContainer"; } protected: - void GetLayout() override; + void UpdateLayout() override; bool IsOfType(LayoutObjectType type) const override { return type == kLayoutObjectSVGHiddenContainer ||
diff --git a/third_party/WebKit/Source/core/layout/svg/LayoutSVGImage.cpp b/third_party/WebKit/Source/core/layout/svg/LayoutSVGImage.cpp index 10b1e45..fc5c911b 100644 --- a/third_party/WebKit/Source/core/layout/svg/LayoutSVGImage.cpp +++ b/third_party/WebKit/Source/core/layout/svg/LayoutSVGImage.cpp
@@ -116,7 +116,7 @@ return old_object_bounding_box.size() != object_bounding_box_.size(); } -void LayoutSVGImage::GetLayout() { +void LayoutSVGImage::UpdateLayout() { DCHECK(NeedsLayout()); LayoutAnalyzer::Scope analyzer(*this);
diff --git a/third_party/WebKit/Source/core/layout/svg/LayoutSVGImage.h b/third_party/WebKit/Source/core/layout/svg/LayoutSVGImage.h index 558100b2..d9c13a8 100644 --- a/third_party/WebKit/Source/core/layout/svg/LayoutSVGImage.h +++ b/third_party/WebKit/Source/core/layout/svg/LayoutSVGImage.h
@@ -64,7 +64,7 @@ void ImageChanged(WrappedImagePtr, const IntRect* = nullptr) override; - void GetLayout() override; + void UpdateLayout() override; void Paint(const PaintInfo&, const LayoutPoint&) const override; bool UpdateBoundingBox();
diff --git a/third_party/WebKit/Source/core/layout/svg/LayoutSVGResourceContainer.cpp b/third_party/WebKit/Source/core/layout/svg/LayoutSVGResourceContainer.cpp index 32e8569e..dd76aca7 100644 --- a/third_party/WebKit/Source/core/layout/svg/LayoutSVGResourceContainer.cpp +++ b/third_party/WebKit/Source/core/layout/svg/LayoutSVGResourceContainer.cpp
@@ -42,7 +42,7 @@ LayoutSVGResourceContainer::~LayoutSVGResourceContainer() {} -void LayoutSVGResourceContainer::GetLayout() { +void LayoutSVGResourceContainer::UpdateLayout() { // FIXME: Investigate a way to detect and break resource layout dependency // cycles early. Then we can remove this method altogether, and fall back onto // LayoutSVGHiddenContainer::layout(). @@ -52,7 +52,7 @@ AutoReset<bool> in_layout_change(&is_in_layout_, true); - LayoutSVGHiddenContainer::GetLayout(); + LayoutSVGHiddenContainer::UpdateLayout(); ClearInvalidationMask(); }
diff --git a/third_party/WebKit/Source/core/layout/svg/LayoutSVGResourceContainer.h b/third_party/WebKit/Source/core/layout/svg/LayoutSVGResourceContainer.h index fb4acab3..617914902 100644 --- a/third_party/WebKit/Source/core/layout/svg/LayoutSVGResourceContainer.h +++ b/third_party/WebKit/Source/core/layout/svg/LayoutSVGResourceContainer.h
@@ -45,7 +45,7 @@ virtual void RemoveClientFromCache(LayoutObject*, bool mark_for_invalidation = true) = 0; - void GetLayout() override; + void UpdateLayout() override; void StyleDidChange(StyleDifference, const ComputedStyle* old_style) final; bool IsOfType(LayoutObjectType type) const override { return type == kLayoutObjectSVGResourceContainer ||
diff --git a/third_party/WebKit/Source/core/layout/svg/LayoutSVGResourceMarker.cpp b/third_party/WebKit/Source/core/layout/svg/LayoutSVGResourceMarker.cpp index 0801b2f..415acf9 100644 --- a/third_party/WebKit/Source/core/layout/svg/LayoutSVGResourceMarker.cpp +++ b/third_party/WebKit/Source/core/layout/svg/LayoutSVGResourceMarker.cpp
@@ -31,7 +31,7 @@ LayoutSVGResourceMarker::~LayoutSVGResourceMarker() {} -void LayoutSVGResourceMarker::GetLayout() { +void LayoutSVGResourceMarker::UpdateLayout() { DCHECK(NeedsLayout()); if (is_in_layout_) return; @@ -41,7 +41,7 @@ // LayoutSVGHiddenContainer overwrites layout(). We need the // layouting of LayoutSVGContainer for calculating local // transformations and paint invalidation. - LayoutSVGContainer::GetLayout(); + LayoutSVGContainer::UpdateLayout(); ClearInvalidationMask(); }
diff --git a/third_party/WebKit/Source/core/layout/svg/LayoutSVGResourceMarker.h b/third_party/WebKit/Source/core/layout/svg/LayoutSVGResourceMarker.h index 27fc51b..1a39b7a 100644 --- a/third_party/WebKit/Source/core/layout/svg/LayoutSVGResourceMarker.h +++ b/third_party/WebKit/Source/core/layout/svg/LayoutSVGResourceMarker.h
@@ -67,7 +67,7 @@ LayoutSVGResourceType ResourceType() const override { return kResourceType; } private: - void GetLayout() override; + void UpdateLayout() override; SVGTransformChange CalculateLocalTransform() final; AffineTransform local_to_parent_transform_;
diff --git a/third_party/WebKit/Source/core/layout/svg/LayoutSVGRoot.cpp b/third_party/WebKit/Source/core/layout/svg/LayoutSVGRoot.cpp index 43dd7ab..1ba7b93 100644 --- a/third_party/WebKit/Source/core/layout/svg/LayoutSVGRoot.cpp +++ b/third_party/WebKit/Source/core/layout/svg/LayoutSVGRoot.cpp
@@ -137,7 +137,7 @@ return LayoutReplaced::ComputeReplacedLogicalHeight(estimated_used_width); } -void LayoutSVGRoot::GetLayout() { +void LayoutSVGRoot::UpdateLayout() { DCHECK(NeedsLayout()); LayoutAnalyzer::Scope analyzer(*this);
diff --git a/third_party/WebKit/Source/core/layout/svg/LayoutSVGRoot.h b/third_party/WebKit/Source/core/layout/svg/LayoutSVGRoot.h index 7016ecc..60c759e 100644 --- a/third_party/WebKit/Source/core/layout/svg/LayoutSVGRoot.h +++ b/third_party/WebKit/Source/core/layout/svg/LayoutSVGRoot.h
@@ -115,7 +115,7 @@ ShouldComputePreferred = kComputeActual) const override; LayoutUnit ComputeReplacedLogicalHeight( LayoutUnit estimated_used_width = LayoutUnit()) const override; - void GetLayout() override; + void UpdateLayout() override; void PaintReplaced(const PaintInfo&, const LayoutPoint&) const override; void WillBeDestroyed() override;
diff --git a/third_party/WebKit/Source/core/layout/svg/LayoutSVGShape.cpp b/third_party/WebKit/Source/core/layout/svg/LayoutSVGShape.cpp index ec32bb5..5e8f695a 100644 --- a/third_party/WebKit/Source/core/layout/svg/LayoutSVGShape.cpp +++ b/third_party/WebKit/Source/core/layout/svg/LayoutSVGShape.cpp
@@ -171,7 +171,7 @@ } } -void LayoutSVGShape::GetLayout() { +void LayoutSVGShape::UpdateLayout() { LayoutAnalyzer::Scope analyzer(*this); // Invalidate all resources of this client if our layout changed.
diff --git a/third_party/WebKit/Source/core/layout/svg/LayoutSVGShape.h b/third_party/WebKit/Source/core/layout/svg/LayoutSVGShape.h index a56b20c..1cf9decd 100644 --- a/third_party/WebKit/Source/core/layout/svg/LayoutSVGShape.h +++ b/third_party/WebKit/Source/core/layout/svg/LayoutSVGShape.h
@@ -136,7 +136,7 @@ return type == kLayoutObjectSVGShape || LayoutSVGModelObject::IsOfType(type); } - void GetLayout() final; + void UpdateLayout() final; void Paint(const PaintInfo&, const LayoutPoint&) const final; void AddOutlineRects(Vector<LayoutRect>&, const LayoutPoint& additional_offset,
diff --git a/third_party/WebKit/Source/core/layout/svg/LayoutSVGText.cpp b/third_party/WebKit/Source/core/layout/svg/LayoutSVGText.cpp index 740039e..51bc388 100644 --- a/third_party/WebKit/Source/core/layout/svg/LayoutSVGText.cpp +++ b/third_party/WebKit/Source/core/layout/svg/LayoutSVGText.cpp
@@ -173,7 +173,7 @@ #endif } -void LayoutSVGText::GetLayout() { +void LayoutSVGText::UpdateLayout() { DCHECK(NeedsLayout()); // This flag is set and reset as needed only within this function. DCHECK(!needs_reordering_);
diff --git a/third_party/WebKit/Source/core/layout/svg/LayoutSVGText.h b/third_party/WebKit/Source/core/layout/svg/LayoutSVGText.h index 6ea2008f..390c000d 100644 --- a/third_party/WebKit/Source/core/layout/svg/LayoutSVGText.h +++ b/third_party/WebKit/Source/core/layout/svg/LayoutSVGText.h
@@ -75,7 +75,7 @@ HitTestAction) override; PositionWithAffinity PositionForPoint(const LayoutPoint&) override; - void GetLayout() override; + void UpdateLayout() override; void AbsoluteQuads(Vector<FloatQuad>&, MapCoordinatesFlags mode = 0) const override;
diff --git a/third_party/WebKit/Source/core/layout/svg/LayoutSVGViewportContainer.cpp b/third_party/WebKit/Source/core/layout/svg/LayoutSVGViewportContainer.cpp index 0e06b0a2..419cf2f2 100644 --- a/third_party/WebKit/Source/core/layout/svg/LayoutSVGViewportContainer.cpp +++ b/third_party/WebKit/Source/core/layout/svg/LayoutSVGViewportContainer.cpp
@@ -32,7 +32,7 @@ is_layout_size_changed_(false), needs_transform_update_(true) {} -void LayoutSVGViewportContainer::GetLayout() { +void LayoutSVGViewportContainer::UpdateLayout() { DCHECK(NeedsLayout()); DCHECK(isSVGSVGElement(GetElement())); @@ -53,7 +53,7 @@ } } - LayoutSVGContainer::GetLayout(); + LayoutSVGContainer::UpdateLayout(); } void LayoutSVGViewportContainer::SetNeedsTransformUpdate() {
diff --git a/third_party/WebKit/Source/core/layout/svg/LayoutSVGViewportContainer.h b/third_party/WebKit/Source/core/layout/svg/LayoutSVGViewportContainer.h index c2a1628..ccfec56 100644 --- a/third_party/WebKit/Source/core/layout/svg/LayoutSVGViewportContainer.h +++ b/third_party/WebKit/Source/core/layout/svg/LayoutSVGViewportContainer.h
@@ -48,7 +48,7 @@ LayoutSVGContainer::IsOfType(type); } - void GetLayout() override; + void UpdateLayout() override; AffineTransform LocalToSVGParentTransform() const override { return local_to_parent_transform_;
diff --git a/third_party/WebKit/Source/core/mojo/MojoHandle.cpp b/third_party/WebKit/Source/core/mojo/MojoHandle.cpp index aed10b7..7cab227 100644 --- a/third_party/WebKit/Source/core/mojo/MojoHandle.cpp +++ b/third_party/WebKit/Source/core/mojo/MojoHandle.cpp
@@ -62,7 +62,7 @@ bytes = array->Data(); num_bytes = array->ByteLength(); } else { - DOMArrayBufferView* view = buffer.getAsArrayBufferView(); + DOMArrayBufferView* view = buffer.getAsArrayBufferView().View(); bytes = view->BaseAddress(); num_bytes = view->byteLength(); } @@ -118,7 +118,7 @@ elements = array->Data(); num_bytes = array->ByteLength(); } else { - DOMArrayBufferView* view = buffer.getAsArrayBufferView(); + DOMArrayBufferView* view = buffer.getAsArrayBufferView().View(); elements = view->BaseAddress(); num_bytes = view->byteLength(); } @@ -166,7 +166,7 @@ elements = array->Data(); num_bytes = array->ByteLength(); } else { - DOMArrayBufferView* view = buffer.getAsArrayBufferView(); + DOMArrayBufferView* view = buffer.getAsArrayBufferView().View(); elements = view->BaseAddress(); num_bytes = view->byteLength(); }
diff --git a/third_party/WebKit/Source/core/page/FocusController.cpp b/third_party/WebKit/Source/core/page/FocusController.cpp index fb151dad..88bc321b 100644 --- a/third_party/WebKit/Source/core/page/FocusController.cpp +++ b/third_party/WebKit/Source/core/page/FocusController.cpp
@@ -370,7 +370,8 @@ if (!focused && document->FocusedElement()) { Element* focused_element = document->FocusedElement(); - focused_element->SetFocused(false); + // Use focus_type kWebFocusTypePage, same as used in DispatchBlurEvent. + focused_element->SetFocused(false, kWebFocusTypePage); DispatchBlurEvent(*document, *focused_element); } @@ -379,7 +380,8 @@ Event::Create(focused ? EventTypeNames::focus : EventTypeNames::blur)); if (focused && document->FocusedElement()) { Element* focused_element(document->FocusedElement()); - focused_element->SetFocused(true); + // Use focus_type kWebFocusTypePage, same as used in DispatchFocusEvent. + focused_element->SetFocused(true, kWebFocusTypePage); DispatchFocusEvent(*document, *focused_element); } }
diff --git a/third_party/WebKit/Source/core/paint/PaintLayerScrollableArea.cpp b/third_party/WebKit/Source/core/paint/PaintLayerScrollableArea.cpp index 9d2e324..d56ec3f 100644 --- a/third_party/WebKit/Source/core/paint/PaintLayerScrollableArea.cpp +++ b/third_party/WebKit/Source/core/paint/PaintLayerScrollableArea.cpp
@@ -804,9 +804,9 @@ LayoutBlock& block = ToLayoutBlock(Box()); block.ScrollbarsChanged(horizontal_scrollbar_should_change, vertical_scrollbar_should_change); - block.GetLayoutBlock(true); + block.UpdateBlockLayout(true); } else { - Box().GetLayout(); + Box().UpdateLayout(); } in_overflow_relayout_ = false; scrollbar_manager_.DestroyDetachedScrollbars();
diff --git a/third_party/WebKit/Source/core/paint/RarePaintData.cpp b/third_party/WebKit/Source/core/paint/RarePaintData.cpp index d3591ae..0a2ec1f 100644 --- a/third_party/WebKit/Source/core/paint/RarePaintData.cpp +++ b/third_party/WebKit/Source/core/paint/RarePaintData.cpp
@@ -5,6 +5,7 @@ #include "core/paint/RarePaintData.h" #include "core/paint/ObjectPaintProperties.h" +#include "core/paint/PaintLayer.h" namespace blink { @@ -12,6 +13,10 @@ RarePaintData::~RarePaintData() {} +void RarePaintData::SetLayer(std::unique_ptr<PaintLayer> layer) { + layer_ = std::move(layer); +}; + ObjectPaintProperties& RarePaintData::EnsurePaintProperties() { if (!paint_properties_) paint_properties_ = ObjectPaintProperties::Create();
diff --git a/third_party/WebKit/Source/core/paint/RarePaintData.h b/third_party/WebKit/Source/core/paint/RarePaintData.h index 7584ae4..b04b5f5 100644 --- a/third_party/WebKit/Source/core/paint/RarePaintData.h +++ b/third_party/WebKit/Source/core/paint/RarePaintData.h
@@ -13,10 +13,10 @@ class PropertyTreeState; class ObjectPaintProperties; +class PaintLayer; // This is for paint-related data on LayoutObject that is not needed on all // objects. -// TODO(pdr): Store LayoutBoxModelObject's m_paintLayer in this structure. class CORE_EXPORT RarePaintData { WTF_MAKE_NONCOPYABLE(RarePaintData); USING_FAST_MALLOC(RarePaintData); @@ -25,6 +25,9 @@ RarePaintData(); ~RarePaintData(); + PaintLayer* Layer() { return layer_.get(); } + void SetLayer(std::unique_ptr<PaintLayer>); + ObjectPaintProperties* PaintProperties() const { return paint_properties_.get(); } @@ -44,6 +47,10 @@ PropertyTreeState ContentsProperties() const; private: + // The PaintLayer associated with this LayoutBoxModelObject. This can be null + // depending on the return value of LayoutBoxModelObject::layerTypeRequired(). + std::unique_ptr<PaintLayer> layer_; + // Holds references to the paint property nodes created by this object. std::unique_ptr<ObjectPaintProperties> paint_properties_;
diff --git a/third_party/WebKit/Source/core/xmlhttprequest/XMLHttpRequest.cpp b/third_party/WebKit/Source/core/xmlhttprequest/XMLHttpRequest.cpp index 91265c49..9864143 100644 --- a/third_party/WebKit/Source/core/xmlhttprequest/XMLHttpRequest.cpp +++ b/third_party/WebKit/Source/core/xmlhttprequest/XMLHttpRequest.cpp
@@ -714,7 +714,7 @@ } if (body.isArrayBufferView()) { - send(body.getAsArrayBufferView(), exception_state); + send(body.getAsArrayBufferView().View(), exception_state); return; }
diff --git a/third_party/WebKit/Source/devtools/front_end/bindings/CSSWorkspaceBinding.js b/third_party/WebKit/Source/devtools/front_end/bindings/CSSWorkspaceBinding.js index fe8044c..c0bef9b 100644 --- a/third_party/WebKit/Source/devtools/front_end/bindings/CSSWorkspaceBinding.js +++ b/third_party/WebKit/Source/devtools/front_end/bindings/CSSWorkspaceBinding.js
@@ -15,6 +15,8 @@ /** @type {!Map.<!SDK.CSSModel, !Bindings.CSSWorkspaceBinding.ModelInfo>} */ this._modelToInfo = new Map(); + /** @type {!Array<!Bindings.CSSWorkspaceBinding.SourceMapping>} */ + this._sourceMappings = []; targetManager.observeModels(SDK.CSSModel, this); } @@ -83,8 +85,33 @@ rawLocationToUILocation(rawLocation) { if (!rawLocation) return null; + for (var i = this._sourceMappings.length - 1; i >= 0; --i) { + var uiLocation = this._sourceMappings[i].rawLocationToUILocation(rawLocation); + if (uiLocation) + return uiLocation; + } return this._modelToInfo.get(rawLocation.cssModel())._rawLocationToUILocation(rawLocation); } + + /** + * @param {!Bindings.CSSWorkspaceBinding.SourceMapping} sourceMapping + */ + addSourceMapping(sourceMapping) { + this._sourceMappings.push(sourceMapping); + } +}; + +/** + * @interface + */ +Bindings.CSSWorkspaceBinding.SourceMapping = function() {}; + +Bindings.CSSWorkspaceBinding.SourceMapping.prototype = { + /** + * @param {!SDK.CSSLocation} rawLocation + * @return {?Workspace.UILocation} + */ + rawLocationToUILocation(rawLocation) {}, }; Bindings.CSSWorkspaceBinding.ModelInfo = class { @@ -220,7 +247,7 @@ if (!this._header) return null; var rawLocation = new SDK.CSSLocation(this._header, this._lineNumber, this._columnNumber); - return this._info._rawLocationToUILocation(rawLocation); + return Bindings.cssWorkspaceBinding.rawLocationToUILocation(rawLocation); } /**
diff --git a/third_party/WebKit/Source/devtools/front_end/bindings/NetworkProject.js b/third_party/WebKit/Source/devtools/front_end/bindings/NetworkProject.js index 547cbaf..36f4242 100644 --- a/third_party/WebKit/Source/devtools/front_end/bindings/NetworkProject.js +++ b/third_party/WebKit/Source/devtools/front_end/bindings/NetworkProject.js
@@ -476,6 +476,14 @@ return workspace.uiSourceCode( Bindings.NetworkProject.projectId(header.cssModel().target(), header.frameId, false), url); } + + /** + * @param {!Workspace.UISourceCode} uiSourceCode + * @return {?SDK.CSSStyleSheetHeader} + */ + static styleHeaderForUISourceCode(uiSourceCode) { + return uiSourceCode[Bindings.NetworkProject._styleSheetSymbol]; + } }; Bindings.NetworkProject._networkProjectSymbol = Symbol('networkProject');
diff --git a/third_party/WebKit/Source/devtools/front_end/bindings/SASSSourceMapping.js b/third_party/WebKit/Source/devtools/front_end/bindings/SASSSourceMapping.js index 8bc0843e..a4917740 100644 --- a/third_party/WebKit/Source/devtools/front_end/bindings/SASSSourceMapping.js +++ b/third_party/WebKit/Source/devtools/front_end/bindings/SASSSourceMapping.js
@@ -29,7 +29,7 @@ */ /** - * @unrestricted + * @implements {Bindings.CSSWorkspaceBinding.SourceMapping} */ Bindings.SASSSourceMapping = class { /** @@ -134,6 +134,7 @@ } /** + * @override * @param {!SDK.CSSLocation} rawLocation * @return {?Workspace.UILocation} */
diff --git a/third_party/WebKit/Source/devtools/front_end/bindings/StylesSourceMapping.js b/third_party/WebKit/Source/devtools/front_end/bindings/StylesSourceMapping.js index e3c34c6..f13a452 100644 --- a/third_party/WebKit/Source/devtools/front_end/bindings/StylesSourceMapping.js +++ b/third_party/WebKit/Source/devtools/front_end/bindings/StylesSourceMapping.js
@@ -29,6 +29,7 @@ */ /** + * @implements {Bindings.CSSWorkspaceBinding.SourceMapping} * @unrestricted */ Bindings.StylesSourceMapping = class { @@ -60,6 +61,7 @@ } /** + * @override * @param {!SDK.CSSLocation} rawLocation * @return {?Workspace.UILocation} */
diff --git a/third_party/WebKit/Source/devtools/front_end/coverage/CoverageListView.js b/third_party/WebKit/Source/devtools/front_end/coverage/CoverageListView.js index 6e6648fd..53aa60b4 100644 --- a/third_party/WebKit/Source/devtools/front_end/coverage/CoverageListView.js +++ b/third_party/WebKit/Source/devtools/front_end/coverage/CoverageListView.js
@@ -71,14 +71,20 @@ /** * @param {?DataGrid.DataGridNode} node */ - _revealSourceForNode(node) { + async _revealSourceForNode(node) { if (!node) return; var coverageInfo = /** @type {!Coverage.CoverageListView.GridNode} */ (node)._coverageInfo; var sourceCode = Workspace.workspace.uiSourceCodeForURL(coverageInfo.url()); if (!sourceCode) return; - Common.Revealer.reveal(sourceCode); + var content = await sourceCode.requestContent(); + if (TextUtils.isMinified(content)) { + var formatData = await Sources.sourceFormatter.format(sourceCode); + Common.Revealer.reveal(formatData.formattedSourceCode); + } else { + Common.Revealer.reveal(sourceCode); + } } _sortingChanged() {
diff --git a/third_party/WebKit/Source/devtools/front_end/coverage/module.json b/third_party/WebKit/Source/devtools/front_end/coverage/module.json index 9e0ad17..1f0c946 100644 --- a/third_party/WebKit/Source/devtools/front_end/coverage/module.json +++ b/third_party/WebKit/Source/devtools/front_end/coverage/module.json
@@ -46,6 +46,7 @@ "sdk", "ui", "source_frame", + "sources", "data_grid" ], "scripts": [
diff --git a/third_party/WebKit/Source/devtools/front_end/network/BlockedURLsPane.js b/third_party/WebKit/Source/devtools/front_end/network/BlockedURLsPane.js index 70daa6ec..35c0f73 100644 --- a/third_party/WebKit/Source/devtools/front_end/network/BlockedURLsPane.js +++ b/third_party/WebKit/Source/devtools/front_end/network/BlockedURLsPane.js
@@ -175,7 +175,7 @@ */ _update() { var enabled = this._manager.blockingEnabled(); - this._list.element.classList.toggle('blocking-disabled', !enabled); + this._list.element.classList.toggle('blocking-disabled', !enabled && !!this._manager.blockedPatterns().length); this._enabledCheckbox.setChecked(enabled); this._list.clear(); for (var pattern of this._manager.blockedPatterns())
diff --git a/third_party/WebKit/Source/devtools/front_end/resources/ApplicationPanelSidebar.js b/third_party/WebKit/Source/devtools/front_end/resources/ApplicationPanelSidebar.js index c68aa70..d7a2d226 100644 --- a/third_party/WebKit/Source/devtools/front_end/resources/ApplicationPanelSidebar.js +++ b/third_party/WebKit/Source/devtools/front_end/resources/ApplicationPanelSidebar.js
@@ -233,21 +233,6 @@ this.databasesListTreeElement.setExpandable(false); } - _resetDOMStorage() { - this._domStorageTreeElements.clear(); - this.localStorageListTreeElement.removeChildren(); - this.sessionStorageListTreeElement.removeChildren(); - } - - _resetCookies() { - this.cookieListTreeElement.removeChildren(); - } - - _resetCacheStorage() { - this.cacheStorageListTreeElement.removeChildren(); - this.cacheStorageListTreeElement.setExpandable(false); - } - _resetAppCache() { for (var frameId of Object.keys(this._applicationCacheFrameElements)) this._applicationCacheFrameManifestRemoved({data: frameId}); @@ -257,15 +242,7 @@ _reset() { this._domains = {}; this._resetWebSQL(); - this._resetDOMStorage(); - this._resetCookies(); - this._resetCacheStorage(); - // No need to this._resetAppCache. - - this._panel.resetView(); - - if (this._sidebarTree.selectedTreeElement) - this._sidebarTree.selectedTreeElement.deselect(); + this.cookieListTreeElement.removeChildren(); } _frameNavigated(event) { @@ -859,6 +836,7 @@ swCacheTreeElement.clear(); this.removeChild(swCacheTreeElement); this._swCacheTreeElements.remove(swCacheTreeElement); + this.setExpandable(this.childCount() > 0); } /** @@ -1130,6 +1108,7 @@ idbDatabaseTreeElement.clear(); this.removeChild(idbDatabaseTreeElement); this._idbDatabaseTreeElements.remove(idbDatabaseTreeElement); + this.setExpandable(this.childCount() > 0); } /**
diff --git a/third_party/WebKit/Source/devtools/front_end/sources/JavaScriptSourceFrame.js b/third_party/WebKit/Source/devtools/front_end/sources/JavaScriptSourceFrame.js index 2799736..1d4627f2 100644 --- a/third_party/WebKit/Source/devtools/front_end/sources/JavaScriptSourceFrame.js +++ b/third_party/WebKit/Source/devtools/front_end/sources/JavaScriptSourceFrame.js
@@ -1207,17 +1207,7 @@ if (this._prettyPrintInfobar) return; - var minified = false; - for (var i = 0; i < 10 && i < this.textEditor.linesCount; ++i) { - var line = this.textEditor.line(i); - if (line.startsWith('//#')) // mind source map. - continue; - if (line.length > 500) { - minified = true; - break; - } - } - if (!minified) + if (!TextUtils.isMinified(/** @type {string} */ (this._debuggerSourceCode.content()))) return; this._prettyPrintInfobar = UI.Infobar.create(
diff --git a/third_party/WebKit/Source/devtools/front_end/sources/SourceFormatter.js b/third_party/WebKit/Source/devtools/front_end/sources/SourceFormatter.js index 8c8f8109..4b60589 100644 --- a/third_party/WebKit/Source/devtools/front_end/sources/SourceFormatter.js +++ b/third_party/WebKit/Source/devtools/front_end/sources/SourceFormatter.js
@@ -2,63 +2,6 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -/** - * @implements {Bindings.DebuggerSourceMapping} - */ -Sources.FormatterScriptMapping = class { - /** - * @override - * @param {!SDK.DebuggerModel.Location} rawLocation - * @return {?Workspace.UILocation} - */ - rawLocationToUILocation(rawLocation) { - var script = rawLocation.script(); - var formatData = script && Sources.SourceFormatData._for(script); - if (!formatData) - return null; - var lineNumber = rawLocation.lineNumber; - var columnNumber = rawLocation.columnNumber || 0; - var formattedLocation = formatData.mapping.originalToFormatted(lineNumber, columnNumber); - return formatData.formattedSourceCode.uiLocation(formattedLocation[0], formattedLocation[1]); - } - - /** - * @override - * @param {!Workspace.UISourceCode} uiSourceCode - * @param {number} lineNumber - * @param {number} columnNumber - * @return {?SDK.DebuggerModel.Location} - */ - uiLocationToRawLocation(uiSourceCode, lineNumber, columnNumber) { - var formatData = Sources.SourceFormatData._for(uiSourceCode); - if (!formatData) - return null; - var originalLocation = formatData.mapping.formattedToOriginal(lineNumber, columnNumber); - var scripts = Sources.SourceFormatter._scriptsForUISourceCode(formatData.originalSourceCode); - if (!scripts.length) - return null; - return scripts[0].debuggerModel.createRawLocation(scripts[0], originalLocation[0], originalLocation[1]); - } - - /** - * @override - * @return {boolean} - */ - isIdentity() { - return false; - } - - /** - * @override - * @param {!Workspace.UISourceCode} uiSourceCode - * @param {number} lineNumber - * @return {boolean} - */ - uiLineHasMapping(uiSourceCode, lineNumber) { - return true; - } -}; - Sources.SourceFormatData = class { /** * @param {!Workspace.UISourceCode} originalSourceCode @@ -95,7 +38,8 @@ /** @type {!Map<string, !Workspace.UISourceCode>} */ this._formattedPaths = new Map(); - this._scriptMapping = new Sources.FormatterScriptMapping(); + this._scriptMapping = new Sources.SourceFormatter.ScriptMapping(); + this._styleMapping = new Sources.SourceFormatter.StyleMapping(); Workspace.workspace.addEventListener( Workspace.Workspace.Events.UISourceCodeRemoved, this._onUISourceCodeRemoved, this); } @@ -120,13 +64,8 @@ return null; delete formattedUISourceCode[Sources.SourceFormatData._formatDataSymbol]; - var scripts = Sources.SourceFormatter._scriptsForUISourceCode(formatData.originalSourceCode); - for (var script of scripts) { - delete script[Sources.SourceFormatData._formatDataSymbol]; - Bindings.debuggerWorkspaceBinding.popSourceMapping(script); - } - if (scripts[0]) - Bindings.debuggerWorkspaceBinding.setSourceMapping(scripts[0].debuggerModel, formattedUISourceCode, null); + this._scriptMapping._setSourceMappingEnabled(formatData, false); + this._styleMapping._setSourceMappingEnabled(formatData, false); this._project.removeFile(formattedUISourceCode.url()); this._formattedPaths.remove(formatData.originalPath()); return formatData.originalSourceCode; @@ -134,28 +73,6 @@ /** * @param {!Workspace.UISourceCode} uiSourceCode - * @return {!Array<!SDK.Script>} - */ - static _scriptsForUISourceCode(uiSourceCode) { - if (uiSourceCode.contentType() === Common.resourceTypes.Document) { - var target = Bindings.NetworkProject.targetForUISourceCode(uiSourceCode); - var debuggerModel = target && target.model(SDK.DebuggerModel); - if (debuggerModel) { - var scripts = debuggerModel.scriptsForSourceURL(uiSourceCode.url()) - .filter(script => script.isInlineScript() && !script.hasSourceURL); - return scripts; - } - } - if (uiSourceCode.contentType().isScript()) { - var rawLocation = Bindings.debuggerWorkspaceBinding.uiLocationToRawLocation(uiSourceCode, 0, 0); - if (rawLocation) - return [rawLocation.script()]; - } - return []; - } - - /** - * @param {!Workspace.UISourceCode} uiSourceCode * @return {boolean} */ hasFormatted(uiSourceCode) { @@ -192,21 +109,12 @@ var formattedUISourceCode = this._project.addContentProvider(formattedURL, contentProvider); var formatData = new Sources.SourceFormatData(uiSourceCode, formattedUISourceCode, formatterMapping); formattedUISourceCode[Sources.SourceFormatData._formatDataSymbol] = formatData; + this._scriptMapping._setSourceMappingEnabled(formatData, true); + this._styleMapping._setSourceMappingEnabled(formatData, true); var path = formatData.originalPath(); this._formattedPaths.set(path, formattedUISourceCode); - var scripts = Sources.SourceFormatter._scriptsForUISourceCode(uiSourceCode); - if (!scripts) - return; - for (var script of scripts) { - script[Sources.SourceFormatData._formatDataSymbol] = formatData; - Bindings.debuggerWorkspaceBinding.pushSourceMapping(script, this._scriptMapping); - } - - Bindings.debuggerWorkspaceBinding.setSourceMapping( - scripts[0].debuggerModel, formattedUISourceCode, this._scriptMapping); - for (var decoration of uiSourceCode.allDecorations()) { var range = decoration.range(); var startLocation = formatterMapping.originalToFormatted(range.startLine, range.startColumn); @@ -222,4 +130,147 @@ } }; +/** + * @implements {Bindings.DebuggerSourceMapping} + */ +Sources.SourceFormatter.ScriptMapping = class { + /** + * @override + * @param {!SDK.DebuggerModel.Location} rawLocation + * @return {?Workspace.UILocation} + */ + rawLocationToUILocation(rawLocation) { + var script = rawLocation.script(); + var formatData = script && Sources.SourceFormatData._for(script); + if (!formatData) + return null; + var lineNumber = rawLocation.lineNumber; + var columnNumber = rawLocation.columnNumber || 0; + var formattedLocation = formatData.mapping.originalToFormatted(lineNumber, columnNumber); + return formatData.formattedSourceCode.uiLocation(formattedLocation[0], formattedLocation[1]); + } + + /** + * @override + * @param {!Workspace.UISourceCode} uiSourceCode + * @param {number} lineNumber + * @param {number} columnNumber + * @return {?SDK.DebuggerModel.Location} + */ + uiLocationToRawLocation(uiSourceCode, lineNumber, columnNumber) { + var formatData = Sources.SourceFormatData._for(uiSourceCode); + if (!formatData) + return null; + var originalLocation = formatData.mapping.formattedToOriginal(lineNumber, columnNumber); + var scripts = this._scriptsForUISourceCode(formatData.originalSourceCode); + if (!scripts.length) + return null; + return scripts[0].debuggerModel.createRawLocation(scripts[0], originalLocation[0], originalLocation[1]); + } + + /** + * @override + * @return {boolean} + */ + isIdentity() { + return false; + } + + /** + * @override + * @param {!Workspace.UISourceCode} uiSourceCode + * @param {number} lineNumber + * @return {boolean} + */ + uiLineHasMapping(uiSourceCode, lineNumber) { + return true; + } + + /** + * @param {!Sources.SourceFormatData} formatData + * @param {boolean} enabled + */ + _setSourceMappingEnabled(formatData, enabled) { + var scripts = this._scriptsForUISourceCode(formatData.originalSourceCode); + if (!scripts.length) + return; + if (enabled) { + for (var script of scripts) { + script[Sources.SourceFormatData._formatDataSymbol] = formatData; + Bindings.debuggerWorkspaceBinding.pushSourceMapping(script, this); + } + } else { + for (var script of scripts) { + delete script[Sources.SourceFormatData._formatDataSymbol]; + Bindings.debuggerWorkspaceBinding.popSourceMapping(script); + } + } + + Bindings.debuggerWorkspaceBinding.setSourceMapping( + scripts[0].debuggerModel, formatData.formattedSourceCode, enabled ? this : null); + } + + /** + * @param {!Workspace.UISourceCode} uiSourceCode + * @return {!Array<!SDK.Script>} + */ + _scriptsForUISourceCode(uiSourceCode) { + if (uiSourceCode.contentType() === Common.resourceTypes.Document) { + var target = Bindings.NetworkProject.targetForUISourceCode(uiSourceCode); + var debuggerModel = target && target.model(SDK.DebuggerModel); + if (debuggerModel) { + var scripts = debuggerModel.scriptsForSourceURL(uiSourceCode.url()) + .filter(script => script.isInlineScript() && !script.hasSourceURL); + return scripts; + } + } + if (uiSourceCode.contentType().isScript()) { + var rawLocation = Bindings.debuggerWorkspaceBinding.uiLocationToRawLocation(uiSourceCode, 0, 0); + if (rawLocation) + return [rawLocation.script()]; + } + return []; + } +}; + +/** + * @implements {Bindings.CSSWorkspaceBinding.SourceMapping} + */ +Sources.SourceFormatter.StyleMapping = class { + constructor() { + Bindings.cssWorkspaceBinding.addSourceMapping(this); + } + + /** + * @override + * @param {!SDK.CSSLocation} rawLocation + * @return {?Workspace.UILocation} + */ + rawLocationToUILocation(rawLocation) { + var styleHeader = rawLocation.header(); + var formatData = styleHeader && Sources.SourceFormatData._for(styleHeader); + if (!formatData) + return null; + var formattedLocation = + formatData.mapping.originalToFormatted(rawLocation.lineNumber, rawLocation.columnNumber || 0); + return formatData.formattedSourceCode.uiLocation(formattedLocation[0], formattedLocation[1]); + } + + /** + * @param {!Sources.SourceFormatData} formatData + * @param {boolean} enable + */ + _setSourceMappingEnabled(formatData, enable) { + var original = formatData.originalSourceCode; + var styleHeader = Bindings.NetworkProject.styleHeaderForUISourceCode(original); + if (!styleHeader) + return; + if (enable) + styleHeader[Sources.SourceFormatData._formatDataSymbol] = formatData; + else + delete styleHeader[Sources.SourceFormatData._formatDataSymbol]; + Bindings.cssWorkspaceBinding.updateLocations(styleHeader); + } +}; + Sources.sourceFormatter = new Sources.SourceFormatter();
diff --git a/third_party/WebKit/Source/devtools/front_end/text_utils/TextUtils.js b/third_party/WebKit/Source/devtools/front_end/text_utils/TextUtils.js index cd4f7033..f0adaf6 100644 --- a/third_party/WebKit/Source/devtools/front_end/text_utils/TextUtils.js +++ b/third_party/WebKit/Source/devtools/front_end/text_utils/TextUtils.js
@@ -280,3 +280,22 @@ */ createTokenizer(mimeType) {} }; + +/** + * @param {string} text + * @return {boolean} + */ +TextUtils.isMinified = function(text) { + var kMaxNonMinifiedLength = 500; + var linesToCheck = 10; + var lastPosition = 0; + do { + var eolIndex = text.indexOf('\n', lastPosition); + if (eolIndex < 0) + eolIndex = text.length; + if (eolIndex - lastPosition > kMaxNonMinifiedLength && text.substr(lastPosition, 3) !== '//#') + return true; + lastPosition = eolIndex + 1; + } while (--linesToCheck >= 0 && lastPosition < text.length); + return false; +}; \ No newline at end of file
diff --git a/third_party/WebKit/Source/modules/beacon/NavigatorBeacon.cpp b/third_party/WebKit/Source/modules/beacon/NavigatorBeacon.cpp index 829cf3c..8acd932b 100644 --- a/third_party/WebKit/Source/modules/beacon/NavigatorBeacon.cpp +++ b/third_party/WebKit/Source/modules/beacon/NavigatorBeacon.cpp
@@ -118,7 +118,7 @@ if (data.isArrayBufferView()) { allowed = PingLoader::SendBeacon(GetSupplementable()->GetFrame(), allowance, url, - data.getAsArrayBufferView(), beacon_size); + data.getAsArrayBufferView().View(), beacon_size); } else if (data.isBlob()) { Blob* blob = data.getAsBlob(); if (!FetchUtils::IsSimpleContentType(AtomicString(blob->type()))) {
diff --git a/third_party/WebKit/Source/modules/canvas2d/BaseRenderingContext2D.cpp b/third_party/WebKit/Source/modules/canvas2d/BaseRenderingContext2D.cpp index 9653160..ccc37be 100644 --- a/third_party/WebKit/Source/modules/canvas2d/BaseRenderingContext2D.cpp +++ b/third_party/WebKit/Source/modules/canvas2d/BaseRenderingContext2D.cpp
@@ -9,6 +9,7 @@ #include "bindings/core/v8/ScriptState.h" #include "core/css/cssom/CSSURLImageValue.h" #include "core/css/parser/CSSParser.h" +#include "core/dom/NotShared.h" #include "core/frame/ImageBitmap.h" #include "core/html/HTMLCanvasElement.h" #include "core/html/HTMLImageElement.h" @@ -1612,9 +1613,10 @@ NeedsFinalizeFrame(); DOMArrayBuffer* array_buffer = DOMArrayBuffer::Create(contents); - return ImageData::Create(image_data_rect.size(), - DOMUint8ClampedArray::Create( - array_buffer, 0, array_buffer->ByteLength())); + return ImageData::Create( + image_data_rect.size(), + NotShared<DOMUint8ClampedArray>(DOMUint8ClampedArray::Create( + array_buffer, 0, array_buffer->ByteLength()))); } void BaseRenderingContext2D::putImageData(ImageData* data,
diff --git a/third_party/WebKit/Source/modules/crypto/Crypto.cpp b/third_party/WebKit/Source/modules/crypto/Crypto.cpp index 483f20e7..0c91536 100644 --- a/third_party/WebKit/Source/modules/crypto/Crypto.cpp +++ b/third_party/WebKit/Source/modules/crypto/Crypto.cpp
@@ -50,27 +50,29 @@ } // namespace -DOMArrayBufferView* Crypto::getRandomValues(DOMArrayBufferView* array, - ExceptionState& exception_state) { - ASSERT(array); - if (!IsIntegerArray(array)) { +NotShared<DOMArrayBufferView> Crypto::getRandomValues( + NotShared<DOMArrayBufferView> array, + ExceptionState& exception_state) { + DCHECK(array); + if (!IsIntegerArray(array.View())) { exception_state.ThrowDOMException( kTypeMismatchError, String::Format("The provided ArrayBufferView is of type '%s', which is " "not an integer array type.", - array->TypeName())); - return nullptr; + array.View()->TypeName())); + return NotShared<DOMArrayBufferView>(nullptr); } - if (array->byteLength() > 65536) { + if (array.View()->byteLength() > 65536) { exception_state.ThrowDOMException( kQuotaExceededError, String::Format("The ArrayBufferView's byte length (%u) exceeds the " "number of bytes of entropy available via this API " "(65536).", - array->byteLength())); - return nullptr; + array.View()->byteLength())); + return NotShared<DOMArrayBufferView>(nullptr); } - CryptographicallyRandomValues(array->BaseAddress(), array->byteLength()); + CryptographicallyRandomValues(array.View()->BaseAddress(), + array.View()->byteLength()); return array; }
diff --git a/third_party/WebKit/Source/modules/crypto/Crypto.h b/third_party/WebKit/Source/modules/crypto/Crypto.h index b60f2d11..0591217 100644 --- a/third_party/WebKit/Source/modules/crypto/Crypto.h +++ b/third_party/WebKit/Source/modules/crypto/Crypto.h
@@ -44,7 +44,8 @@ public: static Crypto* Create() { return new Crypto(); } - DOMArrayBufferView* getRandomValues(DOMArrayBufferView*, ExceptionState&); + NotShared<DOMArrayBufferView> getRandomValues(NotShared<DOMArrayBufferView>, + ExceptionState&); SubtleCrypto* subtle();
diff --git a/third_party/WebKit/Source/modules/crypto/SubtleCrypto.cpp b/third_party/WebKit/Source/modules/crypto/SubtleCrypto.cpp index c774ea3..d45a653 100644 --- a/third_party/WebKit/Source/modules/crypto/SubtleCrypto.cpp +++ b/third_party/WebKit/Source/modules/crypto/SubtleCrypto.cpp
@@ -457,7 +457,7 @@ if (raw_key_data.isArrayBuffer()) { key_data = CopyBytes(raw_key_data.getAsArrayBuffer()); } else if (raw_key_data.isArrayBufferView()) { - key_data = CopyBytes(raw_key_data.getAsArrayBufferView()); + key_data = CopyBytes(raw_key_data.getAsArrayBufferView().View()); } else { result->CompleteWithError( kWebCryptoErrorTypeType,
diff --git a/third_party/WebKit/Source/modules/document_metadata/CopylessPasteServer.cpp b/third_party/WebKit/Source/modules/document_metadata/CopylessPasteServer.cpp index a91dbbb0..7890a88a 100644 --- a/third_party/WebKit/Source/modules/document_metadata/CopylessPasteServer.cpp +++ b/third_party/WebKit/Source/modules/document_metadata/CopylessPasteServer.cpp
@@ -28,9 +28,7 @@ callback.Run(nullptr); return; } - // TODO(wychen): connect with CopylessPasteExtractor::extract() like: - // callback.Run(CopylessPasteExtractor::extract(*m_frame->document())); - callback.Run(nullptr); + callback.Run(CopylessPasteExtractor::extract(*frame_->GetDocument())); } } // namespace blink
diff --git a/third_party/WebKit/Source/modules/encoding/TextDecoder.cpp b/third_party/WebKit/Source/modules/encoding/TextDecoder.cpp index e2c5fc9..b552a9bd 100644 --- a/third_party/WebKit/Source/modules/encoding/TextDecoder.cpp +++ b/third_party/WebKit/Source/modules/encoding/TextDecoder.cpp
@@ -81,9 +81,9 @@ ExceptionState& exception_state) { ASSERT(!input.isNull()); if (input.isArrayBufferView()) { - const char* start = - static_cast<const char*>(input.getAsArrayBufferView()->BaseAddress()); - size_t length = input.getAsArrayBufferView()->byteLength(); + const char* start = static_cast<const char*>( + input.getAsArrayBufferView().View()->BaseAddress()); + size_t length = input.getAsArrayBufferView().View()->byteLength(); return decode(start, length, options, exception_state); } ASSERT(input.isArrayBuffer());
diff --git a/third_party/WebKit/Source/modules/encoding/TextEncoder.cpp b/third_party/WebKit/Source/modules/encoding/TextEncoder.cpp index f206788..2c3d23d 100644 --- a/third_party/WebKit/Source/modules/encoding/TextEncoder.cpp +++ b/third_party/WebKit/Source/modules/encoding/TextEncoder.cpp
@@ -58,7 +58,7 @@ return name; } -DOMUint8Array* TextEncoder::encode(const String& input) { +NotShared<DOMUint8Array> TextEncoder::encode(const String& input) { CString result; if (input.Is8Bit()) result = codec_->Encode(input.Characters8(), input.length(), @@ -71,7 +71,8 @@ const unsigned char* unsigned_buffer = reinterpret_cast<const unsigned char*>(buffer); - return DOMUint8Array::Create(unsigned_buffer, result.length()); + return NotShared<DOMUint8Array>( + DOMUint8Array::Create(unsigned_buffer, result.length())); } } // namespace blink
diff --git a/third_party/WebKit/Source/modules/encoding/TextEncoder.h b/third_party/WebKit/Source/modules/encoding/TextEncoder.h index 21c59997..538fffb 100644 --- a/third_party/WebKit/Source/modules/encoding/TextEncoder.h +++ b/third_party/WebKit/Source/modules/encoding/TextEncoder.h
@@ -34,6 +34,7 @@ #include <memory> #include "bindings/core/v8/ScriptWrappable.h" #include "core/dom/DOMTypedArray.h" +#include "core/dom/NotShared.h" #include "platform/heap/Handle.h" #include "platform/wtf/text/TextCodec.h" #include "platform/wtf/text/TextEncoding.h" @@ -54,7 +55,7 @@ // Implement the IDL String encoding() const; - DOMUint8Array* encode(const String&); + NotShared<DOMUint8Array> encode(const String&); DEFINE_INLINE_TRACE() {}
diff --git a/third_party/WebKit/Source/modules/geolocation/Geoposition.h b/third_party/WebKit/Source/modules/geolocation/Geoposition.h index c2419721..b1f2598 100644 --- a/third_party/WebKit/Source/modules/geolocation/Geoposition.h +++ b/third_party/WebKit/Source/modules/geolocation/Geoposition.h
@@ -30,7 +30,7 @@ #include "modules/EventModules.h" #include "modules/geolocation/Coordinates.h" #include "platform/heap/Handle.h" -#include "platform/wtf/Assertions.h" +#include "wtf/Assertions.h" namespace blink {
diff --git a/third_party/WebKit/Source/modules/imagecapture/ImageCapture.idl b/third_party/WebKit/Source/modules/imagecapture/ImageCapture.idl index 39fa711..db1a39d 100644 --- a/third_party/WebKit/Source/modules/imagecapture/ImageCapture.idl +++ b/third_party/WebKit/Source/modules/imagecapture/ImageCapture.idl
@@ -11,7 +11,7 @@ DependentLifetime, MeasureAs=ImageCaptureConstructor, RaisesException=Constructor, - OriginTrialEnabled=ImageCapture, + RuntimeEnabled=ImageCapture, ] interface ImageCapture { [ImplementedAs=videoStreamTrack] readonly attribute MediaStreamTrack track;
diff --git a/third_party/WebKit/Source/modules/imagecapture/MediaSettingsRange.idl b/third_party/WebKit/Source/modules/imagecapture/MediaSettingsRange.idl index 7f8ee96..34223d9e 100644 --- a/third_party/WebKit/Source/modules/imagecapture/MediaSettingsRange.idl +++ b/third_party/WebKit/Source/modules/imagecapture/MediaSettingsRange.idl
@@ -5,7 +5,7 @@ // https://w3c.github.io/mediacapture-image/index.html#mediasettingsrange [ - OriginTrialEnabled=ImageCapture, + RuntimeEnabled=ImageCapture, ] interface MediaSettingsRange { readonly attribute double max; readonly attribute double min;
diff --git a/third_party/WebKit/Source/modules/imagecapture/PhotoCapabilities.idl b/third_party/WebKit/Source/modules/imagecapture/PhotoCapabilities.idl index fb0e802..d6e12f7 100644 --- a/third_party/WebKit/Source/modules/imagecapture/PhotoCapabilities.idl +++ b/third_party/WebKit/Source/modules/imagecapture/PhotoCapabilities.idl
@@ -24,7 +24,7 @@ }; [ - OriginTrialEnabled=ImageCapture, + RuntimeEnabled=ImageCapture, ] interface PhotoCapabilities { readonly attribute RedEyeReduction redEyeReduction; readonly attribute MediaSettingsRange imageHeight;
diff --git a/third_party/WebKit/Source/modules/media_capabilities/OWNERS b/third_party/WebKit/Source/modules/media_capabilities/OWNERS index 2d28246..b414293 100644 --- a/third_party/WebKit/Source/modules/media_capabilities/OWNERS +++ b/third_party/WebKit/Source/modules/media_capabilities/OWNERS
@@ -1 +1,4 @@ mlamouri@chromium.org + +# TEAM: media-dev@chromium.org +# COMPONENT: Blink>Media>Capabilities
diff --git a/third_party/WebKit/Source/modules/media_controls/BUILD.gn b/third_party/WebKit/Source/modules/media_controls/BUILD.gn index 406b4a9c..c4c0108 100644 --- a/third_party/WebKit/Source/modules/media_controls/BUILD.gn +++ b/third_party/WebKit/Source/modules/media_controls/BUILD.gn
@@ -14,11 +14,15 @@ "MediaControlsOrientationLockDelegate.h", "MediaControlsWindowEventListener.cpp", "MediaControlsWindowEventListener.h", + "elements/MediaControlCurrentTimeDisplayElement.cpp", + "elements/MediaControlCurrentTimeDisplayElement.h", "elements/MediaControlMuteButtonElement.cpp", "elements/MediaControlMuteButtonElement.h", "elements/MediaControlOverlayEnclosureElement.cpp", "elements/MediaControlOverlayEnclosureElement.h", "elements/MediaControlPanelEnclosureElement.cpp", "elements/MediaControlPanelEnclosureElement.h", + "elements/MediaControlRemainingTimeDisplayElement.cpp", + "elements/MediaControlRemainingTimeDisplayElement.h", ] }
diff --git a/third_party/WebKit/Source/modules/media_controls/MediaControlsImpl.cpp b/third_party/WebKit/Source/modules/media_controls/MediaControlsImpl.cpp index 372ad0e..46f1f6f 100644 --- a/third_party/WebKit/Source/modules/media_controls/MediaControlsImpl.cpp +++ b/third_party/WebKit/Source/modules/media_controls/MediaControlsImpl.cpp
@@ -46,9 +46,11 @@ #include "modules/media_controls/MediaControlsMediaEventListener.h" #include "modules/media_controls/MediaControlsOrientationLockDelegate.h" #include "modules/media_controls/MediaControlsWindowEventListener.h" +#include "modules/media_controls/elements/MediaControlCurrentTimeDisplayElement.h" #include "modules/media_controls/elements/MediaControlMuteButtonElement.h" #include "modules/media_controls/elements/MediaControlOverlayEnclosureElement.h" #include "modules/media_controls/elements/MediaControlPanelEnclosureElement.h" +#include "modules/media_controls/elements/MediaControlRemainingTimeDisplayElement.h" #include "platform/EventDispatchForbiddenScope.h" namespace blink { @@ -269,7 +271,7 @@ // | (-webkit-media-controls-play-button) // +-MediaControlCurrentTimeDisplayElement // | (-webkit-media-controls-current-time-display) -// +-MediaControlTimeRemainingDisplayElement +// +-MediaControlRemainingTimeDisplayElement // | (-webkit-media-controls-time-remaining-display) // +-MediaControlTimelineElement // | (-webkit-media-controls-timeline) @@ -324,16 +326,12 @@ play_button_ = play_button; panel->AppendChild(play_button); - MediaControlCurrentTimeDisplayElement* current_time_display = - MediaControlCurrentTimeDisplayElement::Create(*this); - current_time_display_ = current_time_display; + current_time_display_ = new MediaControlCurrentTimeDisplayElement(*this); current_time_display_->SetIsWanted(true); - panel->AppendChild(current_time_display); + panel->AppendChild(current_time_display_); - MediaControlTimeRemainingDisplayElement* duration_display = - MediaControlTimeRemainingDisplayElement::Create(*this); - duration_display_ = duration_display; - panel->AppendChild(duration_display); + duration_display_ = new MediaControlRemainingTimeDisplayElement(*this); + panel->AppendChild(duration_display_); MediaControlTimelineElement* timeline = MediaControlTimelineElement::Create(*this);
diff --git a/third_party/WebKit/Source/modules/media_controls/MediaControlsImpl.h b/third_party/WebKit/Source/modules/media_controls/MediaControlsImpl.h index bf839b5..629a236 100644 --- a/third_party/WebKit/Source/modules/media_controls/MediaControlsImpl.h +++ b/third_party/WebKit/Source/modules/media_controls/MediaControlsImpl.h
@@ -38,9 +38,11 @@ class MediaControlsMediaEventListener; class MediaControlsOrientationLockDelegate; class MediaControlsWindowEventListener; +class MediaControlCurrentTimeDisplayElement; class MediaControlMuteButtonElement; class MediaControlOverlayEnclosureElement; class MediaControlPanelEnclosureElement; +class MediaControlRemainingTimeDisplayElement; class ShadowRoot; // Default implementation of the core/ MediaControls interface used by @@ -209,7 +211,7 @@ Member<MediaControlPlayButtonElement> play_button_; Member<MediaControlTimelineElement> timeline_; Member<MediaControlCurrentTimeDisplayElement> current_time_display_; - Member<MediaControlTimeRemainingDisplayElement> duration_display_; + Member<MediaControlRemainingTimeDisplayElement> duration_display_; Member<MediaControlMuteButtonElement> mute_button_; Member<MediaControlVolumeSliderElement> volume_slider_; Member<MediaControlToggleClosedCaptionsButtonElement>
diff --git a/third_party/WebKit/Source/modules/media_controls/MediaControlsImplTest.cpp b/third_party/WebKit/Source/modules/media_controls/MediaControlsImplTest.cpp index 17e900f..9850df1 100644 --- a/third_party/WebKit/Source/modules/media_controls/MediaControlsImplTest.cpp +++ b/third_party/WebKit/Source/modules/media_controls/MediaControlsImplTest.cpp
@@ -21,6 +21,7 @@ #include "core/layout/LayoutObject.h" #include "core/loader/EmptyClients.h" #include "core/testing/DummyPageHolder.h" +#include "modules/media_controls/elements/MediaControlCurrentTimeDisplayElement.h" #include "platform/heap/Handle.h" #include "platform/testing/EmptyWebMediaPlayer.h" #include "platform/testing/HistogramTester.h" @@ -78,7 +79,7 @@ MockLayoutObject() : LayoutObject(nullptr) {} const char* GetName() const override { return "MockLayoutObject"; } - void GetLayout() override {} + void UpdateLayout() override {} FloatRect LocalBoundingBoxRectForAccessibility() const override { return FloatRect(); } @@ -205,6 +206,9 @@ MediaControlTimelineElement* TimelineElement() const { return media_controls_->timeline_; } + MediaControlCurrentTimeDisplayElement* GetCurrentTimeDisplayElement() const { + return media_controls_->current_time_display_; + } MockVideoWebMediaPlayer* WebMediaPlayer() { return static_cast<MockVideoWebMediaPlayer*>( MediaControls().MediaElement().GetWebMediaPlayer()); @@ -570,10 +574,7 @@ EnsureSizing(); MediaControlCurrentTimeDisplayElement* current_time_display = - static_cast<MediaControlCurrentTimeDisplayElement*>( - GetElementByShadowPseudoId( - MediaControls(), "-webkit-media-controls-current-time-display")); - + GetCurrentTimeDisplayElement(); double duration = 600; LoadMediaWithDuration(duration);
diff --git a/third_party/WebKit/Source/modules/media_controls/elements/MediaControlCurrentTimeDisplayElement.cpp b/third_party/WebKit/Source/modules/media_controls/elements/MediaControlCurrentTimeDisplayElement.cpp new file mode 100644 index 0000000..2c2c491 --- /dev/null +++ b/third_party/WebKit/Source/modules/media_controls/elements/MediaControlCurrentTimeDisplayElement.cpp
@@ -0,0 +1,18 @@ +// 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 "modules/media_controls/elements/MediaControlCurrentTimeDisplayElement.h" + +#include "modules/media_controls/MediaControlsImpl.h" + +namespace blink { + +MediaControlCurrentTimeDisplayElement::MediaControlCurrentTimeDisplayElement( + MediaControlsImpl& media_controls) + : MediaControlTimeDisplayElement(media_controls, kMediaCurrentTimeDisplay) { + SetShadowPseudoId( + AtomicString("-webkit-media-controls-current-time-display")); +} + +} // namespace blink
diff --git a/third_party/WebKit/Source/modules/media_controls/elements/MediaControlCurrentTimeDisplayElement.h b/third_party/WebKit/Source/modules/media_controls/elements/MediaControlCurrentTimeDisplayElement.h new file mode 100644 index 0000000..44bcee6 --- /dev/null +++ b/third_party/WebKit/Source/modules/media_controls/elements/MediaControlCurrentTimeDisplayElement.h
@@ -0,0 +1,22 @@ +// 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 MediaControlCurrentTimeDisplayElement_h +#define MediaControlCurrentTimeDisplayElement_h + +#include "core/html/shadow/MediaControlElementTypes.h" + +namespace blink { + +class MediaControlsImpl; + +class MediaControlCurrentTimeDisplayElement final + : public MediaControlTimeDisplayElement { + public: + explicit MediaControlCurrentTimeDisplayElement(MediaControlsImpl&); +}; + +} // namespace blink + +#endif // MediaControlCurrentTimeDisplayElement_h
diff --git a/third_party/WebKit/Source/modules/media_controls/elements/MediaControlRemainingTimeDisplayElement.cpp b/third_party/WebKit/Source/modules/media_controls/elements/MediaControlRemainingTimeDisplayElement.cpp new file mode 100644 index 0000000..a6e2349 --- /dev/null +++ b/third_party/WebKit/Source/modules/media_controls/elements/MediaControlRemainingTimeDisplayElement.cpp
@@ -0,0 +1,19 @@ +// 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 "modules/media_controls/elements/MediaControlRemainingTimeDisplayElement.h" + +#include "modules/media_controls/MediaControlsImpl.h" + +namespace blink { + +MediaControlRemainingTimeDisplayElement:: + MediaControlRemainingTimeDisplayElement(MediaControlsImpl& media_controls) + : MediaControlTimeDisplayElement(media_controls, + kMediaTimeRemainingDisplay) { + SetShadowPseudoId( + AtomicString("-webkit-media-controls-time-remaining-display")); +} + +} // namespace blink
diff --git a/third_party/WebKit/Source/modules/media_controls/elements/MediaControlRemainingTimeDisplayElement.h b/third_party/WebKit/Source/modules/media_controls/elements/MediaControlRemainingTimeDisplayElement.h new file mode 100644 index 0000000..5808743 --- /dev/null +++ b/third_party/WebKit/Source/modules/media_controls/elements/MediaControlRemainingTimeDisplayElement.h
@@ -0,0 +1,22 @@ +// 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 MediaControlRemainingTimeDisplayElement_h +#define MediaControlRemainingTimeDisplayElement_h + +#include "core/html/shadow/MediaControlElementTypes.h" + +namespace blink { + +class MediaControlsImpl; + +class MediaControlRemainingTimeDisplayElement final + : public MediaControlTimeDisplayElement { + public: + explicit MediaControlRemainingTimeDisplayElement(MediaControlsImpl&); +}; + +} // namespace blink + +#endif // MediaControlRemainingTimeDisplayElement_h
diff --git a/third_party/WebKit/Source/modules/mediasession/OWNERS b/third_party/WebKit/Source/modules/mediasession/OWNERS index 816cc37..59fed2ee 100644 --- a/third_party/WebKit/Source/modules/mediasession/OWNERS +++ b/third_party/WebKit/Source/modules/mediasession/OWNERS
@@ -6,4 +6,5 @@ per-file *StructTraits*.*=set noparent per-file *StructTraits*.*=file://ipc/SECURITY_OWNERS -# COMPONENT: Blink>Media +# TEAM: media-dev@chromium.org +# COMPONENT: Blink>Media>Session
diff --git a/third_party/WebKit/Source/modules/mediasource/SourceBuffer.cpp b/third_party/WebKit/Source/modules/mediasource/SourceBuffer.cpp index 724e3ac3..3d525518 100644 --- a/third_party/WebKit/Source/modules/mediasource/SourceBuffer.cpp +++ b/third_party/WebKit/Source/modules/mediasource/SourceBuffer.cpp
@@ -360,13 +360,15 @@ data->ByteLength(), exception_state); } -void SourceBuffer::appendBuffer(DOMArrayBufferView* data, +void SourceBuffer::appendBuffer(NotShared<DOMArrayBufferView> data, ExceptionState& exception_state) { - BLINK_SBLOG << __func__ << " this=" << this << " size=" << data->byteLength(); + BLINK_SBLOG << __func__ << " this=" << this + << " size=" << data.View()->byteLength(); // Section 3.2 appendBuffer() // https://dvcs.w3.org/hg/html-media/raw-file/default/media-source/media-source.html#widl-SourceBuffer-appendBuffer-void-ArrayBufferView-data - AppendBufferInternal(static_cast<const unsigned char*>(data->BaseAddress()), - data->byteLength(), exception_state); + AppendBufferInternal( + static_cast<const unsigned char*>(data.View()->BaseAddress()), + data.View()->byteLength(), exception_state); } void SourceBuffer::abort(ExceptionState& exception_state) {
diff --git a/third_party/WebKit/Source/modules/mediasource/SourceBuffer.h b/third_party/WebKit/Source/modules/mediasource/SourceBuffer.h index 2a8ad76..6647c0c 100644 --- a/third_party/WebKit/Source/modules/mediasource/SourceBuffer.h +++ b/third_party/WebKit/Source/modules/mediasource/SourceBuffer.h
@@ -33,6 +33,7 @@ #include <memory> #include "bindings/core/v8/ActiveScriptWrappable.h" +#include "core/dom/NotShared.h" #include "core/dom/SuspendableObject.h" #include "modules/EventTargetModules.h" #include "modules/mediasource/TrackDefaultList.h" @@ -78,7 +79,7 @@ double timestampOffset() const; void setTimestampOffset(double, ExceptionState&); void appendBuffer(DOMArrayBuffer* data, ExceptionState&); - void appendBuffer(DOMArrayBufferView* data, ExceptionState&); + void appendBuffer(NotShared<DOMArrayBufferView> data, ExceptionState&); void abort(ExceptionState&); void remove(double start, double end, ExceptionState&); double appendWindowStart() const;
diff --git a/third_party/WebKit/Source/modules/mediastream/MediaTrackCapabilities.idl b/third_party/WebKit/Source/modules/mediastream/MediaTrackCapabilities.idl index e6ed80a..84265fe7 100644 --- a/third_party/WebKit/Source/modules/mediastream/MediaTrackCapabilities.idl +++ b/third_party/WebKit/Source/modules/mediastream/MediaTrackCapabilities.idl
@@ -7,16 +7,16 @@ // https://w3c.github.io/mediacapture-image/#mediatrackcapabilities-section // TODO(mcasas) move out when partial dictionaries are supported // http://crbug.com/579896. - [OriginTrialEnabled=ImageCapture] sequence<DOMString> whiteBalanceMode; - [OriginTrialEnabled=ImageCapture] sequence<DOMString> exposureMode; - [OriginTrialEnabled=ImageCapture] sequence<DOMString> focusMode; - [OriginTrialEnabled=ImageCapture] MediaSettingsRange exposureCompensation; - [OriginTrialEnabled=ImageCapture] MediaSettingsRange colorTemperature; - [OriginTrialEnabled=ImageCapture] MediaSettingsRange iso; - [OriginTrialEnabled=ImageCapture] MediaSettingsRange brightness; - [OriginTrialEnabled=ImageCapture] MediaSettingsRange contrast; - [OriginTrialEnabled=ImageCapture] MediaSettingsRange saturation; - [OriginTrialEnabled=ImageCapture] MediaSettingsRange sharpness; - [OriginTrialEnabled=ImageCapture] MediaSettingsRange zoom; - [OriginTrialEnabled=ImageCapture] boolean torch; + [RuntimeEnabled=ImageCapture] sequence<DOMString> whiteBalanceMode; + [RuntimeEnabled=ImageCapture] sequence<DOMString> exposureMode; + [RuntimeEnabled=ImageCapture] sequence<DOMString> focusMode; + [RuntimeEnabled=ImageCapture] MediaSettingsRange exposureCompensation; + [RuntimeEnabled=ImageCapture] MediaSettingsRange colorTemperature; + [RuntimeEnabled=ImageCapture] MediaSettingsRange iso; + [RuntimeEnabled=ImageCapture] MediaSettingsRange brightness; + [RuntimeEnabled=ImageCapture] MediaSettingsRange contrast; + [RuntimeEnabled=ImageCapture] MediaSettingsRange saturation; + [RuntimeEnabled=ImageCapture] MediaSettingsRange sharpness; + [RuntimeEnabled=ImageCapture] MediaSettingsRange zoom; + [RuntimeEnabled=ImageCapture] boolean torch; };
diff --git a/third_party/WebKit/Source/modules/mediastream/MediaTrackConstraintSet.idl b/third_party/WebKit/Source/modules/mediastream/MediaTrackConstraintSet.idl index 6be0d99b..f02e0c0 100644 --- a/third_party/WebKit/Source/modules/mediastream/MediaTrackConstraintSet.idl +++ b/third_party/WebKit/Source/modules/mediastream/MediaTrackConstraintSet.idl
@@ -38,19 +38,19 @@ // https://w3c.github.io/mediacapture-image/#mediatrackconstraintset-section // TODO(mcasas) move out when partial dictionaries are supported // http://crbug.com/579896. - [OriginTrialEnabled=ImageCapture] ConstrainDOMString whiteBalanceMode; - [OriginTrialEnabled=ImageCapture] ConstrainDOMString exposureMode; - [OriginTrialEnabled=ImageCapture] ConstrainDOMString focusMode; - [OriginTrialEnabled=ImageCapture] ConstrainPoint2D pointsOfInterest; - [OriginTrialEnabled=ImageCapture] ConstrainDouble exposureCompensation; - [OriginTrialEnabled=ImageCapture] ConstrainDouble colorTemperature; - [OriginTrialEnabled=ImageCapture] ConstrainDouble iso; - [OriginTrialEnabled=ImageCapture] ConstrainDouble brightness; - [OriginTrialEnabled=ImageCapture] ConstrainDouble contrast; - [OriginTrialEnabled=ImageCapture] ConstrainDouble saturation; - [OriginTrialEnabled=ImageCapture] ConstrainDouble sharpness; - [OriginTrialEnabled=ImageCapture] ConstrainDouble zoom; - [OriginTrialEnabled=ImageCapture] ConstrainBoolean torch; + [RuntimeEnabled=ImageCapture] ConstrainDOMString whiteBalanceMode; + [RuntimeEnabled=ImageCapture] ConstrainDOMString exposureMode; + [RuntimeEnabled=ImageCapture] ConstrainDOMString focusMode; + [RuntimeEnabled=ImageCapture] ConstrainPoint2D pointsOfInterest; + [RuntimeEnabled=ImageCapture] ConstrainDouble exposureCompensation; + [RuntimeEnabled=ImageCapture] ConstrainDouble colorTemperature; + [RuntimeEnabled=ImageCapture] ConstrainDouble iso; + [RuntimeEnabled=ImageCapture] ConstrainDouble brightness; + [RuntimeEnabled=ImageCapture] ConstrainDouble contrast; + [RuntimeEnabled=ImageCapture] ConstrainDouble saturation; + [RuntimeEnabled=ImageCapture] ConstrainDouble sharpness; + [RuntimeEnabled=ImageCapture] ConstrainDouble zoom; + [RuntimeEnabled=ImageCapture] ConstrainBoolean torch; // The "mandatory" and "_optional" members are retained for conformance // with https://www.w3.org/TR/2013/WD-mediacapture-streams-20130903/ Dictionary mandatory;
diff --git a/third_party/WebKit/Source/modules/mediastream/MediaTrackSettings.idl b/third_party/WebKit/Source/modules/mediastream/MediaTrackSettings.idl index 6991736b..2b6dddb 100644 --- a/third_party/WebKit/Source/modules/mediastream/MediaTrackSettings.idl +++ b/third_party/WebKit/Source/modules/mediastream/MediaTrackSettings.idl
@@ -37,17 +37,17 @@ // https://w3c.github.io/mediacapture-image/#mediatracksettings-section // TODO(mcasas) move out when partial dictionaries are supported // http://crbug.com/579896. - [OriginTrialEnabled=ImageCapture] DOMString whiteBalanceMode; - [OriginTrialEnabled=ImageCapture] DOMString exposureMode; - [OriginTrialEnabled=ImageCapture] DOMString focusMode; - [OriginTrialEnabled=ImageCapture] sequence<Point2D> pointsOfInterest; - [OriginTrialEnabled=ImageCapture] double exposureCompensation; - [OriginTrialEnabled=ImageCapture] double colorTemperature; - [OriginTrialEnabled=ImageCapture] double iso; - [OriginTrialEnabled=ImageCapture] double brightness; - [OriginTrialEnabled=ImageCapture] double contrast; - [OriginTrialEnabled=ImageCapture] double saturation; - [OriginTrialEnabled=ImageCapture] double sharpness; - [OriginTrialEnabled=ImageCapture] double zoom; - [OriginTrialEnabled=ImageCapture] boolean torch; + [RuntimeEnabled=ImageCapture] DOMString whiteBalanceMode; + [RuntimeEnabled=ImageCapture] DOMString exposureMode; + [RuntimeEnabled=ImageCapture] DOMString focusMode; + [RuntimeEnabled=ImageCapture] sequence<Point2D> pointsOfInterest; + [RuntimeEnabled=ImageCapture] double exposureCompensation; + [RuntimeEnabled=ImageCapture] double colorTemperature; + [RuntimeEnabled=ImageCapture] double iso; + [RuntimeEnabled=ImageCapture] double brightness; + [RuntimeEnabled=ImageCapture] double contrast; + [RuntimeEnabled=ImageCapture] double saturation; + [RuntimeEnabled=ImageCapture] double sharpness; + [RuntimeEnabled=ImageCapture] double zoom; + [RuntimeEnabled=ImageCapture] boolean torch; };
diff --git a/third_party/WebKit/Source/modules/mediastream/MediaTrackSupportedConstraints.idl b/third_party/WebKit/Source/modules/mediastream/MediaTrackSupportedConstraints.idl index b2e8cdc..76b7b755 100644 --- a/third_party/WebKit/Source/modules/mediastream/MediaTrackSupportedConstraints.idl +++ b/third_party/WebKit/Source/modules/mediastream/MediaTrackSupportedConstraints.idl
@@ -37,17 +37,17 @@ // https://w3c.github.io/mediacapture-image/#mediatracksupportedconstraints-section // TODO(mcasas) move out when partial dictionaries are supported // http://crbug.com/579896. - [OriginTrialEnabled=ImageCapture] boolean whiteBalanceMode = true; - [OriginTrialEnabled=ImageCapture] boolean exposureMode = true; - [OriginTrialEnabled=ImageCapture] boolean focusMode = true; - [OriginTrialEnabled=ImageCapture] boolean pointsOfInterest = true; - [OriginTrialEnabled=ImageCapture] boolean exposureCompensation = true; - [OriginTrialEnabled=ImageCapture] boolean colorTemperature = true; - [OriginTrialEnabled=ImageCapture] boolean iso = true; - [OriginTrialEnabled=ImageCapture] boolean brightness = true; - [OriginTrialEnabled=ImageCapture] boolean contrast = true; - [OriginTrialEnabled=ImageCapture] boolean saturation = true; - [OriginTrialEnabled=ImageCapture] boolean sharpness = true; - [OriginTrialEnabled=ImageCapture] boolean zoom = true; - [OriginTrialEnabled=ImageCapture] boolean torch = true; + [RuntimeEnabled=ImageCapture] boolean whiteBalanceMode = true; + [RuntimeEnabled=ImageCapture] boolean exposureMode = true; + [RuntimeEnabled=ImageCapture] boolean focusMode = true; + [RuntimeEnabled=ImageCapture] boolean pointsOfInterest = true; + [RuntimeEnabled=ImageCapture] boolean exposureCompensation = true; + [RuntimeEnabled=ImageCapture] boolean colorTemperature = true; + [RuntimeEnabled=ImageCapture] boolean iso = true; + [RuntimeEnabled=ImageCapture] boolean brightness = true; + [RuntimeEnabled=ImageCapture] boolean contrast = true; + [RuntimeEnabled=ImageCapture] boolean saturation = true; + [RuntimeEnabled=ImageCapture] boolean sharpness = true; + [RuntimeEnabled=ImageCapture] boolean zoom = true; + [RuntimeEnabled=ImageCapture] boolean torch = true; };
diff --git a/third_party/WebKit/Source/modules/notifications/Notification.cpp b/third_party/WebKit/Source/modules/notifications/Notification.cpp index 56b2186..0b801f6 100644 --- a/third_party/WebKit/Source/modules/notifications/Notification.cpp +++ b/third_party/WebKit/Source/modules/notifications/Notification.cpp
@@ -368,11 +368,12 @@ Deprecation::CountDeprecation( context, UseCounter::kNotificationPermissionRequestedInsecureOrigin); } + if (context->IsDocument()) { LocalFrame* frame = ToDocument(context)->GetFrame(); if (frame && !frame->IsMainFrame()) { - UseCounter::Count(context, - UseCounter::kNotificationPermissionRequestedIframe); + Deprecation::CountDeprecation( + context, UseCounter::kNotificationPermissionRequestedIframe); } }
diff --git a/third_party/WebKit/Source/modules/payments/PaymentRequest.cpp b/third_party/WebKit/Source/modules/payments/PaymentRequest.cpp index 9b1f9b0..996611e9 100644 --- a/third_party/WebKit/Source/modules/payments/PaymentRequest.cpp +++ b/third_party/WebKit/Source/modules/payments/PaymentRequest.cpp
@@ -1061,8 +1061,8 @@ can_make_payment_resolver_->Resolve(false); break; case CanMakePaymentQueryResult::QUERY_QUOTA_EXCEEDED: - can_make_payment_resolver_->Reject( - DOMException::Create(kQuotaExceededError, "Query quota exceeded")); + can_make_payment_resolver_->Reject(DOMException::Create( + kNotAllowedError, "Not allowed to check whether can make payment")); break; }
diff --git a/third_party/WebKit/Source/modules/peerconnection/RTCDataChannel.cpp b/third_party/WebKit/Source/modules/peerconnection/RTCDataChannel.cpp index 872f4719..fcecd8e 100644 --- a/third_party/WebKit/Source/modules/peerconnection/RTCDataChannel.cpp +++ b/third_party/WebKit/Source/modules/peerconnection/RTCDataChannel.cpp
@@ -227,10 +227,11 @@ } } -void RTCDataChannel::send(DOMArrayBufferView* data, +void RTCDataChannel::send(NotShared<DOMArrayBufferView> data, ExceptionState& exception_state) { - if (!handler_->SendRawData(static_cast<const char*>(data->BaseAddress()), - data->byteLength())) { + if (!handler_->SendRawData( + static_cast<const char*>(data.View()->BaseAddress()), + data.View()->byteLength())) { // FIXME: This should not throw an exception but instead forcefully close // the data channel. ThrowCouldNotSendDataException(exception_state);
diff --git a/third_party/WebKit/Source/modules/peerconnection/RTCDataChannel.h b/third_party/WebKit/Source/modules/peerconnection/RTCDataChannel.h index ca35fb7..3692b1e 100644 --- a/third_party/WebKit/Source/modules/peerconnection/RTCDataChannel.h +++ b/third_party/WebKit/Source/modules/peerconnection/RTCDataChannel.h
@@ -28,6 +28,7 @@ #include <memory> #include "base/gtest_prod_util.h" #include "bindings/core/v8/ActiveScriptWrappable.h" +#include "core/dom/NotShared.h" #include "core/dom/SuspendableObject.h" #include "modules/EventTargetModules.h" #include "platform/Timer.h" @@ -89,7 +90,7 @@ void send(const String&, ExceptionState&); void send(DOMArrayBuffer*, ExceptionState&); - void send(DOMArrayBufferView*, ExceptionState&); + void send(NotShared<DOMArrayBufferView>, ExceptionState&); void send(Blob*, ExceptionState&); void close();
diff --git a/third_party/WebKit/Source/modules/presentation/OWNERS b/third_party/WebKit/Source/modules/presentation/OWNERS index 9a20d44e..7fef279 100644 --- a/third_party/WebKit/Source/modules/presentation/OWNERS +++ b/third_party/WebKit/Source/modules/presentation/OWNERS
@@ -3,4 +3,8 @@ mfoltz@chromium.org mlamouri@chromium.org +per-file *.mojom=set noparent +per-file *.mojom=file://ipc/SECURITY_OWNERS + +# TEAM: media-dev@chromium.org # COMPONENT: Blink>PresentationAPI
diff --git a/third_party/WebKit/Source/modules/presentation/PresentationConnection.cpp b/third_party/WebKit/Source/modules/presentation/PresentationConnection.cpp index 2069e04..c2d82a6 100644 --- a/third_party/WebKit/Source/modules/presentation/PresentationConnection.cpp +++ b/third_party/WebKit/Source/modules/presentation/PresentationConnection.cpp
@@ -282,13 +282,14 @@ HandleMessageQueue(); } -void PresentationConnection::send(DOMArrayBufferView* array_buffer_view, - ExceptionState& exception_state) { - ASSERT(array_buffer_view); +void PresentationConnection::send( + NotShared<DOMArrayBufferView> array_buffer_view, + ExceptionState& exception_state) { + DCHECK(array_buffer_view); if (!CanSendMessage(exception_state)) return; - messages_.push_back(new Message(array_buffer_view->buffer())); + messages_.push_back(new Message(array_buffer_view.View()->buffer())); HandleMessageQueue(); }
diff --git a/third_party/WebKit/Source/modules/presentation/PresentationConnection.h b/third_party/WebKit/Source/modules/presentation/PresentationConnection.h index d4ed003..13346e5 100644 --- a/third_party/WebKit/Source/modules/presentation/PresentationConnection.h +++ b/third_party/WebKit/Source/modules/presentation/PresentationConnection.h
@@ -7,6 +7,7 @@ #include <memory> #include "core/dom/ContextLifecycleObserver.h" +#include "core/dom/NotShared.h" #include "core/events/EventTarget.h" #include "core/fileapi/Blob.h" #include "core/fileapi/FileError.h" @@ -60,7 +61,7 @@ void send(const String& message, ExceptionState&); void send(DOMArrayBuffer*, ExceptionState&); - void send(DOMArrayBufferView*, ExceptionState&); + void send(NotShared<DOMArrayBufferView>, ExceptionState&); void send(Blob*, ExceptionState&); void close(); void terminate();
diff --git a/third_party/WebKit/Source/modules/presentation/PresentationReceiver.cpp b/third_party/WebKit/Source/modules/presentation/PresentationReceiver.cpp index 377e345..064ca77 100644 --- a/third_party/WebKit/Source/modules/presentation/PresentationReceiver.cpp +++ b/third_party/WebKit/Source/modules/presentation/PresentationReceiver.cpp
@@ -11,7 +11,10 @@ #include "core/dom/ExceptionCode.h" #include "core/frame/LocalDOMWindow.h" #include "core/frame/LocalFrame.h" +#include "core/frame/Navigator.h" #include "core/frame/UseCounter.h" +#include "modules/presentation/NavigatorPresentation.h" +#include "modules/presentation/Presentation.h" #include "modules/presentation/PresentationConnection.h" #include "modules/presentation/PresentationConnectionList.h" #include "public/platform/modules/presentation/WebPresentationClient.h" @@ -28,6 +31,18 @@ client->SetReceiver(this); } +// static +PresentationReceiver* PresentationReceiver::From(Document& document) { + if (!document.GetFrame() || !document.GetFrame()->DomWindow()) + return nullptr; + Navigator& navigator = *document.GetFrame()->DomWindow()->navigator(); + Presentation* presentation = NavigatorPresentation::presentation(navigator); + if (!presentation) + return nullptr; + + return presentation->receiver(); +} + ScriptPromise PresentationReceiver::connectionList(ScriptState* script_state) { if (!connection_list_property_) connection_list_property_ =
diff --git a/third_party/WebKit/Source/modules/presentation/PresentationReceiver.h b/third_party/WebKit/Source/modules/presentation/PresentationReceiver.h index e29f745..1d03481 100644 --- a/third_party/WebKit/Source/modules/presentation/PresentationReceiver.h +++ b/third_party/WebKit/Source/modules/presentation/PresentationReceiver.h
@@ -23,7 +23,9 @@ class WebPresentationClient; // Implements the PresentationReceiver interface from the Presentation API from -// which websites can implement the receiving side of a presentation. +// which websites can implement the receiving side of a presentation. This needs +// to be eagerly created in order to have the receiver associated with the +// client. class MODULES_EXPORT PresentationReceiver final : public GarbageCollectedFinalized<PresentationReceiver>, public ScriptWrappable, @@ -37,9 +39,11 @@ Member<DOMException>>; public: - explicit PresentationReceiver(LocalFrame*, WebPresentationClient*); + PresentationReceiver(LocalFrame*, WebPresentationClient*); ~PresentationReceiver() = default; + static PresentationReceiver* From(Document&); + // PresentationReceiver.idl implementation ScriptPromise connectionList(ScriptState*);
diff --git a/third_party/WebKit/Source/modules/push_messaging/PushMessageData.cpp b/third_party/WebKit/Source/modules/push_messaging/PushMessageData.cpp index 5786e6b..454aeef 100644 --- a/third_party/WebKit/Source/modules/push_messaging/PushMessageData.cpp +++ b/third_party/WebKit/Source/modules/push_messaging/PushMessageData.cpp
@@ -32,9 +32,10 @@ PushMessageData* PushMessageData::Create( const ArrayBufferOrArrayBufferViewOrUSVString& message_data) { if (message_data.isArrayBuffer() || message_data.isArrayBufferView()) { - DOMArrayBuffer* buffer = message_data.isArrayBufferView() - ? message_data.getAsArrayBufferView()->buffer() - : message_data.getAsArrayBuffer(); + DOMArrayBuffer* buffer = + message_data.isArrayBufferView() + ? message_data.getAsArrayBufferView().View()->buffer() + : message_data.getAsArrayBuffer(); return new PushMessageData(static_cast<const char*>(buffer->Data()), buffer->ByteLength());
diff --git a/third_party/WebKit/Source/modules/push_messaging/PushSubscriptionOptions.cpp b/third_party/WebKit/Source/modules/push_messaging/PushSubscriptionOptions.cpp index 5505e24..31bef25f 100644 --- a/third_party/WebKit/Source/modules/push_messaging/PushSubscriptionOptions.cpp +++ b/third_party/WebKit/Source/modules/push_messaging/PushSubscriptionOptions.cpp
@@ -31,9 +31,11 @@ length = application_server_key.getAsArrayBuffer()->ByteLength(); } else if (application_server_key.isArrayBufferView()) { input = static_cast<unsigned char*>( - application_server_key.getAsArrayBufferView()->buffer()->Data()); - length = - application_server_key.getAsArrayBufferView()->buffer()->ByteLength(); + application_server_key.getAsArrayBufferView().View()->buffer()->Data()); + length = application_server_key.getAsArrayBufferView() + .View() + ->buffer() + ->ByteLength(); } else { NOTREACHED(); return String();
diff --git a/third_party/WebKit/Source/modules/remoteplayback/OWNERS b/third_party/WebKit/Source/modules/remoteplayback/OWNERS index dc2593f..781e520 100644 --- a/third_party/WebKit/Source/modules/remoteplayback/OWNERS +++ b/third_party/WebKit/Source/modules/remoteplayback/OWNERS
@@ -1,2 +1,6 @@ avayvod@chromium.org mlamouri@chromium.org + +# TEAM: media-dev@chromium.org +# COMPONENT: Blink>Media>RemotePlayback +
diff --git a/third_party/WebKit/Source/modules/screen_orientation/OWNERS b/third_party/WebKit/Source/modules/screen_orientation/OWNERS index 2d28246..db222cf 100644 --- a/third_party/WebKit/Source/modules/screen_orientation/OWNERS +++ b/third_party/WebKit/Source/modules/screen_orientation/OWNERS
@@ -1 +1,7 @@ mlamouri@chromium.org + +per-file *.mojom=set noparent +per-file *.mojom=file://ipc/SECURITY_OWNERS + +# COMPONENT: Blink>ScreenOrientation +
diff --git a/third_party/WebKit/Source/modules/sensor/OrientationSensor.cpp b/third_party/WebKit/Source/modules/sensor/OrientationSensor.cpp index a4d70a4..ed5454c 100644 --- a/third_party/WebKit/Source/modules/sensor/OrientationSensor.cpp +++ b/third_party/WebKit/Source/modules/sensor/OrientationSensor.cpp
@@ -107,9 +107,9 @@ Float32ArrayOrFloat64ArrayOrDOMMatrix& matrix, ExceptionState& exception_state) { if (matrix.isFloat32Array()) - PopulateMatrixInternal(matrix.getAsFloat32Array(), exception_state); + PopulateMatrixInternal(matrix.getAsFloat32Array().View(), exception_state); else if (matrix.isFloat64Array()) - PopulateMatrixInternal(matrix.getAsFloat64Array(), exception_state); + PopulateMatrixInternal(matrix.getAsFloat64Array().View(), exception_state); else if (matrix.isDOMMatrix()) PopulateMatrixInternal(matrix.getAsDOMMatrix(), exception_state); else
diff --git a/third_party/WebKit/Source/modules/webaudio/AnalyserNode.cpp b/third_party/WebKit/Source/modules/webaudio/AnalyserNode.cpp index 822e811..55a3109 100644 --- a/third_party/WebKit/Source/modules/webaudio/AnalyserNode.cpp +++ b/third_party/WebKit/Source/modules/webaudio/AnalyserNode.cpp
@@ -265,20 +265,22 @@ return GetAnalyserHandler().SmoothingTimeConstant(); } -void AnalyserNode::getFloatFrequencyData(DOMFloat32Array* array) { - GetAnalyserHandler().GetFloatFrequencyData(array, context()->currentTime()); +void AnalyserNode::getFloatFrequencyData(NotShared<DOMFloat32Array> array) { + GetAnalyserHandler().GetFloatFrequencyData(array.View(), + context()->currentTime()); } -void AnalyserNode::getByteFrequencyData(DOMUint8Array* array) { - GetAnalyserHandler().GetByteFrequencyData(array, context()->currentTime()); +void AnalyserNode::getByteFrequencyData(NotShared<DOMUint8Array> array) { + GetAnalyserHandler().GetByteFrequencyData(array.View(), + context()->currentTime()); } -void AnalyserNode::getFloatTimeDomainData(DOMFloat32Array* array) { - GetAnalyserHandler().GetFloatTimeDomainData(array); +void AnalyserNode::getFloatTimeDomainData(NotShared<DOMFloat32Array> array) { + GetAnalyserHandler().GetFloatTimeDomainData(array.View()); } -void AnalyserNode::getByteTimeDomainData(DOMUint8Array* array) { - GetAnalyserHandler().GetByteTimeDomainData(array); +void AnalyserNode::getByteTimeDomainData(NotShared<DOMUint8Array> array) { + GetAnalyserHandler().GetByteTimeDomainData(array.View()); } } // namespace blink
diff --git a/third_party/WebKit/Source/modules/webaudio/AnalyserNode.h b/third_party/WebKit/Source/modules/webaudio/AnalyserNode.h index b0dc0da..e124487 100644 --- a/third_party/WebKit/Source/modules/webaudio/AnalyserNode.h +++ b/third_party/WebKit/Source/modules/webaudio/AnalyserNode.h
@@ -27,6 +27,7 @@ #define AnalyserNode_h #include "core/dom/DOMTypedArray.h" +#include "core/dom/NotShared.h" #include "modules/webaudio/AudioBasicInspectorNode.h" #include "modules/webaudio/RealtimeAnalyser.h" @@ -111,10 +112,10 @@ double maxDecibels() const; void setSmoothingTimeConstant(double, ExceptionState&); double smoothingTimeConstant() const; - void getFloatFrequencyData(DOMFloat32Array*); - void getByteFrequencyData(DOMUint8Array*); - void getFloatTimeDomainData(DOMFloat32Array*); - void getByteTimeDomainData(DOMUint8Array*); + void getFloatFrequencyData(NotShared<DOMFloat32Array>); + void getByteFrequencyData(NotShared<DOMUint8Array>); + void getFloatTimeDomainData(NotShared<DOMFloat32Array>); + void getByteTimeDomainData(NotShared<DOMUint8Array>); private: AnalyserNode(BaseAudioContext&);
diff --git a/third_party/WebKit/Source/modules/webaudio/AudioBuffer.cpp b/third_party/WebKit/Source/modules/webaudio/AudioBuffer.cpp index 8d07c3c..190e104 100644 --- a/third_party/WebKit/Source/modules/webaudio/AudioBuffer.cpp +++ b/third_party/WebKit/Source/modules/webaudio/AudioBuffer.cpp
@@ -185,33 +185,34 @@ } } -DOMFloat32Array* AudioBuffer::getChannelData(unsigned channel_index, - ExceptionState& exception_state) { +NotShared<DOMFloat32Array> AudioBuffer::getChannelData( + unsigned channel_index, + ExceptionState& exception_state) { if (channel_index >= channels_.size()) { exception_state.ThrowDOMException( kIndexSizeError, "channel index (" + String::Number(channel_index) + ") exceeds number of channels (" + String::Number(channels_.size()) + ")"); - return nullptr; + return NotShared<DOMFloat32Array>(nullptr); } return getChannelData(channel_index); } -DOMFloat32Array* AudioBuffer::getChannelData(unsigned channel_index) { +NotShared<DOMFloat32Array> AudioBuffer::getChannelData(unsigned channel_index) { if (channel_index >= channels_.size()) - return nullptr; + return NotShared<DOMFloat32Array>(nullptr); - return channels_[channel_index].Get(); + return NotShared<DOMFloat32Array>(channels_[channel_index].Get()); } -void AudioBuffer::copyFromChannel(DOMFloat32Array* destination, +void AudioBuffer::copyFromChannel(NotShared<DOMFloat32Array> destination, long channel_number, ExceptionState& exception_state) { return copyFromChannel(destination, channel_number, 0, exception_state); } -void AudioBuffer::copyFromChannel(DOMFloat32Array* destination, +void AudioBuffer::copyFromChannel(NotShared<DOMFloat32Array> destination, long channel_number, unsigned long start_in_channel, ExceptionState& exception_state) { @@ -223,6 +224,7 @@ ExceptionMessages::kInclusiveBound, static_cast<long>(channels_.size() - 1), ExceptionMessages::kInclusiveBound)); + return; } @@ -240,10 +242,10 @@ } unsigned count = channel_data->length() - start_in_channel; - count = std::min(destination->length(), count); + count = std::min(destination.View()->length(), count); const float* src = channel_data->Data(); - float* dst = destination->Data(); + float* dst = destination.View()->Data(); DCHECK(src); DCHECK(dst); @@ -251,13 +253,13 @@ memcpy(dst, src + start_in_channel, count * sizeof(*src)); } -void AudioBuffer::copyToChannel(DOMFloat32Array* source, +void AudioBuffer::copyToChannel(NotShared<DOMFloat32Array> source, long channel_number, ExceptionState& exception_state) { return copyToChannel(source, channel_number, 0, exception_state); } -void AudioBuffer::copyToChannel(DOMFloat32Array* source, +void AudioBuffer::copyToChannel(NotShared<DOMFloat32Array> source, long channel_number, unsigned long start_in_channel, ExceptionState& exception_state) { @@ -286,9 +288,9 @@ } unsigned count = channel_data->length() - start_in_channel; - count = std::min(source->length(), count); + count = std::min(source.View()->length(), count); - const float* src = source->Data(); + const float* src = source.View()->Data(); float* dst = channel_data->Data(); DCHECK(src); @@ -299,8 +301,8 @@ void AudioBuffer::Zero() { for (unsigned i = 0; i < channels_.size(); ++i) { - if (DOMFloat32Array* array = getChannelData(i)) { - float* data = array->Data(); + if (NotShared<DOMFloat32Array> array = getChannelData(i)) { + float* data = array.View()->Data(); memset(data, 0, length() * sizeof(*data)); } }
diff --git a/third_party/WebKit/Source/modules/webaudio/AudioBuffer.h b/third_party/WebKit/Source/modules/webaudio/AudioBuffer.h index 782b1b9..f42219520 100644 --- a/third_party/WebKit/Source/modules/webaudio/AudioBuffer.h +++ b/third_party/WebKit/Source/modules/webaudio/AudioBuffer.h
@@ -31,6 +31,7 @@ #include "bindings/core/v8/ScriptWrappable.h" #include "core/dom/DOMTypedArray.h" +#include "core/dom/NotShared.h" #include "modules/ModulesExport.h" #include "platform/wtf/PassRefPtr.h" #include "platform/wtf/RefPtr.h" @@ -74,15 +75,20 @@ // Channel data access unsigned numberOfChannels() const { return channels_.size(); } - DOMFloat32Array* getChannelData(unsigned channel_index, ExceptionState&); - DOMFloat32Array* getChannelData(unsigned channel_index); - void copyFromChannel(DOMFloat32Array*, long channel_number, ExceptionState&); - void copyFromChannel(DOMFloat32Array*, + NotShared<DOMFloat32Array> getChannelData(unsigned channel_index, + ExceptionState&); + NotShared<DOMFloat32Array> getChannelData(unsigned channel_index); + void copyFromChannel(NotShared<DOMFloat32Array>, + long channel_number, + ExceptionState&); + void copyFromChannel(NotShared<DOMFloat32Array>, long channel_number, unsigned long start_in_channel, ExceptionState&); - void copyToChannel(DOMFloat32Array*, long channel_number, ExceptionState&); - void copyToChannel(DOMFloat32Array*, + void copyToChannel(NotShared<DOMFloat32Array>, + long channel_number, + ExceptionState&); + void copyToChannel(NotShared<DOMFloat32Array>, long channel_number, unsigned long start_in_channel, ExceptionState&);
diff --git a/third_party/WebKit/Source/modules/webaudio/AudioBufferSourceNode.cpp b/third_party/WebKit/Source/modules/webaudio/AudioBufferSourceNode.cpp index 771a7a2..f7316e1 100644 --- a/third_party/WebKit/Source/modules/webaudio/AudioBufferSourceNode.cpp +++ b/third_party/WebKit/Source/modules/webaudio/AudioBufferSourceNode.cpp
@@ -425,7 +425,7 @@ destination_channels_ = WrapArrayUnique(new float*[number_of_channels]); for (unsigned i = 0; i < number_of_channels; ++i) - source_channels_[i] = buffer->getChannelData(i)->Data(); + source_channels_[i] = buffer->getChannelData(i).View()->Data(); // If this is a grain (as set by a previous call to start()), validate the // grain parameters now since it wasn't validated when start was called
diff --git a/third_party/WebKit/Source/modules/webaudio/AudioParam.cpp b/third_party/WebKit/Source/modules/webaudio/AudioParam.cpp index 85805c51..b3b5be2 100644 --- a/third_party/WebKit/Source/modules/webaudio/AudioParam.cpp +++ b/third_party/WebKit/Source/modules/webaudio/AudioParam.cpp
@@ -469,17 +469,17 @@ return this; } -AudioParam* AudioParam::setValueCurveAtTime(DOMFloat32Array* curve, +AudioParam* AudioParam::setValueCurveAtTime(NotShared<DOMFloat32Array> curve, double time, double duration, ExceptionState& exception_state) { - float* curve_data = curve->Data(); + float* curve_data = curve.View()->Data(); float min = minValue(); float max = maxValue(); // First, find any non-finite value in the curve and throw an exception if // there are any. - for (unsigned k = 0; k < curve->length(); ++k) { + for (unsigned k = 0; k < curve.View()->length(); ++k) { float value = curve_data[k]; if (!std::isfinite(value)) { @@ -494,7 +494,7 @@ // Second, find the first value in the curve (if any) that is outside the // nominal range. It's probably not necessary to produce a warning on every // value outside the nominal range. - for (unsigned k = 0; k < curve->length(); ++k) { + for (unsigned k = 0; k < curve.View()->length(); ++k) { float value = curve_data[k]; if (value < min || value > max) { @@ -503,7 +503,7 @@ } } - Handler().Timeline().SetValueCurveAtTime(curve, time, duration, + Handler().Timeline().SetValueCurveAtTime(curve.View(), time, duration, exception_state); // We could update the histogram with every value in the curve, due to
diff --git a/third_party/WebKit/Source/modules/webaudio/AudioParam.h b/third_party/WebKit/Source/modules/webaudio/AudioParam.h index c393187b..858e12f0 100644 --- a/third_party/WebKit/Source/modules/webaudio/AudioParam.h +++ b/third_party/WebKit/Source/modules/webaudio/AudioParam.h
@@ -32,6 +32,7 @@ #include <sys/types.h> #include "bindings/core/v8/ScriptWrappable.h" #include "core/dom/DOMTypedArray.h" +#include "core/dom/NotShared.h" #include "modules/webaudio/AudioParamTimeline.h" #include "modules/webaudio/AudioSummingJunction.h" #include "modules/webaudio/BaseAudioContext.h" @@ -246,7 +247,7 @@ double time, double time_constant, ExceptionState&); - AudioParam* setValueCurveAtTime(DOMFloat32Array* curve, + AudioParam* setValueCurveAtTime(NotShared<DOMFloat32Array> curve, double time, double duration, ExceptionState&);
diff --git a/third_party/WebKit/Source/modules/webaudio/AudioWorkletGlobalScopeTest.cpp b/third_party/WebKit/Source/modules/webaudio/AudioWorkletGlobalScopeTest.cpp index 0f25c173..6e4e965 100644 --- a/third_party/WebKit/Source/modules/webaudio/AudioWorkletGlobalScopeTest.cpp +++ b/third_party/WebKit/Source/modules/webaudio/AudioWorkletGlobalScopeTest.cpp
@@ -218,10 +218,12 @@ AudioBuffer::Create(1, kRenderQuantumFrames, kTestingSampleRate); AudioBuffer* output_buffer = AudioBuffer::Create(1, kRenderQuantumFrames, kTestingSampleRate); - DOMFloat32Array* input_channel_data = input_buffer->getChannelData(0); + DOMFloat32Array* input_channel_data = + input_buffer->getChannelData(0).View(); float* input_array_data = input_channel_data->Data(); EXPECT_TRUE(input_array_data); - DOMFloat32Array* output_channel_data = output_buffer->getChannelData(0); + DOMFloat32Array* output_channel_data = + output_buffer->getChannelData(0).View(); float* output_array_data = output_channel_data->Data(); EXPECT_TRUE(output_array_data);
diff --git a/third_party/WebKit/Source/modules/webaudio/BaseAudioContext.cpp b/third_party/WebKit/Source/modules/webaudio/BaseAudioContext.cpp index 71c25830..4ff9d1bf 100644 --- a/third_party/WebKit/Source/modules/webaudio/BaseAudioContext.cpp +++ b/third_party/WebKit/Source/modules/webaudio/BaseAudioContext.cpp
@@ -523,8 +523,8 @@ } PeriodicWave* BaseAudioContext::createPeriodicWave( - DOMFloat32Array* real, - DOMFloat32Array* imag, + NotShared<DOMFloat32Array> real, + NotShared<DOMFloat32Array> imag, ExceptionState& exception_state) { DCHECK(IsMainThread()); @@ -532,8 +532,8 @@ } PeriodicWave* BaseAudioContext::createPeriodicWave( - DOMFloat32Array* real, - DOMFloat32Array* imag, + NotShared<DOMFloat32Array> real, + NotShared<DOMFloat32Array> imag, const PeriodicWaveConstraints& options, ExceptionState& exception_state) { DCHECK(IsMainThread());
diff --git a/third_party/WebKit/Source/modules/webaudio/BaseAudioContext.h b/third_party/WebKit/Source/modules/webaudio/BaseAudioContext.h index 6d88f775..a4a6f4f8 100644 --- a/third_party/WebKit/Source/modules/webaudio/BaseAudioContext.h +++ b/third_party/WebKit/Source/modules/webaudio/BaseAudioContext.h
@@ -30,6 +30,7 @@ #include "bindings/core/v8/ScriptPromise.h" #include "bindings/core/v8/ScriptPromiseResolver.h" #include "core/dom/DOMTypedArray.h" +#include "core/dom/NotShared.h" #include "core/dom/SuspendableObject.h" #include "core/events/EventListener.h" #include "modules/EventTargetModules.h" @@ -220,11 +221,11 @@ ChannelMergerNode* createChannelMerger(size_t number_of_inputs, ExceptionState&); OscillatorNode* createOscillator(ExceptionState&); - PeriodicWave* createPeriodicWave(DOMFloat32Array* real, - DOMFloat32Array* imag, + PeriodicWave* createPeriodicWave(NotShared<DOMFloat32Array> real, + NotShared<DOMFloat32Array> imag, ExceptionState&); - PeriodicWave* createPeriodicWave(DOMFloat32Array* real, - DOMFloat32Array* imag, + PeriodicWave* createPeriodicWave(NotShared<DOMFloat32Array> real, + NotShared<DOMFloat32Array> imag, const PeriodicWaveConstraints&, ExceptionState&);
diff --git a/third_party/WebKit/Source/modules/webaudio/BiquadFilterNode.cpp b/third_party/WebKit/Source/modules/webaudio/BiquadFilterNode.cpp index 1deb3078..df2d501 100644 --- a/third_party/WebKit/Source/modules/webaudio/BiquadFilterNode.cpp +++ b/third_party/WebKit/Source/modules/webaudio/BiquadFilterNode.cpp
@@ -172,18 +172,22 @@ return true; } -void BiquadFilterNode::getFrequencyResponse(const DOMFloat32Array* frequency_hz, - DOMFloat32Array* mag_response, - DOMFloat32Array* phase_response) { +void BiquadFilterNode::getFrequencyResponse( + NotShared<const DOMFloat32Array> frequency_hz, + NotShared<DOMFloat32Array> mag_response, + NotShared<DOMFloat32Array> phase_response) { DCHECK(frequency_hz); DCHECK(mag_response); DCHECK(phase_response); - int n = std::min(frequency_hz->length(), - std::min(mag_response->length(), phase_response->length())); - if (n) - GetBiquadProcessor()->GetFrequencyResponse( - n, frequency_hz->Data(), mag_response->Data(), phase_response->Data()); + int n = std::min( + frequency_hz.View()->length(), + std::min(mag_response.View()->length(), phase_response.View()->length())); + if (n) { + GetBiquadProcessor()->GetFrequencyResponse(n, frequency_hz.View()->Data(), + mag_response.View()->Data(), + phase_response.View()->Data()); + } } } // namespace blink
diff --git a/third_party/WebKit/Source/modules/webaudio/BiquadFilterNode.h b/third_party/WebKit/Source/modules/webaudio/BiquadFilterNode.h index 4ca7a35..b83c5c7 100644 --- a/third_party/WebKit/Source/modules/webaudio/BiquadFilterNode.h +++ b/third_party/WebKit/Source/modules/webaudio/BiquadFilterNode.h
@@ -27,6 +27,7 @@ #define BiquadFilterNode_h #include "core/dom/DOMTypedArray.h" +#include "core/dom/NotShared.h" #include "modules/webaudio/AudioNode.h" #include "modules/webaudio/BiquadProcessor.h" @@ -70,9 +71,9 @@ // Get the magnitude and phase response of the filter at the given // set of frequencies (in Hz). The phase response is in radians. - void getFrequencyResponse(const DOMFloat32Array* frequency_hz, - DOMFloat32Array* mag_response, - DOMFloat32Array* phase_response); + void getFrequencyResponse(NotShared<const DOMFloat32Array> frequency_hz, + NotShared<DOMFloat32Array> mag_response, + NotShared<DOMFloat32Array> phase_response); private: BiquadFilterNode(BaseAudioContext&);
diff --git a/third_party/WebKit/Source/modules/webaudio/ConvolverNode.cpp b/third_party/WebKit/Source/modules/webaudio/ConvolverNode.cpp index cf4b8155..c59976b 100644 --- a/third_party/WebKit/Source/modules/webaudio/ConvolverNode.cpp +++ b/third_party/WebKit/Source/modules/webaudio/ConvolverNode.cpp
@@ -131,7 +131,7 @@ RefPtr<AudioBus> buffer_bus = AudioBus::Create(number_of_channels, buffer_length, false); for (unsigned i = 0; i < number_of_channels; ++i) - buffer_bus->SetChannelMemory(i, buffer->getChannelData(i)->Data(), + buffer_bus->SetChannelMemory(i, buffer->getChannelData(i).View()->Data(), buffer_length); buffer_bus->SetSampleRate(buffer->sampleRate());
diff --git a/third_party/WebKit/Source/modules/webaudio/IIRFilterNode.cpp b/third_party/WebKit/Source/modules/webaudio/IIRFilterNode.cpp index d2f05e9..42adea1 100644 --- a/third_party/WebKit/Source/modules/webaudio/IIRFilterNode.cpp +++ b/third_party/WebKit/Source/modules/webaudio/IIRFilterNode.cpp
@@ -126,49 +126,52 @@ static_cast<AudioBasicProcessorHandler&>(Handler()).Processor()); } -void IIRFilterNode::getFrequencyResponse(const DOMFloat32Array* frequency_hz, - DOMFloat32Array* mag_response, - DOMFloat32Array* phase_response, - ExceptionState& exception_state) { - if (!frequency_hz) { +void IIRFilterNode::getFrequencyResponse( + NotShared<const DOMFloat32Array> frequency_hz, + NotShared<DOMFloat32Array> mag_response, + NotShared<DOMFloat32Array> phase_response, + ExceptionState& exception_state) { + if (!frequency_hz.View()) { exception_state.ThrowDOMException(kNotSupportedError, "frequencyHz array cannot be null"); return; } - if (!mag_response) { + if (!mag_response.View()) { exception_state.ThrowDOMException(kNotSupportedError, "magResponse array cannot be null"); return; } - if (!phase_response) { + if (!phase_response.View()) { exception_state.ThrowDOMException(kNotSupportedError, "phaseResponse array cannot be null"); return; } - unsigned frequency_hz_length = frequency_hz->length(); + unsigned frequency_hz_length = frequency_hz.View()->length(); - if (mag_response->length() < frequency_hz_length) { + if (mag_response.View()->length() < frequency_hz_length) { exception_state.ThrowDOMException( kNotSupportedError, ExceptionMessages::IndexExceedsMinimumBound( - "magResponse length", mag_response->length(), frequency_hz_length)); + "magResponse length", mag_response.View()->length(), + frequency_hz_length)); return; } - if (phase_response->length() < frequency_hz_length) { + if (phase_response.View()->length() < frequency_hz_length) { exception_state.ThrowDOMException( - kNotSupportedError, ExceptionMessages::IndexExceedsMinimumBound( - "phaseResponse length", - phase_response->length(), frequency_hz_length)); + kNotSupportedError, + ExceptionMessages::IndexExceedsMinimumBound( + "phaseResponse length", phase_response.View()->length(), + frequency_hz_length)); return; } IirProcessor()->GetFrequencyResponse( - frequency_hz_length, frequency_hz->Data(), mag_response->Data(), - phase_response->Data()); + frequency_hz_length, frequency_hz.View()->Data(), + mag_response.View()->Data(), phase_response.View()->Data()); } } // namespace blink
diff --git a/third_party/WebKit/Source/modules/webaudio/IIRFilterNode.h b/third_party/WebKit/Source/modules/webaudio/IIRFilterNode.h index e16b8db..826bd67a 100644 --- a/third_party/WebKit/Source/modules/webaudio/IIRFilterNode.h +++ b/third_party/WebKit/Source/modules/webaudio/IIRFilterNode.h
@@ -6,6 +6,7 @@ #define IIRFilterNode_h #include "core/dom/DOMTypedArray.h" +#include "core/dom/NotShared.h" #include "modules/webaudio/AudioNode.h" #include "modules/webaudio/IIRProcessor.h" @@ -32,9 +33,9 @@ // Get the magnitude and phase response of the filter at the given // set of frequencies (in Hz). The phase response is in radians. - void getFrequencyResponse(const DOMFloat32Array* frequency_hz, - DOMFloat32Array* mag_response, - DOMFloat32Array* phase_response, + void getFrequencyResponse(NotShared<const DOMFloat32Array> frequency_hz, + NotShared<DOMFloat32Array> mag_response, + NotShared<DOMFloat32Array> phase_response, ExceptionState&); private:
diff --git a/third_party/WebKit/Source/modules/webaudio/OfflineAudioDestinationNode.cpp b/third_party/WebKit/Source/modules/webaudio/OfflineAudioDestinationNode.cpp index 9458026..50e3d5b1 100644 --- a/third_party/WebKit/Source/modules/webaudio/OfflineAudioDestinationNode.cpp +++ b/third_party/WebKit/Source/modules/webaudio/OfflineAudioDestinationNode.cpp
@@ -201,7 +201,7 @@ ++channel_index) { const float* source = render_bus_->Channel(channel_index)->Data(); float* destination = - render_target_->getChannelData(channel_index)->Data(); + render_target_->getChannelData(channel_index).View()->Data(); memcpy(destination + frames_processed_, source, sizeof(float) * frames_available_to_copy); }
diff --git a/third_party/WebKit/Source/modules/webaudio/PeriodicWave.cpp b/third_party/WebKit/Source/modules/webaudio/PeriodicWave.cpp index d1c45ca..fe93007 100644 --- a/third_party/WebKit/Source/modules/webaudio/PeriodicWave.cpp +++ b/third_party/WebKit/Source/modules/webaudio/PeriodicWave.cpp
@@ -83,14 +83,15 @@ } PeriodicWave* PeriodicWave::Create(BaseAudioContext& context, - DOMFloat32Array* real, - DOMFloat32Array* imag, + NotShared<DOMFloat32Array> real, + NotShared<DOMFloat32Array> imag, bool disable_normalization, ExceptionState& exception_state) { DCHECK(IsMainThread()); - return Create(context, real->length(), real->Data(), imag->length(), - imag->Data(), disable_normalization, exception_state); + return Create(context, real.View()->length(), real.View()->Data(), + imag.View()->length(), imag.View()->Data(), + disable_normalization, exception_state); } PeriodicWave* PeriodicWave::Create(BaseAudioContext* context,
diff --git a/third_party/WebKit/Source/modules/webaudio/PeriodicWave.h b/third_party/WebKit/Source/modules/webaudio/PeriodicWave.h index 0a3e261..1e44125 100644 --- a/third_party/WebKit/Source/modules/webaudio/PeriodicWave.h +++ b/third_party/WebKit/Source/modules/webaudio/PeriodicWave.h
@@ -32,6 +32,7 @@ #include <memory> #include "bindings/core/v8/ScriptWrappable.h" #include "core/dom/DOMTypedArray.h" +#include "core/dom/NotShared.h" #include "platform/audio/AudioArray.h" #include "platform/wtf/Forward.h" #include "platform/wtf/Vector.h" @@ -63,8 +64,8 @@ ExceptionState&); static PeriodicWave* Create(BaseAudioContext&, - DOMFloat32Array* real, - DOMFloat32Array* imag, + NotShared<DOMFloat32Array> real, + NotShared<DOMFloat32Array> imag, bool normalize, ExceptionState&);
diff --git a/third_party/WebKit/Source/modules/webaudio/ScriptProcessorNode.cpp b/third_party/WebKit/Source/modules/webaudio/ScriptProcessorNode.cpp index b2d7256..4fbd133 100644 --- a/third_party/WebKit/Source/modules/webaudio/ScriptProcessorNode.cpp +++ b/third_party/WebKit/Source/modules/webaudio/ScriptProcessorNode.cpp
@@ -174,17 +174,21 @@ for (unsigned i = 0; i < number_of_input_channels; ++i) internal_input_bus_->SetChannelMemory( - i, input_buffer->getChannelData(i)->Data() + buffer_read_write_index_, + i, + input_buffer->getChannelData(i).View()->Data() + + buffer_read_write_index_, frames_to_process); if (number_of_input_channels) internal_input_bus_->CopyFrom(*input_bus); // Copy from the output buffer to the output. - for (unsigned i = 0; i < number_of_output_channels; ++i) + for (unsigned i = 0; i < number_of_output_channels; ++i) { memcpy(output_bus->Channel(i)->MutableData(), - output_buffer->getChannelData(i)->Data() + buffer_read_write_index_, + output_buffer->getChannelData(i).View()->Data() + + buffer_read_write_index_, sizeof(float) * frames_to_process); + } // Update the buffering index. buffer_read_write_index_ =
diff --git a/third_party/WebKit/Source/modules/webaudio/WaveShaperNode.cpp b/third_party/WebKit/Source/modules/webaudio/WaveShaperNode.cpp index 8712b4b..994ef204 100644 --- a/third_party/WebKit/Source/modules/webaudio/WaveShaperNode.cpp +++ b/third_party/WebKit/Source/modules/webaudio/WaveShaperNode.cpp
@@ -92,12 +92,12 @@ GetWaveShaperProcessor()->SetCurve(curve_data, curve_length); } -void WaveShaperNode::setCurve(DOMFloat32Array* curve, +void WaveShaperNode::setCurve(NotShared<DOMFloat32Array> curve, ExceptionState& exception_state) { DCHECK(IsMainThread()); if (curve) - SetCurveImpl(curve->Data(), curve->length(), exception_state); + SetCurveImpl(curve.View()->Data(), curve.View()->length(), exception_state); else SetCurveImpl(nullptr, 0, exception_state); } @@ -109,17 +109,18 @@ SetCurveImpl(curve.Data(), curve.size(), exception_state); } -DOMFloat32Array* WaveShaperNode::curve() { +NotShared<DOMFloat32Array> WaveShaperNode::curve() { Vector<float>* curve = GetWaveShaperProcessor()->Curve(); if (!curve) - return nullptr; + return NotShared<DOMFloat32Array>(nullptr); unsigned size = curve->size(); RefPtr<WTF::Float32Array> new_curve = WTF::Float32Array::Create(size); memcpy(new_curve->Data(), curve->Data(), sizeof(float) * size); - return DOMFloat32Array::Create(new_curve.Release()); + return NotShared<DOMFloat32Array>( + DOMFloat32Array::Create(new_curve.Release())); } void WaveShaperNode::setOversample(const String& type) {
diff --git a/third_party/WebKit/Source/modules/webaudio/WaveShaperNode.h b/third_party/WebKit/Source/modules/webaudio/WaveShaperNode.h index 6fd05b2..3773781 100644 --- a/third_party/WebKit/Source/modules/webaudio/WaveShaperNode.h +++ b/third_party/WebKit/Source/modules/webaudio/WaveShaperNode.h
@@ -27,6 +27,7 @@ #define WaveShaperNode_h #include "core/dom/DOMTypedArray.h" +#include "core/dom/NotShared.h" #include "modules/webaudio/AudioNode.h" #include "modules/webaudio/WaveShaperProcessor.h" @@ -46,9 +47,9 @@ ExceptionState&); // setCurve() is called on the main thread. - void setCurve(DOMFloat32Array*, ExceptionState&); + void setCurve(NotShared<DOMFloat32Array>, ExceptionState&); void setCurve(const Vector<float>&, ExceptionState&); - DOMFloat32Array* curve(); + NotShared<DOMFloat32Array> curve(); void setOversample(const String&); String oversample() const;
diff --git a/third_party/WebKit/Source/modules/webgl/WebGL2RenderingContextBase.cpp b/third_party/WebKit/Source/modules/webgl/WebGL2RenderingContextBase.cpp index 21ee642..9a90200 100644 --- a/third_party/WebKit/Source/modules/webgl/WebGL2RenderingContextBase.cpp +++ b/third_party/WebKit/Source/modules/webgl/WebGL2RenderingContextBase.cpp
@@ -248,16 +248,17 @@ WebGLRenderingContextBase::InitializeNewContext(); } -void WebGL2RenderingContextBase::bufferData(GLenum target, - DOMArrayBufferView* src_data, - GLenum usage, - GLuint src_offset, - GLuint length) { +void WebGL2RenderingContextBase::bufferData( + GLenum target, + NotShared<DOMArrayBufferView> src_data, + GLenum usage, + GLuint src_offset, + GLuint length) { if (isContextLost()) return; void* sub_base_address = nullptr; long long sub_byte_length = 0; - if (!ValidateSubSourceAndGetData(src_data, src_offset, length, + if (!ValidateSubSourceAndGetData(src_data.View(), src_offset, length, &sub_base_address, &sub_byte_length)) { SynthesizeGLError(GL_INVALID_VALUE, "bufferData", "srcOffset + length too large"); @@ -279,21 +280,22 @@ } void WebGL2RenderingContextBase::bufferData(GLenum target, - DOMArrayBufferView* data, + NotShared<DOMArrayBufferView> data, GLenum usage) { WebGLRenderingContextBase::bufferData(target, data, usage); } -void WebGL2RenderingContextBase::bufferSubData(GLenum target, - GLintptr dst_byte_offset, - DOMArrayBufferView* src_data, - GLuint src_offset, - GLuint length) { +void WebGL2RenderingContextBase::bufferSubData( + GLenum target, + GLintptr dst_byte_offset, + NotShared<DOMArrayBufferView> src_data, + GLuint src_offset, + GLuint length) { if (isContextLost()) return; void* sub_base_address = nullptr; long long sub_byte_length = 0; - if (!ValidateSubSourceAndGetData(src_data, src_offset, length, + if (!ValidateSubSourceAndGetData(src_data.View(), src_offset, length, &sub_base_address, &sub_byte_length)) { SynthesizeGLError(GL_INVALID_VALUE, "bufferSubData", "srcOffset + length too large"); @@ -365,17 +367,18 @@ static_cast<GLintptr>(write_offset), static_cast<GLsizeiptr>(size)); } -void WebGL2RenderingContextBase::getBufferSubData(GLenum target, - long long src_byte_offset, - DOMArrayBufferView* dst_data, - GLuint dst_offset, - GLuint length) { +void WebGL2RenderingContextBase::getBufferSubData( + GLenum target, + long long src_byte_offset, + NotShared<DOMArrayBufferView> dst_data, + GLuint dst_offset, + GLuint length) { WebGLBuffer* source_buffer = nullptr; void* destination_data_ptr = nullptr; long long destination_byte_length = 0; const char* message = ValidateGetBufferSubData( - __FUNCTION__, target, src_byte_offset, dst_data, dst_offset, length, - &source_buffer, &destination_data_ptr, &destination_byte_length); + __FUNCTION__, target, src_byte_offset, dst_data.View(), dst_offset, + length, &source_buffer, &destination_data_ptr, &destination_byte_length); if (message) { // If there was a GL error, it was already synthesized in // validateGetBufferSubData, so it's not done here. @@ -749,13 +752,14 @@ ContextGL()->PixelStorei(pname, param); } -void WebGL2RenderingContextBase::readPixels(GLint x, - GLint y, - GLsizei width, - GLsizei height, - GLenum format, - GLenum type, - DOMArrayBufferView* pixels) { +void WebGL2RenderingContextBase::readPixels( + GLint x, + GLint y, + GLsizei width, + GLsizei height, + GLenum format, + GLenum type, + NotShared<DOMArrayBufferView> pixels) { if (isContextLost()) return; if (bound_pixel_pack_buffer_.Get()) { @@ -764,17 +768,18 @@ return; } - ReadPixelsHelper(x, y, width, height, format, type, pixels, 0); + ReadPixelsHelper(x, y, width, height, format, type, pixels.View(), 0); } -void WebGL2RenderingContextBase::readPixels(GLint x, - GLint y, - GLsizei width, - GLsizei height, - GLenum format, - GLenum type, - DOMArrayBufferView* pixels, - GLuint offset) { +void WebGL2RenderingContextBase::readPixels( + GLint x, + GLint y, + GLsizei width, + GLsizei height, + GLenum format, + GLenum type, + NotShared<DOMArrayBufferView> pixels, + GLuint offset) { if (isContextLost()) return; if (bound_pixel_pack_buffer_.Get()) { @@ -783,7 +788,7 @@ return; } - ReadPixelsHelper(x, y, width, height, format, type, pixels, offset); + ReadPixelsHelper(x, y, width, height, format, type, pixels.View(), offset); } void WebGL2RenderingContextBase::readPixels(GLint x, @@ -1125,15 +1130,16 @@ reinterpret_cast<const void*>(offset)); } -void WebGL2RenderingContextBase::texImage2D(GLenum target, - GLint level, - GLint internalformat, - GLsizei width, - GLsizei height, - GLint border, - GLenum format, - GLenum type, - DOMArrayBufferView* data) { +void WebGL2RenderingContextBase::texImage2D( + GLenum target, + GLint level, + GLint internalformat, + GLsizei width, + GLsizei height, + GLint border, + GLenum format, + GLenum type, + NotShared<DOMArrayBufferView> data) { if (isContextLost()) return; if (bound_pixel_unpack_buffer_) { @@ -1153,7 +1159,7 @@ GLint border, GLenum format, GLenum type, - DOMArrayBufferView* data, + NotShared<DOMArrayBufferView> data, GLuint src_offset) { if (isContextLost()) return; @@ -1162,9 +1168,9 @@ "a buffer is bound to PIXEL_UNPACK_BUFFER"); return; } - TexImageHelperDOMArrayBufferView(kTexImage2D, target, level, internalformat, - width, height, 1, border, format, type, 0, 0, - 0, data, kNullNotReachable, src_offset); + TexImageHelperDOMArrayBufferView( + kTexImage2D, target, level, internalformat, width, height, 1, border, + format, type, 0, 0, 0, data.View(), kNullNotReachable, src_offset); } void WebGL2RenderingContextBase::texImage2D(GLenum target, @@ -1368,15 +1374,16 @@ type, image_bit_map, exception_state); } -void WebGL2RenderingContextBase::texSubImage2D(GLenum target, - GLint level, - GLint xoffset, - GLint yoffset, - GLsizei width, - GLsizei height, - GLenum format, - GLenum type, - DOMArrayBufferView* pixels) { +void WebGL2RenderingContextBase::texSubImage2D( + GLenum target, + GLint level, + GLint xoffset, + GLint yoffset, + GLsizei width, + GLsizei height, + GLenum format, + GLenum type, + NotShared<DOMArrayBufferView> pixels) { if (isContextLost()) return; if (bound_pixel_unpack_buffer_) { @@ -1388,16 +1395,17 @@ width, height, format, type, pixels); } -void WebGL2RenderingContextBase::texSubImage2D(GLenum target, - GLint level, - GLint xoffset, - GLint yoffset, - GLsizei width, - GLsizei height, - GLenum format, - GLenum type, - DOMArrayBufferView* pixels, - GLuint src_offset) { +void WebGL2RenderingContextBase::texSubImage2D( + GLenum target, + GLint level, + GLint xoffset, + GLint yoffset, + GLsizei width, + GLsizei height, + GLenum format, + GLenum type, + NotShared<DOMArrayBufferView> pixels, + GLuint src_offset) { if (isContextLost()) return; if (bound_pixel_unpack_buffer_) { @@ -1405,9 +1413,9 @@ "a buffer is bound to PIXEL_UNPACK_BUFFER"); return; } - TexImageHelperDOMArrayBufferView(kTexSubImage2D, target, level, 0, width, - height, 1, 0, format, type, xoffset, yoffset, - 0, pixels, kNullNotReachable, src_offset); + TexImageHelperDOMArrayBufferView( + kTexSubImage2D, target, level, 0, width, height, 1, 0, format, type, + xoffset, yoffset, 0, pixels.View(), kNullNotReachable, src_offset); } void WebGL2RenderingContextBase::texSubImage2D(GLenum target, @@ -1648,32 +1656,34 @@ depth); } -void WebGL2RenderingContextBase::texImage3D(GLenum target, - GLint level, - GLint internalformat, - GLsizei width, - GLsizei height, - GLsizei depth, - GLint border, - GLenum format, - GLenum type, - DOMArrayBufferView* pixels) { +void WebGL2RenderingContextBase::texImage3D( + GLenum target, + GLint level, + GLint internalformat, + GLsizei width, + GLsizei height, + GLsizei depth, + GLint border, + GLenum format, + GLenum type, + NotShared<DOMArrayBufferView> pixels) { TexImageHelperDOMArrayBufferView(kTexImage3D, target, level, internalformat, width, height, depth, border, format, type, - 0, 0, 0, pixels, kNullAllowed, 0); + 0, 0, 0, pixels.View(), kNullAllowed, 0); } -void WebGL2RenderingContextBase::texImage3D(GLenum target, - GLint level, - GLint internalformat, - GLsizei width, - GLsizei height, - GLsizei depth, - GLint border, - GLenum format, - GLenum type, - DOMArrayBufferView* pixels, - GLuint src_offset) { +void WebGL2RenderingContextBase::texImage3D( + GLenum target, + GLint level, + GLint internalformat, + GLsizei width, + GLsizei height, + GLsizei depth, + GLint border, + GLenum format, + GLenum type, + NotShared<DOMArrayBufferView> pixels, + GLuint src_offset) { if (isContextLost()) return; if (bound_pixel_unpack_buffer_) { @@ -1683,7 +1693,7 @@ } TexImageHelperDOMArrayBufferView( kTexImage3D, target, level, internalformat, width, height, depth, border, - format, type, 0, 0, 0, pixels, kNullNotReachable, src_offset); + format, type, 0, 0, 0, pixels.View(), kNullNotReachable, src_offset); } void WebGL2RenderingContextBase::texImage3D(GLenum target, @@ -1834,18 +1844,19 @@ unpack_image_height_, exception_state); } -void WebGL2RenderingContextBase::texSubImage3D(GLenum target, - GLint level, - GLint xoffset, - GLint yoffset, - GLint zoffset, - GLsizei width, - GLsizei height, - GLsizei depth, - GLenum format, - GLenum type, - DOMArrayBufferView* pixels, - GLuint src_offset) { +void WebGL2RenderingContextBase::texSubImage3D( + GLenum target, + GLint level, + GLint xoffset, + GLint yoffset, + GLint zoffset, + GLsizei width, + GLsizei height, + GLsizei depth, + GLenum format, + GLenum type, + NotShared<DOMArrayBufferView> pixels, + GLuint src_offset) { if (isContextLost()) return; if (bound_pixel_unpack_buffer_) { @@ -1855,7 +1866,7 @@ } TexImageHelperDOMArrayBufferView( kTexSubImage3D, target, level, 0, width, height, depth, 0, format, type, - xoffset, yoffset, zoffset, pixels, kNullNotReachable, src_offset); + xoffset, yoffset, zoffset, pixels.View(), kNullNotReachable, src_offset); } void WebGL2RenderingContextBase::texSubImage3D(GLenum target, @@ -2050,7 +2061,7 @@ GLsizei width, GLsizei height, GLint border, - DOMArrayBufferView* data) { + NotShared<DOMArrayBufferView> data) { if (isContextLost()) return; if (bound_pixel_unpack_buffer_) { @@ -2069,7 +2080,7 @@ GLsizei width, GLsizei height, GLint border, - DOMArrayBufferView* data, + NotShared<DOMArrayBufferView> data, GLuint src_offset, GLuint src_length_override) { if (isContextLost()) @@ -2083,21 +2094,21 @@ return; if (!ValidateCompressedTexFormat("compressedTexImage2D", internalformat)) return; - if (src_offset > data->byteLength()) { + if (src_offset > data.View()->byteLength()) { SynthesizeGLError(GL_INVALID_VALUE, "compressedTexImage2D", "srcOffset is out of range"); return; } if (src_length_override == 0) { - src_length_override = data->byteLength() - src_offset; - } else if (src_length_override > data->byteLength() - src_offset) { + src_length_override = data.View()->byteLength() - src_offset; + } else if (src_length_override > data.View()->byteLength() - src_offset) { SynthesizeGLError(GL_INVALID_VALUE, "compressedTexImage2D", "srcLengthOverride is out of range"); return; } ContextGL()->CompressedTexImage2D( target, level, internalformat, width, height, border, src_length_override, - static_cast<uint8_t*>(data->BaseAddress()) + src_offset); + static_cast<uint8_t*>(data.View()->BaseAddress()) + src_offset); } void WebGL2RenderingContextBase::compressedTexImage2D(GLenum target, @@ -2128,7 +2139,7 @@ GLsizei width, GLsizei height, GLenum format, - DOMArrayBufferView* data) { + NotShared<DOMArrayBufferView> data) { if (isContextLost()) return; if (bound_pixel_unpack_buffer_) { @@ -2148,7 +2159,7 @@ GLsizei width, GLsizei height, GLenum format, - DOMArrayBufferView* data, + NotShared<DOMArrayBufferView> data, GLuint src_offset, GLuint src_length_override) { if (isContextLost()) @@ -2162,14 +2173,14 @@ return; if (!ValidateCompressedTexFormat("compressedTexSubImage2D", format)) return; - if (src_offset > data->byteLength()) { + if (src_offset > data.View()->byteLength()) { SynthesizeGLError(GL_INVALID_VALUE, "compressedTexSubImage2D", "srcOffset is out of range"); return; } if (src_length_override == 0) { - src_length_override = data->byteLength() - src_offset; - } else if (src_length_override > data->byteLength() - src_offset) { + src_length_override = data.View()->byteLength() - src_offset; + } else if (src_length_override > data.View()->byteLength() - src_offset) { SynthesizeGLError(GL_INVALID_VALUE, "compressedTexImage2D", "srcLengthOverride is out of range"); return; @@ -2177,7 +2188,7 @@ ContextGL()->CompressedTexSubImage2D( target, level, xoffset, yoffset, width, height, format, src_length_override, - static_cast<uint8_t*>(data->BaseAddress()) + src_offset); + static_cast<uint8_t*>(data.View()->BaseAddress()) + src_offset); } void WebGL2RenderingContextBase::compressedTexSubImage2D(GLenum target, @@ -2209,7 +2220,7 @@ GLsizei height, GLsizei depth, GLint border, - DOMArrayBufferView* data, + NotShared<DOMArrayBufferView> data, GLuint src_offset, GLuint src_length_override) { if (isContextLost()) @@ -2223,14 +2234,14 @@ return; if (!ValidateCompressedTexFormat("compressedTexImage3D", internalformat)) return; - if (src_offset > data->byteLength()) { + if (src_offset > data.View()->byteLength()) { SynthesizeGLError(GL_INVALID_VALUE, "compressedTexImage3D", "srcOffset is out of range"); return; } if (src_length_override == 0) { - src_length_override = data->byteLength() - src_offset; - } else if (src_length_override > data->byteLength() - src_offset) { + src_length_override = data.View()->byteLength() - src_offset; + } else if (src_length_override > data.View()->byteLength() - src_offset) { SynthesizeGLError(GL_INVALID_VALUE, "compressedTexImage3D", "srcLengthOverride is out of range"); return; @@ -2238,7 +2249,7 @@ ContextGL()->CompressedTexImage3D( target, level, internalformat, width, height, depth, border, src_length_override, - static_cast<uint8_t*>(data->BaseAddress()) + src_offset); + static_cast<uint8_t*>(data.View()->BaseAddress()) + src_offset); } void WebGL2RenderingContextBase::compressedTexImage3D(GLenum target, @@ -2272,7 +2283,7 @@ GLsizei height, GLsizei depth, GLenum format, - DOMArrayBufferView* data, + NotShared<DOMArrayBufferView> data, GLuint src_offset, GLuint src_length_override) { if (isContextLost()) @@ -2286,14 +2297,14 @@ return; if (!ValidateCompressedTexFormat("compressedTexSubImage3D", format)) return; - if (src_offset > data->byteLength()) { + if (src_offset > data.View()->byteLength()) { SynthesizeGLError(GL_INVALID_VALUE, "compressedTexSubImage3D", "srcOffset is out of range"); return; } if (src_length_override == 0) { - src_length_override = data->byteLength() - src_offset; - } else if (src_length_override > data->byteLength() - src_offset) { + src_length_override = data.View()->byteLength() - src_offset; + } else if (src_length_override > data.View()->byteLength() - src_offset) { SynthesizeGLError(GL_INVALID_VALUE, "compressedTexSubImage3D", "srcLengthOverride is out of range"); return; @@ -2301,7 +2312,7 @@ ContextGL()->CompressedTexSubImage3D( target, level, xoffset, yoffset, zoffset, width, height, depth, format, src_length_override, - static_cast<uint8_t*>(data->BaseAddress()) + src_offset); + static_cast<uint8_t*>(data.View()->BaseAddress()) + src_offset); } void WebGL2RenderingContextBase::compressedTexSubImage3D(GLenum target, @@ -2784,17 +2795,17 @@ void WebGL2RenderingContextBase::uniformMatrix2fv( const WebGLUniformLocation* location, GLboolean transpose, - DOMFloat32Array* v, + NotShared<DOMFloat32Array> v, GLuint src_offset, GLuint src_length) { if (isContextLost() || !ValidateUniformMatrixParameters("uniformMatrix2fv", location, transpose, - v, 4, src_offset, src_length)) + v.View(), 4, src_offset, src_length)) return; ContextGL()->UniformMatrix2fv( location->Location(), - (src_length ? src_length : (v->length() - src_offset)) >> 2, transpose, - v->Data() + src_offset); + (src_length ? src_length : (v.View()->length() - src_offset)) >> 2, + transpose, v.View()->Data() + src_offset); } void WebGL2RenderingContextBase::uniformMatrix2fv( @@ -2816,17 +2827,17 @@ void WebGL2RenderingContextBase::uniformMatrix3fv( const WebGLUniformLocation* location, GLboolean transpose, - DOMFloat32Array* v, + NotShared<DOMFloat32Array> v, GLuint src_offset, GLuint src_length) { if (isContextLost() || !ValidateUniformMatrixParameters("uniformMatrix3fv", location, transpose, - v, 9, src_offset, src_length)) + v.View(), 9, src_offset, src_length)) return; ContextGL()->UniformMatrix3fv( location->Location(), - (src_length ? src_length : (v->length() - src_offset)) / 9, transpose, - v->Data() + src_offset); + (src_length ? src_length : (v.View()->length() - src_offset)) / 9, + transpose, v.View()->Data() + src_offset); } void WebGL2RenderingContextBase::uniformMatrix3fv( @@ -2848,17 +2859,17 @@ void WebGL2RenderingContextBase::uniformMatrix4fv( const WebGLUniformLocation* location, GLboolean transpose, - DOMFloat32Array* v, + NotShared<DOMFloat32Array> v, GLuint src_offset, GLuint src_length) { if (isContextLost() || !ValidateUniformMatrixParameters("uniformMatrix4fv", location, transpose, - v, 16, src_offset, src_length)) + v.View(), 16, src_offset, src_length)) return; ContextGL()->UniformMatrix4fv( location->Location(), - (src_length ? src_length : (v->length() - src_offset)) >> 4, transpose, - v->Data() + src_offset); + (src_length ? src_length : (v.View()->length() - src_offset)) >> 4, + transpose, v.View()->Data() + src_offset); } void WebGL2RenderingContextBase::uniformMatrix4fv( @@ -2880,17 +2891,17 @@ void WebGL2RenderingContextBase::uniformMatrix2x3fv( const WebGLUniformLocation* location, GLboolean transpose, - DOMFloat32Array* value, + NotShared<DOMFloat32Array> value, GLuint src_offset, GLuint src_length) { if (isContextLost() || !ValidateUniformMatrixParameters( - "uniformMatrix2x3fv", location, transpose, value, - 6, src_offset, src_length)) + "uniformMatrix2x3fv", location, transpose, + value.View(), 6, src_offset, src_length)) return; ContextGL()->UniformMatrix2x3fv( location->Location(), - (src_length ? src_length : (value->length() - src_offset)) / 6, transpose, - value->Data() + src_offset); + (src_length ? src_length : (value.View()->length() - src_offset)) / 6, + transpose, value.View()->Data() + src_offset); } void WebGL2RenderingContextBase::uniformMatrix2x3fv( @@ -2913,17 +2924,17 @@ void WebGL2RenderingContextBase::uniformMatrix3x2fv( const WebGLUniformLocation* location, GLboolean transpose, - DOMFloat32Array* value, + NotShared<DOMFloat32Array> value, GLuint src_offset, GLuint src_length) { if (isContextLost() || !ValidateUniformMatrixParameters( - "uniformMatrix3x2fv", location, transpose, value, - 6, src_offset, src_length)) + "uniformMatrix3x2fv", location, transpose, + value.View(), 6, src_offset, src_length)) return; ContextGL()->UniformMatrix3x2fv( location->Location(), - (src_length ? src_length : (value->length() - src_offset)) / 6, transpose, - value->Data() + src_offset); + (src_length ? src_length : (value.View()->length() - src_offset)) / 6, + transpose, value.View()->Data() + src_offset); } void WebGL2RenderingContextBase::uniformMatrix3x2fv( @@ -2946,17 +2957,17 @@ void WebGL2RenderingContextBase::uniformMatrix2x4fv( const WebGLUniformLocation* location, GLboolean transpose, - DOMFloat32Array* value, + NotShared<DOMFloat32Array> value, GLuint src_offset, GLuint src_length) { if (isContextLost() || !ValidateUniformMatrixParameters( - "uniformMatrix2x4fv", location, transpose, value, - 8, src_offset, src_length)) + "uniformMatrix2x4fv", location, transpose, + value.View(), 8, src_offset, src_length)) return; ContextGL()->UniformMatrix2x4fv( location->Location(), - (src_length ? src_length : (value->length() - src_offset)) >> 3, - transpose, value->Data() + src_offset); + (src_length ? src_length : (value.View()->length() - src_offset)) >> 3, + transpose, value.View()->Data() + src_offset); } void WebGL2RenderingContextBase::uniformMatrix2x4fv( @@ -2979,17 +2990,17 @@ void WebGL2RenderingContextBase::uniformMatrix4x2fv( const WebGLUniformLocation* location, GLboolean transpose, - DOMFloat32Array* value, + NotShared<DOMFloat32Array> value, GLuint src_offset, GLuint src_length) { if (isContextLost() || !ValidateUniformMatrixParameters( - "uniformMatrix4x2fv", location, transpose, value, - 8, src_offset, src_length)) + "uniformMatrix4x2fv", location, transpose, + value.View(), 8, src_offset, src_length)) return; ContextGL()->UniformMatrix4x2fv( location->Location(), - (src_length ? src_length : (value->length() - src_offset)) >> 3, - transpose, value->Data() + src_offset); + (src_length ? src_length : (value.View()->length() - src_offset)) >> 3, + transpose, value.View()->Data() + src_offset); } void WebGL2RenderingContextBase::uniformMatrix4x2fv( @@ -3012,17 +3023,17 @@ void WebGL2RenderingContextBase::uniformMatrix3x4fv( const WebGLUniformLocation* location, GLboolean transpose, - DOMFloat32Array* value, + NotShared<DOMFloat32Array> value, GLuint src_offset, GLuint src_length) { if (isContextLost() || !ValidateUniformMatrixParameters( - "uniformMatrix3x4fv", location, transpose, value, - 12, src_offset, src_length)) + "uniformMatrix3x4fv", location, transpose, + value.View(), 12, src_offset, src_length)) return; ContextGL()->UniformMatrix3x4fv( location->Location(), - (src_length ? src_length : (value->length() - src_offset)) / 12, - transpose, value->Data() + src_offset); + (src_length ? src_length : (value.View()->length() - src_offset)) / 12, + transpose, value.View()->Data() + src_offset); } void WebGL2RenderingContextBase::uniformMatrix3x4fv( @@ -3045,17 +3056,17 @@ void WebGL2RenderingContextBase::uniformMatrix4x3fv( const WebGLUniformLocation* location, GLboolean transpose, - DOMFloat32Array* value, + NotShared<DOMFloat32Array> value, GLuint src_offset, GLuint src_length) { if (isContextLost() || !ValidateUniformMatrixParameters( - "uniformMatrix4x3fv", location, transpose, value, - 12, src_offset, src_length)) + "uniformMatrix4x3fv", location, transpose, + value.View(), 12, src_offset, src_length)) return; ContextGL()->UniformMatrix4x3fv( location->Location(), - (src_length ? src_length : (value->length() - src_offset)) / 12, - transpose, value->Data() + src_offset); + (src_length ? src_length : (value.View()->length() - src_offset)) / 12, + transpose, value.View()->Data() + src_offset); } void WebGL2RenderingContextBase::uniformMatrix4x3fv( @@ -3174,7 +3185,7 @@ void WebGL2RenderingContextBase::uniformMatrix2fv( const WebGLUniformLocation* location, GLboolean transpose, - DOMFloat32Array* v) { + NotShared<DOMFloat32Array> v) { WebGLRenderingContextBase::uniformMatrix2fv(location, transpose, v); } @@ -3188,7 +3199,7 @@ void WebGL2RenderingContextBase::uniformMatrix3fv( const WebGLUniformLocation* location, GLboolean transpose, - DOMFloat32Array* v) { + NotShared<DOMFloat32Array> v) { WebGLRenderingContextBase::uniformMatrix3fv(location, transpose, v); } @@ -3202,7 +3213,7 @@ void WebGL2RenderingContextBase::uniformMatrix4fv( const WebGLUniformLocation* location, GLboolean transpose, - DOMFloat32Array* v) { + NotShared<DOMFloat32Array> v) { WebGLRenderingContextBase::uniformMatrix4fv(location, transpose, v); } @@ -3224,15 +3235,16 @@ SetVertexAttribType(index, kInt32ArrayType); } -void WebGL2RenderingContextBase::vertexAttribI4iv(GLuint index, - const DOMInt32Array* v) { +void WebGL2RenderingContextBase::vertexAttribI4iv( + GLuint index, + NotShared<const DOMInt32Array> v) { if (isContextLost()) return; - if (!v || v->length() < 4) { + if (!v.View() || v.View()->length() < 4) { SynthesizeGLError(GL_INVALID_VALUE, "vertexAttribI4iv", "invalid array"); return; } - ContextGL()->VertexAttribI4iv(index, v->Data()); + ContextGL()->VertexAttribI4iv(index, v.View()->Data()); SetVertexAttribType(index, kInt32ArrayType); } @@ -3259,15 +3271,16 @@ SetVertexAttribType(index, kUint32ArrayType); } -void WebGL2RenderingContextBase::vertexAttribI4uiv(GLuint index, - const DOMUint32Array* v) { +void WebGL2RenderingContextBase::vertexAttribI4uiv( + GLuint index, + NotShared<const DOMUint32Array> v) { if (isContextLost()) return; - if (!v || v->length() < 4) { + if (!v.View() || v.View()->length() < 4) { SynthesizeGLError(GL_INVALID_VALUE, "vertexAttribI4uiv", "invalid array"); return; } - ContextGL()->VertexAttribI4uiv(index, v->Data()); + ContextGL()->VertexAttribI4uiv(index, v.View()->Data()); SetVertexAttribType(index, kUint32ArrayType); } @@ -3485,12 +3498,12 @@ void WebGL2RenderingContextBase::clearBufferiv(GLenum buffer, GLint drawbuffer, - DOMInt32Array* value) { + NotShared<DOMInt32Array> value) { if (isContextLost() || - !ValidateClearBuffer("clearBufferiv", buffer, value->length())) + !ValidateClearBuffer("clearBufferiv", buffer, value.View()->length())) return; - ContextGL()->ClearBufferiv(buffer, drawbuffer, value->Data()); + ContextGL()->ClearBufferiv(buffer, drawbuffer, value.View()->Data()); } void WebGL2RenderingContextBase::clearBufferiv(GLenum buffer, @@ -3503,14 +3516,15 @@ ContextGL()->ClearBufferiv(buffer, drawbuffer, value.Data()); } -void WebGL2RenderingContextBase::clearBufferuiv(GLenum buffer, - GLint drawbuffer, - DOMUint32Array* value) { +void WebGL2RenderingContextBase::clearBufferuiv( + GLenum buffer, + GLint drawbuffer, + NotShared<DOMUint32Array> value) { if (isContextLost() || - !ValidateClearBuffer("clearBufferuiv", buffer, value->length())) + !ValidateClearBuffer("clearBufferuiv", buffer, value.View()->length())) return; - ContextGL()->ClearBufferuiv(buffer, drawbuffer, value->Data()); + ContextGL()->ClearBufferuiv(buffer, drawbuffer, value.View()->Data()); } void WebGL2RenderingContextBase::clearBufferuiv(GLenum buffer, @@ -3523,14 +3537,15 @@ ContextGL()->ClearBufferuiv(buffer, drawbuffer, value.Data()); } -void WebGL2RenderingContextBase::clearBufferfv(GLenum buffer, - GLint drawbuffer, - DOMFloat32Array* value) { +void WebGL2RenderingContextBase::clearBufferfv( + GLenum buffer, + GLint drawbuffer, + NotShared<DOMFloat32Array> value) { if (isContextLost() || - !ValidateClearBuffer("clearBufferfv", buffer, value->length())) + !ValidateClearBuffer("clearBufferfv", buffer, value.View()->length())) return; - ContextGL()->ClearBufferfv(buffer, drawbuffer, value->Data()); + ContextGL()->ClearBufferfv(buffer, drawbuffer, value.View()->Data()); } void WebGL2RenderingContextBase::clearBufferfv(GLenum buffer,
diff --git a/third_party/WebKit/Source/modules/webgl/WebGL2RenderingContextBase.h b/third_party/WebKit/Source/modules/webgl/WebGL2RenderingContextBase.h index 086ede6a..52b1d744 100644 --- a/third_party/WebKit/Source/modules/webgl/WebGL2RenderingContextBase.h +++ b/third_party/WebKit/Source/modules/webgl/WebGL2RenderingContextBase.h
@@ -31,21 +31,35 @@ void DestroyContext() override; /* Buffer objects */ - void bufferData(GLenum, DOMArrayBufferView*, GLenum, GLuint, GLuint); - void bufferSubData(GLenum, GLintptr, DOMArrayBufferView*, GLuint, GLuint); + void bufferData(GLenum, + NotShared<DOMArrayBufferView>, + GLenum, + GLuint, + GLuint); + void bufferSubData(GLenum, + GLintptr, + NotShared<DOMArrayBufferView>, + GLuint, + GLuint); // Have to re-declare/re-define the following buffer{Sub}Data functions from // base class. This is because the above buffer{Sub}Data() hides the name // from base class. void bufferData(GLenum target, long long size, GLenum usage); void bufferData(GLenum target, DOMArrayBuffer* data, GLenum usage); - void bufferData(GLenum target, DOMArrayBufferView* data, GLenum usage); + void bufferData(GLenum target, + NotShared<DOMArrayBufferView> data, + GLenum usage); void bufferSubData(GLenum target, long long offset, DOMArrayBuffer* data); void bufferSubData(GLenum target, long long offset, const FlexibleArrayBufferView& data); void copyBufferSubData(GLenum, GLenum, long long, long long, long long); - void getBufferSubData(GLenum, long long, DOMArrayBufferView*, GLuint, GLuint); + void getBufferSubData(GLenum, + long long, + NotShared<DOMArrayBufferView>, + GLuint, + GLuint); void RegisterGetBufferSubDataAsyncCallback( WebGLGetBufferSubDataAsyncCallback*); @@ -149,7 +163,7 @@ GLint, GLenum, GLenum, - DOMArrayBufferView*, + NotShared<DOMArrayBufferView>, GLuint); void texSubImage2D(GLenum, @@ -218,7 +232,7 @@ GLsizei, GLenum, GLenum, - DOMArrayBufferView*, + NotShared<DOMArrayBufferView>, GLuint); // Have to re-declare/re-define the following tex{Sub}Image2D functions from @@ -298,7 +312,7 @@ GLint, GLenum, GLenum, - DOMArrayBufferView*); + NotShared<DOMArrayBufferView>); void texImage3D(GLenum, GLint, GLint, @@ -308,7 +322,7 @@ GLint, GLenum, GLenum, - DOMArrayBufferView*, + NotShared<DOMArrayBufferView>, GLuint); void texImage3D(GLenum, GLint, @@ -384,7 +398,7 @@ GLsizei, GLenum, GLenum, - DOMArrayBufferView*, + NotShared<DOMArrayBufferView>, GLuint); void texSubImage3D(GLenum, GLint, @@ -465,7 +479,7 @@ GLint, GLenum, GLenum, - DOMArrayBufferView*); + NotShared<DOMArrayBufferView>); void texSubImage2D(GLenum, GLint, GLint, @@ -474,7 +488,7 @@ GLsizei, GLenum, GLenum, - DOMArrayBufferView*); + NotShared<DOMArrayBufferView>); void copyTexSubImage3D(GLenum, GLint, @@ -492,7 +506,7 @@ GLsizei width, GLsizei height, GLint border, - DOMArrayBufferView* data, + NotShared<DOMArrayBufferView> data, GLuint src_offset, GLuint src_length_override); void compressedTexSubImage2D(GLenum target, @@ -502,7 +516,7 @@ GLsizei width, GLsizei height, GLenum format, - DOMArrayBufferView* data, + NotShared<DOMArrayBufferView> data, GLuint src_offset, GLuint src_length_override); void compressedTexImage3D(GLenum, @@ -512,7 +526,7 @@ GLsizei, GLsizei, GLint, - DOMArrayBufferView*, + NotShared<DOMArrayBufferView>, GLuint, GLuint); void compressedTexSubImage3D(GLenum, @@ -524,7 +538,7 @@ GLsizei, GLsizei, GLenum, - DOMArrayBufferView*, + NotShared<DOMArrayBufferView>, GLuint, GLuint); void compressedTexImage2D(GLenum target, @@ -574,7 +588,7 @@ GLsizei width, GLsizei height, GLint border, - DOMArrayBufferView* data); + NotShared<DOMArrayBufferView> data); void compressedTexSubImage2D(GLenum target, GLint level, GLint xoffset, @@ -582,7 +596,7 @@ GLsizei width, GLsizei height, GLenum format, - DOMArrayBufferView* data); + NotShared<DOMArrayBufferView> data); /* Programs and shaders */ GLint getFragDataLocation(WebGLProgram*, const String&); @@ -678,7 +692,7 @@ GLuint); void uniformMatrix2fv(const WebGLUniformLocation*, GLboolean, - DOMFloat32Array*, + NotShared<DOMFloat32Array>, GLuint, GLuint); void uniformMatrix2fv(const WebGLUniformLocation*, @@ -688,7 +702,7 @@ GLuint); void uniformMatrix3fv(const WebGLUniformLocation*, GLboolean, - DOMFloat32Array*, + NotShared<DOMFloat32Array>, GLuint, GLuint); void uniformMatrix3fv(const WebGLUniformLocation*, @@ -698,7 +712,7 @@ GLuint); void uniformMatrix4fv(const WebGLUniformLocation*, GLboolean, - DOMFloat32Array*, + NotShared<DOMFloat32Array>, GLuint, GLuint); void uniformMatrix4fv(const WebGLUniformLocation*, @@ -708,7 +722,7 @@ GLuint); void uniformMatrix2x3fv(const WebGLUniformLocation*, GLboolean, - DOMFloat32Array*, + NotShared<DOMFloat32Array>, GLuint, GLuint); void uniformMatrix2x3fv(const WebGLUniformLocation*, @@ -718,7 +732,7 @@ GLuint); void uniformMatrix3x2fv(const WebGLUniformLocation*, GLboolean, - DOMFloat32Array*, + NotShared<DOMFloat32Array>, GLuint, GLuint); void uniformMatrix3x2fv(const WebGLUniformLocation*, @@ -728,7 +742,7 @@ GLuint); void uniformMatrix2x4fv(const WebGLUniformLocation*, GLboolean, - DOMFloat32Array*, + NotShared<DOMFloat32Array>, GLuint, GLuint); void uniformMatrix2x4fv(const WebGLUniformLocation*, @@ -738,7 +752,7 @@ GLuint); void uniformMatrix4x2fv(const WebGLUniformLocation*, GLboolean, - DOMFloat32Array*, + NotShared<DOMFloat32Array>, GLuint, GLuint); void uniformMatrix4x2fv(const WebGLUniformLocation*, @@ -748,7 +762,7 @@ GLuint); void uniformMatrix3x4fv(const WebGLUniformLocation*, GLboolean, - DOMFloat32Array*, + NotShared<DOMFloat32Array>, GLuint, GLuint); void uniformMatrix3x4fv(const WebGLUniformLocation*, @@ -758,7 +772,7 @@ GLuint); void uniformMatrix4x3fv(const WebGLUniformLocation*, GLboolean, - DOMFloat32Array*, + NotShared<DOMFloat32Array>, GLuint, GLuint); void uniformMatrix4x3fv(const WebGLUniformLocation*, @@ -787,28 +801,28 @@ void uniform4iv(const WebGLUniformLocation*, Vector<GLint>&); void uniformMatrix2fv(const WebGLUniformLocation*, GLboolean transpose, - DOMFloat32Array* value); + NotShared<DOMFloat32Array> value); void uniformMatrix2fv(const WebGLUniformLocation*, GLboolean transpose, Vector<GLfloat>& value); void uniformMatrix3fv(const WebGLUniformLocation*, GLboolean transpose, - DOMFloat32Array* value); + NotShared<DOMFloat32Array> value); void uniformMatrix3fv(const WebGLUniformLocation*, GLboolean transpose, Vector<GLfloat>& value); void uniformMatrix4fv(const WebGLUniformLocation*, GLboolean transpose, - DOMFloat32Array* value); + NotShared<DOMFloat32Array> value); void uniformMatrix4fv(const WebGLUniformLocation*, GLboolean transpose, Vector<GLfloat>& value); void vertexAttribI4i(GLuint, GLint, GLint, GLint, GLint); - void vertexAttribI4iv(GLuint, const DOMInt32Array*); + void vertexAttribI4iv(GLuint, NotShared<const DOMInt32Array>); void vertexAttribI4iv(GLuint, const Vector<GLint>&); void vertexAttribI4ui(GLuint, GLuint, GLuint, GLuint, GLuint); - void vertexAttribI4uiv(GLuint, const DOMUint32Array*); + void vertexAttribI4uiv(GLuint, NotShared<const DOMUint32Array>); void vertexAttribI4uiv(GLuint, const Vector<GLuint>&); void vertexAttribIPointer(GLuint index, GLint size, @@ -829,11 +843,11 @@ /* Multiple Render Targets */ void drawBuffers(const Vector<GLenum>&); - void clearBufferiv(GLenum, GLint, DOMInt32Array*); + void clearBufferiv(GLenum, GLint, NotShared<DOMInt32Array>); void clearBufferiv(GLenum, GLint, const Vector<GLint>&); - void clearBufferuiv(GLenum, GLint, DOMUint32Array*); + void clearBufferuiv(GLenum, GLint, NotShared<DOMUint32Array>); void clearBufferuiv(GLenum, GLint, const Vector<GLuint>&); - void clearBufferfv(GLenum, GLint, DOMFloat32Array*); + void clearBufferfv(GLenum, GLint, NotShared<DOMFloat32Array>); void clearBufferfv(GLenum, GLint, const Vector<GLfloat>&); void clearBufferfi(GLenum, GLint, GLfloat, GLint); @@ -908,7 +922,7 @@ GLsizei height, GLenum format, GLenum type, - DOMArrayBufferView* pixels, + NotShared<DOMArrayBufferView> pixels, GLuint offset); void readPixels(GLint x, GLint y, @@ -937,7 +951,7 @@ GLsizei height, GLenum format, GLenum type, - DOMArrayBufferView* pixels) override; + NotShared<DOMArrayBufferView> pixels) override; void RestoreCurrentFramebuffer() override; DECLARE_VIRTUAL_TRACE();
diff --git a/third_party/WebKit/Source/modules/webgl/WebGLGetBufferSubDataAsync.cpp b/third_party/WebKit/Source/modules/webgl/WebGLGetBufferSubDataAsync.cpp index a55e8ee..268e507d 100644 --- a/third_party/WebKit/Source/modules/webgl/WebGLGetBufferSubDataAsync.cpp +++ b/third_party/WebKit/Source/modules/webgl/WebGLGetBufferSubDataAsync.cpp
@@ -36,7 +36,7 @@ ScriptState* script_state, GLenum target, GLintptr src_byte_offset, - DOMArrayBufferView* dst_data, + NotShared<DOMArrayBufferView> dst_data, GLuint dst_offset, GLuint length) { ScriptPromiseResolver* resolver = ScriptPromiseResolver::Create(script_state); @@ -61,8 +61,8 @@ void* destination_data_ptr = nullptr; long long destination_byte_length = 0; const char* message = context->ValidateGetBufferSubData( - __FUNCTION__, target, src_byte_offset, dst_data, dst_offset, length, - &source_buffer, &destination_data_ptr, &destination_byte_length); + __FUNCTION__, target, src_byte_offset, dst_data.View(), dst_offset, + length, &source_buffer, &destination_data_ptr, &destination_byte_length); if (message) { // If there was a GL error, it was already synthesized in // validateGetBufferSubData, so it's not done here. @@ -83,7 +83,7 @@ // If the length of the copy is zero, this is a no-op. if (!destination_byte_length) { - resolver->Resolve(dst_data); + resolver->Resolve(dst_data.View()); return promise; } @@ -101,8 +101,8 @@ } auto callback_object = new WebGLGetBufferSubDataAsyncCallback( - context, resolver, mapped_data, query_id, dst_data, destination_data_ptr, - destination_byte_length); + context, resolver, mapped_data, query_id, dst_data.View(), + destination_data_ptr, destination_byte_length); context->RegisterGetBufferSubDataAsyncCallback(callback_object); auto callback = WTF::Bind(&WebGLGetBufferSubDataAsyncCallback::Resolve, WrapPersistent(callback_object));
diff --git a/third_party/WebKit/Source/modules/webgl/WebGLGetBufferSubDataAsync.h b/third_party/WebKit/Source/modules/webgl/WebGLGetBufferSubDataAsync.h index 82f738b..d0f8ec9 100644 --- a/third_party/WebKit/Source/modules/webgl/WebGLGetBufferSubDataAsync.h +++ b/third_party/WebKit/Source/modules/webgl/WebGLGetBufferSubDataAsync.h
@@ -6,6 +6,7 @@ #define WebGLGetBufferSubDataAsync_h #include "bindings/core/v8/ScriptPromise.h" +#include "core/dom/NotShared.h" #include "modules/webgl/WebGLExtension.h" namespace blink { @@ -25,7 +26,7 @@ ScriptPromise getBufferSubDataAsync(ScriptState*, GLenum target, GLintptr src_byte_offset, - DOMArrayBufferView*, + NotShared<DOMArrayBufferView>, GLuint dst_offset, GLuint length);
diff --git a/third_party/WebKit/Source/modules/webgl/WebGLRenderingContextBase.cpp b/third_party/WebKit/Source/modules/webgl/WebGLRenderingContextBase.cpp index f6091bd..38c7333 100644 --- a/third_party/WebKit/Source/modules/webgl/WebGLRenderingContextBase.cpp +++ b/third_party/WebKit/Source/modules/webgl/WebGLRenderingContextBase.cpp
@@ -1562,8 +1562,8 @@ return ImageData::Create( IntSize(width, height), - DOMUint8ClampedArray::Create(image_data_pixels, 0, - image_data_pixels->ByteLength())); + NotShared<DOMUint8ClampedArray>(DOMUint8ClampedArray::Create( + image_data_pixels, 0, image_data_pixels->ByteLength()))); } void WebGLRenderingContextBase::Reshape(int width, int height) { @@ -1903,12 +1903,13 @@ } void WebGLRenderingContextBase::bufferData(GLenum target, - DOMArrayBufferView* data, + NotShared<DOMArrayBufferView> data, GLenum usage) { if (isContextLost()) return; DCHECK(data); - BufferDataImpl(target, data->byteLength(), data->BaseAddress(), usage); + BufferDataImpl(target, data.View()->byteLength(), data.View()->BaseAddress(), + usage); } void WebGLRenderingContextBase::BufferSubDataImpl(GLenum target, @@ -2075,13 +2076,14 @@ ContextGL()->CompileShader(ObjectOrZero(shader)); } -void WebGLRenderingContextBase::compressedTexImage2D(GLenum target, - GLint level, - GLenum internalformat, - GLsizei width, - GLsizei height, - GLint border, - DOMArrayBufferView* data) { +void WebGLRenderingContextBase::compressedTexImage2D( + GLenum target, + GLint level, + GLenum internalformat, + GLsizei width, + GLsizei height, + GLint border, + NotShared<DOMArrayBufferView> data) { if (isContextLost()) return; if (!ValidateTexture2DBinding("compressedTexImage2D", target)) @@ -2089,8 +2091,8 @@ if (!ValidateCompressedTexFormat("compressedTexImage2D", internalformat)) return; ContextGL()->CompressedTexImage2D(target, level, internalformat, width, - height, border, data->byteLength(), - data->BaseAddress()); + height, border, data.View()->byteLength(), + data.View()->BaseAddress()); } void WebGLRenderingContextBase::compressedTexSubImage2D( @@ -2101,16 +2103,16 @@ GLsizei width, GLsizei height, GLenum format, - DOMArrayBufferView* data) { + NotShared<DOMArrayBufferView> data) { if (isContextLost()) return; if (!ValidateTexture2DBinding("compressedTexSubImage2D", target)) return; if (!ValidateCompressedTexFormat("compressedTexSubImage2D", format)) return; - ContextGL()->CompressedTexSubImage2D(target, level, xoffset, yoffset, width, - height, format, data->byteLength(), - data->BaseAddress()); + ContextGL()->CompressedTexSubImage2D( + target, level, xoffset, yoffset, width, height, format, + data.View()->byteLength(), data.View()->BaseAddress()); } bool WebGLRenderingContextBase::ValidateSettableTexFormat( @@ -4106,14 +4108,15 @@ return true; } -void WebGLRenderingContextBase::readPixels(GLint x, - GLint y, - GLsizei width, - GLsizei height, - GLenum format, - GLenum type, - DOMArrayBufferView* pixels) { - ReadPixelsHelper(x, y, width, height, format, type, pixels, 0); +void WebGLRenderingContextBase::readPixels( + GLint x, + GLint y, + GLsizei width, + GLsizei height, + GLenum format, + GLenum type, + NotShared<DOMArrayBufferView> pixels) { + ReadPixelsHelper(x, y, width, height, format, type, pixels.View(), 0); } void WebGLRenderingContextBase::ReadPixelsHelper(GLint x, @@ -4720,18 +4723,19 @@ format, type, data); } -void WebGLRenderingContextBase::texImage2D(GLenum target, - GLint level, - GLint internalformat, - GLsizei width, - GLsizei height, - GLint border, - GLenum format, - GLenum type, - DOMArrayBufferView* pixels) { +void WebGLRenderingContextBase::texImage2D( + GLenum target, + GLint level, + GLint internalformat, + GLsizei width, + GLsizei height, + GLint border, + GLenum format, + GLenum type, + NotShared<DOMArrayBufferView> pixels) { TexImageHelperDOMArrayBufferView(kTexImage2D, target, level, internalformat, width, height, 1, border, format, type, 0, 0, - 0, pixels, kNullAllowed, 0); + 0, pixels.View(), kNullAllowed, 0); } void WebGLRenderingContextBase::TexImageHelperImageData( @@ -5554,18 +5558,19 @@ TexParameter(target, pname, 0, param, false); } -void WebGLRenderingContextBase::texSubImage2D(GLenum target, - GLint level, - GLint xoffset, - GLint yoffset, - GLsizei width, - GLsizei height, - GLenum format, - GLenum type, - DOMArrayBufferView* pixels) { +void WebGLRenderingContextBase::texSubImage2D( + GLenum target, + GLint level, + GLint xoffset, + GLint yoffset, + GLsizei width, + GLsizei height, + GLenum format, + GLenum type, + NotShared<DOMArrayBufferView> pixels) { TexImageHelperDOMArrayBufferView(kTexSubImage2D, target, level, 0, width, height, 1, 0, format, type, xoffset, yoffset, - 0, pixels, kNullNotAllowed, 0); + 0, pixels.View(), kNullNotAllowed, 0); } void WebGLRenderingContextBase::texSubImage2D(GLenum target, @@ -5919,13 +5924,13 @@ void WebGLRenderingContextBase::uniformMatrix2fv( const WebGLUniformLocation* location, GLboolean transpose, - DOMFloat32Array* v) { + NotShared<DOMFloat32Array> v) { if (isContextLost() || !ValidateUniformMatrixParameters("uniformMatrix2fv", location, transpose, - v, 4, 0, v->length())) + v.View(), 4, 0, v.View()->length())) return; - ContextGL()->UniformMatrix2fv(location->Location(), v->length() >> 2, - transpose, v->Data()); + ContextGL()->UniformMatrix2fv(location->Location(), v.View()->length() >> 2, + transpose, v.View()->Data()); } void WebGLRenderingContextBase::uniformMatrix2fv( @@ -5943,13 +5948,13 @@ void WebGLRenderingContextBase::uniformMatrix3fv( const WebGLUniformLocation* location, GLboolean transpose, - DOMFloat32Array* v) { + NotShared<DOMFloat32Array> v) { if (isContextLost() || !ValidateUniformMatrixParameters("uniformMatrix3fv", location, transpose, - v, 9, 0, v->length())) + v.View(), 9, 0, v.View()->length())) return; - ContextGL()->UniformMatrix3fv(location->Location(), v->length() / 9, - transpose, v->Data()); + ContextGL()->UniformMatrix3fv(location->Location(), v.View()->length() / 9, + transpose, v.View()->Data()); } void WebGLRenderingContextBase::uniformMatrix3fv( @@ -5967,13 +5972,13 @@ void WebGLRenderingContextBase::uniformMatrix4fv( const WebGLUniformLocation* location, GLboolean transpose, - DOMFloat32Array* v) { + NotShared<DOMFloat32Array> v) { if (isContextLost() || !ValidateUniformMatrixParameters("uniformMatrix4fv", location, transpose, - v, 16, 0, v->length())) + v.View(), 16, 0, v.View()->length())) return; - ContextGL()->UniformMatrix4fv(location->Location(), v->length() >> 4, - transpose, v->Data()); + ContextGL()->UniformMatrix4fv(location->Location(), v.View()->length() >> 4, + transpose, v.View()->Data()); } void WebGLRenderingContextBase::uniformMatrix4fv( @@ -6029,15 +6034,16 @@ SetVertexAttribType(index, kFloat32ArrayType); } -void WebGLRenderingContextBase::vertexAttrib1fv(GLuint index, - const DOMFloat32Array* v) { +void WebGLRenderingContextBase::vertexAttrib1fv( + GLuint index, + NotShared<const DOMFloat32Array> v) { if (isContextLost()) return; - if (!v || v->length() < 1) { + if (!v.View() || v.View()->length() < 1) { SynthesizeGLError(GL_INVALID_VALUE, "vertexAttrib1fv", "invalid array"); return; } - ContextGL()->VertexAttrib1fv(index, v->Data()); + ContextGL()->VertexAttrib1fv(index, v.View()->Data()); SetVertexAttribType(index, kFloat32ArrayType); } @@ -6062,15 +6068,16 @@ SetVertexAttribType(index, kFloat32ArrayType); } -void WebGLRenderingContextBase::vertexAttrib2fv(GLuint index, - const DOMFloat32Array* v) { +void WebGLRenderingContextBase::vertexAttrib2fv( + GLuint index, + NotShared<const DOMFloat32Array> v) { if (isContextLost()) return; - if (!v || v->length() < 2) { + if (!v.View() || v.View()->length() < 2) { SynthesizeGLError(GL_INVALID_VALUE, "vertexAttrib2fv", "invalid array"); return; } - ContextGL()->VertexAttrib2fv(index, v->Data()); + ContextGL()->VertexAttrib2fv(index, v.View()->Data()); SetVertexAttribType(index, kFloat32ArrayType); } @@ -6096,15 +6103,16 @@ SetVertexAttribType(index, kFloat32ArrayType); } -void WebGLRenderingContextBase::vertexAttrib3fv(GLuint index, - const DOMFloat32Array* v) { +void WebGLRenderingContextBase::vertexAttrib3fv( + GLuint index, + NotShared<const DOMFloat32Array> v) { if (isContextLost()) return; - if (!v || v->length() < 3) { + if (!v.View() || v.View()->length() < 3) { SynthesizeGLError(GL_INVALID_VALUE, "vertexAttrib3fv", "invalid array"); return; } - ContextGL()->VertexAttrib3fv(index, v->Data()); + ContextGL()->VertexAttrib3fv(index, v.View()->Data()); SetVertexAttribType(index, kFloat32ArrayType); } @@ -6131,15 +6139,16 @@ SetVertexAttribType(index, kFloat32ArrayType); } -void WebGLRenderingContextBase::vertexAttrib4fv(GLuint index, - const DOMFloat32Array* v) { +void WebGLRenderingContextBase::vertexAttrib4fv( + GLuint index, + NotShared<const DOMFloat32Array> v) { if (isContextLost()) return; - if (!v || v->length() < 4) { + if (!v.View() || v.View()->length() < 4) { SynthesizeGLError(GL_INVALID_VALUE, "vertexAttrib4fv", "invalid array"); return; } - ContextGL()->VertexAttrib4fv(index, v->Data()); + ContextGL()->VertexAttrib4fv(index, v.View()->Data()); SetVertexAttribType(index, kFloat32ArrayType); }
diff --git a/third_party/WebKit/Source/modules/webgl/WebGLRenderingContextBase.h b/third_party/WebKit/Source/modules/webgl/WebGLRenderingContextBase.h index 61362cef..3f92cf2 100644 --- a/third_party/WebKit/Source/modules/webgl/WebGLRenderingContextBase.h +++ b/third_party/WebKit/Source/modules/webgl/WebGLRenderingContextBase.h
@@ -35,6 +35,7 @@ #include "bindings/core/v8/ScriptWrappableVisitor.h" #include "core/CoreExport.h" #include "core/dom/DOMTypedArray.h" +#include "core/dom/NotShared.h" #include "core/dom/TypedFlexibleArrayBufferView.h" #include "core/html/canvas/CanvasContextCreationAttributes.h" #include "core/html/canvas/CanvasRenderingContext.h" @@ -166,7 +167,9 @@ void bufferData(GLenum target, long long size, GLenum usage); void bufferData(GLenum target, DOMArrayBuffer* data, GLenum usage); - void bufferData(GLenum target, DOMArrayBufferView* data, GLenum usage); + void bufferData(GLenum target, + NotShared<DOMArrayBufferView> data, + GLenum usage); void bufferSubData(GLenum target, long long offset, DOMArrayBuffer* data); void bufferSubData(GLenum target, long long offset, @@ -189,7 +192,7 @@ GLsizei width, GLsizei height, GLint border, - DOMArrayBufferView* data); + NotShared<DOMArrayBufferView> data); void compressedTexSubImage2D(GLenum target, GLint level, GLint xoffset, @@ -197,7 +200,7 @@ GLsizei width, GLsizei height, GLenum format, - DOMArrayBufferView* data); + NotShared<DOMArrayBufferView> data); void copyTexImage2D(GLenum target, GLint level, @@ -322,7 +325,7 @@ GLsizei height, GLenum format, GLenum type, - DOMArrayBufferView* pixels); + NotShared<DOMArrayBufferView> pixels); void renderbufferStorage(GLenum target, GLenum internalformat, GLsizei width, @@ -345,7 +348,7 @@ GLint border, GLenum format, GLenum type, - DOMArrayBufferView*); + NotShared<DOMArrayBufferView>); void texImage2D(GLenum target, GLint level, GLint internalformat, @@ -392,7 +395,7 @@ GLsizei height, GLenum format, GLenum type, - DOMArrayBufferView*); + NotShared<DOMArrayBufferView>); void texSubImage2D(GLenum target, GLint level, GLint xoffset, @@ -467,19 +470,19 @@ void uniform4iv(const WebGLUniformLocation*, Vector<GLint>&); void uniformMatrix2fv(const WebGLUniformLocation*, GLboolean transpose, - DOMFloat32Array* value); + NotShared<DOMFloat32Array> value); void uniformMatrix2fv(const WebGLUniformLocation*, GLboolean transpose, Vector<GLfloat>& value); void uniformMatrix3fv(const WebGLUniformLocation*, GLboolean transpose, - DOMFloat32Array* value); + NotShared<DOMFloat32Array> value); void uniformMatrix3fv(const WebGLUniformLocation*, GLboolean transpose, Vector<GLfloat>& value); void uniformMatrix4fv(const WebGLUniformLocation*, GLboolean transpose, - DOMFloat32Array* value); + NotShared<DOMFloat32Array> value); void uniformMatrix4fv(const WebGLUniformLocation*, GLboolean transpose, Vector<GLfloat>& value); @@ -488,16 +491,16 @@ void validateProgram(WebGLProgram*); void vertexAttrib1f(GLuint index, GLfloat x); - void vertexAttrib1fv(GLuint index, const DOMFloat32Array* values); + void vertexAttrib1fv(GLuint index, NotShared<const DOMFloat32Array> values); void vertexAttrib1fv(GLuint index, const Vector<GLfloat>& values); void vertexAttrib2f(GLuint index, GLfloat x, GLfloat y); - void vertexAttrib2fv(GLuint index, const DOMFloat32Array* values); + void vertexAttrib2fv(GLuint index, NotShared<const DOMFloat32Array> values); void vertexAttrib2fv(GLuint index, const Vector<GLfloat>& values); void vertexAttrib3f(GLuint index, GLfloat x, GLfloat y, GLfloat z); - void vertexAttrib3fv(GLuint index, const DOMFloat32Array* values); + void vertexAttrib3fv(GLuint index, NotShared<const DOMFloat32Array> values); void vertexAttrib3fv(GLuint index, const Vector<GLfloat>& values); void vertexAttrib4f(GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w); - void vertexAttrib4fv(GLuint index, const DOMFloat32Array* values); + void vertexAttrib4fv(GLuint index, NotShared<const DOMFloat32Array> values); void vertexAttrib4fv(GLuint index, const Vector<GLfloat>& values); void vertexAttribPointer(GLuint index, GLint size,
diff --git a/third_party/WebKit/Source/modules/webmidi/MIDIMessageEvent.cpp b/third_party/WebKit/Source/modules/webmidi/MIDIMessageEvent.cpp index f4a1075..e12dd9a 100644 --- a/third_party/WebKit/Source/modules/webmidi/MIDIMessageEvent.cpp +++ b/third_party/WebKit/Source/modules/webmidi/MIDIMessageEvent.cpp
@@ -12,7 +12,7 @@ const MIDIMessageEventInit& initializer) : Event(type, initializer) { if (initializer.hasData()) - data_ = initializer.data(); + data_ = initializer.data().View(); } } // namespace blink
diff --git a/third_party/WebKit/Source/modules/webmidi/MIDIOutput.cpp b/third_party/WebKit/Source/modules/webmidi/MIDIOutput.cpp index 9070fad..e287267 100644 --- a/third_party/WebKit/Source/modules/webmidi/MIDIOutput.cpp +++ b/third_party/WebKit/Source/modules/webmidi/MIDIOutput.cpp
@@ -221,7 +221,7 @@ MIDIOutput::~MIDIOutput() {} -void MIDIOutput::send(DOMUint8Array* array, +void MIDIOutput::send(NotShared<DOMUint8Array> array, double timestamp, ExceptionState& exception_state) { DCHECK(array); @@ -233,10 +233,11 @@ // This should be performed even if |array| is invalid. open(); - if (MessageValidator::Validate(array, exception_state, - midiAccess()->sysexEnabled())) - midiAccess()->SendMIDIData(port_index_, array->Data(), array->length(), - timestamp); + if (MessageValidator::Validate(array.View(), exception_state, + midiAccess()->sysexEnabled())) { + midiAccess()->SendMIDIData(port_index_, array.View()->Data(), + array.View()->length(), timestamp); + } } void MIDIOutput::send(Vector<unsigned> unsigned_data, @@ -260,10 +261,11 @@ array_data[i] = unsigned_data[i] & 0xff; } - send(array, timestamp, exception_state); + send(NotShared<DOMUint8Array>(array), timestamp, exception_state); } -void MIDIOutput::send(DOMUint8Array* data, ExceptionState& exception_state) { +void MIDIOutput::send(NotShared<DOMUint8Array> data, + ExceptionState& exception_state) { DCHECK(data); send(data, 0.0, exception_state); }
diff --git a/third_party/WebKit/Source/modules/webmidi/MIDIOutput.h b/third_party/WebKit/Source/modules/webmidi/MIDIOutput.h index 3bd59ed..74d4fca 100644 --- a/third_party/WebKit/Source/modules/webmidi/MIDIOutput.h +++ b/third_party/WebKit/Source/modules/webmidi/MIDIOutput.h
@@ -32,6 +32,7 @@ #define MIDIOutput_h #include "core/dom/DOMTypedArray.h" +#include "core/dom/NotShared.h" #include "modules/webmidi/MIDIPort.h" namespace blink { @@ -52,11 +53,11 @@ midi::mojom::PortState); ~MIDIOutput() override; - void send(DOMUint8Array*, double timestamp, ExceptionState&); + void send(NotShared<DOMUint8Array>, double timestamp, ExceptionState&); void send(Vector<unsigned>, double timestamp, ExceptionState&); // send() without optional |timestamp|. - void send(DOMUint8Array*, ExceptionState&); + void send(NotShared<DOMUint8Array>, ExceptionState&); void send(Vector<unsigned>, ExceptionState&); DECLARE_VIRTUAL_TRACE();
diff --git a/third_party/WebKit/Source/modules/websockets/DOMWebSocket.cpp b/third_party/WebKit/Source/modules/websockets/DOMWebSocket.cpp index 767e95e..00b6b25 100644 --- a/third_party/WebKit/Source/modules/websockets/DOMWebSocket.cpp +++ b/third_party/WebKit/Source/modules/websockets/DOMWebSocket.cpp
@@ -477,26 +477,27 @@ channel_->Send(*binary_data, 0, binary_data->ByteLength()); } -void DOMWebSocket::send(DOMArrayBufferView* array_buffer_view, +void DOMWebSocket::send(NotShared<DOMArrayBufferView> array_buffer_view, ExceptionState& exception_state) { NETWORK_DVLOG(1) << "WebSocket " << this << " send() Sending ArrayBufferView " - << array_buffer_view; + << array_buffer_view.View(); DCHECK(array_buffer_view); if (state_ == kConnecting) { SetInvalidStateErrorForSendMethod(exception_state); return; } if (state_ == kClosing || state_ == kClosed) { - UpdateBufferedAmountAfterClose(array_buffer_view->byteLength()); + UpdateBufferedAmountAfterClose(array_buffer_view.View()->byteLength()); return; } RecordSendTypeHistogram(kWebSocketSendTypeArrayBufferView); RecordSendMessageSizeHistogram(kWebSocketSendTypeArrayBufferView, - array_buffer_view->byteLength()); + array_buffer_view.View()->byteLength()); DCHECK(channel_); - buffered_amount_ += array_buffer_view->byteLength(); - channel_->Send(*array_buffer_view->buffer(), array_buffer_view->byteOffset(), - array_buffer_view->byteLength()); + buffered_amount_ += array_buffer_view.View()->byteLength(); + channel_->Send(*array_buffer_view.View()->buffer(), + array_buffer_view.View()->byteOffset(), + array_buffer_view.View()->byteLength()); } void DOMWebSocket::send(Blob* binary_data, ExceptionState& exception_state) {
diff --git a/third_party/WebKit/Source/modules/websockets/DOMWebSocket.h b/third_party/WebKit/Source/modules/websockets/DOMWebSocket.h index 0f1cdff0..42c9a94b 100644 --- a/third_party/WebKit/Source/modules/websockets/DOMWebSocket.h +++ b/third_party/WebKit/Source/modules/websockets/DOMWebSocket.h
@@ -36,6 +36,7 @@ #include <memory> #include "bindings/core/v8/ActiveScriptWrappable.h" #include "bindings/core/v8/ScriptWrappable.h" +#include "core/dom/NotShared.h" #include "core/dom/SuspendableObject.h" #include "core/events/EventListener.h" #include "core/events/EventTarget.h" @@ -90,7 +91,7 @@ void send(const String& message, ExceptionState&); void send(DOMArrayBuffer*, ExceptionState&); - void send(DOMArrayBufferView*, ExceptionState&); + void send(NotShared<DOMArrayBufferView>, ExceptionState&); void send(Blob*, ExceptionState&); // To distinguish close method call with the code parameter from one
diff --git a/third_party/WebKit/Source/modules/webusb/USBDevice.cpp b/third_party/WebKit/Source/modules/webusb/USBDevice.cpp index bbe535f..e651ee3 100644 --- a/third_party/WebKit/Source/modules/webusb/USBDevice.cpp +++ b/third_party/WebKit/Source/modules/webusb/USBDevice.cpp
@@ -85,9 +85,9 @@ vector.Append(static_cast<uint8_t*>(buffer.getAsArrayBuffer()->Data()), buffer.getAsArrayBuffer()->ByteLength()); else - vector.Append( - static_cast<uint8_t*>(buffer.getAsArrayBufferView()->BaseAddress()), - buffer.getAsArrayBufferView()->byteLength()); + vector.Append(static_cast<uint8_t*>( + buffer.getAsArrayBufferView().View()->BaseAddress()), + buffer.getAsArrayBufferView().View()->byteLength()); return vector; }
diff --git a/third_party/WebKit/Source/platform/RuntimeEnabledFeatures.json5 b/third_party/WebKit/Source/platform/RuntimeEnabledFeatures.json5 index fd6a857f..ae070d01 100644 --- a/third_party/WebKit/Source/platform/RuntimeEnabledFeatures.json5 +++ b/third_party/WebKit/Source/platform/RuntimeEnabledFeatures.json5
@@ -491,8 +491,7 @@ }, { name: "ImageCapture", - origin_trial_feature_name: "ImageCapture", - status: "experimental", + status: "stable", }, { name: "ImageOrientation",
diff --git a/third_party/WebKit/Source/platform/exported/Platform.cpp b/third_party/WebKit/Source/platform/exported/Platform.cpp index 2adbdd7..43a2b3c8 100644 --- a/third_party/WebKit/Source/platform/exported/Platform.cpp +++ b/third_party/WebKit/Source/platform/exported/Platform.cpp
@@ -93,8 +93,8 @@ } void Platform::Initialize(Platform* platform) { - ASSERT(!g_platform); - ASSERT(platform); + DCHECK(!g_platform); + DCHECK(platform); g_platform = platform; g_platform->main_thread_ = platform->CurrentThread(); @@ -111,7 +111,7 @@ // TODO(ssid): remove this check after fixing crbug.com/486782. if (g_platform->main_thread_) { - ASSERT(!g_gc_task_runner); + DCHECK(!g_gc_task_runner); g_gc_task_runner = new GCTaskRunner(g_platform->main_thread_); base::trace_event::MemoryDumpManager::GetInstance()->RegisterDumpProvider( PartitionAllocMemoryDumpProvider::Instance(), "PartitionAlloc", @@ -126,7 +126,7 @@ } void Platform::SetCurrentPlatformForTesting(Platform* platform) { - ASSERT(platform); + DCHECK(platform); g_platform = platform; g_platform->main_thread_ = platform->CurrentThread(); }
diff --git a/third_party/WebKit/Source/platform/exported/WebAudioBus.cpp b/third_party/WebKit/Source/platform/exported/WebAudioBus.cpp index 18e5d97e..7b7495f5 100644 --- a/third_party/WebKit/Source/platform/exported/WebAudioBus.cpp +++ b/third_party/WebKit/Source/platform/exported/WebAudioBus.cpp
@@ -48,9 +48,9 @@ } void WebAudioBus::ResizeSmaller(size_t new_length) { - ASSERT(private_); + DCHECK(private_); if (private_) { - ASSERT(new_length <= length()); + DCHECK_LE(new_length, length()); private_->ResizeSmaller(new_length); } } @@ -83,7 +83,7 @@ float* WebAudioBus::ChannelData(unsigned channel_index) { if (!private_) return 0; - ASSERT(channel_index < NumberOfChannels()); + DCHECK_LT(channel_index, NumberOfChannels()); return private_->Channel(channel_index)->MutableData(); }
diff --git a/third_party/WebKit/Source/platform/exported/WebBlobData.cpp b/third_party/WebKit/Source/platform/exported/WebBlobData.cpp index 58c07ff..3a468adc 100644 --- a/third_party/WebKit/Source/platform/exported/WebBlobData.cpp +++ b/third_party/WebKit/Source/platform/exported/WebBlobData.cpp
@@ -41,12 +41,12 @@ WebBlobData::~WebBlobData() {} size_t WebBlobData::ItemCount() const { - ASSERT(!IsNull()); + DCHECK(!IsNull()); return private_->Items().size(); } bool WebBlobData::ItemAt(size_t index, Item& result) const { - ASSERT(!IsNull()); + DCHECK(!IsNull()); if (index >= private_->Items().size()) return false; @@ -77,12 +77,12 @@ result.file_system_url = item.file_system_url; return true; } - ASSERT_NOT_REACHED(); + NOTREACHED(); return false; } WebString WebBlobData::ContentType() const { - ASSERT(!IsNull()); + DCHECK(!IsNull()); return private_->ContentType(); }
diff --git a/third_party/WebKit/Source/platform/exported/WebContentDecryptionModuleResult.cpp b/third_party/WebKit/Source/platform/exported/WebContentDecryptionModuleResult.cpp index f4fa944..0e1dfaa 100644 --- a/third_party/WebKit/Source/platform/exported/WebContentDecryptionModuleResult.cpp +++ b/third_party/WebKit/Source/platform/exported/WebContentDecryptionModuleResult.cpp
@@ -36,7 +36,7 @@ WebContentDecryptionModuleResult::WebContentDecryptionModuleResult( ContentDecryptionModuleResult* impl) : impl_(impl) { - ASSERT(impl_.Get()); + DCHECK(impl_.Get()); } void WebContentDecryptionModuleResult::Reset() {
diff --git a/third_party/WebKit/Source/platform/exported/WebContentSettingCallbacks.cpp b/third_party/WebKit/Source/platform/exported/WebContentSettingCallbacks.cpp index 50b0aae..c1da7697 100644 --- a/third_party/WebKit/Source/platform/exported/WebContentSettingCallbacks.cpp +++ b/third_party/WebKit/Source/platform/exported/WebContentSettingCallbacks.cpp
@@ -43,13 +43,13 @@ } void WebContentSettingCallbacks::DoAllow() { - ASSERT(!private_.IsNull()); + DCHECK(!private_.IsNull()); private_->Callbacks()->OnAllowed(); private_.Reset(); } void WebContentSettingCallbacks::DoDeny() { - ASSERT(!private_.IsNull()); + DCHECK(!private_.IsNull()); private_->Callbacks()->OnDenied(); private_.Reset(); }
diff --git a/third_party/WebKit/Source/platform/exported/WebCredential.cpp b/third_party/WebKit/Source/platform/exported/WebCredential.cpp index bb5cd00..f8b85c37 100644 --- a/third_party/WebKit/Source/platform/exported/WebCredential.cpp +++ b/third_party/WebKit/Source/platform/exported/WebCredential.cpp
@@ -21,7 +21,7 @@ return WTF::MakeUnique<WebFederatedCredential>(credential); } - ASSERT_NOT_REACHED(); + NOTREACHED(); return nullptr; }
diff --git a/third_party/WebKit/Source/platform/exported/WebCryptoAlgorithm.cpp b/third_party/WebKit/Source/platform/exported/WebCryptoAlgorithm.cpp index 3e75178..15361991f 100644 --- a/third_party/WebKit/Source/platform/exported/WebCryptoAlgorithm.cpp +++ b/third_party/WebKit/Source/platform/exported/WebCryptoAlgorithm.cpp
@@ -351,61 +351,61 @@ } WebCryptoAlgorithmId WebCryptoAlgorithm::Id() const { - ASSERT(!IsNull()); + DCHECK(!IsNull()); return private_->id; } WebCryptoAlgorithmParamsType WebCryptoAlgorithm::ParamsType() const { - ASSERT(!IsNull()); + DCHECK(!IsNull()); if (!private_->params) return kWebCryptoAlgorithmParamsTypeNone; return private_->params->GetType(); } const WebCryptoAesCbcParams* WebCryptoAlgorithm::AesCbcParams() const { - ASSERT(!IsNull()); + DCHECK(!IsNull()); if (ParamsType() == kWebCryptoAlgorithmParamsTypeAesCbcParams) return static_cast<WebCryptoAesCbcParams*>(private_->params.get()); return 0; } const WebCryptoAesCtrParams* WebCryptoAlgorithm::AesCtrParams() const { - ASSERT(!IsNull()); + DCHECK(!IsNull()); if (ParamsType() == kWebCryptoAlgorithmParamsTypeAesCtrParams) return static_cast<WebCryptoAesCtrParams*>(private_->params.get()); return 0; } const WebCryptoAesKeyGenParams* WebCryptoAlgorithm::AesKeyGenParams() const { - ASSERT(!IsNull()); + DCHECK(!IsNull()); if (ParamsType() == kWebCryptoAlgorithmParamsTypeAesKeyGenParams) return static_cast<WebCryptoAesKeyGenParams*>(private_->params.get()); return 0; } const WebCryptoHmacImportParams* WebCryptoAlgorithm::HmacImportParams() const { - ASSERT(!IsNull()); + DCHECK(!IsNull()); if (ParamsType() == kWebCryptoAlgorithmParamsTypeHmacImportParams) return static_cast<WebCryptoHmacImportParams*>(private_->params.get()); return 0; } const WebCryptoHmacKeyGenParams* WebCryptoAlgorithm::HmacKeyGenParams() const { - ASSERT(!IsNull()); + DCHECK(!IsNull()); if (ParamsType() == kWebCryptoAlgorithmParamsTypeHmacKeyGenParams) return static_cast<WebCryptoHmacKeyGenParams*>(private_->params.get()); return 0; } const WebCryptoAesGcmParams* WebCryptoAlgorithm::AesGcmParams() const { - ASSERT(!IsNull()); + DCHECK(!IsNull()); if (ParamsType() == kWebCryptoAlgorithmParamsTypeAesGcmParams) return static_cast<WebCryptoAesGcmParams*>(private_->params.get()); return 0; } const WebCryptoRsaOaepParams* WebCryptoAlgorithm::RsaOaepParams() const { - ASSERT(!IsNull()); + DCHECK(!IsNull()); if (ParamsType() == kWebCryptoAlgorithmParamsTypeRsaOaepParams) return static_cast<WebCryptoRsaOaepParams*>(private_->params.get()); return 0; @@ -413,7 +413,7 @@ const WebCryptoRsaHashedImportParams* WebCryptoAlgorithm::RsaHashedImportParams() const { - ASSERT(!IsNull()); + DCHECK(!IsNull()); if (ParamsType() == kWebCryptoAlgorithmParamsTypeRsaHashedImportParams) return static_cast<WebCryptoRsaHashedImportParams*>(private_->params.get()); return 0; @@ -421,28 +421,28 @@ const WebCryptoRsaHashedKeyGenParams* WebCryptoAlgorithm::RsaHashedKeyGenParams() const { - ASSERT(!IsNull()); + DCHECK(!IsNull()); if (ParamsType() == kWebCryptoAlgorithmParamsTypeRsaHashedKeyGenParams) return static_cast<WebCryptoRsaHashedKeyGenParams*>(private_->params.get()); return 0; } const WebCryptoRsaPssParams* WebCryptoAlgorithm::RsaPssParams() const { - ASSERT(!IsNull()); + DCHECK(!IsNull()); if (ParamsType() == kWebCryptoAlgorithmParamsTypeRsaPssParams) return static_cast<WebCryptoRsaPssParams*>(private_->params.get()); return 0; } const WebCryptoEcdsaParams* WebCryptoAlgorithm::EcdsaParams() const { - ASSERT(!IsNull()); + DCHECK(!IsNull()); if (ParamsType() == kWebCryptoAlgorithmParamsTypeEcdsaParams) return static_cast<WebCryptoEcdsaParams*>(private_->params.get()); return 0; } const WebCryptoEcKeyGenParams* WebCryptoAlgorithm::EcKeyGenParams() const { - ASSERT(!IsNull()); + DCHECK(!IsNull()); if (ParamsType() == kWebCryptoAlgorithmParamsTypeEcKeyGenParams) return static_cast<WebCryptoEcKeyGenParams*>(private_->params.get()); return 0; @@ -450,7 +450,7 @@ const WebCryptoEcKeyImportParams* WebCryptoAlgorithm::EcKeyImportParams() const { - ASSERT(!IsNull()); + DCHECK(!IsNull()); if (ParamsType() == kWebCryptoAlgorithmParamsTypeEcKeyImportParams) return static_cast<WebCryptoEcKeyImportParams*>(private_->params.get()); return 0; @@ -458,7 +458,7 @@ const WebCryptoEcdhKeyDeriveParams* WebCryptoAlgorithm::EcdhKeyDeriveParams() const { - ASSERT(!IsNull()); + DCHECK(!IsNull()); if (ParamsType() == kWebCryptoAlgorithmParamsTypeEcdhKeyDeriveParams) return static_cast<WebCryptoEcdhKeyDeriveParams*>(private_->params.get()); return 0; @@ -466,21 +466,21 @@ const WebCryptoAesDerivedKeyParams* WebCryptoAlgorithm::AesDerivedKeyParams() const { - ASSERT(!IsNull()); + DCHECK(!IsNull()); if (ParamsType() == kWebCryptoAlgorithmParamsTypeAesDerivedKeyParams) return static_cast<WebCryptoAesDerivedKeyParams*>(private_->params.get()); return 0; } const WebCryptoHkdfParams* WebCryptoAlgorithm::HkdfParams() const { - ASSERT(!IsNull()); + DCHECK(!IsNull()); if (ParamsType() == kWebCryptoAlgorithmParamsTypeHkdfParams) return static_cast<WebCryptoHkdfParams*>(private_->params.get()); return 0; } const WebCryptoPbkdf2Params* WebCryptoAlgorithm::Pbkdf2Params() const { - ASSERT(!IsNull()); + DCHECK(!IsNull()); if (ParamsType() == kWebCryptoAlgorithmParamsTypePbkdf2Params) return static_cast<WebCryptoPbkdf2Params*>(private_->params.get()); return 0;
diff --git a/third_party/WebKit/Source/platform/exported/WebCryptoKey.cpp b/third_party/WebKit/Source/platform/exported/WebCryptoKey.cpp index 3f5591cc..4ecca33 100644 --- a/third_party/WebKit/Source/platform/exported/WebCryptoKey.cpp +++ b/third_party/WebKit/Source/platform/exported/WebCryptoKey.cpp
@@ -51,7 +51,7 @@ extractable(extractable), algorithm(algorithm), usages(usages) { - ASSERT(!algorithm.IsNull()); + DCHECK(!algorithm.IsNull()); } const std::unique_ptr<WebCryptoKeyHandle> handle; @@ -77,27 +77,27 @@ } WebCryptoKeyHandle* WebCryptoKey::Handle() const { - ASSERT(!IsNull()); + DCHECK(!IsNull()); return private_->handle.get(); } WebCryptoKeyType WebCryptoKey::GetType() const { - ASSERT(!IsNull()); + DCHECK(!IsNull()); return private_->type; } bool WebCryptoKey::Extractable() const { - ASSERT(!IsNull()); + DCHECK(!IsNull()); return private_->extractable; } const WebCryptoKeyAlgorithm& WebCryptoKey::Algorithm() const { - ASSERT(!IsNull()); + DCHECK(!IsNull()); return private_->algorithm; } WebCryptoKeyUsageMask WebCryptoKey::Usages() const { - ASSERT(!IsNull()); + DCHECK(!IsNull()); return private_->usages; }
diff --git a/third_party/WebKit/Source/platform/exported/WebCryptoKeyAlgorithm.cpp b/third_party/WebKit/Source/platform/exported/WebCryptoKeyAlgorithm.cpp index bd84539e..570ac409 100644 --- a/third_party/WebKit/Source/platform/exported/WebCryptoKeyAlgorithm.cpp +++ b/third_party/WebKit/Source/platform/exported/WebCryptoKeyAlgorithm.cpp
@@ -122,26 +122,26 @@ } WebCryptoAlgorithmId WebCryptoKeyAlgorithm::Id() const { - ASSERT(!IsNull()); + DCHECK(!IsNull()); return private_->id; } WebCryptoKeyAlgorithmParamsType WebCryptoKeyAlgorithm::ParamsType() const { - ASSERT(!IsNull()); + DCHECK(!IsNull()); if (!private_->params.get()) return kWebCryptoKeyAlgorithmParamsTypeNone; return private_->params->GetType(); } WebCryptoAesKeyAlgorithmParams* WebCryptoKeyAlgorithm::AesParams() const { - ASSERT(!IsNull()); + DCHECK(!IsNull()); if (ParamsType() == kWebCryptoKeyAlgorithmParamsTypeAes) return static_cast<WebCryptoAesKeyAlgorithmParams*>(private_->params.get()); return 0; } WebCryptoHmacKeyAlgorithmParams* WebCryptoKeyAlgorithm::HmacParams() const { - ASSERT(!IsNull()); + DCHECK(!IsNull()); if (ParamsType() == kWebCryptoKeyAlgorithmParamsTypeHmac) return static_cast<WebCryptoHmacKeyAlgorithmParams*>( private_->params.get()); @@ -150,7 +150,7 @@ WebCryptoRsaHashedKeyAlgorithmParams* WebCryptoKeyAlgorithm::RsaHashedParams() const { - ASSERT(!IsNull()); + DCHECK(!IsNull()); if (ParamsType() == kWebCryptoKeyAlgorithmParamsTypeRsaHashed) return static_cast<WebCryptoRsaHashedKeyAlgorithmParams*>( private_->params.get()); @@ -158,7 +158,7 @@ } WebCryptoEcKeyAlgorithmParams* WebCryptoKeyAlgorithm::EcParams() const { - ASSERT(!IsNull()); + DCHECK(!IsNull()); if (ParamsType() == kWebCryptoKeyAlgorithmParamsTypeEc) return static_cast<WebCryptoEcKeyAlgorithmParams*>(private_->params.get()); return 0; @@ -166,7 +166,7 @@ void WebCryptoKeyAlgorithm::WriteToDictionary( WebCryptoKeyAlgorithmDictionary* dict) const { - ASSERT(!IsNull()); + DCHECK(!IsNull()); dict->SetString("name", WebCryptoAlgorithm::LookupAlgorithmInfo(Id())->name); if (private_->params.get()) private_->params.get()->WriteToDictionary(dict);
diff --git a/third_party/WebKit/Source/platform/exported/WebCryptoResult.cpp b/third_party/WebKit/Source/platform/exported/WebCryptoResult.cpp index fe818b750..2d402af 100644 --- a/third_party/WebKit/Source/platform/exported/WebCryptoResult.cpp +++ b/third_party/WebKit/Source/platform/exported/WebCryptoResult.cpp
@@ -62,7 +62,7 @@ } void WebCryptoResult::CompleteWithKey(const WebCryptoKey& key) { - ASSERT(!key.IsNull()); + DCHECK(!key.IsNull()); if (!Cancelled()) impl_->CompleteWithKey(key); Reset(); @@ -70,8 +70,8 @@ void WebCryptoResult::CompleteWithKeyPair(const WebCryptoKey& public_key, const WebCryptoKey& private_key) { - ASSERT(!public_key.IsNull()); - ASSERT(!private_key.IsNull()); + DCHECK(!public_key.IsNull()); + DCHECK(!private_key.IsNull()); if (!Cancelled()) impl_->CompleteWithKeyPair(public_key, private_key); Reset(); @@ -84,8 +84,8 @@ WebCryptoResult::WebCryptoResult(CryptoResult* impl, PassRefPtr<CryptoResultCancel> cancel) : impl_(impl), cancel_(cancel) { - ASSERT(impl_.Get()); - ASSERT(cancel_.Get()); + DCHECK(impl_.Get()); + DCHECK(cancel_.Get()); } void WebCryptoResult::Reset() {
diff --git a/third_party/WebKit/Source/platform/exported/WebDataConsumerHandle.cpp b/third_party/WebKit/Source/platform/exported/WebDataConsumerHandle.cpp index 695fa19..eefd29a 100644 --- a/third_party/WebKit/Source/platform/exported/WebDataConsumerHandle.cpp +++ b/third_party/WebKit/Source/platform/exported/WebDataConsumerHandle.cpp
@@ -13,11 +13,11 @@ namespace blink { WebDataConsumerHandle::WebDataConsumerHandle() { - ASSERT(ThreadState::Current()); + DCHECK(ThreadState::Current()); } WebDataConsumerHandle::~WebDataConsumerHandle() { - ASSERT(ThreadState::Current()); + DCHECK(ThreadState::Current()); } WebDataConsumerHandle::Result WebDataConsumerHandle::Reader::Read(
diff --git a/third_party/WebKit/Source/platform/exported/WebDragData.cpp b/third_party/WebKit/Source/platform/exported/WebDragData.cpp index 7ae91c4..ccef59ea 100644 --- a/third_party/WebKit/Source/platform/exported/WebDragData.cpp +++ b/third_party/WebKit/Source/platform/exported/WebDragData.cpp
@@ -33,12 +33,12 @@ namespace blink { void WebDragData::SetItems(WebVector<Item> item_list) { - ASSERT(!IsNull()); + DCHECK(!IsNull()); item_list_.Swap(item_list); } void WebDragData::AddItem(const Item& item) { - ASSERT(!IsNull()); + DCHECK(!IsNull()); WebVector<Item> item_list(item_list_.size() + 1); for (unsigned i = 0; i < item_list_.size(); ++i)
diff --git a/third_party/WebKit/Source/platform/exported/WebFileSystemCallbacks.cpp b/third_party/WebKit/Source/platform/exported/WebFileSystemCallbacks.cpp index 23f8637..f0b6e00 100644 --- a/third_party/WebKit/Source/platform/exported/WebFileSystemCallbacks.cpp +++ b/third_party/WebKit/Source/platform/exported/WebFileSystemCallbacks.cpp
@@ -75,13 +75,13 @@ } void WebFileSystemCallbacks::DidSucceed() { - ASSERT(!private_.IsNull()); + DCHECK(!private_.IsNull()); private_->Callbacks()->DidSucceed(); private_.Reset(); } void WebFileSystemCallbacks::DidReadMetadata(const WebFileInfo& web_file_info) { - ASSERT(!private_.IsNull()); + DCHECK(!private_.IsNull()); FileMetadata file_metadata; file_metadata.modification_time = web_file_info.modification_time; file_metadata.length = web_file_info.length; @@ -93,7 +93,7 @@ void WebFileSystemCallbacks::DidCreateSnapshotFile( const WebFileInfo& web_file_info) { - ASSERT(!private_.IsNull()); + DCHECK(!private_.IsNull()); // It's important to create a BlobDataHandle that refers to the platform file // path prior to return from this method so the underlying file will not be // deleted. @@ -115,7 +115,7 @@ void WebFileSystemCallbacks::DidReadDirectory( const WebVector<WebFileSystemEntry>& entries, bool has_more) { - ASSERT(!private_.IsNull()); + DCHECK(!private_.IsNull()); for (size_t i = 0; i < entries.size(); ++i) private_->Callbacks()->DidReadDirectoryEntry(entries[i].name, entries[i].is_directory); @@ -125,7 +125,7 @@ void WebFileSystemCallbacks::DidOpenFileSystem(const WebString& name, const WebURL& root_url) { - ASSERT(!private_.IsNull()); + DCHECK(!private_.IsNull()); private_->Callbacks()->DidOpenFileSystem(name, root_url); private_.Reset(); } @@ -135,7 +135,7 @@ WebFileSystemType type, const WebString& file_path, bool is_directory) { - ASSERT(!private_.IsNull()); + DCHECK(!private_.IsNull()); private_->Callbacks()->DidResolveURL(name, root_url, static_cast<FileSystemType>(type), file_path, is_directory); @@ -144,20 +144,20 @@ void WebFileSystemCallbacks::DidCreateFileWriter(WebFileWriter* web_file_writer, long long length) { - ASSERT(!private_.IsNull()); + DCHECK(!private_.IsNull()); private_->Callbacks()->DidCreateFileWriter(WTF::WrapUnique(web_file_writer), length); private_.Reset(); } void WebFileSystemCallbacks::DidFail(WebFileError error) { - ASSERT(!private_.IsNull()); + DCHECK(!private_.IsNull()); private_->Callbacks()->DidFail(error); private_.Reset(); } bool WebFileSystemCallbacks::ShouldBlockUntilCompletion() const { - ASSERT(!private_.IsNull()); + DCHECK(!private_.IsNull()); return private_->Callbacks()->ShouldBlockUntilCompletion(); }
diff --git a/third_party/WebKit/Source/platform/exported/WebHTTPBody.cpp b/third_party/WebKit/Source/platform/exported/WebHTTPBody.cpp index 0f8de896..d21b692 100644 --- a/third_party/WebKit/Source/platform/exported/WebHTTPBody.cpp +++ b/third_party/WebKit/Source/platform/exported/WebHTTPBody.cpp
@@ -53,12 +53,12 @@ } size_t WebHTTPBody::ElementCount() const { - ASSERT(!IsNull()); + DCHECK(!IsNull()); return private_->Elements().size(); } bool WebHTTPBody::ElementAt(size_t index, Element& result) const { - ASSERT(!IsNull()); + DCHECK(!IsNull()); if (index >= private_->Elements().size()) return false; @@ -96,7 +96,7 @@ result.modification_time = element.expected_file_modification_time_; break; default: - ASSERT_NOT_REACHED(); + NOTREACHED(); return false; } @@ -129,7 +129,7 @@ long long length, double modification_time) { // Currently we only support filesystem URL. - ASSERT(KURL(url).ProtocolIs("filesystem")); + DCHECK(KURL(url).ProtocolIs("filesystem")); EnsureMutable(); private_->AppendFileSystemURLRange(url, start, length, modification_time); } @@ -140,7 +140,7 @@ } long long WebHTTPBody::Identifier() const { - ASSERT(!IsNull()); + DCHECK(!IsNull()); return private_->Identifier(); } @@ -161,7 +161,7 @@ : private_(static_cast<WebHTTPBodyPrivate*>(data.LeakRef())) {} WebHTTPBody& WebHTTPBody::operator=(PassRefPtr<EncodedFormData> data) { - Assign(static_cast<WebHTTPBodyPrivate*>(data.LeakRef())); + DCHECK(static_cast<WebHTTPBodyPrivate*>(data.LeakRef())); return *this; } @@ -177,7 +177,7 @@ } void WebHTTPBody::EnsureMutable() { - ASSERT(!IsNull()); + DCHECK(!IsNull()); if (!private_->HasOneRef()) Assign(static_cast<WebHTTPBodyPrivate*>(private_->Copy().LeakRef())); }
diff --git a/third_party/WebKit/Source/platform/exported/WebHTTPLoadInfo.cpp b/third_party/WebKit/Source/platform/exported/WebHTTPLoadInfo.cpp index f3132c2..fea4ea6d 100644 --- a/third_party/WebKit/Source/platform/exported/WebHTTPLoadInfo.cpp +++ b/third_party/WebKit/Source/platform/exported/WebHTTPLoadInfo.cpp
@@ -56,22 +56,22 @@ } int WebHTTPLoadInfo::HttpStatusCode() const { - ASSERT(!private_.IsNull()); + DCHECK(!private_.IsNull()); return private_->http_status_code; } void WebHTTPLoadInfo::SetHTTPStatusCode(int status_code) { - ASSERT(!private_.IsNull()); + DCHECK(!private_.IsNull()); private_->http_status_code = status_code; } WebString WebHTTPLoadInfo::HttpStatusText() const { - ASSERT(!private_.IsNull()); + DCHECK(!private_.IsNull()); return private_->http_status_text; } void WebHTTPLoadInfo::SetHTTPStatusText(const WebString& status_text) { - ASSERT(!private_.IsNull()); + DCHECK(!private_.IsNull()); private_->http_status_text = status_text; } @@ -88,44 +88,44 @@ void WebHTTPLoadInfo::AddRequestHeader(const WebString& name, const WebString& value) { - ASSERT(!private_.IsNull()); + DCHECK(!private_.IsNull()); AddHeader(&private_->request_headers, name, value); } void WebHTTPLoadInfo::AddResponseHeader(const WebString& name, const WebString& value) { - ASSERT(!private_.IsNull()); + DCHECK(!private_.IsNull()); AddHeader(&private_->response_headers, name, value); } WebString WebHTTPLoadInfo::RequestHeadersText() const { - ASSERT(!private_.IsNull()); + DCHECK(!private_.IsNull()); return private_->request_headers_text; } void WebHTTPLoadInfo::SetRequestHeadersText(const WebString& headers_text) { - ASSERT(!private_.IsNull()); + DCHECK(!private_.IsNull()); private_->request_headers_text = headers_text; } WebString WebHTTPLoadInfo::ResponseHeadersText() const { - ASSERT(!private_.IsNull()); + DCHECK(!private_.IsNull()); return private_->response_headers_text; } void WebHTTPLoadInfo::SetResponseHeadersText(const WebString& headers_text) { - ASSERT(!private_.IsNull()); + DCHECK(!private_.IsNull()); private_->response_headers_text = headers_text; } WebString WebHTTPLoadInfo::NpnNegotiatedProtocol() const { - ASSERT(!private_.IsNull()); + DCHECK(!private_.IsNull()); return private_->npn_negotiated_protocol; } void WebHTTPLoadInfo::SetNPNNegotiatedProtocol( const WebString& npn_negotiated_protocol) { - ASSERT(!private_.IsNull()); + DCHECK(!private_.IsNull()); private_->npn_negotiated_protocol = npn_negotiated_protocol; }
diff --git a/third_party/WebKit/Source/platform/exported/WebMediaConstraints.cpp b/third_party/WebKit/Source/platform/exported/WebMediaConstraints.cpp index c628726..c5e4fcd0 100644 --- a/third_party/WebKit/Source/platform/exported/WebMediaConstraints.cpp +++ b/third_party/WebKit/Source/platform/exported/WebMediaConstraints.cpp
@@ -527,25 +527,25 @@ } void WebMediaConstraints::Initialize() { - ASSERT(IsNull()); + DCHECK(IsNull()); private_ = WebMediaConstraintsPrivate::Create(); } void WebMediaConstraints::Initialize( const WebMediaTrackConstraintSet& basic, const WebVector<WebMediaTrackConstraintSet>& advanced) { - ASSERT(IsNull()); + DCHECK(IsNull()); private_ = WebMediaConstraintsPrivate::Create(basic, advanced); } const WebMediaTrackConstraintSet& WebMediaConstraints::Basic() const { - ASSERT(!IsNull()); + DCHECK(!IsNull()); return private_->Basic(); } const WebVector<WebMediaTrackConstraintSet>& WebMediaConstraints::Advanced() const { - ASSERT(!IsNull()); + DCHECK(!IsNull()); return private_->Advanced(); }
diff --git a/third_party/WebKit/Source/platform/exported/WebMediaDeviceInfo.cpp b/third_party/WebKit/Source/platform/exported/WebMediaDeviceInfo.cpp index 59698881..bb62dca 100644 --- a/third_party/WebKit/Source/platform/exported/WebMediaDeviceInfo.cpp +++ b/third_party/WebKit/Source/platform/exported/WebMediaDeviceInfo.cpp
@@ -90,22 +90,22 @@ } WebString WebMediaDeviceInfo::DeviceId() const { - ASSERT(!private_.IsNull()); + DCHECK(!private_.IsNull()); return private_->DeviceId(); } WebMediaDeviceInfo::MediaDeviceKind WebMediaDeviceInfo::Kind() const { - ASSERT(!private_.IsNull()); + DCHECK(!private_.IsNull()); return private_->Kind(); } WebString WebMediaDeviceInfo::Label() const { - ASSERT(!private_.IsNull()); + DCHECK(!private_.IsNull()); return private_->Label(); } WebString WebMediaDeviceInfo::GroupId() const { - ASSERT(!private_.IsNull()); + DCHECK(!private_.IsNull()); return private_->GroupId(); }
diff --git a/third_party/WebKit/Source/platform/exported/WebMediaStream.cpp b/third_party/WebKit/Source/platform/exported/WebMediaStream.cpp index 1c883c4..a2c065f5 100644 --- a/third_party/WebKit/Source/platform/exported/WebMediaStream.cpp +++ b/third_party/WebKit/Source/platform/exported/WebMediaStream.cpp
@@ -121,12 +121,12 @@ } void WebMediaStream::AddTrack(const WebMediaStreamTrack& track) { - ASSERT(!IsNull()); + DCHECK(!IsNull()); private_->AddRemoteTrack(track); } void WebMediaStream::RemoveTrack(const WebMediaStreamTrack& track) { - ASSERT(!IsNull()); + DCHECK(!IsNull()); private_->RemoveRemoteTrack(track); }
diff --git a/third_party/WebKit/Source/platform/exported/WebMediaStreamTrack.cpp b/third_party/WebKit/Source/platform/exported/WebMediaStreamTrack.cpp index 30cd505..2c53633 100644 --- a/third_party/WebKit/Source/platform/exported/WebMediaStreamTrack.cpp +++ b/third_party/WebKit/Source/platform/exported/WebMediaStreamTrack.cpp
@@ -82,12 +82,12 @@ } bool WebMediaStreamTrack::IsEnabled() const { - ASSERT(!private_.IsNull()); + DCHECK(!private_.IsNull()); return private_->Enabled(); } bool WebMediaStreamTrack::IsMuted() const { - ASSERT(!private_.IsNull()); + DCHECK(!private_.IsNull()); return private_->Muted(); } @@ -97,12 +97,12 @@ } WebString WebMediaStreamTrack::Id() const { - ASSERT(!private_.IsNull()); + DCHECK(!private_.IsNull()); return private_->Id(); } WebMediaStreamSource WebMediaStreamTrack::Source() const { - ASSERT(!private_.IsNull()); + DCHECK(!private_.IsNull()); return WebMediaStreamSource(private_->Source()); } @@ -114,14 +114,14 @@ } void WebMediaStreamTrack::SetTrackData(TrackData* extra_data) { - ASSERT(!private_.IsNull()); + DCHECK(!private_.IsNull()); private_->SetTrackData( WTF::WrapUnique(new TrackDataContainer(WTF::WrapUnique(extra_data)))); } void WebMediaStreamTrack::SetSourceProvider(WebAudioSourceProvider* provider) { - ASSERT(!private_.IsNull()); + DCHECK(!private_.IsNull()); private_->SetSourceProvider(provider); }
diff --git a/third_party/WebKit/Source/platform/exported/WebRTCAnswerOptions.cpp b/third_party/WebKit/Source/platform/exported/WebRTCAnswerOptions.cpp index c2c7470..1812a4c 100644 --- a/third_party/WebKit/Source/platform/exported/WebRTCAnswerOptions.cpp +++ b/third_party/WebKit/Source/platform/exported/WebRTCAnswerOptions.cpp
@@ -20,7 +20,7 @@ } bool WebRTCAnswerOptions::VoiceActivityDetection() const { - ASSERT(!private_.IsNull()); + DCHECK(!private_.IsNull()); return private_->VoiceActivityDetection(); }
diff --git a/third_party/WebKit/Source/platform/exported/WebRTCICECandidate.cpp b/third_party/WebKit/Source/platform/exported/WebRTCICECandidate.cpp index 447c4bed..d68f5944 100644 --- a/third_party/WebKit/Source/platform/exported/WebRTCICECandidate.cpp +++ b/third_party/WebKit/Source/platform/exported/WebRTCICECandidate.cpp
@@ -95,32 +95,32 @@ } WebString WebRTCICECandidate::Candidate() const { - ASSERT(!private_.IsNull()); + DCHECK(!private_.IsNull()); return private_->Candidate(); } WebString WebRTCICECandidate::SdpMid() const { - ASSERT(!private_.IsNull()); + DCHECK(!private_.IsNull()); return private_->SdpMid(); } unsigned short WebRTCICECandidate::SdpMLineIndex() const { - ASSERT(!private_.IsNull()); + DCHECK(!private_.IsNull()); return private_->SdpMLineIndex(); } void WebRTCICECandidate::SetCandidate(WebString candidate) { - ASSERT(!private_.IsNull()); + DCHECK(!private_.IsNull()); private_->SetCandidate(candidate); } void WebRTCICECandidate::SetSdpMid(WebString sdp_mid) { - ASSERT(!private_.IsNull()); + DCHECK(!private_.IsNull()); private_->SetSdpMid(sdp_mid); } void WebRTCICECandidate::SetSdpMLineIndex(unsigned short sdp_m_line_index) { - ASSERT(!private_.IsNull()); + DCHECK(!private_.IsNull()); private_->SetSdpMLineIndex(sdp_m_line_index); }
diff --git a/third_party/WebKit/Source/platform/exported/WebRTCOfferOptions.cpp b/third_party/WebKit/Source/platform/exported/WebRTCOfferOptions.cpp index c05fb94f..a338e4d 100644 --- a/third_party/WebKit/Source/platform/exported/WebRTCOfferOptions.cpp +++ b/third_party/WebKit/Source/platform/exported/WebRTCOfferOptions.cpp
@@ -29,22 +29,22 @@ } int32_t WebRTCOfferOptions::OfferToReceiveVideo() const { - ASSERT(!IsNull()); + DCHECK(!IsNull()); return private_->OfferToReceiveVideo(); } int32_t WebRTCOfferOptions::OfferToReceiveAudio() const { - ASSERT(!IsNull()); + DCHECK(!IsNull()); return private_->OfferToReceiveAudio(); } bool WebRTCOfferOptions::VoiceActivityDetection() const { - ASSERT(!IsNull()); + DCHECK(!IsNull()); return private_->VoiceActivityDetection(); } bool WebRTCOfferOptions::IceRestart() const { - ASSERT(!IsNull()); + DCHECK(!IsNull()); return private_->IceRestart(); }
diff --git a/third_party/WebKit/Source/platform/exported/WebRTCSessionDescription.cpp b/third_party/WebKit/Source/platform/exported/WebRTCSessionDescription.cpp index 979468c3e..f253cef5 100644 --- a/third_party/WebKit/Source/platform/exported/WebRTCSessionDescription.cpp +++ b/third_party/WebKit/Source/platform/exported/WebRTCSessionDescription.cpp
@@ -81,22 +81,22 @@ } WebString WebRTCSessionDescription::GetType() const { - ASSERT(!private_.IsNull()); + DCHECK(!private_.IsNull()); return private_->GetType(); } void WebRTCSessionDescription::SetType(const WebString& type) { - ASSERT(!private_.IsNull()); + DCHECK(!private_.IsNull()); return private_->SetType(type); } WebString WebRTCSessionDescription::Sdp() const { - ASSERT(!private_.IsNull()); + DCHECK(!private_.IsNull()); return private_->Sdp(); } void WebRTCSessionDescription::SetSDP(const WebString& sdp) { - ASSERT(!private_.IsNull()); + DCHECK(!private_.IsNull()); return private_->SetSdp(sdp); }
diff --git a/third_party/WebKit/Source/platform/exported/WebRTCSessionDescriptionRequest.cpp b/third_party/WebKit/Source/platform/exported/WebRTCSessionDescriptionRequest.cpp index 285cb77..6098cd4 100644 --- a/third_party/WebKit/Source/platform/exported/WebRTCSessionDescriptionRequest.cpp +++ b/third_party/WebKit/Source/platform/exported/WebRTCSessionDescriptionRequest.cpp
@@ -51,13 +51,13 @@ void WebRTCSessionDescriptionRequest::RequestSucceeded( const WebRTCSessionDescription& session_description) const { - ASSERT(private_.Get()); + DCHECK(private_.Get()); private_->RequestSucceeded(session_description); } void WebRTCSessionDescriptionRequest::RequestFailed( const WebString& error) const { - ASSERT(private_.Get()); + DCHECK(private_.Get()); private_->RequestFailed(error); }
diff --git a/third_party/WebKit/Source/platform/exported/WebRTCStatsResponse.cpp b/third_party/WebKit/Source/platform/exported/WebRTCStatsResponse.cpp index 58ede93..b7aab27 100644 --- a/third_party/WebKit/Source/platform/exported/WebRTCStatsResponse.cpp +++ b/third_party/WebKit/Source/platform/exported/WebRTCStatsResponse.cpp
@@ -45,7 +45,7 @@ } void WebRTCStatsResponse::AddStats(const WebRTCLegacyStats& stats) { - ASSERT(!private_.IsNull()); + DCHECK(!private_.IsNull()); private_->AddStats(stats); }
diff --git a/third_party/WebKit/Source/platform/exported/WebScrollbarThemeClientImpl.cpp b/third_party/WebKit/Source/platform/exported/WebScrollbarThemeClientImpl.cpp index 235addec..226c041 100644 --- a/third_party/WebKit/Source/platform/exported/WebScrollbarThemeClientImpl.cpp +++ b/third_party/WebKit/Source/platform/exported/WebScrollbarThemeClientImpl.cpp
@@ -65,19 +65,19 @@ FrameViewBase* WebScrollbarThemeClientImpl::Parent() const { // Unused by Chromium scrollbar themes. - ASSERT_NOT_REACHED(); + NOTREACHED(); return 0; } FrameViewBase* WebScrollbarThemeClientImpl::Root() const { // Unused by Chromium scrollbar themes. - ASSERT_NOT_REACHED(); + NOTREACHED(); return 0; } void WebScrollbarThemeClientImpl::SetFrameRect(const IntRect&) { // Unused by Chromium scrollbar themes. - ASSERT_NOT_REACHED(); + NOTREACHED(); } IntRect WebScrollbarThemeClientImpl::FrameRect() const { @@ -86,12 +86,12 @@ void WebScrollbarThemeClientImpl::Invalidate() { // Unused by Chromium scrollbar themes. - ASSERT_NOT_REACHED(); + NOTREACHED(); } void WebScrollbarThemeClientImpl::InvalidateRect(const IntRect&) { // Unused by Chromium scrollbar themes. - ASSERT_NOT_REACHED(); + NOTREACHED(); } ScrollbarOverlayColorTheme @@ -116,7 +116,7 @@ IntPoint WebScrollbarThemeClientImpl::ConvertFromRootFrame( const IntPoint& point_in_root_frame) const { // Unused by Chromium scrollbar themes. - ASSERT_NOT_REACHED(); + NOTREACHED(); return point_in_root_frame; } @@ -165,11 +165,11 @@ } void WebScrollbarThemeClientImpl::StyleChanged() { - ASSERT_NOT_REACHED(); + NOTREACHED(); } void WebScrollbarThemeClientImpl::SetScrollbarsHidden(bool hidden) { - ASSERT_NOT_REACHED(); + NOTREACHED(); } bool WebScrollbarThemeClientImpl::Enabled() const { @@ -177,7 +177,7 @@ } void WebScrollbarThemeClientImpl::SetEnabled(bool) { - ASSERT_NOT_REACHED(); + NOTREACHED(); } bool WebScrollbarThemeClientImpl::IsOverlayScrollbar() const {
diff --git a/third_party/WebKit/Source/platform/exported/WebServiceWorkerRequest.cpp b/third_party/WebKit/Source/platform/exported/WebServiceWorkerRequest.cpp index 20404131..e1233d93 100644 --- a/third_party/WebKit/Source/platform/exported/WebServiceWorkerRequest.cpp +++ b/third_party/WebKit/Source/platform/exported/WebServiceWorkerRequest.cpp
@@ -108,7 +108,7 @@ WebReferrerPolicy referrer_policy) { // WebString doesn't have the distinction between empty and null. We use // the null WTFString for referrer. - ASSERT(Referrer::NoReferrer() == String()); + DCHECK_EQ(Referrer::NoReferrer(), String()); String referrer = web_referrer.IsEmpty() ? Referrer::NoReferrer() : String(web_referrer); private_->referrer_ =
diff --git a/third_party/WebKit/Source/platform/exported/WebStorageQuotaCallbacks.cpp b/third_party/WebKit/Source/platform/exported/WebStorageQuotaCallbacks.cpp index d966bb4..3768068 100644 --- a/third_party/WebKit/Source/platform/exported/WebStorageQuotaCallbacks.cpp +++ b/third_party/WebKit/Source/platform/exported/WebStorageQuotaCallbacks.cpp
@@ -23,7 +23,7 @@ void WebStorageQuotaCallbacks::DidQueryStorageUsageAndQuota( unsigned long long usage_in_bytes, unsigned long long quota_in_bytes) { - ASSERT(!private_.IsNull()); + DCHECK(!private_.IsNull()); private_->DidQueryStorageUsageAndQuota(usage_in_bytes, quota_in_bytes); private_.Reset(); } @@ -31,13 +31,13 @@ void WebStorageQuotaCallbacks::DidGrantStorageQuota( unsigned long long usage_in_bytes, unsigned long long granted_quota_in_bytes) { - ASSERT(!private_.IsNull()); + DCHECK(!private_.IsNull()); private_->DidGrantStorageQuota(usage_in_bytes, granted_quota_in_bytes); private_.Reset(); } void WebStorageQuotaCallbacks::DidFail(WebStorageQuotaError error) { - ASSERT(!private_.IsNull()); + DCHECK(!private_.IsNull()); private_->DidFail(error); private_.Reset(); }
diff --git a/third_party/WebKit/Source/platform/exported/WebURLRequest.cpp b/third_party/WebKit/Source/platform/exported/WebURLRequest.cpp index 0fbd502..e214fdd5 100644 --- a/third_party/WebKit/Source/platform/exported/WebURLRequest.cpp +++ b/third_party/WebKit/Source/platform/exported/WebURLRequest.cpp
@@ -162,7 +162,7 @@ void WebURLRequest::SetHTTPHeaderField(const WebString& name, const WebString& value) { - RELEASE_ASSERT(!DeprecatedEqualIgnoringCase(name, "referer")); + CHECK(!DeprecatedEqualIgnoringCase(name, "referer")); resource_request_->SetHTTPHeaderField(name, value); } @@ -170,7 +170,7 @@ WebReferrerPolicy referrer_policy) { // WebString doesn't have the distinction between empty and null. We use // the null WTFString for referrer. - ASSERT(Referrer::NoReferrer() == String()); + DCHECK_EQ(Referrer::NoReferrer(), String()); String referrer = web_referrer.IsEmpty() ? Referrer::NoReferrer() : String(web_referrer); resource_request_->SetHTTPReferrer(
diff --git a/third_party/WebKit/Source/platform/fonts/CharacterRange.h b/third_party/WebKit/Source/platform/fonts/CharacterRange.h index 56f4cca..e441747 100644 --- a/third_party/WebKit/Source/platform/fonts/CharacterRange.h +++ b/third_party/WebKit/Source/platform/fonts/CharacterRange.h
@@ -9,7 +9,7 @@ struct CharacterRange { CharacterRange(float from, float to) : start(from), end(to) { - ASSERT(start <= end); + DCHECK_LE(start, end); } float Width() const { return end - start; }
diff --git a/third_party/WebKit/Source/platform/fonts/Font.cpp b/third_party/WebKit/Source/platform/fonts/Font.cpp index bcbf112..81d4184 100644 --- a/third_party/WebKit/Source/platform/fonts/Font.cpp +++ b/third_party/WebKit/Source/platform/fonts/Font.cpp
@@ -162,7 +162,8 @@ // sub-run painting is not supported for Bidi text. const TextRun& run = run_info.run; - ASSERT((run_info.from == 0) && (run_info.to == run.length())); + DCHECK_EQ(run_info.from, 0u); + DCHECK_EQ(run_info.to, run.length()); BidiResolver<TextRunIterator, BidiCharacterRun> bidi_resolver; bidi_resolver.SetStatus( BidiStatus(run.Direction(), run.DirectionalOverride()));
diff --git a/third_party/WebKit/Source/platform/fonts/Font.h b/third_party/WebKit/Source/platform/fonts/Font.h index dcb2cc2..081e62ce 100644 --- a/third_party/WebKit/Source/platform/fonts/Font.h +++ b/third_party/WebKit/Source/platform/fonts/Font.h
@@ -205,12 +205,12 @@ inline Font::~Font() {} inline const SimpleFontData* Font::PrimaryFont() const { - ASSERT(font_fallback_list_); + DCHECK(font_fallback_list_); return font_fallback_list_->PrimarySimpleFontData(font_description_); } inline const FontData* Font::FontDataAt(unsigned index) const { - ASSERT(font_fallback_list_); + DCHECK(font_fallback_list_); return font_fallback_list_->FontDataAt(font_description_, index); }
diff --git a/third_party/WebKit/Source/platform/fonts/FontCache.cpp b/third_party/WebKit/Source/platform/fonts/FontCache.cpp index 8e681d84..b35f94b80 100644 --- a/third_party/WebKit/Source/platform/fonts/FontCache.cpp +++ b/third_party/WebKit/Source/platform/fonts/FontCache.cpp
@@ -223,7 +223,7 @@ result = it->value.get(); } - ASSERT(result); + DCHECK(result); return result; } @@ -293,7 +293,7 @@ #if DCHECK_IS_ON() if (should_retain == kDoNotRetain) - ASSERT(purge_prevent_count_); + DCHECK(purge_prevent_count_); #endif return g_font_data_cache->Get(platform_data, should_retain, @@ -332,7 +332,7 @@ } void FontCache::ReleaseFontData(const SimpleFontData* font_data) { - ASSERT(g_font_data_cache); + DCHECK(g_font_data_cache); g_font_data_cache->Release(font_data); } @@ -431,7 +431,7 @@ void FontCache::AddClient(FontCacheClient* client) { CHECK(client); - ASSERT(!FontCacheClients().Contains(client)); + DCHECK(!FontCacheClients().Contains(client)); FontCacheClients().insert(client); } @@ -443,7 +443,7 @@ void FontCache::Invalidate() { if (!g_invalidate_font_cache) { - ASSERT(!g_font_platform_data_cache); + DCHECK(!g_font_platform_data_cache); return; } @@ -484,7 +484,7 @@ void FontCache::DumpFontPlatformDataCache( base::trace_event::ProcessMemoryDump* memory_dump) { - ASSERT(IsMainThread()); + DCHECK(IsMainThread()); if (!g_font_platform_data_cache) return; base::trace_event::MemoryAllocatorDump* dump = @@ -498,7 +498,7 @@ void FontCache::DumpShapeResultCache( base::trace_event::ProcessMemoryDump* memory_dump) { - ASSERT(IsMainThread()); + DCHECK(IsMainThread()); if (!g_fallback_list_shaper_cache) { return; }
diff --git a/third_party/WebKit/Source/platform/fonts/FontCache.h b/third_party/WebKit/Source/platform/fonts/FontCache.h index e3e6fa37..a10b9bd3 100644 --- a/third_party/WebKit/Source/platform/fonts/FontCache.h +++ b/third_party/WebKit/Source/platform/fonts/FontCache.h
@@ -228,7 +228,7 @@ void DisablePurging() { purge_prevent_count_++; } void EnablePurging() { - ASSERT(purge_prevent_count_); + DCHECK(purge_prevent_count_); if (!--purge_prevent_count_) Purge(kPurgeIfNeeded); }
diff --git a/third_party/WebKit/Source/platform/fonts/FontCacheMemoryDumpProvider.cpp b/third_party/WebKit/Source/platform/fonts/FontCacheMemoryDumpProvider.cpp index 6df0454b..4d06df4 100644 --- a/third_party/WebKit/Source/platform/fonts/FontCacheMemoryDumpProvider.cpp +++ b/third_party/WebKit/Source/platform/fonts/FontCacheMemoryDumpProvider.cpp
@@ -17,7 +17,7 @@ bool FontCacheMemoryDumpProvider::OnMemoryDump( const base::trace_event::MemoryDumpArgs&, base::trace_event::ProcessMemoryDump* memory_dump) { - ASSERT(IsMainThread()); + DCHECK(IsMainThread()); FontCache::GetFontCache()->DumpFontPlatformDataCache(memory_dump); FontCache::GetFontCache()->DumpShapeResultCache(memory_dump); return true;
diff --git a/third_party/WebKit/Source/platform/fonts/FontDataCache.cpp b/third_party/WebKit/Source/platform/fonts/FontDataCache.cpp index b0409f8..6a87490 100644 --- a/third_party/WebKit/Source/platform/fonts/FontDataCache.cpp +++ b/third_party/WebKit/Source/platform/fonts/FontDataCache.cpp
@@ -77,7 +77,7 @@ } if (!result.Get()->value.second) { - ASSERT(inactive_font_data_.Contains(result.Get()->value.first)); + DCHECK(inactive_font_data_.Contains(result.Get()->value.first)); inactive_font_data_.erase(result.Get()->value.first); } @@ -98,14 +98,14 @@ } void FontDataCache::Release(const SimpleFontData* font_data) { - ASSERT(!font_data->IsCustomFont()); + DCHECK(!font_data->IsCustomFont()); Cache::iterator it = cache_.Find(&(font_data->PlatformData())); - ASSERT(it != cache_.end()); + DCHECK_NE(it, cache_.end()); if (it == cache_.end()) return; - ASSERT(it->value.second); + DCHECK(it->value.second); if (!--it->value.second) inactive_font_data_.insert(it->value.first); }
diff --git a/third_party/WebKit/Source/platform/fonts/FontDescription.cpp b/third_party/WebKit/Source/platform/fonts/FontDescription.cpp index 6d1672b..060ef8e2 100644 --- a/third_party/WebKit/Source/platform/fonts/FontDescription.cpp +++ b/third_party/WebKit/Source/platform/fonts/FontDescription.cpp
@@ -126,7 +126,7 @@ case kFontWeight900: return kFontWeight700; } - ASSERT_NOT_REACHED(); + NOTREACHED(); return kFontWeightNormal; } @@ -147,7 +147,7 @@ case kFontWeight900: return kFontWeight900; } - ASSERT_NOT_REACHED(); + NOTREACHED(); return kFontWeightNormal; }
diff --git a/third_party/WebKit/Source/platform/fonts/FontFaceCreationParams.h b/third_party/WebKit/Source/platform/fonts/FontFaceCreationParams.h index d899883..80facb8 100644 --- a/third_party/WebKit/Source/platform/fonts/FontFaceCreationParams.h +++ b/third_party/WebKit/Source/platform/fonts/FontFaceCreationParams.h
@@ -82,19 +82,19 @@ FontFaceCreationType CreationType() const { return creation_type_; } AtomicString Family() const { - ASSERT(creation_type_ == kCreateFontByFamily); + DCHECK_EQ(creation_type_, kCreateFontByFamily); return family_; } CString Filename() const { - ASSERT(creation_type_ == kCreateFontByFciIdAndTtcIndex); + DCHECK_EQ(creation_type_, kCreateFontByFciIdAndTtcIndex); return filename_; } int FontconfigInterfaceId() const { - ASSERT(creation_type_ == kCreateFontByFciIdAndTtcIndex); + DCHECK_EQ(creation_type_, kCreateFontByFciIdAndTtcIndex); return fontconfig_interface_id_; } int TtcIndex() const { - ASSERT(creation_type_ == kCreateFontByFciIdAndTtcIndex); + DCHECK_EQ(creation_type_, kCreateFontByFciIdAndTtcIndex); return ttc_index_; }
diff --git a/third_party/WebKit/Source/platform/fonts/FontFallbackIterator.cpp b/third_party/WebKit/Source/platform/fonts/FontFallbackIterator.cpp index 8f9441b..782f704a 100644 --- a/third_party/WebKit/Source/platform/fonts/FontFallbackIterator.cpp +++ b/third_party/WebKit/Source/platform/fonts/FontFallbackIterator.cpp
@@ -123,7 +123,7 @@ return AdoptRef(new FontDataForRangeSetFromCache(last_resort)); } - ASSERT(fallback_stage_ == kFontGroupFonts || + DCHECK(fallback_stage_ == kFontGroupFonts || fallback_stage_ == kSegmentedFace); const FontData* font_data = font_fallback_list_->FontDataAt( font_description_, current_font_data_index_); @@ -163,7 +163,7 @@ fallback_stage_ = kSegmentedFace; } - ASSERT(segmented_face_index_ < segmented->NumFaces()); + DCHECK_LT(segmented_face_index_, segmented->NumFaces()); RefPtr<FontDataForRangeSet> current_segmented_face = segmented->FaceAt(segmented_face_index_); segmented_face_index_++;
diff --git a/third_party/WebKit/Source/platform/fonts/FontFallbackList.cpp b/third_party/WebKit/Source/platform/fonts/FontFallbackList.cpp index 834d8bfb..a4f337d 100644 --- a/third_party/WebKit/Source/platform/fonts/FontFallbackList.cpp +++ b/third_party/WebKit/Source/platform/fonts/FontFallbackList.cpp
@@ -63,7 +63,7 @@ unsigned num_fonts = font_list_.size(); for (unsigned i = 0; i < num_fonts; ++i) { if (!font_list_[i]->IsCustomFont()) { - ASSERT(!font_list_[i]->IsSegmented()); + DCHECK(!font_list_[i]->IsSegmented()); FontCache::GetFontCache()->ReleaseFontData( ToSimpleFontData(font_list_[i])); } @@ -111,7 +111,7 @@ FontCache::GetFontCache() ->GetLastResortFallbackFont(font_description) .Get(); - ASSERT(last_resort_fallback); + DCHECK(last_resort_fallback); return last_resort_fallback; } @@ -121,7 +121,7 @@ const SimpleFontData* font_data_for_space = font_data->FontDataForCharacter(kSpaceCharacter); - ASSERT(font_data_for_space); + DCHECK(font_data_for_space); // When a custom font is loading, we should use the correct fallback font to // layout the text. Here skip the temporary font for the loading custom @@ -222,7 +222,7 @@ .Get(); // This fallback font is already in our list. // Make sure we're not passing in some crazy value here. - ASSERT(realized_font_index == font_list_.size()); + DCHECK_EQ(realized_font_index, font_list_.size()); if (family_index_ == kCAllFamiliesScanned) return 0; @@ -232,7 +232,7 @@ // families we've looked at before in |m_familyIndex|, so that we never scan // the same spot in the list twice. getFontData will adjust our // |m_familyIndex| as it scans for the right font to make. - ASSERT(FontCache::GetFontCache()->Generation() == generation_); + DCHECK_EQ(FontCache::GetFontCache()->Generation(), generation_); RefPtr<FontData> result = GetFontData(font_description, family_index_); if (result) { font_list_.push_back(result);
diff --git a/third_party/WebKit/Source/platform/fonts/FontFallbackList.h b/third_party/WebKit/Source/platform/fonts/FontFallbackList.h index eb31073..31355570 100644 --- a/third_party/WebKit/Source/platform/fonts/FontFallbackList.h +++ b/third_party/WebKit/Source/platform/fonts/FontFallbackList.h
@@ -63,7 +63,7 @@ shape_cache_ = FontCache::GetFontCache()->GetShapeCache(key)->GetWeakPtr(); } - ASSERT(shape_cache_); + DCHECK(shape_cache_); if (GetFontSelector()) shape_cache_->ClearIfVersionChanged(GetFontSelector()->Version()); return shape_cache_.get(); @@ -71,11 +71,11 @@ const SimpleFontData* PrimarySimpleFontData( const FontDescription& font_description) { - ASSERT(IsMainThread()); + DCHECK(IsMainThread()); if (!cached_primary_simple_font_data_) { cached_primary_simple_font_data_ = DeterminePrimarySimpleFontData(font_description); - ASSERT(cached_primary_simple_font_data_); + DCHECK(cached_primary_simple_font_data_); } return cached_primary_simple_font_data_; }
diff --git a/third_party/WebKit/Source/platform/fonts/FontPlatformData.cpp b/third_party/WebKit/Source/platform/fonts/FontPlatformData.cpp index 5adff1a..f279715 100644 --- a/third_party/WebKit/Source/platform/fonts/FontPlatformData.cpp +++ b/third_party/WebKit/Source/platform/fonts/FontPlatformData.cpp
@@ -223,7 +223,7 @@ } String FontPlatformData::FontFamilyName() const { - ASSERT(this->Typeface()); + DCHECK(this->Typeface()); SkTypeface::LocalizedStrings* font_family_iterator = this->Typeface()->createFamilyNameIterator(); SkTypeface::LocalizedString localized_string; @@ -266,9 +266,9 @@ return false; hb_font_t* font = hb_face->GetScaledFont(); - ASSERT(font); + DCHECK(font); hb_face_t* face = hb_font_get_face(font); - ASSERT(face); + DCHECK(face); hb_codepoint_t space; // If the space glyph isn't present in the font then each space character
diff --git a/third_party/WebKit/Source/platform/fonts/GlyphMetricsMap.h b/third_party/WebKit/Source/platform/fonts/GlyphMetricsMap.h index 40bb323..aeb8dde 100644 --- a/third_party/WebKit/Source/platform/fonts/GlyphMetricsMap.h +++ b/third_party/WebKit/Source/platform/fonts/GlyphMetricsMap.h
@@ -112,7 +112,7 @@ GlyphMetricsMap<T>::LocatePageSlowCase(unsigned page_number) { GlyphMetricsPage* page; if (!page_number) { - ASSERT(!filled_primary_page_); + DCHECK(!filled_primary_page_); page = &primary_page_; filled_primary_page_ = true; } else {
diff --git a/third_party/WebKit/Source/platform/fonts/OrientationIterator.cpp b/third_party/WebKit/Source/platform/fonts/OrientationIterator.cpp index 191ea419..2786a6d 100644 --- a/third_party/WebKit/Source/platform/fonts/OrientationIterator.cpp +++ b/third_party/WebKit/Source/platform/fonts/OrientationIterator.cpp
@@ -16,7 +16,7 @@ at_end_(buffer_size == 0) { // There's not much point in segmenting by isUprightInVertical if the text // orientation is not "mixed". - ASSERT(run_orientation == FontOrientation::kVerticalMixed); + DCHECK_EQ(run_orientation, FontOrientation::kVerticalMixed); } bool OrientationIterator::Consume(unsigned* orientation_limit,
diff --git a/third_party/WebKit/Source/platform/fonts/OrientationIteratorTest.cpp b/third_party/WebKit/Source/platform/fonts/OrientationIteratorTest.cpp index d33b8bcb..68be8f9 100644 --- a/third_party/WebKit/Source/platform/fonts/OrientationIteratorTest.cpp +++ b/third_party/WebKit/Source/platform/fonts/OrientationIteratorTest.cpp
@@ -66,7 +66,7 @@ unsigned limit = 0; OrientationIterator::RenderOrientation orientation = OrientationIterator::kOrientationInvalid; - ASSERT(!orientation_iterator.Consume(&limit, &orientation)); + DCHECK(!orientation_iterator.Consume(&limit, &orientation)); ASSERT_EQ(limit, 0u); ASSERT_EQ(orientation, OrientationIterator::kOrientationInvalid); }
diff --git a/third_party/WebKit/Source/platform/fonts/ScriptRunIterator.cpp b/third_party/WebKit/Source/platform/fonts/ScriptRunIterator.cpp index 506b1aa..1b7ccf1 100644 --- a/third_party/WebKit/Source/platform/fonts/ScriptRunIterator.cpp +++ b/third_party/WebKit/Source/platform/fonts/ScriptRunIterator.cpp
@@ -124,8 +124,8 @@ ahead_pos_(0), common_preferred_(USCRIPT_COMMON), script_data_(data) { - ASSERT(text); - ASSERT(data); + DCHECK(text); + DCHECK(data); if (ahead_pos_ < length_) { current_set_.Clear();
diff --git a/third_party/WebKit/Source/platform/fonts/ScriptRunIteratorTest.cpp b/third_party/WebKit/Source/platform/fonts/ScriptRunIteratorTest.cpp index f843def2..3a79c70 100644 --- a/third_party/WebKit/Source/platform/fonts/ScriptRunIteratorTest.cpp +++ b/third_party/WebKit/Source/platform/fonts/ScriptRunIteratorTest.cpp
@@ -37,8 +37,8 @@ } void GetScripts(UChar32 ch, Vector<UScriptCode>& dst) const override { - ASSERT(ch >= kMockCharMin); - ASSERT(ch < kMockCharLimit); + DCHECK_GE(ch, kMockCharMin); + DCHECK_LT(ch, kMockCharLimit); int code = ch - kMockCharMin; dst.Clear(); @@ -87,7 +87,8 @@ } PairedBracketType GetPairedBracketType(UChar32 ch) const override { - ASSERT(ch >= kMockCharMin && ch < kMockCharLimit); + DCHECK_GE(ch, kMockCharMin); + DCHECK_LT(ch, kMockCharLimit); int code = ch - kMockCharMin; if ((code & kCodeBracketBit) == 0) { return PairedBracketType::kBracketTypeNone; @@ -119,56 +120,56 @@ if (in_set) { switch (c) { case '(': - ASSERT(seen == 0); + DCHECK_EQ(seen, 0); seen |= kSawBracket; code |= kCodeBracketBit; break; case '[': - ASSERT(seen == 0); + DCHECK_EQ(seen, 0); seen |= kSawBracket; code |= kCodeBracketBit | kCodeSquareBracketBit; break; case ')': - ASSERT(seen == 0); + DCHECK_EQ(seen, 0); seen |= kSawBracket; code |= kCodeBracketBit | kCodeBracketCloseBit; break; case ']': - ASSERT(seen == 0); + DCHECK_EQ(seen, 0); seen |= kSawBracket; code |= kCodeBracketBit | kCodeSquareBracketBit | kCodeBracketCloseBit; break; case 'i': - ASSERT(seen == 0); // brackets can't be inherited + DCHECK_EQ(seen, 0); // brackets can't be inherited seen |= kSawSpecial; code |= kCodeSpecialInherited; break; case 'c': - ASSERT((seen & ~kSawBracket) == 0); + DCHECK_EQ((seen & ~kSawBracket), 0); seen |= kSawSpecial; code |= kCodeSpecialCommon; break; case 'l': - ASSERT((seen & kSawLatin) == 0); - ASSERT(current_shift < 3); + DCHECK_EQ((seen & kSawLatin), 0); + DCHECK_LT(current_shift, 3); seen |= kSawLatin; list |= kLatin << (2 * current_shift++); break; case 'h': - ASSERT((seen & kSawHan) == 0); - ASSERT(current_shift < 3); + DCHECK_EQ((seen & kSawHan), 0); + DCHECK_LT(current_shift, 3); seen |= kSawHan; list |= kHan << (2 * current_shift++); break; case 'g': - ASSERT((seen & kSawGreek) == 0); - ASSERT(current_shift < 3); + DCHECK_EQ((seen & kSawGreek), 0); + DCHECK_LT(current_shift, 3); seen |= kSawGreek; list |= kGreek << (2 * current_shift++); break; case '>': - ASSERT(seen != 0); + DCHECK_NE(seen, 0); code |= TableLookup(list); result.Append(static_cast<UChar>(kMockCharMin + code)); in_set = false; @@ -333,7 +334,7 @@ ScriptRunIterator script_run_iterator(empty.Characters16(), empty.length()); unsigned limit = 0; UScriptCode code = USCRIPT_INVALID_CODE; - ASSERT(!script_run_iterator.Consume(limit, code)); + DCHECK(!script_run_iterator.Consume(limit, code)); ASSERT_EQ(limit, 0u); ASSERT_EQ(code, USCRIPT_INVALID_CODE); }
diff --git a/third_party/WebKit/Source/platform/fonts/SimpleFontData.cpp b/third_party/WebKit/Source/platform/fonts/SimpleFontData.cpp index 28563c9..ba858b4 100644 --- a/third_party/WebKit/Source/platform/fonts/SimpleFontData.cpp +++ b/third_party/WebKit/Source/platform/fonts/SimpleFontData.cpp
@@ -96,7 +96,7 @@ paint_.setTextEncoding(SkPaint::kGlyphID_TextEncoding); paint_.getFontMetrics(&metrics); SkTypeface* face = paint_.getTypeface(); - ASSERT(face); + DCHECK(face); int vdmx_ascent = 0, vdmx_descent = 0; bool is_vdmx_valid = false; @@ -290,7 +290,7 @@ Glyph SimpleFontData::GlyphForCharacter(UChar32 codepoint) const { uint16_t glyph; SkTypeface* typeface = PlatformData().Typeface(); - RELEASE_ASSERT(typeface); + CHECK(typeface); typeface->charsToGlyphs(&codepoint, SkTypeface::kUTF32_Encoding, &glyph, 1); return glyph; }
diff --git a/third_party/WebKit/Source/platform/fonts/SimpleFontData.h b/third_party/WebKit/Source/platform/fonts/SimpleFontData.h index e867b95..2af2e28 100644 --- a/third_party/WebKit/Source/platform/fonts/SimpleFontData.h +++ b/third_party/WebKit/Source/platform/fonts/SimpleFontData.h
@@ -95,7 +95,7 @@ case kNormalVariant: break; } - ASSERT_NOT_REACHED(); + NOTREACHED(); return const_cast<SimpleFontData*>(this); }
diff --git a/third_party/WebKit/Source/platform/fonts/SmallCapsIteratorTest.cpp b/third_party/WebKit/Source/platform/fonts/SmallCapsIteratorTest.cpp index 4e5994c..5c69e6e 100644 --- a/third_party/WebKit/Source/platform/fonts/SmallCapsIteratorTest.cpp +++ b/third_party/WebKit/Source/platform/fonts/SmallCapsIteratorTest.cpp
@@ -67,7 +67,7 @@ unsigned limit = 0; SmallCapsIterator::SmallCapsBehavior small_caps_behavior = SmallCapsIterator::kSmallCapsInvalid; - ASSERT(!small_caps_iterator.Consume(&limit, &small_caps_behavior)); + DCHECK(!small_caps_iterator.Consume(&limit, &small_caps_behavior)); ASSERT_EQ(limit, 0u); ASSERT_EQ(small_caps_behavior, SmallCapsIterator::kSmallCapsInvalid); }
diff --git a/third_party/WebKit/Source/platform/fonts/SymbolsIteratorTest.cpp b/third_party/WebKit/Source/platform/fonts/SymbolsIteratorTest.cpp index 3b72f1d..569d80d41 100644 --- a/third_party/WebKit/Source/platform/fonts/SymbolsIteratorTest.cpp +++ b/third_party/WebKit/Source/platform/fonts/SymbolsIteratorTest.cpp
@@ -67,7 +67,7 @@ SymbolsIterator symbols_iterator(empty.Characters16(), empty.length()); unsigned limit = 0; FontFallbackPriority symbols_font = FontFallbackPriority::kInvalid; - ASSERT(!symbols_iterator.Consume(&limit, &symbols_font)); + DCHECK(!symbols_iterator.Consume(&limit, &symbols_font)); ASSERT_EQ(limit, 0u); ASSERT_EQ(symbols_font, FontFallbackPriority::kInvalid); }
diff --git a/third_party/WebKit/Source/platform/fonts/UTF16TextIterator.cpp b/third_party/WebKit/Source/platform/fonts/UTF16TextIterator.cpp index 76ddb07..70d0b31 100644 --- a/third_party/WebKit/Source/platform/fonts/UTF16TextIterator.cpp +++ b/third_party/WebKit/Source/platform/fonts/UTF16TextIterator.cpp
@@ -53,7 +53,7 @@ } bool UTF16TextIterator::ConsumeSurrogatePair(UChar32& character) { - ASSERT(U16_IS_SURROGATE(character)); + DCHECK(U16_IS_SURROGATE(character)); if (!IsValidSurrogatePair(character)) { character = kReplacementCharacter;
diff --git a/third_party/WebKit/Source/platform/fonts/mac/FontFamilyMatcherMac.mm b/third_party/WebKit/Source/platform/fonts/mac/FontFamilyMatcherMac.mm index 32bba2f..2745db4 100644 --- a/third_party/WebKit/Source/platform/fonts/mac/FontFamilyMatcherMac.mm +++ b/third_party/WebKit/Source/platform/fonts/mac/FontFamilyMatcherMac.mm
@@ -57,7 +57,8 @@ 0x3fe1eb8520000000, // NSFontWeightHeavy 0x3fe3d70a40000000, // NSFontWeightBlack }; - ASSERT(fontWeight >= 0 && fontWeight <= 8); + DCHECK_GE(fontWeight, 0); + DCHECK_LE(fontWeight, 8); CGFloat* weight = reinterpret_cast<CGFloat*>(&nsFontWeights[fontWeight]); return *weight; }
diff --git a/third_party/WebKit/Source/platform/fonts/mac/FontPlatformDataMac.mm b/third_party/WebKit/Source/platform/fonts/mac/FontPlatformDataMac.mm index f4e6100..e30cd8f 100644 --- a/third_party/WebKit/Source/platform/fonts/mac/FontPlatformDataMac.mm +++ b/third_party/WebKit/Source/platform/fonts/mac/FontPlatformDataMac.mm
@@ -82,7 +82,7 @@ // This function should only be called in response to an error loading a // font due to being blocked by the sandbox. // This by definition shouldn't happen if there is no sandbox support. - ASSERT_NOT_REACHED(); + NOTREACHED(); return nullptr; }
diff --git a/third_party/WebKit/Source/platform/fonts/opentype/OpenTypeCapsSupport.cpp b/third_party/WebKit/Source/platform/fonts/opentype/OpenTypeCapsSupport.cpp index 6a9a06a..cc13286 100644 --- a/third_party/WebKit/Source/platform/fonts/opentype/OpenTypeCapsSupport.cpp +++ b/third_party/WebKit/Source/platform/fonts/opentype/OpenTypeCapsSupport.cpp
@@ -155,7 +155,7 @@ } break; default: - ASSERT_NOT_REACHED(); + NOTREACHED(); } }
diff --git a/third_party/WebKit/Source/platform/fonts/opentype/OpenTypeCapsSupportMPL.cpp b/third_party/WebKit/Source/platform/fonts/opentype/OpenTypeCapsSupportMPL.cpp index 98add31..9fd3a16a 100644 --- a/third_party/WebKit/Source/platform/fonts/opentype/OpenTypeCapsSupportMPL.cpp +++ b/third_party/WebKit/Source/platform/fonts/opentype/OpenTypeCapsSupportMPL.cpp
@@ -15,9 +15,9 @@ bool OpenTypeCapsSupport::SupportsOpenTypeFeature(hb_script_t script, uint32_t tag) const { hb_face_t* face = hb_font_get_face(harf_buzz_face_->GetScaledFont()); - ASSERT(face); + DCHECK(face); - ASSERT( + DCHECK( (tag == HB_TAG('s', 'm', 'c', 'p') || tag == HB_TAG('c', '2', 's', 'c') || tag == HB_TAG('p', 'c', 'a', 'p') || tag == HB_TAG('c', '2', 'p', 'c') || tag == HB_TAG('s', 'u', 'p', 's') || tag == HB_TAG('s', 'u', 'b', 's') ||
diff --git a/third_party/WebKit/Source/platform/fonts/opentype/OpenTypeVerticalData.cpp b/third_party/WebKit/Source/platform/fonts/opentype/OpenTypeVerticalData.cpp index 4fa0345..53792557 100644 --- a/third_party/WebKit/Source/platform/fonts/opentype/OpenTypeVerticalData.cpp +++ b/third_party/WebKit/Source/platform/fonts/opentype/OpenTypeVerticalData.cpp
@@ -245,7 +245,7 @@ size_t count, float* out_xy_array) const { size_t count_widths = advance_widths_.size(); - ASSERT(count_widths > 0); + DCHECK_GT(count_widths, 0u); const FontMetrics& metrics = font->GetFontMetrics(); float size_per_unit = font->SizePerUnit(); float ascent = metrics.Ascent();
diff --git a/third_party/WebKit/Source/platform/fonts/shaping/CachingWordShapeIterator.h b/third_party/WebKit/Source/platform/fonts/shaping/CachingWordShapeIterator.h index ecdbd0d3..ec785260 100644 --- a/third_party/WebKit/Source/platform/fonts/shaping/CachingWordShapeIterator.h +++ b/third_party/WebKit/Source/platform/fonts/shaping/CachingWordShapeIterator.h
@@ -50,7 +50,7 @@ spacing_(run, font->GetFontDescription()), width_so_far_(0), start_index_(0) { - ASSERT(font); + DCHECK(font); // Shaping word by word is faster as each word is cached. If we cannot // use the cache or if the font doesn't support word by word shaping @@ -155,7 +155,7 @@ if (!start_index_ && end_index == length) { *result = ShapeWord(text_run_, font_); } else { - ASSERT(end_index <= length); + DCHECK_LE(end_index, length); TextRun sub_run = text_run_.SubRun(start_index_, end_index - start_index_); *result = ShapeWord(sub_run, font_); @@ -166,7 +166,7 @@ unsigned EndIndexUntil(UChar ch) const { unsigned length = text_run_.length(); - ASSERT(start_index_ < length); + DCHECK_LT(start_index_, length); for (unsigned i = start_index_ + 1;; i++) { if (i == length || text_run_[i] == ch) return i; @@ -194,7 +194,7 @@ if (!NextWord(word_result)) return false; } - ASSERT(*word_result); + DCHECK(*word_result); width_so_far_ += (*word_result)->Width(); return true; }
diff --git a/third_party/WebKit/Source/platform/fonts/shaping/CaseMappingHarfBuzzBufferFiller.cpp b/third_party/WebKit/Source/platform/fonts/shaping/CaseMappingHarfBuzzBufferFiller.cpp index 1a4e830..157a8e66 100644 --- a/third_party/WebKit/Source/platform/fonts/shaping/CaseMappingHarfBuzzBufferFiller.cpp +++ b/third_party/WebKit/Source/platform/fonts/shaping/CaseMappingHarfBuzzBufferFiller.cpp
@@ -43,8 +43,8 @@ return; } - ASSERT(case_mapped_text.length() == buffer_length); - ASSERT(!case_mapped_text.Is8Bit()); + DCHECK_EQ(case_mapped_text.length(), buffer_length); + DCHECK(!case_mapped_text.Is8Bit()); hb_buffer_add_utf16(harf_buzz_buffer_, ToUint16(case_mapped_text.Characters16()), buffer_length, start_index, num_characters);
diff --git a/third_party/WebKit/Source/platform/fonts/shaping/HarfBuzzFace.cpp b/third_party/WebKit/Source/platform/fonts/shaping/HarfBuzzFace.cpp index 83af925..133c195 100644 --- a/third_party/WebKit/Source/platform/fonts/shaping/HarfBuzzFace.cpp +++ b/third_party/WebKit/Source/platform/fonts/shaping/HarfBuzzFace.cpp
@@ -114,7 +114,7 @@ class HbFontCacheEntry : public RefCounted<HbFontCacheEntry> { public: static PassRefPtr<HbFontCacheEntry> Create(hb_font_t* hb_font) { - ASSERT(hb_font); + DCHECK(hb_font); return AdoptRef(new HbFontCacheEntry(hb_font)); } @@ -159,7 +159,7 @@ HarfBuzzFace::~HarfBuzzFace() { HarfBuzzFontCache::iterator result = GetHarfBuzzFontCache()->Find(unique_id_); SECURITY_DCHECK(result != GetHarfBuzzFontCache()->end()); - ASSERT(result.Get()->value->RefCount() > 1); + DCHECK_GT(result.Get()->value->RefCount(), 1); result.Get()->value->Deref(); if (result.Get()->value->RefCount() == 1) GetHarfBuzzFontCache()->erase(unique_id_); @@ -180,7 +180,7 @@ HarfBuzzFontData* hb_font_data = reinterpret_cast<HarfBuzzFontData*>(font_data); - RELEASE_ASSERT(hb_font_data); + CHECK(hb_font_data); if (hb_font_data->range_set_ && !hb_font_data->range_set_->Contains(unicode)) return false; @@ -372,7 +372,7 @@ zero_copy_success_histogram.Count(true); } #endif - ASSERT(face); + DCHECK(face); return face; } @@ -407,7 +407,7 @@ harf_buzz_font_data_->range_set_ = std::move(range_set); harf_buzz_font_data_->UpdateSimpleFontData(platform_data_); - ASSERT(harf_buzz_font_data_->simple_font_data_); + DCHECK(harf_buzz_font_data_->simple_font_data_); int scale = SkiaScalarToHarfBuzzPosition(platform_data_->size()); hb_font_set_scale(unscaled_font_, scale, scale);
diff --git a/third_party/WebKit/Source/platform/fonts/shaping/HarfBuzzShaper.cpp b/third_party/WebKit/Source/platform/fonts/shaping/HarfBuzzShaper.cpp index df76993..ea99800 100644 --- a/third_party/WebKit/Source/platform/fonts/shaping/HarfBuzzShaper.cpp +++ b/third_party/WebKit/Source/platform/fonts/shaping/HarfBuzzShaper.cpp
@@ -72,7 +72,7 @@ HarfBuzzScopedPtr(T* ptr, DestroyFunction destroy) : ptr_(ptr), destroy_(destroy) { - ASSERT(destroy_); + DCHECK(destroy_); } ~HarfBuzzScopedPtr() { if (ptr_) @@ -259,7 +259,7 @@ } // Here we need to put character positions. - ASSERT(num_characters); + DCHECK(num_characters); range_data->holes_queue.push_back( HolesQueueItem(kHolesQueueRange, start_index, num_characters)); } @@ -315,7 +315,7 @@ break; UChar32 hint_char; - RELEASE_ASSERT(it->start_index_ + it->num_characters_ <= text_length_); + CHECK_LE((it->start_index_ + it->num_characters_), text_length_); UTF16TextIterator iterator(text_ + it->start_index_, it->num_characters_); while (iterator.Consume(hint_char)) { hint.push_back(hint_char);
diff --git a/third_party/WebKit/Source/platform/fonts/shaping/RunSegmenter.cpp b/third_party/WebKit/Source/platform/fonts/shaping/RunSegmenter.cpp index 0f1b1c9..2ff7daf 100644 --- a/third_party/WebKit/Source/platform/fonts/shaping/RunSegmenter.cpp +++ b/third_party/WebKit/Source/platform/fonts/shaping/RunSegmenter.cpp
@@ -37,7 +37,7 @@ at_end_(false) {} void RunSegmenter::ConsumeScriptIteratorPastLastSplit() { - ASSERT(script_run_iterator_); + DCHECK(script_run_iterator_); if (script_run_iterator_position_ <= last_split_ && script_run_iterator_position_ < buffer_size_) { while (script_run_iterator_->Consume(script_run_iterator_position_, @@ -61,7 +61,7 @@ } void RunSegmenter::ConsumeSymbolsIteratorPastLastSplit() { - ASSERT(symbols_iterator_); + DCHECK(symbols_iterator_); if (symbols_iterator_position_ <= last_split_ && symbols_iterator_position_ < buffer_size_) { while (
diff --git a/third_party/WebKit/Source/platform/fonts/shaping/RunSegmenterTest.cpp b/third_party/WebKit/Source/platform/fonts/shaping/RunSegmenterTest.cpp index 4150ec56..6eff95a 100644 --- a/third_party/WebKit/Source/platform/fonts/shaping/RunSegmenterTest.cpp +++ b/third_party/WebKit/Source/platform/fonts/shaping/RunSegmenterTest.cpp
@@ -96,7 +96,7 @@ 0, 0, USCRIPT_INVALID_CODE, OrientationIterator::kOrientationKeep}; RunSegmenter run_segmenter(empty.Characters16(), empty.length(), FontOrientation::kVerticalMixed); - ASSERT(!run_segmenter.Consume(&segmenter_range)); + DCHECK(!run_segmenter.Consume(&segmenter_range)); ASSERT_EQ(segmenter_range.start, 0u); ASSERT_EQ(segmenter_range.end, 0u); ASSERT_EQ(segmenter_range.script, USCRIPT_INVALID_CODE);
diff --git a/third_party/WebKit/Source/platform/fonts/shaping/ShapeCache.h b/third_party/WebKit/Source/platform/fonts/shaping/ShapeCache.h index 58c2145..703cf4455 100644 --- a/third_party/WebKit/Source/platform/fonts/shaping/ShapeCache.h +++ b/third_party/WebKit/Source/platform/fonts/shaping/ShapeCache.h
@@ -70,7 +70,7 @@ unsigned short length, TextDirection direction) : length_(length), direction_(static_cast<unsigned>(direction)) { - ASSERT(length <= kCapacity); + DCHECK(length <= kCapacity); StringHasher hasher;
diff --git a/third_party/WebKit/Source/platform/fonts/shaping/ShapeResult.cpp b/third_party/WebKit/Source/platform/fonts/shaping/ShapeResult.cpp index 600f9d8..bd1254ae 100644 --- a/third_party/WebKit/Source/platform/fonts/shaping/ShapeResult.cpp +++ b/third_party/WebKit/Source/platform/fonts/shaping/ShapeResult.cpp
@@ -43,7 +43,7 @@ float ShapeResult::RunInfo::XPositionForVisualOffset( unsigned offset, AdjustMidCluster adjust_mid_cluster) const { - ASSERT(offset < num_characters_); + DCHECK_LT(offset, num_characters_); if (Rtl()) offset = num_characters_ - offset - 1; return XPositionForOffset(offset, adjust_mid_cluster); @@ -52,7 +52,7 @@ float ShapeResult::RunInfo::XPositionForOffset( unsigned offset, AdjustMidCluster adjust_mid_cluster) const { - ASSERT(offset <= num_characters_); + DCHECK_LE(offset, num_characters_); const unsigned num_glyphs = glyph_data_.size(); unsigned glyph_index = 0; float position = 0; @@ -268,8 +268,8 @@ void ShapeResult::FallbackFonts( HashSet<const SimpleFontData*>* fallback) const { - ASSERT(fallback); - ASSERT(primary_font_); + DCHECK(fallback); + DCHECK(primary_font_); for (unsigned i = 0; i < runs_.size(); ++i) { if (runs_[i] && runs_[i]->font_data_ && runs_[i]->font_data_ != primary_font_ && @@ -342,9 +342,9 @@ unsigned start_glyph, unsigned num_glyphs, hb_buffer_t* harf_buzz_buffer) { - ASSERT(num_glyphs > 0); + DCHECK_GT(num_glyphs, 0u); std::unique_ptr<ShapeResult::RunInfo> run(std::move(run_to_insert)); - ASSERT(num_glyphs == run->glyph_data_.size()); + DCHECK_EQ(num_glyphs, run->glyph_data_.size()); const SimpleFontData* current_font_data = run->font_data_.Get(); const hb_glyph_info_t* glyph_infos = @@ -393,7 +393,7 @@ run->width_ = std::max(0.0f, total_advance); width_ += run->width_; num_glyphs_ += num_glyphs; - ASSERT(num_glyphs_ >= num_glyphs); + DCHECK_GE(num_glyphs_, num_glyphs); has_vertical_offsets_ |= has_vertical_offsets; // The runs are stored in result->m_runs in visual order. For LTR, we place
diff --git a/third_party/WebKit/Source/platform/fonts/shaping/ShapeResultBuffer.cpp b/third_party/WebKit/Source/platform/fonts/shaping/ShapeResultBuffer.cpp index b7ffc7c..dd2f90e7 100644 --- a/third_party/WebKit/Source/platform/fonts/shaping/ShapeResultBuffer.cpp +++ b/third_party/WebKit/Source/platform/fonts/shaping/ShapeResultBuffer.cpp
@@ -73,7 +73,7 @@ end_index = temp_index; } uint16_t length = end_index - start_index; - ASSERT(static_cast<unsigned>(start_index + length) <= str_length); + DCHECK_LE(static_cast<unsigned>(start_index + length), str_length); TextBreakIterator* cursor_pos_iterator = CursorMovementIterator(&str[start_index], length); @@ -468,7 +468,7 @@ continue; int offset_for_word = word_result->OffsetForPosition(target_x, include_partial_glyphs); - ASSERT(offset_for_word >= 0); + DCHECK_GE(offset_for_word, 0); total_offset += offset_for_word; if (target_x >= 0 && target_x <= word_result->Width()) return total_offset;
diff --git a/third_party/WebKit/Source/platform/fonts/shaping/ShapeResultSpacing.cpp b/third_party/WebKit/Source/platform/fonts/shaping/ShapeResultSpacing.cpp index 153fb4a..4f9c362be 100644 --- a/third_party/WebKit/Source/platform/fonts/shaping/ShapeResultSpacing.cpp +++ b/third_party/WebKit/Source/platform/fonts/shaping/ShapeResultSpacing.cpp
@@ -42,7 +42,7 @@ expansion_opportunity_count_ = Character::ExpansionOpportunityCount(run, is_after_expansion); if (is_after_expansion && !run.AllowsTrailingExpansion()) { - ASSERT(expansion_opportunity_count_ > 0); + DCHECK_GT(expansion_opportunity_count_, 0u); --expansion_opportunity_count_; } @@ -52,7 +52,7 @@ float ShapeResultSpacing::NextExpansion() { if (!expansion_opportunity_count_) { - ASSERT_NOT_REACHED(); + NOTREACHED(); return 0; }
diff --git a/third_party/WebKit/Source/platform/fonts/skia/FontCacheSkia.cpp b/third_party/WebKit/Source/platform/fonts/skia/FontCacheSkia.cpp index d41fde6..7aafcf3 100644 --- a/third_party/WebKit/Source/platform/fonts/skia/FontCacheSkia.cpp +++ b/third_party/WebKit/Source/platform/fonts/skia/FontCacheSkia.cpp
@@ -84,7 +84,7 @@ UChar32 c, const FontDescription& font_description, FontFallbackPriority fallback_priority) { - ASSERT(fm); + DCHECK(fm); const size_t kMaxLocales = 4; const char* bcp47_locales[kMaxLocales]; @@ -211,7 +211,7 @@ } #endif - ASSERT(font_platform_data); + DCHECK(font_platform_data); return FontDataFromFontPlatformData(font_platform_data, should_retain); }
diff --git a/third_party/WebKit/Source/platform/fonts/win/FontCacheSkiaWin.cpp b/third_party/WebKit/Source/platform/fonts/win/FontCacheSkiaWin.cpp index d230a9a..be25c3a6 100644 --- a/third_party/WebKit/Source/platform/fonts/win/FontCacheSkiaWin.cpp +++ b/third_party/WebKit/Source/platform/fonts/win/FontCacheSkiaWin.cpp
@@ -105,7 +105,7 @@ font_manager_ = sk_ref_sp(static_font_manager_); if (!font_manager_) font_manager_ = SkFontMgr_New_DirectWrite(); - ASSERT(font_manager_.get()); + DCHECK(font_manager_.get()); } // Given the desired base font, this will create a SimpleFontData for a specific @@ -336,7 +336,7 @@ const FontFaceCreationParams& creation_params, float font_size, AlternateFontName alternate_font_name) { - ASSERT(creation_params.CreationType() == kCreateFontByFamily); + DCHECK_EQ(creation_params.CreationType(), kCreateFontByFamily); CString name; sk_sp<SkTypeface> tf =
diff --git a/third_party/WebKit/Source/platform/fonts/win/FontFallbackWin.cpp b/third_party/WebKit/Source/platform/fonts/win/FontFallbackWin.cpp index 26b7bca3..3874415 100644 --- a/third_party/WebKit/Source/platform/fonts/win/FontFallbackWin.cpp +++ b/third_party/WebKit/Source/platform/fonts/win/FontFallbackWin.cpp
@@ -451,7 +451,7 @@ if (script == USCRIPT_INVALID_CODE) return 0; - ASSERT(script < USCRIPT_CODE_LIMIT); + DCHECK_LT(script, USCRIPT_CODE_LIMIT); if (generic == FontDescription::kMonospaceFamily) { const UChar* monospace_family = FindMonospaceFontForScript(script); if (monospace_family) @@ -476,8 +476,8 @@ UScriptCode* script_checked, FontFallbackPriority fallback_priority, SkFontMgr* font_manager) { - ASSERT(character); - ASSERT(font_manager); + DCHECK(character); + DCHECK(font_manager); UBlockCode block = fallback_priority == FontFallbackPriority::kEmojiEmoji ? UBLOCK_EMOTICONS : ublock_getCode(character);
diff --git a/third_party/WebKit/Source/platform/graphics/Canvas2DLayerBridgeTest.cpp b/third_party/WebKit/Source/platform/graphics/Canvas2DLayerBridgeTest.cpp index 8827c44..15da672 100644 --- a/third_party/WebKit/Source/platform/graphics/Canvas2DLayerBridgeTest.cpp +++ b/third_party/WebKit/Source/platform/graphics/Canvas2DLayerBridgeTest.cpp
@@ -81,7 +81,7 @@ } void operator=(PassRefPtr<Canvas2DLayerBridge> layer_bridge) { - ASSERT(!layer_bridge_); + DCHECK(!layer_bridge_); layer_bridge_ = layer_bridge; }
diff --git a/third_party/WebKit/Source/platform/graphics/ColorSpace.cpp b/third_party/WebKit/Source/platform/graphics/ColorSpace.cpp index 676fd60..59d95db 100644 --- a/third_party/WebKit/Source/platform/graphics/ColorSpace.cpp +++ b/third_party/WebKit/Source/platform/graphics/ColorSpace.cpp
@@ -94,7 +94,7 @@ if (dst_color_space == kColorSpaceDeviceRGB) return GetDeviceRgbLUT(); - ASSERT_NOT_REACHED(); + NOTREACHED(); return 0; }
diff --git a/third_party/WebKit/Source/platform/graphics/ColorSpaceProfileData.cpp b/third_party/WebKit/Source/platform/graphics/ColorSpaceProfileData.cpp index 147fe55..e604c13 100644 --- a/third_party/WebKit/Source/platform/graphics/ColorSpaceProfileData.cpp +++ b/third_party/WebKit/Source/platform/graphics/ColorSpaceProfileData.cpp
@@ -95,13 +95,15 @@ namespace blink { void Bt709ColorProfileData(Vector<char>& data) { - ASSERT(WTF::IsMainThread() && data.IsEmpty()); + DCHECK(WTF::IsMainThread()); + DCHECK(data.IsEmpty()); data.Append(bt709ColorProfile::data(), bt709ColorProfile::size()); } void Bt601ColorProfileData(Vector<char>& data) { - ASSERT(WTF::IsMainThread() && data.IsEmpty()); + DCHECK(WTF::IsMainThread()); + DCHECK(data.IsEmpty()); data.Append(bt601ColorProfile::data(), bt601ColorProfile::size()); }
diff --git a/third_party/WebKit/Source/platform/graphics/ContiguousContainer.cpp b/third_party/WebKit/Source/platform/graphics/ContiguousContainer.cpp index 2d995fa..960e780 100644 --- a/third_party/WebKit/Source/platform/graphics/ContiguousContainer.cpp +++ b/third_party/WebKit/Source/platform/graphics/ContiguousContainer.cpp
@@ -40,7 +40,7 @@ bool IsEmpty() const { return UsedCapacity() == 0; } void* Allocate(size_t object_size) { - ASSERT(UnusedCapacity() >= object_size); + DCHECK_GE(UnusedCapacity(), object_size); ANNOTATE_CHANGE_SIZE(begin_, capacity_, UsedCapacity(), UsedCapacity() + object_size); void* result = end_; @@ -49,7 +49,8 @@ } void DeallocateLastObject(void* object) { - RELEASE_ASSERT(begin_ <= object && object < end_); + CHECK_LE(begin_, object); + CHECK_LT(object, end_); ANNOTATE_CHANGE_SIZE(begin_, capacity_, UsedCapacity(), static_cast<char*>(object) - begin_); end_ = static_cast<char*>(object); @@ -105,7 +106,7 @@ void* ContiguousContainerBase::Allocate(size_t object_size, const char* type_name) { - ASSERT(object_size <= max_object_size_); + DCHECK_LE(object_size, max_object_size_); Buffer* buffer_for_alloc = nullptr; if (!buffers_.IsEmpty()) { @@ -168,7 +169,7 @@ ContiguousContainerBase::AllocateNewBufferForNextAllocation( size_t buffer_size, const char* type_name) { - ASSERT(buffers_.IsEmpty() || end_index_ == buffers_.size() - 1); + DCHECK(buffers_.IsEmpty() || end_index_ == buffers_.size() - 1); std::unique_ptr<Buffer> new_buffer = WTF::MakeUnique<Buffer>(buffer_size, type_name); Buffer* buffer_to_return = new_buffer.get();
diff --git a/third_party/WebKit/Source/platform/graphics/ContiguousContainer.h b/third_party/WebKit/Source/platform/graphics/ContiguousContainer.h index e1f9c31e..3836f5b 100644 --- a/third_party/WebKit/Source/platform/graphics/ContiguousContainer.h +++ b/third_party/WebKit/Source/platform/graphics/ContiguousContainer.h
@@ -204,7 +204,7 @@ } void RemoveLast() { - ASSERT(!IsEmpty()); + DCHECK(!IsEmpty()); Last().~BaseElementType(); ContiguousContainerBase::RemoveLast(); } @@ -225,7 +225,7 @@ // Appends a new element using memcpy, then default-constructs a base // element in its place. Use with care. BaseElementType& AppendByMoving(BaseElementType& item, size_t size) { - ASSERT(size >= sizeof(BaseElementType)); + DCHECK_GE(size, sizeof(BaseElementType)); void* new_item = AlignedAllocate(size); memcpy(new_item, static_cast<void*>(&item), size); new (&item) BaseElementType;
diff --git a/third_party/WebKit/Source/platform/graphics/DecodingImageGenerator.cpp b/third_party/WebKit/Source/platform/graphics/DecodingImageGenerator.cpp index db42c9e4..243d3413 100644 --- a/third_party/WebKit/Source/platform/graphics/DecodingImageGenerator.cpp +++ b/third_party/WebKit/Source/platform/graphics/DecodingImageGenerator.cpp
@@ -120,7 +120,8 @@ void* planes[3]) { // YUV decoding does not currently support progressive decoding. See comment // in ImageFrameGenerator.h. - ASSERT(can_yuv_decode_ && all_data_received_); + DCHECK(can_yuv_decode_); + DCHECK(all_data_received_); TRACE_EVENT1("blink", "DecodingImageGenerator::getYUV8Planes", "frame index", static_cast<int>(frame_index_));
diff --git a/third_party/WebKit/Source/platform/graphics/DeferredImageDecoder.cpp b/third_party/WebKit/Source/platform/graphics/DeferredImageDecoder.cpp index 8f60425..09de72ed 100644 --- a/third_party/WebKit/Source/platform/graphics/DeferredImageDecoder.cpp +++ b/third_party/WebKit/Source/platform/graphics/DeferredImageDecoder.cpp
@@ -313,8 +313,8 @@ size_t index, bool known_to_be_opaque) { const SkISize& decoded_size = frame_generator_->GetFullSize(); - ASSERT(decoded_size.width() > 0); - ASSERT(decoded_size.height() > 0); + DCHECK_GT(decoded_size.width(), 0); + DCHECK_GT(decoded_size.height(), 0); sk_sp<SkROBuffer> ro_buffer(rw_buffer_->newRBufferSnapshot()); RefPtr<SegmentReader> segment_reader =
diff --git a/third_party/WebKit/Source/platform/graphics/DrawLooperBuilder.cpp b/third_party/WebKit/Source/platform/graphics/DrawLooperBuilder.cpp index 1487d89..936d557 100644 --- a/third_party/WebKit/Source/platform/graphics/DrawLooperBuilder.cpp +++ b/third_party/WebKit/Source/platform/graphics/DrawLooperBuilder.cpp
@@ -62,7 +62,7 @@ const Color& color, ShadowTransformMode shadow_transform_mode, ShadowAlphaMode shadow_alpha_mode) { - ASSERT(blur >= 0); + DCHECK_GE(blur, 0); // Detect when there's no effective shadow. if (!color.Alpha()) @@ -80,7 +80,7 @@ info.fColorMode = SkBlendMode::kSrc; break; default: - ASSERT_NOT_REACHED(); + NOTREACHED(); } if (blur)
diff --git a/third_party/WebKit/Source/platform/graphics/GraphicsContextStateSaver.h b/third_party/WebKit/Source/platform/graphics/GraphicsContextStateSaver.h index dbc401f..986047d1 100644 --- a/third_party/WebKit/Source/platform/graphics/GraphicsContextStateSaver.h +++ b/third_party/WebKit/Source/platform/graphics/GraphicsContextStateSaver.h
@@ -54,7 +54,7 @@ } void Save() { - ASSERT(!save_and_restore_); + DCHECK(!save_and_restore_); context_.Save(); save_and_restore_ = true; } @@ -66,7 +66,7 @@ } void Restore() { - ASSERT(save_and_restore_); + DCHECK(save_and_restore_); context_.Restore(); save_and_restore_ = false; }
diff --git a/third_party/WebKit/Source/platform/graphics/GraphicsLayer.cpp b/third_party/WebKit/Source/platform/graphics/GraphicsLayer.cpp index 2b71a9d..58dc36c 100644 --- a/third_party/WebKit/Source/platform/graphics/GraphicsLayer.cpp +++ b/third_party/WebKit/Source/platform/graphics/GraphicsLayer.cpp
@@ -1158,7 +1158,7 @@ } PaintController& GraphicsLayer::GetPaintController() { - RELEASE_ASSERT(DrawsContent()); + CHECK(DrawsContent()); if (!paint_controller_) paint_controller_ = PaintController::Create(); return *paint_controller_;
diff --git a/third_party/WebKit/Source/platform/graphics/GraphicsLayerTest.cpp b/third_party/WebKit/Source/platform/graphics/GraphicsLayerTest.cpp index a93dc01..30ef9b2 100644 --- a/third_party/WebKit/Source/platform/graphics/GraphicsLayerTest.cpp +++ b/third_party/WebKit/Source/platform/graphics/GraphicsLayerTest.cpp
@@ -65,7 +65,7 @@ clip_layer_->PlatformLayer()); platform_layer_ = graphics_layer_->PlatformLayer(); layer_tree_view_ = WTF::WrapUnique(new WebLayerTreeViewImplForTesting); - ASSERT(layer_tree_view_); + DCHECK(layer_tree_view_); layer_tree_view_->SetRootLayer(*clip_layer_->PlatformLayer()); layer_tree_view_->RegisterViewportLayers( scroll_elasticity_layer_->PlatformLayer(), clip_layer_->PlatformLayer(),
diff --git a/third_party/WebKit/Source/platform/graphics/GraphicsTypes.cpp b/third_party/WebKit/Source/platform/graphics/GraphicsTypes.cpp index b9c2af58..8a57666 100644 --- a/third_party/WebKit/Source/platform/graphics/GraphicsTypes.cpp +++ b/third_party/WebKit/Source/platform/graphics/GraphicsTypes.cpp
@@ -76,9 +76,9 @@ } String CompositeOperatorName(CompositeOperator op, WebBlendMode blend_op) { - ASSERT(op >= 0); - ASSERT(op < kNumCompositeOperatorNames); - ASSERT(blend_op >= 0); + DCHECK_GE(op, 0); + DCHECK_LT(op, kNumCompositeOperatorNames); + DCHECK_GE(blend_op, 0); if (blend_op != kWebBlendModeNormal) return kBlendOperatorNames[blend_op]; return kCompositeOperatorNames[op]; @@ -101,8 +101,8 @@ } String LineCapName(LineCap cap) { - ASSERT(cap >= 0); - ASSERT(cap < 3); + DCHECK_GE(cap, 0); + DCHECK_LT(cap, 3); const char* const kNames[3] = {"butt", "round", "square"}; return kNames[cap]; } @@ -124,15 +124,15 @@ } String LineJoinName(LineJoin join) { - ASSERT(join >= 0); - ASSERT(join < 3); + DCHECK_GE(join, 0); + DCHECK_LT(join, 3); const char* const kNames[3] = {"miter", "round", "bevel"}; return kNames[join]; } String TextAlignName(TextAlign align) { - ASSERT(align >= 0); - ASSERT(align < 5); + DCHECK_GE(align, 0); + DCHECK_LT(align, 5); const char* const kNames[5] = {"start", "end", "left", "center", "right"}; return kNames[align]; } @@ -162,8 +162,8 @@ } String TextBaselineName(TextBaseline baseline) { - ASSERT(baseline >= 0); - ASSERT(baseline < 6); + DCHECK_GE(baseline, 0); + DCHECK_LT(baseline, 6); const char* const kNames[6] = {"alphabetic", "top", "middle", "bottom", "ideographic", "hanging"}; return kNames[baseline];
diff --git a/third_party/WebKit/Source/platform/graphics/Image.cpp b/third_party/WebKit/Source/platform/graphics/Image.cpp index 57f94fa..798ef9e 100644 --- a/third_party/WebKit/Source/platform/graphics/Image.cpp +++ b/third_party/WebKit/Source/platform/graphics/Image.cpp
@@ -56,7 +56,7 @@ Image::~Image() {} Image* Image::NullImage() { - ASSERT(IsMainThread()); + DCHECK(IsMainThread()); DEFINE_STATIC_REF(Image, null_image, (BitmapImage::Create())); return null_image; }
diff --git a/third_party/WebKit/Source/platform/graphics/ImageDecodingStore.cpp b/third_party/WebKit/Source/platform/graphics/ImageDecodingStore.cpp index a92b37e..259f2b6 100644 --- a/third_party/WebKit/Source/platform/graphics/ImageDecodingStore.cpp +++ b/third_party/WebKit/Source/platform/graphics/ImageDecodingStore.cpp
@@ -45,9 +45,9 @@ ImageDecodingStore::~ImageDecodingStore() { #if DCHECK_IS_ON() SetCacheLimitInBytes(0); - ASSERT(!decoder_cache_map_.size()); - ASSERT(!ordered_cache_list_.size()); - ASSERT(!decoder_cache_key_map_.size()); + DCHECK(!decoder_cache_map_.size()); + DCHECK(!ordered_cache_list_.size()); + DCHECK(!decoder_cache_key_map_.size()); #endif } @@ -60,7 +60,7 @@ bool ImageDecodingStore::LockDecoder(const ImageFrameGenerator* generator, const SkISize& scaled_size, ImageDecoder** decoder) { - ASSERT(decoder); + DCHECK(decoder); MutexLocker lock(mutex_); DecoderCacheMap::iterator iter = decoder_cache_map_.Find( @@ -71,7 +71,7 @@ DecoderCacheEntry* cache_entry = iter->value.get(); // There can only be one user of a decoder at a time. - ASSERT(!cache_entry->UseCount()); + DCHECK(!cache_entry->UseCount()); cache_entry->IncrementUseCount(); *decoder = cache_entry->CachedDecoder(); return true; @@ -101,7 +101,7 @@ DecoderCacheEntry::Create(generator, std::move(decoder)); MutexLocker lock(mutex_); - ASSERT(!decoder_cache_map_.Contains(new_cache_entry->CacheKey())); + DCHECK(!decoder_cache_map_.Contains(new_cache_entry->CacheKey())); InsertCacheInternal(std::move(new_cache_entry), &decoder_cache_map_, &decoder_cache_key_map_); } @@ -116,7 +116,7 @@ SECURITY_DCHECK(iter != decoder_cache_map_.end()); CacheEntry* cache_entry = iter->value.get(); - ASSERT(cache_entry->UseCount()); + DCHECK(cache_entry->UseCount()); cache_entry->DecrementUseCount(); // Delete only one decoder cache entry. Ownership of the cache entry @@ -242,12 +242,12 @@ V* identifier_map, Vector<std::unique_ptr<CacheEntry>>* deletion_list) { const size_t cache_entry_bytes = cache_entry->MemoryUsageInBytes(); - ASSERT(heap_memory_usage_in_bytes_ >= cache_entry_bytes); + DCHECK_GE(heap_memory_usage_in_bytes_, cache_entry_bytes); heap_memory_usage_in_bytes_ -= cache_entry_bytes; // Remove entry from identifier map. typename V::iterator iter = identifier_map->Find(cache_entry->Generator()); - ASSERT(iter != identifier_map->end()); + DCHECK(iter != identifier_map->end()); iter->value.erase(cache_entry->CacheKey()); if (!iter->value.size()) identifier_map->erase(iter); @@ -270,7 +270,7 @@ &decoder_cache_map_, &decoder_cache_key_map_, deletion_list); } else { - ASSERT(false); + DCHECK(false); } } @@ -290,9 +290,9 @@ // For each cache identifier find the corresponding CacheEntry and remove it. for (size_t i = 0; i < cache_identifier_list.size(); ++i) { - ASSERT(cache_map->Contains(cache_identifier_list[i])); + DCHECK(cache_map->Contains(cache_identifier_list[i])); const auto& cache_entry = cache_map->at(cache_identifier_list[i]); - ASSERT(!cache_entry->UseCount()); + DCHECK(!cache_entry->UseCount()); RemoveFromCacheInternal(cache_entry, cache_map, identifier_map, deletion_list); }
diff --git a/third_party/WebKit/Source/platform/graphics/ImageDecodingStore.h b/third_party/WebKit/Source/platform/graphics/ImageDecodingStore.h index 04ee218..dce492d 100644 --- a/third_party/WebKit/Source/platform/graphics/ImageDecodingStore.h +++ b/third_party/WebKit/Source/platform/graphics/ImageDecodingStore.h
@@ -112,14 +112,14 @@ CacheEntry(const ImageFrameGenerator* generator, int use_count) : generator_(generator), use_count_(use_count), prev_(0), next_(0) {} - virtual ~CacheEntry() { ASSERT(!use_count_); } + virtual ~CacheEntry() { DCHECK(!use_count_); } const ImageFrameGenerator* Generator() const { return generator_; } int UseCount() const { return use_count_; } void IncrementUseCount() { ++use_count_; } void DecrementUseCount() { --use_count_; - ASSERT(use_count_ >= 0); + DCHECK_GE(use_count_, 0); } // FIXME: getSafeSize() returns the size in bytes truncated to a 32-bit
diff --git a/third_party/WebKit/Source/platform/graphics/ImageFrameGenerator.cpp b/third_party/WebKit/Source/platform/graphics/ImageFrameGenerator.cpp index d047d12..1cbc8650 100644 --- a/third_party/WebKit/Source/platform/graphics/ImageFrameGenerator.cpp +++ b/third_party/WebKit/Source/platform/graphics/ImageFrameGenerator.cpp
@@ -144,7 +144,7 @@ // This implementation does not support scaling so check the requested size. SkISize scaled_size = SkISize::Make(info.width(), info.height()); - ASSERT(full_size_ == scaled_size); + DCHECK(full_size_ == scaled_size); // It is okay to allocate ref-counted ExternalMemoryAllocator on the stack, // because 1) it contains references to memory that will be invalid after @@ -160,8 +160,8 @@ // Check to see if the decoder has written directly to the pixel memory // provided. If not, make a copy. - ASSERT(bitmap.width() == scaled_size.width()); - ASSERT(bitmap.height() == scaled_size.height()); + DCHECK_EQ(bitmap.width(), scaled_size.width()); + DCHECK_EQ(bitmap.height(), scaled_size.height()); SkAutoLockPixels bitmap_lock(bitmap); if (bitmap.getPixels() != pixels) CopyPixels(pixels, row_bytes, bitmap.getPixels(), bitmap.rowBytes(), info); @@ -191,20 +191,20 @@ data, true, ImageDecoder::kAlphaPremultiplied, decoder_color_behavior_); // getYUVComponentSizes was already called and was successful, so // ImageDecoder::create must succeed. - ASSERT(decoder); + DCHECK(decoder); std::unique_ptr<ImagePlanes> image_planes = WTF::MakeUnique<ImagePlanes>(planes, row_bytes); decoder->SetImagePlanes(std::move(image_planes)); - ASSERT(decoder->CanDecodeToYUV()); + DCHECK(decoder->CanDecodeToYUV()); if (decoder->DecodeToYUV()) { SetHasAlpha(0, false); // YUV is always opaque return true; } - ASSERT(decoder->Failed()); + DCHECK(decoder->Failed()); yuv_decoding_failed_ = true; return false; } @@ -224,7 +224,7 @@ MutexLocker lock(decode_mutex_); const bool resume_decoding = ImageDecodingStore::Instance().LockDecoder(this, full_size_, &decoder); - ASSERT(!resume_decoding || decoder); + DCHECK(!resume_decoding || decoder); SkBitmap full_size_image; bool complete = Decode(data, all_data_received, index, &decoder, @@ -294,12 +294,14 @@ ImageDecoder** decoder, SkBitmap* bitmap, SkBitmap::Allocator* allocator) { - ASSERT(decode_mutex_.Locked()); +#if DCHECK_IS_ON() + DCHECK(decode_mutex_.Locked()); +#endif TRACE_EVENT2("blink", "ImageFrameGenerator::decode", "width", full_size_.width(), "height", full_size_.height()); // Try to create an ImageDecoder if we are not given one. - ASSERT(decoder); + DCHECK(decoder); bool new_decoder = false; bool should_call_set_data = true; if (!*decoder) { @@ -362,8 +364,8 @@ SkBitmap full_size_bitmap = frame->Bitmap(); if (!full_size_bitmap.isNull()) { - ASSERT(full_size_bitmap.width() == full_size_.width() && - full_size_bitmap.height() == full_size_.height()); + DCHECK_EQ(full_size_bitmap.width(), full_size_.width()); + DCHECK_EQ(full_size_bitmap.height(), full_size_.height()); SetHasAlpha(index, !full_size_bitmap.isOpaque()); }
diff --git a/third_party/WebKit/Source/platform/graphics/ImageOrientation.cpp b/third_party/WebKit/Source/platform/graphics/ImageOrientation.cpp index e1aba9f..f97c399 100644 --- a/third_party/WebKit/Source/platform/graphics/ImageOrientation.cpp +++ b/third_party/WebKit/Source/platform/graphics/ImageOrientation.cpp
@@ -53,10 +53,10 @@ case kOriginLeftBottom: return AffineTransform(0, -1, 1, 0, 0, h); default: - ASSERT_NOT_REACHED(); + NOTREACHED(); } - ASSERT_NOT_REACHED(); + NOTREACHED(); return AffineTransform(); }
diff --git a/third_party/WebKit/Source/platform/graphics/InterceptingCanvas.h b/third_party/WebKit/Source/platform/graphics/InterceptingCanvas.h index 1770943..d197d542 100644 --- a/third_party/WebKit/Source/platform/graphics/InterceptingCanvas.h +++ b/third_party/WebKit/Source/platform/graphics/InterceptingCanvas.h
@@ -54,7 +54,7 @@ } ~CanvasInterceptorBase() { - ASSERT(canvas_->call_nesting_depth_ > 0); + DCHECK_GT(canvas_->call_nesting_depth_, 0u); if (!--canvas_->call_nesting_depth_) canvas_->call_count_++; }
diff --git a/third_party/WebKit/Source/platform/graphics/LoggingCanvas.cpp b/third_party/WebKit/Source/platform/graphics/LoggingCanvas.cpp index df8969e..b9334f74 100644 --- a/third_party/WebKit/Source/platform/graphics/LoggingCanvas.cpp +++ b/third_party/WebKit/Source/platform/graphics/LoggingCanvas.cpp
@@ -86,7 +86,7 @@ case SkCanvas::kPolygon_PointMode: return "Polygon"; default: - ASSERT_NOT_REACHED(); + NOTREACHED(); return "?"; }; } @@ -130,7 +130,7 @@ case SkRRect::kComplex_Type: return "Complex"; default: - ASSERT_NOT_REACHED(); + NOTREACHED(); return "?"; }; } @@ -146,7 +146,7 @@ case SkRRect::kLowerLeft_Corner: return "lowerLeftRadius"; default: - ASSERT_NOT_REACHED(); + NOTREACHED(); return "?"; } } @@ -175,7 +175,7 @@ case SkPath::kInverseEvenOdd_FillType: return "InverseEvenOdd"; default: - ASSERT_NOT_REACHED(); + NOTREACHED(); return "?"; }; } @@ -189,7 +189,7 @@ case SkPath::kConcave_Convexity: return "Concave"; default: - ASSERT_NOT_REACHED(); + NOTREACHED(); return "?"; }; } @@ -211,7 +211,7 @@ case SkPath::kDone_Verb: return VerbParams("Done", 0, 0); default: - ASSERT_NOT_REACHED(); + NOTREACHED(); return VerbParams("?", 0, 0); }; } @@ -229,8 +229,8 @@ VerbParams verb_params = SegmentParams(verb); std::unique_ptr<JSONObject> path_point_item = JSONObject::Create(); path_point_item->SetString("verb", verb_params.name); - ASSERT(verb_params.point_count + verb_params.point_offset <= - WTF_ARRAY_LENGTH(points)); + DCHECK_LE(verb_params.point_count + verb_params.point_offset, + WTF_ARRAY_LENGTH(points)); path_point_item->SetArray( "points", ArrayForSkPoints(verb_params.point_count, points + verb_params.point_offset)); @@ -258,7 +258,7 @@ case kN32_SkColorType: return "ARGB8888"; default: - ASSERT_NOT_REACHED(); + NOTREACHED(); return "?"; }; } @@ -366,7 +366,7 @@ case kHigh_SkFilterQuality: return "High"; default: - ASSERT_NOT_REACHED(); + NOTREACHED(); return "?"; }; } @@ -380,7 +380,7 @@ case SkPaint::kRight_Align: return "Right"; default: - ASSERT_NOT_REACHED(); + NOTREACHED(); return "?"; }; } @@ -394,7 +394,7 @@ case SkPaint::kSquare_Cap: return "Square"; default: - ASSERT_NOT_REACHED(); + NOTREACHED(); return "?"; }; } @@ -408,7 +408,7 @@ case SkPaint::kBevel_Join: return "Bevel"; default: - ASSERT_NOT_REACHED(); + NOTREACHED(); return "?"; }; } @@ -422,7 +422,7 @@ case SkPaint::kStrokeAndFill_Style: return "StrokeAndFill"; default: - ASSERT_NOT_REACHED(); + NOTREACHED(); return "?"; }; } @@ -438,7 +438,7 @@ case SkPaint::kGlyphID_TextEncoding: return "GlyphID"; default: - ASSERT_NOT_REACHED(); + NOTREACHED(); return "?"; }; } @@ -454,7 +454,7 @@ case SkPaint::kFull_Hinting: return "Full"; default: - ASSERT_NOT_REACHED(); + NOTREACHED(); return "?"; }; } @@ -543,7 +543,7 @@ reinterpret_cast<const char*>(text_data), byte_length * 2); } default: - ASSERT_NOT_REACHED(); + NOTREACHED(); return "?"; } }
diff --git a/third_party/WebKit/Source/platform/graphics/OffscreenCanvasFrameDispatcherImpl.cpp b/third_party/WebKit/Source/platform/graphics/OffscreenCanvasFrameDispatcherImpl.cpp index 55149140..c4c14299 100644 --- a/third_party/WebKit/Source/platform/graphics/OffscreenCanvasFrameDispatcherImpl.cpp +++ b/third_party/WebKit/Source/platform/graphics/OffscreenCanvasFrameDispatcherImpl.cpp
@@ -402,7 +402,9 @@ sink_->SubmitCompositorFrame(current_local_surface_id_, std::move(frame)); } -void OffscreenCanvasFrameDispatcherImpl::DidReceiveCompositorFrameAck() { +void OffscreenCanvasFrameDispatcherImpl::DidReceiveCompositorFrameAck( + const cc::ReturnedResourceArray& resources) { + ReclaimResources(resources); // TODO(fsamuel): Implement this. }
diff --git a/third_party/WebKit/Source/platform/graphics/OffscreenCanvasFrameDispatcherImpl.h b/third_party/WebKit/Source/platform/graphics/OffscreenCanvasFrameDispatcherImpl.h index 70d1edf..108a22a 100644 --- a/third_party/WebKit/Source/platform/graphics/OffscreenCanvasFrameDispatcherImpl.h +++ b/third_party/WebKit/Source/platform/graphics/OffscreenCanvasFrameDispatcherImpl.h
@@ -40,7 +40,8 @@ void Reshape(int width, int height) final; // cc::mojom::blink::MojoCompositorFrameSinkClient implementation. - void DidReceiveCompositorFrameAck() final; + void DidReceiveCompositorFrameAck( + const cc::ReturnedResourceArray& resources) final; void OnBeginFrame(const cc::BeginFrameArgs&) final; void ReclaimResources(const cc::ReturnedResourceArray& resources) final;
diff --git a/third_party/WebKit/Source/platform/graphics/PaintInvalidationReason.cpp b/third_party/WebKit/Source/platform/graphics/PaintInvalidationReason.cpp index 0fa524b..0450cc1 100644 --- a/third_party/WebKit/Source/platform/graphics/PaintInvalidationReason.cpp +++ b/third_party/WebKit/Source/platform/graphics/PaintInvalidationReason.cpp
@@ -67,7 +67,7 @@ case kPaintInvalidationDelayedFull: return "delayed full"; } - ASSERT_NOT_REACHED(); + NOTREACHED(); return ""; }
diff --git a/third_party/WebKit/Source/platform/graphics/Path.cpp b/third_party/WebKit/Source/platform/graphics/Path.cpp index 6faaf17e..a47b4cfd 100644 --- a/third_party/WebKit/Source/platform/graphics/Path.cpp +++ b/third_party/WebKit/Source/platform/graphics/Path.cpp
@@ -364,9 +364,12 @@ float start_angle, float end_angle, bool anticlockwise) { - ASSERT(EllipseIsRenderable(start_angle, end_angle)); - ASSERT(start_angle >= 0 && start_angle < twoPiFloat); - ASSERT((anticlockwise && (start_angle - end_angle) >= 0) || +#if DCHECK_IS_ON() + DCHECK(EllipseIsRenderable(start_angle, end_angle)); +#endif + DCHECK_GE(start_angle, 0); + DCHECK_LT(start_angle, twoPiFloat); + DCHECK((anticlockwise && (start_angle - end_angle) >= 0) || (!anticlockwise && (end_angle - start_angle) >= 0)); SkScalar cx = WebCoreFloatToSkScalar(p.X()); @@ -425,9 +428,12 @@ float start_angle, float end_angle, bool anticlockwise) { - ASSERT(EllipseIsRenderable(start_angle, end_angle)); - ASSERT(start_angle >= 0 && start_angle < twoPiFloat); - ASSERT((anticlockwise && (start_angle - end_angle) >= 0) || +#if DCHECK_IS_ON() + DCHECK(EllipseIsRenderable(start_angle, end_angle)); +#endif + DCHECK_GE(start_angle, 0); + DCHECK_LT(start_angle, twoPiFloat); + DCHECK((anticlockwise && (start_angle - end_angle) >= 0) || (!anticlockwise && (end_angle - start_angle) >= 0)); if (!rotation) { @@ -439,7 +445,7 @@ // Add an arc after the relevant transform. AffineTransform ellipse_transform = AffineTransform::Translation(p.X(), p.Y()).RotateRadians(rotation); - ASSERT(ellipse_transform.IsInvertible()); + DCHECK(ellipse_transform.IsInvertible()); AffineTransform inverse_ellipse_transform = ellipse_transform.Inverse(); Transform(inverse_ellipse_transform); AddEllipse(FloatPoint::Zero(), radius_x, radius_y, start_angle, end_angle,
diff --git a/third_party/WebKit/Source/platform/graphics/PictureSnapshot.cpp b/third_party/WebKit/Source/platform/graphics/PictureSnapshot.cpp index 0c433115..a915e39 100644 --- a/third_party/WebKit/Source/platform/graphics/PictureSnapshot.cpp +++ b/third_party/WebKit/Source/platform/graphics/PictureSnapshot.cpp
@@ -83,7 +83,7 @@ PassRefPtr<PictureSnapshot> PictureSnapshot::Load( const Vector<RefPtr<TilePictureStream>>& tiles) { - ASSERT(!tiles.IsEmpty()); + DCHECK(!tiles.IsEmpty()); Vector<sk_sp<SkPicture>> pictures; pictures.ReserveCapacity(tiles.size()); FloatRect union_rect;
diff --git a/third_party/WebKit/Source/platform/graphics/ProfilingCanvas.cpp b/third_party/WebKit/Source/platform/graphics/ProfilingCanvas.cpp index 8cea360..cbc9e1b6 100644 --- a/third_party/WebKit/Source/platform/graphics/ProfilingCanvas.cpp +++ b/third_party/WebKit/Source/platform/graphics/ProfilingCanvas.cpp
@@ -44,7 +44,7 @@ return; double delta = WTF::MonotonicallyIncreasingTime() - start_time_; if (auto timings = Canvas()->timings_) { - ASSERT(timings->size() == Canvas()->CallCount()); + DCHECK_EQ(timings->size(), Canvas()->CallCount()); timings->push_back(delta); } }
diff --git a/third_party/WebKit/Source/platform/graphics/compositing/PaintArtifactCompositorTest.cpp b/third_party/WebKit/Source/platform/graphics/compositing/PaintArtifactCompositorTest.cpp index 08cb740..d4ff05f7 100644 --- a/third_party/WebKit/Source/platform/graphics/compositing/PaintArtifactCompositorTest.cpp +++ b/third_party/WebKit/Source/platform/graphics/compositing/PaintArtifactCompositorTest.cpp
@@ -167,7 +167,7 @@ EXPECT_THAT( child->GetPicture(), Pointee(DrawsRectangle(FloatRect(0, 0, 100, 100), Color::kWhite))); - EXPECT_EQ(Translation(50, -50), child->screen_space_transform()); + EXPECT_EQ(Translation(50, -50), child->ScreenSpaceTransform()); EXPECT_EQ(gfx::Size(100, 100), child->bounds()); } @@ -206,7 +206,7 @@ EXPECT_THAT(layer->GetPicture(), Pointee(DrawsRectangles(rects_with_color))); gfx::RectF mapped_rect(0, 0, 100, 100); - layer->screen_space_transform().TransformRect(&mapped_rect); + layer->ScreenSpaceTransform().TransformRect(&mapped_rect); EXPECT_EQ(gfx::RectF(100, 0, 100, 100), mapped_rect); } { @@ -214,7 +214,7 @@ EXPECT_THAT( layer->GetPicture(), Pointee(DrawsRectangle(FloatRect(0, 0, 100, 100), Color::kGray))); - EXPECT_EQ(gfx::Transform(), layer->screen_space_transform()); + EXPECT_EQ(gfx::Transform(), layer->ScreenSpaceTransform()); } } @@ -247,7 +247,7 @@ layer->GetPicture(), Pointee(DrawsRectangle(FloatRect(0, 0, 300, 200), Color::kWhite))); gfx::RectF mapped_rect(0, 0, 300, 200); - layer->screen_space_transform().TransformRect(&mapped_rect); + layer->ScreenSpaceTransform().TransformRect(&mapped_rect); EXPECT_EQ(gfx::RectF(-10, -10, 600, 400), mapped_rect); } { @@ -256,7 +256,7 @@ layer->GetPicture(), Pointee(DrawsRectangle(FloatRect(0, 0, 300, 200), Color::kBlack))); gfx::RectF mapped_rect(0, 0, 300, 200); - layer->screen_space_transform().TransformRect(&mapped_rect); + layer->ScreenSpaceTransform().TransformRect(&mapped_rect); EXPECT_EQ(gfx::RectF(0, 0, 600, 400), mapped_rect); } EXPECT_NE(ContentLayerAt(0)->transform_tree_index(), @@ -313,7 +313,7 @@ // empty rectangle (as the total 90 degree rotation makes it // perpendicular to the viewport). gfx::RectF rect(0, 0, 100, 100); - layer->screen_space_transform().TransformRect(&rect); + layer->ScreenSpaceTransform().TransformRect(&rect); if (transform_is_flattened) EXPECT_FLOAT_RECT_EQ(gfx::RectF(0, 0, 50, 100), rect); else @@ -424,7 +424,7 @@ EXPECT_THAT( layer->GetPicture(), Pointee(DrawsRectangle(FloatRect(0, 0, 300, 200), Color::kBlack))); - EXPECT_EQ(Translation(220, 80), layer->screen_space_transform()); + EXPECT_EQ(Translation(220, 80), layer->ScreenSpaceTransform()); const cc::ClipNode* clip_node = GetPropertyTrees().clip_tree.Node(layer->clip_tree_index()); @@ -467,25 +467,25 @@ EXPECT_THAT( white_layer->GetPicture(), Pointee(DrawsRectangle(FloatRect(0, 0, 100, 100), Color::kWhite))); - EXPECT_EQ(Translation(300, 350), white_layer->screen_space_transform()); + EXPECT_EQ(Translation(300, 350), white_layer->ScreenSpaceTransform()); const cc::Layer* light_gray_layer = ContentLayerAt(1); EXPECT_THAT( light_gray_layer->GetPicture(), Pointee(DrawsRectangle(FloatRect(0, 0, 100, 100), Color::kLightGray))); - EXPECT_EQ(Translation(300, 350), light_gray_layer->screen_space_transform()); + EXPECT_EQ(Translation(300, 350), light_gray_layer->ScreenSpaceTransform()); const cc::Layer* dark_gray_layer = ContentLayerAt(2); EXPECT_THAT( dark_gray_layer->GetPicture(), Pointee(DrawsRectangle(FloatRect(0, 0, 100, 100), Color::kDarkGray))); - EXPECT_EQ(Translation(300, 350), dark_gray_layer->screen_space_transform()); + EXPECT_EQ(Translation(300, 350), dark_gray_layer->ScreenSpaceTransform()); const cc::Layer* black_layer = ContentLayerAt(3); EXPECT_THAT( black_layer->GetPicture(), Pointee(DrawsRectangle(FloatRect(0, 0, 100, 100), Color::kBlack))); - EXPECT_EQ(Translation(300, 350), black_layer->screen_space_transform()); + EXPECT_EQ(Translation(300, 350), black_layer->ScreenSpaceTransform()); EXPECT_EQ(white_layer->clip_tree_index(), dark_gray_layer->clip_tree_index()); const cc::ClipNode* outer_clip = @@ -524,7 +524,7 @@ EXPECT_THAT( drawing_layer->GetPicture(), Pointee(DrawsRectangle(FloatRect(0, 0, 200, 200), Color::kWhite))); - EXPECT_EQ(gfx::Transform(), drawing_layer->screen_space_transform()); + EXPECT_EQ(gfx::Transform(), drawing_layer->ScreenSpaceTransform()); // Check the clip nodes. const cc::ClipNode* clip_node = @@ -564,7 +564,7 @@ EXPECT_THAT( white_layer->GetPicture(), Pointee(DrawsRectangle(FloatRect(0, 0, 640, 480), Color::kWhite))); - EXPECT_EQ(gfx::Transform(), white_layer->screen_space_transform()); + EXPECT_EQ(gfx::Transform(), white_layer->ScreenSpaceTransform()); const cc::ClipNode* white_clip = GetPropertyTrees().clip_tree.Node(white_layer->clip_tree_index()); EXPECT_EQ(cc::ClipNode::ClipType::APPLIES_LOCAL_CLIP, white_clip->clip_type); @@ -574,7 +574,7 @@ EXPECT_THAT( black_layer->GetPicture(), Pointee(DrawsRectangle(FloatRect(0, 0, 640, 480), Color::kBlack))); - EXPECT_EQ(gfx::Transform(), black_layer->screen_space_transform()); + EXPECT_EQ(gfx::Transform(), black_layer->ScreenSpaceTransform()); const cc::ClipNode* black_clip = GetPropertyTrees().clip_tree.Node(black_layer->clip_tree_index()); EXPECT_EQ(cc::ClipNode::ClipType::APPLIES_LOCAL_CLIP, black_clip->clip_type); @@ -611,7 +611,7 @@ ASSERT_EQ(3u, ContentLayerCount()); EXPECT_EQ(layer, ContentLayerAt(1)); EXPECT_EQ(gfx::Size(400, 300), layer->bounds()); - EXPECT_EQ(Translation(50, 60), layer->screen_space_transform()); + EXPECT_EQ(Translation(50, 60), layer->ScreenSpaceTransform()); } TEST_F(PaintArtifactCompositorTestWithPropertyTrees, EffectTreeConversion) { @@ -1719,7 +1719,7 @@ const cc::Layer* masked_layer = ContentLayerAt(0); EXPECT_THAT(masked_layer->GetPicture(), Pointee(DrawsRectangle(FloatRect(0, 0, 200, 200), Color::kGray))); - EXPECT_EQ(Translation(100, 100), masked_layer->screen_space_transform()); + EXPECT_EQ(Translation(100, 100), masked_layer->ScreenSpaceTransform()); EXPECT_EQ(gfx::Size(200, 200), masked_layer->bounds()); const cc::EffectNode* masked_group = GetPropertyTrees().effect_tree.Node(masked_layer->effect_tree_index()); @@ -1729,7 +1729,7 @@ EXPECT_THAT( masking_layer->GetPicture(), Pointee(DrawsRectangle(FloatRect(0, 0, 100, 100), Color::kWhite))); - EXPECT_EQ(Translation(150, 150), masking_layer->screen_space_transform()); + EXPECT_EQ(Translation(150, 150), masking_layer->ScreenSpaceTransform()); EXPECT_EQ(gfx::Size(100, 100), masking_layer->bounds()); const cc::EffectNode* masking_group = GetPropertyTrees().effect_tree.Node(masking_layer->effect_tree_index());
diff --git a/third_party/WebKit/Source/platform/graphics/filters/FEBoxReflect.cpp b/third_party/WebKit/Source/platform/graphics/filters/FEBoxReflect.cpp index 735c6c9..2b99ce6f 100644 --- a/third_party/WebKit/Source/platform/graphics/filters/FEBoxReflect.cpp +++ b/third_party/WebKit/Source/platform/graphics/filters/FEBoxReflect.cpp
@@ -22,7 +22,7 @@ TextStream& FEBoxReflect::ExternalRepresentation(TextStream& ts, int indent) const { // Only called for SVG layout tree printing. - ASSERT_NOT_REACHED(); + NOTREACHED(); return ts; }
diff --git a/third_party/WebKit/Source/platform/graphics/filters/FEColorMatrix.cpp b/third_party/WebKit/Source/platform/graphics/filters/FEColorMatrix.cpp index 9592e45..9696a29 100644 --- a/third_party/WebKit/Source/platform/graphics/filters/FEColorMatrix.cpp +++ b/third_party/WebKit/Source/platform/graphics/filters/FEColorMatrix.cpp
@@ -195,7 +195,7 @@ case FECOLORMATRIX_TYPE_UNKNOWN: break; } - ASSERT_NOT_REACHED(); + NOTREACHED(); return false; }
diff --git a/third_party/WebKit/Source/platform/graphics/filters/FEComposite.cpp b/third_party/WebKit/Source/platform/graphics/filters/FEComposite.cpp index 260e2a5..c06ceea 100644 --- a/third_party/WebKit/Source/platform/graphics/filters/FEComposite.cpp +++ b/third_party/WebKit/Source/platform/graphics/filters/FEComposite.cpp
@@ -165,7 +165,7 @@ case FECOMPOSITE_OPERATOR_LIGHTER: return SkBlendMode::kPlus; default: - ASSERT_NOT_REACHED(); + NOTREACHED(); return SkBlendMode::kSrcOver; } }
diff --git a/third_party/WebKit/Source/platform/graphics/filters/FELighting.cpp b/third_party/WebKit/Source/platform/graphics/filters/FELighting.cpp index 9640b35..d6ee4da 100644 --- a/third_party/WebKit/Source/platform/graphics/filters/FELighting.cpp +++ b/third_party/WebKit/Source/platform/graphics/filters/FELighting.cpp
@@ -119,7 +119,7 @@ std::move(input), &rect); } default: - ASSERT_NOT_REACHED(); + NOTREACHED(); return nullptr; } }
diff --git a/third_party/WebKit/Source/platform/graphics/filters/FilterEffect.cpp b/third_party/WebKit/Source/platform/graphics/filters/FilterEffect.cpp index 2efcce08..36ef9c7 100644 --- a/third_party/WebKit/Source/platform/graphics/filters/FilterEffect.cpp +++ b/third_party/WebKit/Source/platform/graphics/filters/FilterEffect.cpp
@@ -34,7 +34,7 @@ clips_to_bounds_(true), origin_tainted_(false), operating_color_space_(kColorSpaceLinearRGB) { - ASSERT(filter_); + DCHECK(filter_); } FilterEffect::~FilterEffect() {}
diff --git a/third_party/WebKit/Source/platform/graphics/gpu/DrawingBuffer.cpp b/third_party/WebKit/Source/platform/graphics/gpu/DrawingBuffer.cpp index 25771014..9f08a210 100644 --- a/third_party/WebKit/Source/platform/graphics/gpu/DrawingBuffer.cpp +++ b/third_party/WebKit/Source/platform/graphics/gpu/DrawingBuffer.cpp
@@ -78,7 +78,7 @@ PreserveDrawingBuffer preserve, WebGLVersion web_gl_version, ChromiumImageUsage chromium_image_usage) { - ASSERT(context_provider); + DCHECK(context_provider); if (g_should_fail_drawing_buffer_creation_for_testing) { g_should_fail_drawing_buffer_creation_for_testing = false; @@ -91,7 +91,7 @@ // This might be the first time we notice that the GL context is lost. return nullptr; } - ASSERT(extensions_util->SupportsExtension("GL_OES_packed_depth_stencil")); + DCHECK(extensions_util->SupportsExtension("GL_OES_packed_depth_stencil")); extensions_util->EnsureExtensionEnabled("GL_OES_packed_depth_stencil"); bool multisample_supported = want_antialiasing && @@ -186,7 +186,7 @@ if (preserve_drawing_buffer_ == kDiscard) { buffer_clear_needed_ = flag; } else { - ASSERT(!buffer_clear_needed_); + DCHECK(!buffer_clear_needed_); } } @@ -270,7 +270,7 @@ // 4. Here. return false; } - ASSERT(!is_hidden_); + DCHECK(!is_hidden_); if (!contents_changed_) return false; @@ -788,7 +788,7 @@ } void DrawingBuffer::BeginDestruction() { - ASSERT(!destruction_in_progress_); + DCHECK(!destruction_in_progress_); destruction_in_progress_ = true; ClearPlatformLayer(); @@ -1051,7 +1051,7 @@ WTF::ArrayBufferContents& contents) { ScopedStateRestorer scoped_state_restorer(this); - ASSERT(!premultiplied_alpha_); + DCHECK(!premultiplied_alpha_); width = size().Width(); height = size().Height(); @@ -1120,7 +1120,7 @@ pixels[i + 2] = std::min(255, pixels[i + 2] * pixels[i + 3] / 255); } } else if (op != WebGLImageConversion::kAlphaDoNothing) { - ASSERT_NOT_REACHED(); + NOTREACHED(); } }
diff --git a/third_party/WebKit/Source/platform/graphics/gpu/DrawingBufferTest.cpp b/third_party/WebKit/Source/platform/graphics/gpu/DrawingBufferTest.cpp index 6108988..8d8becf 100644 --- a/third_party/WebKit/Source/platform/graphics/gpu/DrawingBufferTest.cpp +++ b/third_party/WebKit/Source/platform/graphics/gpu/DrawingBufferTest.cpp
@@ -537,7 +537,7 @@ depth_stencil_attachment_ = renderbuffer; break; default: - ASSERT_NOT_REACHED(); + NOTREACHED(); break; } }
diff --git a/third_party/WebKit/Source/platform/graphics/gpu/WebGLImageConversion.cpp b/third_party/WebKit/Source/platform/graphics/gpu/WebGLImageConversion.cpp index 1037368..48d109c 100644 --- a/third_party/WebKit/Source/platform/graphics/gpu/WebGLImageConversion.cpp +++ b/third_party/WebKit/Source/platform/graphics/gpu/WebGLImageConversion.cpp
@@ -65,7 +65,7 @@ dst_format = WebGLImageConversion::kDataFormatRGBA8_S; break; default: - ASSERT_NOT_REACHED(); + NOTREACHED(); } break; case GL_UNSIGNED_BYTE: @@ -96,7 +96,7 @@ dst_format = WebGLImageConversion::kDataFormatRA8; break; default: - ASSERT_NOT_REACHED(); + NOTREACHED(); } break; case GL_SHORT: @@ -112,7 +112,7 @@ case GL_RGBA_INTEGER: dst_format = WebGLImageConversion::kDataFormatRGBA16_S; default: - ASSERT_NOT_REACHED(); + NOTREACHED(); } break; case GL_UNSIGNED_SHORT: @@ -133,7 +133,7 @@ dst_format = WebGLImageConversion::kDataFormatRGBA16; break; default: - ASSERT_NOT_REACHED(); + NOTREACHED(); } break; case GL_INT: @@ -151,7 +151,7 @@ dst_format = WebGLImageConversion::kDataFormatRGBA32_S; break; default: - ASSERT_NOT_REACHED(); + NOTREACHED(); } break; case GL_UNSIGNED_INT: @@ -172,7 +172,7 @@ dst_format = WebGLImageConversion::kDataFormatRGBA32; break; default: - ASSERT_NOT_REACHED(); + NOTREACHED(); } break; case GL_HALF_FLOAT_OES: // OES_texture_half_float @@ -198,7 +198,7 @@ dst_format = WebGLImageConversion::kDataFormatRA16F; break; default: - ASSERT_NOT_REACHED(); + NOTREACHED(); } break; case GL_FLOAT: // OES_texture_float @@ -226,7 +226,7 @@ dst_format = WebGLImageConversion::kDataFormatRA32F; break; default: - ASSERT_NOT_REACHED(); + NOTREACHED(); } break; case GL_UNSIGNED_SHORT_4_4_4_4: @@ -251,7 +251,7 @@ dst_format = WebGLImageConversion::kDataFormatRGBA2_10_10_10; break; default: - ASSERT_NOT_REACHED(); + NOTREACHED(); } return dst_format; } @@ -401,7 +401,7 @@ // Pixel unpacking routines. template <int format, typename SourceType, typename DstType> void Unpack(const SourceType*, DstType*, unsigned) { - ASSERT_NOT_REACHED(); + NOTREACHED(); } template <> @@ -660,7 +660,7 @@ template <int format, int alphaOp, typename SourceType, typename DstType> void Pack(const SourceType*, DstType*, unsigned) { - ASSERT_NOT_REACHED(); + NOTREACHED(); } template <> @@ -2266,7 +2266,7 @@ unpacked_intermediate_src_data_ = WrapArrayUnique( new uint8_t[src_sub_rectangle_.Width() * kMaxNumberOfComponents * kMaxBytesPerComponent]); - ASSERT(unpacked_intermediate_src_data_.get()); + DCHECK(unpacked_intermediate_src_data_.get()); } void Convert(WebGLImageConversion::DataFormat src_format, @@ -2319,7 +2319,7 @@ FORMATCONVERTER_CASE_SRCFORMAT( WebGLImageConversion::kDataFormatRGBA2_10_10_10) default: - ASSERT_NOT_REACHED(); + NOTREACHED(); } #undef FORMATCONVERTER_CASE_SRCFORMAT } @@ -2361,7 +2361,7 @@ FORMATCONVERTER_CASE_DSTFORMAT(WebGLImageConversion::kDataFormatRG16F) FORMATCONVERTER_CASE_DSTFORMAT(WebGLImageConversion::kDataFormatRG32F) default: - ASSERT_NOT_REACHED(); + NOTREACHED(); } #undef FORMATCONVERTER_CASE_DSTFORMAT @@ -2379,7 +2379,7 @@ FORMATCONVERTER_CASE_ALPHAOP(WebGLImageConversion::kAlphaDoPremultiply) FORMATCONVERTER_CASE_ALPHAOP(WebGLImageConversion::kAlphaDoUnmultiply) default: - ASSERT_NOT_REACHED(); + NOTREACHED(); } #undef FORMATCONVERTER_CASE_ALPHAOP } @@ -2416,11 +2416,11 @@ // try to return immediately in these cases to avoid generating useless code. if (SrcFormat == DstFormat && alphaOp == WebGLImageConversion::kAlphaDoNothing) { - ASSERT_NOT_REACHED(); + NOTREACHED(); return; } if (!IsFloatFormat<DstFormat>::value && IsFloatFormat<SrcFormat>::value) { - ASSERT_NOT_REACHED(); + NOTREACHED(); return; } @@ -2430,25 +2430,25 @@ WebGLImageConversion::SrcFormatComeFromDOMElementOrImageData(SrcFormat); if (!src_format_comes_from_dom_element_or_image_data && SrcFormat != DstFormat) { - ASSERT_NOT_REACHED(); + NOTREACHED(); return; } // Likewise, only textures uploaded from DOM elements or ImageData can // possibly need to be unpremultiplied. if (!src_format_comes_from_dom_element_or_image_data && alphaOp == WebGLImageConversion::kAlphaDoUnmultiply) { - ASSERT_NOT_REACHED(); + NOTREACHED(); return; } if (src_format_comes_from_dom_element_or_image_data && alphaOp == WebGLImageConversion::kAlphaDoUnmultiply && !SupportsConversionFromDomElements<DstFormat>::value) { - ASSERT_NOT_REACHED(); + NOTREACHED(); return; } if ((!HasAlpha(SrcFormat) || !HasColor(SrcFormat) || !HasColor(DstFormat)) && alphaOp != WebGLImageConversion::kAlphaDoNothing) { - ASSERT_NOT_REACHED(); + NOTREACHED(); return; } // If converting DOM element data to UNSIGNED_INT_5_9_9_9_REV or @@ -2458,7 +2458,7 @@ SrcFormat != DstFormat && (DstFormat == WebGLImageConversion::kDataFormatRGB5999 || DstFormat == WebGLImageConversion::kDataFormatRGB10F11F11F)) { - ASSERT_NOT_REACHED(); + NOTREACHED(); return; } @@ -2471,7 +2471,7 @@ const bool kTrivialUnpack = SrcFormat == kIntermFormat; const bool kTrivialPack = DstFormat == kIntermFormat && alphaOp == WebGLImageConversion::kAlphaDoNothing; - ASSERT(!kTrivialUnpack || !kTrivialPack); + DCHECK(!kTrivialUnpack || !kTrivialPack); const SrcType* src_row_start = static_cast<const SrcType*>(static_cast<const void*>( @@ -2635,12 +2635,14 @@ unsigned* image_size_in_bytes, unsigned* padding_in_bytes, unsigned* skip_size_in_bytes) { - ASSERT(image_size_in_bytes); - ASSERT(params.alignment == 1 || params.alignment == 2 || + DCHECK(image_size_in_bytes); + DCHECK(params.alignment == 1 || params.alignment == 2 || params.alignment == 4 || params.alignment == 8); - ASSERT(params.row_length >= 0 && params.image_height >= 0); - ASSERT(params.skip_pixels >= 0 && params.skip_rows >= 0 && - params.skip_images >= 0); + DCHECK_GE(params.row_length, 0); + DCHECK_GE(params.image_height, 0); + DCHECK_GE(params.skip_pixels, 0); + DCHECK_GE(params.skip_rows, 0); + DCHECK_GE(params.skip_images, 0); if (width < 0 || height < 0 || depth < 0) return GL_INVALID_VALUE; if (!width || !height || !depth) { @@ -2752,7 +2754,7 @@ void WebGLImageConversion::ImageExtractor::ExtractImage( bool premultiply_alpha, bool ignore_color_space) { - ASSERT(!image_pixel_locker_); + DCHECK(!image_pixel_locker_); if (!image_) return; @@ -2809,7 +2811,8 @@ image_source_unpack_alignment_ = 0; // FIXME: this seems to always be zero - why use at all? - ASSERT(skia_image->width() && skia_image->height()); + DCHECK(skia_image->width()); + DCHECK(skia_image->height()); image_width_ = skia_image->width(); image_height_ = skia_image->height();
diff --git a/third_party/WebKit/Source/platform/graphics/paint/ClipDisplayItem.h b/third_party/WebKit/Source/platform/graphics/paint/ClipDisplayItem.h index 7488365..7cd25283 100644 --- a/third_party/WebKit/Source/platform/graphics/paint/ClipDisplayItem.h +++ b/third_party/WebKit/Source/platform/graphics/paint/ClipDisplayItem.h
@@ -21,7 +21,7 @@ const IntRect& clip_rect) : PairedBeginDisplayItem(client, type, sizeof(*this)), clip_rect_(clip_rect) { - ASSERT(IsClipType(type)); + DCHECK(IsClipType(type)); } ClipDisplayItem(const DisplayItemClient& client, @@ -56,7 +56,7 @@ public: EndClipDisplayItem(const DisplayItemClient& client, Type type) : PairedEndDisplayItem(client, type, sizeof(*this)) { - ASSERT(IsEndClipType(type)); + DCHECK(IsEndClipType(type)); } void Replay(GraphicsContext&) const override;
diff --git a/third_party/WebKit/Source/platform/graphics/paint/CompositingRecorder.cpp b/third_party/WebKit/Source/platform/graphics/paint/CompositingRecorder.cpp index e39babd..cdcd8fd 100644 --- a/third_party/WebKit/Source/platform/graphics/paint/CompositingRecorder.cpp +++ b/third_party/WebKit/Source/platform/graphics/paint/CompositingRecorder.cpp
@@ -40,10 +40,13 @@ const DisplayItem* last_display_item = paint_controller.LastDisplayItem(0); const DisplayItem* second_to_last_display_item = paint_controller.LastDisplayItem(1); + // TODO(chrishtr): remove the call to LastDisplayItemIsSubsequenceEnd when + // https://codereview.chromium.org/2768143002 lands. if (!RuntimeEnabledFeatures::slimmingPaintV2Enabled() && last_display_item && second_to_last_display_item && last_display_item->DrawsContent() && second_to_last_display_item->GetType() == - DisplayItem::kBeginCompositing) { + DisplayItem::kBeginCompositing && + !paint_controller.LastDisplayItemIsSubsequenceEnd()) { FloatRect cull_rect( ((DrawingDisplayItem*)last_display_item)->GetPaintRecord()->cullRect()); const DisplayItemClient& display_item_client = last_display_item->Client();
diff --git a/third_party/WebKit/Source/platform/graphics/paint/DisplayItem.cpp b/third_party/WebKit/Source/platform/graphics/paint/DisplayItem.cpp index f057e49..0224858 100644 --- a/third_party/WebKit/Source/platform/graphics/paint/DisplayItem.cpp +++ b/third_party/WebKit/Source/platform/graphics/paint/DisplayItem.cpp
@@ -47,7 +47,7 @@ case DisplayItem::kPaintPhaseMax: return "PaintPhaseClippingMask"; default: - ASSERT_NOT_REACHED(); + NOTREACHED(); return "Unknown"; } } @@ -62,9 +62,9 @@ case DisplayItem::k##DisplayItemName: \ return #DisplayItemName -#define DEFAULT_CASE \ - default: \ - ASSERT_NOT_REACHED(); \ +#define DEFAULT_CASE \ + default: \ + NOTREACHED(); \ return "Unknown" static WTF::String SpecialDrawingTypeAsDebugString(DisplayItem::Type type) {
diff --git a/third_party/WebKit/Source/platform/graphics/paint/DisplayItem.h b/third_party/WebKit/Source/platform/graphics/paint/DisplayItem.h index e472c0c..a9afcd1 100644 --- a/third_party/WebKit/Source/platform/graphics/paint/DisplayItem.h +++ b/third_party/WebKit/Source/platform/graphics/paint/DisplayItem.h
@@ -232,7 +232,7 @@ virtual void Replay(GraphicsContext&) const {} const DisplayItemClient& Client() const { - ASSERT(client_); + DCHECK(client_); return *client_; } Type GetType() const { return type_; } @@ -267,12 +267,12 @@ "Categories " #Category1 " and " #Category2 \ " should have same number of enum values. See comments of " \ "DisplayItem::Type"); \ - ASSERT(Is##Category1##Type(type)); \ + DCHECK(Is##Category1##Type(type)); \ return static_cast<Type>(type - k##Category1##First + \ k##Category2##First); \ } \ static Type category2##TypeTo##Category1##Type(Type type) { \ - ASSERT(Is##Category2##Type(type)); \ + DCHECK(Is##Category2##Type(type)); \ return static_cast<Type>(type - k##Category2##First + \ k##Category1##First); \ }
diff --git a/third_party/WebKit/Source/platform/graphics/paint/DisplayItemList.cpp b/third_party/WebKit/Source/platform/graphics/paint/DisplayItemList.cpp index d2243e1..474a7d12 100644 --- a/third_party/WebKit/Source/platform/graphics/paint/DisplayItemList.cpp +++ b/third_party/WebKit/Source/platform/graphics/paint/DisplayItemList.cpp
@@ -19,13 +19,13 @@ #ifndef NDEBUG String original_debug_string = item.AsDebugString(); #endif - ASSERT(item.HasValidClient()); + DCHECK(item.HasValidClient()); DisplayItem& result = ContiguousContainer::AppendByMoving(item, item.DerivedSize()); // ContiguousContainer::appendByMoving() calls an in-place constructor // on item which replaces it with a tombstone/"dead display item" that // can be safely destructed but should never be used. - ASSERT(!item.HasValidClient()); + DCHECK(!item.HasValidClient()); #ifndef NDEBUG // Save original debug string in the old item to help debugging. item.SetClientDebugString(original_debug_string);
diff --git a/third_party/WebKit/Source/platform/graphics/paint/FloatClipDisplayItem.h b/third_party/WebKit/Source/platform/graphics/paint/FloatClipDisplayItem.h index a17936b07..1e74acf 100644 --- a/third_party/WebKit/Source/platform/graphics/paint/FloatClipDisplayItem.h +++ b/third_party/WebKit/Source/platform/graphics/paint/FloatClipDisplayItem.h
@@ -19,7 +19,7 @@ const FloatRect& clip_rect) : PairedBeginDisplayItem(client, type, sizeof(*this)), clip_rect_(clip_rect) { - ASSERT(IsFloatClipType(type)); + DCHECK(IsFloatClipType(type)); } void Replay(GraphicsContext&) const override; @@ -44,7 +44,7 @@ public: EndFloatClipDisplayItem(const DisplayItemClient& client, Type type) : PairedEndDisplayItem(client, type, sizeof(*this)) { - ASSERT(IsEndFloatClipType(type)); + DCHECK(IsEndFloatClipType(type)); } void Replay(GraphicsContext&) const override;
diff --git a/third_party/WebKit/Source/platform/graphics/paint/ForeignLayerDisplayItem.cpp b/third_party/WebKit/Source/platform/graphics/paint/ForeignLayerDisplayItem.cpp index 717573b..35627b7 100644 --- a/third_party/WebKit/Source/platform/graphics/paint/ForeignLayerDisplayItem.cpp +++ b/third_party/WebKit/Source/platform/graphics/paint/ForeignLayerDisplayItem.cpp
@@ -23,21 +23,21 @@ layer_(std::move(layer)), location_(location), bounds_(bounds) { - ASSERT(RuntimeEnabledFeatures::slimmingPaintV2Enabled()); - ASSERT(IsForeignLayerType(type)); - ASSERT(layer_); + DCHECK(RuntimeEnabledFeatures::slimmingPaintV2Enabled()); + DCHECK(IsForeignLayerType(type)); + DCHECK(layer_); } ForeignLayerDisplayItem::~ForeignLayerDisplayItem() {} void ForeignLayerDisplayItem::Replay(GraphicsContext&) const { - ASSERT_NOT_REACHED(); + NOTREACHED(); } void ForeignLayerDisplayItem::AppendToWebDisplayItemList( const IntRect&, WebDisplayItemList*) const { - ASSERT_NOT_REACHED(); + NOTREACHED(); } bool ForeignLayerDisplayItem::DrawsContent() const {
diff --git a/third_party/WebKit/Source/platform/graphics/paint/GeometryMapper.cpp b/third_party/WebKit/Source/platform/graphics/paint/GeometryMapper.cpp index c627863d..e44d8d0 100644 --- a/third_party/WebKit/Source/platform/graphics/paint/GeometryMapper.cpp +++ b/third_party/WebKit/Source/platform/graphics/paint/GeometryMapper.cpp
@@ -119,7 +119,7 @@ FloatRect mapped_rect = transform_matrix.MapRect(rect_to_map.Rect()); - FloatClipRect clip_rect = + const FloatClipRect& clip_rect = LocalToAncestorClipRectInternal(local_state.Clip(), ancestor_state.Clip(), ancestor_state.Transform(), success); @@ -136,6 +136,7 @@ // --enable-prefer-compositing-to-lcd-text) for details. // Ignore it for SPv1 for now. success = true; + rect_to_map.SetRect(mapped_rect); } } @@ -213,11 +214,11 @@ rect = transform_matrix.Inverse().MapRect(rect); } -FloatClipRect GeometryMapper::LocalToAncestorClipRect( +const FloatClipRect& GeometryMapper::LocalToAncestorClipRect( const PropertyTreeState& local_state, const PropertyTreeState& ancestor_state) { bool success = false; - FloatClipRect result = + const FloatClipRect& result = LocalToAncestorClipRectInternal(local_state.Clip(), ancestor_state.Clip(), ancestor_state.Transform(), success);
diff --git a/third_party/WebKit/Source/platform/graphics/paint/GeometryMapper.h b/third_party/WebKit/Source/platform/graphics/paint/GeometryMapper.h index 2856cc4..559e131c 100644 --- a/third_party/WebKit/Source/platform/graphics/paint/GeometryMapper.h +++ b/third_party/WebKit/Source/platform/graphics/paint/GeometryMapper.h
@@ -138,7 +138,7 @@ // The output FloatClipRect may contain false positives for rounded-ness // if a rounded clip is clipped out, and overly conservative results // in the presences of transforms. - static FloatClipRect LocalToAncestorClipRect( + static const FloatClipRect& LocalToAncestorClipRect( const PropertyTreeState& local_transform_state, const PropertyTreeState& ancestor_state);
diff --git a/third_party/WebKit/Source/platform/graphics/paint/GeometryMapperTest.cpp b/third_party/WebKit/Source/platform/graphics/paint/GeometryMapperTest.cpp index 805cbda..4db405b 100644 --- a/third_party/WebKit/Source/platform/graphics/paint/GeometryMapperTest.cpp +++ b/third_party/WebKit/Source/platform/graphics/paint/GeometryMapperTest.cpp
@@ -17,10 +17,13 @@ namespace blink { -class GeometryMapperTest : public ::testing::Test, - public ScopedSlimmingPaintV2ForTest { +typedef bool SlimmingPaintV2Enabled; +class GeometryMapperTest + : public ::testing::Test, + public ::testing::WithParamInterface<SlimmingPaintV2Enabled>, + public ScopedSlimmingPaintV2ForTest { public: - GeometryMapperTest() : ScopedSlimmingPaintV2ForTest(true) {} + GeometryMapperTest() : ScopedSlimmingPaintV2ForTest(GetParam()) {} const FloatClipRect* GetClip( const ClipPaintPropertyNode* descendant_clip, @@ -78,6 +81,10 @@ private: }; +bool values[] = {false, true}; + +INSTANTIATE_TEST_CASE_P(All, GeometryMapperTest, ::testing::ValuesIn(values)); + const static float kTestEpsilon = 1e-6; #define EXPECT_RECT_EQ(expected, actual) \ @@ -157,7 +164,7 @@ } \ } while (false) -TEST_F(GeometryMapperTest, Root) { +TEST_P(GeometryMapperTest, Root) { FloatRect input(0, 0, 100, 100); bool has_radius = false; @@ -166,7 +173,7 @@ PropertyTreeState::Root(), PropertyTreeState::Root()); } -TEST_F(GeometryMapperTest, IdentityTransform) { +TEST_P(GeometryMapperTest, IdentityTransform) { RefPtr<TransformPaintPropertyNode> transform = TransformPaintPropertyNode::Create(TransformPaintPropertyNode::Root(), TransformationMatrix(), @@ -181,7 +188,7 @@ local_state, PropertyTreeState::Root()); } -TEST_F(GeometryMapperTest, TranslationTransform) { +TEST_P(GeometryMapperTest, TranslationTransform) { TransformationMatrix transform_matrix; transform_matrix.Translate(20, 10); RefPtr<TransformPaintPropertyNode> transform = @@ -202,7 +209,7 @@ EXPECT_RECT_EQ(input, output); } -TEST_F(GeometryMapperTest, RotationAndScaleTransform) { +TEST_P(GeometryMapperTest, RotationAndScaleTransform) { TransformationMatrix transform_matrix; transform_matrix.Rotate(45); transform_matrix.Scale(2); @@ -221,7 +228,7 @@ local_state, PropertyTreeState::Root()); } -TEST_F(GeometryMapperTest, RotationAndScaleTransformWithTransformOrigin) { +TEST_P(GeometryMapperTest, RotationAndScaleTransformWithTransformOrigin) { TransformationMatrix transform_matrix; transform_matrix.Rotate(45); transform_matrix.Scale(2); @@ -241,7 +248,7 @@ local_state, PropertyTreeState::Root()); } -TEST_F(GeometryMapperTest, NestedTransforms) { +TEST_P(GeometryMapperTest, NestedTransforms) { TransformationMatrix rotate_transform; rotate_transform.Rotate(45); RefPtr<TransformPaintPropertyNode> transform1 = @@ -271,7 +278,7 @@ *GetTransform(transform1.Get(), TransformPaintPropertyNode::Root())); } -TEST_F(GeometryMapperTest, NestedTransformsFlattening) { +TEST_P(GeometryMapperTest, NestedTransformsFlattening) { TransformationMatrix rotate_transform; rotate_transform.Rotate3d(45, 0, 0); RefPtr<TransformPaintPropertyNode> transform1 = @@ -297,7 +304,7 @@ PropertyTreeState::Root()); } -TEST_F(GeometryMapperTest, NestedTransformsScaleAndTranslation) { +TEST_P(GeometryMapperTest, NestedTransformsScaleAndTranslation) { TransformationMatrix scale_transform; scale_transform.Scale(2); RefPtr<TransformPaintPropertyNode> transform1 = @@ -328,7 +335,7 @@ TransformPaintPropertyNode::Root())); } -TEST_F(GeometryMapperTest, NestedTransformsIntermediateDestination) { +TEST_P(GeometryMapperTest, NestedTransformsIntermediateDestination) { TransformationMatrix rotate_transform; rotate_transform.Rotate(45); RefPtr<TransformPaintPropertyNode> transform1 = @@ -355,7 +362,7 @@ local_state, intermediate_state); } -TEST_F(GeometryMapperTest, SimpleClip) { +TEST_P(GeometryMapperTest, SimpleClip) { RefPtr<ClipPaintPropertyNode> clip = ClipPaintPropertyNode::Create( ClipPaintPropertyNode::Root(), TransformPaintPropertyNode::Root(), FloatRoundedRect(10, 10, 50, 50)); @@ -377,7 +384,7 @@ local_state, PropertyTreeState::Root()); } -TEST_F(GeometryMapperTest, RoundedClip) { +TEST_P(GeometryMapperTest, RoundedClip) { FloatRoundedRect rect(FloatRect(10, 10, 50, 50), FloatRoundedRect::Radii(FloatSize(1, 1), FloatSize(), FloatSize(), FloatSize())); @@ -403,7 +410,7 @@ local_state, PropertyTreeState::Root()); } -TEST_F(GeometryMapperTest, TwoClips) { +TEST_P(GeometryMapperTest, TwoClips) { FloatRoundedRect clip_rect1( FloatRect(10, 10, 30, 40), FloatRoundedRect::Radii(FloatSize(1, 1), FloatSize(), FloatSize(), @@ -452,7 +459,7 @@ local_state, ancestor_state); } -TEST_F(GeometryMapperTest, TwoClipsTransformAbove) { +TEST_P(GeometryMapperTest, TwoClipsTransformAbove) { RefPtr<TransformPaintPropertyNode> transform = TransformPaintPropertyNode::Create(TransformPaintPropertyNode::Root(), TransformationMatrix(), @@ -500,7 +507,7 @@ local_state, ancestor_state); } -TEST_F(GeometryMapperTest, ClipBeforeTransform) { +TEST_P(GeometryMapperTest, ClipBeforeTransform) { TransformationMatrix rotate_transform; rotate_transform.Rotate(45); RefPtr<TransformPaintPropertyNode> transform = @@ -531,7 +538,7 @@ local_state, PropertyTreeState::Root()); } -TEST_F(GeometryMapperTest, ClipAfterTransform) { +TEST_P(GeometryMapperTest, ClipAfterTransform) { TransformationMatrix rotate_transform; rotate_transform.Rotate(45); RefPtr<TransformPaintPropertyNode> transform = @@ -561,7 +568,7 @@ local_state, PropertyTreeState::Root()); } -TEST_F(GeometryMapperTest, TwoClipsWithTransformBetween) { +TEST_P(GeometryMapperTest, TwoClipsWithTransformBetween) { RefPtr<ClipPaintPropertyNode> clip1 = ClipPaintPropertyNode::Create( ClipPaintPropertyNode::Root(), TransformPaintPropertyNode::Root(), FloatRoundedRect(10, 10, 200, 200)); @@ -623,7 +630,7 @@ } } -TEST_F(GeometryMapperTest, SiblingTransforms) { +TEST_P(GeometryMapperTest, SiblingTransforms) { // These transforms are siblings. Thus mapping from one to the other requires // going through the root. TransformationMatrix rotate_transform1; @@ -688,7 +695,7 @@ EXPECT_RECT_EQ(expected, result); } -TEST_F(GeometryMapperTest, SiblingTransformsWithClip) { +TEST_P(GeometryMapperTest, SiblingTransformsWithClip) { // These transforms are siblings. Thus mapping from one to the other requires // going through the root. TransformationMatrix rotate_transform1; @@ -757,7 +764,7 @@ EXPECT_RECT_EQ(expected_unclipped, result); } -TEST_F(GeometryMapperTest, LowestCommonAncestor) { +TEST_P(GeometryMapperTest, LowestCommonAncestor) { TransformationMatrix matrix; RefPtr<TransformPaintPropertyNode> child1 = TransformPaintPropertyNode::Create(TransformPaintPropertyNode::Root(), @@ -793,7 +800,7 @@ LowestCommonAncestor(child1.Get(), child2.Get())); } -TEST_F(GeometryMapperTest, FilterWithClipsAndTransforms) { +TEST_P(GeometryMapperTest, FilterWithClipsAndTransforms) { RefPtr<TransformPaintPropertyNode> transform_above_effect = TransformPaintPropertyNode::Create(TransformPaintPropertyNode::Root(), TransformationMatrix().Scale(3), @@ -846,7 +853,7 @@ PropertyTreeState::Root()); } -TEST_F(GeometryMapperTest, ReflectionWithPaintOffset) { +TEST_P(GeometryMapperTest, ReflectionWithPaintOffset) { CompositorFilterOperations filters; filters.AppendReferenceFilter(SkiaImageFilterBuilder::BuildBoxReflectFilter( BoxReflection(BoxReflection::kHorizontalReflection, 0), nullptr)); @@ -868,4 +875,25 @@ local_state, PropertyTreeState::Root()); } +TEST_P(GeometryMapperTest, InvertedClip) { + if (RuntimeEnabledFeatures::slimmingPaintV2Enabled()) + return; + + RefPtr<ClipPaintPropertyNode> clip = ClipPaintPropertyNode::Create( + ClipPaintPropertyNode::Root(), TransformPaintPropertyNode::Root(), + FloatRoundedRect(10, 10, 50, 50)); + + PropertyTreeState dest(TransformPaintPropertyNode::Root(), clip.Get(), + EffectPaintPropertyNode::Root()); + + FloatClipRect floatClipRect(FloatRect(0, 0, 10, 200)); + GeometryMapper::LocalToAncestorVisualRect(PropertyTreeState::Root(), dest, + floatClipRect); + + // The "ancestor" clip is below the source clip in this case, so + // LocalToAncestorVisualRect must fall back to the original rect, mapped + // into the root space. + EXPECT_EQ(FloatRect(0, 0, 10, 200), floatClipRect.Rect()); +} + } // namespace blink
diff --git a/third_party/WebKit/Source/platform/graphics/paint/PaintChunk.h b/third_party/WebKit/Source/platform/graphics/paint/PaintChunk.h index cc76574..74c0d28 100644 --- a/third_party/WebKit/Source/platform/graphics/paint/PaintChunk.h +++ b/third_party/WebKit/Source/platform/graphics/paint/PaintChunk.h
@@ -37,7 +37,7 @@ } size_t size() const { - ASSERT(end_index >= begin_index); + DCHECK_GE(end_index, begin_index); return end_index - begin_index; }
diff --git a/third_party/WebKit/Source/platform/graphics/paint/PaintController.cpp b/third_party/WebKit/Source/platform/graphics/paint/PaintController.cpp index 0b017b04..e26681df 100644 --- a/third_party/WebKit/Source/platform/graphics/paint/PaintController.cpp +++ b/third_party/WebKit/Source/platform/graphics/paint/PaintController.cpp
@@ -163,6 +163,7 @@ new_cached_subsequences_.end()); new_cached_subsequences_.insert(&client, SubsequenceMarkers(start, end)); + last_cached_subsequence_end_ = end; } bool PaintController::LastDisplayItemIsNoopBegin() const { @@ -173,6 +174,11 @@ return last_display_item.IsBegin() && !last_display_item.DrawsContent(); } +bool PaintController::LastDisplayItemIsSubsequenceEnd() const { + return !new_cached_subsequences_.IsEmpty() && + last_cached_subsequence_end_ == new_display_item_list_.size() - 1; +} + void PaintController::RemoveLastDisplayItem() { if (new_display_item_list_.IsEmpty()) return; @@ -536,10 +542,12 @@ new_cached_subsequences_.Swap(current_cached_subsequences_); new_cached_subsequences_.Clear(); + last_cached_subsequence_end_ = 0; for (auto& item : current_cached_subsequences_) { item.key->SetDisplayItemsCached(current_cache_generation_); #if CHECK_DISPLAY_ITEM_CLIENT_ALIVENESS DisplayItemClient::EndShouldKeepAliveAllClients(item.key); + DCHECK(current_subsequence_clients_.IsEmpty()); #endif }
diff --git a/third_party/WebKit/Source/platform/graphics/paint/PaintController.h b/third_party/WebKit/Source/platform/graphics/paint/PaintController.h index 10637ce2..5bfc86e 100644 --- a/third_party/WebKit/Source/platform/graphics/paint/PaintController.h +++ b/third_party/WebKit/Source/platform/graphics/paint/PaintController.h
@@ -209,6 +209,8 @@ void EndSubsequence() { current_subsequence_clients_.pop_back(); } #endif + bool LastDisplayItemIsSubsequenceEnd() const; + protected: PaintController() : new_display_item_list_(0), @@ -226,7 +228,8 @@ num_indexed_items_(0), #endif under_invalidation_checking_begin_(0), - under_invalidation_checking_end_(0) { + under_invalidation_checking_end_(0), + last_cached_subsequence_end_(0) { ResetCurrentListIndices(); SetTracksRasterInvalidations( RuntimeEnabledFeatures::paintUnderInvalidationCheckingEnabled()); @@ -419,6 +422,7 @@ CachedSubsequenceMap; CachedSubsequenceMap current_cached_subsequences_; CachedSubsequenceMap new_cached_subsequences_; + size_t last_cached_subsequence_end_; FRIEND_TEST_ALL_PREFIXES(PaintControllerTest, CachedSubsequenceSwapOrder); FRIEND_TEST_ALL_PREFIXES(PaintControllerTest, CachedNestedSubsequenceUpdate);
diff --git a/third_party/WebKit/Source/platform/graphics/paint/PaintControllerTest.cpp b/third_party/WebKit/Source/platform/graphics/paint/PaintControllerTest.cpp index a5c53a9..f5f45cc8 100644 --- a/third_party/WebKit/Source/platform/graphics/paint/PaintControllerTest.cpp +++ b/third_party/WebKit/Source/platform/graphics/paint/PaintControllerTest.cpp
@@ -66,10 +66,10 @@ TestDisplayItem(const FakeDisplayItemClient& client, Type type) : DisplayItem(client, type, sizeof(*this)) {} - void Replay(GraphicsContext&) const final { ASSERT_NOT_REACHED(); } + void Replay(GraphicsContext&) const final { NOTREACHED(); } void AppendToWebDisplayItemList(const IntRect&, WebDisplayItemList*) const final { - ASSERT_NOT_REACHED(); + NOTREACHED(); } }; @@ -2113,6 +2113,8 @@ } void TestNoopPairsInSubsequence() { + EXPECT_FALSE(GetPaintController().LastDisplayItemIsSubsequenceEnd()); + FakeDisplayItemClient container("container"); GraphicsContext context(GetPaintController()); @@ -2140,6 +2142,8 @@ DrawRect(context, container, kBackgroundDrawingType, FloatRect(100, 100, 100, 100)); } + EXPECT_TRUE(GetPaintController().LastDisplayItemIsSubsequenceEnd()); + GetPaintController().CommitNewDisplayItems(); #if CHECK_DISPLAY_ITEM_CLIENT_ALIVENESS
diff --git a/third_party/WebKit/Source/platform/graphics/paint/ScrollDisplayItem.h b/third_party/WebKit/Source/platform/graphics/paint/ScrollDisplayItem.h index 3cbd7fa..6dfca71 100644 --- a/third_party/WebKit/Source/platform/graphics/paint/ScrollDisplayItem.h +++ b/third_party/WebKit/Source/platform/graphics/paint/ScrollDisplayItem.h
@@ -19,7 +19,7 @@ const IntSize& current_offset) : PairedBeginDisplayItem(client, type, sizeof(*this)), current_offset_(current_offset) { - ASSERT(IsScrollType(type)); + DCHECK(IsScrollType(type)); } void Replay(GraphicsContext&) const override; @@ -45,7 +45,7 @@ public: EndScrollDisplayItem(const DisplayItemClient& client, Type type) : PairedEndDisplayItem(client, type, sizeof(*this)) { - ASSERT(IsEndScrollType(type)); + DCHECK(IsEndScrollType(type)); } void Replay(GraphicsContext&) const override;
diff --git a/third_party/WebKit/Source/platform/graphics/paint/SubsequenceRecorder.cpp b/third_party/WebKit/Source/platform/graphics/paint/SubsequenceRecorder.cpp index 1d2d7fa9..b35795d6 100644 --- a/third_party/WebKit/Source/platform/graphics/paint/SubsequenceRecorder.cpp +++ b/third_party/WebKit/Source/platform/graphics/paint/SubsequenceRecorder.cpp
@@ -15,14 +15,14 @@ : paint_controller_(context.GetPaintController()), client_(client), begin_subsequence_index_(0) { +#if CHECK_DISPLAY_ITEM_CLIENT_ALIVENESS + paint_controller_.BeginSubsequence(client_); +#endif + if (paint_controller_.DisplayItemConstructionIsDisabled()) return; begin_subsequence_index_ = paint_controller_.NewDisplayItemList().size(); - -#if CHECK_DISPLAY_ITEM_CLIENT_ALIVENESS - paint_controller_.BeginSubsequence(client_); -#endif } SubsequenceRecorder::~SubsequenceRecorder() {
diff --git a/third_party/WebKit/Source/platform/graphics/paint/Transform3DDisplayItem.h b/third_party/WebKit/Source/platform/graphics/paint/Transform3DDisplayItem.h index d8a6bf2..46d91b11 100644 --- a/third_party/WebKit/Source/platform/graphics/paint/Transform3DDisplayItem.h +++ b/third_party/WebKit/Source/platform/graphics/paint/Transform3DDisplayItem.h
@@ -22,7 +22,7 @@ : PairedBeginDisplayItem(client, type, sizeof(*this)), transform_(transform), transform_origin_(transform_origin) { - ASSERT(DisplayItem::IsTransform3DType(type)); + DCHECK(DisplayItem::IsTransform3DType(type)); } void Replay(GraphicsContext&) const override; @@ -54,7 +54,7 @@ public: EndTransform3DDisplayItem(const DisplayItemClient& client, Type type) : PairedEndDisplayItem(client, type, sizeof(*this)) { - ASSERT(DisplayItem::IsEndTransform3DType(type)); + DCHECK(DisplayItem::IsEndTransform3DType(type)); } void Replay(GraphicsContext&) const override;
diff --git a/third_party/WebKit/Source/platform/graphics/skia/ImagePixelLocker.cpp b/third_party/WebKit/Source/platform/graphics/skia/ImagePixelLocker.cpp index b9399d8..23234582 100644 --- a/third_party/WebKit/Source/platform/graphics/skia/ImagePixelLocker.cpp +++ b/third_party/WebKit/Source/platform/graphics/skia/ImagePixelLocker.cpp
@@ -14,7 +14,7 @@ bool InfoIsCompatible(const SkImageInfo& info, SkAlphaType alpha_type, SkColorType color_type) { - ASSERT(alpha_type != kUnknown_SkAlphaType); + DCHECK_NE(alpha_type, kUnknown_SkAlphaType); if (info.colorType() != color_type) return false;
diff --git a/third_party/WebKit/Source/platform/graphics/skia/SkiaUtils.cpp b/third_party/WebKit/Source/platform/graphics/skia/SkiaUtils.cpp index a502c53..a417e148 100644 --- a/third_party/WebKit/Source/platform/graphics/skia/SkiaUtils.cpp +++ b/third_party/WebKit/Source/platform/graphics/skia/SkiaUtils.cpp
@@ -76,7 +76,7 @@ SkBlendMode WebCoreCompositeToSkiaComposite(CompositeOperator op, WebBlendMode blend_mode) { - ASSERT(op == kCompositeSourceOver || blend_mode == kWebBlendModeNormal); + DCHECK(op == kCompositeSourceOver || blend_mode == kWebBlendModeNormal); if (blend_mode != kWebBlendModeNormal) { if (static_cast<uint8_t>(blend_mode) >= SK_ARRAY_COUNT(kGMapBlendOpsToXfermodeModes)) { @@ -311,7 +311,7 @@ PaintCanvas*, const PaintFlags&, float corner_radius) { - ASSERT_NOT_REACHED(); // Missing an explicit specialization? + NOTREACHED(); // Missing an explicit specialization? } template <>
diff --git a/third_party/WebKit/Source/platform/graphics/skia/SkiaUtils.h b/third_party/WebKit/Source/platform/graphics/skia/SkiaUtils.h index 2469c7f..93b6db0 100644 --- a/third_party/WebKit/Source/platform/graphics/skia/SkiaUtils.h +++ b/third_party/WebKit/Source/platform/graphics/skia/SkiaUtils.h
@@ -101,7 +101,7 @@ case SkPath::kEvenOdd_FillType: return static_cast<WindRule>(fill_type); default: - ASSERT_NOT_REACHED(); + NOTREACHED(); break; } return RULE_NONZERO;
diff --git a/third_party/WebKit/Source/platform/scheduler/base/real_time_domain.cc b/third_party/WebKit/Source/platform/scheduler/base/real_time_domain.cc index ac1cb052..802e56f6 100644 --- a/third_party/WebKit/Source/platform/scheduler/base/real_time_domain.cc +++ b/third_party/WebKit/Source/platform/scheduler/base/real_time_domain.cc
@@ -13,15 +13,7 @@ namespace scheduler { RealTimeDomain::RealTimeDomain(const char* tracing_category) - : TimeDomain(nullptr), - tracing_category_(tracing_category), - task_queue_manager_(nullptr) {} - -RealTimeDomain::RealTimeDomain(TimeDomain::Observer* observer, - const char* tracing_category) - : TimeDomain(observer), - tracing_category_(tracing_category), - task_queue_manager_(nullptr) {} + : tracing_category_(tracing_category), task_queue_manager_(nullptr) {} RealTimeDomain::~RealTimeDomain() {}
diff --git a/third_party/WebKit/Source/platform/scheduler/base/real_time_domain.h b/third_party/WebKit/Source/platform/scheduler/base/real_time_domain.h index b8a5bd5..872cde9 100644 --- a/third_party/WebKit/Source/platform/scheduler/base/real_time_domain.h +++ b/third_party/WebKit/Source/platform/scheduler/base/real_time_domain.h
@@ -17,7 +17,6 @@ class BLINK_PLATFORM_EXPORT RealTimeDomain : public TimeDomain { public: explicit RealTimeDomain(const char* tracing_category); - RealTimeDomain(TimeDomain::Observer* observer, const char* tracing_category); ~RealTimeDomain() override; // TimeDomain implementation:
diff --git a/third_party/WebKit/Source/platform/scheduler/base/task_queue_impl.cc b/third_party/WebKit/Source/platform/scheduler/base/task_queue_impl.cc index 1006ce0..1ff9b277a 100644 --- a/third_party/WebKit/Source/platform/scheduler/base/task_queue_impl.cc +++ b/third_party/WebKit/Source/platform/scheduler/base/task_queue_impl.cc
@@ -102,7 +102,6 @@ // destructor calls UnregisterTaskQueue on all task queues. DCHECK(any_thread().task_queue_manager == nullptr) << "UnregisterTaskQueue must be called first!"; - #endif } @@ -147,7 +146,9 @@ TaskQueueImpl::AnyThread::AnyThread(TaskQueueManager* task_queue_manager, TimeDomain* time_domain) - : task_queue_manager(task_queue_manager), time_domain(time_domain) {} + : task_queue_manager(task_queue_manager), + time_domain(time_domain), + observer(nullptr) {} TaskQueueImpl::AnyThread::~AnyThread() {} @@ -157,6 +158,7 @@ TimeDomain* time_domain) : task_queue_manager(task_queue_manager), time_domain(time_domain), + observer(nullptr), delayed_work_queue( new WorkQueue(task_queue, "delayed", WorkQueue::QueueType::DELAYED)), immediate_work_queue(new WorkQueue(task_queue, @@ -183,6 +185,8 @@ any_thread().task_queue_manager = nullptr; main_thread_only().task_queue_manager = nullptr; + any_thread().observer = nullptr; + main_thread_only().observer = nullptr; main_thread_only().delayed_incoming_queue = std::priority_queue<Task>(); immediate_incoming_queue().Clear(); main_thread_only().immediate_work_queue.reset(); @@ -277,7 +281,7 @@ void TaskQueueImpl::PushOntoDelayedIncomingQueueFromMainThread( Task pending_task, base::TimeTicks now) { - base::TimeTicks delayed_run_time = pending_task.delayed_run_time; + DelayedWakeUp wake_up = pending_task.delayed_wake_up(); main_thread_only().task_queue_manager->DidQueueTask(pending_task); main_thread_only().delayed_incoming_queue.push(std::move(pending_task)); @@ -285,11 +289,11 @@ // is requested if the queue is enabled. Note we still want to schedule a // wake-up even if blocked by a fence, because we'd break throttling logic // otherwise. - base::TimeTicks next_delayed_task = - main_thread_only().delayed_incoming_queue.top().delayed_run_time; - if (next_delayed_task == delayed_run_time && IsQueueEnabled()) { - main_thread_only().time_domain->ScheduleDelayedWork( - this, {delayed_run_time, pending_task.sequence_num}, now); + DelayedWakeUp new_wake_up = + main_thread_only().delayed_incoming_queue.top().delayed_wake_up(); + if (wake_up.time == new_wake_up.time && + wake_up.sequence_num == new_wake_up.sequence_num) { + ScheduleDelayedWorkInTimeDomain(now); } TraceQueueSize(); @@ -358,7 +362,8 @@ (!IsQueueEnabled() || main_thread_only().current_fence); any_thread().task_queue_manager->OnQueueHasIncomingImmediateWork( this, sequence_number, queue_is_blocked); - any_thread().time_domain->OnQueueHasImmediateWork(this); + if (any_thread().observer) + any_thread().observer->OnQueueNextWakeUpChanged(this, desired_run_time); } TraceQueueSize(); @@ -449,9 +454,7 @@ // Make sure the next wake up is scheduled. if (!main_thread_only().delayed_incoming_queue.empty()) { - return DelayedWakeUp{ - main_thread_only().delayed_incoming_queue.top().delayed_run_time, - main_thread_only().delayed_incoming_queue.top().sequence_num}; + return main_thread_only().delayed_incoming_queue.top().delayed_wake_up(); } return base::nullopt; @@ -598,13 +601,7 @@ main_thread_only().time_domain = time_domain; time_domain->RegisterQueue(this); - if (IsQueueEnabled() && !main_thread_only().delayed_incoming_queue.empty()) { - time_domain->ScheduleDelayedWork( - this, - {main_thread_only().delayed_incoming_queue.top().delayed_run_time, - main_thread_only().delayed_incoming_queue.top().sequence_num}, - time_domain->Now()); - } + ScheduleDelayedWorkInTimeDomain(time_domain->Now()); } TimeDomain* TaskQueueImpl::GetTimeDomain() const { @@ -816,24 +813,11 @@ return; if (enable) { - // Check if there's any immediate work on either queue. - bool immediate_queues_empty = - main_thread_only().immediate_work_queue->Empty(); - if (immediate_queues_empty) { - base::AutoLock lock(immediate_incoming_queue_lock_); - immediate_queues_empty = immediate_incoming_queue().empty(); - } - // Avoid holding the lock while we fire the notification. - if (!immediate_queues_empty) - main_thread_only().time_domain->OnQueueHasImmediateWork(this); + if (HasPendingImmediateWork()) + NotifyWakeUpChangedOnMainThread(base::TimeTicks()); - if (!main_thread_only().delayed_incoming_queue.empty()) { - main_thread_only().time_domain->ScheduleDelayedWork( - this, - {main_thread_only().delayed_incoming_queue.top().delayed_run_time, - main_thread_only().delayed_incoming_queue.top().sequence_num}, - main_thread_only().time_domain->Now()); - } + ScheduleDelayedWorkInTimeDomain(main_thread_only().time_domain->Now()); + // Note the selector calls TaskQueueManager::OnTaskQueueEnabled which posts // a DoWork if needed. main_thread_only().task_queue_manager->selector_.EnableQueue(this); @@ -875,13 +859,7 @@ main_thread_only().time_domain->CancelDelayedWork(this); } else if (first_task_runtime != main_thread_only().delayed_incoming_queue.top().delayed_run_time) { - if (IsQueueEnabled()) { - main_thread_only().time_domain->ScheduleDelayedWork( - this, - {main_thread_only().delayed_incoming_queue.top().delayed_run_time, - main_thread_only().delayed_incoming_queue.top().sequence_num}, - main_thread_only().time_domain->Now()); - } + ScheduleDelayedWorkInTimeDomain(main_thread_only().time_domain->Now()); } } @@ -891,6 +869,40 @@ immediate_incoming_queue().push_back(std::move(task)); } +void TaskQueueImpl::SetObserver(Observer* observer) { +#if DCHECK_IS_ON() + if (observer) { + DCHECK(!main_thread_only().observer) << "Can't assign two different " + "observers to " + "blink::scheduler::TaskQueue"; + } +#endif + base::AutoLock lock(any_thread_lock_); + any_thread().observer = observer; + main_thread_only().observer = observer; +} + +void TaskQueueImpl::ScheduleDelayedWorkInTimeDomain(base::TimeTicks now) { + if (!IsQueueEnabled()) + return; + if (main_thread_only().delayed_incoming_queue.empty()) + return; + + main_thread_only().time_domain->ScheduleDelayedWork( + this, main_thread_only().delayed_incoming_queue.top().delayed_wake_up(), + now); + + if (!HasPendingImmediateWork()) { + NotifyWakeUpChangedOnMainThread( + main_thread_only().delayed_incoming_queue.top().delayed_run_time); + } +} + +void TaskQueueImpl::NotifyWakeUpChangedOnMainThread(base::TimeTicks wake_up) { + if (main_thread_only().observer) + main_thread_only().observer->OnQueueNextWakeUpChanged(this, wake_up); +} + } // namespace internal } // namespace scheduler } // namespace blink
diff --git a/third_party/WebKit/Source/platform/scheduler/base/task_queue_impl.h b/third_party/WebKit/Source/platform/scheduler/base/task_queue_impl.h index e1c3a85..02be214e 100644 --- a/third_party/WebKit/Source/platform/scheduler/base/task_queue_impl.h +++ b/third_party/WebKit/Source/platform/scheduler/base/task_queue_impl.h
@@ -65,6 +65,21 @@ const char* disabled_by_default_tracing_category, const char* disabled_by_default_verbose_tracing_category); + // Represents a time at which a task wants to run. Tasks scheduled for the + // same point in time will be ordered by their sequence numbers. + struct DelayedWakeUp { + base::TimeTicks time; + int sequence_num; + + bool operator<=(const DelayedWakeUp& other) const { + if (time == other.time) { + DCHECK_NE(sequence_num, other.sequence_num); + return (sequence_num - other.sequence_num) < 0; + } + return time < other.time; + } + }; + class BLINK_PLATFORM_EXPORT Task : public base::PendingTask { public: Task(); @@ -81,6 +96,10 @@ bool nestable, EnqueueOrder enqueue_order); + DelayedWakeUp delayed_wake_up() const { + return DelayedWakeUp{delayed_run_time, sequence_num}; + } + EnqueueOrder enqueue_order() const { #ifndef NDEBUG DCHECK(enqueue_order_set_); @@ -112,21 +131,6 @@ EnqueueOrder enqueue_order_; }; - // Represents a time at which a task wants to run. Tasks scheduled for the - // same point in time will be ordered by their sequence numbers. - struct DelayedWakeUp { - base::TimeTicks time; - int sequence_num; - - bool operator<=(const DelayedWakeUp& other) const { - if (time == other.time) { - DCHECK_NE(sequence_num, other.sequence_num); - return (sequence_num - other.sequence_num) < 0; - } - return time < other.time; - } - }; - // TaskQueue implementation. void UnregisterTaskQueue() override; bool RunsTasksOnCurrentThread() const override; @@ -155,6 +159,7 @@ bool BlockedByFence() const override; const char* GetName() const override; QueueType GetQueueType() const override; + void SetObserver(Observer* observer) override; // Returns true if a (potentially hypothetical) task with the specified // |enqueue_order| could run on the queue. Must be called from the main @@ -249,11 +254,12 @@ AnyThread(TaskQueueManager* task_queue_manager, TimeDomain* time_domain); ~AnyThread(); - // TaskQueueManager and TimeDomain are maintained in two copies: + // TaskQueueManager, TimeDomain and Observer are maintained in two copies: // inside AnyThread and inside MainThreadOnly. They can be changed only from // main thread, so it should be locked before accessing from other threads. TaskQueueManager* task_queue_manager; TimeDomain* time_domain; + Observer* observer; }; struct MainThreadOnly { @@ -262,10 +268,12 @@ TimeDomain* time_domain); ~MainThreadOnly(); - // Another copy of TaskQueueManager and TimeDomain for lock-free access from - // the main thread. See description inside struct AnyThread for details. + // Another copy of TaskQueueManager, TimeDomain and Observer + // for lock-free access from the main thread. + // See description inside struct AnyThread for details. TaskQueueManager* task_queue_manager; TimeDomain* time_domain; + Observer* observer; std::unique_ptr<WorkQueue> delayed_work_queue; std::unique_ptr<WorkQueue> immediate_work_queue; @@ -329,6 +337,11 @@ void OnQueueEnabledVoteChanged(bool enabled); void EnableOrDisableWithSelector(bool enable); + // Schedules delayed work on time domain and calls the observer. + void ScheduleDelayedWorkInTimeDomain(base::TimeTicks now); + + void NotifyWakeUpChangedOnMainThread(base::TimeTicks wake_up); + const base::PlatformThreadId thread_id_; mutable base::Lock any_thread_lock_;
diff --git a/third_party/WebKit/Source/platform/scheduler/base/task_queue_manager_perftest.cc b/third_party/WebKit/Source/platform/scheduler/base/task_queue_manager_perftest.cc index a0e4922cb..8a9138e 100644 --- a/third_party/WebKit/Source/platform/scheduler/base/task_queue_manager_perftest.cc +++ b/third_party/WebKit/Source/platform/scheduler/base/task_queue_manager_perftest.cc
@@ -29,7 +29,7 @@ // fast forward the timers. class PerfTestTimeDomain : public VirtualTimeDomain { public: - PerfTestTimeDomain() : VirtualTimeDomain(nullptr, base::TimeTicks::Now()) {} + PerfTestTimeDomain() : VirtualTimeDomain(base::TimeTicks::Now()) {} ~PerfTestTimeDomain() override {} base::Optional<base::TimeDelta> DelayTillNextTask(
diff --git a/third_party/WebKit/Source/platform/scheduler/base/task_queue_manager_unittest.cc b/third_party/WebKit/Source/platform/scheduler/base/task_queue_manager_unittest.cc index b797052..52fa223 100644 --- a/third_party/WebKit/Source/platform/scheduler/base/task_queue_manager_unittest.cc +++ b/third_party/WebKit/Source/platform/scheduler/base/task_queue_manager_unittest.cc
@@ -1545,9 +1545,9 @@ base::TimeTicks start_time = manager_->Delegate()->NowTicks(); std::unique_ptr<VirtualTimeDomain> domain_a( - new VirtualTimeDomain(nullptr, start_time)); + new VirtualTimeDomain(start_time)); std::unique_ptr<VirtualTimeDomain> domain_b( - new VirtualTimeDomain(nullptr, start_time)); + new VirtualTimeDomain(start_time)); manager_->RegisterTimeDomain(domain_a.get()); manager_->RegisterTimeDomain(domain_b.get()); runners_[0]->SetTimeDomain(domain_a.get()); @@ -1592,7 +1592,7 @@ base::TimeTicks start_time = manager_->Delegate()->NowTicks(); std::unique_ptr<VirtualTimeDomain> domain_a( - new VirtualTimeDomain(nullptr, start_time)); + new VirtualTimeDomain(start_time)); manager_->RegisterTimeDomain(domain_a.get()); runners_[0]->SetTimeDomain(domain_a.get()); @@ -1612,7 +1612,7 @@ EXPECT_THAT(run_order, ElementsAre(1, 2)); std::unique_ptr<VirtualTimeDomain> domain_b( - new VirtualTimeDomain(nullptr, start_time)); + new VirtualTimeDomain(start_time)); manager_->RegisterTimeDomain(domain_b.get()); runners_[0]->SetTimeDomain(domain_b.get()); @@ -1633,9 +1633,9 @@ base::TimeTicks start_time = manager_->Delegate()->NowTicks(); std::unique_ptr<VirtualTimeDomain> domain_a( - new VirtualTimeDomain(nullptr, start_time)); + new VirtualTimeDomain(start_time)); std::unique_ptr<VirtualTimeDomain> domain_b( - new VirtualTimeDomain(nullptr, start_time)); + new VirtualTimeDomain(start_time)); manager_->RegisterTimeDomain(domain_a.get()); manager_->RegisterTimeDomain(domain_b.get()); @@ -1690,68 +1690,64 @@ } namespace { -class MockTimeDomainObserver : public TimeDomain::Observer { - public: - ~MockTimeDomainObserver() override {} - MOCK_METHOD1(OnTimeDomainHasImmediateWork, void(TaskQueue*)); - MOCK_METHOD1(OnTimeDomainHasDelayedWork, void(TaskQueue*)); +class MockTaskQueueObserver : public TaskQueue::Observer { + public: + ~MockTaskQueueObserver() override {} + + MOCK_METHOD2(OnQueueNextWakeUpChanged, void(TaskQueue*, base::TimeTicks)); }; + } // namespace -TEST_F(TaskQueueManagerTest, TimeDomainObserver_ImmediateTask) { +TEST_F(TaskQueueManagerTest, TaskQueueObserver_ImmediateTask) { Initialize(1u); - MockTimeDomainObserver observer; - std::unique_ptr<VirtualTimeDomain> domain( - new VirtualTimeDomain(&observer, manager_->Delegate()->NowTicks())); - manager_->RegisterTimeDomain(domain.get()); - runners_[0]->SetTimeDomain(domain.get()); + MockTaskQueueObserver observer; + runners_[0]->SetObserver(&observer); // We should get a notification when a task is posted on an empty queue. - EXPECT_CALL(observer, OnTimeDomainHasImmediateWork(runners_[0].get())); + EXPECT_CALL(observer, + OnQueueNextWakeUpChanged(runners_[0].get(), base::TimeTicks())); runners_[0]->PostTask(FROM_HERE, base::Bind(&NopTask)); Mock::VerifyAndClearExpectations(&observer); // But not subsequently. - EXPECT_CALL(observer, OnTimeDomainHasImmediateWork(_)).Times(0); + EXPECT_CALL(observer, OnQueueNextWakeUpChanged(_, _)).Times(0); runners_[0]->PostTask(FROM_HERE, base::Bind(&NopTask)); Mock::VerifyAndClearExpectations(&observer); // Unless the immediate work queue is emptied. runners_[0]->ReloadImmediateWorkQueueIfEmpty(); - EXPECT_CALL(observer, OnTimeDomainHasImmediateWork(runners_[0].get())); + EXPECT_CALL(observer, + OnQueueNextWakeUpChanged(runners_[0].get(), base::TimeTicks())); runners_[0]->PostTask(FROM_HERE, base::Bind(&NopTask)); // Tidy up. runners_[0]->UnregisterTaskQueue(); - manager_->UnregisterTimeDomain(domain.get()); } -TEST_F(TaskQueueManagerTest, TimeDomainObserver_DelayedTask) { +TEST_F(TaskQueueManagerTest, TaskQueueObserver_DelayedTask) { Initialize(1u); - MockTimeDomainObserver observer; - std::unique_ptr<VirtualTimeDomain> domain( - new VirtualTimeDomain(&observer, manager_->Delegate()->NowTicks())); - manager_->RegisterTimeDomain(domain.get()); - runners_[0]->SetTimeDomain(domain.get()); + MockTaskQueueObserver observer; + runners_[0]->SetObserver(&observer); // We should get a notification when a delayed task is posted on an empty // queue. - EXPECT_CALL(observer, OnTimeDomainHasDelayedWork(runners_[0].get())); + EXPECT_CALL(observer, OnQueueNextWakeUpChanged(runners_[0].get(), _)); runners_[0]->PostDelayedTask(FROM_HERE, base::Bind(&NopTask), base::TimeDelta::FromSeconds(10)); Mock::VerifyAndClearExpectations(&observer); // We should not get a notification for a longer delay. - EXPECT_CALL(observer, OnTimeDomainHasDelayedWork(_)).Times(0); + EXPECT_CALL(observer, OnQueueNextWakeUpChanged(_, _)).Times(0); runners_[0]->PostDelayedTask(FROM_HERE, base::Bind(&NopTask), base::TimeDelta::FromSeconds(100)); Mock::VerifyAndClearExpectations(&observer); // We should get a notification for a shorter delay. - EXPECT_CALL(observer, OnTimeDomainHasDelayedWork(runners_[0].get())); + EXPECT_CALL(observer, OnQueueNextWakeUpChanged(runners_[0].get(), _)); runners_[0]->PostDelayedTask(FROM_HERE, base::Bind(&NopTask), base::TimeDelta::FromSeconds(1)); Mock::VerifyAndClearExpectations(&observer); @@ -1762,26 +1758,24 @@ // When a queue has been enabled, we may get a notification if the // TimeDomain's next scheduled wake-up has changed. - EXPECT_CALL(observer, OnTimeDomainHasDelayedWork(runners_[0].get())); + EXPECT_CALL(observer, OnQueueNextWakeUpChanged(runners_[0].get(), _)); voter->SetQueueEnabled(true); // Tidy up. runners_[0]->UnregisterTaskQueue(); - manager_->UnregisterTimeDomain(domain.get()); } -TEST_F(TaskQueueManagerTest, TimeDomainObserver_DelayedTaskMultipleQueues) { +TEST_F(TaskQueueManagerTest, TaskQueueObserver_DelayedTaskMultipleQueues) { Initialize(2u); - MockTimeDomainObserver observer; - std::unique_ptr<VirtualTimeDomain> domain( - new VirtualTimeDomain(&observer, manager_->Delegate()->NowTicks())); - manager_->RegisterTimeDomain(domain.get()); - runners_[0]->SetTimeDomain(domain.get()); - runners_[1]->SetTimeDomain(domain.get()); + MockTaskQueueObserver observer; + runners_[0]->SetObserver(&observer); + runners_[1]->SetObserver(&observer); - EXPECT_CALL(observer, OnTimeDomainHasDelayedWork(runners_[0].get())).Times(1); - EXPECT_CALL(observer, OnTimeDomainHasDelayedWork(runners_[1].get())).Times(1); + EXPECT_CALL(observer, OnQueueNextWakeUpChanged(runners_[0].get(), _)) + .Times(1); + EXPECT_CALL(observer, OnQueueNextWakeUpChanged(runners_[1].get(), _)) + .Times(1); runners_[0]->PostDelayedTask(FROM_HERE, base::Bind(&NopTask), base::TimeDelta::FromSeconds(1)); runners_[1]->PostDelayedTask(FROM_HERE, base::Bind(&NopTask), @@ -1794,30 +1788,29 @@ runners_[1]->CreateQueueEnabledVoter(); // Disabling a queue should not trigger a notification. - EXPECT_CALL(observer, OnTimeDomainHasDelayedWork(_)).Times(0); + EXPECT_CALL(observer, OnQueueNextWakeUpChanged(_, _)).Times(0); voter0->SetQueueEnabled(false); Mock::VerifyAndClearExpectations(&observer); // Re-enabling it should should also trigger a notification. - EXPECT_CALL(observer, OnTimeDomainHasDelayedWork(runners_[0].get())); + EXPECT_CALL(observer, OnQueueNextWakeUpChanged(runners_[0].get(), _)); voter0->SetQueueEnabled(true); Mock::VerifyAndClearExpectations(&observer); // Disabling a queue should not trigger a notification. - EXPECT_CALL(observer, OnTimeDomainHasDelayedWork(_)).Times(0); + EXPECT_CALL(observer, OnQueueNextWakeUpChanged(_, _)).Times(0); voter1->SetQueueEnabled(false); Mock::VerifyAndClearExpectations(&observer); // Re-enabling it should should trigger a notification. - EXPECT_CALL(observer, OnTimeDomainHasDelayedWork(runners_[1].get())); + EXPECT_CALL(observer, OnQueueNextWakeUpChanged(runners_[1].get(), _)); voter1->SetQueueEnabled(true); Mock::VerifyAndClearExpectations(&observer); // Tidy up. - EXPECT_CALL(observer, OnTimeDomainHasDelayedWork(_)).Times(AnyNumber()); + EXPECT_CALL(observer, OnQueueNextWakeUpChanged(_, _)).Times(AnyNumber()); runners_[0]->UnregisterTaskQueue(); runners_[1]->UnregisterTaskQueue(); - manager_->UnregisterTimeDomain(domain.get()); } namespace { @@ -2860,6 +2853,9 @@ TEST_F(TaskQueueManagerTest, SetTimeDomainForDisabledQueue) { Initialize(1u); + MockTaskQueueObserver observer; + runners_[0]->SetObserver(&observer); + runners_[0]->PostDelayedTask(FROM_HERE, base::Bind(&NopTask), base::TimeDelta::FromMilliseconds(1)); @@ -2867,12 +2863,11 @@ runners_[0]->CreateQueueEnabledVoter(); voter->SetQueueEnabled(false); - MockTimeDomainObserver observer; // We should not get a notification for a disabled queue. - EXPECT_CALL(observer, OnTimeDomainHasDelayedWork(_)).Times(0); + EXPECT_CALL(observer, OnQueueNextWakeUpChanged(_, _)).Times(0); std::unique_ptr<VirtualTimeDomain> domain( - new VirtualTimeDomain(&observer, manager_->Delegate()->NowTicks())); + new VirtualTimeDomain(manager_->Delegate()->NowTicks())); manager_->RegisterTimeDomain(domain.get()); runners_[0]->SetTimeDomain(domain.get());
diff --git a/third_party/WebKit/Source/platform/scheduler/base/task_queue_selector_unittest.cc b/third_party/WebKit/Source/platform/scheduler/base/task_queue_selector_unittest.cc index 9d5a353..08c5b0d 100644 --- a/third_party/WebKit/Source/platform/scheduler/base/task_queue_selector_unittest.cc +++ b/third_party/WebKit/Source/platform/scheduler/base/task_queue_selector_unittest.cc
@@ -120,7 +120,7 @@ protected: void SetUp() final { virtual_time_domain_ = base::WrapUnique<VirtualTimeDomain>( - new VirtualTimeDomain(nullptr, base::TimeTicks())); + new VirtualTimeDomain(base::TimeTicks())); for (size_t i = 0; i < kTaskQueueCount; i++) { scoped_refptr<TaskQueueImpl> task_queue = make_scoped_refptr(new TaskQueueImpl(
diff --git a/third_party/WebKit/Source/platform/scheduler/base/time_domain.cc b/third_party/WebKit/Source/platform/scheduler/base/time_domain.cc index d581f93..bdf885b 100644 --- a/third_party/WebKit/Source/platform/scheduler/base/time_domain.cc +++ b/third_party/WebKit/Source/platform/scheduler/base/time_domain.cc
@@ -13,7 +13,7 @@ namespace blink { namespace scheduler { -TimeDomain::TimeDomain(Observer* observer) : observer_(observer) {} +TimeDomain::TimeDomain() {} TimeDomain::~TimeDomain() { DCHECK(main_thread_checker_.CalledOnValidThread()); @@ -55,14 +55,6 @@ // If |queue| is the first wake-up then request the wake-up. if (delayed_wake_up_queue_.Min().queue == queue) RequestWakeUpAt(now, wake_up.time); - - if (observer_) - observer_->OnTimeDomainHasDelayedWork(queue); -} - -void TimeDomain::OnQueueHasImmediateWork(internal::TaskQueueImpl* queue) { - if (observer_) - observer_->OnTimeDomainHasImmediateWork(queue); } void TimeDomain::CancelDelayedWork(internal::TaskQueueImpl* queue) {
diff --git a/third_party/WebKit/Source/platform/scheduler/base/time_domain.h b/third_party/WebKit/Source/platform/scheduler/base/time_domain.h index 6179d01..82db58b 100644 --- a/third_party/WebKit/Source/platform/scheduler/base/time_domain.h +++ b/third_party/WebKit/Source/platform/scheduler/base/time_domain.h
@@ -36,22 +36,7 @@ // changes. class BLINK_PLATFORM_EXPORT TimeDomain { public: - class BLINK_PLATFORM_EXPORT Observer { - public: - virtual ~Observer() {} - - // Called when an empty TaskQueue registered with this TimeDomain has a task - // enqueued. - // |task_queue| - task queue which has immediate work scheduled. - virtual void OnTimeDomainHasImmediateWork(TaskQueue* task_queue) = 0; - - // Called when a TaskQueue registered with this TimeDomain has a delayed - // task enqueued. - // |task_queue| - task queue which has delayed work scheduled. - virtual void OnTimeDomainHasDelayedWork(TaskQueue* task_queue) = 0; - }; - - explicit TimeDomain(Observer* observer); + TimeDomain(); virtual ~TimeDomain(); // Returns a LazyNow that evaluate this TimeDomain's Now. Can be called from @@ -86,10 +71,6 @@ // the next task was posted to and it returns true. Returns false otherwise. bool NextScheduledTaskQueue(TaskQueue** out_task_queue) const; - // Notifies the time domain observer (if any) that |queue| has incoming - // immediate work. - void OnQueueHasImmediateWork(internal::TaskQueueImpl* queue); - // Schedules a call to TaskQueueImpl::WakeUpForDelayedWork when this // TimeDomain reaches |delayed_run_time|. This supersedes any previously // registered wake-up for |queue|. @@ -161,8 +142,6 @@ IntrusiveHeap<ScheduledDelayedWakeUp> delayed_wake_up_queue_; - Observer* const observer_; // NOT OWNED. - base::ThreadChecker main_thread_checker_; DISALLOW_COPY_AND_ASSIGN(TimeDomain);
diff --git a/third_party/WebKit/Source/platform/scheduler/base/time_domain_unittest.cc b/third_party/WebKit/Source/platform/scheduler/base/time_domain_unittest.cc index bc62249b..0e6fc28 100644 --- a/third_party/WebKit/Source/platform/scheduler/base/time_domain_unittest.cc +++ b/third_party/WebKit/Source/platform/scheduler/base/time_domain_unittest.cc
@@ -24,16 +24,14 @@ class MockTimeDomain : public TimeDomain { public: - explicit MockTimeDomain(TimeDomain::Observer* observer) - : TimeDomain(observer), - now_(base::TimeTicks() + base::TimeDelta::FromSeconds(1)) {} + MockTimeDomain() + : now_(base::TimeTicks() + base::TimeDelta::FromSeconds(1)) {} ~MockTimeDomain() override {} using TimeDomain::CancelDelayedWork; using TimeDomain::NextScheduledRunTime; using TimeDomain::NextScheduledTaskQueue; - using TimeDomain::OnQueueHasImmediateWork; using TimeDomain::ScheduleDelayedWork; using TimeDomain::UnregisterQueue; using TimeDomain::WakeUpReadyDelayedQueues; @@ -82,7 +80,7 @@ } virtual MockTimeDomain* CreateMockTimeDomain() { - return new MockTimeDomain(nullptr); + return new MockTimeDomain(); } std::unique_ptr<MockTimeDomain> time_domain_; @@ -124,7 +122,7 @@ Mock::VerifyAndClearExpectations(time_domain_.get()); - // Now scheduler a later wake-up, which should replace the previously + // Now schedule a later wake_up, which should replace the previously // requested one. EXPECT_CALL(*time_domain_.get(), RequestWakeUpAt(_, delayed_runtime2)); time_domain_->ScheduleDelayedWork(task_queue_.get(), {delayed_runtime2, 0}, @@ -330,38 +328,5 @@ task_queue2->UnregisterTaskQueue(); } -namespace { -class MockObserver : public TimeDomain::Observer { - public: - ~MockObserver() override {} - - MOCK_METHOD1(OnTimeDomainHasImmediateWork, void(TaskQueue*)); - MOCK_METHOD1(OnTimeDomainHasDelayedWork, void(TaskQueue*)); -}; -} // namespace - -class TimeDomainWithObserverTest : public TimeDomainTest { - public: - MockTimeDomain* CreateMockTimeDomain() override { - observer_.reset(new MockObserver()); - return new MockTimeDomain(observer_.get()); - } - - std::unique_ptr<MockObserver> observer_; -}; - -TEST_F(TimeDomainWithObserverTest, OnTimeDomainHasImmediateWork) { - EXPECT_CALL(*observer_, OnTimeDomainHasImmediateWork(task_queue_.get())); - time_domain_->OnQueueHasImmediateWork(task_queue_.get()); -} - -TEST_F(TimeDomainWithObserverTest, OnTimeDomainHasDelayedWork) { - EXPECT_CALL(*observer_, OnTimeDomainHasDelayedWork(task_queue_.get())); - EXPECT_CALL(*time_domain_.get(), RequestWakeUpAt(_, _)); - base::TimeTicks now = time_domain_->Now(); - time_domain_->ScheduleDelayedWork( - task_queue_.get(), {now + base::TimeDelta::FromMilliseconds(10), 0}, now); -} - } // namespace scheduler } // namespace blink
diff --git a/third_party/WebKit/Source/platform/scheduler/base/virtual_time_domain.cc b/third_party/WebKit/Source/platform/scheduler/base/virtual_time_domain.cc index 2da1c7c..6e3b285 100644 --- a/third_party/WebKit/Source/platform/scheduler/base/virtual_time_domain.cc +++ b/third_party/WebKit/Source/platform/scheduler/base/virtual_time_domain.cc
@@ -12,9 +12,8 @@ namespace blink { namespace scheduler { -VirtualTimeDomain::VirtualTimeDomain(TimeDomain::Observer* observer, - base::TimeTicks initial_time) - : TimeDomain(observer), now_(initial_time), task_queue_manager_(nullptr) {} +VirtualTimeDomain::VirtualTimeDomain(base::TimeTicks initial_time) + : now_(initial_time), task_queue_manager_(nullptr) {} VirtualTimeDomain::~VirtualTimeDomain() {}
diff --git a/third_party/WebKit/Source/platform/scheduler/base/virtual_time_domain.h b/third_party/WebKit/Source/platform/scheduler/base/virtual_time_domain.h index 67aaa4fb..050c0ba 100644 --- a/third_party/WebKit/Source/platform/scheduler/base/virtual_time_domain.h +++ b/third_party/WebKit/Source/platform/scheduler/base/virtual_time_domain.h
@@ -14,8 +14,7 @@ class BLINK_PLATFORM_EXPORT VirtualTimeDomain : public TimeDomain { public: - VirtualTimeDomain(TimeDomain::Observer* observer, - base::TimeTicks initial_time); + VirtualTimeDomain(base::TimeTicks initial_time); ~VirtualTimeDomain() override; // TimeDomain implementation:
diff --git a/third_party/WebKit/Source/platform/scheduler/child/compositor_worker_scheduler.cc b/third_party/WebKit/Source/platform/scheduler/child/compositor_worker_scheduler.cc index a86fafd6..7cf0752 100644 --- a/third_party/WebKit/Source/platform/scheduler/child/compositor_worker_scheduler.cc +++ b/third_party/WebKit/Source/platform/scheduler/child/compositor_worker_scheduler.cc
@@ -117,6 +117,8 @@ NOTREACHED(); } + void SetObserver(Observer* observer) override { NOTREACHED(); } + private: ~CompositorWorkerTaskRunnerWrapper() override {}
diff --git a/third_party/WebKit/Source/platform/scheduler/renderer/auto_advancing_virtual_time_domain.cc b/third_party/WebKit/Source/platform/scheduler/renderer/auto_advancing_virtual_time_domain.cc index 4da9eb5..fcd38cd 100644 --- a/third_party/WebKit/Source/platform/scheduler/renderer/auto_advancing_virtual_time_domain.cc +++ b/third_party/WebKit/Source/platform/scheduler/renderer/auto_advancing_virtual_time_domain.cc
@@ -9,8 +9,7 @@ AutoAdvancingVirtualTimeDomain::AutoAdvancingVirtualTimeDomain( base::TimeTicks initial_time) - : VirtualTimeDomain(nullptr, initial_time), - can_advance_virtual_time_(true) {} + : VirtualTimeDomain(initial_time), can_advance_virtual_time_(true) {} AutoAdvancingVirtualTimeDomain::~AutoAdvancingVirtualTimeDomain() {}
diff --git a/third_party/WebKit/Source/platform/scheduler/renderer/task_queue_throttler.cc b/third_party/WebKit/Source/platform/scheduler/renderer/task_queue_throttler.cc index 289893c..e9744e2 100644 --- a/third_party/WebKit/Source/platform/scheduler/renderer/task_queue_throttler.cc +++ b/third_party/WebKit/Source/platform/scheduler/renderer/task_queue_throttler.cc
@@ -79,13 +79,13 @@ renderer_scheduler_(renderer_scheduler), tick_clock_(renderer_scheduler->tick_clock()), tracing_category_(tracing_category), - time_domain_(new ThrottledTimeDomain(this, tracing_category)), + time_domain_(new ThrottledTimeDomain(tracing_category)), allow_throttling_(true), weak_factory_(this) { pump_throttled_tasks_closure_.Reset(base::Bind( &TaskQueueThrottler::PumpThrottledTasks, weak_factory_.GetWeakPtr())); forward_immediate_work_callback_ = - base::Bind(&TaskQueueThrottler::OnTimeDomainHasImmediateWork, + base::Bind(&TaskQueueThrottler::OnQueueNextWakeUpChanged, weak_factory_.GetWeakPtr()); renderer_scheduler_->RegisterTimeDomain(time_domain_.get()); @@ -100,6 +100,8 @@ task_queue->SetTimeDomain(renderer_scheduler_->real_time_domain()); task_queue->RemoveFence(); } + if (map_entry.second.throttling_ref_count != 0) + task_queue->SetObserver(nullptr); } renderer_scheduler_->UnregisterTimeDomain(time_domain_.get()); @@ -119,6 +121,8 @@ TRACE_EVENT1(tracing_category_, "TaskQueueThrottler_TaskQueueThrottled", "task_queue", task_queue); + task_queue->SetObserver(this); + if (!allow_throttling_) return; @@ -131,11 +135,9 @@ return; if (!task_queue->IsEmpty()) { - if (task_queue->HasPendingImmediateWork()) { - OnTimeDomainHasImmediateWork(task_queue); - } else { - OnTimeDomainHasDelayedWork(task_queue); - } + LazyNow lazy_now(tick_clock_); + OnQueueNextWakeUpChanged(task_queue, + NextTaskRunTime(&lazy_now, task_queue).value()); } } @@ -150,6 +152,8 @@ TRACE_EVENT1(tracing_category_, "TaskQueueThrottler_TaskQueueUnthrottled", "task_queue", task_queue); + task_queue->SetObserver(nullptr); + MaybeDeleteQueueMetadata(iter); if (!allow_throttling_) @@ -183,17 +187,22 @@ // Iterator may have been deleted by BudgetPool::RemoveQueue, so don't // use it here. queue_details_.erase(task_queue); + + // NOTE: Observer is automatically unregistered when unregistering task queue. } -void TaskQueueThrottler::OnTimeDomainHasImmediateWork(TaskQueue* queue) { - // Forward to the main thread if called from another thread +void TaskQueueThrottler::OnQueueNextWakeUpChanged( + TaskQueue* queue, + base::TimeTicks next_wake_up) { if (!task_runner_->RunsTasksOnCurrentThread()) { - task_runner_->PostTask(FROM_HERE, - base::Bind(forward_immediate_work_callback_, queue)); + task_runner_->PostTask( + FROM_HERE, + base::Bind(forward_immediate_work_callback_, queue, next_wake_up)); return; } + TRACE_EVENT0(tracing_category_, - "TaskQueueThrottler::OnTimeDomainHasImmediateWork"); + "TaskQueueThrottler::OnQueueNextWakeUpChanged"); // We don't expect this to get called for disabled queues, but we can't DCHECK // because of the above thread hop. Just bail out if the queue is disabled. @@ -201,22 +210,9 @@ return; base::TimeTicks now = tick_clock_->NowTicks(); - base::TimeTicks next_allowed_run_time = GetNextAllowedRunTime(now, queue); - MaybeSchedulePumpThrottledTasks(FROM_HERE, now, next_allowed_run_time); -} - -void TaskQueueThrottler::OnTimeDomainHasDelayedWork(TaskQueue* queue) { - TRACE_EVENT0(tracing_category_, - "TaskQueueThrottler::OnTimeDomainHasDelayedWork"); - DCHECK(queue->IsQueueEnabled()); - base::TimeTicks now = tick_clock_->NowTicks(); - LazyNow lazy_now(now); - - base::Optional<base::TimeTicks> next_scheduled_delayed_task = - NextTaskRunTime(&lazy_now, queue); - DCHECK(next_scheduled_delayed_task); - MaybeSchedulePumpThrottledTasks(FROM_HERE, now, - next_scheduled_delayed_task.value()); + MaybeSchedulePumpThrottledTasks( + FROM_HERE, now, + std::max(GetNextAllowedRunTime(now, queue), next_wake_up)); } void TaskQueueThrottler::PumpThrottledTasks() {
diff --git a/third_party/WebKit/Source/platform/scheduler/renderer/task_queue_throttler.h b/third_party/WebKit/Source/platform/scheduler/renderer/task_queue_throttler.h index 2c63547..9a8dd3f 100644 --- a/third_party/WebKit/Source/platform/scheduler/renderer/task_queue_throttler.h +++ b/third_party/WebKit/Source/platform/scheduler/renderer/task_queue_throttler.h
@@ -80,7 +80,7 @@ // See IncreaseThrottleRefCount & DecreaseThrottleRefCount. // // This class is main-thread only. -class BLINK_PLATFORM_EXPORT TaskQueueThrottler : public TimeDomain::Observer, +class BLINK_PLATFORM_EXPORT TaskQueueThrottler : public TaskQueue::Observer, public BudgetPoolController { public: // TODO(altimin): Do not pass tracing category as const char*, @@ -90,9 +90,9 @@ ~TaskQueueThrottler() override; - // TimeDomain::Observer implementation: - void OnTimeDomainHasImmediateWork(TaskQueue*) override; - void OnTimeDomainHasDelayedWork(TaskQueue*) override; + // TaskQueue::Observer implementation: + void OnQueueNextWakeUpChanged(TaskQueue* queue, + base::TimeTicks wake_up) override; // BudgetPoolController implementation: void AddQueueToBudgetPool(TaskQueue* queue, BudgetPool* budget_pool) override; @@ -172,7 +172,8 @@ TaskQueue* queue); TaskQueueMap queue_details_; - base::Callback<void(TaskQueue*)> forward_immediate_work_callback_; + base::Callback<void(TaskQueue*, base::TimeTicks)> + forward_immediate_work_callback_; scoped_refptr<TaskQueue> task_runner_; RendererSchedulerImpl* renderer_scheduler_; // NOT OWNED base::TickClock* tick_clock_; // NOT OWNED
diff --git a/third_party/WebKit/Source/platform/scheduler/renderer/task_queue_throttler_unittest.cc b/third_party/WebKit/Source/platform/scheduler/renderer/task_queue_throttler_unittest.cc index 3f75e5c..277ff6ab 100644 --- a/third_party/WebKit/Source/platform/scheduler/renderer/task_queue_throttler_unittest.cc +++ b/third_party/WebKit/Source/platform/scheduler/renderer/task_queue_throttler_unittest.cc
@@ -275,7 +275,8 @@ } TEST_F(TaskQueueThrottlerTest, OnTimeDomainHasImmediateWork_EnabledQueue) { - task_queue_throttler_->OnTimeDomainHasImmediateWork(timer_queue_.get()); + task_queue_throttler_->OnQueueNextWakeUpChanged(timer_queue_.get(), + base::TimeTicks()); // Check PostPumpThrottledTasksLocked was called. EXPECT_FALSE(task_queue_throttler_->task_runner()->IsEmpty()); } @@ -285,7 +286,8 @@ timer_queue_->CreateQueueEnabledVoter(); voter->SetQueueEnabled(false); - task_queue_throttler_->OnTimeDomainHasImmediateWork(timer_queue_.get()); + task_queue_throttler_->OnQueueNextWakeUpChanged(timer_queue_.get(), + base::TimeTicks()); // Check PostPumpThrottledTasksLocked was not called. EXPECT_TRUE(task_queue_throttler_->task_runner()->IsEmpty()); }
diff --git a/third_party/WebKit/Source/platform/scheduler/renderer/throttled_time_domain.cc b/third_party/WebKit/Source/platform/scheduler/renderer/throttled_time_domain.cc index e5179dd..9126c6f0 100644 --- a/third_party/WebKit/Source/platform/scheduler/renderer/throttled_time_domain.cc +++ b/third_party/WebKit/Source/platform/scheduler/renderer/throttled_time_domain.cc
@@ -7,9 +7,8 @@ namespace blink { namespace scheduler { -ThrottledTimeDomain::ThrottledTimeDomain(TimeDomain::Observer* observer, - const char* tracing_category) - : RealTimeDomain(observer, tracing_category) {} +ThrottledTimeDomain::ThrottledTimeDomain(const char* tracing_category) + : RealTimeDomain(tracing_category) {} ThrottledTimeDomain::~ThrottledTimeDomain() {}
diff --git a/third_party/WebKit/Source/platform/scheduler/renderer/throttled_time_domain.h b/third_party/WebKit/Source/platform/scheduler/renderer/throttled_time_domain.h index 74a654f0..53b4514 100644 --- a/third_party/WebKit/Source/platform/scheduler/renderer/throttled_time_domain.h +++ b/third_party/WebKit/Source/platform/scheduler/renderer/throttled_time_domain.h
@@ -15,8 +15,7 @@ // relies on the owner (TaskQueueThrottler) to schedule wake-ups. class BLINK_PLATFORM_EXPORT ThrottledTimeDomain : public RealTimeDomain { public: - ThrottledTimeDomain(TimeDomain::Observer* observer, - const char* tracing_category); + ThrottledTimeDomain(const char* tracing_category); ~ThrottledTimeDomain() override; // TimeDomain implementation:
diff --git a/third_party/WebKit/Source/web/DevToolsEmulator.cpp b/third_party/WebKit/Source/web/DevToolsEmulator.cpp index 57fbf87f..7f771b55 100644 --- a/third_party/WebKit/Source/web/DevToolsEmulator.cpp +++ b/third_party/WebKit/Source/web/DevToolsEmulator.cpp
@@ -317,7 +317,7 @@ // TODO(dgozman): mainFrameImpl() is null when it's remote. Figure out how // we end up with enabling emulation in this case. if (web_view_impl_->MainFrameImpl()) - web_view_impl_->MainFrameImpl()->GetFrameView()->Layout(); + web_view_impl_->MainFrameImpl()->GetFrameView()->UpdateLayout(); } void DevToolsEmulator::DisableMobileEmulation() { @@ -361,7 +361,7 @@ original_default_maximum_page_scale_factor_); // mainFrameImpl() could be null during cleanup or remote <-> local swap. if (web_view_impl_->MainFrameImpl()) - web_view_impl_->MainFrameImpl()->GetFrameView()->Layout(); + web_view_impl_->MainFrameImpl()->GetFrameView()->UpdateLayout(); } float DevToolsEmulator::CompositorDeviceScaleFactor() const { @@ -508,7 +508,7 @@ // We should instead route emulation from browser through the WebViewImpl // to the local main frame, and remove InspectorEmulationAgent entirely. if (web_view_impl_->MainFrameImpl()) - web_view_impl_->MainFrameImpl()->GetFrameView()->Layout(); + web_view_impl_->MainFrameImpl()->GetFrameView()->UpdateLayout(); } void DevToolsEmulator::SetScriptExecutionDisabled(
diff --git a/third_party/WebKit/Source/web/LocalFrameClientImpl.cpp b/third_party/WebKit/Source/web/LocalFrameClientImpl.cpp index 02f40a8..13c62d2c 100644 --- a/third_party/WebKit/Source/web/LocalFrameClientImpl.cpp +++ b/third_party/WebKit/Source/web/LocalFrameClientImpl.cpp
@@ -59,6 +59,7 @@ #include "modules/device_orientation/DeviceOrientationController.h" #include "modules/encryptedmedia/HTMLMediaElementEncryptedMedia.h" #include "modules/gamepad/NavigatorGamepad.h" +#include "modules/presentation/PresentationReceiver.h" #include "modules/remoteplayback/HTMLMediaElementRemotePlayback.h" #include "modules/remoteplayback/RemotePlayback.h" #include "modules/serviceworkers/NavigatorServiceWorker.h" @@ -159,6 +160,11 @@ if (RuntimeEnabledFeatures::webVREnabled() || OriginTrials::webVREnabled(document->GetExecutionContext())) NavigatorVR::From(*document); + if (RuntimeEnabledFeatures::presentationEnabled() && + web_frame_->GetFrame()->GetSettings()->GetPresentationReceiver()) { + // Call this in order to ensure the object is created. + PresentationReceiver::From(*document); + } } } // FIXME: when extensions go out of process, this whole concept stops working.
diff --git a/third_party/WebKit/Source/web/WebFrameWidgetImpl.cpp b/third_party/WebKit/Source/web/WebFrameWidgetImpl.cpp index c1fb2ee..3d12b17f 100644 --- a/third_party/WebKit/Source/web/WebFrameWidgetImpl.cpp +++ b/third_party/WebKit/Source/web/WebFrameWidgetImpl.cpp
@@ -176,7 +176,7 @@ // scale limit. It is not clear if this is necessary for frame-level widget // resize. if (view->NeedsLayout()) - view->Layout(); + view->UpdateLayout(); // FIXME: Investigate whether this is needed; comment from eseidel suggests // that this function is flawed.
diff --git a/third_party/WebKit/Source/web/WebViewImpl.cpp b/third_party/WebKit/Source/web/WebViewImpl.cpp index d584f4ca..befa8d0 100644 --- a/third_party/WebKit/Source/web/WebViewImpl.cpp +++ b/third_party/WebKit/Source/web/WebViewImpl.cpp
@@ -3752,7 +3752,7 @@ // Relayout immediately to avoid violating the rule that needsLayout() // isn't set at the end of a layout. if (view->NeedsLayout()) - view->Layout(); + view->UpdateLayout(); UpdatePageOverlays();
diff --git a/third_party/WebKit/Source/web/mac/WebSubstringUtil.mm b/third_party/WebKit/Source/web/mac/WebSubstringUtil.mm index 6fd64586..cafa249 100644 --- a/third_party/WebKit/Source/web/mac/WebSubstringUtil.mm +++ b/third_party/WebKit/Source/web/mac/WebSubstringUtil.mm
@@ -200,7 +200,7 @@ WebPoint* baseline_point) { LocalFrame* frame = ToWebLocalFrameImpl(web_frame)->GetFrame(); if (frame->View()->NeedsLayout()) - frame->View()->Layout(); + frame->View()->UpdateLayout(); Element* editable = frame->Selection().RootEditableElementOrDocumentElement(); if (!editable)
diff --git a/third_party/WebKit/Source/web/tests/WebFrameTest.cpp b/third_party/WebKit/Source/web/tests/WebFrameTest.cpp index 91bb12a..f89397ef 100644 --- a/third_party/WebKit/Source/web/tests/WebFrameTest.cpp +++ b/third_party/WebKit/Source/web/tests/WebFrameTest.cpp
@@ -11611,6 +11611,32 @@ EXPECT_FALSE(iframe_doc->documentElement()->GetLayoutObject()); } +TEST_F(WebFrameSimTest, ScrollOriginChangeUpdatesLayerPositions) { + WebView().Resize(WebSize(800, 600)); + SimRequest main_resource("https://example.com/test.html", "text/html"); + + LoadURL("https://example.com/test.html"); + main_resource.Complete( + "<!DOCTYPE html>" + "<body dir='rtl'>" + " <div style='width:1px; height:1px; position:absolute; left:-10000px'>" + " </div>" + "</body>"); + + Compositor().BeginFrame(); + ScrollableArea* area = GetDocument().View()->LayoutViewportScrollableArea(); + ASSERT_EQ(10000, area->ScrollOrigin().X()); + ASSERT_EQ(10000, area->LayerForScrolling()->GetPosition().X()); + + // Removing the overflowing element removes all overflow so the scroll origin + // implicitly is reset to (0, 0). + GetDocument().QuerySelector("div")->remove(); + Compositor().BeginFrame(); + + EXPECT_EQ(0, area->ScrollOrigin().X()); + EXPECT_EQ(0, area->LayerForScrolling()->GetPosition().X()); +} + TEST_F(WebFrameTest, NoLoadingCompletionCallbacksInDetach) { class LoadingObserverFrameClient : public FrameTestHelpers::TestWebFrameClient {
diff --git a/third_party/WebKit/Source/web/tests/WebViewTest.cpp b/third_party/WebKit/Source/web/tests/WebViewTest.cpp index c9ad3a7..745534b8b 100644 --- a/third_party/WebKit/Source/web/tests/WebViewTest.cpp +++ b/third_party/WebKit/Source/web/tests/WebViewTest.cpp
@@ -672,14 +672,14 @@ WebLocalFrameImpl* frame = web_view->MainFrameImpl(); FrameView* frame_view = frame->GetFrame()->View(); - frame_view->Layout(); + frame_view->UpdateLayout(); EXPECT_FALSE(frame_view->LayoutPending()); EXPECT_FALSE(frame_view->NeedsLayout()); web_view->EnableAutoResizeMode(min_auto_resize, max_auto_resize); EXPECT_TRUE(frame_view->LayoutPending()); EXPECT_TRUE(frame_view->NeedsLayout()); - frame_view->Layout(); + frame_view->UpdateLayout(); EXPECT_TRUE(frame->GetFrame()->GetDocument()->IsHTMLDocument());
diff --git a/third_party/WebKit/Tools/Scripts/webkitpy/layout_tests/controllers/manager.py b/third_party/WebKit/Tools/Scripts/webkitpy/layout_tests/controllers/manager.py index cba10f9..fecac2d 100644 --- a/third_party/WebKit/Tools/Scripts/webkitpy/layout_tests/controllers/manager.py +++ b/third_party/WebKit/Tools/Scripts/webkitpy/layout_tests/controllers/manager.py
@@ -368,7 +368,7 @@ tests_to_skip, num_workers, retry_attempt) def _start_servers(self, tests_to_run): - if any(self._port.is_wptserve_test(test) for test in tests_to_run): + if any(self._port.is_wpt_test(test) for test in tests_to_run): self._printer.write_update('Starting WPTServe ...') self._port.start_wptserve() self._wptserve_started = True
diff --git a/third_party/WebKit/Tools/Scripts/webkitpy/layout_tests/port/base.py b/third_party/WebKit/Tools/Scripts/webkitpy/layout_tests/port/base.py index 215d589..1a2c3057 100644 --- a/third_party/WebKit/Tools/Scripts/webkitpy/layout_tests/port/base.py +++ b/third_party/WebKit/Tools/Scripts/webkitpy/layout_tests/port/base.py
@@ -1140,12 +1140,12 @@ self._websocket_server = server @staticmethod - def is_wptserve_test(test): - """Whether wptserve should be used for a given test if enabled.""" + def is_wpt_test(test): + """Whether a test is considered a web-platform-tests test.""" return re.match(r'(virtual/[^/]+/)?external/wpt/', test) def should_use_wptserve(self, test): - return self.is_wptserve_test(test) + return self.is_wpt_test(test) def start_wptserve(self): """Starts a WPT web server.
diff --git a/third_party/WebKit/Tools/Scripts/webkitpy/layout_tests/port/base_unittest.py b/third_party/WebKit/Tools/Scripts/webkitpy/layout_tests/port/base_unittest.py index 84c95d7..3532200 100644 --- a/third_party/WebKit/Tools/Scripts/webkitpy/layout_tests/port/base_unittest.py +++ b/third_party/WebKit/Tools/Scripts/webkitpy/layout_tests/port/base_unittest.py
@@ -490,13 +490,13 @@ port = self.make_port() self.assertRaises(AssertionError, port.virtual_test_suites) - def test_is_wptserve_test(self): + def test_is_wpt_test(self): port = self.make_port() - self.assertTrue(port.is_wptserve_test('external/wpt/foo/bar.html')) - self.assertTrue(port.is_wptserve_test('virtual/a-name/external/wpt/baz/qux.htm')) - self.assertFalse(port.is_wptserve_test('http/wpt/foo.html')) - self.assertFalse(port.is_wptserve_test('virtual/external/wpt/baz/qux.htm')) - self.assertFalse(port.is_wptserve_test('not-virtual/a-name/external/wpt/baz/qux.htm')) + self.assertTrue(port.is_wpt_test('external/wpt/foo/bar.html')) + self.assertTrue(port.is_wpt_test('virtual/a-name/external/wpt/baz/qux.htm')) + self.assertFalse(port.is_wpt_test('http/wpt/foo.html')) + self.assertFalse(port.is_wpt_test('virtual/external/wpt/baz/qux.htm')) + self.assertFalse(port.is_wpt_test('not-virtual/a-name/external/wpt/baz/qux.htm')) def test_default_results_directory(self): port = self.make_port(options=optparse.Values({'target': 'Default', 'configuration': 'Release'}))
diff --git a/third_party/WebKit/Tools/Scripts/webkitpy/tool/commands/rebaseline.py b/third_party/WebKit/Tools/Scripts/webkitpy/tool/commands/rebaseline.py index 9482025..c5e8408 100644 --- a/third_party/WebKit/Tools/Scripts/webkitpy/tool/commands/rebaseline.py +++ b/third_party/WebKit/Tools/Scripts/webkitpy/tool/commands/rebaseline.py
@@ -175,6 +175,13 @@ '\n '.join('%s: %s, %s' % triple for triple in self._iter_combinations()) + '>') + def test_prefixes(self): + return sorted(self._test_prefix_map) + + def build_port_pairs(self, test_prefix): + # Return a copy in case the caller modifies the returned list. + return list(self._test_prefix_map[test_prefix]) + def add(self, test_prefix, build, port_name=None): """Adds an entry for baselines to download for some set of tests.
diff --git a/third_party/WebKit/Tools/Scripts/webkitpy/tool/commands/rebaseline_cl.py b/third_party/WebKit/Tools/Scripts/webkitpy/tool/commands/rebaseline_cl.py index 71349d2..eeef1f69 100644 --- a/third_party/WebKit/Tools/Scripts/webkitpy/tool/commands/rebaseline_cl.py +++ b/third_party/WebKit/Tools/Scripts/webkitpy/tool/commands/rebaseline_cl.py
@@ -36,6 +36,9 @@ optparse.make_option( '--no-trigger-jobs', dest='trigger_jobs', action='store_false', default=True, help='Do not trigger any try jobs.'), + optparse.make_option( + '--fill-missing', dest='fill_missing', action='store_true', default=False, + help='If some platforms have no try job results, use results from try job results of other platforms.'), self.no_optimize_option, self.results_directory_option, ]) @@ -73,7 +76,7 @@ _log.info('Please re-run webkit-patch rebaseline-cl once all pending try jobs have finished.') return 1 - if builders_with_no_results: + if builders_with_no_results and not options.fill_missing: # TODO(qyearsley): Support trying to continue as long as there are # some results from some builder; see http://crbug.com/673966. _log.error('The following builders have no results:') @@ -96,6 +99,9 @@ builds_to_results, only_changed_tests=options.only_changed_tests) + if options.fill_missing: + self.fill_in_missing_results(test_baseline_set) + _log.debug('Rebaselining: %s', test_baseline_set) if not options.dry_run: @@ -220,3 +226,37 @@ except (ValueError, KeyError): _log.warning('Unexpected retry summary content:\n%s', content) return None + + def fill_in_missing_results(self, test_baseline_set): + """Modifies test_baseline_set to guarantee that there are entries for + all ports for all tests to rebaseline. + + For each test prefix, if there is an entry missing for some port, + then an entry should be added for that port using a build that is + available. For example, if there's no entry for the port "win-win7", + then an entry might be added for "win-win7" using a build on + a Win10 builder which does have results. + """ + all_ports = {self._tool.builders.port_name_for_builder_name(b) for b in self._try_bots()} + for test_prefix in test_baseline_set.test_prefixes(): + build_port_pairs = test_baseline_set.build_port_pairs(test_prefix) + missing_ports = all_ports - {p for _, p in build_port_pairs} + if not missing_ports: + continue + _log.info('For %s:', test_prefix) + for port in missing_ports: + build = self._choose_fill_in_build(port, build_port_pairs) + _log.info('Using %s to supply results for %s.', build, port) + test_baseline_set.add(test_prefix, build, port) + return test_baseline_set + + def _choose_fill_in_build(self, _, build_port_pairs): + """Returns a Build to use to supply results for the given port. + + Ideally, this should return a build for a similar port so that the + results from the selected build may also be correct for the target port. + """ + # TODO(qyearsley): Decide what build to use for a given port + # in a more sophisticated way, such that a build with a + # "similar" port will be used when available. + return build_port_pairs[0][0]
diff --git a/third_party/WebKit/Tools/Scripts/webkitpy/tool/commands/rebaseline_cl_unittest.py b/third_party/WebKit/Tools/Scripts/webkitpy/tool/commands/rebaseline_cl_unittest.py index a018495..7a205dd6d 100644 --- a/third_party/WebKit/Tools/Scripts/webkitpy/tool/commands/rebaseline_cl_unittest.py +++ b/third_party/WebKit/Tools/Scripts/webkitpy/tool/commands/rebaseline_cl_unittest.py
@@ -149,6 +149,7 @@ 'results_directory': None, 'verbose': False, 'trigger_jobs': False, + 'fill_missing': False, } options.update(kwargs) return optparse.Values(dict(**options)) @@ -339,3 +340,20 @@ 'ERROR: Aborting: there are unstaged baselines:\n', 'ERROR: /mock-checkout/third_party/WebKit/LayoutTests/my-test-expected.txt\n', ]) + + def test_fill_in_missing_results(self): + test_baseline_set = TestBaselineSet(self.tool) + test_baseline_set.add('fast/dom/prototype-taco.html', Build('MOCK Try Linux', 100)) + test_baseline_set.add('fast/dom/prototype-taco.html', Build('MOCK Try Win', 200)) + self.command.fill_in_missing_results(test_baseline_set) + self.assertEqual( + test_baseline_set.build_port_pairs('fast/dom/prototype-taco.html'), + [ + (Build(builder_name='MOCK Try Linux', build_number=100), 'test-linux-trusty'), + (Build(builder_name='MOCK Try Win', build_number=200), 'test-win-win7'), + (Build(builder_name='MOCK Try Linux', build_number=100), 'test-mac-mac10.11'), + ]) + self.assertLog([ + 'INFO: For fast/dom/prototype-taco.html:\n', + 'INFO: Using Build(builder_name=\'MOCK Try Linux\', build_number=100) to supply results for test-mac-mac10.11.\n', + ])
diff --git a/third_party/WebKit/Tools/Scripts/webkitpy/tool/commands/rebaseline_unittest.py b/third_party/WebKit/Tools/Scripts/webkitpy/tool/commands/rebaseline_unittest.py index c43bcad2..f63b28e 100644 --- a/third_party/WebKit/Tools/Scripts/webkitpy/tool/commands/rebaseline_unittest.py +++ b/third_party/WebKit/Tools/Scripts/webkitpy/tool/commands/rebaseline_unittest.py
@@ -1187,3 +1187,15 @@ ('<TestBaselineSet with:\n' ' a/x.html: Build(builder_name=\'MOCK Mac10.12\', build_number=None), test-mac-mac10.12\n' ' a/x.html: Build(builder_name=\'MOCK Win10\', build_number=None), test-win-win10>')) + + def test_getters(self): + test_baseline_set = TestBaselineSet(host=self.host) + test_baseline_set.add('a/x.html', Build('MOCK Mac10.12')) + test_baseline_set.add('a/x.html', Build('MOCK Win10')) + self.assertEqual(test_baseline_set.test_prefixes(), ['a/x.html']) + self.assertEqual( + test_baseline_set.build_port_pairs('a/x.html'), + [ + (Build(builder_name='MOCK Mac10.12'), 'test-mac-mac10.12'), + (Build(builder_name='MOCK Win10'), 'test-win-win10') + ])
diff --git a/third_party/WebKit/Tools/Scripts/webkitpy/w3c/test_copier.py b/third_party/WebKit/Tools/Scripts/webkitpy/w3c/test_copier.py index 61621936..6b865bf5 100644 --- a/third_party/WebKit/Tools/Scripts/webkitpy/w3c/test_copier.py +++ b/third_party/WebKit/Tools/Scripts/webkitpy/w3c/test_copier.py
@@ -127,12 +127,6 @@ continue # FIXME: This block should really be a separate function, but the early-continues make that difficult. - # TODO(qyearsley): Remove the below block. - if filename != '.gitignore' and (filename.startswith('.') or filename.endswith('.pl')): - _log.debug('Skipping: %s', path_full) - _log.debug(' Reason: Hidden files and perl scripts are not necessary.') - continue - if filename == 'OWNERS' or filename == 'reftest.list': # See http://crbug.com/584660 and http://crbug.com/582838. _log.debug('Skipping: %s', path_full)
diff --git a/third_party/WebKit/Tools/Scripts/webkitpy/w3c/test_importer.py b/third_party/WebKit/Tools/Scripts/webkitpy/w3c/test_importer.py index bbcb285..86d09b4 100644 --- a/third_party/WebKit/Tools/Scripts/webkitpy/w3c/test_importer.py +++ b/third_party/WebKit/Tools/Scripts/webkitpy/w3c/test_importer.py
@@ -352,7 +352,9 @@ if try_results and self.git_cl.has_failing_try_results(try_results): self.fetch_new_expectations_and_baselines() - self._upload_patchset('Update test expectations and baselines.') + message = 'Update test expectations and baselines.' + self.check_run(['git', 'commit', '-a', '-m', message]) + self._upload_patchset(message) # Trigger CQ and wait for CQ try jobs to finish. self.git_cl.run(['set-commit', '--gerrit'])
diff --git a/third_party/WebKit/Tools/Scripts/webkitpy/w3c/wpt_expectations_updater.py b/third_party/WebKit/Tools/Scripts/webkitpy/w3c/wpt_expectations_updater.py index 6eaf99ef..86df73e 100644 --- a/third_party/WebKit/Tools/Scripts/webkitpy/w3c/wpt_expectations_updater.py +++ b/third_party/WebKit/Tools/Scripts/webkitpy/w3c/wpt_expectations_updater.py
@@ -28,6 +28,7 @@ def __init__(self, host): self.host = host + self.port = self.host.port_factory.get() self.finder = WebKitFinder(self.host.filesystem) self.port = self.host.port_factory.get() @@ -255,7 +256,7 @@ """ line_list = [] for test_name, port_results in sorted(merged_results.iteritems()): - if not test_name.startswith('external'): + if not self.port.is_wpt_test(test_name): continue for port_names, results in sorted(port_results.iteritems()): line_list.append(self._create_line(test_name, port_names, results))
diff --git a/third_party/WebKit/Tools/Scripts/webkitpy/w3c/wpt_expectations_updater_unittest.py b/third_party/WebKit/Tools/Scripts/webkitpy/w3c/wpt_expectations_updater_unittest.py index ba7b41d..9b09e6f 100644 --- a/third_party/WebKit/Tools/Scripts/webkitpy/w3c/wpt_expectations_updater_unittest.py +++ b/third_party/WebKit/Tools/Scripts/webkitpy/w3c/wpt_expectations_updater_unittest.py
@@ -198,24 +198,27 @@ self.assertEqual(updater.create_line_list(results), []) def test_create_line_list_new_tests(self): - # In this example, there are three unexpected results. The new - # test expectation lines are sorted by test, and then specifier. + # In this example, there are three unexpected results for wpt tests. + # The new test expectation lines are sorted by test, and then specifier. updater = WPTExpectationsUpdater(self.mock_host()) results = { 'external/wpt/test/zzzz.html': { 'test-mac-mac10.10': {'expected': 'PASS', 'actual': 'TEXT', 'bug': 'crbug.com/test'}, }, - 'external/wpt/test/path.html': { + 'virtual/foo/external/wpt/test/zzzz.html': { 'test-linux-trusty': {'expected': 'FAIL', 'actual': 'PASS', 'bug': 'crbug.com/test'}, 'test-mac-mac10.11': {'expected': 'FAIL', 'actual': 'TIMEOUT', 'bug': 'crbug.com/test'}, }, + 'unrelated/test.html': { + 'test-linux-trusty': {'expected': 'FAIL', 'actual': 'PASS', 'bug': 'crbug.com/test'}, + }, } self.assertEqual( updater.create_line_list(results), [ - 'crbug.com/test [ Trusty ] external/wpt/test/path.html [ Pass ]', - 'crbug.com/test [ Mac10.11 ] external/wpt/test/path.html [ Timeout ]', 'crbug.com/test [ Mac10.10 ] external/wpt/test/zzzz.html [ Failure ]', + 'crbug.com/test [ Trusty ] virtual/foo/external/wpt/test/zzzz.html [ Pass ]', + 'crbug.com/test [ Mac10.11 ] virtual/foo/external/wpt/test/zzzz.html [ Timeout ]', ]) def test_specifier_part(self):
diff --git a/third_party/WebKit/public/platform/modules/presentation/OWNERS b/third_party/WebKit/public/platform/modules/presentation/OWNERS index bc1b773..b372098 100644 --- a/third_party/WebKit/public/platform/modules/presentation/OWNERS +++ b/third_party/WebKit/public/platform/modules/presentation/OWNERS
@@ -1,9 +1,2 @@ -avayvod@chromium.org -imcheng@chromium.org -mfoltz@chromium.org -mlamouri@chromium.org +file://third_party/WebKit/Source/modules/presentation/OWNERS -per-file *.mojom=set noparent -per-file *.mojom=file://ipc/SECURITY_OWNERS - -# COMPONENT: Blink>PresentationAPI
diff --git a/third_party/WebKit/public/platform/modules/screen_orientation/OWNERS b/third_party/WebKit/public/platform/modules/screen_orientation/OWNERS index d5f56643..ecfee58 100644 --- a/third_party/WebKit/public/platform/modules/screen_orientation/OWNERS +++ b/third_party/WebKit/public/platform/modules/screen_orientation/OWNERS
@@ -1,4 +1 @@ -per-file *.mojom=set noparent -per-file *.mojom=file://ipc/SECURITY_OWNERS - -mlamouri@chromium.org +file://third_party/WebKit/Source/modules/screen_orientation/OWNERS
diff --git a/third_party/WebKit/public/platform/scheduler/base/task_queue.h b/third_party/WebKit/public/platform/scheduler/base/task_queue.h index da4102e4..de227cc 100644 --- a/third_party/WebKit/public/platform/scheduler/base/task_queue.h +++ b/third_party/WebKit/public/platform/scheduler/base/task_queue.h
@@ -27,6 +27,20 @@ public: TaskQueue() {} + class BLINK_PLATFORM_EXPORT Observer { + public: + virtual ~Observer() {} + + // Notify observer that the time at which this queue wants to run + // the next task has changed. |next_wakeup| can be in the past + // (e.g. base::TimeTicks() can be used to notify about immediate work). + // Can be called on any thread + // All methods but SetObserver, SetTimeDomain and GetTimeDomain can be + // called on |queue|. + virtual void OnQueueNextWakeUpChanged(TaskQueue* queue, + base::TimeTicks next_wake_up) = 0; + }; + // Unregisters the task queue after which no tasks posted to it will run and // the TaskQueueManager's reference to it will be released soon. virtual void UnregisterTaskQueue() = 0; @@ -208,6 +222,8 @@ virtual bool BlockedByFence() const = 0; + virtual void SetObserver(Observer* observer) = 0; + protected: ~TaskQueue() override {}
diff --git a/third_party/closure_compiler/externs/system_display.js b/third_party/closure_compiler/externs/system_display.js index a37c094..f59d976 100644 --- a/third_party/closure_compiler/externs/system_display.js +++ b/third_party/closure_compiler/externs/system_display.js
@@ -117,6 +117,7 @@ * isPrimary: boolean, * isInternal: boolean, * isEnabled: boolean, + * isUnified: boolean, * dpiX: number, * dpiY: number, * rotation: number, @@ -132,6 +133,7 @@ /** * @typedef {{ + * isUnified: (boolean|undefined), * mirroringSourceId: (string|undefined), * isPrimary: (boolean|undefined), * overscan: (!chrome.system.display.Insets|undefined), @@ -145,17 +147,28 @@ chrome.system.display.DisplayProperties; /** - * Get the information of all attached display devices. - * @param {function(!Array<!chrome.system.display.DisplayUnitInfo>):void} - * callback - * @see https://developer.chrome.com/extensions/system.display#method-getInfo + * @typedef {{ + * singleUnified: (boolean|undefined) + * }} + * @see https://developer.chrome.com/extensions/system.display#type-GetInfoFlags */ -chrome.system.display.getInfo = function(callback) {}; +chrome.system.display.GetInfoFlags; /** - * Get the layout info for all displays. NOTE: This is only available to Chrome - * OS Kiosk apps and Web UI. + * Requests the information for all attached display devices. + * @param {!chrome.system.display.GetInfoFlags} flags Options affecting how the + * information is returned. + * @param {function(!Array<!chrome.system.display.DisplayUnitInfo>):void} + * callback The callback to invoke with the results. + * @see https://developer.chrome.com/extensions/system.display#method-getInfo + */ +chrome.system.display.getInfo = function(flags, callback) {}; + +/** + * Requests the layout info for all displays. NOTE: This is only available to + * Chrome OS Kiosk apps and Web UI. * @param {function(!Array<!chrome.system.display.DisplayLayout>):void} callback + * The callback to invoke with the results. * @see https://developer.chrome.com/extensions/system.display#method-getDisplayLayout */ chrome.system.display.getDisplayLayout = function(callback) {}; @@ -238,13 +251,17 @@ chrome.system.display.overscanCalibrationComplete = function(id) {}; /** - * Starts native touch calibration for a display. This will show an overlay on - * the screen and initialize the UX for touch calibration. If another native - * touch calibration is already in progress this will throw an error. + * Displays the native touch calibration UX for the display with |id| as display + * id. This will show an overlay on the screen with required instructions on how + * to proceed. The callback will be invoked in case of successful calibraion + * only. If the calibration fails, this will throw an error. * @param {string} id The display's unique identifier. + * @param {function(boolean):void=} callback Optional callback to inform the + * caller that the touch calibration has ended. The argument of the + * callback informs if the calibration was a success or not. * @see https://developer.chrome.com/extensions/system.display#method-showNativeTouchCalibration */ -chrome.system.display.showNativeTouchCalibration = function(id) {}; +chrome.system.display.showNativeTouchCalibration = function(id, callback) {}; /** * Starts custom touch calibration for a display. This should be called when @@ -264,15 +281,16 @@ * @param {!chrome.system.display.TouchCalibrationPairQuad} pairs The pairs of * point used to calibrate the display. * @param {!chrome.system.display.Bounds} bounds Bounds of the display when the - * touch calibration was performed. |bounds.left| and |bounds.top| + * touch calibration was performed. |bounds.left| and |bounds.top| * values are ignored. * @see https://developer.chrome.com/extensions/system.display#method-completeCustomTouchCalibration */ chrome.system.display.completeCustomTouchCalibration = function(pairs, bounds) {}; /** - * Resets the touch calibration for the display and removes the saved - * calibration data. + * Resets the touch calibration for the display and brings it back to its + * default state by clearing any touch calibration data associated with the + * display. * @param {string} id The display's unique identifier. * @see https://developer.chrome.com/extensions/system.display#method-clearTouchCalibration */
diff --git a/third_party/closure_compiler/interfaces/system_display_interface.js b/third_party/closure_compiler/interfaces/system_display_interface.js index 845422642..f96cfd27 100644 --- a/third_party/closure_compiler/interfaces/system_display_interface.js +++ b/third_party/closure_compiler/interfaces/system_display_interface.js
@@ -1,4 +1,4 @@ -// Copyright 2016 The Chromium Authors. All rights reserved. +// 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. @@ -16,14 +16,25 @@ SystemDisplay.prototype = { /** - * Get the information of all attached display devices. + * Requests the information for all attached display devices. + * @param {!chrome.system.display.GetInfoFlags} flags Options affecting how + * the information is returned. * @param {function(!Array<!chrome.system.display.DisplayUnitInfo>):void} - * callback + * callback The callback to invoke with the results. * @see https://developer.chrome.com/extensions/system.display#method-getInfo */ getInfo: assertNotReached, /** + * Requests the layout info for all displays. NOTE: This is only available to + * Chrome OS Kiosk apps and Web UI. + * @param {function(!Array<!chrome.system.display.DisplayLayout>):void} + * callback The callback to invoke with the results. + * @see https://developer.chrome.com/extensions/system.display#method-getDisplayLayout + */ + getDisplayLayout: assertNotReached, + + /** * Updates the properties for the display specified by |id|, according to the * information provided in |info|. On failure, $(ref:runtime.lastError) will * be set. NOTE: This is only available to Chrome OS Kiosk apps and Web UI. @@ -42,8 +53,13 @@ * Set the layout for all displays. Any display not included will use the * default layout. If a layout would overlap or be otherwise invalid it will * be adjusted to a valid layout. After layout is resolved, an - * onDisplayChanged event will be triggered. - * @param {!Array<!chrome.system.display.DisplayLayout>} layouts + * onDisplayChanged event will be triggered. NOTE: This is only available to + * Chrome OS Kiosk apps and Web UI. + * @param {!Array<!chrome.system.display.DisplayLayout>} layouts The layout + * information, required for all displays except the primary display. + * @param {function():void=} callback Empty function called when the function + * finishes. To find out whether the function succeeded, + * $(ref:runtime.lastError) should be queried. * @see https://developer.chrome.com/extensions/system.display#method-setDisplayLayout */ setDisplayLayout: assertNotReached, @@ -96,10 +112,15 @@ overscanCalibrationComplete: assertNotReached, /** - * Starts native touch calibration for a display. This will show an overlay on - * the screen and initialize the UX for touch calibration. If another native - * touch calibration is already in progress this will throw an error. + * Displays the native touch calibration UX for the display with |id| as + * display id. This will show an overlay on the screen with required + * instructions on how to proceed. The callback will be invoked in case of + * successful calibraion only. If the calibration fails, this will throw an + * error. * @param {string} id The display's unique identifier. + * @param {function(boolean):void=} callback Optional callback to inform the + * caller that the touch calibration has ended. The argument of the + * callback informs if the calibration was a success or not. * @see https://developer.chrome.com/extensions/system.display#method-showNativeTouchCalibration */ showNativeTouchCalibration: assertNotReached, @@ -129,8 +150,9 @@ completeCustomTouchCalibration: assertNotReached, /** - * Resets the touch calibration for the display and removes the saved - * calibration data. + * Resets the touch calibration for the display and brings it back to its + * default state by clearing any touch calibration data associated with the + * display. * @param {string} id The display's unique identifier. * @see https://developer.chrome.com/extensions/system.display#method-clearTouchCalibration */
diff --git a/third_party/espresso/BUILD.gn b/third_party/espresso/BUILD.gn index 7387e593..105ef88 100644 --- a/third_party/espresso/BUILD.gn +++ b/third_party/espresso/BUILD.gn
@@ -17,7 +17,7 @@ android_java_prebuilt("espresso_contrib_java") { testonly = true - jar_path = "lib/espresso-contrib-2.2-release-no-dep.jar" + jar_path = "lib/espresso-contrib-2.2.1-release-no-dep.jar" deps = [ ":espresso_core_java", "//third_party/guava:guava_java", @@ -27,7 +27,7 @@ android_java_prebuilt("espresso_core_java") { testonly = true - jar_path = "lib/espresso-core-2.2-release-no-dep.jar" + jar_path = "lib/espresso-core-2.2.1-release-no-dep.jar" deps = [ "//third_party/android_tools:android_support_annotations_java", "//third_party/guava:guava_java", @@ -38,12 +38,12 @@ android_java_prebuilt("espresso_idling_java") { testonly = true - jar_path = "lib/espresso-idling-resource-2.2-release-no-dep.jar" + jar_path = "lib/espresso-idling-resource-2.2.1-release-no-dep.jar" } android_java_prebuilt("espresso_intents_java") { testonly = true - jar_path = "lib/espresso-intents-2.2-release-no-dep.jar" + jar_path = "lib/espresso-intents-2.2.1-release-no-dep.jar" deps = [ "//third_party/android_support_test_runner:runner_java", "//third_party/guava:guava_java", @@ -53,7 +53,7 @@ android_java_prebuilt("espresso_web_java") { testonly = true - jar_path = "lib/espresso-web-2.2-release-no-dep.jar" + jar_path = "lib/espresso-web-2.2.1-release-no-dep.jar" deps = [ ":espresso_core_java", "//third_party/guava:guava_java",
diff --git a/third_party/espresso/README.chromium b/third_party/espresso/README.chromium index 98accad..0bf0132 100644 --- a/third_party/espresso/README.chromium +++ b/third_party/espresso/README.chromium
@@ -12,4 +12,9 @@ IMPORTANT: There should only be one version of espresso library (crbug.com/622057) -Local Modifications: None +Local Modifications: +- Version 2.2.1: + - Change Futures.transform(preparedScript, RAW_EVALUATOR) calls to use Futures.transformAsync + in android/support/test/espresso/web/action/JavascriptEvaluation.java for Guava 20.0 + compatibility + - Change all Guava dependencies in Espresso build.gradle files from 18.0 to 20.0
diff --git a/third_party/espresso/lib/espresso-contrib-2.2-release-no-dep.jar.sha1 b/third_party/espresso/lib/espresso-contrib-2.2-release-no-dep.jar.sha1 deleted file mode 100644 index 9bafe15..0000000 --- a/third_party/espresso/lib/espresso-contrib-2.2-release-no-dep.jar.sha1 +++ /dev/null
@@ -1 +0,0 @@ -6a6d035553e64ef79f7e960faeaefb64b2020461 \ No newline at end of file
diff --git a/third_party/espresso/lib/espresso-contrib-2.2.1-release-no-dep.jar.sha1 b/third_party/espresso/lib/espresso-contrib-2.2.1-release-no-dep.jar.sha1 new file mode 100644 index 0000000..1f523df --- /dev/null +++ b/third_party/espresso/lib/espresso-contrib-2.2.1-release-no-dep.jar.sha1
@@ -0,0 +1 @@ +72cf04ecaab0bb92a6a18b0264e0684aa3d1881b \ No newline at end of file
diff --git a/third_party/espresso/lib/espresso-core-2.2-release-no-dep.jar.sha1 b/third_party/espresso/lib/espresso-core-2.2-release-no-dep.jar.sha1 deleted file mode 100644 index dcaec9e0..0000000 --- a/third_party/espresso/lib/espresso-core-2.2-release-no-dep.jar.sha1 +++ /dev/null
@@ -1 +0,0 @@ -ad9632f6066aba08fa7906e8ba5997aa9b5d3e50 \ No newline at end of file
diff --git a/third_party/espresso/lib/espresso-core-2.2.1-release-no-dep.jar.sha1 b/third_party/espresso/lib/espresso-core-2.2.1-release-no-dep.jar.sha1 new file mode 100644 index 0000000..201772ba --- /dev/null +++ b/third_party/espresso/lib/espresso-core-2.2.1-release-no-dep.jar.sha1
@@ -0,0 +1 @@ +06ea68f7818866197247aebb1aa87db2101678ed \ No newline at end of file
diff --git a/third_party/espresso/lib/espresso-idling-resource-2.2-release-no-dep.jar.sha1 b/third_party/espresso/lib/espresso-idling-resource-2.2-release-no-dep.jar.sha1 deleted file mode 100644 index 2bc9dbf..0000000 --- a/third_party/espresso/lib/espresso-idling-resource-2.2-release-no-dep.jar.sha1 +++ /dev/null
@@ -1 +0,0 @@ -1e97deb6027e673ab85fb4953c72676a7a2eb958 \ No newline at end of file
diff --git a/third_party/espresso/lib/espresso-idling-resource-2.2.1-release-no-dep.jar.sha1 b/third_party/espresso/lib/espresso-idling-resource-2.2.1-release-no-dep.jar.sha1 new file mode 100644 index 0000000..c78578d --- /dev/null +++ b/third_party/espresso/lib/espresso-idling-resource-2.2.1-release-no-dep.jar.sha1
@@ -0,0 +1 @@ +600daa034b62e193487208e28bde17cd3de06525 \ No newline at end of file
diff --git a/third_party/espresso/lib/espresso-intents-2.2-release-no-dep.jar.sha1 b/third_party/espresso/lib/espresso-intents-2.2-release-no-dep.jar.sha1 deleted file mode 100644 index bc8df45..0000000 --- a/third_party/espresso/lib/espresso-intents-2.2-release-no-dep.jar.sha1 +++ /dev/null
@@ -1 +0,0 @@ -d022911fd525712d9f2c17a91ac325b245a30557 \ No newline at end of file
diff --git a/third_party/espresso/lib/espresso-intents-2.2.1-release-no-dep.jar.sha1 b/third_party/espresso/lib/espresso-intents-2.2.1-release-no-dep.jar.sha1 new file mode 100644 index 0000000..1cff499 --- /dev/null +++ b/third_party/espresso/lib/espresso-intents-2.2.1-release-no-dep.jar.sha1
@@ -0,0 +1 @@ +24a6808324bba17ae852fe68dea927b0219da19e \ No newline at end of file
diff --git a/third_party/espresso/lib/espresso-web-2.2-release-no-dep.jar.sha1 b/third_party/espresso/lib/espresso-web-2.2-release-no-dep.jar.sha1 deleted file mode 100644 index 18324b89..0000000 --- a/third_party/espresso/lib/espresso-web-2.2-release-no-dep.jar.sha1 +++ /dev/null
@@ -1 +0,0 @@ -83ac4b2b331ece89add05dfac0c362f9a0d768f8 \ No newline at end of file
diff --git a/third_party/espresso/lib/espresso-web-2.2.1-release-no-dep.jar.sha1 b/third_party/espresso/lib/espresso-web-2.2.1-release-no-dep.jar.sha1 new file mode 100644 index 0000000..2b9fddc7 --- /dev/null +++ b/third_party/espresso/lib/espresso-web-2.2.1-release-no-dep.jar.sha1
@@ -0,0 +1 @@ +b4c1ae773ef917a9421a3d616dbd632478aa63b8 \ No newline at end of file
diff --git a/third_party/sfntly/BUILD.gn b/third_party/sfntly/BUILD.gn index c929b658..8f312543 100644 --- a/third_party/sfntly/BUILD.gn +++ b/third_party/sfntly/BUILD.gn
@@ -281,5 +281,63 @@ include_dirs = [ "src/cpp/src/sample" ] } - # TODO(thestig): Get sfntly_unittests to build. + executable("sfntly_unittest") { + sources = [ + "src/cpp/src/test/autogenerated/cmap_basic_test.cc", + "src/cpp/src/test/autogenerated/cmap_test_data.h", + "src/cpp/src/test/bitmap_table_test.cc", + "src/cpp/src/test/byte_array_test.cc", + "src/cpp/src/test/chrome_subsetter.cc", + "src/cpp/src/test/cmap_editing_test.cc", + "src/cpp/src/test/cmap_iterator_test.cc", + "src/cpp/src/test/cmap_test.cc", + "src/cpp/src/test/endian_test.cc", + "src/cpp/src/test/file_io_test.cc", + "src/cpp/src/test/font_data_test.cc", + "src/cpp/src/test/font_parsing_test.cc", + "src/cpp/src/test/hdmx_test.cc", + "src/cpp/src/test/lock_test.cc", + "src/cpp/src/test/memory_io_test.cc", + "src/cpp/src/test/name_editing_test.cc", + "src/cpp/src/test/open_type_data_test.cc", + "src/cpp/src/test/otf_basic_editing_test.cc", + "src/cpp/src/test/platform_thread.cc", + "src/cpp/src/test/platform_thread.h", + "src/cpp/src/test/serialization_test.cc", + "src/cpp/src/test/serialization_test.h", + "src/cpp/src/test/smart_pointer_test.cc", + "src/cpp/src/test/test_data.cc", + "src/cpp/src/test/test_data.h", + "src/cpp/src/test/test_font_utils.cc", + "src/cpp/src/test/test_font_utils.h", + "src/cpp/src/test/test_utils.cc", + "src/cpp/src/test/test_utils.h", + "src/cpp/src/test/test_utils_test.cc", + "src/cpp/src/test/test_xml_utils.cc", + "src/cpp/src/test/test_xml_utils.h", + "src/cpp/src/test/tinyxml/tinystr.cpp", + "src/cpp/src/test/tinyxml/tinystr.h", + "src/cpp/src/test/tinyxml/tinyxml.cpp", + "src/cpp/src/test/tinyxml/tinyxml.h", + "src/cpp/src/test/tinyxml/tinyxmlerror.cpp", + "src/cpp/src/test/tinyxml/tinyxmlparser.cpp", + "src/cpp/src/test/verify_glyf.cc", + "src/cpp/src/test/verify_hhea.cc", + "src/cpp/src/test/verify_hmtx.cc", + "src/cpp/src/test/verify_loca.cc", + "src/cpp/src/test/verify_maxp.cc", + "src/cpp/src/test/verify_name.cc", + "src/cpp/src/test/verify_os2.cc", + ] + + configs += [ ":sfntly_common_config" ] + deps = [ + ":sfntly", + "//testing/gtest", + "//testing/gtest:gtest_main", + "//third_party/icu:icuuc", + ] + defines = [ "TIXML_USE_STL" ] + testonly = true + } }
diff --git a/third_party/sfntly/README.chromium b/third_party/sfntly/README.chromium index c55a947e..6f02baa 100644 --- a/third_party/sfntly/README.chromium +++ b/third_party/sfntly/README.chromium
@@ -1,6 +1,6 @@ Name: sfntly URL: https://github.com/googlei18n/sfntly -Version: b18b09b6114b9b7fe6fc2f96d8b15e8a72f66916 +Version: 04740d2600193b14aa3ef24cd9fbb3d5996b9f77 Security Critical: yes License: Apache 2.0 License File: COPYING.txt
diff --git a/third_party/zlib/OWNERS b/third_party/zlib/OWNERS index 56ee016b..90ca6c07 100644 --- a/third_party/zlib/OWNERS +++ b/third_party/zlib/OWNERS
@@ -1,4 +1,5 @@ agl@chromium.org +cblume@chromium.org gavinp@chromium.org msarett@chromium.org
diff --git a/tools/binary_size/OWNERS b/tools/binary_size/OWNERS index 5ffdf6a..22475b2b 100644 --- a/tools/binary_size/OWNERS +++ b/tools/binary_size/OWNERS
@@ -1,5 +1,4 @@ agrieve@chromium.org -bratell@opera.com -primiano@chromium.org +estevenson@chromium.org # COMPONENT: Tools
diff --git a/tools/binary_size/PRESUBMIT.py b/tools/binary_size/PRESUBMIT.py index 5177786..69eafbe 100644 --- a/tools/binary_size/PRESUBMIT.py +++ b/tools/binary_size/PRESUBMIT.py
@@ -11,11 +11,11 @@ def CommonChecks(input_api, output_api): output = [] output.extend(input_api.canned_checks.RunPylint(input_api, output_api)) - output.extend( - input_api.canned_checks.RunUnitTestsInDirectory( - input_api, output_api, - input_api.PresubmitLocalPath(), - whitelist=[r'.+_test\.py$'])) + py_tests = input_api.canned_checks.GetUnitTestsRecursively( + input_api, output_api, input_api.PresubmitLocalPath(), + whitelist=[r'.+_test\.py$'], blacklist=[]) + + output.extend(input_api.RunTests(py_tests, False)) if input_api.is_committing: output.extend(input_api.canned_checks.PanProjectChecks(input_api,
diff --git a/tools/binary_size/README.md b/tools/binary_size/README.md index 54ddf40..4bc66ea 100644 --- a/tools/binary_size/README.md +++ b/tools/binary_size/README.md
@@ -1,44 +1,52 @@ -# map2size.py +# Tools for analyzing Chrome's binary size -Parses a linker .map file and outputs the result as a .size file. +# Super Size -## Example Usage: +Collect, archive, and analyze Chrome's binary size. + +## "archive" + +Collect size information and dump it into a `.size` file. Mainly consists of +symbol information parsed from a linker .map file. + +### Example Usage: # Android: gn gen out/Release --args='target_os="android" is_official_build=true' ninja -C out/Release -j 1000 libchrome.so - tools/binary_size/map2size.py out/Release/lib.unstripped/libchrome.so chrome.size -v + tools/binary_size/supersize archive chrome.size --elf-file out/Release/lib.unstripped/libchrome.so -v # Linux: gn gen out/Release --args='is_official_build=true' ninja -C out/Release -j 1000 chrome - tools/binary_size/map2size.py out/Release/chrome chrome.size -v + tools/binary_size/supersize archive chrome.size --elf-file out/Release/chrome -v -# create_html_breakdown.py +## "html_report" -Creates an interactive size breakdown as a stand-alone html report. +Creates an interactive size breakdown (by source path) as a stand-alone html +report. ## Example Usage: - tools/binary_size/create_html_breakdown.py chrome.size --report-dir size-report -v + tools/binary_size/supersize html_report chrome.size --report-dir size-report -v xdg-open size-report/index.html -# console.py +## "console" Starts a Python interpreter where you can run custom queries. ## Example Usage: # Runs a single diff and exits (does not enter interactive mode). - tools/binary_size/console.py without_patch.size with_patch.size --query='Diff(size_info2, size_info1)' + tools/binary_size/supersize console without_patch.size with_patch.size --query='Diff(size_info2, size_info1)' # Enters a Python REPL (it will print more guidance). - tools/binary_size/console.py chrome.size + tools/binary_size/supersize console chrome.size -# diagnose_apk_bloat.py +## diagnose_apk_bloat.py Determine the cause of binary size bloat for a patch. -## Example Usage: +### Example Usage: # Sync, build, and store MonochromePublic.apk for HEAD and HEAD^. tools/binary_size/diagnose_apk_bloat.py -v @@ -46,28 +54,39 @@ # Display detailed usage info (there are many options). tools/binary_size/diagnose_apk_bloat.py -h -# Roadmap: +# Roadmap for Super Size: - Tracked in https://crbug.com/681694 +Tracked in https://crbug.com/681694 - 1. More console.py features: - * Template Symbols - shows when templates lead to code bloat. - * Duplicate Symbols - shows when statics in headers are an issue. - * Overloaded Symbols - shows when overloads are excessive. - * Per-class / namespace size (no way to distinguish class vs namespace). - * Per-Chrome package (Chrome-specific grouping. e.g. name prefixes). - * CSV output (for pasting into a spreadsheet). - 1. More create_html_breakdown.py features: - * Break down by other groupings (e.g. create from nested `SymbolGroups`) - 1. More `map2size.py` features: - * Find out more about 0xffffffffffffffff addresses, and why such large - gaps exist after them. - * Use nm to get the full list of symbols that share the same address. - 1. More diagnose_apk_bloat.py features: - * Add diffing functionality to see diff stats for two commits. - * Add --cloud option for using artifacts from perf builders. - 1. Integrate with `resource_sizes.py` so that it tracks size of major - components separately: chrome vs blink vs skia vs v8. - 1. Speed up some steps (like normalizing names) via multiprocessing. - 1. Use resource whitelist information to attribute .pak file size to .o files. - 1. Add dependency graph info, perhaps just on a per-file basis. +1. More `archive` features: + + * Find out more about 0xffffffffffffffff addresses, and why such large + gaps exist after them. + * Use nm to get the full list of symbols that share the same address. + * Collect java symbol information + * Collect .pak file information (using .o.whitelist files) + * Collect .apk entry information + +1. More `console` features: + + * Template Symbols - shows when templates lead to code bloat. + * Duplicate Symbols - shows when statics in headers are an issue. + * Overloaded Symbols - shows when overloads are excessive. + * Per-class / namespace size (no way to distinguish class vs namespace). + * Per-Chrome package (Chrome-specific grouping. e.g. name prefixes). + * CSV output (for pasting into a spreadsheet). + +1. More `html_report` features: + + * Break down by other groupings (e.g. create from nested `SymbolGroups`) + +1. Integrate with `resource_sizes.py` so that it tracks size of major + components separately: chrome vs blink vs skia vs v8. +1. Speed up some steps (like normalizing names) via multiprocessing. +1. Add dependency graph info, perhaps just on a per-file basis. + +# Roadmap for diagnose_apk_bloat.py: +1. More `diagnose_apk_bloat.py` features: + + * Add diffing functionality to see diff stats for two commits. + * Add --cloud option for using artifacts from perf builders.
diff --git a/tools/binary_size/helpers.py b/tools/binary_size/helpers.py deleted file mode 100644 index c82a6ba..0000000 --- a/tools/binary_size/helpers.py +++ /dev/null
@@ -1,51 +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. - -"""Utility methods.""" - -import atexit -import distutils.spawn -import logging -import os -import platform -import resource -import sys - - -SRC_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(__file__))) - - -def AddCommonOptionsAndParseArgs(parser, argv, pypy_warn=True): - parser.add_argument('--no-pypy', action='store_true', - help='Do not automatically switch to pypy when available') - parser.add_argument('-v', - '--verbose', - default=0, - action='count', - help='Verbose level (multiple times for more)') - args = parser.parse_args(argv[1:]) - - logging.basicConfig(level=logging.WARNING - args.verbose * 10, - format='%(levelname).1s %(relativeCreated)6d %(message)s') - - if not args.no_pypy and platform.python_implementation() == 'CPython': - # Switch to pypy if it's available. - pypy_path = distutils.spawn.find_executable('pypy') - if pypy_path: - logging.debug('Switching to pypy.') - os.execv(pypy_path, [pypy_path] + sys.argv) - # NOTE! Running with python: 6s. Running with pypy: 3s - if pypy_warn: - logging.warning( - 'This script runs more than 2x faster if you install pypy.') - - if logging.getLogger().isEnabledFor(logging.DEBUG): - atexit.register(_LogPeakRamUsage) - return args - - -def _LogPeakRamUsage(): - peak_ram_usage = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss - peak_ram_usage += resource.getrusage(resource.RUSAGE_CHILDREN).ru_maxrss - logging.info('Peak RAM usage was %d MB.', peak_ram_usage / 1024)
diff --git a/tools/binary_size/map2size.py b/tools/binary_size/libsupersize/archive.py old mode 100755 new mode 100644 similarity index 96% rename from tools/binary_size/map2size.py rename to tools/binary_size/libsupersize/archive.py index 95310c3..7524094 --- a/tools/binary_size/map2size.py +++ b/tools/binary_size/libsupersize/archive.py
@@ -1,4 +1,3 @@ -#!/usr/bin/env python # 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. @@ -400,24 +399,27 @@ return ["%s=%s" % x for x in sorted(args.iteritems())] -def main(argv): - parser = argparse.ArgumentParser(argv) +def AddArguments(parser): + parser.add_argument('size_file', help='Path to output .size file.') parser.add_argument('--elf-file', required=True, help='Path to input ELF file. Currently used for ' - 'capturing metadata. Pass "" to skip metadata ' - 'collection.') + 'capturing metadata. Pass "" to skip ' + 'metadata collection.') parser.add_argument('--map-file', help='Path to input .map(.gz) file. Defaults to ' '{{elf_file}}.map(.gz)?') - parser.add_argument('--output-file', required=True, - help='Path to output .size file.') parser.add_argument('--no-source-paths', action='store_true', help='Do not use .ninja files to map ' 'object_path -> source_path') - paths.AddOptions(parser) - args = helpers.AddCommonOptionsAndParseArgs(parser, argv) - if not args.output_file.endswith('.size'): - parser.error('output_file must end with .size') + parser.add_argument('--tool-prefix', default='', + help='Path prefix for c++filt.') + parser.add_argument('--output-directory', + help='Path to the root build directory.') + + +def Run(args, parser): + if not args.size_file.endswith('.size'): + parser.error('size_file must end with .size') if args.map_file: if (not args.map_file.endswith('.map') @@ -469,10 +471,6 @@ logging.info('Recording metadata: \n %s', '\n '.join(describe.DescribeMetadata(size_info.metadata))) - logging.info('Saving result to %s', args.output_file) - file_format.SaveSizeInfo(size_info, args.output_file) + logging.info('Saving result to %s', args.size_file) + file_format.SaveSizeInfo(size_info, args.size_file) logging.info('Done') - - -if __name__ == '__main__': - sys.exit(main(sys.argv))
diff --git a/tools/binary_size/console.py b/tools/binary_size/libsupersize/console.py old mode 100755 new mode 100644 similarity index 85% rename from tools/binary_size/console.py rename to tools/binary_size/libsupersize/console.py index 53f7606..34de184 --- a/tools/binary_size/console.py +++ b/tools/binary_size/libsupersize/console.py
@@ -1,17 +1,8 @@ -#!/usr/bin/env python # 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. -"""Tool for analyzing binary size of executables using nm or linker map files. - -Map files can be created by passing "-Map Foo.map" to the linker. If a map file -is unavailable, this tool can also be pointed at an unstripped executable, but -the information does not seem to be as accurate in this case. - -Inspired by SymbolSort for Windows: - https://github.com/adrianstone55/SymbolSort -""" +"""An interactive console for looking analyzing .size files.""" import argparse import atexit @@ -24,10 +15,9 @@ import subprocess import sys +import archive import describe import file_format -import helpers -import map2size import match_util import models import paths @@ -120,8 +110,7 @@ output_dir = self._lazy_paths.output_directory or '' path = os.path.normpath(os.path.join(output_dir, filename)) - found_build_id = map2size.BuildIdFromElf( - path, self._lazy_paths.tool_prefix) + found_build_id = archive.BuildIdFromElf(path, self._lazy_paths.tool_prefix) expected_build_id = size_info.metadata.get(models.METADATA_ELF_BUILD_ID) assert found_build_id == expected_build_id, ( 'Build ID does not match for %s' % path) @@ -228,26 +217,30 @@ code.InteractiveConsole(self._variables).interact(self._CreateBanner()) -def main(argv): - parser = argparse.ArgumentParser() - parser.add_argument('inputs', nargs='+', - help='Input .size files to load. For a single file, ' - 'it will be mapped to variables as: size_info & ' - 'symbols (where symbols = size_info.symbols). For ' - 'multiple inputs, the names will be size_info1, ' - 'symbols1, etc.') - parser.add_argument('--query', - help='Print the result of the given snippet. Example: ' - 'symbols.WhereInSection("d").' - 'WhereBiggerThan(100)') - paths.AddOptions(parser) - args = helpers.AddCommonOptionsAndParseArgs(parser, argv) +def AddArguments(parser): + parser.add_argument( + 'inputs', nargs='+', + help='Input .size files to load. For a single file, it will be mapped to ' + 'the variable "size_info". For multiple inputs, the names will be ' + 'size_info1, size_info2, etc.') + parser.add_argument( + '--query', help='Print the result of the given snippet. Example: ' + 'size_info.symbols.WhereInSection("d")' + '.WhereBiggerThan(100)') + parser.add_argument('--tool-prefix', default='', + help='Path prefix for objdump. Required only for ' + 'Disassemble().') + parser.add_argument('--output-directory', + help='Path to the root build directory. Used only for ' + 'Disassemble().') + +def Run(args, parser): for path in args.inputs: if not path.endswith('.size'): parser.error('All inputs must end with ".size"') - size_infos = [map2size.LoadAndPostProcessSizeInfo(p) for p in args.inputs] + size_infos = [archive.LoadAndPostProcessSizeInfo(p) for p in args.inputs] lazy_paths = paths.LazyPaths(args=args, input_file=args.inputs[0]) session = _Session(size_infos, lazy_paths) @@ -257,7 +250,3 @@ else: logging.info('Entering interactive console.') session.GoInteractive() - - -if __name__ == '__main__': - sys.exit(main(sys.argv))
diff --git a/tools/binary_size/describe.py b/tools/binary_size/libsupersize/describe.py similarity index 100% rename from tools/binary_size/describe.py rename to tools/binary_size/libsupersize/describe.py
diff --git a/tools/binary_size/file_format.py b/tools/binary_size/libsupersize/file_format.py similarity index 99% rename from tools/binary_size/file_format.py rename to tools/binary_size/libsupersize/file_format.py index c9ef495..3e8baaf2 100644 --- a/tools/binary_size/file_format.py +++ b/tools/binary_size/libsupersize/file_format.py
@@ -10,11 +10,12 @@ import datetime import gzip import json -import models import logging import os import shutil +import models + # File format version for .size files. _SERIALIZATION_VERSION = 'Size File Format v1'
diff --git a/tools/binary_size/function_signature.py b/tools/binary_size/libsupersize/function_signature.py similarity index 100% rename from tools/binary_size/function_signature.py rename to tools/binary_size/libsupersize/function_signature.py
diff --git a/tools/binary_size/function_signature_test.py b/tools/binary_size/libsupersize/function_signature_test.py similarity index 100% rename from tools/binary_size/function_signature_test.py rename to tools/binary_size/libsupersize/function_signature_test.py
diff --git a/tools/binary_size/libsupersize/helpers.py b/tools/binary_size/libsupersize/helpers.py new file mode 100644 index 0000000..bddcd764 --- /dev/null +++ b/tools/binary_size/libsupersize/helpers.py
@@ -0,0 +1,11 @@ +# 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. + +"""Utility methods.""" + +import os + + +SRC_ROOT = os.path.dirname( + os.path.dirname(os.path.dirname(os.path.dirname(__file__))))
diff --git a/tools/binary_size/create_html_breakdown.py b/tools/binary_size/libsupersize/html_report.py old mode 100755 new mode 100644 similarity index 94% rename from tools/binary_size/create_html_breakdown.py rename to tools/binary_size/libsupersize/html_report.py index ad278b2..ac21349 --- a/tools/binary_size/create_html_breakdown.py +++ b/tools/binary_size/libsupersize/html_report.py
@@ -1,4 +1,3 @@ -#!/usr/bin/env python # 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. @@ -12,8 +11,8 @@ import shutil import sys +import archive import helpers -import map2size # Node dictionary keys. These are output in json read by the webapp so @@ -163,8 +162,7 @@ shutil.copy(os.path.join(template_src, 'D3SymbolTreeMap.js'), dest_dir) -def main(argv): - parser = argparse.ArgumentParser() +def AddArguments(parser): parser.add_argument('input_file', help='Path to input .size file.') parser.add_argument('--report-dir', metavar='PATH', required=True, @@ -175,9 +173,14 @@ 'space)') parser.add_argument('--include-symbols', action='store_true', help='Use per-symbol granularity rather than per-file.') - args = helpers.AddCommonOptionsAndParseArgs(parser, argv) - size_info = map2size.LoadAndPostProcessSizeInfo(args.input_file) + +def Run(args, parser): + if not args.input_file.endswith('.size'): + parser.error('Input must end with ".size"') + + logging.info('Reading .size file') + size_info = archive.LoadAndPostProcessSizeInfo(args.input_file) symbols = size_info.symbols if not args.include_bss: symbols = symbols.WhereInSection('b').Inverted() @@ -191,15 +194,11 @@ logging.info('Creating JSON objects') tree_root = _MakeCompactTree(symbols, args.include_symbols) - logging.info('Serializing') + logging.info('Serializing JSON') with open(os.path.join(args.report_dir, 'data.js'), 'w') as out_file: out_file.write('var tree_data=') # Use separators without whitespace to get a smaller file. json.dump(tree_root, out_file, ensure_ascii=False, check_circular=False, separators=(',', ':')) - print 'Report saved to ' + args.report_dir + '/index.html' - - -if __name__ == '__main__': - sys.exit(main(sys.argv)) + logging.warning('Report saved to %s/index.html', args.report_dir)
diff --git a/tools/binary_size/integration_test.py b/tools/binary_size/libsupersize/integration_test.py similarity index 85% rename from tools/binary_size/integration_test.py rename to tools/binary_size/libsupersize/integration_test.py index 40c3d6e..830c335 100755 --- a/tools/binary_size/integration_test.py +++ b/tools/binary_size/libsupersize/integration_test.py
@@ -13,9 +13,9 @@ import sys import tempfile +import archive import describe import file_format -import map2size import models import paths @@ -52,7 +52,7 @@ def _RunApp(name, *args): - argv = [os.path.join(_SCRIPT_DIR, name), '--no-pypy'] + argv = [os.path.join(_SCRIPT_DIR, 'main.py'), name, '--no-pypy'] argv.extend(args) return subprocess.check_output(argv).splitlines() @@ -64,16 +64,15 @@ if not IntegrationTest.size_info: lazy_paths = paths.LazyPaths(output_directory=_TEST_DATA_DIR) IntegrationTest.size_info = ( - map2size.CreateSizeInfo(_TEST_MAP_PATH, lazy_paths)) + archive.CreateSizeInfo(_TEST_MAP_PATH, lazy_paths)) return copy.deepcopy(IntegrationTest.size_info) @_CompareWithGolden - def test_Map2Size(self): + def test_Archive(self): with tempfile.NamedTemporaryFile(suffix='.size') as temp_file: - _RunApp('map2size.py', '--output-directory', _TEST_DATA_DIR, - '--map-file', _TEST_MAP_PATH, '--elf-file', '', - '--output-file', temp_file.name) - size_info = map2size.LoadAndPostProcessSizeInfo(temp_file.name) + _RunApp('archive', temp_file.name, '--output-directory', _TEST_DATA_DIR, + '--map-file', _TEST_MAP_PATH, '--elf-file', '') + size_info = archive.LoadAndPostProcessSizeInfo(temp_file.name) # Check that saving & loading is the same as directly parsing the .map. expected_size_info = self._CloneSizeInfo() self.assertEquals(expected_size_info.metadata, size_info.metadata) @@ -87,19 +86,18 @@ stats = describe.DescribeSizeInfoCoverage(size_info) return itertools.chain(stats, sym_strs) - def test_Map2Size_NoSourcePaths(self): + def test_Archive_NoSourcePaths(self): # Just tests that it doesn't crash. with tempfile.NamedTemporaryFile(suffix='.size') as temp_file: - _RunApp('map2size.py', '--no-source-paths', - '--map-file', _TEST_MAP_PATH, '--elf-file', '', - '--output-file', temp_file.name) - map2size.LoadAndPostProcessSizeInfo(temp_file.name) + _RunApp('archive', temp_file.name, '--no-source-paths', + '--map-file', _TEST_MAP_PATH, '--elf-file', '') + archive.LoadAndPostProcessSizeInfo(temp_file.name) @_CompareWithGolden def test_ConsoleNullDiff(self): with tempfile.NamedTemporaryFile(suffix='.size') as temp_file: file_format.SaveSizeInfo(self._CloneSizeInfo(), temp_file.name) - return _RunApp('console.py', '--query', 'Diff(size_info1, size_info2)', + return _RunApp('console', '--query', 'Diff(size_info1, size_info2)', temp_file.name, temp_file.name) @_CompareWithGolden
diff --git a/tools/binary_size/linker_map_parser.py b/tools/binary_size/libsupersize/linker_map_parser.py similarity index 100% rename from tools/binary_size/linker_map_parser.py rename to tools/binary_size/libsupersize/linker_map_parser.py
diff --git a/tools/binary_size/libsupersize/main.py b/tools/binary_size/libsupersize/main.py new file mode 100755 index 0000000..4eeb894 --- /dev/null +++ b/tools/binary_size/libsupersize/main.py
@@ -0,0 +1,83 @@ +#!/usr/bin/env python +# 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. + +"""Collect, archive, and analyze Chrome's binary size.""" + +import argparse +import atexit +import collections +import distutils.spawn +import logging +import os +import platform +import resource +import sys + +import archive +import console +import html_report + + +def _LogPeakRamUsage(): + peak_ram_usage = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss + peak_ram_usage += resource.getrusage(resource.RUSAGE_CHILDREN).ru_maxrss + logging.info('Peak RAM usage was %d MB.', peak_ram_usage / 1024) + + +def _AddCommonArguments(parser): + parser.add_argument('--no-pypy', action='store_true', + help='Do not automatically switch to pypy when available') + parser.add_argument('-v', + '--verbose', + default=0, + action='count', + help='Verbose level (multiple times for more)') + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + sub_parsers = parser.add_subparsers() + actions = collections.OrderedDict() + actions['archive'] = (archive, 'Create a .size file') + actions['html_report'] = ( + html_report, 'Create a stand-alone html report from a .size file.') + actions['console'] = ( + console, + 'Starts an interactive Python console for analyzing .size files.') + + for name, tup in actions.iteritems(): + sub_parser = sub_parsers.add_parser(name, help=tup[1]) + _AddCommonArguments(sub_parser) + tup[0].AddArguments(sub_parser) + sub_parser.set_defaults(func=tup[0].Run) + + if len(sys.argv) == 1: + parser.print_help() + sys.exit(1) + elif len(sys.argv) == 2 and sys.argv[1] in actions: + parser.parse_args(sys.argv[1:] + ['-h']) + sys.exit(1) + + args = parser.parse_args() + logging.basicConfig(level=logging.WARNING - args.verbose * 10, + format='%(levelname).1s %(relativeCreated)6d %(message)s') + + if not args.no_pypy and platform.python_implementation() == 'CPython': + # Switch to pypy if it's available. + pypy_path = distutils.spawn.find_executable('pypy') + if pypy_path: + logging.debug('Switching to pypy.') + os.execv(pypy_path, [pypy_path] + sys.argv) + # Running with python: 6s. Running with pypy: 3s + logging.warning('This script runs more than 2x faster if you install pypy.') + + if logging.getLogger().isEnabledFor(logging.DEBUG): + atexit.register(_LogPeakRamUsage) + + args.func(args, parser) + + +if __name__ == '__main__': + sys.exit(main())
diff --git a/tools/binary_size/match_util.py b/tools/binary_size/libsupersize/match_util.py similarity index 100% rename from tools/binary_size/match_util.py rename to tools/binary_size/libsupersize/match_util.py
diff --git a/tools/binary_size/match_util_test.py b/tools/binary_size/libsupersize/match_util_test.py similarity index 99% rename from tools/binary_size/match_util_test.py rename to tools/binary_size/libsupersize/match_util_test.py index 15053990..eb5349a 100755 --- a/tools/binary_size/match_util_test.py +++ b/tools/binary_size/libsupersize/match_util_test.py
@@ -3,10 +3,10 @@ # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. +import re import unittest import match_util -import re class MatchHelperTest(unittest.TestCase):
diff --git a/tools/binary_size/models.py b/tools/binary_size/libsupersize/models.py similarity index 100% rename from tools/binary_size/models.py rename to tools/binary_size/libsupersize/models.py
diff --git a/tools/binary_size/ninja_parser.py b/tools/binary_size/libsupersize/ninja_parser.py similarity index 100% rename from tools/binary_size/ninja_parser.py rename to tools/binary_size/libsupersize/ninja_parser.py
diff --git a/tools/binary_size/paths.py b/tools/binary_size/libsupersize/paths.py similarity index 93% rename from tools/binary_size/paths.py rename to tools/binary_size/libsupersize/paths.py index 360ab32d..bf877cb6 100644 --- a/tools/binary_size/paths.py +++ b/tools/binary_size/libsupersize/paths.py
@@ -12,13 +12,6 @@ _STATUS_VERIFIED = 2 -def AddOptions(parser): - parser.add_argument('--tool-prefix', default='', - help='Path prefix for c++filt.') - parser.add_argument('--output-directory', - help='Path to the root build directory.') - - class LazyPaths(object): def __init__(self, args=None, tool_prefix=None, output_directory=None, input_file=None):
diff --git a/tools/binary_size/template/D3SymbolTreeMap.js b/tools/binary_size/libsupersize/template/D3SymbolTreeMap.js similarity index 100% rename from tools/binary_size/template/D3SymbolTreeMap.js rename to tools/binary_size/libsupersize/template/D3SymbolTreeMap.js
diff --git a/tools/binary_size/template/index.html b/tools/binary_size/libsupersize/template/index.html similarity index 100% rename from tools/binary_size/template/index.html rename to tools/binary_size/libsupersize/template/index.html
diff --git a/tools/binary_size/template/test-data-generator.html b/tools/binary_size/libsupersize/template/test-data-generator.html similarity index 100% rename from tools/binary_size/template/test-data-generator.html rename to tools/binary_size/libsupersize/template/test-data-generator.html
diff --git a/tools/binary_size/testdata/ActualDiff.golden b/tools/binary_size/libsupersize/testdata/ActualDiff.golden similarity index 100% rename from tools/binary_size/testdata/ActualDiff.golden rename to tools/binary_size/libsupersize/testdata/ActualDiff.golden
diff --git a/tools/binary_size/testdata/Map2Size.golden b/tools/binary_size/libsupersize/testdata/Archive.golden similarity index 100% rename from tools/binary_size/testdata/Map2Size.golden rename to tools/binary_size/libsupersize/testdata/Archive.golden
diff --git a/tools/binary_size/testdata/ConsoleNullDiff.golden b/tools/binary_size/libsupersize/testdata/ConsoleNullDiff.golden similarity index 100% rename from tools/binary_size/testdata/ConsoleNullDiff.golden rename to tools/binary_size/libsupersize/testdata/ConsoleNullDiff.golden
diff --git a/tools/binary_size/testdata/FullDescription.golden b/tools/binary_size/libsupersize/testdata/FullDescription.golden similarity index 100% rename from tools/binary_size/testdata/FullDescription.golden rename to tools/binary_size/libsupersize/testdata/FullDescription.golden
diff --git a/tools/binary_size/testdata/SymbolGroupMethods.golden b/tools/binary_size/libsupersize/testdata/SymbolGroupMethods.golden similarity index 100% rename from tools/binary_size/testdata/SymbolGroupMethods.golden rename to tools/binary_size/libsupersize/testdata/SymbolGroupMethods.golden
diff --git a/tools/binary_size/testdata/build.ninja b/tools/binary_size/libsupersize/testdata/build.ninja similarity index 100% rename from tools/binary_size/testdata/build.ninja rename to tools/binary_size/libsupersize/testdata/build.ninja
diff --git a/tools/binary_size/testdata/sub.ninja b/tools/binary_size/libsupersize/testdata/sub.ninja similarity index 100% rename from tools/binary_size/testdata/sub.ninja rename to tools/binary_size/libsupersize/testdata/sub.ninja
diff --git a/tools/binary_size/testdata/test.map b/tools/binary_size/libsupersize/testdata/test.map similarity index 100% rename from tools/binary_size/testdata/test.map rename to tools/binary_size/libsupersize/testdata/test.map
diff --git a/tools/binary_size/supersize b/tools/binary_size/supersize new file mode 100755 index 0000000..87a5630 --- /dev/null +++ b/tools/binary_size/supersize
@@ -0,0 +1,8 @@ +#!/usr/bin/env bash +# 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. + +base_dir=$(dirname "$0") + +exec python "$base_dir/libsupersize/main.py" "$@"
diff --git a/tools/clang/blink_gc_plugin/BlinkGCPlugin.cpp b/tools/clang/blink_gc_plugin/BlinkGCPlugin.cpp index d263a8cc..08572bc 100644 --- a/tools/clang/blink_gc_plugin/BlinkGCPlugin.cpp +++ b/tools/clang/blink_gc_plugin/BlinkGCPlugin.cpp
@@ -36,7 +36,7 @@ } else if (arg == "warn-unneeded-finalizer") { options_.warn_unneeded_finalizer = true; } else if (arg == "use-chromium-style-naming") { - options_.use_chromium_style_naming = true; + // TODO(dcheng): Remove this once the build no longer passes this flag. } else { llvm::errs() << "Unknown blink-gc-plugin argument: " << arg << "\n"; return false;
diff --git a/tools/clang/blink_gc_plugin/BlinkGCPluginConsumer.cpp b/tools/clang/blink_gc_plugin/BlinkGCPluginConsumer.cpp index 771d3f8..a770f82 100644 --- a/tools/clang/blink_gc_plugin/BlinkGCPluginConsumer.cpp +++ b/tools/clang/blink_gc_plugin/BlinkGCPluginConsumer.cpp
@@ -75,9 +75,6 @@ // Ignore GC implementation files. options_.ignored_directories.push_back("/heap/"); - - if (!options_.use_chromium_style_naming) - Config::UseLegacyNames(); } void BlinkGCPluginConsumer::HandleTranslationUnit(ASTContext& context) {
diff --git a/tools/clang/blink_gc_plugin/BlinkGCPluginOptions.h b/tools/clang/blink_gc_plugin/BlinkGCPluginOptions.h index fee044b..7aee25f 100644 --- a/tools/clang/blink_gc_plugin/BlinkGCPluginOptions.h +++ b/tools/clang/blink_gc_plugin/BlinkGCPluginOptions.h
@@ -16,9 +16,6 @@ // GarbageCollectedFinalized<> when just GarbageCollected<> will do. bool warn_unneeded_finalizer = false; - // TODO(https://crbug.com/675879): Clean up after the Blink rename. - bool use_chromium_style_naming = false; - std::set<std::string> ignored_classes; std::set<std::string> checked_namespaces; std::vector<std::string> ignored_directories;
diff --git a/tools/clang/blink_gc_plugin/CMakeLists.txt b/tools/clang/blink_gc_plugin/CMakeLists.txt index 66549ed..009807b 100644 --- a/tools/clang/blink_gc_plugin/CMakeLists.txt +++ b/tools/clang/blink_gc_plugin/CMakeLists.txt
@@ -30,11 +30,6 @@ endforeach() set_property(TARGET clang APPEND PROPERTY SOURCES ${absolute_sources}) - # TODO(https://crbug.com/675879): Clean up after the Blink rename. - cr_add_test(blink_gc_plugin_legacy_test - python tests/legacy_naming/test.py - ${CMAKE_BINARY_DIR}/bin/clang - ) cr_add_test(blink_gc_plugin_test python tests/test.py ${CMAKE_BINARY_DIR}/bin/clang @@ -45,12 +40,6 @@ cr_install(TARGETS "lib${LIBRARYNAME}" LIBRARY DESTINATION lib) - # TODO(https://crbug.com/675879): Clean up after the Blink rename. - cr_add_test(blink_gc_plugin_legacy_test - python tests/legacy_naming/test.py - ${CMAKE_BINARY_DIR}/bin/clang - $<TARGET_FILE:lib${LIBRARYNAME}> - ) cr_add_test(blink_gc_plugin_test python tests/test.py ${CMAKE_BINARY_DIR}/bin/clang
diff --git a/tools/clang/blink_gc_plugin/Config.cpp b/tools/clang/blink_gc_plugin/Config.cpp index fa00782c..df8867a9 100644 --- a/tools/clang/blink_gc_plugin/Config.cpp +++ b/tools/clang/blink_gc_plugin/Config.cpp
@@ -10,45 +10,24 @@ using namespace clang; -// Legacy names to be removed after Blink rename: -namespace legacy { -const char kCreateName[] = "create"; -const char kTraceName[] = "trace"; -const char kFinalizeName[] = "finalizeGarbageCollectedObject"; -const char kTraceAfterDispatchName[] = "traceAfterDispatch"; -const char kRegisterWeakMembersName[] = "registerWeakMembers"; -const char kAdjustAndMarkName[] = "adjustAndMark"; -const char kIsHeapObjectAliveName[] = "isHeapObjectAlive"; -} // namespace legacy - const char kNewOperatorName[] = "operator new"; -const char* kCreateName = "Create"; -const char* kTraceName = "Trace"; -const char* kFinalizeName = "FinalizeGarbageCollectedObject"; -const char* kTraceAfterDispatchName = "TraceAfterDispatch"; -const char* kRegisterWeakMembersName = "RegisterWeakMembers"; +const char kCreateName[] = "Create"; +const char kTraceName[] = "Trace"; +const char kFinalizeName[] = "FinalizeGarbageCollectedObject"; +const char kTraceAfterDispatchName[] = "TraceAfterDispatch"; +const char kRegisterWeakMembersName[] = "RegisterWeakMembers"; const char kHeapAllocatorName[] = "HeapAllocator"; const char kTraceIfNeededName[] = "TraceIfNeeded"; const char kVisitorDispatcherName[] = "VisitorDispatcher"; const char kVisitorVarName[] = "visitor"; -const char* kAdjustAndMarkName = "AdjustAndMark"; -const char* kIsHeapObjectAliveName = "IsHeapObjectAlive"; +const char kAdjustAndMarkName[] = "AdjustAndMark"; +const char kIsHeapObjectAliveName[] = "IsHeapObjectAlive"; const char kIsEagerlyFinalizedName[] = "IsEagerlyFinalizedMarker"; const char kConstIteratorName[] = "const_iterator"; const char kIteratorName[] = "iterator"; const char kConstReverseIteratorName[] = "const_reverse_iterator"; const char kReverseIteratorName[] = "reverse_iterator"; -void Config::UseLegacyNames() { - kCreateName = legacy::kCreateName; - kTraceName = legacy::kTraceName; - kFinalizeName = legacy::kFinalizeName; - kTraceAfterDispatchName = legacy::kTraceAfterDispatchName; - kRegisterWeakMembersName = legacy::kRegisterWeakMembersName; - kAdjustAndMarkName = legacy::kAdjustAndMarkName; - kIsHeapObjectAliveName = legacy::kIsHeapObjectAliveName; -} - bool Config::IsTemplateInstantiation(CXXRecordDecl* record) { ClassTemplateSpecializationDecl* spec = dyn_cast<clang::ClassTemplateSpecializationDecl>(record);
diff --git a/tools/clang/blink_gc_plugin/Config.h b/tools/clang/blink_gc_plugin/Config.h index f0c4aec..13d38e8 100644 --- a/tools/clang/blink_gc_plugin/Config.h +++ b/tools/clang/blink_gc_plugin/Config.h
@@ -18,17 +18,17 @@ #include "clang/AST/Attr.h" extern const char kNewOperatorName[]; -extern const char* kCreateName; -extern const char* kTraceName; -extern const char* kFinalizeName; -extern const char* kTraceAfterDispatchName; -extern const char* kRegisterWeakMembersName; +extern const char kCreateName[]; +extern const char kTraceName[]; +extern const char kFinalizeName[]; +extern const char kTraceAfterDispatchName[]; +extern const char kRegisterWeakMembersName[]; extern const char kHeapAllocatorName[]; extern const char kTraceIfNeededName[]; extern const char kVisitorDispatcherName[]; extern const char kVisitorVarName[]; -extern const char* kAdjustAndMarkName; -extern const char* kIsHeapObjectAliveName; +extern const char kAdjustAndMarkName[]; +extern const char kIsHeapObjectAliveName[]; extern const char kIsEagerlyFinalizedName[]; extern const char kConstIteratorName[]; extern const char kIteratorName[]; @@ -37,8 +37,6 @@ class Config { public: - static void UseLegacyNames(); - static bool IsMember(const std::string& name) { return name == "Member"; }
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/.gitignore b/tools/clang/blink_gc_plugin/tests/legacy_naming/.gitignore deleted file mode 100644 index 8564477b..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/.gitignore +++ /dev/null
@@ -1,2 +0,0 @@ -/*.o -/*.txt.actual
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/base_class_must_define_virtual_trace.cpp b/tools/clang/blink_gc_plugin/tests/legacy_naming/base_class_must_define_virtual_trace.cpp deleted file mode 100644 index cd38ec9..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/base_class_must_define_virtual_trace.cpp +++ /dev/null
@@ -1,19 +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 "base_class_must_define_virtual_trace.h" - -namespace blink { - -void PartDerived::trace(Visitor* visitor) -{ -} - -void HeapDerived::trace(Visitor* visitor) -{ - visitor->trace(m_part); -} - - -}
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/base_class_must_define_virtual_trace.h b/tools/clang/blink_gc_plugin/tests/legacy_naming/base_class_must_define_virtual_trace.h deleted file mode 100644 index fbd26d73..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/base_class_must_define_virtual_trace.h +++ /dev/null
@@ -1,38 +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 BASE_CLASS_MUST_DEFINE_VIRTUAL_TRACE_H_ -#define BASE_CLASS_MUST_DEFINE_VIRTUAL_TRACE_H_ - -#include "heap/stubs.h" - -namespace blink { - -class PartBase { - DISALLOW_NEW(); - // Missing virtual trace. -}; - -class PartDerived : public PartBase { - DISALLOW_NEW(); -public: - virtual void trace(Visitor*); -}; - -class HeapBase : public GarbageCollected<HeapBase> { - // Missing virtual trace. -}; - - -class HeapDerived : public HeapBase { -public: - virtual void trace(Visitor*); -private: - PartDerived m_part; -}; - - -} - -#endif
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/base_class_must_define_virtual_trace.txt b/tools/clang/blink_gc_plugin/tests/legacy_naming/base_class_must_define_virtual_trace.txt deleted file mode 100644 index f8276eb2..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/base_class_must_define_virtual_trace.txt +++ /dev/null
@@ -1,8 +0,0 @@ -In file included from base_class_must_define_virtual_trace.cpp:5: -./base_class_must_define_virtual_trace.h:12:1: warning: [blink-gc] Left-most base class 'PartBase' of derived class 'PartDerived' must define a virtual trace method. -class PartBase { -^ -./base_class_must_define_virtual_trace.h:23:1: warning: [blink-gc] Left-most base class 'HeapBase' of derived class 'HeapDerived' must define a virtual trace method. -class HeapBase : public GarbageCollected<HeapBase> { -^ -2 warnings generated.
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/base_requires_tracing.cpp b/tools/clang/blink_gc_plugin/tests/legacy_naming/base_requires_tracing.cpp deleted file mode 100644 index 87559a85..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/base_requires_tracing.cpp +++ /dev/null
@@ -1,21 +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 "base_requires_tracing.h" - -namespace blink { - -void A::trace(Visitor* visitor) { } - -void C::trace(Visitor* visitor) { - visitor->trace(m_a); - // Missing B::trace(visitor) -} - -void D::trace(Visitor* visitor) { - visitor->trace(m_a); - C::trace(visitor); -} - -}
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/base_requires_tracing.h b/tools/clang/blink_gc_plugin/tests/legacy_naming/base_requires_tracing.h deleted file mode 100644 index 0205a08..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/base_requires_tracing.h +++ /dev/null
@@ -1,37 +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 BASE_REQUIRES_TRACING_H_ -#define BASE_REQUIRES_TRACING_H_ - -#include "heap/stubs.h" - -namespace blink { - -class A : public GarbageCollected<A> { -public: - virtual void trace(Visitor*); -}; - -class B : public A { - // Does not need trace -}; - -class C : public B { -public: - void trace(Visitor*); -private: - Member<A> m_a; -}; - -class D : public C { -public: - void trace(Visitor*); -private: - Member<A> m_a; -}; - -} - -#endif
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/base_requires_tracing.txt b/tools/clang/blink_gc_plugin/tests/legacy_naming/base_requires_tracing.txt deleted file mode 100644 index ee525b9d..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/base_requires_tracing.txt +++ /dev/null
@@ -1,4 +0,0 @@ -base_requires_tracing.cpp:11:1: warning: [blink-gc] Base class 'B' of derived class 'C' requires tracing. -void C::trace(Visitor* visitor) { -^ -1 warning generated.
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/class_does_not_require_finalization.cpp b/tools/clang/blink_gc_plugin/tests/legacy_naming/class_does_not_require_finalization.cpp deleted file mode 100644 index 9c51eca..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/class_does_not_require_finalization.cpp +++ /dev/null
@@ -1,22 +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 "class_does_not_require_finalization.h" - -namespace blink { - -void DoesNotNeedFinalizer::trace(Visitor* visitor) -{ -} - -DoesNotNeedFinalizer2::~DoesNotNeedFinalizer2() -{ -} - -void DoesNotNeedFinalizer2::trace(Visitor* visitor) -{ -} - - -}
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/class_does_not_require_finalization.flags b/tools/clang/blink_gc_plugin/tests/legacy_naming/class_does_not_require_finalization.flags deleted file mode 100644 index b0bf138..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/class_does_not_require_finalization.flags +++ /dev/null
@@ -1 +0,0 @@ --Xclang -plugin-arg-blink-gc-plugin -Xclang warn-unneeded-finalizer \ No newline at end of file
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/class_does_not_require_finalization.h b/tools/clang/blink_gc_plugin/tests/legacy_naming/class_does_not_require_finalization.h deleted file mode 100644 index c6530f30..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/class_does_not_require_finalization.h +++ /dev/null
@@ -1,47 +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 CLASS_DOES_NOT_REQUIRE_FINALIZATION_BASE_H_ -#define CLASS_DOES_NOT_REQUIRE_FINALIZATION_BASE_H_ - -#include "heap/stubs.h" - -namespace blink { - -class DoesNeedFinalizer : public GarbageCollectedFinalized<DoesNeedFinalizer> { -public: - ~DoesNeedFinalizer() { ; } - void trace(Visitor*); -}; - -class DoesNotNeedFinalizer - : public GarbageCollectedFinalized<DoesNotNeedFinalizer> { -public: - void trace(Visitor*); -}; - -class DoesNotNeedFinalizer2 - : public GarbageCollectedFinalized<DoesNotNeedFinalizer2> { -public: - ~DoesNotNeedFinalizer2(); - void trace(Visitor*); -}; - -class HasEmptyDtor { -public: - virtual ~HasEmptyDtor() { } -}; - -// If there are any virtual destructors involved, give up. - -class DoesNeedFinalizer2 - : public GarbageCollectedFinalized<DoesNeedFinalizer2>, - public HasEmptyDtor { -public: - void trace(Visitor*); -}; - -} - -#endif
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/class_does_not_require_finalization.txt b/tools/clang/blink_gc_plugin/tests/legacy_naming/class_does_not_require_finalization.txt deleted file mode 100644 index 91e264d6..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/class_does_not_require_finalization.txt +++ /dev/null
@@ -1,8 +0,0 @@ -In file included from class_does_not_require_finalization.cpp:5: -./class_does_not_require_finalization.h:18:1: warning: [blink-gc] Class 'DoesNotNeedFinalizer' may not require finalization. -class DoesNotNeedFinalizer -^ -./class_does_not_require_finalization.h:24:1: warning: [blink-gc] Class 'DoesNotNeedFinalizer2' may not require finalization. -class DoesNotNeedFinalizer2 -^ -2 warnings generated.
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/class_multiple_trace_bases.cpp b/tools/clang/blink_gc_plugin/tests/legacy_naming/class_multiple_trace_bases.cpp deleted file mode 100644 index 5bb87c9..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/class_multiple_trace_bases.cpp +++ /dev/null
@@ -1,22 +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 "class_multiple_trace_bases.h" - -namespace blink { - -void Base::trace(Visitor* visitor) { } - -void Mixin1::trace(Visitor* visitor) { } - -void Mixin2::trace(Visitor* visitor) { } - -// Missing: void Derived1::trace(Visitor* visitor); - -void Derived2::trace(Visitor* visitor) { - Base::trace(visitor); - Mixin1::trace(visitor); -} - -}
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/class_multiple_trace_bases.h b/tools/clang/blink_gc_plugin/tests/legacy_naming/class_multiple_trace_bases.h deleted file mode 100644 index 133f006..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/class_multiple_trace_bases.h +++ /dev/null
@@ -1,39 +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 CLASS_MULTIPLE_TRACE_BASES_H_ -#define CLASS_MULTIPLE_TRACE_BASES_H_ - -#include "heap/stubs.h" - -namespace blink { - -class Base : public GarbageCollected<Base> { -public: - virtual void trace(Visitor*); -}; - -class Mixin1 : public GarbageCollectedMixin { -public: - void trace(Visitor*); -}; - -class Mixin2 : public GarbageCollectedMixin { -public: - void trace(Visitor*); -}; - -class Derived1 : public Base, public Mixin1 { - USING_GARBAGE_COLLECTED_MIXIN(Derived1); - // Requires trace method. -}; - -class Derived2 : public Base, public Mixin1, public Mixin2 { - USING_GARBAGE_COLLECTED_MIXIN(Derived2); - void trace(Visitor*) override; -}; - -} - -#endif
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/class_multiple_trace_bases.txt b/tools/clang/blink_gc_plugin/tests/legacy_naming/class_multiple_trace_bases.txt deleted file mode 100644 index 33ae5f5..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/class_multiple_trace_bases.txt +++ /dev/null
@@ -1,14 +0,0 @@ -In file included from class_multiple_trace_bases.cpp:5: -./class_multiple_trace_bases.h:27:1: warning: [blink-gc] Class 'Derived1' requires a trace method. -class Derived1 : public Base, public Mixin1 { -^ -./class_multiple_trace_bases.h:27:18: note: [blink-gc] Untraced base class 'Base' declared here: -class Derived1 : public Base, public Mixin1 { - ^ -./class_multiple_trace_bases.h:27:31: note: [blink-gc] Untraced base class 'Mixin1' declared here: -class Derived1 : public Base, public Mixin1 { - ^ -class_multiple_trace_bases.cpp:17:1: warning: [blink-gc] Base class 'Mixin2' of derived class 'Derived2' requires tracing. -void Derived2::trace(Visitor* visitor) { -^ -2 warnings generated.
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/class_overrides_new.cpp b/tools/clang/blink_gc_plugin/tests/legacy_naming/class_overrides_new.cpp deleted file mode 100644 index 9f47f82a..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/class_overrides_new.cpp +++ /dev/null
@@ -1,7 +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 "class_overrides_new.h" - -// Nothing to define.
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/class_overrides_new.h b/tools/clang/blink_gc_plugin/tests/legacy_naming/class_overrides_new.h deleted file mode 100644 index 3e80e37..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/class_overrides_new.h +++ /dev/null
@@ -1,20 +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 CLASS_OVERRIDES_NEW_H_ -#define CLASS_OVERRIDES_NEW_H_ - -#include "heap/stubs.h" - -namespace blink { - -class HeapObject : public GarbageCollected<HeapObject> { - WTF_MAKE_FAST_ALLOCATED; -public: - void trace(Visitor*) { } -}; - -} - -#endif
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/class_overrides_new.txt b/tools/clang/blink_gc_plugin/tests/legacy_naming/class_overrides_new.txt deleted file mode 100644 index 17f50fe..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/class_overrides_new.txt +++ /dev/null
@@ -1,8 +0,0 @@ -In file included from class_overrides_new.cpp:5: -./class_overrides_new.h:13:5: warning: [blink-gc] Garbage collected class 'HeapObject' is not permitted to override its new operator. - WTF_MAKE_FAST_ALLOCATED; - ^ -./heap/stubs.h:14:5: note: expanded from macro 'WTF_MAKE_FAST_ALLOCATED' - void* operator new(size_t size); \ - ^ -1 warning generated.
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/class_requires_finalization_base.cpp b/tools/clang/blink_gc_plugin/tests/legacy_naming/class_requires_finalization_base.cpp deleted file mode 100644 index 8d47634..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/class_requires_finalization_base.cpp +++ /dev/null
@@ -1,19 +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 "class_requires_finalization_base.h" - -namespace blink { - -void NeedsFinalizer::trace(Visitor* visitor) -{ - A::trace(visitor); -} - -void DoesNotNeedFinalizer::trace(Visitor* visitor) -{ - A::trace(visitor); -} - -}
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/class_requires_finalization_base.h b/tools/clang/blink_gc_plugin/tests/legacy_naming/class_requires_finalization_base.h deleted file mode 100644 index 239c2cf1..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/class_requires_finalization_base.h +++ /dev/null
@@ -1,36 +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 CLASS_REQUIRES_FINALIZATION_BASE_H_ -#define CLASS_REQUIRES_FINALIZATION_BASE_H_ - -#include "heap/stubs.h" - -namespace blink { - -class A : public GarbageCollected<A> { -public: - virtual void trace(Visitor*) {} -}; - -class B { -public: - ~B() { /* user-declared, thus, non-trivial */ } -}; - -// Second base class needs finalization. -class NeedsFinalizer : public A, public B { -public: - void trace(Visitor*); -}; - -// Base does not need finalization. -class DoesNotNeedFinalizer : public A { -public: - void trace(Visitor*); -}; - -} - -#endif
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/class_requires_finalization_base.txt b/tools/clang/blink_gc_plugin/tests/legacy_naming/class_requires_finalization_base.txt deleted file mode 100644 index 935883d..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/class_requires_finalization_base.txt +++ /dev/null
@@ -1,8 +0,0 @@ -In file included from class_requires_finalization_base.cpp:5: -./class_requires_finalization_base.h:23:1: warning: [blink-gc] Class 'NeedsFinalizer' requires finalization. -class NeedsFinalizer : public A, public B { -^ -./class_requires_finalization_base.h:23:34: note: [blink-gc] Base class 'B' requiring finalization declared here: -class NeedsFinalizer : public A, public B { - ^ -1 warning generated.
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/class_requires_finalization_field.cpp b/tools/clang/blink_gc_plugin/tests/legacy_naming/class_requires_finalization_field.cpp deleted file mode 100644 index eb23ab03..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/class_requires_finalization_field.cpp +++ /dev/null
@@ -1,34 +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 "class_requires_finalization_field.h" - -namespace blink { - -void NeedsFinalizer::trace(Visitor* visitor) -{ - visitor->trace(m_as); - A::trace(visitor); -} - -void AlsoNeedsFinalizer::trace(Visitor* visitor) -{ - visitor->trace(m_bs); - A::trace(visitor); -} - -void DoesNotNeedFinalizer::trace(Visitor* visitor) -{ - visitor->trace(m_bs); - A::trace(visitor); -} - -void AlsoDoesNotNeedFinalizer::trace(Visitor* visitor) -{ - visitor->trace(m_as); - visitor->trace(m_cs); - A::trace(visitor); -} - -}
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/class_requires_finalization_field.h b/tools/clang/blink_gc_plugin/tests/legacy_naming/class_requires_finalization_field.h deleted file mode 100644 index 9596127..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/class_requires_finalization_field.h +++ /dev/null
@@ -1,80 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CLASS_REQUIRES_FINALIZATION_H_ -#define CLASS_REQUIRES_FINALIZATION_H_ - -#include "heap/stubs.h" - -namespace blink { - -class A : public GarbageCollected<A> { -public: - virtual void trace(Visitor*) { } -}; - -// Has a non-trivial dtor (user-declared). -class B { -public: - ~B() { } - void trace(Visitor*) { }; -}; - -// Has a trivial dtor. -class C { -public: - void trace(Visitor*) { }; -}; - -} // blink namespace - -namespace WTF { - -template<> -struct VectorTraits<blink::C> { - static const bool needsDestruction = false; -}; - -} // WTF namespace - -namespace blink { - -// Off-heap vectors always need to be finalized. -class NeedsFinalizer : public A { -public: - void trace(Visitor*); -private: - Vector<Member<A> > m_as; -}; - -// On-heap vectors with inlined objects that need destruction -// need to be finalized. -class AlsoNeedsFinalizer : public A { -public: - void trace(Visitor*); -private: - HeapVector<B, 10> m_bs; -}; - -// On-heap vectors with no inlined objects never need to be finalized. -class DoesNotNeedFinalizer : public A { -public: - void trace(Visitor*); -private: - HeapVector<B> m_bs; -}; - -// On-heap vectors with inlined objects that don't need destruction -// don't need to be finalized. -class AlsoDoesNotNeedFinalizer : public A { -public: - void trace(Visitor*); -private: - HeapVector<Member<A>, 10> m_as; - HeapVector<C, 10> m_cs; -}; - -} - -#endif
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/class_requires_finalization_field.txt b/tools/clang/blink_gc_plugin/tests/legacy_naming/class_requires_finalization_field.txt deleted file mode 100644 index 9e37c46..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/class_requires_finalization_field.txt +++ /dev/null
@@ -1,14 +0,0 @@ -In file included from class_requires_finalization_field.cpp:5: -./class_requires_finalization_field.h:44:1: warning: [blink-gc] Class 'NeedsFinalizer' requires finalization. -class NeedsFinalizer : public A { -^ -./class_requires_finalization_field.h:48:5: note: [blink-gc] Field 'm_as' requiring finalization declared here: - Vector<Member<A> > m_as; - ^ -./class_requires_finalization_field.h:53:1: warning: [blink-gc] Class 'AlsoNeedsFinalizer' requires finalization. -class AlsoNeedsFinalizer : public A { -^ -./class_requires_finalization_field.h:57:5: note: [blink-gc] Field 'm_bs' requiring finalization declared here: - HeapVector<B, 10> m_bs; - ^ -2 warnings generated.
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/class_requires_finalization_mixin.cpp b/tools/clang/blink_gc_plugin/tests/legacy_naming/class_requires_finalization_mixin.cpp deleted file mode 100644 index 782810e..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/class_requires_finalization_mixin.cpp +++ /dev/null
@@ -1,37 +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 "class_requires_finalization_mixin.h" - -namespace blink { - -void MixinFinalizable::trace(Visitor* visitor) -{ - visitor->trace(m_onHeap); -} - -void MixinNotFinalizable::trace(Visitor* visitor) -{ - visitor->trace(m_onHeap); -} - -void NeedsFinalizer::trace(Visitor* visitor) -{ - visitor->trace(m_obj); - MixinFinalizable::trace(visitor); -} - -void HasFinalizer::trace(Visitor* visitor) -{ - visitor->trace(m_obj); - MixinFinalizable::trace(visitor); -} - -void NeedsNoFinalization::trace(Visitor* visitor) -{ - visitor->trace(m_obj); - MixinNotFinalizable::trace(visitor); -} - -}
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/class_requires_finalization_mixin.h b/tools/clang/blink_gc_plugin/tests/legacy_naming/class_requires_finalization_mixin.h deleted file mode 100644 index 10befbd..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/class_requires_finalization_mixin.h +++ /dev/null
@@ -1,61 +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 CLASS_REQUIRES_FINALIZATION_MIXIN_H_ -#define CLASS_REQUIRES_FINALIZATION_MIXIN_H_ - -#include "heap/stubs.h" - -namespace blink { - -class OffHeap : public RefCounted<OffHeap> { }; -class OnHeap : public GarbageCollected<OnHeap> { }; - -class MixinFinalizable : public GarbageCollectedMixin { -public: - virtual void trace(Visitor*) override; -private: - RefPtr<OffHeap> m_offHeap; // Requires finalization - Member<OnHeap> m_onHeap; -}; - -class MixinNotFinalizable : public GarbageCollectedMixin { -public: - virtual void trace(Visitor*) override; -private: - Member<OnHeap> m_onHeap; -}; - -class NeedsFinalizer - : public GarbageCollected<NeedsFinalizer> - , public MixinFinalizable { - USING_GARBAGE_COLLECTED_MIXIN(NeedsFinalizer); -public: - virtual void trace(Visitor*) override; -private: - Member<OnHeap> m_obj; -}; - -class HasFinalizer : public GarbageCollectedFinalized<HasFinalizer>, - public MixinFinalizable { - USING_GARBAGE_COLLECTED_MIXIN(HasFinalizer); -public: - virtual void trace(Visitor*) override; -private: - Member<OnHeap> m_obj; -}; - -class NeedsNoFinalization - : public GarbageCollected<NeedsNoFinalization> - , public MixinNotFinalizable { - USING_GARBAGE_COLLECTED_MIXIN(NeedsNoFinalization); -public: - virtual void trace(Visitor*) override; -private: - Member<OnHeap> m_obj; -}; - -} - -#endif
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/class_requires_finalization_mixin.txt b/tools/clang/blink_gc_plugin/tests/legacy_naming/class_requires_finalization_mixin.txt deleted file mode 100644 index 0bf93d5..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/class_requires_finalization_mixin.txt +++ /dev/null
@@ -1,8 +0,0 @@ -In file included from class_requires_finalization_mixin.cpp:5: -./class_requires_finalization_mixin.h:30:1: warning: [blink-gc] Class 'NeedsFinalizer' requires finalization. -class NeedsFinalizer -^ -./class_requires_finalization_mixin.h:32:7: note: [blink-gc] Base class 'MixinFinalizable' requiring finalization declared here: - , public MixinFinalizable { - ^ -1 warning generated.
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/class_requires_trace_method.cpp b/tools/clang/blink_gc_plugin/tests/legacy_naming/class_requires_trace_method.cpp deleted file mode 100644 index f18fdf6d..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/class_requires_trace_method.cpp +++ /dev/null
@@ -1,19 +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 "class_requires_trace_method.h" - -namespace blink { - -void Mixin2::trace(Visitor* visitor) -{ - Mixin::trace(visitor); -} - -void Mixin3::trace(Visitor* visitor) -{ - Mixin::trace(visitor); -} - -} // namespace blink
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/class_requires_trace_method.h b/tools/clang/blink_gc_plugin/tests/legacy_naming/class_requires_trace_method.h deleted file mode 100644 index 4a442b72..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/class_requires_trace_method.h +++ /dev/null
@@ -1,59 +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 CLASS_REQUIRES_TRACE_METHOD_H_ -#define CLASS_REQUIRES_TRACE_METHOD_H_ - -#include "heap/stubs.h" - -namespace blink { - -class HeapObject; - -class PartObject { - DISALLOW_NEW(); -private: - Member<HeapObject> m_obj; -}; - -class HeapObject : public GarbageCollected<HeapObject> { -private: - PartObject m_part; -}; - -class Mixin : public GarbageCollectedMixin { -public: - virtual void trace(Visitor*) override; - Member<Mixin> m_self; -}; - -class HeapObjectMixin : public GarbageCollected<HeapObjectMixin>, public Mixin { - USING_GARBAGE_COLLECTED_MIXIN(HeapObjectMixin); -}; - -class Mixin2 : public Mixin { -public: - virtual void trace(Visitor*) override; -}; - -class HeapObjectMixin2 - : public GarbageCollected<HeapObjectMixin2>, public Mixin2 { - USING_GARBAGE_COLLECTED_MIXIN(HeapObjectMixin2); -}; - -class Mixin3 : public Mixin { -public: - virtual void trace(Visitor*) override; -}; - -class HeapObjectMixin3 - : public GarbageCollected<HeapObjectMixin3>, public Mixin { - USING_GARBAGE_COLLECTED_MIXIN(HeapObjectMixin2); -public: - virtual void trace(Visitor*) override; -}; - -} - -#endif
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/class_requires_trace_method.txt b/tools/clang/blink_gc_plugin/tests/legacy_naming/class_requires_trace_method.txt deleted file mode 100644 index de6fd94..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/class_requires_trace_method.txt +++ /dev/null
@@ -1,14 +0,0 @@ -In file included from class_requires_trace_method.cpp:5: -./class_requires_trace_method.h:14:1: warning: [blink-gc] Class 'PartObject' requires a trace method. -class PartObject { -^ -./class_requires_trace_method.h:17:5: note: [blink-gc] Untraced field 'm_obj' declared here: - Member<HeapObject> m_obj; - ^ -./class_requires_trace_method.h:20:1: warning: [blink-gc] Class 'HeapObject' requires a trace method. -class HeapObject : public GarbageCollected<HeapObject> { -^ -./class_requires_trace_method.h:22:5: note: [blink-gc] Untraced field 'm_part' declared here: - PartObject m_part; - ^ -2 warnings generated.
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/class_requires_trace_method_tmpl.cpp b/tools/clang/blink_gc_plugin/tests/legacy_naming/class_requires_trace_method_tmpl.cpp deleted file mode 100644 index 7051fb2..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/class_requires_trace_method_tmpl.cpp +++ /dev/null
@@ -1,15 +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 "class_requires_trace_method_tmpl.h" - -namespace blink { - -// Does not need a trace method. -class NoTrace : public TemplatedObject<PartObjectA> { }; - -// Needs a trace method. -class NeedsTrace : public TemplatedObject<PartObjectB> { }; - -}
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/class_requires_trace_method_tmpl.h b/tools/clang/blink_gc_plugin/tests/legacy_naming/class_requires_trace_method_tmpl.h deleted file mode 100644 index 70cab61..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/class_requires_trace_method_tmpl.h +++ /dev/null
@@ -1,34 +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 CLASS_REQUIRES_TRACE_METHOD_TMPL_H_ -#define CLASS_REQUIRES_TRACE_METHOD_TMPL_H_ - -#include "heap/stubs.h" - -namespace blink { - -class HeapObject : public GarbageCollected<HeapObject> { }; - -class PartObjectA { - DISALLOW_NEW(); -}; - -class PartObjectB { - DISALLOW_NEW(); -public: - void trace(Visitor* visitor) { visitor->trace(m_obj); } -private: - Member<HeapObject> m_obj; -}; - -template<typename T> -class TemplatedObject { -private: - T m_part; -}; - -} - -#endif
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/class_requires_trace_method_tmpl.txt b/tools/clang/blink_gc_plugin/tests/legacy_naming/class_requires_trace_method_tmpl.txt deleted file mode 100644 index 49705b9..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/class_requires_trace_method_tmpl.txt +++ /dev/null
@@ -1,8 +0,0 @@ -In file included from class_requires_trace_method_tmpl.cpp:5: -./class_requires_trace_method_tmpl.h:27:1: warning: [blink-gc] Class 'TemplatedObject<blink::PartObjectB>' requires a trace method. -class TemplatedObject { -^ -./class_requires_trace_method_tmpl.h:29:5: note: [blink-gc] Untraced field 'm_part' declared here: - T m_part; - ^ -1 warning generated.
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/crash_on_invalid.cpp b/tools/clang/blink_gc_plugin/tests/legacy_naming/crash_on_invalid.cpp deleted file mode 100644 index 6370812e..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/crash_on_invalid.cpp +++ /dev/null
@@ -1,7 +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 "crash_on_invalid.h" - -// Nothing to define.
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/crash_on_invalid.h b/tools/clang/blink_gc_plugin/tests/legacy_naming/crash_on_invalid.h deleted file mode 100644 index a77d097..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/crash_on_invalid.h +++ /dev/null
@@ -1,26 +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. - -// Regression test for http://crbug.com/421958 - -#ifndef CRASH_ON_INVALID_H_ -#define CRASH_ON_INVALID_H_ - -namespace blink { - -class Visitor; -class GamepadCommon {}; -class ScriptWrappable {}; - -class Gamepad final : public GarbageCollectedFinalized<Gamepad>, - public GamepadCommon, - public ScriptWrappable { -public: - virtual const WrapperTypeInfo *wrapperTypeInfo() const {} - void trace(Visitor *); -}; - -} - -#endif
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/crash_on_invalid.txt b/tools/clang/blink_gc_plugin/tests/legacy_naming/crash_on_invalid.txt deleted file mode 100644 index cf19ff5..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/crash_on_invalid.txt +++ /dev/null
@@ -1,8 +0,0 @@ -In file included from crash_on_invalid.cpp:5: -./crash_on_invalid.h:16:30: error: unknown template name 'GarbageCollectedFinalized' -class Gamepad final : public GarbageCollectedFinalized<Gamepad>, - ^ -./crash_on_invalid.h:20:19: error: unknown type name 'WrapperTypeInfo' - virtual const WrapperTypeInfo *wrapperTypeInfo() const {} - ^ -2 errors generated.
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_ptrs.cpp b/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_ptrs.cpp deleted file mode 100644 index f3b39892..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_ptrs.cpp +++ /dev/null
@@ -1,17 +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 "cycle_ptrs.h" - -namespace blink { - -void A::trace(Visitor* visitor) { - visitor->trace(m_b); -} - -void B::trace(Visitor* visitor) { - visitor->trace(m_a); -} - -}
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_ptrs.flags b/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_ptrs.flags deleted file mode 100644 index a55c2f09..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_ptrs.flags +++ /dev/null
@@ -1 +0,0 @@ --Xclang -plugin-arg-blink-gc-plugin -Xclang dump-graph \ No newline at end of file
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_ptrs.h b/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_ptrs.h deleted file mode 100644 index 8c07a06..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_ptrs.h +++ /dev/null
@@ -1,54 +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 CYCLE_PTRS_H_ -#define CYCLE_PTRS_H_ - -#include "heap/stubs.h" - -namespace blink { - -class B; -class C; -class D; -class E; - -// This contains a leaking cycle: -// E -per-> A -mem-> B -ref-> C -own-> D -own-vec-> E - -// The traced cycle from A -> B -> A does not leak. - -class A : public GarbageCollected<A> { -public: - virtual void trace(Visitor*); -private: - Member<B> m_b; -}; - -class B : public GarbageCollectedFinalized<B> { -public: - virtual void trace(Visitor*); -private: - Member<A> m_a; - RefPtr<C> m_c; -}; - -class C : public RefCounted<C> { -private: - OwnPtr<D> m_d; -}; - -class D { -private: - Vector<OwnPtr<E> > m_es; -}; - -class E { -private: - Persistent<A> m_a; -}; - -} - -#endif
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_ptrs.txt b/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_ptrs.txt deleted file mode 100644 index 4d242a6..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_ptrs.txt +++ /dev/null
@@ -1,8 +0,0 @@ - -Found a potentially leaking cycle starting from a GC root: -./cycle_ptrs.h:49:5: blink::E (m_a) => blink::A -./cycle_ptrs.h:26:5: blink::A (m_b) => blink::B -./cycle_ptrs.h:34:5: blink::B (m_c) => blink::C -./cycle_ptrs.h:39:5: blink::C (m_d) => blink::D -./cycle_ptrs.h:44:5: blink::D (m_es) => blink::E -
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_sub.cpp b/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_sub.cpp deleted file mode 100644 index dfe835a..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_sub.cpp +++ /dev/null
@@ -1,14 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "cycle_sub.h" - -namespace blink { - -void B::trace(Visitor* visitor) { - visitor->trace(m_c); - A::trace(visitor); -} - -}
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_sub.flags b/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_sub.flags deleted file mode 100644 index a55c2f09..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_sub.flags +++ /dev/null
@@ -1 +0,0 @@ --Xclang -plugin-arg-blink-gc-plugin -Xclang dump-graph \ No newline at end of file
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_sub.h b/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_sub.h deleted file mode 100644 index a007061..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_sub.h +++ /dev/null
@@ -1,36 +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 CYCLE_SUB_H_ -#define CYCLE_SUB_H_ - -#include "heap/stubs.h" - -namespace blink { - -class C; - -// This contains a leaking cycle: -// C -per-> A -sub-> B -ref-> C - -class A : public GarbageCollectedFinalized<A> { -public: - virtual void trace(Visitor*) {} -}; - -class B : public A { -public: - virtual void trace(Visitor*); -private: - RefPtr<C> m_c; -}; - -class C : public RefCounted<C> { -private: - Persistent<A> m_a; -}; - -} - -#endif
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_sub.txt b/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_sub.txt deleted file mode 100644 index b37907d..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_sub.txt +++ /dev/null
@@ -1,6 +0,0 @@ - -Found a potentially leaking cycle starting from a GC root: -./cycle_sub.h:31:5: blink::C (m_a) => blink::A -./cycle_sub.h:22:11: blink::A (<subclass>) => blink::B -./cycle_sub.h:26:5: blink::B (m_c) => blink::C -
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super.cpp b/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super.cpp deleted file mode 100644 index d9ecd79..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super.cpp +++ /dev/null
@@ -1,21 +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 "cycle_super.h" - -namespace blink { - -void A::trace(Visitor* visitor) { - visitor->trace(m_d); -} - -void B::trace(Visitor* visitor) { - A::trace(visitor); -} - -void C::trace(Visitor* visitor) { - B::trace(visitor); -} - -}
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super.flags b/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super.flags deleted file mode 100644 index a55c2f09..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super.flags +++ /dev/null
@@ -1 +0,0 @@ --Xclang -plugin-arg-blink-gc-plugin -Xclang dump-graph \ No newline at end of file
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super.h b/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super.h deleted file mode 100644 index 13b05c12..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super.h +++ /dev/null
@@ -1,41 +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 CYCLE_SUPER_H_ -#define CYCLE_SUPER_H_ - -#include "heap/stubs.h" - -namespace blink { - -class D; - -// This contains a leaking cycle: -// D -per-> C -sup-> B -sup-> A -ref-> D - -class A : public GarbageCollectedFinalized<A> { -public: - virtual void trace(Visitor*); -private: - RefPtr<D> m_d; -}; - -class B : public A { -public: - virtual void trace(Visitor*); -}; - -class C : public B { -public: - virtual void trace(Visitor*); -}; - -class D : public RefCounted<C> { -private: - Persistent<C> m_c; -}; - -} - -#endif
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super.txt b/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super.txt deleted file mode 100644 index 89b3675..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super.txt +++ /dev/null
@@ -1,5 +0,0 @@ - -Found a potentially leaking cycle starting from a GC root: -./cycle_super.h:36:5: blink::D (m_c) => blink::C -./cycle_super.h:21:5: blink::C (blink::B <: blink::A <: m_d) => blink::D -
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.cpp b/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.cpp deleted file mode 100644 index 33dec59..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.cpp +++ /dev/null
@@ -1,18 +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 "cycle_super_neg.h" - -namespace blink { - -void B::trace(Visitor* visitor) { - A::trace(visitor); -} - -void D::trace(Visitor* visitor) { - visitor->trace(m_c); - A::trace(visitor); -} - -}
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.flags b/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.flags deleted file mode 100644 index a55c2f09..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.flags +++ /dev/null
@@ -1 +0,0 @@ --Xclang -plugin-arg-blink-gc-plugin -Xclang dump-graph \ No newline at end of file
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.h b/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.h deleted file mode 100644 index 6f99eff..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/cycle_super_neg.h +++ /dev/null
@@ -1,44 +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 CYCLE_SUPER_NEG_H_ -#define CYCLE_SUPER_NEG_H_ - -#include "heap/stubs.h" - -namespace blink { - -class C; - -// The chain: -// C -per-> B -sup-> A -sub-> D -ref-> C -// is not a leaking cycle, because the super-class relationship -// should not transitively imply sub-class relationships. -// I.e. B -/-> D - -class A : public GarbageCollectedFinalized<A> { -public: - virtual void trace(Visitor*) {} -}; - -class B : public A { -public: - virtual void trace(Visitor*); -}; - -class C : public RefCounted<C> { -private: - Persistent<B> m_b; -}; - -class D : public A { -public: - virtual void trace(Visitor*); -private: - RefPtr<C> m_c; -}; - -} - -#endif
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/delayed_parsing.cpp b/tools/clang/blink_gc_plugin/tests/legacy_naming/delayed_parsing.cpp deleted file mode 100644 index 149d95e..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/delayed_parsing.cpp +++ /dev/null
@@ -1,25 +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 "heap/stubs.h" - -namespace blink { - -struct HeapObject : public GarbageCollected<HeapObject> { - void trace(Visitor*) { } -}; - -template<typename T> -class TemplateBase - : public GarbageCollected<TemplateBase<T> > { -public: - void trace(Visitor* visitor) { visitor->trace(m_obj); } -private: - Member<HeapObject> m_obj; -}; - -class Subclass : public TemplateBase<Subclass> { -}; - -}
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/delayed_parsing.flags b/tools/clang/blink_gc_plugin/tests/legacy_naming/delayed_parsing.flags deleted file mode 100644 index 94af50f..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/delayed_parsing.flags +++ /dev/null
@@ -1 +0,0 @@ --fdelayed-template-parsing
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/delayed_parsing.txt b/tools/clang/blink_gc_plugin/tests/legacy_naming/delayed_parsing.txt deleted file mode 100644 index e69de29..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/delayed_parsing.txt +++ /dev/null
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/destructor_access_finalized_field.cpp b/tools/clang/blink_gc_plugin/tests/legacy_naming/destructor_access_finalized_field.cpp deleted file mode 100644 index b6bbfd2..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/destructor_access_finalized_field.cpp +++ /dev/null
@@ -1,35 +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 "destructor_access_finalized_field.h" - -namespace blink { - -HeapObject::~HeapObject() -{ - // Valid access to fields. - if (m_ref->foo() && !m_obj) { - m_objs.size(); - m_part.obj(); - } - - // Invalid access to fields. - bar(m_obj); - m_obj->foo(); - m_objs[0]; -} - -void HeapObject::trace(Visitor* visitor) -{ - visitor->trace(m_obj); - visitor->trace(m_objs); - visitor->trace(m_part); -} - -void PartOther::trace(Visitor* visitor) -{ - visitor->trace(m_obj); -} - -}
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/destructor_access_finalized_field.h b/tools/clang/blink_gc_plugin/tests/legacy_naming/destructor_access_finalized_field.h deleted file mode 100644 index 4c72156..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/destructor_access_finalized_field.h +++ /dev/null
@@ -1,45 +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 DESTRUCTOR_ACCESS_FINALIZED_FIELD_H_ -#define DESTRUCTOR_ACCESS_FINALIZED_FIELD_H_ - -#include "heap/stubs.h" - -namespace blink { - -class Other : public RefCounted<Other> { -public: - bool foo() { return true; } -}; - -class HeapObject; - -class PartOther { - ALLOW_ONLY_INLINE_ALLOCATION(); -public: - void trace(Visitor*); - - HeapObject* obj() { return m_obj; } - -private: - Member<HeapObject> m_obj; -}; - -class HeapObject : public GarbageCollectedFinalized<HeapObject> { -public: - ~HeapObject(); - void trace(Visitor*); - bool foo() { return true; } - void bar(HeapObject*) { } -private: - RefPtr<Other> m_ref; - Member<HeapObject> m_obj; - Vector<Member<HeapObject> > m_objs; - PartOther m_part; -}; - -} - -#endif
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/destructor_access_finalized_field.txt b/tools/clang/blink_gc_plugin/tests/legacy_naming/destructor_access_finalized_field.txt deleted file mode 100644 index 0470b51..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/destructor_access_finalized_field.txt +++ /dev/null
@@ -1,19 +0,0 @@ -destructor_access_finalized_field.cpp:18:9: warning: [blink-gc] Finalizer '~HeapObject' accesses potentially finalized field 'm_obj'. - bar(m_obj); - ^ -./destructor_access_finalized_field.h:38:5: note: [blink-gc] Potentially finalized field 'm_obj' declared here: - Member<HeapObject> m_obj; - ^ -destructor_access_finalized_field.cpp:19:5: warning: [blink-gc] Finalizer '~HeapObject' accesses potentially finalized field 'm_obj'. - m_obj->foo(); - ^ -./destructor_access_finalized_field.h:38:5: note: [blink-gc] Potentially finalized field 'm_obj' declared here: - Member<HeapObject> m_obj; - ^ -destructor_access_finalized_field.cpp:20:5: warning: [blink-gc] Finalizer '~HeapObject' accesses potentially finalized field 'm_objs'. - m_objs[0]; - ^ -./destructor_access_finalized_field.h:39:5: note: [blink-gc] Potentially finalized field 'm_objs' declared here: - Vector<Member<HeapObject> > m_objs; - ^ -3 warnings generated.
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/destructor_eagerly_finalized.cpp b/tools/clang/blink_gc_plugin/tests/legacy_naming/destructor_eagerly_finalized.cpp deleted file mode 100644 index 07409cc3..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/destructor_eagerly_finalized.cpp +++ /dev/null
@@ -1,37 +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 "destructor_eagerly_finalized.h" - -namespace blink { - -HeapObjectEagerFinalized::~HeapObjectEagerFinalized() -{ - // Valid access to a non-eagerly finalized field - m_obj->foo(); -} - -void HeapObjectEagerFinalized::trace(Visitor* visitor) -{ - visitor->trace(m_obj); -} - -HeapObjectEagerFinalizedAlso::~HeapObjectEagerFinalizedAlso() -{ - // Valid access to a non-eagerly finalized field - m_heapObject->foo(); - - // Non-valid accesses to eagerly finalized fields. - m_heapObjectFinalized->foo(); - m_heapVector[0]->foo(); -} - -void HeapObjectEagerFinalizedAlso::trace(Visitor* visitor) -{ - visitor->trace(m_heapObject); - visitor->trace(m_heapObjectFinalized); - visitor->trace(m_heapVector); -} - -} // namespace blink
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/destructor_eagerly_finalized.h b/tools/clang/blink_gc_plugin/tests/legacy_naming/destructor_eagerly_finalized.h deleted file mode 100644 index 77a29de..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/destructor_eagerly_finalized.h +++ /dev/null
@@ -1,47 +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 DESTRUCTOR_EAGERLY_FINALIZED_H_ -#define DESTRUCTOR_EAGERLY_FINALIZED_H_ - -#include "heap/stubs.h" - -namespace blink { - -class HeapObject : public GarbageCollected<HeapObject> { -public: - void trace(Visitor*) { } - void foo() { } -}; - -class HeapObjectEagerFinalized - : public GarbageCollectedFinalized<HeapObjectEagerFinalized> { -public: - EAGERLY_FINALIZED(); - ~HeapObjectEagerFinalized(); - void trace(Visitor*); - - void foo() { } - -private: - Member<HeapObject> m_obj; -}; - -// Accessing other eagerly finalized objects during finalization is not allowed. -class HeapObjectEagerFinalizedAlso - : public GarbageCollectedFinalized<HeapObjectEagerFinalizedAlso> { -public: - EAGERLY_FINALIZED(); - ~HeapObjectEagerFinalizedAlso(); - void trace(Visitor*); - -private: - Member<HeapObject> m_heapObject; - Member<HeapObjectEagerFinalized> m_heapObjectFinalized; - HeapVector<Member<HeapObjectEagerFinalized>> m_heapVector; -}; - -} // namespace blink - -#endif // DESTRUCTOR_EAGERLY_FINALIZED_H_
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/destructor_eagerly_finalized.txt b/tools/clang/blink_gc_plugin/tests/legacy_naming/destructor_eagerly_finalized.txt deleted file mode 100644 index 97d5089..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/destructor_eagerly_finalized.txt +++ /dev/null
@@ -1,13 +0,0 @@ -destructor_eagerly_finalized.cpp:26:5: warning: [blink-gc] Finalizer '~HeapObjectEagerFinalizedAlso' accesses eagerly finalized field 'm_heapObjectFinalized'. - m_heapObjectFinalized->foo(); - ^ -./destructor_eagerly_finalized.h:41:5: note: [blink-gc] Field 'm_heapObjectFinalized' having eagerly finalized value, declared here: - Member<HeapObjectEagerFinalized> m_heapObjectFinalized; - ^ -destructor_eagerly_finalized.cpp:27:5: warning: [blink-gc] Finalizer '~HeapObjectEagerFinalizedAlso' accesses eagerly finalized field 'm_heapVector'. - m_heapVector[0]->foo(); - ^ -./destructor_eagerly_finalized.h:42:5: note: [blink-gc] Field 'm_heapVector' having eagerly finalized value, declared here: - HeapVector<Member<HeapObjectEagerFinalized>> m_heapVector; - ^ -2 warnings generated.
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/destructor_in_nonfinalized_class.cpp b/tools/clang/blink_gc_plugin/tests/legacy_naming/destructor_in_nonfinalized_class.cpp deleted file mode 100644 index 8efc41d..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/destructor_in_nonfinalized_class.cpp +++ /dev/null
@@ -1,20 +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 "destructor_in_nonfinalized_class.h" - -namespace blink { - -HeapObject::~HeapObject() -{ - // Do something when destructed... - (void)this; -} - -void HeapObject::trace(Visitor* visitor) -{ - visitor->trace(m_obj); -} - -}
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/destructor_in_nonfinalized_class.h b/tools/clang/blink_gc_plugin/tests/legacy_naming/destructor_in_nonfinalized_class.h deleted file mode 100644 index f3fa506a..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/destructor_in_nonfinalized_class.h +++ /dev/null
@@ -1,22 +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 DESTRUCTOR_IN_NONFINALIZED_CLASS_H_ -#define DESTRUCTOR_IN_NONFINALIZED_CLASS_H_ - -#include "heap/stubs.h" - -namespace blink { - -class HeapObject : public GarbageCollected<HeapObject> { -public: - ~HeapObject(); - void trace(Visitor*); -private: - Member<HeapObject> m_obj; -}; - -} - -#endif
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/destructor_in_nonfinalized_class.txt b/tools/clang/blink_gc_plugin/tests/legacy_naming/destructor_in_nonfinalized_class.txt deleted file mode 100644 index cf19ea1..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/destructor_in_nonfinalized_class.txt +++ /dev/null
@@ -1,8 +0,0 @@ -In file included from destructor_in_nonfinalized_class.cpp:5: -./destructor_in_nonfinalized_class.h:12:1: warning: [blink-gc] Class 'HeapObject' requires finalization. -class HeapObject : public GarbageCollected<HeapObject> { -^ -destructor_in_nonfinalized_class.cpp:9:1: note: [blink-gc] User-declared destructor declared here: -HeapObject::~HeapObject() -^ -1 warning generated.
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/fields_illegal_tracing.cpp b/tools/clang/blink_gc_plugin/tests/legacy_naming/fields_illegal_tracing.cpp deleted file mode 100644 index b831077..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/fields_illegal_tracing.cpp +++ /dev/null
@@ -1,23 +0,0 @@ -// Copyright 2016 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "fields_illegal_tracing.h" - -namespace blink { - -void PartObject::trace(Visitor* visitor) { - visitor->trace(m_obj1); - visitor->trace(m_obj2); - visitor->trace(m_obj3); - visitor->trace(m_obj4); -} - -void HeapObject::trace(Visitor* visitor) { - visitor->trace(m_obj1); - visitor->trace(m_obj2); - visitor->trace(m_obj3); - visitor->trace(m_obj4); -} - -}
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/fields_illegal_tracing.h b/tools/clang/blink_gc_plugin/tests/legacy_naming/fields_illegal_tracing.h deleted file mode 100644 index f4d91dd2..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/fields_illegal_tracing.h +++ /dev/null
@@ -1,63 +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. - -#ifndef FIELDS_ILLEGAL_TRACING_H_ -#define FIELDS_ILLEGAL_TRACING_H_ - -#include "heap/stubs.h" - -namespace blink { - -namespace bar { - -// check that (only) std::unique_ptr<> is reported -// as an illegal smart pointer type. -template<typename T> class unique_ptr { -public: - ~unique_ptr() { } - operator T*() const { return 0; } - T* operator->() { return 0; } - - void trace(Visitor* visitor) - { - } -}; - -} - -class HeapObject; -class PartObject; - -class PartObject { - DISALLOW_NEW(); -public: - void trace(Visitor*); -private: - OwnPtr<HeapObject> m_obj1; - RefPtr<HeapObject> m_obj2; - bar::unique_ptr<HeapObject> m_obj3; - std::unique_ptr<HeapObject> m_obj4; - Vector<int>::iterator m_iterator1; - HeapVector<Member<HeapObject>>::iterator m_iterator2; - HeapHashSet<PartObject>::const_iterator m_iterator3; -}; - -class HeapObject : public GarbageCollectedFinalized<HeapObject> { -public: - void trace(Visitor*); -private: - PartObject m_part; - OwnPtr<HeapObject> m_obj1; - RefPtr<HeapObject> m_obj2; - bar::unique_ptr<HeapObject> m_obj3; - std::unique_ptr<HeapObject> m_obj4; - HeapHashMap<int, Member<HeapObject>>::reverse_iterator m_iterator3; - HeapDeque<Member<HeapObject>>::const_reverse_iterator m_iterator4; - HeapListHashSet<Member<HeapObject>>::const_iterator m_iterator5; - HeapLinkedHashSet<Member<HeapObject>>::const_iterator m_iterator6; -}; - -} - -#endif
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/fields_illegal_tracing.txt b/tools/clang/blink_gc_plugin/tests/legacy_naming/fields_illegal_tracing.txt deleted file mode 100644 index 874be1c..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/fields_illegal_tracing.txt +++ /dev/null
@@ -1,68 +0,0 @@ -In file included from fields_illegal_tracing.cpp:5: -./fields_illegal_tracing.h:32:1: warning: [blink-gc] Class 'PartObject' contains invalid fields. -class PartObject { -^ -./fields_illegal_tracing.h:37:5: note: [blink-gc] OwnPtr field 'm_obj1' to a GC managed class declared here: - OwnPtr<HeapObject> m_obj1; - ^ -./fields_illegal_tracing.h:38:5: note: [blink-gc] RefPtr field 'm_obj2' to a GC managed class declared here: - RefPtr<HeapObject> m_obj2; - ^ -./fields_illegal_tracing.h:40:5: note: [blink-gc] std::unique_ptr field 'm_obj4' to a GC managed class declared here: - std::unique_ptr<HeapObject> m_obj4; - ^ -./fields_illegal_tracing.h:42:5: warning: [blink-gc] Iterator field 'm_iterator2' to a GC managed collection declared here: - HeapVector<Member<HeapObject>>::iterator m_iterator2; - ^ -./fields_illegal_tracing.h:43:5: warning: [blink-gc] Iterator field 'm_iterator3' to a GC managed collection declared here: - HeapHashSet<PartObject>::const_iterator m_iterator3; - ^ -./fields_illegal_tracing.h:46:1: warning: [blink-gc] Class 'HeapObject' contains invalid fields. -class HeapObject : public GarbageCollectedFinalized<HeapObject> { -^ -./fields_illegal_tracing.h:51:5: note: [blink-gc] OwnPtr field 'm_obj1' to a GC managed class declared here: - OwnPtr<HeapObject> m_obj1; - ^ -./fields_illegal_tracing.h:52:5: note: [blink-gc] RefPtr field 'm_obj2' to a GC managed class declared here: - RefPtr<HeapObject> m_obj2; - ^ -./fields_illegal_tracing.h:54:5: note: [blink-gc] std::unique_ptr field 'm_obj4' to a GC managed class declared here: - std::unique_ptr<HeapObject> m_obj4; - ^ -./fields_illegal_tracing.h:55:5: warning: [blink-gc] Iterator field 'm_iterator3' to a GC managed collection declared here: - HeapHashMap<int, Member<HeapObject>>::reverse_iterator m_iterator3; - ^ -./fields_illegal_tracing.h:56:5: warning: [blink-gc] Iterator field 'm_iterator4' to a GC managed collection declared here: - HeapDeque<Member<HeapObject>>::const_reverse_iterator m_iterator4; - ^ -./fields_illegal_tracing.h:58:5: warning: [blink-gc] Iterator field 'm_iterator6' to a GC managed collection declared here: - HeapLinkedHashSet<Member<HeapObject>>::const_iterator m_iterator6; - ^ -fields_illegal_tracing.cpp:9:1: warning: [blink-gc] Class 'PartObject' has untraced or not traceable fields. -void PartObject::trace(Visitor* visitor) { -^ -./fields_illegal_tracing.h:37:5: note: [blink-gc] Untraceable field 'm_obj1' declared here: - OwnPtr<HeapObject> m_obj1; - ^ -./fields_illegal_tracing.h:38:5: note: [blink-gc] Untraceable field 'm_obj2' declared here: - RefPtr<HeapObject> m_obj2; - ^ -./fields_illegal_tracing.h:40:5: note: [blink-gc] Untraceable field 'm_obj4' declared here: - std::unique_ptr<HeapObject> m_obj4; - ^ -fields_illegal_tracing.cpp:16:1: warning: [blink-gc] Class 'HeapObject' has untraced or not traceable fields. -void HeapObject::trace(Visitor* visitor) { -^ -./fields_illegal_tracing.h:51:5: note: [blink-gc] Untraceable field 'm_obj1' declared here: - OwnPtr<HeapObject> m_obj1; - ^ -./fields_illegal_tracing.h:52:5: note: [blink-gc] Untraceable field 'm_obj2' declared here: - RefPtr<HeapObject> m_obj2; - ^ -./fields_illegal_tracing.h:54:5: note: [blink-gc] Untraceable field 'm_obj4' declared here: - std::unique_ptr<HeapObject> m_obj4; - ^ -./fields_illegal_tracing.h:57:5: note: [blink-gc] Untraced field 'm_iterator5' declared here: - HeapListHashSet<Member<HeapObject>>::const_iterator m_iterator5; - ^ -9 warnings generated.
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/fields_require_tracing.cpp b/tools/clang/blink_gc_plugin/tests/legacy_naming/fields_require_tracing.cpp deleted file mode 100644 index 880ce1e..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/fields_require_tracing.cpp +++ /dev/null
@@ -1,26 +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 "fields_require_tracing.h" - -namespace blink { - -void PartObject::trace(Visitor* visitor) { - m_obj1->trace(visitor); // Don't allow direct tracing. - visitor->trace(m_obj2); - // Missing visitor->trace(m_obj3); - visitor->trace(m_parts); -} - -void PartBObject::trace(Visitor* visitor) { - // Missing visitor->trace(m_set); - visitor->trace(m_vector); -} - -void HeapObject::trace(Visitor* visitor) { - // Missing visitor->trace(m_part); - visitor->trace(m_obj); -} - -}
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/fields_require_tracing.h b/tools/clang/blink_gc_plugin/tests/legacy_naming/fields_require_tracing.h deleted file mode 100644 index 1819411..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/fields_require_tracing.h +++ /dev/null
@@ -1,46 +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 FIELDS_REQUIRE_TRACING_H_ -#define FIELDS_REQUIRE_TRACING_H_ - -#include "heap/stubs.h" - -namespace blink { - -class HeapObject; -class PartObject; - -class PartBObject { - DISALLOW_NEW(); -public: - void trace(Visitor*); -private: - HeapHashSet<PartBObject> m_set; - HeapVector<PartBObject> m_vector; -}; - -class PartObject { - DISALLOW_NEW(); -public: - void trace(Visitor*); -private: - Member<HeapObject> m_obj1; - Member<HeapObject> m_obj2; - Member<HeapObject> m_obj3; - - HeapVector<PartBObject> m_parts; -}; - -class HeapObject : public GarbageCollected<HeapObject> { -public: - void trace(Visitor*); -private: - PartObject m_part; - Member<HeapObject> m_obj; -}; - -} - -#endif
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/fields_require_tracing.txt b/tools/clang/blink_gc_plugin/tests/legacy_naming/fields_require_tracing.txt deleted file mode 100644 index 39d49f3..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/fields_require_tracing.txt +++ /dev/null
@@ -1,22 +0,0 @@ -fields_require_tracing.cpp:9:1: warning: [blink-gc] Class 'PartObject' has untraced fields that require tracing. -void PartObject::trace(Visitor* visitor) { -^ -./fields_require_tracing.h:29:5: note: [blink-gc] Untraced field 'm_obj1' declared here: - Member<HeapObject> m_obj1; - ^ -./fields_require_tracing.h:31:5: note: [blink-gc] Untraced field 'm_obj3' declared here: - Member<HeapObject> m_obj3; - ^ -fields_require_tracing.cpp:16:1: warning: [blink-gc] Class 'PartBObject' has untraced fields that require tracing. -void PartBObject::trace(Visitor* visitor) { -^ -./fields_require_tracing.h:20:5: note: [blink-gc] Untraced field 'm_set' declared here: - HeapHashSet<PartBObject> m_set; - ^ -fields_require_tracing.cpp:21:1: warning: [blink-gc] Class 'HeapObject' has untraced fields that require tracing. -void HeapObject::trace(Visitor* visitor) { -^ -./fields_require_tracing.h:40:5: note: [blink-gc] Untraced field 'm_part' declared here: - PartObject m_part; - ^ -3 warnings generated.
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/finalize_after_dispatch.cpp b/tools/clang/blink_gc_plugin/tests/legacy_naming/finalize_after_dispatch.cpp deleted file mode 100644 index 91244d1..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/finalize_after_dispatch.cpp +++ /dev/null
@@ -1,63 +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 "finalize_after_dispatch.h" - -namespace blink { - -static B* toB(A* a) { return static_cast<B*>(a); } - -void A::trace(Visitor* visitor) -{ - switch (m_type) { - case TB: - toB(this)->traceAfterDispatch(visitor); - break; - case TC: - static_cast<C*>(this)->traceAfterDispatch(visitor); - break; - case TD: - static_cast<D*>(this)->traceAfterDispatch(visitor); - break; - } -} - -void A::traceAfterDispatch(Visitor* visitor) -{ -} - -void A::finalizeGarbageCollectedObject() -{ - switch (m_type) { - case TB: - toB(this)->~B(); - break; - case TC: - static_cast<C*>(this)->~C(); - break; - case TD: - // Missing static_cast<D*>(this)->~D(); - break; - } -} - -void B::traceAfterDispatch(Visitor* visitor) -{ - visitor->trace(m_a); - A::traceAfterDispatch(visitor); -} - -void C::traceAfterDispatch(Visitor* visitor) -{ - visitor->trace(m_a); - A::traceAfterDispatch(visitor); -} - -void D::traceAfterDispatch(Visitor* visitor) -{ - visitor->trace(m_a); - Abstract::traceAfterDispatch(visitor); -} - -}
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/finalize_after_dispatch.h b/tools/clang/blink_gc_plugin/tests/legacy_naming/finalize_after_dispatch.h deleted file mode 100644 index acd16ec..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/finalize_after_dispatch.h +++ /dev/null
@@ -1,78 +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 FINALIZE_AFTER_DISPATCH_H_ -#define FINALIZE_AFTER_DISPATCH_H_ - -#include "heap/stubs.h" - -namespace blink { - -class NeedsFinalize : public GarbageCollectedFinalized<NeedsFinalize> { -public: - void trace(Visitor*); - void traceAfterDispatch(Visitor*); - // Needs a finalizeGarbageCollectedObject method. -}; - -class NeedsDispatch : public GarbageCollectedFinalized<NeedsDispatch> { -public: - void trace(Visitor*); - // Needs a traceAfterDispatch method. - void finalizeGarbageCollectedObject() { }; -}; - -class NeedsFinalizedBase : public GarbageCollected<NeedsFinalizedBase> { -public: - void trace(Visitor*) { }; - void traceAfterDispatch(Visitor*) { }; - void finalizeGarbageCollectedObject() { }; -}; - -class A : GarbageCollectedFinalized<A> { -public: - void trace(Visitor*); - void traceAfterDispatch(Visitor*); - void finalizeGarbageCollectedObject(); -protected: - enum Type { TB, TC, TD }; - A(Type type) : m_type(type) { } -private: - Type m_type; -}; - -class B : public A { -public: - B() : A(TB) { } - ~B() { } - void traceAfterDispatch(Visitor*); -private: - Member<A> m_a; -}; - -class C : public A { -public: - C() : A(TC) { } - void traceAfterDispatch(Visitor*); -private: - Member<A> m_a; -}; - -// This class is considered abstract does not need to be dispatched to. -class Abstract : public A { -protected: - Abstract(Type type) : A(type) { } -}; - -class D : public Abstract { -public: - D() : Abstract(TD) { } - void traceAfterDispatch(Visitor*); -private: - Member<A> m_a; -}; - -} - -#endif
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/finalize_after_dispatch.txt b/tools/clang/blink_gc_plugin/tests/legacy_naming/finalize_after_dispatch.txt deleted file mode 100644 index 8a652a4..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/finalize_after_dispatch.txt +++ /dev/null
@@ -1,17 +0,0 @@ -In file included from finalize_after_dispatch.cpp:5: -./finalize_after_dispatch.h:12:1: warning: [blink-gc] Class 'NeedsFinalize' is missing manual finalize dispatch. -class NeedsFinalize : public GarbageCollectedFinalized<NeedsFinalize> { -^ -./finalize_after_dispatch.h:19:1: warning: [blink-gc] Class 'NeedsDispatch' is missing manual trace dispatch. -class NeedsDispatch : public GarbageCollectedFinalized<NeedsDispatch> { -^ -./finalize_after_dispatch.h:26:1: warning: [blink-gc] Class 'NeedsFinalizedBase' requires finalization. -class NeedsFinalizedBase : public GarbageCollected<NeedsFinalizedBase> { -^ -./finalize_after_dispatch.h:30:5: note: [blink-gc] User-declared finalizer declared here: - void finalizeGarbageCollectedObject() { }; - ^ -finalize_after_dispatch.cpp:30:1: warning: [blink-gc] Missing dispatch to class 'D' in manual finalize dispatch. -void A::finalizeGarbageCollectedObject() -^ -4 warnings generated.
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/garbage_collected_mixin.cpp b/tools/clang/blink_gc_plugin/tests/legacy_naming/garbage_collected_mixin.cpp deleted file mode 100644 index e8f42f2..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/garbage_collected_mixin.cpp +++ /dev/null
@@ -1,20 +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 "garbage_collected_mixin.h" - -namespace blink { - -void Mixin::trace(Visitor* visitor) -{ - // Missing: visitor->trace(m_self); -} - -void HeapObject::trace(Visitor* visitor) -{ - visitor->trace(m_mix); - // Missing: Mixin::trace(visitor); -} - -}
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/garbage_collected_mixin.h b/tools/clang/blink_gc_plugin/tests/legacy_naming/garbage_collected_mixin.h deleted file mode 100644 index 3c6f8686..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/garbage_collected_mixin.h +++ /dev/null
@@ -1,29 +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 GARBAGE_COLLECTED_MIXIN_H_ -#define GARBAGE_COLLECTED_MIXIN_H_ - -#include "heap/stubs.h" - -namespace blink { - -class Mixin : public GarbageCollectedMixin { -public: - virtual void trace(Visitor*) override; -private: - Member<Mixin> m_self; -}; - -class HeapObject : public GarbageCollected<HeapObject>, public Mixin { - USING_GARBAGE_COLLECTED_MIXIN(HeapObject); -public: - virtual void trace(Visitor*) override; -private: - Member<Mixin> m_mix; -}; - -} - -#endif
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/garbage_collected_mixin.txt b/tools/clang/blink_gc_plugin/tests/legacy_naming/garbage_collected_mixin.txt deleted file mode 100644 index 4051a6a0..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/garbage_collected_mixin.txt +++ /dev/null
@@ -1,10 +0,0 @@ -garbage_collected_mixin.cpp:9:1: warning: [blink-gc] Class 'Mixin' has untraced fields that require tracing. -void Mixin::trace(Visitor* visitor) -^ -./garbage_collected_mixin.h:16:5: note: [blink-gc] Untraced field 'm_self' declared here: - Member<Mixin> m_self; - ^ -garbage_collected_mixin.cpp:14:1: warning: [blink-gc] Base class 'Mixin' of derived class 'HeapObject' requires tracing. -void HeapObject::trace(Visitor* visitor) -^ -2 warnings generated.
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/heap/stubs.h b/tools/clang/blink_gc_plugin/tests/legacy_naming/heap/stubs.h deleted file mode 100644 index 2b965df..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/heap/stubs.h +++ /dev/null
@@ -1,311 +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 HEAP_STUBS_H_ -#define HEAP_STUBS_H_ - -#include "stddef.h" - -#define WTF_MAKE_FAST_ALLOCATED \ - public: \ - void* operator new(size_t, void* p); \ - void* operator new[](size_t, void* p); \ - void* operator new(size_t size); \ - private: \ - typedef int __thisIsHereToForceASemicolonAfterThisMacro - -namespace WTF { - -template<typename T> class RefCounted { }; - -template<typename T> class RawPtr { -public: - operator T*() const { return 0; } - T* operator->() { return 0; } -}; - -template<typename T> class RefPtr { -public: - ~RefPtr() { } - operator T*() const { return 0; } - T* operator->() { return 0; } -}; - -template<typename T> class OwnPtr { -public: - ~OwnPtr() { } - operator T*() const { return 0; } - T* operator->() { return 0; } -}; - -class DefaultAllocator { -public: - static const bool isGarbageCollected = false; -}; - -template<typename T> -struct VectorTraits { - static const bool needsDestruction = true; -}; - -template<size_t inlineCapacity, bool isGarbageCollected, bool tNeedsDestruction> -class VectorDestructorBase { -public: - ~VectorDestructorBase() {} -}; - -template<size_t inlineCapacity> -class VectorDestructorBase<inlineCapacity, true, false> {}; - -template<> -class VectorDestructorBase<0, true, true> {}; - -template< - typename T, - size_t inlineCapacity = 0, - typename Allocator = DefaultAllocator> -class Vector : public VectorDestructorBase<inlineCapacity, - Allocator::isGarbageCollected, - VectorTraits<T>::needsDestruction> { - public: - using iterator = T*; - using const_iterator = const T*; - using reverse_iterator = T*; - using const_reverse_iterator = const T*; - - size_t size(); - T& operator[](size_t); -}; - -template <typename T, - size_t inlineCapacity = 0, - typename Allocator = DefaultAllocator> -class Deque { - public: - using iterator = T*; - using const_iterator = const T*; - using reverse_iterator = T*; - using const_reverse_iterator = const T*; -}; - -template <typename ValueArg, - typename HashArg = void, - typename TraitsArg = void, - typename Allocator = DefaultAllocator> -class HashSet { - public: - typedef ValueArg* iterator; - typedef const ValueArg* const_iterator; - typedef ValueArg* reverse_iterator; - typedef const ValueArg* const_reverse_iterator; -}; - -template <typename ValueArg, - typename HashArg = void, - typename TraitsArg = void, - typename Allocator = DefaultAllocator> -class ListHashSet { - public: - typedef ValueArg* iterator; - typedef const ValueArg* const_iterator; - typedef ValueArg* reverse_iterator; - typedef const ValueArg* const_reverse_iterator; -}; - -template <typename ValueArg, - typename HashArg = void, - typename TraitsArg = void, - typename Allocator = DefaultAllocator> -class LinkedHashSet { - public: - typedef ValueArg* iterator; - typedef const ValueArg* const_iterator; - typedef ValueArg* reverse_iterator; - typedef const ValueArg* const_reverse_iterator; -}; - -template< - typename ValueArg, - typename HashArg = void, - typename TraitsArg = void, - typename Allocator = DefaultAllocator> -class HashCountedSet {}; - -template <typename KeyArg, - typename MappedArg, - typename HashArg = void, - typename KeyTraitsArg = void, - typename MappedTraitsArg = void, - typename Allocator = DefaultAllocator> -class HashMap { - public: - typedef MappedArg* iterator; - typedef const MappedArg* const_iterator; - typedef MappedArg* reverse_iterator; - typedef const MappedArg* const_reverse_iterator; -}; -} - -// Empty namespace declaration to exercise internal -// handling of namespace equality. -namespace std { - /* empty */ -} - -namespace std { - -template<typename T> class unique_ptr { -public: - ~unique_ptr() { } - operator T*() const { return 0; } - T* operator->() { return 0; } -}; - -} - -namespace blink { - -using namespace WTF; - -#define DISALLOW_NEW() \ - private: \ - void* operator new(size_t) = delete; \ - void* operator new(size_t, void*) = delete; - -#define STACK_ALLOCATED() \ - private: \ - __attribute__((annotate("blink_stack_allocated"))) \ - void* operator new(size_t) = delete; \ - void* operator new(size_t, void*) = delete; - -#define ALLOW_ONLY_INLINE_ALLOCATION() \ - public: \ - void* operator new(size_t, void*); \ - private: \ - void* operator new(size_t) = delete; - -#define GC_PLUGIN_IGNORE(bug) \ - __attribute__((annotate("blink_gc_plugin_ignore"))) - -#define USING_GARBAGE_COLLECTED_MIXIN(type) \ -public: \ - virtual void adjustAndMark(Visitor*) const override { } \ - virtual bool isHeapObjectAlive(Visitor*) const override { return 0; } - -#define EAGERLY_FINALIZED() typedef int IsEagerlyFinalizedMarker - -template<typename T> class GarbageCollected { }; - -template<typename T> -class GarbageCollectedFinalized : public GarbageCollected<T> { }; - -template<typename T> -class RefCountedGarbageCollected : public GarbageCollectedFinalized<T> { }; - -template<typename T> class Member { -public: - operator T*() const { return 0; } - T* operator->() { return 0; } - bool operator!() const { return false; } -}; - -template<typename T> class WeakMember { -public: - operator T*() const { return 0; } - T* operator->() { return 0; } - bool operator!() const { return false; } -}; - -template<typename T> class Persistent { -public: - operator T*() const { return 0; } - T* operator->() { return 0; } - bool operator!() const { return false; } -}; - -template<typename T> class WeakPersistent { -public: - operator T*() const { return 0; } - T* operator->() { return 0; } - bool operator!() const { return false; } -}; - -template<typename T> class CrossThreadPersistent { -public: - operator T*() const { return 0; } - T* operator->() { return 0; } - bool operator!() const { return false; } -}; - -template<typename T> class CrossThreadWeakPersistent { -public: - operator T*() const { return 0; } - T* operator->() { return 0; } - bool operator!() const { return false; } -}; - -class HeapAllocator { -public: - static const bool isGarbageCollected = true; -}; - -template<typename T, size_t inlineCapacity = 0> -class HeapVector : public Vector<T, inlineCapacity, HeapAllocator> { }; - -template<typename T, size_t inlineCapacity = 0> -class HeapDeque : public Vector<T, inlineCapacity, HeapAllocator> { }; - -template<typename T> -class HeapHashSet : public HashSet<T, void, void, HeapAllocator> { }; - -template<typename T> -class HeapListHashSet : public ListHashSet<T, void, void, HeapAllocator> { }; - -template<typename T> -class HeapLinkedHashSet : public LinkedHashSet<T, void, void, HeapAllocator> { -}; - -template<typename T> -class HeapHashCountedSet : public HashCountedSet<T, void, void, HeapAllocator> { -}; - -template<typename K, typename V> -class HeapHashMap : public HashMap<K, V, void, void, void, HeapAllocator> { }; - -template<typename T> -class PersistentHeapVector : public Vector<T, 0, HeapAllocator> { }; - -class Visitor { - public: - template <typename T, void (T::*method)(Visitor*)> - void registerWeakMembers(const T* obj); - - template <typename T> - void trace(const T&); -}; - -class GarbageCollectedMixin { -public: - virtual void adjustAndMark(Visitor*) const = 0; - virtual bool isHeapObjectAlive(Visitor*) const = 0; - virtual void trace(Visitor*) { } -}; - -template<typename T> -struct TraceIfNeeded { - static void trace(Visitor*, T*); -}; - -} - -namespace WTF { - -template<typename T> -struct VectorTraits<blink::Member<T> > { - static const bool needsDestruction = false; -}; - -} - -#endif
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/ignore_class.cpp b/tools/clang/blink_gc_plugin/tests/legacy_naming/ignore_class.cpp deleted file mode 100644 index c539eb6..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/ignore_class.cpp +++ /dev/null
@@ -1,20 +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 "ignore_class.h" - -namespace blink { - -void B::trace(Visitor* visitor) -{ - // Class is ignored so no checking here. -} - -void C::trace(Visitor* visitor) -{ - // Missing trace of m_obj. - // Ignored base class B does not need tracing. -} - -}
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/ignore_class.h b/tools/clang/blink_gc_plugin/tests/legacy_naming/ignore_class.h deleted file mode 100644 index 580ed7c..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/ignore_class.h +++ /dev/null
@@ -1,40 +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 IGNORE_CLASS_H_ -#define IGNORE_CLASS_H_ - -#include "heap/stubs.h" - -namespace blink { - -class HeapObject : public GarbageCollected<HeapObject> { }; - -// Don't require trace method on ignored class. -class GC_PLUGIN_IGNORE("http://crbug.com/12345") A; -class A : public GarbageCollected<A> { -private: - Member<HeapObject> m_obj; -}; - -// Don't require tracing of fields on ignored class. -class GC_PLUGIN_IGNORE("http://crbug.com/12345") B; -class B : public GarbageCollected<B> { -public: - virtual void trace(Visitor*); -private: - Member<HeapObject> m_obj; -}; - -// Don't require tracing of an ignored base class. -class C : public B { -public: - void trace(Visitor*); -private: - Member<HeapObject> m_obj; -}; - -} - -#endif
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/ignore_class.txt b/tools/clang/blink_gc_plugin/tests/legacy_naming/ignore_class.txt deleted file mode 100644 index d3d2d80..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/ignore_class.txt +++ /dev/null
@@ -1,7 +0,0 @@ -ignore_class.cpp:14:1: warning: [blink-gc] Class 'C' has untraced fields that require tracing. -void C::trace(Visitor* visitor) -^ -./ignore_class.h:35:5: note: [blink-gc] Untraced field 'm_obj' declared here: - Member<HeapObject> m_obj; - ^ -1 warning generated.
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/ignore_fields.cpp b/tools/clang/blink_gc_plugin/tests/legacy_naming/ignore_fields.cpp deleted file mode 100644 index 118af754..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/ignore_fields.cpp +++ /dev/null
@@ -1,15 +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 "ignore_fields.h" - -namespace blink { - -void C::trace(Visitor* visitor) -{ - // Missing trace of m_one. - // Not missing ignored field m_two. -} - -}
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/ignore_fields.h b/tools/clang/blink_gc_plugin/tests/legacy_naming/ignore_fields.h deleted file mode 100644 index e12bbab..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/ignore_fields.h +++ /dev/null
@@ -1,43 +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 IGNORE_FIELDS_H_ -#define IGNORE_FIELDS_H_ - -#include "heap/stubs.h" - -namespace blink { - -class HeapObject : public GarbageCollected<HeapObject> { -public: - virtual void trace(Visitor*) { } -}; - -// Don't warn about raw pointers to heap allocated objects. -class A : public GarbageCollected<A>{ -private: - GC_PLUGIN_IGNORE("http://crbug.com/12345") - HeapObject* m_obj; -}; - -// Don't require trace method when (all) GC fields are ignored. -class B : public GarbageCollected<B> { -private: - GC_PLUGIN_IGNORE("http://crbug.com/12345") - Member<HeapObject> m_one; -}; - -// Don't require tracing an ignored field. -class C : public GarbageCollected<C> { -public: - void trace(Visitor*); -private: - Member<HeapObject> m_one; - GC_PLUGIN_IGNORE("http://crbug.com/12345") - Member<HeapObject> m_two; -}; - -} - -#endif
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/ignore_fields.txt b/tools/clang/blink_gc_plugin/tests/legacy_naming/ignore_fields.txt deleted file mode 100644 index b4de4981..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/ignore_fields.txt +++ /dev/null
@@ -1,7 +0,0 @@ -ignore_fields.cpp:9:1: warning: [blink-gc] Class 'C' has untraced fields that require tracing. -void C::trace(Visitor* visitor) -^ -./ignore_fields.h:36:5: note: [blink-gc] Untraced field 'm_one' declared here: - Member<HeapObject> m_one; - ^ -1 warning generated.
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/inner_class.cpp b/tools/clang/blink_gc_plugin/tests/legacy_naming/inner_class.cpp deleted file mode 100644 index 03a53ea..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/inner_class.cpp +++ /dev/null
@@ -1,14 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "inner_class.h" - -namespace blink { - -void SomeObject::InnerObject::trace(Visitor* visitor) -{ - // Missing: visitor->trace(m_obj); -} - -}
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/inner_class.h b/tools/clang/blink_gc_plugin/tests/legacy_naming/inner_class.h deleted file mode 100644 index 30f6ce3..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/inner_class.h +++ /dev/null
@@ -1,24 +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 INNER_CLASS_H_ -#define INNER_CLASS_H_ - -#include "heap/stubs.h" - -namespace blink { - -class SomeObject { -private: - class InnerObject : public GarbageCollected<InnerObject> { - public: - void trace(Visitor*); - private: - Member<InnerObject> m_obj; - }; -}; - -} - -#endif
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/inner_class.txt b/tools/clang/blink_gc_plugin/tests/legacy_naming/inner_class.txt deleted file mode 100644 index acdef6e..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/inner_class.txt +++ /dev/null
@@ -1,7 +0,0 @@ -inner_class.cpp:9:1: warning: [blink-gc] Class 'InnerObject' has untraced fields that require tracing. -void SomeObject::InnerObject::trace(Visitor* visitor) -^ -./inner_class.h:18:9: note: [blink-gc] Untraced field 'm_obj' declared here: - Member<InnerObject> m_obj; - ^ -1 warning generated.
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/left_most_gc_base.cpp b/tools/clang/blink_gc_plugin/tests/legacy_naming/left_most_gc_base.cpp deleted file mode 100644 index 041d9f07..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/left_most_gc_base.cpp +++ /dev/null
@@ -1,7 +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 "left_most_gc_base.h" - -// Nothing to define.
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/left_most_gc_base.h b/tools/clang/blink_gc_plugin/tests/legacy_naming/left_most_gc_base.h deleted file mode 100644 index 0d76d61..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/left_most_gc_base.h +++ /dev/null
@@ -1,30 +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 LEFT_MOST_GC_BASE_H_ -#define LEFT_MOST_GC_BASE_H_ - -#include "heap/stubs.h" - -namespace blink { - -class A { }; -class B { }; - -class Right : public A, public B, public GarbageCollected<Right> { }; // Error -class Left : public GarbageCollected<Left>, public B, public A { }; - -class DerivedRight : public Right, public Left { }; // Error -class DerivedLeft : public Left, public Right { }; - -class C : public GarbageCollected<C> { -public: - virtual void trace(Visitor*); -}; - -class IllFormed : public A, public C { }; // Error - -} - -#endif
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/left_most_gc_base.txt b/tools/clang/blink_gc_plugin/tests/legacy_naming/left_most_gc_base.txt deleted file mode 100644 index e2d04186..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/left_most_gc_base.txt +++ /dev/null
@@ -1,14 +0,0 @@ -In file included from left_most_gc_base.cpp:5: -./left_most_gc_base.h:15:1: warning: [blink-gc] Class 'Right' must derive its GC base in the left-most position. -class Right : public A, public B, public GarbageCollected<Right> { }; // Error -^ -./left_most_gc_base.h:18:1: warning: [blink-gc] Class 'DerivedRight' must derive its GC base in the left-most position. -class DerivedRight : public Right, public Left { }; // Error -^ -./left_most_gc_base.h:12:1: warning: [blink-gc] Left-most base class 'A' of derived class 'IllFormed' must be polymorphic. -class A { }; -^ -./left_most_gc_base.h:26:1: warning: [blink-gc] Class 'IllFormed' must derive its GC base in the left-most position. -class IllFormed : public A, public C { }; // Error -^ -4 warnings generated.
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/member_in_offheap_class.cpp b/tools/clang/blink_gc_plugin/tests/legacy_naming/member_in_offheap_class.cpp deleted file mode 100644 index 4b44c2d..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/member_in_offheap_class.cpp +++ /dev/null
@@ -1,24 +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 "member_in_offheap_class.h" - -namespace blink { - -void OffHeapObject::trace(Visitor* visitor) -{ - visitor->trace(m_obj); -} - -void PartObject::trace(Visitor* visitor) -{ - visitor->trace(m_obj); -} - -void InlineObject::trace(Visitor* visitor) -{ - visitor->trace(m_obj); -} - -}
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/member_in_offheap_class.h b/tools/clang/blink_gc_plugin/tests/legacy_naming/member_in_offheap_class.h deleted file mode 100644 index 2a7c868..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/member_in_offheap_class.h +++ /dev/null
@@ -1,48 +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 MEMBER_IN_OFFHEAP_CLASS_H_ -#define MEMBER_IN_OFFHEAP_CLASS_H_ - -#include "heap/stubs.h" - -namespace blink { - -class HeapObject : public GarbageCollected<HeapObject> { }; - -class OffHeapObject { -public: - void trace(Visitor*); -private: - Member<HeapObject> m_obj; // Must not contain Member. - Persistent<HeapVector<Member<HeapObject> > > m_objs; // OK -}; - -class StackObject { - STACK_ALLOCATED(); -private: - Member<HeapObject> m_obj; // OK - Member<OffHeapObject> m_memberOff; // NOT OK - HeapVector<Member<OffHeapObject>> m_heapVectorMemberOff; // NOT OK -}; - -class PartObject { - DISALLOW_NEW(); -public: - void trace(Visitor*); -private: - Member<HeapObject> m_obj; // OK -}; - -class InlineObject { - ALLOW_ONLY_INLINE_ALLOCATION(); -public: - void trace(Visitor*); -private: - Member<HeapObject> m_obj; // OK -}; - -} - -#endif
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/member_in_offheap_class.txt b/tools/clang/blink_gc_plugin/tests/legacy_naming/member_in_offheap_class.txt deleted file mode 100644 index 9d5f2388..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/member_in_offheap_class.txt +++ /dev/null
@@ -1,17 +0,0 @@ -In file included from member_in_offheap_class.cpp:5: -./member_in_offheap_class.h:14:1: warning: [blink-gc] Class 'OffHeapObject' contains invalid fields. -class OffHeapObject { -^ -./member_in_offheap_class.h:18:5: note: [blink-gc] Member field 'm_obj' in unmanaged class declared here: - Member<HeapObject> m_obj; // Must not contain Member. - ^ -./member_in_offheap_class.h:22:1: warning: [blink-gc] Class 'StackObject' contains invalid fields. -class StackObject { -^ -./member_in_offheap_class.h:26:5: note: [blink-gc] Member field 'm_memberOff' to non-GC managed class declared here: - Member<OffHeapObject> m_memberOff; // NOT OK - ^ -./member_in_offheap_class.h:27:5: note: [blink-gc] Member field 'm_heapVectorMemberOff' to non-GC managed class declared here: - HeapVector<Member<OffHeapObject>> m_heapVectorMemberOff; // NOT OK - ^ -2 warnings generated.
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/non_virtual_trace.cpp b/tools/clang/blink_gc_plugin/tests/legacy_naming/non_virtual_trace.cpp deleted file mode 100644 index 9f57711..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/non_virtual_trace.cpp +++ /dev/null
@@ -1,23 +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 "non_virtual_trace.h" - -namespace blink { - -void A::trace(Visitor* visitor) -{ -} - -void C::trace(Visitor* visitor) -{ - B::trace(visitor); -} - -void D::trace(Visitor* visitor) -{ - B::trace(visitor); -} - -}
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/non_virtual_trace.h b/tools/clang/blink_gc_plugin/tests/legacy_naming/non_virtual_trace.h deleted file mode 100644 index 4179d49..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/non_virtual_trace.h +++ /dev/null
@@ -1,32 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef NON_VIRTUAL_TRACE_H_ -#define NON_VIRTUAL_TRACE_H_ - -#include "heap/stubs.h" - -namespace blink { - -class A : public GarbageCollected<A> { -public: - void trace(Visitor*); -}; - -class B : public A { -}; - -class C : public B { -public: - void trace(Visitor*); // Cannot override a non-virtual trace. -}; - -class D : public B { -public: - virtual void trace(Visitor*); // Cannot override a non-virtual trace. -}; - -} - -#endif
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/non_virtual_trace.txt b/tools/clang/blink_gc_plugin/tests/legacy_naming/non_virtual_trace.txt deleted file mode 100644 index a05a94d..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/non_virtual_trace.txt +++ /dev/null
@@ -1,17 +0,0 @@ -In file included from non_virtual_trace.cpp:5: -./non_virtual_trace.h:12:1: warning: [blink-gc] Left-most base class 'A' of derived class 'D' must define a virtual trace method. -class A : public GarbageCollected<A> { -^ -non_virtual_trace.cpp:13:1: warning: [blink-gc] Class 'C' overrides non-virtual trace of base class 'A'. -void C::trace(Visitor* visitor) -^ -./non_virtual_trace.h:14:5: note: [blink-gc] Non-virtual trace method declared here: - void trace(Visitor*); - ^ -non_virtual_trace.cpp:18:1: warning: [blink-gc] Class 'D' overrides non-virtual trace of base class 'A'. -void D::trace(Visitor* visitor) -^ -./non_virtual_trace.h:14:5: note: [blink-gc] Non-virtual trace method declared here: - void trace(Visitor*); - ^ -3 warnings generated.
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/own_ptr_to_gc_managed_class.cpp b/tools/clang/blink_gc_plugin/tests/legacy_naming/own_ptr_to_gc_managed_class.cpp deleted file mode 100644 index 9e27c3d..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/own_ptr_to_gc_managed_class.cpp +++ /dev/null
@@ -1,11 +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 "own_ptr_to_gc_managed_class.h" - -namespace blink { - -void HeapObject::trace(Visitor* visitor) { } - -}
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/own_ptr_to_gc_managed_class.h b/tools/clang/blink_gc_plugin/tests/legacy_naming/own_ptr_to_gc_managed_class.h deleted file mode 100644 index 6f47bafe..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/own_ptr_to_gc_managed_class.h +++ /dev/null
@@ -1,30 +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 OWN_PTR_TO_GC_MANAGED_CLASS_H_ -#define OWN_PTR_TO_GC_MANAGED_CLASS_H_ - -#include "heap/stubs.h" - -namespace blink { - -class HeapObject; - -class PartObject { - DISALLOW_NEW(); -private: - OwnPtr<HeapObject> m_obj; -}; - -class HeapObject : public GarbageCollectedFinalized<HeapObject> { -public: - void trace(Visitor*); -private: - Vector<OwnPtr<HeapObject> > m_objs; - OwnPtr<HeapVector<Member<HeapObject> > > m_objs2; -}; - -} - -#endif
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/own_ptr_to_gc_managed_class.txt b/tools/clang/blink_gc_plugin/tests/legacy_naming/own_ptr_to_gc_managed_class.txt deleted file mode 100644 index 4102e86..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/own_ptr_to_gc_managed_class.txt +++ /dev/null
@@ -1,17 +0,0 @@ -In file included from own_ptr_to_gc_managed_class.cpp:5: -./own_ptr_to_gc_managed_class.h:14:1: warning: [blink-gc] Class 'PartObject' contains invalid fields. -class PartObject { -^ -./own_ptr_to_gc_managed_class.h:17:5: note: [blink-gc] OwnPtr field 'm_obj' to a GC managed class declared here: - OwnPtr<HeapObject> m_obj; - ^ -./own_ptr_to_gc_managed_class.h:20:1: warning: [blink-gc] Class 'HeapObject' contains invalid fields. -class HeapObject : public GarbageCollectedFinalized<HeapObject> { -^ -./own_ptr_to_gc_managed_class.h:24:5: note: [blink-gc] OwnPtr field 'm_objs' to a GC managed class declared here: - Vector<OwnPtr<HeapObject> > m_objs; - ^ -./own_ptr_to_gc_managed_class.h:25:5: note: [blink-gc] OwnPtr field 'm_objs2' to a GC managed class declared here: - OwnPtr<HeapVector<Member<HeapObject> > > m_objs2; - ^ -2 warnings generated.
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/part_object_to_gc_derived_class.cpp b/tools/clang/blink_gc_plugin/tests/legacy_naming/part_object_to_gc_derived_class.cpp deleted file mode 100644 index 2da8661..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/part_object_to_gc_derived_class.cpp +++ /dev/null
@@ -1,14 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "part_object_to_gc_derived_class.h" - -namespace blink { - -void B::trace(Visitor* visitor) -{ - visitor->trace(m_a); -} - -}
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/part_object_to_gc_derived_class.h b/tools/clang/blink_gc_plugin/tests/legacy_naming/part_object_to_gc_derived_class.h deleted file mode 100644 index ef5a649..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/part_object_to_gc_derived_class.h +++ /dev/null
@@ -1,23 +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 PART_OBJECT_TO_GC_DERIVED_CLASS_H_ -#define PART_OBJECT_TO_GC_DERIVED_CLASS_H_ - -#include "heap/stubs.h" - -namespace blink { - -class A : public GarbageCollected<A> { }; - -class B : public GarbageCollected<B> { -public: - void trace(Visitor*); -private: - A m_a; -}; - -} - -#endif
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/part_object_to_gc_derived_class.txt b/tools/clang/blink_gc_plugin/tests/legacy_naming/part_object_to_gc_derived_class.txt deleted file mode 100644 index 5970132..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/part_object_to_gc_derived_class.txt +++ /dev/null
@@ -1,8 +0,0 @@ -In file included from part_object_to_gc_derived_class.cpp:5: -./part_object_to_gc_derived_class.h:14:1: warning: [blink-gc] Class 'B' contains invalid fields. -class B : public GarbageCollected<B> { -^ -./part_object_to_gc_derived_class.h:18:5: note: [blink-gc] Part-object field 'm_a' to a GC derived class declared here: - A m_a; - ^ -1 warning generated.
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/persistent_field_in_gc_managed_class.cpp b/tools/clang/blink_gc_plugin/tests/legacy_naming/persistent_field_in_gc_managed_class.cpp deleted file mode 100644 index 7b3f286..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/persistent_field_in_gc_managed_class.cpp +++ /dev/null
@@ -1,13 +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 "persistent_field_in_gc_managed_class.h" - -namespace blink { - -void HeapObject::trace(Visitor* visitor) { - visitor->trace(m_parts); -} - -}
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/persistent_field_in_gc_managed_class.h b/tools/clang/blink_gc_plugin/tests/legacy_naming/persistent_field_in_gc_managed_class.h deleted file mode 100644 index a90f63c..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/persistent_field_in_gc_managed_class.h +++ /dev/null
@@ -1,32 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef PERSISTENT_FIELD_IN_GC_MANAGED_CLASS_H_ -#define PERSISTENT_FIELD_IN_GC_MANAGED_CLASS_H_ - -#include "heap/stubs.h" - -namespace blink { - -class HeapObject; - -class PartObject { - DISALLOW_NEW(); -private: - Persistent<HeapObject> m_obj; -}; - -class HeapObject : public GarbageCollected<HeapObject> { -public: - void trace(Visitor*); -private: - PartObject m_part; - HeapVector<PartObject> m_parts; - PersistentHeapVector<Member<HeapObject> > m_objs; - WeakPersistent<HeapObject> m_weakPersistent; -}; - -} - -#endif
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/persistent_field_in_gc_managed_class.txt b/tools/clang/blink_gc_plugin/tests/legacy_naming/persistent_field_in_gc_managed_class.txt deleted file mode 100644 index dd5bc74..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/persistent_field_in_gc_managed_class.txt +++ /dev/null
@@ -1,32 +0,0 @@ -In file included from persistent_field_in_gc_managed_class.cpp:5: -./persistent_field_in_gc_managed_class.h:20:1: warning: [blink-gc] Class 'HeapObject' contains GC root in field 'm_part'. -class HeapObject : public GarbageCollected<HeapObject> { -^ -./persistent_field_in_gc_managed_class.h:24:5: note: [blink-gc] Field 'm_part' with embedded GC root in 'HeapObject' declared here: - PartObject m_part; - ^ -./persistent_field_in_gc_managed_class.h:17:5: note: [blink-gc] Field 'm_obj' defining a GC root declared here: - Persistent<HeapObject> m_obj; - ^ -./persistent_field_in_gc_managed_class.h:20:1: warning: [blink-gc] Class 'HeapObject' contains GC root in field 'm_parts'. -class HeapObject : public GarbageCollected<HeapObject> { -^ -./persistent_field_in_gc_managed_class.h:25:5: note: [blink-gc] Field 'm_parts' with embedded GC root in 'HeapObject' declared here: - HeapVector<PartObject> m_parts; - ^ -./persistent_field_in_gc_managed_class.h:17:5: note: [blink-gc] Field 'm_obj' defining a GC root declared here: - Persistent<HeapObject> m_obj; - ^ -./persistent_field_in_gc_managed_class.h:20:1: warning: [blink-gc] Class 'HeapObject' contains GC root in field 'm_objs'. -class HeapObject : public GarbageCollected<HeapObject> { -^ -./persistent_field_in_gc_managed_class.h:26:5: note: [blink-gc] Field 'm_objs' defining a GC root declared here: - PersistentHeapVector<Member<HeapObject> > m_objs; - ^ -./persistent_field_in_gc_managed_class.h:20:1: warning: [blink-gc] Class 'HeapObject' contains GC root in field 'm_weakPersistent'. -class HeapObject : public GarbageCollected<HeapObject> { -^ -./persistent_field_in_gc_managed_class.h:27:5: note: [blink-gc] Field 'm_weakPersistent' defining a GC root declared here: - WeakPersistent<HeapObject> m_weakPersistent; - ^ -4 warnings generated.
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/persistent_no_trace.cpp b/tools/clang/blink_gc_plugin/tests/legacy_naming/persistent_no_trace.cpp deleted file mode 100644 index 637b46f..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/persistent_no_trace.cpp +++ /dev/null
@@ -1,14 +0,0 @@ -// Copyright 2016 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "persistent_no_trace.h" - -namespace blink { - -void HeapObject::trace(Visitor* visitor) { - visitor->trace(m_crossThreadPersistent); - visitor->trace(m_crossThreadWeakPersistent); -} - -}
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/persistent_no_trace.h b/tools/clang/blink_gc_plugin/tests/legacy_naming/persistent_no_trace.h deleted file mode 100644 index c8beb996..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/persistent_no_trace.h +++ /dev/null
@@ -1,22 +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. - -#ifndef PERSISTENT_NO_TRACE_H_ -#define PERSISTENT_NO_TRACE_H_ - -#include "heap/stubs.h" - -namespace blink { - -class HeapObject : public GarbageCollected<HeapObject> { -public: - void trace(Visitor*); -private: - CrossThreadPersistent<HeapObject> m_crossThreadPersistent; - CrossThreadWeakPersistent<HeapObject> m_crossThreadWeakPersistent; -}; - -} - -#endif
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/persistent_no_trace.txt b/tools/clang/blink_gc_plugin/tests/legacy_naming/persistent_no_trace.txt deleted file mode 100644 index dcfe76d..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/persistent_no_trace.txt +++ /dev/null
@@ -1,10 +0,0 @@ -persistent_no_trace.cpp:9:1: warning: [blink-gc] Class 'HeapObject' has untraced or not traceable fields. -void HeapObject::trace(Visitor* visitor) { -^ -./persistent_no_trace.h:16:5: note: [blink-gc] Untraceable field 'm_crossThreadPersistent' declared here: - CrossThreadPersistent<HeapObject> m_crossThreadPersistent; - ^ -./persistent_no_trace.h:17:5: note: [blink-gc] Untraceable field 'm_crossThreadWeakPersistent' declared here: - CrossThreadWeakPersistent<HeapObject> m_crossThreadWeakPersistent; - ^ -1 warning generated.
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/polymorphic_class_with_non_virtual_trace.cpp b/tools/clang/blink_gc_plugin/tests/legacy_naming/polymorphic_class_with_non_virtual_trace.cpp deleted file mode 100644 index dc7620a..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/polymorphic_class_with_non_virtual_trace.cpp +++ /dev/null
@@ -1,19 +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 "polymorphic_class_with_non_virtual_trace.h" - -namespace blink { - -void IsLeftMostPolymorphic::trace(Visitor* visitor) -{ - visitor->trace(m_obj); -} - -void IsNotLeftMostPolymorphic::trace(Visitor* visitor) -{ - visitor->trace(m_obj); -} - -}
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/polymorphic_class_with_non_virtual_trace.h b/tools/clang/blink_gc_plugin/tests/legacy_naming/polymorphic_class_with_non_virtual_trace.h deleted file mode 100644 index f5d999eb..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/polymorphic_class_with_non_virtual_trace.h +++ /dev/null
@@ -1,61 +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 POLYMORPHIC_CLASS_WITH_NON_VIRTUAL_TRACE_H_ -#define POLYMORPHIC_CLASS_WITH_NON_VIRTUAL_TRACE_H_ - -#include "heap/stubs.h" - -namespace blink { - -class HeapObject : public GarbageCollected<HeapObject> { -public: - void trace(Visitor*) { } -}; - -class NonPolymorphicBase { -}; - -class PolymorphicBase { -public: - virtual void foo(); -}; - -class IsLeftMostPolymorphic - : public GarbageCollected<IsLeftMostPolymorphic>, - public PolymorphicBase { -public: - void trace(Visitor*); -private: - Member<HeapObject> m_obj; -}; - -class IsNotLeftMostPolymorphic - : public GarbageCollected<IsNotLeftMostPolymorphic>, - public NonPolymorphicBase, - public PolymorphicBase { -public: - void trace(Visitor*); -private: - Member<HeapObject> m_obj; -}; - -template<typename T> -class TemplatedNonPolymorphicBase - : public GarbageCollected<TemplatedNonPolymorphicBase<T> > { -public: - void trace(Visitor* visitor) { visitor->trace(m_obj); } -private: - Member<HeapObject> m_obj; -}; - -// Looks OK, but will result in an incorrect object pointer when marking. -class TemplatedIsNotLeftMostPolymorphic - : public TemplatedNonPolymorphicBase<TemplatedIsNotLeftMostPolymorphic>, - public PolymorphicBase { -}; - -} - -#endif
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/polymorphic_class_with_non_virtual_trace.txt b/tools/clang/blink_gc_plugin/tests/legacy_naming/polymorphic_class_with_non_virtual_trace.txt deleted file mode 100644 index 38f2e77..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/polymorphic_class_with_non_virtual_trace.txt +++ /dev/null
@@ -1,8 +0,0 @@ -In file included from polymorphic_class_with_non_virtual_trace.cpp:5: -./polymorphic_class_with_non_virtual_trace.h:17:1: warning: [blink-gc] Left-most base class 'NonPolymorphicBase' of derived class 'IsNotLeftMostPolymorphic' must be polymorphic. -class NonPolymorphicBase { -^ -./polymorphic_class_with_non_virtual_trace.h:45:1: warning: [blink-gc] Left-most base class 'TemplatedNonPolymorphicBase<blink::TemplatedIsNotLeftMostPolymorphic>' of derived class 'TemplatedIsNotLeftMostPolymorphic' must be polymorphic. -class TemplatedNonPolymorphicBase -^ -2 warnings generated.
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/pure_virtual_trace.cpp b/tools/clang/blink_gc_plugin/tests/legacy_naming/pure_virtual_trace.cpp deleted file mode 100644 index d993a326..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/pure_virtual_trace.cpp +++ /dev/null
@@ -1,7 +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 "pure_virtual_trace.h" - -// Nothing to define
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/pure_virtual_trace.h b/tools/clang/blink_gc_plugin/tests/legacy_naming/pure_virtual_trace.h deleted file mode 100644 index 356a95e..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/pure_virtual_trace.h +++ /dev/null
@@ -1,19 +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 PURE_VIRTUAL_TRACE_H_ -#define PURE_VIRTUAL_TRACE_H_ - -#include "heap/stubs.h" - -namespace blink { - -class A : public GarbageCollected<A> { -public: - virtual void trace(Visitor*) = 0; -}; - -} - -#endif
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/pure_virtual_trace.txt b/tools/clang/blink_gc_plugin/tests/legacy_naming/pure_virtual_trace.txt deleted file mode 100644 index 175a28a..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/pure_virtual_trace.txt +++ /dev/null
@@ -1,5 +0,0 @@ -In file included from pure_virtual_trace.cpp:5: -./pure_virtual_trace.h:14:5: warning: [blink-gc] Garbage collected class 'A' is not permitted to declare a pure-virtual trace method. - virtual void trace(Visitor*) = 0; - ^ -1 warning generated.
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/raw_ptr_to_gc_managed_class.cpp b/tools/clang/blink_gc_plugin/tests/legacy_naming/raw_ptr_to_gc_managed_class.cpp deleted file mode 100644 index 4d6cc05..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/raw_ptr_to_gc_managed_class.cpp +++ /dev/null
@@ -1,13 +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 "raw_ptr_to_gc_managed_class.h" - -namespace blink { - -void HeapObject::trace(Visitor* visitor) { - visitor->trace(m_objs); -} - -}
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/raw_ptr_to_gc_managed_class.h b/tools/clang/blink_gc_plugin/tests/legacy_naming/raw_ptr_to_gc_managed_class.h deleted file mode 100644 index 18fa9fa4..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/raw_ptr_to_gc_managed_class.h +++ /dev/null
@@ -1,33 +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 RAW_PTR_TO_GC_MANAGED_CLASS_H_ -#define RAW_PTR_TO_GC_MANAGED_CLASS_H_ - -#include "heap/stubs.h" - -namespace blink { - -class HeapObject; - -class PartObject { - DISALLOW_NEW(); -private: - PartObject(); - - HeapObject* m_rawObj; - HeapObject& m_refObj; -}; - -class HeapObject : public GarbageCollected<HeapObject> { -public: - void trace(Visitor*); -private: - PartObject m_part; - HeapVector<HeapObject*> m_objs; -}; - -} - -#endif
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/raw_ptr_to_gc_managed_class.txt b/tools/clang/blink_gc_plugin/tests/legacy_naming/raw_ptr_to_gc_managed_class.txt deleted file mode 100644 index 98f5abe8..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/raw_ptr_to_gc_managed_class.txt +++ /dev/null
@@ -1,17 +0,0 @@ -In file included from raw_ptr_to_gc_managed_class.cpp:5: -./raw_ptr_to_gc_managed_class.h:14:1: warning: [blink-gc] Class 'PartObject' contains invalid fields. -class PartObject { -^ -./raw_ptr_to_gc_managed_class.h:19:5: note: [blink-gc] Raw pointer field 'm_rawObj' to a GC managed class declared here: - HeapObject* m_rawObj; - ^ -./raw_ptr_to_gc_managed_class.h:20:5: note: [blink-gc] Reference pointer field 'm_refObj' to a GC managed class declared here: - HeapObject& m_refObj; - ^ -./raw_ptr_to_gc_managed_class.h:23:1: warning: [blink-gc] Class 'HeapObject' contains invalid fields. -class HeapObject : public GarbageCollected<HeapObject> { -^ -./raw_ptr_to_gc_managed_class.h:28:5: note: [blink-gc] Raw pointer field 'm_objs' to a GC managed class declared here: - HeapVector<HeapObject*> m_objs; - ^ -2 warnings generated.
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/raw_ptr_to_gc_managed_class_error.cpp b/tools/clang/blink_gc_plugin/tests/legacy_naming/raw_ptr_to_gc_managed_class_error.cpp deleted file mode 100644 index f71d1b8..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/raw_ptr_to_gc_managed_class_error.cpp +++ /dev/null
@@ -1,13 +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 "raw_ptr_to_gc_managed_class_error.h" - -namespace blink { - -void HeapObject::trace(Visitor* visitor) { - visitor->trace(m_objs); -} - -}
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/raw_ptr_to_gc_managed_class_error.flags b/tools/clang/blink_gc_plugin/tests/legacy_naming/raw_ptr_to_gc_managed_class_error.flags deleted file mode 100644 index 2f41be66..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/raw_ptr_to_gc_managed_class_error.flags +++ /dev/null
@@ -1 +0,0 @@ --Werror
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/raw_ptr_to_gc_managed_class_error.h b/tools/clang/blink_gc_plugin/tests/legacy_naming/raw_ptr_to_gc_managed_class_error.h deleted file mode 100644 index f4921c4..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/raw_ptr_to_gc_managed_class_error.h +++ /dev/null
@@ -1,33 +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 RAW_PTR_TO_GC_MANAGED_CLASS_ERROR_H_ -#define RAW_PTR_TO_GC_MANAGED_CLASS_ERROR_H_ - -#include "heap/stubs.h" - -namespace blink { - -class HeapObject; - -class PartObject { - DISALLOW_NEW(); -private: - PartObject(); - - HeapObject* m_rawObj; - HeapObject& m_refObj; -}; - -class HeapObject : public GarbageCollected<HeapObject> { -public: - void trace(Visitor*); -private: - PartObject m_part; - HeapVector<HeapObject*> m_objs; -}; - -} - -#endif
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/raw_ptr_to_gc_managed_class_error.txt b/tools/clang/blink_gc_plugin/tests/legacy_naming/raw_ptr_to_gc_managed_class_error.txt deleted file mode 100644 index c21c8172..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/raw_ptr_to_gc_managed_class_error.txt +++ /dev/null
@@ -1,17 +0,0 @@ -In file included from raw_ptr_to_gc_managed_class_error.cpp:5: -./raw_ptr_to_gc_managed_class_error.h:14:1: error: [blink-gc] Class 'PartObject' contains invalid fields. -class PartObject { -^ -./raw_ptr_to_gc_managed_class_error.h:19:5: note: [blink-gc] Raw pointer field 'm_rawObj' to a GC managed class declared here: - HeapObject* m_rawObj; - ^ -./raw_ptr_to_gc_managed_class_error.h:20:5: note: [blink-gc] Reference pointer field 'm_refObj' to a GC managed class declared here: - HeapObject& m_refObj; - ^ -./raw_ptr_to_gc_managed_class_error.h:23:1: error: [blink-gc] Class 'HeapObject' contains invalid fields. -class HeapObject : public GarbageCollected<HeapObject> { -^ -./raw_ptr_to_gc_managed_class_error.h:28:5: note: [blink-gc] Raw pointer field 'm_objs' to a GC managed class declared here: - HeapVector<HeapObject*> m_objs; - ^ -2 errors generated.
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/ref_ptr_to_gc_managed_class.cpp b/tools/clang/blink_gc_plugin/tests/legacy_naming/ref_ptr_to_gc_managed_class.cpp deleted file mode 100644 index e0a200f..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/ref_ptr_to_gc_managed_class.cpp +++ /dev/null
@@ -1,11 +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 "ref_ptr_to_gc_managed_class.h" - -namespace blink { - -void HeapObject::trace(Visitor*) { } - -}
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/ref_ptr_to_gc_managed_class.h b/tools/clang/blink_gc_plugin/tests/legacy_naming/ref_ptr_to_gc_managed_class.h deleted file mode 100644 index c3df7f8..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/ref_ptr_to_gc_managed_class.h +++ /dev/null
@@ -1,30 +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 REF_PTR_TO_GC_MANAGED_CLASS_H_ -#define REF_PTR_TO_GC_MANAGED_CLASS_H_ - -#include "heap/stubs.h" - -namespace blink { - -class HeapObject; - -class PartObject { - DISALLOW_NEW(); -private: - RefPtr<HeapObject> m_obj; -}; - -class HeapObject : public GarbageCollectedFinalized<HeapObject> { -public: - void trace(Visitor*); -private: - PartObject m_part; - Vector<RefPtr<HeapObject> > m_objs; -}; - -} - -#endif
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/ref_ptr_to_gc_managed_class.txt b/tools/clang/blink_gc_plugin/tests/legacy_naming/ref_ptr_to_gc_managed_class.txt deleted file mode 100644 index fd4978512..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/ref_ptr_to_gc_managed_class.txt +++ /dev/null
@@ -1,14 +0,0 @@ -In file included from ref_ptr_to_gc_managed_class.cpp:5: -./ref_ptr_to_gc_managed_class.h:14:1: warning: [blink-gc] Class 'PartObject' contains invalid fields. -class PartObject { -^ -./ref_ptr_to_gc_managed_class.h:17:5: note: [blink-gc] RefPtr field 'm_obj' to a GC managed class declared here: - RefPtr<HeapObject> m_obj; - ^ -./ref_ptr_to_gc_managed_class.h:20:1: warning: [blink-gc] Class 'HeapObject' contains invalid fields. -class HeapObject : public GarbageCollectedFinalized<HeapObject> { -^ -./ref_ptr_to_gc_managed_class.h:25:5: note: [blink-gc] RefPtr field 'm_objs' to a GC managed class declared here: - Vector<RefPtr<HeapObject> > m_objs; - ^ -2 warnings generated.
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/register_weak_members_template.cpp b/tools/clang/blink_gc_plugin/tests/legacy_naming/register_weak_members_template.cpp deleted file mode 100644 index 6742c22..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/register_weak_members_template.cpp +++ /dev/null
@@ -1,7 +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 "register_weak_members_template.h" - -// Nothing to define here.
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/register_weak_members_template.h b/tools/clang/blink_gc_plugin/tests/legacy_naming/register_weak_members_template.h deleted file mode 100644 index 4df3ade..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/register_weak_members_template.h +++ /dev/null
@@ -1,33 +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 REGISTER_WEAK_MEMBERS_TEMPLATE_H_ -#define REGISTER_WEAK_MEMBERS_TEMPLATE_H_ - -#include "heap/stubs.h" - -namespace blink { - -class X : public GarbageCollected<X> { - public: - void trace(Visitor*) {} -}; - -class HasUntracedWeakMembers : public GarbageCollected<HasUntracedWeakMembers> { - public: - void trace(Visitor* visitor) { - visitor->registerWeakMembers<HasUntracedWeakMembers, - &HasUntracedWeakMembers::clearWeakMembers>( - this); - } - - void clearWeakMembers(Visitor* visitor); - - private: - WeakMember<X> x_; -}; - -} - -#endif // REGISTER_WEAK_MEMBERS_TEMPLATE_H_
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/register_weak_members_template.txt b/tools/clang/blink_gc_plugin/tests/legacy_naming/register_weak_members_template.txt deleted file mode 100644 index b168673..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/register_weak_members_template.txt +++ /dev/null
@@ -1,8 +0,0 @@ -In file included from register_weak_members_template.cpp:5: -./register_weak_members_template.h:19:3: warning: [blink-gc] Class 'HasUntracedWeakMembers' has untraced fields that require tracing. - void trace(Visitor* visitor) { - ^ -./register_weak_members_template.h:28:3: note: [blink-gc] Untraced field 'x_' declared here: - WeakMember<X> x_; - ^ -1 warning generated.
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/stack_allocated.cpp b/tools/clang/blink_gc_plugin/tests/legacy_naming/stack_allocated.cpp deleted file mode 100644 index 3c4e321..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/stack_allocated.cpp +++ /dev/null
@@ -1,23 +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 "stack_allocated.h" - -namespace blink { - -// Verify that anon namespaces are checked. -namespace { - -class AnonStackObject : public StackObject { -public: - HeapObject* m_obj; -}; - -} - -void HeapObject::trace(Visitor* visitor) -{ -} - -}
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/stack_allocated.h b/tools/clang/blink_gc_plugin/tests/legacy_naming/stack_allocated.h deleted file mode 100644 index 22100ec..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/stack_allocated.h +++ /dev/null
@@ -1,54 +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 STACK_ALLOCATED_H_ -#define STACK_ALLOCATED_H_ - -#include "heap/stubs.h" - -namespace blink { - -class HeapObject; - -class PartObject { - DISALLOW_NEW(); -private: - Member<HeapObject> m_obj; // Needs tracing. -}; - -class StackObject { - STACK_ALLOCATED(); - - // Redundant trace() method, warning/error expected. - void trace(Visitor* visitor) { visitor->trace(m_obj); } - -private: - Member<HeapObject> m_obj; // Does not need tracing. -}; - -class HeapObject : public GarbageCollected<HeapObject> { -public: - void trace(Visitor*); -private: - StackObject m_part; // Cannot embed a stack allocated object. -}; - -// Cannot derive from both heap- and stack-allocated objects. -class DerivedHeapObject : public HeapObject, public StackObject { -}; - -// Cannot be stack-allocated and derive from a heap-allocated object. -class DerivedHeapObject2 : public HeapObject { - STACK_ALLOCATED(); -}; - -// STACK_ALLOCATED is inherited. -class DerivedStackObject : public StackObject { -private: - StackObject m_anotherPart; // Also fine. -}; - -} - -#endif
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/stack_allocated.txt b/tools/clang/blink_gc_plugin/tests/legacy_naming/stack_allocated.txt deleted file mode 100644 index 5eb6220..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/stack_allocated.txt +++ /dev/null
@@ -1,35 +0,0 @@ -In file included from stack_allocated.cpp:5: -./stack_allocated.h:14:1: warning: [blink-gc] Class 'PartObject' requires a trace method. -class PartObject { -^ -./stack_allocated.h:17:5: note: [blink-gc] Untraced field 'm_obj' declared here: - Member<HeapObject> m_obj; // Needs tracing. - ^ -./stack_allocated.h:24:5: warning: [blink-gc] The stack allocated class 'StackObject' provides an unnecessary trace method: - void trace(Visitor* visitor) { visitor->trace(m_obj); } - ^ -./stack_allocated.h:30:1: warning: [blink-gc] Class 'HeapObject' contains invalid fields. -class HeapObject : public GarbageCollected<HeapObject> { -^ -./stack_allocated.h:34:5: note: [blink-gc] Stack-allocated field 'm_part' declared here: - StackObject m_part; // Cannot embed a stack allocated object. - ^ -./stack_allocated.h:38:27: warning: [blink-gc] Stack-allocated class 'DerivedHeapObject' derives class 'HeapObject' which is garbage collected. -class DerivedHeapObject : public HeapObject, public StackObject { - ^ -./stack_allocated.h:42:28: warning: [blink-gc] Stack-allocated class 'DerivedHeapObject2' derives class 'HeapObject' which is garbage collected. -class DerivedHeapObject2 : public HeapObject { - ^ -./stack_allocated.h:43:3: warning: [blink-gc] Garbage collected class 'DerivedHeapObject2' is not permitted to override its new operator. - STACK_ALLOCATED(); - ^ -./heap/stubs.h:178:5: note: expanded from macro 'STACK_ALLOCATED' - __attribute__((annotate("blink_stack_allocated"))) \ - ^ -stack_allocated.cpp:12:1: warning: [blink-gc] Class 'AnonStackObject' contains invalid fields. -class AnonStackObject : public StackObject { -^ -stack_allocated.cpp:14:5: note: [blink-gc] Raw pointer field 'm_obj' to a GC managed class declared here: - HeapObject* m_obj; - ^ -7 warnings generated.
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/templated_class_with_local_class_requires_trace.cpp b/tools/clang/blink_gc_plugin/tests/legacy_naming/templated_class_with_local_class_requires_trace.cpp deleted file mode 100644 index bd8b737..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/templated_class_with_local_class_requires_trace.cpp +++ /dev/null
@@ -1,26 +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 "templated_class_with_local_class_requires_trace.h" - -namespace blink { - -template<typename T> -void TemplatedObject<T>::trace(Visitor* visitor) -{ - visitor->trace(m_local); - visitor->trace(m_memberRef); -} - -class Test { -public: - static void test() - { - HeapObject* obj = new HeapObject(); - TemplatedObject<HeapObject>* instance = - new TemplatedObject<HeapObject>(obj); - } -}; - -} // namespace blink
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/templated_class_with_local_class_requires_trace.h b/tools/clang/blink_gc_plugin/tests/legacy_naming/templated_class_with_local_class_requires_trace.h deleted file mode 100644 index d2b0225..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/templated_class_with_local_class_requires_trace.h +++ /dev/null
@@ -1,52 +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 TEMPLATED_CLASS_WITH_LOCAL_CLASS_REQUIRES_TRACE_H -#define TEMPLATED_CLASS_WITH_LOCAL_CLASS_REQUIRES_TRACE_H - -#include "heap/stubs.h" - -namespace blink { - -class NonHeapObject { }; - -class HeapObject : public GarbageCollected<HeapObject> { -public: - HeapObject() { } - - void trace(Visitor*) { } -}; - -template<typename T> -class TemplatedObject final - : public GarbageCollectedFinalized<TemplatedObject<T> > { -public: - TemplatedObject(T*) - { - } - - void trace(Visitor*); - -private: - class Local final : public GarbageCollected<Local> { - public: - void trace(Visitor* visitor) - { - visitor->trace(m_heapObject); - visitor->trace(m_object); - } - private: - Member<HeapObject> m_heapObject; - OwnPtr<HeapObject> m_object; - }; - - Member<Local> m_local; - Member<T> m_memberRef; - OwnPtr<T> m_ownRef; -}; - -} // namespace blink - -#endif // TEMPLATED_CLASS_WITH_LOCAL_CLASS_REQUIRES_TRACE_H -
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/templated_class_with_local_class_requires_trace.txt b/tools/clang/blink_gc_plugin/tests/legacy_naming/templated_class_with_local_class_requires_trace.txt deleted file mode 100644 index fa6b9f5..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/templated_class_with_local_class_requires_trace.txt +++ /dev/null
@@ -1,26 +0,0 @@ -In file included from templated_class_with_local_class_requires_trace.cpp:5: -./templated_class_with_local_class_requires_trace.h:22:1: warning: [blink-gc] Class 'TemplatedObject<blink::HeapObject>' contains invalid fields. -class TemplatedObject final -^ -./templated_class_with_local_class_requires_trace.h:46:5: note: [blink-gc] OwnPtr field 'm_ownRef' to a GC managed class declared here: - OwnPtr<T> m_ownRef; - ^ -./templated_class_with_local_class_requires_trace.h:32:5: warning: [blink-gc] Class 'Local' contains invalid fields. - class Local final : public GarbageCollected<Local> { - ^ -./templated_class_with_local_class_requires_trace.h:41:9: note: [blink-gc] OwnPtr field 'm_object' to a GC managed class declared here: - OwnPtr<HeapObject> m_object; - ^ -./templated_class_with_local_class_requires_trace.h:32:5: warning: [blink-gc] Class 'Local' requires finalization. - class Local final : public GarbageCollected<Local> { - ^ -./templated_class_with_local_class_requires_trace.h:41:9: note: [blink-gc] Field 'm_object' requiring finalization declared here: - OwnPtr<HeapObject> m_object; - ^ -./templated_class_with_local_class_requires_trace.h:34:9: warning: [blink-gc] Class 'Local' has untraced or not traceable fields. - void trace(Visitor* visitor) - ^ -./templated_class_with_local_class_requires_trace.h:41:9: note: [blink-gc] Untraceable field 'm_object' declared here: - OwnPtr<HeapObject> m_object; - ^ -4 warnings generated.
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/test.py b/tools/clang/blink_gc_plugin/tests/legacy_naming/test.py deleted file mode 100755 index 475f6fbf..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/test.py +++ /dev/null
@@ -1,66 +0,0 @@ -#!/usr/bin/env python -# 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. - -import argparse -import os -import subprocess -import sys - -script_dir = os.path.dirname(os.path.realpath(__file__)) -tool_dir = os.path.abspath(os.path.join(script_dir, '../../../pylib')) -sys.path.insert(0, tool_dir) - -from clang import plugin_testing - - -class BlinkGcPluginTest(plugin_testing.ClangPluginTest): - """Test harness for the Blink GC plugin.""" - - def AdjustClangArguments(self, clang_cmd): - clang_cmd.append('-Wno-inaccessible-base') - - def ProcessOneResult(self, test_name, actual): - # Some Blink GC plugins dump a JSON representation of the object graph, and - # use the processed results as the actual results of the test. - if os.path.exists('%s.graph.json' % test_name): - try: - actual = subprocess.check_output( - ['python', '../../process-graph.py', '-c', - '%s.graph.json' % test_name], - stderr=subprocess.STDOUT) - except subprocess.CalledProcessError, e: - # The graph processing script returns a failure exit code if the graph - # is bad (e.g. it has a cycle). The output still needs to be captured in - # that case, since the expected results capture the errors. - actual = e.output - finally: - # Clean up the .graph.json file to prevent false passes from stale - # results from a previous run. - os.remove('%s.graph.json' % test_name) - return super(BlinkGcPluginTest, self).ProcessOneResult(test_name, actual) - - -def main(): - parser = argparse.ArgumentParser() - parser.add_argument( - '--reset-results', - action='store_true', - help='If specified, overwrites the expected results in place.') - parser.add_argument('clang_path', help='The path to the clang binary.') - parser.add_argument('plugin_path', - nargs='?', - help='The path to the plugin library, if any.') - args = parser.parse_args() - - return BlinkGcPluginTest( - os.path.dirname(os.path.realpath(__file__)), - args.clang_path, - args.plugin_path, - 'blink-gc-plugin', - args.reset_results).Run() - - -if __name__ == '__main__': - sys.exit(main())
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/trace_after_dispatch.cpp b/tools/clang/blink_gc_plugin/tests/legacy_naming/trace_after_dispatch.cpp deleted file mode 100644 index c246aaaf..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/trace_after_dispatch.cpp +++ /dev/null
@@ -1,50 +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 "trace_after_dispatch.h" - -namespace blink { - -static B* toB(A* a) { return static_cast<B*>(a); } - -void A::trace(Visitor* visitor) -{ - switch (m_type) { - case TB: - toB(this)->traceAfterDispatch(visitor); - break; - case TC: - static_cast<C*>(this)->traceAfterDispatch(visitor); - break; - case TD: - // Missing static_cast<D*>(this)->traceAfterDispatch(visitor); - break; - } -} - -void A::traceAfterDispatch(Visitor* visitor) -{ -} - -void B::traceAfterDispatch(Visitor* visitor) -{ - visitor->trace(m_a); - // Missing A::traceAfterDispatch(visitor); - // Also check that calling trace does not count. - A::trace(visitor); -} - -void C::traceAfterDispatch(Visitor* visitor) -{ - // Missing visitor->trace(m_a); - A::traceAfterDispatch(visitor); -} - -void D::traceAfterDispatch(Visitor* visitor) -{ - visitor->trace(m_a); - Abstract::traceAfterDispatch(visitor); -} - -}
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/trace_after_dispatch.h b/tools/clang/blink_gc_plugin/tests/legacy_naming/trace_after_dispatch.h deleted file mode 100644 index a19a536..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/trace_after_dispatch.h +++ /dev/null
@@ -1,55 +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 TRACE_AFTER_DISPATCH_H_ -#define TRACE_AFTER_DISPATCH_H_ - -#include "heap/stubs.h" - -namespace blink { - -class A : public GarbageCollected<A> { -public: - void trace(Visitor*); - void traceAfterDispatch(Visitor*); -protected: - enum Type { TB, TC, TD }; - A(Type type) : m_type(type) { } -private: - Type m_type; -}; - -class B : public A { -public: - B() : A(TB) { } - void traceAfterDispatch(Visitor*); -private: - Member<A> m_a; -}; - -class C : public A { -public: - C() : A(TC) { } - void traceAfterDispatch(Visitor*); -private: - Member<A> m_a; -}; - -// This class is considered abstract does not need to be dispatched to. -class Abstract : public A { -protected: - Abstract(Type type) : A(type) { } -}; - -class D : public Abstract { -public: - D() : Abstract(TD) { } - void traceAfterDispatch(Visitor*); -private: - Member<A> m_a; -}; - -} - -#endif
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/trace_after_dispatch.txt b/tools/clang/blink_gc_plugin/tests/legacy_naming/trace_after_dispatch.txt deleted file mode 100644 index 877fbbe..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/trace_after_dispatch.txt +++ /dev/null
@@ -1,13 +0,0 @@ -trace_after_dispatch.cpp:11:1: warning: [blink-gc] Missing dispatch to class 'D' in manual trace dispatch. -void A::trace(Visitor* visitor) -^ -trace_after_dispatch.cpp:30:1: warning: [blink-gc] Base class 'A' of derived class 'B' requires tracing. -void B::traceAfterDispatch(Visitor* visitor) -^ -trace_after_dispatch.cpp:38:1: warning: [blink-gc] Class 'C' has untraced fields that require tracing. -void C::traceAfterDispatch(Visitor* visitor) -^ -./trace_after_dispatch.h:36:5: note: [blink-gc] Untraced field 'm_a' declared here: - Member<A> m_a; - ^ -3 warnings generated.
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/trace_after_dispatch_impl.cpp b/tools/clang/blink_gc_plugin/tests/legacy_naming/trace_after_dispatch_impl.cpp deleted file mode 100644 index ae5ec1e..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/trace_after_dispatch_impl.cpp +++ /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 "trace_after_dispatch_impl.h" - -namespace blink { - -void TraceAfterDispatchInlinedBase::trace(Visitor* visitor) { - // Implement a simple form of manual dispatching, because BlinkGCPlugin - // checks if the tracing is dispatched to all derived classes. - // - // This function has to be implemented out-of-line, since we need to know the - // definition of derived classes here. - if (tag_ == DERIVED) { - static_cast<TraceAfterDispatchInlinedDerived*>(this)->traceAfterDispatch( - visitor); - } else { - traceAfterDispatch(visitor); - } -} - -void TraceAfterDispatchExternBase::trace(Visitor* visitor) { - if (tag_ == DERIVED) { - static_cast<TraceAfterDispatchExternDerived*>(this)->traceAfterDispatch( - visitor); - } else { - traceAfterDispatch(visitor); - } -} - -void TraceAfterDispatchExternBase::traceAfterDispatch(Visitor* visitor) { - visitor->trace(x_base_); -} - -void TraceAfterDispatchExternDerived::traceAfterDispatch(Visitor* visitor) { - visitor->trace(x_derived_); - TraceAfterDispatchExternBase::traceAfterDispatch(visitor); -} - -}
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/trace_after_dispatch_impl.h b/tools/clang/blink_gc_plugin/tests/legacy_naming/trace_after_dispatch_impl.h deleted file mode 100644 index 3913f3ad..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/trace_after_dispatch_impl.h +++ /dev/null
@@ -1,72 +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 TRACE_AFTER_DISPATCH_IMPL_H_ -#define TRACE_AFTER_DISPATCH_IMPL_H_ - -#include "heap/stubs.h" - -namespace blink { - -class X : public GarbageCollected<X> { - public: - void trace(Visitor*) {} -}; - -enum ClassTag { - BASE, DERIVED -}; - -class TraceAfterDispatchInlinedBase - : public GarbageCollected<TraceAfterDispatchInlinedBase> { - public: - explicit TraceAfterDispatchInlinedBase(ClassTag tag) : tag_(tag) {} - - void trace(Visitor*); - void traceAfterDispatch(Visitor* visitor) { visitor->trace(x_base_); } - - private: - ClassTag tag_; - Member<X> x_base_; -}; - -class TraceAfterDispatchInlinedDerived : public TraceAfterDispatchInlinedBase { - public: - TraceAfterDispatchInlinedDerived() : TraceAfterDispatchInlinedBase(DERIVED) {} - - void traceAfterDispatch(Visitor* visitor) { - visitor->trace(x_derived_); - TraceAfterDispatchInlinedBase::traceAfterDispatch(visitor); - } - - private: - Member<X> x_derived_; -}; - -class TraceAfterDispatchExternBase - : public GarbageCollected<TraceAfterDispatchExternBase> { - public: - explicit TraceAfterDispatchExternBase(ClassTag tag) : tag_(tag) {} - - void trace(Visitor* visitor); - void traceAfterDispatch(Visitor* visitor); - - private: - ClassTag tag_; - Member<X> x_base_; -}; - -class TraceAfterDispatchExternDerived : public TraceAfterDispatchExternBase { - public: - TraceAfterDispatchExternDerived() : TraceAfterDispatchExternBase(DERIVED) {} - - void traceAfterDispatch(Visitor* visitor); - - private: - Member<X> x_derived_; -}; - -} - -#endif // TRACE_AFTER_DISPATCH_IMPL_H_
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/trace_after_dispatch_impl.txt b/tools/clang/blink_gc_plugin/tests/legacy_naming/trace_after_dispatch_impl.txt deleted file mode 100644 index e69de29..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/trace_after_dispatch_impl.txt +++ /dev/null
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/trace_after_dispatch_impl_error.cpp b/tools/clang/blink_gc_plugin/tests/legacy_naming/trace_after_dispatch_impl_error.cpp deleted file mode 100644 index 9157bc0..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/trace_after_dispatch_impl_error.cpp +++ /dev/null
@@ -1,42 +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 "trace_after_dispatch_impl_error.h" - -namespace blink { - -inline void TraceAfterDispatchInlinedBase::trace(Visitor* visitor) { - // Implement a simple form of manual dispatching, because BlinkGCPlugin - // checks if the tracing is dispatched to all derived classes. - // - // This function has to be implemented out-of-line, since we need to know the - // definition of derived classes here. - if (tag_ == DERIVED) { - // Missing dispatch call: - // static_cast<TraceAfterDispatchInlinedDerived*>(this)->traceAfterDispatch( - // visitor); - } else { - traceAfterDispatch(visitor); - } -} - -void TraceAfterDispatchExternBase::trace(Visitor* visitor) { - if (tag_ == DERIVED) { - // Missing dispatch call: - // static_cast<TraceAfterDispatchExternDerived*>(this)->traceAfterDispatch( - // visitor); - } else { - traceAfterDispatch(visitor); - } -} - -void TraceAfterDispatchExternBase::traceAfterDispatch(Visitor* visitor) { - // No trace call. -} - -void TraceAfterDispatchExternDerived::traceAfterDispatch(Visitor* visitor) { - // Ditto. -} - -}
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/trace_after_dispatch_impl_error.h b/tools/clang/blink_gc_plugin/tests/legacy_naming/trace_after_dispatch_impl_error.h deleted file mode 100644 index f9878f8..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/trace_after_dispatch_impl_error.h +++ /dev/null
@@ -1,74 +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 TRACE_AFTER_DISPATCH_IMPL_ERROR_H_ -#define TRACE_AFTER_DISPATCH_IMPL_ERROR_H_ - -#include "heap/stubs.h" - -namespace blink { - -class X : public GarbageCollected<X> { - public: - void trace(Visitor*) {} -}; - -enum ClassTag { - BASE, DERIVED -}; - -class TraceAfterDispatchInlinedBase - : public GarbageCollected<TraceAfterDispatchInlinedBase> { - public: - explicit TraceAfterDispatchInlinedBase(ClassTag tag) : tag_(tag) {} - - void trace(Visitor*); - - // No trace call; should get a warning. - void traceAfterDispatch(Visitor*) {} - - private: - ClassTag tag_; - Member<X> x_base_; -}; - -class TraceAfterDispatchInlinedDerived : public TraceAfterDispatchInlinedBase { - public: - TraceAfterDispatchInlinedDerived() : TraceAfterDispatchInlinedBase(DERIVED) {} - - void traceAfterDispatch(Visitor* visitor) { - // No trace call (for member and base class). - } - - private: - Member<X> x_derived_; -}; - -class TraceAfterDispatchExternBase - : public GarbageCollected<TraceAfterDispatchExternBase> { - public: - explicit TraceAfterDispatchExternBase(ClassTag tag) : tag_(tag) {} - - void trace(Visitor* visitor); - - void traceAfterDispatch(Visitor* visitor); - - private: - ClassTag tag_; - Member<X> x_base_; -}; - -class TraceAfterDispatchExternDerived : public TraceAfterDispatchExternBase { - public: - TraceAfterDispatchExternDerived() : TraceAfterDispatchExternBase(DERIVED) {} - - void traceAfterDispatch(Visitor* visitor); - - private: - Member<X> x_derived_; -}; - -} - -#endif // TRACE_AFTER_DISPATCH_IMPL_ERROR_H_
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/trace_after_dispatch_impl_error.txt b/tools/clang/blink_gc_plugin/tests/legacy_naming/trace_after_dispatch_impl_error.txt deleted file mode 100644 index 5cb7cac..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/trace_after_dispatch_impl_error.txt +++ /dev/null
@@ -1,34 +0,0 @@ -trace_after_dispatch_impl_error.cpp:9:1: warning: [blink-gc] Missing dispatch to class 'TraceAfterDispatchInlinedDerived' in manual trace dispatch. -inline void TraceAfterDispatchInlinedBase::trace(Visitor* visitor) { -^ -trace_after_dispatch_impl_error.cpp:24:1: warning: [blink-gc] Missing dispatch to class 'TraceAfterDispatchExternDerived' in manual trace dispatch. -void TraceAfterDispatchExternBase::trace(Visitor* visitor) { -^ -In file included from trace_after_dispatch_impl_error.cpp:5: -./trace_after_dispatch_impl_error.h:29:3: warning: [blink-gc] Class 'TraceAfterDispatchInlinedBase' has untraced fields that require tracing. - void traceAfterDispatch(Visitor*) {} - ^ -./trace_after_dispatch_impl_error.h:33:3: note: [blink-gc] Untraced field 'x_base_' declared here: - Member<X> x_base_; - ^ -./trace_after_dispatch_impl_error.h:40:3: warning: [blink-gc] Base class 'TraceAfterDispatchInlinedBase' of derived class 'TraceAfterDispatchInlinedDerived' requires tracing. - void traceAfterDispatch(Visitor* visitor) { - ^ -./trace_after_dispatch_impl_error.h:40:3: warning: [blink-gc] Class 'TraceAfterDispatchInlinedDerived' has untraced fields that require tracing. -./trace_after_dispatch_impl_error.h:45:3: note: [blink-gc] Untraced field 'x_derived_' declared here: - Member<X> x_derived_; - ^ -trace_after_dispatch_impl_error.cpp:34:1: warning: [blink-gc] Class 'TraceAfterDispatchExternBase' has untraced fields that require tracing. -void TraceAfterDispatchExternBase::traceAfterDispatch(Visitor* visitor) { -^ -./trace_after_dispatch_impl_error.h:59:3: note: [blink-gc] Untraced field 'x_base_' declared here: - Member<X> x_base_; - ^ -trace_after_dispatch_impl_error.cpp:38:1: warning: [blink-gc] Base class 'TraceAfterDispatchExternBase' of derived class 'TraceAfterDispatchExternDerived' requires tracing. -void TraceAfterDispatchExternDerived::traceAfterDispatch(Visitor* visitor) { -^ -trace_after_dispatch_impl_error.cpp:38:1: warning: [blink-gc] Class 'TraceAfterDispatchExternDerived' has untraced fields that require tracing. -./trace_after_dispatch_impl_error.h:69:3: note: [blink-gc] Untraced field 'x_derived_' declared here: - Member<X> x_derived_; - ^ -8 warnings generated.
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/trace_collections.cpp b/tools/clang/blink_gc_plugin/tests/legacy_naming/trace_collections.cpp deleted file mode 100644 index 9ba7c96..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/trace_collections.cpp +++ /dev/null
@@ -1,13 +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 "trace_collections.h" - -namespace blink { - -void HeapObject::trace(Visitor* visitor) -{ -} - -}
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/trace_collections.h b/tools/clang/blink_gc_plugin/tests/legacy_naming/trace_collections.h deleted file mode 100644 index 219b056..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/trace_collections.h +++ /dev/null
@@ -1,44 +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 TRACE_COLLECTIONS_H_ -#define TRACE_COLLECTIONS_H_ - -#include "heap/stubs.h" - -namespace blink { - -class HeapObject : public GarbageCollected<HeapObject> { -public: - void trace(Visitor*); -private: - HeapVector<Member<HeapObject> > m_heapVector; - Vector<Member<HeapObject>, 0, HeapAllocator> m_wtfVector; - - HeapDeque<Member<HeapObject> > m_heapDeque; - Deque<Member<HeapObject>, 0, HeapAllocator> m_wtfDeque; - - HeapHashSet<Member<HeapObject> > m_heapSet; - HashSet<Member<HeapObject>, void, HeapAllocator> m_wtfSet; - - HeapListHashSet<Member<HeapObject> > m_heapListSet; - ListHashSet<Member<HeapObject>, void, HeapAllocator> m_wtfListSet; - - HeapLinkedHashSet<Member<HeapObject> > m_heapLinkedSet; - LinkedHashSet<Member<HeapObject>, void, HeapAllocator> m_wtfLinkedSet; - - HeapHashCountedSet<Member<HeapObject> > m_heapCountedSet; - HashCountedSet<Member<HeapObject>, void, HeapAllocator> m_wtfCountedSet; - - HeapHashMap<int, Member<HeapObject> > m_heapMapKey; - HeapHashMap<Member<HeapObject>, int > m_heapMapVal; - HashMap<int, Member<HeapObject>, void, void, void, HeapAllocator> - m_wtfMapKey; - HashMap<Member<HeapObject>, int, void, void, void, HeapAllocator> - m_wtfMapVal; -}; - -} - -#endif
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/trace_collections.txt b/tools/clang/blink_gc_plugin/tests/legacy_naming/trace_collections.txt deleted file mode 100644 index 7c20ad4..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/trace_collections.txt +++ /dev/null
@@ -1,52 +0,0 @@ -trace_collections.cpp:9:1: warning: [blink-gc] Class 'HeapObject' has untraced fields that require tracing. -void HeapObject::trace(Visitor* visitor) -^ -./trace_collections.h:16:5: note: [blink-gc] Untraced field 'm_heapVector' declared here: - HeapVector<Member<HeapObject> > m_heapVector; - ^ -./trace_collections.h:17:5: note: [blink-gc] Untraced field 'm_wtfVector' declared here: - Vector<Member<HeapObject>, 0, HeapAllocator> m_wtfVector; - ^ -./trace_collections.h:19:5: note: [blink-gc] Untraced field 'm_heapDeque' declared here: - HeapDeque<Member<HeapObject> > m_heapDeque; - ^ -./trace_collections.h:20:5: note: [blink-gc] Untraced field 'm_wtfDeque' declared here: - Deque<Member<HeapObject>, 0, HeapAllocator> m_wtfDeque; - ^ -./trace_collections.h:22:5: note: [blink-gc] Untraced field 'm_heapSet' declared here: - HeapHashSet<Member<HeapObject> > m_heapSet; - ^ -./trace_collections.h:23:5: note: [blink-gc] Untraced field 'm_wtfSet' declared here: - HashSet<Member<HeapObject>, void, HeapAllocator> m_wtfSet; - ^ -./trace_collections.h:25:5: note: [blink-gc] Untraced field 'm_heapListSet' declared here: - HeapListHashSet<Member<HeapObject> > m_heapListSet; - ^ -./trace_collections.h:26:5: note: [blink-gc] Untraced field 'm_wtfListSet' declared here: - ListHashSet<Member<HeapObject>, void, HeapAllocator> m_wtfListSet; - ^ -./trace_collections.h:28:5: note: [blink-gc] Untraced field 'm_heapLinkedSet' declared here: - HeapLinkedHashSet<Member<HeapObject> > m_heapLinkedSet; - ^ -./trace_collections.h:29:5: note: [blink-gc] Untraced field 'm_wtfLinkedSet' declared here: - LinkedHashSet<Member<HeapObject>, void, HeapAllocator> m_wtfLinkedSet; - ^ -./trace_collections.h:31:5: note: [blink-gc] Untraced field 'm_heapCountedSet' declared here: - HeapHashCountedSet<Member<HeapObject> > m_heapCountedSet; - ^ -./trace_collections.h:32:5: note: [blink-gc] Untraced field 'm_wtfCountedSet' declared here: - HashCountedSet<Member<HeapObject>, void, HeapAllocator> m_wtfCountedSet; - ^ -./trace_collections.h:34:5: note: [blink-gc] Untraced field 'm_heapMapKey' declared here: - HeapHashMap<int, Member<HeapObject> > m_heapMapKey; - ^ -./trace_collections.h:35:5: note: [blink-gc] Untraced field 'm_heapMapVal' declared here: - HeapHashMap<Member<HeapObject>, int > m_heapMapVal; - ^ -./trace_collections.h:36:5: note: [blink-gc] Untraced field 'm_wtfMapKey' declared here: - HashMap<int, Member<HeapObject>, void, void, void, HeapAllocator> - ^ -./trace_collections.h:38:5: note: [blink-gc] Untraced field 'm_wtfMapVal' declared here: - HashMap<Member<HeapObject>, int, void, void, void, HeapAllocator> - ^ -1 warning generated.
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/trace_if_needed.cpp b/tools/clang/blink_gc_plugin/tests/legacy_naming/trace_if_needed.cpp deleted file mode 100644 index 563c6cc1..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/trace_if_needed.cpp +++ /dev/null
@@ -1,16 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "trace_if_needed.h" - -namespace blink { - -template<typename T> -void TemplatedObject<T>::trace(Visitor* visitor) -{ - TraceIfNeeded<T>::trace(visitor, &m_one); - // Missing trace of m_two -} - -}
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/trace_if_needed.h b/tools/clang/blink_gc_plugin/tests/legacy_naming/trace_if_needed.h deleted file mode 100644 index 00b8f22..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/trace_if_needed.h +++ /dev/null
@@ -1,27 +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 TRACE_IF_NEEDED_H_ -#define TRACE_IF_NEEDED_H_ - -#include "heap/stubs.h" - -namespace blink { - -class HeapObject : public GarbageCollected<HeapObject> { }; - -template<typename T> -class TemplatedObject : public GarbageCollected<TemplatedObject<T> > { -public: - virtual void trace(Visitor*); -private: - T m_one; - T m_two; -}; - -class InstantiatedObject : public TemplatedObject<Member<HeapObject> > { }; - -} - -#endif
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/trace_if_needed.txt b/tools/clang/blink_gc_plugin/tests/legacy_naming/trace_if_needed.txt deleted file mode 100644 index 79a24e8..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/trace_if_needed.txt +++ /dev/null
@@ -1,7 +0,0 @@ -trace_if_needed.cpp:9:1: warning: [blink-gc] Class 'TemplatedObject<blink::Member<blink::HeapObject> >' has untraced fields that require tracing. -template<typename T> -^ -./trace_if_needed.h:20:5: note: [blink-gc] Untraced field 'm_two' declared here: - T m_two; - ^ -1 warning generated.
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/trace_templated_super.cpp b/tools/clang/blink_gc_plugin/tests/legacy_naming/trace_templated_super.cpp deleted file mode 100644 index 2b59034..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/trace_templated_super.cpp +++ /dev/null
@@ -1,36 +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 "trace_templated_super.h" - -namespace blink { - -template<typename T> -void Super<T>::clearWeakMembers(Visitor* visitor) -{ - (void)m_weak; -} - -template<typename T> -void Super<T>::trace(Visitor* visitor) -{ - visitor->registerWeakMembers<Super<T>, &Super<T>::clearWeakMembers>(this); - visitor->trace(m_obj); - Mixin::trace(visitor); -} - -template<typename T> -void Sub<T>::trace(Visitor* visitor) -{ - // Missing trace of m_obj. - Super<T>::trace(visitor); -} - -void HeapObject::trace(Visitor* visitor) -{ - visitor->trace(m_obj); - Sub<HeapObject>::trace(visitor); -} - -}
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/trace_templated_super.h b/tools/clang/blink_gc_plugin/tests/legacy_naming/trace_templated_super.h deleted file mode 100644 index de8fd7b..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/trace_templated_super.h +++ /dev/null
@@ -1,47 +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 TRACE_TEMPLATED_SUPER_H_ -#define TRACE_TEMPLATED_SUPER_H_ - -#include "heap/stubs.h" - -namespace blink { - -class HeapObject; - -class Mixin : public GarbageCollectedMixin { -public: - virtual void trace(Visitor*) override { } -}; - -template<typename T> -class Super : public GarbageCollected<Super<T> >, public Mixin { - USING_GARBAGE_COLLECTED_MIXIN(Super); -public: - virtual void trace(Visitor*) override; - void clearWeakMembers(Visitor*); -private: - Member<HeapObject> m_obj; - WeakMember<HeapObject> m_weak; -}; - -template<typename T> -class Sub : public Super<T> { -public: - virtual void trace(Visitor* visitor) override; -private: - Member<HeapObject> m_obj; -}; - -class HeapObject : public Sub<HeapObject> { -public: - virtual void trace(Visitor*) override; -private: - Member<HeapObject> m_obj; -}; - -} - -#endif
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/trace_templated_super.txt b/tools/clang/blink_gc_plugin/tests/legacy_naming/trace_templated_super.txt deleted file mode 100644 index 291b018..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/trace_templated_super.txt +++ /dev/null
@@ -1,7 +0,0 @@ -trace_templated_super.cpp:23:1: warning: [blink-gc] Class 'Sub<blink::HeapObject>' has untraced fields that require tracing. -template<typename T> -^ -./trace_templated_super.h:35:5: note: [blink-gc] Untraced field 'm_obj' declared here: - Member<HeapObject> m_obj; - ^ -1 warning generated.
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/traceimpl.cpp b/tools/clang/blink_gc_plugin/tests/legacy_naming/traceimpl.cpp deleted file mode 100644 index a5f3a7a4..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/traceimpl.cpp +++ /dev/null
@@ -1,18 +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 "traceimpl.h" - -namespace blink { - -void TraceImplExtern::trace(Visitor* visitor) { - visitor->trace(x_); -} - -void TraceImplBaseExtern::trace(Visitor* visitor) { - visitor->trace(x_); - Base::trace(visitor); -} - -}
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/traceimpl.h b/tools/clang/blink_gc_plugin/tests/legacy_naming/traceimpl.h deleted file mode 100644 index 57f69c6f..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/traceimpl.h +++ /dev/null
@@ -1,53 +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 TRACEIMPL_H_ -#define TRACEIMPL_H_ - -#include "heap/stubs.h" - -namespace blink { - -class X : public GarbageCollected<X> { - public: - virtual void trace(Visitor*) {} -}; - -class TraceImplInlined : public GarbageCollected<TraceImplInlined> { - public: - void trace(Visitor* visitor) { visitor->trace(x_); } - - private: - Member<X> x_; -}; - -class TraceImplExtern : public GarbageCollected<TraceImplExtern> { - public: - void trace(Visitor* visitor); - - private: - Member<X> x_; -}; - -class Base : public GarbageCollected<Base> { - public: - virtual void trace(Visitor* visitor) {} -}; - -class TraceImplBaseInlined : public Base { - public: - void trace(Visitor* visitor) override { Base::trace(visitor); } -}; - -class TraceImplBaseExtern : public Base { - public: - void trace(Visitor* visitor) override; - - private: - Member<X> x_; -}; - -} - -#endif
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/traceimpl.txt b/tools/clang/blink_gc_plugin/tests/legacy_naming/traceimpl.txt deleted file mode 100644 index e69de29..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/traceimpl.txt +++ /dev/null
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/traceimpl_dependent_scope.cpp b/tools/clang/blink_gc_plugin/tests/legacy_naming/traceimpl_dependent_scope.cpp deleted file mode 100644 index 11b576c..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/traceimpl_dependent_scope.cpp +++ /dev/null
@@ -1,13 +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 "traceimpl_dependent_scope.h" - -namespace blink { - -// Template instantiation. -template class Derived<int>; -template class DerivedMissingTrace<int>; - -}
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/traceimpl_dependent_scope.h b/tools/clang/blink_gc_plugin/tests/legacy_naming/traceimpl_dependent_scope.h deleted file mode 100644 index d0a723b..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/traceimpl_dependent_scope.h +++ /dev/null
@@ -1,39 +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 TRACEIMPL_DEPENDENT_SCOPE_H_ -#define TRACEIMPL_DEPENDENT_SCOPE_H_ - -#include "heap/stubs.h" - -namespace blink { - -class X : public GarbageCollected<X> { - public: - virtual void trace(Visitor*) {} -}; - -template <typename T> -class Base : public GarbageCollected<Base<T> > { - public: - virtual void trace(Visitor*) {} -}; - -template <typename T> -class Derived : public Base<T> { - public: - void trace(Visitor* visitor) override { Base<T>::trace(visitor); } -}; - -template <typename T> -class DerivedMissingTrace : public Base<T> { - public: - void trace(Visitor* visitor) override { - // Missing Base<T>::trace(visitor). - } -}; - -} - -#endif // TRACEIMPL_DEPENDENT_SCOPE_H_
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/traceimpl_dependent_scope.txt b/tools/clang/blink_gc_plugin/tests/legacy_naming/traceimpl_dependent_scope.txt deleted file mode 100644 index 985b7f9..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/traceimpl_dependent_scope.txt +++ /dev/null
@@ -1,5 +0,0 @@ -In file included from traceimpl_dependent_scope.cpp:5: -./traceimpl_dependent_scope.h:32:3: warning: [blink-gc] Base class 'Base<int>' of derived class 'DerivedMissingTrace<int>' requires tracing. - void trace(Visitor* visitor) override { - ^ -1 warning generated.
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/traceimpl_derived_from_templated_base.cpp b/tools/clang/blink_gc_plugin/tests/legacy_naming/traceimpl_derived_from_templated_base.cpp deleted file mode 100644 index 9636fca7..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/traceimpl_derived_from_templated_base.cpp +++ /dev/null
@@ -1,7 +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 "traceimpl_derived_from_templated_base.h" - -// Nothing to define.
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/traceimpl_derived_from_templated_base.h b/tools/clang/blink_gc_plugin/tests/legacy_naming/traceimpl_derived_from_templated_base.h deleted file mode 100644 index b382545..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/traceimpl_derived_from_templated_base.h +++ /dev/null
@@ -1,32 +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 TRACEIMPL_DERIVED_FROM_TEMPLATED_BASE_H_ -#define TRACEIMPL_DERIVED_FROM_TEMPLATED_BASE_H_ - -#include "heap/stubs.h" - -namespace blink { - -class X : public GarbageCollected<X> { - public: - virtual void trace(Visitor*) {} -}; - -template <int Y> -class TraceImplTemplatedBase - : public GarbageCollected<TraceImplTemplatedBase<Y> > { - public: - void trace(Visitor* visitor) { visitor->trace(x_); } - - private: - Member<X> x_; -}; - -class TraceImplDerivedFromTemplatedBase : public TraceImplTemplatedBase<0> { -}; - -} - -#endif // TRACEIMPL_DERIVED_FROM_TEMPLATED_BASE_H_
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/traceimpl_derived_from_templated_base.txt b/tools/clang/blink_gc_plugin/tests/legacy_naming/traceimpl_derived_from_templated_base.txt deleted file mode 100644 index e69de29..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/traceimpl_derived_from_templated_base.txt +++ /dev/null
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/traceimpl_error.cpp b/tools/clang/blink_gc_plugin/tests/legacy_naming/traceimpl_error.cpp deleted file mode 100644 index 3a7638a3..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/traceimpl_error.cpp +++ /dev/null
@@ -1,17 +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 "traceimpl_error.h" - -namespace blink { - -void TraceImplExternWithUntracedMember::trace(Visitor* visitor) { - // Should get a warning as well. -} - -void TraceImplExternWithUntracedBase::trace(Visitor* visitor) { - // Ditto. -} - -}
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/traceimpl_error.h b/tools/clang/blink_gc_plugin/tests/legacy_naming/traceimpl_error.h deleted file mode 100644 index 0960199..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/traceimpl_error.h +++ /dev/null
@@ -1,56 +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 TRACEIMPL_ERROR_H_ -#define TRACEIMPL_ERROR_H_ - -#include "heap/stubs.h" - -namespace blink { - -class X : public GarbageCollected<X> { - public: - virtual void trace(Visitor*) {} -}; - -class TraceImplInlinedWithUntracedMember - : public GarbageCollected<TraceImplInlinedWithUntracedMember> { - public: - void trace(Visitor* visitor) { - // Empty; should get complaints from the plugin for untraced x_. - } - - private: - Member<X> x_; -}; - -class TraceImplExternWithUntracedMember - : public GarbageCollected<TraceImplExternWithUntracedMember> { - public: - void trace(Visitor* visitor); - - private: - Member<X> x_; -}; - -class Base : public GarbageCollected<Base> { - public: - virtual void trace(Visitor*) {} -}; - -class TraceImplInlineWithUntracedBase : public Base { - public: - void trace(Visitor* visitor) override { - // Empty; should get complaints from the plugin for untraced Base. - } -}; - -class TraceImplExternWithUntracedBase : public Base { - public: - void trace(Visitor*) override; -}; - -} - -#endif // TRACEIMPL_ERROR_H_
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/traceimpl_error.txt b/tools/clang/blink_gc_plugin/tests/legacy_naming/traceimpl_error.txt deleted file mode 100644 index 056711a..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/traceimpl_error.txt +++ /dev/null
@@ -1,20 +0,0 @@ -In file included from traceimpl_error.cpp:5: -./traceimpl_error.h:20:3: warning: [blink-gc] Class 'TraceImplInlinedWithUntracedMember' has untraced fields that require tracing. - void trace(Visitor* visitor) { - ^ -./traceimpl_error.h:25:3: note: [blink-gc] Untraced field 'x_' declared here: - Member<X> x_; - ^ -./traceimpl_error.h:44:3: warning: [blink-gc] Base class 'Base' of derived class 'TraceImplInlineWithUntracedBase' requires tracing. - void trace(Visitor* visitor) override { - ^ -traceimpl_error.cpp:9:1: warning: [blink-gc] Class 'TraceImplExternWithUntracedMember' has untraced fields that require tracing. -void TraceImplExternWithUntracedMember::trace(Visitor* visitor) { -^ -./traceimpl_error.h:34:3: note: [blink-gc] Untraced field 'x_' declared here: - Member<X> x_; - ^ -traceimpl_error.cpp:13:1: warning: [blink-gc] Base class 'Base' of derived class 'TraceImplExternWithUntracedBase' requires tracing. -void TraceImplExternWithUntracedBase::trace(Visitor* visitor) { -^ -4 warnings generated.
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/traceimpl_omitted_trace.cpp b/tools/clang/blink_gc_plugin/tests/legacy_naming/traceimpl_omitted_trace.cpp deleted file mode 100644 index b6dc2dff..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/traceimpl_omitted_trace.cpp +++ /dev/null
@@ -1,7 +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 "traceimpl_omitted_trace.h" - -// Nothing to define here.
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/traceimpl_omitted_trace.h b/tools/clang/blink_gc_plugin/tests/legacy_naming/traceimpl_omitted_trace.h deleted file mode 100644 index ec5c0b3e..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/traceimpl_omitted_trace.h +++ /dev/null
@@ -1,33 +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 TRACEIMPL_OMITTED_TRACE_H_ -#define TRACEIMPL_OMITTED_TRACE_H_ - -#include "heap/stubs.h" - -namespace blink { - -class A : public GarbageCollected<A> { - public: - virtual void trace(Visitor* visitor) {} -}; - -class B : public A { - // trace() isn't necessary because we've got nothing to trace here. -}; - -class C : public B { - public: - void trace(Visitor* visitor) override { - // B::trace() is actually A::trace(), and in certain cases we only get - // limited information like "there is a function call that will be resolved - // to A::trace()". We still want to mark B as traced. - B::trace(visitor); - } -}; - -} - -#endif // TRACEIMPL_OMITTED_TRACE_H_
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/traceimpl_omitted_trace.txt b/tools/clang/blink_gc_plugin/tests/legacy_naming/traceimpl_omitted_trace.txt deleted file mode 100644 index e69de29..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/traceimpl_omitted_trace.txt +++ /dev/null
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/traceimpl_overloaded.cpp b/tools/clang/blink_gc_plugin/tests/legacy_naming/traceimpl_overloaded.cpp deleted file mode 100644 index dc7051c..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/traceimpl_overloaded.cpp +++ /dev/null
@@ -1,18 +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 "traceimpl_overloaded.h" - -namespace blink { - -void ExternBase::trace(Visitor* visitor) { - visitor->trace(x_base_); -} - -void ExternDerived::trace(Visitor* visitor) { - visitor->trace(x_derived_); - ExternBase::trace(visitor); -} - -}
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/traceimpl_overloaded.h b/tools/clang/blink_gc_plugin/tests/legacy_naming/traceimpl_overloaded.h deleted file mode 100644 index 34185a39..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/traceimpl_overloaded.h +++ /dev/null
@@ -1,54 +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 TRACEIMPL_OVERLOADED_H_ -#define TRACEIMPL_OVERLOADED_H_ - -#include "heap/stubs.h" - -namespace blink { - -class X : public GarbageCollected<X> { - public: - void trace(Visitor*) {} -}; - -class InlinedBase : public GarbageCollected<InlinedBase> { - public: - virtual void trace(Visitor* visitor) { visitor->trace(x_base_); } - - private: - Member<X> x_base_; -}; - -class InlinedDerived : public InlinedBase { - public: - void trace(Visitor* visitor) override { - visitor->trace(x_derived_); - InlinedBase::trace(visitor); - } - - private: - Member<X> x_derived_; -}; - -class ExternBase : public GarbageCollected<ExternBase> { - public: - virtual void trace(Visitor*); - - private: - Member<X> x_base_; -}; - -class ExternDerived : public ExternBase { - public: - void trace(Visitor*) override; - - private: - Member<X> x_derived_; -}; - -} - -#endif // TRACEIMPL_OVERLOADED_H_
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/traceimpl_overloaded.txt b/tools/clang/blink_gc_plugin/tests/legacy_naming/traceimpl_overloaded.txt deleted file mode 100644 index e69de29..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/traceimpl_overloaded.txt +++ /dev/null
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/traceimpl_overloaded_error.cpp b/tools/clang/blink_gc_plugin/tests/legacy_naming/traceimpl_overloaded_error.cpp deleted file mode 100644 index 478ad7d6..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/traceimpl_overloaded_error.cpp +++ /dev/null
@@ -1,17 +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 "traceimpl_overloaded_error.h" - -namespace blink { - -void ExternBase::trace(Visitor* visitor) { - // Missing visitor->trace(x_base_). -} - -void ExternDerived::trace(Visitor* visitor) { - // Missing visitor->trace(x_derived_) and ExternBase::trace(visitor). -} - -}
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/traceimpl_overloaded_error.h b/tools/clang/blink_gc_plugin/tests/legacy_naming/traceimpl_overloaded_error.h deleted file mode 100644 index 8d6e9504..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/traceimpl_overloaded_error.h +++ /dev/null
@@ -1,53 +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 TRACEIMPL_OVERLOADED_ERROR_H_ -#define TRACEIMPL_OVERLOADED_ERROR_H_ - -#include "heap/stubs.h" - -namespace blink { - -class X : public GarbageCollected<X> { - public: - void trace(Visitor*) {} -}; - -class InlinedBase : public GarbageCollected<InlinedBase> { - public: - virtual void trace(Visitor* visitor) { - // Missing visitor->trace(x_base_). - } - - Member<X> x_base_; -}; - -class InlinedDerived : public InlinedBase { - public: - void trace(Visitor* visitor) override { - // Missing visitor->trace(x_derived_) and InlinedBase::trace(visitor). - } - - Member<X> x_derived_; -}; - -class ExternBase : public GarbageCollected<ExternBase> { - public: - virtual void trace(Visitor*); - - private: - Member<X> x_base_; -}; - -class ExternDerived : public ExternBase { - public: - void trace(Visitor*) override; - - private: - Member<X> x_derived_; -}; - -} - -#endif // TRACEIMPL_OVERLOADED_ERROR_H_
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/traceimpl_overloaded_error.txt b/tools/clang/blink_gc_plugin/tests/legacy_naming/traceimpl_overloaded_error.txt deleted file mode 100644 index bfbabd8..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/traceimpl_overloaded_error.txt +++ /dev/null
@@ -1,28 +0,0 @@ -In file included from traceimpl_overloaded_error.cpp:5: -./traceimpl_overloaded_error.h:19:3: warning: [blink-gc] Class 'InlinedBase' has untraced fields that require tracing. - virtual void trace(Visitor* visitor) { - ^ -./traceimpl_overloaded_error.h:23:3: note: [blink-gc] Untraced field 'x_base_' declared here: - Member<X> x_base_; - ^ -./traceimpl_overloaded_error.h:28:3: warning: [blink-gc] Base class 'InlinedBase' of derived class 'InlinedDerived' requires tracing. - void trace(Visitor* visitor) override { - ^ -./traceimpl_overloaded_error.h:28:3: warning: [blink-gc] Class 'InlinedDerived' has untraced fields that require tracing. -./traceimpl_overloaded_error.h:32:3: note: [blink-gc] Untraced field 'x_derived_' declared here: - Member<X> x_derived_; - ^ -traceimpl_overloaded_error.cpp:9:1: warning: [blink-gc] Class 'ExternBase' has untraced fields that require tracing. -void ExternBase::trace(Visitor* visitor) { -^ -./traceimpl_overloaded_error.h:40:3: note: [blink-gc] Untraced field 'x_base_' declared here: - Member<X> x_base_; - ^ -traceimpl_overloaded_error.cpp:13:1: warning: [blink-gc] Base class 'ExternBase' of derived class 'ExternDerived' requires tracing. -void ExternDerived::trace(Visitor* visitor) { -^ -traceimpl_overloaded_error.cpp:13:1: warning: [blink-gc] Class 'ExternDerived' has untraced fields that require tracing. -./traceimpl_overloaded_error.h:48:3: note: [blink-gc] Untraced field 'x_derived_' declared here: - Member<X> x_derived_; - ^ -6 warnings generated.
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/virtual_and_trace_after_dispatch.cpp b/tools/clang/blink_gc_plugin/tests/legacy_naming/virtual_and_trace_after_dispatch.cpp deleted file mode 100644 index 2ba6f1e..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/virtual_and_trace_after_dispatch.cpp +++ /dev/null
@@ -1,30 +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 "virtual_and_trace_after_dispatch.h" - -namespace blink { - -static B* toB(A* a) { return static_cast<B*>(a); } - -void A::trace(Visitor* visitor) -{ - switch (m_type) { - case TB: - toB(this)->traceAfterDispatch(visitor); - break; - } -} - -void A::traceAfterDispatch(Visitor* visitor) -{ -} - -void B::traceAfterDispatch(Visitor* visitor) -{ - visitor->trace(m_a); - A::traceAfterDispatch(visitor); -} - -}
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/virtual_and_trace_after_dispatch.h b/tools/clang/blink_gc_plugin/tests/legacy_naming/virtual_and_trace_after_dispatch.h deleted file mode 100644 index 50483496..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/virtual_and_trace_after_dispatch.h +++ /dev/null
@@ -1,34 +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 VIRTUAL_AND_TRACE_AFTER_DISPATCH_H_ -#define VIRTUAL_AND_TRACE_AFTER_DISPATCH_H_ - -#include "heap/stubs.h" - -namespace blink { - -class A : public GarbageCollected<A> { -public: - void trace(Visitor*); - void traceAfterDispatch(Visitor*); -protected: - enum Type { TB }; - A(Type type) : m_type(type) { } -private: - Type m_type; -}; - -class B : public A { -public: - B() : A(TB) { } - void traceAfterDispatch(Visitor*); - virtual void foo() { } -private: - Member<A> m_a; -}; - -} - -#endif
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/virtual_and_trace_after_dispatch.txt b/tools/clang/blink_gc_plugin/tests/legacy_naming/virtual_and_trace_after_dispatch.txt deleted file mode 100644 index fb466967..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/virtual_and_trace_after_dispatch.txt +++ /dev/null
@@ -1,11 +0,0 @@ -In file included from virtual_and_trace_after_dispatch.cpp:5: -./virtual_and_trace_after_dispatch.h:12:1: warning: [blink-gc] Left-most base class 'A' of derived class 'B' must be polymorphic. -class A : public GarbageCollected<A> { -^ -./virtual_and_trace_after_dispatch.h:23:1: warning: [blink-gc] Class 'B' contains or inherits virtual methods but implements manual dispatching. -class B : public A { -^ -./virtual_and_trace_after_dispatch.h:14:5: note: [blink-gc] Manual dispatch 'trace' declared here: - void trace(Visitor*); - ^ -2 warnings generated.
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/weak_fields_require_tracing.cpp b/tools/clang/blink_gc_plugin/tests/legacy_naming/weak_fields_require_tracing.cpp deleted file mode 100644 index 382e9f97..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/weak_fields_require_tracing.cpp +++ /dev/null
@@ -1,28 +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 "weak_fields_require_tracing.h" - -namespace blink { - -void HeapObject::trace(Visitor* visitor) -{ - // Missing visitor->trace(m_obj1); - // Missing visitor->trace(m_obj2); - // visitor->trace(m_obj3) in callback. - // Missing visitor->trace(m_set1); - visitor->trace(m_set2); - visitor->registerWeakMembers<HeapObject, - &HeapObject::clearWeakMembers>(this); -} - -void HeapObject::clearWeakMembers(Visitor* visitor) -{ - visitor->trace(m_obj1); // Does not count. - // Missing visitor->trace(m_obj2); - visitor->trace(m_obj3); // OK. - visitor->trace(m_set1); // Does not count. -} - -}
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/weak_fields_require_tracing.h b/tools/clang/blink_gc_plugin/tests/legacy_naming/weak_fields_require_tracing.h deleted file mode 100644 index c6850e6d..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/weak_fields_require_tracing.h +++ /dev/null
@@ -1,26 +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 WEAK_FIELDS_REQUIRE_TRACING_H_ -#define WEAK_FIELDS_REQUIRE_TRACING_H_ - -#include "heap/stubs.h" - -namespace blink { - -class HeapObject : public GarbageCollected<HeapObject> { -public: - void trace(Visitor*); - void clearWeakMembers(Visitor*); -private: - Member<HeapObject> m_obj1; - WeakMember<HeapObject> m_obj2; - WeakMember<HeapObject> m_obj3; - HeapHashSet<WeakMember<HeapObject> > m_set1; - HeapHashSet<WeakMember<HeapObject> > m_set2; -}; - -} - -#endif
diff --git a/tools/clang/blink_gc_plugin/tests/legacy_naming/weak_fields_require_tracing.txt b/tools/clang/blink_gc_plugin/tests/legacy_naming/weak_fields_require_tracing.txt deleted file mode 100644 index 02f56a393..0000000 --- a/tools/clang/blink_gc_plugin/tests/legacy_naming/weak_fields_require_tracing.txt +++ /dev/null
@@ -1,13 +0,0 @@ -weak_fields_require_tracing.cpp:9:1: warning: [blink-gc] Class 'HeapObject' has untraced fields that require tracing. -void HeapObject::trace(Visitor* visitor) -^ -./weak_fields_require_tracing.h:17:5: note: [blink-gc] Untraced field 'm_obj1' declared here: - Member<HeapObject> m_obj1; - ^ -./weak_fields_require_tracing.h:18:5: note: [blink-gc] Untraced field 'm_obj2' declared here: - WeakMember<HeapObject> m_obj2; - ^ -./weak_fields_require_tracing.h:20:5: note: [blink-gc] Untraced field 'm_set1' declared here: - HeapHashSet<WeakMember<HeapObject> > m_set1; - ^ -1 warning generated.
diff --git a/tools/clang/blink_gc_plugin/tests/test.py b/tools/clang/blink_gc_plugin/tests/test.py index b1338bf..a380cc63 100755 --- a/tools/clang/blink_gc_plugin/tests/test.py +++ b/tools/clang/blink_gc_plugin/tests/test.py
@@ -20,10 +20,6 @@ def AdjustClangArguments(self, clang_cmd): clang_cmd.append('-Wno-inaccessible-base') - clang_cmd.append('-Xclang') - clang_cmd.append('-plugin-arg-blink-gc-plugin') - clang_cmd.append('-Xclang') - clang_cmd.append('use-chromium-style-naming') def ProcessOneResult(self, test_name, actual): # Some Blink GC plugins dump a JSON representation of the object graph, and
diff --git a/tools/clang/plugins/ChromeClassTester.cpp b/tools/clang/plugins/ChromeClassTester.cpp index b0cc3db..c938806 100644 --- a/tools/clang/plugins/ChromeClassTester.cpp +++ b/tools/clang/plugins/ChromeClassTester.cpp
@@ -48,15 +48,15 @@ // We handle class types here where we have semantic information. We can only // check structs/classes/enums here, but we get a bunch of nice semantic // information instead of just parsing information. + if (InBannedNamespace(tag)) + return; + + SourceLocation location = tag->getInnerLocStart(); + LocationType location_type = ClassifyLocation(location); + if (location_type == LocationType::kThirdParty) + return; if (CXXRecordDecl* record = dyn_cast<CXXRecordDecl>(tag)) { - if (InBannedNamespace(record)) - return; - - SourceLocation record_location = record->getInnerLocStart(); - if (InBannedDirectory(record_location)) - return; - // We sadly need to maintain a blacklist of types that violate these // rules, but do so for good reason or due to limitations of this // checker (i.e., we don't handle extern templates very well). @@ -69,17 +69,14 @@ if (ends_with(base_name, "Matcher")) return; - CheckChromeClass(record_location, record); + CheckChromeClass(location_type, location, record); } else if (EnumDecl* enum_decl = dyn_cast<EnumDecl>(tag)) { - SourceLocation enum_location = enum_decl->getInnerLocStart(); - if (InBannedDirectory(enum_location)) - return; - std::string base_name = enum_decl->getNameAsString(); + // TODO(dcheng): This should probably consult a separate list. if (IsIgnoredType(base_name)) return; - CheckChromeEnum(enum_location, enum_decl); + CheckChromeEnum(location_type, location, enum_decl); } } @@ -98,27 +95,27 @@ } -bool ChromeClassTester::InBannedDirectory(SourceLocation loc) { +ChromeClassTester::LocationType ChromeClassTester::ClassifyLocation( + SourceLocation loc) { if (instance().getSourceManager().isInSystemHeader(loc)) - return true; + return LocationType::kThirdParty; std::string filename; if (!GetFilename(loc, &filename)) { // If the filename cannot be determined, simply treat this as a banned // location, instead of going through the full lookup process. - return true; + return LocationType::kThirdParty; } // We need to special case scratch space; which is where clang does its // macro expansion. We explicitly want to allow people to do otherwise bad // things through macros that were defined due to third party libraries. if (filename == "<scratch space>") - return true; + return LocationType::kThirdParty; // Don't complain about autogenerated protobuf files. - if (ends_with(filename, ".pb.h")) { - return true; - } + if (ends_with(filename, ".pb.h")) + return LocationType::kThirdParty; #if defined(LLVM_ON_UNIX) // Resolve the symlinktastic relative path and make it absolute. @@ -160,14 +157,14 @@ std::replace(filename.begin(), filename.end(), '\\', '/'); #endif - for (const std::string& allowed_dir : allowed_directories_) { + for (const std::string& blink_dir : blink_directories_) { // If any of the allowed directories occur as a component in filename, // this file is allowed. - assert(allowed_dir.front() == '/' && "Allowed dir must start with '/'"); - assert(allowed_dir.back() == '/' && "Allowed dir must end with '/'"); + assert(blink_dir.front() == '/' && "Allowed dir must start with '/'"); + assert(blink_dir.back() == '/' && "Allowed dir must end with '/'"); - if (filename.find(allowed_dir) != std::string::npos) - return false; + if (filename.find(blink_dir) != std::string::npos) + return LocationType::kBlink; } for (const std::string& banned_dir : banned_directories_) { @@ -177,24 +174,22 @@ assert(banned_dir.back() == '/' && "Banned dir must end with '/'"); if (filename.find(banned_dir) != std::string::npos) - return true; + return LocationType::kThirdParty; } - return false; + return LocationType::kChrome; } bool ChromeClassTester::InBannedNamespace(const Decl* record) { std::string n = GetNamespace(record); - if (!n.empty()) { - return std::find(banned_namespaces_.begin(), banned_namespaces_.end(), n) - != banned_namespaces_.end(); - } + if (!n.empty()) + return banned_namespaces_.find(n) != banned_namespaces_.end(); return false; } std::string ChromeClassTester::GetNamespace(const Decl* record) { - return GetNamespaceImpl(record->getDeclContext(), ""); + return GetNamespaceImpl(record->getDeclContext(), std::string()); } bool ChromeClassTester::HasIgnoredBases(const CXXRecordDecl* record) { @@ -238,9 +233,7 @@ banned_namespaces_.emplace("std"); banned_namespaces_.emplace("__gnu_cxx"); - if (options_.enforce_in_thirdparty_webkit) { - allowed_directories_.emplace("/third_party/WebKit/"); - } + blink_directories_.emplace("/third_party/WebKit/"); banned_directories_.emplace("/third_party/"); banned_directories_.emplace("/native_client/");
diff --git a/tools/clang/plugins/ChromeClassTester.h b/tools/clang/plugins/ChromeClassTester.h index 22af158..03bc2bd 100644 --- a/tools/clang/plugins/ChromeClassTester.h +++ b/tools/clang/plugins/ChromeClassTester.h
@@ -32,15 +32,27 @@ // Emits a simple warning; this shouldn't be used if you require printf-style // printing. + // TODO(dcheng): This will be removed. Do not add new usage. void emitWarning(clang::SourceLocation loc, const char* error); // Utility method for subclasses to check if this class is in a banned // namespace. bool InBannedNamespace(const clang::Decl* record); - // Utility method for subclasses to check if the source location is in a - // directory the plugin should ignore. - bool InBannedDirectory(clang::SourceLocation loc); + // Utility method for subclasses to check how a certain SourceLocation should + // be handled. The main criteria for classification is the SourceLocation's + // path (e.g. whether it's in //third_party). + enum class LocationType { + // Enforce all default checks. + kChrome, + // Enforces a subset of checks for Blink code. This is hopefully a + // transitional stage, as more plugin checks are gradually enabled in Blink. + kBlink, + // Skip all checks. Typically, this is third-party or generated code where + // it doesn't make sense to enforce Chrome's custom diagnostics. + kThirdParty, + }; + LocationType ClassifyLocation(clang::SourceLocation loc); // Utility method for subclasses to determine the namespace of the // specified record, if any. Unnamed namespaces will be identified as @@ -63,14 +75,15 @@ // Filtered versions of tags that are only called with things defined in // chrome header files. - virtual void CheckChromeClass(clang::SourceLocation record_location, + virtual void CheckChromeClass(LocationType location_type, + clang::SourceLocation record_location, clang::CXXRecordDecl* record) = 0; // Filtered versions of enum type that are only called with things defined // in chrome header files. - virtual void CheckChromeEnum(clang::SourceLocation enum_location, - clang::EnumDecl* enum_decl) { - } + virtual void CheckChromeEnum(LocationType location_type, + clang::SourceLocation enum_location, + clang::EnumDecl* enum_decl) = 0; // Utility methods used for filtering out non-chrome classes (and ones we // deliberately ignore) in HandleTagDeclDefinition(). @@ -88,9 +101,8 @@ // List of banned namespaces. std::set<std::string> banned_namespaces_; - // List of directories allowed even though their parent directories are in - // |banned_directories_|, below. - std::set<std::string> allowed_directories_; + // List of Blink directories. + std::set<std::string> blink_directories_; // List of banned directories. std::set<std::string> banned_directories_;
diff --git a/tools/clang/plugins/FindBadConstructsConsumer.cpp b/tools/clang/plugins/FindBadConstructsConsumer.cpp index 4c93af4d..629090c 100644 --- a/tools/clang/plugins/FindBadConstructsConsumer.cpp +++ b/tools/clang/plugins/FindBadConstructsConsumer.cpp
@@ -216,8 +216,14 @@ return true; } -void FindBadConstructsConsumer::CheckChromeClass(SourceLocation record_location, +void FindBadConstructsConsumer::CheckChromeClass(LocationType location_type, + SourceLocation record_location, CXXRecordDecl* record) { + // TODO(dcheng): After emitWarning() is removed, move warning filtering into + // ReportIfSpellingLocNotIgnored. + if (location_type == LocationType::kBlink) + return; + bool implementation_file = InImplementationFile(record_location); if (!implementation_file) { @@ -245,11 +251,15 @@ CheckWeakPtrFactoryMembers(record_location, record); } -void FindBadConstructsConsumer::CheckChromeEnum(SourceLocation enum_location, +void FindBadConstructsConsumer::CheckChromeEnum(LocationType location_type, + SourceLocation enum_location, EnumDecl* enum_decl) { if (!options_.check_enum_last_value) return; + if (location_type == LocationType::kBlink) + return; + bool got_one = false; bool is_signed = false; llvm::APSInt max_so_far; @@ -451,9 +461,12 @@ FindBadConstructsConsumer::ReportIfSpellingLocNotIgnored( SourceLocation loc, unsigned diagnostic_id) { - return SuppressibleDiagnosticBuilder( - &diagnostic(), loc, diagnostic_id, - InBannedDirectory(instance().getSourceManager().getSpellingLoc(loc))); + LocationType type = + ClassifyLocation(instance().getSourceManager().getSpellingLoc(loc)); + bool ignored = + type == LocationType::kThirdParty || type == LocationType::kBlink; + return SuppressibleDiagnosticBuilder(&diagnostic(), loc, diagnostic_id, + ignored); } // Checks that virtual methods are correctly annotated, and have no body in a @@ -609,7 +622,8 @@ bool emit = true; if (loc.isMacroID()) { SourceManager& manager = instance().getSourceManager(); - if (InBannedDirectory(manager.getSpellingLoc(loc))) + LocationType type = ClassifyLocation(manager.getSpellingLoc(loc)); + if (type == LocationType::kThirdParty || type == LocationType::kBlink) emit = false; else { StringRef name = Lexer::getImmediateMacroName( @@ -998,8 +1012,10 @@ // Check if we should even be considering this type (note that there // should be fewer auto types than banned namespace/directory types, // so check this last. + LocationType location_type = + ClassifyLocation(var_decl->getLocStart()); if (!InBannedNamespace(var_decl) && - !InBannedDirectory(var_decl->getLocStart())) { + location_type != LocationType::kThirdParty) { // The range starts from |var_decl|'s loc start, which is the // beginning of the full expression defining this |var_decl|. It // ends, however, where this |var_decl|'s type loc ends, since
diff --git a/tools/clang/plugins/FindBadConstructsConsumer.h b/tools/clang/plugins/FindBadConstructsConsumer.h index 64032d8..a1acf4a1 100644 --- a/tools/clang/plugins/FindBadConstructsConsumer.h +++ b/tools/clang/plugins/FindBadConstructsConsumer.h
@@ -56,9 +56,11 @@ bool VisitCallExpr(clang::CallExpr* call_expr); // ChromeClassTester overrides: - void CheckChromeClass(clang::SourceLocation record_location, + void CheckChromeClass(LocationType location_type, + clang::SourceLocation record_location, clang::CXXRecordDecl* record) override; - void CheckChromeEnum(clang::SourceLocation enum_location, + void CheckChromeEnum(LocationType location_type, + clang::SourceLocation enum_location, clang::EnumDecl* enum_decl) override; private:
diff --git a/tools/mb/mb_config.pyl b/tools/mb/mb_config.pyl index 9cd079e..29585d80 100644 --- a/tools/mb/mb_config.pyl +++ b/tools/mb/mb_config.pyl
@@ -433,6 +433,7 @@ 'official.desktop': { 'linux64': 'official', 'mac64': 'official', + 'mac64-recipes': 'official', 'precise64': 'official_six_concurrent_links', # Currently the official bots set mini_installer_official_deps=1
diff --git a/tools/metrics/actions/actions.xml b/tools/metrics/actions/actions.xml index acd09145..3873170 100644 --- a/tools/metrics/actions/actions.xml +++ b/tools/metrics/actions/actions.xml
@@ -16056,6 +16056,54 @@ <description>Please enter the description of this user action.</description> </action> +<action name="TodayExtension.ExtensionDismissed"> + <owner>olivierrobin@chromium.org</owner> + <description>Dismissed the Chrome Today extension.</description> +</action> + +<action name="TodayExtension.ExtensionDisplayed"> + <owner>olivierrobin@chromium.org</owner> + <description> + Displayed the notification center and display the Chrome Today extension. + </description> +</action> + +<action name="TodayExtension.ExtensionInitialized"> + <owner>olivierrobin@chromium.org</owner> + <description> + Displayed the notification center and initialize the Chrome Today extension. + </description> +</action> + +<action name="TodayExtension.NewTabPressed"> + <owner>olivierrobin@chromium.org</owner> + <description> + Tapped on the "New Tab" button in the Chrome Today extension. + </description> +</action> + +<action name="TodayExtension.OpenClipboardPressed"> + <owner>olivierrobin@chromium.org</owner> + <description> + Tapped on the "Open Copied Link" button in the Chrome Today + extension. + </description> +</action> + +<action name="TodayExtension.PhysicalWebPressed"> + <owner>olivierrobin@chromium.org</owner> + <description> + Tapped on physical web URL in the Chrome Today extension. + </description> +</action> + +<action name="TodayExtension.VoiceSearchPressed"> + <owner>olivierrobin@chromium.org</owner> + <description> + Tapped on the "Voice Search" button in the Chrome Today extension. + </description> +</action> + <action name="ToggleBold"> <owner>Please list the metric's owners. Add more owner tags as needed.</owner> <description>Please enter the description of this user action.</description>
diff --git a/tools/metrics/histograms/histograms.xml b/tools/metrics/histograms/histograms.xml index cbc2af4..cc911dc 100644 --- a/tools/metrics/histograms/histograms.xml +++ b/tools/metrics/histograms/histograms.xml
@@ -5139,6 +5139,9 @@ </histogram> <histogram name="Blink.RestoredCachedStyleSheet2" enum="StyleSheetCacheStatus"> + <obsolete> + Deprecated 04/2017. + </obsolete> <owner>kouhei@chromium.org</owner> <summary> On each link stylesheet tag resolve, record which cache Blink hit. @@ -13937,6 +13940,14 @@ </summary> </histogram> +<histogram name="Download.ParallelDownload.RemainingTimeWhenBuildingRequests" + units="seconds"> + <owner>qinmin@chromium.org</owner> + <summary> + Records the remaining download time when building parallel requests. + </summary> +</histogram> + <histogram name="Download.ParallelDownloadAddStreamSuccess" enum="BooleanSuccess"> <owner>xingliu@chromium.org</owner> @@ -20466,6 +20477,14 @@ </summary> </histogram> +<histogram name="Favicons.LargeIconService.DownloadedSize" units="pixels"> + <owner>jkrcal@chromium.org</owner> + <summary> + Records the size (concretely the width) in pixel of the favicon downloaded + from Google favicon server (size 0 denotes that download has failed). + </summary> +</histogram> + <histogram name="FileBrowser.CloudImport.UserAction" enum="CloudImportUserAction"> <owner>smckay@google.com</owner> @@ -101102,6 +101121,7 @@ <int value="-1772172557" label="enable-osk-overscroll"/> <int value="-1767470652" label="out-of-process-pdf"/> <int value="-1751928267" label="disable-icon-ntp"/> + <int value="-1749176684" label="PauseBackgroundTabs:disabled"/> <int value="-1746767834" label="ssl-interstitial-v2-gray"/> <int value="-1740519217" label="disable-software-rasterizer"/> <int value="-1735643253" label="enable-display-list-2d-canvas"/> @@ -101129,6 +101149,7 @@ <int value="-1660972490" label="gpu-rasterization-msaa-sample-count"/> <int value="-1655535052" label="enable-pointer-events"/> <int value="-1654344175" label="disable-extension-info-dialog"/> + <int value="-1653838003" label="PauseBackgroundTabs:enabled"/> <int value="-1649778035" label="disable-clear-browsing-data-counters"/> <int value="-1648216169" label="NewOmniboxAnswerTypes:disabled"/> <int value="-1634154256" label="ZeroSuggestRedirectToChrome:enabled"/> @@ -101179,6 +101200,7 @@ <int value="-1473136627" label="enable-web-payments"/> <int value="-1467332609" label="tab-management-experiment-type-anise"/> <int value="-1466990325" label="CrosCompUpdates:enabled"/> + <int value="-1463410070" label="IPH_DemoMode:enabled"/> <int value="-1460462432" label="disable-media-source"/> <int value="-1456004000" label="VrShell:disabled"/> <int value="-1443796945" label="OfflinePagesSharing:disabled"/> @@ -101310,6 +101332,7 @@ <int value="-945806012" label="DownloadsUi:enabled"/> <int value="-938178614" label="enable-suggestions-with-substring-match"/> <int value="-933316841" label="enable-permissions-blacklist"/> + <int value="-928138978" label="IPH_DemoMode:disabled"/> <int value="-926422468" label="disable-embedded-shared-worker"/> <int value="-918900957" label="AutofillCreditCardAssist:disabled"/> <int value="-918618075" label="enable-service-worker"/> @@ -106264,6 +106287,8 @@ <int value="4" label="No content length header"/> <int value="5" label="File size does not meet the requirement."/> <int value="6" label="HTTP connection type mismatch."/> + <int value="7" + label="Remaining download time does not meet the requirement."/> </enum> <enum name="ParsedCookieStatus" type="int"> @@ -122299,6 +122324,8 @@ label="Limited to the duration of time starting after first paint, for page loads that reached first paint."/> <affected-histogram + name="PageLoad.Clients.FromGoogleSearch.PageTiming.ForegroundDuration"/> + <affected-histogram name="PageLoad.Clients.SubresourceFilter.PageTiming.ForegroundDuration"/> <affected-histogram name="PageLoad.PageTiming.ForegroundDuration"/> </histogram_suffixes> @@ -122503,6 +122530,7 @@ name="PageLoad.Experimental.AbortTiming.Stop.AfterPaint.BeforeInteraction"/> <affected-histogram name="PageLoad.Experimental.AbortTiming.Stop.BeforeCommit"/> + <affected-histogram name="PageLoad.PageTiming.ForegroundDuration"/> <affected-histogram name="PageLoad.PaintTiming.NavigationToFirstContentfulPaint"/> <affected-histogram name="PageLoad.PaintTiming.NavigationToFirstImagePaint"/> @@ -122718,6 +122746,8 @@ <histogram_suffixes name="PageLoadMetricsNoCommit" separator="."> <suffix name="NoCommit" label="Limited to page loads that did not commit."/> + <affected-histogram + name="PageLoad.Clients.FromGoogleSearch.PageTiming.ForegroundDuration"/> <affected-histogram name="PageLoad.PageTiming.ForegroundDuration"/> </histogram_suffixes>
diff --git a/tools/metrics/ukm/ukm.xml b/tools/metrics/ukm/ukm.xml index 75d8a1a2..e83eafe9 100644 --- a/tools/metrics/ukm/ukm.xml +++ b/tools/metrics/ukm/ukm.xml
@@ -11,6 +11,15 @@ <ukm-configuration> +<event name="Autofill.CardUploadDecision"> + <owner>sebsg@chromium.org</owner> + <metric name="UploadDecision"> + <summary> + Whether the upload was proposed to the user or the reason why it was not. + </summary> + </metric> +</event> + <event name="PageLoad"> <owner>bmcquade@chromium.org</owner> <summary> @@ -36,9 +45,38 @@ </metric> </event> -<event name="Autofill.CardUploadDecision"> +<event name="PaymentRequest.CheckoutEvents"> <owner>sebsg@chromium.org</owner> - <metric name="UploadDecision"/> + <metric name="CompletionsStatus"> + <summary> + How the Payment Request ended. Values defined in the CompletionStatus enum + of components/payments/core/journey_logger.h. + </summary> + </metric> + <metric name="Events"> + <summary> + Bitfield representing the events that occurred during the Payment Request. + Values defined in the Event enum of + components/payments/core/journey_logger.h. + </summary> + </metric> +</event> + +<event name="Translate"> + <owner>hamelphi@chromium.org</owner> + <summary> + Metrics related to a Translate event. These metrics are described in + TranslateEventProto. + </summary> + <metric name="AcceptCount"/> + <metric name="Country"/> + <metric name="DeclineCount"/> + <metric name="EventType"/> + <metric name="IgnoreCount"/> + <metric name="RankerResponse"/> + <metric name="RankerVersion"/> + <metric name="SourceLanguage"/> + <metric name="TargetLanguage"/> </event> </ukm-configuration>
diff --git a/tools/perf/page_sets/tough_video_cases.py b/tools/perf/page_sets/tough_video_cases.py index 1914e734..a841a19a 100644 --- a/tools/perf/page_sets/tough_video_cases.py +++ b/tools/perf/page_sets/tough_video_cases.py
@@ -4,10 +4,35 @@ from telemetry.page import page as page_module from telemetry import story +_PAGE_TAGS_LIST = [ + # Audio codecs: + 'pcm', + 'mp3', + 'aac', + 'vorbis', + 'opus', + # Video codecs: + 'theora', + 'h264', + 'vp8', + 'vp9', + # Test types: + 'audio_video', + 'audio_only', + 'video_only', + 'looping_audio', + # Other filter tags: + 'is_50fps', + 'is_4k', +] + class ToughVideoCasesPage(page_module.Page): - def __init__(self, url, page_set, tags=None): + def __init__(self, url, page_set, tags): + if tags: + for t in tags: + assert t in _PAGE_TAGS_LIST super(ToughVideoCasesPage, self).__init__( url=url, page_set=page_set, tags=tags) @@ -45,7 +70,8 @@ def __init__(self, page_set): super(Page1, self).__init__( url='file://tough_video_cases/video.html?src=crowd.wav&type=audio', - page_set=page_set) + page_set=page_set, + tags=['pcm', 'audio_only']) self.add_browser_metrics = True @@ -58,7 +84,8 @@ def __init__(self, page_set): super(Page2, self).__init__( url='file://tough_video_cases/video.html?src=crowd.ogg&type=audio', - page_set=page_set) + page_set=page_set, + tags=['vorbis', 'audio_only']) self.add_browser_metrics = True @@ -68,13 +95,16 @@ class Page3(ToughVideoCasesPage): + # Note that ffprobe reports about this file: + # "[ogg @ 0x31a3ba0] Broken file, keyframe not correctly marked." + # This media file should probably be removed or replaced. def __init__(self, page_set): super(Page3, self).__init__( url='file://tough_video_cases/video.html?src=crowd1080.ogv', - page_set=page_set) + page_set=page_set, + tags=['is_50fps', 'theora', 'vorbis', 'audio_video']) self.add_browser_metrics = True - self.is_50fps = True def RunPageInteractions(self, action_runner): self.PlayAction(action_runner) @@ -85,7 +115,8 @@ def __init__(self, page_set): super(Page4, self).__init__( url='file://tough_video_cases/video.html?src=crowd1080.webm', - page_set=page_set, tags=['is_50fps']) + page_set=page_set, + tags=['is_50fps', 'vp8', 'vorbis', 'audio_video']) self.add_browser_metrics = True @@ -98,7 +129,8 @@ def __init__(self, page_set): super(Page5, self).__init__( url='file://tough_video_cases/video.html?src=crowd2160.ogv', - page_set=page_set, tags=['is_4k', 'is_50fps']) + page_set=page_set, + tags=['is_4k', 'is_50fps', 'theora', 'vorbis', 'audio_video']) self.add_browser_metrics = True @@ -111,7 +143,8 @@ def __init__(self, page_set): super(Page6, self).__init__( url='file://tough_video_cases/video.html?src=crowd2160.webm', - page_set=page_set, tags=['is_4k', 'is_50fps']) + page_set=page_set, + tags=['is_4k', 'is_50fps', 'vp8', 'vorbis', 'audio_video']) self.add_browser_metrics = True @@ -124,7 +157,8 @@ def __init__(self, page_set): super(Page7, self).__init__( url='file://tough_video_cases/video.html?src=tulip2.ogg&type=audio', - page_set=page_set) + page_set=page_set, + tags=['vorbis', 'audio_only']) self.add_browser_metrics = True @@ -137,7 +171,8 @@ def __init__(self, page_set): super(Page8, self).__init__( url='file://tough_video_cases/video.html?src=tulip2.wav&type=audio', - page_set=page_set) + page_set=page_set, + tags=['pcm', 'audio_only']) self.add_browser_metrics = True @@ -150,7 +185,8 @@ def __init__(self, page_set): super(Page9, self).__init__( url='file://tough_video_cases/video.html?src=tulip2.ogv', - page_set=page_set) + page_set=page_set, + tags=['theora', 'vorbis', 'audio_video']) self.add_browser_metrics = True @@ -163,7 +199,8 @@ def __init__(self, page_set): super(Page10, self).__init__( url='file://tough_video_cases/video.html?src=tulip2.webm', - page_set=page_set) + page_set=page_set, + tags=['vp8', 'vorbis', 'audio_video']) self.add_browser_metrics = True @@ -176,7 +213,8 @@ def __init__(self, page_set): super(Page11, self).__init__( url='file://tough_video_cases/video.html?src=crowd1080.mp4', - page_set=page_set, tags=['is_50fps']) + page_set=page_set, + tags=['is_50fps', 'h264', 'aac', 'audio_video']) self.add_browser_metrics = True @@ -189,7 +227,8 @@ def __init__(self, page_set): super(Page12, self).__init__( url='file://tough_video_cases/video.html?src=crowd2160.mp4', - page_set=page_set, tags=['is_4k', 'is_50fps']) + page_set=page_set, + tags=['is_4k', 'is_50fps', 'h264', 'aac', 'audio_video']) self.add_browser_metrics = True @@ -202,7 +241,8 @@ def __init__(self, page_set): super(Page13, self).__init__( url='file://tough_video_cases/video.html?src=tulip2.mp3&type=audio', - page_set=page_set) + page_set=page_set, + tags=['mp3', 'audio_only']) self.add_browser_metrics = True @@ -215,7 +255,8 @@ def __init__(self, page_set): super(Page14, self).__init__( url='file://tough_video_cases/video.html?src=tulip2.mp4', - page_set=page_set) + page_set=page_set, + tags=['h264', 'aac', 'audio_video']) self.add_browser_metrics = True @@ -228,7 +269,8 @@ def __init__(self, page_set): super(Page15, self).__init__( url='file://tough_video_cases/video.html?src=tulip2.m4a&type=audio', - page_set=page_set) + page_set=page_set, + tags=['aac', 'audio_only']) self.add_browser_metrics = True @@ -241,7 +283,8 @@ def __init__(self, page_set): super(Page16, self).__init__( url='file://tough_video_cases/video.html?src=garden2_10s.webm', - page_set=page_set, tags=['is_4k']) + page_set=page_set, + tags=['is_4k', 'vp8', 'vorbis', 'audio_video']) self.add_browser_metrics = True @@ -254,7 +297,8 @@ def __init__(self, page_set): super(Page17, self).__init__( url='file://tough_video_cases/video.html?src=garden2_10s.mp4', - page_set=page_set, tags=['is_4k']) + page_set=page_set, + tags=['is_4k', 'h264', 'aac', 'audio_video']) self.add_browser_metrics = True @@ -267,7 +311,8 @@ def __init__(self, page_set): super(Page18, self).__init__( url='file://tough_video_cases/video.html?src=garden2_10s.ogv', - page_set=page_set, tags=['is_4k']) + page_set=page_set, + tags=['is_4k', 'theora', 'vorbis', 'audio_video']) self.add_browser_metrics = True @@ -280,7 +325,8 @@ def __init__(self, page_set): super(Page19, self).__init__( url='file://tough_video_cases/video.html?src=tulip2.ogg&type=audio', - page_set=page_set) + page_set=page_set, + tags=['vorbis', 'audio_only']) self.skip_basic_metrics = True @@ -293,7 +339,8 @@ def __init__(self, page_set): super(Page20, self).__init__( url='file://tough_video_cases/video.html?src=tulip2.wav&type=audio', - page_set=page_set) + page_set=page_set, + tags=['pcm', 'audio_only']) self.skip_basic_metrics = True @@ -303,10 +350,14 @@ class Page21(ToughVideoCasesPage): + # Note that ffprobe reports about this file: + # "[ogg @ 0x39adba0] Broken file, keyframe not correctly marked." + # This media file should probably be removed or replaced. def __init__(self, page_set): super(Page21, self).__init__( url='file://tough_video_cases/video.html?src=tulip2.ogv', - page_set=page_set) + page_set=page_set, + tags=['theora', 'vorbis', 'audio_video']) self.skip_basic_metrics = True @@ -319,7 +370,8 @@ def __init__(self, page_set): super(Page22, self).__init__( url='file://tough_video_cases/video.html?src=tulip2.webm', - page_set=page_set) + page_set=page_set, + tags=['vp8', 'vorbis', 'audio_video']) self.skip_basic_metrics = True @@ -332,7 +384,8 @@ def __init__(self, page_set): super(Page23, self).__init__( url='file://tough_video_cases/video.html?src=tulip2.mp3&type=audio', - page_set=page_set) + page_set=page_set, + tags=['mp3', 'audio_only']) self.skip_basic_metrics = True @@ -345,7 +398,8 @@ def __init__(self, page_set): super(Page24, self).__init__( url='file://tough_video_cases/video.html?src=tulip2.mp4', - page_set=page_set) + page_set=page_set, + tags=['h264', 'aac', 'audio_video']) self.skip_basic_metrics = True @@ -358,7 +412,8 @@ def __init__(self, page_set): super(Page25, self).__init__( url='file://tough_video_cases/video.html?src=garden2_10s.webm', - page_set=page_set, tags=['is_4k']) + page_set=page_set, + tags=['is_4k', 'vp8', 'vorbis', 'audio_video']) self.skip_basic_metrics = True @@ -371,7 +426,8 @@ def __init__(self, page_set): super(Page26, self).__init__( url='file://tough_video_cases/video.html?src=garden2_10s.mp4', - page_set=page_set, tags=['is_4k']) + page_set=page_set, + tags=['is_4k', 'h264', 'aac', 'audio_video']) self.skip_basic_metrics = True @@ -384,7 +440,8 @@ def __init__(self, page_set): super(Page27, self).__init__( url='file://tough_video_cases/video.html?src=garden2_10s.ogv', - page_set=page_set, tags=['is_4k']) + page_set=page_set, + tags=['is_4k', 'theora', 'vorbis', 'audio_video']) self.skip_basic_metrics = True @@ -394,10 +451,12 @@ class Page28(ToughVideoCasesPage): + # This page tests looping a single audio track. def __init__(self, page_set): super(Page28, self).__init__( url='file://tough_video_cases/audio_playback.html?id=single_audio', - page_set=page_set) + page_set=page_set, + tags=['pcm', 'looping_audio']) self.skip_basic_metrics = True @@ -407,10 +466,13 @@ class Page29(ToughVideoCasesPage): + # This page tests looping an audio track and playing another in the + # background. def __init__(self, page_set): super(Page29, self).__init__( url='file://tough_video_cases/audio_playback.html?id=mixed_audio', - page_set=page_set) + page_set=page_set, + tags=['pcm', 'looping_audio']) self.skip_basic_metrics = True @@ -422,7 +484,8 @@ def __init__(self, page_set): super(Page30, self).__init__( url='file://tough_video_cases/video.html?src=tulip2.vp9.webm', - page_set=page_set) + page_set=page_set, + tags=['vp9', 'opus', 'audio_video']) self.add_browser_metrics = True @@ -434,7 +497,8 @@ def __init__(self, page_set): super(Page31, self).__init__( url='file://tough_video_cases/video.html?src=tulip2.vp9.webm', - page_set=page_set) + page_set=page_set, + tags=['vp9', 'opus', 'audio_video']) self.skip_basic_metrics = True @@ -446,7 +510,8 @@ def __init__(self, page_set): super(Page32, self).__init__( url='file://tough_video_cases/video.html?src=crowd1080_vp9.webm', - page_set=page_set) + page_set=page_set, + tags=['vp9', 'video_only']) self.add_browser_metrics = True @@ -458,7 +523,8 @@ def __init__(self, page_set): super(Page33, self).__init__( url='file://tough_video_cases/video.html?src=crowd1080_vp9.webm', - page_set=page_set) + page_set=page_set, + tags=['vp9', 'video_only']) self.skip_basic_metrics = True @@ -470,7 +536,8 @@ def __init__(self, page_set): super(Page34, self).__init__( url='file://tough_video_cases/video.html?src=crowd720_vp9.webm', - page_set=page_set) + page_set=page_set, + tags=['vp9', 'video_only']) self.add_browser_metrics = True @@ -482,7 +549,8 @@ def __init__(self, page_set): super(Page35, self).__init__( url='file://tough_video_cases/video.html?src=crowd720_vp9.webm', - page_set=page_set) + page_set=page_set, + tags=['vp9', 'video_only']) self.skip_basic_metrics = True @@ -495,7 +563,8 @@ super(Page36, self).__init__( url=('file://tough_video_cases/video.html?src=' 'smpte_3840x2160_60fps_vp9.webm'), - page_set=page_set, tags=['is_4k']) + page_set=page_set, + tags=['is_4k', 'vp9', 'video_only']) self.add_browser_metrics = True @@ -508,7 +577,8 @@ def __init__(self, page_set): super(Page37, self).__init__( url='file://tough_video_cases/video.html?src=crowd1080_vp9.webm&canvas=true', - page_set=page_set) + page_set=page_set, + tags=['vp9', 'video_only']) self.add_browser_metrics = True @@ -520,7 +590,8 @@ def __init__(self, page_set): super(Page38, self).__init__( url='file://tough_video_cases/video.html?src=tulip2.mp4&canvas=true', - page_set=page_set) + page_set=page_set, + tags=['h264', 'aac', 'audio_video']) self.add_browser_metrics = True @@ -532,7 +603,8 @@ def __init__(self, page_set): super(Page39, self).__init__( url='file://tough_video_cases/video.html?src=garden2_10s.webm&canvas=true', - page_set=page_set, tags=['is_4k']) + page_set=page_set, + tags=['is_4k', 'vp8', 'vorbis', 'audio_video']) self.add_browser_metrics = True @@ -541,13 +613,16 @@ class Page40(ToughVideoCasesPage): + # Note that ffprobe reports about this file: + # "[ogg @ 0x31a3ba0] Broken file, keyframe not correctly marked." + # This media file should probably be removed or replaced. def __init__(self, page_set): super(Page40, self).__init__( url='file://tough_video_cases/video.html?src=crowd1080.ogv&canvas=true', - page_set=page_set) + page_set=page_set, + tags=['is_50fps', 'theora', 'vorbis', 'audio_video']) self.add_browser_metrics = True - self.is_50fps = True def RunPageInteractions(self, action_runner): self.PlayAction(action_runner)
diff --git a/ui/accessibility/ax_position.h b/ui/accessibility/ax_position.h index bbce7f3..0938f05 100644 --- a/ui/accessibility/ax_position.h +++ b/ui/accessibility/ax_position.h
@@ -131,6 +131,7 @@ str = "TreePosition tree_id=" + base::IntToString(tree_id_) + " anchor_id=" + base::IntToString(anchor_id_) + " child_index=" + str_child_index; + break; } case AXPositionKind::TEXT_POSITION: { std::string str_text_offset; @@ -143,6 +144,7 @@ " anchor_id=" + base::IntToString(anchor_id_) + " text_offset=" + str_text_offset + " affinity=" + ui::ToString(static_cast<AXTextAffinity>(affinity_)); + break; } } @@ -225,6 +227,80 @@ return false; } + bool AtStartOfWord() const { + AXPositionInstance text_position = AsLeafTextPosition(); + switch (text_position->kind_) { + case AXPositionKind::NULL_POSITION: + return false; + case AXPositionKind::TREE_POSITION: + NOTREACHED(); + return false; + case AXPositionKind::TEXT_POSITION: { + const std::vector<int32_t> word_starts = + text_position->GetWordStartOffsets(); + auto iterator = + std::find(word_starts.begin(), word_starts.end(), + static_cast<int32_t>(text_position->text_offset_)); + return iterator != word_starts.end(); + } + } + return false; + } + + bool AtEndOfWord() const { + AXPositionInstance text_position = AsLeafTextPosition(); + switch (text_position->kind_) { + case AXPositionKind::NULL_POSITION: + return false; + case AXPositionKind::TREE_POSITION: + NOTREACHED(); + return false; + case AXPositionKind::TEXT_POSITION: { + const std::vector<int32_t> word_ends = + text_position->GetWordEndOffsets(); + auto iterator = + std::find(word_ends.begin(), word_ends.end(), + static_cast<int32_t>(text_position->text_offset_)); + return iterator != word_ends.end(); + } + } + return false; + } + + bool AtStartOfLine() const { + AXPositionInstance text_position = AsLeafTextPosition(); + switch (text_position->kind_) { + case AXPositionKind::NULL_POSITION: + return false; + case AXPositionKind::TREE_POSITION: + NOTREACHED(); + return false; + case AXPositionKind::TEXT_POSITION: + return !text_position->IsInLineBreak() && + GetPreviousOnLineID(text_position->anchor_id_) == + INVALID_ANCHOR_ID && + text_position->AtStartOfAnchor(); + } + return false; + } + + bool AtEndOfLine() const { + AXPositionInstance text_position = AsLeafTextPosition(); + switch (text_position->kind_) { + case AXPositionKind::NULL_POSITION: + return false; + case AXPositionKind::TREE_POSITION: + NOTREACHED(); + return false; + case AXPositionKind::TEXT_POSITION: + return !text_position->IsInLineBreak() && + GetNextOnLineID(text_position->anchor_id_) == + INVALID_ANCHOR_ID && + text_position->AtEndOfAnchor(); + } + return false; + } + // This method returns a position instead of a node because this allows us to // return the corresponding text offset or child index in the ancestor that // relates to the current position. @@ -449,20 +525,28 @@ if (tree_id == INVALID_TREE_ID || parent_id == INVALID_ANCHOR_ID) return CreateNullPosition(); - DCHECK_NE(tree_id, INVALID_TREE_ID); - DCHECK_NE(parent_id, INVALID_ANCHOR_ID); switch (kind_) { case AXPositionKind::NULL_POSITION: NOTREACHED(); return CreateNullPosition(); case AXPositionKind::TREE_POSITION: return CreateTreePosition(tree_id, parent_id, AnchorIndexInParent()); - case AXPositionKind::TEXT_POSITION: - // Make sure that our affinity is propagated to our parent because by - // design our parent includes all our text. - return CreateTextPosition(tree_id, parent_id, - AnchorTextOffsetInParent() + text_offset_, - affinity_); + case AXPositionKind::TEXT_POSITION: { + // If our parent contains all our text, we need to maintain the affinity + // and the text offset. Otherwise, we return a position that is either + // before or after the child and we don't maintain the affinity when the + // position is after the child. + int parent_offset = AnchorTextOffsetInParent(); + AXTextAffinity parent_affinity = affinity_; + if (MaxTextOffset() == MaxTextOffsetInParent()) { + parent_offset += text_offset_; + } else if (text_offset_ > 0) { + parent_offset += MaxTextOffsetInParent(); + parent_affinity = AX_TEXT_AFFINITY_DOWNSTREAM; + } + return CreateTextPosition(tree_id, parent_id, parent_offset, + parent_affinity); + } } return CreateNullPosition(); @@ -548,22 +632,13 @@ if (text_position->IsNullPosition()) return text_position; - // Ignore any nodes with no text or no word boundaries. - while (!text_position->IsNullPosition() && - (!text_position->MaxTextOffset() || - text_position->GetWordStartOffsets().empty())) { - text_position = text_position->CreateNextTextAnchorPosition(); - } - - if (text_position->IsNullPosition()) - return text_position; - const std::vector<int32_t> word_starts = text_position->GetWordStartOffsets(); auto iterator = std::upper_bound(word_starts.begin(), word_starts.end(), static_cast<int32_t>(text_position->text_offset_)); if (iterator == word_starts.end()) { + // Ignore any nodes with no text or no word boundaries. do { text_position = text_position->CreateNextTextAnchorPosition(); } while (!text_position->IsNullPosition() && @@ -572,10 +647,9 @@ if (text_position->IsNullPosition()) return text_position; - // In case there are some non-word characters in front of the first word - // in this text node. const std::vector<int32_t> word_starts = text_position->GetWordStartOffsets(); + DCHECK(!word_starts.empty()); text_position->text_offset_ = static_cast<int>(word_starts[0]); } else { text_position->text_offset_ = static_cast<int>(*iterator); @@ -589,7 +663,7 @@ AXPositionInstance common_ancestor = text_position->LowestCommonAncestor(*this); if (GetAnchor() == common_ancestor->GetAnchor()) - return common_ancestor; + text_position = std::move(common_ancestor); if (was_tree_position) text_position = text_position->AsTreePosition(); @@ -599,22 +673,11 @@ AXPositionInstance CreatePreviousWordStartPosition() const { bool was_tree_position = IsTreePosition(); AXPositionInstance text_position = AsLeafTextPosition(); - if (text_position->IsNullPosition()) - return text_position; if (text_position->AtStartOfAnchor()) { text_position = text_position->CreatePreviousTextAnchorPosition(); text_position = text_position->CreatePositionAtEndOfAnchor(); } - - // Ignore any nodes with no text or no word boundaries. - while (!text_position->IsNullPosition() && - (!text_position->MaxTextOffset() || - text_position->GetWordStartOffsets().empty())) { - text_position = text_position->CreatePreviousTextAnchorPosition(); - text_position = text_position->CreatePositionAtEndOfAnchor(); - } - if (text_position->IsNullPosition()) return text_position; @@ -623,9 +686,8 @@ auto iterator = std::lower_bound(word_starts.begin(), word_starts.end(), static_cast<int32_t>(text_position->text_offset_)); - if (iterator == word_starts.begin()) { - // There must be some non-word characters in front of the first word in - // this text node. + if (word_starts.empty() || iterator == word_starts.begin()) { + // Ignore any nodes with no text or no word boundaries. do { text_position = text_position->CreatePreviousTextAnchorPosition(); } while (!text_position->IsNullPosition() && @@ -636,6 +698,7 @@ const std::vector<int32_t> word_starts = text_position->GetWordStartOffsets(); + DCHECK(!word_starts.empty()); text_position->text_offset_ = static_cast<int>(*(word_starts.end() - 1)); } else { text_position->text_offset_ = static_cast<int>(*(--iterator)); @@ -649,7 +712,7 @@ AXPositionInstance common_ancestor = text_position->LowestCommonAncestor(*this); if (GetAnchor() == common_ancestor->GetAnchor()) - return common_ancestor; + text_position = std::move(common_ancestor); if (was_tree_position) text_position = text_position->AsTreePosition(); @@ -660,27 +723,18 @@ AXPositionInstance CreateNextWordEndPosition() const { bool was_tree_position = IsTreePosition(); AXPositionInstance text_position = AsLeafTextPosition(); - if (text_position->IsNullPosition()) - return text_position; if (text_position->AtEndOfAnchor()) text_position = text_position->CreateNextTextAnchorPosition(); - - // Ignore any nodes with no text or no word boundaries. - while (!text_position->IsNullPosition() && - (!text_position->MaxTextOffset() || - text_position->GetWordEndOffsets().empty())) { - text_position = text_position->CreateNextTextAnchorPosition(); - } - if (text_position->IsNullPosition()) return text_position; - const std::vector<int> word_ends = text_position->GetWordEndOffsets(); - auto iterator = std::upper_bound(word_ends.begin(), word_ends.end(), - text_position->text_offset_); + const std::vector<int32_t> word_ends = text_position->GetWordEndOffsets(); + auto iterator = + std::upper_bound(word_ends.begin(), word_ends.end(), + static_cast<int32_t>(text_position->text_offset_)); if (iterator == word_ends.end()) { - // We should be in the last word of this text node. + // Ignore any nodes with no text or no word boundaries. do { text_position = text_position->CreateNextTextAnchorPosition(); } while (!text_position->IsNullPosition() && @@ -689,10 +743,11 @@ if (text_position->IsNullPosition()) return text_position; - const std::vector<int> word_ends = text_position->GetWordEndOffsets(); - text_position->text_offset_ = word_ends[0]; + const std::vector<int32_t> word_ends = text_position->GetWordEndOffsets(); + DCHECK(!word_ends.empty()); + text_position->text_offset_ = static_cast<int>(word_ends[0]); } else { - text_position->text_offset_ = *iterator; + text_position->text_offset_ = static_cast<int>(*iterator); text_position->affinity_ = AX_TEXT_AFFINITY_DOWNSTREAM; } @@ -703,7 +758,7 @@ AXPositionInstance common_ancestor = text_position->LowestCommonAncestor(*this); if (GetAnchor() == common_ancestor->GetAnchor()) - return common_ancestor; + text_position = std::move(common_ancestor); if (was_tree_position) text_position = text_position->AsTreePosition(); @@ -714,21 +769,11 @@ AXPositionInstance CreatePreviousWordEndPosition() const { bool was_tree_position = IsTreePosition(); AXPositionInstance text_position = AsLeafTextPosition(); - if (text_position->IsNullPosition()) - return text_position; if (text_position->AtStartOfAnchor()) { text_position = text_position->CreatePreviousTextAnchorPosition(); text_position = text_position->CreatePositionAtEndOfAnchor(); } - - // Ignore any nodes with no text or no word boundaries. - while (!text_position->IsNullPosition() && - (!text_position->MaxTextOffset() || - text_position->GetWordStartOffsets().empty())) { - text_position = text_position->CreatePreviousTextAnchorPosition(); - } - if (text_position->IsNullPosition()) return text_position; @@ -736,9 +781,8 @@ auto iterator = std::lower_bound(word_ends.begin(), word_ends.end(), static_cast<int32_t>(text_position->text_offset_)); - if (iterator == word_ends.begin()) { - // We must be anywhere up to and including the end of the first word in - // this node. + if (word_ends.empty() || iterator == word_ends.begin()) { + // Ignore any nodes with no text or no word boundaries. do { text_position = text_position->CreatePreviousTextAnchorPosition(); } while (!text_position->IsNullPosition() && @@ -748,6 +792,7 @@ return text_position; const std::vector<int32_t> word_ends = text_position->GetWordEndOffsets(); + DCHECK(!word_ends.empty()); text_position->text_offset_ = static_cast<int>(*(word_ends.end() - 1)); } else { text_position->text_offset_ = static_cast<int>(*(--iterator)); @@ -761,7 +806,7 @@ AXPositionInstance common_ancestor = text_position->LowestCommonAncestor(*this); if (GetAnchor() == common_ancestor->GetAnchor()) - return common_ancestor; + text_position = std::move(common_ancestor); if (was_tree_position) text_position = text_position->AsTreePosition(); @@ -783,6 +828,8 @@ AX_TEXT_AFFINITY_DOWNSTREAM); text_position = text_position->AsLeafTextPosition()->CreateNextTextAnchorPosition(); + while (text_position->IsInLineBreak()) + text_position = text_position->CreateNextTextAnchorPosition(); if (text_position->IsNullPosition()) return text_position; @@ -793,7 +840,7 @@ AXPositionInstance common_ancestor = text_position->LowestCommonAncestor(*this); if (GetAnchor() == common_ancestor->GetAnchor()) - return common_ancestor; + text_position = std::move(common_ancestor); if (was_tree_position) text_position = text_position->AsTreePosition(); @@ -803,7 +850,7 @@ AXPositionInstance CreatePreviousLineStartPosition() const { bool was_tree_position = IsTreePosition(); AXPositionInstance text_position = AsLeafTextPosition(); - if (text_position->AtStartOfAnchor()) + if (text_position->IsInLineBreak() || text_position->AtStartOfAnchor()) text_position = text_position->CreatePreviousTextAnchorPosition(); if (text_position->IsNullPosition()) return text_position; @@ -825,7 +872,7 @@ AXPositionInstance common_ancestor = text_position->LowestCommonAncestor(*this); if (GetAnchor() == common_ancestor->GetAnchor()) - return common_ancestor; + text_position = std::move(common_ancestor); if (was_tree_position) text_position = text_position->AsTreePosition(); @@ -852,9 +899,8 @@ CreateTextPosition(tree_id_, next_on_line_id, 0 /* text_offset */, AX_TEXT_AFFINITY_DOWNSTREAM); text_position = text_position->AsLeafTextPosition(); - while (text_position->IsInLineBreak()) { + while (text_position->IsInLineBreak()) text_position = text_position->CreatePreviousTextAnchorPosition(); - } if (text_position->IsNullPosition()) return text_position; text_position = text_position->CreatePositionAtEndOfAnchor(); @@ -866,7 +912,7 @@ AXPositionInstance common_ancestor = text_position->LowestCommonAncestor(*this); if (GetAnchor() == common_ancestor->GetAnchor()) - return common_ancestor; + text_position = std::move(common_ancestor); if (was_tree_position) text_position = text_position->AsTreePosition(); @@ -889,9 +935,8 @@ AX_TEXT_AFFINITY_DOWNSTREAM); text_position = text_position->AsLeafTextPosition()->CreatePreviousTextAnchorPosition(); - while (text_position->IsInLineBreak()) { + while (text_position->IsInLineBreak()) text_position = text_position->CreatePreviousTextAnchorPosition(); - } if (text_position->IsNullPosition()) return text_position; text_position = text_position->CreatePositionAtEndOfAnchor(); @@ -903,7 +948,7 @@ AXPositionInstance common_ancestor = text_position->LowestCommonAncestor(*this); if (GetAnchor() == common_ancestor->GetAnchor()) - return common_ancestor; + text_position = std::move(common_ancestor); if (was_tree_position) text_position = text_position->AsTreePosition();
diff --git a/ui/android/OWNERS b/ui/android/OWNERS index e59d378f..136bb69c 100644 --- a/ui/android/OWNERS +++ b/ui/android/OWNERS
@@ -8,5 +8,6 @@ # for display/window/view_android boliu@chromium.org +jinsukkim@chromium.org # COMPONENT: UI
diff --git a/ui/android/delegated_frame_host_android.cc b/ui/android/delegated_frame_host_android.cc index ccb4c68..e33c8b4 100644 --- a/ui/android/delegated_frame_host_android.cc +++ b/ui/android/delegated_frame_host_android.cc
@@ -160,7 +160,9 @@ registered_parent_compositor_ = nullptr; } -void DelegatedFrameHostAndroid::DidReceiveCompositorFrameAck() { +void DelegatedFrameHostAndroid::DidReceiveCompositorFrameAck( + const cc::ReturnedResourceArray& resources) { + client_->ReclaimResources(resources); client_->DidReceiveCompositorFrameAck(); } @@ -188,11 +190,13 @@ } void DelegatedFrameHostAndroid::CreateNewCompositorFrameSinkSupport() { + constexpr bool is_root = false; + constexpr bool handles_frame_sink_id_invalidation = false; + constexpr bool needs_sync_points = true; support_.reset(); - support_ = base::MakeUnique<cc::CompositorFrameSinkSupport>( - this, surface_manager_, frame_sink_id_, false /* is_root */, - false /* handles_frame_sink_id_invalidation */, - true /* needs_sync_points */); + support_ = cc::CompositorFrameSinkSupport::Create( + this, surface_manager_, frame_sink_id_, is_root, + handles_frame_sink_id_invalidation, needs_sync_points); } cc::SurfaceId DelegatedFrameHostAndroid::SurfaceId() const {
diff --git a/ui/android/delegated_frame_host_android.h b/ui/android/delegated_frame_host_android.h index 793d43d..d6065d4 100644 --- a/ui/android/delegated_frame_host_android.h +++ b/ui/android/delegated_frame_host_android.h
@@ -73,7 +73,8 @@ private: // cc::CompositorFrameSinkSupportClient implementation. - void DidReceiveCompositorFrameAck() override; + void DidReceiveCompositorFrameAck( + const cc::ReturnedResourceArray& resources) override; void OnBeginFrame(const cc::BeginFrameArgs& args) override; void ReclaimResources(const cc::ReturnedResourceArray& resources) override; void WillDrawSurface(const cc::LocalSurfaceId& local_surface_id,
diff --git a/ui/aura/gestures/gesture_recognizer_unittest.cc b/ui/aura/gestures/gesture_recognizer_unittest.cc index 0513496..0aff210 100644 --- a/ui/aura/gestures/gesture_recognizer_unittest.cc +++ b/ui/aura/gestures/gesture_recognizer_unittest.cc
@@ -4750,5 +4750,30 @@ EXPECT_TRUE(delegate_2->tap()); } +TEST_F(GestureRecognizerTest, GestureConsumerCleanupBeforeTouchAck) { + std::unique_ptr<QueueTouchEventDelegate> delegate( + new QueueTouchEventDelegate(host()->dispatcher())); + TimedEvents tes; + const int kTouchId = 7; + gfx::Rect bounds(0, 0, 1000, 1000); + + std::unique_ptr<aura::Window> window(CreateTestWindowWithDelegate( + delegate.get(), -1234, bounds, root_window())); + + delegate->set_window(window.get()); + + delegate->Reset(); + ui::TouchEvent press( + ui::ET_TOUCH_PRESSED, gfx::Point(512, 512), tes.Now(), + ui::PointerDetails(ui::EventPointerType::POINTER_TYPE_TOUCH, kTouchId)); + DispatchEventUsingWindowDispatcher(&press); + + window->Hide(); + + delegate->Reset(); + delegate->ReceivedAck(); + EXPECT_0_EVENTS(delegate->events()); +} + } // namespace test } // namespace aura
diff --git a/ui/base/l10n/l10n_util_unittest.cc b/ui/base/l10n/l10n_util_unittest.cc index ee81f036..18d775d 100644 --- a/ui/base/l10n/l10n_util_unittest.cc +++ b/ui/base/l10n/l10n_util_unittest.cc
@@ -10,11 +10,13 @@ #include "base/files/file_util.h" #include "base/i18n/case_conversion.h" #include "base/i18n/rtl.h" +#include "base/i18n/time_formatting.h" #include "base/macros.h" #include "base/memory/ptr_util.h" #include "base/path_service.h" #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" +#include "base/test/icu_test_util.h" #include "base/test/scoped_path_override.h" #include "build/build_config.h" #include "testing/gtest/include/gtest/gtest.h" @@ -584,3 +586,20 @@ EXPECT_FALSE(l10n_util::IsValidLocaleSyntax("en-US@x=")); EXPECT_FALSE(l10n_util::IsValidLocaleSyntax("en-US@=y")); } + +TEST_F(L10nUtilTest, TimeDurationFormatAllLocales) { + base::test::ScopedRestoreICUDefaultLocale restore_locale; + + // Verify that base::TimeDurationFormat() works for all available locales: + // http://crbug.com/707515 + base::TimeDelta kDelta = base::TimeDelta::FromMinutes(15 * 60 + 42); + for (const std::string& locale : l10n_util::GetAvailableLocales()) { + base::i18n::SetICUDefaultLocale(locale); + base::string16 str; + const bool result = + base::TimeDurationFormat(kDelta, base::DURATION_WIDTH_NUMERIC, &str); + EXPECT_TRUE(result) << "Failed to format duration for " << locale; + if (result) + EXPECT_FALSE(str.empty()) << "Got empty string for " << locale; + } +}
diff --git a/ui/compositor/compositor.cc b/ui/compositor/compositor.cc index f69e71e..b83b08fe 100644 --- a/ui/compositor/compositor.cc +++ b/ui/compositor/compositor.cc
@@ -126,7 +126,7 @@ settings.initial_debug_state.SetRecordRenderingStats( command_line->HasSwitch(cc::switches::kEnableGpuBenchmarking)); - settings.needs_valid_local_surface_id = + settings.enable_surface_synchronization = command_line->HasSwitch(cc::switches::kEnableSurfaceSynchronization); settings.use_zero_copy = IsUIZeroCopyEnabled();
diff --git a/ui/events/gestures/gesture_recognizer_impl.cc b/ui/events/gestures/gesture_recognizer_impl.cc index 5b2263f..5f7e70cd 100644 --- a/ui/events/gestures/gesture_recognizer_impl.cc +++ b/ui/events/gestures/gesture_recognizer_impl.cc
@@ -36,18 +36,19 @@ } } -bool RemoveConsumerFromMap(GestureConsumer* consumer, - GestureRecognizerImpl::TouchIdToConsumerMap* map) { - bool consumer_removed = false; +// Generic function to remove every entry from a map having the given value. +template <class Key, class T, class Value> +bool RemoveValueFromMap(std::map<Key, T>* map, const Value& value) { + bool removed = false; for (auto i = map->begin(); i != map->end();) { - if (i->second == consumer) { + if (i->second == value) { map->erase(i++); - consumer_removed = true; + removed = true; } else { ++i; } } - return consumer_removed; + return removed; } } // namespace @@ -302,12 +303,17 @@ GestureConsumer* consumer) { bool state_cleaned_up = false; - if (consumer_gesture_provider_.count(consumer)) { + auto consumer_gesture_provider_it = consumer_gesture_provider_.find(consumer); + if (consumer_gesture_provider_it != consumer_gesture_provider_.end()) { + // Remove gesture provider associated with the consumer from + // |event_to_gesture_provider_| map. + RemoveValueFromMap(&event_to_gesture_provider_, + consumer_gesture_provider_it->second.get()); state_cleaned_up = true; - consumer_gesture_provider_.erase(consumer); + consumer_gesture_provider_.erase(consumer_gesture_provider_it); } - state_cleaned_up |= RemoveConsumerFromMap(consumer, &touch_id_target_); + state_cleaned_up |= RemoveValueFromMap(&touch_id_target_, consumer); return state_cleaned_up; }
diff --git a/ui/gl/BUILD.gn b/ui/gl/BUILD.gn index 35cce3c..a36683eb 100644 --- a/ui/gl/BUILD.gn +++ b/ui/gl/BUILD.gn
@@ -10,7 +10,8 @@ import("//testing/test.gni") declare_args() { - enable_swiftshader = is_win + enable_swiftshader = (is_win || (is_linux && !is_chromeos && use_x11)) && + (target_cpu == "x86" || target_cpu == "x64") } use_egl = is_win || is_android || is_linux
diff --git a/ui/ozone/platform/drm/gpu/hardware_display_plane_atomic.cc b/ui/ozone/platform/drm/gpu/hardware_display_plane_atomic.cc index 6ca6f6b4..9ad137f4 100644 --- a/ui/ozone/platform/drm/gpu/hardware_display_plane_atomic.cc +++ b/ui/ozone/platform/drm/gpu/hardware_display_plane_atomic.cc
@@ -19,6 +19,38 @@ const char* kSrcYPropName = "SRC_Y"; const char* kSrcWPropName = "SRC_W"; const char* kSrcHPropName = "SRC_H"; +const char* kRotationPropName = "rotation"; + +// TODO(dcastagna): Remove the following defines once they're in libdrm headers. +#if !defined(DRM_ROTATE_0) +#define DRM_ROTATE_0 0 +#define DRM_ROTATE_90 1 +#define DRM_ROTATE_180 2 +#define DRM_ROTATE_270 3 +#define DRM_REFLECT_X 4 +#define DRM_REFLECT_Y 5 +#endif + +uint32_t OverlayTransformToDrmRotationPropertyValue( + gfx::OverlayTransform transform) { + switch (transform) { + case gfx::OVERLAY_TRANSFORM_NONE: + return 0; + case gfx::OVERLAY_TRANSFORM_FLIP_HORIZONTAL: + return 1 << DRM_REFLECT_X; + case gfx::OVERLAY_TRANSFORM_FLIP_VERTICAL: + return 1 << DRM_REFLECT_Y; + case gfx::OVERLAY_TRANSFORM_ROTATE_90: + return 1 << DRM_ROTATE_90; + case gfx::OVERLAY_TRANSFORM_ROTATE_180: + return 1 << DRM_ROTATE_180; + case gfx::OVERLAY_TRANSFORM_ROTATE_270: + return 1 << DRM_ROTATE_270; + default: + NOTREACHED(); + } + return 0; +} } // namespace @@ -51,11 +83,13 @@ HardwareDisplayPlaneAtomic::~HardwareDisplayPlaneAtomic() { } -bool HardwareDisplayPlaneAtomic::SetPlaneData(drmModeAtomicReq* property_set, - uint32_t crtc_id, - uint32_t framebuffer, - const gfx::Rect& crtc_rect, - const gfx::Rect& src_rect) { +bool HardwareDisplayPlaneAtomic::SetPlaneData( + drmModeAtomicReq* property_set, + uint32_t crtc_id, + uint32_t framebuffer, + const gfx::Rect& crtc_rect, + const gfx::Rect& src_rect, + const gfx::OverlayTransform transform) { int plane_set_succeeded = drmModeAtomicAddProperty(property_set, plane_id_, crtc_prop_.id, crtc_id) && @@ -76,7 +110,10 @@ drmModeAtomicAddProperty(property_set, plane_id_, src_w_prop_.id, src_rect.width()) && drmModeAtomicAddProperty(property_set, plane_id_, src_h_prop_.id, - src_rect.height()); + src_rect.height()) && + drmModeAtomicAddProperty( + property_set, plane_id_, rotation_prop_.id, + OverlayTransformToDrmRotationPropertyValue(transform)); if (!plane_set_succeeded) { PLOG(ERROR) << "Failed to set plane data"; return false; @@ -87,16 +124,18 @@ bool HardwareDisplayPlaneAtomic::InitializeProperties( DrmDevice* drm, const ScopedDrmObjectPropertyPtr& plane_props) { - bool props_init = crtc_prop_.Initialize(drm, kCrtcPropName, plane_props) && - fb_prop_.Initialize(drm, kFbPropName, plane_props) && - crtc_x_prop_.Initialize(drm, kCrtcXPropName, plane_props) && - crtc_y_prop_.Initialize(drm, kCrtcYPropName, plane_props) && - crtc_w_prop_.Initialize(drm, kCrtcWPropName, plane_props) && - crtc_h_prop_.Initialize(drm, kCrtcHPropName, plane_props) && - src_x_prop_.Initialize(drm, kSrcXPropName, plane_props) && - src_y_prop_.Initialize(drm, kSrcYPropName, plane_props) && - src_w_prop_.Initialize(drm, kSrcWPropName, plane_props) && - src_h_prop_.Initialize(drm, kSrcHPropName, plane_props); + bool props_init = + crtc_prop_.Initialize(drm, kCrtcPropName, plane_props) && + fb_prop_.Initialize(drm, kFbPropName, plane_props) && + crtc_x_prop_.Initialize(drm, kCrtcXPropName, plane_props) && + crtc_y_prop_.Initialize(drm, kCrtcYPropName, plane_props) && + crtc_w_prop_.Initialize(drm, kCrtcWPropName, plane_props) && + crtc_h_prop_.Initialize(drm, kCrtcHPropName, plane_props) && + src_x_prop_.Initialize(drm, kSrcXPropName, plane_props) && + src_y_prop_.Initialize(drm, kSrcYPropName, plane_props) && + src_w_prop_.Initialize(drm, kSrcWPropName, plane_props) && + src_h_prop_.Initialize(drm, kSrcHPropName, plane_props) && + rotation_prop_.Initialize(drm, kRotationPropName, plane_props); if (!props_init) { LOG(ERROR) << "Unable to get plane properties.";
diff --git a/ui/ozone/platform/drm/gpu/hardware_display_plane_atomic.h b/ui/ozone/platform/drm/gpu/hardware_display_plane_atomic.h index b9c694df..5d58a46 100644 --- a/ui/ozone/platform/drm/gpu/hardware_display_plane_atomic.h +++ b/ui/ozone/platform/drm/gpu/hardware_display_plane_atomic.h
@@ -5,6 +5,7 @@ #ifndef UI_OZONE_PLATFORM_DRM_GPU_HARDWARE_DISPLAY_PLANE_ATOMIC_H_ #define UI_OZONE_PLATFORM_DRM_GPU_HARDWARE_DISPLAY_PLANE_ATOMIC_H_ +#include "ui/gfx/overlay_transform.h" #include "ui/ozone/platform/drm/gpu/hardware_display_plane.h" #include <stdint.h> @@ -28,7 +29,8 @@ uint32_t crtc_id, uint32_t framebuffer, const gfx::Rect& crtc_rect, - const gfx::Rect& src_rect); + const gfx::Rect& src_rect, + const gfx::OverlayTransform transform); void set_crtc(CrtcController* crtc) { crtc_ = crtc; } CrtcController* crtc() const { return crtc_; } @@ -56,6 +58,7 @@ Property src_y_prop_; Property src_w_prop_; Property src_h_prop_; + Property rotation_prop_; CrtcController* crtc_ = nullptr; };
diff --git a/ui/ozone/platform/drm/gpu/hardware_display_plane_manager_atomic.cc b/ui/ozone/platform/drm/gpu/hardware_display_plane_manager_atomic.cc index 17bdd2a..a71335e 100644 --- a/ui/ozone/platform/drm/gpu/hardware_display_plane_manager_atomic.cc +++ b/ui/ozone/platform/drm/gpu/hardware_display_plane_manager_atomic.cc
@@ -46,7 +46,8 @@ HardwareDisplayPlaneAtomic* atomic_plane = static_cast<HardwareDisplayPlaneAtomic*>(plane); atomic_plane->SetPlaneData(plane_list->atomic_property_set.get(), 0, 0, - gfx::Rect(), gfx::Rect()); + gfx::Rect(), gfx::Rect(), + gfx::OVERLAY_TRANSFORM_NONE); } } @@ -98,9 +99,9 @@ uint32_t framebuffer_id = overlay.z_order ? overlay.buffer->GetFramebufferId() : overlay.buffer->GetOpaqueFramebufferId(); - if (!atomic_plane->SetPlaneData(plane_list->atomic_property_set.get(), - crtc_id, framebuffer_id, - overlay.display_bounds, src_rect)) { + if (!atomic_plane->SetPlaneData( + plane_list->atomic_property_set.get(), crtc_id, framebuffer_id, + overlay.display_bounds, src_rect, overlay.plane_transform)) { LOG(ERROR) << "Failed to set plane properties"; return false; }
diff --git a/ui/views/BUILD.gn b/ui/views/BUILD.gn index e83f5b9..c5fdc56 100644 --- a/ui/views/BUILD.gn +++ b/ui/views/BUILD.gn
@@ -876,6 +876,7 @@ "controls/native/native_view_host_unittest.cc", "controls/prefix_selector_unittest.cc", "controls/progress_bar_unittest.cc", + "controls/resize_area_unittest.cc", "controls/scroll_view_unittest.cc", "controls/scrollbar/scrollbar_unittest.cc", "controls/slider_unittest.cc",
diff --git a/ui/views/controls/resize_area.cc b/ui/views/controls/resize_area.cc index 3698078..06c0325 100644 --- a/ui/views/controls/resize_area.cc +++ b/ui/views/controls/resize_area.cc
@@ -14,9 +14,6 @@ const char ResizeArea::kViewClassName[] = "ResizeArea"; -//////////////////////////////////////////////////////////////////////////////// -// ResizeArea - ResizeArea::ResizeArea(ResizeAreaDelegate* delegate) : delegate_(delegate), initial_position_(0) { @@ -34,17 +31,25 @@ : gfx::kNullCursor; } +void ResizeArea::OnGestureEvent(ui::GestureEvent* event) { + if (event->type() == ui::ET_GESTURE_TAP_DOWN) { + SetInitialPosition(event->x()); + event->SetHandled(); + } else if (event->type() == ui::ET_GESTURE_SCROLL_BEGIN || + event->type() == ui::ET_GESTURE_SCROLL_UPDATE) { + ReportResizeAmount(event->x(), false); + event->SetHandled(); + } else if (event->type() == ui::ET_GESTURE_END) { + ReportResizeAmount(event->x(), true); + event->SetHandled(); + } +} + bool ResizeArea::OnMousePressed(const ui::MouseEvent& event) { if (!event.IsOnlyLeftMouseButton()) return false; - // The resize area obviously will move once you start dragging so we need to - // convert coordinates to screen coordinates so that we don't lose our - // bearings. - gfx::Point point(event.x(), 0); - View::ConvertPointToScreen(this, &point); - initial_position_ = point.x(); - + SetInitialPosition(event.x()); return true; } @@ -76,4 +81,10 @@ last_update); } +void ResizeArea::SetInitialPosition(int event_x) { + gfx::Point point(event_x, 0); + View::ConvertPointToScreen(this, &point); + initial_position_ = point.x(); +} + } // namespace views
diff --git a/ui/views/controls/resize_area.h b/ui/views/controls/resize_area.h index 171c80565..31dc6e3 100644 --- a/ui/views/controls/resize_area.h +++ b/ui/views/controls/resize_area.h
@@ -14,11 +14,7 @@ class ResizeAreaDelegate; -//////////////////////////////////////////////////////////////////////////////// -// // An invisible area that acts like a horizontal resizer. -// -//////////////////////////////////////////////////////////////////////////////// class VIEWS_EXPORT ResizeArea : public View { public: static const char kViewClassName[]; @@ -26,9 +22,10 @@ explicit ResizeArea(ResizeAreaDelegate* delegate); ~ResizeArea() override; - // Overridden from views::View: + // views::View: const char* GetClassName() const override; gfx::NativeCursor GetCursor(const ui::MouseEvent& event) override; + void OnGestureEvent(ui::GestureEvent* event) override; bool OnMousePressed(const ui::MouseEvent& event) override; bool OnMouseDragged(const ui::MouseEvent& event) override; void OnMouseReleased(const ui::MouseEvent& event) override; @@ -40,10 +37,16 @@ // directionality. void ReportResizeAmount(int resize_amount, bool last_update); + // Converts |event_x| to screen coordinates and sets |initial_position_| to + // this value. + void SetInitialPosition(int event_x); + // The delegate to notify when we have updates. ResizeAreaDelegate* delegate_; - // The mouse position at start (in screen coordinates). + // The event's x-position at the start of the resize operation. The resize + // area will move while being dragged, so |initial_position_| is represented + // in screen coordinates so that we don't lose our bearings. int initial_position_; DISALLOW_COPY_AND_ASSIGN(ResizeArea);
diff --git a/ui/views/controls/resize_area_delegate.h b/ui/views/controls/resize_area_delegate.h index cc5e133d..ee5e57b 100644 --- a/ui/views/controls/resize_area_delegate.h +++ b/ui/views/controls/resize_area_delegate.h
@@ -16,7 +16,7 @@ // positive (depending on direction of dragging and flips according to // locale directionality: dragging to the left in LTR locales gives negative // |resize_amount| but positive amount for RTL). |done_resizing| is true if - // the user has released the mouse. + // the user has released the pointer (mouse, stylus, touch, etc.). virtual void OnResize(int resize_amount, bool done_resizing) = 0; protected:
diff --git a/ui/views/controls/resize_area_unittest.cc b/ui/views/controls/resize_area_unittest.cc new file mode 100644 index 0000000..0dd9107 --- /dev/null +++ b/ui/views/controls/resize_area_unittest.cc
@@ -0,0 +1,200 @@ +// 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 "ui/views/controls/resize_area.h" + +#include <memory> + +#include "testing/gtest/include/gtest/gtest.h" +#include "ui/aura/window.h" +#include "ui/events/test/event_generator.h" +#include "ui/views/controls/resize_area_delegate.h" +#include "ui/views/test/views_test_base.h" +#include "ui/views/view.h" +#include "ui/views/widget/widget.h" + +namespace { +// Constants used by the ResizeAreaTest.SuccessfulGestureDrag test to simulate +// a gesture drag by |kGestureScrollDistance| resulting from +// |kGestureScrollSteps| ui::ET_GESTURE_SCROLL_UPDATE events being delivered. +const int kGestureScrollDistance = 100; +const int kGestureScrollSteps = 4; +const int kDistancePerGestureScrollUpdate = + kGestureScrollDistance / kGestureScrollSteps; +} + +namespace views { + +// Testing delegate used by ResizeAreaTest. +class TestResizeAreaDelegate : public ResizeAreaDelegate { + public: + TestResizeAreaDelegate(); + ~TestResizeAreaDelegate() override; + + // ResizeAreaDelegate: + void OnResize(int resize_amount, bool done_resizing) override; + + int resize_amount() { return resize_amount_; } + bool done_resizing() { return done_resizing_; } + bool on_resize_called() { return on_resize_called_; } + + private: + int resize_amount_; + bool done_resizing_; + bool on_resize_called_; + + DISALLOW_COPY_AND_ASSIGN(TestResizeAreaDelegate); +}; + +TestResizeAreaDelegate::TestResizeAreaDelegate() + : resize_amount_(0), done_resizing_(false), on_resize_called_(false) {} + +TestResizeAreaDelegate::~TestResizeAreaDelegate() {} + +void TestResizeAreaDelegate::OnResize(int resize_amount, bool done_resizing) { + resize_amount_ = resize_amount; + done_resizing_ = done_resizing; + on_resize_called_ = true; +} + +// Test fixture for testing the ResizeArea class. +class ResizeAreaTest : public ViewsTestBase { + public: + ResizeAreaTest(); + ~ResizeAreaTest() override; + + // Callback used by the SuccessfulGestureDrag test. + void ProcessGesture(ui::EventType type, const gfx::Vector2dF& delta); + + protected: + // testing::Test: + void SetUp() override; + void TearDown() override; + + ui::test::EventGenerator* event_generator() { return event_generator_.get(); } + + int resize_amount() { return delegate_->resize_amount(); } + bool done_resizing() { return delegate_->done_resizing(); } + bool on_resize_called() { return delegate_->on_resize_called(); } + views::Widget* widget() { return widget_; } + + private: + TestResizeAreaDelegate* delegate_ = nullptr; + ResizeArea* resize_area_ = nullptr; + views::Widget* widget_ = nullptr; + std::unique_ptr<ui::test::EventGenerator> event_generator_; + + // The number of ui::ET_GESTURE_SCROLL_UPDATE events seen by + // ProcessGesture(). + int gesture_scroll_updates_seen_ = 0; + + DISALLOW_COPY_AND_ASSIGN(ResizeAreaTest); +}; + +ResizeAreaTest::ResizeAreaTest() {} + +ResizeAreaTest::~ResizeAreaTest() {} + +void ResizeAreaTest::ProcessGesture(ui::EventType type, + const gfx::Vector2dF& delta) { + if (type == ui::ET_GESTURE_SCROLL_BEGIN) { + EXPECT_FALSE(done_resizing()); + EXPECT_FALSE(on_resize_called()); + } else if (type == ui::ET_GESTURE_SCROLL_UPDATE) { + gesture_scroll_updates_seen_++; + EXPECT_EQ(kDistancePerGestureScrollUpdate * gesture_scroll_updates_seen_, + resize_amount()); + EXPECT_FALSE(done_resizing()); + EXPECT_TRUE(on_resize_called()); + } else if (type == ui::ET_GESTURE_SCROLL_END) { + EXPECT_TRUE(done_resizing()); + } +} + +void ResizeAreaTest::SetUp() { + views::ViewsTestBase::SetUp(); + + delegate_ = new TestResizeAreaDelegate; + resize_area_ = new ResizeArea(delegate_); + + gfx::Size size(10, 10); + resize_area_->SetBounds(0, 0, size.width(), size.height()); + + views::Widget::InitParams init_params( + CreateParams(views::Widget::InitParams::TYPE_WINDOW_FRAMELESS)); + init_params.bounds = gfx::Rect(size); + + widget_ = new views::Widget(); + widget_->Init(init_params); + widget_->SetContentsView(resize_area_); + widget_->Show(); + + event_generator_.reset( + new ui::test::EventGenerator(widget_->GetNativeWindow())); +} + +void ResizeAreaTest::TearDown() { + if (widget_ && !widget_->IsClosed()) + widget_->Close(); + + views::ViewsTestBase::TearDown(); +} + +// TODO(tdanderson): Enable these tests on OSX. See crbug.com/710475. +#if !defined(OS_MACOSX) +// Verifies the correct calls have been made to +// TestResizeAreaDelegate::OnResize() for a sequence of mouse events +// corresponding to a successful resize operation. +TEST_F(ResizeAreaTest, SuccessfulMouseDrag) { + event_generator()->MoveMouseToCenterOf(widget()->GetNativeView()); + event_generator()->PressLeftButton(); + + const int kFirstDragAmount = -5; + event_generator()->MoveMouseBy(kFirstDragAmount, 0); + EXPECT_EQ(kFirstDragAmount, resize_amount()); + EXPECT_FALSE(done_resizing()); + EXPECT_TRUE(on_resize_called()); + + const int kSecondDragAmount = 17; + event_generator()->MoveMouseBy(kSecondDragAmount, 0); + EXPECT_EQ(kFirstDragAmount + kSecondDragAmount, resize_amount()); + EXPECT_FALSE(done_resizing()); + + event_generator()->ReleaseLeftButton(); + EXPECT_EQ(kFirstDragAmount + kSecondDragAmount, resize_amount()); + EXPECT_TRUE(done_resizing()); +} + +// Verifies that no resize is performed when attempting to resize using the +// right mouse button. +TEST_F(ResizeAreaTest, FailedMouseDrag) { + event_generator()->MoveMouseToCenterOf(widget()->GetNativeView()); + event_generator()->PressRightButton(); + + const int kDragAmount = 18; + event_generator()->MoveMouseBy(kDragAmount, 0); + EXPECT_EQ(0, resize_amount()); +} + +// Verifies the correct calls have been made to +// TestResizeAreaDelegate::OnResize() for a sequence of gesture events +// corresponding to a successful resize operation. +TEST_F(ResizeAreaTest, SuccessfulGestureDrag) { + gfx::Point start = widget()->GetNativeView()->bounds().CenterPoint(); + event_generator()->GestureScrollSequenceWithCallback( + start, gfx::Point(start.x() + kGestureScrollDistance, start.y()), + base::TimeDelta::FromMilliseconds(200), kGestureScrollSteps, + base::Bind(&ResizeAreaTest::ProcessGesture, base::Unretained(this))); +} + +// Verifies that no resize is performed on a gesture tap. +TEST_F(ResizeAreaTest, NoDragOnGestureTap) { + event_generator()->GestureTapAt( + widget()->GetNativeView()->bounds().CenterPoint()); + + EXPECT_EQ(0, resize_amount()); +} +#endif // !defined(OS_MACOSX) + +} // namespace views
diff --git a/ui/views/controls/tree/tree_view.cc b/ui/views/controls/tree/tree_view.cc index 2bfbd210..31b8fde8 100644 --- a/ui/views/controls/tree/tree_view.cc +++ b/ui/views/controls/tree/tree_view.cc
@@ -729,6 +729,8 @@ -(empty_editor_size_.height() - font_list_.GetHeight()) / 2); // Give a little extra space for editing. row_bounds.set_width(row_bounds.width() + 50); + // Scroll as necessary to ensure that the editor is visible. + ScrollRectToVisible(row_bounds); editor_->SetBoundsRect(row_bounds); editor_->Layout(); }
diff --git a/ui/views/win/hwnd_message_handler.cc b/ui/views/win/hwnd_message_handler.cc index 94ba713..8d690aac 100644 --- a/ui/views/win/hwnd_message_handler.cc +++ b/ui/views/win/hwnd_message_handler.cc
@@ -1690,6 +1690,13 @@ // We are now creating a fake mouse event with pointer type of pen from // the WM_POINTER message and then setting up an associated pointer // details in the MouseEvent which contains the pen's information. + ui::EventPointerType input_type = ui::EventPointerType::POINTER_TYPE_PEN; + // TODO(lanwei): penFlags of PEN_FLAG_INVERTED may also indicate we are using + // an eraser, but it is under debate. Please see + // https://github.com/w3c/pointerevents/issues/134/. + if (pointer_pen_info.penFlags & PEN_FLAG_ERASER) + input_type = ui::EventPointerType::POINTER_TYPE_ERASER; + float pressure = static_cast<float>(pointer_pen_info.pressure) / 1024; float rotation = pointer_pen_info.rotation; int tilt_x = pointer_pen_info.tiltX; @@ -1745,9 +1752,8 @@ ui::MouseEvent event(event_type, point, point, base::TimeTicks::Now(), flag, flag); ui::PointerDetails pointer_details( - ui::EventPointerType::POINTER_TYPE_PEN, pointer_id, - /* radius_x */ 0.0f, /* radius_y */ 0.0f, pressure, tilt_x, tilt_y, - /* tangential_pressure */ 0.0f, rotation); + input_type, pointer_id, /* radius_x */ 0.0f, /* radius_y */ 0.0f, + pressure, tilt_x, tilt_y, /* tangential_pressure */ 0.0f, rotation); event.set_pointer_details(pointer_details); event.SetClickCount(click_count);
diff --git a/ui/webui/resources/cr_elements/cr_action_menu/cr_action_menu.js b/ui/webui/resources/cr_elements/cr_action_menu/cr_action_menu.js index 9a94cfa..42b0065 100644 --- a/ui/webui/resources/cr_elements/cr_action_menu/cr_action_menu.js +++ b/ui/webui/resources/cr_elements/cr_action_menu/cr_action_menu.js
@@ -173,6 +173,7 @@ this.style.right = ''; this.style.top = ''; + this.anchorElement_.scrollIntoViewIfNeeded(); this.showModal(); var rect = this.anchorElement_.getBoundingClientRect();
diff --git a/ui/webui/resources/html/md_select_css.html b/ui/webui/resources/html/md_select_css.html index 7217ff3..59f97c7e 100644 --- a/ui/webui/resources/html/md_select_css.html +++ b/ui/webui/resources/html/md_select_css.html
@@ -4,26 +4,29 @@ <dom-module id="md-select"> <template> <style> + .md-select, + .md-select-underline { + --md-side-padding: 12px; + } + .md-select { --md-arrow-width: 0.9em; -webkit-appearance: none; /* Ensure that the text does not overlap with the down arrow. */ - -webkit-padding-end: calc(var(--md-arrow-width) * 1.8); + -webkit-padding-end: calc(var(--md-side-padding) + + var(--md-arrow-width) * 1.8); + -webkit-padding-start: var(--md-side-padding); background: url( - chrome://resources/images/arrow_down.svg) 97% center no-repeat; + chrome://resources/images/arrow_down.svg) + calc(97% - var(--md-side-padding)) center no-repeat; background-size: var(--md-arrow-width); - border-bottom: 1px solid var(--paper-grey-300); - border-left: none; - /* Override Mac's default border-radius */ - border-radius: 0; - border-right: none; - border-top: none; + border: none; color: var(--primary-text-color); cursor: pointer; font-family: inherit; font-size: inherit; outline: none; - padding-bottom: 3px; + padding-bottom: 4px; padding-top: 3px; width: var(--md-select-width, 200px); } @@ -37,20 +40,35 @@ } :host-context([dir=rtl]) .md-select { - background-position-x: 3%; + background-position-x: calc(var(--md-side-padding) + 3%); } + /* Persistent underline */ .md-select-underline { - border-top: 2px solid var(--google-blue-500); + border-top: 1px solid var(--paper-grey-300); display: block; - position: relative; - top: -1px; + margin: 0 var(--md-side-padding); + } + + /* Focus underline */ + .md-select-underline::after { + border-top: 2px solid var(--google-blue-500); + content: ''; + display: block; transform: scale3d(0, 1, 1); transition: transform 200ms ease-in; - width: 100%; } - .md-select:focus + .md-select-underline { + /* Force the thicker "focus" underline to be properly overlapping with the + * "persistent" underline, and also make it visible by 1px while the + * <select> is expanded. */ + .md-select-underline, + .md-select-underline::after { + position: relative; + top: -1px; + } + + .md-select:focus + .md-select-underline::after { transform: scale3d(1, 1, 1); transition: transform 200ms ease-out; }