diff --git a/DEPS b/DEPS index 863dc7e..e07c2f2 100644 --- a/DEPS +++ b/DEPS
@@ -253,19 +253,19 @@ # 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': '88f90513a9ba47a9e3e0c09ab2403fa6b4e59cfc', + 'skia_revision': '27be14f2ca99bb8800b356461a5077af7989881d', # 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': 'c4193466599b4c033bdb78e3a7e040ae477700b6', + 'v8_revision': '412fc23ff5587db033f7ff3612b476b9c90c0d31', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling ANGLE # and whatever else without interference from each other. - 'angle_revision': '5e0c51ce7c09ae8cc255c61ef871a4f9f87351d6', + 'angle_revision': '48c86e1b38439aa0ae127dff3d1076056f9466f2', # 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': '3c9e2a377a645806e91723bda65e7236b3a15a00', + 'swiftshader_revision': '89bd767fec5336b717cd982af6eef524293f360c', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling PDFium # and whatever else without interference from each other. @@ -328,7 +328,7 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling devtools-frontend # and whatever else without interference from each other. - 'devtools_frontend_revision': '93b0c2cf90584dd67baa82d85f8225763876d69a', + 'devtools_frontend_revision': '133980b8824c3122f28683d783f45ff52069ee65', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling libprotobuf-mutator # and whatever else without interference from each other. @@ -368,7 +368,7 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling feed # and whatever else without interference from each other. - 'dawn_revision': '896688dd64e9f43796a11db450a690bc8ad94ff0', + 'dawn_revision': '5b9b9867cde3fe452ab97d8afcc728f4f564b5d8', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling feed # and whatever else without interference from each other. @@ -380,7 +380,7 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling libexpat # and whatever else without interference from each other. - 'libexpat_revision': '65a21f2b2a306d29b44e70264aca948aa0454219', + 'libexpat_revision': '53fbdf5b8925a426e1b41a9e09b833986b87524e', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling wuffs # and whatever else without interference from each other. @@ -435,7 +435,7 @@ 'libcxx_revision': '79a2e924d96e2fc1e4b937c42efd08898fa472d7', # GN CIPD package version. - 'gn_version': 'git_revision:d7c2209cebcfe37f46dba7be4e1a7000ffc342fb', + 'gn_version': 'git_revision:46f94b5a7f5527b5d7ef57271d3e9447a65e22ac', } # Only these hosts are allowed for dependencies in this DEPS file. @@ -704,7 +704,7 @@ Var('chromium_git') + '/external/github.com/toji/webvr.info.git' + '@' + 'c58ae99b9ff9e2aa4c524633519570bf33536248', 'src/docs/website': { - 'url': Var('chromium_git') + '/website.git' + '@' + 'e934ac434eb2953e18c857adecdc06d9f084ad72', + 'url': Var('chromium_git') + '/website.git' + '@' + '0857d2c1df75cb63e6e636f7f5638b801b6b8ad3', }, 'src/ios/third_party/earl_grey2/src': { @@ -1131,7 +1131,7 @@ }, 'src/third_party/depot_tools': - Var('chromium_git') + '/chromium/tools/depot_tools.git' + '@' + '8edc960e9acbaedbff28e323e77a4129817266b3', + Var('chromium_git') + '/chromium/tools/depot_tools.git' + '@' + '1b4881c9300a81bac80eace84caa2c10c2e41fa5', 'src/third_party/devtools-frontend/src': Var('chromium_git') + '/devtools/devtools-frontend' + '@' + Var('devtools_frontend_revision'), @@ -1183,7 +1183,7 @@ Var('chromium_git') + '/external/github.com/google/gemmlowp.git' + '@' + '13d57703abca3005d97b19df1f2db731607a7dc2', 'src/third_party/grpc/src': { - 'url': Var('chromium_git') + '/external/github.com/grpc/grpc.git' + '@' + '754913545189b819829284b79ac5a4d31fddbdcc', + 'url': Var('chromium_git') + '/external/github.com/grpc/grpc.git' + '@' + 'f8a909e76fcd947949502832a7ab8e2cba2b8e27', }, 'src/third_party/freetype/src': @@ -1592,7 +1592,7 @@ 'packages': [ { 'package': 'fuchsia/third_party/android/aemu/release/linux-amd64', - 'version': '5G3S33FRzpsxXGkFGIIeXWqeDIZy92MxmfIV-egyMzkC' + 'version': 'zB8Bv2er0E-n3l3q1QNaqEtzd8Mr4HhrfxrwsBqzDBwC' }, ], 'condition': 'host_os == "linux" and checkout_fuchsia', @@ -1735,7 +1735,7 @@ Var('chromium_git') + '/external/github.com/gpuweb/cts.git' + '@' + '2860185ed0581ee6b884dfb727a42e82b8b7e7a5', 'src/third_party/webrtc': - Var('webrtc_git') + '/src.git' + '@' + '57869dae117d164f66c0c3cb75cb9c078e07c922', + Var('webrtc_git') + '/src.git' + '@' + 'fdaa77cd218a5190a7a0e42107d002e55f46a5e2', 'src/third_party/libgifcodec': Var('skia_git') + '/libgifcodec' + '@'+ Var('libgifcodec_revision'), @@ -1805,7 +1805,7 @@ Var('chromium_git') + '/v8/v8.git' + '@' + Var('v8_revision'), 'src-internal': { - 'url': 'https://chrome-internal.googlesource.com/chrome/src-internal.git@0a9a1b9ea86d5637fa831142f4ee35f5db54dadc', + 'url': 'https://chrome-internal.googlesource.com/chrome/src-internal.git@2a3fe4bc34d596d697b17a9ed5a10db4417c4d5f', 'condition': 'checkout_src_internal', },
diff --git a/WATCHLISTS b/WATCHLISTS index 145b439..348c1067a 100644 --- a/WATCHLISTS +++ b/WATCHLISTS
@@ -2595,7 +2595,6 @@ 'libaom': ['fgalligan@chromium.org', 'jianj@chromium.org', 'jzern@chromium.org', - 'kyslov@google.com', 'marpan@chromium.org', 'tomfinegan@chromium.org'], 'libvpx': ['fgalligan@chromium.org',
diff --git a/android_webview/BUILD.gn b/android_webview/BUILD.gn index 2f4afc76..5f6e16e 100644 --- a/android_webview/BUILD.gn +++ b/android_webview/BUILD.gn
@@ -731,6 +731,33 @@ jar_excluded_patterns = [ "*/PlatformServiceBridgeImpl.class" ] } +android_aidl("js_sandbox_aidl") { + import_include = [ "java/src" ] + sources = [ + "java/src/org/chromium/android_webview/js/common/IJsSandboxContext.aidl", + "java/src/org/chromium/android_webview/js/common/IJsSandboxContextCallback.aidl", + "java/src/org/chromium/android_webview/js/common/IJsSandboxService.aidl", + ] +} + +android_library("js_sandbox_aidl_java") { + srcjar_deps = [ ":js_sandbox_aidl" ] +} + +android_library("js_sandbox_java") { + sources = [ + "java/src/org/chromium/android_webview/js/browser/AwJsContext.java", + "java/src/org/chromium/android_webview/js/browser/AwJsSandbox.java", + "java/src/org/chromium/android_webview/js/renderer/JsSandboxContext.java", + "java/src/org/chromium/android_webview/js/renderer/JsSandboxService.java", + ] + + deps = [ + ":js_sandbox_aidl_java", + "//base:base_java", + ] +} + # This target compiles the implementation of PlatformServiceBridge for AOSP targets. android_library("platform_service_bridge_upstream_implementation_java") { sources = [ "java/src/org/chromium/android_webview/common/PlatformServiceBridgeImpl.java" ]
diff --git a/android_webview/browser/gfx/begin_frame_source_webview.cc b/android_webview/browser/gfx/begin_frame_source_webview.cc index b6a26df..5294d2ac 100644 --- a/android_webview/browser/gfx/begin_frame_source_webview.cc +++ b/android_webview/browser/gfx/begin_frame_source_webview.cc
@@ -119,6 +119,11 @@ parent_->AddBeginFrameCompletionCallback(std::move(callback)); } +const viz::BeginFrameArgs& +BeginFrameSourceWebView::LastDispatchedBeginFrameArgs() { + return parent_observer_->LastUsedBeginFrameArgs(); +} + // static RootBeginFrameSourceWebView* RootBeginFrameSourceWebView::GetInstance() { static base::NoDestructor<RootBeginFrameSourceWebView> instance;
diff --git a/android_webview/browser/gfx/begin_frame_source_webview.h b/android_webview/browser/gfx/begin_frame_source_webview.h index 9abd8f7..3fabcc69 100644 --- a/android_webview/browser/gfx/begin_frame_source_webview.h +++ b/android_webview/browser/gfx/begin_frame_source_webview.h
@@ -36,6 +36,9 @@ // Schedules BeginFrame completion callback on root begin frame source. virtual void AddBeginFrameCompletionCallback(base::OnceClosure callback); + // Returns last dispatched begin frame args. + const viz::BeginFrameArgs& LastDispatchedBeginFrameArgs(); + protected: void ObserveBeginFrameSource(viz::BeginFrameSource* begin_frame_source);
diff --git a/android_webview/browser/gfx/browser_view_renderer.cc b/android_webview/browser/gfx/browser_view_renderer.cc index 5302d1c..0979837 100644 --- a/android_webview/browser/gfx/browser_view_renderer.cc +++ b/android_webview/browser/gfx/browser_view_renderer.cc
@@ -328,7 +328,8 @@ std::unique_ptr<ChildFrame> child_frame = std::make_unique<ChildFrame>( std::move(future), frame_sink_id_, viewport_size_for_tile_priority, external_draw_constraints_.transform, offscreen_pre_raster_, dip_scale_, - std::move(requests), did_invalidate); + std::move(requests), did_invalidate, + begin_frame_source_->LastDispatchedBeginFrameArgs()); ReturnUnusedResource( current_compositor_frame_consumer_->SetFrameOnUI(std::move(child_frame)));
diff --git a/android_webview/browser/gfx/child_frame.cc b/android_webview/browser/gfx/child_frame.cc index ecab0ea..9109b634 100644 --- a/android_webview/browser/gfx/child_frame.cc +++ b/android_webview/browser/gfx/child_frame.cc
@@ -20,7 +20,8 @@ bool offscreen_pre_raster, float device_scale_factor, CopyOutputRequestQueue copy_requests, - bool did_invalidate) + bool did_invalidate, + const viz::BeginFrameArgs& begin_frame_args) : frame_future(std::move(frame_future)), frame_sink_id(frame_sink_id), viewport_size_for_tile_priority(viewport_size_for_tile_priority), @@ -28,7 +29,8 @@ offscreen_pre_raster(offscreen_pre_raster), device_scale_factor(device_scale_factor), copy_requests(std::move(copy_requests)), - did_invalidate(did_invalidate) {} + did_invalidate(did_invalidate), + begin_frame_args(begin_frame_args) {} ChildFrame::~ChildFrame() { }
diff --git a/android_webview/browser/gfx/child_frame.h b/android_webview/browser/gfx/child_frame.h index e335e22..e5068cc 100644 --- a/android_webview/browser/gfx/child_frame.h +++ b/android_webview/browser/gfx/child_frame.h
@@ -9,6 +9,7 @@ #include <vector> #include "base/containers/circular_deque.h" +#include "components/viz/common/frame_sinks/begin_frame_args.h" #include "components/viz/common/surfaces/frame_sink_id.h" #include "components/viz/common/surfaces/surface_id.h" #include "content/public/browser/android/synchronous_compositor.h" @@ -36,7 +37,8 @@ bool offscreen_pre_raster, float device_scale_factor, CopyOutputRequestQueue copy_requests, - bool did_invalidate); + bool did_invalidate, + const viz::BeginFrameArgs& begin_frame_args); ChildFrame(const ChildFrame&) = delete; ChildFrame& operator=(const ChildFrame&) = delete; @@ -66,6 +68,13 @@ // Used for metrics, indicates that we invalidated for this frame. const bool did_invalidate; + + // Latest BeginFrameArgs this frame is being presented for so far. Normally + // this corresponds to the begin frame of the current draw cycle (BeginFrame + // => DrawOnUI => Sync => DrawOnRT), but in cases when DrawOnRT doesn't happen + // (e.g webview is offscreen) this will be updated to more recent draws. + // See: `HardwareRenderer::WaitAndPruneFrameQueue()` for details. + viz::BeginFrameArgs begin_frame_args; }; using ChildFrameQueue = base::circular_deque<std::unique_ptr<ChildFrame>>;
diff --git a/android_webview/browser/gfx/hardware_renderer.cc b/android_webview/browser/gfx/hardware_renderer.cc index 0037528..19ab334 100644 --- a/android_webview/browser/gfx/hardware_renderer.cc +++ b/android_webview/browser/gfx/hardware_renderer.cc
@@ -194,6 +194,11 @@ from->clear(); } +viz::BeginFrameArgs NewerBeginFrameArgs(const viz::BeginFrameArgs& args1, + const viz::BeginFrameArgs& args2) { + return args1.frame_id.IsNextInSequenceTo(args2.frame_id) ? args1 : args2; +} + } // namespace // static @@ -222,6 +227,11 @@ child_frames.pop_back(); MoveCopyRequests(&frame->copy_requests, &child_frames[remaining_frame_index]->copy_requests); + + // If we're dropping frames at the end, we need update begin frame args. + child_frames[remaining_frame_index]->begin_frame_args = NewerBeginFrameArgs( + child_frames[remaining_frame_index]->begin_frame_args, + frame->begin_frame_args); DCHECK(!frame->frame); } DCHECK_EQ(static_cast<size_t>(remaining_frame_index), @@ -233,6 +243,9 @@ child_frames.pop_front(); MoveCopyRequests(&frame->copy_requests, &child_frames.back()->copy_requests); + // We shouldn't drop newer frames. + DCHECK(!frame->begin_frame_args.frame_id.IsNextInSequenceTo( + child_frames.back()->begin_frame_args.frame_id)); if (frame->frame) pruned_frames.emplace_back(std::move(frame)); }
diff --git a/android_webview/browser/gfx/test/invalidate_test.cc b/android_webview/browser/gfx/test/invalidate_test.cc index 2deb663..e01e95a 100644 --- a/android_webview/browser/gfx/test/invalidate_test.cc +++ b/android_webview/browser/gfx/test/invalidate_test.cc
@@ -329,7 +329,7 @@ auto child_frame = std::make_unique<ChildFrame>( future, kRootClientSinkId, kFrameSize, gfx::Transform(), false, 1.0f, - CopyOutputRequestQueue(), /*did_invalidate=*/invalidated); + CopyOutputRequestQueue(), /*did_invalidate=*/invalidated, args); return child_frame; }
diff --git a/android_webview/java/src/org/chromium/android_webview/common/ProductionSupportedFlagList.java b/android_webview/java/src/org/chromium/android_webview/common/ProductionSupportedFlagList.java index 9675aecf..cb4c0e8 100644 --- a/android_webview/java/src/org/chromium/android_webview/common/ProductionSupportedFlagList.java +++ b/android_webview/java/src/org/chromium/android_webview/common/ProductionSupportedFlagList.java
@@ -286,5 +286,7 @@ "Makes WebRtcTimer coalesce delayed tasks on metronome ticks."), Flag.baseFeature(BlinkFeatures.VIEWPORT_HEIGHT_CLIENT_HINT_HEADER, "Enables the use of sec-ch-viewport-height client hint."), + Flag.baseFeature(BlinkFeatures.USER_AGENT_OVERRIDE_EXPERIMENT, + "Collects metrics on when the User-Agent string is overridden and how"), }; }
diff --git a/android_webview/java/src/org/chromium/android_webview/js/browser/AwJsContext.java b/android_webview/java/src/org/chromium/android_webview/js/browser/AwJsContext.java new file mode 100644 index 0000000..0bb958e --- /dev/null +++ b/android_webview/java/src/org/chromium/android_webview/js/browser/AwJsContext.java
@@ -0,0 +1,84 @@ +// Copyright 2022 The Chromium 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.android_webview.js.browser; + +import android.os.Build; +import android.os.RemoteException; + +import org.chromium.android_webview.js.common.IJsSandboxContext; +import org.chromium.android_webview.js.common.IJsSandboxContextCallback; +import org.chromium.base.Log; + +/** Provides a sandboxed execution context. */ +public class AwJsContext implements AutoCloseable { + private static final String TAG = "AwJsContext"; + private IJsSandboxContext mJsContextStub; + private android.util.CloseGuard mGuard; + + /** Used to report the results of the JS evaluation. */ + public interface ExecutionCallback { + void reportResult(String result); + } + + AwJsContext(IJsSandboxContext jsContextStub) { + mJsContextStub = jsContextStub; + if (Build.VERSION.SDK_INT >= 30) { + mGuard = new android.util.CloseGuard(); + mGuard.open("close"); + } + // This should be at the end of the constructor. + } + + /** Evaluates the Javascript code and calls the callback with the result of the execution. */ + public void evaluateJavascript(String code, ExecutionCallback callback) { + if (mJsContextStub == null) { + throw new IllegalStateException( + "Calling evaluateJavascript() after closing the context"); + } + IJsSandboxContextCallback.Stub callbackStub = new IJsSandboxContextCallback.Stub() { + @Override + public void reportResult(String result) { + callback.reportResult(result); + } + }; + try { + mJsContextStub.evaluateJavascript(code, callbackStub); + } catch (RemoteException e) { + throw e.rethrowAsRuntimeException(); + } + } + + @Override + public void close() { + if (mJsContextStub == null) { + return; + } + try { + mJsContextStub.close(); + } catch (RemoteException e) { + Log.e(TAG, "RemoteException was thrown during close()", e); + } + mJsContextStub = null; + if (Build.VERSION.SDK_INT >= 30) { + mGuard.close(); + } + } + + @Override + protected void finalize() throws Throwable { + try { + if (Build.VERSION.SDK_INT >= 30) { + if (mGuard != null) { + mGuard.warnIfOpen(); + } + } + if (mJsContextStub != null) { + close(); + } + } finally { + super.finalize(); + } + } +}
diff --git a/android_webview/java/src/org/chromium/android_webview/js/browser/AwJsSandbox.java b/android_webview/java/src/org/chromium/android_webview/js/browser/AwJsSandbox.java new file mode 100644 index 0000000..b7d8242 --- /dev/null +++ b/android_webview/java/src/org/chromium/android_webview/js/browser/AwJsSandbox.java
@@ -0,0 +1,107 @@ +// Copyright 2022 The Chromium 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.android_webview.js.browser; + +import android.content.ComponentName; +import android.content.Context; +import android.content.Intent; +import android.content.ServiceConnection; +import android.os.IBinder; +import android.os.RemoteException; + +import org.chromium.android_webview.js.common.IJsSandboxContext; +import org.chromium.android_webview.js.common.IJsSandboxService; +import org.chromium.android_webview.js.renderer.JsSandboxService; +import org.chromium.base.ContextUtils; + +/** + * Sandbox that can execute JS in a safe environment. TODO(crbug.com/1297672): Evaluate the thread + * safety of this class and enforce ThreadChecker if needed. Refer crrev.com/c/3466074. + */ +public class AwJsSandbox implements AutoCloseable { + // TODO(crbug.com/1297672): Add capability to this class to support spawning + // different processes as needed. This might require that we have a static + // variable in here that tracks the existing services we are connected to and + // connect to a different one when creating a new object. + private static final String TAG = "AwJsSandbox"; + + private IJsSandboxService mJsSandboxService; + private ConnectionSetup mConnection; + + static class ConnectionSetup implements ServiceConnection { + private ReadyCallback mReadyCallback; + private AwJsSandbox mAwJsSandbox; + + @Override + public void onServiceConnected(ComponentName name, IBinder service) { + IJsSandboxService jsSandboxService = IJsSandboxService.Stub.asInterface(service); + // We are calling this from the main looper for now. + mAwJsSandbox = new AwJsSandbox(this, jsSandboxService); + mReadyCallback.createdConnectedInstance(mAwJsSandbox); + } + + @Override + public void onServiceDisconnected(ComponentName name) { + mAwJsSandbox.close(); + } + + ConnectionSetup(ReadyCallback callback) { + mReadyCallback = callback; + } + } + + /** Callback used to inform caller when a connected instance is ready. */ + public interface ReadyCallback { + void createdConnectedInstance(AwJsSandbox awJsSandbox); + } + + /** + * Use this method to create new instances that are connected to the service. The callback is + * called from the main looper (Looper.getMainLooper()). We only support creation of a single + * connected instance, we would need to add restrictions to enforce this. + * + * @param callback used to pass a callback function on creation of object. + */ + public static void newConnectedInstance(ReadyCallback callback) { + Intent intent = new Intent(ContextUtils.getApplicationContext(), JsSandboxService.class); + ConnectionSetup connectionSetup = new ConnectionSetup(callback); + boolean isBinding = ContextUtils.getApplicationContext().bindService( + intent, connectionSetup, Context.BIND_AUTO_CREATE); + if (!isBinding) { + throw new RuntimeException( + "System couldn't find the sandbox service or client doesn't have" + + "permission to bind to it " + intent); + } + } + + // We prevent direct initialitations of this class. Use AwJsSandbox.newConnectedInstance(). + private AwJsSandbox(ConnectionSetup connectionSetup, IJsSandboxService jsSandboxService) { + mConnection = connectionSetup; + mJsSandboxService = jsSandboxService; + } + + /** Creates an execution context within which JS can be executed multiple times. */ + public AwJsContext createContext() { + if (mJsSandboxService == null) { + throw new IllegalStateException( + "Attempting to createContext on a service that isn't connected"); + } + try { + IJsSandboxContext contextStub = mJsSandboxService.createContext(); + return new AwJsContext(contextStub); + } catch (RemoteException e) { + throw e.rethrowAsRuntimeException(); + } + } + + @Override + public void close() { + if (mJsSandboxService == null) { + return; + } + ContextUtils.getApplicationContext().unbindService(mConnection); + mJsSandboxService = null; + } +}
diff --git a/android_webview/java/src/org/chromium/android_webview/js/common/IJsSandboxContext.aidl b/android_webview/java/src/org/chromium/android_webview/js/common/IJsSandboxContext.aidl new file mode 100644 index 0000000..21281e7 --- /dev/null +++ b/android_webview/java/src/org/chromium/android_webview/js/common/IJsSandboxContext.aidl
@@ -0,0 +1,25 @@ +// Copyright 2022 The Chromium 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.android_webview.js.common; + +import org.chromium.android_webview.js.common.IJsSandboxContextCallback; + +/** + * Used by the embedding app to execute JavaScript in a sandboxed environment. + */ +interface IJsSandboxContext { + /** + * @param code the JavaScript code + * to be evaluated in the sandbox. + * @param callback used to pass the information back to the embedding app + * from the sandbox. + */ + void evaluateJavascript(in String code, in IJsSandboxContextCallback callback); + + /** + * Stop the execution of the context as soon as possible and destroy it. + */ + void close(); +}
diff --git a/android_webview/java/src/org/chromium/android_webview/js/common/IJsSandboxContextCallback.aidl b/android_webview/java/src/org/chromium/android_webview/js/common/IJsSandboxContextCallback.aidl new file mode 100644 index 0000000..56a4a11 --- /dev/null +++ b/android_webview/java/src/org/chromium/android_webview/js/common/IJsSandboxContextCallback.aidl
@@ -0,0 +1,13 @@ +// Copyright 2022 The Chromium 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.android_webview.js.common; + +/** + * Used to communicate the result of the JavaScript evaluation from the + * sandbox to the embedding app. + */ +oneway interface IJsSandboxContextCallback { + void reportResult(in String result); +}
diff --git a/android_webview/java/src/org/chromium/android_webview/js/common/IJsSandboxService.aidl b/android_webview/java/src/org/chromium/android_webview/js/common/IJsSandboxService.aidl new file mode 100644 index 0000000..9f0867e --- /dev/null +++ b/android_webview/java/src/org/chromium/android_webview/js/common/IJsSandboxService.aidl
@@ -0,0 +1,13 @@ +// Copyright 2022 The Chromium 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.android_webview.js.common; +import org.chromium.android_webview.js.common.IJsSandboxContext; + +/** + * Used by the embedding app to execute JavaScript in a sandboxed environment. + */ +interface IJsSandboxService { + IJsSandboxContext createContext(); +}
diff --git a/android_webview/java/src/org/chromium/android_webview/js/common/OWNERS b/android_webview/java/src/org/chromium/android_webview/js/common/OWNERS new file mode 100644 index 0000000..8f094e0 --- /dev/null +++ b/android_webview/java/src/org/chromium/android_webview/js/common/OWNERS
@@ -0,0 +1,2 @@ +per-file *.aidl=set noparent +per-file *.aidl=file://ipc/SECURITY_OWNERS
diff --git a/android_webview/java/src/org/chromium/android_webview/js/renderer/JsSandboxContext.java b/android_webview/java/src/org/chromium/android_webview/js/renderer/JsSandboxContext.java new file mode 100644 index 0000000..c14126e --- /dev/null +++ b/android_webview/java/src/org/chromium/android_webview/js/renderer/JsSandboxContext.java
@@ -0,0 +1,46 @@ +// Copyright 2022 The Chromium 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.android_webview.js.renderer; + +import android.os.Handler; +import android.os.Looper; +import android.os.RemoteException; + +import org.chromium.android_webview.js.common.IJsSandboxContext; +import org.chromium.android_webview.js.common.IJsSandboxContextCallback; +import org.chromium.base.Log; + +/** + * Service that provides a method for Javascript execution. TODO(crbug.com/1297672): Currently this + * is just meant to be a tracer to define the end to end flow and does not do anything useful. + */ +public class JsSandboxContext extends IJsSandboxContext.Stub { + private static final String TAG = "JsSandboxContext"; + private boolean mIsClosed = false; + + @Override + public void evaluateJavascript(String serialisedJS, IJsSandboxContextCallback callback) { + if (mIsClosed) { + throw new IllegalStateException("evaluateJavascript() called after close()"); + } + // Just posting to the mainLooper for now. + Handler handler = new Handler(Looper.getMainLooper()); + handler.postDelayed(() -> { + String result = serialisedJS.toUpperCase(); + try { + callback.reportResult(result); + } catch (RemoteException e) { + Log.e(TAG, "reporting result failed", e); + } + }, 100); + } + + @Override + public void close() { + mIsClosed = true; + // Do nothing for now. Eventually this should stop the execution and destroy the + // context in native. + } +}
diff --git a/android_webview/java/src/org/chromium/android_webview/js/renderer/JsSandboxService.java b/android_webview/java/src/org/chromium/android_webview/js/renderer/JsSandboxService.java new file mode 100644 index 0000000..f8934d63 --- /dev/null +++ b/android_webview/java/src/org/chromium/android_webview/js/renderer/JsSandboxService.java
@@ -0,0 +1,32 @@ +// Copyright 2022 The Chromium 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.android_webview.js.renderer; + +import android.app.Service; +import android.content.Intent; +import android.os.IBinder; + +import org.chromium.android_webview.js.common.IJsSandboxContext; +import org.chromium.android_webview.js.common.IJsSandboxService; + +/** + * Service that creates a context for Javascript execution. TODO(crbug.com/1297672): Currently this + * is just meant to be a tracer to define the end to end flow and does not do anything useful. + */ +public class JsSandboxService extends Service { + private static final String TAG = "JsSandboxService"; + + private final IJsSandboxService.Stub mBinder = new IJsSandboxService.Stub() { + @Override + public IJsSandboxContext createContext() { + return new JsSandboxContext(); + } + }; + + @Override + public IBinder onBind(Intent intent) { + return mBinder; + } +}
diff --git a/android_webview/javatests/src/org/chromium/android_webview/test/services/JsSandboxServiceTest.java b/android_webview/javatests/src/org/chromium/android_webview/test/services/JsSandboxServiceTest.java new file mode 100644 index 0000000..24dca42 --- /dev/null +++ b/android_webview/javatests/src/org/chromium/android_webview/test/services/JsSandboxServiceTest.java
@@ -0,0 +1,70 @@ +// Copyright 2022 The Chromium 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.android_webview.test.services; + +import androidx.test.filters.MediumTest; + +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; + +import org.chromium.android_webview.js.browser.AwJsContext; +import org.chromium.android_webview.js.browser.AwJsSandbox; +import org.chromium.android_webview.test.AwJUnit4ClassRunner; +import org.chromium.base.test.util.CallbackHelper; + +/** Instrumentation test for JsSandboxService. */ +@RunWith(AwJUnit4ClassRunner.class) +public class JsSandboxServiceTest { + private class TestExecutionCallback implements AwJsContext.ExecutionCallback { + public CallbackHelper helper = new CallbackHelper(); + public String result; + + @Override + public void reportResult(String result) { + this.result = result; + helper.notifyCalled(); + } + } + + // Test sending data to the service and retrieving it back. + // TODO(crbug.com/1297672): Currently this test only checks if evaluateJavascript() can convert + // the input string to uppercase. This needs to be modified to test the actual + // behaviour of the evaluateJavascript() method once implemented. + @Test + @MediumTest + public void testJsEvaluation() throws Throwable { + final String smallCase = "helloworld"; + final String expected = "HELLOWORLD"; + TestExecutionCallback callback = new TestExecutionCallback(); + + AwJsSandbox.newConnectedInstance(jsSandbox -> { + AwJsContext jsContext = jsSandbox.createContext(); + jsContext.evaluateJavascript(smallCase, callback); + }); + + callback.helper.waitForCallback("Timed out waiting for reportResult() to be called", 0); + Assert.assertEquals(expected, callback.result); + } + + @Test + @MediumTest + public void testClosingOneContextBeforeExecutingOther() throws Throwable { + final String smallCase = "helloworld"; + final String expected = "HELLOWORLD"; + TestExecutionCallback callback = new TestExecutionCallback(); + + AwJsSandbox.newConnectedInstance(jsSandbox -> { + AwJsContext jsContext1 = jsSandbox.createContext(); + AwJsContext jsContext2 = jsSandbox.createContext(); + jsContext1.close(); + jsContext2.evaluateJavascript(smallCase, callback); + jsContext2.close(); + }); + + callback.helper.waitForCallback("Timed out waiting for reportResult() to be called", 0); + Assert.assertEquals(expected, callback.result); + } +}
diff --git a/android_webview/nonembedded/component_updater/registration.cc b/android_webview/nonembedded/component_updater/registration.cc index 07db62b..ec0bf6b9 100644 --- a/android_webview/nonembedded/component_updater/registration.cc +++ b/android_webview/nonembedded/component_updater/registration.cc
@@ -72,7 +72,6 @@ RegisterComponentInstallerPolicyShim( std::make_unique< component_updater::ClientSidePhishingComponentInstallerPolicy>( - nullptr, // Files shouldn't be parsed or loaded in this process, thus // ClientSidePhishingComponentInstallerPolicy::ComponentReady will // never be called in this process and the `ReadFilesCallback`
diff --git a/android_webview/test/BUILD.gn b/android_webview/test/BUILD.gn index 84a2fdac..c3e32df 100644 --- a/android_webview/test/BUILD.gn +++ b/android_webview/test/BUILD.gn
@@ -87,6 +87,7 @@ "//android_webview:android_webview_java", "//android_webview:android_webview_product_config_java", "//android_webview:common_java", + "//android_webview:js_sandbox_java", "//android_webview:locale_pak_assets", "//android_webview:platform_service_bridge_upstream_implementation_java", "//base:base_java", @@ -221,6 +222,8 @@ "//android_webview:common_crash_java", "//android_webview:common_platform_services_java", "//android_webview:common_variations_java", + "//android_webview:js_sandbox_aidl_java", + "//android_webview:js_sandbox_java", "//android_webview/nonembedded:devui_java", "//android_webview/nonembedded:services_java", "//android_webview/proto:aw_variations_seed_proto_java", @@ -406,6 +409,7 @@ "../javatests/src/org/chromium/android_webview/test/devui/util/WebViewCrashLogParserTest.java", "../javatests/src/org/chromium/android_webview/test/services/ComponentsProviderServiceTest.java", "../javatests/src/org/chromium/android_webview/test/services/CrashReceiverServiceTest.java", + "../javatests/src/org/chromium/android_webview/test/services/JsSandboxServiceTest.java", "../javatests/src/org/chromium/android_webview/test/services/MetricsBridgeServiceTest.java", "../javatests/src/org/chromium/android_webview/test/services/MetricsBridgeServiceUnitTest.java", "../javatests/src/org/chromium/android_webview/test/services/MetricsUploadServiceTest.java",
diff --git a/android_webview/test/shell/AndroidManifest.xml b/android_webview/test/shell/AndroidManifest.xml index 0bcbce1..351fe87 100644 --- a/android_webview/test/shell/AndroidManifest.xml +++ b/android_webview/test/shell/AndroidManifest.xml
@@ -69,6 +69,11 @@ android:exported="false" /> <meta-data android:name="org.chromium.content.browser.NUM_PRIVILEGED_SERVICES" android:value="0"/> + <!-- JS Execution Sandbox --> + <service android:name="org.chromium.android_webview.js.renderer.JsSandboxService" + android:process=":js_sandboxed_process0" + android:isolatedProcess="true" + android:exported="false" /> <!-- See AwSecondBrowserProcessTest --> <service android:name="org.chromium.android_webview.test.SecondBrowserProcess" android:process=":second_browser_process"
diff --git a/ash/accessibility/accessibility_controller_impl.cc b/ash/accessibility/accessibility_controller_impl.cc index 4a3aa86e..871ee60 100644 --- a/ash/accessibility/accessibility_controller_impl.cc +++ b/ash/accessibility/accessibility_controller_impl.cc
@@ -2310,10 +2310,12 @@ case FeatureType::kDictation: if (enabled && ::features::IsExperimentalAccessibilityDictationCommandsEnabled()) { - // The Dictation bubble is hidden behind a flag; only create the - // controller if the flag is enabled. - dictation_bubble_controller_ = - std::make_unique<DictationBubbleController>(); + if (!dictation_bubble_controller_) { + // The Dictation bubble is hidden behind a flag; only create the + // controller if the flag is enabled. + dictation_bubble_controller_ = + std::make_unique<DictationBubbleController>(); + } } else { dictation_nudge_controller_.reset(); dictation_bubble_controller_.reset(); @@ -2421,4 +2423,14 @@ dictation_bubble_controller_->UpdateBubble(visible, icon, text, hints); } +DictationBubbleController* +AccessibilityControllerImpl::GetDictationBubbleControllerForTest() { + if (!dictation_bubble_controller_) { + dictation_bubble_controller_ = + std::make_unique<DictationBubbleController>(); + } + + return dictation_bubble_controller_.get(); +} + } // namespace ash
diff --git a/ash/accessibility/accessibility_controller_impl.h b/ash/accessibility/accessibility_controller_impl.h index da26d150..7c15db9 100644 --- a/ash/accessibility/accessibility_controller_impl.h +++ b/ash/accessibility/accessibility_controller_impl.h
@@ -491,9 +491,7 @@ return dictation_soda_download_progress_; } - DictationBubbleController* GetDictationBubbleControllerForTest() { - return dictation_bubble_controller_.get(); - } + DictationBubbleController* GetDictationBubbleControllerForTest(); private: // Populate |features_| with the feature of the correct type.
diff --git a/ash/app_list/app_list_controller_impl.cc b/ash/app_list/app_list_controller_impl.cc index 2c12055..e2e26315 100644 --- a/ash/app_list/app_list_controller_impl.cc +++ b/ash/app_list/app_list_controller_impl.cc
@@ -56,6 +56,7 @@ #include "base/bind.h" #include "base/callback_helpers.h" #include "base/callback_list.h" +#include "base/containers/adapters.h" #include "base/containers/contains.h" #include "base/containers/cxx20_erase.h" #include "base/logging.h" @@ -165,10 +166,11 @@ aura::Window* container = Shell::Get()->GetPrimaryRootWindow()->GetChildById( kShellWindowId_HomeScreenContainer); aura::Window::Windows windows_to_minimize; - for (auto it = windows.rbegin(); it != windows.rend(); it++) { - if (!container->Contains(*it) && !base::Contains(windows_to_ignore, *it) && - !WindowState::Get(*it)->IsMinimized()) { - windows_to_minimize.push_back(*it); + for (aura::Window* window : base::Reversed(windows)) { + if (!container->Contains(window) && + !base::Contains(windows_to_ignore, window) && + !WindowState::Get(window)->IsMinimized()) { + windows_to_minimize.push_back(window); } }
diff --git a/ash/app_list/views/app_list_bubble_view.cc b/ash/app_list/views/app_list_bubble_view.cc index 90f2205..a356a94 100644 --- a/ash/app_list/views/app_list_bubble_view.cc +++ b/ash/app_list/views/app_list_bubble_view.cc
@@ -490,10 +490,12 @@ const absl::optional<AppListSortOrder>& new_order, bool animate, base::OnceClosure update_position_closure) { - // Hide any open folder by showing the apps page. - if (showing_folder_) { + // If app list sort order change is animated, hide any open folders as part of + // animation. If the update is not animated, e.g. when committing sort order, + // keep the folder open to prevent folder closure when apps within the folder + // are reordered, or whe the folder gets renamed. + if (animate && showing_folder_) HideFolderView(/*animate=*/false, /*hide_for_reparent=*/false); - } apps_page_->UpdateForNewSortingOrder(new_order, animate, std::move(update_position_closure)); @@ -535,8 +537,12 @@ } void AppListBubbleView::Layout() { + views::View::Layout(); + // The folder view has custom layout code that centers the folder over the // associated root apps grid folder item. + // Folder bounds depend on the associated item view location in the apps + // grid, so the folder needs to be laid out after the root apps grid. if (showing_folder_) { gfx::Rect folder_bounding_box = GetLocalBounds(); folder_bounding_box.Inset(kFolderViewInset, kFolderViewInset); @@ -546,8 +552,6 @@ // view is "visible" but hidden offscreen. See app_list_folder_view.cc. folder_view_->SetBoundsRect(folder_view_->preferred_bounds()); } - - views::View::Layout(); } void AppListBubbleView::QueryChanged(SearchBoxViewBase* sender) {
diff --git a/ash/app_list/views/app_list_toast_view.cc b/ash/app_list/views/app_list_toast_view.cc index ee81141..54ca49e4 100644 --- a/ash/app_list/views/app_list_toast_view.cc +++ b/ash/app_list/views/app_list_toast_view.cc
@@ -166,6 +166,9 @@ label_container_->AddChildView(std::make_unique<views::Label>(title)); title_label_->SetHorizontalAlignment(gfx::HorizontalAlignment::ALIGN_LEFT); title_label_->SetMultiLine(true); + // TODO(crbug/682266): This is a temporary fix for the issue where the multi + // line label appears cut-off. + title_label_->SetMaximumWidth(GetExpandedTitleLabelWidth()); layout_manager_->SetFlexForView(label_container_, 1); } @@ -327,4 +330,11 @@ icon_->SetHorizontalAlignment(views::ImageView::Alignment::kCenter); } +int AppListToastView::GetExpandedTitleLabelWidth() { + const int icon_width = icon_ ? icon_->size().width() : 0; + const int button_width = toast_button_ ? toast_button_->size().width() : 0; + return GetPreferredSize().width() - kInteriorMargin.width() - icon_width - + button_width - kTitleContainerMargin.width(); +} + } // namespace ash
diff --git a/ash/app_list/views/app_list_toast_view.h b/ash/app_list/views/app_list_toast_view.h index b9e39ca..53a3dfef 100644 --- a/ash/app_list/views/app_list_toast_view.h +++ b/ash/app_list/views/app_list_toast_view.h
@@ -107,6 +107,9 @@ // Creates an ImageView for the icon and inserts it in the toast view. void CreateIconView(); + // Get the available space for `title_label_` width. + int GetExpandedTitleLabelWidth(); + // Vector icons to use with dark/light mode. const gfx::VectorIcon* dark_icon_ = nullptr; const gfx::VectorIcon* light_icon_ = nullptr;
diff --git a/ash/app_list/views/apps_container_view.cc b/ash/app_list/views/apps_container_view.cc index f53f29b..9090d3c 100644 --- a/ash/app_list/views/apps_container_view.cc +++ b/ash/app_list/views/apps_container_view.cc
@@ -689,10 +689,6 @@ if (new_order) toast_container_->AnnounceSortOrder(*new_order); - // Hide any open folder and transition to the apps page. - SetShowState(SHOW_APPS, /*show_apps_with_animation=*/false); - DisableFocusForShowingActiveFolder(false); - if (!animate) { // Reordering is not required so update the undo toast and return early. app_list_nudge_controller_->OnTemporarySortOrderChanged(new_order); @@ -700,6 +696,13 @@ return; } + // If app list sort order change is animated, hide any open folders as part of + // animation. If the update is not animated, e.g. when committing sort order, + // keep the folder open to prevent folder closure when apps within the folder + // are reordered, or whe the folder gets renamed. + SetShowState(SHOW_APPS, /*show_apps_with_animation=*/false); + DisableFocusForShowingActiveFolder(false); + // If `apps_grid_view_` is under page transition animation, finish the // animation before starting the reorder animation. ash::PaginationModel* pagination_model = apps_grid_view_->pagination_model(); @@ -1513,24 +1516,24 @@ views::AnimationBuilder animation_builder; fade_in_abort_handle_ = animation_builder.GetAbortHandle(); - views::AnimationSequenceBlock sequence_block = - animation_builder - .OnEnded( - base::BindOnce(&AppsContainerView::OnFadeInChildrenAnimationEnded, - weak_ptr_factory_.GetWeakPtr(), - /*aborted=*/false)) - .OnAborted( - base::BindOnce(&AppsContainerView::OnFadeInChildrenAnimationEnded, - weak_ptr_factory_.GetWeakPtr(), - /*aborted=*/true)) - .Once(); - sequence_block.SetDuration(kChildrenFadeInAnimationDuration) + animation_builder + .OnEnded( + base::BindOnce(&AppsContainerView::OnFadeInChildrenAnimationEnded, + weak_ptr_factory_.GetWeakPtr(), + /*aborted=*/false)) + .OnAborted( + base::BindOnce(&AppsContainerView::OnFadeInChildrenAnimationEnded, + weak_ptr_factory_.GetWeakPtr(), + /*aborted=*/true)) + .Once() + .SetDuration(kChildrenFadeInAnimationDuration) .SetOpacity(toast_container_->layer(), 1.f); // Continue section should be faded in only when the page changes. if (page_change) { continue_container_->layer()->SetOpacity(0.f); - sequence_block.SetOpacity(continue_container_->layer(), 1.f); + animation_builder.GetCurrentSequence().SetOpacity( + continue_container_->layer(), 1.f); } }
diff --git a/ash/app_list/views/apps_grid_view.cc b/ash/app_list/views/apps_grid_view.cc index ffa5a15..18405ed 100644 --- a/ash/app_list/views/apps_grid_view.cc +++ b/ash/app_list/views/apps_grid_view.cc
@@ -1969,18 +1969,15 @@ views::AnimationBuilder animation_builder; reorder_animation_abort_handle_ = animation_builder.GetAbortHandle(); - auto sequence_block = - animation_builder - .OnEnded(base::BindOnce(&AppsGridView::OnFadeInAnimationEnded, - weak_factory_.GetWeakPtr(), done_callback, - /*abort=*/false)) - .OnAborted(base::BindOnce(&AppsGridView::OnFadeInAnimationEnded, - weak_factory_.GetWeakPtr(), done_callback, - /*abort=*/true)) - .Once(); - - // Animate to show the apps grid. - sequence_block.SetDuration(kFadeInAnimationDuration) + animation_builder + .OnEnded(base::BindOnce(&AppsGridView::OnFadeInAnimationEnded, + weak_factory_.GetWeakPtr(), done_callback, + /*abort=*/false)) + .OnAborted(base::BindOnce(&AppsGridView::OnFadeInAnimationEnded, + weak_factory_.GetWeakPtr(), done_callback, + /*abort=*/true)) + .Once() + .SetDuration(kFadeInAnimationDuration) .SetOpacity(layer(), 1.f, gfx::Tween::LINEAR); // Assume all the items matched by the indices in `range` are @@ -2006,9 +2003,10 @@ // Create a slide animation on `animted_view` using `sequence_block`'s // existing time duration. - SlideViewIntoPositionWithSequenceBlock(animated_view, offset, - /*time_delta=*/absl::nullopt, - gfx::Tween::LINEAR, &sequence_block); + SlideViewIntoPositionWithSequenceBlock( + animated_view, offset, + /*time_delta=*/absl::nullopt, gfx::Tween::LINEAR, + &animation_builder.GetCurrentSequence()); } }
diff --git a/ash/app_list/views/continue_task_container_view.cc b/ash/app_list/views/continue_task_container_view.cc index 7cab02fd..0526022 100644 --- a/ash/app_list/views/continue_task_container_view.cc +++ b/ash/app_list/views/continue_task_container_view.cc
@@ -338,12 +338,11 @@ animation_builder.OnAborted(base::BindOnce( &ContinueTaskContainerView::ClearAnimatingViews, base::Unretained(this))); - views::AnimationSequenceBlock last_sequence = animation_builder.Once(); - last_sequence.SetDuration(base::Milliseconds(100)); + animation_builder.Once().SetDuration(base::Milliseconds(100)); // Fade out views for results that got removed. for (auto* view : views_to_fade_out) - ScheduleFadeOutAnimation(view, &last_sequence); + ScheduleFadeOutAnimation(view, &animation_builder.GetCurrentSequence()); // Immediately hide views that remained in place, and for which the new result // views will not be animated in. @@ -355,18 +354,18 @@ // Slide out old result views for results whose position changed. base::TimeDelta delay = views_to_fade_out.empty() ? base::TimeDelta() : base::Milliseconds(200); - last_sequence = last_sequence.At(delay); - last_sequence.SetDuration(base::Milliseconds(100)); + animation_builder.GetCurrentSequence().At(delay).SetDuration( + base::Milliseconds(100)); for (auto& view : views_to_slide_out) { ScheduleSlideOutAnimation(view.second, tablet_mode_ ? 0 : -34, is_rtl, - &last_sequence); + &animation_builder.GetCurrentSequence()); } // Animate new views in. delay = views_to_fade_out.empty() ? base::Milliseconds(100) : base::Milliseconds(300); - last_sequence = last_sequence.At(delay); - last_sequence.SetDuration(base::Milliseconds(300)); + animation_builder.GetCurrentSequence().At(delay).SetDuration( + base::Milliseconds(300)); for (auto* view : suggestion_tasks_views_) { const std::string& result_id = view->result()->id(); @@ -387,7 +386,8 @@ initial_offset = -initial_offset; } } - ScheduleSlideInAnimation(view, initial_offset, is_rtl, &last_sequence); + ScheduleSlideInAnimation(view, initial_offset, is_rtl, + &animation_builder.GetCurrentSequence()); } } @@ -454,11 +454,11 @@ view->layer()->SetTransform(translation); } views::AnimationBuilder animation_builder; - views::AnimationSequenceBlock sequence = animation_builder.Once(); - sequence.SetDuration(duration); + animation_builder.Once().SetDuration(duration); for (auto* view : suggestion_tasks_views_) { - sequence.SetTransform(view, gfx::Transform(), tween) + animation_builder.GetCurrentSequence() + .SetTransform(view, gfx::Transform(), tween) .SetOpacity(view, 1.0f, tween); } }
diff --git a/ash/app_list/views/pulsing_block_view.cc b/ash/app_list/views/pulsing_block_view.cc index 6dba650..395f5d2 100644 --- a/ash/app_list/views/pulsing_block_view.cc +++ b/ash/app_list/views/pulsing_block_view.cc
@@ -37,16 +37,17 @@ const gfx::Rect local_bounds(layer->bounds().size()); views::AnimationBuilder builder; - views::AnimationSequenceBlock block = builder.Repeatedly(); + builder.Repeatedly(); for (size_t i = 0; i < std::size(kAnimationOpacity); ++i) { - block = block.SetDuration(base::Milliseconds(kAnimationDurationInMs)) - .SetOpacity(layer, kAnimationOpacity[i]) - .SetTransform(layer, - gfx::GetScaleTransform(local_bounds.CenterPoint(), - kAnimationScale[i])) - .Then(); + builder.GetCurrentSequence() + .SetDuration(base::Milliseconds(kAnimationDurationInMs)) + .SetOpacity(layer, kAnimationOpacity[i]) + .SetTransform(layer, gfx::GetScaleTransform(local_bounds.CenterPoint(), + kAnimationScale[i])) + .Then(); } - block.SetDuration(base::Milliseconds(kAnimationDurationInMs)); + builder.GetCurrentSequence().SetDuration( + base::Milliseconds(kAnimationDurationInMs)); } } // namespace
diff --git a/ash/ash_strings.grd b/ash/ash_strings.grd index 383ca59a..af88edb 100644 --- a/ash/ash_strings.grd +++ b/ash/ash_strings.grd
@@ -4888,7 +4888,7 @@ Cable may not support displays </message> <message name="IDS_ASH_USB_NOTIFICATION_V2_CABLE_WARNING_DISPLAY_BODY" desc="Notification body text for when a user connects a display to a Chromebook's USB-C port with a cable that cannot support driving display signals."> - Your USB-C cable may not connect to diplays properly + Your USB-C cable may not connect to displays properly </message> <message name="IDS_ASH_USB_NOTIFICATION_V2_CABLE_WARNING_PERFORMANCE_TITLE" desc="Notification title text for when a user connects something to the USB-C port on their Chromebook and performance is in some way limited by the cable."> Cable may impact performance
diff --git a/ash/ash_strings_grd/IDS_ASH_USB_NOTIFICATION_V2_CABLE_WARNING_DISPLAY_BODY.png.sha1 b/ash/ash_strings_grd/IDS_ASH_USB_NOTIFICATION_V2_CABLE_WARNING_DISPLAY_BODY.png.sha1 index 60d8dab..8aafb85 100644 --- a/ash/ash_strings_grd/IDS_ASH_USB_NOTIFICATION_V2_CABLE_WARNING_DISPLAY_BODY.png.sha1 +++ b/ash/ash_strings_grd/IDS_ASH_USB_NOTIFICATION_V2_CABLE_WARNING_DISPLAY_BODY.png.sha1
@@ -1 +1 @@ -aac41ca3dc368f2cdca31e8eb53ffbb047945536 \ No newline at end of file +5f958b1cd3dc09af5f76027787b16134b554f33b \ No newline at end of file
diff --git a/ash/components/tether/host_scan_device_prioritizer_impl.cc b/ash/components/tether/host_scan_device_prioritizer_impl.cc index 06cea57..f294008 100644 --- a/ash/components/tether/host_scan_device_prioritizer_impl.cc +++ b/ash/components/tether/host_scan_device_prioritizer_impl.cc
@@ -6,6 +6,7 @@ #include "ash/components/tether/pref_names.h" #include "ash/components/tether/tether_host_response_recorder.h" +#include "base/containers/adapters.h" #include "base/memory/ptr_util.h" #include "base/values.h" #include "chromeos/network/network_state.h" @@ -60,14 +61,13 @@ // Iterate from the last stored ID to the first stored ID. This ensures that // the items at the front of the list end up in the front of the prioritized // |remote_devices| vector. - for (auto prioritized_it = prioritized_ids.rbegin(); - prioritized_it != prioritized_ids.rend(); ++prioritized_it) { + for (const std::string& prioritized_id : base::Reversed(prioritized_ids)) { // Iterate through |remote_devices| to see if a device ID exists which is // equal to |stored_id|. If one exists, remove it from its previous // position in the list and add it at the front instead. for (auto remote_devices_it = remote_devices->begin(); remote_devices_it != remote_devices->end(); ++remote_devices_it) { - if (remote_devices_it->GetDeviceId() != *prioritized_it) { + if (remote_devices_it->GetDeviceId() != prioritized_id) { continue; }
diff --git a/ash/constants/ash_features.cc b/ash/constants/ash_features.cc index cd36faa..633848c 100644 --- a/ash/constants/ash_features.cc +++ b/ash/constants/ash_features.cc
@@ -1116,6 +1116,11 @@ const base::Feature kProjectorExcludeTranscript{ "ProjectorExcludeTranscript", base::FEATURE_DISABLED_BY_DEFAULT}; +// Controls whether Projector's tutorial videos are displayed. +const base::Feature kProjectorTutorialVideoView( + "ProjectorTutorialVideoView", + base::FEATURE_DISABLED_BY_DEFAULT); + // Controls whether the quick dim prototype is enabled. const base::Feature kQuickDim{"QuickDim", base::FEATURE_ENABLED_BY_DEFAULT}; @@ -1960,6 +1965,10 @@ return base::FeatureList::IsEnabled(kProjectorExcludeTranscript); } +bool IsProjectorTutorialVideoViewEnabled() { + return base::FeatureList::IsEnabled(kProjectorTutorialVideoView); +} + bool IsQuickDimEnabled() { return base::FeatureList::IsEnabled(kQuickDim) && ash::switches::HasHps(); }
diff --git a/ash/constants/ash_features.h b/ash/constants/ash_features.h index 7e0ca41..f83e70c 100644 --- a/ash/constants/ash_features.h +++ b/ash/constants/ash_features.h
@@ -437,6 +437,8 @@ COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kProjectorExcludeTranscript; COMPONENT_EXPORT(ASH_CONSTANTS) +extern const base::Feature kProjectorTutorialVideoView; +COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kQuickDim; COMPONENT_EXPORT(ASH_CONSTANTS) extern const base::Feature kQuickSettingsNetworkRevamp; @@ -689,6 +691,7 @@ COMPONENT_EXPORT(ASH_CONSTANTS) bool IsProjectorAnnotatorEnabled(); COMPONENT_EXPORT(ASH_CONSTANTS) bool IsProjectorAppDebugMode(); COMPONENT_EXPORT(ASH_CONSTANTS) bool IsProjectorExcludeTranscriptEnabled(); +COMPONENT_EXPORT(ASH_CONSTANTS) bool IsProjectorTutorialVideoViewEnabled(); COMPONENT_EXPORT(ASH_CONSTANTS) bool IsQuickDimEnabled(); COMPONENT_EXPORT(ASH_CONSTANTS) bool IsQuickSettingsNetworkRevampEnabled();
diff --git a/ash/quick_pair/keyed_service/battery_update_message_handler.cc b/ash/quick_pair/keyed_service/battery_update_message_handler.cc index af528ff..1b99e8d 100644 --- a/ash/quick_pair/keyed_service/battery_update_message_handler.cc +++ b/ash/quick_pair/keyed_service/battery_update_message_handler.cc
@@ -7,6 +7,7 @@ #include "ash/quick_pair/common/logging.h" #include "base/bind.h" #include "base/callback.h" +#include "base/containers/adapters.h" #include "device/bluetooth/bluetooth_adapter.h" #include "device/bluetooth/bluetooth_adapter_factory.h" #include "device/bluetooth/bluetooth_device.h" @@ -74,10 +75,9 @@ DCHECK(message_stream); // Iterate over messages for battery update if it already exists. - for (auto it = message_stream->messages().rbegin(); - it != message_stream->messages().rend(); ++it) { - if ((*it)->is_battery_update()) { - SetBatteryInfo(device_address, (*it)->get_battery_update()); + for (const auto& message : base::Reversed(message_stream->messages())) { + if (message->is_battery_update()) { + SetBatteryInfo(device_address, message->get_battery_update()); return; } }
diff --git a/ash/shelf/hotseat_widget.cc b/ash/shelf/hotseat_widget.cc index e6f59a63..52d4a22e 100644 --- a/ash/shelf/hotseat_widget.cc +++ b/ash/shelf/hotseat_widget.cc
@@ -4,6 +4,7 @@ #include "ash/shelf/hotseat_widget.h" +#include <memory> #include <utility> #include "ash/constants/ash_features.h" @@ -20,6 +21,7 @@ #include "ash/shelf/shelf_navigation_widget.h" #include "ash/shelf/shelf_view.h" #include "ash/shell.h" +#include "ash/style/highlight_border.h" #include "ash/system/status_area_widget.h" #include "ash/wallpaper/wallpaper_controller_impl.h" #include "ash/wm/overview/overview_controller.h" @@ -36,6 +38,7 @@ #include "ui/gfx/color_palette.h" #include "ui/gfx/color_utils.h" #include "ui/gfx/geometry/rounded_corners_f.h" +#include "ui/views/background.h" #include "ui/views/layout/fill_layout.h" #include "ui/views/view_targeter_delegate.h" #include "ui/views/widget/widget_delegate.h" @@ -397,8 +400,7 @@ public OverviewObserver, public WallpaperControllerObserver { public: - DelegateView() : translucent_background_(ui::LAYER_SOLID_COLOR) { - translucent_background_.SetName("hotseat/Background"); + DelegateView() { SetEventTargeter(std::make_unique<views::ViewTargeter>(this)); SetPaintToLayer(ui::LAYER_NOT_DRAWN); } @@ -448,7 +450,6 @@ // views::WidgetDelegateView: bool CanActivate() const override; - void ReorderChildLayers(ui::Layer* parent_layer) override; // OverviewObserver: void OnOverviewModeWillStart() override; @@ -462,17 +463,17 @@ } int background_blur() const { - return translucent_background_.background_blur(); + return translucent_background_->layer()->background_blur(); } bool is_translucent_background_visible_for_test() { - return translucent_background_.GetTargetVisibility(); + return translucent_background_->layer()->GetTargetVisibility(); } private: FocusCycler* focus_cycler_ = nullptr; // A background layer that may be visible depending on HotseatState. - ui::Layer translucent_background_; + views::View* translucent_background_ = nullptr; ScrollableShelfView* scrollable_shelf_view_ = nullptr; // unowned. HotseatWidget* hotseat_widget_ = nullptr; // unowned. // Blur is disabled during animations to improve performance. @@ -512,13 +513,25 @@ DCHECK(scrollable_shelf_view); scrollable_shelf_view_ = scrollable_shelf_view; - layer()->Add(&translucent_background_); - layer()->StackAtBottom(&translucent_background_); + // A container view added here is to prevent the `translucent_background_` + // being stretched by the fill layout. + auto* background_container_view = + AddChildViewAt(std::make_unique<views::View>(), 0); + background_container_view->SetEnabled(false); + translucent_background_ = + background_container_view->AddChildView(std::make_unique<views::View>()); + if (features::IsDarkLightModeEnabled()) { + translucent_background_->SetPaintToLayer(); + translucent_background_->layer()->SetFillsBoundsOpaquely(false); + } else { + translucent_background_->SetPaintToLayer(ui::LAYER_SOLID_COLOR); + } + translucent_background_->layer()->SetName("hotseat/Background"); } void HotseatWidget::DelegateView::UpdateTranslucentBackground() { if (!HotseatWidget::ShouldShowHotseatBackground()) { - translucent_background_.SetVisible(false); + translucent_background_->SetVisible(false); SetBackgroundBlur(false); return; } @@ -532,10 +545,10 @@ const gfx::Rect& background_bounds) { DCHECK(HotseatWidget::ShouldShowHotseatBackground()); - translucent_background_.SetVisible(true); + translucent_background_->SetVisible(true); SetBackgroundBlur(/*enable_blur=*/true); - auto* animator = translucent_background_.GetAnimator(); + auto* animator = translucent_background_->layer()->GetAnimator(); absl::optional<ui::AnimationThroughputReporter> reporter; if (hotseat_widget_ && hotseat_widget_->state() != HotseatState::kNone) { @@ -547,14 +560,19 @@ ui::ScopedLayerAnimationSettings color_animation_setter(animator); DoScopedAnimationSetting(&color_animation_setter); target_color_ = ShelfConfig::Get()->GetDefaultShelfColor(); - translucent_background_.SetColor(target_color_); + if (features::IsDarkLightModeEnabled()) { + translucent_background_->SetBackground( + views::CreateSolidBackground(target_color_)); + } else { + translucent_background_->layer()->SetColor(target_color_); + } } // Animate the bounds change if there's a change of width (for instance when // dragging an app into, or out of, the shelf) and meanwhile scrollable // shelf's bounds does not update at the same time. const bool animate_bounds = - background_bounds.width() != translucent_background_.bounds().width() && + background_bounds.width() != translucent_background_->bounds().width() && (scrollable_shelf_view_ && !scrollable_shelf_view_->NeedUpdateToTargetBounds()); absl::optional<ui::ScopedLayerAnimationSettings> bounds_animation_setter; @@ -565,11 +583,18 @@ const float radius = hotseat_widget_->GetHotseatSize() / 2.0f; gfx::RoundedCornersF rounded_corners = {radius, radius, radius, radius}; - if (translucent_background_.rounded_corner_radii() != rounded_corners) - translucent_background_.SetRoundedCornerRadius(rounded_corners); + if (translucent_background_->layer()->rounded_corner_radii() != + rounded_corners) { + translucent_background_->layer()->SetRoundedCornerRadius(rounded_corners); + if (features::IsDarkLightModeEnabled()) { + translucent_background_->SetBorder(std::make_unique<HighlightBorder>( + radius, HighlightBorder::Type::kHighlightBorder1, + /*use_light_colors=*/true)); + } + } - if (translucent_background_.GetTargetBounds() != background_bounds) - translucent_background_.SetBounds(background_bounds); + if (translucent_background_->layer()->GetTargetBounds() != background_bounds) + translucent_background_->SetBoundsRect(background_bounds); } void HotseatWidget::DelegateView::SetBackgroundBlur(bool enable_blur) { @@ -578,8 +603,8 @@ const int blur_radius = enable_blur ? ShelfConfig::Get()->shelf_blur_radius() : 0; - if (translucent_background_.background_blur() != blur_radius) - translucent_background_.SetBackgroundBlur(blur_radius); + if (translucent_background_->layer()->background_blur() != blur_radius) + translucent_background_->layer()->SetBackgroundBlur(blur_radius); } void HotseatWidget::DelegateView::OnHotseatTransitionAnimationWillStart( @@ -621,11 +646,6 @@ return focus_cycler_ && focus_cycler_->widget_activating() == GetWidget(); } -void HotseatWidget::DelegateView::ReorderChildLayers(ui::Layer* parent_layer) { - views::View::ReorderChildLayers(parent_layer); - parent_layer->StackAtBottom(&translucent_background_); -} - void HotseatWidget::DelegateView::OnOverviewModeWillStart() { DCHECK_LE(blur_lock_, 2);
diff --git a/ash/style/highlight_border.cc b/ash/style/highlight_border.cc index 6f3e73f1..521e1a7 100644 --- a/ash/style/highlight_border.cc +++ b/ash/style/highlight_border.cc
@@ -8,6 +8,7 @@ #include "ash/public/cpp/style/scoped_light_mode_as_default.h" #include "ash/style/ash_color_provider.h" #include "ui/gfx/canvas.h" +#include "ui/gfx/geometry/dip_util.h" #include "ui/views/view.h" namespace ash { @@ -51,15 +52,23 @@ flags.setAntiAlias(true); const float half_thickness = kHighlightBorderThickness / 2.0f; - gfx::RectF outer_border_bounds(view.GetLocalBounds()); - outer_border_bounds.Inset(half_thickness, half_thickness); - canvas->DrawRoundRect(outer_border_bounds, corner_radius_, flags); + const gfx::Rect bounds = view.GetLocalBounds(); - gfx::RectF inner_border_bounds(view.GetLocalBounds()); + // Scale bounds and corner radius with device scale factor to make sure + // border bounds match content bounds but keep border stroke width the same. + const float dsf = canvas->UndoDeviceScaleFactor(); + const gfx::RectF pixel_bounds = gfx::ConvertRectToPixels(bounds, dsf); + const float scaled_corner_radius = dsf * corner_radius_; + gfx::RectF outer_border_bounds(pixel_bounds); + + outer_border_bounds.Inset(half_thickness, half_thickness); + canvas->DrawRoundRect(outer_border_bounds, scaled_corner_radius, flags); + + gfx::RectF inner_border_bounds(pixel_bounds); inner_border_bounds.Inset(gfx::Insets(kHighlightBorderThickness)); inner_border_bounds.Inset(half_thickness, half_thickness); flags.setColor(inner_color); - canvas->DrawRoundRect(inner_border_bounds, corner_radius_, flags); + canvas->DrawRoundRect(inner_border_bounds, scaled_corner_radius, flags); } gfx::Insets HighlightBorder::GetInsets() const {
diff --git a/ash/webui/personalization_app/resources/trusted/ambient/ambient_weather_element.html b/ash/webui/personalization_app/resources/trusted/ambient/ambient_weather_element.html index d0e4b1e..66f4dcc 100644 --- a/ash/webui/personalization_app/resources/trusted/ambient/ambient_weather_element.html +++ b/ash/webui/personalization_app/resources/trusted/ambient/ambient_weather_element.html
@@ -10,6 +10,7 @@ } cr-radio-button { height: 48px; + padding: 0 var(--cr-section-padding); } cr-radio-button + cr-radio-button { border-top: var(--cr-separator-line);
diff --git a/ash/webui/personalization_app/resources/untrusted/collections_grid.html b/ash/webui/personalization_app/resources/untrusted/collections_grid.html index 22078bb..e2d065f 100644 --- a/ash/webui/personalization_app/resources/untrusted/collections_grid.html +++ b/ash/webui/personalization_app/resources/untrusted/collections_grid.html
@@ -19,7 +19,7 @@ <div class$="[[getClassForImagesContainer_(item)]]"> <template is="dom-repeat" items="[[item.preview]]" as="preview"> <img is="cr-auto-img" auto-src="[[preview.url]]" - aria-hidden="true"> + aria-hidden="true" clear-src> </template> </div> <div class="photo-text-container"> @@ -37,7 +37,7 @@ on-click="onCollectionSelected_" on-keypress="onCollectionSelected_"> <div class$="[[getClassForImagesContainer_(item)]]"> <img is="cr-auto-img" auto-src="[[getImageUrlForEmptyTile_(item)]]" - aria-hidden="true"> + aria-hidden="true" clear-src> </div> <div class="photo-text-container"> <p title$="[[item.name]]">[[item.name]]</p> @@ -53,7 +53,7 @@ <template is="dom-repeat" items="[[item.preview]]" as="preview"> <img is="cr-auto-img" auto-src="[[preview.url]]" aria-hidden="true" on-load="onImgLoad_" on-error="onImgLoad_" - with-cookies="[[isGooglePhotosTile_(item)]]"> + with-cookies="[[isGooglePhotosTile_(item)]]" clear-src> </template> </div> <div class="photo-text-container" hidden>
diff --git a/ash/webui/personalization_app/resources/untrusted/images_grid.html b/ash/webui/personalization_app/resources/untrusted/images_grid.html index 0f0080a5..c977b38 100644 --- a/ash/webui/personalization_app/resources/untrusted/images_grid.html +++ b/ash/webui/personalization_app/resources/untrusted/images_grid.html
@@ -25,7 +25,7 @@ <div class="photo-images-container"> <template is="dom-repeat" items="[[item.preview]]" as="preview"> <img is="cr-auto-img" class$="[[getClassForImg_(index, item)]]" - auto-src="[[preview.url]]" aria-hidden="true"> + auto-src="[[preview.url]]" aria-hidden="true" clear-src> </template> <iron-icon icon="personalization:checkmark"></iron-icon> </div>
diff --git a/ash/webui/personalization_app/resources/untrusted/images_grid.ts b/ash/webui/personalization_app/resources/untrusted/images_grid.ts index a2ffdcd6..9d068e5 100644 --- a/ash/webui/personalization_app/resources/untrusted/images_grid.ts +++ b/ash/webui/personalization_app/resources/untrusted/images_grid.ts
@@ -2,6 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +import '//resources/cr_elements/cr_auto_img/cr_auto_img.js'; import '//resources/polymer/v3_0/iron-list/iron-list.js'; import './setup.js'; import '../trusted/wallpaper/styles.js'; @@ -72,19 +73,6 @@ if (validateReceivedData(event)) { visible = event.visible; } - if (!visible) { - // TODO(b/219799872) revisit if this is necessary. - // When the grid is hidden, do some dom magic to hide old image - // content. This is in preparation for a user switching to a new - // wallpaper collection and loading a new set of images. - const ironList = this.shadowRoot!.querySelector('iron-list'); - const images: NodeListOf<HTMLImageElement> = - ironList!.querySelectorAll('.photo-container img'); - for (const image of images) { - image.src = ''; - } - this.tiles_ = []; - } if (visible) { // If iron-list items were updated while this iron-list was hidden, // the layout will be incorrect. Trigger another layout when iron-list
diff --git a/ash/webui/shimless_rma/DEPS b/ash/webui/shimless_rma/DEPS index c72c12ae..b8d5aff 100644 --- a/ash/webui/shimless_rma/DEPS +++ b/ash/webui/shimless_rma/DEPS
@@ -4,6 +4,8 @@ "+chromeos/dbus/rmad", "+chromeos/dbus/update_engine", "+chromeos/dbus/util", + "+chromeos/login/login_state", + "+chromeos/services/network_config", "+ui/resources", "+ui/web_dialogs", "+ui/chromeos/strings",
diff --git a/ash/webui/shimless_rma/backend/BUILD.gn b/ash/webui/shimless_rma/backend/BUILD.gn index dfd5a5dc..b97da59 100644 --- a/ash/webui/shimless_rma/backend/BUILD.gn +++ b/ash/webui/shimless_rma/backend/BUILD.gn
@@ -26,6 +26,7 @@ "//chromeos/dbus/update_engine:proto", "//chromeos/dbus/util", "//chromeos/network:network", + "//chromeos/services/network_config:in_process_instance", "//chromeos/services/network_config/public/mojom:mojom", "//components/qr_code_generator", ] @@ -49,6 +50,7 @@ "//chromeos/dbus/rmad", "//chromeos/dbus/rmad:rmad_proto", "//chromeos/dbus/update_engine:update_engine", + "//chromeos/login/login_state:login_state", "//chromeos/network:network", "//chromeos/network:test_support", "//chromeos/services/network_config/public/cpp:test_support",
diff --git a/ash/webui/shimless_rma/backend/shimless_rma_service.cc b/ash/webui/shimless_rma/backend/shimless_rma_service.cc index 0b5bff7..1369315 100644 --- a/ash/webui/shimless_rma/backend/shimless_rma_service.cc +++ b/ash/webui/shimless_rma/backend/shimless_rma_service.cc
@@ -15,6 +15,7 @@ #include "ash/webui/shimless_rma/mojom/shimless_rma.mojom.h" #include "ash/webui/shimless_rma/mojom/shimless_rma_mojom_traits.h" #include "base/bind.h" +#include "base/containers/contains.h" #include "base/logging.h" #include "chromeos/dbus/power/power_manager_client.h" #include "chromeos/dbus/rmad/rmad.pb.h" @@ -22,6 +23,8 @@ #include "chromeos/dbus/util/version_loader.h" #include "chromeos/network/network_state.h" #include "chromeos/network/network_state_handler.h" +#include "chromeos/services/network_config/in_process_instance.h" +#include "chromeos/services/network_config/public/mojom/cros_network_config.mojom.h" #include "components/qr_code_generator/qr_code_generator.h" using chromeos::network_config::mojom::ConnectionStateType; @@ -35,6 +38,8 @@ namespace { +namespace network_mojom = ::chromeos::network_config::mojom; + mojom::State RmadStateToMojo(rmad::RmadState::StateCase rmadState) { return mojo::EnumTraits<ash::shimless_rma::mojom::State, rmad::RmadState::StateCase>::ToMojom(rmadState); @@ -79,12 +84,23 @@ qr_code->data.assign(qr_data->data.begin(), qr_data->data.end()); return qr_code; } + +chromeos::network_config::mojom::NetworkFilterPtr GetNetworkFilter() { + return network_mojom::NetworkFilter::New( + network_mojom::FilterType::kConfigured, network_mojom::NetworkType::kWiFi, + network_mojom::kNoLimit); +} + } // namespace ShimlessRmaService::ShimlessRmaService( std::unique_ptr<ShimlessRmaDelegate> shimless_rma_delegate) : shimless_rma_delegate_(std::move(shimless_rma_delegate)) { chromeos::RmadClient::Get()->AddObserver(this); + + network_config::BindToInProcessInstance( + remote_cros_network_config_.BindNewPipeAndPassReceiver()); + version_updater_.SetOsUpdateStatusCallback( base::BindRepeating(&ShimlessRmaService::OnOsUpdateStatusCallback, weak_ptr_factory_.GetWeakPtr())); @@ -167,6 +183,59 @@ } } +void ShimlessRmaService::TrackConfiguredNetworks() { + // Only populate `existing_saved_network_guids_` once to avoid treating a new + // network like an existing network. TrackConfiguredNetworks() can potentially + // be called twice if the user navigates back to the networking page. + if (!existing_saved_network_guids_.empty()) { + LOG(WARNING) << "Already captured configured networks."; + return; + } + + remote_cros_network_config_->GetNetworkStateList( + GetNetworkFilter(), + base::BindOnce(&ShimlessRmaService::OnTrackConfiguredNetworks, + base::Unretained(this))); +} + +void ShimlessRmaService::OnTrackConfiguredNetworks( + std::vector<network_mojom::NetworkStatePropertiesPtr> networks) { + for (auto& network : networks) { + existing_saved_network_guids_.push_back(std::move(network->guid)); + } +} + +void ShimlessRmaService::ForgetNewNetworkConnections() { + remote_cros_network_config_->GetNetworkStateList( + GetNetworkFilter(), + base::BindOnce(&ShimlessRmaService::OnForgetNewNetworkConnections, + base::Unretained(this))); +} + +void ShimlessRmaService::OnForgetNewNetworkConnections( + std::vector<chromeos::network_config::mojom::NetworkStatePropertiesPtr> + networks) { + for (auto& network : networks) { + const std::string& guid = network->guid; + const bool found_network_guid = + base::Contains(existing_saved_network_guids_, guid); + + // If `network` did not exist before RMA, attempt to forget it. + if (!found_network_guid) { + remote_cros_network_config_->ForgetNetwork( + guid, base::BindOnce(&ShimlessRmaService::OnForgetNetwork, + base::Unretained(this), guid)); + } + } +} + +void ShimlessRmaService::OnForgetNetwork(const std::string& guid, + bool success) { + if (!success) { + LOG(ERROR) << "Failed to forget saved network configuration GUID: " << guid; + } +} + void ShimlessRmaService::NetworkSelectionComplete( NetworkSelectionCompleteCallback callback) { if (state_proto_.state_case() != rmad::RmadState::kWelcome || @@ -849,6 +918,9 @@ rmad::RmadErrorCode::RMAD_ERROR_REQUEST_INVALID); return; } + + ForgetNewNetworkConnections(); + state_proto_.mutable_repair_complete()->set_shutdown( rmad::RepairCompleteState::RMAD_REPAIR_COMPLETE_REBOOT); TransitionNextStateGeneric(std::move(callback)); @@ -863,6 +935,9 @@ rmad::RmadErrorCode::RMAD_ERROR_REQUEST_INVALID); return; } + + ForgetNewNetworkConnections(); + state_proto_.mutable_repair_complete()->set_shutdown( rmad::RepairCompleteState::RMAD_REPAIR_COMPLETE_SHUTDOWN); TransitionNextStateGeneric(std::move(callback)); @@ -878,6 +953,9 @@ rmad::RmadErrorCode::RMAD_ERROR_REQUEST_INVALID); return; } + + ForgetNewNetworkConnections(); + state_proto_.mutable_repair_complete()->set_shutdown( rmad::RepairCompleteState::RMAD_REPAIR_COMPLETE_BATTERY_CUTOFF); TransitionNextStateGeneric(std::move(callback)); @@ -1114,6 +1192,7 @@ return; } + ForgetNewNetworkConnections(); // Send status before shutting down or restarting Chrome session. std::move(callback).Run(rmad::RMAD_ERROR_OK);
diff --git a/ash/webui/shimless_rma/backend/shimless_rma_service.h b/ash/webui/shimless_rma/backend/shimless_rma_service.h index f909a85..aa340a5 100644 --- a/ash/webui/shimless_rma/backend/shimless_rma_service.h +++ b/ash/webui/shimless_rma/backend/shimless_rma_service.h
@@ -7,12 +7,14 @@ #include <memory> #include <string> +#include <vector> #include "ash/webui/shimless_rma/backend/version_updater.h" #include "ash/webui/shimless_rma/mojom/shimless_rma.mojom.h" #include "chromeos/dbus/rmad/rmad.pb.h" #include "chromeos/dbus/rmad/rmad_client.h" #include "chromeos/dbus/update_engine/update_engine.pb.h" +#include "chromeos/services/network_config/public/mojom/cros_network_config.mojom.h" #include "mojo/public/cpp/bindings/pending_receiver.h" #include "mojo/public/cpp/bindings/receiver.h" #include "mojo/public/cpp/bindings/remote_set.h" @@ -41,6 +43,7 @@ void BeginFinalization(BeginFinalizationCallback callback) override; + void TrackConfiguredNetworks(); void NetworkSelectionComplete( NetworkSelectionCompleteCallback callback) override; @@ -207,6 +210,23 @@ void OsUpdateOrNextRmadStateCallback(TransitionStateCallback callback, const std::string& version); + // Saves existing configured networks to `existing_saved_networks_`. + void OnTrackConfiguredNetworks( + std::vector<chromeos::network_config::mojom::NetworkStatePropertiesPtr> + networks); + + // Fetches the list of configured networks on RMA completion/exit. + void ForgetNewNetworkConnections(); + + // Compares the saved and current list of configured networks and attempts to + // drop any new network configurations. + void OnForgetNewNetworkConnections( + std::vector<chromeos::network_config::mojom::NetworkStatePropertiesPtr> + networks); + + // Confirms if the network was dropped. + void OnForgetNetwork(const std::string& guid, bool success); + rmad::RmadState state_proto_; bool can_abort_ = false; bool can_go_back_ = false; @@ -239,6 +259,14 @@ mojo::Remote<mojom::UpdateRoFirmwareObserver> update_ro_firmware_observer_; mojo::Receiver<mojom::ShimlessRmaService> receiver_{this}; + // Remote for sending requests to the CrosNetworkConfig service. + mojo::Remote<chromeos::network_config::mojom::CrosNetworkConfig> + remote_cros_network_config_; + + // The GUIDs of the saved network configurations prior to starting RMA. Needed + // to track network connections added during RMA. + std::vector<std::string> existing_saved_network_guids_; + VersionUpdater version_updater_; base::OnceCallback<void(const std::string& version)> check_os_callback_;
diff --git a/ash/webui/shimless_rma/backend/shimless_rma_service_unittest.cc b/ash/webui/shimless_rma/backend/shimless_rma_service_unittest.cc index 4b31679e..6a17cd95 100644 --- a/ash/webui/shimless_rma/backend/shimless_rma_service_unittest.cc +++ b/ash/webui/shimless_rma/backend/shimless_rma_service_unittest.cc
@@ -12,6 +12,7 @@ #include "ash/webui/shimless_rma/backend/shimless_rma_delegate.h" #include "ash/webui/shimless_rma/mojom/shimless_rma.mojom.h" +#include "base/callback_helpers.h" #include "base/strings/stringprintf.h" #include "base/test/bind.h" #include "base/test/task_environment.h" @@ -19,8 +20,12 @@ #include "chromeos/dbus/rmad/fake_rmad_client.h" #include "chromeos/dbus/rmad/rmad_client.h" #include "chromeos/dbus/update_engine/update_engine.pb.h" +#include "chromeos/login/login_state/login_state.h" +#include "chromeos/network/managed_network_configuration_handler.h" #include "chromeos/network/network_configuration_handler.h" +#include "chromeos/network/network_state_handler.h" #include "chromeos/network/network_state_test_helper.h" +#include "chromeos/network/network_type_pattern.h" #include "chromeos/services/network_config/public/cpp/cros_network_config_test_helper.h" #include "chromeos/services/network_config/public/mojom/cros_network_config.mojom.h" #include "testing/gtest/include/gtest/gtest.h" @@ -87,11 +92,7 @@ void SetUp() override { chromeos::DBusThreadManager::Initialize(); - cros_network_config_test_helper_ = - std::make_unique<network_config::CrosNetworkConfigTestHelper>(false); - cros_network_config_test_helper().Initialize(nullptr); - NetworkHandler::Initialize(); - + SetupFakeNetwork(); FakeRmadClientForTest::Initialize(); rmad_client_ = chromeos::RmadClient::Get(); // ShimlessRmaService has to be created after RmadClient or there will be a @@ -111,9 +112,32 @@ chromeos::RmadClient::Shutdown(); NetworkHandler::Shutdown(); cros_network_config_test_helper_.reset(); + chromeos::LoginState::Shutdown(); chromeos::DBusThreadManager::Shutdown(); } + void SetupFakeNetwork() { + chromeos::LoginState::Initialize(); + + cros_network_config_test_helper_ = + std::make_unique<network_config::CrosNetworkConfigTestHelper>(false); + network_configuration_handler_ = + NetworkConfigurationHandler::InitializeForTest( + network_state_helper().network_state_handler(), + cros_network_config_test_helper().network_device_handler()); + managed_network_configuration_handler_ = + ManagedNetworkConfigurationHandler::InitializeForTesting( + /*network_state_handler=*/nullptr, + /*network_profile_handler=*/nullptr, + /*network_device_handler=*/nullptr, + network_configuration_handler_.get(), + /*ui_proxy_config_service=*/nullptr); + cros_network_config_test_helper().Initialize( + managed_network_configuration_handler_.get()); + + NetworkHandler::Initialize(); + } + rmad::RmadState* CreateState(rmad::RmadState::StateCase state_case) { rmad::RmadState* state = new rmad::RmadState(); switch (state_case) { @@ -215,6 +239,13 @@ base::RunLoop().RunUntilIdle(); } + void GetCurrentlyConfiguredWifiNetworks( + NetworkStateHandler::NetworkStateList* list) { + network_state_handler()->GetNetworkListByType( + NetworkTypePattern::WiFi(), /*configured_only=*/true, + /*visible_only=*/true, /*no_limit=*/0, list); + } + protected: network_config::CrosNetworkConfigTestHelper& cros_network_config_test_helper() { @@ -225,12 +256,19 @@ return cros_network_config_test_helper_->network_state_helper(); } + chromeos::NetworkStateHandler* network_state_handler() { + return network_state_helper().network_state_handler(); + } + std::unique_ptr<ShimlessRmaService> shimless_rma_provider_; chromeos::RmadClient* rmad_client_ = nullptr; // Unowned convenience pointer. private: std::unique_ptr<network_config::CrosNetworkConfigTestHelper> cros_network_config_test_helper_; + std::unique_ptr<ManagedNetworkConfigurationHandler> + managed_network_configuration_handler_; + std::unique_ptr<NetworkConfigurationHandler> network_configuration_handler_; base::test::TaskEnvironment task_environment_; }; @@ -419,6 +457,68 @@ run_loop.Run(); } +TEST_F(ShimlessRmaServiceTest, ConfiguredNetworksKeepExistingNetworks) { + const std::vector<rmad::GetStateReply> fake_states = { + CreateStateReply(rmad::RmadState::kRepairComplete, rmad::RMAD_ERROR_OK)}; + fake_rmad_client_()->SetFakeStateReplies(std::move(fake_states)); + + base::RunLoop run_loop; + shimless_rma_provider_->GetCurrentState(base::DoNothing()); + run_loop.RunUntilIdle(); + + // Simulate 2 saved networks existing before the start of RMA. + SetupWiFiNetwork("WiFi 1"); + SetupWiFiNetwork("WiFi 2"); + NetworkStateHandler::NetworkStateList configured_networks; + GetCurrentlyConfiguredWifiNetworks(&configured_networks); + EXPECT_EQ(2u, configured_networks.size()); + + // Snapshot the saved networks before connecting to a network during RMA. + shimless_rma_provider_->TrackConfiguredNetworks(); + run_loop.RunUntilIdle(); + + // End RMA and expect no networks to be removed from the saved networks. + shimless_rma_provider_->EndRmaAndReboot(base::DoNothing()); + run_loop.RunUntilIdle(); + + GetCurrentlyConfiguredWifiNetworks(&configured_networks); + EXPECT_EQ(2u, configured_networks.size()); +} + +TEST_F(ShimlessRmaServiceTest, ConfiguredNetworksDropNewNetworks) { + const std::vector<rmad::GetStateReply> fake_states = { + CreateStateReply(rmad::RmadState::kRepairComplete, rmad::RMAD_ERROR_OK)}; + fake_rmad_client_()->SetFakeStateReplies(std::move(fake_states)); + + base::RunLoop run_loop; + shimless_rma_provider_->GetCurrentState(base::DoNothing()); + run_loop.RunUntilIdle(); + + // Simulate a saved network existing before the start of RMA. + const std::string saved_network_guid = "WiFi 1"; + SetupWiFiNetwork(saved_network_guid); + NetworkStateHandler::NetworkStateList configured_networks; + GetCurrentlyConfiguredWifiNetworks(&configured_networks); + EXPECT_EQ(1u, configured_networks.size()); + + // Snapshot the saved networks before connecting to a network during RMA. + shimless_rma_provider_->TrackConfiguredNetworks(); + run_loop.RunUntilIdle(); + + // Simulate connecting to a new network on the RMA `kConfigureNetwork` page. + SetupWiFiNetwork("WiFi 2"); + GetCurrentlyConfiguredWifiNetworks(&configured_networks); + EXPECT_EQ(2u, configured_networks.size()); + + // End RMA and expect the new network to be removed from the saved networks. + shimless_rma_provider_->EndRmaAndReboot(base::DoNothing()); + run_loop.RunUntilIdle(); + + GetCurrentlyConfiguredWifiNetworks(&configured_networks); + EXPECT_EQ(1u, configured_networks.size()); + EXPECT_EQ(saved_network_guid, configured_networks[0]->guid()); +} + // TODO(gavindodd): Add tests of transitions back from rmad states through // the mojom chrome update and network selection states when implemented.
diff --git a/ash/wm/ash_focus_rules.cc b/ash/wm/ash_focus_rules.cc index d0ab0444..bf8487d 100644 --- a/ash/wm/ash_focus_rules.cc +++ b/ash/wm/ash_focus_rules.cc
@@ -14,6 +14,7 @@ #include "ash/wm/overview/overview_controller.h" #include "ash/wm/window_restore/window_restore_controller.h" #include "ash/wm/window_state.h" +#include "base/containers/adapters.h" #include "base/containers/contains.h" #include "components/app_restore/full_restore_utils.h" #include "ui/aura/client/aura_constants.h" @@ -225,13 +226,11 @@ aura::Window* AshFocusRules::GetTopmostWindowToActivateInContainer( aura::Window* container, aura::Window* ignore) const { - for (aura::Window::Windows::const_reverse_iterator i = - container->children().rbegin(); - i != container->children().rend(); ++i) { - WindowState* window_state = WindowState::Get(*i); - if (*i != ignore && window_state->CanActivate() && + for (aura::Window* child : base::Reversed(container->children())) { + WindowState* window_state = WindowState::Get(child); + if (child != ignore && window_state->CanActivate() && !window_state->IsMinimized()) - return *i; + return child; } return nullptr; }
diff --git a/ash/wm/desks/templates/desks_templates_dialog_controller.cc b/ash/wm/desks/templates/desks_templates_dialog_controller.cc index 64996d9..bac4b5de 100644 --- a/ash/wm/desks/templates/desks_templates_dialog_controller.cc +++ b/ash/wm/desks/templates/desks_templates_dialog_controller.cc
@@ -287,6 +287,7 @@ dialog_widget_ = views::DialogDelegate::CreateDialogWidget( std::move(dialog), /*context=*/root_window, /*parent=*/nullptr); + dialog_widget_->GetNativeWindow()->SetName("TemplateDialogForTesting"); dialog_widget_->Show(); dialog_widget_observation_.Observe(dialog_widget_); }
diff --git a/ash/wm/desks/templates/desks_templates_item_view.cc b/ash/wm/desks/templates/desks_templates_item_view.cc index af18e5f3..b9a86f54 100644 --- a/ash/wm/desks/templates/desks_templates_item_view.cc +++ b/ash/wm/desks/templates/desks_templates_item_view.cc
@@ -401,9 +401,6 @@ defer_select_all_ = false; name_view_->UpdateViewAppearance(); - if (MaybeShowReplaceDialog()) - return; - // Collapse the whitespace for the text first before comparing it or trying to // commit the name in order to prevent duplicate name issues. const std::u16string user_entered_name = @@ -421,27 +418,36 @@ return; } + // Check if template name exist, replace existing template if confirmed by + // user. Use a post task to avoid activating a widget while another widget is + // still being activated. In this case, we don't want to show the dialog and + // activate its associated widget until after the desks bar widget is finished + // activating. See https://crbug.com/1301759. + auto* template_to_replace = FindOtherTemplateWithName(name_view_->GetText()); + if (template_to_replace) { + base::ThreadTaskRunnerHandle::Get()->PostTask( + FROM_HERE, + base::BindOnce(&DesksTemplatesItemView::MaybeShowReplaceDialog, + weak_ptr_factory_.GetWeakPtr(), template_to_replace)); + return; + } + UpdateTemplateName(); } -bool DesksTemplatesItemView::MaybeShowReplaceDialog() { - // Check if template name exist, replace existing template if confirmed by - // user. - const std::u16string new_name = name_view_->GetText(); - auto* template_item = FindOtherTemplateWithName(new_name); - if (!template_item) - return false; +void DesksTemplatesItemView::MaybeShowReplaceDialog( + DesksTemplatesItemView* template_to_replace) { // Show replace template dialog. If accepted, replace old template and commit // name change. aura::Window* root_window = GetWidget()->GetNativeWindow()->GetRootWindow(); DesksTemplatesDialogController::Get()->ShowReplaceDialog( - root_window, new_name, - base::BindOnce(&DesksTemplatesItemView::ReplaceTemplate, - weak_ptr_factory_.GetWeakPtr(), - template_item->desk_template_->uuid().AsLowercaseString()), + root_window, name_view_->GetText(), + base::BindOnce( + &DesksTemplatesItemView::ReplaceTemplate, + weak_ptr_factory_.GetWeakPtr(), + template_to_replace->desk_template_->uuid().AsLowercaseString()), base::BindOnce(&DesksTemplatesItemView::RevertTemplateName, weak_ptr_factory_.GetWeakPtr())); - return true; } views::Button::KeyClickAction DesksTemplatesItemView::GetKeyClickActionForEvent(
diff --git a/ash/wm/desks/templates/desks_templates_item_view.h b/ash/wm/desks/templates/desks_templates_item_view.h index ac06b6e..3b3cc81 100644 --- a/ash/wm/desks/templates/desks_templates_item_view.h +++ b/ash/wm/desks/templates/desks_templates_item_view.h
@@ -90,7 +90,7 @@ // so, remove auto added number. void MaybeRemoveNameNumber(); // Show replace dialog when found a name duplication. - bool MaybeShowReplaceDialog(); + void MaybeShowReplaceDialog(DesksTemplatesItemView* template_to_replace); // Rename current template with new name, delete old template with same name // by uuid. Used for callback functions for Replace Dialog. void ReplaceTemplate(const std::string& uuid);
diff --git a/ash/wm/desks/templates/desks_templates_unittest.cc b/ash/wm/desks/templates/desks_templates_unittest.cc index bdd4533..fc882d6 100644 --- a/ash/wm/desks/templates/desks_templates_unittest.cc +++ b/ash/wm/desks/templates/desks_templates_unittest.cc
@@ -66,6 +66,7 @@ #include "ui/events/test/event_generator.h" #include "ui/views/controls/label.h" #include "ui/views/controls/textfield/textfield.h" +#include "ui/views/widget/any_widget_observer.h" #include "ui/views/window/dialog_delegate.h" #include "ui/wm/core/cursor_manager.h" @@ -2948,16 +2949,16 @@ // Set template 1 under new name. GetItemViewFromTemplatesGrid(0)->desk_template()->set_template_name( u"Desk 2"); - // Save template 2 under new name, this will trigger replace dialog. + // Save template 2 under new name and confirm, this will trigger replace + // dialog. name_view->SetText(u"Desk 2"); + EXPECT_EQ(u"Desk 2", name_view->GetText()); + views::NamedWidgetShownWaiter waiter(views::test::AnyWidgetTestPasskey{}, + "TemplateDialogForTesting"); GetEventGenerator()->PressAndReleaseKey(ui::VKEY_RETURN); - - auto* dialog_controller = DesksTemplatesDialogController::Get(); + views::Widget* dialog_widget = waiter.WaitIfNeededAndGet(); // Cancel on replace dialog will revert view name to template name. - dialog_controller->dialog_widget() - ->widget_delegate() - ->AsDialogDelegate() - ->CancelDialog(); + dialog_widget->widget_delegate()->AsDialogDelegate()->CancelDialog(); EXPECT_EQ(u"Desk 1", name_view->GetText()); }
diff --git a/ash/wm/window_finder.cc b/ash/wm/window_finder.cc index 3846db1..86ecc20c 100644 --- a/ash/wm/window_finder.cc +++ b/ash/wm/window_finder.cc
@@ -10,6 +10,7 @@ #include "ash/wm/overview/overview_grid.h" #include "ash/wm/overview/overview_session.h" #include "ash/wm/window_util.h" +#include "base/containers/adapters.h" #include "ui/aura/client/screen_position_client.h" #include "ui/aura/window.h" #include "ui/aura/window_targeter.h" @@ -73,13 +74,11 @@ return nullptr; } - for (aura::Window::Windows::const_reverse_iterator i = - window->children().rbegin(); - i != window->children().rend(); ++i) { + for (auto* child : base::Reversed(window->children())) { aura::WindowTargeter* child_targeter = - (*i)->targeter() ? (*i)->targeter() : targeter; + child->targeter() ? child->targeter() : targeter; aura::Window* result = GetTopmostWindowAtPointWithinWindow( - screen_point, *i, child_targeter, ignore); + screen_point, child, child_targeter, ignore); if (result) return result; }
diff --git a/ash/wm/workspace/backdrop_controller.cc b/ash/wm/workspace/backdrop_controller.cc index d370a5a..a264929 100644 --- a/ash/wm/workspace/backdrop_controller.cc +++ b/ash/wm/workspace/backdrop_controller.cc
@@ -28,6 +28,7 @@ #include "ash/wm/window_util.h" #include "base/auto_reset.h" #include "base/bind.h" +#include "base/containers/adapters.h" #include "base/memory/weak_ptr.h" #include "ui/aura/client/aura_constants.h" #include "ui/compositor/layer.h" @@ -292,9 +293,7 @@ aura::Window* BackdropController::GetTopmostWindowWithBackdrop() { const aura::Window::Windows windows = container_->children(); - for (auto window_iter = windows.rbegin(); window_iter != windows.rend(); - ++window_iter) { - aura::Window* window = *window_iter; + for (aura::Window* window : base::Reversed(windows)) { if (window == backdrop_window_) continue;
diff --git a/ash/wm/workspace/multi_window_resize_controller.cc b/ash/wm/workspace/multi_window_resize_controller.cc index 658449b..ea6f299 100644 --- a/ash/wm/workspace/multi_window_resize_controller.cc +++ b/ash/wm/workspace/multi_window_resize_controller.cc
@@ -13,6 +13,7 @@ #include "ash/wm/resize_shadow_controller.h" #include "ash/wm/window_util.h" #include "ash/wm/workspace/workspace_window_resizer.h" +#include "base/containers/adapters.h" #include "ui/aura/client/aura_constants.h" #include "ui/aura/window_delegate.h" #include "ui/base/cursor/cursor.h" @@ -387,8 +388,7 @@ int y_in_parent) const { aura::Window* parent = window_to_ignore->parent(); const aura::Window::Windows& windows = parent->children(); - for (auto i = windows.rbegin(); i != windows.rend(); ++i) { - aura::Window* window = *i; + for (aura::Window* window : base::Reversed(windows)) { if (window == window_to_ignore || !window->IsVisible()) continue; @@ -422,8 +422,7 @@ int bottom = window->bounds().bottom(); aura::Window* parent = window->parent(); const aura::Window::Windows& windows = parent->children(); - for (auto i = windows.rbegin(); i != windows.rend(); ++i) { - aura::Window* other = *i; + for (aura::Window* other : base::Reversed(windows)) { if (other == window || !other->IsVisible()) continue; switch (direction) {
diff --git a/ash/wm/workspace/workspace_window_resizer_unittest.cc b/ash/wm/workspace/workspace_window_resizer_unittest.cc index c8cde2ad..f253d8a 100644 --- a/ash/wm/workspace/workspace_window_resizer_unittest.cc +++ b/ash/wm/workspace/workspace_window_resizer_unittest.cc
@@ -16,6 +16,7 @@ #include "ash/wm/wm_event.h" #include "ash/wm/workspace/phantom_window_controller.h" #include "ash/wm/workspace_controller.h" +#include "base/containers/adapters.h" #include "base/strings/stringprintf.h" #include "base/test/metrics/histogram_tester.h" #include "base/test/scoped_feature_list.h" @@ -142,10 +143,10 @@ std::vector<int> WindowOrderAsIntVector(aura::Window* parent) const { std::vector<int> result; const aura::Window::Windows& windows = parent->children(); - for (aura::Window::Windows::const_reverse_iterator i = windows.rbegin(); - i != windows.rend(); ++i) { - if (*i == window_.get() || *i == window2_.get() || *i == window3_.get()) { - result.push_back((*i)->GetId()); + for (aura::Window* window : base::Reversed(windows)) { + if (window == window_.get() || window == window2_.get() || + window == window3_.get()) { + result.push_back(window->GetId()); } } return result;
diff --git a/base/allocator/partition_allocator/partition_alloc_unittest.cc b/base/allocator/partition_allocator/partition_alloc_unittest.cc index 1b34bc0..7f5984e5 100644 --- a/base/allocator/partition_allocator/partition_alloc_unittest.cc +++ b/base/allocator/partition_allocator/partition_alloc_unittest.cc
@@ -1195,16 +1195,20 @@ } } -TEST_P(PartitionAllocTest, GetSlotStartMultiplePages) { +// TODO(crbug.com/1217582): Disabled since the `real_size` is never set or set incorrectly. +TEST_P(PartitionAllocTest, DISABLED_GetSlotStartMultiplePages) { // Find the smallest bucket with multiple PartitionPages. size_t real_size; + bool init_real_size = false; for (PartitionBucket<ThreadSafe>& bucket : allocator.root()->buckets) { if (bucket.num_system_pages_per_slot_span > NumSystemPagesPerPartitionPage()) { real_size = bucket.slot_size; + init_real_size = true; break; } } + ASSERT_TRUE(init_real_size); const size_t requested_size = real_size - kExtraAllocSize; // Double check we don't end up with 0 or negative size.
diff --git a/base/json/json_parser_unittest.rs b/base/json/json_parser_unittest.rs index d908686a..6bb9b733 100644 --- a/base/json/json_parser_unittest.rs +++ b/base/json/json_parser_unittest.rs
@@ -1,5 +1,5 @@ -use base_rs::{JsonOptions, NewValueSlotForTesting, ValueSlotRef}; -use rust_gtest_interop_rs::prelude::*; +use base::{JsonOptions, NewValueSlotForTesting, ValueSlotRef}; +use rust_gtest_interop::prelude::*; #[gtest(RustJsonParserTest, ChromiumExtensions)] fn test_chromium_extensions() { @@ -28,6 +28,6 @@ allow_x_escapes: false, }; let mut value_slot = NewValueSlotForTesting(); - base_rs::decode_json(b"{ \"a\": 4 }", options, ValueSlotRef::from(&mut value_slot)).unwrap(); + base::decode_json(b"{ \"a\": 4 }", options, ValueSlotRef::from(&mut value_slot)).unwrap(); expect_eq!(format!("{:?}", ValueSlotRef::from(&mut value_slot)), "{\n \"a\": 4\n}\n"); }
diff --git a/base/test/android/javatests/src/org/chromium/base/test/util/FlakyTest.java b/base/test/android/javatests/src/org/chromium/base/test/util/FlakyTest.java index 83f8e9f..e650ad2 100644 --- a/base/test/android/javatests/src/org/chromium/base/test/util/FlakyTest.java +++ b/base/test/android/javatests/src/org/chromium/base/test/util/FlakyTest.java
@@ -10,6 +10,8 @@ import java.lang.annotation.Target; /** + * @deprecated Use "@DisabledTest" instead which has identical behavior. + * * This annotation is for flaky tests. * <p> * Tests with this annotation will not be run on any of the normal bots. @@ -17,6 +19,7 @@ */ @Target({ElementType.METHOD, ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) +@Deprecated public @interface FlakyTest { String message() default ""; }
diff --git a/base/threading/hang_watcher.cc b/base/threading/hang_watcher.cc index 5cb6b27..46f63a23 100644 --- a/base/threading/hang_watcher.cc +++ b/base/threading/hang_watcher.cc
@@ -113,6 +113,26 @@ break; } break; + + case HangWatcher::ProcessType::kUtilityProcess: + switch (thread_type) { + case HangWatcher::ThreadType::kIOThread: + UMA_HISTOGRAM_BOOLEAN( + "HangWatcher.IsThreadHung.UtilityProcess." + "IOThread", + any_thread_hung); + break; + case HangWatcher::ThreadType::kMainThread: + UMA_HISTOGRAM_BOOLEAN( + "HangWatcher.IsThreadHung.UtilityProcess." + "MainThread", + any_thread_hung); + break; + case HangWatcher::ThreadType::kThreadPoolThread: + // Not recorded for now. + break; + } + break; } } @@ -173,6 +193,17 @@ &kEnableHangWatcher, "renderer_process_threadpool_log_level", static_cast<int>(LoggingLevel::kUmaOnly)}; +// Utility process. +constexpr base::FeatureParam<int> kUtilityProcessIOThreadLogLevel{ + &kEnableHangWatcher, "utility_process_io_thread_log_level", + static_cast<int>(LoggingLevel::kUmaOnly)}; +constexpr base::FeatureParam<int> kUtilityProcessMainThreadLogLevel{ + &kEnableHangWatcher, "utility_process_main_thread_log_level", + static_cast<int>(LoggingLevel::kUmaOnly)}; +constexpr base::FeatureParam<int> kUtilityProcessThreadPoolLogLevel{ + &kEnableHangWatcher, "utility_process_threadpool_log_level", + static_cast<int>(LoggingLevel::kUmaOnly)}; + // static const base::TimeDelta WatchHangsInScope::kDefaultHangWatchTime = base::Seconds(10); @@ -345,6 +376,18 @@ static_cast<LoggingLevel>(kRendererProcessMainThreadLogLevel.Get()), std::memory_order_relaxed); break; + + case HangWatcher::ProcessType::kUtilityProcess: + g_threadpool_log_level.store( + static_cast<LoggingLevel>(kUtilityProcessThreadPoolLogLevel.Get()), + std::memory_order_relaxed); + g_io_thread_log_level.store( + static_cast<LoggingLevel>(kUtilityProcessIOThreadLogLevel.Get()), + std::memory_order_relaxed); + g_main_thread_log_level.store( + static_cast<LoggingLevel>(kUtilityProcessMainThreadLogLevel.Get()), + std::memory_order_relaxed); + break; } }
diff --git a/base/threading/hang_watcher.h b/base/threading/hang_watcher.h index 86edd64..0a70c0e 100644 --- a/base/threading/hang_watcher.h +++ b/base/threading/hang_watcher.h
@@ -111,7 +111,8 @@ kBrowserProcess = 1, kGPUProcess = 2, kRendererProcess = 3, - kMax = kRendererProcess + kUtilityProcess = 4, + kMax = kUtilityProcess }; // Describes the type of a thread for logging purposes.
diff --git a/base/values_unittest.rs b/base/values_unittest.rs index c7c936e..2c8d9a9 100644 --- a/base/values_unittest.rs +++ b/base/values_unittest.rs
@@ -1,5 +1,5 @@ -use base_rs::{NewValueSlotForTesting, ValueSlotRef}; -use rust_gtest_interop_rs::prelude::*; +use base::{NewValueSlotForTesting, ValueSlotRef}; +use rust_gtest_interop::prelude::*; #[gtest(RustValuesTest, AllocDealloc)] fn test_alloc_dealloc() {
diff --git a/build/config/rust.gni b/build/config/rust.gni index e65327c8..e917732d 100644 --- a/build/config/rust.gni +++ b/build/config/rust.gni
@@ -97,7 +97,7 @@ # We use the Rust linker for building test executables, so we only build them # if we're able to use the Rust linker. We could use the C++ linker for this # too, we've just not set up GN to do so at the moment. -build_rust_unit_tests = toolchain_has_rust && rustc_can_link +can_build_rust_unit_tests = toolchain_has_rust && rustc_can_link # We want to store rust_sysroot as a source-relative variable for ninja # portability. In practice if an external toolchain was specified, it might
diff --git a/build/fuchsia/linux.sdk.sha1 b/build/fuchsia/linux.sdk.sha1 index 89f3d1a..6c9d9c5 100644 --- a/build/fuchsia/linux.sdk.sha1 +++ b/build/fuchsia/linux.sdk.sha1
@@ -1 +1 @@ -7.20220309.0.1 +7.20220309.2.1
diff --git a/build/fuchsia/mac.sdk.sha1 b/build/fuchsia/mac.sdk.sha1 index 89f3d1a..6c9d9c5 100644 --- a/build/fuchsia/mac.sdk.sha1 +++ b/build/fuchsia/mac.sdk.sha1
@@ -1 +1 @@ -7.20220309.0.1 +7.20220309.2.1
diff --git a/build/rust/cargo_crate.gni b/build/rust/cargo_crate.gni index 14aca63e..b28da98 100644 --- a/build/rust/cargo_crate.gni +++ b/build/rust/cargo_crate.gni
@@ -25,7 +25,7 @@ # epoch # deps # features -# skip_unit_tests +# build_native_rust_unit_tests # edition # crate_name # All just as in rust_static_library.gni @@ -104,6 +104,10 @@ target_type = "rust_library" } + if (!defined(build_native_rust_unit_tests)) { + build_native_rust_unit_tests = true + } + # We may generate multiple build rules for the same Cargo crate, as they may # have multiple build configurations: for use from deps, build-deps or # dev-deps. But that would try to build multiple crates with the same name, @@ -239,7 +243,6 @@ if (current_toolchain == host_toolchain) { rust_target(build_script_name) { target_type = "executable" - skip_unit_tests = true sources = invoker.build_sources crate_root = invoker.build_root if (defined(invoker.build_deps)) {
diff --git a/build/rust/mixed_target.gni b/build/rust/mixed_target.gni index 90bc8ee7..5b44778 100644 --- a/build/rust/mixed_target.gni +++ b/build/rust/mixed_target.gni
@@ -33,9 +33,6 @@ # rs_configs # rs_deps # rs_public_deps -# rs_test_deps -# rs_skip_unit_tests -# rs_unit_test_target # rs_crate_name # rs_crate_root # rs_features @@ -44,6 +41,11 @@ # 'rs_' prefix, e.g. rs_configs here means the same as 'configs' in # rust_static_library. # +# rs_build_native_rust_unit_tests +# This is used by Rust build tests, but should not be used in Chromium +# code. Instead, prefer to write gtest tests. See how to do that in +# //testing/rust_gtest_interop/README.md. +# # In the event that Rust is not enabled in the build, this will produce a # plain C/C++ target. # @@ -71,14 +73,12 @@ "rs_configs", "rs_deps", "rs_public_deps", - "rs_test_deps", "rs_sources", "rs_features", "rs_cxx_bindings", "rs_crate_name", "rs_crate_root", - "rs_skip_unit_tests", - "rs_unit_test_target", + "rs_build_native_rust_unit_tests", ] # TODO(crbug.com/1280708, crbug.com/1304707): Drop toolchain_has_rust after we have support for @@ -93,6 +93,7 @@ if (_rs_enable) { rust_static_library("${_target_name}_rs") { + crate_name = _target_name mutually_dependent_target = ":${_target_name}" mutually_dependent_public_deps = [] if (defined(invoker.public_deps)) { @@ -109,9 +110,6 @@ # sets them for each type of rust target. configs += invoker.rs_configs } - if (defined(invoker.rs_test_deps)) { - test_deps = invoker.rs_test_deps - } if (defined(invoker.rs_sources)) { sources = invoker.rs_sources } @@ -130,12 +128,9 @@ if (defined(invoker.rs_crate_name)) { crate_name = invoker.rs_crate_name } - skip_unit_tests = true - if (defined(invoker.rs_skip_unit_tests)) { - skip_unit_tests = invoker.rs_skip_unit_tests - } - if (defined(invoker.rs_unit_test_target)) { - unit_test_target = invoker.rs_unit_test_target + build_native_rust_unit_tests = false + if (defined(invoker.rs_build_native_rust_unit_tests)) { + build_native_rust_unit_tests = invoker.rs_build_native_rust_unit_tests } if (defined(invoker.testonly) && invoker.testonly) { testonly = true @@ -172,8 +167,8 @@ public_deps += [ ":${_target_name}_rs" ] if (defined(visibility)) { - if (!defined(invoker.rs_skip_unit_tests) || - !invoker.rs_skip_unit_tests) { + if (defined(invoker.rs_build_native_rust_unit_tests) && + invoker.rs_build_native_rust_unit_tests) { _unit_test_target = "${_target_name}_rs_unittests" if (defined(invoker.rs_unit_test_target)) { _unit_test_target = invoker.rs_unit_test_target
diff --git a/build/rust/rust_executable.gni b/build/rust/rust_executable.gni index 2f6c18f..ab22c51 100644 --- a/build/rust/rust_executable.gni +++ b/build/rust/rust_executable.gni
@@ -17,10 +17,13 @@ # List of GN targets on which this crate's tests depend, in addition # to deps. # -# skip_unit_tests (optional) -# Avoids building unit tests associated with this Rust crate. Normally, -# this template will create a `<name>_unittests` executable in the output -# directory; this behavior is suppressed if this flag is set to true. +# build_native_rust_unit_tests (optional) +# Builds native unit tests (under #[cfg(test)]) written inside the Rust +# crate. This will create a `<name>_unittests` executable in the output +# directory when set to true. +# Chromium code should not set this, and instead prefer to split the code +# into a library and write gtests against it. See how to do that in +# //testing/rust_gtest_interop/README.md. # # unit_test_target (optional) # Overrides the default name for the unit tests target
diff --git a/build/rust/rust_static_library.gni b/build/rust/rust_static_library.gni index 7fc8bd1..a31df60 100644 --- a/build/rust/rust_static_library.gni +++ b/build/rust/rust_static_library.gni
@@ -90,10 +90,10 @@ # to include headers from the mutually_dependent_target by depending on its # public_deps. # -# skip_unit_tests (optional) -# Avoids building unit tests associated with this Rust crate. Normally, -# this template will create a `<name>_unittests` executable in the output -# directory; this behavior is suppressed if this flag is set to true. +# build_native_rust_unit_tests (optional) +# Builds native unit tests (under #[cfg(test)]) written inside the Rust +# crate. This will create a `<name>_unittests` executable in the output +# directory when set to true. # # unit_test_target (optional) # Overrides the default name for the unit tests target
diff --git a/build/rust/rust_target.gni b/build/rust/rust_target.gni index eeb2896..fa335ee 100644 --- a/build/rust/rust_target.gni +++ b/build/rust/rust_target.gni
@@ -116,9 +116,10 @@ _public_deps += invoker.public_deps } - _build_unit_tests = build_rust_unit_tests - if (defined(invoker.skip_unit_tests) && invoker.skip_unit_tests == true) { - _build_unit_tests = false + _build_unit_tests = false + if (defined(invoker.build_native_rust_unit_tests)) { + _build_unit_tests = + invoker.build_native_rust_unit_tests && can_build_rust_unit_tests } # Declares that the Rust crate generates bindings between C++ and Rust via the
diff --git a/build/rust/rust_unit_test.gni b/build/rust/rust_unit_test.gni index 31a713b..c5ca024 100644 --- a/build/rust/rust_unit_test.gni +++ b/build/rust/rust_unit_test.gni
@@ -39,7 +39,7 @@ # import loop). template("rust_unit_test") { - assert(build_rust_unit_tests) + assert(can_build_rust_unit_tests) if (defined(invoker.crate_name)) { _crate_name = invoker.crate_name } else {
diff --git a/build/rust/tests/BUILD.gn b/build/rust/tests/BUILD.gn index d435cac..c2b5d08d 100644 --- a/build/rust/tests/BUILD.gn +++ b/build/rust/tests/BUILD.gn
@@ -11,7 +11,7 @@ testonly = true deps = [ ":deps" ] - if (build_rust_unit_tests) { + if (can_build_rust_unit_tests) { deps += [ ":build_rust_tests" ] } } @@ -43,7 +43,7 @@ "test_rust_shared_library", ] } - if (build_rust_unit_tests) { + if (can_build_rust_unit_tests) { deps += [ "test_cpp_including_rust:test_cpp_including_rust_unittests", "test_mixed_component:test_mixed_component_rs_unittests", @@ -83,7 +83,7 @@ } } -if (build_rust_unit_tests) { +if (can_build_rust_unit_tests) { # A group covering all native Rust unit tests under //build/rust directory. rust_unit_tests_group("build_rust_tests") { deps = [ ":deps" ]
diff --git a/build/rust/tests/test_mixed_component/BUILD.gn b/build/rust/tests/test_mixed_component/BUILD.gn index be0a0ece..9b879d5 100644 --- a/build/rust/tests/test_mixed_component/BUILD.gn +++ b/build/rust/tests/test_mixed_component/BUILD.gn
@@ -13,7 +13,10 @@ rs_sources = [ "component.rs" ] rs_crate_root = "component.rs" rs_cxx_bindings = [ "component.rs" ] - rs_skip_unit_tests = false + + # TODO(danakj): We should write a gtest binary instead of using native rust + # tests. Then remove this flag from mixed_target.gni. + rs_build_native_rust_unit_tests = true } executable("test_mixed_component_demo") {
diff --git a/build/rust/tests/test_mixed_executable/BUILD.gn b/build/rust/tests/test_mixed_executable/BUILD.gn index 5525a48f..a55587bef 100644 --- a/build/rust/tests/test_mixed_executable/BUILD.gn +++ b/build/rust/tests/test_mixed_executable/BUILD.gn
@@ -8,5 +8,4 @@ sources = [ "main.cc" ] rs_sources = [ "src/lib.rs" ] rs_cxx_bindings = [ "src/lib.rs" ] - rs_skip_unit_tests = false }
diff --git a/build/rust/tests/test_mixed_shared_library/BUILD.gn b/build/rust/tests/test_mixed_shared_library/BUILD.gn index e671704..34f31e92 100644 --- a/build/rust/tests/test_mixed_shared_library/BUILD.gn +++ b/build/rust/tests/test_mixed_shared_library/BUILD.gn
@@ -17,7 +17,10 @@ "//build/rust/tests/test_cpp_including_rust:*", ] deps = [ ":some_headers" ] - rs_skip_unit_tests = false + + # TODO(danakj): We should write a gtest binary instead of using native rust + # tests. Then remove this flag from mixed_target.gni. + rs_build_native_rust_unit_tests = true } # Exists to test that such dependents are visible to the source_set
diff --git a/build/rust/tests/test_mixed_static_library/BUILD.gn b/build/rust/tests/test_mixed_static_library/BUILD.gn index 9e1bf63..b3e444d 100644 --- a/build/rust/tests/test_mixed_static_library/BUILD.gn +++ b/build/rust/tests/test_mixed_static_library/BUILD.gn
@@ -18,7 +18,10 @@ "//build/rust/tests/test_rust_unittests:*", ] deps = [ ":some_headers" ] - rs_skip_unit_tests = false + + # TODO(danakj): We should write a gtest binary instead of using native rust + # tests. Then remove this flag from mixed_target.gni. + rs_build_native_rust_unit_tests = true } # Exists to test that such dependents are visible to the source_set
diff --git a/build/rust/tests/test_mixed_testonly_executable/BUILD.gn b/build/rust/tests/test_mixed_testonly_executable/BUILD.gn index 6fde9a7..0e20ec7 100644 --- a/build/rust/tests/test_mixed_testonly_executable/BUILD.gn +++ b/build/rust/tests/test_mixed_testonly_executable/BUILD.gn
@@ -9,5 +9,4 @@ rs_sources = [ "src/lib.rs" ] rs_cxx_bindings = [ "src/lib.rs" ] testonly = true - rs_skip_unit_tests = false }
diff --git a/build/rust/tests/test_rust_exe/BUILD.gn b/build/rust/tests/test_rust_exe/BUILD.gn index c32634f..d20bcc2 100644 --- a/build/rust/tests/test_rust_exe/BUILD.gn +++ b/build/rust/tests/test_rust_exe/BUILD.gn
@@ -14,4 +14,5 @@ "//build/rust/tests/test_rust_static_library", "//build/rust/tests/test_rust_static_library_non_standard_arrangement", ] + build_native_rust_unit_tests = true }
diff --git a/build/rust/tests/test_rust_exe/main.rs b/build/rust/tests/test_rust_exe/main.rs index 88c50a96..3ed0237 100644 --- a/build/rust/tests/test_rust_exe/main.rs +++ b/build/rust/tests/test_rust_exe/main.rs
@@ -5,7 +5,7 @@ use test_rlib_crate::say_hello_from_crate; fn main() { - assert_eq!(test_mixed_static_library_rs::add_two_ints_via_rust_then_cpp(12, 13), 25); + assert_eq!(test_mixed_static_library::add_two_ints_via_rust_then_cpp(12, 13), 25); assert_eq!(test_proc_macro_crate::calculate_using_proc_macro!(), 30); assert_eq!(test_rust_static_library::add_two_ints_via_rust(3, 4), 7); assert_eq!(test_rust_static_library_non_standard_arrangement::do_subtract(4, 3), 1); @@ -28,7 +28,7 @@ #[test] fn test_call_to_rust_then_cpp() { - assert_eq!(test_mixed_static_library_rs::add_two_ints_via_rust_then_cpp(12, 13), 25) + assert_eq!(test_mixed_static_library::add_two_ints_via_rust_then_cpp(12, 13), 25) } #[test]
diff --git a/build/rust/tests/test_rust_multiple_dep_versions_exe/v1/BUILD.gn b/build/rust/tests/test_rust_multiple_dep_versions_exe/v1/BUILD.gn index f97c9daa..e264a2cf 100644 --- a/build/rust/tests/test_rust_multiple_dep_versions_exe/v1/BUILD.gn +++ b/build/rust/tests/test_rust_multiple_dep_versions_exe/v1/BUILD.gn
@@ -8,7 +8,8 @@ epoch = "1" sources = [ "src/lib.rs" ] - # Avoiding collision between v1 and v2 unit tests.The output binary should - # be versioned or renamed somehow. - skip_unit_tests = true + # TODO(crbug.com/1304751): This should be true to test that we avoid collision + # between v1 and v2 unit tests. The output binary should be versioned or + # renamed somehow. + build_native_rust_unit_tests = false }
diff --git a/build/rust/tests/test_rust_multiple_dep_versions_exe/v2/BUILD.gn b/build/rust/tests/test_rust_multiple_dep_versions_exe/v2/BUILD.gn index c4ac765..beb7e5a 100644 --- a/build/rust/tests/test_rust_multiple_dep_versions_exe/v2/BUILD.gn +++ b/build/rust/tests/test_rust_multiple_dep_versions_exe/v2/BUILD.gn
@@ -8,7 +8,8 @@ epoch = "2" sources = [ "src/lib.rs" ] - # Avoiding collision between v1 and v2 unit tests.The output binary should - # be versioned or renamed somehow. - skip_unit_tests = true + # TODO(crbug.com/1304751): This should be true to test that we avoid collision + # between v1 and v2 unit tests. The output binary should be versioned or + # renamed somehow. + build_native_rust_unit_tests = false }
diff --git a/build/rust/tests/test_rust_shared_library/BUILD.gn b/build/rust/tests/test_rust_shared_library/BUILD.gn index 9e9a179..53ce222 100644 --- a/build/rust/tests/test_rust_shared_library/BUILD.gn +++ b/build/rust/tests/test_rust_shared_library/BUILD.gn
@@ -8,5 +8,6 @@ rust_shared_library("test_rust_shared_library") { sources = [ "src/lib.rs" ] cxx_bindings = [ "src/lib.rs" ] + build_native_rust_unit_tests = true } }
diff --git a/build/rust/tests/test_rust_static_library/BUILD.gn b/build/rust/tests/test_rust_static_library/BUILD.gn index e565f1c..d3c21b0 100644 --- a/build/rust/tests/test_rust_static_library/BUILD.gn +++ b/build/rust/tests/test_rust_static_library/BUILD.gn
@@ -7,4 +7,5 @@ rust_static_library("test_rust_static_library") { sources = [ "src/lib.rs" ] cxx_bindings = [ "src/lib.rs" ] + build_native_rust_unit_tests = true }
diff --git a/build/rust/tests/test_rust_static_library_non_standard_arrangement/BUILD.gn b/build/rust/tests/test_rust_static_library_non_standard_arrangement/BUILD.gn index ffa362e7..227e7ba7 100644 --- a/build/rust/tests/test_rust_static_library_non_standard_arrangement/BUILD.gn +++ b/build/rust/tests/test_rust_static_library_non_standard_arrangement/BUILD.gn
@@ -8,4 +8,8 @@ sources = [ "foo.rs" ] crate_root = "foo.rs" unit_test_target = "foo_tests" + + # TODO(danakj): We should write a gtest binary instead of using native rust + # tests outside of a cargo_crate(). + build_native_rust_unit_tests = true }
diff --git a/build/rust/tests/test_rust_unittests/main.rs b/build/rust/tests/test_rust_unittests/main.rs index 328a46c..630bc98 100644 --- a/build/rust/tests/test_rust_unittests/main.rs +++ b/build/rust/tests/test_rust_unittests/main.rs
@@ -6,7 +6,7 @@ extern crate test; use test::Bencher; -use test_mixed_static_library_rs::add_two_ints_using_cpp; +use test_mixed_static_library::add_two_ints_using_cpp; #[test] fn test_call_into_mixed_static_library() {
diff --git a/build/rust/tests/test_variable_static_library/BUILD.gn b/build/rust/tests/test_variable_static_library/BUILD.gn index bcf62ff..e3424fa 100644 --- a/build/rust/tests/test_variable_static_library/BUILD.gn +++ b/build/rust/tests/test_variable_static_library/BUILD.gn
@@ -17,7 +17,7 @@ ] rs_sources = [ "src/lib.rs" ] rs_cxx_bindings = [ "src/lib.rs" ] - rs_skip_unit_tests = false + rs_build_native_rust_unit_tests = true } executable("test_variable_static_library_demo") {
diff --git a/chrome/android/features/start_surface/internal/java/src/org/chromium/chrome/features/start_surface/StartSurfaceDelegate.java b/chrome/android/features/start_surface/internal/java/src/org/chromium/chrome/features/start_surface/StartSurfaceDelegate.java index 71132c2..d0626af 100644 --- a/chrome/android/features/start_surface/internal/java/src/org/chromium/chrome/features/start_surface/StartSurfaceDelegate.java +++ b/chrome/android/features/start_surface/internal/java/src/org/chromium/chrome/features/start_surface/StartSurfaceDelegate.java
@@ -38,8 +38,10 @@ /** StartSurfaceDelegate. */ public class StartSurfaceDelegate { public static Layout createStartSurfaceLayout(Context context, LayoutUpdateHost updateHost, - LayoutRenderHost renderHost, StartSurface startSurface, JankTracker jankTracker) { - return new StartSurfaceLayout(context, updateHost, renderHost, startSurface, jankTracker); + LayoutRenderHost renderHost, StartSurface startSurface, JankTracker jankTracker, + ViewGroup startSurfaceScrimAnchor, ScrimCoordinator scrimCoordinator) { + return new StartSurfaceLayout(context, updateHost, renderHost, startSurface, jankTracker, + startSurfaceScrimAnchor, scrimCoordinator); } /** {@see StartSurfaceCoordinator} */
diff --git a/chrome/android/features/start_surface/internal/java/src/org/chromium/chrome/features/start_surface/StartSurfaceLayout.java b/chrome/android/features/start_surface/internal/java/src/org/chromium/chrome/features/start_surface/StartSurfaceLayout.java index c36b107..74a8040 100644 --- a/chrome/android/features/start_surface/internal/java/src/org/chromium/chrome/features/start_surface/StartSurfaceLayout.java +++ b/chrome/android/features/start_surface/internal/java/src/org/chromium/chrome/features/start_surface/StartSurfaceLayout.java
@@ -46,7 +46,10 @@ import org.chromium.chrome.browser.tasks.tab_management.TabUiFeatureUtilities; import org.chromium.chrome.browser.util.ChromeAccessibilityUtil; import org.chromium.components.browser_ui.widget.animation.Interpolators; +import org.chromium.components.browser_ui.widget.scrim.ScrimCoordinator; +import org.chromium.components.browser_ui.widget.scrim.ScrimProperties; import org.chromium.components.version_info.VersionInfo; +import org.chromium.ui.modelutil.PropertyModel; import org.chromium.ui.resources.ResourceManager; import java.util.ArrayList; @@ -72,7 +75,7 @@ private static final String TRACE_HIDE_START_SURFACE = "StartSurfaceLayout.Hide.StartSurface"; // The transition animation from a tab to the tab switcher. - private AnimatorSet mTabToSwitcherAnimation; + private AnimatorSet mTabToSwitcherShrinkExpandAnimation; private boolean mIsAnimating; private TabListSceneLayer mSceneLayer; @@ -80,6 +83,10 @@ private final JankTracker mJankTracker; private final StartSurface.Controller mController; private final StartSurface.OverviewModeObserver mStartSurfaceObserver; + @Nullable + private final ViewGroup mScrimAnchor; + @Nullable + private final ScrimCoordinator mScrimCoordinator; // Always use getGridTabListDelegate() instead to make sure it's not null. @Nullable private TabSwitcher.TabListDelegate mGridTabListDelegate; @@ -112,7 +119,8 @@ private PerfListener mPerfListenerForTesting; public StartSurfaceLayout(Context context, LayoutUpdateHost updateHost, - LayoutRenderHost renderHost, StartSurface startSurface, JankTracker jankTracker) { + LayoutRenderHost renderHost, StartSurface startSurface, JankTracker jankTracker, + ViewGroup startSurfaceScrimAnchor, ScrimCoordinator scrimCoordinator) { super(context, updateHost, renderHost); mDummyLayoutTab = createLayoutTab(Tab.INVALID_TAB_ID, false); mDummyLayoutTab.setShowToolbar(true); @@ -120,6 +128,8 @@ mStartSurface.setOnTabSelectingListener(this::onTabSelecting); mController = mStartSurface.getController(); mJankTracker = jankTracker; + mScrimAnchor = startSurfaceScrimAnchor; + mScrimCoordinator = scrimCoordinator; mStartSurfaceObserver = new StartSurface.OverviewModeObserver() { @Override @@ -134,7 +144,7 @@ // The Tab-to-GTS animation is done, and it's time to renew the thumbnail without // causing janky frames. When animation is off, the thumbnail is already updated // when showing the GTS. - if (TabUiFeatureUtilities.isTabToGtsAnimationEnabled()) { + if (isTabGtsAnimationEnabled()) { // Delay thumbnail taking a bit more to make it less likely to happen before the // thumbnail taking triggered by ThumbnailFetcher. See crbug.com/996385 for // details. @@ -160,8 +170,7 @@ // If not doing GTS-to-Tab transition animation or start surface homepage is hiding // (instead of grid tab switcher), we show the fade-out instead, which was already // done. - if (!TabUiFeatureUtilities.isTabToGtsAnimationEnabled() - || isHidingStartSurfaceHomepage()) { + if (!isTabGtsAnimationEnabled() || isHidingStartSurfaceHomepage()) { postHiding(); return; } @@ -258,33 +267,34 @@ quick = getGridTabListDelegate().prepareOverview(); } - // Skip shrinking animation when there is no tab in current tab model. If it's showing - // start surface, we don't show the shrink tab animation. + // Skip animation when there is no tab in current tab model or If it's showing + // start surface, we don't show the shrink tab animatio. boolean isCurrentTabModelEmpty = mTabModelSelector.getCurrentModel().getCount() == 0; - boolean showShrinkingAnimation = animate - && TabUiFeatureUtilities.isTabToGtsAnimationEnabled() && !isCurrentTabModelEmpty - && !isShowingStartSurfaceHomepage; + animate = animate && !isCurrentTabModelEmpty && !isShowingStartSurfaceHomepage; - boolean skipSlowZooming = TabUiFeatureUtilities.SKIP_SLOW_ZOOMING.getValue(); - Log.d(TAG, "SkipSlowZooming = " + skipSlowZooming); - if (skipSlowZooming) { - showShrinkingAnimation &= quick; + if (mScrimCoordinator != null + && TabUiFeatureUtilities.isTabletGridTabSwitcherPolishEnabled(getContext())) { + showOverviewWithScrim(animate); + } else { + showOverviewWithTabShrink(animate, + () + -> getGridTabListDelegate().getThumbnailLocationOfCurrentTab(false), + isShowingStartSurfaceHomepage, quick); } - if (TabUiFeatureUtilities.isLaunchPolishEnabled()) { - // Intentionally disable the shrinking animation when accessibility is enabled. - // During the shrinking animation, since the ComponsitorViewHolder is not focusable, - // I think we are in a temporary no "valid" focus target state, so the focus shifts - // to the omnibox and triggers an accessibility announcement of the URL and a - // keyboard hiding event. Disable the animation to avoid this temporary state. - showShrinkingAnimation &= !ChromeAccessibilityUtil.get().isAccessibilityEnabled(); - } + } - if (!showShrinkingAnimation) { - mController.showOverview(animate); - return; - } + private void showOverviewWithScrim(boolean animate) { + PropertyModel scrimProp = new PropertyModel.Builder(ScrimProperties.REQUIRED_KEYS) + .with(ScrimProperties.ANCHOR_VIEW, mScrimAnchor) + .with(ScrimProperties.SHOW_IN_FRONT_OF_ANCHOR_VIEW, false) + .build(); + mScrimCoordinator.showScrim(scrimProp); + mController.showOverview(animate); + } - shrinkTab(animate, () -> getGridTabListDelegate().getThumbnailLocationOfCurrentTab(false)); + private void removeBrowserScrim() { + if (mScrimCoordinator == null || !mScrimCoordinator.isShowingScrim()) return; + mScrimCoordinator.hideScrim(true); } @Override @@ -349,7 +359,8 @@ updateCacheVisibleIds(new LinkedList<>(Arrays.asList(sourceTabId))); mIsAnimating = true; - mController.hideOverview(!TabUiFeatureUtilities.isTabToGtsAnimationEnabled()); + removeBrowserScrim(); + mController.hideOverview(!isTabGtsAnimationEnabled()); } @Override @@ -412,8 +423,10 @@ @Override protected void forceAnimationToFinish() { super.forceAnimationToFinish(); - if (mTabToSwitcherAnimation != null) { - if (mTabToSwitcherAnimation.isRunning()) mTabToSwitcherAnimation.end(); + if (mTabToSwitcherShrinkExpandAnimation != null) { + if (mTabToSwitcherShrinkExpandAnimation.isRunning()) { + mTabToSwitcherShrinkExpandAnimation.end(); + } } } @@ -442,8 +455,29 @@ * @param animate Whether to play an entry animation. * @param target The target {@link Rect} area. */ - private void shrinkTab(boolean animate, Supplier<Rect> target) { - if (target.get() == null) { + private void showOverviewWithTabShrink(boolean animate, Supplier<Rect> target, + boolean isShowingStartSurfaceHomepage, boolean quick) { + // Skip shrinking animation when there is no tab in current tab model. If it's showing + // start surface, we don't show the shrink tab animation. + boolean isCurrentTabModelEmpty = mTabModelSelector.getCurrentModel().getCount() == 0; + boolean showShrinkingAnimation = animate && isTabGtsAnimationEnabled() + && !isCurrentTabModelEmpty && !isShowingStartSurfaceHomepage; + + boolean skipSlowZooming = TabUiFeatureUtilities.SKIP_SLOW_ZOOMING.getValue(); + Log.d(TAG, "SkipSlowZooming = " + skipSlowZooming); + if (skipSlowZooming) { + showShrinkingAnimation &= quick; + } + if (TabUiFeatureUtilities.isLaunchPolishEnabled()) { + // Intentionally disable the shrinking animation when accessibility is enabled. + // During the shrinking animation, since the ComponsitorViewHolder is not focusable, + // I think we are in a temporary no "valid" focus target state, so the focus shifts + // to the omnibox and triggers an accessibility announcement of the URL and a + // keyboard hiding event. Disable the animation to avoid this temporary state. + showShrinkingAnimation &= !ChromeAccessibilityUtil.get().isAccessibilityEnabled(); + } + + if (!showShrinkingAnimation || target.get() == null) { mController.showOverview(animate); return; } @@ -486,12 +520,12 @@ backgroundAlpha.setInterpolator(Interpolators.FAST_OUT_LINEAR_IN_INTERPOLATOR); animationList.add(backgroundAlpha); - mTabToSwitcherAnimation = new AnimatorSet(); - mTabToSwitcherAnimation.playTogether(animationList); - mTabToSwitcherAnimation.addListener(new AnimatorListenerAdapter() { + mTabToSwitcherShrinkExpandAnimation = new AnimatorSet(); + mTabToSwitcherShrinkExpandAnimation.playTogether(animationList); + mTabToSwitcherShrinkExpandAnimation.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { - mTabToSwitcherAnimation = null; + mTabToSwitcherShrinkExpandAnimation = null; // Step 2: fade in the real GTS RecyclerView. mController.showOverview(true); @@ -502,7 +536,7 @@ mStartTime = SystemClock.elapsedRealtime(); mLastFrameTime = SystemClock.elapsedRealtime(); mMaxFrameInterval = 0; - mTabToSwitcherAnimation.start(); + mTabToSwitcherShrinkExpandAnimation.start(); } /** @@ -541,12 +575,12 @@ backgroundAlpha.setInterpolator(Interpolators.FAST_OUT_LINEAR_IN_INTERPOLATOR); animationList.add(backgroundAlpha); - mTabToSwitcherAnimation = new AnimatorSet(); - mTabToSwitcherAnimation.playTogether(animationList); - mTabToSwitcherAnimation.addListener(new AnimatorListenerAdapter() { + mTabToSwitcherShrinkExpandAnimation = new AnimatorSet(); + mTabToSwitcherShrinkExpandAnimation.playTogether(animationList); + mTabToSwitcherShrinkExpandAnimation.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { - mTabToSwitcherAnimation = null; + mTabToSwitcherShrinkExpandAnimation = null; postHiding(); reportAnimationPerf(false); @@ -556,7 +590,7 @@ mStartTime = SystemClock.elapsedRealtime(); mLastFrameTime = SystemClock.elapsedRealtime(); mMaxFrameInterval = 0; - mTabToSwitcherAnimation.start(); + mTabToSwitcherShrinkExpandAnimation.start(); } private Rect getThumbnailLocationOfCurrentTab() { @@ -689,9 +723,7 @@ // The content viewport is intentionally sent as both params below. mSceneLayer.pushLayers(getContext(), contentViewport, contentViewport, this, tabContentManager, resourceManager, browserControls, - TabUiFeatureUtilities.isTabToGtsAnimationEnabled() - ? currentTabListDelegate.getResourceId() - : 0, + isTabGtsAnimationEnabled() ? currentTabListDelegate.getResourceId() : 0, mBackgroundAlpha, currentTabListDelegate.getTabListTopOffset()); mFrameCount++; if (mLastFrameTime != 0) { @@ -708,7 +740,7 @@ @Override public boolean onUpdateAnimation(long time, boolean jumpToEnd) { - return mTabToSwitcherAnimation == null && !mIsAnimating; + return mTabToSwitcherShrinkExpandAnimation == null && !mIsAnimating; } @Override @@ -722,4 +754,15 @@ } return super.canHostBeFocusable(); } + + /** + * Shrink/Expand animation is disabled for Tablet TabSwitcher launch polish. + * @return + */ + private boolean isTabGtsAnimationEnabled() { + if (TabUiFeatureUtilities.isTabletGridTabSwitcherPolishEnabled(getContext())) { + return false; + } + return TabUiFeatureUtilities.isTabToGtsAnimationEnabled(); + } }
diff --git a/chrome/android/features/tab_ui/java/src/org/chromium/chrome/browser/tasks/tab_management/TabManagementDelegate.java b/chrome/android/features/tab_ui/java/src/org/chromium/chrome/browser/tasks/tab_management/TabManagementDelegate.java index 533bdf3..f1dad7b 100644 --- a/chrome/android/features/tab_ui/java/src/org/chromium/chrome/browser/tasks/tab_management/TabManagementDelegate.java +++ b/chrome/android/features/tab_ui/java/src/org/chromium/chrome/browser/tasks/tab_management/TabManagementDelegate.java
@@ -207,10 +207,14 @@ * @param updateHost The parent {@link LayoutUpdateHost}. * @param renderHost The parent {@link LayoutRenderHost}. * @param startSurface The {@link StartSurface} the layout should own. + * @param startSurfaceScrimAnchor {@link ViewGroup} used by start surface layout to show scrim + * when overview is visible. + * @param scrimCoordinator {@link ScrimCoordinator} to show/hide scrim. * @return The {@link StartSurfaceLayout}. */ Layout createStartSurfaceLayout(Context context, LayoutUpdateHost updateHost, - LayoutRenderHost renderHost, StartSurface startSurface, JankTracker jankTracker); + LayoutRenderHost renderHost, StartSurface startSurface, JankTracker jankTracker, + ViewGroup startSurfaceScrimAnchor, ScrimCoordinator scrimCoordinator); /** * Create the {@link StartSurface}
diff --git a/chrome/android/features/tab_ui/java/src/org/chromium/chrome/browser/tasks/tab_management/TabManagementDelegateImpl.java b/chrome/android/features/tab_ui/java/src/org/chromium/chrome/browser/tasks/tab_management/TabManagementDelegateImpl.java index ae1fdd2..6a23f0e 100644 --- a/chrome/android/features/tab_ui/java/src/org/chromium/chrome/browser/tasks/tab_management/TabManagementDelegateImpl.java +++ b/chrome/android/features/tab_ui/java/src/org/chromium/chrome/browser/tasks/tab_management/TabManagementDelegateImpl.java
@@ -155,9 +155,10 @@ @Override public Layout createStartSurfaceLayout(Context context, LayoutUpdateHost updateHost, - LayoutRenderHost renderHost, StartSurface startSurface, JankTracker jankTracker) { - return StartSurfaceDelegate.createStartSurfaceLayout( - context, updateHost, renderHost, startSurface, jankTracker); + LayoutRenderHost renderHost, StartSurface startSurface, JankTracker jankTracker, + ViewGroup startSurfaceScrimAnchor, ScrimCoordinator scrimCoordinator) { + return StartSurfaceDelegate.createStartSurfaceLayout(context, updateHost, renderHost, + startSurface, jankTracker, startSurfaceScrimAnchor, scrimCoordinator); } @Override
diff --git a/chrome/android/features/tab_ui/javatests/src/org/chromium/chrome/browser/tasks/tab_management/TabSwitcherTabletTest.java b/chrome/android/features/tab_ui/javatests/src/org/chromium/chrome/browser/tasks/tab_management/TabSwitcherTabletTest.java index 25ed18b..e2bba88 100644 --- a/chrome/android/features/tab_ui/javatests/src/org/chromium/chrome/browser/tasks/tab_management/TabSwitcherTabletTest.java +++ b/chrome/android/features/tab_ui/javatests/src/org/chromium/chrome/browser/tasks/tab_management/TabSwitcherTabletTest.java
@@ -19,12 +19,9 @@ import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; -import static org.chromium.components.embedder_support.util.UrlConstants.NTP_NON_NATIVE_URL; - import android.graphics.Bitmap; import android.support.test.InstrumentationRegistry; -import androidx.annotation.Nullable; import androidx.test.filters.MediumTest; import org.junit.After; @@ -37,11 +34,9 @@ import org.chromium.base.Callback; import org.chromium.base.GarbageCollectionTestUtils; -import org.chromium.base.test.util.Batch; import org.chromium.base.test.util.CallbackHelper; import org.chromium.base.test.util.CommandLineFlags; import org.chromium.base.test.util.CriteriaHelper; -import org.chromium.base.test.util.DisabledTest; import org.chromium.base.test.util.Restriction; import org.chromium.chrome.browser.compositor.layouts.Layout; import org.chromium.chrome.browser.compositor.layouts.LayoutManagerImpl; @@ -63,6 +58,7 @@ import org.chromium.chrome.test.util.TabStripUtils; import org.chromium.chrome.test.util.browser.Features.DisableFeatures; import org.chromium.chrome.test.util.browser.Features.EnableFeatures; +import org.chromium.components.browser_ui.widget.scrim.ScrimCoordinator; import org.chromium.content_public.browser.test.util.TestThreadUtils; import org.chromium.ui.test.util.DisableAnimationsTestRule; import org.chromium.ui.test.util.UiRestriction; @@ -78,14 +74,13 @@ * Tests for the {@link TabSwitcher} on tablet */ @RunWith(ChromeJUnit4ClassRunner.class) -@CommandLineFlags.Add({ChromeSwitches.DISABLE_FIRST_RUN_EXPERIENCE}) -@EnableFeatures({ChromeFeatureList.GRID_TAB_SWITCHER_FOR_TABLETS}) +@CommandLineFlags. +Add({ChromeSwitches.DISABLE_FIRST_RUN_EXPERIENCE, "force-fieldtrials=Study/Group"}) +@EnableFeatures({ChromeFeatureList.GRID_TAB_SWITCHER_FOR_TABLETS + "<Study"}) @DisableFeatures(ChromeFeatureList.TAB_TO_GTS_ANIMATION) @Restriction( {Restriction.RESTRICTION_TYPE_NON_LOW_END_DEVICE, UiRestriction.RESTRICTION_TYPE_TABLET}) -@Batch(Batch.PER_CLASS) public class TabSwitcherTabletTest { - private static final long CALLBACK_WAIT_TIMEOUT = 15L; @ClassRule public static DisableAnimationsTestRule sEnableAnimationsRule = @@ -94,33 +89,28 @@ public ChromeTabbedActivityTestRule mActivityTestRule = new ChromeTabbedActivityTestRule(); private List<WeakReference<Bitmap>> mAllBitmaps = new LinkedList<>(); - private Callback<Bitmap> mBitmapListener = - (bitmap) -> mAllBitmaps.add(new WeakReference<>(bitmap)); private TabSwitcher.TabListDelegate mTabListDelegate; - private CallbackHelper mLayoutChangedCallbackHelper; - private LayoutStateObserver mLayoutObserver; + private CallbackHelper mLayoutChangedCallbackHelper = new CallbackHelper(); private int mCurrentlyActiveLayout; private Callback<LayoutManagerImpl> mLayoutManagerCallback; @Before public void setUp() throws ExecutionException { - // After setUp, Chrome is launched and has one NTP. - mActivityTestRule.startMainActivityFromLauncher(); + mActivityTestRule.startMainActivityOnBlankPage(); + CriteriaHelper.pollUiThread(mActivityTestRule.getActivity() + .getTabModelSelectorSupplier() + .get()::isTabStateInitialized); Layout layout = mActivityTestRule.getActivity().getLayoutManager().getOverviewLayout(); assertTrue(layout instanceof StartSurfaceLayout); StartSurfaceLayout mStartSurfaceLayout = (StartSurfaceLayout) layout; mTabListDelegate = mStartSurfaceLayout.getStartSurfaceForTesting().getGridTabListDelegate(); + Callback<Bitmap> mBitmapListener = (bitmap) -> mAllBitmaps.add(new WeakReference<>(bitmap)); mTabListDelegate.setBitmapCallbackForTesting(mBitmapListener); - CriteriaHelper.pollUiThread(mActivityTestRule.getActivity() - .getTabModelSelectorSupplier() - .get()::isTabStateInitialized); - - mLayoutChangedCallbackHelper = new CallbackHelper(); - mLayoutObserver = new LayoutStateProvider.LayoutStateObserver() { + LayoutStateObserver mLayoutObserver = new LayoutStateProvider.LayoutStateObserver() { @Override public void onFinishedHiding(int layoutType) { mCurrentlyActiveLayout = layoutType; @@ -132,6 +122,8 @@ () -> mActivityTestRule.getActivity().getLayoutManagerSupplier().addObserver( mLayoutManagerCallback)); + + prepareTabs(1, 1); } @After @@ -145,7 +137,6 @@ @Test @MediumTest - @DisabledTest public void testEnterAndExitTabSwitcherVerifyThumbnails() throws ExecutionException, TimeoutException { enterGTSWithThumbnailChecking(); @@ -155,7 +146,6 @@ @Test @MediumTest public void testToggleIncognitoSwitcher() throws InterruptedException, ExecutionException { - prepareTabs(1, 1, NTP_NON_NATIVE_URL); TabUiTestHelper.enterTabSwitcher(mActivityTestRule.getActivity()); // Start with incognito switcher. @@ -170,10 +160,8 @@ @Test @MediumTest - @DisabledTest public void testTabSwitcherToolbar() throws InterruptedException, ExecutionException, TimeoutException { - prepareTabs(1, 0, NTP_NON_NATIVE_URL); TabUiTestHelper.enterTabSwitcher(mActivityTestRule.getActivity()); // Assert hidden views. @@ -184,6 +172,12 @@ .check(matches(withEffectiveVisibility(GONE))); onView(allOf(withId(R.id.new_tab_button), withParent(withId(R.id.tab_switcher_toolbar)))) .check(matches(withEffectiveVisibility(GONE))); + onView(allOf(withId(R.id.incognito_tabs_stub), + withParent(withId(R.id.tab_switcher_toolbar)))) + .check(matches(withEffectiveVisibility(GONE))); + onView(allOf(withId(R.id.tab_switcher_mode_tab_switcher_button), + withParent(withId(R.id.tab_switcher_switches_and_menu)))) + .check(matches(withEffectiveVisibility(GONE))); // Assert visible views. onView(allOf(withId(R.id.new_tab_view), withParent(withId(R.id.tab_switcher_toolbar)))) @@ -191,9 +185,6 @@ onView(allOf(withId(R.id.menu_button_wrapper), withParent(withId(R.id.tab_switcher_switches_and_menu)))) .check(matches(isDisplayed())); - onView(allOf(withId(R.id.tab_switcher_mode_tab_switcher_button), - withParent(withId(R.id.tab_switcher_switches_and_menu)))) - .check(matches(isDisplayed())); // Exit switcher. exitSwitcherWithTabClick(0); @@ -206,6 +197,62 @@ .check(matches(isDisplayed())); } + @Test + @MediumTest + @CommandLineFlags.Add({"force-fieldtrial-params=Study.Group:enable_launch_polish/true"}) + public void testTabSwitcherToolbar_withPolishFlag_incognitoTabsOpen() + throws InterruptedException, ExecutionException, TimeoutException { + TabUiTestHelper.enterTabSwitcher(mActivityTestRule.getActivity()); + + // Assert hidden views. + onView(allOf(withId(R.id.incognito_switch), + withParent(withId(R.id.tab_switcher_switches_and_menu)))) + .check(matches(withEffectiveVisibility(GONE))); + onView(allOf(withId(R.id.new_tab_button), withParent(withId(R.id.tab_switcher_toolbar)))) + .check(matches(withEffectiveVisibility(GONE))); + onView(allOf(withId(R.id.tab_switcher_mode_tab_switcher_button), + withParent(withId(R.id.tab_switcher_switches_and_menu)))) + .check(matches(withEffectiveVisibility(GONE))); + + // Assert visible views. + onView(allOf(withId(R.id.new_tab_view), withParent(withId(R.id.tab_switcher_toolbar)))) + .check(matches(isDisplayed())); + onView(allOf(withId(R.id.menu_button_wrapper), + withParent(withId(R.id.tab_switcher_switches_and_menu)))) + .check(matches(isDisplayed())); + onView(allOf(withId(R.id.incognito_toggle_tabs), + withParent(withId(R.id.tab_switcher_toolbar)))) + .check(matches(isDisplayed())); + // Tablet toolbar is not hidden for polish + onView(allOf(withId(R.id.toolbar), withClassName(is(ToolbarTablet.class.getName())))) + .check(matches(isDisplayed())); + + // Exit switcher. + exitSwitcherPolishWithTabClick(0); + + // Assert tablet toolbar shows and switcher toolbar is gone. + onView(allOf(withId(R.id.tab_switcher_toolbar), + withClassName(is(TabSwitcherModeTopToolbar.class.getName())))) + .check(matches(withEffectiveVisibility(GONE))); + onView(allOf(withId(R.id.toolbar), withClassName(is(ToolbarTablet.class.getName())))) + .check(matches(isDisplayed())); + } + + @Test + @MediumTest + @CommandLineFlags.Add({"force-fieldtrial-params=Study.Group:enable_launch_polish/true"}) + public void testTabSwitcherV1Scrim() throws TimeoutException { + TabUiTestHelper.enterTabSwitcher(mActivityTestRule.getActivity()); + + ScrimCoordinator scrimCoordinator = mActivityTestRule.getActivity() + .getRootUiCoordinatorForTesting() + .getScrimCoordinator(); + assertTrue(scrimCoordinator.isShowingScrim()); + + exitSwitcherPolishWithTabClick(0); + assertFalse(scrimCoordinator.isShowingScrim()); + } + protected void clickIncognitoToggleButton() { final CallbackHelper tabModelSelectedCallback = new CallbackHelper(); TabModelSelectorObserver observer = new TabModelSelectorObserver() { @@ -233,7 +280,7 @@ }); } - private void prepareTabs(int numTabs, int numIncognitoTabs, @Nullable String url) { + private void prepareTabs(int numTabs, int numIncognitoTabs) { int oldCount = mTabListDelegate.getBitmapFetchCountForTesting(); TabUiTestHelper.prepareTabsWithThumbnail( mActivityTestRule, numTabs, numIncognitoTabs, null); @@ -252,7 +299,14 @@ private void exitSwitcherWithTabClick(int index) throws TimeoutException { TabUiTestHelper.clickNthCardFromTabSwitcher(mActivityTestRule.getActivity(), index); - mLayoutChangedCallbackHelper.waitForFirst(CALLBACK_WAIT_TIMEOUT, TimeUnit.SECONDS); + mLayoutChangedCallbackHelper.waitForCallback(1, 1, CALLBACK_WAIT_TIMEOUT, TimeUnit.SECONDS); + assertTrue(mCurrentlyActiveLayout == LayoutType.TAB_SWITCHER); + } + + private void exitSwitcherPolishWithTabClick(int index) throws TimeoutException { + TabUiTestHelper.clickNthCardFromTabletTabSwitcherPolish( + mActivityTestRule.getActivity(), index); + mLayoutChangedCallbackHelper.waitForCallback(1, 1, CALLBACK_WAIT_TIMEOUT, TimeUnit.SECONDS); assertTrue(mCurrentlyActiveLayout == LayoutType.TAB_SWITCHER); }
diff --git a/chrome/android/features/tab_ui/javatests/src/org/chromium/chrome/browser/tasks/tab_management/TabUiTestHelper.java b/chrome/android/features/tab_ui/javatests/src/org/chromium/chrome/browser/tasks/tab_management/TabUiTestHelper.java index 3e2c0b5..6d8024e0 100644 --- a/chrome/android/features/tab_ui/javatests/src/org/chromium/chrome/browser/tasks/tab_management/TabUiTestHelper.java +++ b/chrome/android/features/tab_ui/javatests/src/org/chromium/chrome/browser/tasks/tab_management/TabUiTestHelper.java
@@ -141,13 +141,29 @@ * @param index The index of the target card. */ public static void clickNthCardFromTabSwitcher(ChromeTabbedActivity cta, int index) { + clickTabSwitcherCardWithParent(cta, index, org.chromium.chrome.R.id.compositor_view_holder); + } + + private static void clickTabSwitcherCardWithParent( + ChromeTabbedActivity cta, int index, int parentId) { assertTrue(cta.getLayoutManager().overviewVisible()); - onView(allOf(withParent(withId(org.chromium.chrome.R.id.compositor_view_holder)), - withId(R.id.tab_list_view))) + onView(allOf(withParent(withId(parentId)), withId(R.id.tab_list_view))) .perform(RecyclerViewActions.actionOnItemAtPosition(index, click())); } /** + * Click the Nth card in grid tab switcher. When group is enabled and the Nth card is a + * group, this will open up the dialog; otherwise this will open up the tab page. + * @param cta The current running activity. + * @param index The index of the target card. + */ + public static void clickNthCardFromTabletTabSwitcherPolish( + ChromeTabbedActivity cta, int index) { + clickTabSwitcherCardWithParent( + cta, index, org.chromium.chrome.R.id.grid_tab_switcher_view_holder); + } + + /** * Click the first tab in tab grid dialog to open a tab page. * @param cta The current running activity. */
diff --git a/chrome/android/java/res_app/layout/main.xml b/chrome/android/java/res_app/layout/main.xml index 3c4a7871..ea90a464 100644 --- a/chrome/android/java/res_app/layout/main.xml +++ b/chrome/android/java/res_app/layout/main.xml
@@ -25,13 +25,6 @@ <include layout="@layout/compositor_view_holder"/> - <ViewStub - android:id="@+id/grid_tab_switcher_view_holder_stub" - android:layout_width="match_parent" - android:layout_height="match_parent" - android:inflatedId="@+id/grid_tab_switcher_view_holder" - android:layout="@layout/grid_tab_switcher_view_holder" /> - <!-- Parent holder for the AR SurfaceView, used to render content when in AR mode (which has some separate requirements preventing us from using the default compositor surface view). This needs to be in @@ -129,6 +122,13 @@ android:layout_width="match_parent" android:layout_height="wrap_content" /> + <ViewStub + android:id="@+id/grid_tab_switcher_view_holder_stub" + android:layout_width="match_parent" + android:layout_height="match_parent" + android:inflatedId="@+id/grid_tab_switcher_view_holder" + android:layout="@layout/grid_tab_switcher_view_holder" /> + <ViewStub android:id="@+id/continuous_search_container_stub" android:layout_width="match_parent"
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 7b7ca65..97c23e4 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/ChromeTabbedActivity.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/ChromeTabbedActivity.java
@@ -715,10 +715,12 @@ } // clang-format off + ViewGroup tabSwitcherViewHolder = findViewById(R.id.grid_tab_switcher_view_holder); mLayoutManager = new LayoutManagerChromeTablet(compositorViewHolder, mContentContainer, mStartSurfaceSupplier.get(), getTabContentManagerSupplier(), mOverviewModeBehaviorSupplier, - mRootUiCoordinator::getTopUiThemeColorProvider, mJankTracker); + mRootUiCoordinator::getTopUiThemeColorProvider, mJankTracker, tabSwitcherViewHolder, + mRootUiCoordinator.getScrimCoordinator()); mLayoutStateProviderOneshotSupplier.set(mLayoutManager); // clang-format on mOverviewModeController = mLayoutManager;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/compositor/layouts/LayoutManagerChrome.java b/chrome/android/java/src/org/chromium/chrome/browser/compositor/layouts/LayoutManagerChrome.java index 6de511b..556785e 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/compositor/layouts/LayoutManagerChrome.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/compositor/layouts/LayoutManagerChrome.java
@@ -41,6 +41,7 @@ import org.chromium.chrome.features.start_surface.StartSurface; import org.chromium.components.browser_ui.widget.gesture.SwipeGestureListener.ScrollDirection; import org.chromium.components.browser_ui.widget.gesture.SwipeGestureListener.SwipeHandler; +import org.chromium.components.browser_ui.widget.scrim.ScrimCoordinator; import org.chromium.components.embedder_support.util.UrlUtilities; import org.chromium.ui.resources.dynamics.DynamicResourceLoader; @@ -81,12 +82,16 @@ * @param tabContentManagerSupplier Supplier of the {@link TabContentManager} instance. * @param overviewModeBehaviorSupplier Supplier of the {@link OverviewModeBehavior}. * @param topUiThemeColorProvider {@link ThemeColorProvider} for top UI. + * @param startSurfaceScrimAnchor {@link ViewGroup} used by start surface layout to show scrim + * when overview is visible. + * @param scrimCoordinator {@link ScrimCoordinator} to show/hide scrim. */ public LayoutManagerChrome(LayoutManagerHost host, ViewGroup contentContainer, boolean createOverviewLayout, @Nullable StartSurface startSurface, ObservableSupplier<TabContentManager> tabContentManagerSupplier, OneshotSupplierImpl<OverviewModeBehavior> overviewModeBehaviorSupplier, - Supplier<TopUiThemeColorProvider> topUiThemeColorProvider, JankTracker jankTracker) { + Supplier<TopUiThemeColorProvider> topUiThemeColorProvider, JankTracker jankTracker, + ViewGroup startSurfaceScrimAnchor, ScrimCoordinator scrimCoordinator) { super(host, contentContainer, tabContentManagerSupplier, topUiThemeColorProvider); Context context = host.getContext(); LayoutRenderHost renderHost = host.getLayoutRenderHost(); @@ -115,8 +120,9 @@ TabManagementModuleProvider.getDelegate(); assert tabManagementDelegate != null; - mOverviewLayout = tabManagementDelegate.createStartSurfaceLayout( - context, this, renderHost, startSurface, jankTracker); + mOverviewLayout = tabManagementDelegate.createStartSurfaceLayout(context, this, + renderHost, startSurface, jankTracker, startSurfaceScrimAnchor, + scrimCoordinator); } }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/compositor/layouts/LayoutManagerChromePhone.java b/chrome/android/java/src/org/chromium/chrome/browser/compositor/layouts/LayoutManagerChromePhone.java index 5058be1..64d5f72 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/compositor/layouts/LayoutManagerChromePhone.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/compositor/layouts/LayoutManagerChromePhone.java
@@ -49,7 +49,7 @@ OneshotSupplierImpl<OverviewModeBehavior> overviewModeBehaviorSupplier, Supplier<TopUiThemeColorProvider> topUiThemeColorProvider, JankTracker jankTracker) { super(host, contentContainer, true, startSurface, tabContentManagerSupplier, - overviewModeBehaviorSupplier, topUiThemeColorProvider, jankTracker); + overviewModeBehaviorSupplier, topUiThemeColorProvider, jankTracker, null, null); } @Override
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/compositor/layouts/LayoutManagerChromeTablet.java b/chrome/android/java/src/org/chromium/chrome/browser/compositor/layouts/LayoutManagerChromeTablet.java index f868eb32..c0dc9351 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/compositor/layouts/LayoutManagerChromeTablet.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/compositor/layouts/LayoutManagerChromeTablet.java
@@ -21,6 +21,7 @@ import org.chromium.chrome.browser.theme.TopUiThemeColorProvider; import org.chromium.chrome.browser.toolbar.ControlContainer; import org.chromium.chrome.features.start_surface.StartSurface; +import org.chromium.components.browser_ui.widget.scrim.ScrimCoordinator; import org.chromium.ui.resources.dynamics.DynamicResourceLoader; /** @@ -42,16 +43,20 @@ * @param tabContentManagerSupplier Supplier of the {@link TabContentManager} instance. * @param overviewModeBehaviorSupplier Supplier of the {@link OverviewModeBehavior}. * @param topUiThemeColorProvider {@link ThemeColorProvider} for top UI. + * @param startSurfaceScrimAnchor {@link ViewGroup} used by start surface layout to show scrim + * when overview is visible. + * @param scrimCoordinator {@link ScrimCoordinator} to show/hide scrim. */ public LayoutManagerChromeTablet(LayoutManagerHost host, ViewGroup contentContainer, StartSurface startSurface, ObservableSupplier<TabContentManager> tabContentManagerSupplier, OneshotSupplierImpl<OverviewModeBehavior> overviewModeBehaviorSupplier, - Supplier<TopUiThemeColorProvider> topUiThemeColorProvider, JankTracker jankTracker) { + Supplier<TopUiThemeColorProvider> topUiThemeColorProvider, JankTracker jankTracker, + ViewGroup startSurfaceScrimAnchor, ScrimCoordinator scrimCoordinator) { super(host, contentContainer, TabUiFeatureUtilities.isGridTabSwitcherEnabled(host.getContext()), startSurface, tabContentManagerSupplier, overviewModeBehaviorSupplier, topUiThemeColorProvider, - jankTracker); + jankTracker, startSurfaceScrimAnchor, scrimCoordinator); mTabStripLayoutHelperManager = new StripLayoutHelperManager( host.getContext(), this, mHost.getLayoutRenderHost(), () -> mLayerTitleCache);
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/compositor/overlays/strip/StripLayoutHelperManager.java b/chrome/android/java/src/org/chromium/chrome/browser/compositor/overlays/strip/StripLayoutHelperManager.java index 05c7ebe..6ade280d 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/compositor/overlays/strip/StripLayoutHelperManager.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/compositor/overlays/strip/StripLayoutHelperManager.java
@@ -386,8 +386,8 @@ @Override public void getVirtualViews(List<VirtualView> views) { - if (mModelSelectorButton.isVisible()) views.add(mModelSelectorButton); if (!getStripScrim().isVisible()) getActiveStripLayoutHelper().getVirtualViews(views); + if (mModelSelectorButton.isVisible()) views.add(mModelSelectorButton); } @Override
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/init/ChromeBrowserInitializer.java b/chrome/android/java/src/org/chromium/chrome/browser/init/ChromeBrowserInitializer.java index 591bd90..06dda766 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/init/ChromeBrowserInitializer.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/init/ChromeBrowserInitializer.java
@@ -27,6 +27,7 @@ import org.chromium.base.task.ChainedTasks; import org.chromium.base.task.PostTask; import org.chromium.base.task.TaskTraits; +import org.chromium.build.NativeLibraries; import org.chromium.chrome.browser.AppHooks; import org.chromium.chrome.browser.ChromeStrictMode; import org.chromium.chrome.browser.FileProviderHelper; @@ -159,6 +160,10 @@ } if (parts.isActivityFinishingOrDestroyed()) return; preInflationStartupDone(); + if (Process.is64Bit()) { + // This should be called before calling into LibraryLoader. + ensureLibraryCanBeLoadedIn64Bit(); + } parts.setContentViewAndLoadLibrary(() -> this.onInflationComplete(parts)); } @@ -317,6 +322,21 @@ } } + private void ensureLibraryCanBeLoadedIn64Bit() { + // Fail here before loading libmonochrome.so on 64-bit platforms, otherwise the failing + // native stacktrace will not make it obvious that this is a bitness issue. See this bug + // for context: https://crbug.com/1303857 While non-component builds has only one library, + // monochrome may not be the first in the list for component builds. + for (String libraryName : NativeLibraries.LIBRARIES) { + if (libraryName.equals("monochrome") || libraryName.equals("monochrome.cr")) { + throw new RuntimeException( + "Starting in 64-bit mode requires the 64-bit native library. If the " + + "device is 64-bit only, see alternatives here: " + + "https://crbug.com/1303857#c7."); + } + } + } + private void startChromeBrowserProcessesAsync(boolean startGpuProcess, boolean startMinimalBrowser, BrowserStartupController.StartupCallback callback) { try {
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/share/ShareButtonController.java b/chrome/android/java/src/org/chromium/chrome/browser/share/ShareButtonController.java index 888c8b8..4b190b6 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/share/ShareButtonController.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/share/ShareButtonController.java
@@ -32,6 +32,7 @@ import org.chromium.components.feature_engagement.EventConstants; import org.chromium.components.feature_engagement.FeatureConstants; import org.chromium.components.feature_engagement.Tracker; +import org.chromium.components.ukm.UkmRecorder; import org.chromium.ui.modaldialog.ModalDialogManager; import org.chromium.ui.modaldialog.ModalDialogManager.ModalDialogManagerObserver; import org.chromium.ui.modelutil.PropertyModel; @@ -112,6 +113,10 @@ if (tab == null) return; if (onShareRunnable != null) onShareRunnable.run(); RecordUserAction.record("MobileTopToolbarShareButton"); + if (tab.getWebContents() != null) { + new UkmRecorder.Bridge().recordEventWithBooleanMetric( + tab.getWebContents(), "TopToolbar.Share", "HasOccurred"); + } shareDelegate.share(tab, /*shareDirectly=*/false, ShareOrigin.TOP_TOOLBAR); if (mTrackerSupplier.hasValue()) {
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/site_settings/WebsitePermissionsFetcherTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/site_settings/WebsitePermissionsFetcherTest.java index 9edd5093..3abc16eb 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/site_settings/WebsitePermissionsFetcherTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/site_settings/WebsitePermissionsFetcherTest.java
@@ -493,7 +493,7 @@ // If the ContentSettingsType.NUM_TYPES value changes *and* a new value has been exposed on // Android, then please update this code block to include a test for your new type. // Otherwise, just update count in the assert. - Assert.assertEquals(75, ContentSettingsType.NUM_TYPES); + Assert.assertEquals(76, ContentSettingsType.NUM_TYPES); websitePreferenceBridge.addContentSettingException( new ContentSettingException(ContentSettingsType.COOKIES, googleOrigin, ContentSettingValues.DEFAULT, preferenceSource));
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/tab/state/ShoppingPersistedTabDataTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/tab/state/ShoppingPersistedTabDataTest.java index 9d606ed..e324bd7 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/tab/state/ShoppingPersistedTabDataTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/tab/state/ShoppingPersistedTabDataTest.java
@@ -1128,6 +1128,36 @@ helper.waitForCallback(count); } + @SmallTest + @Test + public void testDestroyedTab() throws TimeoutException { + TabImpl tab = mock(TabImpl.class); + doReturn(true).when(tab).isDestroyed(); + CallbackHelper helper = new CallbackHelper(); + int count = helper.getCallCount(); + TestThreadUtils.runOnUiThreadBlocking(() -> { + ShoppingPersistedTabData.from(tab, (res) -> { + Assert.assertNull(res); + helper.notifyCalled(); + }); + }); + helper.waitForCallback(count); + } + + @SmallTest + @Test + public void testNullTab() throws TimeoutException { + CallbackHelper helper = new CallbackHelper(); + int count = helper.getCallCount(); + TestThreadUtils.runOnUiThreadBlocking(() -> { + ShoppingPersistedTabData.from(null, (res) -> { + Assert.assertNull(res); + helper.notifyCalled(); + }); + }); + helper.waitForCallback(count); + } + static class DeserializeAndLogCheckerShoppingPersistedTabData extends ShoppingPersistedTabData { DeserializeAndLogCheckerShoppingPersistedTabData(Tab tab) { super(tab);
diff --git a/chrome/android/junit/DEPS b/chrome/android/junit/DEPS index dd3ed77..fd8febd 100644 --- a/chrome/android/junit/DEPS +++ b/chrome/android/junit/DEPS
@@ -35,6 +35,7 @@ "+components/security_state/content/android/java/src/org/chromium/components/security_state/SecurityStateModel.java", "+components/sync/android/java/src/org/chromium/components/sync", "+components/sync/test/android/javatests/src/org/chromium/components/sync/test/util", + "+components/ukm/android", "-content/public/android/java", "+content/public/android/java/src/org/chromium/content_public",
diff --git a/chrome/android/junit/src/org/chromium/chrome/browser/share/ShareButtonControllerUnitTest.java b/chrome/android/junit/src/org/chromium/chrome/browser/share/ShareButtonControllerUnitTest.java index 686f814..b6846be 100644 --- a/chrome/android/junit/src/org/chromium/chrome/browser/share/ShareButtonControllerUnitTest.java +++ b/chrome/android/junit/src/org/chromium/chrome/browser/share/ShareButtonControllerUnitTest.java
@@ -30,6 +30,7 @@ import org.robolectric.annotation.Config; import org.chromium.base.supplier.ObservableSupplier; +import org.chromium.base.test.util.JniMocker; import org.chromium.chrome.browser.ActivityTabProvider; import org.chromium.chrome.browser.feature_engagement.TrackerFactory; import org.chromium.chrome.browser.flags.ChromeFeatureList; @@ -43,6 +44,8 @@ import org.chromium.components.feature_engagement.EventConstants; import org.chromium.components.feature_engagement.FeatureConstants; import org.chromium.components.feature_engagement.Tracker; +import org.chromium.components.ukm.UkmRecorder; +import org.chromium.components.ukm.UkmRecorderJni; import org.chromium.content_public.browser.WebContents; import org.chromium.testing.local.LocalRobolectricTestRunner; import org.chromium.ui.modaldialog.ModalDialogManager; @@ -56,6 +59,11 @@ @Rule public TestRule mProcessor = new Features.JUnitProcessor(); + @Rule + public JniMocker mJniMocker = new JniMocker(); + @Mock + private UkmRecorder.Natives mUkmRecorderJniMock; + @Mock private Context mContext; @Mock @@ -85,6 +93,7 @@ @Before public void setUp() { MockitoAnnotations.initMocks(this); + mJniMocker.mock(UkmRecorderJni.TEST_HOOKS, mUkmRecorderJniMock); doReturn(mTab).when(mTabProvider).get(); doReturn(mContext).when(mTab).getContext();
diff --git a/chrome/app/chrome_exe_main_mac.c b/chrome/app/chrome_exe_main_mac.c index 220b6e26..9a1a1a4 100644 --- a/chrome/app/chrome_exe_main_mac.c +++ b/chrome/app/chrome_exe_main_mac.c
@@ -57,58 +57,59 @@ // padding to the x86_64 slice that precedes it. The arm64 slice needs to remain // at offset 304kB (since 98.0.4758.80). The signed x86_64 slice has size 287296 // bytes in 98.0.4758.80, but has shrunk since then, and before the introduction -// of any padding, would now be 216784 bytes long. To make up the 70512-byte -// difference, 68kB (69632 bytes) of padding is added to the x86_64 slice to +// of any padding, would now be 37724 bytes long. To make up the 249572-byte +// difference, 240kB (245760 bytes) of padding is added to the x86_64 slice to // ensure that its size is stable, causing the arm64 slice to land where it // needs to be when universalized. This padding needs to be added to the thin -// form of the x86_64 image before being fed to universalizer.py. Why 69632 -// bytes and not 70512? To keep it an even multiple of linker pages (not machine -// pages: linker pages are 4kB for lld targeting x86_64 and 16kB for ld64 -// targeting x86_64, but Chrome uses lld). In any case, I'll make up almost all -// of the 880-byte difference with one more weird trick below. +// form of the x86_64 image before being fed to universalizer.py. Why 245760 +// bytes and not 249572? To keep it an even multiple of linker pages (not +// machine pages: linker pages are 4kB for lld targeting x86_64 and 16kB for +// ld64 targeting x86_64, but Chrome uses lld). In any case, I'll make up almost +// all of the 3812-byte difference with one more weird trick below. // // There are several terrible ways to insert this padding into the x86_64 image. // Best would be something that considers the size of the x86_64 image without // padding, and inserts the precise amount required. It may be possible to do // this after linking, but the options that have been attempted so far were not -// successful. So this quick and very dirty 68kB buffer is added to increase the -// size of __TEXT,__const in a way that no tool could possibly see as suspicious -// after link time. The variable is marked with the "used" attribute to prevent -// the compiler from issuing warnings about the referenced variable, to prevent -// the compiler from removing it under optimization, and to set the +// successful. So this quick and very dirty 240kB buffer is added to increase +// the size of __TEXT,__const in a way that no tool could possibly see as +// suspicious after link time. The variable is marked with the "used" attribute +// to prevent the compiler from issuing warnings about the referenced variable, +// to prevent the compiler from removing it under optimization, and to set the // S_ATTR_NO_DEAD_STRIP section attribute to prevent the linker from removing it // under -dead_strip. Note that the standardized [[maybe_unused]] attribute only // suppresses the warning, but does not prevent the compiler or linker from // removing it. // -// The introduction of this fixed 68kB of padding causes the unsigned linker -// output to grow by 68kB precisely, but the signed output will grow by slightly -// more. This is because the code signature's code directory contains SHA-1 and -// SHA-256 hashes of each 4kB code signing page (note, not machine pages or -// linker pages) in the image, adding 20 and 32 bytes each (macOS 12.0.1 +// The introduction of this fixed 240kB of padding causes the unsigned linker +// output to grow by 240kB precisely, but the signed output will grow by +// slightly more. This is because the code signature's code directory contains +// SHA-1 and SHA-256 hashes of each 4kB code signing page (note, not machine +// pages or linker pages) in the image, adding 20 and 32 bytes each (macOS +// 12.0.1 // https://github.com/apple-oss-distributions/Security/blob/main/OSX/libsecurity_codesigning/lib/signer.cpp#L298 -// Security::CodeSigning::SecCodeSigner::Signer::prepare). For the 68kB -// addition, the code signature grows by (68 / 4) * (20 + 32) = 884 bytes, thus -// the total size of the linker output grows by 68kB + 884 = 70516 bytes. It is -// not possible to control this any more granularly: if the buffer were sized at -// 68kB - 884 = 68748 bytes, it would either cause no change in the space -// allocated to the __TEXT segment (due to padding for alignment) or would cause -// the segment to shrink by a linker page (note, not a code signing or machine -// page) which would which would cause the linker output to shrink by the same -// amount and would be absolutely undesirable. Luckily, the net growth of 70516 -// bytes is almost at the target of 70512 on the nose. In any event, having the -// signed x86_64 slice sized at 287300 bytes instead of 287296 should not be a -// problem. Subtle differences in characteristics including the code signature -// itself can easily produce differences of that magnitude. It's necessary for -// the size to wind up in the range (278528, 294912], and as long as that's met, -// the 16kB alignment for the arm64 slice that follows it in the fat file will -// cause it to appear at the desired 304kB. +// Security::CodeSigning::SecCodeSigner::Signer::prepare). For the 240kB +// addition, the code signature grows by (240 / 4) * (20 + 32) = 3120 bytes, +// thus the total size of the linker output grows by 240kB + 3120 = 248880 +// bytes. It is not possible to control this any more granularly: if the buffer +// were sized at 240kB - 3120 = 242640 bytes, it would either cause no change in +// the space allocated to the __TEXT segment (due to padding for alignment) or +// would cause the segment to shrink by a linker page (note, not a code signing +// or machine page) which would which would cause the linker output to shrink by +// the same amount and would be absolutely undesirable. Luckily, the net growth +// of 248880 bytes is very close to the target growth of 249572 bytes. In any +// event, having the signed x86_64 slice sized at 286604 bytes instead of 287296 +// should not be a problem. Subtle differences in characteristics including the +// code signature itself can easily produce differences of that magnitude. It's +// necessary for the size to wind up in the range (278528, 294912], and as long +// as that's met, the 16kB alignment for the arm64 slice that follows it in the +// fat file will cause it to appear at the desired 304kB. // // If the main executable has a significant change in size, this will need to be // revised. Hopefully a more elegant solution will become apparent before that's // required. static __attribute__((used)) -const char kGrossPaddingForCrbug1300598[68 * 1024] = {}; +const char kGrossPaddingForCrbug1300598[240 * 1024] = {}; #endif __attribute__((visibility("default"))) int main(int argc, char* argv[]) {
diff --git a/chrome/app/chrome_main_delegate.cc b/chrome/app/chrome_main_delegate.cc index bf5f5a6..cc6167f7 100644 --- a/chrome/app/chrome_main_delegate.cc +++ b/chrome/app/chrome_main_delegate.cc
@@ -723,6 +723,8 @@ } else if (process_type == switches::kRendererProcess) { hang_watcher_process_type = base::HangWatcher::ProcessType::kRendererProcess; + } else if (process_type == switches::kUtilityProcess) { + hang_watcher_process_type = base::HangWatcher::ProcessType::kUtilityProcess; } else { hang_watcher_process_type = base::HangWatcher::ProcessType::kUnknownProcess; }
diff --git a/chrome/browser/BUILD.gn b/chrome/browser/BUILD.gn index 800044a..8a371b378 100644 --- a/chrome/browser/BUILD.gn +++ b/chrome/browser/BUILD.gn
@@ -377,6 +377,8 @@ "data_reduction_proxy/data_reduction_proxy_chrome_settings_factory.h", "data_reduction_proxy/data_reduction_proxy_tab_helper.cc", "data_reduction_proxy/data_reduction_proxy_tab_helper.h", + "data_use_measurement/chrome_data_use_measurement.cc", + "data_use_measurement/chrome_data_use_measurement.h", "defaults.cc", "defaults.h", "device_reauth/chrome_biometric_authenticator_factory.h", @@ -1825,6 +1827,10 @@ "webid/federated_identity_active_session_permission_context.h", "webid/federated_identity_active_session_permission_context_factory.cc", "webid/federated_identity_active_session_permission_context_factory.h", + "webid/federated_identity_api_permission_context.cc", + "webid/federated_identity_api_permission_context.h", + "webid/federated_identity_api_permission_context_factory.cc", + "webid/federated_identity_api_permission_context_factory.h", "webid/federated_identity_request_permission_context.cc", "webid/federated_identity_request_permission_context.h", "webid/federated_identity_request_permission_context_factory.cc",
diff --git a/chrome/browser/about_flags.cc b/chrome/browser/about_flags.cc index 6e7d97a..faebbb3 100644 --- a/chrome/browser/about_flags.cc +++ b/chrome/browser/about_flags.cc
@@ -7843,13 +7843,6 @@ kOsDesktop | kOsAndroid, FEATURE_VALUE_TYPE(omnibox::kUpdatedConnectionSecurityIndicators)}, -#if BUILDFLAG(IS_ANDROID) - {"swap-android-share-hub-rows", - flag_descriptions::kSwapAndroidShareHubRowsName, - flag_descriptions::kSwapAndroidShareHubRowsDescription, kOsAndroid, - FEATURE_VALUE_TYPE(share::kSwapAndroidShareHubRows)}, -#endif - {"enable-drdc", flag_descriptions::kEnableDrDcName, flag_descriptions::kEnableDrDcDescription, kOsAll, FEATURE_VALUE_TYPE(features::kEnableDrDc)},
diff --git a/chrome/browser/app_controller_mac_browsertest.mm b/chrome/browser/app_controller_mac_browsertest.mm index 30d4a3f..88fdabb 100644 --- a/chrome/browser/app_controller_mac_browsertest.mm +++ b/chrome/browser/app_controller_mac_browsertest.mm
@@ -17,7 +17,6 @@ #include "base/command_line.h" #include "base/mac/foundation_util.h" #include "base/mac/scoped_nsobject.h" -#include "base/path_service.h" #include "base/run_loop.h" #include "base/scoped_observation.h" #include "base/strings/sys_string_conversions.h" @@ -57,7 +56,6 @@ #include "chrome/browser/ui/webui/welcome/helpers.h" #include "chrome/common/chrome_constants.h" #include "chrome/common/chrome_features.h" -#include "chrome/common/chrome_paths.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/pref_names.h" #include "chrome/common/url_constants.h" @@ -71,13 +69,11 @@ #include "content/public/browser/web_contents.h" #include "content/public/test/browser_test.h" #include "content/public/test/browser_test_utils.h" -#include "content/public/test/prerender_test_util.h" #include "content/public/test/test_navigation_observer.h" #include "extensions/browser/app_window/app_window_registry.h" #include "extensions/browser/extension_dialog_auto_confirm.h" #include "extensions/common/extension.h" #include "extensions/test/extension_test_message_listener.h" -#include "net/dns/mock_host_resolver.h" #include "net/test/embedded_test_server/embedded_test_server.h" #include "third_party/blink/public/common/features.h" #import "ui/events/test/cocoa_test_event_utils.h" @@ -1211,61 +1207,4 @@ EXPECT_EQ(g_handoff_url, test_url2); } -class AppControllerHandoffPrerenderBrowserTest - : public AppControllerHandoffBrowserTest { - public: - void SetUpOnMainThread() override { - prerender_helper_.SetUp(embedded_test_server()); - host_resolver()->AddRule("*", "127.0.0.1"); - embedded_test_server()->ServeFilesFromDirectory( - base::PathService::CheckedGet(chrome::DIR_TEST_DATA)); - ASSERT_TRUE(embedded_test_server()->Start()); - } - - content::WebContents* GetActiveWebContents() { - return browser()->tab_strip_model()->GetActiveWebContents(); - } - - content::test::PrerenderTestHelper& prerender_helper() { - return prerender_helper_; - } - - protected: - AppControllerHandoffPrerenderBrowserTest() - : prerender_helper_(base::BindRepeating( - &AppControllerHandoffPrerenderBrowserTest::GetActiveWebContents, - // Unretained is safe here, as this class owns PrerenderTestHelper - // object, which holds the callback being constructed here, so the - // callback will be destructed before this class. - base::Unretained(this))) {} - - private: - content::test::PrerenderTestHelper prerender_helper_; -}; - -// Tests that as a user switches from main page to prerendered page, the correct -// URL is being passed to the Handoff. -IN_PROC_BROWSER_TEST_F(AppControllerHandoffPrerenderBrowserTest, - TestHandoffURLs) { - // Navigate to an initial page. - GURL url = embedded_test_server()->GetURL("/empty.html"); - ASSERT_TRUE(content::NavigateToURL(GetActiveWebContents(), url)); - - // Start a prerender. - GURL prerender_url = embedded_test_server()->GetURL("/simple.html"); - prerender_helper().AddPrerender(prerender_url); - EXPECT_EQ(g_handoff_url, url); - - // Activate. - content::TestNavigationManager navigation_manager(GetActiveWebContents(), - prerender_url); - ASSERT_TRUE( - content::ExecJs(GetActiveWebContents()->GetMainFrame(), - content::JsReplace("location = $1", prerender_url))); - navigation_manager.WaitForNavigationFinished(); - EXPECT_TRUE(navigation_manager.was_prerendered_page_activation()); - EXPECT_TRUE(navigation_manager.was_successful()); - EXPECT_EQ(g_handoff_url, prerender_url); -} - } // namespace
diff --git a/chrome/browser/ash/accessibility/accessibility_extension_api_browsertest.cc b/chrome/browser/ash/accessibility/accessibility_extension_api_browsertest.cc index 89ac5824..6d0e262 100644 --- a/chrome/browser/ash/accessibility/accessibility_extension_api_browsertest.cc +++ b/chrome/browser/ash/accessibility/accessibility_extension_api_browsertest.cc
@@ -30,10 +30,7 @@ : public extensions::ExtensionApiTest, public testing::WithParamInterface<ContextType> { public: - AccessibilityPrivateApiTest() : ExtensionApiTest(GetParam()) { - dictation_bubble_test_helper_ = - std::make_unique<DictationBubbleTestHelper>(); - } + AccessibilityPrivateApiTest() : ExtensionApiTest(GetParam()) {} ~AccessibilityPrivateApiTest() override = default; AccessibilityPrivateApiTest& operator=(const AccessibilityPrivateApiTest&) = delete; @@ -47,6 +44,12 @@ ::features::kExperimentalAccessibilityDictationCommands); } + void SetUpOnMainThread() override { + ExtensionApiTest::SetUpOnMainThread(); + dictation_bubble_test_helper_ = + std::make_unique<DictationBubbleTestHelper>(); + } + [[nodiscard]] bool RunSubtest(const char* subtest) { return RunExtensionTest("accessibility_private", {.custom_arg = subtest}); }
diff --git a/chrome/browser/ash/accessibility/dictation_browsertest.cc b/chrome/browser/ash/accessibility/dictation_browsertest.cc index 819e3a91..8743465 100644 --- a/chrome/browser/ash/accessibility/dictation_browsertest.cc +++ b/chrome/browser/ash/accessibility/dictation_browsertest.cc
@@ -1271,7 +1271,7 @@ // Tests the behavior of the Dictation bubble UI. class DictationUITest : public DictationExtensionTest { protected: - DictationUITest() : dictation_bubble_test_helper_() {} + DictationUITest() = default; ~DictationUITest() override = default; DictationUITest(const DictationUITest&) = delete; DictationUITest& operator=(const DictationUITest&) = delete; @@ -1285,6 +1285,12 @@ scoped_feature_list_.InitWithFeatures(enabled_features, disabled_features); } + void SetUpOnMainThread() override { + DictationExtensionTest::SetUpOnMainThread(); + dictation_bubble_test_helper_ = + std::make_unique<DictationBubbleTestHelper>(); + } + void WaitForProperties( bool visible, DictationBubbleIconType icon, @@ -1303,7 +1309,8 @@ std::string error_message = "Still waiting for UI visibility: "; error_message += visible ? "true" : "false"; SuccessWaiter(base::BindLambdaForTesting([&]() { - return dictation_bubble_test_helper_.IsVisible() == visible; + return dictation_bubble_test_helper_->IsVisible() == + visible; }), error_message) .Wait(); @@ -1312,7 +1319,7 @@ void WaitForVisibleIcon(DictationBubbleIconType icon) { std::string error_message = "Still waiting for UI icon: " + ToString(icon); SuccessWaiter(base::BindLambdaForTesting([&]() { - return dictation_bubble_test_helper_.GetVisibleIcon() == + return dictation_bubble_test_helper_->GetVisibleIcon() == icon; }), error_message) @@ -1323,7 +1330,7 @@ std::string error_message = "Still waiting for UI text: " + base::UTF16ToUTF8(text); SuccessWaiter(base::BindLambdaForTesting([&]() { - return dictation_bubble_test_helper_.GetText() == text; + return dictation_bubble_test_helper_->GetText() == text; }), error_message) .Wait(); @@ -1332,14 +1339,15 @@ void WaitForVisibleHints(const std::vector<std::u16string>& hints) { std::string error_message = base::UTF16ToUTF8( u"Still waiting for UI hints: " + base::JoinString(hints, u",")); - SuccessWaiter(base::BindLambdaForTesting([&]() { - return dictation_bubble_test_helper_.HasVisibleHints(hints); - }), - error_message) + SuccessWaiter( + base::BindLambdaForTesting([&]() { + return dictation_bubble_test_helper_->HasVisibleHints(hints); + }), + error_message) .Wait(); } - DictationBubbleTestHelper dictation_bubble_test_helper_; + std::unique_ptr<DictationBubbleTestHelper> dictation_bubble_test_helper_; base::test::ScopedFeatureList scoped_feature_list_; }; @@ -1348,11 +1356,10 @@ DictationUITest, ::testing::Values(speech::SpeechRecognitionType::kNetwork)); -// TODO(crbug.com/1303604): OnDevice tests are flaky. -// INSTANTIATE_TEST_SUITE_P( -// OnDevice, -// DictationUITest, -// ::testing::Values(speech::SpeechRecognitionType::kOnDevice)); +INSTANTIATE_TEST_SUITE_P( + OnDevice, + DictationUITest, + ::testing::Values(speech::SpeechRecognitionType::kOnDevice)); IN_PROC_BROWSER_TEST_P(DictationUITest, ShownWhenSpeechRecognitionStarts) { ToggleDictationWithKeystroke();
diff --git a/chrome/browser/ash/accessibility/dictation_bubble_test_helper.cc b/chrome/browser/ash/accessibility/dictation_bubble_test_helper.cc index f26185b1..4b9f3c7 100644 --- a/chrome/browser/ash/accessibility/dictation_bubble_test_helper.cc +++ b/chrome/browser/ash/accessibility/dictation_bubble_test_helper.cc
@@ -12,6 +12,11 @@ namespace ash { +DictationBubbleTestHelper::DictationBubbleTestHelper() { + // Ensure the bubble UI is initialized. + GetController()->MaybeInitialize(); +} + bool DictationBubbleTestHelper::IsVisible() { return GetController()->widget_->IsVisible(); }
diff --git a/chrome/browser/ash/accessibility/dictation_bubble_test_helper.h b/chrome/browser/ash/accessibility/dictation_bubble_test_helper.h index adadaa8..1874e00b 100644 --- a/chrome/browser/ash/accessibility/dictation_bubble_test_helper.h +++ b/chrome/browser/ash/accessibility/dictation_bubble_test_helper.h
@@ -15,7 +15,7 @@ class DictationBubbleTestHelper { public: - DictationBubbleTestHelper() = default; + DictationBubbleTestHelper(); ~DictationBubbleTestHelper() = default; DictationBubbleTestHelper(const DictationBubbleTestHelper&) = delete; DictationBubbleTestHelper& operator=(const DictationBubbleTestHelper&) =
diff --git a/chrome/browser/ash/web_applications/projector_app/untrusted_projector_ui_config.cc b/chrome/browser/ash/web_applications/projector_app/untrusted_projector_ui_config.cc index 67d3cc2f..b684c3ea 100644 --- a/chrome/browser/ash/web_applications/projector_app/untrusted_projector_ui_config.cc +++ b/chrome/browser/ash/web_applications/projector_app/untrusted_projector_ui_config.cc
@@ -23,6 +23,8 @@ source->AddBoolean("isDebugMode", ash::features::IsProjectorAppDebugMode()); source->AddBoolean("isExcludeTranscriptEnabled", ash::features::IsProjectorExcludeTranscriptEnabled()); + source->AddBoolean("isTutorialVideoViewEnabled", + ash::features::IsProjectorTutorialVideoViewEnabled()); } UntrustedProjectorUIConfig::UntrustedProjectorUIConfig()
diff --git a/chrome/browser/chrome_content_browser_client.cc b/chrome/browser/chrome_content_browser_client.cc index 2d1711a..6dbf816e 100644 --- a/chrome/browser/chrome_content_browser_client.cc +++ b/chrome/browser/chrome_content_browser_client.cc
@@ -41,6 +41,7 @@ #include "chrome/browser/content_settings/cookie_settings_factory.h" #include "chrome/browser/content_settings/host_content_settings_map_factory.h" #include "chrome/browser/custom_handlers/protocol_handler_registry_factory.h" +#include "chrome/browser/data_use_measurement/chrome_data_use_measurement.h" #include "chrome/browser/defaults.h" #include "chrome/browser/device_api/device_service_impl.h" #include "chrome/browser/device_api/managed_configuration_service.h" @@ -5807,6 +5808,9 @@ task_manager::TaskManagerInterface::UpdateAccumulatedStatsNetworkForRoute( render_frame_host_id, recv_bytes, sent_bytes); #endif + + ChromeDataUseMeasurement::GetInstance().ReportNetworkServiceDataUse( + network_traffic_annotation_id_hash, recv_bytes, sent_bytes); } base::FilePath
diff --git a/chrome/browser/client_hints/client_hints_browsertest.cc b/chrome/browser/client_hints/client_hints_browsertest.cc index fec123b..1b3eede 100644 --- a/chrome/browser/client_hints/client_hints_browsertest.cc +++ b/chrome/browser/client_hints/client_hints_browsertest.cc
@@ -1530,13 +1530,20 @@ .GetLastCommittedEntry() ->SetIsOverridingUserAgent(true); + // Since no value was provided for client hints, they are sent with blank or + // false values. ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), kUrl)); EXPECT_TRUE(ExecuteScriptAndExtractString( web_contents, "window.domAutomationController.send(document.body.textContent);", &header_value)); - // Since no value was provided for client hints, they are not sent. - EXPECT_EQ("foo\nNone\nNone", header_value); + EXPECT_EQ("foo\n\n?0", header_value); + EXPECT_TRUE( + ExecuteScriptAndExtractString(web_contents, + "window.domAutomationController.send(JSON." + "stringify(navigator.userAgentData));", + &header_value)); + EXPECT_EQ(R"({"brands":[],"mobile":false})", header_value); // Now actually provide values for the hints. blink::UserAgentOverride ua_override; @@ -1552,6 +1559,14 @@ "window.domAutomationController.send(document.body.textContent);", &header_value)); EXPECT_EQ("foobar\n\"Foobarnator\";v=\"3.14\"\n?1", header_value); + EXPECT_TRUE( + ExecuteScriptAndExtractString(web_contents, + "window.domAutomationController.send(JSON." + "stringify(navigator.userAgentData));", + &header_value)); + EXPECT_EQ( + R"({"brands":[{"brand":"Foobarnator","version":"3.14"}],"mobile":true})", + header_value); } IN_PROC_BROWSER_TEST_F(ClientHintsBrowserTest, EmptyAcceptCH) { @@ -3358,6 +3373,11 @@ base::StrCat({kOriginUrl, "/accept_ch_ua_iframe_request.html"})); } + GURL accept_ch_ua_iframe_sandbox_request_url() const { + return GURL(base::StrCat( + {kOriginUrl, "/accept_ch_ua_iframe_sandbox_request.html"})); + } + GURL critical_ch_ua_subresource_request_url() const { return GURL( base::StrCat({kOriginUrl, "/critical_ch_ua_subresource_request.html"})); @@ -3773,6 +3793,29 @@ } IN_PROC_BROWSER_TEST_P(SameOriginUaOriginTrialBrowserTest, + IframeRequestUaWithValidOriginTrialTokenIgnoreSandbox) { + SetTestOptions( + { + /*has_ot_token=*/true, + /*valid_ot_token=*/true, + /*has_accept_ch_header=*/true, + /*has_critical_ch_header=*/false, + }, + {accept_ch_ua_iframe_sandbox_request_url(), simple_request_url()}); + + // Ensure that frames with sandbox flags don't interfere with the origin trial + NavigateAndCheckHeaders(accept_ch_ua_iframe_sandbox_request_url(), + /*ch_ua_reduced_expected=*/GetParam() == + UserAgentOriginTrialTestType::UAReduction, + /*ch_ua_exist_expected=*/true); + + CheckSecClientHintUaCount(); + + // Make sure the last intercepted URL was the request for the embedded iframe. + EXPECT_EQ(last_request_url().path(), "/simple.html"); +} + +IN_PROC_BROWSER_TEST_P(SameOriginUaOriginTrialBrowserTest, IframeRequestUaWithValidOriginTrialTokenAndCriticalCH) { SetTestOptions( {/*has_ot_token=*/true, /*valid_ot_token=*/true, @@ -3861,7 +3904,7 @@ // Since the UA override was set, the UA client hints are *not* added to the // request. - CheckUaOriginTrialClientHint(/*ch_ua_expected=*/false); + CheckUaOriginTrialClientHint(/*ch_ua_expected=*/true); // Make sure the overridden UA string is the one sent. CheckUserAgentString(user_agent_override); @@ -3890,7 +3933,7 @@ // Since the UA override was set, the UA client hints are *not* added to the // request. - CheckUaOriginTrialClientHint(/*ch_ua_expected=*/false); + CheckUaOriginTrialClientHint(/*ch_ua_expected=*/true); // Make sure the overridden UA string is the one sent. CheckUserAgentString(user_agent_override); } @@ -3914,7 +3957,7 @@ // Since the UA override was set, the UA client hints are *not* added to the // request. - CheckUaOriginTrialClientHint(/*ch_ua_expected=*/false); + CheckUaOriginTrialClientHint(/*ch_ua_expected=*/true); // Make sure the overridden UA string is the one sent. CheckUserAgentString(user_agent_override); }
diff --git a/chrome/browser/component_updater/chrome_client_side_phishing_component_installer.cc b/chrome/browser/component_updater/chrome_client_side_phishing_component_installer.cc index 3eef6abba..d893109f 100644 --- a/chrome/browser/component_updater/chrome_client_side_phishing_component_installer.cc +++ b/chrome/browser/component_updater/chrome_client_side_phishing_component_installer.cc
@@ -68,7 +68,7 @@ void RegisterClientSidePhishingComponent(ComponentUpdateService* cus) { auto installer = base::MakeRefCounted<ComponentInstaller>( std::make_unique<ClientSidePhishingComponentInstallerPolicy>( - cus, base::BindRepeating(&PopulateModelFromFiles), + base::BindRepeating(&PopulateModelFromFiles), base::BindRepeating(&GetInstallerAttributes))); installer->Register(cus, base::OnceClosure()); }
diff --git a/chrome/browser/component_updater/pki_metadata_component_installer.cc b/chrome/browser/component_updater/pki_metadata_component_installer.cc index 7df9a25..73534c4d 100644 --- a/chrome/browser/component_updater/pki_metadata_component_installer.cc +++ b/chrome/browser/component_updater/pki_metadata_component_installer.cc
@@ -244,7 +244,7 @@ popular_scts.reserve(proto->popular_scts().size()); std::transform( proto->popular_scts().begin(), proto->popular_scts().end(), - popular_scts.begin(), [](std::string sct) { + std::back_inserter(popular_scts), [](std::string sct) { const uint8_t* raw_data = reinterpret_cast<const uint8_t*>(sct.data()); return std::vector<uint8_t>(raw_data, raw_data + sct.length()); });
diff --git a/chrome/browser/content_creation/reactions/internal/android/java/src/org/chromium/chrome/browser/content_creation/reactions/scene/ReactionLayout.java b/chrome/browser/content_creation/reactions/internal/android/java/src/org/chromium/chrome/browser/content_creation/reactions/scene/ReactionLayout.java index a3da980..7e5b969 100644 --- a/chrome/browser/content_creation/reactions/internal/android/java/src/org/chromium/chrome/browser/content_creation/reactions/scene/ReactionLayout.java +++ b/chrome/browser/content_creation/reactions/internal/android/java/src/org/chromium/chrome/browser/content_creation/reactions/scene/ReactionLayout.java
@@ -134,6 +134,10 @@ screenHeight - (layoutParams.topMargin - mHeight); ReactionLayout.this.setLayoutParams(layoutParams); break; + case MotionEvent.ACTION_UP: + view.announceForAccessibility(mContext.getString( + R.string.lightweight_reactions_reaction_moved_announcement)); + break; } return true; }
diff --git a/chrome/browser/content_creation/reactions/internal/android/java/src/org/chromium/chrome/browser/content_creation/reactions/scene/SceneCoordinator.java b/chrome/browser/content_creation/reactions/internal/android/java/src/org/chromium/chrome/browser/content_creation/reactions/scene/SceneCoordinator.java index d48a88f..ccaf188 100644 --- a/chrome/browser/content_creation/reactions/internal/android/java/src/org/chromium/chrome/browser/content_creation/reactions/scene/SceneCoordinator.java +++ b/chrome/browser/content_creation/reactions/internal/android/java/src/org/chromium/chrome/browser/content_creation/reactions/scene/SceneCoordinator.java
@@ -434,6 +434,8 @@ new ReactionGifDrawable(reaction, baseGifImage, Bitmap.Config.ARGB_8888), reaction.localizedName); resetReactions(mActiveReaction); + mActiveReaction.announceForAccessibility(mActivity.getString( + R.string.lightweight_reactions_reaction_changed_announcement)); }); }
diff --git a/chrome/browser/data_use_measurement/DIR_METADATA b/chrome/browser/data_use_measurement/DIR_METADATA new file mode 100644 index 0000000..3c8435d --- /dev/null +++ b/chrome/browser/data_use_measurement/DIR_METADATA
@@ -0,0 +1,3 @@ +monorail: { + component: "Internals>Network>DataUse" +}
diff --git a/chrome/browser/data_use_measurement/OWNERS b/chrome/browser/data_use_measurement/OWNERS new file mode 100644 index 0000000..d4302ee --- /dev/null +++ b/chrome/browser/data_use_measurement/OWNERS
@@ -0,0 +1,3 @@ +curranmax@chromium.org +ryansturm@chromium.org +spelchat@chromium.org \ No newline at end of file
diff --git a/chrome/browser/data_use_measurement/chrome_data_use_measurement.cc b/chrome/browser/data_use_measurement/chrome_data_use_measurement.cc new file mode 100644 index 0000000..c3e77af --- /dev/null +++ b/chrome/browser/data_use_measurement/chrome_data_use_measurement.cc
@@ -0,0 +1,124 @@ +// Copyright 2022 The Chromium 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/data_use_measurement/chrome_data_use_measurement.h" + +#include "base/metrics/histogram_functions.h" +#include "base/metrics/histogram_macros.h" +#include "base/no_destructor.h" +#include "content/public/browser/browser_thread.h" + +#if BUILDFLAG(IS_ANDROID) +#include "net/android/traffic_stats.h" +#endif + +using content::BrowserThread; + +// static +ChromeDataUseMeasurement& ChromeDataUseMeasurement::GetInstance() { + DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI) || + !BrowserThread::IsThreadInitialized(BrowserThread::UI)); + + static base::NoDestructor<ChromeDataUseMeasurement> + s_chrome_data_use_measurement; + return *s_chrome_data_use_measurement; +} + +ChromeDataUseMeasurement::ChromeDataUseMeasurement() { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + +#if BUILDFLAG(IS_ANDROID) + int64_t bytes = 0; + // Query Android traffic stats. + if (net::android::traffic_stats::GetCurrentUidRxBytes(&bytes)) + rx_bytes_os_ = bytes; + + if (net::android::traffic_stats::GetCurrentUidTxBytes(&bytes)) + tx_bytes_os_ = bytes; +#endif +} + +ChromeDataUseMeasurement::~ChromeDataUseMeasurement() = default; + +void ChromeDataUseMeasurement::ReportNetworkServiceDataUse( + int32_t network_traffic_annotation_id_hash, + int64_t recv_bytes, + int64_t sent_bytes) { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + // Negative byte numbers is not a critical problem (i.e., should have no + // security implications) but is not expected. TODO(rajendrant): remove these + // DCHECKs or consider using uint in Mojo instead. + DCHECK_GE(recv_bytes, 0); + DCHECK_GE(sent_bytes, 0); + + ReportDataUsage(TrafficDirection::kUpstream, sent_bytes); + ReportDataUsage(TrafficDirection::kDownstream, recv_bytes); +} + +void ChromeDataUseMeasurement::ReportDataUsage(TrafficDirection dir, + int64_t message_size_bytes) { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + + if (message_size_bytes <= 0) + return; + + if (dir == TrafficDirection::kDownstream) { + base::UmaHistogramCustomCounts("DataUse.BytesReceived3.Delegate", + message_size_bytes, 50, 10 * 1000 * 1000, + 50); + } + + if (dir == TrafficDirection::kUpstream) + UMA_HISTOGRAM_COUNTS_1M("DataUse.BytesSent3.Delegate", message_size_bytes); + +#if BUILDFLAG(IS_ANDROID) + bytes_transferred_since_last_traffic_stats_query_ += message_size_bytes; + MaybeRecordNetworkBytesOS(); +#endif +} + +#if BUILDFLAG(IS_ANDROID) +void ChromeDataUseMeasurement::MaybeRecordNetworkBytesOS() { + // Minimum number of bytes that should be reported by the network delegate + // before Android's TrafficStats API is queried (if Chrome is not in + // background). This reduces the overhead of repeatedly calling the API. + static const int64_t kMinDelegateBytes = 25000; + + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + if (bytes_transferred_since_last_traffic_stats_query_ < kMinDelegateBytes) { + return; + } + bytes_transferred_since_last_traffic_stats_query_ = 0; + int64_t bytes = 0; + // Query Android traffic stats directly instead of registering with the + // DataUseAggregator since the latter does not provide notifications for + // the incognito traffic. + if (net::android::traffic_stats::GetCurrentUidRxBytes(&bytes)) { + if (rx_bytes_os_ != 0) { + DCHECK_GE(bytes, rx_bytes_os_); + if (bytes > rx_bytes_os_) { + int64_t incremental_bytes = bytes - rx_bytes_os_; + // Do not record samples with value 0. + base::UmaHistogramCustomCounts("DataUse.BytesReceived3.OS", + incremental_bytes, 50, 10 * 1000 * 1000, + 50); + } + } + rx_bytes_os_ = bytes; + } + + if (net::android::traffic_stats::GetCurrentUidTxBytes(&bytes)) { + if (tx_bytes_os_ != 0) { + DCHECK_GE(bytes, tx_bytes_os_); + if (bytes > tx_bytes_os_) { + int64_t incremental_bytes = bytes - tx_bytes_os_; + // Do not record samples with value 0. + UMA_HISTOGRAM_COUNTS_1M("DataUse.BytesSent3.OS", incremental_bytes); + } + } + tx_bytes_os_ = bytes; + } +} + +#endif
diff --git a/chrome/browser/data_use_measurement/chrome_data_use_measurement.h b/chrome/browser/data_use_measurement/chrome_data_use_measurement.h new file mode 100644 index 0000000..1945049 --- /dev/null +++ b/chrome/browser/data_use_measurement/chrome_data_use_measurement.h
@@ -0,0 +1,57 @@ +// Copyright 2022 The Chromium 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_DATA_USE_MEASUREMENT_CHROME_DATA_USE_MEASUREMENT_H_ +#define CHROME_BROWSER_DATA_USE_MEASUREMENT_CHROME_DATA_USE_MEASUREMENT_H_ + +#include "base/sequence_checker.h" +#include "build/build_config.h" + +class ChromeDataUseMeasurement { + public: + static ChromeDataUseMeasurement& GetInstance(); + + ChromeDataUseMeasurement(const ChromeDataUseMeasurement&) = delete; + ChromeDataUseMeasurement& operator=(const ChromeDataUseMeasurement&) = delete; + + // Called when requests complete from NetworkService. Called for all requests + // (including service requests and user-initiated requests). + void ReportNetworkServiceDataUse(int32_t network_traffic_annotation_id_hash, + int64_t recv_bytes, + int64_t sent_bytes); + + ChromeDataUseMeasurement(); + ~ChromeDataUseMeasurement(); + + private: + // Specifies that data is received or sent, respectively. + enum class TrafficDirection { kDownstream, kUpstream }; + + // Records data use histograms. It gets the size of exchanged + // message, its direction (which is upstream or downstream) and reports to the + // histogram DataUse.Services.{Dimensions} with, services as the buckets. + // |app_state| indicates the app state which can be foreground, or background. + void ReportDataUsage(TrafficDirection dir, int64_t message_size_bytes); + +#if BUILDFLAG(IS_ANDROID) + // Records the count of bytes received and sent by Chrome on the network as + // reported by the operating system. + void MaybeRecordNetworkBytesOS(); + + // Number of bytes received and sent by Chromium as reported by the operating + // system when it was last queried for traffic statistics. Set to 0 if the + // operating system was never queried. + int64_t rx_bytes_os_ = 0; + int64_t tx_bytes_os_ = 0; + + // Number of bytes received and sent by Chromium as reported by the network + // delegate since the operating system was last queried for traffic + // statistics. + int64_t bytes_transferred_since_last_traffic_stats_query_ = 0; +#endif + + SEQUENCE_CHECKER(sequence_checker_); +}; + +#endif // CHROME_BROWSER_DATA_USE_MEASUREMENT_CHROME_DATA_USE_MEASUREMENT_H_
diff --git a/chrome/browser/data_use_measurement/chrome_data_use_measurement_browsertest.cc b/chrome/browser/data_use_measurement/chrome_data_use_measurement_browsertest.cc new file mode 100644 index 0000000..0c9d25c --- /dev/null +++ b/chrome/browser/data_use_measurement/chrome_data_use_measurement_browsertest.cc
@@ -0,0 +1,49 @@ +// Copyright 2022 The Chromium 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/data_use_measurement/chrome_data_use_measurement.h" + +#include "base/run_loop.h" +#include "base/task/thread_pool/thread_pool_instance.h" +#include "build/build_config.h" +#include "chrome/browser/browser_process.h" +#include "chrome/browser/ui/browser.h" +#include "chrome/test/base/in_process_browser_test.h" +#include "chrome/test/base/ui_test_utils.h" +#include "content/public/test/browser_test.h" +#include "content/public/test/browser_test_utils.h" +#include "content/public/test/content_browser_test.h" +#include "testing/gmock/include/gmock/gmock.h" + +class ChromeDataUseMeasurementBrowserTest : public InProcessBrowserTest { + protected: + void SetUpOnMainThread() override { + embedded_test_server()->ServeFilesFromSourceDirectory( + GetChromeTestDataDir()); + ASSERT_TRUE(embedded_test_server()->Start()); + } + + size_t GetTotalDataUse() const { + return histogram_tester_.GetTotalSum("DataUse.BytesReceived3.Delegate") + + histogram_tester_.GetTotalSum("DataUse.BytesSent3.Delegate"); + } + + void RetryUntilUserInitiatedDataUsePrefHasEntry() { + do { + base::ThreadPoolInstance::Get()->FlushForTesting(); + base::RunLoop().RunUntilIdle(); + } while (GetTotalDataUse() == 0); + } + + private: + base::HistogramTester histogram_tester_; +}; + +IN_PROC_BROWSER_TEST_F(ChromeDataUseMeasurementBrowserTest, DataUseRecorded) { + ASSERT_TRUE(ui_test_utils::NavigateToURL( + browser(), embedded_test_server()->GetURL("/title1.html"))); + RetryUntilUserInitiatedDataUsePrefHasEntry(); + + EXPECT_GT(GetTotalDataUse(), 0u); +}
diff --git a/chrome/browser/download/chrome_download_manager_delegate.cc b/chrome/browser/download/chrome_download_manager_delegate.cc index beb483d..fc1d593 100644 --- a/chrome/browser/download/chrome_download_manager_delegate.cc +++ b/chrome/browser/download/chrome_download_manager_delegate.cc
@@ -1777,12 +1777,6 @@ #if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) || \ BUILDFLAG(IS_MAC) - if (!base::FeatureList::IsEnabled( - download::features::kAllowSavePackageScanning)) { - std::move(callback).Run(true); - return; - } - absl::optional<enterprise_connectors::AnalysisSettings> settings = safe_browsing::DeepScanningRequest::ShouldUploadBinary(download_item);
diff --git a/chrome/browser/flag-metadata.json b/chrome/browser/flag-metadata.json index 6534683..6ed5e810 100644 --- a/chrome/browser/flag-metadata.json +++ b/chrome/browser/flag-metadata.json
@@ -5613,11 +5613,6 @@ "expiry_milestone": 104 }, { - "name": "swap-android-share-hub-rows", - "owners": [ "ellyjones", "chrome-sharing-eng@google.com" ], - "expiry_milestone": 100 - }, - { "name": "sync-android-promos-revamp", "owners": ["mmrashad@google.com", "chrome-sync-dev@google.com"], "expiry_milestone": 103
diff --git a/chrome/browser/flag_descriptions.cc b/chrome/browser/flag_descriptions.cc index a3de5bd..f9497a3 100644 --- a/chrome/browser/flag_descriptions.cc +++ b/chrome/browser/flag_descriptions.cc
@@ -3552,11 +3552,6 @@ "An option in `Site settings` to persistently request the " "desktop version of websites."; -const char kSwapAndroidShareHubRowsName[] = "Swap Android share hub rows."; -const char kSwapAndroidShareHubRowsDescription[] = - "Swap the order of the first-party and third-party rows in the Android " - "share hub."; - const char kRequestDesktopSiteForTabletsName[] = "Request desktop site for tablets on Android"; const char kRequestDesktopSiteForTabletsDescription[] =
diff --git a/chrome/browser/flag_descriptions.h b/chrome/browser/flag_descriptions.h index 72743c5..f93fb2f 100644 --- a/chrome/browser/flag_descriptions.h +++ b/chrome/browser/flag_descriptions.h
@@ -2030,9 +2030,6 @@ extern const char kRequestDesktopSiteGlobalName[]; extern const char kRequestDesktopSiteGlobalDescription[]; -extern const char kSwapAndroidShareHubRowsName[]; -extern const char kSwapAndroidShareHubRowsDescription[]; - extern const char kRequestDesktopSiteForTabletsName[]; extern const char kRequestDesktopSiteForTabletsDescription[];
diff --git a/chrome/browser/flags/android/chrome_feature_list.cc b/chrome/browser/flags/android/chrome_feature_list.cc index 6f5ac9b..55f4b1a 100644 --- a/chrome/browser/flags/android/chrome_feature_list.cc +++ b/chrome/browser/flags/android/chrome_feature_list.cc
@@ -364,7 +364,6 @@ &send_tab_to_self::kSendTabToSelfSigninPromo, &send_tab_to_self::kSendTabToSelfV2, &share::kPersistShareHubOnAppSwitch, - &share::kSwapAndroidShareHubRows, &share::kUpcomingSharingFeatures, &signin::kMobileIdentityConsistencyPromos, &switches::kAllowSyncOffForChildAccounts,
diff --git a/chrome/browser/flags/android/java/src/org/chromium/chrome/browser/flags/ChromeFeatureList.java b/chrome/browser/flags/android/java/src/org/chromium/chrome/browser/flags/ChromeFeatureList.java index d00b46b..02bddac5 100644 --- a/chrome/browser/flags/android/java/src/org/chromium/chrome/browser/flags/ChromeFeatureList.java +++ b/chrome/browser/flags/android/java/src/org/chromium/chrome/browser/flags/ChromeFeatureList.java
@@ -494,7 +494,6 @@ public static final String START_SURFACE_ANDROID = "StartSurfaceAndroid"; public static final String STORE_HOURS = "StoreHoursAndroid"; public static final String SUPPRESS_TOOLBAR_CAPTURES = "SuppressToolbarCaptures"; - public static final String SWAP_ANDROID_SHARE_HUB_ROWS = "SwapAndroidShareHubRows"; public static final String SWAP_PIXEL_FORMAT_TO_FIX_CONVERT_FROM_TRANSLUCENT = "SwapPixelFormatToFixConvertFromTranslucent"; public static final String SYNC_TRUSTED_VAULT_PASSPHRASE_RECOVERY =
diff --git a/chrome/browser/locale/BUILD.gn b/chrome/browser/locale/BUILD.gn index a4fa0691..8630691 100644 --- a/chrome/browser/locale/BUILD.gn +++ b/chrome/browser/locale/BUILD.gn
@@ -47,6 +47,7 @@ "//chrome/browser/ui/android/strings:ui_strings_grd", "//chrome/browser/ui/messages/android:java", "//components/browser_ui/settings/android:java", + "//components/browser_ui/strings/android:browser_ui_strings_grd", "//components/browser_ui/widget/android:java", "//components/search_engines/android:java", "//third_party/androidx:androidx_annotation_annotation_java",
diff --git a/chrome/browser/page_load_metrics/page_load_metrics_browsertest.cc b/chrome/browser/page_load_metrics/page_load_metrics_browsertest.cc index 05a46bd..56b097c 100644 --- a/chrome/browser/page_load_metrics/page_load_metrics_browsertest.cc +++ b/chrome/browser/page_load_metrics/page_load_metrics_browsertest.cc
@@ -55,6 +55,7 @@ #include "chrome/common/url_constants.h" #include "chrome/test/base/in_process_browser_test.h" #include "chrome/test/base/ui_test_utils.h" +#include "components/embedder_support/user_agent_utils.h" #include "components/keep_alive_registry/keep_alive_types.h" #include "components/keep_alive_registry/scoped_keep_alive.h" #include "components/no_state_prefetch/browser/no_state_prefetch_handle.h" @@ -72,6 +73,7 @@ #include "components/ukm/test_ukm_recorder.h" #include "content/public/browser/back_forward_cache.h" #include "content/public/browser/browser_thread.h" +#include "content/public/browser/navigation_entry.h" #include "content/public/browser/render_process_host.h" #include "content/public/browser/render_view_host.h" #include "content/public/common/content_features.h" @@ -94,6 +96,7 @@ #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/blink/public/common/features.h" +#include "third_party/blink/public/common/user_agent/user_agent_metadata.h" #include "third_party/blink/public/mojom/use_counter/css_property_id.mojom.h" #include "third_party/blink/public/mojom/web_feature/web_feature.mojom.h" #include "ui/gfx/geometry/size.h" @@ -141,7 +144,8 @@ PageLoadMetricsBrowserTest() { scoped_feature_list_.InitWithFeatures( {ukm::kUkmFeature, blink::features::kPortals, - blink::features::kPortalsCrossOrigin}, + blink::features::kPortalsCrossOrigin, + blink::features::kUserAgentOverrideExperiment}, {}); } @@ -2014,6 +2018,107 @@ waiter->Wait(); } +IN_PROC_BROWSER_TEST_F(PageLoadMetricsBrowserTest, + UseCounterUserAgentOverride) { + ASSERT_TRUE(embedded_test_server()->Start()); + + content::WebContents* web_contents = + browser()->tab_strip_model()->GetActiveWebContents(); + std::string original_ua = embedder_support::GetUserAgent(); + std::string ua_no_substring = "foo"; + std::string ua_prefix = "foo" + original_ua; + std::string ua_suffix = original_ua + "foo"; + + { + base::HistogramTester histogram; + web_contents->SetUserAgentOverride( + blink::UserAgentOverride::UserAgentOnly(ua_no_substring), false); + web_contents->GetController() + .GetLastCommittedEntry() + ->SetIsOverridingUserAgent(true); + auto waiter = CreatePageLoadMetricsTestWaiter(); + waiter->AddUseCounterFeatureExpectation({ + blink::mojom::UseCounterFeatureType::kUserAgentOverride, + blink::UserAgentOverride::UserAgentOverriden, + }); + ASSERT_TRUE(ui_test_utils::NavigateToURL( + browser(), embedded_test_server()->GetURL("/empty.html"))); + content::EvalJsResult result = EvalJs(web_contents, "navigator.userAgent;"); + waiter->Wait(); + NavigateToUntrackedUrl(); + content::FetchHistogramsFromChildProcesses(); + // Expect 2; one in the navigation stack and one in the renderer + histogram.ExpectBucketCount( + blink::UserAgentOverride::kUserAgentOverrideHistogram, + blink::UserAgentOverride::UserAgentOverriden, 2); + histogram.ExpectBucketCount( + blink::UserAgentOverride::kUserAgentOverrideHistogram, + blink::UserAgentOverride::UserAgentOverrideSubstring, 0); + histogram.ExpectBucketCount( + blink::UserAgentOverride::kUserAgentOverrideHistogram, + blink::UserAgentOverride::UserAgentOverrideSuffix, 0); + } + + { + base::HistogramTester histogram; + web_contents->SetUserAgentOverride( + blink::UserAgentOverride::UserAgentOnly(ua_prefix), false); + web_contents->GetController() + .GetLastCommittedEntry() + ->SetIsOverridingUserAgent(true); + auto waiter = CreatePageLoadMetricsTestWaiter(); + waiter->AddUseCounterFeatureExpectation({ + blink::mojom::UseCounterFeatureType::kUserAgentOverride, + blink::UserAgentOverride::UserAgentOverrideSubstring, + }); + ASSERT_TRUE(ui_test_utils::NavigateToURL( + browser(), embedded_test_server()->GetURL("/empty.html"))); + content::EvalJsResult result = EvalJs(web_contents, "navigator.userAgent;"); + waiter->Wait(); + NavigateToUntrackedUrl(); + content::FetchHistogramsFromChildProcesses(); + // Expect 2; one in the navigation stack and one in the renderer + histogram.ExpectBucketCount( + blink::UserAgentOverride::kUserAgentOverrideHistogram, + blink::UserAgentOverride::UserAgentOverriden, 0); + histogram.ExpectBucketCount( + blink::UserAgentOverride::kUserAgentOverrideHistogram, + blink::UserAgentOverride::UserAgentOverrideSubstring, 2); + histogram.ExpectBucketCount( + blink::UserAgentOverride::kUserAgentOverrideHistogram, + blink::UserAgentOverride::UserAgentOverrideSuffix, 0); + } + { + base::HistogramTester histogram; + web_contents->SetUserAgentOverride( + blink::UserAgentOverride::UserAgentOnly(ua_suffix), false); + web_contents->GetController() + .GetLastCommittedEntry() + ->SetIsOverridingUserAgent(true); + auto waiter = CreatePageLoadMetricsTestWaiter(); + waiter->AddUseCounterFeatureExpectation({ + blink::mojom::UseCounterFeatureType::kUserAgentOverride, + blink::UserAgentOverride::UserAgentOverrideSuffix, + }); + ASSERT_TRUE(ui_test_utils::NavigateToURL( + browser(), embedded_test_server()->GetURL("/empty.html"))); + content::EvalJsResult result = EvalJs(web_contents, "navigator.userAgent;"); + waiter->Wait(); + NavigateToUntrackedUrl(); + content::FetchHistogramsFromChildProcesses(); + // Expect 2; one in the navigation stack and one in the renderer + histogram.ExpectBucketCount( + blink::UserAgentOverride::kUserAgentOverrideHistogram, + blink::UserAgentOverride::UserAgentOverriden, 0); + histogram.ExpectBucketCount( + blink::UserAgentOverride::kUserAgentOverrideHistogram, + blink::UserAgentOverride::UserAgentOverrideSubstring, 0); + histogram.ExpectBucketCount( + blink::UserAgentOverride::kUserAgentOverrideHistogram, + blink::UserAgentOverride::UserAgentOverrideSuffix, 2); + } +} + class SessionRestorePageLoadMetricsBrowserTest : public PageLoadMetricsBrowserTest { public:
diff --git a/chrome/browser/profiles/profile_impl.cc b/chrome/browser/profiles/profile_impl.cc index 8b00649..de7a723 100644 --- a/chrome/browser/profiles/profile_impl.cc +++ b/chrome/browser/profiles/profile_impl.cc
@@ -109,6 +109,8 @@ #include "chrome/browser/updates/announcement_notification/announcement_notification_service_factory.h" #include "chrome/browser/webid/federated_identity_active_session_permission_context.h" #include "chrome/browser/webid/federated_identity_active_session_permission_context_factory.h" +#include "chrome/browser/webid/federated_identity_api_permission_context.h" +#include "chrome/browser/webid/federated_identity_api_permission_context_factory.h" #include "chrome/browser/webid/federated_identity_request_permission_context.h" #include "chrome/browser/webid/federated_identity_request_permission_context_factory.h" #include "chrome/browser/webid/federated_identity_sharing_permission_context.h" @@ -162,6 +164,7 @@ #include "content/public/browser/browser_thread.h" #include "content/public/browser/dom_storage_context.h" #include "content/public/browser/federated_identity_active_session_permission_context_delegate.h" +#include "content/public/browser/federated_identity_api_permission_context_delegate.h" #include "content/public/browser/federated_identity_request_permission_context_delegate.h" #include "content/public/browser/federated_identity_sharing_permission_context_delegate.h" #include "content/public/browser/permission_controller.h" @@ -1325,6 +1328,11 @@ return ContentIndexProviderFactory::GetForProfile(this); } +content::FederatedIdentityApiPermissionContextDelegate* +ProfileImpl::GetFederatedIdentityApiPermissionContext() { + return FederatedIdentityApiPermissionContextFactory::GetForProfile(this); +} + content::FederatedIdentityActiveSessionPermissionContextDelegate* ProfileImpl::GetFederatedIdentityActiveSessionPermissionContext() { return FederatedIdentityActiveSessionPermissionContextFactory::GetForProfile(
diff --git a/chrome/browser/profiles/profile_impl.h b/chrome/browser/profiles/profile_impl.h index e72bfb5..1de6f3a 100644 --- a/chrome/browser/profiles/profile_impl.h +++ b/chrome/browser/profiles/profile_impl.h
@@ -92,6 +92,8 @@ content::FileSystemAccessPermissionContext* GetFileSystemAccessPermissionContext() override; content::ContentIndexProvider* GetContentIndexProvider() override; + content::FederatedIdentityApiPermissionContextDelegate* + GetFederatedIdentityApiPermissionContext() override; content::FederatedIdentityActiveSessionPermissionContextDelegate* GetFederatedIdentityActiveSessionPermissionContext() override; content::FederatedIdentityRequestPermissionContextDelegate*
diff --git a/chrome/browser/resources/chromeos/accessibility/chromevox/background/desktop_automation_handler.js b/chrome/browser/resources/chromeos/accessibility/chromevox/background/desktop_automation_handler.js index 5e75335..92edae6 100644 --- a/chrome/browser/resources/chromeos/accessibility/chromevox/background/desktop_automation_handler.js +++ b/chrome/browser/resources/chromeos/accessibility/chromevox/background/desktop_automation_handler.js
@@ -531,43 +531,51 @@ return; } - const t = evt.target; - const fromDesktop = t.root.role === RoleType.DESKTOP; + const target = evt.target; + const fromDesktop = target.root.role === RoleType.DESKTOP; const onDesktop = ChromeVoxState.instance.currentRange.start.node.root.role === RoleType.DESKTOP; - if (fromDesktop && !onDesktop && t.role !== RoleType.SLIDER) { + const isSlider = target.role === RoleType.SLIDER; + + // TODO(accessibility): get rid of callers who use value changes on list + // boxes. + const isListBox = target.role === RoleType.LIST_BOX; + if (fromDesktop && !onDesktop && !isSlider && !isListBox) { // Only respond to value changes from the desktop if it's coming from a // slider e.g. the volume slider. Do this to avoid responding to frequent // updates from UI e.g. download progress bars. return; } - if (t.state.focused || fromDesktop || - AutomationUtil.isDescendantOf( - ChromeVoxState.instance.currentRange.start.node, t)) { - if (new Date() - this.lastValueChanged_ <= - DesktopAutomationHandler.MIN_VALUE_CHANGE_DELAY_MS) { - return; - } - this.lastValueChanged_ = new Date(); - - const output = new Output(); - output.withoutFocusRing(); - - if (fromDesktop && - (!this.lastValueTarget_ || this.lastValueTarget_ !== t)) { - const range = cursors.Range.fromNode(t); - output.withRichSpeechAndBraille(range, range, OutputEventType.NAVIGATE); - this.lastValueTarget_ = t; - } else { - output.format( - '$if($value, $value, $if($valueForRange, $valueForRange))', t); - } - - Output.forceModeForNextSpeechUtterance(QueueMode.INTERJECT); - output.go(); + if (!target.state.focused && (!fromDesktop || (!isSlider && !isListBox)) && + !AutomationUtil.isDescendantOf( + ChromeVoxState.instance.currentRange.start.node, target)) { + return; } + + if (new Date() - this.lastValueChanged_ <= + DesktopAutomationHandler.MIN_VALUE_CHANGE_DELAY_MS) { + return; + } + + this.lastValueChanged_ = new Date(); + + const output = new Output(); + output.withoutFocusRing(); + + if (fromDesktop && + (!this.lastValueTarget_ || this.lastValueTarget_ !== target)) { + const range = cursors.Range.fromNode(target); + output.withRichSpeechAndBraille(range, range, OutputEventType.NAVIGATE); + this.lastValueTarget_ = target; + } else { + output.format( + '$if($value, $value, $if($valueForRange, $valueForRange))', target); + } + + Output.forceModeForNextSpeechUtterance(QueueMode.INTERJECT); + output.go(); } /**
diff --git a/chrome/browser/resources/chromeos/accessibility/chromevox/background/editing/editing_test.js b/chrome/browser/resources/chromeos/accessibility/chromevox/background/editing/editing_test.js index 10e1291..8d50968 100644 --- a/chrome/browser/resources/chromeos/accessibility/chromevox/background/editing/editing_test.js +++ b/chrome/browser/resources/chromeos/accessibility/chromevox/background/editing/editing_test.js
@@ -2112,10 +2112,8 @@ }); }); -// TODO(crbug.com/1304140): Disabled due to flakyness TEST_F( - 'ChromeVoxEditingTest', 'DISABLED_InputTextBrailleContractions', - function() { + 'ChromeVoxEditingTest', 'InputTextBrailleContractions', function() { const site = ` <input type=text value="about that"></input> `; @@ -2138,15 +2136,12 @@ // Set braille to use 6-dot braille (which is defaulted to UEB grade 2 // contracted braille). localStorage['brailleTable'] = 'en-ueb-g2'; - BrailleBackground.getInstance().getTranslatorManager().refresh( - localStorage['brailleTable']); + // Wait for it to be fully refreshed (liblouis loads the new tables, our // translators are re-created). - await new Promise(r => { - BrailleBackground.getInstance() - .getTranslatorManager() - .addChangeListener(r); - }); + await BrailleBackground.getInstance() + .getTranslatorManager() + .loadTablesForTest(); async function waitForBrailleDots(expectedDots) { return new Promise(r => {
diff --git a/chrome/browser/resources/chromeos/accessibility/chromevox/braille/braille_translator_manager.js b/chrome/browser/resources/chromeos/accessibility/chromevox/braille/braille_translator_manager.js index bb37167..298bac6 100644 --- a/chrome/browser/resources/chromeos/accessibility/chromevox/braille/braille_translator_manager.js +++ b/chrome/browser/resources/chromeos/accessibility/chromevox/braille/braille_translator_manager.js
@@ -82,8 +82,9 @@ * @param {string} brailleTable The table for this translator to use. * @param {string=} opt_brailleTable8 Optionally specify an uncontracted * table. + * @param {function()=} opt_finishCallback Called when the refresh finishes. */ - refresh(brailleTable, opt_brailleTable8) { + refresh(brailleTable, opt_brailleTable8, opt_finishCallback) { if (brailleTable && brailleTable === this.defaultTableId_) { return; } @@ -154,6 +155,10 @@ this.liblouis_.getTranslator( uncontractedTable.fileNames, function(uncontractedTranslator) { finishRefresh(translator, uncontractedTranslator); + + if (opt_finishCallback) { + opt_finishCallback(); + } }); } }.bind(this)); @@ -187,15 +192,18 @@ /** * Asynchronously fetches the list of braille tables and refreshes the * translators when done. + * @return {!Promise} Resolves when tables are loaded. * @private */ - fetchTables_() { - BrailleTable.getAll(function(tables) { - this.tables_ = tables; + async fetchTables_() { + return new Promise(r => { + BrailleTable.getAll(tables => { + this.tables_ = tables; - // Initial refresh; set options from user preferences. - this.refresh(localStorage['brailleTable']); - }.bind(this)); + // Initial refresh; set options from user preferences. + this.refresh(localStorage['brailleTable'], undefined, r); + }); + }); } /** @@ -220,4 +228,12 @@ getTablesForTest() { return this.tables_; } + + /** + * Loads liblouis tables and returns a promise resolved when loaded. + * @return {!Promise} + */ + async loadTablesForTest() { + await this.fetchTables_(); + } };
diff --git a/chrome/browser/resources/history/history_clusters/metrics_proxy.ts b/chrome/browser/resources/history/history_clusters/metrics_proxy.ts index 03a6338d..08c182b0 100644 --- a/chrome/browser/resources/history/history_clusters/metrics_proxy.ts +++ b/chrome/browser/resources/history/history_clusters/metrics_proxy.ts
@@ -16,7 +16,7 @@ OPENED_IN_TAB_GROUP = 'OpenedInTabGroup', RELATED_SEARCH_CLICKED = 'RelatedSearchClicked', RELATED_VISITS_VISIBILITY_TOGGLED = 'RelatedVisitsVisibilityToggled', - VISIT_CLICKED = 'RelatedSearchClicked', + VISIT_CLICKED = 'VisitClicked', } export enum RelatedSearchAction {
diff --git a/chrome/browser/safe_browsing/download_protection/deep_scanning_browsertest.cc b/chrome/browser/safe_browsing/download_protection/deep_scanning_browsertest.cc index d596032..c44ac12 100644 --- a/chrome/browser/safe_browsing/download_protection/deep_scanning_browsertest.cc +++ b/chrome/browser/safe_browsing/download_protection/deep_scanning_browsertest.cc
@@ -1497,10 +1497,7 @@ public: SavePackageDeepScanningBrowserTest() : DownloadDeepScanningBrowserTestBase(/*connectors_machine_scope=*/true, - /*is_consumer=*/false) { - scoped_feature_list_.InitAndEnableFeature( - download::features::kAllowSavePackageScanning); - } + /*is_consumer=*/false) {} base::FilePath GetSaveDir() { return DownloadPrefs(browser()->profile()).DownloadPath(); @@ -1509,9 +1506,6 @@ base::FilePath GetTestFilePath() { return GetTestDataDirectory().AppendASCII("save_page/text.txt"); } - - protected: - base::test::ScopedFeatureList scoped_feature_list_; }; IN_PROC_BROWSER_TEST_F(SavePackageDeepScanningBrowserTest, Allowed) {
diff --git a/chrome/browser/share/android/java/src/org/chromium/chrome/browser/share/share_sheet/ShareSheetBottomSheetContent.java b/chrome/browser/share/android/java/src/org/chromium/chrome/browser/share/share_sheet/ShareSheetBottomSheetContent.java index 53c5797..3d74296ca 100644 --- a/chrome/browser/share/android/java/src/org/chromium/chrome/browser/share/share_sheet/ShareSheetBottomSheetContent.java +++ b/chrome/browser/share/android/java/src/org/chromium/chrome/browser/share/share_sheet/ShareSheetBottomSheetContent.java
@@ -19,7 +19,6 @@ import android.widget.AdapterView.OnItemClickListener; import android.widget.ImageView; import android.widget.ImageView.ScaleType; -import android.widget.LinearLayout; import android.widget.ScrollView; import android.widget.TextView; @@ -34,7 +33,6 @@ import org.chromium.base.ContextUtils; import org.chromium.base.metrics.RecordUserAction; import org.chromium.chrome.R; -import org.chromium.chrome.browser.flags.ChromeFeatureList; import org.chromium.chrome.browser.share.ChromeShareExtras.DetailedContentType; import org.chromium.chrome.browser.share.link_to_text.LinkToTextCoordinator.LinkGeneration; import org.chromium.chrome.browser.share.share_sheet.ShareSheetLinkToggleCoordinator.LinkToggleState; @@ -151,38 +149,6 @@ /*firstParty=*/false); thirdParty.addOnScrollListener( new ScrollEventReporter("SharingHubAndroid.ThirdPartyAppsScrolled")); - - if (shouldSwapFirstAndThirdPartyRows()) { - swapFirstAndThirdPartyRows(); - } - } - - boolean shouldSwapFirstAndThirdPartyRows() { - return ChromeFeatureList.isEnabled(ChromeFeatureList.SWAP_ANDROID_SHARE_HUB_ROWS) - || ChromeFeatureList.isEnabled(ChromeFeatureList.UPCOMING_SHARING_FEATURES); - } - - void swapFirstAndThirdPartyRows() { - View firstPartyRow = getContentView().findViewById(R.id.share_sheet_chrome_apps); - View thirdPartyRow = getContentView().findViewById(R.id.share_sheet_other_apps); - - LinearLayout layout = getContentView().findViewById(R.id.share_sheet_layout); - assert firstPartyRow.getParent() == layout; - assert thirdPartyRow.getParent() == layout; - - int firstPartyIndex = layout.indexOfChild(firstPartyRow); - int thirdPartyIndex = layout.indexOfChild(thirdPartyRow); - - if (thirdPartyIndex > firstPartyIndex) { - // If the rows are already swapped, we're updating an existing sheet; - // don't swap them again. - return; - } - - layout.removeViewAt(firstPartyIndex); - layout.removeViewAt(thirdPartyIndex); - layout.addView(firstPartyRow, thirdPartyIndex); - layout.addView(thirdPartyRow, firstPartyIndex); } void createFirstPartyRecyclerViews(List<PropertyModel> firstPartyModels) {
diff --git a/chrome/browser/share/share_features.cc b/chrome/browser/share/share_features.cc index d0f1f2ba..2addc1e 100644 --- a/chrome/browser/share/share_features.cc +++ b/chrome/browser/share/share_features.cc
@@ -10,8 +10,6 @@ "PersistShareHubOnAppSwitch", base::FEATURE_DISABLED_BY_DEFAULT}; const base::Feature kSharingDesktopScreenshotsEdit{ "SharingDesktopScreenshotsEdit", base::FEATURE_DISABLED_BY_DEFAULT}; -const base::Feature kSwapAndroidShareHubRows{"SwapAndroidShareHubRows", - base::FEATURE_DISABLED_BY_DEFAULT}; const base::Feature kUpcomingSharingFeatures{"UpcomingSharingFeatures", base::FEATURE_DISABLED_BY_DEFAULT};
diff --git a/chrome/browser/share/share_features.h b/chrome/browser/share/share_features.h index 614f978e..e02fe00 100644 --- a/chrome/browser/share/share_features.h +++ b/chrome/browser/share/share_features.h
@@ -11,7 +11,6 @@ extern const base::Feature kPersistShareHubOnAppSwitch; extern const base::Feature kSharingDesktopScreenshotsEdit; -extern const base::Feature kSwapAndroidShareHubRows; extern const base::Feature kUpcomingSharingFeatures; bool AreUpcomingSharingFeaturesEnabled();
diff --git a/chrome/browser/tab/java/src/org/chromium/chrome/browser/tab/state/ShoppingPersistedTabData.java b/chrome/browser/tab/java/src/org/chromium/chrome/browser/tab/state/ShoppingPersistedTabData.java index a3b1f03..0e886c5 100644 --- a/chrome/browser/tab/java/src/org/chromium/chrome/browser/tab/state/ShoppingPersistedTabData.java +++ b/chrome/browser/tab/java/src/org/chromium/chrome/browser/tab/state/ShoppingPersistedTabData.java
@@ -441,6 +441,10 @@ * - Uninitialized Tab */ public static void from(Tab tab, Callback<ShoppingPersistedTabData> callback) { + if (tab == null || tab.isDestroyed()) { + PostTask.runOrPostTask(UiThreadTaskTraits.DEFAULT, () -> { callback.onResult(null); }); + return; + } if (sDelayedInitFinished) { fromWithoutDelayedInit(tab, callback); } else {
diff --git a/chrome/browser/ui/android/omnibox/BUILD.gn b/chrome/browser/ui/android/omnibox/BUILD.gn index c540569..bb7d354 100644 --- a/chrome/browser/ui/android/omnibox/BUILD.gn +++ b/chrome/browser/ui/android/omnibox/BUILD.gn
@@ -187,6 +187,7 @@ "//components/search_engines/android:java", "//components/security_state/core:security_state_enums_java", "//components/signin/public/android:java", + "//components/ukm/android:java", "//components/user_prefs/android:java", "//content/public/android:content_java", "//third_party/android_deps:android_support_v7_appcompat_java",
diff --git a/chrome/browser/ui/android/omnibox/DEPS b/chrome/browser/ui/android/omnibox/DEPS index 16e50a3..cda56e6 100644 --- a/chrome/browser/ui/android/omnibox/DEPS +++ b/chrome/browser/ui/android/omnibox/DEPS
@@ -13,6 +13,7 @@ "+components/page_info/android/java/src/org/chromium/components/page_info", "+components/search_engines/android", "+components/signin/public/android", + "+components/ukm/android", "+content/public/android", "+url/android", ]
diff --git a/chrome/browser/ui/android/omnibox/java/src/org/chromium/chrome/browser/omnibox/suggestions/editurl/EditUrlSuggestionProcessor.java b/chrome/browser/ui/android/omnibox/java/src/org/chromium/chrome/browser/omnibox/suggestions/editurl/EditUrlSuggestionProcessor.java index df3710e..7e273415 100644 --- a/chrome/browser/ui/android/omnibox/java/src/org/chromium/chrome/browser/omnibox/suggestions/editurl/EditUrlSuggestionProcessor.java +++ b/chrome/browser/ui/android/omnibox/java/src/org/chromium/chrome/browser/omnibox/suggestions/editurl/EditUrlSuggestionProcessor.java
@@ -25,6 +25,7 @@ import org.chromium.chrome.browser.tab.Tab; import org.chromium.components.favicon.LargeIconBridge; import org.chromium.components.omnibox.AutocompleteMatch; +import org.chromium.components.ukm.UkmRecorder; import org.chromium.ui.base.Clipboard; import org.chromium.ui.modelutil.PropertyModel; @@ -162,6 +163,12 @@ /** Invoked when user interacts with Share action button. */ private void onShareLink() { RecordUserAction.record("Omnibox.EditUrlSuggestion.Share"); + Tab tab = mTabSupplier.get(); + if (tab != null && tab.getWebContents() != null) { + new UkmRecorder.Bridge().recordEventWithBooleanMetric( + mTabSupplier.get().getWebContents(), "Omnibox.EditUrlSuggestion.Share", + "HasOccurred"); + } mUrlBarDelegate.clearOmniboxFocus(); // TODO(mdjones): This should only share the displayed URL instead of the background tab. mShareDelegateSupplier.get().share(mTabSupplier.get(), false, ShareOrigin.EDIT_URL);
diff --git a/chrome/browser/ui/android/strings/android_chrome_strings.grd b/chrome/browser/ui/android/strings/android_chrome_strings.grd index b6c5e4b..35b9954c 100644 --- a/chrome/browser/ui/android/strings/android_chrome_strings.grd +++ b/chrome/browser/ui/android/strings/android_chrome_strings.grd
@@ -204,9 +204,6 @@ <!-- NOTE: Generic strings used across multiple features belong in //components/browser_ui/strings/android. --> <!-- Main Preferences --> - <message name="IDS_SETTINGS" desc="Title for Chrome's Settings."> - Settings - </message> <message name="IDS_PREFS_SECTION_BASICS" desc='Title of "Basics" section of preferences. [CHAR_LIMIT=32]'> Basics </message> @@ -5140,10 +5137,18 @@ Creating GIF </message> + <message name="IDS_LIGHTWEIGHT_REACTIONS_REACTION_MOVED_ANNOUNCEMENT" is_accessibility_with_no_ui="true" desc="The accessibility text to read when a reaction is moved."> + Reaction moved + </message> + <message name="IDS_LIGHTWEIGHT_REACTIONS_TOOLBAR_ANNOUNCEMENT" is_accessibility_with_no_ui="true" desc="The accessibility text to read when the lightweight reactions toolbar is selected. The user can then select a reaction from the toolbar to place on the screen."> Choose an emotion </message> + <message name="IDS_LIGHTWEIGHT_REACTIONS_REACTION_CHANGED_ANNOUNCEMENT" is_accessibility_with_no_ui="true" desc="The accessibility text to read when a reaction is selected from the toolbar and the active reaction is changed."> + Reaction changed + </message> + <message name="IDS_LIGHTWEIGHT_REACTIONS_RESIZE_AND_ROTATE_BUTTON" is_accessibility_with_no_ui="true" desc="The accessibility text to read when the resize and rotate editing tool is selected. The user can then resize and rotate the reaction on the scene."> Resize and rotate </message>
diff --git a/chrome/browser/ui/android/toolbar/java/res/layout/start_top_toolbar.xml b/chrome/browser/ui/android/toolbar/java/res/layout/start_top_toolbar.xml index ff887069..0ea3aa1 100644 --- a/chrome/browser/ui/android/toolbar/java/res/layout/start_top_toolbar.xml +++ b/chrome/browser/ui/android/toolbar/java/res/layout/start_top_toolbar.xml
@@ -20,6 +20,9 @@ android:contentDescription="@string/accessibility_toolbar_btn_home" android:src="@drawable/btn_toolbar_home" android:visibility="gone" + app:menuMaxWidth="@dimen/home_button_list_menu_width" + app:menuPositionedAtEnd="false" + app:menuVerticalOverlapAnchor="false" app:tint="@color/default_icon_color_tint_list" /> <ViewStub
diff --git a/chrome/browser/ui/android/toolbar/java/res/layout/toolbar_tablet.xml b/chrome/browser/ui/android/toolbar/java/res/layout/toolbar_tablet.xml index 82d675d..58bebd0 100644 --- a/chrome/browser/ui/android/toolbar/java/res/layout/toolbar_tablet.xml +++ b/chrome/browser/ui/android/toolbar/java/res/layout/toolbar_tablet.xml
@@ -28,6 +28,9 @@ android:src="@drawable/btn_toolbar_home" android:contentDescription="@string/accessibility_toolbar_btn_home" android:visibility="gone" + app:menuMaxWidth="@dimen/home_button_list_menu_width" + app:menuPositionedAtEnd="false" + app:menuVerticalOverlapAnchor="false" app:tint="@color/default_icon_color_tint_list" /> <org.chromium.ui.widget.ChromeImageButton
diff --git a/chrome/browser/ui/app_list/DEPS b/chrome/browser/ui/app_list/DEPS index 05680e7..1c60fc26 100644 --- a/chrome/browser/ui/app_list/DEPS +++ b/chrome/browser/ui/app_list/DEPS
@@ -15,6 +15,7 @@ ], "app_list_sort_browsertest\.cc": [ + "+ash/app_list/app_list_model_provider.h", "+ash/app_list/views/app_list_item_view.h", "+ash/app_list/views/app_list_menu_model_adapter.h", "+ash/app_list/views/apps_grid_context_menu.h",
diff --git a/chrome/browser/ui/app_list/app_list_sort_browsertest.cc b/chrome/browser/ui/app_list/app_list_sort_browsertest.cc index 30d7d19a..3aca17e 100644 --- a/chrome/browser/ui/app_list/app_list_sort_browsertest.cc +++ b/chrome/browser/ui/app_list/app_list_sort_browsertest.cc
@@ -2,12 +2,14 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +#include "ash/app_list/app_list_model_provider.h" #include "ash/app_list/views/app_list_item_view.h" #include "ash/app_list/views/app_list_menu_model_adapter.h" #include "ash/app_list/views/apps_grid_context_menu.h" #include "ash/app_list/views/apps_grid_view.h" #include "ash/constants/ash_features.h" #include "ash/public/cpp/accelerators.h" +#include "ash/public/cpp/app_list/app_list_model_delegate.h" #include "ash/public/cpp/test/app_list_test_api.h" #include "ash/public/cpp/test/shell_test_api.h" #include "ash/shell.h" @@ -97,13 +99,37 @@ kAppListFolderItemMenu }; + // Finds an folder item view in the provided apps grid. + ash::AppListItemView* FindFolderItemView(ash::AppsGridView* apps_grid_view) { + auto* model = apps_grid_view->view_model(); + for (int index = 0; index < model->view_size(); ++index) { + ash::AppListItemView* current_view = model->view_at(index); + if (current_view->is_folder()) + return current_view; + } + + return nullptr; + } + + // Finds a non-folder item view in the provided apps grid. + ash::AppListItemView* FindNonFolderItemView( + ash::AppsGridView* apps_grid_view) { + auto* model = apps_grid_view->view_model(); + for (int index = 0; index < model->view_size(); ++index) { + ash::AppListItemView* current_view = model->view_at(index); + if (!current_view->is_folder()) + return current_view; + } + + return nullptr; + } + // Shows the specified root menu that contains sorting menu options. Returns // the root menu after showing. - views::MenuItemView* ShowRootMenuAndReturn(MenuType menu_type) { + views::MenuItemView* ShowRootMenuAndReturn(ash::AppsGridView* apps_grid_view, + MenuType menu_type) { views::MenuItemView* root_menu = nullptr; - ash::AppsGridView* apps_grid_view = - app_list_test_api_.GetTopLevelAppsGridView(); EXPECT_GT(apps_grid_view->view_model()->view_size(), 0); switch (menu_type) { @@ -116,17 +142,11 @@ break; case MenuType::kAppListNonFolderItemMenu: case MenuType::kAppListFolderItemMenu: - ash::AppListItemView* item_view = nullptr; - auto* model = apps_grid_view->view_model(); const bool is_folder_item = (menu_type == MenuType::kAppListFolderItemMenu); - for (int index = 0; index < model->view_size(); ++index) { - ash::AppListItemView* current_view = model->view_at(index); - if (current_view->is_folder() == is_folder_item) { - item_view = current_view; - break; - } - } + ash::AppListItemView* item_view = + is_folder_item ? FindFolderItemView(apps_grid_view) + : FindNonFolderItemView(apps_grid_view); EXPECT_TRUE(item_view); event_generator_->MoveMouseTo( item_view->GetBoundsInScreen().CenterPoint()); @@ -193,21 +213,30 @@ kFadeInAborted, }; - // Reorders the app list items through the specified context menu indicated by - // `menu_type`. `target_status` is the reorder animation's target status. void ReorderByMouseClickAtContextMenu(ash::AppListSortOrder order, MenuType menu_type, AnimationTargetStatus target_status) { + ReorderByMouseClickAtContextMenuInAppsGrid( + app_list_test_api_.GetTopLevelAppsGridView(), order, menu_type, + target_status); + } + + // Reorders the app list items through the specified context menu indicated by + // `menu_type`. `target_status` is the reorder animation's target status. + void ReorderByMouseClickAtContextMenuInAppsGrid( + ash::AppsGridView* apps_grid_view, + ash::AppListSortOrder order, + MenuType menu_type, + AnimationTargetStatus target_status) { // Ensure that the apps grid layout is refreshed before showing the // context menu. - app_list_test_api_.GetTopLevelAppsGridView() - ->GetWidget() - ->LayoutRootViewIfNecessary(); + apps_grid_view->GetWidget()->LayoutRootViewIfNecessary(); // Custom order is not a menu option. ASSERT_NE(order, ash::AppListSortOrder::kCustom); - views::MenuItemView* root_menu = ShowRootMenuAndReturn(menu_type); + views::MenuItemView* root_menu = + ShowRootMenuAndReturn(apps_grid_view, menu_type); // Get the "Name" or "Color" option. views::MenuItemView* reorder_option = nullptr; @@ -667,6 +696,170 @@ std::vector<std::string>({app2_id_, app3_id_, app1_id_})); } +IN_PROC_BROWSER_TEST_F(AppListSortBrowserTest, + SortUsingContextMenuOnFolderChildViewClamshell) { + ash::ShellTestApi().SetTabletModeEnabledForTest(false); + ash::AcceleratorController::Get()->PerformActionIfEnabled( + ash::TOGGLE_APP_LIST_FULLSCREEN, {}); + app_list_test_api_.WaitForBubbleWindow(/*wait_for_opening_animation=*/true); + + // Create an app list folder. + app_list_test_api_.CreateFolderWithApps({app1_id_, app2_id_}); + ash::AppsGridView* top_level_grid = + app_list_test_api_.GetTopLevelAppsGridView(); + top_level_grid->Layout(); + + // Click on the folder to open it. + base::RunLoop run_loop; + app_list_test_api_.SetFolderViewAnimationCallback(run_loop.QuitClosure()); + + ash::AppListItemView* folder_item_view = FindFolderItemView(top_level_grid); + ASSERT_TRUE(folder_item_view); + event_generator_->MoveMouseTo( + folder_item_view->GetBoundsInScreen().CenterPoint()); + event_generator_->ClickLeftButton(); + + run_loop.Run(); + + ash::AppsGridView* folder_grid = app_list_test_api_.GetFolderAppsGridView(); + EXPECT_TRUE(folder_grid->IsDrawn()); + ReorderByMouseClickAtContextMenuInAppsGrid( + folder_grid, ash::AppListSortOrder::kNameAlphabetical, + MenuType::kAppListNonFolderItemMenu, AnimationTargetStatus::kCompleted); + EXPECT_EQ(GetAppIdsInOrdinalOrder(), + std::vector<std::string>({app1_id_, app2_id_, app3_id_})); + EXPECT_FALSE(app_list_test_api_.GetFolderAppsGridView()->IsDrawn()); +} + +IN_PROC_BROWSER_TEST_F(AppListSortBrowserTest, + FolderNotClosedIfTemporarySortIsCommittedClamshell) { + ash::ShellTestApi().SetTabletModeEnabledForTest(false); + ash::AcceleratorController::Get()->PerformActionIfEnabled( + ash::TOGGLE_APP_LIST_FULLSCREEN, {}); + app_list_test_api_.WaitForBubbleWindow(/*wait_for_opening_animation=*/true); + + // Create an app list folder. + const std::string folder_id = + app_list_test_api_.CreateFolderWithApps({app1_id_, app2_id_}); + ash::AppsGridView* top_level_grid = + app_list_test_api_.GetTopLevelAppsGridView(); + top_level_grid->Layout(); + + // Order apps grid to transition to temporary sort order. + ReorderByMouseClickAtContextMenu(ash::AppListSortOrder::kNameAlphabetical, + MenuType::kAppListFolderItemMenu, + AnimationTargetStatus::kCompleted); + EXPECT_EQ(GetAppIdsInOrdinalOrder(), + std::vector<std::string>({app1_id_, app2_id_, app3_id_})); + + // Click on the folder item to open it. + base::RunLoop run_loop; + app_list_test_api_.SetFolderViewAnimationCallback(run_loop.QuitClosure()); + + ash::AppListItemView* folder_item_view = FindFolderItemView(top_level_grid); + ASSERT_TRUE(folder_item_view); + event_generator_->MoveMouseTo( + folder_item_view->GetBoundsInScreen().CenterPoint()); + event_generator_->ClickLeftButton(); + + run_loop.Run(); + + ash::AppsGridView* folder_grid = app_list_test_api_.GetFolderAppsGridView(); + EXPECT_TRUE(folder_grid->IsDrawn()); + EXPECT_TRUE(app_list_test_api_.GetBubbleReorderUndoToastVisibility()); + + // Rename folder to commit the sort order - verify that the folder remained + // open. + ash::AppListModelProvider::Get()->model()->delegate()->RequestFolderRename( + folder_id, "Test folder"); + EXPECT_EQ(GetAppIdsInOrdinalOrder(), + std::vector<std::string>({app1_id_, app2_id_, app3_id_})); + EXPECT_TRUE(app_list_test_api_.GetFolderAppsGridView()->IsDrawn()); + EXPECT_FALSE(app_list_test_api_.GetBubbleReorderUndoToastVisibility()); +} + +IN_PROC_BROWSER_TEST_F(AppListSortBrowserTest, + SortUsingContextMenuOnFolderChildViewTablet) { + ash::ShellTestApi().SetTabletModeEnabledForTest(true); + ash::AcceleratorController::Get()->PerformActionIfEnabled( + ash::TOGGLE_APP_LIST_FULLSCREEN, {}); + app_list_test_api_.WaitForAppListShowAnimation(/*is_bubble_window=*/false); + + // Create an app list folder. + app_list_test_api_.CreateFolderWithApps({app1_id_, app2_id_}); + ash::AppsGridView* top_level_grid = + app_list_test_api_.GetTopLevelAppsGridView(); + top_level_grid->Layout(); + + // Click on the folder to open it. + base::RunLoop run_loop; + app_list_test_api_.SetFolderViewAnimationCallback(run_loop.QuitClosure()); + + ash::AppListItemView* folder_item_view = FindFolderItemView(top_level_grid); + ASSERT_TRUE(folder_item_view); + event_generator_->MoveMouseTo( + folder_item_view->GetBoundsInScreen().CenterPoint()); + event_generator_->ClickLeftButton(); + + run_loop.Run(); + + ash::AppsGridView* folder_grid = app_list_test_api_.GetFolderAppsGridView(); + EXPECT_TRUE(folder_grid->IsDrawn()); + ReorderByMouseClickAtContextMenuInAppsGrid( + folder_grid, ash::AppListSortOrder::kNameAlphabetical, + MenuType::kAppListNonFolderItemMenu, AnimationTargetStatus::kCompleted); + EXPECT_EQ(GetAppIdsInOrdinalOrder(), + std::vector<std::string>({app1_id_, app2_id_, app3_id_})); + EXPECT_FALSE(app_list_test_api_.GetFolderAppsGridView()->IsDrawn()); +} + +IN_PROC_BROWSER_TEST_F(AppListSortBrowserTest, + FolderNotClosedIfTemporarySortIsCommittedTablet) { + ash::ShellTestApi().SetTabletModeEnabledForTest(true); + ash::AcceleratorController::Get()->PerformActionIfEnabled( + ash::TOGGLE_APP_LIST_FULLSCREEN, {}); + app_list_test_api_.WaitForAppListShowAnimation(/*is_bubble_window=*/false); + + // Create an app list folder. + const std::string folder_id = + app_list_test_api_.CreateFolderWithApps({app1_id_, app2_id_}); + ash::AppsGridView* top_level_grid = + app_list_test_api_.GetTopLevelAppsGridView(); + top_level_grid->Layout(); + + // Order apps grid to transition to temporary sort order. + ReorderByMouseClickAtContextMenu(ash::AppListSortOrder::kNameAlphabetical, + MenuType::kAppListFolderItemMenu, + AnimationTargetStatus::kCompleted); + EXPECT_EQ(GetAppIdsInOrdinalOrder(), + std::vector<std::string>({app1_id_, app2_id_, app3_id_})); + + // Click on the folder item to open it. + base::RunLoop run_loop; + app_list_test_api_.SetFolderViewAnimationCallback(run_loop.QuitClosure()); + + ash::AppListItemView* folder_item_view = FindFolderItemView(top_level_grid); + ASSERT_TRUE(folder_item_view); + event_generator_->MoveMouseTo( + folder_item_view->GetBoundsInScreen().CenterPoint()); + event_generator_->ClickLeftButton(); + + run_loop.Run(); + + ash::AppsGridView* folder_grid = app_list_test_api_.GetFolderAppsGridView(); + EXPECT_TRUE(folder_grid->IsDrawn()); + EXPECT_TRUE(app_list_test_api_.GetFullscreenReorderUndoToastVisibility()); + + // Rename folder to commit the sort order - verify that the folder remained + // open. + ash::AppListModelProvider::Get()->model()->delegate()->RequestFolderRename( + folder_id, "Test folder"); + EXPECT_EQ(GetAppIdsInOrdinalOrder(), + std::vector<std::string>({app1_id_, app2_id_, app3_id_})); + EXPECT_TRUE(app_list_test_api_.GetFolderAppsGridView()->IsDrawn()); + EXPECT_FALSE(app_list_test_api_.GetFullscreenReorderUndoToastVisibility()); +} + // Verify that starting a new reorder before the old animation completes works // as expected. IN_PROC_BROWSER_TEST_F(
diff --git a/chrome/browser/ui/ash/clipboard_history_browsertest.cc b/chrome/browser/ui/ash/clipboard_history_browsertest.cc index 3a34996..bbec053c 100644 --- a/chrome/browser/ui/ash/clipboard_history_browsertest.cc +++ b/chrome/browser/ui/ash/clipboard_history_browsertest.cc
@@ -29,6 +29,7 @@ #include "chrome/browser/ui/ash/clipboard_image_model_request.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" +#include "chrome/test/base/in_process_browser_test.h" #include "chrome/test/base/ui_test_utils.h" #include "chromeos/crosapi/mojom/clipboard_history.mojom.h" #include "components/user_manager/user_manager.h" @@ -273,19 +274,16 @@ } // namespace -// Verify clipboard history's features in the multiprofile environment. -class ClipboardHistoryWithMultiProfileBrowserTest - : public ash::LoginManagerTest { +class ClipboardHistoryBrowserTest : public ash::LoginManagerTest { public: - ClipboardHistoryWithMultiProfileBrowserTest() : LoginManagerTest() { - login_mixin_.AppendRegularUsers(2); + ClipboardHistoryBrowserTest() { + login_mixin_.AppendRegularUsers(1); account_id1_ = login_mixin_.users()[0].account_id; - account_id2_ = login_mixin_.users()[1].account_id; feature_list_.InitAndEnableFeature(chromeos::features::kClipboardHistory); } - ~ClipboardHistoryWithMultiProfileBrowserTest() override = default; + ~ClipboardHistoryBrowserTest() override = default; ui::test::EventGenerator* GetEventGenerator() { return event_generator_.get(); @@ -323,6 +321,8 @@ Release(key, modifiers); } + // TODO(crbug.com/1304484): Check whether this currently unused function + // should have been used or if it can be deleted. void WaitUntilItemDeletionCompletes() { auto* context_menu = GetContextMenu(); DCHECK(context_menu); @@ -331,13 +331,6 @@ run_loop.Run(); } - void PasteFromClipboardHistoryMenuAndWait() { - ASSERT_FALSE(GetClipboardHistoryController()->IsMenuShowing()); - ShowContextMenuViaAccelerator(/*wait_for_selection=*/true); - PressAndRelease(ui::VKEY_RETURN); - WaitForOperationConfirmed(); - } - void ShowContextMenuViaAccelerator(bool wait_for_selection) { PressAndRelease(ui::KeyboardCode::VKEY_V, ui::EF_COMMAND_DOWN); if (!wait_for_selection) @@ -353,9 +346,11 @@ return GetContextMenu()->GetMenuItemViewAtForTest(index); } + // TODO(crbug.com/1304484): Check whether this currently unused function + // should have been used or if it can be deleted. views::MenuItemView* GetMenuItemViewForTest(int index) { return const_cast<views::MenuItemView*>( - const_cast<const ClipboardHistoryWithMultiProfileBrowserTest*>(this) + const_cast<const ClipboardHistoryBrowserTest*>(this) ->GetMenuItemViewForIndex(index)); } @@ -370,7 +365,7 @@ ash::ClipboardHistoryItemView* GetHistoryItemViewForIndex(int index) { return const_cast<ash::ClipboardHistoryItemView*>( - const_cast<const ClipboardHistoryWithMultiProfileBrowserTest*>(this) + const_cast<const ClipboardHistoryBrowserTest*>(this) ->GetHistoryItemViewForIndex(index)); } @@ -400,10 +395,10 @@ ash::LoginManagerTest::SetUpOnMainThread(); event_generator_ = std::make_unique<ui::test::EventGenerator>( ash::Shell::GetPrimaryRootWindow()); + LoginUser(account_id1_); } AccountId account_id1_; - AccountId account_id2_; ash::LoginManagerMixin login_mixin_{&mixin_host_}; std::unique_ptr<ui::test::EventGenerator> event_generator_; @@ -411,67 +406,8 @@ base::test::ScopedFeatureList feature_list_; }; -// Verify that the clipboard data history is recorded as expected in the -// Multiuser environment. -IN_PROC_BROWSER_TEST_F(ClipboardHistoryWithMultiProfileBrowserTest, - VerifyClipboardHistoryAcrossMultiUser) { - LoginUser(account_id1_); - EXPECT_TRUE(GetClipboardItems().empty()); - - // Store text when the user1 is active. - const std::string copypaste_data1("user1_text1"); - SetClipboardText(copypaste_data1); - - { - const std::list<ash::ClipboardHistoryItem>& items = GetClipboardItems(); - EXPECT_EQ(1u, items.size()); - EXPECT_EQ(copypaste_data1, items.front().data().text()); - } - - // Log in as the user2. The clipboard history should be non-empty. - ash::UserAddingScreen::Get()->Start(); - AddUser(account_id2_); - EXPECT_FALSE(GetClipboardItems().empty()); - - // Store text when the user2 is active. - const std::string copypaste_data2("user2_text1"); - SetClipboardText(copypaste_data2); - - { - const std::list<ash::ClipboardHistoryItem>& items = GetClipboardItems(); - EXPECT_EQ(2u, items.size()); - EXPECT_EQ(copypaste_data2, items.front().data().text()); - } - - // Switch to the user1. - user_manager::UserManager::Get()->SwitchActiveUser(account_id1_); - - // Store text when the user1 is active. - const std::string copypaste_data3("user1_text2"); - SetClipboardText(copypaste_data3); - - { - const std::list<ash::ClipboardHistoryItem>& items = GetClipboardItems(); - EXPECT_EQ(3u, items.size()); - - // Note that items in |data| follow the time ordering. The most recent item - // is always the first one. - auto it = items.begin(); - EXPECT_EQ(copypaste_data3, it->data().text()); - - std::advance(it, 1u); - EXPECT_EQ(copypaste_data2, it->data().text()); - - std::advance(it, 1u); - EXPECT_EQ(copypaste_data1, it->data().text()); - } -} - // Verifies the history menu's ui interaction with the menu item selection. -IN_PROC_BROWSER_TEST_F(ClipboardHistoryWithMultiProfileBrowserTest, - VerifySelectionBehavior) { - LoginUser(account_id1_); - +IN_PROC_BROWSER_TEST_F(ClipboardHistoryBrowserTest, VerifySelectionBehavior) { SetClipboardText("A"); SetClipboardText("B"); SetClipboardText("C"); @@ -526,10 +462,8 @@ } // Verifies the selection traversal via the tab key. -IN_PROC_BROWSER_TEST_F(ClipboardHistoryWithMultiProfileBrowserTest, +IN_PROC_BROWSER_TEST_F(ClipboardHistoryBrowserTest, VerifyTabSelectionTraversal) { - LoginUser(account_id1_); - SetClipboardText("A"); SetClipboardText("B"); ShowContextMenuViaAccelerator(/*wait_for_selection=*/true); @@ -611,10 +545,8 @@ } // Verifies the tab traversal on the history menu with only one item. -IN_PROC_BROWSER_TEST_F(ClipboardHistoryWithMultiProfileBrowserTest, +IN_PROC_BROWSER_TEST_F(ClipboardHistoryBrowserTest, VerifyTabTraversalOnOneItemMenu) { - LoginUser(account_id1_); - SetClipboardText("A"); ShowContextMenuViaAccelerator(/*wait_for_selection=*/true); @@ -647,10 +579,8 @@ // Verifies that the history menu is anchored at the cursor's location when // not having any textfield. -IN_PROC_BROWSER_TEST_F(ClipboardHistoryWithMultiProfileBrowserTest, +IN_PROC_BROWSER_TEST_F(ClipboardHistoryBrowserTest, ShowHistoryMenuWhenNoTextfieldExists) { - LoginUser(account_id1_); - // Close the browser window to ensure that textfield does not exist. CloseAllBrowsers(); @@ -677,10 +607,7 @@ } // Verify the handling of the click cancel event. -IN_PROC_BROWSER_TEST_F(ClipboardHistoryWithMultiProfileBrowserTest, - HandleClickCancelEvent) { - LoginUser(account_id1_); - +IN_PROC_BROWSER_TEST_F(ClipboardHistoryBrowserTest, HandleClickCancelEvent) { // Write some things to the clipboard. SetClipboardText("A"); SetClipboardText("B"); @@ -710,10 +637,8 @@ } // Verifies item deletion through the mouse click at the delete button. -IN_PROC_BROWSER_TEST_F(ClipboardHistoryWithMultiProfileBrowserTest, +IN_PROC_BROWSER_TEST_F(ClipboardHistoryBrowserTest, DeleteItemByClickAtDeleteButton) { - LoginUser(account_id1_); - // Write some things to the clipboard. SetClipboardText("A"); SetClipboardText("B"); @@ -737,10 +662,8 @@ } // Verifies that the selected item should be deleted by the backspace key. -IN_PROC_BROWSER_TEST_F(ClipboardHistoryWithMultiProfileBrowserTest, - DeleteItemViaBackspaceKey) { +IN_PROC_BROWSER_TEST_F(ClipboardHistoryBrowserTest, DeleteItemViaBackspaceKey) { base::HistogramTester histogram_tester; - LoginUser(account_id1_); // Write some things to the clipboard. SetClipboardText("A"); @@ -778,10 +701,8 @@ EXPECT_FALSE(GetClipboardHistoryController()->IsMenuShowing()); } -IN_PROC_BROWSER_TEST_F(ClipboardHistoryWithMultiProfileBrowserTest, +IN_PROC_BROWSER_TEST_F(ClipboardHistoryBrowserTest, ShouldPasteHistoryAsPlainText) { - LoginUser(account_id1_); - // Increase delay interval before restoring the clipboard buffer following // a paste event as this test has exhibited flakiness due to the amount of // time it takes a paste event to reach the web contents under test. Remove @@ -901,10 +822,84 @@ ClipboardDataWaiter().WaitFor(&clipboard_data); } -class ClipboardHistoryBrowserTest : public InProcessBrowserTest { +// Verify clipboard history's features in the multiprofile environment. +class ClipboardHistoryMultiProfileBrowserTest + : public ClipboardHistoryBrowserTest { public: - ClipboardHistoryBrowserTest() = default; - ~ClipboardHistoryBrowserTest() override = default; + ClipboardHistoryMultiProfileBrowserTest() { + login_mixin_.AppendRegularUsers(1); + // Previous user was added in base class. + EXPECT_EQ(2U, login_mixin_.users().size()); + account_id2_ = login_mixin_.users()[1].account_id; + } + + ~ClipboardHistoryMultiProfileBrowserTest() override = default; + + protected: + AccountId account_id2_; +}; + +// Verify that the clipboard data history is recorded as expected in the +// Multiuser environment. +IN_PROC_BROWSER_TEST_F(ClipboardHistoryMultiProfileBrowserTest, + VerifyClipboardHistoryAcrossMultiUser) { + EXPECT_TRUE(GetClipboardItems().empty()); + + // Store text when the user1 is active. + const std::string copypaste_data1("user1_text1"); + SetClipboardText(copypaste_data1); + + { + const std::list<ash::ClipboardHistoryItem>& items = GetClipboardItems(); + EXPECT_EQ(1u, items.size()); + EXPECT_EQ(copypaste_data1, items.front().data().text()); + } + + // Log in as the user2. The clipboard history should be non-empty. + ash::UserAddingScreen::Get()->Start(); + AddUser(account_id2_); + EXPECT_FALSE(GetClipboardItems().empty()); + + // Store text when the user2 is active. + const std::string copypaste_data2("user2_text1"); + SetClipboardText(copypaste_data2); + + { + const std::list<ash::ClipboardHistoryItem>& items = GetClipboardItems(); + EXPECT_EQ(2u, items.size()); + EXPECT_EQ(copypaste_data2, items.front().data().text()); + } + + // Switch to the user1. + user_manager::UserManager::Get()->SwitchActiveUser(account_id1_); + + // Store text when the user1 is active. + const std::string copypaste_data3("user1_text2"); + SetClipboardText(copypaste_data3); + + { + const std::list<ash::ClipboardHistoryItem>& items = GetClipboardItems(); + EXPECT_EQ(3u, items.size()); + + // Note that items in |data| follow the time ordering. The most recent item + // is always the first one. + auto it = items.begin(); + EXPECT_EQ(copypaste_data3, it->data().text()); + + std::advance(it, 1u); + EXPECT_EQ(copypaste_data2, it->data().text()); + + std::advance(it, 1u); + EXPECT_EQ(copypaste_data1, it->data().text()); + } +} + +// TODO(crbug.com/1304484): Make this class inherit from +// `ClipboardHistoryBrowserTest` instead if possible. +class ClipboardHistoryWebContentsBrowserTest : public InProcessBrowserTest { + public: + ClipboardHistoryWebContentsBrowserTest() = default; + ~ClipboardHistoryWebContentsBrowserTest() override = default; // InProcessBrowserTest: void SetUpOnMainThread() override { @@ -922,7 +917,7 @@ // show in the clipboard history menu. Switching the auto resize mode is covered // in this test case. // Flaky: crbug/1224777 -IN_PROC_BROWSER_TEST_F(ClipboardHistoryBrowserTest, +IN_PROC_BROWSER_TEST_F(ClipboardHistoryWebContentsBrowserTest, DISABLED_VerifyHTMLRendering) { // Load the web page which contains images and text. ASSERT_TRUE(ui_test_utils::NavigateToURL( @@ -1016,17 +1011,16 @@ // to help verify the multipaste menu item's response to the gesture tap and // the mouse click. class ClipboardHistoryTextfieldBrowserTest - : public ClipboardHistoryWithMultiProfileBrowserTest { + : public ClipboardHistoryBrowserTest { public: ClipboardHistoryTextfieldBrowserTest() = default; ~ClipboardHistoryTextfieldBrowserTest() override = default; protected: - // ClipboardHistoryWithMultiProfileBrowserTest: + // ClipboardHistoryBrowserTest: void SetUpOnMainThread() override { - ClipboardHistoryWithMultiProfileBrowserTest::SetUpOnMainThread(); + ClipboardHistoryBrowserTest::SetUpOnMainThread(); - LoginUser(account_id1_); CloseAllBrowsers(); // Create a widget containing a single, focusable textfield. @@ -1046,6 +1040,13 @@ ASSERT_TRUE(textfield_->GetText().empty()); } + void PasteFromClipboardHistoryMenuAndWait() { + ASSERT_FALSE(GetClipboardHistoryController()->IsMenuShowing()); + ShowContextMenuViaAccelerator(/*wait_for_selection=*/true); + PressAndRelease(ui::VKEY_RETURN); + WaitForOperationConfirmed(); + } + std::unique_ptr<views::Widget> widget_; views::Textfield* textfield_ = nullptr; };
diff --git a/chrome/browser/ui/cocoa/handoff_active_url_observer.cc b/chrome/browser/ui/cocoa/handoff_active_url_observer.cc index ffb72e7..df4ebfe 100644 --- a/chrome/browser/ui/cocoa/handoff_active_url_observer.cc +++ b/chrome/browser/ui/cocoa/handoff_active_url_observer.cc
@@ -10,7 +10,7 @@ #include "chrome/browser/ui/browser_list.h" #include "chrome/browser/ui/cocoa/handoff_active_url_observer_delegate.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" -#include "content/public/browser/page.h" +#include "content/public/browser/navigation_handle.h" #include "content/public/browser/web_contents.h" HandoffActiveURLObserver::HandoffActiveURLObserver( @@ -52,7 +52,15 @@ delegate_->HandoffActiveURLChanged(selection.new_contents); } -void HandoffActiveURLObserver::PrimaryPageChanged(content::Page& page) { +void HandoffActiveURLObserver::DidFinishNavigation( + content::NavigationHandle* navigation_handle) { + // TODO(https://crbug.com/1218946): With MPArch there may be multiple main + // frames. This caller was converted automatically to the primary main frame + // to preserve its semantics. Follow up to confirm correctness. + if (!navigation_handle->IsInPrimaryMainFrame() || + !navigation_handle->HasCommitted()) + return; + delegate_->HandoffActiveURLChanged(web_contents()); }
diff --git a/chrome/browser/ui/cocoa/handoff_active_url_observer.h b/chrome/browser/ui/cocoa/handoff_active_url_observer.h index af19043..3247c17 100644 --- a/chrome/browser/ui/cocoa/handoff_active_url_observer.h +++ b/chrome/browser/ui/cocoa/handoff_active_url_observer.h
@@ -10,7 +10,6 @@ #include "content/public/browser/web_contents_observer.h" namespace content { -class Page; class WebContents; } @@ -43,7 +42,8 @@ const TabStripSelectionChange& selection) override; // content::WebContentsObserver - void PrimaryPageChanged(content::Page& page) override; + void DidFinishNavigation( + content::NavigationHandle* navigation_handle) override; // Updates the active browser. void SetActiveBrowser(Browser* active_browser);
diff --git a/chrome/browser/ui/pdf/chrome_pdf_web_contents_helper_client.cc b/chrome/browser/ui/pdf/chrome_pdf_web_contents_helper_client.cc index 8e7c9c9..118c57c2 100644 --- a/chrome/browser/ui/pdf/chrome_pdf_web_contents_helper_client.cc +++ b/chrome/browser/ui/pdf/chrome_pdf_web_contents_helper_client.cc
@@ -9,22 +9,9 @@ #include "chrome/browser/ui/tab_contents/core_tab_helper.h" #include "chrome/common/content_restriction.h" #include "extensions/browser/guest_view/mime_handler_view/mime_handler_view_guest.h" -#include "ppapi/c/private/ppb_pdf.h" namespace { -// For the UpdateContentRestrictions() call below, ensure the enum values in -// chrome/common/content_restriction.h and ppapi/c/private/ppb_pdf.h match. -#define STATIC_ASSERT_ENUM(a, b) \ - static_assert(static_cast<int>(a) == static_cast<int>(b), \ - "mismatching enums: " #a) - -STATIC_ASSERT_ENUM(CONTENT_RESTRICTION_COPY, PP_CONTENT_RESTRICTION_COPY); -STATIC_ASSERT_ENUM(CONTENT_RESTRICTION_CUT, PP_CONTENT_RESTRICTION_CUT); -STATIC_ASSERT_ENUM(CONTENT_RESTRICTION_PASTE, PP_CONTENT_RESTRICTION_PASTE); -STATIC_ASSERT_ENUM(CONTENT_RESTRICTION_PRINT, PP_CONTENT_RESTRICTION_PRINT); -STATIC_ASSERT_ENUM(CONTENT_RESTRICTION_SAVE, PP_CONTENT_RESTRICTION_SAVE); - content::WebContents* GetWebContentsToUse( content::WebContents* web_contents) { // If we're viewing the PDF in a MimeHandlerViewGuest, use its embedder
diff --git a/chrome/browser/ui/views/bookmarks/bookmark_bar_view_unittest.cc b/chrome/browser/ui/views/bookmarks/bookmark_bar_view_unittest.cc index faf3c431..ff47d6aa 100644 --- a/chrome/browser/ui/views/bookmarks/bookmark_bar_view_unittest.cc +++ b/chrome/browser/ui/views/bookmarks/bookmark_bar_view_unittest.cc
@@ -23,7 +23,6 @@ #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/views/bookmarks/bookmark_bar_view_test_helper.h" #include "chrome/browser/ui/views/native_widget_factory.h" -#include "chrome/browser/ui/views/read_later/read_later_button.h" #include "chrome/common/url_constants.h" #include "chrome/test/base/test_browser_window.h" #include "chrome/test/base/testing_profile.h" @@ -32,7 +31,6 @@ #include "components/bookmarks/common/bookmark_pref_names.h" #include "components/bookmarks/test/bookmark_test_helpers.h" #include "components/prefs/pref_service.h" -#include "components/reading_list/features/reading_list_switches.h" #include "components/search_engines/search_terms_data.h" #include "components/search_engines/template_url_service.h" #include "components/search_engines/template_url_service_client.h" @@ -51,8 +49,6 @@ class BookmarkBarViewBaseTest : public ChromeViewsTestBase { public: BookmarkBarViewBaseTest() { - feature_list_.InitAndEnableFeature(reading_list::switches::kReadLater); - TestingProfile::Builder profile_builder; profile_builder.AddTestingFactory( TemplateURLServiceFactory::GetInstance(), @@ -236,25 +232,6 @@ EXPECT_FALSE(test_helper_->apps_page_shortcut()->GetVisible()); } -// Verify that in instant extended mode the visibility of the reading list -// button properly follows the pref value. -TEST_F(BookmarkBarViewTest, ReadingListVisibility) { - browser()->profile()->GetPrefs()->SetBoolean( - bookmarks::prefs::kShowReadingListInBookmarkBar, false); - EXPECT_FALSE(bookmark_bar_view()->read_later_button()->GetVisible()); - - // Try to make the Apps shortcut visible. Its visibility depends on whether - // the app launcher is enabled. - browser()->profile()->GetPrefs()->SetBoolean( - bookmarks::prefs::kShowReadingListInBookmarkBar, true); - EXPECT_TRUE(bookmark_bar_view()->read_later_button()->GetVisible()); - - // Make sure we can also properly transition from true to false. - browser()->profile()->GetPrefs()->SetBoolean( - bookmarks::prefs::kShowReadingListInBookmarkBar, false); - EXPECT_FALSE(bookmark_bar_view()->read_later_button()->GetVisible()); -} - // Various assertions around visibility of the overflow_button. TEST_F(BookmarkBarViewTest, OverflowVisibility) { EXPECT_FALSE(test_helper_->overflow_button()->GetVisible());
diff --git a/chrome/browser/ui/views/extensions/extensions_tabbed_menu_view.cc b/chrome/browser/ui/views/extensions/extensions_tabbed_menu_view.cc index 6ae7857..3bad726 100644 --- a/chrome/browser/ui/views/extensions/extensions_tabbed_menu_view.cc +++ b/chrome/browser/ui/views/extensions/extensions_tabbed_menu_view.cc
@@ -13,6 +13,7 @@ #include "base/i18n/case_conversion.h" #include "base/notreached.h" #include "base/strings/utf_string_conversions.h" +#include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/chrome_pages.h" #include "chrome/browser/ui/extensions/extension_action_view_controller.h" @@ -49,6 +50,8 @@ namespace { +using UserSiteSetting = extensions::PermissionsManager::UserSiteSetting; + // Site access settings group id for the radio buttons. constexpr int kGroupId = 1; @@ -536,14 +539,16 @@ .Build(); const auto create_radio_button_builder = - [current_site](int label_id, bool replace_current_site) { - auto label = replace_current_site + [this, current_site](UserSiteSetting site_settings, int label_id) { + auto label = ((site_settings == UserSiteSetting::kGrantAllExtensions) || + (site_settings == UserSiteSetting::kBlockAllExtensions)) ? l10n_util::GetStringFUTF16(label_id, current_site) : l10n_util::GetStringUTF16(label_id); - // TODO(crbug.com/1263310): Add callback. Differentiate between types - // with a SiteSettings enum. return views::Builder<views::RadioButton>( - std::make_unique<views::RadioButton>(label, kGroupId)); + std::make_unique<views::RadioButton>(label, kGroupId)) + .SetCallback(base::BindRepeating( + &ExtensionsTabbedMenuView::OnSiteSettingSelected, + base::Unretained(this), site_settings)); }; auto site_access_footer = @@ -565,30 +570,20 @@ .SetVisible(show_site_settings_) .AddChildren( create_radio_button_builder( - IDS_EXTENSIONS_MENU_SITE_ACCESS_TAB_USER_SETTINGS_ALLOW_ALL_TEXT, - true), + UserSiteSetting::kGrantAllExtensions, + IDS_EXTENSIONS_MENU_SITE_ACCESS_TAB_USER_SETTINGS_ALLOW_ALL_TEXT), create_radio_button_builder( - IDS_EXTENSIONS_MENU_SITE_ACCESS_TAB_USER_SETTINGS_BLOCK_ALL_TEXT, - true), + UserSiteSetting::kBlockAllExtensions, + IDS_EXTENSIONS_MENU_SITE_ACCESS_TAB_USER_SETTINGS_BLOCK_ALL_TEXT), create_radio_button_builder( - IDS_EXTENSIONS_MENU_SITE_ACCESS_TAB_USER_SETTINGS_CUSTOMIZE_EACH_TEXT, - false))) + UserSiteSetting::kCustomizeByExtension, + IDS_EXTENSIONS_MENU_SITE_ACCESS_TAB_USER_SETTINGS_CUSTOMIZE_EACH_TEXT))) .Build(); CreateTab(tabbed_pane_, 0, IDS_EXTENSIONS_MENU_SITE_ACCESS_TAB_TITLE, std::move(site_access_content), std::move(site_access_footer)); } -void ExtensionsTabbedMenuView::OnSiteSettingsButtonPressed() { - show_site_settings_ = !show_site_settings_; - - site_settings_button_->SetIcon(show_site_settings_); - site_settings_->SetVisible(show_site_settings_); - - // Resize the menu according to the site settings visibility. - SizeToContents(); -} - void ExtensionsTabbedMenuView::CreateExtensionsTab() { auto installed_items = views::Builder<views::BoxLayoutView>() @@ -695,6 +690,9 @@ move_items_between_sections_if_necessary(&has_access_); } +// TODO(crbug.com/1263310): Add user permissions changes listener to update the +// site access content views. + void ExtensionsTabbedMenuView::UpdateSiteAccessSectionsVisibility() { // Site access tab should only display content related to the current site. // Therefore, hide all the site access content views if this method is called @@ -766,6 +764,37 @@ return menu_items; } +void ExtensionsTabbedMenuView::OnSiteSettingsButtonPressed() { + show_site_settings_ = !show_site_settings_; + + site_settings_button_->SetIcon(show_site_settings_); + site_settings_->SetVisible(show_site_settings_); + + // Resize the menu according to the site settings visibility. + SizeToContents(); +} + +void ExtensionsTabbedMenuView::OnSiteSettingSelected( + extensions::PermissionsManager::UserSiteSetting site_settings) { + auto current_origin = url::Origin::Create(browser_->tab_strip_model() + ->GetActiveWebContents() + ->GetLastCommittedURL()); + auto* permissions_manager = + extensions::PermissionsManager::Get(browser_->profile()); + switch (site_settings) { + case UserSiteSetting::kGrantAllExtensions: + permissions_manager->AddUserPermittedSite(current_origin); + break; + case UserSiteSetting::kBlockAllExtensions: + permissions_manager->AddUserRestrictedSite(current_origin); + break; + case UserSiteSetting::kCustomizeByExtension: + permissions_manager->RemoveUserPermittedSite(current_origin); + permissions_manager->RemoveUserRestrictedSite(current_origin); + break; + } +} + void ExtensionsTabbedMenuView::ConsistencyCheck() { #if DCHECK_IS_ON() const base::flat_set<std::string>& action_ids = toolbar_model_->action_ids();
diff --git a/chrome/browser/ui/views/extensions/extensions_tabbed_menu_view.h b/chrome/browser/ui/views/extensions/extensions_tabbed_menu_view.h index d2965fa..b5388615 100644 --- a/chrome/browser/ui/views/extensions/extensions_tabbed_menu_view.h +++ b/chrome/browser/ui/views/extensions/extensions_tabbed_menu_view.h
@@ -12,6 +12,7 @@ #include "chrome/browser/ui/toolbar/toolbar_actions_model.h" #include "chrome/browser/ui/views/extensions/extensions_toolbar_button.h" #include "chrome/browser/ui/views/hover_button.h" +#include "extensions/browser/permissions_manager.h" #include "ui/base/metadata/metadata_header_macros.h" #include "ui/views/bubble/bubble_dialog_delegate_view.h" @@ -178,6 +179,10 @@ std::vector<SiteAccessMenuItemView*> GetVisibleMenuItemsOf( SiteAccessSection section) const; + // Handles the selection of a site setting radio button. + void OnSiteSettingSelected( + extensions::PermissionsManager::UserSiteSetting site_setting); + // Shows or hides the site setting options when `site_settings_button_` is // pressed. void OnSiteSettingsButtonPressed();
diff --git a/chrome/browser/ui/views/extensions/extensions_tabbed_menu_view_unittest.cc b/chrome/browser/ui/views/extensions/extensions_tabbed_menu_view_unittest.cc index 534dbef..eac47f7 100644 --- a/chrome/browser/ui/views/extensions/extensions_tabbed_menu_view_unittest.cc +++ b/chrome/browser/ui/views/extensions/extensions_tabbed_menu_view_unittest.cc
@@ -26,14 +26,22 @@ #include "extensions/common/extension_urls.h" #include "extensions/test/test_extension_dir.h" #include "testing/gmock/include/gmock/gmock.h" +#include "ui/events/base_event_utils.h" +#include "ui/views/controls/button/radio_button.h" #include "ui/views/controls/combobox/combobox.h" #include "ui/views/view_utils.h" +#include "url/origin.h" namespace { +// Combobox option's indexes for site access menu items. constexpr int kOnClickComboboxIndex = 0; constexpr int kOnSiteComboboxIndex = 1; constexpr int kOnAllSitesComboboxIndex = 2; +// Button's indexes for site access settings +constexpr int kGrantAllExtensionsIndex = 0; +constexpr int kBlockAllExtensionsIndex = 1; +constexpr int kCustomizeByExtensionIndex = 2; // A scoper that manages a Browser instance created by BrowserWithTestWindowTest // beyond the default instance it creates in SetUp. @@ -156,6 +164,7 @@ void ClickContextMenuButton(InstalledExtensionMenuItemView* installed_item); void SelectSiteAccessInCombobox(SiteAccessMenuItemView* site_access_item, int index); + void SelectSiteSetting(int index); void LayoutMenuIfNecessary() { extensions_tabbed_menu()->GetWidget()->LayoutRootViewIfNecessary(); @@ -275,6 +284,17 @@ LayoutMenuIfNecessary(); } +void ExtensionsTabbedMenuViewUnitTest::SelectSiteSetting(int index) { + auto* site_setting = static_cast<views::RadioButton*>( + extensions_tabbed_menu()->GetSiteSettingsForTesting()->children().at( + index)); + + ui::MouseEvent release_event(ui::ET_MOUSE_RELEASED, gfx::PointF(), + gfx::PointF(), ui::EventTimeForNow(), + ui::EF_LEFT_MOUSE_BUTTON, 0); + site_setting->NotifyClick(release_event); +} + TEST_F(ExtensionsTabbedMenuViewUnitTest, ButtonOpensAndClosesCorrespondingTab) { // Load an extension with all urls permissions so the site access button is // visible. @@ -1015,6 +1035,46 @@ EXPECT_FALSE(site_settings->GetVisible()); } +TEST_F(ExtensionsTabbedMenuViewUnitTest, SiteAccessTab_SelectSiteSetting) { + auto extensionA = + InstallExtensionWithHostPermissions("Extension A", {"<all_urls>"}); + auto extensionB = + InstallExtensionWithHostPermissions("Extension B", {"<all_urls>"}); + + // Navigate to a url where the extension should have access to. + const GURL url("http://www.a.com"); + web_contents_tester()->NavigateAndCommit(url); + WaitForAnimation(); + ShowSiteAccessTabInMenu(); + + auto* manager = extensions::PermissionsManager::Get(profile()); + auto origin = url::Origin::Create(url); + + // Verify site has "customize by extensions" site setting by default. + EXPECT_EQ( + manager->GetUserSiteSetting(origin), + extensions::PermissionsManager::UserSiteSetting::kCustomizeByExtension); + + // TODO(crbug.com/1263310): After adding a permissions manager observer in the + // menu, test the site access tab contents view is the appropriate instead of + // checking the user site setting directly. + + SelectSiteSetting(kGrantAllExtensionsIndex); + EXPECT_EQ( + manager->GetUserSiteSetting(origin), + extensions::PermissionsManager::UserSiteSetting::kGrantAllExtensions); + + SelectSiteSetting(kBlockAllExtensionsIndex); + EXPECT_EQ( + manager->GetUserSiteSetting(origin), + extensions::PermissionsManager::UserSiteSetting::kBlockAllExtensions); + + SelectSiteSetting(kCustomizeByExtensionIndex); + EXPECT_EQ( + manager->GetUserSiteSetting(origin), + extensions::PermissionsManager::UserSiteSetting::kCustomizeByExtension); +} + TEST_F(ExtensionsTabbedMenuViewUnitTest, WindowTitle) { InstallExtension("Test Extension");
diff --git a/chrome/browser/ui/webui/inspect_ui_browsertest.cc b/chrome/browser/ui/webui/inspect_ui_browsertest.cc index 0105caa..866ef699 100644 --- a/chrome/browser/ui/webui/inspect_ui_browsertest.cc +++ b/chrome/browser/ui/webui/inspect_ui_browsertest.cc
@@ -52,7 +52,13 @@ } }; -IN_PROC_BROWSER_TEST_F(InspectUITest, InspectUIPage) { +// Disabled due to excessive flakiness. http://crbug.com/1304812 +#if BUILDFLAG(IS_MAC) +#define MAYBE_InspectUIPage DISABLED_InspectUIPage +#else +#define MAYBE_InspectUIPage InspectUIPage +#endif +IN_PROC_BROWSER_TEST_F(InspectUITest, MAYBE_InspectUIPage) { ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), GURL(chrome::kChromeUIInspectURL))); ASSERT_TRUE(WebUIBrowserTest::RunJavascriptAsyncTest(
diff --git a/chrome/browser/ui/webui/read_later/read_later_page_handler_unittest.cc b/chrome/browser/ui/webui/read_later/read_later_page_handler_unittest.cc index 797ea91..7f7f804 100644 --- a/chrome/browser/ui/webui/read_later/read_later_page_handler_unittest.cc +++ b/chrome/browser/ui/webui/read_later/read_later_page_handler_unittest.cc
@@ -21,6 +21,7 @@ #include "components/reading_list/core/reading_list_model.h" #include "content/public/test/test_web_ui.h" #include "testing/gmock/include/gmock/gmock.h" +#include "ui/base/mojom/window_open_disposition.mojom.h" #include "url/gurl.h" namespace { @@ -154,6 +155,16 @@ handler()->GetReadLaterEntries(std::move(callback)); } + ui::mojom::ClickModifiersPtr GetClickModifiers() { + ui::mojom::ClickModifiersPtr info = ui::mojom::ClickModifiers::New(); + info->middle_button = false; + info->alt_key = false; + info->ctrl_key = false; + info->meta_key = false; + info->shift_key = false; + return info; + } + testing::StrictMock<MockPage> page_; private: @@ -185,43 +196,43 @@ // Check that OpenURL from the NTP does not open a new tab. EXPECT_EQ(browser()->tab_strip_model()->count(), 5); - handler()->OpenURL(GURL(kTabUrl3), true, {}); + handler()->OpenURL(GURL(kTabUrl3), true, GetClickModifiers()); EXPECT_EQ(browser()->tab_strip_model()->count(), 5); // Expect ItemsChanged to be called 5 times. // Four times for the two AddEntry calls in SetUp(). - // Once for the OpenURL call above. - EXPECT_CALL(page_, ItemsChanged(testing::_)).Times(5); + EXPECT_CALL(page_, ItemsChanged(testing::_)).Times(4); // Expect CurrentPageActionButtonStateChanged to be called once. EXPECT_CALL(page_, CurrentPageActionButtonStateChanged(testing::_)).Times(1); // Get Read later entries. GetAndVerifyReadLaterEntries( - /* unread_size= */ 1u, /* read_size= */ 1u, + /* unread_size= */ 2u, /* read_size= */ 0u, /* expected_unread_data= */ - {std::make_pair(GURL(kTabUrl1), kTabName1)}, - /* expected_read_data= */ {std::make_pair(GURL(kTabUrl3), kTabName3)}); + {std::make_pair(GURL(kTabUrl3), kTabName3), + std::make_pair(GURL(kTabUrl1), kTabName1)}, + /* expected_read_data= */ {}); } TEST_F(TestReadLaterPageHandlerTest, OpenURLNotOnNTP) { - // Check that OpenURL opens a new tab when not on the NTP. + // Check that OpenURL opens in the same tab when not on the NTP. EXPECT_EQ(browser()->tab_strip_model()->count(), 4); - handler()->OpenURL(GURL(kTabUrl3), true, {}); - EXPECT_EQ(browser()->tab_strip_model()->count(), 5); + handler()->OpenURL(GURL(kTabUrl3), true, GetClickModifiers()); + EXPECT_EQ(browser()->tab_strip_model()->count(), 4); // Expect ItemsChanged to be called 5 times. // Four times for the two AddEntry calls in SetUp(). - // Once for the OpenURL call above. - EXPECT_CALL(page_, ItemsChanged(testing::_)).Times(5); + EXPECT_CALL(page_, ItemsChanged(testing::_)).Times(4); // Expect CurrentPageActionButtonStateChanged to be called once. EXPECT_CALL(page_, CurrentPageActionButtonStateChanged(testing::_)).Times(1); // Get Read later entries. GetAndVerifyReadLaterEntries( - /* unread_size= */ 1u, /* read_size= */ 1u, + /* unread_size= */ 2u, /* read_size= */ 0u, /* expected_unread_data= */ - {std::make_pair(GURL(kTabUrl1), kTabName1)}, - /* expected_read_data= */ {std::make_pair(GURL(kTabUrl3), kTabName3)}); + {std::make_pair(GURL(kTabUrl3), kTabName3), + std::make_pair(GURL(kTabUrl1), kTabName1)}, + /* expected_read_data= */ {}); } TEST_F(TestReadLaterPageHandlerTest, UpdateReadStatus) { @@ -262,15 +273,14 @@ TEST_F(TestReadLaterPageHandlerTest, UpdateAndRemoveEntry) { EXPECT_FALSE(model()->IsPerformingBatchUpdates()); - handler()->OpenURL(GURL(kTabUrl3), true, {}); + handler()->OpenURL(GURL(kTabUrl3), true, GetClickModifiers()); handler()->RemoveEntry(GURL(kTabUrl3)); EXPECT_FALSE(model()->IsPerformingBatchUpdates()); // Expect ItemsChanged to be called 6 times. // Four times for the two AddEntry calls in SetUp(). - // Once for the OpenURL call above. // Once for the RemoveEntry call above. - EXPECT_CALL(page_, ItemsChanged(testing::_)).Times(6); + EXPECT_CALL(page_, ItemsChanged(testing::_)).Times(5); // Expect CurrentPageActionButtonStateChanged to be called once. EXPECT_CALL(page_, CurrentPageActionButtonStateChanged(testing::_)).Times(1); @@ -285,7 +295,7 @@ TEST_F(TestReadLaterPageHandlerTest, PostBatchUpdate) { auto token = model()->BeginBatchUpdates(); EXPECT_TRUE(model()->IsPerformingBatchUpdates()); - handler()->OpenURL(GURL(kTabUrl3), true, {}); + handler()->OpenURL(GURL(kTabUrl3), true, GetClickModifiers()); handler()->RemoveEntry(GURL(kTabUrl3)); token.reset(); EXPECT_FALSE(model()->IsPerformingBatchUpdates()); @@ -314,7 +324,7 @@ content::WebContents::Create(params); handler()->set_web_contents_for_testing(web_contents.get()); - handler()->OpenURL(GURL(kTabUrl3), true, {}); + handler()->OpenURL(GURL(kTabUrl3), true, GetClickModifiers()); handler()->RemoveEntry(GURL(kTabUrl3)); // Expect ItemsChanged to be called four times from the two AddEntry calls in @@ -333,17 +343,16 @@ } TEST_F(TestReadLaterPageHandlerTest, OpenURLAndReadd) { - // Check that OpenURL opens a new tab when not on the NTP. EXPECT_EQ(browser()->tab_strip_model()->count(), 4); - handler()->OpenURL(GURL(kTabUrl3), true, {}); - EXPECT_EQ(browser()->tab_strip_model()->count(), 5); + handler()->OpenURL(GURL(kTabUrl3), true, GetClickModifiers()); + EXPECT_EQ(browser()->tab_strip_model()->count(), 4); model()->AddEntry(GURL(kTabUrl3), kTabName3, reading_list::EntrySource::ADDED_VIA_CURRENT_APP); // Expect ItemsChanged to be called 6 times. // Four times for the two AddEntry calls in SetUp(). - // Once for the OpenURL call above, and twice for the AddEntry call above. - EXPECT_CALL(page_, ItemsChanged(testing::_)).Times(7); + // Twice for the AddEntry call above. + EXPECT_CALL(page_, ItemsChanged(testing::_)).Times(6); // Expect CurrentPageActionButtonStateChanged to be called once when the // current page is added while on that page. EXPECT_CALL(page_, CurrentPageActionButtonStateChanged(testing::_)).Times(2);
diff --git a/chrome/browser/ui/webui/settings/site_settings_helper.cc b/chrome/browser/ui/webui/settings/site_settings_helper.cc index afec1507..f313adc1 100644 --- a/chrome/browser/ui/webui/settings/site_settings_helper.cc +++ b/chrome/browser/ui/webui/settings/site_settings_helper.cc
@@ -165,6 +165,7 @@ {ContentSettingsType::HTTP_ALLOWED, nullptr}, {ContentSettingsType::FORMFILL_METADATA, nullptr}, {ContentSettingsType::FEDERATED_IDENTITY_ACTIVE_SESSION, nullptr}, + {ContentSettingsType::FEDERATED_IDENTITY_API, nullptr}, {ContentSettingsType::AUTO_DARK_WEB_CONTENT, nullptr}, {ContentSettingsType::REQUEST_DESKTOP_SITE, nullptr}, };
diff --git a/chrome/browser/ui/webui/signin/profile_picker_handler.cc b/chrome/browser/ui/webui/signin/profile_picker_handler.cc index cb530f0..b7c9c3c 100644 --- a/chrome/browser/ui/webui/signin/profile_picker_handler.cc +++ b/chrome/browser/ui/webui/signin/profile_picker_handler.cc
@@ -30,13 +30,13 @@ #include "chrome/browser/profiles/profiles_state.h" #include "chrome/browser/signin/signin_features.h" #include "chrome/browser/signin/signin_util.h" -#include "chrome/browser/themes/theme_properties.h" #include "chrome/browser/themes/theme_service.h" #include "chrome/browser/themes/theme_service_factory.h" #include "chrome/browser/ui/browser_commands.h" #include "chrome/browser/ui/browser_finder.h" #include "chrome/browser/ui/browser_window.h" #include "chrome/browser/ui/chrome_pages.h" +#include "chrome/browser/ui/color/chrome_color_id.h" #include "chrome/browser/ui/profile_picker.h" #include "chrome/browser/ui/signin/profile_colors_util.h" #include "chrome/browser/ui/singleton_tabs.h" @@ -56,6 +56,8 @@ #include "third_party/skia/include/core/SkColor.h" #include "ui/base/l10n/l10n_util.h" #include "ui/base/webui/web_ui_util.h" +#include "ui/color/color_id.h" +#include "ui/color/color_provider.h" #include "ui/gfx/color_utils.h" #include "ui/gfx/image/image.h" @@ -143,14 +145,13 @@ return dict; } -base::Value CreateDefaultProfileThemeInfo(float scale_factor, bool dark_mode) { - SkColor frame_color = ThemeProperties::GetDefaultColor( - ThemeProperties::COLOR_FRAME_ACTIVE, /*incognito=*/false, dark_mode); - SkColor active_tab_color = ThemeProperties::GetDefaultColor( - ThemeProperties::COLOR_TOOLBAR, /*incognito=*/false, dark_mode); - SkColor frame_text_color = ThemeProperties::GetDefaultColor( - ThemeProperties::COLOR_TAB_FOREGROUND_INACTIVE_FRAME_ACTIVE, - /*incognito=*/false, dark_mode); +base::Value CreateDefaultProfileThemeInfo( + const ui::ColorProvider& color_provider, + float scale_factor) { + SkColor frame_color = color_provider.GetColor(ui::kColorFrameActive); + SkColor active_tab_color = color_provider.GetColor(kColorToolbar); + SkColor frame_text_color = + color_provider.GetColor(kColorTabForegroundInactiveFrameActive); return GetAutogeneratedProfileThemeInfoValue( kDefaultThemeColorId, absl::nullopt, frame_color, active_tab_color, frame_text_color, scale_factor); @@ -604,9 +605,8 @@ web_ui()->GetDeviceScaleFactor()); } else { profile_dict = CreateDefaultProfileThemeInfo( - web_ui()->GetDeviceScaleFactor(), - webui::GetNativeTheme(web_ui()->GetWebContents()) - ->ShouldUseDarkColors()); + web_ui()->GetWebContents()->GetColorProvider(), + web_ui()->GetDeviceScaleFactor()); } ResolveJavascriptCallback(callback_id, std::move(profile_dict)); return; @@ -630,9 +630,8 @@ switch (color_id) { case kDefaultThemeColorId: dict = CreateDefaultProfileThemeInfo( - web_ui()->GetDeviceScaleFactor(), - webui::GetNativeTheme(web_ui()->GetWebContents()) - ->ShouldUseDarkColors()); + web_ui()->GetWebContents()->GetColorProvider(), + web_ui()->GetDeviceScaleFactor()); break; case kManuallyPickedColorId: dict = CreateAutogeneratedProfileThemeInfo(
diff --git a/chrome/browser/webid/federated_identity_api_permission_context.cc b/chrome/browser/webid/federated_identity_api_permission_context.cc new file mode 100644 index 0000000..44fdcd46 --- /dev/null +++ b/chrome/browser/webid/federated_identity_api_permission_context.cc
@@ -0,0 +1,22 @@ +// Copyright 2022 The Chromium 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/webid/federated_identity_api_permission_context.h" + +#include "chrome/browser/content_settings/host_content_settings_map_factory.h" +#include "components/content_settings/core/common/content_settings_types.h" + +FederatedIdentityApiPermissionContext::FederatedIdentityApiPermissionContext( + content::BrowserContext* browser_context) + : host_content_settings_map_( + HostContentSettingsMapFactory::GetForProfile(browser_context)) {} + +FederatedIdentityApiPermissionContext:: + ~FederatedIdentityApiPermissionContext() = default; + +bool FederatedIdentityApiPermissionContext::HasApiPermission() { + return host_content_settings_map_->GetDefaultContentSetting( + ContentSettingsType::FEDERATED_IDENTITY_API, nullptr) != + ContentSetting::CONTENT_SETTING_BLOCK; +}
diff --git a/chrome/browser/webid/federated_identity_api_permission_context.h b/chrome/browser/webid/federated_identity_api_permission_context.h new file mode 100644 index 0000000..a86584d6 --- /dev/null +++ b/chrome/browser/webid/federated_identity_api_permission_context.h
@@ -0,0 +1,38 @@ +// Copyright 2022 The Chromium 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_WEBID_FEDERATED_IDENTITY_API_PERMISSION_CONTEXT_H_ +#define CHROME_BROWSER_WEBID_FEDERATED_IDENTITY_API_PERMISSION_CONTEXT_H_ + +#include "components/content_settings/core/browser/host_content_settings_map.h" +#include "components/keyed_service/core/keyed_service.h" +#include "content/public/browser/federated_identity_api_permission_context_delegate.h" + +namespace content { +class BrowserContext; +} + +// Context for storing user permission to use the browser FedCM API. +class FederatedIdentityApiPermissionContext + : public content::FederatedIdentityApiPermissionContextDelegate, + public KeyedService { + public: + explicit FederatedIdentityApiPermissionContext( + content::BrowserContext* browser_context); + + ~FederatedIdentityApiPermissionContext() override; + + FederatedIdentityApiPermissionContext( + const FederatedIdentityApiPermissionContext&) = delete; + FederatedIdentityApiPermissionContext& operator=( + const FederatedIdentityApiPermissionContext&) = delete; + + // content::FederatedIdentityApiPermissionContextDelegate: + bool HasApiPermission() override; + + private: + const raw_ptr<HostContentSettingsMap> host_content_settings_map_; +}; + +#endif // CHROME_BROWSER_WEBID_FEDERATED_IDENTITY_API_PERMISSION_CONTEXT_H_
diff --git a/chrome/browser/webid/federated_identity_api_permission_context_factory.cc b/chrome/browser/webid/federated_identity_api_permission_context_factory.cc new file mode 100644 index 0000000..3135bc2 --- /dev/null +++ b/chrome/browser/webid/federated_identity_api_permission_context_factory.cc
@@ -0,0 +1,51 @@ +// Copyright 2022 The Chromium 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/webid/federated_identity_api_permission_context_factory.h" + +#include "base/no_destructor.h" +#include "chrome/browser/content_settings/host_content_settings_map_factory.h" +#include "chrome/browser/profiles/incognito_helpers.h" +#include "chrome/browser/profiles/profile.h" +#include "chrome/browser/webid/federated_identity_api_permission_context.h" +#include "components/keyed_service/content/browser_context_dependency_manager.h" + +// static +FederatedIdentityApiPermissionContext* +FederatedIdentityApiPermissionContextFactory::GetForProfile( + content::BrowserContext* profile) { + return static_cast<FederatedIdentityApiPermissionContext*>( + GetInstance()->GetServiceForBrowserContext(profile, true)); +} + +// static +FederatedIdentityApiPermissionContextFactory* +FederatedIdentityApiPermissionContextFactory::GetInstance() { + static base::NoDestructor<FederatedIdentityApiPermissionContextFactory> + instance; + return instance.get(); +} + +FederatedIdentityApiPermissionContextFactory:: + FederatedIdentityApiPermissionContextFactory() + : BrowserContextKeyedServiceFactory( + "FederatedIdentityApiPermissionContext", + BrowserContextDependencyManager::GetInstance()) { + DependsOn(HostContentSettingsMapFactory::GetInstance()); +} + +FederatedIdentityApiPermissionContextFactory:: + ~FederatedIdentityApiPermissionContextFactory() = default; + +content::BrowserContext* +FederatedIdentityApiPermissionContextFactory::GetBrowserContextToUse( + content::BrowserContext* context) const { + return chrome::GetBrowserContextOwnInstanceInIncognito(context); +} + +KeyedService* +FederatedIdentityApiPermissionContextFactory::BuildServiceInstanceFor( + content::BrowserContext* profile) const { + return new FederatedIdentityApiPermissionContext(profile); +}
diff --git a/chrome/browser/webid/federated_identity_api_permission_context_factory.h b/chrome/browser/webid/federated_identity_api_permission_context_factory.h new file mode 100644 index 0000000..8a773ed --- /dev/null +++ b/chrome/browser/webid/federated_identity_api_permission_context_factory.h
@@ -0,0 +1,35 @@ +// Copyright 2022 The Chromium 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_WEBID_FEDERATED_IDENTITY_API_PERMISSION_CONTEXT_FACTORY_H_ +#define CHROME_BROWSER_WEBID_FEDERATED_IDENTITY_API_PERMISSION_CONTEXT_FACTORY_H_ + +#include "base/no_destructor.h" +#include "components/keyed_service/content/browser_context_keyed_service_factory.h" + +class FederatedIdentityApiPermissionContext; + +// Factory to get or create an instance of FederatedIdentityApiPermissionContext +// from a Profile. +class FederatedIdentityApiPermissionContextFactory + : public BrowserContextKeyedServiceFactory { + public: + static FederatedIdentityApiPermissionContext* GetForProfile( + content::BrowserContext* profile); + static FederatedIdentityApiPermissionContextFactory* GetInstance(); + + private: + friend class base::NoDestructor<FederatedIdentityApiPermissionContextFactory>; + + FederatedIdentityApiPermissionContextFactory(); + ~FederatedIdentityApiPermissionContextFactory() override; + + // BrowserContextKeyedServiceFactory: + content::BrowserContext* GetBrowserContextToUse( + content::BrowserContext* context) const override; + KeyedService* BuildServiceInstanceFor( + content::BrowserContext* profile) const override; +}; + +#endif // CHROME_BROWSER_WEBID_FEDERATED_IDENTITY_API_PERMISSION_CONTEXT_FACTORY_H_
diff --git a/chrome/build/linux.pgo.txt b/chrome/build/linux.pgo.txt index f2d9fb1..4ccbb99 100644 --- a/chrome/build/linux.pgo.txt +++ b/chrome/build/linux.pgo.txt
@@ -1 +1 @@ -chrome-linux-main-1646826770-b66753a40fb30a402813de1564cc7e21d1e75d43.profdata +chrome-linux-main-1646848743-f4bf9e0d566ba1b4309d748ee5f06b4c6576b1de.profdata
diff --git a/chrome/build/mac-arm.pgo.txt b/chrome/build/mac-arm.pgo.txt index d562427..495d7dc 100644 --- a/chrome/build/mac-arm.pgo.txt +++ b/chrome/build/mac-arm.pgo.txt
@@ -1 +1 @@ -chrome-mac-arm-main-1646826770-218cbbfef4d06ca227d408fc50d75423fba985dc.profdata +chrome-mac-arm-main-1646848743-259c444a76fa0f689cf0263d15b88189d22c7c5b.profdata
diff --git a/chrome/build/mac.pgo.txt b/chrome/build/mac.pgo.txt index 3393b24..9566cb5 100644 --- a/chrome/build/mac.pgo.txt +++ b/chrome/build/mac.pgo.txt
@@ -1 +1 @@ -chrome-mac-main-1646826770-62f02101f8b60b65a5c67b9a8c10ad6798971b68.profdata +chrome-mac-main-1646848743-e2c7d6dc58a9807d53cf3a38e60f409d16bfb970.profdata
diff --git a/chrome/build/win32.pgo.txt b/chrome/build/win32.pgo.txt index 32ca8d04..81146ff 100644 --- a/chrome/build/win32.pgo.txt +++ b/chrome/build/win32.pgo.txt
@@ -1 +1 @@ -chrome-win32-main-1646837990-810a983cbde6610fae4e3631b1e0b3674e9e318e.profdata +chrome-win32-main-1646848743-b8579d2cada885e51e0583777092fd6e89e1dd63.profdata
diff --git a/chrome/build/win64.pgo.txt b/chrome/build/win64.pgo.txt index a3243142..76a4ec9a 100644 --- a/chrome/build/win64.pgo.txt +++ b/chrome/build/win64.pgo.txt
@@ -1 +1 @@ -chrome-win64-main-1646826770-6b492edaf61420697708eef7fa732e07507c7bd9.profdata +chrome-win64-main-1646848743-b9b53dfd52e3bf3cec452c85b7ec3285a0e17d67.profdata
diff --git a/chrome/common/ppapi_utils.cc b/chrome/common/ppapi_utils.cc index 862778c3..6685347e 100644 --- a/chrome/common/ppapi_utils.cc +++ b/chrome/common/ppapi_utils.cc
@@ -73,10 +73,8 @@ #include "ppapi/c/private/ppb_ext_crx_file_system_private.h" #include "ppapi/c/private/ppb_file_io_private.h" #include "ppapi/c/private/ppb_file_ref_private.h" -#include "ppapi/c/private/ppb_flash_font_file.h" #include "ppapi/c/private/ppb_host_resolver_private.h" #include "ppapi/c/private/ppb_isolated_file_system_private.h" -#include "ppapi/c/private/ppb_pdf.h" #include "ppapi/c/private/ppb_proxy_private.h" #include "ppapi/c/private/ppb_tcp_server_socket_private.h" #include "ppapi/c/private/ppb_tcp_socket_private.h" @@ -97,9 +95,7 @@ return true; #include "ppapi/thunk/interfaces_ppb_private.h" -#include "ppapi/thunk/interfaces_ppb_private_flash.h" #include "ppapi/thunk/interfaces_ppb_private_no_permissions.h" -#include "ppapi/thunk/interfaces_ppb_private_pdf.h" #include "ppapi/thunk/interfaces_ppb_public_dev.h" #include "ppapi/thunk/interfaces_ppb_public_dev_channel.h" #include "ppapi/thunk/interfaces_ppb_public_socket.h"
diff --git a/chrome/renderer/BUILD.gn b/chrome/renderer/BUILD.gn index 481936d..0e6d552 100644 --- a/chrome/renderer/BUILD.gn +++ b/chrome/renderer/BUILD.gn
@@ -220,8 +220,6 @@ sources += [ "pepper/chrome_renderer_pepper_host_factory.cc", "pepper/chrome_renderer_pepper_host_factory.h", - "pepper/pepper_flash_font_file_host.cc", - "pepper/pepper_flash_font_file_host.h", "pepper/pepper_helper.cc", "pepper/pepper_helper.h", "pepper/pepper_shared_memory_message_filter.cc",
diff --git a/chrome/renderer/pepper/pepper_flash_font_file_host.cc b/chrome/renderer/pepper/pepper_flash_font_file_host.cc deleted file mode 100644 index f092185..0000000 --- a/chrome/renderer/pepper/pepper_flash_font_file_host.cc +++ /dev/null
@@ -1,119 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/renderer/pepper/pepper_flash_font_file_host.h" - -#include "base/sys_byteorder.h" -#include "build/build_config.h" -#include "content/public/renderer/renderer_ppapi_host.h" - -#include "ppapi/c/pp_errors.h" -#include "ppapi/c/trusted/ppb_browser_font_trusted.h" -#include "ppapi/host/dispatch_host_message.h" -#include "ppapi/host/host_message_context.h" -#include "ppapi/host/ppapi_host.h" -#include "ppapi/proxy/ppapi_messages.h" -#include "ppapi/proxy/serialized_structs.h" - -#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_OPENBSD) -#include "components/services/font/public/cpp/font_loader.h" -#include "pdf/font_table_linux.h" -#elif BUILDFLAG(IS_WIN) -#include "third_party/skia/include/core/SkFontMgr.h" -#endif - -PepperFlashFontFileHost::PepperFlashFontFileHost( - content::RendererPpapiHost* host, - PP_Instance instance, - PP_Resource resource, - const ppapi::proxy::SerializedFontDescription& description, - PP_PrivateFontCharset charset) - : ResourceHost(host->GetPpapiHost(), instance, resource) { -#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) - // The global SkFontConfigInterface is configured and initialized with a - // SkFontconfigInterface compatible font_service::FontLoader in - // RendererBlinkPlatformImpl (called from RenderThreadImpl::Init) at startup - // of the mimehandler process, which is a renderer type process. We can reuse - // it here to call a plugin specific font matching method out of process here. - // TODO(drott): Find a way to pass this through instead of casting. - font_service::FontLoader* font_loader_casted = - reinterpret_cast<font_service::FontLoader*>( - SkFontConfigInterface::RefGlobal().get()); - font_loader_casted->MatchFontWithFallback( - description.face, - description.weight >= PP_BROWSERFONT_TRUSTED_WEIGHT_BOLD, - description.italic, charset, PP_BROWSERFONT_TRUSTED_FAMILY_DEFAULT, - &font_file_); -#elif BUILDFLAG(IS_WIN) - int weight = description.weight; - if (weight == FW_DONTCARE) - weight = SkFontStyle::kNormal_Weight; - SkFontStyle style(weight, SkFontStyle::kNormal_Width, - description.italic ? SkFontStyle::kItalic_Slant - : SkFontStyle::kUpright_Slant); - sk_sp<SkFontMgr> font_mgr(SkFontMgr::RefDefault()); - - typeface_ = sk_sp<SkTypeface>( - font_mgr->matchFamilyStyle(description.face.c_str(), style)); -#endif -} - -PepperFlashFontFileHost::~PepperFlashFontFileHost() {} - -int32_t PepperFlashFontFileHost::OnResourceMessageReceived( - const IPC::Message& msg, - ppapi::host::HostMessageContext* context) { - PPAPI_BEGIN_MESSAGE_MAP(PepperFlashFontFileHost, msg) - PPAPI_DISPATCH_HOST_RESOURCE_CALL(PpapiHostMsg_FlashFontFile_GetFontTable, - OnGetFontTable) - PPAPI_END_MESSAGE_MAP() - return PP_ERROR_FAILED; -} - -bool PepperFlashFontFileHost::GetFontData(uint32_t table, - void* buffer, - size_t* length) { - bool result = false; -#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) - if (font_file_.IsValid()) { - result = - pdf::GetFontTable(font_file_.GetPlatformFile(), table, /*offset=*/0, - reinterpret_cast<uint8_t*>(buffer), length); - } -#elif BUILDFLAG(IS_WIN) - if (typeface_) { - table = base::ByteSwap(table); - if (buffer == NULL) { - *length = typeface_->getTableSize(table); - if (*length > 0) - result = true; - } else { - size_t new_length = typeface_->getTableData(table, 0, *length, buffer); - if (new_length == *length) - result = true; - } - } -#endif - return result; -} - -int32_t PepperFlashFontFileHost::OnGetFontTable( - ppapi::host::HostMessageContext* context, - uint32_t table) { - std::string contents; - int32_t result = PP_ERROR_FAILED; - size_t length = 0; - if (GetFontData(table, NULL, &length)) { - contents.resize(length); - uint8_t* contents_ptr = - reinterpret_cast<uint8_t*>(const_cast<char*>(contents.c_str())); - if (GetFontData(table, contents_ptr, &length)) { - result = PP_OK; - } else { - contents.clear(); - } - } - context->reply_msg = PpapiPluginMsg_FlashFontFile_GetFontTableReply(contents); - return result; -}
diff --git a/chrome/renderer/pepper/pepper_flash_font_file_host.h b/chrome/renderer/pepper/pepper_flash_font_file_host.h deleted file mode 100644 index e6a9f81a..0000000 --- a/chrome/renderer/pepper/pepper_flash_font_file_host.h +++ /dev/null
@@ -1,62 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROME_RENDERER_PEPPER_PEPPER_FLASH_FONT_FILE_HOST_H_ -#define CHROME_RENDERER_PEPPER_PEPPER_FLASH_FONT_FILE_HOST_H_ - -#include <stddef.h> -#include <stdint.h> - -#include "build/build_config.h" -#include "ppapi/c/private/pp_private_font_charset.h" -#include "ppapi/host/resource_host.h" - -#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_OPENBSD) -#include "base/files/file.h" -#elif BUILDFLAG(IS_WIN) -#include "third_party/skia/include/core/SkRefCnt.h" -#include "third_party/skia/include/core/SkTypeface.h" -#endif - -namespace content { -class RendererPpapiHost; -} - -namespace ppapi { -namespace proxy { -struct SerializedFontDescription; -} -} - -class PepperFlashFontFileHost : public ppapi::host::ResourceHost { - public: - PepperFlashFontFileHost( - content::RendererPpapiHost* host, - PP_Instance instance, - PP_Resource resource, - const ppapi::proxy::SerializedFontDescription& description, - PP_PrivateFontCharset charset); - - PepperFlashFontFileHost(const PepperFlashFontFileHost&) = delete; - PepperFlashFontFileHost& operator=(const PepperFlashFontFileHost&) = delete; - - ~PepperFlashFontFileHost() override; - - int32_t OnResourceMessageReceived( - const IPC::Message& msg, - ppapi::host::HostMessageContext* context) override; - - private: - int32_t OnGetFontTable(ppapi::host::HostMessageContext* context, - uint32_t table); - bool GetFontData(uint32_t table, void* buffer, size_t* length); - -#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) - base::File font_file_; -#elif BUILDFLAG(IS_WIN) - sk_sp<SkTypeface> typeface_; -#endif -}; - -#endif // CHROME_RENDERER_PEPPER_PEPPER_FLASH_FONT_FILE_HOST_H_
diff --git a/chrome/test/BUILD.gn b/chrome/test/BUILD.gn index 77e3f1ba..867445c 100644 --- a/chrome/test/BUILD.gn +++ b/chrome/test/BUILD.gn
@@ -1641,6 +1641,7 @@ "../browser/content_settings/sound_content_setting_observer_browsertest.cc", "../browser/crash_recovery_browsertest.cc", "../browser/custom_handlers/protocol_handler_registry_browsertest.cc", + "../browser/data_use_measurement/chrome_data_use_measurement_browsertest.cc", "../browser/device_api/managed_configuration_api_browsertest.cc", "../browser/devtools/device/adb/adb_client_socket_browsertest.cc", "../browser/devtools/device/adb/mock_adb_server.cc",
diff --git a/chrome/test/data/client_hints/accept_ch_ua_iframe_sandbox_request.html b/chrome/test/data/client_hints/accept_ch_ua_iframe_sandbox_request.html new file mode 100644 index 0000000..16d487e --- /dev/null +++ b/chrome/test/data/client_hints/accept_ch_ua_iframe_sandbox_request.html
@@ -0,0 +1,9 @@ +<!DOCTYPE html> +<html> +<!-- Prevent favicon fetch request. --> +<link rel="icon" href="data:;base64,="> +<head></head> +<body> +<iframe src="simple.html" id="test" sandbox></iframe> +</body> +</html>
diff --git a/chrome/test/data/webui/cr_components/chromeos/bluetooth/fake_bluetooth_config.js b/chrome/test/data/webui/cr_components/chromeos/bluetooth/fake_bluetooth_config.js index 7bd7ddf..6d5d0ed 100644 --- a/chrome/test/data/webui/cr_components/chromeos/bluetooth/fake_bluetooth_config.js +++ b/chrome/test/data/webui/cr_components/chromeos/bluetooth/fake_bluetooth_config.js
@@ -12,7 +12,7 @@ import 'chrome://resources/mojo/chromeos/services/bluetooth_config/public/mojom/cros_bluetooth_config.mojom-lite.js'; import {stringToMojoString16} from 'chrome://resources/cr_components/chromeos/bluetooth/bluetooth_utils.js'; -import {assertFalse, assertTrue} from '../../../chai_assert.js'; +import {assertFalse, assertNotReached, assertTrue} from '../../../chai_assert.js'; import {FakeDevicePairingHandler} from './fake_device_pairing_handler.js'; const mojom = chromeos.bluetoothConfig.mojom; @@ -134,6 +134,16 @@ this.bluetooth_device_status_observers_.push(observer); } + /** + * @override + * @param {!chromeos.bluetoothConfig.mojom.DiscoverySessionStatusObserverInterface} + * observer + */ + observeDiscoverySessionStatusChanges(observer) { + // This method left unimplemented while the observer is not used in JS. + assertNotReached(); + } + /** * @override
diff --git a/chrome/test/data/webui/cr_elements/cr_auto_img_test.ts b/chrome/test/data/webui/cr_elements/cr_auto_img_test.ts index cb30973..6868b2f 100644 --- a/chrome/test/data/webui/cr_elements/cr_auto_img_test.ts +++ b/chrome/test/data/webui/cr_elements/cr_auto_img_test.ts
@@ -8,6 +8,26 @@ import {assertEquals} from 'chrome://webui-test/chai_assert.js'; +async function waitForAttributeChange( + element: HTMLElement, attribute: string): Promise<Array<MutationRecord>> { + return new Promise(resolve => { + const observer = new MutationObserver((mutations, obs) => { + obs.disconnect(); + resolve(mutations); + }); + observer.observe( + element, + { + attributes: true, + attributeFilter: [attribute], + attributeOldValue: true, + childList: false, + subtree: false, + }, + ); + }); +} + suite('CrAutoImgElementTest', () => { let img: CrAutoImgElement; @@ -77,4 +97,30 @@ encodeURIComponent(autoSrc)}&withCookies=true`, img.src); }); + + test( + 'setting clear-src removes the src attribute first when auto-src changes', + async () => { + const originalSrc = 'chrome://foo/foo.png'; + img.clearSrc = ''; + img.autoSrc = originalSrc; + assertEquals( + originalSrc, img.src, 'src attribute is set to initial value'); + + const newSrc = 'chrome://bar/bar.png'; + + const attrChangedPromise = waitForAttributeChange(img, 'src'); + img.autoSrc = newSrc; + + const mutations = await attrChangedPromise; + assertEquals(2, mutations.length, 'src is changed twice'); + assertEquals( + originalSrc, mutations[0]?.oldValue, + 'src starts as original value'); + + assertEquals( + null, mutations[1]?.oldValue, 'src is set to null in between'); + + assertEquals(newSrc, img.src, 'src attribute is set to new value'); + }); });
diff --git a/chromeos/services/bluetooth_config/BUILD.gn b/chromeos/services/bluetooth_config/BUILD.gn index 8a2b4c7..b5762f2 100644 --- a/chromeos/services/bluetooth_config/BUILD.gn +++ b/chromeos/services/bluetooth_config/BUILD.gn
@@ -45,6 +45,8 @@ "discovery_session_manager.h", "discovery_session_manager_impl.cc", "discovery_session_manager_impl.h", + "discovery_session_status_notifier.cc", + "discovery_session_status_notifier.h", "fast_pair_delegate.h", "initializer.h", "initializer_impl.cc", @@ -122,6 +124,8 @@ "fake_discovered_devices_provider.h", "fake_discovery_session_manager.cc", "fake_discovery_session_manager.h", + "fake_discovery_session_status_observer.cc", + "fake_discovery_session_status_observer.h", "fake_fast_pair_delegate.cc", "fake_fast_pair_delegate.h", "fake_key_entered_handler.cc",
diff --git a/chromeos/services/bluetooth_config/cros_bluetooth_config.cc b/chromeos/services/bluetooth_config/cros_bluetooth_config.cc index 4384fbc..a6fd5bbc 100644 --- a/chromeos/services/bluetooth_config/cros_bluetooth_config.cc +++ b/chromeos/services/bluetooth_config/cros_bluetooth_config.cc
@@ -87,6 +87,12 @@ std::move(observer)); } +void CrosBluetoothConfig::ObserveDiscoverySessionStatusChanges( + mojo::PendingRemote<mojom::DiscoverySessionStatusObserver> observer) { + discovery_session_manager_->ObserveDiscoverySessionStatusChanges( + std::move(observer)); +} + void CrosBluetoothConfig::SetBluetoothEnabledState(bool enabled) { bluetooth_power_controller_->SetBluetoothEnabledState(enabled); }
diff --git a/chromeos/services/bluetooth_config/cros_bluetooth_config.h b/chromeos/services/bluetooth_config/cros_bluetooth_config.h index e85b24f6..ae2197da 100644 --- a/chromeos/services/bluetooth_config/cros_bluetooth_config.h +++ b/chromeos/services/bluetooth_config/cros_bluetooth_config.h
@@ -58,6 +58,9 @@ void ObserveDeviceStatusChanges( mojo::PendingRemote<mojom::BluetoothDeviceStatusObserver> observer) override; + void ObserveDiscoverySessionStatusChanges( + mojo::PendingRemote<mojom::DiscoverySessionStatusObserver> observer) + override; void SetBluetoothEnabledState(bool enabled) override; void StartDiscovery( mojo::PendingRemote<mojom::BluetoothDiscoveryDelegate> delegate) override;
diff --git a/chromeos/services/bluetooth_config/cros_bluetooth_config_unittest.cc b/chromeos/services/bluetooth_config/cros_bluetooth_config_unittest.cc index 2aaa3e05..1fb86f0a 100644 --- a/chromeos/services/bluetooth_config/cros_bluetooth_config_unittest.cc +++ b/chromeos/services/bluetooth_config/cros_bluetooth_config_unittest.cc
@@ -15,6 +15,7 @@ #include "chromeos/services/bluetooth_config/device_name_manager_impl.h" #include "chromeos/services/bluetooth_config/fake_bluetooth_device_status_observer.h" #include "chromeos/services/bluetooth_config/fake_bluetooth_discovery_delegate.h" +#include "chromeos/services/bluetooth_config/fake_discovery_session_status_observer.h" #include "chromeos/services/bluetooth_config/fake_fast_pair_delegate.h" #include "chromeos/services/bluetooth_config/fake_system_properties_observer.h" #include "chromeos/services/bluetooth_config/initializer_impl.h" @@ -162,5 +163,13 @@ base::RunLoop().RunUntilIdle(); } +TEST_F(CrosBluetoothConfigTest, CallDiscoverySessionStatusApiFunction) { + mojo::Remote<mojom::CrosBluetoothConfig> remote = BindToInterface(); + FakeDiscoverySessionStatusObserver fake_observer; + remote->ObserveDiscoverySessionStatusChanges( + fake_observer.GeneratePendingRemote()); + base::RunLoop().RunUntilIdle(); +} + } // namespace bluetooth_config } // namespace chromeos
diff --git a/chromeos/services/bluetooth_config/discovery_session_manager.cc b/chromeos/services/bluetooth_config/discovery_session_manager.cc index 11141baf..de838617 100644 --- a/chromeos/services/bluetooth_config/discovery_session_manager.cc +++ b/chromeos/services/bluetooth_config/discovery_session_manager.cc
@@ -45,6 +45,8 @@ if (!had_client_before_call) { BLUETOOTH_LOG(EVENT) << "StartDiscovery() called as the first client"; OnHasAtLeastOneDiscoveryClientChanged(); + NotifyHasAtLeastOneDiscoverySessionChanged( + /*has_at_least_one_discovery_session=*/true); return; } @@ -83,6 +85,8 @@ // The number of clients has decreased from >0 to 0. OnHasAtLeastOneDiscoveryClientChanged(); + NotifyHasAtLeastOneDiscoverySessionChanged( + /*has_at_least_one_discovery_session=*/false); } bool DiscoverySessionManager::HasAtLeastOneDiscoveryClient() const { @@ -147,6 +151,8 @@ BLUETOOTH_LOG(EVENT) << "The number of discovery clients has decreased from 1 to 0"; OnHasAtLeastOneDiscoveryClientChanged(); + NotifyHasAtLeastOneDiscoverySessionChanged( + /*has_at_least_one_discovery_session=*/false); } }
diff --git a/chromeos/services/bluetooth_config/discovery_session_manager.h b/chromeos/services/bluetooth_config/discovery_session_manager.h index a9193eb..6e9c7e2c 100644 --- a/chromeos/services/bluetooth_config/discovery_session_manager.h +++ b/chromeos/services/bluetooth_config/discovery_session_manager.h
@@ -10,6 +10,7 @@ #include "chromeos/services/bluetooth_config/adapter_state_controller.h" #include "chromeos/services/bluetooth_config/device_pairing_handler.h" #include "chromeos/services/bluetooth_config/discovered_devices_provider.h" +#include "chromeos/services/bluetooth_config/discovery_session_status_notifier.h" #include "chromeos/services/bluetooth_config/public/mojom/cros_bluetooth_config.mojom.h" #include "mojo/public/cpp/bindings/pending_remote.h" #include "mojo/public/cpp/bindings/remote_set.h" @@ -31,7 +32,8 @@ // responsible for starting and stopping discovery and does not handle pairing // attempts. class DiscoverySessionManager : public AdapterStateController::Observer, - public DiscoveredDevicesProvider::Observer { + public DiscoveredDevicesProvider::Observer, + public DiscoverySessionStatusNotifier { public: ~DiscoverySessionManager() override;
diff --git a/chromeos/services/bluetooth_config/discovery_session_manager_impl.cc b/chromeos/services/bluetooth_config/discovery_session_manager_impl.cc index 5934f67..5896e193 100644 --- a/chromeos/services/bluetooth_config/discovery_session_manager_impl.cc +++ b/chromeos/services/bluetooth_config/discovery_session_manager_impl.cc
@@ -4,9 +4,11 @@ #include "chromeos/services/bluetooth_config/discovery_session_manager_impl.h" +#include "base/feature_list.h" #include "chromeos/services/bluetooth_config/device_pairing_handler_impl.h" #include "components/device_event_log/device_event_log.h" #include "device/bluetooth/bluetooth_discovery_session.h" +#include "device/bluetooth/floss/floss_features.h" namespace chromeos { namespace bluetooth_config { @@ -59,6 +61,15 @@ // |discovery_session_| is no longer operational, so destroy it. BLUETOOTH_LOG(EVENT) << "Adapter discovering became false during an active " "discovery session, destroying session"; + + // With Floss the discovery could be stopped due to Inquiry timeout or before + // pairing/connection while pairing may be ongoing. UI should not destroy + // discovery session since doing so will clear the pairing handler which is + // still needed. + // TODO(b/222230887): Decouple pairing handler from discovery session. + if (base::FeatureList::IsEnabled(floss::features::kFlossEnabled)) + return; + DestroyDiscoverySession(); }
diff --git a/chromeos/services/bluetooth_config/discovery_session_manager_impl_unittest.cc b/chromeos/services/bluetooth_config/discovery_session_manager_impl_unittest.cc index 332f1b9e..6e52af6 100644 --- a/chromeos/services/bluetooth_config/discovery_session_manager_impl_unittest.cc +++ b/chromeos/services/bluetooth_config/discovery_session_manager_impl_unittest.cc
@@ -10,6 +10,7 @@ #include "base/strings/strcat.h" #include "base/strings/string_number_conversions.h" #include "base/test/bind.h" +#include "base/test/scoped_feature_list.h" #include "base/test/task_environment.h" #include "base/types/token_type.h" #include "chromeos/services/bluetooth_config/device_conversion_util.h" @@ -19,8 +20,12 @@ #include "chromeos/services/bluetooth_config/fake_device_pairing_delegate.h" #include "chromeos/services/bluetooth_config/fake_device_pairing_handler.h" #include "chromeos/services/bluetooth_config/fake_discovered_devices_provider.h" +#include "chromeos/services/bluetooth_config/fake_discovery_session_status_observer.h" +#include "device/bluetooth/floss/floss_features.h" #include "device/bluetooth/test/mock_bluetooth_adapter.h" #include "device/bluetooth/test/mock_bluetooth_device.h" +#include "mojo/public/cpp/bindings/pending_remote.h" +#include "mojo/public/cpp/bindings/receiver.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/abseil-cpp/absl/types/optional.h" @@ -149,9 +154,9 @@ /*connected=*/false); ON_CALL(*mock_device, Connect_(testing::_, testing::_)) .WillByDefault(testing::Invoke( - [](device::BluetoothDevice::PairingDelegate* pairing_delegate, - device::BluetoothDevice::ConnectCallback& callback) { - std::move(callback).Run(absl::nullopt); + [this](device::BluetoothDevice::PairingDelegate* pairing_delegate, + device::BluetoothDevice::ConnectCallback& callback) { + connect_callback_ = std::move(callback); })); mock_devices_.push_back(std::move(mock_device)); @@ -167,10 +172,27 @@ discovery_session_manager_->FlushForTesting(); } + bool HasPendingConnectCallback() const { + return !connect_callback_.is_null(); + } + + void InvokePendingConnectCallback() { + std::move(connect_callback_).Run(absl::nullopt); + base::RunLoop().RunUntilIdle(); + } + void SetShouldSynchronouslyInvokeStartScanCallback(bool should) { should_synchronously_invoke_start_scan_callback_ = should; } + std::unique_ptr<FakeDiscoverySessionStatusObserver> Observe() { + auto observer = std::make_unique<FakeDiscoverySessionStatusObserver>(); + discovery_session_manager_->ObserveDiscoverySessionStatusChanges( + observer->GeneratePendingRemote()); + discovery_session_manager_->FlushForTesting(); + return observer; + } + private: class FakeDevicePairingHandlerFactory : public DevicePairingHandlerImpl::Factory { @@ -238,6 +260,7 @@ bool should_synchronously_invoke_start_scan_callback_ = false; StartScanCallback start_scan_callback_; StopScanCallback stop_scan_callback_; + device::BluetoothDevice::ConnectCallback connect_callback_; FakeAdapterStateController fake_adapter_state_controller_; FakeDiscoveredDevicesProvider fake_discovered_devices_provider_; @@ -406,16 +429,28 @@ } TEST_F(DiscoverySessionManagerImplTest, MultipleClientsAttemptPairing) { + std::unique_ptr<FakeDiscoverySessionStatusObserver> observer = Observe(); + + // Initially, observer would see the default state, which is 0 sessions. + EXPECT_FALSE(observer->has_at_least_one_discovery_session()); + EXPECT_EQ(0, observer->num_discovery_session_changed_calls()); + std::unique_ptr<FakeBluetoothDiscoveryDelegate> delegate1 = StartDiscovery(); InvokePendingStartScanCallback(/*success=*/true); EXPECT_TRUE(delegate1->IsMojoPipeConnected()); EXPECT_EQ(1u, delegate1->num_start_callbacks()); EXPECT_TRUE(delegate1->pairing_handler().is_connected()); + // Going from 0 to 1 discovery sessions should notify observers. + EXPECT_TRUE(observer->has_at_least_one_discovery_session()); + EXPECT_EQ(1, observer->num_discovery_session_changed_calls()); std::unique_ptr<FakeBluetoothDiscoveryDelegate> delegate2 = StartDiscovery(); EXPECT_TRUE(delegate2->IsMojoPipeConnected()); EXPECT_EQ(1u, delegate2->num_start_callbacks()); EXPECT_TRUE(delegate2->pairing_handler().is_connected()); + // Going from 1 to 1+ discovery sessions should not notify observers. + EXPECT_TRUE(observer->has_at_least_one_discovery_session()); + EXPECT_EQ(1, observer->num_discovery_session_changed_calls()); // Simulate first client attempting to pair with an unknown device_id. absl::optional<mojom::PairingResult> result; @@ -427,6 +462,7 @@ result = pairing_result; })); base::RunLoop().RunUntilIdle(); + EXPECT_FALSE(HasPendingConnectCallback()); EXPECT_EQ(result, mojom::PairingResult::kNonAuthFailure); // First client's pairing handler should still be alive because we can retry @@ -446,12 +482,17 @@ result = pairing_result; })); base::RunLoop().RunUntilIdle(); + EXPECT_TRUE(HasPendingConnectCallback()); + InvokePendingConnectCallback(); EXPECT_EQ(result, mojom::PairingResult::kSuccess); // First client's Mojo pipes should be disconnected. EXPECT_FALSE(delegate1->IsMojoPipeConnected()); EXPECT_FALSE(delegate1->pairing_handler().is_connected()); EXPECT_FALSE(pairing_delegate2->IsMojoPipeConnected()); + // Going from 1+ to 1 discovery sessions should not notify observers. + EXPECT_TRUE(observer->has_at_least_one_discovery_session()); + EXPECT_EQ(1, observer->num_discovery_session_changed_calls()); // Simulate second client pairing with a known device_id. std::string device_id2; @@ -464,6 +505,8 @@ result = pairing_result; })); base::RunLoop().RunUntilIdle(); + EXPECT_TRUE(HasPendingConnectCallback()); + InvokePendingConnectCallback(); EXPECT_EQ(result, mojom::PairingResult::kSuccess); // Second client's Mojo pipes should be disconnected and discovery stopped. @@ -471,6 +514,9 @@ EXPECT_FALSE(delegate2->pairing_handler().is_connected()); EXPECT_FALSE(pairing_delegate3->IsMojoPipeConnected()); InvokePendingStopScanCallback(/*success=*/true); + // Going from 1 to 0 discovery sessions should notify observers. + EXPECT_FALSE(observer->has_at_least_one_discovery_session()); + EXPECT_EQ(2, observer->num_discovery_session_changed_calls()); } TEST_F(DiscoverySessionManagerImplTest, StartDiscoverySynchronous) { @@ -493,5 +539,104 @@ EXPECT_EQ(0u, delegate->num_stop_callbacks()); } +TEST_F(DiscoverySessionManagerImplTest, DisconnectToStopObserving) { + std::unique_ptr<FakeDiscoverySessionStatusObserver> observer = Observe(); + + // Initially, observer would see the default state, which is 0 sessions. + EXPECT_FALSE(observer->has_at_least_one_discovery_session()); + EXPECT_EQ(0, observer->num_discovery_session_changed_calls()); + + // Disconnect the Mojo pipe; this should stop observing. + observer->DisconnectMojoPipe(); + + // Add the first client and start discovery. The observer should not be + // notified since it is disconnected. + std::unique_ptr<FakeBluetoothDiscoveryDelegate> delegate1 = StartDiscovery(); + InvokePendingStartScanCallback(/*success=*/true); + EXPECT_FALSE(observer->has_at_least_one_discovery_session()); + EXPECT_EQ(0, observer->num_discovery_session_changed_calls()); +} + +TEST_F(DiscoverySessionManagerImplTest, AdapterDiscoveringStopsDuringPairing) { + std::unique_ptr<FakeBluetoothDiscoveryDelegate> delegate = StartDiscovery(); + + InvokePendingStartScanCallback(/*success=*/true); + EXPECT_TRUE(delegate->IsMojoPipeConnected()); + EXPECT_EQ(1u, delegate->num_start_callbacks()); + EXPECT_TRUE(delegate->pairing_handler().is_connected()); + + // Simulate client pairing with a device. + std::string device_id; + AddDevice(&device_id); + absl::optional<mojom::PairingResult> result; + auto pairing_delegate = std::make_unique<FakeDevicePairingDelegate>(); + delegate->pairing_handler()->PairDevice( + device_id, pairing_delegate->GeneratePendingRemote(), + base::BindLambdaForTesting( + [&result](mojom::PairingResult pairing_result) { + result = pairing_result; + })); + base::RunLoop().RunUntilIdle(); + EXPECT_TRUE(HasPendingConnectCallback()); + + // Simulate the discovery session stopping unexpectedly before pairing + // completes. Discovery should stop and the discovery delegate, pairing + // handler, and pairing delegate disconnected. + SimulateDiscoverySessionStopping(); + EXPECT_FALSE(delegate->IsMojoPipeConnected()); + EXPECT_EQ(1u, delegate->num_stop_callbacks()); + EXPECT_FALSE(delegate->pairing_handler().is_connected()); + EXPECT_FALSE(pairing_delegate->IsMojoPipeConnected()); + InvokePendingStopScanCallback(/*success=*/true); +} + +TEST_F(DiscoverySessionManagerImplTest, + AdapterDiscoveringStopsDuringPairing_Floss) { + base::test::ScopedFeatureList feature_list; + feature_list.InitAndEnableFeature(floss::features::kFlossEnabled); + EXPECT_TRUE(base::FeatureList::IsEnabled(floss::features::kFlossEnabled)); + + std::unique_ptr<FakeBluetoothDiscoveryDelegate> delegate = StartDiscovery(); + + InvokePendingStartScanCallback(/*success=*/true); + EXPECT_TRUE(delegate->IsMojoPipeConnected()); + EXPECT_EQ(1u, delegate->num_start_callbacks()); + EXPECT_TRUE(delegate->pairing_handler().is_connected()); + + // Simulate client pairing with a device. + std::string device_id; + AddDevice(&device_id); + absl::optional<mojom::PairingResult> result; + auto pairing_delegate = std::make_unique<FakeDevicePairingDelegate>(); + delegate->pairing_handler()->PairDevice( + device_id, pairing_delegate->GeneratePendingRemote(), + base::BindLambdaForTesting( + [&result](mojom::PairingResult pairing_result) { + result = pairing_result; + })); + base::RunLoop().RunUntilIdle(); + EXPECT_TRUE(HasPendingConnectCallback()); + + // Simulate the discovery session stopping before pairing + // completes. This can happen with Floss enabled, but the device pairing + // handler should remain alive. + // TODO(b/222230887): Remove this test when DiscoverySessionManager and + // DevicePairingHandler lifecycles are decoupled. + SimulateDiscoverySessionStopping(); + EXPECT_TRUE(delegate->IsMojoPipeConnected()); + EXPECT_EQ(0u, delegate->num_stop_callbacks()); + EXPECT_TRUE(delegate->pairing_handler().is_connected()); + EXPECT_TRUE(pairing_delegate->IsMojoPipeConnected()); + + InvokePendingConnectCallback(); + EXPECT_EQ(result, mojom::PairingResult::kSuccess); + + // The client's Mojo pipes should now be disconnected and discovery stopped. + EXPECT_FALSE(delegate->IsMojoPipeConnected()); + EXPECT_FALSE(delegate->pairing_handler().is_connected()); + EXPECT_FALSE(pairing_delegate->IsMojoPipeConnected()); + InvokePendingStopScanCallback(/*success=*/true); +} + } // namespace bluetooth_config } // namespace chromeos
diff --git a/chromeos/services/bluetooth_config/discovery_session_status_notifier.cc b/chromeos/services/bluetooth_config/discovery_session_status_notifier.cc new file mode 100644 index 0000000..86e122d --- /dev/null +++ b/chromeos/services/bluetooth_config/discovery_session_status_notifier.cc
@@ -0,0 +1,34 @@ +// Copyright 2022 The Chromium 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/services/bluetooth_config/discovery_session_status_notifier.h" +#include "chromeos/services/bluetooth_config/public/cpp/cros_bluetooth_config_util.h" +#include "components/device_event_log/device_event_log.h" + +namespace chromeos { +namespace bluetooth_config { + +DiscoverySessionStatusNotifier::DiscoverySessionStatusNotifier() = default; + +DiscoverySessionStatusNotifier::~DiscoverySessionStatusNotifier() = default; + +void DiscoverySessionStatusNotifier::ObserveDiscoverySessionStatusChanges( + mojo::PendingRemote<mojom::DiscoverySessionStatusObserver> observer) { + observers_.Add(std::move(observer)); +} + +void DiscoverySessionStatusNotifier::NotifyHasAtLeastOneDiscoverySessionChanged( + bool has_at_least_one_discovery_session) { + BLUETOOTH_LOG(EVENT) + << "Notifying observers that the existence of at least one" + " discovery session has changed to: " + << has_at_least_one_discovery_session; + for (auto& observer : observers_) { + observer->OnHasAtLeastOneDiscoverySessionChanged( + has_at_least_one_discovery_session); + } +} + +} // namespace bluetooth_config +} // namespace chromeos
diff --git a/chromeos/services/bluetooth_config/discovery_session_status_notifier.h b/chromeos/services/bluetooth_config/discovery_session_status_notifier.h new file mode 100644 index 0000000..575943d --- /dev/null +++ b/chromeos/services/bluetooth_config/discovery_session_status_notifier.h
@@ -0,0 +1,42 @@ +// Copyright 2022 The Chromium 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_SERVICES_BLUETOOTH_CONFIG_DISCOVERY_SESSION_STATUS_NOTIFIER_H_ +#define CHROMEOS_SERVICES_BLUETOOTH_CONFIG_DISCOVERY_SESSION_STATUS_NOTIFIER_H_ + +#include "chromeos/services/bluetooth_config/public/mojom/cros_bluetooth_config.mojom.h" +#include "mojo/public/cpp/bindings/remote.h" +#include "mojo/public/cpp/bindings/remote_set.h" + +namespace chromeos { +namespace bluetooth_config { + +// Notifiers all listeners of changes in discovery session status. +class DiscoverySessionStatusNotifier { + public: + virtual ~DiscoverySessionStatusNotifier(); + + // Adds an observer of discovery session status. |observer| will be notified + // each time discovery session status changes. To stop observing, clients + // should disconnect the Mojo pipe to |observer| by deleting the associated + // Receiver. + void ObserveDiscoverySessionStatusChanges( + mojo::PendingRemote<mojom::DiscoverySessionStatusObserver> observer); + + protected: + DiscoverySessionStatusNotifier(); + + // Notifies all observers when "having at least one discovery session" changes + // between true and false. + void NotifyHasAtLeastOneDiscoverySessionChanged( + bool has_at_least_one_discovery_session); + + private: + mojo::RemoteSet<mojom::DiscoverySessionStatusObserver> observers_; +}; + +} // namespace bluetooth_config +} // namespace chromeos + +#endif // CHROMEOS_SERVICES_BLUETOOTH_CONFIG_DISCOVERY_SESSION_STATUS_NOTIFIER_H_
diff --git a/chromeos/services/bluetooth_config/fake_discovery_session_manager.cc b/chromeos/services/bluetooth_config/fake_discovery_session_manager.cc index 8168eb6..3a670383 100644 --- a/chromeos/services/bluetooth_config/fake_discovery_session_manager.cc +++ b/chromeos/services/bluetooth_config/fake_discovery_session_manager.cc
@@ -23,10 +23,16 @@ is_discovery_session_active_ = is_active; - if (is_discovery_session_active_) + if (is_discovery_session_active_) { NotifyDiscoveryStarted(); - else + NotifyHasAtLeastOneDiscoverySessionChanged(is_discovery_session_active_); + } else { NotifyDiscoveryStoppedAndClearActiveClients(); + // DiscoverySessionStatusObservers would have been notified by the above + // call but this fake manager always early returns before notifying + // observers. Explicitly notify observers. + NotifyHasAtLeastOneDiscoverySessionChanged(is_discovery_session_active_); + } } bool FakeDiscoverySessionManager::IsDiscoverySessionActive() const {
diff --git a/chromeos/services/bluetooth_config/fake_discovery_session_manager.h b/chromeos/services/bluetooth_config/fake_discovery_session_manager.h index a7cc704..efa44f5 100644 --- a/chromeos/services/bluetooth_config/fake_discovery_session_manager.h +++ b/chromeos/services/bluetooth_config/fake_discovery_session_manager.h
@@ -18,8 +18,8 @@ DiscoveredDevicesProvider* discovered_devices_provider); ~FakeDiscoverySessionManager() override; - // Sets whether a discovery session is active and notifies delegates of the - // change. + // Sets whether a discovery session is active and notifies delegates and + // observers of the change. void SetIsDiscoverySessionActive(bool is_active); using DiscoverySessionManager::HasAtLeastOneDiscoveryClient;
diff --git a/chromeos/services/bluetooth_config/fake_discovery_session_status_observer.cc b/chromeos/services/bluetooth_config/fake_discovery_session_status_observer.cc new file mode 100644 index 0000000..bd4974d --- /dev/null +++ b/chromeos/services/bluetooth_config/fake_discovery_session_status_observer.cc
@@ -0,0 +1,39 @@ +// Copyright 2022 The Chromium 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/services/bluetooth_config/fake_discovery_session_status_observer.h" + +#include <utility> + +#include "base/run_loop.h" + +namespace chromeos { +namespace bluetooth_config { + +FakeDiscoverySessionStatusObserver::FakeDiscoverySessionStatusObserver() = + default; + +FakeDiscoverySessionStatusObserver::~FakeDiscoverySessionStatusObserver() = + default; + +mojo::PendingRemote<mojom::DiscoverySessionStatusObserver> +FakeDiscoverySessionStatusObserver::GeneratePendingRemote() { + return receiver_.BindNewPipeAndPassRemote(); +} + +void FakeDiscoverySessionStatusObserver::DisconnectMojoPipe() { + receiver_.reset(); + + // Allow the disconnection to propagate. + base::RunLoop().RunUntilIdle(); +} + +void FakeDiscoverySessionStatusObserver::OnHasAtLeastOneDiscoverySessionChanged( + bool has_at_least_one_discovery_session) { + has_at_least_one_discovery_session_ = has_at_least_one_discovery_session; + num_discovery_session_changed_calls_++; +} + +} // namespace bluetooth_config +} // namespace chromeos
diff --git a/chromeos/services/bluetooth_config/fake_discovery_session_status_observer.h b/chromeos/services/bluetooth_config/fake_discovery_session_status_observer.h new file mode 100644 index 0000000..eb95ba5 --- /dev/null +++ b/chromeos/services/bluetooth_config/fake_discovery_session_status_observer.h
@@ -0,0 +1,52 @@ +// Copyright 2022 The Chromium 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_SERVICES_BLUETOOTH_CONFIG_FAKE_DISCOVERY_SESSION_STATUS_OBSERVER_H_ +#define CHROMEOS_SERVICES_BLUETOOTH_CONFIG_FAKE_DISCOVERY_SESSION_STATUS_OBSERVER_H_ + +#include "base/run_loop.h" +#include "chromeos/services/bluetooth_config/public/mojom/cros_bluetooth_config.mojom.h" +#include "mojo/public/cpp/bindings/pending_remote.h" +#include "mojo/public/cpp/bindings/receiver.h" + +namespace chromeos { +namespace bluetooth_config { + +class FakeDiscoverySessionStatusObserver + : public mojom::DiscoverySessionStatusObserver { + public: + FakeDiscoverySessionStatusObserver(); + ~FakeDiscoverySessionStatusObserver() override; + + // Generates a PendingRemote associated with this object. To disconnect the + // associated Mojo pipe, use DisconnectMojoPipe(). + mojo::PendingRemote<mojom::DiscoverySessionStatusObserver> + GeneratePendingRemote(); + + // Disconnects the Mojo pipe associated with a PendingRemote returned by + // GeneratePendingRemote(). + void DisconnectMojoPipe(); + + bool has_at_least_one_discovery_session() const { + return has_at_least_one_discovery_session_; + } + + int num_discovery_session_changed_calls() const { + return num_discovery_session_changed_calls_; + } + + private: + // mojom::DiscoverySessionStatusObserver: + void OnHasAtLeastOneDiscoverySessionChanged( + bool has_at_least_one_discovery_session) override; + + bool has_at_least_one_discovery_session_ = false; + int num_discovery_session_changed_calls_ = 0; + mojo::Receiver<mojom::DiscoverySessionStatusObserver> receiver_{this}; +}; + +} // namespace bluetooth_config +} // namespace chromeos + +#endif // CHROMEOS_SERVICES_BLUETOOTH_CONFIG_FAKE_DISCOVERY_SESSION_STATUS_OBSERVER_H_
diff --git a/chromeos/services/bluetooth_config/public/mojom/cros_bluetooth_config.mojom b/chromeos/services/bluetooth_config/public/mojom/cros_bluetooth_config.mojom index 5e84734..b35a8450 100644 --- a/chromeos/services/bluetooth_config/public/mojom/cros_bluetooth_config.mojom +++ b/chromeos/services/bluetooth_config/public/mojom/cros_bluetooth_config.mojom
@@ -173,6 +173,14 @@ OnDeviceDisconnected(PairedBluetoothDeviceProperties device); }; +// Observer for changes to starting/stopping Discovery Sessions. +interface DiscoverySessionStatusObserver { + // Invoked when the number of discovery sessions changes from 0 to 1 + // or vice versa. + OnHasAtLeastOneDiscoverySessionChanged( + bool has_at_least_one_discovery_session); +}; + // Provided to the pairing UI to handle keys that have been entered // on the user's keyboard during a pairing attempt which requires // that the user types in a PIN or passkey. @@ -294,6 +302,12 @@ ObserveDeviceStatusChanges( pending_remote<BluetoothDeviceStatusObserver> observer); + // Invokes OnHasAtLeastOneDiscoverySessionChanged() when the number of + // discovery sessions changes from 0 to 1 or vice versa. To stop observing, + // disconnect |observer|. + ObserveDiscoverySessionStatusChanges( + pending_remote<DiscoverySessionStatusObserver> observer); + // Turns Bluetooth on or off. If Bluetooth is unavailable or if it is // not currently modifiable, this function is a no-op. SetBluetoothEnabledState(bool enabled);
diff --git a/components/autofill/core/common/autofill_features.cc b/components/autofill/core/common/autofill_features.cc index 69a07a92..eb24224 100644 --- a/components/autofill/core/common/autofill_features.cc +++ b/components/autofill/core/common/autofill_features.cc
@@ -400,6 +400,12 @@ const base::Feature kAutofillServerCommunication{ "AutofillServerCommunication", base::FEATURE_ENABLED_BY_DEFAULT}; +// Controls whether Autofill may fill across origins as part of the +// AutofillAcrossIframes experiment. +// TODO(crbug.com/1220038): Clean up when launched. +const base::Feature kAutofillSharedAutofill{"AutofillSharedAutofill", + base::FEATURE_DISABLED_BY_DEFAULT}; + // Controls attaching the autofill type predictions to their respective // element in the DOM. const base::Feature kAutofillShowTypePredictions{
diff --git a/components/autofill/core/common/autofill_features.h b/components/autofill/core/common/autofill_features.h index 08fe889..91a9e1c 100644 --- a/components/autofill/core/common/autofill_features.h +++ b/components/autofill/core/common/autofill_features.h
@@ -145,6 +145,8 @@ COMPONENT_EXPORT(AUTOFILL) extern const base::Feature kAutofillServerCommunication; COMPONENT_EXPORT(AUTOFILL) +extern const base::Feature kAutofillSharedAutofill; +COMPONENT_EXPORT(AUTOFILL) extern const base::Feature kAutofillShowTypePredictions; COMPONENT_EXPORT(AUTOFILL) extern const base::Feature kAutofillSilentProfileUpdateForInsufficientImport;
diff --git a/components/browser_ui/strings/android/browser_ui_strings.grd b/components/browser_ui/strings/android/browser_ui_strings.grd index 47892a3..bb2d4667 100644 --- a/components/browser_ui/strings/android/browser_ui_strings.grd +++ b/components/browser_ui/strings/android/browser_ui_strings.grd
@@ -270,6 +270,9 @@ <message name="IDS_SEARCH" desc="The label for a search button."> Search </message> + <message name="IDS_SETTINGS" desc="Title for Chrome's Settings."> + Settings + </message> <message name="IDS_SHOW_INFO" desc="The label for a info button to show info."> Show Info </message>
diff --git a/components/browsing_data/content/browsing_data_helper.cc b/components/browsing_data/content/browsing_data_helper.cc index 657187e..8d7c317 100644 --- a/components/browsing_data/content/browsing_data_helper.cc +++ b/components/browsing_data/content/browsing_data_helper.cc
@@ -174,6 +174,10 @@ delete_end, HostContentSettingsMap::PatternSourcePredicate()); host_content_settings_map->ClearSettingsForOneTypeWithPredicate( + ContentSettingsType::FEDERATED_IDENTITY_API, delete_begin, delete_end, + HostContentSettingsMap::PatternSourcePredicate()); + + host_content_settings_map->ClearSettingsForOneTypeWithPredicate( ContentSettingsType::FEDERATED_IDENTITY_REQUEST, delete_begin, delete_end, HostContentSettingsMap::PatternSourcePredicate());
diff --git a/components/component_updater/installer_policies/client_side_phishing_component_installer_policy.cc b/components/component_updater/installer_policies/client_side_phishing_component_installer_policy.cc index 09f45c67..1d56ab32 100644 --- a/components/component_updater/installer_policies/client_side_phishing_component_installer_policy.cc +++ b/components/component_updater/installer_policies/client_side_phishing_component_installer_policy.cc
@@ -13,7 +13,6 @@ #include "base/callback.h" #include "base/files/file_path.h" #include "base/files/file_util.h" -#include "base/metrics/histogram_functions.h" #include "base/values.h" #include "base/version.h" #include "components/component_updater/component_installer.h" @@ -30,9 +29,6 @@ 0xc0, 0x22, 0xc8, 0xd2, 0xe0, 0xe3, 0xe2, 0x33, 0x88, 0x1f, 0x09, 0x6d, 0xde, 0x65, 0x6a, 0x83, 0x32, 0x71, 0x52, 0x6e, 0x77}; -const char kClientSidePhishingExtensionId[] = - "imefjhfbkmcmebodilednhmaccmincoa"; - } // namespace const base::FilePath::CharType kClientModelBinaryPbFileName[] = @@ -42,22 +38,14 @@ ClientSidePhishingComponentInstallerPolicy:: ClientSidePhishingComponentInstallerPolicy( - ComponentUpdateService* cus, const ReadFilesCallback& read_files_callback, const InstallerAttributesCallback& installer_attributes_callback) - : cus_(cus), - read_files_callback_(std::move(read_files_callback)), + : read_files_callback_(std::move(read_files_callback)), installer_attributes_callback_(std::move(installer_attributes_callback)) { - // `cus_` can be nullptr on android_webview. - if (cus_) - cus_->AddObserver(this); } ClientSidePhishingComponentInstallerPolicy:: - ~ClientSidePhishingComponentInstallerPolicy() { - if (cus_) - cus_->RemoveObserver(this); -} + ~ClientSidePhishingComponentInstallerPolicy() = default; // static void ClientSidePhishingComponentInstallerPolicy::GetPublicHash( @@ -122,18 +110,4 @@ return installer_attributes_callback_.Run(); } -void ClientSidePhishingComponentInstallerPolicy::OnEvent( - ComponentUpdateService::Observer::Events event, - const std::string& id) { - if (id != kClientSidePhishingExtensionId) - return; - - if (event == ComponentUpdateService::Observer::Events::COMPONENT_UPDATED) { - base::UmaHistogramBoolean("SBClientPhishing.ComponentUpdated", true); - } else if (event == - ComponentUpdateService::Observer::Events::COMPONENT_NOT_UPDATED) { - base::UmaHistogramBoolean("SBClientPhishing.ComponentUpdated", false); - } -} - } // namespace component_updater
diff --git a/components/component_updater/installer_policies/client_side_phishing_component_installer_policy.h b/components/component_updater/installer_policies/client_side_phishing_component_installer_policy.h index 98dea7f7..825c8ea1 100644 --- a/components/component_updater/installer_policies/client_side_phishing_component_installer_policy.h +++ b/components/component_updater/installer_policies/client_side_phishing_component_installer_policy.h
@@ -12,7 +12,6 @@ #include "base/callback.h" #include "components/component_updater/component_installer.h" -#include "components/component_updater/component_updater_service.h" namespace base { class FilePath; @@ -26,8 +25,7 @@ extern const base::FilePath::CharType kVisualTfLiteModelFileName[]; class ClientSidePhishingComponentInstallerPolicy - : public ComponentInstallerPolicy, - public component_updater::ComponentUpdateService::Observer { + : public ComponentInstallerPolicy { public: // A callback to read model files from the given install path and populate the // model appropriately, used to customize the behaviour of `ComponentReady`. @@ -39,7 +37,6 @@ base::RepeatingCallback<update_client::InstallerAttributes()>; ClientSidePhishingComponentInstallerPolicy( - ComponentUpdateService* cus, const ReadFilesCallback& read_files_callback, const InstallerAttributesCallback& installer_attributes_callback); ClientSidePhishingComponentInstallerPolicy( @@ -50,11 +47,6 @@ static void GetPublicHash(std::vector<uint8_t>* hash); - // ComponentUpdateService::Observer implementation. - void OnEvent( - component_updater::ComponentUpdateService::Observer::Events event, - const std::string& id) override; - private: // The following methods override ComponentInstallerPolicy. bool SupportsGroupPolicyEnabledComponentUpdates() const override; @@ -75,7 +67,6 @@ static base::FilePath GetInstalledPath(const base::FilePath& base); - component_updater::ComponentUpdateService* cus_; ReadFilesCallback read_files_callback_; InstallerAttributesCallback installer_attributes_callback_; };
diff --git a/components/content_settings/core/browser/content_settings_registry.cc b/components/content_settings/core/browser/content_settings_registry.cc index 3673363..b5e821f 100644 --- a/components/content_settings/core/browser/content_settings_registry.cc +++ b/components/content_settings/core/browser/content_settings_registry.cc
@@ -644,6 +644,16 @@ ContentSettingsInfo::INHERIT_IN_INCOGNITO, ContentSettingsInfo::PERSISTENT, ContentSettingsInfo::EXCEPTIONS_ON_SECURE_AND_INSECURE_ORIGINS); + + Register(ContentSettingsType::FEDERATED_IDENTITY_API, "webid-api", + CONTENT_SETTING_ALLOW, WebsiteSettingsInfo::UNSYNCABLE, + AllowlistedSchemes(), + ValidSettings(CONTENT_SETTING_ALLOW, CONTENT_SETTING_BLOCK), + WebsiteSettingsInfo::SINGLE_ORIGIN_ONLY_SCOPE, + WebsiteSettingsRegistry::ALL_PLATFORMS, + ContentSettingsInfo::INHERIT_IN_INCOGNITO, + ContentSettingsInfo::PERSISTENT, + ContentSettingsInfo::EXCEPTIONS_ON_SECURE_ORIGINS_ONLY); } void ContentSettingsRegistry::Register(
diff --git a/components/content_settings/core/browser/content_settings_registry_unittest.cc b/components/content_settings/core/browser/content_settings_registry_unittest.cc index 2330253..a816caa 100644 --- a/components/content_settings/core/browser/content_settings_registry_unittest.cc +++ b/components/content_settings/core/browser/content_settings_registry_unittest.cc
@@ -200,6 +200,11 @@ registry()->Get(ContentSettingsType::INSECURE_PRIVATE_NETWORK); EXPECT_EQ(CONTENT_SETTING_BLOCK, insecure_private_network->GetInitialDefaultSetting()); + + const ContentSettingsInfo* federated_identity = + registry()->Get(ContentSettingsType::FEDERATED_IDENTITY_API); + EXPECT_EQ(CONTENT_SETTING_ALLOW, + federated_identity->GetInitialDefaultSetting()); } } // namespace content_settings
diff --git a/components/content_settings/core/common/content_settings.cc b/components/content_settings/core/common/content_settings.cc index 2412212b..e08368c 100644 --- a/components/content_settings/core/common/content_settings.cc +++ b/components/content_settings/core/common/content_settings.cc
@@ -102,6 +102,7 @@ {ContentSettingsType::FEDERATED_IDENTITY_ACTIVE_SESSION, 82}, {ContentSettingsType::AUTO_DARK_WEB_CONTENT, 83}, {ContentSettingsType::REQUEST_DESKTOP_SITE, 84}, + {ContentSettingsType::FEDERATED_IDENTITY_API, 85}, }; } // namespace
diff --git a/components/content_settings/core/common/content_settings_types.h b/components/content_settings/core/common/content_settings_types.h index c73c004..c110a033 100644 --- a/components/content_settings/core/common/content_settings_types.h +++ b/components/content_settings/core/common/content_settings_types.h
@@ -281,6 +281,10 @@ // site instead of the mobile one. REQUEST_DESKTOP_SITE, + // Setting to indicate whether browser should allow signing into a website via + // the browser FedCM API. + FEDERATED_IDENTITY_API, + NUM_TYPES, };
diff --git a/components/download/public/common/download_features.cc b/components/download/public/common/download_features.cc index 9610df2..602b950 100644 --- a/components/download/public/common/download_features.cc +++ b/components/download/public/common/download_features.cc
@@ -69,9 +69,6 @@ const base::Feature kAllowFileBufferSizeControl{ "AllowFileBufferSizeControl", base::FEATURE_ENABLED_BY_DEFAULT}; -const base::Feature kAllowSavePackageScanning{"AllowSavePackageScanning", - base::FEATURE_ENABLED_BY_DEFAULT}; - const base::Feature kIncognitoDownloadsWarning{ "IncognitoDownloadsWarning", base::FEATURE_DISABLED_BY_DEFAULT};
diff --git a/components/download/public/common/download_features.h b/components/download/public/common/download_features.h index 72388eedc..42b8f5b 100644 --- a/components/download/public/common/download_features.h +++ b/components/download/public/common/download_features.h
@@ -71,9 +71,6 @@ COMPONENTS_DOWNLOAD_EXPORT extern const base::Feature kAllowFileBufferSizeControl; -// Whether to allow scanning save packages before saving them to disk. -COMPONENTS_DOWNLOAD_EXPORT extern const base::Feature kAllowSavePackageScanning; - // Whether to show warning when downloading in incognito. COMPONENTS_DOWNLOAD_EXPORT extern const base::Feature kIncognitoDownloadsWarning;
diff --git a/components/favicon/core/favicon_database_unittest.cc b/components/favicon/core/favicon_database_unittest.cc index 81bfc3c..4dd1041 100644 --- a/components/favicon/core/favicon_database_unittest.cc +++ b/components/favicon/core/favicon_database_unittest.cc
@@ -1034,7 +1034,7 @@ { sql::Database raw_db; EXPECT_TRUE(raw_db.Open(file_name_)); - ASSERT_EQ("ok", sql::test::IntegrityCheck(&raw_db)); + ASSERT_EQ("ok", sql::test::IntegrityCheck(raw_db)); } static const char kIndexName[] = "icon_mapping_page_url_idx"; ASSERT_TRUE(sql::test::CorruptIndexRootPage(file_name_, kIndexName)); @@ -1043,7 +1043,7 @@ { sql::Database raw_db; EXPECT_TRUE(raw_db.Open(file_name_)); - ASSERT_NE("ok", sql::test::IntegrityCheck(&raw_db)); + EXPECT_NE("ok", sql::test::IntegrityCheck(raw_db)); } // Open the database and access the corrupt index. @@ -1066,7 +1066,7 @@ { sql::Database raw_db; EXPECT_TRUE(raw_db.Open(file_name_)); - ASSERT_EQ("ok", sql::test::IntegrityCheck(&raw_db)); + ASSERT_EQ("ok", sql::test::IntegrityCheck(raw_db)); // Check that the expected tables exist. VerifyTablesAndColumns(&raw_db); @@ -1091,12 +1091,14 @@ // Database is unusable at the SQLite level. { - sql::test::ScopedErrorExpecter expecter; - expecter.ExpectError(SQLITE_CORRUPT); sql::Database raw_db; - EXPECT_TRUE(raw_db.Open(file_name_)); - EXPECT_FALSE(raw_db.IsSQLValid("PRAGMA integrity_check")); - ASSERT_TRUE(expecter.SawExpectedErrors()); + { + sql::test::ScopedErrorExpecter expecter; + expecter.ExpectError(SQLITE_CORRUPT); + EXPECT_TRUE(raw_db.Open(file_name_)); + EXPECT_TRUE(expecter.SawExpectedErrors()); + } + EXPECT_EQ("ok", sql::test::IntegrityCheck(raw_db)); } // Database should be recovered during open. @@ -1127,7 +1129,7 @@ { sql::Database raw_db; EXPECT_TRUE(raw_db.Open(file_name_)); - ASSERT_EQ("ok", sql::test::IntegrityCheck(&raw_db)); + ASSERT_EQ("ok", sql::test::IntegrityCheck(raw_db)); } static const char kIndexName[] = "icon_mapping_page_url_idx"; ASSERT_TRUE(sql::test::CorruptIndexRootPage(file_name_, kIndexName)); @@ -1136,7 +1138,7 @@ { sql::Database raw_db; EXPECT_TRUE(raw_db.Open(file_name_)); - ASSERT_NE("ok", sql::test::IntegrityCheck(&raw_db)); + EXPECT_NE("ok", sql::test::IntegrityCheck(raw_db)); } // Open the database and access the corrupt index. Note that this upgrades @@ -1151,7 +1153,7 @@ // will recover the database and poison the handle, so the outer call // fails. EXPECT_FALSE(db.GetIconMappingsForPageURL(kPageUrl2, nullptr)); - ASSERT_TRUE(expecter.SawExpectedErrors()); + EXPECT_TRUE(expecter.SawExpectedErrors()); } } @@ -1159,7 +1161,7 @@ { sql::Database raw_db; EXPECT_TRUE(raw_db.Open(file_name_)); - ASSERT_EQ("ok", sql::test::IntegrityCheck(&raw_db)); + ASSERT_EQ("ok", sql::test::IntegrityCheck(raw_db)); // Check that the expected tables exist. VerifyTablesAndColumns(&raw_db); @@ -1184,12 +1186,14 @@ // Database is unusable at the SQLite level. { - sql::test::ScopedErrorExpecter expecter; - expecter.ExpectError(SQLITE_CORRUPT); sql::Database raw_db; - EXPECT_TRUE(raw_db.Open(file_name_)); - EXPECT_FALSE(raw_db.IsSQLValid("PRAGMA integrity_check")); - ASSERT_TRUE(expecter.SawExpectedErrors()); + { + sql::test::ScopedErrorExpecter expecter; + expecter.ExpectError(SQLITE_CORRUPT); + ASSERT_TRUE(raw_db.Open(file_name_)); + EXPECT_TRUE(expecter.SawExpectedErrors()); + } + EXPECT_EQ("ok", sql::test::IntegrityCheck(raw_db)); } // Database should be recovered during open. @@ -1199,7 +1203,7 @@ sql::test::ScopedErrorExpecter expecter; expecter.ExpectError(SQLITE_CORRUPT); ASSERT_EQ(sql::INIT_OK, db.Init(file_name_)); - ASSERT_TRUE(expecter.SawExpectedErrors()); + EXPECT_TRUE(expecter.SawExpectedErrors()); } EXPECT_TRUE(CheckPageHasIcon(&db, kPageUrl1, @@ -1223,21 +1227,23 @@ // Database is unusable at the SQLite level. { - sql::test::ScopedErrorExpecter expecter; - expecter.ExpectError(SQLITE_CORRUPT); sql::Database raw_db; - EXPECT_TRUE(raw_db.Open(file_name_)); - EXPECT_FALSE(raw_db.IsSQLValid("PRAGMA integrity_check")); - ASSERT_TRUE(expecter.SawExpectedErrors()); + { + sql::test::ScopedErrorExpecter expecter; + expecter.ExpectError(SQLITE_CORRUPT); + EXPECT_TRUE(raw_db.Open(file_name_)); + EXPECT_TRUE(expecter.SawExpectedErrors()); + } + EXPECT_EQ("ok", sql::test::IntegrityCheck(raw_db)); } // Database open should succeed. { + FaviconDatabase db; sql::test::ScopedErrorExpecter expecter; expecter.ExpectError(SQLITE_CORRUPT); - FaviconDatabase db; ASSERT_EQ(sql::INIT_OK, db.Init(file_name_)); - ASSERT_TRUE(expecter.SawExpectedErrors()); + EXPECT_TRUE(expecter.SawExpectedErrors()); } // The database should be usable at the SQLite level, with a current schema @@ -1245,7 +1251,7 @@ { sql::Database raw_db; EXPECT_TRUE(raw_db.Open(file_name_)); - ASSERT_EQ("ok", sql::test::IntegrityCheck(&raw_db)); + ASSERT_EQ("ok", sql::test::IntegrityCheck(raw_db)); // Check that the expected tables exist. VerifyTablesAndColumns(&raw_db); @@ -1267,12 +1273,14 @@ // Database is unusable at the SQLite level. { - sql::test::ScopedErrorExpecter expecter; - expecter.ExpectError(SQLITE_CORRUPT); sql::Database raw_db; - EXPECT_TRUE(raw_db.Open(file_name_)); - EXPECT_FALSE(raw_db.IsSQLValid("PRAGMA integrity_check")); - ASSERT_TRUE(expecter.SawExpectedErrors()); + { + sql::test::ScopedErrorExpecter expecter; + expecter.ExpectError(SQLITE_CORRUPT); + EXPECT_TRUE(raw_db.Open(file_name_)); + EXPECT_TRUE(expecter.SawExpectedErrors()); + } + EXPECT_EQ("ok", sql::test::IntegrityCheck(raw_db)); } // Database open should succeed. @@ -1289,7 +1297,7 @@ { sql::Database raw_db; EXPECT_TRUE(raw_db.Open(file_name_)); - ASSERT_EQ("ok", sql::test::IntegrityCheck(&raw_db)); + ASSERT_EQ("ok", sql::test::IntegrityCheck(raw_db)); // Check that the expected tables exist. VerifyTablesAndColumns(&raw_db);
diff --git a/components/history/core/browser/top_sites_database_unittest.cc b/components/history/core/browser/top_sites_database_unittest.cc index fde3d29..8f66825 100644 --- a/components/history/core/browser/top_sites_database_unittest.cc +++ b/components/history/core/browser/top_sites_database_unittest.cc
@@ -148,85 +148,21 @@ // data. TEST_F(TopSitesDatabaseTest, Recovery1) { // Create an example database. - EXPECT_TRUE(CreateDatabaseFromSQL(file_name_, "TopSites.v1.sql")); + ASSERT_TRUE(CreateDatabaseFromSQL(file_name_, "TopSites.v1.sql")); // Corrupt the database by adjusting the header size. EXPECT_TRUE(sql::test::CorruptSizeInHeader(file_name_)); // Database is unusable at the SQLite level. { - sql::test::ScopedErrorExpecter expecter; - expecter.ExpectError(SQLITE_CORRUPT); - sql::Database raw_db; - EXPECT_TRUE(raw_db.Open(file_name_)); - EXPECT_FALSE(raw_db.IsSQLValid("PRAGMA integrity_check")); - ASSERT_TRUE(expecter.SawExpectedErrors()); - } - - // Corruption should be detected and recovered during Init(). - { - sql::test::ScopedErrorExpecter expecter; - expecter.ExpectError(SQLITE_CORRUPT); - - TopSitesDatabase db; - ASSERT_TRUE(db.Init(file_name_)); - VerifyTablesAndColumns(db.db_.get()); - VerifyDatabaseEmpty(db.db_.get()); - - ASSERT_TRUE(expecter.SawExpectedErrors()); - } -} - -// Version 2 is deprecated, the resulting schema should be current, with no -// data. -TEST_F(TopSitesDatabaseTest, Recovery2) { - // Create an example database. - EXPECT_TRUE(CreateDatabaseFromSQL(file_name_, "TopSites.v2.sql")); - - // Corrupt the database by adjusting the header. - EXPECT_TRUE(sql::test::CorruptSizeInHeader(file_name_)); - - // Database is unusable at the SQLite level. - { - sql::test::ScopedErrorExpecter expecter; - expecter.ExpectError(SQLITE_CORRUPT); - sql::Database raw_db; - EXPECT_TRUE(raw_db.Open(file_name_)); - EXPECT_FALSE(raw_db.IsSQLValid("PRAGMA integrity_check")); - ASSERT_TRUE(expecter.SawExpectedErrors()); - } - - // Corruption should be detected and recovered during Init(). - { - sql::test::ScopedErrorExpecter expecter; - expecter.ExpectError(SQLITE_CORRUPT); - - TopSitesDatabase db; - ASSERT_TRUE(db.Init(file_name_)); - VerifyTablesAndColumns(db.db_.get()); - VerifyDatabaseEmpty(db.db_.get()); - - ASSERT_TRUE(expecter.SawExpectedErrors()); - } -} - -TEST_F(TopSitesDatabaseTest, Recovery3_CorruptHeader) { - // Create an example database. - EXPECT_TRUE(CreateDatabaseFromSQL(file_name_, "TopSites.v3.sql")); - - // Corrupt the database by adjusting the header. - EXPECT_TRUE(sql::test::CorruptSizeInHeader(file_name_)); - - // Database is unusable at the SQLite level. - { sql::Database raw_db; { sql::test::ScopedErrorExpecter expecter; expecter.ExpectError(SQLITE_CORRUPT); - EXPECT_TRUE(raw_db.Open(file_name_)); + ASSERT_TRUE(raw_db.Open(file_name_)); EXPECT_TRUE(expecter.SawExpectedErrors()); } - EXPECT_FALSE(raw_db.IsSQLValid("PRAGMA integrity_check")); + EXPECT_EQ("ok", sql::test::IntegrityCheck(raw_db)); } // Corruption should be detected and recovered during Init(). @@ -236,7 +172,75 @@ sql::test::ScopedErrorExpecter expecter; expecter.ExpectError(SQLITE_CORRUPT); ASSERT_TRUE(db.Init(file_name_)); - ASSERT_TRUE(expecter.SawExpectedErrors()); + EXPECT_TRUE(expecter.SawExpectedErrors()); + } + VerifyTablesAndColumns(db.db_.get()); + VerifyDatabaseEmpty(db.db_.get()); + } +} + +// Version 2 is deprecated, the resulting schema should be current, with no +// data. +TEST_F(TopSitesDatabaseTest, Recovery2) { + // Create an example database. + ASSERT_TRUE(CreateDatabaseFromSQL(file_name_, "TopSites.v2.sql")); + + // Corrupt the database by adjusting the header. + EXPECT_TRUE(sql::test::CorruptSizeInHeader(file_name_)); + + // Database is unusable at the SQLite level. + { + sql::Database raw_db; + { + sql::test::ScopedErrorExpecter expecter; + expecter.ExpectError(SQLITE_CORRUPT); + ASSERT_TRUE(raw_db.Open(file_name_)); + EXPECT_TRUE(expecter.SawExpectedErrors()); + } + EXPECT_EQ("ok", sql::test::IntegrityCheck(raw_db)); + } + + // Corruption should be detected and recovered during Init(). + { + TopSitesDatabase db; + { + sql::test::ScopedErrorExpecter expecter; + expecter.ExpectError(SQLITE_CORRUPT); + ASSERT_TRUE(db.Init(file_name_)); + EXPECT_TRUE(expecter.SawExpectedErrors()); + } + VerifyTablesAndColumns(db.db_.get()); + VerifyDatabaseEmpty(db.db_.get()); + } +} + +TEST_F(TopSitesDatabaseTest, Recovery3_CorruptHeader) { + // Create an example database. + ASSERT_TRUE(CreateDatabaseFromSQL(file_name_, "TopSites.v3.sql")); + + // Corrupt the database by adjusting the header. + EXPECT_TRUE(sql::test::CorruptSizeInHeader(file_name_)); + + // Database is unusable at the SQLite level. + { + sql::Database raw_db; + { + sql::test::ScopedErrorExpecter expecter; + expecter.ExpectError(SQLITE_CORRUPT); + ASSERT_TRUE(raw_db.Open(file_name_)); + EXPECT_TRUE(expecter.SawExpectedErrors()); + } + EXPECT_EQ("ok", sql::test::IntegrityCheck(raw_db)); + } + + // Corruption should be detected and recovered during Init(). + { + TopSitesDatabase db; + { + sql::test::ScopedErrorExpecter expecter; + expecter.ExpectError(SQLITE_CORRUPT); + ASSERT_TRUE(db.Init(file_name_)); + EXPECT_TRUE(expecter.SawExpectedErrors()); } MostVisitedURLList urls; @@ -249,13 +253,13 @@ { sql::Database raw_db; EXPECT_TRUE(raw_db.Open(file_name_)); - ASSERT_EQ("ok", sql::test::IntegrityCheck(&raw_db)); + EXPECT_EQ("ok", sql::test::IntegrityCheck(raw_db)); } } TEST_F(TopSitesDatabaseTest, Recovery3to4_CorruptIndex) { // Create an example database. - EXPECT_TRUE(CreateDatabaseFromSQL(file_name_, "TopSites.v3.sql")); + ASSERT_TRUE(CreateDatabaseFromSQL(file_name_, "TopSites.v3.sql")); // Previously, this was part of a monolithic Recovery3 test that aimed to // cover both header corruption and index corruption. However, while testing @@ -276,8 +280,8 @@ // check. { sql::Database raw_db; - EXPECT_TRUE(raw_db.Open(file_name_)); - ASSERT_NE("ok", sql::test::IntegrityCheck(&raw_db)); + ASSERT_TRUE(raw_db.Open(file_name_)); + EXPECT_NE("ok", sql::test::IntegrityCheck(raw_db)); } // Open the database and access the corrupt index. @@ -302,8 +306,8 @@ // Check that the database is recovered at the SQLite level. { sql::Database raw_db; - EXPECT_TRUE(raw_db.Open(file_name_)); - ASSERT_EQ("ok", sql::test::IntegrityCheck(&raw_db)); + ASSERT_TRUE(raw_db.Open(file_name_)); + ASSERT_EQ("ok", sql::test::IntegrityCheck(raw_db)); } // After recovery, the database accesses won't throw errors. Recovery should @@ -339,10 +343,10 @@ { sql::test::ScopedErrorExpecter expecter; expecter.ExpectError(SQLITE_CORRUPT); - EXPECT_TRUE(raw_db.Open(file_name_)); + ASSERT_TRUE(raw_db.Open(file_name_)); EXPECT_TRUE(expecter.SawExpectedErrors()); } - EXPECT_FALSE(raw_db.IsSQLValid("PRAGMA integrity_check")); + EXPECT_EQ("ok", sql::test::IntegrityCheck(raw_db)); } // Corruption should be detected and recovered during Init(). @@ -352,7 +356,7 @@ sql::test::ScopedErrorExpecter expecter; expecter.ExpectError(SQLITE_CORRUPT); ASSERT_TRUE(db.Init(file_name_)); - ASSERT_TRUE(expecter.SawExpectedErrors()); + EXPECT_TRUE(expecter.SawExpectedErrors()); } MostVisitedURLList urls; @@ -364,25 +368,25 @@ // Double-check database integrity. { sql::Database raw_db; - EXPECT_TRUE(raw_db.Open(file_name_)); - ASSERT_EQ("ok", sql::test::IntegrityCheck(&raw_db)); + ASSERT_TRUE(raw_db.Open(file_name_)); + EXPECT_EQ("ok", sql::test::IntegrityCheck(raw_db)); } } TEST_F(TopSitesDatabaseTest, Recovery4_CorruptIndex) { // Create an example database. - EXPECT_TRUE(CreateDatabaseFromSQL(file_name_, "TopSites.v4.sql")); + ASSERT_TRUE(CreateDatabaseFromSQL(file_name_, "TopSites.v4.sql")); // Corrupt the thumnails.url auto-index. static const char kIndexName[] = "sqlite_autoindex_top_sites_1"; - ASSERT_TRUE(sql::test::CorruptIndexRootPage(file_name_, kIndexName)); + EXPECT_TRUE(sql::test::CorruptIndexRootPage(file_name_, kIndexName)); // SQLite can operate on the database, but notices the corruption in integrity // check. { sql::Database raw_db; - EXPECT_TRUE(raw_db.Open(file_name_)); - ASSERT_NE("ok", sql::test::IntegrityCheck(&raw_db)); + ASSERT_TRUE(raw_db.Open(file_name_)); + EXPECT_NE("ok", sql::test::IntegrityCheck(raw_db)); } // Open the database and access the corrupt index. @@ -400,15 +404,15 @@ EXPECT_EQ(TopSitesDatabase::kRankOfNonExistingURL, db.GetURLRank(MostVisitedURL(kUrl1, std::u16string()))); - ASSERT_TRUE(expecter.SawExpectedErrors()); + EXPECT_TRUE(expecter.SawExpectedErrors()); } } // Check that the database is recovered at the SQLite level. { sql::Database raw_db; - EXPECT_TRUE(raw_db.Open(file_name_)); - ASSERT_EQ("ok", sql::test::IntegrityCheck(&raw_db)); + ASSERT_TRUE(raw_db.Open(file_name_)); + ASSERT_EQ("ok", sql::test::IntegrityCheck(raw_db)); } // After recovery, the database accesses won't throw errors. Recovery should @@ -433,26 +437,26 @@ TEST_F(TopSitesDatabaseTest, Recovery4_CorruptIndexAndLostRow) { // Create an example database. - EXPECT_TRUE(CreateDatabaseFromSQL(file_name_, "TopSites.v4.sql")); + ASSERT_TRUE(CreateDatabaseFromSQL(file_name_, "TopSites.v4.sql")); // Delete a row. { sql::Database raw_db; - EXPECT_TRUE(raw_db.Open(file_name_)); + ASSERT_TRUE(raw_db.Open(file_name_)); EXPECT_TRUE( raw_db.Execute("DELETE FROM top_sites WHERE url = " "'http://www.google.com/chrome/intl/en/welcome.html'")); } // Corrupt the thumnails.url auto-index. static const char kIndexName[] = "sqlite_autoindex_top_sites_1"; - ASSERT_TRUE(sql::test::CorruptIndexRootPage(file_name_, kIndexName)); + EXPECT_TRUE(sql::test::CorruptIndexRootPage(file_name_, kIndexName)); // SQLite can operate on the database, but notices the corruption in integrity // check. { sql::Database raw_db; - EXPECT_TRUE(raw_db.Open(file_name_)); - ASSERT_NE("ok", sql::test::IntegrityCheck(&raw_db)); + ASSERT_TRUE(raw_db.Open(file_name_)); + EXPECT_NE("ok", sql::test::IntegrityCheck(raw_db)); } // Open the database and access the corrupt index. @@ -470,15 +474,15 @@ EXPECT_EQ(TopSitesDatabase::kRankOfNonExistingURL, db.GetURLRank(MostVisitedURL(kUrl0, std::u16string()))); - ASSERT_TRUE(expecter.SawExpectedErrors()); + EXPECT_TRUE(expecter.SawExpectedErrors()); } } // Check that the database is recovered at the SQLite level. { sql::Database raw_db; - EXPECT_TRUE(raw_db.Open(file_name_)); - ASSERT_EQ("ok", sql::test::IntegrityCheck(&raw_db)); + ASSERT_TRUE(raw_db.Open(file_name_)); + ASSERT_EQ("ok", sql::test::IntegrityCheck(raw_db)); } // After recovery, the database accesses won't throw errors. Recovery should
diff --git a/components/metrics/serialization/serialization_utils.cc b/components/metrics/serialization/serialization_utils.cc index 5091a7a..882bdf2 100644 --- a/components/metrics/serialization/serialization_utils.cc +++ b/components/metrics/serialization/serialization_utils.cc
@@ -26,26 +26,6 @@ namespace metrics { namespace { - -// Record number of reads on successful reads. Errors (file can't be opened, -// file can't be flock'ed) do not generate a sample. (If the file is found to -// be corrupt partway through, the number of successfully read entries is -// recorded.) -void RecordNumberOfReadsMetric(int num_reads) { - // 100,000 to match kMaxMessagesPerRead. - base::UmaHistogramCounts100000("UMA.ReadAndTruncateMetricsFromFile.ReadCount", - num_reads); -} - -// Record number of elements discarded because the file is too large. Errors -// (file can't be opened, file can't be flock'ed) do not generate a sample. -// (If the file is found to be corrupt partway through, the number of -// successfully read entries is recorded.) -void RecordNumberOfDiscardsMetric(int num_discards) { - base::UmaHistogramCounts1M( - "UMA.ReadAndTruncateMetricsFromFile.DiscardedCount", num_discards); -} - // Reads the next message from |file_descriptor| into |message|. // // |message| will be set to the empty string if no message could be read (EOF) @@ -154,8 +134,6 @@ if (errno == ENOENT) { // File doesn't exist, nothing to collect. This isn't an error, it just // means nothing on the ChromeOS side has written to the file yet. - RecordNumberOfReadsMetric(0); - RecordNumberOfDiscardsMetric(0); } else { DPLOG(ERROR) << "bad metrics file stat: " << filename; } @@ -163,8 +141,6 @@ } if (stat_buf.st_size == 0) { // Also nothing to collect. - RecordNumberOfReadsMetric(0); - RecordNumberOfDiscardsMetric(0); return; } base::ScopedFD fd(open(filename.c_str(), O_RDWR)); @@ -180,13 +156,13 @@ // This processes all messages in the log. When all messages are // read and processed, or an error occurs, or we've read so many that the - // buffer is at risk of overflowing, truncate the file to zero size. - bool read_complete = false; + // buffer is at risk of overflowing, truncate the file to zero size. If we + // hit kMaxMessagesPerRead, don't add them to the vector to avoid memory + // overflow. while (metrics->size() < kMaxMessagesPerRead) { std::string message; if (!ReadMessage(fd.get(), &message)) { - read_complete = true; break; } @@ -195,21 +171,6 @@ metrics->push_back(std::move(sample)); } - // If we hit kMaxMessagesPerRead, count the number of discarded messages for - // the discard metric, but don't add them to the vector to avoid memory - // overflow. - int num_discards = 0; - while (!read_complete) { - std::string message; - if (!ReadMessage(fd.get(), &message)) { - read_complete = true; - } else { - ++num_discards; - } - } - RecordNumberOfDiscardsMetric(num_discards); - RecordNumberOfReadsMetric(metrics->size()); - result = ftruncate(fd.get(), 0); if (result < 0) DPLOG(ERROR) << "truncate metrics log: " << filename;
diff --git a/components/metrics/serialization/serialization_utils_unittest.cc b/components/metrics/serialization/serialization_utils_unittest.cc index 868e1e17..76963a62 100644 --- a/components/metrics/serialization/serialization_utils_unittest.cc +++ b/components/metrics/serialization/serialization_utils_unittest.cc
@@ -191,7 +191,6 @@ } TEST_F(SerializationUtilsTest, WriteReadTest) { - base::HistogramTester histogram_tester; std::unique_ptr<MetricSample> hist = MetricSample::HistogramSample("myhist", 1, 2, 3, 4); std::unique_ptr<MetricSample> crash = MetricSample::CrashSample("mycrash"); @@ -222,15 +221,9 @@ int64_t size = 0; ASSERT_TRUE(base::GetFileSize(filepath(), &size)); ASSERT_EQ(0, size); - - histogram_tester.ExpectUniqueSample( - "UMA.ReadAndTruncateMetricsFromFile.ReadCount", 5, 1); - histogram_tester.ExpectUniqueSample( - "UMA.ReadAndTruncateMetricsFromFile.DiscardedCount", 0, 1); } TEST_F(SerializationUtilsTest, TooManyMessagesTest) { - base::HistogramTester histogram_tester; std::unique_ptr<MetricSample> hist = MetricSample::HistogramSample("myhist", 1, 2, 3, 4); @@ -252,17 +245,9 @@ int64_t size = 0; ASSERT_TRUE(base::GetFileSize(filepath(), &size)); ASSERT_EQ(0, size); - histogram_tester.ExpectUniqueSample( - "UMA.ReadAndTruncateMetricsFromFile.ReadCount", - SerializationUtils::kMaxMessagesPerRead, 1); - histogram_tester.ExpectUniqueSample( - "UMA.ReadAndTruncateMetricsFromFile.DiscardedCount", kDiscardedSamples, - 1); } TEST_F(SerializationUtilsTest, ReadEmptyFile) { - base::HistogramTester histogram_tester; - { // Create a zero-length file and then close file descriptor. base::File file(filepath(), @@ -273,10 +258,6 @@ std::vector<std::unique_ptr<MetricSample>> vect; SerializationUtils::ReadAndTruncateMetricsFromFile(filename(), &vect); EXPECT_THAT(vect, IsEmpty()); - histogram_tester.ExpectUniqueSample( - "UMA.ReadAndTruncateMetricsFromFile.ReadCount", 0, 1); - histogram_tester.ExpectUniqueSample( - "UMA.ReadAndTruncateMetricsFromFile.DiscardedCount", 0, 1); } TEST_F(SerializationUtilsTest, ReadNonExistentFile) { @@ -285,10 +266,6 @@ std::vector<std::unique_ptr<MetricSample>> vect; SerializationUtils::ReadAndTruncateMetricsFromFile(filename(), &vect); EXPECT_THAT(vect, IsEmpty()); - histogram_tester.ExpectUniqueSample( - "UMA.ReadAndTruncateMetricsFromFile.ReadCount", 0, 1); - histogram_tester.ExpectUniqueSample( - "UMA.ReadAndTruncateMetricsFromFile.DiscardedCount", 0, 1); } } // namespace
diff --git a/components/nacl/browser/nacl_process_host.cc b/components/nacl/browser/nacl_process_host.cc index 00d3c9c..3688fad 100644 --- a/components/nacl/browser/nacl_process_host.cc +++ b/components/nacl/browser/nacl_process_host.cc
@@ -62,7 +62,6 @@ #include "ppapi/host/host_factory.h" #include "ppapi/host/ppapi_host.h" #include "ppapi/proxy/ppapi_messages.h" -#include "ppapi/shared_impl/ppapi_constants.h" #include "ppapi/shared_impl/ppapi_nacl_plugin_args.h" #include "sandbox/policy/mojom/sandbox.mojom.h" #include "sandbox/policy/switches.h"
diff --git a/components/page_load_metrics/browser/observers/use_counter_page_load_metrics_observer.cc b/components/page_load_metrics/browser/observers/use_counter_page_load_metrics_observer.cc index a56e3a1f..61fa9c7 100644 --- a/components/page_load_metrics/browser/observers/use_counter_page_load_metrics_observer.cc +++ b/components/page_load_metrics/browser/observers/use_counter_page_load_metrics_observer.cc
@@ -9,6 +9,7 @@ #include "content/public/browser/navigation_handle.h" #include "content/public/browser/render_frame_host.h" #include "services/metrics/public/cpp/ukm_builders.h" +#include "third_party/blink/public/common/user_agent/user_agent_metadata.h" #include "third_party/blink/public/mojom/use_counter/use_counter_feature.mojom.h" using FeatureType = blink::mojom::UseCounterFeatureType; @@ -16,6 +17,8 @@ using WebFeature = blink::mojom::WebFeature; using CSSSampleId = blink::mojom::CSSSampleId; using PermissionsPolicyFeature = blink::mojom::PermissionsPolicyFeature; +using UserAgentOverrideHistogram = + blink::UserAgentOverride::UserAgentOverrideHistogram; namespace { @@ -214,6 +217,13 @@ internal::kPermissionsPolicyIframeAttributeHistogramName, static_cast<PermissionsPolicyFeature>(feature.value())); break; + case FeatureType::kUserAgentOverride: + if (TestAndSet(user_agent_override_features_recorded_, feature.value())) + return; + UMA_HISTOGRAM_ENUMERATION( + internal::kUserAgentOverrideHistogramName, + static_cast<UserAgentOverrideHistogram>(feature.value())); + break; } }
diff --git a/components/page_load_metrics/browser/observers/use_counter_page_load_metrics_observer.h b/components/page_load_metrics/browser/observers/use_counter_page_load_metrics_observer.h index d6f5930..dc69e92 100644 --- a/components/page_load_metrics/browser/observers/use_counter_page_load_metrics_observer.h +++ b/components/page_load_metrics/browser/observers/use_counter_page_load_metrics_observer.h
@@ -27,6 +27,8 @@ "Blink.UseCounter.PermissionsPolicy.Header2"; const char kPermissionsPolicyIframeAttributeHistogramName[] = "Blink.UseCounter.PermissionsPolicy.Allow2"; +const char kUserAgentOverrideHistogramName[] = + "Blink.UseCounter.UserAgentOverride"; } // namespace internal @@ -103,6 +105,11 @@ blink::mojom::PermissionsPolicyFeature::kMaxValue) + 1> header_permissions_policy_features_recorded_; + std::bitset< + static_cast<size_t>( + blink::UserAgentOverride::UserAgentOverrideHistogram::kMaxValue) + + 1> + user_agent_override_features_recorded_; }; #endif // COMPONENTS_PAGE_LOAD_METRICS_BROWSER_OBSERVERS_USE_COUNTER_PAGE_LOAD_METRICS_OBSERVER_H_
diff --git a/components/page_load_metrics/browser/observers/use_counter_page_load_metrics_observer_unittest.cc b/components/page_load_metrics/browser/observers/use_counter_page_load_metrics_observer_unittest.cc index 4b4cf68..3e7a7d5 100644 --- a/components/page_load_metrics/browser/observers/use_counter_page_load_metrics_observer_unittest.cc +++ b/components/page_load_metrics/browser/observers/use_counter_page_load_metrics_observer_unittest.cc
@@ -36,6 +36,8 @@ return internal::kPermissionsPolicyHeaderHistogramName; case FeatureType::kPermissionsPolicyIframeAttribute: return internal::kPermissionsPolicyIframeAttributeHistogramName; + case FeatureType::kUserAgentOverride: + return internal::kUserAgentOverrideHistogramName; } }
diff --git a/components/policy/core/browser/android/policy_cache_updater_android_unittest.cc b/components/policy/core/browser/android/policy_cache_updater_android_unittest.cc index 1a243e0d..2d8fb27 100644 --- a/components/policy/core/browser/android/policy_cache_updater_android_unittest.cc +++ b/components/policy/core/browser/android/policy_cache_updater_android_unittest.cc
@@ -48,7 +48,8 @@ if (has_error_) { errors->AddError(policy_name_, IDS_POLICY_BLOCKED); } - return policies.GetValue(kPolicyName) && !has_error_; + return policies.GetValue(kPolicyName, base::Value::Type::INTEGER) && + !has_error_; } private:
diff --git a/components/policy/core/browser/configuration_policy_handler.cc b/components/policy/core/browser/configuration_policy_handler.cc index aad4ed2..7f58e5e9 100644 --- a/components/policy/core/browser/configuration_policy_handler.cc +++ b/components/policy/core/browser/configuration_policy_handler.cc
@@ -78,7 +78,7 @@ bool TypeCheckingPolicyHandler::CheckAndGetValue(const PolicyMap& policies, PolicyErrorMap* errors, const base::Value** value) { - *value = policies.GetValue(policy_name()); + *value = policies.GetValueUnsafe(policy_name()); if (*value && (*value)->type() != value_type_) { errors->AddError(policy_name(), IDS_POLICY_TYPE_ERROR, base::Value::GetTypeName(value_type_)); @@ -233,7 +233,7 @@ PrefValueMap* prefs) { if (!pref_path_) return; - const base::Value* value = policies.GetValue(policy_name()); + const base::Value* value = policies.GetValueUnsafe(policy_name()); base::ListValue list; if (value && Convert(value, &list, nullptr)) prefs->SetValue(pref_path_, std::move(list)); @@ -304,7 +304,7 @@ PrefValueMap* prefs) { if (!pref_path_) return; - const base::Value* value = policies.GetValue(policy_name()); + const base::Value* value = policies.GetValueUnsafe(policy_name()); int value_in_range; if (value && EnsureInRange(value, &value_in_range, nullptr)) prefs->SetInteger(pref_path_, value_in_range); @@ -328,7 +328,7 @@ PrefValueMap* prefs) { if (!pref_path_) return; - const base::Value* value = policies.GetValue(policy_name()); + const base::Value* value = policies.GetValueUnsafe(policy_name()); int percentage; if (value && EnsureInRange(value, &percentage, nullptr)) prefs->SetDouble(pref_path_, static_cast<double>(percentage) / 100.); @@ -348,7 +348,7 @@ PrefValueMap* prefs) { if (!pref_path_) return; - const base::Value* value = policies.GetValue(policy_name()); + const base::Value* value = policies.GetValueUnsafe(policy_name()); if (value) prefs->SetValue(pref_path_, value->Clone()); } @@ -368,7 +368,7 @@ bool SchemaValidatingPolicyHandler::CheckPolicySettings( const PolicyMap& policies, PolicyErrorMap* errors) { - const base::Value* value = policies.GetValue(policy_name()); + const base::Value* value = policies.GetValueUnsafe(policy_name()); if (!value) return true; @@ -389,7 +389,7 @@ const PolicyMap& policies, PolicyErrorMap* errors, std::unique_ptr<base::Value>* output) { - const base::Value* value = policies.GetValue(policy_name()); + const base::Value* value = policies.GetValueUnsafe(policy_name()); if (!value) return true; @@ -449,7 +449,7 @@ PrefValueMap* prefs) { if (!pref_path_) return; - const base::Value* value = policies.GetValue(policy_name()); + const base::Value* value = policies.GetValueUnsafe(policy_name()); if (value) prefs->SetValue(pref_path_, value->Clone()); } @@ -481,7 +481,7 @@ bool SimpleJsonStringSchemaValidatingPolicyHandler::CheckPolicySettings( const PolicyMap& policies, PolicyErrorMap* errors) { - const base::Value* root_value = policies.GetValue(policy_name()); + const base::Value* root_value = policies.GetValueUnsafe(policy_name()); if (!root_value) return true; @@ -612,7 +612,7 @@ PrefValueMap* prefs) { if (!pref_path_) return; - const base::Value* value = policies.GetValue(policy_name()); + const base::Value* value = policies.GetValueUnsafe(policy_name()); if (value) prefs->SetValue(pref_path_, value->Clone()); }
diff --git a/components/policy/core/browser/configuration_policy_handler_list.cc b/components/policy/core/browser/configuration_policy_handler_list.cc index 78856f2..d33eecd 100644 --- a/components/policy/core/browser/configuration_policy_handler_list.cc +++ b/components/policy/core/browser/configuration_policy_handler_list.cc
@@ -54,9 +54,10 @@ // applying the policies. PolicyMap filtered_policies = policies.Clone(); base::flat_set<std::string> enabled_future_policies = - allow_future_policies_ ? base::flat_set<std::string>() - : ValueToStringSet(policies.GetValue( - key::kEnableExperimentalPolicies)); + allow_future_policies_ + ? base::flat_set<std::string>() + : ValueToStringSet(policies.GetValue(key::kEnableExperimentalPolicies, + base::Value::Type::LIST)); filtered_policies.EraseMatching(base::BindRepeating( &ConfigurationPolicyHandlerList::FilterOutUnsupportedPolicies, base::Unretained(this), enabled_future_policies, future_policies));
diff --git a/components/policy/core/browser/configuration_policy_handler_list_unittest.cc b/components/policy/core/browser/configuration_policy_handler_list_unittest.cc index ae17934..80de0b71 100644 --- a/components/policy/core/browser/configuration_policy_handler_list_unittest.cc +++ b/components/policy/core/browser/configuration_policy_handler_list_unittest.cc
@@ -35,13 +35,15 @@ bool CheckPolicySettings(const PolicyMap& policies, PolicyErrorMap* errors) override { - return policies.GetValue(policy_name_); + return policies.GetValueUnsafe(policy_name_); } protected: void ApplyPolicySettings(const PolicyMap& policies, PrefValueMap* prefs) override { - prefs->SetInteger(policy_name_, policies.GetValue(policy_name_)->GetInt()); + prefs->SetInteger( + policy_name_, + policies.GetValue(policy_name_, base::Value::Type::INTEGER)->GetInt()); } private: @@ -105,7 +107,8 @@ EXPECT_EQ(kPolicyValue, pref_value); // Pref filter never affects PolicyMap. - const base::Value* policy_value = policies_.GetValue(policy_name); + const base::Value* policy_value = + policies_.GetValue(policy_name, base::Value::Type::INTEGER); ASSERT_TRUE(policy_value); EXPECT_EQ(kPolicyValue, policy_value->GetInt());
diff --git a/components/policy/core/browser/policy_conversions_client.cc b/components/policy/core/browser/policy_conversions_client.cc index c920022..e7c10bf 100644 --- a/components/policy/core/browser/policy_conversions_client.cc +++ b/components/policy/core/browser/policy_conversions_client.cc
@@ -148,19 +148,20 @@ GetPolicyService()->GetPolicies(policy_namespace); bool cloud_machine_precedence = - chrome_policies.Get(key::kCloudPolicyOverridesPlatformPolicy) - ? chrome_policies.GetValue(key::kCloudPolicyOverridesPlatformPolicy) - ->GetIfBool() - .value_or(false) - : false; + chrome_policies.GetValue(key::kCloudPolicyOverridesPlatformPolicy, + base::Value::Type::BOOLEAN) && + chrome_policies + .GetValue(key::kCloudPolicyOverridesPlatformPolicy, + base::Value::Type::BOOLEAN) + ->GetBool(); bool cloud_user_precedence = - chrome_policies.Get(key::kCloudUserPolicyOverridesCloudMachinePolicy) - ? chrome_policies.IsUserAffiliated() && - chrome_policies - .GetValue(key::kCloudUserPolicyOverridesCloudMachinePolicy) - ->GetIfBool() - .value_or(false) - : false; + chrome_policies.IsUserAffiliated() && + chrome_policies.GetValue(key::kCloudUserPolicyOverridesCloudMachinePolicy, + base::Value::Type::BOOLEAN) && + chrome_policies + .GetValue(key::kCloudUserPolicyOverridesCloudMachinePolicy, + base::Value::Type::BOOLEAN) + ->GetBool(); std::vector<int> precedence_order(4); if (cloud_user_precedence) { @@ -235,8 +236,8 @@ absl::optional<Schema> known_policy_schema = GetKnownPolicySchema(known_policy_schemas, policy_name); Value value(Value::Type::DICTIONARY); - value.SetKey("value", - CopyAndMaybeConvert(*policy.value(), known_policy_schema)); + value.SetKey("value", CopyAndMaybeConvert(*policy.value_unsafe(), + known_policy_schema)); if (convert_types_enabled_) { value.SetKey( "scope",
diff --git a/components/policy/core/browser/url_allowlist_policy_handler.cc b/components/policy/core/browser/url_allowlist_policy_handler.cc index 79b3153..2408777 100644 --- a/components/policy/core/browser/url_allowlist_policy_handler.cc +++ b/components/policy/core/browser/url_allowlist_policy_handler.cc
@@ -29,7 +29,7 @@ bool URLAllowlistPolicyHandler::CheckPolicySettings(const PolicyMap& policies, PolicyErrorMap* errors) { - const base::Value* url_allowlist = policies.GetValue(policy_name()); + const base::Value* url_allowlist = policies.GetValueUnsafe(policy_name()); if (!url_allowlist) return true; @@ -77,8 +77,9 @@ void URLAllowlistPolicyHandler::ApplyPolicySettings(const PolicyMap& policies, PrefValueMap* prefs) { - const base::Value* url_allowlist = policies.GetValue(policy_name()); - if (!url_allowlist || !url_allowlist->is_list()) { + const base::Value* url_allowlist = + policies.GetValue(policy_name(), base::Value::Type::LIST); + if (!url_allowlist) { return; }
diff --git a/components/policy/core/browser/url_blocklist_policy_handler.cc b/components/policy/core/browser/url_blocklist_policy_handler.cc index e2c0f9f..cdec91d 100644 --- a/components/policy/core/browser/url_blocklist_policy_handler.cc +++ b/components/policy/core/browser/url_blocklist_policy_handler.cc
@@ -34,7 +34,7 @@ size_t disabled_schemes_entries = 0; // This policy is deprecated but still supported so check it first. const base::Value* disabled_schemes = - policies.GetValue(key::kDisabledSchemes); + policies.GetValueUnsafe(key::kDisabledSchemes); if (disabled_schemes) { if (!disabled_schemes->is_list()) { errors->AddError(key::kDisabledSchemes, IDS_POLICY_TYPE_ERROR, @@ -44,7 +44,7 @@ } } - const base::Value* url_blocklist = policies.GetValue(policy_name()); + const base::Value* url_blocklist = policies.GetValueUnsafe(policy_name()); if (!url_blocklist) return true; @@ -93,9 +93,10 @@ void URLBlocklistPolicyHandler::ApplyPolicySettings(const PolicyMap& policies, PrefValueMap* prefs) { - const base::Value* url_blocklist_policy = policies.GetValue(policy_name()); + const base::Value* url_blocklist_policy = + policies.GetValueUnsafe(policy_name()); const base::Value* disabled_schemes_policy = - policies.GetValue(key::kDisabledSchemes); + policies.GetValueUnsafe(key::kDisabledSchemes); absl::optional<std::vector<base::Value>> merged_url_blocklist;
diff --git a/components/policy/core/browser/url_scheme_list_policy_handler.cc b/components/policy/core/browser/url_scheme_list_policy_handler.cc index 33774e56..5b6f4dc 100644 --- a/components/policy/core/browser/url_scheme_list_policy_handler.cc +++ b/components/policy/core/browser/url_scheme_list_policy_handler.cc
@@ -35,12 +35,11 @@ if (!TypeCheckingPolicyHandler::CheckPolicySettings(policies, errors)) return false; - const base::Value* schemes = policies.GetValue(policy_name()); + const base::Value* schemes = + policies.GetValue(policy_name(), base::Value::Type::LIST); if (!schemes || schemes->GetListDeprecated().empty()) return true; - DCHECK(schemes->is_list()); - // Filters more than |url_util::kMaxFiltersPerPolicy| are ignored, add a // warning message. if (schemes->GetListDeprecated().size() > policy::kMaxUrlFiltersPerPolicy) { @@ -65,8 +64,9 @@ void URLSchemeListPolicyHandler::ApplyPolicySettings(const PolicyMap& policies, PrefValueMap* prefs) { - const base::Value* schemes = policies.GetValue(policy_name()); - if (!schemes || !schemes->is_list()) + const base::Value* schemes = + policies.GetValue(policy_name(), base::Value::Type::LIST); + if (!schemes) return; std::vector<base::Value> filtered_schemes; for (const auto& entry : schemes->GetListDeprecated()) {
diff --git a/components/policy/core/common/android/android_combined_policy_provider_unittest.cc b/components/policy/core/common/android/android_combined_policy_provider_unittest.cc index b0bf7fbf..9fe59197 100644 --- a/components/policy/core/common/android/android_combined_policy_provider_unittest.cc +++ b/components/policy/core/common/android/android_combined_policy_provider_unittest.cc
@@ -75,7 +75,8 @@ manager.FlushPolicies(env, nullptr); const PolicyBundle& bundle = manager.policies(); const PolicyMap& map = bundle.Get(ns); - const base::Value* value = map.GetValue("TestPolicy"); + const base::Value* value = + map.GetValue("TestPolicy", base::Value::Type::STRING); ASSERT_NE(nullptr, value); EXPECT_EQ(base::Value::Type::STRING, value->type()); ASSERT_TRUE(value->is_string());
diff --git a/components/policy/core/common/android/policy_map_android.cc b/components/policy/core/common/android/policy_map_android.cc index d482ebe..037c9e4 100644 --- a/components/policy/core/common/android/policy_map_android.cc +++ b/components/policy/core/common/android/policy_map_android.cc
@@ -31,7 +31,7 @@ const base::android::JavaRef<jstring>& policy) const { const base::Value* value = GetValue(env, policy); DCHECK(value && value->is_int()) - << "The policy must be exist and stored as integer."; + << "The policy must exist and be stored as integer."; return value->GetInt(); } @@ -41,7 +41,7 @@ const base::android::JavaRef<jstring>& policy) const { const base::Value* value = GetValue(env, policy); DCHECK(value && value->is_bool()) - << "The policy must be exist and stored as boolean."; + << "The policy must exist and be stored as boolean."; return value->GetBool(); } @@ -108,7 +108,7 @@ const base::Value* PolicyMapAndroid::GetValue( JNIEnv* env, const base::android::JavaRef<jstring>& policy) const { - return policy_map_.GetValue( + return policy_map_.GetValueUnsafe( base::android::ConvertJavaStringToUTF8(env, policy)); }
diff --git a/components/policy/core/common/cloud/user_cloud_policy_store_unittest.cc b/components/policy/core/common/cloud/user_cloud_policy_store_unittest.cc index a504cd4e..32a7caf 100644 --- a/components/policy/core/common/cloud/user_cloud_policy_store_unittest.cc +++ b/components/policy/core/common/cloud/user_cloud_policy_store_unittest.cc
@@ -109,7 +109,8 @@ const PolicyMap::Entry* entry = store->policy_map().Get(key::kSearchSuggestEnabled); ASSERT_TRUE(entry); - EXPECT_TRUE(base::Value(true).Equals(entry->value())); + EXPECT_TRUE( + base::Value(true).Equals(entry->value(base::Value::Type::BOOLEAN))); ASSERT_TRUE(store->policy_map().Get(key::kURLBlocklist)); }
diff --git a/components/policy/core/common/command_line_policy_provider_unittest.cc b/components/policy/core/common/command_line_policy_provider_unittest.cc index da428e3..23219c4 100644 --- a/components/policy/core/common/command_line_policy_provider_unittest.cc +++ b/components/policy/core/common/command_line_policy_provider_unittest.cc
@@ -25,7 +25,7 @@ const base::Value* policy_value = provider->policies() .Get(PolicyNamespace(POLICY_DOMAIN_CHROME, std::string())) - .GetValue("policy"); + .GetValue("policy", base::Value::Type::INTEGER); ASSERT_TRUE(policy_value); ASSERT_TRUE(policy_value->is_int()); EXPECT_EQ(10, policy_value->GetInt());
diff --git a/components/policy/core/common/config_dir_policy_loader.cc b/components/policy/core/common/config_dir_policy_loader.cc index 4dcab62e..fb70e431 100644 --- a/components/policy/core/common/config_dir_policy_loader.cc +++ b/components/policy/core/common/config_dir_policy_loader.cc
@@ -19,6 +19,7 @@ #include "base/json/json_file_value_serializer.h" #include "base/json/json_reader.h" #include "base/logging.h" +#include "base/syslog_logging.h" #include "components/policy/core/common/policy_bundle.h" #include "components/policy/core/common/policy_load_status.h" #include "components/policy/core/common/policy_types.h" @@ -146,15 +147,15 @@ std::unique_ptr<base::Value> value = deserializer.Deserialize(&error_code, &error_msg); if (!value) { - LOG(WARNING) << "Failed to read configuration file " - << config_file.value() << ": " << error_msg; + SYSLOG(WARNING) << "Failed to read configuration file " + << config_file.value() << ": " << error_msg; status.Add(JsonErrorToPolicyLoadStatus(error_code)); continue; } base::DictionaryValue* dictionary_value = nullptr; if (!value->GetAsDictionary(&dictionary_value)) { - LOG(WARNING) << "Expected JSON dictionary in configuration file " - << config_file.value(); + SYSLOG(WARNING) << "Expected JSON dictionary in configuration file " + << config_file.value(); status.Add(POLICY_LOAD_STATUS_PARSE_ERROR); continue; } @@ -188,7 +189,7 @@ const base::DictionaryValue* domains_dictionary; if (!policies->GetAsDictionary(&domains_dictionary)) { - LOG(WARNING) << "3rdparty value is not a dictionary!"; + SYSLOG(WARNING) << "3rdparty value is not a dictionary!"; return; } @@ -201,15 +202,15 @@ for (base::DictionaryValue::Iterator domains_it(*domains_dictionary); !domains_it.IsAtEnd(); domains_it.Advance()) { if (!base::Contains(supported_domains, domains_it.key())) { - LOG(WARNING) << "Unsupported 3rd party policy domain: " - << domains_it.key(); + SYSLOG(WARNING) << "Unsupported 3rd party policy domain: " + << domains_it.key(); continue; } const base::DictionaryValue* components_dictionary; if (!domains_it.value().GetAsDictionary(&components_dictionary)) { - LOG(WARNING) << "3rdparty/" << domains_it.key() - << " value is not a dictionary!"; + SYSLOG(WARNING) << "3rdparty/" << domains_it.key() + << " value is not a dictionary!"; continue; } @@ -218,8 +219,8 @@ !components_it.IsAtEnd(); components_it.Advance()) { const base::DictionaryValue* policy_dictionary; if (!components_it.value().GetAsDictionary(&policy_dictionary)) { - LOG(WARNING) << "3rdparty/" << domains_it.key() << "/" - << components_it.key() << " value is not a dictionary!"; + SYSLOG(WARNING) << "3rdparty/" << domains_it.key() << "/" + << components_it.key() << " value is not a dictionary!"; continue; }
diff --git a/components/policy/core/common/default_chrome_apps_migrator.cc b/components/policy/core/common/default_chrome_apps_migrator.cc index cd3a5c1..f90995a 100644 --- a/components/policy/core/common/default_chrome_apps_migrator.cc +++ b/components/policy/core/common/default_chrome_apps_migrator.cc
@@ -40,15 +40,15 @@ return; EnsurePolicyValueIsList(policies, key::kExtensionInstallBlocklist); - base::Value* blocklist_value = - policies->GetMutableValue(key::kExtensionInstallBlocklist); + base::Value* blocklist_value = policies->GetMutableValue( + key::kExtensionInstallBlocklist, base::Value::Type::LIST); for (const std::string& chrome_app_id : chrome_app_ids) { blocklist_value->Append(chrome_app_id); } EnsurePolicyValueIsList(policies, key::kWebAppInstallForceList); - base::Value* web_app_policy_value = - policies->GetMutableValue(key::kWebAppInstallForceList); + base::Value* web_app_policy_value = policies->GetMutableValue( + key::kWebAppInstallForceList, base::Value::Type::LIST); for (const std::string& chrome_app_id : chrome_app_ids) { base::Value web_app(base::Value::Type::DICTIONARY); web_app.SetStringKey("url", chrome_app_to_web_app_.at(chrome_app_id)); @@ -66,8 +66,9 @@ if (!forcelist_entry) return std::vector<std::string>(); - const base::Value* forcelist_value = forcelist_entry->value(); - if (!forcelist_value || !forcelist_value->is_list()) + const base::Value* forcelist_value = + forcelist_entry->value(base::Value::Type::LIST); + if (!forcelist_value) return std::vector<std::string>(); std::vector<std::string> chrome_app_ids; @@ -95,7 +96,7 @@ void DefaultChromeAppsMigrator::EnsurePolicyValueIsList( PolicyMap* policies, const std::string& policy_name) const { - const base::Value* policy_value = policies->GetValue(policy_name); + const base::Value* policy_value = policies->GetValueUnsafe(policy_name); if (!policy_value || !policy_value->is_list()) { const PolicyMap::Entry* forcelist_entry = policies->Get(key::kExtensionInstallForcelist); @@ -113,9 +114,9 @@ void DefaultChromeAppsMigrator::MigratePinningPolicy( PolicyMap* policies) const { - base::Value* pinned_apps_value = - policies->GetMutableValue(key::kPinnedLauncherApps); - if (!pinned_apps_value || !pinned_apps_value->is_list()) + base::Value* pinned_apps_value = policies->GetMutableValue( + key::kPinnedLauncherApps, base::Value::Type::LIST); + if (!pinned_apps_value) return; for (auto& list_entry : pinned_apps_value->GetListDeprecated()) { if (!list_entry.is_string()) @@ -127,4 +128,4 @@ } } -} // namespace policy \ No newline at end of file +} // namespace policy
diff --git a/components/policy/core/common/default_chrome_apps_migrator_unittest.cc b/components/policy/core/common/default_chrome_apps_migrator_unittest.cc index b8a51b9..d62ca8c4 100644 --- a/components/policy/core/common/default_chrome_apps_migrator_unittest.cc +++ b/components/policy/core/common/default_chrome_apps_migrator_unittest.cc
@@ -71,20 +71,20 @@ PolicyMap expected_map(policy_map_.Clone()); // Add force installed chrome app that should be migrated. - base::Value* forcelist_value = - policy_map_.GetMutableValue(key::kExtensionInstallForcelist); + base::Value* forcelist_value = policy_map_.GetMutableValue( + key::kExtensionInstallForcelist, base::Value::Type::LIST); forcelist_value->Append(std::string(kAppId1) + ";https://example.com"); // Chrome app should be blocked after migration. - base::Value* blocklist_value = - expected_map.GetMutableValue(key::kExtensionInstallBlocklist); + base::Value* blocklist_value = expected_map.GetMutableValue( + key::kExtensionInstallBlocklist, base::Value::Type::LIST); blocklist_value->Append(std::string(kAppId1)); // Corresponding web app should be force installed after migration. base::Value first_app(base::Value::Type::DICTIONARY); first_app.SetStringKey("url", kWebAppUrl1); - base::Value* web_app_value = - expected_map.GetMutableValue(key::kWebAppInstallForceList); + base::Value* web_app_value = expected_map.GetMutableValue( + key::kWebAppInstallForceList, base::Value::Type::LIST); web_app_value->Append(std::move(first_app)); migrator_.Migrate(&policy_map_); @@ -96,22 +96,22 @@ PolicyMap expected_map(policy_map_.Clone()); // Add two force installed chrome apps and two extensions. - base::Value* forcelist_value = - policy_map_.GetMutableValue(key::kExtensionInstallForcelist); + base::Value* forcelist_value = policy_map_.GetMutableValue( + key::kExtensionInstallForcelist, base::Value::Type::LIST); forcelist_value->Append("extension1"); forcelist_value->Append(kAppId1); forcelist_value->Append("extension2"); forcelist_value->Append(kAppId2); // Only extensions should be left now. - base::Value* expected_forcelist = - expected_map.GetMutableValue(key::kExtensionInstallForcelist); + base::Value* expected_forcelist = expected_map.GetMutableValue( + key::kExtensionInstallForcelist, base::Value::Type::LIST); expected_forcelist->Append("extension1"); expected_forcelist->Append("extension2"); // Chrome apps should be blocked after migration. - base::Value* blocklist_value = - expected_map.GetMutableValue(key::kExtensionInstallBlocklist); + base::Value* blocklist_value = expected_map.GetMutableValue( + key::kExtensionInstallBlocklist, base::Value::Type::LIST); blocklist_value->Append(kAppId1); blocklist_value->Append(kAppId2); @@ -120,8 +120,8 @@ first_app.SetStringKey("url", kWebAppUrl1); base::Value second_app(base::Value::Type::DICTIONARY); second_app.SetStringKey("url", kWebAppUrl2); - base::Value* web_app_value = - expected_map.GetMutableValue(key::kWebAppInstallForceList); + base::Value* web_app_value = expected_map.GetMutableValue( + key::kWebAppInstallForceList, base::Value::Type::LIST); web_app_value->Append(std::move(first_app)); web_app_value->Append(std::move(second_app)); @@ -137,8 +137,8 @@ PolicyMap expected_map(policy_map_.Clone()); // Add force installed chrome app. - base::Value* forcelist_value = - policy_map_.GetMutableValue(key::kExtensionInstallForcelist); + base::Value* forcelist_value = policy_map_.GetMutableValue( + key::kExtensionInstallForcelist, base::Value::Type::LIST); forcelist_value->Append(kAppId1); // Set ExtensionInstallBlocklist to non-list type. @@ -157,8 +157,8 @@ // Corresponding web app should be force installed after migration. base::Value first_app(base::Value::Type::DICTIONARY); first_app.SetStringKey("url", kWebAppUrl1); - base::Value* web_app_value = - expected_map.GetMutableValue(key::kWebAppInstallForceList); + base::Value* web_app_value = expected_map.GetMutableValue( + key::kWebAppInstallForceList, base::Value::Type::LIST); web_app_value->Append(std::move(first_app)); migrator_.Migrate(&policy_map_); @@ -173,8 +173,8 @@ PolicyMap expected_map(policy_map_.Clone()); // Add force installed chrome app. - base::Value* forcelist_value = - policy_map_.GetMutableValue(key::kExtensionInstallForcelist); + base::Value* forcelist_value = policy_map_.GetMutableValue( + key::kExtensionInstallForcelist, base::Value::Type::LIST); forcelist_value->Append(kAppId1); // Set WebAppInstallForceList to non-list type. @@ -183,8 +183,8 @@ ->set_value(std::move(web_app_value)); // Chrome app should be blocked after migration. - base::Value* blocklist_value = - expected_map.GetMutableValue(key::kExtensionInstallBlocklist); + base::Value* blocklist_value = expected_map.GetMutableValue( + key::kExtensionInstallBlocklist, base::Value::Type::LIST); blocklist_value->Append(kAppId1); base::Value web_app_expected_value(base::Value::Type::LIST); @@ -206,30 +206,30 @@ PolicyMap expected_map(policy_map_.Clone()); // Add force installed chrome app that should be migrated. - base::Value* forcelist_value = - policy_map_.GetMutableValue(key::kExtensionInstallForcelist); + base::Value* forcelist_value = policy_map_.GetMutableValue( + key::kExtensionInstallForcelist, base::Value::Type::LIST); forcelist_value->Append(std::string(kAppId1)); // Make the chrome app pinned. - base::Value* pinned_apps_value = - policy_map_.GetMutableValue(key::kPinnedLauncherApps); + base::Value* pinned_apps_value = policy_map_.GetMutableValue( + key::kPinnedLauncherApps, base::Value::Type::LIST); pinned_apps_value->Append(std::string(kAppId1)); // Chrome app should be blocked after migration. - base::Value* blocklist_value = - expected_map.GetMutableValue(key::kExtensionInstallBlocklist); + base::Value* blocklist_value = expected_map.GetMutableValue( + key::kExtensionInstallBlocklist, base::Value::Type::LIST); blocklist_value->Append(std::string(kAppId1)); // Corresponding web app should be force installed after migration. base::Value first_app(base::Value::Type::DICTIONARY); first_app.SetStringKey("url", kWebAppUrl1); - base::Value* web_app_value = - expected_map.GetMutableValue(key::kWebAppInstallForceList); + base::Value* web_app_value = expected_map.GetMutableValue( + key::kWebAppInstallForceList, base::Value::Type::LIST); web_app_value->Append(std::move(first_app)); // The corresponding Web App should be pinned. - base::Value* pinned_expected_value = - expected_map.GetMutableValue(key::kPinnedLauncherApps); + base::Value* pinned_expected_value = expected_map.GetMutableValue( + key::kPinnedLauncherApps, base::Value::Type::LIST); pinned_expected_value->Append(std::string(kWebAppUrl1)); migrator_.Migrate(&policy_map_); @@ -237,4 +237,4 @@ EXPECT_TRUE(policy_map_.Equals(expected_map)); } -} // namespace policy \ No newline at end of file +} // namespace policy
diff --git a/components/policy/core/common/generate_policy_source_unittest.cc b/components/policy/core/common/generate_policy_source_unittest.cc index 543afdf..58be40b 100644 --- a/components/policy/core/common/generate_policy_source_unittest.cc +++ b/components/policy/core/common/generate_policy_source_unittest.cc
@@ -229,8 +229,8 @@ // If policy not configured yet, set the enterprise default. SetEnterpriseUsersDefaults(&policy_map); - const base::Value* multiprof_behavior = - policy_map.GetValue(key::kChromeOsMultiProfileUserBehavior); + const base::Value* multiprof_behavior = policy_map.GetValue( + key::kChromeOsMultiProfileUserBehavior, base::Value::Type::STRING); base::Value expected("primary-only"); EXPECT_EQ(expected, *multiprof_behavior); @@ -239,8 +239,8 @@ POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD, base::Value("test_value"), nullptr); SetEnterpriseUsersDefaults(&policy_map); - multiprof_behavior = - policy_map.GetValue(key::kChromeOsMultiProfileUserBehavior); + multiprof_behavior = policy_map.GetValue( + key::kChromeOsMultiProfileUserBehavior, base::Value::Type::STRING); expected = base::Value("test_value"); EXPECT_EQ(expected, *multiprof_behavior); } @@ -251,12 +251,12 @@ // If policy not configured yet, set the enterprise system-wide default. SetEnterpriseUsersSystemWideDefaults(&policy_map); - const base::Value* pin_unlock_autosubmit_enabled = - policy_map.GetValue(key::kPinUnlockAutosubmitEnabled); + const base::Value* pin_unlock_autosubmit_enabled = policy_map.GetValue( + key::kPinUnlockAutosubmitEnabled, base::Value::Type::BOOLEAN); ASSERT_TRUE(pin_unlock_autosubmit_enabled); EXPECT_FALSE(pin_unlock_autosubmit_enabled->GetBool()); - const base::Value* allow_dinosaur_easter_egg = - policy_map.GetValue(key::kAllowDinosaurEasterEgg); + const base::Value* allow_dinosaur_easter_egg = policy_map.GetValue( + key::kAllowDinosaurEasterEgg, base::Value::Type::BOOLEAN); EXPECT_EQ(nullptr, allow_dinosaur_easter_egg); // If policy already configured, it's not changed to enterprise defaults. @@ -264,11 +264,12 @@ POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD, base::Value(true), nullptr); SetEnterpriseUsersSystemWideDefaults(&policy_map); - pin_unlock_autosubmit_enabled = - policy_map.GetValue(key::kPinUnlockAutosubmitEnabled); + pin_unlock_autosubmit_enabled = policy_map.GetValue( + key::kPinUnlockAutosubmitEnabled, base::Value::Type::BOOLEAN); ASSERT_TRUE(pin_unlock_autosubmit_enabled); EXPECT_TRUE(pin_unlock_autosubmit_enabled->GetBool()); - allow_dinosaur_easter_egg = policy_map.GetValue(key::kAllowDinosaurEasterEgg); + allow_dinosaur_easter_egg = policy_map.GetValue(key::kAllowDinosaurEasterEgg, + base::Value::Type::BOOLEAN); EXPECT_EQ(nullptr, allow_dinosaur_easter_egg); } @@ -278,12 +279,12 @@ // If policy not configured yet, set the enterprise profile default. SetEnterpriseUsersProfileDefaults(&policy_map); - const base::Value* allow_dinosaur_easter_egg = - policy_map.GetValue(key::kAllowDinosaurEasterEgg); + const base::Value* allow_dinosaur_easter_egg = policy_map.GetValue( + key::kAllowDinosaurEasterEgg, base::Value::Type::BOOLEAN); ASSERT_TRUE(allow_dinosaur_easter_egg); EXPECT_FALSE(allow_dinosaur_easter_egg->GetBool()); - const base::Value* pin_unlock_autosubmit_enabled = - policy_map.GetValue(key::kPinUnlockAutosubmitEnabled); + const base::Value* pin_unlock_autosubmit_enabled = policy_map.GetValue( + key::kPinUnlockAutosubmitEnabled, base::Value::Type::BOOLEAN); EXPECT_EQ(nullptr, pin_unlock_autosubmit_enabled); // If policy already configured, it's not changed to enterprise defaults. @@ -291,11 +292,12 @@ POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD, base::Value(true), nullptr); SetEnterpriseUsersProfileDefaults(&policy_map); - allow_dinosaur_easter_egg = policy_map.GetValue(key::kAllowDinosaurEasterEgg); + allow_dinosaur_easter_egg = policy_map.GetValue(key::kAllowDinosaurEasterEgg, + base::Value::Type::BOOLEAN); ASSERT_TRUE(allow_dinosaur_easter_egg); EXPECT_TRUE(allow_dinosaur_easter_egg->GetBool()); - pin_unlock_autosubmit_enabled = - policy_map.GetValue(key::kPinUnlockAutosubmitEnabled); + pin_unlock_autosubmit_enabled = policy_map.GetValue( + key::kPinUnlockAutosubmitEnabled, base::Value::Type::BOOLEAN); EXPECT_EQ(nullptr, pin_unlock_autosubmit_enabled); } #endif
diff --git a/components/policy/core/common/legacy_chrome_policy_migrator_unittest.cc b/components/policy/core/common/legacy_chrome_policy_migrator_unittest.cc index 720a29f..3259f501 100644 --- a/components/policy/core/common/legacy_chrome_policy_migrator_unittest.cc +++ b/components/policy/core/common/legacy_chrome_policy_migrator_unittest.cc
@@ -50,11 +50,13 @@ // kOldPolicy should have been copied to kNewPolicy, kOtherPolicy remains EXPECT_EQ(3u, chrome_map.size()); - ASSERT_TRUE(chrome_map.GetValue(kNewPolicy)); + ASSERT_TRUE(chrome_map.GetValue(kNewPolicy, base::Value::Type::INTEGER)); // Old Value should be copied over. - EXPECT_EQ(base::Value(kOldValue), *chrome_map.GetValue(kNewPolicy)); + EXPECT_EQ(base::Value(kOldValue), + *chrome_map.GetValue(kNewPolicy, base::Value::Type::INTEGER)); // Other Value should be unchanged. - EXPECT_EQ(base::Value(kOtherValue), *chrome_map.GetValue(kOtherPolicy)); + EXPECT_EQ(base::Value(kOtherValue), + *chrome_map.GetValue(kOtherPolicy, base::Value::Type::INTEGER)); base::RepeatingCallback<std::u16string(int)> l10nlookup = base::BindRepeating(&l10n_util::GetStringUTF16); // Old policy should always be marked deprecated @@ -80,9 +82,10 @@ migrator.Migrate(&bundle); - ASSERT_TRUE(chrome_map.GetValue(kNewPolicy)); + ASSERT_TRUE(chrome_map.GetValue(kNewPolicy, base::Value::Type::INTEGER)); // Old Value should be transformed - EXPECT_EQ(base::Value(kTransformedValue), *chrome_map.GetValue(kNewPolicy)); + EXPECT_EQ(base::Value(kTransformedValue), + *chrome_map.GetValue(kNewPolicy, base::Value::Type::INTEGER)); } TEST(LegacyChromePolicyMigratorTest, IgnoreOldIfNewIsSet) { @@ -97,7 +100,8 @@ migrator.Migrate(&bundle); // New Value is unchanged - EXPECT_EQ(base::Value(kNewValue), *chrome_map.GetValue(kNewPolicy)); + EXPECT_EQ(base::Value(kNewValue), + *chrome_map.GetValue(kNewPolicy, base::Value::Type::INTEGER)); // Should be no warning on new policy base::RepeatingCallback<std::u16string(int)> l10nlookup = base::BindRepeating(&l10n_util::GetStringUTF16);
diff --git a/components/policy/core/common/policy_loader_command_line_unittest.cc b/components/policy/core/common/policy_loader_command_line_unittest.cc index 7f258e8..281fac8 100644 --- a/components/policy/core/common/policy_loader_command_line_unittest.cc +++ b/components/policy/core/common/policy_loader_command_line_unittest.cc
@@ -34,8 +34,8 @@ EXPECT_EQ(POLICY_SCOPE_MACHINE, actual_policy->scope); EXPECT_EQ(POLICY_SOURCE_COMMAND_LINE, actual_policy->source); - ASSERT_TRUE(actual_policy->value()); - EXPECT_EQ(expected_policy.second, *(actual_policy->value())); + ASSERT_TRUE(actual_policy->value_unsafe()); + EXPECT_EQ(expected_policy.second, *(actual_policy->value_unsafe())); } }
diff --git a/components/policy/core/common/policy_loader_common.cc b/components/policy/core/common/policy_loader_common.cc index 75bba5b..5d64293b 100644 --- a/components/policy/core/common/policy_loader_common.cc +++ b/components/policy/core/common/policy_loader_common.cc
@@ -71,8 +71,8 @@ if (!map_entry) return false; - base::Value* policy_list_value = map_entry->value(); - if (!policy_list_value || !policy_list_value->is_list()) + base::Value* policy_list_value = map_entry->value(base::Value::Type::LIST); + if (!policy_list_value) return false; // Using index for loop to update the list in place. @@ -110,8 +110,8 @@ bool FilterSensitiveExtensionSettings(PolicyMap::Entry* map_entry) { if (!map_entry) return false; - base::Value* policy_dict_value = map_entry->value(); - if (!policy_dict_value || !policy_dict_value->is_dict()) { + base::Value* policy_dict_value = map_entry->value(base::Value::Type::DICT); + if (!policy_dict_value) { return false; }
diff --git a/components/policy/core/common/policy_loader_lacros_unittest.cc b/components/policy/core/common/policy_loader_lacros_unittest.cc index bb940f7b..5135867 100644 --- a/components/policy/core/common/policy_loader_lacros_unittest.cc +++ b/components/policy/core/common/policy_loader_lacros_unittest.cc
@@ -7,6 +7,7 @@ #include <stdint.h> #include <vector> +#include "base/values.h" #include "chromeos/crosapi/mojom/crosapi.mojom.h" #include "chromeos/lacros/lacros_service.h" #include "chromeos/lacros/lacros_test_helper.h" @@ -77,28 +78,39 @@ void CheckProfilePolicies(const PolicyMap& policy_map) const { if (per_profile_ == PolicyPerProfileFilter::kFalse) { - EXPECT_EQ(nullptr, policy_map.GetValue(key::kHomepageLocation)); - EXPECT_EQ(nullptr, policy_map.GetValue(key::kAllowDinosaurEasterEgg)); + EXPECT_EQ(nullptr, policy_map.GetValue(key::kHomepageLocation, + base::Value::Type::STRING)); + EXPECT_EQ(nullptr, policy_map.GetValue(key::kAllowDinosaurEasterEgg, + base::Value::Type::BOOLEAN)); } else { EXPECT_EQ("http://chromium.org", - policy_map.GetValue(key::kHomepageLocation)->GetString()); + policy_map + .GetValue(key::kHomepageLocation, base::Value::Type::STRING) + ->GetString()); // Enterprise default. - EXPECT_EQ(false, - policy_map.GetValue(key::kAllowDinosaurEasterEgg)->GetBool()); + EXPECT_EQ(false, policy_map + .GetValue(key::kAllowDinosaurEasterEgg, + base::Value::Type::BOOLEAN) + ->GetBool()); } } void CheckSystemWidePolicies(const PolicyMap& policy_map) const { if (per_profile_ == PolicyPerProfileFilter::kTrue) { - EXPECT_EQ(nullptr, - policy_map.GetValue(key::kTaskManagerEndProcessEnabled)); - EXPECT_EQ(nullptr, policy_map.GetValue(key::kPinUnlockAutosubmitEnabled)); + EXPECT_EQ(nullptr, policy_map.GetValue(key::kTaskManagerEndProcessEnabled, + base::Value::Type::BOOLEAN)); + EXPECT_EQ(nullptr, policy_map.GetValue(key::kPinUnlockAutosubmitEnabled, + base::Value::Type::BOOLEAN)); } else { - EXPECT_FALSE( - policy_map.GetValue(key::kTaskManagerEndProcessEnabled)->GetBool()); + EXPECT_FALSE(policy_map + .GetValue(key::kTaskManagerEndProcessEnabled, + base::Value::Type::BOOLEAN) + ->GetBool()); // Enterprise default. - EXPECT_FALSE( - policy_map.GetValue(key::kPinUnlockAutosubmitEnabled)->GetBool()); + EXPECT_FALSE(policy_map + .GetValue(key::kPinUnlockAutosubmitEnabled, + base::Value::Type::BOOLEAN) + ->GetBool()); } }
diff --git a/components/policy/core/common/policy_loader_win.cc b/components/policy/core/common/policy_loader_win.cc index 738207c..d11e2aa1 100644 --- a/components/policy/core/common/policy_loader_win.cc +++ b/components/policy/core/common/policy_loader_win.cc
@@ -34,6 +34,7 @@ #include "base/path_service.h" #include "base/scoped_native_library.h" #include "base/strings/string_util.h" +#include "base/syslog_logging.h" #include "base/task/sequenced_task_runner.h" #include "base/threading/scoped_thread_priority.h" #include "base/values.h" @@ -84,7 +85,7 @@ std::unique_ptr<base::Value> policy_value(gpo_dict->ConvertToJSON(schema)); const base::DictionaryValue* policy_dict = nullptr; if (!policy_value->GetAsDictionary(&policy_dict) || !policy_dict) { - LOG(WARNING) << "Root policy object is not a dictionary!"; + SYSLOG(WARNING) << "Root policy object is not a dictionary!"; return; }
diff --git a/components/policy/core/common/policy_map.cc b/components/policy/core/common/policy_map.cc index 2ddd3a2e..70a2af7 100644 --- a/components/policy/core/common/policy_map.cc +++ b/components/policy/core/common/policy_map.cc
@@ -182,8 +182,8 @@ // They have to update when sources change. message_ids_ == other.message_ids_ && is_default_value_ == other.is_default_value_ && - ((!value_ && !other.value()) || - (value_ && other.value() && *value_ == *other.value())) && + ((!value_ && !other.value_unsafe()) || + (value_ && other.value_unsafe() && *value_ == *other.value_unsafe())) && ExternalDataFetcher::Equals(external_data_fetcher.get(), other.external_data_fetcher.get()); return equals; @@ -214,9 +214,9 @@ std::move(conflict.conflicts.begin(), conflict.conflicts.end(), std::back_inserter(conflicts)); - bool is_value_equal = (!this->value() && !conflict.value()) || - (this->value() && conflict.value() && - *this->value() == *conflict.value()); + bool is_value_equal = (!this->value_unsafe() && !conflict.value_unsafe()) || + (this->value_unsafe() && conflict.value_unsafe() && + *this->value_unsafe() == *conflict.value_unsafe()); ConflictType type = is_value_equal ? ConflictType::Supersede : ConflictType::Override; @@ -486,7 +486,8 @@ higher_policy.source != conflicting_policy.source && conflicting_policy.source == POLICY_SOURCE_ENTERPRISE_DEFAULT; if (!overwriting_default_policy) { - policy->value() && *other_policy_copy.value() == *policy->value() + policy->value_unsafe() && + *other_policy_copy.value_unsafe() == *policy->value_unsafe() ? higher_policy.AddMessage(MessageType::kInfo, IDS_POLICY_CONFLICT_SAME_VALUE) : higher_policy.AddMessage(MessageType::kWarning,
diff --git a/components/policy/core/common/policy_merger.cc b/components/policy/core/common/policy_merger.cc index 71609f7..31846f0 100644 --- a/components/policy/core/common/policy_merger.cc +++ b/components/policy/core/common/policy_merger.cc
@@ -31,7 +31,7 @@ const PolicyMap::Entry& entry_1, const PolicyMap::Entry& entry_2, const bool is_user_cloud_merging_enabled) { - if (entry_1.value()->type() != entry_2.value()->type()) + if (entry_1.value_unsafe()->type() != entry_2.value_unsafe()->type()) return false; if (entry_1.ignored() || entry_2.ignored() || @@ -108,12 +108,12 @@ return false; if (policies_to_merge_.find("*") != policies_to_merge_.end()) - return policy.value()->is_list(); + return policy.value(base::Value::Type::LIST) != nullptr; if (policies_to_merge_.find(policy_name) == policies_to_merge_.end()) return false; - if (!policy.value()->is_list()) { + if (!policy.value(base::Value::Type::LIST)) { policy.AddMessage(PolicyMap::MessageType::kError, IDS_POLICY_LIST_MERGING_WRONG_POLICY_TYPE_SPECIFIED); return false; @@ -135,7 +135,8 @@ compare_value_ptr); bool value_changed = false; - for (const base::Value& val : policy->value()->GetListDeprecated()) { + for (const base::Value& val : + policy->value(base::Value::Type::LIST)->GetListDeprecated()) { if (duplicates.find(&val) != duplicates.end()) continue; duplicates.insert(&val); @@ -150,7 +151,8 @@ continue; } - for (const base::Value& val : it.entry().value()->GetListDeprecated()) { + for (const base::Value& val : + it.entry().value(base::Value::Type::LIST)->GetListDeprecated()) { if (duplicates.find(&val) != duplicates.end()) continue; duplicates.insert(&val); @@ -206,7 +208,7 @@ allowed_policies_.find(policy_name) != allowed_policies_.end(); if (policies_to_merge_.find("*") != policies_to_merge_.end()) - return allowed_to_merge && policy.value()->is_dict(); + return allowed_to_merge && policy.value(base::Value::Type::DICT); if (policies_to_merge_.find(policy_name) == policies_to_merge_.end()) return false; @@ -217,7 +219,7 @@ return false; } - if (!policy.value()->is_dict()) { + if (!policy.value(base::Value::Type::DICT)) { policy.AddMessage( PolicyMap::MessageType::kError, IDS_POLICY_DICTIONARY_MERGING_WRONG_POLICY_TYPE_SPECIFIED); @@ -255,7 +257,7 @@ const base::DictionaryValue* dict = nullptr; - it->value()->GetAsDictionary(&dict); + it->value(base::Value::Type::DICT)->GetAsDictionary(&dict); DCHECK(dict); for (auto pair : dict->DictItems()) {
diff --git a/components/policy/core/common/policy_migrator.cc b/components/policy/core/common/policy_migrator.cc index 8289cd39..51398ca 100644 --- a/components/policy/core/common/policy_migrator.cc +++ b/components/policy/core/common/policy_migrator.cc
@@ -32,7 +32,7 @@ VLOG(3) << "Legacy policy '" << migration.old_name << "' has been copied to '" << migration.new_name << "'."; auto new_entry = entry->DeepCopy(); - migration.transform.Run(new_entry.value()); + migration.transform.Run(new_entry.value_unsafe()); new_entry.AddMessage(PolicyMap::MessageType::kWarning, IDS_POLICY_MIGRATED_NEW_POLICY, {base::UTF8ToUTF16(migration.old_name)});
diff --git a/components/policy/core/common/policy_service.cc b/components/policy/core/common/policy_service.cc index 3d8fdd7..678579e 100644 --- a/components/policy/core/common/policy_service.cc +++ b/components/policy/core/common/policy_service.cc
@@ -30,13 +30,13 @@ const PolicyMap& current) { if (ns != ns_) return; - for (auto it = callback_map_.begin(); it != callback_map_.end(); ++it) { - const base::Value* prev = previous.GetValue(it->first); - const base::Value* cur = current.GetValue(it->first); + for (auto it : callback_map_) { + const base::Value* prev = previous.GetValueUnsafe(it.first); + const base::Value* cur = current.GetValueUnsafe(it.first); // Check if the values pointed to by |prev| and |cur| are different. if ((!prev ^ !cur) || (prev && cur && *prev != *cur)) - it->second.Run(prev, cur); + it.second.Run(prev, cur); } }
diff --git a/components/policy/core/common/policy_service_impl.cc b/components/policy/core/common/policy_service_impl.cc index ca435f5..edc507e5 100644 --- a/components/policy/core/common/policy_service_impl.cc +++ b/components/policy/core/common/policy_service_impl.cc
@@ -52,8 +52,8 @@ // For all renamed policies we need to explicitly merge the value of the // old policy with the new one or else merging will not be carried over // if desired. - base::Value* merge_list = - policies->GetMutableValue(key::kPolicyListMultipleSourceMergeList); + base::Value* merge_list = policies->GetMutableValue( + key::kPolicyListMultipleSourceMergeList, base::Value::Type::LIST); base::flat_set<std::string> policy_lists_to_merge = policy::ValueToStringSet(merge_list); const std::vector<std::pair<const char*, const char*>> renamed_policies = {{ @@ -127,8 +127,8 @@ for (const char* policy_key : metrics_keys) { PolicyMap::Entry* policy = policies->GetMutable(policy_key); if (policy && policy->level != POLICY_LEVEL_RECOMMENDED && - policy->value() && policy->value()->is_bool() && - policy->value()->GetBool()) { + policy->value(base::Value::Type::BOOLEAN) && + policy->value(base::Value::Type::BOOLEAN)->GetBool()) { policy->level = POLICY_LEVEL_RECOMMENDED; policy->AddMessage(PolicyMap::MessageType::kInfo, IDS_POLICY_IGNORED_MANDATORY_REPORTING_POLICY); @@ -142,7 +142,8 @@ const PolicyBundle& bundle, const PolicyNamespace& space, const std::string& policy) { - return ValueToStringSet(bundle.Get(space).GetValue(policy)); + return ValueToStringSet( + bundle.Get(space).GetValue(policy, base::Value::Type::LIST)); } } // namespace @@ -363,17 +364,17 @@ // This has to be done after setting enterprise default values since it is // enabled by default for enterprise users. - auto* atomic_policy_group_enabled_policy_value = + auto* atomic_policy_group_enabled_entry = chrome_policies.Get(key::kPolicyAtomicGroupsEnabled); // This policy has to be ignored if it comes from a user signed-in profile. bool atomic_policy_group_enabled = - atomic_policy_group_enabled_policy_value && - atomic_policy_group_enabled_policy_value->value()->GetIfBool().value_or( - false) && - !(atomic_policy_group_enabled_policy_value->source == - POLICY_SOURCE_CLOUD && - atomic_policy_group_enabled_policy_value->scope == POLICY_SCOPE_USER); + atomic_policy_group_enabled_entry && + atomic_policy_group_enabled_entry->value(base::Value::Type::BOOLEAN) && + atomic_policy_group_enabled_entry->value(base::Value::Type::BOOLEAN) + ->GetBool() && + !(atomic_policy_group_enabled_entry->source == POLICY_SOURCE_CLOUD && + atomic_policy_group_enabled_entry->scope == POLICY_SCOPE_USER); PolicyListMerger policy_list_merger(std::move(policy_lists_to_merge)); PolicyDictionaryMerger policy_dictionary_merger( @@ -381,11 +382,10 @@ // Pass affiliation and CloudUserPolicyMerge values to both mergers. const bool is_user_affiliated = chrome_policies.IsUserAffiliated(); + const base::Value* cloud_user_policy_merge_value = chrome_policies.GetValue( + key::kCloudUserPolicyMerge, base::Value::Type::BOOLEAN); const bool is_user_cloud_merging_enabled = - chrome_policies.GetValue(key::kCloudUserPolicyMerge) && - chrome_policies.GetValue(key::kCloudUserPolicyMerge) - ->GetIfBool() - .value_or(false); + cloud_user_policy_merge_value && cloud_user_policy_merge_value->GetBool(); policy_list_merger.SetAllowUserCloudPolicyMerging( is_user_affiliated && is_user_cloud_merging_enabled); policy_dictionary_merger.SetAllowUserCloudPolicyMerging(
diff --git a/components/policy/core/common/policy_service_impl_unittest.cc b/components/policy/core/common/policy_service_impl_unittest.cc index fe90616..28e4800 100644 --- a/components/policy/core/common/policy_service_impl_unittest.cc +++ b/components/policy/core/common/policy_service_impl_unittest.cc
@@ -592,8 +592,8 @@ const PolicyMap& policies = policy_service_->GetPolicies( PolicyNamespace(POLICY_DOMAIN_CHROME, std::string())); - EXPECT_EQ(kValue2, *policies.GetValue("aaa")); - EXPECT_EQ(kValue0, *policies.GetValue("bbb")); + EXPECT_EQ(kValue2, *policies.GetValue("aaa", base::Value::Type::INTEGER)); + EXPECT_EQ(kValue0, *policies.GetValue("bbb", base::Value::Type::INTEGER)); } TEST_F(PolicyServiceTest, NamespaceMerge) { @@ -1745,7 +1745,7 @@ policies_2.emplace_back(key::kExtensionInstallForcelist, list2.Clone()); policies_2.emplace_back(key::kExtensionInstallBlocklist, list2.Clone()); policies_2.emplace_back(key::kExtensionInstallAllowlist, - entry_list_3.value()->Clone()); + entry_list_3.value(base::Value::Type::LIST)->Clone()); auto policy_bundle_2 = CreateBundle(POLICY_SCOPE_MACHINE, POLICY_SOURCE_CLOUD, std::move(policies_2), chrome_namespace); @@ -2232,14 +2232,17 @@ // Precedence metapolicies set from a user cloud source are ignored. EXPECT_EQ(nullptr, policy_service_->GetPolicies(chrome_namespace) - .GetValue(key::kCloudPolicyOverridesPlatformPolicy)); + .GetValue(key::kCloudPolicyOverridesPlatformPolicy, + base::Value::Type::BOOLEAN)); EXPECT_EQ(nullptr, policy_service_->GetPolicies(chrome_namespace) - .GetValue(key::kCloudUserPolicyOverridesCloudMachinePolicy)); + .GetValue(key::kCloudUserPolicyOverridesCloudMachinePolicy, + base::Value::Type::BOOLEAN)); // Other policies set from a user cloud source are not ignored. EXPECT_NE(nullptr, policy_service_->GetPolicies(chrome_namespace) - .GetValue(key::kBookmarkBarEnabled)); + .GetValue(key::kBookmarkBarEnabled, + base::Value::Type::BOOLEAN)); } } // namespace policy
diff --git a/components/policy/core/common/policy_test_utils.cc b/components/policy/core/common/policy_test_utils.cc index aa8f2d7..59cf85c 100644 --- a/components/policy/core/common/policy_test_utils.cc +++ b/components/policy/core/common/policy_test_utils.cc
@@ -47,8 +47,8 @@ PolicyNamespace(POLICY_DOMAIN_CHROME, std::string())); if (!map.empty()) { base::DictionaryValue dict; - for (auto it = map.begin(); it != map.end(); ++it) - dict.SetKey(it->first, it->second.value()->Clone()); + for (const auto& it : map) + dict.SetKey(it.first, it.second.value_unsafe()->Clone()); LOG(WARNING) << "There are pre-existing policies in this machine: " << dict; #if BUILDFLAG(IS_WIN) LOG(WARNING) << "From: " << kRegistryChromePolicyKey; @@ -182,7 +182,7 @@ return os << "{" << std::endl << " \"level\": " << e.level << "," << std::endl << " \"scope\": " << e.scope << "," << std::endl - << " \"value\": " << *e.value() << "}"; + << " \"value\": " << *e.value_unsafe() << "}"; } std::ostream& operator<<(std::ostream& os, const policy::PolicyNamespace& ns) {
diff --git a/components/policy/core/common/schema_map.cc b/components/policy/core/common/schema_map.cc index 5e1c997..66841fb 100644 --- a/components/policy/core/common/schema_map.cc +++ b/components/policy/core/common/schema_map.cc
@@ -67,10 +67,10 @@ PolicyMap::Entry& entry = it_map->second; const Schema policy_schema = schema->GetProperty(policy_name); - const bool has_value = entry.value(); + const bool has_value = entry.value_unsafe(); const bool is_valid = has_value && - policy_schema.Normalize(entry.value(), SCHEMA_ALLOW_UNKNOWN, + policy_schema.Normalize(entry.value_unsafe(), SCHEMA_ALLOW_UNKNOWN, /* out_error_path=*/nullptr, /* out_error=*/nullptr, /* out_changed=*/nullptr);
diff --git a/components/policy/core/common/values_util.cc b/components/policy/core/common/values_util.cc index 82d8dc6..c2b269f 100644 --- a/components/policy/core/common/values_util.cc +++ b/components/policy/core/common/values_util.cc
@@ -9,10 +9,7 @@ namespace policy { base::flat_set<std::string> ValueToStringSet(const base::Value* value) { - if (!value) - return base::flat_set<std::string>(); - - if (!value->is_list()) + if (!value || !value->is_list()) return base::flat_set<std::string>(); const auto& items = value->GetListDeprecated();
diff --git a/components/reading_list/features/reading_list_switches.cc b/components/reading_list/features/reading_list_switches.cc index b5b032a..7b0b63cd 100644 --- a/components/reading_list/features/reading_list_switches.cc +++ b/components/reading_list/features/reading_list_switches.cc
@@ -12,7 +12,7 @@ #if !BUILDFLAG(IS_IOS) namespace features { // Hosts some content in a side panel. https://crbug.com/1149995 -const base::Feature kSidePanel{"SidePanel", base::FEATURE_DISABLED_BY_DEFAULT}; +const base::Feature kSidePanel{"SidePanel", base::FEATURE_ENABLED_BY_DEFAULT}; } // namespace features #endif // !BUILDFLAG(IS_IOS)
diff --git a/components/ukm/android/java/src/org/chromium/components/ukm/UkmRecorder.java b/components/ukm/android/java/src/org/chromium/components/ukm/UkmRecorder.java index 2d3bdaf5..1013c49 100644 --- a/components/ukm/android/java/src/org/chromium/components/ukm/UkmRecorder.java +++ b/components/ukm/android/java/src/org/chromium/components/ukm/UkmRecorder.java
@@ -4,6 +4,8 @@ package org.chromium.components.ukm; +import androidx.annotation.VisibleForTesting; + import org.chromium.base.annotations.JNINamespace; import org.chromium.base.annotations.NativeMethods; import org.chromium.content_public.browser.WebContents; @@ -69,7 +71,8 @@ } @NativeMethods - interface Natives { + @VisibleForTesting(otherwise = VisibleForTesting.PACKAGE_PRIVATE) + public interface Natives { void recordEventWithBooleanMetric( WebContents webContents, String eventName, String metricName); void recordEventWithIntegerMetric(
diff --git a/components/viz/service/display/skia_renderer.cc b/components/viz/service/display/skia_renderer.cc index a53eb88..2e3a5954 100644 --- a/components/viz/service/display/skia_renderer.cc +++ b/components/viz/service/display/skia_renderer.cc
@@ -762,6 +762,7 @@ void SkiaRenderer::FinishDrawingFrame() { TRACE_EVENT0("viz", "SkiaRenderer::FinishDrawingFrame"); + root_canvas_ = nullptr; current_canvas_ = nullptr; current_surface_ = nullptr;
diff --git a/content/browser/BUILD.gn b/content/browser/BUILD.gn index d0e64e8..56fdba5e8 100644 --- a/content/browser/BUILD.gn +++ b/content/browser/BUILD.gn
@@ -432,6 +432,7 @@ "attribution_reporting/attribution_report_scheduler.h", "attribution_reporting/attribution_report_sender.h", "attribution_reporting/attribution_reporting.cc", + "attribution_reporting/attribution_source_type.cc", "attribution_reporting/attribution_source_type.h", "attribution_reporting/attribution_storage.cc", "attribution_reporting/attribution_storage.h",
diff --git a/content/browser/accessibility/browser_accessibility_cocoa.h b/content/browser/accessibility/browser_accessibility_cocoa.h index c2c23bd..31ac270 100644 --- a/content/browser/accessibility/browser_accessibility_cocoa.h +++ b/content/browser/accessibility/browser_accessibility_cocoa.h
@@ -119,7 +119,6 @@ @property(nonatomic, readonly) NSArray* children; @property(nonatomic, readonly) NSArray* columns; @property(nonatomic, readonly) NSValue* columnIndexRange; -@property(nonatomic, readonly) NSString* descriptionForAccessibility; @property(nonatomic, readonly) NSNumber* disclosing; @property(nonatomic, readonly) id disclosedByRow; @property(nonatomic, readonly) NSNumber* disclosureLevel;
diff --git a/content/browser/accessibility/browser_accessibility_cocoa.mm b/content/browser/accessibility/browser_accessibility_cocoa.mm index 656ba9b..d76c979 100644 --- a/content/browser/accessibility/browser_accessibility_cocoa.mm +++ b/content/browser/accessibility/browser_accessibility_cocoa.mm
@@ -537,18 +537,6 @@ return true; } -void AppendTextToString(const std::string& extra_text, std::string* string) { - if (extra_text.empty()) - return; - - if (string->empty()) { - *string = extra_text; - return; - } - - *string += std::string(". ") + extra_text; -} - bool IsSelectedStateRelevant(BrowserAccessibility* item) { if (!item->HasBoolAttribute(ax::mojom::BoolAttribute::kSelected)) return false; // Does not have selected state -> not relevant. @@ -611,7 +599,6 @@ {NSAccessibilityColumnsAttribute, @"columns"}, {NSAccessibilityColumnIndexRangeAttribute, @"columnIndexRange"}, {NSAccessibilityContentsAttribute, @"contents"}, - {NSAccessibilityDescriptionAttribute, @"descriptionForAccessibility"}, {NSAccessibilityDisclosingAttribute, @"disclosing"}, {NSAccessibilityDisclosedByRowAttribute, @"disclosedByRow"}, {NSAccessibilityDisclosureLevelAttribute, @"disclosureLevel"}, @@ -781,91 +768,6 @@ return table; } -- (NSString*)AXDescription { - return [self descriptionForAccessibility]; -} - -- (NSString*)descriptionForAccessibility { - if (![self instanceActive]) - return nil; - - // Mac OS X wants static text exposed in AXValue. - if (ui::IsNameExposedInAXValueForRole([self internalRole])) - return @""; - - // If we're exposing the title in TitleUIElement, don't also redundantly - // expose it in AXDescription. - if ([self titleUIElement]) - return @""; - - ax::mojom::NameFrom nameFrom = static_cast<ax::mojom::NameFrom>( - _owner->GetIntAttribute(ax::mojom::IntAttribute::kNameFrom)); - std::string name = _owner->GetName(); - - auto status = _owner->GetData().GetImageAnnotationStatus(); - switch (status) { - case ax::mojom::ImageAnnotationStatus::kEligibleForAnnotation: - case ax::mojom::ImageAnnotationStatus::kAnnotationPending: - case ax::mojom::ImageAnnotationStatus::kAnnotationEmpty: - case ax::mojom::ImageAnnotationStatus::kAnnotationAdult: - case ax::mojom::ImageAnnotationStatus::kAnnotationProcessFailed: { - std::u16string status_string = - _owner->GetLocalizedStringForImageAnnotationStatus(status); - AppendTextToString(base::UTF16ToUTF8(status_string), &name); - break; - } - - case ax::mojom::ImageAnnotationStatus::kAnnotationSucceeded: - AppendTextToString(_owner->GetStringAttribute( - ax::mojom::StringAttribute::kImageAnnotation), - &name); - break; - - case ax::mojom::ImageAnnotationStatus::kNone: - case ax::mojom::ImageAnnotationStatus::kWillNotAnnotateDueToScheme: - case ax::mojom::ImageAnnotationStatus::kIneligibleForAnnotation: - case ax::mojom::ImageAnnotationStatus::kSilentlyEligibleForAnnotation: - break; - } - - if (!name.empty()) { - // On Mac OS X, the accessible name of an object is exposed as its - // title if it comes from visible text, and as its description - // otherwise, but never both. - - // Group, radiogroup etc. - if ([self shouldExposeNameInDescription]) { - return base::SysUTF8ToNSString(name); - } else if (nameFrom == ax::mojom::NameFrom::kCaption || - nameFrom == ax::mojom::NameFrom::kContents || - nameFrom == ax::mojom::NameFrom::kRelatedElement || - nameFrom == ax::mojom::NameFrom::kValue) { - return @""; - } else { - return base::SysUTF8ToNSString(name); - } - } - - // Given an image where there's no other title, return the base part - // of the filename as the description. - if ([[self role] isEqualToString:NSAccessibilityImageRole]) { - if ([self accessibilityTitleUIElement]) - return @""; - - std::string url; - if (_owner->GetStringAttribute(ax::mojom::StringAttribute::kUrl, &url)) { - // Given a url like http://foo.com/bar/baz.png, just return the - // base name, e.g., "baz.png". - size_t leftIndex = url.rfind('/'); - std::string basename = - leftIndex != std::string::npos ? url.substr(leftIndex) : url; - return base::SysUTF8ToNSString(basename); - } - } - - return @""; -} - - (NSNumber*)disclosing { if (![self instanceActive]) return nil; @@ -1218,41 +1120,6 @@ return ax::mojom::Role::kNone; } -- (BOOL)shouldExposeNameInDescription { - // Image annotations are not visible text, so they should be exposed - // as a description and not a title. - switch (_owner->GetData().GetImageAnnotationStatus()) { - case ax::mojom::ImageAnnotationStatus::kEligibleForAnnotation: - case ax::mojom::ImageAnnotationStatus::kAnnotationPending: - case ax::mojom::ImageAnnotationStatus::kAnnotationEmpty: - case ax::mojom::ImageAnnotationStatus::kAnnotationAdult: - case ax::mojom::ImageAnnotationStatus::kAnnotationProcessFailed: - case ax::mojom::ImageAnnotationStatus::kAnnotationSucceeded: - return true; - - case ax::mojom::ImageAnnotationStatus::kNone: - case ax::mojom::ImageAnnotationStatus::kWillNotAnnotateDueToScheme: - case ax::mojom::ImageAnnotationStatus::kIneligibleForAnnotation: - case ax::mojom::ImageAnnotationStatus::kSilentlyEligibleForAnnotation: - break; - } - - // VoiceOver computes the wrong description for a link. - if (ui::IsLink(_owner->GetRole())) - return true; - - // VoiceOver will not read the label of these roles unless it is - // exposed in the description instead of the title. - switch (_owner->GetRole()) { - case ax::mojom::Role::kGenericContainer: - case ax::mojom::Role::kGroup: - case ax::mojom::Role::kRadioGroup: - return true; - default: - return false; - } -} - - (content::BrowserAccessibility*)owner { return _owner; } @@ -1668,7 +1535,7 @@ if (ui::IsNameExposedInAXValueForRole([self internalRole])) return @""; - if ([self shouldExposeNameInDescription]) + if ([self isLabelable]) return @""; // If we're exposing the title in TitleUIElement, don't also redundantly @@ -2622,7 +2489,6 @@ // General attributes. NSMutableArray* ret = [NSMutableArray arrayWithObjects:NSAccessibilityChildrenAttribute, - NSAccessibilityDescriptionAttribute, NSAccessibilityEnabledAttribute, NSAccessibilityEndTextMarkerAttribute, NSAccessibilityFocusedAttribute,
diff --git a/content/browser/accessibility/browser_accessibility_cocoa_browsertest.mm b/content/browser/accessibility/browser_accessibility_cocoa_browsertest.mm index 05cfc8e5..56ab7e0e 100644 --- a/content/browser/accessibility/browser_accessibility_cocoa_browsertest.mm +++ b/content/browser/accessibility/browser_accessibility_cocoa_browsertest.mm
@@ -403,7 +403,7 @@ [child->GetNativeViewAccessible() retain]); EXPECT_NSEQ(base::SysUTF8ToNSString(expected_descriptions[child_index]), - [child_obj descriptionForAccessibility]); + [child_obj accessibilityLabel]); } } @@ -492,13 +492,13 @@ EXPECT_EQ(3U, [row_nodes count]); EXPECT_NSEQ(@"AXRow", [row_nodes[0] role]); - EXPECT_NSEQ(@"row1", [row_nodes[0] descriptionForAccessibility]); + EXPECT_NSEQ(@"row1", [row_nodes[0] accessibilityLabel]); EXPECT_NSEQ(@"AXRow", [row_nodes[1] role]); - EXPECT_NSEQ(@"row2", [row_nodes[1] descriptionForAccessibility]); + EXPECT_NSEQ(@"row2", [row_nodes[1] accessibilityLabel]); EXPECT_NSEQ(@"AXRow", [row_nodes[2] role]); - EXPECT_NSEQ(@"row3", [row_nodes[2] descriptionForAccessibility]); + EXPECT_NSEQ(@"row3", [row_nodes[2] accessibilityLabel]); } IN_PROC_BROWSER_TEST_F(BrowserAccessibilityCocoaBrowserTest, @@ -539,14 +539,14 @@ base::scoped_nsobject<BrowserAccessibilityCocoa> col_obj( [column->GetNativeViewAccessible() retain]); EXPECT_NSEQ(@"AXColumn", [col_obj role]); - EXPECT_NSEQ(@"column1", [col_obj descriptionForAccessibility]); + EXPECT_NSEQ(@"column1", [col_obj accessibilityLabel]); NSArray* row_nodes = [col_obj rows]; EXPECT_NSEQ(@"AXRow", [row_nodes[0] role]); - EXPECT_NSEQ(@"row1", [row_nodes[0] descriptionForAccessibility]); + EXPECT_NSEQ(@"row1", [row_nodes[0] accessibilityLabel]); EXPECT_NSEQ(@"AXRow", [row_nodes[1] role]); - EXPECT_NSEQ(@"row2", [row_nodes[1] descriptionForAccessibility]); + EXPECT_NSEQ(@"row2", [row_nodes[1] accessibilityLabel]); } IN_PROC_BROWSER_TEST_F(BrowserAccessibilityCocoaBrowserTest,
diff --git a/content/browser/accessibility/browser_accessibility_mac_unittest.mm b/content/browser/accessibility/browser_accessibility_mac_unittest.mm index e42265d1..2481608 100644 --- a/content/browser/accessibility/browser_accessibility_mac_unittest.mm +++ b/content/browser/accessibility/browser_accessibility_mac_unittest.mm
@@ -130,14 +130,14 @@ TEST_F(BrowserAccessibilityMacTest, HitTestTest) { BrowserAccessibilityCocoa* firstChild = [accessibility_ accessibilityHitTest:NSMakePoint(50, 50)]; - EXPECT_NSEQ(@"Child1", firstChild.descriptionForAccessibility); + EXPECT_NSEQ(@"Child1", firstChild.accessibilityLabel); } // Test doing a hit test on the edge of a child. TEST_F(BrowserAccessibilityMacTest, EdgeHitTest) { BrowserAccessibilityCocoa* firstChild = [accessibility_ accessibilityHitTest:NSZeroPoint]; - EXPECT_NSEQ(@"Child1", firstChild.descriptionForAccessibility); + EXPECT_NSEQ(@"Child1", firstChild.accessibilityLabel); } // This will test a hit test with invalid coordinates. It is assumed that @@ -158,7 +158,7 @@ // Get the first child. BrowserAccessibilityCocoa* retainedFirstChild = [accessibility_ accessibilityHitTest:NSMakePoint(50, 50)]; - EXPECT_NSEQ(@"Child1", retainedFirstChild.descriptionForAccessibility); + EXPECT_NSEQ(@"Child1", retainedFirstChild.accessibilityLabel); // Retain it. This simulates what the system might do with an // accessibility object. @@ -168,7 +168,7 @@ RebuildAccessibilityTree(); // Now any attributes we query should return nil. - EXPECT_NSEQ(nil, retainedFirstChild.descriptionForAccessibility); + EXPECT_NSEQ(nil, retainedFirstChild.accessibilityLabel); // Don't leak memory in the test. [retainedFirstChild release];
diff --git a/content/browser/accessibility/dump_accessibility_scripts_browsertest.cc b/content/browser/accessibility/dump_accessibility_scripts_browsertest.cc index 98dfb3f2..0fb88d7 100644 --- a/content/browser/accessibility/dump_accessibility_scripts_browsertest.cc +++ b/content/browser/accessibility/dump_accessibility_scripts_browsertest.cc
@@ -211,6 +211,10 @@ RunTypedTest<kMacAttributes>("ax-column-header-ui-elements.html"); } +IN_PROC_BROWSER_TEST_P(DumpAccessibilityScriptTest, AXDescription) { + RunTypedTest<kMacAttributes>("ax-description.html"); +} + IN_PROC_BROWSER_TEST_P(DumpAccessibilityScriptTest, AXDetailsElements) { RunTypedTest<kMacAttributes>("ax-details-elements.html"); } @@ -399,6 +403,10 @@ RunTypedTest<kMacMethods>("accessibility-is-ignored.html"); } +IN_PROC_BROWSER_TEST_P(DumpAccessibilityScriptTest, AccessibilityLabel) { + RunTypedTest<kMacMethods>("accessibility-label.html"); +} + IN_PROC_BROWSER_TEST_P(DumpAccessibilityScriptTest, AccessibilityPlaceholderValue) { RunTypedTest<kMacMethods>("accessibility-placeholder-value.html");
diff --git a/content/browser/accessibility/dump_accessibility_tree_browsertest.cc b/content/browser/accessibility/dump_accessibility_tree_browsertest.cc index 8f4bfc08..ff79ece 100644 --- a/content/browser/accessibility/dump_accessibility_tree_browsertest.cc +++ b/content/browser/accessibility/dump_accessibility_tree_browsertest.cc
@@ -1887,6 +1887,12 @@ RunHtmlTest(FILE_PATH_LITERAL("footer-inside-other-section.html")); } +IN_PROC_BROWSER_TEST_P(DumpAccessibilityTreeTest, + AccessibilityFooterInsideSectionRoleGeneric) { + RunRegressionTest( + FILE_PATH_LITERAL("footer-inside-section-role-generic.html")); +} + IN_PROC_BROWSER_TEST_P(DumpAccessibilityTreeTest, AccessibilityForm) { RunHtmlTest(FILE_PATH_LITERAL("form.html")); } @@ -1943,6 +1949,12 @@ RunHtmlTest(FILE_PATH_LITERAL("header-inside-other-section.html")); } +IN_PROC_BROWSER_TEST_P(DumpAccessibilityTreeTest, + AccessibilityHeaderInsideSectionRoleGeneric) { + RunRegressionTest( + FILE_PATH_LITERAL("header-inside-section-role-generic.html")); +} + IN_PROC_BROWSER_TEST_P(DumpAccessibilityTreeTest, AccessibilityHeading) { RunHtmlTest(FILE_PATH_LITERAL("heading.html")); }
diff --git a/content/browser/aggregation_service/aggregatable_report.cc b/content/browser/aggregation_service/aggregatable_report.cc index 2a3fbda..8296e31 100644 --- a/content/browser/aggregation_service/aggregatable_report.cc +++ b/content/browser/aggregation_service/aggregatable_report.cc
@@ -486,14 +486,11 @@ kDomainSeparationPrefix + sizeof(kDomainSeparationPrefix)); std::string encoded_shared_info = - report_request.shared_info_.SerializeAsJson(); + report_request.shared_info().SerializeAsJson(); authenticated_info.insert(authenticated_info.end(), encoded_shared_info.begin(), encoded_shared_info.end()); - // To avoid unnecessary copies, we move the processing urls and shared info - // from the `report_request`'s private members. Note that the request object - // is destroyed at the end of this method. std::vector<AggregatableReport::AggregationServicePayload> encrypted_payloads; DCHECK_EQ(unencrypted_payloads.size(), num_processing_urls); for (size_t i = 0; i < num_processing_urls; ++i) {
diff --git a/content/browser/aggregation_service/aggregatable_report.h b/content/browser/aggregation_service/aggregatable_report.h index 89225a0..365764b9 100644 --- a/content/browser/aggregation_service/aggregatable_report.h +++ b/content/browser/aggregation_service/aggregatable_report.h
@@ -274,10 +274,6 @@ } private: - // To avoid unnecessary copies, allow the provider to directly access members - // of the AggregatableReportRequest being consumed. - friend class AggregatableReport::Provider; - static absl::optional<AggregatableReportRequest> CreateInternal( std::vector<GURL> processing_urls, AggregationServicePayloadContents payload_contents,
diff --git a/content/browser/attribution_reporting/aggregatable_attribution_utils_unittest.cc b/content/browser/attribution_reporting/aggregatable_attribution_utils_unittest.cc index 00b5240..39900b6 100644 --- a/content/browser/attribution_reporting/aggregatable_attribution_utils_unittest.cc +++ b/content/browser/attribution_reporting/aggregatable_attribution_utils_unittest.cc
@@ -98,7 +98,7 @@ Values{{"key1", 32768}, {"key2", 1664}}); absl::optional<AttributionFilterData> source_filter_data = - AttributionFilterData::FromFilterValues({{"filter", {"value"}}}); + AttributionFilterData::FromSourceFilterValues({{"filter", {"value"}}}); ASSERT_TRUE(source_filter_data.has_value()); absl::optional<AttributionAggregatableSources> sources =
diff --git a/content/browser/attribution_reporting/attribution_aggregatable_trigger.cc b/content/browser/attribution_reporting/attribution_aggregatable_trigger.cc index 93faa6d..0219bc9 100644 --- a/content/browser/attribution_reporting/attribution_aggregatable_trigger.cc +++ b/content/browser/attribution_reporting/attribution_aggregatable_trigger.cc
@@ -29,13 +29,13 @@ return absl::nullopt; absl::optional<AttributionFilterData> filters = - AttributionFilterData::FromFilterValues( + AttributionFilterData::FromTriggerFilterValues( std::move(mojo->filters->filter_values)); if (!filters.has_value()) return absl::nullopt; absl::optional<AttributionFilterData> not_filters = - AttributionFilterData::FromFilterValues( + AttributionFilterData::FromTriggerFilterValues( std::move(mojo->not_filters->filter_values)); if (!not_filters.has_value()) return absl::nullopt;
diff --git a/content/browser/attribution_reporting/attribution_data_host_manager_impl.cc b/content/browser/attribution_reporting/attribution_data_host_manager_impl.cc index f337ca7f..ae5cd72 100644 --- a/content/browser/attribution_reporting/attribution_data_host_manager_impl.cc +++ b/content/browser/attribution_reporting/attribution_data_host_manager_impl.cc
@@ -104,16 +104,11 @@ } absl::optional<AttributionFilterData> filter_data = - AttributionFilterData::FromFilterValues( + AttributionFilterData::FromSourceFilterValues( std::move(data->filter_data->filter_values)); if (!filter_data.has_value()) return; - // "source_type" is automatically generated in source filter data during - // attribution source matching, so it is an error to specify it here. - if (filter_data->filter_values().contains("source_type")) - return; - absl::optional<AttributionAggregatableSources> aggregatable_sources = AttributionAggregatableSources::Create( ConvertToProto(*data->aggregatable_sources));
diff --git a/content/browser/attribution_reporting/attribution_filter_data.cc b/content/browser/attribution_reporting/attribution_filter_data.cc index 105d63d..f8a6487 100644 --- a/content/browser/attribution_reporting/attribution_filter_data.cc +++ b/content/browser/attribution_reporting/attribution_filter_data.cc
@@ -14,15 +14,32 @@ namespace content { +namespace { + +constexpr char kFilterSourceType[] = "source_type"; + +} // namespace + // static -absl::optional<AttributionFilterData> AttributionFilterData::Deserialize( - const std::string& string) { +absl::optional<AttributionFilterData> +AttributionFilterData::DeserializeSourceFilterData( + const std::string& string, + AttributionSourceType source_type) { proto::AttributionFilterData msg; if (!msg.ParseFromString(string)) return absl::nullopt; FilterValues::container_type filter_values; - filter_values.reserve(msg.filter_values().size()); + filter_values.reserve(msg.filter_values().size() + 1); + + // Add the auto-generated filter first so that it is retained instead of any + // existing filter of the same name in `msg`, which should only be possible + // with database corruption (extremely unlikely) or deliberate modification of + // the DB. This approach works because `base::flat_map` uses a stable + // sort/unique when being constructed from an existing container. + filter_values.emplace_back( + kFilterSourceType, + std::vector<std::string>{AttributionSourceTypeToString(source_type)}); for (google::protobuf::MapPair<std::string, proto::AttributionFilterValues>& entry : *msg.mutable_filter_values()) { @@ -35,14 +52,38 @@ std::make_move_iterator(values->end()))); } - return AttributionFilterData::FromFilterValues(std::move(filter_values)); + return FromFilterValues(std::move(filter_values), + /*extra_filters_allowed=*/1); +} + +// static +absl::optional<AttributionFilterData> +AttributionFilterData::FromSourceFilterValues(FilterValues&& filter_values) { + absl::optional<AttributionFilterData> result = + FromFilterValues(std::move(filter_values), + /*extra_filters_allowed=*/0); + + if (!result || result->filter_values_.contains(kFilterSourceType)) + return absl::nullopt; + + return result; +} + +// static +absl::optional<AttributionFilterData> +AttributionFilterData::FromTriggerFilterValues(FilterValues&& filter_values) { + return FromFilterValues(std::move(filter_values), + /*extra_filters_allowed=*/0); } // static absl::optional<AttributionFilterData> AttributionFilterData::FromFilterValues( - FilterValues&& filter_values) { - if (filter_values.size() > blink::kMaxAttributionFiltersPerSource) + FilterValues&& filter_values, + size_t extra_filters_allowed) { + if (filter_values.size() > + blink::kMaxAttributionFiltersPerSource + extra_filters_allowed) { return absl::nullopt; + } for (const auto& [filter, values] : filter_values) { if (filter.size() > blink::kMaxBytesPerAttributionFilterString) @@ -60,6 +101,12 @@ return AttributionFilterData(std::move(filter_values)); } +// static +AttributionFilterData AttributionFilterData::CreateForTesting( + FilterValues filter_values) { + return AttributionFilterData(std::move(filter_values)); +} + AttributionFilterData::AttributionFilterData() = default; AttributionFilterData::AttributionFilterData(FilterValues filter_values) @@ -79,6 +126,8 @@ AttributionFilterData&&) = default; std::string AttributionFilterData::Serialize() const { + DCHECK(!filter_values_.contains(kFilterSourceType)); + proto::AttributionFilterData msg; for (const auto& [filter, values] : filter_values_) {
diff --git a/content/browser/attribution_reporting/attribution_filter_data.h b/content/browser/attribution_reporting/attribution_filter_data.h index 9f7a77c..8f97265 100644 --- a/content/browser/attribution_reporting/attribution_filter_data.h +++ b/content/browser/attribution_reporting/attribution_filter_data.h
@@ -5,10 +5,13 @@ #ifndef CONTENT_BROWSER_ATTRIBUTION_REPORTING_ATTRIBUTION_FILTER_DATA_H_ #define CONTENT_BROWSER_ATTRIBUTION_REPORTING_ATTRIBUTION_FILTER_DATA_H_ +#include <stddef.h> + #include <string> #include <vector> #include "base/containers/flat_map.h" +#include "content/browser/attribution_reporting/attribution_source_type.h" #include "content/common/content_export.h" #include "third_party/abseil-cpp/absl/types/optional.h" @@ -19,9 +22,25 @@ public: using FilterValues = base::flat_map<std::string, std::vector<std::string>>; - static absl::optional<AttributionFilterData> Deserialize(const std::string&); + // Deserializes `string`, if valid. Returns `absl::nullopt` if not. + // + // If deserialization succeeded, the returned filter data will also contain a + // "source_type" key corresponding to `source_type`, representing the + // autogenerated field of the same name. + static absl::optional<AttributionFilterData> DeserializeSourceFilterData( + const std::string& string, + AttributionSourceType source_type); - static absl::optional<AttributionFilterData> FromFilterValues(FilterValues&&); + // Source filter data is not allowed to contain a `source_type` filter. + static absl::optional<AttributionFilterData> FromSourceFilterValues( + FilterValues&&); + + // Trigger filter data is allowed to contain a `source_type` filter. + static absl::optional<AttributionFilterData> FromTriggerFilterValues( + FilterValues&&); + + // Creates without validation. + static AttributionFilterData CreateForTesting(FilterValues); AttributionFilterData(); @@ -38,6 +57,10 @@ std::string Serialize() const; private: + static absl::optional<AttributionFilterData> FromFilterValues( + FilterValues&& filter_values, + size_t extra_filters_allowed); + explicit AttributionFilterData(FilterValues filter_values); FilterValues filter_values_;
diff --git a/content/browser/attribution_reporting/attribution_filter_data_unittest.cc b/content/browser/attribution_reporting/attribution_filter_data_unittest.cc new file mode 100644 index 0000000..9c1b849523 --- /dev/null +++ b/content/browser/attribution_reporting/attribution_filter_data_unittest.cc
@@ -0,0 +1,126 @@ +// Copyright 2022 The Chromium 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/attribution_reporting/attribution_filter_data.h" + +#include <stddef.h> + +#include <string> +#include <utility> +#include <vector> + +#include "base/check.h" +#include "base/strings/string_number_conversions.h" +#include "content/browser/attribution_reporting/attribution_reporting.pb.h" +#include "content/browser/attribution_reporting/attribution_source_type.h" +#include "testing/gmock/include/gmock/gmock.h" +#include "testing/gtest/include/gtest/gtest.h" +#include "third_party/abseil-cpp/absl/types/optional.h" +#include "third_party/blink/public/common/attribution_reporting/constants.h" + +namespace content { + +namespace { + +using ::testing::ElementsAre; +using ::testing::Pair; + +std::string CreateSerialized( + const AttributionFilterData::FilterValues& filter_values) { + proto::AttributionFilterData msg; + + for (const auto& [filter, values] : filter_values) { + proto::AttributionFilterValues filter_values_msg; + for (std::string value : values) { + filter_values_msg.mutable_values()->Add(std::move(value)); + } + (*msg.mutable_filter_values())[filter] = std::move(filter_values_msg); + } + + std::string string; + bool success = msg.SerializeToString(&string); + CHECK(success); + return string; +} + +AttributionFilterData::FilterValues CreateFilterValues(size_t n) { + AttributionFilterData::FilterValues filter_values; + for (size_t i = 0; i < n; i++) { + filter_values.emplace(base::NumberToString(i), std::vector<std::string>()); + } + CHECK_EQ(filter_values.size(), n); + return filter_values; +} + +// Tests that a "source_type" filter present in the serialized data is +// overridden by the autogenerated one. +TEST(AttributionFilterDataTest, + DeserializeSourceFilterData_OverridesSourceTypeFilter) { + const std::string serialized = CreateSerialized({{"source_type", {"abc"}}}); + + EXPECT_THAT(AttributionFilterData::DeserializeSourceFilterData( + serialized, AttributionSourceType::kEvent) + ->filter_values(), + ElementsAre(Pair("source_type", ElementsAre("event")))); + + EXPECT_THAT(AttributionFilterData::DeserializeSourceFilterData( + serialized, AttributionSourceType::kNavigation) + ->filter_values(), + ElementsAre(Pair("source_type", ElementsAre("navigation")))); +} + +// Tests that serialized data is allowed +// `blink::kMaxAttributionFiltersPerSource` + 1 filters to account for the +// autogenerated "source_type" filter. +TEST(AttributionFilterDataTest, + DeserializeSourceFilterData_AllowsOneExtraFilter) { + EXPECT_TRUE(AttributionFilterData::DeserializeSourceFilterData( + CreateSerialized(CreateFilterValues( + blink::kMaxAttributionFiltersPerSource)), + AttributionSourceType::kEvent) + .has_value()); + + EXPECT_FALSE(AttributionFilterData::DeserializeSourceFilterData( + CreateSerialized(CreateFilterValues( + blink::kMaxAttributionFiltersPerSource + 1)), + AttributionSourceType::kEvent) + .has_value()); +} + +TEST(AttributionFilterDataTest, + FromSourceFilterValues_ProhibitsSourceTypeFilter) { + EXPECT_FALSE(AttributionFilterData::FromSourceFilterValues( + {{"source_type", {"event"}}})); +} + +TEST(AttributionFilterDataTest, + FromTriggerFilterValues_AllowsSourceTypeFilter) { + EXPECT_TRUE(AttributionFilterData::FromTriggerFilterValues( + {{"source_type", {"event"}}})); +} + +TEST(AttributionFilterDatTest, FromSourceFilterValues_LimitsFilterCount) { + EXPECT_TRUE(AttributionFilterData::FromSourceFilterValues( + CreateFilterValues(blink::kMaxAttributionFiltersPerSource)) + .has_value()); + + EXPECT_FALSE( + AttributionFilterData::FromSourceFilterValues( + CreateFilterValues(blink::kMaxAttributionFiltersPerSource + 1)) + .has_value()); +} + +TEST(AttributionFilterDatTest, FromTriggerFilterValues_LimitsFilterCount) { + EXPECT_TRUE(AttributionFilterData::FromTriggerFilterValues( + CreateFilterValues(blink::kMaxAttributionFiltersPerSource)) + .has_value()); + + EXPECT_FALSE( + AttributionFilterData::FromTriggerFilterValues( + CreateFilterValues(blink::kMaxAttributionFiltersPerSource + 1)) + .has_value()); +} + +} // namespace +} // namespace content
diff --git a/content/browser/attribution_reporting/attribution_manager_impl_unittest.cc b/content/browser/attribution_reporting/attribution_manager_impl_unittest.cc index ec817e0..f94f11b 100644 --- a/content/browser/attribution_reporting/attribution_manager_impl_unittest.cc +++ b/content/browser/attribution_reporting/attribution_manager_impl_unittest.cc
@@ -359,14 +359,13 @@ }; TEST_F(AttributionManagerImplTest, ImpressionRegistered_ReturnedToWebUI) { - auto impression = SourceBuilder() - .SetExpiry(kImpressionExpiry) - .SetSourceEventId(100) - .Build(); - attribution_manager_->HandleSource(impression); + SourceBuilder builder; + builder.SetExpiry(kImpressionExpiry).SetSourceEventId(100); + attribution_manager_->HandleSource(builder.Build()); EXPECT_THAT(StoredSources(), - ElementsAre(CommonSourceInfoIs(impression.common_info()))); + ElementsAre(CommonSourceInfoIs( + builder.SetDefaultFilterData().BuildCommonInfo()))); } TEST_F(AttributionManagerImplTest, ExpiredImpression_NotReturnedToWebUI) { @@ -388,9 +387,10 @@ attribution_manager_->HandleTrigger(conversion); AttributionReport expected_report = - ReportBuilder(AttributionInfoBuilder(builder.BuildStored()) - .SetTime(base::Time::Now()) - .Build()) + ReportBuilder( + AttributionInfoBuilder(builder.SetDefaultFilterData().BuildStored()) + .SetTime(base::Time::Now()) + .Build()) .SetTriggerData(5) .SetReportTime(base::Time::Now() + kFirstReportingWindow) .Build(); @@ -1068,6 +1068,7 @@ SourceBuilder builder; builder.SetExpiry(kImpressionExpiry).SetSourceEventId(7); + StorableSource source = builder.Build(); Checkpoint checkpoint; { @@ -1089,11 +1090,11 @@ EXPECT_CALL(observer, OnReportsChanged).Times(0); EXPECT_CALL(observer, OnSourceDeactivated(DeactivatedSource{ - builder.BuildStored(), + builder.SetDefaultFilterData().BuildStored(), DeactivatedSource::Reason::kReplacedByNewerSource})); } - attribution_manager_->HandleSource(builder.Build()); + attribution_manager_->HandleSource(source); EXPECT_THAT(StoredSources(), SizeIs(1)); checkpoint.Call(1); @@ -1114,6 +1115,7 @@ SourceBuilder builder; builder.SetExpiry(kImpressionExpiry).SetSourceEventId(7); + StorableSource source = builder.Build(); Checkpoint checkpoint; { @@ -1141,11 +1143,11 @@ EXPECT_CALL(observer, OnReportsChanged); EXPECT_CALL(observer, OnSourceDeactivated(DeactivatedSource{ - builder.BuildStored(), + builder.SetDefaultFilterData().BuildStored(), DeactivatedSource::Reason::kReachedAttributionLimit})); } - attribution_manager_->HandleSource(builder.Build()); + attribution_manager_->HandleSource(source); EXPECT_THAT(StoredSources(), SizeIs(1)); checkpoint.Call(1);
diff --git a/content/browser/attribution_reporting/attribution_report.cc b/content/browser/attribution_reporting/attribution_report.cc index 6157a23..dfcd6ae 100644 --- a/content/browser/attribution_reporting/attribution_report.cc +++ b/content/browser/attribution_reporting/attribution_report.cc
@@ -160,16 +160,8 @@ dict.SetStringKey("trigger_data", base::NumberToString(data.trigger_data)); - const char* source_type = nullptr; - switch (common_source_info.source_type()) { - case AttributionSourceType::kNavigation: - source_type = "navigation"; - break; - case AttributionSourceType::kEvent: - source_type = "event"; - break; - } - dict.SetStringKey("source_type", source_type); + dict.SetStringKey("source_type", AttributionSourceTypeToString( + common_source_info.source_type())); dict.SetStringKey("report_id", report->external_report_id().AsLowercaseString());
diff --git a/content/browser/attribution_reporting/attribution_source_type.cc b/content/browser/attribution_reporting/attribution_source_type.cc new file mode 100644 index 0000000..b1c2a62c --- /dev/null +++ b/content/browser/attribution_reporting/attribution_source_type.cc
@@ -0,0 +1,18 @@ +// Copyright 2022 The Chromium 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/attribution_reporting/attribution_source_type.h" + +namespace content { + +const char* AttributionSourceTypeToString(AttributionSourceType source_type) { + switch (source_type) { + case AttributionSourceType::kNavigation: + return "navigation"; + case AttributionSourceType::kEvent: + return "event"; + } +} + +} // namespace content
diff --git a/content/browser/attribution_reporting/attribution_source_type.h b/content/browser/attribution_reporting/attribution_source_type.h index d395f68..d0540f1a 100644 --- a/content/browser/attribution_reporting/attribution_source_type.h +++ b/content/browser/attribution_reporting/attribution_source_type.h
@@ -5,6 +5,8 @@ #ifndef CONTENT_BROWSER_ATTRIBUTION_REPORTING_ATTRIBUTION_SOURCE_TYPE_H_ #define CONTENT_BROWSER_ATTRIBUTION_REPORTING_ATTRIBUTION_SOURCE_TYPE_H_ +#include "content/common/content_export.h" + namespace content { // Denotes the type of source for this impression. This allows different types @@ -18,6 +20,9 @@ kMaxValue = kEvent, }; +// Returns "navigation" or "event". +CONTENT_EXPORT const char* AttributionSourceTypeToString(AttributionSourceType); + } // namespace content #endif // CONTENT_BROWSER_ATTRIBUTION_REPORTING_ATTRIBUTION_SOURCE_TYPE_H_
diff --git a/content/browser/attribution_reporting/attribution_storage_sql.cc b/content/browser/attribution_reporting/attribution_storage_sql.cc index e17c3869..acaa3e7 100644 --- a/content/browser/attribution_reporting/attribution_storage_sql.cc +++ b/content/browser/attribution_reporting/attribution_storage_sql.cc
@@ -249,15 +249,19 @@ int64_t aggregatable_budget_consumed = statement.ColumnInt64(col++); absl::optional<AttributionAggregatableSources> aggregatable_sources = ParseAggregatableSources(statement.ColumnString(col++)); - absl::optional<AttributionFilterData> filter_data = - AttributionFilterData::Deserialize(statement.ColumnString(col++)); if (!source_type.has_value() || !attribution_logic.has_value() || num_conversions < 0 || aggregatable_budget_consumed < 0 || - !aggregatable_sources.has_value() || !filter_data.has_value()) { + !aggregatable_sources.has_value()) { return absl::nullopt; } + absl::optional<AttributionFilterData> filter_data = + AttributionFilterData::DeserializeSourceFilterData( + statement.ColumnString(col++), *source_type); + if (!filter_data) + return absl::nullopt; + return StoredSourceData{ .source = StoredSource( CommonSourceInfo(source_event_id, std::move(impression_origin),
diff --git a/content/browser/attribution_reporting/attribution_storage_sql_unittest.cc b/content/browser/attribution_reporting/attribution_storage_sql_unittest.cc index 298e638..02205d0d 100644 --- a/content/browser/attribution_reporting/attribution_storage_sql_unittest.cc +++ b/content/browser/attribution_reporting/attribution_storage_sql_unittest.cc
@@ -751,7 +751,7 @@ const auto impression = SourceBuilder().SetSourceEventId(kMaxUint64).Build(); storage()->StoreSource(impression); EXPECT_THAT(storage()->GetActiveSources(), - ElementsAre(CommonSourceInfoIs(impression.common_info()))); + ElementsAre(SourceEventIdIs(kMaxUint64))); EXPECT_EQ( AttributionTrigger::EventLevelResult::kSuccess,
diff --git a/content/browser/attribution_reporting/attribution_storage_unittest.cc b/content/browser/attribution_reporting/attribution_storage_unittest.cc index 6e9cd2e9..0779daa 100644 --- a/content/browser/attribution_reporting/attribution_storage_unittest.cc +++ b/content/browser/attribution_reporting/attribution_storage_unittest.cc
@@ -160,10 +160,10 @@ } TEST_F(AttributionStorageTest, ImpressionStoredAndRetrieved_ValuesIdentical) { - auto impression = SourceBuilder().Build(); - storage()->StoreSource(impression); + storage()->StoreSource(SourceBuilder().Build()); EXPECT_THAT(storage()->GetActiveSources(), - ElementsAre(CommonSourceInfoIs(impression.common_info()))); + ElementsAre(CommonSourceInfoIs( + SourceBuilder().SetDefaultFilterData().BuildCommonInfo()))); } #if BUILDFLAG(IS_ANDROID) @@ -171,15 +171,15 @@ ImpressionStoredAndRetrieved_ValuesIdentical_AndroidApp) { url::ScopedSchemeRegistryForTests scoped_registry; url::AddStandardScheme(kAndroidAppScheme, url::SCHEME_WITH_HOST); - auto impression = SourceBuilder() - .SetImpressionOrigin(url::Origin::Create( - GURL("android-app:com.any.app"))) - .Build(); - storage()->StoreSource(impression); + SourceBuilder builder; + builder.SetImpressionOrigin( + url::Origin::Create(GURL("android-app:com.any.app"))); + storage()->StoreSource(builder.Build()); // Verify that each field was stored as expected. EXPECT_THAT(storage()->GetActiveSources(), - ElementsAre(CommonSourceInfoIs(impression.common_info()))); + ElementsAre(CommonSourceInfoIs( + builder.SetDefaultFilterData().BuildCommonInfo()))); } #endif @@ -284,8 +284,8 @@ EXPECT_EQ(AttributionTrigger::EventLevelResult::kSuccess, MaybeCreateAndStoreEventLevelReport(conversion)); - AttributionReport expected_report = - GetExpectedEventLevelReport(SourceBuilder().BuildStored(), conversion); + AttributionReport expected_report = GetExpectedEventLevelReport( + SourceBuilder().SetDefaultFilterData().BuildStored(), conversion); task_environment_.FastForwardBy(kReportDelay); @@ -400,8 +400,8 @@ auto conversion = DefaultTrigger(); EXPECT_EQ(AttributionTrigger::EventLevelResult::kSuccess, MaybeCreateAndStoreEventLevelReport(conversion)); - AttributionReport expected_report = - GetExpectedEventLevelReport(builder.BuildStored(), conversion); + AttributionReport expected_report = GetExpectedEventLevelReport( + builder.SetDefaultFilterData().BuildStored(), conversion); task_environment_.FastForwardBy(kReportDelay); @@ -434,8 +434,8 @@ EXPECT_EQ(AttributionTrigger::EventLevelResult::kSuccess, MaybeCreateAndStoreEventLevelReport(conversion)); - AttributionReport expected_report = - GetExpectedEventLevelReport(builder.BuildStored(), conversion); + AttributionReport expected_report = GetExpectedEventLevelReport( + builder.SetDefaultFilterData().BuildStored(), conversion); // Verify it was the first impression that converted. EXPECT_THAT(storage()->GetAttributionReports(base::Time::Now()), @@ -458,8 +458,8 @@ builder.SetSourceEventId(10); storage()->StoreSource(builder.Build()); - AttributionReport third_expected_conversion = - GetExpectedEventLevelReport(builder.BuildStored(), conversion); + AttributionReport third_expected_conversion = GetExpectedEventLevelReport( + builder.SetDefaultFilterData().BuildStored(), conversion); EXPECT_EQ(AttributionTrigger::EventLevelResult::kSuccess, MaybeCreateAndStoreEventLevelReport(conversion)); @@ -709,8 +709,8 @@ task_environment_.FastForwardBy(base::Days(1)); - const AttributionReport expected_report = - GetExpectedEventLevelReport(builder.BuildStored(), conversion); + const AttributionReport expected_report = GetExpectedEventLevelReport( + builder.SetDefaultFilterData().BuildStored(), conversion); EXPECT_EQ(AttributionTrigger::EventLevelResult::kSuccess, MaybeCreateAndStoreEventLevelReport(conversion)); @@ -813,8 +813,8 @@ AttributionTrigger::EventLevelResult::kExcessiveAttributions), DroppedReportsAre(SizeIs(1)))); - const AttributionReport expected_report = - GetExpectedEventLevelReport(SourceBuilder().BuildStored(), conversion); + const AttributionReport expected_report = GetExpectedEventLevelReport( + SourceBuilder().SetDefaultFilterData().BuildStored(), conversion); EXPECT_THAT(storage()->GetAttributionReports(base::Time::Max()), ElementsAre(expected_report, expected_report)); @@ -911,8 +911,8 @@ EXPECT_EQ(AttributionTrigger::EventLevelResult::kExcessiveAttributions, MaybeCreateAndStoreEventLevelReport(conversion)); - const AttributionReport expected_report = - GetExpectedEventLevelReport(builder.BuildStored(), conversion); + const AttributionReport expected_report = GetExpectedEventLevelReport( + builder.SetDefaultFilterData().BuildStored(), conversion); task_environment_.FastForwardBy(kReportDelay); @@ -1135,6 +1135,7 @@ AttributionInfoBuilder( builder .SetAttributionLogic(StoredSource::AttributionLogic::kFalsely) + .SetDefaultFilterData() .BuildStored()) .SetTime(base::Time::Now()) .Build()) @@ -1542,11 +1543,11 @@ builder1.SetDedupKeys({13}); EXPECT_THAT(storage()->StoreSource(builder2.Build()).deactivated_sources, ElementsAre(DeactivatedSource( - builder1.BuildStored(), + builder1.SetDefaultFilterData().BuildStored(), DeactivatedSource::Reason::kReplacedByNewerSource))); EXPECT_THAT(storage()->GetActiveSources(), - ElementsAre(builder2.BuildStored())); + ElementsAre(builder2.SetDefaultFilterData().BuildStored())); } TEST_F(AttributionStorageTest, StoreSource_ReturnsDeactivatedSources_Limited) { @@ -1578,10 +1579,10 @@ /*deactivated_source_return_limit=*/1) .deactivated_sources, ElementsAre(DeactivatedSource( - builder1.BuildStored(), + builder1.SetDefaultFilterData().BuildStored(), DeactivatedSource::Reason::kReplacedByNewerSource))); EXPECT_THAT(storage()->GetActiveSources(), - ElementsAre(builder3.BuildStored())); + ElementsAre(builder3.SetDefaultFilterData().BuildStored())); } TEST_F(AttributionStorageTest, @@ -1611,10 +1612,10 @@ EXPECT_THAT(storage()->MaybeCreateAndStoreReport(DefaultTrigger()), AllOf(CreateReportEventLevelStatusIs( AttributionTrigger::EventLevelResult::kPriorityTooLow), - DroppedReportsAre( - ElementsAre(ReportSourceIs(builder.BuildStored()))), + DroppedReportsAre(ElementsAre(ReportSourceIs( + builder.SetDefaultFilterData().BuildStored()))), DeactivatedSourceIs(DeactivatedSource( - builder.BuildStored(), + builder.SetDefaultFilterData().BuildStored(), DeactivatedSource::Reason::kReachedAttributionLimit)))); } @@ -1897,19 +1898,14 @@ TEST_F(AttributionStorageTest, StoreAggregatableAttribution) { storage()->StoreSource(SourceBuilder().Build()); - auto attribution_info = - AttributionInfoBuilder( - SourceBuilder().SetSourceId(StoredSource::Id(1)).BuildStored()) - .SetDebugKey(33) - .Build(); - const auto expected_report = - ReportBuilder( - AttributionInfoBuilder( - SourceBuilder().SetSourceId(StoredSource::Id(1)).BuildStored()) - .SetTime(base::Time::Now()) - .SetDebugKey(33) - .Build()) + ReportBuilder(AttributionInfoBuilder(SourceBuilder() + .SetSourceId(StoredSource::Id(1)) + .SetDefaultFilterData() + .BuildStored()) + .SetTime(base::Time::Now()) + .SetDebugKey(33) + .Build()) .SetReportTime(base::Time::Now() + base::Hours(2)) .SetAggregatableHistogramContributions( {AggregatableHistogramContribution(/*key=*/1, /*value=*/2), @@ -2148,18 +2144,28 @@ } TEST_F(AttributionStorageTest, SourceFilterData_RoundTrips) { - storage()->StoreSource( - SourceBuilder().SetFilterData(AttributionFilterData()).Build()); + storage()->StoreSource(SourceBuilder() + .SetFilterData(AttributionFilterData()) + .SetSourceType(AttributionSourceType::kNavigation) + .Build()); auto filter_data = - AttributionFilterData::FromFilterValues({{"abc", {"x", "y"}}}); + AttributionFilterData::FromSourceFilterValues({{"abc", {"x", "y"}}}); ASSERT_TRUE(filter_data.has_value()); - storage()->StoreSource(SourceBuilder().SetFilterData(*filter_data).Build()); + storage()->StoreSource(SourceBuilder() + .SetFilterData(*filter_data) + .SetSourceType(AttributionSourceType::kEvent) + .Build()); - EXPECT_THAT(storage()->GetActiveSources(), - ElementsAre(SourceFilterDataIs(AttributionFilterData()), - SourceFilterDataIs(*filter_data))); + EXPECT_THAT( + storage()->GetActiveSources(), + ElementsAre(SourceFilterDataIs(AttributionFilterData::CreateForTesting( + {{"source_type", {"navigation"}}})), + SourceFilterDataIs(AttributionFilterData::CreateForTesting({ + {"abc", {"x", "y"}}, + {"source_type", {"event"}}, + })))); } TEST_F(AttributionStorageTest, NoMatchingTriggers) {
diff --git a/content/browser/attribution_reporting/attribution_test_utils.cc b/content/browser/attribution_reporting/attribution_test_utils.cc index a63da42..b9fc7c63 100644 --- a/content/browser/attribution_reporting/attribution_test_utils.cc +++ b/content/browser/attribution_reporting/attribution_test_utils.cc
@@ -430,6 +430,12 @@ return *this; } +SourceBuilder& SourceBuilder::SetDefaultFilterData() { + filter_data_ = AttributionFilterData::CreateForTesting( + {{"source_type", {AttributionSourceTypeToString(source_type_)}}}); + return *this; +} + SourceBuilder& SourceBuilder::SetDebugKey(absl::optional<uint64_t> debug_key) { debug_key_ = debug_key; return *this; @@ -867,15 +873,7 @@ } std::ostream& operator<<(std::ostream& out, AttributionSourceType source_type) { - switch (source_type) { - case AttributionSourceType::kNavigation: - out << "kNavigation"; - break; - case AttributionSourceType::kEvent: - out << "kEvent"; - break; - } - return out; + return out << AttributionSourceTypeToString(source_type); } std::ostream& operator<<(std::ostream& out,
diff --git a/content/browser/attribution_reporting/attribution_test_utils.h b/content/browser/attribution_reporting/attribution_test_utils.h index 5e2a862..f90008f6 100644 --- a/content/browser/attribution_reporting/attribution_test_utils.h +++ b/content/browser/attribution_reporting/attribution_test_utils.h
@@ -351,6 +351,9 @@ SourceBuilder& SetFilterData(AttributionFilterData filter_data); + // Sets the filter data to the autogenerated "source_type" filter. + SourceBuilder& SetDefaultFilterData(); + SourceBuilder& SetDebugKey(absl::optional<uint64_t> debug_key); SourceBuilder& SetSourceId(StoredSource::Id source_id);
diff --git a/content/browser/attribution_reporting/attribution_utils_unittest.cc b/content/browser/attribution_reporting/attribution_utils_unittest.cc index 954d4d37..90fb95e 100644 --- a/content/browser/attribution_reporting/attribution_utils_unittest.cc +++ b/content/browser/attribution_reporting/attribution_utils_unittest.cc
@@ -15,11 +15,11 @@ auto empty_filter = AttributionFilterData(); auto empty_filter_values = - AttributionFilterData::FromFilterValues({{"filter1", {}}}); + AttributionFilterData::FromSourceFilterValues({{"filter1", {}}}); ASSERT_TRUE(empty_filter_values.has_value()); auto one_filter = - AttributionFilterData::FromFilterValues({{"filter1", {"value1"}}}); + AttributionFilterData::FromSourceFilterValues({{"filter1", {"value1"}}}); ASSERT_TRUE(one_filter.has_value()); const struct { @@ -58,26 +58,26 @@ TEST(AttributionUtilsTest, AttributionFilterDataMatch) { auto empty_filter_values = - AttributionFilterData::FromFilterValues({{"filter1", {}}}); + AttributionFilterData::FromSourceFilterValues({{"filter1", {}}}); ASSERT_TRUE(empty_filter_values.has_value()); auto one_filter = - AttributionFilterData::FromFilterValues({{"filter1", {"value1"}}}); + AttributionFilterData::FromSourceFilterValues({{"filter1", {"value1"}}}); ASSERT_TRUE(one_filter.has_value()); auto one_filter_different = - AttributionFilterData::FromFilterValues({{"filter1", {"value2"}}}); + AttributionFilterData::FromSourceFilterValues({{"filter1", {"value2"}}}); ASSERT_TRUE(one_filter_different.has_value()); - auto two_filters = AttributionFilterData::FromFilterValues( + auto two_filters = AttributionFilterData::FromSourceFilterValues( {{"filter1", {"value1"}}, {"filter2", {"value2"}}}); ASSERT_TRUE(two_filters.has_value()); - auto one_mismatched_filter = AttributionFilterData::FromFilterValues( + auto one_mismatched_filter = AttributionFilterData::FromSourceFilterValues( {{"filter1", {"value1"}}, {"filter2", {"value3"}}}); ASSERT_TRUE(one_mismatched_filter.has_value()); - auto two_mismatched_filter = AttributionFilterData::FromFilterValues( + auto two_mismatched_filter = AttributionFilterData::FromSourceFilterValues( {{"filter1", {"value3"}}, {"filter2", {"value4"}}}); ASSERT_TRUE(two_mismatched_filter.has_value()); @@ -121,34 +121,35 @@ TEST(AttributionUtilsTest, NegatedAttributionFilterDataMatch) { auto empty_filter_values = - AttributionFilterData::FromFilterValues({{"filter1", {}}}); + AttributionFilterData::FromSourceFilterValues({{"filter1", {}}}); ASSERT_TRUE(empty_filter_values.has_value()); auto one_filter = - AttributionFilterData::FromFilterValues({{"filter1", {"value1"}}}); + AttributionFilterData::FromSourceFilterValues({{"filter1", {"value1"}}}); ASSERT_TRUE(one_filter.has_value()); auto one_filter_different = - AttributionFilterData::FromFilterValues({{"filter1", {"value2"}}}); + AttributionFilterData::FromSourceFilterValues({{"filter1", {"value2"}}}); ASSERT_TRUE(one_filter_different.has_value()); - auto one_filter_one_different = AttributionFilterData::FromFilterValues( + auto one_filter_one_different = AttributionFilterData::FromSourceFilterValues( {{"filter1", {"value1", "value2"}}}); ASSERT_TRUE(one_filter_different.has_value()); - auto one_filter_multiple_different = AttributionFilterData::FromFilterValues( - {{"filter1", {"value2", "value3"}}}); + auto one_filter_multiple_different = + AttributionFilterData::FromSourceFilterValues( + {{"filter1", {"value2", "value3"}}}); ASSERT_TRUE(one_filter_different.has_value()); - auto two_filters = AttributionFilterData::FromFilterValues( + auto two_filters = AttributionFilterData::FromSourceFilterValues( {{"filter1", {"value1"}}, {"filter2", {"value2"}}}); ASSERT_TRUE(two_filters.has_value()); - auto one_mismatched_filter = AttributionFilterData::FromFilterValues( + auto one_mismatched_filter = AttributionFilterData::FromSourceFilterValues( {{"filter1", {"value1"}}, {"filter2", {"value3"}}}); ASSERT_TRUE(one_mismatched_filter.has_value()); - auto two_mismatched_filter = AttributionFilterData::FromFilterValues( + auto two_mismatched_filter = AttributionFilterData::FromSourceFilterValues( {{"filter1", {"value3"}}, {"filter2", {"value4"}}}); ASSERT_TRUE(two_mismatched_filter.has_value());
diff --git a/content/browser/browser_context.cc b/content/browser/browser_context.cc index b0ebdaa..323ffab 100644 --- a/content/browser/browser_context.cc +++ b/content/browser/browser_context.cc
@@ -387,6 +387,11 @@ std::move(stats_db), BrowserFeatureProvider::GetFactoryCB()); } +FederatedIdentityApiPermissionContextDelegate* +BrowserContext::GetFederatedIdentityApiPermissionContext() { + return nullptr; +} + FederatedIdentityActiveSessionPermissionContextDelegate* BrowserContext::GetFederatedIdentityActiveSessionPermissionContext() { return nullptr;
diff --git a/content/browser/client_hints/client_hints.cc b/content/browser/client_hints/client_hints.cc index b253179..03c0d36b 100644 --- a/content/browser/client_hints/client_hints.cc +++ b/content/browser/client_hints/client_hints.cc
@@ -523,9 +523,10 @@ // Captures the state used in applying client hints. struct ClientHintsExtendedData { - ClientHintsExtendedData(const url::Origin origin, + ClientHintsExtendedData(const url::Origin& origin, FrameTreeNode* frame_tree_node, - ClientHintsControllerDelegate* delegate) + ClientHintsControllerDelegate* delegate, + const absl::optional<GURL>& maybe_request_url) : resource_origin(origin) { // If the current frame is the main frame, the URL wasn't committed yet, so // in order to get the main frame URL, we should use the provided URL @@ -554,14 +555,18 @@ // TODO(crbug.com/1258063): Remove once the UserAgentReduction Origin Trial // is finished. if (frame_tree_node && !is_main_frame) { + url::Origin trial_origin = + maybe_request_url ? url::Origin::Create(maybe_request_url.value()) + : origin; + is_embedder_ua_reduced = IsOriginTrialHintEnabledForFrame( - resource_origin, main_frame_origin, frame_tree_node, delegate, + trial_origin, main_frame_origin, frame_tree_node, delegate, WebClientHintsType::kUAReduced); is_embedder_ua_full = IsOriginTrialHintEnabledForFrame( - resource_origin, main_frame_origin, frame_tree_node, delegate, + trial_origin, main_frame_origin, frame_tree_node, delegate, WebClientHintsType::kFullUserAgent); is_embedder_partitioned_cookies = IsOriginTrialHintEnabledForFrame( - resource_origin, main_frame_origin, frame_tree_node, delegate, + trial_origin, main_frame_origin, frame_tree_node, delegate, WebClientHintsType::kPartitionedCookies); } @@ -697,7 +702,8 @@ FrameTreeNode* frame_tree_node, ClientUaHeaderCallType call_type, net::HttpRequestHeaders* headers, - const blink::ParsedPermissionsPolicy& container_policy) { + const blink::ParsedPermissionsPolicy& container_policy, + const absl::optional<GURL>& request_url) { absl::optional<blink::UserAgentMetadata> ua_metadata; bool disable_due_to_custom_ua = false; if (override_ua) { @@ -723,7 +729,8 @@ if (!ua_metadata.has_value()) ua_metadata = delegate->GetUserAgentMetadata(); - ClientHintsExtendedData data(origin, frame_tree_node, delegate); + ClientHintsExtendedData data(origin, frame_tree_node, delegate, + request_url); UpdateIFramePermissionsPolicyWithDelegationSupportForClientHints( data, container_policy); @@ -809,14 +816,18 @@ bool ShouldAddClientHints(const url::Origin& origin, FrameTreeNode* frame_tree_node, - ClientHintsControllerDelegate* delegate) { + ClientHintsControllerDelegate* delegate, + const absl::optional<GURL> maybe_request_url) { + url::Origin origin_to_check = + maybe_request_url ? url::Origin::Create(maybe_request_url.value()) + : origin; // Client hints should only be enabled when JavaScript is enabled. Platforms // which enable/disable JavaScript on a per-origin basis should implement // IsJavaScriptAllowed to check a given origin. Other platforms (Android // WebView) enable/disable JavaScript on a per-View basis, using the // WebPreferences setting. - return IsValidURLForClientHints(origin) && - delegate->IsJavaScriptAllowed(origin.GetURL()) && + return IsValidURLForClientHints(origin_to_check) && + delegate->IsJavaScriptAllowed(origin_to_check.GetURL()) && (!frame_tree_node || IsJavascriptEnabled(frame_tree_node)); } @@ -835,16 +846,17 @@ ClientHintsControllerDelegate* delegate, bool override_ua, FrameTreeNode* frame_tree_node, - net::HttpRequestHeaders* headers) { + net::HttpRequestHeaders* headers, + const absl::optional<GURL>& request_url) { DCHECK(frame_tree_node); if (!UserAgentClientHintEnabled() || - !ShouldAddClientHints(origin, frame_tree_node, delegate)) { + !ShouldAddClientHints(origin, frame_tree_node, delegate, request_url)) { return; } UpdateNavigationRequestClientUaHeadersImpl( origin, delegate, override_ua, frame_tree_node, - ClientUaHeaderCallType::kAfterCreated, headers, {}); + ClientUaHeaderCallType::kAfterCreated, headers, {}, request_url); } namespace { @@ -856,8 +868,9 @@ ClientHintsControllerDelegate* delegate, bool is_ua_override_on, FrameTreeNode* frame_tree_node, - const blink::ParsedPermissionsPolicy& container_policy) { - ClientHintsExtendedData data(origin, frame_tree_node, delegate); + const blink::ParsedPermissionsPolicy& container_policy, + const absl::optional<GURL>& request_url) { + ClientHintsExtendedData data(origin, frame_tree_node, delegate, request_url); UpdateIFramePermissionsPolicyWithDelegationSupportForClientHints( data, container_policy); @@ -903,7 +916,8 @@ if (UserAgentClientHintEnabled()) { UpdateNavigationRequestClientUaHeadersImpl( origin, delegate, is_ua_override_on, frame_tree_node, - ClientUaHeaderCallType::kDuringCreation, headers, container_policy); + ClientUaHeaderCallType::kDuringCreation, headers, container_policy, + request_url); } if (ShouldAddClientHint(data, WebClientHintsType::kPrefersColorScheme)) { @@ -955,7 +969,7 @@ } AddRequestClientHintsHeaders(origin, headers, context, delegate, - is_ua_override_on, nullptr, {}); + is_ua_override_on, nullptr, {}, absl::nullopt); } void AddNavigationRequestClientHintsHeaders( @@ -965,7 +979,8 @@ ClientHintsControllerDelegate* delegate, bool is_ua_override_on, FrameTreeNode* frame_tree_node, - const blink::ParsedPermissionsPolicy& container_policy) { + const blink::ParsedPermissionsPolicy& container_policy, + const absl::optional<GURL>& request_url) { DCHECK(frame_tree_node); DCHECK_CURRENTLY_ON(BrowserThread::UI); DCHECK_EQ(blink::kWebEffectiveConnectionTypeMappingCount, @@ -973,14 +988,13 @@ DCHECK_EQ(blink::kWebEffectiveConnectionTypeMappingCount, static_cast<size_t>(net::EFFECTIVE_CONNECTION_TYPE_LAST)); DCHECK(context); - - if (!ShouldAddClientHints(origin, frame_tree_node, delegate)) { + if (!ShouldAddClientHints(origin, frame_tree_node, delegate, request_url)) { return; } AddRequestClientHintsHeaders(origin, headers, context, delegate, is_ua_override_on, frame_tree_node, - container_policy); + container_policy, request_url); } absl::optional<std::vector<WebClientHintsType>> @@ -1071,13 +1085,15 @@ std::vector<WebClientHintsType> LookupAcceptCHForCommit( const url::Origin& origin, ClientHintsControllerDelegate* delegate, - FrameTreeNode* frame_tree_node) { + FrameTreeNode* frame_tree_node, + const absl::optional<GURL>& request_url) { std::vector<WebClientHintsType> result; - if (!ShouldAddClientHints(origin, frame_tree_node, delegate)) { + if (!ShouldAddClientHints(origin, frame_tree_node, delegate, request_url)) { return result; } - const ClientHintsExtendedData data(origin, frame_tree_node, delegate); + const ClientHintsExtendedData data(origin, frame_tree_node, delegate, + request_url); std::vector<WebClientHintsType> hints = data.hints.GetEnabledHints(); if (data.is_embedder_ua_reduced && !base::Contains(hints, WebClientHintsType::kUAReduced)) { @@ -1099,7 +1115,8 @@ FrameTreeNode* frame_tree_node, ClientHintsControllerDelegate* delegate, const std::vector<WebClientHintsType>& critical_hints) { - ClientHintsExtendedData data(origin, frame_tree_node, delegate); + ClientHintsExtendedData data(origin, frame_tree_node, delegate, + absl::nullopt); // Note: these only check for per-hint origin/permissions policy settings, not // origin-level or "browser-level" policies like disabiling JS or other
diff --git a/content/browser/client_hints/client_hints.h b/content/browser/client_hints/client_hints.h index 7259809..eee3bff 100644 --- a/content/browser/client_hints/client_hints.h +++ b/content/browser/client_hints/client_hints.h
@@ -13,6 +13,7 @@ #include "net/http/http_request_headers.h" #include "services/network/public/mojom/parsed_headers.mojom-forward.h" #include "third_party/blink/public/common/permissions_policy/permissions_policy.h" +#include "url/gurl.h" namespace net { class HttpResponseHeaders; @@ -25,10 +26,27 @@ // Returns whether client hints can be added for the given URL and frame. This // is true only if the URL is eligible and JavaScript is enabled. +// +// |origin| is the origin to be used for client hints storage. +// |maybe_request_url| is the url of the request. It is used as an origin for +// the origin trial client hints. +// +// Where possible, |origin| should be the origin of the document the navigation +// is creating. NavigationRequest::GetOriginToCommit() is used, and takes +// sandbox into account, which means that |origin| can be opaque. When called at +// request time, NavigationRequest::GetTentativeOriginAtRequestTime() should be +// used, because it is not possible to determine the origin before receiving the +// final navigation response and the CSP:sandbox response header. It takes into +// account the sandbox flags set by the embedder only. +// +// If |request_url| is not provided, |origin| must not be opaque. This is the +// case for Critical-CH processing and ACCEPT_CH frame processing, where the +// document is not taken into account. CONTENT_EXPORT bool ShouldAddClientHints( const url::Origin& origin, FrameTreeNode* frame_tree_node, - ClientHintsControllerDelegate* delegate); + ClientHintsControllerDelegate* delegate, + const absl::optional<GURL> maybe_request_url = absl::nullopt); // Returns |rtt| after adding host-specific random noise, and rounding it as // per the NetInfo spec to improve privacy. @@ -55,12 +73,15 @@ // Updates the user agent client hint headers. This is called if the value of // |override_ua| changes after the NavigationRequest was created. +// +// See |ShouldAddClientHints| for |origin| vs |request_url| CONTENT_EXPORT void UpdateNavigationRequestClientUaHeaders( const url::Origin& origin, ClientHintsControllerDelegate* delegate, bool override_ua, FrameTreeNode* frame_tree_node, - net::HttpRequestHeaders* headers); + net::HttpRequestHeaders* headers, + const absl::optional<GURL>& request_url = absl::nullopt); CONTENT_EXPORT void AddNavigationRequestClientHintsHeaders( const url::Origin& origin, @@ -69,7 +90,8 @@ ClientHintsControllerDelegate* delegate, bool is_ua_override_on, FrameTreeNode*, - const blink::ParsedPermissionsPolicy&); + const blink::ParsedPermissionsPolicy&, + const absl::optional<GURL>& request_url = absl::nullopt); // Adds client hints headers for a prefetch navigation that is not associated // with a frame. It must be a main frame navigation. |is_javascript_enabled| is @@ -112,10 +134,14 @@ // // Note that this is based on the top-level frame, and not necessarily the // frame being committed. +// +// See |ShouldAddClientHints| for |origin| vs |request_url| CONTENT_EXPORT std::vector<::network::mojom::WebClientHintsType> -LookupAcceptCHForCommit(const url::Origin& origin, - ClientHintsControllerDelegate* delegate, - FrameTreeNode* frame_tree_node); +LookupAcceptCHForCommit( + const url::Origin& origin, + ClientHintsControllerDelegate* delegate, + FrameTreeNode* frame_tree_node, + const absl::optional<GURL>& request_url = absl::nullopt); } // namespace content
diff --git a/content/browser/devtools/devtools_instrumentation.cc b/content/browser/devtools/devtools_instrumentation.cc index db699bb..b59b9147 100644 --- a/content/browser/devtools/devtools_instrumentation.cc +++ b/content/browser/devtools/devtools_instrumentation.cc
@@ -171,6 +171,9 @@ case FederatedAuthRequestResult::kApprovalDeclined: { return FederatedAuthRequestIssueReasonEnum::ApprovalDeclined; } + case FederatedAuthRequestResult::kErrorDisabledInSettings: { + return FederatedAuthRequestIssueReasonEnum::DisabledInSettings; + } case FederatedAuthRequestResult::kErrorTooManyRequests: { return FederatedAuthRequestIssueReasonEnum::TooManyRequests; }
diff --git a/content/browser/interest_group/ad_auction_service_impl_unittest.cc b/content/browser/interest_group/ad_auction_service_impl_unittest.cc index a35d5b91..e62271c 100644 --- a/content/browser/interest_group/ad_auction_service_impl_unittest.cc +++ b/content/browser/interest_group/ad_auction_service_impl_unittest.cc
@@ -2599,6 +2599,186 @@ EXPECT_EQ(b_group.ads.value()[0].metadata, "{\"new_a\":\"b\"}"); } +// Set the maximum number of parallel updates to 2. Create three interest +// groups, each in origin A, and update origin A's interest groups. +// +// Check that all the interest groups updated. +TEST_F(AdAuctionServiceImplTest, UpdatesInBatches) { + manager_->set_max_parallel_updates_for_testing(2); + + network_responder_->RegisterUpdateResponse( + kDailyUpdateUrlPath, base::StringPrintf(R"({ +"ads": [{"renderUrl": "%s/new_ad_render_url", + "metadata": {"new_a": "b"} + }] +})", + kOriginStringA)); + + // Create 3 interest groups for kOriginA. + blink::InterestGroup interest_group = CreateInterestGroup(); + interest_group.expiry = base::Time::Now() + base::Days(30); + interest_group.update_url = kUpdateUrlA; + interest_group.ads.emplace(); + blink::InterestGroup::Ad ad( + /*render_url=*/GURL("https://example.com/render"), + /*metadata=*/"{\"ad\":\"metadata\",\"here\":[1,2,3]}"); + interest_group.ads->emplace_back(std::move(ad)); + JoinInterestGroupAndFlush(interest_group); + EXPECT_EQ(1, GetJoinCount(kOriginA, kInterestGroupName)); + + constexpr char kInterestGroupName2[] = "group2"; + interest_group = CreateInterestGroup(); + interest_group.name = kInterestGroupName2; + interest_group.expiry = base::Time::Now() + base::Days(30); + interest_group.update_url = kUpdateUrlA; + interest_group.ads.emplace(); + ad = blink::InterestGroup::Ad( + /*render_url=*/GURL("https://example.com/render"), + /*metadata=*/"{\"ad\":\"metadata\",\"here\":[1,2,3]}"); + interest_group.ads->emplace_back(std::move(ad)); + JoinInterestGroupAndFlush(interest_group); + EXPECT_EQ(1, GetJoinCount(kOriginA, kInterestGroupName2)); + + constexpr char kInterestGroupName3[] = "group3"; + interest_group = CreateInterestGroup(); + interest_group.name = kInterestGroupName3; + interest_group.expiry = base::Time::Now() + base::Days(30); + interest_group.update_url = kUpdateUrlA; + interest_group.ads.emplace(); + ad = blink::InterestGroup::Ad( + /*render_url=*/GURL("https://example.com/render"), + /*metadata=*/"{\"ad\":\"metadata\",\"here\":[1,2,3]}"); + interest_group.ads->emplace_back(std::move(ad)); + JoinInterestGroupAndFlush(interest_group); + EXPECT_EQ(1, GetJoinCount(kOriginA, kInterestGroupName3)); + + EXPECT_EQ(network_responder_->UpdateCount(), 0u); + + // Update all interest groups. + NavigateAndCommit(kUrlA); + UpdateInterestGroupNoFlush(); + task_environment()->RunUntilIdle(); + + EXPECT_EQ(network_responder_->UpdateCount(), 3u); + + std::vector<StorageInterestGroup> groups = + GetInterestGroupsForOwner(kOriginA); + ASSERT_EQ(groups.size(), 3u); + + for (size_t i = 0; i < groups.size(); i++) { + SCOPED_TRACE(i); + const auto& group = groups[i].interest_group; + ASSERT_TRUE(group.ads.has_value()); + ASSERT_EQ(group.ads->size(), 1u); + EXPECT_EQ(group.ads.value()[0].render_url.spec(), + base::StringPrintf("%s/new_ad_render_url", kOriginStringA)); + EXPECT_EQ(group.ads.value()[0].metadata, "{\"new_a\":\"b\"}"); + } +} + +// Set the maximum number of parallel updates to 2. Create three interest +// groups, each in origin A, and update origin A's interest groups. Make one +// fail, and one timeout. +// +// Check that the interest group that didn't fail or timeout updates +// successfully. +TEST_F(AdAuctionServiceImplTest, UpdatesInBatchesWithFailuresAndTimeouts) { + manager_->set_max_parallel_updates_for_testing(2); + + network_responder_->RegisterUpdateResponse( + kDailyUpdateUrlPath, base::StringPrintf(R"({ +"ads": [{"renderUrl": "%s/new_ad_render_url", + "metadata": {"new_a": "b"} + }] +})", + kOriginStringA)); + network_responder_->FailUpdateRequestWithError(kDailyUpdateUrlPath2, + net::ERR_CONNECTION_RESET); + // We never respond to this -- just let it timeout. + network_responder_->RegisterDeferredUpdateResponse(kDailyUpdateUrlPath3); + + // Create 3 interest groups for kOriginA -- give them different update URLs to + // so that some timeout and some fail. + blink::InterestGroup interest_group = CreateInterestGroup(); + interest_group.expiry = base::Time::Now() + base::Days(30); + interest_group.update_url = kUpdateUrlA; + interest_group.ads.emplace(); + blink::InterestGroup::Ad ad( + /*render_url=*/GURL("https://example.com/render"), + /*metadata=*/"{\"ad\":\"metadata\",\"here\":[1,2,3]}"); + interest_group.ads->emplace_back(std::move(ad)); + JoinInterestGroupAndFlush(interest_group); + EXPECT_EQ(1, GetJoinCount(kOriginA, kInterestGroupName)); + + constexpr char kInterestGroupName2[] = "group2"; + interest_group = CreateInterestGroup(); + interest_group.name = kInterestGroupName2; + interest_group.expiry = base::Time::Now() + base::Days(30); + interest_group.update_url = kUpdateUrlA2; + interest_group.ads.emplace(); + ad = blink::InterestGroup::Ad( + /*render_url=*/GURL("https://example.com/render"), + /*metadata=*/"{\"ad\":\"metadata\",\"here\":[1,2,3]}"); + interest_group.ads->emplace_back(std::move(ad)); + JoinInterestGroupAndFlush(interest_group); + EXPECT_EQ(1, GetJoinCount(kOriginA, kInterestGroupName2)); + + constexpr char kInterestGroupName3[] = "group3"; + interest_group = CreateInterestGroup(); + interest_group.name = kInterestGroupName3; + interest_group.expiry = base::Time::Now() + base::Days(30); + interest_group.update_url = kUpdateUrlA3; + interest_group.ads.emplace(); + ad = blink::InterestGroup::Ad( + /*render_url=*/GURL("https://example.com/render"), + /*metadata=*/"{\"ad\":\"metadata\",\"here\":[1,2,3]}"); + interest_group.ads->emplace_back(std::move(ad)); + JoinInterestGroupAndFlush(interest_group); + EXPECT_EQ(1, GetJoinCount(kOriginA, kInterestGroupName3)); + + EXPECT_EQ(network_responder_->UpdateCount(), 0u); + + // Update all interest groups. + NavigateAndCommit(kUrlA); + UpdateInterestGroupNoFlush(); + task_environment()->RunUntilIdle(); + + // Requests are issued in random order. If the first or second request is the + // delayed request, the third request won't be issued, since the first 2 + // aren't complete. On the other hand, if the delayed request is the third + // request, all three update requests would have been issued by now. + EXPECT_GE(network_responder_->UpdateCount(), 2u); + EXPECT_LE(network_responder_->UpdateCount(), 3u); + + // Now, fast forward so that the hanging request times out. After this, all + // updates should be completed. + task_environment()->FastForwardBy(base::Seconds(31)); + task_environment()->RunUntilIdle(); + EXPECT_EQ(network_responder_->UpdateCount(), 3u); + + std::vector<StorageInterestGroup> groups = + GetInterestGroupsForOwner(kOriginA); + ASSERT_EQ(groups.size(), 3u); + + for (size_t i = 0; i < groups.size(); i++) { + SCOPED_TRACE(i); + const auto& group = groups[i].interest_group; + ASSERT_TRUE(group.ads.has_value()); + ASSERT_EQ(group.ads->size(), 1u); + + if (group.update_url == kUpdateUrlA) { + EXPECT_EQ(group.ads.value()[0].render_url.spec(), + base::StringPrintf("%s/new_ad_render_url", kOriginStringA)); + EXPECT_EQ(group.ads.value()[0].metadata, "{\"new_a\":\"b\"}"); + } else { + EXPECT_EQ(group.ads.value()[0].render_url.spec(), + "https://example.com/render"); + EXPECT_EQ(group.ads.value()[0].metadata, + "{\"ad\":\"metadata\",\"here\":[1,2,3]}"); + } + } +} + // Create an interest group in a.test, and in b.test. Defer the update response // for a.test, and update a.test and b.test. //
diff --git a/content/browser/interest_group/interest_group_manager_impl.cc b/content/browser/interest_group/interest_group_manager_impl.cc index 2803319c..c55070c 100644 --- a/content/browser/interest_group/interest_group_manager_impl.cc +++ b/content/browser/interest_group/interest_group_manager_impl.cc
@@ -72,6 +72,12 @@ update_manager_.set_max_update_round_duration_for_testing(delta); // IN-TEST } +void InterestGroupManagerImpl::set_max_parallel_updates_for_testing( + int max_parallel_updates) { + update_manager_.set_max_parallel_updates_for_testing( // IN-TEST + max_parallel_updates); +} + void InterestGroupManagerImpl::RecordInterestGroupBid( const ::url::Origin& owner, const std::string& name) { @@ -128,9 +134,10 @@ void InterestGroupManagerImpl::GetInterestGroupsForUpdate( const url::Origin& owner, + int groups_limit, base::OnceCallback<void(std::vector<StorageInterestGroup>)> callback) { impl_.AsyncCall(&InterestGroupStorage::GetInterestGroupsForUpdate) - .WithArgs(owner) + .WithArgs(owner, groups_limit) .Then(std::move(callback)); }
diff --git a/content/browser/interest_group/interest_group_manager_impl.h b/content/browser/interest_group/interest_group_manager_impl.h index 4691a31..27833ad8 100644 --- a/content/browser/interest_group/interest_group_manager_impl.h +++ b/content/browser/interest_group/interest_group_manager_impl.h
@@ -86,6 +86,9 @@ // For testing *only*; changes the maximum amount of time that the update // process can run before it gets cancelled for taking too long. void set_max_update_round_duration_for_testing(base::TimeDelta delta); + // For testing *only*; changes the maximum number of groups that can be + // updated at the same time. + void set_max_parallel_updates_for_testing(int max_parallel_updates); // Adds an entry to the bidding history for this interest group. void RecordInterestGroupBid(const url::Origin& owner, const std::string& name); @@ -147,9 +150,13 @@ // GetInterestGroupsForUpdate() call with the same `owner` won't return // anything until after the success rate limit period passes. // + // `groups_limit` sets a limit on the maximum number of interest groups that + // may be returned. + // // To be called only by `update_manager_`. void GetInterestGroupsForUpdate( const url::Origin& owner, + int groups_limit, base::OnceCallback<void(std::vector<StorageInterestGroup>)> callback); // Updates the interest group of the same name based on the information in
diff --git a/content/browser/interest_group/interest_group_storage.cc b/content/browser/interest_group/interest_group_storage.cc index f3de010..db8d94bb 100644 --- a/content/browser/interest_group/interest_group_storage.cc +++ b/content/browser/interest_group/interest_group_storage.cc
@@ -4,6 +4,9 @@ #include "content/browser/interest_group/interest_group_storage.h" +#include <stddef.h> + +#include <algorithm> #include <memory> #include <vector> @@ -14,6 +17,7 @@ #include "base/metrics/histogram_functions.h" #include "base/metrics/histogram_macros.h" #include "base/notreached.h" +#include "base/rand_util.h" #include "base/sequence_checker.h" #include "base/strings/string_piece.h" #include "base/threading/sequenced_task_runner_handle.h" @@ -1738,7 +1742,8 @@ } std::vector<StorageInterestGroup> -InterestGroupStorage::GetInterestGroupsForUpdate(const url::Origin& owner) { +InterestGroupStorage::GetInterestGroupsForUpdate(const url::Origin& owner, + size_t groups_limit) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); if (!EnsureDBInitialized()) return {}; @@ -1748,6 +1753,8 @@ /*get_groups_for_update=*/true); if (!maybe_result) return {}; + base::RandomShuffle(maybe_result->begin(), maybe_result->end()); + maybe_result->resize(std::min(maybe_result->size(), groups_limit)); return std::move(maybe_result.value()); }
diff --git a/content/browser/interest_group/interest_group_storage.h b/content/browser/interest_group/interest_group_storage.h index 6253abf8..2159e74 100644 --- a/content/browser/interest_group/interest_group_storage.h +++ b/content/browser/interest_group/interest_group_storage.h
@@ -107,8 +107,12 @@ // the `next_update_after` field such that a subsequent // GetInterestGroupsForUpdate() call with the same `owner` won't return // anything until after the success rate limit period passes. + // + // `groups_limit` sets a limit on the maximum number of interest groups that + // may be returned. std::vector<StorageInterestGroup> GetInterestGroupsForUpdate( - const url::Origin& owner); + const url::Origin& owner, + size_t groups_limit); // Gets a list of all interest group joining origins. Each joining origin // will only appear once. std::vector<url::Origin> GetAllInterestGroupJoiningOrigins();
diff --git a/content/browser/interest_group/interest_group_storage_unittest.cc b/content/browser/interest_group/interest_group_storage_unittest.cc index b2fa44b..e75df4b 100644 --- a/content/browser/interest_group/interest_group_storage_unittest.cc +++ b/content/browser/interest_group/interest_group_storage_unittest.cc
@@ -4,6 +4,8 @@ #include "content/browser/interest_group/interest_group_storage.h" +#include <stddef.h> + #include <functional> #include <memory> @@ -201,7 +203,7 @@ histograms.ExpectUniqueSample("Storage.InterestGroup.PerSiteCount", 1u, 1); } -// Test that joining and interest group twice increments the counter. +// Test that joining an interest group twice increments the counter. // Test that joining multiple interest groups with the same owner only creates a // single distinct owner. Test that leaving one interest group does not affect // membership of other interest groups by the same owner. @@ -249,6 +251,53 @@ EXPECT_EQ(test_origin, origins[0]); } +// Join 5 interest groups in the same origin, and one interest group in another +// origin. +// +// Fetch interest groups for update with a limit of 2 interest groups. Only 2 +// interest groups should be returned, and they should all belong to the first +// test origin. +// +// Then, fetch 100 groups for update. Only 5 should be returned. +TEST_F(InterestGroupStorageTest, GetInterestGroupsForUpdate) { + const url::Origin test_origin1 = + url::Origin::Create(GURL("https://owner1.example.com")); + const url::Origin test_origin2 = + url::Origin::Create(GURL("https://owner2.example.com")); + std::unique_ptr<InterestGroupStorage> storage = CreateStorage(); + + constexpr size_t kNumOrigin1Groups = 5, kSmallFetchGroups = 2, + kLargeFetchGroups = 100; + ASSERT_LT(kSmallFetchGroups, kNumOrigin1Groups); + ASSERT_GT(kLargeFetchGroups, kNumOrigin1Groups); + for (size_t i = 0; i < kNumOrigin1Groups; i++) { + storage->JoinInterestGroup( + NewInterestGroup(test_origin1, + base::StrCat({"example", base::NumberToString(i)})), + test_origin1.GetURL()); + } + storage->JoinInterestGroup(NewInterestGroup(test_origin2, "example"), + test_origin2.GetURL()); + + std::vector<StorageInterestGroup> update_groups = + storage->GetInterestGroupsForUpdate(test_origin1, + /*groups_limit=*/kSmallFetchGroups); + + EXPECT_EQ(kSmallFetchGroups, update_groups.size()); + for (const auto& group : update_groups) { + EXPECT_EQ(test_origin1, group.interest_group.owner); + } + + update_groups = + storage->GetInterestGroupsForUpdate(test_origin1, + /*groups_limit=*/kLargeFetchGroups); + + EXPECT_EQ(kNumOrigin1Groups, update_groups.size()); + for (const auto& group : update_groups) { + EXPECT_EQ(test_origin1, group.interest_group.owner); + } +} + TEST_F(InterestGroupStorageTest, BidCount) { const url::Origin test_origin = url::Origin::Create(GURL("https://owner.example.com"));
diff --git a/content/browser/interest_group/interest_group_update_manager.cc b/content/browser/interest_group/interest_group_update_manager.cc index c3aec8b..d9a4b95 100644 --- a/content/browser/interest_group/interest_group_update_manager.cc +++ b/content/browser/interest_group/interest_group_update_manager.cc
@@ -37,6 +37,9 @@ // cancelled for taking too long. constexpr base::TimeDelta kMaxUpdateRoundDuration = base::Minutes(10); +// The maximum number of groups that can be updated at the same time. +constexpr int kMaxParallelUpdates = 5; + constexpr net::NetworkTrafficAnnotationTag kTrafficAnnotation = net::DefineNetworkTrafficAnnotation("interest_group_update_fetcher", R"( semantics { @@ -185,6 +188,7 @@ scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory) : manager_(manager), max_update_round_duration_(kMaxUpdateRoundDuration), + max_parallel_updates_(kMaxParallelUpdates), url_loader_factory_(std::move(url_loader_factory)) {} InterestGroupUpdateManager::~InterestGroupUpdateManager() = default; @@ -201,6 +205,11 @@ max_update_round_duration_ = delta; } +void InterestGroupUpdateManager::set_max_parallel_updates_for_testing( + int max_parallel_updates) { + max_parallel_updates_ = max_parallel_updates; +} + InterestGroupUpdateManager::OwnersToUpdate::OwnersToUpdate() = default; InterestGroupUpdateManager::OwnersToUpdate::~OwnersToUpdate() = default; @@ -275,7 +284,8 @@ DCHECK_EQ(num_in_flight_updates_, 0); DCHECK(!waiting_on_db_read_); waiting_on_db_read_ = true; - manager_->GetInterestGroupsForUpdate(owner, std::move(callback)); + manager_->GetInterestGroupsForUpdate( + owner, /*groups_limit=*/max_parallel_updates_, std::move(callback)); } void InterestGroupUpdateManager::DidUpdateInterestGroupsOfOwnerDbLoad( @@ -284,6 +294,8 @@ DCHECK_EQ(owner, owners_to_update_.FrontOwner()); DCHECK_EQ(num_in_flight_updates_, 0); DCHECK(waiting_on_db_read_); + DCHECK_LE(storage_groups.size(), + static_cast<unsigned int>(max_parallel_updates_)); waiting_on_db_read_ = false; if (storage_groups.empty()) { // All interest groups for `owner` are up to date, so we can pop it off the
diff --git a/content/browser/interest_group/interest_group_update_manager.h b/content/browser/interest_group/interest_group_update_manager.h index cbf9a684..5ca05c27 100644 --- a/content/browser/interest_group/interest_group_update_manager.h +++ b/content/browser/interest_group/interest_group_update_manager.h
@@ -63,6 +63,10 @@ // process can run before it gets cancelled for taking too long. void set_max_update_round_duration_for_testing(base::TimeDelta delta); + // For testing *only*; changes the maximum number of groups that can be + // updated at the same time. + void set_max_parallel_updates_for_testing(int max_parallel_updates); + private: using UrlLoadersList = std::list<std::unique_ptr<network::SimpleURLLoader>>; @@ -222,6 +226,11 @@ // Should *only* be changed by tests. base::TimeDelta max_update_round_duration_; + // The maximum number of groups that can be updated at the same time. + // + // Should *only* be changed by tests. + int max_parallel_updates_; + // The last time we started a round of updating; used to cancel long-running // updates. base::TimeTicks last_update_started_ = base::TimeTicks::Min();
diff --git a/content/browser/network_service_restart_browsertest.cc b/content/browser/network_service_restart_browsertest.cc index 8ff5cd9..a53c017 100644 --- a/content/browser/network_service_restart_browsertest.cc +++ b/content/browser/network_service_restart_browsertest.cc
@@ -62,10 +62,6 @@ #include "testing/gmock/include/gmock/gmock.h" #include "third_party/blink/public/common/features.h" -#if BUILDFLAG(ENABLE_PLUGINS) -#include "content/public/test/ppapi_test_utils.h" -#endif - namespace content { namespace { @@ -140,12 +136,6 @@ const NetworkServiceRestartBrowserTest&) = delete; void SetUpCommandLine(base::CommandLine* command_line) override { -#if BUILDFLAG(ENABLE_PLUGINS) - // TODO(lukasza, kmoon): https://crbug.com/702993: Remove this dependency - // (and //ppapi/tests/corb_test_plugin.cc + BUILD.gn dependencies) once - // PDF support doesn't depend on PPAPI anymore. - ASSERT_TRUE(ppapi::RegisterCorbTestPlugin(command_line)); -#endif ContentBrowserTest::SetUpCommandLine(command_line); } @@ -1012,96 +1002,6 @@ EXPECT_EQ("foo=bar", EvalJs(web_contents, "document.cookie;")); } -#if BUILDFLAG(ENABLE_PLUGINS) -// Make sure that "trusted" plugins continue to be able to issue requests that -// are cross-origin (wrt the host frame) after a network process crash: -// - html frame: main-frame.com/title1.html -// \-- plugin document: cross.origin.com/.../js.txt (`plugin_document_url`) -// \-- request from plugin: cross.origin.com/.../js.txt -// This mimics the behavior of PDFs, which only issue requests for the plugin -// document (e.q. network::ResourceRequest::request_initiator is same-origin wrt -// ResourceRequest::url). -// -// This primarily verifies that OnNetworkServiceCrashRestorePluginExceptions in -// render_process_host_impl.cc refreshes AddAllowedRequestInitiatorForPlugin -// data after a NetworkService crash. -// -// See also https://crbug.com/874515 and https://crbug.com/846339. -// -// TODO(lukasza, kmoon): https://crbug.com/702993: Remove this test once PDF -// support doesn't depend on PPAPI anymore. -IN_PROC_BROWSER_TEST_F(NetworkServiceRestartBrowserTest, Plugin) { - if (IsInProcessNetworkService()) - return; - auto* web_contents = shell()->web_contents(); - ASSERT_TRUE(NavigateToURL( - web_contents, - embedded_test_server()->GetURL("main.frame.com", "/title1.html"))); - - // Load cross-origin document into the test plugin (see - // ppapi::RegisterCorbTestPlugin). - // - // The document has to be a MIME type that CORB will allow (such as - // javascript) - it cannot be a pdf or json, because these would be blocked by - // CORB (the real PDF plugin works because the plugin is hosted in a Chrome - // Extension where CORB is turned off). - GURL plugin_document_url = embedded_test_server()->GetURL( - "cross.origin.com", "/site_isolation/js.txt"); - const char kLoadingScriptTemplate[] = R"( - var obj = document.createElement('object'); - obj.id = 'plugin'; - obj.data = $1; - obj.type = 'application/x-fake-pdf-for-testing'; - obj.width = 400; - obj.height = 400; - - document.body.appendChild(obj); - )"; - EXPECT_FALSE( - web_contents->GetMainFrame()->GetLastCommittedOrigin().IsSameOriginWith( - url::Origin::Create(plugin_document_url))); - ASSERT_TRUE(ExecJs(web_contents, - JsReplace(kLoadingScriptTemplate, plugin_document_url))); - - // Ask the plugin to re-request the document URL (similarly to what the PDF - // plugin does to get chunks of linearized PDFs). - const char kFetchScriptTemplate[] = R"( - new Promise(function (resolve, reject) { - var obj = document.getElementById('plugin'); - function callback(event) { - // Ignore plugin messages unrelated to requestUrl. - if (!event.data.startsWith('requestUrl: ')) - return; - - obj.removeEventListener('message', callback); - resolve('msg-from-plugin: ' + event.data); - }; - obj.addEventListener('message', callback); - obj.postMessage('requestUrl: ' + $1); - }); - )"; - std::string fetch_script = - JsReplace(kFetchScriptTemplate, plugin_document_url); - ASSERT_EQ( - "msg-from-plugin: requestUrl: RESPONSE BODY: " - "var j = 0; document.write(j);\n", - EvalJs(web_contents, fetch_script)); - - // Crash the Network Service process and wait until host frame's - // URLLoaderFactory has been refreshed. - SimulateNetworkServiceCrash(); - main_frame()->FlushNetworkAndNavigationInterfacesForTesting(); - - // Try the fetch again - it should still work (i.e. the mechanism for relaxing - // request_initiator_origin_lock enforcement should be resilient to network - // process crashes). - ASSERT_EQ( - "msg-from-plugin: requestUrl: RESPONSE BODY: " - "var j = 0; document.write(j);\n", - EvalJs(web_contents, fetch_script)); -} -#endif - // TODO(crbug.com/901026): Fix deadlock on process startup on Android. #if BUILDFLAG(IS_ANDROID) IN_PROC_BROWSER_TEST_F(NetworkServiceRestartBrowserTest,
diff --git a/content/browser/plugin_service_impl.cc b/content/browser/plugin_service_impl.cc index 8074a84..2824157 100644 --- a/content/browser/plugin_service_impl.cc +++ b/content/browser/plugin_service_impl.cc
@@ -149,39 +149,6 @@ return nullptr; } - if (info->permissions & ppapi::PERMISSION_PDF) { - // Extra assertions for the PDF plugin. These assertions do not apply to - // the test plugin. - if (0 == (info->permissions & ppapi::PERMISSION_TESTING)) { - // We want to limit ability to bypass |request_initiator_origin_lock| to - // trustworthy renderers. PDF plugin is okay, because it is always hosted - // by the PDF extension (mhjfbmdgcfjbbpaeojofohoefgiehjai) or - // chrome://print, both of which we assume are trustworthy (the extension - // process can also host other extensions, but this is okay). - // - // The CHECKs below help verify that |render_process_id| does not host - // web-controlled content. This is a defense-in-depth for verifying that - // ShouldAllowPluginCreation called above is doing the right thing. - auto* policy = ChildProcessSecurityPolicyImpl::GetInstance(); - ProcessLock renderer_lock = policy->GetProcessLock(render_process_id); - CHECK(!renderer_lock.matches_scheme(url::kHttpScheme) && - !renderer_lock.matches_scheme(url::kHttpsScheme)); - CHECK(embedder_origin.scheme() != url::kHttpScheme); - CHECK(embedder_origin.scheme() != url::kHttpsScheme); - CHECK(!embedder_origin.opaque()); - } - - // In some scenarios, the PDF plugin can issue fetch requests that will need - // to be proxied by |render_process_id| - such proxying needs to bypass - // CORB. See also https://crbug.com/1027173. - // - // TODO(lukasza, kmoon): https://crbug.com/702993: Remove the code here once - // PDF support doesn't depend on PPAPI anymore. - DCHECK(origin_lock.has_value()); - RenderProcessHostImpl::AddAllowedRequestInitiatorForPlugin( - render_process_id, origin_lock.value()); - } - PpapiPluginProcessHost* plugin_host = FindPpapiPluginProcess(plugin_path, profile_data_directory, origin_lock); if (plugin_host)
diff --git a/content/browser/renderer_host/navigation_request.cc b/content/browser/renderer_host/navigation_request.cc index 32e16c5..c2aee0a 100644 --- a/content/browser/renderer_host/navigation_request.cc +++ b/content/browser/renderer_host/navigation_request.cc
@@ -146,6 +146,7 @@ #include "third_party/blink/public/common/permissions_policy/document_policy.h" #include "third_party/blink/public/common/renderer_preferences/renderer_preferences.h" #include "third_party/blink/public/common/security/address_space_feature.h" +#include "third_party/blink/public/common/user_agent/user_agent_metadata.h" #include "third_party/blink/public/common/web_preferences/web_preferences.h" #include "third_party/blink/public/mojom/fetch/fetch_api_request.mojom.h" #include "third_party/blink/public/mojom/loader/mixed_content.mojom.h" @@ -325,6 +326,31 @@ return headers.GetHeader(header, &value) && value == "?1"; } +void LogUserAgentOverrideHistogram(const std::string& user_agent) { + std::string ua_original = GetContentClient()->browser()->GetUserAgent(); + base::UmaHistogramEnumeration("Navigation.UserAgentStringType", + UserAgentStringType::kOverriden); + + if (!base::FeatureList::IsEnabled( + blink::features::kUserAgentOverrideExperiment)) { + return; + } + + auto it = user_agent.find(ua_original); + blink::UserAgentOverride::UserAgentOverrideHistogram histogram = + blink::UserAgentOverride::UserAgentOverrideHistogram::UserAgentOverriden; + if (it == 0) { + histogram = blink::UserAgentOverride::UserAgentOverrideHistogram:: + UserAgentOverrideSuffix; + } else if (it != std::string::npos) { + histogram = blink::UserAgentOverride::UserAgentOverrideHistogram:: + UserAgentOverrideSubstring; + } + + base::UmaHistogramEnumeration( + blink::UserAgentOverride::kUserAgentOverrideHistogram, histogram); +} + // Computes the value that should be set for the User-Agent header, based on the // values of relevant headers like Sec-CH-UA-Reduced or Sec-CH-UA-Full. If // `user_agent_override` is non-empty, `user_agent_override` is returned as the @@ -333,8 +359,7 @@ const std::string& user_agent_override, content::BrowserContext* context) { if (!user_agent_override.empty()) { - base::UmaHistogramEnumeration("Navigation.UserAgentStringType", - UserAgentStringType::kOverriden); + LogUserAgentOverrideHistogram(user_agent_override); return user_agent_override; } @@ -1567,12 +1592,16 @@ BrowserContext* browser_context = controller->GetBrowserContext(); ClientHintsControllerDelegate* client_hints_delegate = browser_context->GetClientHintsControllerDelegate(); - if (client_hints_delegate) { + // Loading an about:srcdoc url on the main frame will cause a failure later + // and GetTentativeOriginAtRequestTime() can't handle it until then. + if ((CheckAboutSrcDoc() != AboutSrcDocCheckResult::BLOCK_REQUEST) && + client_hints_delegate) { net::HttpRequestHeaders client_hints_headers; AddNavigationRequestClientHintsHeaders( - url::Origin::Create(common_params_->url), &client_hints_headers, + GetTentativeOriginAtRequestTime(), &client_hints_headers, browser_context, client_hints_delegate, is_overriding_user_agent(), - frame_tree_node_, commit_params_->frame_policy.container_policy); + frame_tree_node_, commit_params_->frame_policy.container_policy, + common_params_->url); headers.MergeFrom(client_hints_headers); } @@ -4085,16 +4114,18 @@ net::HTTP_TEMPORARY_REDIRECT) { std::vector<network::mojom::WebClientHintsType> client_hints = LookupAcceptCHForCommit(source_origin, client_hints_delegate, - frame_tree_node_); + frame_tree_node_, + commit_params_->redirects.back()); RemoveOriginTrialHintsFromAcceptCH(commit_params_->redirects.back(), client_hints_delegate, response_head, client_hints, frame_tree_node_); } AddNavigationRequestClientHintsHeaders( - url::Origin::Create(common_params_->url), &client_hints_extra_headers, + GetTentativeOriginAtRequestTime(), &client_hints_extra_headers, browser_context, client_hints_delegate, is_overriding_user_agent(), - frame_tree_node_, commit_params_->frame_policy.container_policy); + frame_tree_node_, commit_params_->frame_policy.container_policy, + common_params_->url); modified_headers.MergeFrom(client_hints_extra_headers); // On a redirect, unless devtools has overridden the User-Agent header, if // the Critical-CH header has Sec-CH-UA-Reduced, then we should send the @@ -4495,8 +4526,8 @@ frame_tree_node_); } commit_params_->enabled_client_hints = - LookupAcceptCHForCommit(url::Origin::Create(common_params_->url), - client_hints_delegate, frame_tree_node_); + LookupAcceptCHForCommit(GetOriginToCommit(), client_hints_delegate, + frame_tree_node_, common_params_->url); RemoveOriginTrialHintsFromAcceptCH( common_params_->url, client_hints_delegate, response(), commit_params_->enabled_client_hints, frame_tree_node_); @@ -6659,8 +6690,9 @@ browser_context->GetClientHintsControllerDelegate(); if (client_hints_delegate) { UpdateNavigationRequestClientUaHeaders( - url::Origin::Create(common_params_->url), client_hints_delegate, - is_overriding_user_agent(), frame_tree_node_, &headers); + GetTentativeOriginAtRequestTime(), client_hints_delegate, + is_overriding_user_agent(), frame_tree_node_, &headers, + common_params_->url); } headers.SetHeader( net::HttpRequestHeaders::kUserAgent,
diff --git a/content/browser/web_contents/web_contents_impl_browsertest.cc b/content/browser/web_contents/web_contents_impl_browsertest.cc index 3c415139..e89f092 100644 --- a/content/browser/web_contents/web_contents_impl_browsertest.cc +++ b/content/browser/web_contents/web_contents_impl_browsertest.cc
@@ -23,6 +23,7 @@ #include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" #include "base/test/bind.h" +#include "base/test/metrics/histogram_tester.h" #include "base/test/scoped_feature_list.h" #include "base/test/test_timeouts.h" #include "base/threading/thread_restrictions.h" @@ -99,6 +100,7 @@ #include "third_party/blink/public/common/client_hints/client_hints.h" #include "third_party/blink/public/common/features.h" #include "third_party/blink/public/common/page/page_zoom.h" +#include "third_party/blink/public/common/user_agent/user_agent_metadata.h" #include "third_party/blink/public/mojom/frame/fullscreen.mojom.h" #include "ui/base/clipboard/clipboard_format_type.h" #include "url/gurl.h" @@ -2454,6 +2456,96 @@ EvalJs(shell()->web_contents(), "document.body.textContent;")); } +class WebContentsImplBrowserTestUserAgentOverrideSubstring + : public WebContentsImplBrowserTest { + public: + void SetUp() override { + scoped_feature_list_.InitAndEnableFeature( + blink::features::kUserAgentOverrideExperiment); + WebContentsImplBrowserTest::SetUp(); + } + + private: + base::test::ScopedFeatureList scoped_feature_list_; +}; + +// Verify UserAgentOverride histograms +IN_PROC_BROWSER_TEST_F(WebContentsImplBrowserTestUserAgentOverrideSubstring, + UserAgentOverrideHistogram) { + ASSERT_TRUE(embedded_test_server()->Start()); + const std::string kHeaderPath = + std::string("/echoheader?") + net::HttpRequestHeaders::kUserAgent; + const GURL kUrl(embedded_test_server()->GetURL(kHeaderPath)); + EXPECT_TRUE(NavigateToURL(shell(), kUrl)); + + std::string original_ua = ShellContentBrowserClient::Get()->GetUserAgent(); + std::string ua_no_substring = "foo"; + std::string ua_prefix = "foo" + original_ua; + std::string ua_suffix = original_ua + "foo"; + { + base::HistogramTester histogram; + shell()->web_contents()->SetUserAgentOverride( + blink::UserAgentOverride::UserAgentOnly(ua_no_substring), false); + shell() + ->web_contents() + ->GetController() + .GetLastCommittedEntry() + ->SetIsOverridingUserAgent(true); + EXPECT_TRUE(NavigateToURL(shell(), kUrl)); + histogram.ExpectBucketCount( + blink::UserAgentOverride::kUserAgentOverrideHistogram, + blink::UserAgentOverride::UserAgentOverriden, 1); + histogram.ExpectBucketCount( + blink::UserAgentOverride::kUserAgentOverrideHistogram, + blink::UserAgentOverride::UserAgentOverrideSubstring, 0); + histogram.ExpectBucketCount( + blink::UserAgentOverride::kUserAgentOverrideHistogram, + blink::UserAgentOverride::UserAgentOverrideSuffix, 0); + } + + { + base::HistogramTester histogram; + shell()->web_contents()->SetUserAgentOverride( + blink::UserAgentOverride::UserAgentOnly(ua_prefix), false); + shell() + ->web_contents() + ->GetController() + .GetLastCommittedEntry() + ->SetIsOverridingUserAgent(true); + EXPECT_TRUE(NavigateToURL(shell(), kUrl)); + histogram.ExpectBucketCount( + blink::UserAgentOverride::kUserAgentOverrideHistogram, + blink::UserAgentOverride::UserAgentOverriden, 0); + histogram.ExpectBucketCount( + blink::UserAgentOverride::kUserAgentOverrideHistogram, + blink::UserAgentOverride::UserAgentOverrideSubstring, 1); + histogram.ExpectBucketCount( + blink::UserAgentOverride::kUserAgentOverrideHistogram, + blink::UserAgentOverride::UserAgentOverrideSuffix, 0); + } + + { + base::HistogramTester histogram; + shell()->web_contents()->SetUserAgentOverride( + blink::UserAgentOverride::UserAgentOnly(ua_suffix), false); + shell() + ->web_contents() + ->GetController() + .GetLastCommittedEntry() + ->SetIsOverridingUserAgent(true); + EXPECT_TRUE(NavigateToURL(shell(), kUrl)); + histogram.ExpectBucketCount( + blink::UserAgentOverride::kUserAgentOverrideHistogram, + blink::UserAgentOverride::UserAgentOverriden, 0); + histogram.ExpectBucketCount( + blink::UserAgentOverride::kUserAgentOverrideHistogram, + blink::UserAgentOverride::UserAgentOverrideSubstring, 0); + histogram.ExpectBucketCount( + blink::UserAgentOverride::kUserAgentOverrideHistogram, + blink::UserAgentOverride::UserAgentOverrideSuffix, 1); + } +} + // Verifies the user-agent string may be changed in DidStartNavigation(). IN_PROC_BROWSER_TEST_F(WebContentsImplBrowserTest, SetUserAgentOverrideFromDidStartNavigation) {
diff --git a/content/browser/webid/federated_auth_request_impl.cc b/content/browser/webid/federated_auth_request_impl.cc index 4016d20..195cef85 100644 --- a/content/browser/webid/federated_auth_request_impl.cc +++ b/content/browser/webid/federated_auth_request_impl.cc
@@ -17,6 +17,7 @@ #include "content/public/browser/browser_context.h" #include "content/public/browser/content_browser_client.h" #include "content/public/browser/federated_identity_active_session_permission_context_delegate.h" +#include "content/public/browser/federated_identity_api_permission_context_delegate.h" #include "content/public/browser/federated_identity_request_permission_context_delegate.h" #include "content/public/browser/federated_identity_sharing_permission_context_delegate.h" #include "content/public/browser/render_frame_host.h" @@ -79,6 +80,9 @@ case FederatedAuthRequestResult::kApprovalDeclined: { return "User declined the sign-in attempt."; } + case FederatedAuthRequestResult::kErrorDisabledInSettings: { + return "Third-party sign in was disabled in browser Site Settings."; + } case FederatedAuthRequestResult::kErrorTooManyRequests: { return "Only one navigator.credentials.get request may be outstanding at " "one time."; @@ -174,6 +178,7 @@ case FederatedAuthRequestResult::kErrorCanceled: { return RequestIdTokenStatus::kErrorCanceled; } + case FederatedAuthRequestResult::kErrorDisabledInSettings: case FederatedAuthRequestResult::kErrorFetchingManifestHttpNotFound: case FederatedAuthRequestResult::kErrorFetchingManifestNoResponse: case FederatedAuthRequestResult::kErrorFetchingManifestInvalidResponse: @@ -260,6 +265,13 @@ return; } + if (GetApiPermissionContext() && + !GetApiPermissionContext()->HasApiPermission()) { + CompleteRequest(FederatedAuthRequestResult::kErrorDisabledInSettings, "", + /*should_call_callback=*/false); + return; + } + request_dialog_controller_ = CreateDialogController(); FetchManifest(base::BindOnce(&FederatedAuthRequestImpl::OnManifestFetched, @@ -270,6 +282,13 @@ if (!auth_request_callback_) return; + if (GetApiPermissionContext() && + !GetApiPermissionContext()->HasApiPermission()) { + CompleteRequest(FederatedAuthRequestResult::kErrorDisabledInSettings, "", + /*should_call_callback=*/false); + return; + } + // Dialog will be hidden by the destructor for request_dialog_controller_, // triggered by CompleteRequest. RecordRequestIdTokenStatus(IdTokenStatus::kAborted, @@ -305,6 +324,12 @@ return; } + if (GetApiPermissionContext() && + !GetApiPermissionContext()->HasApiPermission()) { + CompleteRevokeRequest(RevokeStatus::kError, /*should_call_callback=*/false); + return; + } + if (!GetRequestPermissionContext() || !GetRequestPermissionContext()->HasRequestPermission( origin_, url::Origin::Create(provider_))) { @@ -338,6 +363,12 @@ logout_callback_ = std::move(callback); + if (GetApiPermissionContext() && + !GetApiPermissionContext()->HasApiPermission()) { + CompleteLogoutRequest(LogoutRpsStatus::kError); + return; + } + if (logout_requests.empty()) { CompleteLogoutRequest(LogoutRpsStatus::kError); return; @@ -1050,6 +1081,15 @@ return active_session_permission_delegate_; } +FederatedIdentityApiPermissionContextDelegate* +FederatedAuthRequestImpl::GetApiPermissionContext() { + if (!api_permission_delegate_) { + api_permission_delegate_ = render_frame_host_->GetBrowserContext() + ->GetFederatedIdentityApiPermissionContext(); + } + return api_permission_delegate_; +} + FederatedIdentityRequestPermissionContextDelegate* FederatedAuthRequestImpl::GetRequestPermissionContext() { if (!request_permission_delegate_) {
diff --git a/content/browser/webid/federated_auth_request_impl.h b/content/browser/webid/federated_auth_request_impl.h index 3006e88..2dc06e60 100644 --- a/content/browser/webid/federated_auth_request_impl.h +++ b/content/browser/webid/federated_auth_request_impl.h
@@ -24,6 +24,7 @@ namespace content { class FederatedIdentityActiveSessionPermissionContextDelegate; +class FederatedIdentityApiPermissionContextDelegate; class FederatedIdentityRequestPermissionContextDelegate; class FederatedIdentitySharingPermissionContextDelegate; class RenderFrameHostImpl; @@ -131,6 +132,7 @@ FederatedIdentityActiveSessionPermissionContextDelegate* GetActiveSessionPermissionContext(); + FederatedIdentityApiPermissionContextDelegate* GetApiPermissionContext(); FederatedIdentityRequestPermissionContextDelegate* GetRequestPermissionContext(); FederatedIdentitySharingPermissionContextDelegate* @@ -183,6 +185,8 @@ raw_ptr<FederatedIdentityActiveSessionPermissionContextDelegate> active_session_permission_delegate_ = nullptr; + raw_ptr<FederatedIdentityApiPermissionContextDelegate> + api_permission_delegate_ = nullptr; raw_ptr<FederatedIdentityRequestPermissionContextDelegate> request_permission_delegate_ = nullptr; raw_ptr<FederatedIdentitySharingPermissionContextDelegate>
diff --git a/content/child/runtime_features.cc b/content/child/runtime_features.cc index d2b60c3..ecef1337 100644 --- a/content/child/runtime_features.cc +++ b/content/child/runtime_features.cc
@@ -267,7 +267,7 @@ {wf::EnableSharedArrayBuffer, features::kSharedArrayBuffer}, {wf::EnableSharedArrayBufferOnDesktop, features::kSharedArrayBufferOnDesktop}, - {wf::EnableSharedAutofill, autofill::features::kAutofillAcrossIframes}, + {wf::EnableSharedAutofill, autofill::features::kAutofillSharedAutofill}, {wf::EnableSignedExchangeSubresourcePrefetch, features::kSignedExchangeSubresourcePrefetch}, {wf::EnableSkipTouchEventFilter, blink::features::kSkipTouchEventFilter},
diff --git a/content/public/browser/BUILD.gn b/content/public/browser/BUILD.gn index b90cd59..95fece613 100644 --- a/content/public/browser/BUILD.gn +++ b/content/public/browser/BUILD.gn
@@ -166,6 +166,7 @@ "favicon_status.h", "feature_observer_client.h", "federated_identity_active_session_permission_context_delegate.h", + "federated_identity_api_permission_context_delegate.h", "federated_identity_request_permission_context_delegate.h", "federated_identity_sharing_permission_context_delegate.h", "file_select_listener.h",
diff --git a/content/public/browser/browser_context.h b/content/public/browser/browser_context.h index 13775ce..621191a 100644 --- a/content/public/browser/browser_context.h +++ b/content/public/browser/browser_context.h
@@ -83,6 +83,7 @@ class DownloadManager; class DownloadManagerDelegate; class FederatedIdentityActiveSessionPermissionContextDelegate; +class FederatedIdentityApiPermissionContextDelegate; class FederatedIdentityRequestPermissionContextDelegate; class FederatedIdentitySharingPermissionContextDelegate; class FileSystemAccessPermissionContext; @@ -412,6 +413,10 @@ virtual std::unique_ptr<media::VideoDecodePerfHistory> CreateVideoDecodePerfHistory(); + // Gets the permission context for determining whether the FedCM API is + // enabled in site settings. + virtual FederatedIdentityApiPermissionContextDelegate* + GetFederatedIdentityApiPermissionContext(); // Gets the permission context for allowing session management capabilities // between an identity provider and a relying party if one exists, or // nullptr otherwise.
diff --git a/content/public/browser/federated_identity_api_permission_context_delegate.h b/content/public/browser/federated_identity_api_permission_context_delegate.h new file mode 100644 index 0000000..e377850 --- /dev/null +++ b/content/public/browser/federated_identity_api_permission_context_delegate.h
@@ -0,0 +1,23 @@ +// Copyright 2022 The Chromium 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_BROWSER_FEDERATED_IDENTITY_API_PERMISSION_CONTEXT_DELEGATE_H_ +#define CONTENT_PUBLIC_BROWSER_FEDERATED_IDENTITY_API_PERMISSION_CONTEXT_DELEGATE_H_ + +namespace content { + +// Delegate interface for the FedCM implementation to query whether the FedCM +// API is enabled in Site Settings. +class FederatedIdentityApiPermissionContextDelegate { + public: + FederatedIdentityApiPermissionContextDelegate() = default; + virtual ~FederatedIdentityApiPermissionContextDelegate() = default; + + // Returns whether the FedCM API is enabled in site settings. + virtual bool HasApiPermission() = 0; +}; + +} // namespace content + +#endif // CONTENT_PUBLIC_BROWSER_FEDERATED_IDENTITY_API_PERMISSION_CONTEXT_DELEGATE_H_
diff --git a/content/public/test/ppapi_test_utils.cc b/content/public/test/ppapi_test_utils.cc index 1559058..d48fb5e 100644 --- a/content/public/test/ppapi_test_utils.cc +++ b/content/public/test/ppapi_test_utils.cc
@@ -16,7 +16,6 @@ #include "content/browser/renderer_host/pepper/pepper_udp_socket_message_filter.h" #include "content/public/common/content_constants.h" #include "content/public/common/content_switches.h" -#include "ppapi/shared_impl/ppapi_constants.h" #include "ppapi/shared_impl/ppapi_switches.h" using CharType = base::FilePath::CharType; @@ -72,20 +71,6 @@ return RegisterPlugins(command_line, plugins); } -bool RegisterFakePdfPluginLibrary(base::CommandLine* command_line, - const StringType& library_name) { - std::vector<PluginInfo> plugins; - // Register a fake PDF plugin with 100.0 version (to avoid outdated checks). - base::FilePath::StringType fake_pdf_parameter = - base::FilePath::FromUTF8Unsafe(std::string("#") + "Fake PDF" + - "#Description#100.0") - .value(); - plugins.push_back( - PluginInfo(library_name, fake_pdf_parameter, - FILE_PATH_LITERAL("application/x-fake-pdf-for-testing"))); - return RegisterPlugins(command_line, plugins); -} - } // namespace bool RegisterTestPlugin(base::CommandLine* command_line) { @@ -107,12 +92,6 @@ extra_registration_parameters); } -bool RegisterCorbTestPlugin(base::CommandLine* command_line) { - StringType library_name = - base::FilePath::FromUTF8Unsafe(ppapi::kCorbTestPluginName).value(); - return RegisterFakePdfPluginLibrary(command_line, library_name); -} - bool RegisterBlinkTestPlugin(base::CommandLine* command_line) { #if BUILDFLAG(IS_WIN) static const CharType kPluginLibrary[] = L"blink_test_plugin.dll";
diff --git a/content/public/test/ppapi_test_utils.h b/content/public/test/ppapi_test_utils.h index bdaeeba..549c84fc 100644 --- a/content/public/test/ppapi_test_utils.h +++ b/content/public/test/ppapi_test_utils.h
@@ -35,9 +35,6 @@ base::CommandLine* command_line, const base::FilePath::StringType& extra_registration_parameters); -// Registers the PDF-imitating CORB-testing plugin. -[[nodiscard]] bool RegisterCorbTestPlugin(base::CommandLine* command_line); - // Registers the Blink test plugin to application/x-blink-test-plugin. [[nodiscard]] bool RegisterBlinkTestPlugin(base::CommandLine* command_line);
diff --git a/content/renderer/accessibility/render_accessibility_impl_browsertest.cc b/content/renderer/accessibility/render_accessibility_impl_browsertest.cc index 52d9528..cb7cba6 100644 --- a/content/renderer/accessibility/render_accessibility_impl_browsertest.cc +++ b/content/renderer/accessibility/render_accessibility_impl_browsertest.cc
@@ -32,7 +32,6 @@ #include "mojo/public/cpp/bindings/receiver.h" #include "mojo/public/cpp/bindings/receiver_set.h" #include "mojo/public/cpp/bindings/remote.h" -#include "ppapi/c/private/ppp_pdf.h" #include "services/image_annotation/public/cpp/image_processor.h" #include "services/image_annotation/public/mojom/image_annotation.mojom.h" #include "services/metrics/public/cpp/mojo_ukm_recorder.h"
diff --git a/content/renderer/pepper/pepper_plugin_instance_impl.cc b/content/renderer/pepper/pepper_plugin_instance_impl.cc index 87bd9f26..f1a03eb 100644 --- a/content/renderer/pepper/pepper_plugin_instance_impl.cc +++ b/content/renderer/pepper/pepper_plugin_instance_impl.cc
@@ -2083,10 +2083,8 @@ // Some APIs aren't implemented in-process. switch (id) { case ppapi::BROWSER_FONT_SINGLETON_ID: - case ppapi::FLASH_FULLSCREEN_SINGLETON_ID: case ppapi::ISOLATED_FILESYSTEM_SINGLETON_ID: case ppapi::NETWORK_PROXY_SINGLETON_ID: - case ppapi::PDF_SINGLETON_ID: NOTIMPLEMENTED(); return nullptr; case ppapi::GAMEPAD_SINGLETON_ID:
diff --git a/content/renderer/pepper/plugin_module.cc b/content/renderer/pepper/plugin_module.cc index 3892b02..8279ddc 100644 --- a/content/renderer/pepper/plugin_module.cc +++ b/content/renderer/pepper/plugin_module.cc
@@ -104,11 +104,9 @@ #include "ppapi/c/private/ppb_ext_crx_file_system_private.h" #include "ppapi/c/private/ppb_file_io_private.h" #include "ppapi/c/private/ppb_file_ref_private.h" -#include "ppapi/c/private/ppb_flash_font_file.h" #include "ppapi/c/private/ppb_host_resolver_private.h" #include "ppapi/c/private/ppb_instance_private.h" #include "ppapi/c/private/ppb_isolated_file_system_private.h" -#include "ppapi/c/private/ppb_pdf.h" #include "ppapi/c/private/ppb_proxy_private.h" #include "ppapi/c/private/ppb_tcp_server_socket_private.h" #include "ppapi/c/private/ppb_tcp_socket_private.h" @@ -294,9 +292,7 @@ return ppapi::thunk::Get##iface_struct##_Thunk(); #include "ppapi/thunk/interfaces_ppb_private.h" -#include "ppapi/thunk/interfaces_ppb_private_flash.h" #include "ppapi/thunk/interfaces_ppb_private_no_permissions.h" -#include "ppapi/thunk/interfaces_ppb_private_pdf.h" #include "ppapi/thunk/interfaces_ppb_public_dev.h" #include "ppapi/thunk/interfaces_ppb_public_dev_channel.h" #include "ppapi/thunk/interfaces_ppb_public_socket.h"
diff --git a/content/renderer/pepper/resource_creation_impl.cc b/content/renderer/pepper/resource_creation_impl.cc index 41372a7..cd26247 100644 --- a/content/renderer/pepper/resource_creation_impl.cc +++ b/content/renderer/pepper/resource_creation_impl.cc
@@ -81,13 +81,6 @@ return 0; // Not supported in-process. } -PP_Resource ResourceCreationImpl::CreateFlashFontFile( - PP_Instance instance, - const PP_BrowserFont_Trusted_Description* description, - PP_PrivateFontCharset charset) { - return 0; // Not supported in-process. -} - PP_Resource ResourceCreationImpl::CreateGraphics3D(PP_Instance instance, PP_Resource share_context, const int32_t* attrib_list) {
diff --git a/content/renderer/pepper/resource_creation_impl.h b/content/renderer/pepper/resource_creation_impl.h index 73adbe1..bca1a43 100644 --- a/content/renderer/pepper/resource_creation_impl.h +++ b/content/renderer/pepper/resource_creation_impl.h
@@ -43,10 +43,6 @@ PP_Resource CreateAudioOutput(PP_Instance instance) override; PP_Resource CreateBuffer(PP_Instance instance, uint32_t size) override; PP_Resource CreateCameraDevicePrivate(PP_Instance instance) override; - PP_Resource CreateFlashFontFile( - PP_Instance instance, - const PP_BrowserFont_Trusted_Description* description, - PP_PrivateFontCharset charset) override; PP_Resource CreateGraphics3D(PP_Instance instance, PP_Resource share_context, const int32_t* attrib_list) override;
diff --git a/content/test/BUILD.gn b/content/test/BUILD.gn index d6935f7bb..6d45e7b 100644 --- a/content/test/BUILD.gn +++ b/content/test/BUILD.gn
@@ -1540,10 +1540,7 @@ "//ppapi/proxy:ipc", "//ppapi/shared_impl:test_support", ] - data_deps += [ - "//ppapi:corb_test_plugin", - "//ppapi:ppapi_tests", - ] + data_deps += [ "//ppapi:ppapi_tests" ] if (is_mac) { data += [ "$root_out_dir/ppapi_tests.plugin/" ] } @@ -1944,6 +1941,7 @@ "../browser/attribution_reporting/aggregatable_attribution_utils_unittest.cc", "../browser/attribution_reporting/attribution_cookie_checker_impl_unittest.cc", "../browser/attribution_reporting/attribution_data_host_manager_impl_unittest.cc", + "../browser/attribution_reporting/attribution_filter_data_unittest.cc", "../browser/attribution_reporting/attribution_host_unittest.cc", "../browser/attribution_reporting/attribution_host_utils_unittest.cc", "../browser/attribution_reporting/attribution_insecure_random_generator_unittest.cc",
diff --git a/content/test/attribution_simulator_input_parser.cc b/content/test/attribution_simulator_input_parser.cc index 014fc8f..36909fe 100644 --- a/content/test/attribution_simulator_input_parser.cc +++ b/content/test/attribution_simulator_input_parser.cc
@@ -377,10 +377,10 @@ } absl::optional<AttributionFilterData> filter_data = - AttributionFilterData::FromFilterValues(std::move(container)); + AttributionFilterData::FromSourceFilterValues(std::move(container)); // TODO(apaseltiner): Provide more detailed information. if (!filter_data) - *Error() << "too big"; + *Error() << "invalid"; return std::move(filter_data).value_or(AttributionFilterData()); }
diff --git a/content/test/attribution_simulator_input_parser_unittest.cc b/content/test/attribution_simulator_input_parser_unittest.cc index 20021b44..5bd580d 100644 --- a/content/test/attribution_simulator_input_parser_unittest.cc +++ b/content/test/attribution_simulator_input_parser_unittest.cc
@@ -154,10 +154,11 @@ .SetExpiry(base::Days(10)) // rounded to whole number of days .SetPriority(0) // default .SetDebugKey(absl::nullopt) // default - .SetFilterData(*AttributionFilterData::FromFilterValues({ - {"a", {}}, - {"b", {"c", "d"}}, - })) + .SetFilterData( + *AttributionFilterData::FromSourceFilterValues({ + {"a", {}}, + {"b", {"c", "d"}}, + })) .Build(), _)))); EXPECT_THAT(error_stream.str(), IsEmpty());
diff --git a/content/test/data/accessibility/mac/attributes/ax-description-expected.txt b/content/test/data/accessibility/mac/attributes/ax-description-expected.txt new file mode 100644 index 0000000..64c3290 --- /dev/null +++ b/content/test/data/accessibility/mac/attributes/ax-description-expected.txt
@@ -0,0 +1,5 @@ +// AXDescription is a generic attribute. +input.accessibilityAttributeNames.has(AXDescription)='yes' +// AXDescription is mapped to accessibilityLabel +input.accessibilityAttributeValue(AXDescription)='This is input' +empty.accessibilityAttributeValue(AXDescription)=''
diff --git a/content/test/data/accessibility/mac/attributes/ax-description.html b/content/test/data/accessibility/mac/attributes/ax-description.html new file mode 100644 index 0000000..68c5af8 --- /dev/null +++ b/content/test/data/accessibility/mac/attributes/ax-description.html
@@ -0,0 +1,11 @@ +<!-- +@SCRIPT: + // AXDescription is a generic attribute. + input.accessibilityAttributeNames.has(AXDescription) + // AXDescription is mapped to accessibilityLabel + input.accessibilityAttributeValue(AXDescription) + empty.accessibilityAttributeValue(AXDescription) +--> +<!DOCTYPE html> +<input id="input" aria-label="This is input"> +<input id="empty">
diff --git a/content/test/data/accessibility/mac/methods/accessibility-label-expected.txt b/content/test/data/accessibility/mac/methods/accessibility-label-expected.txt new file mode 100644 index 0000000..aeeeb12c --- /dev/null +++ b/content/test/data/accessibility/mac/methods/accessibility-label-expected.txt
@@ -0,0 +1,2 @@ +// Labelable with not empty name +labelable.accessibilityLabel='This is input'
diff --git a/content/test/data/accessibility/mac/methods/accessibility-label.html b/content/test/data/accessibility/mac/methods/accessibility-label.html new file mode 100644 index 0000000..1820706a --- /dev/null +++ b/content/test/data/accessibility/mac/methods/accessibility-label.html
@@ -0,0 +1,7 @@ +<!-- +@SCRIPT: + // Labelable with not empty name + labelable.accessibilityLabel +--> +<!DOCTYPE html> +<input id="labelable" aria-label="This is input">
diff --git a/content/test/data/accessibility/regression/footer-inside-section-role-generic-expected-blink.txt b/content/test/data/accessibility/regression/footer-inside-section-role-generic-expected-blink.txt new file mode 100644 index 0000000..66e3067 --- /dev/null +++ b/content/test/data/accessibility/regression/footer-inside-section-role-generic-expected-blink.txt
@@ -0,0 +1,12 @@ +rootWebArea +++genericContainer ignored +++++genericContainer ignored +++++++footerAsNonLandmark +++++++++paragraph +++++++++++staticText name='footer inside section with role presentational.' +++++++++++++inlineTextBox name='footer inside section with role presentational.' +++++++genericContainer +++++++++footerAsNonLandmark +++++++++++paragraph +++++++++++++staticText name='footer inside section with role generic.' +++++++++++++++inlineTextBox name='footer inside section with role generic.'
diff --git a/content/test/data/accessibility/regression/footer-inside-section-role-generic.html b/content/test/data/accessibility/regression/footer-inside-section-role-generic.html new file mode 100644 index 0000000..7cbae1f4 --- /dev/null +++ b/content/test/data/accessibility/regression/footer-inside-section-role-generic.html
@@ -0,0 +1,11 @@ +<!DOCTYPE html> +<section role="presentation"> + <footer> + <p>footer inside section with role presentational.</p> + </footer> +</section> +<section role="generic"> + <footer> + <p>footer inside section with role generic.</p> + </footer> +</section>
diff --git a/content/test/data/accessibility/regression/header-inside-section-role-generic-expected-blink.txt b/content/test/data/accessibility/regression/header-inside-section-role-generic-expected-blink.txt new file mode 100644 index 0000000..49e54dd --- /dev/null +++ b/content/test/data/accessibility/regression/header-inside-section-role-generic-expected-blink.txt
@@ -0,0 +1,12 @@ +rootWebArea +++genericContainer ignored +++++genericContainer ignored +++++++headerAsNonLandmark +++++++++paragraph +++++++++++staticText name='header inside section with role presentational.' +++++++++++++inlineTextBox name='header inside section with role presentational.' +++++++genericContainer +++++++++headerAsNonLandmark +++++++++++paragraph +++++++++++++staticText name='header inside section with role generic.' +++++++++++++++inlineTextBox name='header inside section with role generic.'
diff --git a/content/test/data/accessibility/regression/header-inside-section-role-generic.html b/content/test/data/accessibility/regression/header-inside-section-role-generic.html new file mode 100644 index 0000000..d0677ee --- /dev/null +++ b/content/test/data/accessibility/regression/header-inside-section-role-generic.html
@@ -0,0 +1,11 @@ +<!DOCTYPE html> +<section role="presentation"> + <header> + <p>header inside section with role presentational.</p> + </header> +</section> +<section role="generic"> + <header> + <p>header inside section with role generic.</p> + </header> +</section>
diff --git a/content/test/data/gpu/pixel_webgpu_cached_swap_buffer_invalidated.html b/content/test/data/gpu/pixel_webgpu_cached_swap_buffer_invalidated.html index a8ac584..ea8c53ab 100644 --- a/content/test/data/gpu/pixel_webgpu_cached_swap_buffer_invalidated.html +++ b/content/test/data/gpu/pixel_webgpu_cached_swap_buffer_invalidated.html
@@ -45,6 +45,7 @@ device: device, format: 'bgra8unorm', usage: GPUTextureUsage.RENDER_ATTACHMENT, + compositingAlphaMode: 'premultiplied', }); let framesToRender = 30;
diff --git a/content/test/gpu/gpu_tests/test_expectations/pixel_expectations.txt b/content/test/gpu/gpu_tests/test_expectations/pixel_expectations.txt index 9de7e58..c4e3e4e 100644 --- a/content/test/gpu/gpu_tests/test_expectations/pixel_expectations.txt +++ b/content/test/gpu/gpu_tests/test_expectations/pixel_expectations.txt
@@ -377,6 +377,9 @@ crbug.com/1290953 [ android android-pixel-4 android-webview-instrumentation ] Pixel_CanvasLowLatency2DDrawImage [ Failure ] crbug.com/1290953 [ android android-pixel-4 android-webview-instrumentation ] Pixel_CanvasLowLatency2DImageData [ Failure ] +# Flaky incorrect rendering on Windows Nvidia 1660 +crbug.com/1181126 [ win10 nvidia-0x2184 ] Pixel_WebGL2_BlitFramebuffer_Result_Displayed [ RetryOnFailure ] + ####################################################################### # Automated Entries After This Point - Do Not Manually Add Below Here # #######################################################################
diff --git a/extensions/browser/permissions_manager.cc b/extensions/browser/permissions_manager.cc index fa358fe..fcade45 100644 --- a/extensions/browser/permissions_manager.cc +++ b/extensions/browser/permissions_manager.cc
@@ -209,6 +209,19 @@ return user_permissions_; } +PermissionsManager::UserSiteSetting PermissionsManager::GetUserSiteSetting( + const url::Origin& origin) const { + if (user_permissions_.permitted_sites.find(origin) != + user_permissions_.permitted_sites.end()) { + return UserSiteSetting::kGrantAllExtensions; + } + if (user_permissions_.restricted_sites.find(origin) != + user_permissions_.restricted_sites.end()) { + return UserSiteSetting::kBlockAllExtensions; + } + return UserSiteSetting::kCustomizeByExtension; +} + void PermissionsManager::AddObserver(Observer* observer) { observers_.AddObserver(observer); }
diff --git a/extensions/browser/permissions_manager.h b/extensions/browser/permissions_manager.h index e61ab705..ab409b8 100644 --- a/extensions/browser/permissions_manager.h +++ b/extensions/browser/permissions_manager.h
@@ -52,6 +52,17 @@ std::set<url::Origin> permitted_sites; }; + // The user's site setting for a given site. + enum class UserSiteSetting { + // All extensions that request access are granted access in the site. + kGrantAllExtensions, + // All extensions that request access have withheld access in the site. + kBlockAllExtensions, + // Each extension that requests access can have its site access customized + // in the site. + kCustomizeByExtension, + }; + class Observer { public: virtual void UserPermissionsSettingsChanged( @@ -93,6 +104,9 @@ // Returns the user's permission settings. const UserPermissionsSettings& GetUserPermissionsSettings() const; + // Returns the user's site setting for `origin`. + UserSiteSetting GetUserSiteSetting(const url::Origin& origin) const; + // Adds or removes observers. void AddObserver(Observer* observer); void RemoveObserver(Observer* observer);
diff --git a/extensions/browser/permissions_manager_unittest.cc b/extensions/browser/permissions_manager_unittest.cc index 7e9b258..19a55a5 100644 --- a/extensions/browser/permissions_manager_unittest.cc +++ b/extensions/browser/permissions_manager_unittest.cc
@@ -20,6 +20,8 @@ namespace extensions { +using UserSiteSetting = PermissionsManager::UserSiteSetting; + class PermissionsManagerUnittest : public ExtensionsTest { public: PermissionsManagerUnittest() = default; @@ -94,12 +96,16 @@ // Verify the restricted sites list is empty. EXPECT_EQ(GetRestrictedSitesFromManager(), std::set<url::Origin>()); EXPECT_EQ(GetRestrictedSitesFromPrefs(), nullptr); + EXPECT_EQ(manager_->GetUserSiteSetting(url), + UserSiteSetting::kCustomizeByExtension); // Add `url` to restricted sites. Verify the site is stored both in manager // and prefs restricted sites. manager_->AddUserRestrictedSite(url); EXPECT_EQ(GetRestrictedSitesFromManager(), set_with_url); EXPECT_EQ(*GetRestrictedSitesFromPrefs(), value_with_url); + EXPECT_EQ(manager_->GetUserSiteSetting(url), + UserSiteSetting::kBlockAllExtensions); // Adding an existent restricted site. Verify the entry is not duplicated. manager_->AddUserRestrictedSite(url); @@ -112,6 +118,8 @@ EXPECT_EQ(GetRestrictedSitesFromManager(), std::set<url::Origin>()); EXPECT_EQ(*GetRestrictedSitesFromPrefs(), base::Value(base::Value::Type::LIST)); + EXPECT_EQ(manager_->GetUserSiteSetting(url), + UserSiteSetting::kCustomizeByExtension); } TEST_F(PermissionsManagerUnittest, AddAndRemovePermittedSite) { @@ -124,12 +132,16 @@ // Verify the permitted sites list is empty. EXPECT_EQ(GetPermittedSitesFromManager(), std::set<url::Origin>()); EXPECT_EQ(GetPermittedSitesFromPrefs(), nullptr); + EXPECT_EQ(manager_->GetUserSiteSetting(url), + PermissionsManager::UserSiteSetting::kCustomizeByExtension); // Add `url` to permitted sites. Verify the site is stored both in manager // and prefs permitted sites. manager_->AddUserPermittedSite(url); EXPECT_EQ(GetPermittedSitesFromManager(), set_with_url); EXPECT_EQ(*GetPermittedSitesFromPrefs(), value_with_url); + EXPECT_EQ(manager_->GetUserSiteSetting(url), + PermissionsManager::UserSiteSetting::kGrantAllExtensions); // Adding an existent permitted site. Verify the entry is not duplicated. manager_->AddUserPermittedSite(url); @@ -142,6 +154,8 @@ EXPECT_EQ(GetPermittedSitesFromManager(), std::set<url::Origin>()); EXPECT_EQ(*GetPermittedSitesFromPrefs(), base::Value(base::Value::Type::LIST)); + EXPECT_EQ(manager_->GetUserSiteSetting(url), + PermissionsManager::UserSiteSetting::kCustomizeByExtension); } TEST_F(PermissionsManagerUnittest, @@ -157,6 +171,8 @@ manager_->GetUserPermissionsSettings(); EXPECT_EQ(actual_permissions.restricted_sites, set_with_url); EXPECT_EQ(actual_permissions.permitted_sites, empty_set); + EXPECT_EQ(manager_->GetUserSiteSetting(url), + PermissionsManager::UserSiteSetting::kBlockAllExtensions); } { @@ -168,6 +184,8 @@ manager_->GetUserPermissionsSettings(); EXPECT_EQ(actual_permissions.restricted_sites, empty_set); EXPECT_EQ(actual_permissions.permitted_sites, set_with_url); + EXPECT_EQ(manager_->GetUserSiteSetting(url), + PermissionsManager::UserSiteSetting::kGrantAllExtensions); } { @@ -179,6 +197,8 @@ manager_->GetUserPermissionsSettings(); EXPECT_EQ(actual_permissions.restricted_sites, set_with_url); EXPECT_EQ(actual_permissions.permitted_sites, empty_set); + EXPECT_EQ(manager_->GetUserSiteSetting(url), + PermissionsManager::UserSiteSetting::kBlockAllExtensions); } }
diff --git a/extensions/renderer/guest_view/guest_view_internal_custom_bindings.cc b/extensions/renderer/guest_view/guest_view_internal_custom_bindings.cc index 4959f96d..b27291f 100644 --- a/extensions/renderer/guest_view/guest_view_internal_custom_bindings.cc +++ b/extensions/renderer/guest_view/guest_view_internal_custom_bindings.cc
@@ -194,7 +194,7 @@ // Add flag to |params| to indicate that the element size is specified in // logical units. - params->SetBoolean(guest_view::kElementSizeIsLogical, true); + params->GetDict().Set(guest_view::kElementSizeIsLogical, true); content::RenderFrame* embedder_parent_frame = content::RenderFrame::FromWebFrame(parent_frame->ToWebLocalFrame());
diff --git a/extensions/shell/browser/shell_virtual_keyboard_delegate.cc b/extensions/shell/browser/shell_virtual_keyboard_delegate.cc index 6051ea5..d1e088b 100644 --- a/extensions/shell/browser/shell_virtual_keyboard_delegate.cc +++ b/extensions/shell/browser/shell_virtual_keyboard_delegate.cc
@@ -17,7 +17,7 @@ void ShellVirtualKeyboardDelegate::GetKeyboardConfig( OnKeyboardSettingsCallback on_settings_callback) { std::unique_ptr<base::DictionaryValue> settings(new base::DictionaryValue()); - settings->SetBoolean("hotrodmode", is_hotrod_keyboard_); + settings->GetDict().Set("hotrodmode", is_hotrod_keyboard_); std::move(on_settings_callback).Run(std::move(settings)); }
diff --git a/gpu/command_buffer/service/external_vk_image_dawn_representation.cc b/gpu/command_buffer/service/external_vk_image_dawn_representation.cc index fc63311..5f8b5ed 100644 --- a/gpu/command_buffer/service/external_vk_image_dawn_representation.cc +++ b/gpu/command_buffer/service/external_vk_image_dawn_representation.cc
@@ -55,11 +55,12 @@ texture_descriptor.mipLevelCount = 1; texture_descriptor.sampleCount = 1; - // We need to have an internal usage of CopySrc in order to use - // CopyTextureToTextureInternal. + // We need to have internal usages of CopySrc for copies and + // RenderAttachment for clears. WGPUDawnTextureInternalUsageDescriptor internalDesc = {}; internalDesc.chain.sType = WGPUSType_DawnTextureInternalUsageDescriptor; - internalDesc.internalUsage = WGPUTextureUsage_CopySrc; + internalDesc.internalUsage = + WGPUTextureUsage_CopySrc | WGPUTextureUsage_RenderAttachment; texture_descriptor.nextInChain = reinterpret_cast<WGPUChainedStruct*>(&internalDesc);
diff --git a/gpu/command_buffer/service/shared_image_backing_d3d.cc b/gpu/command_buffer/service/shared_image_backing_d3d.cc index 9f51ca99..2e2c33e 100644 --- a/gpu/command_buffer/service/shared_image_backing_d3d.cc +++ b/gpu/command_buffer/service/shared_image_backing_d3d.cc
@@ -620,11 +620,12 @@ } #endif - // We need to have an internal usage of CopySrc in order to use - // CopyTextureToTextureInternal. + // We need to have internal usages of CopySrc for copies and + // RenderAttachment for clears. WGPUDawnTextureInternalUsageDescriptor internalDesc = {}; internalDesc.chain.sType = WGPUSType_DawnTextureInternalUsageDescriptor; - internalDesc.internalUsage = WGPUTextureUsage_CopySrc; + internalDesc.internalUsage = + WGPUTextureUsage_CopySrc | WGPUTextureUsage_RenderAttachment; texture_descriptor.nextInChain = reinterpret_cast<WGPUChainedStruct*>(&internalDesc);
diff --git a/gpu/command_buffer/service/shared_image_backing_factory_iosurface.mm b/gpu/command_buffer/service/shared_image_backing_factory_iosurface.mm index 66598f2..5cfcad9 100644 --- a/gpu/command_buffer/service/shared_image_backing_factory_iosurface.mm +++ b/gpu/command_buffer/service/shared_image_backing_factory_iosurface.mm
@@ -120,11 +120,12 @@ texture_descriptor.mipLevelCount = 1; texture_descriptor.sampleCount = 1; - // We need to have an internal usage of CopySrc in order to use - // CopyTextureToTextureInternal. + // We need to have internal usages of CopySrc for copies and + // RenderAttachment for clears. WGPUDawnTextureInternalUsageDescriptor internalDesc = {}; internalDesc.chain.sType = WGPUSType_DawnTextureInternalUsageDescriptor; - internalDesc.internalUsage = WGPUTextureUsage_CopySrc; + internalDesc.internalUsage = + WGPUTextureUsage_CopySrc | WGPUTextureUsage_RenderAttachment; texture_descriptor.nextInChain = reinterpret_cast<WGPUChainedStruct*>(&internalDesc);
diff --git a/gpu/command_buffer/service/shared_image_representation_dawn_ozone.cc b/gpu/command_buffer/service/shared_image_representation_dawn_ozone.cc index 6e3ddef..9d3d98c 100644 --- a/gpu/command_buffer/service/shared_image_representation_dawn_ozone.cc +++ b/gpu/command_buffer/service/shared_image_representation_dawn_ozone.cc
@@ -70,11 +70,12 @@ texture_descriptor.mipLevelCount = 1; texture_descriptor.sampleCount = 1; - // We need to have an internal usage of CopySrc in order to use - // CopyTextureToTextureInternal. + // We need to have internal usages of CopySrc for copies and + // RenderAttachment for clears. WGPUDawnTextureInternalUsageDescriptor internalDesc = {}; internalDesc.chain.sType = WGPUSType_DawnTextureInternalUsageDescriptor; - internalDesc.internalUsage = WGPUTextureUsage_CopySrc; + internalDesc.internalUsage = + WGPUTextureUsage_CopySrc | WGPUTextureUsage_RenderAttachment; texture_descriptor.nextInChain = reinterpret_cast<WGPUChainedStruct*>(&internalDesc);
diff --git a/gpu/command_buffer/service/webgpu_decoder_impl.cc b/gpu/command_buffer/service/webgpu_decoder_impl.cc index dd1e79f..bd85889f 100644 --- a/gpu/command_buffer/service/webgpu_decoder_impl.cc +++ b/gpu/command_buffer/service/webgpu_decoder_impl.cc
@@ -1812,8 +1812,15 @@ render_pass_descriptor.colorAttachmentCount = 1; render_pass_descriptor.colorAttachments = &color_attachment; + WGPUDawnEncoderInternalUsageDescriptor internal_usage_desc = { + .chain = {.sType = WGPUSType_DawnEncoderInternalUsageDescriptor}, + .useInternalUsages = true, + }; + WGPUCommandEncoderDescriptor command_encoder_desc = { + .nextInChain = &internal_usage_desc.chain, + }; WGPUCommandEncoder encoder = - procs.deviceCreateCommandEncoder(device, nullptr); + procs.deviceCreateCommandEncoder(device, &command_encoder_desc); WGPURenderPassEncoder pass = procs.commandEncoderBeginRenderPass(encoder, &render_pass_descriptor); procs.renderPassEncoderEndPass(pass);
diff --git a/infra/config/generated/builders/ci/mac-fieldtrial-rel/properties.json b/infra/config/generated/builders/ci/mac-fieldtrial-rel/properties.json new file mode 100644 index 0000000..7f417dd --- /dev/null +++ b/infra/config/generated/builders/ci/mac-fieldtrial-rel/properties.json
@@ -0,0 +1,59 @@ +{ + "$build/chromium_tests_builder_config": { + "builder_config": { + "builder_db": { + "entries": [ + { + "builder_id": { + "bucket": "ci", + "builder": "mac-fieldtrial-rel", + "project": "chromium" + }, + "builder_spec": { + "builder_group": "chromium.fyi", + "execution_mode": "COMPILE_AND_TEST", + "legacy_chromium_config": { + "apply_configs": [ + "mb" + ], + "build_config": "Release", + "config": "chromium", + "target_bits": 64 + }, + "legacy_gclient_config": { + "config": "chromium" + } + } + } + ] + }, + "builder_ids": [ + { + "bucket": "ci", + "builder": "mac-fieldtrial-rel", + "project": "chromium" + } + ], + "mirroring_builder_group_and_names": [ + { + "builder": "mac-fieldtrial-fyi-rel", + "group": "tryserver.chromium.mac" + } + ] + } + }, + "$build/goma": { + "rpc_extra_params": "?prod", + "server_host": "goma.chromium.org", + "use_luci_auth": true + }, + "$recipe_engine/resultdb/test_presentation": { + "column_keys": [], + "grouping_keys": [ + "status", + "v.test_suite" + ] + }, + "builder_group": "chromium.fyi", + "recipe": "chromium" +} \ No newline at end of file
diff --git a/infra/config/generated/builders/try/mac-fieldtrial-fyi-rel/properties.json b/infra/config/generated/builders/try/mac-fieldtrial-fyi-rel/properties.json new file mode 100644 index 0000000..589310b2 --- /dev/null +++ b/infra/config/generated/builders/try/mac-fieldtrial-fyi-rel/properties.json
@@ -0,0 +1,53 @@ +{ + "$build/chromium_tests_builder_config": { + "builder_config": { + "builder_db": { + "entries": [ + { + "builder_id": { + "bucket": "ci", + "builder": "mac-fieldtrial-rel", + "project": "chromium" + }, + "builder_spec": { + "builder_group": "chromium.fyi", + "execution_mode": "COMPILE_AND_TEST", + "legacy_chromium_config": { + "apply_configs": [ + "mb" + ], + "build_config": "Release", + "config": "chromium", + "target_bits": 64 + }, + "legacy_gclient_config": { + "config": "chromium" + } + } + } + ] + }, + "builder_ids": [ + { + "bucket": "ci", + "builder": "mac-fieldtrial-rel", + "project": "chromium" + } + ] + } + }, + "$build/goma": { + "rpc_extra_params": "?prod", + "server_host": "goma.chromium.org", + "use_luci_auth": true + }, + "$recipe_engine/resultdb/test_presentation": { + "column_keys": [], + "grouping_keys": [ + "status", + "v.test_suite" + ] + }, + "builder_group": "tryserver.chromium.mac", + "recipe": "chromium_trybot" +} \ No newline at end of file
diff --git a/infra/config/generated/luci/commit-queue.cfg b/infra/config/generated/luci/commit-queue.cfg index 3b368ba..757ed57f 100644 --- a/infra/config/generated/luci/commit-queue.cfg +++ b/infra/config/generated/luci/commit-queue.cfg
@@ -1601,6 +1601,10 @@ includable_only: true } builders { + name: "chromium/try/mac-fieldtrial-fyi-rel" + includable_only: true + } + builders { name: "chromium/try/mac-inverse-fieldtrials-fyi-rel" includable_only: true }
diff --git a/infra/config/generated/luci/cr-buildbucket.cfg b/infra/config/generated/luci/cr-buildbucket.cfg index f3e99c2..d4b2eef 100644 --- a/infra/config/generated/luci/cr-buildbucket.cfg +++ b/infra/config/generated/luci/cr-buildbucket.cfg
@@ -37374,6 +37374,83 @@ } } builders { + name: "mac-fieldtrial-rel" + swarming_host: "chromium-swarm.appspot.com" + dimensions: "builder:mac-fieldtrial-rel" + dimensions: "cpu:x86-64" + dimensions: "os:Mac-11" + dimensions: "pool:luci.chromium.ci" + exe { + cipd_package: "infra/chromium/bootstrapper/${platform}" + cipd_version: "latest" + cmd: "bootstrapper" + } + properties: + '{' + ' "$bootstrap/exe": {' + ' "exe": {' + ' "cipd_package": "infra/recipe_bundles/chromium.googlesource.com/chromium/tools/build",' + ' "cipd_version": "refs/heads/main",' + ' "cmd": [' + ' "luciexe"' + ' ]' + ' }' + ' },' + ' "$bootstrap/properties": {' + ' "properties_file": "infra/config/generated/builders/ci/mac-fieldtrial-rel/properties.json",' + ' "top_level_project": {' + ' "ref": "refs/heads/main",' + ' "repo": {' + ' "host": "chromium.googlesource.com",' + ' "project": "chromium/src"' + ' }' + ' }' + ' },' + ' "builder_group": "chromium.fyi",' + ' "led_builder_is_bootstrapped": true,' + ' "recipe": "chromium"' + '}' + execution_timeout_secs: 36000 + build_numbers: YES + service_account: "chromium-ci-builder@chops-service-accounts.iam.gserviceaccount.com" + experiments { + key: "luci.recipes.use_python3" + value: 100 + } + resultdb { + enable: true + bq_exports { + project: "chrome-luci-data" + dataset: "chromium" + table: "ci_test_results" + test_results {} + } + bq_exports { + project: "chrome-luci-data" + dataset: "chromium" + table: "gpu_ci_test_results" + test_results { + predicate { + test_id_regexp: "ninja://chrome/test:telemetry_gpu_integration_test[^/]*/.+" + } + } + } + bq_exports { + project: "chrome-luci-data" + dataset: "chromium" + table: "blink_web_tests_ci_test_results" + test_results { + predicate { + test_id_regexp: "ninja://[^/]*blink_web_tests/.+" + } + } + } + history_options { + use_invocation_timestamp: true + } + } + } + builders { name: "mac-hermetic-upgrade-rel" swarming_host: "chromium-swarm.appspot.com" dimensions: "builder:mac-hermetic-upgrade-rel" @@ -70886,6 +70963,95 @@ } } builders { + name: "mac-fieldtrial-fyi-rel" + swarming_host: "chromium-swarm.appspot.com" + dimensions: "builderless:1" + dimensions: "cpu:x86-64" + dimensions: "os:Mac-11" + dimensions: "pool:luci.chromium.try" + dimensions: "ssd:1" + exe { + cipd_package: "infra/chromium/bootstrapper/${platform}" + cipd_version: "latest" + cmd: "bootstrapper" + } + properties: + '{' + ' "$bootstrap/exe": {' + ' "exe": {' + ' "cipd_package": "infra/recipe_bundles/chromium.googlesource.com/chromium/tools/build",' + ' "cipd_version": "refs/heads/main",' + ' "cmd": [' + ' "luciexe"' + ' ]' + ' }' + ' },' + ' "$bootstrap/properties": {' + ' "properties_file": "infra/config/generated/builders/try/mac-fieldtrial-fyi-rel/properties.json",' + ' "top_level_project": {' + ' "ref": "refs/heads/main",' + ' "repo": {' + ' "host": "chromium.googlesource.com",' + ' "project": "chromium/src"' + ' }' + ' }' + ' },' + ' "builder_group": "tryserver.chromium.mac",' + ' "led_builder_is_bootstrapped": true,' + ' "recipe": "chromium_trybot"' + '}' + execution_timeout_secs: 14400 + expiration_secs: 7200 + grace_period { + seconds: 120 + } + caches { + name: "win_toolchain" + path: "win_toolchain" + } + build_numbers: YES + service_account: "chromium-try-builder@chops-service-accounts.iam.gserviceaccount.com" + task_template_canary_percentage { + value: 5 + } + experiments { + key: "luci.recipes.use_python3" + value: 100 + } + resultdb { + enable: true + bq_exports { + project: "chrome-luci-data" + dataset: "chromium" + table: "try_test_results" + test_results {} + } + bq_exports { + project: "chrome-luci-data" + dataset: "chromium" + table: "gpu_try_test_results" + test_results { + predicate { + test_id_regexp: "ninja://chrome/test:telemetry_gpu_integration_test[^/]*/.+" + } + } + } + bq_exports { + project: "chrome-luci-data" + dataset: "chromium" + table: "blink_web_tests_try_test_results" + test_results { + predicate { + test_id_regexp: "ninja://[^/]*blink_web_tests/.+" + } + } + } + history_options { + use_invocation_timestamp: true + } + } + } + builders { name: "mac-inverse-fieldtrials-fyi-rel" swarming_host: "chromium-swarm.appspot.com" dimensions: "builderless:1"
diff --git a/infra/config/generated/luci/luci-milo.cfg b/infra/config/generated/luci/luci-milo.cfg index 29f9802..cb7608f 100644 --- a/infra/config/generated/luci/luci-milo.cfg +++ b/infra/config/generated/luci/luci-milo.cfg
@@ -6427,6 +6427,10 @@ category: "cronet" } builders { + name: "buildbucket/luci.chromium.ci/mac-fieldtrial-rel" + category: "mac" + } + builders { name: "buildbucket/luci.chromium.ci/Mac Builder Next" category: "mac" short_name: "bld" @@ -15269,6 +15273,9 @@ name: "buildbucket/luci.chromium.try/mac-dawn-rel" } builders { + name: "buildbucket/luci.chromium.try/mac-fieldtrial-fyi-rel" + } + builders { name: "buildbucket/luci.chromium.try/mac-inverse-fieldtrials-fyi-rel" } builders { @@ -16377,6 +16384,9 @@ name: "buildbucket/luci.chromium.try/mac-clang-tidy-rel" } builders { + name: "buildbucket/luci.chromium.try/mac-fieldtrial-fyi-rel" + } + builders { name: "buildbucket/luci.chromium.try/mac-inverse-fieldtrials-fyi-rel" } builders {
diff --git a/infra/config/generated/luci/luci-scheduler.cfg b/infra/config/generated/luci/luci-scheduler.cfg index afe5505..722b8bb 100644 --- a/infra/config/generated/luci/luci-scheduler.cfg +++ b/infra/config/generated/luci/luci-scheduler.cfg
@@ -6147,6 +6147,16 @@ } } job { + id: "mac-fieldtrial-rel" + realm: "ci" + acl_sets: "ci" + buildbucket { + server: "cr-buildbucket.appspot.com" + bucket: "ci" + builder: "mac-fieldtrial-rel" + } +} +job { id: "mac-hermetic-upgrade-rel" realm: "ci" acl_sets: "ci" @@ -7330,6 +7340,7 @@ triggers: "mac-arm64-on-arm64-rel-reclient" triggers: "mac-arm64-rel" triggers: "mac-code-coverage" + triggers: "mac-fieldtrial-rel" triggers: "mac-hermetic-upgrade-rel" triggers: "mac-mojo-rel" triggers: "mac-official"
diff --git a/infra/config/generated/sheriff-rotations/android b/infra/config/generated/sheriff-rotations/android.txt similarity index 100% rename from infra/config/generated/sheriff-rotations/android rename to infra/config/generated/sheriff-rotations/android.txt
diff --git a/infra/config/generated/sheriff-rotations/chromium.clang b/infra/config/generated/sheriff-rotations/chromium.clang.txt similarity index 100% rename from infra/config/generated/sheriff-rotations/chromium.clang rename to infra/config/generated/sheriff-rotations/chromium.clang.txt
diff --git a/infra/config/generated/sheriff-rotations/chromium.gpu b/infra/config/generated/sheriff-rotations/chromium.gpu.txt similarity index 100% rename from infra/config/generated/sheriff-rotations/chromium.gpu rename to infra/config/generated/sheriff-rotations/chromium.gpu.txt
diff --git a/infra/config/generated/sheriff-rotations/chromium b/infra/config/generated/sheriff-rotations/chromium.txt similarity index 100% rename from infra/config/generated/sheriff-rotations/chromium rename to infra/config/generated/sheriff-rotations/chromium.txt
diff --git a/infra/config/generated/sheriff-rotations/ios b/infra/config/generated/sheriff-rotations/ios.txt similarity index 100% rename from infra/config/generated/sheriff-rotations/ios rename to infra/config/generated/sheriff-rotations/ios.txt
diff --git a/infra/config/lib/sheriff_rotations.star b/infra/config/lib/sheriff_rotations.star index 56f2e49..f3f306d 100644 --- a/infra/config/lib/sheriff_rotations.star +++ b/infra/config/lib/sheriff_rotations.star
@@ -37,7 +37,7 @@ for sheriffed_builder_node in graph.children(sheriff_rotation_node.key, _SHERIFFED_BUILDER.kind): key = sheriffed_builder_node.key sheriffed_builders.append("{}/{}".format(key.container.id, key.id)) - sheriff_rotation_file = "sheriff-rotations/{}".format(sheriff_rotation_node.key.id) + sheriff_rotation_file = "sheriff-rotations/{}.txt".format(sheriff_rotation_node.key.id) ctx.output[sheriff_rotation_file] = "".join(["{}\n".format(b) for b in sorted(sheriffed_builders)]) lucicfg.generator(_generate_sheriff_rotations_files)
diff --git a/infra/config/main.star b/infra/config/main.star index 29f234f..d98790c 100755 --- a/infra/config/main.star +++ b/infra/config/main.star
@@ -37,7 +37,7 @@ "luci/realms.cfg", "luci/tricium-prod.cfg", "outages.pyl", - "sheriff-rotations/*", + "sheriff-rotations/*.txt", "project.pyl", ], fail_on_warnings = True,
diff --git a/infra/config/subprojects/chromium/ci/chromium.fyi.star b/infra/config/subprojects/chromium/ci/chromium.fyi.star index 8cee44f..dce8d24 100644 --- a/infra/config/subprojects/chromium/ci/chromium.fyi.star +++ b/infra/config/subprojects/chromium/ci/chromium.fyi.star
@@ -442,6 +442,27 @@ ) ci.builder( + name = "mac-fieldtrial-rel", + builderless = False, + console_view_entry = consoles.console_view_entry( + category = "mac", + ), + builder_spec = builder_config.builder_spec( + chromium_config = builder_config.chromium_config( + config = "chromium", + apply_configs = ["mb"], + build_config = builder_config.build_config.RELEASE, + target_bits = 64, + ), + gclient_config = builder_config.gclient_config( + config = "chromium", + ), + ), + cores = None, + os = os.MAC_DEFAULT, +) + +ci.builder( name = "linux-lacros-builder-fyi-rel", console_view_entry = consoles.console_view_entry( category = "linux",
diff --git a/infra/config/subprojects/chromium/try/tryserver.chromium.mac.star b/infra/config/subprojects/chromium/try/tryserver.chromium.mac.star index 9a4baefd..853be83 100644 --- a/infra/config/subprojects/chromium/try/tryserver.chromium.mac.star +++ b/infra/config/subprojects/chromium/try/tryserver.chromium.mac.star
@@ -52,6 +52,12 @@ ) try_.builder( + name = "mac-fieldtrial-fyi-rel", + os = os.MAC_DEFAULT, + mirrors = ["ci/mac-fieldtrial-rel"], +) + +try_.builder( name = "mac-builder-next-rel", os = os.MAC_12, )
diff --git a/ios/chrome/browser/ui/badges/badge_popup_menu_item.mm b/ios/chrome/browser/ui/badges/badge_popup_menu_item.mm index fca9fad..3e3a0cf 100644 --- a/ios/chrome/browser/ui/badges/badge_popup_menu_item.mm +++ b/ios/chrome/browser/ui/badges/badge_popup_menu_item.mm
@@ -202,11 +202,26 @@ _titleLabel.textColor = [UIColor colorNamed:kBlueColor]; _titleLabel.adjustsFontForContentSizeCategory = YES; + // ImageView is wrapped inside a wrapper to support symbol image. Doing so + // makes sure that the size of the badge stays the same across all cells, + // regardless of the badge image being used. _badgeView = [[UIImageView alloc] init]; _badgeView.translatesAutoresizingMaskIntoConstraints = NO; - _badgeView.tintColor = [UIColor colorNamed:kBlueColor]; - _badgeView.backgroundColor = [UIColor colorNamed:kBlueHaloColor]; - _badgeView.layer.cornerRadius = kBadgeCornerRadius; + UIView* badgeWrapperView = [[UIView alloc] init]; + badgeWrapperView.translatesAutoresizingMaskIntoConstraints = NO; + badgeWrapperView.tintColor = [UIColor colorNamed:kBlueColor]; + badgeWrapperView.backgroundColor = [UIColor colorNamed:kBlueHaloColor]; + badgeWrapperView.layer.cornerRadius = kBadgeCornerRadius; + [badgeWrapperView addSubview:_badgeView]; + + [NSLayoutConstraint activateConstraints:@[ + [badgeWrapperView.widthAnchor + constraintEqualToConstant:kCellHeight - 2 * kVerticalMargin], + [badgeWrapperView.centerXAnchor + constraintEqualToAnchor:_badgeView.centerXAnchor], + [badgeWrapperView.centerYAnchor + constraintEqualToAnchor:_badgeView.centerYAnchor], + ]]; _trailingImageView = [[UIImageView alloc] initWithImage: @@ -216,11 +231,9 @@ _trailingImageView.tintColor = [UIColor colorNamed:kBlueColor]; [self.contentView addSubview:_titleLabel]; - [self.contentView addSubview:_badgeView]; + [self.contentView addSubview:badgeWrapperView]; [self.contentView addSubview:_trailingImageView]; - // TODO(crbug.com/1293060): Maintain image aspect ratio once we move icon - // image file format to SVG from PNG. ApplyVisualConstraintsWithMetrics( @[ @"H:|-(margin)-[badge]-(margin)-[text]-(margin)-[gear]-(margin)-|", @@ -230,7 +243,7 @@ ], @{ @"text" : _titleLabel, - @"badge" : _badgeView, + @"badge" : badgeWrapperView, @"gear" : _trailingImageView, }, @{
diff --git a/ios/chrome/browser/ui/content_suggestions/BUILD.gn b/ios/chrome/browser/ui/content_suggestions/BUILD.gn index 8a7ef7e5..00b1170f 100644 --- a/ios/chrome/browser/ui/content_suggestions/BUILD.gn +++ b/ios/chrome/browser/ui/content_suggestions/BUILD.gn
@@ -113,10 +113,12 @@ source_set("content_suggestions_ui") { sources = [ + "content_suggestions_collection_consumer.h", "content_suggestions_collection_controlling.h", "content_suggestions_collection_synchronizing.h", + "content_suggestions_collection_view_controller.h", + "content_suggestions_collection_view_controller.mm", "content_suggestions_commands.h", - "content_suggestions_consumer.h", "content_suggestions_header_commands.h", "content_suggestions_header_controlling.h", "content_suggestions_header_provider.h", @@ -130,8 +132,6 @@ "content_suggestions_header_view_controller_delegate.h", "content_suggestions_layout.h", "content_suggestions_layout.mm", - "content_suggestions_view_controller.h", - "content_suggestions_view_controller.mm", "content_suggestions_view_controller_audience.h", "ntp_home_consumer.h", "user_account_image_update_delegate.h",
diff --git a/ios/chrome/browser/ui/content_suggestions/OWNERS b/ios/chrome/browser/ui/content_suggestions/OWNERS index 12fb7e67..24334e1 100644 --- a/ios/chrome/browser/ui/content_suggestions/OWNERS +++ b/ios/chrome/browser/ui/content_suggestions/OWNERS
@@ -1,3 +1,4 @@ gambard@chromium.org sczs@chromium.org -adamta@google.com \ No newline at end of file +adamta@google.com +thegreenfrog@chromium.org \ No newline at end of file
diff --git a/ios/chrome/browser/ui/content_suggestions/content_suggestions_consumer.h b/ios/chrome/browser/ui/content_suggestions/content_suggestions_collection_consumer.h similarity index 91% rename from ios/chrome/browser/ui/content_suggestions/content_suggestions_consumer.h rename to ios/chrome/browser/ui/content_suggestions/content_suggestions_collection_consumer.h index 4f5ffbc..c27deb7 100644 --- a/ios/chrome/browser/ui/content_suggestions/content_suggestions_consumer.h +++ b/ios/chrome/browser/ui/content_suggestions/content_suggestions_collection_consumer.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 IOS_CHROME_BROWSER_UI_CONTENT_SUGGESTIONS_CONTENT_SUGGESTIONS_CONSUMER_H_ -#define IOS_CHROME_BROWSER_UI_CONTENT_SUGGESTIONS_CONTENT_SUGGESTIONS_CONSUMER_H_ +#ifndef IOS_CHROME_BROWSER_UI_CONTENT_SUGGESTIONS_CONTENT_SUGGESTIONS_COLLECTION_CONSUMER_H_ +#define IOS_CHROME_BROWSER_UI_CONTENT_SUGGESTIONS_CONTENT_SUGGESTIONS_COLLECTION_CONSUMER_H_ #import "ios/chrome/browser/ui/content_suggestions/cells/suggested_content.h" @@ -13,7 +13,7 @@ using CSCollectionViewItem = CollectionViewItem<SuggestedContent>; -@protocol ContentSuggestionsConsumer +@protocol ContentSuggestionsCollectionConsumer // Informs the consumer to reload with |sections| and |items|. - (void)reloadDataWithSections: @@ -36,4 +36,4 @@ @end -#endif // IOS_CHROME_BROWSER_UI_CONTENT_SUGGESTIONS_CONTENT_SUGGESTIONS_CONSUMER_H_ +#endif // IOS_CHROME_BROWSER_UI_CONTENT_SUGGESTIONS_CONTENT_SUGGESTIONS_COLLECTION_CONSUMER_H_
diff --git a/ios/chrome/browser/ui/content_suggestions/content_suggestions_view_controller.h b/ios/chrome/browser/ui/content_suggestions/content_suggestions_collection_view_controller.h similarity index 91% rename from ios/chrome/browser/ui/content_suggestions/content_suggestions_view_controller.h rename to ios/chrome/browser/ui/content_suggestions/content_suggestions_collection_view_controller.h index 7a3d89a..a73b51b 100644 --- a/ios/chrome/browser/ui/content_suggestions/content_suggestions_view_controller.h +++ b/ios/chrome/browser/ui/content_suggestions/content_suggestions_collection_view_controller.h
@@ -1,15 +1,15 @@ -// Copyright 2016 The Chromium Authors. All rights reserved. +// Copyright 2022 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef IOS_CHROME_BROWSER_UI_CONTENT_SUGGESTIONS_CONTENT_SUGGESTIONS_VIEW_CONTROLLER_H_ -#define IOS_CHROME_BROWSER_UI_CONTENT_SUGGESTIONS_CONTENT_SUGGESTIONS_VIEW_CONTROLLER_H_ +#ifndef IOS_CHROME_BROWSER_UI_CONTENT_SUGGESTIONS_CONTENT_SUGGESTIONS_COLLECTION_VIEW_CONTROLLER_H_ +#define IOS_CHROME_BROWSER_UI_CONTENT_SUGGESTIONS_CONTENT_SUGGESTIONS_COLLECTION_VIEW_CONTROLLER_H_ #import <UIKit/UIKit.h> #import "ios/chrome/browser/ui/collection_view/collection_view_controller.h" #import "ios/chrome/browser/ui/content_suggestions/cells/suggested_content.h" -#import "ios/chrome/browser/ui/content_suggestions/content_suggestions_consumer.h" +#import "ios/chrome/browser/ui/content_suggestions/content_suggestions_collection_consumer.h" namespace { @@ -60,8 +60,8 @@ @protocol SuggestedContent; // CollectionViewController to display the suggestions items. -@interface ContentSuggestionsViewController - : CollectionViewController <ContentSuggestionsConsumer> +@interface ContentSuggestionsCollectionViewController + : CollectionViewController <ContentSuggestionsCollectionConsumer> // Inits view controller with |style|. - (instancetype)initWithStyle:(CollectionViewControllerStyle)style @@ -96,4 +96,4 @@ - (UIView*)headerViewForWidth:(CGFloat)width; @end -#endif // IOS_CHROME_BROWSER_UI_CONTENT_SUGGESTIONS_CONTENT_SUGGESTIONS_VIEW_CONTROLLER_H_ +#endif // IOS_CHROME_BROWSER_UI_CONTENT_SUGGESTIONS_CONTENT_SUGGESTIONS_COLLECTION_VIEW_CONTROLLER_H_
diff --git a/ios/chrome/browser/ui/content_suggestions/content_suggestions_view_controller.mm b/ios/chrome/browser/ui/content_suggestions/content_suggestions_collection_view_controller.mm similarity index 98% rename from ios/chrome/browser/ui/content_suggestions/content_suggestions_view_controller.mm rename to ios/chrome/browser/ui/content_suggestions/content_suggestions_collection_view_controller.mm index c362558..af9ea1f8 100644 --- a/ios/chrome/browser/ui/content_suggestions/content_suggestions_view_controller.mm +++ b/ios/chrome/browser/ui/content_suggestions/content_suggestions_collection_view_controller.mm
@@ -1,8 +1,8 @@ -// Copyright 2016 The Chromium Authors. All rights reserved. +// Copyright 2022 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#import "ios/chrome/browser/ui/content_suggestions/content_suggestions_view_controller.h" +#import "ios/chrome/browser/ui/content_suggestions/content_suggestions_collection_view_controller.h" #include "base/mac/foundation_util.h" #include "base/metrics/user_metrics.h" @@ -56,7 +56,7 @@ const CGFloat kCardBorderRadius = 11; } // namespace -@interface ContentSuggestionsViewController () < +@interface ContentSuggestionsCollectionViewController () < UIGestureRecognizerDelegate, ContentSuggestionsSelectionActions> @@ -77,7 +77,7 @@ @end -@implementation ContentSuggestionsViewController +@implementation ContentSuggestionsCollectionViewController @dynamic collectionViewModel; @@ -284,6 +284,7 @@ (UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section { if ([self isHeaderSection:section]) { + DCHECK(!IsContentSuggestionsHeaderMigrationEnabled()); return CGSizeMake(0, [self.headerProvider headerHeight]); } CGSize defaultSize = [super collectionView:collectionView @@ -325,7 +326,6 @@ return [self shouldUseCustomStyleForSection:section]; } - #pragma mark - UIGestureRecognizerDelegate - (BOOL)gestureRecognizer:(UIGestureRecognizer*)gestureRecognizer @@ -336,7 +336,7 @@ ntp_home::FakeOmniboxAccessibilityID(); } -#pragma mark - ContentSuggestionsConsumer +#pragma mark - ContentSuggestionsCollectionConsumer - (void)reloadDataWithSections: (NSArray<ContentSuggestionsSectionInformation*>*)sections
diff --git a/ios/chrome/browser/ui/content_suggestions/content_suggestions_coordinator.mm b/ios/chrome/browser/ui/content_suggestions/content_suggestions_coordinator.mm index 6054638..2deb152f 100644 --- a/ios/chrome/browser/ui/content_suggestions/content_suggestions_coordinator.mm +++ b/ios/chrome/browser/ui/content_suggestions/content_suggestions_coordinator.mm
@@ -37,6 +37,7 @@ #import "ios/chrome/browser/ui/commands/omnibox_commands.h" #import "ios/chrome/browser/ui/commands/open_new_tab_command.h" #import "ios/chrome/browser/ui/content_suggestions/cells/content_suggestions_most_visited_item.h" +#import "ios/chrome/browser/ui/content_suggestions/content_suggestions_collection_view_controller.h" #import "ios/chrome/browser/ui/content_suggestions/content_suggestions_constants.h" #import "ios/chrome/browser/ui/content_suggestions/content_suggestions_feature.h" #import "ios/chrome/browser/ui/content_suggestions/content_suggestions_header_commands.h" @@ -44,7 +45,6 @@ #import "ios/chrome/browser/ui/content_suggestions/content_suggestions_header_view_controller.h" #import "ios/chrome/browser/ui/content_suggestions/content_suggestions_mediator.h" #import "ios/chrome/browser/ui/content_suggestions/content_suggestions_menu_provider.h" -#import "ios/chrome/browser/ui/content_suggestions/content_suggestions_view_controller.h" #import "ios/chrome/browser/ui/content_suggestions/content_suggestions_view_controller_audience.h" #import "ios/chrome/browser/ui/content_suggestions/ntp_home_constant.h" #import "ios/chrome/browser/ui/content_suggestions/ntp_home_mediator.h" @@ -89,7 +89,7 @@ } @property(nonatomic, strong) - ContentSuggestionsViewController* suggestionsViewController; + ContentSuggestionsCollectionViewController* suggestionsViewController; @property(nonatomic, strong) ContentSuggestionsMediator* contentSuggestionsMediator; @property(nonatomic, strong) @@ -209,8 +209,9 @@ [self.contentSuggestionsMediator notificationPromo]->CanShow(); } - self.suggestionsViewController = [[ContentSuggestionsViewController alloc] - initWithStyle:CollectionViewControllerStyleDefault]; + self.suggestionsViewController = + [[ContentSuggestionsCollectionViewController alloc] + initWithStyle:CollectionViewControllerStyleDefault]; self.suggestionsViewController.suggestionCommandHandler = self.ntpMediator; self.suggestionsViewController.audience = self; self.suggestionsViewController.contentSuggestionsEnabled =
diff --git a/ios/chrome/browser/ui/content_suggestions/content_suggestions_favicon_mediator.h b/ios/chrome/browser/ui/content_suggestions/content_suggestions_favicon_mediator.h index 17156642..61bdbc9f 100644 --- a/ios/chrome/browser/ui/content_suggestions/content_suggestions_favicon_mediator.h +++ b/ios/chrome/browser/ui/content_suggestions/content_suggestions_favicon_mediator.h
@@ -13,6 +13,7 @@ class LargeIconService; } +@protocol ContentSuggestionsCollectionConsumer; @protocol ContentSuggestionsConsumer; @class ContentSuggestionsMostVisitedItem; @class ContentSuggestionsParentItem; @@ -33,7 +34,7 @@ - (instancetype)init NS_UNAVAILABLE; // The consumer that will be notified when the data change. -@property(nonatomic, weak) id<ContentSuggestionsConsumer> consumer; +@property(nonatomic, weak) id<ContentSuggestionsCollectionConsumer> consumer; // FaviconAttributesProvider to fetch the favicon for the most visited tiles. @property(nonatomic, strong, readonly)
diff --git a/ios/chrome/browser/ui/content_suggestions/content_suggestions_favicon_mediator.mm b/ios/chrome/browser/ui/content_suggestions/content_suggestions_favicon_mediator.mm index 75f9b54..a051b9f 100644 --- a/ios/chrome/browser/ui/content_suggestions/content_suggestions_favicon_mediator.mm +++ b/ios/chrome/browser/ui/content_suggestions/content_suggestions_favicon_mediator.mm
@@ -9,7 +9,7 @@ #include "ios/chrome/browser/application_context.h" #import "ios/chrome/browser/ui/content_suggestions/cells/content_suggestions_most_visited_item.h" #import "ios/chrome/browser/ui/content_suggestions/cells/content_suggestions_parent_item.h" -#import "ios/chrome/browser/ui/content_suggestions/content_suggestions_consumer.h" +#import "ios/chrome/browser/ui/content_suggestions/content_suggestions_collection_consumer.h" #import "ios/chrome/browser/ui/content_suggestions/content_suggestions_feature.h" #import "ios/chrome/browser/ui/content_suggestions/identifier/content_suggestions_section_information.h" #import "ios/chrome/browser/ui/favicon/favicon_attributes_provider.h"
diff --git a/ios/chrome/browser/ui/content_suggestions/content_suggestions_header_synchronizer.h b/ios/chrome/browser/ui/content_suggestions/content_suggestions_header_synchronizer.h index fab929b..51c943d 100644 --- a/ios/chrome/browser/ui/content_suggestions/content_suggestions_header_synchronizer.h +++ b/ios/chrome/browser/ui/content_suggestions/content_suggestions_header_synchronizer.h
@@ -14,7 +14,6 @@ @protocol ContentSuggestionsCollectionControlling; @protocol ContentSuggestionsHeaderControlling; -@class ContentSuggestionsViewController; // Synchronizer for all the interactions between the HeaderController and the // CollectionView. It handles the interactions both ways.
diff --git a/ios/chrome/browser/ui/content_suggestions/content_suggestions_header_synchronizer.mm b/ios/chrome/browser/ui/content_suggestions/content_suggestions_header_synchronizer.mm index 8ef13e8..638dd4de 100644 --- a/ios/chrome/browser/ui/content_suggestions/content_suggestions_header_synchronizer.mm +++ b/ios/chrome/browser/ui/content_suggestions/content_suggestions_header_synchronizer.mm
@@ -10,8 +10,8 @@ #import "ios/chrome/browser/ui/content_suggestions/cells/content_suggestions_most_visited_cell.h" #import "ios/chrome/browser/ui/content_suggestions/content_suggestions_collection_controlling.h" #import "ios/chrome/browser/ui/content_suggestions/content_suggestions_collection_utils.h" +#import "ios/chrome/browser/ui/content_suggestions/content_suggestions_collection_view_controller.h" #import "ios/chrome/browser/ui/content_suggestions/content_suggestions_header_controlling.h" -#import "ios/chrome/browser/ui/content_suggestions/content_suggestions_view_controller.h" #import "ios/chrome/browser/ui/util/uikit_ui_util.h" #if !defined(__has_feature) || !__has_feature(objc_arc)
diff --git a/ios/chrome/browser/ui/content_suggestions/content_suggestions_mediator.h b/ios/chrome/browser/ui/content_suggestions/content_suggestions_mediator.h index 62aab6b5..b02f5be6 100644 --- a/ios/chrome/browser/ui/content_suggestions/content_suggestions_mediator.h +++ b/ios/chrome/browser/ui/content_suggestions/content_suggestions_mediator.h
@@ -10,7 +10,7 @@ #include <memory> #include "components/prefs/pref_service.h" -#import "ios/chrome/browser/ui/content_suggestions/content_suggestions_consumer.h" +#import "ios/chrome/browser/ui/content_suggestions/content_suggestions_collection_consumer.h" #import "ios/chrome/browser/ui/start_surface/start_surface_recent_tab_removal_observer_bridge.h" namespace favicon { @@ -26,7 +26,7 @@ } // namespace user_prefs @protocol ContentSuggestionsCommands; -@protocol ContentSuggestionsConsumer; +@protocol ContentSuggestionsCollectionConsumer; @protocol ContentSuggestionsGestureCommands; @protocol ContentSuggestionsHeaderProvider; @protocol DiscoverFeedDelegate; @@ -67,7 +67,7 @@ @property(nonatomic, weak) id<DiscoverFeedDelegate> discoverFeedDelegate; // The consumer that will be notified when the data change. -@property(nonatomic, weak) id<ContentSuggestionsConsumer> consumer; +@property(nonatomic, weak) id<ContentSuggestionsCollectionConsumer> consumer; // WebStateList associated with this mediator. @property(nonatomic, assign) WebStateList* webStateList;
diff --git a/ios/chrome/browser/ui/content_suggestions/content_suggestions_mediator.mm b/ios/chrome/browser/ui/content_suggestions/content_suggestions_mediator.mm index 0f4f7d42..59f0768 100644 --- a/ios/chrome/browser/ui/content_suggestions/content_suggestions_mediator.mm +++ b/ios/chrome/browser/ui/content_suggestions/content_suggestions_mediator.mm
@@ -228,7 +228,7 @@ return _notificationPromo.get(); } -- (void)setConsumer:(id<ContentSuggestionsConsumer>)consumer { +- (void)setConsumer:(id<ContentSuggestionsCollectionConsumer>)consumer { _consumer = consumer; self.faviconMediator.consumer = consumer; [self reloadAllData];
diff --git a/ios/chrome/browser/ui/content_suggestions/ntp_home_mediator.h b/ios/chrome/browser/ui/content_suggestions/ntp_home_mediator.h index 2bcdc0e..42daa347 100644 --- a/ios/chrome/browser/ui/content_suggestions/ntp_home_mediator.h +++ b/ios/chrome/browser/ui/content_suggestions/ntp_home_mediator.h
@@ -27,7 +27,7 @@ @protocol ContentSuggestionsCollectionControlling; @class ContentSuggestionsHeaderSynchronizer; @class ContentSuggestionsMediator; -@class ContentSuggestionsViewController; +@class ContentSuggestionsCollectionViewController; @protocol LogoVendor; @class NewTabPageViewController; @protocol NTPHomeConsumer; @@ -72,7 +72,7 @@ // TODO(crbug.com/1114792): Create a protocol to avoid duplication and update // comment. @property(nonatomic, weak) - ContentSuggestionsViewController* suggestionsViewController; + ContentSuggestionsCollectionViewController* suggestionsViewController; // View Controller forthe NTP if using the refactored NTP and the Feed is // visible. // TODO(crbug.com/1114792): Create a protocol to avoid duplication and update
diff --git a/ios/chrome/browser/ui/content_suggestions/ntp_home_mediator.mm b/ios/chrome/browser/ui/content_suggestions/ntp_home_mediator.mm index 222bff7..a7c2942c 100644 --- a/ios/chrome/browser/ui/content_suggestions/ntp_home_mediator.mm +++ b/ios/chrome/browser/ui/content_suggestions/ntp_home_mediator.mm
@@ -36,10 +36,10 @@ #import "ios/chrome/browser/ui/content_suggestions/cells/content_suggestions_most_visited_item.h" #import "ios/chrome/browser/ui/content_suggestions/cells/content_suggestions_return_to_recent_tab_item.h" #import "ios/chrome/browser/ui/content_suggestions/content_suggestions_collection_utils.h" +#import "ios/chrome/browser/ui/content_suggestions/content_suggestions_collection_view_controller.h" #import "ios/chrome/browser/ui/content_suggestions/content_suggestions_feature.h" #import "ios/chrome/browser/ui/content_suggestions/content_suggestions_header_synchronizer.h" #import "ios/chrome/browser/ui/content_suggestions/content_suggestions_mediator.h" -#import "ios/chrome/browser/ui/content_suggestions/content_suggestions_view_controller.h" #import "ios/chrome/browser/ui/content_suggestions/content_suggestions_view_controller_audience.h" #import "ios/chrome/browser/ui/content_suggestions/ntp_home_consumer.h" #import "ios/chrome/browser/ui/content_suggestions/ntp_home_metrics.h"
diff --git a/ios/chrome/browser/ui/content_suggestions/ntp_home_mediator_unittest.mm b/ios/chrome/browser/ui/content_suggestions/ntp_home_mediator_unittest.mm index 1033549..f1b3c988 100644 --- a/ios/chrome/browser/ui/content_suggestions/ntp_home_mediator_unittest.mm +++ b/ios/chrome/browser/ui/content_suggestions/ntp_home_mediator_unittest.mm
@@ -22,7 +22,7 @@ #import "ios/chrome/browser/ui/commands/browser_commands.h" #import "ios/chrome/browser/ui/commands/snackbar_commands.h" #import "ios/chrome/browser/ui/content_suggestions/cells/content_suggestions_most_visited_item.h" -#import "ios/chrome/browser/ui/content_suggestions/content_suggestions_view_controller.h" +#import "ios/chrome/browser/ui/content_suggestions/content_suggestions_collection_view_controller.h" #import "ios/chrome/browser/ui/content_suggestions/ntp_home_consumer.h" #import "ios/chrome/browser/ui/ntp/logo_vendor.h" #import "ios/chrome/browser/ui/toolbar/test/toolbar_test_navigation_manager.h" @@ -68,7 +68,7 @@ logo_vendor_ = OCMProtocolMock(@protocol(LogoVendor)); dispatcher_ = OCMProtocolMock(@protocol(NTPHomeMediatorDispatcher)); suggestions_view_controller_ = - OCMClassMock([ContentSuggestionsViewController class]); + OCMClassMock([ContentSuggestionsCollectionViewController class]); voice_availability_.SetVoiceProviderEnabled(true); UrlLoadingNotifierBrowserAgent::CreateForBrowser(browser_.get());
diff --git a/ios/chrome/browser/ui/content_suggestions/ntp_home_test_utils.mm b/ios/chrome/browser/ui/content_suggestions/ntp_home_test_utils.mm index ae90e542..aa8e0309 100644 --- a/ios/chrome/browser/ui/content_suggestions/ntp_home_test_utils.mm +++ b/ios/chrome/browser/ui/content_suggestions/ntp_home_test_utils.mm
@@ -11,8 +11,8 @@ #include "base/strings/utf_string_conversions.h" #include "components/ntp_snippets/content_suggestion.h" #include "components/ntp_snippets/status.h" +#import "ios/chrome/browser/ui/content_suggestions/content_suggestions_collection_view_controller.h" #import "ios/chrome/browser/ui/content_suggestions/content_suggestions_constants.h" -#import "ios/chrome/browser/ui/content_suggestions/content_suggestions_view_controller.h" #import "ios/chrome/browser/ui/content_suggestions/ntp_home_constant.h" #import "ios/chrome/browser/ui/ntp/new_tab_page_constants.h" #import "ios/testing/earl_grey/earl_grey_app.h"
diff --git a/ios/chrome/browser/ui/ntp/OWNERS b/ios/chrome/browser/ui/ntp/OWNERS index 8cd2a888..d32ce6c 100644 --- a/ios/chrome/browser/ui/ntp/OWNERS +++ b/ios/chrome/browser/ui/ntp/OWNERS
@@ -2,4 +2,5 @@ justincohen@chromium.org gambard@chromium.org sczs@chromium.org -adamta@google.com \ No newline at end of file +adamta@google.com +thegreenfrog@chromium.org \ No newline at end of file
diff --git a/ios/chrome/browser/ui/ntp/new_tab_page_coordinator_unittest.mm b/ios/chrome/browser/ui/ntp/new_tab_page_coordinator_unittest.mm index 8077536..5ef99ad 100644 --- a/ios/chrome/browser/ui/ntp/new_tab_page_coordinator_unittest.mm +++ b/ios/chrome/browser/ui/ntp/new_tab_page_coordinator_unittest.mm
@@ -16,7 +16,7 @@ #import "ios/chrome/browser/ui/commands/command_dispatcher.h" #import "ios/chrome/browser/ui/commands/omnibox_commands.h" #import "ios/chrome/browser/ui/commands/snackbar_commands.h" -#import "ios/chrome/browser/ui/content_suggestions/content_suggestions_view_controller.h" +#import "ios/chrome/browser/ui/content_suggestions/content_suggestions_collection_view_controller.h" #import "ios/chrome/browser/ui/main/scene_state.h" #import "ios/chrome/browser/ui/main/scene_state_browser_agent.h" #import "ios/chrome/browser/ui/ntp/incognito_view_controller.h"
diff --git a/ios/chrome/browser/ui/ntp/new_tab_page_view_controller.h b/ios/chrome/browser/ui/ntp/new_tab_page_view_controller.h index 0761251..d405c68 100644 --- a/ios/chrome/browser/ui/ntp/new_tab_page_view_controller.h +++ b/ios/chrome/browser/ui/ntp/new_tab_page_view_controller.h
@@ -12,7 +12,6 @@ @class BubblePresenter; @class ContentSuggestionsHeaderViewController; -@class ContentSuggestionsViewController; @class FeedMetricsRecorder; @class DiscoverFeedWrapperViewController; @class FeedHeaderViewController;
diff --git a/ios/chrome/browser/ui/overlays/overlay_presentation_context_fullscreen_disabler_unittest.mm b/ios/chrome/browser/ui/overlays/overlay_presentation_context_fullscreen_disabler_unittest.mm index 7e5dbd2..8d17550 100644 --- a/ios/chrome/browser/ui/overlays/overlay_presentation_context_fullscreen_disabler_unittest.mm +++ b/ios/chrome/browser/ui/overlays/overlay_presentation_context_fullscreen_disabler_unittest.mm
@@ -47,10 +47,9 @@ web_view_ = [[WKWebView alloc] initWithFrame:scoped_window_.Get().bounds configuration:[[WKWebViewConfiguration alloc] init]]; - content_view_ = [[CRWWebViewContentView alloc] - initWithWebView:web_view_ - scrollView:web_view_.scrollView - fullscreenState:CrFullscreenState::kNotInFullScreen]; + content_view_ = + [[CRWWebViewContentView alloc] initWithWebView:web_view_ + scrollView:web_view_.scrollView]; // Set up the fake presentation context so OverlayPresenterObserver // callbacks are sent. overlay_presenter()->SetPresentationContext(&presentation_context_);
diff --git a/ios/chrome/browser/ui/settings/password/passwords_table_view_controller.mm b/ios/chrome/browser/ui/settings/password/passwords_table_view_controller.mm index ac08c63..47a33953 100644 --- a/ios/chrome/browser/ui/settings/password/passwords_table_view_controller.mm +++ b/ios/chrome/browser/ui/settings/password/passwords_table_view_controller.mm
@@ -349,6 +349,9 @@ @property(nonatomic, assign) OnDeviceEncryptionState onDeviceEncryptionStateInModel; +// Return YES if the search bar should be enabled. +@property(nonatomic, assign) BOOL shouldEnableSearchBar; + @end @implementation PasswordsTableViewController @@ -389,6 +392,9 @@ prefName:password_manager::prefs::kCredentialsEnableService]; [_passwordManagerEnabled setObserver:self]; + // Default behavior: search bar is enabled. + self.shouldEnableSearchBar = YES; + [self updateUIForEditState]; [self updateExportPasswordsButton]; } @@ -516,19 +522,18 @@ } } -- (void)setTableViewEditing:(BOOL)editing animated:(BOOL)animated { +- (void)setEditing:(BOOL)editing animated:(BOOL)animated { [super setEditing:editing animated:animated]; if (editing) { [self setSavePasswordsSwitchItemEnabled:NO]; [self setExportPasswordsButtonEnabled:NO]; - [self setSearchBarEnabled:NO]; } else { [self setSavePasswordsSwitchItemEnabled:YES]; if (_exportReady) { [self setExportPasswordsButtonEnabled:YES]; } - [self setSearchBarEnabled:YES]; } + [self setSearchBarEnabled:self.shouldEnableSearchBar]; [self updatePasswordCheckButtonWithState:self.passwordCheckState]; [self updatePasswordCheckStatusLabelWithState:self.passwordCheckState]; if (_checkForProblemsItem) { @@ -774,10 +779,11 @@ } - (void)editButtonPressed { - // No need to call super here because it is done in -setTableViewEditing - // already. Only consider the state to be editing when the Edit button is - // pressed (not when the user swiped to delete a password). - [self setTableViewEditing:!self.tableView.editing animated:YES]; + // Disable search bar if the user is bulk editing (edit mode). (Reverse logic + // because parent method -editButtonPressed is calling setEditing to change + // the state). + self.shouldEnableSearchBar = self.tableView.editing; + [super editButtonPressed]; } #pragma mark - SettingsControllerProtocol @@ -1224,7 +1230,7 @@ withRowAnimation:UITableViewRowAnimationAutomatic]; [self scrollToLastUpdatedItem]; } else if (_savedForms.empty() && _blockedForms.empty()) { - [self setTableViewEditing:NO animated:YES]; + [self setEditing:NO animated:YES]; } } } @@ -1824,7 +1830,7 @@ // If both lists are empty, exit editing mode. if (strongSelf->_savedForms.empty() && strongSelf->_blockedForms.empty()) - [strongSelf setTableViewEditing:NO animated:YES]; + [strongSelf setEditing:NO animated:YES]; [strongSelf updateUIForEditState]; [strongSelf updateExportPasswordsButton]; }];
diff --git a/ios/chrome/browser/ui/settings/password/passwords_table_view_controller_unittest.mm b/ios/chrome/browser/ui/settings/password/passwords_table_view_controller_unittest.mm index a3ec44d..b02f83d 100644 --- a/ios/chrome/browser/ui/settings/password/passwords_table_view_controller_unittest.mm +++ b/ios/chrome/browser/ui/settings/password/passwords_table_view_controller_unittest.mm
@@ -62,7 +62,6 @@ UISearchBarDelegate, PasswordsConsumer> - (void)updateExportPasswordsButton; -- (void)setTableViewEditing:(BOOL)editing animated:(BOOL)animated; @end namespace { @@ -278,7 +277,7 @@ void SetEditing(bool editing) { PasswordsTableViewController* passwords_controller = static_cast<PasswordsTableViewController*>(controller()); - [passwords_controller setTableViewEditing:editing animated:NO]; + [passwords_controller setEditing:editing animated:NO]; } void RunUntilIdle() { task_environment_.RunUntilIdle(); } @@ -512,7 +511,7 @@ CheckTextCellTextWithId(IDS_IOS_EXPORT_PASSWORDS, GetSectionIndex(ExportPasswordsButton), 0); - [passwords_controller setTableViewEditing:YES animated:NO]; + [passwords_controller setEditing:YES animated:NO]; EXPECT_NSEQ([UIColor colorNamed:kTextSecondaryColor], exportButton.textColor); EXPECT_TRUE(exportButton.accessibilityTraits & @@ -533,8 +532,8 @@ CheckTextCellTextWithId(IDS_IOS_EXPORT_PASSWORDS, GetSectionIndex(ExportPasswordsButton), 0); - [passwords_controller setTableViewEditing:YES animated:NO]; - [passwords_controller setTableViewEditing:NO animated:NO]; + [passwords_controller setEditing:YES animated:NO]; + [passwords_controller setEditing:NO animated:NO]; EXPECT_NSEQ([UIColor colorNamed:kBlueColor], exportButton.textColor); EXPECT_FALSE(exportButton.accessibilityTraits & @@ -553,14 +552,14 @@ CheckTextCellTextWithId(IDS_IOS_CHECK_PASSWORDS_NOW_BUTTON, GetSectionIndex(PasswordCheck), 1); - [passwords_controller setTableViewEditing:YES animated:NO]; + [passwords_controller setEditing:YES animated:NO]; EXPECT_NSEQ([UIColor colorNamed:kTextSecondaryColor], checkPasswordButton.textColor); EXPECT_TRUE(checkPasswordButton.accessibilityTraits & UIAccessibilityTraitNotEnabled); - [passwords_controller setTableViewEditing:NO animated:NO]; + [passwords_controller setEditing:NO animated:NO]; EXPECT_NSEQ([UIColor colorNamed:kBlueColor], checkPasswordButton.textColor); EXPECT_FALSE(checkPasswordButton.accessibilityTraits & UIAccessibilityTraitNotEnabled);
diff --git a/ios/chrome/browser/ui/side_swipe/side_swipe_controller_unittest.mm b/ios/chrome/browser/ui/side_swipe/side_swipe_controller_unittest.mm index 10bb87c8..fe16931 100644 --- a/ios/chrome/browser/ui/side_swipe/side_swipe_controller_unittest.mm +++ b/ios/chrome/browser/ui/side_swipe/side_swipe_controller_unittest.mm
@@ -46,8 +46,7 @@ configuration:[[WKWebViewConfiguration alloc] init]]), content_view_([[CRWWebViewContentView alloc] initWithWebView:web_view_ - scrollView:web_view_.scrollView - fullscreenState:CrFullscreenState::kNotInFullScreen]) { + scrollView:web_view_.scrollView]) { auto original_web_state(std::make_unique<web::FakeWebState>()); original_web_state->SetView(content_view_); CRWWebViewScrollViewProxy* scroll_view_proxy =
diff --git a/ios/chrome/test/earl_grey/chrome_matchers_app_interface.mm b/ios/chrome/test/earl_grey/chrome_matchers_app_interface.mm index fbb6e30a..330e3f6 100644 --- a/ios/chrome/test/earl_grey/chrome_matchers_app_interface.mm +++ b/ios/chrome/test/earl_grey/chrome_matchers_app_interface.mm
@@ -21,8 +21,8 @@ #import "ios/chrome/browser/ui/autofill/manual_fill/manual_fill_password_mediator.h" #import "ios/chrome/browser/ui/autofill/manual_fill/password_view_controller.h" #import "ios/chrome/browser/ui/bookmarks/bookmark_ui_constants.h" +#import "ios/chrome/browser/ui/content_suggestions/content_suggestions_collection_view_controller.h" #import "ios/chrome/browser/ui/content_suggestions/content_suggestions_constants.h" -#import "ios/chrome/browser/ui/content_suggestions/content_suggestions_view_controller.h" #import "ios/chrome/browser/ui/content_suggestions/ntp_home_constant.h" #import "ios/chrome/browser/ui/history/history_ui_constants.h" #import "ios/chrome/browser/ui/location_bar/location_bar_constants.h"
diff --git a/ios/testing/BUILD.gn b/ios/testing/BUILD.gn index 52d6d17..cc728e43 100644 --- a/ios/testing/BUILD.gn +++ b/ios/testing/BUILD.gn
@@ -131,9 +131,6 @@ "data/http_server_files/onload_replacestate_reload.html", "data/http_server_files/onload_replacestate_reload.js", "data/http_server_files/opensearch.xml", - "data/http_server_files/permissions/camera_and_microphone.html", - "data/http_server_files/permissions/camera_only.html", - "data/http_server_files/permissions/microphone_only.html", "data/http_server_files/pony.html", "data/http_server_files/profile_form.html", "data/http_server_files/readonly_form.html",
diff --git a/ios/testing/data/http_server_files/permissions/camera_and_microphone.html b/ios/testing/data/http_server_files/permissions/camera_and_microphone.html deleted file mode 100644 index 08a0084..0000000 --- a/ios/testing/data/http_server_files/permissions/camera_and_microphone.html +++ /dev/null
@@ -1,48 +0,0 @@ -<!DOCTYPE html> - -<!-- Copyright 2022 The Chromium Authors. All rights reserved. -Use of this source code is governed by a BSD-style license that can be -found in the LICENSE file. --> - -<html> -<head> - <meta charset="utf-8"> - <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> - <meta name="viewport" content="width=device-width"> - <title>Requesting Camera and Microphone Permissions</title> -</head> - -<body> - <div id="container"> - <video autoplay="true" id="videoElement" width="480px" height="270px" muted> - </video> - <p>Current volume: <span id="volume">0</span></p> - </div> - <script type="text/javascript"> - const video = document.querySelector("#videoElement"); - const audio = document.querySelector("#volume"); - navigator.mediaDevices.getUserMedia({ audio: true, video: true }) - .then(function(stream) { - // Video. - video.srcObject = stream; - - // Audio. - const audioCtx = new AudioContext(); - const source = audioCtx.createMediaStreamSource(stream); - - const analyser = audioCtx.createAnalyser(); - analyser.fftSize = 64; - const bufferLength = analyser.frequencyBinCount; - let dataArray = new Uint8Array(bufferLength); - - // Connect the source to be analysed. - source.connect(analyser); - setInterval(function () { - analyser.getByteFrequencyData(dataArray); - let averageVolume = dataArray.reduce((a, b) => a + b) / bufferLength; - audio.innerHTML = averageVolume; - }, 500); - }); -</script> -</body> -</html>
diff --git a/ios/testing/data/http_server_files/permissions/camera_only.html b/ios/testing/data/http_server_files/permissions/camera_only.html deleted file mode 100644 index 362ed96..0000000 --- a/ios/testing/data/http_server_files/permissions/camera_only.html +++ /dev/null
@@ -1,28 +0,0 @@ -<!DOCTYPE html> - -<!-- Copyright 2022 The Chromium Authors. All rights reserved. -Use of this source code is governed by a BSD-style license that can be -found in the LICENSE file. --> - -<html> -<head> - <meta charset="utf-8"> - <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> - <meta name="viewport" content="width=device-width"> - <title>Requesting Camera Permissions</title> -</head> - -<body> - <div id="container"> - <video autoplay="true" id="videoElement" width="480px" height="270px"> - </video> - </div> - <script type="text/javascript"> - var video = document.querySelector("#videoElement"); - navigator.mediaDevices.getUserMedia({ video: true }) - .then(function(stream) { - video.srcObject = stream; - }); -</script> -</body> -</html>
diff --git a/ios/testing/data/http_server_files/permissions/microphone_only.html b/ios/testing/data/http_server_files/permissions/microphone_only.html deleted file mode 100644 index 31b0ed0..0000000 --- a/ios/testing/data/http_server_files/permissions/microphone_only.html +++ /dev/null
@@ -1,40 +0,0 @@ -<!DOCTYPE html> - -<!-- Copyright 2022 The Chromium Authors. All rights reserved. -Use of this source code is governed by a BSD-style license that can be -found in the LICENSE file. --> - -<html> -<head> - <meta charset="utf-8"> - <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> - <meta name="viewport" content="width=device-width"> - - <title>Requesting Microphone Permissions</title> -</head> - -<body> - <p>Current volume: <span id="volume">0</span></p> - <script type="text/javascript"> - const volumeNode = document.getElementById("volume"); - navigator.mediaDevices.getUserMedia({ audio: true }).then( - function(stream) { - const audioCtx = new AudioContext(); - const source = audioCtx.createMediaStreamSource(stream); - - const analyser = audioCtx.createAnalyser(); - analyser.fftSize = 64; - const bufferLength = analyser.frequencyBinCount; - let dataArray = new Uint8Array(bufferLength); - - // Connect the source to be analysed. - source.connect(analyser); - setInterval(function () { - analyser.getByteFrequencyData(dataArray); - let averageVolume = dataArray.reduce((a, b) => a + b) / bufferLength; - volumeNode.innerHTML = averageVolume; - }, 500); - }); -</script> -</body> -</html>
diff --git a/ios/web/BUILD.gn b/ios/web/BUILD.gn index 3b279608..a3ae1c7 100644 --- a/ios/web/BUILD.gn +++ b/ios/web/BUILD.gn
@@ -579,7 +579,6 @@ "//ios/web/navigation:wk_navigation_util", "//ios/web/public/find_in_page", "//ios/web/public/js_messaging", - "//ios/web/public/permissions", "//ios/web/public/security", "//ios/web/public/session", "//ios/web/public/test", @@ -620,7 +619,6 @@ "web_state/error_page_inttest.mm", "web_state/http_auth_inttest.mm", "web_state/keep_render_process_alive_inttest.mm", - "web_state/permissions_inttest.mm", "web_state/ui/crw_context_menu_element_fetcher_inttest.mm", "web_state/web_state_observer_inttest.mm", "webui/web_ui_inttest.mm",
diff --git a/ios/web/common/crw_content_view.h b/ios/web/common/crw_content_view.h index 8ace43e..69a90a7 100644 --- a/ios/web/common/crw_content_view.h +++ b/ios/web/common/crw_content_view.h
@@ -7,17 +7,6 @@ #import <UIKit/UIKit.h> -// For devices running on a version >= iOS 15.4, WKFullScreenState is converted -// into CrFullscreenState. Once min version supported is iOS 15.4, -// uses of this enum should be be replaced with WKFullScreenState and this enum -// declaration should be removed. -enum class CrFullscreenState { - kEnteringFullscreen, - kExitingFullscreen, - kInFullscreen, - kNotInFullScreen, -}; - // UIViews conforming to CRWScrollableContent (i.e. CRWContentViews) are used // to display content within a WebState. @protocol CRWScrollableContent <NSObject>
diff --git a/ios/web/common/crw_web_view_content_view.h b/ios/web/common/crw_web_view_content_view.h index d488361c..8b248b9 100644 --- a/ios/web/common/crw_web_view_content_view.h +++ b/ios/web/common/crw_web_view_content_view.h
@@ -16,15 +16,26 @@ // The webView passed to |-initWithWebView|. @property(nonatomic, strong, readonly) UIView* webView; +#if defined(__IPHONE_15_4) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_15_4 // The fullscreen state of this view -@property(nonatomic, readonly) CrFullscreenState fullscreenState; +@property(nonatomic, readonly) + WKFullscreenState fullscreenState API_AVAILABLE(ios(15)); // Initializes the CRWWebViewContentView to display |webView| and passes state -// of fullscreen mode. This should pass in a default value of -// CrFullscreenState (e.g., kNotInFullScreen). +// of fullscreen mode. This should become the default constructor when we +// start building with the 15.4 SDK and pass in a default value of +// WKFullscreenState (e.g., WKFullscreenStateNotInFullscreen). Additionally, +// code in initWithWebView:scrollView should be moved into this constructor at +// that time. - (instancetype)initWithWebView:(UIView*)webView scrollView:(UIScrollView*)scrollView - fullscreenState:(CrFullscreenState)fullscreenState + fullscreenState:(WKFullscreenState)fullscreenState + API_AVAILABLE(ios(15)); +#endif // defined(__IPHONE_15_4) + +// Initializes the CRWWebViewContentView to display |webView|. +- (instancetype)initWithWebView:(UIView*)webView + scrollView:(UIScrollView*)scrollView NS_DESIGNATED_INITIALIZER; // Available only for testing. @@ -35,7 +46,10 @@ - (instancetype)initWithCoder:(NSCoder*)decoder NS_UNAVAILABLE; - (instancetype)initWithFrame:(CGRect)frame NS_UNAVAILABLE; -- (void)updateFullscreenState:(CrFullscreenState)fullscreenState; +#if defined(__IPHONE_15_4) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_15_4 +- (void)updateFullscreenState:(WKFullscreenState)fullscreenState + API_AVAILABLE(ios(15)); +#endif // defined(__IPHONE_15_4) @end
diff --git a/ios/web/common/crw_web_view_content_view.mm b/ios/web/common/crw_web_view_content_view.mm index 14079a1..a5eb3293 100644 --- a/ios/web/common/crw_web_view_content_view.mm +++ b/ios/web/common/crw_web_view_content_view.mm
@@ -34,11 +34,13 @@ @synthesize viewportEdgesAffectedBySafeArea = _viewportEdgesAffectedBySafeArea; @synthesize viewportInsets = _viewportInsets; @synthesize webView = _webView; + +#if defined(__IPHONE_15_4) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_15_4 @synthesize fullscreenState = _fullscreenState; +#endif // defined(__IPHONE_15_4) - (instancetype)initWithWebView:(UIView*)webView - scrollView:(UIScrollView*)scrollView - fullscreenState:(CrFullscreenState)fullscreenState { + scrollView:(UIScrollView*)scrollView { self = [super initWithFrame:CGRectZero]; if (self) { DCHECK(webView); @@ -46,10 +48,21 @@ DCHECK([scrollView isDescendantOfView:webView]); _webView = webView; _scrollView = scrollView; + } + return self; +} + +#if defined(__IPHONE_15_4) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_15_4 +- (instancetype)initWithWebView:(UIView*)webView + scrollView:(UIScrollView*)scrollView + fullscreenState:(WKFullscreenState)fullscreenState { + self = [self initWithWebView:webView scrollView:scrollView]; + if (self) { _fullscreenState = fullscreenState; } return self; } +#endif // defined(__IPHONE_15_4) - (instancetype)initForTesting { return [super initWithFrame:CGRectZero]; @@ -82,9 +95,11 @@ return [_webView becomeFirstResponder]; } -- (void)updateFullscreenState:(CrFullscreenState)fullscreenState { +#if defined(__IPHONE_15_4) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_15_4 +- (void)updateFullscreenState:(WKFullscreenState)fullscreenState { _fullscreenState = fullscreenState; } +#endif // defined(__IPHONE_15_4) #pragma mark Layout
diff --git a/ios/web/web_state/permissions_inttest.mm b/ios/web/web_state/permissions_inttest.mm deleted file mode 100644 index 6d59dfe..0000000 --- a/ios/web/web_state/permissions_inttest.mm +++ /dev/null
@@ -1,287 +0,0 @@ -// Copyright 2022 The Chromium 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 "base/test/ios/wait_util.h" -#include "base/test/scoped_feature_list.h" -#include "ios/testing/scoped_block_swizzler.h" -#include "ios/web/common/features.h" -#import "ios/web/public/permissions/permissions.h" -#import "ios/web/public/test/navigation_test_util.h" -#import "ios/web/public/web_state.h" -#include "ios/web/public/web_state_observer.h" -#import "ios/web/test/web_test_with_web_controller.h" -#import "ios/web/web_state/ui/crw_web_controller.h" -#import "ios/web/web_state/ui/crw_wk_ui_handler.h" -#import "ios/web/web_state/ui/crw_wk_ui_handler_delegate.h" -#include "net/test/embedded_test_server/embedded_test_server.h" -#include "testing/gmock/include/gmock/gmock.h" -#include "testing/gtest/include/gtest/gtest.h" -#include "testing/gtest_mac.h" - -#if !defined(__has_feature) || !__has_feature(objc_arc) -#error "This file requires ARC support." -#endif - -using base::test::ios::kWaitForPageLoadTimeout; - -namespace { - -// This is the timeout used to wait for the WKUIDelegate's decision handler -// block of the to respond to permissions requests. The web state's permission -// states would only update after the decision handler blocks responds, so all -// checks should be ran after this timeout. -const CGFloat kWebViewDecisionHandlingTimeout = 0.1; - -// Mocks WebStateObserver callbacks. -class WebStateObserverMock : public web::WebStateObserver { - public: - WebStateObserverMock() = default; - - WebStateObserverMock(const WebStateObserverMock&) = delete; - WebStateObserverMock& operator=(const WebStateObserverMock&) = delete; - - MOCK_METHOD2(PermissionStateChanged, void(web::WebState*, web::Permission)); - void WebStateDestroyed(web::WebState* web_state) override { NOTREACHED(); } -}; - -// Verifies that the current permission states matches expected. -ACTION_P3(VerifyPermissionState, web_state, permission, permission_state) { - EXPECT_EQ(web_state, arg0); - EXPECT_EQ(web_state->GetStateForPermission(permission), permission_state); -} - -} // namespace - -// Fake WKUIDelegate for WKWebView to override media permissions. -API_AVAILABLE(ios(15.0)) -@interface FakeCRWWKUIHandler : CRWWKUIHandler - -@property(nonatomic, assign) WKPermissionDecision decision; -@property(nonatomic, assign) BOOL decisionMade; - -@end - -@implementation FakeCRWWKUIHandler - -// Method for WKUIDelegate to allow media permissions when requested. -- (void)webView:(WKWebView*)webView - requestMediaCapturePermissionForOrigin:(WKSecurityOrigin*)origin - initiatedByFrame:(WKFrameInfo*)frame - type:(WKMediaCaptureType)type - decisionHandler: - (void (^)(WKPermissionDecision decision)) - decisionHandler { - decisionHandler(self.decision); - // Adds timeout to make sure self.decisionMade is set after the decision - // handler completes. - dispatch_after(dispatch_time(DISPATCH_TIME_NOW, - kWebViewDecisionHandlingTimeout * NSEC_PER_SEC), - dispatch_get_main_queue(), ^{ - self.decisionMade = YES; - }); -} - -@end - -namespace web { - -// Tests fixture to test permissions handling for web state and its observer. -class PermissionsInttest : public WebTestWithWebController { - public: - void SetUp() override { - WebTestWithWebState::SetUp(); - if (@available(iOS 15.0, *)) { - // Turn on media permissions feature. - scoped_feature_list_.InitWithFeatures( - {features::kMediaPermissionsControl}, {}); - - // Switch actual objects to fakes/mocks for testing purposes. - handler_ = [[FakeCRWWKUIHandler alloc] init]; - handler_.delegate = (id<CRWWKUIHandlerDelegate>)web_controller(); - swizzler_ = std::make_unique<ScopedBlockSwizzler>( - [CRWWebController class], NSSelectorFromString(@"UIHandler"), ^{ - return handler_; - }); - - web_state()->AddObserver(&observer_); - - // Set up test server. - test_server_ = std::make_unique<net::EmbeddedTestServer>(); - test_server_->ServeFilesFromSourceDirectory( - base::FilePath("ios/testing/data/http_server_files/permissions")); - ASSERT_TRUE(test_server_->Start()); - } - } - - void TearDown() override { - web_state()->RemoveObserver(&observer_); - WebTestWithWebState::TearDown(); - } - - protected: - base::test::ScopedFeatureList scoped_feature_list_; - std::unique_ptr<ScopedBlockSwizzler> swizzler_; - std::unique_ptr<net::EmbeddedTestServer> test_server_; - testing::NiceMock<WebStateObserverMock> observer_; - FakeCRWWKUIHandler* handler_ API_AVAILABLE(ios(15.0)); -}; - -using base::test::ios::WaitUntilConditionOrTimeout; - -// Tests that web state observer gets invoked for camera only when the website -// only requests for camera permissions and changed via web_state() setter -// API afterwards. -TEST_F(PermissionsInttest, - TestsThatPermissionStateChangedObserverInvokedForCameraOnly) { - if (@available(iOS 15.0, *)) { - EXPECT_CALL(observer_, - PermissionStateChanged(web_state(), PermissionCamera)) - .Times(testing::Exactly(2)) - .WillOnce(VerifyPermissionState(web_state(), PermissionCamera, - PermissionStateAllowed)); - EXPECT_CALL(observer_, - PermissionStateChanged(web_state(), PermissionMicrophone)) - .Times(0); - - // Initial load. - handler_.decision = WKPermissionDecisionGrant; - test::LoadUrl(web_state(), test_server_->GetURL("/camera_only.html")); - EXPECT_TRUE(WaitUntilConditionOrTimeout(kWaitForPageLoadTimeout, ^bool { - return handler_.decisionMade; - })); - - // Update permission through web state API. - web_state()->SetStateForPermission(PermissionStateBlocked, - PermissionCamera); - EXPECT_TRUE(WaitUntilConditionOrTimeout(kWaitForPageLoadTimeout, ^bool { - return web_state()->GetStateForPermission(PermissionCamera) == - PermissionStateBlocked; - })); - } -} - -// Tests that web state observer gets invoked for microphone only when the -// website only requests for microphone permissions and changed via web_state() -// setter API afterwards. -TEST_F(PermissionsInttest, - TestsThatPermissionStateChangedObserverInvokedForMicrophoneOnly) { - if (@available(iOS 15.0, *)) { - EXPECT_CALL(observer_, - PermissionStateChanged(web_state(), PermissionCamera)) - .Times(0); - EXPECT_CALL(observer_, - PermissionStateChanged(web_state(), PermissionMicrophone)) - .Times(testing::Exactly(2)) - .WillOnce(VerifyPermissionState(web_state(), PermissionMicrophone, - PermissionStateAllowed)); - - // Initial load. - handler_.decision = WKPermissionDecisionGrant; - test::LoadUrl(web_state(), test_server_->GetURL("/microphone_only.html")); - EXPECT_TRUE(WaitUntilConditionOrTimeout(kWaitForPageLoadTimeout, ^bool { - return handler_.decisionMade; - })); - - // Update permission through web state API. - web_state()->SetStateForPermission(PermissionStateNotAccessible, - PermissionMicrophone); - EXPECT_TRUE(WaitUntilConditionOrTimeout(kWaitForPageLoadTimeout, ^bool { - return web_state()->GetStateForPermission(PermissionMicrophone) == - PermissionStateNotAccessible; - })); - } -} - -// Tests that web state observer gets invoked for both camera and microphone, -// when both are requested by the web page and set via web_state() afterwards. -TEST_F(PermissionsInttest, - TestsThatPermissionStateChangedObserverInvokedForCameraAndMicrophone) { - if (@available(iOS 15.0, *)) { - EXPECT_CALL(observer_, - PermissionStateChanged(web_state(), PermissionCamera)) - .Times(testing::Exactly(2)) - .WillOnce(VerifyPermissionState(web_state(), PermissionCamera, - PermissionStateAllowed)); - EXPECT_CALL(observer_, - PermissionStateChanged(web_state(), PermissionMicrophone)) - .Times(testing::Exactly(1)) - .WillOnce(VerifyPermissionState(web_state(), PermissionMicrophone, - PermissionStateAllowed)); - - // Initial load. - handler_.decision = WKPermissionDecisionGrant; - test::LoadUrl(web_state(), - test_server_->GetURL("/camera_and_microphone.html")); - EXPECT_TRUE(WaitUntilConditionOrTimeout(kWaitForPageLoadTimeout, ^bool { - return handler_.decisionMade; - })); - - // Only block one of them (camera in this case). - web_state()->SetStateForPermission(PermissionStateBlocked, - PermissionCamera); - EXPECT_TRUE(WaitUntilConditionOrTimeout(kWaitForPageLoadTimeout, ^bool { - return web_state()->GetStateForPermission(PermissionCamera) == - PermissionStateBlocked; - })); - EXPECT_EQ(web_state()->GetStateForPermission(PermissionMicrophone), - PermissionStateAllowed); - } -} - -// Tests that web state observer should not be invoked when permission is -// denied. -TEST_F(PermissionsInttest, - TestsThatPermissionStateChangedObserverNotInvokedWhenPermissionDenied) { - if (@available(iOS 15.0, *)) { - EXPECT_CALL(observer_, - PermissionStateChanged(web_state(), PermissionCamera)) - .Times(0); - - handler_.decision = WKPermissionDecisionDeny; - test::LoadUrl(web_state(), test_server_->GetURL("/camera_only.html")); - EXPECT_TRUE(WaitUntilConditionOrTimeout(kWaitForPageLoadTimeout, ^bool { - return handler_.decisionMade; - })); - EXPECT_EQ([web_controller() ensureWebViewCreated].cameraCaptureState, - WKMediaCaptureStateNone); - } -} - -// Tests that permission could not be manually altered if it has never been -// granted by WKUIDelegate in the first place. -TEST_F(PermissionsInttest, - TestsThatWebStateShouldNotAlterPermissionIfNotAccessible) { - if (@available(iOS 15.0, *)) { - handler_.decision = WKPermissionDecisionDeny; - test::LoadUrl(web_state(), test_server_->GetURL("/camera_only.html")); - EXPECT_TRUE(WaitUntilConditionOrTimeout(kWaitForPageLoadTimeout, ^bool { - return handler_.decisionMade; - })); - web_state()->SetStateForPermission(PermissionStateAllowed, - PermissionCamera); - web_state()->SetStateForPermission(PermissionStateBlocked, - PermissionMicrophone); - // Neither permission should be changed. - EXPECT_FALSE(WaitUntilConditionOrTimeout(kWaitForPageLoadTimeout, ^bool { - // Camera permission asked but denied. - BOOL cameraPermissionChanged = - web_state()->GetStateForPermission(PermissionCamera) != - PermissionStateNotAccessible; - // Microphone permission never asked. - BOOL microphonePermissionChanged = - web_state()->GetStateForPermission(PermissionMicrophone) != - PermissionStateNotAccessible; - - return cameraPermissionChanged || microphonePermissionChanged; - })); - EXPECT_EQ([web_controller() ensureWebViewCreated].cameraCaptureState, - WKMediaCaptureStateNone); - EXPECT_EQ([web_controller() ensureWebViewCreated].microphoneCaptureState, - WKMediaCaptureStateNone); - } -} - -// TODO(crbug.com/1284709): Navigation, refresh, and iframe handling. - -} // namespace web
diff --git a/ios/web/web_state/ui/crw_web_controller.mm b/ios/web/web_state/ui/crw_web_controller.mm index 1bfd3e9..a61b39e 100644 --- a/ios/web/web_state/ui/crw_web_controller.mm +++ b/ios/web/web_state/ui/crw_web_controller.mm
@@ -481,13 +481,15 @@ }]; } - if (@available(iOS 15.4, *)) { +#if defined(__IPHONE_15_4) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_15_4 + if (@available(iOS 15, *)) { if (base::FeatureList::IsEnabled(web::features::kEnableFullscreenAPI)) { [observers addEntriesFromDictionary:@{ @"fullscreenState" : @"fullscreenStateDidChange" }]; } } +#endif // defined(__IPHONE_15_4) return observers; } @@ -1193,25 +1195,6 @@ } } -#if defined(__IPHONE_15_4) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_15_4 -- (CrFullscreenState)CrFullscreenStateFromWKFullscreenState: - (WKFullscreenState)state API_AVAILABLE(ios(15.4)) { - switch (state) { - case WKFullscreenStateEnteringFullscreen: - return CrFullscreenState::kEnteringFullscreen; - case WKFullscreenStateExitingFullscreen: - return CrFullscreenState::kExitingFullscreen; - case WKFullscreenStateInFullscreen: - return CrFullscreenState::kInFullscreen; - case WKFullscreenStateNotInFullscreen: - return CrFullscreenState::kNotInFullScreen; - default: - NOTREACHED(); - return CrFullscreenState::kNotInFullScreen; - } -} -#endif // defined (__IPHONE_15_4) - #pragma mark - End of loading - (void)didFinishNavigation:(web::NavigationContextImpl*)context { @@ -1662,22 +1645,20 @@ return; #if defined(__IPHONE_15_4) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_15_4 - if (@available(iOS 15.4, *)) { + if (@available(iOS 15, *)) { CRWWebViewContentView* webViewContentView = [[CRWWebViewContentView alloc] initWithWebView:self.webView scrollView:self.webScrollView - fullscreenState:[self CrFullscreenStateFromWKFullscreenState: - self.webView.fullscreenState]]; + fullscreenState:self.webView.fullscreenState]; [_containerView displayWebViewContentView:webViewContentView]; return; } -#endif // defined(__IPHONE_15_4) - - CRWWebViewContentView* webViewContentView = [[CRWWebViewContentView alloc] - initWithWebView:self.webView - scrollView:self.webScrollView - fullscreenState:CrFullscreenState::kNotInFullScreen]; +#else + CRWWebViewContentView* webViewContentView = + [[CRWWebViewContentView alloc] initWithWebView:self.webView + scrollView:self.webScrollView]; [_containerView displayWebViewContentView:webViewContentView]; +#endif // defined(__IPHONE_15_4) } - (void)removeWebView { @@ -1838,13 +1819,9 @@ } #if defined(__IPHONE_15_4) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_15_4 -- (void)fullscreenStateDidChange { - if (@available(iOS 15.4, *)) { - [_containerView - updateWebViewContentViewFullscreenState: - [self CrFullscreenStateFromWKFullscreenState:self.webView - .fullscreenState]]; - } +- (void)fullscreenStateDidChange API_AVAILABLE(ios(15.0)) { + [_containerView + updateWebViewContentViewFullscreenState:self.webView.fullscreenState]; } #endif // defined (__IPHONE_15_4)
diff --git a/ios/web/web_state/ui/crw_web_controller_container_view.h b/ios/web/web_state/ui/crw_web_controller_container_view.h index 01f374e..a2e2b785 100644 --- a/ios/web/web_state/ui/crw_web_controller_container_view.h +++ b/ios/web/web_state/ui/crw_web_controller_container_view.h
@@ -69,9 +69,11 @@ // doesn't suspend it's counterpart process. - (void)updateWebViewContentViewForContainerWindow:(UIWindow*)window; +#if defined(__IPHONE_15_4) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_15_4 // Updates |webViewContentView| with the current fullscreen state - (void)updateWebViewContentViewFullscreenState: - (CrFullscreenState)fullscreenState; + (WKFullscreenState)fullscreenState API_AVAILABLE(ios(15)); +#endif // defined(__IPHONE_15_4) @end
diff --git a/ios/web/web_state/ui/crw_web_controller_container_view.mm b/ios/web/web_state/ui/crw_web_controller_container_view.mm index db12ab1..811bd2d 100644 --- a/ios/web/web_state/ui/crw_web_controller_container_view.mm +++ b/ios/web/web_state/ui/crw_web_controller_container_view.mm
@@ -149,11 +149,15 @@ [self setNeedsLayout]; } +#if defined(__IPHONE_15_4) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_15_4 - (void)updateWebViewContentViewFullscreenState: - (CrFullscreenState)fullscreenState { + (WKFullscreenState)fullscreenState { DCHECK(_webViewContentView); - [self.webViewContentView updateFullscreenState:fullscreenState]; + if (@available(iOS 15.4, *)) { + [self.webViewContentView updateFullscreenState:fullscreenState]; + } } +#endif // defined(__IPHONE_15_4) #pragma mark UIView (printing)
diff --git a/ios/web/web_state/ui/crw_web_view_content_view_unittest.mm b/ios/web/web_state/ui/crw_web_view_content_view_unittest.mm index 63d2477..def046b 100644 --- a/ios/web/web_state/ui/crw_web_view_content_view_unittest.mm +++ b/ios/web/web_state/ui/crw_web_view_content_view_unittest.mm
@@ -24,10 +24,9 @@ UIView* webView = [[UIView alloc] init]; UIScrollView* scrollView = [[UIScrollView alloc] init]; [webView addSubview:scrollView]; - CRWWebViewContentView* contentView = [[CRWWebViewContentView alloc] - initWithWebView:webView - scrollView:scrollView - fullscreenState:CrFullscreenState::kNotInFullScreen]; + CRWWebViewContentView* contentView = + [[CRWWebViewContentView alloc] initWithWebView:webView + scrollView:scrollView]; contentView.shouldUseViewContentInset = YES; const UIEdgeInsets contentInset = UIEdgeInsetsMake(10, 10, 10, 10);
diff --git a/mojo/public/cpp/base/values_mojom_traits.cc b/mojo/public/cpp/base/values_mojom_traits.cc index b84f6b7..81a9c79 100644 --- a/mojo/public/cpp/base/values_mojom_traits.cc +++ b/mojo/public/cpp/base/values_mojom_traits.cc
@@ -43,6 +43,39 @@ return true; } +bool StructTraits< + mojo_base::mojom::DeprecatedDictionaryValueDataView, + base::Value>::Read(mojo_base::mojom::DeprecatedDictionaryValueDataView data, + base::Value* value_out) { + mojo::MapDataView<mojo::StringDataView, mojo_base::mojom::ValueDataView> view; + data.GetStorageDataView(&view); + std::vector<base::Value::DictStorage::value_type> dict_storage; + dict_storage.reserve(view.size()); + for (size_t i = 0; i < view.size(); ++i) { + base::StringPiece key; + base::Value value; + if (!view.keys().Read(i, &key) || !view.values().Read(i, &value)) + return false; + dict_storage.emplace_back(std::string(key), std::move(value)); + } + *value_out = base::Value(base::Value::DictStorage(std::move(dict_storage))); + return true; +} + +bool StructTraits<mojo_base::mojom::DeprecatedListValueDataView, base::Value>:: + Read(mojo_base::mojom::DeprecatedListValueDataView data, + base::Value* value_out) { + mojo::ArrayDataView<mojo_base::mojom::ValueDataView> view; + data.GetStorageDataView(&view); + base::Value::ListStorage list_storage(view.size()); + for (size_t i = 0; i < view.size(); ++i) { + if (!view.Read(i, &list_storage[i])) + return false; + } + *value_out = base::Value(std::move(list_storage)); + return true; +} + bool UnionTraits<mojo_base::mojom::ValueDataView, base::Value>::Read( mojo_base::mojom::ValueDataView data, base::Value* value_out) {
diff --git a/mojo/public/cpp/base/values_mojom_traits.h b/mojo/public/cpp/base/values_mojom_traits.h index 4e3e95f1..e0797d5f 100644 --- a/mojo/public/cpp/base/values_mojom_traits.h +++ b/mojo/public/cpp/base/values_mojom_traits.h
@@ -67,6 +67,31 @@ template <> struct COMPONENT_EXPORT(MOJO_BASE_SHARED_TRAITS) + StructTraits<mojo_base::mojom::DeprecatedDictionaryValueDataView, + base::Value> { + static const base::Value& storage(const base::Value& value) { + DCHECK(value.is_dict()); + return value; + } + + static bool Read(mojo_base::mojom::DeprecatedDictionaryValueDataView data, + base::Value* value); +}; + +template <> +struct COMPONENT_EXPORT(MOJO_BASE_SHARED_TRAITS) + StructTraits<mojo_base::mojom::DeprecatedListValueDataView, base::Value> { + static base::span<const base::Value> storage(const base::Value& value) { + DCHECK(value.is_list()); + return value.GetListDeprecated(); + } + + static bool Read(mojo_base::mojom::DeprecatedListValueDataView data, + base::Value* value); +}; + +template <> +struct COMPONENT_EXPORT(MOJO_BASE_SHARED_TRAITS) UnionTraits<mojo_base::mojom::ValueDataView, base::Value> { static mojo_base::mojom::ValueDataView::Tag GetTag(const base::Value& data) { switch (data.type()) {
diff --git a/mojo/public/mojom/base/BUILD.gn b/mojo/public/mojom/base/BUILD.gn index 2c6af6e7..affa16b 100644 --- a/mojo/public/mojom/base/BUILD.gn +++ b/mojo/public/mojom/base/BUILD.gn
@@ -315,12 +315,26 @@ move_only = true }, { - mojom = "mojo_base.mojom.ListValue" + mojom = "mojo_base.mojom.DictionaryValue" + + # TODO(https://crbug.com/1301890): Change this to ::base::Value::Dict. cpp = "::base::Value" move_only = true }, { - mojom = "mojo_base.mojom.DictionaryValue" + mojom = "mojo_base.mojom.ListValue" + + # TODO(https://crbug.com/1301889): Change this to ::base::Value::List. + cpp = "::base::Value" + move_only = true + }, + { + mojom = "mojo_base.mojom.DeprecatedDictionaryValue" + cpp = "::base::Value" + move_only = true + }, + { + mojom = "mojo_base.mojom.DeprecatedListValue" cpp = "::base::Value" move_only = true },
diff --git a/mojo/public/mojom/base/values.mojom b/mojo/public/mojom/base/values.mojom index 5ffe845..df5e395 100644 --- a/mojo/public/mojom/base/values.mojom +++ b/mojo/public/mojom/base/values.mojom
@@ -27,9 +27,10 @@ // Interfaces that only want to handle a value of dictionary or list type // should use base.mojom.DictionaryValue or base.mojom.ListValue in the method -// declaration. Though both of these types are mapped to base::Value in C++, -// the generated deserialization will guarantee that the method is only invoked -// with a base::Value of the correct subtype. +// declaration. Currently, both of these are typemapped to base::Value, though +// once all existing usage is swapped over to the deprecated versions below, +// the typemap will be updated to deserialize as a base::Value::Dict and +// base::Value::List respectively instead. [Stable] struct DictionaryValue { map<string, Value> storage; @@ -39,3 +40,17 @@ struct ListValue { array<Value> storage; }; + +// Legacy versions of the above dictionary and list value types. Both are +// unconditionally typemapped to base::Value. Though the typemap ensures that +// the deserialized base::Value has a matching subtype, use of these will be +// removed in the future due to lack of type safety. +[Stable] +struct DeprecatedDictionaryValue { + map<string, Value> storage; +}; + +[Stable] +struct DeprecatedListValue { + array<Value> storage; +};
diff --git a/mojo/public/rust/BUILD.gn b/mojo/public/rust/BUILD.gn index c29b2dc..4ff1b40 100644 --- a/mojo/public/rust/BUILD.gn +++ b/mojo/public/rust/BUILD.gn
@@ -15,7 +15,7 @@ # Meta target to build test binaries, if supported. rust_unit_tests_group("mojo_rust_tests") { deps = [] - if (build_rust_unit_tests) { + if (can_build_rust_unit_tests) { deps += [ ":mojo_rust_unittests" ] } if (rustc_can_link) { @@ -47,6 +47,9 @@ "mojo_rust_unittests" # avoids conflict with C++ target elsewhere crate_name = "mojo" edition = "2018" + + # TODO(danakj): Move to a gtest target. + build_native_rust_unit_tests = true sources = [ "bindings/decoding.rs", "bindings/encoding.rs",
diff --git a/mojo/public/rust/bindings/message.rs b/mojo/public/rust/bindings/message.rs index 3e218b3..065cd07 100644 --- a/mojo/public/rust/bindings/message.rs +++ b/mojo/public/rust/bindings/message.rs
@@ -18,11 +18,12 @@ /// a response. pub const MESSAGE_HEADER_IS_RESPONSE: u32 = 2; -const MESSAGE_HEADER_VERSIONS: [(u32, u32); 2] = [(0, 16), (1, 24)]; +const MESSAGE_HEADER_VERSIONS: [(u32, u32); 2] = [(0, 24), (1, 32)]; /// A message header object implemented as a Mojom struct. pub struct MessageHeader { pub version: u32, + pub interface_id: u32, pub name: u32, pub flags: u32, pub request_id: u64, @@ -31,7 +32,7 @@ impl MessageHeader { /// Create a new MessageHeader. pub fn new(version: u32, name: u32, flags: u32) -> MessageHeader { - MessageHeader { version: version, name: name, flags: flags, request_id: 0 } + MessageHeader { version: version, interface_id: 0, name: name, flags: flags, request_id: 0 } } } @@ -45,7 +46,7 @@ /// This value differs based on whether or not /// a request_id is necessary. fn serialized_size(&self, _context: &Context) -> usize { - let mut size = DATA_HEADER_SIZE + 8; + let mut size = DATA_HEADER_SIZE + 12; if self.flags != MESSAGE_HEADER_NO_FLAG { size += 8; } @@ -53,6 +54,7 @@ } fn encode_value(self, encoder: &mut Encoder, context: Context) { + MojomEncodable::encode(self.interface_id, encoder, context.clone()); MojomEncodable::encode(self.name, encoder, context.clone()); MojomEncodable::encode(self.flags, encoder, context.clone()); if self.version > 0 { @@ -66,6 +68,7 @@ Ok(header) => header.data(), Err(err) => return Err(err), }; + let interface_id = state.decode::<u32>(); let name = state.decode::<u32>(); let flags = state.decode::<u32>(); if flags > MESSAGE_HEADER_IS_RESPONSE { @@ -75,10 +78,17 @@ if flags == MESSAGE_HEADER_IS_RESPONSE || flags == MESSAGE_HEADER_EXPECT_RESPONSE { return Err(ValidationError::MessageHeaderMissingRequestId); } - Ok(MessageHeader { version: version, name: name, flags: flags, request_id: 0 }) + Ok(MessageHeader { + version: version, + interface_id: interface_id, + name: name, + flags: flags, + request_id: 0, + }) } else if version == 1 { Ok(MessageHeader { version: version, + interface_id: interface_id, name: name, flags: flags, request_id: state.decode::<u64>(),
diff --git a/mojo/public/rust/lib.rs b/mojo/public/rust/lib.rs index b349e88..dd506bf8 100644 --- a/mojo/public/rust/lib.rs +++ b/mojo/public/rust/lib.rs
@@ -2,10 +2,6 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -// Workaround for linkage bug for rust binary -> C++ component -> rust component -// dependency. TOOD(https://crbug.com/1289742): remove this after fix. -extern crate base_rs; - #[macro_use] mod macros { /// This macro must be used at the top-level in any
diff --git a/mojo/public/rust/tests/encoding.rs b/mojo/public/rust/tests/encoding.rs index ef91a79..721abfe 100644 --- a/mojo/public/rust/tests/encoding.rs +++ b/mojo/public/rust/tests/encoding.rs
@@ -10,7 +10,7 @@ use mojo::bindings::encoding::Context; use mojo::bindings::message::MessageHeader; -use mojo::bindings::mojom::{MojomInterface, MojomPointer, MojomStruct, MojomUnion}; +use mojo::bindings::mojom::{MojomInterface, MojomPointer, MojomStruct}; use mojo::system; use mojo::system::Handle; @@ -433,240 +433,6 @@ } } } - conformance_mthd14_good_1 { - MessageHeader => { - |header: MessageHeader| { - assert_eq!(header.version, 0); - assert_eq!(header.name, 14); - assert_eq!(header.flags, 0); - } - }, - ConformanceTestInterfaceMethod14Request => { - |payload: &ConformanceTestInterfaceMethod14Request| { - match payload.param0 { - UnionA::a(ref val) => assert_eq!(*val, 54), - _ => panic!("Incorrect union variant! Tag found: {}", payload.param0.get_tag()), - } - } - } - } - conformance_mthd14_good_array_in_union { - MessageHeader => { - |header: MessageHeader| { - assert_eq!(header.version, 0); - assert_eq!(header.name, 14); - assert_eq!(header.flags, 0); - } - }, - ConformanceTestInterfaceMethod14Request => { - |payload: &ConformanceTestInterfaceMethod14Request| { - match payload.param0 { - UnionA::d(ref val) => assert_eq!(*val, Some(vec![0, 1, 2])), - _ => panic!("Incorrect union variant! Tag found: {}", payload.param0.get_tag()), - } - } - } - } - conformance_mthd14_good_map_in_union { - MessageHeader => { - |header: MessageHeader| { - assert_eq!(header.version, 0); - assert_eq!(header.name, 14); - assert_eq!(header.flags, 0); - } - }, - ConformanceTestInterfaceMethod14Request => { - |payload: &ConformanceTestInterfaceMethod14Request| { - let mut map = HashMap::with_capacity(2); - map.insert(String::from_utf8(vec![0, 1, 2, 3, 4]).unwrap(), 1); - map.insert(String::from_utf8(vec![5, 6, 7, 8, 9]).unwrap(), 2); - match payload.param0 { - UnionA::e(ref val) => assert_eq!(*val, Some(map)), - _ => panic!("Incorrect union variant! Tag found: {}", payload.param0.get_tag()), - } - } - } - } - conformance_mthd14_good_nested_union { - MessageHeader => { - |header: MessageHeader| { - assert_eq!(header.version, 0); - assert_eq!(header.name, 14); - assert_eq!(header.flags, 0); - } - }, - ConformanceTestInterfaceMethod14Request => { - |payload: &ConformanceTestInterfaceMethod14Request| { - match payload.param0 { - UnionA::f(ref val) => { - assert!(val.is_some()); - let inner = val.as_ref().unwrap(); - match *inner { - UnionB::b(inner_val) => assert_eq!(inner_val, 10), - _ => panic!("Incorrect inner union variant! Tag found: {}", inner.get_tag()), - } - }, - _ => panic!("Incorrect union variant! Tag found: {}", payload.param0.get_tag()), - } - } - } - } - conformance_mthd14_good_null_array_in_union { - MessageHeader => { - |header: MessageHeader| { - assert_eq!(header.version, 0); - assert_eq!(header.name, 14); - assert_eq!(header.flags, 0); - } - }, - ConformanceTestInterfaceMethod14Request => { - |payload: &ConformanceTestInterfaceMethod14Request| { - match payload.param0 { - UnionA::d(ref val) => assert_eq!(*val, None), - _ => panic!("Incorrect union variant! Tag found: {}", payload.param0.get_tag()), - } - } - } - } - conformance_mthd14_good_null_map_in_union { - MessageHeader => { - |header: MessageHeader| { - assert_eq!(header.version, 0); - assert_eq!(header.name, 14); - assert_eq!(header.flags, 0); - } - }, - ConformanceTestInterfaceMethod14Request => { - |payload: &ConformanceTestInterfaceMethod14Request| { - match payload.param0 { - UnionA::e(ref val) => assert_eq!(*val, None), - _ => panic!("Incorrect union variant! Tag found: {}", payload.param0.get_tag()), - } - } - } - } - conformance_mthd14_good_struct_in_union { - MessageHeader => { - |header: MessageHeader| { - assert_eq!(header.version, 0); - assert_eq!(header.name, 14); - assert_eq!(header.flags, 0); - } - }, - ConformanceTestInterfaceMethod14Request => { - |payload: &ConformanceTestInterfaceMethod14Request| { - match payload.param0 { - UnionA::c(ref val) => { - let struct_val = val.as_ref().unwrap(); - assert_eq!(struct_val.i, 20); - }, - _ => panic!("Incorrect union variant! Tag found: {}", payload.param0.get_tag()), - } - } - } - } - conformance_mthd14_good_unknown_union_tag { - MessageHeader => { - |header: MessageHeader| { - assert_eq!(header.version, 0); - assert_eq!(header.name, 14); - assert_eq!(header.flags, 0); - } - }, - ConformanceTestInterfaceMethod14Request => { - |payload: &ConformanceTestInterfaceMethod14Request| { - match payload.param0 { - UnionA::_Unknown(ref val) => assert_eq!(*val, 54), - _ => panic!("Incorrect union variant! Tag found: {}", payload.param0.get_tag()), - } - } - } - } - conformance_mthd15_good_union_in_array { - MessageHeader => { - |header: MessageHeader| { - assert_eq!(header.version, 0); - assert_eq!(header.name, 15); - assert_eq!(header.flags, 0); - } - }, - ConformanceTestInterfaceMethod15Request => { - |payload: &ConformanceTestInterfaceMethod15Request| { - assert_eq!(payload.param0.a, true); - assert_eq!(payload.param0.b, 22); - assert!(payload.param0.c.is_none()); - assert!(payload.param0.d.is_some()); - assert!(payload.param0.e.is_none()); - let array = payload.param0.d.as_ref().unwrap(); - assert_eq!(array.len(), 3); - for u in array.iter() { - match *u { - UnionA::b(ref val) => assert_eq!(*val, 10), - _ => panic!("Incorrect union variant! Tag found: {}", u.get_tag()), - } - } - } - } - } - conformance_mthd15_good_union_in_map { - MessageHeader => { - |header: MessageHeader| { - assert_eq!(header.version, 0); - assert_eq!(header.name, 15); - assert_eq!(header.flags, 0); - } - }, - ConformanceTestInterfaceMethod15Request => { - |payload: &ConformanceTestInterfaceMethod15Request| { - assert_eq!(payload.param0.a, true); - assert_eq!(payload.param0.b, 22); - assert!(payload.param0.c.is_none()); - assert!(payload.param0.d.is_none()); - assert!(payload.param0.e.is_some()); - let map = payload.param0.e.as_ref().unwrap(); - assert_eq!(map.len(), 3); - let mut expect_keys = HashMap::with_capacity(3); - expect_keys.insert(8, false); - expect_keys.insert(7, false); - expect_keys.insert(1, false); - for (key, value) in map.iter() { - expect_keys.insert(*key, true); - match *value { - UnionA::b(ref val) => assert_eq!(*val, 10), - _ => panic!("Incorrect union variant! Tag found: {}", value.get_tag()), - } - } - for (key, value) in expect_keys.iter() { - if *value == false { - panic!("Expected key `{}`, but not found!", *key); - } - } - } - } - } - conformance_mthd15_good_union_in_struct { - MessageHeader => { - |header: MessageHeader| { - assert_eq!(header.version, 0); - assert_eq!(header.name, 15); - assert_eq!(header.flags, 0); - } - }, - ConformanceTestInterfaceMethod15Request => { - |payload: &ConformanceTestInterfaceMethod15Request| { - assert_eq!(payload.param0.a, true); - assert_eq!(payload.param0.b, 22); - assert!(payload.param0.c.is_some()); - assert!(payload.param0.d.is_none()); - assert!(payload.param0.e.is_none()); - let union_val = payload.param0.c.as_ref().unwrap(); - match *union_val { - UnionA::b(ref val) => assert_eq!(*val, 54), - _ => panic!("Incorrect union variant! Tag found: {}", union_val.get_tag()), - } - } - } - } integration_intf_rqst_mthd0_good { MessageHeader => { |header: MessageHeader| { @@ -697,4 +463,241 @@ } } } + + // Tests with missing data: + // + // conformance_mthd14_good_1 { + // MessageHeader => { + // |header: MessageHeader| { + // assert_eq!(header.version, 0); + // assert_eq!(header.name, 14); + // assert_eq!(header.flags, 0); + // } + // }, + // ConformanceTestInterfaceMethod14Request => { + // |payload: &ConformanceTestInterfaceMethod14Request| { + // match payload.param0 { + // UnionA::a(ref val) => assert_eq!(*val, 54), + // _ => panic!("Incorrect union variant! Tag found: {}", payload.param0.get_tag()), + // } + // } + // } + // } + // conformance_mthd14_good_array_in_union { + // MessageHeader => { + // |header: MessageHeader| { + // assert_eq!(header.version, 0); + // assert_eq!(header.name, 14); + // assert_eq!(header.flags, 0); + // } + // }, + // ConformanceTestInterfaceMethod14Request => { + // |payload: &ConformanceTestInterfaceMethod14Request| { + // match payload.param0 { + // UnionA::d(ref val) => assert_eq!(*val, Some(vec![0, 1, 2])), + // _ => panic!("Incorrect union variant! Tag found: {}", payload.param0.get_tag()), + // } + // } + // } + // } + // conformance_mthd14_good_map_in_union { + // MessageHeader => { + // |header: MessageHeader| { + // assert_eq!(header.version, 0); + // assert_eq!(header.name, 14); + // assert_eq!(header.flags, 0); + // } + // }, + // ConformanceTestInterfaceMethod14Request => { + // |payload: &ConformanceTestInterfaceMethod14Request| { + // let mut map = HashMap::with_capacity(2); + // map.insert(String::from_utf8(vec![0, 1, 2, 3, 4]).unwrap(), 1); + // map.insert(String::from_utf8(vec![5, 6, 7, 8, 9]).unwrap(), 2); + // match payload.param0 { + // UnionA::e(ref val) => assert_eq!(*val, Some(map)), + // _ => panic!("Incorrect union variant! Tag found: {}", payload.param0.get_tag()), + // } + // } + // } + // } + // conformance_mthd14_good_nested_union { + // MessageHeader => { + // |header: MessageHeader| { + // assert_eq!(header.version, 0); + // assert_eq!(header.name, 14); + // assert_eq!(header.flags, 0); + // } + // }, + // ConformanceTestInterfaceMethod14Request => { + // |payload: &ConformanceTestInterfaceMethod14Request| { + // match payload.param0 { + // UnionA::f(ref val) => { + // assert!(val.is_some()); + // let inner = val.as_ref().unwrap(); + // match *inner { + // UnionB::b(inner_val) => assert_eq!(inner_val, 10), + // _ => panic!("Incorrect inner union variant! Tag found: {}", inner.get_tag()), + // } + // }, + // _ => panic!("Incorrect union variant! Tag found: {}", payload.param0.get_tag()), + // } + // } + // } + // } + // conformance_mthd14_good_null_array_in_union { + // MessageHeader => { + // |header: MessageHeader| { + // assert_eq!(header.version, 0); + // assert_eq!(header.name, 14); + // assert_eq!(header.flags, 0); + // } + // }, + // ConformanceTestInterfaceMethod14Request => { + // |payload: &ConformanceTestInterfaceMethod14Request| { + // match payload.param0 { + // UnionA::d(ref val) => assert_eq!(*val, None), + // _ => panic!("Incorrect union variant! Tag found: {}", payload.param0.get_tag()), + // } + // } + // } + // } + // conformance_mthd14_good_null_map_in_union { + // MessageHeader => { + // |header: MessageHeader| { + // assert_eq!(header.version, 0); + // assert_eq!(header.name, 14); + // assert_eq!(header.flags, 0); + // } + // }, + // ConformanceTestInterfaceMethod14Request => { + // |payload: &ConformanceTestInterfaceMethod14Request| { + // match payload.param0 { + // UnionA::e(ref val) => assert_eq!(*val, None), + // _ => panic!("Incorrect union variant! Tag found: {}", payload.param0.get_tag()), + // } + // } + // } + // } + // conformance_mthd14_good_struct_in_union { + // MessageHeader => { + // |header: MessageHeader| { + // assert_eq!(header.version, 0); + // assert_eq!(header.name, 14); + // assert_eq!(header.flags, 0); + // } + // }, + // ConformanceTestInterfaceMethod14Request => { + // |payload: &ConformanceTestInterfaceMethod14Request| { + // match payload.param0 { + // UnionA::c(ref val) => { + // let struct_val = val.as_ref().unwrap(); + // assert_eq!(struct_val.i, 20); + // }, + // _ => panic!("Incorrect union variant! Tag found: {}", payload.param0.get_tag()), + // } + // } + // } + // } + // conformance_mthd14_good_unknown_union_tag { + // MessageHeader => { + // |header: MessageHeader| { + // assert_eq!(header.version, 0); + // assert_eq!(header.name, 14); + // assert_eq!(header.flags, 0); + // } + // }, + // ConformanceTestInterfaceMethod14Request => { + // |payload: &ConformanceTestInterfaceMethod14Request| { + // match payload.param0 { + // UnionA::_Unknown(ref val) => assert_eq!(*val, 54), + // _ => panic!("Incorrect union variant! Tag found: {}", payload.param0.get_tag()), + // } + // } + // } + // } + // conformance_mthd15_good_union_in_array { + // MessageHeader => { + // |header: MessageHeader| { + // assert_eq!(header.version, 0); + // assert_eq!(header.name, 15); + // assert_eq!(header.flags, 0); + // } + // }, + // ConformanceTestInterfaceMethod15Request => { + // |payload: &ConformanceTestInterfaceMethod15Request| { + // assert_eq!(payload.param0.a, true); + // assert_eq!(payload.param0.b, 22); + // assert!(payload.param0.c.is_none()); + // assert!(payload.param0.d.is_some()); + // assert!(payload.param0.e.is_none()); + // let array = payload.param0.d.as_ref().unwrap(); + // assert_eq!(array.len(), 3); + // for u in array.iter() { + // match *u { + // UnionA::b(ref val) => assert_eq!(*val, 10), + // _ => panic!("Incorrect union variant! Tag found: {}", u.get_tag()), + // } + // } + // } + // } + // } + // conformance_mthd15_good_union_in_map { + // MessageHeader => { + // |header: MessageHeader| { + // assert_eq!(header.version, 0); + // assert_eq!(header.name, 15); + // assert_eq!(header.flags, 0); + // } + // }, + // ConformanceTestInterfaceMethod15Request => { + // |payload: &ConformanceTestInterfaceMethod15Request| { + // assert_eq!(payload.param0.a, true); + // assert_eq!(payload.param0.b, 22); + // assert!(payload.param0.c.is_none()); + // assert!(payload.param0.d.is_none()); + // assert!(payload.param0.e.is_some()); + // let map = payload.param0.e.as_ref().unwrap(); + // assert_eq!(map.len(), 3); + // let mut expect_keys = HashMap::with_capacity(3); + // expect_keys.insert(8, false); + // expect_keys.insert(7, false); + // expect_keys.insert(1, false); + // for (key, value) in map.iter() { + // expect_keys.insert(*key, true); + // match *value { + // UnionA::b(ref val) => assert_eq!(*val, 10), + // _ => panic!("Incorrect union variant! Tag found: {}", value.get_tag()), + // } + // } + // for (key, value) in expect_keys.iter() { + // if *value == false { + // panic!("Expected key `{}`, but not found!", *key); + // } + // } + // } + // } + // } + // conformance_mthd15_good_union_in_struct { + // MessageHeader => { + // |header: MessageHeader| { + // assert_eq!(header.version, 0); + // assert_eq!(header.name, 15); + // assert_eq!(header.flags, 0); + // } + // }, + // ConformanceTestInterfaceMethod15Request => { + // |payload: &ConformanceTestInterfaceMethod15Request| { + // assert_eq!(payload.param0.a, true); + // assert_eq!(payload.param0.b, 22); + // assert!(payload.param0.c.is_some()); + // assert!(payload.param0.d.is_none()); + // assert!(payload.param0.e.is_none()); + // let union_val = payload.param0.c.as_ref().unwrap(); + // match *union_val { + // UnionA::b(ref val) => assert_eq!(*val, 54), + // _ => panic!("Incorrect union variant! Tag found: {}", union_val.get_tag()), + // } + // } + // } + // } }
diff --git a/mojo/public/rust/tests/lib.rs b/mojo/public/rust/tests/lib.rs index 1803b58..f06815d 100644 --- a/mojo/public/rust/tests/lib.rs +++ b/mojo/public/rust/tests/lib.rs
@@ -25,5 +25,5 @@ // The code in crate/bindings/{encoding,decoding}.rs needs to be updated and // the tests must be updated to use the available test data // -// mod encoding; -// mod validation; +mod encoding; +mod validation;
diff --git a/mojo/public/rust/tests/validation.rs b/mojo/public/rust/tests/validation.rs index a8f5ebe..2197ba5b 100644 --- a/mojo/public/rust/tests/validation.rs +++ b/mojo/public/rust/tests/validation.rs
@@ -69,11 +69,6 @@ conformance_mthd11_num_bytes_version_mismatch_1 => ConformanceTestInterfaceRequestOption; conformance_mthd11_num_bytes_version_mismatch_2 => ConformanceTestInterfaceRequestOption; conformance_mthd12_invalid_request_flags => ConformanceTestInterfaceRequestOption; - // conformance_mthd14_unexpected_null_array_in_union => ConformanceTestInterfaceRequestOption; - // conformance_mthd14_unexpected_null_map_in_union => ConformanceTestInterfaceRequestOption; - // conformance_mthd14_unexpected_null_struct_in_union => ConformanceTestInterfaceRequestOption; - // conformance_mthd14_unexpected_null_union_in_union => ConformanceTestInterfaceRequestOption; - // conformance_mthd15_unexpected_null_union_in_array => ConformanceTestInterfaceRequestOption; conformance_mthd1_misaligned_struct => ConformanceTestInterfaceRequestOption; conformance_mthd1_struct_pointer_overflow => ConformanceTestInterfaceRequestOption; conformance_mthd1_unexpected_null_struct => ConformanceTestInterfaceRequestOption; @@ -123,4 +118,12 @@ integration_intf_resp_mthd0_unexpected_array_header => IntegrationTestInterfaceResponseOption; integration_intf_rqst_mthd0_unexpected_struct_header => IntegrationTestInterfaceRequestOption; integration_msghdr_invalid_flags => IntegrationTestInterfaceRequestOption; + + // Tests with missing data: + // + // conformance_mthd14_unexpected_null_array_in_union => ConformanceTestInterfaceRequestOption; + // conformance_mthd14_unexpected_null_map_in_union => ConformanceTestInterfaceRequestOption; + // conformance_mthd14_unexpected_null_struct_in_union => ConformanceTestInterfaceRequestOption; + // conformance_mthd14_unexpected_null_union_in_union => ConformanceTestInterfaceRequestOption; + // conformance_mthd15_unexpected_null_union_in_array => ConformanceTestInterfaceRequestOption; }
diff --git a/net/cert/internal/trust_store_mac.cc b/net/cert/internal/trust_store_mac.cc index ee4c8604..af7952d 100644 --- a/net/cert/internal/trust_store_mac.cc +++ b/net/cert/internal/trust_store_mac.cc
@@ -653,7 +653,7 @@ private: // (Re-)Initialize the cache if necessary. Must be called after acquiring // |cache_lock_| and before accessing any of the |*_domain_cache_| members. - void MaybeInitializeCache() { + void MaybeInitializeCache() EXCLUSIVE_LOCKS_REQUIRED(cache_lock_) { cache_lock_.AssertAcquired(); int64_t keychain_iteration = keychain_observer_->Iteration(); if (iteration_ == keychain_iteration) @@ -675,11 +675,11 @@ base::Lock cache_lock_; // |cache_lock_| must be held while accessing any following members. - int64_t iteration_ = -1; - bool system_domain_initialized_ = false; - TrustDomainCache system_domain_cache_; - TrustDomainCache admin_domain_cache_; - TrustDomainCache user_domain_cache_; + int64_t iteration_ GUARDED_BY(cache_lock_) = -1; + bool system_domain_initialized_ GUARDED_BY(cache_lock_) = false; + TrustDomainCache system_domain_cache_ GUARDED_BY(cache_lock_); + TrustDomainCache admin_domain_cache_ GUARDED_BY(cache_lock_); + TrustDomainCache user_domain_cache_ GUARDED_BY(cache_lock_); }; // TrustImplNoCache is the simplest approach which calls @@ -832,7 +832,7 @@ return trust_details; } - void MaybeResetCache() { + void MaybeResetCache() EXCLUSIVE_LOCKS_REQUIRED(cache_lock_) { cache_lock_.AssertAcquired(); int64_t keychain_iteration = keychain_observer_->Iteration(); if (iteration_ == keychain_iteration) @@ -846,14 +846,15 @@ base::Lock cache_lock_; // |cache_lock_| must be held while accessing any following members. - base::LRUCache<SHA256HashValue, TrustStatusDetails> trust_status_cache_; + base::LRUCache<SHA256HashValue, TrustStatusDetails> trust_status_cache_ + GUARDED_BY(cache_lock_); // Tracks the number of keychain changes that have been observed. If the // keychain observer has noted a change, MaybeResetCache will update // |iteration_| and the cache will be cleared. Any in-flight trust // resolutions that started before the keychain update was observed should // not cache their results, as it isn't clear whether the calculated result // applies to the new or old trust settings. - int64_t iteration_ = -1; + int64_t iteration_ GUARDED_BY(cache_lock_) = -1; }; TrustStoreMac::TrustStoreMac(CFStringRef policy_oid,
diff --git a/net/http/structured_headers.cc b/net/http/structured_headers.cc index 799f927b..58953d7 100644 --- a/net/http/structured_headers.cc +++ b/net/http/structured_headers.cc
@@ -28,19 +28,19 @@ #define TCHAR DIGIT LCALPHA UCALPHA "!#$%&'*+-.^_`|~" // https://tools.ietf.org/html/draft-ietf-httpbis-header-structure-09#section-3.9 constexpr char kTokenChars09[] = DIGIT UCALPHA LCALPHA "_-.:%*/"; -// https://tools.ietf.org/html/draft-ietf-httpbis-header-structure-15#section-3.3.4 -constexpr char kTokenChars15[] = TCHAR ":/"; +// https://www.rfc-editor.org/rfc/rfc8941.html#section-3.3.4 +constexpr char kTokenChars[] = TCHAR ":/"; // https://tools.ietf.org/html/draft-ietf-httpbis-header-structure-09#section-3.1 constexpr char kKeyChars09[] = DIGIT LCALPHA "_-"; -// https://tools.ietf.org/html/draft-ietf-httpbis-header-structure-15#section-3.1.2 -constexpr char kKeyChars15[] = DIGIT LCALPHA "_-.*"; +// https://www.rfc-editor.org/rfc/rfc8941.html#section-3.1.2 +constexpr char kKeyChars[] = DIGIT LCALPHA "_-.*"; constexpr char kSP[] = " "; constexpr char kOWS[] = " \t"; #undef DIGIT #undef LCALPHA #undef UCALPHA -// https://tools.ietf.org/html/draft-ietf-httpbis-header-structure-15#section-3.3.1 +// https://www.rfc-editor.org/rfc/rfc8941.html#section-3.3.1 constexpr int64_t kMaxInteger = 999'999'999'999'999L; constexpr int64_t kMinInteger = -999'999'999'999'999L; @@ -51,21 +51,22 @@ constexpr double kTooLargeDecimal = 1e12 - 0.0005; // Parser for (a subset of) Structured Headers for HTTP defined in [SH09] and -// [SH15]. [SH09] compatibility is retained for use by Web Packaging, and can be -// removed once that spec is updated, and users have migrated to new headers. +// [RFC8941]. [SH09] compatibility is retained for use by Web Packaging, and can +// be removed once that spec is updated, and users have migrated to new headers. // [SH09] https://tools.ietf.org/html/draft-ietf-httpbis-header-structure-09 -// [SH15] https://tools.ietf.org/html/draft-ietf-httpbis-header-structure-15 +// [RFC8941] https://www.rfc-editor.org/rfc/rfc8941.html class StructuredHeaderParser { public: enum DraftVersion { kDraft09, - kDraft15, + kFinal, }; explicit StructuredHeaderParser(base::StringPiece str, DraftVersion version) : input_(str), version_(version) { // [SH09] 4.2 Step 1. - // [SH15] 4.2 Step 2. // Discard any leading OWS from input_string. + // [RFC8941] 4.2 Step 2. + // Discard any leading SP characters from input_string. SkipWhitespaces(); } StructuredHeaderParser(const StructuredHeaderParser&) = delete; @@ -74,10 +75,12 @@ // Callers should call this after ReadSomething(), to check if parser has // consumed all the input successfully. bool FinishParsing() { - // [SH09] 4.2 Step 7. [SH15] 4.2 Step 6. + // [SH09] 4.2 Step 7. // Discard any leading OWS from input_string. + // [RFC8941] 4.2 Step 6. + // Discard any leading SP characters from input_string. SkipWhitespaces(); - // [SH09] 4.2 Step 8. [SH15] 4.2 Step 7. + // [SH09] 4.2 Step 8. [RFC8941] 4.2 Step 7. // If input_string is not empty, fail parsing. return input_.empty(); } @@ -107,28 +110,28 @@ return result; } - // Parses a List ([SH15] 4.2.1). + // Parses a List ([RFC8941] 4.2.1). absl::optional<List> ReadList() { - DCHECK_EQ(version_, kDraft15); + DCHECK_EQ(version_, kFinal); List members; while (!input_.empty()) { absl::optional<ParameterizedMember> member(ReadItemOrInnerList()); if (!member) return absl::nullopt; members.push_back(std::move(*member)); - SkipWhitespaces(); + SkipOWS(); if (input_.empty()) break; if (!ConsumeChar(',')) return absl::nullopt; - SkipWhitespaces(); + SkipOWS(); if (input_.empty()) return absl::nullopt; } return members; } - // Parses an Item ([SH15] 4.2.3). + // Parses an Item ([RFC8941] 4.2.3). absl::optional<ParameterizedItem> ReadItem() { absl::optional<Item> item = ReadBareItem(); if (!item) @@ -139,8 +142,8 @@ return ParameterizedItem(std::move(*item), std::move(*parameters)); } - // Parses a bare Item ([SH15] 4.2.3.1, though this is also the algorithm for - // parsing an Item from [SH09] 4.2.7). + // Parses a bare Item ([RFC8941] 4.2.3.1, though this is also the algorithm + // for parsing an Item from [SH09] 4.2.7). absl::optional<Item> ReadBareItem() { if (input_.empty()) { DVLOG(1) << "ReadBareItem: unexpected EOF"; @@ -154,7 +157,7 @@ return ReadByteSequence(); return ReadToken(); case ':': - if (version_ == kDraft15) + if (version_ == kFinal) return ReadByteSequence(); return absl::nullopt; case '?': @@ -168,9 +171,9 @@ } } - // Parses a Dictionary ([SH15] 4.2.2). + // Parses a Dictionary ([RFC8941] 4.2.2). absl::optional<Dictionary> ReadDictionary() { - DCHECK_EQ(version_, kDraft15); + DCHECK_EQ(version_, kFinal); Dictionary members; while (!input_.empty()) { absl::optional<std::string> key(ReadKey()); @@ -189,12 +192,12 @@ member = ParameterizedMember{Item(true), std::move(*parameters)}; } members[*key] = std::move(*member); - SkipWhitespaces(); + SkipOWS(); if (input_.empty()) break; if (!ConsumeChar(',')) return absl::nullopt; - SkipWhitespaces(); + SkipOWS(); if (input_.empty()) return absl::nullopt; } @@ -254,9 +257,9 @@ std::move(parameters)); } - // Parses an Item or Inner List ([SH15] 4.2.1.1). + // Parses an Item or Inner List ([RFC8941] 4.2.1.1). absl::optional<ParameterizedMember> ReadItemOrInnerList() { - DCHECK_EQ(version_, kDraft15); + DCHECK_EQ(version_, kFinal); std::vector<Item> member; bool member_is_inner_list = (!input_.empty() && input_.front() == '('); if (member_is_inner_list) { @@ -270,7 +273,7 @@ } } - // Parses Parameters ([SH15] 4.2.3.2) + // Parses Parameters ([RFC8941] 4.2.3.2) absl::optional<Parameters> ReadParameters() { Parameters parameters; base::flat_set<std::string> keys; @@ -304,9 +307,9 @@ return parameters; } - // Parses an Inner List ([SH15] 4.2.1.2). + // Parses an Inner List ([RFC8941] 4.2.1.2). absl::optional<ParameterizedMember> ReadInnerList() { - DCHECK_EQ(version_, kDraft15); + DCHECK_EQ(version_, kFinal); if (!ConsumeChar('(')) return absl::nullopt; std::vector<ParameterizedItem> inner_list; @@ -331,7 +334,7 @@ return absl::nullopt; } - // Parses a Key ([SH09] 4.2.2, [SH15] 4.2.3.3). + // Parses a Key ([SH09] 4.2.2, [RFC8941] 4.2.3.3). absl::optional<std::string> ReadKey() { if (version_ == kDraft09) { if (input_.empty() || !base::IsAsciiLower(input_.front())) { @@ -346,7 +349,7 @@ } } const char* allowed_chars = - (version_ == kDraft09 ? kKeyChars09 : kKeyChars15); + (version_ == kDraft09 ? kKeyChars09 : kKeyChars); size_t len = input_.find_first_not_of(allowed_chars); if (len == base::StringPiece::npos) len = input_.size(); @@ -355,7 +358,7 @@ return key; } - // Parses a Token ([SH09] 4.2.10, [SH15] 4.2.6). + // Parses a Token ([SH09] 4.2.10, [RFC8941] 4.2.6). absl::optional<Item> ReadToken() { if (input_.empty() || !(base::IsAsciiAlpha(input_.front()) || input_.front() == '*')) { @@ -363,7 +366,7 @@ return absl::nullopt; } size_t len = input_.find_first_not_of(version_ == kDraft09 ? kTokenChars09 - : kTokenChars15); + : kTokenChars); if (len == base::StringPiece::npos) len = input_.size(); std::string token(input_.substr(0, len)); @@ -371,7 +374,7 @@ return Item(std::move(token), Item::kTokenType); } - // Parses a Number ([SH09] 4.2.8, [SH15] 4.2.4). + // Parses a Number ([SH09] 4.2.8, [RFC8941] 4.2.4). absl::optional<Item> ReadNumber() { bool is_negative = ConsumeChar('-'); bool is_decimal = false; @@ -391,21 +394,21 @@ return absl::nullopt; } if (!is_decimal) { - // [SH15] restricts the range of integers further. - if (version_ == kDraft15 && i > 15) { + // [RFC8941] restricts the range of integers further. + if (version_ == kFinal && i > 15) { LogParseError("ReadNumber", "integer too long"); return absl::nullopt; } } else { - if (version_ != kDraft15 && i > 16) { + if (version_ != kFinal && i > 16) { LogParseError("ReadNumber", "float too long"); return absl::nullopt; } - if (version_ == kDraft15 && decimal_position > 12) { + if (version_ == kFinal && decimal_position > 12) { LogParseError("ReadNumber", "decimal too long"); return absl::nullopt; } - if (i - decimal_position > (version_ == kDraft15 ? 4 : 7)) { + if (i - decimal_position > (version_ == kFinal ? 4 : 7)) { LogParseError("ReadNumber", "too many digits after decimal"); return absl::nullopt; } @@ -430,12 +433,12 @@ int64_t n; if (!base::StringToInt64(output_number_string, &n)) return absl::nullopt; - DCHECK(version_ != kDraft15 || (n <= kMaxInteger && n >= kMinInteger)); + DCHECK(version_ != kFinal || (n <= kMaxInteger && n >= kMinInteger)); return Item(is_negative ? -n : n); } } - // Parses a String ([SH09] 4.2.9, [SH15] 4.2.5). + // Parses a String ([SH09] 4.2.9, [RFC8941] 4.2.5). absl::optional<Item> ReadString() { std::string s; if (!ConsumeChar('"')) { @@ -474,7 +477,7 @@ return s; } - // Parses a Byte Sequence ([SH09] 4.2.11, [SH15] 4.2.7). + // Parses a Byte Sequence ([SH09] 4.2.11, [RFC8941] 4.2.7). absl::optional<Item> ReadByteSequence() { char delimiter = (version_ == kDraft09 ? '*' : ':'); if (!ConsumeChar(delimiter)) { @@ -500,7 +503,7 @@ return Item(std::move(binary), Item::kByteSequenceType); } - // Parses a Boolean ([SH15] 4.2.8). + // Parses a Boolean ([RFC8941] 4.2.8). // Note that this only parses ?0 and ?1 forms from SH version 10+, not the // previous ?F and ?T, which were not needed by any consumers of SH version 9. absl::optional<Item> ReadBoolean() { @@ -517,6 +520,9 @@ return absl::nullopt; } + // There are several points in the specs where the handling of whitespace + // differs between Draft 9 and the final RFC. In those cases, Draft 9 allows + // any OWS character, while the RFC allows only a U+0020 SPACE. void SkipWhitespaces() { if (version_ == kDraft09) { input_ = @@ -527,6 +533,11 @@ } } + void SkipOWS() { + input_ = + base::TrimString(input_, base::StringPiece(kOWS), base::TRIM_LEADING); + } + bool ConsumeChar(char expected) { if (!input_.empty() && input_.front() == expected) { input_.remove_prefix(1); @@ -545,8 +556,8 @@ DraftVersion version_; }; -// Serializer for (a subset of) Structured Headers for HTTP defined in [SH15]. -// [SH15] https://tools.ietf.org/html/draft-ietf-httpbis-header-structure-15 +// Serializer for (a subset of) Structured Field Values for HTTP defined in +// [RFC8941]. Note that this serializer does not attempt to support [SH09]. class StructuredHeaderSerializer { public: StructuredHeaderSerializer() = default; @@ -557,7 +568,7 @@ std::string Output() { return output_.str(); } - // Serializes a List ([SH15] 4.1.1). + // Serializes a List ([RFC8941] 4.1.1). bool WriteList(const List& value) { bool first = true; for (const auto& member : value) { @@ -570,17 +581,17 @@ return true; } - // Serializes an Item ([SH15] 4.1.3). + // Serializes an Item ([RFC8941] 4.1.3). bool WriteItem(const ParameterizedItem& value) { if (!WriteBareItem(value.item)) return false; return WriteParameters(value.params); } - // Serializes an Item ([SH15] 4.1.3). + // Serializes an Item ([RFC8941] 4.1.3). bool WriteBareItem(const Item& value) { if (value.is_string()) { - // Serializes a String ([SH15] 4.1.6). + // Serializes a String ([RFC8941] 4.1.6). output_ << "\""; for (const char& c : value.GetString()) { if (!base::IsAsciiPrintable(c)) @@ -593,19 +604,18 @@ return true; } if (value.is_token()) { - // Serializes a Token ([SH15] 4.1.7). + // Serializes a Token ([RFC8941] 4.1.7). if (!value.GetString().size() || !(base::IsAsciiAlpha(value.GetString().front()) || value.GetString().front() == '*')) return false; - if (value.GetString().find_first_not_of(kTokenChars15) != - std::string::npos) + if (value.GetString().find_first_not_of(kTokenChars) != std::string::npos) return false; output_ << value.GetString(); return true; } if (value.is_byte_sequence()) { - // Serializes a Byte Sequence ([SH15] 4.1.8). + // Serializes a Byte Sequence ([RFC8941] 4.1.8). output_ << ":"; output_ << base::Base64Encode( base::as_bytes(base::make_span(value.GetString()))); @@ -613,14 +623,14 @@ return true; } if (value.is_integer()) { - // Serializes an Integer ([SH15] 4.1.4). + // Serializes an Integer ([RFC8941] 4.1.4). if (value.GetInteger() > kMaxInteger || value.GetInteger() < kMinInteger) return false; output_ << value.GetInteger(); return true; } if (value.is_decimal()) { - // Serializes a Decimal ([SH15] 4.1.5). + // Serializes a Decimal ([RFC8941] 4.1.5). double decimal_value = value.GetDecimal(); if (!std::isfinite(decimal_value) || fabs(decimal_value) >= kTooLargeDecimal) @@ -663,14 +673,14 @@ return true; } if (value.is_boolean()) { - // Serializes a Boolean ([SH15] 4.1.9). + // Serializes a Boolean ([RFC8941] 4.1.9). output_ << (value.GetBoolean() ? "?1" : "?0"); return true; } return false; } - // Serializes a Dictionary ([SH15] 4.1.2). + // Serializes a Dictionary ([RFC8941] 4.1.2). bool WriteDictionary(const Dictionary& value) { bool first = true; for (const auto& dict : value) { @@ -696,7 +706,7 @@ private: bool WriteParameterizedMember(const ParameterizedMember& value) { - // Serializes a parameterized member ([SH15] 4.1.1). + // Serializes a parameterized member ([RFC8941] 4.1.1). if (value.member_is_inner_list) { if (!WriteInnerList(value.member)) return false; @@ -709,7 +719,7 @@ } bool WriteInnerList(const std::vector<ParameterizedItem>& value) { - // Serializes an inner list ([SH15] 4.1.1.1). + // Serializes an inner list ([RFC8941] 4.1.1.1). output_ << "("; bool first = true; for (const ParameterizedItem& member : value) { @@ -724,7 +734,7 @@ } bool WriteParameters(const Parameters& value) { - // Serializes a parameter list ([SH15] 4.1.1.2). + // Serializes a parameter list ([RFC8941] 4.1.1.2). for (const auto& param_name_and_value : value) { const std::string& param_name = param_name_and_value.first; const Item& param_value = param_name_and_value.second; @@ -743,10 +753,10 @@ } bool WriteKey(const std::string& value) { - // Serializes a Key ([SH15] 4.1.1.3). + // Serializes a Key ([RFC8941] 4.1.1.3). if (!value.size()) return false; - if (value.find_first_not_of(kKeyChars15) != std::string::npos) + if (value.find_first_not_of(kKeyChars) != std::string::npos) return false; if (!base::IsAsciiLower(value[0]) && value[0] != '*') return false; @@ -894,7 +904,7 @@ } absl::optional<ParameterizedItem> ParseItem(base::StringPiece str) { - StructuredHeaderParser parser(str, StructuredHeaderParser::kDraft15); + StructuredHeaderParser parser(str, StructuredHeaderParser::kFinal); absl::optional<ParameterizedItem> item = parser.ReadItem(); if (item && parser.FinishParsing()) return item; @@ -902,7 +912,7 @@ } absl::optional<Item> ParseBareItem(base::StringPiece str) { - StructuredHeaderParser parser(str, StructuredHeaderParser::kDraft15); + StructuredHeaderParser parser(str, StructuredHeaderParser::kFinal); absl::optional<Item> item = parser.ReadBareItem(); if (item && parser.FinishParsing()) return item; @@ -927,7 +937,7 @@ } absl::optional<List> ParseList(base::StringPiece str) { - StructuredHeaderParser parser(str, StructuredHeaderParser::kDraft15); + StructuredHeaderParser parser(str, StructuredHeaderParser::kFinal); absl::optional<List> list = parser.ReadList(); if (list && parser.FinishParsing()) return list; @@ -935,7 +945,7 @@ } absl::optional<Dictionary> ParseDictionary(const base::StringPiece& str) { - StructuredHeaderParser parser(str, StructuredHeaderParser::kDraft15); + StructuredHeaderParser parser(str, StructuredHeaderParser::kFinal); absl::optional<Dictionary> dictionary = parser.ReadDictionary(); if (dictionary && parser.FinishParsing()) return dictionary;
diff --git a/net/http/structured_headers.h b/net/http/structured_headers.h index 5292f01..2627246 100644 --- a/net/http/structured_headers.h +++ b/net/http/structured_headers.h
@@ -19,14 +19,19 @@ namespace structured_headers { // This file implements parsing of HTTP structured headers, as defined in -// https://httpwg.org/http-extensions/draft-ietf-httpbis-header-structure.html. +// RFC8941 (https://www.rfc-editor.org/rfc/rfc8941.html). For compatibility with +// the shipped implementation of Web Packaging, this file also supports a +// previous revision of the standard, referred to here as "Draft 9". +// (https://datatracker.ietf.org/doc/draft-ietf-httpbis-header-structure/09/) // -// Both drafts 9 and 15 are currently supported. The major difference -// between the two drafts is in the various list formats: Draft 9 describes -// Parameterised lists and lists-of-lists, while draft 15 uses a single List -// syntax, whose members may be inner lists. There should be no ambiguity, -// however, as the code which calls this parser should be expecting only a -// single type for a given header. +// The major difference between the two revisions is in the various list +// formats: Draft 9 describes "parameterised lists" and "lists-of-lists", while +// the final RFC uses a single "list" syntax, whose members may be inner lists. +// There should be no ambiguity, however, as the code which calls this parser +// should be expecting only a single type for a given header. +// +// References within the code are tagged with either [SH09] or [RFC8941], +// depending on which revision they refer to. // // Currently supported data types are: // Item:
diff --git a/net/http/structured_headers_generated_unittest.cc b/net/http/structured_headers_generated_unittest.cc index f2250839..82d1e01 100644 --- a/net/http/structured_headers_generated_unittest.cc +++ b/net/http/structured_headers_generated_unittest.cc
@@ -13,14 +13,14 @@ // This file contains tests cases for the Structured Header parser and // serializer, taken from the public test case repository at -// https://github.com/httpwg/structured-header-tests. All of the tests are -// named, so a given test case can be found in the JSON files in that repository -// by searching for the test name. This file is generated, with the test cases +// https://github.com/httpwg/structured-field-tests. All of the tests are named, +// so a given test case can be found in the JSON files in that repository by +// searching for the test name. This file is generated, with the test cases // being automatically translated from the JSON source to C++ unit tests. Please // do not modify, as the contents will be overwritten when this is re-generated. -// Generated on 2020-04-10 from structured-header-tests.git @ -// 0a8ab1b649080239abb21ecd3ca15a4aead419aa +// Generated on 2022-03-05 from structured-field-tests.git @ +// 4d33b9c2f4e0a7d7d1d733ccf48783aaead8ca4d namespace net { namespace structured_headers { @@ -129,8 +129,8 @@ {"Example-BoolHdr", "?1", 2, {{Item(true), {}}}}, // item.json {"empty item", "", 0, absl::nullopt}, - {"leading space", " 1", 3, {{Integer(1), {}}}, "1"}, - {"trailing space", "1 ", 3, {{Integer(1), {}}}, "1"}, + {"leading space", " \t 1", 4, absl::nullopt}, + {"trailing space", "1 \t ", 4, absl::nullopt}, {"leading and trailing space", " 1 ", 5, {{Integer(1), {}}}, "1"}, {"leading and trailing whitespace", " 1 ", 8, {{Integer(1), {}}}, "1"}, // number-generated.json @@ -836,7 +836,6 @@ // number.json {"basic integer", "42", 2, {{Integer(42), {}}}}, {"zero integer", "0", 1, {{Integer(0), {}}}}, - {"leading 0 zero", "00", 2, {{Integer(0), {}}}, "0"}, {"negative zero", "-0", 2, {{Integer(0), {}}}, "0"}, {"double negative zero", "--0", 3, absl::nullopt}, {"negative integer", "-42", 3, {{Integer(-42), {}}}}, @@ -1009,134 +1008,134 @@ {"0x7d in string", "\" } \"", 5, {{Item(" } "), {}}}}, {"0x7e in string", "\" ~ \"", 5, {{Item(" ~ "), {}}}}, {"0x7f in string", "\" \177 \"", 5, absl::nullopt}, - {"0x00 in string", "\"\\\000\"", 4, absl::nullopt}, - {"0x01 in string", "\"\\\001\"", 4, absl::nullopt}, - {"0x02 in string", "\"\\\002\"", 4, absl::nullopt}, - {"0x03 in string", "\"\\\003\"", 4, absl::nullopt}, - {"0x04 in string", "\"\\\004\"", 4, absl::nullopt}, - {"0x05 in string", "\"\\\005\"", 4, absl::nullopt}, - {"0x06 in string", "\"\\\006\"", 4, absl::nullopt}, - {"0x07 in string", "\"\\\a\"", 4, absl::nullopt}, - {"0x08 in string", "\"\\\b\"", 4, absl::nullopt}, - {"0x09 in string", "\"\\\t\"", 4, absl::nullopt}, - {"0x0a in string", "\"\\\n\"", 4, absl::nullopt}, - {"0x0b in string", "\"\\\v\"", 4, absl::nullopt}, - {"0x0c in string", "\"\\\f\"", 4, absl::nullopt}, - {"0x0d in string", "\"\\\r\"", 4, absl::nullopt}, - {"0x0e in string", "\"\\\016\"", 4, absl::nullopt}, - {"0x0f in string", "\"\\\017\"", 4, absl::nullopt}, - {"0x10 in string", "\"\\\020\"", 4, absl::nullopt}, - {"0x11 in string", "\"\\\021\"", 4, absl::nullopt}, - {"0x12 in string", "\"\\\022\"", 4, absl::nullopt}, - {"0x13 in string", "\"\\\023\"", 4, absl::nullopt}, - {"0x14 in string", "\"\\\024\"", 4, absl::nullopt}, - {"0x15 in string", "\"\\\025\"", 4, absl::nullopt}, - {"0x16 in string", "\"\\\026\"", 4, absl::nullopt}, - {"0x17 in string", "\"\\\027\"", 4, absl::nullopt}, - {"0x18 in string", "\"\\\030\"", 4, absl::nullopt}, - {"0x19 in string", "\"\\\031\"", 4, absl::nullopt}, - {"0x1a in string", "\"\\\032\"", 4, absl::nullopt}, - {"0x1b in string", "\"\\\033\"", 4, absl::nullopt}, - {"0x1c in string", "\"\\\034\"", 4, absl::nullopt}, - {"0x1d in string", "\"\\\035\"", 4, absl::nullopt}, - {"0x1e in string", "\"\\\036\"", 4, absl::nullopt}, - {"0x1f in string", "\"\\\037\"", 4, absl::nullopt}, - {"0x20 in string", "\"\\ \"", 4, absl::nullopt}, - {"0x21 in string", "\"\\!\"", 4, absl::nullopt}, - {"0x22 in string", "\"\\\"\"", 4, {{Item("\""), {}}}}, - {"0x23 in string", "\"\\#\"", 4, absl::nullopt}, - {"0x24 in string", "\"\\$\"", 4, absl::nullopt}, - {"0x25 in string", "\"\\%\"", 4, absl::nullopt}, - {"0x26 in string", "\"\\&\"", 4, absl::nullopt}, - {"0x27 in string", "\"\\'\"", 4, absl::nullopt}, - {"0x28 in string", "\"\\(\"", 4, absl::nullopt}, - {"0x29 in string", "\"\\)\"", 4, absl::nullopt}, - {"0x2a in string", "\"\\*\"", 4, absl::nullopt}, - {"0x2b in string", "\"\\+\"", 4, absl::nullopt}, - {"0x2c in string", "\"\\,\"", 4, absl::nullopt}, - {"0x2d in string", "\"\\-\"", 4, absl::nullopt}, - {"0x2e in string", "\"\\.\"", 4, absl::nullopt}, - {"0x2f in string", "\"\\/\"", 4, absl::nullopt}, - {"0x30 in string", "\"\\0\"", 4, absl::nullopt}, - {"0x31 in string", "\"\\1\"", 4, absl::nullopt}, - {"0x32 in string", "\"\\2\"", 4, absl::nullopt}, - {"0x33 in string", "\"\\3\"", 4, absl::nullopt}, - {"0x34 in string", "\"\\4\"", 4, absl::nullopt}, - {"0x35 in string", "\"\\5\"", 4, absl::nullopt}, - {"0x36 in string", "\"\\6\"", 4, absl::nullopt}, - {"0x37 in string", "\"\\7\"", 4, absl::nullopt}, - {"0x38 in string", "\"\\8\"", 4, absl::nullopt}, - {"0x39 in string", "\"\\9\"", 4, absl::nullopt}, - {"0x3a in string", "\"\\:\"", 4, absl::nullopt}, - {"0x3b in string", "\"\\;\"", 4, absl::nullopt}, - {"0x3c in string", "\"\\<\"", 4, absl::nullopt}, - {"0x3d in string", "\"\\=\"", 4, absl::nullopt}, - {"0x3e in string", "\"\\>\"", 4, absl::nullopt}, - {"0x3f in string", "\"\\?\"", 4, absl::nullopt}, - {"0x40 in string", "\"\\@\"", 4, absl::nullopt}, - {"0x41 in string", "\"\\A\"", 4, absl::nullopt}, - {"0x42 in string", "\"\\B\"", 4, absl::nullopt}, - {"0x43 in string", "\"\\C\"", 4, absl::nullopt}, - {"0x44 in string", "\"\\D\"", 4, absl::nullopt}, - {"0x45 in string", "\"\\E\"", 4, absl::nullopt}, - {"0x46 in string", "\"\\F\"", 4, absl::nullopt}, - {"0x47 in string", "\"\\G\"", 4, absl::nullopt}, - {"0x48 in string", "\"\\H\"", 4, absl::nullopt}, - {"0x49 in string", "\"\\I\"", 4, absl::nullopt}, - {"0x4a in string", "\"\\J\"", 4, absl::nullopt}, - {"0x4b in string", "\"\\K\"", 4, absl::nullopt}, - {"0x4c in string", "\"\\L\"", 4, absl::nullopt}, - {"0x4d in string", "\"\\M\"", 4, absl::nullopt}, - {"0x4e in string", "\"\\N\"", 4, absl::nullopt}, - {"0x4f in string", "\"\\O\"", 4, absl::nullopt}, - {"0x50 in string", "\"\\P\"", 4, absl::nullopt}, - {"0x51 in string", "\"\\Q\"", 4, absl::nullopt}, - {"0x52 in string", "\"\\R\"", 4, absl::nullopt}, - {"0x53 in string", "\"\\S\"", 4, absl::nullopt}, - {"0x54 in string", "\"\\T\"", 4, absl::nullopt}, - {"0x55 in string", "\"\\U\"", 4, absl::nullopt}, - {"0x56 in string", "\"\\V\"", 4, absl::nullopt}, - {"0x57 in string", "\"\\W\"", 4, absl::nullopt}, - {"0x58 in string", "\"\\X\"", 4, absl::nullopt}, - {"0x59 in string", "\"\\Y\"", 4, absl::nullopt}, - {"0x5a in string", "\"\\Z\"", 4, absl::nullopt}, - {"0x5b in string", "\"\\[\"", 4, absl::nullopt}, - {"0x5c in string", "\"\\\\\"", 4, {{Item("\\"), {}}}}, - {"0x5d in string", "\"\\]\"", 4, absl::nullopt}, - {"0x5e in string", "\"\\^\"", 4, absl::nullopt}, - {"0x5f in string", "\"\\_\"", 4, absl::nullopt}, - {"0x60 in string", "\"\\`\"", 4, absl::nullopt}, - {"0x61 in string", "\"\\a\"", 4, absl::nullopt}, - {"0x62 in string", "\"\\b\"", 4, absl::nullopt}, - {"0x63 in string", "\"\\c\"", 4, absl::nullopt}, - {"0x64 in string", "\"\\d\"", 4, absl::nullopt}, - {"0x65 in string", "\"\\e\"", 4, absl::nullopt}, - {"0x66 in string", "\"\\f\"", 4, absl::nullopt}, - {"0x67 in string", "\"\\g\"", 4, absl::nullopt}, - {"0x68 in string", "\"\\h\"", 4, absl::nullopt}, - {"0x69 in string", "\"\\i\"", 4, absl::nullopt}, - {"0x6a in string", "\"\\j\"", 4, absl::nullopt}, - {"0x6b in string", "\"\\k\"", 4, absl::nullopt}, - {"0x6c in string", "\"\\l\"", 4, absl::nullopt}, - {"0x6d in string", "\"\\m\"", 4, absl::nullopt}, - {"0x6e in string", "\"\\n\"", 4, absl::nullopt}, - {"0x6f in string", "\"\\o\"", 4, absl::nullopt}, - {"0x70 in string", "\"\\p\"", 4, absl::nullopt}, - {"0x71 in string", "\"\\q\"", 4, absl::nullopt}, - {"0x72 in string", "\"\\r\"", 4, absl::nullopt}, - {"0x73 in string", "\"\\s\"", 4, absl::nullopt}, - {"0x74 in string", "\"\\t\"", 4, absl::nullopt}, - {"0x75 in string", "\"\\u\"", 4, absl::nullopt}, - {"0x76 in string", "\"\\v\"", 4, absl::nullopt}, - {"0x77 in string", "\"\\w\"", 4, absl::nullopt}, - {"0x78 in string", "\"\\x\"", 4, absl::nullopt}, - {"0x79 in string", "\"\\y\"", 4, absl::nullopt}, - {"0x7a in string", "\"\\z\"", 4, absl::nullopt}, - {"0x7b in string", "\"\\{\"", 4, absl::nullopt}, - {"0x7c in string", "\"\\|\"", 4, absl::nullopt}, - {"0x7d in string", "\"\\}\"", 4, absl::nullopt}, - {"0x7e in string", "\"\\~\"", 4, absl::nullopt}, - {"0x7f in string", "\"\\\177\"", 4, absl::nullopt}, + {"Escaped 0x00 in string", "\"\\\000\"", 4, absl::nullopt}, + {"Escaped 0x01 in string", "\"\\\001\"", 4, absl::nullopt}, + {"Escaped 0x02 in string", "\"\\\002\"", 4, absl::nullopt}, + {"Escaped 0x03 in string", "\"\\\003\"", 4, absl::nullopt}, + {"Escaped 0x04 in string", "\"\\\004\"", 4, absl::nullopt}, + {"Escaped 0x05 in string", "\"\\\005\"", 4, absl::nullopt}, + {"Escaped 0x06 in string", "\"\\\006\"", 4, absl::nullopt}, + {"Escaped 0x07 in string", "\"\\\a\"", 4, absl::nullopt}, + {"Escaped 0x08 in string", "\"\\\b\"", 4, absl::nullopt}, + {"Escaped 0x09 in string", "\"\\\t\"", 4, absl::nullopt}, + {"Escaped 0x0a in string", "\"\\\n\"", 4, absl::nullopt}, + {"Escaped 0x0b in string", "\"\\\v\"", 4, absl::nullopt}, + {"Escaped 0x0c in string", "\"\\\f\"", 4, absl::nullopt}, + {"Escaped 0x0d in string", "\"\\\r\"", 4, absl::nullopt}, + {"Escaped 0x0e in string", "\"\\\016\"", 4, absl::nullopt}, + {"Escaped 0x0f in string", "\"\\\017\"", 4, absl::nullopt}, + {"Escaped 0x10 in string", "\"\\\020\"", 4, absl::nullopt}, + {"Escaped 0x11 in string", "\"\\\021\"", 4, absl::nullopt}, + {"Escaped 0x12 in string", "\"\\\022\"", 4, absl::nullopt}, + {"Escaped 0x13 in string", "\"\\\023\"", 4, absl::nullopt}, + {"Escaped 0x14 in string", "\"\\\024\"", 4, absl::nullopt}, + {"Escaped 0x15 in string", "\"\\\025\"", 4, absl::nullopt}, + {"Escaped 0x16 in string", "\"\\\026\"", 4, absl::nullopt}, + {"Escaped 0x17 in string", "\"\\\027\"", 4, absl::nullopt}, + {"Escaped 0x18 in string", "\"\\\030\"", 4, absl::nullopt}, + {"Escaped 0x19 in string", "\"\\\031\"", 4, absl::nullopt}, + {"Escaped 0x1a in string", "\"\\\032\"", 4, absl::nullopt}, + {"Escaped 0x1b in string", "\"\\\033\"", 4, absl::nullopt}, + {"Escaped 0x1c in string", "\"\\\034\"", 4, absl::nullopt}, + {"Escaped 0x1d in string", "\"\\\035\"", 4, absl::nullopt}, + {"Escaped 0x1e in string", "\"\\\036\"", 4, absl::nullopt}, + {"Escaped 0x1f in string", "\"\\\037\"", 4, absl::nullopt}, + {"Escaped 0x20 in string", "\"\\ \"", 4, absl::nullopt}, + {"Escaped 0x21 in string", "\"\\!\"", 4, absl::nullopt}, + {"Escaped 0x22 in string", "\"\\\"\"", 4, {{Item("\""), {}}}}, + {"Escaped 0x23 in string", "\"\\#\"", 4, absl::nullopt}, + {"Escaped 0x24 in string", "\"\\$\"", 4, absl::nullopt}, + {"Escaped 0x25 in string", "\"\\%\"", 4, absl::nullopt}, + {"Escaped 0x26 in string", "\"\\&\"", 4, absl::nullopt}, + {"Escaped 0x27 in string", "\"\\'\"", 4, absl::nullopt}, + {"Escaped 0x28 in string", "\"\\(\"", 4, absl::nullopt}, + {"Escaped 0x29 in string", "\"\\)\"", 4, absl::nullopt}, + {"Escaped 0x2a in string", "\"\\*\"", 4, absl::nullopt}, + {"Escaped 0x2b in string", "\"\\+\"", 4, absl::nullopt}, + {"Escaped 0x2c in string", "\"\\,\"", 4, absl::nullopt}, + {"Escaped 0x2d in string", "\"\\-\"", 4, absl::nullopt}, + {"Escaped 0x2e in string", "\"\\.\"", 4, absl::nullopt}, + {"Escaped 0x2f in string", "\"\\/\"", 4, absl::nullopt}, + {"Escaped 0x30 in string", "\"\\0\"", 4, absl::nullopt}, + {"Escaped 0x31 in string", "\"\\1\"", 4, absl::nullopt}, + {"Escaped 0x32 in string", "\"\\2\"", 4, absl::nullopt}, + {"Escaped 0x33 in string", "\"\\3\"", 4, absl::nullopt}, + {"Escaped 0x34 in string", "\"\\4\"", 4, absl::nullopt}, + {"Escaped 0x35 in string", "\"\\5\"", 4, absl::nullopt}, + {"Escaped 0x36 in string", "\"\\6\"", 4, absl::nullopt}, + {"Escaped 0x37 in string", "\"\\7\"", 4, absl::nullopt}, + {"Escaped 0x38 in string", "\"\\8\"", 4, absl::nullopt}, + {"Escaped 0x39 in string", "\"\\9\"", 4, absl::nullopt}, + {"Escaped 0x3a in string", "\"\\:\"", 4, absl::nullopt}, + {"Escaped 0x3b in string", "\"\\;\"", 4, absl::nullopt}, + {"Escaped 0x3c in string", "\"\\<\"", 4, absl::nullopt}, + {"Escaped 0x3d in string", "\"\\=\"", 4, absl::nullopt}, + {"Escaped 0x3e in string", "\"\\>\"", 4, absl::nullopt}, + {"Escaped 0x3f in string", "\"\\?\"", 4, absl::nullopt}, + {"Escaped 0x40 in string", "\"\\@\"", 4, absl::nullopt}, + {"Escaped 0x41 in string", "\"\\A\"", 4, absl::nullopt}, + {"Escaped 0x42 in string", "\"\\B\"", 4, absl::nullopt}, + {"Escaped 0x43 in string", "\"\\C\"", 4, absl::nullopt}, + {"Escaped 0x44 in string", "\"\\D\"", 4, absl::nullopt}, + {"Escaped 0x45 in string", "\"\\E\"", 4, absl::nullopt}, + {"Escaped 0x46 in string", "\"\\F\"", 4, absl::nullopt}, + {"Escaped 0x47 in string", "\"\\G\"", 4, absl::nullopt}, + {"Escaped 0x48 in string", "\"\\H\"", 4, absl::nullopt}, + {"Escaped 0x49 in string", "\"\\I\"", 4, absl::nullopt}, + {"Escaped 0x4a in string", "\"\\J\"", 4, absl::nullopt}, + {"Escaped 0x4b in string", "\"\\K\"", 4, absl::nullopt}, + {"Escaped 0x4c in string", "\"\\L\"", 4, absl::nullopt}, + {"Escaped 0x4d in string", "\"\\M\"", 4, absl::nullopt}, + {"Escaped 0x4e in string", "\"\\N\"", 4, absl::nullopt}, + {"Escaped 0x4f in string", "\"\\O\"", 4, absl::nullopt}, + {"Escaped 0x50 in string", "\"\\P\"", 4, absl::nullopt}, + {"Escaped 0x51 in string", "\"\\Q\"", 4, absl::nullopt}, + {"Escaped 0x52 in string", "\"\\R\"", 4, absl::nullopt}, + {"Escaped 0x53 in string", "\"\\S\"", 4, absl::nullopt}, + {"Escaped 0x54 in string", "\"\\T\"", 4, absl::nullopt}, + {"Escaped 0x55 in string", "\"\\U\"", 4, absl::nullopt}, + {"Escaped 0x56 in string", "\"\\V\"", 4, absl::nullopt}, + {"Escaped 0x57 in string", "\"\\W\"", 4, absl::nullopt}, + {"Escaped 0x58 in string", "\"\\X\"", 4, absl::nullopt}, + {"Escaped 0x59 in string", "\"\\Y\"", 4, absl::nullopt}, + {"Escaped 0x5a in string", "\"\\Z\"", 4, absl::nullopt}, + {"Escaped 0x5b in string", "\"\\[\"", 4, absl::nullopt}, + {"Escaped 0x5c in string", "\"\\\\\"", 4, {{Item("\\"), {}}}}, + {"Escaped 0x5d in string", "\"\\]\"", 4, absl::nullopt}, + {"Escaped 0x5e in string", "\"\\^\"", 4, absl::nullopt}, + {"Escaped 0x5f in string", "\"\\_\"", 4, absl::nullopt}, + {"Escaped 0x60 in string", "\"\\`\"", 4, absl::nullopt}, + {"Escaped 0x61 in string", "\"\\a\"", 4, absl::nullopt}, + {"Escaped 0x62 in string", "\"\\b\"", 4, absl::nullopt}, + {"Escaped 0x63 in string", "\"\\c\"", 4, absl::nullopt}, + {"Escaped 0x64 in string", "\"\\d\"", 4, absl::nullopt}, + {"Escaped 0x65 in string", "\"\\e\"", 4, absl::nullopt}, + {"Escaped 0x66 in string", "\"\\f\"", 4, absl::nullopt}, + {"Escaped 0x67 in string", "\"\\g\"", 4, absl::nullopt}, + {"Escaped 0x68 in string", "\"\\h\"", 4, absl::nullopt}, + {"Escaped 0x69 in string", "\"\\i\"", 4, absl::nullopt}, + {"Escaped 0x6a in string", "\"\\j\"", 4, absl::nullopt}, + {"Escaped 0x6b in string", "\"\\k\"", 4, absl::nullopt}, + {"Escaped 0x6c in string", "\"\\l\"", 4, absl::nullopt}, + {"Escaped 0x6d in string", "\"\\m\"", 4, absl::nullopt}, + {"Escaped 0x6e in string", "\"\\n\"", 4, absl::nullopt}, + {"Escaped 0x6f in string", "\"\\o\"", 4, absl::nullopt}, + {"Escaped 0x70 in string", "\"\\p\"", 4, absl::nullopt}, + {"Escaped 0x71 in string", "\"\\q\"", 4, absl::nullopt}, + {"Escaped 0x72 in string", "\"\\r\"", 4, absl::nullopt}, + {"Escaped 0x73 in string", "\"\\s\"", 4, absl::nullopt}, + {"Escaped 0x74 in string", "\"\\t\"", 4, absl::nullopt}, + {"Escaped 0x75 in string", "\"\\u\"", 4, absl::nullopt}, + {"Escaped 0x76 in string", "\"\\v\"", 4, absl::nullopt}, + {"Escaped 0x77 in string", "\"\\w\"", 4, absl::nullopt}, + {"Escaped 0x78 in string", "\"\\x\"", 4, absl::nullopt}, + {"Escaped 0x79 in string", "\"\\y\"", 4, absl::nullopt}, + {"Escaped 0x7a in string", "\"\\z\"", 4, absl::nullopt}, + {"Escaped 0x7b in string", "\"\\{\"", 4, absl::nullopt}, + {"Escaped 0x7c in string", "\"\\|\"", 4, absl::nullopt}, + {"Escaped 0x7d in string", "\"\\}\"", 4, absl::nullopt}, + {"Escaped 0x7e in string", "\"\\~\"", 4, absl::nullopt}, + {"Escaped 0x7f in string", "\"\\\177\"", 4, absl::nullopt}, // string.json {"basic string", "\"foo bar\"", 9, {{Item("foo bar"), {}}}}, {"empty string", "\"\"", 2, {{Item(""), {}}}}, @@ -1453,8 +1452,6 @@ // format is identical to raw. } list_test_cases[] = { - // dictionary.json - {"tab separated dictionary", "a=1\t,\tb=2", 9, absl::nullopt}, // examples.json {"Example-StrListHeader", "\"foo\", \"bar\", \"It was the best of times.\"", @@ -2073,7 +2070,11 @@ 6, {{{Integer(1), {}}, {Integer(42), {}}}}, "1, 42"}, - {"tab separated list", "1\t,\t42", 6, absl::nullopt}, + {"tab separated list", + "1\t,\t42", + 6, + {{{Integer(1), {}}, {Integer(42), {}}}}, + "1, 42"}, {"two line list", "1, 42", 5, @@ -2081,6 +2082,7 @@ "1, 42"}, {"trailing comma list", "1, 42,", 6, absl::nullopt}, {"empty item list", "1,,42", 5, absl::nullopt}, + {"empty item list (multiple field lines)", "1, , 42", 7, absl::nullopt}, // listlist.json {"basic list of lists", "(1 2), (42 43)", @@ -2110,6 +2112,7 @@ absl::nullopt}, {"no spaces in inner-list", "(abc\"def\"?0123*dXZ3*xyz)", 24, absl::nullopt}, + {"no closing parenthesis", "(", 1, absl::nullopt}, // param-list.json {"basic parameterised list", "abc_123;a=1;b=2; cdef_456, ghi;q=9;r=\"+w\"", @@ -2167,6 +2170,24 @@ absl::nullopt}, {"empty item parameterised list", "text/html,,text/plain;q=0.5,", 28, absl::nullopt}, + // param-listlist.json + {"parameterised inner list", + "(abc_123);a=1;b=2, cdef_456", + 27, + {{{{{Item("abc_123", Item::kTokenType), {}}}, + {Param("a", 1), Param("b", 2)}}, + {Item("cdef_456", Item::kTokenType), {}}}}}, + {"parameterised inner list item", + "(abc_123;a=1;b=2;cdef_456)", + 26, + {{{{{Item("abc_123", Item::kTokenType), + {Param("a", 1), Param("b", 2), BooleanParam("cdef_456", true)}}}, + {}}}}}, + {"parameterised inner list with parameterised item", + "(abc_123;a=1;b=2);cdef_456", + 26, + {{{{{Item("abc_123", Item::kTokenType), {Param("a", 1), Param("b", 2)}}}, + {BooleanParam("cdef_456", true)}}}}}, // token.json {"basic token - list", "a_b-c3/*", @@ -2227,6 +2248,11 @@ 10, {Dictionary{{{"a", {Integer(1), {}}}, {"b", {Integer(2), {}}}}}}, "a=1, b=2"}, + {"tab separated dictionary", + "a=1\t,\tb=2", + 9, + {Dictionary{{{"a", {Integer(1), {}}}, {"b", {Integer(2), {}}}}}}, + "a=1, b=2"}, {"leading whitespace dictionary", " a=1 , b=2", 15, @@ -2325,6 +2351,215 @@ {Dictionary{{{"foo", {Integer(1), {}}}, {"bar", {Integer(2), {}}}}}}, "foo=1, bar=2"}, // key-generated.json + {"0x00 as a single-character dictionary key", "\000=1", 3, absl::nullopt}, + {"0x01 as a single-character dictionary key", "\001=1", 3, absl::nullopt}, + {"0x02 as a single-character dictionary key", "\002=1", 3, absl::nullopt}, + {"0x03 as a single-character dictionary key", "\003=1", 3, absl::nullopt}, + {"0x04 as a single-character dictionary key", "\004=1", 3, absl::nullopt}, + {"0x05 as a single-character dictionary key", "\005=1", 3, absl::nullopt}, + {"0x06 as a single-character dictionary key", "\006=1", 3, absl::nullopt}, + {"0x07 as a single-character dictionary key", "\a=1", 3, absl::nullopt}, + {"0x08 as a single-character dictionary key", "\b=1", 3, absl::nullopt}, + {"0x09 as a single-character dictionary key", "\t=1", 3, absl::nullopt}, + {"0x0a as a single-character dictionary key", "\n=1", 3, absl::nullopt}, + {"0x0b as a single-character dictionary key", "\v=1", 3, absl::nullopt}, + {"0x0c as a single-character dictionary key", "\f=1", 3, absl::nullopt}, + {"0x0d as a single-character dictionary key", "\r=1", 3, absl::nullopt}, + {"0x0e as a single-character dictionary key", "\016=1", 3, absl::nullopt}, + {"0x0f as a single-character dictionary key", "\017=1", 3, absl::nullopt}, + {"0x10 as a single-character dictionary key", "\020=1", 3, absl::nullopt}, + {"0x11 as a single-character dictionary key", "\021=1", 3, absl::nullopt}, + {"0x12 as a single-character dictionary key", "\022=1", 3, absl::nullopt}, + {"0x13 as a single-character dictionary key", "\023=1", 3, absl::nullopt}, + {"0x14 as a single-character dictionary key", "\024=1", 3, absl::nullopt}, + {"0x15 as a single-character dictionary key", "\025=1", 3, absl::nullopt}, + {"0x16 as a single-character dictionary key", "\026=1", 3, absl::nullopt}, + {"0x17 as a single-character dictionary key", "\027=1", 3, absl::nullopt}, + {"0x18 as a single-character dictionary key", "\030=1", 3, absl::nullopt}, + {"0x19 as a single-character dictionary key", "\031=1", 3, absl::nullopt}, + {"0x1a as a single-character dictionary key", "\032=1", 3, absl::nullopt}, + {"0x1b as a single-character dictionary key", "\033=1", 3, absl::nullopt}, + {"0x1c as a single-character dictionary key", "\034=1", 3, absl::nullopt}, + {"0x1d as a single-character dictionary key", "\035=1", 3, absl::nullopt}, + {"0x1e as a single-character dictionary key", "\036=1", 3, absl::nullopt}, + {"0x1f as a single-character dictionary key", "\037=1", 3, absl::nullopt}, + {"0x20 as a single-character dictionary key", "=1", 2, absl::nullopt}, + {"0x21 as a single-character dictionary key", "!=1", 3, absl::nullopt}, + {"0x22 as a single-character dictionary key", "\"=1", 3, absl::nullopt}, + {"0x23 as a single-character dictionary key", "#=1", 3, absl::nullopt}, + {"0x24 as a single-character dictionary key", "$=1", 3, absl::nullopt}, + {"0x25 as a single-character dictionary key", "%=1", 3, absl::nullopt}, + {"0x26 as a single-character dictionary key", "&=1", 3, absl::nullopt}, + {"0x27 as a single-character dictionary key", "'=1", 3, absl::nullopt}, + {"0x28 as a single-character dictionary key", "(=1", 3, absl::nullopt}, + {"0x29 as a single-character dictionary key", ")=1", 3, absl::nullopt}, + {"0x2a as a single-character dictionary key", + "*=1", + 3, + {Dictionary{{{"*", {Integer(1), {}}}}}}}, + {"0x2b as a single-character dictionary key", "+=1", 3, absl::nullopt}, + {"0x2c as a single-character dictionary key", ",=1", 3, absl::nullopt}, + {"0x2d as a single-character dictionary key", "-=1", 3, absl::nullopt}, + {"0x2e as a single-character dictionary key", ".=1", 3, absl::nullopt}, + {"0x2f as a single-character dictionary key", "/=1", 3, absl::nullopt}, + {"0x30 as a single-character dictionary key", "0=1", 3, absl::nullopt}, + {"0x31 as a single-character dictionary key", "1=1", 3, absl::nullopt}, + {"0x32 as a single-character dictionary key", "2=1", 3, absl::nullopt}, + {"0x33 as a single-character dictionary key", "3=1", 3, absl::nullopt}, + {"0x34 as a single-character dictionary key", "4=1", 3, absl::nullopt}, + {"0x35 as a single-character dictionary key", "5=1", 3, absl::nullopt}, + {"0x36 as a single-character dictionary key", "6=1", 3, absl::nullopt}, + {"0x37 as a single-character dictionary key", "7=1", 3, absl::nullopt}, + {"0x38 as a single-character dictionary key", "8=1", 3, absl::nullopt}, + {"0x39 as a single-character dictionary key", "9=1", 3, absl::nullopt}, + {"0x3a as a single-character dictionary key", ":=1", 3, absl::nullopt}, + {"0x3b as a single-character dictionary key", ";=1", 3, absl::nullopt}, + {"0x3c as a single-character dictionary key", "<=1", 3, absl::nullopt}, + {"0x3d as a single-character dictionary key", "==1", 3, absl::nullopt}, + {"0x3e as a single-character dictionary key", ">=1", 3, absl::nullopt}, + {"0x3f as a single-character dictionary key", "?=1", 3, absl::nullopt}, + {"0x40 as a single-character dictionary key", "@=1", 3, absl::nullopt}, + {"0x41 as a single-character dictionary key", "A=1", 3, absl::nullopt}, + {"0x42 as a single-character dictionary key", "B=1", 3, absl::nullopt}, + {"0x43 as a single-character dictionary key", "C=1", 3, absl::nullopt}, + {"0x44 as a single-character dictionary key", "D=1", 3, absl::nullopt}, + {"0x45 as a single-character dictionary key", "E=1", 3, absl::nullopt}, + {"0x46 as a single-character dictionary key", "F=1", 3, absl::nullopt}, + {"0x47 as a single-character dictionary key", "G=1", 3, absl::nullopt}, + {"0x48 as a single-character dictionary key", "H=1", 3, absl::nullopt}, + {"0x49 as a single-character dictionary key", "I=1", 3, absl::nullopt}, + {"0x4a as a single-character dictionary key", "J=1", 3, absl::nullopt}, + {"0x4b as a single-character dictionary key", "K=1", 3, absl::nullopt}, + {"0x4c as a single-character dictionary key", "L=1", 3, absl::nullopt}, + {"0x4d as a single-character dictionary key", "M=1", 3, absl::nullopt}, + {"0x4e as a single-character dictionary key", "N=1", 3, absl::nullopt}, + {"0x4f as a single-character dictionary key", "O=1", 3, absl::nullopt}, + {"0x50 as a single-character dictionary key", "P=1", 3, absl::nullopt}, + {"0x51 as a single-character dictionary key", "Q=1", 3, absl::nullopt}, + {"0x52 as a single-character dictionary key", "R=1", 3, absl::nullopt}, + {"0x53 as a single-character dictionary key", "S=1", 3, absl::nullopt}, + {"0x54 as a single-character dictionary key", "T=1", 3, absl::nullopt}, + {"0x55 as a single-character dictionary key", "U=1", 3, absl::nullopt}, + {"0x56 as a single-character dictionary key", "V=1", 3, absl::nullopt}, + {"0x57 as a single-character dictionary key", "W=1", 3, absl::nullopt}, + {"0x58 as a single-character dictionary key", "X=1", 3, absl::nullopt}, + {"0x59 as a single-character dictionary key", "Y=1", 3, absl::nullopt}, + {"0x5a as a single-character dictionary key", "Z=1", 3, absl::nullopt}, + {"0x5b as a single-character dictionary key", "[=1", 3, absl::nullopt}, + {"0x5c as a single-character dictionary key", "\\=1", 3, absl::nullopt}, + {"0x5d as a single-character dictionary key", "]=1", 3, absl::nullopt}, + {"0x5e as a single-character dictionary key", "^=1", 3, absl::nullopt}, + {"0x5f as a single-character dictionary key", "_=1", 3, absl::nullopt}, + {"0x60 as a single-character dictionary key", "`=1", 3, absl::nullopt}, + {"0x61 as a single-character dictionary key", + "a=1", + 3, + {Dictionary{{{"a", {Integer(1), {}}}}}}}, + {"0x62 as a single-character dictionary key", + "b=1", + 3, + {Dictionary{{{"b", {Integer(1), {}}}}}}}, + {"0x63 as a single-character dictionary key", + "c=1", + 3, + {Dictionary{{{"c", {Integer(1), {}}}}}}}, + {"0x64 as a single-character dictionary key", + "d=1", + 3, + {Dictionary{{{"d", {Integer(1), {}}}}}}}, + {"0x65 as a single-character dictionary key", + "e=1", + 3, + {Dictionary{{{"e", {Integer(1), {}}}}}}}, + {"0x66 as a single-character dictionary key", + "f=1", + 3, + {Dictionary{{{"f", {Integer(1), {}}}}}}}, + {"0x67 as a single-character dictionary key", + "g=1", + 3, + {Dictionary{{{"g", {Integer(1), {}}}}}}}, + {"0x68 as a single-character dictionary key", + "h=1", + 3, + {Dictionary{{{"h", {Integer(1), {}}}}}}}, + {"0x69 as a single-character dictionary key", + "i=1", + 3, + {Dictionary{{{"i", {Integer(1), {}}}}}}}, + {"0x6a as a single-character dictionary key", + "j=1", + 3, + {Dictionary{{{"j", {Integer(1), {}}}}}}}, + {"0x6b as a single-character dictionary key", + "k=1", + 3, + {Dictionary{{{"k", {Integer(1), {}}}}}}}, + {"0x6c as a single-character dictionary key", + "l=1", + 3, + {Dictionary{{{"l", {Integer(1), {}}}}}}}, + {"0x6d as a single-character dictionary key", + "m=1", + 3, + {Dictionary{{{"m", {Integer(1), {}}}}}}}, + {"0x6e as a single-character dictionary key", + "n=1", + 3, + {Dictionary{{{"n", {Integer(1), {}}}}}}}, + {"0x6f as a single-character dictionary key", + "o=1", + 3, + {Dictionary{{{"o", {Integer(1), {}}}}}}}, + {"0x70 as a single-character dictionary key", + "p=1", + 3, + {Dictionary{{{"p", {Integer(1), {}}}}}}}, + {"0x71 as a single-character dictionary key", + "q=1", + 3, + {Dictionary{{{"q", {Integer(1), {}}}}}}}, + {"0x72 as a single-character dictionary key", + "r=1", + 3, + {Dictionary{{{"r", {Integer(1), {}}}}}}}, + {"0x73 as a single-character dictionary key", + "s=1", + 3, + {Dictionary{{{"s", {Integer(1), {}}}}}}}, + {"0x74 as a single-character dictionary key", + "t=1", + 3, + {Dictionary{{{"t", {Integer(1), {}}}}}}}, + {"0x75 as a single-character dictionary key", + "u=1", + 3, + {Dictionary{{{"u", {Integer(1), {}}}}}}}, + {"0x76 as a single-character dictionary key", + "v=1", + 3, + {Dictionary{{{"v", {Integer(1), {}}}}}}}, + {"0x77 as a single-character dictionary key", + "w=1", + 3, + {Dictionary{{{"w", {Integer(1), {}}}}}}}, + {"0x78 as a single-character dictionary key", + "x=1", + 3, + {Dictionary{{{"x", {Integer(1), {}}}}}}}, + {"0x79 as a single-character dictionary key", + "y=1", + 3, + {Dictionary{{{"y", {Integer(1), {}}}}}}}, + {"0x7a as a single-character dictionary key", + "z=1", + 3, + {Dictionary{{{"z", {Integer(1), {}}}}}}}, + {"0x7b as a single-character dictionary key", "{=1", 3, absl::nullopt}, + {"0x7c as a single-character dictionary key", "|=1", 3, absl::nullopt}, + {"0x7d as a single-character dictionary key", "}=1", 3, absl::nullopt}, + {"0x7e as a single-character dictionary key", "~=1", 3, absl::nullopt}, + {"0x7f as a single-character dictionary key", "\177=1", 3, absl::nullopt}, {"0x00 in dictionary key", "a\000a=1", 5, absl::nullopt}, {"0x01 in dictionary key", "a\001a=1", 5, absl::nullopt}, {"0x02 in dictionary key", "a\002a=1", 5, absl::nullopt},
diff --git a/net/http/structured_headers_unittest.cc b/net/http/structured_headers_unittest.cc index 62b53b0c6..d2848b2b 100644 --- a/net/http/structured_headers_unittest.cc +++ b/net/http/structured_headers_unittest.cc
@@ -236,7 +236,10 @@ "en=\"Applepie\", da=:aGVsbG8=:", {Dictionary{{{"en", {Item("Applepie"), {}}}, {"da", {Item("hello", Item::kByteSequenceType), {}}}}}}}, - {"tab separated dictionary", "a=1\t,\tb=2", absl::nullopt}, + {"tab separated dictionary", + "a=1\t,\tb=2", + {Dictionary{{{"a", {Integer(1L), {}}}, {"b", {Integer(2L), {}}}}}}, + "a=1, b=2"}, {"missing value with params dictionary", "a=1, b;foo=9, c=3", {Dictionary{{{"a", {Integer(1L), {}}},
diff --git a/pdf/BUILD.gn b/pdf/BUILD.gn index a6033b7..4d0d5535 100644 --- a/pdf/BUILD.gn +++ b/pdf/BUILD.gn
@@ -240,8 +240,6 @@ "ppapi_migration/bitmap.h", "ppapi_migration/graphics.cc", "ppapi_migration/graphics.h", - "ppapi_migration/image.cc", - "ppapi_migration/image.h", "ppapi_migration/result_codes.h", "ppapi_migration/url_loader.cc", "ppapi_migration/url_loader.h",
diff --git a/pdf/paint_ready_rect.cc b/pdf/paint_ready_rect.cc index 75afd22..6879f126 100644 --- a/pdf/paint_ready_rect.cc +++ b/pdf/paint_ready_rect.cc
@@ -4,13 +4,13 @@ #include "pdf/paint_ready_rect.h" -#include "pdf/ppapi_migration/image.h" +#include "third_party/skia/include/core/SkBitmap.h" #include "ui/gfx/geometry/rect.h" namespace chrome_pdf { PaintReadyRect::PaintReadyRect(const gfx::Rect& rect, - const Image& image, + const SkBitmap& image, bool flush_now) : rect_(rect), image_(image), flush_now_(flush_now) {}
diff --git a/pdf/paint_ready_rect.h b/pdf/paint_ready_rect.h index 9db2244..121c4b31 100644 --- a/pdf/paint_ready_rect.h +++ b/pdf/paint_ready_rect.h
@@ -5,7 +5,7 @@ #ifndef PDF_PAINT_READY_RECT_H_ #define PDF_PAINT_READY_RECT_H_ -#include "pdf/ppapi_migration/image.h" +#include "third_party/skia/include/core/SkBitmap.h" #include "ui/gfx/geometry/rect.h" namespace chrome_pdf { @@ -16,7 +16,7 @@ class PaintReadyRect { public: PaintReadyRect(const gfx::Rect& rect, - const Image& image, + const SkBitmap& image, bool flush_now = false); PaintReadyRect(const PaintReadyRect& other); @@ -26,7 +26,7 @@ const gfx::Rect& rect() const { return rect_; } void set_rect(const gfx::Rect& rect) { rect_ = rect; } - const Image& image() const { return image_; } + const SkBitmap& image() const { return image_; } // Whether to flush to screen immediately; otherwise, when the rest of the // plugin viewport is ready. @@ -34,7 +34,7 @@ private: gfx::Rect rect_; - Image image_; + SkBitmap image_; bool flush_now_; };
diff --git a/pdf/pdf_view_plugin_base.cc b/pdf/pdf_view_plugin_base.cc index 3504ec47..2b4eca8 100644 --- a/pdf/pdf_view_plugin_base.cc +++ b/pdf/pdf_view_plugin_base.cc
@@ -51,7 +51,6 @@ #include "pdf/pdf_features.h" #include "pdf/pdfium/pdfium_engine.h" #include "pdf/pdfium/pdfium_form_filler.h" -#include "pdf/ppapi_migration/image.h" #include "pdf/ppapi_migration/result_codes.h" #include "pdf/ppapi_migration/url_loader.h" #include "pdf/ui/document_properties.h" @@ -902,8 +901,8 @@ OnGeometryChanged(zoom_, old_device_scale); } -Image PdfViewPluginBase::GetPluginImageData() const { - return Image(image_data_); +SkBitmap PdfViewPluginBase::GetPluginImageData() const { + return image_data_; } void PdfViewPluginBase::RecalculateAreas(double old_zoom,
diff --git a/pdf/pdf_view_plugin_base.h b/pdf/pdf_view_plugin_base.h index b4ca873..d08a3b0 100644 --- a/pdf/pdf_view_plugin_base.h +++ b/pdf/pdf_view_plugin_base.h
@@ -44,7 +44,6 @@ namespace chrome_pdf { -class Image; class PDFiumEngine; class Thumbnail; class UrlLoader; @@ -263,7 +262,7 @@ void OnGeometryChanged(double old_zoom, float old_device_scale); // Returns the plugin-specific image data buffer. - virtual Image GetPluginImageData() const; + virtual SkBitmap GetPluginImageData() const; // Updates the geometry of the plugin and its image data if the plugin rect // or the device scale has changed. `new_plugin_rect` must be in device
diff --git a/pdf/ppapi_migration/graphics.cc b/pdf/ppapi_migration/graphics.cc index 5b41e5b..1f4b9a4 100644 --- a/pdf/ppapi_migration/graphics.cc +++ b/pdf/ppapi_migration/graphics.cc
@@ -15,8 +15,8 @@ #include "base/memory/ptr_util.h" #include "base/notreached.h" #include "base/threading/sequenced_task_runner_handle.h" -#include "pdf/ppapi_migration/image.h" #include "pdf/ppapi_migration/result_codes.h" +#include "third_party/skia/include/core/SkBitmap.h" #include "third_party/skia/include/core/SkCanvas.h" #include "ui/gfx/blit.h" #include "ui/gfx/geometry/point.h" @@ -63,11 +63,14 @@ return true; } -void SkiaGraphics::PaintImage(const Image& image, const gfx::Rect& src_rect) { +void SkiaGraphics::PaintImage(const SkBitmap& image, + const gfx::Rect& src_rect) { SkRect skia_rect = RectToSkRect(src_rect); + + // TODO(crbug.com/1284255): Avoid inefficient `SkBitmap::asImage()`. skia_graphics_->getCanvas()->drawImageRect( - image.skia_image().asImage(), skia_rect, skia_rect, SkSamplingOptions(), - nullptr, SkCanvas::kStrict_SrcRectConstraint); + image.asImage(), skia_rect, skia_rect, SkSamplingOptions(), nullptr, + SkCanvas::kStrict_SrcRectConstraint); } void SkiaGraphics::Scroll(const gfx::Rect& clip, const gfx::Vector2d& amount) {
diff --git a/pdf/ppapi_migration/graphics.h b/pdf/ppapi_migration/graphics.h index 561edf2..0b11bb5 100644 --- a/pdf/ppapi_migration/graphics.h +++ b/pdf/ppapi_migration/graphics.h
@@ -13,6 +13,7 @@ #include "third_party/skia/include/core/SkSurface.h" #include "ui/gfx/geometry/size.h" +class SkBitmap; class SkImage; namespace gfx { @@ -24,8 +25,6 @@ namespace chrome_pdf { -class Image; - // Abstraction for a Pepper or Skia graphics device. // TODO(crbug.com/1099020): Implement the Skia graphics device. class Graphics { @@ -40,7 +39,7 @@ // Paints the `src_rect` region of `image` to the graphics device. The image // must be compatible with the concrete `Graphics` implementation. - virtual void PaintImage(const Image& image, const gfx::Rect& src_rect) = 0; + virtual void PaintImage(const SkBitmap& image, const gfx::Rect& src_rect) = 0; // Shifts the `clip` region of the graphics device by `amount`. virtual void Scroll(const gfx::Rect& clip, const gfx::Vector2d& amount) = 0; @@ -88,7 +87,7 @@ bool Flush(base::OnceClosure callback) override; - void PaintImage(const Image& image, const gfx::Rect& src_rect) override; + void PaintImage(const SkBitmap& image, const gfx::Rect& src_rect) override; void Scroll(const gfx::Rect& clip, const gfx::Vector2d& amount) override; void SetScale(float scale) override;
diff --git a/pdf/ppapi_migration/graphics_unittest.cc b/pdf/ppapi_migration/graphics_unittest.cc index d668624..e2e7a72 100644 --- a/pdf/ppapi_migration/graphics_unittest.cc +++ b/pdf/ppapi_migration/graphics_unittest.cc
@@ -10,7 +10,6 @@ #include "cc/test/pixel_comparator.h" #include "cc/test/pixel_test_utils.h" #include "pdf/ppapi_migration/bitmap.h" -#include "pdf/ppapi_migration/image.h" #include "pdf/test/test_helpers.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" @@ -120,7 +119,7 @@ // Paint a nonuniform SkBitmap to graphics. initial_bitmap_ = CreateNonuniformBitmap(kGraphicsRect.width(), kGraphicsRect.height()); - graphics_->PaintImage(Image(initial_bitmap_), kGraphicsRect); + graphics_->PaintImage(initial_bitmap_, kGraphicsRect); graphics_->Flush(base::DoNothing()); SkBitmap initial_snapshot; ASSERT_TRUE(client_.snapshot->asLegacyBitmap(&initial_snapshot)); @@ -134,7 +133,7 @@ if (!graphics_) return; - graphics_->PaintImage(Image(initial_bitmap_), kGraphicsRect); + graphics_->PaintImage(initial_bitmap_, kGraphicsRect); graphics_->Scroll(kGraphicsRect, scroll_amount); graphics_->Flush(base::DoNothing()); }
diff --git a/pdf/ppapi_migration/image.cc b/pdf/ppapi_migration/image.cc deleted file mode 100644 index 894678d..0000000 --- a/pdf/ppapi_migration/image.cc +++ /dev/null
@@ -1,19 +0,0 @@ -// Copyright 2020 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "pdf/ppapi_migration/image.h" - -#include "third_party/skia/include/core/SkBitmap.h" - -namespace chrome_pdf { - -Image::Image(const SkBitmap& skia_image) : image_(skia_image) {} - -Image::Image(const Image& other) = default; - -Image& Image::operator=(const Image& other) = default; - -Image::~Image() = default; - -} // namespace chrome_pdf
diff --git a/pdf/ppapi_migration/image.h b/pdf/ppapi_migration/image.h deleted file mode 100644 index 58cd53f..0000000 --- a/pdf/ppapi_migration/image.h +++ /dev/null
@@ -1,31 +0,0 @@ -// Copyright 2020 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef PDF_PPAPI_MIGRATION_IMAGE_H_ -#define PDF_PPAPI_MIGRATION_IMAGE_H_ - -#include "third_party/skia/include/core/SkBitmap.h" - -namespace chrome_pdf { - -// Holder for an image in either Pepper or Skia format. -// -// Note that both Pepper and Skia images retain shared ownership of any -// underlying pixel memory, so this class may be copied freely. -class Image final { - public: - explicit Image(const SkBitmap& skia_image); - Image(const Image& other); - Image& operator=(const Image& other); - ~Image(); - - const SkBitmap& skia_image() const { return image_; } - - private: - SkBitmap image_; -}; - -} // namespace chrome_pdf - -#endif // PDF_PPAPI_MIGRATION_IMAGE_H_
diff --git a/pdf/test/test_helpers.cc b/pdf/test/test_helpers.cc index ccf013d1..0a8e502 100644 --- a/pdf/test/test_helpers.cc +++ b/pdf/test/test_helpers.cc
@@ -8,7 +8,6 @@ #include "base/files/file_path.h" #include "base/path_service.h" #include "pdf/ppapi_migration/bitmap.h" -#include "pdf/ppapi_migration/image.h" #include "third_party/skia/include/core/SkBitmap.h" #include "third_party/skia/include/core/SkColor.h" #include "ui/gfx/geometry/skia_conversions.h" @@ -26,10 +25,10 @@ .Append(path); } -Image CreateSkiaImageForTesting(const gfx::Size& size, SkColor color) { +SkBitmap CreateSkiaImageForTesting(const gfx::Size& size, SkColor color) { SkBitmap bitmap = CreateN32PremulSkBitmap(gfx::SizeToSkISize(size)); bitmap.eraseColor(color); - return Image(bitmap); + return bitmap; } } // namespace chrome_pdf
diff --git a/pdf/test/test_helpers.h b/pdf/test/test_helpers.h index e168426..411047a7 100644 --- a/pdf/test/test_helpers.h +++ b/pdf/test/test_helpers.h
@@ -6,9 +6,10 @@ #define PDF_TEST_TEST_HELPERS_H_ #include "base/files/file_path.h" -#include "pdf/ppapi_migration/image.h" #include "third_party/skia/include/core/SkColor.h" +class SkBitmap; + namespace gfx { class Size; } // namespace gfx @@ -20,7 +21,7 @@ base::FilePath GetTestDataFilePath(const base::FilePath& path); // Creates a Skia-format `Image` of a given size filled with a given color. -Image CreateSkiaImageForTesting(const gfx::Size& size, SkColor color); +SkBitmap CreateSkiaImageForTesting(const gfx::Size& size, SkColor color); } // namespace chrome_pdf
diff --git a/ppapi/BUILD.gn b/ppapi/BUILD.gn index c2dab92d..bfa92ed7 100644 --- a/ppapi/BUILD.gn +++ b/ppapi/BUILD.gn
@@ -177,8 +177,6 @@ "tests/test_file_chooser.h", "tests/test_net_address_private.cc", "tests/test_net_address_private.h", - "tests/test_pdf.cc", - "tests/test_pdf.h", "tests/test_tcp_socket_private_trusted.cc", "tests/test_tcp_socket_private_trusted.h", "tests/test_url_util.cc", @@ -221,31 +219,6 @@ deps = [ ":ppapi_tests_sources" ] } -# Test plugin for Cross-Origin Read Blocking. -# See also ppapi::RegisterCorbTestPlugin. -source_set("corb_test_plugin_sources") { - sources = [ - "tests/corb_test_plugin.cc", - "tests/test_utils.cc", - "tests/test_utils.h", - ] - - deps = [ - "//ppapi/cpp", - "//ppapi/shared_impl", - ] -} - -if (!is_mac) { - shared_library("corb_test_plugin") { - deps = [ ":corb_test_plugin_sources" ] - } -} else { - mac_plugin_bundle("corb_test_plugin") { - deps = [ ":corb_test_plugin_sources" ] - } -} - source_set("blink_deprecated_test_plugin_sources") { sources = [ "tests/blink_deprecated_test_plugin.cc" ] @@ -296,7 +269,6 @@ "proxy/mock_resource.cc", "proxy/mock_resource.h", "proxy/nacl_message_scanner_unittest.cc", - "proxy/pdf_resource_unittest.cc", "proxy/plugin_dispatcher_unittest.cc", "proxy/plugin_resource_tracker_unittest.cc", "proxy/plugin_var_tracker_unittest.cc",
diff --git a/ppapi/PRESUBMIT.py b/ppapi/PRESUBMIT.py index 5ac546f9..fb6bf1b 100644 --- a/ppapi/PRESUBMIT.py +++ b/ppapi/PRESUBMIT.py
@@ -177,7 +177,6 @@ files = input_api.change.AffectedFiles() INTERFACE_FILES = ('ppapi/thunk/interfaces_legacy.h', - 'ppapi/thunk/interfaces_ppb_private_flash.h', 'ppapi/thunk/interfaces_ppb_private.h', 'ppapi/thunk/interfaces_ppb_private_no_permissions.h', 'ppapi/thunk/interfaces_ppb_public_dev_channel.h', @@ -224,9 +223,6 @@ # through idl. whitelist = ['ppb_opengles2', 'ppb_opengles2ext_dev'] - # The PDF interface is hand-written. - whitelist += ['ppb_pdf', 'ppp_pdf'] - # Find all relevant .h and .idl files. for filename in files: name, ext = os.path.splitext(filename)
diff --git a/ppapi/api/private/ppb_flash_font_file.idl b/ppapi/api/private/ppb_flash_font_file.idl deleted file mode 100644 index b921d18..0000000 --- a/ppapi/api/private/ppb_flash_font_file.idl +++ /dev/null
@@ -1,50 +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. - */ - -/** - * This file contains the <code>PPB_Flash_FontFile</code> interface. - */ - -[generate_thunk] - -label Chrome { - M24 = 0.1, - M48 = 0.2 -}; - -interface PPB_Flash_FontFile { - /* Returns a resource identifying a font file corresponding to the given font - * request after applying the browser-specific fallback. - */ - PP_Resource Create( - [in] PP_Instance instance, - [in] PP_BrowserFont_Trusted_Description description, - [in] PP_PrivateFontCharset charset); - - /* Determines if a given resource is Flash font file. - */ - PP_Bool IsFlashFontFile([in] PP_Resource resource); - - /* Returns the requested font table. - * |output_length| should pass in the size of |output|. And it will return - * the actual length of returned data. |output| could be NULL in order to - * query the size of the buffer size needed. In that case, the input value of - * |output_length| is ignored. - * Note: it is Linux only and fails directly on other platforms. - */ - PP_Bool GetFontTable( - [in] PP_Resource font_file, - [in] uint32_t table, - [out] mem_t output, - [out] uint32_t output_length); - - /** - * Returns whether <code>PPB_Flash_FontFile</code> is supported on Windows. - */ - [version=0.2] - PP_Bool IsSupportedForWindows(); - -}; -
diff --git a/ppapi/c/BUILD.gn b/ppapi/c/BUILD.gn index 073f4671f..25d464f 100644 --- a/ppapi/c/BUILD.gn +++ b/ppapi/c/BUILD.gn
@@ -118,12 +118,10 @@ "private/ppb_ext_crx_file_system_private.h", "private/ppb_file_io_private.h", "private/ppb_file_ref_private.h", - "private/ppb_flash_font_file.h", "private/ppb_host_resolver_private.h", "private/ppb_instance_private.h", "private/ppb_isolated_file_system_private.h", "private/ppb_net_address_private.h", - "private/ppb_pdf.h", "private/ppb_proxy_private.h", "private/ppb_tcp_server_socket_private.h", "private/ppb_tcp_socket_private.h", @@ -132,7 +130,6 @@ "private/ppb_uma_private.h", "private/ppb_x509_certificate_private.h", "private/ppp_instance_private.h", - "private/ppp_pdf.h", "private/ppp_pexe_stream_handler.h", # Deprecated interfaces.
diff --git a/ppapi/c/private/OWNERS b/ppapi/c/private/OWNERS deleted file mode 100644 index e62fc9ac..0000000 --- a/ppapi/c/private/OWNERS +++ /dev/null
@@ -1,2 +0,0 @@ -per-file ppb_pdf.h=thestig@chromium.org -per-file ppp_pdf.h=thestig@chromium.org
diff --git a/ppapi/c/private/ppb_flash_font_file.h b/ppapi/c/private/ppb_flash_font_file.h deleted file mode 100644 index a1cc7865..0000000 --- a/ppapi/c/private/ppb_flash_font_file.h +++ /dev/null
@@ -1,80 +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. - */ - -/* From private/ppb_flash_font_file.idl modified Fri Oct 23 10:34:57 2015. */ - -#ifndef PPAPI_C_PRIVATE_PPB_FLASH_FONT_FILE_H_ -#define PPAPI_C_PRIVATE_PPB_FLASH_FONT_FILE_H_ - -#include "ppapi/c/pp_bool.h" -#include "ppapi/c/pp_instance.h" -#include "ppapi/c/pp_macros.h" -#include "ppapi/c/pp_resource.h" -#include "ppapi/c/pp_stdint.h" -#include "ppapi/c/pp_var.h" -#include "ppapi/c/private/pp_private_font_charset.h" -#include "ppapi/c/trusted/ppb_browser_font_trusted.h" - -#define PPB_FLASH_FONTFILE_INTERFACE_0_1 "PPB_Flash_FontFile;0.1" -#define PPB_FLASH_FONTFILE_INTERFACE_0_2 "PPB_Flash_FontFile;0.2" -#define PPB_FLASH_FONTFILE_INTERFACE PPB_FLASH_FONTFILE_INTERFACE_0_2 - -/** - * @file - * This file contains the <code>PPB_Flash_FontFile</code> interface. - */ - - -/** - * @addtogroup Interfaces - * @{ - */ -struct PPB_Flash_FontFile_0_2 { - /* Returns a resource identifying a font file corresponding to the given font - * request after applying the browser-specific fallback. - */ - PP_Resource (*Create)( - PP_Instance instance, - const struct PP_BrowserFont_Trusted_Description* description, - PP_PrivateFontCharset charset); - /* Determines if a given resource is Flash font file. - */ - PP_Bool (*IsFlashFontFile)(PP_Resource resource); - /* Returns the requested font table. - * |output_length| should pass in the size of |output|. And it will return - * the actual length of returned data. |output| could be NULL in order to - * query the size of the buffer size needed. In that case, the input value of - * |output_length| is ignored. - * Note: it is Linux only and fails directly on other platforms. - */ - PP_Bool (*GetFontTable)(PP_Resource font_file, - uint32_t table, - void* output, - uint32_t* output_length); - /** - * Returns whether <code>PPB_Flash_FontFile</code> is supported on Windows. - */ - PP_Bool (*IsSupportedForWindows)(void); -}; - -typedef struct PPB_Flash_FontFile_0_2 PPB_Flash_FontFile; - -struct PPB_Flash_FontFile_0_1 { - PP_Resource (*Create)( - PP_Instance instance, - const struct PP_BrowserFont_Trusted_Description* description, - PP_PrivateFontCharset charset); - PP_Bool (*IsFlashFontFile)(PP_Resource resource); - PP_Bool (*GetFontTable)(PP_Resource font_file, - uint32_t table, - void* output, - uint32_t* output_length); -}; -/** - * @} - */ - -#endif /* PPAPI_C_PRIVATE_PPB_FLASH_FONT_FILE_H_ */ -
diff --git a/ppapi/c/private/ppb_pdf.h b/ppapi/c/private/ppb_pdf.h deleted file mode 100644 index 4199699..0000000 --- a/ppapi/c/private/ppb_pdf.h +++ /dev/null
@@ -1,133 +0,0 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef PPAPI_C_PRIVATE_PPB_PDF_H_ -#define PPAPI_C_PRIVATE_PPB_PDF_H_ - -#include <stdint.h> - -#include "ppapi/c/pp_bool.h" -#include "ppapi/c/pp_instance.h" -#include "ppapi/c/pp_point.h" -#include "ppapi/c/pp_rect.h" -#include "ppapi/c/pp_resource.h" -#include "ppapi/c/pp_var.h" -#include "ppapi/c/private/pp_private_font_charset.h" - -#define PPB_PDF_INTERFACE "PPB_PDF;1" - -typedef enum { - PP_PDFFEATURE_HIDPI = 0, - PP_PDFFEATURE_PRINTING = 1 -} PP_PDFFeature; - -typedef enum { - PP_CONTENT_RESTRICTION_COPY = 1 << 0, - PP_CONTENT_RESTRICTION_CUT = 1 << 1, - PP_CONTENT_RESTRICTION_PASTE = 1 << 2, - PP_CONTENT_RESTRICTION_PRINT = 1 << 3, - PP_CONTENT_RESTRICTION_SAVE = 1 << 4 -} PP_ContentRestriction; - -struct PP_PrivateFontFileDescription { - const char* face; - uint32_t weight; - bool italic; -}; - -struct PP_PrivateFindResult { - int start_index; - int length; -}; - -struct PPB_PDF { - // Returns a resource identifying a font file corresponding to the given font - // request after applying the browser-specific fallback. - // - // Currently Linux-only. - PP_Resource (*GetFontFileWithFallback)( - PP_Instance instance, - const struct PP_BrowserFont_Trusted_Description* description, - PP_PrivateFontCharset charset); - - // Given a resource previously returned by GetFontFileWithFallback, returns - // a pointer to the requested font table. Linux only. - bool (*GetFontTableForPrivateFontFile)(PP_Resource font_file, - uint32_t table, - void* output, - uint32_t* output_length); - - // Search the given string using ICU. Use PPB_Core's MemFree on results when - // done. - void (*SearchString)(PP_Instance instance, - const unsigned short* string, - const unsigned short* term, - bool case_sensitive, - struct PP_PrivateFindResult** results, - uint32_t* count); - - // Since WebFrame doesn't know about PPAPI requests, it'll think the page has - // finished loading even if there are outstanding requests by the plugin. - // Take this out once WebFrame knows about requests by PPAPI plugins. - void (*DidStartLoading)(PP_Instance instance); - void (*DidStopLoading)(PP_Instance instance); - - // Sets content restriction for a full-page plugin (i.e. can't copy/print). - // The value is a bitfield of PP_ContentRestriction enums. - void (*SetContentRestriction)(PP_Instance instance, int restrictions); - - // Notifies the browser that the given action has been performed. - void (*UserMetricsRecordAction)(PP_Instance instance, struct PP_Var action); - - // Notifies the browser that the PDF has an unsupported feature. - void (*HasUnsupportedFeature)(PP_Instance instance); - - // Invoke SaveAs... dialog, similar to the right-click or wrench menu. - void (*SaveAs)(PP_Instance instance); - - // Invoke Print dialog for plugin. - void (*Print)(PP_Instance instance); - - PP_Bool(*IsFeatureEnabled)(PP_Instance instance, PP_PDFFeature feature); - - // Sets the selected text of the plugin. - void(*SetSelectedText)(PP_Instance instance, const char* selected_text); - - // Sets the link currently under the cursor. - void (*SetLinkUnderCursor)(PP_Instance instance, const char* url); - - // Gets pointers to the mmap'd V8 snapshot file and its size. - // This is needed when loading V8's initial snapshot from an external file. - void (*GetV8ExternalSnapshotData)(PP_Instance instance, - const char** snapshot_data_out, - int* snapshot_size_out); - - // Sends information about the PDF's URL and the embedder's URL. - void (*SetCrashData)(PP_Instance instance, - const char* pdf_url, - const char* top_level_url); - - // Sets the current selection bounding edges. - void (*SelectionChanged)(PP_Instance instance, - const struct PP_FloatPoint* left, - int32_t left_height, - const struct PP_FloatPoint* right, - int32_t right_height); - - // Sets whether the PDF viewer can handle save commands internally. - void (*SetPluginCanSave)(PP_Instance instance, bool can_save); - - // Displays an alert dialog. - void (*ShowAlertDialog)(PP_Instance instance, const char* message); - - // Displays a confirmation dialog. This method is synchronous. - bool (*ShowConfirmDialog)(PP_Instance instance, const char* message); - - // Displays a prompt dialog. This method is synchronous. - struct PP_Var (*ShowPromptDialog)(PP_Instance instance, - const char* message, - const char* default_answer); -}; - -#endif // PPAPI_C_PRIVATE_PPB_PDF_H_
diff --git a/ppapi/c/private/ppp_pdf.h b/ppapi/c/private/ppp_pdf.h deleted file mode 100644 index b45531f..0000000 --- a/ppapi/c/private/ppp_pdf.h +++ /dev/null
@@ -1,69 +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 PPAPI_C_PRIVATE_PPP_PDF_H_ -#define PPAPI_C_PRIVATE_PPP_PDF_H_ - -#include <stdint.h> - -#include "ppapi/c/dev/pp_print_settings_dev.h" -#include "ppapi/c/pp_instance.h" -#include "ppapi/c/pp_point.h" -#include "ppapi/c/pp_var.h" - -#define PPP_PDF_INTERFACE_1 "PPP_Pdf;1" -#define PPP_PDF_INTERFACE PPP_PDF_INTERFACE_1 - -typedef enum { - PP_PRIVATEDUPLEXMODE_NONE = 0, - PP_PRIVATEDUPLEXMODE_SIMPLEX = 1, - PP_PRIVATEDUPLEXMODE_SHORT_EDGE = 2, - PP_PRIVATEDUPLEXMODE_LONG_EDGE = 3, - PP_PRIVATEDUPLEXMODE_LAST = PP_PRIVATEDUPLEXMODE_LONG_EDGE -} PP_PrivateDuplexMode_Dev; -PP_COMPILE_ASSERT_SIZE_IN_BYTES(PP_PrivateDuplexMode_Dev, 4); - -struct PP_PdfPrintPresetOptions_Dev { - // Returns whether scaling is disabled. Returns same information as the - // PPP_Printing_Dev's method IsScalingDiabled(). - PP_Bool is_scaling_disabled; - - // Number of copies to be printed. - int32_t copies; - - // DuplexMode to be used for printing. - PP_PrivateDuplexMode_Dev duplex; - - // True if all the pages in the PDF are the same size. - PP_Bool is_page_size_uniform; - - // Only valid if |is_page_size_uniform| is true. The page size. - PP_Size uniform_page_size; -}; -PP_COMPILE_ASSERT_STRUCT_SIZE_IN_BYTES(PP_PdfPrintPresetOptions_Dev, 24); - -struct PP_PdfPrintSettings_Dev { - // Used for N-up mode. - uint32_t pages_per_sheet; - - // The scale factor percentage, where 100 indicates default scaling. - uint32_t scale_factor; -}; -PP_COMPILE_ASSERT_STRUCT_SIZE_IN_BYTES(PP_PdfPrintSettings_Dev, 8); - -struct PPP_Pdf_1_1 { - // This is a specialized version of PPP_Printing_Dev's Begin method. - // It functions in the same way, but takes an additional |pdf_print_settings| - // parameter. When the PPP_Pdf interface is available, use this instead of - // PPP_Printing_Dev's Begin method, in conjuction with PPP_Printing_Dev's - // other methods. - int32_t (*PrintBegin)( - PP_Instance instance, - const struct PP_PrintSettings_Dev* print_settings, - const struct PP_PdfPrintSettings_Dev* pdf_print_settings); -}; - -typedef PPP_Pdf_1_1 PPP_Pdf; - -#endif // PPAPI_C_PRIVATE_PPP_PDF_H_
diff --git a/ppapi/cpp/BUILD.gn b/ppapi/cpp/BUILD.gn index 975feff..d3b6bb6e 100644 --- a/ppapi/cpp/BUILD.gn +++ b/ppapi/cpp/BUILD.gn
@@ -203,8 +203,6 @@ "private/ext_crx_file_system_private.h", "private/file_io_private.cc", "private/file_io_private.h", - "private/flash_font_file.cc", - "private/flash_font_file.h", "private/host_resolver_private.cc", "private/host_resolver_private.h", "private/instance_private.cc", @@ -215,8 +213,6 @@ "private/net_address_private.h", "private/pass_file_handle.cc", "private/pass_file_handle.h", - "private/pdf.cc", - "private/pdf.h", "private/tcp_server_socket_private.cc", "private/tcp_server_socket_private.h", "private/tcp_socket_private.cc",
diff --git a/ppapi/cpp/private/OWNERS b/ppapi/cpp/private/OWNERS deleted file mode 100644 index 3f1a11b..0000000 --- a/ppapi/cpp/private/OWNERS +++ /dev/null
@@ -1 +0,0 @@ -per-file pdf.*=thestig@chromium.org
diff --git a/ppapi/cpp/private/flash_font_file.cc b/ppapi/cpp/private/flash_font_file.cc deleted file mode 100644 index 30a5f66..0000000 --- a/ppapi/cpp/private/flash_font_file.cc +++ /dev/null
@@ -1,74 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ppapi/cpp/private/flash_font_file.h" - -#include "ppapi/c/private/ppb_flash_font_file.h" -#include "ppapi/c/trusted/ppb_browser_font_trusted.h" -#include "ppapi/cpp/instance_handle.h" -#include "ppapi/cpp/module_impl.h" - -namespace pp { - -namespace { - -template <> const char* interface_name<PPB_Flash_FontFile_0_1>() { - return PPB_FLASH_FONTFILE_INTERFACE_0_1; -} - -template <> const char* interface_name<PPB_Flash_FontFile_0_2>() { - return PPB_FLASH_FONTFILE_INTERFACE_0_2; -} - -} // namespace - -namespace flash { - -FontFile::FontFile() { -} - -FontFile::FontFile(const InstanceHandle& instance, - const PP_BrowserFont_Trusted_Description* description, - PP_PrivateFontCharset charset) { - if (has_interface<PPB_Flash_FontFile_0_2>()) { - PassRefFromConstructor(get_interface<PPB_Flash_FontFile_0_2>()->Create( - instance.pp_instance(), description, charset)); - } - else if (has_interface<PPB_Flash_FontFile_0_1>()) { - PassRefFromConstructor(get_interface<PPB_Flash_FontFile_0_1>()->Create( - instance.pp_instance(), description, charset)); - } -} - -FontFile::~FontFile() { -} - -// static -bool FontFile::IsAvailable() { - return (has_interface<PPB_Flash_FontFile_0_2>() || - has_interface<PPB_Flash_FontFile_0_1>()); -} - -bool FontFile::IsSupportedForWindows() { - if (has_interface<PPB_Flash_FontFile_0_2>()) - return !!get_interface<PPB_Flash_FontFile_0_2>()->IsSupportedForWindows(); - return false; -} - -bool FontFile::GetFontTable(uint32_t table, - void* output, - uint32_t* output_length) { - if (has_interface<PPB_Flash_FontFile_0_2>()) { - return !!get_interface<PPB_Flash_FontFile_0_2>()-> - GetFontTable(pp_resource(), table, output, output_length); - } - else if (has_interface<PPB_Flash_FontFile_0_1>()) { - return !!get_interface<PPB_Flash_FontFile_0_1>()-> - GetFontTable(pp_resource(), table, output, output_length); - } - return false; -} - -} // namespace flash -} // namespace pp
diff --git a/ppapi/cpp/private/flash_font_file.h b/ppapi/cpp/private/flash_font_file.h deleted file mode 100644 index 0c4aaa6..0000000 --- a/ppapi/cpp/private/flash_font_file.h +++ /dev/null
@@ -1,42 +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 PPAPI_CPP_PRIVATE_FLASH_FONT_FILE_H_ -#define PPAPI_CPP_PRIVATE_FLASH_FONT_FILE_H_ - -#include <stdint.h> - -#include "ppapi/c/private/pp_private_font_charset.h" -#include "ppapi/cpp/resource.h" - -struct PP_BrowserFont_Trusted_Description; - -namespace pp { - -class InstanceHandle; - -namespace flash { - -class FontFile : public Resource { - public: - // Default constructor for making an is_null() FontFile resource. - FontFile(); - FontFile(const InstanceHandle& instance, - const PP_BrowserFont_Trusted_Description* description, - PP_PrivateFontCharset charset); - virtual ~FontFile(); - - // Returns true if the required interface is available. - static bool IsAvailable(); - - // Returns true if this interface is supported for Windows. - bool IsSupportedForWindows(); - - bool GetFontTable(uint32_t table, void* output, uint32_t* output_length); -}; - -} // namespace flash -} // namespace pp - -#endif // PPAPI_CPP_PRIVATE_FLASH_FONT_FILE_H_
diff --git a/ppapi/cpp/private/pdf.cc b/ppapi/cpp/private/pdf.cc deleted file mode 100644 index 08494de..0000000 --- a/ppapi/cpp/private/pdf.cc +++ /dev/null
@@ -1,208 +0,0 @@ -// Copyright (c) 2013 The Chromium 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 "ppapi/cpp/private/pdf.h" - -#include "ppapi/c/trusted/ppb_browser_font_trusted.h" -#include "ppapi/cpp/image_data.h" -#include "ppapi/cpp/instance_handle.h" -#include "ppapi/cpp/module_impl.h" -#include "ppapi/cpp/var.h" - -namespace pp { - -namespace { - -template <> const char* interface_name<PPB_PDF>() { - return PPB_PDF_INTERFACE; -} - -} // namespace - -// static -bool PDF::IsAvailable() { - return has_interface<PPB_PDF>(); -} - -// static -PP_Resource PDF::GetFontFileWithFallback( - const InstanceHandle& instance, - const PP_BrowserFont_Trusted_Description* description, - PP_PrivateFontCharset charset) { - if (has_interface<PPB_PDF>()) { - return get_interface<PPB_PDF>()->GetFontFileWithFallback( - instance.pp_instance(), description, charset); - } - return 0; -} - -// static -bool PDF::GetFontTableForPrivateFontFile(PP_Resource font_file, - uint32_t table, - void* output, - uint32_t* output_length) { - if (has_interface<PPB_PDF>()) { - return get_interface<PPB_PDF>()->GetFontTableForPrivateFontFile(font_file, - table, output, output_length); - } - return false; -} - -// static -void PDF::SearchString(const InstanceHandle& instance, - const unsigned short* string, - const unsigned short* term, - bool case_sensitive, - PP_PrivateFindResult** results, - uint32_t* count) { - if (has_interface<PPB_PDF>()) { - get_interface<PPB_PDF>()->SearchString(instance.pp_instance(), string, - term, case_sensitive, results, count); - } -} - -// static -void PDF::DidStartLoading(const InstanceHandle& instance) { - if (has_interface<PPB_PDF>()) - get_interface<PPB_PDF>()->DidStartLoading(instance.pp_instance()); -} - -// static -void PDF::DidStopLoading(const InstanceHandle& instance) { - if (has_interface<PPB_PDF>()) - get_interface<PPB_PDF>()->DidStopLoading(instance.pp_instance()); -} - -// static -void PDF::SetContentRestriction(const InstanceHandle& instance, - int restrictions) { - if (has_interface<PPB_PDF>()) { - get_interface<PPB_PDF>()->SetContentRestriction(instance.pp_instance(), - restrictions); - } -} - -// static -void PDF::UserMetricsRecordAction(const InstanceHandle& instance, - const Var& action) { - if (has_interface<PPB_PDF>()) { - get_interface<PPB_PDF>()->UserMetricsRecordAction(instance.pp_instance(), - action.pp_var()); - } -} - -// static -void PDF::HasUnsupportedFeature(const InstanceHandle& instance) { - if (has_interface<PPB_PDF>()) - get_interface<PPB_PDF>()->HasUnsupportedFeature(instance.pp_instance()); -} - -// static -void PDF::ShowAlertDialog(const InstanceHandle& instance, const char* message) { - if (has_interface<PPB_PDF>()) - get_interface<PPB_PDF>()->ShowAlertDialog(instance.pp_instance(), message); -} - -// static -bool PDF::ShowConfirmDialog(const InstanceHandle& instance, - const char* message) { - if (has_interface<PPB_PDF>()) { - return get_interface<PPB_PDF>()->ShowConfirmDialog(instance.pp_instance(), - message); - } - return false; -} - -// static -pp::Var PDF::ShowPromptDialog(const InstanceHandle& instance, - const char* message, - const char* default_answer) { - if (has_interface<PPB_PDF>()) { - return pp::Var(PASS_REF, - get_interface<PPB_PDF>()->ShowPromptDialog( - instance.pp_instance(), message, default_answer)); - } - return pp::Var(); -} - -// static -void PDF::SaveAs(const InstanceHandle& instance) { - if (has_interface<PPB_PDF>()) - get_interface<PPB_PDF>()->SaveAs(instance.pp_instance()); -} - -// static -void PDF::Print(const InstanceHandle& instance) { - if (has_interface<PPB_PDF>()) - get_interface<PPB_PDF>()->Print(instance.pp_instance()); -} - -// static -bool PDF::IsFeatureEnabled(const InstanceHandle& instance, - PP_PDFFeature feature) { - if (has_interface<PPB_PDF>()) - return PP_ToBool(get_interface<PPB_PDF>()->IsFeatureEnabled( - instance.pp_instance(), feature)); - return false; -} - -// static -void PDF::SetSelectedText(const InstanceHandle& instance, - const char* selected_text) { - if (has_interface<PPB_PDF>()) { - get_interface<PPB_PDF>()->SetSelectedText(instance.pp_instance(), - selected_text); - } -} - -// static -void PDF::SetLinkUnderCursor(const InstanceHandle& instance, const char* url) { - if (has_interface<PPB_PDF>()) - get_interface<PPB_PDF>()->SetLinkUnderCursor(instance.pp_instance(), url); -} - -// static -void PDF::GetV8ExternalSnapshotData(const InstanceHandle& instance, - const char** snapshot_data_out, - int* snapshot_size_out) { - if (has_interface<PPB_PDF>()) { - get_interface<PPB_PDF>()->GetV8ExternalSnapshotData( - instance.pp_instance(), snapshot_data_out, snapshot_size_out); - return; - } - *snapshot_data_out = NULL; - *snapshot_size_out = 0; -} - -// static -void PDF::SetCrashData(const InstanceHandle& instance, - const char* pdf_url, - const char* top_level_url) { - if (has_interface<PPB_PDF>()) { - get_interface<PPB_PDF>()->SetCrashData(instance.pp_instance(), pdf_url, - top_level_url); - } -} - -// static -void PDF::SelectionChanged(const InstanceHandle& instance, - const PP_FloatPoint& left, - int32_t left_height, - const PP_FloatPoint& right, - int32_t right_height) { - if (has_interface<PPB_PDF>()) { - get_interface<PPB_PDF>()->SelectionChanged( - instance.pp_instance(), &left, left_height, &right, right_height); - } -} - -// static -void PDF::SetPluginCanSave(const InstanceHandle& instance, bool can_save) { - if (has_interface<PPB_PDF>()) { - get_interface<PPB_PDF>()->SetPluginCanSave(instance.pp_instance(), - can_save); - } -} - -} // namespace pp
diff --git a/ppapi/cpp/private/pdf.h b/ppapi/cpp/private/pdf.h deleted file mode 100644 index 2eb96aa..0000000 --- a/ppapi/cpp/private/pdf.h +++ /dev/null
@@ -1,76 +0,0 @@ -// Copyright (c) 2013 The Chromium 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 PPAPI_CPP_PRIVATE_PDF_H_ -#define PPAPI_CPP_PRIVATE_PDF_H_ - -#include <stdint.h> - -#include "ppapi/c/private/ppb_pdf.h" - -struct PP_BrowserFont_Trusted_Description; - -namespace pp { - -class InstanceHandle; -class Var; - -class PDF { - public: - // Returns true if the required interface is available. - static bool IsAvailable(); - - static PP_Resource GetFontFileWithFallback( - const InstanceHandle& instance, - const PP_BrowserFont_Trusted_Description* description, - PP_PrivateFontCharset charset); - static bool GetFontTableForPrivateFontFile(PP_Resource font_file, - uint32_t table, - void* output, - uint32_t* output_length); - static void SearchString(const InstanceHandle& instance, - const unsigned short* string, - const unsigned short* term, - bool case_sensitive, - PP_PrivateFindResult** results, - uint32_t* count); - static void DidStartLoading(const InstanceHandle& instance); - static void DidStopLoading(const InstanceHandle& instance); - static void SetContentRestriction(const InstanceHandle& instance, - int restrictions); - static void UserMetricsRecordAction(const InstanceHandle& instance, - const Var& action); - static void HasUnsupportedFeature(const InstanceHandle& instance); - static void ShowAlertDialog(const InstanceHandle& instance, - const char* message); - static bool ShowConfirmDialog(const InstanceHandle& instance, - const char* message); - static pp::Var ShowPromptDialog(const InstanceHandle& instance, - const char* message, - const char* default_answer); - static void SaveAs(const InstanceHandle& instance); - static void Print(const InstanceHandle& instance); - static bool IsFeatureEnabled(const InstanceHandle& instance, - PP_PDFFeature feature); - static void SetSelectedText(const InstanceHandle& instance, - const char* selected_text); - static void SetLinkUnderCursor(const InstanceHandle& instance, - const char* url); - static void GetV8ExternalSnapshotData(const InstanceHandle& instance, - const char** snapshot_data_out, - int* snapshot_size_out); - static void SetCrashData(const InstanceHandle& instance, - const char* pdf_url, - const char* top_level_url); - static void SelectionChanged(const InstanceHandle& instance, - const PP_FloatPoint& left, - int32_t left_height, - const PP_FloatPoint& right, - int32_t right_height); - static void SetPluginCanSave(const InstanceHandle& instance, bool can_save); -}; - -} // namespace pp - -#endif // PPAPI_CPP_PRIVATE_PDF_H_
diff --git a/ppapi/proxy/BUILD.gn b/ppapi/proxy/BUILD.gn index 8c6329ca..c2b7fc3c 100644 --- a/ppapi/proxy/BUILD.gn +++ b/ppapi/proxy/BUILD.gn
@@ -110,8 +110,6 @@ "ppp_messaging_proxy.h", "ppp_mouse_lock_proxy.cc", "ppp_mouse_lock_proxy.h", - "ppp_pdf_proxy.cc", - "ppp_pdf_proxy.h", "ppp_printing_proxy.cc", "ppp_printing_proxy.h", "ppp_text_input_proxy.cc", @@ -189,14 +187,10 @@ "browser_font_singleton_resource.h", "device_enumeration_resource_helper.cc", "device_enumeration_resource_helper.h", - "flash_font_file_resource.cc", - "flash_font_file_resource.h", "host_dispatcher.cc", "host_dispatcher.h", "host_var_serialization_rules.cc", "host_var_serialization_rules.h", - "pdf_resource.cc", - "pdf_resource.h", "ppb_buffer_proxy.cc", "ppb_var_deprecated_proxy.cc", "ppb_var_deprecated_proxy.h",
diff --git a/ppapi/proxy/OWNERS b/ppapi/proxy/OWNERS index cf5f23a..a7e6c89 100644 --- a/ppapi/proxy/OWNERS +++ b/ppapi/proxy/OWNERS
@@ -6,7 +6,3 @@ per-file *_param_traits*.*=set noparent per-file *_param_traits*.*=file://ipc/SECURITY_OWNERS - -per-file pdf_resource.*=thestig@chromium.org -per-file pdf_resource_unittest.cc=thestig@chromium.org -per-file ppp_pdf_proxy.*=thestig@chromium.org
diff --git a/ppapi/proxy/flash_font_file_resource.cc b/ppapi/proxy/flash_font_file_resource.cc deleted file mode 100644 index e16a03f38..0000000 --- a/ppapi/proxy/flash_font_file_resource.cc +++ /dev/null
@@ -1,82 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ppapi/proxy/flash_font_file_resource.h" - -#include <cstring> -#include <memory> - -#include "ppapi/c/pp_errors.h" -#include "ppapi/proxy/ppapi_messages.h" - -namespace ppapi { -namespace proxy { - -FlashFontFileResource::FlashFontFileResource( - Connection connection, - PP_Instance instance, - const PP_BrowserFont_Trusted_Description* description, - PP_PrivateFontCharset charset) - : PluginResource(connection, instance), - charset_(charset) { - description_.SetFromPPBrowserFontDescription(*description); -} - -FlashFontFileResource::~FlashFontFileResource() { -} - -thunk::PPB_Flash_FontFile_API* - FlashFontFileResource::AsPPB_Flash_FontFile_API() { - return this; -} - -PP_Bool FlashFontFileResource::GetFontTable(uint32_t table, - void* output, - uint32_t* output_length) { - if (!output_length) - return PP_FALSE; - - if (!sent_create_to_renderer()) { - SendCreate( - RENDERER, PpapiHostMsg_FlashFontFile_Create(description_, charset_)); - } - - const std::string* contents = GetFontTable(table); - if (!contents) { - std::string out_contents; - int32_t result = SyncCall<PpapiPluginMsg_FlashFontFile_GetFontTableReply>( - RENDERER, PpapiHostMsg_FlashFontFile_GetFontTable(table), - &out_contents); - if (result != PP_OK) - return PP_FALSE; - - contents = AddFontTable(table, out_contents); - } - - // If we are going to copy the data into |output|, it must be big enough. - if (output && *output_length < contents->size()) - return PP_FALSE; - - *output_length = static_cast<uint32_t>(contents->size()); - if (output) - memcpy(output, contents->c_str(), *output_length); - return PP_TRUE; -} - -const std::string* FlashFontFileResource::GetFontTable(uint32_t table) const { - auto found = font_tables_.find(table); - return (found != font_tables_.end()) ? found->second.get() : nullptr; -} - -const std::string* FlashFontFileResource::AddFontTable( - uint32_t table, - const std::string& contents) { - auto contents_copy = std::make_unique<std::string>(contents); - std::string* contents_copy_ptr = contents_copy.get(); - font_tables_[table] = std::move(contents_copy); - return contents_copy_ptr; -} - -} // namespace proxy -} // namespace ppapi
diff --git a/ppapi/proxy/flash_font_file_resource.h b/ppapi/proxy/flash_font_file_resource.h deleted file mode 100644 index 8fe12a0..0000000 --- a/ppapi/proxy/flash_font_file_resource.h +++ /dev/null
@@ -1,63 +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 PPAPI_PROXY_FLASH_FONT_FILE_RESOURCE_H_ -#define PPAPI_PROXY_FLASH_FONT_FILE_RESOURCE_H_ - -#include <stdint.h> - -#include <string> -#include <unordered_map> - -#include "ppapi/c/private/pp_private_font_charset.h" -#include "ppapi/proxy/plugin_resource.h" -#include "ppapi/proxy/serialized_structs.h" -#include "ppapi/thunk/ppb_flash_font_file_api.h" - -struct PP_BrowserFont_Trusted_Description; - -namespace ppapi { -namespace proxy { - -// TODO(yzshen): write unittest and browser test. -class FlashFontFileResource : public PluginResource, - public thunk::PPB_Flash_FontFile_API { - public: - FlashFontFileResource(Connection connection, - PP_Instance instance, - const PP_BrowserFont_Trusted_Description* description, - PP_PrivateFontCharset charset); - - FlashFontFileResource(const FlashFontFileResource&) = delete; - FlashFontFileResource& operator=(const FlashFontFileResource&) = delete; - - ~FlashFontFileResource() override; - - // Resource overrides. - thunk::PPB_Flash_FontFile_API* AsPPB_Flash_FontFile_API() override; - - // PPB_Flash_FontFile_API. - PP_Bool GetFontTable(uint32_t table, - void* output, - uint32_t* output_length) override; - - private: - // Sees if we have a cache of the font table and returns a pointer to it. - // Returns NULL if we don't have it. - const std::string* GetFontTable(uint32_t table) const; - - const std::string* AddFontTable(uint32_t table, const std::string& contents); - - using FontTableMap = - std::unordered_map<uint32_t, std::unique_ptr<std::string>>; - FontTableMap font_tables_; - - SerializedFontDescription description_; - const PP_PrivateFontCharset charset_; -}; - -} // namespace proxy -} // namespace ppapi - -#endif // PPAPI_PROXY_FLASH_FONT_FILE_RESOURCE_H_
diff --git a/ppapi/proxy/interface_list.cc b/ppapi/proxy/interface_list.cc index c401a1c..5328628 100644 --- a/ppapi/proxy/interface_list.cc +++ b/ppapi/proxy/interface_list.cc
@@ -76,11 +76,9 @@ #include "ppapi/c/private/ppb_ext_crx_file_system_private.h" #include "ppapi/c/private/ppb_file_io_private.h" #include "ppapi/c/private/ppb_file_ref_private.h" -#include "ppapi/c/private/ppb_flash_font_file.h" #include "ppapi/c/private/ppb_host_resolver_private.h" #include "ppapi/c/private/ppb_isolated_file_system_private.h" #include "ppapi/c/private/ppb_net_address_private.h" -#include "ppapi/c/private/ppb_pdf.h" #include "ppapi/c/private/ppb_tcp_server_socket_private.h" #include "ppapi/c/private/ppb_tcp_socket_private.h" #include "ppapi/c/private/ppb_testing_private.h" @@ -112,7 +110,6 @@ #include "ppapi/proxy/ppp_instance_proxy.h" #include "ppapi/proxy/ppp_messaging_proxy.h" #include "ppapi/proxy/ppp_mouse_lock_proxy.h" -#include "ppapi/proxy/ppp_pdf_proxy.h" #include "ppapi/proxy/ppp_printing_proxy.h" #include "ppapi/proxy/ppp_text_input_proxy.h" #include "ppapi/proxy/ppp_video_decoder_proxy.h" @@ -181,14 +178,6 @@ Permission current_required_permission = PERMISSION_PRIVATE; #include "ppapi/thunk/interfaces_ppb_private.h" } - { - Permission current_required_permission = PERMISSION_FLASH; - #include "ppapi/thunk/interfaces_ppb_private_flash.h" - } - { - Permission current_required_permission = PERMISSION_PDF; - #include "ppapi/thunk/interfaces_ppb_private_pdf.h" - } #endif // !BUILDFLAG(IS_NACL) { Permission current_required_permission = PERMISSION_DEV_CHANNEL; @@ -286,8 +275,6 @@ AddProxy(API_ID_PPP_TEXT_INPUT, &ProxyFactory<PPP_TextInput_Proxy>); AddPPP(PPP_TEXTINPUT_DEV_INTERFACE, PPP_TextInput_Proxy::GetProxyInterface()); #if !BUILDFLAG(IS_NACL) - AddProxy(API_ID_PPP_PDF, &ProxyFactory<PPP_Pdf_Proxy>); - AddPPP(PPP_PDF_INTERFACE, PPP_Pdf_Proxy::GetProxyInterface()); AddProxy(API_ID_PPP_VIDEO_DECODER_DEV, &ProxyFactory<PPP_VideoDecoder_Proxy>); AddPPP(PPP_VIDEODECODER_DEV_INTERFACE, PPP_VideoDecoder_Proxy::GetProxyInterface());
diff --git a/ppapi/proxy/pdf_resource.cc b/ppapi/proxy/pdf_resource.cc deleted file mode 100644 index f2b9a2f..0000000 --- a/ppapi/proxy/pdf_resource.cc +++ /dev/null
@@ -1,224 +0,0 @@ -// Copyright (c) 2013 The Chromium 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 "ppapi/proxy/pdf_resource.h" - -#include <stddef.h> -#include <stdint.h> -#include <stdlib.h> -#include <string.h> - -#include <limits> -#include <utility> -#include <vector> - -#include "base/command_line.h" -#include "base/debug/crash_logging.h" -#include "base/metrics/histogram.h" -#include "base/strings/utf_string_conversions.h" -#include "gin/v8_initializer.h" -#include "ppapi/c/pp_errors.h" -#include "ppapi/c/private/ppb_pdf.h" -#include "ppapi/proxy/plugin_globals.h" -#include "ppapi/proxy/ppapi_messages.h" -#include "ppapi/shared_impl/var.h" -#include "third_party/icu/source/i18n/unicode/usearch.h" - -namespace ppapi { -namespace proxy { - -namespace { - -// TODO(raymes): This is just copied from render_thread_impl.cc. We should have -// generic code somewhere to get the locale in the plugin. -std::string GetLocale() { - // The browser process should have passed the locale to the plugin via the - // --lang command line flag. - const base::CommandLine& parsed_command_line = - *base::CommandLine::ForCurrentProcess(); - const std::string& lang = parsed_command_line.GetSwitchValueASCII("lang"); - DCHECK(!lang.empty()); - return lang; -} - -} // namespace - -PDFResource::PDFResource(Connection connection, PP_Instance instance) - : PluginResource(connection, instance) { - SendCreate(RENDERER, PpapiHostMsg_PDF_Create()); -} - -PDFResource::~PDFResource() { -} - -thunk::PPB_PDF_API* PDFResource::AsPPB_PDF_API() { - return this; -} - -void PDFResource::SearchString(const unsigned short* input_string, - const unsigned short* input_term, - bool case_sensitive, - PP_PrivateFindResult** results, - uint32_t* count) { - if (locale_.empty()) - locale_ = GetLocale() + "@collation=search"; - - const UChar* string = reinterpret_cast<const UChar*>(input_string); - const UChar* term = reinterpret_cast<const UChar*>(input_term); - - UErrorCode status = U_ZERO_ERROR; - UStringSearch* searcher = - usearch_open(term, -1, string, -1, locale_.c_str(), nullptr, &status); - DCHECK(U_SUCCESS(status)) << status; - UCollationStrength strength = case_sensitive ? UCOL_TERTIARY : UCOL_PRIMARY; - - UCollator* collator = usearch_getCollator(searcher); - if (ucol_getStrength(collator) != strength) { - ucol_setStrength(collator, strength); - usearch_reset(searcher); - } - - status = U_ZERO_ERROR; - int match_start = usearch_first(searcher, &status); - DCHECK(U_SUCCESS(status)); - - std::vector<PP_PrivateFindResult> pp_results; - while (match_start != USEARCH_DONE) { - int32_t matched_length = usearch_getMatchedLength(searcher); - PP_PrivateFindResult result; - result.start_index = match_start; - result.length = matched_length; - pp_results.push_back(result); - match_start = usearch_next(searcher, &status); - DCHECK(U_SUCCESS(status)); - } - - if (pp_results.empty() || - pp_results.size() > std::numeric_limits<uint32_t>::max() || - pp_results.size() > SIZE_MAX / sizeof(PP_PrivateFindResult)) { - *count = 0; - *results = nullptr; - } else { - *count = static_cast<uint32_t>(pp_results.size()); - const size_t result_size = pp_results.size() * sizeof(PP_PrivateFindResult); - *results = reinterpret_cast<PP_PrivateFindResult*>(malloc(result_size)); - memcpy(*results, &pp_results[0], result_size); - } - - usearch_close(searcher); -} - -void PDFResource::DidStartLoading() { - Post(RENDERER, PpapiHostMsg_PDF_DidStartLoading()); -} - -void PDFResource::DidStopLoading() { - Post(RENDERER, PpapiHostMsg_PDF_DidStopLoading()); -} - -void PDFResource::SetContentRestriction(int restrictions) { - Post(RENDERER, PpapiHostMsg_PDF_SetContentRestriction(restrictions)); -} - -void PDFResource::UserMetricsRecordAction(const PP_Var& action) { - scoped_refptr<ppapi::StringVar> action_str( - ppapi::StringVar::FromPPVar(action)); - if (action_str.get()) { - Post(RENDERER, - PpapiHostMsg_PDF_UserMetricsRecordAction(action_str->value())); - } -} - -void PDFResource::HasUnsupportedFeature() { - Post(RENDERER, PpapiHostMsg_PDF_HasUnsupportedFeature()); -} - -void PDFResource::Print() { - Post(RENDERER, PpapiHostMsg_PDF_Print()); -} - -void PDFResource::ShowAlertDialog(const char* message) { - SyncCall<PpapiPluginMsg_PDF_ShowAlertDialogReply>( - RENDERER, PpapiHostMsg_PDF_ShowAlertDialog(message)); -} - -bool PDFResource::ShowConfirmDialog(const char* message) { - bool bool_result = false; - if (SyncCall<PpapiPluginMsg_PDF_ShowConfirmDialogReply>( - RENDERER, PpapiHostMsg_PDF_ShowConfirmDialog(message), - &bool_result) != PP_OK) { - return false; - } - return bool_result; -} - -PP_Var PDFResource::ShowPromptDialog(const char* message, - const char* default_answer) { - std::string str_result; - if (SyncCall<PpapiPluginMsg_PDF_ShowPromptDialogReply>( - RENDERER, PpapiHostMsg_PDF_ShowPromptDialog(message, default_answer), - &str_result) != PP_OK) { - return PP_MakeUndefined(); - } - return StringVar::StringToPPVar(str_result); -} - -void PDFResource::SaveAs() { - Post(RENDERER, PpapiHostMsg_PDF_SaveAs()); -} - -PP_Bool PDFResource::IsFeatureEnabled(PP_PDFFeature feature) { - PP_Bool result = PP_FALSE; - switch (feature) { - case PP_PDFFEATURE_HIDPI: - result = PP_TRUE; - break; - case PP_PDFFEATURE_PRINTING: - // TODO(raymes): Use PrintRenderFrameHelper::IsPrintingEnabled. - result = PP_FALSE; - break; - } - return result; -} - -void PDFResource::SetSelectedText(const char* selected_text) { - Post(RENDERER, - PpapiHostMsg_PDF_SetSelectedText(base::UTF8ToUTF16(selected_text))); -} - -void PDFResource::SetLinkUnderCursor(const char* url) { - Post(RENDERER, PpapiHostMsg_PDF_SetLinkUnderCursor(url)); -} - -void PDFResource::GetV8ExternalSnapshotData(const char** snapshot_data_out, - int* snapshot_size_out) { - gin::V8Initializer::GetV8ExternalSnapshotData(snapshot_data_out, - snapshot_size_out); -} - -void PDFResource::SetCrashData(const char* pdf_url, const char* top_level_url) { - if (pdf_url) { - static base::debug::CrashKeyString* subresource_url = - base::debug::AllocateCrashKeyString("subresource_url", - base::debug::CrashKeySize::Size256); - base::debug::SetCrashKeyString(subresource_url, pdf_url); - } - if (top_level_url) - PluginGlobals::Get()->SetActiveURL(top_level_url); -} - -void PDFResource::SelectionChanged(const PP_FloatPoint& left, - int32_t left_height, - const PP_FloatPoint& right, - int32_t right_height) { - Post(RENDERER, PpapiHostMsg_PDF_SelectionChanged(left, left_height, right, - right_height)); -} - -void PDFResource::SetPluginCanSave(bool can_save) { - Post(RENDERER, PpapiHostMsg_PDF_SetPluginCanSave(can_save)); -} - -} // namespace proxy -} // namespace ppapi
diff --git a/ppapi/proxy/pdf_resource.h b/ppapi/proxy/pdf_resource.h deleted file mode 100644 index 9d0c394..0000000 --- a/ppapi/proxy/pdf_resource.h +++ /dev/null
@@ -1,76 +0,0 @@ -// Copyright (c) 2013 The Chromium 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 PPAPI_PROXY_PDF_RESOURCE_H_ -#define PPAPI_PROXY_PDF_RESOURCE_H_ - -#include <string> - -#include "base/compiler_specific.h" -#include "ppapi/c/pp_instance.h" -#include "ppapi/c/pp_var.h" -#include "ppapi/proxy/connection.h" -#include "ppapi/proxy/plugin_resource.h" -#include "ppapi/proxy/ppapi_proxy_export.h" -#include "ppapi/thunk/ppb_pdf_api.h" - -namespace ppapi { -namespace proxy { - -class PPAPI_PROXY_EXPORT PDFResource - : public PluginResource, - public thunk::PPB_PDF_API { - public: - PDFResource(Connection connection, PP_Instance instance); - - PDFResource(const PDFResource&) = delete; - PDFResource& operator=(const PDFResource&) = delete; - - ~PDFResource() override; - - // For unittesting with a given locale. - void SetLocaleForTest(const std::string& locale) { - locale_ = locale; - } - - // Resource override. - thunk::PPB_PDF_API* AsPPB_PDF_API() override; - - // PPB_PDF_API implementation. - void SearchString(const unsigned short* input_string, - const unsigned short* input_term, - bool case_sensitive, - PP_PrivateFindResult** results, - uint32_t* count) override; - void DidStartLoading() override; - void DidStopLoading() override; - void SetContentRestriction(int restrictions) override; - void UserMetricsRecordAction(const PP_Var& action) override; - void HasUnsupportedFeature() override; - void Print() override; - void ShowAlertDialog(const char* messasge) override; - bool ShowConfirmDialog(const char* messasge) override; - PP_Var ShowPromptDialog(const char* messasge, - const char* default_answer) override; - void SaveAs() override; - PP_Bool IsFeatureEnabled(PP_PDFFeature feature) override; - void SetSelectedText(const char* selected_text) override; - void SetLinkUnderCursor(const char* url) override; - void GetV8ExternalSnapshotData(const char** snapshot_data_out, - int* snapshot_size_out) override; - void SetCrashData(const char* pdf_url, const char* top_level_url) override; - void SelectionChanged(const PP_FloatPoint& left, - int32_t left_height, - const PP_FloatPoint& right, - int32_t right_height) override; - void SetPluginCanSave(bool can_save) override; - - private: - std::string locale_; -}; - -} // namespace proxy -} // namespace ppapi - -#endif // PPAPI_PROXY_PDF_RESOURCE_H_
diff --git a/ppapi/proxy/pdf_resource_unittest.cc b/ppapi/proxy/pdf_resource_unittest.cc deleted file mode 100644 index f70149e8..0000000 --- a/ppapi/proxy/pdf_resource_unittest.cc +++ /dev/null
@@ -1,153 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include <cstring> - -#include "base/strings/utf_string_conversions.h" -#include "ppapi/c/dev/ppb_memory_dev.h" -#include "ppapi/c/pp_errors.h" -#include "ppapi/c/ppb_image_data.h" -#include "ppapi/proxy/pdf_resource.h" -#include "ppapi/proxy/ppapi_messages.h" -#include "ppapi/proxy/ppapi_proxy_test.h" -#include "ppapi/proxy/ppb_image_data_proxy.h" -#include "ppapi/proxy/serialized_handle.h" -#include "ppapi/shared_impl/proxy_lock.h" -#include "ppapi/shared_impl/scoped_pp_var.h" -#include "ppapi/shared_impl/var.h" -#include "ppapi/thunk/thunk.h" - -namespace ppapi { -namespace proxy { - -namespace { - -typedef PluginProxyTest PDFResourceTest; - -} // namespace - -TEST_F(PDFResourceTest, SearchString) { - ProxyAutoLock lock; - // Instantiate a resource explicitly so we can specify the locale. - auto pdf_resource = base::MakeRefCounted<PDFResource>( - Connection(&sink(), &sink(), 0), pp_instance()); - pdf_resource->SetLocaleForTest("en-US@collation=search"); - - std::u16string input; - std::u16string term; - base::UTF8ToUTF16("abcdefabcdef", 12, &input); - base::UTF8ToUTF16("bc", 2, &term); - - PP_PrivateFindResult* results; - uint32_t count = 0; - pdf_resource->SearchString( - reinterpret_cast<const unsigned short*>(input.c_str()), - reinterpret_cast<const unsigned short*>(term.c_str()), - true, - &results, - &count); - - ASSERT_EQ(2U, count); - ASSERT_EQ(1, results[0].start_index); - ASSERT_EQ(2, results[0].length); - ASSERT_EQ(7, results[1].start_index); - ASSERT_EQ(2, results[1].length); - - const PPB_Memory_Dev* memory_iface = thunk::GetPPB_Memory_Dev_0_1_Thunk(); - memory_iface->MemFree(results); -} - -TEST_F(PDFResourceTest, DidStartLoading) { - const PPB_PDF* pdf_iface = thunk::GetPPB_PDF_Thunk(); - - pdf_iface->DidStartLoading(pp_instance()); - - ResourceMessageCallParams params; - IPC::Message msg; - ASSERT_TRUE(sink().GetFirstResourceCallMatching( - PpapiHostMsg_PDF_DidStartLoading::ID, ¶ms, &msg)); -} - -TEST_F(PDFResourceTest, DidStopLoading) { - const PPB_PDF* pdf_iface = thunk::GetPPB_PDF_Thunk(); - - pdf_iface->DidStopLoading(pp_instance()); - - ResourceMessageCallParams params; - IPC::Message msg; - ASSERT_TRUE(sink().GetFirstResourceCallMatching( - PpapiHostMsg_PDF_DidStopLoading::ID, ¶ms, &msg)); -} - -TEST_F(PDFResourceTest, SetContentRestriction) { - const PPB_PDF* pdf_iface = thunk::GetPPB_PDF_Thunk(); - - int restrictions = 5; - pdf_iface->SetContentRestriction(pp_instance(), restrictions); - - ResourceMessageCallParams params; - IPC::Message msg; - ASSERT_TRUE(sink().GetFirstResourceCallMatching( - PpapiHostMsg_PDF_SetContentRestriction::ID, ¶ms, &msg)); -} - -TEST_F(PDFResourceTest, HasUnsupportedFeature) { - const PPB_PDF* pdf_iface = thunk::GetPPB_PDF_Thunk(); - - pdf_iface->HasUnsupportedFeature(pp_instance()); - - ResourceMessageCallParams params; - IPC::Message msg; - ASSERT_TRUE(sink().GetFirstResourceCallMatching( - PpapiHostMsg_PDF_HasUnsupportedFeature::ID, ¶ms, &msg)); -} - -TEST_F(PDFResourceTest, Print) { - const PPB_PDF* pdf_iface = thunk::GetPPB_PDF_Thunk(); - - pdf_iface->Print(pp_instance()); - - ResourceMessageCallParams params; - IPC::Message msg; - ASSERT_TRUE(sink().GetFirstResourceCallMatching( - PpapiHostMsg_PDF_Print::ID, ¶ms, &msg)); -} - -TEST_F(PDFResourceTest, SaveAs) { - const PPB_PDF* pdf_iface = thunk::GetPPB_PDF_Thunk(); - - pdf_iface->SaveAs(pp_instance()); - - ResourceMessageCallParams params; - IPC::Message msg; - ASSERT_TRUE(sink().GetFirstResourceCallMatching( - PpapiHostMsg_PDF_SaveAs::ID, ¶ms, &msg)); -} - -TEST_F(PDFResourceTest, SelectionChanged) { - const PPB_PDF* pdf_iface = thunk::GetPPB_PDF_Thunk(); - - PP_FloatPoint left = PP_MakeFloatPoint(0.0f, 0.0f); - PP_FloatPoint right = PP_MakeFloatPoint(1.0f, 1.0f); - pdf_iface->SelectionChanged(pp_instance(), &left, 0, &right, 0); - - ResourceMessageCallParams params; - IPC::Message msg; - ASSERT_TRUE(sink().GetFirstResourceCallMatching( - PpapiHostMsg_PDF_SelectionChanged::ID, ¶ms, &msg)); -} - -TEST_F(PDFResourceTest, SetPluginCanSave) { - const PPB_PDF* pdf_iface = thunk::GetPPB_PDF_Thunk(); - - pdf_iface->SetPluginCanSave(pp_instance(), true); - - ResourceMessageCallParams params; - IPC::Message msg; - ASSERT_TRUE(sink().GetFirstResourceCallMatching( - PpapiHostMsg_PDF_SetPluginCanSave::ID, ¶ms, &msg)); -} - -} // namespace proxy -} // namespace ppapi
diff --git a/ppapi/proxy/plugin_globals.cc b/ppapi/proxy/plugin_globals.cc index a5942a905..6cba804 100644 --- a/ppapi/proxy/plugin_globals.cc +++ b/ppapi/proxy/plugin_globals.cc
@@ -20,7 +20,6 @@ #include "ppapi/proxy/ppb_message_loop_proxy.h" #include "ppapi/proxy/resource_reply_thread_registrar.h" #include "ppapi/proxy/udp_socket_filter.h" -#include "ppapi/shared_impl/ppapi_constants.h" #include "ppapi/shared_impl/proxy_lock.h" #include "ppapi/thunk/enter.h"
diff --git a/ppapi/proxy/ppapi_messages.h b/ppapi/proxy/ppapi_messages.h index 17655cbb..d1290a26 100644 --- a/ppapi/proxy/ppapi_messages.h +++ b/ppapi/proxy/ppapi_messages.h
@@ -59,8 +59,6 @@ #include "ppapi/c/private/ppb_host_resolver_private.h" #include "ppapi/c/private/ppb_isolated_file_system_private.h" #include "ppapi/c/private/ppb_net_address_private.h" -#include "ppapi/c/private/ppb_pdf.h" -#include "ppapi/c/private/ppp_pdf.h" #include "ppapi/proxy/host_resolver_private_resource.h" #include "ppapi/proxy/network_list_resource.h" #include "ppapi/proxy/ppapi_param_traits.h" @@ -114,7 +112,6 @@ PP_PRINTORIENTATION_ROTATED_LAST) IPC_ENUM_TRAITS(PP_PrintOutputFormat_Dev) // Bitmask. IPC_ENUM_TRAITS_MAX_VALUE(PP_PrintScalingOption_Dev, PP_PRINTSCALINGOPTION_LAST) -IPC_ENUM_TRAITS_MAX_VALUE(PP_PrivateDuplexMode_Dev, PP_PRIVATEDUPLEXMODE_LAST) IPC_ENUM_TRAITS_MAX_VALUE(PP_PrivateFontCharset, PP_PRIVATEFONTCHARSET_LAST) IPC_ENUM_TRAITS_MAX_VALUE(PP_TCPSocket_Option, PP_TCPSOCKET_OPTION_RECV_BUFFER_SIZE) @@ -205,19 +202,6 @@ IPC_STRUCT_TRAITS_MEMBER(format) IPC_STRUCT_TRAITS_END() -IPC_STRUCT_TRAITS_BEGIN(PP_PdfPrintPresetOptions_Dev) - IPC_STRUCT_TRAITS_MEMBER(is_scaling_disabled) - IPC_STRUCT_TRAITS_MEMBER(copies) - IPC_STRUCT_TRAITS_MEMBER(duplex) - IPC_STRUCT_TRAITS_MEMBER(is_page_size_uniform) - IPC_STRUCT_TRAITS_MEMBER(uniform_page_size) -IPC_STRUCT_TRAITS_END() - -IPC_STRUCT_TRAITS_BEGIN(PP_PdfPrintSettings_Dev) - IPC_STRUCT_TRAITS_MEMBER(pages_per_sheet) - IPC_STRUCT_TRAITS_MEMBER(scale_factor) -IPC_STRUCT_TRAITS_END() - IPC_STRUCT_TRAITS_BEGIN(PP_URLComponent_Dev) IPC_STRUCT_TRAITS_MEMBER(begin) IPC_STRUCT_TRAITS_MEMBER(len) @@ -598,13 +582,6 @@ IPC_MESSAGE_ROUTED1(PpapiMsg_PPPMouseLock_MouseLockLost, PP_Instance /* instance */) -// PPP_Pdf -IPC_SYNC_MESSAGE_ROUTED3_1(PpapiMsg_PPPPdf_PrintBegin, - PP_Instance /* instance */, - PP_PrintSettings_Dev /* print_settings */, - PP_PdfPrintSettings_Dev /* pdf_print_settings */, - int32_t /* result */) - // PPP_Printing IPC_SYNC_MESSAGE_ROUTED1_1(PpapiMsg_PPPPrinting_QuerySupportedFormats, PP_Instance /* instance */, @@ -1812,84 +1789,6 @@ uint32_t /* callback_id */, std::vector<ppapi::DeviceRefData> /* devices */) -// Flash font file. -IPC_MESSAGE_CONTROL2(PpapiHostMsg_FlashFontFile_Create, - ppapi::proxy::SerializedFontDescription /* description */, - PP_PrivateFontCharset /* charset */) -IPC_MESSAGE_CONTROL1(PpapiHostMsg_FlashFontFile_GetFontTable, - uint32_t /* table */) -IPC_MESSAGE_CONTROL1(PpapiPluginMsg_FlashFontFile_GetFontTableReply, - std::string /* output */) - -// PDF ------------------------------------------------------------------------ - -// Creates the PDF resource. -IPC_MESSAGE_CONTROL0(PpapiHostMsg_PDF_Create) - -// Notifies the renderer that the PDF started loading. -IPC_MESSAGE_CONTROL0(PpapiHostMsg_PDF_DidStartLoading) - -// Notifies the renderer that the PDF stopped loading. -IPC_MESSAGE_CONTROL0(PpapiHostMsg_PDF_DidStopLoading) - -// Sets any restrictions on the PDF content. -IPC_MESSAGE_CONTROL1(PpapiHostMsg_PDF_SetContentRestriction, - int /* restrictions */) - -// Requests that the specified action be recorded with UMA. -IPC_MESSAGE_CONTROL1(PpapiHostMsg_PDF_UserMetricsRecordAction, - std::string /* action */) - -// Notifies the renderer that the current PDF uses an unsupported feature. -IPC_MESSAGE_CONTROL0(PpapiHostMsg_PDF_HasUnsupportedFeature) - -// Notifies the renderer to print the current PDF. -IPC_MESSAGE_CONTROL0(PpapiHostMsg_PDF_Print) - -// Notifies the renderer to display an alert dialog. -IPC_MESSAGE_CONTROL1(PpapiHostMsg_PDF_ShowAlertDialog, - std::string /* message */) -// Reply from the renderer that the alert has been acknowledged. -IPC_MESSAGE_CONTROL0(PpapiPluginMsg_PDF_ShowAlertDialogReply) - -// Notifies the renderer to display a confirmation dialog. -IPC_MESSAGE_CONTROL1(PpapiHostMsg_PDF_ShowConfirmDialog, - std::string /* message */) -// Reply from the renderer with the results of the confirm dialog. -IPC_MESSAGE_CONTROL1(PpapiPluginMsg_PDF_ShowConfirmDialogReply, - bool /* bool result */) - -// Notifies the renderer to display a prompt dialog. -IPC_MESSAGE_CONTROL2(PpapiHostMsg_PDF_ShowPromptDialog, - std::string /* message */, - std::string /* default answer */) -// Reply from the renderer with the results of the prompt dialog. -IPC_MESSAGE_CONTROL1(PpapiPluginMsg_PDF_ShowPromptDialogReply, - std::string /* str_result */) - -// Notifies the renderer to save the current PDF. -IPC_MESSAGE_CONTROL0(PpapiHostMsg_PDF_SaveAs) - -// Called by the plugin when its selection changes. -IPC_MESSAGE_CONTROL1(PpapiHostMsg_PDF_SetSelectedText, - std::u16string /* selected_text */) - -// Called by the plugin to set the link under the cursor. -IPC_MESSAGE_CONTROL1(PpapiHostMsg_PDF_SetLinkUnderCursor, - std::string /* url */) - -// Send information about the selection coordinates. -IPC_MESSAGE_CONTROL4(PpapiHostMsg_PDF_SelectionChanged, - PP_FloatPoint /* left */, - int32_t /* left_height */, - PP_FloatPoint /* right */, - int32_t /* right_height */) - -// Lets the renderer know that the PDF plugin can handle save commands -// internally. i.e. It will provide the data to save and trigger the download -// dialog. -IPC_MESSAGE_CONTROL1(PpapiHostMsg_PDF_SetPluginCanSave, bool /* can_save */) - // VideoCapture ---------------------------------------------------------------- // VideoCapture_Dev, plugin -> host
diff --git a/ppapi/proxy/ppb_instance_proxy.cc b/ppapi/proxy/ppb_instance_proxy.cc index 1d8882ca..12031dc 100644 --- a/ppapi/proxy/ppb_instance_proxy.cc +++ b/ppapi/proxy/ppb_instance_proxy.cc
@@ -25,7 +25,6 @@ #include "ppapi/proxy/isolated_file_system_private_resource.h" #include "ppapi/proxy/message_handler.h" #include "ppapi/proxy/network_proxy_resource.h" -#include "ppapi/proxy/pdf_resource.h" #include "ppapi/proxy/plugin_dispatcher.h" #include "ppapi/proxy/ppapi_messages.h" #include "ppapi/proxy/serialized_var.h" @@ -322,20 +321,13 @@ case UMA_SINGLETON_ID: new_singleton = new UMAPrivateResource(connection, instance); break; - case FLASH_FULLSCREEN_SINGLETON_ID: - NOTREACHED(); - break; // Flash/trusted resources aren't needed for NaCl. #if !BUILDFLAG(IS_NACL) && !defined(NACL_WIN64) case BROWSER_FONT_SINGLETON_ID: new_singleton = new BrowserFontSingletonResource(connection, instance); break; - case PDF_SINGLETON_ID: - new_singleton = new PDFResource(connection, instance); - break; #else case BROWSER_FONT_SINGLETON_ID: - case PDF_SINGLETON_ID: NOTREACHED(); break; #endif // !BUILDFLAG(IS_NACL) && !defined(NACL_WIN64)
diff --git a/ppapi/proxy/ppp_instance_proxy.cc b/ppapi/proxy/ppp_instance_proxy.cc index de545865..4c25b62 100644 --- a/ppapi/proxy/ppp_instance_proxy.cc +++ b/ppapi/proxy/ppp_instance_proxy.cc
@@ -35,7 +35,6 @@ using thunk::EnterInstanceAPINoLock; using thunk::EnterInstanceNoLock; using thunk::EnterResourceNoLock; -using thunk::PPB_Flash_Fullscreen_API; using thunk::PPB_Instance_API; using thunk::PPB_View_API;
diff --git a/ppapi/proxy/ppp_pdf_proxy.cc b/ppapi/proxy/ppp_pdf_proxy.cc deleted file mode 100644 index 58d3f48e..0000000 --- a/ppapi/proxy/ppp_pdf_proxy.cc +++ /dev/null
@@ -1,81 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ppapi/proxy/ppp_pdf_proxy.h" - -#include "build/build_config.h" -#include "ppapi/proxy/host_dispatcher.h" -#include "ppapi/proxy/ppapi_messages.h" -#include "ppapi/shared_impl/proxy_lock.h" - -namespace ppapi { -namespace proxy { - -namespace { - -#if !BUILDFLAG(IS_NACL) -int32_t PrintBegin(PP_Instance instance, - const PP_PrintSettings_Dev* print_settings, - const PP_PdfPrintSettings_Dev* pdf_print_settings) { - int32_t ret = 0; - HostDispatcher::GetForInstance(instance)->Send(new PpapiMsg_PPPPdf_PrintBegin( - API_ID_PPP_PDF, instance, *print_settings, *pdf_print_settings, &ret)); - return ret; -} - -const PPP_Pdf ppp_pdf_interface = { - &PrintBegin, -}; -#else -// The NaCl plugin doesn't need the host side interface - stub it out. -const PPP_Pdf ppp_pdf_interface = {}; -#endif - -} // namespace - -PPP_Pdf_Proxy::PPP_Pdf_Proxy(Dispatcher* dispatcher) - : InterfaceProxy(dispatcher), - ppp_pdf_(NULL) { - if (dispatcher->IsPlugin()) { - ppp_pdf_ = static_cast<const PPP_Pdf*>( - dispatcher->local_get_interface()(PPP_PDF_INTERFACE)); - } -} - -PPP_Pdf_Proxy::~PPP_Pdf_Proxy() { -} - -// static -const PPP_Pdf* PPP_Pdf_Proxy::GetProxyInterface() { - return &ppp_pdf_interface; -} - -bool PPP_Pdf_Proxy::OnMessageReceived(const IPC::Message& msg) { - if (!dispatcher()->IsPlugin()) - return false; - - bool handled = true; - IPC_BEGIN_MESSAGE_MAP(PPP_Pdf_Proxy, msg) - IPC_MESSAGE_HANDLER(PpapiMsg_PPPPdf_PrintBegin, OnPluginMsgPrintBegin) - IPC_MESSAGE_UNHANDLED(handled = false) - IPC_END_MESSAGE_MAP() - return handled; -} - -void PPP_Pdf_Proxy::OnPluginMsgPrintBegin( - PP_Instance instance, - const PP_PrintSettings_Dev& print_settings, - const PP_PdfPrintSettings_Dev& pdf_print_settings, - int32_t* result) { - if (!ppp_pdf_) { - *result = 0; - return; - } - - *result = CallWhileUnlocked(ppp_pdf_->PrintBegin, instance, &print_settings, - &pdf_print_settings); -} - -} // namespace proxy -} // namespace ppapi
diff --git a/ppapi/proxy/ppp_pdf_proxy.h b/ppapi/proxy/ppp_pdf_proxy.h deleted file mode 100644 index 9d034ae..0000000 --- a/ppapi/proxy/ppp_pdf_proxy.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 PPAPI_PROXY_PPP_PDF_PROXY_H_ -#define PPAPI_PROXY_PPP_PDF_PROXY_H_ - -#include "ppapi/c/private/ppp_pdf.h" -#include "ppapi/proxy/interface_proxy.h" - -namespace ppapi { - -namespace proxy { - -class PPP_Pdf_Proxy : public InterfaceProxy { - public: - explicit PPP_Pdf_Proxy(Dispatcher* dispatcher); - - PPP_Pdf_Proxy(const PPP_Pdf_Proxy&) = delete; - PPP_Pdf_Proxy& operator=(const PPP_Pdf_Proxy&) = delete; - - ~PPP_Pdf_Proxy() override; - - static const PPP_Pdf* GetProxyInterface(); - - // InterfaceProxy implementation. - bool OnMessageReceived(const IPC::Message& msg) override; - - private: - // Message handlers. - void OnPluginMsgPrintBegin(PP_Instance instance, - const PP_PrintSettings_Dev& print_settings, - const PP_PdfPrintSettings_Dev& pdf_print_settings, - int32_t* result); - - // When this proxy is in the plugin side, this value caches the interface - // pointer so we don't have to retrieve it from the dispatcher each time. - // In the host, this value is always NULL. - const PPP_Pdf* ppp_pdf_; -}; - -} // namespace proxy -} // namespace ppapi - -#endif // PPAPI_PROXY_PPP_PDF_PROXY_H_
diff --git a/ppapi/proxy/resource_creation_proxy.cc b/ppapi/proxy/resource_creation_proxy.cc index 380fad4..5cc1aaf 100644 --- a/ppapi/proxy/resource_creation_proxy.cc +++ b/ppapi/proxy/resource_creation_proxy.cc
@@ -15,7 +15,6 @@ #include "ppapi/proxy/file_io_resource.h" #include "ppapi/proxy/file_ref_resource.h" #include "ppapi/proxy/file_system_resource.h" -#include "ppapi/proxy/flash_font_file_resource.h" #include "ppapi/proxy/graphics_2d_resource.h" #include "ppapi/proxy/host_resolver_private_resource.h" #include "ppapi/proxy/host_resolver_resource.h" @@ -405,14 +404,6 @@ return PPB_Buffer_Proxy::CreateProxyResource(instance, size); } -PP_Resource ResourceCreationProxy::CreateFlashFontFile( - PP_Instance instance, - const PP_BrowserFont_Trusted_Description* description, - PP_PrivateFontCharset charset) { - return (new FlashFontFileResource( - GetConnection(), instance, description, charset))->GetReference(); -} - PP_Resource ResourceCreationProxy::CreateVideoCapture(PP_Instance instance) { PluginDispatcher* dispatcher = PluginDispatcher::GetForInstance(instance); if (!dispatcher)
diff --git a/ppapi/proxy/resource_creation_proxy.h b/ppapi/proxy/resource_creation_proxy.h index f98bc14..36da978 100644 --- a/ppapi/proxy/resource_creation_proxy.h +++ b/ppapi/proxy/resource_creation_proxy.h
@@ -161,10 +161,6 @@ PP_Instance instance, const PP_BrowserFont_Trusted_Description* description) override; PP_Resource CreateBuffer(PP_Instance instance, uint32_t size) override; - PP_Resource CreateFlashFontFile( - PP_Instance instance, - const PP_BrowserFont_Trusted_Description* description, - PP_PrivateFontCharset charset) override; PP_Resource CreateVideoCapture(PP_Instance instance) override; PP_Resource CreateVideoDecoderDev( PP_Instance instance,
diff --git a/ppapi/shared_impl/BUILD.gn b/ppapi/shared_impl/BUILD.gn index 2931e65..c496f4f 100644 --- a/ppapi/shared_impl/BUILD.gn +++ b/ppapi/shared_impl/BUILD.gn
@@ -61,7 +61,6 @@ "ppb_audio_config_shared.h", "ppb_device_ref_shared.cc", "ppb_device_ref_shared.h", - "ppb_flash_font_file_shared.h", "ppb_image_data_shared.cc", "ppb_image_data_shared.h", "ppb_message_loop_shared.cc", @@ -139,7 +138,6 @@ "media_stream_video_track_shared.h", "platform_file.cc", "platform_file.h", - "ppapi_constants.h", "ppapi_nacl_plugin_args.cc", "ppapi_nacl_plugin_args.h", "ppapi_permissions.cc",
diff --git a/ppapi/shared_impl/api_id.h b/ppapi/shared_impl/api_id.h index 4845f96c..f9522f0 100644 --- a/ppapi/shared_impl/api_id.h +++ b/ppapi/shared_impl/api_id.h
@@ -26,14 +26,12 @@ API_ID_PPB_VIDEO_DECODER_DEV, API_ID_PPB_X509_CERTIFICATE_PRIVATE, API_ID_PPP_CLASS, - API_ID_PPP_FIND_PRIVATE, API_ID_PPP_GRAPHICS_3D, API_ID_PPP_INPUT_EVENT, API_ID_PPP_INSTANCE, API_ID_PPP_INSTANCE_PRIVATE, API_ID_PPP_MESSAGING, API_ID_PPP_MOUSE_LOCK, - API_ID_PPP_PDF, API_ID_PPP_PRINTING, API_ID_PPP_TEXT_INPUT, API_ID_PPP_VIDEO_DECODER_DEV,
diff --git a/ppapi/shared_impl/ppapi_constants.h b/ppapi/shared_impl/ppapi_constants.h deleted file mode 100644 index 528dfe2..0000000 --- a/ppapi/shared_impl/ppapi_constants.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 PPAPI_SHARED_IMPL_PPAPI_CONSTANTS_H_ -#define PPAPI_SHARED_IMPL_PPAPI_CONSTANTS_H_ - -#include "build/build_config.h" -#include "ppapi/shared_impl/ppapi_shared_export.h" - -namespace ppapi { - -#if BUILDFLAG(IS_WIN) -const char kCorbTestPluginName[] = "corb_test_plugin.dll"; -#elif BUILDFLAG(IS_MAC) -const char kCorbTestPluginName[] = "corb_test_plugin.plugin"; -#elif BUILDFLAG(IS_POSIX) -const char kCorbTestPluginName[] = "libcorb_test_plugin.so"; -#endif - -} // namespace ppapi - -#endif // PPAPI_SHARED_IMPL_PPAPI_CONSTANTS_H_
diff --git a/ppapi/shared_impl/ppapi_nacl_plugin_args.cc b/ppapi/shared_impl/ppapi_nacl_plugin_args.cc index c30470b..92df690 100644 --- a/ppapi/shared_impl/ppapi_nacl_plugin_args.cc +++ b/ppapi/shared_impl/ppapi_nacl_plugin_args.cc
@@ -2,7 +2,6 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "ppapi/shared_impl/ppapi_constants.h" #include "ppapi/shared_impl/ppapi_nacl_plugin_args.h" namespace ppapi {
diff --git a/ppapi/shared_impl/ppb_flash_font_file_shared.h b/ppapi/shared_impl/ppb_flash_font_file_shared.h deleted file mode 100644 index 85ec991..0000000 --- a/ppapi/shared_impl/ppb_flash_font_file_shared.h +++ /dev/null
@@ -1,19 +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 PPAPI_SHARED_IMPL_PPB_FLASH_FONT_FILE_SHARED_H_ -#define PPAPI_SHARED_IMPL_PPB_FLASH_FONT_FILE_SHARED_H_ - -#include "ppapi/c/pp_bool.h" - -namespace ppapi { - -class PPB_Flash_FontFile_Shared { - public: - static PP_Bool IsSupportedForWindows() { return PP_TRUE; } -}; - -} // namespace ppapi - -#endif // PPAPI_SHARED_IMPL_PPB_FLASH_FONT_FILE_SHARED_H_ \ No newline at end of file
diff --git a/ppapi/shared_impl/resource.h b/ppapi/shared_impl/resource.h index e5df24e..13dcafe5 100644 --- a/ppapi/shared_impl/resource.h +++ b/ppapi/shared_impl/resource.h
@@ -35,9 +35,6 @@ F(PPB_FileIO_API) \ F(PPB_FileRef_API) \ F(PPB_FileSystem_API) \ - F(PPB_Find_API) \ - F(PPB_Flash_FontFile_API) \ - F(PPB_Flash_Fullscreen_API) \ F(PPB_Gamepad_API) \ F(PPB_Graphics2D_API) \ F(PPB_Graphics3D_API) \ @@ -53,7 +50,6 @@ F(PPB_NetworkList_API) \ F(PPB_NetworkMonitor_API) \ F(PPB_NetworkProxy_API) \ - F(PPB_PDF_API) \ F(PPB_Printing_API) \ F(PPB_Scrollbar_API) \ F(PPB_TCPServerSocket_Private_API) \
diff --git a/ppapi/shared_impl/singleton_resource_id.h b/ppapi/shared_impl/singleton_resource_id.h index b41a34dd2..36550af 100644 --- a/ppapi/shared_impl/singleton_resource_id.h +++ b/ppapi/shared_impl/singleton_resource_id.h
@@ -11,11 +11,9 @@ // PPB_Instance_API.GetSingletonResource. enum SingletonResourceID { BROWSER_FONT_SINGLETON_ID, - FLASH_FULLSCREEN_SINGLETON_ID, GAMEPAD_SINGLETON_ID, ISOLATED_FILESYSTEM_SINGLETON_ID, NETWORK_PROXY_SINGLETON_ID, - PDF_SINGLETON_ID, UMA_SINGLETON_ID, };
diff --git a/ppapi/tests/OWNERS b/ppapi/tests/OWNERS index 107fb80..17525ab 100644 --- a/ppapi/tests/OWNERS +++ b/ppapi/tests/OWNERS
@@ -1,3 +1,2 @@ per-file blink_test_plugin.cc=dcheng@chromium.org per-file blink_deprecated_test_plugin.cc=dcheng@chromium.org -per-file test_pdf.*=thestig@chromium.org
diff --git a/ppapi/tests/all_c_includes.h b/ppapi/tests/all_c_includes.h index 71e8a00..98b6acf 100644 --- a/ppapi/tests/all_c_includes.h +++ b/ppapi/tests/all_c_includes.h
@@ -99,11 +99,9 @@ #include "ppapi/c/private/ppb_display_color_profile_private.h" #include "ppapi/c/private/ppb_ext_crx_file_system_private.h" #include "ppapi/c/private/ppb_file_io_private.h" -#include "ppapi/c/private/ppb_flash_font_file.h" #include "ppapi/c/private/ppb_host_resolver_private.h" #include "ppapi/c/private/ppb_instance_private.h" #include "ppapi/c/private/ppb_net_address_private.h" -#include "ppapi/c/private/ppb_pdf.h" #include "ppapi/c/private/ppb_proxy_private.h" #include "ppapi/c/private/ppb_tcp_socket_private.h" #include "ppapi/c/private/ppb_testing_private.h"
diff --git a/ppapi/tests/all_cpp_includes.h b/ppapi/tests/all_cpp_includes.h index 9f6364d..ed29cd5 100644 --- a/ppapi/tests/all_cpp_includes.h +++ b/ppapi/tests/all_cpp_includes.h
@@ -46,7 +46,6 @@ #include "ppapi/cpp/point.h" #include "ppapi/cpp/private/camera_capabilities_private.h" #include "ppapi/cpp/private/camera_device_private.h" -#include "ppapi/cpp/private/flash_font_file.h" #include "ppapi/cpp/private/instance_private.h" #include "ppapi/cpp/private/net_address_private.h" #include "ppapi/cpp/private/tcp_socket_private.h"
diff --git a/ppapi/tests/corb_test_plugin.cc b/ppapi/tests/corb_test_plugin.cc deleted file mode 100644 index a23597b..0000000 --- a/ppapi/tests/corb_test_plugin.cc +++ /dev/null
@@ -1,93 +0,0 @@ -// Copyright 2018 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include <stdint.h> - -#include <sstream> - -#include "ppapi/c/trusted/ppb_url_loader_trusted.h" -#include "ppapi/cpp/instance.h" -#include "ppapi/cpp/module.h" -#include "ppapi/cpp/url_loader.h" -#include "ppapi/cpp/url_request_info.h" -#include "ppapi/tests/test_utils.h" - -// Windows defines 'PostMessage', so we have to undef it. -#ifdef PostMessage -#undef PostMessage -#endif - -// This is a simple C++ Pepper plugin that enables some NetworkService/CORB -// tests (e.g. NetworkServiceRestartBrowserTest.Plugin). -class CorbTestInstance : public pp::Instance { - public: - explicit CorbTestInstance(PP_Instance instance) : pp::Instance(instance) {} - ~CorbTestInstance() override {} - - void HandleMessage(const pp::Var& message_data) override { - if (!message_data.is_string()) - return; - - std::string msg = message_data.AsString(); - const std::string kRequestUrlMsgPrefix("requestUrl: "); - if (msg.substr(0, kRequestUrlMsgPrefix.size()) == kRequestUrlMsgPrefix) { - // This is for NetworkServiceRestartBrowserTest.Plugin test. - std::string url = msg.substr(kRequestUrlMsgPrefix.size()); - RequestURLAndPostResponseBody(url); - } - } - - private: - void RequestURLAndPostResponseBody(const std::string& url) { - pp::URLLoader loader(this); - - const PPB_URLLoaderTrusted* url_loader_trusted_interface = nullptr; - url_loader_trusted_interface = static_cast<const PPB_URLLoaderTrusted*>( - pp::Module::Get()->GetBrowserInterface(PPB_URLLOADERTRUSTED_INTERFACE)); - url_loader_trusted_interface->GrantUniversalAccess(loader.pp_resource()); - - pp::URLRequestInfo request(this); - request.SetURL(url); - request.SetAllowCrossOriginRequests(true); - - // Set the |request_initiator| in the same way as the PDF plugin. - // - // (The PDF plugin is currently the only plugin that depends on relaxing - // `request_initiator_origin_lock` enforcement via - // network::mojom::NetworkService::AddAllowedRequestInitiatorForPlugin.) - request.SetCustomReferrerURL(url); - - std::ostringstream msg_builder; - std::string response_body; - int result = OpenURLRequest(this->pp_instance(), &loader, request, - PP_OPTIONAL, &response_body); - if (result == PP_OK) { - msg_builder << "requestUrl: " - << "RESPONSE BODY: " << response_body; - } else { - msg_builder << "requestUrl: " - << "PPAPI ERROR: " << result; - } - - PostMessage(pp::Var(msg_builder.str())); - } -}; - -class CorbTestModule : public pp::Module { - public: - CorbTestModule() : pp::Module() {} - virtual ~CorbTestModule() {} - - virtual pp::Instance* CreateInstance(PP_Instance instance) { - return new CorbTestInstance(instance); - } -}; - -namespace pp { - -Module* CreateModule() { - return new CorbTestModule(); -} - -} // namespace pp
diff --git a/ppapi/tests/test_pdf.cc b/ppapi/tests/test_pdf.cc deleted file mode 100644 index 644cf2619..0000000 --- a/ppapi/tests/test_pdf.cc +++ /dev/null
@@ -1,37 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ppapi/tests/test_pdf.h" - -#include "ppapi/c/private/ppb_pdf.h" -#include "ppapi/cpp/image_data.h" -#include "ppapi/cpp/point.h" -#include "ppapi/cpp/private/pdf.h" -#include "ppapi/cpp/var.h" -#include "ppapi/tests/testing_instance.h" - -REGISTER_TEST_CASE(PDF); - -TestPDF::TestPDF(TestingInstance* instance) - : TestCase(instance) { -} - -void TestPDF::RunTests(const std::string& filter) { - RUN_TEST(GetV8ExternalSnapshotData, filter); -} - -std::string TestPDF::TestGetV8ExternalSnapshotData() { - const char* snapshot_data; - int snapshot_size; - - pp::PDF::GetV8ExternalSnapshotData(instance_, &snapshot_data, &snapshot_size); -#ifdef V8_USE_EXTERNAL_STARTUP_DATA - ASSERT_NE(snapshot_data, (char*) (NULL)); - ASSERT_NE(snapshot_size, 0); -#else - ASSERT_EQ(snapshot_data, (char*) (NULL)); - ASSERT_EQ(snapshot_size, 0); -#endif - PASS(); -}
diff --git a/ppapi/tests/test_pdf.h b/ppapi/tests/test_pdf.h deleted file mode 100644 index 10effb9..0000000 --- a/ppapi/tests/test_pdf.h +++ /dev/null
@@ -1,25 +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 PPAPI_TESTS_TEST_PDF_H_ -#define PPAPI_TESTS_TEST_PDF_H_ - -#include <string> - -#include "ppapi/c/pp_stdint.h" -#include "ppapi/tests/test_case.h" - -class TestPDF : public TestCase { - public: - explicit TestPDF(TestingInstance* instance); - - // TestCase implementation. - virtual void RunTests(const std::string& filter); - - private: - std::string TestGetLocalizedString(); - std::string TestGetV8ExternalSnapshotData(); -}; - -#endif // PPAPI_TESTS_TEST_PDF_H_
diff --git a/ppapi/thunk/BUILD.gn b/ppapi/thunk/BUILD.gn index 2228cf3c..cd481ad 100644 --- a/ppapi/thunk/BUILD.gn +++ b/ppapi/thunk/BUILD.gn
@@ -11,7 +11,6 @@ "enter.h", "interfaces_postamble.h", "interfaces_ppb_private.h", - "interfaces_ppb_private_flash.h", "interfaces_ppb_private_no_permissions.h", "interfaces_ppb_public_dev.h", "interfaces_ppb_public_dev_channel.h", @@ -71,7 +70,6 @@ "ppb_file_ref_thunk.cc", "ppb_file_system_api.h", "ppb_file_system_thunk.cc", - "ppb_flash_font_file_api.h", "ppb_fullscreen_thunk.cc", "ppb_gamepad_api.h", "ppb_gamepad_thunk.cc", @@ -106,7 +104,6 @@ "ppb_network_monitor_thunk.cc", "ppb_network_proxy_api.h", "ppb_network_proxy_thunk.cc", - "ppb_pdf_api.h", "ppb_printing_api.h", "ppb_printing_dev_thunk.cc", "ppb_tcp_server_socket_private_api.h", @@ -155,9 +152,7 @@ "ppb_browser_font_trusted_thunk.cc", "ppb_buffer_thunk.cc", "ppb_char_set_thunk.cc", - "ppb_flash_font_file_thunk.cc", "ppb_gles_chromium_texture_mapping_thunk.cc", - "ppb_pdf_thunk.cc", "ppb_url_util_thunk.cc", "ppb_video_capture_thunk.cc", "ppb_video_decoder_dev_thunk.cc",
diff --git a/ppapi/thunk/OWNERS b/ppapi/thunk/OWNERS deleted file mode 100644 index 926c489e..0000000 --- a/ppapi/thunk/OWNERS +++ /dev/null
@@ -1,3 +0,0 @@ -per-file interfaces_ppb_private_pdf.h=thestig@chromium.org -per-file ppb_pdf_thunk.cc=thestig@chromium.org -per-file ppb_pdf_api.h=thestig@chromium.org
diff --git a/ppapi/thunk/interfaces_ppb_private_flash.h b/ppapi/thunk/interfaces_ppb_private_flash.h deleted file mode 100644 index 20ead8e..0000000 --- a/ppapi/thunk/interfaces_ppb_private_flash.h +++ /dev/null
@@ -1,17 +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. - -// Please see inteface_ppb_public_stable for the documentation on the format of -// this file. - -// no-include-guard-because-multiply-included - -#include "ppapi/thunk/interfaces_preamble.h" - -PROXIED_IFACE(PPB_FLASH_FONTFILE_INTERFACE_0_1, - PPB_Flash_FontFile_0_1) -PROXIED_IFACE(PPB_FLASH_FONTFILE_INTERFACE_0_2, - PPB_Flash_FontFile_0_2) - -#include "ppapi/thunk/interfaces_postamble.h"
diff --git a/ppapi/thunk/interfaces_ppb_private_pdf.h b/ppapi/thunk/interfaces_ppb_private_pdf.h deleted file mode 100644 index 008e3102..0000000 --- a/ppapi/thunk/interfaces_ppb_private_pdf.h +++ /dev/null
@@ -1,19 +0,0 @@ -// Copyright 2018 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -// Please see inteface_ppb_public_stable for the documentation on the format of -// this file. - -// no-include-guard-because-multiply-included - -#include "build/build_config.h" -#include "ppapi/thunk/interfaces_preamble.h" - -// See interfaces_ppb_private_no_permissions.h for other private interfaces. - -#if !BUILDFLAG(IS_NACL) -PROXIED_IFACE(PPB_PDF_INTERFACE, PPB_PDF) -#endif // !BUILDFLAG(IS_NACL) - -#include "ppapi/thunk/interfaces_postamble.h"
diff --git a/ppapi/thunk/ppb_flash_font_file_api.h b/ppapi/thunk/ppb_flash_font_file_api.h deleted file mode 100644 index 9e8ce23..0000000 --- a/ppapi/thunk/ppb_flash_font_file_api.h +++ /dev/null
@@ -1,26 +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 PPAPI_THUNK_PPB_FLASH_FONT_FILE_API_H_ -#define PPAPI_THUNK_PPB_FLASH_FONT_FILE_API_H_ - -#include "ppapi/c/pp_stdint.h" - -namespace ppapi { -namespace thunk { - -class PPB_Flash_FontFile_API { - public: - virtual ~PPB_Flash_FontFile_API() {} - - virtual PP_Bool GetFontTable(uint32_t table, - void* output, - uint32_t* output_length) = 0; -}; - -} // namespace thunk -} // namespace ppapi - -#endif // PPAPI_THUNK_PPB_FLASH_FONT_FILE_API_H_ -
diff --git a/ppapi/thunk/ppb_flash_font_file_thunk.cc b/ppapi/thunk/ppb_flash_font_file_thunk.cc deleted file mode 100644 index 37a85fe..0000000 --- a/ppapi/thunk/ppb_flash_font_file_thunk.cc +++ /dev/null
@@ -1,74 +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. - -// From private/ppb_flash_font_file.idl modified Wed Mar 9 12:48:51 2016. - -#include <stdint.h> - -#include "base/logging.h" -#include "ppapi/c/pp_errors.h" -#include "ppapi/c/private/ppb_flash_font_file.h" -#include "ppapi/shared_impl/ppb_flash_font_file_shared.h" -#include "ppapi/shared_impl/tracked_callback.h" -#include "ppapi/thunk/enter.h" -#include "ppapi/thunk/ppapi_thunk_export.h" -#include "ppapi/thunk/ppb_flash_font_file_api.h" - -namespace ppapi { -namespace thunk { - -namespace { - -PP_Resource Create(PP_Instance instance, - const struct PP_BrowserFont_Trusted_Description* description, - PP_PrivateFontCharset charset) { - VLOG(4) << "PPB_Flash_FontFile::Create()"; - EnterResourceCreation enter(instance); - if (enter.failed()) - return 0; - return enter.functions()->CreateFlashFontFile(instance, description, charset); -} - -PP_Bool IsFlashFontFile(PP_Resource resource) { - VLOG(4) << "PPB_Flash_FontFile::IsFlashFontFile()"; - EnterResource<PPB_Flash_FontFile_API> enter(resource, false); - return PP_FromBool(enter.succeeded()); -} - -PP_Bool GetFontTable(PP_Resource font_file, - uint32_t table, - void* output, - uint32_t* output_length) { - VLOG(4) << "PPB_Flash_FontFile::GetFontTable()"; - EnterResource<PPB_Flash_FontFile_API> enter(font_file, true); - if (enter.failed()) - return PP_FALSE; - return enter.object()->GetFontTable(table, output, output_length); -} - -PP_Bool IsSupportedForWindows(void) { - VLOG(4) << "PPB_Flash_FontFile::IsSupportedForWindows()"; - return PPB_Flash_FontFile_Shared::IsSupportedForWindows(); -} - -const PPB_Flash_FontFile_0_1 g_ppb_flash_fontfile_thunk_0_1 = { - &Create, &IsFlashFontFile, &GetFontTable}; - -const PPB_Flash_FontFile_0_2 g_ppb_flash_fontfile_thunk_0_2 = { - &Create, &IsFlashFontFile, &GetFontTable, &IsSupportedForWindows}; - -} // namespace - -PPAPI_THUNK_EXPORT const PPB_Flash_FontFile_0_1* -GetPPB_Flash_FontFile_0_1_Thunk() { - return &g_ppb_flash_fontfile_thunk_0_1; -} - -PPAPI_THUNK_EXPORT const PPB_Flash_FontFile_0_2* -GetPPB_Flash_FontFile_0_2_Thunk() { - return &g_ppb_flash_fontfile_thunk_0_2; -} - -} // namespace thunk -} // namespace ppapi
diff --git a/ppapi/thunk/ppb_pdf_api.h b/ppapi/thunk/ppb_pdf_api.h deleted file mode 100644 index aeb033cd..0000000 --- a/ppapi/thunk/ppb_pdf_api.h +++ /dev/null
@@ -1,50 +0,0 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef PPAPI_THUNK_PPB_PDF_API_H_ -#define PPAPI_THUNK_PPB_PDF_API_H_ - -#include "ppapi/c/private/ppb_pdf.h" -#include "ppapi/shared_impl/singleton_resource_id.h" - -namespace ppapi { -namespace thunk { - -class PPB_PDF_API { - public: - virtual void SearchString(const unsigned short* input_string, - const unsigned short* input_term, - bool case_sensitive, - PP_PrivateFindResult** results, - uint32_t* count) = 0; - virtual void DidStartLoading() = 0; - virtual void DidStopLoading() = 0; - virtual void SetContentRestriction(int restrictions) = 0; - virtual void UserMetricsRecordAction(const PP_Var& action) = 0; - virtual void HasUnsupportedFeature() = 0; - virtual void ShowAlertDialog(const char* message) = 0; - virtual bool ShowConfirmDialog(const char* message) = 0; - virtual PP_Var ShowPromptDialog(const char* message, - const char* default_answer) = 0; - virtual void SaveAs() = 0; - virtual PP_Bool IsFeatureEnabled(PP_PDFFeature feature) = 0; - virtual void Print() = 0; - virtual void SetSelectedText(const char* selected_text) = 0; - virtual void SetLinkUnderCursor(const char* url) = 0; - virtual void GetV8ExternalSnapshotData(const char** snapshot_data_out, - int* snapshot_size_out) = 0; - virtual void SetCrashData(const char* pdf_url, const char* top_level_url) = 0; - virtual void SelectionChanged(const PP_FloatPoint& left, - int32_t left_height, - const PP_FloatPoint& right, - int32_t right_height) = 0; - virtual void SetPluginCanSave(bool can_save) = 0; - - static const SingletonResourceID kSingletonResourceID = PDF_SINGLETON_ID; -}; - -} // namespace thunk -} // namespace ppapi - -#endif // PPAPI_THUNK_PPB_PDF_API_H_
diff --git a/ppapi/thunk/ppb_pdf_thunk.cc b/ppapi/thunk/ppb_pdf_thunk.cc deleted file mode 100644 index 464a022d..0000000 --- a/ppapi/thunk/ppb_pdf_thunk.cc +++ /dev/null
@@ -1,210 +0,0 @@ -// Copyright (c) 2013 The Chromium 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 <stdint.h> - -#include "ppapi/c/pp_errors.h" -#include "ppapi/c/private/ppb_pdf.h" -#include "ppapi/thunk/enter.h" -#include "ppapi/thunk/ppb_flash_font_file_api.h" -#include "ppapi/thunk/ppb_pdf_api.h" -#include "ppapi/thunk/resource_creation_api.h" -#include "ppapi/thunk/thunk.h" - -namespace ppapi { -namespace thunk { - -namespace { - -PP_Resource GetFontFileWithFallback( - PP_Instance instance, - const PP_BrowserFont_Trusted_Description* description, - PP_PrivateFontCharset charset) { - // TODO(raymes): Eventually we should replace the use of this function with - // PPB_Flash_Font_File directly in the PDF code. - // For now just call into PPB_Flash_Font_File which has the exact same API. - EnterResourceCreation enter(instance); - if (enter.failed()) - return 0; - return enter.functions()->CreateFlashFontFile(instance, description, charset); -} - -bool GetFontTableForPrivateFontFile(PP_Resource font_file, - uint32_t table, - void* output, - uint32_t* output_length) { - // TODO(raymes): Eventually we should replace the use of this function with - // PPB_Flash_Font_File directly in the PDF code. - // For now just call into PPB_Flash_Font_File which has the exact same API. - EnterResource<PPB_Flash_FontFile_API> enter(font_file, true); - if (enter.failed()) - return PP_FALSE; - return PP_ToBool(enter.object()->GetFontTable(table, output, output_length)); -} - -void SearchString(PP_Instance instance, - const unsigned short* string, - const unsigned short* term, - bool case_sensitive, - PP_PrivateFindResult** results, - uint32_t* count) { - EnterInstanceAPI<PPB_PDF_API> enter(instance); - if (enter.failed()) - return; - enter.functions()->SearchString(string, term, case_sensitive, results, count); -} - -void DidStartLoading(PP_Instance instance) { - EnterInstanceAPI<PPB_PDF_API> enter(instance); - if (enter.succeeded()) - enter.functions()->DidStartLoading(); -} - -void DidStopLoading(PP_Instance instance) { - EnterInstanceAPI<PPB_PDF_API> enter(instance); - if (enter.succeeded()) - enter.functions()->DidStopLoading(); -} - -void SetContentRestriction(PP_Instance instance, int restrictions) { - EnterInstanceAPI<PPB_PDF_API> enter(instance); - if (enter.succeeded()) - enter.functions()->SetContentRestriction(restrictions); -} - -void UserMetricsRecordAction(PP_Instance instance, PP_Var action) { - EnterInstanceAPI<PPB_PDF_API> enter(instance); - if (enter.succeeded()) - enter.functions()->UserMetricsRecordAction(action); -} - -void HasUnsupportedFeature(PP_Instance instance) { - EnterInstanceAPI<PPB_PDF_API> enter(instance); - if (enter.succeeded()) - enter.functions()->HasUnsupportedFeature(); -} - -void ShowAlertDialog(PP_Instance instance, const char* message) { - EnterInstanceAPI<PPB_PDF_API> enter(instance); - if (enter.succeeded()) - enter.functions()->ShowAlertDialog(message); -} - -bool ShowConfirmDialog(PP_Instance instance, const char* message) { - EnterInstanceAPI<PPB_PDF_API> enter(instance); - if (enter.succeeded()) - return enter.functions()->ShowConfirmDialog(message); - return false; -} - -PP_Var ShowPromptDialog(PP_Instance instance, - const char* message, - const char* default_answer) { - EnterInstanceAPI<PPB_PDF_API> enter(instance); - if (enter.succeeded()) - return enter.functions()->ShowPromptDialog(message, default_answer); - return PP_MakeUndefined(); -} - -void SaveAs(PP_Instance instance) { - EnterInstanceAPI<PPB_PDF_API> enter(instance); - if (enter.succeeded()) - enter.functions()->SaveAs(); -} - -void Print(PP_Instance instance) { - EnterInstanceAPI<PPB_PDF_API> enter(instance); - if (enter.succeeded()) - enter.functions()->Print(); -} - -PP_Bool IsFeatureEnabled(PP_Instance instance, PP_PDFFeature feature) { - EnterInstanceAPI<PPB_PDF_API> enter(instance); - if (enter.failed()) - return PP_FALSE; - return enter.functions()->IsFeatureEnabled(feature); -} - -void SetSelectedText(PP_Instance instance, - const char* selected_text) { - EnterInstanceAPI<PPB_PDF_API> enter(instance); - if (enter.succeeded()) - enter.functions()->SetSelectedText(selected_text); -} - -void SetLinkUnderCursor(PP_Instance instance, const char* url) { - EnterInstanceAPI<PPB_PDF_API> enter(instance); - if (enter.failed()) - return; - enter.functions()->SetLinkUnderCursor(url); -} - -void GetV8ExternalSnapshotData(PP_Instance instance, - const char** snapshot_data_out, - int* snapshot_size_out) { - EnterInstanceAPI<PPB_PDF_API> enter(instance); - if (enter.failed()) - return; - enter.functions()->GetV8ExternalSnapshotData(snapshot_data_out, - snapshot_size_out); -} - -void SetCrashData(PP_Instance instance, - const char* pdf_url, - const char* top_level_url) { - EnterInstanceAPI<PPB_PDF_API> enter(instance); - if (enter.failed()) - return; - enter.functions()->SetCrashData(pdf_url, top_level_url); -} - -void SelectionChanged(PP_Instance instance, - const PP_FloatPoint* left, - int32_t left_height, - const PP_FloatPoint* right, - int32_t right_height) { - EnterInstanceAPI<PPB_PDF_API> enter(instance); - if (enter.failed()) - return; - enter.functions()->SelectionChanged(*left, left_height, *right, right_height); -} - -void SetPluginCanSave(PP_Instance instance, bool can_save) { - EnterInstanceAPI<PPB_PDF_API> enter(instance); - if (enter.failed()) - return; - enter.functions()->SetPluginCanSave(can_save); -} - -const PPB_PDF g_ppb_pdf_thunk = { - &GetFontFileWithFallback, - &GetFontTableForPrivateFontFile, - &SearchString, - &DidStartLoading, - &DidStopLoading, - &SetContentRestriction, - &UserMetricsRecordAction, - &HasUnsupportedFeature, - &SaveAs, - &Print, - &IsFeatureEnabled, - &SetSelectedText, - &SetLinkUnderCursor, - &GetV8ExternalSnapshotData, - &SetCrashData, - &SelectionChanged, - &SetPluginCanSave, - &ShowAlertDialog, - &ShowConfirmDialog, - &ShowPromptDialog, -}; - -} // namespace - -const PPB_PDF* GetPPB_PDF_Thunk() { - return &g_ppb_pdf_thunk; -} - -} // namespace thunk -} // namespace ppapi
diff --git a/ppapi/thunk/resource_creation_api.h b/ppapi/thunk/resource_creation_api.h index c20ed8f1..098432b 100644 --- a/ppapi/thunk/resource_creation_api.h +++ b/ppapi/thunk/resource_creation_api.h
@@ -182,10 +182,6 @@ PP_Instance instance, const PP_BrowserFont_Trusted_Description* description) = 0; virtual PP_Resource CreateBuffer(PP_Instance instance, uint32_t size) = 0; - virtual PP_Resource CreateFlashFontFile( - PP_Instance instance, - const PP_BrowserFont_Trusted_Description* description, - PP_PrivateFontCharset charset) = 0; virtual PP_Resource CreateVideoCapture(PP_Instance instance) = 0; virtual PP_Resource CreateVideoDecoderDev( PP_Instance instance,
diff --git a/ppapi/thunk/thunk.h b/ppapi/thunk/thunk.h index 99a24c6d..8809070 100644 --- a/ppapi/thunk/thunk.h +++ b/ppapi/thunk/thunk.h
@@ -19,9 +19,7 @@ } } #include "ppapi/thunk/interfaces_ppb_private.h" -#include "ppapi/thunk/interfaces_ppb_private_flash.h" #include "ppapi/thunk/interfaces_ppb_private_no_permissions.h" -#include "ppapi/thunk/interfaces_ppb_private_pdf.h" #include "ppapi/thunk/interfaces_ppb_public_dev.h" #include "ppapi/thunk/interfaces_ppb_public_dev_channel.h" #include "ppapi/thunk/interfaces_ppb_public_socket.h"
diff --git a/services/data_decoder/public/cpp/BUILD.gn b/services/data_decoder/public/cpp/BUILD.gn index df5d677..eabb063 100644 --- a/services/data_decoder/public/cpp/BUILD.gn +++ b/services/data_decoder/public/cpp/BUILD.gn
@@ -25,18 +25,17 @@ public = [ "data_decoder.h", "json_sanitizer.h", - "safe_xml_parser.h", ] sources = [ "data_decoder.cc", "json_sanitizer.cc", - "safe_xml_parser.cc", ] configs += [ "//build/config/compiler:wexit_time_destructors" ] public_deps = [ + ":safe_xml_parser", ":service_provider", "//base", "//services/data_decoder/public/mojom", @@ -72,6 +71,15 @@ defines = [ "IS_DATA_DECODER_PUBLIC_IMPL" ] } +source_set("safe_xml_parser") { + public = [ "safe_xml_parser.h" ] + + sources = [ "safe_xml_parser.cc" ] + + public_deps = [ "//base" ] + deps = [ "//services/data_decoder/public/mojom:mojom_xml_parser" ] +} + source_set("test_support") { testonly = true sources = [
diff --git a/services/data_decoder/public/mojom/BUILD.gn b/services/data_decoder/public/mojom/BUILD.gn index 663666b..af95b981 100644 --- a/services/data_decoder/public/mojom/BUILD.gn +++ b/services/data_decoder/public/mojom/BUILD.gn
@@ -12,11 +12,11 @@ "image_decoder.mojom", "json_parser.mojom", "web_bundler.mojom", - "xml_parser.mojom", ] public_deps = [ ":mojom_resource_snapshot_for_web_bundle", + ":mojom_xml_parser", "//components/web_package/mojom", "//mojo/public/mojom/base", "//sandbox/policy/mojom", @@ -31,6 +31,12 @@ } } +mojom("mojom_xml_parser") { + sources = [ "xml_parser.mojom" ] + + public_deps = [ "//mojo/public/mojom/base" ] +} + mojom("mojom_resource_snapshot_for_web_bundle") { generate_java = true sources = [ "resource_snapshot_for_web_bundle.mojom" ]
diff --git a/sql/test/test_helpers.cc b/sql/test/test_helpers.cc index b98144da..525d6f5 100644 --- a/sql/test/test_helpers.cc +++ b/sql/test/test_helpers.cc
@@ -19,6 +19,7 @@ #include "base/files/file_util.h" #include "base/files/scoped_file.h" #include "base/strings/string_piece.h" +#include "base/strings/string_util.h" #include "base/threading/thread_restrictions.h" #include "sql/database.h" #include "sql/statement.h" @@ -297,13 +298,11 @@ return db.Execute(sql.c_str()); } -std::string IntegrityCheck(sql::Database* db) { - sql::Statement statement(db->GetUniqueStatement("PRAGMA integrity_check")); +std::string IntegrityCheck(sql::Database& db) { + std::vector<std::string> messages; + EXPECT_TRUE(db.FullIntegrityCheck(&messages)); - // SQLite should always return a row of data. - EXPECT_TRUE(statement.Step()); - - return statement.ColumnString(0); + return base::JoinString(messages, "\n"); } std::string ExecuteWithResult(sql::Database* db, const char* sql) {
diff --git a/sql/test/test_helpers.h b/sql/test/test_helpers.h index ba98f42e..baa72d02d 100644 --- a/sql/test/test_helpers.h +++ b/sql/test/test_helpers.h
@@ -73,10 +73,8 @@ [[nodiscard]] bool CreateDatabaseFromSQL(const base::FilePath& db_path, const base::FilePath& sql_path); -// Return the results of running "PRAGMA integrity_check" on |db|. -// TODO(shess): sql::Database::IntegrityCheck() is basically the -// same, but not as convenient for testing. Maybe combine. -[[nodiscard]] std::string IntegrityCheck(sql::Database* db); +// Test-friendly wrapper around sql::Database::IntegrityCheck(). +[[nodiscard]] std::string IntegrityCheck(sql::Database& db); // ExecuteWithResult() executes |sql| and returns the first column of the first // row as a string. The empty string is returned for no rows. This makes it
diff --git a/testing/PRESUBMIT.py b/testing/PRESUBMIT.py index 2d378cb..d85ec943 100644 --- a/testing/PRESUBMIT.py +++ b/testing/PRESUBMIT.py
@@ -38,7 +38,8 @@ output_api, files_to_skip=[r'gmock.*', r'gtest.*', r'buildbot.*', r'merge_scripts.*', r'trigger_scripts.*', - r'unexpected_passes_common.*'])) + r'unexpected_passes_common.*', + r'clusterfuzz.*'])) # Pylint2.7 is run on subdirs whose presubmit checks are migrated to Python3 output.extend(input_api.canned_checks.RunPylint( input_api, @@ -46,7 +47,8 @@ files_to_check=[r'buildbot.*\.py$', r'merge_scripts.*\.py$', r'trigger_scripts.*\.py$', - r'unexpected_passes_common.*\.py$'], + r'unexpected_passes_common.*\.py$', + r'clusterfuzz.*\.py$'], version='2.7')) return output
diff --git a/testing/buildbot/chromium.fyi.json b/testing/buildbot/chromium.fyi.json index 0a0b2b8..f2a77f2 100644 --- a/testing/buildbot/chromium.fyi.json +++ b/testing/buildbot/chromium.fyi.json
@@ -91071,6 +91071,202 @@ } ] }, + "mac-fieldtrial-rel": { + "gtest_tests": [ + { + "args": [ + "--disable-field-trial-config" + ], + "merge": { + "args": [], + "script": "//testing/merge_scripts/standard_gtest_merge.py" + }, + "name": "browser_tests_no_field_trial", + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "cpu": "arm64", + "os": "Mac-11" + } + ], + "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com", + "shards": 10 + }, + "test": "browser_tests", + "test_id_prefix": "ninja://chrome/test:browser_tests/" + }, + { + "args": [ + "--disable-field-trial-config" + ], + "merge": { + "args": [], + "script": "//testing/merge_scripts/standard_gtest_merge.py" + }, + "name": "components_browsertests_no_field_trial", + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "cpu": "arm64", + "os": "Mac-11" + } + ], + "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" + }, + "test": "components_browsertests", + "test_id_prefix": "ninja://components:components_browsertests/" + }, + { + "args": [ + "--disable-field-trial-config" + ], + "merge": { + "args": [], + "script": "//testing/merge_scripts/standard_gtest_merge.py" + }, + "name": "content_browsertests_no_field_trial", + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "cpu": "arm64", + "os": "Mac-11" + } + ], + "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" + }, + "test": "content_browsertests", + "test_id_prefix": "ninja://content/test:content_browsertests/" + }, + { + "args": [ + "--disable-field-trial-config" + ], + "merge": { + "args": [], + "script": "//testing/merge_scripts/standard_gtest_merge.py" + }, + "name": "interactive_ui_tests_no_field_trial", + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "cpu": "arm64", + "os": "Mac-11" + } + ], + "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" + }, + "test": "interactive_ui_tests", + "test_id_prefix": "ninja://chrome/test:interactive_ui_tests/" + }, + { + "args": [ + "--disable-field-trial-config" + ], + "merge": { + "args": [], + "script": "//testing/merge_scripts/standard_gtest_merge.py" + }, + "name": "sync_integration_tests_no_field_trial", + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "cpu": "arm64", + "os": "Mac-11" + } + ], + "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" + }, + "test": "sync_integration_tests", + "test_id_prefix": "ninja://chrome/test:sync_integration_tests/" + }, + { + "args": [ + "--disable-field-trial-config" + ], + "merge": { + "args": [], + "script": "//testing/merge_scripts/standard_gtest_merge.py" + }, + "name": "xr_browser_tests_no_field_trial", + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "cpu": "arm64", + "os": "Mac-11" + } + ], + "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com" + }, + "test": "xr_browser_tests", + "test_id_prefix": "ninja://chrome/test:xr_browser_tests/" + } + ], + "isolated_scripts": [ + { + "args": [ + "--xvfb", + "--jobs=1", + "--extra-browser-args='--enable-crashpad --disable-field-trial-config'" + ], + "isolate_name": "telemetry_perf_unittests", + "merge": { + "args": [], + "script": "//testing/merge_scripts/standard_isolated_script_merge.py" + }, + "name": "telemetry_perf_unittests_no_field_trial", + "resultdb": { + "enable": true + }, + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "cpu": "arm64", + "os": "Mac-11" + } + ], + "idempotent": false, + "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com", + "shards": 12 + }, + "test_id_prefix": "ninja://chrome/test:telemetry_perf_unittests/" + }, + { + "args": [ + "--jobs=1", + "--extra-browser-args='--disable-gpu --disable-field-trial-config'" + ], + "isolate_name": "telemetry_unittests", + "merge": { + "args": [], + "script": "//testing/merge_scripts/standard_isolated_script_merge.py" + }, + "name": "telemetry_unittests_no_field_trial", + "resultdb": { + "enable": true + }, + "swarming": { + "can_use_on_swarming_builders": true, + "dimension_sets": [ + { + "cpu": "arm64", + "os": "Mac-11" + } + ], + "idempotent": false, + "service_account": "chromium-tester@chops-service-accounts.iam.gserviceaccount.com", + "shards": 8 + }, + "test_id_prefix": "ninja://chrome/test:telemetry_unittests/" + } + ] + }, "mac-hermetic-upgrade-rel": { "additional_compile_targets": [ "all"
diff --git a/testing/buildbot/waterfalls.pyl b/testing/buildbot/waterfalls.pyl index 475cdf4..9b80f7a 100644 --- a/testing/buildbot/waterfalls.pyl +++ b/testing/buildbot/waterfalls.pyl
@@ -3466,6 +3466,15 @@ 'gtest_tests': 'chromium_mac_gtests', }, }, + 'mac-fieldtrial-rel': { + 'mixins': [ + 'mac_11_arm64', + ], + 'test_suites': { + 'gtest_tests': 'fieldtrial_browser_tests', + 'isolated_scripts': 'fieldtrial_isolated_scripts', + }, + }, 'mac-hermetic-upgrade-rel': { 'additional_compile_targets': [ 'all', @@ -5484,7 +5493,7 @@ 'mixins': [ 'marshmallow' ], 'test_suites': { 'gtest_tests': 'rust_gtests', - # Currently `build_rust_unit_tests` is false on Android (because + # Currently `can_build_rust_unit_tests` is false on Android (because # `rustc_can_link` is false). # TODO(https://crbug.com/1260120): Cover `rust_native_tests` here. },
diff --git a/testing/clusterfuzz/common/fuzzy_types.py b/testing/clusterfuzz/common/fuzzy_types.py index 37cfec1e..27a8617 100644 --- a/testing/clusterfuzz/common/fuzzy_types.py +++ b/testing/clusterfuzz/common/fuzzy_types.py
@@ -107,8 +107,11 @@ items.RandomMutation() return sep.join(items) - -class FuzzySequence(object): +# Pylint doesn't recognize that in this case 'self' is some mutable sequence, +# so the unsupoorted-assignment-operation and unsupported-delete-operation +# warnings have been disabled here. +# pylint: disable=unsupported-assignment-operation,unsupported-delete-operation +class FuzzySequence(object): #pylint: disable=useless-object-inheritance """A helpful mixin for writing fuzzy mutable sequence types. If a method parameter is left at its default value of None, an appropriate @@ -154,6 +157,7 @@ if amount is None: amount = utils.RandomLowInteger(min(1, len(self)), len(self) - location) del self[location:location+amount] +# pylint: enable=unsupported-assignment-operation,unsupported-delete-operation class FuzzyList(list, FuzzySequence):
diff --git a/testing/clusterfuzz/common/utils.py b/testing/clusterfuzz/common/utils.py index e499ad2..f61217f 100644 --- a/testing/clusterfuzz/common/utils.py +++ b/testing/clusterfuzz/common/utils.py
@@ -23,7 +23,7 @@ return int(math.floor(math.pow(base, random.uniform(low, high)))) -def WeightedChoice(choices): +def WeightedChoice(choices): # pylint: disable=inconsistent-return-statements """Chooses an item given a sequence of (choice, weight) tuples""" total = sum(w for c, w in choices) r = random.uniform(0, total)
diff --git a/testing/rust_gtest_interop/gtest_attribute.rs b/testing/rust_gtest_interop/gtest_attribute.rs index 8571691..b3f48d8a 100644 --- a/testing/rust_gtest_interop/gtest_attribute.rs +++ b/testing/rust_gtest_interop/gtest_attribute.rs
@@ -97,10 +97,6 @@ .into(); } - // TODO(crbug.com/1296158): This should be `rust_gtest_interop` but currently the mixed-target - // Rust crate gets an _rs suffix. - let interop_crate_name = format_ident!("rust_gtest_interop_rs"); - let (test_suite_name, test_name) = match args.len() { 2 => { let suite = match get_arg_string(&args, GtestAttributeArgument::TestSuite) { @@ -197,16 +193,16 @@ use std::fmt::Display; use std::result::Result; - #[::#interop_crate_name::small_ctor::ctor] + #[::rust_gtest_interop::small_ctor::ctor] unsafe fn register_test() { - let r = ::#interop_crate_name::__private::TestRegistration { + let r = ::rust_gtest_interop::__private::TestRegistration { func: #run_test_fn, test_suite_name: #test_suite_name_c_bytes, test_name: #test_name_c_bytes, file: #file_c_bytes, line: line!(), }; - ::#interop_crate_name::__private::register_test(r); + ::rust_gtest_interop::__private::register_test(r); } // The function is extern "C" so `register_test()` can pass this fn as a pointer to C++ @@ -222,13 +218,13 @@ #[no_mangle] extern "C" fn #run_test_fn() { let catch_result = std::panic::catch_unwind(|| #test_fn()); - use ::#interop_crate_name::TestResult; + use ::rust_gtest_interop::TestResult; let err_message: Option<String> = match catch_result { Ok(fn_result) => TestResult::into_error_message(fn_result), Err(_) => Some("Test panicked".to_string()), }; if let Some(m) = err_message.as_ref() { - ::#interop_crate_name::__private::add_failure_at(file!(), line!(), &m); + ::rust_gtest_interop::__private::add_failure_at(file!(), line!(), &m); } }
diff --git a/testing/rust_gtest_interop/rust_gtest_interop_unittest.rs b/testing/rust_gtest_interop/rust_gtest_interop_unittest.rs index 11e53394..7fa6d0b 100644 --- a/testing/rust_gtest_interop/rust_gtest_interop_unittest.rs +++ b/testing/rust_gtest_interop/rust_gtest_interop_unittest.rs
@@ -1,4 +1,4 @@ -use rust_gtest_interop_rs::prelude::*; +use rust_gtest_interop::prelude::*; #[gtest(Test, InTopModule)] fn test() {
diff --git a/testing/variations/fieldtrial_testing_config.json b/testing/variations/fieldtrial_testing_config.json index 2cde3fc1..89f731e 100644 --- a/testing/variations/fieldtrial_testing_config.json +++ b/testing/variations/fieldtrial_testing_config.json
@@ -2155,21 +2155,6 @@ ] } ], - "ContentCaptureWebLayer": [ - { - "platforms": [ - "android_weblayer" - ], - "experiments": [ - { - "name": "Enabled", - "enable_features": [ - "ContentCaptureInWebLayer" - ] - } - ] - } - ], "ContentLanguagesInLanguagePicker": [ { "platforms": [
diff --git a/third_party/androidx/build.gradle.template b/third_party/androidx/build.gradle.template index 8cc4848..cfa496e 100644 --- a/third_party/androidx/build.gradle.template +++ b/third_party/androidx/build.gradle.template
@@ -53,6 +53,7 @@ compile 'androidx.savedstate:savedstate:{{androidx_dependency_version}}' compile 'androidx.slice:slice-builders:{{androidx_dependency_version}}' compile 'androidx.slice:slice-core:{{androidx_dependency_version}}' + compile 'androidx.slice:slice-view:{{androidx_dependency_version}}' compile 'androidx.swiperefreshlayout:swiperefreshlayout:{{androidx_dependency_version}}' compile 'androidx.tvprovider:tvprovider:{{androidx_dependency_version}}' compile 'androidx.vectordrawable:vectordrawable:{{androidx_dependency_version}}'
diff --git a/third_party/blink/common/features.cc b/third_party/blink/common/features.cc index 367b8632..5a4389e 100644 --- a/third_party/blink/common/features.cc +++ b/third_party/blink/common/features.cc
@@ -1315,5 +1315,8 @@ const base::Feature kZeroCopyTabCapture{"ZeroCopyTabCapture", base::FEATURE_DISABLED_BY_DEFAULT}; +const base::Feature kUserAgentOverrideExperiment{ + "UserAgentOverrideExperiment", base::FEATURE_DISABLED_BY_DEFAULT}; + } // namespace features } // namespace blink
diff --git a/third_party/blink/common/use_counter/use_counter_feature.cc b/third_party/blink/common/use_counter/use_counter_feature.cc index 3ffd8c60..0bdcb36c 100644 --- a/third_party/blink/common/use_counter/use_counter_feature.cc +++ b/third_party/blink/common/use_counter/use_counter_feature.cc
@@ -4,6 +4,7 @@ #include "third_party/blink/public/common/use_counter/use_counter_feature.h" +#include "third_party/blink/public/common/user_agent/user_agent_metadata.h" #include "third_party/blink/public/mojom/permissions_policy/permissions_policy_feature.mojom-shared.h" #include "third_party/blink/public/mojom/use_counter/css_property_id.mojom-shared.h" #include "third_party/blink/public/mojom/web_feature/web_feature.mojom-shared.h" @@ -39,6 +40,11 @@ return value_ < static_cast<UseCounterFeature::EnumValue>( mojom::PermissionsPolicyFeature::kMaxValue) + 1; + case mojom::UseCounterFeatureType::kUserAgentOverride: + return value_ < static_cast<UseCounterFeature::EnumValue>( + blink::UserAgentOverride::UserAgentOverrideHistogram:: + kMaxValue) + + 1; } }
diff --git a/third_party/blink/common/use_counter/use_counter_feature_mojom_traits.cc b/third_party/blink/common/use_counter/use_counter_feature_mojom_traits.cc index 2ac239b..31b5fa3d 100644 --- a/third_party/blink/common/use_counter/use_counter_feature_mojom_traits.cc +++ b/third_party/blink/common/use_counter/use_counter_feature_mojom_traits.cc
@@ -30,6 +30,8 @@ return feature.value() == static_cast<blink::UseCounterFeature::EnumValue>( blink::mojom::PermissionsPolicyFeature::kNotFound); + case blink::mojom::UseCounterFeatureType::kUserAgentOverride: + return false; } } } // namespace
diff --git a/third_party/blink/common/use_counter/use_counter_feature_tracker.cc b/third_party/blink/common/use_counter/use_counter_feature_tracker.cc index 010fe7ae..5d0e493 100644 --- a/third_party/blink/common/use_counter/use_counter_feature_tracker.cc +++ b/third_party/blink/common/use_counter/use_counter_feature_tracker.cc
@@ -28,6 +28,8 @@ return iframe_permissions_policy_features_.test(feature.value()); case FeatureType::kPermissionsPolicyHeader: return header_permissions_policy_features_.test(feature.value()); + case FeatureType::kUserAgentOverride: + return user_agent_override_features_.test(feature.value()); } } @@ -69,6 +71,12 @@ if (header_permissions_policy_features_.test(i)) ret.push_back({FeatureType::kPermissionsPolicyHeader, i}); } + + for (uint32_t i = 0; i < user_agent_override_features_.size(); i++) { + if (user_agent_override_features_.test(i)) + ret.push_back({FeatureType::kUserAgentOverride, i}); + } + return ret; } @@ -106,6 +114,9 @@ case FeatureType::kPermissionsPolicyHeader: header_permissions_policy_features_[feature.value()] = value; break; + case FeatureType::kUserAgentOverride: + user_agent_override_features_[feature.value()] = value; + break; } }
diff --git a/third_party/blink/public/common/features.h b/third_party/blink/public/common/features.h index 9a9c79c..524f778 100644 --- a/third_party/blink/public/common/features.h +++ b/third_party/blink/public/common/features.h
@@ -673,6 +673,10 @@ // which should trigger a zero-copy path in the tab capture code. BLINK_COMMON_EXPORT extern const base::Feature kZeroCopyTabCapture; +// Experiment for measuring how often an overridden User-Agent string is made by +// appending or prepending to the original User-Agent string. +BLINK_COMMON_EXPORT extern const base::Feature kUserAgentOverrideExperiment; + } // namespace features } // namespace blink
diff --git a/third_party/blink/public/common/use_counter/use_counter_feature_tracker.h b/third_party/blink/public/common/use_counter/use_counter_feature_tracker.h index 51e2600..29627a9 100644 --- a/third_party/blink/public/common/use_counter/use_counter_feature_tracker.h +++ b/third_party/blink/public/common/use_counter/use_counter_feature_tracker.h
@@ -10,6 +10,7 @@ #include <vector> #include "third_party/blink/public/common/common_export.h" #include "third_party/blink/public/common/use_counter/use_counter_feature.h" +#include "third_party/blink/public/common/user_agent/user_agent_metadata.h" #include "third_party/blink/public/mojom/permissions_policy/permissions_policy_feature.mojom-shared.h" #include "third_party/blink/public/mojom/use_counter/css_property_id.mojom-shared.h" #include "third_party/blink/public/mojom/web_feature/web_feature.mojom-shared.h" @@ -49,6 +50,10 @@ blink::mojom::PermissionsPolicyFeature::kMaxValue) + 1> header_permissions_policy_features_; + std::bitset<static_cast<size_t>( + UserAgentOverride::UserAgentOverrideHistogram::kMaxValue) + + 1> + user_agent_override_features_; }; } // namespace blink
diff --git a/third_party/blink/public/common/user_agent/user_agent_metadata.h b/third_party/blink/public/common/user_agent/user_agent_metadata.h index bb65f7f..8b034dd 100644 --- a/third_party/blink/public/common/user_agent/user_agent_metadata.h +++ b/third_party/blink/public/common/user_agent/user_agent_metadata.h
@@ -74,10 +74,15 @@ // Like above, this has legacy IPC traits in // content/public/common/common_param_traits_macros.h struct BLINK_COMMON_EXPORT UserAgentOverride { - // Helper which sets only UA, no client hints. + // Helper which sets only UA with blank client hints. static UserAgentOverride UserAgentOnly(const std::string& ua) { UserAgentOverride result; result.ua_string_override = ua; + + // If ua is empty, it's assumed the system default should be used + if (!ua.empty()) + result.ua_metadata_override = UserAgentMetadata(); + return result; } @@ -89,6 +94,18 @@ // should be used. If this is null, and |ua_string_override| is non-empty, // no UA client hints will be sent. absl::optional<UserAgentMetadata> ua_metadata_override; + + static constexpr char kUserAgentOverrideHistogram[] = + "Blink.UseCounter.UserAgentOverride"; + + // These values are persisted to logs. Entries should not be renumbered and + // numeric values should never be reused. + enum UserAgentOverrideHistogram { + UserAgentOverriden = 0, + UserAgentOverrideSubstring = 1, + UserAgentOverrideSuffix = 2, + kMaxValue = UserAgentOverrideSuffix, + }; }; bool BLINK_COMMON_EXPORT operator==(const UserAgentMetadata& a,
diff --git a/third_party/blink/public/devtools_protocol/browser_protocol.pdl b/third_party/blink/public/devtools_protocol/browser_protocol.pdl index 3cc043f..7b91f4eb 100644 --- a/third_party/blink/public/devtools_protocol/browser_protocol.pdl +++ b/third_party/blink/public/devtools_protocol/browser_protocol.pdl
@@ -792,6 +792,7 @@ ClientMetadataNoResponse ClientMetadataInvalidResponse ClientMetadataMissingPrivacyPolicyUrl + DisabledInSettings ErrorFetchingSignin InvalidSigninResponse AccountsHttpNotFound
diff --git a/third_party/blink/public/mojom/devtools/inspector_issue.mojom b/third_party/blink/public/mojom/devtools/inspector_issue.mojom index 16176e33..19c78fd 100644 --- a/third_party/blink/public/mojom/devtools/inspector_issue.mojom +++ b/third_party/blink/public/mojom/devtools/inspector_issue.mojom
@@ -184,6 +184,7 @@ enum FederatedAuthRequestResult { kSuccess, kApprovalDeclined, + kErrorDisabledInSettings, kErrorTooManyRequests, kErrorFetchingManifestHttpNotFound, kErrorFetchingManifestNoResponse,
diff --git a/third_party/blink/public/mojom/use_counter/use_counter_feature.mojom b/third_party/blink/public/mojom/use_counter/use_counter_feature.mojom index e5378ae..174267f 100644 --- a/third_party/blink/public/mojom/use_counter/use_counter_feature.mojom +++ b/third_party/blink/public/mojom/use_counter/use_counter_feature.mojom
@@ -19,6 +19,8 @@ kPermissionsPolicyIframeAttribute, // Blink.UseCounter.PermissionsPolicy.Header kPermissionsPolicyHeader, + // Blink.UseCounter.UserAgentOverride + kUserAgentOverride, }; // This struct corresponds to `blink::UseCounterFeature`.
diff --git a/third_party/blink/renderer/bindings/generated_in_modules.gni b/third_party/blink/renderer/bindings/generated_in_modules.gni index e21670a..4f57aa5f 100644 --- a/third_party/blink/renderer/bindings/generated_in_modules.gni +++ b/third_party/blink/renderer/bindings/generated_in_modules.gni
@@ -391,6 +391,8 @@ "$root_gen_dir/third_party/blink/renderer/bindings/modules/v8/v8_gpu_buffer_binding_layout.h", "$root_gen_dir/third_party/blink/renderer/bindings/modules/v8/v8_gpu_buffer_descriptor.cc", "$root_gen_dir/third_party/blink/renderer/bindings/modules/v8/v8_gpu_buffer_descriptor.h", + "$root_gen_dir/third_party/blink/renderer/bindings/modules/v8/v8_gpu_canvas_compositing_alpha_mode.cc", + "$root_gen_dir/third_party/blink/renderer/bindings/modules/v8/v8_gpu_canvas_compositing_alpha_mode.h", "$root_gen_dir/third_party/blink/renderer/bindings/modules/v8/v8_gpu_canvas_configuration.cc", "$root_gen_dir/third_party/blink/renderer/bindings/modules/v8/v8_gpu_canvas_configuration.h", "$root_gen_dir/third_party/blink/renderer/bindings/modules/v8/v8_gpu_color_dict.cc",
diff --git a/third_party/blink/renderer/core/document_transition/document_transition.cc b/third_party/blink/renderer/core/document_transition/document_transition.cc index d493c7c..5fc332b6 100644 --- a/third_party/blink/renderer/core/document_transition/document_transition.cc +++ b/third_party/blink/renderer/core/document_transition/document_transition.cc
@@ -9,7 +9,11 @@ #include "base/trace_event/trace_event.h" #include "cc/document_transition/document_transition_request.h" #include "cc/trees/paint_holding_reason.h" +#include "third_party/blink/renderer/bindings/core/v8/script_function.h" +#include "third_party/blink/renderer/bindings/core/v8/script_promise.h" #include "third_party/blink/renderer/bindings/core/v8/script_promise_resolver.h" +#include "third_party/blink/renderer/bindings/core/v8/script_value.h" +#include "third_party/blink/renderer/bindings/core/v8/v8_binding_for_core.h" #include "third_party/blink/renderer/bindings/core/v8/v8_document_transition_set_element_options.h" #include "third_party/blink/renderer/core/css/style_change_reason.h" #include "third_party/blink/renderer/core/dom/document.h" @@ -22,7 +26,9 @@ #include "third_party/blink/renderer/core/page/chrome_client.h" #include "third_party/blink/renderer/core/page/page.h" #include "third_party/blink/renderer/core/paint/paint_layer.h" +#include "third_party/blink/renderer/platform/bindings/script_state.h" #include "third_party/blink/renderer/platform/graphics/compositor_element_id.h" +#include "third_party/blink/renderer/platform/heap/garbage_collected.h" #include "third_party/blink/renderer/platform/wtf/cross_thread_functional.h" #include "third_party/blink/renderer/platform/wtf/hash_map.h" #include "third_party/blink/renderer/platform/wtf/std_lib_extras.h" @@ -32,10 +38,12 @@ namespace blink { namespace { -const char kAbortedFromCaptureAndHold[] = - "Aborted due to captureAndHold() call"; const char kAbortedFromStart[] = "Aborted due to start() call"; const char kAbortedFromScript[] = "Aborted due to abort() call"; +const char kAbortedFromCallback[] = + "Aborted due to failure in DocumentTransitionCallback"; +const char kAbortedFromInvalidConfigAtStart[] = + "Start failed: invalid element configuration"; uint32_t NextDocumentTag() { static uint32_t next_document_tag = 1u; @@ -44,6 +52,30 @@ } // namespace +DocumentTransition::PostCaptureResolved::PostCaptureResolved( + DocumentTransition* transition, + bool success) + : transition_(transition), success_(success) {} + +DocumentTransition::PostCaptureResolved::~PostCaptureResolved() = default; + +ScriptValue DocumentTransition::PostCaptureResolved::Call(ScriptState*, + ScriptValue) { + if (transition_) + transition_->NotifyPostCaptureCallbackResolved(success_); + return ScriptValue(); +} + +void DocumentTransition::PostCaptureResolved::Trace(Visitor* visitor) const { + ScriptFunction::Callable::Trace(visitor); + visitor->Trace(transition_); +} + +void DocumentTransition::PostCaptureResolved::Cancel() { + DCHECK(transition_); + transition_ = nullptr; +} + DocumentTransition::DocumentTransition(Document* document) : ExecutionContextLifecycleObserver(document->GetExecutionContext()), document_(document), @@ -51,7 +83,10 @@ void DocumentTransition::Trace(Visitor* visitor) const { visitor->Trace(document_); - visitor->Trace(capture_promise_resolver_); + visitor->Trace(capture_resolved_callback_); + visitor->Trace(start_script_state_); + visitor->Trace(post_capture_success_callable_); + visitor->Trace(post_capture_reject_callable_); visitor->Trace(start_promise_resolver_); visitor->Trace(style_tracker_); @@ -61,37 +96,27 @@ } void DocumentTransition::ContextDestroyed() { - if (capture_promise_resolver_) { - capture_promise_resolver_->Detach(); - capture_promise_resolver_ = nullptr; - } - if (start_promise_resolver_) { - start_promise_resolver_->Detach(); - start_promise_resolver_ = nullptr; - } - ResetState(); + ResetTransitionState(); + ResetScriptState(nullptr); } bool DocumentTransition::HasPendingActivity() const { - if (capture_promise_resolver_ || start_promise_resolver_) - return true; - return false; + return style_tracker_; } -void DocumentTransition::AssertNoTransition() { - DCHECK_EQ(state_, State::kIdle); - DCHECK(!style_tracker_); - DCHECK(!capture_promise_resolver_); +bool DocumentTransition::StartNewTransition() { + if (state_ != State::kIdle || style_tracker_) + return false; + + DCHECK(!capture_resolved_callback_); + DCHECK(!post_capture_success_callable_); + DCHECK(!post_capture_reject_callable_); DCHECK(!start_promise_resolver_); -} - -void DocumentTransition::StartNewTransition() { style_tracker_ = MakeGarbageCollected<DocumentTransitionStyleTracker>(*document_); + return true; } -void DocumentTransition::FinalizeNewTransition() {} - void DocumentTransition::setElement( ScriptState* script_state, Element* element, @@ -110,9 +135,14 @@ style_tracker_->AddSharedElement(element, tag); } -ScriptPromise DocumentTransition::captureAndHold( - ScriptState* script_state, - ExceptionState& exception_state) { +ScriptPromise DocumentTransition::start(ScriptState* script_state, + ExceptionState& exception_state) { + return start(script_state, nullptr, exception_state); +} + +ScriptPromise DocumentTransition::start(ScriptState* script_state, + V8DocumentTransitionCallback* callback, + ExceptionState& exception_state) { switch (state_) { case State::kIdle: if (!document_ || !document_->View()) { @@ -130,7 +160,7 @@ case State::kCapturing: case State::kCaptured: case State::kStarted: - CancelPendingTransition(kAbortedFromCaptureAndHold); + CancelPendingTransition(kAbortedFromStart); exception_state.ThrowDOMException( DOMExceptionCode::kInvalidStateError, "Transition aborted, invalid captureAndHold call"); @@ -146,11 +176,22 @@ exception_state.ThrowDOMException( DOMExceptionCode::kInvalidStateError, "Capture failed: invalid element configuration."); - ResetState(); + ResetTransitionState(); return ScriptPromise(); } - capture_promise_resolver_ = + // PREPARE PHASE + // The capture request below will initiate an async operation to cache + // textures for the current DOM. The |capture_resolved_callback_| is invoked + // when that async operation finishes. + // + // START PHASE + // When this async callback finishes executing, animations are started using + // images from old and new DOM elements. The |start_promise_resolver_| + // returned here resolves when these animations finish. + capture_resolved_callback_ = callback; + start_script_state_ = script_state; + start_promise_resolver_ = MakeGarbageCollected<ScriptPromiseResolver>(script_state); state_ = State::kCapturing; @@ -162,50 +203,6 @@ NotifyHasChangesToCommit(); - return capture_promise_resolver_->Promise(); -} - -ScriptPromise DocumentTransition::start(ScriptState* script_state, - ExceptionState& exception_state) { - switch (state_) { - case State::kIdle: - case State::kCapturing: - CancelPendingTransition(kAbortedFromStart); - exception_state.ThrowDOMException( - DOMExceptionCode::kInvalidStateError, - "Transition must be prepared before it can be started."); - return ScriptPromise(); - case State::kCaptured: - // We expect this case in a proper transition. - DCHECK(style_tracker_); - break; - case State::kStarted: - CancelPendingTransition(kAbortedFromStart); - exception_state.ThrowDOMException( - DOMExceptionCode::kInvalidStateError, - "Transition aborted, invalid start call"); - return ScriptPromise(); - } - - StopDeferringCommits(); - - bool start_succeeded = style_tracker_->Start(); - if (!start_succeeded) { - exception_state.ThrowDOMException( - DOMExceptionCode::kInvalidStateError, - "Start failed: invalid element configuration."); - ResetState(); - return ScriptPromise(); - } - - last_start_sequence_id_ = next_sequence_id_++; - state_ = State::kStarted; - start_promise_resolver_ = - MakeGarbageCollected<ScriptPromiseResolver>(script_state); - pending_request_ = - DocumentTransitionRequest::CreateAnimateRenderer(document_tag_); - - NotifyHasChangesToCommit(); return start_promise_resolver_->Promise(); } @@ -233,20 +230,45 @@ if (sequence_id != last_prepare_sequence_id_) return; - // We could have detached the resolver if the execution context was destroyed. - if (!capture_promise_resolver_) + // We could have abandoned the transition before capture finishes. + if (state_ == State::kIdle) { return; + } DCHECK(state_ == State::kCapturing); - DCHECK(capture_promise_resolver_); if (style_tracker_) style_tracker_->CaptureResolved(); // Defer commits before resolving the promise to ensure any updates made in // the callback are deferred. StartDeferringCommits(); - capture_promise_resolver_->Resolve(); - capture_promise_resolver_ = nullptr; + if (!capture_resolved_callback_) { + state_ = State::kCaptured; + start_script_state_ = nullptr; + NotifyPostCaptureCallbackResolved(/*success=*/true); + return; + } + + v8::Maybe<ScriptPromise> result = capture_resolved_callback_->Invoke(nullptr); + if (result.IsNothing()) { + CancelPendingTransition(kAbortedFromCallback); + return; + } + + post_capture_success_callable_ = + MakeGarbageCollected<PostCaptureResolved>(this, true); + post_capture_reject_callable_ = + MakeGarbageCollected<PostCaptureResolved>(this, false); + + ScriptState::Scope scope(start_script_state_); + result.ToChecked().Then( + MakeGarbageCollected<ScriptFunction>(start_script_state_, + post_capture_success_callable_), + MakeGarbageCollected<ScriptFunction>(start_script_state_, + post_capture_reject_callable_)); + + capture_resolved_callback_ = nullptr; + start_script_state_ = nullptr; state_ = State::kCaptured; } @@ -272,7 +294,35 @@ style_tracker_->StartFinished(); pending_request_ = DocumentTransitionRequest::CreateRelease(document_tag_); NotifyHasChangesToCommit(); - ResetState(/*abort_style_tracker=*/false); + ResetTransitionState(/*abort_style_tracker=*/false); +} + +void DocumentTransition::NotifyPostCaptureCallbackResolved(bool success) { + DCHECK_EQ(state_, State::kCaptured); + DCHECK(style_tracker_); + DCHECK(start_promise_resolver_); + DCHECK(!capture_resolved_callback_); + + StopDeferringCommits(); + + if (!success) { + CancelPendingTransition(kAbortedFromCallback); + return; + } + + bool start_succeeded = style_tracker_->Start(); + if (!start_succeeded) { + CancelPendingTransition(kAbortedFromInvalidConfigAtStart); + return; + } + + last_start_sequence_id_ = next_sequence_id_++; + state_ = State::kStarted; + post_capture_success_callable_ = nullptr; + post_capture_reject_callable_ = nullptr; + pending_request_ = + DocumentTransitionRequest::CreateAnimateRenderer(document_tag_); + NotifyHasChangesToCommit(); } std::unique_ptr<DocumentTransitionRequest> @@ -282,11 +332,6 @@ bool DocumentTransition::IsTransitionParticipant( const LayoutObject& object) const { - // If our state is idle and we're outside of script mutation scope, it implies - // that we have no style tracker. - DCHECK(state_ != State::kIdle || script_mutations_allowed_ || - !style_tracker_); - // The layout view is always a participant if there is a transition. if (auto* layout_view = DynamicTo<LayoutView>(object)) return state_ != State::kIdle; @@ -438,24 +483,17 @@ } void DocumentTransition::CancelPendingTransition(const char* abort_message) { - ResetState(); + bool need_release_directive = state_ == State::kStarted; + ResetTransitionState(); + ResetScriptState(abort_message); - if (capture_promise_resolver_) { - capture_promise_resolver_->Reject(MakeGarbageCollected<DOMException>( - DOMExceptionCode::kAbortError, abort_message)); - capture_promise_resolver_ = nullptr; - } - if (start_promise_resolver_) { - start_promise_resolver_->Reject(MakeGarbageCollected<DOMException>( - DOMExceptionCode::kAbortError, abort_message)); - start_promise_resolver_ = nullptr; - + if (need_release_directive) { pending_request_ = DocumentTransitionRequest::CreateRelease(document_tag_); NotifyHasChangesToCommit(); } } -void DocumentTransition::ResetState(bool abort_style_tracker) { +void DocumentTransition::ResetTransitionState(bool abort_style_tracker) { if (abort_style_tracker) { if (style_tracker_) style_tracker_->Abort(); @@ -466,4 +504,29 @@ state_ = State::kIdle; } +void DocumentTransition::ResetScriptState(const char* abort_message) { + capture_resolved_callback_ = nullptr; + start_script_state_ = nullptr; + + if (post_capture_success_callable_) { + DCHECK(post_capture_reject_callable_); + + post_capture_success_callable_->Cancel(); + post_capture_success_callable_ = nullptr; + + post_capture_reject_callable_->Cancel(); + post_capture_reject_callable_ = nullptr; + } + + if (start_promise_resolver_) { + if (abort_message) { + start_promise_resolver_->Reject(MakeGarbageCollected<DOMException>( + DOMExceptionCode::kAbortError, abort_message)); + } else { + start_promise_resolver_->Detach(); + } + start_promise_resolver_ = nullptr; + } +} + } // namespace blink
diff --git a/third_party/blink/renderer/core/document_transition/document_transition.h b/third_party/blink/renderer/core/document_transition/document_transition.h index edcca73e..2b3621e6 100644 --- a/third_party/blink/renderer/core/document_transition/document_transition.h +++ b/third_party/blink/renderer/core/document_transition/document_transition.h
@@ -10,6 +10,9 @@ #include "base/memory/scoped_refptr.h" #include "base/task/single_thread_task_runner.h" #include "third_party/blink/renderer/bindings/core/v8/active_script_wrappable.h" +#include "third_party/blink/renderer/bindings/core/v8/script_function.h" +#include "third_party/blink/renderer/bindings/core/v8/script_value.h" +#include "third_party/blink/renderer/bindings/core/v8/v8_document_transition_callback.h" #include "third_party/blink/renderer/core/core_export.h" #include "third_party/blink/renderer/core/document_transition/document_transition_request.h" #include "third_party/blink/renderer/core/document_transition/document_transition_style_tracker.h" @@ -18,6 +21,7 @@ #include "third_party/blink/renderer/platform/bindings/script_wrappable.h" #include "third_party/blink/renderer/platform/graphics/document_transition_shared_element_id.h" #include "third_party/blink/renderer/platform/graphics/paint/effect_paint_property_node.h" +#include "third_party/blink/renderer/platform/heap/forward.h" #include "third_party/blink/renderer/platform/wtf/wtf_size_t.h" namespace blink { @@ -51,35 +55,10 @@ // ActiveScriptWrappable functionality. bool HasPendingActivity() const override; - bool CanCreateNewTransition() const { - return state_ == State::kIdle && !script_mutations_allowed_; - } - - class ScriptMutationsAllowedScope { - STACK_ALLOCATED(); - - public: - ~ScriptMutationsAllowedScope() { - transition_->script_mutations_allowed_ = false; - transition_->FinalizeNewTransition(); - } - - private: - friend class DocumentTransition; - - explicit ScriptMutationsAllowedScope(DocumentTransition* transition) - : transition_(transition) { - transition_->script_mutations_allowed_ = true; - transition_->AssertNoTransition(); - transition_->StartNewTransition(); - } - - DocumentTransition* transition_; - }; - - ScriptMutationsAllowedScope CreateScriptMutationsAllowedScope() { - return ScriptMutationsAllowedScope{this}; - } + // Initiates a new transition via createDocumentTransition() API. Returns + // false if a transition was already active which must finish before a new one + // can be started. + bool StartNewTransition(); // JavaScript API implementation. void setElement(ScriptState*, @@ -87,8 +66,10 @@ const AtomicString&, const DocumentTransitionSetElementOptions*, ExceptionState&); - ScriptPromise captureAndHold(ScriptState*, ExceptionState&); ScriptPromise start(ScriptState*, ExceptionState&); + ScriptPromise start(ScriptState*, + V8DocumentTransitionCallback* callback, + ExceptionState&); void ignoreCSSTaggedElements(ScriptState*, ExceptionState&); void abandon(ScriptState*, ExceptionState&); @@ -136,22 +117,37 @@ // LifecycleNotificationObserver overrides. void WillStartLifecycleUpdate(const LocalFrameView&) override; - bool HasActiveTransition() const { return state_ != State::kIdle; } - private: friend class DocumentTransitionTest; enum class State { kIdle, kCapturing, kCaptured, kStarted }; - void AssertNoTransition(); - void StartNewTransition(); - void FinalizeNewTransition(); + // Invoked when the async callback dispatched after capture finishes + // executing. + class PostCaptureResolved : public ScriptFunction::Callable { + public: + explicit PostCaptureResolved(DocumentTransition* transition, bool success); + ~PostCaptureResolved() override; + + ScriptValue Call(ScriptState*, ScriptValue) override; + void Trace(Visitor* visitor) const override; + + void Cancel(); + + private: + Member<DocumentTransition> transition_; + const bool success_; + }; void NotifyHasChangesToCommit(); void NotifyCaptureFinished(uint32_t sequence_id); void NotifyStartFinished(uint32_t sequence_id); + // Dispatched when the DocumentTransitionCallback has finished executing and + // start phase of the animation can be initiated. + void NotifyPostCaptureCallbackResolved(bool success); + // Used to defer visual updates between transition prepare finishing and // transition start to allow the page to set up the final scene // asynchronously. @@ -163,13 +159,27 @@ // Resets internal state, called in both abort situations and transition // finished situations. - void ResetState(bool abort_style_tracker = true); + void ResetTransitionState(bool abort_style_tracker = true); + void ResetScriptState(const char* abort_message); Member<Document> document_; State state_ = State::kIdle; - Member<ScriptPromiseResolver> capture_promise_resolver_; + // Script callback passed to the start() API. Dispatched when capturing + // snapshots from the old DOM finishes. + Member<V8DocumentTransitionCallback> capture_resolved_callback_; + + // Script state cached from the start() API. + Member<ScriptState> start_script_state_; + + // The following callables are used to track when the async + // |capture_resolved_callback_| finishes executing. + Member<PostCaptureResolved> post_capture_success_callable_; + Member<PostCaptureResolved> post_capture_reject_callable_; + + // The following promise is provided to script and resolved when all + // animations from the start phase finish. Member<ScriptPromiseResolver> start_promise_resolver_; // Created conditionally if renderer based SharedElementTransitions is @@ -192,9 +202,6 @@ bool deferring_commits_ = false; - // This is set to true when we allow script calls to modify state. - bool script_mutations_allowed_ = false; - // Set only for tests. bool disable_end_transition_ = false; };
diff --git a/third_party/blink/renderer/core/document_transition/document_transition.idl b/third_party/blink/renderer/core/document_transition/document_transition.idl index 7c304109..90d2a58 100644 --- a/third_party/blink/renderer/core/document_transition/document_transition.idl +++ b/third_party/blink/renderer/core/document_transition/document_transition.idl
@@ -13,13 +13,12 @@ // transition, whether as a part of captureAndHold or start phases. [CallWith=ScriptState, RaisesException] void setElement(Element element, DOMString? tag, optional DocumentTransitionSetElementOptions options = {}); - // Request to capture the currently set elements, including the root, and - // hold visual contents until start is called - [CallWith=ScriptState, RaisesException] Promise<void> captureAndHold(); - - // Starts the transition with the captured elements and elements set for - // start. - [CallWith=ScriptState, RaisesException] Promise<void> start(); + // Starts the transition with the captured elements. + // |callback| is used to asynchronously initialize the new DOM for the + // transition. Animations are started when this callback returns. + // The returned promise is resolved when all animations for this transition + // are finished. + [CallWith=ScriptState, RaisesException] Promise<void> start(optional DocumentTransitionCallback callback); // Ignores CSS tagged elements [CallWith=ScriptState, RaisesException] void ignoreCSSTaggedElements();
diff --git a/third_party/blink/renderer/core/document_transition/document_transition_callback.idl b/third_party/blink/renderer/core/document_transition/document_transition_callback.idl index bf1e354..0ea0b90 100644 --- a/third_party/blink/renderer/core/document_transition/document_transition_callback.idl +++ b/third_party/blink/renderer/core/document_transition/document_transition_callback.idl
@@ -4,5 +4,5 @@ [ RuntimeEnabled=DocumentTransition -] callback DocumentTransitionCallback = void(DocumentTransition documentTransition); +] callback DocumentTransitionCallback = Promise<void>();
diff --git a/third_party/blink/renderer/core/document_transition/document_transition_supplement.cc b/third_party/blink/renderer/core/document_transition/document_transition_supplement.cc index 456b39f..589a151d 100644 --- a/third_party/blink/renderer/core/document_transition/document_transition_supplement.cc +++ b/third_party/blink/renderer/core/document_transition/document_transition_supplement.cc
@@ -8,6 +8,7 @@ #include "third_party/blink/renderer/bindings/core/v8/v8_document_transition_callback.h" #include "third_party/blink/renderer/core/document_transition/document_transition.h" #include "third_party/blink/renderer/core/dom/document.h" +#include "third_party/blink/renderer/platform/bindings/exception_state.h" namespace blink { @@ -42,15 +43,18 @@ } // static -void DocumentTransitionSupplement::createDocumentTransition( +DocumentTransition* DocumentTransitionSupplement::createDocumentTransition( Document& document, - V8DocumentTransitionCallback* callback) { + ExceptionState& exception_state) { auto* transition = EnsureDocumentTransition(document); - // TODO(vmpstr): We need to figure what to do if we already have a transition. - if (transition->HasActiveTransition()) - return; - auto script_scope = transition->CreateScriptMutationsAllowedScope(); - callback->InvokeAndReportException(&document, transition); + + if (!transition->StartNewTransition()) { + exception_state.ThrowDOMException(DOMExceptionCode::kInvalidStateError, + "Transition already in progress"); + return nullptr; + } + + return transition; } DocumentTransition* DocumentTransitionSupplement::GetTransition() {
diff --git a/third_party/blink/renderer/core/document_transition/document_transition_supplement.h b/third_party/blink/renderer/core/document_transition/document_transition_supplement.h index a18d0a3..ecd5ed5 100644 --- a/third_party/blink/renderer/core/document_transition/document_transition_supplement.h +++ b/third_party/blink/renderer/core/document_transition/document_transition_supplement.h
@@ -26,8 +26,8 @@ static DocumentTransition* EnsureDocumentTransition(Document&); - static void createDocumentTransition(Document&, - V8DocumentTransitionCallback* callback); + static DocumentTransition* createDocumentTransition(Document&, + ExceptionState&); DocumentTransition* GetTransition();
diff --git a/third_party/blink/renderer/core/document_transition/document_transition_supplement.idl b/third_party/blink/renderer/core/document_transition/document_transition_supplement.idl index 7d9578dd..69299d1 100644 --- a/third_party/blink/renderer/core/document_transition/document_transition_supplement.idl +++ b/third_party/blink/renderer/core/document_transition/document_transition_supplement.idl
@@ -6,5 +6,5 @@ ImplementedAs=DocumentTransitionSupplement, RuntimeEnabled=DocumentTransition ] partial interface Document { - [MeasureAs=DocumentTransition] void createDocumentTransition(DocumentTransitionCallback callback); + [MeasureAs=DocumentTransition, RaisesException] DocumentTransition createDocumentTransition(); };
diff --git a/third_party/blink/renderer/core/document_transition/document_transition_test.cc b/third_party/blink/renderer/core/document_transition/document_transition_test.cc index b7dc0e6..ca22a56 100644 --- a/third_party/blink/renderer/core/document_transition/document_transition_test.cc +++ b/third_party/blink/renderer/core/document_transition/document_transition_test.cc
@@ -3,6 +3,7 @@ // found in the LICENSE file. #include "third_party/blink/renderer/core/document_transition/document_transition.h" +#include <memory> #include "base/check_op.h" #include "base/memory/scoped_refptr.h" @@ -12,21 +13,32 @@ #include "third_party/blink/public/web/web_settings.h" #include "third_party/blink/renderer/bindings/core/v8/script_promise_tester.h" #include "third_party/blink/renderer/bindings/core/v8/v8_binding_for_testing.h" +#include "third_party/blink/renderer/bindings/core/v8/v8_document_transition_callback.h" #include "third_party/blink/renderer/bindings/core/v8/v8_document_transition_set_element_options.h" #include "third_party/blink/renderer/core/css/style_change_reason.h" #include "third_party/blink/renderer/core/css/style_engine.h" #include "third_party/blink/renderer/core/document_transition/document_transition_supplement.h" #include "third_party/blink/renderer/core/document_transition/document_transition_utils.h" #include "third_party/blink/renderer/core/dom/abort_signal.h" +#include "third_party/blink/renderer/core/dom/element.h" #include "third_party/blink/renderer/core/dom/node_computed_style.h" #include "third_party/blink/renderer/core/dom/pseudo_element.h" #include "third_party/blink/renderer/core/frame/frame_test_helpers.h" #include "third_party/blink/renderer/core/html/html_element.h" #include "third_party/blink/renderer/core/paint/paint_layer.h" +#include "third_party/blink/renderer/core/testing/mock_function_scope.h" +#include "third_party/blink/renderer/platform/bindings/exception_state.h" +#include "third_party/blink/renderer/platform/bindings/script_state.h" #include "third_party/blink/renderer/platform/graphics/compositing/paint_artifact_compositor.h" #include "third_party/blink/renderer/platform/testing/find_cc_layer.h" #include "third_party/blink/renderer/platform/testing/paint_test_configurations.h" +#include "third_party/blink/renderer/platform/testing/unit_test_helpers.h" +#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h" #include "third_party/blink/renderer/platform/wtf/text/atomic_string.h" +#include "v8-external.h" +#include "v8-function-callback.h" +#include "v8-function.h" +#include "v8-value.h" namespace blink { @@ -187,7 +199,7 @@ TEST_P(DocumentTransitionTest, TransitionPreparePromiseResolves) { auto* transition = DocumentTransitionSupplement::EnsureDocumentTransition(GetDocument()); - auto scope = transition->CreateScriptMutationsAllowedScope(); + ASSERT_TRUE(transition->StartNewTransition()); ASSERT_TRUE(transition); EXPECT_EQ(GetState(transition), State::kIdle); @@ -195,32 +207,49 @@ ScriptState* script_state = v8_scope.GetScriptState(); ExceptionState& exception_state = v8_scope.GetExceptionState(); + MockFunctionScope funcs(script_state); + auto* document_transition_callback = + V8DocumentTransitionCallback::Create(funcs.ExpectCall()); + ScriptPromiseTester promise_tester( - script_state, transition->captureAndHold(script_state, exception_state)); + script_state, + transition->start(script_state, document_transition_callback, + exception_state)); EXPECT_EQ(GetState(transition), State::kCapturing); UpdateAllLifecyclePhasesAndFinishDirectives(); - promise_tester.WaitUntilSettled(); - - EXPECT_TRUE(promise_tester.IsFulfilled()); EXPECT_EQ(GetState(transition), State::kCaptured); + + test::RunPendingTasks(); + EXPECT_EQ(GetState(transition), State::kStarted); + UpdateAllLifecyclePhasesAndFinishDirectives(); + FinishTransition(); + promise_tester.WaitUntilSettled(); + EXPECT_TRUE(promise_tester.IsFulfilled()); } -TEST_P(DocumentTransitionTest, AdditionalPrepareAbortsTransition) { +TEST_P(DocumentTransitionTest, AdditionalStartAbortsTransition) { auto* transition = DocumentTransitionSupplement::EnsureDocumentTransition(GetDocument()); - auto scope = transition->CreateScriptMutationsAllowedScope(); + ASSERT_TRUE(transition->StartNewTransition()); V8TestingScope v8_scope; ScriptState* script_state = v8_scope.GetScriptState(); ExceptionState& exception_state = v8_scope.GetExceptionState(); + MockFunctionScope funcs(script_state); + auto* document_transition_callback = + V8DocumentTransitionCallback::Create(funcs.ExpectNoCall()); + ScriptPromiseTester first_promise_tester( - script_state, transition->captureAndHold(script_state, exception_state)); + script_state, + transition->start(script_state, document_transition_callback, + exception_state)); EXPECT_EQ(GetState(transition), State::kCapturing); EXPECT_FALSE(exception_state.HadException()); - transition->captureAndHold(script_state, exception_state); + transition->start(script_state, document_transition_callback, + exception_state); EXPECT_TRUE(exception_state.HadException()); EXPECT_EQ(GetState(transition), State::kIdle); @@ -248,19 +277,24 @@ auto* transition = DocumentTransitionSupplement::EnsureDocumentTransition(GetDocument()); - auto scope = transition->CreateScriptMutationsAllowedScope(); + ASSERT_TRUE(transition->StartNewTransition()); V8TestingScope v8_scope; ScriptState* script_state = v8_scope.GetScriptState(); ExceptionState& exception_state = v8_scope.GetExceptionState(); + MockFunctionScope funcs(script_state); + auto* document_transition_callback = + V8DocumentTransitionCallback::Create(funcs.ExpectCall()); + EXPECT_FALSE(ShouldCompositeForDocumentTransition(e1)); EXPECT_FALSE(ShouldCompositeForDocumentTransition(e2)); EXPECT_FALSE(ShouldCompositeForDocumentTransition(e3)); transition->setElement(script_state, e1, "e1", nullptr, exception_state); transition->setElement(script_state, e3, "e3", nullptr, exception_state); - transition->captureAndHold(script_state, exception_state); + transition->start(script_state, document_transition_callback, + exception_state); // Update the lifecycle while keeping the transition active. UpdateAllLifecyclePhasesForTest(); @@ -302,12 +336,16 @@ auto* transition = DocumentTransitionSupplement::EnsureDocumentTransition(GetDocument()); - auto scope = transition->CreateScriptMutationsAllowedScope(); + ASSERT_TRUE(transition->StartNewTransition()); V8TestingScope v8_scope; ScriptState* script_state = v8_scope.GetScriptState(); ExceptionState& exception_state = v8_scope.GetExceptionState(); + MockFunctionScope funcs(script_state); + auto* document_transition_callback = + V8DocumentTransitionCallback::Create(funcs.ExpectNoCall()); + EXPECT_FALSE(ShouldCompositeForDocumentTransition(e1)); EXPECT_FALSE(ShouldCompositeForDocumentTransition(e2)); EXPECT_FALSE(ShouldCompositeForDocumentTransition(e3)); @@ -315,7 +353,8 @@ transition->setElement(script_state, e1, "e1", nullptr, exception_state); transition->setElement(script_state, e2, "e2", nullptr, exception_state); transition->setElement(script_state, e3, "e3", nullptr, exception_state); - transition->captureAndHold(script_state, exception_state); + transition->start(script_state, document_transition_callback, + exception_state); EXPECT_TRUE(ShouldCompositeForDocumentTransition(e1)); EXPECT_TRUE(ShouldCompositeForDocumentTransition(e2)); @@ -347,7 +386,7 @@ auto* transition = DocumentTransitionSupplement::EnsureDocumentTransition(GetDocument()); - auto scope = transition->CreateScriptMutationsAllowedScope(); + ASSERT_TRUE(transition->StartNewTransition()); V8TestingScope v8_scope; ScriptState* script_state = v8_scope.GetScriptState(); @@ -356,22 +395,62 @@ // Set two of the elements to be shared. transition->setElement(script_state, e1, "e1", nullptr, exception_state); transition->setElement(script_state, e3, "e3", nullptr, exception_state); - transition->captureAndHold(script_state, exception_state); + + struct Data { + STACK_ALLOCATED(); + + public: + Data(DocumentTransition* transition, + ScriptState* script_state, + ExceptionState& exception_state, + Element* e3, + Element* e2) + : transition(transition), + script_state(script_state), + exception_state(exception_state), + e3(e3), + e2(e2) {} + + DocumentTransition* transition; + ScriptState* script_state; + ExceptionState& exception_state; + Element* e3; + Element* e2; + }; + Data data(transition, script_state, exception_state, e3, e2); + + // This callback sets the elements for the start phase of the transition. + auto start_setup_lambda = + [](const v8::FunctionCallbackInfo<v8::Value>& info) { + auto* data = + static_cast<Data*>(info.Data().As<v8::External>()->Value()); + + // Set two different elements as shared. + // Unset e3. + data->transition->setElement(data->script_state, data->e3, + AtomicString(), nullptr, + data->exception_state); + // Set e2 to be the same tag as "e3". + // TODO(vmpstr): We should be able to support new tags for entry + // transitions. + data->transition->setElement(data->script_state, data->e2, "e3", + nullptr, data->exception_state); + }; + auto start_setup_callback = + v8::Function::New(v8_scope.GetContext(), start_setup_lambda, + v8::External::New(v8_scope.GetIsolate(), &data)) + .ToLocalChecked(); + + transition->start(script_state, + V8DocumentTransitionCallback::Create(start_setup_callback), + exception_state); EXPECT_TRUE(ShouldCompositeForDocumentTransition(e1)); EXPECT_FALSE(ShouldCompositeForDocumentTransition(e2)); EXPECT_TRUE(ShouldCompositeForDocumentTransition(e3)); UpdateAllLifecyclePhasesAndFinishDirectives(); - - // Set two different elements as shared. - // Unset e3. - transition->setElement(script_state, e3, AtomicString(), nullptr, - exception_state); - // Set e2 to be the same tag as "e3". - // TODO(vmpstr): We should be able to support new tags for entry transitions. - transition->setElement(script_state, e2, "e3", nullptr, exception_state); - transition->start(script_state, exception_state); + test::RunPendingTasks(); EXPECT_TRUE(ShouldCompositeForDocumentTransition(e1)); EXPECT_TRUE(ShouldCompositeForDocumentTransition(e2)); @@ -384,87 +463,95 @@ EXPECT_FALSE(ShouldCompositeForDocumentTransition(e3)); } -TEST_P(DocumentTransitionTest, AdditionalPrepareAfterPreparedAbortsTransition) { +TEST_P(DocumentTransitionTest, AdditionalStartAfterStartAbortsTransition) { auto* transition = DocumentTransitionSupplement::EnsureDocumentTransition(GetDocument()); - auto scope = transition->CreateScriptMutationsAllowedScope(); + ASSERT_TRUE(transition->StartNewTransition()); V8TestingScope v8_scope; ScriptState* script_state = v8_scope.GetScriptState(); ExceptionState& exception_state = v8_scope.GetExceptionState(); + MockFunctionScope funcs(script_state); + auto* document_transition_callback = + V8DocumentTransitionCallback::Create(funcs.ExpectCall()); + ScriptPromiseTester first_promise_tester( - script_state, transition->captureAndHold(script_state, exception_state)); + script_state, + transition->start(script_state, document_transition_callback, + exception_state)); EXPECT_EQ(GetState(transition), State::kCapturing); UpdateAllLifecyclePhasesAndFinishDirectives(); - first_promise_tester.WaitUntilSettled(); - EXPECT_TRUE(first_promise_tester.IsFulfilled()); EXPECT_EQ(GetState(transition), State::kCaptured); EXPECT_FALSE(exception_state.HadException()); - transition->captureAndHold(script_state, exception_state); + transition->start(script_state, document_transition_callback, + exception_state); EXPECT_TRUE(exception_state.HadException()); EXPECT_EQ(GetState(transition), State::kIdle); } TEST_P(DocumentTransitionTest, TransitionCleanedUpBeforePromiseResolution) { + auto* transition = + DocumentTransitionSupplement::EnsureDocumentTransition(GetDocument()); + ASSERT_TRUE(transition->StartNewTransition()); + ASSERT_TRUE(transition); + EXPECT_EQ(GetState(transition), State::kIdle); + V8TestingScope v8_scope; ScriptState* script_state = v8_scope.GetScriptState(); ExceptionState& exception_state = v8_scope.GetExceptionState(); - auto* transition = - DocumentTransitionSupplement::EnsureDocumentTransition(GetDocument()); - auto scope = transition->CreateScriptMutationsAllowedScope(); - ScriptPromiseTester tester( - script_state, transition->captureAndHold(script_state, exception_state)); + MockFunctionScope funcs(script_state); + auto* document_transition_callback = + V8DocumentTransitionCallback::Create(funcs.ExpectCall()); + + ScriptPromiseTester promise_tester( + script_state, + transition->start(script_state, document_transition_callback, + exception_state)); // ActiveScriptWrappable should keep the transition alive. ThreadState::Current()->CollectAllGarbageForTesting(); + EXPECT_EQ(GetState(transition), State::kCapturing); UpdateAllLifecyclePhasesAndFinishDirectives(); - tester.WaitUntilSettled(); - EXPECT_TRUE(tester.IsFulfilled()); + EXPECT_EQ(GetState(transition), State::kCaptured); + + test::RunPendingTasks(); + EXPECT_EQ(GetState(transition), State::kStarted); + UpdateAllLifecyclePhasesAndFinishDirectives(); + FinishTransition(); + promise_tester.WaitUntilSettled(); + EXPECT_TRUE(promise_tester.IsFulfilled()); } -TEST_P(DocumentTransitionTest, StartHasNoEffectUnlessPrepared) { +TEST_P(DocumentTransitionTest, MultipleStartsBeforeTransitionFinished) { auto* transition = DocumentTransitionSupplement::EnsureDocumentTransition(GetDocument()); - auto scope = transition->CreateScriptMutationsAllowedScope(); - EXPECT_EQ(GetState(transition), State::kIdle); - EXPECT_FALSE(transition->TakePendingRequest()); + ASSERT_TRUE(transition->StartNewTransition()); V8TestingScope v8_scope; ScriptState* script_state = v8_scope.GetScriptState(); ExceptionState& exception_state = v8_scope.GetExceptionState(); - transition->start(script_state, exception_state); - EXPECT_EQ(GetState(transition), State::kIdle); - EXPECT_FALSE(transition->TakePendingRequest()); - EXPECT_TRUE(exception_state.HadException()); -} + MockFunctionScope funcs(script_state); + auto* document_transition_callback = + V8DocumentTransitionCallback::Create(funcs.ExpectCall()); -TEST_P(DocumentTransitionTest, StartAfterPrepare) { - auto* transition = - DocumentTransitionSupplement::EnsureDocumentTransition(GetDocument()); - auto scope = transition->CreateScriptMutationsAllowedScope(); - - V8TestingScope v8_scope; - ScriptState* script_state = v8_scope.GetScriptState(); - ExceptionState& exception_state = v8_scope.GetExceptionState(); - - ScriptPromiseTester capture_tester( - script_state, transition->captureAndHold(script_state, exception_state)); + ScriptPromiseTester start_tester( + script_state, + transition->start(script_state, document_transition_callback, + exception_state)); EXPECT_EQ(GetState(transition), State::kCapturing); UpdateAllLifecyclePhasesAndFinishDirectives(); - capture_tester.WaitUntilSettled(); - EXPECT_TRUE(capture_tester.IsFulfilled()); EXPECT_EQ(GetState(transition), State::kCaptured); - ScriptPromiseTester start_tester( - script_state, transition->start(script_state, exception_state)); - // Take the request. + // We should have a start request from the async callback passed to start() + // resolving. + test::RunPendingTasks(); auto start_request = transition->TakePendingRequest(); EXPECT_TRUE(start_request); EXPECT_EQ(GetState(transition), State::kStarted); @@ -472,8 +559,10 @@ // Subsequent starts should get an exception and cancel an existing // transition. EXPECT_FALSE(exception_state.HadException()); - transition->start(script_state, exception_state); + transition->start(script_state, document_transition_callback, + exception_state); EXPECT_TRUE(exception_state.HadException()); + // We will have a release request at this point. EXPECT_TRUE(transition->TakePendingRequest()); @@ -486,30 +575,32 @@ TEST_P(DocumentTransitionTest, StartPromiseIsResolved) { auto* transition = DocumentTransitionSupplement::EnsureDocumentTransition(GetDocument()); - auto scope = transition->CreateScriptMutationsAllowedScope(); + ASSERT_TRUE(transition->StartNewTransition()); V8TestingScope v8_scope; ScriptState* script_state = v8_scope.GetScriptState(); ExceptionState& exception_state = v8_scope.GetExceptionState(); - ScriptPromiseTester capture_tester( - script_state, transition->captureAndHold(script_state, exception_state)); + MockFunctionScope funcs(script_state); + auto* document_transition_callback = + V8DocumentTransitionCallback::Create(funcs.ExpectCall()); + + ScriptPromiseTester start_tester( + script_state, + transition->start(script_state, document_transition_callback, + exception_state)); EXPECT_EQ(GetState(transition), State::kCapturing); // Visual updates are allows during capture phase. EXPECT_FALSE(LayerTreeHost()->IsDeferringCommits()); UpdateAllLifecyclePhasesAndFinishDirectives(); - capture_tester.WaitUntilSettled(); - EXPECT_TRUE(capture_tester.IsFulfilled()); EXPECT_EQ(GetState(transition), State::kCaptured); // Visual updates are stalled between captured and start. EXPECT_TRUE(LayerTreeHost()->IsDeferringCommits()); - ScriptPromiseTester start_tester( - script_state, transition->start(script_state, exception_state)); - + test::RunPendingTasks(); EXPECT_EQ(GetState(transition), State::kStarted); UpdateAllLifecyclePhasesAndFinishDirectives(); FinishTransition(); @@ -525,20 +616,26 @@ TEST_P(DocumentTransitionTest, Abandon) { auto* transition = DocumentTransitionSupplement::EnsureDocumentTransition(GetDocument()); - auto scope = transition->CreateScriptMutationsAllowedScope(); + ASSERT_TRUE(transition->StartNewTransition()); V8TestingScope v8_scope; ScriptState* script_state = v8_scope.GetScriptState(); ExceptionState& exception_state = v8_scope.GetExceptionState(); - ScriptPromiseTester capture_tester( - script_state, transition->captureAndHold(script_state, exception_state)); + MockFunctionScope funcs(script_state); + auto* document_transition_callback = + V8DocumentTransitionCallback::Create(funcs.ExpectNoCall()); + + ScriptPromiseTester start_tester( + script_state, + transition->start(script_state, document_transition_callback, + exception_state)); EXPECT_EQ(GetState(transition), State::kCapturing); transition->abandon(script_state, exception_state); - capture_tester.WaitUntilSettled(); - EXPECT_TRUE(capture_tester.IsRejected()); + start_tester.WaitUntilSettled(); + EXPECT_TRUE(start_tester.IsRejected()); EXPECT_EQ(GetState(transition), State::kIdle); } @@ -561,16 +658,21 @@ auto* transition = DocumentTransitionSupplement::EnsureDocumentTransition(GetDocument()); - auto scope = transition->CreateScriptMutationsAllowedScope(); + ASSERT_TRUE(transition->StartNewTransition()); V8TestingScope v8_scope; ScriptState* script_state = v8_scope.GetScriptState(); ExceptionState& exception_state = v8_scope.GetExceptionState(); + MockFunctionScope funcs(script_state); + auto* document_transition_callback = + V8DocumentTransitionCallback::Create(funcs.ExpectCall()); + transition->setElement(script_state, e1, "e1", nullptr, exception_state); transition->setElement(script_state, e2, "e2", nullptr, exception_state); transition->setElement(script_state, e3, "e3", nullptr, exception_state); - transition->captureAndHold(script_state, exception_state); + transition->start(script_state, document_transition_callback, + exception_state); ASSERT_FALSE(exception_state.HadException()); UpdateAllLifecyclePhasesForTest(); @@ -590,8 +692,8 @@ <div id=e2></div> <div id=e3></div> )HTML"); - transition->start(script_state, exception_state); - ASSERT_FALSE(exception_state.HadException()); + test::RunPendingTasks(); + EXPECT_EQ(GetState(transition), State::kStarted); // The start phase should generate pseudo elements for rendering new live // content.
diff --git a/third_party/blink/renderer/core/dom/element.cc b/third_party/blink/renderer/core/dom/element.cc index f4190da1..ce44f79 100644 --- a/third_party/blink/renderer/core/dom/element.cc +++ b/third_party/blink/renderer/core/dom/element.cc
@@ -1220,47 +1220,44 @@ int Element::OffsetLeft() { GetDocument().EnsurePaintLocationDataValidForNode( this, DocumentUpdateReason::kJavaScript); - if (LayoutBoxModelObject* layout_object = GetLayoutBoxModelObject()) - return AdjustForAbsoluteZoom::AdjustLayoutUnit( - LayoutUnit( - layout_object->PixelSnappedOffsetLeft(OffsetParent())), - layout_object->StyleRef()) - .Round(); + if (const auto* layout_object = GetLayoutBoxModelObject()) { + return AdjustForAbsoluteZoom::AdjustInt( + layout_object->PixelSnappedOffsetLeft(OffsetParent()), + layout_object->StyleRef()); + } return 0; } int Element::OffsetTop() { GetDocument().EnsurePaintLocationDataValidForNode( this, DocumentUpdateReason::kJavaScript); - if (LayoutBoxModelObject* layout_object = GetLayoutBoxModelObject()) - return AdjustForAbsoluteZoom::AdjustLayoutUnit( - LayoutUnit(layout_object->PixelSnappedOffsetTop(OffsetParent())), - layout_object->StyleRef()) - .Round(); + if (const auto* layout_object = GetLayoutBoxModelObject()) { + return AdjustForAbsoluteZoom::AdjustInt( + layout_object->PixelSnappedOffsetTop(OffsetParent()), + layout_object->StyleRef()); + } return 0; } int Element::OffsetWidth() { GetDocument().EnsurePaintLocationDataValidForNode( this, DocumentUpdateReason::kJavaScript); - if (LayoutBoxModelObject* layout_object = GetLayoutBoxModelObject()) - return AdjustForAbsoluteZoom::AdjustLayoutUnit( - LayoutUnit( - layout_object->PixelSnappedOffsetWidth(OffsetParent())), - layout_object->StyleRef()) - .Round(); + if (const auto* layout_object = GetLayoutBoxModelObject()) { + return AdjustForAbsoluteZoom::AdjustInt( + layout_object->PixelSnappedOffsetWidth(OffsetParent()), + layout_object->StyleRef()); + } return 0; } int Element::OffsetHeight() { GetDocument().EnsurePaintLocationDataValidForNode( this, DocumentUpdateReason::kJavaScript); - if (LayoutBoxModelObject* layout_object = GetLayoutBoxModelObject()) - return AdjustForAbsoluteZoom::AdjustLayoutUnit( - LayoutUnit( - layout_object->PixelSnappedOffsetHeight(OffsetParent())), - layout_object->StyleRef()) - .Round(); + if (const auto* layout_object = GetLayoutBoxModelObject()) { + return AdjustForAbsoluteZoom::AdjustInt( + layout_object->PixelSnappedOffsetHeight(OffsetParent()), + layout_object->StyleRef()); + } return 0; } @@ -1276,10 +1273,10 @@ GetDocument().UpdateStyleAndLayoutForNode(this, DocumentUpdateReason::kJavaScript); - if (LayoutBox* layout_object = GetLayoutBox()) - return AdjustForAbsoluteZoom::AdjustLayoutUnit(layout_object->ClientLeft(), - layout_object->StyleRef()) - .Round(); + if (const auto* layout_object = GetLayoutBox()) { + return AdjustForAbsoluteZoom::AdjustInt(layout_object->ClientLeft().Round(), + layout_object->StyleRef()); + } return 0; } @@ -1287,10 +1284,10 @@ GetDocument().UpdateStyleAndLayoutForNode(this, DocumentUpdateReason::kJavaScript); - if (LayoutBox* layout_object = GetLayoutBox()) - return AdjustForAbsoluteZoom::AdjustLayoutUnit(layout_object->ClientTop(), - layout_object->StyleRef()) - .Round(); + if (const auto* layout_object = GetLayoutBox()) { + return AdjustForAbsoluteZoom::AdjustInt(layout_object->ClientTop().Round(), + layout_object->StyleRef()); + } return 0; } @@ -1395,19 +1392,15 @@ // OverflowClipRect() may return infinite along a particular axis if // |layout_view| is not a scroll-container. DCHECK(layout_view->IsScrollContainer()); - int result = - AdjustForAbsoluteZoom::AdjustLayoutUnit( - layout_view->OverflowClipRect(PhysicalOffset()).Width(), - layout_view->StyleRef()) - .Round(); + int result = AdjustForAbsoluteZoom::AdjustInt( + layout_view->OverflowClipRect(PhysicalOffset()).Width().Round(), + layout_view->StyleRef()); RecordScrollbarSizeForStudy(result, /* is_width= */ true, /* is_offset= */ false); return result; } - int result = AdjustForAbsoluteZoom::AdjustLayoutUnit( - LayoutUnit(layout_view->GetLayoutSize().width()), - layout_view->StyleRef()) - .Round(); + int result = AdjustForAbsoluteZoom::AdjustInt( + layout_view->GetLayoutSize().width(), layout_view->StyleRef()); RecordScrollbarSizeForStudy(result, /* is_width= */ true, /* is_offset= */ false); return result; @@ -1418,13 +1411,10 @@ DocumentUpdateReason::kJavaScript); int result = 0; - if (LayoutBox* layout_object = GetLayoutBox()) { - result = - AdjustForAbsoluteZoom::AdjustLayoutUnit( - LayoutUnit(layout_object - ->PixelSnappedClientWidthWithTableSpecialBehavior()), - layout_object->StyleRef()) - .Round(); + if (const auto* layout_object = GetLayoutBox()) { + result = AdjustForAbsoluteZoom::AdjustInt( + layout_object->PixelSnappedClientWidthWithTableSpecialBehavior(), + layout_object->StyleRef()); RecordScrollbarSizeForStudy(result, /* is_width= */ true, /* is_offset= */ false); } @@ -1449,19 +1439,15 @@ // OverflowClipRect() may return infinite along a particular axis if // |layout_view| is not a scroll-container. DCHECK(layout_view->IsScrollContainer()); - int result = - AdjustForAbsoluteZoom::AdjustLayoutUnit( - layout_view->OverflowClipRect(PhysicalOffset()).Height(), - layout_view->StyleRef()) - .Round(); + int result = AdjustForAbsoluteZoom::AdjustInt( + layout_view->OverflowClipRect(PhysicalOffset()).Height().Round(), + layout_view->StyleRef()); RecordScrollbarSizeForStudy(result, /* is_width= */ false, /* is_offset= */ false); return result; } - int result = AdjustForAbsoluteZoom::AdjustLayoutUnit( - LayoutUnit(layout_view->GetLayoutSize().height()), - layout_view->StyleRef()) - .Round(); + int result = AdjustForAbsoluteZoom::AdjustInt( + layout_view->GetLayoutSize().height(), layout_view->StyleRef()); RecordScrollbarSizeForStudy(result, /* is_width= */ false, /* is_offset= */ false); return result; @@ -1472,13 +1458,10 @@ DocumentUpdateReason::kJavaScript); int result = 0; - if (LayoutBox* layout_object = GetLayoutBox()) { - result = AdjustForAbsoluteZoom::AdjustLayoutUnit( - LayoutUnit( - layout_object - ->PixelSnappedClientHeightWithTableSpecialBehavior()), - layout_object->StyleRef()) - .Round(); + if (const auto* layout_object = GetLayoutBox()) { + result = AdjustForAbsoluteZoom::AdjustInt( + layout_object->PixelSnappedClientHeightWithTableSpecialBehavior(), + layout_object->StyleRef()); RecordScrollbarSizeForStudy(result, /* is_width= */ false, /* is_offset= */ false); }
diff --git a/third_party/blink/renderer/core/frame/local_frame_client.h b/third_party/blink/renderer/core/frame/local_frame_client.h index 3e36e5e7..74e7292 100644 --- a/third_party/blink/renderer/core/frame/local_frame_client.h +++ b/third_party/blink/renderer/core/frame/local_frame_client.h
@@ -237,6 +237,7 @@ std::unique_ptr<PolicyContainer> policy_container, std::unique_ptr<WebDocumentLoader::ExtraData> extra_data) = 0; + virtual String UserAgentOverride() = 0; virtual String UserAgent() = 0; virtual String FullUserAgent() = 0; virtual String ReducedUserAgent() = 0;
diff --git a/third_party/blink/renderer/core/frame/local_frame_client_impl.cc b/third_party/blink/renderer/core/frame/local_frame_client_impl.cc index e193f6c..a89bdbe 100644 --- a/third_party/blink/renderer/core/frame/local_frame_client_impl.cc +++ b/third_party/blink/renderer/core/frame/local_frame_client_impl.cc
@@ -40,6 +40,7 @@ #include "mojo/public/cpp/bindings/type_converter.h" #include "third_party/blink/public/common/blob/blob_utils.h" #include "third_party/blink/public/common/permissions_policy/permissions_policy.h" +#include "third_party/blink/public/common/user_agent/user_agent_metadata.h" #include "third_party/blink/public/mojom/frame/user_activation_update_types.mojom-blink-forward.h" #include "third_party/blink/public/platform/modules/service_worker/web_service_worker_provider.h" #include "third_party/blink/public/platform/modules/service_worker/web_service_worker_provider_client.h" @@ -783,11 +784,17 @@ return document_loader; } +String LocalFrameClientImpl::UserAgentOverride() { + return web_frame_->Client() + ? String(web_frame_->Client()->UserAgentOverride()) + : g_empty_string; +} + String LocalFrameClientImpl::UserAgent() { - WebString override = - web_frame_->Client() ? web_frame_->Client()->UserAgentOverride() : ""; - if (!override.IsEmpty()) + String override = UserAgentOverride(); + if (!override.IsEmpty()) { return override; + } if (user_agent_.IsEmpty()) user_agent_ = Platform::Current()->UserAgent(); @@ -795,10 +802,10 @@ } String LocalFrameClientImpl::ReducedUserAgent() { - WebString override = - web_frame_->Client() ? web_frame_->Client()->UserAgentOverride() : ""; - if (!override.IsEmpty()) + String override = UserAgentOverride(); + if (!override.IsEmpty()) { return override; + } if (reduced_user_agent_.IsEmpty()) reduced_user_agent_ = Platform::Current()->ReducedUserAgent(); @@ -806,10 +813,10 @@ } String LocalFrameClientImpl::FullUserAgent() { - WebString override = - web_frame_->Client() ? web_frame_->Client()->UserAgentOverride() : ""; - if (!override.IsEmpty()) + String override = UserAgentOverride(); + if (!override.IsEmpty()) { return override; + } if (full_user_agent_.IsEmpty()) full_user_agent_ = Platform::Current()->FullUserAgent();
diff --git a/third_party/blink/renderer/core/frame/local_frame_client_impl.h b/third_party/blink/renderer/core/frame/local_frame_client_impl.h index 503b864..4797360 100644 --- a/third_party/blink/renderer/core/frame/local_frame_client_impl.h +++ b/third_party/blink/renderer/core/frame/local_frame_client_impl.h
@@ -166,6 +166,7 @@ std::unique_ptr<PolicyContainer> policy_container, std::unique_ptr<WebDocumentLoader::ExtraData> extra_data) override; + String UserAgentOverride() override; WTF::String UserAgent() override; WTF::String FullUserAgent() override; WTF::String ReducedUserAgent() override;
diff --git a/third_party/blink/renderer/core/frame/use_counter_impl.cc b/third_party/blink/renderer/core/frame/use_counter_impl.cc index eaea9c3..415cd1b 100644 --- a/third_party/blink/renderer/core/frame/use_counter_impl.cc +++ b/third_party/blink/renderer/core/frame/use_counter_impl.cc
@@ -29,6 +29,7 @@ #include "third_party/blink/public/common/scheme_registry.h" #include "third_party/blink/public/mojom/permissions_policy/permissions_policy_feature.mojom-blink.h" #include "third_party/blink/public/mojom/use_counter/use_counter_feature.mojom-blink.h" +#include "third_party/blink/public/mojom/use_counter/use_counter_feature.mojom-shared.h" #include "third_party/blink/renderer/core/css/css_style_sheet.h" #include "third_party/blink/renderer/core/css/style_sheet_contents.h" #include "third_party/blink/renderer/core/dom/document.h" @@ -305,10 +306,20 @@ // TODO(crbug.com/1206004): Add trace event for permissions policy metrics // gathering. return; + case mojom::blink::UseCounterFeatureType::kUserAgentOverride: + return; } DCHECK(trace_name); TRACE_EVENT1(TRACE_DISABLED_BY_DEFAULT("blink.feature_usage"), trace_name, "feature", feature.value()); } +void UseCounterImpl::CountUserAgentOverride( + blink::UserAgentOverride::UserAgentOverrideHistogram ua_override, + const LocalFrame* source_frame) { + Count({mojom::blink::UseCounterFeatureType::kUserAgentOverride, + static_cast<uint32_t>(ua_override)}, + source_frame); +} + } // namespace blink
diff --git a/third_party/blink/renderer/core/frame/use_counter_impl.h b/third_party/blink/renderer/core/frame/use_counter_impl.h index fb633df..dd1ba9bc 100644 --- a/third_party/blink/renderer/core/frame/use_counter_impl.h +++ b/third_party/blink/renderer/core/frame/use_counter_impl.h
@@ -28,6 +28,7 @@ #include <bitset> #include "third_party/blink/public/common/use_counter/use_counter_feature_tracker.h" +#include "third_party/blink/public/common/user_agent/user_agent_metadata.h" #include "third_party/blink/public/mojom/permissions_policy/permissions_policy_feature.mojom-blink-forward.h" #include "third_party/blink/renderer/core/core_export.h" #include "third_party/blink/renderer/core/css/css_property_names.h" @@ -117,6 +118,9 @@ void CountPermissionsPolicyUsage(mojom::blink::PermissionsPolicyFeature, PermissionsPolicyUsageType, const LocalFrame&); + void CountUserAgentOverride( + blink::UserAgentOverride::UserAgentOverrideHistogram, + const LocalFrame*); // Return whether the feature has been seen since the last page load // (except when muted). Does include features seen in documents which have
diff --git a/third_party/blink/renderer/core/html/html_element.cc b/third_party/blink/renderer/core/html/html_element.cc index aae2330..040d0f6 100644 --- a/third_party/blink/renderer/core/html/html_element.cc +++ b/third_party/blink/renderer/core/html/html_element.cc
@@ -1729,11 +1729,11 @@ GetDocument().EnsurePaintLocationDataValidForNode( this, DocumentUpdateReason::kJavaScript); Element* offset_parent = unclosedOffsetParent(); - if (LayoutBoxModelObject* layout_object = GetLayoutBoxModelObject()) - return AdjustForAbsoluteZoom::AdjustLayoutUnit( - LayoutUnit(layout_object->PixelSnappedOffsetLeft(offset_parent)), - layout_object->StyleRef()) - .Round(); + if (const auto* layout_object = GetLayoutBoxModelObject()) { + return AdjustForAbsoluteZoom::AdjustInt( + layout_object->PixelSnappedOffsetLeft(offset_parent), + layout_object->StyleRef()); + } return 0; } @@ -1741,11 +1741,11 @@ GetDocument().EnsurePaintLocationDataValidForNode( this, DocumentUpdateReason::kJavaScript); Element* offset_parent = unclosedOffsetParent(); - if (LayoutBoxModelObject* layout_object = GetLayoutBoxModelObject()) - return AdjustForAbsoluteZoom::AdjustLayoutUnit( - LayoutUnit(layout_object->PixelSnappedOffsetTop(offset_parent)), - layout_object->StyleRef()) - .Round(); + if (const auto* layout_object = GetLayoutBoxModelObject()) { + return AdjustForAbsoluteZoom::AdjustInt( + layout_object->PixelSnappedOffsetTop(offset_parent), + layout_object->StyleRef()); + } return 0; } @@ -1754,12 +1754,10 @@ this, DocumentUpdateReason::kJavaScript); Element* offset_parent = unclosedOffsetParent(); int result = 0; - if (LayoutBoxModelObject* layout_object = GetLayoutBoxModelObject()) { - result = - AdjustForAbsoluteZoom::AdjustLayoutUnit( - LayoutUnit(layout_object->PixelSnappedOffsetWidth(offset_parent)), - layout_object->StyleRef()) - .Round(); + if (const auto* layout_object = GetLayoutBoxModelObject()) { + result = AdjustForAbsoluteZoom::AdjustInt( + layout_object->PixelSnappedOffsetWidth(offset_parent), + layout_object->StyleRef()); RecordScrollbarSizeForStudy(result, /* isWidth= */ true, /* is_offset= */ true); } @@ -1772,12 +1770,10 @@ this, DocumentUpdateReason::kJavaScript); Element* offset_parent = unclosedOffsetParent(); int result = 0; - if (LayoutBoxModelObject* layout_object = GetLayoutBoxModelObject()) { - result = - AdjustForAbsoluteZoom::AdjustLayoutUnit( - LayoutUnit(layout_object->PixelSnappedOffsetHeight(offset_parent)), - layout_object->StyleRef()) - .Round(); + if (const auto* layout_object = GetLayoutBoxModelObject()) { + result = AdjustForAbsoluteZoom::AdjustInt( + layout_object->PixelSnappedOffsetHeight(offset_parent), + layout_object->StyleRef()); RecordScrollbarSizeForStudy(result, /* is_width= */ false, /* is_offset= */ true); }
diff --git a/third_party/blink/renderer/core/layout/build.gni b/third_party/blink/renderer/core/layout/build.gni index 9d3c565..4ca11d2 100644 --- a/third_party/blink/renderer/core/layout/build.gni +++ b/third_party/blink/renderer/core/layout/build.gni
@@ -332,7 +332,6 @@ "ng/grid/layout_ng_grid_interface.h", "ng/grid/ng_grid_break_token_data.h", "ng/grid/ng_grid_data.h", - "ng/grid/ng_grid_geometry.h", "ng/grid/ng_grid_item.cc", "ng/grid/ng_grid_item.h", "ng/grid/ng_grid_layout_algorithm.cc",
diff --git a/third_party/blink/renderer/core/layout/ng/flex/ng_flex_layout_algorithm.cc b/third_party/blink/renderer/core/layout/ng/flex/ng_flex_layout_algorithm.cc index de1ec10..6b5a281 100644 --- a/third_party/blink/renderer/core/layout/ng/flex/ng_flex_layout_algorithm.cc +++ b/third_party/blink/renderer/core/layout/ng/flex/ng_flex_layout_algorithm.cc
@@ -161,6 +161,16 @@ // We are interested in cases where the flex item *may* expand due to // fragmentation (lines pushed down by a fragmentation line, etc). bool MinBlockSizeShouldEncompassIntrinsicSize(const NGFlexItem& item) { + // If this item has (any) descendant that is percentage based, we can end + // up in a situation where we'll constantly try and expand the row. E.g. + // <div style="display: flex;"> + // <div style="min-height: 100px;"> + // <div style="height: 200%;"></div> + // </div> + // </div> + if (item.has_descendant_that_depends_on_percentage_block_size) + return false; + if (item.ng_input_node.IsMonolithic()) return false; @@ -1172,6 +1182,9 @@ layout_result = item->layout_result_; } + flex_item.has_descendant_that_depends_on_percentage_block_size = + layout_result->HasDescendantThatDependsOnPercentageBlockSize(); + // The break-before and break-after values of flex items in a flex row are // propagated to the row itself. Accumulate the BreakBetween values for // each row ahead of time so that they can be stored on the break token
diff --git a/third_party/blink/renderer/core/layout/ng/flex/ng_flex_line.h b/third_party/blink/renderer/core/layout/ng/flex/ng_flex_line.h index f5dbe73..b4840861 100644 --- a/third_party/blink/renderer/core/layout/ng/flex/ng_flex_line.h +++ b/third_party/blink/renderer/core/layout/ng/flex/ng_flex_line.h
@@ -28,6 +28,7 @@ // fragmentation. LayoutUnit total_remaining_block_size; FlexOffset offset; + bool has_descendant_that_depends_on_percentage_block_size = false; NGBlockNode ng_input_node; };
diff --git a/third_party/blink/renderer/core/layout/ng/grid/layout_ng_grid.cc b/third_party/blink/renderer/core/layout/ng/grid/layout_ng_grid.cc index b1d0e613..5743bce 100644 --- a/third_party/blink/renderer/core/layout/ng/grid/layout_ng_grid.cc +++ b/third_party/blink/renderer/core/layout/ng/grid/layout_ng_grid.cc
@@ -216,8 +216,8 @@ return LayoutUnit(); return (track_direction == kForColumns) - ? grid_layout_data->column_geometry.gutter_size - : grid_layout_data->row_geometry.gutter_size; + ? grid_layout_data->columns.GutterSize() + : grid_layout_data->rows.GutterSize(); } LayoutUnit LayoutNGGrid::GridItemOffset( @@ -235,19 +235,23 @@ if (!grid_layout_data) return track_sizes; - const auto& geometry = (track_direction == kForColumns) - ? grid_layout_data->column_geometry - : grid_layout_data->row_geometry; + const auto& track_collection = (track_direction == kForColumns) + ? grid_layout_data->columns + : grid_layout_data->rows; - track_sizes.ReserveInitialCapacity( - std::min<wtf_size_t>(geometry.track_count, kGridMaxTracks)); + // |EndLineOfImplicitGrid| is equivalent to the total track count. + track_sizes.ReserveInitialCapacity(std::min<wtf_size_t>( + track_collection.EndLineOfImplicitGrid(), kGridMaxTracks)); - for (const auto& range : geometry.ranges) { - Vector<LayoutUnit> track_sizes_in_range = - ComputeTrackSizeRepeaterForRange(geometry, range); - for (wtf_size_t i = 0; i < range.track_count; ++i) { + const wtf_size_t range_count = track_collection.RangeCount(); + for (wtf_size_t i = 0; i < range_count; ++i) { + auto track_sizes_in_range = + ComputeTrackSizeRepeaterForRange(track_collection, i); + + const wtf_size_t range_track_count = track_collection.RangeTrackCount(i); + for (wtf_size_t j = 0; j < range_track_count; ++j) { track_sizes.emplace_back( - track_sizes_in_range[i % track_sizes_in_range.size()]); + track_sizes_in_range[j % track_sizes_in_range.size()]); // Respect total track count limit. DCHECK(track_sizes.size() <= kGridMaxTracks); @@ -269,35 +273,37 @@ } Vector<LayoutUnit> LayoutNGGrid::ComputeTrackSizeRepeaterForRange( - const NGGridLayoutData::TrackCollectionGeometry& geometry, - const NGGridLayoutData::RangeData& range) const { - if (range.IsCollapsed()) + const NGGridLayoutTrackCollection& track_collection, + wtf_size_t range_index) const { + const wtf_size_t range_set_count = + track_collection.RangeSetCount(range_index); + + if (!range_set_count) return {LayoutUnit()}; Vector<LayoutUnit> track_sizes; - track_sizes.ReserveInitialCapacity(range.set_count); + track_sizes.ReserveInitialCapacity(range_set_count); - const wtf_size_t ending_set_index = range.begin_set_index + range.set_count; - for (wtf_size_t set_index = range.begin_set_index; - set_index < ending_set_index; ++set_index) { - DCHECK_LT(set_index + 1, geometry.sets.size()); + const wtf_size_t begin_set_index = + track_collection.RangeBeginSetIndex(range_index); + const wtf_size_t end_set_index = begin_set_index + range_set_count; - // Set information is stored as offsets. To determine the size of a single - // track in a given set, first determine the total size the set takes up by - // finding the difference between the offsets. + for (wtf_size_t i = begin_set_index; i < end_set_index; ++i) { LayoutUnit set_size = - geometry.sets[set_index + 1].offset - geometry.sets[set_index].offset; + track_collection.GetSetOffset(i + 1) - track_collection.GetSetOffset(i); + const wtf_size_t set_track_count = track_collection.GetSetTrackCount(i); - const wtf_size_t set_track_count = geometry.sets[set_index + 1].track_count; - DCHECK_GT(set_track_count, 0u); + DCHECK_GE(set_size, 0); + set_size = (set_size - track_collection.GutterSize() * set_track_count) + .ClampNegativeToZero(); // Once we have determined the size of the set, we can find the size of a // given track by dividing the |set_size| by the |set_track_count|. // In some situations, this will leave a remainder, but rather than try to // distribute the space unequally between tracks, discard it to prefer equal // length tracks. - track_sizes.emplace_back((set_size / set_track_count) - - geometry.gutter_size); + DCHECK_GT(set_track_count, 0u); + track_sizes.emplace_back(set_size / set_track_count); } return track_sizes; } @@ -309,33 +315,38 @@ if (!grid_layout_data) return expanded_positions; - const auto& geometry = (track_direction == kForColumns) - ? grid_layout_data->column_geometry - : grid_layout_data->row_geometry; + const auto& track_collection = (track_direction == kForColumns) + ? grid_layout_data->columns + : grid_layout_data->rows; - expanded_positions.ReserveInitialCapacity( - std::min<wtf_size_t>(geometry.track_count + 1, kGridMaxTracks + 1)); + // |EndLineOfImplicitGrid| is equivalent to the total track count. + expanded_positions.ReserveInitialCapacity(std::min<wtf_size_t>( + track_collection.EndLineOfImplicitGrid() + 1, kGridMaxTracks + 1)); - LayoutUnit current_offset = geometry.sets[0].offset; + auto current_offset = track_collection.GetSetOffset(0); expanded_positions.emplace_back(current_offset); - bool is_last_range_collapsed = true; + auto last_applied_gutter_size = LayoutUnit(); auto BuildExpandedPositions = [&]() { - for (const auto& range : geometry.ranges) { - is_last_range_collapsed = range.IsCollapsed(); - Vector<LayoutUnit> track_sizes_in_range = - ComputeTrackSizeRepeaterForRange(geometry, range); + const wtf_size_t range_count = track_collection.RangeCount(); - for (wtf_size_t i = 0; i < range.track_count; ++i) { + for (wtf_size_t i = 0; i < range_count; ++i) { + auto track_sizes_in_range = + ComputeTrackSizeRepeaterForRange(track_collection, i); + last_applied_gutter_size = track_collection.RangeSetCount(i) + ? track_collection.GutterSize() + : LayoutUnit(); + + const wtf_size_t range_track_count = track_collection.RangeTrackCount(i); + for (wtf_size_t j = 0; j < range_track_count; ++j) { current_offset += - track_sizes_in_range[i % track_sizes_in_range.size()] + - (range.IsCollapsed() ? LayoutUnit() : geometry.gutter_size); + track_sizes_in_range[j % track_sizes_in_range.size()] + + last_applied_gutter_size; expanded_positions.emplace_back(current_offset); // Respect total track count limit, don't forget to account for the // initial offset. - DCHECK_LE(expanded_positions.size(), - static_cast<unsigned int>(kGridMaxTracks + 1)); + DCHECK(expanded_positions.size() <= kGridMaxTracks + 1); if (expanded_positions.size() == kGridMaxTracks + 1) return; } @@ -343,8 +354,7 @@ }; BuildExpandedPositions(); - if (!is_last_range_collapsed) - expanded_positions.back() -= geometry.gutter_size; + expanded_positions.back() -= last_applied_gutter_size; return expanded_positions; }
diff --git a/third_party/blink/renderer/core/layout/ng/grid/layout_ng_grid.h b/third_party/blink/renderer/core/layout/ng/grid/layout_ng_grid.h index 10b78ec..d34e5cc 100644 --- a/third_party/blink/renderer/core/layout/ng/grid/layout_ng_grid.h +++ b/third_party/blink/renderer/core/layout/ng/grid/layout_ng_grid.h
@@ -58,8 +58,8 @@ const NGGridLayoutData* GridLayoutData() const; Vector<LayoutUnit> ComputeTrackSizeRepeaterForRange( - const NGGridLayoutData::TrackCollectionGeometry& geometry, - const NGGridLayoutData::RangeData& range) const; + const NGGridLayoutTrackCollection& track_collection, + wtf_size_t range_index) const; Vector<LayoutUnit> ComputeExpandedPositions( const GridTrackSizingDirection track_direction) const;
diff --git a/third_party/blink/renderer/core/layout/ng/grid/ng_grid_break_token_data.h b/third_party/blink/renderer/core/layout/ng/grid/ng_grid_break_token_data.h index f886e8c..a6e4c84 100644 --- a/third_party/blink/renderer/core/layout/ng/grid/ng_grid_break_token_data.h +++ b/third_party/blink/renderer/core/layout/ng/grid/ng_grid_break_token_data.h
@@ -5,7 +5,7 @@ #ifndef THIRD_PARTY_BLINK_RENDERER_CORE_LAYOUT_NG_GRID_NG_GRID_BREAK_TOKEN_DATA_H_ #define THIRD_PARTY_BLINK_RENDERER_CORE_LAYOUT_NG_GRID_NG_GRID_BREAK_TOKEN_DATA_H_ -#include "third_party/blink/renderer/core/layout/ng/grid/ng_grid_geometry.h" +#include "third_party/blink/renderer/core/layout/ng/grid/ng_grid_data.h" #include "third_party/blink/renderer/core/layout/ng/ng_block_break_token_data.h" #include "third_party/blink/renderer/core/layout/ng/ng_fragmentation_utils.h" #include "third_party/blink/renderer/platform/geometry/layout_unit.h" @@ -15,8 +15,8 @@ struct GridItemPlacementData { GridItemPlacementData( - const LogicalOffset offset, - const LogicalOffset relative_offset, + LogicalOffset offset, + LogicalOffset relative_offset, bool has_descendant_that_depends_on_percentage_block_size) : offset(offset), relative_offset(relative_offset), @@ -32,23 +32,24 @@ public: NGGridBreakTokenData( const NGBlockBreakTokenData* break_token_data, - const NGGridGeometry& grid_geometry, + const NGGridLayoutData& layout_data, + LayoutUnit intrinsic_block_size, const Vector<GridItemPlacementData>& grid_items_placement_data, const Vector<LayoutUnit>& row_offset_adjustments, - const Vector<EBreakBetween>& row_break_between, - LayoutUnit intrinsic_block_size) + const Vector<EBreakBetween>& row_break_between) : NGBlockBreakTokenData(kGridBreakTokenData, break_token_data), - grid_geometry(grid_geometry), + layout_data(layout_data), + intrinsic_block_size(intrinsic_block_size), grid_items_placement_data(grid_items_placement_data), row_offset_adjustments(row_offset_adjustments), - row_break_between(row_break_between), - intrinsic_block_size(intrinsic_block_size) {} + row_break_between(row_break_between) {} - NGGridGeometry grid_geometry; + NGGridLayoutData layout_data; + LayoutUnit intrinsic_block_size; + Vector<GridItemPlacementData> grid_items_placement_data; Vector<LayoutUnit> row_offset_adjustments; Vector<EBreakBetween> row_break_between; - LayoutUnit intrinsic_block_size; }; template <>
diff --git a/third_party/blink/renderer/core/layout/ng/grid/ng_grid_data.h b/third_party/blink/renderer/core/layout/ng/grid/ng_grid_data.h index 7274b4c..0283635 100644 --- a/third_party/blink/renderer/core/layout/ng/grid/ng_grid_data.h +++ b/third_party/blink/renderer/core/layout/ng/grid/ng_grid_data.h
@@ -5,7 +5,6 @@ #ifndef THIRD_PARTY_BLINK_RENDERER_CORE_LAYOUT_NG_GRID_NG_GRID_DATA_H_ #define THIRD_PARTY_BLINK_RENDERER_CORE_LAYOUT_NG_GRID_NG_GRID_DATA_H_ -#include "third_party/blink/renderer/core/layout/ng/grid/ng_grid_geometry.h" #include "third_party/blink/renderer/core/layout/ng/grid/ng_grid_track_collection.h" #include "third_party/blink/renderer/platform/geometry/layout_unit.h" #include "third_party/blink/renderer/platform/wtf/vector.h" @@ -13,9 +12,6 @@ namespace blink { struct CORE_EXPORT NGGridPlacementData { - USING_FAST_MALLOC(NGGridPlacementData); - - public: NGGridPlacementData(const bool is_parent_grid_container, const wtf_size_t column_auto_repetitions, const wtf_size_t row_auto_repetitions) @@ -53,18 +49,14 @@ USING_FAST_MALLOC(NGGridLayoutData); public: - using RangeData = NGGridLayoutTrackCollection::Range; + NGGridLayoutData() : columns(kForColumns), rows(kForRows) {} - struct TrackCollectionGeometry { - Vector<RangeData> ranges; - Vector<SetOffsetData> sets; + NGGridLayoutData(NGGridSizingTrackCollection&& columns, + NGGridSizingTrackCollection&& rows) + : columns(std::move(columns)), rows(std::move(rows)) {} - LayoutUnit gutter_size; - wtf_size_t track_count; - }; - - TrackCollectionGeometry column_geometry; - TrackCollectionGeometry row_geometry; + NGGridSizingTrackCollection columns; + NGGridSizingTrackCollection rows; }; } // namespace blink
diff --git a/third_party/blink/renderer/core/layout/ng/grid/ng_grid_geometry.h b/third_party/blink/renderer/core/layout/ng/grid/ng_grid_geometry.h deleted file mode 100644 index 6b64212..0000000 --- a/third_party/blink/renderer/core/layout/ng/grid/ng_grid_geometry.h +++ /dev/null
@@ -1,95 +0,0 @@ -// Copyright 2021 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_LAYOUT_NG_GRID_NG_GRID_GEOMETRY_H_ -#define THIRD_PARTY_BLINK_RENDERER_CORE_LAYOUT_NG_GRID_NG_GRID_GEOMETRY_H_ - -#include "third_party/blink/renderer/core/style/grid_positions_resolver.h" -#include "third_party/blink/renderer/platform/geometry/layout_unit.h" -#include "third_party/blink/renderer/platform/wtf/vector.h" - -namespace blink { - -struct SetOffsetData { - SetOffsetData(LayoutUnit offset, wtf_size_t track_count) - : offset(offset), track_count(track_count) {} - - LayoutUnit offset; - wtf_size_t track_count; -}; - -// Contains the information about the start offset of the tracks, as well as -// the gutter size between them, for a given direction. -struct TrackGeometry { - LayoutUnit start_offset; - LayoutUnit gutter_size; -}; - -// Represents the offsets for the sets, and the gutter-size. -// -// Initially we only know some of the set sizes - others will be indefinite. To -// represent this we store both the offset for the set, and a vector of all -// last indefinite indices (or kNotFound if everything so far has been -// definite). This allows us to get the appropriate size if a grid item spans -// only fixed tracks, but will allow us to return an indefinite size if it -// spans any indefinite set. -// -// As an example: -// grid-template-rows: auto auto 100px 100px auto 100px; -// -// Results in: -// | auto | auto | 100 | 100 | auto | 100 | -// [{0, kNotFound}, {0, 0}, {0, 1}, {100, 1}, {200, 1}, {200, 4}, {300, 4}] -// -// Various queries (start/end refer to the grid lines): -// start: 0, end: 1 -> indefinite as: -// "start <= sets[end].last_indefinite_index" -// start: 1, end: 3 -> indefinite as: -// "start <= sets[end].last_indefinite_index" -// start: 2, end: 4 -> 200px -// start: 5, end: 6 -> 100px -// start: 3, end: 5 -> indefinite as: -// "start <= sets[end].last_indefinite_index" -struct SetGeometry { - SetGeometry() = default; - - SetGeometry(const TrackGeometry track_alignment_geometry, - const wtf_size_t set_count) - : gutter_size(track_alignment_geometry.gutter_size) { - sets.ReserveInitialCapacity(set_count); - sets.emplace_back(track_alignment_geometry.start_offset, - /* track_count */ 0); - } - - SetGeometry(const Vector<SetOffsetData>& sets, const LayoutUnit gutter_size) - : sets(sets), gutter_size(gutter_size) {} - - LayoutUnit FinalGutterSize() const { - DCHECK_GT(sets.size(), 0u); - return (sets.size() == 1) ? LayoutUnit() : gutter_size; - } - - Vector<wtf_size_t> last_indefinite_indices; - Vector<LayoutUnit> major_baselines; - Vector<LayoutUnit> minor_baselines; - Vector<SetOffsetData> sets; - - LayoutUnit gutter_size; -}; - -// Contains all the geometry information relevant to the final grid. This -// should have all the grid information needed to size and position items. -struct NGGridGeometry { - NGGridGeometry() = default; - - NGGridGeometry(SetGeometry&& column_geometry, SetGeometry&& row_geometry) - : column_geometry(column_geometry), row_geometry(row_geometry) {} - - SetGeometry column_geometry; - SetGeometry row_geometry; -}; - -} // namespace blink - -#endif // THIRD_PARTY_BLINK_RENDERER_CORE_LAYOUT_NG_GRID_NG_GRID_GEOMETRY_H_
diff --git a/third_party/blink/renderer/core/layout/ng/grid/ng_grid_layout_algorithm.cc b/third_party/blink/renderer/core/layout/ng/grid/ng_grid_layout_algorithm.cc index 057dd5e..f88006c 100644 --- a/third_party/blink/renderer/core/layout/ng/grid/ng_grid_layout_algorithm.cc +++ b/third_party/blink/renderer/core/layout/ng/grid/ng_grid_layout_algorithm.cc
@@ -89,22 +89,6 @@ namespace { -LayoutUnit ComputeSetSpanSize(const SetGeometry& set_geometry, - const GridItemIndices& set_indices) { - DCHECK_LT(set_indices.end, set_geometry.sets.size()); - DCHECK_LE(set_indices.begin, set_indices.end); - - const LayoutUnit start_offset = set_geometry.sets[set_indices.begin].offset; - const LayoutUnit end_offset = set_geometry.sets[set_indices.end].offset; - DCHECK_GE(end_offset, start_offset); - - // The size of a set span is the end offset minus the start offset and gutter - // size. It is floored at zero so that the size is not negative when the - // gutter size is greater than the difference between the offsets. - return (end_offset - start_offset - set_geometry.gutter_size) - .ClampNegativeToZero(); -} - bool HasBlockSizeDependentGridItem(const GridItems& grid_items) { for (const auto& grid_item : grid_items.item_data) { if (grid_item.is_sizing_dependent_on_block_size) @@ -113,58 +97,6 @@ return false; } -bool MayChangeOrthogonalItemContributions(const GridItems& grid_items, - const SetGeometry& old_row_geometry, - const SetGeometry& new_row_geometry) { - auto GridItemRowSpanSize = [](const GridItemData& grid_item, - const SetGeometry& set_geometry) -> LayoutUnit { - const auto& set_indices = grid_item.SetIndices(kForRows); - const wtf_size_t last_indefinite_index = - set_geometry.last_indefinite_indices.IsEmpty() - ? kNotFound - : set_geometry.last_indefinite_indices[set_indices.end]; - - return (last_indefinite_index == kNotFound || - last_indefinite_index < set_indices.begin) - ? ComputeSetSpanSize(set_geometry, set_indices) - : kIndefiniteSize; - }; - - for (const auto& grid_item : grid_items.item_data) { - if (grid_item.is_sizing_dependent_on_block_size) { - const auto old_size = GridItemRowSpanSize(grid_item, old_row_geometry); - const auto new_size = GridItemRowSpanSize(grid_item, new_row_geometry); - - DCHECK_NE(new_size, kIndefiniteSize); - if (old_size != new_size) - return true; - } - } - return false; -} - -NGGridLayoutData BundleLayoutData( - const NGGridSizingTrackCollection& column_track_collection, - const NGGridSizingTrackCollection& row_track_collection, - const NGGridGeometry& grid_geometry) { - NGGridLayoutData layout_data; - - layout_data.column_geometry.gutter_size = - grid_geometry.column_geometry.gutter_size; - layout_data.column_geometry.track_count = - column_track_collection.NonCollapsedTrackCount(); - layout_data.column_geometry.sets = grid_geometry.column_geometry.sets; - layout_data.column_geometry.ranges = column_track_collection.Ranges(); - - layout_data.row_geometry.gutter_size = grid_geometry.row_geometry.gutter_size; - layout_data.row_geometry.track_count = - row_track_collection.NonCollapsedTrackCount(); - layout_data.row_geometry.sets = grid_geometry.row_geometry.sets; - layout_data.row_geometry.ranges = row_track_collection.Ranges(); - - return layout_data; -} - NGGridProperties InitializeGridProperties( const GridItems& grid_items, const WritingMode container_writing_mode) { @@ -345,10 +277,8 @@ BuildBlockTrackCollections(&grid_items, &column_block_track_collection, &row_block_track_collection); - NGGridSizingTrackCollection column_track_collection; - NGGridSizingTrackCollection row_track_collection; + NGGridLayoutData layout_data; LayoutUnit intrinsic_block_size; - NGGridGeometry grid_geometry; if (IsResumingLayout(BreakToken())) { // TODO(layout-dev): When we support variable inline-size fragments we'll @@ -359,26 +289,20 @@ // first row). const auto* grid_data = To<NGGridBreakTokenData>(BreakToken()->TokenData()); intrinsic_block_size = grid_data->intrinsic_block_size; - grid_geometry = grid_data->grid_geometry; + layout_data = grid_data->layout_data; - column_track_collection = - NGGridSizingTrackCollection(column_block_track_collection, - /* is_available_size_indefinite */ false); - row_track_collection = NGGridSizingTrackCollection( - row_block_track_collection, /* is_available_size_indefinite */ false); - - CacheGridTrackSpanProperties(column_track_collection, &grid_items); - CacheGridTrackSpanProperties(row_track_collection, &grid_items); + CacheGridTrackSpanProperties(layout_data.columns, &grid_items); + CacheGridTrackSpanProperties(layout_data.rows, &grid_items); // Cache set indices for grid items. for (auto& grid_item : grid_items.item_data) { - grid_item.ComputeSetIndices(column_track_collection); - grid_item.ComputeSetIndices(row_track_collection); + grid_item.ComputeSetIndices(layout_data.columns); + grid_item.ComputeSetIndices(layout_data.rows); } } else { - grid_geometry = ComputeGridGeometry( - column_block_track_collection, row_block_track_collection, &grid_items, - &intrinsic_block_size, &column_track_collection, &row_track_collection); + ComputeGridGeometry(column_block_track_collection, + row_block_track_collection, &grid_items, &layout_data, + &intrinsic_block_size); } Vector<EBreakBetween> row_break_between; @@ -387,39 +311,37 @@ // non-fragmented |PlaceGridItems| pass. Vector<GridItemPlacementData> grid_items_placement_data; Vector<LayoutUnit> row_offset_adjustments; + if (IsResumingLayout(BreakToken())) { const auto* grid_data = To<NGGridBreakTokenData>(BreakToken()->TokenData()); + grid_items_placement_data = grid_data->grid_items_placement_data; row_offset_adjustments = grid_data->row_offset_adjustments; row_break_between = grid_data->row_break_between; } else { row_offset_adjustments = - Vector<LayoutUnit>(grid_geometry.row_geometry.sets.size()); - PlaceGridItems(grid_items, grid_geometry, &row_break_between, + Vector<LayoutUnit>(layout_data.rows.GetSetCount() + 1); + PlaceGridItems(grid_items, layout_data, &row_break_between, &grid_items_placement_data); } - PlaceGridItemsForFragmentation(grid_items, row_break_between, - &grid_geometry, &grid_items_placement_data, - &row_offset_adjustments, - &intrinsic_block_size); + PlaceGridItemsForFragmentation( + grid_items, row_break_between, &layout_data, &grid_items_placement_data, + &row_offset_adjustments, &intrinsic_block_size); container_builder_.SetBreakTokenData( MakeGarbageCollected<NGGridBreakTokenData>( - container_builder_.GetBreakTokenData(), grid_geometry, - grid_items_placement_data, row_offset_adjustments, - row_break_between, intrinsic_block_size)); + container_builder_.GetBreakTokenData(), layout_data, + intrinsic_block_size, grid_items_placement_data, + row_offset_adjustments, row_break_between)); } else { - PlaceGridItems(grid_items, grid_geometry, &row_break_between); + PlaceGridItems(grid_items, layout_data, &row_break_between); } - auto layout_data = std::make_unique<NGGridLayoutData>(BundleLayoutData( - column_track_collection, row_track_collection, grid_geometry)); - const auto& border_padding = BorderPadding(); const auto& constraint_space = ConstraintSpace(); - const LayoutUnit block_size = ComputeBlockSizeForFragment( + const auto block_size = ComputeBlockSizeForFragment( constraint_space, container_style, border_padding, intrinsic_block_size, container_builder_.InlineSize()); @@ -427,18 +349,13 @@ // are the size of the grid, and *not* where the inflow grid-items are placed. // Explicitly set the inflow-bounds to the grid size. if (node.IsScrollContainer()) { - LogicalRect inflow_bounds; - inflow_bounds.offset = {grid_geometry.column_geometry.sets.front().offset, - grid_geometry.row_geometry.sets.front().offset}; + LogicalOffset offset = {layout_data.columns.GetSetOffset(0), + layout_data.rows.GetSetOffset(0)}; - inflow_bounds.size = {grid_geometry.column_geometry.sets.back().offset - - grid_geometry.column_geometry.FinalGutterSize() - - inflow_bounds.offset.inline_offset, - grid_geometry.row_geometry.sets.back().offset - - grid_geometry.row_geometry.FinalGutterSize() - - inflow_bounds.offset.block_offset}; + LogicalSize size = {layout_data.columns.ComputeSetSpanSize(), + layout_data.rows.ComputeSetSpanSize()}; - container_builder_.SetInflowBounds(inflow_bounds); + container_builder_.SetInflowBounds(LogicalRect(offset, size)); } container_builder_.SetMayHaveDescendantAboveBlockStart(false); @@ -473,16 +390,18 @@ container_builder_.CheckNoBlockFragmentation(); #endif } + // Set our break-before/break-after. if (constraint_space.ShouldPropagateChildBreakValues()) { container_builder_.SetInitialBreakBefore(row_break_between.front()); container_builder_.SetPreviousBreakAfter(row_break_between.back()); } - PlaceOutOfFlowItems(*layout_data, block_size); + PlaceOutOfFlowItems(layout_data, block_size); - // Store layout data for use in computed style and devtools. - container_builder_.TransferGridLayoutData(std::move(layout_data)); + // Store grid geometry for use in computed style and devtools. + container_builder_.TransferGridLayoutData(std::make_unique<NGGridLayoutData>( + NGGridLayoutData(std::move(layout_data)))); NGOutOfFlowLayoutPart(node, constraint_space, &container_builder_).Run(); return container_builder_.ToBoxFragment(); @@ -523,68 +442,52 @@ const bool is_block_available_size_indefinite = grid_available_size_.block_size == kIndefiniteSize; - // Build algorithm track collections from the block track collections. - NGGridSizingTrackCollection column_track_collection( - column_block_track_collection, is_inline_available_size_indefinite); - NGGridSizingTrackCollection row_track_collection( - row_block_track_collection, is_block_available_size_indefinite); + NGGridLayoutData layout_data( + NGGridSizingTrackCollection(column_block_track_collection, + is_inline_available_size_indefinite), + NGGridSizingTrackCollection(row_block_track_collection, + is_block_available_size_indefinite)); NGGridProperties grid_properties = InitializeGridProperties(grid_items, container_style.GetWritingMode()); - CacheGridTrackSpanProperties(column_track_collection, &grid_items, + CacheGridTrackSpanProperties(layout_data.columns, &grid_items, &grid_properties); - CacheGridTrackSpanProperties(row_track_collection, &grid_items, - &grid_properties); + CacheGridTrackSpanProperties(layout_data.rows, &grid_items, &grid_properties); // Cache set indices for grid items. for (auto& grid_item : grid_items) { - grid_item.ComputeSetIndices(column_track_collection); - grid_item.ComputeSetIndices(row_track_collection); + grid_item.ComputeSetIndices(layout_data.columns); + grid_item.ComputeSetIndices(layout_data.rows); } bool depends_on_block_constraints = false; auto ComputeTotalColumnSize = [&](const SizingConstraint sizing_constraint) -> LayoutUnit { - NGGridGeometry grid_geometry( - InitializeTrackSizes(grid_properties, &column_track_collection), - InitializeTrackSizes(grid_properties, &row_track_collection)); + InitializeTrackSizes(grid_properties, &layout_data.columns); + InitializeTrackSizes(grid_properties, &layout_data.rows); bool needs_additional_pass = false; - grid_geometry.column_geometry = ComputeUsedTrackSizes( - grid_properties, sizing_constraint, &column_track_collection, - &grid_geometry, &grid_items, &needs_additional_pass); + ComputeUsedTrackSizes(layout_data, grid_properties, sizing_constraint, + &grid_items, &layout_data.columns, + &needs_additional_pass); if (needs_additional_pass || HasBlockSizeDependentGridItem(grid_items)) { // If we need to calculate the row geometry, we have a dependency on our // block constraints. depends_on_block_constraints = true; - absl::optional<SetGeometry> initial_row_geometry; - if (!needs_additional_pass) - initial_row_geometry = grid_geometry.row_geometry; - - grid_geometry.row_geometry = ComputeUsedTrackSizes( - grid_properties, sizing_constraint, &row_track_collection, - &grid_geometry, &grid_items, &needs_additional_pass); - - if (!needs_additional_pass) { - DCHECK(initial_row_geometry); - needs_additional_pass = MayChangeOrthogonalItemContributions( - grid_items, *initial_row_geometry, grid_geometry.row_geometry); - } + ComputeUsedTrackSizes(layout_data, grid_properties, sizing_constraint, + &grid_items, &layout_data.rows, + &needs_additional_pass); if (needs_additional_pass) { - grid_geometry.column_geometry = - InitializeTrackSizes(grid_properties, &column_track_collection); - grid_geometry.column_geometry = ComputeUsedTrackSizes( - grid_properties, sizing_constraint, &column_track_collection, - &grid_geometry, &grid_items); + InitializeTrackSizes(grid_properties, &layout_data.columns); + ComputeUsedTrackSizes(layout_data, grid_properties, sizing_constraint, + &grid_items, &layout_data.columns); } } - return ComputeSetSpanSize( - grid_geometry.column_geometry, - /* set_indices */ {0, grid_geometry.column_geometry.sets.size() - 1}); + return layout_data.columns.ComputeSetSpanSize(); }; MinMaxSizes sizes{ComputeTotalColumnSize(SizingConstraint::kMinContent), @@ -597,8 +500,373 @@ return MinMaxSizesResult(sizes, /* depends_on_block_constraints */ false); } +LayoutUnit NGGridLayoutAlgorithm::Baseline( + const NGGridLayoutData& layout_data, + const GridItemData& grid_item, + const GridTrackSizingDirection track_direction) const { + // "If a box spans multiple shared alignment contexts, then it participates + // in first/last baseline alignment within its start-most/end-most shared + // alignment context along that axis", so we only need to look at the first + // index for baseline/first-baseline support. + // https://www.w3.org/TR/css-align-3/#baseline-sharing-group + if (track_direction == kForColumns) { + const wtf_size_t set_index = grid_item.column_set_indices.begin; + return (grid_item.column_baseline_type == BaselineType::kMajor) + ? layout_data.columns.MajorBaseline(set_index) + : layout_data.columns.MinorBaseline(set_index); + } else { + const wtf_size_t set_index = grid_item.row_set_indices.begin; + return (grid_item.row_baseline_type == BaselineType::kMajor) + ? layout_data.rows.MajorBaseline(set_index) + : layout_data.rows.MinorBaseline(set_index); + } +} + namespace { +struct FirstSetGeometry { + LayoutUnit start_offset; + LayoutUnit gutter_size; +}; + +FirstSetGeometry ComputeFirstSetGeometry( + const NGGridSizingTrackCollection& track_collection, + const ComputedStyle& container_style, + LayoutUnit available_size, + LayoutUnit start_border_scrollbar_padding) { + const bool is_for_columns = track_collection.Direction() == kForColumns; + + const auto& content_alignment = is_for_columns + ? container_style.JustifyContent() + : container_style.AlignContent(); + const auto overflow = content_alignment.Overflow(); + + // Determining the free-space is typically unnecessary, i.e. if there is + // default alignment. Only compute this on-demand. + auto FreeSpace = [&]() -> LayoutUnit { + LayoutUnit free_space = available_size - track_collection.TotalTrackSize(); + + // If overflow is 'safe', make sure we don't overflow the 'start' edge + // (potentially causing some data loss as the overflow is unreachable). + return (overflow == OverflowAlignment::kSafe) + ? free_space.ClampNegativeToZero() + : free_space; + }; + + // The default alignment, perform adjustments on top of this. + FirstSetGeometry geometry{start_border_scrollbar_padding, + track_collection.GutterSize()}; + + // If we have an indefinite |available_size| we can't perform any alignment, + // just return the default alignment. + if (available_size == kIndefiniteSize) + return geometry; + + // TODO(ikilpatrick): 'space-between', 'space-around', and 'space-evenly' all + // divide by the free-space, and may have a non-zero modulo. Investigate if + // this should be distributed between the tracks. + switch (content_alignment.Distribution()) { + case ContentDistributionType::kSpaceBetween: { + // Default behavior for 'space-between' is to start align content. + const wtf_size_t track_count = track_collection.NonCollapsedTrackCount(); + const LayoutUnit free_space = FreeSpace(); + if (track_count < 2 || free_space < LayoutUnit()) + return geometry; + + geometry.gutter_size += free_space / (track_count - 1); + return geometry; + } + case ContentDistributionType::kSpaceAround: { + // Default behavior for 'space-around' is to center content. + const wtf_size_t track_count = track_collection.NonCollapsedTrackCount(); + const LayoutUnit free_space = FreeSpace(); + if (track_count < 1 || free_space < LayoutUnit()) { + geometry.start_offset += free_space / 2; + return geometry; + } + + LayoutUnit track_space = free_space / track_count; + geometry.start_offset += track_space / 2; + geometry.gutter_size += track_space; + return geometry; + } + case ContentDistributionType::kSpaceEvenly: { + // Default behavior for 'space-evenly' is to center content. + const wtf_size_t track_count = track_collection.NonCollapsedTrackCount(); + const LayoutUnit free_space = FreeSpace(); + if (free_space < LayoutUnit()) { + geometry.start_offset += free_space / 2; + return geometry; + } + + LayoutUnit track_space = free_space / (track_count + 1); + geometry.start_offset += track_space; + geometry.gutter_size += track_space; + return geometry; + } + case ContentDistributionType::kStretch: + case ContentDistributionType::kDefault: + break; + } + + switch (content_alignment.GetPosition()) { + case ContentPosition::kLeft: { + DCHECK(is_for_columns); + if (IsLtr(container_style.Direction())) + return geometry; + + geometry.start_offset += FreeSpace(); + return geometry; + } + case ContentPosition::kRight: { + DCHECK(is_for_columns); + if (IsRtl(container_style.Direction())) + return geometry; + + geometry.start_offset += FreeSpace(); + return geometry; + } + case ContentPosition::kCenter: { + geometry.start_offset += FreeSpace() / 2; + return geometry; + } + case ContentPosition::kEnd: + case ContentPosition::kFlexEnd: { + geometry.start_offset += FreeSpace(); + return geometry; + } + case ContentPosition::kStart: + case ContentPosition::kFlexStart: + case ContentPosition::kNormal: + case ContentPosition::kBaseline: + case ContentPosition::kLastBaseline: + return geometry; + } +} + +} // namespace + +void NGGridLayoutAlgorithm::ComputeGridGeometry( + const NGGridBlockTrackCollection& column_block_track_collection, + const NGGridBlockTrackCollection& row_block_track_collection, + GridItems* grid_items, + NGGridLayoutData* layout_data, + LayoutUnit* intrinsic_block_size) { + DCHECK(grid_items && layout_data && intrinsic_block_size); + + DCHECK_NE(grid_available_size_.inline_size, kIndefiniteSize); + const bool is_block_available_size_indefinite = + grid_available_size_.block_size == kIndefiniteSize; + + layout_data->columns = NGGridSizingTrackCollection( + column_block_track_collection, /* is_available_size_indefinite */ false); + layout_data->rows = NGGridSizingTrackCollection( + row_block_track_collection, is_block_available_size_indefinite); + + const auto& container_style = Style(); + NGGridProperties grid_properties = + InitializeGridProperties(*grid_items, container_style.GetWritingMode()); + + CacheGridTrackSpanProperties(layout_data->columns, grid_items, + &grid_properties); + CacheGridTrackSpanProperties(layout_data->rows, grid_items, &grid_properties); + + // Cache set indices for grid items. + for (auto& grid_item : grid_items->item_data) { + grid_item.ComputeSetIndices(layout_data->columns); + grid_item.ComputeSetIndices(layout_data->rows); + } + + auto ComputeGrid = [&]() { + // We perform the track sizing algorithm using two methods. First + // |InitializeTrackSizes|, which we need to get an initial column and row + // set geometry. Then |ComputeUsedTrackSizes|, to finalize the sizing + // algorithm for both dimensions. + InitializeTrackSizes(grid_properties, &layout_data->columns); + InitializeTrackSizes(grid_properties, &layout_data->rows); + + bool needs_additional_pass = false; + ComputeUsedTrackSizes(*layout_data, grid_properties, + SizingConstraint::kLayout, grid_items, + &layout_data->columns, &needs_additional_pass); + + ComputeUsedTrackSizes(*layout_data, grid_properties, + SizingConstraint::kLayout, grid_items, + &layout_data->rows, &needs_additional_pass); + + // If we had an orthogonal item which may have depended on the resolved row + // tracks, re-run the track sizing algorithm for both dimensions. + if (needs_additional_pass) { + InitializeTrackSizes(grid_properties, &layout_data->columns); + ComputeUsedTrackSizes(*layout_data, grid_properties, + SizingConstraint::kLayout, grid_items, + &layout_data->columns); + + InitializeTrackSizes(grid_properties, &layout_data->rows); + ComputeUsedTrackSizes(*layout_data, grid_properties, + SizingConstraint::kLayout, grid_items, + &layout_data->rows); + } + }; + + ComputeGrid(); + + const auto& border_scrollbar_padding = BorderScrollbarPadding(); + const auto& constraint_space = ConstraintSpace(); + + if (contain_intrinsic_block_size_) { + *intrinsic_block_size = *contain_intrinsic_block_size_; + } else { + *intrinsic_block_size = layout_data->rows.ComputeSetSpanSize() + + border_scrollbar_padding.BlockSum(); + + // TODO(layout-dev): This isn't great but matches legacy. Ideally this + // would only apply when we have only flexible track(s). + const auto& node = Node(); + if (grid_items->IsEmpty() && node.HasLineIfEmpty()) { + *intrinsic_block_size = std::max( + *intrinsic_block_size, border_scrollbar_padding.BlockSum() + + node.EmptyLineBlockSize(BreakToken())); + } + + *intrinsic_block_size = ClampIntrinsicBlockSize(constraint_space, node, + border_scrollbar_padding, + *intrinsic_block_size); + } + + if (grid_available_size_.block_size == kIndefiniteSize) { + const auto block_size = ComputeBlockSizeForFragment( + constraint_space, container_style, BorderPadding(), + *intrinsic_block_size, container_builder_.InlineSize()); + + DCHECK_NE(block_size, kIndefiniteSize); + + grid_available_size_.block_size = grid_min_available_size_.block_size = + grid_max_available_size_.block_size = + (block_size - border_scrollbar_padding.BlockSum()) + .ClampNegativeToZero(); + + // If we have any rows, gaps which will resolve differently if we have a + // definite |grid_available_size_| re-compute the grid using the + // |block_size| calculated above. + bool should_recompute_grid = + (container_style.RowGap() && + container_style.RowGap()->IsPercentOrCalc()) || + grid_properties.IsDependentOnAvailableSize(kForRows); + + // If we are a flex-item, we may have our initial block-size forced to be + // indefinite, however grid layout always re-computes the grid using the + // final "used" block-size. + // We can detect this case by checking if computing our block-size (with an + // indefinite intrinsic size) is definite. + // + // TODO(layout-dev): A small optimization here would be to do this only if + // we have 'auto' tracks which fill the remaining available space. + if (constraint_space.IsInitialBlockSizeIndefinite()) { + should_recompute_grid |= + ComputeBlockSizeForFragment( + constraint_space, container_style, BorderPadding(), + /* intrinsic_block_size */ kIndefiniteSize, + container_builder_.InlineSize()) != kIndefiniteSize; + } + + if (should_recompute_grid) { + layout_data->rows = NGGridSizingTrackCollection( + row_block_track_collection, /* is_available_size_indefinite */ false); + CacheGridTrackSpanProperties(layout_data->rows, grid_items, + &grid_properties); + ComputeGrid(); + } else if (container_style.AlignContent() != + ComputedStyleInitialValues::InitialAlignContent()) { + DCHECK(layout_data->rows.IsForSizing()); + + auto& sizing_collection = + To<NGGridSizingTrackCollection>(layout_data->rows); + + // Re-compute the row geometry now that we resolved the available block + // size. "align-content: space-evenly", etc, require the resolved size. + auto first_set_geometry = ComputeFirstSetGeometry( + sizing_collection, container_style, grid_available_size_.block_size, + border_scrollbar_padding.block_start); + + sizing_collection.CacheSetsGeometry(first_set_geometry.start_offset, + first_set_geometry.gutter_size); + } + } + + // Calculate final alignment baselines for grid item layout. + if (grid_properties.HasBaseline(kForColumns)) { + CalculateAlignmentBaselines(*layout_data, SizingConstraint::kLayout, + grid_items, &layout_data->columns); + } + if (grid_properties.HasBaseline(kForRows)) { + CalculateAlignmentBaselines(*layout_data, SizingConstraint::kLayout, + grid_items, &layout_data->rows); + } +} + +LayoutUnit NGGridLayoutAlgorithm::ComputeIntrinsicBlockSizeIgnoringChildren() + const { + const auto& node = Node(); + const LayoutUnit override_intrinsic_block_size = + node.OverrideIntrinsicContentBlockSize(); + DCHECK(node.ShouldApplyBlockSizeContainment()); + + // First check 'contain-intrinsic-size'. + if (override_intrinsic_block_size != kIndefiniteSize) + return BorderScrollbarPadding().BlockSum() + override_intrinsic_block_size; + + // Don't append any children for this calculation. + GridItems grid_items; + NGGridPlacementData placement_data(node.IsParentNGGrid(), + ComputeAutomaticRepetitions(kForColumns), + ComputeAutomaticRepetitions(kForRows)); + + const auto& container_style = Style(); + NGGridBlockTrackCollection column_block_track_collection( + container_style, placement_data, kForColumns); + NGGridBlockTrackCollection row_block_track_collection( + container_style, placement_data, kForRows); + + BuildBlockTrackCollections(&grid_items, &column_block_track_collection, + &row_block_track_collection); + + const bool is_block_available_size_indefinite = + grid_available_size_.block_size == kIndefiniteSize; + + NGGridLayoutData layout_data; + layout_data.rows = NGGridSizingTrackCollection( + row_block_track_collection, is_block_available_size_indefinite); + + NGGridProperties grid_properties = + InitializeGridProperties(grid_items, Style().GetWritingMode()); + CacheGridTrackSpanProperties(layout_data.rows, &grid_items, &grid_properties); + + InitializeTrackSizes(grid_properties, &layout_data.rows); + ComputeUsedTrackSizes(layout_data, grid_properties, SizingConstraint::kLayout, + &grid_items, &layout_data.rows); + + return layout_data.rows.ComputeSetSpanSize() + + BorderScrollbarPadding().BlockSum(); +} + +namespace { + +const NGLayoutResult* LayoutNodeForMeasure( + const NGBlockNode& node, + const NGConstraintSpace& constraint_space, + const SizingConstraint sizing_constraint) { + // Disable side effects during MinMax computation to avoid potential "MinMax + // after layout" crashes. This is not necessary during the layout pass, and + // would have a negative impact on performance if used there. + absl::optional<NGDisableSideEffectsScope> disable_side_effects; + if (sizing_constraint != SizingConstraint::kLayout && + !node.GetLayoutBox()->NeedsLayout()) { + disable_side_effects.emplace(); + } + return node.Layout(constraint_space); +} + LayoutUnit GetLogicalBaseline(const NGBoxFragment& fragment, const GridTrackSizingDirection track_direction, const WritingMode writing_mode) { @@ -668,320 +936,10 @@ } } -bool HasSynthesizedBaseline(const GridTrackSizingDirection track_direction, - const NGBoxFragment& fragment, - const WritingMode writing_mode) { - const auto child_writing_mode = - fragment.GetWritingDirection().GetWritingMode(); - const bool is_for_columns = (track_direction == kForColumns); - - // TODO(kschmi): Reconcile this with layout experts to see if this makes - // sense. Some of the entries here are non-intuitive. - switch (writing_mode) { - case WritingMode::kHorizontalTb: - switch (child_writing_mode) { - case WritingMode::kHorizontalTb: - return is_for_columns ? true : !fragment.Baseline().has_value(); - case WritingMode::kVerticalLr: - return is_for_columns ? !fragment.Baseline().has_value() : true; - case WritingMode::kVerticalRl: - return is_for_columns ? (!fragment.Baseline().has_value()) : true; - default: - NOTREACHED(); - return false; - } - case WritingMode::kVerticalLr: - switch (child_writing_mode) { - case WritingMode::kHorizontalTb: - return is_for_columns ? !fragment.Baseline().has_value() : true; - case WritingMode::kVerticalLr: - return is_for_columns ? true : !fragment.Baseline().has_value(); - case WritingMode::kVerticalRl: - return is_for_columns ? true : !fragment.Baseline().has_value(); - default: - NOTREACHED(); - return false; - } - case WritingMode::kVerticalRl: - switch (child_writing_mode) { - case WritingMode::kHorizontalTb: - return is_for_columns ? !fragment.Baseline().has_value() : true; - case WritingMode::kVerticalLr: - return is_for_columns ? true : !fragment.Baseline().has_value(); - case WritingMode::kVerticalRl: - return is_for_columns ? true : !fragment.Baseline().has_value(); - default: - NOTREACHED(); - return false; - } - default: - NOTREACHED(); - return false; - } -} - -} // namespace - -LayoutUnit NGGridLayoutAlgorithm::Baseline( - const NGGridGeometry& grid_geometry, - const GridItemData& grid_item, - const GridTrackSizingDirection track_direction) const { - // "If a box spans multiple shared alignment contexts, then it participates - // in first/last baseline alignment within its start-most/end-most shared - // alignment context along that axis", so we only need to look at the first - // index for baseline/first-baseline support. - // https://www.w3.org/TR/css-align-3/#baseline-sharing-group - if (track_direction == kForColumns) { - const wtf_size_t set_index = grid_item.column_set_indices.begin; - return (grid_item.column_baseline_type == BaselineType::kMajor) - ? grid_geometry.column_geometry.major_baselines[set_index] - : grid_geometry.column_geometry.minor_baselines[set_index]; - } else { - const wtf_size_t set_index = grid_item.row_set_indices.begin; - return (grid_item.row_baseline_type == BaselineType::kMajor) - ? grid_geometry.row_geometry.major_baselines[set_index] - : grid_geometry.row_geometry.minor_baselines[set_index]; - } -} - -NGGridGeometry NGGridLayoutAlgorithm::ComputeGridGeometry( - const NGGridBlockTrackCollection& column_block_track_collection, - const NGGridBlockTrackCollection& row_block_track_collection, - GridItems* grid_items, - LayoutUnit* intrinsic_block_size, - NGGridSizingTrackCollection* column_track_collection, - NGGridSizingTrackCollection* row_track_collection) { - DCHECK(grid_items && intrinsic_block_size && column_track_collection && - row_track_collection); - - DCHECK_NE(grid_available_size_.inline_size, kIndefiniteSize); - const bool is_block_available_size_indefinite = - grid_available_size_.block_size == kIndefiniteSize; - - // Build algorithm row track collection from the block track collection. - *column_track_collection = NGGridSizingTrackCollection( - column_block_track_collection, /* is_available_size_indefinite */ false); - *row_track_collection = NGGridSizingTrackCollection( - row_block_track_collection, is_block_available_size_indefinite); - - const auto& container_style = Style(); - NGGridProperties grid_properties = - InitializeGridProperties(*grid_items, container_style.GetWritingMode()); - - CacheGridTrackSpanProperties(*column_track_collection, grid_items, - &grid_properties); - CacheGridTrackSpanProperties(*row_track_collection, grid_items, - &grid_properties); - - // Cache set indices for grid items. - for (auto& grid_item : grid_items->item_data) { - grid_item.ComputeSetIndices(*column_track_collection); - grid_item.ComputeSetIndices(*row_track_collection); - } - - NGGridGeometry grid_geometry; - auto ComputeGrid = [&]() { - // We perform the track sizing algorithm using two methods. First - // |InitializeTrackSizes|, which we need to get an initial column and row - // set geometry. Then |ComputeUsedTrackSizes|, to finalize the sizing - // algorithm for both dimensions. - grid_geometry = NGGridGeometry( - InitializeTrackSizes(grid_properties, column_track_collection), - InitializeTrackSizes(grid_properties, row_track_collection)); - - bool needs_additional_pass = false; - grid_geometry.column_geometry = ComputeUsedTrackSizes( - grid_properties, SizingConstraint::kLayout, column_track_collection, - &grid_geometry, grid_items, &needs_additional_pass); - - absl::optional<SetGeometry> initial_row_geometry; - if (!needs_additional_pass && HasBlockSizeDependentGridItem(*grid_items)) - initial_row_geometry = grid_geometry.row_geometry; - - grid_geometry.row_geometry = ComputeUsedTrackSizes( - grid_properties, SizingConstraint::kLayout, row_track_collection, - &grid_geometry, grid_items, &needs_additional_pass); - - if (!needs_additional_pass && initial_row_geometry) { - needs_additional_pass = MayChangeOrthogonalItemContributions( - *grid_items, *initial_row_geometry, grid_geometry.row_geometry); - } - - // If we had an orthogonal item which may have depended on the resolved row - // tracks, re-run the track sizing algorithm for both dimensions. - if (needs_additional_pass) { - grid_geometry.column_geometry = - InitializeTrackSizes(grid_properties, column_track_collection); - grid_geometry.column_geometry = ComputeUsedTrackSizes( - grid_properties, SizingConstraint::kLayout, column_track_collection, - &grid_geometry, grid_items); - - grid_geometry.row_geometry = - InitializeTrackSizes(grid_properties, row_track_collection); - grid_geometry.row_geometry = ComputeUsedTrackSizes( - grid_properties, SizingConstraint::kLayout, row_track_collection, - &grid_geometry, grid_items); - } - }; - - ComputeGrid(); - - if (contain_intrinsic_block_size_) { - *intrinsic_block_size = *contain_intrinsic_block_size_; - } else { - // Intrinsic block size is based on the final row offset. Because gutters - // are included in row offsets, subtract out the final gutter (if present). - *intrinsic_block_size = grid_geometry.row_geometry.sets.back().offset - - grid_geometry.row_geometry.FinalGutterSize() + - BorderScrollbarPadding().block_end; - - // TODO(layout-dev): This isn't great but matches legacy. Ideally this - // would only apply when we have only flexible track(s). - const auto& node = Node(); - if (grid_items->IsEmpty() && node.HasLineIfEmpty()) { - *intrinsic_block_size = std::max( - *intrinsic_block_size, BorderScrollbarPadding().BlockSum() + - node.EmptyLineBlockSize(BreakToken())); - } - - *intrinsic_block_size = ClampIntrinsicBlockSize(ConstraintSpace(), node, - BorderScrollbarPadding(), - *intrinsic_block_size); - } - - if (grid_available_size_.block_size == kIndefiniteSize) { - const LayoutUnit block_size = ComputeBlockSizeForFragment( - ConstraintSpace(), container_style, BorderPadding(), - *intrinsic_block_size, container_builder_.InlineSize()); - - DCHECK_NE(block_size, kIndefiniteSize); - - grid_available_size_.block_size = grid_min_available_size_.block_size = - grid_max_available_size_.block_size = - (block_size - BorderScrollbarPadding().BlockSum()) - .ClampNegativeToZero(); - - // If we have any rows, gaps which will resolve differently if we have a - // definite |grid_available_size_| re-compute the grid using the - // |block_size| calculated above. - bool should_recompute_grid = - (container_style.RowGap() && - container_style.RowGap()->IsPercentOrCalc()) || - grid_properties.IsDependentOnAvailableSize(kForRows); - - // If we are a flex-item, we may have our initial block-size forced to be - // indefinite, however grid layout always re-computes the grid using the - // final "used" block-size. - // We can detect this case by checking if computing our block-size (with an - // indefinite intrinsic size) is definite. - // - // TODO(layout-dev): A small optimization here would be to do this only if - // we have 'auto' tracks which fill the remaining available space. - if (ConstraintSpace().IsInitialBlockSizeIndefinite()) { - should_recompute_grid |= - ComputeBlockSizeForFragment( - ConstraintSpace(), container_style, BorderPadding(), - /* intrinsic_block_size */ kIndefiniteSize, - container_builder_.InlineSize()) != kIndefiniteSize; - } - - if (should_recompute_grid) { - *row_track_collection = NGGridSizingTrackCollection( - row_block_track_collection, /* is_available_size_indefinite */ false); - CacheGridTrackSpanProperties(*row_track_collection, grid_items, - &grid_properties); - ComputeGrid(); - } else if (container_style.AlignContent() != - ComputedStyleInitialValues::InitialAlignContent()) { - // Re-compute the row geometry now that we resolved the available block - // size. "align-content: space-evenly", etc, require the resolved size. - grid_geometry.row_geometry = ComputeSetGeometry(*row_track_collection); - } - } - - // Calculate final alignment baselines for grid item layout. - if (grid_properties.HasBaseline(kForColumns)) { - CalculateAlignmentBaselines(kForColumns, SizingConstraint::kLayout, - &grid_geometry, grid_items); - } - if (grid_properties.HasBaseline(kForRows)) { - CalculateAlignmentBaselines(kForRows, SizingConstraint::kLayout, - &grid_geometry, grid_items); - } - return grid_geometry; -} - -LayoutUnit NGGridLayoutAlgorithm::ComputeIntrinsicBlockSizeIgnoringChildren() - const { - const auto& node = Node(); - const LayoutUnit override_intrinsic_block_size = - node.OverrideIntrinsicContentBlockSize(); - DCHECK(node.ShouldApplyBlockSizeContainment()); - - // First check 'contain-intrinsic-size'. - if (override_intrinsic_block_size != kIndefiniteSize) - return BorderScrollbarPadding().BlockSum() + override_intrinsic_block_size; - - // Don't append any children for this calculation. - GridItems grid_items; - NGGridPlacementData placement_data(node.IsParentNGGrid(), - ComputeAutomaticRepetitions(kForColumns), - ComputeAutomaticRepetitions(kForRows)); - - const auto& container_style = Style(); - NGGridBlockTrackCollection column_block_track_collection( - container_style, placement_data, kForColumns); - NGGridBlockTrackCollection row_block_track_collection( - container_style, placement_data, kForRows); - - BuildBlockTrackCollections(&grid_items, &column_block_track_collection, - &row_block_track_collection); - - const bool is_block_available_size_indefinite = - grid_available_size_.block_size == kIndefiniteSize; - - // Build algorithm row track collection from the block track collection. - NGGridSizingTrackCollection row_track_collection( - row_block_track_collection, is_block_available_size_indefinite); - - NGGridProperties grid_properties = - InitializeGridProperties(grid_items, Style().GetWritingMode()); - - NGGridGeometry grid_geometry( - SetGeometry(), - InitializeTrackSizes(grid_properties, &row_track_collection)); - - // Resolve the rows. - grid_geometry.row_geometry = - ComputeUsedTrackSizes(grid_properties, SizingConstraint::kLayout, - &row_track_collection, &grid_geometry, &grid_items); - - return grid_geometry.row_geometry.sets.back().offset - - grid_geometry.row_geometry.FinalGutterSize() + - BorderScrollbarPadding().block_end; -} - -namespace { - -const NGLayoutResult* LayoutNodeForMeasure( - const NGBlockNode& node, - const NGConstraintSpace& constraint_space, - const SizingConstraint sizing_constraint) { - // Disable side effects during MinMax computation to avoid potential "MinMax - // after layout" crashes. This is not necessary during the layout pass, and - // would have a negative impact on performance if used there. - absl::optional<NGDisableSideEffectsScope> disable_side_effects; - if (sizing_constraint != SizingConstraint::kLayout && - !node.GetLayoutBox()->NeedsLayout()) { - disable_side_effects.emplace(); - } - return node.Layout(constraint_space); -} - } // namespace LayoutUnit NGGridLayoutAlgorithm::ContributionSizeForGridItem( - const NGGridGeometry& grid_geometry, + const NGGridLayoutData& layout_data, const SizingConstraint sizing_constraint, const GridTrackSizingDirection track_direction, const GridItemContributionType contribution_type, @@ -999,8 +957,8 @@ // TODO(ikilpatrick): We'll need to record if any child used an indefinite // size for its contribution, such that we can then do the 2nd pass on the // track-sizing algorithm. - const auto space = CreateConstraintSpaceForMeasure(*grid_item, grid_geometry, - track_direction); + const auto space = + CreateConstraintSpaceForMeasure(*grid_item, layout_data, track_direction); const auto margins = ComputeMarginsFor(space, item_style, ConstraintSpace()); auto MinMaxContentSizes = [&]() -> MinMaxSizes { @@ -1046,7 +1004,7 @@ // If we are orthogonal grid-item, resolving against an indefinite size, // set our inline-size to our max content-contribution size. const auto fallback_space = CreateConstraintSpaceForMeasure( - *grid_item, grid_geometry, track_direction, + *grid_item, layout_data, track_direction, /* opt_fixed_block_size */ MinMaxContentSizes().max_size); result = LayoutNodeForMeasure(node, fallback_space, sizing_constraint); @@ -1060,7 +1018,7 @@ if (grid_item->IsBaselineAlignedForDirection(track_direction)) { LayoutUnit track_baseline = - Baseline(grid_geometry, *grid_item, track_direction); + Baseline(layout_data, *grid_item, track_direction); // The item's baseline alignment impacts the item's contribution as the // difference between the track's baseline and the item's baseline. @@ -1159,26 +1117,22 @@ ? MinMaxContentSizes().min_size : BlockContributionSize(); - const auto& set_geometry = is_for_columns - ? grid_geometry.column_geometry - : grid_geometry.row_geometry; const auto& set_indices = grid_item->SetIndices(track_direction); - const wtf_size_t last_indefinite_index = - set_geometry.last_indefinite_indices[set_indices.end]; + const auto& track_collection = + is_for_columns ? layout_data.columns : layout_data.rows; - if (last_indefinite_index == kNotFound || - last_indefinite_index < set_indices.begin) { + auto spanned_tracks_definite_max_size = + track_collection.ComputeSetSpanSize(set_indices.begin, + set_indices.end); + + if (spanned_tracks_definite_max_size != kIndefiniteSize) { // Further clamp the minimum size to less than or equal to the // stretch fit into the grid area’s maximum size in that dimension, // as represented by the sum of those grid tracks’ max track sizing // functions plus any intervening fixed gutters. - LayoutUnit spanned_tracks_definite_max_size = - ComputeSetSpanSize(set_geometry, set_indices); - DCHECK_GE(spanned_tracks_definite_max_size, 0); - - const LayoutUnit border_padding_sum = - is_parallel_with_track_direction ? border_padding.InlineSum() - : border_padding.BlockSum(); + const auto border_padding_sum = is_parallel_with_track_direction + ? border_padding.InlineSum() + : border_padding.BlockSum(); DCHECK_GE(contribution, baseline_shim + border_padding_sum); // The stretch fit into a given size is that size, minus the box’s @@ -1263,7 +1217,7 @@ : grid_min_available_size_.block_size; } - const LayoutUnit grid_gap = GridGap(track_direction); + const LayoutUnit gutter_size = GutterSize(track_direction); LayoutUnit auto_repeater_size; LayoutUnit non_auto_specified_size; @@ -1307,7 +1261,7 @@ if (is_auto_repeater) track_contribution = std::max(LayoutUnit(1), track_contribution); - repeater_size += track_contribution + grid_gap; + repeater_size += track_contribution + gutter_size; } if (!is_auto_repeater) { non_auto_specified_size += @@ -1321,17 +1275,17 @@ DCHECK_GT(auto_repeater_size, 0); // We can compute the number of repetitions by satisfying the expression - // below. Notice that we subtract an extra |grid_gap| since it was included + // below. Notice that we subtract an extra |gutter_size| since it was included // in the contribution for the last set in the collection. // available_size = // (repetitions * auto_repeater_size) + - // non_auto_specified_size - grid_gap + // non_auto_specified_size - gutter_size // // Solving for repetitions we have: // repetitions = - // available_size - (non_auto_specified_size - grid_gap) / + // available_size - (non_auto_specified_size - gutter_size) / // auto_repeater_size - non_auto_specified_size -= grid_gap; + non_auto_specified_size -= gutter_size; // First we want to allow as many repetitions as possible, up to the max // available-size. Only do this if we have a definite max-size. @@ -1376,21 +1330,75 @@ EnsureTrackCoverage(row_track_collection); } +namespace { + +bool HasSynthesizedBaseline(const GridTrackSizingDirection track_direction, + const NGBoxFragment& fragment, + const WritingMode writing_mode) { + const auto child_writing_mode = + fragment.GetWritingDirection().GetWritingMode(); + const bool is_for_columns = (track_direction == kForColumns); + + // TODO(kschmi): Reconcile this with layout experts to see if this makes + // sense. Some of the entries here are non-intuitive. + switch (writing_mode) { + case WritingMode::kHorizontalTb: + switch (child_writing_mode) { + case WritingMode::kHorizontalTb: + return is_for_columns ? true : !fragment.Baseline().has_value(); + case WritingMode::kVerticalLr: + return is_for_columns ? !fragment.Baseline().has_value() : true; + case WritingMode::kVerticalRl: + return is_for_columns ? (!fragment.Baseline().has_value()) : true; + default: + NOTREACHED(); + return false; + } + case WritingMode::kVerticalLr: + switch (child_writing_mode) { + case WritingMode::kHorizontalTb: + return is_for_columns ? !fragment.Baseline().has_value() : true; + case WritingMode::kVerticalLr: + return is_for_columns ? true : !fragment.Baseline().has_value(); + case WritingMode::kVerticalRl: + return is_for_columns ? true : !fragment.Baseline().has_value(); + default: + NOTREACHED(); + return false; + } + case WritingMode::kVerticalRl: + switch (child_writing_mode) { + case WritingMode::kHorizontalTb: + return is_for_columns ? !fragment.Baseline().has_value() : true; + case WritingMode::kVerticalLr: + return is_for_columns ? true : !fragment.Baseline().has_value(); + case WritingMode::kVerticalRl: + return is_for_columns ? true : !fragment.Baseline().has_value(); + default: + NOTREACHED(); + return false; + } + default: + NOTREACHED(); + return false; + } +} + +} // namespace + void NGGridLayoutAlgorithm::CalculateAlignmentBaselines( - const GridTrackSizingDirection track_direction, + const NGGridLayoutData& layout_data, const SizingConstraint sizing_constraint, - NGGridGeometry* grid_geometry, GridItems* grid_items, + NGGridLayoutTrackCollection* track_collection, bool* needs_additional_pass) const { - DCHECK(grid_geometry && grid_items); + DCHECK(grid_items && track_collection && track_collection->IsForSizing()); + auto* sizing_collection = To<NGGridSizingTrackCollection>(track_collection); + const auto track_direction = sizing_collection->Direction(); const bool is_for_columns = track_direction == kForColumns; - auto& set_geometry = is_for_columns ? grid_geometry->column_geometry - : grid_geometry->row_geometry; - const wtf_size_t set_count = set_geometry.sets.size(); - set_geometry.major_baselines.Fill(LayoutUnit::Min(), set_count); - set_geometry.minor_baselines.Fill(LayoutUnit::Min(), set_count); + sizing_collection->ResetBaselines(); auto UpdateBaseline = [&](const GridItemData& grid_item, LayoutUnit candidate_baseline) { @@ -1399,17 +1407,16 @@ // alignment context along that axis", so we only need to look at the first // index for baseline/first-baseline support. // https://www.w3.org/TR/css-align-3/#baseline-sharing-group + const auto baseline_type = is_for_columns ? grid_item.column_baseline_type + : grid_item.row_baseline_type; const wtf_size_t set_index = is_for_columns ? grid_item.column_set_indices.begin : grid_item.row_set_indices.begin; - const bool is_major_baseline = - BaselineType::kMajor == (is_for_columns ? grid_item.column_baseline_type - : grid_item.row_baseline_type); - LayoutUnit& track_baseline = is_major_baseline - ? set_geometry.major_baselines[set_index] - : set_geometry.minor_baselines[set_index]; - track_baseline = std::max(track_baseline, candidate_baseline); + if (baseline_type == BaselineType::kMajor) + sizing_collection->SetMajorBaseline(set_index, candidate_baseline); + else + sizing_collection->SetMinorBaseline(set_index, candidate_baseline); }; for (auto& grid_item : grid_items->item_data) { @@ -1417,7 +1424,7 @@ continue; LogicalRect unused_grid_area; - const auto space = CreateConstraintSpaceForLayout(*grid_geometry, grid_item, + const auto space = CreateConstraintSpaceForLayout(layout_data, grid_item, &unused_grid_area); // We cannot apply some of the baseline alignment rules for synthesized @@ -1466,31 +1473,19 @@ } // https://drafts.csswg.org/css-grid-2/#algo-init -SetGeometry NGGridLayoutAlgorithm::InitializeTrackSizes( +void NGGridLayoutAlgorithm::InitializeTrackSizes( const NGGridProperties& grid_properties, - NGGridSizingTrackCollection* track_collection) const { - DCHECK(track_collection); + NGGridLayoutTrackCollection* track_collection) const { + DCHECK(track_collection && track_collection->IsForSizing()); - const auto track_direction = track_collection->Direction(); - const wtf_size_t set_count = track_collection->SetCount() + 1; + auto* sizing_collection = To<NGGridSizingTrackCollection>(track_collection); + const auto track_direction = sizing_collection->Direction(); + const bool is_for_columns = track_direction == kForColumns; - LayoutUnit available_size = (track_direction == kForColumns) - ? grid_available_size_.inline_size - : grid_available_size_.block_size; + LayoutUnit available_size = is_for_columns ? grid_available_size_.inline_size + : grid_available_size_.block_size; - TrackGeometry track_geometry; - track_geometry.start_offset = (track_direction == kForColumns) - ? BorderScrollbarPadding().inline_start - : BorderScrollbarPadding().block_start; - track_geometry.gutter_size = GridGap(track_direction); - SetGeometry set_geometry(track_geometry, set_count); - - // The initial last indefinite index is always kNotFound. - wtf_size_t last_indefinite_index = kNotFound; - set_geometry.last_indefinite_indices.ReserveInitialCapacity(set_count); - set_geometry.last_indefinite_indices.emplace_back(last_indefinite_index); - - for (auto set_iterator = track_collection->GetSetIterator(); + for (auto set_iterator = sizing_collection->GetSetIterator(); !set_iterator.IsAtEnd(); set_iterator.MoveToNextSet()) { auto& current_set = set_iterator.CurrentSet(); const auto& track_size = current_set.track_size; @@ -1517,18 +1512,10 @@ LayoutUnit fixed_max_breadth = MinimumValueForLength( track_size.MaxTrackBreadth().length(), available_size); current_set.growth_limit = fixed_max_breadth * current_set.track_count; - - // For the purposes of our "base" row set geometry, we only use any - // definite max track sizing functions. We will use this value later to - // measure orthogonal (or %-block-size) grid item contributions. - track_geometry.start_offset += - (fixed_max_breadth + set_geometry.gutter_size) * - current_set.track_count; } else { // An intrinsic or flexible sizing function: Use an initial growth limit // of infinity. current_set.growth_limit = kIndefiniteSize; - last_indefinite_index = set_geometry.sets.size() - 1; } if (track_size.HasFixedMinTrackBreadth()) { @@ -1545,64 +1532,154 @@ DCHECK(track_size.HasIntrinsicMinTrackBreadth()); current_set.InitBaseSize(LayoutUnit()); } - - set_geometry.sets.emplace_back(track_geometry.start_offset, - current_set.track_count); - set_geometry.last_indefinite_indices.emplace_back(last_indefinite_index); } - // If all of our tracks have a definite size upfront, we use - // |ComputeSetGeometry| which will apply alignment (if present). - return grid_properties.IsSpanningOnlyDefiniteTracks(track_direction) - ? ComputeSetGeometry(*track_collection) - : set_geometry; + LayoutUnit start_border_scrollbar_padding = + is_for_columns ? BorderScrollbarPadding().inline_start + : BorderScrollbarPadding().block_start; + + // If all of our tracks have a definite size upfront, we can use the current + // set sizes as the used track sizes (applying alignment, if present). + if (grid_properties.IsSpanningOnlyDefiniteTracks(track_direction)) { + sizing_collection->SetGutterSize(GutterSize(track_direction)); + auto first_set_geometry = + ComputeFirstSetGeometry(*sizing_collection, Style(), available_size, + start_border_scrollbar_padding); + sizing_collection->CacheSetsGeometry(first_set_geometry.start_offset, + first_set_geometry.gutter_size); + } else { + sizing_collection->InitializeSetsGeometry(start_border_scrollbar_padding, + GutterSize(track_direction)); + } } +namespace { + +struct BlockSizeDependentGridItem { + const GridItemData* item_data; + LayoutUnit cached_block_size; +}; + +Vector<BlockSizeDependentGridItem> BlockSizeDependentGridItems( + const GridItems& grid_items, + const NGGridSizingTrackCollection& track_collection) { + DCHECK_EQ(track_collection.Direction(), kForRows); + + Vector<BlockSizeDependentGridItem> dependent_items; + dependent_items.ReserveInitialCapacity(grid_items.Size()); + + for (const auto& grid_item : grid_items.item_data) { + if (!grid_item.is_sizing_dependent_on_block_size) + continue; + + const auto& set_indices = grid_item.SetIndices(kForRows); + BlockSizeDependentGridItem dependent_item = { + &grid_item, track_collection.ComputeSetSpanSize(set_indices.begin, + set_indices.end)}; + dependent_items.emplace_back(std::move(dependent_item)); + } + + dependent_items.ShrinkToFit(); + return dependent_items; +} + +bool MayChangeBlockSizeDependentGridItemContributions( + const Vector<BlockSizeDependentGridItem>& dependent_items, + const NGGridSizingTrackCollection& track_collection) { + DCHECK_EQ(track_collection.Direction(), kForRows); + + for (const auto& grid_item : dependent_items) { + const auto& set_indices = grid_item.item_data->SetIndices(kForRows); + const LayoutUnit block_size = + track_collection.ComputeSetSpanSize(set_indices.begin, set_indices.end); + + DCHECK_NE(block_size, kIndefiniteSize); + if (block_size != grid_item.cached_block_size) + return true; + } + return false; +} + +} // namespace + // https://drafts.csswg.org/css-grid-2/#algo-track-sizing -SetGeometry NGGridLayoutAlgorithm::ComputeUsedTrackSizes( +void NGGridLayoutAlgorithm::ComputeUsedTrackSizes( + const NGGridLayoutData& layout_data, const NGGridProperties& grid_properties, const SizingConstraint sizing_constraint, - NGGridSizingTrackCollection* track_collection, - NGGridGeometry* grid_geometry, GridItems* grid_items, + NGGridLayoutTrackCollection* track_collection, bool* needs_additional_pass) const { - DCHECK(track_collection && grid_geometry && grid_items); + DCHECK(grid_items && track_collection && track_collection->IsForSizing()); const auto track_direction = track_collection->Direction(); + const bool is_for_columns = track_direction == kForColumns; + + // We can skip the rest of the track sizing algorithm if all the sets in the + // collection have a definite size. + if (grid_properties.IsSpanningOnlyDefiniteTracks(track_direction)) + return; + + auto* sizing_collection = To<NGGridSizingTrackCollection>(track_collection); + sizing_collection->SetGutterSize(GutterSize(track_direction)); // Cache baselines, as these contributions can influence track sizing. if (grid_properties.HasBaseline(track_direction)) { - CalculateAlignmentBaselines(track_direction, sizing_constraint, - grid_geometry, grid_items, - needs_additional_pass); + CalculateAlignmentBaselines(layout_data, sizing_constraint, grid_items, + sizing_collection, needs_additional_pass); } // 2. Resolve intrinsic track sizing functions to absolute lengths. if (grid_properties.HasIntrinsicTrack(track_direction)) { - ResolveIntrinsicTrackSizes(*grid_geometry, sizing_constraint, - track_collection, grid_items); + ResolveIntrinsicTrackSizes(layout_data, sizing_constraint, + sizing_collection, grid_items); } // If any track still has an infinite growth limit (i.e. it had no items // placed in it), set its growth limit to its base size before maximizing. - track_collection->SetAllGrowthLimitsToBaseSize(); + sizing_collection->SetIndefiniteGrowthLimitsToBaseSize(); // 3. If the free space is positive, distribute it equally to the base sizes // of all tracks, freezing tracks as they reach their growth limits (and // continuing to grow the unfrozen tracks as needed). - MaximizeTracks(sizing_constraint, track_collection); + MaximizeTracks(sizing_constraint, sizing_collection); // 4. This step sizes flexible tracks using the largest value it can assign to // an 'fr' without exceeding the available space. if (grid_properties.HasFlexibleTrack(track_direction)) { - ExpandFlexibleTracks(*grid_geometry, sizing_constraint, track_collection, + ExpandFlexibleTracks(layout_data, sizing_constraint, sizing_collection, grid_items); } // 5. Stretch tracks with an 'auto' max track sizing function. - StretchAutoTracks(sizing_constraint, track_collection); + StretchAutoTracks(sizing_constraint, sizing_collection); - return ComputeSetGeometry(*track_collection); + // After computing row sizes, if we're still trying to determine whether we + // need to perform and additional pass, check if there is a grid item whose + // contributions relied on the available block size and may be changed. + const bool needs_to_check_block_size_dependent_grid_items = + !is_for_columns && needs_additional_pass && !(*needs_additional_pass); + + Vector<BlockSizeDependentGridItem> block_size_dependent_grid_items; + if (needs_to_check_block_size_dependent_grid_items) { + block_size_dependent_grid_items = + BlockSizeDependentGridItems(*grid_items, *sizing_collection); + } + + auto first_set_geometry = ComputeFirstSetGeometry( + *sizing_collection, Style(), + is_for_columns ? grid_available_size_.inline_size + : grid_available_size_.block_size, + is_for_columns ? BorderScrollbarPadding().inline_start + : BorderScrollbarPadding().block_start); + + sizing_collection->CacheSetsGeometry(first_set_geometry.start_offset, + first_set_geometry.gutter_size); + + if (needs_to_check_block_size_dependent_grid_items) { + *needs_additional_pass = MayChangeBlockSizeDependentGridItemContributions( + block_size_dependent_grid_items, *sizing_collection); + } } // Helpers for the track sizing algorithm. @@ -2060,7 +2137,7 @@ void NGGridLayoutAlgorithm::IncreaseTrackSizesToAccommodateGridItems( GridItems::Iterator group_begin, GridItems::Iterator group_end, - const NGGridGeometry& grid_geometry, + const NGGridLayoutData& layout_data, const bool is_group_spanning_flex_track, const SizingConstraint sizing_constraint, const GridItemContributionType contribution_type, @@ -2088,8 +2165,8 @@ sets_to_grow.Shrink(0); sets_to_grow_beyond_limit.Shrink(0); - LayoutUnit spanned_tracks_size = - GridGap(track_direction) * (grid_item.SpanSize(track_direction) - 1); + LayoutUnit spanned_tracks_size = track_collection->GutterSize() * + (grid_item.SpanSize(track_direction) - 1); ClampedDouble flex_factor_sum = 0; for (auto set_iterator = @@ -2128,7 +2205,7 @@ // remaining size contribution. For infinite growth limits, substitute with // the track's base size. This is the space to distribute, floor it at zero. LayoutUnit extra_space = ContributionSizeForGridItem( - grid_geometry, sizing_constraint, track_direction, contribution_type, + layout_data, sizing_constraint, track_direction, contribution_type, &grid_item); extra_space = (extra_space - spanned_tracks_size).ClampNegativeToZero(); @@ -2173,7 +2250,7 @@ // https://drafts.csswg.org/css-grid-2/#algo-content void NGGridLayoutAlgorithm::ResolveIntrinsicTrackSizes( - const NGGridGeometry& grid_geometry, + const NGGridLayoutData& layout_data, const SizingConstraint sizing_constraint, NGGridSizingTrackCollection* track_collection, GridItems* grid_items) const { @@ -2219,23 +2296,23 @@ current_group_span_size); IncreaseTrackSizesToAccommodateGridItems( - current_group_begin, current_group_end, grid_geometry, + current_group_begin, current_group_end, layout_data, /* is_group_spanning_flex_track */ false, sizing_constraint, GridItemContributionType::kForIntrinsicMinimums, track_collection); IncreaseTrackSizesToAccommodateGridItems( - current_group_begin, current_group_end, grid_geometry, + current_group_begin, current_group_end, layout_data, /* is_group_spanning_flex_track */ false, sizing_constraint, GridItemContributionType::kForContentBasedMinimums, track_collection); IncreaseTrackSizesToAccommodateGridItems( - current_group_begin, current_group_end, grid_geometry, + current_group_begin, current_group_end, layout_data, /* is_group_spanning_flex_track */ false, sizing_constraint, GridItemContributionType::kForMaxContentMinimums, track_collection); IncreaseTrackSizesToAccommodateGridItems( - current_group_begin, current_group_end, grid_geometry, + current_group_begin, current_group_end, layout_data, /* is_group_spanning_flex_track */ false, sizing_constraint, GridItemContributionType::kForIntrinsicMaximums, track_collection); IncreaseTrackSizesToAccommodateGridItems( - current_group_begin, current_group_end, grid_geometry, + current_group_begin, current_group_end, layout_data, /* is_group_spanning_flex_track */ false, sizing_constraint, GridItemContributionType::kForMaxContentMaximums, track_collection); @@ -2259,43 +2336,20 @@ // We can safely skip contributions for maximums since a <flex> definition // does not have an intrinsic max track sizing function. IncreaseTrackSizesToAccommodateGridItems( - current_group_begin, grid_items->end(), grid_geometry, + current_group_begin, grid_items->end(), layout_data, /* is_group_spanning_flex_track */ true, sizing_constraint, GridItemContributionType::kForIntrinsicMinimums, track_collection); IncreaseTrackSizesToAccommodateGridItems( - current_group_begin, grid_items->end(), grid_geometry, + current_group_begin, grid_items->end(), layout_data, /* is_group_spanning_flex_track */ true, sizing_constraint, GridItemContributionType::kForContentBasedMinimums, track_collection); IncreaseTrackSizesToAccommodateGridItems( - current_group_begin, grid_items->end(), grid_geometry, + current_group_begin, grid_items->end(), layout_data, /* is_group_spanning_flex_track */ true, sizing_constraint, GridItemContributionType::kForMaxContentMinimums, track_collection); } } -namespace { - -void GrowSetsByItemIncurredIncrease(GridSetVector* sets_to_grow) { - for (auto* set : *sets_to_grow) - set->IncreaseBaseSize(set->BaseSize() + set->item_incurred_increase); -} - -LayoutUnit ComputeTotalTrackSize( - const NGGridSizingTrackCollection& track_collection, - const LayoutUnit grid_gap) { - LayoutUnit total_track_size; - for (auto set_iterator = track_collection.GetConstSetIterator(); - !set_iterator.IsAtEnd(); set_iterator.MoveToNextSet()) { - const auto& set = set_iterator.CurrentSet(); - total_track_size += set.BaseSize() + set.track_count * grid_gap; - } - // Clamp to zero to avoid a negative |grid_gap| when there are no tracks. - total_track_size -= grid_gap; - return total_track_size.ClampNegativeToZero(); -} - -} // namespace - // https://drafts.csswg.org/css-grid-2/#algo-grow-tracks void NGGridLayoutAlgorithm::MaximizeTracks( const SizingConstraint sizing_constraint, @@ -2306,7 +2360,7 @@ return; GridSetVector sets_to_grow; - sets_to_grow.ReserveInitialCapacity(track_collection->SetCount()); + sets_to_grow.ReserveInitialCapacity(track_collection->GetSetCount()); for (auto set_iterator = track_collection->GetSetIterator(); !set_iterator.IsAtEnd(); set_iterator.MoveToNextSet()) { sets_to_grow.push_back(&set_iterator.CurrentSet()); @@ -2314,7 +2368,9 @@ DistributeExtraSpaceToSetsEqually( free_space, GridItemContributionType::kForFreeSpace, &sets_to_grow); - GrowSetsByItemIncurredIncrease(&sets_to_grow); + + for (auto* set : sets_to_grow) + set->IncreaseBaseSize(set->BaseSize() + set->item_incurred_increase); // TODO(ethavar): If this would cause the grid to be larger than the grid // container’s inner size as limited by its 'max-width/height', then redo this @@ -2365,9 +2421,9 @@ free_space = (track_direction == kForColumns) ? grid_min_available_size_.inline_size : grid_min_available_size_.block_size; + DCHECK_NE(free_space, kIndefiniteSize); - free_space -= - ComputeTotalTrackSize(*track_collection, GridGap(track_direction)); + free_space -= track_collection->TotalTrackSize(); } if (free_space <= 0) @@ -2376,12 +2432,13 @@ DistributeExtraSpaceToSetsEqually(free_space, GridItemContributionType::kForFreeSpace, &sets_to_grow, &sets_to_grow); - GrowSetsByItemIncurredIncrease(&sets_to_grow); + for (auto* set : sets_to_grow) + set->IncreaseBaseSize(set->BaseSize() + set->item_incurred_increase); } // https://drafts.csswg.org/css-grid-2/#algo-flex-tracks void NGGridLayoutAlgorithm::ExpandFlexibleTracks( - const NGGridGeometry& grid_geometry, + const NGGridLayoutData& layout_data, const SizingConstraint sizing_constraint, NGGridSizingTrackCollection* track_collection, GridItems* grid_items) const { @@ -2394,10 +2451,8 @@ if (!free_space) return; + const auto gutter_size = track_collection->GutterSize(); const auto track_direction = track_collection->Direction(); - const LayoutUnit gutter_size = (track_direction == kForColumns) - ? grid_geometry.column_geometry.gutter_size - : grid_geometry.row_geometry.gutter_size; // https://drafts.csswg.org/css-grid-2/#algo-find-fr-size GridSetVector flexible_sets; @@ -2513,7 +2568,7 @@ double grid_item_fr_size = FindFrSize( GetSetIteratorForItem(grid_item, *track_collection), ContributionSizeForGridItem( - grid_geometry, sizing_constraint, track_direction, + layout_data, sizing_constraint, track_direction, GridItemContributionType::kForMaxContentMaximums, &grid_item)); fr_size = std::max(grid_item_fr_size, fr_size); } @@ -2568,165 +2623,19 @@ // inner size when it’s sized to its min-width/height (max-width/height). } -namespace { - -TrackGeometry ComputeFirstTrackInCollectionGeometry( - const ComputedStyle& style, - const StyleContentAlignmentData& content_alignment, - const NGGridSizingTrackCollection& track_collection, - LayoutUnit available_size, - LayoutUnit start_border_scrollbar_padding, - LayoutUnit grid_gap) { - const OverflowAlignment overflow = content_alignment.Overflow(); - // Determining the free-space is typically unnecessary, i.e. if there is - // default alignment. Only compute this on-demand. - auto FreeSpace = [&]() -> LayoutUnit { - LayoutUnit free_space = - available_size - ComputeTotalTrackSize(track_collection, grid_gap); - // If overflow is 'safe', we have to make sure we don't overflow the - // 'start' edge (potentially cause some data loss as the overflow is - // unreachable). - return (overflow == OverflowAlignment::kSafe) - ? free_space.ClampNegativeToZero() - : free_space; - }; - // The default alignment, perform adjustments on top of this. - TrackGeometry geometry = {start_border_scrollbar_padding, grid_gap}; - - // If we have an indefinite |available_size| we can't perform any alignment, - // just return the default alignment. - if (available_size == kIndefiniteSize) - return geometry; - - // TODO(ikilpatrick): 'space-between', 'space-around', and 'space-evenly' all - // divide by the free-space, and may have a non-zero modulo. Investigate if - // this should be distributed between the tracks. - switch (content_alignment.Distribution()) { - case ContentDistributionType::kSpaceBetween: { - // Default behavior for 'space-between' is to start align content. - const wtf_size_t track_count = track_collection.NonCollapsedTrackCount(); - const LayoutUnit free_space = FreeSpace(); - if (track_count < 2 || free_space < LayoutUnit()) - return geometry; - - geometry.gutter_size += free_space / (track_count - 1); - return geometry; - } - case ContentDistributionType::kSpaceAround: { - // Default behavior for 'space-around' is to center content. - const wtf_size_t track_count = track_collection.NonCollapsedTrackCount(); - const LayoutUnit free_space = FreeSpace(); - if (track_count < 1 || free_space < LayoutUnit()) { - geometry.start_offset += free_space / 2; - return geometry; - } - - LayoutUnit track_space = free_space / track_count; - geometry.start_offset += track_space / 2; - geometry.gutter_size += track_space; - return geometry; - } - case ContentDistributionType::kSpaceEvenly: { - // Default behavior for 'space-evenly' is to center content. - const wtf_size_t track_count = track_collection.NonCollapsedTrackCount(); - const LayoutUnit free_space = FreeSpace(); - if (free_space < LayoutUnit()) { - geometry.start_offset += free_space / 2; - return geometry; - } - - LayoutUnit track_space = free_space / (track_count + 1); - geometry.start_offset += track_space; - geometry.gutter_size += track_space; - return geometry; - } - case ContentDistributionType::kStretch: - case ContentDistributionType::kDefault: - break; - } - - switch (content_alignment.GetPosition()) { - case ContentPosition::kLeft: { - DCHECK_EQ(track_collection.Direction(), kForColumns); - if (IsLtr(style.Direction())) - return geometry; - - geometry.start_offset += FreeSpace(); - return geometry; - } - case ContentPosition::kRight: { - DCHECK_EQ(track_collection.Direction(), kForColumns); - if (IsRtl(style.Direction())) - return geometry; - - geometry.start_offset += FreeSpace(); - return geometry; - } - case ContentPosition::kCenter: { - geometry.start_offset += FreeSpace() / 2; - return geometry; - } - case ContentPosition::kEnd: - case ContentPosition::kFlexEnd: { - geometry.start_offset += FreeSpace(); - return geometry; - } - case ContentPosition::kStart: - case ContentPosition::kFlexStart: - case ContentPosition::kNormal: - case ContentPosition::kBaseline: - case ContentPosition::kLastBaseline: - return geometry; - } -} - -} // namespace - -// Calculates the offsets for all sets. -SetGeometry NGGridLayoutAlgorithm::ComputeSetGeometry( - const NGGridSizingTrackCollection& track_collection) const { - const bool is_for_columns = track_collection.Direction() == kForColumns; - - const LayoutUnit available_size = is_for_columns - ? grid_available_size_.inline_size - : grid_available_size_.block_size; - TrackGeometry track_geometry = - is_for_columns - ? ComputeFirstTrackInCollectionGeometry( - Style(), Style().JustifyContent(), track_collection, - available_size, BorderScrollbarPadding().inline_start, - GridGap(kForColumns)) - : ComputeFirstTrackInCollectionGeometry( - Style(), Style().AlignContent(), track_collection, - available_size, BorderScrollbarPadding().block_start, - GridGap(kForRows)); - - SetGeometry set_geometry(track_geometry, track_collection.SetCount() + 1); - for (auto set_iterator = track_collection.GetConstSetIterator(); - !set_iterator.IsAtEnd(); set_iterator.MoveToNextSet()) { - const auto& set = set_iterator.CurrentSet(); - track_geometry.start_offset += - set.BaseSize() + set.track_count * set_geometry.gutter_size; - set_geometry.sets.emplace_back(track_geometry.start_offset, - set.track_count); - } - return set_geometry; -} - -LayoutUnit NGGridLayoutAlgorithm::GridGap( +LayoutUnit NGGridLayoutAlgorithm::GutterSize( const GridTrackSizingDirection track_direction) const { - const absl::optional<Length>& gap = - (track_direction == kForColumns) ? Style().ColumnGap() : Style().RowGap(); + const bool is_for_columns = track_direction == kForColumns; + const auto& gutter_size = + is_for_columns ? Style().ColumnGap() : Style().RowGap(); - if (!gap) + if (!gutter_size) return LayoutUnit(); - LayoutUnit available_size = - ((track_direction == kForColumns) ? grid_available_size_.inline_size - : grid_available_size_.block_size) - .ClampIndefiniteToZero(); - - return MinimumValueForLength(*gap, available_size); + LayoutUnit available_size = (is_for_columns ? grid_available_size_.inline_size + : grid_available_size_.block_size) + .ClampIndefiniteToZero(); + return MinimumValueForLength(*gutter_size, available_size); } // TODO(ikilpatrick): Determine if other uses of this method need to respect @@ -2746,12 +2655,12 @@ LayoutUnit free_space = (track_direction == kForColumns) ? grid_available_size_.inline_size : grid_available_size_.block_size; + if (free_space != kIndefiniteSize) { - free_space -= - ComputeTotalTrackSize(track_collection, GridGap(track_direction)); // If tracks consume more space than the grid container has available, // clamp the free space to zero as there's no more room left to grow. - free_space = free_space.ClampNegativeToZero(); + free_space = (free_space - track_collection.TotalTrackSize()) + .ClampNegativeToZero(); } return free_space; } @@ -2876,18 +2785,19 @@ } const NGConstraintSpace NGGridLayoutAlgorithm::CreateConstraintSpaceForLayout( - const NGGridGeometry& grid_geometry, + const NGGridLayoutData& layout_data, const GridItemData& grid_item, LogicalRect* containing_grid_area, absl::optional<LayoutUnit> opt_fragment_relative_block_offset, bool opt_min_block_size_should_encompass_intrinsic_size) const { - ComputeGridItemOffsetAndSize(grid_item, grid_geometry.column_geometry, - kForColumns, + ComputeGridItemOffsetAndSize(grid_item, layout_data.columns, &containing_grid_area->offset.inline_offset, &containing_grid_area->size.inline_size); - ComputeGridItemOffsetAndSize(grid_item, grid_geometry.row_geometry, kForRows, + + ComputeGridItemOffsetAndSize(grid_item, layout_data.rows, &containing_grid_area->offset.block_offset, &containing_grid_area->size.block_size); + return CreateConstraintSpace( grid_item, containing_grid_area->size, NGCacheSlot::kLayout, /* opt_fixed_block_size */ absl::nullopt, @@ -2897,19 +2807,19 @@ const NGConstraintSpace NGGridLayoutAlgorithm::CreateConstraintSpaceForMeasure( const GridItemData& grid_item, - const NGGridGeometry& grid_geometry, + const NGGridLayoutData& layout_data, const GridTrackSizingDirection track_direction, absl::optional<LayoutUnit> opt_fixed_block_size) const { LogicalOffset unused_offset; LogicalSize containing_grid_area_size(kIndefiniteSize, kIndefiniteSize); if (track_direction == kForColumns) { - ComputeGridItemOffsetAndSize(grid_item, grid_geometry.row_geometry, - kForRows, &unused_offset.block_offset, + ComputeGridItemOffsetAndSize(grid_item, layout_data.rows, + &unused_offset.block_offset, &containing_grid_area_size.block_size); } else { - ComputeGridItemOffsetAndSize(grid_item, grid_geometry.column_geometry, - kForColumns, &unused_offset.inline_offset, + ComputeGridItemOffsetAndSize(grid_item, layout_data.columns, + &unused_offset.inline_offset, &containing_grid_area_size.inline_size); } return CreateConstraintSpace(grid_item, containing_grid_area_size, @@ -2980,27 +2890,28 @@ void NGGridLayoutAlgorithm::PlaceGridItems( const GridItems& grid_items, - const NGGridGeometry& grid_geometry, + const NGGridLayoutData& layout_data, Vector<EBreakBetween>* out_row_break_between, Vector<GridItemPlacementData>* out_grid_items_placement_data) { DCHECK(out_row_break_between); + const auto& container_space = ConstraintSpace(); const auto container_writing_direction = container_space.GetWritingDirection(); bool should_propagate_child_break_values = - ConstraintSpace().ShouldPropagateChildBreakValues(); + container_space.ShouldPropagateChildBreakValues(); if (should_propagate_child_break_values) { *out_row_break_between = Vector<EBreakBetween>( - grid_geometry.row_geometry.sets.size(), EBreakBetween::kAuto); + layout_data.rows.GetSetCount() + 1, EBreakBetween::kAuto); } BaselineAccumulator baseline_accumulator; for (const auto& grid_item : grid_items.item_data) { LogicalRect containing_grid_area; - const NGConstraintSpace space = CreateConstraintSpaceForLayout( - grid_geometry, grid_item, &containing_grid_area); + const auto space = CreateConstraintSpaceForLayout(layout_data, grid_item, + &containing_grid_area); const auto& item_style = grid_item.node.Style(); const auto margins = ComputeMarginsFor(space, item_style, container_space); @@ -3018,9 +2929,10 @@ // baseline and its track baseline. const LayoutUnit item_baseline = GetLogicalBaseline( logical_fragment, track_direction, - ConstraintSpace().GetWritingDirection().GetWritingMode()); - LayoutUnit track_baseline = - Baseline(grid_geometry, grid_item, track_direction); + container_space.GetWritingDirection().GetWritingMode()); + const LayoutUnit track_baseline = + Baseline(layout_data, grid_item, track_direction); + return (track_baseline != LayoutUnit::Min()) ? (track_baseline - item_baseline) : item_baseline; @@ -3114,11 +3026,11 @@ void NGGridLayoutAlgorithm::PlaceGridItemsForFragmentation( const GridItems& grid_items, const Vector<EBreakBetween>& row_break_between, - NGGridGeometry* grid_geometry, + NGGridLayoutData* layout_data, Vector<GridItemPlacementData>* grid_items_placement_data, Vector<LayoutUnit>* row_offset_adjustments, LayoutUnit* intrinsic_block_size) { - DCHECK(grid_geometry && grid_items_placement_data && row_offset_adjustments && + DCHECK(layout_data && grid_items_placement_data && row_offset_adjustments && intrinsic_block_size); // TODO(ikilpatrick): Update SetHasSeenAllChildren and early exit if true. @@ -3225,7 +3137,7 @@ .has_descendant_that_depends_on_percentage_block_size); LogicalRect grid_area; const auto space = CreateConstraintSpaceForLayout( - *grid_geometry, grid_item, &grid_area, fragment_relative_block_offset, + *layout_data, grid_item, &grid_area, fragment_relative_block_offset, min_block_size_should_encompass_intrinsic_size); // Make the grid area relative to this fragment. @@ -3313,10 +3225,9 @@ if (IsAvoidBreakValue(ConstraintSpace(), break_between)) { for (int index = item_row_set_index - 1; index >= 0; --index) { // Only consider rows within this fragmentainer. - LayoutUnit offset = - grid_geometry->row_geometry.sets[index].offset + - (*row_offset_adjustments)[index] - - previous_consumed_block_size; + LayoutUnit offset = layout_data->rows.GetSetOffset(index) + + (*row_offset_adjustments)[index] - + previous_consumed_block_size; if (offset <= LayoutUnit()) break; @@ -3369,33 +3280,30 @@ } }; - // This will adjust the pre-computed item-offset (for all items starting at - // |row_index| and below) by |delta|. + // Adjust by |delta| the pre-computed item-offset for all grid items with a + // row begin index greater or equal than |row_index|. auto AdjustItemOffsets = [&](wtf_size_t row_index, LayoutUnit delta) { - auto* items_it = grid_items.item_data.begin(); + const auto* current_item = grid_items.item_data.begin(); + for (auto& item_placement_data : *grid_items_placement_data) { - if ((items_it++)->SetIndices(kForRows).begin < row_index) - continue; - item_placement_data.offset.block_offset += delta; + if (row_index <= (current_item++)->SetIndices(kForRows).begin) + item_placement_data.offset.block_offset += delta; } }; // Adjust our grid break-token data to accommodate the larger item in the row. // Returns true if this function adjusted the break-token data in any way. auto ExpandRow = [&]() -> bool { - if (max_row_expansion == LayoutUnit()) + if (max_row_expansion == 0) return false; - DCHECK_GT(max_row_expansion, LayoutUnit()); + + DCHECK_GT(max_row_expansion, 0); DCHECK(IsExpansionMakingProgress(expansion_row_set_index)); *intrinsic_block_size += max_row_expansion; AdjustItemOffsets(expansion_row_set_index + 1, max_row_expansion); - - // Expand the positions of all the sets by the increase. - auto* it = - grid_geometry->row_geometry.sets.begin() + expansion_row_set_index + 1; - while (it != grid_geometry->row_geometry.sets.end()) - (it++)->offset += max_row_expansion; + layout_data->rows.AdjustSetOffsets(expansion_row_set_index + 1, + max_row_expansion); previous_expansion_row_set_index = expansion_row_set_index; return true; @@ -3409,7 +3317,7 @@ return false; const LayoutUnit fragment_relative_row_offset = - grid_geometry->row_geometry.sets[breakpoint_row_set_index].offset + + layout_data->rows.GetSetOffset(breakpoint_row_set_index) + (*row_offset_adjustments)[breakpoint_row_set_index] - previous_consumed_block_size; @@ -3529,29 +3437,29 @@ namespace { Vector<std::div_t> ComputeTrackSizesInRange( - const SetGeometry& set_geometry, - const wtf_size_t range_starting_set_index, + const NGGridLayoutTrackCollection& track_collection, + const wtf_size_t range_begin_set_index, const wtf_size_t range_set_count) { Vector<std::div_t> track_sizes; track_sizes.ReserveInitialCapacity(range_set_count); - const wtf_size_t ending_set_index = - range_starting_set_index + range_set_count; - for (wtf_size_t set_index = range_starting_set_index; - set_index < ending_set_index; ++set_index) { + const wtf_size_t ending_set_index = range_begin_set_index + range_set_count; + for (wtf_size_t i = range_begin_set_index; i < ending_set_index; ++i) { // Set information is stored as offsets. To determine the size of a single // track in a givent set, first determine the total size the set takes up // by finding the difference between the offsets and subtracting the gutter // size for each track in the set. - const wtf_size_t set_track_count = - set_geometry.sets[set_index + 1].track_count; - DCHECK_GE(set_track_count, 1u); - LayoutUnit set_size = set_geometry.sets[set_index + 1].offset - - set_geometry.sets[set_index].offset - - set_geometry.gutter_size * set_track_count; + LayoutUnit set_size = + track_collection.GetSetOffset(i + 1) - track_collection.GetSetOffset(i); + const wtf_size_t set_track_count = track_collection.GetSetTrackCount(i); + + DCHECK_GE(set_size, 0); + set_size = (set_size - track_collection.GutterSize() * set_track_count) + .ClampNegativeToZero(); // Once we have determined the size of the set, we can find the size of a // given track by dividing the |set_size| by the |set_track_count|. + DCHECK_GT(set_track_count, 0u); track_sizes.emplace_back(std::div(set_size.RawValue(), set_track_count)); } return track_sizes; @@ -3559,17 +3467,18 @@ // For out of flow items that are located in the middle of a range, computes // the extra offset relative to the start of its containing range. -LayoutUnit ComputeTrackOffsetInRange(const SetGeometry& set_geometry, - const wtf_size_t range_starting_set_index, - const wtf_size_t range_set_count, - const wtf_size_t offset_in_range) { +LayoutUnit ComputeTrackOffsetInRange( + const NGGridLayoutTrackCollection& track_collection, + const wtf_size_t range_begin_set_index, + const wtf_size_t range_set_count, + const wtf_size_t offset_in_range) { if (!range_set_count || !offset_in_range) return LayoutUnit(); // To compute the index offset, we have to determine the size of the // tracks within the grid item's span. Vector<std::div_t> track_sizes = ComputeTrackSizesInRange( - set_geometry, range_starting_set_index, range_set_count); + track_collection, range_begin_set_index, range_set_count); // Calculate how many sets there are from the start of the range to the // |offset_in_range|. This division can produce a remainder, which would @@ -3579,26 +3488,24 @@ const wtf_size_t remaining_track_count = offset_in_range % range_set_count; // Iterate over the sets and add the sizes of the tracks to |index_offset|. - LayoutUnit index_offset = set_geometry.gutter_size * offset_in_range; - for (wtf_size_t track_index = 0; track_index < track_sizes.size(); - ++track_index) { + LayoutUnit index_offset = track_collection.GutterSize() * offset_in_range; + for (wtf_size_t i = 0; i < track_sizes.size(); ++i) { // If we have a remainder from the |floor_set_track_count|, we have to // consider it to get the correct offset. - int set_count = - floor_set_track_count + ((remaining_track_count > track_index) ? 1 : 0); - index_offset += LayoutUnit::FromRawValue( - (set_count * track_sizes[track_index].quot) + - std::min(set_count, track_sizes[track_index].rem)); + const wtf_size_t set_count = + floor_set_track_count + ((remaining_track_count > i) ? 1 : 0); + index_offset += + LayoutUnit::FromRawValue(std::min<int>(set_count, track_sizes[i].rem) + + (set_count * track_sizes[i].quot)); } return index_offset; } template <bool snap_to_end_of_track> -LayoutUnit TrackOffset(const NGGridSizingTrackCollection& track_collection, - const SetGeometry& set_geometry, +LayoutUnit TrackOffset(const NGGridLayoutTrackCollection& track_collection, const wtf_size_t range_index, const wtf_size_t offset_in_range) { - const wtf_size_t range_starting_set_index = + const wtf_size_t range_begin_set_index = track_collection.RangeBeginSetIndex(range_index); const wtf_size_t range_track_count = track_collection.RangeTrackCount(range_index); @@ -3609,15 +3516,16 @@ if (offset_in_range == range_track_count) { DCHECK(snap_to_end_of_track); track_offset = - set_geometry.sets[range_starting_set_index + range_set_count].offset; + track_collection.GetSetOffset(range_begin_set_index + range_set_count); } else { - DCHECK_LT(offset_in_range, range_track_count); DCHECK(offset_in_range || !snap_to_end_of_track); + DCHECK_LT(offset_in_range, range_track_count); + // If an out of flow item starts/ends in the middle of a range, compute and // add the extra offset to the start offset of the range. track_offset = - set_geometry.sets[range_starting_set_index].offset + - ComputeTrackOffsetInRange(set_geometry, range_starting_set_index, + track_collection.GetSetOffset(range_begin_set_index) + + ComputeTrackOffsetInRange(track_collection, range_begin_set_index, range_set_count, offset_in_range); } @@ -3626,12 +3534,11 @@ // However, only snap if this range is not collapsed or if it can snap to the // end of the last track in the previous range of the collection. if (snap_to_end_of_track && (range_set_count || range_index)) - track_offset -= set_geometry.gutter_size; + track_offset -= track_collection.GutterSize(); return track_offset; } -LayoutUnit TrackStartOffset(const NGGridSizingTrackCollection& track_collection, - const SetGeometry& set_geometry, +LayoutUnit TrackStartOffset(const NGGridLayoutTrackCollection& track_collection, const wtf_size_t range_index, const wtf_size_t offset_in_range) { if (!track_collection.RangeCount()) { @@ -3639,7 +3546,7 @@ // undefined grid, start offset is the start border scrollbar padding. DCHECK_EQ(range_index, 0u); DCHECK_EQ(offset_in_range, 0u); - return set_geometry.sets[0].offset; + return track_collection.GetSetOffset(0); } const wtf_size_t range_track_count = @@ -3651,16 +3558,15 @@ // tracks in the range is for the last range in the collection, which should // match the end line of the implicit grid; snap to the track end instead. return TrackOffset</* snap_to_end_of_track */ true>( - track_collection, set_geometry, range_index, offset_in_range); + track_collection, range_index, offset_in_range); } DCHECK_LT(offset_in_range, range_track_count); return TrackOffset</* snap_to_end_of_track */ false>( - track_collection, set_geometry, range_index, offset_in_range); + track_collection, range_index, offset_in_range); } -LayoutUnit TrackEndOffset(const NGGridSizingTrackCollection& track_collection, - const SetGeometry& set_geometry, +LayoutUnit TrackEndOffset(const NGGridLayoutTrackCollection& track_collection, const wtf_size_t range_index, const wtf_size_t offset_in_range) { if (!track_collection.RangeCount()) { @@ -3668,25 +3574,24 @@ // undefined grid, end offset is the start border scrollbar padding. DCHECK_EQ(range_index, 0u); DCHECK_EQ(offset_in_range, 0u); - return set_geometry.sets[0].offset; + return track_collection.GetSetOffset(0); } if (!offset_in_range && !range_index) { // Only allow the offset to be 0 for the first range in the collection, // which is the start line of the implicit grid; don't snap to the end. return TrackOffset</* snap_to_end_of_track */ false>( - track_collection, set_geometry, range_index, offset_in_range); + track_collection, range_index, offset_in_range); } DCHECK_GT(offset_in_range, 0u); return TrackOffset</* snap_to_end_of_track */ true>( - track_collection, set_geometry, range_index, offset_in_range); + track_collection, range_index, offset_in_range); } void ComputeOutOfFlowOffsetAndSize( const GridItemData& out_of_flow_item, - const SetGeometry& set_geometry, - const NGGridSizingTrackCollection& track_collection, + const NGGridLayoutTrackCollection& track_collection, const NGBoxStrut& borders, const LogicalSize& border_box_size, LayoutUnit* start_offset, @@ -3712,9 +3617,9 @@ if (item_placement.range_index.begin != kNotFound) { DCHECK_NE(item_placement.offset_in_range.begin, kNotFound); - *start_offset = TrackStartOffset(track_collection, set_geometry, - item_placement.range_index.begin, - item_placement.offset_in_range.begin); + *start_offset = + TrackStartOffset(track_collection, item_placement.range_index.begin, + item_placement.offset_in_range.begin); } // If the end line is defined, the offset (which can be the offset at the @@ -3723,14 +3628,11 @@ if (item_placement.range_index.end != kNotFound) { DCHECK_NE(item_placement.offset_in_range.end, kNotFound); - end_offset = TrackEndOffset(track_collection, set_geometry, - item_placement.range_index.end, - item_placement.offset_in_range.end); + end_offset = + TrackEndOffset(track_collection, item_placement.range_index.end, + item_placement.offset_in_range.end); *size = end_offset - *start_offset; } else { - // By the time we call this method, we shouldn't have indefinite tracks. - DCHECK(set_geometry.last_indefinite_indices.IsEmpty()); - // |start_offset| can be greater than |end_offset| if the track sizes from // the grid overflow the container's respective size. *size = (end_offset - *start_offset).ClampNegativeToZero(); @@ -3742,35 +3644,18 @@ void NGGridLayoutAlgorithm::ComputeGridItemOffsetAndSize( const GridItemData& grid_item, - const SetGeometry& set_geometry, - const GridTrackSizingDirection track_direction, + const NGGridLayoutTrackCollection& track_collection, LayoutUnit* start_offset, LayoutUnit* size) const { DCHECK(start_offset && size && !grid_item.IsOutOfFlow()); - const auto& set_indices = grid_item.SetIndices(track_direction); - DCHECK_LT(set_indices.end, set_geometry.sets.size()); - DCHECK_LT(set_indices.begin, set_indices.end); + const auto& set_indices = grid_item.SetIndices(track_collection.Direction()); + *start_offset = track_collection.GetSetOffset(set_indices.begin); + *size = + track_collection.ComputeSetSpanSize(set_indices.begin, set_indices.end); - *start_offset = set_geometry.sets[set_indices.begin].offset; - *size = kIndefiniteSize; - - // If we are measuring a grid item we might not yet have determined the final - // used sizes for all sets; |last_indefinite_index| is the last set which has - // an indefinite used size, if |set_indices.begin| is greater, then all the - // sets between it and |set_indices.end| are definite. - const wtf_size_t last_indefinite_index = - set_geometry.last_indefinite_indices.IsEmpty() - ? kNotFound - : set_geometry.last_indefinite_indices[set_indices.end]; - if (last_indefinite_index == kNotFound || - set_indices.begin > last_indefinite_index) { - *size = ComputeSetSpanSize(set_geometry, set_indices); - if (size->MightBeSaturated()) - *size = LayoutUnit(); - } - DCHECK(!size->MightBeSaturated()); - DCHECK(*size >= 0 || *size == kIndefiniteSize); + if (size->MightBeSaturated()) + *size = LayoutUnit(); } // static @@ -3782,31 +3667,20 @@ GridItemData* out_of_flow_item) { DCHECK(out_of_flow_item && out_of_flow_item->IsOutOfFlow()); - NGGridSizingTrackCollection column_track_collection( - layout_data.column_geometry.ranges, kForColumns); - NGGridSizingTrackCollection row_track_collection( - layout_data.row_geometry.ranges, kForRows); - - out_of_flow_item->ComputeOutOfFlowItemPlacement(column_track_collection, + out_of_flow_item->ComputeOutOfFlowItemPlacement(layout_data.columns, grid_placement); - out_of_flow_item->ComputeOutOfFlowItemPlacement(row_track_collection, + out_of_flow_item->ComputeOutOfFlowItemPlacement(layout_data.rows, grid_placement); - SetGeometry column_geometry(layout_data.column_geometry.sets, - layout_data.column_geometry.gutter_size); - SetGeometry row_geometry(layout_data.row_geometry.sets, - layout_data.row_geometry.gutter_size); - LogicalRect containing_rect; - ComputeOutOfFlowOffsetAndSize( - *out_of_flow_item, column_geometry, column_track_collection, borders, - border_box_size, &containing_rect.offset.inline_offset, - &containing_rect.size.inline_size); - ComputeOutOfFlowOffsetAndSize(*out_of_flow_item, row_geometry, - row_track_collection, borders, border_box_size, - &containing_rect.offset.block_offset, - &containing_rect.size.block_size); + ComputeOutOfFlowOffsetAndSize( + *out_of_flow_item, layout_data.columns, borders, border_box_size, + &containing_rect.offset.inline_offset, &containing_rect.size.inline_size); + + ComputeOutOfFlowOffsetAndSize( + *out_of_flow_item, layout_data.rows, borders, border_box_size, + &containing_rect.offset.block_offset, &containing_rect.size.block_size); return containing_rect; }
diff --git a/third_party/blink/renderer/core/layout/ng/grid/ng_grid_layout_algorithm.h b/third_party/blink/renderer/core/layout/ng/grid/ng_grid_layout_algorithm.h index cc9ea0cd..c45bbfc 100644 --- a/third_party/blink/renderer/core/layout/ng/grid/ng_grid_layout_algorithm.h +++ b/third_party/blink/renderer/core/layout/ng/grid/ng_grid_layout_algorithm.h
@@ -6,7 +6,7 @@ #define THIRD_PARTY_BLINK_RENDERER_CORE_LAYOUT_NG_GRID_NG_GRID_LAYOUT_ALGORITHM_H_ #include "third_party/blink/renderer/core/layout/ng/grid/ng_grid_break_token_data.h" -#include "third_party/blink/renderer/core/layout/ng/grid/ng_grid_geometry.h" +#include "third_party/blink/renderer/core/layout/ng/grid/ng_grid_data.h" #include "third_party/blink/renderer/core/layout/ng/grid/ng_grid_item.h" #include "third_party/blink/renderer/core/layout/ng/grid/ng_grid_node.h" #include "third_party/blink/renderer/core/layout/ng/grid/ng_grid_placement.h" @@ -53,7 +53,7 @@ // Helper that computes tracks sizes in a given range. static Vector<std::div_t> ComputeTrackSizesInRange( - const SetGeometry& set_geometry, + const NGGridLayoutTrackCollection& track_collection, wtf_size_t range_starting_set_index, wtf_size_t range_set_count); @@ -62,24 +62,23 @@ const NGLayoutResult* LayoutInternal(); - LayoutUnit Baseline(const NGGridGeometry& grid_geometry, + LayoutUnit Baseline(const NGGridLayoutData& layout_data, const GridItemData& grid_item, const GridTrackSizingDirection track_direction) const; - NGGridGeometry ComputeGridGeometry( + void ComputeGridGeometry( const NGGridBlockTrackCollection& column_block_track_collection, const NGGridBlockTrackCollection& row_block_track_collection, GridItems* grid_items, - LayoutUnit* intrinsic_block_size, - NGGridSizingTrackCollection* column_track_collection, - NGGridSizingTrackCollection* row_track_collection); + NGGridLayoutData* layout_data, + LayoutUnit* intrinsic_block_size); LayoutUnit ComputeIntrinsicBlockSizeIgnoringChildren() const; // Returns the size that a grid item will distribute across the tracks with an // intrinsic sizing function it spans in the relevant track direction. LayoutUnit ContributionSizeForGridItem( - const NGGridGeometry& grid_geometry, + const NGGridLayoutData& layout_data, const SizingConstraint sizing_constraint, const GridTrackSizingDirection track_direction, const GridItemContributionType contribution_type, @@ -94,31 +93,30 @@ NGGridBlockTrackCollection* row_track_collection) const; // Determines the major/minor alignment baselines for each row/column based on - // each item in |grid_items|, and stores the results in |grid_geometry|. + // each item in |grid_items|, and stores the results in |track_collection|. void CalculateAlignmentBaselines( - const GridTrackSizingDirection track_direction, + const NGGridLayoutData& layout_data, const SizingConstraint sizing_constraint, - NGGridGeometry* grid_geometry, GridItems* grid_items, + NGGridLayoutTrackCollection* track_collection, bool* needs_additional_pass = nullptr) const; // Initializes the given track collection, and returns the base set geometry. - SetGeometry InitializeTrackSizes( + void InitializeTrackSizes( const NGGridProperties& grid_properties, - NGGridSizingTrackCollection* track_collection) const; + NGGridLayoutTrackCollection* track_collection) const; // Calculates from the min and max track sizing functions the used track size. - SetGeometry ComputeUsedTrackSizes( - const NGGridProperties& grid_properties, - const SizingConstraint sizing_constraint, - NGGridSizingTrackCollection* track_collection, - NGGridGeometry* grid_geometry, - GridItems* grid_items, - bool* needs_additional_pass = nullptr) const; + void ComputeUsedTrackSizes(const NGGridLayoutData& layout_data, + const NGGridProperties& grid_properties, + const SizingConstraint sizing_constraint, + GridItems* grid_items, + NGGridLayoutTrackCollection* track_collection, + bool* needs_additional_pass = nullptr) const; // These methods implement the steps of the algorithm for intrinsic track size // resolution defined in https://drafts.csswg.org/css-grid-2/#algo-content. - void ResolveIntrinsicTrackSizes(const NGGridGeometry& grid_geometry, + void ResolveIntrinsicTrackSizes(const NGGridLayoutData& layout_data, const SizingConstraint sizing_constraint, NGGridSizingTrackCollection* track_collection, GridItems* grid_items) const; @@ -126,7 +124,7 @@ void IncreaseTrackSizesToAccommodateGridItems( GridItems::Iterator group_begin, GridItems::Iterator group_end, - const NGGridGeometry& grid_geometry, + const NGGridLayoutData& layout_data, const bool is_group_spanning_flex_track, const SizingConstraint sizing_constraint, const GridItemContributionType contribution_type, @@ -138,16 +136,13 @@ void StretchAutoTracks(const SizingConstraint sizing_constraint, NGGridSizingTrackCollection* track_collection) const; - void ExpandFlexibleTracks(const NGGridGeometry& grid_geometry, + void ExpandFlexibleTracks(const NGGridLayoutData& layout_data, const SizingConstraint sizing_constraint, NGGridSizingTrackCollection* track_collection, GridItems* grid_items) const; - SetGeometry ComputeSetGeometry( - const NGGridSizingTrackCollection& track_collection) const; - - // Gets the row or column gap of the grid. - LayoutUnit GridGap(const GridTrackSizingDirection track_direction) const; + // Gets the specified [column|row]-gap of the grid. + LayoutUnit GutterSize(const GridTrackSizingDirection track_direction) const; LayoutUnit DetermineFreeSpace( SizingConstraint sizing_constraint, @@ -163,7 +158,7 @@ bool opt_min_block_size_should_encompass_intrinsic_size = false) const; const NGConstraintSpace CreateConstraintSpaceForLayout( - const NGGridGeometry& grid_geometry, + const NGGridLayoutData& layout_data, const GridItemData& grid_item, LogicalRect* containing_grid_area, absl::optional<LayoutUnit> opt_fragment_relative_block_offset = @@ -172,7 +167,7 @@ const NGConstraintSpace CreateConstraintSpaceForMeasure( const GridItemData& grid_item, - const NGGridGeometry& grid_geometry, + const NGGridLayoutData& layout_data, const GridTrackSizingDirection track_direction, absl::optional<LayoutUnit> opt_fixed_block_size = absl::nullopt) const; @@ -186,7 +181,7 @@ // of each item before fragmentation occurs. void PlaceGridItems( const GridItems& grid_items, - const NGGridGeometry& grid_geometry, + const NGGridLayoutData& layout_data, Vector<EBreakBetween>* out_row_break_between, Vector<GridItemPlacementData>* out_grid_items_placement_data = nullptr); @@ -198,7 +193,7 @@ void PlaceGridItemsForFragmentation( const GridItems& grid_items, const Vector<EBreakBetween>& row_break_between, - NGGridGeometry* grid_geometry, + NGGridLayoutData* layout_data, Vector<GridItemPlacementData>* grid_item_placement_data, Vector<LayoutUnit>* row_offset_adjustments, LayoutUnit* intrinsic_block_size); @@ -210,8 +205,7 @@ void ComputeGridItemOffsetAndSize( const GridItemData& grid_item, - const SetGeometry& set_geometry, - const GridTrackSizingDirection track_direction, + const NGGridLayoutTrackCollection& track_collection, LayoutUnit* start_offset, LayoutUnit* size) const;
diff --git a/third_party/blink/renderer/core/layout/ng/grid/ng_grid_layout_algorithm_test.cc b/third_party/blink/renderer/core/layout/ng/grid/ng_grid_layout_algorithm_test.cc index ea1a124..8b8a7fd 100644 --- a/third_party/blink/renderer/core/layout/ng/grid/ng_grid_layout_algorithm_test.cc +++ b/third_party/blink/renderer/core/layout/ng/grid/ng_grid_layout_algorithm_test.cc
@@ -59,24 +59,22 @@ &row_block_track_collection); LayoutUnit unused_intrinsic_block_size; - grid_geometry_ = algorithm.ComputeGridGeometry( + algorithm.ComputeGridGeometry( column_block_track_collection, row_block_track_collection, - &items_->grid_items_, &unused_intrinsic_block_size, - &column_track_collection_, &row_track_collection_); + &items_->grid_items_, &layout_data_, &unused_intrinsic_block_size); } NGGridSizingTrackCollection& TrackCollection( GridTrackSizingDirection track_direction) { - return (track_direction == kForColumns) ? column_track_collection_ - : row_track_collection_; + return (track_direction == kForColumns) ? layout_data_.columns + : layout_data_.rows; } LayoutUnit BaseRowSizeForChild(const NGGridLayoutAlgorithm& algorithm, wtf_size_t index) { LayoutUnit offset, size; algorithm.ComputeGridItemOffsetAndSize(items_->grid_items_.item_data[index], - grid_geometry_.row_geometry, - kForRows, &offset, &size); + layout_data_.rows, &offset, &size); return size; } @@ -162,16 +160,13 @@ } struct Items final : public GarbageCollected<Items> { - public: - GridItems grid_items_; - void Trace(Visitor* visitor) const { visitor->Trace(grid_items_); } + GridItems grid_items_; }; + Persistent<Items> items_ = MakeGarbageCollected<Items>(); - NGGridGeometry grid_geometry_; - NGGridSizingTrackCollection column_track_collection_; - NGGridSizingTrackCollection row_track_collection_; + NGGridLayoutData layout_data_; }; TEST_F(NGGridLayoutAlgorithmTest, NGGridLayoutAlgorithmBaseSetSizes) {
diff --git a/third_party/blink/renderer/core/layout/ng/grid/ng_grid_track_collection.cc b/third_party/blink/renderer/core/layout/ng/grid/ng_grid_track_collection.cc index 2d7d522c..15a2ba82 100644 --- a/third_party/blink/renderer/core/layout/ng/grid/ng_grid_track_collection.cc +++ b/third_party/blink/renderer/core/layout/ng/grid/ng_grid_track_collection.cc
@@ -499,6 +499,63 @@ return grid_line <= EndLineOfImplicitGrid(); } +wtf_size_t NGGridLayoutTrackCollection::GetSetCount() const { + if (ranges_.IsEmpty()) + return 0; + const auto& last_range = ranges_.back(); + return last_range.begin_set_index + last_range.set_count; +} + +LayoutUnit NGGridLayoutTrackCollection::GetSetOffset( + wtf_size_t set_index) const { + DCHECK_LT(set_index, sets_geometry_.size()); + return sets_geometry_[set_index].offset; +} + +wtf_size_t NGGridLayoutTrackCollection::GetSetTrackCount( + wtf_size_t set_index) const { + DCHECK_LT(set_index + 1, sets_geometry_.size()); + return sets_geometry_[set_index + 1].track_count; +} + +LayoutUnit NGGridLayoutTrackCollection::MajorBaseline( + wtf_size_t set_index) const { + DCHECK_LT(set_index, major_baselines_.size()); + return major_baselines_[set_index]; +} + +LayoutUnit NGGridLayoutTrackCollection::MinorBaseline( + wtf_size_t set_index) const { + DCHECK_LT(set_index, minor_baselines_.size()); + return minor_baselines_[set_index]; +} + +LayoutUnit NGGridLayoutTrackCollection::ComputeSetSpanSize() const { + return ComputeSetSpanSize(0, GetSetCount()); +} + +LayoutUnit NGGridLayoutTrackCollection::ComputeSetSpanSize( + wtf_size_t begin_set_index, + wtf_size_t end_set_index) const { + DCHECK_LE(begin_set_index, end_set_index); + DCHECK_LT(end_set_index, sets_geometry_.size()); + + if (begin_set_index == end_set_index) + return LayoutUnit(); + + if (IsSpanningIndefiniteSet(begin_set_index, end_set_index)) + return kIndefiniteSize; + + // The size of a set span is the end offset minus the gutter size and start + // offset. It is floored at zero so that the size is not negative when the + // gutter size is greater than the difference between the offsets. + auto set_span_size = sets_geometry_[end_set_index].offset - + sets_geometry_[begin_set_index].offset; + + DCHECK_GE(set_span_size, 0); + return (set_span_size - gutter_size_).ClampNegativeToZero(); +} + NGGridSizingTrackCollection::NGGridSizingTrackCollection( const NGGridBlockTrackCollection& block_track_collection, bool is_available_size_indefinite) @@ -511,14 +568,18 @@ : block_track_collection.ExplicitTracks(), is_available_size_indefinite); } + + const wtf_size_t set_count = sets_.size() + 1; + last_indefinite_indices_.ReserveInitialCapacity(set_count); + sets_geometry_.ReserveInitialCapacity(set_count); } -NGGridSet& NGGridSizingTrackCollection::SetAt(wtf_size_t set_index) { +NGGridSet& NGGridSizingTrackCollection::GetSetAt(wtf_size_t set_index) { DCHECK_LT(set_index, sets_.size()); return sets_[set_index]; } -const NGGridSet& NGGridSizingTrackCollection::SetAt( +const NGGridSet& NGGridSizingTrackCollection::GetSetAt( wtf_size_t set_index) const { DCHECK_LT(set_index, sets_.size()); return sets_[set_index]; @@ -540,15 +601,101 @@ return SetIterator(this, begin_set_index, end_set_index); } -void NGGridSizingTrackCollection::SetAllGrowthLimitsToBaseSize() { - for (auto set_iterator = GetSetIterator(); !set_iterator.IsAtEnd(); - set_iterator.MoveToNextSet()) { - auto& set = set_iterator.CurrentSet(); +bool NGGridSizingTrackCollection::IsSpanningIndefiniteSet( + wtf_size_t begin_set_index, + wtf_size_t end_set_index) const { + if (last_indefinite_indices_.IsEmpty()) + return false; + + DCHECK_LT(begin_set_index, end_set_index); + DCHECK_LT(end_set_index, last_indefinite_indices_.size()); + const wtf_size_t last_indefinite_index = + last_indefinite_indices_[end_set_index]; + + return last_indefinite_index != kNotFound && + begin_set_index <= last_indefinite_index; +} + +LayoutUnit NGGridSizingTrackCollection::TotalTrackSize() const { + if (sets_.IsEmpty()) + return LayoutUnit(); + + LayoutUnit total_track_size; + for (const auto& set : sets_) + total_track_size += set.BaseSize() + set.track_count * gutter_size_; + return total_track_size - gutter_size_; +} + +void NGGridSizingTrackCollection::InitializeSetsGeometry( + LayoutUnit first_set_offset, + LayoutUnit gutter_size) { + last_indefinite_indices_.Shrink(0); + sets_geometry_.Shrink(0); + + last_indefinite_indices_.push_back(kNotFound); + sets_geometry_.emplace_back(first_set_offset, /* track_count */ 0); + + for (const auto& set : sets_) { + if (set.GrowthLimit() == kIndefiniteSize) { + last_indefinite_indices_.push_back(last_indefinite_indices_.size() - 1); + } else { + first_set_offset += set.GrowthLimit() + set.track_count * gutter_size; + last_indefinite_indices_.push_back(last_indefinite_indices_.back()); + } + sets_geometry_.emplace_back(first_set_offset, set.track_count); + } + gutter_size_ = gutter_size; +} + +void NGGridSizingTrackCollection::CacheSetsGeometry(LayoutUnit first_set_offset, + LayoutUnit gutter_size) { + last_indefinite_indices_.clear(); + sets_geometry_.Shrink(0); + + sets_geometry_.emplace_back(first_set_offset, /* track_count */ 0); + for (const auto& set : sets_) { + first_set_offset += set.BaseSize() + set.track_count * gutter_size; + sets_geometry_.emplace_back(first_set_offset, set.track_count); + } + gutter_size_ = gutter_size; +} + +void NGGridSizingTrackCollection::AdjustSetOffsets(wtf_size_t set_index, + LayoutUnit delta) { + DCHECK_LT(set_index, sets_geometry_.size()); + for (wtf_size_t i = set_index; i < sets_geometry_.size(); ++i) + sets_geometry_[i].offset += delta; +} + +void NGGridSizingTrackCollection::SetIndefiniteGrowthLimitsToBaseSize() { + for (auto& set : sets_) { if (set.GrowthLimit() == kIndefiniteSize) set.growth_limit = set.base_size; } } +void NGGridSizingTrackCollection::ResetBaselines() { + const wtf_size_t set_count = sets_.size(); + major_baselines_ = Vector<LayoutUnit>(set_count); + minor_baselines_ = Vector<LayoutUnit>(set_count); +} + +void NGGridSizingTrackCollection::SetMajorBaseline( + wtf_size_t set_index, + LayoutUnit candidate_baseline) { + DCHECK_LT(set_index, major_baselines_.size()); + if (candidate_baseline > major_baselines_[set_index]) + major_baselines_[set_index] = candidate_baseline; +} + +void NGGridSizingTrackCollection::SetMinorBaseline( + wtf_size_t set_index, + LayoutUnit candidate_baseline) { + DCHECK_LT(set_index, minor_baselines_.size()); + if (candidate_baseline > minor_baselines_[set_index]) + minor_baselines_[set_index] = candidate_baseline; +} + void NGGridSizingTrackCollection::AppendTrackRange( const NGGridBlockTrackCollection::Range& block_track_range, const NGGridTrackList& specified_track_list,
diff --git a/third_party/blink/renderer/core/layout/ng/grid/ng_grid_track_collection.h b/third_party/blink/renderer/core/layout/ng/grid/ng_grid_track_collection.h index 63b0203..8b35c96 100644 --- a/third_party/blink/renderer/core/layout/ng/grid/ng_grid_track_collection.h +++ b/third_party/blink/renderer/core/layout/ng/grid/ng_grid_track_collection.h
@@ -94,10 +94,9 @@ wtf_size_t* grid_item_range_index_to_cache; }; - NGGridBlockTrackCollection( - const ComputedStyle& grid_style, - const NGGridPlacementData& placement_data, - GridTrackSizingDirection track_direction = kForColumns); + NGGridBlockTrackCollection(const ComputedStyle& grid_style, + const NGGridPlacementData& placement_data, + GridTrackSizingDirection track_direction); // NGGridTrackCollectionBase overrides. wtf_size_t RangeCount() const override { return ranges_.size(); } @@ -146,6 +145,84 @@ Vector<Range> ranges_; }; +class CORE_EXPORT NGGridLayoutTrackCollection + : public NGGridTrackCollectionBase { + public: + struct CORE_EXPORT Range { + bool IsCollapsed() const; + + wtf_size_t set_count; + wtf_size_t start_line; + wtf_size_t track_count; + wtf_size_t begin_set_index; + + TrackSpanProperties properties; + }; + + struct SetGeometry { + SetGeometry(LayoutUnit offset, wtf_size_t track_count) + : offset(offset), track_count(track_count) {} + + LayoutUnit offset; + wtf_size_t track_count; + }; + + explicit NGGridLayoutTrackCollection(GridTrackSizingDirection track_direction) + : NGGridTrackCollectionBase(track_direction) {} + + // NGGridTrackCollectionBase overrides. + wtf_size_t RangeCount() const override { return ranges_.size(); } + wtf_size_t RangeStartLine(wtf_size_t range_index) const override; + wtf_size_t RangeTrackCount(wtf_size_t range_index) const override; + + // Returns the number of sets spanned by a given track range. + wtf_size_t RangeSetCount(wtf_size_t range_index) const; + // Return the index of the first set spanned by a given track range. + wtf_size_t RangeBeginSetIndex(wtf_size_t range_index) const; + + // Returns true if the specified property has been set in the track span + // properties bitmask of the range at position |range_index|. + bool RangeHasTrackSpanProperty( + wtf_size_t range_index, + TrackSpanProperties::PropertyId property_id) const; + + wtf_size_t EndLineOfImplicitGrid() const; + // Returns true if |grid_line| is contained within the implicit grid. + bool IsGridLineWithinImplicitGrid(wtf_size_t grid_line) const; + + wtf_size_t GetSetCount() const; + LayoutUnit GetSetOffset(wtf_size_t set_index) const; + wtf_size_t GetSetTrackCount(wtf_size_t set_index) const; + + LayoutUnit MajorBaseline(wtf_size_t set_index) const; + LayoutUnit MinorBaseline(wtf_size_t set_index) const; + + // Returns the total size of all sets in the collection. + LayoutUnit ComputeSetSpanSize() const; + // Returns the total size of all sets with index in the range [begin, end). + LayoutUnit ComputeSetSpanSize(wtf_size_t begin_set_index, + wtf_size_t end_set_index) const; + + LayoutUnit GutterSize() const { return gutter_size_; } + const Vector<Range>& Ranges() const { return ranges_; } + + // Don't allow this class to be used for grid sizing. + virtual bool IsForSizing() const { return false; } + // Indefinite indices are only used while measuring grid item contributions. + virtual bool IsSpanningIndefiniteSet(wtf_size_t begin_set_index, + wtf_size_t end_set_index) const { + return false; + } + + protected: + LayoutUnit gutter_size_; + + Vector<Range> ranges_; + Vector<LayoutUnit> major_baselines_; + Vector<LayoutUnit> minor_baselines_; + Vector<SetGeometry> sets_geometry_; +}; + // |NGGridBlockTrackCollection::EnsureTrackCoverage| may introduce a range start // and/or end at the middle of any repeater from the block collection. This will // affect how some repeated tracks within the same repeater group resolve their @@ -217,52 +294,6 @@ bool is_infinitely_growable : 1; }; -class CORE_EXPORT NGGridLayoutTrackCollection - : public NGGridTrackCollectionBase { - public: - struct CORE_EXPORT Range { - bool IsCollapsed() const; - - wtf_size_t set_count; - wtf_size_t start_line; - wtf_size_t track_count; - wtf_size_t begin_set_index; - - TrackSpanProperties properties; - }; - - // NGGridTrackCollectionBase overrides. - wtf_size_t RangeCount() const override { return ranges_.size(); } - wtf_size_t RangeStartLine(wtf_size_t range_index) const override; - wtf_size_t RangeTrackCount(wtf_size_t range_index) const override; - - // Returns the number of sets spanned by a given track range. - wtf_size_t RangeSetCount(wtf_size_t range_index) const; - // Return the index of the first set spanned by a given track range. - wtf_size_t RangeBeginSetIndex(wtf_size_t range_index) const; - - // Returns true if the specified property has been set in the track span - // properties bitmask of the range at position |range_index|. - bool RangeHasTrackSpanProperty( - wtf_size_t range_index, - TrackSpanProperties::PropertyId property_id) const; - - wtf_size_t EndLineOfImplicitGrid() const; - bool IsGridLineWithinImplicitGrid(wtf_size_t grid_line) const; - - const Vector<Range>& Ranges() const { return ranges_; } - - protected: - explicit NGGridLayoutTrackCollection(GridTrackSizingDirection track_direction) - : NGGridTrackCollectionBase(track_direction) {} - - NGGridLayoutTrackCollection(const Vector<Range>& range_data, - GridTrackSizingDirection track_direction) - : NGGridTrackCollectionBase(track_direction), ranges_(range_data) {} - - Vector<Range> ranges_; -}; - class CORE_EXPORT NGGridSizingTrackCollection : public NGGridLayoutTrackCollection { public: @@ -284,7 +315,7 @@ end_set_index_(end_set_index) { DCHECK(track_collection_); DCHECK_LE(current_set_index_, end_set_index_); - DCHECK_LE(end_set_index_, track_collection_->SetCount()); + DCHECK_LE(end_set_index_, track_collection_->GetSetCount()); } bool IsAtEnd() const { @@ -299,7 +330,7 @@ NGGridSetRef CurrentSet() const { DCHECK_LT(current_set_index_, end_set_index_); - return track_collection_->SetAt(current_set_index_); + return track_collection_->GetSetAt(current_set_index_); } private: @@ -311,8 +342,8 @@ typedef SetIteratorBase<false> SetIterator; typedef SetIteratorBase<true> ConstSetIterator; - explicit NGGridSizingTrackCollection( - GridTrackSizingDirection track_direction = kForColumns) + // TODO(ethavar): We shouldn't copy the sizing collection. + explicit NGGridSizingTrackCollection(GridTrackSizingDirection track_direction) : NGGridLayoutTrackCollection(track_direction) {} // |is_available_size_indefinite| is used to normalize percentage track @@ -321,15 +352,9 @@ const NGGridBlockTrackCollection& block_track_collection, bool is_available_size_indefinite); - NGGridSizingTrackCollection(const Vector<Range>& range_data, - GridTrackSizingDirection track_direction) - : NGGridLayoutTrackCollection(range_data, track_direction) {} - - // Returns the number of sets in the collection. - wtf_size_t SetCount() const { return sets_.size(); } // Returns a reference to the set located at position |set_index|. - NGGridSet& SetAt(wtf_size_t set_index); - const NGGridSet& SetAt(wtf_size_t set_index) const; + NGGridSet& GetSetAt(wtf_size_t set_index); + const NGGridSet& GetSetAt(wtf_size_t set_index) const; // Returns an iterator for all the sets contained in this collection. SetIterator GetSetIterator(); ConstSetIterator GetConstSetIterator() const; @@ -338,11 +363,31 @@ SetIterator GetSetIterator(wtf_size_t begin_set_index, wtf_size_t end_set_index); + // This class should be specifically used for grid sizing. + bool IsForSizing() const override { return true; } + bool IsSpanningIndefiniteSet(wtf_size_t begin_set_index, + wtf_size_t end_set_index) const override; + wtf_size_t NonCollapsedTrackCount() const { return non_collapsed_track_count_; } + LayoutUnit TotalTrackSize() const; - void SetAllGrowthLimitsToBaseSize(); + // Caches the initial geometry used to compute grid item contributions. + void InitializeSetsGeometry(LayoutUnit first_set_offset, + LayoutUnit gutter_size); + // Caches the final geometry required to place |NGGridSet| in the grid. + void CacheSetsGeometry(LayoutUnit first_set_offset, LayoutUnit gutter_size); + // Increase by |delta| the offset of every set with index > |set_index|. + void AdjustSetOffsets(wtf_size_t set_index, LayoutUnit delta); + void SetIndefiniteGrowthLimitsToBaseSize(); + + void ResetBaselines(); + + void SetMajorBaseline(wtf_size_t set_index, LayoutUnit candidate_baseline); + void SetMinorBaseline(wtf_size_t set_index, LayoutUnit candidate_baseline); + + void SetGutterSize(LayoutUnit gutter_size) { gutter_size_ = gutter_size; } private: void AppendTrackRange( @@ -352,15 +397,49 @@ wtf_size_t non_collapsed_track_count_; + // Initially we only know some of the set sizes - others will be indefinite. + // To represent this we store both the offset for the set, and a vector of all + // last indefinite indices (or kNotFound if everything so far has been + // definite). This allows us to get the appropriate size if a grid item spans + // only fixed tracks, but will allow us to return an indefinite size if it + // spans any indefinite set. + // + // As an example: + // grid-template-rows: auto auto 100px 100px auto 100px; + // + // Results in: + // | auto | auto | 100 | 100 | auto | 100 | + // [{0, kNotFound}, {0, 0}, {0, 1}, {100, 1}, {200, 1}, {200, 4}, {300, 4}] + // + // Various queries (start/end refer to the grid lines): + // start: 0, end: 1 -> indefinite as: + // "start <= sets[end].last_indefinite_index" + // start: 1, end: 3 -> indefinite as: + // "start <= sets[end].last_indefinite_index" + // start: 2, end: 4 -> 200px + // start: 5, end: 6 -> 100px + // start: 3, end: 5 -> indefinite as: + // "start <= sets[end].last_indefinite_index" + Vector<wtf_size_t> last_indefinite_indices_; + // A vector of every set element that compose the entire collection's ranges; // track definitions from the same set are stored in consecutive positions, // preserving the order in which the definitions appear in their range. Vector<NGGridSet> sets_; }; +template <> +struct DowncastTraits<NGGridSizingTrackCollection> { + static bool AllowFrom(const NGGridLayoutTrackCollection& layout_collection) { + return layout_collection.IsForSizing(); + } +}; + } // namespace blink WTF_ALLOW_MOVE_INIT_AND_COMPARE_WITH_MEM_FUNCTIONS( blink::NGGridLayoutTrackCollection::Range) +WTF_ALLOW_MOVE_INIT_AND_COMPARE_WITH_MEM_FUNCTIONS( + blink::NGGridLayoutTrackCollection::SetGeometry) #endif // THIRD_PARTY_BLINK_RENDERER_CORE_LAYOUT_NG_GRID_NG_GRID_TRACK_COLLECTION_H_
diff --git a/third_party/blink/renderer/core/loader/empty_clients.h b/third_party/blink/renderer/core/loader/empty_clients.h index e23de75..fb500a3b 100644 --- a/third_party/blink/renderer/core/loader/empty_clients.h +++ b/third_party/blink/renderer/core/loader/empty_clients.h
@@ -306,6 +306,7 @@ std::unique_ptr<PolicyContainer> policy_container, std::unique_ptr<WebDocumentLoader::ExtraData> extra_data) override; + String UserAgentOverride() override { return ""; } String UserAgent() override { return ""; } String FullUserAgent() override { return ""; } String ReducedUserAgent() override { return ""; }
diff --git a/third_party/blink/renderer/core/loader/frame_loader.cc b/third_party/blink/renderer/core/loader/frame_loader.cc index d7b2da6..12fabb1 100644 --- a/third_party/blink/renderer/core/loader/frame_loader.cc +++ b/third_party/blink/renderer/core/loader/frame_loader.cc
@@ -49,9 +49,11 @@ #include "services/network/public/cpp/web_sandbox_flags.h" #include "services/network/public/mojom/web_sandbox_flags.mojom-blink.h" #include "third_party/blink/public/common/features.h" +#include "third_party/blink/public/common/user_agent/user_agent_metadata.h" #include "third_party/blink/public/mojom/fetch/fetch_api_request.mojom-blink.h" #include "third_party/blink/public/mojom/loader/request_context_frame_type.mojom-blink.h" #include "third_party/blink/public/platform/modules/service_worker/web_service_worker_network_provider.h" +#include "third_party/blink/public/platform/platform.h" #include "third_party/blink/public/platform/task_type.h" #include "third_party/blink/public/platform/web_content_settings_client.h" #include "third_party/blink/public/platform/web_url_request.h" @@ -1329,25 +1331,53 @@ view->ScheduleAnimation(); } -String FrameLoader::UserAgent() const { - String user_agent = Client()->UserAgent(); +String FrameLoader::ApplyUserAgentOverrideAndLog( + const String& user_agent) const { + String user_agent_override; probe::ApplyUserAgentOverride(probe::ToCoreProbeSink(frame_->GetDocument()), - &user_agent); - return user_agent; + &user_agent_override); + + if (Client()->UserAgentOverride().IsEmpty() && + user_agent_override.IsEmpty()) { + return user_agent; + } + + if (user_agent_override.IsEmpty()) { + user_agent_override = user_agent; + } + + if (base::FeatureList::IsEnabled( + blink::features::kUserAgentOverrideExperiment)) { + String ua_original = Platform::Current()->UserAgent(); + + auto it = user_agent_override.Find(ua_original); + UserAgentOverride::UserAgentOverrideHistogram histogram = + UserAgentOverride::UserAgentOverrideHistogram::UserAgentOverriden; + if (it == 0) { + histogram = UserAgentOverride::UserAgentOverrideHistogram:: + UserAgentOverrideSuffix; + } else if (it != kNotFound) { + histogram = UserAgentOverride::UserAgentOverrideHistogram:: + UserAgentOverrideSubstring; + } + + document_loader_->GetUseCounter().CountUserAgentOverride(histogram, + frame_.Get()); + } + + return user_agent_override; +} + +String FrameLoader::UserAgent() const { + return ApplyUserAgentOverrideAndLog(Client()->UserAgent()); } String FrameLoader::FullUserAgent() const { - String user_agent = Client()->FullUserAgent(); - probe::ApplyUserAgentOverride(probe::ToCoreProbeSink(frame_->GetDocument()), - &user_agent); - return user_agent; + return ApplyUserAgentOverrideAndLog(Client()->FullUserAgent()); } String FrameLoader::ReducedUserAgent() const { - String user_agent = Client()->ReducedUserAgent(); - probe::ApplyUserAgentOverride(probe::ToCoreProbeSink(frame_->GetDocument()), - &user_agent); - return user_agent; + return ApplyUserAgentOverrideAndLog(Client()->ReducedUserAgent()); } absl::optional<blink::UserAgentMetadata> FrameLoader::UserAgentMetadata()
diff --git a/third_party/blink/renderer/core/loader/frame_loader.h b/third_party/blink/renderer/core/loader/frame_loader.h index 21c3343..5b508a2 100644 --- a/third_party/blink/renderer/core/loader/frame_loader.h +++ b/third_party/blink/renderer/core/loader/frame_loader.h
@@ -299,6 +299,8 @@ LocalFrameClient* Client() const; + String ApplyUserAgentOverrideAndLog(const String& user_agent) const; + Member<LocalFrame> frame_; Member<ProgressTracker> progress_tracker_;
diff --git a/third_party/blink/renderer/modules/webgpu/gpu_canvas_configuration.idl b/third_party/blink/renderer/modules/webgpu/gpu_canvas_configuration.idl index b9709c14..1e4ff0c 100644 --- a/third_party/blink/renderer/modules/webgpu/gpu_canvas_configuration.idl +++ b/third_party/blink/renderer/modules/webgpu/gpu_canvas_configuration.idl
@@ -4,9 +4,15 @@ // https://gpuweb.github.io/gpuweb/ +enum GPUCanvasCompositingAlphaMode { + "opaque", + "premultiplied", +}; + dictionary GPUCanvasConfiguration : GPUObjectDescriptorBase { required GPUDevice device; required GPUTextureFormat format; GPUTextureUsageFlags usage = 16; // GPUTextureUsage.RENDER_ATTACHMENT + GPUCanvasCompositingAlphaMode compositingAlphaMode = "opaque"; GPUExtent3D size; };
diff --git a/third_party/blink/renderer/modules/webgpu/gpu_canvas_context.cc b/third_party/blink/renderer/modules/webgpu/gpu_canvas_context.cc index b9f4a1e6..b39ea0c 100644 --- a/third_party/blink/renderer/modules/webgpu/gpu_canvas_context.cc +++ b/third_party/blink/renderer/modules/webgpu/gpu_canvas_context.cc
@@ -6,6 +6,7 @@ #include "components/viz/common/resources/resource_format_utils.h" #include "third_party/blink/renderer/bindings/core/v8/v8_union_htmlcanvaselement_offscreencanvas.h" +#include "third_party/blink/renderer/bindings/modules/v8/v8_gpu_canvas_compositing_alpha_mode.h" #include "third_party/blink/renderer/bindings/modules/v8/v8_gpu_canvas_configuration.h" #include "third_party/blink/renderer/bindings/modules/v8/v8_union_canvasrenderingcontext2d_gpucanvascontext_imagebitmaprenderingcontext_webgl2renderingcontext_webglrenderingcontext.h" #include "third_party/blink/renderer/bindings/modules/v8/v8_union_gpucanvascontext_imagebitmaprenderingcontext_offscreencanvasrenderingcontext2d_webgl2renderingcontext_webglrenderingcontext.h" @@ -207,8 +208,9 @@ } swapchain_ = MakeGarbageCollected<GPUSwapChain>( - this, configured_device_, usage, format, filter_quality_, size); - swapchain_->CcLayer()->SetContentsOpaque(!CreationAttributes().alpha); + this, configured_device_, usage, format, filter_quality_, + descriptor->compositingAlphaMode().AsEnum(), size); + if (descriptor->hasLabel()) swapchain_->setLabel(descriptor->label());
diff --git a/third_party/blink/renderer/modules/webgpu/gpu_swap_chain.cc b/third_party/blink/renderer/modules/webgpu/gpu_swap_chain.cc index f3e12c1..e77c830 100644 --- a/third_party/blink/renderer/modules/webgpu/gpu_swap_chain.cc +++ b/third_party/blink/renderer/modules/webgpu/gpu_swap_chain.cc
@@ -19,22 +19,82 @@ namespace blink { -GPUSwapChain::GPUSwapChain(GPUCanvasContext* context, - GPUDevice* device, - WGPUTextureUsage usage, - WGPUTextureFormat format, - cc::PaintFlags::FilterQuality filter_quality, - gfx::Size size) +GPUSwapChain::GPUSwapChain( + GPUCanvasContext* context, + GPUDevice* device, + WGPUTextureUsage usage, + WGPUTextureFormat format, + cc::PaintFlags::FilterQuality filter_quality, + V8GPUCanvasCompositingAlphaMode::Enum compositing_alpha_mode, + gfx::Size size) : DawnObjectBase(device->GetDawnControlClient()), device_(device), context_(context), usage_(usage), format_(format), + compositing_alpha_mode_(compositing_alpha_mode), size_(size) { // TODO: Use label from GPUObjectDescriptorBase. swap_buffers_ = base::AdoptRef(new WebGPUSwapBufferProvider( this, GetDawnControlClient(), device->GetHandle(), usage_, format)); swap_buffers_->SetFilterQuality(filter_quality); + + // Note: SetContentsOpaque is only an optimization hint. It doesn't + // actually make the contents opaque. + switch (compositing_alpha_mode) { + case V8GPUCanvasCompositingAlphaMode::Enum::kOpaque: { + CcLayer()->SetContentsOpaque(true); + + WGPUShaderModuleWGSLDescriptor wgsl_desc = { + .chain = {.sType = WGPUSType_ShaderModuleWGSLDescriptor}, + .source = R"( + @stage(vertex) fn vert_main(@builtin(vertex_index) VertexIndex : u32) -> @builtin(position) vec4<f32> { + var pos = array<vec2<f32>, 3>( + vec2<f32>(-1.0, -1.0), + vec2<f32>( 3.0, -1.0), + vec2<f32>(-1.0, 3.0)); + return vec4<f32>(pos[VertexIndex], 0.0, 1.0); + } + + @stage(fragment) fn frag_main() -> @location(0) vec4<f32> { + return vec4<f32>(1.0); + } + )", + }; + WGPUShaderModuleDescriptor shader_module_desc = {.nextInChain = + &wgsl_desc.chain}; + WGPUShaderModule shader_module = GetProcs().deviceCreateShaderModule( + device_->GetHandle(), &shader_module_desc); + + WGPUColorTargetState color_target = { + .format = format_, + .writeMask = WGPUColorWriteMask_Alpha, + }; + WGPUFragmentState fragment = { + .module = shader_module, + .entryPoint = "frag_main", + .targetCount = 1, + .targets = &color_target, + }; + WGPURenderPipelineDescriptor pipeline_desc = { + .vertex = + { + .module = shader_module, + .entryPoint = "vert_main", + }, + .primitive = {.topology = WGPUPrimitiveTopology_TriangleList}, + .multisample = {.count = 1, .mask = 0xFFFFFFFF}, + .fragment = &fragment, + }; + alpha_to_one_pipeline_ = GetProcs().deviceCreateRenderPipeline( + device_->GetHandle(), &pipeline_desc); + GetProcs().shaderModuleRelease(shader_module); + break; + } + case V8GPUCanvasCompositingAlphaMode::Enum::kPremultiplied: + CcLayer()->SetContentsOpaque(false); + break; + } } GPUSwapChain::~GPUSwapChain() { @@ -48,6 +108,10 @@ } void GPUSwapChain::Neuter() { + if (alpha_to_one_pipeline_ != nullptr) { + GetProcs().renderPipelineRelease(alpha_to_one_pipeline_); + alpha_to_one_pipeline_ = nullptr; + } texture_ = nullptr; if (swap_buffers_) { swap_buffers_->Neuter(); @@ -310,6 +374,54 @@ // WebGPUSwapBufferProvider::Client implementation void GPUSwapChain::OnTextureTransferred() { DCHECK(texture_); + // The texture is about to be transferred to the compositor. + // For compositing alpha mode Opaque, clear the alpha channel to + // 1.0. + switch (compositing_alpha_mode_) { + case V8GPUCanvasCompositingAlphaMode::Enum::kOpaque: { + WGPUTextureView attachment_view = + GetProcs().textureCreateView(texture_->GetHandle(), nullptr); + + WGPUDawnEncoderInternalUsageDescriptor internal_usage_desc = { + .chain = {.sType = WGPUSType_DawnEncoderInternalUsageDescriptor}, + .useInternalUsages = true, + }; + WGPUCommandEncoderDescriptor command_encoder_desc = { + .nextInChain = &internal_usage_desc.chain, + }; + WGPUCommandEncoder command_encoder = + GetProcs().deviceCreateCommandEncoder(device_->GetHandle(), + &command_encoder_desc); + + WGPURenderPassColorAttachment color_attachment = { + .view = attachment_view, + .loadOp = WGPULoadOp_Load, + .storeOp = WGPUStoreOp_Store, + }; + WGPURenderPassDescriptor render_pass_desc = { + .colorAttachmentCount = 1, + .colorAttachments = &color_attachment, + }; + WGPURenderPassEncoder pass = GetProcs().commandEncoderBeginRenderPass( + command_encoder, &render_pass_desc); + DCHECK(alpha_to_one_pipeline_); + GetProcs().renderPassEncoderSetPipeline(pass, alpha_to_one_pipeline_); + GetProcs().renderPassEncoderDraw(pass, 3, 1, 0, 0); + GetProcs().renderPassEncoderEnd(pass); + + WGPUCommandBuffer command_buffer = + GetProcs().commandEncoderFinish(command_encoder, nullptr); + GetProcs().queueSubmit(device_->queue()->GetHandle(), 1, &command_buffer); + + GetProcs().renderPassEncoderRelease(pass); + GetProcs().commandEncoderRelease(command_encoder); + GetProcs().commandBufferRelease(command_buffer); + GetProcs().textureViewRelease(attachment_view); + break; + } + case V8GPUCanvasCompositingAlphaMode::Enum::kPremultiplied: + break; + } texture_ = nullptr; }
diff --git a/third_party/blink/renderer/modules/webgpu/gpu_swap_chain.h b/third_party/blink/renderer/modules/webgpu/gpu_swap_chain.h index 3b6a89b..2e43efa 100644 --- a/third_party/blink/renderer/modules/webgpu/gpu_swap_chain.h +++ b/third_party/blink/renderer/modules/webgpu/gpu_swap_chain.h
@@ -5,6 +5,7 @@ #ifndef THIRD_PARTY_BLINK_RENDERER_MODULES_WEBGPU_GPU_SWAP_CHAIN_H_ #define THIRD_PARTY_BLINK_RENDERER_MODULES_WEBGPU_GPU_SWAP_CHAIN_H_ +#include "third_party/blink/renderer/bindings/modules/v8/v8_gpu_canvas_compositing_alpha_mode.h" #include "third_party/blink/renderer/modules/webgpu/dawn_object.h" #include "third_party/blink/renderer/platform/graphics/gpu/webgpu_swap_buffer_provider.h" #include "third_party/blink/renderer/platform/heap/garbage_collected.h" @@ -30,6 +31,7 @@ WGPUTextureUsage, WGPUTextureFormat, cc::PaintFlags::FilterQuality, + V8GPUCanvasCompositingAlphaMode::Enum, gfx::Size); GPUSwapChain(const GPUSwapChain&) = delete; @@ -77,11 +79,13 @@ Member<GPUDevice> device_; Member<GPUCanvasContext> context_; - WGPUTextureUsage usage_; - WGPUTextureFormat format_; + const WGPUTextureUsage usage_; + const WGPUTextureFormat format_; + const V8GPUCanvasCompositingAlphaMode::Enum compositing_alpha_mode_; const gfx::Size size_; Member<GPUTexture> texture_; + WGPURenderPipeline alpha_to_one_pipeline_ = nullptr; scoped_refptr<StaticBitmapImage> SnapshotInternal( const WGPUTexture& texture,
diff --git a/third_party/blink/renderer/platform/bindings/v8_per_isolate_data.cc b/third_party/blink/renderer/platform/bindings/v8_per_isolate_data.cc index c7e9ab45..fe8509a 100644 --- a/third_party/blink/renderer/platform/bindings/v8_per_isolate_data.cc +++ b/third_party/blink/renderer/platform/bindings/v8_per_isolate_data.cc
@@ -422,8 +422,8 @@ } void ReportV8OOMError(const char* location, bool is_js_heap) { - LOG(FATAL) << "V8 " << (is_js_heap ? "javascript" : "process") << " OOM: (" - << location << ")."; + DVLOG(1) << "V8 " << (is_js_heap ? "javascript" : "process") << " OOM: (" + << location << ")."; OOM_CRASH(0); }
diff --git a/third_party/blink/renderer/platform/runtime_enabled_features.json5 b/third_party/blink/renderer/platform/runtime_enabled_features.json5 index 2488d56e..bdece37 100644 --- a/third_party/blink/renderer/platform/runtime_enabled_features.json5 +++ b/third_party/blink/renderer/platform/runtime_enabled_features.json5
@@ -2133,7 +2133,7 @@ }, { name: "SharedAutofill", - status: "experimental", + status: "test", }, { name: "SharedStorageAPI", @@ -2582,8 +2582,9 @@ status: "experimental", }, { + // Draft WebGL extensions are deliberately not enabled by experimental web + // platform features. name: "WebGLDraftExtensions", - status: "experimental", }, { name: "WebGLImageChromium",
diff --git a/third_party/blink/renderer/platform/scheduler/common/scheduling_policy.cc b/third_party/blink/renderer/platform/scheduler/common/scheduling_policy.cc deleted file mode 100644 index 6b7c95c..0000000 --- a/third_party/blink/renderer/platform/scheduler/common/scheduling_policy.cc +++ /dev/null
@@ -1,65 +0,0 @@ -// Copyright 2019 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "third_party/blink/renderer/platform/scheduler/public/scheduling_policy.h" - -namespace blink { - -bool SchedulingPolicy::IsFeatureSticky(SchedulingPolicy::Feature feature) { - switch (feature) { - case Feature::kWebSocket: - case Feature::kWebRTC: - case Feature::kDedicatedWorkerOrWorklet: - case Feature::kOutstandingIndexedDBTransaction: - case Feature::kOutstandingNetworkRequestDirectSocket: - case Feature::kOutstandingNetworkRequestFetch: - case Feature::kOutstandingNetworkRequestOthers: - case Feature::kOutstandingNetworkRequestXHR: - case Feature::kBroadcastChannel: - case Feature::kIndexedDBConnection: - case Feature::kWebGL: - case Feature::kWebVR: - case Feature::kWebXR: - case Feature::kSharedWorker: - case Feature::kWebHID: - case Feature::kWebShare: - case Feature::kWebDatabase: - case Feature::kPortal: - case Feature::kSpeechRecognizer: - case Feature::kSpeechSynthesis: - return false; - case Feature::kMainResourceHasCacheControlNoStore: - case Feature::kMainResourceHasCacheControlNoCache: - case Feature::kSubresourceHasCacheControlNoStore: - case Feature::kSubresourceHasCacheControlNoCache: - case Feature::kPageShowEventListener: - case Feature::kPageHideEventListener: - case Feature::kBeforeUnloadEventListener: - case Feature::kUnloadEventListener: - case Feature::kFreezeEventListener: - case Feature::kResumeEventListener: - case Feature::kContainsPlugins: - case Feature::kDocumentLoaded: - case Feature::kRequestedNotificationsPermission: - case Feature::kRequestedMIDIPermission: - case Feature::kRequestedAudioCapturePermission: - case Feature::kRequestedVideoCapturePermission: - case Feature::kRequestedBackForwardCacheBlockedSensors: - case Feature::kRequestedBackgroundWorkPermission: - case Feature::kWebLocks: - case Feature::kRequestedStorageAccessGrant: - case Feature::kWebNfc: - case Feature::kWebFileSystem: - case Feature::kAppBanner: - case Feature::kPrinting: - case Feature::kPictureInPicture: - case Feature::kIdleManager: - case Feature::kPaymentManager: - case Feature::kKeyboardLock: - case Feature::kWebOTPService: - return true; - } -} - -} // namespace blink
diff --git a/third_party/blink/web_tests/FlagExpectations/disable-layout-ng b/third_party/blink/web_tests/FlagExpectations/disable-layout-ng index 925317ac..421e473 100644 --- a/third_party/blink/web_tests/FlagExpectations/disable-layout-ng +++ b/third_party/blink/web_tests/FlagExpectations/disable-layout-ng
@@ -1030,6 +1030,7 @@ crbug.com/1132627 external/wpt/css/css-flexbox/flex-aspect-ratio-img-column-011.html [ Failure ] crbug.com/721123 css3/flexbox/flexitem.html [ Failure ] crbug.com/591099 css3/flexbox/flex-align-vertical-writing-mode.html [ Failure ] +crbug.com/591099 css3/flexbox/flex-flow-auto-margins-no-available-space-assert.html [ Failure ] crbug.com/721123 external/wpt/css/css-flexbox/flexitem-stretch-image.html [ Failure ] crbug.com/704294 external/wpt/css/css-flexbox/flex-aspect-ratio-img-row-006.html [ Failure ] crbug.com/704294 external/wpt/css/css-flexbox/canvas-dynamic-change-001.html [ Failure ]
diff --git a/third_party/blink/web_tests/FlagExpectations/highdpi b/third_party/blink/web_tests/FlagExpectations/highdpi index b11b9d2..26e9e16 100644 --- a/third_party/blink/web_tests/FlagExpectations/highdpi +++ b/third_party/blink/web_tests/FlagExpectations/highdpi
@@ -174,6 +174,7 @@ editing/inserting/insert-space-in-empty-doc.html [ Pass ] editing/pasteboard/drag-image-to-contenteditable-in-iframe.html [ Pass ] editing/selection/selection-background.html [ Pass ] +external/wpt/css/cssom-view/pt-to-px-width.html [ Pass ] external/wpt/pointerlock/movementX_Y_basic.html [ Pass ] external/wpt/svg/painting/svg-with-outline.html [ Pass ] fast/backgrounds/background-origin-root-element.html [ Pass ]
diff --git a/third_party/blink/web_tests/TestExpectations b/third_party/blink/web_tests/TestExpectations index 028c9f32..605ccb2 100644 --- a/third_party/blink/web_tests/TestExpectations +++ b/third_party/blink/web_tests/TestExpectations
@@ -276,7 +276,8 @@ # These tests require shared-storage and fenced-frames # Keep this in sync with VirtualTestSuites. crbug.com/1218540 wpt_internal/shared_storage/* [ Skip ] -crbug.com/1218540 virtual/shared-storage/* [ Pass ] +crbug.com/1218540 virtual/shared-storage-fenced-frame-mparch/* [ Pass ] +crbug.com/1218540 virtual/shared-storage-fenced-frame-shadow-dom/* [ Pass ] # These tests require the experimental prerender feature. # See https://crbug.com/1126305. @@ -3364,6 +3365,9 @@ crbug.com/626703 [ Win ] virtual/prerender/external/wpt/speculation-rules/prerender/storage-foundation.https.html [ Failure ] # ====== New tests from wpt-importer added here ====== +crbug.com/626703 [ Mac10.12 ] virtual/fenced-frame-mparch/wpt_internal/fenced_frame/navigate-ancestor-nested-fenced-frame.https.html [ Timeout ] +crbug.com/626703 [ Mac10.12 ] virtual/no-auto-wpt-origin-isolation/external/wpt/html/browsers/origin/origin-keyed-agent-clusters/1-iframe/parent-yes-child-yes-port.sub.https.html [ Timeout ] +crbug.com/626703 [ Mac10.12 ] virtual/no-auto-wpt-origin-isolation/external/wpt/html/browsers/origin/origin-keyed-agent-clusters/2-iframes/parent-yes-child1-yes-subdomain-child2-yes-subdomain2.sub.https.html [ Timeout ] crbug.com/626703 virtual/no-forced-frame-updates/external/wpt/html/dom/render-blocking/header-inserted-preload-link.tentative.html [ Timeout ] crbug.com/626703 [ Mac11-arm64 ] external/wpt/html/cross-origin-embedder-policy/worker-inheritance.sub.https.html [ Timeout ] crbug.com/626703 [ Mac11-arm64 ] virtual/no-auto-wpt-origin-isolation/external/wpt/html/browsers/origin/origin-keyed-agent-clusters/1-iframe/parent-no-child-yes-port.sub.https.html [ Timeout ]
diff --git a/third_party/blink/web_tests/VirtualTestSuites b/third_party/blink/web_tests/VirtualTestSuites index dc28388e..1ab7e2d 100644 --- a/third_party/blink/web_tests/VirtualTestSuites +++ b/third_party/blink/web_tests/VirtualTestSuites
@@ -1022,11 +1022,18 @@ "args": ["--enable-blink-features=HighlightInheritance"] }, { - "prefix": "shared-storage", + "prefix": "shared-storage-fenced-frame-mparch", "bases": [ "wpt_internal/shared_storage" ], - "args": ["--enable-features=SharedStorageAPI,FencedFrames"] + "args": ["--enable-features=SharedStorageAPI,FencedFrames:implementation_type/mparch"] + }, + { + "prefix": "shared-storage-fenced-frame-shadow-dom", + "bases": [ + "wpt_internal/shared_storage" + ], + "args": ["--enable-features=SharedStorageAPI,FencedFrames:implementation_type/shadow_dom"] }, { "prefix": "fenced-frame-mparch",
diff --git a/third_party/blink/web_tests/css3/flexbox/flex-flow-auto-margins-no-available-space-assert.html b/third_party/blink/web_tests/css3/flexbox/flex-flow-auto-margins-no-available-space-assert.html index c049fa7..1001628 100644 --- a/third_party/blink/web_tests/css3/flexbox/flex-flow-auto-margins-no-available-space-assert.html +++ b/third_party/blink/web_tests/css3/flexbox/flex-flow-auto-margins-no-available-space-assert.html
@@ -10,7 +10,7 @@ } </style> <script src="../../resources/check-layout.js"></script> -<abbr data-expected-height=30210272> +<abbr data-expected-height=30210271> <input></input> </abbr> <p> crbug.com/380201: Don't shrink below border/padding when stretching children within a flexbox with no available space.</p>
diff --git a/third_party/blink/web_tests/document-transition/multiple-shared-elements-animate-crash.html b/third_party/blink/web_tests/document-transition/multiple-shared-elements-animate-crash.html index afd028e..e089ad1 100644 --- a/third_party/blink/web_tests/document-transition/multiple-shared-elements-animate-crash.html +++ b/third_party/blink/web_tests/document-transition/multiple-shared-elements-animate-crash.html
@@ -46,16 +46,12 @@ async_test((t) => { t.step(() => { requestAnimationFrame(() => requestAnimationFrame(async () => { - document.createDocumentTransition(async (transition) => { - transition.setElement(e1, "e1"); - transition.setElement(e2, "e2"); - - await transition.captureAndHold(); - + let transition = document.createDocumentTransition(); + transition.setElement(e1, "e1"); + transition.setElement(e2, "e2"); + await transition.start(() => { container.classList.remove("left"); container.classList.add("right"); - - await transition.start(); }); requestAnimationFrame(() => {
diff --git a/third_party/blink/web_tests/document-transition/paint-order.html b/third_party/blink/web_tests/document-transition/paint-order.html index 1daff159..3a9cf32 100644 --- a/third_party/blink/web_tests/document-transition/paint-order.html +++ b/third_party/blink/web_tests/document-transition/paint-order.html
@@ -32,18 +32,14 @@ async function doTransition() { let elem = document.getElementsByTagName("div")[0]; - document.createDocumentTransition(async (t) => { - t.setElement(elem, "shared"); - await t.captureAndHold(); - + let t = document.createDocumentTransition(); + t.setElement(elem, "shared"); + await t.start(() => { elem.style.backgroundColor = "red"; - - await t.start(); - - if (window.testRunner) { - requestAnimationFrame(() => requestAnimationFrame(() => testRunner.notifyDone())); - } }); + if (window.testRunner) { + requestAnimationFrame(() => requestAnimationFrame(() => testRunner.notifyDone())); + } } onload = requestAnimationFrame(() => requestAnimationFrame(doTransition));
diff --git a/third_party/blink/web_tests/external/Version b/third_party/blink/web_tests/external/Version index 26a04a19..ecb9fd3 100644 --- a/third_party/blink/web_tests/external/Version +++ b/third_party/blink/web_tests/external/Version
@@ -1 +1 @@ -Version: 5abcf5a929664fc4bcd331d5082e26a5c39d9b62 +Version: aee3583a2c92911540493123490d8db028b38eca
diff --git a/third_party/blink/web_tests/external/WPT_BASE_MANIFEST_8.json b/third_party/blink/web_tests/external/WPT_BASE_MANIFEST_8.json index 285141b..84ba327 100644 --- a/third_party/blink/web_tests/external/WPT_BASE_MANIFEST_8.json +++ b/third_party/blink/web_tests/external/WPT_BASE_MANIFEST_8.json
@@ -243498,7 +243498,7 @@ [] ], "README.md": [ - "6ce0dd33303526980a361b7c091a982f3ee8730c", + "20f1e60a8bb2bf4aeb183d5ba4020f8f2a073327", [] ], "build-css-testsuites.sh": [ @@ -280829,7 +280829,7 @@ [] ], "computed-testcommon.js": [ - "42cc17652e169f07fe930196d00caf5501d3788f", + "3d1c7184422fea7f56c61e58e96a38d58df4c9c2", [] ], "green.ico": [ @@ -281398,7 +281398,7 @@ [] ], "frontend.py": [ - "9397e05ad5126240e82b9a5f4f1a87b239a4492d", + "3f06e3c1430d4e504bd6053f0fdd935d8af6c588", [] ], "index.md": [ @@ -281414,7 +281414,7 @@ [] ], "requirements.txt": [ - "66d66469d53ca6b1f5597f7ad0ce563df44f5cad", + "1cdeadd2dcc60e3262ab609b6fb89394f86d6d46", [] ], "reviewing-tests": { @@ -287405,15 +287405,15 @@ ], "resources": { "font-asserts.js": [ - "2c658a15c2c27dc8903296b687c6f735ceb1945d", + "7094d8f0bf3bb8a20a28d1fa037d1421aea669ee", [] ], "font-data.js": [ - "94575b7191b73cdef7c11e575472c4fa1157036e", + "f8e97038205a71201baa8c5a8750ebe2eea851bd", [] ], "font-test-utils.js": [ - "21327b5fed38d4b9c3a7c475210e137169a70538", + "84dade8d4b7baa0c07be2aca1cd7c1af6b9bac79", [] ] } @@ -306891,9 +306891,29 @@ "175cdf80464a658981a55d09d788dee26bf1e1a0", [] ], + "fetch-and-record-js.h2.py": [ + "d1b5d0e1cb02847dbcbfd635d7b0934775617763", + [] + ], + "get-fetch-timing-and-headers.h2.py": [ + "ff4f8bedd2b473599828866e0c9353d5c63f5723", + [] + ], "preload-initiator-type.html": [ "34188df2fe437fdbc8d6814ad33c83c8dac23391", [] + ], + "referrer-policy-test-loader.h2.py": [ + "ad48cbb71d3bb577be86c5a7ab02134ad018d2e9", + [] + ], + "referrer-policy-test.html": [ + "514e6c6539ca90e09756209d46b47e9321735148", + [] + ], + "utils.py": [ + "aa6f331b4196cfbc82a03aa058ad839081ea10e9", + [] ] } }, @@ -314124,7 +314144,7 @@ [] ], "basic-shared-worker-expected.txt": [ - "9e12e7b3b52d7ee50703cdb7ed115ddd71336c6f", + "a974f409b9debc2f2bf04d0047c39f0180308b8a", [] ], "basic-shared-worker.https-expected.txt": [ @@ -314144,7 +314164,7 @@ [] ], "shared-worker-insecure-first.https-expected.txt": [ - "170f14ce790bf70c74fad215bf36b8b0b85fa95d", + "4feba4d92f4e1f23e636bd690db91e19e9586354", [] ], "shared-worker-secure-first.https-expected.txt": [ @@ -385927,7 +385947,7 @@ ] }, "calc-angle-values.html": [ - "0bbb43dcf162a171ef8ea6414ea78625e1839204", + "699af7a5cdcb3b4cfa106f53eb416a15427f0a91", [ null, {} @@ -385969,7 +385989,7 @@ ] ], "calc-infinity-nan-computed.html": [ - "cfcaa816f4eea63191142d9113eff1e4b5e2cbd9", + "55b891c1e48bdf4b62603690cd163482f2e7ba17", [ null, {} @@ -423985,7 +424005,7 @@ ] ], "font_access_blob.tentative.https.window.js": [ - "90c58c8ea175204f4f1916d2fbd61b5a868a2b46", + "a4ab8b3a7d5e4cb5d0d520a243ead39a028b8c20", [ "font-access/font_access_blob.tentative.https.window.html", { @@ -424014,6 +424034,24 @@ } ] ], + "font_access_permission.tentative.https.window.js": [ + "6826f102743f013a0d6a156fe715c52ebf453825", + [ + "font-access/font_access_permission.tentative.https.window.html", + { + "script_metadata": [ + [ + "script", + "/resources/testdriver.js" + ], + [ + "script", + "/resources/testdriver-vendor.js" + ] + ] + } + ] + ], "font_access_query_select.tentative.https.window.js": [ "b00a96f9a2ad5d298921bd3904acdb42fbd4828e", [ @@ -474535,6 +474573,20 @@ ] } ] + ], + "referrer-policy.h2.window.js": [ + "28756c9f857704c0373f622d5778e219c8a2af94", + [ + "loading/early-hints/referrer-policy.h2.window.html", + { + "script_metadata": [ + [ + "script", + "/common/utils.js" + ] + ] + } + ] ] }, "preloader-css-import-no-quote.tentative.html": [ @@ -561586,14 +561638,14 @@ ] ], "block-in-inline-insert-019.html": [ - "0a2ea483e5d69e15410961bb92331405a685dc40", + "1f1cd1ae09a261f5339687f7386070f2c2c83827", [ null, {} ] ], "block-in-inline-insert-020.html": [ - "2a3b15a8e8dfdcf5b26b05131639f7a436a2a4f4", + "3fbed1b3c05c4d2e055129b32c44fafdc1339483", [ null, {}
diff --git a/third_party/blink/web_tests/external/wpt/client-hints/accept-ch-stickiness/resources/clear-site-data.html.headers b/third_party/blink/web_tests/external/wpt/client-hints/accept-ch-stickiness/resources/clear-site-data.html.headers index a0077c0..955424f 100644 --- a/third_party/blink/web_tests/external/wpt/client-hints/accept-ch-stickiness/resources/clear-site-data.html.headers +++ b/third_party/blink/web_tests/external/wpt/client-hints/accept-ch-stickiness/resources/clear-site-data.html.headers
@@ -1 +1,2 @@ Clear-Site-Data: "*" +Access-Control-Allow-Origin: * \ No newline at end of file
diff --git a/third_party/blink/web_tests/external/wpt/client-hints/sandbox/iframe-csp-same-origin.https.html b/third_party/blink/web_tests/external/wpt/client-hints/sandbox/iframe-csp-same-origin.https.html new file mode 100644 index 0000000..f96e642f --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/client-hints/sandbox/iframe-csp-same-origin.https.html
@@ -0,0 +1,18 @@ +<!DOCTYPE html> +<html> + +<body> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<script src="resources/util.js"></script> + +<script> + +sandbox_iframe_test("", + expect_iframe_hints, + "CSP sandboxed iframe with same-origin flag does send client hint headers"); + +</script> + +</body> +</html> \ No newline at end of file
diff --git a/third_party/blink/web_tests/external/wpt/client-hints/sandbox/iframe-csp-same-origin.https.html.headers b/third_party/blink/web_tests/external/wpt/client-hints/sandbox/iframe-csp-same-origin.https.html.headers new file mode 100644 index 0000000..cf57761d --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/client-hints/sandbox/iframe-csp-same-origin.https.html.headers
@@ -0,0 +1,2 @@ +Accept-CH: sec-ch-device-memory, device-memory, sec-ch-dpr, dpr, sec-ch-viewport-width, viewport-width, rtt, downlink, ect +Content-Security-Policy: sandbox allow-scripts allow-same-origin \ No newline at end of file
diff --git a/third_party/blink/web_tests/external/wpt/client-hints/sandbox/iframe-csp.https.html b/third_party/blink/web_tests/external/wpt/client-hints/sandbox/iframe-csp.https.html new file mode 100644 index 0000000..6412eb6 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/client-hints/sandbox/iframe-csp.https.html
@@ -0,0 +1,18 @@ +<!DOCTYPE html> +<html> + +<body> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<script src="resources/util.js"></script> + +<script> + +sandbox_iframe_test("", + expect_iframe_no_hints, + "CSP sandboxed iframe does not send client hint headers"); + +</script> + +</body> +</html> \ No newline at end of file
diff --git a/third_party/blink/web_tests/external/wpt/client-hints/sandbox/iframe-csp.https.html.headers b/third_party/blink/web_tests/external/wpt/client-hints/sandbox/iframe-csp.https.html.headers new file mode 100644 index 0000000..e0deb77 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/client-hints/sandbox/iframe-csp.https.html.headers
@@ -0,0 +1,2 @@ +Accept-CH: sec-ch-device-memory, device-memory, sec-ch-dpr, dpr, sec-ch-viewport-width, viewport-width, rtt, downlink, ect +Content-Security-Policy: sandbox allow-scripts \ No newline at end of file
diff --git a/third_party/blink/web_tests/external/wpt/client-hints/sandbox/iframe-iframe-popups.https.html b/third_party/blink/web_tests/external/wpt/client-hints/sandbox/iframe-iframe-popups.https.html new file mode 100644 index 0000000..e8852c9 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/client-hints/sandbox/iframe-iframe-popups.https.html
@@ -0,0 +1,18 @@ +<!DOCTYPE html> +<html> + +<body> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<script src="resources/util.js"></script> + +<script> + +sandbox_iframe_test("allow-scripts allow-popups", + "resources/iframe-with-embedded-popup-expect-no-hints.html", + "Popup from an iframe within a sandboxed iframe does not send hints"); + +</script> + +</body> +</html> \ No newline at end of file
diff --git a/third_party/blink/web_tests/external/wpt/client-hints/sandbox/iframe-iframe-popups.https.html.headers b/third_party/blink/web_tests/external/wpt/client-hints/sandbox/iframe-iframe-popups.https.html.headers new file mode 100644 index 0000000..53fe8f5 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/client-hints/sandbox/iframe-iframe-popups.https.html.headers
@@ -0,0 +1 @@ +Accept-CH: sec-ch-device-memory, device-memory, sec-ch-dpr, dpr, sec-ch-viewport-width, viewport-width, rtt, downlink, ect \ No newline at end of file
diff --git a/third_party/blink/web_tests/external/wpt/client-hints/sandbox/iframe-popups-escape-sandbox.https.html b/third_party/blink/web_tests/external/wpt/client-hints/sandbox/iframe-popups-escape-sandbox.https.html new file mode 100644 index 0000000..fbe723b --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/client-hints/sandbox/iframe-popups-escape-sandbox.https.html
@@ -0,0 +1,18 @@ +<!DOCTYPE html> +<html> + +<body> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<script src="resources/util.js"></script> + +<script> + +sandbox_iframe_test("allow-scripts allow-popups allow-popups-to-escape-sandbox", + "resources/embedded-popup-expect-hints.html", + "popup from sandboxed iframe with allow-popups-to-escape-sandbox flag does send client hint headers"); + +</script> + +</body> +</html> \ No newline at end of file
diff --git a/third_party/blink/web_tests/external/wpt/client-hints/sandbox/iframe-popups-escape-sandbox.https.html.headers b/third_party/blink/web_tests/external/wpt/client-hints/sandbox/iframe-popups-escape-sandbox.https.html.headers new file mode 100644 index 0000000..53fe8f5 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/client-hints/sandbox/iframe-popups-escape-sandbox.https.html.headers
@@ -0,0 +1 @@ +Accept-CH: sec-ch-device-memory, device-memory, sec-ch-dpr, dpr, sec-ch-viewport-width, viewport-width, rtt, downlink, ect \ No newline at end of file
diff --git a/third_party/blink/web_tests/external/wpt/client-hints/sandbox/iframe-popups.https.html b/third_party/blink/web_tests/external/wpt/client-hints/sandbox/iframe-popups.https.html new file mode 100644 index 0000000..9cb0713a --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/client-hints/sandbox/iframe-popups.https.html
@@ -0,0 +1,18 @@ +<!DOCTYPE html> +<html> + +<body> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<script src="resources/util.js"></script> + +<script> + +sandbox_iframe_test("allow-scripts allow-popups", + "resources/embedded-popup-expect-no-hints.html", + "popup from sandboxed iframe does not send client hint headers"); + +</script> + +</body> +</html> \ No newline at end of file
diff --git a/third_party/blink/web_tests/external/wpt/client-hints/sandbox/iframe-popups.https.html.headers b/third_party/blink/web_tests/external/wpt/client-hints/sandbox/iframe-popups.https.html.headers new file mode 100644 index 0000000..53fe8f5 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/client-hints/sandbox/iframe-popups.https.html.headers
@@ -0,0 +1 @@ +Accept-CH: sec-ch-device-memory, device-memory, sec-ch-dpr, dpr, sec-ch-viewport-width, viewport-width, rtt, downlink, ect \ No newline at end of file
diff --git a/third_party/blink/web_tests/external/wpt/client-hints/sandbox/iframe-same-origin.https.html b/third_party/blink/web_tests/external/wpt/client-hints/sandbox/iframe-same-origin.https.html new file mode 100644 index 0000000..e9a01f5 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/client-hints/sandbox/iframe-same-origin.https.html
@@ -0,0 +1,16 @@ +<!DOCTYPE html> +<html> + +<body> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<script src="resources/util.js"></script> + +<script> +sandbox_iframe_test("allow-scripts allow-same-origin", + expect_iframe_hints, + "Same origin sandboxed iframe with allow-same-origin flag does send client hint headers"); +</script> + +</body> +</html> \ No newline at end of file
diff --git a/third_party/blink/web_tests/external/wpt/client-hints/sandbox/iframe-same-origin.https.html.headers b/third_party/blink/web_tests/external/wpt/client-hints/sandbox/iframe-same-origin.https.html.headers new file mode 100644 index 0000000..53fe8f5 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/client-hints/sandbox/iframe-same-origin.https.html.headers
@@ -0,0 +1 @@ +Accept-CH: sec-ch-device-memory, device-memory, sec-ch-dpr, dpr, sec-ch-viewport-width, viewport-width, rtt, downlink, ect \ No newline at end of file
diff --git a/third_party/blink/web_tests/external/wpt/client-hints/sandbox/iframe.https.html b/third_party/blink/web_tests/external/wpt/client-hints/sandbox/iframe.https.html new file mode 100644 index 0000000..2d3e63c --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/client-hints/sandbox/iframe.https.html
@@ -0,0 +1,18 @@ +<!DOCTYPE html> +<html> + +<body> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<script src="resources/util.js"></script> + +<script> + +sandbox_iframe_test("allow-scripts", + expect_iframe_no_hints, + "sandboxed iframe does not send client hint headers"); + +</script> + +</body> +</html> \ No newline at end of file
diff --git a/third_party/blink/web_tests/external/wpt/client-hints/sandbox/iframe.https.html.headers b/third_party/blink/web_tests/external/wpt/client-hints/sandbox/iframe.https.html.headers new file mode 100644 index 0000000..53fe8f5 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/client-hints/sandbox/iframe.https.html.headers
@@ -0,0 +1 @@ +Accept-CH: sec-ch-device-memory, device-memory, sec-ch-dpr, dpr, sec-ch-viewport-width, viewport-width, rtt, downlink, ect \ No newline at end of file
diff --git a/third_party/blink/web_tests/external/wpt/client-hints/sandbox/resources/embedded-popup-expect-hints.html b/third_party/blink/web_tests/external/wpt/client-hints/sandbox/resources/embedded-popup-expect-hints.html new file mode 100644 index 0000000..6cd5f0a2 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/client-hints/sandbox/resources/embedded-popup-expect-hints.html
@@ -0,0 +1,11 @@ +<!DOCTYPE html> +<html> +<body> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<script src="util.js"></script> +<script> +sandbox_popup_listener("/client-hints/resources/expect-client-hints-headers.html"); +</script> +</body> +</html> \ No newline at end of file
diff --git a/third_party/blink/web_tests/external/wpt/client-hints/sandbox/resources/embedded-popup-expect-no-hints.html b/third_party/blink/web_tests/external/wpt/client-hints/sandbox/resources/embedded-popup-expect-no-hints.html new file mode 100644 index 0000000..46dbb7f23 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/client-hints/sandbox/resources/embedded-popup-expect-no-hints.html
@@ -0,0 +1,11 @@ +<!DOCTYPE html> +<html> +<body> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<script src="util.js"></script> +<script> +sandbox_popup_listener("/client-hints/resources/expect-no-client-hints-headers.html"); +</script> +</body> +</html> \ No newline at end of file
diff --git a/third_party/blink/web_tests/external/wpt/client-hints/sandbox/resources/iframe-with-embedded-popup-expect-no-hints.html b/third_party/blink/web_tests/external/wpt/client-hints/sandbox/resources/iframe-with-embedded-popup-expect-no-hints.html new file mode 100644 index 0000000..21efd76 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/client-hints/sandbox/resources/iframe-with-embedded-popup-expect-no-hints.html
@@ -0,0 +1,12 @@ +<!DOCTYPE html> +<html> +<body> +<script> + window.addEventListener('message', e => { + window.parent.postMessage(e.data, '*'); + }); + +</script> +<iframe src="embedded-popup-expect-no-hints.html" /> +</body> +</html> \ No newline at end of file
diff --git a/third_party/blink/web_tests/external/wpt/client-hints/sandbox/resources/util.js b/third_party/blink/web_tests/external/wpt/client-hints/sandbox/resources/util.js new file mode 100644 index 0000000..79e9a87b --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/client-hints/sandbox/resources/util.js
@@ -0,0 +1,48 @@ +const iframe_src = + "/client-hints/resources/expect-client-hints-headers-iframe.py"; + +const expect_iframe_no_hints = iframe_src + + "?sec-ch-device-memory=false" + + "&device-memory=false" + + "&sec-ch-dpr=false" + + "&dpr=false" + + "&sec-ch-viewport-width=false" + + "&viewport-width=false" + + "&sec-ch-ua=true" + + "&sec-ch-ua-mobile=true"; + +const expect_iframe_hints = iframe_src + + "?sec-ch-device-memory=true" + + "&device-memory=true" + + "&sec-ch-dpr=true" + + "&dpr=true" + + "&sec-ch-viewport-width=true" + + "&viewport-width=true" + + "&sec-ch-ua=true" + + "&sec-ch-ua-mobile=true"; + +function sandbox_iframe_test(sandbox, src, title) { + return promise_test(async t => { + const iframe = document.createElement("iframe"); + if (sandbox !== "") + iframe.sandbox = sandbox; + iframe.src = src; + + let msg = await new Promise(resolve => { + window.addEventListener('message', resolve); + document.body.appendChild(iframe); + }); + + assert_equals(msg.data, "PASS", "message from opened frame"); + await fetch("/client-hints/accept-ch-stickiness/resources/clear-site-data.html"); + }, title); +} + +function sandbox_popup_listener(src) { + window.addEventListener('message', e => { + window.parent.postMessage(e.data, '*'); + }); + + let popup_window = window.open("/resources/blank.html"); + popup_window.location.href = src; +} \ No newline at end of file
diff --git a/third_party/blink/web_tests/external/wpt/css/README.md b/third_party/blink/web_tests/external/wpt/css/README.md index 6ce0dd3..20f1e60 100644 --- a/third_party/blink/web_tests/external/wpt/css/README.md +++ b/third_party/blink/web_tests/external/wpt/css/README.md
@@ -22,41 +22,4 @@ `css` directory. -Importing Old Branches ----------------------- - -Given an old branch in git based against the old csswg-test -repository, it can be moved over to the merged repo in one of two -ways: - - * (Recommended:) Rebasing on top of web-platform-tests: with the old - branch checked out, run `git rebase -Xsubtree=css/ origin/master` - (or similar, depending on the name of the upstream remote). - - * Merging to web-platform-tests: with web-platform-tests' master - branch checked out, run `git merge -Xsubtree=css/ my_shiny_branch` - (or similar, depending on the name of your branch). - -If you have a branch/bookmark in Mercurial, the process is more -complicated: - - 1. From the Mercurial repo, run `hg export --git -r 'outgoing()' > - foo.patch`. This will export all the changeset shown in `hg log -r - 'outgoing()'`; it's recommended you check this is the right set of - changesets before continuing! - - 2. Move to the git repo, and create a new branch based on - web-platform-tests' master; e.g., `git checkout -b hg-import - origin/master` (or similar, depending on the name of the upstream - remote). - - 3. Download [hg-patch-to-git-patch][] and run `python2 - hg-patch-to-git-patch < foo.patch > bar.patch` (where `foo.patch` - is the path to the `foo.patch` you exported above). - - 4. Run `git am --directory=css/ < bar.patch`. - - -[harness]: https://test.csswg.org/harness/ [spec-link]: https://web-platform-tests.org/writing-tests/css-metadata.html#specification-links -[hg-patch-to-git-patch]: https://raw.githubusercontent.com/mozilla/moz-git-tools/master/hg-patch-to-git-patch
diff --git a/third_party/blink/web_tests/external/wpt/css/css-break/flexbox/multi-line-row-flex-fragmentation-046.html b/third_party/blink/web_tests/external/wpt/css/css-break/flexbox/multi-line-row-flex-fragmentation-046.html index 03f6770..99e2533 100644 --- a/third_party/blink/web_tests/external/wpt/css/css-break/flexbox/multi-line-row-flex-fragmentation-046.html +++ b/third_party/blink/web_tests/external/wpt/css/css-break/flexbox/multi-line-row-flex-fragmentation-046.html
@@ -6,10 +6,10 @@ <link rel="match" href="../../reference/ref-filled-green-100px-square.xht"> <p>Test passes if there is a filled green square and <strong>no red</strong>.</p> <div style="width: 100px; height: 100px; columns: 2; column-fill: auto; column-gap: 0; background: red;"> - <div style="display: flex; flex-wrap: wrap;"> - <div style="height: 20px; width: 50px; background: green;"></div> - <div style="min-height: 90px;"> - <div style="height: 200%; width: 50px; background: green;"></div> + <div style="display: flex; flex-wrap: wrap; min-height: 200px;"> + <div style="flex: 0.5; width: 50px; background: green;"></div> + <div style="flex: 0.5; background: green;"> + <div style="height: 200%; width: 50px;"></div> </div> </div> </div>
diff --git a/third_party/blink/web_tests/external/wpt/css/css-break/flexbox/single-line-row-flex-fragmentation-026.html b/third_party/blink/web_tests/external/wpt/css/css-break/flexbox/single-line-row-flex-fragmentation-026.html index d88d93b2..9a78bf50 100644 --- a/third_party/blink/web_tests/external/wpt/css/css-break/flexbox/single-line-row-flex-fragmentation-026.html +++ b/third_party/blink/web_tests/external/wpt/css/css-break/flexbox/single-line-row-flex-fragmentation-026.html
@@ -6,9 +6,9 @@ <link rel="match" href="../../reference/ref-filled-green-100px-square.xht"> <p>Test passes if there is a filled green square and <strong>no red</strong>.</p> <div style="width: 100px; height: 100px; columns: 2; column-fill: auto; column-gap: 0; background: red;"> - <div style="display: flex;"> - <div style="min-height: 100px;"> - <div style="height: 200%; width: 50px; background: green;"></div> + <div style="display: flex; min-height: 200px;"> + <div style="flex: 1; background: green;"> + <div style="height: 200%;"></div> </div> </div> </div>
diff --git a/third_party/blink/web_tests/external/wpt/css/cssom-view/pt-to-px-width.html b/third_party/blink/web_tests/external/wpt/css/cssom-view/pt-to-px-width.html new file mode 100644 index 0000000..485149a --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/css/cssom-view/pt-to-px-width.html
@@ -0,0 +1,21 @@ +<!DOCTYPE html> +<meta charset="utf-8"> +<title>10pt converted to offset/client/scroll width</title> +<link rel="help" href="https://www.w3.org/TR/css-values-4/#absolute-lengths"> + +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<style> +/* According to the CSS Values specification 10pt is abour 13.33px. */ +#target { width: 10pt; } +</style> + +<div id="target"></div> + +<script> +test(() => { + assert_equals(target.scrollWidth, 13, "scrollWidth"); + assert_equals(target.offsetWidth, 13, "offsetWidth"); + assert_equals(target.clientWidth, 13, "clientWidth"); +}); +</script>
diff --git a/third_party/blink/web_tests/external/wpt/docs/frontend.py b/third_party/blink/web_tests/external/wpt/docs/frontend.py index 9397e05..3f06e3c 100644 --- a/third_party/blink/web_tests/external/wpt/docs/frontend.py +++ b/third_party/blink/web_tests/external/wpt/docs/frontend.py
@@ -108,7 +108,7 @@ sys.exit(1) if kwargs["serve"] is not None: executable = "sphinx-autobuild" - extras = ["-p", str(kwargs["serve"]), + extras = ["--port", str(kwargs["serve"]), "--host", "0.0.0.0", "--watch", os.path.abspath(os.path.join(here, os.pardir, "resources")), # Ignore changes to files specified with glob pattern
diff --git a/third_party/blink/web_tests/external/wpt/docs/requirements.txt b/third_party/blink/web_tests/external/wpt/docs/requirements.txt index 66d6646..1cdeadd2 100644 --- a/third_party/blink/web_tests/external/wpt/docs/requirements.txt +++ b/third_party/blink/web_tests/external/wpt/docs/requirements.txt
@@ -1,6 +1,6 @@ recommonmark==0.7.1 sphinx-argparse==0.3.1 -sphinx-autobuild==0.7.1 +sphinx-autobuild==2021.3.14 sphinx-js==3.1.2 sphinx==4.4.0 markupsafe==2.0.1
diff --git a/third_party/blink/web_tests/images/zoomed-offset-size-expected.txt b/third_party/blink/web_tests/images/zoomed-offset-size-expected.txt deleted file mode 100644 index 53872b623..0000000 --- a/third_party/blink/web_tests/images/zoomed-offset-size-expected.txt +++ /dev/null
@@ -1,4 +0,0 @@ -This is a testharness.js-based test. -FAIL Image should return a size of 250x166 regardless of zoom level. assert_equals: expected 250 but got 251 -Harness: the test ran to completion. -
diff --git a/third_party/blink/web_tests/images/zoomed-offset-size.html b/third_party/blink/web_tests/images/zoomed-offset-size.html index 2153eba..28d48f8 100644 --- a/third_party/blink/web_tests/images/zoomed-offset-size.html +++ b/third_party/blink/web_tests/images/zoomed-offset-size.html
@@ -15,7 +15,7 @@ assert_equals(wrapElement.offsetWidth, 250); assert_equals(wrapElement.offsetHeight, 166); } - for (var i = 90; i <= 200; i += 5) + for (var i = 100; i <= 200; i += 25) testSize(i/100); document.body.style.zoom = 1.0; });
diff --git a/third_party/blink/web_tests/platform/linux/fast/forms/color/color-picker-appearance-zoom200-expected.png b/third_party/blink/web_tests/platform/linux/fast/forms/color/color-picker-appearance-zoom200-expected.png index 7873f8a..63f475f 100644 --- a/third_party/blink/web_tests/platform/linux/fast/forms/color/color-picker-appearance-zoom200-expected.png +++ b/third_party/blink/web_tests/platform/linux/fast/forms/color/color-picker-appearance-zoom200-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac-mac11-arm64/fast/forms/color/color-picker-appearance-zoom200-expected.png b/third_party/blink/web_tests/platform/mac-mac11-arm64/fast/forms/color/color-picker-appearance-zoom200-expected.png index 320f805..3dc0d45 100644 --- a/third_party/blink/web_tests/platform/mac-mac11-arm64/fast/forms/color/color-picker-appearance-zoom200-expected.png +++ b/third_party/blink/web_tests/platform/mac-mac11-arm64/fast/forms/color/color-picker-appearance-zoom200-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/mac/fast/forms/color/color-picker-appearance-zoom200-expected.png b/third_party/blink/web_tests/platform/mac/fast/forms/color/color-picker-appearance-zoom200-expected.png index 36985edc..35a0d839 100644 --- a/third_party/blink/web_tests/platform/mac/fast/forms/color/color-picker-appearance-zoom200-expected.png +++ b/third_party/blink/web_tests/platform/mac/fast/forms/color/color-picker-appearance-zoom200-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/win/fast/forms/color/color-picker-appearance-zoom200-expected.png b/third_party/blink/web_tests/platform/win/fast/forms/color/color-picker-appearance-zoom200-expected.png index 65b873d..b17a6d4 100644 --- a/third_party/blink/web_tests/platform/win/fast/forms/color/color-picker-appearance-zoom200-expected.png +++ b/third_party/blink/web_tests/platform/win/fast/forms/color/color-picker-appearance-zoom200-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/platform/win10/fast/forms/color/color-picker-appearance-zoom200-expected.png b/third_party/blink/web_tests/platform/win10/fast/forms/color/color-picker-appearance-zoom200-expected.png new file mode 100644 index 0000000..b17a6d4 --- /dev/null +++ b/third_party/blink/web_tests/platform/win10/fast/forms/color/color-picker-appearance-zoom200-expected.png Binary files differ
diff --git a/third_party/blink/web_tests/virtual/disable-user-agent-client-hint-feature/external/wpt/client-hints/sandbox/iframe-csp-same-origin.https-expected.txt b/third_party/blink/web_tests/virtual/disable-user-agent-client-hint-feature/external/wpt/client-hints/sandbox/iframe-csp-same-origin.https-expected.txt new file mode 100644 index 0000000..bcecb57 --- /dev/null +++ b/third_party/blink/web_tests/virtual/disable-user-agent-client-hint-feature/external/wpt/client-hints/sandbox/iframe-csp-same-origin.https-expected.txt
@@ -0,0 +1,4 @@ +This is a testharness.js-based test. +FAIL CSP sandboxed iframe with same-origin flag does send client hint headers assert_equals: message from opened frame expected "PASS" but got "FAIL Sec-CH-UA True None" +Harness: the test ran to completion. +
diff --git a/third_party/blink/web_tests/virtual/disable-user-agent-client-hint-feature/external/wpt/client-hints/sandbox/iframe-csp.https-expected.txt b/third_party/blink/web_tests/virtual/disable-user-agent-client-hint-feature/external/wpt/client-hints/sandbox/iframe-csp.https-expected.txt new file mode 100644 index 0000000..20e5769 --- /dev/null +++ b/third_party/blink/web_tests/virtual/disable-user-agent-client-hint-feature/external/wpt/client-hints/sandbox/iframe-csp.https-expected.txt
@@ -0,0 +1,4 @@ +This is a testharness.js-based test. +FAIL CSP sandboxed iframe does not send client hint headers assert_equals: message from opened frame expected "PASS" but got "FAIL Sec-CH-UA True None" +Harness: the test ran to completion. +
diff --git a/third_party/blink/web_tests/virtual/disable-user-agent-client-hint-feature/external/wpt/client-hints/sandbox/iframe-same-origin.https-expected.txt b/third_party/blink/web_tests/virtual/disable-user-agent-client-hint-feature/external/wpt/client-hints/sandbox/iframe-same-origin.https-expected.txt new file mode 100644 index 0000000..84b6d5b --- /dev/null +++ b/third_party/blink/web_tests/virtual/disable-user-agent-client-hint-feature/external/wpt/client-hints/sandbox/iframe-same-origin.https-expected.txt
@@ -0,0 +1,4 @@ +This is a testharness.js-based test. +FAIL Same origin sandboxed iframe with allow-same-origin flag does send client hint headers assert_equals: message from opened frame expected "PASS" but got "FAIL Sec-CH-UA True None" +Harness: the test ran to completion. +
diff --git a/third_party/blink/web_tests/virtual/disable-user-agent-client-hint-feature/external/wpt/client-hints/sandbox/iframe.https-expected.txt b/third_party/blink/web_tests/virtual/disable-user-agent-client-hint-feature/external/wpt/client-hints/sandbox/iframe.https-expected.txt new file mode 100644 index 0000000..0c528597 --- /dev/null +++ b/third_party/blink/web_tests/virtual/disable-user-agent-client-hint-feature/external/wpt/client-hints/sandbox/iframe.https-expected.txt
@@ -0,0 +1,4 @@ +This is a testharness.js-based test. +FAIL sandboxed iframe does not send client hint headers assert_equals: message from opened frame expected "PASS" but got "FAIL Sec-CH-UA True None" +Harness: the test ran to completion. +
diff --git a/third_party/blink/web_tests/virtual/shared-storage-fenced-frame-mparch/README.md b/third_party/blink/web_tests/virtual/shared-storage-fenced-frame-mparch/README.md new file mode 100644 index 0000000..ee9850c --- /dev/null +++ b/third_party/blink/web_tests/virtual/shared-storage-fenced-frame-mparch/README.md
@@ -0,0 +1,8 @@ +# Shared Storage + +The tests are run with the flag --enable-features=SharedStorageAPI,FencedFrames:implementation\_type/mparch + +You can run these tests by targeting the following directory: +`virtual/shared-storage-fenced-frame-mparch/wpt_internal/shared_storage. + +See crbug.com/1218540.
diff --git a/third_party/blink/web_tests/virtual/shared-storage-fenced-frame-shadow-dom/README.md b/third_party/blink/web_tests/virtual/shared-storage-fenced-frame-shadow-dom/README.md new file mode 100644 index 0000000..b4d8990 --- /dev/null +++ b/third_party/blink/web_tests/virtual/shared-storage-fenced-frame-shadow-dom/README.md
@@ -0,0 +1,8 @@ +# Shared Storage + +The tests are run with the flag --enable-features=SharedStorageAPI,FencedFrames:implementation\_type/shadow\_dom + +You can run these tests by targeting the following directory: +`virtual/shared-storage-fenced-frame-shadow-dom/wpt_internal/shared_storage. + +See crbug.com/1218540.
diff --git a/third_party/blink/web_tests/virtual/shared-storage/README.md b/third_party/blink/web_tests/virtual/shared-storage/README.md deleted file mode 100644 index b623009..0000000 --- a/third_party/blink/web_tests/virtual/shared-storage/README.md +++ /dev/null
@@ -1,5 +0,0 @@ -# Shared Storage - -The tests are run with the flag --enable-features=SharedStorageAPI,FencedFrames - -See crbug.com/1218540.
diff --git a/third_party/blink/web_tests/virtual/stable/webexposed/feature-policy-features-expected.txt b/third_party/blink/web_tests/virtual/stable/webexposed/feature-policy-features-expected.txt index 98cce56e..6133725 100644 --- a/third_party/blink/web_tests/virtual/stable/webexposed/feature-policy-features-expected.txt +++ b/third_party/blink/web_tests/virtual/stable/webexposed/feature-policy-features-expected.txt
@@ -43,7 +43,6 @@ publickey-credentials-get screen-wake-lock serial -shared-autofill sync-xhr usb window-placement
diff --git a/third_party/blink/web_tests/wpt_internal/document-transition/duplicate_tag_rejects.html b/third_party/blink/web_tests/wpt_internal/document-transition/duplicate_tag_rejects.html index 40d674494..33c0f10 100644 --- a/third_party/blink/web_tests/wpt_internal/document-transition/duplicate_tag_rejects.html +++ b/third_party/blink/web_tests/wpt_internal/document-transition/duplicate_tag_rejects.html
@@ -22,33 +22,29 @@ <script> promise_test(async t => { return new Promise((resolve, reject) => { - document.createDocumentTransition(async transition => { - transition.setElement(first, "target"); - transition.setElement(first, "target"); - await transition.captureAndHold().then(() => - transition.start().then(resolve, reject)); - }); + let transition = document.createDocumentTransition(); + transition.setElement(first, "target"); + transition.setElement(first, "target"); + transition.start(()=>{}).then(resolve, reject); }); }, "Same element with the same tag is no-op"); promise_test(async t => { return new Promise((resolve, reject) => { - document.createDocumentTransition(async transition => { - transition.setElement(first, "target"); - transition.setElement(second, "target"); - transition.captureAndHold().then(reject, resolve); - }); + let transition = document.createDocumentTransition(); + transition.setElement(first, "target"); + transition.setElement(second, "target"); + transition.start(()=>{}).then(reject, resolve); }); }, "Two different elements with the same tag rejects capture"); promise_test(async t => { return new Promise((resolve, reject) => { - document.createDocumentTransition(async transition => { - transition.setElement(first, "target"); - await transition.captureAndHold(); + let transition = document.createDocumentTransition(); + transition.setElement(first, "target"); + transition.start(() => { transition.setElement(second, "target"); - transition.start().then(reject, resolve); - }); + }).then(reject, resolve); }); }, "Two different elements with the same tag rejects start"); </script>
diff --git a/third_party/blink/web_tests/wpt_internal/document-transition/new-content-captures-clip-path.html b/third_party/blink/web_tests/wpt_internal/document-transition/new-content-captures-clip-path.html index 893b1856..9e4552c1 100644 --- a/third_party/blink/web_tests/wpt_internal/document-transition/new-content-captures-clip-path.html +++ b/third_party/blink/web_tests/wpt_internal/document-transition/new-content-captures-clip-path.html
@@ -34,12 +34,10 @@ <div id=e1 class=box></div> <script> async function runTest() { - document.createDocumentTransition(async (t) => { - t.setElement(e1, "e1"); - await t.captureAndHold(); + let t = document.createDocumentTransition(); + t.setElement(e1, "e1"); + t.start(() => { e1.classList.add("dst"); - t.start(); - requestAnimationFrame(() => requestAnimationFrame(takeScreenshot)); }); }
diff --git a/third_party/blink/web_tests/wpt_internal/document-transition/new-content-captures-different-size.html b/third_party/blink/web_tests/wpt_internal/document-transition/new-content-captures-different-size.html index e854acb..ddb495489 100644 --- a/third_party/blink/web_tests/wpt_internal/document-transition/new-content-captures-different-size.html +++ b/third_party/blink/web_tests/wpt_internal/document-transition/new-content-captures-different-size.html
@@ -45,19 +45,16 @@ <div id=e3 class=box>three</div> <script> async function runTest() { - document.createDocumentTransition(async (t) => { - t.setElement(e1, "e1"); - t.setElement(e2, "e2"); - t.setElement(e3, "e3"); - await t.captureAndHold(); - + let t = document.createDocumentTransition(); + t.setElement(e1, "e1"); + t.setElement(e2, "e2"); + t.setElement(e3, "e3"); + t.start(() => { e1.classList.add("dst"); e2.classList.add("dst"); e3.classList.add("dst"); - - t.start(); + requestAnimationFrame(() => requestAnimationFrame(takeScreenshot)); }); - requestAnimationFrame(() => requestAnimationFrame(takeScreenshot)); } onload = () => requestAnimationFrame(() => requestAnimationFrame(runTest)); </script>
diff --git a/third_party/blink/web_tests/wpt_internal/document-transition/new-content-captures-opacity.html b/third_party/blink/web_tests/wpt_internal/document-transition/new-content-captures-opacity.html index f1a79e9..901f63c5 100644 --- a/third_party/blink/web_tests/wpt_internal/document-transition/new-content-captures-opacity.html +++ b/third_party/blink/web_tests/wpt_internal/document-transition/new-content-captures-opacity.html
@@ -33,18 +33,14 @@ <div id=e3 class=box></div> <script> async function runTest() { - document.createDocumentTransition(async (t) => { - t.setElement(e1, "e1"); - t.setElement(e2, "e2"); - t.setElement(e3, "e3"); - await t.captureAndHold(); - + let t = document.createDocumentTransition(); + t.setElement(e1, "e1"); + t.setElement(e2, "e2"); + t.setElement(e3, "e3"); + t.start(() => { e1.classList.add("dst"); e2.classList.add("dst"); e3.classList.add("dst"); - - t.start(); - requestAnimationFrame(() => requestAnimationFrame(takeScreenshot)); }); }
diff --git a/third_party/blink/web_tests/wpt_internal/document-transition/new-content-captures-root.html b/third_party/blink/web_tests/wpt_internal/document-transition/new-content-captures-root.html index 8f1ae23..a31e05b9 100644 --- a/third_party/blink/web_tests/wpt_internal/document-transition/new-content-captures-root.html +++ b/third_party/blink/web_tests/wpt_internal/document-transition/new-content-captures-root.html
@@ -37,15 +37,10 @@ <div id=shared></div> <script> async function runTest() { - document.createDocumentTransition(async (t) => { - t.setElement(shared, "shared"); - - await t.captureAndHold(); - + let t = document.createDocumentTransition(); + t.setElement(shared, "shared"); + t.start(() => { e1.classList.add("dst"); - - t.start(); - requestAnimationFrame(() => requestAnimationFrame(takeScreenshot)); }); }
diff --git a/third_party/blink/web_tests/wpt_internal/document-transition/new-element-on-start.html b/third_party/blink/web_tests/wpt_internal/document-transition/new-element-on-start.html index ff1b0b7e..be97f0e 100644 --- a/third_party/blink/web_tests/wpt_internal/document-transition/new-element-on-start.html +++ b/third_party/blink/web_tests/wpt_internal/document-transition/new-element-on-start.html
@@ -53,20 +53,14 @@ <script> async function runTest() { - document.createDocumentTransition(async (t) => { - t.setElement(hidden, "hidden"); - - t.setElement(before, "before"); - - await t.captureAndHold(); - + let t = document.createDocumentTransition(); + t.setElement(hidden, "hidden"); + t.setElement(before, "before"); + t.start(() => { t.setElement(before, null); before.remove(); - t.setElement(after, "after"); - t.start(); - requestAnimationFrame(() => requestAnimationFrame(takeScreenshot)) }); }
diff --git a/third_party/blink/web_tests/wpt_internal/document-transition/old-content-captures-clip-path.html b/third_party/blink/web_tests/wpt_internal/document-transition/old-content-captures-clip-path.html index 9958196..1d67b999 100644 --- a/third_party/blink/web_tests/wpt_internal/document-transition/old-content-captures-clip-path.html +++ b/third_party/blink/web_tests/wpt_internal/document-transition/old-content-captures-clip-path.html
@@ -33,14 +33,10 @@ <div id=e1 class=box></div> <script> async function runTest() { - document.createDocumentTransition(async (t) => { - t.setElement(e1, "e1"); - await t.captureAndHold(); - + let t = document.createDocumentTransition(); + t.setElement(e1, "e1"); + t.start(() => { e1.classList.add("dst"); - - t.start(); - requestAnimationFrame(() => requestAnimationFrame(takeScreenshot)); }); }
diff --git a/third_party/blink/web_tests/wpt_internal/document-transition/old-content-captures-different-size.html b/third_party/blink/web_tests/wpt_internal/document-transition/old-content-captures-different-size.html index 2e5c66b4d..bbf5ab2 100644 --- a/third_party/blink/web_tests/wpt_internal/document-transition/old-content-captures-different-size.html +++ b/third_party/blink/web_tests/wpt_internal/document-transition/old-content-captures-different-size.html
@@ -45,18 +45,14 @@ <div id=e3 class=box>three</div> <script> async function runTest() { - document.createDocumentTransition(async (t) => { - t.setElement(e1, "e1"); - t.setElement(e2, "e2"); - t.setElement(e3, "e3"); - await t.captureAndHold(); - + let t = document.createDocumentTransition(); + t.setElement(e1, "e1"); + t.setElement(e2, "e2"); + t.setElement(e3, "e3"); + t.start(() => { e1.classList.add("dst"); e2.classList.add("dst"); e3.classList.add("dst"); - - t.start(); - requestAnimationFrame(() => requestAnimationFrame(takeScreenshot)); }); }
diff --git a/third_party/blink/web_tests/wpt_internal/document-transition/old-content-captures-opacity.html b/third_party/blink/web_tests/wpt_internal/document-transition/old-content-captures-opacity.html index db57c1b..1841faa 100644 --- a/third_party/blink/web_tests/wpt_internal/document-transition/old-content-captures-opacity.html +++ b/third_party/blink/web_tests/wpt_internal/document-transition/old-content-captures-opacity.html
@@ -34,18 +34,14 @@ <div id=e3 class=box>three</div> <script> async function runTest() { - document.createDocumentTransition(async (t) => { - t.setElement(e1, "e1"); - t.setElement(e2, "e2"); - t.setElement(e3, "e3"); - await t.captureAndHold(); - + let t = document.createDocumentTransition(); + t.setElement(e1, "e1"); + t.setElement(e2, "e2"); + t.setElement(e3, "e3"); + t.start(() => { e1.classList.add("dst"); e2.classList.add("dst"); e3.classList.add("dst"); - - t.start(); - requestAnimationFrame(() => requestAnimationFrame(takeScreenshot)); }); }
diff --git a/third_party/blink/web_tests/wpt_internal/document-transition/old-content-captures-root.html b/third_party/blink/web_tests/wpt_internal/document-transition/old-content-captures-root.html index ce187204..67a8636 100644 --- a/third_party/blink/web_tests/wpt_internal/document-transition/old-content-captures-root.html +++ b/third_party/blink/web_tests/wpt_internal/document-transition/old-content-captures-root.html
@@ -37,15 +37,10 @@ <div id=shared></div> <script> async function runTest() { - document.createDocumentTransition(async (t) => { - t.setElement(shared, "shared"); - - await t.captureAndHold(); - + let t = document.createDocumentTransition(); + t.setElement(shared, "shared"); + t.start(() => { e1.classList.add("dst"); - - t.start(); - requestAnimationFrame(() => requestAnimationFrame(takeScreenshot)); }); }
diff --git a/third_party/blink/web_tests/wpt_internal/document-transition/one-element-two-targets.html b/third_party/blink/web_tests/wpt_internal/document-transition/one-element-two-targets.html index 1cf84c5..248765a8 100644 --- a/third_party/blink/web_tests/wpt_internal/document-transition/one-element-two-targets.html +++ b/third_party/blink/web_tests/wpt_internal/document-transition/one-element-two-targets.html
@@ -57,20 +57,16 @@ <script> async function runTest() { - document.createDocumentTransition(async (t) => { - t.setElement(hidden, "hidden"); + let t = document.createDocumentTransition(); + t.setElement(hidden, "hidden"); - t.setElement(from, "target1"); - t.setElement(from, "target2"); - - await t.captureAndHold(); - + t.setElement(from, "target1"); + t.setElement(from, "target2"); + t.start(() => { t.setElement(from, null); t.setElement(left, "target1"); t.setElement(right, "target2"); - t.start(); - requestAnimationFrame(() => requestAnimationFrame(() => requestAnimationFrame(() => requestAnimationFrame(takeScreenshot)) ));
diff --git a/third_party/blink/web_tests/wpt_internal/document-transition/reserved_root_tag_rejects.html b/third_party/blink/web_tests/wpt_internal/document-transition/reserved_root_tag_rejects.html index a43945e1..bfa3f13 100644 --- a/third_party/blink/web_tests/wpt_internal/document-transition/reserved_root_tag_rejects.html +++ b/third_party/blink/web_tests/wpt_internal/document-transition/reserved_root_tag_rejects.html
@@ -21,22 +21,20 @@ <script> promise_test(async t => { return new Promise((resolve, reject) => { - document.createDocumentTransition(transition => { - transition.setElement(target, "root"); - transition.captureAndHold().then(reject, resolve); - }); + let transition = document.createDocumentTransition(); + transition.setElement(target, "root"); + transition.start().then(reject, resolve); }); }, "Root tag on an element rejects capture"); promise_test(async t => { return new Promise((resolve, reject) => { - document.createDocumentTransition(async transition => { - transition.setElement(target, "foo"); - await transition.captureAndHold(); + let transition = document.createDocumentTransition(); + transition.setElement(target, "foo"); + transition.start(() => { transition.setElement(target, null); transition.setElement(target, "root"); - transition.start().then(reject, resolve); - }); + }).then(reject, resolve); }); }, "Root tag on an element rejects start"); </script>
diff --git a/third_party/blink/web_tests/wpt_internal/document-transition/root-scrollbar-with-fixed-background.html b/third_party/blink/web_tests/wpt_internal/document-transition/root-scrollbar-with-fixed-background.html index 3de6696..6043a73 100644 --- a/third_party/blink/web_tests/wpt_internal/document-transition/root-scrollbar-with-fixed-background.html +++ b/third_party/blink/web_tests/wpt_internal/document-transition/root-scrollbar-with-fixed-background.html
@@ -51,10 +51,9 @@ await waitForAtLeastOneFrame(); document.documentElement.scrollTop = 500; - document.createDocumentTransition(async (t) => { - t.setElement(hide, "hide"); - await t.captureAndHold(); - t.start(); + let t = document.createDocumentTransition(); + t.setElement(hide, "hide"); + t.start(() => { requestAnimationFrame(() => requestAnimationFrame(takeScreenshot)); }); }
diff --git a/third_party/blink/web_tests/wpt_internal/document-transition/shared-transition-author-style.manual.html b/third_party/blink/web_tests/wpt_internal/document-transition/shared-transition-author-style.manual.html index 38e8c7c..bbd1b50b8 100644 --- a/third_party/blink/web_tests/wpt_internal/document-transition/shared-transition-author-style.manual.html +++ b/third_party/blink/web_tests/wpt_internal/document-transition/shared-transition-author-style.manual.html
@@ -75,20 +75,16 @@ pseudoStyle.appendChild(document.createTextNode(transitionStyle)); async function runAnimation() { - document.createDocumentTransition(async (t) => { - t.setElement(target, "target"); - await t.captureAndHold(); - + let t = document.createDocumentTransition(); + t.setElement(target, "target"); + await t.start(() => { target.classList.remove(classes[i]); i = (i + 1) % classes.length; target.classList.add(classes[i]); document.head.appendChild(pseudoStyle); - - await t.start(); - - document.head.removeChild(pseudoStyle); }); + document.head.removeChild(pseudoStyle) } function init() {
diff --git a/third_party/blink/web_tests/wpt_internal/document-transition/shared-transition-half.manual.html b/third_party/blink/web_tests/wpt_internal/document-transition/shared-transition-half.manual.html index 90ee5b8..4a45e55 100644 --- a/third_party/blink/web_tests/wpt_internal/document-transition/shared-transition-half.manual.html +++ b/third_party/blink/web_tests/wpt_internal/document-transition/shared-transition-half.manual.html
@@ -44,15 +44,12 @@ let classes = ["top", "bottom"] let i = 0; async function runAnimation() { - document.createDocumentTransition(async (t) => { - t.setElement(target, "target"); - await t.captureAndHold(); - + let t = document.createDocumentTransition(); + t.setElement(target, "target"); + await t.start(() => { target.classList.remove(classes[i]); i = (i + 1) % classes.length; target.classList.add(classes[i]); - - await t.start(); }); }
diff --git a/third_party/blink/web_tests/wpt_internal/document-transition/shared-transition-shapes.manual.html b/third_party/blink/web_tests/wpt_internal/document-transition/shared-transition-shapes.manual.html index 8a06dbad..9963eefe 100644 --- a/third_party/blink/web_tests/wpt_internal/document-transition/shared-transition-shapes.manual.html +++ b/third_party/blink/web_tests/wpt_internal/document-transition/shared-transition-shapes.manual.html
@@ -60,19 +60,16 @@ let classes = ["left", "right"] let i = 0; async function runAnimation() { - document.createDocumentTransition(async (t) => { - t.setElement(e1, "e1"); - t.setElement(e2, "e2"); - t.setElement(e3, "e3"); - t.setElement(e4, "e4"); - t.setElement(e5, "e5"); - await t.captureAndHold(); - + let t = document.createDocumentTransition(); + t.setElement(e1, "e1"); + t.setElement(e2, "e2"); + t.setElement(e3, "e3"); + t.setElement(e4, "e4"); + t.setElement(e5, "e5"); + await t.start(() => { container.classList.remove(classes[i]); i = (i + 1) % classes.length; container.classList.add(classes[i]); - - await t.start(); }); }
diff --git a/third_party/blink/web_tests/wpt_internal/document-transition/transition-waits-for-animations.html b/third_party/blink/web_tests/wpt_internal/document-transition/transition-waits-for-animations.html index 204e891..9da3cc84 100644 --- a/third_party/blink/web_tests/wpt_internal/document-transition/transition-waits-for-animations.html +++ b/third_party/blink/web_tests/wpt_internal/document-transition/transition-waits-for-animations.html
@@ -34,14 +34,11 @@ <script> async function startTransition() { - document.createDocumentTransition(async (t) => { - t.setElement(e1, "e1"); - await t.captureAndHold(); - + let t = document.createDocumentTransition(); + t.setElement(e1, "e1"); + t.start(() => { e1.classList.remove("left"); e1.classList.add("right"); - - t.start(); }); }
diff --git a/third_party/blink/web_tests/wpt_internal/document-transition/two-elements-one-target.html b/third_party/blink/web_tests/wpt_internal/document-transition/two-elements-one-target.html index 4345be8..fb1886e1 100644 --- a/third_party/blink/web_tests/wpt_internal/document-transition/two-elements-one-target.html +++ b/third_party/blink/web_tests/wpt_internal/document-transition/two-elements-one-target.html
@@ -62,21 +62,16 @@ <script> async function runTest() { - document.createDocumentTransition(async (t) => { - t.setElement(hidden, "hidden"); - - t.setElement(left, "target1"); - t.setElement(right, "target2"); - - await t.captureAndHold(); - + let t = document.createDocumentTransition(); + t.setElement(hidden, "hidden"); + t.setElement(left, "target1"); + t.setElement(right, "target2"); + t.start(() => { t.setElement(left, null); t.setElement(right, null); t.setElement(to, "target1"); t.setElement(to, "target2"); - t.start(); - requestAnimationFrame(() => requestAnimationFrame(takeScreenshot)) }); }
diff --git a/third_party/blink/web_tests/wpt_internal/document-transition/uncontained-transition-crash.html b/third_party/blink/web_tests/wpt_internal/document-transition/uncontained-transition-crash.html index 1f6c8836..6489709a 100644 --- a/third_party/blink/web_tests/wpt_internal/document-transition/uncontained-transition-crash.html +++ b/third_party/blink/web_tests/wpt_internal/document-transition/uncontained-transition-crash.html
@@ -31,23 +31,21 @@ async function runTest() { await waitForAtLeastOneFrame(); // Prepare with a shared element - document.createDocumentTransition(async (t) => { - t.setElement(first, "shared"); - let promise = t.captureAndHold(); - - // Force a hit test, which will determine compositing reasons. - document.elementFromPoint(0, 0); - - // Now wait for the capture to happen. This will note that we don't have - // paint containment and should de-composite the element. - await promise; - + let t = document.createDocumentTransition(); + t.setElement(first, "shared"); + let promise = t.start(() => { t.setElement(first, null); t.setElement(second, "shared"); - - t.start(); }); + // The start() call above starts the capture. Force a hit test, which will + // determine compositing reasons. + document.elementFromPoint(0, 0); + + // Wait for the transition to finish. This will note that we don't have + // paint containment and should de-composite the element. + await promise; + takeScreenshot(); }
diff --git a/third_party/expat/README.chromium b/third_party/expat/README.chromium index 2dcae63a..190f65a9 100644 --- a/third_party/expat/README.chromium +++ b/third_party/expat/README.chromium
@@ -1,10 +1,10 @@ Name: Expat XML Parser Short Name: expat URL: https://github.com/libexpat/libexpat -Version: R_2_4_5-9-g65a21f2b -CPEPrefix: cpe:/a:libexpat:expat:2.4.5 -Date: 20220222 -Revision: 65a21f2b2a306d29b44e70264aca948aa0454219 +Version: R_2_4_7-4-g53fbdf5b +CPEPrefix: cpe:/a:libexpat:expat:2.4.7 +Date: 20220309 +Revision: 53fbdf5b8925a426e1b41a9e09b833986b87524e Security Critical: yes License: MIT License File: src/expat/COPYING
diff --git a/third_party/expat/include/expat_config/expat_config.h b/third_party/expat/include/expat_config/expat_config.h index 3324ceb..07ae928 100644 --- a/third_party/expat/include/expat_config/expat_config.h +++ b/third_party/expat/include/expat_config/expat_config.h
@@ -77,7 +77,7 @@ #define PACKAGE_NAME "expat" /* Define to the full name and version of this package. */ -#define PACKAGE_STRING "expat 2.4.6" +#define PACKAGE_STRING "expat 2.4.7" /* Define to the one symbol short name of this package. */ #define PACKAGE_TARNAME "expat" @@ -86,7 +86,7 @@ #define PACKAGE_URL "" /* Define to the version of this package. */ -#define PACKAGE_VERSION "2.4.6" +#define PACKAGE_VERSION "2.4.7" /* Define to 1 if all of the C90 standard headers exist (not just the ones required in a freestanding environment). This macro is provided for @@ -94,7 +94,7 @@ #define STDC_HEADERS 1 /* Version number of package */ -#define VERSION "2.4.6" +#define VERSION "2.4.7" /* Define WORDS_BIGENDIAN to 1 if your processor stores words with the most significant byte first (like Motorola and SPARC, unlike Intel). */
diff --git a/third_party/grpc/BUILD.gn b/third_party/grpc/BUILD.gn index 6947383..968f6d7 100644 --- a/third_party/grpc/BUILD.gn +++ b/third_party/grpc/BUILD.gn
@@ -52,6 +52,7 @@ "-Wno-implicit-fallthrough", "-Wno-shadow", "-Wno-unreachable-code-return", + "-Wno-unreachable-code-break", ] if (is_android) { @@ -467,7 +468,16 @@ "src/src/core/ext/transport/chttp2/transport/stream_map.h", "src/src/core/ext/transport/chttp2/transport/varint.h", "src/src/core/ext/transport/inproc/inproc_transport.h", + "src/src/core/ext/upb-generated/envoy/admin/v3/certs.upb.h", + "src/src/core/ext/upb-generated/envoy/admin/v3/clusters.upb.h", "src/src/core/ext/upb-generated/envoy/admin/v3/config_dump.upb.h", + "src/src/core/ext/upb-generated/envoy/admin/v3/init_dump.upb.h", + "src/src/core/ext/upb-generated/envoy/admin/v3/listeners.upb.h", + "src/src/core/ext/upb-generated/envoy/admin/v3/memory.upb.h", + "src/src/core/ext/upb-generated/envoy/admin/v3/metrics.upb.h", + "src/src/core/ext/upb-generated/envoy/admin/v3/mutex_stats.upb.h", + "src/src/core/ext/upb-generated/envoy/admin/v3/server_info.upb.h", + "src/src/core/ext/upb-generated/envoy/admin/v3/tap.upb.h", "src/src/core/ext/upb-generated/envoy/annotations/deprecation.upb.h", "src/src/core/ext/upb-generated/envoy/annotations/resource.upb.h", "src/src/core/ext/upb-generated/envoy/config/accesslog/v3/accesslog.upb.h", @@ -476,12 +486,14 @@ "src/src/core/ext/upb-generated/envoy/config/cluster/v3/cluster.upb.h", "src/src/core/ext/upb-generated/envoy/config/cluster/v3/filter.upb.h", "src/src/core/ext/upb-generated/envoy/config/cluster/v3/outlier_detection.upb.h", + "src/src/core/ext/upb-generated/envoy/config/common/matcher/v3/matcher.upb.h", "src/src/core/ext/upb-generated/envoy/config/core/v3/address.upb.h", "src/src/core/ext/upb-generated/envoy/config/core/v3/backoff.upb.h", "src/src/core/ext/upb-generated/envoy/config/core/v3/base.upb.h", "src/src/core/ext/upb-generated/envoy/config/core/v3/config_source.upb.h", "src/src/core/ext/upb-generated/envoy/config/core/v3/event_service_config.upb.h", "src/src/core/ext/upb-generated/envoy/config/core/v3/extension.upb.h", + "src/src/core/ext/upb-generated/envoy/config/core/v3/grpc_method_list.upb.h", "src/src/core/ext/upb-generated/envoy/config/core/v3/grpc_service.upb.h", "src/src/core/ext/upb-generated/envoy/config/core/v3/health_check.upb.h", "src/src/core/ext/upb-generated/envoy/config/core/v3/http_uri.upb.h", @@ -499,13 +511,24 @@ "src/src/core/ext/upb-generated/envoy/config/listener/v3/listener_components.upb.h", "src/src/core/ext/upb-generated/envoy/config/listener/v3/quic_config.upb.h", "src/src/core/ext/upb-generated/envoy/config/listener/v3/udp_listener_config.upb.h", + "src/src/core/ext/upb-generated/envoy/config/metrics/v3/metrics_service.upb.h", "src/src/core/ext/upb-generated/envoy/config/metrics/v3/stats.upb.h", "src/src/core/ext/upb-generated/envoy/config/overload/v3/overload.upb.h", "src/src/core/ext/upb-generated/envoy/config/rbac/v3/rbac.upb.h", "src/src/core/ext/upb-generated/envoy/config/route/v3/route.upb.h", "src/src/core/ext/upb-generated/envoy/config/route/v3/route_components.upb.h", "src/src/core/ext/upb-generated/envoy/config/route/v3/scoped_route.upb.h", + "src/src/core/ext/upb-generated/envoy/config/tap/v3/common.upb.h", + "src/src/core/ext/upb-generated/envoy/config/trace/v3/datadog.upb.h", + "src/src/core/ext/upb-generated/envoy/config/trace/v3/dynamic_ot.upb.h", "src/src/core/ext/upb-generated/envoy/config/trace/v3/http_tracer.upb.h", + "src/src/core/ext/upb-generated/envoy/config/trace/v3/lightstep.upb.h", + "src/src/core/ext/upb-generated/envoy/config/trace/v3/opencensus.upb.h", + "src/src/core/ext/upb-generated/envoy/config/trace/v3/service.upb.h", + "src/src/core/ext/upb-generated/envoy/config/trace/v3/skywalking.upb.h", + "src/src/core/ext/upb-generated/envoy/config/trace/v3/trace.upb.h", + "src/src/core/ext/upb-generated/envoy/config/trace/v3/xray.upb.h", + "src/src/core/ext/upb-generated/envoy/config/trace/v3/zipkin.upb.h", "src/src/core/ext/upb-generated/envoy/extensions/clusters/aggregate/v3/cluster.upb.h", "src/src/core/ext/upb-generated/envoy/extensions/filters/common/fault/v3/fault.upb.h", "src/src/core/ext/upb-generated/envoy/extensions/filters/http/fault/v3/fault.upb.h", @@ -516,16 +539,14 @@ "src/src/core/ext/upb-generated/envoy/extensions/transport_sockets/tls/v3/common.upb.h", "src/src/core/ext/upb-generated/envoy/extensions/transport_sockets/tls/v3/secret.upb.h", "src/src/core/ext/upb-generated/envoy/extensions/transport_sockets/tls/v3/tls.upb.h", - "src/src/core/ext/upb-generated/envoy/service/cluster/v3/cds.upb.h", + "src/src/core/ext/upb-generated/envoy/extensions/transport_sockets/tls/v3/tls_spiffe_validator_config.upb.h", "src/src/core/ext/upb-generated/envoy/service/discovery/v3/ads.upb.h", "src/src/core/ext/upb-generated/envoy/service/discovery/v3/discovery.upb.h", - "src/src/core/ext/upb-generated/envoy/service/endpoint/v3/eds.upb.h", - "src/src/core/ext/upb-generated/envoy/service/listener/v3/lds.upb.h", "src/src/core/ext/upb-generated/envoy/service/load_stats/v3/lrs.upb.h", - "src/src/core/ext/upb-generated/envoy/service/route/v3/rds.upb.h", - "src/src/core/ext/upb-generated/envoy/service/route/v3/srds.upb.h", "src/src/core/ext/upb-generated/envoy/service/status/v3/csds.upb.h", + "src/src/core/ext/upb-generated/envoy/type/http/v3/cookie.upb.h", "src/src/core/ext/upb-generated/envoy/type/http/v3/path_transformation.upb.h", + "src/src/core/ext/upb-generated/envoy/type/matcher/v3/http_inputs.upb.h", "src/src/core/ext/upb-generated/envoy/type/matcher/v3/metadata.upb.h", "src/src/core/ext/upb-generated/envoy/type/matcher/v3/node.upb.h", "src/src/core/ext/upb-generated/envoy/type/matcher/v3/number.upb.h", @@ -536,17 +557,19 @@ "src/src/core/ext/upb-generated/envoy/type/matcher/v3/value.upb.h", "src/src/core/ext/upb-generated/envoy/type/metadata/v3/metadata.upb.h", "src/src/core/ext/upb-generated/envoy/type/tracing/v3/custom_tag.upb.h", + "src/src/core/ext/upb-generated/envoy/type/v3/hash_policy.upb.h", "src/src/core/ext/upb-generated/envoy/type/v3/http.upb.h", + "src/src/core/ext/upb-generated/envoy/type/v3/http_status.upb.h", "src/src/core/ext/upb-generated/envoy/type/v3/percent.upb.h", "src/src/core/ext/upb-generated/envoy/type/v3/range.upb.h", + "src/src/core/ext/upb-generated/envoy/type/v3/ratelimit_unit.upb.h", "src/src/core/ext/upb-generated/envoy/type/v3/semantic_version.upb.h", + "src/src/core/ext/upb-generated/envoy/type/v3/token_bucket.upb.h", "src/src/core/ext/upb-generated/google/api/annotations.upb.h", "src/src/core/ext/upb-generated/google/api/expr/v1alpha1/checked.upb.h", - "src/src/core/ext/upb-generated/google/api/expr/v1alpha1/eval.upb.h", - "src/src/core/ext/upb-generated/google/api/expr/v1alpha1/explain.upb.h", "src/src/core/ext/upb-generated/google/api/expr/v1alpha1/syntax.upb.h", - "src/src/core/ext/upb-generated/google/api/expr/v1alpha1/value.upb.h", "src/src/core/ext/upb-generated/google/api/http.upb.h", + "src/src/core/ext/upb-generated/google/api/httpbody.upb.h", "src/src/core/ext/upb-generated/google/protobuf/any.upb.h", "src/src/core/ext/upb-generated/google/protobuf/duration.upb.h", "src/src/core/ext/upb-generated/google/protobuf/empty.upb.h", @@ -554,6 +577,7 @@ "src/src/core/ext/upb-generated/google/protobuf/timestamp.upb.h", "src/src/core/ext/upb-generated/google/protobuf/wrappers.upb.h", "src/src/core/ext/upb-generated/google/rpc/status.upb.h", + "src/src/core/ext/upb-generated/opencensus/proto/trace/v1/trace_config.upb.h", "src/src/core/ext/upb-generated/src/proto/grpc/gcp/altscontext.upb.h", "src/src/core/ext/upb-generated/src/proto/grpc/gcp/handshaker.upb.h", "src/src/core/ext/upb-generated/src/proto/grpc/gcp/transport_security_common.upb.h", @@ -566,16 +590,33 @@ "src/src/core/ext/upb-generated/udpa/annotations/status.upb.h", "src/src/core/ext/upb-generated/udpa/annotations/versioning.upb.h", "src/src/core/ext/upb-generated/validate/validate.upb.h", + "src/src/core/ext/upb-generated/xds/annotations/v3/migrate.upb.h", + "src/src/core/ext/upb-generated/xds/annotations/v3/security.upb.h", + "src/src/core/ext/upb-generated/xds/annotations/v3/sensitive.upb.h", "src/src/core/ext/upb-generated/xds/annotations/v3/status.upb.h", + "src/src/core/ext/upb-generated/xds/annotations/v3/versioning.upb.h", "src/src/core/ext/upb-generated/xds/core/v3/authority.upb.h", "src/src/core/ext/upb-generated/xds/core/v3/collection_entry.upb.h", "src/src/core/ext/upb-generated/xds/core/v3/context_params.upb.h", + "src/src/core/ext/upb-generated/xds/core/v3/extension.upb.h", "src/src/core/ext/upb-generated/xds/core/v3/resource.upb.h", "src/src/core/ext/upb-generated/xds/core/v3/resource_locator.upb.h", "src/src/core/ext/upb-generated/xds/core/v3/resource_name.upb.h", "src/src/core/ext/upb-generated/xds/data/orca/v3/orca_load_report.upb.h", + "src/src/core/ext/upb-generated/xds/type/matcher/v3/matcher.upb.h", + "src/src/core/ext/upb-generated/xds/type/matcher/v3/regex.upb.h", + "src/src/core/ext/upb-generated/xds/type/matcher/v3/string.upb.h", "src/src/core/ext/upb-generated/xds/type/v3/typed_struct.upb.h", + "src/src/core/ext/upbdefs-generated/envoy/admin/v3/certs.upbdefs.h", + "src/src/core/ext/upbdefs-generated/envoy/admin/v3/clusters.upbdefs.h", "src/src/core/ext/upbdefs-generated/envoy/admin/v3/config_dump.upbdefs.h", + "src/src/core/ext/upbdefs-generated/envoy/admin/v3/init_dump.upbdefs.h", + "src/src/core/ext/upbdefs-generated/envoy/admin/v3/listeners.upbdefs.h", + "src/src/core/ext/upbdefs-generated/envoy/admin/v3/memory.upbdefs.h", + "src/src/core/ext/upbdefs-generated/envoy/admin/v3/metrics.upbdefs.h", + "src/src/core/ext/upbdefs-generated/envoy/admin/v3/mutex_stats.upbdefs.h", + "src/src/core/ext/upbdefs-generated/envoy/admin/v3/server_info.upbdefs.h", + "src/src/core/ext/upbdefs-generated/envoy/admin/v3/tap.upbdefs.h", "src/src/core/ext/upbdefs-generated/envoy/annotations/deprecation.upbdefs.h", "src/src/core/ext/upbdefs-generated/envoy/annotations/resource.upbdefs.h", "src/src/core/ext/upbdefs-generated/envoy/config/accesslog/v3/accesslog.upbdefs.h", @@ -584,12 +625,14 @@ "src/src/core/ext/upbdefs-generated/envoy/config/cluster/v3/cluster.upbdefs.h", "src/src/core/ext/upbdefs-generated/envoy/config/cluster/v3/filter.upbdefs.h", "src/src/core/ext/upbdefs-generated/envoy/config/cluster/v3/outlier_detection.upbdefs.h", + "src/src/core/ext/upbdefs-generated/envoy/config/common/matcher/v3/matcher.upbdefs.h", "src/src/core/ext/upbdefs-generated/envoy/config/core/v3/address.upbdefs.h", "src/src/core/ext/upbdefs-generated/envoy/config/core/v3/backoff.upbdefs.h", "src/src/core/ext/upbdefs-generated/envoy/config/core/v3/base.upbdefs.h", "src/src/core/ext/upbdefs-generated/envoy/config/core/v3/config_source.upbdefs.h", "src/src/core/ext/upbdefs-generated/envoy/config/core/v3/event_service_config.upbdefs.h", "src/src/core/ext/upbdefs-generated/envoy/config/core/v3/extension.upbdefs.h", + "src/src/core/ext/upbdefs-generated/envoy/config/core/v3/grpc_method_list.upbdefs.h", "src/src/core/ext/upbdefs-generated/envoy/config/core/v3/grpc_service.upbdefs.h", "src/src/core/ext/upbdefs-generated/envoy/config/core/v3/health_check.upbdefs.h", "src/src/core/ext/upbdefs-generated/envoy/config/core/v3/http_uri.upbdefs.h", @@ -607,13 +650,24 @@ "src/src/core/ext/upbdefs-generated/envoy/config/listener/v3/listener_components.upbdefs.h", "src/src/core/ext/upbdefs-generated/envoy/config/listener/v3/quic_config.upbdefs.h", "src/src/core/ext/upbdefs-generated/envoy/config/listener/v3/udp_listener_config.upbdefs.h", + "src/src/core/ext/upbdefs-generated/envoy/config/metrics/v3/metrics_service.upbdefs.h", "src/src/core/ext/upbdefs-generated/envoy/config/metrics/v3/stats.upbdefs.h", "src/src/core/ext/upbdefs-generated/envoy/config/overload/v3/overload.upbdefs.h", "src/src/core/ext/upbdefs-generated/envoy/config/rbac/v3/rbac.upbdefs.h", "src/src/core/ext/upbdefs-generated/envoy/config/route/v3/route.upbdefs.h", "src/src/core/ext/upbdefs-generated/envoy/config/route/v3/route_components.upbdefs.h", "src/src/core/ext/upbdefs-generated/envoy/config/route/v3/scoped_route.upbdefs.h", + "src/src/core/ext/upbdefs-generated/envoy/config/tap/v3/common.upbdefs.h", + "src/src/core/ext/upbdefs-generated/envoy/config/trace/v3/datadog.upbdefs.h", + "src/src/core/ext/upbdefs-generated/envoy/config/trace/v3/dynamic_ot.upbdefs.h", "src/src/core/ext/upbdefs-generated/envoy/config/trace/v3/http_tracer.upbdefs.h", + "src/src/core/ext/upbdefs-generated/envoy/config/trace/v3/lightstep.upbdefs.h", + "src/src/core/ext/upbdefs-generated/envoy/config/trace/v3/opencensus.upbdefs.h", + "src/src/core/ext/upbdefs-generated/envoy/config/trace/v3/service.upbdefs.h", + "src/src/core/ext/upbdefs-generated/envoy/config/trace/v3/skywalking.upbdefs.h", + "src/src/core/ext/upbdefs-generated/envoy/config/trace/v3/trace.upbdefs.h", + "src/src/core/ext/upbdefs-generated/envoy/config/trace/v3/xray.upbdefs.h", + "src/src/core/ext/upbdefs-generated/envoy/config/trace/v3/zipkin.upbdefs.h", "src/src/core/ext/upbdefs-generated/envoy/extensions/clusters/aggregate/v3/cluster.upbdefs.h", "src/src/core/ext/upbdefs-generated/envoy/extensions/filters/common/fault/v3/fault.upbdefs.h", "src/src/core/ext/upbdefs-generated/envoy/extensions/filters/http/fault/v3/fault.upbdefs.h", @@ -624,16 +678,14 @@ "src/src/core/ext/upbdefs-generated/envoy/extensions/transport_sockets/tls/v3/common.upbdefs.h", "src/src/core/ext/upbdefs-generated/envoy/extensions/transport_sockets/tls/v3/secret.upbdefs.h", "src/src/core/ext/upbdefs-generated/envoy/extensions/transport_sockets/tls/v3/tls.upbdefs.h", - "src/src/core/ext/upbdefs-generated/envoy/service/cluster/v3/cds.upbdefs.h", + "src/src/core/ext/upbdefs-generated/envoy/extensions/transport_sockets/tls/v3/tls_spiffe_validator_config.upbdefs.h", "src/src/core/ext/upbdefs-generated/envoy/service/discovery/v3/ads.upbdefs.h", "src/src/core/ext/upbdefs-generated/envoy/service/discovery/v3/discovery.upbdefs.h", - "src/src/core/ext/upbdefs-generated/envoy/service/endpoint/v3/eds.upbdefs.h", - "src/src/core/ext/upbdefs-generated/envoy/service/listener/v3/lds.upbdefs.h", "src/src/core/ext/upbdefs-generated/envoy/service/load_stats/v3/lrs.upbdefs.h", - "src/src/core/ext/upbdefs-generated/envoy/service/route/v3/rds.upbdefs.h", - "src/src/core/ext/upbdefs-generated/envoy/service/route/v3/srds.upbdefs.h", "src/src/core/ext/upbdefs-generated/envoy/service/status/v3/csds.upbdefs.h", + "src/src/core/ext/upbdefs-generated/envoy/type/http/v3/cookie.upbdefs.h", "src/src/core/ext/upbdefs-generated/envoy/type/http/v3/path_transformation.upbdefs.h", + "src/src/core/ext/upbdefs-generated/envoy/type/matcher/v3/http_inputs.upbdefs.h", "src/src/core/ext/upbdefs-generated/envoy/type/matcher/v3/metadata.upbdefs.h", "src/src/core/ext/upbdefs-generated/envoy/type/matcher/v3/node.upbdefs.h", "src/src/core/ext/upbdefs-generated/envoy/type/matcher/v3/number.upbdefs.h", @@ -644,17 +696,19 @@ "src/src/core/ext/upbdefs-generated/envoy/type/matcher/v3/value.upbdefs.h", "src/src/core/ext/upbdefs-generated/envoy/type/metadata/v3/metadata.upbdefs.h", "src/src/core/ext/upbdefs-generated/envoy/type/tracing/v3/custom_tag.upbdefs.h", + "src/src/core/ext/upbdefs-generated/envoy/type/v3/hash_policy.upbdefs.h", "src/src/core/ext/upbdefs-generated/envoy/type/v3/http.upbdefs.h", + "src/src/core/ext/upbdefs-generated/envoy/type/v3/http_status.upbdefs.h", "src/src/core/ext/upbdefs-generated/envoy/type/v3/percent.upbdefs.h", "src/src/core/ext/upbdefs-generated/envoy/type/v3/range.upbdefs.h", + "src/src/core/ext/upbdefs-generated/envoy/type/v3/ratelimit_unit.upbdefs.h", "src/src/core/ext/upbdefs-generated/envoy/type/v3/semantic_version.upbdefs.h", + "src/src/core/ext/upbdefs-generated/envoy/type/v3/token_bucket.upbdefs.h", "src/src/core/ext/upbdefs-generated/google/api/annotations.upbdefs.h", "src/src/core/ext/upbdefs-generated/google/api/expr/v1alpha1/checked.upbdefs.h", - "src/src/core/ext/upbdefs-generated/google/api/expr/v1alpha1/eval.upbdefs.h", - "src/src/core/ext/upbdefs-generated/google/api/expr/v1alpha1/explain.upbdefs.h", "src/src/core/ext/upbdefs-generated/google/api/expr/v1alpha1/syntax.upbdefs.h", - "src/src/core/ext/upbdefs-generated/google/api/expr/v1alpha1/value.upbdefs.h", "src/src/core/ext/upbdefs-generated/google/api/http.upbdefs.h", + "src/src/core/ext/upbdefs-generated/google/api/httpbody.upbdefs.h", "src/src/core/ext/upbdefs-generated/google/protobuf/any.upbdefs.h", "src/src/core/ext/upbdefs-generated/google/protobuf/duration.upbdefs.h", "src/src/core/ext/upbdefs-generated/google/protobuf/empty.upbdefs.h", @@ -662,24 +716,34 @@ "src/src/core/ext/upbdefs-generated/google/protobuf/timestamp.upbdefs.h", "src/src/core/ext/upbdefs-generated/google/protobuf/wrappers.upbdefs.h", "src/src/core/ext/upbdefs-generated/google/rpc/status.upbdefs.h", + "src/src/core/ext/upbdefs-generated/opencensus/proto/trace/v1/trace_config.upbdefs.h", "src/src/core/ext/upbdefs-generated/udpa/annotations/migrate.upbdefs.h", "src/src/core/ext/upbdefs-generated/udpa/annotations/security.upbdefs.h", "src/src/core/ext/upbdefs-generated/udpa/annotations/sensitive.upbdefs.h", "src/src/core/ext/upbdefs-generated/udpa/annotations/status.upbdefs.h", "src/src/core/ext/upbdefs-generated/udpa/annotations/versioning.upbdefs.h", "src/src/core/ext/upbdefs-generated/validate/validate.upbdefs.h", + "src/src/core/ext/upbdefs-generated/xds/annotations/v3/migrate.upbdefs.h", + "src/src/core/ext/upbdefs-generated/xds/annotations/v3/security.upbdefs.h", + "src/src/core/ext/upbdefs-generated/xds/annotations/v3/sensitive.upbdefs.h", "src/src/core/ext/upbdefs-generated/xds/annotations/v3/status.upbdefs.h", + "src/src/core/ext/upbdefs-generated/xds/annotations/v3/versioning.upbdefs.h", "src/src/core/ext/upbdefs-generated/xds/core/v3/authority.upbdefs.h", "src/src/core/ext/upbdefs-generated/xds/core/v3/collection_entry.upbdefs.h", "src/src/core/ext/upbdefs-generated/xds/core/v3/context_params.upbdefs.h", + "src/src/core/ext/upbdefs-generated/xds/core/v3/extension.upbdefs.h", "src/src/core/ext/upbdefs-generated/xds/core/v3/resource.upbdefs.h", "src/src/core/ext/upbdefs-generated/xds/core/v3/resource_locator.upbdefs.h", "src/src/core/ext/upbdefs-generated/xds/core/v3/resource_name.upbdefs.h", + "src/src/core/ext/upbdefs-generated/xds/type/matcher/v3/matcher.upbdefs.h", + "src/src/core/ext/upbdefs-generated/xds/type/matcher/v3/regex.upbdefs.h", + "src/src/core/ext/upbdefs-generated/xds/type/matcher/v3/string.upbdefs.h", "src/src/core/ext/upbdefs-generated/xds/type/v3/typed_struct.upbdefs.h", "src/src/core/lib/address_utils/parse_address.h", "src/src/core/lib/address_utils/sockaddr_utils.h", "src/src/core/lib/avl/avl.h", "src/src/core/lib/backoff/backoff.h", + "src/src/core/lib/channel/call_finalization.h", "src/src/core/lib/channel/call_tracer.h", "src/src/core/lib/channel/channel_args.h", "src/src/core/lib/channel/channel_args_preconditioning.h", @@ -693,6 +757,7 @@ "src/src/core/lib/channel/handshaker.h", "src/src/core/lib/channel/handshaker_factory.h", "src/src/core/lib/channel/handshaker_registry.h", + "src/src/core/lib/channel/promise_based_filter.h", "src/src/core/lib/channel/status_util.h", "src/src/core/lib/compression/compression_internal.h", "src/src/core/lib/compression/message_compress.h", @@ -715,6 +780,7 @@ "src/src/core/lib/gpr/useful.h", "src/src/core/lib/gprpp/atomic_utils.h", "src/src/core/lib/gprpp/bitset.h", + "src/src/core/lib/gprpp/capture.h", "src/src/core/lib/gprpp/chunked_vector.h", "src/src/core/lib/gprpp/construct_destruct.h", "src/src/core/lib/gprpp/cpp_impl_of.h", @@ -738,9 +804,11 @@ "src/src/core/lib/gprpp/sync.h", "src/src/core/lib/gprpp/table.h", "src/src/core/lib/gprpp/thd.h", + "src/src/core/lib/gprpp/time.h", "src/src/core/lib/gprpp/time_util.h", "src/src/core/lib/http/format_request.h", "src/src/core/lib/http/httpcli.h", + "src/src/core/lib/http/httpcli_ssl_credentials.h", "src/src/core/lib/http/parser.h", "src/src/core/lib/iomgr/block_annotate.h", "src/src/core/lib/iomgr/buffer_list.h", @@ -775,7 +843,6 @@ "src/src/core/lib/iomgr/internal_errqueue.h", "src/src/core/lib/iomgr/iocp_windows.h", "src/src/core/lib/iomgr/iomgr.h", - "src/src/core/lib/iomgr/iomgr_custom.h", "src/src/core/lib/iomgr/iomgr_internal.h", "src/src/core/lib/iomgr/is_epollexclusive_available.h", "src/src/core/lib/iomgr/load_file.h", @@ -783,15 +850,12 @@ "src/src/core/lib/iomgr/nameser.h", "src/src/core/lib/iomgr/polling_entity.h", "src/src/core/lib/iomgr/pollset.h", - "src/src/core/lib/iomgr/pollset_custom.h", "src/src/core/lib/iomgr/pollset_set.h", - "src/src/core/lib/iomgr/pollset_set_custom.h", "src/src/core/lib/iomgr/pollset_set_windows.h", "src/src/core/lib/iomgr/pollset_windows.h", "src/src/core/lib/iomgr/port.h", "src/src/core/lib/iomgr/python_util.h", "src/src/core/lib/iomgr/resolve_address.h", - "src/src/core/lib/iomgr/resolve_address_custom.h", "src/src/core/lib/iomgr/resolve_address_impl.h", "src/src/core/lib/iomgr/resolve_address_posix.h", "src/src/core/lib/iomgr/resolve_address_windows.h", @@ -807,14 +871,12 @@ "src/src/core/lib/iomgr/sys_epoll_wrapper.h", "src/src/core/lib/iomgr/tcp_client.h", "src/src/core/lib/iomgr/tcp_client_posix.h", - "src/src/core/lib/iomgr/tcp_custom.h", "src/src/core/lib/iomgr/tcp_posix.h", "src/src/core/lib/iomgr/tcp_server.h", "src/src/core/lib/iomgr/tcp_server_utils_posix.h", "src/src/core/lib/iomgr/tcp_windows.h", "src/src/core/lib/iomgr/time_averaged_stats.h", "src/src/core/lib/iomgr/timer.h", - "src/src/core/lib/iomgr/timer_custom.h", "src/src/core/lib/iomgr/timer_generic.h", "src/src/core/lib/iomgr/timer_heap.h", "src/src/core/lib/iomgr/timer_manager.h", @@ -828,6 +890,7 @@ # "src/src/core/lib/matchers/matchers.h", "src/src/core/lib/profiling/timers.h", "src/src/core/lib/promise/activity.h", + "src/src/core/lib/promise/arena_promise.h", "src/src/core/lib/promise/context.h", "src/src/core/lib/promise/detail/basic_seq.h", "src/src/core/lib/promise/detail/promise_factory.h", @@ -838,8 +901,11 @@ "src/src/core/lib/promise/loop.h", "src/src/core/lib/promise/map.h", "src/src/core/lib/promise/poll.h", + "src/src/core/lib/promise/promise.h", "src/src/core/lib/promise/race.h", "src/src/core/lib/promise/seq.h", + "src/src/core/lib/promise/sleep.h", + "src/src/core/lib/promise/try_seq.h", "src/src/core/lib/resolver/resolver.h", "src/src/core/lib/resolver/resolver_factory.h", "src/src/core/lib/resolver/resolver_registry.h", @@ -855,13 +921,16 @@ "src/src/core/lib/security/authorization/evaluate_args.h", # "src/src/core/lib/security/authorization/grpc_authorization_engine.h", + "src/src/core/lib/security/authorization/grpc_server_authz_filter.h", + # "src/src/core/lib/security/authorization/matchers.h", # "src/src/core/lib/security/authorization/rbac_policy.h", - "src/src/core/lib/security/authorization/sdk_server_authz_filter.h", "src/src/core/lib/security/context/security_context.h", "src/src/core/lib/security/credentials/alts/alts_credentials.h", "src/src/core/lib/security/credentials/alts/check_gcp_environment.h", "src/src/core/lib/security/credentials/alts/grpc_alts_credentials_options.h", + "src/src/core/lib/security/credentials/call_creds_util.h", + "src/src/core/lib/security/credentials/channel_creds_registry.h", "src/src/core/lib/security/credentials/composite/composite_credentials.h", "src/src/core/lib/security/credentials/credentials.h", "src/src/core/lib/security/credentials/external/aws_external_account_credentials.h", @@ -905,6 +974,7 @@ "src/src/core/lib/security/util/json_util.h", "src/src/core/lib/service_config/service_config.h", "src/src/core/lib/service_config/service_config_call_data.h", + "src/src/core/lib/service_config/service_config_impl.h", "src/src/core/lib/service_config/service_config_parser.h", "src/src/core/lib/slice/b64.h", "src/src/core/lib/slice/percent_encoding.h", @@ -914,7 +984,6 @@ "src/src/core/lib/slice/slice_refcount_base.h", "src/src/core/lib/slice/slice_split.h", "src/src/core/lib/slice/slice_string_helpers.h", - "src/src/core/lib/slice/slice_utils.h", "src/src/core/lib/surface/api_trace.h", "src/src/core/lib/surface/builtins.h", "src/src/core/lib/surface/call.h", @@ -962,6 +1031,7 @@ "src/src/core/tsi/alts/zero_copy_frame_protector/alts_zero_copy_grpc_protector.h", "src/src/core/tsi/fake_transport_security.h", "src/src/core/tsi/local_transport_security.h", + "src/src/core/tsi/ssl/key_logging/ssl_key_logging.h", "src/src/core/tsi/ssl/session_cache/ssl_session.h", "src/src/core/tsi/ssl/session_cache/ssl_session_cache.h", "src/src/core/tsi/ssl_transport_security.h", @@ -1091,15 +1161,9 @@ "src/src/core/ext/transport/binder/wire_format/wire_writer.cc", "src/src/core/ext/transport/chttp2/alpn/alpn.cc", "src/src/core/ext/transport/chttp2/client/chttp2_connector.cc", - "src/src/core/ext/transport/chttp2/client/insecure/channel_create_posix.cc", - "src/src/core/ext/transport/chttp2/client/secure/secure_channel_create.cc", "src/src/core/ext/transport/chttp2/server/chttp2_server.cc", - "src/src/core/ext/transport/chttp2/server/insecure/server_chttp2.cc", - "src/src/core/ext/transport/chttp2/server/insecure/server_chttp2_posix.cc", - "src/src/core/ext/transport/chttp2/server/secure/server_secure_chttp2.cc", "src/src/core/ext/transport/chttp2/transport/bin_decoder.cc", "src/src/core/ext/transport/chttp2/transport/bin_encoder.cc", - "src/src/core/ext/transport/chttp2/transport/chttp2_plugin.cc", "src/src/core/ext/transport/chttp2/transport/chttp2_transport.cc", "src/src/core/ext/transport/chttp2/transport/context_list.cc", "src/src/core/ext/transport/chttp2/transport/flow_control.cc", @@ -1122,7 +1186,16 @@ "src/src/core/ext/transport/chttp2/transport/writing.cc", "src/src/core/ext/transport/inproc/inproc_plugin.cc", "src/src/core/ext/transport/inproc/inproc_transport.cc", + "src/src/core/ext/upb-generated/envoy/admin/v3/certs.upb.c", + "src/src/core/ext/upb-generated/envoy/admin/v3/clusters.upb.c", "src/src/core/ext/upb-generated/envoy/admin/v3/config_dump.upb.c", + "src/src/core/ext/upb-generated/envoy/admin/v3/init_dump.upb.c", + "src/src/core/ext/upb-generated/envoy/admin/v3/listeners.upb.c", + "src/src/core/ext/upb-generated/envoy/admin/v3/memory.upb.c", + "src/src/core/ext/upb-generated/envoy/admin/v3/metrics.upb.c", + "src/src/core/ext/upb-generated/envoy/admin/v3/mutex_stats.upb.c", + "src/src/core/ext/upb-generated/envoy/admin/v3/server_info.upb.c", + "src/src/core/ext/upb-generated/envoy/admin/v3/tap.upb.c", "src/src/core/ext/upb-generated/envoy/annotations/deprecation.upb.c", "src/src/core/ext/upb-generated/envoy/annotations/resource.upb.c", "src/src/core/ext/upb-generated/envoy/config/accesslog/v3/accesslog.upb.c", @@ -1131,12 +1204,14 @@ "src/src/core/ext/upb-generated/envoy/config/cluster/v3/cluster.upb.c", "src/src/core/ext/upb-generated/envoy/config/cluster/v3/filter.upb.c", "src/src/core/ext/upb-generated/envoy/config/cluster/v3/outlier_detection.upb.c", + "src/src/core/ext/upb-generated/envoy/config/common/matcher/v3/matcher.upb.c", "src/src/core/ext/upb-generated/envoy/config/core/v3/address.upb.c", "src/src/core/ext/upb-generated/envoy/config/core/v3/backoff.upb.c", "src/src/core/ext/upb-generated/envoy/config/core/v3/base.upb.c", "src/src/core/ext/upb-generated/envoy/config/core/v3/config_source.upb.c", "src/src/core/ext/upb-generated/envoy/config/core/v3/event_service_config.upb.c", "src/src/core/ext/upb-generated/envoy/config/core/v3/extension.upb.c", + "src/src/core/ext/upb-generated/envoy/config/core/v3/grpc_method_list.upb.c", "src/src/core/ext/upb-generated/envoy/config/core/v3/grpc_service.upb.c", "src/src/core/ext/upb-generated/envoy/config/core/v3/health_check.upb.c", "src/src/core/ext/upb-generated/envoy/config/core/v3/http_uri.upb.c", @@ -1154,30 +1229,38 @@ "src/src/core/ext/upb-generated/envoy/config/listener/v3/listener_components.upb.c", "src/src/core/ext/upb-generated/envoy/config/listener/v3/quic_config.upb.c", "src/src/core/ext/upb-generated/envoy/config/listener/v3/udp_listener_config.upb.c", + "src/src/core/ext/upb-generated/envoy/config/metrics/v3/metrics_service.upb.c", "src/src/core/ext/upb-generated/envoy/config/metrics/v3/stats.upb.c", "src/src/core/ext/upb-generated/envoy/config/overload/v3/overload.upb.c", "src/src/core/ext/upb-generated/envoy/config/rbac/v3/rbac.upb.c", "src/src/core/ext/upb-generated/envoy/config/route/v3/route.upb.c", "src/src/core/ext/upb-generated/envoy/config/route/v3/route_components.upb.c", "src/src/core/ext/upb-generated/envoy/config/route/v3/scoped_route.upb.c", + "src/src/core/ext/upb-generated/envoy/config/tap/v3/common.upb.c", + "src/src/core/ext/upb-generated/envoy/config/trace/v3/datadog.upb.c", + "src/src/core/ext/upb-generated/envoy/config/trace/v3/dynamic_ot.upb.c", "src/src/core/ext/upb-generated/envoy/config/trace/v3/http_tracer.upb.c", + "src/src/core/ext/upb-generated/envoy/config/trace/v3/lightstep.upb.c", + "src/src/core/ext/upb-generated/envoy/config/trace/v3/opencensus.upb.c", + "src/src/core/ext/upb-generated/envoy/config/trace/v3/service.upb.c", + "src/src/core/ext/upb-generated/envoy/config/trace/v3/skywalking.upb.c", + "src/src/core/ext/upb-generated/envoy/config/trace/v3/trace.upb.c", + "src/src/core/ext/upb-generated/envoy/config/trace/v3/xray.upb.c", + "src/src/core/ext/upb-generated/envoy/config/trace/v3/zipkin.upb.c", "src/src/core/ext/upb-generated/envoy/extensions/filters/common/fault/v3/fault.upb.c", "src/src/core/ext/upb-generated/envoy/extensions/filters/http/router/v3/router.upb.c", "src/src/core/ext/upb-generated/envoy/extensions/filters/network/http_connection_manager/v3/http_connection_manager.upb.c", "src/src/core/ext/upb-generated/envoy/extensions/transport_sockets/tls/v3/cert.upb.c", - "src/src/core/ext/upb-generated/envoy/extensions/transport_sockets/tls/v3/common.upb.c", "src/src/core/ext/upb-generated/envoy/extensions/transport_sockets/tls/v3/secret.upb.c", "src/src/core/ext/upb-generated/envoy/extensions/transport_sockets/tls/v3/tls.upb.c", - "src/src/core/ext/upb-generated/envoy/service/cluster/v3/cds.upb.c", + "src/src/core/ext/upb-generated/envoy/extensions/transport_sockets/tls/v3/tls_spiffe_validator_config.upb.c", "src/src/core/ext/upb-generated/envoy/service/discovery/v3/ads.upb.c", "src/src/core/ext/upb-generated/envoy/service/discovery/v3/discovery.upb.c", - "src/src/core/ext/upb-generated/envoy/service/endpoint/v3/eds.upb.c", - "src/src/core/ext/upb-generated/envoy/service/listener/v3/lds.upb.c", "src/src/core/ext/upb-generated/envoy/service/load_stats/v3/lrs.upb.c", - "src/src/core/ext/upb-generated/envoy/service/route/v3/rds.upb.c", - "src/src/core/ext/upb-generated/envoy/service/route/v3/srds.upb.c", "src/src/core/ext/upb-generated/envoy/service/status/v3/csds.upb.c", + "src/src/core/ext/upb-generated/envoy/type/http/v3/cookie.upb.c", "src/src/core/ext/upb-generated/envoy/type/http/v3/path_transformation.upb.c", + "src/src/core/ext/upb-generated/envoy/type/matcher/v3/http_inputs.upb.c", "src/src/core/ext/upb-generated/envoy/type/matcher/v3/metadata.upb.c", "src/src/core/ext/upb-generated/envoy/type/matcher/v3/node.upb.c", "src/src/core/ext/upb-generated/envoy/type/matcher/v3/number.upb.c", @@ -1187,21 +1270,25 @@ "src/src/core/ext/upb-generated/envoy/type/matcher/v3/struct.upb.c", "src/src/core/ext/upb-generated/envoy/type/matcher/v3/value.upb.c", "src/src/core/ext/upb-generated/envoy/type/tracing/v3/custom_tag.upb.c", + "src/src/core/ext/upb-generated/envoy/type/v3/hash_policy.upb.c", "src/src/core/ext/upb-generated/envoy/type/v3/http.upb.c", + "src/src/core/ext/upb-generated/envoy/type/v3/http_status.upb.c", "src/src/core/ext/upb-generated/envoy/type/v3/percent.upb.c", "src/src/core/ext/upb-generated/envoy/type/v3/range.upb.c", + "src/src/core/ext/upb-generated/envoy/type/v3/ratelimit_unit.upb.c", "src/src/core/ext/upb-generated/envoy/type/v3/semantic_version.upb.c", + "src/src/core/ext/upb-generated/envoy/type/v3/token_bucket.upb.c", "src/src/core/ext/upb-generated/google/api/annotations.upb.c", "src/src/core/ext/upb-generated/google/api/expr/v1alpha1/checked.upb.c", - "src/src/core/ext/upb-generated/google/api/expr/v1alpha1/eval.upb.c", - "src/src/core/ext/upb-generated/google/api/expr/v1alpha1/explain.upb.c", "src/src/core/ext/upb-generated/google/api/expr/v1alpha1/syntax.upb.c", + "src/src/core/ext/upb-generated/google/api/httpbody.upb.c", "src/src/core/ext/upb-generated/google/protobuf/any.upb.c", "src/src/core/ext/upb-generated/google/protobuf/duration.upb.c", "src/src/core/ext/upb-generated/google/protobuf/empty.upb.c", "src/src/core/ext/upb-generated/google/protobuf/timestamp.upb.c", "src/src/core/ext/upb-generated/google/protobuf/wrappers.upb.c", "src/src/core/ext/upb-generated/google/rpc/status.upb.c", + "src/src/core/ext/upb-generated/opencensus/proto/trace/v1/trace_config.upb.c", "src/src/core/ext/upb-generated/src/proto/grpc/gcp/altscontext.upb.c", "src/src/core/ext/upb-generated/src/proto/grpc/gcp/handshaker.upb.c", "src/src/core/ext/upb-generated/src/proto/grpc/gcp/transport_security_common.upb.c", @@ -1220,7 +1307,16 @@ "src/src/core/ext/upb-generated/xds/core/v3/resource_name.upb.c", "src/src/core/ext/upb-generated/xds/data/orca/v3/orca_load_report.upb.c", "src/src/core/ext/upb-generated/xds/type/v3/typed_struct.upb.c", + "src/src/core/ext/upbdefs-generated/envoy/admin/v3/certs.upbdefs.c", + "src/src/core/ext/upbdefs-generated/envoy/admin/v3/clusters.upbdefs.c", "src/src/core/ext/upbdefs-generated/envoy/admin/v3/config_dump.upbdefs.c", + "src/src/core/ext/upbdefs-generated/envoy/admin/v3/init_dump.upbdefs.c", + "src/src/core/ext/upbdefs-generated/envoy/admin/v3/listeners.upbdefs.c", + "src/src/core/ext/upbdefs-generated/envoy/admin/v3/memory.upbdefs.c", + "src/src/core/ext/upbdefs-generated/envoy/admin/v3/metrics.upbdefs.c", + "src/src/core/ext/upbdefs-generated/envoy/admin/v3/mutex_stats.upbdefs.c", + "src/src/core/ext/upbdefs-generated/envoy/admin/v3/server_info.upbdefs.c", + "src/src/core/ext/upbdefs-generated/envoy/admin/v3/tap.upbdefs.c", "src/src/core/ext/upbdefs-generated/envoy/annotations/deprecation.upbdefs.c", "src/src/core/ext/upbdefs-generated/envoy/annotations/resource.upbdefs.c", "src/src/core/ext/upbdefs-generated/envoy/config/accesslog/v3/accesslog.upbdefs.c", @@ -1229,12 +1325,14 @@ "src/src/core/ext/upbdefs-generated/envoy/config/cluster/v3/cluster.upbdefs.c", "src/src/core/ext/upbdefs-generated/envoy/config/cluster/v3/filter.upbdefs.c", "src/src/core/ext/upbdefs-generated/envoy/config/cluster/v3/outlier_detection.upbdefs.c", + "src/src/core/ext/upbdefs-generated/envoy/config/common/matcher/v3/matcher.upbdefs.c", "src/src/core/ext/upbdefs-generated/envoy/config/core/v3/address.upbdefs.c", "src/src/core/ext/upbdefs-generated/envoy/config/core/v3/backoff.upbdefs.c", "src/src/core/ext/upbdefs-generated/envoy/config/core/v3/base.upbdefs.c", "src/src/core/ext/upbdefs-generated/envoy/config/core/v3/config_source.upbdefs.c", "src/src/core/ext/upbdefs-generated/envoy/config/core/v3/event_service_config.upbdefs.c", "src/src/core/ext/upbdefs-generated/envoy/config/core/v3/extension.upbdefs.c", + "src/src/core/ext/upbdefs-generated/envoy/config/core/v3/grpc_method_list.upbdefs.c", "src/src/core/ext/upbdefs-generated/envoy/config/core/v3/grpc_service.upbdefs.c", "src/src/core/ext/upbdefs-generated/envoy/config/core/v3/health_check.upbdefs.c", "src/src/core/ext/upbdefs-generated/envoy/config/core/v3/http_uri.upbdefs.c", @@ -1252,30 +1350,38 @@ "src/src/core/ext/upbdefs-generated/envoy/config/listener/v3/listener_components.upbdefs.c", "src/src/core/ext/upbdefs-generated/envoy/config/listener/v3/quic_config.upbdefs.c", "src/src/core/ext/upbdefs-generated/envoy/config/listener/v3/udp_listener_config.upbdefs.c", + "src/src/core/ext/upbdefs-generated/envoy/config/metrics/v3/metrics_service.upbdefs.c", "src/src/core/ext/upbdefs-generated/envoy/config/metrics/v3/stats.upbdefs.c", "src/src/core/ext/upbdefs-generated/envoy/config/overload/v3/overload.upbdefs.c", "src/src/core/ext/upbdefs-generated/envoy/config/rbac/v3/rbac.upbdefs.c", "src/src/core/ext/upbdefs-generated/envoy/config/route/v3/route.upbdefs.c", "src/src/core/ext/upbdefs-generated/envoy/config/route/v3/route_components.upbdefs.c", "src/src/core/ext/upbdefs-generated/envoy/config/route/v3/scoped_route.upbdefs.c", + "src/src/core/ext/upbdefs-generated/envoy/config/tap/v3/common.upbdefs.c", + "src/src/core/ext/upbdefs-generated/envoy/config/trace/v3/datadog.upbdefs.c", + "src/src/core/ext/upbdefs-generated/envoy/config/trace/v3/dynamic_ot.upbdefs.c", "src/src/core/ext/upbdefs-generated/envoy/config/trace/v3/http_tracer.upbdefs.c", + "src/src/core/ext/upbdefs-generated/envoy/config/trace/v3/lightstep.upbdefs.c", + "src/src/core/ext/upbdefs-generated/envoy/config/trace/v3/opencensus.upbdefs.c", + "src/src/core/ext/upbdefs-generated/envoy/config/trace/v3/service.upbdefs.c", + "src/src/core/ext/upbdefs-generated/envoy/config/trace/v3/skywalking.upbdefs.c", + "src/src/core/ext/upbdefs-generated/envoy/config/trace/v3/trace.upbdefs.c", + "src/src/core/ext/upbdefs-generated/envoy/config/trace/v3/xray.upbdefs.c", + "src/src/core/ext/upbdefs-generated/envoy/config/trace/v3/zipkin.upbdefs.c", "src/src/core/ext/upbdefs-generated/envoy/extensions/filters/common/fault/v3/fault.upbdefs.c", "src/src/core/ext/upbdefs-generated/envoy/extensions/filters/http/router/v3/router.upbdefs.c", "src/src/core/ext/upbdefs-generated/envoy/extensions/filters/network/http_connection_manager/v3/http_connection_manager.upbdefs.c", "src/src/core/ext/upbdefs-generated/envoy/extensions/transport_sockets/tls/v3/cert.upbdefs.c", - "src/src/core/ext/upbdefs-generated/envoy/extensions/transport_sockets/tls/v3/common.upbdefs.c", "src/src/core/ext/upbdefs-generated/envoy/extensions/transport_sockets/tls/v3/secret.upbdefs.c", "src/src/core/ext/upbdefs-generated/envoy/extensions/transport_sockets/tls/v3/tls.upbdefs.c", - "src/src/core/ext/upbdefs-generated/envoy/service/cluster/v3/cds.upbdefs.c", + "src/src/core/ext/upbdefs-generated/envoy/extensions/transport_sockets/tls/v3/tls_spiffe_validator_config.upbdefs.c", "src/src/core/ext/upbdefs-generated/envoy/service/discovery/v3/ads.upbdefs.c", "src/src/core/ext/upbdefs-generated/envoy/service/discovery/v3/discovery.upbdefs.c", - "src/src/core/ext/upbdefs-generated/envoy/service/endpoint/v3/eds.upbdefs.c", - "src/src/core/ext/upbdefs-generated/envoy/service/listener/v3/lds.upbdefs.c", "src/src/core/ext/upbdefs-generated/envoy/service/load_stats/v3/lrs.upbdefs.c", - "src/src/core/ext/upbdefs-generated/envoy/service/route/v3/rds.upbdefs.c", - "src/src/core/ext/upbdefs-generated/envoy/service/route/v3/srds.upbdefs.c", "src/src/core/ext/upbdefs-generated/envoy/service/status/v3/csds.upbdefs.c", + "src/src/core/ext/upbdefs-generated/envoy/type/http/v3/cookie.upbdefs.c", "src/src/core/ext/upbdefs-generated/envoy/type/http/v3/path_transformation.upbdefs.c", + "src/src/core/ext/upbdefs-generated/envoy/type/matcher/v3/http_inputs.upbdefs.c", "src/src/core/ext/upbdefs-generated/envoy/type/matcher/v3/metadata.upbdefs.c", "src/src/core/ext/upbdefs-generated/envoy/type/matcher/v3/node.upbdefs.c", "src/src/core/ext/upbdefs-generated/envoy/type/matcher/v3/number.upbdefs.c", @@ -1285,21 +1391,25 @@ "src/src/core/ext/upbdefs-generated/envoy/type/matcher/v3/struct.upbdefs.c", "src/src/core/ext/upbdefs-generated/envoy/type/matcher/v3/value.upbdefs.c", "src/src/core/ext/upbdefs-generated/envoy/type/tracing/v3/custom_tag.upbdefs.c", + "src/src/core/ext/upbdefs-generated/envoy/type/v3/hash_policy.upbdefs.c", "src/src/core/ext/upbdefs-generated/envoy/type/v3/http.upbdefs.c", + "src/src/core/ext/upbdefs-generated/envoy/type/v3/http_status.upbdefs.c", "src/src/core/ext/upbdefs-generated/envoy/type/v3/percent.upbdefs.c", "src/src/core/ext/upbdefs-generated/envoy/type/v3/range.upbdefs.c", + "src/src/core/ext/upbdefs-generated/envoy/type/v3/ratelimit_unit.upbdefs.c", "src/src/core/ext/upbdefs-generated/envoy/type/v3/semantic_version.upbdefs.c", + "src/src/core/ext/upbdefs-generated/envoy/type/v3/token_bucket.upbdefs.c", "src/src/core/ext/upbdefs-generated/google/api/annotations.upbdefs.c", "src/src/core/ext/upbdefs-generated/google/api/expr/v1alpha1/checked.upbdefs.c", - "src/src/core/ext/upbdefs-generated/google/api/expr/v1alpha1/eval.upbdefs.c", - "src/src/core/ext/upbdefs-generated/google/api/expr/v1alpha1/explain.upbdefs.c", "src/src/core/ext/upbdefs-generated/google/api/expr/v1alpha1/syntax.upbdefs.c", + "src/src/core/ext/upbdefs-generated/google/api/httpbody.upbdefs.c", "src/src/core/ext/upbdefs-generated/google/protobuf/any.upbdefs.c", "src/src/core/ext/upbdefs-generated/google/protobuf/duration.upbdefs.c", "src/src/core/ext/upbdefs-generated/google/protobuf/empty.upbdefs.c", "src/src/core/ext/upbdefs-generated/google/protobuf/timestamp.upbdefs.c", "src/src/core/ext/upbdefs-generated/google/protobuf/wrappers.upbdefs.c", "src/src/core/ext/upbdefs-generated/google/rpc/status.upbdefs.c", + "src/src/core/ext/upbdefs-generated/opencensus/proto/trace/v1/trace_config.upbdefs.c", "src/src/core/ext/upbdefs-generated/udpa/annotations/migrate.upbdefs.c", "src/src/core/ext/upbdefs-generated/udpa/annotations/security.upbdefs.c", "src/src/core/ext/upbdefs-generated/udpa/annotations/sensitive.upbdefs.c", @@ -1324,6 +1434,7 @@ "src/src/core/lib/channel/connected_channel.cc", "src/src/core/lib/channel/handshaker.cc", "src/src/core/lib/channel/handshaker_registry.cc", + "src/src/core/lib/channel/promise_based_filter.cc", "src/src/core/lib/channel/status_util.cc", "src/src/core/lib/compression/compression.cc", "src/src/core/lib/compression/compression_internal.cc", @@ -1333,9 +1444,10 @@ "src/src/core/lib/debug/stats_data.cc", "src/src/core/lib/debug/trace.cc", "src/src/core/lib/event_engine/channel_args_endpoint_config.cc", + "src/src/core/lib/event_engine/default_event_engine_factory.cc", "src/src/core/lib/event_engine/event_engine.cc", - "src/src/core/lib/event_engine/event_engine_factory.cc", "src/src/core/lib/event_engine/memory_allocator.cc", + "src/src/core/lib/event_engine/resolved_address.cc", "src/src/core/lib/event_engine/sockaddr.cc", "src/src/core/lib/gpr/alloc.cc", "src/src/core/lib/gpr/atm.cc", @@ -1425,7 +1537,6 @@ "src/src/core/lib/iomgr/grpc_if_nametoindex_unsupported.cc", "src/src/core/lib/iomgr/internal_errqueue.cc", "src/src/core/lib/iomgr/iocp_windows.cc", - "src/src/core/lib/iomgr/iomgr_custom.cc", "src/src/core/lib/iomgr/iomgr_internal.cc", "src/src/core/lib/iomgr/iomgr_posix.cc", "src/src/core/lib/iomgr/iomgr_posix_cfstream.cc", @@ -1434,15 +1545,13 @@ "src/src/core/lib/iomgr/load_file.cc", "src/src/core/lib/iomgr/lockfree_event.cc", "src/src/core/lib/iomgr/polling_entity.cc", - "src/src/core/lib/iomgr/pollset_custom.cc", "src/src/core/lib/iomgr/pollset_set.cc", - "src/src/core/lib/iomgr/pollset_set_custom.cc", "src/src/core/lib/iomgr/pollset_set_windows.cc", "src/src/core/lib/iomgr/pollset_windows.cc", "src/src/core/lib/iomgr/resolve_address.cc", - "src/src/core/lib/iomgr/resolve_address_custom.cc", "src/src/core/lib/iomgr/resolve_address_posix.cc", "src/src/core/lib/iomgr/resolve_address_windows.cc", + "src/src/core/lib/iomgr/sockaddr_utils_posix.cc", "src/src/core/lib/iomgr/socket_factory_posix.cc", "src/src/core/lib/iomgr/socket_mutator.cc", "src/src/core/lib/iomgr/socket_utils_common_posix.cc", @@ -1452,13 +1561,10 @@ "src/src/core/lib/iomgr/socket_windows.cc", "src/src/core/lib/iomgr/tcp_client.cc", "src/src/core/lib/iomgr/tcp_client_cfstream.cc", - "src/src/core/lib/iomgr/tcp_client_custom.cc", "src/src/core/lib/iomgr/tcp_client_posix.cc", "src/src/core/lib/iomgr/tcp_client_windows.cc", - "src/src/core/lib/iomgr/tcp_custom.cc", "src/src/core/lib/iomgr/tcp_posix.cc", "src/src/core/lib/iomgr/tcp_server.cc", - "src/src/core/lib/iomgr/tcp_server_custom.cc", "src/src/core/lib/iomgr/tcp_server_posix.cc", "src/src/core/lib/iomgr/tcp_server_utils_posix_common.cc", "src/src/core/lib/iomgr/tcp_server_utils_posix_ifaddrs.cc", @@ -1466,7 +1572,6 @@ "src/src/core/lib/iomgr/tcp_server_windows.cc", "src/src/core/lib/iomgr/tcp_windows.cc", "src/src/core/lib/iomgr/time_averaged_stats.cc", - "src/src/core/lib/iomgr/timer_custom.cc", "src/src/core/lib/iomgr/timer_generic.cc", "src/src/core/lib/iomgr/timer_heap.cc", "src/src/core/lib/iomgr/timer_manager.cc", @@ -1485,6 +1590,7 @@ "src/src/core/lib/profiling/basic_timers.cc", "src/src/core/lib/profiling/stap_timers.cc", "src/src/core/lib/promise/activity.cc", + "src/src/core/lib/promise/sleep.cc", "src/src/core/lib/resolver/resolver_registry.cc", "src/src/core/lib/resolver/server_address.cc", "src/src/core/lib/resource_quota/api.cc", @@ -1496,8 +1602,9 @@ "src/src/core/lib/security/authorization/evaluate_args.cc", # "src/src/core/lib/security/authorization/grpc_authorization_engine.cc", + "src/src/core/lib/security/authorization/grpc_server_authz_filter.cc", + # "src/src/core/lib/security/authorization/rbac_policy.cc", - "src/src/core/lib/security/authorization/sdk_server_authz_filter.cc", "src/src/core/lib/security/context/security_context.cc", "src/src/core/lib/security/credentials/alts/alts_credentials.cc", "src/src/core/lib/security/credentials/alts/check_gcp_environment.cc", @@ -1507,6 +1614,8 @@ "src/src/core/lib/security/credentials/alts/grpc_alts_credentials_client_options.cc", "src/src/core/lib/security/credentials/alts/grpc_alts_credentials_options.cc", "src/src/core/lib/security/credentials/alts/grpc_alts_credentials_server_options.cc", + "src/src/core/lib/security/credentials/call_creds_util.cc", + "src/src/core/lib/security/credentials/channel_creds_registry_init.cc", "src/src/core/lib/security/credentials/composite/composite_credentials.cc", "src/src/core/lib/security/credentials/credentials.cc", "src/src/core/lib/security/credentials/external/aws_external_account_credentials.cc", @@ -1550,13 +1659,12 @@ "src/src/core/lib/security/transport/security_handshaker.cc", "src/src/core/lib/security/transport/server_auth_filter.cc", "src/src/core/lib/security/transport/tsi_error.cc", - "src/src/core/lib/service_config/service_config.cc", + "src/src/core/lib/service_config/service_config_impl.cc", "src/src/core/lib/slice/b64.cc", "src/src/core/lib/slice/percent_encoding.cc", "src/src/core/lib/slice/slice.cc", "src/src/core/lib/slice/slice_api.cc", "src/src/core/lib/slice/slice_buffer.cc", - "src/src/core/lib/slice/slice_intern.cc", "src/src/core/lib/slice/slice_refcount.cc", "src/src/core/lib/slice/slice_split.cc", "src/src/core/lib/slice/slice_string_helpers.cc", @@ -1575,7 +1683,6 @@ "src/src/core/lib/surface/completion_queue_factory.cc", "src/src/core/lib/surface/event_string.cc", "src/src/core/lib/surface/init.cc", - "src/src/core/lib/surface/init_secure.cc", "src/src/core/lib/surface/lame_client.cc", "src/src/core/lib/surface/metadata_array.cc", "src/src/core/lib/surface/server.cc", @@ -1592,6 +1699,7 @@ "src/src/core/lib/transport/transport.cc", "src/src/core/lib/transport/transport_op_string.cc", "src/src/core/lib/uri/uri_parser.cc", + "src/src/core/plugin_registry/grpc_plugin_registry_extra.cc", "src/src/core/tsi/alts/crypt/aes_gcm.cc", "src/src/core/tsi/alts/crypt/gsec.cc", "src/src/core/tsi/alts/frame_protector/alts_counter.cc", @@ -1613,6 +1721,7 @@ "src/src/core/tsi/alts/zero_copy_frame_protector/alts_zero_copy_grpc_protector.cc", "src/src/core/tsi/fake_transport_security.cc", "src/src/core/tsi/local_transport_security.cc", + "src/src/core/tsi/ssl/key_logging/ssl_key_logging.cc", "src/src/core/tsi/ssl/session_cache/ssl_session_boringssl.cc", "src/src/core/tsi/ssl/session_cache/ssl_session_cache.cc", "src/src/core/tsi/ssl/session_cache/ssl_session_openssl.cc", @@ -1695,25 +1804,41 @@ source_set("grpc++_repeated1") { sources = [ - "src/src/core/ext/transport/chttp2/client/insecure/channel_create.cc", "src/src/core/ext/upb-generated/envoy/extensions/clusters/aggregate/v3/cluster.upb.c", "src/src/core/ext/upb-generated/envoy/extensions/filters/http/fault/v3/fault.upb.c", "src/src/core/ext/upb-generated/envoy/extensions/filters/http/rbac/v3/rbac.upb.c", + "src/src/core/ext/upb-generated/envoy/extensions/transport_sockets/tls/v3/common.upb.c", "src/src/core/ext/upb-generated/envoy/type/metadata/v3/metadata.upb.c", - "src/src/core/ext/upb-generated/google/api/expr/v1alpha1/value.upb.c", "src/src/core/ext/upb-generated/google/api/http.upb.c", "src/src/core/ext/upb-generated/google/protobuf/struct.upb.c", "src/src/core/ext/upb-generated/udpa/annotations/status.upb.c", + "src/src/core/ext/upb-generated/xds/annotations/v3/migrate.upb.c", + "src/src/core/ext/upb-generated/xds/annotations/v3/security.upb.c", + "src/src/core/ext/upb-generated/xds/annotations/v3/sensitive.upb.c", + "src/src/core/ext/upb-generated/xds/annotations/v3/versioning.upb.c", + "src/src/core/ext/upb-generated/xds/core/v3/extension.upb.c", "src/src/core/ext/upb-generated/xds/core/v3/resource.upb.c", + "src/src/core/ext/upb-generated/xds/type/matcher/v3/matcher.upb.c", + "src/src/core/ext/upb-generated/xds/type/matcher/v3/regex.upb.c", + "src/src/core/ext/upb-generated/xds/type/matcher/v3/string.upb.c", "src/src/core/ext/upbdefs-generated/envoy/extensions/clusters/aggregate/v3/cluster.upbdefs.c", "src/src/core/ext/upbdefs-generated/envoy/extensions/filters/http/fault/v3/fault.upbdefs.c", "src/src/core/ext/upbdefs-generated/envoy/extensions/filters/http/rbac/v3/rbac.upbdefs.c", + "src/src/core/ext/upbdefs-generated/envoy/extensions/transport_sockets/tls/v3/common.upbdefs.c", "src/src/core/ext/upbdefs-generated/envoy/type/metadata/v3/metadata.upbdefs.c", - "src/src/core/ext/upbdefs-generated/google/api/expr/v1alpha1/value.upbdefs.c", "src/src/core/ext/upbdefs-generated/google/api/http.upbdefs.c", "src/src/core/ext/upbdefs-generated/google/protobuf/struct.upbdefs.c", "src/src/core/ext/upbdefs-generated/udpa/annotations/status.upbdefs.c", + "src/src/core/ext/upbdefs-generated/xds/annotations/v3/migrate.upbdefs.c", + "src/src/core/ext/upbdefs-generated/xds/annotations/v3/security.upbdefs.c", + "src/src/core/ext/upbdefs-generated/xds/annotations/v3/sensitive.upbdefs.c", + "src/src/core/ext/upbdefs-generated/xds/annotations/v3/versioning.upbdefs.c", + "src/src/core/ext/upbdefs-generated/xds/core/v3/extension.upbdefs.c", "src/src/core/ext/upbdefs-generated/xds/core/v3/resource.upbdefs.c", + "src/src/core/ext/upbdefs-generated/xds/type/matcher/v3/matcher.upbdefs.c", + "src/src/core/ext/upbdefs-generated/xds/type/matcher/v3/regex.upbdefs.c", + "src/src/core/ext/upbdefs-generated/xds/type/matcher/v3/string.upbdefs.c", + "src/src/core/lib/gprpp/time.cc", "src/src/core/lib/iomgr/event_engine/endpoint.cc", "src/src/core/lib/iomgr/iomgr.cc", "src/src/core/lib/iomgr/pollset.cc", @@ -1834,6 +1959,10 @@ "src/src/core/ext/upb-generated/google/protobuf/descriptor.upb.h", "src/src/core/ext/upbdefs-generated/google/protobuf/descriptor.upbdefs.c", "src/src/core/ext/upbdefs-generated/google/protobuf/descriptor.upbdefs.h", + "src/third_party/upb/third_party/utf8_range/naive.c", + "src/third_party/upb/third_party/utf8_range/range2-neon.c", + "src/third_party/upb/third_party/utf8_range/range2-sse.c", + "src/third_party/upb/third_party/utf8_range/utf8_range.h", "src/third_party/upb/upb/decode.c", "src/third_party/upb/upb/decode.h", "src/third_party/upb/upb/decode_fast.c",
diff --git a/third_party/grpc/README.chromium b/third_party/grpc/README.chromium index e2741daa..721f230 100644 --- a/third_party/grpc/README.chromium +++ b/third_party/grpc/README.chromium
@@ -1,8 +1,8 @@ Name: grpc URL: https://github.com/grpc/grpc License: Apache 2.0 -Version: v1.43.0+ -Revision: 754913545189b819829284b79ac5a4d31fddbdcc +Version: v1.44.0+ +Revision: f8a909e76fcd947949502832a7ab8e2cba2b8e27 Security Critical: yes Please note that that the use of gRPC is not generally allowed within Chromium.
diff --git a/third_party/grpc/plugin_registry/grpc_plugin_registry.cc b/third_party/grpc/plugin_registry/grpc_plugin_registry.cc index 1130cb3..a626aeb 100644 --- a/third_party/grpc/plugin_registry/grpc_plugin_registry.cc +++ b/third_party/grpc/plugin_registry/grpc_plugin_registry.cc
@@ -27,12 +27,12 @@ #include "third_party/grpc/src/src/core/lib/config/core_configuration.h" #include "third_party/grpc/src/src/core/lib/surface/builtins.h" +extern void grpc_register_extra_plugins(void); + void grpc_chttp2_plugin_init(void); void grpc_chttp2_plugin_shutdown(void); void grpc_client_channel_init(void); void grpc_client_channel_shutdown(void); -void grpc_resolver_fake_init(void); -void grpc_resolver_fake_shutdown(void); void grpc_lb_policy_grpclb_init(void); void grpc_lb_policy_grpclb_shutdown(void); void grpc_lb_policy_priority_init(void); @@ -45,71 +45,24 @@ void grpc_lb_policy_round_robin_shutdown(void); void grpc_resolver_dns_ares_init(void); void grpc_resolver_dns_ares_shutdown(void); -void grpc_resolver_dns_native_init(void); -void grpc_resolver_dns_native_shutdown(void); -void grpc_resolver_sockaddr_init(void); -void grpc_resolver_sockaddr_shutdown(void); -void grpc_message_size_filter_init(void); -void grpc_message_size_filter_shutdown(void); namespace grpc_core { -void FaultInjectionFilterInit(void); -void FaultInjectionFilterShutdown(void); void GrpcLbPolicyRingHashInit(void); void GrpcLbPolicyRingHashShutdown(void); #ifndef GRPC_NO_RLS void RlsLbPluginInit(); void RlsLbPluginShutdown(); #endif // !GRPC_NO_RLS -void ServiceConfigParserInit(void); -void ServiceConfigParserShutdown(void); } // namespace grpc_core -#ifndef GRPC_NO_XDS -namespace grpc_core { -void RbacFilterInit(void); -void RbacFilterShutdown(void); -void XdsClientGlobalInit(); -void XdsClientGlobalShutdown(); -} // namespace grpc_core -void grpc_certificate_provider_registry_init(void); -void grpc_certificate_provider_registry_shutdown(void); -namespace grpc_core { -void FileWatcherCertificateProviderInit(); -void FileWatcherCertificateProviderShutdown(); -} // namespace grpc_core -void grpc_lb_policy_cds_init(void); -void grpc_lb_policy_cds_shutdown(void); -void grpc_lb_policy_xds_cluster_impl_init(void); -void grpc_lb_policy_xds_cluster_impl_shutdown(void); -void grpc_lb_policy_xds_cluster_resolver_init(void); -void grpc_lb_policy_xds_cluster_resolver_shutdown(void); -void grpc_lb_policy_xds_cluster_manager_init(void); -void grpc_lb_policy_xds_cluster_manager_shutdown(void); -void grpc_resolver_xds_init(void); -void grpc_resolver_xds_shutdown(void); -namespace grpc_core { -void GoogleCloud2ProdResolverInit(); -void GoogleCloud2ProdResolverShutdown(); -} // namespace grpc_core -#endif - -#ifdef GPR_SUPPORT_BINDER_TRANSPORT -void grpc_resolver_binder_init(void); -void grpc_resolver_binder_shutdown(void); -#endif - void grpc_register_built_in_plugins(void) { - grpc_register_plugin(grpc_chttp2_plugin_init, grpc_chttp2_plugin_shutdown); - grpc_register_plugin(grpc_core::ServiceConfigParserInit, - grpc_core::ServiceConfigParserShutdown); grpc_register_plugin(grpc_client_channel_init, grpc_client_channel_shutdown); - grpc_register_plugin(grpc_resolver_fake_init, grpc_resolver_fake_shutdown); // grpc_register_plugin(grpc_lb_policy_grpclb_init, // grpc_lb_policy_grpclb_shutdown); #ifndef GRPC_NO_RLS grpc_register_plugin(grpc_core::RlsLbPluginInit, grpc_core::RlsLbPluginShutdown); #endif // !GRPC_NO_RLS + // grpc_register_plugin(grpc_lb_policy_priority_init, // grpc_lb_policy_priority_shutdown); // grpc_register_plugin(grpc_lb_policy_weighted_target_init, @@ -122,41 +75,7 @@ // grpc_core::GrpcLbPolicyRingHashShutdown); grpc_register_plugin(grpc_resolver_dns_ares_init, grpc_resolver_dns_ares_shutdown); - grpc_register_plugin(grpc_resolver_dns_native_init, - grpc_resolver_dns_native_shutdown); - grpc_register_plugin(grpc_resolver_sockaddr_init, - grpc_resolver_sockaddr_shutdown); - grpc_register_plugin(grpc_message_size_filter_init, - grpc_message_size_filter_shutdown); - grpc_register_plugin(grpc_core::FaultInjectionFilterInit, - grpc_core::FaultInjectionFilterShutdown); -#ifndef GRPC_NO_XDS - // rbac_filter is being guarded with GRPC_NO_XDS to avoid a dependency on the - // re2 library by default - grpc_register_plugin(grpc_core::RbacFilterInit, - grpc_core::RbacFilterShutdown); - grpc_register_plugin(grpc_core::XdsClientGlobalInit, - grpc_core::XdsClientGlobalShutdown); - grpc_register_plugin(grpc_certificate_provider_registry_init, - grpc_certificate_provider_registry_shutdown); - grpc_register_plugin(grpc_core::FileWatcherCertificateProviderInit, - grpc_core::FileWatcherCertificateProviderShutdown); - grpc_register_plugin(grpc_lb_policy_cds_init, grpc_lb_policy_cds_shutdown); - grpc_register_plugin(grpc_lb_policy_xds_cluster_impl_init, - grpc_lb_policy_xds_cluster_impl_shutdown); - grpc_register_plugin(grpc_lb_policy_xds_cluster_resolver_init, - grpc_lb_policy_xds_cluster_resolver_shutdown); - grpc_register_plugin(grpc_lb_policy_xds_cluster_manager_init, - grpc_lb_policy_xds_cluster_manager_shutdown); - grpc_register_plugin(grpc_resolver_xds_init, grpc_resolver_xds_shutdown); - grpc_register_plugin(grpc_core::GoogleCloud2ProdResolverInit, - grpc_core::GoogleCloud2ProdResolverShutdown); -#endif - -#ifdef GPR_SUPPORT_BINDER_TRANSPORT - grpc_register_plugin(grpc_resolver_binder_init, - grpc_resolver_binder_shutdown); -#endif + grpc_register_extra_plugins(); } namespace grpc_core { @@ -176,10 +95,15 @@ extern void RegisterSecurityFilters(CoreConfiguration::Builder* builder); extern void RegisterServiceConfigChannelArgFilter( CoreConfiguration::Builder* builder); +extern void RegisterExtraFilters(CoreConfiguration::Builder* builder); extern void RegisterResourceQuota(CoreConfiguration::Builder* builder); -#ifndef GRPC_NO_XDS -extern void RegisterXdsChannelStackModifier( - CoreConfiguration::Builder* builder); +extern void FaultInjectionFilterRegister(CoreConfiguration::Builder* builder); +extern void RegisterNativeDnsResolver(CoreConfiguration::Builder* builder); +extern void RegisterAresDnsResolver(CoreConfiguration::Builder* builder); +extern void RegisterSockaddrResolver(CoreConfiguration::Builder* builder); +extern void RegisterFakeResolver(CoreConfiguration::Builder* builder); +#ifdef GPR_SUPPORT_BINDER_TRANSPORT +extern void RegisterBinderResolver(CoreConfiguration::Builder* builder); #endif void BuildCoreConfiguration(CoreConfiguration::Builder* builder) { @@ -194,12 +118,18 @@ RegisterMessageSizeFilter(builder); RegisterServiceConfigChannelArgFilter(builder); RegisterResourceQuota(builder); -#ifndef GRPC_NO_XDS - RegisterXdsChannelStackModifier(builder); + FaultInjectionFilterRegister(builder); + RegisterAresDnsResolver(builder); + RegisterNativeDnsResolver(builder); + RegisterSockaddrResolver(builder); + RegisterFakeResolver(builder); +#ifdef GPR_SUPPORT_BINDER_TRANSPORT + RegisterBinderResolver(builder); #endif // Run last so it gets a consistent location. // TODO(ctiller): Is this actually necessary? RegisterSecurityFilters(builder); + RegisterExtraFilters(builder); RegisterBuiltins(builder); }
diff --git a/third_party/grpc/template/BUILD.chromium.gn.template b/third_party/grpc/template/BUILD.chromium.gn.template index 924bd88..22742ff2 100644 --- a/third_party/grpc/template/BUILD.chromium.gn.template +++ b/third_party/grpc/template/BUILD.chromium.gn.template
@@ -57,6 +57,7 @@ "-Wno-implicit-fallthrough", "-Wno-shadow", "-Wno-unreachable-code-return", + "-Wno-unreachable-code-break", ] if (is_android) {
diff --git a/third_party/rust/aho_corasick/v0_7/BUILD.gn b/third_party/rust/aho_corasick/v0_7/BUILD.gn index 2a9a9bb..67fd89cd 100644 --- a/third_party/rust/aho_corasick/v0_7/BUILD.gn +++ b/third_party/rust/aho_corasick/v0_7/BUILD.gn
@@ -15,7 +15,7 @@ crate_root = "crate/src/lib.rs" # Unit tests skipped. Generate with --with-tests to include them. - skip_unit_tests = true + build_native_rust_unit_tests = false sources = [ "crate/src/lib.rs" ] edition = "2018" deps = [ "//third_party/rust/memchr/v2:lib" ]
diff --git a/third_party/rust/ansi_term/v0_11/BUILD.gn b/third_party/rust/ansi_term/v0_11/BUILD.gn index 40d2e645..0af45316 100644 --- a/third_party/rust/ansi_term/v0_11/BUILD.gn +++ b/third_party/rust/ansi_term/v0_11/BUILD.gn
@@ -16,7 +16,7 @@ crate_root = "crate/src/lib.rs" # Unit tests skipped. Generate with --with-tests to include them. - skip_unit_tests = true + build_native_rust_unit_tests = false sources = [ "crate/src/lib.rs" ] edition = "2015" }
diff --git a/third_party/rust/aquamarine/v0_1/BUILD.gn b/third_party/rust/aquamarine/v0_1/BUILD.gn index 465556ee..4c20851 100644 --- a/third_party/rust/aquamarine/v0_1/BUILD.gn +++ b/third_party/rust/aquamarine/v0_1/BUILD.gn
@@ -15,7 +15,7 @@ crate_root = "crate/src/lib.rs" # Unit tests skipped. Generate with --with-tests to include them. - skip_unit_tests = true + build_native_rust_unit_tests = false sources = [ "crate/src/lib.rs" ] edition = "2018" deps = [
diff --git a/third_party/rust/atty/v0_2/BUILD.gn b/third_party/rust/atty/v0_2/BUILD.gn index 4274e04..0f6cc09 100644 --- a/third_party/rust/atty/v0_2/BUILD.gn +++ b/third_party/rust/atty/v0_2/BUILD.gn
@@ -15,7 +15,7 @@ crate_root = "crate/src/lib.rs" # Unit tests skipped. Generate with --with-tests to include them. - skip_unit_tests = true + build_native_rust_unit_tests = false sources = [ "crate/src/lib.rs" ] edition = "2015" deps = []
diff --git a/third_party/rust/autocxx/v0_16/BUILD.gn b/third_party/rust/autocxx/v0_16/BUILD.gn index 710eedd..411e5b5 100644 --- a/third_party/rust/autocxx/v0_16/BUILD.gn +++ b/third_party/rust/autocxx/v0_16/BUILD.gn
@@ -11,7 +11,7 @@ crate_root = "crate/src/lib.rs" # Unit tests skipped. Generate with --with-tests to include them. - skip_unit_tests = true + build_native_rust_unit_tests = false sources = [ "crate/src/lib.rs" ] edition = "2021" deps = [
diff --git a/third_party/rust/autocxx_bindgen/v0_59/BUILD.gn b/third_party/rust/autocxx_bindgen/v0_59/BUILD.gn index 6b72318..d7beebf 100644 --- a/third_party/rust/autocxx_bindgen/v0_59/BUILD.gn +++ b/third_party/rust/autocxx_bindgen/v0_59/BUILD.gn
@@ -11,7 +11,7 @@ crate_root = "crate/src/lib.rs" # Unit tests skipped. Generate with --with-tests to include them. - skip_unit_tests = true + build_native_rust_unit_tests = false sources = [ "crate/src/lib.rs" ] edition = "2018" deps = [
diff --git a/third_party/rust/autocxx_engine/v0_16/BUILD.gn b/third_party/rust/autocxx_engine/v0_16/BUILD.gn index 54dd611..9de2d4c7 100644 --- a/third_party/rust/autocxx_engine/v0_16/BUILD.gn +++ b/third_party/rust/autocxx_engine/v0_16/BUILD.gn
@@ -15,7 +15,7 @@ crate_root = "crate/src/lib.rs" # Unit tests skipped. Generate with --with-tests to include them. - skip_unit_tests = true + build_native_rust_unit_tests = false sources = [ "crate/src/lib.rs" ] edition = "2021" deps = [
diff --git a/third_party/rust/autocxx_macro/v0_16/BUILD.gn b/third_party/rust/autocxx_macro/v0_16/BUILD.gn index 5da1c516..b94b7fb 100644 --- a/third_party/rust/autocxx_macro/v0_16/BUILD.gn +++ b/third_party/rust/autocxx_macro/v0_16/BUILD.gn
@@ -15,7 +15,7 @@ crate_root = "crate/src/lib.rs" # Unit tests skipped. Generate with --with-tests to include them. - skip_unit_tests = true + build_native_rust_unit_tests = false sources = [ "crate/src/lib.rs" ] edition = "2021" deps = [
diff --git a/third_party/rust/autocxx_parser/v0_16/BUILD.gn b/third_party/rust/autocxx_parser/v0_16/BUILD.gn index 2fa0421e..2905b012 100644 --- a/third_party/rust/autocxx_parser/v0_16/BUILD.gn +++ b/third_party/rust/autocxx_parser/v0_16/BUILD.gn
@@ -15,7 +15,7 @@ crate_root = "crate/src/lib.rs" # Unit tests skipped. Generate with --with-tests to include them. - skip_unit_tests = true + build_native_rust_unit_tests = false sources = [ "crate/src/lib.rs" ] edition = "2021" deps = [
diff --git a/third_party/rust/bindgen/v0_59/BUILD.gn b/third_party/rust/bindgen/v0_59/BUILD.gn index 9be249d6..ab02481 100644 --- a/third_party/rust/bindgen/v0_59/BUILD.gn +++ b/third_party/rust/bindgen/v0_59/BUILD.gn
@@ -47,7 +47,7 @@ crate_root = "crate/src/lib.rs" # Unit tests skipped. Generate with --with-tests to include them. - skip_unit_tests = true + build_native_rust_unit_tests = false sources = [ "crate/src/lib.rs" ] edition = "2018" deps = [
diff --git a/third_party/rust/bitflags/v1/BUILD.gn b/third_party/rust/bitflags/v1/BUILD.gn index b11610e..7ddd1e7 100644 --- a/third_party/rust/bitflags/v1/BUILD.gn +++ b/third_party/rust/bitflags/v1/BUILD.gn
@@ -15,7 +15,7 @@ crate_root = "crate/src/lib.rs" # Unit tests skipped. Generate with --with-tests to include them. - skip_unit_tests = true + build_native_rust_unit_tests = false sources = [ "crate/src/lib.rs" ] edition = "2018" }
diff --git a/third_party/rust/cexpr/v0_6/BUILD.gn b/third_party/rust/cexpr/v0_6/BUILD.gn index 903a93a..fb039531 100644 --- a/third_party/rust/cexpr/v0_6/BUILD.gn +++ b/third_party/rust/cexpr/v0_6/BUILD.gn
@@ -15,7 +15,7 @@ crate_root = "crate/src/lib.rs" # Unit tests skipped. Generate with --with-tests to include them. - skip_unit_tests = true + build_native_rust_unit_tests = false sources = [ "crate/src/lib.rs" ] edition = "2018" deps = [ "//third_party/rust/nom/v7:lib" ]
diff --git a/third_party/rust/cfg_if/v1/BUILD.gn b/third_party/rust/cfg_if/v1/BUILD.gn index c6570b7..20da8ba 100644 --- a/third_party/rust/cfg_if/v1/BUILD.gn +++ b/third_party/rust/cfg_if/v1/BUILD.gn
@@ -15,7 +15,7 @@ crate_root = "crate/src/lib.rs" # Unit tests skipped. Generate with --with-tests to include them. - skip_unit_tests = true + build_native_rust_unit_tests = false sources = [ "crate/src/lib.rs" ] edition = "2018" }
diff --git a/third_party/rust/clang_sys/v1/BUILD.gn b/third_party/rust/clang_sys/v1/BUILD.gn index ca1adcc..4ff86b28 100644 --- a/third_party/rust/clang_sys/v1/BUILD.gn +++ b/third_party/rust/clang_sys/v1/BUILD.gn
@@ -15,7 +15,7 @@ crate_root = "crate/src/lib.rs" # Unit tests skipped. Generate with --with-tests to include them. - skip_unit_tests = true + build_native_rust_unit_tests = false sources = [ "crate/src/lib.rs" ] edition = "2015" deps = [
diff --git a/third_party/rust/clap/v2/BUILD.gn b/third_party/rust/clap/v2/BUILD.gn index c576ecf2..d52bcb39 100644 --- a/third_party/rust/clap/v2/BUILD.gn +++ b/third_party/rust/clap/v2/BUILD.gn
@@ -15,7 +15,7 @@ crate_root = "crate/src/lib.rs" # Unit tests skipped. Generate with --with-tests to include them. - skip_unit_tests = true + build_native_rust_unit_tests = false sources = [ "crate/src/lib.rs" ] edition = "2015" deps = [
diff --git a/third_party/rust/codespan_reporting/v0_11/BUILD.gn b/third_party/rust/codespan_reporting/v0_11/BUILD.gn index 55d61e3..a61a733 100644 --- a/third_party/rust/codespan_reporting/v0_11/BUILD.gn +++ b/third_party/rust/codespan_reporting/v0_11/BUILD.gn
@@ -15,7 +15,7 @@ crate_root = "crate/src/lib.rs" # Unit tests skipped. Generate with --with-tests to include them. - skip_unit_tests = true + build_native_rust_unit_tests = false sources = [ "crate/src/lib.rs" ] edition = "2018" deps = [
diff --git a/third_party/rust/cxx/v1/BUILD.gn b/third_party/rust/cxx/v1/BUILD.gn index 6998416e..ab59da3 100644 --- a/third_party/rust/cxx/v1/BUILD.gn +++ b/third_party/rust/cxx/v1/BUILD.gn
@@ -11,7 +11,7 @@ crate_root = "crate/src/lib.rs" # Unit tests skipped. Generate with --with-tests to include them. - skip_unit_tests = true + build_native_rust_unit_tests = false sources = [ "crate/src/lib.rs" ] edition = "2018" deps = [
diff --git a/third_party/rust/cxx_gen/v0_7/BUILD.gn b/third_party/rust/cxx_gen/v0_7/BUILD.gn index 3609105..0d2634fe 100644 --- a/third_party/rust/cxx_gen/v0_7/BUILD.gn +++ b/third_party/rust/cxx_gen/v0_7/BUILD.gn
@@ -15,7 +15,7 @@ crate_root = "crate/src/lib.rs" # Unit tests skipped. Generate with --with-tests to include them. - skip_unit_tests = true + build_native_rust_unit_tests = false sources = [ "crate/src/lib.rs" ] edition = "2018" deps = [
diff --git a/third_party/rust/cxxbridge_cmd/v1/BUILD.gn b/third_party/rust/cxxbridge_cmd/v1/BUILD.gn index b0f13164..92b5c73 100644 --- a/third_party/rust/cxxbridge_cmd/v1/BUILD.gn +++ b/third_party/rust/cxxbridge_cmd/v1/BUILD.gn
@@ -24,7 +24,7 @@ crate_root = "crate/src/lib.rs" # Unit tests skipped. Generate with --with-tests to include them. - skip_unit_tests = true + build_native_rust_unit_tests = false sources = [ "crate/src/lib.rs" ] edition = "2018" deps = [
diff --git a/third_party/rust/cxxbridge_macro/v1/BUILD.gn b/third_party/rust/cxxbridge_macro/v1/BUILD.gn index d78bd9b47..07ebe4b 100644 --- a/third_party/rust/cxxbridge_macro/v1/BUILD.gn +++ b/third_party/rust/cxxbridge_macro/v1/BUILD.gn
@@ -15,7 +15,7 @@ crate_root = "crate/src/lib.rs" # Unit tests skipped. Generate with --with-tests to include them. - skip_unit_tests = true + build_native_rust_unit_tests = false sources = [ "crate/src/lib.rs" ] edition = "2018" deps = [
diff --git a/third_party/rust/either/v1/BUILD.gn b/third_party/rust/either/v1/BUILD.gn index 64332498..3d0cc31 100644 --- a/third_party/rust/either/v1/BUILD.gn +++ b/third_party/rust/either/v1/BUILD.gn
@@ -15,7 +15,7 @@ crate_root = "crate/src/lib.rs" # Unit tests skipped. Generate with --with-tests to include them. - skip_unit_tests = true + build_native_rust_unit_tests = false sources = [ "crate/src/lib.rs" ] edition = "2015" features = [ "use_std" ]
diff --git a/third_party/rust/env_logger/v0_9/BUILD.gn b/third_party/rust/env_logger/v0_9/BUILD.gn index e9a48165..4b58b75f 100644 --- a/third_party/rust/env_logger/v0_9/BUILD.gn +++ b/third_party/rust/env_logger/v0_9/BUILD.gn
@@ -15,7 +15,7 @@ crate_root = "crate/src/lib.rs" # Unit tests skipped. Generate with --with-tests to include them. - skip_unit_tests = true + build_native_rust_unit_tests = false sources = [ "crate/src/lib.rs" ] edition = "2018" deps = [
diff --git a/third_party/rust/fastrand/v1/BUILD.gn b/third_party/rust/fastrand/v1/BUILD.gn index 017f25b7..caff98d 100644 --- a/third_party/rust/fastrand/v1/BUILD.gn +++ b/third_party/rust/fastrand/v1/BUILD.gn
@@ -15,7 +15,7 @@ crate_root = "crate/src/lib.rs" # Unit tests skipped. Generate with --with-tests to include them. - skip_unit_tests = true + build_native_rust_unit_tests = false sources = [ "crate/src/lib.rs" ] edition = "2018" }
diff --git a/third_party/rust/glob/v0_3/BUILD.gn b/third_party/rust/glob/v0_3/BUILD.gn index 99f30a27..0ed91dde 100644 --- a/third_party/rust/glob/v0_3/BUILD.gn +++ b/third_party/rust/glob/v0_3/BUILD.gn
@@ -15,7 +15,7 @@ crate_root = "crate/src/lib.rs" # Unit tests skipped. Generate with --with-tests to include them. - skip_unit_tests = true + build_native_rust_unit_tests = false sources = [ "crate/src/lib.rs" ] edition = "2015" }
diff --git a/third_party/rust/heck/v0_3/BUILD.gn b/third_party/rust/heck/v0_3/BUILD.gn index ae8a883e..faa3ea9 100644 --- a/third_party/rust/heck/v0_3/BUILD.gn +++ b/third_party/rust/heck/v0_3/BUILD.gn
@@ -15,7 +15,7 @@ crate_root = "crate/src/lib.rs" # Unit tests skipped. Generate with --with-tests to include them. - skip_unit_tests = true + build_native_rust_unit_tests = false sources = [ "crate/src/lib.rs" ] edition = "2018" deps = [ "//third_party/rust/unicode_segmentation/v1:lib" ]
diff --git a/third_party/rust/humantime/v2/BUILD.gn b/third_party/rust/humantime/v2/BUILD.gn index ea50c2e..8aa698f 100644 --- a/third_party/rust/humantime/v2/BUILD.gn +++ b/third_party/rust/humantime/v2/BUILD.gn
@@ -15,7 +15,7 @@ crate_root = "crate/src/lib.rs" # Unit tests skipped. Generate with --with-tests to include them. - skip_unit_tests = true + build_native_rust_unit_tests = false sources = [ "crate/src/lib.rs" ] edition = "2018" }
diff --git a/third_party/rust/indoc/v1/BUILD.gn b/third_party/rust/indoc/v1/BUILD.gn index 13ead02..747d0acc 100644 --- a/third_party/rust/indoc/v1/BUILD.gn +++ b/third_party/rust/indoc/v1/BUILD.gn
@@ -15,7 +15,7 @@ crate_root = "crate/src/lib.rs" # Unit tests skipped. Generate with --with-tests to include them. - skip_unit_tests = true + build_native_rust_unit_tests = false sources = [ "crate/src/lib.rs" ] edition = "2018" deps = [ "//third_party/rust/unindent/v0_1:lib" ]
diff --git a/third_party/rust/itertools/v0_10/BUILD.gn b/third_party/rust/itertools/v0_10/BUILD.gn index c5fd24ed..0553a072 100644 --- a/third_party/rust/itertools/v0_10/BUILD.gn +++ b/third_party/rust/itertools/v0_10/BUILD.gn
@@ -15,7 +15,7 @@ crate_root = "crate/src/lib.rs" # Unit tests skipped. Generate with --with-tests to include them. - skip_unit_tests = true + build_native_rust_unit_tests = false sources = [ "crate/src/lib.rs" ] edition = "2018" deps = [ "//third_party/rust/either/v1:lib" ]
diff --git a/third_party/rust/itertools/v0_9/BUILD.gn b/third_party/rust/itertools/v0_9/BUILD.gn index f8d03077..1ad1b25 100644 --- a/third_party/rust/itertools/v0_9/BUILD.gn +++ b/third_party/rust/itertools/v0_9/BUILD.gn
@@ -15,7 +15,7 @@ crate_root = "crate/src/lib.rs" # Unit tests skipped. Generate with --with-tests to include them. - skip_unit_tests = true + build_native_rust_unit_tests = false sources = [ "crate/src/lib.rs" ] edition = "2018" deps = [ "//third_party/rust/either/v1:lib" ]
diff --git a/third_party/rust/itoa/v0_4/BUILD.gn b/third_party/rust/itoa/v0_4/BUILD.gn index 11c9d7b..63c6c85 100644 --- a/third_party/rust/itoa/v0_4/BUILD.gn +++ b/third_party/rust/itoa/v0_4/BUILD.gn
@@ -15,7 +15,7 @@ crate_root = "crate/src/lib.rs" # Unit tests skipped. Generate with --with-tests to include them. - skip_unit_tests = true + build_native_rust_unit_tests = false sources = [ "crate/src/lib.rs" ] edition = "2015" }
diff --git a/third_party/rust/itoa/v1/BUILD.gn b/third_party/rust/itoa/v1/BUILD.gn index 83fbfa4..c6ee850e 100644 --- a/third_party/rust/itoa/v1/BUILD.gn +++ b/third_party/rust/itoa/v1/BUILD.gn
@@ -15,7 +15,7 @@ crate_root = "crate/src/lib.rs" # Unit tests skipped. Generate with --with-tests to include them. - skip_unit_tests = true + build_native_rust_unit_tests = false sources = [ "crate/src/lib.rs" ] edition = "2018" }
diff --git a/third_party/rust/lazy_static/v1/BUILD.gn b/third_party/rust/lazy_static/v1/BUILD.gn index f75f5fed..ab0678f 100644 --- a/third_party/rust/lazy_static/v1/BUILD.gn +++ b/third_party/rust/lazy_static/v1/BUILD.gn
@@ -15,7 +15,7 @@ crate_root = "crate/src/lib.rs" # Unit tests skipped. Generate with --with-tests to include them. - skip_unit_tests = true + build_native_rust_unit_tests = false sources = [ "crate/src/lib.rs" ] edition = "2015" }
diff --git a/third_party/rust/lazycell/v1/BUILD.gn b/third_party/rust/lazycell/v1/BUILD.gn index 59ad931..6e47cb7c 100644 --- a/third_party/rust/lazycell/v1/BUILD.gn +++ b/third_party/rust/lazycell/v1/BUILD.gn
@@ -15,7 +15,7 @@ crate_root = "crate/src/lib.rs" # Unit tests skipped. Generate with --with-tests to include them. - skip_unit_tests = true + build_native_rust_unit_tests = false sources = [ "crate/src/lib.rs" ] edition = "2015" }
diff --git a/third_party/rust/libc/v0_2/BUILD.gn b/third_party/rust/libc/v0_2/BUILD.gn index 9973a72e..6b331db 100644 --- a/third_party/rust/libc/v0_2/BUILD.gn +++ b/third_party/rust/libc/v0_2/BUILD.gn
@@ -16,7 +16,7 @@ crate_root = "crate/src/lib.rs" # Unit tests skipped. Generate with --with-tests to include them. - skip_unit_tests = true + build_native_rust_unit_tests = false sources = [ "crate/src/lib.rs" ] edition = "2015" features = [ "std" ]
diff --git a/third_party/rust/libloading/v0_7/BUILD.gn b/third_party/rust/libloading/v0_7/BUILD.gn index 64526eca..2e85286 100644 --- a/third_party/rust/libloading/v0_7/BUILD.gn +++ b/third_party/rust/libloading/v0_7/BUILD.gn
@@ -15,7 +15,7 @@ crate_root = "crate/src/lib.rs" # Unit tests skipped. Generate with --with-tests to include them. - skip_unit_tests = true + build_native_rust_unit_tests = false sources = [ "crate/src/lib.rs" ] edition = "2015" deps = []
diff --git a/third_party/rust/link_cplusplus/v1/BUILD.gn b/third_party/rust/link_cplusplus/v1/BUILD.gn index 479a5708..87c221b 100644 --- a/third_party/rust/link_cplusplus/v1/BUILD.gn +++ b/third_party/rust/link_cplusplus/v1/BUILD.gn
@@ -15,7 +15,7 @@ crate_root = "crate/src/lib.rs" # Unit tests skipped. Generate with --with-tests to include them. - skip_unit_tests = true + build_native_rust_unit_tests = false sources = [ "crate/src/lib.rs" ] edition = "2018" build_root = "crate/build.rs"
diff --git a/third_party/rust/log/v0_4/BUILD.gn b/third_party/rust/log/v0_4/BUILD.gn index 31ae0785f..7266cb05 100644 --- a/third_party/rust/log/v0_4/BUILD.gn +++ b/third_party/rust/log/v0_4/BUILD.gn
@@ -15,7 +15,7 @@ crate_root = "crate/src/lib.rs" # Unit tests skipped. Generate with --with-tests to include them. - skip_unit_tests = true + build_native_rust_unit_tests = false sources = [ "crate/src/lib.rs" ] edition = "2015" deps = [ "//third_party/rust/cfg_if/v1:lib" ]
diff --git a/third_party/rust/memchr/v2/BUILD.gn b/third_party/rust/memchr/v2/BUILD.gn index 010b223..1594f10 100644 --- a/third_party/rust/memchr/v2/BUILD.gn +++ b/third_party/rust/memchr/v2/BUILD.gn
@@ -15,7 +15,7 @@ crate_root = "crate/src/lib.rs" # Unit tests skipped. Generate with --with-tests to include them. - skip_unit_tests = true + build_native_rust_unit_tests = false sources = [ "crate/src/lib.rs" ] edition = "2018" features = [ "std" ]
diff --git a/third_party/rust/minimal_lexical/v0_2/BUILD.gn b/third_party/rust/minimal_lexical/v0_2/BUILD.gn index 3fab64a7..a9ab52c45 100644 --- a/third_party/rust/minimal_lexical/v0_2/BUILD.gn +++ b/third_party/rust/minimal_lexical/v0_2/BUILD.gn
@@ -15,7 +15,7 @@ crate_root = "crate/src/lib.rs" # Unit tests skipped. Generate with --with-tests to include them. - skip_unit_tests = true + build_native_rust_unit_tests = false sources = [ "crate/src/lib.rs" ] edition = "2018" features = [ "std" ]
diff --git a/third_party/rust/moveit/v0_4/BUILD.gn b/third_party/rust/moveit/v0_4/BUILD.gn index c4cd005..494b49b 100644 --- a/third_party/rust/moveit/v0_4/BUILD.gn +++ b/third_party/rust/moveit/v0_4/BUILD.gn
@@ -15,7 +15,7 @@ crate_root = "crate/src/lib.rs" # Unit tests skipped. Generate with --with-tests to include them. - skip_unit_tests = true + build_native_rust_unit_tests = false sources = [ "crate/src/lib.rs" ] edition = "2018" deps = [ "//third_party/rust/cxx/v1:lib" ]
diff --git a/third_party/rust/nom/v7/BUILD.gn b/third_party/rust/nom/v7/BUILD.gn index 94bdff16..7591fa1 100644 --- a/third_party/rust/nom/v7/BUILD.gn +++ b/third_party/rust/nom/v7/BUILD.gn
@@ -15,7 +15,7 @@ crate_root = "crate/src/lib.rs" # Unit tests skipped. Generate with --with-tests to include them. - skip_unit_tests = true + build_native_rust_unit_tests = false sources = [ "crate/src/lib.rs" ] edition = "2018" deps = [
diff --git a/third_party/rust/once_cell/v1/BUILD.gn b/third_party/rust/once_cell/v1/BUILD.gn index 3956608..31bdee2 100644 --- a/third_party/rust/once_cell/v1/BUILD.gn +++ b/third_party/rust/once_cell/v1/BUILD.gn
@@ -15,7 +15,7 @@ crate_root = "crate/src/lib.rs" # Unit tests skipped. Generate with --with-tests to include them. - skip_unit_tests = true + build_native_rust_unit_tests = false sources = [ "crate/src/lib.rs" ] edition = "2018" features = [
diff --git a/third_party/rust/peeking_take_while/v0_1/BUILD.gn b/third_party/rust/peeking_take_while/v0_1/BUILD.gn index 8ebdcdf..010b338 100644 --- a/third_party/rust/peeking_take_while/v0_1/BUILD.gn +++ b/third_party/rust/peeking_take_while/v0_1/BUILD.gn
@@ -15,7 +15,7 @@ crate_root = "crate/src/lib.rs" # Unit tests skipped. Generate with --with-tests to include them. - skip_unit_tests = true + build_native_rust_unit_tests = false sources = [ "crate/src/lib.rs" ] edition = "2015" }
diff --git a/third_party/rust/proc_macro2/v1/BUILD.gn b/third_party/rust/proc_macro2/v1/BUILD.gn index a6bb5f2..dc198c79 100644 --- a/third_party/rust/proc_macro2/v1/BUILD.gn +++ b/third_party/rust/proc_macro2/v1/BUILD.gn
@@ -15,7 +15,7 @@ crate_root = "crate/src/lib.rs" # Unit tests skipped. Generate with --with-tests to include them. - skip_unit_tests = true + build_native_rust_unit_tests = false sources = [ "crate/src/lib.rs" ] edition = "2018" deps = [ "//third_party/rust/unicode_xid/v0_2:lib" ]
diff --git a/third_party/rust/proc_macro_error/v1/BUILD.gn b/third_party/rust/proc_macro_error/v1/BUILD.gn index f348d38..31055fc9 100644 --- a/third_party/rust/proc_macro_error/v1/BUILD.gn +++ b/third_party/rust/proc_macro_error/v1/BUILD.gn
@@ -15,7 +15,7 @@ crate_root = "crate/src/lib.rs" # Unit tests skipped. Generate with --with-tests to include them. - skip_unit_tests = true + build_native_rust_unit_tests = false sources = [ "crate/src/lib.rs" ] edition = "2018" deps = [
diff --git a/third_party/rust/proc_macro_error_attr/v1/BUILD.gn b/third_party/rust/proc_macro_error_attr/v1/BUILD.gn index 15206471..6bd8729 100644 --- a/third_party/rust/proc_macro_error_attr/v1/BUILD.gn +++ b/third_party/rust/proc_macro_error_attr/v1/BUILD.gn
@@ -15,7 +15,7 @@ crate_root = "crate/src/lib.rs" # Unit tests skipped. Generate with --with-tests to include them. - skip_unit_tests = true + build_native_rust_unit_tests = false sources = [ "crate/src/lib.rs" ] edition = "2018" deps = [
diff --git a/third_party/rust/quote/v1/BUILD.gn b/third_party/rust/quote/v1/BUILD.gn index 25cffdf..b8c283d0 100644 --- a/third_party/rust/quote/v1/BUILD.gn +++ b/third_party/rust/quote/v1/BUILD.gn
@@ -15,7 +15,7 @@ crate_root = "crate/src/lib.rs" # Unit tests skipped. Generate with --with-tests to include them. - skip_unit_tests = true + build_native_rust_unit_tests = false sources = [ "crate/src/lib.rs" ] edition = "2018" deps = [ "//third_party/rust/proc_macro2/v1:lib" ]
diff --git a/third_party/rust/regex/v1/BUILD.gn b/third_party/rust/regex/v1/BUILD.gn index d255275..f106379c 100644 --- a/third_party/rust/regex/v1/BUILD.gn +++ b/third_party/rust/regex/v1/BUILD.gn
@@ -15,7 +15,7 @@ crate_root = "crate/src/lib.rs" # Unit tests skipped. Generate with --with-tests to include them. - skip_unit_tests = true + build_native_rust_unit_tests = false sources = [ "crate/src/lib.rs" ] edition = "2018" deps = [
diff --git a/third_party/rust/regex_syntax/v0_6/BUILD.gn b/third_party/rust/regex_syntax/v0_6/BUILD.gn index a3f71e65..0ce56fb 100644 --- a/third_party/rust/regex_syntax/v0_6/BUILD.gn +++ b/third_party/rust/regex_syntax/v0_6/BUILD.gn
@@ -15,7 +15,7 @@ crate_root = "crate/src/lib.rs" # Unit tests skipped. Generate with --with-tests to include them. - skip_unit_tests = true + build_native_rust_unit_tests = false sources = [ "crate/src/lib.rs" ] edition = "2018" features = [
diff --git a/third_party/rust/remove_dir_all/v0_5/BUILD.gn b/third_party/rust/remove_dir_all/v0_5/BUILD.gn index f5e7b8f..c921690 100644 --- a/third_party/rust/remove_dir_all/v0_5/BUILD.gn +++ b/third_party/rust/remove_dir_all/v0_5/BUILD.gn
@@ -15,7 +15,7 @@ crate_root = "crate/src/lib.rs" # Unit tests skipped. Generate with --with-tests to include them. - skip_unit_tests = true + build_native_rust_unit_tests = false sources = [ "crate/src/lib.rs" ] edition = "2015" deps = []
diff --git a/third_party/rust/rstest/v0_12/BUILD.gn b/third_party/rust/rstest/v0_12/BUILD.gn index 5b4ee97..81f438c 100644 --- a/third_party/rust/rstest/v0_12/BUILD.gn +++ b/third_party/rust/rstest/v0_12/BUILD.gn
@@ -10,7 +10,7 @@ crate_type = "proc-macro" testonly = "true" crate_root = "crate/src/lib.rs" - skip_unit_tests = true + build_native_rust_unit_tests = false sources = [ "crate/src/lib.rs" ] edition = "2018" deps = [
diff --git a/third_party/rust/rustc_hash/v1/BUILD.gn b/third_party/rust/rustc_hash/v1/BUILD.gn index 9ec8ce1..6b90ba6c7 100644 --- a/third_party/rust/rustc_hash/v1/BUILD.gn +++ b/third_party/rust/rustc_hash/v1/BUILD.gn
@@ -15,7 +15,7 @@ crate_root = "crate/src/lib.rs" # Unit tests skipped. Generate with --with-tests to include them. - skip_unit_tests = true + build_native_rust_unit_tests = false sources = [ "crate/src/lib.rs" ] edition = "2015" features = [ "std" ]
diff --git a/third_party/rust/rustc_version/v0_4/BUILD.gn b/third_party/rust/rustc_version/v0_4/BUILD.gn index 2b6cb374..3db4932 100644 --- a/third_party/rust/rustc_version/v0_4/BUILD.gn +++ b/third_party/rust/rustc_version/v0_4/BUILD.gn
@@ -13,7 +13,7 @@ # third_party.toml to use it from first-party code. visibility = [ "//third_party/rust/*" ] crate_root = "crate/src/lib.rs" - skip_unit_tests = true + build_native_rust_unit_tests = false sources = [ "crate/src/lib.rs" ] edition = "2018" deps = [ "//third_party/rust/semver/v1:lib" ]
diff --git a/third_party/rust/rustversion/v1/BUILD.gn b/third_party/rust/rustversion/v1/BUILD.gn index 40ef43f..d779e30 100644 --- a/third_party/rust/rustversion/v1/BUILD.gn +++ b/third_party/rust/rustversion/v1/BUILD.gn
@@ -15,7 +15,7 @@ crate_root = "crate/src/lib.rs" # Unit tests skipped. Generate with --with-tests to include them. - skip_unit_tests = true + build_native_rust_unit_tests = false sources = [ "crate/src/lib.rs" ] edition = "2018" build_root = "crate/build/build.rs"
diff --git a/third_party/rust/ryu/v1/BUILD.gn b/third_party/rust/ryu/v1/BUILD.gn index 2a1fa400..8ca0c57 100644 --- a/third_party/rust/ryu/v1/BUILD.gn +++ b/third_party/rust/ryu/v1/BUILD.gn
@@ -15,7 +15,7 @@ crate_root = "crate/src/lib.rs" # Unit tests skipped. Generate with --with-tests to include them. - skip_unit_tests = true + build_native_rust_unit_tests = false sources = [ "crate/src/lib.rs" ] edition = "2018" build_root = "crate/build.rs"
diff --git a/third_party/rust/semver/v1/BUILD.gn b/third_party/rust/semver/v1/BUILD.gn index 3d5f002..6b915db 100644 --- a/third_party/rust/semver/v1/BUILD.gn +++ b/third_party/rust/semver/v1/BUILD.gn
@@ -15,7 +15,7 @@ crate_root = "crate/src/lib.rs" # Unit tests skipped. Generate with --with-tests to include them. - skip_unit_tests = true + build_native_rust_unit_tests = false sources = [ "crate/src/lib.rs" ] edition = "2018" features = [ "std" ]
diff --git a/third_party/rust/serde/v1/BUILD.gn b/third_party/rust/serde/v1/BUILD.gn index 817cfcfa..ead8845 100644 --- a/third_party/rust/serde/v1/BUILD.gn +++ b/third_party/rust/serde/v1/BUILD.gn
@@ -11,7 +11,7 @@ crate_root = "crate/src/lib.rs" # Unit tests skipped. Generate with --with-tests to include them. - skip_unit_tests = true + build_native_rust_unit_tests = false sources = [ "crate/src/lib.rs" ] edition = "2015" deps = [ "//third_party/rust/serde_derive/v1:lib" ]
diff --git a/third_party/rust/serde_derive/v1/BUILD.gn b/third_party/rust/serde_derive/v1/BUILD.gn index b04bf3b..909238c 100644 --- a/third_party/rust/serde_derive/v1/BUILD.gn +++ b/third_party/rust/serde_derive/v1/BUILD.gn
@@ -15,7 +15,7 @@ crate_root = "crate/src/lib.rs" # Unit tests skipped. Generate with --with-tests to include them. - skip_unit_tests = true + build_native_rust_unit_tests = false sources = [ "crate/src/lib.rs" ] edition = "2015" deps = [
diff --git a/third_party/rust/serde_json/v1/BUILD.gn b/third_party/rust/serde_json/v1/BUILD.gn index 0998db1..fa74368 100644 --- a/third_party/rust/serde_json/v1/BUILD.gn +++ b/third_party/rust/serde_json/v1/BUILD.gn
@@ -15,7 +15,7 @@ crate_root = "crate/src/lib.rs" # Unit tests skipped. Generate with --with-tests to include them. - skip_unit_tests = true + build_native_rust_unit_tests = false sources = [ "crate/src/lib.rs" ] edition = "2018" deps = [
diff --git a/third_party/rust/serde_jsonrc/v0_1/BUILD.gn b/third_party/rust/serde_jsonrc/v0_1/BUILD.gn index c241d4e..9e19d7df 100644 --- a/third_party/rust/serde_jsonrc/v0_1/BUILD.gn +++ b/third_party/rust/serde_jsonrc/v0_1/BUILD.gn
@@ -11,7 +11,7 @@ crate_root = "crate/src/lib.rs" # Unit tests skipped. Generate with --with-tests to include them. - skip_unit_tests = true + build_native_rust_unit_tests = false sources = [ "crate/src/lib.rs" ] edition = "2018" deps = [
diff --git a/third_party/rust/shlex/v1/BUILD.gn b/third_party/rust/shlex/v1/BUILD.gn index 84ac685..534bb912 100644 --- a/third_party/rust/shlex/v1/BUILD.gn +++ b/third_party/rust/shlex/v1/BUILD.gn
@@ -15,7 +15,7 @@ crate_root = "crate/src/lib.rs" # Unit tests skipped. Generate with --with-tests to include them. - skip_unit_tests = true + build_native_rust_unit_tests = false sources = [ "crate/src/lib.rs" ] edition = "2015" features = [ "std" ]
diff --git a/third_party/rust/small_ctor/v0_1/BUILD.gn b/third_party/rust/small_ctor/v0_1/BUILD.gn index 48de6b79..95ae7bd 100644 --- a/third_party/rust/small_ctor/v0_1/BUILD.gn +++ b/third_party/rust/small_ctor/v0_1/BUILD.gn
@@ -10,7 +10,7 @@ crate_type = "proc-macro" testonly = "true" crate_root = "crate/src/lib.rs" - skip_unit_tests = true + build_native_rust_unit_tests = false sources = [ "crate/src/lib.rs" ] edition = "2018" }
diff --git a/third_party/rust/strsim/v0_8/BUILD.gn b/third_party/rust/strsim/v0_8/BUILD.gn index 6993d4a..3baa7c1 100644 --- a/third_party/rust/strsim/v0_8/BUILD.gn +++ b/third_party/rust/strsim/v0_8/BUILD.gn
@@ -15,7 +15,7 @@ crate_root = "crate/src/lib.rs" # Unit tests skipped. Generate with --with-tests to include them. - skip_unit_tests = true + build_native_rust_unit_tests = false sources = [ "crate/src/lib.rs" ] edition = "2015" }
diff --git a/third_party/rust/strum_macros/v0_23/BUILD.gn b/third_party/rust/strum_macros/v0_23/BUILD.gn index 5cbcc9fc..bdbd910 100644 --- a/third_party/rust/strum_macros/v0_23/BUILD.gn +++ b/third_party/rust/strum_macros/v0_23/BUILD.gn
@@ -15,7 +15,7 @@ crate_root = "crate/src/lib.rs" # Unit tests skipped. Generate with --with-tests to include them. - skip_unit_tests = true + build_native_rust_unit_tests = false sources = [ "crate/src/lib.rs" ] edition = "2018" deps = [
diff --git a/third_party/rust/syn/v1/BUILD.gn b/third_party/rust/syn/v1/BUILD.gn index 528748d..1e387f7 100644 --- a/third_party/rust/syn/v1/BUILD.gn +++ b/third_party/rust/syn/v1/BUILD.gn
@@ -15,7 +15,7 @@ crate_root = "crate/src/lib.rs" # Unit tests skipped. Generate with --with-tests to include them. - skip_unit_tests = true + build_native_rust_unit_tests = false sources = [ "crate/src/lib.rs" ] edition = "2018" deps = [
diff --git a/third_party/rust/tempfile/v3/BUILD.gn b/third_party/rust/tempfile/v3/BUILD.gn index 5c10155d..eca5a2c 100644 --- a/third_party/rust/tempfile/v3/BUILD.gn +++ b/third_party/rust/tempfile/v3/BUILD.gn
@@ -15,7 +15,7 @@ crate_root = "crate/src/lib.rs" # Unit tests skipped. Generate with --with-tests to include them. - skip_unit_tests = true + build_native_rust_unit_tests = false sources = [ "crate/src/lib.rs" ] edition = "2018" deps = [
diff --git a/third_party/rust/termcolor/v1/BUILD.gn b/third_party/rust/termcolor/v1/BUILD.gn index 21203db..4b247491 100644 --- a/third_party/rust/termcolor/v1/BUILD.gn +++ b/third_party/rust/termcolor/v1/BUILD.gn
@@ -15,7 +15,7 @@ crate_root = "crate/src/lib.rs" # Unit tests skipped. Generate with --with-tests to include them. - skip_unit_tests = true + build_native_rust_unit_tests = false sources = [ "crate/src/lib.rs" ] edition = "2018" deps = []
diff --git a/third_party/rust/textwrap/v0_11/BUILD.gn b/third_party/rust/textwrap/v0_11/BUILD.gn index f8bef99..fa0a768 100644 --- a/third_party/rust/textwrap/v0_11/BUILD.gn +++ b/third_party/rust/textwrap/v0_11/BUILD.gn
@@ -15,7 +15,7 @@ crate_root = "crate/src/lib.rs" # Unit tests skipped. Generate with --with-tests to include them. - skip_unit_tests = true + build_native_rust_unit_tests = false sources = [ "crate/src/lib.rs" ] edition = "2015" deps = [ "//third_party/rust/unicode_width/v0_1:lib" ]
diff --git a/third_party/rust/unicode_segmentation/v1/BUILD.gn b/third_party/rust/unicode_segmentation/v1/BUILD.gn index 05b108a..b96055e 100644 --- a/third_party/rust/unicode_segmentation/v1/BUILD.gn +++ b/third_party/rust/unicode_segmentation/v1/BUILD.gn
@@ -15,7 +15,7 @@ crate_root = "crate/src/lib.rs" # Unit tests skipped. Generate with --with-tests to include them. - skip_unit_tests = true + build_native_rust_unit_tests = false sources = [ "crate/src/lib.rs" ] edition = "2018" }
diff --git a/third_party/rust/unicode_width/v0_1/BUILD.gn b/third_party/rust/unicode_width/v0_1/BUILD.gn index 6ef17d6..e864565 100644 --- a/third_party/rust/unicode_width/v0_1/BUILD.gn +++ b/third_party/rust/unicode_width/v0_1/BUILD.gn
@@ -15,7 +15,7 @@ crate_root = "crate/src/lib.rs" # Unit tests skipped. Generate with --with-tests to include them. - skip_unit_tests = true + build_native_rust_unit_tests = false sources = [ "crate/src/lib.rs" ] edition = "2015" }
diff --git a/third_party/rust/unicode_xid/v0_2/BUILD.gn b/third_party/rust/unicode_xid/v0_2/BUILD.gn index 0972c8d..4a5d93b2 100644 --- a/third_party/rust/unicode_xid/v0_2/BUILD.gn +++ b/third_party/rust/unicode_xid/v0_2/BUILD.gn
@@ -15,7 +15,7 @@ crate_root = "crate/src/lib.rs" # Unit tests skipped. Generate with --with-tests to include them. - skip_unit_tests = true + build_native_rust_unit_tests = false sources = [ "crate/src/lib.rs" ] edition = "2015" }
diff --git a/third_party/rust/unindent/v0_1/BUILD.gn b/third_party/rust/unindent/v0_1/BUILD.gn index 9c3afce..0fa1b33 100644 --- a/third_party/rust/unindent/v0_1/BUILD.gn +++ b/third_party/rust/unindent/v0_1/BUILD.gn
@@ -15,7 +15,7 @@ crate_root = "crate/src/lib.rs" # Unit tests skipped. Generate with --with-tests to include them. - skip_unit_tests = true + build_native_rust_unit_tests = false sources = [ "crate/src/lib.rs" ] edition = "2018" }
diff --git a/third_party/rust/unzip_n/v0_1/BUILD.gn b/third_party/rust/unzip_n/v0_1/BUILD.gn index a7e75b9..9009c7e 100644 --- a/third_party/rust/unzip_n/v0_1/BUILD.gn +++ b/third_party/rust/unzip_n/v0_1/BUILD.gn
@@ -15,7 +15,7 @@ crate_root = "crate/src/lib.rs" # Unit tests skipped. Generate with --with-tests to include them. - skip_unit_tests = true + build_native_rust_unit_tests = false sources = [ "crate/src/lib.rs" ] edition = "2018" deps = [
diff --git a/third_party/rust/vec_map/v0_8/BUILD.gn b/third_party/rust/vec_map/v0_8/BUILD.gn index 33e1c481..bb57315 100644 --- a/third_party/rust/vec_map/v0_8/BUILD.gn +++ b/third_party/rust/vec_map/v0_8/BUILD.gn
@@ -15,7 +15,7 @@ crate_root = "crate/src/lib.rs" # Unit tests skipped. Generate with --with-tests to include them. - skip_unit_tests = true + build_native_rust_unit_tests = false sources = [ "crate/src/lib.rs" ] edition = "2015" }
diff --git a/third_party/rust/version_check/v0_9/BUILD.gn b/third_party/rust/version_check/v0_9/BUILD.gn index 679d664..ec58538 100644 --- a/third_party/rust/version_check/v0_9/BUILD.gn +++ b/third_party/rust/version_check/v0_9/BUILD.gn
@@ -15,7 +15,7 @@ crate_root = "crate/src/lib.rs" # Unit tests skipped. Generate with --with-tests to include them. - skip_unit_tests = true + build_native_rust_unit_tests = false sources = [ "crate/src/lib.rs" ] edition = "2015" }
diff --git a/third_party/rust/which/v4/BUILD.gn b/third_party/rust/which/v4/BUILD.gn index 8fe5b521f..ed106454 100644 --- a/third_party/rust/which/v4/BUILD.gn +++ b/third_party/rust/which/v4/BUILD.gn
@@ -15,7 +15,7 @@ crate_root = "crate/src/lib.rs" # Unit tests skipped. Generate with --with-tests to include them. - skip_unit_tests = true + build_native_rust_unit_tests = false sources = [ "crate/src/lib.rs" ] edition = "2018" deps = [
diff --git a/third_party/rust/winapi/v0_3/BUILD.gn b/third_party/rust/winapi/v0_3/BUILD.gn index 3f2bb97..f7359c9b 100644 --- a/third_party/rust/winapi/v0_3/BUILD.gn +++ b/third_party/rust/winapi/v0_3/BUILD.gn
@@ -16,7 +16,7 @@ crate_root = "crate/src/lib.rs" # Unit tests skipped. Generate with --with-tests to include them. - skip_unit_tests = true + build_native_rust_unit_tests = false sources = [ "crate/src/lib.rs" ] edition = "2015" features = [
diff --git a/third_party/rust/winapi_util/v0_1/BUILD.gn b/third_party/rust/winapi_util/v0_1/BUILD.gn index b8b9515..af558202 100644 --- a/third_party/rust/winapi_util/v0_1/BUILD.gn +++ b/third_party/rust/winapi_util/v0_1/BUILD.gn
@@ -16,7 +16,7 @@ crate_root = "crate/src/lib.rs" # Unit tests skipped. Generate with --with-tests to include them. - skip_unit_tests = true + build_native_rust_unit_tests = false sources = [ "crate/src/lib.rs" ] edition = "2018" deps = [ "//third_party/rust/winapi/v0_3:lib" ]
diff --git a/tools/binary_size/libsupersize/dex_disassembly.py b/tools/binary_size/libsupersize/dex_disassembly.py new file mode 100644 index 0000000..9f5b30b --- /dev/null +++ b/tools/binary_size/libsupersize/dex_disassembly.py
@@ -0,0 +1,278 @@ +# Copyright 2022 The Chromium Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. +"""Class to get the dex disassembly for symbols.""" + +import dataclasses +import difflib +import json +import logging +import os +import re +import subprocess +import sys +import zipfile + +import archive +import models +import path_util +import zip_util + +_PROGUARD_CLASS_MAPPING_RE = re.compile(r'(?P<original_name>[^ ]+)' + r' -> ' + r'(?P<obfuscated_name>[^:]+):') +_SYMBOL_FULL_NAME_RE = re.compile(r'(.*?)#(.*?)\((.*?)\):? ?(.*)') +_R8_OUTPUT_RE = re.compile(r"'([^']+)'") +_R8_PARAM_RE = re.compile(r'\(.*?\)') + + +@dataclasses.dataclass +class _Method: + name: str + class_name: str + param_types: list = None + return_type: str = None + bytecode: list = None + + +class _Class: + def __init__(self, name): + self.name = name + self.methods = [] + + def _FindMethodByteCode(self, class_name, method_name, param_types, + return_type): + for method in self.methods: + if (method.name == method_name and method.class_name == class_name + and method.return_type == return_type + and method.param_types == param_types): + return method.bytecode + return None + + +def _DisassembleApk(mapping, apk_path): + r8_path = path_util.GetR8Path() + cmd = [ + 'java', '-cp', r8_path, 'com.android.tools.r8.Disassemble', '--pg-map', + mapping, apk_path + ] + return subprocess.check_output(cmd, encoding='utf8') + + +def _ParseDisassembly(disassembly): + disassembly = disassembly.splitlines(keepends=True) + classes = {} + current_class = None + current_method = None + reading_positions = False + reading_methods = False + for idx, line in enumerate(disassembly): + line = line.strip() + if line.startswith('# Class:'): + # New class started, no longer reading methods. + reading_methods = False + # Example of line: '# Class: \'className\'' + match = _R8_OUTPUT_RE.search(line) + if match: + current_class = _Class(match.group(1)) + classes[current_class.name] = current_class + elif line.startswith('# Method:') and current_class: + # Example of line: '# Method: \'methodName\':' + match = _R8_OUTPUT_RE.search(line) + if match: + reading_methods = True + current_method = _Method(match.group(1), current_class.name) + current_class.methods.append(current_method) + elif reading_methods and line.startswith('registers:'): + # Example of line: 'registers: 1, inputs: 1, outputs: 1' + assert idx > 0 + header = disassembly[idx - 1] + # Example of header: 'returnType className.methodName(param1, param2)' + return_type = header.split()[0] + current_method.return_type = return_type + match = _R8_PARAM_RE.search(header) + if match: + params = (match.group(0))[1:-1] + current_method.param_types = params.split(', ') if params else [] + bytecode_start = idx + reading_positions = True + elif reading_positions and line == '': + current_method.bytecode = disassembly[bytecode_start:idx] + reading_positions = False + return classes + + +def _CreateClassDeobfuscationMap(obfuscated_mapping): + mapping = {} + for line in obfuscated_mapping: + # We are on a class name so add it to the class mapping. + if not line.startswith(' '): + match = _PROGUARD_CLASS_MAPPING_RE.search(line) + if match: + mapping[match.group('obfuscated_name')] = match.group('original_name') + return mapping + + +def _ChangeObfusactedNames(disassembly, obfuscated_map): + for _, value in disassembly.items(): + for method in value.methods: + method.return_type = obfuscated_map.get(method.return_type, + method.return_type) + if method.param_types: + for idx, param in enumerate(method.param_types): + method.param_types[idx] = obfuscated_map.get(param, param) + return disassembly + + +def _ComputeDisassemblyForSymbol(deobfuscated_disassembly, symbol_full_name): + param_types = None + return_type = None + bytecode = None + # Example of symbol_full_name: + # className#methodName(param1,param2): returnType + m = _SYMBOL_FULL_NAME_RE.match(symbol_full_name) + if m: + class_name, method_name, param_types, return_type = m.groups() + param_types = param_types.split(',') if param_types else [] + disassembly = deobfuscated_disassembly.get(class_name) + if disassembly is not None: + bytecode = disassembly._FindMethodByteCode(class_name, method_name, + param_types, return_type) + return bytecode + + +def _CaptureDisassemblyForSymbol(symbol, apk_to_disassembly, apk_dir, + deobfuscation_map): + logging.debug('Attempting to capture disassembly for symbol %s', + symbol.full_name) + container = symbol.container + proguard_mapping_file_name = container.metadata.get( + 'proguard_mapping_file_name') + if proguard_mapping_file_name is None: + logging.debug('Mapping file does not exist in container metadata.') + return None + proguard_mapping_file_path = os.path.join(apk_dir, proguard_mapping_file_name) + apk_file_name = container.metadata.get('apk_file_name') + apk_file_path = os.path.join(apk_dir, apk_file_name) + split_name = container.metadata.get('apk_split_name') + cache_key = (apk_file_path, split_name) + disassembly = apk_to_disassembly.get(cache_key) + if disassembly is None: + if split_name: + logging.debug('Running R8 on APK: %s', split_name) + with zip_util.UnzipToTemp(apk_file_path, + f'splits/{split_name}.apk') as split_path: + r8_output = _DisassembleApk(proguard_mapping_file_path, split_path) + else: + logging.debug('Running R8 on APK: %s', apk_file_name) + r8_output = _DisassembleApk(proguard_mapping_file_path, apk_file_path) + obfuscated_to_deobfuscated_class_names = deobfuscation_map.get( + proguard_mapping_file_path) + if obfuscated_to_deobfuscated_class_names is None: + logging.debug('Parsing mapping file %s', proguard_mapping_file_path) + with open(proguard_mapping_file_path, 'r') as fh: + obfuscated_to_deobfuscated_class_names = _CreateClassDeobfuscationMap( + fh) + deobfuscation_map[ + proguard_mapping_file_path] = obfuscated_to_deobfuscated_class_names + logging.debug('Changing obfuscated names...') + disassembly = _ChangeObfusactedNames( + _ParseDisassembly(r8_output), obfuscated_to_deobfuscated_class_names) + apk_to_disassembly[cache_key] = disassembly + return _ComputeDisassemblyForSymbol(disassembly, symbol.full_name) + + +def _CreateUnifiedDiff(name, before, after): + unified_diff = difflib.unified_diff(before, + after, + fromfile=name, + tofile=name, + n=10) + # Strip new line characters as difflib.unified_diff adds extra newline + # characters to the first few lines which we do not want. + #unified_diff = [x.strip() for x in unified_diff] + return ''.join(unified_diff) + + +def _AddUnifiedDiff(top_changed_symbols, before_directory, after_directory): + # Counter used to skip over symbols where we couldn't find the disassembly. + counter = 10 + before = None + after = None + before_apk_to_disassembly = {} + after_apk_to_disassembly = {} + deobfuscation_map = {} + for symbol in top_changed_symbols: + logging.debug('Symbols to go: %d', counter) + after = _CaptureDisassemblyForSymbol(symbol.after_symbol, + after_apk_to_disassembly, + after_directory, deobfuscation_map) + if after is None: + continue + if symbol.before_symbol: + before = _CaptureDisassemblyForSymbol(symbol.before_symbol, + before_apk_to_disassembly, + before_directory, deobfuscation_map) + else: + before = None + logging.debug('Adding disassembly for symbol: %s ', symbol.full_name) + symbol.disassembly = _CreateUnifiedDiff(symbol.full_name, before or [], + after) + counter -= 1 + if counter == 0: + break + + +def _GetTopChangedSymbols(delta_size_info): + # Currently we are restricting symbols to dex methods. + sorted_symbols = [ + symbol for symbol in delta_size_info.raw_symbols + if symbol.section_name.endswith('dex.method') and symbol.after_symbol + ] + sorted_symbols.sort(key=lambda x: -abs(x.size)) + return sorted_symbols + + +def AddDisassembly(delta_size_info, before_directory, after_directory): + """Adds disassembly diffs to top changed symbols. + + Adds the unified diff on the "before" and "after" disassembly to the + top 10 changed symbols. + + Args: + delta_size_info: DeltaSizeInfo Object we are adding disassembly to. + before_directory: Directory of the "before" APK. + after_directory: Directory of the "after" APK. + """ + logging.debug('Computing top changed symbols') + top_changed_symbols = _GetTopChangedSymbols(delta_size_info) + logging.debug('Adding disassembly to top 10 changed symbols') + _AddUnifiedDiff(top_changed_symbols, before_directory, after_directory) + + +def main(): + # Gets disassembly for symbol. + size_file_path = sys.argv[1] + symbol_full_name = sys.argv[2] + mapping_file_name = sys.argv[3] + apk_dir = sys.argv[4] + size_info = archive.LoadAndPostProcessSizeInfo(size_file_path) + matched_symbols = [ + sym for sym in size_info.raw_symbols if sym.full_name == symbol_full_name + ] + if not matched_symbols: + print(f'Symbol {symbol_full_name} not found') + return + for i, sym in enumerate(matched_symbols): + if i > 0: + print('-' * 80) + sym.container.metadata[ + models.METADATA_PROGUARD_MAPPING_FILENAME] = mapping_file_name + bytecode = _CaptureDisassemblyForSymbol(sym, {}, apk_dir, {}) + for line in bytecode: + print(line, end='') + return + + +if __name__ == '__main__': + main()
diff --git a/tools/binary_size/libsupersize/main.py b/tools/binary_size/libsupersize/main.py index 508ee6dc..a361539 100755 --- a/tools/binary_size/libsupersize/main.py +++ b/tools/binary_size/libsupersize/main.py
@@ -2,7 +2,6 @@ # 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 @@ -16,6 +15,7 @@ import archive import console import diff +import dex_disassembly import file_format import models import os @@ -62,7 +62,6 @@ class _SaveDiffAction: - @staticmethod def AddArguments(parser): parser.add_argument('before', help='Before-patch .size file.') @@ -97,7 +96,6 @@ args.before_directory = os.path.dirname(args.before) if not args.after_directory: args.after_directory = os.path.dirname(args.after) - before_size_info = archive.LoadAndPostProcessSizeInfo(args.before) after_size_info = archive.LoadAndPostProcessSizeInfo(args.after) # If a URL or title exists, we only want to add it to the build config of @@ -107,6 +105,9 @@ if args.url: after_size_info.build_config[models.BUILD_CONFIG_URL] = args.url delta_size_info = diff.Diff(before_size_info, after_size_info) + if args.save_disassembly: + dex_disassembly.AddDisassembly(delta_size_info, args.before_directory, + args.after_directory) file_format.SaveDeltaSizeInfo(delta_size_info, args.output_file)
diff --git a/tools/binary_size/libsupersize/models.py b/tools/binary_size/libsupersize/models.py index 25155a3c..86a92bd 100644 --- a/tools/binary_size/libsupersize/models.py +++ b/tools/binary_size/libsupersize/models.py
@@ -627,10 +627,7 @@ to one symbol in the |before|, and then be an alias to another in |after|. """ - __slots__ = ( - 'before_symbol', - 'after_symbol', - ) + __slots__ = ('before_symbol', 'after_symbol', 'disassembly') def __init__(self, before_symbol, after_symbol): self.before_symbol = before_symbol
diff --git a/tools/binary_size/libsupersize/path_util.py b/tools/binary_size/libsupersize/path_util.py index f003f4c..229945c 100644 --- a/tools/binary_size/libsupersize/path_util.py +++ b/tools/binary_size/libsupersize/path_util.py
@@ -200,3 +200,7 @@ def GetDefaultJsonConfigPath(): return FromToolsSrcRoot('tools', 'binary_size', 'supersize.json') + + +def GetR8Path(): + return FromToolsSrcRoot('third_party', 'r8', 'lib', 'r8.jar')
diff --git a/tools/binary_size/libsupersize/testdata/Console.golden b/tools/binary_size/libsupersize/testdata/Console.golden index 937b01d..624f883 100644 --- a/tools/binary_size/libsupersize/testdata/Console.golden +++ b/tools/binary_size/libsupersize/testdata/Console.golden
@@ -7,7 +7,7 @@ SymbolGroup (extends Symbol): CountUniqueSymbols, Filter, GroupedBy, GroupedByAliases, GroupedByComponent, GroupedByContainer, GroupedByContainerAndSectionName, GroupedByFullName, GroupedByName, GroupedByPath, GroupedBySectionName, Inverted, IterUniqueSymbols, Sorted, SortedByAddress, SortedByCount, SortedByName, WhereAddressInRange, WhereComponentMatches, WhereFullNameMatches, WhereGeneratedByToolchain, WhereHasAnyAttribution, WhereHasComponent, WhereHasFlag, WhereHasPath, WhereInContainer, WhereInSection, WhereIsDex, WhereIsGroup, WhereIsNative, WhereIsOnDemand, WhereIsPak, WhereIsPlaceholder, WhereIsTemplate, WhereMatches, WhereNameMatches, WhereObjectPathMatches, WherePathMatches, WherePssBiggerThan, WhereSizeBiggerThan, WhereSourceIsGenerated, WhereSourcePathMatches, WhereTemplateNameMatches, index, is_default_sorted DeltaSizeInfo: ContainerForName, after, before, build_config, containers, native_symbols, pak_symbols, raw_symbols, section_sizes, symbols -DeltaSymbol (extends Symbol): after_symbol, before_symbol, diff_status +DeltaSymbol (extends Symbol): after_symbol, before_symbol, diff_status, disassembly DeltaSymbolGroup (extends SymbolGroup): CountsByDiffStatus, WhereDiffStatusIs, diff_status canned_queries: CategorizeByChromeComponent, CategorizeGenerated, LargeFiles, PakByPath, StaticInitializers, TemplatesByName
diff --git a/tools/binary_size/supersize.pydeps b/tools/binary_size/supersize.pydeps index 1b7d364..622bd56d 100644 --- a/tools/binary_size/supersize.pydeps +++ b/tools/binary_size/supersize.pydeps
@@ -51,6 +51,7 @@ libsupersize/data_quality.py libsupersize/demangle.py libsupersize/describe.py +libsupersize/dex_disassembly.py libsupersize/diff.py libsupersize/dir_metadata.py libsupersize/dwarfdump.py
diff --git a/tools/crates/lib/build_rule.py b/tools/crates/lib/build_rule.py index 2460c5c783..0093f64 100644 --- a/tools/crates/lib/build_rule.py +++ b/tools/crates/lib/build_rule.py
@@ -342,12 +342,18 @@ self._write(indent + 2, "testonly = \"true\"") self._write(indent + 2, "crate_root = \"{}\"".format(self.lib_root)) - if not usage == cargo.CrateUsage.FOR_NORMAL: - self._write(indent + 2, "skip_unit_tests = true") - elif not args.with_tests: - for c in consts.GN_TESTS_COMMENT.split("\n"): - self._write(indent + 2, c) - self._write(indent + 2, "skip_unit_tests = true") + if usage == cargo.CrateUsage.FOR_NORMAL: + if args.with_tests: + self._write(indent + 2, + "build_native_rust_unit_tests = true") + else: + for c in consts.GN_TESTS_COMMENT.split("\n"): + self._write(indent + 2, c) + self._write(indent + 2, + "build_native_rust_unit_tests = false") + else: + self._write(indent + 2, + "build_native_rust_unit_tests = false") self._write_common(indent + 2, self, self.lib_sources, usage) self._write(indent, "}")
diff --git a/tools/crates/lib/consts.py b/tools/crates/lib/consts.py index e26e74f..efba338a 100644 --- a/tools/crates/lib/consts.py +++ b/tools/crates/lib/consts.py
@@ -81,7 +81,7 @@ r"The Chromium Authors\. All rights reserved\." GN_HEADER_YEAR_REGEX = re.compile(_GN_HEADER_YEAR) -# Comment on the skip_unit_tests field in BUILD.gn file output. +# Comment on the build_native_rust_unit_tests field in BUILD.gn file output. GN_TESTS_COMMENT = \ """# Unit tests skipped. Generate with --with-tests to include them."""
diff --git a/tools/mb/mb.py b/tools/mb/mb.py index 8e5e3016..56ec82e 100755 --- a/tools/mb/mb.py +++ b/tools/mb/mb.py
@@ -807,22 +807,31 @@ config = self.builder_groups[builder_group][builder] if not config: continue + + def flatten(config): + flattened_config = FlattenConfig(self.configs, self.mixins, config) + if flattened_config['gn_args'] == 'error': + return None + args = {'gn_args': gn_helpers.FromGNArgs(flattened_config['gn_args'])} + if flattened_config.get('args_file'): + args['args_file'] = flattened_config['args_file'] + return args + if isinstance(config, dict): # This is a 'phased' builder. Each key in the config is a different # phase of the builder. args = {} for k, v in config.items(): - args[k] = gn_helpers.FromGNArgs( - FlattenConfig(self.configs, self.mixins, v)['gn_args']) + flattened = flatten(v) + if flattened is None: + continue + args[k] = flattened elif config.startswith('//'): args = config else: - flattened_config = FlattenConfig(self.configs, self.mixins, config) - if flattened_config['gn_args'] == 'error': + args = flatten(config) + if args is None: continue - args = {'gn_args': gn_helpers.FromGNArgs(flattened_config['gn_args'])} - if flattened_config.get('args_file'): - args['args_file'] = flattened_config['args_file'] obj[builder_group][builder] = args return obj
diff --git a/tools/mb/mb_config.pyl b/tools/mb/mb_config.pyl index 465c3c403..6d19da7 100644 --- a/tools/mb/mb_config.pyl +++ b/tools/mb/mb_config.pyl
@@ -288,7 +288,7 @@ 'reclient': 'gpu_tests_release_bot_minimal_symbols_reclient', }, 'Comparison Simple Chrome (reclient)': { - 'goma': 'chromeos_amd64-generic_use_fake_dbus_clients', + 'goma': 'chromeos_amd64-generic_use_fake_dbus_clients_goma', 'reclient': 'chromeos_amd64-generic_use_fake_dbus_clients_reclient', }, 'Libfuzzer Upload Chrome OS ASan': 'libfuzzer_chromeos_asan_release_bot', @@ -377,6 +377,7 @@ # TODO(crbug.com/1252626): remove this after the migration. 'mac-arm64-on-arm64-rel-reclient': 'mac_arm64_release_bot_reclient', 'mac-code-coverage': 'clang_code_coverage', + 'mac-fieldtrial-rel': 'mac_arm64_gpu_tests_release_bot_minimal_symbols_no_nacl', 'mac-hermetic-upgrade-rel': 'release_bot', 'mac-paeverywhere-x64-fyi-dbg': 'debug_bot_paeverywhere_x64', 'mac-paeverywhere-x64-fyi-rel': 'release_trybot_paeverywhere_x64', @@ -1138,6 +1139,7 @@ 'ios-simulator-multi-window': 'ios_simulator_debug_static_bot_xctest', 'ios-simulator-rts': 'ios_simulator_code_coverage_partial_instrumentation_xctest', 'mac-arm64-on-arm64-rel': 'mac_arm64_release_trybot', + 'mac-fieldtrial-fyi-rel': 'mac_arm64_gpu_tests_release_bot_minimal_symbols_no_nacl', 'mac-osxbeta-rel': 'gpu_tests_release_trybot', 'mac_chromium_10.11_rel_ng': 'gpu_tests_release_trybot', 'mac_chromium_10.12_rel_ng': 'gpu_tests_release_trybot', @@ -1941,6 +1943,10 @@ 'chromeos_amd64-generic-vm', 'use_fake_dbus_clients', 'dcheck_always_on', ], + 'chromeos_amd64-generic_use_fake_dbus_clients_goma':[ + 'chromeos_amd64-generic_goma', 'use_fake_dbus_clients', + ], + 'chromeos_amd64-generic_use_fake_dbus_clients_reclient': [ 'chromeos_amd64-generic_reclient', 'use_fake_dbus_clients', ], @@ -3474,6 +3480,10 @@ 'mixins': ['chromeos', 'chromeos_codecs'], }, + 'chromeos_amd64-generic_goma': { + 'mixins': ['chromeos_device', 'amd64-generic-vm',] + }, + 'chromeos_amd64-generic_reclient': { 'mixins': ['chromeos_device_reclient', 'amd64-generic-vm',] },
diff --git a/tools/mb/mb_config_expectations/chromium.fyi.json b/tools/mb/mb_config_expectations/chromium.fyi.json index c593e22..6bbee3ab 100644 --- a/tools/mb/mb_config_expectations/chromium.fyi.json +++ b/tools/mb/mb_config_expectations/chromium.fyi.json
@@ -32,84 +32,102 @@ }, "Comparison Android (reclient)": { "goma": { - "ffmpeg_branding": "Chrome", - "is_component_build": false, - "is_debug": true, - "proprietary_codecs": true, - "symbol_level": 1, - "system_webview_package_name": "com.google.android.webview", - "target_cpu": "arm64", - "target_os": "android", - "use_goma": true + "gn_args": { + "ffmpeg_branding": "Chrome", + "is_component_build": false, + "is_debug": true, + "proprietary_codecs": true, + "symbol_level": 1, + "system_webview_package_name": "com.google.android.webview", + "target_cpu": "arm64", + "target_os": "android", + "use_goma": true + } }, "reclient": { - "ffmpeg_branding": "Chrome", - "is_component_build": false, - "is_debug": true, - "proprietary_codecs": true, - "symbol_level": 1, - "system_webview_package_name": "com.google.android.webview", - "target_cpu": "arm64", - "target_os": "android", - "use_rbe": true, - "use_remoteexec": true + "gn_args": { + "ffmpeg_branding": "Chrome", + "is_component_build": false, + "is_debug": true, + "proprietary_codecs": true, + "symbol_level": 1, + "system_webview_package_name": "com.google.android.webview", + "target_cpu": "arm64", + "target_os": "android", + "use_rbe": true, + "use_remoteexec": true + } } }, "Comparison Linux (reclient)": { "goma": { - "dcheck_always_on": false, - "ffmpeg_branding": "Chrome", - "is_component_build": false, - "is_debug": false, - "proprietary_codecs": true, - "use_goma": true + "gn_args": { + "dcheck_always_on": false, + "ffmpeg_branding": "Chrome", + "is_component_build": false, + "is_debug": false, + "proprietary_codecs": true, + "use_goma": true + } }, "reclient": { - "dcheck_always_on": false, - "ffmpeg_branding": "Chrome", - "is_component_build": false, - "is_debug": false, - "proprietary_codecs": true, - "use_rbe": true, - "use_remoteexec": true + "gn_args": { + "dcheck_always_on": false, + "ffmpeg_branding": "Chrome", + "is_component_build": false, + "is_debug": false, + "proprietary_codecs": true, + "use_rbe": true, + "use_remoteexec": true + } } }, "Comparison Simple Chrome (reclient)": { "goma": { - "dcheck_always_on": false, - "is_chromeos_device": true, - "ozone_platform_headless": true, - "use_goma": true, - "use_real_dbus_clients": false + "args_file": "//build/args/chromeos/amd64-generic-vm.gni", + "gn_args": { + "dcheck_always_on": false, + "is_chromeos_device": true, + "ozone_platform_headless": true, + "use_goma": true, + "use_real_dbus_clients": false + } }, "reclient": { - "dcheck_always_on": false, - "is_chromeos_device": true, - "ozone_platform_headless": true, - "use_rbe": true, - "use_real_dbus_clients": false, - "use_remoteexec": true + "args_file": "//build/args/chromeos/amd64-generic-vm.gni", + "gn_args": { + "dcheck_always_on": false, + "is_chromeos_device": true, + "ozone_platform_headless": true, + "use_rbe": true, + "use_real_dbus_clients": false, + "use_remoteexec": true + } } }, "Comparison Windows (reclient)": { "goma": { - "dcheck_always_on": false, - "ffmpeg_branding": "Chrome", - "is_component_build": false, - "is_debug": false, - "proprietary_codecs": true, - "symbol_level": 1, - "use_goma": true + "gn_args": { + "dcheck_always_on": false, + "ffmpeg_branding": "Chrome", + "is_component_build": false, + "is_debug": false, + "proprietary_codecs": true, + "symbol_level": 1, + "use_goma": true + } }, "reclient": { - "dcheck_always_on": false, - "ffmpeg_branding": "Chrome", - "is_component_build": false, - "is_debug": false, - "proprietary_codecs": true, - "symbol_level": 1, - "use_rbe": true, - "use_remoteexec": true + "gn_args": { + "dcheck_always_on": false, + "ffmpeg_branding": "Chrome", + "is_component_build": false, + "is_debug": false, + "proprietary_codecs": true, + "symbol_level": 1, + "use_rbe": true, + "use_remoteexec": true + } } }, "Libfuzzer Upload Chrome OS ASan": { @@ -1184,6 +1202,19 @@ "use_goma": true } }, + "mac-fieldtrial-rel": { + "gn_args": { + "dcheck_always_on": false, + "enable_nacl": false, + "ffmpeg_branding": "Chrome", + "is_component_build": false, + "is_debug": false, + "proprietary_codecs": true, + "symbol_level": 1, + "target_cpu": "arm64", + "use_goma": true + } + }, "mac-hermetic-upgrade-rel": { "gn_args": { "dcheck_always_on": false,
diff --git a/tools/mb/mb_config_expectations/chromium.linux.json b/tools/mb/mb_config_expectations/chromium.linux.json index c55fe513..13cd774 100644 --- a/tools/mb/mb_config_expectations/chromium.linux.json +++ b/tools/mb/mb_config_expectations/chromium.linux.json
@@ -64,15 +64,19 @@ }, "Deterministic Linux (dbg)": { "goma": { - "is_component_build": true, - "is_debug": true, - "symbol_level": 1, - "use_goma": true + "gn_args": { + "is_component_build": true, + "is_debug": true, + "symbol_level": 1, + "use_goma": true + } }, "local": { - "is_component_build": true, - "is_debug": true, - "symbol_level": 1 + "gn_args": { + "is_component_build": true, + "is_debug": true, + "symbol_level": 1 + } } }, "Fuchsia ARM64": {
diff --git a/tools/mb/mb_config_expectations/tryserver.chromium.mac.json b/tools/mb/mb_config_expectations/tryserver.chromium.mac.json index a867ed3..02db7cb5 100644 --- a/tools/mb/mb_config_expectations/tryserver.chromium.mac.json +++ b/tools/mb/mb_config_expectations/tryserver.chromium.mac.json
@@ -483,6 +483,19 @@ "use_goma": true } }, + "mac-fieldtrial-fyi-rel": { + "gn_args": { + "dcheck_always_on": false, + "enable_nacl": false, + "ffmpeg_branding": "Chrome", + "is_component_build": false, + "is_debug": false, + "proprietary_codecs": true, + "symbol_level": 1, + "target_cpu": "arm64", + "use_goma": true + } + }, "mac-inverse-fieldtrials-fyi-rel": { "gn_args": { "blink_enable_generated_code_formatting": false,
diff --git a/tools/metrics/histograms/enums.xml b/tools/metrics/histograms/enums.xml index 7e7124a..1962864 100644 --- a/tools/metrics/histograms/enums.xml +++ b/tools/metrics/histograms/enums.xml
@@ -14664,11 +14664,6 @@ <int value="4" label="Invalid score"/> </enum> -<enum name="ClientSidePhishingUpdateStatus"> - <int value="0" label="Not updated"/> - <int value="1" label="Updated"/> -</enum> - <enum name="ClientTagBasedModelTypeProcessorErrors"> <int value="0" label="Incomplete storage keys from loading metadata"/> <int value="1" label="Incomplete storage keys from full update"/> @@ -16026,6 +16021,7 @@ <int value="82" label="Federated identity active session"/> <int value="83" label="Auto-darken web content"/> <int value="84" label="Request desktop site"/> + <int value="85" label="Federated identity browser JavaScript API"/> </enum> <enum name="ContentTypeParseableResult"> @@ -91122,6 +91118,12 @@ <int value="15" label="kExtensionMessagingNeitherPrivileged"/> </enum> +<enum name="UserAgentOverride"> + <int value="0" label="Override does not contain original"/> + <int value="1" label="Override contains original string and is not a suffix"/> + <int value="2" label="Override is original string and suffix"/> +</enum> + <enum name="UserAgentRequestType"> <int value="0" label="RequestDesktop"/> <int value="1" label="RequestMobile"/>
diff --git a/tools/metrics/histograms/metadata/blink/histograms.xml b/tools/metrics/histograms/metadata/blink/histograms.xml index d135f13..e3de127 100644 --- a/tools/metrics/histograms/metadata/blink/histograms.xml +++ b/tools/metrics/histograms/metadata/blink/histograms.xml
@@ -2504,6 +2504,20 @@ </summary> </histogram> +<histogram name="Blink.UseCounter.UserAgentOverride" enum="UserAgentOverride" + expires_after="M106"> + <owner>aarontag@chromium.org</owner> + <owner>miketaylr@chromium.org</owner> + <summary> + Measures how often a User-Agent string is overridden, how often that + override contains the original User-Agent string, and how often that + override is the original User-Agent string with a suffix concatinated to the + end. Measured once per navigation request and at most once per page load, + either when a resource fetch request is prepared or when navigator.userAgent + is accessed, if the UA string has been overridden. + </summary> +</histogram> + <histogram base="true" name="Blink.UserDrivenDocumentUpdate.UpdateTime" units="microseconds" expires_after="2022-07-03"> <!-- Name completed by histogram_suffixes name="BlinkUpdateTimePreFCPSuffixes" -->
diff --git a/tools/metrics/histograms/metadata/data/histograms.xml b/tools/metrics/histograms/metadata/data/histograms.xml index 11b67c3..a5f26408 100644 --- a/tools/metrics/histograms/metadata/data/histograms.xml +++ b/tools/metrics/histograms/metadata/data/histograms.xml
@@ -22,6 +22,13 @@ <histograms> +<variants name="MeasuringLayer"> + <variant name="Delegate" summary="As reported by the network delegate."/> + <variant name="OS" + summary="As reported by the operating system. Currently logged only on + Android."/> +</variants> + <histogram name="ConnectivityDetector.ConnectionState.{Client}" enum="ConnectivityDetectorConnectionState" expires_after="2021-11-15"> <owner>curranmax@chromium.org</owner> @@ -134,6 +141,9 @@ <histogram name="DataUse.AllServicesKB" enum="DataUseServicesHash" expires_after="2022-08-28"> + <obsolete> + Obsoleted. + </obsolete> <owner>rajendrant@chromium.org</owner> <owner>mcrouse@chromium.org</owner> <summary> @@ -182,6 +192,9 @@ <histogram name="DataUse.BytesReceived2" units="bytes" expires_after="2022-06-19"> + <obsolete> + Obsoleted. + </obsolete> <owner>rajendrant@chromium.org</owner> <owner>mcrouse@chromium.org</owner> <summary> @@ -190,7 +203,22 @@ </summary> </histogram> +<histogram name="DataUse.BytesReceived3.{MeasuringLayer}" units="bytes" + expires_after="2022-08-28"> + <owner>curranmax@chromium.org</owner> + <owner>ryansturm@chromium.org</owner> + <owner>spelchat@chromium.org</owner> + <summary> + Count of total bytes received by the Chrome on the network. This is recorded + when requests complete. + </summary> + <token key="MeasuringLayer" variants="MeasuringLayer"/> +</histogram> + <histogram name="DataUse.BytesSent" units="bytes" expires_after="2022-08-28"> + <obsolete> + Obsoleted. + </obsolete> <owner>rajendrant@chromium.org</owner> <owner>mcrouse@chromium.org</owner> <summary> @@ -199,6 +227,18 @@ </summary> </histogram> +<histogram name="DataUse.BytesSent3.{MeasuringLayer}" units="bytes" + expires_after="2022-08-28"> + <owner>curranmax@chromium.org</owner> + <owner>ryansturm@chromium.org</owner> + <owner>spelchat@chromium.org</owner> + <summary> + Count of total bytes sent by the Chrome on the network. With network + servicification this is recorded when requests complete. + </summary> + <token key="MeasuringLayer" variants="MeasuringLayer"/> +</histogram> + <histogram name="DataUse.ContentType.UserTrafficKB" enum="DataUseContentType" expires_after="2022-08-28"> <owner>rajendrant@chromium.org</owner>
diff --git a/tools/metrics/histograms/metadata/hang_watcher/histograms.xml b/tools/metrics/histograms/metadata/hang_watcher/histograms.xml index 4a48ed11..424b8800 100644 --- a/tools/metrics/histograms/metadata/hang_watcher/histograms.xml +++ b/tools/metrics/histograms/metadata/hang_watcher/histograms.xml
@@ -33,6 +33,10 @@ summary="the IO-Thread of a Renderer process"/> <variant name="RendererProcess.MainThread" summary="the Main Thread of a Renderer process"/> + <variant name="UtilityProcess.IOThread" + summary="the IO-Thread of a Utility process"/> + <variant name="UtilityProcess.MainThread" + summary="the Main Thread of a Utility process"/> </variants> <variants name="ProcessType">
diff --git a/tools/metrics/histograms/metadata/history/histograms.xml b/tools/metrics/histograms/metadata/history/histograms.xml index bc4835e..e1591417 100644 --- a/tools/metrics/histograms/metadata/history/histograms.xml +++ b/tools/metrics/histograms/metadata/history/histograms.xml
@@ -807,7 +807,6 @@ The value represents the 0-indexed index of the cluster. </summary> <token key="ClusterAction"> - <variant name="Clicked" summary="clicks a visit"/> <variant name="Deleted" summary="deletes a history cluster"/> <variant name="OpenedInTabGroup" summary="opens the visit urls in a history cluster in a new tab group"/> @@ -815,6 +814,7 @@ summary="clicks a related search suggestion"/> <variant name="RelatedVisitsVisibilityToggled" summary="toggles visibility of the default-hidden related visits"/> + <variant name="VisitClicked" summary="clicks a visit"/> </token> </histogram>
diff --git a/tools/metrics/histograms/metadata/renderer/histograms.xml b/tools/metrics/histograms/metadata/renderer/histograms.xml index 7ba5a68f..1ed5e54 100644 --- a/tools/metrics/histograms/metadata/renderer/histograms.xml +++ b/tools/metrics/histograms/metadata/renderer/histograms.xml
@@ -294,7 +294,7 @@ </histogram> <histogram name="Renderer.Font.Shaping.DomContentLoaded" units="ms" - expires_after="2022-04-18"> + expires_after="2022-09-09"> <owner>tkent@chromium.org</owner> <owner>kojii@chromium.org</owner> <owner>yosin@chromium.org</owner> @@ -307,7 +307,7 @@ </histogram> <histogram name="Renderer.Font.Shaping.FCP" units="ms" - expires_after="2022-07-11"> + expires_after="2022-09-09"> <owner>tkent@chromium.org</owner> <owner>kojii@chromium.org</owner> <owner>yosin@chromium.org</owner>
diff --git a/tools/metrics/histograms/metadata/sb_client/histograms.xml b/tools/metrics/histograms/metadata/sb_client/histograms.xml index d620178..2ee0b54 100644 --- a/tools/metrics/histograms/metadata/sb_client/histograms.xml +++ b/tools/metrics/histograms/metadata/sb_client/histograms.xml
@@ -428,17 +428,6 @@ </summary> </histogram> -<histogram name="SBClientPhishing.ComponentUpdateEvent" - enum="ClientSidePhishingUpdateStatus" expires_after="2023-02-10"> - <owner>drubery@chromium.org</owner> - <owner>chrome-safebrowsing-alerts@google.com</owner> - <summary> - Records whether or not the Client Side Detection model was updated or not. - This is logged each time the component updater checks for an update - (approximately every 6 hours or on startup). - </summary> -</histogram> - <histogram name="SBClientPhishing.DOMFeatureChunkTime" units="ms" expires_after="M77"> <owner>gab@chromium.org</owner>
diff --git a/tools/metrics/histograms/metadata/uma/histograms.xml b/tools/metrics/histograms/metadata/uma/histograms.xml index 0e1e49e..f9480b1 100644 --- a/tools/metrics/histograms/metadata/uma/histograms.xml +++ b/tools/metrics/histograms/metadata/uma/histograms.xml
@@ -94,7 +94,9 @@ </histogram> <histogram name="UMA.AntiVirusMetricsProvider.Result" - enum="AntiVirusMetricsProviderResult" expires_after="2020-03-08"> + enum="AntiVirusMetricsProviderResult" expires_after="never"> +<!-- expires-never: needed to proactively diagnose changes in the Windows API used here. --> + <owner>wfh@chromium.org</owner> <owner>src/base/metrics/OWNERS</owner> <summary> @@ -635,37 +637,6 @@ </token> </histogram> -<histogram name="UMA.ReadAndTruncateMetricsFromFile.DiscardedCount" - units="samples" expires_after="2022-04-17"> - <owner>iby@chromium.org</owner> - <owner>cros-telemetry@google.com</owner> - <summary> - Number of metric samples discarded on each read from the ChromeOS external - metrics file. This should only be greater than 0 if the file had so many - samples we couldn't fit them all in memory. Emitted each time - ReadAndTruncateMetricsFromFile() is called and successfully processes the - external metrics file. No entry is emitted if there was an unexpected error - opening the file. If the file is found to be corrupt partway through a read, - the number of entries discarded before the corruption is found is recorded. - </summary> -</histogram> - -<histogram name="UMA.ReadAndTruncateMetricsFromFile.ReadCount" units="samples" - expires_after="2022-04-17"> - <owner>iby@chromium.org</owner> - <owner>cros-telemetry@google.com</owner> - <summary> - Number of metric samples successfully read from the ChromeOS external - metrics file on each read. Samples discarded because the file is too large - are recorded in UMA.ReadAndTruncateMetricsFromFile.DiscardedCount and not in - here. Emitted each time ReadAndTruncateMetricsFromFile() is called and - successfully processes the external metrics file. No entry is emitted if - there was an unexpected error opening the file. If the file is found to be - corrupt partway through a read, the number of entries read before the - corruption is found is recorded. - </summary> -</histogram> - <histogram name="UMA.SamplingRatePerMille" units="samples per mille" expires_after="2022-08-01"> <owner>jwd@chromium.org</owner>
diff --git a/tools/metrics/ukm/ukm.xml b/tools/metrics/ukm/ukm.xml index 0cd0cdb..b94baa1 100644 --- a/tools/metrics/ukm/ukm.xml +++ b/tools/metrics/ukm/ukm.xml
@@ -12153,6 +12153,21 @@ </metric> </event> +<event name="Omnibox.EditUrlSuggestion.Share"> + <owner>nyquist@chromium.org</owner> + <owner>ssid@chromium.org</owner> + <owner>xingliu@chromium.org</owner> + <summary> + User pressed 'Share' while viewing edit URL suggestions which shares the + current URL. + </summary> + <metric name="HasOccurred" enum="Boolean"> + <summary> + A boolean signaling that the event has occurred; only records true values. + </summary> + </metric> +</event> + <event name="OmniboxSecurityIndicator.FormSubmission"> <owner>meacer@chromium.org</owner> <summary> @@ -18521,6 +18536,20 @@ </metric> </event> +<event name="TopToolbar.Share"> + <owner>nyquist@chromium.org</owner> + <owner>ssid@chromium.org</owner> + <owner>xingliu@chromium.org</owner> + <summary> + User pressed the 'Share' in the top toolbar, which shares the current URL. + </summary> + <metric name="HasOccurred" enum="Boolean"> + <summary> + A boolean signaling that the event has occurred; only records true values. + </summary> + </metric> +</event> + <event name="TouchToFill.Shown"> <owner>kazinova@google.com</owner> <owner>fhorschig@chromium.org</owner>
diff --git a/tools/perf/core/perfetto_binary_roller/binary_deps.json b/tools/perf/core/perfetto_binary_roller/binary_deps.json index 1583e2d..ab2bf7d 100644 --- a/tools/perf/core/perfetto_binary_roller/binary_deps.json +++ b/tools/perf/core/perfetto_binary_roller/binary_deps.json
@@ -5,8 +5,8 @@ "remote_path": "perfetto_binaries/trace_processor_shell/linux_arm64/49b4b5dcbc312d8d2c3751cf29238b8efeb4e494/trace_processor_shell" }, "win": { - "hash": "57e2b76fdb61ebeee75f23b3232c98d866d3f500", - "remote_path": "perfetto_binaries/trace_processor_shell/win/36ea3cdde2aec59c5eec1ca96419b319dd375c19/trace_processor_shell.exe" + "hash": "babaf8a1dca71ffed6e81ec4897e05b736c6a32c", + "remote_path": "perfetto_binaries/trace_processor_shell/win/6eb273237653c5c8d417fd1b556c6d361eb6a79d/trace_processor_shell.exe" }, "linux_arm": { "hash": "58893933be305d3bfe0a72ebebcacde2ac3ca893",
diff --git a/ui/accessibility/platform/ax_platform_node_cocoa.h b/ui/accessibility/platform/ax_platform_node_cocoa.h index ed74a6d..b0219420 100644 --- a/ui/accessibility/platform/ax_platform_node_cocoa.h +++ b/ui/accessibility/platform/ax_platform_node_cocoa.h
@@ -38,6 +38,10 @@ // Returns true if this accessible element should be included into the ax tree. - (BOOL)isIncludedInPlatformTree; +// Returns true if this object should expose its accessible name using +// accessibilityLabel (legacy AXDescription attribute). +- (BOOL)isLabelable; + // Returns an accessible element serving as a title UI element, an element // representing the accessible name of the object and which is exposed via // accessibilityTitleUIElement (or AXTitleUIElement legacy attribute) not via
diff --git a/ui/accessibility/platform/ax_platform_node_cocoa.mm b/ui/accessibility/platform/ax_platform_node_cocoa.mm index 5e83c6e..9f9f9f1 100644 --- a/ui/accessibility/platform/ax_platform_node_cocoa.mm +++ b/ui/accessibility/platform/ax_platform_node_cocoa.mm
@@ -460,9 +460,8 @@ if (!ui::IsControl(_node->GetRole())) return nil; - if (!_node->HasNameFromOtherElement()) { + if (!_node->HasNameFromOtherElement()) return nil; - } std::vector<int32_t> labelledby_ids = _node->GetIntListAttribute(ax::mojom::IntListAttribute::kLabelledbyIds); @@ -482,6 +481,42 @@ return label->GetNativeViewAccessible(); } +- (BOOL)isLabelable { + // Image annotations are not visible text, so they should be exposed + // as a description and not a title. + switch (_node->GetData().GetImageAnnotationStatus()) { + case ax::mojom::ImageAnnotationStatus::kEligibleForAnnotation: + case ax::mojom::ImageAnnotationStatus::kAnnotationPending: + case ax::mojom::ImageAnnotationStatus::kAnnotationEmpty: + case ax::mojom::ImageAnnotationStatus::kAnnotationAdult: + case ax::mojom::ImageAnnotationStatus::kAnnotationProcessFailed: + case ax::mojom::ImageAnnotationStatus::kAnnotationSucceeded: + return true; + + case ax::mojom::ImageAnnotationStatus::kNone: + case ax::mojom::ImageAnnotationStatus::kWillNotAnnotateDueToScheme: + case ax::mojom::ImageAnnotationStatus::kIneligibleForAnnotation: + case ax::mojom::ImageAnnotationStatus::kSilentlyEligibleForAnnotation: + break; + } + + // VoiceOver computes the wrong description for a link. + ax::mojom::Role role = _node->GetRole(); + if (ui::IsLink(role)) + return true; + + // VoiceOver will not read the label of these roles unless it is + // exposed in the description instead of the title. + switch (role) { + case ax::mojom::Role::kGenericContainer: + case ax::mojom::Role::kGroup: + case ax::mojom::Role::kRadioGroup: + return true; + default: + return false; + } +} + + (NSString*)nativeRoleFromAXRole:(ax::mojom::Role)role { static const base::NoDestructor<RoleMap> role_map(BuildRoleMap()); RoleMap::const_iterator it = role_map->find(role); @@ -701,28 +736,20 @@ // These attributes are required on all accessibility objects. NSArray* const kAllRoleAttributes = @[ - NSAccessibilityBlockQuoteLevelAttribute, - NSAccessibilityChildrenAttribute, - NSAccessibilityDOMClassList, - NSAccessibilityDOMIdentifierAttribute, - NSAccessibilityElementBusyAttribute, - NSAccessibilityParentAttribute, - NSAccessibilityPositionAttribute, - NSAccessibilityRoleAttribute, - NSAccessibilitySizeAttribute, + NSAccessibilityBlockQuoteLevelAttribute, NSAccessibilityChildrenAttribute, + NSAccessibilityDOMClassList, NSAccessibilityDOMIdentifierAttribute, + NSAccessibilityDescriptionAttribute, NSAccessibilityElementBusyAttribute, + NSAccessibilityParentAttribute, NSAccessibilityPositionAttribute, + NSAccessibilityRoleAttribute, NSAccessibilitySizeAttribute, NSAccessibilitySubroleAttribute, // Title is required for most elements. Cocoa asks for the value even if it // is omitted here, but won't present it to accessibility APIs without this. NSAccessibilityTitleAttribute, // Attributes which are not required, but are general to all roles. - NSAccessibilityRoleDescriptionAttribute, - NSAccessibilityEnabledAttribute, - NSAccessibilityFocusedAttribute, - NSAccessibilityHelpAttribute, - NSAccessibilityTopLevelUIElementAttribute, - NSAccessibilityVisitedAttribute, - NSAccessibilityWindowAttribute, - NSAccessibilityChromeAXNodeIdAttribute + NSAccessibilityRoleDescriptionAttribute, NSAccessibilityEnabledAttribute, + NSAccessibilityFocusedAttribute, NSAccessibilityHelpAttribute, + NSAccessibilityTopLevelUIElementAttribute, NSAccessibilityVisitedAttribute, + NSAccessibilityWindowAttribute, NSAccessibilityChromeAXNodeIdAttribute ]; // Attributes required for user-editable controls. NSArray* const kValueAttributes = @[ NSAccessibilityValueAttribute ]; @@ -1445,7 +1472,7 @@ } - (NSString*)AXDescription { - return [self AXTitle]; + return [self accessibilityLabel]; } // Misc attributes. @@ -1627,11 +1654,84 @@ } - (NSString*)accessibilityLabel { - // accessibilityLabel is "a short description of the accessibility element", - // and accessibilityTitle is "the title of the accessibility element"; at - // least in Chromium, the title usually is a short description of the element, - // so it also functions as a label. - return [self AXDescription]; + if (![self instanceActive]) + return nil; + + // Mac OS X wants static text exposed in AXValue. + if (ui::IsNameExposedInAXValueForRole([self internalRole])) + return @""; + + // If we're exposing the title in TitleUIElement, don't also redundantly + // expose it in AXDescription. + if ([self titleUIElement]) + return @""; + + std::string name = _node->GetName(); + std::string extraText; + ax::mojom::ImageAnnotationStatus status = + _node->GetData().GetImageAnnotationStatus(); + switch (status) { + case ax::mojom::ImageAnnotationStatus::kEligibleForAnnotation: + case ax::mojom::ImageAnnotationStatus::kAnnotationPending: + case ax::mojom::ImageAnnotationStatus::kAnnotationEmpty: + case ax::mojom::ImageAnnotationStatus::kAnnotationAdult: + case ax::mojom::ImageAnnotationStatus::kAnnotationProcessFailed: { + extraText = base::UTF16ToUTF8( + _node->GetDelegate()->GetLocalizedStringForImageAnnotationStatus( + status)); + break; + } + + case ax::mojom::ImageAnnotationStatus::kAnnotationSucceeded: + extraText = _node->GetStringAttribute( + ax::mojom::StringAttribute::kImageAnnotation); + break; + + case ax::mojom::ImageAnnotationStatus::kNone: + case ax::mojom::ImageAnnotationStatus::kWillNotAnnotateDueToScheme: + case ax::mojom::ImageAnnotationStatus::kIneligibleForAnnotation: + case ax::mojom::ImageAnnotationStatus::kSilentlyEligibleForAnnotation: + break; + } + + if (!extraText.empty()) { + if (!name.empty()) + name += ". "; + name += extraText; + } + + if (!name.empty()) { + // On Mac OS X, the accessible name of an object is exposed as its + // title if it comes from visible text, and as its description + // otherwise, but never both. + if ([self isLabelable]) + return base::SysUTF8ToNSString(name); + + ax::mojom::NameFrom nameFrom = _node->GetNameFrom(); + if (nameFrom == ax::mojom::NameFrom::kCaption || + nameFrom == ax::mojom::NameFrom::kContents || + nameFrom == ax::mojom::NameFrom::kRelatedElement || + nameFrom == ax::mojom::NameFrom::kValue) { + return @""; + } + return base::SysUTF8ToNSString(name); + } + + // Given an image where there's no other title, return the base part + // of the filename as the description. + if ([[self accessibilityRole] isEqualToString:NSAccessibilityImageRole]) { + std::string url; + if (_node->GetStringAttribute(ax::mojom::StringAttribute::kUrl, &url)) { + // Given a url like http://foo.com/bar/baz.png, just return the + // base name, e.g., "baz.png". + size_t leftIndex = url.rfind('/'); + std::string basename = + leftIndex != std::string::npos ? url.substr(leftIndex) : url; + return base::SysUTF8ToNSString(basename); + } + } + + return @""; } - (NSString*)accessibilityTitle {
diff --git a/ui/accessibility/platform/inspect/ax_inspect_utils_mac.mm b/ui/accessibility/platform/inspect/ax_inspect_utils_mac.mm index 630e601a..40ce4c1 100644 --- a/ui/accessibility/platform/inspect/ax_inspect_utils_mac.mm +++ b/ui/accessibility/platform/inspect/ax_inspect_utils_mac.mm
@@ -50,6 +50,7 @@ NSAccessibilityBlockQuoteLevelAttribute, NSAccessibilityChromeAXNodeIdAttribute, NSAccessibilityColumnHeaderUIElementsAttribute, + NSAccessibilityDescriptionAttribute, NSAccessibilityDetailsElementsAttribute, NSAccessibilityDOMClassList, NSAccessibilityDropEffectsAttribute,
diff --git a/ui/android/java/src/org/chromium/ui/base/DropDataContentProvider.java b/ui/android/java/src/org/chromium/ui/base/DropDataContentProvider.java index 2418fb30..d40231d 100644 --- a/ui/android/java/src/org/chromium/ui/base/DropDataContentProvider.java +++ b/ui/android/java/src/org/chromium/ui/base/DropDataContentProvider.java
@@ -203,6 +203,10 @@ } private boolean matchMimeType(String mimeType, String mimeTypeFilter) { + if (mimeType == null || mimeTypeFilter == null) { + return false; + } + int idx1 = mimeType.indexOf('/'); String type = mimeType.substring(0, idx1); String subtype = mimeType.substring(idx1 + 1);
diff --git a/ui/views/animation/animation_builder.cc b/ui/views/animation/animation_builder.cc index ef87e8c..c920f1c 100644 --- a/ui/views/animation/animation_builder.cc +++ b/ui/views/animation/animation_builder.cc
@@ -167,7 +167,14 @@ AnimationBuilder::AnimationBuilder() = default; +AnimationBuilder::AnimationBuilder(AnimationBuilder&& rhs) = default; + +AnimationBuilder& AnimationBuilder::operator=(AnimationBuilder&& rhs) = default; + AnimationBuilder::~AnimationBuilder() { + // Terminate `current_sequence_` to complete layer animation configuration. + current_sequence_.reset(); + DCHECK(!next_animation_observer_) << "Callbacks were scheduled without creating a sequence block " "afterwards. There are no animations to run these callbacks on."; @@ -228,12 +235,12 @@ return *this; } -AnimationSequenceBlock AnimationBuilder::Once() { +AnimationSequenceBlock& AnimationBuilder::Once() { repeating_ = false; return NewSequence(); } -AnimationSequenceBlock AnimationBuilder::Repeatedly() { +AnimationSequenceBlock& AnimationBuilder::Repeatedly() { repeating_ = true; return NewSequence(); } @@ -250,6 +257,14 @@ values.insert(it, std::move(value)); } +std::unique_ptr<AnimationSequenceBlock> AnimationBuilder::SwapCurrentSequence( + base::PassKey<AnimationSequenceBlock>, + std::unique_ptr<AnimationSequenceBlock> new_sequence) { + auto old_sequence = std::move(current_sequence_); + current_sequence_ = std::move(new_sequence); + return old_sequence; +} + void AnimationBuilder::BlockEndedAt(base::PassKey<AnimationSequenceBlock>, base::TimeDelta end) { end_ = std::max(end_, end); @@ -290,6 +305,11 @@ values_.clear(); } +AnimationSequenceBlock& AnimationBuilder::GetCurrentSequence() { + DCHECK(current_sequence_); + return *current_sequence_; +} + std::unique_ptr<AnimationAbortHandle> AnimationBuilder::GetAbortHandle() { DCHECK(!abort_handle_) << "An abort handle is already created."; abort_handle_ = new AnimationAbortHandle(GetObserver()); @@ -308,9 +328,18 @@ GetObserverDeletedCallback() = std::move(deleted_closure); } -AnimationSequenceBlock AnimationBuilder::NewSequence() { +AnimationSequenceBlock& AnimationBuilder::NewSequence() { // Each sequence should have its own observer. + // `current_sequence_` is set only when `repeating_` is true. + DCHECK(!current_sequence_ || repeating_); + + // Ensure to terminate the current sequence block before touching the + // animation sequence observer so that the sequence observer is attached to + // the layer animation sequence. + if (current_sequence_) + current_sequence_.reset(); + // The observer needs to outlive the AnimationBuilder and will manage its own // lifetime. GetAttachedToSequence should not return false here. This is // DCHECKed in the observer’s destructor. @@ -322,8 +351,9 @@ } end_ = base::TimeDelta(); - return AnimationSequenceBlock(base::PassKey<AnimationBuilder>(), this, - base::TimeDelta()); + current_sequence_ = std::make_unique<AnimationSequenceBlock>( + base::PassKey<AnimationBuilder>(), this, base::TimeDelta()); + return *current_sequence_; } // static
diff --git a/ui/views/animation/animation_builder.h b/ui/views/animation/animation_builder.h index 94f0ceb3..921b291c 100644 --- a/ui/views/animation/animation_builder.h +++ b/ui/views/animation/animation_builder.h
@@ -28,6 +28,7 @@ class AnimationAbortHandle; +// Provides an unfinalized animation sequence block if any to build animations. class VIEWS_EXPORT AnimationBuilder { public: class Observer : public ui::LayerAnimationObserver { @@ -81,6 +82,8 @@ }; AnimationBuilder(); + AnimationBuilder(AnimationBuilder&& rhs); + AnimationBuilder& operator=(AnimationBuilder&& rhs); ~AnimationBuilder(); // Options for the whole animation @@ -112,8 +115,8 @@ std::unique_ptr<AnimationAbortHandle> GetAbortHandle(); // Creates a new sequence (that optionally repeats). - AnimationSequenceBlock Once(); - AnimationSequenceBlock Repeatedly(); + AnimationSequenceBlock& Once(); + AnimationSequenceBlock& Repeatedly(); // Adds an animation element `element` for `key` at `start` to `values`. void AddLayerAnimationElement( @@ -123,6 +126,11 @@ base::TimeDelta original_duration, std::unique_ptr<ui::LayerAnimationElement> element); + // Swaps `current_sequence_` with `new_sequence` and returns the old one. + [[nodiscard]] std::unique_ptr<AnimationSequenceBlock> SwapCurrentSequence( + base::PassKey<AnimationSequenceBlock>, + std::unique_ptr<AnimationSequenceBlock> new_sequence); + // Called when a block ends. Ensures all animations in the sequence will run // until at least `end`. void BlockEndedAt(base::PassKey<AnimationSequenceBlock>, base::TimeDelta end); @@ -131,6 +139,13 @@ // `layer_animation_sequences_`. void TerminateSequence(base::PassKey<AnimationSequenceBlock>); + // Returns a left value reference to the object held by `current_sequence_`. + // Assumes that `current_sequence_` is set. + // NOTE: be wary when keeping this method's return value because the current + // sequence held by an `AnimationBuilder` instance could be destroyed during + // `AnimationBuilder` instance's life cycle. + AnimationSequenceBlock& GetCurrentSequence(); + static void SetObserverDeletedCallbackForTesting( base::RepeatingClosure deleted_closure); @@ -139,9 +154,9 @@ Observer* GetObserver(); - // Resets data for the current sequence as necessary, creates and returns the - // initial block. - AnimationSequenceBlock NewSequence(); + // Resets data for the current sequence as necessary, creates a new sequence + // block and returns the new block's left value reference. + AnimationSequenceBlock& NewSequence(); // Returns a reference to the observer deleted callback used for testing. static base::RepeatingClosure& GetObserverDeletedCallback(); @@ -163,6 +178,15 @@ std::map<AnimationKey, std::vector<Value>> values_; raw_ptr<AnimationAbortHandle> abort_handle_ = nullptr; + + // An unfinalized sequence block currently used to build animations. NOTE: the + // animation effects carried by `current_sequence_` attach to a layer only + // after `current_sequence_` is destroyed. + // The life cycle of `current_sequence_`: + // (1) The old sequence is replaced by a new one. When being replaced, the + // old sequence is destroyed. + // (2) Gets destroyed when the host `AnimationBuilder` is destroyed. + std::unique_ptr<AnimationSequenceBlock> current_sequence_; }; } // namespace views
diff --git a/ui/views/animation/animation_builder_unittest.cc b/ui/views/animation/animation_builder_unittest.cc index 97a6a20..eb4283c 100644 --- a/ui/views/animation/animation_builder_unittest.cc +++ b/ui/views/animation/animation_builder_unittest.cc
@@ -20,6 +20,8 @@ namespace views { +namespace { + class TestAnimatibleLayerOwner : public ui::LayerOwner { public: TestAnimatibleLayerOwner() : ui::LayerOwner(std::make_unique<ui::Layer>()) { @@ -33,6 +35,18 @@ ui::TestLayerAnimationDelegate delegate_; }; +// Configures the layer animation on `layer_owner` and returns the builder. +AnimationBuilder BuildLayerOpacityAnimationAndReturnBuilder( + ui::LayerOwner* layer_owner, + const base::TimeDelta& duration) { + EXPECT_NE(0.f, layer_owner->layer()->opacity()); + AnimationBuilder builder; + builder.Once().SetDuration(duration).SetOpacity(layer_owner, 0.f); + return builder; +} + +} // namespace + class AnimationBuilderTest : public testing::Test { public: AnimationBuilderTest() = default; @@ -946,9 +960,12 @@ { AnimationBuilder builder; - auto block = builder.Repeatedly(); + builder.Repeatedly(); for (const auto& opacity : kOpacity) { - block = block.SetDuration(kDuration).SetOpacity(view, opacity).Then(); + builder.GetCurrentSequence() + .SetDuration(kDuration) + .SetOpacity(view, opacity) + .Then(); } } @@ -1130,4 +1147,35 @@ } } +// Verifies that configuring layer animations with an animation builder returned +// from a function works as expected. +TEST_F(AnimationBuilderTest, BuildAnimationWithBuilderFromScope) { + TestAnimatibleLayerOwner* first_animating_view = CreateTestLayerOwner(); + TestAnimatibleLayerOwner* second_animating_view = CreateTestLayerOwner(); + EXPECT_EQ(1.f, first_animating_view->layer()->opacity()); + EXPECT_EQ(1.f, second_animating_view->layer()->opacity()); + + constexpr auto kDuration = base::Seconds(3); + { + // Build a layer animation on `second_animating_view` with a builder + // returned from a function. + AnimationBuilder builder = BuildLayerOpacityAnimationAndReturnBuilder( + first_animating_view, kDuration); + builder.GetCurrentSequence().SetOpacity(second_animating_view, 0.f); + } + + // Verify that both views are under animation. + EXPECT_TRUE(first_animating_view->layer()->GetAnimator()->is_animating()); + EXPECT_TRUE(second_animating_view->layer()->GetAnimator()->is_animating()); + + Step(kDuration); + + // Verify that after `kDuration` time, both layer animations end. In addition, + // both layers are set with the target opacity. + EXPECT_FALSE(first_animating_view->layer()->GetAnimator()->is_animating()); + EXPECT_FALSE(second_animating_view->layer()->GetAnimator()->is_animating()); + EXPECT_EQ(0.f, first_animating_view->delegate()->GetOpacityForAnimation()); + EXPECT_EQ(0.f, second_animating_view->delegate()->GetOpacityForAnimation()); +} + } // namespace views
diff --git a/ui/views/animation/animation_sequence_block.cc b/ui/views/animation/animation_sequence_block.cc index efdea11..21630c6b 100644 --- a/ui/views/animation/animation_sequence_block.cc +++ b/ui/views/animation/animation_sequence_block.cc
@@ -32,31 +32,6 @@ base::TimeDelta start) : builder_key_(builder_key), owner_(owner), start_(start) {} -AnimationSequenceBlock::AnimationSequenceBlock(AnimationSequenceBlock&& other) - : builder_key_(std::move(other.builder_key_)), - owner_(other.owner_), - start_(std::move(other.start_)), - duration_(std::move(other.duration_)), - elements_(std::move(other.elements_)) { - DCHECK(!other.finalized_) - << "Do not access old blocks after creating new ones."; - other.finalized_ = true; -} - -AnimationSequenceBlock& AnimationSequenceBlock::operator=( - AnimationSequenceBlock&& other) { - DCHECK(!other.finalized_) - << "Do not access old blocks after creating new ones."; - builder_key_ = std::move(other.builder_key_); - owner_ = other.owner_; - start_ = std::move(other.start_); - duration_ = std::move(other.duration_); - elements_ = std::move(other.elements_); - finalized_ = false; - other.finalized_ = true; - return *this; -} - AnimationSequenceBlock::~AnimationSequenceBlock() { if (!finalized_) { TerminateBlock(); @@ -207,20 +182,29 @@ return SetVisibility(target->layer(), visible, tween_type); } -AnimationSequenceBlock AnimationSequenceBlock::At( +AnimationSequenceBlock& AnimationSequenceBlock::At( base::TimeDelta since_sequence_start) { + // NOTE: at the end of this function, this object is destroyed. + DCHECK(!finalized_) << "Do not access old blocks after creating new ones."; TerminateBlock(); finalized_ = true; - return AnimationSequenceBlock(builder_key_, owner_, since_sequence_start); + + // NOTE: `old_sequence` is actually the sequence block itself. Do not destruct + // this object until the function end. + auto old_sequence = owner_->SwapCurrentSequence( + PassKey(), std::make_unique<AnimationSequenceBlock>( + builder_key_, owner_, since_sequence_start)); + + return owner_->GetCurrentSequence(); } -AnimationSequenceBlock AnimationSequenceBlock::Offset( +AnimationSequenceBlock& AnimationSequenceBlock::Offset( base::TimeDelta since_last_block_start) { return At(start_ + since_last_block_start); } -AnimationSequenceBlock AnimationSequenceBlock::Then() { +AnimationSequenceBlock& AnimationSequenceBlock::Then() { return Offset(duration_.value_or(base::TimeDelta())); }
diff --git a/ui/views/animation/animation_sequence_block.h b/ui/views/animation/animation_sequence_block.h index ae58911..df2b7b2d 100644 --- a/ui/views/animation/animation_sequence_block.h +++ b/ui/views/animation/animation_sequence_block.h
@@ -47,8 +47,8 @@ AnimationSequenceBlock(base::PassKey<AnimationBuilder> builder_key, AnimationBuilder* owner, base::TimeDelta start); - AnimationSequenceBlock(AnimationSequenceBlock&& other); - AnimationSequenceBlock& operator=(AnimationSequenceBlock&& other); + AnimationSequenceBlock(AnimationSequenceBlock&& other) = delete; + AnimationSequenceBlock& operator=(AnimationSequenceBlock&& other) = delete; ~AnimationSequenceBlock(); // Sets the duration of this block. The duration may be set at most once and @@ -131,9 +131,9 @@ gfx::Tween::Type tween_type = gfx::Tween::LINEAR); // Creates a new block. - AnimationSequenceBlock At(base::TimeDelta since_sequence_start); - AnimationSequenceBlock Offset(base::TimeDelta since_last_block_start); - AnimationSequenceBlock Then(); + AnimationSequenceBlock& At(base::TimeDelta since_sequence_start); + AnimationSequenceBlock& Offset(base::TimeDelta since_last_block_start); + AnimationSequenceBlock& Then(); private: using AnimationValue = absl::variant<gfx::Rect,
diff --git a/ui/views/animation/square_ink_drop_ripple.cc b/ui/views/animation/square_ink_drop_ripple.cc index bd1542c..c468914 100644 --- a/ui/views/animation/square_ink_drop_ripple.cc +++ b/ui/views/animation/square_ink_drop_ripple.cc
@@ -227,10 +227,10 @@ InkDropState new_ink_drop_state) { InkDropTransforms transforms; AnimationBuilder builder; - auto sequence = builder - .SetPreemptionStrategy( - ui::LayerAnimator::IMMEDIATELY_ANIMATE_TO_NEW_TARGET) - .Once(); + builder + .SetPreemptionStrategy( + ui::LayerAnimator::IMMEDIATELY_ANIMATE_TO_NEW_TARGET) + .Once(); auto animate_to_transforms = [this](AnimationSequenceBlock& sequence, @@ -244,15 +244,14 @@ auto pending_animation = [this, &animate_to_transforms]( AnimationSequenceBlock& sequence, - const InkDropTransforms& transforms) -> AnimationSequenceBlock { - auto new_sequence = + const InkDropTransforms& transforms) -> AnimationSequenceBlock& { + auto& new_sequence = sequence.SetDuration(GetAnimationDuration(ACTION_PENDING_FADE_IN)) .SetOpacity(&root_layer_, visible_opacity_, gfx::Tween::EASE_IN) - .Then(); - animate_to_transforms( - new_sequence.SetDuration(GetAnimationDuration(ACTION_PENDING_TRANSFORM)) - .SetOpacity(&root_layer_, visible_opacity_, gfx::Tween::EASE_IN), - transforms, gfx::Tween::EASE_IN_OUT); + .Then() + .SetDuration(GetAnimationDuration(ACTION_PENDING_TRANSFORM)) + .SetOpacity(&root_layer_, visible_opacity_, gfx::Tween::EASE_IN); + animate_to_transforms(new_sequence, transforms, gfx::Tween::EASE_IN_OUT); return new_sequence; }; @@ -263,13 +262,14 @@ break; } else { CalculateCircleTransforms(small_size_, &transforms); - sequence = sequence.SetDuration(GetAnimationDuration(HIDDEN_FADE_OUT)) - .SetOpacity(&root_layer_, kHiddenOpacity, - gfx::Tween::EASE_IN_OUT) - .At(base::TimeDelta()); - animate_to_transforms( - sequence.SetDuration(GetAnimationDuration(HIDDEN_TRANSFORM)), - transforms, gfx::Tween::EASE_IN_OUT); + auto& sequence = + builder.GetCurrentSequence() + .SetDuration(GetAnimationDuration(HIDDEN_FADE_OUT)) + .SetOpacity(&root_layer_, kHiddenOpacity, + gfx::Tween::EASE_IN_OUT) + .At(base::TimeDelta()) + .SetDuration(GetAnimationDuration(HIDDEN_TRANSFORM)); + animate_to_transforms(sequence, transforms, gfx::Tween::EASE_IN_OUT); } break; case InkDropState::ACTION_PENDING: { @@ -281,7 +281,7 @@ << " new_ink_drop_state=" << ToString(new_ink_drop_state); CalculateCircleTransforms(large_size_, &transforms); - pending_animation(sequence, transforms); + pending_animation(builder.GetCurrentSequence(), transforms); break; } case InkDropState::ACTION_TRIGGERED: { @@ -294,17 +294,17 @@ gfx::Size s = ScaleToRoundedSize(large_size_, kQuickActionBurstScale); CalculateCircleTransforms(s, &transforms); if (old_ink_drop_state == InkDropState::HIDDEN) { - sequence = pending_animation(sequence, transforms).Then(); + pending_animation(builder.GetCurrentSequence(), transforms).Then(); } else { builder.SetPreemptionStrategy(ui::LayerAnimator::ENQUEUE_NEW_ANIMATION); } - sequence = - sequence.SetDuration(GetAnimationDuration(ACTION_TRIGGERED_FADE_OUT)) - .SetOpacity(&root_layer_, kHiddenOpacity, gfx::Tween::EASE_IN_OUT) - .Offset(base::TimeDelta()); - animate_to_transforms(sequence.SetDuration(GetAnimationDuration( - ACTION_TRIGGERED_TRANSFORM)), - transforms, gfx::Tween::EASE_IN_OUT); + builder.GetCurrentSequence() + .SetDuration(GetAnimationDuration(ACTION_TRIGGERED_FADE_OUT)) + .SetOpacity(&root_layer_, kHiddenOpacity, gfx::Tween::EASE_IN_OUT) + .Offset(base::TimeDelta()) + .SetDuration(GetAnimationDuration(ACTION_TRIGGERED_TRANSFORM)); + animate_to_transforms(builder.GetCurrentSequence(), transforms, + gfx::Tween::EASE_IN_OUT); break; } case InkDropState::ALTERNATE_ACTION_PENDING: { @@ -315,7 +315,8 @@ CalculateRectTransforms(small_size_, small_corner_radius_, &transforms); animate_to_transforms( - sequence.SetDuration(GetAnimationDuration(ALTERNATE_ACTION_PENDING)) + builder.GetCurrentSequence() + .SetDuration(GetAnimationDuration(ALTERNATE_ACTION_PENDING)) .SetOpacity(&root_layer_, visible_opacity_, gfx::Tween::EASE_IN), transforms, gfx::Tween::EASE_IN_OUT); break; @@ -331,43 +332,43 @@ GetAnimationDuration(ALTERNATE_ACTION_TRIGGERED_TRANSFORM) - GetAnimationDuration(ALTERNATE_ACTION_TRIGGERED_FADE_OUT); CalculateRectTransforms(large_size_, large_corner_radius_, &transforms); - sequence = - sequence.SetDuration(visible_duration) - .SetOpacity(&root_layer_, visible_opacity_, - gfx::Tween::EASE_IN_OUT) - .Then() - .SetDuration( - GetAnimationDuration(ALTERNATE_ACTION_TRIGGERED_FADE_OUT)) - .SetOpacity(&root_layer_, kHiddenOpacity, gfx::Tween::EASE_IN_OUT) - .At(base::TimeDelta()); - animate_to_transforms(sequence.SetDuration(GetAnimationDuration( - ALTERNATE_ACTION_TRIGGERED_TRANSFORM)), - transforms, gfx::Tween::EASE_IN_OUT); + builder.GetCurrentSequence() + .SetDuration(visible_duration) + .SetOpacity(&root_layer_, visible_opacity_, gfx::Tween::EASE_IN_OUT) + .Then() + .SetDuration( + GetAnimationDuration(ALTERNATE_ACTION_TRIGGERED_FADE_OUT)) + .SetOpacity(&root_layer_, kHiddenOpacity, gfx::Tween::EASE_IN_OUT) + .At(base::TimeDelta()) + .SetDuration( + GetAnimationDuration(ALTERNATE_ACTION_TRIGGERED_TRANSFORM)); + animate_to_transforms(builder.GetCurrentSequence(), transforms, + gfx::Tween::EASE_IN_OUT); break; } case InkDropState::ACTIVATED: { // Animate the opacity so that it cancels any opacity animations already // in progress. - sequence = sequence.SetDuration(base::TimeDelta()) - .SetOpacity(&root_layer_, visible_opacity_, - gfx::Tween::EASE_IN_OUT) - .Then(); + builder.GetCurrentSequence() + .SetDuration(base::TimeDelta()) + .SetOpacity(&root_layer_, visible_opacity_, gfx::Tween::EASE_IN_OUT) + .Then(); if (old_ink_drop_state == InkDropState::HIDDEN) { CalculateCircleTransforms(large_size_, &transforms); - sequence = animate_to_transforms( - sequence.SetDuration( - GetAnimationDuration(ACTIVATED_CIRCLE_TRANSFORM)), - transforms, gfx::Tween::EASE_IN_OUT) - .Then(); + animate_to_transforms( + builder.GetCurrentSequence().SetDuration( + GetAnimationDuration(ACTIVATED_CIRCLE_TRANSFORM)), + transforms, gfx::Tween::EASE_IN_OUT) + .Then(); } else if (old_ink_drop_state == InkDropState::ACTION_PENDING) { builder.SetPreemptionStrategy(ui::LayerAnimator::ENQUEUE_NEW_ANIMATION); } GetActivatedTargetTransforms(&transforms); - animate_to_transforms( - sequence.SetDuration(GetAnimationDuration(ACTIVATED_RECT_TRANSFORM)), - transforms, gfx::Tween::EASE_IN_OUT); + animate_to_transforms(builder.GetCurrentSequence().SetDuration( + GetAnimationDuration(ACTIVATED_RECT_TRANSFORM)), + transforms, gfx::Tween::EASE_IN_OUT); break; } case InkDropState::DEACTIVATED: { @@ -375,17 +376,16 @@ GetAnimationDuration(DEACTIVATED_TRANSFORM) - GetAnimationDuration(DEACTIVATED_FADE_OUT); GetDeactivatedTargetTransforms(&transforms); - sequence = - sequence.SetDuration(visible_duration) - .SetOpacity(&root_layer_, visible_opacity_, - gfx::Tween::EASE_IN_OUT) - .Then() - .SetDuration(GetAnimationDuration(DEACTIVATED_FADE_OUT)) - .SetOpacity(&root_layer_, kHiddenOpacity, gfx::Tween::EASE_IN_OUT) - .At(base::TimeDelta()); - animate_to_transforms( - sequence.SetDuration(GetAnimationDuration(DEACTIVATED_TRANSFORM)), - transforms, gfx::Tween::EASE_IN_OUT); + builder.GetCurrentSequence() + .SetDuration(visible_duration) + .SetOpacity(&root_layer_, visible_opacity_, gfx::Tween::EASE_IN_OUT) + .Then() + .SetDuration(GetAnimationDuration(DEACTIVATED_FADE_OUT)) + .SetOpacity(&root_layer_, kHiddenOpacity, gfx::Tween::EASE_IN_OUT) + .At(base::TimeDelta()); + animate_to_transforms(builder.GetCurrentSequence().SetDuration( + GetAnimationDuration(DEACTIVATED_TRANSFORM)), + transforms, gfx::Tween::EASE_IN_OUT); break; } }
diff --git a/ui/webui/resources/cr_elements/cr_auto_img/cr_auto_img.js b/ui/webui/resources/cr_elements/cr_auto_img/cr_auto_img.js index 4567e9c..6ccfb833 100644 --- a/ui/webui/resources/cr_elements/cr_auto_img/cr_auto_img.js +++ b/ui/webui/resources/cr_elements/cr_auto_img/cr_auto_img.js
@@ -13,13 +13,17 @@ * * 2. In HTML instantiate * - * <img is="cr-auto-img" auto-src="https://foo.com/bar.png"></img> + * <img is="cr-auto-img" auto-src="https://foo.com/bar.png"> * * If your image needs to be fetched using cookies, you can use the * with-cookies attribute as follows: * * <img is="cr-auto-img" auto-src="https://foo.com/bar.png" with-cookies> - * </img> + * + * If you want the image to reset to an empty state when auto-src changes + * and the new image is still loading, set the clear-src attribute: + * + * <img is="cr-auto-img" auto-src="[[calculateSrc()]]" clear-src> * * NOTE: Since <cr-auto-img> may use the chrome://image data source some images * may be transcoded to PNG. @@ -29,6 +33,9 @@ const AUTO_SRC = 'auto-src'; /** @type {string} */ +const CLEAR_SRC = 'clear-src'; + +/** @type {string} */ const WITH_COOKIES = 'with-cookies'; export class CrAutoImgElement extends HTMLImageElement { @@ -41,6 +48,12 @@ return; } + if (this.hasAttribute(CLEAR_SRC)) { + // Remove the src attribute so that the old image is not shown while the + // new one is loading. + this.removeAttribute('src'); + } + let url = null; try { url = new URL(newValue || ''); @@ -73,6 +86,16 @@ } /** @param {string} _ */ + set clearSrc(_) { + this.setAttribute(CLEAR_SRC, ''); + } + + /** @return {string} */ + get clearSrc() { + return this.getAttribute(CLEAR_SRC); + } + + /** @param {string} _ */ set withCookies(_) { this.setAttribute(WITH_COOKIES, ''); }